|
| 1 | +import Browser, { Alarms } from 'webextension-polyfill'; |
| 2 | +import { logger } from '../compositions/logger'; |
| 3 | +import { StorageParams } from '../storage/storage-params'; |
| 4 | +import { injecStorage } from '../storage/inject-storage'; |
| 5 | +import { DAY_MINUTES, getNextTimeOfDay } from '../utils/time'; |
| 6 | + |
| 7 | +export enum JobId { |
| 8 | + DailySummaryNotification = '@alarm/daily-summary-notification', |
| 9 | +} |
| 10 | + |
| 11 | +export function scheduleJobs(): void { |
| 12 | + Browser.alarms.onAlarm.addListener(async alarm => { |
| 13 | + logger.log(`[schedule-jobs] Alarm ${alarm.name} triggered`, alarm); |
| 14 | + switch (alarm.name) { |
| 15 | + case JobId.DailySummaryNotification: { |
| 16 | + //await dailySummaryNotification(); |
| 17 | + break; |
| 18 | + } |
| 19 | + } |
| 20 | + logger.log(`[schedule-jobs] ${alarm.name} finished`); |
| 21 | + }); |
| 22 | + |
| 23 | + Browser.runtime.onInstalled.addListener(rescheduleJobs); |
| 24 | +} |
| 25 | + |
| 26 | +async function rescheduleJobs(): Promise<void> { |
| 27 | + const storage = injecStorage(); |
| 28 | + const dailySummaryNotificationTime = (await storage.getValue( |
| 29 | + StorageParams.DAILY_SUMMARY_NOTIFICATION_TIME, |
| 30 | + )) as number; |
| 31 | + await Browser.alarms.clear(JobId.DailySummaryNotification); |
| 32 | + Browser.alarms.create(JobId.DailySummaryNotification, { |
| 33 | + when: getNextTimeOfDay(dailySummaryNotificationTime), |
| 34 | + periodInMinutes: DAY_MINUTES, |
| 35 | + }); |
| 36 | +} |
| 37 | + |
| 38 | +async function createAlarmIfMissing( |
| 39 | + name: string, |
| 40 | + alarmInfo: Alarms.CreateAlarmInfoType, |
| 41 | +): Promise<void> { |
| 42 | + const existing = await Browser.alarms.get(name).catch(() => undefined); |
| 43 | + if (existing == null) { |
| 44 | + Browser.alarms.create(name, alarmInfo); |
| 45 | + } |
| 46 | +} |
0 commit comments