Open History to see the last commit
1import * as Notifications from "expo-notifications";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4import { Platform } from "react-native";
5import { msg } from "gt-react-native";
6
7import { m } from "../../i18n/messages";
8
9export type NotificationPermissionResult =
10 | { readonly type: "unsupported" }
11 | { readonly type: "granted" }
12 | { readonly type: "denied"; readonly canAskAgain: boolean };
13
14export class NotificationPermissionReadError extends Schema.TaggedError<NotificationPermissionReadError>()(
15 "NotificationPermissionReadError",
16 {
17 cause: Schema.Defect(),
18 },
19) {
20 override get message(): string {
21 return m(msg("Failed to read notification permissions."));
22 }
23}
24
25export class NotificationPermissionRequestError extends Schema.TaggedError<NotificationPermissionRequestError>()(
26 "NotificationPermissionRequestError",
27 {
28 cause: Schema.Defect(),
29 },
30) {
31 override get message(): string {
32 return m(msg("Failed to request notification permissions."));
33 }
34}
35
36export const requestAgentNotificationPermission: Effect.Effect<
37 NotificationPermissionResult,
38 NotificationPermissionReadError | NotificationPermissionRequestError
39> = Effect.gen(function* () {
40 if (Platform.OS !== "ios" && Platform.OS !== "android") {
41 return { type: "unsupported" };
42 }
43
44 if (Platform.OS === "android") {
45 yield* Effect.tryPromise({
46 try: () =>
47 Notifications.setNotificationChannelAsync("agent-alerts", {
48 name: m(msg("Agent alerts")),
49 importance: Notifications.AndroidImportance.HIGH,
50 }),
51 catch: (cause) => new NotificationPermissionRequestError({ cause }),
52 });
53 }
54
55 const existing = yield* Effect.tryPromise({
56 try: () => Notifications.getPermissionsAsync(),
57 catch: (cause) => new NotificationPermissionReadError({ cause }),
58 });
59 if (existing.granted) {
60 return { type: "granted" };
61 }
62
63 if (!existing.canAskAgain) {
64 return { type: "denied", canAskAgain: false };
65 }
66
67 const requested = yield* Effect.tryPromise({
68 try: () =>
69 Notifications.requestPermissionsAsync({
70 ios: {
71 allowAlert: true,
72 allowBadge: true,
73 allowSound: true,
74 },
75 }),
76 catch: (cause) => new NotificationPermissionRequestError({ cause }),
77 });
78 return requested.granted
79 ? { type: "granted" }
80 : { type: "denied", canAskAgain: requested.canAskAgain };
81});