1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
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<String> = []
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)
}
}
}