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

geesawra.industries/old-fella

Old people's social media app

0
1
main
252 lines · 12.6 KB Raw History
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
    }
}