File size: 3,281 Bytes
9f21d0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import dayjs from "dayjs";

export interface PushNotificationOptions extends NotificationOptions {
  [key: string]: unknown;
}

interface TimerEntry {
  id: ReturnType<typeof setTimeout>;
  date: Date | string | number | dayjs.Dayjs;
  message: string;
}

// Non-standard webkit message-handler bridge used by the iOS wrapper app
interface WebkitWindow {
  webkit?: {
    messageHandlers: {
      iosNotify: {
        postMessage(content: unknown, origin: string): void;
      };
    };
  };
}

export class PushManager {
  options: PushNotificationOptions;

  timers: TimerEntry[] = [];

  constructor(options: PushNotificationOptions = {}) {
    this.options = options;
  }

  get available(): boolean {
    if ("webkit" in window) {
      return true;
    }
    if (!("Notification" in window) || !("ServiceWorkerRegistration" in window)) {
      console.log("Notification API not supported!");
      return false;
    }
    switch (Notification.permission) {
      case "granted":
        return true;
      case "default":
        this.requestPermission();
        return true;
      case "denied":
        return false;
      default:
        return false;
    }
  }

  requestPermission(): void {
    Notification.requestPermission().then((result) => {
      console.log(`Notifcation permission result: ${result}`);
    });
  }

  get active(): boolean {
    return this.timers.length > 0;
  }

  clearTimers(): void {
    this.timers.forEach((timer) => {
      clearTimeout(timer.id);
    });
    this.timers = [];
  }

  persistentNotification(message: string, options?: PushNotificationOptions): void {
    if (!this.available) {
      return;
    }
    const optionsMerged = { ...this.options, ...options };
    try {
      navigator.serviceWorker
        .getRegistration()
        .then((reg) => reg?.showNotification(message, optionsMerged))
        .catch((err) => console.log(`Service Worker registration error: ${err}`));
    } catch (err) {
      console.log(`Notification API error: ${err}`);
    }
  }

  notifyInMs(ms: number, message: string, options?: PushNotificationOptions): void {
    if (!this.available) {
      return;
    }
    console.log(`Notify "${message}" in ${ms / 1000}s`);
    setTimeout(() => {
      this.persistentNotification(message, options);
    }, ms);
  }

  notifyAtDate(date: Date | string | number, message: string, options?: PushNotificationOptions): void {
    if (!this.available) {
      return;
    }
    const waitMs = dayjs(date).diff(dayjs());
    if (waitMs < 0) {
      return;
    }
    if (this.timers.some((timer) => Math.abs(dayjs(timer.date as Date).diff(date, "seconds")) < 10)) {
      console.log("Ignore duplicate entry");
      return;
    }
    console.log(`Notify "${message}" at ${date}s ${dayjs(date).unix()}`);

    if ("webkit" in window) {
      const content = {
        date: dayjs(date).unix(),
        delay: waitMs / 1000,
        message,
      };
      const w = window as unknown as WebkitWindow;
      w.webkit?.messageHandlers.iosNotify.postMessage(content, self.location.origin);
    } else {
      const id = setTimeout(() => {
        this.persistentNotification(message, options);
      }, waitMs);
      this.timers.push({
        id,
        date,
        message,
      });
    }
  }
}