Branchwell

Graphley / app · graphley.ai / Sources / AnalyticsKit / OpenTalonTodos.swift

Raw 5.4 KB on 089159c793cd9cbff9078de2ee49995b60c6b768
1import Foundation
2
3/// Turns each new App Store review into an OpenTalon to-do (the old `opentalon_todo.py` hook, moved in).
4/// OpenTalon serves MCP over HTTP on 127.0.0.1; its port and token are saved in the Keychain with
5/// `set_source_key` (source "opentalon"). Each to-do has a stable key, sent as OpenTalon's requestKey, so a
6/// review never makes two to-dos, even with the old pull still running. Unsent to-dos wait for the next refresh.
7public struct OpenTalonTodos: Sendable {
8 let session: URLSession
9 public init(session: URLSession = .shared) { self.session = session }
10 public static var isConfigured: Bool { Keychain.has(.openTalonConnection) }
11
12 static let boards = ["6746770199": "Jotley", "6821642700": "PulseCanvas"]
13 static let boardNames = ["Jotley", "PulseCanvas", "OpenTalon", "Textley", "Voxley", "Inkspring", "Graphley", "Glimmer"]
14 static let fallback = "Portfolio Analytics"
15
16 public static func todo(for r: Review) -> ReviewTodo {
17 let board = boards[r.appID] ?? boardNames.first { r.appName.lowercased().contains($0.lowercased()) } ?? fallback
18 let stars = String(repeating: "★", count: r.stars) + String(repeating: "☆", count: max(0, 5 - r.stars))
19 let app = r.appName.components(separatedBy: ":").first ?? r.appName
20 let due = ISO8601DateFormatter.day.date(from: r.firstSeen).flatMap { Calendar.current.date(byAdding: .day, value: 3, to: $0) }.map { DayKey.string($0) }
21 let notes = """
22 \(stars) from \(r.author.isEmpty ? "a customer" : r.author) (\(r.country)), version \(r.version.isEmpty ? "?" : r.version), \(r.date).
23
24 "\(r.title)"
25 \(r.text)
26
27 Review page: \(r.url)
28 Reply in App Store Connect: https://appstoreconnect.apple.com/apps/\(r.appID)/distribution/activity/ios/ratingsResponses
29 """
30 return ReviewTodo(key: "appstore-review-\(r.appID)-\(r.id)", board: board,
31 title: "Reply to the \(r.stars)-star App Store review of \(app): \"\(r.title.prefix(80))\"",
32 notes: notes, priority: r.stars <= 3 ? "High" : "Medium", due: due)
33 }
34
35 /// Sends each to-do; returns the keys created (or already there).
36 public func send(_ todos: [ReviewTodo], source: String = "Graphley") async throws -> [String] {
37 guard !todos.isEmpty else { return [] }
38 guard let raw = Keychain.get(.openTalonConnection),
39 let config = try? JSONSerialization.jsonObject(with: Data(raw.utf8)) as? [String: Any],
40 let token = config["token"] as? String, let port = (config["port"] as? Int) ?? Int(config["port"] as? String ?? "")
41 else { throw AnalyticsError.notSignedIn("OpenTalon (save its connection with set_source_key)") }
42 let boards = try await call(port, token, "list_boards", [:])["boards"] as? [[String: Any]] ?? []
43 let ids = Dictionary(boards.compactMap { b in (b["name"] as? String).map { ($0.lowercased(), b["id"] as? String ?? "") } }, uniquingKeysWith: { a, _ in a })
44 var sent: [String] = []
45 for t in todos {
46 guard let board = ids[t.board.lowercased()] ?? ids[Self.fallback.lowercased()] else { continue }
47 var args: [String: Any] = ["boardId": board, "title": String(t.title.prefix(500)), "requestKey": String(t.key.prefix(200)),
48 "notes": t.notes + "\nSource: \(source), key \(t.key)", "priority": t.priority]
49 if let due = t.due { args["dueDate"] = due }
50 _ = try await call(port, token, "create_task", args)
51 sent.append(t.key)
52 }
53 return sent
54 }
55
56 func call(_ port: Int, _ token: String, _ name: String, _ arguments: [String: Any]) async throws -> [String: Any] {
57 var r = URLRequest(url: URL(string: "http://127.0.0.1:\(port)/mcp")!)
58 r.httpMethod = "POST"; r.timeoutInterval = 30
59 r.setValue("application/json", forHTTPHeaderField: "Content-Type")
60 r.setValue("application/json, text/event-stream", forHTTPHeaderField: "Accept")
61 r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
62 r.httpBody = try JSONSerialization.data(withJSONObject: ["jsonrpc": "2.0", "id": name, "method": "tools/call",
63 "params": ["name": name, "arguments": arguments]])
64 let (data, response) = try await session.data(for: r)
65 let code = (response as? HTTPURLResponse)?.statusCode ?? 0
66 guard code == 200 else { throw AnalyticsError.http(code, "OpenTalon \(name)") }
67 var body = String(decoding: data, as: UTF8.self)
68 if body.hasPrefix("event:") || body.contains("\ndata:") || body.hasPrefix("data:") {
69 body = body.split(separator: "\n").filter { $0.hasPrefix("data:") }.last.map { String($0.dropFirst(5)) } ?? ""
70 }
71 let reply = (try? JSONSerialization.jsonObject(with: Data(body.utf8))) as? [String: Any] ?? [:]
72 if let e = reply["error"] as? [String: Any] { throw AnalyticsError.badResponse("OpenTalon \(name): \(e["message"] ?? "")") }
73 let result = reply["result"] as? [String: Any] ?? [:]
74 if result["isError"] as? Bool == true { throw AnalyticsError.badResponse("OpenTalon \(name)") }
75 return result["structuredContent"] as? [String: Any] ?? [:]
76 }
77}
78
79extension ISO8601DateFormatter {
80 nonisolated(unsafe) static let day: ISO8601DateFormatter = { let f = ISO8601DateFormatter(); f.formatOptions = [.withFullDate]; f.timeZone = .current; return f }()
81}