-
Notifications
You must be signed in to change notification settings - Fork 0
/
twitch-monitor.js
263 lines (210 loc) · 8.66 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
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");
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 = [];
}
static start() {
// Load channel names from config
this.channelNames = [];
config.twitch_channels.split(',').forEach((channelName) => {
if (channelName) {
this.channelNames.push(channelName.toLowerCase());
}
});
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 < TwitchMonitor.MIN_POLL_INTERVAL_MS) {
// Enforce minimum poll interval to help avoid rate limits
checkIntervalMs = TwitchMonitor.MIN_POLL_INTERVAL_MS;
}
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 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) {
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;
}
})
}
// 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 gotChannelNames = [];
users.forEach((user) => {
const channelName = user.login.toLowerCase();
let prevUserData = this._userData[channelName] || { };
this._userData[channelName] = Object.assign({ }, prevUserData, user);
gotChannelNames.push(user.display_name);
});
if (gotChannelNames.length) {
console.debug('[TwitchMonitor]', 'Updated user info:', gotChannelNames.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[channelName] || { };
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;
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.activeStreams = [];
TwitchMonitor.streamData = { };
TwitchMonitor.channelLiveCallbacks = [];
TwitchMonitor.channelOfflineCallbacks = [];
TwitchMonitor.MIN_POLL_INTERVAL_MS = 30000;
module.exports = TwitchMonitor;
TwitchMonitor.__init();