~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
124 lines · 5.0 KB Raw History
import Foundation

struct SharedImport {
    struct Attachment {
        let kind: Kind
        let data: Data
        let filename: String
    }

    let id: String
    let text: String
    let attachments: [Attachment]
}

struct SharedImportFile {
    let kind: SharedImport.Attachment.Kind
    let url: URL
}

enum SharedImportStore {
    private struct ManifestAttachment: Codable {
        let kind: SharedImport.Attachment.Kind
        let filename: String
    }

    private struct Manifest: Codable {
        let text: String
        let attachments: [ManifestAttachment]
    }

    enum StoreError: LocalizedError {
        case unavailable
        case invalidContent
        case unsupportedContent

        var errorDescription: String? {
            switch self {
            case .unavailable: return "Old Fella could not access shared items. Please try again."
            case .invalidContent: return "Share one video or up to ten photos."
            case .unsupportedContent: return "Old Fella could not read this item. Share a photo, video, or link."
            }
        }
    }

    private static func queueURL() throws -> URL {
        guard let container = FileManager.default.containerURL(
            forSecurityApplicationGroupIdentifier: AppGroup.identifier) else {
            throw StoreError.unavailable
        }
        return container.appendingPathComponent("PendingShares", isDirectory: true)
    }

    static func enqueue(text: String, files: [SharedImportFile], queue: URL? = nil) throws {
        guard !text.isEmpty || !files.isEmpty,
            files.count <= 10,
            files.filter({ $0.kind == .video }).count <= 1,
            !files.contains(where: { $0.kind == .video }) || files.count == 1
        else {
            throw StoreError.invalidContent
        }

        let fileManager = FileManager.default
        let queue = try queue ?? queueURL()
        try fileManager.createDirectory(at: queue, withIntermediateDirectories: true)
        let id = UUID().uuidString
        let staging = queue.appendingPathComponent(".\(id)", isDirectory: true)
        let destination = queue.appendingPathComponent(id, isDirectory: true)
        try fileManager.createDirectory(at: staging, withIntermediateDirectories: false)
        do {
            var attachments: [ManifestAttachment] = []
            for (index, file) in files.enumerated() {
                let suffix = file.url.pathExtension
                let name = suffix.isEmpty ? "\(index)" : "\(index).\(suffix)"
                try fileManager.copyItem(at: file.url, to: staging.appendingPathComponent(name))
                attachments.append(ManifestAttachment(kind: file.kind, filename: name))
            }
            let data = try JSONEncoder().encode(Manifest(text: text, attachments: attachments))
            try data.write(to: staging.appendingPathComponent("manifest.json"), options: .atomic)
            try fileManager.moveItem(at: staging, to: destination)
        } catch {
            try? fileManager.removeItem(at: staging)
            throw error
        }
    }

    static func peekNext(queue: URL? = nil) async throws -> SharedImport? {
        try await Task.detached(priority: .userInitiated) {
            let fileManager = FileManager.default
            let queue = try queue ?? queueURL()
            guard fileManager.fileExists(atPath: queue.path) else { return nil }
            let entries = try fileManager.contentsOfDirectory(
                at: queue, includingPropertiesForKeys: [.creationDateKey], options: [.skipsHiddenFiles]
            ).sorted {
                let first = (try? $0.resourceValues(forKeys: [.creationDateKey]).creationDate) ?? .distantPast
                let second = (try? $1.resourceValues(forKeys: [.creationDateKey]).creationDate) ?? .distantPast
                return first < second
            }
            guard let item = entries.first else { return nil }
            let manifest = try JSONDecoder().decode(
                Manifest.self, from: Data(contentsOf: item.appendingPathComponent("manifest.json")))
            let attachments = try manifest.attachments.map { attachment in
                SharedImport.Attachment(
                    kind: attachment.kind,
                    data: try Data(
                        contentsOf: item.appendingPathComponent(attachment.filename), options: .mappedIfSafe),
                    filename: attachment.filename
                )
            }
            return SharedImport(id: item.lastPathComponent, text: manifest.text, attachments: attachments)
        }.value
    }

    static func acknowledge(_ item: SharedImport, queue: URL? = nil) async throws {
        try await Task.detached(priority: .userInitiated) {
            guard UUID(uuidString: item.id) != nil else { throw StoreError.invalidContent }
            let queue = try queue ?? queueURL()
            try FileManager.default.removeItem(at: queue.appendingPathComponent(item.id, isDirectory: true))
        }.value
    }
}

extension SharedImport.Attachment {
    enum Kind: String, Codable { case image, video }
}