|
| 1 | +import WebKit |
| 2 | +import Foundation |
| 3 | + |
| 4 | +class WebFetcher: NSObject, WKNavigationDelegate { |
| 5 | + static let shared = WebFetcher() |
| 6 | + |
| 7 | + private var webView: WKWebView! |
| 8 | + private var isReady = false |
| 9 | + private var isBusy = false |
| 10 | + private var taskQueue: [(orgId: String, cookieString: String, completion: (Result<Data, Error>) -> Void)] = [] |
| 11 | + |
| 12 | + private override init() { |
| 13 | + super.init() |
| 14 | + DispatchQueue.main.async { self.setup() } |
| 15 | + } |
| 16 | + |
| 17 | + private func setup() { |
| 18 | + let config = WKWebViewConfiguration() |
| 19 | + config.websiteDataStore = .nonPersistent() |
| 20 | + webView = WKWebView(frame: .zero, configuration: config) |
| 21 | + webView.navigationDelegate = self |
| 22 | + } |
| 23 | + |
| 24 | + // MARK: - Public |
| 25 | + |
| 26 | + private let maxQueueSize = 20 |
| 27 | + |
| 28 | + func fetch(orgId: String, cookieString: String, completion: @escaping (Result<Data, Error>) -> Void) { |
| 29 | + DispatchQueue.main.async { |
| 30 | + guard self.taskQueue.count < self.maxQueueSize else { |
| 31 | + completion(.failure(NSError(domain: "WebFetcher", code: -2, userInfo: [NSLocalizedDescriptionKey: "Queue full"]))) |
| 32 | + return |
| 33 | + } |
| 34 | + self.taskQueue.append((orgId, cookieString, completion)) |
| 35 | + self.drainQueue() |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + // MARK: - WKNavigationDelegate |
| 40 | + |
| 41 | + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { |
| 42 | + guard let host = webView.url?.host, host.contains("claude.ai") else { return } |
| 43 | + isReady = true |
| 44 | + drainQueue() |
| 45 | + } |
| 46 | + |
| 47 | + func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { |
| 48 | + if !isReady { |
| 49 | + isReady = true |
| 50 | + drainQueue() |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { |
| 55 | + if !isReady { |
| 56 | + isReady = true |
| 57 | + drainQueue() |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + // MARK: - Queue |
| 62 | + |
| 63 | + private func drainQueue() { |
| 64 | + guard !isBusy, !taskQueue.isEmpty else { return } |
| 65 | + isBusy = true |
| 66 | + let task = taskQueue.removeFirst() |
| 67 | + executeTask(task) |
| 68 | + } |
| 69 | + |
| 70 | + private func executeTask(_ task: (orgId: String, cookieString: String, completion: (Result<Data, Error>) -> Void)) { |
| 71 | + injectCookies(task.cookieString) { |
| 72 | + if self.isReady { |
| 73 | + self.performFetch(orgId: task.orgId, completion: task.completion) |
| 74 | + } else { |
| 75 | + // Navigate to claude.ai first, then fetch on didFinish |
| 76 | + self.taskQueue.insert(task, at: 0) |
| 77 | + self.isBusy = false |
| 78 | + self.isReady = false |
| 79 | + self.webView.load(URLRequest(url: URL(string: "https://claude.ai")!)) |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + private func injectCookies(_ cookieString: String, completion: @escaping () -> Void) { |
| 85 | + let store = webView.configuration.websiteDataStore.httpCookieStore |
| 86 | + store.getAllCookies { existing in |
| 87 | + let group = DispatchGroup() |
| 88 | + for cookie in existing { |
| 89 | + group.enter() |
| 90 | + store.delete(cookie) { group.leave() } |
| 91 | + } |
| 92 | + group.notify(queue: .main) { |
| 93 | + let cookies: [HTTPCookie] = cookieString |
| 94 | + .components(separatedBy: ";") |
| 95 | + .compactMap { part in |
| 96 | + let t = part.trimmingCharacters(in: .whitespaces) |
| 97 | + let kv = t.components(separatedBy: "=") |
| 98 | + guard kv.count >= 2 else { return nil } |
| 99 | + let name = kv[0].trimmingCharacters(in: .whitespaces) |
| 100 | + let value = kv.dropFirst().joined(separator: "=") |
| 101 | + return HTTPCookie(properties: [ |
| 102 | + .name: name, |
| 103 | + .value: value, |
| 104 | + .domain: ".claude.ai", |
| 105 | + .path: "/", |
| 106 | + .secure: "TRUE" |
| 107 | + ]) |
| 108 | + } |
| 109 | + let g2 = DispatchGroup() |
| 110 | + for cookie in cookies { |
| 111 | + g2.enter() |
| 112 | + store.setCookie(cookie) { g2.leave() } |
| 113 | + } |
| 114 | + g2.notify(queue: .main) { completion() } |
| 115 | + } |
| 116 | + } |
| 117 | + } |
| 118 | + |
| 119 | + private func performFetch(orgId: String, completion: @escaping (Result<Data, Error>) -> Void) { |
| 120 | + let js = """ |
| 121 | + const r = await fetch('/api/organizations/\(orgId)/usage', { |
| 122 | + credentials: 'include', |
| 123 | + headers: { |
| 124 | + 'accept': '*/*', |
| 125 | + 'anthropic-client-platform': 'web_claude_ai', |
| 126 | + 'anthropic-client-version': '1.0.0', |
| 127 | + 'anthropic-client-sha': 'ec58f908c65bf1b6cd36aab8c717a3c78597ac3b', |
| 128 | + 'sec-fetch-dest': 'empty', |
| 129 | + 'sec-fetch-mode': 'cors', |
| 130 | + 'sec-fetch-site': 'same-origin' |
| 131 | + } |
| 132 | + }); |
| 133 | + const body = await r.text(); |
| 134 | + return {status: r.status, body: body}; |
| 135 | + """ |
| 136 | + webView.callAsyncJavaScript(js, arguments: [:], in: nil, in: .page) { [weak self] result in |
| 137 | + guard let self else { return } |
| 138 | + defer { |
| 139 | + self.isBusy = false |
| 140 | + self.drainQueue() |
| 141 | + } |
| 142 | + switch result { |
| 143 | + case .success(let value): |
| 144 | + guard let dict = value as? [String: Any], |
| 145 | + let status = dict["status"] as? Int, |
| 146 | + let body = dict["body"] as? String else { |
| 147 | + completion(.failure(NSError(domain: "WebFetcher", code: -1))) |
| 148 | + return |
| 149 | + } |
| 150 | + if status == 200, let data = body.data(using: .utf8) { |
| 151 | + completion(.success(data)) |
| 152 | + } else { |
| 153 | + completion(.failure(NSError(domain: "WebFetcher", code: status))) |
| 154 | + } |
| 155 | + case .failure(let error): |
| 156 | + completion(.failure(error)) |
| 157 | + } |
| 158 | + } |
| 159 | + } |
| 160 | +} |
0 commit comments