@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
@@ -3,7 +3,7 @@ import Capacitor
3
3
  import WebKit
4
4
 
5
5
  @objc(OnairosSpotifyNativePlugin)
6
- class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDelegate, WKScriptMessageHandler {
6
+ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler {
7
7
  public let identifier = "OnairosSpotifyNativePlugin"
8
8
  public let jsName = "OnairosSpotifyNative"
9
9
  public let pluginMethods: [CAPPluginMethod] = [
@@ -15,7 +15,6 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
15
15
  private let defaultBackendBaseURL = "https://api2.onairos.uk"
16
16
  private let spotifyPlayerURL = "https://open.spotify.com/"
17
17
  private let spotifyLoginURL = "https://accounts.spotify.com/login?continue=https%3A%2F%2Fopen.spotify.com%2F"
18
- private let spotifyUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36"
19
18
 
20
19
  private var overlayWindow: UIWindow?
21
20
  private var spotifyWebView: WKWebView?
@@ -30,8 +29,19 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
30
29
  private var backendBaseURL = ""
31
30
  private var exportFinished = false
32
31
  private var injectionAttempts = 0
32
+ private var extractionRunning = false
33
+ private var useHostImportUI = false
34
+ private var generation = UUID()
35
+ private var sessionId = ""
36
+ private var introPending = false
37
+ private var introStarted = Date()
38
+ private var networkTask: URLSessionDataTask?
33
39
 
34
40
  @objc func connectSpotifyNative(_ call: CAPPluginCall) {
41
+ DispatchQueue.main.async { [weak self] in self?.beginConnection(call) }
42
+ }
43
+
44
+ private func beginConnection(_ call: CAPPluginCall) {
35
45
  if pendingCall != nil {
36
46
  call.reject("Spotify connection is already in progress.")
37
47
  return
@@ -43,6 +53,10 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
43
53
  return
44
54
  }
45
55
 
56
+ generation = UUID()
57
+ sessionId = call.getString("sessionId") ?? generation.uuidString
58
+ useHostImportUI = call.getBool("useHostImportUI") ?? false
59
+ introPending = useHostImportUI; introStarted = Date()
46
60
  pendingCall = call
47
61
  bridge?.saveCall(call)
48
62
  pendingJWTToken = jwtToken
@@ -51,16 +65,20 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
51
65
  .trimmingCharacters(in: CharacterSet(charactersIn: "/").union(.whitespacesAndNewlines))
52
66
  exportFinished = false
53
67
  injectionAttempts = 0
68
+ extractionRunning = false
54
69
 
55
70
  emitStatus("opening", message: "Opening Spotify...")
56
- DispatchQueue.main.async { [weak self] in
57
- self?.presentSpotifyWebView(in: self?.activeScene())
58
- }
71
+ presentSpotifyWebView(in: activeScene())
59
72
  }
60
73
 
61
74
  @objc func closeSpotifyConnector(_ call: CAPPluginCall) {
62
- cancelFlow(message: nil, rejectPending: false)
63
- call.resolve()
75
+ DispatchQueue.main.async { [weak self] in
76
+ guard let self = self else { call.resolve(); return }
77
+ // A disposed JS component must not close a newer attempt.
78
+ if let id = call.getString("sessionId"), id != self.sessionId { call.resolve(); return }
79
+ self.cancelFlow(message: "Spotify connection canceled.", rejectPending: true)
80
+ call.resolve()
81
+ }
64
82
  }
65
83
 
66
84
  @objc func openSpotifyConnector(_ call: CAPPluginCall) {
@@ -82,15 +100,18 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
82
100
  config.websiteDataStore = .default()
83
101
  config.userContentController = userContentController
84
102
  config.userContentController.addUserScript(WKUserScript(
85
- source: Self.spotifyTokenInterceptorScript,
103
+ // Auth/challenge pages must retain their real browser environment.
104
+ // Token hooks are only needed after Spotify reaches the web player.
105
+ source: "if (window.location.origin === 'https://open.spotify.com') {" + OnairosRNScrapers.spotifyTokenInterceptor + "}",
86
106
  injectionTime: .atDocumentStart,
87
- forMainFrameOnly: false
107
+ forMainFrameOnly: true
88
108
  ))
89
109
  config.allowsInlineMediaPlayback = true
110
+ config.preferences.javaScriptCanOpenWindowsAutomatically = true
90
111
 
91
112
  let webView = WKWebView(frame: .zero, configuration: config)
92
113
  webView.navigationDelegate = self
93
- webView.customUserAgent = spotifyUserAgent
114
+ webView.uiDelegate = self
94
115
  webView.translatesAutoresizingMaskIntoConstraints = false
95
116
  webView.allowsBackForwardNavigationGestures = true
96
117
 
@@ -120,13 +141,13 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
120
141
  label.layer.zPosition = 999
121
142
 
122
143
  let loadingOverlay = UIView()
123
- loadingOverlay.backgroundColor = UIColor.black.withAlphaComponent(0.88)
144
+ loadingOverlay.backgroundColor = UIColor(red:0.984,green:0.984,blue:0.980,alpha:1)
124
145
  loadingOverlay.translatesAutoresizingMaskIntoConstraints = false
125
146
  loadingOverlay.isHidden = true
126
147
  loadingOverlay.layer.zPosition = 998
127
148
 
128
149
  let loadingPanel = UIView()
129
- loadingPanel.backgroundColor = UIColor(red: 0.07, green: 0.08, blue: 0.07, alpha: 0.96)
150
+ loadingPanel.backgroundColor = .white
130
151
  loadingPanel.layer.cornerRadius = 24
131
152
  loadingPanel.layer.borderWidth = 1
132
153
  loadingPanel.layer.borderColor = UIColor.white.withAlphaComponent(0.14).cgColor
@@ -144,14 +165,14 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
144
165
 
145
166
  let titleLabel = UILabel()
146
167
  titleLabel.text = "Connecting Spotify"
147
- titleLabel.textColor = .white
168
+ titleLabel.textColor = .darkGray
148
169
  titleLabel.font = UIFont.systemFont(ofSize: 24, weight: .bold)
149
170
  titleLabel.textAlignment = .center
150
171
  titleLabel.translatesAutoresizingMaskIntoConstraints = false
151
172
 
152
173
  let statusLabel = UILabel()
153
174
  statusLabel.text = "Preparing import..."
154
- statusLabel.textColor = UIColor.white.withAlphaComponent(0.78)
175
+ statusLabel.textColor = .darkGray
155
176
  statusLabel.font = UIFont.systemFont(ofSize: 15, weight: .medium)
156
177
  statusLabel.textAlignment = .center
157
178
  statusLabel.numberOfLines = 3
@@ -234,7 +255,7 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
234
255
  }
235
256
 
236
257
  func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
237
- guard !exportFinished else { return }
258
+ guard webView === spotifyWebView, !exportFinished else { return }
238
259
  guard let url = webView.url else { return }
239
260
 
240
261
  if isSpotifyLoginURL(url) {
@@ -247,6 +268,22 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
247
268
  scheduleExtractionAttempt()
248
269
  }
249
270
 
271
+ func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
272
+ guard webView === spotifyWebView else { return nil }
273
+ if let url = navigationAction.request.url, url.scheme == "https", url.user == nil, url.password == nil { webView.load(navigationAction.request) }
274
+ return nil
275
+ }
276
+
277
+ func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
278
+ guard webView === spotifyWebView, (error as NSError).code != NSURLErrorCancelled else { return }
279
+ finishWithError("Spotify sign-in could not load. Please retry.")
280
+ }
281
+
282
+ func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
283
+ guard webView === spotifyWebView, pendingCall != nil else { return }
284
+ finishWithError("Spotify’s browser closed unexpectedly. Please retry.")
285
+ }
286
+
250
287
  private func isSpotifyLoginURL(_ url: URL) -> Bool {
251
288
  let host = url.host?.lowercased() ?? ""
252
289
  let absolute = url.absoluteString.lowercased()
@@ -268,25 +305,32 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
268
305
  finishWithError("Timed out waiting for Spotify web player login.")
269
306
  return
270
307
  }
308
+ let requestGeneration = generation
271
309
  DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in
272
- self?.injectSpotifyExportScript()
310
+ guard let self = self, self.generation == requestGeneration, self.pendingCall != nil else { return }
311
+ self.injectSpotifyExportScript()
273
312
  }
274
313
  }
275
314
 
276
315
  private func injectSpotifyExportScript() {
277
- guard !exportFinished, let webView = spotifyWebView else { return }
278
- webView.evaluateJavaScript(Self.spotifyExportScript) { [weak self] _, error in
279
- if let error = error {
280
- self?.emitStatus("waiting_for_login", message: error.localizedDescription)
281
- }
282
- if self?.exportFinished == false {
316
+ guard !exportFinished, !extractionRunning, let webView = spotifyWebView else { return }
317
+ extractionRunning = true
318
+ let requestGeneration = generation
319
+ webView.evaluateJavaScript(OnairosRNScrapers.spotifyExport) { [weak self] _, error in
320
+ guard self?.generation == requestGeneration, self?.spotifyWebView === webView else { return }
321
+ if error != nil {
322
+ self?.extractionRunning = false
283
323
  self?.scheduleExtractionAttempt()
284
324
  }
285
325
  }
286
326
  }
287
327
 
288
328
  func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
289
- guard message.name == "onairosSpotify" else { return }
329
+ guard message.webView === spotifyWebView, pendingCall != nil,
330
+ message.name == "onairosSpotify", message.frameInfo.isMainFrame,
331
+ message.frameInfo.securityOrigin.protocol == "https",
332
+ message.frameInfo.securityOrigin.host == "open.spotify.com",
333
+ !exportFinished else { return }
290
334
 
291
335
  let raw: Any
292
336
  if let body = message.body as? String,
@@ -301,13 +345,15 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
301
345
  let type = payload["type"] as? String ?? ""
302
346
 
303
347
  if type == "SPOTIFY_EXPORT_PROGRESS" {
304
- emitStatus(payload["stage"] as? String ?? "progress", message: payload["message"] as? String)
348
+ emitStatus("extracting", message: payload["message"] as? String, progress: payload["progress"] as? Double)
305
349
  return
306
350
  }
307
351
 
308
352
  if type == "SPOTIFY_EXPORT_ERROR" {
309
- let recoverable = (payload["recoverable"] as? Bool) ?? false
310
353
  let message = payload["message"] as? String ?? "Spotify export failed."
354
+ let recoverable = (payload["recoverable"] as? Bool) == true || message.contains("No authentication token") || message == "Page not ready"
355
+ extractionRunning = false
356
+ if recoverable { scheduleExtractionAttempt() }
311
357
  emitStatus(recoverable ? "waiting_for_login" : "error", message: message)
312
358
  if !recoverable {
313
359
  finishWithError(message)
@@ -315,7 +361,13 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
315
361
  return
316
362
  }
317
363
 
364
+ if type == "SPOTIFY_EXPORT_NATIVE_FALLBACK" {
365
+ exportFinished = true
366
+ fetchNativeFallback(payload)
367
+ return
368
+ }
318
369
  if type == "SPOTIFY_EXPORT_COMPLETE" {
370
+ guard payload["success"] as? Bool == true else { finishWithError("Spotify did not confirm extraction."); return }
319
371
  exportFinished = true
320
372
  emitStatus("uploading", message: "Uploading Spotify data...")
321
373
  let extracted = payload["data"] as? [String: Any] ?? [:]
@@ -324,13 +376,28 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
324
376
  }
325
377
 
326
378
  private func uploadSpotifyData(_ extracted: [String: Any]) {
379
+ if useHostImportUI {
380
+ guard let call = pendingCall else { return }
381
+ pendingCall = nil
382
+ cleanup()
383
+ call.resolve(["extracted":true,"data":extracted])
384
+ return
385
+ }
327
386
  guard let url = URL(string: "\(backendBaseURL)/platform-data/store") else {
328
387
  finishWithError("Invalid Onairos backend URL.")
329
388
  return
330
389
  }
331
390
 
332
- let data = extracted["data"] as? [String: Any] ?? extracted
333
- let summary = extracted["summary"] as? [String: Any] ?? [:]
391
+ let fields = ["trackId","name","artists","album","albumId","popularity","duration","playedAt","savedAt","imageUrl","previewUrl","explicit"]
392
+ func tracks(_ value:Any?) -> [[String:Any]] {
393
+ (value as? [[String:Any]] ?? []).filter { ($0["trackId"] as? String)?.isEmpty == false && ($0["name"] as? String)?.isEmpty == false }.map { item in item.filter { fields.contains($0.key) } }
394
+ }
395
+ let saved = tracks(extracted["savedTracks"])
396
+ let recent = saved.isEmpty ? tracks(extracted["tracks"]) : []
397
+ guard !saved.isEmpty || !recent.isEmpty else { finishWithError("No Spotify activity was available to import."); return }
398
+ let profile = (extracted["profile"] as? [String:Any] ?? [:]).filter { ["userId","displayName","country","subscription","followers"].contains($0.key) }
399
+ let data:[String:Any] = ["savedTracks":saved,"recentlyPlayed":recent,"topTracks":[],"topArtists":[],"topItems":["tracks":[],"artists":[],"timeRange":"medium_term"],"playlists":[],"savedAlbums":[],"profile":profile,"spotifyUserId":extracted["userId"] ?? profile["userId"] ?? ""]
400
+ let summary:[String:Any] = ["savedTracksCount":saved.count,"recentlyPlayedCount":recent.count,"topTracksCount":0,"topArtistsCount":0,"playlistCount":0,"savedAlbumsCount":0]
334
401
  let body: [String: Any] = [
335
402
  "platform": "mobile-spotify",
336
403
  "dataType": "streaming",
@@ -362,7 +429,10 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
362
429
  }
363
430
  request.httpBody = bodyData
364
431
 
365
- URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
432
+ let requestGeneration = generation
433
+ networkTask = URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
434
+ DispatchQueue.main.async {
435
+ guard self?.pendingCall != nil, self?.generation == requestGeneration else { return }
366
436
  if let error = error {
367
437
  self?.finishWithError(error.localizedDescription)
368
438
  return
@@ -370,13 +440,54 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
370
440
 
371
441
  let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0
372
442
  guard (200..<300).contains(statusCode) else {
373
- let text = data.flatMap { String(data: $0, encoding: .utf8) } ?? ""
374
- self?.finishWithError("Spotify upload failed (\(statusCode)): \(text.prefix(180))")
443
+ self?.finishWithError("Spotify upload failed (\(statusCode)).")
375
444
  return
376
445
  }
377
446
 
447
+ guard let data = data, let result = try? JSONSerialization.jsonObject(with: data) as? [String:Any], result["success"] as? Bool == true else {
448
+ self?.finishWithError("Spotify upload did not confirm success."); return
449
+ }
378
450
  self?.finishWithSuccess(summary: summary)
379
- }.resume()
451
+ }
452
+ }
453
+ networkTask?.resume()
454
+ }
455
+
456
+ private func fetchNativeFallback(_ payload: [String:Any]) {
457
+ guard let token = payload["accessToken"] as? String, !token.isEmpty,
458
+ let url = URL(string:"https://api.spotify.com/v1/me/player/recently-played?limit=20") else {
459
+ finishWithError("Spotify could not start its native fallback."); return
460
+ }
461
+ var request = URLRequest(url:url); request.timeoutInterval = 30
462
+ request.setValue("Bearer \(token)",forHTTPHeaderField:"Authorization")
463
+ request.setValue("application/json",forHTTPHeaderField:"Accept")
464
+ let requestGeneration = generation
465
+ networkTask = URLSession.shared.dataTask(with:request) { [weak self] data,response,error in
466
+ DispatchQueue.main.async {
467
+ guard let self = self, self.pendingCall != nil, self.generation == requestGeneration else { return }
468
+ guard error == nil, let http=response as? HTTPURLResponse, (200..<300).contains(http.statusCode),
469
+ let data=data, let body=try? JSONSerialization.jsonObject(with:data) as? [String:Any],
470
+ let items=body["items"] as? [[String:Any]] else {
471
+ self.finishWithError("Spotify's native fallback could not load listening history."); return
472
+ }
473
+ let tracks:[[String:Any]]=items.compactMap { item in
474
+ guard let track=item["track"] as? [String:Any], let name=track["name"] as? String else { return nil }
475
+ let album=track["album"] as? [String:Any] ?? [:]
476
+ let id=track["id"] as? String ?? ""
477
+ var value:[String:Any] = ["name":name,"trackId":id,"uri":track["uri"] as? String ?? "spotify:track:\(id)",
478
+ "artists":(track["artists"] as? [[String:Any]] ?? []).compactMap{$0["name"] as? String},
479
+ "popularity":track["popularity"] ?? 0,"duration":track["duration_ms"] ?? 0]
480
+ value["album"]=album["name"];value["albumId"]=album["id"];value["playedAt"]=item["played_at"]
481
+ value["imageUrl"]=(album["images"] as? [[String:Any]])?.first?["url"]
482
+ value["previewUrl"]=track["preview_url"];value["explicit"]=track["explicit"]
483
+ return value
484
+ }
485
+ let profile=payload["profile"] as? [String:Any] ?? [:]
486
+ self.uploadSpotifyData(["tracks":tracks,"profile":profile,"userId":payload["userId"] ?? "",
487
+ "summary":["totalTracks":tracks.count,"totalContexts":items.count,"source":"native-fetch"]])
488
+ }
489
+ }
490
+ networkTask?.resume()
380
491
  }
381
492
 
382
493
  private func activeScene() -> UIWindowScene? {
@@ -395,23 +506,20 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
395
506
  let window = UIWindow(windowScene: scene)
396
507
  window.windowLevel = .alert + 1
397
508
  window.rootViewController = viewController
398
- window.makeKeyAndVisible()
509
+ if !introPending { window.makeKeyAndVisible() }
399
510
  overlayWindow = window
400
511
  }
401
512
 
402
- private func emitStatus(_ status: String, message: String? = nil) {
403
- DispatchQueue.main.async {
404
- if let message = message {
405
- self.progressLabel?.text = message
406
- self.loadingStatusLabel?.text = message
407
- }
408
- self.updateLoadingOverlay(for: status)
409
- self.notifyListeners("onairosNativeConnectorEvent", data: [
410
- "platform": "spotify",
411
- "status": status,
412
- "message": message ?? ""
413
- ])
513
+ private func emitStatus(_ status: String, message: String? = nil, progress: Double? = nil) {
514
+ guard pendingCall != nil else { return }
515
+ if let message = message {
516
+ self.progressLabel?.text = message
517
+ self.loadingStatusLabel?.text = message
414
518
  }
519
+ self.updateLoadingOverlay(for: status)
520
+ var event:[String:Any] = ["platform":"spotify","sessionId":sessionId,"status":status,"message":message ?? ""]
521
+ if let progress = progress { event["progress"] = progress }
522
+ self.notifyListeners("onairosNativeConnectorEvent", data:event)
415
523
  }
416
524
 
417
525
  private func updateLoadingOverlay(for status: String) {
@@ -423,6 +531,25 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
423
531
  "done"
424
532
  ]
425
533
  let shouldShow = visibleStatuses.contains(status)
534
+ if useHostImportUI {
535
+ if shouldShow {
536
+ introPending = false
537
+ overlayWindow?.isHidden = true
538
+ bridge?.viewController?.view.window?.makeKey()
539
+ } else if introPending {
540
+ // RN keeps its welcome frame visible until first load + 2600ms.
541
+ guard status == "waiting_for_login" else { return }
542
+ let requestGeneration = generation
543
+ let remaining = max(0, 2.6 - Date().timeIntervalSince(introStarted))
544
+ DispatchQueue.main.asyncAfter(deadline: .now() + remaining) { [weak self] in
545
+ guard let self = self, self.generation == requestGeneration, self.introPending else { return }
546
+ self.introPending = false
547
+ self.overlayWindow?.alpha = 0; self.overlayWindow?.makeKeyAndVisible()
548
+ UIView.animate(withDuration: 0.32) { self.overlayWindow?.alpha = 1 }
549
+ }
550
+ } else { overlayWindow?.makeKeyAndVisible() }
551
+ return
552
+ }
426
553
  loadingOverlayView?.isHidden = !shouldShow
427
554
  progressLabel?.isHidden = shouldShow
428
555
 
@@ -453,9 +580,7 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
453
580
  private func finishWithSuccess(summary: [String: Any]) {
454
581
  guard let call = pendingCall else { return }
455
582
  emitStatus("done", message: "Spotify import finished.")
456
- DispatchQueue.main.async { [weak self] in
457
- self?.cleanup()
458
- }
583
+ cleanup()
459
584
  call.resolve([
460
585
  "success": true,
461
586
  "status": "done",
@@ -468,17 +593,13 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
468
593
  private func finishWithError(_ message: String) {
469
594
  guard let call = pendingCall else { return }
470
595
  emitStatus("error", message: message)
471
- DispatchQueue.main.async { [weak self] in
472
- self?.cleanup()
473
- }
596
+ cleanup()
474
597
  call.reject(message)
475
598
  pendingCall = nil
476
599
  }
477
600
 
478
601
  private func cancelFlow(message: String?, rejectPending: Bool) {
479
- DispatchQueue.main.async { [weak self] in
480
- self?.cleanup()
481
- }
602
+ cleanup()
482
603
  guard rejectPending, let call = pendingCall else { return }
483
604
  let errorMessage = message ?? "Spotify connection canceled."
484
605
  emitStatus("error", message: errorMessage)
@@ -487,6 +608,12 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
487
608
  }
488
609
 
489
610
  private func cleanup() {
611
+ generation = UUID()
612
+ spotifyWebView?.stopLoading()
613
+ introPending = false
614
+ spotifyWebView?.uiDelegate = nil
615
+ networkTask?.cancel(); networkTask = nil
616
+ extractionRunning = false
490
617
  spotifyWebView?.configuration.userContentController.removeScriptMessageHandler(forName: "onairosSpotify")
491
618
  spotifyWebView?.navigationDelegate = nil
492
619
  spotifyWebView = nil
@@ -503,580 +630,4 @@ class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDeleg
503
630
  exportFinished = true
504
631
  }
505
632
 
506
- private static let spotifyTokenInterceptorScript = """
507
- (function() {
508
- if (window.__onairosSpotifyInterceptorInstalled) return true;
509
- window.__onairosSpotifyInterceptorInstalled = true;
510
- window.__onairos_spotify__ = Object.assign({
511
- accessToken: null,
512
- clientToken: null,
513
- clientId: null,
514
- userId: null,
515
- tokenExpiry: null,
516
- appVersion: null,
517
- capturedAt: null,
518
- exportStarted: false
519
- }, window.__onairos_spotify__ || {});
520
-
521
- function normalizeHeaders(input) {
522
- var normalized = {};
523
- try {
524
- if (!input) return normalized;
525
- if (typeof Headers !== 'undefined' && input instanceof Headers) {
526
- input.forEach(function(value, key) { normalized[String(key).toLowerCase()] = value; });
527
- return normalized;
528
- }
529
- if (typeof input.forEach === 'function') {
530
- input.forEach(function(value, key) { normalized[String(key).toLowerCase()] = value; });
531
- return normalized;
532
- }
533
- Object.keys(input).forEach(function(key) {
534
- normalized[String(key).toLowerCase()] = input[key];
535
- });
536
- } catch (e) {}
537
- return normalized;
538
- }
539
-
540
- function rememberRequest(url, headers) {
541
- try {
542
- var authHeader = headers.authorization || '';
543
- if (authHeader.indexOf('Bearer ') === 0) {
544
- window.__onairos_spotify__.accessToken = authHeader.replace('Bearer ', '');
545
- window.__onairos_spotify__.capturedAt = Date.now();
546
- }
547
- if (headers['client-token']) {
548
- window.__onairos_spotify__.clientToken = headers['client-token'];
549
- }
550
- if (headers['spotify-app-version']) {
551
- window.__onairos_spotify__.appVersion = headers['spotify-app-version'];
552
- }
553
- var userMatch = String(url || '').match(/\\/user\\/([a-zA-Z0-9]+)\\//);
554
- if (userMatch) {
555
- window.__onairos_spotify__.userId = userMatch[1];
556
- }
557
- } catch (e) {}
558
- }
559
-
560
- function rememberTokenResponse(url, response) {
561
- if (String(url || '').indexOf('get_access_token') === -1) return;
562
- try {
563
- response.clone().json().then(function(data) {
564
- if (data && data.accessToken && !data.isAnonymous) {
565
- window.__onairos_spotify__.accessToken = data.accessToken;
566
- window.__onairos_spotify__.clientId = data.clientId || window.__onairos_spotify__.clientId;
567
- window.__onairos_spotify__.tokenExpiry = data.accessTokenExpirationTimestampMs || window.__onairos_spotify__.tokenExpiry;
568
- window.__onairos_spotify__.capturedAt = Date.now();
569
- }
570
- }).catch(function() {});
571
- } catch (e) {}
572
- }
573
-
574
- try {
575
- var originalFetch = window.fetch;
576
- if (typeof originalFetch === 'function') {
577
- window.fetch = function() {
578
- var requestLike = arguments[0];
579
- var url = typeof requestLike === 'string' ? requestLike : (requestLike && requestLike.url ? requestLike.url : '');
580
- var opts = arguments[1] || {};
581
- var headers = normalizeHeaders(opts.headers || (requestLike && requestLike.headers ? requestLike.headers : {}));
582
- rememberRequest(url, headers);
583
- var result = originalFetch.apply(this, arguments);
584
- try {
585
- result.then(function(response) { rememberTokenResponse(url, response); }).catch(function() {});
586
- } catch (e) {}
587
- return result;
588
- };
589
- }
590
- } catch (fetchErr) {}
591
-
592
- try {
593
- var originalOpen = XMLHttpRequest.prototype.open;
594
- var originalSend = XMLHttpRequest.prototype.send;
595
- var originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
596
-
597
- XMLHttpRequest.prototype.open = function(method, url) {
598
- this.__onairosSpotifyTrace = { url: url || '', headers: {} };
599
- return originalOpen.apply(this, arguments);
600
- };
601
-
602
- XMLHttpRequest.prototype.setRequestHeader = function(name, value) {
603
- this.__onairosSpotifyTrace = this.__onairosSpotifyTrace || { url: '', headers: {} };
604
- this.__onairosSpotifyTrace.headers[String(name).toLowerCase()] = value;
605
- return originalSetRequestHeader.apply(this, arguments);
606
- };
607
-
608
- XMLHttpRequest.prototype.send = function() {
609
- var trace = this.__onairosSpotifyTrace || {};
610
- rememberRequest(trace.url || '', normalizeHeaders(trace.headers || {}));
611
- return originalSend.apply(this, arguments);
612
- };
613
- } catch (xhrErr) {}
614
-
615
- return true;
616
- })();
617
- true;
618
- """
619
-
620
- private static let spotifyExportScript = """
621
- (async function() {
622
- if (window.__onairosSpotifyExportRunning) return true;
623
- window.__onairosSpotifyExportRunning = true;
624
- window.__onairos_spotify__ = window.__onairos_spotify__ || {};
625
- window.__onairos_spotify__.exportStarted = true;
626
-
627
- var post = function(payload) {
628
- try {
629
- window.webkit.messageHandlers.onairosSpotify.postMessage(JSON.stringify(payload));
630
- } catch (e) {}
631
- };
632
- var progress = function(stage, message) {
633
- post({ type: 'SPOTIFY_EXPORT_PROGRESS', stage: stage, message: message });
634
- };
635
- var fail = function(message, recoverable) {
636
- window.__onairosSpotifyExportRunning = false;
637
- post({ type: 'SPOTIFY_EXPORT_ERROR', message: message, recoverable: !!recoverable });
638
- };
639
- var toJson = async function(response) {
640
- if (!response || !response.ok) return null;
641
- try { return await response.json(); } catch (e) { return null; }
642
- };
643
- var mapImage = function(images) {
644
- return Array.isArray(images) && images[0] ? images[0].url : '';
645
- };
646
- var mapRestTrack = function(item, playedAt, savedAt) {
647
- var track = item && item.track ? item.track : item;
648
- if (!track) return null;
649
- return {
650
- uri: track.uri || (track.id ? 'spotify:track:' + track.id : ''),
651
- trackId: track.id || '',
652
- name: track.name || '',
653
- artists: Array.isArray(track.artists) ? track.artists.map(function(a) { return a && a.name; }).filter(Boolean) : [],
654
- album: track.album && track.album.name ? track.album.name : '',
655
- albumId: track.album && track.album.id ? track.album.id : '',
656
- duration: track.duration_ms || 0,
657
- playedAt: playedAt || item.played_at || '',
658
- savedAt: savedAt || item.added_at || '',
659
- imageUrl: track.album ? mapImage(track.album.images) : '',
660
- explicit: !!track.explicit,
661
- popularity: track.popularity || 0
662
- };
663
- };
664
- var delay = function(ms) {
665
- return new Promise(function(resolve) { setTimeout(resolve, ms); });
666
- };
667
- var currentSpotifyState = function() {
668
- return window.__onairos_spotify__ || {};
669
- };
670
- var normalizeSpotifyUri = function(value) {
671
- if (!value || typeof value !== 'string') return null;
672
- if (value.indexOf('spotify:') === 0) return value;
673
- var openMatch = value.match(/open\\.spotify\\.com\\/(track|album|artist|playlist|episode|show)\\/([A-Za-z0-9]+)/i);
674
- if (openMatch) return 'spotify:' + openMatch[1].toLowerCase() + ':' + openMatch[2];
675
- return null;
676
- };
677
- var extractTrackFromGraphQLNode = function(trackNode, playedAt) {
678
- if (!trackNode || typeof trackNode !== 'object') return null;
679
- var uri =
680
- normalizeSpotifyUri(trackNode.uri) ||
681
- normalizeSpotifyUri(trackNode._uri) ||
682
- normalizeSpotifyUri(trackNode.trackUri) ||
683
- normalizeSpotifyUri(trackNode.track_uri) ||
684
- normalizeSpotifyUri(trackNode.spotifyUri) ||
685
- normalizeSpotifyUri(trackNode.entityUri) ||
686
- normalizeSpotifyUri(trackNode.linkTo) ||
687
- null;
688
- if (!uri && trackNode.id) uri = 'spotify:track:' + trackNode.id;
689
- if (!uri || uri.indexOf('spotify:track:') !== 0) return null;
690
-
691
- var artists = [];
692
- if (Array.isArray(trackNode.artists)) {
693
- artists = trackNode.artists.map(function(artist) { return artist && artist.name ? artist.name : ''; }).filter(Boolean);
694
- } else if (Array.isArray(trackNode.artist)) {
695
- artists = trackNode.artist.map(function(artist) { return artist && artist.name ? artist.name : ''; }).filter(Boolean);
696
- } else if (trackNode.artists && Array.isArray(trackNode.artists.items)) {
697
- artists = trackNode.artists.items.map(function(artist) {
698
- return artist && artist.profile && artist.profile.name ? artist.profile.name : '';
699
- }).filter(Boolean);
700
- } else if (trackNode.firstArtist && Array.isArray(trackNode.firstArtist.items)) {
701
- artists = trackNode.firstArtist.items.map(function(artist) {
702
- return artist && artist.profile && artist.profile.name ? artist.profile.name : '';
703
- }).filter(Boolean);
704
- }
705
-
706
- var albumNode = trackNode.album || trackNode.albumOfTrack || null;
707
- var albumUri = albumNode && (
708
- normalizeSpotifyUri(albumNode.uri) ||
709
- normalizeSpotifyUri(albumNode._uri) ||
710
- normalizeSpotifyUri(albumNode.albumUri)
711
- );
712
- var imageUrl = '';
713
- if (albumNode && Array.isArray(albumNode.images) && albumNode.images[0]) {
714
- imageUrl = albumNode.images[0].url || '';
715
- } else if (albumNode && albumNode.coverArt && Array.isArray(albumNode.coverArt.sources) && albumNode.coverArt.sources[0]) {
716
- imageUrl = albumNode.coverArt.sources[0].url || '';
717
- }
718
-
719
- var durationMs =
720
- trackNode.duration_ms ||
721
- (trackNode.duration && trackNode.duration.totalMilliseconds) ||
722
- trackNode.duration ||
723
- 0;
724
-
725
- return {
726
- uri: uri,
727
- trackId: trackNode.id || uri.split(':').pop(),
728
- name: trackNode.name || trackNode.trackName || trackNode.title || 'Unknown',
729
- artists: artists,
730
- album: albumNode && albumNode.name ? albumNode.name : '',
731
- albumId: albumNode ? (albumNode.id || (albumUri ? albumUri.split(':').pop() : '')) : '',
732
- popularity: trackNode.popularity || 0,
733
- duration: durationMs,
734
- playedAt: playedAt || trackNode.playedAt || trackNode.played_at || trackNode.lastPlayedTime || '',
735
- imageUrl: imageUrl,
736
- previewUrl: trackNode.preview_url || '',
737
- explicit: typeof trackNode.explicit === 'boolean'
738
- ? trackNode.explicit
739
- : !!(trackNode.contentRating && trackNode.contentRating.label === 'EXPLICIT')
740
- };
741
- };
742
- var mapLibraryTrackItem = function(item) {
743
- if (!item || !item.track) return null;
744
- var trackWrapper = item.track;
745
- var trackNode = trackWrapper.data || trackWrapper;
746
- if (trackWrapper.data && typeof trackWrapper.data === 'object') {
747
- trackNode = {};
748
- Object.keys(trackWrapper.data).forEach(function(key) { trackNode[key] = trackWrapper.data[key]; });
749
- trackNode.uri =
750
- trackNode.uri ||
751
- trackWrapper._uri ||
752
- trackWrapper.uri ||
753
- trackWrapper.trackUri ||
754
- trackWrapper.track_uri ||
755
- null;
756
- trackNode._uri = trackNode._uri || trackNode.uri;
757
- }
758
- var normalized = extractTrackFromGraphQLNode(trackNode, '');
759
- if (!normalized) return null;
760
- normalized.savedAt = item.addedAt && item.addedAt.isoString ? item.addedAt.isoString : '';
761
- return normalized;
762
- };
763
-
764
- try {
765
- if (!/open\\.spotify\\.com$/i.test(location.host)) {
766
- fail('Waiting for Spotify web player...', true);
767
- return true;
768
- }
769
-
770
- progress('authenticating', 'Checking Spotify session...');
771
- var spotifyState = window.__onairos_spotify__ || {};
772
- var token = spotifyState.accessToken || null;
773
- var tokenExpiry = spotifyState.tokenExpiry || null;
774
- try {
775
- var tokenResponse = await fetch('https://open.spotify.com/get_access_token?reason=transport&productType=web_player', {
776
- credentials: 'include',
777
- headers: { accept: 'application/json' }
778
- });
779
- var tokenJson = await toJson(tokenResponse);
780
- if (tokenJson && tokenJson.accessToken && !tokenJson.isAnonymous) {
781
- token = tokenJson.accessToken;
782
- tokenExpiry = tokenJson.accessTokenExpirationTimestampMs || tokenExpiry;
783
- window.__onairos_spotify__.accessToken = token;
784
- window.__onairos_spotify__.tokenExpiry = tokenExpiry;
785
- }
786
- } catch (tokenFetchError) {}
787
-
788
- if (!token) {
789
- fail('Spotify is open, but Onairos is still waiting for the logged-in web player token.', true);
790
- return true;
791
- }
792
-
793
- var clientToken = spotifyState.clientToken || null;
794
- var appVersion = spotifyState.appVersion || null;
795
- for (var waitI = 0; waitI < 8; waitI++) {
796
- var liveState = currentSpotifyState();
797
- token = liveState.accessToken || token;
798
- clientToken = liveState.clientToken || clientToken;
799
- appVersion = liveState.appVersion || appVersion;
800
- tokenExpiry = liveState.tokenExpiry || tokenExpiry;
801
- if (clientToken && appVersion) break;
802
- progress('authenticating', 'Waiting for Spotify player session...');
803
- await delay(650);
804
- }
805
-
806
- var webHeaders = function() {
807
- var liveState = currentSpotifyState();
808
- var headers = {
809
- Authorization: 'Bearer ' + (liveState.accessToken || token),
810
- Accept: 'application/json',
811
- 'app-platform': 'WebPlayer'
812
- };
813
- if (liveState.clientToken || clientToken) headers['client-token'] = liveState.clientToken || clientToken;
814
- if (liveState.appVersion || appVersion) headers['spotify-app-version'] = liveState.appVersion || appVersion;
815
- return headers;
816
- };
817
- var restHeaders = function() {
818
- return {
819
- Authorization: 'Bearer ' + ((currentSpotifyState().accessToken) || token),
820
- Accept: 'application/json'
821
- };
822
- };
823
- var spFetch = async function(url, opts) {
824
- opts = opts || {};
825
- var fetchOptions = {
826
- method: opts.method || 'GET',
827
- headers: webHeaders(),
828
- credentials: 'include'
829
- };
830
- if (opts.body) {
831
- fetchOptions.body = typeof opts.body === 'string' ? opts.body : JSON.stringify(opts.body);
832
- fetchOptions.headers['Content-Type'] = 'application/json';
833
- }
834
- var response = await fetch(url, fetchOptions);
835
- if (!response.ok) {
836
- var body = '';
837
- try { body = await response.text(); } catch (e) {}
838
- throw new Error('HTTP ' + response.status + ' ' + url.split('?')[0].split('/').slice(-2).join('/') + ' ' + body.slice(0, 80));
839
- }
840
- return response.json();
841
- };
842
- var restFetch = async function(url) {
843
- var response = await fetch(url, {
844
- method: 'GET',
845
- headers: restHeaders(),
846
- credentials: 'include'
847
- });
848
- if (!response.ok) throw new Error('HTTP ' + response.status + ' spotify-web-api');
849
- return response.json();
850
- };
851
- var PATHFINDER = 'https://api-partner.spotify.com/pathfinder/v2/query';
852
- var PROFILE_ATTRIBUTES_HASH = '53bcb064f6cd18c23f752bc324a791194d20df612d8e1239c735144ab0399ced';
853
- var ACCOUNT_ATTRIBUTES_HASH = '24aaa3057b69fa91492de26841ad199bd0b330ca95817b7a4d6715150de01827';
854
- var FETCH_LIBRARY_TRACKS_HASH = '087278b20b743578a6262c2b0b4bcd20d879c503cc359a2285baf083ef944240';
855
- var DECORATE_CONTEXT_TRACKS_HASH = '4210a7207beed5259945560dbeeb0bd55d709ce25de5f28021e1393b6af59121';
856
- var LIBRARY_TRACKS_PAGE_SIZE = 25;
857
- var pathfinderFetch = function(operationName, variables, sha256Hash) {
858
- return spFetch(PATHFINDER, {
859
- method: 'POST',
860
- body: {
861
- operationName: operationName,
862
- variables: variables || {},
863
- extensions: {
864
- persistedQuery: {
865
- version: 1,
866
- sha256Hash: sha256Hash
867
- }
868
- }
869
- }
870
- });
871
- };
872
- var fetchAllLikedSongs = async function() {
873
- var offset = 0;
874
- var totalCount = null;
875
- var collected = [];
876
- while (true) {
877
- var response = await pathfinderFetch(
878
- 'fetchLibraryTracks',
879
- { offset: offset, limit: LIBRARY_TRACKS_PAGE_SIZE },
880
- FETCH_LIBRARY_TRACKS_HASH
881
- );
882
- var page = response && response.data && response.data.me && response.data.me.library && response.data.me.library.tracks
883
- ? response.data.me.library.tracks
884
- : null;
885
- var pageItems = page && Array.isArray(page.items) ? page.items : [];
886
- if (page && typeof page.totalCount === 'number') totalCount = page.totalCount;
887
- for (var i = 0; i < pageItems.length; i++) collected.push(pageItems[i]);
888
- progress('extracting', 'Finding your liked songs (' + collected.length + (totalCount != null ? '/' + totalCount : '') + ')...');
889
- if (pageItems.length === 0) break;
890
- offset += pageItems.length;
891
- if ((totalCount != null && collected.length >= totalCount) || pageItems.length < LIBRARY_TRACKS_PAGE_SIZE) break;
892
- if (offset >= 500) break;
893
- await delay(120);
894
- }
895
- return { items: collected, totalCount: totalCount != null ? totalCount : collected.length };
896
- };
897
- var decorateTrackUris = async function(trackUris) {
898
- var response = await pathfinderFetch(
899
- 'decorateContextTracks',
900
- { uris: trackUris || [] },
901
- DECORATE_CONTEXT_TRACKS_HASH
902
- );
903
- return response && response.data && Array.isArray(response.data.tracks)
904
- ? response.data.tracks
905
- : [];
906
- };
907
- var hydrateLikedTracks = async function(likedItems) {
908
- var hydratedTracks = [];
909
- var savedAtByUri = {};
910
- var orderedUris = [];
911
- var seenOrderedUris = {};
912
- for (var itemIndex = 0; itemIndex < likedItems.length; itemIndex++) {
913
- var likedItem = likedItems[itemIndex];
914
- var trackWrapper = likedItem && likedItem.track ? likedItem.track : null;
915
- var trackUri = normalizeSpotifyUri(trackWrapper && (trackWrapper._uri || trackWrapper.uri || trackWrapper.trackUri || trackWrapper.track_uri));
916
- if (!trackUri || trackUri.indexOf('spotify:track:') !== 0) continue;
917
- savedAtByUri[trackUri] = likedItem.addedAt && likedItem.addedAt.isoString ? likedItem.addedAt.isoString : '';
918
- if (!seenOrderedUris[trackUri]) {
919
- seenOrderedUris[trackUri] = true;
920
- orderedUris.push(trackUri);
921
- }
922
- }
923
- for (var offset = 0; offset < orderedUris.length; offset += LIBRARY_TRACKS_PAGE_SIZE) {
924
- var batchUris = orderedUris.slice(offset, offset + LIBRARY_TRACKS_PAGE_SIZE);
925
- var batchTracks = await decorateTrackUris(batchUris);
926
- for (var trackIndex = 0; trackIndex < batchTracks.length; trackIndex++) {
927
- var normalizedTrack = extractTrackFromGraphQLNode(batchTracks[trackIndex], '');
928
- if (!normalizedTrack || !normalizedTrack.uri) continue;
929
- normalizedTrack.savedAt = savedAtByUri[normalizedTrack.uri] || '';
930
- hydratedTracks.push(normalizedTrack);
931
- }
932
- await delay(120);
933
- }
934
- return hydratedTracks;
935
- };
936
-
937
- var normalizedProfile = { userId: '', displayName: 'unknown' };
938
- progress('extracting', 'Reading Spotify profile...');
939
- try {
940
- var profileAttributesResp = await pathfinderFetch('profileAttributes', {}, PROFILE_ATTRIBUTES_HASH);
941
- var profileAttributes = profileAttributesResp && profileAttributesResp.data && profileAttributesResp.data.me && profileAttributesResp.data.me.profile
942
- ? profileAttributesResp.data.me.profile
943
- : null;
944
- if (profileAttributes) {
945
- normalizedProfile.userId = profileAttributes.username || '';
946
- normalizedProfile.displayName = profileAttributes.name || profileAttributes.username || 'unknown';
947
- normalizedProfile.imageUrl = profileAttributes.avatar || '';
948
- }
949
- } catch (profileAttributesError) {}
950
- try {
951
- var accountAttributesResp = await pathfinderFetch('accountAttributes', {}, ACCOUNT_ATTRIBUTES_HASH);
952
- var accountAttributes = accountAttributesResp && accountAttributesResp.data && accountAttributesResp.data.me && accountAttributesResp.data.me.account && accountAttributesResp.data.me.account.attributes
953
- ? accountAttributesResp.data.me.account.attributes
954
- : null;
955
- if (accountAttributes) {
956
- normalizedProfile.subscription = accountAttributes.catalogue || '';
957
- normalizedProfile.country = accountAttributes.country || '';
958
- }
959
- } catch (accountAttributesError) {}
960
- try {
961
- var restProfile = await restFetch('https://api.spotify.com/v1/me');
962
- normalizedProfile.userId = normalizedProfile.userId || restProfile.id || '';
963
- normalizedProfile.displayName = normalizedProfile.displayName !== 'unknown' ? normalizedProfile.displayName : (restProfile.display_name || restProfile.id || 'unknown');
964
- normalizedProfile.email = restProfile.email || '';
965
- normalizedProfile.country = normalizedProfile.country || restProfile.country || '';
966
- normalizedProfile.subscription = normalizedProfile.subscription || restProfile.product || '';
967
- normalizedProfile.followers = restProfile.followers && restProfile.followers.total || 0;
968
- normalizedProfile.imageUrl = normalizedProfile.imageUrl || mapImage(restProfile.images);
969
- } catch (restProfileError) {}
970
-
971
- progress('extracting', 'Finding your liked songs...');
972
- var savedTracks = [];
973
- var likedSongsTotal = 0;
974
- try {
975
- var likedSongsData = await fetchAllLikedSongs();
976
- likedSongsTotal = likedSongsData.totalCount || likedSongsData.items.length;
977
- savedTracks = await hydrateLikedTracks(likedSongsData.items);
978
- if (savedTracks.length === 0 && likedSongsData.items.length > 0) {
979
- savedTracks = likedSongsData.items.map(mapLibraryTrackItem).filter(Boolean);
980
- }
981
- } catch (likedSongsError) {}
982
- if (savedTracks.length === 0) {
983
- try {
984
- var saved = await restFetch('https://api.spotify.com/v1/me/tracks?limit=50');
985
- savedTracks = Array.isArray(saved && saved.items)
986
- ? saved.items.map(function(x) { return mapRestTrack(x, '', x.added_at); }).filter(Boolean)
987
- : [];
988
- likedSongsTotal = saved && saved.total ? saved.total : savedTracks.length;
989
- } catch (savedRestError) {}
990
- }
991
-
992
- progress('extracting', 'Reading listening activity...');
993
- var recentlyPlayed = [];
994
- try {
995
- var recent = await restFetch('https://api.spotify.com/v1/me/player/recently-played?limit=20');
996
- recentlyPlayed = Array.isArray(recent && recent.items)
997
- ? recent.items.map(function(x) { return mapRestTrack(x, x.played_at, ''); }).filter(Boolean)
998
- : [];
999
- } catch (recentError) {}
1000
-
1001
- var playlistItems = [];
1002
- try {
1003
- var playlists = await restFetch('https://api.spotify.com/v1/me/playlists?limit=50');
1004
- playlistItems = Array.isArray(playlists && playlists.items)
1005
- ? playlists.items.map(function(p) {
1006
- return {
1007
- playlistId: p.id || '',
1008
- name: p.name || '',
1009
- description: p.description || '',
1010
- isPublic: !!p.public,
1011
- isCollaborative: !!p.collaborative,
1012
- trackCount: p.tracks && p.tracks.total ? p.tracks.total : 0,
1013
- imageUrl: mapImage(p.images),
1014
- owner: p.owner && (p.owner.display_name || p.owner.id) || ''
1015
- };
1016
- })
1017
- : [];
1018
- } catch (playlistsError) {}
1019
-
1020
- var savedAlbums = [];
1021
- try {
1022
- var albums = await restFetch('https://api.spotify.com/v1/me/albums?limit=50');
1023
- savedAlbums = Array.isArray(albums && albums.items)
1024
- ? albums.items.map(function(x) {
1025
- var album = x.album || x;
1026
- return {
1027
- albumId: album.id || '',
1028
- name: album.name || '',
1029
- artists: Array.isArray(album.artists) ? album.artists.map(function(a) { return a && a.name; }).filter(Boolean) : [],
1030
- releaseDate: album.release_date || '',
1031
- trackCount: album.total_tracks || 0,
1032
- imageUrl: mapImage(album.images),
1033
- savedAt: x.added_at || ''
1034
- };
1035
- })
1036
- : [];
1037
- } catch (albumsError) {}
1038
-
1039
- progress('uploading', 'Preparing Spotify data...');
1040
- var result = {
1041
- data: {
1042
- savedTracks: savedTracks,
1043
- topTracks: [],
1044
- topArtists: [],
1045
- topItems: { tracks: [], artists: [], timeRange: 'medium_term' },
1046
- recentlyPlayed: recentlyPlayed,
1047
- playlists: playlistItems,
1048
- savedAlbums: savedAlbums,
1049
- profile: normalizedProfile,
1050
- spotifyUserId: normalizedProfile && normalizedProfile.userId || ''
1051
- },
1052
- summary: {
1053
- savedTracksCount: savedTracks.length,
1054
- totalSavedTracks: savedTracks.length,
1055
- totalLibraryTracks: likedSongsTotal,
1056
- topTracksCount: 0,
1057
- totalTopTracks: 0,
1058
- topArtistsCount: 0,
1059
- totalTopArtists: 0,
1060
- recentlyPlayedCount: recentlyPlayed.length,
1061
- totalRecentlyPlayed: recentlyPlayed.length,
1062
- playlistCount: playlistItems.length,
1063
- totalPlaylists: playlistItems.length,
1064
- savedAlbumsCount: savedAlbums.length,
1065
- totalSavedAlbums: savedAlbums.length,
1066
- subscription: normalizedProfile && normalizedProfile.subscription || 'unknown',
1067
- displayName: normalizedProfile && normalizedProfile.displayName || 'unknown',
1068
- source: savedTracks.length > 0 ? 'pathfinder-fetchLibraryTracks' : 'spotify-web-api-fallback'
1069
- }
1070
- };
1071
-
1072
- post({ type: 'SPOTIFY_EXPORT_COMPLETE', data: result });
1073
- } catch (e) {
1074
- fail(e && e.message ? e.message : 'Spotify export failed.', false);
1075
- } finally {
1076
- window.__onairosSpotifyExportRunning = false;
1077
- }
1078
- return true;
1079
- })();
1080
- true;
1081
- """
1082
633
  }