-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
88 lines (83 loc) · 2.41 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
import _ from "lodash";
import { safeLoad } from "js-yaml";
import cheerio from "cheerio";
import req from "request-promise-native";
import redis from "then-redis";
let cache = redis.createClient(process.env.REDIS_URL);
if (process.env.REDIS_FLUSH) cache.flushdb();
import { sendEmail, makeEmail, reqOptions, parseMoney } from "./functions";
let reqs = [];
let toEmail;
req(process.env.SOURCE_PATH)
.then(content => {
let parsed = safeLoad(content);
toEmail = parsed.email;
return parsed.busquedas;
})
.then(busquedas => {
busquedas.forEach((b, i) => {
let name = b.nombre;
let r = req(b.url, reqOptions)
.then(body => {
return cheerio.load(body);
})
.then($ => {
if ($(".redwarning_failover").text() == "Resultado no encontrado.") {
$(".listing_thumbs").empty();
}
return $;
})
.then($ => {
let $ads = $(".listing_thumbs .ad"),
ads = [];
$ads.each((i, el) => {
let ad = {
id: $(el).attr("id").trim(),
html: $(el).html()
};
ads.push(ad);
});
return ads;
})
.then(ads => {
if (ads.length == 0) return { items: [] };
return cache.mget(ads.map(a => a.id)).then(function(caches) {
let group = {};
group.title = name;
group.items = [];
ads.forEach((ad, i) => {
if (caches[i]) {
let cached = JSON.parse(caches[i]);
} else {
group.items.push(ad.html);
cache.set(ad.id, JSON.stringify(ad));
}
});
return group;
});
})
.then(group => {
if (group.items.length < 1) {
console.log("nada nuevo para ", name);
return null;
} else {
console.log("%s nuevos para %s", group.items.length, name);
return group;
}
})
.catch(e => {
console.log(e);
});
reqs.push(r);
});
Promise.all(reqs).then(groups => {
groups = _.compact(groups);
if (groups.length > 0) {
console.log(`enviando notificaciones a ${toEmail}`);
sendEmail(makeEmail(groups), toEmail, true);
} else {
console.log("nada que reportar");
process.exit(0);
}
});
});