-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
379 lines (337 loc) · 10.2 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
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// load env
const dotenv = require("dotenv");
dotenv.config();
// scheduler for checking content
const { ToadScheduler, SimpleIntervalJob, Task } = require("toad-scheduler");
const scheduler = new ToadScheduler();
// init service
const TgtgService = require("./tgtgService");
const tgtg = new TgtgService(
process.env.TGTG_REFRESH_TOKEN,
process.env.TGTG_User
);
const PushService = require("./pushService");
const ReserveService = require("./reserveService");
const RESERVE_ITEMS = process.env.RESERVE_ITEMS || [];
const reserver = new ReserveService(RESERVE_ITEMS);
const ExternalService = require("./externalService");
const exService = new ExternalService();
let reqMap = {};
let didNotifyError = false;
let pushService = null;
// launch notification
const ENABLE_NOTIFICATION_ANNOUNCEMENT = process.env.PO_ANNOUNCE || "0";
let notificationOnAnnounced = false;
let notificationOffAnnounced = false;
let notificatonLastStatusIsEnabled = false;
// default request cycle
const REQUEST_TIMER = process.env.REQ_TIMER || 60;
console.log(REQUEST_TIMER);
function getPushService() {
if (pushService == null) {
pushService = new PushService(process.env.PO_USER, process.env.PO_TOKEN);
}
return pushService;
}
function pushItem(item) {
const pushCallback = function (err, result) {
if (err) {
throw err;
}
console.log(result);
};
let pickupTime = "";
if (Object.prototype.hasOwnProperty.call(item, "pickup_interval")) {
if (
Object.prototype.hasOwnProperty.call(item.pickup_interval, "start") &&
Object.prototype.hasOwnProperty.call(item.pickup_interval, "end")
) {
let startTime = item.pickup_interval.start;
let startDate = new Date(startTime);
let endTime = item.pickup_interval.end;
let endDate = new Date(endTime);
const pickDate = startDate.toLocaleDateString("de-DE");
const options = {
hour: "2-digit",
minute: "2-digit",
timeZone: "Europe/Berlin",
};
const pickStart = startDate.toLocaleTimeString("de-DE", options);
const pickEnd = endDate.toLocaleTimeString("de-DE", options);
pickupTime = `${pickDate}\n${pickStart} - ${pickEnd}`;
}
}
let rating = "";
if (Object.prototype.hasOwnProperty.call(item, "item")) {
if (
Object.prototype.hasOwnProperty.call(item.item, "average_overall_rating")
) {
if (
Object.prototype.hasOwnProperty.call(
item.item.average_overall_rating,
"average_overall_rating"
)
) {
const avg = item.item.average_overall_rating.average_overall_rating;
if (avg != null && avg !== undefined) {
rating = `(⭐️${avg.toFixed(2)})`;
}
}
}
}
// fetch number of reserving items & prevent double ordering
const count = reserver.checkReserve(item);
if (count > 0) {
// notify user about reserving
getPushService().pushNotification(
item.display_name,
`Reservierte Anzahl: ${count} [${item.items_available}] \n${pickupTime}`,
pushCallback
);
const reserveCallback = function (order, err) {
if (err == null) {
tgtg.cancelItem(order.id);
} else {
console.log(JSON.stringify(err));
}
};
// reserve
tgtg.orderItem(`${item.item.item_id}`, count, reserveCallback);
return;
}
getPushService().pushNotification(
item.display_name,
`Anzahl: ${item.items_available} ${rating} \n${pickupTime}\n${parseFloat(
item.item.item_price.minor_units / 100.0
).toFixed(item.item.item_price.decimals)} ${item.item.item_price.code}`,
pushCallback
);
}
function checkItemForPush(itemResp) {
const response = itemResp;
// prevent aborting
if (response == null || response === undefined) {
if (!didNotifyError) {
didNotifyError = true;
console.log(
`${new Date().toLocaleString(
"de-DE"
)}| Error fetching response: ${response}`
);
getPushService().pushNotification(
"Error fetching response",
"" + response
);
}
return;
}
if (!Object.prototype.hasOwnProperty.call(response, "item")) {
if (!didNotifyError) {
didNotifyError = true;
console.log(
`${new Date().toLocaleString(
"de-DE"
)}| Error fetching response.item: ${JSON.stringify(response)}`
);
getPushService().pushNotification(
"Error fetching response.item",
JSON.stringify(response)
);
}
return;
}
if (!Object.prototype.hasOwnProperty.call(response.item, "item_id")) {
if (!didNotifyError) {
didNotifyError = true;
console.log(
`${new Date().toLocaleString(
"de-DE"
)}| Error fetching item_id: ${JSON.stringify(response)}`
);
getPushService().pushNotification(
"Error fetching item_id",
"" + JSON.stringify(response.item)
);
}
return;
}
// request was valid
didNotifyError = false;
if (Object.prototype.hasOwnProperty.call(reqMap, response.item.item_id)) {
if (
response.items_available > 0 &&
reqMap[response.item.item_id].items_available < response.items_available
) {
// new items added
pushItem(response);
} else {
// check dynamic price change
if (
reqMap[response.item.item_id].item_card_type === "DYNAMIC_PRICE" &&
reqMap[response.item.item_id].item_price >
response.item.item_price.minor_units &&
response.items_available > 0
) {
// push for price decrease and items are available
pushItem(response);
} else {
// no changes
console.log(
`${new Date().toLocaleString("de-DE")}| ${response.item.item_id}: ${
response.display_name
} - Count ${response.items_available}`
);
}
}
} else {
if (response.items_available > 0) {
// first call and item is available
pushItem(response);
} else {
// first call and not available
console.log(
`${new Date().toLocaleString("de-DE")}| ${response.item.item_id}: ${
response.display_name
} not available`
);
}
}
let requestData = {};
requestData["items_available"] = response.items_available;
requestData["item_card_type"] = "DEFAULT";
if (
Object.prototype.hasOwnProperty.call(response, "item") &&
Object.prototype.hasOwnProperty.call(response.item, "item_price") &&
Object.prototype.hasOwnProperty.call(
response.item.item_price,
"minor_units"
)
) {
requestData["item_price"] = response.item.item_price.minor_units;
}
if (Object.prototype.hasOwnProperty.call(response, "item_card")) {
if (
Object.prototype.hasOwnProperty.call(response.item_card, "item_card_type")
) {
requestData["item_card_type"] = response.item_card.item_card_type;
}
}
// save item data
reqMap[response.item.item_id] = requestData;
}
const task = new Task("simple task", () => {
// check whether external source can be accessed
const exCallback = function (body, resp, err) {
// external service not configured
const date = new Date();
const hour = parseInt(
date.toLocaleString("en-GB", {
hour: "2-digit",
hour12: false,
timeZone: "Europe/Berlin",
})
);
if (
(body === undefined && resp === undefined && err === undefined) ||
(err !== undefined && err !== null)
) {
// only check between 6-22
if (hour > 6 && hour < 22) {
triggerCheckItems();
} else if (hour > 22) {
// after 10 pm reset checks
reserver.reset();
}
} else {
// use time settings from external service
// body data
// _id: string;
// enabled: number;
// start: string;
// end: string;
// startHour: number;
// endHour: number;
if (Object.prototype.hasOwnProperty.call(body, "enabled")) {
if (body.enabled === 1) {
if (
ENABLE_NOTIFICATION_ANNOUNCEMENT === "1" &&
!notificationOnAnnounced
) {
if (!notificatonLastStatusIsEnabled) {
notificationOnAnnounced = true;
notificationOffAnnounced = false;
// enabled=false => enabled=true
getPushService().pushNotificationWithPriority(
"Information",
"tgtg-checker ON",
-1,
(err, result) => {}
);
}
}
// only check between start and end
if (hour > body.startHour && hour < body.endHour) {
triggerCheckItems();
} else if (hour > body.endHour) {
// after 10 pm reset checks
reserver.reset();
}
} else {
// disabled checking
if (
ENABLE_NOTIFICATION_ANNOUNCEMENT === "1" &&
!notificationOffAnnounced
) {
if (!notificatonLastStatusIsEnabled) {
notificationOffAnnounced = true;
notificationOnAnnounced = false;
// enabled=false => enabled=true
getPushService().pushNotificationWithPriority(
"Information",
"tgtg-checker OFF",
-1,
(err, result) => {}
);
}
}
}
// update last status
notificatonLastStatusIsEnabled = body.enabled === 1;
} else {
console.log("External data could not processed");
}
}
};
exService.getTgNotification(exCallback);
});
function triggerCheckItems() {
const LIST = JSON.parse(process.env.ITEMS);
if (LIST.length > 0) {
const callback = function (item, err) {
if (err == null) {
checkItemForPush(item);
} else {
console.log("bad request " + err);
}
};
// check item
tgtg.checkItems(LIST, callback);
} else {
// req all items from favorites
const callback = function (favItem, err) {
if (err == null) {
checkItemForPush(favItem);
} else {
console.log(JSON.stringify(err));
}
};
tgtg.checkfavorites(callback);
}
}
const job1 = new SimpleIntervalJob(
{ seconds: REQUEST_TIMER, runImmediately: true },
task,
"id_1"
);
// create and start jobs
scheduler.addSimpleIntervalJob(job1);