forked from vartan/robin-grow
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathrobin.user.js
2259 lines (1929 loc) · 89.6 KB
/
robin.user.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
// ==UserScript==
// @name parrot (color multichat for robin!)
// @namespace http://tampermonkey.net/
// @version 3.65
// @description Recreate Slack on top of an 8 day Reddit project.
// @author dashed, voltaek, daegalus, vvvv, orangeredstilton, lost_penguin, AviN456, Annon201, LTAcosta, mofosyne
// @include https://www.reddit.com/robin*
// @updateURL https://github.com/5a1t/parrot/raw/master/robin.user.js
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @require https://raw.githubusercontent.com/ricmoo/aes-js/master/index.js
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_addStyle
// @grant GM_xmlhttpRequest
// ==/UserScript==
(function() {
// hacky solutions
var CURRENT_CHANNEL = "";
var GOTO_BOTTOM = true;
var robinChatWindow = $('#robinChatWindow');
String.prototype.lpad = function(padString, length) {
var str = this;
var prepend_str = "";
for (var i = str.length; i < length; i++) {
prepend_str = padString + prepend_str;
}
return prepend_str + str;
};
String.prototype.rpad = function(padString, length) {
var str = this;
var prepend_str = "";
for (var i = str.length; i < length; i++) {
prepend_str = padString + prepend_str;
}
return str + prepend_str;
};
function tryHide(){
if(settings.hideVote){
console.log("hiding vote buttons.");
$('.robin-chat--buttons').hide();
}
else{
$('.robin-chat--buttons').show();
}
}
// Channel selected in channel drop-down
function dropdownChannel()
{
return $("#chat-prepend-select").val().trim();
}
function buildDropdown()
{
split_channels = getChannelString().split(",");
drop_html = "";
for (var tag in split_channels) {
var channel_name = split_channels[tag].trim();
drop_html += '<option value="' + channel_name + '">' + channel_name + '</option>';
}
$("#chat-prepend-select").html(drop_html);
$("#chat-prepend-select").on("change", function() { updateTextCounter(); });
}
function updateUserPanel(){
var options = {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit"
};
$(".robin-room-participant").each( function(){
lastseen = userExtra[$(this).find(".robin--username").text().trim()];
if(lastseen){
datestring = lastseen.toLocaleTimeString("en-us", options);
$( this ).find(".robin--username").nextAll().remove();
$( this ).find(".robin--username").after("<span class=\"robin-message--message\"style=\"font-size: 10px;\"> " + datestring + "</span>");
}
});
}
// Utils
function getChannelString() {
return settings.filterChannel ? settings.channel : "," + settings.channel;
}
function getChannelList()
{
var channels = String(getChannelString()).split(",");
var channelArray = [];
for (i = 0; i < channels.length; i++)
{
var channel = channels[i].trim();
if (channel.length > 0)
channelArray.push(channel.toLowerCase());
}
return channelArray;
}
function hasChannel(source)
{
channel_array = getChannelList();
source = String(source).toLowerCase();
return hasChannelFromList(source, channel_array, false);
}
function hasChannelFromList(source, channels, shall_trim, ignore_empty)
{
channel_array = channels;
source = shall_trim ? String(source).toLowerCase().trim() : String(source).toLowerCase();
for (idx = 0; idx < channel_array.length; idx++)
{
var current_chan = shall_trim ? channel_array[idx].trim() : channel_array[idx];
if(ignore_empty && current_chan.length <= 0) {
continue;
}
if(source.startsWith(current_chan.toLowerCase())) {
return {
name: current_chan,
has: true,
index: idx
};
}
}
return {
name: "",
has: false,
index: 0
};
}
function formatNumber(n) {
var part = n.toString().split(".");
part[0] = part[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return part.join(".");
}
function addMins(date, mins) {
var newDateObj = new Date(date.getTime() + mins * 60000);
return newDateObj;
}
function howLongLeft(endTime) {
if (endTime === null) {
return 0;
}
try {
return Math.floor((endTime - new Date()) / 60 / 1000 * 10) / 10;
} catch (e) {
return 0;
}
}
var UserExtra = {
load: function loadSetting() {
var userExtra = localStorage.getItem('parrot-user-extra');
var users_version = localStorage.getItem('parrot-user-version');
try {
userExtra = userExtra ? JSON.parse(userExtra) : {};
} catch(e) { console.log("Error parsing userExtra..");}
userExtra = userExtra || {};
if(users_version == 12){
console.log("found a good user list!");
//return userExtra;
//JSON.stringify is returning undefined.. Reset list each time for now. Will fix.
return {};
}
else {
console.log("found a bad user list, resetting!");
localStorage.setItem('parrot-user-extra', JSON.stringify({}));
return {};
}
},
save: function saveSetting(userExtra) {
console.log("Saving");
//console.log(JSON.stringify(userExtra));
localStorage.setItem('parrot-user-extra', JSON.stringify(userExtra));
localStorage.setItem('parrot-user-version', 12);
}
}
var Settings = {
setupUI: function() {
// Open Settings button
$robinVoteWidget.prepend("<div class='addon'><div id='chatstats' class='robin-chat--vote info-box-only'></div></div>");
$robinVoteWidget.prepend("<div class='addon'><div class='usercount robin-chat--vote info-box-only'></div></div>");
$robinVoteWidget.prepend("<div class='addon'><div class='timeleft robin-chat--vote info-box-only'></div></div>");
$robinVoteWidget.prepend('<div class="addon" id="openBtn_wrap"><div class="robin-chat--vote" id="openBtn">Open Settings</div></div>');
$robinVoteWidget.append('<div class="addon"><div class="robin-chat--vote" id="standingsBtn">Show Standings</div></div>');
$robinVoteWidget.append('<div class="addon"><div class="robin-chat--vote" id="channelsBtn">Show Most Active Channels</div></div>');
$("#openBtn_wrap").prepend('<div class="robin-chat--sidebar-widget">' +
'<a target="_blank" href="https://www.reddit.com/r/parrot_script/"><div class="robin-chat--vote">' +
'<img src="https://i.imgur.com/ch75qF2.png">Parrot</div><p>soKukunelits fork ~ ' + versionString + '</p></a></div>');
// Setting container
$(".robin-chat--sidebar").before(
'<div class="robin-chat--sidebar" style="display:none;" id="settingContainer">' +
'<div class="robin-chat--sidebar-widget robin-chat--vote-widget" id="settingContent">' +
'<div class="robin-chat--vote" id="closeBtn">Close Settings</div>' +
'</div>' +
'</div>'
);
// Standing container
$("#settingContainer").before(
'<div class="robin-chat--sidebar" style="display:none;" id="standingsContainer">' +
'<div class="robin-chat--sidebar-widget robin-chat--vote-widget" id="standingsContent">' +
'<div id="standingsTable">' +
'<div>Reddit leaderboard</div><br/>' +
'<div id="standingsTableReddit"></div><br/>' +
'<div id="standingsTableMonstrous"></div>' +
'</div>' +
'<a href="https://www.reddit.com/r/robintracking/comments/4czzo2/robin_chatter_leader_board_official/" target="_blank">' +
'<div class="robin-chat--vote">Full Leaderboard</div></a>' +
'<div class="robin-chat--vote" id="closeStandingsBtn">Close Standings</div>' +
'</div>' +
'</div>'
);
// Active channels container
$("#settingContainer").before(
'<div class="robin-chat--sidebar" style="display:none;" id="channelsContainer">' +
'<div class="robin-chat--sidebar-widget robin-chat--vote-widget" id="channelsContent">' +
'<div id="channelsTable">' +
'<div>Most Active Channels (experimental)</div><br/>' +
'<div id="activeChannelsTable"></div><br/>' +
'</div>' +
'<div class="robin-chat--vote" id="closeChannelsBtn">Close Channel List</div>' +
'</div>' +
'</div>'
);
$("#settingContent").append('<div class="robin-chat--sidebar-widget robin-chat--notification-widget"><ul><li>Click on chat name to hide sidebar</li><li>Left click usernames to mute.</li>' +
'<li>Right click usernames to copy to message.<li>Tab autocompletes usernames in the message box.</li><li>Ctrl+shift+left/right switches between channel tabs.</li>' +
'<li>Up/down in the message box cycles through sent message history.</li><li>Report any bugs or issues <a href="https://www.reddit.com/r/parrot_script/" target="_blank"><strong>HERE<strong></a></li>' +
'<li>Created for soKukuneli chat (T16)</li></ul></div>');
$("#robinDesktopNotifier").detach().appendTo("#settingContent");
$("#openBtn").on("click", function openSettings() {
$(".robin-chat--sidebar").hide();
$("#settingContainer").show();
});
$("#closeBtn").on("click", function closeSettings() {
$(".robin-chat--sidebar").show();
$("#settingContainer").hide();
$("#standingsContainer").hide();
$("#channelsContainer").hide();
tryHide();
update();
});
$("#standingsBtn").on("click", function openStandings() {
$(".robin-chat--sidebar").hide();
startStandings();
$("#standingsContainer").show();
});
$("#closeStandingsBtn").on("click", function closeStandings() {
$(".robin-chat--sidebar").show();
stopStandings();
$("#standingsContainer").hide();
$("#settingContainer").hide();
$("#channelsContainer").hide();
});
$("#channelsBtn").on("click", function openChannels() {
$(".robin-chat--sidebar").hide();
startChannels();
$("#channelsContainer").show();
});
$("#closeChannelsBtn").on("click", function closeChannels() {
$(".robin-chat--sidebar").show();
stopChannels();
$("#channelsContainer").hide();
$("#standingsContainer").hide();
$("#settingContainer").hide();
});
$("#robinSendMessage").prepend('<div id="chat-prepend-area"><label>Send chat to</span><select id="chat-prepend-select"></select></div>');
function setVote(vote) {
return function() {
settings.vote = vote;
Settings.save(settings);
};
}
$(".robin-chat--vote.robin--vote-class--abandon").on("click", setVote("abandon"));
$(".robin-chat--vote.robin--vote-class--continue").on("click", setVote("stay"));
$(".robin-chat--vote.robin--vote-class--increase").on("click", setVote("grow"));
$('.robin-chat--buttons').prepend("<div class='robin-chat--vote robin--vote-class--novote'><span class='robin--icon'></span><div class='robin-chat--vote-label'></div></div>");
},
load: function loadSetting() {
var setting = localStorage.getItem('robin-grow-settings');
try {
setting = setting ? JSON.parse(setting) : {};
} catch(e) {}
setting = setting || {};
toggleSidebarPosition(setting);
if (!setting.vote)
setting.vote = "grow";
return setting;
},
save: function saveSetting(settings) {
localStorage.setItem('robin-grow-settings', JSON.stringify(settings));
},
addBool: function addBoolSetting(name, description, defaultSetting, callback) {
defaultSetting = settings[name] || defaultSetting;
$("#settingContent").append('<div class="robin-chat--sidebar-widget robin-chat--notification-widget"><label><input type="checkbox" name="setting-' + name + '"' + (defaultSetting ? ' checked' : '') + '>' + description + '</label></div>');
$("input[name='setting-" + name + "']").change(function() {
settings[name] = !settings[name];
Settings.save(settings);
if(callback) {
callback();
}
});
if (settings[name] !== undefined) {
$("input[name='setting-" + name + "']").prop("checked", settings[name]);
} else {
settings[name] = defaultSetting;
}
},
addRadio: function addRadioSetting(name, description, items, defaultSettings, callback) {
//items JSON format:
// {"id":[{"value":<string>,
// "friendlyName":<string>}]};
defaultSettings = settings[name] || defaultSettings;
$("#settingContent").append('<div id="settingsContainer-' + name + '" class="robin-chat--sidebar-widget robin-chat--notification-widget"><span style="font-weight: 300; letter-spacing: 0.5px; line-height: 15px; font-size:' + settings.fontsize + 'px;">' + description + '</span><br><br>');
for (i in items.id) {
$("#settingsContainer-" + name).append('<label><input type="radio" name="settingsContainer-' + name + '" value="' + items.id[i].value + '"> ' + items.id[i].friendlyName + '</input></label><br>');
}
$("#settingsContainer-" + name).append('</div>');
if (settings[name] != undefined) {
$("input:radio[name='setting-" + name + "'][value='" + settings[name] + "']").prop("checked", true);
}
else {
$("input:radio[name='setting-" + name + "'][value='" + defaultSettings + "']").prop("checked", true);
}
$("input:radio[name='setting-" + name + "']").on("click", function () {
settings[name] = $("input:radio[name='setting-" + name + "']:checked").val();
Settings.save(settings);
});
if (callback) {
callback();
}
},
addInput: function addInputSetting(name, description, defaultSetting, callback) {
defaultSetting = settings[name] || defaultSetting;
$("#settingContent").append('<div id="robinDesktopNotifier" class="robin-chat--sidebar-widget robin-chat--notification-widget"><label>' + description + '</label><input type="text" name="setting-' + name + '"></div>');
$("input[name='setting-" + name + "']").prop("defaultValue", defaultSetting)
.on("change", function() {
settings[name] = String($(this).val());
Settings.save(settings);
if(callback) {
callback();
}
});
settings[name] = defaultSetting;
},
addButton: function(appendToID, newButtonID, description, callback, options) {
options = options || {};
$('#' + appendToID).append('<div class="addon"><div class="robin-chat--vote" style="font-weight: bold; padding: 5px;cursor: pointer;" id="' + newButtonID + '">' + description + '</div></div>');
$('#' + newButtonID).on('click', function(e) { callback(e, options); });
}
};
function clearChat() {
console.log("chat cleared!");
getChannelMessageList(selectedChannel).empty();
}
function setRobinMessageVisibility() {
var prop = (settings.removeRobinMessages) ? "none" : "block";
$('#robinMessageVisiblity')
.text('.robin-message.robin--flair-class--no-flair.robin--user-class--system {display: ' + prop + ';}');
}
function toggleSidebarPosition(setting) {
settings = settings || setting;
var elements = {
header: $('.robin-chat--header'),
content: $('.content[role="main"]'),
votePanel: $('.robin-chat--buttons'),
sidebars: $('.robin-chat--sidebar'),
chat: $('.robin-chat--main')
};
var sidebars = elements.sidebars.detach();
settings.sidebarPosition ? elements.chat.before(sidebars) : elements.chat.after(sidebars);
}
function toggleTableMode(setting) {
settings = settings || setting;
if (settings.tableMode)
$('.robin-chat--message-list').addClass('robin-chat--message-list-table-mode');
else $('.robin-chat--message-list').removeClass('robin-chat--message-list-table-mode');
}
function grabStandings() {
var standings;
// Reddit leaderboard
$.ajax({
url: 'https://www.reddit.com/r/robintracking/comments/4czzo2/robin_chatter_leader_board_official/.rss?limit=1',
data: {},
success: function( data ) {
var currentRoomName = $('.robin-chat--room-name').text();
var standingsPost = $(data).find("entry > content").first();
var decoded = $($('<div/>').html(standingsPost).text()).find('table').first();
decoded.find('tr').each(function(i) {
var row = $(this).find('td,th');
var nameColumn = $(row.get(2));
nameColumn.find('a').prop('target','_blank');
if (currentRoomName.startsWith(nameColumn.text().substring(0,6))) {
var color = String(settings.leaderboard_current_color).length > 0 ? String(settings.leaderboard_current_color).trim() : '#22bb45';
row.css('background-color', color);
}
row.each(function(j) {if (j == 3 || j == 4 || j > 5) {
$(this).remove();
}});
});
$("#standingsTableReddit").html(decoded);
},
dataType: 'xml'
});
// monstrouspeace.com tracker board
$("#standingsTableMonstrous").html("");
if (settings.monstrousStats)
{
$.ajax({
type: 'GET',
url: 'https://monstrouspeace.com/robintracker/json.php',
data: { get_param: 'value' },
dataType: 'json',
xhr: function() { return new GM_XHR(); },
success: function(data) {
var decoded =
'<br/><div style="font-weight: bold; text-align: center;">MonstrousPeace.com tracking (experimental)</div><br/>' +
"<table>\r\n" +
"<thead>\r\n" +
"<tr><th>#</th><th>Participants</th><th>Grow</th><th>Stay</th><th>Room Name</th><th>Tier</th></tr>\r\n" +
"</thead>\r\n" +
"<tbody>\r\n";
$.each(data, function(index, e) {
decoded += "<tr><td>" + (index+1) + "</td><td>" + e.count + "</td><td>" + e.grow + "</td><td>" + e.stay + "</td><td>" + e.room + "</td><td>" + e.tier + "</td></tr>\r\n";
});
decoded +=
"</tbody>\r\n" +
"</table>\r\n" +
'<br/>';
$("#standingsTableMonstrous").html(decoded);
}
});
}
};
//
// XHR that can cross same origin policy boundaries
//
function GM_XHR() {
this.type = null;
this.url = null;
this.async = null;
this.username = null;
this.password = null;
this.status = null;
this.headers = {};
this.readyState = null;
this.abort = function() { this.readyState = 0; };
this.getAllResponseHeaders = function(name) { return this.readyState != 4 ? "" : this.responseHeaders; };
this.getResponseHeader = function(name) {
var regexp = new RegExp('^'+name+': (.*)$','im');
var match = regexp.exec(this.responseHeaders);
if (match) { return match[1]; }
return '';
};
this.open = function(type, url, async, username, password) {
this.type = type ? type : null;
this.url = url ? url : null;
this.async = async ? async : null;
this.username = username ? username : null;
this.password = password ? password : null;
this.readyState = 1;
};
this.setRequestHeader = function(name, value) { this.headers[name] = value; };
this.send = function(data) {
this.data = data;
var that = this;
GM_xmlhttpRequest({
method: this.type,
url: this.url,
headers: this.headers,
data: this.data,
onload: function(rsp) { for (var k in rsp) { that[k] = rsp[k]; } that.onreadystatechange(); },
onerror: function(rsp) { for (var k in rsp) { that[k] = rsp[k]; } }
});
};
};
var standingsInterval = 0;
function startStandings() {
stopStandings();
standingsInterval = setInterval(grabStandings, 120000);
grabStandings();
}
function stopStandings() {
if (standingsInterval){
clearInterval(standingsInterval);
standingsInterval = 0;
}
}
function updateChannels()
{
// Sort the channels
var channels = [];
for(var channel in activeChannelsCounts){
if (activeChannelsCounts[channel] > 1){
channels.push(channel);
}
}
channels.sort(function(a,b) {return activeChannelsCounts[b] - activeChannelsCounts[a];});
// Build the table
var html = "<table>\r\n" +
"<thead>\r\n" +
"<tr><th>#</th><th>Channel Name</th><th>Join Channel</th></tr>\r\n" +
"</thead>\r\n" +
"<tbody>\r\n";
var limit = 50;
if (channels.length < limit)
limit = channels.length;
for (var i = 0; i < limit; i++) {
html += "<tr><td>" + (i+1) + "</td><td>" + channels[i] + "</td><td><div class=\"channelBtn robin-chat--vote\">Join Channel</div></td></tr>\r\n";
}
html += "</tbody>\r\n" +
"</table>\r\n" +
'<br/>';
$("#activeChannelsTable").html(html);
$(".channelBtn").on("click", function joinChannel() {
var channel = $(this).parent().prev().contents().text();
var channels = getChannelList();
if (channel && $.inArray(channel, channels) < 0) {
settings.channel += "," + channel;
Settings.save(settings);
buildDropdown();
resetChannels();
}
});
}
var channelsInterval = 0;
function startChannels() {
stopChannels();
channelsInterval = setInterval(updateChannels, 30000);
updateChannels();
}
function stopChannels() {
if (channelsInterval){
clearInterval(channelsInterval);
channelsInterval = 0;
}
}
var currentUsersName = $('div#header span.user a').html();
// Settings begin
var $robinVoteWidget = $("#robinVoteWidget");
// IF the widget isn't there, we're probably on a reddit error page.
if (!$robinVoteWidget.length) {
// Don't overload reddit, wait a bit before reloading.
setTimeout(function() {
window.location.reload();
}, 300000);
return;
}
// Get version string (if available from script engine)
var versionString = "";
if (typeof GM_info !== "undefined") {
versionString = GM_info.script.version;
}
Settings.setupUI($robinVoteWidget);
var settings = Settings.load();
var userExtra = UserExtra.load();
startUserExtra();
function tryStoreUserExtra(){
console.log("storing lastseens");
UserExtra.save(userExtra);
}
var userExtraInterval = 0;
function startUserExtra() {
userExtraInterval = setInterval(listAllUsers, 10*1000);
userExtraInterval = setInterval(tryStoreUserExtra, 20*1000);
}
// bootstrap
tryHide();
// Options begin
Settings.addButton("settingContent", "update-script-button", "Update Parrot", function(){ window.open("https://github.com/5a1t/parrot/raw/master/robin.user.js?t=" + (+ new Date()), "_blank"); });
Settings.addButton("robinChatInput", "clear-chat-button", "Clear Chat", clearChat);
Settings.addBool("hideVote", "Hide voting panel", false, tryHide);
Settings.addBool("removeSpam", "Remove bot spam", true);
Settings.addInput("spamFilters", "<label>Custom Spam Filters<ul><li><b>Checkbox 'Remove bot spam' (above)</b></li><li>Comma-delimited</li><li>Spaces are NOT stripped</li></ul></label>", "spam example 1,John Madden");
Settings.addBool("enableUnicode", "Allow unicode characters. Unicode is considered spam and thus are filtered out", false);
Settings.addBool("sidebarPosition", "Left sidebar", false, toggleSidebarPosition);
Settings.addBool("force_scroll", "Force scroll to bottom", false);
Settings.addInput("cipherkey", "16 Character Cipher Key", "Example128BitKey");
Settings.addInput("maxprune", "Max messages before pruning", "500");
Settings.addBool("tableMode", "Toggle table-mode for the message list", false, toggleTableMode);
Settings.addInput("fontsize", "Chat font size", "12");
Settings.addInput("fontstyle", "Font Style (default Consolas)", "");
Settings.addBool("alignment", "Right align usernames", true);
Settings.addInput("username_bg", "Custom background color on usernames", "");
Settings.addBool("removeRobinMessages", "Hide [robin] messages everywhere", false, setRobinMessageVisibility);
Settings.addBool("removeChanMessageFromGlobal", "Hide channel messages in Global", false);
Settings.addBool("filterChannel", "Hide non-channel messages in Global", false, function() { buildDropdown(); });
Settings.addInput("channel", "<label>Channel Listing<ul><li>Multi-room-listening with comma-separated rooms</li><li>Names are case-insensitive</li><li>Spaces are NOT stripped</li></ul></label>", "%parrot", function() { buildDropdown(); resetChannels(); });
Settings.addInput("channel_exclude", "<label>Channel Exclusion Filter<ul><li>Multi-room-listening with comma-separated rooms</li><li><strong>List of channels to exclude from Global channel (e.g. trivia channels)</strong></li><li>Names are case-insensitive</li><li>Spaces are NOT stripped</li></ul></label>", "");
Settings.addBool("tabChanColors", "Use color on channel tabs", true);
Settings.addBool("twitchEmotes", "Twitch emotes (<a href='https://twitchemotes.com/filters/global' target='_blank'>Normal</a>, <a href='https://nightdev.com/betterttv/faces.php' target='_blank'>BTTV</a>)", false);
Settings.addBool("youtubeVideo", "Inline youtube videos", false);
Settings.addBool("timeoutEnabled", "Reload page after inactivity timeout", true);
Settings.addInput("messageHistorySize", "Sent Message History Size", "50");
Settings.addBool("monstrousStats", "Show automated leaderboard on standings page (asks for permission)</a>", false);
Settings.addBool("reportStats", "Contribute statistics to the <a href='https://monstrouspeace.com/robintracker/'>Automated Leaderboard</a>.", true);
Settings.addInput("statReportingInterval", "Report Statistics Interval (seconds) [above needs to be checked]", "300");
Settings.addInput("leaderboard_current_color", "Highlight color of current chat room in leaderboard standings", '#22bb45');
Settings.addBool("enableTabComplete", "Tab Autocomplete usernames", true);
Settings.addBool("enableQuickTabNavigation", "Keyboard channel-tabs navigation", true);
Settings.addBool("enableAdvancedNaviOptions", "Keyboard navigation key remapping. Use custom settings below for switching channels instead:", false, function(){
$('input[name^=setting-quickTabNavi]').prop('disabled',!$('input[name=setting-enableAdvancedNaviOptions]').prop('checked'));
});
Settings.addBool("quickTabNaviCtrlRequired", "Ctrl", true);
Settings.addBool("quickTabNaviShiftRequired", "Shift", false);
Settings.addBool("quickTabNaviAltRequired", "Alt", true);
Settings.addBool("quickTabNaviMetaRequired", "Meta", false);
Settings.addInput("quickTabNaviKeyLeft", "Key codes: Left = 37, Up = 38, Right = 39, Down = 40. See <a href='https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode' target='_blank'>Mozilla.org's documentation</a> for more key codes.<br><br>Navigate left tab final key code","37");
Settings.addInput("quickTabNaviKeyRight", "Navigate right tab final key code","39");
$('input[name^=setting-quickTabNavi]').prop('disabled',!settings.enableAdvancedNaviOptions);
$("#settingContent").append("<div class='robin-chat--sidebar-widget robin-chat--notification-widget'><label id='blockedUserContainer'>Muted Users (click to unmute)</label>");
$("#blockedUserContainer").append("<div id='blockedUserList' class='robin-chat--sidebar-widget robin-chat--user-list-widget'></div>");
$("#settingContent").append('<div class="robin-chat--sidebar-widget robin-chat--report" style="text-align:center;"><a target="_blank" href="https://www.reddit.com/r/parrot_script/">parrot v' + versionString + '</a></div>');
$('head').append('<style id="robinMessageVisiblity"></style>');
setRobinMessageVisibility();
// Options end
// Settings end
var timeStarted = new Date();
var name = $(".robin-chat--room-name").text();
var urlRegex = new RegExp(/(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?/ig);
var youtubeRegex = new RegExp(/.*(?:youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|watch\?(?:[a-zA-Z-_]+=[a-zA-Z0-9-_]+&)+v=)([^#\&\?]*).*/);
var list = {};
buildDropdown();
var isEndingSoon = false;
var endTime = null;
var endTimeAttempts = 0;
// Grab the timestamp from the time remaining message and then calc the ending time using the estimate it gives you
function getEndTime() { // mostly from /u/Yantrio, modified by /u/voltaek
endTimeAttempts++;
var remainingMessageContainer = $(".robin--user-class--system:contains('approx')");
if (remainingMessageContainer.length === 0) {
// for cases where it says "soon" instead of a time on page load
var endingSoonMessageContainer = $(".robin--user-class--system:contains('soon')");
if (endingSoonMessageContainer.length !== 0) {
isEndingSoon = true;
}
return null;
}
var message = $(".robin-message--message", remainingMessageContainer).text();
var time = new Date($(".robin-message--timestamp", remainingMessageContainer).attr("datetime"));
try {
return addMins(time, message.match(/\d+/)[0]);
} catch (e) {
return null;
}
}
endTime = getEndTime();
var lastStatisticsUpdate = 0;
function update() {
switch(settings.vote) {
case "abandon":
$(".robin-chat--vote.robin--vote-class--abandon:not('.robin--active')").click();
break;
case "stay":
$(".robin-chat--vote.robin--vote-class--continue:not('.robin--active')").click();
break;
case "grow":
$(".robin-chat--vote.robin--vote-class--increase:not('.robin--active')").click();
break;
default:
$(".robin-chat--vote.robin--vote-class--increase:not('.robin--active')").click();
break;
}
if (endTime !== null || isEndingSoon) {
$(".timeleft").text(isEndingSoon ? "waiting to merge" : formatNumber(howLongLeft(endTime)) + " minutes remaining");
}
else if (endTimeAttempts <= 3 && endTime === null) {
$("#robinVoteWidget .timeleft").parent().hide();
endTime = getEndTime();
if (endTime !== null || isEndingSoon) {
$("#robinVoteWidget .timeleft").parent().show();
}
}
var users = 0;
$.get("/robin/", function(a) {
var START_TOKEN = "<script type=\"text/javascript\" id=\"config\">r.setup(";
var END_TOKEN = ")</script>";
var start = a.substring(a.indexOf(START_TOKEN)+START_TOKEN.length);
var end = start.substring(0,start.indexOf(END_TOKEN));
config = JSON.parse(end);
list = config.robin_user_list;
var counts = list.reduce(function(counts, voter) {
counts[voter.vote] += 1;
return counts;
}, {
INCREASE: 0,
ABANDON: 0,
NOVOTE: 0,
CONTINUE: 0
});
var GROW_STR = formatNumber(counts.INCREASE);
var ABANDON_STR = formatNumber(counts.ABANDON);
var NOVOTE_STR = formatNumber(counts.NOVOTE);
var STAY_STR = formatNumber(counts.CONTINUE);
$robinVoteWidget.find('.robin--vote-class--increase .robin-chat--vote-label').html('grow<br>(' + GROW_STR + ')');
$robinVoteWidget.find('.robin--vote-class--abandon .robin-chat--vote-label').html('abandon<br>(' + ABANDON_STR + ')');
$robinVoteWidget.find('.robin--vote-class--novote .robin-chat--vote-label').html('no vote<br>(' + NOVOTE_STR + ')');
$robinVoteWidget.find('.robin--vote-class--continue .robin-chat--vote-label').html('stay<br>(' + STAY_STR + ')');
users = list.length;
$(".usercount").text(formatNumber(users) + " users in chat");
currentTime = Math.floor(Date.now()/1000);
// if(settings.reportStats && (currentTime-lastStatisticsUpdate)>=parseInt(settings.statReportingInterval))
// #yolo-robin till April 8th
if((currentTime-lastStatisticsUpdate)>=parseInt(settings.statReportingInterval))
{
lastStatisticsUpdate = currentTime;
// Report statistics to the automated leaderboard
trackers = [
"https://monstrouspeace.com/robintracker/track.php"
];
queryString = "?id=" + config.robin_room_name.substr(0,10) +
"&guid=" + config.robin_room_id +
"&ab=" + counts.ABANDON +
"&st=" + counts.CONTINUE +
"&gr=" + counts.INCREASE +
"&nv=" + counts.NOVOTE +
"&count=" + users +
"&ft=" + Math.floor(config.robin_room_date / 1000) +
"&rt=" + Math.floor(config.robin_room_reap_time / 1000);
trackers.forEach(function(tracker){
$.get(tracker + queryString);
});
}
var $chatstats = $("#chatstats");
if(settings.hideVote){
$chatstats.text("GROW: " + GROW_STR + " (" + (counts.INCREASE / users * 100).toFixed(0) + "%) STAY: " + STAY_STR + " (" + (counts.CONTINUE / users * 100).toFixed(0) + "%)");
$chatstats.show();
} else {
$chatstats.hide();
}
});
var lastChatString = $(".robin-message--timestamp").last().attr("datetime");
var timeSinceLastChat = new Date() - (new Date(lastChatString));
var now = new Date();
if (timeSinceLastChat !== undefined && (timeSinceLastChat > 600000 && now - timeStarted > 600000)) {
if (settings.timeoutEnabled)
window.location.reload(); // reload if we haven't seen any activity in a minute.
}
// Try to join if not currently in a chat
if ($("#joinRobinContainer").length) {
$("#joinRobinContainer").click();
setTimeout(function() {
$("#joinRobin").click();
}, 1000);
}
}
// hash string so finding spam doesn't take up too much memory
function hashString(str) {
var hash = 0;
if (str != 0) {
for (i = 0; i < str.length; i++) {
char = str.charCodeAt(i);
if (str.charCodeAt(i) > 0x40) { // Let's try to not include the number in the hash in order to filter bots
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
}
}
return hash;
}
// Searches through all messages to find and hide spam
var spamCounts = {};
function findAndHideSpam() {
// getChannelTab
var len = channelList.length;
while(len-- > -1) {
//var $messages = getChannelTab(len).find(".robin-message");
var $messages = getChannelMessageList(len).find(".robin-message");
var maxprune = parseInt(settings.maxprune || "1000", 10);
if (isNaN(maxprune)) {
maxprune = 1000;
}
if ( maxprune <= 0) {
maxprune = 1;
}
//console.log("maxprune: " + maxprune + " Messages.length: " + $messages.length + " len: " + len) ;
if ($messages.length > maxprune) {
$messages.slice(0, $messages.length - maxprune).remove();
}
}
if (false && settings.findAndHideSpam) {
// skips over ones that have been hidden during this run of the loop
$('.robin--user-class--user .robin-message--message:not(.addon--hide)').each(function() {
var $this = $(this);
var hash = hashString($this.text());
var user = $('.robin-message--from', $this.closest('.robin-message')).text();
if (!(user in spamCounts)) {
spamCounts[user] = {};
}
if (hash in spamCounts[user]) {
spamCounts[user][hash].count++;
spamCounts[user][hash].elements.push(this);
} else {
spamCounts[user][hash] = {
count: 1,
text: $this.text(),
elements: [this]
};
}
$this = null;
});
$.each(spamCounts, function(user, messages) {
$.each(messages, function(hash, message) {
if (message.count >= 3) {
$.each(message.elements, function(index, element) {
$(element).closest('.robin-message').addClass('addon--hide').remove();
});
} else {
message.count = 0;
}
message.elements = [];
});
});
}
}
// faster to save this in memory
/* Detects unicode spam - Credit to travelton
* https://gist.github.com/travelton */
var UNICODE_SPAM_RE = /[\u0080-\uFFFF]/;
function isBotSpam(text) {
// starts with a [, has "Autovoter", or is a vote
var filter = text.indexOf("[") === 0 ||
text == "voted to STAY" ||
text == "voted to GROW" ||
text == "voted to ABANDON" ||
text.indexOf("Autovoter") > -1 ||
(!settings['enableUnicode'] && UNICODE_SPAM_RE.test(text));
var spamFilters = settings.spamFilters.split(",").map(function(filter) { return filter.trim().toLowerCase(); });
spamFilters.forEach(function(filterVal) {
filter = filter || filterVal.length > 0 && text.toLowerCase().indexOf(filterVal) >= 0;
});
// if(filter)console.log("removing "+text);
return filter;
}
// Individual mute button /u/verox-
var mutedList = settings.mutedUsersList || [];
$('body').on('click', ".robin--username", function() {
var username = String($(this).text()).trim();
var clickedUser = mutedList.indexOf(username);
var $userNames = $(".robin--username:contains(" + username + ")");
if (clickedUser == -1) {
// Mute our user.
mutedList.push(username);
$userNames.css({textDecoration: "line-through"});
} else {
// Unmute our user.
$userNames.css({textDecoration: "none"});
mutedList.splice(clickedUser, 1);
}
settings.mutedUsersList = mutedList;
Settings.save(settings);
listMutedUsers();
});
// Copy cliked username into textarea /u/tW4r based on /u/verox-'s Individual mute button
$('body').on('contextmenu', ".robin--username", function (event) {
// Prevent context-menu from showing up
event.preventDefault();
// Get clicked username and previuos input source
var username = String($(this).text()).trim();