summaryrefslogtreecommitdiff
path: root/app/(tabs)/index.tsx
blob: 6f196eab60df6b1767fd77e051684027a8d288d2 (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
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
import {
  Alert,
  Platform,
  Pressable,
  StyleSheet,
  Text,
  TextInput,
  View,
} from "react-native";
import ParallaxScrollView from "@/components/ParallaxScrollView";
import { ThemedText } from "@/components/ThemedText";
import { ThemedView } from "@/components/ThemedView";
import React, { useState, useEffect, useRef, useCallback } from "react";
import AsyncStorage from "@react-native-async-storage/async-storage";
import MapView, { LatLng, Marker } from "react-native-maps";
import * as Notifications from "expo-notifications";
import * as Device from "expo-device";
import * as Location from "expo-location";
import Constants from "expo-constants";
import { Link, useFocusEffect } from "expo-router";
import * as TaskManager from "expo-task-manager";
import { Audio } from 'expo-av';

const LOCATION_TASK_NAME = "background-location-task";

/**
 * Task manager task definition for background location tracking.
 * This function processes incoming location data in the background.
 * If an error occurs, it logs the error to the console.
 * @param {Object} task - Task data including location and error.
 */
TaskManager.defineTask(LOCATION_TASK_NAME, async ({ data, error }) => {
  if (error) {
    console.error(error);
    return;
  }
  if (data) {
    const { locations } = data;
    console.log("Received new locations:", locations);
    updateLocation(location.coords, location.coords.speed);
    // Process the locations here
  }
});

interface NotificationPositionData {
  movingActivity: string;
}

interface NotificationAlertData {
  text1: string;
  text2: string;
  text3: string;
}

interface NotificationData {
  id: string;
  createdAt: string;
  level: string;
  alert: NotificationAlertData;
  position: NotificationPositionData;
}

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: false,
  }),
});

/**
 * Displays an alert with an error message related to push notification registration.
 * @param {string} errorMessage - The error message to be shown in the alert.
 */
function handleRegistrationError(errorMessage: string) {
  Alert.alert("Error registering this device", errorMessage);
}

/**
 * Registers the device for push notifications. Requests permission and retrieves a push token.
 * Supports Android-specific notification channel setup.
 * @returns {Promise<string | undefined>} - The push token or undefined if registration fails.
 */
async function registerForPushNotificationsAsync(): Promise<string | undefined> {
  if (Platform.OS === "android") {
    Notifications.setNotificationChannelAsync("default", {
      name: "default",
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: "#007AFF",
    });
  }

  if (Device.isDevice) {
    const { status: existingStatus } =
      await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== "granted") {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== "granted") {
      handleRegistrationError(
        "Permission not granted to get push token for push notification!",
      );
      return;
    }
    const projectId =
      Constants?.expoConfig?.extra?.eas?.projectId ??
      Constants?.easConfig?.projectId;
    if (!projectId) {
      handleRegistrationError("Project ID not found");
    }
    try {
      const pushTokenString = (
        await Notifications.getExpoPushTokenAsync({
          projectId,
        })
      ).data;
      return pushTokenString;
    } catch (e: unknown) {
      handleRegistrationError(`${e}`);
    }
  } else {
    handleRegistrationError("Must use physical device for push notifications");
  }
}

export default function HomeScreen() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [token, setToken] = useState("");
  const [userId, setUserId] = useState("");
  const [coordinates, setCoordinates] = useState({
    latitude: 0,
    longitude: 0,
  });
  const [region, setRegion] = useState({
    latitude: 0,
    longitude: 0,
    latitudeDelta: 0.03,
    longitudeDelta: 0.03,
  });
  const [notification, setNotification] = useState<NotificationData | null>(
    null,
  );
  const mapRef = useRef(null);

  const [sound, setSound] = useState<Audio.Sound | null>(null);

  async function playSound(uri: any) {
    const { sound } = await Audio.Sound.createAsync({ uri });
    setSound(sound);
    await sound.playAsync();
  }

  /**
   * Stores the token in AsyncStorage (or localStorage for web). This is used to persist user tokens.
   * @param {string} token - The token to be stored.
   */
  const storeToken = async (token: string) => {
    if (Platform.OS === "web") {
      localStorage.setItem("token", token);
    } else {
      await AsyncStorage.setItem("token", token);
    }
  };

  /**
   * Stores the user ID in AsyncStorage (or localStorage for web). Used for persisting user session data.
   * @param {string} userId - The user ID to be stored.
   */
  const storeUserId = async (userId: string) => {
    if (Platform.OS === "web") {
      localStorage.setItem("userId", userId);
    } else {
      await AsyncStorage.setItem("userId", userId);
    }
  };

  /**
   * Handles the login process by sending login credentials to the server,
   * storing the returned token and user ID, and registering for push notifications.
   */
  const handleLogin = async () => {
    if (!email || !password) {
      Alert.alert("Error", "Email and password are required.");
      return;
    }

    try {
      const response = await fetch(
        `${process.env.EXPO_PUBLIC_API_URL}/graphql`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            query: `
            mutation Login($input: LoginCredentials!) {
              login(input: $input) {
                accessToken
                tokenType
                userId
              }
            }`,
            variables: {
              input: {
                email: email,
                password,
              },
            },
          }),
        },
      );

      const data = await response.json();

      if (data.errors) {
        const errorMessages = data.errors.map((error: any) => error.message);
        Alert.alert("Error", errorMessages.join("\n"));
      } else {
        const { accessToken, userId } = data.data.login;
        await storeToken(accessToken);
        await storeUserId(String(userId));
        setToken(accessToken);
        setUserId(String(userId));

        registerForPushNotificationsAsync()
          .then(async (notificationToken) => {
            if (!notificationToken) return;

            const regex = /ExponentPushToken\[(.*?)\]/;
            const match = notificationToken.match(regex);

            if (match && match[1]) {
              notificationToken = match[1];
            }
            await fetch(`${process.env.EXPO_PUBLIC_API_URL}/graphql`, {
              method: "POST",
              headers: {
                Authorization: `Bearer ${accessToken}`,
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                query: `
                    mutation RegisterDevice($input: RegisterNotificationToken!) {
                      registerDevice(input: $input) { id name email }
                    }
                  `,
                variables: {
                  input: {
                    token: notificationToken,
                  },
                },
              }),
            });
          })
          .catch((error: any) => alert(`${error}`));
        fetchNotifications();
      }
    } catch (err) {
      console.error("Login Error:", err);
      Alert.alert("Error", "An error occurred during login.");
    }
  };

  /**
   * Handles the logout process by removing the stored token and user ID, clearing user session data.
   */
  const handleLogout = async () => {
    await removeToken();
  };

  /**
   * Removes the stored token and user ID from AsyncStorage (or localStorage for web).
   */
  const removeToken = async () => {
    if (Platform.OS === "web") {
      localStorage.removeItem("token");
      localStorage.removeItem("userId");
    } else {
      await AsyncStorage.removeItem("token");
      await AsyncStorage.removeItem("userId");
    }
    setToken("");
    setUserId("");
  };

  /**
   * Formats a given timestamp into a readable date string with the format "Day Mon DD YYYY HH:mm".
   * @param {string} timestamp - The timestamp (in seconds) to be formatted.
   * @returns {string} - The formatted date string.
   */
  const formatDate = (timestamp: string): string => {
    const date = new Date(parseInt(timestamp) * 1000);
    return `${date.toDateString()} ${date.getHours()}:${(date.getMinutes() < 10 ? "0" : "") + date.getMinutes()}`;
  };

  /**
   * Updates the current user location both in the app state and by sending the data to the server.
   * @param {LatLng} coords - The latitude and longitude coordinates.
   * @param {number} speed - The speed of the device in m/s.
   */
  const updateLocation = async (coords: LatLng, speed: number) => {
    setCoordinates({
      latitude: coords.latitude,
      longitude: coords.longitude,
    });

    if (region.longitude == 0 && region.latitude == 0) {
      setRegion({
        latitude: coords.latitude,
        longitude: coords.longitude,
        latitudeDelta: 0.03,
        longitudeDelta: 0.03,
      });
    }


    if (!token || !userId) return;

    try {
      let movingActivity: string;
      if (speed == 0) {
        movingActivity = "STILL";
      } else if (speed < 1.5) {
        movingActivity = "WALKING";
      } else if (speed >= 1.5 && speed < 5) {
        movingActivity = "RUNNING";
      } else {
        movingActivity = "IN_VEHICLE";
      }

      const response = await fetch(
        `${process.env.EXPO_PUBLIC_API_URL}/graphql`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            query: `
            mutation NewPosition($input: PositionInput!) {
              newPosition(input: $input) {
                id
              }
            }
            `,
            variables: {
              input: {
                latitude: coords.latitude,
                longitude: coords.longitude,
                movingActivity,
              },
            },
          }),
        },
      );
      const data = await response.json();
      if (response.status != 200) {
        console.error(data)
      }
    } catch (err) {
      console.error("Error on updating position");
    }
  }

  /**
   * Fetch notifications from the server for a given user.
   */
  const fetchNotifications = async () => {
    if (!token || !userId) return;

    try {
      const response = await fetch(
        `${process.env.EXPO_PUBLIC_API_URL}/graphql`,
        {
          method: "POST",
          headers: {
            Authorization: `Bearer ${token}`,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            query: `{ notifications(seen: false) { id, createdAt, level, alert { id, text1 text2 text3, audio1, audio2, audio3 }, movingActivity } }`,
          }),
        },
      );

      const data = await response.json();

      if (data.data && data.data.notifications && data.data.notifications.length) {
        const n = data.data.notifications[0];
        setNotification(n);
        if (n.movingActivity == "IN_VEHICLE") {
          let source = null;
          switch (n.level) {
            case "ONE":
              source = n.alert.audio1;
              break;
            case "TWO":
              source = n.alert.audio2;
              break;
            case "THREE":
              source = n.alert.audio3;
              break;
          }

          if (source) {
            let binary = '';
            source.forEach((byte: any) => {
              binary += String.fromCharCode(byte);
            });
            const uri = `data:audio/mpeg;base64,${btoa(binary)}`
            playSound(uri);
          }
        }
      } else {
        setNotification(null);
      }
    } catch (err) {
      console.error("Fetch notifications:", err);
    }
  };

  useEffect(() => {
    Notifications.addNotificationReceivedListener(() => {
      fetchNotifications();
    });
  }, [token, userId]);

  useFocusEffect(useCallback(() => {
    fetchNotifications();
  }, []))

  useEffect(() => {
    const retrieveToken = async () => {
      const storedToken =
        Platform.OS === "web"
          ? localStorage.getItem("token")
          : await AsyncStorage.getItem("token");
      setToken(storedToken || "");
      const storedUserId =
        Platform.OS === "web"
          ? localStorage.getItem("userId")
          : await AsyncStorage.getItem("userId");
      setUserId(storedUserId || "");
    };

    retrieveToken();
  }, []);

  useEffect(() => {
    if (mapRef.current && region) {
      mapRef.current.animateToRegion(region, 1000);
    }
  }, [region]);

  useEffect(() => {
    const startBackgroundLocationTracking = async () => {
      try {
        const { status } = await Location.requestForegroundPermissionsAsync();
        if (status === "granted") {
          Location.watchPositionAsync(
            {
              accuracy: Location.Accuracy.Balanced,
              distanceInterval: 10,
            },
            location => {
              updateLocation(location.coords, location.coords.speed);
            }
          )

          await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
            accuracy: Location.Accuracy.Balanced, // ~100 meters of precision
            distanceInterval: 10, // Send data only if they moved of >=10 meters
            deferredUpdatesInterval: 10000,
            showsBackgroundLocationIndicator: true,
            foregroundService: {
              notificationTitle: "CAS4 Location Tracking",
              notificationBody:
                "Your location is being tracked in the background.",
              notificationColor: "#FFFFFF",
            },
          });
        } else {
          Alert.alert("Background location permission not granted");
        }
      } catch (error) {
        console.error("Error starting background location updates:", error);
      }
    };
    startBackgroundLocationTracking();
  }, []);

  useEffect(() => {
    return sound ? () => { console.log('Unloading Sound'); sound.unloadAsync(); } : undefined;
  }, [sound]);

  return (
    <ParallaxScrollView token={token} userId={userId}>
      {token && userId ? (
        <>
          {notification ? (
            <View>
              <Link
                href={`/notifications/${notification.id}`}
                style={{ width: "100%" }}
              >
                <View style={styles.notificationBox}>
                  <Text style={styles.notificationBoxText}>
                    Oh no, you are (or have been) in an alerted area in{" "}
                    {formatDate(notification.createdAt)}!
                  </Text>
                  <View style={styles.notificationDelimiter} />
                  <Text style={[styles.notificationBoxText, { fontStyle: 'italic' }]}>"
                    {notification.level == 'ONE' ?
                      notification.alert.text1 : notification.level == 'TWO' ?
                        notification.alert.text2 : notification.alert.text3}
                    "</Text>
                  <View style={styles.notificationDelimiter} />
                  <Text style={styles.notificationBoxText}>
                    Click this banner to know more!
                  </Text>
                </View>
              </Link>
            </View>
          ) : (
            <></>
          )
          }
          <ThemedView>
            <Pressable onPress={handleLogout} style={styles.formButton}>
              <Text style={{ color: "white", textAlign: "center" }}>
                Logout
              </Text>
            </Pressable>
          </ThemedView>
          <View>
            <MapView ref={mapRef} initialRegion={region} style={styles.map}>
              <Marker coordinate={coordinates} title="Me" />
            </MapView>
          </View>
        </>
      ) : (
        <>
          <ThemedView style={styles.titleContainer}>
            <ThemedText type="subtitle">Welcome, mate!</ThemedText>
          </ThemedView>
          <ThemedView style={styles.formContainer}>
            <View>
              <ThemedText style={styles.text}>Email</ThemedText>
              <TextInput
                style={styles.formInput}
                onChangeText={setEmail}
                value={email}
              />
            </View>
            <View>
              <ThemedText style={styles.text}>Password</ThemedText>
              <TextInput
                style={styles.formInput}
                onChangeText={setPassword}
                value={password}
                secureTextEntry
              />
            </View>
            <View style={styles.buttonContainer}>
              <Pressable onPress={handleLogin} style={styles.formButton}>
                <Text style={{ color: "white", textAlign: "center" }}>
                  Login
                </Text>
              </Pressable>
            </View>
          </ThemedView>
        </>
      )}
    </ParallaxScrollView>
  );
}

const styles = StyleSheet.create({
  titleContainer: {
    flexDirection: "row",
    alignItems: "center",
    marginBottom: 20,
  },
  text: {
    marginBottom: 8,
  },
  formContainer: {
    marginTop: 20,
    paddingHorizontal: 20,
  },
  formInput: {
    width: "100%",
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: "#ccc",
    backgroundColor: "#f9f9f9",
    marginBottom: 20,
  },
  buttonContainer: {
    marginTop: 20,
  },
  formButton: {
    paddingVertical: 12,
    paddingHorizontal: 24,
    backgroundColor: "#007AFF",
    fontSize: 16,
    fontWeight: "600",
    textAlign: "center",
    borderRadius: 8,
    color: "white",
  },
  map: {
    height: 400,
  },
  notificationBox: {
    padding: 40,
    borderRadius: 8,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    backgroundColor: "#EA2027",
  },
  notificationBoxText: {
    color: "#fff",
    textAlign: "center",
    fontWeight: "bold",
  },
  notificationDelimiter: {
    marginVertical: 30,
    width: '100%',
    height: 1,
    backgroundColor: '#B2171B'
  }
});