Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / AccountAnalytics.swift

Raw 17.2 KB on 8f75dd7d901e2186ca9d9e1cf2f061105c02ae42
1import CryptoKit
2import Foundation
3
4@MainActor
5struct AccountAnalytics {
6 let workspace: Workspace
7 var transport = SocialTransport()
8 var accountOverride: ManagedSocialAccount? = nil
9
10 func account(_ platform: SocialPlatform) -> ManagedSocialAccount? {
11 accountOverride ?? (try? workspace.socialAccounts.savedAccount(platform))
12 }
13
14 func capabilities(_ platform: SocialPlatform, account: ManagedSocialAccount) -> (followers: Bool, posts: Bool) {
15 let scopes = Set((account.session.scopes ?? "").split { $0.isWhitespace || $0 == "," })
16 return switch platform {
17 case .x: (scopes.contains("users.read"), scopes.contains("tweet.read"))
18 case .instagram: (scopes.contains("instagram_business_basic"), scopes.contains("instagram_business_basic"))
19 case .tiktok: (scopes.contains("user.info.stats"), scopes.contains("video.list"))
20 case .linkedin: (scopes.contains("r_member_profileAnalytics"), false)
21 case .reddit: (false, scopes.contains("read") && account.username.range(of: #"\A[A-Za-z0-9_-]{1,30}\z"#, options: .regularExpression) != nil)
22 }
23 }
24
25 func accountKey(_ platform: SocialPlatform, id: String) -> String {
26 SHA256.hash(data: Data((platform.rawValue + ":" + id).utf8)).prefix(16).map { String(format: "%02x", $0) }.joined()
27 }
28
29 func state(_ platform: SocialPlatform, account: ManagedSocialAccount) -> WorkspaceRecord? {
30 state(platform, accountID: account.id)
31 }
32
33 func state(_ platform: SocialPlatform, accountID: String) -> WorkspaceRecord? {
34 let id = "analytics-state-" + accountKey(platform, id: accountID)
35 return workspace.records.first { $0.kind == "analytics-state" && $0.id == id }
36 }
37
38 func automatic(_ platform: SocialPlatform) -> Bool {
39 let all = workspace.settings["analyticsAutomatic"] as? [String: [String: Any]] ?? [:]
40 guard let item = all[platform.rawValue], let account = account(platform) else { return false }
41 return item["enabled"] as? Bool == true && item["session"] as? String == account.connectionKey
42 }
43
44 func setAutomatic(_ enabled: Bool, platform: SocialPlatform) throws {
45 try workspace.withChanges {
46 var all = workspace.settings["analyticsAutomatic"] as? [String: [String: Any]] ?? [:]
47 if enabled {
48 guard let account = account(platform) else { throw WorkspaceError("Connect the account first.") }
49 let available = capabilities(platform, account: account)
50 guard available.followers || available.posts else { throw WorkspaceError("This account needs analytics read permission.") }
51 all[platform.rawValue] = ["enabled": true, "session": account.connectionKey]
52 } else {
53 all[platform.rawValue] = ["enabled": false]
54 }
55 try workspace.set("analyticsAutomatic", to: all)
56 }
57 }
58
59 func poll(now: Date = .now) async {
60 for platform in SocialPlatform.allCases where automatic(platform) {
61 if Task.isCancelled { return }
62 guard let account = account(platform),
63 now.timeIntervalSince(attempt(state(platform, account: account))) >= 86_400 else { continue }
64 _ = try? await refresh(platform, now: now)
65 }
66 }
67
68 @discardableResult
69 func refresh(_ platform: SocialPlatform, older: Bool = false, now: Date = .now) async throws -> [String] {
70 guard !workspace.refreshingAnalytics.contains(platform) else { return [] }
71 guard let initial = account(platform) else { throw WorkspaceError("Connect \(platform.name) first.") }
72 let available = capabilities(platform, account: initial)
73 guard available.followers || available.posts else { throw WorkspaceError("This account needs analytics read permission.") }
74 let key = accountKey(platform, id: initial.id)
75 let prior = state(platform, account: initial)
76 let cursor = prior?["cursor"] ?? ""
77 if older && cursor.isEmpty { return [] }
78 if !older, now.timeIntervalSince(attempt(prior)) < 60 { return [] }
79 workspace.refreshingAnalytics.insert(platform)
80 defer { workspace.refreshingAnalytics.remove(platform) }
81 var next = prior ?? WorkspaceRecord.new("analytics-state")
82 next["id"] = "analytics-state-" + key
83 next["platform"] = platform.rawValue
84 next["accountId"] = initial.id
85 next["accountKey"] = key
86 next["lastAttemptAt"] = workspaceTimestamp(now)
87 if !older { next["lastLatestAttemptAt"] = workspaceTimestamp(now) }
88 try workspace.saveAnalyticsRows([next])
89
90 let authorized: ManagedSocialAccount
91 if let accountOverride { authorized = accountOverride }
92 else { authorized = try await workspace.socialAccounts.authorized(platform) }
93 guard authorized.connectionKey == initial.connectionKey else { throw WorkspaceError("The account changed. Refresh again.") }
94 var warnings: [String] = []
95 let timestamp = workspaceTimestamp(now)
96 if available.followers && !older {
97 do {
98 var metrics = try await profile(platform, account: authorized)
99 metrics["at"] = timestamp
100 guard account(platform)?.connectionKey == initial.connectionKey else {
101 throw WorkspaceError("The account changed during analytics refresh.")
102 }
103 let id = "analytics-day-" + key + "-" + String(timestamp.prefix(10))
104 var day = workspace.records.first { $0.kind == "analytics-day" && $0.id == id } ?? WorkspaceRecord.new("analytics-day")
105 day["id"] = id
106 day["platform"] = platform.rawValue
107 day["accountId"] = initial.id
108 day["accountKey"] = key
109 day.fields["first"] = day.fields["first"] ?? metrics
110 day.fields["last"] = metrics
111 next["profileAt"] = timestamp
112 next["profileError"] = ""
113 try workspace.saveAnalyticsRows([day, next])
114 } catch {
115 warnings.append("Follower counts were unavailable. Previously saved observations were kept.")
116 next["profileError"] = warnings.last ?? ""
117 }
118 }
119 if available.posts {
120 do {
121 let page = try await posts(platform, account: authorized, cursor: older ? cursor : "")
122 guard account(platform)?.connectionKey == initial.connectionKey else {
123 throw WorkspaceError("The account changed during analytics refresh.")
124 }
125 let posts = page.0.map { fields -> WorkspaceRecord in
126 let id = fields["postId"] as? String ?? ""
127 var post = WorkspaceRecord(kind: "analytics-post", fields: fields)
128 post["id"] = "analytics-post-" + key + "-" + accountKey(platform, id: id)
129 post["accountKey"] = key
130 post["accountId"] = initial.id
131 post["platform"] = platform.rawValue
132 post["observedAt"] = timestamp
133 return post
134 }
135 next["cursor"] = page.1
136 next["postsAt"] = timestamp
137 next["postsError"] = ""
138 try workspace.saveAnalyticsRows(posts + [next])
139 } catch {
140 warnings.append("Post metrics were unavailable. Previously saved observations were kept.")
141 next["postsError"] = warnings.last ?? ""
142 }
143 }
144 guard account(platform)?.connectionKey == initial.connectionKey else { throw WorkspaceError("The account changed during analytics refresh.") }
145 try workspace.saveAnalyticsRows([next])
146 return warnings
147 }
148
149 private func attempt(_ state: WorkspaceRecord?) -> Date {
150 if let number = state?.fields["lastLatestAttemptAt"] as? Double {
151 return Date(timeIntervalSince1970: number / 1000)
152 }
153 return scheduleDate(state?["lastLatestAttemptAt"] ?? "") ?? .distantPast
154 }
155
156 private func profile(_ platform: SocialPlatform, account: ManagedSocialAccount) async throws -> [String: Any] {
157 let url: URL
158 let metricKey: String
159 switch platform {
160 case .x:
161 url = URL(string: "https://api.x.com/2/users/")!.appending(path: account.id)
162 .appending(queryItems: [.init(name: "user.fields", value: "public_metrics")])
163 metricKey = "followers_count"
164 case .instagram:
165 url = URL(string: "https://graph.instagram.com/v25.0/")!.appending(path: account.id)
166 .appending(queryItems: [.init(name: "fields", value: "id,followers_count,follows_count,media_count")])
167 metricKey = "followers_count"
168 case .tiktok:
169 url = URL(string: "https://open.tiktokapis.com/v2/user/info/?fields=open_id,follower_count,following_count,likes_count,video_count")!
170 metricKey = "follower_count"
171 case .linkedin:
172 url = URL(string: "https://api.linkedin.com/rest/memberFollowersCount?q=me")!
173 metricKey = "memberFollowersCount"
174 case .reddit: throw WorkspaceError("Reddit doesn’t provide follower counts for this connection.")
175 }
176 let (value, _) = try await transport.request(url, token: account.session.accessToken,
177 headers: platform == .linkedin ? LinkedInPages.headers : [:])
178 let data = value["data"] as? [String: Any] ?? [:]
179 let metrics: [String: Any]
180 switch platform {
181 case .x:
182 guard data["id"] as? String == account.id, value["errors"] == nil else { throw WorkspaceError("Incomplete X profile.") }
183 metrics = data["public_metrics"] as? [String: Any] ?? [:]
184 case .instagram:
185 guard value["id"] as? String == account.id else { throw WorkspaceError("Incomplete Instagram profile.") }
186 metrics = value
187 case .tiktok:
188 let user = data["user"] as? [String: Any] ?? [:]
189 guard user["open_id"] as? String == account.id else { throw WorkspaceError("Incomplete TikTok profile.") }
190 metrics = user
191 default: metrics = (value["elements"] as? [[String: Any]])?.first ?? [:]
192 }
193 guard let count = AnalyticsReport.integerMetric(metrics[metricKey]) else { throw WorkspaceError("Follower count unavailable.") }
194 var observation: [String: Any] = ["followers": count]
195 observation["following"] = AnalyticsReport.integerMetric(metrics["following_count"] ?? metrics["follows_count"])
196 observation["accountPosts"] = AnalyticsReport.integerMetric(metrics["tweet_count"] ?? metrics["post_count"] ?? metrics["media_count"] ?? metrics["video_count"])
197 observation["totalLikes"] = AnalyticsReport.integerMetric(metrics["likes_count"])
198 return observation
199 }
200
201 private func posts(_ platform: SocialPlatform, account: ManagedSocialAccount,
202 cursor: String) async throws -> ([[String: Any]], String) {
203 let url: URL
204 let params: [String: Any]?
205 var headers: [String: String] = [:]
206 switch platform {
207 case .x:
208 var query: [URLQueryItem] = [.init(name: "max_results", value: "25"), .init(name: "exclude", value: "retweets"),
209 .init(name: "tweet.fields", value: "created_at,public_metrics")]
210 if !cursor.isEmpty { query.append(.init(name: "pagination_token", value: cursor)) }
211 url = URL(string: "https://api.x.com/2/users/")!.appending(path: account.id).appending(path: "tweets").appending(queryItems: query)
212 params = nil
213 case .instagram:
214 var query: [URLQueryItem] = [.init(name: "fields", value: "id,caption,timestamp,permalink,like_count,comments_count"), .init(name: "limit", value: "25")]
215 if !cursor.isEmpty { query.append(.init(name: "after", value: cursor)) }
216 url = URL(string: "https://graph.instagram.com/v25.0/")!.appending(path: account.id).appending(path: "media").appending(queryItems: query)
217 params = nil
218 case .tiktok:
219 url = URL(string: "https://open.tiktokapis.com/v2/video/list/?fields=id,title,video_description,create_time,share_url,like_count,comment_count,share_count,view_count")!
220 if !cursor.isEmpty {
221 guard let value = Int64(cursor), value >= 0 else { throw WorkspaceError("Invalid TikTok analytics cursor.") }
222 params = ["max_count": 20, "cursor": value]
223 } else { params = ["max_count": 20] }
224 case .reddit:
225 var query: [URLQueryItem] = [.init(name: "limit", value: "25"), .init(name: "raw_json", value: "1")]
226 if !cursor.isEmpty { query.append(.init(name: "after", value: cursor)) }
227 url = URL(string: "https://oauth.reddit.com/user/")!.appending(path: account.username).appending(path: "submitted").appending(queryItems: query)
228 params = nil
229 headers["User-Agent"] = "desktop:com.protomota.inkspring:v1.0 (Inkspring; https://inkspring.ai)"
230 case .linkedin: return ([], "")
231 }
232 let (value, _) = try await transport.request(url, token: account.session.accessToken, method: params == nil ? "GET" : "POST", json: params, headers: headers)
233 let data = value["data"] as? [String: Any] ?? [:]
234 let meta = value["meta"] as? [String: Any] ?? [:]
235 let paging = value["paging"] as? [String: Any] ?? [:]
236 let raw: [[String: Any]]?
237 let next: String
238 switch platform {
239 case .x:
240 guard value["errors"] == nil else { throw WorkspaceError("Incomplete X analytics page.") }
241 raw = value["data"] as? [[String: Any]] ?? (meta["result_count"] as? Int == 0 ? [] : nil)
242 next = meta["next_token"] as? String ?? ""
243 case .instagram:
244 raw = value["data"] as? [[String: Any]]
245 next = paging["next"] is String ? (paging["cursors"] as? [String: Any])?["after"] as? String ?? "" : ""
246 case .tiktok:
247 raw = data["videos"] as? [[String: Any]]
248 next = data["has_more"] as? Bool == true ? (data["cursor"] as? NSNumber)?.stringValue ?? "" : ""
249 default:
250 raw = try (data["children"] as? [[String: Any]])?.map { child in
251 guard child["kind"] as? String == "t3", let post = child["data"] as? [String: Any],
252 (post["author"] as? String)?.caseInsensitiveCompare(account.username) == .orderedSame else {
253 throw WorkspaceError("Incomplete Reddit analytics page.")
254 }
255 return post
256 }
257 next = data["after"] as? String ?? ""
258 }
259 guard let raw, raw.count <= 25, next.utf8.count <= 4000 else { throw WorkspaceError("Incomplete analytics page.") }
260 return (try raw.map { try post($0, platform: platform) }, next)
261 }
262
263 private func post(_ row: [String: Any], platform: SocialPlatform) throws -> [String: Any] {
264 let rawID = platform == .reddit ? row["name"] : row["id"]
265 let id = rawID as? String ?? (rawID as? NSNumber)?.stringValue ?? ""
266 let date: Date?
267 if let text = row["created_at"] as? String ?? row["timestamp"] as? String { date = scheduleDate(text) }
268 else if let seconds = row["create_time"] as? Double ?? row["created_utc"] as? Double, seconds.isFinite,
269 (0...9_000_000_000).contains(seconds) { date = Date(timeIntervalSince1970: seconds) }
270 else { date = nil }
271 guard !id.isEmpty, id.utf8.count <= 100, let date else { throw WorkspaceError("Incomplete analytics post.") }
272 let x = row["public_metrics"] as? [String: Any] ?? [:]
273 var metrics: [String: Any] = [:]
274 metrics["likes"] = AnalyticsReport.integerMetric(x["like_count"] ?? row["like_count"])
275 metrics["replies"] = AnalyticsReport.integerMetric(x["reply_count"] ?? row["comments_count"] ?? row["comment_count"] ?? row["num_comments"])
276 if platform == .x {
277 let shares = [x["retweet_count"] ?? x["repost_count"], x["quote_count"]].compactMap {
278 AnalyticsReport.integerMetric($0)
279 }
280 if !shares.isEmpty { metrics["shares"] = AnalyticsReport.integerMetric(shares.reduce(0, +)) }
281 } else {
282 metrics["shares"] = AnalyticsReport.integerMetric(row["share_count"])
283 }
284 metrics["views"] = AnalyticsReport.integerMetric(x["impression_count"] ?? row["view_count"])
285 if platform == .reddit { metrics["score"] = AnalyticsReport.integerMetric(row["score"], signed: true) }
286 let content = row["text"] as? String ?? row["caption"] as? String ?? row["video_description"] as? String ?? row["title"] as? String ?? ""
287 let address = switch platform {
288 case .x: "https://x.com/i/web/status/" + id
289 case .reddit: "https://www.reddit.com" + (row["permalink"] as? String ?? "")
290 default: row["permalink"] as? String ?? row["share_url"] as? String ?? ""
291 }
292 let hosts = ["x.com", "instagram.com", "www.instagram.com", "tiktok.com", "www.tiktok.com", "www.reddit.com"]
293 let link = URL(string: address).flatMap { $0.scheme == "https" && hosts.contains($0.host ?? "") && $0.user == nil && $0.password == nil ? $0.absoluteString : nil } ?? ""
294 return ["postId": id, "publishedAt": workspaceTimestamp(date), "content": String(content.prefix(5000)), "url": link, "metrics": metrics]
295 }
296}