-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathworker.js
253 lines (209 loc) · 6.96 KB
/
worker.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
const Telegram = require("telegraf/telegram");
const puppeteer = require("puppeteer-extra");
const StealthPlugin = require("puppeteer-extra-plugin-stealth");
const { sequelize, defaultRows, Message, Setting } = require("./models");
/**
* A function that update's the worker activity status in Database
*/
async function updateWorkerStatus(initial = false) {
if (initial === true) {
return await Setting.findOrCreate({
where: { type: "worker" },
defaults: { data: new Date().toISOString() },
});
}
await Setting.update(
{ data: new Date().toISOString() },
{ where: { type: "worker" } }
);
}
/**
* A function that will obtain the URL of a screenshot generated by TradingView.
*
* @param {class} page - A puppeteer page instance
* @param {object} options - Options used while taking a screenshot
*
* @returns {string} - The screenshot Image URL
*/
async function screenshot(page, { symbol, timeframe }) {
// Symbol URL
let url = `https://www.tradingview.com/symbols/${symbol}/`;
const [exchange, stock] = symbol.split(":");
if (exchange && stock) {
url = `https://www.tradingview.com/symbols/${stock}/?exchange=${exchange}`;
}
// Go to symbol page
await page.goto(url);
await page.waitForSelector('a[href*="/chart/?"]');
const graphUrl = await page.evaluate(
() => document.querySelector('a[href*="/chart/?"]').href
);
// Go to graph page
await page.goto(graphUrl);
await page.waitForSelector(".menu-1fA401bY");
await page.click(".menu-1fA401bY");
await page.waitForSelector(".item-2xPVYue0");
await page.evaluate((timeframe) => {
document.querySelectorAll(".item-2xPVYue0").forEach((tag) => {
if (tag.textContent !== timeframe) return;
tag.click();
});
}, timeframe);
// Wait for image generation
await page.waitForSelector("[class='chart-loading-screen']");
await page.click("#header-toolbar-screenshot");
const snapshotIdResponse = await page.waitForResponse(
(response) =>
response.url().endsWith("snapshot/") && response.status() === 200
);
const snapshotId = await snapshotIdResponse.text();
return `https://www.tradingview.com/x/${snapshotId}/`;
}
/**
* A worker that is called periodically to dispatch messages.
*
* @param {class} page - A puppeteer page instance
*/
async function processQueue(page) {
// Update worker status
await updateWorkerStatus();
const botSettings = await Setting.findOne({
where: { type: "telegram:bot" },
});
const screenshotSettings = await Setting.findOne({
where: { type: "tradingview:screenshot" },
});
const pendingMessages = await Message.findAll({
where: { status: "pending" },
});
console.log(new Date(), "Pending messages:", pendingMessages.length);
const bot = new Telegram(botSettings.data);
// Iterate over all messages
for (let i = 0; i < pendingMessages.length; i++) {
const message = pendingMessages[i];
const id = message["id"];
const data = message["data"];
const timeframe = message["timeframe"];
const channels = message["channels"].split(",");
const symbol = data.split(" ")[0];
console.log(new Date(), "Processing Message ID:", id);
// Iterate over all channels
for (let j = 0; j < channels.length; j++) {
const channel = channels[j];
let image = null;
if (screenshotSettings.enabled) {
try {
image = await screenshot(page, {
symbol,
timeframe: timeframe || screenshotSettings.data,
});
console.log(new Date(), "Screenshot (SUCCESS):", symbol);
} catch (err) {
image =
"https://miro.medium.com/max/978/1*pUEZd8z__1p-7ICIO1NZFA.png";
// Update logs
await Message.update({ log: JSON.stringify(err) }, { where: { id } });
console.log(new Date(), "Screenshot (FAILED):", symbol);
}
// Update worker status
await updateWorkerStatus();
}
// Dispatch messages
try {
let response;
if (screenshotSettings.enabled) {
response = await bot.sendPhoto(channel, image, { caption: data });
} else {
response = await bot.sendMessage(channel, data);
}
await Message.update(
{ status: "success", log: JSON.stringify(response) },
{ where: { id } }
);
console.log(new Date(), "Dispatch (SUCCESS):", channel);
} catch (err) {
// Update logs
await Message.update(
{ status: "failed", log: JSON.stringify(err) },
{ where: { id } }
);
console.log(new Date(), "Dispatch (FAILED):", err);
}
// Update worker status
await updateWorkerStatus();
}
}
}
/**
* Init worker function
*/
async function init() {
console.log(new Date(), "Worker started");
/**********************
* INITILIZE DATABASE *
**********************/
await sequelize.sync();
await defaultRows();
await updateWorkerStatus(true);
/**********************
* INITIALIZE BROWSER *
**********************/
puppeteer.use(StealthPlugin());
const browser = await puppeteer.launch({
headless: true,
args: ["--start-fullscreen", "--no-sandbox", "--window-size=1366,768"],
});
const page = (await browser.pages())[0];
// Confirm leaving page without saving
page.on("dialog", async (dialog) => {
await dialog.accept();
});
console.log(new Date(), "Browser session opened");
const credentialsSettings = await Setting.findOne({
where: { type: "tradingview:credentials" },
});
/********************
* LOGIN TO ACCOUNT *
********************/
if (credentialsSettings.enabled) {
try {
const [email, password] = credentialsSettings.data.split(":");
await page.goto("https://www.tradingview.com/#signin");
await page.click("span.js-show-email");
await page.type('[name="username"]', email);
await page.type('[name="password"]', password);
await page.click('[type="submit"]');
const loginResponse = await page.waitForResponse(
(response) =>
response.url().endsWith("accounts/signin/") &&
response.status() === 200
);
const loginSuccess = (await loginResponse.text()).includes("user");
if (loginSuccess) {
console.log(new Date(), "Login (SUCCESS):", credentialsSettings.data);
} else {
console.log(new Date(), "Login (INVALID):", credentialsSettings.data);
}
} catch (err) {
console.log(new Date(), "Login (FAILED):", err);
}
}
/********************
* PROCESS MESSAGES *
********************/
while (true) {
// Update worker stats
console.log(new Date(), "Checking Queue");
try {
// Process Queue
await processQueue(page);
} catch (err) {
console.log(new Date(), "Process Queue (FAILED):", err);
}
const wait = 1; // seconds
console.log(new Date(), `Recheck Queue in: ${wait} seconds`);
// Sleep
await new Promise((resolve) => setTimeout(resolve, wait * 1000));
}
}
init();