import Foundation /// Follower and subscriber counts, one per account per day, plus YouTube video views. Public pages and /// APIs where they exist (GitHub, YouTube), the account's own token for X and Instagram (Keychain only). /// Substack and LinkedIn have no API: an agent or the user records their counts (`record_followers`). /// Same sources as the old `socials/pull_socials.py`. public struct Socials: Sendable { let session: URLSession public init(session: URLSession = .shared) { self.session = session } 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" public struct Result: Sendable { public var points: [DataPoint] = [] public var videos: [Video] = [] public var updated: [String] = [] public var failed: [String: String] = [:] } public func pull(accounts: [SocialAccount], today: String = DayKey.string(.now)) async -> Result { var result = Result() for account in accounts where account.source != "manual" { do { switch account.platform { case .github: result.points.append(.init(day: today, subject: account.id, metric: .followers, value: try await github(account.handle))) case .youtube: let handle = account.handle.hasPrefix("@") ? String(account.handle.dropFirst()) : account.handle let page = try await text("https://www.youtube.com/@\(handle)") result.points.append(.init(day: today, subject: account.id, metric: .followers, value: try Self.subscribers(page))) let (videos, points) = try await youtubeVideos(handle: handle, account: account.id, channelPage: page, today: today) result.videos += videos; result.points += points case .x: result.points.append(.init(day: today, subject: account.id, metric: .followers, value: try await x(account.handle))) case .instagram: result.points.append(.init(day: today, subject: account.id, metric: .followers, value: try await instagram(account.handle))) case .substack, .linkedin: continue } result.updated.append(account.title + " " + account.handle) } catch { result.failed[account.title + " " + account.handle] = error.localizedDescription } } return result } func text(_ url: String) async throws -> String { var r = URLRequest(url: URL(string: url)!) r.setValue(Self.browser, forHTTPHeaderField: "User-Agent") r.setValue("en-US,en;q=0.9", forHTTPHeaderField: "Accept-Language") r.setValue("CONSENT=YES+1", forHTTPHeaderField: "Cookie") let (data, response) = try await session.data(for: r) let code = (response as? HTTPURLResponse)?.statusCode ?? 0 guard code == 200 else { throw AnalyticsError.http(code, url) } return String(decoding: data, as: UTF8.self) } func github(_ user: String) async throws -> Double { var r = URLRequest(url: URL(string: "https://api.github.com/users/\(user)")!) r.setValue("application/vnd.github+json", forHTTPHeaderField: "Accept") r.setValue("Graphley", forHTTPHeaderField: "User-Agent") guard let n = try await session.json(r, retries: 2)["followers"] as? Int else { throw AnalyticsError.badResponse("GitHub") } return Double(n) } func x(_ handle: String) async throws -> Double { guard let token = Keychain.get(.xBearerToken) else { throw AnalyticsError.notSignedIn("X (save the X API bearer token)") } let name = handle.hasPrefix("@") ? String(handle.dropFirst()) : handle var r = URLRequest(url: URL(string: "https://api.x.com/2/users/by/username/\(name)?user.fields=public_metrics")!) r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") let json: [String: Any] do { json = try await session.json(r, retries: 1) } catch AnalyticsError.http(let code, _) { throw AnalyticsError.http(code, "X API") } guard let metrics = (json["data"] as? [String: Any])?["public_metrics"] as? [String: Any], let n = metrics["followers_count"] as? Int else { throw AnalyticsError.badResponse("X API") } return Double(n) } func instagram(_ handle: String) async throws -> Double { guard let token = Keychain.get(.instagramToken) else { throw AnalyticsError.notSignedIn("Instagram (save the account's Graph API token)") } var c = URLComponents(string: "https://graph.instagram.com/v23.0/me")! c.queryItems = [.init(name: "fields", value: "username,followers_count"), .init(name: "access_token", value: token)] let json: [String: Any] do { json = try await session.json(URLRequest(url: c.url!), retries: 1) } catch AnalyticsError.http(let code, _) { throw AnalyticsError.http(code, "Instagram API") } let want = handle.hasPrefix("@") ? String(handle.dropFirst()) : handle guard (json["username"] as? String)?.lowercased() == want.lowercased() else { throw AnalyticsError.badResponse("Instagram token is for another account") } guard let n = json["followers_count"] as? Int else { throw AnalyticsError.badResponse("Instagram API") } return Double(n) } // MARK: YouTube static func count(_ text: String) -> Double? { let t = text.replacingOccurrences(of: ",", with: "").trimmingCharacters(in: .whitespaces) guard let last = t.last else { return nil } let scale: Double = ["K": 1_000, "M": 1_000_000, "B": 1_000_000_000][String(last).uppercased()] ?? 1 return Double(scale == 1 ? t : String(t.dropLast())).map { ($0 * scale).rounded() } } static func subscribers(_ page: String) throws -> Double { for pattern in [#""content":"([\d.,]+[KMB]?) subscribers?""#, #"([\d.,]+[KMB]?) subscribers?"#] { if let m = page.range(of: pattern, options: .regularExpression) { let match = String(page[m]) if let n = match.range(of: #"[\d.,]+[KMB]?"#, options: .regularExpression).flatMap({ count(String(match[$0])) }) { return n } } } if page.contains("No subscribers") { return 0 } throw AnalyticsError.badResponse("YouTube channel page (no subscriber count)") } /// The newest five from the public feed (views and likes) and every video, Short and stream on the channel's tabs (views). func youtubeVideos(handle: String, account: String, channelPage: String, today: String) async throws -> ([Video], [DataPoint]) { guard let r = channelPage.range(of: #""(?:externalId|channelId)":"(UC[\w-]{22})""#, options: .regularExpression) else { throw AnalyticsError.badResponse("YouTube channel page (no channel ID)") } let channel = String(channelPage[r].dropLast().suffix(24)) var videos: [String: Video] = [:] var points: [DataPoint] = [] let feed = try await text("https://www.youtube.com/feeds/videos.xml?channel_id=\(channel)") for entry in FeedParser.entries(feed).sorted(by: { $0.published > $1.published }).prefix(5) { 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)") points.append(.init(day: today, subject: entry.id, metric: .videoViews, value: entry.views)) points.append(.init(day: today, subject: entry.id, metric: .videoLikes, value: entry.likes)) } for (tab, kind) in [("videos", "video"), ("shorts", "short"), ("streams", "live")] { guard let page = try? await text("https://www.youtube.com/@\(handle)/\(tab)") else { continue } for v in Self.tabVideos(page, kind: kind) where !points.contains(where: { $0.subject == v.id && $0.metric == .videoViews }) { if videos[v.id] == nil { videos[v.id] = Video(id: v.id, account: account, title: v.title, kind: kind, published: nil, url: (kind == "short" ? "https://www.youtube.com/shorts/" : "https://www.youtube.com/watch?v=") + v.id) } points.append(.init(day: today, subject: v.id, metric: .videoViews, value: v.views)) } } return (Array(videos.values), points) } /// Video IDs, titles and view counts from a channel tab's ytInitialData. static func tabVideos(_ page: String, kind: String) -> [(id: String, title: String, views: Double)] { guard let start = page.range(of: "var ytInitialData = ") ?? page.range(of: "window[\"ytInitialData\"] = "), let end = page.range(of: ";", range: start.upperBound.. [String] { if let s = node as? String { return [s] } if let d = node as? [String: Any] { return d.values.flatMap(strings) } if let a = node as? [Any] { return a.flatMap(strings) } return [] } func firstString(_ node: Any, _ key: String) -> String? { if let d = node as? [String: Any] { if let s = d[key] as? String { return s } for v in d.values { if let s = firstString(v, key) { return s } } } else if let a = node as? [Any] { for v in a { if let s = firstString(v, key) { return s } } } return nil } func views(_ node: Any) -> Double? { for s in strings(node) { let t = s.trimmingCharacters(in: .whitespaces) if t.lowercased() == "no views" { return 0 } if let r = t.range(of: #"^[\d.,]+[KMBkmb]?\s+views?$"#, options: .regularExpression), r.lowerBound == t.startIndex, let n = count(String(t.prefix { !$0.isWhitespace })) { return n } } return nil } func walk(_ node: Any) { if let d = node as? [String: Any] { for key in ["videoRenderer", "gridVideoRenderer", "reelItemRenderer", "shortsLockupViewModel", "lockupViewModel"] { guard let item = d[key] as? [String: Any] else { continue } let id = item["videoId"] as? String ?? (key == "lockupViewModel" ? item["contentId"] as? String : nil) ?? firstString(item, "videoId") guard let id, id.count == 11, found[id] == nil, let v = views(item["viewCountText"] ?? item) else { continue } let title = firstString(item["title"] ?? [:], "simpleText") ?? firstString(item["title"] ?? [:], "content") ?? firstString(item["headline"] ?? [:], "simpleText") ?? firstString(item["overlayMetadata"] ?? [:], "content") ?? firstString(item["metadata"] ?? [:], "content") ?? id found[id] = (title, v); order.append(id) } d.values.forEach(walk) } else if let a = node as? [Any] { a.forEach(walk) } } walk(json) return order.map { ($0, found[$0]!.0, found[$0]!.1) } } } /// The YouTube channel feed (Atom): video ID, title, published day, views and likes. final class FeedParser: NSObject, XMLParserDelegate { struct Entry { var id = "", title = "", published = "", views = 0.0, likes = 0.0 } private var entries: [Entry] = [] private var current: Entry? private var text = "" static func entries(_ xml: String) -> [Entry] { let p = FeedParser() let parser = XMLParser(data: Data(xml.utf8)); parser.delegate = p; parser.parse() return p.entries } func parser(_ parser: XMLParser, didStartElement name: String, namespaceURI: String?, qualifiedName: String?, attributes: [String: String] = [:]) { text = "" if name == "entry" { current = Entry() } if name == "media:statistics" { current?.views = Double(attributes["views"] ?? "") ?? 0 } if name == "media:starRating" { current?.likes = Double(attributes["count"] ?? "") ?? 0 } } func parser(_ parser: XMLParser, foundCharacters string: String) { text += string } func parser(_ parser: XMLParser, didEndElement name: String, namespaceURI: String?, qualifiedName: String?) { switch name { case "yt:videoId": current?.id = text case "title" where current != nil: current?.title = text case "published": current?.published = String(text.prefix(10)) case "entry": if let c = current { entries.append(c) }; current = nil default: break } } }