/
mixer-chat.js
1218 lines (1033 loc) · 43.7 KB
/
mixer-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
'use strict';
const request = require('request');
const mixerInteractive = require('./mixer-interactive.js');
const Mixer = require('@mixer/client-node');
const ws = require('ws');
const dataAccess = require('./data-access.js');
const {ipcMain} = require('electron');
const Grouper = require('../interactive/auto-grouper');
const commandRouter = require("../chat/command-router.js");
const timedCommands = require("../chat/timed-commands.js");
const chatProcessor = require("../common/handlers/chatProcessor.js");
const reconnectService = require('./reconnect.js');
const logger = require('../logwrapper');
const { LiveEvent, EventType, EventSourceType } = require('../live-events/EventType');
const eventRouter = require('../live-events/events-router');
const accountAccess = require('./account-access');
require('request-debug')(request, function(type, data) {
logger.debug("Request debug: ", { type: type, data: data });
});
const streamerClient = new Mixer.Client(new Mixer.DefaultRequestRunner());
const botClient = new Mixer.Client(new Mixer.DefaultRequestRunner());
// Options
let options = {
cliendId: 'f78304ba46861ddc7a8c1fb3706e997c3945ef275d7618a9'
};
// This holds the connection status of chat.
let chatConnected = false;
// Holds a cache of all commands.
let commandCache = [];
// Get User Info
// This grabs the user info of a person in chat.
function getChatUserInfo(userID, callback) {
let dbAuth = dataAccess.getJsonDbInUserData("/user-settings/auth");
let streamer = dbAuth.getData('/streamer');
// Request User Info and return response.
streamerClient.request('GET', `chats/` + streamer['channelId'] + '/users/' + userID).then(response => {
callback(response);
})
.catch(error => {
// Log error for dev.
logger.error("error getting chat user info", error);
callback(null);
});
}
function getUserInfo(userID, callback) {
// Request User Info and return response.
streamerClient.request('GET', "users/" + userID).then(response => {
let user = response.body;
callback(user);
})
.catch(error => {
// Log error for dev.
logger.error("error while getting user info", error);
callback(null);
});
}
function updateStreamTitle(title) {
logger.info("updating channel title to: " + title);
let dbAuth = dataAccess.getJsonDbInUserData("/user-settings/auth");
let streamer = dbAuth.getData('/streamer');
request.patch('https://mixer.com/api/v1/channels/' + streamer['channelId'], {
'auth': {
'bearer': streamer['accessToken']
},
'body': {
name: title
},
json: true
}, (err) => {
if (err) {
logger.error("error setting title for channel", err);
}
});
}
function updateStreamAudience(audienceType) {
logger.info("updating channel aud to: " + audienceType);
let dbAuth = dataAccess.getJsonDbInUserData("/user-settings/auth");
let streamer = dbAuth.getData('/streamer');
request.patch('https://mixer.com/api/v1/channels/' + streamer['channelId'], {
'auth': {
'bearer': streamer['accessToken']
},
'body': {
audience: audienceType
},
json: true
}, (err) => {
if (err) {
logger.error("error setting audience for channel", err);
}
});
}
function updateStreamGame(gameQuery) {
logger.info("updating channel game to: " + gameQuery);
let dbAuth = dataAccess.getJsonDbInUserData("/user-settings/auth");
let streamer = dbAuth.getData('/streamer');
streamerClient.request('GET', 'types', {
qs: {
query: gameQuery
}
})
.then(res => {
let gameList = res.body;
logger.silly(gameList);
if (gameList != null && Array.isArray(gameList) && gameList.length > 0) {
let firstGame = gameList[0];
request.patch('https://mixer.com/api/v1/channels/' + streamer['channelId'], {
'auth': {
'bearer': streamer['accessToken']
},
'body': {
typeId: firstGame.id
},
json: true
}, (err) => {
if (err) {
logger.error("error setting game for channel", err);
}
});
}
}, function (err) {
logger.error("error while looking up games", err);
});
}
function getCurrentBroadcast() {
let streamerData = accountAccess.getAccounts().streamer;
return streamerClient.request("GET", `channels/${streamerData.channelId}/broadcast`)
.then(resp => {
if (resp.statusCode === 200)
return resp.body;
return null;
});
}
function requestAsStreamer(method, route, body) {
return new Promise(resolve => {
//updating account cache
accountAccess.updateAccountCache();
let streamerData = accountAccess.getAccounts().streamer;
let options = {
url: `https://mixer.com/api/v1/${route}`,
method: method,
headers: {
'User-Agent': 'MixerClient/0.13.0 (JavaScript; Node.js v6.5.0)',
'Authorization': `Bearer ${streamerData.accessToken}`
},
json: true,
body: body
};
request(options, function(err, res) {
resolve(res);
});
});
}
function createClip(title, duration) {
return new Promise(async resolve => {
logger.info("Attempting to create clip...");
let clipResult = { success: false };
let streamerData = accountAccess.getAccounts().streamer;
if (!streamerData.partnered && !streamerData.canClip) {
logger.warn("An unapproved user type attempted to create a clip!");
clipResult.reason = "Not allowed to create clips!";
return resolve(clipResult);
}
let currentBroadcast = await getCurrentBroadcast();
if (currentBroadcast == null) {
clipResult.reason = "Not currently broadcasting";
return resolve(clipResult);
}
// make sure duration is valid
if (isNaN(duration)) {
duration = 30;
} else if (duration < 15) {
duration = 15;
} else if (duration > 300) {
duration = 300;
}
let createClipRequest = {
broadcastId: currentBroadcast.id,
clipDurationInSeconds: duration
};
if (title != null) {
createClipRequest.highlightTitle = title;
}
logger.info(`Creating clip with title '${title}' and duration of ${duration}s for broadcast Id ${currentBroadcast.id}`);
let createClipResponse = await requestAsStreamer('POST', 'clips/create', createClipRequest);
logger.debug("Create clip response:");
logger.debug(createClipResponse.statusCode);
logger.debug(createClipResponse.statusMessage);
logger.debug(createClipResponse.body);
if (createClipResponse.statusCode === 200) {
clipResult.success = true;
clipResult.highlightResponse = createClipResponse.body;
} else {
clipResult.reason = `Create clip call to Mixer failed (status code ${createClipResponse.statusCode}`;
}
resolve(clipResult);
});
}
// Refreshes the commands cache
function refreshCommandCache(retry) {
// FB: I've set a weird retry thing here because I ran into a rare issue where upon saving settings the app tried to
// save and get the same file at the same time which threw errors and caused the cache to get out
// of sync.
if (retry === null || retry === undefined) {
retry = 1;
}
// Get commands file
let dbCommands = dataAccess.getJsonDbInUserData("/user-settings/chat/commands");
if (dbCommands === undefined || dbCommands === null) return;
// We've got the last used board! Let's update the interactive cache.
if (dbCommands != null) {
if (retry <= 3) {
try {
// Get settings for last board.
let commands = dbCommands.getData('/');
commandCache = commands;
logger.info('Updated Command cache.');
} catch (err) {
logger.info('Command cache update failed. Retrying. (Try ' + retry + '/3)');
retry = retry + 1;
refreshCommandCache(retry);
}
} else {
renderWindow.webContents.send('error', "Could not sync up command cache. Reconnect to try resyncing.");
}
}
}
refreshCommandCache();
// Creates the chat websocket
// This sets up and auths with the chat websocket.
function createChatSocket (chatter, userId, channelId, endpoints, authkey) {
return new Promise((resolve, reject) => {
if (authkey != null) {
// Connect
const socket = new Mixer.Socket(ws, endpoints).boot();
// Handle errors
// Without this the app seems to hang when the socket connection above gets server errors back.
// With this the socket above seems to search for the next working connection point automatically.
socket.on('error', error => {
logger.error("error from chat socket", error);
});
// Confirm login.
if (chatter === "Streamer") {
socket.auth(channelId, userId, authkey)
.then((res) => {
if (res.authenticated === true) {
global.streamerChat = socket;
resolve("Streamer");
} else {
logger.error(chatter + ' did not authenticate successfully.');
reject(res);
}
})
.catch(err => {
reject(err);
});
} else if (chatter === "Bot") {
socket.auth(channelId, userId, authkey)
.then((res) => {
if (res.authenticated === true) {
global.botChat = socket;
resolve("Bot");
} else {
logger.error(chatter + ' did not authenticate successfully.');
reject(res);
}
})
.catch(err => {
reject(err);
});
} else {
reject('Error creating chat socket for ' + chatter + '.');
}
} else {
logger.info('No auth key provided to connect to chat for ' + chatter);
}
});
}
// Sets up chat data processing
// This sets up chat data processing after chat sockets are connected and created.
function createChatDataProcessing(chatter) {
return new Promise((resolve, reject) => {
let socket = [];
logger.debug("Creating chat data proccessing");
// Refresh all caches.
refreshCommandCache();
mixerInteractive.refreshInteractiveCache();
// Get controls to send on.
let interactiveCache = mixerInteractive.getInteractiveCache();
interactiveCache = interactiveCache['firebot'];
// Setup all data processing!
if (chatter === "Streamer") {
socket = global.streamerChat;
// React to chat messages
socket.on('ChatMessage', data => {
// Send to command router to see if we need to act on a command.
commandRouter.handleChatCommand(data, 'streamer', interactiveCache, commandCache);
logger.debug("Recieved chat", data);
if (data.message.meta.whisper === true) {
if (data.user_name !== accountAccess.getAccounts().bot.username) {
// Send to UI to show in chat window.
chatProcessor.uiChatMessage(data);
}
} else {
chatProcessor.uiChatMessage(data);
}
// Send event
let event = new LiveEvent(EventType.CHAT_MESSAGE, EventSourceType.CHAT, {username: data.user_name, data: data});
eventRouter.uncachedEvent(event);
});
// User joined the channel
socket.on('UserJoin', data => {
data.fbEvent = 'UserJoin';
renderWindow.webContents.send('chatUpdate', data);
let event = new LiveEvent(EventType.USER_JOINED_CHAT, EventSourceType.CHAT, {username: data.username, data: data});
eventRouter.uncachedEvent(event);
});
// User left the channel.
socket.on('UserLeave', data => {
data.fbEvent = 'UserLeave';
renderWindow.webContents.send('chatUpdate', data);
let event = new LiveEvent(EventType.USER_LEAVE_CHAT, EventSourceType.CHAT, {username: data.username, data: data});
eventRouter.uncachedEvent(event);
});
// Poll Started
socket.on('PollStart', data => {
data.fbEvent = 'PollStart';
renderWindow.webContents.send('chatUpdate', data);
let event = new LiveEvent(EventType.POLL_STARTED, EventSourceType.CHAT, {username: data.author.user_name, data: data});
eventRouter.cachedEvent(event, data.endsAt);
});
// Poll End
socket.on('PollEnd', data => {
data.fbEvent = 'PollEnd';
renderWindow.webContents.send('chatUpdate', data);
let event = new LiveEvent(EventType.POLL_ENDED, EventSourceType.CHAT, {username: data.author.user_name, data: data});
eventRouter.uncachedEvent(event);
});
// Deleted Message
socket.on('DeleteMessage', data => {
data.fbEvent = 'DeleteMessage';
renderWindow.webContents.send('chatUpdate', data);
logger.debug("delete" + JSON.stringify(data));
let event = new LiveEvent(EventType.MESSAGE_DELETED, EventSourceType.CHAT, {username: data.moderator.user_name, data: data});
eventRouter.uncachedEvent(event);
});
// Purge Message
// Provides a moderator object if messages purged due to a ban.
socket.on('PurgeMessage', data => {
data.fbEvent = 'PurgeMessage';
renderWindow.webContents.send('chatUpdate', data);
getUserInfo(data.user_id, (user) => {
logger.info('username ' + user.username);
let event;
//if purge has moderator, it was a timeout/purge
if (data.moderator !== undefined) {
event = new LiveEvent(EventType.MESSAGE_PURGED, EventSourceType.CHAT, {username: user.username});
//otherwise it was the result of a ban
} else {
event = new LiveEvent(EventType.USER_BANNED, EventSourceType.CHAT, {username: user.username});
}
eventRouter.cachedEvent(event);
});
});
// Clear Messages
socket.on('ClearMessages', data => {
data.fbEvent = 'ClearMessages';
renderWindow.webContents.send('chatUpdate', data);
let event = new LiveEvent(EventType.CHAT_CLEARED, EventSourceType.CHAT, {username: data.clearer.user_name, data: data});
eventRouter.uncachedEvent(event);
});
// User Update
// Bans, subscribes, modding, etc...
socket.on('UserUpdate', data => {
data.fbEvent = 'UserUpdate';
renderWindow.webContents.send('chatUpdate', data);
});
// User Timeout - Probably won't happen
socket.on('UserTimeout', data => {
data.fbEvent = 'UserTimeout';
renderWindow.webContents.send('chatUpdate', data);
// let event = new LiveEvent(EventType.USER_TIMEOUT, EventSourceType.CHAT, {username: data.user.user_name, data: data});
// eventRouter.uncachedEvent(event);
});
let reconnectChat = () => {
socket.close();
// Set connection status to offline
renderWindow.webContents.send('chatConnection', "Offline");
// Set chat connection to offline.
chatConnected = false;
// Clear current chat messages and display alert message. It will resync them all on reconnect.
renderWindow.webContents.send('chatUpdate', {fbEvent: "Disconnected"});
// Try to reconnect
reconnectService.reconnect('Chat', false, false);
};
// Handle errors
socket.on('error', error => {
// Log for dev.
logger.error("error from streamer chat socket", error);
reconnectChat();
});
socket.on('closed', () => {
if (chatConnected) {
reconnectChat();
}
});
resolve(true);
} else if (chatter === "Bot") {
socket = global.botChat;
// React to chat messages
socket.on('ChatMessage', data => {
commandRouter.handleChatCommand(data, 'bot', interactiveCache, commandCache);
if (data.message.meta.whisper === true) {
if (data.user_name !== accountAccess.getAccounts().streamer.username) {
// Send to UI to show in chat window.
chatProcessor.uiChatMessage(data);
}
}
});
let reconnectChat = () => {
socket.close();
// Set connection status to offline
renderWindow.webContents.send('chatConnection', "Offline");
// Set chat connection to offline.
chatConnected = false;
// Try to reconnect
reconnectService.reconnect('Chat', false, false);
};
// Handle errors
socket.on('error', error => {
// Log for dev.
logger.error("error from bot chat socket", error);
reconnectChat();
});
socket.on('closed', () => {
if (chatConnected) {
reconnectChat();
}
});
resolve(true);
}
reject('Invalid user given to chat data process setup.');
});
}
// Disconnect from chat
// This should gracefully disconnect from chat.
function chatDisconnect() {
if (global.streamerChat != null) {
logger.info('Disconnecting streamer chat.');
global.streamerChat.close();
global.streamerChat = null;
// Stop timed command loop.
timedCommands.timedCmdLoop(false);
}
if (global.botChat != null) {
logger.info('Disconnecting bot chat.');
global.botChat.close();
global.botChat = null;
}
// Set connection status to offline
renderWindow.webContents.send('chatConnection', "Offline");
// Set chat connection to offline.
chatConnected = false;
}
// Get current viewers
function getCurrentViewers() {
logger.info('Attempting to get current viewer count');
let dbAuth = dataAccess.getJsonDbInUserData("/user-settings/auth"),
streamer = dbAuth.getData('/streamer');
return streamerClient.request('GET', 'channels/' + streamer.channelId, {
qs: {
fields: 'viewersCurrent'
}
})
.then(res => {
return res.body.viewersCurrent;
}, function (err) {
logger.error("error while getting current viewers", err);
return 0;
});
}
function getCurrentViewerList() {
logger.info('Attempting to get current viewer count');
let dbAuth = dataAccess.getJsonDbInUserData("/user-settings/auth"),
streamer = dbAuth.getData('/streamer');
return streamerClient.request('GET', 'chats/' + streamer.channelId + "/users", {
qs: {
fields: 'userName'
}
})
.then(res => {
let usernames = res.body.map(u => u.userName);
usernames.push(streamer.username);
return usernames;
}, function (err) {
logger.error("error while getting current viewer list", err);
return [];
});
}
// Gets general channel data, defaults to streamer data
exports.getGeneralChannelData = function(channelNameOrId, getBroadcastData = true) {
return new Promise(async resolve => {
if (channelNameOrId == null) {
let dbAuth = dataAccess.getJsonDbInUserData("/user-settings/auth"),
streamer = dbAuth.getData('/streamer');
channelNameOrId = streamer.channelId;
}
let generalDeets = {};
try {
let data = await streamerClient.request('GET', 'channels/' + channelNameOrId, {
qs: {
fields: 'online,name,type,id,userId,token,viewersCurrent'
}
});
generalDeets = data.body;
} catch (err) {
logger.error("error while getting channel deets", err);
resolve(null);
return;
}
if (getBroadcastData && generalDeets.online === true) {
try {
let broadcastData = await streamerClient.request('GET', `channels/${generalDeets.id}/broadcast`, {
qs: {
fields: 'startedAt'
}
});
generalDeets.startedAt = broadcastData.body.startedAt;
} catch (err) {
logger.error("error while getting broadcast deets", err);
}
}
resolve(generalDeets);
});
};
// Streamer Chat Connect
// This checks to see if the streamer is logged into the app, and if so it will connect them to chat.
function streamerConnect(streamer) {
return new Promise((resolve) => {
let userInfo;
// Bot Login
streamerClient.use(new Mixer.OAuthProvider(streamerClient, {
clientId: options.cliendId,
tokens: {
access: streamer.accessToken,
expires: Date.now() + (365 * 24 * 60 * 60 * 1000)
}
}));
getCurrentViewers().then(currentViewers => {
renderWindow.webContents.send('currentViewersUpdate', { viewersCurrent: currentViewers });
});
// Request chat endpoints and connect.
streamerClient.request('GET', `users/` + streamer['userId'])
.then(response => {
userInfo = response.body;
return new Mixer.ChatService(streamerClient).join(response.body.channel.id);
})
.catch(error => {
// Popup error.
renderWindow.webContents.send('error', "Error getting chat endpoints. Did you lose connection?");
// Set connection status to offline
renderWindow.webContents.send('chatConnection', "Offline");
// Log error for dev.
logger.error("error while getting user", error);
// Try to reconnect
chatConnected = false;
reconnectService.reconnect('Chat', false, false);
return {then: function() {} };
})
.then(response => {
const body = response.body;
return createChatSocket("Streamer", userInfo.id, userInfo.channel.id, body.endpoints, body.authkey);
})
.catch(error => {
// Popup error.
renderWindow.webContents.send('error', "Error creating chat socket.");
// Set connection status to offline
renderWindow.webContents.send('chatConnection', "Offline");
// Log error for dev.
logger.error("error while creating chat socket", error);
// Try to reconnect
chatConnected = false;
reconnectService.reconnect('Chat', false, false);
return {then: function() {} };
})
.then(response => {
return createChatDataProcessing(response);
})
.catch(error => {
// Popup error.
renderWindow.webContents.send('error', "Error setting up chat data processing for Streamer.");
// Set connection status to offline
renderWindow.webContents.send('chatConnection', "Offline");
// Log error for dev.
logger.error("error while setting up chat data proccess for streamer", error);
// Try to reconnect
chatConnected = false;
reconnectService.reconnect('Chat', false, false);
return {then: function() {} };
})
.then(() => {
// Update streamer name for chat permissions.
commandRouter.updateStreamerUsername();
accountAccess.updateAccountCache();
})
.catch(error => {
// Popup error.
renderWindow.webContents.send('error', "Error updating username cache for commands.");
// Set connection status to offline
renderWindow.webContents.send('chatConnection', "Offline");
// Log error for dev.
logger.error("error while upping username case for commands", error);
// Try to reconnect
chatConnected = false;
reconnectService.reconnect('Chat', false, false);
return {then: function() {} };
})
.catch(error => {
// Popup error.
renderWindow.webContents.send('error', "Error starting timed commands or auto grouper.");
// Set connection status to offline
renderWindow.webContents.send('chatConnection', "Offline");
// Log error for dev.
logger.error("error while trying to start timed commands", error);
// Try to reconnect
chatConnected = false;
reconnectService.reconnect('Chat', false, false);
return {then: function() {} };
})
.then(() => {
// Get chat history and send it to ui.
chatProcessor.uiGetChatHistory(streamerClient);
// Get chat user list and send it to ui.
chatProcessor.uiChatUserRefresh(0, []);
})
.catch(error => {
// Popup error.
renderWindow.webContents.send('error', "Error getting chat history or refreshing chat userlist.");
// Set connection status to offline
renderWindow.webContents.send('chatConnection', "Offline");
// Log error for dev.
logger.error("error while error getting chat history", error);
// Try to reconnect
chatConnected = false;
reconnectService.reconnect('Chat', false, false);
return {then: function() {} };
})
.then(() => {
// Set connection status to online
renderWindow.webContents.send('chatConnection', "Online");
// Set chat connection to online.
chatConnected = true;
// Start timed command loop.
timedCommands.timedCmdLoop(true);
// Start auto grouper if both chat and interactive connected.
// This auto groups people for interactive groups and depends on chat being connected.
Grouper.startQueue();
// Fire the chat connected event.
let event = new LiveEvent(EventType.CHAT_CONNECTED, EventSourceType.FIREBOT, {username: "Firebot"});
eventRouter.uncachedEvent(event);
resolve(true);
})
.catch(error => {
// Popup error.
renderWindow.webContents.send('error', "Error finishing chat connection processes.");
// Set connection status to offline
renderWindow.webContents.send('chatConnection', "Offline");
// Log error for dev.
logger.error("error while finsing chat connection processes", error);
// Try to reconnect
chatConnected = false;
reconnectService.reconnect('Chat', false, false);
return {then: function() {} };
});
});
}
// Bot Chat Connect
// This checks to see if bot info is available, and if so it will connect them to chat.
function botConnect(botter) {
return new Promise((resolve, reject) => {
if (botter !== []) {
let userInfo,
dbAuth = dataAccess.getJsonDbInUserData("/user-settings/auth"),
streamer = dbAuth.getData('/streamer');
// Bot Login
botClient.use(new Mixer.OAuthProvider(botClient, {
clientId: options.cliendId,
tokens: {
access: botter.accessToken,
expires: Date.now() + (365 * 24 * 60 * 60 * 1000)
}
}));
// Request chat endpoints and connect.
botClient.request('GET', `users/` + botter['userId'])
.then(response => {
userInfo = response.body;
return new Mixer.ChatService(botClient).join(streamer['channelId']);
})
.catch(error => {
// Popup error.
renderWindow.webContents.send('error', "Error getting chat endpoints.");
// Set connection status to offline
renderWindow.webContents.send('chatConnection', "Offline");
// Log error for dev.
logger.error("error while getting chat endpoints", error);
// Try to reconnect
chatConnected = false;
reconnectService.reconnect('Chat', false, false);
return {then: function() {} };
})
.then(response => {
const body = response.body;
return createChatSocket("Bot", userInfo.id, streamer['channelId'], body.endpoints, body.authkey);
})
.catch(error => {
// Popup error.
renderWindow.webContents.send('error', "Couldnt connect to chat as the bot.");
// Set connection status to offline
renderWindow.webContents.send('chatConnection', "Offline");
// Log error for dev.
logger.error("error while connecting to chat as bot", error);
// Try to reconnect
chatConnected = false;
reconnectService.reconnect('Chat', false, false);
return {then: function() {} };
})
.then(response => {
return createChatDataProcessing(response);
})
.catch(error => {
// Popup error.
renderWindow.webContents.send('error', "Error setting up chat data processing for Bot.");
// Set connection status to offline
renderWindow.webContents.send('chatConnection', "Offline");
// Log error for dev.
logger.error("error while setting up chat processing for bot", error);
// Try to reconnect
chatConnected = false;
reconnectService.reconnect('Chat', false, false);
return {then: function() {} };
})
.then(() => {
resolve(true);
})
.catch(error => {
reject(error);
// Log error for dev.
//logger.error(error);
// Try to reconnect
chatConnected = false;
reconnectService.reconnect('Chat', false, false);
return {then: function() {} };
});
} else {
resolve(true);
}
});
}
// Chat Connector
// This function connects to mixer chat and monitors messages.
function chatConnect() {
return new Promise((resolve, reject) => {
let dbAuth = dataAccess.getJsonDbInUserData("/user-settings/auth"),
streamer = [],
botter = [];
// Get streamer data.
try {
streamer = dbAuth.getData('/streamer');
} catch (err) {
renderWindow.webContents.send('error', "You need to sign into the app as a streamer to connect to chat.");
reject(err);
return;
}
// Get Bot Data
try {
botter = dbAuth.getData('/bot');
} catch (err) {
logger.info('No bot logged in. Skipping. (chat-connect)');
}
// Connect Kickoff
streamerConnect(streamer)
.then(() => {
botConnect(botter);
})
.catch(err => {
logger.error("error while connecting streamer/bot", err);
reject(err);
});
});
}
// Whisper
// Send a whisper to a specific person from whoever the chatter is (streamer or bot).
function whisper(chatter, username, message) {
if (message == null || message.trim() === "") {
return;
}
if (message.length > 360) {
message = message.substring(0, 359);
}
// Normalize the chatter type
chatter = chatter.toLowerCase();
if (chatter === "streamer") {
try {
global.streamerChat.call('whisper', [username, message]);
logger.info('Sent message as ' + chatter + '.');
} catch (err) {
logger.eror("error sending whisper as streamer", err);
renderWindow.webContents.send('error', "There was an error sending a whisper to chat as the streamer. If you are testing a chat button, please make sure Interactive is connected.");
}
} else if (chatter === "bot") {
try {
global.botChat.call('whisper', [username, message]);
logger.info('Sent message as ' + chatter + '.');
} catch (err) {
logger.error("error sending whisper as bot", err);
renderWindow.webContents.send('error', "There was an error sending a whisper to chat as the bot. If you are testing a chat button, please make sure Interactive is connected.");
}
}
}
// Broadcast
// Send a broadcast to the channel from whoever the chatter is (streamer or bot).
function broadcast(chatter, message) {
if (message == null || message.trim() === "") {
return;
}
if (message.length > 360) {
message = message.substring(0, 359);
}
// Normalize the chatter type
chatter = chatter.toLowerCase();
if (chatter === "streamer") {
try {
global.streamerChat.call('msg', [message]);
logger.info('Sent message as ' + chatter + '.');
} catch (err) {
logger.error("error sending chat as streamer", err);
renderWindow.webContents.send('error', "There was an error sending a message to chat as the streamer. If you are testing a chat button, please make sure Interactive is connected.");
}
} else if (chatter === "bot") {