-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.js
More file actions
418 lines (378 loc) · 13.7 KB
/
App.js
File metadata and controls
418 lines (378 loc) · 13.7 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
import React, { useEffect, useState, useRef } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import notifee, {
AndroidImportance,
TriggerType,
AuthorizationStatus,
EventType,
} from "@notifee/react-native";
import { NavigationContainer } from "@react-navigation/native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import AppNavigator from "./app/navigation/AppNavigator";
import { Modal, View, Text, TouchableOpacity, AppState, Platform, Linking, Alert } from "react-native";
import { DeviceEventEmitter } from 'react-native';
// Constants
const CHANNEL_ID = "watermate-reminders";
const DEFAULT_CUP_SIZE = 250;
const MIN_REMINDERS = 7;
const MAX_REMINDERS = 9;
// Notification titles for engagement
const NOTIFICATION_TITLES = [
"icl u no water pmo 😒",
"Dawggg… u crusty rn 💀",
"No water? This you? 👇",
"Ngl… go sip something rn 🫗",
"Ye thirst wali energy off hai 😶🌫️",
"Bro wake up, you need water frfr 🥲",
"Main hoon paani, mujhe chahiye tu 😤💧",
"You're dryin' out! 💦",
"Hydra-what? hydra-YOU! 🐍💦",
"Water > Drama. stay hydrated queen. 👑💧",
"C'mon gng, drink up!🫠",
"You're better than 'em, drink! 🥤",
"Hydrated ppl don't gatekeep ✨",
"Twin your body's running on fumes 😵💫",
"Canteen baad me, pehle paani! 🤨",
"Bottoms up bbg! ❤️",
"Geeli rizz incoming 🚰💅",
"Tough day? Wateeerrr! 💧",
"Open you mouth, take it all in! 💦",
"Pani pi le, bhai 🚰",
"Hydrate or diedrate 😵",
"Abey chug chug kar! 🍼",
"This ain't a thirst trap 👀💧",
"SIP happens 🤷♂️",
"Bois, it's water o'clock 🔔",
"Water you doing, bro? 🌊",
"Sookhe se lag rahe ho 👁👄👁",
"Drink like your ex is watching 🥴",
"POV: You forgot again! 😒",
"Jal le lijiye...🥛",
"Water gives you glowww 🌟",
"Naam batao, paani pilaun? 😉",
];
// --- Notification System ---
class NotificationSystem {
static async requestExactAlarmPermissionIfNeeded() {
if (Platform.OS === 'android' && Platform.Version >= 31) {
try {
const status = await notifee.requestPermission({
android: {
exactAlarms: true,
},
});
console.log('[Notifee] Exact alarm permission status:', status);
// Check if permission is still not granted
const settings = await notifee.getNotificationSettings();
if (settings.android?.exactAlarms === false) {
Alert.alert(
'Enable Exact Alarms',
'To receive timely reminders, please enable "Schedule exact alarms" for WaterMate in your device settings.',
[
{
text: 'Open Settings',
onPress: () => {
Linking.openSettings();
},
},
{ text: 'Cancel', style: 'cancel' },
]
);
}
} catch (e) {
console.error('[Notifee] Error requesting exact alarm permission:', e);
}
}
}
static async initialize() {
try {
// Check and request permissions
const settings = await notifee.getNotificationSettings();
console.log('[Notifee] Current settings:', settings);
if (settings.authorizationStatus !== AuthorizationStatus.AUTHORIZED) {
const authStatus = await notifee.requestPermission();
console.log('[Notifee] Permission status after request:', authStatus);
// Defensive: Try again to get the latest status
const newSettings = await notifee.getNotificationSettings();
console.log('[Notifee] New settings after request:', newSettings);
if (
newSettings.authorizationStatus !== AuthorizationStatus.AUTHORIZED &&
authStatus !== AuthorizationStatus.AUTHORIZED
) {
throw new Error('Notification permission denied');
}
}
// Request exact alarm permission for Android 12+
await this.requestExactAlarmPermissionIfNeeded();
// Create notification channel
await this.createNotificationChannel();
return true;
} catch (error) {
console.error('[Notifee] Initialization error:', error);
return false;
}
}
static async createNotificationChannel() {
try {
const channel = await notifee.createChannel({
id: CHANNEL_ID,
name: "WaterMate Reminders",
importance: AndroidImportance.HIGH,
vibration: true,
sound: 'default',
lights: true,
});
console.log('[Notifee] Channel created:', channel);
return channel;
} catch (error) {
console.error('[Notifee] Channel creation error:', error);
throw error;
}
}
static getRandomTitle() {
return NOTIFICATION_TITLES[Math.floor(Math.random() * NOTIFICATION_TITLES.length)];
}
static async scheduleHydrationReminders(wakeHour, sleepHour, numReminders) {
try {
console.log('[Notifee] Starting to schedule reminders:', { wakeHour, sleepHour, numReminders });
// Cancel existing notifications
await notifee.cancelAllNotifications();
const now = new Date();
const start = new Date(now);
start.setHours(wakeHour, 0, 0, 0);
const end = new Date(now);
end.setHours(sleepHour, 0, 0, 0);
if (end <= start) end.setDate(end.getDate() + 1);
const awakeMs = end - start;
const reminders = Math.max(MIN_REMINDERS, Math.min(MAX_REMINDERS, numReminders));
const intervalMs = awakeMs / reminders;
console.log('[Notifee] Scheduling parameters:', {
start: start.toISOString(),
end: end.toISOString(),
reminders,
intervalMs
});
const today = new Date();
const y = today.getFullYear(), m = today.getMonth(), d = today.getDate();
const todayTimes = [];
for (let i = 0; i < reminders; i++) {
const reminderTime = new Date(start.getTime() + i * intervalMs);
if (reminderTime <= now) {
reminderTime.setDate(reminderTime.getDate() + 1);
}
// Only save reminders for today
if (
reminderTime.getFullYear() === y &&
reminderTime.getMonth() === m &&
reminderTime.getDate() === d
) {
todayTimes.push(reminderTime.getTime());
}
// Final check before scheduling
if (reminderTime.getTime() <= Date.now()) {
console.warn('Skipping reminder in the past:', reminderTime);
continue;
}
const notification = {
title: this.getRandomTitle(),
body: "Stay hydrated for better health and energy.",
android: {
channelId: CHANNEL_ID,
pressAction: { id: "default" },
actions: [
{ title: "I Drank", pressAction: { id: "drank" } },
{ title: "Remind me later", pressAction: { id: "remind_later" } },
],
importance: AndroidImportance.HIGH,
sound: 'default',
vibration: true,
},
data: {
type: 'hydration_reminder',
reminderIndex: i,
totalReminders: reminders,
},
};
const trigger = {
type: TriggerType.TIMESTAMP,
timestamp: reminderTime.getTime(),
alarmManager: { allowWhileIdle: true },
};
await notifee.createTriggerNotification(notification, trigger);
console.log(`[Notifee] Scheduled reminder ${i + 1}/${reminders} for ${reminderTime.toLocaleString()}`);
}
// Save today's reminder times for UI
await AsyncStorage.setItem('reminderTimesToday', JSON.stringify(todayTimes));
return true;
} catch (error) {
console.error('[Notifee] Error scheduling reminders:', error);
return false;
}
}
static async scheduleDailyReset() {
try {
const now = new Date();
const midnight = new Date(now);
midnight.setHours(24, 0, 0, 0);
const notification = {
title: "🌙 Daily Reset",
body: "Resetting your daily water intake",
android: {
channelId: CHANNEL_ID,
pressAction: { id: "reset" },
importance: AndroidImportance.HIGH,
sound: 'default',
vibration: true,
},
data: { type: "daily_reset" },
};
const trigger = {
type: TriggerType.TIMESTAMP,
timestamp: midnight.getTime(),
alarmManager: { allowWhileIdle: true },
};
await notifee.createTriggerNotification(notification, trigger);
console.log(`[Notifee] Scheduled daily reset for ${midnight.toLocaleString()}`);
return true;
} catch (error) {
console.error('[Notifee] Error scheduling daily reset:', error);
return false;
}
}
static async handleDrankAction(notificationId) {
try {
const cupSize = parseInt(await AsyncStorage.getItem("cupSizePreference")) || DEFAULT_CUP_SIZE;
const today = new Date().toDateString();
const historyStr = await AsyncStorage.getItem("history");
const history = historyStr ? JSON.parse(historyStr) : [];
const entry = {
id: Date.now().toString(),
time: new Date().toLocaleTimeString(),
amount: cupSize,
date: today,
};
const updatedHistory = [entry, ...history];
await AsyncStorage.setItem("history", JSON.stringify(updatedHistory));
let intake = 0;
updatedHistory.forEach(e => { if (e.date === today) intake += e.amount; });
await AsyncStorage.setItem("dailyIntake", intake.toString());
DeviceEventEmitter.emit('waterIntakeUpdated');
if (notificationId) {
await notifee.cancelNotification(notificationId);
}
console.log('[Notifee] Drank action handled successfully');
return true;
} catch (error) {
console.error('[Notifee] Error handling drank action:', error);
return false;
}
}
static async handleRemindMeLater(notificationId) {
try {
if (notificationId) {
await notifee.cancelNotification(notificationId);
}
const reminderTime = new Date(Date.now() + 30 * 60 * 1000); // 30 minutes later
const notification = {
title: this.getRandomTitle(),
body: "Time for your water break!",
android: {
channelId: CHANNEL_ID,
pressAction: { id: "default" },
actions: [
{ title: "I Drank", pressAction: { id: "drank" } },
{ title: "Remind me later", pressAction: { id: "remind_later" } },
],
importance: AndroidImportance.HIGH,
sound: 'default',
vibration: true,
},
};
const trigger = {
type: TriggerType.TIMESTAMP,
timestamp: reminderTime.getTime(),
alarmManager: { allowWhileIdle: true },
};
await notifee.createTriggerNotification(notification, trigger);
console.log(`[Notifee] Rescheduled reminder for ${reminderTime.toLocaleString()}`);
return true;
} catch (error) {
console.error('[Notifee] Error handling remind later:', error);
return false;
}
}
}
// --- Event Handlers ---
notifee.onForegroundEvent(async ({ type, detail }) => {
console.log('[Notifee] Foreground event:', type, detail);
switch (type) {
case EventType.ACTION_PRESS:
if (detail?.pressAction?.id === "drank") {
await NotificationSystem.handleDrankAction(detail?.notification?.id);
} else if (detail?.pressAction?.id === "remind_later") {
await NotificationSystem.handleRemindMeLater(detail?.notification?.id);
} else if (detail?.pressAction?.id === "reset" || detail?.notification?.data?.type === "daily_reset") {
await AsyncStorage.setItem("dailyIntake", "0");
DeviceEventEmitter.emit('waterIntakeUpdated');
console.log('[Notifee] Daily reset completed');
}
break;
default:
break;
}
});
notifee.onBackgroundEvent(async ({ type, detail }) => {
console.log('[Notifee] Background event:', type, detail);
switch (type) {
case EventType.ACTION_PRESS:
if (detail?.pressAction?.id === "drank") {
await NotificationSystem.handleDrankAction(detail?.notification?.id);
} else if (detail?.pressAction?.id === "remind_later") {
await NotificationSystem.handleRemindMeLater(detail?.notification?.id);
} else if (detail?.pressAction?.id === "reset" || detail?.notification?.data?.type === "daily_reset") {
await AsyncStorage.setItem("dailyIntake", "0");
DeviceEventEmitter.emit('waterIntakeUpdated');
}
break;
default:
break;
}
});
// --- App Component ---
export default function App() {
const [initialRoute, setInitialRoute] = useState(null);
const [appReady, setAppReady] = useState(false);
useEffect(() => {
const init = async () => {
try {
// Move alarm permission check here, before any navigation
NotificationSystem.requestExactAlarmPermissionIfNeeded();
// Initialize notification system
const initialized = await NotificationSystem.initialize();
if (!initialized) {
console.error('[Notifee] Failed to initialize notification system');
setAppReady(true);
return;
}
// Check onboarding status
const onboarded = await AsyncStorage.getItem("onboardingCompleted");
setInitialRoute(onboarded === "true" ? "Home" : "Welcome");
setAppReady(true);
} catch (error) {
console.error('[Notifee] App initialization error:', error);
setAppReady(true);
}
};
init();
}, []);
if (!appReady) {
return null;
}
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<NavigationContainer>
<AppNavigator initialRoute={initialRoute} />
</NavigationContainer>
</GestureHandlerRootView>
);
}