@onairosofficial/onairos-capacitor 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,993 @@
1
+ import UIKit
2
+ import Capacitor
3
+ import WebKit
4
+
5
+ @objc(OnairosChatGPTNativePlugin)
6
+ class OnairosChatGPTNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDelegate, WKHTTPCookieStoreObserver, WKScriptMessageHandler {
7
+ public let identifier = "OnairosChatGPTNativePlugin"
8
+ public let jsName = "OnairosChatGPTNative"
9
+ public let pluginMethods: [CAPPluginMethod] = [
10
+ CAPPluginMethod(name: "connectChatGPTNative", returnType: CAPPluginReturnPromise),
11
+ CAPPluginMethod(name: "closeChatGPTConnector", returnType: CAPPluginReturnPromise),
12
+ CAPPluginMethod(name: "openChatGPTConnector", returnType: CAPPluginReturnPromise)
13
+ ]
14
+
15
+ private let backendBaseURL = "https://api2.onairos.uk"
16
+ private let bridgeBaseURL = "https://onairos.io"
17
+ private let chatGPTLoginURL = "https://chatgpt.com/auth/login"
18
+ private let mobileUserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"
19
+
20
+ private var overlayWindow: UIWindow?
21
+ private var loginWebView: WKWebView?
22
+ private var progressLabel: UILabel?
23
+ private var progressBar: UIProgressView?
24
+ private var pendingConversations: [[String: Any]] = []
25
+ private var pendingMemories: [String: Any]?
26
+ private var pendingJWTToken = ""
27
+ private var pendingCall: CAPPluginCall?
28
+ private var didCaptureSessionCookies = false
29
+ private var isVerifyingSession = false
30
+ private var isFlowCancelled = false
31
+ private var bridgePageReady = false
32
+ private var didInjectBridgeUpload = false
33
+
34
+ @objc func connectChatGPTNative(_ call: CAPPluginCall) {
35
+ if pendingCall != nil {
36
+ call.reject("ChatGPT connection is already in progress.")
37
+ return
38
+ }
39
+
40
+ let jwtToken = (call.getString("jwtToken") ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
41
+ if jwtToken.isEmpty {
42
+ call.reject("Missing Onairos JWT token for ChatGPT connection.")
43
+ return
44
+ }
45
+
46
+ pendingCall = call
47
+ bridge?.saveCall(call)
48
+ pendingJWTToken = jwtToken
49
+ pendingConversations = []
50
+ pendingMemories = nil
51
+ didCaptureSessionCookies = false
52
+ isVerifyingSession = false
53
+ isFlowCancelled = false
54
+ bridgePageReady = false
55
+ didInjectBridgeUpload = false
56
+
57
+ emitStatus("verifying_session", message: "Opening ChatGPT login…")
58
+ DispatchQueue.main.async { [weak self] in
59
+ self?.presentChatGPTLogin(in: self?.activeScene())
60
+ }
61
+ }
62
+
63
+ @objc func closeChatGPTConnector(_ call: CAPPluginCall) {
64
+ cancelFlow(message: nil, rejectPending: false)
65
+ call.resolve()
66
+ }
67
+
68
+ @objc func openChatGPTConnector(_ call: CAPPluginCall) {
69
+ guard let url = URL(string: chatGPTLoginURL) else {
70
+ call.reject("Invalid ChatGPT URL.")
71
+ return
72
+ }
73
+ DispatchQueue.main.async {
74
+ UIApplication.shared.open(url)
75
+ call.resolve()
76
+ }
77
+ }
78
+
79
+ private func presentChatGPTLogin(in scene: UIWindowScene?) {
80
+ guard !isFlowCancelled else { return }
81
+
82
+ WKWebsiteDataStore.default().httpCookieStore.getAllCookies { [weak self] cookies in
83
+ guard let self = self, !self.isFlowCancelled else { return }
84
+
85
+ let chatCookies = cookies.filter { cookie in
86
+ cookie.domain.contains("chatgpt.com") || cookie.domain.contains("openai.com")
87
+ }
88
+ let hasSessionCookie = chatCookies.contains { self.nameMatchesSession($0.name) }
89
+
90
+ if hasSessionCookie {
91
+ self.attemptSessionCapture(using: chatCookies, in: scene) { [weak self] in
92
+ guard let self = self, !self.isFlowCancelled else { return }
93
+ DispatchQueue.main.async {
94
+ self.showChatGPTLoginWebView(in: scene)
95
+ }
96
+ }
97
+ return
98
+ }
99
+
100
+ DispatchQueue.main.async {
101
+ self.showChatGPTLoginWebView(in: scene)
102
+ }
103
+ }
104
+ }
105
+
106
+ private func showChatGPTLoginWebView(in scene: UIWindowScene?) {
107
+ guard !isFlowCancelled else { return }
108
+ if !Thread.isMainThread {
109
+ DispatchQueue.main.async { [weak self] in
110
+ self?.showChatGPTLoginWebView(in: scene)
111
+ }
112
+ return
113
+ }
114
+
115
+ let config = WKWebViewConfiguration()
116
+ config.websiteDataStore = .default()
117
+ config.allowsInlineMediaPlayback = true
118
+ config.websiteDataStore.httpCookieStore.add(self)
119
+
120
+ let webView = WKWebView(frame: .zero, configuration: config)
121
+ webView.navigationDelegate = self
122
+ webView.customUserAgent = mobileUserAgent
123
+ webView.translatesAutoresizingMaskIntoConstraints = false
124
+ webView.layer.cornerRadius = 16
125
+ webView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
126
+ webView.clipsToBounds = true
127
+
128
+ let viewController = UIViewController()
129
+ viewController.view.backgroundColor = .white
130
+ viewController.view.layer.cornerRadius = 16
131
+ viewController.view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
132
+ viewController.view.clipsToBounds = true
133
+
134
+ let closeButton = UIButton(type: .system)
135
+ closeButton.setTitle("✕", for: .normal)
136
+ closeButton.setTitleColor(.white, for: .normal)
137
+ closeButton.backgroundColor = UIColor.black.withAlphaComponent(0.7)
138
+ closeButton.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .medium)
139
+ closeButton.layer.cornerRadius = 20
140
+ closeButton.translatesAutoresizingMaskIntoConstraints = false
141
+ closeButton.layer.zPosition = 1000
142
+ closeButton.addAction(UIAction { [weak self] _ in
143
+ self?.cancelFlow(message: "User canceled ChatGPT login.")
144
+ }, for: .touchUpInside)
145
+
146
+ viewController.view.addSubview(webView)
147
+ viewController.view.addSubview(closeButton)
148
+
149
+ NSLayoutConstraint.activate([
150
+ webView.leadingAnchor.constraint(equalTo: viewController.view.leadingAnchor),
151
+ webView.trailingAnchor.constraint(equalTo: viewController.view.trailingAnchor),
152
+ webView.topAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.topAnchor, constant: 10),
153
+ webView.bottomAnchor.constraint(equalTo: viewController.view.bottomAnchor),
154
+ closeButton.topAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.topAnchor, constant: 8),
155
+ closeButton.trailingAnchor.constraint(equalTo: viewController.view.trailingAnchor, constant: -12),
156
+ closeButton.widthAnchor.constraint(equalToConstant: 40),
157
+ closeButton.heightAnchor.constraint(equalToConstant: 40)
158
+ ])
159
+
160
+ loginWebView = webView
161
+ presentInOverlayWindow(viewController, in: scene)
162
+
163
+ if let url = URL(string: chatGPTLoginURL) {
164
+ var request = URLRequest(url: url)
165
+ request.setValue("en-US,en;q=0.9", forHTTPHeaderField: "Accept-Language")
166
+ request.setValue("https://chatgpt.com", forHTTPHeaderField: "Referer")
167
+ webView.load(request)
168
+ }
169
+
170
+ pollForChatGPTCookies()
171
+ }
172
+
173
+ private func pollForChatGPTCookies() {
174
+ var attempts = 0
175
+
176
+ func poll() {
177
+ guard !self.isFlowCancelled else { return }
178
+ attempts += 1
179
+
180
+ WKWebsiteDataStore.default().httpCookieStore.getAllCookies { [weak self] cookies in
181
+ guard let self = self, !self.isFlowCancelled else { return }
182
+
183
+ let chatCookies = cookies.filter { cookie in
184
+ cookie.domain.contains("chatgpt.com") || cookie.domain.contains("openai.com")
185
+ }
186
+ let hasSessionCookie = chatCookies.contains { self.nameMatchesSession($0.name) }
187
+
188
+ if hasSessionCookie && !self.didCaptureSessionCookies && !self.isVerifyingSession {
189
+ self.attemptSessionCapture(using: chatCookies, in: self.activeScene()) { [weak self] in
190
+ guard let self = self, !self.isFlowCancelled else { return }
191
+ if attempts < 120 {
192
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
193
+ poll()
194
+ }
195
+ } else {
196
+ self.finishWithError("Timed out waiting for ChatGPT login.")
197
+ }
198
+ }
199
+ } else if attempts < 120 {
200
+ DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
201
+ poll()
202
+ }
203
+ } else if !self.didCaptureSessionCookies {
204
+ self.finishWithError("Timed out waiting for ChatGPT login.")
205
+ }
206
+ }
207
+ }
208
+
209
+ poll()
210
+ }
211
+
212
+ private func attemptSessionCapture(using chatCookies: [HTTPCookie], in scene: UIWindowScene?, onFailure: (() -> Void)? = nil) {
213
+ guard !isFlowCancelled, !didCaptureSessionCookies, !isVerifyingSession else { return }
214
+
215
+ isVerifyingSession = true
216
+ emitStatus("verifying_session", message: "Verifying ChatGPT session…")
217
+ let cookieHeader = buildCookieHeader(from: chatCookies)
218
+
219
+ verifyChatGPTSession(cookieHeader: cookieHeader) { [weak self] authenticated in
220
+ guard let self = self else { return }
221
+ self.isVerifyingSession = false
222
+ guard !self.isFlowCancelled else { return }
223
+
224
+ if authenticated {
225
+ self.beginAuthenticatedImportFlow(using: chatCookies, in: scene)
226
+ } else {
227
+ onFailure?()
228
+ }
229
+ }
230
+ }
231
+
232
+ private func beginAuthenticatedImportFlow(using chatCookies: [HTTPCookie], in scene: UIWindowScene?) {
233
+ guard !isFlowCancelled, !didCaptureSessionCookies else { return }
234
+
235
+ didCaptureSessionCookies = true
236
+ emitStatus("authenticated", message: "Authenticated — opening import…")
237
+ DispatchQueue.main.async { [weak self] in
238
+ self?.showImportBridgeOverlay(in: scene)
239
+ }
240
+ DispatchQueue.global(qos: .userInitiated).async { [weak self] in
241
+ self?.scrapeConversations(using: chatCookies)
242
+ }
243
+ }
244
+
245
+ private func showImportBridgeOverlay(in scene: UIWindowScene?) {
246
+ guard !isFlowCancelled else { return }
247
+ if !Thread.isMainThread {
248
+ DispatchQueue.main.async { [weak self] in
249
+ self?.showImportBridgeOverlay(in: scene)
250
+ }
251
+ return
252
+ }
253
+
254
+ let contentController = WKUserContentController()
255
+ contentController.add(self, name: "bridgeCallback")
256
+
257
+ let config = WKWebViewConfiguration()
258
+ config.websiteDataStore = .default()
259
+ config.userContentController = contentController
260
+
261
+ let webView = WKWebView(frame: .zero, configuration: config)
262
+ webView.navigationDelegate = self
263
+ webView.customUserAgent = mobileUserAgent
264
+ webView.scrollView.contentInsetAdjustmentBehavior = .never
265
+ webView.translatesAutoresizingMaskIntoConstraints = false
266
+ webView.backgroundColor = .white
267
+ webView.isOpaque = true
268
+
269
+ let viewController = UIViewController()
270
+ viewController.view.backgroundColor = .white
271
+
272
+ let closeButton = UIButton(type: .system)
273
+ closeButton.setTitle("✕", for: .normal)
274
+ closeButton.setTitleColor(.white, for: .normal)
275
+ closeButton.backgroundColor = UIColor.black.withAlphaComponent(0.7)
276
+ closeButton.titleLabel?.font = UIFont.systemFont(ofSize: 20, weight: .medium)
277
+ closeButton.layer.cornerRadius = 20
278
+ closeButton.translatesAutoresizingMaskIntoConstraints = false
279
+ closeButton.layer.zPosition = 1000
280
+ closeButton.addAction(UIAction { [weak self] _ in
281
+ self?.cancelFlow(message: "User canceled ChatGPT import.")
282
+ }, for: .touchUpInside)
283
+
284
+ viewController.view.addSubview(webView)
285
+ viewController.view.addSubview(closeButton)
286
+ NSLayoutConstraint.activate([
287
+ webView.leadingAnchor.constraint(equalTo: viewController.view.leadingAnchor),
288
+ webView.trailingAnchor.constraint(equalTo: viewController.view.trailingAnchor),
289
+ webView.topAnchor.constraint(equalTo: viewController.view.topAnchor),
290
+ webView.bottomAnchor.constraint(equalTo: viewController.view.bottomAnchor),
291
+ closeButton.topAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.topAnchor, constant: 8),
292
+ closeButton.trailingAnchor.constraint(equalTo: viewController.view.trailingAnchor, constant: -12),
293
+ closeButton.widthAnchor.constraint(equalToConstant: 40),
294
+ closeButton.heightAnchor.constraint(equalToConstant: 40)
295
+ ])
296
+
297
+ bridgePageReady = false
298
+ didInjectBridgeUpload = false
299
+ progressLabel = nil
300
+ progressBar = nil
301
+ loginWebView?.navigationDelegate = nil
302
+ loginWebView?.stopLoading()
303
+ loginWebView = webView
304
+
305
+ overlayWindow?.isHidden = true
306
+ overlayWindow?.rootViewController = nil
307
+ overlayWindow = nil
308
+
309
+ presentInOverlayWindow(viewController, in: scene)
310
+
311
+ if let url = URL(string: "\(bridgeBaseURL)/extract-data/") {
312
+ var request = URLRequest(url: url)
313
+ request.setValue("no-cache", forHTTPHeaderField: "Cache-Control")
314
+ request.setValue("no-cache", forHTTPHeaderField: "Pragma")
315
+ webView.load(request)
316
+ } else {
317
+ finishWithError("Invalid Onairos import bridge URL.")
318
+ }
319
+ }
320
+
321
+ private func updateProgress(_ fraction: Float, message: String) {
322
+ DispatchQueue.main.async { [weak self] in
323
+ self?.progressBar?.setProgress(fraction, animated: true)
324
+ self?.progressLabel?.text = message
325
+ }
326
+ }
327
+
328
+ private func nameMatchesSession(_ name: String) -> Bool {
329
+ name.contains("session") || name == "__Secure-next-auth.session-token" || name == "aiap_session"
330
+ }
331
+
332
+ private func buildCookieHeader(from cookies: [HTTPCookie]) -> String {
333
+ cookies.map { "\($0.name)=\($0.value)" }.joined(separator: "; ")
334
+ }
335
+
336
+ private func scrapeConversations(using cookies: [HTTPCookie]) {
337
+ guard !isFlowCancelled else { return }
338
+
339
+ let cookieStorage = HTTPCookieStorage.shared
340
+ cookies.forEach { cookieStorage.setCookie($0) }
341
+ let cookieHeader = buildCookieHeader(from: cookies)
342
+
343
+ fetchAccessToken(cookieHeader: cookieHeader) { [weak self] token in
344
+ guard let self = self, !self.isFlowCancelled else { return }
345
+
346
+ guard let token, !token.isEmpty else {
347
+ self.emitStatus("access_token_missing", message: "Could not verify ChatGPT session.")
348
+ self.finishWithError("Could not verify ChatGPT session.")
349
+ return
350
+ }
351
+
352
+ self.emitStatus("authenticated", message: "Authenticated — starting scrape…")
353
+ self.emitStatus("scraping_started", message: "Scraping your ChatGPT data…")
354
+ self.requestConversations(authBearer: token, cookieHeader: cookieHeader) { [weak self] result in
355
+ guard let self = self, !self.isFlowCancelled else { return }
356
+ switch result {
357
+ case .failure(let error):
358
+ self.finishWithError(error.localizedDescription)
359
+ case .success(let conversations):
360
+ self.updateProgress(0.88, message: "Fetching memories…")
361
+ self.fetchMemories(authBearer: token, cookieHeader: cookieHeader) { [weak self] memories in
362
+ guard let self = self, !self.isFlowCancelled else { return }
363
+ self.pendingMemories = memories
364
+ self.processAndUploadViaBridge(conversations)
365
+ }
366
+ }
367
+ }
368
+ }
369
+ }
370
+
371
+ private func fetchAccessToken(cookieHeader: String, completion: @escaping (String?) -> Void) {
372
+ guard let url = URL(string: "https://chatgpt.com/api/auth/session") else {
373
+ completion(nil)
374
+ return
375
+ }
376
+
377
+ var request = URLRequest(url: url)
378
+ request.httpMethod = "GET"
379
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
380
+ request.setValue("https://chatgpt.com", forHTTPHeaderField: "Referer")
381
+ request.setValue(mobileUserAgent, forHTTPHeaderField: "User-Agent")
382
+ request.setValue("en-US,en;q=0.9", forHTTPHeaderField: "Accept-Language")
383
+ if !cookieHeader.isEmpty {
384
+ request.setValue(cookieHeader, forHTTPHeaderField: "Cookie")
385
+ }
386
+
387
+ URLSession.shared.dataTask(with: request) { data, _, error in
388
+ guard error == nil,
389
+ let data,
390
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
391
+ completion(nil)
392
+ return
393
+ }
394
+
395
+ let token =
396
+ (json["accessToken"] as? String) ??
397
+ (json["access_token"] as? String) ??
398
+ ((json["session"] as? [String: Any])?["accessToken"] as? String)
399
+ completion(token)
400
+ }.resume()
401
+ }
402
+
403
+ private func verifyChatGPTSession(cookieHeader: String, completion: @escaping (Bool) -> Void) {
404
+ fetchAccessToken(cookieHeader: cookieHeader) { token in
405
+ completion(!(token ?? "").isEmpty)
406
+ }
407
+ }
408
+
409
+ private func requestConversations(authBearer: String, cookieHeader: String, completion: @escaping (Result<[[String: Any]], Error>) -> Void) {
410
+ updateProgress(0.05, message: "Fetching conversation list…")
411
+
412
+ guard let url = URL(string: "https://chatgpt.com/backend-api/conversations?offset=0&limit=10") else {
413
+ completion(.failure(NSError(domain: "OnairosChatGPTNative", code: 1001, userInfo: [NSLocalizedDescriptionKey: "Invalid conversation list URL."])))
414
+ return
415
+ }
416
+
417
+ var request = URLRequest(url: url)
418
+ request.httpMethod = "GET"
419
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
420
+ request.setValue("https://chatgpt.com", forHTTPHeaderField: "Referer")
421
+ request.setValue(mobileUserAgent, forHTTPHeaderField: "User-Agent")
422
+ request.setValue("en-US,en;q=0.9", forHTTPHeaderField: "Accept-Language")
423
+ request.setValue(cookieHeader, forHTTPHeaderField: "Cookie")
424
+ request.setValue("Bearer \(authBearer)", forHTTPHeaderField: "Authorization")
425
+
426
+ URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
427
+ guard let self = self else { return }
428
+ if let error {
429
+ completion(.failure(error))
430
+ return
431
+ }
432
+
433
+ guard let http = response as? HTTPURLResponse,
434
+ let data,
435
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
436
+ completion(.failure(NSError(domain: "OnairosChatGPTNative", code: 1002, userInfo: [NSLocalizedDescriptionKey: "Invalid ChatGPT conversation response."])))
437
+ return
438
+ }
439
+
440
+ let items = (json["items"] as? [[String: Any]]) ?? []
441
+ let ids = items.compactMap { $0["id"] as? String }
442
+ guard !ids.isEmpty else {
443
+ let message = (http.statusCode == 401 || http.statusCode == 403)
444
+ ? "Could not access ChatGPT conversations."
445
+ : "No ChatGPT conversations were found."
446
+ completion(.failure(NSError(domain: "OnairosChatGPTNative", code: http.statusCode, userInfo: [NSLocalizedDescriptionKey: message])))
447
+ return
448
+ }
449
+
450
+ self.fetchAllConversationDetails(ids: ids, authBearer: authBearer, cookieHeader: cookieHeader, completion: completion)
451
+ }.resume()
452
+ }
453
+
454
+ private func fetchAllConversationDetails(ids: [String], authBearer: String, cookieHeader: String, completion: @escaping (Result<[[String: Any]], Error>) -> Void) {
455
+ let group = DispatchGroup()
456
+ let lock = NSLock()
457
+ var conversations: [[String: Any]] = []
458
+
459
+ for (index, conversationID) in ids.enumerated() {
460
+ group.enter()
461
+ let delay = Double(index) * (0.35 + Double.random(in: 0...0.45))
462
+ DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + delay) {
463
+ guard !self.isFlowCancelled else {
464
+ group.leave()
465
+ return
466
+ }
467
+
468
+ self.updateProgress(
469
+ 0.12 + Float(index) / Float(max(ids.count, 1)) * 0.68,
470
+ message: "Processing \(index + 1)/\(ids.count) conversations"
471
+ )
472
+
473
+ self.fetchConversationDetail(id: conversationID, authBearer: authBearer, cookieHeader: cookieHeader) { data in
474
+ if let data {
475
+ lock.lock()
476
+ conversations.append(data)
477
+ lock.unlock()
478
+ }
479
+ group.leave()
480
+ }
481
+ }
482
+ }
483
+
484
+ group.notify(queue: .main) {
485
+ if self.isFlowCancelled {
486
+ return
487
+ }
488
+ completion(.success(conversations))
489
+ }
490
+ }
491
+
492
+ private func fetchConversationDetail(id: String, authBearer: String, cookieHeader: String, completion: @escaping ([String: Any]?) -> Void) {
493
+ guard let url = URL(string: "https://chatgpt.com/backend-api/conversation/\(id)") else {
494
+ completion(nil)
495
+ return
496
+ }
497
+
498
+ var request = URLRequest(url: url)
499
+ request.httpMethod = "GET"
500
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
501
+ request.setValue("https://chatgpt.com", forHTTPHeaderField: "Referer")
502
+ request.setValue(mobileUserAgent, forHTTPHeaderField: "User-Agent")
503
+ request.setValue(cookieHeader, forHTTPHeaderField: "Cookie")
504
+ request.setValue("Bearer \(authBearer)", forHTTPHeaderField: "Authorization")
505
+
506
+ URLSession.shared.dataTask(with: request) { data, _, _ in
507
+ guard let data,
508
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
509
+ completion(nil)
510
+ return
511
+ }
512
+ completion(json)
513
+ }.resume()
514
+ }
515
+
516
+ private func fetchMemories(authBearer: String, cookieHeader: String, completion: @escaping ([String: Any]?) -> Void) {
517
+ guard let url = URL(string: "https://chatgpt.com/backend-api/memories?include_memory_entries=true&memory_entries_filter=all") else {
518
+ completion(nil)
519
+ return
520
+ }
521
+
522
+ var request = URLRequest(url: url)
523
+ request.httpMethod = "GET"
524
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
525
+ request.setValue("https://chatgpt.com", forHTTPHeaderField: "Referer")
526
+ request.setValue(mobileUserAgent, forHTTPHeaderField: "User-Agent")
527
+ request.setValue("en-US,en;q=0.9", forHTTPHeaderField: "Accept-Language")
528
+ request.setValue(cookieHeader, forHTTPHeaderField: "Cookie")
529
+ request.setValue("Bearer \(authBearer)", forHTTPHeaderField: "Authorization")
530
+
531
+ URLSession.shared.dataTask(with: request) { data, response, _ in
532
+ guard let http = response as? HTTPURLResponse,
533
+ let data,
534
+ (200..<300).contains(http.statusCode),
535
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
536
+ completion(nil)
537
+ return
538
+ }
539
+ completion(json)
540
+ }.resume()
541
+ }
542
+
543
+ private func processAndUploadViaBridge(_ conversations: [[String: Any]]) {
544
+ var formatted: [[String: Any]] = []
545
+
546
+ for conversation in conversations {
547
+ let conversationID = (conversation["id"] as? String) ?? (conversation["conversation_id"] as? String) ?? "unknown"
548
+ let title = (conversation["title"] as? String) ?? "Untitled"
549
+ let createTime = (conversation["create_time"] as? TimeInterval) ?? Date().timeIntervalSince1970
550
+ let updateTime = (conversation["update_time"] as? TimeInterval) ?? Date().timeIntervalSince1970
551
+
552
+ var messages: [[String: Any]] = []
553
+ if let mapping = conversation["mapping"] as? [String: [String: Any]] {
554
+ for (_, node) in mapping {
555
+ guard let message = node["message"] as? [String: Any],
556
+ let author = message["author"] as? [String: Any],
557
+ let role = author["role"] as? String,
558
+ let content = message["content"] as? [String: Any],
559
+ let parts = content["parts"] as? [String],
560
+ let text = parts.first else {
561
+ continue
562
+ }
563
+
564
+ let timestamp = (message["create_time"] as? TimeInterval).map {
565
+ ISO8601DateFormatter().string(from: Date(timeIntervalSince1970: $0))
566
+ } ?? ISO8601DateFormatter().string(from: Date())
567
+
568
+ messages.append([
569
+ "id": (message["id"] as? String) ?? UUID().uuidString,
570
+ "role": role,
571
+ "content": text,
572
+ "timestamp": timestamp,
573
+ "metadata": message["metadata"] ?? [:]
574
+ ])
575
+ }
576
+ }
577
+
578
+ messages.sort { ($0["timestamp"] as? String ?? "") < ($1["timestamp"] as? String ?? "") }
579
+
580
+ formatted.append([
581
+ "conversationId": conversationID,
582
+ "title": title,
583
+ "messages": messages,
584
+ "create_time": Int(createTime),
585
+ "update_time": Int(updateTime)
586
+ ])
587
+ }
588
+
589
+ pendingConversations = formatted
590
+ emitStatus("uploading", message: "Uploading through Onairos import…")
591
+
592
+ DispatchQueue.main.async { [weak self] in
593
+ self?.navigateToBridgeForUpload()
594
+ }
595
+ }
596
+
597
+ private func navigateToBridgeForUpload() {
598
+ guard !isFlowCancelled else { return }
599
+ if bridgePageReady {
600
+ injectBridgeUploadScriptIfReady()
601
+ return
602
+ }
603
+ showImportBridgeOverlay(in: activeScene())
604
+ }
605
+
606
+ private func injectBridgeUploadScriptIfReady() {
607
+ guard bridgePageReady, !didInjectBridgeUpload else { return }
608
+ guard !pendingConversations.isEmpty || pendingMemories != nil else { return }
609
+ didInjectBridgeUpload = true
610
+ injectBridgeUploadScript()
611
+ }
612
+
613
+ private func injectBridgeUploadScript() {
614
+ guard !isFlowCancelled else { return }
615
+
616
+ let conversationsJSON = (try? JSONSerialization.data(withJSONObject: pendingConversations))
617
+ .flatMap { String(data: $0, encoding: .utf8) } ?? "[]"
618
+ let memoriesJSON = pendingMemories
619
+ .flatMap { try? JSONSerialization.data(withJSONObject: $0) }
620
+ .flatMap { String(data: $0, encoding: .utf8) } ?? "null"
621
+
622
+ let script = """
623
+ (async function() {
624
+ try {
625
+ var baseUrl = \(jsonString(backendBaseURL));
626
+ var authToken = \(jsonString(pendingJWTToken));
627
+ var convos = \(conversationsJSON);
628
+ var memories = \(memoriesJSON);
629
+ var successCount = 0;
630
+ var failCount = 0;
631
+ var memorySuccess = false;
632
+
633
+ for (var i = 0; i < convos.length; i++) {
634
+ var c = convos[i];
635
+ try {
636
+ var response = await fetch(baseUrl + '/llm-data/store', {
637
+ method: 'POST',
638
+ headers: {
639
+ 'Content-Type': 'application/json',
640
+ 'Authorization': 'Bearer ' + authToken
641
+ },
642
+ body: JSON.stringify({
643
+ platform: 'mobile-chatgpt',
644
+ conversationData: {
645
+ conversationId: c.conversationId,
646
+ messages: c.messages,
647
+ context: {
648
+ title: c.title,
649
+ create_time: c.create_time,
650
+ update_time: c.update_time
651
+ },
652
+ mobileMetadata: {
653
+ platform: 'ios',
654
+ appVersion: '1.0.0',
655
+ isOfflineSync: false
656
+ }
657
+ },
658
+ memoryType: 'conversation'
659
+ })
660
+ });
661
+ if (response.ok) { successCount++; } else { failCount++; }
662
+ } catch (_) {
663
+ failCount++;
664
+ }
665
+ if (i < convos.length - 1) {
666
+ await new Promise(function(resolve) { setTimeout(resolve, 200); });
667
+ }
668
+ }
669
+
670
+ if (memories) {
671
+ try {
672
+ var memoryResponse = await fetch(baseUrl + '/llm-data/store-memories', {
673
+ method: 'POST',
674
+ headers: {
675
+ 'Content-Type': 'application/json',
676
+ 'Authorization': 'Bearer ' + authToken
677
+ },
678
+ body: JSON.stringify({
679
+ platform: 'mobile-chatgpt',
680
+ memoriesData: memories,
681
+ metadata: {
682
+ source: 'ios-native',
683
+ appVersion: '1.0.0',
684
+ fetchedAt: new Date().toISOString()
685
+ }
686
+ })
687
+ });
688
+ memorySuccess = !!memoryResponse.ok;
689
+ } catch (_) {}
690
+ }
691
+
692
+ window.webkit.messageHandlers.bridgeCallback.postMessage(JSON.stringify({
693
+ type: 'BRIDGE_UPLOAD_COMPLETE',
694
+ success: successCount > 0 || convos.length === 0,
695
+ conversationSuccess: successCount > 0 || convos.length === 0,
696
+ memorySuccess: memorySuccess,
697
+ storedConversations: successCount,
698
+ failedConversations: failCount
699
+ }));
700
+ } catch (error) {
701
+ window.webkit.messageHandlers.bridgeCallback.postMessage(JSON.stringify({
702
+ type: 'BRIDGE_UPLOAD_ERROR',
703
+ message: (error && error.message) || 'Upload failed'
704
+ }));
705
+ }
706
+ })();
707
+ """
708
+
709
+ loginWebView?.evaluateJavaScript(script, completionHandler: nil)
710
+ }
711
+
712
+ private func jsonString(_ value: String) -> String {
713
+ let escaped = value
714
+ .replacingOccurrences(of: "\\", with: "\\\\")
715
+ .replacingOccurrences(of: "\"", with: "\\\"")
716
+ .replacingOccurrences(of: "\n", with: "\\n")
717
+ return "\"\(escaped)\""
718
+ }
719
+
720
+ func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
721
+ guard !isFlowCancelled, message.name == "bridgeCallback" else { return }
722
+
723
+ let payload: [String: Any]?
724
+ if let body = message.body as? String,
725
+ let data = body.data(using: .utf8),
726
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
727
+ payload = json
728
+ } else {
729
+ payload = message.body as? [String: Any]
730
+ }
731
+
732
+ guard let payload,
733
+ let type = payload["type"] as? String else {
734
+ finishWithError("Invalid upload callback from Onairos import bridge.")
735
+ return
736
+ }
737
+
738
+ if type == "BRIDGE_UPLOAD_COMPLETE" {
739
+ let conversationSuccess = payload["conversationSuccess"] as? Bool ?? false
740
+ let memorySuccess = payload["memorySuccess"] as? Bool ?? false
741
+ let overallSuccess = payload["success"] as? Bool ?? false
742
+
743
+ if conversationSuccess {
744
+ emitStatus("success_conversations", message: "Saved ChatGPT conversations.")
745
+ }
746
+ if memorySuccess {
747
+ emitStatus("success_memories", message: "Saved ChatGPT memories.")
748
+ }
749
+
750
+ if overallSuccess {
751
+ finishWithSuccess()
752
+ } else {
753
+ finishWithError("Could not store ChatGPT conversations.")
754
+ }
755
+ } else if type == "BRIDGE_UPLOAD_ERROR" {
756
+ finishWithError(payload["message"] as? String ?? "ChatGPT upload failed.")
757
+ }
758
+
759
+ pendingConversations = []
760
+ pendingMemories = nil
761
+ }
762
+
763
+ func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
764
+ let currentURL = webView.url?.absoluteString ?? ""
765
+ if currentURL.contains("/extract-data/") {
766
+ bridgePageReady = true
767
+ injectBridgeUploadScriptIfReady()
768
+ }
769
+ }
770
+
771
+ func cookiesDidChange(in cookieStore: WKHTTPCookieStore) {
772
+ guard !isFlowCancelled, !didCaptureSessionCookies, !isVerifyingSession else { return }
773
+
774
+ cookieStore.getAllCookies { [weak self] cookies in
775
+ guard let self = self, !self.isFlowCancelled, !self.didCaptureSessionCookies else { return }
776
+
777
+ let chatCookies = cookies.filter { cookie in
778
+ cookie.domain.contains("chatgpt.com") || cookie.domain.contains("openai.com")
779
+ }
780
+ let hasSessionCookie = chatCookies.contains { self.nameMatchesSession($0.name) }
781
+ guard hasSessionCookie else { return }
782
+
783
+ self.attemptSessionCapture(using: chatCookies, in: self.activeScene())
784
+ }
785
+ }
786
+
787
+ private func emitStatus(_ status: String, message: String? = nil) {
788
+ var payload: [String: Any] = [
789
+ "platform": "ChatGPT",
790
+ "status": status
791
+ ]
792
+ if let message, !message.isEmpty {
793
+ payload["message"] = message
794
+ }
795
+ notifyListeners("onairosNativeConnectorEvent", data: payload)
796
+ }
797
+
798
+ private func finishWithSuccess() {
799
+ guard let call = pendingCall else { return }
800
+ emitStatus("done", message: "ChatGPT import finished.")
801
+ bridgePageReady = false
802
+ didInjectBridgeUpload = false
803
+ showSuccessScreen()
804
+ call.resolve([
805
+ "success": true,
806
+ "platform": "ChatGPT"
807
+ ])
808
+ bridge?.releaseCall(call)
809
+ pendingCall = nil
810
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.25) { [weak self] in
811
+ self?.dismissOverlayWindow()
812
+ }
813
+ }
814
+
815
+ private func finishWithError(_ message: String) {
816
+ guard let call = pendingCall else { return }
817
+ emitStatus("error", message: message)
818
+ bridgePageReady = false
819
+ didInjectBridgeUpload = false
820
+ showErrorScreen(title: "ChatGPT Import Failed", message: message)
821
+ call.reject(message)
822
+ bridge?.releaseCall(call)
823
+ pendingCall = nil
824
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.75) { [weak self] in
825
+ self?.dismissOverlayWindow()
826
+ }
827
+ }
828
+
829
+ private func cancelFlow(message: String?, rejectPending: Bool = true) {
830
+ isFlowCancelled = true
831
+ didCaptureSessionCookies = false
832
+ isVerifyingSession = false
833
+ pendingConversations = []
834
+ pendingMemories = nil
835
+ loginWebView?.navigationDelegate = nil
836
+ loginWebView?.stopLoading()
837
+ loginWebView = nil
838
+ bridgePageReady = false
839
+ didInjectBridgeUpload = false
840
+ dismissOverlayWindow()
841
+
842
+ guard rejectPending, let call = pendingCall else { return }
843
+ let errorMessage = message ?? "ChatGPT connection canceled."
844
+ emitStatus("error", message: errorMessage)
845
+ call.reject(errorMessage)
846
+ bridge?.releaseCall(call)
847
+ pendingCall = nil
848
+ }
849
+
850
+ private func activeScene() -> UIWindowScene? {
851
+ if !Thread.isMainThread { return nil }
852
+ let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
853
+ return scenes.first { $0.activationState == .foregroundActive } ?? scenes.first
854
+ }
855
+
856
+ private func presentInOverlayWindow(_ viewController: UIViewController, in scene: UIWindowScene?) {
857
+ if !Thread.isMainThread {
858
+ DispatchQueue.main.async { [weak self] in
859
+ self?.presentInOverlayWindow(viewController, in: scene)
860
+ }
861
+ return
862
+ }
863
+
864
+ guard let scene else { return }
865
+
866
+ let window = UIWindow(windowScene: scene)
867
+ window.frame = scene.coordinateSpace.bounds
868
+ window.windowLevel = .alert + 1
869
+ window.backgroundColor = UIColor.black.withAlphaComponent(0.3)
870
+ window.rootViewController = viewController
871
+ window.makeKeyAndVisible()
872
+ overlayWindow = window
873
+
874
+ _ = viewController.view
875
+ viewController.view.translatesAutoresizingMaskIntoConstraints = false
876
+ let modalStartY = window.bounds.height * 0.15
877
+ viewController.view.layer.cornerRadius = 16
878
+ viewController.view.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
879
+ viewController.view.clipsToBounds = true
880
+
881
+ NSLayoutConstraint.activate([
882
+ viewController.view.leadingAnchor.constraint(equalTo: window.leadingAnchor),
883
+ viewController.view.trailingAnchor.constraint(equalTo: window.trailingAnchor),
884
+ viewController.view.topAnchor.constraint(equalTo: window.topAnchor, constant: modalStartY),
885
+ viewController.view.bottomAnchor.constraint(equalTo: window.bottomAnchor)
886
+ ])
887
+
888
+ window.setNeedsLayout()
889
+ window.layoutIfNeeded()
890
+ }
891
+
892
+ private func dismissOverlayWindow() {
893
+ if !Thread.isMainThread {
894
+ DispatchQueue.main.async { [weak self] in
895
+ self?.dismissOverlayWindow()
896
+ }
897
+ return
898
+ }
899
+
900
+ overlayWindow?.isHidden = true
901
+ overlayWindow?.rootViewController = nil
902
+ overlayWindow = nil
903
+ }
904
+
905
+ private func showSuccessScreen() {
906
+ if !Thread.isMainThread {
907
+ DispatchQueue.main.async { [weak self] in
908
+ self?.showSuccessScreen()
909
+ }
910
+ return
911
+ }
912
+
913
+ let viewController = UIViewController()
914
+ viewController.view.backgroundColor = .white
915
+
916
+ let icon = UIImageView()
917
+ icon.image = UIImage(systemName: "checkmark.circle.fill")
918
+ icon.tintColor = .systemGreen
919
+ icon.contentMode = .scaleAspectFit
920
+ icon.translatesAutoresizingMaskIntoConstraints = false
921
+
922
+ let label = UILabel()
923
+ label.text = "ChatGPT Connected"
924
+ label.textColor = .black
925
+ label.font = .systemFont(ofSize: 18, weight: .medium)
926
+ label.textAlignment = .center
927
+
928
+ let stack = UIStackView(arrangedSubviews: [icon, label])
929
+ stack.axis = .vertical
930
+ stack.alignment = .center
931
+ stack.spacing = 12
932
+ stack.translatesAutoresizingMaskIntoConstraints = false
933
+
934
+ viewController.view.addSubview(stack)
935
+ NSLayoutConstraint.activate([
936
+ icon.widthAnchor.constraint(equalToConstant: 60),
937
+ icon.heightAnchor.constraint(equalToConstant: 60),
938
+ stack.centerXAnchor.constraint(equalTo: viewController.view.centerXAnchor),
939
+ stack.centerYAnchor.constraint(equalTo: viewController.view.centerYAnchor)
940
+ ])
941
+
942
+ presentInOverlayWindow(viewController, in: activeScene())
943
+ }
944
+
945
+ private func showErrorScreen(title: String, message: String) {
946
+ if !Thread.isMainThread {
947
+ DispatchQueue.main.async { [weak self] in
948
+ self?.showErrorScreen(title: title, message: message)
949
+ }
950
+ return
951
+ }
952
+
953
+ let viewController = UIViewController()
954
+ viewController.view.backgroundColor = .white
955
+
956
+ let icon = UIImageView()
957
+ icon.image = UIImage(systemName: "exclamationmark.triangle.fill")
958
+ icon.tintColor = .systemOrange
959
+ icon.contentMode = .scaleAspectFit
960
+ icon.translatesAutoresizingMaskIntoConstraints = false
961
+
962
+ let titleLabel = UILabel()
963
+ titleLabel.text = title
964
+ titleLabel.textColor = .black
965
+ titleLabel.font = .systemFont(ofSize: 18, weight: .semibold)
966
+ titleLabel.textAlignment = .center
967
+
968
+ let messageLabel = UILabel()
969
+ messageLabel.text = message
970
+ messageLabel.textColor = .darkGray
971
+ messageLabel.font = .systemFont(ofSize: 14, weight: .regular)
972
+ messageLabel.numberOfLines = 0
973
+ messageLabel.textAlignment = .center
974
+
975
+ let stack = UIStackView(arrangedSubviews: [icon, titleLabel, messageLabel])
976
+ stack.axis = .vertical
977
+ stack.alignment = .center
978
+ stack.spacing = 12
979
+ stack.translatesAutoresizingMaskIntoConstraints = false
980
+
981
+ viewController.view.addSubview(stack)
982
+ NSLayoutConstraint.activate([
983
+ icon.widthAnchor.constraint(equalToConstant: 52),
984
+ icon.heightAnchor.constraint(equalToConstant: 52),
985
+ stack.centerXAnchor.constraint(equalTo: viewController.view.centerXAnchor),
986
+ stack.centerYAnchor.constraint(equalTo: viewController.view.centerYAnchor),
987
+ stack.leadingAnchor.constraint(greaterThanOrEqualTo: viewController.view.leadingAnchor, constant: 24),
988
+ stack.trailingAnchor.constraint(lessThanOrEqualTo: viewController.view.trailingAnchor, constant: -24)
989
+ ])
990
+
991
+ presentInOverlayWindow(viewController, in: activeScene())
992
+ }
993
+ }