-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
510 lines (435 loc) · 15.9 KB
/
index.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
const fs = require( 'fs' );
require( 'dotenv' ).config();
const tmi = require( 'tmi.js' );
const got = require( 'got' );
const chalk = require( 'chalk' );
const blessed = require( 'blessed' );
const contrib = require( 'blessed-contrib' );
const chunk = require( 'lodash.chunk' );
const timestamp = require( 'time-stamp' );
const now = require( 'performance-now' );
let liveStreams = [];
let devAccounts = {};
let twitchNames = {};
let extraStreams = {};
let games;
let gamesToCheck = [];
const posts = [];
const context = [];
const screen = blessed.screen();
let twitchClient = false;
const grid = new contrib.grid( {
rows: 12,
cols: 12,
screen: screen
} );
const lineStats = {
title: 'texts',
x: [],
y: [],
};
const MAX_LINE_POINTS = 30;
//grid.set(row, col, rowSpan, colSpan, obj, opts)
const messageLog = grid.set(0, 0, 9, 4, contrib.log, {
fg: 'green',
selectedFg: 'green',
label: 'Message Log'
});
const performanceLine = grid.set(9, 0, 3, 4, contrib.line, {
style: {
line: 'yellow',
ext: 'green',
baseline: 'black'
},
xLabelPadding: 3,
xPadding: 5,
howLegend: true,
wholeNumbersOnly: true, //true=do not show fraction in y axis
label: 'Messages / second',
});
const devLog = grid.set(0, 4, 12, 4, contrib.log, {
fg: 'green',
selectedFg: 'green',
label: 'Dev Log'
});
const contextCount = grid.set( 0, 8, 3, 4, contrib.lcd, {
segmentWidth: 0.06, // how wide are the segments in % so 50% = 0.5
segmentInterval: 0.11, // spacing between the segments in % so 50% = 0.550% = 0.5
strokeWidth: 0.11, // spacing between the segments in % so 50% = 0.5
elements: 6, // how many elements in the display. or how many characters can be displayed.
display: 'ZERO', // what should be displayed before first call to setDisplay
elementSpacing: 4, // spacing between each element
elementPadding: 2, // how far away from the edges to put the elements
color: 'white', // color for the segments
label: 'Stored context objects'
} );
const contextSize = grid.set( 3, 8, 3, 4, contrib.lcd, {
segmentWidth: 0.06, // how wide are the segments in % so 50% = 0.5
segmentInterval: 0.11, // spacing between the segments in % so 50% = 0.550% = 0.5
strokeWidth: 0.11, // spacing between the segments in % so 50% = 0.5
elements: 9, // how many elements in the display. or how many characters can be displayed.
display: 'WAITING', // what should be displayed before first call to setDisplay
elementSpacing: 4, // spacing between each element
elementPadding: 2, // how far away from the edges to put the elements
color: 'white', // color for the segments
label: 'Context memory size'
} );
const systemLog = grid.set( 6, 8, 6, 4, contrib.log, {
fg: 'green',
selectedFg: 'green',
label: 'System Log'
});
screen.key(['escape', 'q', 'C-c'], function(ch, key) {
return process.exit(0);
});
screen.render();
const sleep = function sleep( ms ) {
return new Promise( ( resolve ) => {
setTimeout( resolve, ms );
} );
};
const logLine = function logLine( line, log, type = 'info' ) {
chunk( line.split( '' ), 55 ).forEach( ( arrayChunk ) => {
let lineToLog = arrayChunk.join( '' );
if ( type === 'error' ) {
// lineToLog = chalk.red( lineToLog );
}
log.log( lineToLog );
} );
};
const getUsersInChat = function getUsersInChat( streamName ) {
const dataUrl = `https://tmi.twitch.tv/group/user/${ streamName }/chatters`;
return got( dataUrl, {
json: true,
} );
};
const cleanContexts = function cleanContexts(){
if ( context.length === 0 ) {
return;
}
const timeSinceMessage = Date.now() - context[ context.length - 1 ].timestamp;
if ( timeSinceMessage >= 300000 ) {
context.pop();
cleanContexts();
}
};
const addMessageStat = function addMessageStat(){
const currentTimestamp = timestamp( 'HH:mm:ss' );
if ( lineStats.x.length > MAX_LINE_POINTS ) {
lineStats.x.shift();
lineStats.y.shift();
}
if ( lineStats.x[ lineStats.x.length - 1 ] !== currentTimestamp ) {
lineStats.x.push( currentTimestamp );
lineStats.y.push( 0 );
}
lineStats.y[ lineStats.y.length - 1 ] = lineStats.y[ lineStats.y.length - 1 ] + 1;
};
const memorySizeOf = function memorySizeOf(obj) {
var bytes = 0;
const decimalPlaces = 2;
function sizeOf(obj) {
if(obj !== null && obj !== undefined) {
switch(typeof obj) {
case 'number':
bytes += 8;
break;
case 'string':
bytes += obj.length * 2;
break;
case 'boolean':
bytes += 4;
break;
case 'object':
var objClass = Object.prototype.toString.call(obj).slice(8, -1);
if(objClass === 'Object' || objClass === 'Array') {
for(var key in obj) {
if(!obj.hasOwnProperty(key)) continue;
sizeOf(obj[key]);
}
} else bytes += obj.toString().length * 2;
break;
}
}
return bytes;
};
function formatByteSize(bytes) {
if(bytes < 1024) return bytes + ' b';
else if(bytes < 1048576) return(bytes / 1024).toFixed( decimalPlaces ) + ' KB';
else if(bytes < 1073741824) return(bytes / 1048576).toFixed( decimalPlaces ) + ' MB';
else return(bytes / 1073741824).toFixed( decimalPlaces ) + ' GB';
};
return formatByteSize(sizeOf(obj));
};
const apiRequest = function apiRequest( path ) {
return got( `https://api2.developertracker.com${ path }`, {
headers: {
Authorization: `Bearer ${ process.env.API_TOKEN }`
},
json: true,
} )
.then( ( response ) => {
return response.body;
} );
};
const twitchApiRequest = function twitchApiRequest( path ) {
return got( `https://api.twitch.tv/kraken${ path }`, {
headers: {
'Accept': 'application/vnd.twitchtv.v5+json',
'Client-ID': process.env.TWITCH_CLIENTID,
},
json: true,
} )
.then( ( response ) => {
return response.body;
} );
}
const checkDevsInStream = async function checkDevsInStream( stream ) {
const start = now();
let response;
try {
response = await getUsersInChat( stream );
} catch ( getUsersError ) {
logLine( `Failed to get users for ${ stream }`, systemLog );
logLine( getUsersError.message, systemLog );
return false;
}
let users = [];
Object.keys( response.body.chatters ).forEach( ( chatterType ) => {
users = users.concat( response.body.chatters[ chatterType ] );
} );
for ( const dev in devAccounts ) {
if ( users.includes( dev ) ) {
logLine( `[${ timestamp( 'HH:mm' ) }] ${ dev } spotted in #${ stream }`, devLog );
}
}
const end = now();
// Make sure we don't do more than 1 request / 1000 ms
if ( end - start < 1000 ) {
await sleep( 1000 - ( end - start ) );
}
};
const findDevs = async function findDevs(){
while ( true ) {
const streamsCopy = liveStreams.slice(); // Make sure the streams isn't altered
for ( let i = 0; i < streamsCopy.length; i = i + 1 ) {
await checkDevsInStream( streamsCopy[ i ].replace( '#', '' ) )
}
// Wait so we don't blow the CPU ^^
if ( streamsCopy.length < 1 ) {
await sleep( 1000 );
}
}
};
const getGames = async function getGames() {
// console.log( '<info> Fetching games from API...' );
logLine( 'Fetching games from API...', systemLog );
let gamesResponse;
try {
gamesResponse = await apiRequest( '/games' );
} catch ( apiRequestError ) {
logLine( apiRequestError, systemLog, 'error' );
// throw apiRequestError;
return false;
}
games = gamesResponse.data;
for ( let i = 0; i < gamesResponse.data.length; i = i + 1 ) {
if ( gamesResponse.data[ i ].config.sources && gamesResponse.data[ i ].config.sources.Twitch ) {
if ( gamesResponse.data[ i ].config.sources.Twitch.name ) {
twitchNames[ gamesResponse.data.identifier ] = gamesResponse.data[ i ].config.sources.Twitch.name;
}
if ( gamesResponse.data[ i ].config.sources.Twitch.allowedSections ) {
extraStreams[ gamesResponse.data.identifier ] = gamesResponse.data[ i ].config.sources.Twitch.allowedSections.map( ( streamName ) => {
return `#${ streamName }`;
} );
}
}
}
}
const getStreams = async function getStreams() {
// console.log( '<info> Getting streams from kraken API' );
logLine( 'Getting streams from kraken API', systemLog );
for ( let i = 0; i < gamesToCheck.length; i = i + 1 ) {
const apiPath = `/search/streams?query=${ encodeURIComponent( gamesToCheck[ i ] ) }&limit=25`;
try {
let streamsResponse = await twitchApiRequest( apiPath );
logLine( `Twitch returned ${ streamsResponse.streams.length } streams for ${ encodeURIComponent( gamesToCheck[ i ] ) }`, systemLog );
for ( let j = 0; j < streamsResponse.streams.length; j++ ) {
if ( streamsResponse.streams[ j ].viewers >= 100 ) {
const stream = `#${ streamsResponse.streams[ j ].channel.name }`;
liveStreams.push( stream );
}
}
} catch ( twitchApiRequestError ) {
logLine( `Twitch ${ apiPath } failed with "${ twitchApiRequestError.message }".`, systemLog, 'error' );
// throw twitchApiRequestError;
}
}
}
const getDevelopers = async function getDevelopers(){
// console.log( '<info> Getting developers from API...' );
logLine( 'Getting developers from API...', systemLog );
for ( let game of games ) {
const accountResponse = await apiRequest( `/${ game.identifier }/accounts` );
// logLine( `got ${ accountResponse.data.length } accounts for ${ game.identifier }`, systemLog );
accountResponse.data.map( ( account ) => {
if ( account.service !== 'Twitch' ) {
return true;
}
const twitchGameName = twitchNames[ game.identifier ] || game.name;
if ( !gamesToCheck.includes( twitchGameName ) ) {
gamesToCheck.push( twitchGameName );
}
devAccounts[ account.identifier.toLowerCase() ] = Object.assign(
{},
account,
{
twitchActivity: {
updatedAt: Date.now(),
active: false,
messages: [],
},
}
);
} );
}
};
// Not happy with this; too many possible inconsistencies
// - can't guarantee context message will be correct
const messageHandler = function messageHandler( data ) {
const { channel, userstate, message, self } = data;
const sender = userstate.username;
const parts = message.split(' ');
addMessageStat();
if ( devAccounts[ sender ] ) {
// handle dev message
// console.log( chalk.yellow( `${ data.userstate[ 'display-name' ] }: ${ data.message }` ) );
devLog.log( `${ channel } ${ data.userstate[ 'display-name' ] }: ${ data.message }` );
fs.appendFile( './posts.txt', `${ JSON.stringify( data ) }\n`, ( appendError ) => {
if ( appendError ) {
logLine( appendError.message, systemLog, 'error' );
} else {
logLine( 'Dev message saved', systemLog );
}
} );
parts.forEach( part => {
if ( !part.startsWith( '@' )) {
return;
}
// get context
context.forEach( ( msg, index ) => {
if ( msg.username !== part.slice( 1 ).toLowerCase() || msg.channel !== channel ) {
return;
}
const newMsg = {
developer: devAccounts[ sender ].identifier,
toUser: msg.displayName,
channel,
message,
context: msg,
timestamp: Date.now(),
};
// Delete context messages after tying to a dev message
context.splice( index, 1 );
// console.log( `<info> New post found:\n${ chalk.green( JSON.stringify( newMsg, null, 4 ) ) }` );
fs.appendFile( './devs.txt', JSON.stringify( newMsg, null, 4 ), ( appendError ) => {
if ( appendError ) {
logLine( appendError.message, systemLog, 'error' );
} else {
logLine( 'Dev post saved', systemLog );
}
} );
posts.unshift( newMsg );
} );
} );
} else {
const newContext = {
username: userstate.username,
displayName: userstate[ 'display-name' ],
channel,
message,
// toDev: part.slice( 1 ).toLowerCase(),
timestamp: Date.now(),
};
context.unshift( newContext );
messageLog.log( `${ data.userstate[ 'display-name' ] }: ${ data.message }` );
contextCount.setDisplay( context.length );
}
}
const streamConnectionHandler = async function streamConnectionHandler( channels ) {
logLine( `Listening for activity from ${ Object.keys( devAccounts ).length } devs in ${ channels.length } streams`, systemLog );
const currentChannels = twitchClient.getChannels();
for ( const connectedChannel of currentChannels ) {
if ( !channels.includes( connectedChannel ) ) {
twitchClient.part( connectedChannel );
await sleep( 1000 );
}
}
for ( const newChannel of channels ) {
if ( !currentChannels.includes( newChannel ) ) {
twitchClient.join( newChannel );
await sleep( 1000 );
}
}
}
const twitchIrc = async function twitchIrc() {
// Twitch IRC client config options
/* Docs: https://docs.tmijs.org/v1.2.1/Configuration.html */
const config = {
options: {
debug: false,
},
connection: {
reconnect: true,
},
identity: {
username: process.env.TWITCH_USERNAME,
password: process.env.TWITCH_OAUTH,
},
channels: [],
};
if ( !twitchClient ) {
twitchClient = new tmi.client( config );
// The on chat event will fire for every message (in every connected channel)
/* Docs for chat event: https://docs.tmijs.org/v1.2.1/Events.html#chat */
twitchClient.on('chat', ( channel, userstate, message, self ) => {
const msgData = { channel, userstate, message, self };
messageHandler( msgData );
});
await twitchClient.connect();
}
};
function startup() {
getGames()
.then( () => {
return getDevelopers();
} )
.then( () => {
return getStreams();
} )
.then( () => {
return twitchIrc();
} )
.then( () => {
streamConnectionHandler( [ ...new Set( liveStreams ) ] );
} );
}
startup();
findDevs();
// Initiate a clean contexts call every 100ms
setInterval( cleanContexts, 100 );
// Update memory usage every 1000ms
setInterval( () => {
contextSize.setDisplay( memorySizeOf( context ) );
}, 1000 );
// Update performance line every 1000ms
setInterval( () => {
performanceLine.setData( [ lineStats ] );
}, 1000 );
setInterval( () => {
// console.log( '<info> Running refresh routine...' );
logLine( 'Running refresh routine...', systemLog );
liveStreams = [];
devAccounts = {};
startup();
}, 600000 );