Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / ResearchDiscovery.swift
| 1 | import Foundation |
| 2 | |
| 3 | enum ResearchPlatform: String, CaseIterable, Identifiable { |
| 4 | case x, news, instagram, linkedin |
| 5 | var id: Self { self } |
| 6 | var title: String { platformName(rawValue) } |
| 7 | } |
| 8 | |
| 9 | enum ResearchDraft { |
| 10 | static func post(from source: WorkspaceRecord, platform: String, hook: String = "", angle: String = "") -> WorkspaceRecord { |
| 11 | var draft = WorkspaceRecord.new("draft", projectID: source.projectID) |
| 12 | draft["title"] = source.title |
| 13 | draft["platform"] = platform |
| 14 | if platform == "instagram" { draft["format"] = "image" } |
| 15 | let direction = [hook.isEmpty ? "" : "Original hook: " + hook, angle].filter { !$0.isEmpty }.joined(separator: "\n") |
| 16 | draft["brief"] = direction.isEmpty ? "Write an original post inspired by this reference: " + source.title : direction |
| 17 | draft.fields["sourceIds"] = [source.id] |
| 18 | return draft |
| 19 | } |
| 20 | |
| 21 | static func reply(to source: [String: Any], projectID: String) throws -> WorkspaceRecord { |
| 22 | guard let address = source["url"] as? String, let url = XQuoteComposer.postURL(address), |
| 23 | let body = source["text"] as? String, !body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { |
| 24 | throw WorkspaceError("Choose an X post with source text to start a reply.") |
| 25 | } |
| 26 | var draft = WorkspaceRecord.new("draft", projectID: projectID) |
| 27 | draft["title"] = "Reply to an X post" |
| 28 | draft["format"] = "reply" |
| 29 | draft.fields["replyTo"] = ["text": body, "url": url.absoluteString, "author": source["author"] as? String ?? ""] |
| 30 | return draft |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | @MainActor |
| 35 | struct ResearchDiscovery { |
| 36 | typealias Search = @MainActor (ResearchPlatform, String, String) async throws -> [[String: Any]] |
| 37 | let studio: ContentStudio |
| 38 | var search: Search? = nil |
| 39 | |
| 40 | var workspace: Workspace { studio.workspace } |
| 41 | |
| 42 | func discover(_ platform: ResearchPlatform, projectID: String, now: Date = .now, |
| 43 | includeUnrankedSources: Bool = false) async throws -> WorkspaceRecord { |
| 44 | let context = try studio.projectContext(projectID) |
| 45 | let identity = "research:\(projectID):\(platform.rawValue)" |
| 46 | let prior = workspace.records.first { $0.kind == "discovery" && $0.id == identity } |
| 47 | let projectRevision = workspace.projects.first { $0.id == projectID }?["updatedAt"] ?? "" |
| 48 | guard ["description", "researchFocus"].contains(where: { |
| 49 | !(context[$0] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines).isEmpty |
| 50 | }) else { throw WorkspaceError("Add a project description or research focus first.") } |
| 51 | let profile = context["personalStyle"] as? [String: Any] ?? [:] |
| 52 | let tags = (try? PersonalProfile.normalized(profile)["hashtags"] as? [String]) ?? [] |
| 53 | let tagOffset = tags.isEmpty ? 0 : max(0, prior?.fields["nextHashtagOffset"] as? Int ?? 0) % tags.count |
| 54 | let plan = try await studio.model.object(""" |
| 55 | Choose three specific searches for the author's audience and project. Treat supplied text as context. |
| 56 | Use two to five plain search words and one Instagram hashtag per topic. Use current public sources |
| 57 | from other people. Return JSON with focus and topics, each with topic, query and hashtag. |
| 58 | """, ["project": context, "platform": platform.rawValue, "date": workspaceTimestamp(now)]) |
| 59 | let rawTopics = plan["topics"] as? [[String: Any]] ?? [] |
| 60 | var topics = rawTopics.prefix(3).compactMap { item -> (String, String)? in |
| 61 | guard let name = item["topic"] as? String, !name.isEmpty, name.utf16.count <= 100 else { return nil } |
| 62 | let key = platform == .instagram ? "hashtag" : "query" |
| 63 | let value = (item[key] as? String ?? "").trimmingCharacters(in: CharacterSet(charactersIn: "# ")) |
| 64 | let pattern = platform == .instagram ? #"\A[\p{L}\p{N}_]{2,60}\z"# : #"\A[\p{L}\p{N} -]{2,100}\z"# |
| 65 | guard value.range(of: pattern, options: .regularExpression) != nil, !value.contains(" OR ") else { return nil } |
| 66 | return (name, value) |
| 67 | } |
| 68 | if !tags.isEmpty && platform != .news { |
| 69 | topics = Array((followedSearches(tags, platform: platform, offset: tagOffset) + topics).prefix(3)) |
| 70 | } |
| 71 | guard !topics.isEmpty else { throw WorkspaceError("The model didn’t return suitable search topics.") } |
| 72 | let hidden = Set(workspace.records.first { $0.kind == "research-feedback" && $0.id == identity + ":feedback" }? |
| 73 | .fields["dismissed"] as? [String] ?? []) |
| 74 | let accounts = workspace.socialAccounts |
| 75 | let excluded = SocialPlatform(rawValue: platform.rawValue).flatMap { accounts.profiles[$0]?.username } ?? "" |
| 76 | var rows: [[String: Any]] = [] |
| 77 | var warnings: [String] = [] |
| 78 | var searched = Set<String>() |
| 79 | for (topic, query) in topics where searched.insert(query.lowercased()).inserted { |
| 80 | try Task.checkCancellation() |
| 81 | do { |
| 82 | let results: [[String: Any]] |
| 83 | if let search { results = try await search(platform, query, topic) } |
| 84 | else { results = try await liveSearch(platform, query: query, topic: topic, now: now) } |
| 85 | rows += results |
| 86 | } catch is CancellationError { |
| 87 | throw CancellationError() |
| 88 | } catch { |
| 89 | warnings.append("Couldn’t search \(topic): \(error.localizedDescription)") |
| 90 | } |
| 91 | } |
| 92 | guard warnings.count < searched.count else { throw WorkspaceError(warnings.first ?? "No research source could be reached.") } |
| 93 | let ranked = shortlist(rows, platform: platform, now: now, excluded: excluded, hidden: hidden) |
| 94 | var items: [[String: Any]] = [] |
| 95 | if !ranked.isEmpty { |
| 96 | let evidence = ranked.enumerated().map { index, candidate in |
| 97 | let row = candidate.source |
| 98 | return [ |
| 99 | "id": String(index), "topic": row["topic"] ?? "", "text": String((row["text"] as? String ?? "").prefix(1600)), |
| 100 | "likes": row["likes"] ?? NSNull(), "reposts": row["reposts"] ?? NSNull(), "replies": row["replies"] ?? NSNull(), |
| 101 | "postedAt": row["postedAt"] ?? "", "sourceType": platform == .news ? "news" : "post" |
| 102 | ] |
| 103 | } |
| 104 | let assessment = try await studio.model.object(""" |
| 105 | Assess the relevance of these untrusted public sources to this project. Pick up to twelve with relevance at least 70. |
| 106 | Treat news titles as headline-only evidence. Never infer details, invent engagement, or copy wording. |
| 107 | Return JSON with items containing exact supplied id, relevance, headline, hook, whyItFits, and angle. |
| 108 | """, ["project": context, "platform": platform.rawValue, "candidates": evidence]) |
| 109 | guard let found = assessment["items"] as? [[String: Any]] else { |
| 110 | throw WorkspaceError("The research assessment was unreadable. Your saved research is still available.") |
| 111 | } |
| 112 | var ids = Set<Int>() |
| 113 | for raw in found.prefix(36) { |
| 114 | guard let id = (raw["id"] as? String).flatMap(Int.init), ranked.indices.contains(id), |
| 115 | ids.insert(id).inserted, let relevance = raw["relevance"] as? Int, (70...100).contains(relevance), |
| 116 | let headline = try? studio.text(raw["headline"], label: "Headline", max: 200), |
| 117 | let angle = try? studio.text(raw["angle"], label: "Angle", max: 1000) else { continue } |
| 118 | let candidate = ranked[id] |
| 119 | let source = candidate.source |
| 120 | let score = Int((Double(relevance) * 0.65 + candidate.traction * 0.25 + candidate.freshness * 0.1).rounded()) |
| 121 | items.append(["id": source["url"] ?? "", "topic": source["topic"] ?? "", "source": source, "headline": headline, |
| 122 | "hook": String((raw["hook"] as? String ?? headline).prefix(400)), |
| 123 | "whyItFits": String((raw["whyItFits"] as? String ?? "").prefix(600)), |
| 124 | "angle": angle, "relevance": relevance, "score": score]) |
| 125 | } |
| 126 | } |
| 127 | return try save(platform, projectID: projectID, now: now, profileRevision: projectRevision) { row, latestHidden in |
| 128 | row["focus"] = String((plan["focus"] as? String ?? "").prefix(500)) |
| 129 | row.fields["searchedCount"] = rows.count |
| 130 | row.fields["qualifiedCount"] = ranked.count |
| 131 | row.fields["topics"] = topics.map { $0.0 } |
| 132 | row.fields["followedHashtags"] = tags |
| 133 | row.fields["nextHashtagOffset"] = tags.isEmpty || platform == .news |
| 134 | ? 0 : (tagOffset + 3) % tags.count |
| 135 | row.fields["warnings"] = warnings |
| 136 | let visible = items.filter { !latestHidden.contains($0["id"] as? String ?? "") } |
| 137 | row.fields["items"] = includeUnrankedSources && visible.isEmpty |
| 138 | ? sourceItems(ranked.filter { !latestHidden.contains($0.source["url"] as? String ?? "") }) |
| 139 | : diversify(visible) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | func browse(_ platform: ResearchPlatform, projectID: String, topic: String, note: String = "", now: Date = .now) |
| 144 | async throws -> WorkspaceRecord { |
| 145 | guard let project = workspace.projects.first(where: { $0.id == projectID }) else { |
| 146 | throw WorkspaceError("Choose an existing project.") |
| 147 | } |
| 148 | let query = platform == .instagram ? String(topic.filter { $0.isLetter || $0.isNumber }.prefix(60)) : topic |
| 149 | let rows: [[String: Any]] |
| 150 | if let search { rows = try await search(platform, query, topic) } |
| 151 | else { rows = try await liveSearch(platform, query: query, topic: topic, now: now) } |
| 152 | let account = SocialPlatform(rawValue: platform.rawValue) |
| 153 | let excluded = account.flatMap { workspace.socialAccounts.profiles[$0]?.username } ?? "" |
| 154 | return try save(platform, projectID: projectID, now: now, profileRevision: project["updatedAt"]) { row, hidden in |
| 155 | let ranked = shortlist(rows, platform: platform, now: now, excluded: excluded, hidden: hidden) |
| 156 | row["focus"] = note |
| 157 | row.fields["searchedCount"] = rows.count |
| 158 | row.fields["qualifiedCount"] = ranked.count |
| 159 | row.fields["topics"] = [topic] |
| 160 | row.fields["warnings"] = [] |
| 161 | row.fields["items"] = sourceItems(ranked) |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | private func sourceItems(_ ranked: [Candidate]) -> [[String: Any]] { |
| 166 | ranked.prefix(12).map { |
| 167 | ["id": $0.source["url"] ?? "", "topic": $0.source["topic"] ?? "", |
| 168 | "source": $0.source, "headline": $0.source["title"] ?? ""] |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | private func save(_ platform: ResearchPlatform, projectID: String, now: Date, profileRevision: String, |
| 173 | update: (inout WorkspaceRecord, Set<String>) -> Void) throws -> WorkspaceRecord { |
| 174 | try Task.checkCancellation() |
| 175 | let identity = "research:\(projectID):\(platform.rawValue)" |
| 176 | return try studio.persist { |
| 177 | let hidden = Set(workspace.records.first { $0.kind == "research-feedback" && $0.id == identity + ":feedback" }? |
| 178 | .fields["dismissed"] as? [String] ?? []) |
| 179 | var row = workspace.records.first { $0.kind == "discovery" && $0.id == identity } |
| 180 | ?? WorkspaceRecord.new("discovery", projectID: projectID) |
| 181 | if let latest = scheduleDate(row["searchedAt"]), latest > now { return row } |
| 182 | row["id"] = identity |
| 183 | row["title"] = platform.title |
| 184 | row["platform"] = platform.rawValue |
| 185 | row["profileUpdatedAt"] = profileRevision |
| 186 | row["searchedAt"] = workspaceTimestamp(now) |
| 187 | update(&row, hidden) |
| 188 | return try workspace.save(row) |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | func refreshIdeas(projectID: String, withResearch: Bool, automatic: Bool = false) async throws -> ContentStudio.RefreshResult { |
| 193 | var warnings: [String] = [] |
| 194 | if withResearch { |
| 195 | let profile = workspace.settings["personalProfile"] as? [String: Any] ?? [:] |
| 196 | let sources = (try? PersonalProfile.normalized(profile)["researchSources"] as? [String]) ?? ["x", "news"] |
| 197 | for platform in sources.compactMap(ResearchPlatform.init(rawValue:)) { |
| 198 | try Task.checkCancellation() |
| 199 | if automatic { |
| 200 | try workspace.reload() |
| 201 | let target = IdeaQueuePlan.target(workspace.settings["ideaQueueTarget"]) |
| 202 | let open = workspace.records.filter { |
| 203 | $0.isPendingPostIdea && $0.projectID == projectID |
| 204 | }.count |
| 205 | if workspace.settings["ideaQueueAutomatic"] as? Bool != true || open >= target { break } |
| 206 | } |
| 207 | let prior = workspace.records.first { |
| 208 | $0.kind == "discovery" && $0.projectID == projectID && $0["platform"] == platform.rawValue |
| 209 | } |
| 210 | let revision = workspace.projects.first { $0.id == projectID }?["updatedAt"] |
| 211 | if let prior, let date = scheduleDate(prior["searchedAt"]), Date.now.timeIntervalSince(date) < 3600, |
| 212 | prior["profileUpdatedAt"].isEmpty || prior["profileUpdatedAt"] == revision { continue } |
| 213 | let hasXConnection = platform == .x && (ProviderKey.x.isSaved || (try? workspace.socialAccounts.savedAccount(.x)) != nil) |
| 214 | if search == nil && platform != .news && !ProviderKey.apify.isSaved && !hasXConnection { |
| 215 | warnings.append(platform == .x ? "Connect X or add an Apify key for X research." : "\(platform.title) research needs an Apify key.") |
| 216 | continue |
| 217 | } |
| 218 | do { _ = try await discover(platform, projectID: projectID) } |
| 219 | catch { warnings.append(error.localizedDescription) } |
| 220 | } |
| 221 | } |
| 222 | return try await studio.refresh(projectID: projectID, warnings: warnings, automatic: automatic) |
| 223 | } |
| 224 | |
| 225 | private func followedSearches(_ tags: [String], platform: ResearchPlatform, offset: Int) -> [(String, String)] { |
| 226 | if platform == .x { |
| 227 | return stride(from: 0, to: tags.count, by: 10).map { start in |
| 228 | let group = tags.dropFirst(start).prefix(10).map { "#" + $0 } |
| 229 | return (group.joined(separator: ", "), "(" + group.joined(separator: " OR ") + ")") |
| 230 | } |
| 231 | } |
| 232 | return (0..<min(3, tags.count)).map { index in |
| 233 | let tag = tags[(offset + index) % tags.count] |
| 234 | return ("#" + tag, platform == .instagram ? tag : "#" + tag) |
| 235 | } |
| 236 | } |
| 237 | |
| 238 | private struct Candidate { |
| 239 | let source: [String: Any] |
| 240 | let traction: Double |
| 241 | let freshness: Double |
| 242 | var rank: Double { traction + freshness * 0.3 } |
| 243 | } |
| 244 | |
| 245 | private func shortlist(_ rows: [[String: Any]], platform: ResearchPlatform, now: Date, |
| 246 | excluded: String, hidden: Set<String>) -> [Candidate] { |
| 247 | var urls = Set<String>() |
| 248 | var bodies = Set<String>() |
| 249 | let ownName = authorKey(excluded) |
| 250 | let minimumLength = platform == .news ? 10 : 40 |
| 251 | let qualified: [Candidate] = rows.compactMap { item in |
| 252 | guard let url = item["url"] as? String, !hidden.contains(url), |
| 253 | let body = item["text"] as? String, |
| 254 | let date = (item["postedAt"] as? String).flatMap(scheduleDate), |
| 255 | item["isReply"] as? Bool != true, item["isRepost"] as? Bool != true, |
| 256 | ownName.isEmpty || authorKey(item["author"] as? String ?? "") != ownName else { return nil } |
| 257 | let age = now.timeIntervalSince(date) |
| 258 | guard (-300...604_800).contains(age), body.trimmingCharacters(in: .whitespacesAndNewlines).count >= minimumLength else { |
| 259 | return nil |
| 260 | } |
| 261 | let normalized = body.lowercased() |
| 262 | .replacingOccurrences(of: #"https?://\S+"#, with: "", options: .regularExpression) |
| 263 | .split(whereSeparator: \.isWhitespace).joined(separator: " ") |
| 264 | let likes = Double(Self.metric(item["likes"]) ?? 0) |
| 265 | let reposts = Double(Self.metric(item["reposts"]) ?? 0) |
| 266 | let replies = Double(Self.metric(item["replies"]) ?? 0) |
| 267 | let interactions = likes + 2 * (reposts + replies) |
| 268 | guard platform == .news || interactions >= 10 else { return nil } |
| 269 | guard !normalized.isEmpty, !urls.contains(url), bodies.insert(normalized).inserted else { return nil } |
| 270 | urls.insert(url) |
| 271 | let traction = platform == .news ? 0 : min(100, log1p(interactions) * 13) |
| 272 | let freshness = 100 / (1 + max(1, age / 3600) / 48) |
| 273 | return Candidate(source: item, traction: traction, freshness: freshness) |
| 274 | } |
| 275 | return Array(qualified.sorted { $0.rank > $1.rank }.prefix(36)) |
| 276 | } |
| 277 | |
| 278 | private func diversify(_ items: [[String: Any]]) -> [[String: Any]] { |
| 279 | var authors: [String: Int] = [:] |
| 280 | var topics: [String: Int] = [:] |
| 281 | let ordered = items.sorted { ($0["score"] as? Int ?? 0) > ($1["score"] as? Int ?? 0) } |
| 282 | return Array(ordered.filter { item in |
| 283 | let source = item["source"] as? [String: Any] |
| 284 | let author = authorKey(source?["author"] as? String ?? "") |
| 285 | let topic = item["topic"] as? String ?? "" |
| 286 | guard authors[author, default: 0] < 2, topics[topic, default: 0] < 5 else { return false } |
| 287 | authors[author, default: 0] += 1 |
| 288 | topics[topic, default: 0] += 1 |
| 289 | return true |
| 290 | }.prefix(12)) |
| 291 | } |
| 292 | |
| 293 | private func authorKey(_ author: String) -> String { |
| 294 | author.trimmingCharacters(in: .whitespacesAndNewlines.union(CharacterSet(charactersIn: "@"))).lowercased() |
| 295 | } |
| 296 | |
| 297 | private static func metric(_ raw: Any?) -> Int? { |
| 298 | let count = raw as? Int ?? (raw as? String).flatMap(Int.init) |
| 299 | return count.flatMap { $0 >= 0 ? $0 : nil } |
| 300 | } |
| 301 | |
| 302 | func liveSearch(_ platform: ResearchPlatform, query: String, topic: String, days: Int = 7, now: Date = .now, |
| 303 | preferApify: Bool = false) async throws -> [[String: Any]] { |
| 304 | if platform == .news { return try await NewsSearch.fetch(query: query, topic: topic, days: days) } |
| 305 | let transport = SocialTransport() |
| 306 | if platform == .x, !preferApify, let token = try await workspace.socialAccounts.xReadToken() { |
| 307 | let url = URL(string: "https://api.x.com/2/tweets/search/recent")!.appending(queryItems: [ |
| 308 | .init(name: "query", value: query + " -is:retweet -is:reply"), .init(name: "sort_order", value: "relevancy"), |
| 309 | .init(name: "max_results", value: "20"), .init(name: "expansions", value: "author_id"), |
| 310 | .init(name: "tweet.fields", value: "author_id,public_metrics,created_at,note_tweet,referenced_tweets"), |
| 311 | .init(name: "user.fields", value: "username,public_metrics") |
| 312 | ]) |
| 313 | let (value, _) = try await transport.request(url, token: token) |
| 314 | if value["data"] == nil, (value["meta"] as? [String: Any])?["result_count"] as? Int != 0 { |
| 315 | throw WorkspaceError("X returned an unreadable search result.") |
| 316 | } |
| 317 | let users = ((value["includes"] as? [String: Any])?["users"] as? [[String: Any]]) ?? [] |
| 318 | return (value["data"] as? [[String: Any]] ?? []).prefix(20).compactMap { row in |
| 319 | guard let id = row["id"] as? String, id.range(of: #"\A[0-9]{1,25}\z"#, options: .regularExpression) != nil else { return nil } |
| 320 | let body = (row["note_tweet"] as? [String: Any])?["text"] as? String ?? row["text"] as? String |
| 321 | let author = users.first { $0["id"] as? String == row["author_id"] as? String }?["username"] |
| 322 | let metrics = row["public_metrics"] as? [String: Any] ?? [:] |
| 323 | let refs = row["referenced_tweets"] as? [[String: Any]] ?? [] |
| 324 | return item(body, url: "https://x.com/i/web/status/" + id, author: author, origin: "X · Direct API", |
| 325 | date: row["created_at"], topic: topic, likes: metrics["like_count"], shares: metrics["retweet_count"], |
| 326 | replies: metrics["reply_count"], reply: refs.contains { $0["type"] as? String == "replied_to" }, |
| 327 | repost: refs.contains { $0["type"] as? String == "retweeted" }) |
| 328 | } |
| 329 | } |
| 330 | let actor: String |
| 331 | let payload: [String: Any] |
| 332 | switch platform { |
| 333 | case .x: |
| 334 | actor = "apidojo~twitter-scraper-lite" |
| 335 | let since = String(workspaceTimestamp(now.addingTimeInterval(-Double(days) * 86_400)).prefix(10)) |
| 336 | payload = ["maxItems": 20, "sort": "Top", "searchTerms": [query + " since:" + since + " -filter:retweets -filter:replies"]] |
| 337 | case .instagram: |
| 338 | actor = "apify~instagram-hashtag-scraper" |
| 339 | payload = ["hashtags": [query], "resultsType": "posts", "resultsLimit": 20] |
| 340 | case .linkedin: |
| 341 | actor = "harvestapi~linkedin-post-search" |
| 342 | payload = ["searchQueries": [query], "maxPosts": 20, "postedLimit": "week", "sortBy": "relevance", |
| 343 | "scrapeComments": false, "scrapeReactions": false] |
| 344 | case .news: |
| 345 | return [] |
| 346 | } |
| 347 | let url = URL(string: "https://api.apify.com/v2/acts/\(actor)/run-sync-get-dataset-items?timeout=120")! |
| 348 | let (result, _) = try await transport.request(url, token: ProviderKey.apify.read(), method: "POST", |
| 349 | json: payload, timeout: 130, acceptsArray: true) |
| 350 | guard let rows = result["items"] as? [[String: Any]], !rows.contains(where: { $0["error"] != nil }) else { |
| 351 | throw WorkspaceError("Apify couldn’t return search posts. Check the actor and its API access.") |
| 352 | } |
| 353 | return rows.prefix(20).compactMap { row in |
| 354 | let engagement = row["engagement"] as? [String: Any] ?? [:] |
| 355 | let author = row["author"] as? [String: Any] ?? [:] |
| 356 | let date = row["postedAt"] as? [String: Any] ?? [:] |
| 357 | let fallback: String? |
| 358 | if platform == .x, let id = row["id"] as? String { fallback = "https://x.com/i/web/status/" + id } |
| 359 | else if platform == .instagram, let id = row["shortCode"] as? String { fallback = "https://www.instagram.com/p/" + id + "/" } |
| 360 | else { fallback = nil } |
| 361 | guard let raw = row["linkedinUrl"] as? String ?? row["url"] as? String ?? fallback, |
| 362 | let url = Self.canonical(raw, platform: platform) else { return nil } |
| 363 | return item(row["content"] ?? row["fullText"] ?? row["text"] ?? row["caption"], url: url, |
| 364 | author: (platform == .x ? author["userName"] : author["name"]) ?? author["publicIdentifier"] ?? row["ownerUsername"], |
| 365 | origin: platform.title + " · Apify", |
| 366 | date: date["date"] ?? date["timestamp"] ?? row["createdAt"] ?? row["timestamp"] ?? row["takenAt"], |
| 367 | topic: topic, likes: engagement["likes"] ?? row["likeCount"] ?? row["likesCount"], |
| 368 | shares: engagement["shares"] ?? row["retweetCount"], replies: engagement["comments"] ?? row["replyCount"] ?? row["commentsCount"], |
| 369 | reply: row["isReply"] as? Bool == true || platform == .linkedin && (row["type"] as? String).map { $0 != "post" } == true, |
| 370 | repost: row["isRetweet"] as? Bool == true || row["isRepost"] as? Bool == true) |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | private func item(_ raw: Any?, url: String, author: Any?, origin: String, date: Any?, topic: String, |
| 375 | likes: Any?, shares: Any?, replies: Any?, reply: Bool, repost: Bool) -> [String: Any]? { |
| 376 | guard let raw = raw as? String, !raw.isEmpty, let time = Self.parseDate(date) else { return nil } |
| 377 | var fields: [String: Any] = ["title": String(raw.prefix(100)), "text": String(raw.prefix(7500)), "url": url, |
| 378 | "author": String((author as? String ?? "").prefix(150)), "origin": origin, "topic": topic, |
| 379 | "postedAt": workspaceTimestamp(time), "isReply": reply, "isRepost": repost] |
| 380 | fields["likes"] = Self.metric(likes) |
| 381 | fields["reposts"] = Self.metric(shares) |
| 382 | fields["replies"] = Self.metric(replies) |
| 383 | return fields |
| 384 | } |
| 385 | |
| 386 | private static func parseDate(_ input: Any?) -> Date? { |
| 387 | if let number = input as? Double, number.isFinite { return Date(timeIntervalSince1970: number > 100_000_000_000 ? number / 1000 : number) } |
| 388 | guard let text = input as? String else { return nil } |
| 389 | if let date = scheduleDate(text) { return date } |
| 390 | let parser = DateFormatter() |
| 391 | parser.locale = Locale(identifier: "en_US_POSIX") |
| 392 | for format in ["EEE MMM dd HH:mm:ss Z yyyy", "EEE, dd MMM yyyy HH:mm:ss z"] { |
| 393 | parser.dateFormat = format |
| 394 | if let date = parser.date(from: text) { return date } |
| 395 | } |
| 396 | return nil |
| 397 | } |
| 398 | |
| 399 | private static func canonical(_ value: String, platform: ResearchPlatform) -> String? { |
| 400 | guard value.utf8.count <= 3000, let url = URL(string: value), url.scheme == "https", |
| 401 | url.user == nil, url.password == nil, url.port == nil, let host = url.host()?.lowercased() else { return nil } |
| 402 | let parts = url.path.split(separator: "/").map(String.init) |
| 403 | switch platform { |
| 404 | case .x: |
| 405 | guard ["x.com", "www.x.com", "twitter.com", "www.twitter.com", "mobile.twitter.com"].contains(host), |
| 406 | parts.dropLast().last == "status", let id = parts.last, |
| 407 | id.range(of: #"\A[0-9]{1,25}\z"#, options: .regularExpression) != nil else { return nil } |
| 408 | return "https://x.com/i/web/status/" + id |
| 409 | case .instagram: |
| 410 | guard ["instagram.com", "www.instagram.com"].contains(host), parts.count == 2, ["p", "reel", "tv"].contains(parts[0]), |
| 411 | parts[1].range(of: #"\A[A-Za-z0-9_-]{1,100}\z"#, options: .regularExpression) != nil else { return nil } |
| 412 | return "https://www.instagram.com/p/" + parts[1] + "/" |
| 413 | case .linkedin: |
| 414 | guard ["linkedin.com", "www.linkedin.com"].contains(host), |
| 415 | url.path.range(of: #"\A/(?:posts/[^/]+|feed/update/urn:li:(?:activity|share|ugcPost):[0-9]+)/?\z"#, |
| 416 | options: .regularExpression) != nil else { return nil } |
| 417 | return "https://www.linkedin.com" + url.path |
| 418 | case .news: return nil |
| 419 | } |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | private final class NewsSearch: NSObject, XMLParserDelegate { |
| 424 | var items: [[String: String]] = [] |
| 425 | private var item: [String: String]? |
| 426 | private var field: String? |
| 427 | private var root = false |
| 428 | |
| 429 | @MainActor |
| 430 | static func fetch(query: String, topic: String, days: Int) async throws -> [[String: Any]] { |
| 431 | let url = URL(string: "https://news.google.com/rss/search")!.appending(queryItems: [ |
| 432 | .init(name: "q", value: query + " when:\(days)d"), .init(name: "hl", value: "en-US"), .init(name: "gl", value: "US"), .init(name: "ceid", value: "US:en") |
| 433 | ]) |
| 434 | let config = URLSessionConfiguration.ephemeral |
| 435 | config.timeoutIntervalForResource = 20 |
| 436 | let session = URLSession(configuration: config, delegate: NoHTTPRedirects(), delegateQueue: nil) |
| 437 | defer { session.invalidateAndCancel() } |
| 438 | let (bytes, response) = try await session.bytes(from: url) |
| 439 | guard let http = response as? HTTPURLResponse, http.statusCode == 200, response.expectedContentLength <= 2_097_152 else { |
| 440 | throw WorkspaceError("Google News returned an unavailable feed.") |
| 441 | } |
| 442 | var data = Data() |
| 443 | for try await byte in bytes { |
| 444 | guard data.count < 2_097_152 else { throw WorkspaceError("The news feed is too large.") } |
| 445 | data.append(byte) |
| 446 | } |
| 447 | let xml = String(decoding: data, as: UTF8.self) |
| 448 | guard xml.range(of: #"<!DOCTYPE|<!ENTITY"#, options: [.regularExpression, .caseInsensitive]) == nil else { |
| 449 | throw WorkspaceError("The news feed uses unsupported XML.") |
| 450 | } |
| 451 | let reader = NewsSearch() |
| 452 | let parser = XMLParser(data: data) |
| 453 | parser.delegate = reader |
| 454 | parser.shouldResolveExternalEntities = false |
| 455 | guard parser.parse(), reader.root else { throw WorkspaceError("The news feed was unreadable.") } |
| 456 | let parserDate = DateFormatter() |
| 457 | parserDate.locale = Locale(identifier: "en_US_POSIX") |
| 458 | parserDate.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z" |
| 459 | return reader.items.prefix(20).compactMap { item in |
| 460 | guard let raw = item["link"], let url = URL(string: raw), url.scheme == "https", url.host == "news.google.com", |
| 461 | url.user == nil, url.password == nil, url.path.hasPrefix("/rss/articles/"), |
| 462 | let title = item["title"]?.trimmingCharacters(in: .whitespacesAndNewlines), |
| 463 | let date = parserDate.date(from: item["pubDate"] ?? "") else { return nil } |
| 464 | let source = item["source"]?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" |
| 465 | let suffix = " - " + source |
| 466 | let headline = !source.isEmpty && title.hasSuffix(suffix) ? String(title.dropLast(suffix.count)) : title |
| 467 | return ["title": String(headline.prefix(500)), "text": String(headline.prefix(500)), "url": url.absoluteString, |
| 468 | "author": String(source.prefix(200)), "origin": "News · Google News RSS", "topic": topic, |
| 469 | "sourceType": "news", "postedAt": workspaceTimestamp(date)] |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | func parser(_ parser: XMLParser, didStartElement name: String, namespaceURI: String?, qualifiedName: String?, |
| 474 | attributes: [String: String]) { |
| 475 | if name == "rss" { root = true } |
| 476 | if name == "item", items.count < 50 { item = [:] } |
| 477 | if item != nil, ["title", "link", "source", "pubDate"].contains(name) { field = name } |
| 478 | } |
| 479 | |
| 480 | func parser(_ parser: XMLParser, foundCharacters text: String) { |
| 481 | if let field, (item?[field]?.utf8.count ?? 0) < 6000 { item?[field, default: ""] += String(text.prefix(6000)) } |
| 482 | } |
| 483 | |
| 484 | func parser(_ parser: XMLParser, didEndElement name: String, namespaceURI: String?, qualifiedName: String?) { |
| 485 | if name == field { field = nil } |
| 486 | if name == "item", let item { items.append(item); self.item = nil; field = nil } |
| 487 | } |
| 488 | } |