Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / ReplyInbox.swift
| 1 | import Foundation |
| 2 | |
| 3 | @MainActor |
| 4 | struct ReplyInbox { |
| 5 | let workspace: Workspace |
| 6 | var transport = SocialTransport() |
| 7 | var accountOverride: ManagedSocialAccount? = nil |
| 8 | |
| 9 | private func savedAccount() throws -> ManagedSocialAccount? { |
| 10 | if let accountOverride { return accountOverride } |
| 11 | return try workspace.socialAccounts.savedAccount(.x) |
| 12 | } |
| 13 | |
| 14 | private func canRead(_ account: ManagedSocialAccount) -> Bool { |
| 15 | (account.session.scopes ?? "").split { $0.isWhitespace || $0 == "," }.contains("tweet.read") |
| 16 | } |
| 17 | |
| 18 | private func state(_ account: ManagedSocialAccount) -> [String: Any] { |
| 19 | let states = workspace.settings["replyInboxSync"] as? [String: [String: Any]] ?? [:] |
| 20 | return states[account.connectionKey] ?? [:] |
| 21 | } |
| 22 | |
| 23 | var monitoring: Bool { |
| 24 | guard let account = try? savedAccount(), canRead(account), |
| 25 | let setting = workspace.settings["replyMonitoringX"] as? [String: Any] else { return false } |
| 26 | return setting["enabled"] as? Bool == true && setting["session"] as? String == account.connectionKey |
| 27 | } |
| 28 | |
| 29 | var hasOlder: Bool { |
| 30 | guard let account = try? savedAccount() else { return false } |
| 31 | return !(state(account)["historyCursor"] as? String ?? "").isEmpty |
| 32 | } |
| 33 | |
| 34 | var lastChecked: Date? { |
| 35 | guard let account = try? savedAccount() else { return nil } |
| 36 | return (state(account)["lastSuccessAt"] as? String).flatMap(scheduleDate) |
| 37 | } |
| 38 | |
| 39 | var rows: [WorkspaceRecord] { |
| 40 | let account = try? savedAccount() |
| 41 | let published = Set(workspace.records.filter { |
| 42 | $0.kind == "publication" && $0["platform"] == "x" && $0["status"] == "published" && $0["accountId"] == account?.id |
| 43 | }.map { $0["replyToId"] }) |
| 44 | return workspace.records.filter { $0.kind == "reply-inbox" && (account == nil || $0["accountId"] == account?.id) } |
| 45 | .map { value in |
| 46 | var row = value |
| 47 | if row["status"] != "archived" && published.contains(row["postId"]) { row["status"] = "replied" } |
| 48 | return row |
| 49 | } |
| 50 | .map { row in (row: row, date: scheduleDate(row["createdAt"]) ?? .distantPast) } |
| 51 | .sorted { $0.date > $1.date } |
| 52 | .map(\.row) |
| 53 | } |
| 54 | |
| 55 | func setMonitoring(_ enabled: Bool) throws { |
| 56 | if enabled { |
| 57 | guard let account = try savedAccount(), canRead(account) else { |
| 58 | throw WorkspaceError("Connect X with read permission before enabling monitoring.") |
| 59 | } |
| 60 | try workspace.set("replyMonitoringX", to: ["enabled": true, "session": account.connectionKey]) |
| 61 | } else { |
| 62 | try workspace.set("replyMonitoringX", to: ["enabled": false]) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | func poll(now: Date = .now) async { |
| 67 | guard monitoring, let account = try? savedAccount() else { return } |
| 68 | let attempt = (state(account)["lastAttemptAt"] as? String).flatMap(scheduleDate) ?? .distantPast |
| 69 | guard now.timeIntervalSince(attempt) >= 300 else { return } |
| 70 | do { _ = try await refresh(now: now) } |
| 71 | catch { workspace.notice = error.localizedDescription } |
| 72 | } |
| 73 | |
| 74 | @discardableResult |
| 75 | func refresh(older: Bool = false, now: Date = .now) async throws -> Int { |
| 76 | guard !workspace.refreshingReplies else { return 0 } |
| 77 | try workspace.reload() |
| 78 | guard let initial = try savedAccount(), canRead(initial), validID(initial.id) else { |
| 79 | throw WorkspaceError("Connect X with read permission in Connections.") |
| 80 | } |
| 81 | let sync = state(initial) |
| 82 | let since = sync["sinceId"] as? String ?? "" |
| 83 | let cursor = sync[older ? "historyCursor" : "recentCursor"] as? String ?? "" |
| 84 | if older && cursor.isEmpty { return 0 } |
| 85 | workspace.refreshingReplies = true |
| 86 | defer { workspace.refreshingReplies = false } |
| 87 | let attempt = workspaceTimestamp(now) |
| 88 | try workspace.saveReplyPage([], session: initial.connectionKey, |
| 89 | state: sync.merging(["lastAttemptAt": attempt]) { _, new in new }) |
| 90 | let account: ManagedSocialAccount |
| 91 | if let accountOverride { account = accountOverride } |
| 92 | else { account = try await workspace.socialAccounts.authorized(.x) } |
| 93 | guard account.connectionKey == initial.connectionKey else { throw WorkspaceError("The X connection changed. Refresh again.") } |
| 94 | let base = URL(string: "https://api.x.com/2/users/")!.appending(path: account.id).appending(path: "mentions") |
| 95 | var query: [URLQueryItem] = [ |
| 96 | .init(name: "max_results", value: "25"), |
| 97 | .init(name: "tweet.fields", value: "author_id,created_at,conversation_id,in_reply_to_user_id,referenced_tweets"), |
| 98 | .init(name: "expansions", value: "author_id,referenced_tweets.id,referenced_tweets.id.author_id"), |
| 99 | .init(name: "user.fields", value: "name,username") |
| 100 | ] |
| 101 | if !older && validID(since) { query.append(.init(name: "since_id", value: since)) } |
| 102 | if !cursor.isEmpty { query.append(.init(name: "pagination_token", value: cursor)) } |
| 103 | let (value, _) = try await transport.request(base.appending(queryItems: query), token: account.session.accessToken) |
| 104 | let meta = value["meta"] as? [String: Any] ?? [:] |
| 105 | let rows = value["data"] as? [[String: Any]] ?? [] |
| 106 | guard (value["data"] is [[String: Any]] || value["data"] == nil && meta["result_count"] as? Int == 0), |
| 107 | rows.count <= 25, |
| 108 | rows.allSatisfy({ validID($0["id"] as? String ?? "") && validID($0["author_id"] as? String ?? "") && $0["text"] is String }) else { |
| 109 | throw WorkspaceError("X returned an incomplete reply page. Refresh again.") |
| 110 | } |
| 111 | let includes = value["includes"] as? [String: Any] ?? [:] |
| 112 | let users = includes["users"] as? [[String: Any]] ?? [] |
| 113 | let parents = includes["tweets"] as? [[String: Any]] ?? [] |
| 114 | let errors = value["errors"] as? [[String: Any]] ?? [] |
| 115 | if !errors.isEmpty { |
| 116 | let ids = Set(rows.compactMap { $0["id"] as? String }) |
| 117 | let related = Set(rows.flatMap { row -> [String] in |
| 118 | let links = row["referenced_tweets"] as? [[String: Any]] ?? [] |
| 119 | return [row["author_id"] as? String ?? ""] + links.compactMap { $0["id"] as? String } |
| 120 | } + parents.compactMap { $0["author_id"] as? String }) |
| 121 | guard !rows.isEmpty, meta["result_count"] as? Int == rows.count, errors.allSatisfy({ |
| 122 | let resource = $0["resource_id"] as? String ?? $0["value"] as? String ?? "" |
| 123 | return related.contains(resource) && !ids.contains(resource) |
| 124 | }) else { throw WorkspaceError("X returned an incomplete reply page. Refresh again.") } |
| 125 | } |
| 126 | guard try savedAccount()?.connectionKey == initial.connectionKey else { |
| 127 | throw WorkspaceError("The X connection changed before replies could be saved.") |
| 128 | } |
| 129 | let mapped = rows.compactMap { row -> WorkspaceRecord? in |
| 130 | let id = row["id"] as? String ?? "" |
| 131 | let authorID = row["author_id"] as? String ?? "" |
| 132 | guard authorID != account.id else { return nil } |
| 133 | let author = users.first { $0["id"] as? String == authorID } |
| 134 | var item = WorkspaceRecord.new("reply-inbox") |
| 135 | item["id"] = "reply-x-\(account.id)-\(id)" |
| 136 | item["accountId"] = account.id |
| 137 | item["postId"] = id |
| 138 | item["platform"] = "x" |
| 139 | item["author"] = String((author?["username"] as? String ?? author?["name"] as? String ?? "X member").prefix(150)) |
| 140 | item["text"] = String((row["text"] as? String ?? "").prefix(12_500)) |
| 141 | item["url"] = "https://x.com/i/web/status/" + id |
| 142 | item["kind"] = row["in_reply_to_user_id"] as? String == account.id ? "reply" : "mention" |
| 143 | item["createdAt"] = (row["created_at"] as? String).flatMap(scheduleDate).map(workspaceTimestamp) ?? attempt |
| 144 | let references = row["referenced_tweets"] as? [[String: Any]] ?? [] |
| 145 | if let parentID = references.first(where: { $0["type"] as? String == "replied_to" })?["id"] as? String, validID(parentID), |
| 146 | let parent = parents.first(where: { $0["id"] as? String == parentID })?["text"] as? String { |
| 147 | item.fields["parent"] = ["text": String(parent.prefix(20_000)), "url": "https://x.com/i/web/status/" + parentID] |
| 148 | } |
| 149 | return item |
| 150 | } |
| 151 | let next = String((meta["next_token"] as? String ?? "").prefix(4000)) |
| 152 | let possibleIDs = [since, sync["recentHighId"] as? String ?? "", meta["newest_id"] as? String ?? ""] + rows.compactMap { $0["id"] as? String } |
| 153 | let newest = possibleIDs.filter(validID).max { $0.count == $1.count ? $0 < $1 : $0.count < $1.count } ?? "" |
| 154 | var updated = sync |
| 155 | updated["lastAttemptAt"] = attempt |
| 156 | updated["lastSuccessAt"] = attempt |
| 157 | if older { |
| 158 | updated["historyCursor"] = next |
| 159 | } else if since.isEmpty { |
| 160 | updated["sinceId"] = newest |
| 161 | updated["historyCursor"] = next |
| 162 | } else { |
| 163 | updated["recentCursor"] = next |
| 164 | updated["recentHighId"] = next.isEmpty ? "" : newest |
| 165 | updated["sinceId"] = next.isEmpty ? newest : since |
| 166 | } |
| 167 | return try workspace.saveReplyPage(mapped, session: account.connectionKey, state: updated) |
| 168 | } |
| 169 | |
| 170 | private func validID(_ text: String) -> Bool { |
| 171 | text.range(of: #"\A[0-9]{1,25}\z"#, options: .regularExpression) != nil |
| 172 | } |
| 173 | } |