@onairosofficial/onairos-capacitor 0.1.3 → 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 (95) 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/EmailAuth.jsx +4 -116
  28. package/src/components/PinSetup.jsx +39 -226
  29. package/src/components/SDKDesignPreview.jsx +33 -0
  30. package/src/components/SessionUserBar.jsx +2 -1
  31. package/src/components/TrainingScreen.jsx +18 -12
  32. package/src/components/UniversalOnboarding.jsx +191 -424
  33. package/src/components/WelcomeScreen.jsx +19 -12
  34. package/src/components/parity/NativeConnections.jsx +136 -0
  35. package/src/components/parity/NativeScreens.jsx +48 -0
  36. package/src/components/ui/PageLayout.jsx +7 -3
  37. package/src/nativeImport/ConnectorLoading.jsx +13 -0
  38. package/src/nativeImport/CustomImportSession.js +115 -0
  39. package/src/nativeImport/ImportIcon.jsx +29 -0
  40. package/src/nativeImport/ImportProgress.jsx +24 -0
  41. package/src/nativeImport/ImportStatus.jsx +9 -0
  42. package/src/nativeImport/NativeChatImport.jsx +28 -0
  43. package/src/nativeImport/NativeImportSession.js +123 -0
  44. package/src/nativeImport/NativeScraperImport.jsx +57 -0
  45. package/src/nativeImport/SmartFilter.jsx +28 -0
  46. package/src/nativeImport/customPayload.js +37 -0
  47. package/src/nativeImport/netflixExport.js +30 -0
  48. package/src/nativeImport/netflixHistory.js +28 -0
  49. package/src/nativeImport/netflixSession.js +59 -0
  50. package/src/nativeImport/rawHandoff.js +7 -0
  51. package/src/nativeImport/rn/config/api.js +5 -0
  52. package/src/nativeImport/rn/services/apiKeyService.js +2 -0
  53. package/src/nativeImport/rn/services/hingePayload.js +37 -0
  54. package/src/nativeImport/rn/services/nativeConversationImport.js +138 -0
  55. package/src/nativeImport/rn/services/nativeFileTransfer.js +127 -0
  56. package/src/nativeImport/rn/services/nativeRawRedaction.js +136 -0
  57. package/src/nativeImport/rn/services/netflixPayload.js +70 -0
  58. package/src/nativeImport/rn/services/rawMemoryPolicy.js +38 -0
  59. package/src/nativeImport/rn/services/sephoraPayload.js +166 -0
  60. package/src/nativeImport/rn/services/spotifyPayload.js +99 -0
  61. package/src/nativeImport/rn/source-manifest.json +45 -0
  62. package/src/nativeImport/rn/utils/importedFiles.js +74 -0
  63. package/src/nativeImport/rn/utils/nativeImportDates.js +45 -0
  64. package/src/nativeImport/rn/utils/nativeImportFileReceiver.js +51 -0
  65. package/src/nativeImport/rn/utils/nativeImportMetadata.js +74 -0
  66. package/src/nativeImport/rn/utils/nativeImportTopics.js +56 -0
  67. package/src/nativeImport/rn/utils/rawExportDelivery.js +12 -0
  68. package/src/nativeImport/rn/utils/webviewScripts/chatgptDiscovery.js +99 -0
  69. package/src/nativeImport/rn/utils/webviewScripts/claude.js +349 -0
  70. package/src/nativeImport/rn/utils/webviewScripts/gemini.js +356 -0
  71. package/src/nativeImport/rn/utils/webviewScripts/hinge.js +375 -0
  72. package/src/nativeImport/rn/utils/webviewScripts/instagram.js +152 -0
  73. package/src/nativeImport/rn/utils/webviewScripts/linkedin.js +825 -0
  74. package/src/nativeImport/rn/utils/webviewScripts/nativeChatGPTImport.js +202 -0
  75. package/src/nativeImport/rn/utils/webviewScripts/nativeChatGPTSession.js +63 -0
  76. package/src/nativeImport/rn/utils/webviewScripts/nativeImportFiles.js +132 -0
  77. package/src/nativeImport/rn/utils/webviewScripts/nativeImportProviders.js +80 -0
  78. package/src/nativeImport/rn/utils/webviewScripts/nativeLoginViewport.js +28 -0
  79. package/src/nativeImport/rn/utils/webviewScripts/netflix.js +257 -0
  80. package/src/nativeImport/rn/utils/webviewScripts/sephora.js +862 -0
  81. package/src/nativeImport/rn/utils/webviewScripts/sephoraSession.js +160 -0
  82. package/src/nativeImport/rn/utils/webviewScripts/spotify.js +1868 -0
  83. package/src/nativeImport/rn/utils/webviewScripts/telegram.js +630 -0
  84. package/src/nativeImport/rn/utils/webviewScripts/tiktok.js +2920 -0
  85. package/src/onairos.capacitor.jsx +14 -2
  86. package/src/onairos.core.jsx +3 -0
  87. package/src/onairosButton.jsx +23 -17
  88. package/src/styles/onairos-fonts.css +20 -0
  89. package/src/styles/onairos-native.css +709 -0
  90. package/src/styles/onairos-rn-parity.css +175 -0
  91. package/src/styles/sdkCssRegistry.js +83 -1
  92. package/src/styles/tailwind.capacitor.css +6 -0
  93. package/src/utils/capacitorPlugins.js +20 -12
  94. package/src/utils/nativeConnectorSession.js +18 -0
  95. package/src/utils/parityPolicy.js +41 -0
@@ -0,0 +1,1868 @@
1
+ // Synced from RN utils/webviewScripts/spotify.ts by scripts/sync-rn-connectors.cjs.
2
+ const SPOTIFY_WEBVIEW_DEBUG = false;
3
+ const SPOTIFY_TOKEN_INTERCEPTOR_SCRIPT = `
4
+ (function() {
5
+ var DEBUG_ENABLED = ${SPOTIFY_WEBVIEW_DEBUG ? "true" : "false"};
6
+ window.__onairos_spotify__ = Object.assign({
7
+ accessToken: null,
8
+ clientToken: null,
9
+ clientId: null,
10
+ userId: null,
11
+ tokenExpiry: null,
12
+ appVersion: null,
13
+ capturedAt: null,
14
+ graphqlOperations: [],
15
+ graphqlResponses: [],
16
+ recentlyPlayedGraphQL: null,
17
+ exportStarted: false,
18
+ spclientTrace: []
19
+ }, window.__onairos_spotify__ || {});
20
+
21
+ function safePostMessage(payload) {
22
+ try {
23
+ if (window.ReactNativeWebView && typeof window.ReactNativeWebView.postMessage === 'function') {
24
+ window.ReactNativeWebView.postMessage(JSON.stringify(payload));
25
+ }
26
+ } catch (e) {}
27
+ }
28
+
29
+ function truncateString(value, maxLength) {
30
+ if (value == null) return '';
31
+ var stringValue = String(value);
32
+ if (stringValue.length <= maxLength) return stringValue;
33
+ return stringValue.slice(0, maxLength) + '...';
34
+ }
35
+
36
+ function summarizeToken(token) {
37
+ if (!token || typeof token !== 'string') return 'missing';
38
+ return 'present';
39
+ }
40
+
41
+ function normalizeHeaders(input) {
42
+ var normalized = {};
43
+ try {
44
+ if (!input) return normalized;
45
+ if (typeof Headers !== 'undefined' && input instanceof Headers) {
46
+ input.forEach(function(value, key) { normalized[key] = value; });
47
+ return normalized;
48
+ }
49
+ if (typeof input.forEach === 'function') {
50
+ input.forEach(function(value, key) { normalized[key] = value; });
51
+ return normalized;
52
+ }
53
+ var keys = Object.keys(input);
54
+ for (var i = 0; i < keys.length; i++) {
55
+ normalized[keys[i]] = input[keys[i]];
56
+ }
57
+ } catch (e) {}
58
+ return normalized;
59
+ }
60
+
61
+ function shouldTraceUrl(url) {
62
+ return url.indexOf('spclient.wg.spotify.com') !== -1 ||
63
+ url.indexOf('api-partner.spotify.com/pathfinder/v2/query') !== -1 ||
64
+ url.indexOf('open.spotify.com/api/token') !== -1 ||
65
+ url.indexOf('get_access_token') !== -1 ||
66
+ url.indexOf('apresolve.spotify.com') !== -1;
67
+ }
68
+
69
+ function rememberTrace(entry) {
70
+ try {
71
+ var trace = window.__onairos_spotify__.spclientTrace || [];
72
+ trace.push(entry);
73
+ window.__onairos_spotify__.spclientTrace = trace.slice(-80);
74
+ } catch (e) {}
75
+ }
76
+
77
+ function emitTrace(direction, transport, url, details) {
78
+ if (!DEBUG_ENABLED) return;
79
+ if (!shouldTraceUrl(url)) return;
80
+ var source = window.__onairos_spotify__.exportStarted ? 'export-script' : 'page';
81
+ var userMatch = String(url || '').match(/\\/user\\/([a-zA-Z0-9]+)\\//);
82
+ var summary = {
83
+ source: source,
84
+ direction: direction,
85
+ transport: transport,
86
+ url: url,
87
+ userId: userMatch ? userMatch[1] : null,
88
+ details: details || {},
89
+ at: Date.now()
90
+ };
91
+ rememberTrace(summary);
92
+ safePostMessage({
93
+ type: 'SPOTIFY_SPCLIENT_TRACE',
94
+ message: source + ' ' + transport + ' ' + direction + ' ' + url +
95
+ (summary.userId ? ' userId=' + summary.userId : '') +
96
+ (details && details.operationName ? ' op=' + details.operationName : '') +
97
+ (details && details.status ? ' status=' + details.status : '') +
98
+ (details && details.hasAuth != null ? ' auth=' + details.hasAuth : '') +
99
+ (details && details.hasClientToken != null ? ' clientToken=' + details.hasClientToken : '') +
100
+ (details && details.appVersion ? ' appVersion=' + details.appVersion : '') +
101
+ (details && details.bodyPreview ? ' body=' + details.bodyPreview : '')
102
+ });
103
+
104
+ if (source === 'page' && url.indexOf('/recently-played/v3/user/') !== -1) {
105
+ safePostMessage({
106
+ type: 'SPOTIFY_PAGE_RECENTLY_PLAYED_CAPTURED',
107
+ userId: summary.userId,
108
+ direction: direction,
109
+ status: details && details.status ? details.status : null,
110
+ transport: transport,
111
+ url: url
112
+ });
113
+ }
114
+ }
115
+
116
+ function parsePathfinderUrl(rawUrl) {
117
+ try {
118
+ var parsed = new URL(rawUrl, window.location.href);
119
+ return {
120
+ operationName: parsed.searchParams.get('operationName') || null,
121
+ variables: parsed.searchParams.get('variables') || '',
122
+ extensions: parsed.searchParams.get('extensions') || ''
123
+ };
124
+ } catch (e) {
125
+ return {
126
+ operationName: null,
127
+ variables: '',
128
+ extensions: ''
129
+ };
130
+ }
131
+ }
132
+
133
+ function rememberGraphQLOperation(operationName) {
134
+ if (!operationName) return;
135
+ var existingOps = window.__onairos_spotify__.graphqlOperations || [];
136
+ if (existingOps.indexOf(operationName) === -1) {
137
+ existingOps.push(operationName);
138
+ }
139
+ window.__onairos_spotify__.graphqlOperations = existingOps.slice(-20);
140
+ }
141
+
142
+ function rememberGraphQLResponse(entry) {
143
+ if (!entry) return;
144
+ var responses = window.__onairos_spotify__.graphqlResponses || [];
145
+ responses.push(entry);
146
+ window.__onairos_spotify__.graphqlResponses = responses.slice(-10);
147
+ }
148
+
149
+ var _origFetch = window.fetch;
150
+ window.fetch = function() {
151
+ var requestLike = arguments[0];
152
+ var url = (typeof requestLike === 'string') ? requestLike : (requestLike && requestLike.url ? requestLike.url : '');
153
+ var opts = arguments[1] || {};
154
+ var headers = normalizeHeaders(opts.headers || (requestLike && requestLike.headers ? requestLike.headers : {}));
155
+ var pathfinderOperationName = null;
156
+ var pathfinderBodyRaw = '';
157
+ var pathfinderUrlMeta = null;
158
+
159
+ // Capture bearer token from any API request authorization header
160
+ var authHeader = headers.authorization || headers.Authorization || '';
161
+ if (authHeader && authHeader.indexOf('Bearer ') === 0 && !window.__onairos_spotify__.accessToken) {
162
+ window.__onairos_spotify__.accessToken = authHeader.replace('Bearer ', '');
163
+ window.__onairos_spotify__.capturedAt = Date.now();
164
+ }
165
+
166
+ // Capture client-token header (needed for GraphQL calls)
167
+ var ct = headers['client-token'] || headers['Client-Token'] || '';
168
+ if (ct && !window.__onairos_spotify__.clientToken) {
169
+ window.__onairos_spotify__.clientToken = ct;
170
+ }
171
+
172
+ // Capture app version
173
+ var appVer = headers['spotify-app-version'] || '';
174
+ if (appVer && !window.__onairos_spotify__.appVersion) {
175
+ window.__onairos_spotify__.appVersion = appVer;
176
+ }
177
+
178
+ // Extract user ID from spclient URLs
179
+ var userMatch = url.match(/\\/user\\/([a-zA-Z0-9]+)\\//);
180
+ if (userMatch && !window.__onairos_spotify__.userId) {
181
+ window.__onairos_spotify__.userId = userMatch[1];
182
+ }
183
+
184
+ // Capture GraphQL operation names from Spotify's first-party page requests
185
+ if (url.indexOf('api-partner.spotify.com/pathfinder/v2/query') !== -1) {
186
+ pathfinderUrlMeta = parsePathfinderUrl(url);
187
+ pathfinderOperationName = pathfinderUrlMeta.operationName || null;
188
+ pathfinderBodyRaw = (pathfinderUrlMeta.variables || '') + ' ' + (pathfinderUrlMeta.extensions || '');
189
+ try {
190
+ if (typeof opts.body === 'string') {
191
+ pathfinderBodyRaw = opts.body;
192
+ var parsedBody = JSON.parse(opts.body);
193
+ pathfinderOperationName = parsedBody.operationName || parsedBody.operation || null;
194
+ } else if (opts.body && typeof opts.body === 'object') {
195
+ pathfinderBodyRaw = JSON.stringify(opts.body);
196
+ pathfinderOperationName = opts.body.operationName || opts.body.operation || null;
197
+ }
198
+
199
+ rememberGraphQLOperation(pathfinderOperationName);
200
+ } catch (e) {}
201
+ }
202
+
203
+ emitTrace('request', 'fetch', url, {
204
+ method: opts.method || (requestLike && requestLike.method) || 'GET',
205
+ operationName: pathfinderOperationName || null,
206
+ hasAuth: !!authHeader,
207
+ hasClientToken: !!ct,
208
+ appVersion: appVer || null,
209
+ hasBody: !!pathfinderBodyRaw
210
+ });
211
+
212
+ // Intercept get_access_token response for token + clientId
213
+ var result = _origFetch.apply(this, arguments);
214
+ if (shouldTraceUrl(url)) {
215
+ result.then(function(response) {
216
+ var clone = response.clone();
217
+ return clone.text().then(function(text) {
218
+ emitTrace('response', 'fetch', url, {
219
+ status: response.status,
220
+ operationName: pathfinderOperationName || null,
221
+ hasBody: text.length > 0
222
+ });
223
+ }).catch(function() {
224
+ emitTrace('response', 'fetch', url, {
225
+ status: response.status,
226
+ operationName: pathfinderOperationName || null
227
+ });
228
+ });
229
+ }).catch(function(fetchTraceErr) {
230
+ emitTrace('error', 'fetch', url, {
231
+ operationName: pathfinderOperationName || null,
232
+ hasError: true
233
+ });
234
+ });
235
+ }
236
+ if (url.indexOf('api-partner.spotify.com/pathfinder/v2/query') !== -1) {
237
+ result.then(function(response) {
238
+ return response.clone().text();
239
+ }).then(function(text) {
240
+ try {
241
+ var opName = (pathfinderOperationName || '').toLowerCase();
242
+ var bodyRaw = (pathfinderBodyRaw || '').toLowerCase();
243
+ var textLower = (text || '').toLowerCase();
244
+ var parsedResponse = JSON.parse(text);
245
+ var entry = {
246
+ operationName: pathfinderOperationName || null,
247
+ capturedAt: Date.now(),
248
+ queryHint: [
249
+ bodyRaw.indexOf('recent') !== -1 ? 'recent' : '',
250
+ bodyRaw.indexOf('history') !== -1 ? 'history' : '',
251
+ bodyRaw.indexOf('jump') !== -1 ? 'jump' : '',
252
+ ].filter(Boolean).join(' '),
253
+ response: parsedResponse
254
+ };
255
+ rememberGraphQLResponse(entry);
256
+
257
+ var looksLikeRecentlyPlayed =
258
+ opName.indexOf('recent') !== -1 ||
259
+ opName.indexOf('history') !== -1 ||
260
+ opName.indexOf('jump') !== -1 ||
261
+ bodyRaw.indexOf('recent') !== -1 ||
262
+ bodyRaw.indexOf('history') !== -1 ||
263
+ bodyRaw.indexOf('jump') !== -1 ||
264
+ textLower.indexOf('recentlyplayed') !== -1 ||
265
+ textLower.indexOf('lastplayed') !== -1 ||
266
+ textLower.indexOf('playedat') !== -1 ||
267
+ opName === 'home';
268
+
269
+ if (looksLikeRecentlyPlayed) {
270
+ window.__onairos_spotify__.recentlyPlayedGraphQL = entry;
271
+ }
272
+ } catch (e) {}
273
+ }).catch(function() {});
274
+ }
275
+ if (url.indexOf('get_access_token') !== -1) {
276
+ result.then(function(response) {
277
+ return response.clone().text();
278
+ }).then(function(text) {
279
+ try {
280
+ var data = JSON.parse(text);
281
+ if (data && data.accessToken) {
282
+ window.__onairos_spotify__.accessToken = data.accessToken;
283
+ window.__onairos_spotify__.clientId = data.clientId || null;
284
+ window.__onairos_spotify__.tokenExpiry = data.accessTokenExpirationTimestampMs || null;
285
+ window.__onairos_spotify__.capturedAt = Date.now();
286
+ }
287
+ } catch(e) {}
288
+ }).catch(function() {});
289
+ }
290
+
291
+ return result;
292
+ };
293
+
294
+ try {
295
+ var _origXHROpen = XMLHttpRequest.prototype.open;
296
+ var _origXHRSend = XMLHttpRequest.prototype.send;
297
+ var _origXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
298
+
299
+ XMLHttpRequest.prototype.open = function(method, url) {
300
+ this.__onairos_spotify_trace = this.__onairos_spotify_trace || {};
301
+ this.__onairos_spotify_trace.method = method || 'GET';
302
+ this.__onairos_spotify_trace.url = url || '';
303
+ this.__onairos_spotify_trace.headers = this.__onairos_spotify_trace.headers || {};
304
+ return _origXHROpen.apply(this, arguments);
305
+ };
306
+
307
+ XMLHttpRequest.prototype.setRequestHeader = function(name, value) {
308
+ this.__onairos_spotify_trace = this.__onairos_spotify_trace || {};
309
+ this.__onairos_spotify_trace.headers = this.__onairos_spotify_trace.headers || {};
310
+ this.__onairos_spotify_trace.headers[name] = value;
311
+ return _origXHRSetRequestHeader.apply(this, arguments);
312
+ };
313
+
314
+ XMLHttpRequest.prototype.send = function(body) {
315
+ var trace = this.__onairos_spotify_trace || {};
316
+ var url = trace.url || '';
317
+ var headers = normalizeHeaders(trace.headers || {});
318
+ var authHeader = headers.authorization || headers.Authorization || '';
319
+ var clientTokenHeader = headers['client-token'] || headers['Client-Token'] || '';
320
+ var appVersionHeader = headers['spotify-app-version'] || '';
321
+
322
+ emitTrace('request', 'xhr', url, {
323
+ method: trace.method || 'GET',
324
+ hasAuth: !!authHeader,
325
+ hasClientToken: !!clientTokenHeader,
326
+ appVersion: appVersionHeader || null
327
+ });
328
+
329
+ if (authHeader && authHeader.indexOf('Bearer ') === 0 && !window.__onairos_spotify__.accessToken) {
330
+ window.__onairos_spotify__.accessToken = authHeader.replace('Bearer ', '');
331
+ window.__onairos_spotify__.capturedAt = Date.now();
332
+ }
333
+ if (clientTokenHeader && !window.__onairos_spotify__.clientToken) {
334
+ window.__onairos_spotify__.clientToken = clientTokenHeader;
335
+ }
336
+ if (appVersionHeader && !window.__onairos_spotify__.appVersion) {
337
+ window.__onairos_spotify__.appVersion = appVersionHeader;
338
+ }
339
+
340
+ this.addEventListener('loadend', function() {
341
+ emitTrace('response', 'xhr', url, {
342
+ status: this.status,
343
+ hasBody: !!this.responseText
344
+ });
345
+ });
346
+
347
+ return _origXHRSend.apply(this, arguments);
348
+ };
349
+ } catch (xhrErr) {}
350
+ })();
351
+ true;
352
+ `;
353
+ const SPOTIFY_CONSENT_POPUP_SCRIPT = `
354
+ (function() {
355
+ try {
356
+ var existing = document.getElementById('onairos-consent-overlay');
357
+ if (existing) existing.remove();
358
+
359
+ var overlay = document.createElement('div');
360
+ overlay.id = 'onairos-consent-overlay';
361
+ overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.85);z-index:999999;display:flex;align-items:center;justify-content:center;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,sans-serif;';
362
+
363
+ var popup = document.createElement('div');
364
+ popup.style.cssText = 'background:#121212;border-radius:16px;padding:32px;max-width:400px;width:90%;box-shadow:0 20px 60px rgba(0,0,0,0.5);border:1px solid #282828;';
365
+
366
+ var icon = document.createElement('div');
367
+ icon.style.cssText = 'text-align:center;font-size:48px;margin-bottom:16px;';
368
+ icon.textContent = '\\u{1F3B5}';
369
+
370
+ var title = document.createElement('h2');
371
+ title.style.cssText = 'margin:0 0 12px 0;font-size:24px;color:#FFFFFF;text-align:center;';
372
+ title.textContent = 'Export Spotify Data?';
373
+
374
+ var desc = document.createElement('p');
375
+ desc.style.cssText = 'margin:0 0 24px 0;color:#B3B3B3;font-size:16px;line-height:1.5;text-align:center;';
376
+ desc.textContent = 'Allow Onairos to export your Spotify liked songs and profile data for analysis?';
377
+
378
+ var btnRow = document.createElement('div');
379
+ btnRow.style.cssText = 'display:flex;gap:12px;justify-content:center;';
380
+
381
+ var denyBtn = document.createElement('button');
382
+ denyBtn.id = 'onairos-deny';
383
+ denyBtn.textContent = 'Deny';
384
+ denyBtn.style.cssText = 'flex:1;padding:14px 24px;border:2px solid #404040;background:transparent;color:#B3B3B3;border-radius:8px;font-size:16px;font-weight:600;cursor:pointer;';
385
+
386
+ var allowBtn = document.createElement('button');
387
+ allowBtn.id = 'onairos-allow';
388
+ allowBtn.textContent = 'Allow';
389
+ allowBtn.style.cssText = 'flex:1;padding:14px 24px;border:none;background:linear-gradient(135deg,#1DB954 0%,#1AA34A 100%);color:white;border-radius:8px;font-size:16px;font-weight:600;cursor:pointer;';
390
+
391
+ btnRow.appendChild(denyBtn);
392
+ btnRow.appendChild(allowBtn);
393
+ popup.appendChild(icon);
394
+ popup.appendChild(title);
395
+ popup.appendChild(desc);
396
+ popup.appendChild(btnRow);
397
+ overlay.appendChild(popup);
398
+ document.body.appendChild(overlay);
399
+
400
+ denyBtn.onclick = function() {
401
+ overlay.remove();
402
+ window.ReactNativeWebView.postMessage(JSON.stringify({
403
+ type: 'SPOTIFY_CONSENT',
404
+ status: 'denied'
405
+ }));
406
+ };
407
+
408
+ allowBtn.onclick = function() {
409
+ allowBtn.textContent = 'Starting...';
410
+ allowBtn.disabled = true;
411
+ window.ReactNativeWebView.postMessage(JSON.stringify({
412
+ type: 'SPOTIFY_CONSENT',
413
+ status: 'allowed'
414
+ }));
415
+ setTimeout(function() { overlay.remove(); }, 500);
416
+ };
417
+ } catch (error) {
418
+ window.ReactNativeWebView.postMessage(JSON.stringify({
419
+ type: 'SPOTIFY_CONSENT',
420
+ status: 'error',
421
+ message: error.message
422
+ }));
423
+ }
424
+ })();
425
+ true;
426
+ `;
427
+ const SPOTIFY_EXPORT_SCRIPT = `
428
+ (async function() {
429
+ try {
430
+ var DEBUG_ENABLED = ${SPOTIFY_WEBVIEW_DEBUG ? "true" : "false"};
431
+ window.__onairos_spotify__ = window.__onairos_spotify__ || {};
432
+ window.__onairos_spotify__.exportStarted = true;
433
+
434
+ var postMsg = function(obj) {
435
+ window.ReactNativeWebView.postMessage(JSON.stringify(obj));
436
+ };
437
+
438
+ var progress = function(stage, pct, msg) {
439
+ postMsg({ type: 'SPOTIFY_EXPORT_PROGRESS', stage: stage, progress: pct, message: msg });
440
+ };
441
+
442
+ if (!document.body) {
443
+ postMsg({ type: 'SPOTIFY_EXPORT_ERROR', message: 'Page not ready' });
444
+ return;
445
+ }
446
+
447
+ // ============================================================
448
+ // GET TOKEN: Try interceptor first, then fetch directly
449
+ // ============================================================
450
+ var sp = window.__onairos_spotify__ || {};
451
+ var TOKEN = sp.accessToken || null;
452
+ var CLIENT_TOKEN = sp.clientToken || null;
453
+ var USER_ID = sp.userId || null;
454
+ var TOKEN_EXPIRY = sp.tokenExpiry || null;
455
+ var USER_ID_CANDIDATES = [];
456
+ var USER_ID_CANDIDATE_META = {};
457
+ var RECENTLY_PLAYED_LIMIT = 20;
458
+ var LIBRARY_TRACKS_PAGE_SIZE = 25;
459
+ var HEADER_WAIT_MAX_ATTEMPTS = 4;
460
+ var HEADER_WAIT_DELAY_MS = 600;
461
+
462
+ if (DEBUG_ENABLED) {
463
+ console.log('[SPOTIFY] Token from interceptor:', !!TOKEN, 'userId:', USER_ID);
464
+ }
465
+
466
+ function addUserIdCandidate(candidate, source, score) {
467
+ if (!candidate || typeof candidate !== 'string') return;
468
+ var trimmed = candidate.trim();
469
+ if (!/^[a-z0-9]{20,}$/i.test(trimmed)) return;
470
+
471
+ var existingMeta = USER_ID_CANDIDATE_META[trimmed];
472
+ if (!existingMeta) {
473
+ USER_ID_CANDIDATES.push(trimmed);
474
+ USER_ID_CANDIDATE_META[trimmed] = {
475
+ source: source || 'unknown',
476
+ score: score || 0
477
+ };
478
+ return;
479
+ }
480
+
481
+ if ((score || 0) > (existingMeta.score || 0)) {
482
+ existingMeta.score = score || 0;
483
+ existingMeta.source = source || existingMeta.source;
484
+ }
485
+ }
486
+
487
+ if (USER_ID) {
488
+ addUserIdCandidate(USER_ID, 'pre-injected-profile-username', 1100);
489
+ }
490
+
491
+ function addUserIdsFromText(text, source, score) {
492
+ if (!text || typeof text !== 'string') return;
493
+
494
+ var patterns = [
495
+ /spotify:user:([a-z0-9]{20,})/ig,
496
+ /open\\.spotify\\.com\\/user\\/([a-z0-9]{20,})/ig,
497
+ /"username"\\s*:\\s*"([a-z0-9]{20,})"/ig,
498
+ /"userId"\\s*:\\s*"([a-z0-9]{20,})"/ig,
499
+ /\\/user\\/([a-z0-9]{20,})\\//ig
500
+ ];
501
+
502
+ for (var pi = 0; pi < patterns.length; pi++) {
503
+ var pattern = patterns[pi];
504
+ var match;
505
+ while ((match = pattern.exec(text)) !== null) {
506
+ addUserIdCandidate(match[1], source, score);
507
+ }
508
+ }
509
+ }
510
+
511
+ function buildUserIdCandidateList() {
512
+ var ordered = [];
513
+ var seen = {};
514
+
515
+ function pushCandidate(value) {
516
+ if (!value || seen[value]) return;
517
+ seen[value] = true;
518
+ ordered.push(value);
519
+ }
520
+
521
+ if (USER_ID) pushCandidate(USER_ID);
522
+
523
+ var scored = USER_ID_CANDIDATES.slice().sort(function(a, b) {
524
+ return (USER_ID_CANDIDATE_META[b] ? USER_ID_CANDIDATE_META[b].score : 0) -
525
+ (USER_ID_CANDIDATE_META[a] ? USER_ID_CANDIDATE_META[a].score : 0);
526
+ });
527
+
528
+ for (var i = 0; i < scored.length; i++) {
529
+ pushCandidate(scored[i]);
530
+ }
531
+
532
+ return ordered;
533
+ }
534
+
535
+ function formatUserIdCandidates(limit) {
536
+ var candidates = buildUserIdCandidateList();
537
+ var formatted = [];
538
+ limit = limit || 6;
539
+
540
+ for (var i = 0; i < candidates.length && formatted.length < limit; i++) {
541
+ var candidate = candidates[i];
542
+ var meta = USER_ID_CANDIDATE_META[candidate] || {};
543
+ formatted.push(candidate + (meta.source ? ' [' + meta.source + ']' : ''));
544
+ }
545
+
546
+ return formatted.join(', ');
547
+ }
548
+
549
+ function scanPerformanceEntriesForUserIds() {
550
+ try {
551
+ if (!window.performance || typeof window.performance.getEntriesByType !== 'function') return;
552
+ var entries = window.performance.getEntriesByType('resource') || [];
553
+ for (var i = 0; i < entries.length; i++) {
554
+ var resourceName = entries[i] && entries[i].name ? String(entries[i].name) : '';
555
+ if (!resourceName) continue;
556
+ addUserIdsFromText(resourceName, 'resource-timing', 500);
557
+ if (resourceName.indexOf('/recently-played/v3/user/') !== -1) {
558
+ addUserIdsFromText(resourceName, 'resource-timing-recent', 900);
559
+ }
560
+ }
561
+ } catch (performanceErr) {}
562
+ }
563
+
564
+ function scanCapturedGraphQLForUserIds() {
565
+ try {
566
+ var spotifyState = window.__onairos_spotify__ || {};
567
+ var responses = Array.isArray(spotifyState.graphqlResponses) ? spotifyState.graphqlResponses : [];
568
+ for (var i = 0; i < responses.length; i++) {
569
+ var responseEntry = responses[i];
570
+ if (!responseEntry) continue;
571
+ addUserIdsFromText(responseEntry.queryHint || '', 'graphql-query', 250);
572
+ try {
573
+ addUserIdsFromText(JSON.stringify(responseEntry.response || {}), 'graphql-response', 250);
574
+ } catch (graphQLStringifyErr) {}
575
+ }
576
+ } catch (graphQLErr) {}
577
+ }
578
+
579
+ function inspectRuntimeValue(value, source, depth, seenObjects) {
580
+ if (!value || depth > 2) return;
581
+
582
+ var valueType = typeof value;
583
+ if (valueType === 'string') {
584
+ addUserIdCandidate(value, source, 300);
585
+ addUserIdsFromText(value, source, 300);
586
+ return;
587
+ }
588
+
589
+ if (valueType !== 'object' && valueType !== 'function') {
590
+ return;
591
+ }
592
+
593
+ if (seenObjects.indexOf(value) !== -1) {
594
+ return;
595
+ }
596
+ seenObjects.push(value);
597
+
598
+ try {
599
+ if (typeof value.namespace === 'string') addUserIdCandidate(value.namespace, source + '.namespace', 1000);
600
+ if (typeof value.username === 'string') addUserIdCandidate(value.username, source + '.username', 900);
601
+ if (typeof value.userId === 'string') addUserIdCandidate(value.userId, source + '.userId', 900);
602
+ if (typeof value.uri === 'string') addUserIdsFromText(value.uri, source + '.uri', 500);
603
+ if (typeof value.href === 'string') addUserIdsFromText(value.href, source + '.href', 500);
604
+ } catch (runtimeValueErr) {}
605
+
606
+ var keys = [];
607
+ try {
608
+ keys = Object.keys(value);
609
+ } catch (keysErr) {
610
+ keys = [];
611
+ }
612
+
613
+ for (var i = 0; i < keys.length && i < 20; i++) {
614
+ var key = keys[i];
615
+ try {
616
+ inspectRuntimeValue(value[key], source + '.' + key, depth + 1, seenObjects);
617
+ } catch (childInspectErr) {}
618
+ }
619
+ }
620
+
621
+ function getWebpackRequire() {
622
+ var chunkNames = ['webpackChunkopen', 'webpackChunkclient_web', 'webpackChunkspotify'];
623
+ for (var i = 0; i < chunkNames.length; i++) {
624
+ var chunkName = chunkNames[i];
625
+ var chunkArray = window[chunkName];
626
+ if (!chunkArray || typeof chunkArray.push !== 'function') continue;
627
+
628
+ try {
629
+ var webpackRequire = null;
630
+ chunkArray.push([[Date.now()], {}, function(req) { webpackRequire = req; }]);
631
+ if (webpackRequire && webpackRequire.c) {
632
+ return webpackRequire;
633
+ }
634
+ } catch (webpackErr) {}
635
+ }
636
+
637
+ return null;
638
+ }
639
+
640
+ function scanRuntimeGlobalsForUserIds() {
641
+ var seenObjects = [];
642
+
643
+ try {
644
+ if (window.Spicetify) {
645
+ inspectRuntimeValue(window.Spicetify, 'window.Spicetify', 0, seenObjects);
646
+ }
647
+ } catch (spicetifyErr) {}
648
+
649
+ try {
650
+ var webpackRequire = getWebpackRequire();
651
+ if (webpackRequire && webpackRequire.c) {
652
+ var moduleIds = Object.keys(webpackRequire.c);
653
+ for (var i = 0; i < moduleIds.length && i < 250; i++) {
654
+ var moduleExport = webpackRequire.c[moduleIds[i]] && webpackRequire.c[moduleIds[i]].exports;
655
+ inspectRuntimeValue(moduleExport, 'webpack.' + moduleIds[i], 0, seenObjects);
656
+ }
657
+ }
658
+ } catch (webpackScanErr) {}
659
+ }
660
+
661
+ // If interceptor did not capture a token, fetch it directly using the
662
+ // same endpoint the Spotify web player calls (cookies provide auth)
663
+ if (!TOKEN) {
664
+ progress('auth', 5, 'Connecting to Spotify...');
665
+
666
+ try {
667
+ var tokenResp = await fetch('https://open.spotify.com/get_access_token?reason=transport&productType=web_player', {
668
+ credentials: 'include'
669
+ });
670
+ if (tokenResp.ok) {
671
+ var tokenData = await tokenResp.json();
672
+ if (DEBUG_ENABLED) {
673
+ console.log('[SPOTIFY] Direct token response: isAnonymous=' + tokenData.isAnonymous);
674
+ }
675
+ if (tokenData && tokenData.accessToken && !tokenData.isAnonymous) {
676
+ TOKEN = tokenData.accessToken;
677
+ TOKEN_EXPIRY = tokenData.accessTokenExpirationTimestampMs || null;
678
+
679
+ // Extract username from JWT payload (sub claim)
680
+ try {
681
+ var parts = TOKEN.split('.');
682
+ if (parts.length >= 2) {
683
+ var payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')));
684
+ USER_ID = payload.sub || payload.username || tokenData.clientId || USER_ID;
685
+ }
686
+ } catch(jwtErr) {
687
+ USER_ID = tokenData.clientId || USER_ID;
688
+ }
689
+
690
+ if (!window.__onairos_spotify__) window.__onairos_spotify__ = {};
691
+ window.__onairos_spotify__.accessToken = TOKEN;
692
+ window.__onairos_spotify__.userId = USER_ID;
693
+ window.__onairos_spotify__.tokenExpiry = TOKEN_EXPIRY;
694
+ }
695
+ }
696
+ } catch(e) {
697
+ if (DEBUG_ENABLED) {
698
+ console.error('[SPOTIFY] Direct token fetch failed:', e.message);
699
+ }
700
+ }
701
+ }
702
+
703
+ if (!TOKEN) {
704
+ postMsg({
705
+ type: 'SPOTIFY_EXPORT_ERROR',
706
+ status: 'error',
707
+ message: 'No authentication token found. Please wait for Spotify to finish loading, then retry.',
708
+ success: false
709
+ });
710
+ return;
711
+ }
712
+
713
+ progress('auth', 8, 'Finishing your Spotify connection...');
714
+ if (DEBUG_ENABLED) {
715
+ postMsg({
716
+ type: 'SPOTIFY_EXPORT_PROGRESS',
717
+ stage: 'debug',
718
+ progress: 0,
719
+ message: '[DEBUG] Initial USER_ID=' + USER_ID + ', token length=' + (TOKEN ? TOKEN.length : 0)
720
+ });
721
+ }
722
+
723
+ progress('init', 9, 'Getting to know your Spotify...');
724
+ for (var waitI = 0; waitI < HEADER_WAIT_MAX_ATTEMPTS; waitI++) {
725
+ await new Promise(function(r) { setTimeout(r, HEADER_WAIT_DELAY_MS); });
726
+ var spNow = window.__onairos_spotify__ || {};
727
+
728
+ if (spNow.clientToken) {
729
+ CLIENT_TOKEN = spNow.clientToken;
730
+ }
731
+ if (spNow.tokenExpiry) {
732
+ TOKEN_EXPIRY = spNow.tokenExpiry;
733
+ }
734
+ if (spNow.userId && spNow.userId.length > 10) {
735
+ addUserIdCandidate(spNow.userId, 'interceptor-url', 1000);
736
+ USER_ID = spNow.userId;
737
+ }
738
+
739
+ if ((spNow.clientToken || CLIENT_TOKEN) && (spNow.appVersion || sp.appVersion)) {
740
+ break;
741
+ }
742
+
743
+ if (waitI === 2) {
744
+ if (DEBUG_ENABLED) {
745
+ postMsg({
746
+ type: 'SPOTIFY_EXPORT_PROGRESS',
747
+ stage: 'debug',
748
+ progress: 0,
749
+ message: '[DEBUG] Still waiting for Spotify client headers...'
750
+ });
751
+ }
752
+ progress('init', 9, 'Getting to know your Spotify...');
753
+ }
754
+ }
755
+
756
+ if (DEBUG_ENABLED) {
757
+ postMsg({ type: 'SPOTIFY_EXPORT_PROGRESS', stage: 'debug', progress: 0, message: '[DEBUG] Final USER_ID=' + USER_ID });
758
+ }
759
+ var liveHeaderState = currentSpotifyState();
760
+ debugMsg('Header state: clientToken=' + (!!(liveHeaderState.clientToken || CLIENT_TOKEN)) + ', appVersion=' + (!!liveHeaderState.appVersion));
761
+ var finalCandidates = buildUserIdCandidateList();
762
+ if (DEBUG_ENABLED && finalCandidates.length > 0) {
763
+ postMsg({
764
+ type: 'SPOTIFY_EXPORT_PROGRESS',
765
+ stage: 'debug',
766
+ progress: 0,
767
+ message: '[DEBUG] User ID candidates: ' + formatUserIdCandidates(6)
768
+ });
769
+ }
770
+
771
+ // ============================================================
772
+ // HELPERS
773
+ // ============================================================
774
+ function delay(ms) { return new Promise(function(r) { setTimeout(r, ms); }); }
775
+
776
+ function debugMsg(msg) {
777
+ if (!DEBUG_ENABLED) return;
778
+ postMsg({ type: 'SPOTIFY_EXPORT_PROGRESS', stage: 'debug', progress: 0, message: '[DEBUG] ' + msg });
779
+ }
780
+
781
+ function currentSpotifyState() {
782
+ return window.__onairos_spotify__ || {};
783
+ }
784
+
785
+ function truncateString(value, maxLength) {
786
+ if (value == null) return '';
787
+ var stringValue = String(value);
788
+ if (stringValue.length <= maxLength) return stringValue;
789
+ return stringValue.slice(0, maxLength) + '...';
790
+ }
791
+
792
+ function summarizeAuthToken(token) {
793
+ if (!token || typeof token !== 'string') return 'missing';
794
+ return 'present';
795
+ }
796
+
797
+ function summarizeClientToken(token) {
798
+ if (!token || typeof token !== 'string') return 'missing';
799
+ return 'present';
800
+ }
801
+
802
+ function summarizeHeaders(headers) {
803
+ var authHeader = headers && headers.Authorization ? headers.Authorization : '';
804
+ var bearerToken = authHeader.indexOf('Bearer ') === 0 ? authHeader.substring(7) : authHeader;
805
+ return JSON.stringify({
806
+ authorization: summarizeAuthToken(bearerToken),
807
+ clientToken: summarizeClientToken(headers ? headers['client-token'] : null),
808
+ appPlatform: headers ? headers['app-platform'] : null,
809
+ appVersion: headers ? headers['spotify-app-version'] : null,
810
+ accept: headers ? headers.Accept : null,
811
+ contentType: headers ? headers['Content-Type'] : null
812
+ });
813
+ }
814
+
815
+ function summarizeResponseHeaders(resp) {
816
+ if (!resp || !resp.headers || typeof resp.headers.get !== 'function') return '{}';
817
+ return JSON.stringify({
818
+ contentType: resp.headers.get('content-type'),
819
+ retryAfter: resp.headers.get('retry-after'),
820
+ cacheControl: resp.headers.get('cache-control'),
821
+ server: resp.headers.get('server'),
822
+ etag: resp.headers.get('etag')
823
+ });
824
+ }
825
+
826
+ function shouldDebugHttp(url) {
827
+ return url.indexOf('/recently-played/v3/user/') !== -1 ||
828
+ url.indexOf('/metadata/4/track/') !== -1 ||
829
+ url.indexOf('/user-profile-view/v3/profile/me') !== -1 ||
830
+ url.indexOf('/v1/me/player/recently-played') !== -1;
831
+ }
832
+
833
+ function webHeaders() {
834
+ var liveState = currentSpotifyState();
835
+ var liveToken = liveState.accessToken || TOKEN;
836
+ var liveClientToken = liveState.clientToken || CLIENT_TOKEN;
837
+ var liveAppVersion = liveState.appVersion || sp.appVersion || null;
838
+ var h = {
839
+ 'Authorization': 'Bearer ' + liveToken,
840
+ 'Accept': 'application/json',
841
+ 'app-platform': 'WebPlayer'
842
+ };
843
+ if (liveClientToken) h['client-token'] = liveClientToken;
844
+ if (liveAppVersion) h['spotify-app-version'] = liveAppVersion;
845
+ return h;
846
+ }
847
+
848
+ function restHeaders() {
849
+ var liveState = currentSpotifyState();
850
+ return {
851
+ 'Authorization': 'Bearer ' + (liveState.accessToken || TOKEN),
852
+ 'Accept': 'application/json'
853
+ };
854
+ }
855
+
856
+ function normalizeSpotifyUri(value) {
857
+ if (!value || typeof value !== 'string') return null;
858
+ if (value.indexOf('spotify:') === 0) return value;
859
+
860
+ var openMatch = value.match(/open\\.spotify\\.com\\/(track|album|artist|playlist|episode|show)\\/([A-Za-z0-9]+)/i);
861
+ if (openMatch) {
862
+ return 'spotify:' + openMatch[1].toLowerCase() + ':' + openMatch[2];
863
+ }
864
+
865
+ return null;
866
+ }
867
+
868
+ function extractTrackFromGraphQLNode(trackNode, playedAt) {
869
+ if (!trackNode || typeof trackNode !== 'object') return null;
870
+
871
+ var uri =
872
+ normalizeSpotifyUri(trackNode.uri) ||
873
+ normalizeSpotifyUri(trackNode._uri) ||
874
+ normalizeSpotifyUri(trackNode.trackUri) ||
875
+ normalizeSpotifyUri(trackNode.track_uri) ||
876
+ normalizeSpotifyUri(trackNode.spotifyUri) ||
877
+ normalizeSpotifyUri(trackNode.entityUri) ||
878
+ normalizeSpotifyUri(trackNode.linkTo) ||
879
+ null;
880
+ if (!uri && trackNode.id) {
881
+ uri = 'spotify:track:' + trackNode.id;
882
+ }
883
+ if (!uri || uri.indexOf('spotify:track:') !== 0) return null;
884
+
885
+ var artists = [];
886
+ if (Array.isArray(trackNode.artists)) {
887
+ artists = trackNode.artists.map(function(artist) {
888
+ return artist && artist.name ? artist.name : '';
889
+ }).filter(Boolean);
890
+ } else if (Array.isArray(trackNode.artist)) {
891
+ artists = trackNode.artist.map(function(artist) {
892
+ return artist && artist.name ? artist.name : '';
893
+ }).filter(Boolean);
894
+ } else if (trackNode.artists && Array.isArray(trackNode.artists.items)) {
895
+ artists = trackNode.artists.items.map(function(artist) {
896
+ return artist && artist.profile && artist.profile.name ? artist.profile.name : '';
897
+ }).filter(Boolean);
898
+ } else if (trackNode.firstArtist && Array.isArray(trackNode.firstArtist.items)) {
899
+ artists = trackNode.firstArtist.items.map(function(artist) {
900
+ return artist && artist.profile && artist.profile.name ? artist.profile.name : '';
901
+ }).filter(Boolean);
902
+ }
903
+
904
+ var albumNode = trackNode.album || trackNode.albumOfTrack || null;
905
+ var albumName = albumNode && (albumNode.name || (albumNode.coverArt && albumNode.name)) ? albumNode.name : undefined;
906
+ var albumUri =
907
+ albumNode &&
908
+ (normalizeSpotifyUri(albumNode.uri) ||
909
+ normalizeSpotifyUri(albumNode._uri) ||
910
+ normalizeSpotifyUri(albumNode.albumUri) ||
911
+ null);
912
+ var imageUrl = undefined;
913
+ if (albumNode && Array.isArray(albumNode.images) && albumNode.images[0]) {
914
+ imageUrl = albumNode.images[0].url;
915
+ } else if (albumNode && Array.isArray(albumNode.coverArt && albumNode.coverArt.sources) && albumNode.coverArt.sources[0]) {
916
+ imageUrl = albumNode.coverArt.sources[0].url;
917
+ }
918
+
919
+ var durationMs =
920
+ trackNode.duration_ms ||
921
+ (trackNode.duration && trackNode.duration.totalMilliseconds) ||
922
+ trackNode.duration ||
923
+ 0;
924
+ var explicit =
925
+ typeof trackNode.explicit === 'boolean'
926
+ ? trackNode.explicit
927
+ : !!(trackNode.contentRating && trackNode.contentRating.label === 'EXPLICIT');
928
+
929
+ return {
930
+ uri: uri,
931
+ trackId: trackNode.id || uri.split(':').pop(),
932
+ name: trackNode.name || trackNode.trackName || trackNode.title || 'Unknown',
933
+ artists: artists,
934
+ album: albumName,
935
+ albumId: albumNode ? (albumNode.id || (albumUri ? albumUri.split(':').pop() : undefined)) : undefined,
936
+ popularity: trackNode.popularity || 0,
937
+ duration: durationMs,
938
+ playedAt: playedAt || trackNode.playedAt || trackNode.played_at || trackNode.lastPlayedTime || undefined,
939
+ imageUrl: imageUrl,
940
+ previewUrl: trackNode.preview_url || undefined,
941
+ explicit: explicit
942
+ };
943
+ }
944
+
945
+ function collectSpotifyUris(root, onlyTracks) {
946
+ var seen = {};
947
+ var uris = [];
948
+
949
+ function pushUri(value) {
950
+ var normalized = normalizeSpotifyUri(value);
951
+ if (!normalized) return;
952
+ if (onlyTracks && normalized.indexOf('spotify:track:') !== 0) return;
953
+ if (!seen[normalized]) {
954
+ seen[normalized] = true;
955
+ uris.push(normalized);
956
+ }
957
+ }
958
+
959
+ function visit(node) {
960
+ if (!node || typeof node !== 'object') return;
961
+ if (Array.isArray(node)) {
962
+ for (var i = 0; i < node.length; i++) visit(node[i]);
963
+ return;
964
+ }
965
+
966
+ pushUri(node.uri);
967
+ pushUri(node._uri);
968
+ pushUri(node.trackUri);
969
+ pushUri(node.track_uri);
970
+ pushUri(node.spotifyUri);
971
+ pushUri(node.entityUri);
972
+ pushUri(node.linkTo);
973
+
974
+ for (var key in node) {
975
+ if (Object.prototype.hasOwnProperty.call(node, key)) {
976
+ visit(node[key]);
977
+ }
978
+ }
979
+ }
980
+
981
+ visit(root);
982
+ return uris;
983
+ }
984
+
985
+ function collectTracksFromGraphQL(root) {
986
+ var seen = {};
987
+ var tracks = [];
988
+
989
+ function pushTrack(trackNode, playedAt) {
990
+ var normalized = extractTrackFromGraphQLNode(trackNode, playedAt);
991
+ if (!normalized || !normalized.uri || seen[normalized.uri]) {
992
+ return;
993
+ }
994
+ seen[normalized.uri] = true;
995
+ tracks.push(normalized);
996
+ }
997
+
998
+ function visit(node, inheritedPlayedAt) {
999
+ if (!node || typeof node !== 'object') return;
1000
+ if (Array.isArray(node)) {
1001
+ for (var i = 0; i < node.length; i++) {
1002
+ visit(node[i], inheritedPlayedAt);
1003
+ }
1004
+ return;
1005
+ }
1006
+
1007
+ var playedAt = node.playedAt || node.played_at || node.lastPlayedTime || inheritedPlayedAt || undefined;
1008
+
1009
+ if (node.track && typeof node.track === 'object') {
1010
+ pushTrack(node.track, playedAt);
1011
+ }
1012
+
1013
+ if (typeof node.uri === 'string' && node.uri.indexOf('spotify:track:') === 0) {
1014
+ pushTrack(node, playedAt);
1015
+ }
1016
+
1017
+ if (typeof node.trackUri === 'string' && node.trackUri.indexOf('spotify:track:') === 0) {
1018
+ pushTrack(node, playedAt);
1019
+ }
1020
+
1021
+ if (node.data && typeof node.data === 'object') {
1022
+ var mergedDataNode = node.data;
1023
+ if (!mergedDataNode.uri) {
1024
+ mergedDataNode = {};
1025
+ for (var dataKey in node.data) {
1026
+ if (Object.prototype.hasOwnProperty.call(node.data, dataKey)) {
1027
+ mergedDataNode[dataKey] = node.data[dataKey];
1028
+ }
1029
+ }
1030
+ mergedDataNode.uri = node.trackUri || node.track_uri || node._uri || node.uri || node.entityUri || null;
1031
+ }
1032
+ pushTrack(mergedDataNode, playedAt);
1033
+ }
1034
+
1035
+ if (node.content && node.content.data && typeof node.content.data === 'object') {
1036
+ pushTrack(node.content.data, playedAt);
1037
+ }
1038
+
1039
+ if (node.itemV2 && node.itemV2.data && typeof node.itemV2.data === 'object') {
1040
+ pushTrack(node.itemV2.data, playedAt);
1041
+ }
1042
+
1043
+ for (var key in node) {
1044
+ if (Object.prototype.hasOwnProperty.call(node, key)) {
1045
+ visit(node[key], playedAt);
1046
+ }
1047
+ }
1048
+ }
1049
+
1050
+ visit(root, undefined);
1051
+ return tracks;
1052
+ }
1053
+
1054
+ function textFromValue(value) {
1055
+ if (!value) return null;
1056
+ if (typeof value === 'string') return value;
1057
+ if (typeof value.text === 'string') return value.text;
1058
+ if (typeof value.label === 'string') return value.label;
1059
+ if (typeof value.title === 'string') return value.title;
1060
+ return null;
1061
+ }
1062
+
1063
+ function findHomeSections(root) {
1064
+ var sections = [];
1065
+
1066
+ function pushSections(items) {
1067
+ if (!Array.isArray(items)) return;
1068
+ for (var i = 0; i < items.length; i++) {
1069
+ sections.push(items[i]);
1070
+ }
1071
+ }
1072
+
1073
+ function visit(node) {
1074
+ if (!node || typeof node !== 'object') return;
1075
+ if (Array.isArray(node)) {
1076
+ for (var i = 0; i < node.length; i++) visit(node[i]);
1077
+ return;
1078
+ }
1079
+
1080
+ if (node.sectionContainer && node.sectionContainer.sections && Array.isArray(node.sectionContainer.sections.items)) {
1081
+ pushSections(node.sectionContainer.sections.items);
1082
+ }
1083
+ if (node.sections && Array.isArray(node.sections.items)) {
1084
+ pushSections(node.sections.items);
1085
+ }
1086
+
1087
+ for (var key in node) {
1088
+ if (Object.prototype.hasOwnProperty.call(node, key)) {
1089
+ visit(node[key]);
1090
+ }
1091
+ }
1092
+ }
1093
+
1094
+ visit(root);
1095
+ return sections;
1096
+ }
1097
+
1098
+ function describeGraphQLResponse(entry) {
1099
+ if (!entry || !entry.response) return 'empty response';
1100
+
1101
+ var response = entry.response;
1102
+ var sections = findHomeSections(response);
1103
+ if (sections.length === 0) {
1104
+ var responseUris = collectSpotifyUris(response, false);
1105
+ var responseTrackUris = collectSpotifyUris(response, true);
1106
+ return 'uris=' + responseUris.length + ', trackUris=' + responseTrackUris.length;
1107
+ }
1108
+
1109
+ var descriptions = [];
1110
+ for (var i = 0; i < sections.length && descriptions.length < 8; i++) {
1111
+ var section = sections[i] || {};
1112
+ var sectionTitle =
1113
+ textFromValue(section.title) ||
1114
+ textFromValue(section.data && section.data.title) ||
1115
+ textFromValue(section.header && section.header.title) ||
1116
+ textFromValue(section.sectionHeader && section.sectionHeader.title) ||
1117
+ 'untitled';
1118
+ var sectionTrackCount = collectTracksFromGraphQL(section).length;
1119
+ var sectionUriCount = collectSpotifyUris(section, false).length;
1120
+ descriptions.push(sectionTitle + ' (tracks=' + sectionTrackCount + ', uris=' + sectionUriCount + ')');
1121
+ }
1122
+
1123
+ return descriptions.join(' | ');
1124
+ }
1125
+
1126
+ function scoreGraphQLEntry(entry) {
1127
+ if (!entry) return -1;
1128
+ var score = 0;
1129
+ var name = (entry.operationName || '').toLowerCase();
1130
+ var hint = (entry.queryHint || '').toLowerCase();
1131
+
1132
+ if (name === 'home') score += 60;
1133
+ if (name.indexOf('recent') !== -1) score += 100;
1134
+ if (name.indexOf('history') !== -1) score += 90;
1135
+ if (name.indexOf('jump') !== -1) score += 70;
1136
+ if (hint.indexOf('recent') !== -1) score += 40;
1137
+ if (hint.indexOf('history') !== -1) score += 30;
1138
+ if (hint.indexOf('jump') !== -1) score += 20;
1139
+
1140
+ return score;
1141
+ }
1142
+
1143
+ function uniqueGraphQLCandidates(state) {
1144
+ var raw = [];
1145
+ if (state.recentlyPlayedGraphQL) raw.push(state.recentlyPlayedGraphQL);
1146
+ if (Array.isArray(state.graphqlResponses)) {
1147
+ raw = raw.concat(state.graphqlResponses);
1148
+ }
1149
+
1150
+ var seen = {};
1151
+ var candidates = [];
1152
+ for (var i = 0; i < raw.length; i++) {
1153
+ var candidate = raw[i];
1154
+ if (!candidate || !candidate.response) continue;
1155
+ var key = (candidate.operationName || 'unknown') + ':' + (candidate.capturedAt || i);
1156
+ if (seen[key]) continue;
1157
+ seen[key] = true;
1158
+ candidates.push(candidate);
1159
+ }
1160
+
1161
+ candidates.sort(function(a, b) {
1162
+ return scoreGraphQLEntry(b) - scoreGraphQLEntry(a);
1163
+ });
1164
+
1165
+ return candidates;
1166
+ }
1167
+
1168
+ // All requests go through Spotify first-party endpoints from the logged-in web player session.
1169
+ var SPCLIENT = 'https://spclient.wg.spotify.com';
1170
+ var PATHFINDER = 'https://api-partner.spotify.com/pathfinder/v2/query';
1171
+ var PROFILE_ATTRIBUTES_HASH = '53bcb064f6cd18c23f752bc324a791194d20df612d8e1239c735144ab0399ced';
1172
+ var ACCOUNT_ATTRIBUTES_HASH = '24aaa3057b69fa91492de26841ad199bd0b330ca95817b7a4d6715150de01827';
1173
+ var FETCH_LIBRARY_TRACKS_HASH = '087278b20b743578a6262c2b0b4bcd20d879c503cc359a2285baf083ef944240';
1174
+ var DECORATE_CONTEXT_TRACKS_HASH = '4210a7207beed5259945560dbeeb0bd55d709ce25de5f28021e1393b6af59121';
1175
+
1176
+ async function restFetch(url) {
1177
+ if (shouldDebugHttp(url)) {
1178
+ debugMsg('REST request -> ' + url + ' headers=' + summarizeHeaders(restHeaders()));
1179
+ }
1180
+ var resp = await fetch(url, {
1181
+ method: 'GET',
1182
+ headers: restHeaders()
1183
+ });
1184
+ if (shouldDebugHttp(url)) {
1185
+ debugMsg('REST response <- ' + resp.status + ' ' + url + ' headers=' + summarizeResponseHeaders(resp));
1186
+ }
1187
+ if (resp.status === 429) {
1188
+ var wait = parseInt(resp.headers.get('Retry-After') || '3', 10);
1189
+ throw new Error('HTTP 429 spotify-web-api retry_after=' + wait);
1190
+ }
1191
+ if (!resp.ok) {
1192
+ var body = '';
1193
+ try { body = await resp.text(); } catch(e) {}
1194
+ if (shouldDebugHttp(url)) {
1195
+ debugMsg('REST error body received <- ' + (body.length > 0 ? 'yes' : 'no'));
1196
+ }
1197
+ throw new Error('HTTP ' + resp.status + ' spotify-web-api');
1198
+ }
1199
+ return resp.json();
1200
+ }
1201
+
1202
+ async function spFetch(url, opts, retries) {
1203
+ retries = retries || 0;
1204
+ opts = opts || {};
1205
+ var fetchOpts = {
1206
+ method: opts.method || 'GET',
1207
+ headers: webHeaders(),
1208
+ credentials: 'include'
1209
+ };
1210
+ if (opts.body) {
1211
+ fetchOpts.body = typeof opts.body === 'string' ? opts.body : JSON.stringify(opts.body);
1212
+ fetchOpts.headers['Content-Type'] = 'application/json';
1213
+ }
1214
+ if (shouldDebugHttp(url)) {
1215
+ debugMsg('spFetch request -> ' + url + ' headers=' + summarizeHeaders(fetchOpts.headers));
1216
+ }
1217
+ var resp = await fetch(url, fetchOpts);
1218
+ if (shouldDebugHttp(url)) {
1219
+ debugMsg('spFetch response <- ' + resp.status + ' ' + url + ' headers=' + summarizeResponseHeaders(resp));
1220
+ }
1221
+ if (resp.status === 429 && retries < 3) {
1222
+ var wait = parseInt(resp.headers.get('Retry-After') || '3', 10);
1223
+ debugMsg('Rate limited, retrying in ' + wait + 's...');
1224
+ await delay(wait * 1000);
1225
+ return spFetch(url, opts, retries + 1);
1226
+ }
1227
+ if (!resp.ok) {
1228
+ var body = '';
1229
+ try { body = await resp.text(); } catch(e) {}
1230
+ if (shouldDebugHttp(url)) {
1231
+ debugMsg('spFetch error body received <- ' + (body.length > 0 ? 'yes' : 'no'));
1232
+ }
1233
+ throw new Error('HTTP ' + resp.status + ' ' + url.split('?')[0].split('/').slice(-2).join('/'));
1234
+ }
1235
+ return resp.json();
1236
+ }
1237
+
1238
+ async function pathfinderFetch(operationName, variables, sha256Hash) {
1239
+ return spFetch(PATHFINDER, {
1240
+ method: 'POST',
1241
+ body: {
1242
+ operationName: operationName,
1243
+ variables: variables || {},
1244
+ extensions: {
1245
+ persistedQuery: {
1246
+ version: 1,
1247
+ sha256Hash: sha256Hash
1248
+ }
1249
+ }
1250
+ }
1251
+ });
1252
+ }
1253
+
1254
+ function normalizeSubscription(value) {
1255
+ var normalized = (value || '').toLowerCase();
1256
+ if (normalized === 'premium' || normalized === 'free' || normalized === 'family') {
1257
+ return normalized;
1258
+ }
1259
+ return undefined;
1260
+ }
1261
+
1262
+ function mapLibraryTrackItem(item) {
1263
+ if (!item || !item.track) return null;
1264
+
1265
+ var trackWrapper = item.track;
1266
+ var trackNode = trackWrapper.data || trackWrapper;
1267
+ if (trackWrapper.data && typeof trackWrapper.data === 'object') {
1268
+ trackNode = {};
1269
+ for (var key in trackWrapper.data) {
1270
+ if (Object.prototype.hasOwnProperty.call(trackWrapper.data, key)) {
1271
+ trackNode[key] = trackWrapper.data[key];
1272
+ }
1273
+ }
1274
+ trackNode.uri =
1275
+ trackNode.uri ||
1276
+ trackWrapper._uri ||
1277
+ trackWrapper.uri ||
1278
+ trackWrapper.trackUri ||
1279
+ trackWrapper.track_uri ||
1280
+ null;
1281
+ trackNode._uri =
1282
+ trackNode._uri ||
1283
+ trackWrapper._uri ||
1284
+ trackWrapper.uri ||
1285
+ trackWrapper.trackUri ||
1286
+ trackWrapper.track_uri ||
1287
+ null;
1288
+ }
1289
+ var normalized = extractTrackFromGraphQLNode(trackNode, undefined);
1290
+ if (!normalized) return null;
1291
+
1292
+ normalized.savedAt = item.addedAt && item.addedAt.isoString
1293
+ ? item.addedAt.isoString
1294
+ : undefined;
1295
+
1296
+ return normalized;
1297
+ }
1298
+
1299
+ async function fetchAllLikedSongs() {
1300
+ var offset = 0;
1301
+ var totalCount = null;
1302
+ var collected = [];
1303
+
1304
+ while (true) {
1305
+ var response = await pathfinderFetch(
1306
+ 'fetchLibraryTracks',
1307
+ { offset: offset, limit: LIBRARY_TRACKS_PAGE_SIZE },
1308
+ FETCH_LIBRARY_TRACKS_HASH
1309
+ );
1310
+ var page = response &&
1311
+ response.data &&
1312
+ response.data.me &&
1313
+ response.data.me.library &&
1314
+ response.data.me.library.tracks
1315
+ ? response.data.me.library.tracks
1316
+ : null;
1317
+
1318
+ var pageItems = page && Array.isArray(page.items) ? page.items : [];
1319
+ if (page && typeof page.totalCount === 'number') {
1320
+ totalCount = page.totalCount;
1321
+ }
1322
+ debugMsg('fetchLibraryTracks page: offset=' + offset + ', requested=' + LIBRARY_TRACKS_PAGE_SIZE + ', returned=' + pageItems.length + ', total=' + (totalCount != null ? totalCount : 'unknown'));
1323
+
1324
+ for (var i = 0; i < pageItems.length; i++) {
1325
+ collected.push(pageItems[i]);
1326
+ }
1327
+
1328
+ var progressTotal = totalCount || collected.length || 1;
1329
+ var pct = 20 + Math.round((Math.min(collected.length, progressTotal) / progressTotal) * 70);
1330
+ progress('library', Math.min(pct, 90), 'Finding your favorite hits...');
1331
+
1332
+ if (pageItems.length === 0) {
1333
+ break;
1334
+ }
1335
+
1336
+ offset += pageItems.length;
1337
+ if ((totalCount != null && collected.length >= totalCount) || pageItems.length < LIBRARY_TRACKS_PAGE_SIZE) {
1338
+ break;
1339
+ }
1340
+
1341
+ await delay(120);
1342
+ }
1343
+
1344
+ return {
1345
+ items: collected,
1346
+ totalCount: totalCount != null ? totalCount : collected.length
1347
+ };
1348
+ }
1349
+
1350
+ async function decorateTrackUris(trackUris) {
1351
+ var response = await pathfinderFetch(
1352
+ 'decorateContextTracks',
1353
+ { uris: trackUris || [] },
1354
+ DECORATE_CONTEXT_TRACKS_HASH
1355
+ );
1356
+ return response &&
1357
+ response.data &&
1358
+ Array.isArray(response.data.tracks)
1359
+ ? response.data.tracks
1360
+ : [];
1361
+ }
1362
+
1363
+ async function hydrateLikedTracks(likedItems) {
1364
+ var hydratedTracks = [];
1365
+ var savedAtByUri = {};
1366
+ var orderedUris = [];
1367
+ var seenOrderedUris = {};
1368
+
1369
+ for (var itemIndex = 0; itemIndex < likedItems.length; itemIndex++) {
1370
+ var likedItem = likedItems[itemIndex];
1371
+ var trackWrapper = likedItem && likedItem.track ? likedItem.track : null;
1372
+ var trackUri = normalizeSpotifyUri(
1373
+ trackWrapper && (trackWrapper._uri || trackWrapper.uri || trackWrapper.trackUri || trackWrapper.track_uri)
1374
+ );
1375
+ if (!trackUri || trackUri.indexOf('spotify:track:') !== 0) {
1376
+ continue;
1377
+ }
1378
+
1379
+ savedAtByUri[trackUri] = likedItem.addedAt && likedItem.addedAt.isoString
1380
+ ? likedItem.addedAt.isoString
1381
+ : undefined;
1382
+
1383
+ if (!seenOrderedUris[trackUri]) {
1384
+ seenOrderedUris[trackUri] = true;
1385
+ orderedUris.push(trackUri);
1386
+ }
1387
+ }
1388
+
1389
+ for (var offset = 0; offset < orderedUris.length; offset += LIBRARY_TRACKS_PAGE_SIZE) {
1390
+ var batchUris = orderedUris.slice(offset, offset + LIBRARY_TRACKS_PAGE_SIZE);
1391
+ var batchTracks = await decorateTrackUris(batchUris);
1392
+ debugMsg('decorateContextTracks batch: offset=' + offset + ', requested=' + batchUris.length + ', returned=' + batchTracks.length);
1393
+
1394
+ for (var trackIndex = 0; trackIndex < batchTracks.length; trackIndex++) {
1395
+ var normalizedTrack = extractTrackFromGraphQLNode(batchTracks[trackIndex], undefined);
1396
+ if (!normalizedTrack || !normalizedTrack.uri) {
1397
+ continue;
1398
+ }
1399
+
1400
+ normalizedTrack.savedAt = savedAtByUri[normalizedTrack.uri];
1401
+ hydratedTracks.push(normalizedTrack);
1402
+ }
1403
+
1404
+ await delay(120);
1405
+ }
1406
+
1407
+ return hydratedTracks;
1408
+ }
1409
+
1410
+ async function fetchRecentlyPlayedWithUserId(candidateUserId) {
1411
+ var rpUrl = SPCLIENT + '/recently-played/v3/user/' + candidateUserId + '/recently-played?format=json&offset=0&limit=' + RECENTLY_PLAYED_LIMIT + '&filter=default%2Ccollection-new-episodes&market=from_token';
1412
+ return spFetch(rpUrl);
1413
+ }
1414
+
1415
+ // Fetch track metadata by hex GID
1416
+ async function getTrackMeta(hexGid) {
1417
+ var data = await spFetch(SPCLIENT + '/metadata/4/track/' + hexGid + '?market=from_token');
1418
+ return {
1419
+ name: data.name || data.original_title || 'Unknown',
1420
+ artists: (data.artist || []).map(function(a) { return a.name; }),
1421
+ album: data.album ? data.album.name : null,
1422
+ popularity: data.popularity || 0,
1423
+ duration: data.duration || 0,
1424
+ uri: data.canonical_uri || ''
1425
+ };
1426
+ }
1427
+
1428
+ // Convert spotify base62 ID to hex GID
1429
+ function uriToGid(uri) {
1430
+ var base62chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
1431
+ var id = uri.split(':').pop();
1432
+ var n = BigInt(0);
1433
+ for (var i = 0; i < id.length; i++) {
1434
+ n = n * BigInt(62) + BigInt(base62chars.indexOf(id[i]));
1435
+ }
1436
+ var hex = n.toString(16);
1437
+ while (hex.length < 32) hex = '0' + hex;
1438
+ return hex;
1439
+ }
1440
+
1441
+ // ============================================================
1442
+ // EXTRACTION \u2014 all via spclient.wg.spotify.com
1443
+ // ============================================================
1444
+ try {
1445
+ var profile = { userId: USER_ID || 'unknown', displayName: USER_ID || 'unknown' };
1446
+ var tracks = [];
1447
+ var seenUris = {};
1448
+
1449
+ progress('profile', 10, 'Getting to know your Spotify...');
1450
+
1451
+ try {
1452
+ var profileAttributesResp = await pathfinderFetch('profileAttributes', {}, PROFILE_ATTRIBUTES_HASH);
1453
+ var profileAttributes = profileAttributesResp &&
1454
+ profileAttributesResp.data &&
1455
+ profileAttributesResp.data.me &&
1456
+ profileAttributesResp.data.me.profile
1457
+ ? profileAttributesResp.data.me.profile
1458
+ : null;
1459
+
1460
+ if (profileAttributes) {
1461
+ if (profileAttributes.username) {
1462
+ USER_ID = profileAttributes.username;
1463
+ addUserIdCandidate(USER_ID, 'pathfinder-profileAttributes', 1500);
1464
+ }
1465
+
1466
+ profile = {
1467
+ userId: USER_ID || profile.userId,
1468
+ displayName: profileAttributes.name || USER_ID || 'unknown',
1469
+ imageUrl: profileAttributes.avatar || undefined
1470
+ };
1471
+ debugMsg('profileAttributes resolved username: ' + (USER_ID || 'unknown'));
1472
+ } else {
1473
+ debugMsg('profileAttributes returned no profile payload');
1474
+ }
1475
+ } catch (profileAttributesErr) {
1476
+ debugMsg('profileAttributes failed: ' + profileAttributesErr.message);
1477
+ }
1478
+
1479
+ try {
1480
+ var accountAttributesResp = await pathfinderFetch('accountAttributes', {}, ACCOUNT_ATTRIBUTES_HASH);
1481
+ var accountAttributes = accountAttributesResp &&
1482
+ accountAttributesResp.data &&
1483
+ accountAttributesResp.data.me &&
1484
+ accountAttributesResp.data.me.account &&
1485
+ accountAttributesResp.data.me.account.attributes
1486
+ ? accountAttributesResp.data.me.account.attributes
1487
+ : null;
1488
+
1489
+ if (accountAttributes) {
1490
+ profile.subscription = normalizeSubscription(accountAttributes.catalogue);
1491
+ profile.country = accountAttributes.country || profile.country;
1492
+ }
1493
+ } catch (accountAttributesErr) {
1494
+ debugMsg('accountAttributes failed: ' + accountAttributesErr.message);
1495
+ }
1496
+
1497
+ // Profile is available from spclient even when recently-played is not.
1498
+ try {
1499
+ var profileResp = await fetch('https://spclient.wg.spotify.com/user-profile-view/v3/profile/me', {
1500
+ headers: webHeaders(),
1501
+ credentials: 'include'
1502
+ });
1503
+ if (profileResp.ok) {
1504
+ var profileData = await profileResp.json();
1505
+ profile = {
1506
+ userId: USER_ID || profile.userId,
1507
+ displayName: profile.displayName || profileData.name || USER_ID || 'unknown',
1508
+ imageUrl: profile.imageUrl || profileData.image_url || undefined,
1509
+ followers: profile.followers || profileData.followers_count || undefined,
1510
+ subscription: profile.subscription,
1511
+ country: profile.country
1512
+ };
1513
+ }
1514
+ } catch (profileErr) {
1515
+ debugMsg('Profile refresh failed: ' + profileErr.message);
1516
+ }
1517
+
1518
+ progress('library', 20, 'Finding your favorite hits...');
1519
+ try {
1520
+ var likedSongsData = await fetchAllLikedSongs();
1521
+ var savedTracks = await hydrateLikedTracks(likedSongsData.items);
1522
+ if (savedTracks.length === 0 && likedSongsData.items.length > 0) {
1523
+ debugMsg('decorateContextTracks returned 0 tracks, falling back to library payload mapping');
1524
+ var seenSavedTrackIds = {};
1525
+
1526
+ for (var likedIndex = 0; likedIndex < likedSongsData.items.length; likedIndex++) {
1527
+ var mappedTrack = mapLibraryTrackItem(likedSongsData.items[likedIndex]);
1528
+ if (!mappedTrack || !mappedTrack.trackId || seenSavedTrackIds[mappedTrack.trackId]) {
1529
+ continue;
1530
+ }
1531
+
1532
+ seenSavedTrackIds[mappedTrack.trackId] = true;
1533
+ savedTracks.push(mappedTrack);
1534
+ }
1535
+ }
1536
+
1537
+ debugMsg('Fetched ' + savedTracks.length + ' liked songs');
1538
+ if (savedTracks.length > 0) {
1539
+ debugMsg('Liked songs sample: ' + savedTracks[0].name + ' by ' + savedTracks[0].artists.join(', '));
1540
+ }
1541
+
1542
+ progress('complete', 95, 'Wrapping up your favorite hits...');
1543
+ postMsg({
1544
+ type: 'SPOTIFY_EXPORT_COMPLETE',
1545
+ status: 'success',
1546
+ data: {
1547
+ profile: profile,
1548
+ savedTracks: savedTracks,
1549
+ summary: {
1550
+ totalSavedTracks: savedTracks.length,
1551
+ totalLibraryTracks: likedSongsData.totalCount,
1552
+ displayName: profile.displayName,
1553
+ source: 'pathfinder-fetchLibraryTracks'
1554
+ },
1555
+ userId: USER_ID
1556
+ },
1557
+ success: true
1558
+ });
1559
+ return;
1560
+ } catch (likedSongsErr) {
1561
+ debugMsg('Liked songs fetch failed: ' + likedSongsErr.message);
1562
+ }
1563
+
1564
+ var latestSpotifyState = window.__onairos_spotify__ || {};
1565
+ var seenOps = latestSpotifyState.graphqlOperations || [];
1566
+ if (seenOps.length > 0) {
1567
+ debugMsg('GraphQL operations seen: ' + seenOps.join(', '));
1568
+ }
1569
+
1570
+ var resolvedRecentlyPlayed = null;
1571
+ var candidateUserIds = buildUserIdCandidateList();
1572
+ if (candidateUserIds.length > 0) {
1573
+ debugMsg('Trying recently-played candidates: ' + candidateUserIds.slice(0, 6).join(', '));
1574
+ }
1575
+ for (var candidateIndex = 0; candidateIndex < candidateUserIds.length && candidateIndex < 8; candidateIndex++) {
1576
+ var candidateUserId = candidateUserIds[candidateIndex];
1577
+ try {
1578
+ var candidateResponse = await fetchRecentlyPlayedWithUserId(candidateUserId);
1579
+ var candidateContexts = Array.isArray(candidateResponse.playContexts) ? candidateResponse.playContexts : [];
1580
+ USER_ID = candidateUserId;
1581
+ resolvedRecentlyPlayed = candidateResponse;
1582
+ debugMsg('Recently-played matched candidate: ' + candidateUserId + ' (' + candidateContexts.length + ' contexts)');
1583
+ break;
1584
+ } catch (candidateErr) {
1585
+ var candidateMessage = candidateErr && candidateErr.message ? candidateErr.message : String(candidateErr);
1586
+ if (candidateMessage.indexOf('HTTP 404') === 0) {
1587
+ debugMsg('Candidate 404: ' + candidateUserId);
1588
+ } else {
1589
+ debugMsg('Candidate failed ' + candidateUserId + ': ' + candidateMessage);
1590
+ }
1591
+ }
1592
+ }
1593
+
1594
+ if (resolvedRecentlyPlayed && Array.isArray(resolvedRecentlyPlayed.playContexts)) {
1595
+ progress('recent', 10, 'Fetching listening history...');
1596
+ var contexts = resolvedRecentlyPlayed.playContexts || [];
1597
+ profile.userId = USER_ID;
1598
+ debugMsg('Got ' + contexts.length + ' play contexts');
1599
+
1600
+ var trackUris = [];
1601
+ var playedAtByUri = {};
1602
+ for (var ci = 0; ci < contexts.length; ci++) {
1603
+ var contextTrackUri = contexts[ci].lastPlayedTrackUri || '';
1604
+ if (contextTrackUri.indexOf('spotify:track:') === 0 && !seenUris[contextTrackUri]) {
1605
+ seenUris[contextTrackUri] = true;
1606
+ trackUris.push(contextTrackUri);
1607
+ }
1608
+ if (contextTrackUri.indexOf('spotify:track:') === 0 && !playedAtByUri[contextTrackUri] && contexts[ci].lastPlayedTime) {
1609
+ playedAtByUri[contextTrackUri] = new Date(contexts[ci].lastPlayedTime).toISOString();
1610
+ }
1611
+ }
1612
+ debugMsg('Found ' + trackUris.length + ' unique tracks to fetch');
1613
+
1614
+ progress('metadata', 30, 'Fetching track details (0/' + trackUris.length + ')...');
1615
+ for (var ti = 0; ti < trackUris.length; ti++) {
1616
+ try {
1617
+ var resolvedHexGid = uriToGid(trackUris[ti]);
1618
+ var resolvedMeta = await getTrackMeta(resolvedHexGid);
1619
+ resolvedMeta.playedAt = playedAtByUri[trackUris[ti]] || undefined;
1620
+ tracks.push(resolvedMeta);
1621
+
1622
+ if ((ti + 1) % 5 === 0 || ti === trackUris.length - 1) {
1623
+ var resolvedPct = 30 + Math.round(((ti + 1) / trackUris.length) * 60);
1624
+ progress('metadata', resolvedPct, 'Fetching track details (' + (ti + 1) + '/' + trackUris.length + ')...');
1625
+ }
1626
+ } catch (resolvedTrackErr) {
1627
+ debugMsg('Track ' + ti + ' failed: ' + resolvedTrackErr.message);
1628
+ }
1629
+ await delay(100);
1630
+ }
1631
+
1632
+ debugMsg('Got metadata for ' + tracks.length + ' tracks');
1633
+ if (tracks.length > 0) {
1634
+ debugMsg('Sample: ' + tracks[0].name + ' by ' + tracks[0].artists.join(', '));
1635
+ }
1636
+
1637
+ progress('complete', 95, 'Done! Got ' + tracks.length + ' tracks');
1638
+ postMsg({
1639
+ type: 'SPOTIFY_EXPORT_COMPLETE',
1640
+ status: 'success',
1641
+ data: {
1642
+ profile: profile,
1643
+ tracks: tracks,
1644
+ summary: {
1645
+ totalTracks: tracks.length,
1646
+ totalContexts: contexts.length,
1647
+ displayName: profile.displayName,
1648
+ source: 'spclient-recently-played'
1649
+ },
1650
+ userId: USER_ID
1651
+ },
1652
+ success: true
1653
+ });
1654
+ return;
1655
+ }
1656
+
1657
+ var graphQLCandidates = uniqueGraphQLCandidates(latestSpotifyState);
1658
+ for (var gqlIndex = 0; gqlIndex < graphQLCandidates.length; gqlIndex++) {
1659
+ var gqlEntry = graphQLCandidates[gqlIndex];
1660
+ try {
1661
+ debugMsg('Using captured GraphQL response from operation: ' + (gqlEntry.operationName || 'unknown'));
1662
+ var gqlTracks = collectTracksFromGraphQL(gqlEntry.response);
1663
+ debugMsg('Captured GraphQL yielded ' + gqlTracks.length + ' tracks');
1664
+ if (gqlTracks.length > 0) {
1665
+ progress('complete', 95, 'Done! Got ' + gqlTracks.length + ' tracks');
1666
+ postMsg({
1667
+ type: 'SPOTIFY_EXPORT_COMPLETE',
1668
+ status: 'success',
1669
+ data: {
1670
+ profile: profile,
1671
+ tracks: gqlTracks,
1672
+ summary: {
1673
+ totalTracks: gqlTracks.length,
1674
+ totalContexts: gqlTracks.length,
1675
+ displayName: profile.displayName,
1676
+ source: 'captured-graphql'
1677
+ },
1678
+ userId: USER_ID
1679
+ },
1680
+ success: true
1681
+ });
1682
+ return;
1683
+ }
1684
+
1685
+ debugMsg('GraphQL response summary: ' + describeGraphQLResponse(gqlEntry));
1686
+ } catch (gqlErr) {
1687
+ debugMsg('Captured GraphQL parse failed: ' + gqlErr.message);
1688
+ }
1689
+ }
1690
+
1691
+ // STEP 1: Try the official Spotify Web API first. This no longer needs USER_ID.
1692
+ progress('recent', 10, 'Fetching listening history...');
1693
+ try {
1694
+ var restData = await restFetch('https://api.spotify.com/v1/me/player/recently-played?limit=' + RECENTLY_PLAYED_LIMIT);
1695
+ var restItems = Array.isArray(restData.items) ? restData.items : [];
1696
+ debugMsg('Official REST returned ' + restItems.length + ' items');
1697
+
1698
+ var restTracks = [];
1699
+ for (var ri = 0; ri < restItems.length; ri++) {
1700
+ var playedItem = restItems[ri] || {};
1701
+ var track = playedItem.track || {};
1702
+ var artists = Array.isArray(track.artists)
1703
+ ? track.artists.map(function(a) { return a && a.name ? a.name : ''; }).filter(Boolean)
1704
+ : [];
1705
+ var imageUrl = track.album && Array.isArray(track.album.images) && track.album.images[0]
1706
+ ? track.album.images[0].url
1707
+ : null;
1708
+ var trackUri = track.uri || (track.id ? 'spotify:track:' + track.id : '');
1709
+
1710
+ if (!trackUri || !track.name) {
1711
+ continue;
1712
+ }
1713
+
1714
+ restTracks.push({
1715
+ uri: trackUri,
1716
+ name: track.name,
1717
+ artists: artists,
1718
+ album: track.album ? track.album.name : null,
1719
+ albumId: track.album ? track.album.id : undefined,
1720
+ popularity: track.popularity || 0,
1721
+ duration: track.duration_ms || 0,
1722
+ playedAt: playedItem.played_at || undefined,
1723
+ imageUrl: imageUrl || undefined,
1724
+ previewUrl: track.preview_url || undefined,
1725
+ explicit: !!track.explicit
1726
+ });
1727
+ }
1728
+
1729
+ debugMsg('Mapped ' + restTracks.length + ' tracks from official REST');
1730
+ progress('complete', 95, 'Done! Got ' + restTracks.length + ' tracks');
1731
+
1732
+ var restSummary = {
1733
+ totalTracks: restTracks.length,
1734
+ totalContexts: restItems.length,
1735
+ displayName: profile.displayName,
1736
+ source: 'spotify-web-api'
1737
+ };
1738
+
1739
+ postMsg({
1740
+ type: 'SPOTIFY_EXPORT_COMPLETE',
1741
+ status: 'success',
1742
+ data: {
1743
+ profile: profile,
1744
+ tracks: restTracks,
1745
+ summary: restSummary,
1746
+ userId: USER_ID
1747
+ },
1748
+ success: true
1749
+ });
1750
+ return;
1751
+ } catch (restErr) {
1752
+ debugMsg('Official REST failed: ' + restErr.message);
1753
+ if ((restErr.message || '').indexOf('HTTP 429') === 0) {
1754
+ postMsg({
1755
+ type: 'SPOTIFY_EXPORT_NATIVE_FALLBACK',
1756
+ accessToken: TOKEN,
1757
+ tokenExpiry: TOKEN_EXPIRY,
1758
+ userId: USER_ID,
1759
+ profile: profile,
1760
+ message: 'Official REST rate limited in WebView; retrying natively.'
1761
+ });
1762
+ return;
1763
+ }
1764
+ }
1765
+
1766
+ // STEP 2: Fall back to the legacy internal endpoint if REST is unavailable.
1767
+ progress('recent', 10, 'Fetching listening history...');
1768
+ var rpUrl = SPCLIENT + '/recently-played/v3/user/' + USER_ID + '/recently-played?format=json&offset=0&limit=' + RECENTLY_PLAYED_LIMIT + '&filter=default%2Ccollection-new-episodes&market=from_token';
1769
+ var rpData = await spFetch(rpUrl);
1770
+ var contexts = rpData.playContexts || [];
1771
+ debugMsg('Got ' + contexts.length + ' play contexts');
1772
+
1773
+ // Extract unique track URIs from lastPlayedTrackUri
1774
+ var trackUris = [];
1775
+ for (var ci = 0; ci < contexts.length; ci++) {
1776
+ var trackUri = contexts[ci].lastPlayedTrackUri || '';
1777
+ if (trackUri.indexOf('spotify:track:') === 0 && !seenUris[trackUri]) {
1778
+ seenUris[trackUri] = true;
1779
+ trackUris.push(trackUri);
1780
+ }
1781
+ }
1782
+ debugMsg('Found ' + trackUris.length + ' unique tracks to fetch');
1783
+
1784
+ // STEP 3: Fetch metadata for each track via metadata API
1785
+ progress('metadata', 30, 'Fetching track details (0/' + trackUris.length + ')...');
1786
+ for (var ti = 0; ti < trackUris.length; ti++) {
1787
+ try {
1788
+ var hexGid = uriToGid(trackUris[ti]);
1789
+ var meta = await getTrackMeta(hexGid);
1790
+ tracks.push(meta);
1791
+
1792
+ if ((ti + 1) % 5 === 0 || ti === trackUris.length - 1) {
1793
+ var pct = 30 + Math.round(((ti + 1) / trackUris.length) * 60);
1794
+ progress('metadata', pct, 'Fetching track details (' + (ti + 1) + '/' + trackUris.length + ')...');
1795
+ }
1796
+ } catch (te) {
1797
+ debugMsg('Track ' + ti + ' failed: ' + te.message);
1798
+ }
1799
+ await delay(100);
1800
+ }
1801
+
1802
+ debugMsg('Got metadata for ' + tracks.length + ' tracks');
1803
+ if (tracks.length > 0) {
1804
+ debugMsg('Sample: ' + tracks[0].name + ' by ' + tracks[0].artists.join(', '));
1805
+ }
1806
+
1807
+ // STEP 4: Send results
1808
+ progress('complete', 95, 'Done! Got ' + tracks.length + ' tracks');
1809
+
1810
+ var summary = {
1811
+ totalTracks: tracks.length,
1812
+ totalContexts: contexts.length,
1813
+ displayName: profile.displayName
1814
+ };
1815
+
1816
+ postMsg({
1817
+ type: 'SPOTIFY_EXPORT_COMPLETE',
1818
+ status: 'success',
1819
+ data: {
1820
+ profile: profile,
1821
+ tracks: tracks,
1822
+ summary: summary,
1823
+ userId: USER_ID
1824
+ },
1825
+ success: true
1826
+ });
1827
+
1828
+ } catch (error) {
1829
+ debugMsg('Fatal: ' + error.message);
1830
+ postMsg({
1831
+ type: 'SPOTIFY_EXPORT_ERROR',
1832
+ status: 'error',
1833
+ message: 'Export failed: ' + error.message,
1834
+ success: false
1835
+ });
1836
+ }
1837
+
1838
+ } catch (error) {
1839
+ if (${SPOTIFY_WEBVIEW_DEBUG ? "true" : "false"}) {
1840
+ console.error('[SPOTIFY] Init error:', error.message);
1841
+ }
1842
+ window.ReactNativeWebView.postMessage(JSON.stringify({
1843
+ type: 'SPOTIFY_EXPORT_ERROR',
1844
+ status: 'error',
1845
+ message: 'Script init error: ' + error.message,
1846
+ success: false
1847
+ }));
1848
+ }
1849
+ })();
1850
+ true;
1851
+ `;
1852
+ const SPOTIFY_SUCCESS_SCRIPT = `
1853
+ (function() {
1854
+ })();
1855
+ true;
1856
+ `;
1857
+ const SPOTIFY_ERROR_SCRIPT = `
1858
+ (function() {
1859
+ })();
1860
+ true;
1861
+ `;
1862
+ export {
1863
+ SPOTIFY_CONSENT_POPUP_SCRIPT,
1864
+ SPOTIFY_ERROR_SCRIPT,
1865
+ SPOTIFY_EXPORT_SCRIPT,
1866
+ SPOTIFY_SUCCESS_SCRIPT,
1867
+ SPOTIFY_TOKEN_INTERCEPTOR_SCRIPT
1868
+ };