-
-
Notifications
You must be signed in to change notification settings - Fork 211
/
ClientBase.js
1449 lines (1275 loc) · 44.9 KB
/
ClientBase.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
/// <reference path="../types.d.ts" />
const _global = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {};
const _WebSocket = _global.WebSocket ?? require('ws');
const EventEmitter = require('./EventEmitter');
const Logger = require('./Logger');
const parser = require('./parser');
const Queue = require('./Queue');
const _ = require('./utils');
// Client instance
class ClientBase extends EventEmitter {
constructor(opts) {
super();
this.opts = opts ?? {};
this.opts.channels = this.opts.channels ?? [];
this.opts.connection = this.opts.connection ?? {};
this.opts.identity = this.opts.identity ?? {};
this.opts.options = this.opts.options ?? {};
this.clientId = this.opts.options.clientId ?? null;
this._globalDefaultChannel = _.channel(this.opts.options.globalDefaultChannel ?? '#tmijs');
this._skipMembership = this.opts.options.skipMembership ?? false;
this.maxReconnectAttempts = this.opts.connection.maxReconnectAttempts ?? Infinity;
this.maxReconnectInterval = this.opts.connection.maxReconnectInterval ?? 30000;
this.reconnect = this.opts.connection.reconnect ?? true;
this.reconnectDecay = this.opts.connection.reconnectDecay ?? 1.5;
this.reconnectInterval = this.opts.connection.reconnectInterval ?? 1000;
this.reconnecting = false;
this.reconnections = 0;
this.reconnectTimer = this.reconnectInterval;
this.currentLatency = 0;
this.latency = new Date();
this.secure = this.opts.connection.secure ?? (!this.opts.connection.server && !this.opts.connection.port);
this.pingLoop = null;
this.pingTimeout = null;
this.wasCloseCalled = false;
this.reason = '';
this.ws = null;
// Raw data and object for emote-sets
this.emotes = '';
// This is unused but remains for backwards compatibility
this.emotesets = {};
this.username = '';
this.channels = [];
this.globaluserstate = {};
this.userstate = {};
this.lastJoined = '';
this.moderators = {};
// Create the logger
this.log = this.opts.logger ?? new Logger();
try {
this.log.setLevel(this.opts.options.debug ? 'info' : 'error');
}
catch(err) {}
// Format the channel names
this.opts.channels.forEach((part, index, theArray) => theArray[index] = _.channel(part)
);
this.setMaxListeners(0);
}
/** @deprecated */
api() {
throw new Error('The Client.api() method has been removed.');
}
// Handle parsed chat server message
handleMessage(message) {
if(!message) {
return;
}
if(this.listenerCount('raw_message')) {
this.emit('raw_message', JSON.parse(JSON.stringify(message)), message);
}
const channel = _.channel(message.params[0] ?? null);
const msg = message.params[1] ?? null;
const msgid = message.tags['msg-id'] ?? null;
// Parse badges, badge-info and emotes
const tags = message.tags = parser.badges(parser.badgeInfo(parser.emotes(message.tags)));
// Transform IRCv3 tags
for(const key in tags) {
if(key === 'emote-sets' || key === 'ban-duration' || key === 'bits') {
continue;
}
let value = tags[key];
if(typeof value === 'boolean') {
value = null;
}
else if(value === '1') {
value = true;
}
else if(value === '0') {
value = false;
}
else if(typeof value === 'string') {
value = _.unescapeIRC(value);
}
tags[key] = value;
}
// Messages with no prefix
if(message.prefix === null) {
switch(message.command) {
// Received PING from server
case 'PING':
this.emit('ping');
if(this._isConnected()) {
this.ws.send('PONG');
}
break;
// Received PONG from server, return current latency
case 'PONG': {
this.currentLatency = (new Date().getTime() - this.latency.getTime()) / 1000;
this.emits([ 'pong', '_promisePing' ], [ [ this.currentLatency ] ]);
clearTimeout(this.pingTimeout);
break;
}
default:
this.log.warn(`Could not parse message with no prefix:\n${JSON.stringify(message, null, 4)}`);
break;
}
}
// Messages with "tmi.twitch.tv" as a prefix
else if(message.prefix === 'tmi.twitch.tv') {
switch(message.command) {
case '002':
case '003':
case '004':
case '372':
case '375':
case 'CAP':
break;
// Retrieve username from server
case '001':
[ this.username ] = message.params;
break;
// Connected to server
case '376': {
this.log.info('Connected to server.');
this.userstate[this._globalDefaultChannel] = {};
this.emits([ 'connected', '_promiseConnect' ], [ [ this.server, this.port ], [ null ] ]);
this.reconnections = 0;
this.reconnectTimer = this.reconnectInterval;
// Set an internal ping timeout check interval
this.pingLoop = setInterval(() => {
// Make sure the connection is opened before sending the message
if(this._isConnected()) {
this.ws.send('PING');
}
this.latency = new Date();
this.pingTimeout = setTimeout(() => {
if(this.ws !== null) {
this.wasCloseCalled = false;
this.log.error('Ping timeout.');
this.ws.close();
clearInterval(this.pingLoop);
clearTimeout(this.pingTimeout);
}
}, this.opts.connection.timeout ?? 9999);
}, 60000);
// Join all the channels from the config with an interval
let joinInterval = this.opts.options.joinInterval ?? 2000;
if(joinInterval < 300) {
joinInterval = 300;
}
const joinQueue = new Queue(joinInterval);
const joinChannels = [ ...new Set([ ...this.opts.channels, ...this.channels ]) ];
this.channels = [];
for(let i = 0; i < joinChannels.length; i++) {
const channel = joinChannels[i];
joinQueue.add(() => {
if(this._isConnected()) {
this.join(channel).catch(err => this.log.error(err));
}
});
}
joinQueue.next();
break;
}
case 'NOTICE': {
const nullArr = [ null ];
const noticeArr = [ channel, msgid, msg ];
const msgidArr = [ msgid ];
const channelTrueArr = [ channel, true ];
const channelFalseArr = [ channel, false ];
const noticeAndNull = [ noticeArr, nullArr ];
const noticeAndMsgid = [ noticeArr, msgidArr ];
const basicLog = `[${channel}] ${msg}`;
switch(msgid) {
// This room is now in subscribers-only mode.
case 'subs_on':
this.log.info(`[${channel}] This room is now in subscribers-only mode.`);
this.emits([ 'subscriber', 'subscribers', '_promiseSubscribers' ], [ channelTrueArr, channelTrueArr, nullArr ]);
break;
// This room is no longer in subscribers-only mode.
case 'subs_off':
this.log.info(`[${channel}] This room is no longer in subscribers-only mode.`);
this.emits([ 'subscriber', 'subscribers', '_promiseSubscribersoff' ], [ channelFalseArr, channelFalseArr, nullArr ]);
break;
// This room is now in emote-only mode.
case 'emote_only_on':
this.log.info(`[${channel}] This room is now in emote-only mode.`);
this.emits([ 'emoteonly', '_promiseEmoteonly' ], [ channelTrueArr, nullArr ]);
break;
// This room is no longer in emote-only mode.
case 'emote_only_off':
this.log.info(`[${channel}] This room is no longer in emote-only mode.`);
this.emits([ 'emoteonly', '_promiseEmoteonlyoff' ], [ channelFalseArr, nullArr ]);
break;
// Do not handle slow_on/off here, listen to the ROOMSTATE notice instead as it returns the delay.
case 'slow_on':
case 'slow_off':
break;
// Do not handle followers_on/off here, listen to the ROOMSTATE notice instead as it returns the delay.
case 'followers_on_zero':
case 'followers_on':
case 'followers_off':
break;
// This room is now in r9k mode.
case 'r9k_on':
this.log.info(`[${channel}] This room is now in r9k mode.`);
this.emits([ 'r9kmode', 'r9kbeta', '_promiseR9kbeta' ], [ channelTrueArr, channelTrueArr, nullArr ]);
break;
// This room is no longer in r9k mode.
case 'r9k_off':
this.log.info(`[${channel}] This room is no longer in r9k mode.`);
this.emits([ 'r9kmode', 'r9kbeta', '_promiseR9kbetaoff' ], [ channelFalseArr, channelFalseArr, nullArr ]);
break;
// The moderators of this room are: [..., ...]
case 'room_mods': {
const listSplit = msg.split(': ');
const mods = (listSplit.length > 1 ? listSplit[1] : '').toLowerCase()
.split(', ')
.filter(n => n);
this.emits([ '_promiseMods', 'mods' ], [ [ null, mods ], [ channel, mods ] ]);
break;
}
// There are no moderators for this room.
case 'no_mods':
this.emits([ '_promiseMods', 'mods' ], [ [ null, [] ], [ channel, [] ] ]);
break;
// The VIPs of this channel are: [..., ...]
case 'vips_success': {
const listSplit = (msg.endsWith('.') ? msg.slice(0, -1) : msg).split(': ');
const vips = (listSplit.length > 1 ? listSplit[1] : '').toLowerCase()
.split(', ')
.filter(n => n);
this.emits([ '_promiseVips', 'vips' ], [ [ null, vips ], [ channel, vips ] ]);
break;
}
// There are no VIPs for this room.
case 'no_vips':
this.emits([ '_promiseVips', 'vips' ], [ [ null, [] ], [ channel, [] ] ]);
break;
// Ban command failed
case 'already_banned':
case 'bad_ban_admin':
case 'bad_ban_anon':
case 'bad_ban_broadcaster':
case 'bad_ban_global_mod':
case 'bad_ban_mod':
case 'bad_ban_self':
case 'bad_ban_staff':
case 'usage_ban':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseBan' ], noticeAndMsgid);
break;
// Ban command success
case 'ban_success':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseBan' ], noticeAndNull);
break;
// Clear command failed
case 'usage_clear':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseClear' ], noticeAndMsgid);
break;
// Mods command failed
case 'usage_mods':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseMods' ], [ noticeArr, [ msgid, [] ] ]);
break;
// Mod command success
case 'mod_success':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseMod' ], noticeAndNull);
break;
// VIPs command failed
case 'usage_vips':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseVips' ], [ noticeArr, [ msgid, [] ] ]);
break;
// VIP command failed
case 'usage_vip':
case 'bad_vip_grantee_banned':
case 'bad_vip_grantee_already_vip':
case 'bad_vip_max_vips_reached':
case 'bad_vip_achievement_incomplete':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseVip' ], [ noticeArr, [ msgid, [] ] ]);
break;
// VIP command success
case 'vip_success':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseVip' ], noticeAndNull);
break;
// Mod command failed
case 'usage_mod':
case 'bad_mod_banned':
case 'bad_mod_mod':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseMod' ], noticeAndMsgid);
break;
// Unmod command success
case 'unmod_success':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseUnmod' ], noticeAndNull);
break;
// Unvip command success.
case 'unvip_success':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseUnvip' ], noticeAndNull);
break;
// Unmod command failed
case 'usage_unmod':
case 'bad_unmod_mod':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseUnmod' ], noticeAndMsgid);
break;
// Unvip command failed
case 'usage_unvip':
case 'bad_unvip_grantee_not_vip':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseUnvip' ], noticeAndMsgid);
break;
// Color command success
case 'color_changed':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseColor' ], noticeAndNull);
break;
// Color command failed
case 'usage_color':
case 'turbo_only_color':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseColor' ], noticeAndMsgid);
break;
// Commercial command success
case 'commercial_success':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseCommercial' ], noticeAndNull);
break;
// Commercial command failed
case 'usage_commercial':
case 'bad_commercial_error':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseCommercial' ], noticeAndMsgid);
break;
// Host command success
case 'hosts_remaining': {
this.log.info(basicLog);
const remainingHost = (!isNaN(msg[0]) ? parseInt(msg[0]) : 0);
this.emits([ 'notice', '_promiseHost' ], [ noticeArr, [ null, ~~remainingHost ] ]);
break;
}
// Host command failed
case 'bad_host_hosting':
case 'bad_host_rate_exceeded':
case 'bad_host_error':
case 'usage_host':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseHost' ], [ noticeArr, [ msgid, null ] ]);
break;
// r9kbeta command failed
case 'already_r9k_on':
case 'usage_r9k_on':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseR9kbeta' ], noticeAndMsgid);
break;
// r9kbetaoff command failed
case 'already_r9k_off':
case 'usage_r9k_off':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseR9kbetaoff' ], noticeAndMsgid);
break;
// Timeout command success
case 'timeout_success':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseTimeout' ], noticeAndNull);
break;
case 'delete_message_success':
this.log.info(`[${channel} ${msg}]`);
this.emits([ 'notice', '_promiseDeletemessage' ], noticeAndNull);
break;
// Subscribersoff command failed
case 'already_subs_off':
case 'usage_subs_off':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseSubscribersoff' ], noticeAndMsgid);
break;
// Subscribers command failed
case 'already_subs_on':
case 'usage_subs_on':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseSubscribers' ], noticeAndMsgid);
break;
// Emoteonlyoff command failed
case 'already_emote_only_off':
case 'usage_emote_only_off':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseEmoteonlyoff' ], noticeAndMsgid);
break;
// Emoteonly command failed
case 'already_emote_only_on':
case 'usage_emote_only_on':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseEmoteonly' ], noticeAndMsgid);
break;
// Slow command failed
case 'usage_slow_on':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseSlow' ], noticeAndMsgid);
break;
// Slowoff command failed
case 'usage_slow_off':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseSlowoff' ], noticeAndMsgid);
break;
// Timeout command failed
case 'usage_timeout':
case 'bad_timeout_admin':
case 'bad_timeout_anon':
case 'bad_timeout_broadcaster':
case 'bad_timeout_duration':
case 'bad_timeout_global_mod':
case 'bad_timeout_mod':
case 'bad_timeout_self':
case 'bad_timeout_staff':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseTimeout' ], noticeAndMsgid);
break;
// Unban command success
// Unban can also be used to cancel an active timeout.
case 'untimeout_success':
case 'unban_success':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseUnban' ], noticeAndNull);
break;
// Unban command failed
case 'usage_unban':
case 'bad_unban_no_ban':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseUnban' ], noticeAndMsgid);
break;
// Delete command failed
case 'usage_delete':
case 'bad_delete_message_error':
case 'bad_delete_message_broadcaster':
case 'bad_delete_message_mod':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseDeletemessage' ], noticeAndMsgid);
break;
// Unhost command failed
case 'usage_unhost':
case 'not_hosting':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseUnhost' ], noticeAndMsgid);
break;
// Whisper command failed
case 'whisper_invalid_login':
case 'whisper_invalid_self':
case 'whisper_limit_per_min':
case 'whisper_limit_per_sec':
case 'whisper_restricted':
case 'whisper_restricted_recipient':
this.log.info(basicLog);
this.emits([ 'notice', '_promiseWhisper' ], noticeAndMsgid);
break;
// Permission error
case 'no_permission':
case 'msg_banned':
case 'msg_room_not_found':
case 'msg_channel_suspended':
case 'tos_ban':
case 'invalid_user':
this.log.info(basicLog);
this.emits([
'notice',
'_promiseBan',
'_promiseClear',
'_promiseUnban',
'_promiseTimeout',
'_promiseDeletemessage',
'_promiseMods',
'_promiseMod',
'_promiseUnmod',
'_promiseVips',
'_promiseVip',
'_promiseUnvip',
'_promiseCommercial',
'_promiseHost',
'_promiseUnhost',
'_promiseJoin',
'_promisePart',
'_promiseR9kbeta',
'_promiseR9kbetaoff',
'_promiseSlow',
'_promiseSlowoff',
'_promiseFollowers',
'_promiseFollowersoff',
'_promiseSubscribers',
'_promiseSubscribersoff',
'_promiseEmoteonly',
'_promiseEmoteonlyoff',
'_promiseWhisper'
], [ noticeArr, [ msgid, channel ] ]);
break;
// Automod-related
case 'msg_rejected':
case 'msg_rejected_mandatory':
this.log.info(basicLog);
this.emit('automod', channel, msgid, msg);
break;
// Unrecognized command
case 'unrecognized_cmd':
this.log.info(basicLog);
this.emit('notice', channel, msgid, msg);
break;
// Send the following msg-ids to the notice event listener
case 'cmds_available':
case 'host_target_went_offline':
case 'msg_censored_broadcaster':
case 'msg_duplicate':
case 'msg_emoteonly':
case 'msg_verified_email':
case 'msg_ratelimit':
case 'msg_subsonly':
case 'msg_timedout':
case 'msg_bad_characters':
case 'msg_channel_blocked':
case 'msg_facebook':
case 'msg_followersonly':
case 'msg_followersonly_followed':
case 'msg_followersonly_zero':
case 'msg_slowmode':
case 'msg_suspended':
case 'no_help':
case 'usage_disconnect':
case 'usage_help':
case 'usage_me':
case 'unavailable_command':
this.log.info(basicLog);
this.emit('notice', channel, msgid, msg);
break;
// Ignore this because we are already listening to HOSTTARGET
case 'host_on':
case 'host_off':
break;
default:
if(msg.includes('Login unsuccessful') || msg.includes('Login authentication failed')) {
this.wasCloseCalled = false;
this.reconnect = false;
this.reason = msg;
this.log.error(this.reason);
this.ws.close();
}
else if(msg.includes('Error logging in') || msg.includes('Improperly formatted auth')) {
this.wasCloseCalled = false;
this.reconnect = false;
this.reason = msg;
this.log.error(this.reason);
this.ws.close();
}
else if(msg.includes('Invalid NICK')) {
this.wasCloseCalled = false;
this.reconnect = false;
this.reason = 'Invalid NICK.';
this.log.error(this.reason);
this.ws.close();
}
else {
this.log.warn(`Could not parse NOTICE from tmi.twitch.tv:\n${JSON.stringify(message, null, 4)}`);
this.emit('notice', channel, msgid, msg);
}
break;
}
break;
}
// Handle subanniversary / resub
case 'USERNOTICE': {
const username = tags['display-name'] || tags['login'];
const plan = tags['msg-param-sub-plan'] ?? '';
const planName = _.unescapeIRC(tags['msg-param-sub-plan-name'] ?? '') || null;
const prime = plan.includes('Prime');
const methods = { prime, plan, planName };
const streakMonths = ~~(tags['msg-param-streak-months'] || 0);
const recipient = tags['msg-param-recipient-display-name'] || tags['msg-param-recipient-user-name'];
const giftSubCount = ~~tags['msg-param-mass-gift-count'];
tags['message-type'] = msgid;
switch(msgid) {
// Handle resub
case 'resub':
this.emits([ 'resub', 'subanniversary' ], [
[ channel, username, streakMonths, msg, tags, methods ]
]);
break;
// Handle sub
case 'sub':
this.emits([ 'subscription', 'sub' ], [
[ channel, username, methods, msg, tags ]
]);
break;
// Handle gift sub
case 'subgift':
this.emit('subgift', channel, username, streakMonths, recipient, methods, tags);
break;
// Handle anonymous gift sub
// Need proof that this event occur
case 'anonsubgift':
this.emit('anonsubgift', channel, streakMonths, recipient, methods, tags);
break;
// Handle random gift subs
case 'submysterygift':
this.emit('submysterygift', channel, username, giftSubCount, methods, tags);
break;
// Handle anonymous random gift subs
// Need proof that this event occur
case 'anonsubmysterygift':
this.emit('anonsubmysterygift', channel, giftSubCount, methods, tags);
break;
// Handle user upgrading from Prime to a normal tier sub
case 'primepaidupgrade':
this.emit('primepaidupgrade', channel, username, methods, tags);
break;
// Handle user upgrading from a gifted sub
case 'giftpaidupgrade': {
const sender = tags['msg-param-sender-name'] || tags['msg-param-sender-login'];
this.emit('giftpaidupgrade', channel, username, sender, tags);
break;
}
// Handle user upgrading from an anonymous gifted sub
case 'anongiftpaidupgrade':
this.emit('anongiftpaidupgrade', channel, username, tags);
break;
case 'announcement': {
const color = tags['msg-param-color'];
this.emit('announcement', channel, tags, msg, false, color);
break;
}
// Handle raid
case 'raid': {
const username = tags['msg-param-displayName'] || tags['msg-param-login'];
const viewers = +tags['msg-param-viewerCount'];
this.emit('raided', channel, username, viewers, tags);
break;
}
// All other msgid events should be emitted under a usernotice event
// until it comes up and needs to be added
default:
this.emit('usernotice', msgid, channel, tags, msg);
break;
}
break;
}
// Channel is now hosting another channel or exited host mode
case 'HOSTTARGET': {
const msgSplit = msg.split(' ');
const viewers = ~~msgSplit[1] || 0;
// Stopped hosting
if(msgSplit[0] === '-') {
this.log.info(`[${channel}] Exited host mode.`);
this.emits([ 'unhost', '_promiseUnhost' ], [ [ channel, viewers ], [ null ] ]);
}
// Now hosting
else {
this.log.info(`[${channel}] Now hosting ${msgSplit[0]} for ${viewers} viewer(s).`);
this.emit('hosting', channel, msgSplit[0], viewers);
}
break;
}
// Someone has been timed out or chat has been cleared by a moderator
case 'CLEARCHAT':
// User has been banned / timed out by a moderator
if(message.params.length > 1) {
// Duration returns null if it's a ban, otherwise it's a timeout
const duration = message.tags['ban-duration'] ?? null;
if(duration === null) {
this.log.info(`[${channel}] ${msg} has been banned.`);
this.emit('ban', channel, msg, null, message.tags);
}
else {
this.log.info(`[${channel}] ${msg} has been timed out for ${duration} seconds.`);
this.emit('timeout', channel, msg, null, ~~duration, message.tags);
}
}
// Chat was cleared by a moderator
else {
this.log.info(`[${channel}] Chat was cleared by a moderator.`);
this.emits([ 'clearchat', '_promiseClear' ], [ [ channel ], [ null ] ]);
}
break;
// Someone's message has been deleted
case 'CLEARMSG':
if(message.params.length > 1) {
const deletedMessage = msg;
const username = tags['login'];
tags['message-type'] = 'messagedeleted';
this.log.info(`[${channel}] ${username}'s message has been deleted.`);
this.emit('messagedeleted', channel, username, deletedMessage, tags);
}
break;
// Received a reconnection request from the server
case 'RECONNECT':
this.log.info('Received RECONNECT request from Twitch..');
this.log.info(`Disconnecting and reconnecting in ${Math.round(this.reconnectTimer / 1000)} seconds..`);
this.disconnect().catch(err => this.log.error(err));
setTimeout(() => this.connect().catch(err => this.log.error(err)), this.reconnectTimer);
break;
// Received when joining a channel and every time you send a PRIVMSG to a channel.
case 'USERSTATE':
message.tags.username = this.username;
// Add the client to the moderators of this room
if(message.tags['user-type'] === 'mod') {
if(!this.moderators[channel]) {
this.moderators[channel] = [];
}
if(!this.moderators[channel].includes(this.username)) {
this.moderators[channel].push(this.username);
}
}
// Logged in and username doesn't start with justinfan
if(!_.isJustinfan(this.getUsername()) && !this.userstate[channel]) {
this.userstate[channel] = tags;
this.lastJoined = channel;
this.channels.push(channel);
this.log.info(`Joined ${channel}`);
this.emit('join', channel, _.username(this.getUsername()), true);
}
// Emote-sets has changed, update it
if(message.tags['emote-sets'] !== this.emotes) {
this.emotes = message.tags['emote-sets'];
this.emit('emotesets', this.emotes, null);
}
this.userstate[channel] = tags;
break;
// Describe non-channel-specific state informations
case 'GLOBALUSERSTATE':
this.globaluserstate = tags;
this.emit('globaluserstate', tags);
// Received emote-sets and emote-sets has changed, update it
if(message.tags['emote-sets'] !== undefined && message.tags['emote-sets'] !== this.emotes) {
this.emotes = message.tags['emote-sets'];
this.emit('emotesets', this.emotes, null);
}
break;
// Received when joining a channel and every time one of the chat room settings, like slow mode, change.
// The message on join contains all room settings.
case 'ROOMSTATE':
// We use this notice to know if we successfully joined a channel
if(_.channel(this.lastJoined) === channel) {
this.emit('_promiseJoin', null, channel);
}
// Provide the channel name in the tags before emitting it
message.tags.channel = channel;
this.emit('roomstate', channel, message.tags);
if(!_.hasOwn(message.tags, 'subs-only')) {
// Handle slow mode here instead of the slow_on/off notice
// This room is now in slow mode. You may send messages every slow_duration seconds.
if(_.hasOwn(message.tags, 'slow')) {
if(typeof message.tags.slow === 'boolean' && !message.tags.slow) {
const disabled = [ channel, false, 0 ];
this.log.info(`[${channel}] This room is no longer in slow mode.`);
this.emits([ 'slow', 'slowmode', '_promiseSlowoff' ], [ disabled, disabled, [ null ] ]);
}
else {
const seconds = ~~message.tags.slow;
const enabled = [ channel, true, seconds ];
this.log.info(`[${channel}] This room is now in slow mode.`);
this.emits([ 'slow', 'slowmode', '_promiseSlow' ], [ enabled, enabled, [ null ] ]);
}
}
// Handle followers only mode here instead of the followers_on/off notice
// This room is now in follower-only mode.
// This room is now in <duration> followers-only mode.
// This room is no longer in followers-only mode.
// duration is in minutes (string)
// -1 when /followersoff (string)
// false when /followers with no duration (boolean)
if(_.hasOwn(message.tags, 'followers-only')) {
if(message.tags['followers-only'] === '-1') {
const disabled = [ channel, false, 0 ];
this.log.info(`[${channel}] This room is no longer in followers-only mode.`);
this.emits([ 'followersonly', 'followersmode', '_promiseFollowersoff' ], [ disabled, disabled, [ null ] ]);
}
else {
const minutes = ~~message.tags['followers-only'];
const enabled = [ channel, true, minutes ];
this.log.info(`[${channel}] This room is now in follower-only mode.`);
this.emits([ 'followersonly', 'followersmode', '_promiseFollowers' ], [ enabled, enabled, [ null ] ]);
}
}
}
break;
// Wrong cluster
case 'SERVERCHANGE':
break;
default:
this.log.warn(`Could not parse message from tmi.twitch.tv:\n${JSON.stringify(message, null, 4)}`);
break;
}
}
// Messages from jtv
else if(message.prefix === 'jtv') {
switch(message.command) {
case 'MODE':
if(msg === '+o') {
// Add username to the moderators
if(!this.moderators[channel]) {
this.moderators[channel] = [];
}
if(!this.moderators[channel].includes(message.params[2])) {
this.moderators[channel].push(message.params[2]);
}
this.emit('mod', channel, message.params[2]);
}
else if(msg === '-o') {
// Remove username from the moderators
if(!this.moderators[channel]) {
this.moderators[channel] = [];
}
this.moderators[channel].filter(value => value !== message.params[2]);
this.emit('unmod', channel, message.params[2]);
}
break;
default:
this.log.warn(`Could not parse message from jtv:\n${JSON.stringify(message, null, 4)}`);
break;
}
}
// Anything else
else {
switch(message.command) {
case '353':
this.emit('names', message.params[2], message.params[3].split(' '));
break;
case '366':
break;
// Someone has joined the channel
case 'JOIN': {
const [ nick ] = message.prefix.split('!');
const matchesUsername = this.username === nick;
const isSelfAnon = matchesUsername && _.isJustinfan(this.getUsername());
// Joined a channel as a justinfan (anonymous) user
if(isSelfAnon) {
this.lastJoined = channel;
this.channels.push(channel);
this.log.info(`Joined ${channel}`);
this.emit('join', channel, nick, true);
}
// Someone else joined the channel, just emit the join event
else if(!matchesUsername) {
this.emit('join', channel, nick, false);
}
break;
}
// Someone has left the channel
case 'PART': {
const [ nick ] = message.prefix.split('!');
const isSelf = this.username === nick;
// Client left a channel
if(isSelf) {
if(this.userstate[channel]) {
delete this.userstate[channel];
}
let index = this.channels.indexOf(channel);
if(index !== -1) {
this.channels.splice(index, 1);
}