import Foundation import Observation /// App-wide state: the signed-in account and the API clients. /// Injected into the environment from `UntangleApp`. @MainActor @Observable final class AppModel { private(set) var bobbin = Bobbin() let oauth = OAuthClient() private(set) var session: OAuthSession? private(set) var pds: PDSClient? /// The user chose to browse without signing in. var isGuest = false var isSignedIn: Bool { session != nil } var currentDID: String? { session?.did } var currentHandle: String? { session?.handle } init() { if let stored = SessionKeychain.load() { activate(stored) } } func signIn(identifier: String, authenticate: @escaping OAuthClient.Authenticate) async throws { let session = try await oauth.signIn(identifier: identifier, authenticate: authenticate) SessionKeychain.save(session) activate(session) isGuest = false } func signOut() { if let session { let oauth = oauth Task { await oauth.revoke(session) } } SessionKeychain.delete() session = nil pds = nil isGuest = false } private func activate(_ session: OAuthSession) { self.session = session pds = PDSClient(session: session, oauth: oauth) { updated in SessionKeychain.save(updated) } } // MARK: Writes enum WriteError: LocalizedError { case signedOut var errorDescription: String? { "Sign in to do that." } } private func requirePDS() throws -> PDSClient { guard let pds else { throw WriteError.signedOut } return pds } /// Stars a repo, returning the new star record's URI. func star(repoDID: String) async throws -> String { let output = try await requirePDS().createRecord(collection: NSID.star, record: [ "subject": .object(["$type": .string("\(NSID.star)#repo"), "identity": .string(repoDID)]), "createdAt": .string(ATDate.now()), ]) return output.uri } /// Follows someone. The record key is the followed account's DID. func follow(did: String) async throws -> String { let output = try await requirePDS().createRecord(collection: NSID.follow, rkey: did, record: [ "createdAt": .string(ATDate.now()), ]) return output.uri } /// Deletes one of the user's own records (an unstar, unfollow, etc.). func deleteRecord(uri: String) async throws { try await requirePDS().deleteRecord(uri: uri) } // MARK: Tickets (written to the repo's own repo through its knot) private func knot() throws -> KnotClient { KnotClient(pds: try requirePDS()) } private static func markdown(_ text: String, inline: Bool = false) -> JSONValue { .object([ "$type": .string(inline ? NSID.markdownInline : NSID.markdown), "text": .string(text), ]) } /// Opens an issue, returning its URI. func createIssue(repoDID: String, title: String, body: String) async throws -> String { var record: [String: JSONValue] = [ "title": Self.markdown(title, inline: true), "state": .string("open"), "createdAt": .string(ATDate.now()), ] if !body.isEmpty { record["body"] = Self.markdown(body) } return try await knot().createRecord(repoDID: repoDID, collection: NSID.ticket, record: record).uri } /// Comments on a ticket (issue or pull request). func comment(on ticket: StrongRef, body: String) async throws { guard let repoDID = ATURI(ticket.uri)?.authority else { return } _ = try await knot().createRecord(repoDID: repoDID, collection: NSID.comment, record: [ "subject": .object([ "$type": .string(NSID.strongRef), "uri": .string(ticket.uri), "cid": .string(ticket.cid), ]), "body": Self.markdown(body), "createdAt": .string(ATDate.now()), ]) } /// Closes or reopens a ticket by rewriting its state. func setTicketState(uri: String, open: Bool) async throws { guard let parsed = ATURI(uri), let rkey = parsed.rkey else { return } let knot = try knot() let current = try await knot.getRecord(repoDID: parsed.authority, collection: NSID.ticket, rkey: rkey) guard case .object(var record) = current.value else { return } record["state"] = .string(open ? "open" : "closed") // The knot refuses atproto self-labels on tickets. record["labels"] = nil try await knot.putRecord(repoDID: parsed.authority, collection: NSID.ticket, rkey: rkey, record: record, swapRecord: current.cid) } // MARK: API service /// Switches every Bobbin request to `service` and remembers the choice. func setAPIService(_ service: URL) { Bobbin.configuredService = service bobbin = Bobbin(service: service) } }