Graphley / app · graphley.ai / Sources / AnalyticsKit / Socials.swift
| 1 | import Foundation |
| 2 | |
| 3 | /// Follower and subscriber counts, one per account per day, plus YouTube video views. Public pages and |
| 4 | /// APIs where they exist (GitHub, YouTube), the account's own token for X and Instagram (Keychain only). |
| 5 | /// Substack and LinkedIn have no API: an agent or the user records their counts (`record_followers`). |
| 6 | /// Same sources as the old `socials/pull_socials.py`. |
| 7 | public struct Socials: Sendable { |
| 8 | let session: URLSession |
| 9 | public init(session: URLSession = .shared) { self.session = session } |
| 10 | static let browser = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36" |
| 11 | |
| 12 | public struct Result: Sendable { |
| 13 | public var points: [DataPoint] = [] |
| 14 | public var videos: [Video] = [] |
| 15 | public var updated: [String] = [] |
| 16 | public var failed: [String: String] = [:] |
| 17 | } |
| 18 | |
| 19 | public func pull(accounts: [SocialAccount], today: String = DayKey.string(.now)) async -> Result { |
| 20 | var result = Result() |
| 21 | for account in accounts where account.source != "manual" { |
| 22 | do { |
| 23 | switch account.platform { |
| 24 | case .github: |
| 25 | result.points.append(.init(day: today, subject: account.id, metric: .followers, value: try await github(account.handle))) |
| 26 | case .youtube: |
| 27 | let handle = account.handle.hasPrefix("@") ? String(account.handle.dropFirst()) : account.handle |
| 28 | let page = try await text("https://www.youtube.com/@\(handle)") |
| 29 | result.points.append(.init(day: today, subject: account.id, metric: .followers, value: try Self.subscribers(page))) |
| 30 | let (videos, points) = try await youtubeVideos(handle: handle, account: account.id, channelPage: page, today: today) |
| 31 | result.videos += videos; result.points += points |
| 32 | case .x: |
| 33 | result.points.append(.init(day: today, subject: account.id, metric: .followers, value: try await x(account.handle))) |
| 34 | case .instagram: |
| 35 | result.points.append(.init(day: today, subject: account.id, metric: .followers, value: try await instagram(account.handle))) |
| 36 | case .substack, .linkedin: |
| 37 | continue |
| 38 | } |
| 39 | result.updated.append(account.title + " " + account.handle) |
| 40 | } catch { |
| 41 | result.failed[account.title + " " + account.handle] = error.localizedDescription |
| 42 | } |
| 43 | } |
| 44 | return result |
| 45 | } |
| 46 | |
| 47 | func text(_ url: String) async throws -> String { |
| 48 | var r = URLRequest(url: URL(string: url)!) |
| 49 | r.setValue(Self.browser, forHTTPHeaderField: "User-Agent") |
| 50 | r.setValue("en-US,en;q=0.9", forHTTPHeaderField: "Accept-Language") |
| 51 | r.setValue("CONSENT=YES+1", forHTTPHeaderField: "Cookie") |
| 52 | let (data, response) = try await session.data(for: r) |
| 53 | let code = (response as? HTTPURLResponse)?.statusCode ?? 0 |
| 54 | guard code == 200 else { throw AnalyticsError.http(code, url) } |
| 55 | return String(decoding: data, as: UTF8.self) |
| 56 | } |
| 57 | |
| 58 | func github(_ user: String) async throws -> Double { |
| 59 | var r = URLRequest(url: URL(string: "https://api.github.com/users/\(user)")!) |
| 60 | r.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept") |
| 61 | r.setValue("Graphley", forHTTPHeaderField: "User-Agent") |
| 62 | guard let n = try await session.json(r, retries: 2)["followers"] as? Int else { throw AnalyticsError.badResponse("GitHub") } |
| 63 | return Double(n) |
| 64 | } |
| 65 | |
| 66 | func x(_ handle: String) async throws -> Double { |
| 67 | guard let token = Keychain.get(.xBearerToken) else { throw AnalyticsError.notSignedIn("X (save the X API bearer token)") } |
| 68 | let name = handle.hasPrefix("@") ? String(handle.dropFirst()) : handle |
| 69 | var r = URLRequest(url: URL(string: "https://api.x.com/2/users/by/username/\(name)?user.fields=public_metrics")!) |
| 70 | r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") |
| 71 | let json: [String: Any] |
| 72 | do { json = try await session.json(r, retries: 1) } catch AnalyticsError.http(let code, _) { throw AnalyticsError.http(code, "X API") } |
| 73 | guard let metrics = (json["data"] as? [String: Any])?["public_metrics"] as? [String: Any], let n = metrics["followers_count"] as? Int |
| 74 | else { throw AnalyticsError.badResponse("X API") } |
| 75 | return Double(n) |
| 76 | } |
| 77 | |
| 78 | func instagram(_ handle: String) async throws -> Double { |
| 79 | guard let token = Keychain.get(.instagramToken) else { throw AnalyticsError.notSignedIn("Instagram (save the account's Graph API token)") } |
| 80 | var c = URLComponents(string: "https://graph.instagram.com/v23.0/me")! |
| 81 | c.queryItems = [.init(name: "fields", value: "username,followers_count"), .init(name: "access_token", value: token)] |
| 82 | let json: [String: Any] |
| 83 | do { json = try await session.json(URLRequest(url: c.url!), retries: 1) } catch AnalyticsError.http(let code, _) { throw AnalyticsError.http(code, "Instagram API") } |
| 84 | let want = handle.hasPrefix("@") ? String(handle.dropFirst()) : handle |
| 85 | guard (json["username"] as? String)?.lowercased() == want.lowercased() else { throw AnalyticsError.badResponse("Instagram token is for another account") } |
| 86 | guard let n = json["followers_count"] as? Int else { throw AnalyticsError.badResponse("Instagram API") } |
| 87 | return Double(n) |
| 88 | } |
| 89 | |
| 90 | // MARK: YouTube |
| 91 | |
| 92 | static func count(_ text: String) -> Double? { |
| 93 | let t = text.replacingOccurrences(of: ",", with: "").trimmingCharacters(in: .whitespaces) |
| 94 | guard let last = t.last else { return nil } |
| 95 | let scale: Double = ["K": 1_000, "M": 1_000_000, "B": 1_000_000_000][String(last).uppercased()] ?? 1 |
| 96 | return Double(scale == 1 ? t : String(t.dropLast())).map { ($0 * scale).rounded() } |
| 97 | } |
| 98 | |
| 99 | static func subscribers(_ page: String) throws -> Double { |
| 100 | for pattern in [#""content":"([\d.,]+[KMB]?) subscribers?""#, #"([\d.,]+[KMB]?) subscribers?"#] { |
| 101 | if let m = page.range(of: pattern, options: .regularExpression) { |
| 102 | let match = String(page[m]) |
| 103 | if let n = match.range(of: #"[\d.,]+[KMB]?"#, options: .regularExpression).flatMap({ count(String(match[$0])) }) { return n } |
| 104 | } |
| 105 | } |
| 106 | if page.contains("No subscribers") { return 0 } |
| 107 | throw AnalyticsError.badResponse("YouTube channel page (no subscriber count)") |
| 108 | } |
| 109 | |
| 110 | /// The newest five from the public feed (views and likes) and every video, Short and stream on the channel's tabs (views). |
| 111 | func youtubeVideos(handle: String, account: String, channelPage: String, today: String) async throws -> ([Video], [DataPoint]) { |
| 112 | guard let r = channelPage.range(of: #""(?:externalId|channelId)":"(UC[\w-]{22})""#, options: .regularExpression) else { |
| 113 | throw AnalyticsError.badResponse("YouTube channel page (no channel ID)") |
| 114 | } |
| 115 | let channel = String(channelPage[r].dropLast().suffix(24)) |
| 116 | var videos: [String: Video] = [:] |
| 117 | var points: [DataPoint] = [] |
| 118 | let feed = try await text("https://www.youtube.com/feeds/videos.xml?channel_id=\(channel)") |
| 119 | for entry in FeedParser.entries(feed).sorted(by: { $0.published > $1.published }).prefix(5) { |
| 120 | videos[entry.id] = Video(id: entry.id, account: account, title: entry.title, kind: "video", published: entry.published, url: "https://www.youtube.com/watch?v=\(entry.id)") |
| 121 | points.append(.init(day: today, subject: entry.id, metric: .videoViews, value: entry.views)) |
| 122 | points.append(.init(day: today, subject: entry.id, metric: .videoLikes, value: entry.likes)) |
| 123 | } |
| 124 | for (tab, kind) in [("videos", "video"), ("shorts", "short"), ("streams", "live")] { |
| 125 | guard let page = try? await text("https://www.youtube.com/@\(handle)/\(tab)") else { continue } |
| 126 | for v in Self.tabVideos(page, kind: kind) where !points.contains(where: { $0.subject == v.id && $0.metric == .videoViews }) { |
| 127 | if videos[v.id] == nil { |
| 128 | videos[v.id] = Video(id: v.id, account: account, title: v.title, kind: kind, published: nil, |
| 129 | url: (kind == "short" ? "https://www.youtube.com/shorts/" : "https://www.youtube.com/watch?v=") + v.id) |
| 130 | } |
| 131 | points.append(.init(day: today, subject: v.id, metric: .videoViews, value: v.views)) |
| 132 | } |
| 133 | } |
| 134 | return (Array(videos.values), points) |
| 135 | } |
| 136 | |
| 137 | /// Video IDs, titles and view counts from a channel tab's ytInitialData. |
| 138 | static func tabVideos(_ page: String, kind: String) -> [(id: String, title: String, views: Double)] { |
| 139 | guard let start = page.range(of: "var ytInitialData = ") ?? page.range(of: "window[\"ytInitialData\"] = "), |
| 140 | let end = page.range(of: ";</script>", range: start.upperBound..<page.endIndex), |
| 141 | let json = try? JSONSerialization.jsonObject(with: Data(page[start.upperBound..<end.lowerBound].utf8)) else { return [] } |
| 142 | var found: [String: (String, Double)] = [:] |
| 143 | var order: [String] = [] |
| 144 | func strings(_ node: Any) -> [String] { |
| 145 | if let s = node as? String { return [s] } |
| 146 | if let d = node as? [String: Any] { return d.values.flatMap(strings) } |
| 147 | if let a = node as? [Any] { return a.flatMap(strings) } |
| 148 | return [] |
| 149 | } |
| 150 | func firstString(_ node: Any, _ key: String) -> String? { |
| 151 | if let d = node as? [String: Any] { |
| 152 | if let s = d[key] as? String { return s } |
| 153 | for v in d.values { if let s = firstString(v, key) { return s } } |
| 154 | } else if let a = node as? [Any] { |
| 155 | for v in a { if let s = firstString(v, key) { return s } } |
| 156 | } |
| 157 | return nil |
| 158 | } |
| 159 | func views(_ node: Any) -> Double? { |
| 160 | for s in strings(node) { |
| 161 | let t = s.trimmingCharacters(in: .whitespaces) |
| 162 | if t.lowercased() == "no views" { return 0 } |
| 163 | if let r = t.range(of: #"^[\d.,]+[KMBkmb]?\s+views?$"#, options: .regularExpression), r.lowerBound == t.startIndex, |
| 164 | let n = count(String(t.prefix { !$0.isWhitespace })) { return n } |
| 165 | } |
| 166 | return nil |
| 167 | } |
| 168 | func walk(_ node: Any) { |
| 169 | if let d = node as? [String: Any] { |
| 170 | for key in ["videoRenderer", "gridVideoRenderer", "reelItemRenderer", "shortsLockupViewModel", "lockupViewModel"] { |
| 171 | guard let item = d[key] as? [String: Any] else { continue } |
| 172 | let id = item["videoId"] as? String ?? (key == "lockupViewModel" ? item["contentId"] as? String : nil) ?? firstString(item, "videoId") |
| 173 | guard let id, id.count == 11, found[id] == nil, let v = views(item["viewCountText"] ?? item) else { continue } |
| 174 | let title = firstString(item["title"] ?? [:], "simpleText") ?? firstString(item["title"] ?? [:], "content") |
| 175 | ?? firstString(item["headline"] ?? [:], "simpleText") ?? firstString(item["overlayMetadata"] ?? [:], "content") |
| 176 | ?? firstString(item["metadata"] ?? [:], "content") ?? id |
| 177 | found[id] = (title, v); order.append(id) |
| 178 | } |
| 179 | d.values.forEach(walk) |
| 180 | } else if let a = node as? [Any] { a.forEach(walk) } |
| 181 | } |
| 182 | walk(json) |
| 183 | return order.map { ($0, found[$0]!.0, found[$0]!.1) } |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | /// The YouTube channel feed (Atom): video ID, title, published day, views and likes. |
| 188 | final class FeedParser: NSObject, XMLParserDelegate { |
| 189 | struct Entry { var id = "", title = "", published = "", views = 0.0, likes = 0.0 } |
| 190 | private var entries: [Entry] = [] |
| 191 | private var current: Entry? |
| 192 | private var text = "" |
| 193 | |
| 194 | static func entries(_ xml: String) -> [Entry] { |
| 195 | let p = FeedParser() |
| 196 | let parser = XMLParser(data: Data(xml.utf8)); parser.delegate = p; parser.parse() |
| 197 | return p.entries |
| 198 | } |
| 199 | |
| 200 | func parser(_ parser: XMLParser, didStartElement name: String, namespaceURI: String?, qualifiedName: String?, attributes: [String: String] = [:]) { |
| 201 | text = "" |
| 202 | if name == "entry" { current = Entry() } |
| 203 | if name == "media:statistics" { current?.views = Double(attributes["views"] ?? "") ?? 0 } |
| 204 | if name == "media:starRating" { current?.likes = Double(attributes["count"] ?? "") ?? 0 } |
| 205 | } |
| 206 | func parser(_ parser: XMLParser, foundCharacters string: String) { text += string } |
| 207 | func parser(_ parser: XMLParser, didEndElement name: String, namespaceURI: String?, qualifiedName: String?) { |
| 208 | switch name { |
| 209 | case "yt:videoId": current?.id = text |
| 210 | case "title" where current != nil: current?.title = text |
| 211 | case "published": current?.published = String(text.prefix(10)) |
| 212 | case "entry": if let c = current { entries.append(c) }; current = nil |
| 213 | default: break |
| 214 | } |
| 215 | } |
| 216 | } |