import CryptoKit import Foundation actor DraftLocalMediaStore { struct Entry: Codable { let id: UUID let images: [ImageFile] let video: VideoFile? let replyTo: String? let publishResultUnknown: Bool var references: [String] { images.map { "oldfella-drafts/\(id.uuidString)/image-\($0.id.uuidString)" } + (video.map { ["oldfella-drafts/\(id.uuidString)/video-\($0.id.uuidString)"] } ?? []) } } struct ImageFile: Codable { let id: UUID let mimeType: String } struct VideoFile: Codable { let id: UUID let mimeType: String } private struct Binding: Codable { let remoteID: String let entryID: UUID let fingerprint: String } private let directory: URL? private let fileManager = FileManager.default init(directory: URL? = nil) { self.directory = directory ?? FileManager.default.containerURL( forSecurityApplicationGroupIdentifier: AppGroup.identifier)? .appendingPathComponent("DraftMedia", isDirectory: true) } func prepare(_ draft: ComposerDraft, accountID: String) throws -> Entry { let account = try accountDirectory(accountID) try fileManager.createDirectory(at: account, withIntermediateDirectories: true) let id = UUID() let entry = Entry( id: id, images: draft.attachments.map { ImageFile(id: $0.id, mimeType: $0.mimeType) }, video: draft.video.map { VideoFile(id: $0.id, mimeType: $0.mimeType) }, replyTo: draft.replyTo, publishResultUnknown: draft.publishResultUnknown) let staging = account.appendingPathComponent(".\(id.uuidString)", isDirectory: true) try fileManager.createDirectory(at: staging, withIntermediateDirectories: false) defer { try? fileManager.removeItem(at: staging) } for image in draft.attachments { try image.data.write(to: staging.appendingPathComponent("image-\(image.id.uuidString)"), options: .atomic) } if let video = draft.video { let destination = staging.appendingPathComponent("video-\(video.id.uuidString)") switch video.source { case .data(let data): try data.write(to: destination, options: .atomic) case .file(let source): try fileManager.copyItem(at: source, to: destination) } } try JSONEncoder().encode(entry).write(to: staging.appendingPathComponent("entry.json"), options: .atomic) try fileManager.moveItem(at: staging, to: account.appendingPathComponent(id.uuidString, isDirectory: true)) return entry } func bind(_ entry: Entry, remoteID: String, fingerprint: String, accountID: String) throws { let destination = try bindingURL(remoteID, accountID: accountID) let previous = try? JSONDecoder().decode(Binding.self, from: Data(contentsOf: destination)) try fileManager.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) let binding = Binding(remoteID: remoteID, entryID: entry.id, fingerprint: fingerprint) try JSONEncoder().encode(binding).write(to: destination, options: .atomic) if let previous, previous.entryID != entry.id { let directory = try accountDirectory(accountID).appendingPathComponent(previous.entryID.uuidString) try? fileManager.removeItem(at: directory) } } func entry(remoteID: String, fingerprint: String, accountID: String) throws -> Entry? { let bindingURL = try bindingURL(remoteID, accountID: accountID) guard fileManager.fileExists(atPath: bindingURL.path) else { return nil } let binding = try JSONDecoder().decode(Binding.self, from: Data(contentsOf: bindingURL)) guard binding.remoteID == remoteID, binding.fingerprint == fingerprint else { return nil } let directory = try accountDirectory(accountID).appendingPathComponent(binding.entryID.uuidString) let entry = try JSONDecoder().decode( Entry.self, from: Data(contentsOf: directory.appendingPathComponent("entry.json"))) guard entry.id == binding.entryID, entry.images.count <= 4, entry.video == nil || entry.images.isEmpty, Set(entry.images.map(\.id)).count == entry.images.count, entry.images.allSatisfy({ $0.mimeType.hasPrefix("image/") }), entry.video.map({ $0.mimeType.hasPrefix("video/") }) ?? true else { throw SavedPostDraftError.unavailable("The media for this draft could not be read.") } for reference in entry.references { let filename = URL(fileURLWithPath: reference).lastPathComponent guard fileManager.fileExists(atPath: directory.appendingPathComponent(filename).path) else { throw SavedPostDraftError.unavailable("The media for this draft is no longer on this device.") } } return entry } func images(_ entry: Entry, altText: [String], accountID: String) throws -> [ImageAttachment] { guard entry.images.count == altText.count else { throw ServiceError.invalidResponse } let directory = try accountDirectory(accountID).appendingPathComponent(entry.id.uuidString) return try zip(entry.images, altText).map { image, alt in ImageAttachment( id: image.id, data: try Data( contentsOf: directory.appendingPathComponent("image-\(image.id.uuidString)"), options: .mappedIfSafe), altText: alt, mimeType: image.mimeType) } } func video(_ entry: Entry, accountID: String) throws -> VideoAttachment? { guard let video = entry.video else { return nil } let directory = try accountDirectory(accountID).appendingPathComponent(entry.id.uuidString) return VideoAttachment( id: video.id, data: try Data( contentsOf: directory.appendingPathComponent("video-\(video.id.uuidString)"), options: .mappedIfSafe), mimeType: video.mimeType) } func removeBinding(remoteID: String, accountID: String) throws { let url = try bindingURL(remoteID, accountID: accountID) guard fileManager.fileExists(atPath: url.path) else { return } let binding = try JSONDecoder().decode(Binding.self, from: Data(contentsOf: url)) guard binding.remoteID == remoteID else { throw ServiceError.invalidResponse } try fileManager.removeItem(at: url) let directory = try accountDirectory(accountID).appendingPathComponent(binding.entryID.uuidString) try? fileManager.removeItem(at: directory) } func removePrepared(_ entry: Entry, accountID: String) throws { let directory = try accountDirectory(accountID).appendingPathComponent(entry.id.uuidString) if fileManager.fileExists(atPath: directory.path) { try fileManager.removeItem(at: directory) } } private func accountDirectory(_ accountID: String) throws -> URL { guard let directory, !accountID.isEmpty else { throw SavedPostDraftError.unavailable("Old Fella could not access the media for saved drafts. Try again.") } return directory.appendingPathComponent(Self.hash(Data(accountID.utf8)), isDirectory: true) } private func bindingURL(_ remoteID: String, accountID: String) throws -> URL { try accountDirectory(accountID).appendingPathComponent("bindings", isDirectory: true) .appendingPathComponent(Self.hash(Data(remoteID.utf8)) + ".json") } static func hash(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() } }