@onairosofficial/onairos-capacitor 0.1.4 → 0.1.5

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.
Files changed (88) hide show
  1. package/OnairosofficialOnairosCapacitor.podspec +1 -1
  2. package/README.md +1 -1
  3. package/dist/onairos.capacitor.esm.js +509 -1
  4. package/dist/onairos.capacitor.esm.turbopack.js +509 -1
  5. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosChatGPTNativePlugin.swift +187 -945
  6. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosRNScrapers.swift +1800 -0
  7. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosSpotifyNativePlugin.swift +180 -629
  8. package/onairos.d.ts +24 -0
  9. package/package.json +5 -2
  10. package/src/assets/connectors/Linkedinicon.png +0 -0
  11. package/src/assets/connectors/Redditicon.png +0 -0
  12. package/src/assets/connectors/YouTubeicon2.png +0 -0
  13. package/src/assets/connectors/chatgpt.png +0 -0
  14. package/src/assets/connectors/claude.png +0 -0
  15. package/src/assets/connectors/instagram.png +0 -0
  16. package/src/assets/connectors/netflix.png +0 -0
  17. package/src/assets/connectors/pinterest.png +0 -0
  18. package/src/assets/connectors/sephora.png +0 -0
  19. package/src/assets/connectors/spotify.png +0 -0
  20. package/src/assets/connectors/tiktok.png +0 -0
  21. package/src/assets/permissions/onairos.png +0 -0
  22. package/src/assets/permissions/personalization.png +0 -0
  23. package/src/assets/permissions/public-profile-person.png +0 -0
  24. package/src/assets/permissions/raw-memories.png +0 -0
  25. package/src/capacitorConnectorCatalog.js +2 -6
  26. package/src/components/DataRequest.jsx +96 -532
  27. package/src/components/PinSetup.jsx +39 -226
  28. package/src/components/SDKDesignPreview.jsx +33 -0
  29. package/src/components/SessionUserBar.jsx +2 -1
  30. package/src/components/UniversalOnboarding.jsx +190 -423
  31. package/src/components/WelcomeScreen.jsx +7 -0
  32. package/src/components/parity/NativeConnections.jsx +136 -0
  33. package/src/components/parity/NativeScreens.jsx +48 -0
  34. package/src/components/ui/PageLayout.jsx +7 -3
  35. package/src/nativeImport/ConnectorLoading.jsx +13 -0
  36. package/src/nativeImport/CustomImportSession.js +115 -0
  37. package/src/nativeImport/ImportIcon.jsx +29 -0
  38. package/src/nativeImport/ImportProgress.jsx +24 -0
  39. package/src/nativeImport/ImportStatus.jsx +9 -0
  40. package/src/nativeImport/NativeChatImport.jsx +28 -0
  41. package/src/nativeImport/NativeImportSession.js +123 -0
  42. package/src/nativeImport/NativeScraperImport.jsx +57 -0
  43. package/src/nativeImport/SmartFilter.jsx +28 -0
  44. package/src/nativeImport/customPayload.js +37 -0
  45. package/src/nativeImport/netflixExport.js +30 -0
  46. package/src/nativeImport/netflixHistory.js +28 -0
  47. package/src/nativeImport/netflixSession.js +59 -0
  48. package/src/nativeImport/rawHandoff.js +7 -0
  49. package/src/nativeImport/rn/config/api.js +5 -0
  50. package/src/nativeImport/rn/services/apiKeyService.js +2 -0
  51. package/src/nativeImport/rn/services/hingePayload.js +37 -0
  52. package/src/nativeImport/rn/services/nativeConversationImport.js +138 -0
  53. package/src/nativeImport/rn/services/nativeFileTransfer.js +127 -0
  54. package/src/nativeImport/rn/services/nativeRawRedaction.js +136 -0
  55. package/src/nativeImport/rn/services/netflixPayload.js +70 -0
  56. package/src/nativeImport/rn/services/rawMemoryPolicy.js +38 -0
  57. package/src/nativeImport/rn/services/sephoraPayload.js +166 -0
  58. package/src/nativeImport/rn/services/spotifyPayload.js +99 -0
  59. package/src/nativeImport/rn/source-manifest.json +45 -0
  60. package/src/nativeImport/rn/utils/importedFiles.js +74 -0
  61. package/src/nativeImport/rn/utils/nativeImportDates.js +45 -0
  62. package/src/nativeImport/rn/utils/nativeImportFileReceiver.js +51 -0
  63. package/src/nativeImport/rn/utils/nativeImportMetadata.js +74 -0
  64. package/src/nativeImport/rn/utils/nativeImportTopics.js +56 -0
  65. package/src/nativeImport/rn/utils/rawExportDelivery.js +12 -0
  66. package/src/nativeImport/rn/utils/webviewScripts/chatgptDiscovery.js +99 -0
  67. package/src/nativeImport/rn/utils/webviewScripts/claude.js +349 -0
  68. package/src/nativeImport/rn/utils/webviewScripts/gemini.js +356 -0
  69. package/src/nativeImport/rn/utils/webviewScripts/hinge.js +375 -0
  70. package/src/nativeImport/rn/utils/webviewScripts/instagram.js +152 -0
  71. package/src/nativeImport/rn/utils/webviewScripts/linkedin.js +825 -0
  72. package/src/nativeImport/rn/utils/webviewScripts/nativeChatGPTImport.js +202 -0
  73. package/src/nativeImport/rn/utils/webviewScripts/nativeChatGPTSession.js +63 -0
  74. package/src/nativeImport/rn/utils/webviewScripts/nativeImportFiles.js +132 -0
  75. package/src/nativeImport/rn/utils/webviewScripts/nativeImportProviders.js +80 -0
  76. package/src/nativeImport/rn/utils/webviewScripts/nativeLoginViewport.js +28 -0
  77. package/src/nativeImport/rn/utils/webviewScripts/netflix.js +257 -0
  78. package/src/nativeImport/rn/utils/webviewScripts/sephora.js +862 -0
  79. package/src/nativeImport/rn/utils/webviewScripts/sephoraSession.js +160 -0
  80. package/src/nativeImport/rn/utils/webviewScripts/spotify.js +1868 -0
  81. package/src/nativeImport/rn/utils/webviewScripts/telegram.js +630 -0
  82. package/src/nativeImport/rn/utils/webviewScripts/tiktok.js +2920 -0
  83. package/src/onairos.core.jsx +3 -0
  84. package/src/onairosButton.jsx +23 -17
  85. package/src/styles/onairos-rn-parity.css +175 -0
  86. package/src/styles/tailwind.capacitor.css +4 -0
  87. package/src/utils/nativeConnectorSession.js +18 -0
  88. package/src/utils/parityPolicy.js +41 -0
@@ -2,992 +2,234 @@ import UIKit
2
2
  import Capacitor
3
3
  import WebKit
4
4
 
5
+ /// Private provider browser transport. Selection, extraction and receipt handling
6
+ /// use the same scripts/services as RN; this bridge never receives provider tokens.
5
7
  @objc(OnairosChatGPTNativePlugin)
6
- class OnairosChatGPTNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDelegate, WKHTTPCookieStoreObserver, WKScriptMessageHandler {
8
+ class OnairosChatGPTNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler {
7
9
  public let identifier = "OnairosChatGPTNativePlugin"
8
10
  public let jsName = "OnairosChatGPTNative"
9
11
  public let pluginMethods: [CAPPluginMethod] = [
10
- CAPPluginMethod(name: "connectChatGPTNative", returnType: CAPPluginReturnPromise),
12
+ CAPPluginMethod(name: "startNativeImport", returnType: CAPPluginReturnPromise),
13
+ CAPPluginMethod(name: "runNativeImportScript", returnType: CAPPluginReturnPromise),
14
+ CAPPluginMethod(name: "setNativeImportVisible", returnType: CAPPluginReturnPromise),
15
+ CAPPluginMethod(name: "finishNativeImport", returnType: CAPPluginReturnPromise),
11
16
  CAPPluginMethod(name: "closeChatGPTConnector", returnType: CAPPluginReturnPromise),
12
- CAPPluginMethod(name: "openChatGPTConnector", returnType: CAPPluginReturnPromise)
17
+ CAPPluginMethod(name: "connectChatGPTNative", returnType: CAPPluginReturnPromise)
13
18
  ]
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
19
+ private var overlay: UIWindow?
20
+ private var browser: WKWebView?
21
+ private var navigationObservation: NSKeyValueObservation?
22
+ private var platform = "chatgpt"
23
+ private var sessionScript = ""
24
+ private var sessionId = ""
25
+ private var recovered = false
26
+ private var introPending = false
27
+ private var introStarted = Date()
28
+ private let providers: [String:(origin:String, login:String, name:String, prefix:String)] = [
29
+ "chatgpt":("https://chatgpt.com","https://chatgpt.com/auth/login","ChatGPT",""),
30
+ "claude":("https://claude.ai","https://claude.ai/login","Claude",""),
31
+ "netflix":("https://www.netflix.com","https://www.netflix.com/login","Netflix","NETFLIX"),
32
+ "sephora":("https://www.sephora.com","https://www.sephora.com","Sephora","SEPHORA"),
33
+ "instagram-data":("https://www.instagram.com","https://www.instagram.com/accounts/login/","Instagram","INSTAGRAM"),
34
+ "hinge":("https://hinge.co","https://hinge.co","Hinge","HINGE")
35
+ ]
36
+ private var origin: String { providers[platform]!.origin }
37
+ private var loginURL: String { providers[platform]!.login }
38
+ private func allowedOrigin(_ value:String) -> Bool { value == origin || (platform == "instagram-data" && value == "https://instagram.com") }
33
39
 
34
40
  @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
- }
41
+ call.reject("This connector requires Smart Filter. Update the JavaScript SDK and native package together.", "SMART_FILTER_REQUIRED")
104
42
  }
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()
43
+ @objc func startNativeImport(_ call: CAPPluginCall) {
44
+ DispatchQueue.main.async { [weak self] in self?.beginImport(call) }
171
45
  }
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
- }
46
+ private func beginImport(_ call: CAPPluginCall) {
47
+ guard browser == nil else { call.reject("An import is already open."); return }
48
+ guard let provider = call.getString("platform"), providers[provider] != nil,
49
+ let script = call.getString("sessionScript"), script.utf8.count < 1_000_000,
50
+ let id = call.getString("sessionId"), !id.isEmpty else {
51
+ call.reject("Invalid private import configuration."); return
229
52
  }
53
+ platform = provider; sessionScript = script; sessionId = id; recovered = false
54
+ introPending = call.getBool("useHostIntro") ?? false; introStarted = Date()
55
+ present(call)
230
56
  }
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)
57
+ private func present(_ call: CAPPluginCall) {
58
+ guard let scene = bridge?.viewController?.view.window?.windowScene ?? UIApplication.shared.connectedScenes.compactMap({$0 as? UIWindowScene}).first(where: {$0.activationState == .foregroundActive}) else {
59
+ call.reject("No active window for the connector."); return
242
60
  }
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
61
+ let content = WKUserContentController()
62
+ content.add(self, name: "onairosPrivateImport")
63
+ if platform == "netflix" {
64
+ content.addUserScript(WKUserScript(source: OnairosRNScrapers.netflixBrowserScript, injectionTime: .atDocumentStart, forMainFrameOnly: true))
252
65
  }
253
-
254
- let contentController = WKUserContentController()
255
- contentController.add(self, name: "bridgeCallback")
256
-
66
+ let shim = "window.ReactNativeWebView={postMessage:function(raw){window.webkit.messageHandlers.onairosPrivateImport.postMessage(raw);}};"
67
+ content.addUserScript(WKUserScript(source: shim + sessionScript, injectionTime: .atDocumentStart, forMainFrameOnly: true))
257
68
  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)
69
+ config.websiteDataStore = .nonPersistent()
70
+ config.userContentController = content
71
+ config.preferences.javaScriptCanOpenWindowsAutomatically = true
72
+ let view = WKWebView(frame: .zero, configuration: config)
73
+ // RN requires desktop Netflix pages: mobile pages redirect to the app
74
+ // and do not expose the viewing-history markup used by its scraper.
75
+ if platform == "netflix" { view.customUserAgent = OnairosRNScrapers.netflixUserAgent }
76
+ view.navigationDelegate = self; view.uiDelegate = self
77
+ view.translatesAutoresizingMaskIntoConstraints = false
78
+ #if DEBUG
79
+ if #available(iOS 16.4, *) { view.isInspectable = true }
80
+ #endif
81
+ let controller = UIViewController()
82
+ controller.view.backgroundColor = .white
83
+ let close = UIButton(type: .system)
84
+ close.setTitle("Close", for: .normal)
85
+ close.accessibilityLabel = "Close \(providers[platform]!.name)"
86
+ close.addTarget(self, action: #selector(cancelFromUI), for: .touchUpInside)
87
+ close.translatesAutoresizingMaskIntoConstraints = false
88
+ let title = UILabel(); title.text = providers[platform]!.name
89
+ title.font = .systemFont(ofSize: 17, weight: .semibold); title.translatesAutoresizingMaskIntoConstraints = false
90
+ controller.view.addSubview(view); controller.view.addSubview(close); controller.view.addSubview(title)
286
91
  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)
92
+ close.leadingAnchor.constraint(equalTo: controller.view.leadingAnchor, constant: 16),
93
+ close.topAnchor.constraint(equalTo: controller.view.safeAreaLayoutGuide.topAnchor),close.heightAnchor.constraint(equalToConstant: 44),
94
+ title.centerXAnchor.constraint(equalTo: controller.view.centerXAnchor),title.centerYAnchor.constraint(equalTo: close.centerYAnchor),
95
+ view.topAnchor.constraint(equalTo: close.bottomAnchor),view.bottomAnchor.constraint(equalTo: controller.view.bottomAnchor),
96
+ view.leadingAnchor.constraint(equalTo: controller.view.leadingAnchor),view.trailingAnchor.constraint(equalTo: controller.view.trailingAnchor)
295
97
  ])
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.")
98
+ let window = UIWindow(windowScene: scene); window.windowLevel = .alert + 1
99
+ window.rootViewController = controller; overlay = window; browser = view
100
+ // RN WebView reports history navigation as well as document loads.
101
+ navigationObservation = view.observe(\.url, options: [.new]) { [weak self] view, _ in
102
+ guard let self = self, self.browser === view, !view.isLoading else { return }
103
+ self.reportNavigation(view)
318
104
  }
105
+ if !introPending { window.makeKeyAndVisible() }; view.load(URLRequest(url: URL(string: loginURL)!))
106
+ call.resolve(["opened": true])
319
107
  }
320
-
321
- private func updateProgress(_ fraction: Float, message: String) {
108
+ @objc func runNativeImportScript(_ call: CAPPluginCall) {
322
109
  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
- }
110
+ guard let self = self, let id = call.getString("sessionId"), id == self.sessionId,
111
+ let script = call.getString("script"), script.utf8.count < 1_000_000,
112
+ let browser = self.browser, self.allowedOrigin(Self.origin(browser.url)) else {
113
+ call.reject("The provider session is not ready."); return
367
114
  }
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
115
+ browser.evaluateJavaScript(script) { _, error in
116
+ if error != nil { call.reject("Could not run the provider import.") } else { call.resolve() }
393
117
  }
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
118
  }
407
119
  }
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
-
120
+ @objc func setNativeImportVisible(_ call: CAPPluginCall) {
592
121
  DispatchQueue.main.async { [weak self] in
593
- self?.navigateToBridgeForUpload()
122
+ guard let self = self, call.getString("sessionId") == self.sessionId else { call.reject("Stale import session."); return }
123
+ let visible = call.getBool("visible") ?? false
124
+ self.introPending = false
125
+ self.overlay?.isHidden = !visible
126
+ if visible { self.overlay?.makeKeyAndVisible() } else { self.bridge?.viewController?.view.window?.makeKey() }
127
+ call.resolve()
594
128
  }
595
129
  }
596
-
597
- private func navigateToBridgeForUpload() {
598
- guard !isFlowCancelled else { return }
599
- if bridgePageReady {
600
- injectBridgeUploadScriptIfReady()
601
- return
130
+ @objc func finishNativeImport(_ call: CAPPluginCall) {
131
+ DispatchQueue.main.async { [weak self] in
132
+ guard let self = self, call.getString("sessionId") == self.sessionId else { call.reject("Stale import session."); return }
133
+ self.tearDown(); call.resolve()
602
134
  }
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
135
  }
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)\""
136
+ @objc func closeChatGPTConnector(_ call: CAPPluginCall) {
137
+ DispatchQueue.main.async { [weak self] in self?.cancelFromUI(); call.resolve() }
138
+ }
139
+ @objc private func cancelFromUI() {
140
+ notifyListeners("nativeImportLifecycle", data: ["status":"cancelled", "sessionId":sessionId])
141
+ tearDown()
142
+ }
143
+ private func tearDown() {
144
+ introPending = false
145
+ navigationObservation = nil
146
+ browser?.stopLoading()
147
+ browser?.configuration.userContentController.removeScriptMessageHandler(forName: "onairosPrivateImport")
148
+ browser?.configuration.userContentController.removeAllUserScripts()
149
+ browser?.navigationDelegate = nil; browser?.uiDelegate = nil
150
+ overlay?.isHidden = true; overlay?.rootViewController = nil
151
+ browser = nil; overlay = nil; sessionScript = ""; sessionId = ""
152
+ bridge?.viewController?.view.window?.makeKey()
153
+ }
154
+ private static func origin(_ url: URL?) -> String {
155
+ guard let url = url, url.scheme == "https", let host = url.host, url.user == nil, url.password == nil, url.port == nil else { return "" }
156
+ return "https://\(host)"
718
157
  }
719
-
720
158
  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
159
+ guard message.webView === browser, message.frameInfo.isMainFrame, !sessionId.isEmpty,
160
+ let text = message.body as? String, text.utf8.count <= 4_000_000,
161
+ let data = text.data(using: .utf8), let value = try? JSONSerialization.jsonObject(with: data) as? [String:Any] else { return }
162
+ let security = message.frameInfo.securityOrigin
163
+ let sender = "\(security.protocol)://\(security.host)"
164
+ let channel = value["channel"] as? String ?? ""
165
+ guard security.protocol == "https", security.port == 0 || security.port == 443 else { return }
166
+ let prefix = providers[platform]!.prefix
167
+ if prefix.isEmpty {
168
+ guard ["onairos-native-session", "onairos-native-import", "onairos-native-signout"].contains(channel),
169
+ channel == "onairos-native-session" || allowedOrigin(sender) else { return }
728
170
  } 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
171
+ let type = value["type"] as? String ?? ""
172
+ guard allowedOrigin(sender), ["\(prefix)_AUTH_STATE","\(prefix)_EXPORT_PROGRESS","\(prefix)_EXPORT_COMPLETE","\(prefix)_EXPORT_ERROR"].contains(type) else { return }
736
173
  }
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
174
+ notifyListeners("nativeImportMessage", data: ["raw":text,"origin":sender,"sessionId":sessionId])
761
175
  }
762
-
763
176
  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)
177
+ guard webView === browser else { return }
178
+ if introPending {
179
+ let id = sessionId
180
+ let remaining = max(0, 2.6 - Date().timeIntervalSince(introStarted))
181
+ DispatchQueue.main.asyncAfter(deadline: .now() + remaining) { [weak self] in
182
+ guard let self = self, self.introPending, self.sessionId == id else { return }
183
+ self.introPending = false
184
+ self.overlay?.alpha = 0; self.overlay?.makeKeyAndVisible()
185
+ UIView.animate(withDuration: 0.32) { self.overlay?.alpha = 1 }
186
+ }
187
+ }
188
+ webView.evaluateJavaScript(sessionScript, completionHandler: nil)
189
+ reportNavigation(webView)
190
+ }
191
+ private func reportNavigation(_ webView: WKWebView) {
192
+ guard webView === browser, !sessionId.isEmpty else { return }
193
+ notifyListeners("nativeImportLifecycle", data:["status":"navigation","sessionId":sessionId,"origin":Self.origin(webView.url),"path":webView.url?.path ?? ""])
194
+ }
195
+ func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
196
+ guard webView === browser, let url = navigationAction.request.url, url.user == nil, url.password == nil else {
197
+ decisionHandler(.cancel); return
198
+ }
199
+ if url.absoluteString == "about:blank" { decisionHandler(.allow); return }
200
+ guard url.scheme == "https" else {
201
+ decisionHandler(.cancel)
202
+ // Keep Netflix's app CTA in the authenticated web session.
203
+ if platform == "netflix", ["nflx", "netflix"].contains(url.scheme?.lowercased() ?? ""), allowedOrigin(Self.origin(webView.url)) {
204
+ webView.evaluateJavaScript("window.location.assign('https://www.netflix.com/browse');true;", completionHandler:nil)
860
205
  }
861
206
  return
862
207
  }
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
- }
208
+ // Match RN: tapped HTTPS universal links are re-issued from the page,
209
+ // which avoids handing the authenticated connector to the Netflix app.
210
+ if platform == "netflix", navigationAction.navigationType == .linkActivated,
211
+ navigationAction.targetFrame?.isMainFrame != false,
212
+ let data = try? JSONEncoder().encode(url.absoluteString), let quoted = String(data:data,encoding:.utf8) {
213
+ decisionHandler(.cancel)
214
+ webView.evaluateJavaScript("window.location.assign(" + quoted + ");true;", completionHandler:nil)
897
215
  return
898
216
  }
899
-
900
- overlayWindow?.isHidden = true
901
- overlayWindow?.rootViewController = nil
902
- overlayWindow = nil
217
+ decisionHandler(.allow)
903
218
  }
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())
219
+ func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
220
+ if let url = navigationAction.request.url, url.scheme == "https", url.user == nil, url.password == nil { webView.load(navigationAction.request) }
221
+ return nil
943
222
  }
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())
223
+ func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
224
+ guard webView === browser else { return }
225
+ let failure = error as NSError
226
+ // A cancelled/policy-reissued link is not a failed login or lost session.
227
+ if failure.code == NSURLErrorCancelled || (failure.domain == "WebKitErrorDomain" && failure.code == 102) { return }
228
+ notifyListeners("nativeImportLifecycle", data:["status":"error","sessionId":sessionId,"message":"The sign-in page could not load. Please retry.","nativeCode":failure.code])
229
+ tearDown()
230
+ }
231
+ func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
232
+ if !recovered && overlay?.isHidden == false { recovered = true; webView.reload() }
233
+ else { notifyListeners("nativeImportLifecycle", data: ["status":"error","sessionId":sessionId,"message":"The provider browser ended. Please retry."]); tearDown() }
992
234
  }
993
235
  }