forked from D3vl0per/Twitch-watcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
302 lines (224 loc) · 9.48 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
require('dotenv').config();
const puppeteer = require('puppeteer-core');
const dayjs = require('dayjs');
const cheerio = require('cheerio');
var fs = require('fs');
const inquirer = require('./input');
var run = true;
// ========================================== 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) || 6); // Minutes
const maxWatching = (Number(process.env.maxWatching) || 15); //Minutes
const streamerListRefresh = (Number(process.env.streamerListRefresh) || 2);
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 browserScreenshot = (process.env.browserScreenshot || false);
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',
'--window-size=240,135'
]
};//https://github.com/D3vl0per/Valorant-watcher/issues/24
const playerSettingsQuery = 'button[data-a-target="player-settings-button"]';
const playerSettingsQualityQuery = 'button[data-a-target="player-settings-menu-item-quality"]';
const playerSettingsQuality160pQuery = 'div[class="tw-pd-05"]:last-child';
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"]';
// ========================================== CONFIG SECTION =================================================================
async function main(){
console.clear();
console.log("=========================");
const cookie = await readLoginData();
let browser = await puppeteer.launch(browserConfig);
const page = await browser.newPage();
console.log('🔧 Set User-Agent');
await page.setUserAgent(userAgent); //Set userAgent
console.log('🔧 Set auth cookie');
await page.setCookie(...cookie); //Set cookie
console.log('⏰ Setting timeouts');
await page.setDefaultNavigationTimeout(process.env.timeout || 30000);
await page.setDefaultTimeout(process.env.timeout || 30000);
process.stdout.write('🔐 Checking login... ');
await checkLogin(page);
let streamers = await getAllStreamer(page);
console.log("=========================");
console.log('📌 Run watcher');
await viewRandomPage(page, streamers)
await browser.close();
};
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 {
process.stdout.write('🔎 Check 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('❌ Create config file');
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.error(err)
}
}
async function getAllStreamer(page) {
console.log("=========================");
console.log('📡 Check active streamers');
console.log('⏰ Waiting for Twitch.tv loading...');
await page.goto(streamersUrl, {
"waitUntil": "networkidle0"
});
await scroll(page, scrollTimes);
const jquery = await queryOnWebsite(page, channelsQuery);
let streamers = new Array();
console.log('🧹 Filter out html codes');
for (var i = 0; i < jquery.length; i++) {
streamers[i] = jquery[i].attribs.href.split("/")[1];
}
return streamers;
}
async function viewRandomPage(page, streamers) {
var last_refresh = dayjs().add(streamerListRefresh, streamerListRefreshUnit);
while (run) {
if (dayjs(last_refresh).isBefore(dayjs())) {
streamers = await getAllStreamer(page); //Call getAllStreamer function and refresh the list
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🔗 Streamer: ', baseUrl + watch);
await page.goto(baseUrl + watch, {
"waitUntil": "networkidle2"
});//https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#pagegobackoptions
await clickWhenExist(page, matureContentQuery);//Click on accept button
await page.keyboard.press('m'); //For unmute
await clickWhenExist(page, playerSettingsQuery);
await clickWhenExist(page, playerSettingsQualityQuery);
await clickWhenExist(page, playerSettingsQuality160pQuery);
if (true){
await page.waitFor(1000);
fs.access(screenshotFolder, error => {
if (error) {
fs.promises.mkdir(screenshotFolder);
}
});
await page.screenshot({path: `${screenshotFolder}${watch}.png`});
}
await clickWhenExist(page, sidebarQuery); //Open sidebar
// Fix for issue https://github.com/D3vl0per/Valorant-watcher/issues/37
let status = await queryOnWebsite(page, userStatusQuery); //status jQuery
if (status[0] && status[0].children[0] && status[0].children[0].data) {
console.log('💡 Your account status:', status[0].children[0].data);
}
await clickWhenExist(page, sidebarQuery); //Close sidebar
console.log('💤 I\'ll watch this for ' + sleep / 60000 + ' minutes\n');
await page.waitFor(sleep);
}
}
async function checkLogin(page) {
await page.goto(baseUrl, {
"waitUntil": "networkidle0"
});//https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#pagegobackoptions
let cookieSetByServer = await page.cookies();
await clickWhenExist(page, cookiePolicyQuery);
for (var i = 0; i < cookieSetByServer.length; i++) {
if (cookieSetByServer[i].name == 'twilight-user') {
console.log('✅ Login successful');
return true;
}
}
console.log('\n🛑 Login failed!');
console.log('🔑 Wrong token!');
if (!process.env.token) {
fs.unlinkSync(configPath);
}
process.exit();
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
async function queryOnWebsite(page, query){
let bodyHTML = await page.evaluate(() => document.body.innerHTML);
let $ = cheerio.load(bodyHTML);
const jquery = $(query);
return jquery;
}
async function clickWhenExist(page, query) {
let result = await queryOnWebsite(page, query);
try {
if (result[0].type == 'tag'){
await page.click(query)
await page.waitFor(500);
}
} catch (e) {}
}
async function setQuality(page) {
console.log(element);
}
async function scroll(page, times) {
console.log('🔨 Emulate the 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);
}
}
async function shutDown() {
console.log("\n👋Bye Bye👋");
run = false;
process.exit();
}
main();
process.on("SIGINT", shutDown);
process.on("SIGTERM", shutDown);