@onairosofficial/onairos-capacitor 0.1.1 → 0.1.2
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.
- package/CAPACITOR_QUICK_START.md +379 -0
- package/CONNECTORS.md +122 -0
- package/OnairosofficialOnairosCapacitor.podspec +13 -0
- package/Package.swift +26 -0
- package/README.md +7 -13
- package/dist/onairos.capacitor.esm.js +1 -1
- package/dist/onairos.capacitor.esm.turbopack.js +1 -1
- package/docs/CAPACITOR_INTEGRATION_GUIDE.md +159 -0
- package/docs/CAPACITOR_MOCK_APP_TESTING.md +213 -0
- package/docs/CAPACITOR_SDK_FIXES_SUMMARY.md +65 -0
- package/docs/CROSS_SDK_PARITY.md +239 -0
- package/docs/DATA_FREQUENCY.md +57 -0
- package/docs/DEVELOPER_SDK_CHANGES.md +532 -0
- package/docs/INCIDENT_ENABLETRAINING_PIN_WEB_8.1.9.md +82 -0
- package/docs/ONAIROS_BUTTON_PROPS.md +152 -0
- package/docs/PLATFORM_APIS.md +559 -0
- package/docs/RAW_MEMORIES_API.md +305 -0
- package/docs/RAW_MEMORIES_SDK_UPDATE.md +54 -0
- package/docs/SDK_PARITY_ROLLUP_2026_04_24_to_05_02.md +96 -0
- package/docs/oldFixes.md +216 -0
- package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosChatGPTNativePlugin.swift +993 -0
- package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosNetflixNativePlugin.swift +33 -0
- package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosSpotifyNativePlugin.swift +1082 -0
- package/onairos.d.ts +10 -10
- package/package.json +9 -6
- package/src/nativeConnectors.js +5 -0
- package/src/onairos.capacitor.jsx +1 -2
- package/src/onairos.jsx +1 -1
|
@@ -0,0 +1,1082 @@
|
|
|
1
|
+
import UIKit
|
|
2
|
+
import Capacitor
|
|
3
|
+
import WebKit
|
|
4
|
+
|
|
5
|
+
@objc(OnairosSpotifyNativePlugin)
|
|
6
|
+
class OnairosSpotifyNativePlugin: CAPPlugin, CAPBridgedPlugin, WKNavigationDelegate, WKScriptMessageHandler {
|
|
7
|
+
public let identifier = "OnairosSpotifyNativePlugin"
|
|
8
|
+
public let jsName = "OnairosSpotifyNative"
|
|
9
|
+
public let pluginMethods: [CAPPluginMethod] = [
|
|
10
|
+
CAPPluginMethod(name: "connectSpotifyNative", returnType: CAPPluginReturnPromise),
|
|
11
|
+
CAPPluginMethod(name: "closeSpotifyConnector", returnType: CAPPluginReturnPromise),
|
|
12
|
+
CAPPluginMethod(name: "openSpotifyConnector", returnType: CAPPluginReturnPromise)
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
private let defaultBackendBaseURL = "https://api2.onairos.uk"
|
|
16
|
+
private let spotifyPlayerURL = "https://open.spotify.com/"
|
|
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
|
+
|
|
20
|
+
private var overlayWindow: UIWindow?
|
|
21
|
+
private var spotifyWebView: WKWebView?
|
|
22
|
+
private var progressLabel: UILabel?
|
|
23
|
+
private var loadingOverlayView: UIView?
|
|
24
|
+
private var loadingStatusLabel: UILabel?
|
|
25
|
+
private var loadingProgressView: UIProgressView?
|
|
26
|
+
private var loadingActivityIndicator: UIActivityIndicatorView?
|
|
27
|
+
private var pendingCall: CAPPluginCall?
|
|
28
|
+
private var pendingJWTToken = ""
|
|
29
|
+
private var pendingApiKey = ""
|
|
30
|
+
private var backendBaseURL = ""
|
|
31
|
+
private var exportFinished = false
|
|
32
|
+
private var injectionAttempts = 0
|
|
33
|
+
|
|
34
|
+
@objc func connectSpotifyNative(_ call: CAPPluginCall) {
|
|
35
|
+
if pendingCall != nil {
|
|
36
|
+
call.reject("Spotify connection is already in progress.")
|
|
37
|
+
return
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
let jwtToken = (call.getString("jwtToken") ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
|
|
41
|
+
if jwtToken.isEmpty {
|
|
42
|
+
call.reject("Missing Onairos JWT token for Spotify connection.")
|
|
43
|
+
return
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
pendingCall = call
|
|
47
|
+
bridge?.saveCall(call)
|
|
48
|
+
pendingJWTToken = jwtToken
|
|
49
|
+
pendingApiKey = (call.getString("apiKey") ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
|
|
50
|
+
backendBaseURL = (call.getString("baseUrl") ?? defaultBackendBaseURL)
|
|
51
|
+
.trimmingCharacters(in: CharacterSet(charactersIn: "/").union(.whitespacesAndNewlines))
|
|
52
|
+
exportFinished = false
|
|
53
|
+
injectionAttempts = 0
|
|
54
|
+
|
|
55
|
+
emitStatus("opening", message: "Opening Spotify...")
|
|
56
|
+
DispatchQueue.main.async { [weak self] in
|
|
57
|
+
self?.presentSpotifyWebView(in: self?.activeScene())
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
@objc func closeSpotifyConnector(_ call: CAPPluginCall) {
|
|
62
|
+
cancelFlow(message: nil, rejectPending: false)
|
|
63
|
+
call.resolve()
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
@objc func openSpotifyConnector(_ call: CAPPluginCall) {
|
|
67
|
+
guard let url = URL(string: spotifyLoginURL) else {
|
|
68
|
+
call.reject("Invalid Spotify URL.")
|
|
69
|
+
return
|
|
70
|
+
}
|
|
71
|
+
DispatchQueue.main.async {
|
|
72
|
+
UIApplication.shared.open(url)
|
|
73
|
+
call.resolve()
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
private func presentSpotifyWebView(in scene: UIWindowScene?) {
|
|
78
|
+
let userContentController = WKUserContentController()
|
|
79
|
+
userContentController.add(self, name: "onairosSpotify")
|
|
80
|
+
|
|
81
|
+
let config = WKWebViewConfiguration()
|
|
82
|
+
config.websiteDataStore = .default()
|
|
83
|
+
config.userContentController = userContentController
|
|
84
|
+
config.userContentController.addUserScript(WKUserScript(
|
|
85
|
+
source: Self.spotifyTokenInterceptorScript,
|
|
86
|
+
injectionTime: .atDocumentStart,
|
|
87
|
+
forMainFrameOnly: false
|
|
88
|
+
))
|
|
89
|
+
config.allowsInlineMediaPlayback = true
|
|
90
|
+
|
|
91
|
+
let webView = WKWebView(frame: .zero, configuration: config)
|
|
92
|
+
webView.navigationDelegate = self
|
|
93
|
+
webView.customUserAgent = spotifyUserAgent
|
|
94
|
+
webView.translatesAutoresizingMaskIntoConstraints = false
|
|
95
|
+
webView.allowsBackForwardNavigationGestures = true
|
|
96
|
+
|
|
97
|
+
let viewController = UIViewController()
|
|
98
|
+
viewController.view.backgroundColor = .white
|
|
99
|
+
|
|
100
|
+
let closeButton = UIButton(type: .system)
|
|
101
|
+
closeButton.setTitle("Close", for: .normal)
|
|
102
|
+
closeButton.setTitleColor(.white, for: .normal)
|
|
103
|
+
closeButton.backgroundColor = UIColor.black.withAlphaComponent(0.72)
|
|
104
|
+
closeButton.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: .semibold)
|
|
105
|
+
closeButton.layer.cornerRadius = 18
|
|
106
|
+
closeButton.translatesAutoresizingMaskIntoConstraints = false
|
|
107
|
+
closeButton.layer.zPosition = 1000
|
|
108
|
+
closeButton.addAction(UIAction { [weak self] _ in
|
|
109
|
+
self?.cancelFlow(message: "User canceled Spotify login.", rejectPending: true)
|
|
110
|
+
}, for: .touchUpInside)
|
|
111
|
+
|
|
112
|
+
let label = UILabel()
|
|
113
|
+
label.text = "Log in to Spotify. Onairos will import once you reach the web player."
|
|
114
|
+
label.font = UIFont.systemFont(ofSize: 13, weight: .medium)
|
|
115
|
+
label.textColor = UIColor.darkGray
|
|
116
|
+
label.numberOfLines = 2
|
|
117
|
+
label.textAlignment = .center
|
|
118
|
+
label.backgroundColor = UIColor.white.withAlphaComponent(0.92)
|
|
119
|
+
label.translatesAutoresizingMaskIntoConstraints = false
|
|
120
|
+
label.layer.zPosition = 999
|
|
121
|
+
|
|
122
|
+
let loadingOverlay = UIView()
|
|
123
|
+
loadingOverlay.backgroundColor = UIColor.black.withAlphaComponent(0.88)
|
|
124
|
+
loadingOverlay.translatesAutoresizingMaskIntoConstraints = false
|
|
125
|
+
loadingOverlay.isHidden = true
|
|
126
|
+
loadingOverlay.layer.zPosition = 998
|
|
127
|
+
|
|
128
|
+
let loadingPanel = UIView()
|
|
129
|
+
loadingPanel.backgroundColor = UIColor(red: 0.07, green: 0.08, blue: 0.07, alpha: 0.96)
|
|
130
|
+
loadingPanel.layer.cornerRadius = 24
|
|
131
|
+
loadingPanel.layer.borderWidth = 1
|
|
132
|
+
loadingPanel.layer.borderColor = UIColor.white.withAlphaComponent(0.14).cgColor
|
|
133
|
+
loadingPanel.translatesAutoresizingMaskIntoConstraints = false
|
|
134
|
+
|
|
135
|
+
let brandBadge = UILabel()
|
|
136
|
+
brandBadge.text = "S"
|
|
137
|
+
brandBadge.textAlignment = .center
|
|
138
|
+
brandBadge.textColor = UIColor(red: 0.10, green: 0.73, blue: 0.33, alpha: 1.0)
|
|
139
|
+
brandBadge.backgroundColor = .white
|
|
140
|
+
brandBadge.font = UIFont.systemFont(ofSize: 28, weight: .black)
|
|
141
|
+
brandBadge.layer.cornerRadius = 32
|
|
142
|
+
brandBadge.clipsToBounds = true
|
|
143
|
+
brandBadge.translatesAutoresizingMaskIntoConstraints = false
|
|
144
|
+
|
|
145
|
+
let titleLabel = UILabel()
|
|
146
|
+
titleLabel.text = "Connecting Spotify"
|
|
147
|
+
titleLabel.textColor = .white
|
|
148
|
+
titleLabel.font = UIFont.systemFont(ofSize: 24, weight: .bold)
|
|
149
|
+
titleLabel.textAlignment = .center
|
|
150
|
+
titleLabel.translatesAutoresizingMaskIntoConstraints = false
|
|
151
|
+
|
|
152
|
+
let statusLabel = UILabel()
|
|
153
|
+
statusLabel.text = "Preparing import..."
|
|
154
|
+
statusLabel.textColor = UIColor.white.withAlphaComponent(0.78)
|
|
155
|
+
statusLabel.font = UIFont.systemFont(ofSize: 15, weight: .medium)
|
|
156
|
+
statusLabel.textAlignment = .center
|
|
157
|
+
statusLabel.numberOfLines = 3
|
|
158
|
+
statusLabel.translatesAutoresizingMaskIntoConstraints = false
|
|
159
|
+
|
|
160
|
+
let spinner = UIActivityIndicatorView(style: .large)
|
|
161
|
+
spinner.color = UIColor(red: 0.10, green: 0.73, blue: 0.33, alpha: 1.0)
|
|
162
|
+
spinner.hidesWhenStopped = false
|
|
163
|
+
spinner.startAnimating()
|
|
164
|
+
spinner.translatesAutoresizingMaskIntoConstraints = false
|
|
165
|
+
|
|
166
|
+
let progressView = UIProgressView(progressViewStyle: .default)
|
|
167
|
+
progressView.progressTintColor = UIColor(red: 0.10, green: 0.73, blue: 0.33, alpha: 1.0)
|
|
168
|
+
progressView.trackTintColor = UIColor.white.withAlphaComponent(0.16)
|
|
169
|
+
progressView.progress = 0.18
|
|
170
|
+
progressView.translatesAutoresizingMaskIntoConstraints = false
|
|
171
|
+
|
|
172
|
+
loadingPanel.addSubview(brandBadge)
|
|
173
|
+
loadingPanel.addSubview(titleLabel)
|
|
174
|
+
loadingPanel.addSubview(statusLabel)
|
|
175
|
+
loadingPanel.addSubview(spinner)
|
|
176
|
+
loadingPanel.addSubview(progressView)
|
|
177
|
+
loadingOverlay.addSubview(loadingPanel)
|
|
178
|
+
|
|
179
|
+
viewController.view.addSubview(webView)
|
|
180
|
+
viewController.view.addSubview(loadingOverlay)
|
|
181
|
+
viewController.view.addSubview(label)
|
|
182
|
+
viewController.view.addSubview(closeButton)
|
|
183
|
+
|
|
184
|
+
NSLayoutConstraint.activate([
|
|
185
|
+
webView.leadingAnchor.constraint(equalTo: viewController.view.leadingAnchor),
|
|
186
|
+
webView.trailingAnchor.constraint(equalTo: viewController.view.trailingAnchor),
|
|
187
|
+
webView.topAnchor.constraint(equalTo: viewController.view.topAnchor),
|
|
188
|
+
webView.bottomAnchor.constraint(equalTo: viewController.view.bottomAnchor),
|
|
189
|
+
loadingOverlay.leadingAnchor.constraint(equalTo: viewController.view.leadingAnchor),
|
|
190
|
+
loadingOverlay.trailingAnchor.constraint(equalTo: viewController.view.trailingAnchor),
|
|
191
|
+
loadingOverlay.topAnchor.constraint(equalTo: viewController.view.topAnchor),
|
|
192
|
+
loadingOverlay.bottomAnchor.constraint(equalTo: viewController.view.bottomAnchor),
|
|
193
|
+
loadingPanel.leadingAnchor.constraint(equalTo: loadingOverlay.leadingAnchor, constant: 30),
|
|
194
|
+
loadingPanel.trailingAnchor.constraint(equalTo: loadingOverlay.trailingAnchor, constant: -30),
|
|
195
|
+
loadingPanel.centerYAnchor.constraint(equalTo: loadingOverlay.centerYAnchor),
|
|
196
|
+
brandBadge.topAnchor.constraint(equalTo: loadingPanel.topAnchor, constant: 30),
|
|
197
|
+
brandBadge.centerXAnchor.constraint(equalTo: loadingPanel.centerXAnchor),
|
|
198
|
+
brandBadge.widthAnchor.constraint(equalToConstant: 64),
|
|
199
|
+
brandBadge.heightAnchor.constraint(equalToConstant: 64),
|
|
200
|
+
titleLabel.topAnchor.constraint(equalTo: brandBadge.bottomAnchor, constant: 18),
|
|
201
|
+
titleLabel.leadingAnchor.constraint(equalTo: loadingPanel.leadingAnchor, constant: 24),
|
|
202
|
+
titleLabel.trailingAnchor.constraint(equalTo: loadingPanel.trailingAnchor, constant: -24),
|
|
203
|
+
statusLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 10),
|
|
204
|
+
statusLabel.leadingAnchor.constraint(equalTo: loadingPanel.leadingAnchor, constant: 28),
|
|
205
|
+
statusLabel.trailingAnchor.constraint(equalTo: loadingPanel.trailingAnchor, constant: -28),
|
|
206
|
+
spinner.topAnchor.constraint(equalTo: statusLabel.bottomAnchor, constant: 24),
|
|
207
|
+
spinner.centerXAnchor.constraint(equalTo: loadingPanel.centerXAnchor),
|
|
208
|
+
progressView.topAnchor.constraint(equalTo: spinner.bottomAnchor, constant: 24),
|
|
209
|
+
progressView.leadingAnchor.constraint(equalTo: loadingPanel.leadingAnchor, constant: 32),
|
|
210
|
+
progressView.trailingAnchor.constraint(equalTo: loadingPanel.trailingAnchor, constant: -32),
|
|
211
|
+
progressView.bottomAnchor.constraint(equalTo: loadingPanel.bottomAnchor, constant: -34),
|
|
212
|
+
label.leadingAnchor.constraint(equalTo: viewController.view.leadingAnchor, constant: 18),
|
|
213
|
+
label.trailingAnchor.constraint(equalTo: viewController.view.trailingAnchor, constant: -18),
|
|
214
|
+
label.bottomAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.bottomAnchor, constant: -12),
|
|
215
|
+
closeButton.topAnchor.constraint(equalTo: viewController.view.safeAreaLayoutGuide.topAnchor, constant: 8),
|
|
216
|
+
closeButton.trailingAnchor.constraint(equalTo: viewController.view.trailingAnchor, constant: -12),
|
|
217
|
+
closeButton.widthAnchor.constraint(equalToConstant: 72),
|
|
218
|
+
closeButton.heightAnchor.constraint(equalToConstant: 36)
|
|
219
|
+
])
|
|
220
|
+
|
|
221
|
+
self.spotifyWebView = webView
|
|
222
|
+
self.progressLabel = label
|
|
223
|
+
self.loadingOverlayView = loadingOverlay
|
|
224
|
+
self.loadingStatusLabel = statusLabel
|
|
225
|
+
self.loadingProgressView = progressView
|
|
226
|
+
self.loadingActivityIndicator = spinner
|
|
227
|
+
presentInOverlayWindow(viewController, in: scene)
|
|
228
|
+
|
|
229
|
+
if let url = URL(string: spotifyLoginURL) {
|
|
230
|
+
var request = URLRequest(url: url)
|
|
231
|
+
request.setValue("en-US,en;q=0.9", forHTTPHeaderField: "Accept-Language")
|
|
232
|
+
webView.load(request)
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
|
|
237
|
+
guard !exportFinished else { return }
|
|
238
|
+
guard let url = webView.url else { return }
|
|
239
|
+
|
|
240
|
+
if isSpotifyLoginURL(url) {
|
|
241
|
+
emitStatus("waiting_for_login", message: "Log in to Spotify. Import starts after the web player opens.")
|
|
242
|
+
return
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
guard isSpotifyPlayerURL(url) else { return }
|
|
246
|
+
emitStatus("authenticated", message: "Spotify web player loaded. Importing...")
|
|
247
|
+
scheduleExtractionAttempt()
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
private func isSpotifyLoginURL(_ url: URL) -> Bool {
|
|
251
|
+
let host = url.host?.lowercased() ?? ""
|
|
252
|
+
let absolute = url.absoluteString.lowercased()
|
|
253
|
+
return host.contains("accounts.spotify.com") ||
|
|
254
|
+
absolute.contains("/login") ||
|
|
255
|
+
absolute.contains("/authorize") ||
|
|
256
|
+
absolute.contains("/signup")
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
private func isSpotifyPlayerURL(_ url: URL) -> Bool {
|
|
260
|
+
let host = url.host?.lowercased() ?? ""
|
|
261
|
+
return host == "open.spotify.com" || host.hasSuffix(".open.spotify.com")
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
private func scheduleExtractionAttempt() {
|
|
265
|
+
guard !exportFinished else { return }
|
|
266
|
+
injectionAttempts += 1
|
|
267
|
+
if injectionAttempts > 90 {
|
|
268
|
+
finishWithError("Timed out waiting for Spotify web player login.")
|
|
269
|
+
return
|
|
270
|
+
}
|
|
271
|
+
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in
|
|
272
|
+
self?.injectSpotifyExportScript()
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
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 {
|
|
283
|
+
self?.scheduleExtractionAttempt()
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
|
|
289
|
+
guard message.name == "onairosSpotify" else { return }
|
|
290
|
+
|
|
291
|
+
let raw: Any
|
|
292
|
+
if let body = message.body as? String,
|
|
293
|
+
let data = body.data(using: .utf8),
|
|
294
|
+
let parsed = try? JSONSerialization.jsonObject(with: data) {
|
|
295
|
+
raw = parsed
|
|
296
|
+
} else {
|
|
297
|
+
raw = message.body
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
guard let payload = raw as? [String: Any] else { return }
|
|
301
|
+
let type = payload["type"] as? String ?? ""
|
|
302
|
+
|
|
303
|
+
if type == "SPOTIFY_EXPORT_PROGRESS" {
|
|
304
|
+
emitStatus(payload["stage"] as? String ?? "progress", message: payload["message"] as? String)
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
if type == "SPOTIFY_EXPORT_ERROR" {
|
|
309
|
+
let recoverable = (payload["recoverable"] as? Bool) ?? false
|
|
310
|
+
let message = payload["message"] as? String ?? "Spotify export failed."
|
|
311
|
+
emitStatus(recoverable ? "waiting_for_login" : "error", message: message)
|
|
312
|
+
if !recoverable {
|
|
313
|
+
finishWithError(message)
|
|
314
|
+
}
|
|
315
|
+
return
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
if type == "SPOTIFY_EXPORT_COMPLETE" {
|
|
319
|
+
exportFinished = true
|
|
320
|
+
emitStatus("uploading", message: "Uploading Spotify data...")
|
|
321
|
+
let extracted = payload["data"] as? [String: Any] ?? [:]
|
|
322
|
+
uploadSpotifyData(extracted)
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
private func uploadSpotifyData(_ extracted: [String: Any]) {
|
|
327
|
+
guard let url = URL(string: "\(backendBaseURL)/platform-data/store") else {
|
|
328
|
+
finishWithError("Invalid Onairos backend URL.")
|
|
329
|
+
return
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
let data = extracted["data"] as? [String: Any] ?? extracted
|
|
333
|
+
let summary = extracted["summary"] as? [String: Any] ?? [:]
|
|
334
|
+
let body: [String: Any] = [
|
|
335
|
+
"platform": "mobile-spotify",
|
|
336
|
+
"dataType": "streaming",
|
|
337
|
+
"data": data,
|
|
338
|
+
"summary": summary,
|
|
339
|
+
"mobileMetadata": [
|
|
340
|
+
"platform": "ios",
|
|
341
|
+
"source": "capacitor-wkwebview",
|
|
342
|
+
"appVersion": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0",
|
|
343
|
+
"osVersion": UIDevice.current.systemVersion,
|
|
344
|
+
"deviceModel": UIDevice.current.model,
|
|
345
|
+
"isOfflineSync": false,
|
|
346
|
+
"extractedAt": ISO8601DateFormatter().string(from: Date())
|
|
347
|
+
]
|
|
348
|
+
]
|
|
349
|
+
|
|
350
|
+
guard let bodyData = try? JSONSerialization.data(withJSONObject: body) else {
|
|
351
|
+
finishWithError("Could not encode Spotify data.")
|
|
352
|
+
return
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
var request = URLRequest(url: url)
|
|
356
|
+
request.httpMethod = "POST"
|
|
357
|
+
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
358
|
+
request.setValue("Bearer \(pendingJWTToken)", forHTTPHeaderField: "Authorization")
|
|
359
|
+
request.setValue("OnairosSDK/1.0.0 (ios)", forHTTPHeaderField: "User-Agent")
|
|
360
|
+
if !pendingApiKey.isEmpty {
|
|
361
|
+
request.setValue(pendingApiKey, forHTTPHeaderField: "x-api-key")
|
|
362
|
+
}
|
|
363
|
+
request.httpBody = bodyData
|
|
364
|
+
|
|
365
|
+
URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
|
|
366
|
+
if let error = error {
|
|
367
|
+
self?.finishWithError(error.localizedDescription)
|
|
368
|
+
return
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0
|
|
372
|
+
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))")
|
|
375
|
+
return
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
self?.finishWithSuccess(summary: summary)
|
|
379
|
+
}.resume()
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
private func activeScene() -> UIWindowScene? {
|
|
383
|
+
UIApplication.shared.connectedScenes
|
|
384
|
+
.compactMap { $0 as? UIWindowScene }
|
|
385
|
+
.first { $0.activationState == .foregroundActive } ??
|
|
386
|
+
UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
private func presentInOverlayWindow(_ viewController: UIViewController, in scene: UIWindowScene?) {
|
|
390
|
+
guard let scene = scene else {
|
|
391
|
+
finishWithError("Could not find an active iOS scene.")
|
|
392
|
+
return
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
let window = UIWindow(windowScene: scene)
|
|
396
|
+
window.windowLevel = .alert + 1
|
|
397
|
+
window.rootViewController = viewController
|
|
398
|
+
window.makeKeyAndVisible()
|
|
399
|
+
overlayWindow = window
|
|
400
|
+
}
|
|
401
|
+
|
|
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
|
+
])
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
private func updateLoadingOverlay(for status: String) {
|
|
418
|
+
let visibleStatuses = [
|
|
419
|
+
"authenticated",
|
|
420
|
+
"authenticating",
|
|
421
|
+
"extracting",
|
|
422
|
+
"uploading",
|
|
423
|
+
"done"
|
|
424
|
+
]
|
|
425
|
+
let shouldShow = visibleStatuses.contains(status)
|
|
426
|
+
loadingOverlayView?.isHidden = !shouldShow
|
|
427
|
+
progressLabel?.isHidden = shouldShow
|
|
428
|
+
|
|
429
|
+
let progress: Float
|
|
430
|
+
switch status {
|
|
431
|
+
case "authenticated":
|
|
432
|
+
progress = 0.18
|
|
433
|
+
case "authenticating":
|
|
434
|
+
progress = 0.30
|
|
435
|
+
case "extracting":
|
|
436
|
+
progress = 0.64
|
|
437
|
+
case "uploading":
|
|
438
|
+
progress = 0.88
|
|
439
|
+
case "done":
|
|
440
|
+
progress = 1.0
|
|
441
|
+
default:
|
|
442
|
+
progress = loadingProgressView?.progress ?? 0.18
|
|
443
|
+
}
|
|
444
|
+
loadingProgressView?.setProgress(progress, animated: true)
|
|
445
|
+
|
|
446
|
+
if status == "done" {
|
|
447
|
+
loadingActivityIndicator?.stopAnimating()
|
|
448
|
+
} else if shouldShow {
|
|
449
|
+
loadingActivityIndicator?.startAnimating()
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
private func finishWithSuccess(summary: [String: Any]) {
|
|
454
|
+
guard let call = pendingCall else { return }
|
|
455
|
+
emitStatus("done", message: "Spotify import finished.")
|
|
456
|
+
DispatchQueue.main.async { [weak self] in
|
|
457
|
+
self?.cleanup()
|
|
458
|
+
}
|
|
459
|
+
call.resolve([
|
|
460
|
+
"success": true,
|
|
461
|
+
"status": "done",
|
|
462
|
+
"platform": "spotify",
|
|
463
|
+
"summary": summary
|
|
464
|
+
])
|
|
465
|
+
pendingCall = nil
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
private func finishWithError(_ message: String) {
|
|
469
|
+
guard let call = pendingCall else { return }
|
|
470
|
+
emitStatus("error", message: message)
|
|
471
|
+
DispatchQueue.main.async { [weak self] in
|
|
472
|
+
self?.cleanup()
|
|
473
|
+
}
|
|
474
|
+
call.reject(message)
|
|
475
|
+
pendingCall = nil
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
private func cancelFlow(message: String?, rejectPending: Bool) {
|
|
479
|
+
DispatchQueue.main.async { [weak self] in
|
|
480
|
+
self?.cleanup()
|
|
481
|
+
}
|
|
482
|
+
guard rejectPending, let call = pendingCall else { return }
|
|
483
|
+
let errorMessage = message ?? "Spotify connection canceled."
|
|
484
|
+
emitStatus("error", message: errorMessage)
|
|
485
|
+
call.reject(errorMessage)
|
|
486
|
+
pendingCall = nil
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
private func cleanup() {
|
|
490
|
+
spotifyWebView?.configuration.userContentController.removeScriptMessageHandler(forName: "onairosSpotify")
|
|
491
|
+
spotifyWebView?.navigationDelegate = nil
|
|
492
|
+
spotifyWebView = nil
|
|
493
|
+
progressLabel = nil
|
|
494
|
+
loadingOverlayView = nil
|
|
495
|
+
loadingStatusLabel = nil
|
|
496
|
+
loadingProgressView = nil
|
|
497
|
+
loadingActivityIndicator = nil
|
|
498
|
+
overlayWindow?.isHidden = true
|
|
499
|
+
overlayWindow = nil
|
|
500
|
+
pendingJWTToken = ""
|
|
501
|
+
pendingApiKey = ""
|
|
502
|
+
backendBaseURL = ""
|
|
503
|
+
exportFinished = true
|
|
504
|
+
}
|
|
505
|
+
|
|
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
|
+
}
|