-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcapture.js
More file actions
337 lines (269 loc) · 10 KB
/
capture.js
File metadata and controls
337 lines (269 loc) · 10 KB
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
/* -------------------------------------------------------------------- */
/* Plugin Name : TradingView-Webhook-Alert-Telegram-SnapShot */
/* Author Name : rasoul707 */
/* File Name : capture.js */
/* -------------------------------------------------------------------- */
const express = require('express');
const puppeteer = require('puppeteer');
const UserAgent = require('user-agents');
const moment = require('moment');
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
const app = express();
let browser, useragent;
const chromeOptions = {
headless: true,
defaultViewport: null,
args: [
"--incognito",
"--no-sandbox",
"--single-process",
"--no-zygote",
"--disable-setuid-sandbox",
"--disable-dev-shm-usage",
"--disable-accelerated-2d-canvas",
"--disable-gpu",
"--window-size=1920x1080",
],
};
const blockedResourceTypes = [
'image',
'media',
'font',
'texttrack',
'object',
'beacon',
'csp_report',
'imageset',
];
const skippedResources = [
'quantserve',
'adzerk',
'doubleclick',
'adition',
'exelator',
'sharethrough',
'cdn.api.twitter',
'google-analytics',
'googletagmanager',
'google',
'fontawesome',
'facebook',
'analytics',
'optimizely',
'clicktale',
'mixpanel',
'zedo',
'clicksor',
'tiqcdn',
];
const newPage = async () => {
const page = await browser.newPage();
page.setDefaultNavigationTimeout(0);
await page.setRequestInterception(true);
await page.setUserAgent(useragent);
await page.setViewport({
width: 1920,
height: 1080,
});
page.on('request', request => {
const requestUrl = request._url.split('?')[0].split('#')[0];
if (
blockedResourceTypes.indexOf(request.resourceType()) !== -1 ||
skippedResources.some(resource => requestUrl.indexOf(resource) !== -1)
) {
request.abort();
} else {
request.continue();
}
});
return page
}
app.get('/start', async function (req, res) {
const userAgent = new UserAgent({ "deviceCategory": "desktop" })
useragent = userAgent.toString()
browser = await puppeteer.launch(chromeOptions);
const page = await newPage();
const authUrl = 'https://www.tradingview.com/accounts/signin/?next=https://www.tradingview.com';
const username = req.query.username
const password = req.query.password
let status = ''
let ok = false
await page.goto(authUrl, { timeout: 25000, waitUntil: 'networkidle2', });
if (await page.url() === authUrl) {
await page.click('.tv-signin-dialog__toggle-email')
await page.type('input[name="username"]', username)
await page.type('input[name="password"]', password)
await page.click('button[type="submit"]')
await page.waitForTimeout(5000);
if (page.url() === authUrl) {
status = "error"
ok = false
}
else {
status = "login"
ok = true
}
} else {
status = "hasLogin"
ok = true
}
await page.close();
res.json({ ok, status, username, password, useragent });
});
const dateTimeRange = (interval, candles) => {
interval = interval.toUpperCase();
const types = ['H', 'D', 'W', 'M', 'Y']
const temp = interval.slice(-1)
const now = moment()
let _start = {}
let _end = {}
let duration
let number
candles = parseInt(candles)
if (!candles || isNaN(candles)) candles = 1
if (!types.includes(temp)) {
duration = 'm'
number = parseInt(interval)
}
else {
duration = temp
number = parseInt(interval.substring(0, interval.length - 1))
}
if (!number || isNaN(number)) number = 1
if (duration === 'S') {
_start = { seconds: candles * number }
_end = { seconds: number * 10 }
now.endOf('second')
} if (duration === 'm') {
_start = { minutes: candles * number }
_end = { minutes: number * 10 }
now.endOf('minute').add(1, 'second')
}
if (duration === 'H') {
_start = { hours: candles * number }
_end = { hours: number * 10 }
now.endOf('hour').add(1, 'second')
}
if (duration === 'D') {
_start = { days: candles * number }
_end = { days: number * 10 }
now.endOf('day').add(1, 'second')
}
if (duration === 'W') {
_start = { weeks: candles * number }
_end = { weeks: number * 10 }
now.endOf('week').add(1, 'second')
}
if (duration === 'M') {
_start = { months: candles * number }
_end = { months: number * 10 }
now.endOf('month').add(1, 'second')
}
if (duration === 'Y') {
_start = { years: candles * number }
_end = { years: number * 10 }
now.endOf('year').add(1, 'second')
}
const start = now.clone().subtract(_start)
const end = now.clone().add(_end)
return { start, end }
}
const uploadImg = async (_page, ii) => {
const img = await _page.screenshot();
const n = await fetch('https://api.upload.io/v1/files/basic', {
method: 'POST',
headers: {
Authorization: "Bearer public_12a1xk8CY7DbH49KvyPFABVpCSws",
"Content-Type": "image/png"
},
body: img
})
// console.log(ii, await n.json())
const json = await n.json()
return json['fileUrl']
}
app.get('/capture', async function (req, res) {
var base = req.query.base;
var exchange = req.query.exchange;
var ticker = req.query.ticker;
var interval = req.query.interval;
var candles = req.query.candles;
const url = 'https://www.tradingview.com/' + base + '?symbol=' + exchange + ':' + ticker + '&interval=' + interval;
const page = await newPage();
let images = []
await page.goto(url, { timeout: 25000, waitUntil: 'domcontentloaded', }).then(async () => {
await page.waitForSelector('#header-toolbar-symbol-search', { visible: true });
page.keyboard.press('AltLeft');
await page.keyboard.press('KeyR');
if (candles) {
await page.waitForTimeout(200);
page.keyboard.press('AltLeft');
await page.keyboard.press('KeyG');
const { start, end } = dateTimeRange(interval, candles)
const start_date = start.format("YYYYMMDD")
const end_date = end.format("YYYYMMDD")
const start_time = start.format("HHmm")
const end_time = end.format("HHmm")
images.push(await uploadImg(page, '#wait'))
await page.waitForSelector('[data-name="go-to-date-dialog"] div[data-name="tab-item-customrange"]', { visible: true });
await page.click('[data-name="go-to-date-dialog"] div[data-name="tab-item-customrange"]')
await page.focus('[data-name="go-to-date-dialog"] .bodyWrapper-70bfoXiO > div > :nth-child(1) > :nth-child(1) input');
await page.waitForTimeout(200);
await page.keyboard.press('End');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.type(start_date, { delay: 100 });
await page.focus('[data-name="go-to-date-dialog"] .bodyWrapper-70bfoXiO > div > :nth-child(1) > :nth-child(2) input');
await page.waitForTimeout(200);
await page.keyboard.press('Backspace');
await page.keyboard.type(start_time, { delay: 100 });
//
await page.click('[data-name="go-to-date-dialog"] div[data-name="tab-item-customrange"]')
//
await page.focus('[data-name="go-to-date-dialog"] .bodyWrapper-70bfoXiO > div > :nth-child(2) > :nth-child(1) input');
await page.waitForTimeout(200);
await page.keyboard.press('End');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.press('Backspace');
await page.keyboard.type(end_date, { delay: 100 });
await page.focus('[data-name="go-to-date-dialog"] .bodyWrapper-70bfoXiO > div > :nth-child(2) > :nth-child(2) input');
await page.waitForTimeout(200);
await page.keyboard.press('Backspace');
await page.keyboard.type(end_time, { delay: 100 });
//
await page.click('[data-name="go-to-date-dialog"] div[data-name="tab-item-customrange"]')
//
images.push(await uploadImg(page, '#before'))
await page.waitForTimeout(200)
await page.click('[data-name="go-to-date-dialog"] button[data-name="submit-button"]')
images.push(await uploadImg(page, '#final'))
}
const token = await page.evaluate(async () => {
return this._exposed_chartWidgetCollection.takeScreenshot()
})
console.log('Success')
res.json({ ok: true, token, images });
}).catch((err) => {
console.log('Failed', err)
res.json({ ok: false, error: err.toString(), images })
throw err;
})
await page.close();
});
app.listen(7007);