forked from D3vl0per/Twitch-watcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
369 lines (285 loc) · 11.2 KB
/
app.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
require('dotenv').config();
const puppeteer = require('puppeteer-core');
const dayjs = require('dayjs');
const cheerio = require('cheerio');
var fs = require('fs');
const inquirer = require('./input');
const treekill = require('tree-kill');
var run = true;
var firstRun = true;
var cookie = null;
var streamers = null;
// ========================================== CONFIG SECTION =================================================================
const configPath = './config.json'
const screenshotFolder = './screenshots/';
const baseUrl = 'https://www.twitch.tv/';
const userAgent = (process.env.userAgent || 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36');
const streamersUrl = (process.env.streamersUrl || 'https://www.twitch.tv/directory/game/VALORANT?tl=c2542d6d-cd10-4532-919b-3d19f30a768b');
const scrollDelay = (Number(process.env.scrollDelay) || 2000);
const scrollTimes = (Number(process.env.scrollTimes) || 5);
const minWatching = (Number(process.env.minWatching) || 15); // Minutes
const maxWatching = (Number(process.env.maxWatching) || 30); //Minutes
const streamerListRefresh = (Number(process.env.streamerListRefresh) || 1);
const streamerListRefreshUnit = (process.env.streamerListRefreshUnit || 'hour'); //https://day.js.org/docs/en/manipulate/add
const showBrowser = false; // false state equ headless mode;
const proxy = (process.env.proxy || ""); // "ip:port" By https://github.com/Jan710
const proxyAuth = (process.env.proxyAuth || "");
const browserScreenshot = (process.env.browserScreenshot || false);
const browserClean = 1;
const browserCleanUnit = 'hour';
var browserConfig = {
headless: !showBrowser,
args: [
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote',
'--disable-gpu',
'--no-sandbox',
'--disable-setuid-sandbox'
]
}; //https://github.com/D3vl0per/Valorant-watcher/issues/24
const cookiePolicyQuery = 'button[data-a-target="consent-banner-accept"]';
const matureContentQuery = 'button[data-a-target="player-overlay-mature-accept"]';
const sidebarQuery = '*[data-test-selector="user-menu__toggle"]';
const userStatusQuery = 'span[data-a-target="presence-text"]';
const channelsQuery = 'a[data-test-selector*="ChannelLink"]';
const streamPauseQuery = 'button[data-a-target="player-play-pause-button"]';
const streamSettingsQuery = '[data-a-target="player-settings-button"]';
const streamQualitySettingQuery = '[data-a-target="player-settings-menu-item-quality"]';
const streamQualityQuery = 'input[data-a-target="tw-radio"]';
// ========================================== CONFIG SECTION =================================================================
async function viewRandomPage(browser, page) {
var streamer_last_refresh = dayjs().add(streamerListRefresh, streamerListRefreshUnit);
var browser_last_refresh = dayjs().add(browserClean, browserCleanUnit);
while (run) {
try {
if (dayjs(browser_last_refresh).isBefore(dayjs())) {
var newSpawn = await cleanup(browser, page);
browser = newSpawn.browser;
page = newSpawn.page;
firstRun = true;
browser_last_refresh = dayjs().add(browserClean, browserCleanUnit);
}
if (dayjs(streamer_last_refresh).isBefore(dayjs())) {
await getAllStreamer(page); //Call getAllStreamer function and refresh the list
streamer_last_refresh = dayjs().add(streamerListRefresh, streamerListRefreshUnit); //https://github.com/D3vl0per/Valorant-watcher/issues/25
}
let watch = streamers[getRandomInt(0, streamers.length - 1)]; //https://github.com/D3vl0per/Valorant-watcher/issues/27
var sleep = getRandomInt(minWatching, maxWatching) * 60000; //Set watuching timer
console.log('\n🔗 Now watching streamer: ', baseUrl + watch);
await page.goto(baseUrl + watch, {
"waitUntil": "networkidle0"
}); //https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#pagegobackoptions
await clickWhenExist(page, cookiePolicyQuery);
await clickWhenExist(page, matureContentQuery); //Click on accept button
if (firstRun) {
console.log('🔧 Setting lowest possible resolution..');
await clickWhenExist(page, streamPauseQuery);
await clickWhenExist(page, streamSettingsQuery);
await page.waitFor(streamQualitySettingQuery);
await clickWhenExist(page, streamQualitySettingQuery);
await page.waitFor(streamQualityQuery);
var resolution = await queryOnWebsite(page, streamQualityQuery);
resolution = resolution[resolution.length - 1].attribs.id;
await page.evaluate((resolution) => {
document.getElementById(resolution).click();
}, resolution);
await clickWhenExist(page, streamPauseQuery);
await page.keyboard.press('m'); //For unmute
firstRun = false;
}
if (browserScreenshot) {
await page.waitFor(1000);
fs.access(screenshotFolder, error => {
if (error) {
fs.promises.mkdir(screenshotFolder);
}
});
await page.screenshot({
path: `${screenshotFolder}${watch}.png`
});
console.log('📸 Screenshot created: ' + `${watch}.png`);
}
await clickWhenExist(page, sidebarQuery); //Open sidebar
await page.waitFor(userStatusQuery); //Waiting for sidebar
let status = await queryOnWebsite(page, userStatusQuery); //status jQuery
await clickWhenExist(page, sidebarQuery); //Close sidebar
console.log('💡 Account status:', status[0] ? status[0].children[0].data : "Unknown");
console.log('🕒 Time: ' + dayjs().format('HH:mm:ss'));
console.log('💤 Watching stream for ' + sleep / 60000 + ' minutes\n');
await page.waitFor(sleep);
} catch (e) {
console.log('🤬 Error: ', e);
console.log('Please visit the discord channel to receive help: https://discord.gg/s8AH4aZ');
}
}
}
async function readLoginData() {
const cookie = [{
"domain": ".twitch.tv",
"hostOnly": false,
"httpOnly": false,
"name": "auth-token",
"path": "/",
"sameSite": "no_restriction",
"secure": true,
"session": false,
"storeId": "0",
"id": 1
}];
try {
console.log('🔎 Checking config file...');
if (fs.existsSync(configPath)) {
console.log('✅ Json config found!');
let configFile = JSON.parse(fs.readFileSync(configPath, 'utf8'))
if (proxy) browserConfig.args.push('--proxy-server=' + proxy);
browserConfig.executablePath = configFile.exec;
cookie[0].value = configFile.token;
return cookie;
} else if (process.env.token) {
console.log('✅ Env config found');
if (proxy) browserConfig.args.push('--proxy-server=' + proxy);
cookie[0].value = process.env.token; //Set cookie from env
browserConfig.executablePath = '/usr/bin/chromium-browser'; //For docker container
return cookie;
} else {
console.log('❌ No config file found!');
let input = await inquirer.askLogin();
fs.writeFile(configPath, JSON.stringify(input), function(err) {
if (err) {
console.log(err);
}
});
if (proxy) browserConfig.args[6] = '--proxy-server=' + proxy;
browserConfig.executablePath = input.exec;
cookie[0].value = input.token;
return cookie;
}
} catch (err) {
console.log('🤬 Error: ', e);
console.log('Please visit my discord channel to solve this problem: https://discord.gg/s8AH4aZ');
}
}
async function spawnBrowser() {
console.log("=========================");
console.log('📱 Launching browser...');
var browser = await puppeteer.launch(browserConfig);
var page = await browser.newPage();
console.log('🔧 Setting User-Agent...');
await page.setUserAgent(userAgent); //Set userAgent
console.log('🔧 Setting auth token...');
await page.setCookie(...cookie); //Set cookie
console.log('⏰ Setting timeouts...');
await page.setDefaultNavigationTimeout(process.env.timeout || 0);
await page.setDefaultTimeout(process.env.timeout || 0);
if (proxyAuth) {
await page.setExtraHTTPHeaders({
'Proxy-Authorization': 'Basic ' + Buffer.from(proxyAuth).toString('base64')
})
}
return {
browser,
page
};
}
async function getAllStreamer(page) {
console.log("=========================");
await page.goto(streamersUrl, {
"waitUntil": "networkidle0"
});
console.log('🔐 Checking login...');
await checkLogin(page);
console.log('📡 Checking active streamers...');
await scroll(page, scrollTimes);
const jquery = await queryOnWebsite(page, channelsQuery);
streamers = null;
streamers = new Array();
console.log('🧹 Filtering out html codes...');
for (var i = 0; i < jquery.length; i++) {
streamers[i] = jquery[i].attribs.href.split("/")[1];
}
return;
}
async function checkLogin(page) {
let cookieSetByServer = await page.cookies();
for (var i = 0; i < cookieSetByServer.length; i++) {
if (cookieSetByServer[i].name == 'twilight-user') {
console.log('✅ Login successful!');
return true;
}
}
console.log('🛑 Login failed!');
console.log('🔑 Invalid token!');
console.log('\nPleas ensure that you have a valid twitch auth-token.\nhttps://github.com/D3vl0per/Valorant-watcher#how-token-does-it-look-like');
if (!process.env.token) {
fs.unlinkSync(configPath);
}
process.exit();
}
async function scroll(page, times) {
console.log('🔨 Emulating scrolling...');
for (var i = 0; i < times; i++) {
await page.evaluate(async (page) => {
var x = document.getElementsByClassName("scrollable-trigger__wrapper");
x[0].scrollIntoView();
});
await page.waitFor(scrollDelay);
}
return;
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
async function clickWhenExist(page, query) {
let result = await queryOnWebsite(page, query);
try {
if (result[0].type == 'tag' && result[0].name == 'button') {
await page.click(query);
await page.waitFor(500);
return;
}
} catch (e) {}
}
async function queryOnWebsite(page, query) {
let bodyHTML = await page.evaluate(() => document.body.innerHTML);
let $ = cheerio.load(bodyHTML);
const jquery = $(query);
return jquery;
}
async function cleanup(browser, page) {
const pages = await browser.pages();
await pages.map((page) => page.close());
await treekill(browser.process().pid, 'SIGKILL');
//await browser.close();
return await spawnBrowser();
}
async function killBrowser(browser, page) {
const pages = await browser.pages();
await pages.map((page) => page.close());
treekill(browser.process().pid, 'SIGKILL');
return;
}
async function shutDown() {
console.log("\n👋Bye Bye👋");
run = false;
process.exit();
}
async function main() {
console.clear();
console.log("=========================");
cookie = await readLoginData();
var {
browser,
page
} = await spawnBrowser();
await getAllStreamer(page);
console.log("=========================");
console.log('🔭 Running watcher...');
await viewRandomPage(browser, page);
};
main();
process.on("SIGINT", shutDown);
process.on("SIGTERM", shutDown);