-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathrlcs.user.js
3115 lines (2702 loc) · 207 KB
/
rlcs.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 RLC
// @version 3.22.2
// @description Chat-like functionality for Reddit Live
// @author FatherDerp & Stjerneklar
// @contributor Kretenkobr2, thybag, mofosyne, jhon, FlamingObsidian, MrSpicyWeiner, TheVarmari, dashed
// @website https://github.com/BNolet/RLC/
// @namespace http://tampermonkey.net/
// @include https://www.reddit.com/live/*
// @exclude https://www.reddit.com/live/
// @exclude https://www.reddit.com/live
// @exclude https://www.reddit.com/live/*/edit*
// @exclude https://www.reddit.com/live/*/contributors*
// @exclude https://*.reddit.com/live/create*
// @require https://code.jquery.com/jquery-2.2.3.min.js
// @grant GM_addStyle
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_getResourceText
// @grant GM_deleteValue
// @grant GM_listValues
// @run-at document-idle
// @noframes
// ==/UserScript==
// ██████╗ ██╗ ██████╗ ██╗███╗ ██╗████████╗██████╗ ██████╗
// ██╔══██╗██║ ██╔════╝ ██║████╗ ██║╚══██╔══╝██╔══██╗██╔═══██╗
// ██████╔╝██║ ██║ ██║██╔██╗ ██║ ██║ ██████╔╝██║ ██║
// ██╔══██╗██║ ██║ ██║██║╚██╗██║ ██║ ██╔══██╗██║ ██║
// ██║ ██║███████╗╚██████╗ ██║██║ ╚████║ ██║ ██║ ██║╚██████╔╝
// ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝
// Welcome to Reddit Live Chat source code, enjoy your visit.
// Please group your variables with the relevant functions and follow existing structure.
// (Unless you are willing to rewrite the structure into something more sane)
// To get a good idea of whats going on, start from window.load near the bottom.
// I recommend using Sublime Text when browsing this file as these comment blocks are readable from the minimap.
// - Stjerneklar
// ██████╗ ██╗ ██████╗ ██████╗ ██████╗ ████████╗██╗ ██████╗ ███╗ ██╗███████╗
// ██╔══██╗██║ ██╔════╝ ██╔═══██╗██╔══██╗╚══██╔══╝██║██╔═══██╗████╗ ██║██╔════╝
// ██████╔╝██║ ██║ ██║ ██║██████╔╝ ██║ ██║██║ ██║██╔██╗ ██║███████╗
// ██╔══██╗██║ ██║ ██║ ██║██╔═══╝ ██║ ██║██║ ██║██║╚██╗██║╚════██║
// ██║ ██║███████╗╚██████╗ ╚██████╔╝██║ ██║ ██║╚██████╔╝██║ ╚████║███████║
// ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝
//
// Calls createOption to set up lables, GM values and body classes based on stored GM values if set.
//
// Create persistant option
function createOption(name, clickAction, defaultState, description){
var checkedMarkup;
var key = "rlc-" + name.replace(/\W/g, "");
var state = (typeof defaultState !== "undefined") ? defaultState : false;
// Add if not exist in optionsArray
if ( !(key in optionsArray) ){
optionsArray.push(key);
}
// Try and state if setting is defined
if (GM_getValue(key)){
state = GM_getValue(key);
}
// Markup for state
checkedMarkup = state ? "checked='checked'" : "";
// sorry, im nub
if (description === undefined) {
description = "";
}
// Render option
var $option = $(`<label id='option-${key}'><input type='checkbox' ${checkedMarkup}>${name}<span>${description}</span></label>`).click(function(e){
// capture only checkbox's event
var target = $( e.target );
if ( !target.is( "input" ) ) {
return;
}
var checked = $(this).find("input").is(":checked");
//console.log("option set to "+checked);
// Persist state
if (checked !== state){
GM_setValue(key, checked);
state = checked;
}
clickAction(checked, $(this));
});
// Add to DOM
$("#rlc-settings").append($option);
clickAction(state, $option);
//uncomment below to output option key/value
//console.log(key+" = "+state);
}
function setCustomBg() {
// avoid triggering during init
if (loadHistoryMessageException != 1) {
var bgurlsuggestion; //try to get a saved background url depending on dark mode setting
if (GM_getValue("rlc-DarkMode")) { bgurlsuggestion = GM_getValue("customBGdark")}
else { bgurlsuggestion = GM_getValue("customBGlight");}
// if we cant, use the sample url
if (typeof bgurlsuggestion === "undefined" ) {
bgurlsuggestion = "http://i.imgur.com/uy50nCx.jpg";
}
var bgurl = prompt("enter background url", bgurlsuggestion); //prompt user for url with default or saved url suggested
if (bgurl != null) { //if the user filled out the prompt
$("#customBGstyle").remove(); //clear existing background style tag set in 248 or 251
//save bgurl to seperate variables depending on light/dark mode
if (GM_getValue("rlc-DarkMode")) { GM_setValue("customBGdark",bgurl)}
else { GM_setValue("customBGlight",bgurl) }
var bgimagecss = `body {background-image: url(${bgurl})!important;` //build css rule
$("body").append(`<style id='customBGstyle'>${bgimagecss}</style>`); //append style tag with css rule
}
}
else {
//same as above but without the prompt. this code runs on init if option is enabled
var bgurl;
if (GM_getValue("rlc-DarkMode")) { bgurl = GM_getValue("customBGdark")}
else { bgurl = GM_getValue("customBGlight");}
if (typeof bgurl === "undefined" ) {
bgurl = "http://i.imgur.com/uy50nCx.jpg";
}
var bgimagecss = `body {background-image: url(${bgurl})!important;` //build css rule
$("body").append(`<style id='customBGstyle'>${bgimagecss}</style>`); //append style tag with css rule
}
}
function createOptions() {
// set default states(on first load of RLC, otherwise presists via GM/TM local variables)
// ONLY NEEEDED FOR DEFAULT TRUE
if (GM_getValue("rlc-ChannelColors")===undefined) { GM_setValue("rlc-ChannelColors", true);}
if (GM_getValue("rlc-AutoScroll")===undefined) { GM_setValue("rlc-AutoScroll", true);}
if (GM_getValue("rlc-FullSize")===undefined) { GM_setValue("rlc-FullSize", true);}
if (GM_getValue("rlc-ShowChannelsUI")===undefined) { GM_setValue("rlc-ShowChannelsUI", true);}
// Format: name, function, state, description(optional)
createOption("Full Size", function(checked){
if (checked){
$("body").addClass("rlc-fullwidth");
} else {
$("body").removeClass("rlc-fullwidth");
}
scrollToBottom();
},false, "remove RLC max width/height");
createOption("Dark Mode", function(checked){
if (loadHistoryMessageException != 1) { refreshChat(); }
if (checked){
$("body").addClass("dark-background");
} else {
$("body").removeClass("dark-background");
}
},false);
createOption("Robin Colors", function(checked){
if (loadHistoryMessageException != 1) { refreshChat(); }
},false, "color usernames via robin algorithm (existing messages are not modified)");
createOption("Compact Mode", function(checked){
if (checked){
$("body").addClass("rlc-compact");
} else {
$("body").removeClass("rlc-compact");
}
scrollToBottom();
},false, "hide header");
createOption("Left Panel", function(checked){
if (checked){
$("body").addClass("rlc-leftPanel");
} else {
$("body").removeClass("rlc-leftPanel");
}
scrollToBottom();
},false, "hide header");
createOption("Channel Colors", function(checked){
if (checked){
$("#rlc-main").addClass("show-colors");
} else {
$("#rlc-main").removeClass("show-colors");
}
},false, "give channels background colors");
createOption("Show Channels UI", function(checked){
if (checked){
$("body").addClass("rlc-showChannelsUI");
} else {
$("body").removeClass("rlc-showChannelsUI");
}
},false,"show channel tabs and message channel selector");
createOption("Channel Message Counters", function(checked){
},false,"show counters for messages in tabs");
createOption("12 Hour Mode", function(checked){
if (loadHistoryMessageException != 1) { refreshChat(); }
},false,"12 Hour Time Stamps");
createOption("Seconds Mode", function(checked){
if (loadHistoryMessageException != 1) { refreshChat(); }
if (checked){
$("body").addClass("rlc-secondsMode");
} else {
$("body").removeClass("rlc-secondsMode");
}
},false,"Time Stamps with Seconds");
createOption("Hide Channels in Global", function(checked){
if (checked){
$("body").addClass("rlc-hideChannelsInGlobal");
} else {
if (loadHistoryMessageException != 1) { refreshChat(); }
$("body").removeClass("rlc-hideChannelsInGlobal");
}
},false, "hide in-channel messages in global tab (the channel must added for this to work)");
createOption("Notification Sound", function(checked){
},false, "play sound when you are mentioned");
createOption("Chrome Notifications", function(checked){
if (checked && Notification && !Notification.permission !== "granted"){
Notification.requestPermission();
}
},false, "show notice when you are mentioned");
createOption("All Notifications when unfocused", function(checked){
},false, "show notice on any message if window is not focused");
createOption("Chrome Scroll Bars", function(checked){
if (checked){
$("body").addClass("rlc-customscrollbars");
} else {
$("body").removeClass("rlc-customscrollbars");
}
},false, "use custom scrollbars");
createOption("Text To Speech (TTS)", function(checked){
if (checked){
$("body").addClass("rlc-TextToSpeech");
$("#togglebarTTS").addClass("selected");
} else {
$("body").removeClass("rlc-TextToSpeech");
$("#togglebarTTS").removeClass("selected");
window.speechSynthesis && window.speechSynthesis.cancel && window.speechSynthesis.cancel();
}
},false, "read messages aloud");
createOption("TTS Username Narration", function(checked){
},false, "example: [message] said [name]");
createOption("TTS Disable User-based Voices", function(checked){
},false, "do not modify TTS voices based on usernames");
createOption("TTS Disable Self-narration", function(checked){
},false, "don't read messages sent by me aloud");
createOption("Auto Scroll", function(checked){
if (checked){
$("#togglebarAutoscroll").addClass("selected");
$("body").addClass("AutoScroll");
} else {
$("#togglebarAutoscroll").removeClass("selected");
$("body").removeClass("AutoScroll");
}
},false, "scroll chat on new message");
createOption("No Emotes", function(checked){
if (loadHistoryMessageException != 1) { refreshChat(); }
},false, "disable RLC smileys");
createOption("No Twitch Emotes", function(checked){
if (loadHistoryMessageException != 1) { refreshChat(); }
},false, "disable Twitch Emotes");
createOption("Hide Giphy Images", function(checked){
if (loadHistoryMessageException != 1) { refreshChat(); }
},false, "disable giphy gifs");
createOption("Disable Markdown", function(checked){
if (loadHistoryMessageException != 1) { refreshChat(); }
},false, "get messages without reddit formatting");
createOption("Max Messages 25", function(checked){
if (checked){
if (loadHistoryMessageException != 1) {
cropMessages(25);
}
}
},false, "do not show more than 25 messages");
createOption("Custom Background", function(checked){
if (checked === true){
$("body").addClass("rlc-customBg");
setCustomBg();
}
else {
$("body").removeClass("rlc-customBg");
$("#customBGstyle").remove(); //clear existing background style tag set in 248 or 251
}
},false, "sample image works best in dark mode");
createOption("No Message Removal", function(checked){
},false, "don't remove messages ever");
}
// ████████╗ █████╗ ██████╗ ██████╗ ███████╗██████╗ ██████╗██╗ ██╗ █████╗ ███╗ ██╗███╗ ██╗███████╗██╗ ███████╗
// ╚══██╔══╝██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗ ██╔════╝██║ ██║██╔══██╗████╗ ██║████╗ ██║██╔════╝██║ ██╔════╝
// ██║ ███████║██████╔╝██████╔╝█████╗ ██║ ██║ ██║ ███████║███████║██╔██╗ ██║██╔██╗ ██║█████╗ ██║ ███████╗
// ██║ ██╔══██║██╔══██╗██╔══██╗██╔══╝ ██║ ██║ ██║ ██╔══██║██╔══██║██║╚██╗██║██║╚██╗██║██╔══╝ ██║ ╚════██║
// ██║ ██║ ██║██████╔╝██████╔╝███████╗██████╔╝ ╚██████╗██║ ██║██║ ██║██║ ╚████║██║ ╚████║███████╗███████╗███████║
// ╚═╝ ╚═╝ ╚═╝╚═════╝ ╚═════╝ ╚══════╝╚═════╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═══╝╚══════╝╚══════╝╚══════╝
var tabbedChannels = new function(){
/* Basic usage - tabbedChannels.init( dom_node_to_add_tabs_to );
and hook up tabbedChannels.proccessLine(lower_case_text, jquery_of_line_container);
to each line detected by the system */
var _self = this;
// Default options
this.channels = ["%general", "%offtopic","%dev"];
this.mode = "single";
// internals
this.unreadCounts = {};
this.$el = null;
this.$opt = null;
this.defaultRoomClasses = "";
this.channelMatchingCache = [];
//channels user is in currently
this.currentRooms = 0;
// When channel is clicked, toggle it on or off
this.toggleChannel = function(e){
var channel = $(e.target).data("filter");
if (channel===null)return; // no a channel
if (!$("#rlc-chat").hasClass("rlc-filter-" + channel)){
_self.enableChannel(channel);
$(e.target).addClass("selected");
// clear unread counter
$(e.target).find("span").text(0);
_self.unreadCounts[channel] = 0;
} else {
_self.disableChannel(channel);
$(e.target).removeClass("selected");
}
// scroll everything correctly
scrollToBottom();
};
// Enable a channel
this.enableChannel = function(channelID){
// if using room type "single", deslect other rooms on change
if (this.mode === "single"){
this.disableAllChannels();
}
$("#rlc-chat").addClass("rlc-filter rlc-filter-" + channelID);
$("#rlc-chat").attr("data-channel-key", this.channels[channelID]);
this.currentRooms++;
// unselect show all
_self.$el.find("span.all").removeClass("selected");
};
// disable a channel
this.disableChannel = function(channelID){
$("#rlc-chat").removeClass("rlc-filter-" + channelID);
this.currentRooms--;
// no rooms selcted, run "show all"
if (this.currentRooms === 0){
this.disableAllChannels();
} else {
// Grab next channel name if u leave a room in multi mode
$("#rlc-chat").attr("data-channel-key", $(".rlc-filters span.selected").first().data("filter-name"));
}
};
// turn all channels off
this.disableAllChannels = function(){
$("#rlc-chat").attr("class", _self.defaultRoomClasses).attr("data-channel-key", "");
_self.$el.find(".rlc-filters > span").removeClass("selected");
this.currentRooms = 0;
_self.$el.find("span.all").addClass("selected");
scrollToBottom();
};
// render tabs
this.drawTabs = function(){
var html = "";
$("#rlc-channel-dropdown").empty();
$("#rlc-channel-dropdown").append("<option></option>")
for(var i in this.channels){
if (typeof this.channels[i] === "undefined") continue;
html += `<span data-filter="${i}" data-filter-name="${this.channels[i]}">${this.channels[i]}(<span>0</span>)</span> `;
$("#rlc-channel-dropdown").append(`<option>${this.channels[i]}</option>`)
}
this.$el.find(".rlc-filters").html(html);
};
// After creation of a new channel, go find if any content (not matched by a channel already) is relevant
this.reScanChannels = function(){
$("#rlc-chat").find("li.rlc-message").each(function(idx,item){
var line = $(item).find(".body .md").text().toLowerCase();
tabbedChannels.proccessLine(line, $(item), true);
});
};
// Add new channel
this.addChannel = function(newChannel){
if (this.channels.indexOf(newChannel) === -1){
this.channels.push(newChannel);
this.unreadCounts[this.channels.length-1] = 0;
this.updateChannelMatchCache();
this.saveChannelList();
this.drawTabs();
// Populate content for channel
this.reScanChannels();
// refresh everything after redraw
this.disableAllChannels();
}
};
// remove existing channel
this.removeChannel = function(channel){
if (confirm("are you sure you wish to remove the " + channel + " channel?")){
var idx = this.channels.indexOf(channel);
delete this.channels[idx];
this.updateChannelMatchCache();
this.saveChannelList();
this.drawTabs();
// sub channels, will fall back to existing channels
this.reScanChannels();
// refresh everything after redraw
this.disableAllChannels();
}
};
// save channel list
this.saveChannelList = function(){
// clean array before save
var channels = this.channels.filter(function (item) { return item !== undefined; });
GM_setValue("rlc-channels", channels);
};
// Change chat mode
this.changeChannelMode = function(){
_self.mode = $(this).data("type");
// swicth bolding
$(this).parent().find("span").css("font-weight", "normal");
$(this).css("font-weight", "bold");
_self.disableAllChannels();
// Update mode setting
GM_setValue("rlc-mode", _self.mode);
};
this.updateChannelMatchCache = function(){
var order = this.channels.slice(0);
order.sort(function(a, b){
return b.length - a.length; // ASC -> a - b; DESC -> b - a
});
for(var i in order){
order[i] = this.channels.indexOf(order[i]);
}
// sorted array of channel name indexs
this.channelMatchingCache = order;
};
// Procces each chat line to create text
this.proccessLine = function(text, $elment, rescan){
var i, idx, channel;
// If rescanning, clear any existing "channel" classes
if (typeof rescan !== "undefined" && rescan === true){
$elment.removeClass("in-channel");
for(i=0; i <= this.channels.length; i++){
$elment.removeClass("rlc-filter-" + i);
}
}
// Scan for channel identifiers
for(i=0; i< this.channelMatchingCache.length; i++){ // Sorted so longer get picked out before shorter ones (sub channel matching)
idx = this.channelMatchingCache[i];
channel = this.channels[idx];
if (typeof channel === "undefined") continue;
// Handle channel prefix in message
if (text.indexOf(channel) === 0){
$elment.find(".body").append(`<a class='channelname'> in ${channel}</a>`);
$elment.addClass(`rlc-filter-${idx} in-channel`);
this.unreadCounts[idx]++;
// Remove channel name in messages
var newele = $elment.find(".body .md p").html().replace(channel, "");
$elment.find(".body .md p").html(newele);
if ($elment.find(".body .md p").html().indexOf("/me") === 0){
$elment.addClass("user-narration");
$elment.find(".body .md p").html($elment.find(".body .md p").html().replace("/me", " " + $elment.find(".author").html()));
}
return;
}
}
};
// If in one channel, auto add channel keys
this.submitHelper = function(){
if ($("#rlc-chat").hasClass("rlc-filter")){
// Auto add channel key
let channelKey = $("#rlc-chat").attr("data-channel-key");
if ($("#new-update-form textarea").val().indexOf("/me") === 0){
$("#new-update-form textarea").val(channelKey + "/me " + $("#new-update-form textarea").val().substr(3));
} else if ($("#new-update-form textarea").val().indexOf("/") !== 0){
// If it's not a "/" command, add channel
$("#new-update-form textarea").val(channelKey + " " + $("#new-update-form textarea").val());
}
}
// else read from dropdown populated by channels
else {
let channelKey = $("#rlc-channel-dropdown option:selected" ).text();
if (channelKey !== "") {
if ($("#new-update-form textarea").val().indexOf("/me") === 0){
$("#new-update-form textarea").val(channelKey + "/me " + $("#new-update-form textarea").val().substr(3));
} else if ($("#new-update-form textarea").val().indexOf("/") !== 0){
// If it's not a "/" command, add channel
$("#new-update-form textarea").val(channelKey + " " + $("#new-update-form textarea").val());
}
}
}
};
// Update channel message counts
this.tick = function(){
_self.$el.find(".rlc-filters span").each(function(){
if ($(this).hasClass("selected")) return;
$(this).find("span").text(_self.unreadCounts[$(this).data("filter")]);
});
};
// Init tab zone
this.init = function($el){
// Load channels
if (GM_getValue("rlc-channels")){
this.channels = GM_getValue("rlc-channels");
}
if (GM_getValue("rlc-mode")){
this.mode = GM_getValue("rlc-mode");
}
// Init counters
for(var i in this.channels){
this.unreadCounts[i] = 0;
}
// Update channel cache
this.updateChannelMatchCache();
this.$el = $el;
// Create inital markup
this.$el.html("<span class='all selected'>Global</span><span><div class='rlc-filters'></div></span><span class='more'>[Channels]</span>");
this.$opt = $("<div class='rlc-channel-add' style='display:none'><input name='add-channel'><button>Add channel</button> <span class='channel-mode'>Channel Mode: <span title='View one channel at a time' data-type='single'>Single</span> | <span title='View many channels at once' data-type='multi'>Multi</span></span></div>").insertAfter(this.$el);
// Attach events
this.$el.find(".rlc-filters").click(this.toggleChannel);
this.$el.find("span.all").click(this.disableAllChannels);
this.$el.find("span.more").click(function(){ $(".rlc-channel-add").toggle(); $("body").toggleClass("rlc-addchanmenu"); });
this.$el.find(".rlc-filters").bind("contextmenu", function(e){
e.preventDefault();
e.stopPropagation();
var chanID = $(e.target).data("filter");
if (chanID===null)return; // no a channel
_self.removeChannel(_self.channels[chanID]);
});
// Form events
this.$opt.find(".channel-mode span").click(this.changeChannelMode);
this.$opt.find("button").click(function(){
var newChan = _self.$opt.find("input[name='add-channel']").val();
if (newChan !== "") _self.addChannel(newChan);
_self.$opt.find("input[name='add-channel']").val("");
});
$(".save-button .btn").click(this.submitHelper);
// Store default room class
this.defaultRoomClasses = $("#rlc-chat").attr("class") ? $("#rlc-chat").attr("class") : "";
// Redraw tabs
this.drawTabs();
// Start tab message number ticker if enabled
if (GM_getValue("rlc-ChannelMessageCounters")){
setInterval(this.tick, 2000);
}
};
}();
// Channel Colours for tabbed channels
var colors = ["rgba(255,0,0,0.1)", "rgba(0,255,0,0.1)", "rgba(0,0,255,0.1)", "rgba(0,255,255,0.1)", "rgba(255,0,255,0.1)", "rgba(255,255,0,0.1)", "rgba(211,211,211, .1)", "rgba(0,100,0, .1)", "rgba(255,20,147, .1)", "rgba(184,134,11, .1)"];
var color;
var colorcollection = "";
for(var c = 0; c < 10; c++){ // c reduced from 35
color = colors[(c % (colors.length))];
colorcollection = colorcollection + `#rlc-main.show-colors #rlc-chat li.rlc-message.rlc-filter-${c} { background: ${color};}`;
colorcollection = colorcollection + `#rlc-chat.rlc-filter.rlc-filter-${c} li.rlc-message.rlc-filter-${c} { display:block;}`;
}
GM_addStyle(colorcollection);
// ██╗ ██╗██╗ ██╗███████╗ █████╗ ██████╗ ██╗ ██╗ ██╗███████╗██████╗ ███████╗ ██████╗ ██████╗██╗ ██╗███████╗████████╗
// ██║ ██║██║ ██║██╔════╝ ██╔══██╗██╔══██╗██║ ██║ ██║██╔════╝██╔══██╗██╔════╝██╔═══██╗██╔════╝██║ ██╔╝██╔════╝╚══██╔══╝
// ██║ ██║██║ ██║█████╗ ███████║██████╔╝██║ ██║ █╗ ██║█████╗ ██████╔╝███████╗██║ ██║██║ █████╔╝ █████╗ ██║
// ██║ ██║╚██╗ ██╔╝██╔══╝ ██╔══██║██╔═══╝ ██║ ██║███╗██║██╔══╝ ██╔══██╗╚════██║██║ ██║██║ ██╔═██╗ ██╔══╝ ██║
// ███████╗██║ ╚████╔╝ ███████╗ ██║ ██║██║ ██║ ╚███╔███╔╝███████╗██████╔╝███████║╚██████╔╝╚██████╗██║ ██╗███████╗ ██║
// ╚══════╝╚═╝ ╚═══╝ ╚══════╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚══╝╚══╝ ╚══════╝╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝╚══════╝ ╚═╝
// used to make sure that the url we use to connect the websocket does not end in a slash.
function stripTrailingSlash(str) {
if(str.substr(-1) === '/') {
return str.substr(0, str.length - 1);
}
return str;
}
/* connectionTimer & incConTimer track how long time has passed since last websocket activity and notifies the user
if more than 2 minutes have passed without activity, as this is taken as a disconnect. */
var connectionTimer = 0;
function incConTimer() {
connectionTimer = connectionTimer + 1;
if (connectionTimer > 2) {
location.reload();
}
}
setInterval(incConTimer, 60000);
+function(){
$.getJSON(stripTrailingSlash(window.location.href) + "/about.json", function(data) {
var websocket_url = data.data.websocket_url;
var ws = new WebSocket(websocket_url);
ws.onmessage = function (evt) {
// Ensure data has data
if(!data.hasOwnProperty('data'))
{
console.log("Help me Obi-Wan Kenobi. We got empty data!");
return;
}
var msg = JSON.parse(evt.data);
connectionTimer = 0; // connection timer is reset on any activity that has data
switch(msg.type) {
case 'update':
var payload = msg.payload.data;
// See messageFaker function for how messages from json are turned into rlc-messages
$(".rlc-message-listing").prepend(messageFaker(payload));
break;
/* disabled, liveupdate header already tracks this
case 'activity':
var payload = msg.payload;
console.log('user count from websocket:', payload.count);
break;
*/
case 'delete':
if(!GM_getValue("rlc-NoMessageRemoval")) {
console.log("message deleted:"+msg.payload);
var messageToDelete = "rlc-id-"+msg.payload;
$( "li[name='"+messageToDelete+"']" ).remove();
reAlternate();
}
break;
/* embeds_ready - a previously posted update has
been parsed and embedded media is available for it now.
the payload contains a liveupdate_id and list of embeds to add to it.*/
case 'embeds_ready':
console.log(msg.payload.liveupdate_id);
var messageToMark = "rlc-id-"+msg.payload.liveupdate_id;
$( "li[name='"+messageToMark+"']" ).addClass("rlc-hasEmbed");
break;
}
};
});
}();
// ██████╗ ███████╗████████╗ ███╗ ███╗███████╗███████╗███████╗███████╗ █████╗ ██████╗ ███████╗███████╗
// ██╔════╝ ██╔════╝╚══██╔══╝ ████╗ ████║██╔════╝██╔════╝██╔════╝██╔════╝██╔══██╗██╔════╝ ██╔════╝██╔════╝
// ██║ ███╗█████╗ ██║ ██╔████╔██║█████╗ ███████╗███████╗███████╗███████║██║ ███╗█████╗ ███████╗
// ██║ ██║██╔══╝ ██║ ██║╚██╔╝██║██╔══╝ ╚════██║╚════██║╚════██║██╔══██║██║ ██║██╔══╝ ╚════██║
// ╚██████╔╝███████╗ ██║ ██║ ╚═╝ ██║███████╗███████║███████║███████║██║ ██║╚██████╔╝███████╗███████║
// ╚═════╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚══════╝
function getContributors() {
var urlToGet = stripTrailingSlash(window.location.href) + "/contributors.json";
var ajaxLoadUsers = $.getJSON( urlToGet, function( data ) {
var userdata = data[0].data.children;
$.each( userdata, function( ) {
console.log($(this));
console.log($(this)[0].name);
console.log($(this)[0].permissions);
});
});
ajaxLoadUsers.complete(function() {
});
}
function getMessages(gettingOld) {
loadHistoryMessageException = 1;
var urlToGet = stripTrailingSlash(window.location.href) + "/.json";
if (gettingOld) {
var lastMessage = $(".rlc-message:last-child");
if(lastMessage.length !== 1) { console.log("nolastmessage");}
else {
urlToGet += "?after="+$(".rlc-message:last-child").attr("name").split("rlc-id-")[1];
}
}
var ajaxLoadOldMessages = $.getJSON( urlToGet, function( data ) {
// Ensure data has data
if(!data.hasOwnProperty('data'))
{
console.log("Help me Obi-Wan Kenobi. We got empty data!");
return;
}
var oldmessages = data.data.children; //navigate the data to the object containing the messages
$.each( oldmessages, function( ) {
var msg = $(this).toArray()[0].data; //navigate to the message data level we want
// See messageFaker function for how messages from json are turned into rlc-messages
$(".rlc-message-listing").append(messageFaker(msg));
});
});
ajaxLoadOldMessages.complete(function() {
loadHistoryMessageException = 0;
reAlternate();
});
}
function messageFaker(msg) {
var msgID = msg.name;
var $msgbody = msg.body_html;
if (GM_getValue("rlc-DisableMarkdown")) {$msgbody + '<div class="md"><p>'+ msg.body +'</p></div>';}
// Unescaped html escaped string by way of crazy voodo magic.
$msgbody = $("<textarea/>").html($msgbody).val()
var usr = msg.author;
var utcSeconds = msg.created_utc;
// translate created_utc to a human readable version
var readAbleDate = new Date(0); // The 0 there is the key, which sets the date to the epoch
readAbleDate.setUTCSeconds(utcSeconds);
var hours = readAbleDate.getHours();
var minutes = ((readAbleDate.getMinutes() < 10)? '0' : '') + readAbleDate.getMinutes() ;
var seconds = readAbleDate.getSeconds().toString();
// if seconds is a single diget value, prefix it with a 0 (12:00:1 becomes 12:00:01)
if (seconds.length === 1) { seconds = "0" + seconds};
if (GM_getValue("rlc-12HourMode")) {
//it is pm if hours from 12 onwards
var suffix = (hours >= 12)? 'PM' : 'AM';
//only -12 from hours if it is greater than 12 (if not back at mid night)
hours = (hours > 12)? hours -12 : hours;
//if 00 then it is 12 am
hours = (hours === '00')? 12 : hours;
} else {
suffix = "";
}
if(GM_getValue("rlc-SecondsMode"))
{
finaltimestamp = hours.toString() + ":" + minutes.toString()+ ":" + seconds.toString() + " " + suffix;
}else var finaltimestamp = hours.toString() + ":" + minutes.toString() + " " + suffix;
var fakeMessage = `
<li class="rlc-message" name="rlc-id-${msgID}">
<div class="body">${$msgbody}
<div class="simpletime">${finaltimestamp}</div>
<a href="/user/${usr}" class="author">${usr}</a>
</div>
</li>`
return fakeMessage;
}
// ███╗ ███╗███████╗████████╗ █████╗ ███╗ ███╗███████╗ ██████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗████████╗███████╗
// ████╗ ████║██╔════╝╚══██╔══╝██╔══██╗ ████╗ ████║██╔════╝██╔════╝ ██╔════╝██║ ██║████╗ ██║██╔════╝╚══██╔══╝██╔════╝
// ██╔████╔██║█████╗ ██║ ███████║ ██╔████╔██║███████╗██║ ███╗ █████╗ ██║ ██║██╔██╗ ██║██║ ██║ ███████╗
// ██║╚██╔╝██║██╔══╝ ██║ ██╔══██║ ██║╚██╔╝██║╚════██║██║ ██║ ██╔══╝ ██║ ██║██║╚██╗██║██║ ██║ ╚════██║
// ██║ ╚═╝ ██║███████╗ ██║ ██║ ██║ ██║ ╚═╝ ██║███████║╚██████╔╝ ██║ ╚██████╔╝██║ ╚████║╚██████╗ ██║ ███████║
// ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚══════╝
// fix problems with message background alternation without reloading messages
function reAlternate(){
$('.rlc-message').removeClass('alt-bgcolor');
$('.rlc-message.muted').remove();
$('.rlc-message:odd').addClass('alt-bgcolor');
}
// called by the max messages option, removes any message with a number higher than the specified max.
// this is done by looping trough a list of all messages and for each message checking what number the message is in the list.
// if the message number in the list(referred to as its index) is heigher than the max number supplied, the message is removed.
function cropMessages(max) {
$( ".rlc-message" ).each(function( index ) {
if (index > max) {
$( this ).remove();
}
});
}
// Scroll chat to bottom in order to show the latest message
var scrollToBottom = function(){
if (GM_getValue("rlc-AutoScroll")){
$("#rlc-chat").scrollTop($("#rlc-chat")[0].scrollHeight);
}
};
// scroll to bottom on window resize
$( window ).resize(function() {
scrollToBottom();
});
// remove all messages and get the latest 25 messages via ajax
// used to redraw the chat after certain option changes or mute/unmute
function refreshChat() {
$(".rlc-message").remove();
getMessages();
updateUserListInterface();
}
// ████████╗███████╗██╗ ██╗████████╗ ████████╗ ██████╗ ███████╗██████╗ ███████╗███████╗ ██████╗██╗ ██╗
// ╚══██╔══╝██╔════╝╚██╗██╔╝╚══██╔══╝ ╚══██╔══╝██╔═══██╗ ██╔════╝██╔══██╗██╔════╝██╔════╝██╔════╝██║ ██║
// ██║ █████╗ ╚███╔╝ ██║ ██║ ██║ ██║ ███████╗██████╔╝█████╗ █████╗ ██║ ███████║
// ██║ ██╔══╝ ██╔██╗ ██║ ██║ ██║ ██║ ╚════██║██╔═══╝ ██╔══╝ ██╔══╝ ██║ ██╔══██║
// ██║ ███████╗██╔╝ ██╗ ██║ ██║ ╚██████╔╝ ███████║██║ ███████╗███████╗╚██████╗██║ ██║
// ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚══════╝╚══════╝ ╚═════╝╚═╝ ╚═╝
var digits = ["", "one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine ", "ten ", "eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ", "sixteen ", "seventeen ", "eighteen ", "nineteen "],
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
// Numbers to english words for TTS
function numberToEnglish (num) {
if ((num = num.toString()).length > 8) return "Overflow in numberToEnglish function.";
let n = ("000000000" + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
// NOTE: IF YOU REPLACE != with !== below, the numbers are read wrong
if (!n) return; var str = "";
str += (n[1] != 0) ? (digits[Number(n[1])] || tens[n[1][0]] + " " + digits[n[1][1]]) + "crore " : "";
str += (n[2] != 0) ? (digits[Number(n[2])] || tens[n[2][0]] + " " + digits[n[2][1]]) + "lakh " : "";
str += (n[3] != 0) ? (digits[Number(n[3])] || tens[n[3][0]] + " " + digits[n[3][1]]) + "thousand " : "";
str += (n[4] != 0) ? (digits[Number(n[4])] || tens[n[4][0]] + " " + digits[n[4][1]]) + "hundred " : "";
str += (n[5] != 0) ? ((str != "") ? "and " : "") + (digits[Number(n[5])] || tens[n[5][0]] + " " + digits[n[5][1]]) + " " : "";
return str.trim();
}
// Select Emoji to narration tone
var toneList = {
"smile": "smiling",
"evilsmile": "with an evil smile",
"angry": "angrily",
"frown": "while frowning",
"confused":"confusedly",
"disappointed": "in a disappointed tone",
"meh": "in a disinterested manner",
"shocked": "in shock",
"happy": "happily",
"sad": "looking sad",
"crying": "with tears in his eyes",
"wink": "while winking",
"bored": "boredly",
"annoyed": "expressing annoyance",
"xsmile": "with a grinning broadly",
"xsad": "very sadly",
"xhappy": "very happily",
"tongue": "while sticking out a tongue"
};
// Abbreviation Expansion (All keys must be in uppercase)
var replaceStrList = {
"AFAIK": "As Far As I Know",
"AFK": "Away From Keyboard",
"AKA": "Also Known As",
"ASAP": "As Soon As Possible",
"ATM": "At the moment",
"BRB": "Be right back",
"B8": "Bait",
"BTW": "By The Way",
"CYA": "See Ya",
"CBA": "Can't Be Arsed",
"DAFUQ": "The Fuck",
"DEF": "Definitely",
"DIY": "Do It Yourself",
"FTW": "For The Win",
"FK": "Fuck",
"FTFY": "Fixed That For You",
"FTFY2": "Fuck That, Fuck You",
"FFS": "For Fucks Sake",
"G2G": "Got To Go",
"GR8": "Great",
"GL": "Good Luck",
"GTFO": "Get The Fuck Out",
"HF": "Have Fun",
"IRL": "In Real Life",
"IIRC": "If I Recall Correctly",
"IKR": "I Know Right",
"IMO": "In My Opinion",
"IDK": "I don't know",
"JK": "Just Kidding",
"NVM": "Nevermind",
"N1": "Nice One",
"NP": "No problem",
"OFC": "Of Course",
"OMG": "Oh My God",
"PPL": "People",
"PLZ": "Please",
"PLS": "Please",
"RLY": "Really",
"RN": "Right Now",
"RTFM": "Read The Fucking Manual",
"HAATIVCALBE": "Hobbit's Awesome Abbreviation That Is Very Cool And Loved By Everyone",
"RLC": "Reddit Live Chat",
"SEC": "Second",
"STFU": "Shut The Fuck Up",
"SRSLY": "Seriously",
"SRY": "Sorry",