forked from aidiss/barbora-delivery-spot-alert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
90 lines (72 loc) · 2.19 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
import env from 'dotenv'
import fetch from 'node-fetch'
import notifier from 'node-notifier'
env.config()
const { LATEST_DELIVERY_INTERVAL_IN_DAYS, COOKIE, FCM_SERVER_KEY, FCM_TOKEN } = process.env
const host = 'https://pagrindinis.barbora.lt'
const deliveryTimesURL = `${host}/api/eshop/v1/cart/deliveries`
const deliveryRequestInfo = {
headers: {
Authorization: 'Basic YXBpa2V5OlNlY3JldEtleQ==',
Cookie: COOKIE
}
}
const fcmURL = 'https://fcm.googleapis.com/fcm/send'
const fcmRequestInfo = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `key=${FCM_SERVER_KEY}`
}
}
const notificationTitle = 'Barbora available delivery times'
async function run() {
const response = await fetch(deliveryTimesURL, deliveryRequestInfo)
if (response.status !== 200) {
return console.log(response.status)
}
const body = await response.json()
const availableTimes = filterAvailableTimes(body.deliveries[0].params.matrix)
if (availableTimes.length) {
const message = availableTimes.join(', ')
if (FCM_TOKEN) {
fetch(fcmURL, {
...fcmRequestInfo,
body: JSON.stringify({
to: FCM_TOKEN,
notification: {
title: notificationTitle,
body: message
}
})
})
} else {
notifier.notify({
title: notificationTitle,
message,
open: host
})
}
}
}
function filterAvailableTimes(list) {
const availableTimes = list.flatMap(({ hours }) =>
hours.filter(({ available }) => available).map(({ deliveryTime }) => deliveryTime)
)
if (LATEST_DELIVERY_INTERVAL_IN_DAYS) {
const latestDate = new Date()
latestDate.setDate(latestDate.getDate() + parseInt(LATEST_DELIVERY_INTERVAL_IN_DAYS))
latestDate.setHours(23, 59, 59, 999)
const timesBeforeLatestDate = availableTimes.filter(time => {
const date = new Date(time)
return date.getTime() < latestDate.getTime()
})
if (availableTimes.length && !timesBeforeLatestDate.length) {
console.log('Available times found but filtered by latest delivery interval')
}
return timesBeforeLatestDate
}
return availableTimes
}
setInterval(run, 60000)
run()