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

geesawra.industries/old-fella

Old people's social media app

0
1
main
146 lines · 6.0 KB Raw History
import ATProtoKit
import Darwin
import Foundation
import OSLog
import Security
import UIKit

extension ATProtoBlueskyService {
    func restoreAccount() async throws -> Account? {
        try await restoreAccount { _ in }
    }

    func restoreAccount(onLocalAccount: @MainActor @Sendable (String) -> Void) async throws -> Account? {
        let generation = UUID()
        sessionGeneration = generation
        selectedLabelers.removeAll()
        cachedLabelDefinitions.removeAll()
        refreshTask = nil
        let restored: StoredSession
        do {
            let lock = try await acquireRefreshLock()
            defer {
                if let lock {
                    flock(lock, LOCK_UN)
                    close(lock)
                }
            }
            guard generation == sessionGeneration else { throw ServiceError.noSession }
            if usesSharedSession, try currentSessionID() == nil,
                let legacyID = defaults.string(forKey: sessionDefaultsKey) {
                try migrateLegacySession(account: legacyID)
            }
            guard let sessionID = try currentSessionID() else { return nil }
            guard let data = try keychainRead(account: sessionID) else {
                try clearCurrentSessionID()
                return nil
            }
            activeSessionID = sessionID
            restored = try JSONDecoder().decode(StoredSession.self, from: data)
            stored = restored
        }
        await onLocalAccount(restored.did)
        guard generation == sessionGeneration else { throw ServiceError.noSession }
        _ = try await accessToken()
        guard generation == sessionGeneration else { throw ServiceError.noSession }
        let result = await account(for: restored)
        guard generation == sessionGeneration else { throw ServiceError.noSession }
        return result
    }

    func signIn(handle: String, appPassword: String, authFactorToken: String?) async throws -> Account {
        let cleanHandle = handle.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "@", with: "")
        guard !cleanHandle.isEmpty, !appPassword.isEmpty else { throw ServiceError.invalidCredentials }
        let generation = UUID()
        sessionGeneration = generation
        selectedLabelers.removeAll()
        cachedLabelDefinitions.removeAll()
        refreshTask = nil
        let did = try await resolveDID(for: cleanHandle)
        let loginPDSURL = try await resolvePDSURL(for: did)
        let client = await apiClient(for: loginPDSURL)
        let response: ComAtprotoLexicon.Server.CreateSessionOutput
        do {
            response = try await client.createSession(
                with: cleanHandle, and: appPassword,
                authenticationFactorToken: authFactorToken.flatMap { $0.isEmpty ? nil : $0 })
        } catch ServiceError.serverResponse(let code, _)
            where authFactorToken != nil && ["InvalidToken", "ExpiredToken"].contains(code) {
            throw ServiceError.authFactorTokenRejected
        }
        let documentData = try response.didDocument?.toJSON()
        let fallbackDocument = documentData.flatMap { try? JSONSerialization.jsonObject(with: $0) }
        let pdsURL = try await resolvePDSURL(for: response.did, fallbackDocument: fallbackDocument)
        guard generation == sessionGeneration else { throw ServiceError.noSession }
        let newSession = StoredSession(
            handle: response.handle, did: response.did, accessToken: response.accessToken,
            refreshToken: response.refreshToken, expiresAt: Self.expiration(of: response.accessToken), pdsURL: pdsURL)
        try await storeSession(newSession, generation: generation)
        followRecordURIs.removeAll()
        let result = await account(for: newSession)
        guard generation == sessionGeneration else { throw ServiceError.noSession }
        return result
    }

    func account(for session: StoredSession) async -> Account {
        let profile = try? await getProfile(actorID: session.did)
        var account = Account(
            handle: session.handle,
            displayName: profile?.displayName ?? session.handle,
            id: session.did,
            avatarURL: profile?.avatarImageURL
        )
        account.isAvatarURLKnown = profile != nil
        return account
    }

    func signOut() async throws {
        sessionGeneration = UUID()
        refreshTask?.cancel()
        refreshTask = nil
        let lock = try await acquireRefreshLock()
        defer {
            if let lock {
                flock(lock, LOCK_UN)
                close(lock)
            }
        }
        let sessionID = try currentSessionID()
        if !usesSharedSession || sessionID == activeSessionID {
            try clearCurrentSessionID()
            if let sessionID { try keychainDelete(account: sessionID) }
            if usesSharedSession { clearLegacySession() }
        }
        activeSessionID = nil
        stored = nil
        selectedLabelers.removeAll()
        cachedLabelDefinitions.removeAll()
        followRecordURIs.removeAll()
    }
    private func storeSession(_ newSession: StoredSession, generation: UUID) async throws {
        let sessionID = UUID().uuidString
        do {
            let lock = try await acquireRefreshLock()
            defer {
                if let lock {
                    flock(lock, LOCK_UN)
                    close(lock)
                }
            }
            guard generation == sessionGeneration else { throw ServiceError.noSession }
            let previousSessionID = try currentSessionID()
            try keychainWrite(JSONEncoder().encode(newSession), account: sessionID)
            do {
                try setCurrentSessionID(sessionID)
            } catch {
                try? keychainDelete(account: sessionID)
                throw error
            }
            if let previousSessionID { try? keychainDelete(account: previousSessionID) }
            if usesSharedSession { clearLegacySession() }
            activeSessionID = sessionID
            stored = newSession
        }
    }

}