This repository has been archived by the owner on Jun 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
rdio-enhancer.ts
1464 lines (1339 loc) · 46.1 KB
/
rdio-enhancer.ts
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
declare var R, t, player_model, Notification, webkitNotifications, chrome;
function codeToString(f) {
var args = [];
for (var i = 1; i < arguments.length; ++i) {
args.push(JSON.stringify(arguments[i]));
}
return "(" + f.toString() + ")(" + args.join(",") + ");";
}
function injectedJs() {
// Used to store play next items
var play_next_queue = [];
var WEB_SERVICE_TYPES = {
ALBUM: 'a',
ALBUM_STATION: 'ar',
ARIST: 'r',
ARTIST_STATION: 'rr',
ARTIST_TOP_SONGS_STATION: 'tr',
AUTOPLAY_STATION: 'ap',
CATEGORY: 'tpc',
COLLECTION_ALBUM: 'al',
COLLECTION_ARTIST: 'rl',
GENRE_STATION: 'gr',
HEAVY_ROTATION_STATION: 'h',
HEAVY_ROTATION_USER_STATION: 'e',
LABEL: 'l',
LABEL_STATION: 'lr',
PLAYLIST: 'p',
PLAYLIST_STATION: 'pr',
SONG_STATION: 'sr',
TASTE_PROFILE_STATION: 'tp',
TRACK: 't',
USER: 's',
USER_COLLECTION_STATION: 'c'
};
// Build the Rdio Enhancer Class
R.enhancer = {
log: function(item) {
console.debug("==============================================");
console.debug(item);
},
copyText: function copyText(text) {
var textField = document.createElement('textarea');
textField.innerText = text;
document.body.appendChild(textField);
textField.select();
document.execCommand('copy');
textField.remove();
},
overwrite_playlist: function() {
if(!R.Models || !R.Models.Playlist) {
window.setTimeout(R.enhancer.overwrite_playlist, 100);
return;
}
// Overwrite the playlist add function to support adding playlists to playlists
// From core.rdio.js line 8056
R.Models.Playlist.prototype.add = function(model) {
var model_type = model.get("type");
var playlist_this = this;
if (model_type == "a" || model_type == "al" || model_type == "t" || model_type == "p") {
var track_list = [];
if(model_type == "a" || model_type == "al") {
track_list = model.get("trackKeys");
}
else if(model_type == "t") {
track_list = [model.get("key")];
}
else if(model_type == "p") {
R.enhancer.getModels(
function(tracks) {
for(var x = 0; x < tracks.length; x++) {
track_list.push(tracks[x].attributes.source.attributes.key);
}
// This is redundant, but it works
if(playlist_this.has("tracks")) {
playlist_this.get("tracks").addSource(model);
}
var d = {
method: "addToPlaylist",
content: {
playlist: playlist_this.get("key"),
tracks: track_list,
extras: ["-*", "duration", "Playlist.PUBLISHED"]
},
success: function(a) {
R.enhancer.show_message('Added "' + model.get("name") + '" to Playlist "' + playlist_this.get("name") + '"');
a.result && playlist_this.set(a.result);
a[0] && a[0].result && playlist_this.set(a[0].result);
}
};
playlist_this._requestQueue.push(d);
},
model.get("tracks"),
'Fetching Playlist data... Please wait. If your Playlist is large this can take awhile.',
'There was an error getting the Playlist data, if you have a large Playlist try scrolling down to load more first and then try the action again.'
);
// The function continues in the callback, so return here
return;
}
if(playlist_this.has("tracks")) {
playlist_this.get("tracks").addSource(model);
}
var d = {
method: "addToPlaylist",
content: {
playlist: playlist_this.get("key"),
tracks: track_list,
extras: ["-*", "duration", "Playlist.PUBLISHED"]
},
success: function(a) {
R.enhancer.show_message('Added "' + model.get("name") + '" to Playlist "' + playlist_this.get("name") + '"');
a.result && playlist_this.set(a.result);
a[0] && a[0].result && playlist_this.set(a[0].result);
}
};
playlist_this._requestQueue.push(d);
}
};
},
overwrite_create: function() {
if(R.Component && R.Component.orig_create) {
// Safety check so this can't be called twice.
return;
}
if (R.Mixins && R.Mixins.artistShareMenu) {
R.Mixins.artistShareMenu.getShareSubOptions = function() {
return [
{
label: t('Copy link'),
context: this,
callback: function() {
R.enhancer.copyText(this.model.get('shortUrl'));
},
extraClassNames: 'share copy_link',
value: 'copy_link'
},
{
label: t('Share options'),
context: this,
callback: function() {
if ( this._shareButtonMenu ) {
this._shareButtonMenu.destroy();
}
if ( this.menu ) {
this.menu.destroy();
}
this._doShare();
},
extraClassNames: 'share',
value: null
}
];
}
}
if(!R.Component || !R.Component.create) {
window.setTimeout(R.enhancer.overwrite_create, 100);
return;
}
R.Component.orig_create = R.Component.create;
R.Component.create = function(a,b,c) {
//R.enhancer.log("Rdio Enhancer:")
//R.enhancer.log(a);
if(a == "App.Header") {
// Add new event
b.orig_events = b.events;
b.events = function() {
var local_events = b.orig_events.call(this);
local_events["click .enhancer_master_menu"] = "onEnhancerMenuButtonClicked";
return local_events;
};
// Inject Enhancer menu functions
b.onEnhancerMenuButtonClicked = function(event) {
this.enhancerMenu.open();
R.Utils.stopEvent(event);
};
b.onEnhancerMenuOptionSelected = function(linkvalue, something) {
linkvalue && (something ? window.open(linkvalue, "_blank") : R.router.navigate(linkvalue, true));
};
b.getEnhancerMenuOptions = new Backbone.Collection([
{
label: "Rdio Enhancer Settings",
value: "",
callback: R.enhancer.settings_dialog,
visible: true
},
{
label: "About Rdio Enhancer",
value: "",
callback: R.enhancer.about_dialog,
visible: true
}
]);
b.orig_onRendered = b.onRendered;
b.onRendered = function() {
b.orig_onRendered.call(this);
this.$(".right_container .user_nav").append('<span class="user_nav_button enhancer_master_menu"></span>');
var enhancer_menu_ele = this.$(".enhancer_master_menu");
this.enhancerMenu = this.addChild(new R.Components.Menu({
positionOverEl: enhancer_menu_ele,
positionUnder: true,
model: this.getEnhancerMenuOptions
}));
this.listen(this.enhancerMenu, "optionSelected", this.onEnhancerMenuOptionSelected);
};
}
if(a == "Dialog.EditPlaylistDialog.Rdio") {
b._getAttributes = function() {
var parent_get_attributes = R.Components.Dialog.EditPlaylistDialog.Rdio.callSuper(this, "_getAttributes");
if (this.model.isNew()) {
var track_list = [],
source_model = this.options.sourceModel;
if (source_model) {
var model_type = source_model.get("type");
if(model_type == "a" || model_type == "al") {
track_list = source_model.get("trackKeys");
}
else if(model_type == "t") {
track_list = [source_model.get("key")];
}
else if(model_type == "p") {
var models = source_model.get("tracks").models;
if(models.length > 0) {
track_list = [];
}
for(var x = 0; x < models.length; x++) {
track_list.push(models[x].attributes.source.attributes.key);
}
}
}
parent_get_attributes.tracks = track_list;
}
return parent_get_attributes;
}
}
if(a == "ActionMenu") {
b.orig_getMenuOptions = b.getMenuOptions;
b.getMenuOptions = function() {
var menuOptions = b.orig_getMenuOptions.call(this);
menuOptions.push({
label: "Sort Playlist",
value: new Backbone.Collection(this.getSortMenuOptions()),
visible: this.playlistFeaturesVisible
});
menuOptions.push({
label: "Extras",
value: new Backbone.Collection(this.getExtraMenuOptions()),
visible: this.playlistFeaturesVisible
});
var tags: any = [];
_.each(R.enhancer.getTagsForAlbum(this.model.get("albumKey")), _.bind(function(tag) {
tags.push({
label: tag,
value: tag,
maxWidth: 150,
context: a,
useTitle: true,
hasDelete: true,
deleteTooltip: "Remove from tags",
callback: _.bind(this.onRemoveFromTags, this, tag)
});
}, this));
tags = new Backbone.Collection(tags);
menuOptions.push(
{
label: "Tags",
visible: this.manageTagsVisible,
value: new Backbone.Collection([
{
embed: true,
value: tags,
visible: tags.length > 0
},
{
visible: tags.length > 0
},
{
label: t("Add Tags..."),
value: "manageTags",
callback: _.bind(this.onManageTags, this)
}
])
})
return menuOptions;
};
b.onRemoveFromTags = function(tagToRemove) {
R.enhancer.removeTag(tagToRemove, this.model.get("albumKey"));
this.menuDirty = true;
};
b.onManageTags = function(model) {
var that = this;
R.loader.load(["Dialog.FormDialog"], function() {
var dialog = new R.Components.Dialog.FormDialog({
title: "Add Tags"
});
dialog.onOpen = function() {
// Form with only a textarea allowing the user to enter tags (each separated by a comma)
this.$(".body").html('<ul class="form_list"><li class="form_row no_line"><div class="label">Tags :<br/>(comma separated)</div><div class="field"><textarea style="height:72px;" class="tags" name="tags"></textarea></div></li></ul>');
this.$(".body .tags").val(R.enhancer.getTagsForAlbum(that.model.get("albumKey")));
this.$(".footer .blue").removeAttr("disabled");
// Save the tags when the user click on confirm
this.$(".footer .blue").on("click", _.bind(function() {
var tags = _.map(this.$(".body .tags").val().trim().split(","), function(tag: string) { return tag.trim(); });
// Compare with previously set tags - might need to remove some
var previousTags = R.enhancer.getTagsForAlbum(that.model.get("albumKey"));
_.each(_.difference(previousTags, tags), function(removedTag) {
R.enhancer.removeTag(removedTag, that.model.get("albumKey"));
});
R.enhancer.setTags(tags, that.model.get("albumKey"));
that.menuDirty = true;
this.close();
}, this));
};
dialog.open()
});
};
b.addToPlaylistItemVisible_orig = b.addToPlaylistItemVisible;
b.addToPlaylistItemVisible = function() {
return b.addToPlaylistItemVisible_orig.call(this) || this.playlistFeaturesVisible();
};
b.playlistFeaturesVisible = function() {
return this.model instanceof R.Models.Playlist;
};
b.manageTagsVisible = function() {
return this.model.get("type") === "al";
};
// Inject Sort menu functions
b.getSortMenuOptions = function() {
return [{
label: "Sort by Artist",
value: "sortbyartist",
callback: this.sortPlaylistbyArtist,
visible: true
}, {
label: "Sort by Album",
value: "sortbyalbum",
callback: this.sortPlaylistbyAlbum,
visible: true
}, {
label: "Sort by Song Name",
value: "sortbysong",
callback: this.sortPlaylistbySong,
visible: true
}, {
label: "Sort by Release Date",
value: "sortbyreleasedateasc",
callback: this.sortPlaylistbyReleaseDate,
visible: true
}, {
label: "Sort by Play Count",
value: "sortbyplaycount",
callback: this.sortPlaylistbyPlayCount,
visible: true
}, {
label: "Reverse",
value: "reverse",
callback: this.sortPlaylistReverse,
visible: true
}, {
label: "Randomize",
value: "randomize",
callback: this.sortPlaylistRandom,
visible: true
}];
};
b.sortPlaylistbyArtist = function() {
R.enhancer.getTracks(function(tracks) {
R.enhancer.show_message("Sorted Playlist by Artist");
R.enhancer.current_playlist.model.setPlaylistOrder(R.enhancer.getKeys(tracks.sort(R.enhancer.sortByArtist)));
R.enhancer.current_playlist.render();
});
};
b.sortPlaylistbyAlbum = function() {
R.enhancer.getTracks(function(tracks) {
R.enhancer.show_message("Sorted Playlist by Album");
R.enhancer.current_playlist.model.setPlaylistOrder(R.enhancer.getKeys(tracks.sort(R.enhancer.sortByAlbum)));
R.enhancer.current_playlist.render();
});
};
b.sortPlaylistbySong = function() {
R.enhancer.getTracks(function(tracks) {
R.enhancer.show_message("Sorted Playlist by Song Name");
R.enhancer.current_playlist.model.setPlaylistOrder(R.enhancer.getKeys(tracks.sort(R.enhancer.sortByTrackName)));
R.enhancer.current_playlist.render();
});
};
b.sortPlaylistbyReleaseDate = function() {
R.enhancer.getTracks(function(tracks) {
var album_keys = [];
var results:any = {};
jQuery.each(tracks, function(index, value) {
var album_key = value.attributes.source.attributes.albumKey;
if(album_keys.indexOf(album_key) === -1) {
album_keys.push(album_key);
}
});
R.Api.request({
method: "get",
content: {
keys: album_keys,
extras: ["-*", "releaseDate"]
},
success: function(success_data) {
results = success_data;
jQuery.each(tracks, function(index, track) {
if (success_data.result[track.attributes.source.attributes.albumKey].releaseDate) {
track.attributes.source.attributes.releaseDate = results.result[track.attributes.source.attributes.albumKey].releaseDate;
}
});
R.enhancer.show_message("Sorted Playlist by Release Date" );
R.enhancer.current_playlist.model.setPlaylistOrder(R.enhancer.getKeys(tracks.sort(R.enhancer.sortByReleaseDate)));
R.enhancer.current_playlist.render();
}
});
});
};
b.sortPlaylistbyPlayCount = function() {
R.enhancer.getTracks(function(tracks) {
var results: any = {};
R.Api.request({
method: "get",
content: {
keys: R.enhancer.getKeys(tracks),
extras: ["-*", "playCount"]
},
success: function(success_data) {
results = success_data;
jQuery.each(tracks, function(index, track) {
if (success_data.result[track.attributes.source.attributes.key].playCount) {
track.attributes.source.attributes.playCount = results.result[track.attributes.source.attributes.key].playCount;
}
});
R.enhancer.show_message("Sorted Playlist by Play Count" );
R.enhancer.current_playlist.model.setPlaylistOrder(R.enhancer.getKeys(tracks.sort(R.enhancer.sortByPlayCount)));
R.enhancer.current_playlist.render();
}
});
});
};
b.sortPlaylistReverse = function() {
R.enhancer.getTracks(function(tracks) {
R.enhancer.show_message("Reversed Playlist")
R.enhancer.current_playlist.model.setPlaylistOrder(R.enhancer.getKeys(tracks.reverse()));
R.enhancer.current_playlist.render();
});
}
b.sortPlaylistRandom = function() {
R.enhancer.getTracks(function(tracks) {
R.enhancer.show_message("Randomized Playlist")
R.enhancer.current_playlist.model.setPlaylistOrder(R.enhancer.getKeys(R.enhancer.shuffle(tracks)));
R.enhancer.current_playlist.render();
});
};
// End Sort menu functions
// Inject Extras menu functions
b.getExtraMenuOptions = function() {
var submenu = [{
label: "Export to CSV",
value: "exporttocsv",
callback: this.exportToCSV,
visible: true
}, {
label: "Fork Playlist",
value: "forkplaylist",
callback: this.forkPlaylist,
visible: true
}, {
label: "About Rdio Enhancer",
value: "aboutrdioenhancer",
callback: R.enhancer.about_dialog,
visible: true
}
];
if (this.model.canEdit !== undefined && this.model.canEdit()) {
submenu.unshift ({
label: "Remove Duplicates",
value: "removeduplicates",
callback: this.removeDuplicates,
visible: true
});
}
return submenu;
};
b.removeDuplicates = function() {
R.enhancer.getTracks(function(tracks) {
var playlist_key = R.enhancer.current_playlist.model.get("key");
// This is a bit hackish, but the API doesn't work well.
// The removeFromPlaylist function is based more on the index and count than the tracklist
// So order matters!!
// First we sort the playlist to unique tracks first and then duplicate tracks last.
// Then just chop off all the duplicate tracks.
// This way we only need one call to removeFromPlaylist to remove all the duplicates.
var unique_tracks = [];
var duplicate_tracks = [];
jQuery.each(tracks, function(index, value) {
var track_key = value.attributes.source.attributes.key;
if(jQuery.inArray(track_key, unique_tracks) === -1) {
unique_tracks.push(track_key);
}
else {
duplicate_tracks.push(track_key);
}
});
if(duplicate_tracks.length > 0) {
R.enhancer.show_message('Removing Duplicates from "' + R.enhancer.current_playlist.model.get("name") + '"');
R.enhancer.sortPlaylist(playlist_key, unique_tracks.concat(duplicate_tracks), function(status) {
if (status.result) {
R.Api.request({
method: "removeFromPlaylist",
content: {
playlist: playlist_key,
index: unique_tracks.length,
count: duplicate_tracks.length,
tracks: duplicate_tracks,
extras: ["-*", "duration", "Playlist.PUBLISHED"]
},
success: function(success_data) {
R.enhancer.current_playlist.render();
}
});
}
});
}
else {
R.enhancer.show_message('There are no duplicates to remove "' + R.enhancer.current_playlist.model.get("name") + '"');
}
});
};
b.exportToCSV = function() {
R.enhancer.getTracks(function(tracks) {
var csv = [["Name", "Artist", "Album", "Track Number"].join(",")];
var keys = ["name", "artist", "album", "trackNum"];
var regex = new RegExp('"', 'g');
jQuery.each(tracks, function(index, track) {
var values = [];
jQuery.each(keys, function(index, key) {
if( typeof track.attributes.source.attributes[key] === 'number' ) {
values.push( track.attributes.source.attributes[key] );
}
else {
values.push( track.attributes.source.attributes[key].replace(regex, '""') );
}
});
csv.push('"' + values.join('","') + '"');
});
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv.join("\n")));
pom.setAttribute('download', R.enhancer.current_playlist.model.get("name") + '.csv');
pom.click();
});
};
b.forkPlaylist = function() {
R.enhancer.getTracks(function(tracks) {
R.loader.load(["Dialog.EditPlaylistDialog.Rdio"], function() {
var editor = new R.Components.Dialog.EditPlaylistDialog.Rdio({
sourceModel: R.enhancer.current_playlist.model,
isNew: true
});
editor.open()
});
});
};
}
if(a == "Catalog2014.Playlist") {
//R.enhancer.log(b);
b.orig_onRendered = b.onRendered;
b.onRendered = function() {
b.orig_onRendered.call(this);
//R.enhancer.log(this.model);
R.enhancer.current_playlist = this;
}
}
if(a == "Profile.Favorites") {
b.orig_onRendered = b.onRendered;
b.onRendered = function() {
b.orig_onRendered.call(this);
this.$(".section_header").append('<span class="export_to_csv_box">Start Export #: <input type="text" class="export_start" value="0"> <button type="button" class="button exportToCSV with_text">Export to CSV</button></span>');
this.$(".header").append('<span class="filter_container"><div class="TextInput filter"><input class="tags_filter unstyled" placeholder="Filter By Tag" name="" type="text" value=""></div></span>');
this.$(".exportToCSV").on("click", function(e) {
var start = parseInt( jQuery(".export_start").val() );
var regex = new RegExp('"', 'g');
R.enhancer.getFavoriteTracks(function(tracks) {
var csv = [["Name", "Artist", "Album", "Track Number"].join(",")];
var keys = ["name", "artist", "album", "trackNum"];
jQuery.each(tracks, function(index, track) {
var values = [];
jQuery.each(keys, function(index, key) {
if( typeof track[key] === 'number' ) {
values.push( track[key] );
}
else {
values.push( track[key].replace(regex, '""') );
}
});
csv.push('"' + values.join('","') + '"');
});
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv.join("\n")));
pom.setAttribute('download', 'collection.csv');
pom.click();
}, start);
});
this.$(".tags_filter").on("keyup", _.bind(function() {
var value = this.$(".tags_filter").val().trim();
var albums = R.enhancer.getAlbumsForTag(value);
if (albums.length > 0) {
R.enhancer.collection.collectionModel.reset();
R.enhancer.collection.collectionModel.on("loaded", function() {
R.enhancer.collection.collectionModel.off("loaded");
R.enhancer.collection.collectionModel.manualFiltered = true;
R.enhancer.collection.collectionModel.reset(R.enhancer.collection.collectionModel.filter(function(model) { return _.contains(albums, model.get("albumKey")); }));
});
R.enhancer.collection.collectionModel.get({start:R.enhancer.collection.collectionModel.models.length, count:R.enhancer.collection.collectionModel._limit});
} else if (R.enhancer.collection.collectionModel.manualFiltered) {
R.enhancer.collection.collectionModel.manualFiltered = false;
R.enhancer.collection.collectionModel.reset();
}
}, this));
}
}
if(a == "Menu") {
b.orig_onRendered = b.onRendered;
b.onRendered = function() {
b.orig_onRendered.call(this);
var menu = this;
if(menu.$('li:first-child').text().trim() == 'Name') {
// private scope for this menu component
(function() {
var item = $('<li class="option truncated_line">Unavailable Albums</li>'),
spinner = new R.Components.Spinner(),
template = _.template(''
+ '<div class="album">'
+ '<div class="album_name"><a href="<%= albumUrl %>"><%= name %></a></div>'
+ '<div class="album_artist"><a href="<%= artistUrl %>"><%= artist %></a></div>'
+ '<div class="badge colored">Unavailable</div>'
+ '</div>'
);
menu.$('ul').append(item);
item.on('click', function(event) {
R.loader.load(["Dialog"], function() {
var dialog = new R.Components.Dialog({
title: 'Unavailable Albums',
width: 550,
extraClassName: 'unavailable_dialog',
closeButton: 'Close'
});
dialog.onOpen = function() {
if(R.enhancer.cache['unavailable_albums']) {
dialog.onLoaded(R.enhancer.cache['unavailable_albums']);
} else {
this.$('.body .container').append(spinner.el);
spinner.spin();
R.enhancer.getUnavilableAlbums(function(results) {
// caching results of this call as it's unlikely that:
// 1) someone will add an unavailable album to their favorites
// 2) a previously saved album will change to unavailable during their session
R.enhancer.cache['unavailable_albums'] = results;
dialog.onLoaded(results);
});
}
};
dialog.onLoaded = function(data) {
var albums = [];
for(var i = 0, length = data.length, album; i < length; i++) {
// console.debug(data[i]);
albums.push(template(data[i]));
}
spinner.stop();
this.$('.body .container').html('<ul>' + albums.join('') + '</ul>');
this.onResize();
};
menu.close();
dialog.open();
});
});
})();
}
}
}
if(a == "InfiniteScroll") {
b.orig_ensureItemsLoaded = b.ensureItemsLoaded;
b.ensureItemsLoaded = function() {
// When manually filtered (by tagging system)
// stop the component from reloading all albums
if (this.model.manualFiltered) {
return;
}
b.orig_ensureItemsLoaded.call(this);
}
}
// Create playlists based on an artist's top tracks
if(a == "Catalog.Artist.Songs") {
b.orig_events = b.events || null;
b.events = function() {
var local_events = b.orig_events ? b.orig_events.call(this) : {};
local_events["click .artist_tracks_to_playlist"] = "onArtistTracksToPlaylistClicked";
return local_events;
};
b.onArtistTracksToPlaylistClicked = function(event) {
this.artistTracksToPlaylistMenu.open();
R.Utils.stopEvent(event);
};
b.onArtistTracksToPlaylistOptionSelected = function(menuItem) {
var count = menuItem.get('value'),
artistKey = this.model.get('key'),
maxArtistTracks = this.model.get('length'),
playlistName = this.model.get('name') + ' Top Tracks',
tracksToAdd,
getTracks,
createPlaylist;
createPlaylist = (tracksToAdd) => {
return R.Api.request({
method: "createPlaylist",
content: { name: playlistName, description: playlistName, tracks: tracksToAdd },
success: function() {
R.enhancer.show_message('Playlist created.', true);
},
error: function() {
R.enhancer.show_message('There was an error creating an artist playlist.', true);
}
});
}
R.Api.request({
method: "getTracksForArtist",
content: { artist: artistKey, count: count, extras: ['-*', 'key'] },
success: (response) => {
if(response.status != 'ok') {
R.enhancer.show_message('There was an error getting tracks for this artist.', true);
return;
}
tracksToAdd = _.pluck(response.result.items, 'key');
createPlaylist(tracksToAdd);
},
error: () => {
R.enhancer.show_message('There was an error getting tracks for this artist.', true);
}
});
};
b.getMenuOptions = (maxTracks) => {
var sizeChoices = _.filter([10, 100, 250, 500, 1000], (num) => { return num <= maxTracks }),
menuOptions = new Backbone.Collection([]),
cur,
createMenuItem;
createMenuItem = (val) => {
return {
label: 'Add Top ' + val,
value: val,
callback: b.onArtistTracksToPlaylistOptionSelected,
extraClassNames: 'playlist'
};
};
while (sizeChoices.length) {
cur = sizeChoices.shift();
menuOptions.push(createMenuItem(cur));
}
menuOptions.push(createMenuItem(maxTracks));
return menuOptions;
};
b.orig_onRendered = b.onRendered || R.doNothing;
b.onRendered = function() {
b.orig_onRendered.call(this);
this.$(".SortControls").append('<div class="artist_tracks_to_playlist"></div>');
var $artistTracksToPlaylistMenuEl = this.$(".artist_tracks_to_playlist"),
artistMaxTracks = this.model.get('length'),
menuOptionsModel = b.getMenuOptions(artistMaxTracks);
this.artistTracksToPlaylistMenu = this.addChild(new R.Components.Menu({
positionOverEl: $artistTracksToPlaylistMenuEl,
positionUnder: false,
model: menuOptionsModel,
defaultContext: this
}));
};
}
if(a == "Catalog2014.Album") {
b.orig_onInserted = b.onInserted;
b.onInserted = function() {
b.orig_onInserted.call(this);
this.trigger('Catalog2014.Album:inserted');
}
}
if(a == "TrackList") {
b.orig_onRendered = b.onRendered;
b.onRendered = function() {
b.orig_onRendered.call(this);
if (this.options.highlightTrack && this.parent() instanceof R.Components.Catalog2014.Album) {
this.listen(this.parent(), "Catalog2014.Album:inserted", () => {
this.$('.url_highlighted a').focus();
});
}
}
}
return R.Component.orig_create.call(this, a,b,c);
};
},
get_setting: function(setting_name) {
if(window.localStorage["/enhancer/settings/" + setting_name]) {
return window.localStorage["/enhancer/settings/" + setting_name];
}
return false;
},
set_setting: function(setting_name, value) {
window.localStorage["/enhancer/settings/" + setting_name] = value;
},
settings_dialog: function() {
R.loader.load(["Dialog"], function() {
var enhancer_settings_dialog = new R.Components.Dialog({
title: "Rdio Enhancer Settings",
buttons: new Backbone.Model({
label: "Save",
className: "blue",
context: this,
callback: function() {
switch(enhancer_settings_dialog.$("input[name=enhancer_notifications]:checked").val()) {
case "chrome":
R.enhancer.set_setting("notifications", "chrome");
break;
case "none":
R.enhancer.set_setting("notifications", "none");
break;
case "html":
default:
R.enhancer.set_setting("notifications", "html");
break;
}
enhancer_settings_dialog.close();
}
}),
closeButton: "Cancel"
});
enhancer_settings_dialog.onOpen = function() {
this.$(".body").addClass("Dialog_FormDialog");
this.$(".body .container").append($("#enhancer_settings_form").clone());
// Notification settings
var notification_setting = R.enhancer.get_setting("notifications");
if(notification_setting === false) {
notification_setting = "html";
}
this.$(".body #enhancer_notifications_" + notification_setting).prop('checked',true);
};
enhancer_settings_dialog.open()
});
},
about_dialog: function() {
R.loader.load(["Dialog"], function() {
var about_enhancer = new R.Components.Dialog({
title: "About Rdio Enhancer"
});
about_enhancer.onOpen = function() {
this.$(".body").html('<p>Enhancement features brought to you by <a href="https://chrome.google.com/webstore/detail/hmaalfaappddkggilhahaebfhdmmmngf" target="_blank">Rdio Enhancer</a></p><p>Get the code or browse the code at <a href="https://github.com/matt-h/rdio-enhancer" target="_blank">https://github.com/matt-h/rdio-enhancer</a></p><p>If you like this extension, <a href="https://chrome.google.com/webstore/detail/hmaalfaappddkggilhahaebfhdmmmngf" target="_blank">please rate it here</a></p>');
};
about_enhancer.open()
});
},
get_messages: function() {
var messages = jQuery(".enhancer_messages");
if(messages.length < 1) {
messages = jQuery('<div class="enhancer_messages"></div>').appendTo("body");
messages.on("click", ".enhancer_message_box", function(event) {
$(this).fadeOut("slow", function() {
$(this).remove();
});
});
}
return messages;
},
show_message: function(msg_txt, force_message) {
switch(R.enhancer.get_setting("notifications")) {
case "none":
// Force message option shows the message if the user settings are none
if(force_message !== true) {
break;
}
case false:
case "html":
var messages = R.enhancer.get_messages();
jQuery('<div class="enhancer_message_box">' + msg_txt + '</div>').appendTo(messages).fadeIn("slow").delay(10000).fadeOut("slow", function() {
jQuery(this).remove();
});
break;
case "chrome":
if ("Notification" in window) {
if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification("Rdio Notification", {body: msg_txt});
}
else if (Notification.permission !== 'denied') {
Notification.requestPermission(function (permission) {
// Whatever the user answers, we make sure we store the information
if(!('permission' in Notification)) {
Notification.permission = permission;
}
// If the user is okay, let's create a notification
if (permission === "granted") {
var notification = new Notification("Rdio Notification", {body: msg_txt});
}
});
}
}
else if("webkitNotifications" in window) {
var notification = webkitNotifications.createNotification(
"", // icon url - can be relative
"Rdio Notification", // notification title
msg_txt // notification body text
);
notification.show();
}
break;
}
},
/**
* Show yourself in the listeners badges
*/
inject_hasListened: function inject_extras(args): boolean {
var didModify = false;
// Adding has listened for favorites isn't very useful
if (args.method === 'getFavorites') return didModify;
try {
if (args.content) {