forked from DanLatimer/kijiji-scraper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
209 lines (176 loc) · 6.47 KB
/
server.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
"use strict";
const axios = require('axios');
const _ = require('lodash');
const cheerio = require('cheerio');
const schedule = require('node-schedule');
const moment = require('moment');
const Queue = require('smart-request-balancer');
const RSVP = require('rsvp');
const nodemailer = require('nodemailer');
const fs = require("fs");
const { Ad } = require('./classes/ad.js');
const { AdStore } = require('./classes/ad-store.js');
const { ProgressIndicator } = require('./classes/progress-indicator');
const config = require('./config');
const requestQueue = new Queue({
overall: {
limit: 2,
rate: 1,
},
retryTime: 300,
ignoreOverallOverheat: true
})
console.log('--------------------------------------------')
console.log('Kijiji Scrapper started');
console.log('--------------------------------------------\n')
console.log(`Watching the following page for new ads: \n${config.urls.map(u => u.url ? u.url : u).join('\n')}\n`);
const adStore = new AdStore();
schedule.scheduleJob(`*/${config.minutesBetweenCheck} * * * *`, updateItems);
let updatePromise = Promise.resolve()
updateItems();
function updateItems() {
updatePromise = updatePromise
.then(() => getAdListPromises())
.then(adListPromises => RSVP.Promise.all(adListPromises))
.then(parsedAdsList => {
const fetchedAds = parsedAdsList.reduce((adList1, adList2) => adList1.concat(adList2));
const newAds = adStore.add(fetchedAds);
const adPromises = getAdPromises(newAds)
return adPromises
.then(adList => adList.filter(adItem => !adItem.isIgnored))
.then(adList => adList.filter(adItem => !adItem.isBusiness))
.then(adList => {
const ignoredCount = newAds.length - adList.length;
console.log(`fetched ${fetchedAds.length} ads, ${newAds.length} new, ${ignoredCount} ignored, emailing ${adList.length}`);
emailAds(adList);
})
})
.then(() => console.log(`Ads updated, total ads in datastore: ${adStore.length}\n`))
.catch(err => console.error('error fetching things:', err))
}
function getAdListPromises() {
const progressIndicator = new ProgressIndicator('ad lists', config.urls.length)
return config.urls
.map(urlConfig =>
createAdFetchPromise(urlConfig)
.then(adList => {
progressIndicator.oneComplete()
return adList
})
)
}
function getAdPromises(newAds) {
const requiresAdditionalDetails = config.highQualityEmails
if (!requiresAdditionalDetails) {
return Promise.resolve(newAds)
}
console.log('')
const progressIndicator = new ProgressIndicator('ad additional details', newAds.length)
const adPromises = newAds.map(ad => ad.loadAdditionalDetails().then(ad => {
progressIndicator.oneComplete()
return ad
}))
return RSVP.Promise.all(adPromises)
}
function createAdFetchPromise(urlConfig) {
let url;
let ignores
if (typeof urlConfig === 'string') {
url = urlConfig
} else {
url = urlConfig.url
ignores = _.get(urlConfig, 'ignores', [])
}
if (_.isEmpty(url)) {
console.log(`invalid URL config: ${urlConfig}`)
return RSVP.Promise.resolve([])
}
return requestQueue.request(retry =>
axios
.get(url)
.then(response => {
const $ = loadCheerio(response.data);
if (!$) {
console.log(`Failed to load ad list: ${url}`)
return []
}
const parsedAds = $('div.search-item')
.get()
.map(item => {
return Ad.buildAd($(item), ignores, requestQueue)
})
return parsedAds
}))
}
function loadCheerio(html) {
try {
return cheerio.load(html);
} catch (e) {
console.error('cheerio is a failure :(');
}
}
function emailAds(ads) {
if (!ads.length) {
return
}
logAdsBeingEmailed(ads);
let transporter = getMailerTransport();
if (!transporter) {
return;
}
// setup e-mail data with unicode symbols
let mailOptions = {
from: 'Kijiji Scraper <[email protected]>', // sender address
to: `${config.email.targetEmail}`, // list of receivers
subject: createAdsFoundMessage(ads), // Subject line
text: JSON.stringify(ads), // plaintext body
html: formatAds(ads) // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, error => {
if (error) {
return console.log(`Email failed: ${error}`);
}
console.log('Email sent successfully\n');
});
}
function getMailerTransport() {
if (config.email.gmailPassword) {
return nodemailer.createTransport(
`smtps://${config.email.gmailUser}%40gmail.com:${config.email.gmailPassword}@smtp.gmail.com`);
}
if (!config.email.oauth.clientId || !config.email.oauth.clientSecret || !config.email.oauth.refreshToken) {
console.log('Could not initialize mailer as password was empty and no oauth credentials were provided')
return null;
}
return nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: "OAuth2",
user: config.email.gmailUser,
clientId: config.email.oauth.clientId,
clientSecret: config.email.oauth.clientSecret,
refreshToken: config.email.oauth.refreshToken
}
});
}
function logAdsBeingEmailed(ads) {
console.log('\n' + createAdsFoundMessage(ads));
ads.forEach(ad => {
console.log(`emailing new ad: ${ad.title}`);
});
console.log(``);
}
function createAdsFoundMessage(ads) {
const numberOfAds = ads.length;
const pluralization = numberOfAds === 1 ? 'ad' : 'ads'
return `${numberOfAds} new ${pluralization}`;
}
function formatAds(ads) {
const adsFoundMessage = createAdsFoundMessage(ads);
const adsTableRows = ads.map(ad => ad.toHtml());
return `<h1>${adsFoundMessage}</h1>` +
`<table>${adsTableRows.join('')}</table>`;
}