summaryrefslogtreecommitdiff
path: root/lib/notifications.ts
blob: a9c9a958a18219841536216a969272d5532a30c6 (plain)
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import Constants from "expo-constants";
import * as Device from "expo-device";
import * as Notifications from "expo-notifications";
import { Platform } from "react-native";
import { apiClient } from "../api/client";

// Configure notification handling behavior
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: true,
    shouldShowBanner: true,
    shouldShowList: true,
  }),
});

export type NotificationPermissionStatus =
  | "granted"
  | "denied"
  | "undetermined";

/**
 * Get current notification permission status
 */
export async function getNotificationPermissionStatus(): Promise<NotificationPermissionStatus> {
  const { status } = await Notifications.getPermissionsAsync();
  return status;
}

/**
 * Request notification permissions from the user
 */
export async function requestNotificationPermissions(): Promise<NotificationPermissionStatus> {
  // Check if we're on a physical device (notifications don't work on simulator)
  if (!Device.isDevice) {
    console.log("Push notifications require a physical device");
    return "denied";
  }

  // Get existing permissions first
  const { status: existingStatus } = await Notifications.getPermissionsAsync();

  let finalStatus = existingStatus;

  // Only ask if permissions have not already been determined
  if (existingStatus !== "granted") {
    const { status } = await Notifications.requestPermissionsAsync();
    finalStatus = status;
  }

  return finalStatus;
}

/**
 * Get the Expo push token for this device
 */
export async function getExpoPushToken(): Promise<string | null> {
  if (!Device.isDevice) {
    console.log("Push notifications require a physical device");
    return null;
  }

  const { status } = await Notifications.getPermissionsAsync();
  if (status !== "granted") {
    console.log("Notification permissions not granted");
    return null;
  }

  try {
    // Get the project ID from Expo config
    const projectId =
      Constants.expoConfig?.extra?.eas?.projectId ??
      Constants.easConfig?.projectId;

    if (!projectId) {
      console.error("Project ID not found in Expo config");
      return null;
    }

    const tokenData = await Notifications.getExpoPushTokenAsync({
      projectId,
    });

    return tokenData.data;
  } catch (error) {
    console.error("Failed to get Expo push token:", error);
    return null;
  }
}

/**
 * Register push token with the backend
 */
export async function registerPushToken(): Promise<boolean> {
  const token = await getExpoPushToken();

  if (!token) {
    console.log("No push token available to register");
    return false;
  }

  try {
    await apiClient.post("/parent/push-token", { token });
    console.log("Push token registered successfully");
    return true;
  } catch (error) {
    console.error("Failed to register push token:", error);
    return false;
  }
}

/**
 * Remove push token from the backend
 */
export async function unregisterPushToken(): Promise<boolean> {
  const token = await getExpoPushToken();

  if (!token) {
    console.log("No push token available to unregister");
    return false;
  }

  try {
    await apiClient.delete("/parent/push-token", { token });
    console.log("Push token unregistered successfully");
    return true;
  } catch (error) {
    console.error("Failed to unregister push token:", error);
    return false;
  }
}

/**
 * Set up Android notification channel for alerts
 */
export async function setupNotificationChannels(): Promise<void> {
  if (Platform.OS === "android") {
    await Notifications.setNotificationChannelAsync("default", {
      name: "Default",
      importance: Notifications.AndroidImportance.DEFAULT,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: "#FF231F7C",
    });

    await Notifications.setNotificationChannelAsync("alerts", {
      name: "Safety Alerts",
      description: "Important safety alerts about your child's device",
      importance: Notifications.AndroidImportance.HIGH,
      vibrationPattern: [0, 500, 250, 500],
      lightColor: "#FF0000",
      sound: "default",
      enableVibrate: true,
      enableLights: true,
    });
  }
}

/**
 * Add a listener for received notifications (when app is foregrounded)
 */
export function addNotificationReceivedListener(
  callback: (notification: Notifications.Notification) => void
): Notifications.EventSubscription {
  return Notifications.addNotificationReceivedListener(callback);
}

/**
 * Add a listener for notification responses (when user taps notification)
 */
export function addNotificationResponseListener(
  callback: (response: Notifications.NotificationResponse) => void
): Notifications.EventSubscription {
  return Notifications.addNotificationResponseReceivedListener(callback);
}

/**
 * Get the last notification response (for handling cold start from notification)
 */
export async function getLastNotificationResponse(): Promise<Notifications.NotificationResponse | null> {
  return Notifications.getLastNotificationResponseAsync();
}

/**
 * Initialize notifications: setup channels, request permissions, and register token
 * Call this when the user is authenticated
 */
export async function initializeNotifications(): Promise<{
  permissionStatus: NotificationPermissionStatus;
  tokenRegistered: boolean;
}> {
  // Setup Android channels first
  await setupNotificationChannels();

  // Request permissions
  const permissionStatus = await requestNotificationPermissions();

  if (permissionStatus !== "granted") {
    return { permissionStatus, tokenRegistered: false };
  }

  // Register token with backend
  const tokenRegistered = await registerPushToken();

  return { permissionStatus, tokenRegistered };
}