import Foundation /// Turns each new App Store review into an OpenTalon to-do (the old `opentalon_todo.py` hook, moved in). /// OpenTalon serves MCP over HTTP on 127.0.0.1; its port and token are saved in the Keychain with /// `set_source_key` (source "opentalon"). Each to-do has a stable key, sent as OpenTalon's requestKey, so a /// review never makes two to-dos, even with the old pull still running. Unsent to-dos wait for the next refresh. public struct OpenTalonTodos: Sendable { let session: URLSession public init(session: URLSession = .shared) { self.session = session } public static var isConfigured: Bool { Keychain.has(.openTalonConnection) } static let boards = ["6746770199": "Jotley", "6821642700": "PulseCanvas"] static let boardNames = ["Jotley", "PulseCanvas", "OpenTalon", "Textley", "Voxley", "Inkspring", "Graphley", "Glimmer"] static let fallback = "Portfolio Analytics" public static func todo(for r: Review) -> ReviewTodo { let board = boards[r.appID] ?? boardNames.first { r.appName.lowercased().contains($0.lowercased()) } ?? fallback let stars = String(repeating: "★", count: r.stars) + String(repeating: "☆", count: max(0, 5 - r.stars)) let app = r.appName.components(separatedBy: ":").first ?? r.appName let due = ISO8601DateFormatter.day.date(from: r.firstSeen).flatMap { Calendar.current.date(byAdding: .day, value: 3, to: $0) }.map { DayKey.string($0) } let notes = """ \(stars) from \(r.author.isEmpty ? "a customer" : r.author) (\(r.country)), version \(r.version.isEmpty ? "?" : r.version), \(r.date). "\(r.title)" \(r.text) Review page: \(r.url) Reply in App Store Connect: https://appstoreconnect.apple.com/apps/\(r.appID)/distribution/activity/ios/ratingsResponses """ return ReviewTodo(key: "appstore-review-\(r.appID)-\(r.id)", board: board, title: "Reply to the \(r.stars)-star App Store review of \(app): \"\(r.title.prefix(80))\"", notes: notes, priority: r.stars <= 3 ? "High" : "Medium", due: due) } /// Sends each to-do; returns the keys created (or already there). public func send(_ todos: [ReviewTodo], source: String = "Graphley") async throws -> [String] { guard !todos.isEmpty else { return [] } guard let raw = Keychain.get(.openTalonConnection), let config = try? JSONSerialization.jsonObject(with: Data(raw.utf8)) as? [String: Any], let token = config["token"] as? String, let port = (config["port"] as? Int) ?? Int(config["port"] as? String ?? "") else { throw AnalyticsError.notSignedIn("OpenTalon (save its connection with set_source_key)") } let boards = try await call(port, token, "list_boards", [:])["boards"] as? [[String: Any]] ?? [] let ids = Dictionary(boards.compactMap { b in (b["name"] as? String).map { ($0.lowercased(), b["id"] as? String ?? "") } }, uniquingKeysWith: { a, _ in a }) var sent: [String] = [] for t in todos { guard let board = ids[t.board.lowercased()] ?? ids[Self.fallback.lowercased()] else { continue } var args: [String: Any] = ["boardId": board, "title": String(t.title.prefix(500)), "requestKey": String(t.key.prefix(200)), "notes": t.notes + "\nSource: \(source), key \(t.key)", "priority": t.priority] if let due = t.due { args["dueDate"] = due } _ = try await call(port, token, "create_task", args) sent.append(t.key) } return sent } func call(_ port: Int, _ token: String, _ name: String, _ arguments: [String: Any]) async throws -> [String: Any] { var r = URLRequest(url: URL(string: "http://127.0.0.1:\(port)/mcp")!) r.httpMethod = "POST"; r.timeoutInterval = 30 r.setValue("application/json", forHTTPHeaderField: "Content-Type") r.setValue("application/json, text/event-stream", forHTTPHeaderField: "Accept") r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") r.httpBody = try JSONSerialization.data(withJSONObject: ["jsonrpc": "2.0", "id": name, "method": "tools/call", "params": ["name": name, "arguments": arguments]]) let (data, response) = try await session.data(for: r) let code = (response as? HTTPURLResponse)?.statusCode ?? 0 guard code == 200 else { throw AnalyticsError.http(code, "OpenTalon \(name)") } var body = String(decoding: data, as: UTF8.self) if body.hasPrefix("event:") || body.contains("\ndata:") || body.hasPrefix("data:") { body = body.split(separator: "\n").filter { $0.hasPrefix("data:") }.last.map { String($0.dropFirst(5)) } ?? "" } let reply = (try? JSONSerialization.jsonObject(with: Data(body.utf8))) as? [String: Any] ?? [:] if let e = reply["error"] as? [String: Any] { throw AnalyticsError.badResponse("OpenTalon \(name): \(e["message"] ?? "")") } let result = reply["result"] as? [String: Any] ?? [:] if result["isError"] as? Bool == true { throw AnalyticsError.badResponse("OpenTalon \(name)") } return result["structuredContent"] as? [String: Any] ?? [:] } } extension ISO8601DateFormatter { nonisolated(unsafe) static let day: ISO8601DateFormatter = { let f = ISO8601DateFormatter(); f.formatOptions = [.withFullDate]; f.timeZone = .current; return f }() }