forked from roydejong/timbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitch-monitor.js
295 lines (236 loc) · 10.4 KB
/
twitch-monitor.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
const config = require('./config.json');
const TwitchApi = require('./twitch-api');
const MiniDb = require('./minidb');
const moment = require('moment');
class TwitchMonitor {
static __init() {
this._userDb = new MiniDb("twitch-users-v2");
this._gameDb = new MiniDb("twitch-games");
this._lastUserRefresh = this._userDb.get("last-update") || null;
this._pendingUserRefresh = false;
this._userData = this._userDb.get("user-list") || { };
this._pendingGameRefresh = false;
this._gameData = this._gameDb.get("game-list") || { };
this._watchingGameIds = [];
this.channelNames = [];
this.activeStreams = [];
this.streamData = {};
this.channelLiveCallbacks = [];
this.channelOfflineCallbacks = [];
this.MIN_POLL_INTERVAL_MS = 30000;
}
static start() {
// Check if configuration is set up correctly
if (config.twitch_channels === "blank" || !config.twitch_channels.trim()) {
console.warn('[Discord]', 'Configuration problem /!\\ Twitch channels not set up yet');
return;
}
const announceChannel = typeof config.discord_announce_channel === 'string' ? config.discord_announce_channel : '';
if (announceChannel === "blank") {
console.warn('[Discord]', 'Configuration problem /!\\ Announce channel not set up yet');
}
if (Object.keys(config.discord_mentions).length === 1 && config.discord_mentions.blank === "blank") {
console.warn('[Discord]', 'Configuration problem /!\\ Discord mentions not set up yet');
}
if (typeof config.discord_bot_token !== 'string' || config.discord_bot_token === "blank" || !config.discord_bot_token.trim()) {
console.warn('[Discord]', 'Configuration problem /!\\ Discord bot token not set up yet');
}
if (typeof config.twitch_client_id !== 'string' || config.twitch_client_id === "blank" || !config.twitch_client_id.trim()) {
console.warn('[Twitch]', 'Configuration problem /!\\ Twitch client ID not set up yet');
}
if (typeof config.twitch_oauth_token !== 'string' || config.twitch_oauth_token === "blank" || !config.twitch_oauth_token.trim()) {
console.warn('[Twitch]', 'Configuration problem /!\\ Twitch OAuth token not set up yet');
}
// Load channel names from config
this.channelNames = config.twitch_channels.split(',').map(channelName => channelName.trim().toLowerCase()).filter(Boolean);
if (!this.channelNames.length) {
console.warn('[TwitchMonitor]', 'No channels configured');
return;
}
// Configure polling interval
let checkIntervalMs = parseInt(config.twitch_check_interval_ms);
if (isNaN(checkIntervalMs) || checkIntervalMs < this.MIN_POLL_INTERVAL_MS) {
// Enforce minimum poll interval to help avoid rate limits
checkIntervalMs = this.MIN_POLL_INTERVAL_MS;
}
this.pollingInterval = setInterval(() => {
this.refresh("Periodic refresh");
}, checkIntervalMs + 1000);
// Immediate refresh after startup
setTimeout(() => {
this.refresh("Initial refresh after start-up");
}, 1000);
// Ready!
console.log('[TwitchMonitor]', `Configured stream status polling for channels:`, this.channelNames.join(', '),
`(${checkIntervalMs}ms interval)`);
}
static stop() {
if (this.pollingInterval) {
clearInterval(this.pollingInterval);
this.pollingInterval = null;
console.log('[TwitchMonitor]', 'Polling stopped.');
}
}
static refresh(reason) {
const now = moment();
console.log('[Twitch]', ' ▪ ▪ ▪ ▪ ▪ ', `Refreshing now (${reason ? reason : "No reason"})`, ' ▪ ▪ ▪ ▪ ▪ ');
// Refresh all users periodically
if (this._lastUserRefresh === null || now.diff(moment(this._lastUserRefresh), 'minutes') >= 10) {
this._pendingUserRefresh = true;
TwitchApi.fetchUsers(this.channelNames)
.then((users) => {
this.handleUserList(users);
})
.catch((err) => {
console.warn('[TwitchMonitor]', 'Error in users refresh:', err);
})
.then(() => {
if (this._pendingUserRefresh) {
this._pendingUserRefresh = false;
this.refresh('Got Twitch users, need to get streams');
}
})
}
// Refresh all games if needed
if (this._pendingGameRefresh) {
TwitchApi.fetchGames(this._watchingGameIds)
.then((games) => {
this.handleGameList(games);
})
.catch((err) => {
console.warn('[TwitchMonitor]', 'Error in games refresh:', err);
})
.then(() => {
if (this._pendingGameRefresh) {
this._pendingGameRefresh = false;
}
});
}
// Refresh all streams
if (!this._pendingUserRefresh && !this._pendingGameRefresh) {
TwitchApi.fetchStreams(this.channelNames)
.then((channels) => {
this.handleStreamList(channels);
})
.catch((err) => {
console.warn('[TwitchMonitor]', 'Error in streams refresh:', err);
});
}
}
static handleUserList(users) {
let namesSeen = [];
users.forEach((user) => {
let prevUserData = this._userData[user.id] || { };
this._userData[user.id] = Object.assign({}, prevUserData, user);
namesSeen.push(user.display_name);
});
if (namesSeen.length) {
console.debug('[TwitchMonitor]', 'Updated user info:', namesSeen.join(', '));
}
this._lastUserRefresh = moment();
this._userDb.put("last-update", this._lastUserRefresh);
this._userDb.put("user-list", this._userData);
}
static handleGameList(games) {
let gotGameNames = [];
games.forEach((game) => {
const gameId = game.id;
let prevGameData = this._gameData[gameId] || { };
this._gameData[gameId] = Object.assign({}, prevGameData, game);
gotGameNames.push(`${game.id} → ${game.name}`);
});
if (gotGameNames.length) {
console.debug('[TwitchMonitor]', 'Updated game info:', gotGameNames.join(', '));
}
this._lastGameRefresh = moment();
this._gameDb.put("last-update", this._lastGameRefresh);
this._gameDb.put("game-list", this._gameData);
}
static handleStreamList(streams) {
// Index channel data & build list of stream IDs now online
let nextOnlineList = [];
let nextGameIdList = [];
streams.forEach((stream) => {
const channelName = stream.user_name.toLowerCase();
if (stream.type === "live") {
nextOnlineList.push(channelName);
}
let userDataBase = this._userData[stream.user_id] || { };
let prevStreamData = this.streamData[channelName] || { };
this.streamData[channelName] = Object.assign({}, userDataBase, prevStreamData, stream);
this.streamData[channelName].game = (stream.game_id && this._gameData[stream.game_id]) || null;
this.streamData[channelName].user = userDataBase;
if (stream.game_id) {
nextGameIdList.push(stream.game_id);
}
});
// Find channels that are now online, but were not before
let notifyFailed = false;
let anyChanges = false;
for (let i = 0; i < nextOnlineList.length; i++) {
let _chanName = nextOnlineList[i];
if (this.activeStreams.indexOf(_chanName) === -1) {
// Stream was not in the list before
console.log('[TwitchMonitor]', 'Stream channel has gone online:', _chanName);
anyChanges = true;
}
if (!this.handleChannelLiveUpdate(this.streamData[_chanName], true)) {
notifyFailed = true;
}
}
// Find channels that are now offline, but were online before
for (let i = 0; i < this.activeStreams.length; i++) {
let _chanName = this.activeStreams[i];
if (nextOnlineList.indexOf(_chanName) === -1) {
// Stream was in the list before, but no longer
console.log('[TwitchMonitor]', 'Stream channel has gone offline:', _chanName);
this.streamData[_chanName].type = "detected_offline";
this.handleChannelOffline(this.streamData[_chanName]);
anyChanges = true;
}
}
if (!notifyFailed) {
// Notify OK, update list
this.activeStreams = nextOnlineList;
} else {
console.log('[TwitchMonitor]', 'Could not notify channel, will try again next update.');
}
if (!this._watchingGameIds.hasEqualValues(nextGameIdList)) {
// We need to refresh game info
this._watchingGameIds = nextGameIdList;
this._pendingGameRefresh = true;
this.refresh("Need to request game data");
}
}
static handleChannelLiveUpdate(streamData, isOnline) {
for (let i = 0; i < this.channelLiveCallbacks.length; i++) {
let _callback = this.channelLiveCallbacks[i];
if (_callback) {
if (_callback(streamData, isOnline) === false) {
return false;
}
}
}
return true;
}
static handleChannelOffline(streamData) {
this.handleChannelLiveUpdate(streamData, false);
for (let i = 0; i < this.channelOfflineCallbacks.length; i++) {
let _callback = this.channelOfflineCallbacks[i];
if (_callback) {
if (_callback(streamData) === false) {
return false;
}
}
}
return true;
}
static onChannelLiveUpdate(callback) {
this.channelLiveCallbacks.push(callback);
}
static onChannelOffline(callback) {
this.channelOfflineCallbacks.push(callback);
}
}
TwitchMonitor.__init();
module.exports = TwitchMonitor;