-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
180 lines (148 loc) · 5.16 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
"use strict";
const fs = require("fs");
const express = require("express")
const puppeteer = require("puppeteer");
const flatCache = require("flat-cache");
const debounce = require("underscore/cjs/debounce");
const EventSource = require("eventsource");
const cache = flatCache.load("cache");
const PORT = process.env.PORT || 3001;
const USERNAME = process.env.USERNAME || "<your email here if you want>";
const PASSWORD = process.env.PASSWORD || "<your password here>";
const WEBHOOKURL = process.env.WEBHOOKURL || "<webhook url here>";
const DEBUG = process.env.DEBUG || false;
const HEADLESS = process.env.HEADLESS === "false" ? false : true;
const SANBOXMODE = process.env.SANBOXMODE || false;
const app = express();
const getFileUpdatedDate = () => fs.statSync(cache._pathToFile).mtime;
const log = (msg) => {if (DEBUG) console.log(msg)};
try {
// if no cache exists initialize it
if (!fs.existsSync(cache._pathToFile)) {
const pastDate = new Date('Wed Jan 1 2020 00:00:00 GMT+0800 (CST)');
cache.setKey("cookie", JSON.stringify({}));
cache.setKey("carbs", null);
cache.setKey("calories", null);
cache.save(true);
fs.utimesSync(cache._pathToFile, pastDate, pastDate);
}
} catch(err) {
// do nothing
}
// if there is a webhook url set listen for incoming data from it.
if (WEBHOOKURL) {
const evtSource = new EventSource(WEBHOOKURL);
evtSource.onmessage = (event) => {
const data = JSON.parse(event.data);
log("Saving data from webhook");
saveData(data);
log("Data saved from webhook: "+ event.data);
};
}
// debounce this so it doesn't open 10,000 browser sessions if user hits refresh non-stop.
const checkForData = debounce(() => {
const hours = 60 * 120 * 1000;
const lastUpdated = getFileUpdatedDate();
log("Date last updated: " + lastUpdated);
if (!lastUpdated || new Date() - new Date(lastUpdated) > hours) {
log("Fetching new data via webdriver...")
startDataScrape(cache);
}
}, 1000);
const saveData = (data) => {
cache.setKey("carbs", data.carbs);
cache.setKey("calories", data.calories);
cache.save(true);
};
async function doLogin(page) {
await page.waitFor(1000);
const emailInput = "#login_user_form input[name=username]";
const passwordInput = "#login_user_form input[name=password]";
const loginSubmitBtn = "#login_user_form button[type=submit]";
await page.focus(emailInput);
await page.type(emailInput, USERNAME);
await page.type(passwordInput, PASSWORD);
await page.click(loginSubmitBtn);
await page.waitForSelector(".servingsPanel");
}
async function saveCookies(page) {
const cookiesObject = await page.cookies();
log("***** Cooke data saved *****");
log("cookie: " + JSON.stringify(cookiesObject));
cache.setKey("cookie", JSON.stringify(cookiesObject));
cache.save(true);
}
async function parseData(page, cache) {
await page.waitFor(4000);
const data = await page.evaluate(function() {
let carbs = document.querySelector(".diary_side_box .summary-carbs").textContent;
carbs = carbs.replace(/\s\(\d+%\)/gi, "").replace(/\sg/gi, "").replace(/\s+/gi, "").split("/");
const carbsAllowed = carbs[1];
const calories = document.querySelectorAll(".diary_side_box img")[1].nextElementSibling.textContent;
const totalCarbs = Math.round(carbsAllowed - parseFloat(carbs[0]));
const totalCalories = parseInt(calories, 10);
if (totalCarbs && totalCalories) {
return {
carbs: totalCarbs,
calories: totalCalories,
};
}
});
log("***** Data parsed *****");
log(data);
saveData(data);
}
async function startDataScrape(cache) {
const url = "https://cronometer.com/";
const cookies = JSON.parse(cache.getKey("cookie"));
let options = {headless: HEADLESS};
if (SANBOXMODE) {
options["args"] = ['--no-sandbox'];
}
const browser = await puppeteer.launch(options);
const page = await browser.newPage();
if (cookies && cookies.length) {
for (let cookie of cookies) {
await page.setCookie(cookie);
}
log("***** Current session cookies set *****");
}
page.on("console", consoleObj => log(consoleObj.text()));
await page.goto(url);
await page.waitFor(1000);
// Surely there's a better way?
try {
await page.waitForSelector(".servingsPanel", 10000);
log("**** LOGGED IN ****");
await parseData(page, cache);
await saveCookies(page);
} catch (err) {
await page.goto("https://cronometer.com/login/");
log("**** NOT LOGGED IN: logging in... ****");
await doLogin(page);
await parseData(page, cache);
await saveCookies(page);
}
browser.close();
}
// Use pug templates cuz I'm hipster like that.
app.set("view engine", "pug");
app.set("views", "./templates");
app.use(express.static(__dirname + "/public"));
app.get("/json", async (req, res, next) => {
await checkForData();
res.json({
carbs: cache.getKey("carbs"),
calories: cache.getKey("calories")
});
next();
});
app.get("/", async (req, res, next) => {
await checkForData();
res.render("base", {
carbs: cache.getKey("carbs"),
calories: cache.getKey("calories")
});
next();
});
app.listen(PORT, () => console.log(`Example app listening on port ${PORT}!`));