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
import ATProtoKit
import Foundation
extension ATProtoBlueskyService {
private static let profileCollection = ProfileCollection.type
private static let profileLinkCollection = ProfileLinkCollection.type
private struct ProfileRecord: Decodable {
let cid: String
let value: [String: CodableValue]
}
private struct ProfileLinkReference: Sendable {
let uri: String
let cid: String
let key: String
var value: CodableValue { .dictionary(["uri": .string(uri), "cid": .string(cid)]) }
}
func loadProfileEdit(accountID: String) async throws -> EditableProfile {
guard let account = stored, account.did == accountID else { throw ServiceError.noSession }
let generation = sessionGeneration
let profile = try await readProfileRecord(collection: Self.profileCollection, key: "self", account: account)
let value = profile?.value ?? [:]
let refs = try Self.profileLinkReferences(in: value, accountID: accountID)
let links = try await withThrowingTaskGroup(of: (Int, ProfileEdit.Link).self) { group in
for (index, ref) in refs.enumerated() {
group.addTask {
let record = try await self.readProfileRecord(
collection: Self.profileLinkCollection, key: ref.key, cid: ref.cid, account: account)
return (index, ProfileEdit.Link(
title: record?.value["title"]?.profileString ?? "",
address: record?.value["url"]?.profileString ?? ""))
}
}
var ordered: [(Int, ProfileEdit.Link)] = []
for try await link in group { ordered.append(link) }
return ordered.sorted { $0.0 < $1.0 }.map(\.1)
}
guard generation == sessionGeneration else { throw ServiceError.noSession }
return EditableProfile(
accountID: accountID, recordCID: profile?.cid, avatarURL: Self.profileAvatarURL(value["avatar"], account: account),
draft: ProfileEdit(
displayName: value["displayName"]?.profileString ?? "",
bio: value["description"]?.profileString ?? "", links: links))
}
func saveProfileEdit(_ draft: ProfileEdit, original: EditableProfile, accountID: String) async throws
-> ProfileEditResult {
if let error = draft.validationError(comparedTo: original.draft) { throw ProfileEditError.invalidInput(error) }
guard let account = stored, account.did == accountID, original.accountID == accountID else {
throw ServiceError.noSession
}
let generation = sessionGeneration
let current = try await readProfileRecord(collection: Self.profileCollection, key: "self", account: account)
guard current?.cid == original.recordCID else { throw ProfileEditError.changedOnServer }
guard generation == sessionGeneration else { throw ServiceError.noSession }
let client = try await authenticatedClient()
do {
guard generation == sessionGeneration else { throw ServiceError.noSession }
let value = try await updatedProfile(draft, original: original.draft, current: current?.value ?? [:],
client: client, account: account)
let links = try Self.profileLinkReferences(in: value, accountID: accountID)
try await writeProfile(value, previousCID: current?.cid, client: client, account: account)
guard generation == sessionGeneration else { throw ServiceError.noSession }
if let id = client.sessionConfiguration?.instanceUUID {
await UserSessionRegistry.shared.removeSession(for: id)
}
return ProfileEditResult(
account: Account(handle: account.handle, displayName: draft.displayName, id: account.did,
avatarURL: Self.profileAvatarURL(value["avatar"], account: account)),
linkIDs: links.map(\.uri))
} catch {
if let id = client.sessionConfiguration?.instanceUUID {
await UserSessionRegistry.shared.removeSession(for: id)
}
throw error
}
}
private func updatedProfile(
_ draft: ProfileEdit, original: ProfileEdit, current: [String: CodableValue],
client: ATProtoKit, account: StoredSession
) async throws -> [String: CodableValue] {
var value = current
value["$type"] = .string(Self.profileCollection)
if draft.displayName != original.displayName {
value["displayName"] = draft.displayName.isEmpty ? nil : .string(draft.displayName)
}
if draft.bio != original.bio {
value["description"] = draft.bio.isEmpty ? nil : .string(draft.bio)
}
switch draft.avatar {
case .keep: break
case .remove: value["avatar"] = nil
case .replace(let data):
guard !data.isEmpty, data.count <= 1_000_000 else { throw ServiceError.imageTooLarge }
let blob = try await client.uploadBlob(data, contentType: "image/jpeg")
value["avatar"] = try JSONDecoder().decode(CodableValue.self, from: JSONEncoder().encode(blob))
}
if draft.links != original.links {
let refs = try Self.profileLinkReferences(in: current, accountID: account.did)
guard refs.count == original.links.count else { throw ServiceError.invalidResponse }
let existing = Dictionary(uniqueKeysWithValues: zip(original.links.map(\.id), zip(original.links, refs)))
var ordered: [CodableValue] = []
for link in draft.links {
let previous = existing[link.id]
let ref = try await writeProfileLink(link, previous: previous, client: client, account: account)
ordered.append(ref.value)
}
value["links"] = ordered.isEmpty ? nil : .array(ordered)
}
return value
}
private func writeProfileLink(
_ link: ProfileEdit.Link, previous: (ProfileEdit.Link, ProfileLinkReference)?,
client: ATProtoKit, account: StoredSession
) async throws -> ProfileLinkReference {
var record: [String: CodableValue] = [:]
if let (oldLink, ref) = previous {
if link.title == oldLink.title, link.address == oldLink.address { return ref }
record = try await readProfileRecord(
collection: Self.profileLinkCollection, key: ref.key, cid: ref.cid, account: account)?.value ?? [:]
if link.address != oldLink.address { record["icon"] = nil }
}
record["$type"] = .string(Self.profileLinkCollection)
record["title"] = link.title.isEmpty ? nil : .string(link.title)
record["url"] = .string(link.address)
record["createdAt"] = record["createdAt"] ?? .string(ISO8601DateFormatter().string(from: link.editedAt))
// A new record keeps the old link visible until Bluesky saves the new profile order.
let key = Self.profileLinkKey(link)
let result = try await client.putRecord(
repository: account.did, collection: Self.profileLinkCollection, recordKey: key,
shouldValidate: nil, record: .record(RawProfileRecord<ProfileLinkCollection>(record)))
guard result.recordURI == "at://\(account.did)/\(Self.profileLinkCollection)/\(key)",
!result.recordCID.isEmpty else { throw ServiceError.invalidResponse }
return ProfileLinkReference(uri: result.recordURI, cid: result.recordCID, key: key)
}
private func writeProfile(
_ value: [String: CodableValue], previousCID: String?, client: ATProtoKit, account: StoredSession
) async throws {
let record = UnknownType.record(RawProfileRecord<ProfileCollection>(value))
do {
if let previousCID {
_ = try await client.putRecord(
repository: account.did, collection: Self.profileCollection, recordKey: "self",
shouldValidate: nil, record: record, swapRecord: previousCID)
} else {
_ = try await client.createRecord(
repositoryDID: account.did, collection: Self.profileCollection, recordKey: "self",
shouldValidate: nil, record: record)
}
} catch {
// The reply can fail after the write. Read the profile before reporting a failure.
if let latest = try? await readProfileRecord(collection: Self.profileCollection, key: "self", account: account) {
if latest.value == value { return }
if latest.cid != previousCID { throw ProfileEditError.changedOnServer }
}
throw error
}
}
private func readProfileRecord(collection: String, key: String, cid: String? = nil, account: StoredSession)
async throws -> ProfileRecord? {
guard stored?.did == account.did else { throw ServiceError.noSession }
let url = account.pdsURL.appending(path: "xrpc/com.atproto.repo.getRecord")
var query = [URLQueryItem(name: "repo", value: account.did), URLQueryItem(name: "collection", value: collection),
URLQueryItem(name: "rkey", value: key)]
if let cid { query.append(URLQueryItem(name: "cid", value: cid)) }
do {
let (data, _) = try await send(to: url.appending(queryItems: query), method: "GET", body: nil,
contentType: nil, authenticated: true)
let record = try JSONDecoder().decode(ProfileRecord.self, from: data)
guard !record.cid.isEmpty else { throw ServiceError.invalidResponse }
return cid == nil || cid == record.cid ? record : nil
} catch ServiceError.serverResponse(code: "RecordNotFound", message: _) {
return nil
}
}
private static func profileLinkReferences(in record: [String: CodableValue], accountID: String) throws
-> [ProfileLinkReference] {
guard let links = record["links"] else { return [] }
guard case .array(let refs) = links else { throw ServiceError.invalidResponse }
let prefix = "at://\(accountID)/\(profileLinkCollection)/"
return try refs.map { ref in
guard case .dictionary(let value) = ref, let uri = value["uri"]?.profileString,
uri.hasPrefix(prefix), let cid = value["cid"]?.profileString, !cid.isEmpty
else { throw ServiceError.invalidResponse }
let key = String(uri.dropFirst(prefix.count))
guard !key.isEmpty, !key.contains("/") else { throw ServiceError.invalidResponse }
return ProfileLinkReference(uri: uri, cid: cid, key: key)
}
}
private static func profileAvatarURL(_ value: CodableValue?, account: StoredSession) -> URL? {
guard case .dictionary(let blob) = value else { return nil }
let cid: String?
if case .dictionary(let reference) = blob["ref"] {
cid = reference["$link"]?.profileString
} else {
cid = blob["cid"]?.profileString
}
guard let cid else { return nil }
return account.pdsURL.appending(path: "xrpc/com.atproto.sync.getBlob").appending(queryItems: [
URLQueryItem(name: "did", value: account.did), URLQueryItem(name: "cid", value: cid)
])
}
private static func profileLinkKey(_ link: ProfileEdit.Link) -> String {
// AT Protocol TIDs encode a microsecond timestamp and a 10-bit clock ID.
let alphabet = Array("234567abcdefghijklmnopqrstuvwxyz")
let clockID = (UInt64(link.revision.uuid.14) << 8 | UInt64(link.revision.uuid.15)) & 1023
let value = UInt64(link.editedAt.timeIntervalSince1970 * 1_000_000) << 10 | clockID
return String((0..<13).reversed().map { alphabet[Int((value >> ($0 * 5)) & 31)] })
}
}
private protocol ProfileRecordCollection {
static var type: String { get }
}
private enum ProfileCollection: ProfileRecordCollection {
static let type = "app.bsky.actor.profile"
}
private enum ProfileLinkCollection: ProfileRecordCollection {
static let type = "app.bsky.actor.link"
}
// ATProtoKit 0.34.1 encodes UnknownType.unknown as data. Encode the record as an object.
private struct RawProfileRecord<Collection: ProfileRecordCollection>: ATRecordProtocol {
static var type: String { Collection.type }
let value: [String: CodableValue]
init(_ value: [String: CodableValue]) { self.value = value }
init(from decoder: Decoder) throws { value = try [String: CodableValue](from: decoder) }
func encode(to encoder: Encoder) throws { try value.encode(to: encoder) }
}
private extension CodableValue {
var profileString: String? {
guard case .string(let value) = self else { return nil }
return value
}
}