-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
library.js
3610 lines (3161 loc) · 131 KB
/
library.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
// Документация: https://chimildic.github.io/goofy
// Телеграм: https://t.me/forum_goofy
// Форум: https://github.com/Chimildic/goofy/discussions
const VERSION = '1.8.5';
const UserProperties = PropertiesService.getUserProperties();
const KeyValue = UserProperties.getProperties();
const API_BASE_URL = 'https://api.spotify.com/v1';
const DEFAULT_DATE = new Date('2000-01-01');
function doGet() {
return Auth.hasAccess() ? displayLaunchPage_() : Auth.displayAuthPage();
}
function displayAuthResult_(request) {
return Auth.displayAuthResult(request);
}
function displayLaunchPage_() {
try {
return HtmlService.createHtmlOutputFromFile('launch.html')
.addMetaTag('viewport', 'width=device-width, initial-scale=1')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
} catch {
return HtmlService.createHtmlOutput('Авторизация прошла успешно');
}
}
function runTasks_() {
RecentTracks.update();
let isUpdatedSavedTracks = Clerk.runOnceAWeek('monday', '01:00', updateSavedTracks);
!isUpdatedSavedTracks && Clerk.runOnceAfter('01:00', appendSavedTracks);
function updateSavedTracks(tracks) {
tracks = tracks || Source.getSavedTracks();
Cache.compressTracks(tracks);
Cache.write('SavedTracks.json', tracks);
}
function appendSavedTracks() {
let cacheTracks = Cache.read('SavedTracks.json');
let remoteTracks = Source.getSavedTracks(50);
Filter.removeTracks(remoteTracks, cacheTracks);
if (remoteTracks.length == 50 || cacheTracks.length == 0) {
updateSavedTracks();
} else if (remoteTracks.length > 0) {
updateSavedTracks(Combiner.push(remoteTracks, cacheTracks));
}
}
}
String.prototype.formatName = function () {
return this.toLowerCase()
.replace(/['`,?!@#$%^&*()+-./\\]/g, ' ')
.replace(/\s{2,}/g, ' ')
.replace(/ё/g, 'е')
.trim();
};
Date.prototype.setBound = function (value) {
if (value == 'startDay') {
this.setHours(0, 0, 0, 0);
} else if (value == 'endDay') {
this.setHours(23, 59, 59, 999);
}
return this;
};
Date.prototype.getTimestampUNIX = function (bound) {
return Math.trunc(this.setBound(bound).getTime() / 1000);
};
Object.prototype.isEmpty = function () {
return Object.keys(this).length == 0;
}
Array.prototype.toObject = function (parseMethod) {
return this.reduce((accumulator, element, i) => (accumulator[parseMethod(element)] = i, accumulator), {});
}
JSON.parseFromString = function (content) {
try {
return JSON.parse(content);
} catch (error) {
Admin.printError('Не удалось преобразовать строку JSON в объект JavaScript\n', error.stack, '\nКонтент:', `"${content}"`);
return undefined;
}
}
JSON.parseFromResponse = function (response) {
let content = response.getContentText();
if (content.length == 0) {
return { msg: 'Пустое тело ответа', status: response.getResponseCode() };
}
return JSON.parseFromString(content);
}
HtmlService.createCheerio = function (response) {
try {
return Cheerio.load(response.getContentText());
} catch (error) {
Admin.printInfo(error);
}
}
const CustomUrlFetchApp = (function () {
let countRequest = 0;
return {
fetch, fetchAll, parseQuery,
getCountRequest: () => countRequest,
};
function fetch(url, params = {}) {
params.muteHttpExceptions = true;
return readResponse(tryFetch(url, params), url, params);
}
function fetchAll(requests) {
requests.forEach((request) => (request.muteHttpExceptions = true));
let responses = [];
let limit = KeyValue.REQUESTS_IN_ROW || 20;
let count = Math.ceil(requests.length / limit);
for (let i = 0; i < count; i++) {
let requestPack = requests.splice(0, limit);
let responsePack = sendPack(requestPack).map((response, index) =>
readResponse(response, requestPack[index].url, {
headers: requestPack[index].headers,
payload: requestPack[index].payload,
muteHttpExceptions: requestPack[index].muteHttpExceptions,
})
);
Combiner.push(responses, responsePack);
}
return responses;
function sendPack(requests) {
let raw = tryFetchAll(requests);
if (typeof raw == 'undefined') {
return [];
}
let failed = raw.reduce((failed, response, index) => {
if (response.getResponseCode() == 429) {
failed.requests.push(requests[index])
failed.syncIndexes.push(index);
let seconds = parseRetryAfter(response);
if (failed.seconds < seconds) {
failed.seconds = seconds;
}
}
return failed;
}, { seconds: 0, requests: [], syncIndexes: [] });
if (failed.seconds > 0) {
Admin.pause(failed.seconds);
sendPack(failed.requests).forEach((response, index) => {
let requestIndex = failed.syncIndexes[index];
raw[requestIndex] = response;
});
}
return raw;
}
function tryFetchAll(requests) {
return tryCallback(() => {
countRequest += requests.length;
return UrlFetchApp.fetchAll(requests)
});
}
}
function readResponse(response, url, params = {}) {
if (isSuccess(response.getResponseCode())) {
return onSuccess();
}
return onError();
function isSuccess(code) {
return code >= 200 && code < 300;
}
function onSuccess() {
let type = response.getHeaders()['Content-Type'] || '';
if (type.includes('json')) {
return JSON.parseFromResponse(response) || [];
}
return response;
}
function onError() {
let responseCode = response.getResponseCode();
if (responseCode == 429) {
return onRetryAfter();
}
writeErrorLog();
if (responseCode >= 500) {
return tryFetchOnce();
}
}
function onRetryAfter() {
Admin.pause(parseRetryAfter(response));
return fetch(url, params);
}
function tryFetchOnce() {
Admin.pause(2);
response = tryFetch(url, params);
if (isSuccess(response.getResponseCode())) {
return onSuccess();
}
writeErrorLog();
}
function writeErrorLog() {
let errorText = response.getContentText().substring(0, 500)
if (errorText.toLowerCase().includes('access not granted')) {
throw `Нет прав доступа. Для повторной авторизации:\n1) Нажмите "начать развертывание > пробные развертывания"\n2) Перейдите по ссылке "веб-приложение"\n3) Подтвердите права доступа\n\nОшибка может возникать при смене пароля от Spotify аккаунта.\n\nЕсли при переходе по ссылке веб-приложения страница не открывается, повторите шаги в режиме инкогнито\n(Google делает автоматический редирект на другой аккаунт, где ваш проект с goofy недоступен).`
} else {
Admin.printError(`Номер: ${response.getResponseCode()}\nАдрес: ${url}\nМетод: ${params.method}\nТекст ответа: ${errorText}`);
}
}
}
function parseRetryAfter(response) {
return 1 + (parseInt(response.getHeaders()['Retry-After']) || 2);
}
function tryFetch(url, params) {
return tryCallback(() => {
countRequest++;
return UrlFetchApp.fetch(url, params)
});
}
function tryCallback(callback, attempt = 0) {
try {
return callback();
} catch (error) {
Admin.printError('При отправке запроса произошла ошибка:\n', error.stack);
if (attempt++ < 2) {
Admin.pause(5);
return tryCallback(callback, attempt);
}
}
}
function parseQuery(obj) {
return Object.keys(obj)
.map((k) => (typeof obj[k] != 'string' && obj[k] != undefined) || (typeof obj[k] == 'string' && obj[k].length > 0)
? `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`
: ''
).filter(s => s.length > 0).join('&');
}
})();
const Source = (function () {
return {
getTracks, getTracksRandom, getPlaylistTracks, getTopTracks, getTopArtists, getFollowedTracks, getSavedTracks,
getSavedAlbumTracks, getSavedAlbums, getRecomTracks, getArtists, getArtistsAlbums, getArtistsTracks,
getAlbumTracks, getAlbumsTracks, getArtistsTopTracks, getRelatedArtists, getCategoryTracks,
getListCategory, mineTracks, craftTracks, extractTracks, createUrlForRecomTracks, getRecentReleasesByArtists,
};
function getTopTracks(timeRange) {
return getTop(timeRange, 'tracks');
}
function getTopArtists(timeRange) {
return getTop(timeRange, 'artists');
}
function getTop(timeRange, type) {
// Баг Spotify: https://community.spotify.com/t5/Spotify-for-Developers/Bug-with-offset-for-method-quot-Get-User-s-Top-Artists-and/td-p/5032362
let template = `${API_BASE_URL}/me/top/%s?offset=%s&limit=%s&time_range=%s_term`;
return SpotifyRequest.getAll([
Utilities.formatString(template, type, 0, 49, timeRange),
Utilities.formatString(template, type, 49, 49, timeRange),
], false).reduce((items, response) => {
return Combiner.push(items, response.items);
}, []);
}
function getListCategory(params = {}) {
let query = CustomUrlFetchApp.parseQuery(params);
let url = `${API_BASE_URL}/browse/categories?${query}`;
return SpotifyRequest.get(url).items;
}
function getCategoryTracks(category_id, params = {}) {
let query = CustomUrlFetchApp.parseQuery(params);
let url = `${API_BASE_URL}/browse/categories/${category_id}/playlists?${query}`;
return getTracks(SpotifyRequest.get(url).items);
}
function getRelatedArtists(artists, isFlat = true) {
return getArtistsByPath(artists, '/artists/%s/related-artists', isFlat);
}
function getArtistsTopTracks(artists, isFlat = true) {
return getArtistsByPath(artists, '/artists/%s/top-tracks?market=from_token', isFlat);
}
function getArtistsByPath(artists, path, isFlat) {
let template = API_BASE_URL + path;
let urls = artists.reduce((urls, artist) => {
urls.push(Utilities.formatString(template, artist.id));
return urls;
}, []);
let responses = SpotifyRequest.getAll(urls);
return isFlat ? responses.flat(1) : responses;
}
function getRecomTracks(queryObj) {
let url = createUrlForRecomTracks(queryObj);
return SpotifyRequest.get(url).tracks;
}
function getFollowedTracks(params = {}) {
let playlists = getFollowedPlaylists(params.type, params.userId, params.exclude);
Selector.keepRandom(playlists, params.limit);
return !params.hasOwnProperty('isFlat') || params.isFlat ? getTracks(playlists) : playlists.map(p => {
p.tracks.items = getTracks([p]);
return p;
});
}
function getArtistsTracks(params) {
let artists = getArtists(params.artist);
params.album = params.album || {};
params.album.isFlat = false;
let tracks = getArtistsAlbums(artists, params.album).reduce((tracks, albums) => {
tracks.push(getAlbumsTracks(albums, params.album.track_limit));
return tracks;
}, []);
return !params.hasOwnProperty('isFlat') || params.isFlat ? tracks.flat(1) : tracks;
}
function getArtists(paramsArtist) {
let artists = [];
if (paramsArtist.include) {
Combiner.push(artists, getArtistsById(paramsArtist.include));
}
if (paramsArtist.followed_include) {
Combiner.push(artists, getFollowedArtists());
}
if (paramsArtist.exclude) {
let excludeIds = paramsArtist.exclude.map((item) => item.id);
artists = artists.filter((item) => !excludeIds.includes(item.id));
}
artists = artists.filter((artist) => {
artist.followers = artist.followers.total || artist.followers;
return (
RangeTracks.isBelong(artist, paramsArtist) &&
RangeTracks.isBelongGenres(artist.genres, paramsArtist.genres) &&
!RangeTracks.isBelongBanGenres(artist.genres, paramsArtist.ban_genres)
);
});
return Selector.sliceRandom(artists, paramsArtist.artist_limit);
}
function getArtistsById(artistsArray) {
let ids = artistsArray.map((item) => item.id);
return SpotifyRequest.getFullObjByIds('artists', ids, 50);
}
function getFollowedArtists() {
return SpotifyRequest.getItemsByPath('me/following?type=artist&limit=50');
}
function getArtistsAlbums(artists, params = {}) {
let groups = params.groups || 'album,single';
let albums = artists.reduce((albums, artist) => {
let path = `artists/${artist.id}/albums?include_groups=${groups}&limit=50&market=from_token`;
let response = SpotifyRequest.getItemsByPath(path).filter((album) => RangeTracks.isBelongReleaseDate(album.release_date, params.release_date));
Filter.dedupAlbums(response);
albums.push(Selector.sliceRandom(response, params.album_limit));
return albums;
}, []);
return !params.hasOwnProperty('isFlat') || params.isFlat ? albums.flat(1) : albums;
}
function getAlbumsTracks(albums, limit) {
return albums.reduce((tracks, album) => {
return Combiner.push(tracks, getAlbumTracks(album, limit));
}, []);
}
function getAlbumTracks(album, limit) {
let items = SpotifyRequest.getItemsByPath(`albums/${album.id}/tracks`);
Selector.keepRandom(items, limit);
return items.map((item) => {
item.album = album;
return item;
});
}
function getSavedAlbumTracks(limit) {
let items = getSavedAlbums();
Selector.keepRandom(items, limit);
return items.reduce((tracks, album) => {
let albumTracks = album.tracks.items.map(item => (item.album = album, item));
// Фикс ошибки при использовании JSON.stringify
// TypeError: Converting circular structure to JSON
delete album.tracks;
return Combiner.push(tracks, albumTracks)
}, []);
}
function getSavedAlbums() {
return SpotifyRequest.getItemsByPath('me/albums?limit=50', 400).map((item) => {
let album = item.album;
album.added_at = item.added_at;
return album;
});
}
function getFollowedPlaylists(type = 'followed', userId = User.id, excludePlaylist = []) {
let playlistArray = Playlist.getPlaylistArray(userId);
if (type != 'all') {
playlistArray = playlistArray.filter((playlist) => {
let isOwned = playlist.owner.id == userId;
return type == 'owned' ? isOwned : !isOwned;
});
}
if (excludePlaylist.length > 0) {
let ids = excludePlaylist.map((item) => item.id);
playlistArray = playlistArray.filter((item) => !ids.includes(item.id));
}
return playlistArray;
}
function getRecentReleasesByArtists(params) {
if (params.artists.length >= 300) {
console.warn(`При большом количестве исполнителей (запрошено ${params.artists.length}) функция может не уложиться в лимит времени выполнения\nили получить временный бан от Spotify за спам запросами.\n\nВоспользуйтесь шаблоном: https://chimildic.github.io/goofy/#/template?id=Новые-релизы-по-частям`)
}
let initDateStr = new Date().toISOString()
let startDate = params.hasOwnProperty('sinceDays') ? Filter.getDateRel(params.beforeDays, 'startDay') : params.startDate
let types = params.type.sort((a, b) => a.localeCompare(b))
let requestUrls = params.artists.map(artist => `${API_BASE_URL}/artists/${artist.id}/albums?include_groups=${types.join(",")}&limit=50&market=from_token`)
let foundReleases = {}
let uncompleteRequests = []
SpotifyRequest.getAll(requestUrls).forEach((response, index) => {
let minFoundDateStrings = types.reduce((acc, type) => (acc[type] = initDateStr, acc), {})
let artistId = params.artists[index].id
foundReleases[artistId] = foundReleases[artistId] || {}
foundReleases[artistId].albums = response.items.filter(album => {
minFoundDateStrings[album.album_type] = album.release_date
return RangeTracks.isBelongReleaseDate(album.release_date, params.date)
})
if (response.items.length == 50 && response.next != undefined) {
let notFoundTypes = []
Object.entries(minFoundDateStrings).forEach(([albumType, dateStr]) => {
let minFoundDate = new Date(dateStr)
if (startDate < minFoundDate) {
notFoundTypes.push(albumType)
}
})
if (notFoundTypes.length > 0) {
uncompleteRequests.push({ id: artistId, groups: notFoundTypes })
}
}
})
uncompleteRequests.forEach(item => {
let artistAlbums = Source.getArtistsAlbums(/* artist = { id: '' }*/ item, /* params = { groups: [] }*/ item)
Combiner.push(foundReleases[item.id].albums, artistAlbums)
})
let trackGroups = Object.entries(foundReleases).map(([artistId, data]) => {
Filter.dedupAlbums(data.albums)
return Source.getAlbumsTracks(data.albums) || []
})
if (!params.hasOwnProperty('isFlat') || params.isFlat) {
let tracks = trackGroups.flat(1)
Order.sort(tracks, 'album.release_date', 'desc')
return tracks
}
return trackGroups
}
function mineTracks(params) {
let findMethod, getTracksMethod;
let selectMethod = params.hasOwnProperty('inRow') && params.inRow ? Selector.keepFirst : Selector.keepRandom;
if (params.type == 'album') {
findMethod = Search.findAlbums;
getTracksMethod = getAlbumsTracks;
} else if (params.type == 'track') {
findMethod = Search.findTracks;
// getTracksMethod - не нужно, треки уже в результате поиска
} else {
params.type = 'playlist';
findMethod = Search.findPlaylists;
getTracksMethod = getTracks;
}
let result = findMethod(params.keyword, params.requestCount);
if (params.type == 'playlist' && params.hasOwnProperty('followers')) {
filterByFollowers();
}
let tracks = reduceResult();
Filter.dedupTracks(tracks);
return tracks;
function reduceResult() {
return result.reduce((tracks, array) => {
selectMethod(array, params.itemCount || 3);
Selector.keepAllExceptFirst(array, params.skipCount || 0);
let trackItems = getTracksMethod ? getTracksMethod(array) : array;
return Combiner.push(tracks, filterPopularity(trackItems));
}, []);
}
function filterByFollowers() {
for (let i = 0; i < result.length; i++) {
result[i] = getFullPlaylistObject(result[i]).filter((p) => {
return isBelongRangeFollowers(p.followers.total);
});
}
}
function filterPopularity(array) {
if (!params.hasOwnProperty('popularity')) {
return array;
}
if (array[0] && !array[0].hasOwnProperty('popularity')) {
let ids = array.map((t) => t.id);
array = SpotifyRequest.getFullObjByIds('tracks', ids, 50);
}
return array.filter((t) => t.popularity >= (params.popularity || 0));
}
function getFullPlaylistObject(array) {
let urls = array.map(p => `${API_BASE_URL}/playlists/${p.id}`);
return SpotifyRequest.getAll(urls);
}
function isBelongRangeFollowers(value) {
return value >= params.followers.min && value <= params.followers.max;
}
}
function craftTracks(tracks, params = {}) {
let recomTracks = SpotifyRequest.getAll(createUrls()).reduce((recomTracks, response) => {
return Combiner.push(recomTracks, response.tracks);
}, []);
Filter.dedupTracks(recomTracks);
return recomTracks;
function createUrls() {
let urls = [];
let queryObj = params.query || {};
let ids = mapToIds();
let availablePosition = findAvailablePosition();
let count = Math.ceil(ids.length / availablePosition);
for (let i = 0; i < count; i++) {
queryObj[params.key] = ids.splice(0, availablePosition).join(',');
urls.push(createUrlForRecomTracks(queryObj));
}
return urls;
}
function mapToIds() {
let ids;
if (params.key == 'seed_artists') {
ids = tracks.map((t) => (t.artists ? t.artists[0].id : t.id));
} else {
ids = tracks.map((t) => t.id);
params.key = 'seed_tracks';
}
return Array.from(new Set(ids));
}
function findAvailablePosition() {
let value = 5;
if (!params.hasOwnProperty('query')) {
return value;
}
if (params.query.hasOwnProperty('seed_genres')) {
value -= params.query.seed_genres.split(',').length;
}
if (params.query.hasOwnProperty('seed_tracks') && params.key != 'seed_tracks') {
value -= params.query.seed_tracks.split(',').length;
}
if (params.query.hasOwnProperty('seed_artists') && params.key != 'seed_artists') {
value -= params.query.seed_artists.split(',').length;
}
if (value <= 0) {
throw `Не осталось места под ${params.key}. Уменьшите количество значения других seed_*`;
}
return value;
}
}
function createUrlForRecomTracks(queryObj) {
queryObj.limit = queryObj.limit > 100 ? 100 : queryObj.limit || 100;
queryObj.market = queryObj.market || 'from_token';
let query = CustomUrlFetchApp.parseQuery(queryObj);
return `${API_BASE_URL}/recommendations?${query}`;
}
function getTracksRandom(playlistArray, countPlaylist = 1) {
return getTracks(Selector.sliceRandom(playlistArray, countPlaylist));
}
function getPlaylistTracks(name, id, userId, count, inRow) {
return getTracks([{ id: id, name: name, userId: userId, count: count, inRow: inRow == undefined ? true : inRow }]);
}
function getTracks(playlistArray) {
return extractTracks(getTrackItems(playlistArray));
}
function getTrackItems(playlistArray) {
return playlistArray.reduce((items, playlist) => {
let playlistItems = [];
if (typeof playlist == 'undefined') {
return items;
}
if (playlist.id) {
playlistItems = getItemsByPlaylistId(playlist.id);
} else if (playlist.name) {
playlistItems = getItemsByPlaylistName(playlist.name, playlist.userId);
}
if (!playlist.hasOwnProperty('inRow') || playlist.inRow) {
Selector.keepFirst(playlistItems, playlist.count);
} else {
Selector.keepRandom(playlistItems, playlist.count);
}
return Combiner.push(items, playlistItems);
}, []);
}
function getItemsByPlaylistId(playlistId) {
let playlist = Playlist.getById(playlistId);
return getItemsByPlaylistObject(playlist);
}
function getItemsByPlaylistName(playlistName, userId) {
let playlist = Playlist.getByName(playlistName, userId);
if (!playlist || !playlist.id) {
return [];
}
return getItemsByPlaylistId(playlist.id);
}
function getItemsByPlaylistObject(obj) {
let items = [];
if (obj && obj.tracks && obj.tracks.items) {
items = obj.tracks.total <= 100 ? obj.tracks.items : SpotifyRequest.getItemsByNext(obj.tracks);
items.forEach((item) => (item.origin = { id: obj.id, name: obj.name, type: obj.type }));
}
return items;
}
function getSavedTracks(limit = 200000) {
let requestCount = Math.ceil(limit / 50);
let items = SpotifyRequest.getItemsByPath('me/tracks?limit=50', requestCount);
return Selector.sliceFirst(extractTracks(items), limit);
}
function extractTracks(items) {
if (!items || items.length == 0) return [];
let key = items[0].played_at ? 'played_at' : 'added_at';
return items.reduce((tracks, item) => {
if ((!item.hasOwnProperty('is_local') || !item.is_local) && item.track && item.track.artists && item.track.artists.length > 0) {
let date = item[key] ? item[key] : DEFAULT_DATE.toISOString();
item.track[key] = date;
if (item.hasOwnProperty('origin')) {
item.track.origin = item.origin;
}
tracks.push(item.track);
}
return tracks;
}, []);
}
})();
const Player = (function () {
return {
getPlayback, transferPlayback, getAvailableDevices, next, previous, pause, resume, toggleShuffle, setRepeatMode, addToQueue,
};
function getPlayback() {
return SpotifyRequest.get(`${API_BASE_URL}/me/player`) || {};
}
function transferPlayback(deviceId, isPlay) {
return SpotifyRequest.put(`${API_BASE_URL}/me/player`, { device_ids: [deviceId], play: isPlay, });
}
function getAvailableDevices() {
return SpotifyRequest.get(`${API_BASE_URL}/me/player/devices`);
}
function next(deviceId) {
return SpotifyRequest.post(createUrl('/me/player/next', deviceId));
}
function previous(deviceId) {
return SpotifyRequest.post(createUrl('/me/player/previous', deviceId));
}
function pause(deviceId) {
return SpotifyRequest.put(createUrl('/me/player/pause', deviceId));
}
function toggleShuffle(state, deviceId) {
return SpotifyRequest.put(createUrl('/me/player/shuffle', deviceId, { state: state }));
}
function setRepeatMode(state, deviceId) {
return SpotifyRequest.put(createUrl('/me/player/repeat', deviceId, { state: state }));
}
function resume(params = {}) {
if (params.hasOwnProperty('tracks')) {
params.uris = params.tracks.map(t => t.uri || `spotify:track:${t.id}`);
delete params.tracks;
}
let url = createUrl('/me/player/play', params.deviceId);
return SpotifyRequest.put(url, params);
}
function addToQueue(tracks, deviceId) {
Array.isArray(tracks) ? tracks.forEach(t => addItem(t.id)) : addItem(tracks.id);
function addItem(id) {
let queryObj = { uri: `spotify:track:${id}` };
let url = createUrl('/me/player/queue', deviceId, queryObj);
return SpotifyRequest.post(url);
}
}
function createUrl(path, deviceId = '', queryObj = {}) {
queryObj.device_id = queryObj.device_id || deviceId;
let query = CustomUrlFetchApp.parseQuery(queryObj);
return API_BASE_URL + path + `?${query ? query : ''}`;
}
})();
const RecentTracks = (function () {
const ON_SPOTIFY_RECENT_TRACKS = 'true' === KeyValue.ON_SPOTIFY_RECENT_TRACKS;
const ON_LASTFM_RECENT_TRACKS = 'true' === KeyValue.ON_LASTFM_RECENT_TRACKS;
const SPOTIFY_FILENAME = 'SpotifyRecentTracks.json';
const LASTFM_FILENAME = 'LastfmRecentTracks.json';
const BOTH_SOURCE_FILENAME = 'BothRecentTracks.json';
const ITEMS_LIMIT = parseInt(KeyValue.COUNT_RECENT_TRACKS) || 60000;
return {
get, update, compress, appendTracks,
};
function get(limit) {
let tracks = [];
if (ON_SPOTIFY_RECENT_TRACKS && ON_LASTFM_RECENT_TRACKS) {
tracks = Cache.read(BOTH_SOURCE_FILENAME);
} else if (ON_SPOTIFY_RECENT_TRACKS) {
tracks = Cache.read(SPOTIFY_FILENAME);
} else if (ON_LASTFM_RECENT_TRACKS) {
tracks = Cache.read(LASTFM_FILENAME);
}
return Selector.sliceFirst(tracks, limit);
}
function update() {
let hasUpdate = 0;
if (ON_SPOTIFY_RECENT_TRACKS) {
hasUpdate += updatePlatformRecentTracks(getSpotifyRecentTracks(), SPOTIFY_FILENAME, findNewPlayed);
}
if (ON_LASTFM_RECENT_TRACKS) {
let lastfmTracks = Lastfm.getLastfmRecentTracks(KeyValue.LASTFM_LOGIN, parseInt(KeyValue.LASTFM_RANGE_RECENT_TRACKS));
hasUpdate += updatePlatformRecentTracks(lastfmTracks, LASTFM_FILENAME, Lastfm.findNewPlayed);
}
if (hasUpdate > 0 && ON_SPOTIFY_RECENT_TRACKS && ON_LASTFM_RECENT_TRACKS) {
updateBothSourceRecentTracks();
}
}
function updatePlatformRecentTracks(recentTracks, filename, findNewPlayedMethod) {
let fileItems = Cache.read(filename);
let newItems = findNewPlayedMethod(recentTracks, fileItems);
return appendNewPlayed(newItems, filename);
}
function updateBothSourceRecentTracks() {
let spotifyTracks = Cache.read(SPOTIFY_FILENAME);
let lastfmTracks = Cache.read(LASTFM_FILENAME);
Combiner.push(spotifyTracks, lastfmTracks);
Order.sort(spotifyTracks, 'meta.played_at', 'desc');
Filter.dedupTracks(spotifyTracks);
Cache.write(BOTH_SOURCE_FILENAME, spotifyTracks);
}
function appendNewPlayed(newItems, filename) {
if (newItems.length == 0) {
Admin.printInfo(`Нет новых треков ${filename}`);
return false;
}
Cache.compressTracks(newItems);
let total = Cache.append(filename, newItems, 'begin', ITEMS_LIMIT);
Admin.printInfo(`+${newItems.length}, всего: ${total} (${filename})`);
return true;
}
function getSpotifyRecentTracks() {
let url = `${API_BASE_URL}/me/player/recently-played?limit=50`;
return Source.extractTracks(SpotifyRequest.get(url).items);
}
function findNewPlayed(recentItems, fileItems) {
if (fileItems.length == 0) {
return recentItems;
}
let lastPlayedTime = new Date(fileItems[0].played_at).getTime();
for (let i = recentItems.length - 1; i >= 0; i--) {
let time = new Date(recentItems[i].played_at).getTime();
if (time - lastPlayedTime == 0) {
return recentItems.slice(0, i);
}
}
return recentItems.filter(recentItem => {
return -1 == fileItems.findIndex(fileItem =>
fileItem.name == recentItem.name
&& fileItem.played_at == recentItem.played_at);
});
}
function appendTracks(filename, tracks) {
Cache.compressTracks(tracks);
tracks.forEach((t) => {
if (t.hasOwnProperty('added_at')) {
t.played_at = t.added_at;
delete t.added_at;
} else if (!t.hasOwnProperty('played_at')) {
t.played_at = new Date().toISOString();
}
});
let fileItems = Cache.read(filename);
Combiner.push(fileItems, tracks);
Order.sort(fileItems, 'meta.played_at', 'desc');
Cache.write(filename, fileItems);
}
function compress() {
if (ON_SPOTIFY_RECENT_TRACKS) {
compressFile(SPOTIFY_FILENAME);
}
if (ON_LASTFM_RECENT_TRACKS) {
compressFile(LASTFM_FILENAME);
}
if (ON_SPOTIFY_RECENT_TRACKS && ON_LASTFM_RECENT_TRACKS) {
compressFile(BOTH_SOURCE_FILENAME);
}
}
function compressFile(filename) {
Cache.copy(filename);
let tracks = Cache.read(filename);
Cache.compressTracks(tracks);
Cache.write(filename, tracks);
}
})();
const Combiner = (function () {
return {
alternate, mixinMulti, mixin, replace, push,
};
function replace(oldArray, newArray) {
oldArray.length = 0;
push(oldArray, newArray);
}
function push(sourceArray, ...additionalArray) {
additionalArray.forEach((array) => {
array = Array.isArray(array) ? array : [array];
if (array.length < 1000) {
sourceArray.push.apply(sourceArray, array);
} else {
array.forEach((item) => sourceArray.push(item));
}
});
return sourceArray;
}
function alternate(bound, ...arrays) {
let limitLength = getLimitLength(bound, arrays);
const resultArray = [];
for (let i = 0; i < limitLength; i++) {
pushPack(i);
}
return resultArray;
function pushPack(index) {
arrays.forEach((array) => {
if (array.length > index) {
resultArray.push(array[index]);
}
});
}
}
function mixin(xArray, yArray, xRow, yRow, toLimitOn) {
return mixinMulti({
toLimitOn: toLimitOn || false,
source: [xArray, yArray],
inRow: [xRow, yRow],
});
}
function mixinMulti(params) {
let resultArray = [];
if (params.source.length != params.inRow.length || (params.toLimitOn && !isEnoughItems())) {
return resultArray;
}
let limitLength = getLimitLength('max', params.source);
for (let i = 0; i < limitLength; i++) {
let hasNextFullPack = pushAllPack(i);
if (params.toLimitOn && !hasNextFullPack) {
break;
}
}
return resultArray;
function pushAllPack(step) {
let hasNextFullPack = true;
params.source.forEach((array, rowIndex) => {
let hasNextPack = pushPack(array, step, params.inRow[rowIndex]);
hasNextFullPack = hasNextFullPack && hasNextPack;
});
return hasNextFullPack;
}
function pushPack(array, step, inRow) {
let startIndex = step * inRow;
let endIndex = startIndex + inRow;
push(resultArray, array.slice(startIndex, endIndex));
let nextEndIndex = endIndex + inRow - 1;
return array[nextEndIndex] != undefined;
}
function isEnoughItems() {
for (let i = 0; i < params.source.length; i++) {
if (params.source[i].length < params.inRow[i]) {
return false;
}
}
return true;
}
}
function getLimitLength(type, arrays) {
let lengthArray = arrays.map((item) => item.length);
let mathMethod = type == 'min' ? Math.min : Math.max;
return mathMethod(...lengthArray);
}
})();
const RangeTracks = (function () {
const BAN_KEYS = ['genres', 'ban_genres', 'release_date', 'followed_include', 'include', 'exclude', 'groups', 'artist_limit', 'album_limit', 'track_limit', 'isRemoveUnknownGenre'];
let _cachedTracks, _lastOutRange, _params;
return { rangeTracks, getLastOutRange, isBelong, isBelongGenres, isBelongBanGenres, isBelongReleaseDate, };
function getLastOutRange() {
return _lastOutRange ? _lastOutRange.slice() : [];
}
function rangeTracks(tracks, params) {
_params = params;
_lastOutRange = [];
_cachedTracks = getCachedTracks(tracks, params);
let filteredTracks = tracks.filter((track) => {
if (isBelongMeta(track) && isBelongFeatures(track) && isBelongArtist(track) && isBelongAlbum(track)) {
return true;
} else {
_lastOutRange.push(track);
return false;
}
});
Combiner.replace(tracks, filteredTracks);
}
function isBelongMeta(track) {
if (!_params.meta) {
return true;
}
let trackMeta = _cachedTracks.meta[track.id] ? _cachedTracks.meta[track.id] : track;
return _params.meta ? isBelong(trackMeta, _params.meta) : true;
}
function isBelongFeatures(track) {
if (!_params.features) {