Compare commits
No commits in common. "6378758f9b18c2d845259637750213d57777c3a7" and "bf957ba11571edd647a71ed53e54a99fca6b2445" have entirely different histories.
6378758f9b
...
bf957ba115
24 changed files with 463 additions and 425 deletions
|
@ -3,9 +3,6 @@
|
|||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.CALL_PHONE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC"/>
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION"/>
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||
|
@ -47,8 +44,6 @@
|
|||
<meta-data android:name="expo.modules.updates.EXPO_UPDATES_CHECK_ON_LAUNCH" android:value="ERROR_RECOVERY_ONLY"/>
|
||||
<meta-data android:name="expo.modules.updates.EXPO_UPDATES_LAUNCH_WAIT_MS" android:value="0"/>
|
||||
<meta-data android:name="expo.modules.updates.EXPO_UPDATE_URL" android:value="https://expo-updates.alertesecours.fr/api/manifest?project=alerte-secours&channel=release"/>
|
||||
<service android:name="com.transistorsoft.locationmanager.service.LocationRequestService" android:foregroundServiceType="location|dataSync" android:enabled="true" android:exported="false" tools:replace="android:foregroundServiceType"/>
|
||||
<service android:name="com.transistorsoft.backgroundfetch.BackgroundFetchService" android:foregroundServiceType="dataSync" android:enabled="true" android:exported="false"/>
|
||||
<activity android:name=".MainActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|uiMode|locale|layoutDirection" android:launchMode="singleTask" android:windowSoftInputMode="adjustResize" android:theme="@style/Theme.App.SplashScreen" android:exported="true" android:screenOrientation="portrait">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN"/>
|
||||
|
@ -78,4 +73,4 @@
|
|||
</activity>
|
||||
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" android:exported="false"/>
|
||||
</application>
|
||||
</manifest>
|
||||
</manifest>
|
187
index.js
187
index.js
|
@ -20,7 +20,6 @@ import onMessageReceived from "~/notifications/onMessageReceived";
|
|||
import { createLogger } from "~/lib/logger";
|
||||
import * as Sentry from "@sentry/react-native";
|
||||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import { STORAGE_KEYS } from "~/storage/storageKeys";
|
||||
|
||||
// setup notification, this have to stay in index.js
|
||||
notifee.onBackgroundEvent(notificationBackgroundEvent);
|
||||
|
@ -32,16 +31,14 @@ messaging().setBackgroundMessageHandler(onMessageReceived);
|
|||
registerRootComponent(App);
|
||||
|
||||
// Constants for persistence
|
||||
const LAST_SYNC_TIME_KEY = "@geolocation_last_sync_time";
|
||||
// const FORCE_SYNC_INTERVAL = 24 * 60 * 60 * 1000;
|
||||
// const FORCE_SYNC_INTERVAL = 60 * 60 * 1000; // DEBUGGING
|
||||
const FORCE_SYNC_INTERVAL = 5 * 60 * 1000; // DEBUGGING
|
||||
const FORCE_SYNC_INTERVAL = 60 * 60 * 1000; // DEBUGGING
|
||||
|
||||
// Helper functions for persisting sync time
|
||||
const getLastSyncTime = async () => {
|
||||
try {
|
||||
const value = await AsyncStorage.getItem(
|
||||
STORAGE_KEYS.GEOLOCATION_LAST_SYNC_TIME,
|
||||
);
|
||||
const value = await AsyncStorage.getItem(LAST_SYNC_TIME_KEY);
|
||||
return value ? parseInt(value, 10) : Date.now();
|
||||
} catch (error) {
|
||||
Sentry.captureException(error, {
|
||||
|
@ -53,10 +50,7 @@ const getLastSyncTime = async () => {
|
|||
|
||||
const setLastSyncTime = async (time) => {
|
||||
try {
|
||||
await AsyncStorage.setItem(
|
||||
STORAGE_KEYS.GEOLOCATION_LAST_SYNC_TIME,
|
||||
time.toString(),
|
||||
);
|
||||
await AsyncStorage.setItem(LAST_SYNC_TIME_KEY, time.toString());
|
||||
} catch (error) {
|
||||
Sentry.captureException(error, {
|
||||
tags: { module: "headless-task", operation: "set-last-sync-time" },
|
||||
|
@ -125,24 +119,111 @@ const HeadlessTask = async (event) => {
|
|||
throw new Error("Invalid event name received");
|
||||
}
|
||||
|
||||
// Add initial breadcrumb
|
||||
Sentry.addBreadcrumb({
|
||||
message: "HeadlessTask started",
|
||||
category: "headless-task",
|
||||
level: "info",
|
||||
data: {
|
||||
eventName: name,
|
||||
params: params ? JSON.stringify(params) : null,
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
});
|
||||
|
||||
geolocBgLogger.info("HeadlessTask event received", { name, params });
|
||||
|
||||
switch (name) {
|
||||
case "heartbeat":
|
||||
// Add breadcrumb for heartbeat event
|
||||
Sentry.addBreadcrumb({
|
||||
message: "Heartbeat event received",
|
||||
category: "headless-task",
|
||||
level: "info",
|
||||
timestamp: Date.now() / 1000,
|
||||
});
|
||||
|
||||
// Get persisted last sync time
|
||||
const lastSyncTime = await getLastSyncTime();
|
||||
const now = Date.now();
|
||||
const timeSinceLastSync = now - lastSyncTime;
|
||||
|
||||
// Add context about sync timing
|
||||
Sentry.setContext("sync-timing", {
|
||||
lastSyncTime: new Date(lastSyncTime).toISOString(),
|
||||
currentTime: new Date(now).toISOString(),
|
||||
timeSinceLastSync: timeSinceLastSync,
|
||||
timeSinceLastSyncHours: (
|
||||
timeSinceLastSync /
|
||||
(1000 * 60 * 60)
|
||||
).toFixed(2),
|
||||
needsForceSync: timeSinceLastSync >= FORCE_SYNC_INTERVAL,
|
||||
});
|
||||
|
||||
Sentry.addBreadcrumb({
|
||||
message: "Sync timing calculated",
|
||||
category: "headless-task",
|
||||
level: "info",
|
||||
data: {
|
||||
timeSinceLastSyncHours: (
|
||||
timeSinceLastSync /
|
||||
(1000 * 60 * 60)
|
||||
).toFixed(2),
|
||||
needsForceSync: timeSinceLastSync >= FORCE_SYNC_INTERVAL,
|
||||
},
|
||||
});
|
||||
|
||||
// Get current position with performance tracking
|
||||
const locationStartTime = Date.now();
|
||||
const location = await getCurrentPosition();
|
||||
const locationDuration = Date.now() - locationStartTime;
|
||||
|
||||
const isLocationError = location && location.code !== undefined;
|
||||
|
||||
Sentry.addBreadcrumb({
|
||||
message: "getCurrentPosition completed",
|
||||
category: "headless-task",
|
||||
level: isLocationError ? "warning" : "info",
|
||||
data: {
|
||||
success: !isLocationError,
|
||||
error: isLocationError ? location : undefined,
|
||||
coords: !isLocationError ? location?.coords : undefined,
|
||||
},
|
||||
});
|
||||
|
||||
geolocBgLogger.debug("getCurrentPosition result", { location });
|
||||
|
||||
if (timeSinceLastSync >= FORCE_SYNC_INTERVAL) {
|
||||
geolocBgLogger.info("Forcing location sync after 24h");
|
||||
|
||||
Sentry.addBreadcrumb({
|
||||
message: "Force sync triggered",
|
||||
category: "headless-task",
|
||||
level: "info",
|
||||
data: {
|
||||
timeSinceLastSyncHours: (
|
||||
timeSinceLastSync /
|
||||
(1000 * 60 * 60)
|
||||
).toFixed(2),
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
// Get pending records count before sync with timeout
|
||||
const pendingCount = await Promise.race([
|
||||
BackgroundGeolocation.getCount(),
|
||||
new Promise((_, reject) =>
|
||||
setTimeout(() => reject(new Error("getCount timeout")), 10000),
|
||||
),
|
||||
]);
|
||||
|
||||
Sentry.addBreadcrumb({
|
||||
message: "Pending records count",
|
||||
category: "headless-task",
|
||||
level: "info",
|
||||
data: { pendingCount },
|
||||
});
|
||||
|
||||
// Change pace to ensure location updates with timeout
|
||||
await Promise.race([
|
||||
BackgroundGeolocation.changePace(true),
|
||||
|
@ -154,6 +235,12 @@ const HeadlessTask = async (event) => {
|
|||
),
|
||||
]);
|
||||
|
||||
Sentry.addBreadcrumb({
|
||||
message: "changePace completed",
|
||||
category: "headless-task",
|
||||
level: "info",
|
||||
});
|
||||
|
||||
// Perform sync with timeout
|
||||
const syncResult = await Promise.race([
|
||||
BackgroundGeolocation.sync(),
|
||||
|
@ -162,8 +249,26 @@ const HeadlessTask = async (event) => {
|
|||
),
|
||||
]);
|
||||
|
||||
Sentry.addBreadcrumb({
|
||||
message: "Sync completed successfully",
|
||||
category: "headless-task",
|
||||
level: "info",
|
||||
data: {
|
||||
syncResult: Array.isArray(syncResult)
|
||||
? `${syncResult.length} records`
|
||||
: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
// Update last sync time after successful sync
|
||||
await setLastSyncTime(now);
|
||||
|
||||
Sentry.addBreadcrumb({
|
||||
message: "Last sync time updated",
|
||||
category: "headless-task",
|
||||
level: "info",
|
||||
data: { newSyncTime: new Date(now).toISOString() },
|
||||
});
|
||||
} catch (syncError) {
|
||||
Sentry.captureException(syncError, {
|
||||
tags: {
|
||||
|
@ -181,6 +286,22 @@ const HeadlessTask = async (event) => {
|
|||
|
||||
geolocBgLogger.error("Force sync failed", { error: syncError });
|
||||
}
|
||||
} else {
|
||||
Sentry.addBreadcrumb({
|
||||
message: "Force sync not needed",
|
||||
category: "headless-task",
|
||||
level: "info",
|
||||
data: {
|
||||
timeSinceLastSyncHours: (
|
||||
timeSinceLastSync /
|
||||
(1000 * 60 * 60)
|
||||
).toFixed(2),
|
||||
nextSyncInHours: (
|
||||
(FORCE_SYNC_INTERVAL - timeSinceLastSync) /
|
||||
(1000 * 60 * 60)
|
||||
).toFixed(2),
|
||||
},
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
||||
|
@ -191,6 +312,17 @@ const HeadlessTask = async (event) => {
|
|||
break;
|
||||
}
|
||||
|
||||
Sentry.addBreadcrumb({
|
||||
message: "Location update received",
|
||||
category: "headless-task",
|
||||
level: "info",
|
||||
data: {
|
||||
coords: params.location?.coords,
|
||||
activity: params.location?.activity,
|
||||
hasLocation: !!params.location,
|
||||
},
|
||||
});
|
||||
|
||||
geolocBgLogger.debug("Location update received", {
|
||||
location: params.location,
|
||||
});
|
||||
|
@ -206,6 +338,17 @@ const HeadlessTask = async (event) => {
|
|||
const httpStatus = params.response?.status;
|
||||
const isHttpSuccess = httpStatus === 200;
|
||||
|
||||
Sentry.addBreadcrumb({
|
||||
message: "HTTP response received",
|
||||
category: "headless-task",
|
||||
level: isHttpSuccess ? "info" : "warning",
|
||||
data: {
|
||||
status: httpStatus,
|
||||
success: params.response?.success,
|
||||
hasResponse: !!params.response,
|
||||
},
|
||||
});
|
||||
|
||||
geolocBgLogger.debug("HTTP response received", {
|
||||
response: params.response,
|
||||
});
|
||||
|
@ -215,6 +358,13 @@ const HeadlessTask = async (event) => {
|
|||
try {
|
||||
const now = Date.now();
|
||||
await setLastSyncTime(now);
|
||||
|
||||
Sentry.addBreadcrumb({
|
||||
message: "Last sync time updated (HTTP success)",
|
||||
category: "headless-task",
|
||||
level: "info",
|
||||
data: { newSyncTime: new Date(now).toISOString() },
|
||||
});
|
||||
} catch (syncTimeError) {
|
||||
geolocBgLogger.error("Failed to update sync time", {
|
||||
error: syncTimeError,
|
||||
|
@ -231,11 +381,26 @@ const HeadlessTask = async (event) => {
|
|||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
Sentry.addBreadcrumb({
|
||||
message: "Unknown event type",
|
||||
category: "headless-task",
|
||||
level: "warning",
|
||||
data: { eventName: name },
|
||||
});
|
||||
}
|
||||
|
||||
// Task completed successfully
|
||||
const taskDuration = Date.now() - taskStartTime;
|
||||
|
||||
Sentry.addBreadcrumb({
|
||||
message: "HeadlessTask completed successfully",
|
||||
category: "headless-task",
|
||||
level: "info",
|
||||
data: {
|
||||
eventName: name,
|
||||
duration: taskDuration,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
const taskDuration = Date.now() - taskStartTime;
|
||||
|
||||
|
|
|
@ -186,11 +186,7 @@
|
|||
F7ADCC68A8E44BA69FCA849E /* Fix Xcode 15 Bug */,
|
||||
B1AB92A327A24FB294681EDD /* Fix Xcode 15 Bug */,
|
||||
0E26E4D25E2E49C3AB2723FA /* Fix Xcode 15 Bug */,
|
||||
5D0A324371BA4A5385A92DF5 /* Fix Xcode 15 Bug */,
|
||||
40472AFA41A8495E9D557630 /* Fix Xcode 15 Bug */,
|
||||
771057F6078145908B36B18B /* Fix Xcode 15 Bug */,
|
||||
7C1CC306C4DF48D4B5E1BDFB /* Fix Xcode 15 Bug */,
|
||||
2401E852B4D64D59BD803280 /* Remove signature files (Xcode workaround) */,
|
||||
8589214E888941E1817F4C9F /* Remove signature files (Xcode workaround) */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
|
@ -1103,142 +1099,6 @@ fi";
|
|||
shellScript = "
|
||||
echo \"Remove signature files (Xcode workaround)\";
|
||||
rm -rf \"$CONFIGURATION_BUILD_DIR/MapLibre.xcframework-ios.signature\";
|
||||
";
|
||||
};
|
||||
5D0A324371BA4A5385A92DF5 /* Fix Xcode 15 Bug */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
name = "Fix Xcode 15 Bug";
|
||||
inputPaths = (
|
||||
);
|
||||
outputPaths = (
|
||||
);
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "if [ \"$XCODE_VERSION_MAJOR\" = \"1500\" ]; then
|
||||
echo \"Remove signature files (Xcode 15 workaround)\"
|
||||
find \"$BUILD_DIR/${CONFIGURATION}-iphoneos\" -name \"*.signature\" -type f | xargs -r rm
|
||||
fi";
|
||||
};
|
||||
C637A42109E14A1AA86AF639 /* Remove signature files (Xcode workaround) */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
name = "Remove signature files (Xcode workaround)";
|
||||
inputPaths = (
|
||||
);
|
||||
outputPaths = (
|
||||
);
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "
|
||||
echo \"Remove signature files (Xcode workaround)\";
|
||||
rm -rf \"$CONFIGURATION_BUILD_DIR/MapLibre.xcframework-ios.signature\";
|
||||
";
|
||||
};
|
||||
40472AFA41A8495E9D557630 /* Fix Xcode 15 Bug */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
name = "Fix Xcode 15 Bug";
|
||||
inputPaths = (
|
||||
);
|
||||
outputPaths = (
|
||||
);
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "if [ \"$XCODE_VERSION_MAJOR\" = \"1500\" ]; then
|
||||
echo \"Remove signature files (Xcode 15 workaround)\"
|
||||
find \"$BUILD_DIR/${CONFIGURATION}-iphoneos\" -name \"*.signature\" -type f | xargs -r rm
|
||||
fi";
|
||||
};
|
||||
B79BB2C3F48A4CC4B6830286 /* Remove signature files (Xcode workaround) */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
name = "Remove signature files (Xcode workaround)";
|
||||
inputPaths = (
|
||||
);
|
||||
outputPaths = (
|
||||
);
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "
|
||||
echo \"Remove signature files (Xcode workaround)\";
|
||||
rm -rf \"$CONFIGURATION_BUILD_DIR/MapLibre.xcframework-ios.signature\";
|
||||
";
|
||||
};
|
||||
771057F6078145908B36B18B /* Fix Xcode 15 Bug */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
name = "Fix Xcode 15 Bug";
|
||||
inputPaths = (
|
||||
);
|
||||
outputPaths = (
|
||||
);
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "if [ \"$XCODE_VERSION_MAJOR\" = \"1500\" ]; then
|
||||
echo \"Remove signature files (Xcode 15 workaround)\"
|
||||
find \"$BUILD_DIR/${CONFIGURATION}-iphoneos\" -name \"*.signature\" -type f | xargs -r rm
|
||||
fi";
|
||||
};
|
||||
83ACE65C55FE44EC820FD39A /* Remove signature files (Xcode workaround) */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
name = "Remove signature files (Xcode workaround)";
|
||||
inputPaths = (
|
||||
);
|
||||
outputPaths = (
|
||||
);
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "
|
||||
echo \"Remove signature files (Xcode workaround)\";
|
||||
rm -rf \"$CONFIGURATION_BUILD_DIR/MapLibre.xcframework-ios.signature\";
|
||||
";
|
||||
};
|
||||
7C1CC306C4DF48D4B5E1BDFB /* Fix Xcode 15 Bug */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
name = "Fix Xcode 15 Bug";
|
||||
inputPaths = (
|
||||
);
|
||||
outputPaths = (
|
||||
);
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "if [ \"$XCODE_VERSION_MAJOR\" = \"1500\" ]; then
|
||||
echo \"Remove signature files (Xcode 15 workaround)\"
|
||||
find \"$BUILD_DIR/${CONFIGURATION}-iphoneos\" -name \"*.signature\" -type f | xargs -r rm
|
||||
fi";
|
||||
};
|
||||
2401E852B4D64D59BD803280 /* Remove signature files (Xcode workaround) */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
name = "Remove signature files (Xcode workaround)";
|
||||
inputPaths = (
|
||||
);
|
||||
outputPaths = (
|
||||
);
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "
|
||||
echo \"Remove signature files (Xcode workaround)\";
|
||||
rm -rf \"$CONFIGURATION_BUILD_DIR/MapLibre.xcframework-ios.signature\";
|
||||
";
|
||||
};
|
||||
/* End PBXShellScriptBuildPhase section */
|
||||
|
|
|
@ -7,8 +7,8 @@ import { createLogger } from "~/lib/logger";
|
|||
import { SYSTEM_SCOPES } from "~/lib/logger/scopes";
|
||||
|
||||
import { authActions, permissionWizardActions } from "~/stores";
|
||||
import { secureStore } from "~/storage/memorySecureStore";
|
||||
import memoryAsyncStorage from "~/storage/memoryAsyncStorage";
|
||||
import { secureStore } from "~/lib/memorySecureStore";
|
||||
import memoryAsyncStorage from "~/lib/memoryAsyncStorage";
|
||||
|
||||
import "~/lib/mapbox";
|
||||
import "~/i18n";
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
import { secureStore } from "~/storage/memorySecureStore";
|
||||
import { STORAGE_KEYS } from "~/storage/storageKeys";
|
||||
import { secureStore } from "~/lib/memorySecureStore";
|
||||
import uuidGenerator from "react-native-uuid";
|
||||
import { createLogger } from "~/lib/logger";
|
||||
import { FEATURE_SCOPES } from "~/lib/logger/scopes";
|
||||
|
@ -22,12 +21,12 @@ async function getDeviceUuid() {
|
|||
// Create a new promise for this generation attempt
|
||||
uuidGenerationPromise = (async () => {
|
||||
try {
|
||||
let deviceUuid = await secureStore.getItemAsync(STORAGE_KEYS.DEVICE_UUID);
|
||||
let deviceUuid = await secureStore.getItemAsync("deviceUuid");
|
||||
|
||||
if (!deviceUuid) {
|
||||
deviceLogger.info("No device UUID found, generating new one");
|
||||
deviceUuid = uuidGenerator.v4();
|
||||
await secureStore.setItemAsync(STORAGE_KEYS.DEVICE_UUID, deviceUuid);
|
||||
await secureStore.setItemAsync("deviceUuid", deviceUuid);
|
||||
deviceLogger.info("New device UUID generated and stored", {
|
||||
uuid: deviceUuid.substring(0, 8) + "...",
|
||||
});
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
import React from "react";
|
||||
import { View, ScrollView, StyleSheet, Platform } from "react-native";
|
||||
import AsyncStorage from "~/storage/memoryAsyncStorage";
|
||||
import { STORAGE_KEYS } from "~/storage/storageKeys";
|
||||
import AsyncStorage from "~/lib/memoryAsyncStorage";
|
||||
|
||||
import Text from "../Text";
|
||||
|
||||
|
@ -65,12 +64,14 @@ Ce Contrat constitue l'intégralité de l'accord entre vous et nous concernant l
|
|||
Si vous avez des questions concernant ce Contrat, veuillez nous contacter à :
|
||||
Email : contact@alertesecours.fr`;
|
||||
|
||||
const EULA_STORAGE_KEY = "@eula_accepted";
|
||||
|
||||
const EULA = ({ onAccept, visible = true }) => {
|
||||
if (!visible || Platform.OS !== "ios") return null;
|
||||
|
||||
const handleAccept = async () => {
|
||||
try {
|
||||
await AsyncStorage.setItem(STORAGE_KEYS.EULA_ACCEPTED, "true");
|
||||
await AsyncStorage.setItem(EULA_STORAGE_KEY, "true");
|
||||
onAccept();
|
||||
} catch (error) {
|
||||
console.error("Error saving EULA acceptance:", error);
|
||||
|
|
|
@ -11,8 +11,8 @@ import {
|
|||
usePermissionWizardState,
|
||||
useNetworkState,
|
||||
} from "~/stores";
|
||||
import { secureStore } from "~/storage/memorySecureStore";
|
||||
import memoryAsyncStorage from "~/storage/memoryAsyncStorage";
|
||||
import { secureStore } from "~/lib/memorySecureStore";
|
||||
import memoryAsyncStorage from "~/lib/memoryAsyncStorage";
|
||||
|
||||
import requestPermissionLocationBackground from "~/permissions/requestPermissionLocationBackground";
|
||||
import requestPermissionLocationForeground from "~/permissions/requestPermissionLocationForeground";
|
||||
|
|
12
src/env.js
12
src/env.js
|
@ -1,6 +1,8 @@
|
|||
import { Platform } from "react-native";
|
||||
import { secureStore } from "~/storage/memorySecureStore";
|
||||
import { STORAGE_KEYS } from "~/storage/storageKeys";
|
||||
import { secureStore } from "~/lib/secureStore";
|
||||
|
||||
// Key for storing staging setting in secureStore
|
||||
const STAGING_SETTING_KEY = "env.isStaging";
|
||||
|
||||
// Logging configuration
|
||||
const LOG_SCOPES = process.env.APP_LOG_SCOPES;
|
||||
|
@ -95,7 +97,7 @@ export const setStaging = async (enabled) => {
|
|||
}
|
||||
|
||||
// Persist the staging setting
|
||||
await secureStore.setItemAsync(STORAGE_KEYS.ENV_IS_STAGING, String(enabled));
|
||||
await secureStore.setItemAsync(STAGING_SETTING_KEY, String(enabled));
|
||||
};
|
||||
|
||||
// Initialize with default values
|
||||
|
@ -104,9 +106,7 @@ const env = { ...envMap };
|
|||
// Load the staging setting from secureStore
|
||||
export const initializeEnv = async () => {
|
||||
try {
|
||||
const storedStaging = await secureStore.getItemAsync(
|
||||
STORAGE_KEYS.ENV_IS_STAGING,
|
||||
);
|
||||
const storedStaging = await secureStore.getItemAsync(STAGING_SETTING_KEY);
|
||||
if (storedStaging !== null) {
|
||||
const isStaging = storedStaging === "true";
|
||||
if (isStaging) {
|
||||
|
|
|
@ -1,8 +1,9 @@
|
|||
import { useState, useEffect } from "react";
|
||||
import AsyncStorage from "~/storage/memoryAsyncStorage";
|
||||
import { STORAGE_KEYS } from "~/storage/storageKeys";
|
||||
import AsyncStorage from "~/lib/memoryAsyncStorage";
|
||||
import { Platform } from "react-native";
|
||||
|
||||
const EULA_STORAGE_KEY = "@eula_accepted";
|
||||
|
||||
export const useEULA = () => {
|
||||
const [eulaAccepted, setEulaAccepted] = useState(true);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
@ -15,7 +16,7 @@ export const useEULA = () => {
|
|||
|
||||
const checkEULA = async () => {
|
||||
try {
|
||||
const accepted = await AsyncStorage.getItem(STORAGE_KEYS.EULA_ACCEPTED);
|
||||
const accepted = await AsyncStorage.getItem(EULA_STORAGE_KEY);
|
||||
setEulaAccepted(!!accepted);
|
||||
} catch (error) {
|
||||
console.error("Error checking EULA status:", error);
|
||||
|
|
|
@ -1,7 +1,6 @@
|
|||
import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import { createLogger } from "~/lib/logger";
|
||||
import { SYSTEM_SCOPES } from "~/lib/logger/scopes";
|
||||
import { getAsyncStorageKeys } from "./storageKeys";
|
||||
|
||||
const storageLogger = createLogger({
|
||||
module: SYSTEM_SCOPES.STORAGE,
|
||||
|
@ -30,8 +29,15 @@ export const memoryAsyncStorage = {
|
|||
|
||||
storageLogger.info("Initializing memory async storage");
|
||||
|
||||
// Get all registered AsyncStorage keys from the registry
|
||||
const knownKeys = getAsyncStorageKeys();
|
||||
// List of known keys that need to be cached
|
||||
const knownKeys = [
|
||||
"permission_wizard_completed",
|
||||
"override_messages",
|
||||
"last_known_location",
|
||||
"eula_accepted",
|
||||
"last_update_check",
|
||||
"emulator_mode_enabled",
|
||||
];
|
||||
|
||||
// Load all known keys into memory
|
||||
for (const key of knownKeys) {
|
||||
|
@ -146,20 +152,19 @@ export const memoryAsyncStorage = {
|
|||
storageLogger.debug("Set in memory cache", { key });
|
||||
|
||||
// Try to persist to AsyncStorage
|
||||
(async () => {
|
||||
try {
|
||||
await AsyncStorage.setItem(key, value);
|
||||
storageLogger.debug("Persisted to AsyncStorage", { key });
|
||||
} catch (error) {
|
||||
storageLogger.warn(
|
||||
"Failed to persist to AsyncStorage, kept in memory only",
|
||||
{
|
||||
key,
|
||||
error: error.message,
|
||||
},
|
||||
);
|
||||
}
|
||||
})();
|
||||
try {
|
||||
await AsyncStorage.setItem(key, value);
|
||||
storageLogger.debug("Persisted to AsyncStorage", { key });
|
||||
} catch (error) {
|
||||
storageLogger.warn(
|
||||
"Failed to persist to AsyncStorage, kept in memory only",
|
||||
{
|
||||
key,
|
||||
error: error.message,
|
||||
},
|
||||
);
|
||||
// Continue - value is at least in memory
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
|
@ -173,18 +178,16 @@ export const memoryAsyncStorage = {
|
|||
storageLogger.debug("Deleted from memory cache", { key });
|
||||
|
||||
// Try to delete from AsyncStorage
|
||||
(async () => {
|
||||
try {
|
||||
await AsyncStorage.removeItem(key);
|
||||
storageLogger.debug("Deleted from AsyncStorage", { key });
|
||||
} catch (error) {
|
||||
storageLogger.warn("Failed to delete from AsyncStorage", {
|
||||
key,
|
||||
error: error.message,
|
||||
});
|
||||
// Continue - at least removed from memory
|
||||
}
|
||||
})();
|
||||
try {
|
||||
await AsyncStorage.removeItem(key);
|
||||
storageLogger.debug("Deleted from AsyncStorage", { key });
|
||||
} catch (error) {
|
||||
storageLogger.warn("Failed to delete from AsyncStorage", {
|
||||
key,
|
||||
error: error.message,
|
||||
});
|
||||
// Continue - at least removed from memory
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
|
@ -239,16 +242,14 @@ export const memoryAsyncStorage = {
|
|||
storageLogger.info("Cleared memory cache");
|
||||
|
||||
// Try to clear AsyncStorage
|
||||
(async () => {
|
||||
try {
|
||||
await AsyncStorage.clear();
|
||||
storageLogger.info("Cleared AsyncStorage");
|
||||
} catch (error) {
|
||||
storageLogger.warn("Failed to clear AsyncStorage", {
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
})();
|
||||
try {
|
||||
await AsyncStorage.clear();
|
||||
storageLogger.info("Cleared AsyncStorage");
|
||||
} catch (error) {
|
||||
storageLogger.warn("Failed to clear AsyncStorage", {
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
|
@ -1,7 +1,6 @@
|
|||
import { secureStore as originalSecureStore } from "./secureStore";
|
||||
import { createLogger } from "~/lib/logger";
|
||||
import { SYSTEM_SCOPES } from "~/lib/logger/scopes";
|
||||
import { getSecureStoreKeys } from "./storageKeys";
|
||||
|
||||
const storageLogger = createLogger({
|
||||
module: SYSTEM_SCOPES.STORAGE,
|
||||
|
@ -30,8 +29,16 @@ export const memorySecureStore = {
|
|||
|
||||
storageLogger.info("Initializing memory secure store");
|
||||
|
||||
// Get all registered secure store keys from the registry
|
||||
const knownKeys = getSecureStoreKeys();
|
||||
// List of known keys that need to be cached
|
||||
const knownKeys = [
|
||||
"deviceUuid",
|
||||
"authToken",
|
||||
"userToken",
|
||||
"dev.authToken",
|
||||
"dev.userToken",
|
||||
"anon.authToken",
|
||||
"anon.userToken",
|
||||
];
|
||||
|
||||
// Load all known keys into memory
|
||||
for (const key of knownKeys) {
|
|
@ -1,9 +1,10 @@
|
|||
import BackgroundGeolocation from "react-native-background-geolocation";
|
||||
import AsyncStorage from "~/storage/memoryAsyncStorage";
|
||||
import { STORAGE_KEYS } from "~/storage/storageKeys";
|
||||
import AsyncStorage from "~/lib/memoryAsyncStorage";
|
||||
import { createLogger } from "~/lib/logger";
|
||||
import { BACKGROUND_SCOPES } from "~/lib/logger/scopes";
|
||||
|
||||
const EMULATOR_MODE_KEY = "emulator_mode_enabled";
|
||||
|
||||
// Global variables
|
||||
let emulatorIntervalId = null;
|
||||
let isEmulatorModeEnabled = false;
|
||||
|
@ -17,9 +18,7 @@ const emulatorLogger = createLogger({
|
|||
// Initialize emulator mode based on stored preference
|
||||
export const initEmulatorMode = async () => {
|
||||
try {
|
||||
const storedValue = await AsyncStorage.getItem(
|
||||
STORAGE_KEYS.EMULATOR_MODE_ENABLED,
|
||||
);
|
||||
const storedValue = await AsyncStorage.getItem(EMULATOR_MODE_KEY);
|
||||
emulatorLogger.debug("Initializing emulator mode", { storedValue });
|
||||
|
||||
if (storedValue === "true") {
|
||||
|
@ -59,7 +58,7 @@ export const enableEmulatorMode = async () => {
|
|||
isEmulatorModeEnabled = true;
|
||||
|
||||
// Persist the setting
|
||||
await AsyncStorage.setItem(STORAGE_KEYS.EMULATOR_MODE_ENABLED, "true");
|
||||
await AsyncStorage.setItem(EMULATOR_MODE_KEY, "true");
|
||||
emulatorLogger.debug("Emulator mode setting saved");
|
||||
} catch (error) {
|
||||
emulatorLogger.error("Failed to enable emulator mode", {
|
||||
|
@ -82,7 +81,7 @@ export const disableEmulatorMode = async () => {
|
|||
|
||||
// Persist the setting
|
||||
try {
|
||||
await AsyncStorage.setItem(STORAGE_KEYS.EMULATOR_MODE_ENABLED, "false");
|
||||
await AsyncStorage.setItem(EMULATOR_MODE_KEY, "false");
|
||||
emulatorLogger.debug("Emulator mode setting saved");
|
||||
} catch (error) {
|
||||
emulatorLogger.error("Failed to save emulator mode setting", {
|
||||
|
|
|
@ -4,8 +4,17 @@ import { createLogger } from "~/lib/logger";
|
|||
import { BACKGROUND_SCOPES } from "~/lib/logger/scopes";
|
||||
import jwtDecode from "jwt-decode";
|
||||
import { initEmulatorMode } from "./emulatorService";
|
||||
import * as Sentry from "@sentry/react-native";
|
||||
import { SPAN_STATUS_OK, SPAN_STATUS_ERROR } from "@sentry/react-native";
|
||||
|
||||
import { getAuthState, subscribeAuthState, permissionsActions } from "~/stores";
|
||||
import throttle from "lodash.throttle";
|
||||
|
||||
import {
|
||||
getAuthState,
|
||||
subscribeAuthState,
|
||||
authActions,
|
||||
permissionsActions,
|
||||
} from "~/stores";
|
||||
|
||||
import setLocationState from "~/location/setLocationState";
|
||||
import { storeLocation } from "~/utils/location/storage";
|
||||
|
@ -67,6 +76,9 @@ export default async function trackLocation() {
|
|||
isStaging: env.IS_STAGING,
|
||||
});
|
||||
|
||||
// Throttling configuration for auth reload only
|
||||
const AUTH_RELOAD_THROTTLE = 5000; // 5 seconds throttle
|
||||
|
||||
// Handle auth function - no throttling or cooldown
|
||||
async function handleAuth(userToken) {
|
||||
locationLogger.info("Handling auth token update", {
|
||||
|
@ -96,6 +108,25 @@ export default async function trackLocation() {
|
|||
},
|
||||
);
|
||||
|
||||
// Verify the current configuration
|
||||
try {
|
||||
const currentConfig = await BackgroundGeolocation.getConfig();
|
||||
locationLogger.debug("Current background geolocation config", {
|
||||
hasHeaders: !!currentConfig.headers,
|
||||
headerKeys: currentConfig.headers
|
||||
? Object.keys(currentConfig.headers)
|
||||
: [],
|
||||
authHeader: currentConfig.headers?.Authorization
|
||||
? currentConfig.headers.Authorization.substring(0, 15) + "..."
|
||||
: "Not set",
|
||||
url: currentConfig.url,
|
||||
});
|
||||
} catch (error) {
|
||||
locationLogger.error("Failed to get background geolocation config", {
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
|
||||
const state = await BackgroundGeolocation.getState();
|
||||
try {
|
||||
const decodedToken = jwtDecode(userToken);
|
||||
|
@ -140,6 +171,19 @@ export default async function trackLocation() {
|
|||
battery: location.battery,
|
||||
});
|
||||
|
||||
// Add Sentry breadcrumb for location updates
|
||||
Sentry.addBreadcrumb({
|
||||
message: "Location update in trackLocation",
|
||||
category: "geolocation",
|
||||
level: "info",
|
||||
data: {
|
||||
coords: location.coords,
|
||||
activity: location.activity?.type,
|
||||
battery: location.battery?.level,
|
||||
isMoving: location.isMoving,
|
||||
},
|
||||
});
|
||||
|
||||
if (
|
||||
location.coords &&
|
||||
location.coords.latitude &&
|
||||
|
@ -151,12 +195,100 @@ export default async function trackLocation() {
|
|||
}
|
||||
});
|
||||
|
||||
// The core auth reload function that will be throttled
|
||||
function _reloadAuth() {
|
||||
locationLogger.info("Refreshing authentication token");
|
||||
authActions.reload(); // should retriger sync in handleAuth via subscribeAuthState when done
|
||||
}
|
||||
|
||||
// Create throttled version of auth reload with lodash
|
||||
const reloadAuth = throttle(_reloadAuth, AUTH_RELOAD_THROTTLE, {
|
||||
leading: true,
|
||||
trailing: false, // Prevent trailing calls to avoid duplicate refreshes
|
||||
});
|
||||
|
||||
BackgroundGeolocation.onHttp(async (response) => {
|
||||
// log status code and response
|
||||
// Log the full response including headers if available
|
||||
locationLogger.debug("HTTP response received", {
|
||||
status: response?.status,
|
||||
success: response?.success,
|
||||
responseText: response?.responseText,
|
||||
url: response?.url,
|
||||
method: response?.method,
|
||||
isSync: response?.isSync,
|
||||
requestHeaders:
|
||||
response?.request?.headers || "Headers not available in response",
|
||||
});
|
||||
|
||||
// Add Sentry breadcrumb for HTTP responses
|
||||
Sentry.addBreadcrumb({
|
||||
message: "Background geolocation HTTP response",
|
||||
category: "geolocation-http",
|
||||
level: response?.status === 200 ? "info" : "warning",
|
||||
data: {
|
||||
status: response?.status,
|
||||
success: response?.success,
|
||||
url: response?.url,
|
||||
isSync: response?.isSync,
|
||||
recordCount: response?.count,
|
||||
},
|
||||
});
|
||||
|
||||
// Log the current auth token for comparison
|
||||
const { userToken } = getAuthState();
|
||||
locationLogger.debug("Current auth state token", {
|
||||
tokenAvailable: !!userToken,
|
||||
tokenPrefix: userToken ? userToken.substring(0, 10) + "..." : null,
|
||||
});
|
||||
|
||||
const statusCode = response?.status;
|
||||
|
||||
switch (statusCode) {
|
||||
case 410:
|
||||
// Token expired, logout
|
||||
locationLogger.info("Auth token expired (410), logging out");
|
||||
Sentry.addBreadcrumb({
|
||||
message: "Auth token expired - logging out",
|
||||
category: "geolocation-auth",
|
||||
level: "warning",
|
||||
});
|
||||
authActions.logout();
|
||||
break;
|
||||
case 401:
|
||||
// Unauthorized, use throttled reload
|
||||
locationLogger.info("Unauthorized (401), attempting to refresh token");
|
||||
|
||||
// Add more detailed logging of the error response
|
||||
try {
|
||||
const errorBody = response?.responseText
|
||||
? JSON.parse(response.responseText)
|
||||
: null;
|
||||
locationLogger.debug("Unauthorized error details", {
|
||||
errorBody,
|
||||
errorType: errorBody?.error?.type,
|
||||
errorMessage: errorBody?.error?.message,
|
||||
errorPath: errorBody?.error?.errors?.[0]?.path,
|
||||
});
|
||||
|
||||
Sentry.addBreadcrumb({
|
||||
message: "Unauthorized - refreshing token",
|
||||
category: "geolocation-auth",
|
||||
level: "warning",
|
||||
data: {
|
||||
errorType: errorBody?.error?.type,
|
||||
errorMessage: errorBody?.error?.message,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
locationLogger.debug("Failed to parse error response", {
|
||||
error: e.message,
|
||||
responseText: response?.responseText,
|
||||
});
|
||||
}
|
||||
|
||||
reloadAuth();
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
|
|
|
@ -9,15 +9,15 @@ export default function getStatusCode({ networkError, graphQLErrors }) {
|
|||
if (graphQLErrors) {
|
||||
let code;
|
||||
for (const err of graphQLErrors) {
|
||||
if (err.extensions?.http) {
|
||||
if (err.extensions.http) {
|
||||
code = err.extensions.http;
|
||||
break;
|
||||
}
|
||||
if (err.extensions?.statusCode) {
|
||||
if (err.extensions.statusCode) {
|
||||
code = err.extensions.statusCode;
|
||||
break;
|
||||
}
|
||||
if (err.extensions?.code) {
|
||||
if (err.extensions.code) {
|
||||
code = err.extensions.code;
|
||||
break;
|
||||
}
|
||||
|
|
|
@ -25,7 +25,7 @@ const getReleaseVersion = () => {
|
|||
|
||||
Sentry.init({
|
||||
dsn: env.SENTRY_DSN,
|
||||
tracesSampleRate: 0.1,
|
||||
tracesSampleRate: 1.0,
|
||||
debug: __DEV__,
|
||||
// Configure release to match ios-archive.sh format
|
||||
release: getReleaseVersion(),
|
||||
|
|
|
@ -1,83 +0,0 @@
|
|||
/**
|
||||
* Storage Keys Registry
|
||||
*
|
||||
* This file maintains a registry of all storage keys used throughout the application.
|
||||
* By defining keys as constants here, they are automatically included in memory storage
|
||||
* initialization, eliminating the need for manual maintenance of key lists.
|
||||
*/
|
||||
|
||||
const secureStoreKeys = new Set();
|
||||
const asyncStorageKeys = new Set();
|
||||
|
||||
/**
|
||||
* Register a secure store key and return it as a constant
|
||||
* @param {string} key - The storage key to register for secure store
|
||||
* @returns {string} The same key, now registered for secure store
|
||||
*/
|
||||
export const registerSecureStoreKey = (key) => {
|
||||
secureStoreKeys.add(key);
|
||||
return key;
|
||||
};
|
||||
|
||||
/**
|
||||
* Register an AsyncStorage key and return it as a constant
|
||||
* @param {string} key - The storage key to register for AsyncStorage
|
||||
* @returns {string} The same key, now registered for AsyncStorage
|
||||
*/
|
||||
export const registerAsyncStorageKey = (key) => {
|
||||
asyncStorageKeys.add(key);
|
||||
return key;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get all secure store keys
|
||||
* @returns {string[]} Array of secure store keys
|
||||
*/
|
||||
export const getSecureStoreKeys = () => Array.from(secureStoreKeys);
|
||||
|
||||
/**
|
||||
* Get all AsyncStorage keys
|
||||
* @returns {string[]} Array of AsyncStorage keys
|
||||
*/
|
||||
export const getAsyncStorageKeys = () => Array.from(asyncStorageKeys);
|
||||
|
||||
/**
|
||||
* Get all registered storage keys (both types)
|
||||
* @returns {string[]} Array of all registered keys
|
||||
*/
|
||||
export const getAllRegisteredKeys = () => [
|
||||
...Array.from(secureStoreKeys),
|
||||
...Array.from(asyncStorageKeys),
|
||||
];
|
||||
|
||||
/**
|
||||
* Storage key constants
|
||||
* All storage keys used throughout the application should be defined here.
|
||||
*/
|
||||
export const STORAGE_KEYS = {
|
||||
// Secure Store Keys - Authentication & Security
|
||||
DEVICE_UUID: registerSecureStoreKey("deviceUuid"),
|
||||
AUTH_TOKEN: registerSecureStoreKey("authToken"),
|
||||
USER_TOKEN: registerSecureStoreKey("userToken"),
|
||||
DEV_AUTH_TOKEN: registerSecureStoreKey("dev.authToken"),
|
||||
DEV_USER_TOKEN: registerSecureStoreKey("dev.userToken"),
|
||||
ANON_AUTH_TOKEN: registerSecureStoreKey("anon.authToken"),
|
||||
ANON_USER_TOKEN: registerSecureStoreKey("anon.userToken"),
|
||||
FCM_TOKEN_STORED: registerSecureStoreKey("fcmTokenStored"),
|
||||
FCM_TOKEN_STORED_DEVICE_ID: registerSecureStoreKey("fcmTokenStoredDeviceId"),
|
||||
ENV_IS_STAGING: registerSecureStoreKey("env.isStaging"),
|
||||
|
||||
// AsyncStorage Keys - App State & Preferences
|
||||
GEOLOCATION_LAST_SYNC_TIME: registerAsyncStorageKey(
|
||||
"@geolocation_last_sync_time",
|
||||
),
|
||||
EULA_ACCEPTED: registerAsyncStorageKey("@eula_accepted"),
|
||||
OVERRIDE_MESSAGES: registerAsyncStorageKey("@override_messages"),
|
||||
PERMISSION_WIZARD_COMPLETED: registerAsyncStorageKey(
|
||||
"@permission_wizard_completed",
|
||||
),
|
||||
LAST_UPDATE_CHECK_TIME: registerAsyncStorageKey("lastUpdateCheckTime"),
|
||||
LAST_KNOWN_LOCATION: registerAsyncStorageKey("@last_known_location"),
|
||||
EULA_ACCEPTED_SIMPLE: registerAsyncStorageKey("eula_accepted"),
|
||||
EMULATOR_MODE_ENABLED: registerAsyncStorageKey("emulator_mode_enabled"),
|
||||
};
|
|
@ -1,7 +1,8 @@
|
|||
import { createAtom } from "~/lib/atomic-zustand";
|
||||
import debounce from "lodash.debounce";
|
||||
import AsyncStorage from "~/storage/memoryAsyncStorage";
|
||||
import { STORAGE_KEYS } from "~/storage/storageKeys";
|
||||
import AsyncStorage from "~/lib/memoryAsyncStorage";
|
||||
|
||||
const OVERRIDE_MESSAGES_STORAGE_KEY = "@override_messages";
|
||||
|
||||
export default createAtom(({ merge, set, get, reset }) => {
|
||||
const overrideMessagesCache = {};
|
||||
|
@ -9,7 +10,7 @@ export default createAtom(({ merge, set, get, reset }) => {
|
|||
const initCache = async () => {
|
||||
try {
|
||||
const storedData = await AsyncStorage.getItem(
|
||||
STORAGE_KEYS.OVERRIDE_MESSAGES,
|
||||
OVERRIDE_MESSAGES_STORAGE_KEY,
|
||||
);
|
||||
const storedMessages = storedData ? JSON.parse(storedData) : {};
|
||||
Object.entries(storedMessages).forEach(([messageId, data]) => {
|
||||
|
@ -23,7 +24,7 @@ export default createAtom(({ merge, set, get, reset }) => {
|
|||
const saveOverrideMessagesToStorage = async () => {
|
||||
try {
|
||||
await AsyncStorage.setItem(
|
||||
STORAGE_KEYS.OVERRIDE_MESSAGES,
|
||||
OVERRIDE_MESSAGES_STORAGE_KEY,
|
||||
JSON.stringify(overrideMessagesCache),
|
||||
);
|
||||
} catch (error) {
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
import { secureStore } from "~/storage/memorySecureStore";
|
||||
import { STORAGE_KEYS } from "~/storage/storageKeys";
|
||||
import { secureStore } from "~/lib/memorySecureStore";
|
||||
import jwtDecode from "jwt-decode";
|
||||
import { createLogger } from "~/lib/logger";
|
||||
import { FEATURE_SCOPES } from "~/lib/logger/scopes";
|
||||
|
@ -11,13 +10,13 @@ import isExpired from "~/lib/time/isExpired";
|
|||
import { registerUser, loginUserToken } from "~/auth/actions";
|
||||
|
||||
// DEV
|
||||
// SecureStore.deleteItemAsync(STORAGE_KEYS.USER_TOKEN);
|
||||
// SecureStore.deleteItemAsync(STORAGE_KEYS.AUTH_TOKEN);
|
||||
// SecureStore.deleteItemAsync(STORAGE_KEYS.DEV_USER_TOKEN);
|
||||
// SecureStore.deleteItemAsync(STORAGE_KEYS.DEV_AUTH_TOKEN);
|
||||
// SecureStore.deleteItemAsync(STORAGE_KEYS.ANON_USER_TOKEN);
|
||||
// SecureStore.deleteItemAsync(STORAGE_KEYS.ANON_AUTH_TOKEN);
|
||||
// SecureStore.getItemAsync(STORAGE_KEYS.USER_TOKEN).then((t) => authLogger.debug("User token", { token: t }));
|
||||
// SecureStore.deleteItemAsync("userToken");
|
||||
// SecureStore.deleteItemAsync("authToken");
|
||||
// SecureStore.deleteItemAsync("dev.userToken");
|
||||
// SecureStore.deleteItemAsync("dev.authToken");
|
||||
// SecureStore.deleteItemAsync("anon.userToken");
|
||||
// SecureStore.deleteItemAsync("anon.authToken");
|
||||
// SecureStore.getItemAsync("userToken").then((t) => authLogger.debug("User token", { token: t }));
|
||||
|
||||
const authLogger = createLogger({
|
||||
module: FEATURE_SCOPES.AUTH,
|
||||
|
@ -69,7 +68,7 @@ export default createAtom(({ get, merge, getActions }) => {
|
|||
authLogger.info("Attempting to login with auth token");
|
||||
const { userToken } = await loginUserToken({ authToken });
|
||||
authLogger.info("Successfully obtained user token");
|
||||
await secureStore.setItemAsync(STORAGE_KEYS.USER_TOKEN, userToken);
|
||||
await secureStore.setItemAsync("userToken", userToken);
|
||||
endLoading({
|
||||
userToken,
|
||||
});
|
||||
|
@ -82,8 +81,8 @@ export default createAtom(({ get, merge, getActions }) => {
|
|||
"Auth token expired, clearing tokens and reinitializing",
|
||||
);
|
||||
await Promise.all([
|
||||
secureStore.deleteItemAsync(STORAGE_KEYS.AUTH_TOKEN),
|
||||
secureStore.deleteItemAsync(STORAGE_KEYS.USER_TOKEN),
|
||||
secureStore.deleteItemAsync("authToken"),
|
||||
secureStore.deleteItemAsync("userToken"),
|
||||
]);
|
||||
return init();
|
||||
}
|
||||
|
@ -94,8 +93,8 @@ export default createAtom(({ get, merge, getActions }) => {
|
|||
const init = async () => {
|
||||
authLogger.debug("Initializing auth state");
|
||||
let { userToken, authToken } = await promiseObject({
|
||||
userToken: secureStore.getItemAsync(STORAGE_KEYS.USER_TOKEN),
|
||||
authToken: secureStore.getItemAsync(STORAGE_KEYS.AUTH_TOKEN),
|
||||
userToken: secureStore.getItemAsync("userToken"),
|
||||
authToken: secureStore.getItemAsync("authToken"),
|
||||
});
|
||||
// await delay(5);
|
||||
// authLogger.debug("Auth tokens", { userToken, authToken });
|
||||
|
@ -122,7 +121,7 @@ export default createAtom(({ get, merge, getActions }) => {
|
|||
const res = await registerUser();
|
||||
authLogger.info("Successfully registered new user");
|
||||
authToken = res.authToken;
|
||||
await secureStore.setItemAsync(STORAGE_KEYS.AUTH_TOKEN, authToken);
|
||||
await secureStore.setItemAsync("authToken", authToken);
|
||||
}
|
||||
|
||||
if (!userToken && authToken) {
|
||||
|
@ -166,7 +165,7 @@ export default createAtom(({ get, merge, getActions }) => {
|
|||
startLoading();
|
||||
|
||||
authLogger.debug("Deleting userToken for refresh");
|
||||
await secureStore.deleteItemAsync(STORAGE_KEYS.USER_TOKEN);
|
||||
await secureStore.deleteItemAsync("userToken");
|
||||
|
||||
await init();
|
||||
return true;
|
||||
|
@ -184,7 +183,7 @@ export default createAtom(({ get, merge, getActions }) => {
|
|||
const { onReloadAuthToken: authToken } = get();
|
||||
|
||||
if (authToken) {
|
||||
await secureStore.setItemAsync(STORAGE_KEYS.AUTH_TOKEN, authToken);
|
||||
await secureStore.setItemAsync("authToken", authToken);
|
||||
await loadUserJWT(authToken);
|
||||
} else {
|
||||
await init();
|
||||
|
@ -205,12 +204,12 @@ export default createAtom(({ get, merge, getActions }) => {
|
|||
if (!isConnected) {
|
||||
// backup anon tokens
|
||||
const [anonAuthToken, anonUserToken] = await Promise.all([
|
||||
secureStore.getItemAsync(STORAGE_KEYS.AUTH_TOKEN),
|
||||
secureStore.getItemAsync(STORAGE_KEYS.USER_TOKEN),
|
||||
secureStore.getItemAsync("authToken"),
|
||||
secureStore.getItemAsync("userToken"),
|
||||
]);
|
||||
await Promise.all([
|
||||
secureStore.setItemAsync(STORAGE_KEYS.ANON_AUTH_TOKEN, anonAuthToken),
|
||||
secureStore.setItemAsync(STORAGE_KEYS.ANON_USER_TOKEN, anonUserToken),
|
||||
secureStore.setItemAsync("anon.authToken", anonAuthToken),
|
||||
secureStore.setItemAsync("anon.userToken", anonUserToken),
|
||||
]);
|
||||
}
|
||||
merge({ onReloadAuthToken: authTokenJwt });
|
||||
|
@ -220,12 +219,12 @@ export default createAtom(({ get, merge, getActions }) => {
|
|||
const impersonate = async ({ authTokenJwt }) => {
|
||||
authLogger.info("Starting impersonation");
|
||||
const [anonAuthToken, anonUserToken] = await Promise.all([
|
||||
secureStore.getItemAsync(STORAGE_KEYS.AUTH_TOKEN),
|
||||
secureStore.getItemAsync(STORAGE_KEYS.USER_TOKEN),
|
||||
secureStore.getItemAsync("authToken"),
|
||||
secureStore.getItemAsync("userToken"),
|
||||
]);
|
||||
await Promise.all([
|
||||
secureStore.setItemAsync(STORAGE_KEYS.DEV_AUTH_TOKEN, anonAuthToken),
|
||||
secureStore.setItemAsync(STORAGE_KEYS.DEV_USER_TOKEN, anonUserToken),
|
||||
secureStore.setItemAsync("dev.authToken", anonAuthToken),
|
||||
secureStore.setItemAsync("dev.userToken", anonUserToken),
|
||||
]);
|
||||
merge({ onReloadAuthToken: authTokenJwt });
|
||||
triggerReload();
|
||||
|
@ -235,29 +234,29 @@ export default createAtom(({ get, merge, getActions }) => {
|
|||
authLogger.info("Initiating logout");
|
||||
const [devAuthToken, devUserToken, anonAuthToken, anonUserToken] =
|
||||
await Promise.all([
|
||||
secureStore.getItemAsync(STORAGE_KEYS.DEV_AUTH_TOKEN),
|
||||
secureStore.getItemAsync(STORAGE_KEYS.DEV_USER_TOKEN),
|
||||
secureStore.getItemAsync(STORAGE_KEYS.ANON_AUTH_TOKEN),
|
||||
secureStore.getItemAsync(STORAGE_KEYS.ANON_USER_TOKEN),
|
||||
secureStore.getItemAsync("dev.authToken"),
|
||||
secureStore.getItemAsync("dev.userToken"),
|
||||
secureStore.getItemAsync("anon.authToken"),
|
||||
secureStore.getItemAsync("anon.userToken"),
|
||||
]);
|
||||
if (devAuthToken && devUserToken) {
|
||||
await Promise.all([
|
||||
secureStore.setItemAsync(STORAGE_KEYS.AUTH_TOKEN, devAuthToken),
|
||||
secureStore.setItemAsync(STORAGE_KEYS.USER_TOKEN, devUserToken),
|
||||
secureStore.deleteItemAsync(STORAGE_KEYS.DEV_AUTH_TOKEN),
|
||||
secureStore.deleteItemAsync(STORAGE_KEYS.DEV_USER_TOKEN),
|
||||
secureStore.setItemAsync("authToken", devAuthToken),
|
||||
secureStore.setItemAsync("userToken", devUserToken),
|
||||
secureStore.deleteItemAsync("dev.authToken"),
|
||||
secureStore.deleteItemAsync("dev.userToken"),
|
||||
]);
|
||||
} else if (anonAuthToken && anonUserToken) {
|
||||
await Promise.all([
|
||||
secureStore.setItemAsync(STORAGE_KEYS.AUTH_TOKEN, anonAuthToken),
|
||||
secureStore.setItemAsync(STORAGE_KEYS.USER_TOKEN, anonUserToken),
|
||||
secureStore.deleteItemAsync(STORAGE_KEYS.ANON_AUTH_TOKEN),
|
||||
secureStore.deleteItemAsync(STORAGE_KEYS.ANON_USER_TOKEN),
|
||||
secureStore.setItemAsync("authToken", anonAuthToken),
|
||||
secureStore.setItemAsync("userToken", anonUserToken),
|
||||
secureStore.deleteItemAsync("anon.authToken"),
|
||||
secureStore.deleteItemAsync("anon.userToken"),
|
||||
]);
|
||||
} else {
|
||||
await Promise.all([
|
||||
secureStore.deleteItemAsync(STORAGE_KEYS.AUTH_TOKEN),
|
||||
secureStore.deleteItemAsync(STORAGE_KEYS.USER_TOKEN),
|
||||
secureStore.deleteItemAsync("authToken"),
|
||||
secureStore.deleteItemAsync("userToken"),
|
||||
]);
|
||||
merge({
|
||||
userOffMode: true,
|
||||
|
@ -276,31 +275,6 @@ export default createAtom(({ get, merge, getActions }) => {
|
|||
triggerReload();
|
||||
};
|
||||
|
||||
const setUserToken = async (userToken) => {
|
||||
authLogger.info("Setting user token", {
|
||||
hasToken: !!userToken,
|
||||
});
|
||||
|
||||
try {
|
||||
// Update secure storage
|
||||
await secureStore.setItemAsync(STORAGE_KEYS.USER_TOKEN, userToken);
|
||||
|
||||
// Update in-memory state
|
||||
merge({ userToken });
|
||||
|
||||
// Update session from JWT
|
||||
if (userToken) {
|
||||
const jwtData = jwtDecode(userToken);
|
||||
sessionActions.loadSessionFromJWT(jwtData);
|
||||
}
|
||||
|
||||
authLogger.debug("User token updated successfully");
|
||||
} catch (error) {
|
||||
authLogger.error("Failed to set user token", { error: error.message });
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
default: {
|
||||
userToken: null,
|
||||
|
@ -320,7 +294,6 @@ export default createAtom(({ get, merge, getActions }) => {
|
|||
logout,
|
||||
onReload,
|
||||
userOnMode,
|
||||
setUserToken,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
import { createAtom } from "~/lib/atomic-zustand";
|
||||
import { secureStore } from "~/storage/memorySecureStore";
|
||||
import { STORAGE_KEYS } from "~/storage/storageKeys";
|
||||
import { secureStore } from "~/lib/secureStore";
|
||||
|
||||
export default createAtom(({ merge, reset }) => {
|
||||
const setFcmToken = (token) => {
|
||||
|
@ -10,11 +9,8 @@ export default createAtom(({ merge, reset }) => {
|
|||
};
|
||||
|
||||
const setFcmTokenStored = ({ fcmToken, deviceId }) => {
|
||||
secureStore.setItemAsync(STORAGE_KEYS.FCM_TOKEN_STORED, fcmToken);
|
||||
secureStore.setItemAsync(
|
||||
STORAGE_KEYS.FCM_TOKEN_STORED_DEVICE_ID,
|
||||
deviceId.toString(),
|
||||
);
|
||||
secureStore.setItemAsync("fcmTokenStored", fcmToken);
|
||||
secureStore.setItemAsync("fcmTokenStoredDeviceId", deviceId.toString());
|
||||
merge({
|
||||
fcmTokenStored: fcmToken,
|
||||
deviceId,
|
||||
|
@ -22,11 +18,9 @@ export default createAtom(({ merge, reset }) => {
|
|||
};
|
||||
|
||||
const init = async () => {
|
||||
const fcmTokenStored = await secureStore.getItemAsync(
|
||||
STORAGE_KEYS.FCM_TOKEN_STORED,
|
||||
);
|
||||
const fcmTokenStored = await secureStore.getItemAsync("fcmTokenStored");
|
||||
const fcmTokenStoredDeviceId = await secureStore.getItemAsync(
|
||||
STORAGE_KEYS.FCM_TOKEN_STORED_DEVICE_ID,
|
||||
"fcmTokenStoredDeviceId",
|
||||
);
|
||||
const deviceId = fcmTokenStoredDeviceId
|
||||
? parseInt(fcmTokenStoredDeviceId, 10)
|
||||
|
|
|
@ -61,7 +61,7 @@ export default createAtom(({ get, merge, reset }) => {
|
|||
...m,
|
||||
routeName,
|
||||
});
|
||||
navLogger.debug("Route updated", { routeName });
|
||||
navLogger.info("Route updated", { routeName });
|
||||
};
|
||||
|
||||
const initialValues = {
|
||||
|
@ -78,11 +78,11 @@ export default createAtom(({ get, merge, reset }) => {
|
|||
default: initialValues,
|
||||
actions: {
|
||||
reset: () => {
|
||||
navLogger.debug("Resetting navigation state to initial values");
|
||||
navLogger.info("Resetting navigation state to initial values");
|
||||
reset();
|
||||
},
|
||||
updateRouteFromRootStack: (state) => {
|
||||
navLogger.debug("Updating route from root stack", { state });
|
||||
navLogger.info("Updating route from root stack", { state });
|
||||
const { index, routeNames } = state;
|
||||
const rootRouteName = routeNames[index];
|
||||
updateRoute({
|
||||
|
@ -90,7 +90,7 @@ export default createAtom(({ get, merge, reset }) => {
|
|||
});
|
||||
},
|
||||
updateRouteFromDrawer: (state) => {
|
||||
navLogger.debug("Updating route from drawer", { state });
|
||||
navLogger.info("Updating route from drawer", { state });
|
||||
const { index, routeNames } = state;
|
||||
const drawerRouteName = routeNames[index];
|
||||
updateRoute({
|
||||
|
@ -98,7 +98,7 @@ export default createAtom(({ get, merge, reset }) => {
|
|||
});
|
||||
},
|
||||
updateRouteFromMain: (state) => {
|
||||
navLogger.debug("Updating route from main", { state });
|
||||
navLogger.info("Updating route from main", { state });
|
||||
const { index, routeNames } = state;
|
||||
const mainRouteName = routeNames[index];
|
||||
updateRoute({
|
||||
|
@ -106,13 +106,13 @@ export default createAtom(({ get, merge, reset }) => {
|
|||
});
|
||||
},
|
||||
setNextNavigation: (nextNavigation) => {
|
||||
navLogger.debug("Setting next navigation", { nextNavigation });
|
||||
navLogger.info("Setting next navigation", { nextNavigation });
|
||||
merge({
|
||||
nextNavigation,
|
||||
});
|
||||
},
|
||||
setMessageViewFocus: (isFocused, alertId = null) => {
|
||||
navLogger.debug("Setting message view focus", { isFocused, alertId });
|
||||
navLogger.info("Setting message view focus", { isFocused, alertId });
|
||||
merge({
|
||||
isOnMessageView: isFocused,
|
||||
currentMessageAlertId: isFocused ? alertId : null,
|
||||
|
|
|
@ -1,13 +1,12 @@
|
|||
import { createAtom } from "~/lib/atomic-zustand";
|
||||
import AsyncStorage from "~/storage/memoryAsyncStorage";
|
||||
import { STORAGE_KEYS } from "~/storage/storageKeys";
|
||||
import AsyncStorage from "~/lib/memoryAsyncStorage";
|
||||
|
||||
const WIZARD_COMPLETED_KEY = "@permission_wizard_completed";
|
||||
|
||||
export default createAtom(({ set, get }) => {
|
||||
const init = async () => {
|
||||
try {
|
||||
const wizardCompleted = await AsyncStorage.getItem(
|
||||
STORAGE_KEYS.PERMISSION_WIZARD_COMPLETED,
|
||||
);
|
||||
const wizardCompleted = await AsyncStorage.getItem(WIZARD_COMPLETED_KEY);
|
||||
if (wizardCompleted === "true") {
|
||||
set("completed", true);
|
||||
}
|
||||
|
@ -28,10 +27,7 @@ export default createAtom(({ set, get }) => {
|
|||
setCompleted: (completed) => {
|
||||
set("completed", completed);
|
||||
if (completed) {
|
||||
AsyncStorage.setItem(
|
||||
STORAGE_KEYS.PERMISSION_WIZARD_COMPLETED,
|
||||
"true",
|
||||
).catch((error) => {
|
||||
AsyncStorage.setItem(WIZARD_COMPLETED_KEY, "true").catch((error) => {
|
||||
console.error("Error saving permission wizard status:", error);
|
||||
});
|
||||
}
|
||||
|
|
|
@ -1,13 +1,14 @@
|
|||
import { useCallback, useEffect, useState } from "react";
|
||||
import { Alert } from "react-native";
|
||||
import * as Updates from "expo-updates";
|
||||
import AsyncStorage from "~/storage/memoryAsyncStorage";
|
||||
import { STORAGE_KEYS } from "~/storage/storageKeys";
|
||||
import AsyncStorage from "~/lib/memoryAsyncStorage";
|
||||
import useNow from "~/hooks/useNow";
|
||||
import * as Sentry from "@sentry/react-native";
|
||||
|
||||
import env from "~/env";
|
||||
import { treeActions } from "~/stores";
|
||||
|
||||
const LAST_UPDATE_CHECK_KEY = "lastUpdateCheckTime";
|
||||
const UPDATE_CHECK_INTERVAL = 24 * 60 * 60 * 1000;
|
||||
|
||||
const applyUpdate = async () => {
|
||||
|
@ -27,17 +28,12 @@ const checkForUpdate = async () => {
|
|||
return;
|
||||
}
|
||||
try {
|
||||
const lastCheckString = await AsyncStorage.getItem(
|
||||
STORAGE_KEYS.LAST_UPDATE_CHECK_TIME,
|
||||
);
|
||||
const lastCheckString = await AsyncStorage.getItem(LAST_UPDATE_CHECK_KEY);
|
||||
const lastCheck = lastCheckString ? new Date(lastCheckString) : null;
|
||||
const nowDate = new Date();
|
||||
|
||||
if (!lastCheck || nowDate - lastCheck > UPDATE_CHECK_INTERVAL) {
|
||||
await AsyncStorage.setItem(
|
||||
STORAGE_KEYS.LAST_UPDATE_CHECK_TIME,
|
||||
nowDate.toISOString(),
|
||||
);
|
||||
await AsyncStorage.setItem(LAST_UPDATE_CHECK_KEY, nowDate.toISOString());
|
||||
|
||||
const update = await Updates.checkForUpdateAsync();
|
||||
if (!update.isAvailable) {
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
import AsyncStorage from "~/storage/memoryAsyncStorage";
|
||||
import { STORAGE_KEYS } from "~/storage/storageKeys";
|
||||
import AsyncStorage from "~/lib/memoryAsyncStorage";
|
||||
import { createLogger } from "~/lib/logger";
|
||||
import { SYSTEM_SCOPES } from "~/lib/logger/scopes";
|
||||
|
||||
|
@ -8,6 +7,8 @@ const storageLogger = createLogger({
|
|||
feature: "location-cache",
|
||||
});
|
||||
|
||||
export const LOCATION_STORAGE_KEY = "@last_known_location";
|
||||
|
||||
/**
|
||||
* Stores location data in AsyncStorage with timestamp
|
||||
* @param {Object} coords - Location coordinates object
|
||||
|
@ -35,7 +36,7 @@ export async function storeLocation(
|
|||
});
|
||||
|
||||
await AsyncStorage.setItem(
|
||||
STORAGE_KEYS.LAST_KNOWN_LOCATION,
|
||||
LOCATION_STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
coords,
|
||||
timestamp,
|
||||
|
@ -57,7 +58,7 @@ export async function storeLocation(
|
|||
export async function getStoredLocation() {
|
||||
try {
|
||||
storageLogger.debug("Retrieving stored location data");
|
||||
const stored = await AsyncStorage.getItem(STORAGE_KEYS.LAST_KNOWN_LOCATION);
|
||||
const stored = await AsyncStorage.getItem(LOCATION_STORAGE_KEY);
|
||||
|
||||
if (!stored) {
|
||||
storageLogger.debug("No stored location data found");
|
||||
|
|
Loading…
Add table
Reference in a new issue