import ATProtoKit import Foundation extension ATProtoBlueskyService { private static let draftLocalMedia = DraftLocalMediaStore() func loadDrafts(cursor: String?) async throws -> SavedPostDraftPage { guard let accountID = stored?.did else { throw ServiceError.noSession } let generation = sessionGeneration let response = try await rawDraftPage(cursor: cursor) var summaries: [SavedPostDraft] = [] for wire in response.drafts { let context = await localDraftContext(wire, accountID: accountID) summaries.append(SavedPostDraft( id: wire.id, text: wire.text, updatedAt: wire.updatedAt, imageCount: wire.images.count, hasVideo: !wire.videos.isEmpty, replyTo: context.entry?.replyTo, quotePostID: wire.quotePostID, unavailableReason: wire.unsupportedReason ?? context.reason)) } guard generation == sessionGeneration else { throw ServiceError.noSession } return SavedPostDraftPage(drafts: summaries, cursor: response.cursor) } func loadDraft(id: String) async throws -> ComposerDraft { guard let accountID = stored?.did else { throw ServiceError.noSession } let generation = sessionGeneration let wire = try await findDraft(id: id) if let reason = wire.unsupportedReason { throw SavedPostDraftError.unavailable(reason) } let context = await localDraftContext(wire, accountID: accountID) if let reason = context.reason { throw SavedPostDraftError.unavailable(reason) } let images: [ImageAttachment] let video: VideoAttachment? if let entry = context.entry { images = try await Self.draftLocalMedia.images( entry, altText: wire.images.map { $0["alt"] as? String ?? "" }, accountID: accountID) video = try await Self.draftLocalMedia.video(entry, accountID: accountID) } else { images = [] video = nil } guard generation == sessionGeneration else { throw ServiceError.noSession } return ComposerDraft( text: wire.text, attachments: images, video: video, replyTo: context.entry?.replyTo, quotePostID: wire.quotePostID, publishResultUnknown: context.entry?.publishResultUnknown ?? false) } func saveDraft(_ draft: ComposerDraft, id: String?) async throws -> String { guard let accountID = stored?.did else { throw ServiceError.noSession } let generation = sessionGeneration try validateDraftForSaving(draft) let previous = try await writableDraft(id: id, accountID: accountID) let entry: DraftLocalMediaStore.Entry? if !draft.attachments.isEmpty || draft.video != nil || draft.replyTo != nil || draft.publishResultUnknown { entry = try await Self.draftLocalMedia.prepare(draft, accountID: accountID) } else { entry = nil } let prepared = try await preparedDraft(draft, entry: entry, previous: previous, accountID: accountID) guard generation == sessionGeneration else { await discardPreparedDraft(entry, accountID: accountID) throw ServiceError.noSession } let remoteID = try await writePreparedDraft(prepared.definition, entry: entry, id: id, accountID: accountID) guard generation == sessionGeneration else { throw ServiceError.noSession } if let entry { try await Self.draftLocalMedia.bind( entry, remoteID: remoteID, fingerprint: prepared.fingerprint, accountID: accountID) } else { try? await Self.draftLocalMedia.removeBinding(remoteID: remoteID, accountID: accountID) } if id != nil { try await confirmDraft(id: remoteID, fingerprint: prepared.fingerprint) } guard generation == sessionGeneration else { throw ServiceError.noSession } return remoteID } private func validateDraftForSaving(_ draft: ComposerDraft) throws { guard draft.attachments.count <= 4 else { throw SavedPostDraftError.unavailable("Drafts support up to four photos. Remove photos before saving.") } guard draft.video == nil || draft.attachments.isEmpty, draft.text.utf8.count <= 10_000 else { throw SavedPostDraftError.unavailable( "This post cannot be saved as a draft. Shorten it or remove its media.") } guard Set(draft.attachments.map(\.id)).count == draft.attachments.count, draft.attachments.allSatisfy({ $0.mimeType.hasPrefix("image/") }), draft.video.map({ $0.mimeType.hasPrefix("video/") }) ?? true else { throw SavedPostDraftError.unavailable("The media for this draft could not be saved.") } } private func writableDraft(id: String?, accountID: String) async throws -> SavedDraftWire? { guard let id else { return nil } let previous = try await findDraft(id: id) if let reason = previous.unsupportedReason { throw SavedPostDraftError.unavailable(reason) } let context = await localDraftContext(previous, accountID: accountID) if let reason = context.reason { throw SavedPostDraftError.unavailable(reason) } return previous } private func writeDraft(_ definition: AppBskyLexicon.Draft.DraftDefinition, id: String?) async throws -> String { let client: ATProtoKit do { client = try await authenticatedClient() } catch { throw ActionNotSentError(underlying: error) } let remoteID: String do { if let id { try await client.updateDraft(id: id, with: definition) remoteID = id } else { remoteID = try await client.createDraft(definition).id } await releaseDraftClient(client) } catch { await releaseDraftClient(client) throw error } return remoteID } private func preparedDraft( _ draft: ComposerDraft, entry: DraftLocalMediaStore.Entry?, previous: SavedDraftWire?, accountID: String ) async throws -> (definition: AppBskyLexicon.Draft.DraftDefinition, fingerprint: String) { do { let definition = try await draftDefinition(draft, entry: entry, previous: previous) let encoded = try JSONEncoder().encode(definition) guard let object = try JSONSerialization.jsonObject(with: encoded) as? [String: Any] else { throw ServiceError.invalidResponse } return (definition, try SavedDraftWire.fingerprint(object)) } catch { await discardPreparedDraft(entry, accountID: accountID) throw error } } private func writePreparedDraft( _ definition: AppBskyLexicon.Draft.DraftDefinition, entry: DraftLocalMediaStore.Entry?, id: String?, accountID: String ) async throws -> String { do { return try await writeDraft(definition, id: id) } catch { let rejectedCodes = ["DraftLimitReached", "InvalidRequest", "InvalidToken", "ExpiredToken", "AuthMissing"] if error is ActionNotSentError || error is ATRequestPrepareError || error is EncodingError { await discardPreparedDraft(entry, accountID: accountID) } else if let error = error as? ServiceError { switch error { case .noSession: await discardPreparedDraft(entry, accountID: accountID) case .serverResponse(let code, _) where rejectedCodes.contains(code): await discardPreparedDraft(entry, accountID: accountID) default: break } } throw error } } private func discardPreparedDraft(_ entry: DraftLocalMediaStore.Entry?, accountID: String) async { if let entry { try? await Self.draftLocalMedia.removePrepared(entry, accountID: accountID) } } private func confirmDraft(id: String, fingerprint: String) async throws { let confirmed = try await findDraft(id: id) guard try SavedDraftWire.fingerprint(confirmed.draft) == fingerprint else { throw SavedPostDraftError.unavailable( "The saved draft could not be confirmed. Keep editing and try again.") } } func deleteDraft(id: String) async throws { guard let accountID = stored?.did else { throw ServiceError.noSession } let generation = sessionGeneration let client = try await authenticatedClient() do { try await client.deleteDraft(id: id) await releaseDraftClient(client) } catch { await releaseDraftClient(client) throw error } guard generation == sessionGeneration else { throw ServiceError.noSession } try? await Self.draftLocalMedia.removeBinding(remoteID: id, accountID: accountID) } private func draftDefinition( _ draft: ComposerDraft, entry: DraftLocalMediaStore.Entry?, previous: SavedDraftWire? ) async throws -> AppBskyLexicon.Draft.DraftDefinition { let images = zip(draft.attachments, entry?.references ?? []).map { image, path in AppBskyLexicon.Draft.DraftEmbedImageDefinition(localRef: .init(path: path), altText: image.altText) } let videos = draft.video.flatMap { _ in entry?.references.first }.map { [AppBskyLexicon.Draft.DraftEmbedVideoDefinition(localRef: .init(path: $0), altText: nil, captions: nil)] } let records: [AppBskyLexicon.Draft.DraftEmbedRecordDefinition]? if let quoteID = draft.quotePostID { let reference: ComAtprotoLexicon.Repository.StrongReference if previous?.quotePostID == quoteID, let old = (previous?.post["embedRecords"] as? [[String: Any]])?.first?["record"] as? [String: Any], let cid = old["cid"] as? String { reference = .init(recordURI: quoteID, cidHash: cid) } else { guard let post = try await loadPost(uri: quoteID).first(where: { $0.id == quoteID }), !post.cid.isEmpty else { throw ServiceError.postReferenceUnavailable } reference = .init(recordURI: quoteID, cidHash: post.cid) } records = [.init(record: reference)] } else { records = nil } let post = AppBskyLexicon.Draft.DraftPostDefinition( text: draft.text, embedImages: images.isEmpty ? nil : images, embedVideos: videos, embedRecords: records) let deviceName = draft.replyTo != nil || draft.publishResultUnknown ? SavedDraftWire.localContextDeviceName : "Old Fella" return .init(deviceName: deviceName, posts: [post]) } private func localDraftContext(_ wire: SavedDraftWire, accountID: String) async -> (entry: DraftLocalMediaStore.Entry?, reason: String?) { guard wire.needsLocalContext || !wire.references.isEmpty else { return (nil, nil) } do { let fingerprint = try SavedDraftWire.fingerprint(wire.draft) guard let entry = try await Self.draftLocalMedia.entry( remoteID: wire.id, fingerprint: fingerprint, accountID: accountID), entry.references == wire.references else { return (nil, "Open this draft on the device where it was saved.") } return (entry, nil) } catch { return (nil, error.localizedDescription) } } private func findDraft(id: String) async throws -> SavedDraftWire { var cursor: String? var seen: Set = [] repeat { let page = try await rawDraftPage(cursor: cursor) if let draft = page.drafts.first(where: { $0.id == id }) { return draft } cursor = page.cursor if let cursor, !seen.insert(cursor).inserted { throw ServiceError.invalidResponse } } while cursor != nil throw SavedPostDraftError.missing } private func rawDraftPage(cursor: String?) async throws -> (drafts: [SavedDraftWire], cursor: String?) { let capture = ResponseCapture() let client = try await authenticatedClient(capture: capture) do { _ = try await client.getDrafts(limit: 100, cursor: cursor) await releaseDraftClient(client) } catch { await releaseDraftClient(client) guard error is DecodingError, await capture.read() != nil else { throw error } } guard let data = await capture.read(), let object = try JSONSerialization.jsonObject(with: data) as? [String: Any], let drafts = object["drafts"] as? [[String: Any]] else { throw ServiceError.invalidResponse } let formatter = ISO8601DateFormatter() let views = try drafts.map { view -> SavedDraftWire in guard let id = view["id"] as? String, let draft = view["draft"] as? [String: Any], let date = view["updatedAt"] as? String else { throw ServiceError.invalidResponse } formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] let fractionalDate = formatter.date(from: date) formatter.formatOptions = [.withInternetDateTime] guard let updatedAt = fractionalDate ?? formatter.date(from: date) else { throw ServiceError.invalidResponse } return SavedDraftWire(id: id, draft: draft, updatedAt: updatedAt) } return (views, object["cursor"] as? String) } private func releaseDraftClient(_ client: ATProtoKit) async { if let id = client.sessionConfiguration?.instanceUUID { await UserSessionRegistry.shared.removeSession(for: id) } } }