-
Notifications
You must be signed in to change notification settings - Fork 30
/
chat.js
2145 lines (1974 loc) · 73.3 KB
/
chat.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
/* global $, window, document */
import { KEYCODES, DATE_FORMATS, isKeyCode, GENERIFY_OPTIONS } from "./const";
import { debounce } from "throttle-debounce";
import moment from "moment";
import EventEmitter from "./emitter";
import ChatSource from "./source";
import ChatUser from "./user";
import ViewerState from "./viewerstate";
import { MessageBuilder, MessageTypes } from "./messages";
import {
ChatMenu,
ChatUserMenu,
ChatWhisperUsers,
ChatEmoteMenu,
ChatSettingsMenu,
ChatContextMenu,
ChatEmoteInfoMenu
} from "./menus";
import ChatAutoComplete from "./autocomplete";
import ChatInputHistory from "./history";
import ChatUserFocus from "./focus";
import ChatSpoiler from "./spoiler";
import ChatStore from "./store";
import UserFeatures from "./features";
import Settings from "./settings";
import ChatWindow from "./window";
import WhisperStore from "./whispers";
import notificationSound from "./notificationSound";
const regextime = /(\d+(?:\.\d*)?)([a-z]+)?/gi;
const regexsafe = /[\-\[\]\/{}()*+?.\\^$|]/g;
const nickmessageregex = /(?:(?:^|\s)@?)([a-zA-Z0-9_]{3,20})(?=$|\s|[.?!,])/g;
const nickregex = /^[a-zA-Z0-9_]{3,20}$/;
const nsfwnsfl = new RegExp(`\\b(?:NSFL|NSFW)\\b`, "i");
const tagcolors = [
"green",
"yellow",
"orange",
"red",
"purple",
"blue",
"sky",
"lime",
"pink",
"black"
];
const errorstrings = new Map([
["unknown", "Unknown error, this usually indicates an internal problem :("],
["nopermission", "You do not have the required permissions to use that"],
["protocolerror", "Invalid or badly formatted"],
["needlogin", "You have to be logged in to use that"],
["invalidmsg", "The message was invalid"],
["throttled", "Throttled! You were trying to send messages too fast"],
["duplicate", "The message is identical to the last one you sent"],
["muted", "You are muted. Check your profile for more information."],
["submode", "The channel is currently in subscriber only mode"],
["needbanreason", "Providing a reason for the ban is mandatory"],
[
"banned",
"You have been banned."
],
["privmsgbanned", "Cannot send private messages while banned"],
["requiresocket", "This chat requires WebSockets"],
["toomanyconnections", "Only 5 concurrent connections allowed"],
["socketerror", "Error contacting server"],
[
"privmsgaccounttooyoung",
"Your account is too recent to send private messages"
],
["notfound", "The user was not found"],
["notconnected", "You have to be connected to use that"]
]);
const hintstrings = new Map([
[
"slashhelp",
"Type in /help for more a list of commands, do advanced things like modify your scroll-back size"
],
[
"tabcompletion",
"Use the tab key to auto-complete names and emotes (for user only completion prepend a @ or press shift)"
],
[
"hoveremotes",
"Hovering your mouse over an emote will show you the emote code"
],
["highlight", "Chat messages containing your username will be highlighted"],
["notify", "Use /w <username> to send a private message to someone"],
[
"ignoreuser",
"Use /ignore <username> to hide messages from pesky chatters"
],
["mutespermanent", "Mutes are never persistent, don't worry it will pass!"],
[
"tagshint",
`Use the /tag <nick> <color> to highlight users you like. There are preset colors to choose from ${tagcolors.join(
", "
)}, or \`/tag <nick> #HEXCODE\``
],
["contextmenu", "Right click a user to access quick options!"]
]);
const settingsdefault = new Map([
["schemaversion", 2],
["showtime", false],
["hideflairicons", false],
["profilesettings", false],
["timestampformat", "HH:mm"],
["maxlines", 250],
["notificationwhisper", true],
["soundnotificationwhisper", false],
["notificationhighlight", true],
["soundnotificationhighlight", false],
["notificationsoundfile", ""],
["highlight", true], // todo rename this to `highlightself` or something
["customhighlight", []],
["highlightnicks", []],
["taggednicks", []],
["showremoved", 0], // 0 = false (removes), 1 = true (censor), 2 = do nothing
["showhispersinchat", true],
["ignorenicks", []],
["focusmentioned", false],
["notificationtimeout", true],
["ignorementions", false],
["autocompletehelper", true],
["autocompleteemotepreview", true],
["taggedvisibility", false],
["hidensfw", false],
["animateforever", true],
["formatter-green", true],
["formatter-emote", true],
["formatter-combo", true],
["holidayemotemodifiers", true],
["disablespoilers", false],
["viewerstateindicator", 1],
["shortenlinks", true],
["hiddenemotes", []]
]);
const commandsinfo = new Map([
["help", { desc: "Helpful information." }],
["emotes", { desc: "A list of the chats emotes in text form." }],
["me", { desc: "A normal message, but emotive." }],
[
"message",
{
desc: "Whisper someone",
alias: ["msg", "whisper", "w", "tell", "t", "notify"]
}
],
[
"ignore",
{
desc:
"No longer see user messages, without <nick> to list the nicks ignored"
}
],
["unignore", { desc: "Remove a user from your ignore list" }],
[
"highlight",
{ desc: "Highlights target nicks messages for easier visibility" }
],
["unhighlight", { desc: "Unhighlight target nick" }],
["maxlines", { desc: "The maximum number of lines the chat will store" }],
[
"mute",
{
desc: "The users messages will be blocked from everyone.",
admin: true
}
],
["unmute", { desc: "Unmute the user.", admin: true }],
["subonly", { desc: "Subscribers only", admin: true }],
[
"ban",
{
desc: "User will no longer be able to connect to the chat.",
admin: true
}
],
["unban", { desc: "Unban a user", admin: true }],
["timestampformat", { desc: "Set the time format of the chat." }],
["tag", { desc: "Mark a users messages" }],
["untag", { desc: "No longer mark the users messages" }],
["exit", { desc: "Exit the conversation you are in." }],
[
"hideemote",
{ desc: "Hide emotes in chat by converting them to plain text." }
],
["unhideemote", { desc: "Unhide a hidden emote." }],
["spoiler", { desc: "Wraps a message in the spoiler tags `||`." }],
]);
const banstruct = {
id: 0,
userid: 0,
username: "",
targetuserid: "",
targetusername: "",
ipaddress: "",
reason: "",
starttimestamp: "",
endtimestamp: ""
};
const debounceFocus = debounce(10, c => c.input.focus());
const focusIfNothingSelected = chat => {
if (window.getSelection().isCollapsed && !chat.input.is(":focus")) {
debounceFocus(chat);
}
};
const extractHostname = url => {
let hostname =
url.indexOf("://") > -1 ? url.split("/")[2] : url.split("/")[0];
hostname = hostname.split(":")[0];
hostname = hostname.split("?")[0];
return hostname;
};
const Notification = window.Notification || {};
class Chat {
constructor() {
/** @type JQuery */
this.ui = null;
this.css = null;
this.output = null;
this.input = null;
this.loginscrn = null;
this.loadingscrn = null;
this.showmotd = true;
this.authenticated = false;
this.backlogloading = false;
this.unresolved = [];
this.emoticons = new Set();
this.emoteswithsuffixes = new Set();
this.user = new ChatUser();
this.users = new Map();
this.viewerStates = new Map();
this.whispers = new Map();
this.whisperStore = new WhisperStore('Anonymous');
this.windows = new Map();
this.settings = new Map([...settingsdefault]);
this.autocomplete = new ChatAutoComplete();
this.menus = new Map();
this.taggednicks = new Map();
this.ignoring = new Set();
this.mainwindow = null;
this.nukes = [];
this.regexhighlightcustom = null;
this.regexhighlightnicks = null;
this.regexhighlightself = null;
// An interface to tell the chat to do things via chat commands, or via emit
// e.g. control.emit('CONNECT', 'ws://localhost:9001') is essentially chat.cmdCONNECT('ws://localhost:9001')
this.control = new EventEmitter(this);
// The websocket connection, emits events from the chat server
this.source = new ChatSource();
this.source.on("REFRESH", () => window.location.reload(false));
this.source.on("PING", data => this.source.send("PONG", data));
this.source.on("CONNECTING", data => this.onCONNECTING(data));
this.source.on("OPEN", data => this.onOPEN(data));
this.source.on("DISPATCH", data => this.onDISPATCH(data));
this.source.on("CLOSE", data => this.onCLOSE(data));
this.source.on("NAMES", data => this.onNAMES(data));
this.source.on("QUIT", data => this.onQUIT(data));
this.source.on("MSG", data => this.onMSG(data));
this.source.on("MUTE", data => this.onMUTE(data));
this.source.on("UNMUTE", data => this.onUNMUTE(data));
this.source.on("BAN", data => this.onBAN(data));
this.source.on("UNBAN", data => this.onUNBAN(data));
this.source.on("ERR", data => this.onERR(data));
this.source.on("SOCKETERROR", data => this.onSOCKETERROR(data));
this.source.on("SUBONLY", data => this.onSUBONLY(data));
this.source.on("BROADCAST", data => this.onBROADCAST(data));
this.source.on("PRIVMSGSENT", data => this.onPRIVMSGSENT(data));
this.source.on("PRIVMSG", data => this.onPRIVMSG(data));
this.source.on("VIEWERSTATE", data => this.onVIEWERSTATE(data));
this.control.on("SEND", data => this.cmdSEND(data));
this.control.on("HINT", data => this.cmdHINT(data));
this.control.on("EMOTES", data => this.cmdEMOTES(data));
this.control.on("HELP", data => this.cmdHELP(data));
this.control.on("IGNORE", data => this.cmdIGNORE(data));
this.control.on("UNIGNORE", data => this.cmdUNIGNORE(data));
this.control.on("MUTE", data => this.cmdMUTE(data));
this.control.on("BAN", data => this.cmdBAN(data, "BAN"));
this.control.on("IPBAN", data => this.cmdBAN(data, "IPBAN"));
this.control.on("UNMUTE", data => this.cmdUNBAN(data, "UNMUTE"));
this.control.on("UNBAN", data => this.cmdUNBAN(data, "UNBAN"));
this.control.on("SUBONLY", data => this.cmdSUBONLY(data, "SUBONLY"));
this.control.on("MAXLINES", data => this.cmdMAXLINES(data, "MAXLINES"));
this.control.on("UNHIGHLIGHT", data =>
this.cmdHIGHLIGHT(data, "UNHIGHLIGHT")
);
this.control.on("HIGHLIGHT", data =>
this.cmdHIGHLIGHT(data, "HIGHLIGHT")
);
this.control.on("TIMESTAMPFORMAT", data =>
this.cmdTIMESTAMPFORMAT(data)
);
this.control.on("BROADCAST", data => this.cmdBROADCAST(data));
this.control.on("CONNECT", data => this.cmdCONNECT(data));
this.control.on("TAG", data => this.cmdTAG(data));
this.control.on("UNTAG", data => this.cmdUNTAG(data));
this.control.on("BANINFO", data => this.cmdBANINFO(data));
this.control.on("EXIT", data => this.cmdEXIT(data));
this.control.on("MESSAGE", data => this.cmdWHISPER(data));
this.control.on("MSG", data => this.cmdWHISPER(data));
this.control.on("WHISPER", data => this.cmdWHISPER(data));
this.control.on("W", data => this.cmdWHISPER(data));
this.control.on("TELL", data => this.cmdWHISPER(data));
this.control.on("T", data => this.cmdWHISPER(data));
this.control.on("NOTIFY", data => this.cmdWHISPER(data));
this.control.on("HIDEEMOTE", data =>
this.cmdHIDEEMOTE(data, "HIDEEMOTE")
);
this.control.on("UNHIDEEMOTE", data =>
this.cmdHIDEEMOTE(data, "UNHIDEEMOTE")
);
this.control.on("SPOILER", data => this.cmdSPOILER(data))
notificationSound.loadConfig();
}
withUserAndSettings(data) {
return this.withUser(data).withSettings(
data && data.hasOwnProperty("settings")
? new Map(data.settings)
: new Map()
);
}
withUser(user) {
this.user = this.addUser(user || { nick: "Anonymous" });
this.authenticated =
this.user !== null &&
this.user.username !== "" &&
this.user.username !== "Anonymous";
return this;
}
withSettings(settings) {
// If authed and #settings.profilesettings=true use #settings
// Else use whats in LocalStorage#chat.settings
let stored =
settings !== null &&
this.authenticated &&
settings.get("profilesettings")
? settings
: new Map(ChatStore.read("chat.settings") || []);
// Loop through settings and apply any settings found in the #stored data
if (stored.size > 0) {
[...this.settings.keys()]
.filter(
k => stored.get(k) !== undefined && stored.get(k) !== null
)
.forEach(k => this.settings.set(k, stored.get(k)));
}
// Upgrade if schema is out of date
const oldversion = stored.has("schemaversion")
? parseInt(stored.get("schemaversion"))
: -1;
const newversion = settingsdefault.get("schemaversion");
if (oldversion !== -1 && newversion > oldversion) {
Settings.upgrade(this, oldversion, newversion);
this.settings.set("schemaversion", newversion);
this.saveSettings();
}
this.taggednicks = new Map(this.settings.get("taggednicks"));
this.rebuildHexColorStyles(this.taggednicks);
this.ignoring = new Set(this.settings.get("ignorenicks"));
return this;
}
withGui() {
this.ui = $("#chat");
this.css = $("#chat-styles")[0]["sheet"];
this.ishidden =
(document["visibilityState"] || "visible") !== "visible";
this.output = this.ui.find("#chat-output-frame");
this.input = this.ui.find("#chat-input-control");
this.chatinputerror = this.ui.find("#chat-input-error");
this.loginscrn = this.ui.find("#chat-login-screen");
this.loadingscrn = this.ui.find("#chat-loading");
this.windowselect = this.ui.find("#chat-windows-select");
this.inputhistory = new ChatInputHistory(this);
this.userfocus = new ChatUserFocus(this, this.css);
this.spoiler = new ChatSpoiler(this);
this.mainwindow = new ChatWindow("main").into(this);
this.windowToFront("main");
this.menus.set(
"settings",
new ChatSettingsMenu(
this.ui.find("#chat-settings"),
this.ui.find("#chat-settings-btn"),
this
)
);
this.menus.set(
"emotes",
new ChatEmoteMenu(
this.ui.find("#chat-emote-list"),
this.ui.find("#chat-emoticon-btn"),
this
)
);
this.menus.set(
"users",
new ChatUserMenu(
this.ui.find("#chat-user-list"),
this.ui.find("#chat-users-btn"),
this
)
);
this.menus.set(
"whisper-users",
new ChatWhisperUsers(
this.ui.find("#chat-whisper-users"),
this.ui.find("#chat-whisper-btn"),
this
)
);
commandsinfo.forEach((a, k) => {
this.autocomplete.add(`/${k}`);
(a["alias"] || []).forEach(k => this.autocomplete.add(`/${k}`));
});
this.emoticons.forEach(e => this.autocomplete.add(e, true));
const suffixes = Object.keys(GENERIFY_OPTIONS);
suffixes.forEach(e => this.autocomplete.add(`:${e}`, true));
this.autocomplete.bind(this);
this.applySettings(false);
// Chat input
this.input.on("keypress", e => {
if (isKeyCode(e, KEYCODES.ENTER) && !e.shiftKey && !e.ctrlKey) {
e.preventDefault();
e.stopPropagation();
if (!this.authenticated) {
this.loginscrn.show();
} else {
// don't do anything if the message is marked invalid client-side (currently only when the message is too long)
if (!this.input.hasClass("invalid-msg-warning")) {
this.control.emit(
"SEND",
this.input.val().toString().trim()
);
this.input.val("").trigger("input");
}
}
this.input.focus();
}
});
//make the border red if a message exceeds the character limit
this.input.on("keydown", (e) => {
let chars = this.input.val().toString().length
if(isKeyCode(e, KEYCODES.BACKSPACE))
chars--
this.testIfValid(chars);
});
this.input.on("keyup", (e) => {
this.testIfValid(this.input.val().toString().length);
});
/**
* Syncing the text content of the scaler with the input, so that
* the scaler grows the containing element to the exact size to
* contain the text entered.
*/
const inputScaler = this.ui.find("#chat-input-scaler");
let lastHeightScaler = 0;
this.input.on("input keydown", () => {
// Get pinned state before syncing the scaler
const wasScrollPinned = this.mainwindow.scrollplugin.isPinned();
inputScaler.text(this.input.val());
if (lastHeightScaler !== inputScaler.height()) {
lastHeightScaler = inputScaler.height();
this.mainwindow.scrollplugin.reset();
if (wasScrollPinned) {
this.mainwindow.updateAndPin();
}
}
});
// Chat focus / menu close when clicking on some areas
let downinoutput = false;
this.output.on("mousedown", () => {
downinoutput = true;
});
this.output.on("mouseup", () => {
if (downinoutput) {
downinoutput = false;
ChatMenu.closeMenus(this);
focusIfNothingSelected(this);
}
});
const rustlaUrl = new URL(RUSTLA_URL);
this.output.on('click', 'a', (e) => {
let linkUrl;
try {
linkUrl = new URL($(e.target).attr('href'));
} catch (e) {
return;
}
const path = linkUrl.pathname.match(/^\/([a-z0-9\-_]+)(?:\/([^ ]+))?$/i);
if (rustlaUrl.host === linkUrl.host && path && !e.ctrlKey && !e.metaKey && window.top !== window.self) {
const [, service, channel] = path;
const payload = channel ? { service, channel } : { path: service };
window.parent.postMessage({ action: 'STREAM_SET', payload }, '*');
console.log({ action: 'STREAM_SET', payload });
e.preventDefault();
e.stopPropagation();
}
});
this.ui.on("click", "#chat-tools-wrap", () => {
ChatMenu.closeMenus(this);
focusIfNothingSelected(this);
});
// ESC
document.addEventListener("keydown", e => {
if (isKeyCode(e, KEYCODES.ESC)) ChatMenu.closeMenus(this); // ESC key
});
// Focus textbox using the TAB button
document.addEventListener('keydown', e => {
if (isKeyCode(e, KEYCODES.TAB)) {
event.preventDefault();
this.input.focus();
}
});
// Visibility
document.addEventListener(
"visibilitychange",
debounce(100, () => {
this.ishidden =
(document["visibilityState"] || "visible") !== "visible";
if (!this.ishidden) focusIfNothingSelected(this);
else ChatMenu.closeMenus(this);
}),
true
);
// Resize
let resizing = false;
const onresizecomplete = debounce(100, () => {
resizing = false;
this.getActiveWindow().unlock();
focusIfNothingSelected(this);
});
const onresize = () => {
if (!resizing) {
resizing = true;
ChatMenu.closeMenus(this);
this.getActiveWindow().lock();
}
onresizecomplete();
};
window.addEventListener("resize", onresize, false);
// Chat user whisper tabs
this.windowselect.on("click", ".fa-close", e => {
ChatMenu.closeMenus(this);
this.removeWindow(
$(e.currentTarget)
.parent()
.data("name")
.toLowerCase()
);
this.input.focus();
return false;
});
this.windowselect.on("click", ".tab", e => {
ChatMenu.closeMenus(this);
this.windowToFront(
$(e.currentTarget)
.data("name")
.toLowerCase()
);
this.input.focus();
return false;
});
// Censored
this.output.on("click", ".censored", e => {
const nick = $(e.currentTarget)
.closest(".msg-user")
.data("username");
this.getActiveWindow()
.getlines(`.censored[data-username="${nick}"]`)
.removeClass("censored");
return false;
});
// Login
this.loginscrn.on("click", "#chat-btn-login", () => {
this.loginscrn.hide();
if (LOGIN_URI) {
window.top.location.href = LOGIN_URI;
return;
}
try {
window.top.showLoginModal();
} catch (_) {
const { origin, pathname } = location;
if (window.self === window.top) {
let follow = "";
try {
follow = encodeURIComponent(pathname);
} catch (_) {}
location.href = `${origin}/login?follow=${follow}`;
} else {
location.href = `${origin}/login`;
}
}
return false;
});
this.loginscrn.on("click", "#chat-btn-cancel", () =>
this.loginscrn.hide()
);
this.output.on("click mousedown", ".msg-whisper a.user", e => {
const msg = $(e.target).closest(".msg-chat");
this.openConversation(
msg
.data("username")
.toString()
.toLowerCase()
);
return false;
});
this.output.on("click", "a.user", e => {
if (e.ctrlKey || e.metaKey) {
const msg = $(e.target).closest(".msg-chat");
this.openViewerStateStream(msg.data("username"))
}
})
// Context menu
this.output.on("contextmenu", "a.user", e => {
if ($(e.target).parent().data("username").toLowerCase() !== this.user.username.toLowerCase()) {
e.preventDefault();
window.getSelection().removeAllRanges();
this.contextMenu = new ChatContextMenu(this, e);
this.contextMenu.show(e);
this.mainwindow.lock();
}
})
this.output.on("click", "span.generify-container span.chat-emote", e => {
e.preventDefault();
let temp = this.emoteInfoMenu;
this.emoteInfoMenu = new ChatEmoteInfoMenu(this, e);
this.emoteInfoMenu.show(e);
if(temp && temp.emoteInfoID == this.emoteInfoMenu.emoteInfoID)
{
this.emoteInfoMenu.hide()
this.emoteInfoMenu = undefined;
}
})
this.ui.on("click","#chat-emote-info", (e) => {
// prevents hiding the popup accidentally if you're clicking text inside of it
e.stopPropagation();
});
this.ui.on("click", (e) => {
if (this.contextMenu) {
if (!$(e.target).is(this.contextMenu.ui)) {
this.contextMenu.hide();
if (this.mainwindow.locked()) {
this.mainwindow.unlock();
}
}
}
if (this.emoteInfoMenu) {
if (
e.target.innerText.split(":")[0] !=
this.emoteInfoMenu.targetEmote
) {
this.emoteInfoMenu.hide();
}
}
});
window.addEventListener('beforeunload', (event) => ChatStore.write('chat.unsentMessage', this.input.val()));
this.loadingscrn.fadeOut(250, () => this.loadingscrn.remove());
this.mainwindow.updateAndPin();
this.input.focus();
this.input
.focus()
.attr(
"placeholder",
this.authenticated
? `Write something ${this.user.username} ...`
: "You need to be signed in to chat."
);
this.input.val(ChatStore.read('chat.unsentMessage') ? ChatStore.read('chat.unsentMessage') : null);
return this;
}
testIfValid(messageLength){
if (messageLength > 512) {
this.input.addClass("invalid-msg-warning");
this.chatinputerror.addClass("show")
} else if (messageLength <= 512) {
this.input.removeClass("invalid-msg-warning");
this.chatinputerror.removeClass("show")
}
};
withEmotes(emotes) {
this.emoticons = new Set(emotes["default"]);
for (var s in GENERIFY_OPTIONS) {
for (var e of this.emoticons) {
this.emoteswithsuffixes.add(`${e}:${s}`);
}
}
return this;
}
withHistory(history) {
if (history && history.length > 0) {
this.backlogloading = true;
history.forEach(line =>
this.source.parseAndDispatch({ data: line })
);
MessageBuilder.element("<hr/>").into(this);
this.backlogloading = false;
this.mainwindow.updateAndPin();
}
return this;
}
withViewerStates(viewerStates) {
viewerStates.forEach(state => this.onVIEWERSTATE(state));
return this;
}
withWhispers() {
if (this.authenticated) {
this.whisperStore = new WhisperStore(this.user.nick.toLowerCase());
this.whisperStore.load().forEach(e => this.whispers.set(e['key'], {
id: -1,
nick: e['nick'],
unread: e['unread'],
open: false
}));
this.menus.get('whisper-users').redraw();
}
return this;
}
connect(uri) {
this.source.connect(uri);
return this;
}
saveSettings() {
if (this.authenticated) {
if (this.settings.get("profilesettings")) {
$.ajax({
url: `${API_URI}/api/chat/me/settings`,
method: "post",
data: JSON.stringify([...this.settings])
});
} else {
ChatStore.write("chat.settings", this.settings);
}
} else {
ChatStore.write("chat.settings", this.settings);
}
}
// De-bounced saveSettings
commitSettings() {
if (!this.debouncedsave) {
this.debouncedsave = debounce(1000, () => this.saveSettings());
}
this.debouncedsave();
}
// Save settings if save=true then apply current settings to chat
applySettings(save = true) {
if (save) this.saveSettings();
// Formats
DATE_FORMATS.TIME = this.settings.get("timestampformat");
// Ignore Regex
const ignores = Array.from(this.ignoring.values()).map(
Chat.makeSafeForRegex
);
this.ignoreregex =
ignores.length > 0
? new RegExp(`\\b(?:${ignores.join("|")})\\b`, "i")
: null;
// Highlight Regex
const cust = [...(this.settings.get("customhighlight") || [])].filter(
a => a !== ""
);
const nicks = [...(this.settings.get("highlightnicks") || [])].filter(
a => a !== ""
);
this.regexhighlightself = this.user.nick
? new RegExp(`\\b(?:${this.user.nick})\\b`, "i")
: null;
this.regexhighlightcustom =
cust.length > 0
? new RegExp(`\\b(?:${cust.join("|")})\\b`, "i")
: null;
this.regexhighlightnicks =
nicks.length > 0
? new RegExp(`\\b(?:${nicks.join("|")})\\b`, "i")
: null;
// Settings Css
Array.from(this.settings.keys()).forEach(key => {
const value = this.settings.get(key);
if (typeof value === "boolean") {
this.ui.toggleClass(`pref-${key}`, value);
} else if (!isNaN(parseInt(value))) {
this.ui
.prop("className")
.split(/\s+/)
.filter(c => c.startsWith(`pref-${key}`))
.forEach(c => this.ui.removeClass(c));
this.ui.addClass(`pref-${key}-${value}`);
}
});
// Update maxlines
[...this.windows].forEach(w => {
w.maxlines = this.settings.get("maxlines");
});
if (this.mainwindow !== null) {
this.mainwindow.maxlines = this.settings.get("maxlines");
this.mainwindow.cleanup();
}
// Formatter enable/disable
const messages = require("./messages.js");
messages.setFormattersFromSettings(this.settings);
}
addUser(data) {
if (!data) {
return null;
}
const normalized = data.nick.toLowerCase();
let user = this.users.get(normalized);
if (!user) {
user = new ChatUser(data);
this.users.set(normalized, user);
this.updateUserViewerState(data.nick);
} else if (
data.hasOwnProperty("features") &&
!Chat.isArraysEqual(data.features, user.features)
) {
user.features = data.features;
}
return user;
}
addViewerState(nick) {
const normalized = nick.toLowerCase();
let viewerState = this.viewerStates.get(normalized);
if (!viewerState) {
viewerState = new ViewerState();
this.viewerStates.set(normalized, viewerState);
this.updateUserViewerState(nick);
}
return viewerState;
}
updateUserViewerState(nick) {
const normalized = nick.toLowerCase();
let viewerState = this.viewerStates.get(normalized);
let user = this.users.get(normalized);
if (user && viewerState) {
user.viewerState = viewerState;
}
}
addAffixToEmotes(text, affix) {
text.trim();
var updatedText = text.split(" ")
for (var i = 0; i < updatedText.length; i++) {
if (!updatedText[i].includes(":love") && (this.emoticons.has(updatedText[i].split(":")[0]) || this.emoteswithsuffixes.has(updatedText[i]))) {
updatedText[i] += affix;
}
}
return updatedText.join(" ");
}
addMessage(message, win = null) {
// Dont add the gui if user is ignored
if (
message.type === MessageTypes.USER &&
this.ignored(message.user.nick, message.message)
) {
const isOwn =
message.user.username.toLowerCase() ===
this.user.username.toLowerCase();
if (!isOwn) return;
}
if (win === null) {
win = this.mainwindow;
}
if (!this.backlogloading) win.lock();
// Break the current combo if this message is not an emote
// We dont need to check what type the current message is, we just know that its a new message, so the combo is invalid.
if (
win.lastmessage &&
win.lastmessage.type === MessageTypes.EMOTE &&
win.lastmessage.emotecount > 1
) {
win.lastmessage.completeCombo();
}
// Populate the tag, mentioned users and highlight for this $message.
if (message.type === MessageTypes.USER) {
// check if message is `/me `
message.slashme =
message.message.substring(0, 4).toLowerCase() === "/me ";
// check if this is the current users message
message.isown =
message.user.username.toLowerCase() ===
this.user.username.toLowerCase();
// check if the last message was from the same user
message.continued =
win.lastmessage &&
!win.lastmessage.target &&
win.lastmessage.user &&
win.lastmessage.user.username.toLowerCase() ===
message.user.username.toLowerCase();
// get mentions from message
message.mentioned = Chat.extractNicks(message.message).reduce((m, a) => {
const user = this.users.get(a.toLowerCase());
return user ? [...m, user.nick] : m;
}, []);
// set tagged state
message.tag = this.taggednicks.get(message.user.nick.toLowerCase());
// set highlighted state if this is not the current users message or a bot, as well as other highlight criteria
message.highlighted =
!message.isown &&
!message.user.hasFeature(UserFeatures.BOT) &&
// Check current user nick against msg.message (if highlight setting is on)
((this.regexhighlightself &&
this.settings.get("highlight") &&
this.regexhighlightself.test(message.message)) ||
// Check /highlight nicks against msg.nick
(this.regexhighlightnicks &&
this.regexhighlightnicks.test(message.user.username)) ||
// Check custom highlight against msg.nick and msg.message
(this.regexhighlightcustom &&
this.regexhighlightcustom.test(
message.user.username + " " + message.message
)));
if (this.settings.get("holidayemotemodifiers")){
const t = new Date();
if (t.getMonth() === 1 && t.getDate() === 14) {
message.message = this.addAffixToEmotes(message.message, ":love");
}
}
}
/* else if(win.lastmessage && win.lastmessage.type === message.type && [MessageTypes.ERROR,MessageTypes.INFO,MessageTypes.COMMAND,MessageTypes.STATUS].indexOf(message.type)){
message.continued = true
} */
// The point where we actually add the message dom
win.addMessage(this, message);
// Show desktop notification
if (
!this.backlogloading &&
message.highlighted &&
this.settings.get("notificationhighlight") &&
this.ishidden
) {
Chat.showNotification(
`${message.user.username} said ...`,