-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
216 lines (158 loc) · 6.19 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
const arg = require("yargs").argv
const chrome = require('puppeteer')
const fs = require('fs')
const path = require('path')
const jsonfile = require('jsonfile')
const cliProgress = require("cli-progress")
const progressBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_classic)
const prompt = require('prompt')
const config = jsonfile.readFileSync('./config.json')
const email = require('./email')
cli()
function sleep(sec) {
return new Promise( res => {
progressBar.start(sec, 0)
let progressValue = 0
let incrementer = setInterval(() => {
progressBar.update( ++progressValue )
}, 1000)
setTimeout( () => {
clearInterval(incrementer)
progressBar.stop()
res()
}, sec * 1000 );
})
}
async function saveConfig(json) {
let filePath = './config.json'
try {
await jsonfile.writeFile(filePath, json, {
spaces: 4
})
console.log(filePath, 'successfully updated')
} catch (e) {
console.error('Error happened while updating', filePath, '\nHere is the error: \n\n', e)
}
}
function cli() {
console.log( JSON.stringify(config, null, 4), '\n\n' )
prompt.start()
let questions = [
`Confirm the above configuration Press [ENTER] to continue . . .`
]
prompt.get([questions[0]], function(err, result) {
if (err) {
return onErr(err)
}
run()
})
}
function onErr(err) {
console.log(err)
return 1
}
async function run() {
let options = {
width: config.chrome.x,
height: config.chrome.y
}
const browser = await chrome.launch({
headless: config.chrome.headless,
devtools: config.chrome.devtools,
args: [`--window-size=${options.width},${options.height}`]
})
const page = await browser.newPage()
await page.setViewport({
width: options.width,
height: options.height,
deviceScaleFactor: 1,
})
job(page)
}
async function getDescriptionsSendEmail( items, page ) {
for (let i in items) {
let item = items[i]
try {
await page.goto(item.url)
await page.waitForSelector('#desc_ifr')
let descriptionURL = await page.evaluate(() => {
return document.querySelector('#desc_ifr').src
})
await page.goto(descriptionURL)
let description = await page.evaluate(() => {
return window.ds_div.outerText
})
item.description = description
console.log('Sending email =>', item.title )
email.send(item)
} catch (e) {
console.log('Description failure => ', item.title)
console.log('Description failure => ', e, '\n\n')
}
}
return items
}
function extractProduct(lastItem, belowWhatPrice) {
try {
let items = Array.from( document.querySelector('.b-list__items_nofooter').children )
let products = []
for ( let i in items ) {
let item = items[i]
let product = {
title: item.querySelector('.s-item__title').textContent.replace('New listing', '')
, newListing: item.querySelector('.s-item__title').textContent.startsWith('New listing')
, price: parseFloat( item.querySelector('.s-item__price').textContent.replace('£', '') )
, url: item.querySelector('.s-item__image').firstElementChild.href
, fastNfree: item.querySelector('.s-item__fnf') ? true : false
, postage: 0
, bestOffer: false
}
if ( lastItem.url === product.url ) {
return products
} else {
if ( item.querySelector('.s-item__shipping.s-item__logisticsCost') ) {
product.postage = item.querySelector('.s-item__shipping.s-item__logisticsCost').textContent
}
if ( item.querySelector('.s-item__purchase-options.s-item__purchaseOptions') ) {
let bestOffer = item.querySelector('.s-item__purchase-options.s-item__purchaseOptions').textContent
product.bestOffer = bestOffer.includes('Best Offer')
}
if ( product.bestOffer || product.price <= belowWhatPrice ) products.push( product )
}
}
return products
} catch (e) {
console.log('Invalid listing => I have yet to extract it correctly')
console.log('Invalid List error =>', e, '\n\n')
}
}
async function job(page){
for ( let u in config.urlsToTrack ){
let ebay = config.urlsToTrack[u]
await page.goto( ebay.url )
/*
I stringify the function purely to keep
the large function separate from this
"job" function
Otherwise the function can get largely big
This way function is kept separate using
"eval" function as passing the function
does not work. It needs to be defined
inside the scope
*/
let stringifiedFunction = `(${extractProduct.toString()})`
let newItems = await page.evaluate( (thisConfig, extractProduct) => {
extractProduct = eval(extractProduct)
return extractProduct(thisConfig.lastListedItem, thisConfig.belowWhatPrice)
}, config.urlsToTrack[u], stringifiedFunction )
// console.log('newItems', newItems, JSON.stringify(config, null, 4) )
if ( newItems.length > 0 ) {
config.urlsToTrack[u].lastListedItem = newItems[0]
await saveConfig(config)
newItems = await getDescriptionsSendEmail( newItems, page )
}
}
console.log('\n\n\nAll URLs have been tracked. Waiting for', config.howOftenInMins, 'minutes . . .')
await sleep( 60 * config.howOftenInMins )
job(page)
}