-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
79 lines (63 loc) · 2.2 KB
/
background.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
const defaultInterval = 60
const defaultDuration = 1
const useOptions = callback => chrome.storage.sync.get({
awarenessReminderInterval: defaultInterval,
awarenessReminderDuration: defaultDuration,
}, options => callback(options))
function clearPreviousNotifications () {
chrome.notifications.getAll(notifications => {
const ids = Object.keys(notifications)
ids.forEach(id => {
if (id.includes('breath_watch_reminder')) {
chrome.notifications.clear(id)
}
})
})
}
function createNotification ({ id, requireInteraction }) {
clearPreviousNotifications()
const notificationOptions = {
type: "basic",
title: "Watch your breath",
message: "It's time to become mindful of your breath.",
iconUrl: "images/breath_watch128.png",
requireInteraction,
}
chrome.notifications.create(id, notificationOptions)
}
function triggerReminder () {
const timeNow = Date.now()
const id = `breath_watch_reminder_${timeNow}`
let timeToPersist = defaultDuration * 60000
useOptions(options => {
if (options) timeToPersist = parseInt(options.awarenessReminderDuration, 10)
const requireInteraction = timeToPersist !== 0
createNotification({ id, requireInteraction })
if (timeToPersist < 1) return
setTimeout(() => chrome.notifications.clear(id), timeToPersist)
})
}
function createInterval ({ trigger }) {
let periodInMinutes = defaultInterval
useOptions(options => {
if (options) periodInMinutes = parseInt(options.awarenessReminderInterval, 10)
chrome.alarms.create("BreathWatch Alert", { periodInMinutes })
if (trigger) triggerReminder()
})
}
chrome.runtime.onInstalled.addListener(() => createInterval({ trigger: true }))
chrome.runtime.onStartup.addListener(() => createInterval({ trigger: true}))
chrome.alarms.onAlarm.addListener(() => triggerReminder())
chrome.storage.onChanged.addListener(changes => {
const valuesToWatch = ['awarenessReminderInterval', 'awarenessReminderDuration']
const filteredChanges = valuesToWatch.reduce((obj, key) => {
const filtered = {
...obj,
[key]: changes[key]
}
return changes[key] ? filtered : obj
}, {})
if (filteredChanges) {
createInterval({ trigger: false })
}
})