forked from stappmus/Omarchy-Spotify
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApi.js
More file actions
2199 lines (2005 loc) · 78.3 KB
/
Copy pathApi.js
File metadata and controls
2199 lines (2005 loc) · 78.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
.pragma library
var API_BASE = "https://api.spotify.com/v1"
var TOKEN_URL = "https://accounts.spotify.com/api/token"
var AUTH_URL = "https://accounts.spotify.com/authorize"
// Deliberately omit profile and email scopes. The remaining scopes correspond
// directly to visible library, history, playlist, and playback controls.
var SCOPES = [
"user-library-read",
"user-library-modify",
"user-follow-read",
"user-follow-modify",
"user-read-recently-played",
"user-read-playback-position",
"user-top-read",
"playlist-read-private",
"playlist-read-collaborative",
"playlist-modify-private",
"playlist-modify-public",
"user-read-playback-state",
"user-modify-playback-state"
]
var SEARCH_TYPES = ["track", "artist", "album", "playlist", "show", "episode", "audiobook"]
var DISCOVERY_SEARCHES = [
"Discover Weekly",
"Release Radar",
"daylist",
"Daily Mix",
"New Music Friday",
"Fresh Finds"
]
// spotifyd's software mixer maps its normalized volume over a 60 dB
// logarithmic range. Convert that control to a cubic slider over the same
// range, matching the gentler taper used by common desktop audio mixers.
// Zero remains a true mute in both directions.
var SPOTIFYD_CUBIC_FLOOR = 0.1
function clampUnit(value) {
return Math.max(0, Math.min(1, Number(value) || 0))
}
function normalizeVolumePercent(value) {
if (value === null || value === undefined || value === "") return null
var volume = Number(value)
return isFinite(volume) ? Math.max(0, Math.min(100, volume)) : null
}
function spotifydVolumeToSlider(value) {
var volume = clampUnit(value)
if (volume <= 0) return 0
var cubicRoot = Math.pow(10, volume - 1)
return clampUnit((cubicRoot - SPOTIFYD_CUBIC_FLOOR)
/ (1 - SPOTIFYD_CUBIC_FLOOR))
}
function sliderToSpotifydVolume(value) {
var slider = clampUnit(value)
if (slider <= 0) return 0
var cubicRoot = SPOTIFYD_CUBIC_FLOOR
+ (1 - SPOTIFYD_CUBIC_FLOOR) * slider
return clampUnit(1 + Math.log(cubicRoot) / Math.LN10)
}
function encode(value) {
return encodeURIComponent(String(value === undefined || value === null ? "" : value))
}
function queryString(values) {
if (!values) return ""
var pairs = []
var keys = Object.keys(values).sort()
for (var i = 0; i < keys.length; i++) {
var key = keys[i]
var value = values[key]
if (value === undefined || value === null || value === "") continue
if (Array.isArray(value)) value = value.join(",")
pairs.push(encode(key) + "=" + encode(value))
}
return pairs.join("&")
}
function appendQuery(path, values) {
var query = queryString(values)
if (!query) return String(path || "")
return String(path || "") + (String(path || "").indexOf("?") >= 0 ? "&" : "?") + query
}
function formBody(values) {
return queryString(values)
}
function shallowCopy(value) {
var copy = ({})
if (!value || typeof value !== "object" || Array.isArray(value)) return copy
for (var key in value) copy[key] = value[key]
return copy
}
function assign(target, source) {
var next = target && typeof target === "object" && !Array.isArray(target)
? target : ({})
if (!source || typeof source !== "object" || Array.isArray(source)) return next
for (var key in source) next[key] = source[key]
return next
}
function parseJson(text, fallback) {
try {
var parsed = JSON.parse(String(text || ""))
return parsed === null ? fallback : parsed
} catch (e) {
return fallback
}
}
function barTrackText(title, artist, showTitle, showArtist, playing, showPaused) {
if (playing !== true && showPaused === false) return ""
var cleanTitle = String(title || "").trim()
var cleanArtist = String(artist || "").trim()
var parts = []
if (showArtist && cleanArtist) parts.push(cleanArtist)
if (showTitle && cleanTitle) parts.push(cleanTitle)
return parts.join(" - ")
}
function canScrollBarText(showTitle, showArtist) {
return showTitle === true || showArtist === true
}
var BAR_TEXT_WIDTH_MIN = 160
var BAR_TEXT_WIDTH_MAX = 560
var BAR_TEXT_WIDTH_STEP = 40
// Slider geometry for the bar label cap. The uncapped notch sits one step past
// the widest real width, so 0 has somewhere to live without a second control.
function barTextWidthSlider() {
return {
min: BAR_TEXT_WIDTH_MIN,
step: BAR_TEXT_WIDTH_STEP,
unlimited: BAR_TEXT_WIDTH_MAX + BAR_TEXT_WIDTH_STEP,
ticks: (BAR_TEXT_WIDTH_MAX - BAR_TEXT_WIDTH_MIN) / BAR_TEXT_WIDTH_STEP + 2
}
}
// Cap in unscaled px, snapped to the slider's notches. 0 means no cap;
// anything unparseable falls back to the historical 240px bound.
function normalizedMaxBarTextWidth(value) {
if (value === undefined || value === null || String(value).trim() === "")
return 240
var width = Number(value)
if (!isFinite(width) || width < 0) return 240
if (width === 0) return 0
var clamped = Math.max(BAR_TEXT_WIDTH_MIN, Math.min(BAR_TEXT_WIDTH_MAX, width))
return BAR_TEXT_WIDTH_MIN + Math.round(
(clamped - BAR_TEXT_WIDTH_MIN) / BAR_TEXT_WIDTH_STEP) * BAR_TEXT_WIDTH_STEP
}
function normalizedScrollSpeed(value) {
var speed = Number(value)
if (!isFinite(speed)) speed = 1
return Math.round(Math.max(0.25, Math.min(3, speed)) * 4) / 4
}
function timestampIsFresh(timestamp, now, lifetimeMs) {
var checkedAt = Number(timestamp)
var current = Number(now)
var lifetime = Number(lifetimeMs)
if (!isFinite(checkedAt) || !isFinite(current) || !isFinite(lifetime)
|| checkedAt <= 0 || lifetime <= 0) return false
var age = current - checkedAt
return age >= 0 && age < lifetime
}
function deadlineRemainingSeconds(deadline, now) {
var end = Number(deadline)
var current = Number(now)
if (!isFinite(end) || !isFinite(current)) return 0
return Math.max(0, Math.ceil((end - current) / 1000))
}
// Maintain a small least-recently-touched key order without replacing the
// caller's array. One touch can add at most one key, so a single returned key
// lets callers evict the matching map entry without replacement collections.
function touchBoundedOrder(order, key, limit) {
if (!Array.isArray(order)) return ""
var name = String(key || "")
if (!name) return ""
var maximum = Math.max(0, Math.floor(Number(limit) || 0))
var oldIndex = order.indexOf(name)
if (oldIndex >= 0) order.splice(oldIndex, 1)
order.push(name)
return order.length > maximum ? String(order.shift() || "") : ""
}
// Nested arrays become array-like QML sequences after passing through a
// ListView model. Preserve them instead of relying on Array.isArray(), which
// returns false for that representation.
function arrayValues(values) {
if (Array.isArray(values)) return values
if (!values || typeof values === "string") return []
var length = Number(values.length)
if (!isFinite(length) || length <= 0) return []
var result = []
for (var i = 0; i < Math.floor(length); i++) result.push(values[i])
return result
}
function safeApiUrl(path) {
var value = String(path || "")
if (value.charAt(0) === "/") return API_BASE + value
if (value === API_BASE || value.indexOf(API_BASE + "/") === 0) return value
return ""
}
function redact(value) {
var text = String(value || "")
text = text.replace(/(authorization\s*:\s*bearer\s+)[^\s]+/ig, "$1<redacted>")
text = text.replace(/(^|[?&\s])((?:code|access_token|refresh_token|code_verifier|client_secret|password)=)[^&#\s]+/ig, "$1$2<redacted>")
text = text.replace(/("(?:access_token|refresh_token|code|code_verifier|client_secret|password)"\s*:\s*")[^"]+/ig, "$1<redacted>")
return text
}
function responseError(status, payload, fallback) {
var message = ""
if (payload && typeof payload === "object") {
if (typeof payload.error === "object" && payload.error) {
message = payload.error.message || payload.error.status || ""
if (payload.error.reason && String(payload.error.reason) !== String(message))
message += (message ? " (" : "") + String(payload.error.reason) + (message ? ")" : "")
}
else if (typeof payload.error === "string")
message = payload.error_description || payload.error
else
message = payload.message || ""
}
if (!message) message = fallback || "Spotify could not complete this request"
return redact(message)
}
function rateLimitSuffix(retryAfter) {
var seconds = Number(String(retryAfter || "").trim())
if (!isFinite(seconds) || seconds <= 0) return ""
seconds = Math.max(1, Math.round(seconds))
return ". Try again in " + seconds + (seconds === 1 ? " second" : " seconds") + "."
}
function rateLimitMessage(retryAfter) {
var suffix = rateLimitSuffix(retryAfter)
return suffix ? "Spotify is busy" + suffix
: "Spotify is busy. Try again in a moment."
}
var API_MAX_IN_FLIGHT = 2
var API_MAX_RATE_LIMIT_RETRIES = 4
function rateLimitRetryMs(retryAfter, attempt) {
var value = String(retryAfter || "").trim()
var seconds = Number(value)
if (!value || !isFinite(seconds) || seconds < 0) return 10000
var headerMs = Math.round(seconds * 1000)
var retry = Math.max(0, Math.floor(Number(attempt) || 0))
var backoffMs = 1000 * Math.pow(2, retry)
// Spotify often 429s again if we retry at exactly Retry-After, especially
// when the header is 1 second. Wait a little longer and grow the delay.
return Math.min(30000, Math.max(1000, headerMs, backoffMs) + 400)
}
function shouldRetryRateLimit(retriesSoFar) {
return (Number(retriesSoFar) || 0) < API_MAX_RATE_LIMIT_RETRIES
}
function apiInFlightLimit(restricted) {
return restricted === true ? 1 : API_MAX_IN_FLIGHT
}
function responseRetryAfter(xhr) {
if (!xhr || typeof xhr.getResponseHeader !== "function") return ""
var value = xhr.getResponseHeader("Retry-After")
if (!value) value = xhr.getResponseHeader("retry-after")
return value ? String(value) : ""
}
function apiRequestIsMutating(method) {
var value = String(method || "GET").toUpperCase()
return value !== "GET" && value !== "HEAD"
}
function enqueueApiJob(queue, job, preferFront) {
var next = arrayValues(queue)
if (!job) return next
if (preferFront === true || apiRequestIsMutating(job.method)) next.unshift(job)
else next.push(job)
return next
}
function dequeueApiJob(queue) {
var next = arrayValues(queue)
while (next.length) {
var job = next.shift()
if (!job || (job.handle && job.handle.aborted === true)) continue
return { job: job, queue: next }
}
return { job: null, queue: next }
}
function apiCooldownMs(now, until) {
var wait = (Number(until) || 0) - (Number(now) || 0)
return wait > 0 ? Math.ceil(wait) : 0
}
function nextRateLimitedUntil(now, retryAfter, currentUntil, attempt) {
var proposed = (Number(now) || 0) + rateLimitRetryMs(retryAfter, attempt)
var existing = Number(currentUntil) || 0
return proposed > existing ? proposed : existing
}
function playlistOwnedByUser(playlist, userId) {
var user = String(userId || "")
return !!playlist && !!user && String(playlist.ownerId || "") === user
}
function playlistItemsHiddenByApi(status, owned, collaborative, knownUser) {
if (owned === true || collaborative === true || knownUser !== true) return false
var code = Number(status) || 0
return code === 403 || code === 200
}
function playlistItemsHiddenMessage() {
return "Spotify does not expose the contents of this playlist unless you own or collaborate on it. You can still play it as a Spotify context."
}
function playlistItemsEmptyMessage(playlist, itemCount, error, status, userId) {
if (!playlist) return ""
var count = Number(itemCount) || 0
var owned = playlistOwnedByUser(playlist, userId)
var collaborative = !!(playlist && playlist.collaborative === true)
var knownUser = String(userId || "") !== ""
if (error) {
if (playlistItemsHiddenByApi(status, owned, collaborative, knownUser))
return playlistItemsHiddenMessage()
return "Couldn't load this playlist. Try again in a moment."
}
if (count > 0) return ""
if (playlistItemsHiddenByApi(200, owned, collaborative, knownUser))
return playlistItemsHiddenMessage()
return "This playlist has no visible items."
}
function localSocketFallbackMessage() {
return "The local player was not ready, so this track is starting through Spotify."
}
// While a player surface is open, keep this computer registered as a Spotify
// Connect receiver. The configured idle timeout begins only after every player
// surface closes.
function visibleLocalReceiverAction(uiVisible, fullyConnected, running, busy) {
if (uiVisible !== true || fullyConnected !== true) return "idle"
if (busy === true) return "wait"
if (running === true) return "refresh"
return "start"
}
// A paused item is still an active media session: keep its MPRIS metadata and
// resume controls alive after the UI closes. Only an empty/stopped receiver is
// eligible for the configured background shutdown timeout.
function idleShutdownShouldRun(daemonRunning, hasMedia, uiVisible, idleMinutes) {
return daemonRunning === true && hasMedia !== true && uiVisible !== true
&& Number(idleMinutes) > 0
}
function remotePlaybackPollShouldRun(loggedIn, loading, uiVisible, useRemote,
playing) {
if (loggedIn !== true || loading === true) return false
if (uiVisible === true) return true
return useRemote === true && playing === true
}
function remotePlaybackPollInterval(uiVisible, useRemote, hasLocal) {
return uiVisible === true && (useRemote === true || hasLocal !== true)
? 5000 : 15000
}
function normalizedShortcutPlayer(value) {
var text = String(value || "")
if (text === "Full player") return "Full player"
if (text === "Mini player") return "Mini player"
return "Omarchy Music app"
}
function normalizedShortcutHints(value) {
return String(value || "On") === "Off" ? "Off" : "On"
}
function shortcutSequenceList(value) {
if (value === undefined || value === null || value === "") return []
return Array.isArray(value) ? value : [value]
}
function parseShortcutSequence(sequence) {
var raw = String(sequence || "").replace(/^\s+|\s+$/g, "")
var result = { ctrl: false, shift: false, alt: false, key: "" }
if (!raw) return result
var parts = raw.split("+")
for (var i = 0; i < parts.length; i++) {
var part = String(parts[i] || "").replace(/^\s+|\s+$/g, "")
if (!part) continue
var lower = part.toLowerCase()
if (lower === "ctrl" || lower === "control") result.ctrl = true
else if (lower === "shift") result.shift = true
else if (lower === "alt") result.alt = true
else if (lower === "meta" || lower === "super") continue
else result.key = part
}
return result
}
function shortcutModifiersMatch(sequence, held) {
var parsed = parseShortcutSequence(sequence)
var flags = held && typeof held === "object" ? held : {}
var ctrl = flags.ctrl === true
var shift = flags.shift === true
var alt = flags.alt === true
return parsed.ctrl === ctrl && parsed.shift === shift && parsed.alt === alt
}
function shortcutModifierFlagsAfterEvent(reportedFlags, pressed, previousFlags,
changedModifierFlag) {
var reported = Number(reportedFlags) || 0
var previous = Number(previousFlags) || 0
var changed = Number(changedModifierFlag) || 0
if (changed !== 0)
return pressed === true ? (reported | changed) : (reported & ~changed)
// Some Qt key-release events omit modifiers that are still physically held.
// A non-modifier release cannot change that state, so retain the last value.
return pressed === true ? reported : previous
}
function shortcutKeycap(sequence) {
var key = String(parseShortcutSequence(sequence).key || "")
var lower = key.toLowerCase()
if (lower === "left") return "←"
if (lower === "right") return "→"
if (lower === "up") return "↑"
if (lower === "down") return "↓"
if (lower === "space") return "Space"
if (lower === "esc" || lower === "escape") return "Esc"
if (lower === "tab") return "Tab"
if (lower === "menu") return "Menu"
return key
}
function shortcutHintCaption(sequences, held, active) {
if (active === false) return ""
var list = shortcutSequenceList(sequences)
var labels = []
var seen = {}
for (var i = 0; i < list.length; i++) {
if (!shortcutModifiersMatch(list[i], held)) continue
var label = shortcutKeycap(list[i])
if (!label || seen[label]) continue
seen[label] = true
labels.push(label)
}
return labels.join(" ")
}
function shortcutOverlayLabel(sequences, held, active, navHint) {
if (active === false) return ""
var nav = String(navHint || "")
var chord = shortcutHintCaption(sequences, held, true)
if (nav && chord && nav !== chord) return nav + " " + chord
if (nav) return nav
return chord
}
function repeatModeLabel(mode) {
var value = String(mode || "off")
if (value === "track") return "This song"
if (value === "context") return "All"
return "Off"
}
var TYPE_LABELS = {
track: { singular: "Song", plural: "Songs" },
artist: { singular: "Artist", plural: "Artists" },
album: { singular: "Album", plural: "Albums" },
playlist: { singular: "Playlist", plural: "Playlists" },
show: { singular: "Podcast", plural: "Podcasts" },
episode: { singular: "Episode", plural: "Episodes" },
audiobook: { singular: "Audiobook", plural: "Books" }
}
function typeLabel(type, plural) {
var entry = TYPE_LABELS[String(type || "")]
if (!entry) return plural ? "results" : "Spotify item"
return plural ? entry.plural : entry.singular
}
function searchTypeLabel(type) {
return typeLabel(type, true)
}
function spotifyTypeLabel(type) {
return typeLabel(type, false)
}
var MUTE_THRESHOLD = 0.001
var UNMUTE_FLOOR = 0.05
var SEARCH_DEBOUNCE_MS = 600
var VOLUME_FLUSH_MS = 80
var VOLUME_FLUSH_REMOTE_MS = 250
var VOLUME_FLUSH_SONOS_MS = 120
var SLIDER_VOLUME_ACK_TOLERANCE = 0.04
function volumeFlushInterval(target) {
var backend = String(target || "").trim().toLowerCase()
if (backend === "remote") return VOLUME_FLUSH_REMOTE_MS
if (backend === "sonos") return VOLUME_FLUSH_SONOS_MS
return VOLUME_FLUSH_MS
}
function nextVolume(current, delta) {
return clampUnit((Number(current) || 0) + (Number(delta) || 0))
}
function pendingSliderVolumeShouldHold(reportedSlider, pending, now) {
if (!pending) return false
if ((Number(now) || 0) >= (Number(pending.expiresAt) || 0)) return false
var requested = Number(pending.slider)
if (!isFinite(requested)) return false
return Math.abs(clampUnit(reportedSlider) - clampUnit(requested))
> SLIDER_VOLUME_ACK_TOLERANCE
}
function displayedSliderVolume(reportedSlider, pending, now) {
if (pendingSliderVolumeShouldHold(reportedSlider, pending, now))
return clampUnit(pending.slider)
return clampUnit(reportedSlider)
}
function shouldRememberVolume(value) {
return clampUnit(value) > MUTE_THRESHOLD
}
function unmuteVolume(previous) {
return Math.max(UNMUTE_FLOOR, Number(previous) || 0)
}
function seekPosition(position, delta, length) {
var next = Math.max(0, (Number(position) || 0) + (Number(delta) || 0))
var maximum = Math.max(0, Number(length) || 0)
return maximum > 0 ? Math.min(maximum, next) : next
}
function backendLoadFields(body) {
var source = body || null
if (!source || typeof source !== "object") return null
var fields = { play: true }
var contextUri = String(source.context_uri || "")
if (contextUri) {
fields.context_uri = contextUri
var offset = source.offset || null
if (offset && offset.uri) fields.offset_uri = String(offset.uri)
if (offset && offset.position !== undefined && offset.position !== null) {
var index = Math.floor(Number(offset.position))
if (isFinite(index) && index >= 0) fields.offset_index = index
}
} else if (Array.isArray(source.uris) && source.uris.length) {
var uris = []
for (var i = 0; i < source.uris.length; i++) {
var uri = String(source.uris[i] || "")
if (uri) uris.push(uri)
}
if (!uris.length) return null
fields.uris = uris
} else {
return null
}
var positionMs = Math.floor(Number(source.position_ms) || 0)
if (positionMs > 0) fields.position_ms = positionMs
return fields
}
// Preserve Spotify's current playback target unless the user explicitly chose
// another device in this app. The local spotifyd player is only the fallback
// when Spotify has no active device. Keeping a restricted device here avoids
// silently moving playback locally; Spotify can report the unsupported action.
function preferredPlaybackDevice(devices, selectedId, explicitSelection, currentDevice) {
var values = Array.isArray(devices) ? devices : []
var key = String(selectedId || "")
if (explicitSelection && key) {
for (var i = 0; i < values.length; i++)
if (String(values[i].id || "") === key && values[i].restricted !== true)
return values[i]
}
var current = currentDevice || null
if (current && current.active === true) {
for (var j = 0; j < values.length; j++)
if (playbackDevicesMatch(values[j], current))
return values[j]
return current
}
for (var k = 0; k < values.length; k++)
if (values[k].active === true)
return values[k]
for (var l = 0; l < values.length; l++)
if (values[l].local === true && values[l].restricted !== true && values[l].id)
return values[l]
return null
}
// Keep an active remote receiver untouched, but remember an active local
// receiver as the implicit selection so the UI and subsequent playback agree.
function automaticLocalPlaybackDevice(selectedId, preferredDevice, localDevice) {
if (String(selectedId || "")) return null
var current = preferredDevice || null
if (current && current.active === true && current.local !== true) return null
var candidate = current && current.local === true ? current : (localDevice || null)
return candidate && candidate.local === true && candidate.id
&& candidate.restricted !== true ? candidate : null
}
// Omitting device_id tells Spotify to keep the user's active device. Address a
// device directly only for an explicit choice or an inactive fallback target.
function playbackTargetDeviceId(device, explicitSelection) {
var item = device || null
if (!item) return ""
return explicitSelection === true || item.active !== true
? String(item.id || "") : ""
}
function isLocalPlaybackDevice(device, configuredName, runtimeName, knownId) {
var item = device || {}
var id = String(item.id || "")
var rememberedId = String(knownId || "")
if (id && rememberedId && id === rememberedId) return true
var name = String(item.sourceName || item.name || "")
var configured = String(configuredName || "")
var runtime = String(runtimeName || "")
return !!name && (name === configured || (!!runtime && name === runtime))
}
// Spotify may expose an active hardware player through /me/player while
// omitting it from /me/player/devices (Sonos is a common example). Device ids
// are authoritative when both endpoints provide one; otherwise fall back to
// the user-visible name and device type.
function playbackDevicesMatch(left, right) {
var first = left || {}
var second = right || {}
var firstId = String(first.id || "")
var secondId = String(second.id || "")
if (firstId && secondId) return firstId === secondId
var firstName = String(first.name || first.sourceName || "").trim().toLowerCase()
var secondName = String(second.name || second.sourceName || "").trim().toLowerCase()
if (!firstName || firstName !== secondName) return false
var firstType = String(first.type || "").trim().toLowerCase()
var secondType = String(second.type || "").trim().toLowerCase()
return !firstType || !secondType || firstType === secondType
}
function pendingRemoteDeviceMatches(pending, device, now) {
if (!pending || !pending.device || !device) return false
var expiresAt = Number(pending.expiresAt)
var current = Number(now)
if (!isFinite(expiresAt) || !isFinite(current) || current >= expiresAt)
return false
return playbackDevicesMatch(pending.device, device)
}
function playbackPositionAt(positionSeconds, receivedAt, playing, now) {
var value = Math.max(0, Number(positionSeconds) || 0)
var anchor = Number(receivedAt)
var current = Number(now)
if (playing === true && isFinite(anchor) && isFinite(current))
value += Math.max(0, current - anchor) / 1000
return value
}
// Spotify can briefly return the pre-command playback state after accepting a
// seek. Keep the requested anchor until the active device reports a position
// close enough to acknowledge it, or until the bounded grace period expires.
function pendingRemoteSeekShouldHold(playback, pending, now) {
var state = playback || null
if (!state || !pendingRemoteDeviceMatches(pending, state.device, now))
return false
var currentUri = String((state.item && state.item.uri) || "")
var requestedUri = String(pending.uri || "")
if (!currentUri || (requestedUri && currentUri !== requestedUri)) return false
var reported = playbackPositionAt(state.progressSeconds, state.receivedAt,
state.playing, now)
var requested = playbackPositionAt(pending.positionSeconds,
pending.requestedAt, pending.playing, now)
return Math.abs(reported - requested) > 2
}
function displayedRemotePosition(playback, pending, now) {
var state = playback || {}
if (pendingRemoteSeekShouldHold(state, pending, now))
return playbackPositionAt(pending.positionSeconds, pending.requestedAt,
pending.playing, now)
return playbackPositionAt(state.progressSeconds, state.receivedAt,
state.playing, now)
}
// Volume has no timestamp in Spotify's response. An exact percentage is
// therefore the acknowledgement; null or a different value remains stale for
// the same bounded grace period.
function pendingRemoteVolumeShouldHold(device, pending, now) {
if (!pendingRemoteDeviceMatches(pending, device, now)) return false
var requested = normalizeVolumePercent(pending.volumePercent)
var reported = normalizeVolumePercent((device || {}).volumePercent)
return requested !== null
&& (reported === null || Math.abs(reported - requested) > 0.5)
}
function playbackSliderFeedbackComplete(sourceValue, pendingValue, sourcePending,
elapsedMs, tolerance, minimumMs, timeoutMs) {
var elapsed = Math.max(0, Number(elapsedMs) || 0)
var timeout = Math.max(1, Number(timeoutMs) || 1)
if (elapsed >= timeout) return true
var minimum = Math.max(0, Number(minimumMs) || 0)
var difference = Math.abs((Number(sourceValue) || 0)
- (Number(pendingValue) || 0))
return elapsed >= minimum && sourcePending !== true
&& difference <= Math.max(0, Number(tolerance) || 0)
}
function spotifyConnectTokenType(value) {
var tokenType = String(value || "default").trim().toLowerCase()
return ["default", "accesstoken", "authorization_code"].indexOf(tokenType) >= 0
? tokenType : "default"
}
function isSpotifyConnectDeviceId(value) {
return /^[A-Za-z0-9_.:-]{8,160}$/.test(String(value || ""))
}
// Some hardware receivers expose their device id as their Web API name. Local
// ZeroConf discovery has the user-facing alias and can safely relabel the same
// receiver because playbackDevicesMatch requires equal ids when both exist.
function spotifyDeviceNameNeedsDiscovery(device) {
var item = device || {}
var name = String(item.name || "").trim()
var id = String(item.id || "").trim()
return !name || (!!id && name.toLowerCase() === id.toLowerCase())
|| /^[a-f0-9]{40}$/i.test(name)
}
function playbackDeviceDisplayName(device, discoveredDevices) {
var item = device || {}
var receivers = Array.isArray(discoveredDevices) ? discoveredDevices : []
for (var i = 0; i < receivers.length; i++) {
var receiver = receivers[i]
if (!receiver || !playbackDevicesMatch(receiver, item)) continue
var discoveredName = String(receiver.name || "").trim()
if (discoveredName) return discoveredName
}
return String(item.name || "").trim()
}
function normalizePlaybackState(value, imageWidth) {
if (!value || typeof value !== "object" || Array.isArray(value)) return null
var source = value
var rawDevice = source.device || null
var device = rawDevice && typeof rawDevice === "object" ? {
id: String(rawDevice.id || ""),
name: String(rawDevice.name || "Spotify device"),
type: String(rawDevice.type || "unknown"),
active: rawDevice.is_active === true,
restricted: rawDevice.is_restricted === true,
// Spotify explicitly permits this field to be null. Preserve that as
// "unknown" instead of making a missing reading look like a real mute.
volumePercent: normalizeVolumePercent(rawDevice.volume_percent),
supportsVolume: rawDevice.supports_volume === true
} : null
var item = source.item && typeof source.item === "object"
? normalizeTrack(source.item, imageWidth || 192) : null
if (!device && !item) return null
return {
device: device,
item: item,
playing: source.is_playing === true,
progressSeconds: Math.max(0, Number(source.progress_ms) || 0) / 1000,
receivedAt: Date.now(),
repeatMode: ["off", "track", "context"].indexOf(String(source.repeat_state)) >= 0
? String(source.repeat_state) : "off",
shuffle: source.shuffle_state === true,
contextUri: source.context && source.context.uri
? String(source.context.uri) : "",
contextHref: source.context && source.context.href
? String(source.context.href) : "",
contextType: source.context && source.context.type
? String(source.context.type) : "",
disallows: source.actions && source.actions.disallows
&& typeof source.actions.disallows === "object"
? source.actions.disallows : ({})
}
}
function imageFor(images, targetWidth) {
if (!Array.isArray(images) || images.length === 0) return ""
var target = Math.max(1, Number(targetWidth) || 128)
var best = null
var bestScore = Number.MAX_VALUE
for (var i = 0; i < images.length; i++) {
var image = images[i]
if (!image || !image.url) continue
var width = Number(image.width) || target
// Prefer the smallest image that is still large enough. Undersized images
// get a larger penalty so artwork is not visibly upscaled.
var score = width >= target ? width - target : (target - width) * 4
if (score < bestScore) {
best = image
bestScore = score
}
}
return best ? String(best.url) : ""
}
function artistNames(artists) {
var source = arrayValues(artists)
var names = []
for (var i = 0; i < source.length; i++)
if (source[i] && source[i].name) names.push(String(source[i].name))
return names.join(", ")
}
function artistSubtitleSuffix(item) {
var source = item || {}
var prefix = artistNames(source.artists)
var subtitle = String(source.subtitle || "")
return prefix && subtitle.indexOf(prefix) === 0
? subtitle.substring(prefix.length) : ""
}
function artistForName(items, name) {
var rows = arrayValues(items)
var expected = String(name || "").trim().toLowerCase()
var fallback = null
for (var i = 0; i < rows.length; i++) {
var item = rows[i]
if (!item || item.type !== "artist" || !item.name) continue
if (!fallback) fallback = item
if (expected && String(item.name).trim().toLowerCase() === expected) return item
}
return fallback
}
function artistContextAvailable(mediaType, trackId, artists) {
return String(mediaType || "") === "track"
|| String(trackId || "") !== "" || arrayValues(artists).length > 0
}
function spotifyTrackId(value) {
var match = String(value || "").match(
/(?:spotify:track:|spotify\/track\/|open\.spotify\.com\/track\/)([A-Za-z0-9]+)/)
return match ? match[1] : ""
}
// Playback from another Spotify Connect device already carries a normalized
// item. Local spotifyd playback may expose only MPRIS metadata, so synthesize
// the small track shape needed by library actions in that case. A matching
// episode must not be mistaken for a track when spotifyd's object-path
// fallback supplied its id.
function currentPlaybackTrack(trackId, remoteTrack, title, artist, album,
coverUrl, durationSeconds, externalUrl) {
var id = String(trackId || "").trim()
if (!id) return null
var remote = remoteTrack && typeof remoteTrack === "object"
? remoteTrack : null
var remoteId = remote
? String(remote.id || spotifyTrackId(remote.uri)).trim() : ""
if (remote && remoteId === id) {
if (String(remote.type || "track") !== "track") return null
if (remote.uri) return remote
}
return {
kind: "item",
type: "track",
id: id,
uri: "spotify:track:" + id,
name: String(title || "Untitled"),
subtitle: String(artist || ""),
album: String(album || ""),
artists: [],
albumItem: null,
parentContext: null,
imageUrl: String(coverUrl || ""),
durationMs: Math.max(0, Number(durationSeconds) || 0) * 1000,
externalUrl: String(externalUrl || "")
}
}
function lyricsSong(trackId, title, artist, album, duration, coverUrl,
positionSeconds) {
var id = String(trackId || "").trim()
var songTitle = String(title || "").trim()
var songArtist = String(artist || "").trim()
if (!id || !songTitle || !songArtist) return null
var songDuration = Math.max(0, Number(duration) || 0)
var songPosition = Math.max(0, Number(positionSeconds) || 0)
if (songDuration > 0) songPosition = Math.min(songPosition, songDuration)
return {
id: "spotify:track:" + id,
title: songTitle,
artist: songArtist,
album: String(album || "").trim(),
duration: songDuration,
coverUrl: String(coverUrl || "").trim(),
positionSeconds: songPosition
}
}
function optionalPluginState(installed, enabled) {
if (installed !== true) return "missing"
return enabled === true ? "ready" : "disabled"
}
// Installation runs non-interactively only after the app's own confirmation
// prompt. Keep the repository and plugin id as separate argv entries so no
// user-controlled text is ever interpreted by a shell.
function optionalPluginSetupCommand(state, pluginId, repositoryUrl) {
var availability = String(state || "")
var id = String(pluginId || "").trim()
var url = String(repositoryUrl || "").trim()
// Use the absolute binary so a Quickshell Process/execDetached does not
// depend on the shell's PATH. --yes keeps add non-interactive.
if (availability === "missing" && url)
return ["/usr/bin/omarchy", "plugin", "add", url, "--enable", "--yes"]
if (availability === "disabled" && id)
return ["/usr/bin/omarchy", "plugin", "enable", id, "--section", "center"]
return []
}
function lyricsInstallIntent(song, surface, now) {
if (!song || typeof song !== "object") return null
return {
song: song,
surface: String(surface || ""),
startedAt: Number(now) || Date.now()
}
}
function lyricsInstallIntentIsFresh(intent, now, lifetimeMs) {
if (!intent || typeof intent !== "object" || !intent.song) return false
return timestampIsFresh(intent.startedAt, now,
lifetimeMs === undefined ? 180000 : lifetimeMs)
}
function sessionWithoutLyricsInstall(session) {
var next = shallowCopy(session)
delete next.pendingLyricsInstall
return next
}
var SESSION_STATE_LIMIT = 16000
function normalizedSessionState(value) {
var session = value
if (typeof session === "string") session = parseJson(session, ({}))
if (!session || typeof session !== "object" || Array.isArray(session)) session = ({})
return JSON.stringify(session).length <= SESSION_STATE_LIMIT ? session : ({})
}
function sessionRecord(sessionState, searchHistory) {
return {
sessionState: normalizedSessionState(sessionState),
searchHistory: parseStringList(searchHistory, 12)
}
}
function emptySessionRecord() {
return sessionRecord(({}), [])
}
function parseSessionRecord(raw) {
var parsed = parseJson(String(raw || ""), null)
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
return emptySessionRecord()
return sessionRecord(parsed.sessionState, parsed.searchHistory)
}
function encodeSessionRecord(sessionState, searchHistory) {
var record = sessionRecord(sessionState, searchHistory)
record.version = 1
return JSON.stringify(record, null, 2) + "\n"
}
function sessionRecordIsEmpty(record) {
var value = record && typeof record === "object" ? record : emptySessionRecord()
var session = value.sessionState
var history = value.searchHistory
var hasSession = !!session && typeof session === "object" && !Array.isArray(session)
&& Object.keys(session).length > 0