forked from spicetify/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spicetifyWrapper.js
1730 lines (1637 loc) · 66.5 KB
/
spicetifyWrapper.js
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
const Spicetify = {
get CosmosAPI() {return window.cosmos},
get BridgeAPI() {return window.bridge},
get LiveAPI() {return window.live},
Player: {
addEventListener: (type, callback) => {
if (!(type in Spicetify.Player.eventListeners)) {
Spicetify.Player.eventListeners[type] = [];
}
Spicetify.Player.eventListeners[type].push(callback)
},
dispatchEvent: (event) => {
if (!(event.type in Spicetify.Player.eventListeners)) {
return true;
}
const stack = Spicetify.Player.eventListeners[event.type];
for (let i = 0; i < stack.length; i++) {
if (typeof stack[i] === "function") {
stack[i](event);
}
}
return !event.defaultPrevented;
},
eventListeners: {},
seek: (p) => {
if (p <= 1) {
p = Math.round(p * Spicetify.Player.origin.duration());
}
Spicetify.Player.origin.seek(p);
},
getProgress: () => Spicetify.Player.origin.progressbar.getRealValue(),
getProgressPercent: () => Spicetify.Player.origin.progressbar.getPercentage(),
getDuration: () => Spicetify.Player.origin.duration(),
setVolume: (v) => { Spicetify.Player.origin.changeVolume(v, false) },
increaseVolume: () => { Spicetify.Player.origin.increaseVolume() },
decreaseVolume: () => { Spicetify.Player.origin.decreaseVolume() },
getVolume: () => Spicetify.Player.origin.volume(),
next: () => { Spicetify.Player.origin._doSkipToNext() },
back: () => { Spicetify.Player.origin._doSkipToPrevious() },
togglePlay: () => { Spicetify.Player.origin._doTogglePlay() },
isPlaying: () => Spicetify.Player.origin.playing(),
toggleShuffle: () => { Spicetify.Player.origin.toggleShuffle() },
getShuffle: () => Spicetify.Player.origin.shuffle(),
setShuffle: (b) => { Spicetify.Player.origin.shuffle(b) },
toggleRepeat: () => { Spicetify.Player.origin.toggleRepeat() },
getRepeat: () => Spicetify.Player.origin.repeat(),
setRepeat: (r) => { Spicetify.Player.origin.repeat(r) },
getMute: () => Spicetify.Player.origin.mute(),
toggleMute: () => { Spicetify.Player.origin._doToggleMute() },
setMute: (b) => { Spicetify.Player.origin.changeVolume(Spicetify.Player.origin._unmutedVolume, b) },
formatTime: (ms) => Spicetify.Player.origin._formatTime(ms),
getHeart: () => Spicetify.LiveAPI(Spicetify.Player.data.track.uri).get("added"),
pause: () => {Spicetify.Player.isPlaying() && Spicetify.Player.togglePlay()},
play: () => {!Spicetify.Player.isPlaying() && Spicetify.Player.togglePlay()},
removeEventListener: (type, callback) => {
if (!(type in Spicetify.Player.eventListeners)) {
return;
}
const stack = Spicetify.Player.eventListeners[type];
for (let i = 0; i < stack.length; i++) {
if (stack[i] === callback) {
stack.splice(i, 1);
return;
}
}
},
skipBack: (amount = 15e3) => {Spicetify.Player.seek(Spicetify.Player.getProgress() - amount)},
skipForward: (amount = 15e3) => {Spicetify.Player.seek(Spicetify.Player.getProgress() + amount)},
toggleHeart: () => {document.querySelector('[data-interaction-target="save-remove-button"]').click()},
},
showNotification: (text) => {
Spicetify.EventDispatcher.dispatchEvent(
new Spicetify.Event(Spicetify.Event.TYPES.SHOW_NOTIFICATION_BUBBLE, {
i18n: text,
messageHtml: text
})
);
},
test: () => {
const SPICETIFY_METHOD = [
"Player",
"addToQueue",
"BridgeAPI",
"CosmosAPI",
"Event",
"EventDispatcher",
"getAudioData",
"Keyboard",
"URI",
"LiveAPI",
"LocalStorage",
"PlaybackControl",
"Queue",
"removeFromQueue",
"showNotification",
"getAblumArtColors",
"Menu",
"ContextMenu",
"Abba",
];
const PLAYER_METHOD = [
"addEventListener",
"back",
"data",
"decreaseVolume",
"dispatchEvent",
"eventListeners",
"formatTime",
"getDuration",
"getHeart",
"getMute",
"getProgress",
"getProgressPercent",
"getRepeat",
"getShuffle",
"getVolume",
"increaseVolume",
"isPlaying",
"next",
"pause",
"play",
"removeEventListener",
"seek",
"setMute",
"setRepeat",
"setShuffle",
"setVolume",
"skipBack",
"skipForward",
"toggleHeart",
"toggleMute",
"togglePlay",
"toggleRepeat",
"toggleShuffle",
]
let count = SPICETIFY_METHOD.length;
SPICETIFY_METHOD.forEach((method) => {
if (Spicetify[method] === undefined || Spicetify[method] === null) {
console.error(`Spicetify.${method} is not available. Please open an issue in Spicetify repository to inform me about it.`)
count--;
}
})
console.log(`${count}/${SPICETIFY_METHOD.length} Spicetify methods and objects are OK.`)
count = PLAYER_METHOD.length;
PLAYER_METHOD.forEach((method) => {
if (Spicetify.Player[method] === undefined || Spicetify.Player[method] === null) {
console.error(`Spicetify.Player.${method} is not available. Please open an issue in Spicetify repository to inform me about it.`)
count--;
}
})
console.log(`${count}/${PLAYER_METHOD.length} Spicetify.Player methods and objects are OK.`)
}
}
Spicetify.URI = (function () {
/**
* Copyright (c) 2017 Spotify AB
*
* Fast base62 encoder/decoder.
*
* Usage:
*
* Base62.toHex('1C0pasJ0dS2Z46GKh2puYo') // -> '34ff970885ca8fa02c0d6e459377d5d0'
* ^^^
* |
* Length-22 base62-encoded ID.
* Lengths other than 22 or invalid base62 IDs
* are not supported.
*
* Base62.fromHex('34ff970885ca8fa02c0d6e459377d5d0') // -> '1C0pasJ0dS2Z46GKh2puYo'
* ^^^
* |
* Length-32 hex-encoded ID.
* Lengths other than 32 are not supported.
*
* Written by @ludde, programatically tested and documented by @felipec.
*/
var Base62 = (function () {
// Alphabets
var HEX16 = '0123456789abcdef';
var BASE62 =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Hexadecimal fragments
var HEX256 = [];
HEX256.length = 256;
for (var i = 0; i < 256; i++) {
HEX256[i] = HEX16[i >> 4] + HEX16[i & 0xf];
}
// Look-up tables
var ID62 = [];
ID62.length = 128;
for (var i = 0; i < BASE62.length; ++i) {
ID62[BASE62.charCodeAt(i)] = i;
}
var ID16 = [];
for (var i = 0; i < 16; i++) {
ID16[HEX16.charCodeAt(i)] = i;
}
for (var i = 0; i < 6; i++) {
ID16['ABCDEF'.charCodeAt(i)] = 10 + i;
}
return {
toHex: function (s) {
if (s.length !== 22) {
// Can only parse base62 ids with length == 22.
// Invalid base62 ids will lead to garbage in the output.
return null;
}
// 1 / (2^32)
var MAX_INT_INV = 2.3283064365386963e-10;
// 2^32
var MAX_INT = 0x100000000;
// 62^3
var P62_3 = 238328;
var p0, p1, p2, p3;
var v;
// First 7 characters fit in 2^53
// prettier-ignore
p0 =
ID62[s.charCodeAt(0)] * 56800235584 + // * 62^6
ID62[s.charCodeAt(1)] * 916132832 + // * 62^5
ID62[s.charCodeAt(2)] * 14776336 + // * 62^4
ID62[s.charCodeAt(3)] * 238328 + // * 62^3
ID62[s.charCodeAt(4)] * 3844 + // * 62^2
ID62[s.charCodeAt(5)] * 62 + // * 62^1
ID62[s.charCodeAt(6)]; // * 62^0
p1 = (p0 * MAX_INT_INV) | 0;
p0 -= p1 * MAX_INT;
// 62^10 < 2^64
v =
ID62[s.charCodeAt(7)] * 3844 +
ID62[s.charCodeAt(8)] * 62 +
ID62[s.charCodeAt(9)];
(p0 = p0 * P62_3 + v), (p0 = p0 - (v = (p0 * MAX_INT_INV) | 0) * MAX_INT);
p1 = p1 * P62_3 + v;
// 62^13 < 2^96
v =
ID62[s.charCodeAt(10)] * 3844 +
ID62[s.charCodeAt(11)] * 62 +
ID62[s.charCodeAt(12)];
(p0 = p0 * P62_3 + v), (p0 = p0 - (v = (p0 * MAX_INT_INV) | 0) * MAX_INT);
(p1 = p1 * P62_3 + v), (p1 = p1 - (v = (p1 * MAX_INT_INV) | 0) * MAX_INT);
p2 = v;
// 62^16 < 2^96
v =
ID62[s.charCodeAt(13)] * 3844 +
ID62[s.charCodeAt(14)] * 62 +
ID62[s.charCodeAt(15)];
(p0 = p0 * P62_3 + v), (p0 = p0 - (v = (p0 * MAX_INT_INV) | 0) * MAX_INT);
(p1 = p1 * P62_3 + v), (p1 = p1 - (v = (p1 * MAX_INT_INV) | 0) * MAX_INT);
p2 = p2 * P62_3 + v;
// 62^19 < 2^128
v =
ID62[s.charCodeAt(16)] * 3844 +
ID62[s.charCodeAt(17)] * 62 +
ID62[s.charCodeAt(18)];
(p0 = p0 * P62_3 + v), (p0 = p0 - (v = (p0 * MAX_INT_INV) | 0) * MAX_INT);
(p1 = p1 * P62_3 + v), (p1 = p1 - (v = (p1 * MAX_INT_INV) | 0) * MAX_INT);
(p2 = p2 * P62_3 + v), (p2 = p2 - (v = (p2 * MAX_INT_INV) | 0) * MAX_INT);
p3 = v;
v =
ID62[s.charCodeAt(19)] * 3844 +
ID62[s.charCodeAt(20)] * 62 +
ID62[s.charCodeAt(21)];
(p0 = p0 * P62_3 + v), (p0 = p0 - (v = (p0 * MAX_INT_INV) | 0) * MAX_INT);
(p1 = p1 * P62_3 + v), (p1 = p1 - (v = (p1 * MAX_INT_INV) | 0) * MAX_INT);
(p2 = p2 * P62_3 + v), (p2 = p2 - (v = (p2 * MAX_INT_INV) | 0) * MAX_INT);
(p3 = p3 * P62_3 + v), (p3 = p3 - (v = (p3 * MAX_INT_INV) | 0) * MAX_INT);
if (v) {
// carry not allowed
return null;
}
// prettier-ignore
return HEX256[p3 >>> 24] + HEX256[(p3 >>> 16) & 0xFF] + HEX256[(p3 >>> 8) & 0xFF] + HEX256[(p3) & 0xFF] +
HEX256[p2 >>> 24] + HEX256[(p2 >>> 16) & 0xFF] + HEX256[(p2 >>> 8) & 0xFF] + HEX256[(p2) & 0xFF] +
HEX256[p1 >>> 24] + HEX256[(p1 >>> 16) & 0xFF] + HEX256[(p1 >>> 8) & 0xFF] + HEX256[(p1) & 0xFF] +
HEX256[p0 >>> 24] + HEX256[(p0 >>> 16) & 0xFF] + HEX256[(p0 >>> 8) & 0xFF] + HEX256[(p0) & 0xFF];
},
fromHex: function (s) {
var i;
var p0 = 0, p1 = 0, p2 = 0;
for (i = 0; i < 10; i++) p2 = p2 * 16 + ID16[s.charCodeAt(i)];
for (i = 0; i < 11; i++) p1 = p1 * 16 + ID16[s.charCodeAt(i + 10)];
for (i = 0; i < 11; i++) p0 = p0 * 16 + ID16[s.charCodeAt(i + 21)];
if (isNaN(p0 + p1 + p2)) {
return null;
}
var P16_11 = 17592186044416; // 16^11
var INV_62 = 1.0 / 62;
var acc;
var ret = '';
i = 0;
for (; i < 7; ++i) {
acc = p2;
p2 = Math.floor(acc * INV_62);
acc = (acc - p2 * 62) * P16_11 + p1;
p1 = Math.floor(acc * INV_62);
acc = (acc - p1 * 62) * P16_11 + p0;
p0 = Math.floor(acc * INV_62);
ret = BASE62[acc - p0 * 62] + ret;
}
p1 += p2 * P16_11;
for (; i < 15; ++i) {
acc = p1;
p1 = Math.floor(acc * INV_62);
acc = (acc - p1 * 62) * P16_11 + p0;
p0 = Math.floor(acc * INV_62);
ret = BASE62[acc - p0 * 62] + ret;
}
p0 += p1 * P16_11;
for (; i < 21; ++i) {
acc = p0;
p0 = Math.floor(acc * INV_62);
ret = BASE62[acc - p0 * 62] + ret;
}
return BASE62[p0] + ret;
},
// Expose the lookup tables
HEX256: HEX256, // number -> 'hh'
ID16: ID16, // hexadecimal char code -> 0..15
ID62: ID62, // base62 char code -> 0..61
};
})();
/**
* The URI prefix for URIs.
*
* @const
* @private
*/
var URI_PREFIX = 'spotify:';
/**
* The URL prefix for Play.
*
* @const
* @private
*/
var PLAY_HTTP_PREFIX = 'http://play.spotify.com/';
/**
* The HTTPS URL prefix for Play.
*
* @const
* @private
*/
var PLAY_HTTPS_PREFIX = 'https://play.spotify.com/';
/**
* The URL prefix for Open.
*
* @const
* @private
*/
var OPEN_HTTP_PREFIX = 'http://open.spotify.com/';
/**
* The HTTPS URL prefix for Open.
*
* @const
* @private
*/
var OPEN_HTTPS_PREFIX = 'https://open.spotify.com/';
var ERROR_INVALID = new TypeError('Invalid Spotify URI!');
var ERROR_NOT_IMPLEMENTED = new TypeError('Not implemented!');
/**
* The format for the URI to parse.
*
* @enum {number}
* @private
*/
var Format = {
URI: 0,
URL: 1
};
/**
* Represents the result of a URI splitting operation.
*
* @typedef {{
* format: Format,
* components: Array.<string>
* }}
* @see _splitIntoComponents
* @private
*/
var SplittedURI;
/**
* Split an string URI or HTTP/HTTPS URL into components, skipping the prefix.
*
* @param {string} str A string URI to split.
* @return {SplittedURI} The parsed URI.
* @private
*/
var _splitIntoComponents = function (str) {
var components;
var format;
var query;
var anchor;
var querySplit = str.split('?');
if (querySplit.length > 1) {
str = querySplit.shift();
query = querySplit.pop();
var queryHashSplit = query.split('#');
if (queryHashSplit.length > 1) {
query = queryHashSplit.shift();
anchor = queryHashSplit.pop();
}
query = decodeQueryString(query);
}
var hashSplit = str.split('#');
if (hashSplit.length > 1) {
// first token
str = hashSplit.shift();
// last token
anchor = hashSplit.pop();
}
if (str.indexOf(URI_PREFIX) === 0) {
components = str.slice(URI_PREFIX.length).split(':');
format = Format.URI;
} else {
// For HTTP URLs, ignore any query string argument
str = str.split('?')[0];
if (str.indexOf(PLAY_HTTP_PREFIX) === 0) {
components = str.slice(PLAY_HTTP_PREFIX.length).split('/');
} else if (str.indexOf(PLAY_HTTPS_PREFIX) === 0) {
components = str.slice(PLAY_HTTPS_PREFIX.length).split('/');
} else if (str.indexOf(OPEN_HTTP_PREFIX) === 0) {
components = str.slice(OPEN_HTTP_PREFIX.length).split('/');
} else if (str.indexOf(OPEN_HTTPS_PREFIX) === 0) {
components = str.slice(OPEN_HTTPS_PREFIX.length).split('/');
} else {
throw ERROR_INVALID;
}
format = Format.URL;
}
if (anchor) {
components.push(anchor);
}
return {
format: format,
components: components,
query: query
};
};
/**
* Encodes a component according to a format.
*
* @param {string} component A component string.
* @param {Format} format A format.
* @return {string} An encoded component string.
* @private
*/
var _encodeComponent = function (component, format) {
component = encodeURIComponent(component);
if (format === Format.URI) {
component = component.replace(/%20/g, '+');
}
// encode characters that are not encoded by default by encodeURIComponent
// but that the Spotify URI spec encodes: !'*()
component = component.replace(/[!'()]/g, escape);
component = component.replace(/\*/g, '%2A');
return component;
};
/**
* Decodes a component according to a format.
*
* @param {string} component An encoded component string.
* @param {Format} format A format.
* @return {string} An decoded component string.
* @private
*/
var _decodeComponent = function (component, format) {
var part = format == Format.URI ? component.replace(/\+/g, '%20') : component;
return decodeURIComponent(part);
};
/**
* Returns the components of a URI as an array.
*
* @param {URI} uri A uri.
* @param {Format} format The output format.
* @return {Array.<string>} An array of uri components.
* @private
*/
var _getComponents = function (uri, format) {
var base62;
if (uri.id) {
base62 = uri._base62Id;
}
var components;
var i;
var len;
switch (uri.type) {
case URI.Type.ALBUM:
components = [URI.Type.ALBUM, base62];
if (uri.disc) {
components.push(uri.disc);
}
return components;
case URI.Type.AD:
return [URI.Type.AD, uri._base62Id];
case URI.Type.ARTIST:
return [URI.Type.ARTIST, base62];
case URI.Type.ARTIST_TOPLIST:
return [URI.Type.ARTIST, base62, URI.Type.TOP, uri.toplist];
case URI.Type.DAILY_MIX:
return [URI.Type.DAILY_MIX, base62];
case URI.Type.SEARCH:
return [URI.Type.SEARCH, _encodeComponent(uri.query, format)];
case URI.Type.TRACK:
if (uri.context || uri.play) {
base62 += encodeQueryString({
context: uri.context,
play: uri.play
});
}
if (uri.anchor) {
base62 += '#' + uri.anchor;
}
return [URI.Type.TRACK, base62];
case URI.Type.TRACKSET:
var trackIds = [];
for (i = 0, len = uri.tracks.length; i < len; i++) {
trackIds.push(uri.tracks[i]._base62Id);
}
trackIds = [trackIds.join(',')];
// Index can be 0 sometimes (required for trackset)
if (uri.index !== null) {
trackIds.push('#', uri.index);
}
return [URI.Type.TRACKSET, _encodeComponent(uri.name)].concat(trackIds);
case URI.Type.FACEBOOK:
return [URI.Type.USER, URI.Type.FACEBOOK, uri.uid];
case URI.Type.AUDIO_FILE:
return [URI.Type.AUDIO_FILE, uri.extension, uri._base62Id];
case URI.Type.FOLDER:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.FOLDER, uri._base62Id];
case URI.Type.FOLLOWERS:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.FOLLOWERS];
case URI.Type.FOLLOWING:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.FOLLOWING];
case URI.Type.PLAYLIST:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.PLAYLIST, base62];
case URI.Type.PLAYLIST_V2:
return [URI.Type.PLAYLIST, base62];
case URI.Type.STARRED:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.STARRED];
case URI.Type.TEMP_PLAYLIST:
return [URI.Type.TEMP_PLAYLIST, uri.origin, uri.data];
case URI.Type.CONTEXT_GROUP:
return [URI.Type.CONTEXT_GROUP, uri.origin, uri.name];
case URI.Type.USER_TOPLIST:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.TOP, uri.toplist];
// Legacy Toplist
case URI.Type.USER_TOP_TRACKS:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.TOPLIST];
case URI.Type.TOPLIST:
return [URI.Type.TOP, uri.toplist].concat(uri.global ? [URI.Type.GLOBAL] : ['country', uri.country]);
case URI.Type.INBOX:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.INBOX];
case URI.Type.ROOTLIST:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.ROOTLIST];
case URI.Type.PUBLISHED_ROOTLIST:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.PUBLISHED_ROOTLIST];
case URI.Type.COLLECTION_TRACK_LIST:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.COLLECTION_TRACK_LIST, base62];
case URI.Type.PROFILE:
if (uri.args && uri.args.length > 0)
return [URI.Type.USER, _encodeComponent(uri.username, format)].concat(uri.args);
return [URI.Type.USER, _encodeComponent(uri.username, format)];
case URI.Type.LOCAL_ARTIST:
return [URI.Type.LOCAL, _encodeComponent(uri.artist, format)];
case URI.Type.LOCAL_ALBUM:
return [URI.Type.LOCAL, _encodeComponent(uri.artist, format), _encodeComponent(uri.album, format)];
case URI.Type.LOCAL:
return [URI.Type.LOCAL,
_encodeComponent(uri.artist, format),
_encodeComponent(uri.album, format),
_encodeComponent(uri.track, format),
uri.duration];
case URI.Type.LIBRARY:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.LIBRARY].concat(uri.category ? [uri.category] : []);
case URI.Type.IMAGE:
return [URI.Type.IMAGE, uri._base62Id];
case URI.Type.MOSAIC:
components = uri.ids.slice(0);
components.unshift(URI.Type.MOSAIC);
return components;
case URI.Type.RADIO:
return [URI.Type.RADIO, uri.args];
case URI.Type.SPECIAL:
components = [URI.Type.SPECIAL];
var args = uri.args || [];
for (i = 0, len = args.length; i < len; ++i)
components.push(_encodeComponent(args[i], format));
return components;
case URI.Type.STATION:
components = [URI.Type.STATION];
var args = uri.args || [];
for (i = 0, len = args.length; i < len; i++) {
components.push(_encodeComponent(args[i], format));
}
return components;
case URI.Type.APPLICATION:
components = [URI.Type.APP, uri._base62Id];
var args = uri.args || [];
for (i = 0, len = args.length; i < len; ++i)
components.push(_encodeComponent(args[i], format));
return components;
case URI.Type.COLLECTION_ALBUM:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.COLLECTION, URI.Type.ALBUM, base62];
case URI.Type.COLLECTION_MISSING_ALBUM:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.COLLECTION, URI.Type.ALBUM, base62, 'missing'];
case URI.Type.COLLECTION_ARTIST:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.COLLECTION, URI.Type.ARTIST, base62];
case URI.Type.COLLECTION:
return [URI.Type.USER, _encodeComponent(uri.username, format), URI.Type.COLLECTION].concat(uri.category ? [uri.category] : []);
case URI.Type.EPISODE:
if (uri.context || uri.play) {
base62 += encodeQueryString({
context: uri.context,
play: uri.play
});
}
return [URI.Type.EPISODE, base62];
case URI.Type.SHOW:
return [URI.Type.SHOW, base62];
case URI.Type.CONCERT:
return [URI.Type.CONCERT, base62];
default:
throw ERROR_INVALID;
}
};
var encodeQueryString = function (values) {
var str = '?';
for (var i in values) {
if (values.hasOwnProperty(i) && values[i] !== undefined) {
if (str.length > 1) {
str += '&';
}
str += i + '=' + encodeURIComponent(values[i]);
}
}
return str;
};
var decodeQueryString = function (str) {
return str.split('&').reduce(function (object, pair) {
pair = pair.split('=');
object[pair[0]] = decodeURIComponent(pair[1]);
return object;
}, {});
};
/**
* Parses the components of a URI into a real URI object.
*
* @param {Array.<string>} components The components of the URI as a string
* array.
* @param {Format} format The format of the source string.
* @return {URI} The URI object.
* @private
*/
var _parseFromComponents = function (components, format, query) {
var _current = 0;
query = query || {};
var _getNextComponent = function () {
return components[_current++];
};
var _getIdComponent = function () {
var component = _getNextComponent();
if (component.length > 22) {
throw new Error('Invalid ID');
}
return component;
};
var _getRemainingComponents = function () {
return components.slice(_current);
};
var _getRemainingString = function () {
var separator = (format == Format.URI) ? ':' : '/';
return components.slice(_current).join(separator);
};
var part = _getNextComponent();
var id;
var i;
var len;
switch (part) {
case URI.Type.ALBUM:
return URI.albumURI(_getIdComponent(), parseInt(_getNextComponent(), 10));
case URI.Type.AD:
return URI.adURI(_getNextComponent());
case URI.Type.ARTIST:
id = _getIdComponent();
if (_getNextComponent() == URI.Type.TOP) {
return URI.artistToplistURI(id, _getNextComponent());
} else {
return URI.artistURI(id);
}
case URI.Type.AUDIO_FILE:
return URI.audioFileURI(_getNextComponent(), _getNextComponent());
case URI.Type.DAILY_MIX:
return URI.dailyMixURI(_getIdComponent());
case URI.Type.TEMP_PLAYLIST:
return URI.temporaryPlaylistURI(_getNextComponent(), _getRemainingString());
case URI.Type.PLAYLIST:
return URI.playlistV2URI(_getIdComponent());
case URI.Type.SEARCH:
return URI.searchURI(_decodeComponent(_getRemainingString(), format));
case URI.Type.TRACK:
return URI.trackURI(_getIdComponent(), _getNextComponent(), query.context, query.play);
case URI.Type.TRACKSET:
var name = _decodeComponent(_getNextComponent());
var tracksArray = _getNextComponent();
var hashSign = _getNextComponent();
var index = parseInt(_getNextComponent(), 10);
// Sanity check: %23 is URL code for "#"
if (hashSign !== '%23' || isNaN(index)) {
index = null;
}
var tracksetTracks = [];
if (tracksArray) {
tracksArray = _decodeComponent(tracksArray).split(',');
for (i = 0, len = tracksArray.length; i < len; i++) {
var trackId = tracksArray[i];
tracksetTracks.push(URI.trackURI(trackId));
}
}
return URI.tracksetURI(tracksetTracks, name, index);
case URI.Type.CONTEXT_GROUP:
return URI.contextGroupURI(_getNextComponent(), _getNextComponent());
case URI.Type.TOP:
var type = _getNextComponent();
if (_getNextComponent() == URI.Type.GLOBAL) {
return URI.toplistURI(type, null, true);
} else {
return URI.toplistURI(type, _getNextComponent(), false);
}
case URI.Type.USER:
var username = _decodeComponent(_getNextComponent(), format);
var text = _getNextComponent();
if (username == URI.Type.FACEBOOK && text != null) {
return URI.facebookURI(parseInt(text, 10));
} else if (text != null) {
switch (text) {
case URI.Type.PLAYLIST:
return URI.playlistURI(username, _getIdComponent());
case URI.Type.FOLDER:
return URI.folderURI(username, _getIdComponent());
case URI.Type.COLLECTION_TRACK_LIST:
return URI.collectionTrackList(username, _getIdComponent());
case URI.Type.COLLECTION:
var collectionItemType = _getNextComponent();
switch (collectionItemType) {
case URI.Type.ALBUM:
id = _getIdComponent();
if (_getNextComponent() === 'missing') {
return URI.collectionMissingAlbumURI(username, id);
} else {
return URI.collectionAlbumURI(username, id);
}
case URI.Type.ARTIST:
return URI.collectionArtistURI(username, _getIdComponent());
default:
return URI.collectionURI(username, collectionItemType);
}
case URI.Type.STARRED:
return URI.starredURI(username);
case URI.Type.FOLLOWERS:
return URI.followersURI(username);
case URI.Type.FOLLOWING:
return URI.followingURI(username);
case URI.Type.TOP:
return URI.userToplistURI(username, _getNextComponent());
case URI.Type.INBOX:
return URI.inboxURI(username);
case URI.Type.ROOTLIST:
return URI.rootlistURI(username);
case URI.Type.PUBLISHED_ROOTLIST:
return URI.publishedRootlistURI(username);
case URI.Type.TOPLIST:
// legacy toplist
return URI.userTopTracksURI(username);
case URI.Type.LIBRARY:
return URI.libraryURI(username, _getNextComponent());
}
}
var rem = _getRemainingComponents();
if (text != null && rem.length > 0) {
return URI.profileURI(username, [text].concat(rem));
} else if (text != null) {
return URI.profileURI(username, [text]);
} else {
return URI.profileURI(username);
}
case URI.Type.LOCAL:
var artistNameComponent = _getNextComponent();
var artistName = artistNameComponent && _decodeComponent(artistNameComponent, format);
var albumNameComponent = _getNextComponent();
var albumName = albumNameComponent && _decodeComponent(albumNameComponent, format);
var trackNameComponent = _getNextComponent();
var trackName = trackNameComponent && _decodeComponent(trackNameComponent, format);
var durationComponent = _getNextComponent();
var duration = parseInt(durationComponent, 10);
if (trackNameComponent !== undefined) {
return URI.localURI(artistName, albumName, trackName, duration);
} else if (albumNameComponent !== undefined) {
return URI.localAlbumURI(artistName, albumName);
} else {
return URI.localArtistURI(artistName);
}
case URI.Type.IMAGE:
return URI.imageURI(_getIdComponent());
case URI.Type.MOSAIC:
return URI.mosaicURI(components.slice(_current));
case URI.Type.RADIO:
return URI.radioURI(_getRemainingString());
case URI.Type.SPECIAL:
var args = _getRemainingComponents();
for (i = 0, len = args.length; i < len; ++i)
args[i] = _decodeComponent(args[i], format);
return URI.specialURI(args);
case URI.Type.STATION:
return URI.stationURI(_getRemainingComponents());
case URI.Type.EPISODE:
return URI.episodeURI(_getIdComponent(), query.context, query.play);
case URI.Type.SHOW:
return URI.showURI(_getIdComponent());
case URI.Type.CONCERT:
return URI.concertURI(_getIdComponent());
case '':
break;
default:
if (part === URI.Type.APP) {
id = _getNextComponent();
} else {
id = part;
}
var decodedId = _decodeComponent(id, format);
if (_encodeComponent(decodedId, format) !== id) {
break;
}
var args = _getRemainingComponents();
for (i = 0, len = args.length; i < len; ++i)
args[i] = _decodeComponent(args[i], format);
return URI.applicationURI(decodedId, args);
}
throw ERROR_INVALID;
};
/**
* A class holding information about a uri.
*
* @constructor
* @param {URI.Type} type
* @param {Object} props
*/
function URI(type, props) {
this.type = type;
// Merge properties into URI object.
for (var prop in props) {
if (typeof props[prop] == 'function') {
continue;
}
this[prop] = props[prop];
}
}
// Lazy convert the id to hexadecimal only when requested
Object.defineProperty(URI.prototype, 'id', {
get: function () {
if (!this._hexId) {
this._hexId = this._base62Id ? URI.idToHex(this._base62Id) : undefined;
}
return this._hexId;
},
set: function (id) {
this._base62Id = id ? URI.hexToId(id) : undefined;
this._hexId = undefined;
},
enumerable: true,
configurable: true
});
URI.prototype.toAppType = function () {
if (this.type == URI.Type.APPLICATION) {
return URI.applicationURI(this.id, this.args);
} else {
var components = _getComponents(this, Format.URL);
var id = components.shift();
var len = components.length;
if (len) {
while (len--) {
components[len] = _decodeComponent(components[len], Format.URL);
}
}
if (this.type == URI.Type.RADIO) {
components = components.shift().split(':');
}
var result = URI.applicationURI(id, components);
return result;
}
};
URI.prototype.toRealType = function () {
if (this.type == URI.Type.APPLICATION) {
return _parseFromComponents([this.id].concat(this.args), Format.URI);
} else {
return new URI(null, this);
}
};
URI.prototype.toURI = function () {
return URI_PREFIX + _getComponents(this, Format.URI).join(':');
};
URI.prototype.toString = function () {
return this.toURI();
};
URI.prototype.toURLPath = function (opt_leadingSlash) {
var components = _getComponents(this, Format.URL);
if (components[0] === URI.Type.APP) {
components.shift();
}
// Some URIs are allowed to have empty components. It should be investigated
// whether we need to strip empty components at all from any URIs. For now,
// we check specifically for tracksets and local tracks and strip empty
// components for all other URIs.
//
// For tracksets, it's permissible to have a path that looks like
// 'trackset//trackURI' because the identifier parameter for a trackset can
// be blank. For local tracks, some metadata can be missing, like missing
// album name would be 'spotify:local:artist::track:duration'.
var isTrackset = components[0] === URI.Type.TRACKSET;
var isLocalTrack = components[0] === URI.Type.LOCAL;
var shouldStripEmptyComponents = !isTrackset && !isLocalTrack;
if (shouldStripEmptyComponents) {
var _temp = [];
for (var i = 0, l = components.length; i < l; i++) {
var component = components[i];
if (!!component) {
_temp.push(component);
}
}
components = _temp;
}
var path = components.join('/');
return opt_leadingSlash ? '/' + path : path;
};
URI.prototype.toPlayURL = function () {
return PLAY_HTTPS_PREFIX + this.toURLPath();
};
URI.prototype.toURL = function () {
return this.toPlayURL();
};
URI.prototype.toOpenURL = function () {
return OPEN_HTTPS_PREFIX + this.toURLPath();
};
URI.prototype.toSecurePlayURL = function () {
return this.toPlayURL();
};
URI.prototype.toSecureURL = function () {