-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
108 lines (99 loc) · 2.56 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
const kijiji = require('kijiji-scraper');
const dotenv = require('dotenv');
const path = require('path');
dotenv.load({ path: path.join(__dirname, '.env') });
const mailgun = require('mailgun-js')({
apiKey: process.env.MAILGUN_API_KEY,
domain: process.env.MAILGUN_DOMAIN
});
function scrape() {
return new Promise((resolve, reject) => {
var queryPrefs = {
'locationId': process.env.KIJIJI_LOC_ID,
'categoryId': process.env.KIJIJI_CAT_ID
}
var queryParams = {
'minPrice': process.env.KIJIJI_MIN_PRICE,
'maxPrice': process.env.KIJIJI_MAX_PRICE,
'adType': 'OFFER',
'keywords': process.env.KIJIJI_SEARCHQ
}
kijiji.query(queryPrefs, queryParams, (err, ads) => {
if (err) {
reject(err);
} else {
resolve(ads);
}
});
});
}
function sendEmail(msgBody) {
var data = {
from: process.env.MAILGUN_FROM,
to: process.env.MAILGUN_TO,
subject: 'Kijiji Summary',
text: 'HTML Email not supported',
html: msgBody
};
return new Promise((resolve, reject) => {
mailgun.messages().send(data, function (error, body) {
if (error) {
reject(error);
} else {
resolve(body);
}
});
});
}
function compileEmail(ads) {
var email = '';
for (var i = 0; i < ads.length; i++) {
var ad = ads[i];
const title = ad.title;
const link = ad.link;
const desc = ad.description;
const date = ad.pubDate;
const price = ad['g-core:price'];
var img = null;
try {
img = ad.innerAd.image;
} catch (e) {
// oh well...
console.error(e);
}
// I hate to do this, but I need to finish this project in 20 mins
// and don't have time to learn a framework D:
if (title && link && desc && price) {
email += '<h1>' + title + '</h1>';
email += '<h3>' + date + '</h3>';
email += '<h2>Price:</h2>';
email += '<p>' + price + '</p>';
email += '<h2>Description:</h2>';
email += '<p>' + desc + '</p>';
email += '<a href=' + link + '><strong>Link</strong></a><br>';
if (img)
email += '<br><img src=' + img + '>';
email += '<hr><br>';
email += `
<style>
body { background-color: #2b2a2a; color: #f4f4f4; font-family: sans-serif; }
a { color: #f4f4f4; }
</style>
`
}
}
return email;
}
scrape()
.then(ads => {
return compileEmail(ads);
})
.then(body => {
return sendEmail(body);
})
.then(result => {
console.log('Message queued.');
})
.catch(err => {
console.error(err);
});