mirror of
https://git.rezel.net/LudoTech/traque.git
synced 2026-04-11 00:30:19 +02:00
Fix background task + socket in services + cleaning
This commit is contained in:
@@ -1,14 +1,13 @@
|
||||
// React
|
||||
import { useCallback } from "react";
|
||||
// Hook
|
||||
import { useSocketCommands } from "./useSocketCommands";
|
||||
// Services
|
||||
import { emitSendPosition, emitCapture } from "../services/socketEmitter";
|
||||
|
||||
export const useGame = () => {
|
||||
const { emitSendPosition, emitCapture } = useSocketCommands();
|
||||
|
||||
const sendCurrentPosition = useCallback(() => {
|
||||
emitSendPosition();
|
||||
}, [emitSendPosition]);
|
||||
}, []);
|
||||
|
||||
const capture = useCallback((captureCode) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -22,7 +21,7 @@ export const useGame = () => {
|
||||
resolve(response);
|
||||
});
|
||||
});
|
||||
}, [emitCapture]);
|
||||
}, []);
|
||||
|
||||
return { sendCurrentPosition, capture };
|
||||
};
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
// Rect
|
||||
import { useCallback, useMemo } from "react";
|
||||
// Contexts
|
||||
import { useTeamConnexion } from "../context/teamConnexionContext";
|
||||
import { useTeamContext } from '../context/teamContext';
|
||||
// Util
|
||||
import { SERVER_URL } from "../util/constants";
|
||||
|
||||
export const useImageApi = () => {
|
||||
const { teamId } = useTeamConnexion();
|
||||
const { teamInfos } = useTeamContext();
|
||||
const { enemyName } = teamInfos;
|
||||
|
||||
const uploadTeamImage = useCallback(async (imageUri) => {
|
||||
if (!imageUri || !teamId) return;
|
||||
|
||||
const data = new FormData();
|
||||
data.append('file', {
|
||||
uri: imageUri,
|
||||
name: 'photo.jpg',
|
||||
type: 'image/jpeg',
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await fetch(`${SERVER_URL}/upload?team=${teamId}`, {
|
||||
method: 'POST',
|
||||
body: data,
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error("Échec de l'upload");
|
||||
return await response.blob();
|
||||
} catch (error) {
|
||||
console.error("Erreur uploadImage :", error);
|
||||
throw error;
|
||||
}
|
||||
}, [teamId]);
|
||||
|
||||
const enemyImage = useMemo(() => {
|
||||
if (!teamId || !enemyName) return require('../assets/images/missing_image.jpg');
|
||||
|
||||
return {uri: `${SERVER_URL}/photo/enemy?team=${teamId}`};
|
||||
}, [teamId, enemyName]);
|
||||
|
||||
return { enemyImage, uploadTeamImage };
|
||||
};
|
||||
@@ -1,82 +1,33 @@
|
||||
// React
|
||||
import { useEffect, useState, useCallback, useMemo } from "react";
|
||||
import { Alert } from "react-native";
|
||||
import { useState, useEffect } from 'react';
|
||||
// Expo
|
||||
import { defineTask, isTaskRegisteredAsync } from "expo-task-manager";
|
||||
import * as Location from 'expo-location';
|
||||
// Hook
|
||||
import { useSocketCommands } from "./useSocketCommands";
|
||||
// Constants
|
||||
import { LOCATION_PARAMETERS } from '../constants';
|
||||
|
||||
export const useLocation = (timeInterval, distanceInterval) => {
|
||||
const { emitUpdatePosition } = useSocketCommands();
|
||||
const [location, setLocation] = useState(null); // [latitude, longitude]
|
||||
const LOCATION_TASK_NAME = "background-location-task";
|
||||
const locationUpdateParameters = useMemo(() => ({
|
||||
accuracy: Location.Accuracy.High,
|
||||
distanceInterval: distanceInterval, // Update every 10 meters
|
||||
timeInterval: timeInterval, // Minimum interval in ms
|
||||
showsBackgroundLocationIndicator: true, // iOS only
|
||||
pausesUpdatesAutomatically: false, // (iOS) Prevents auto-pausing of location updates
|
||||
foregroundService: {
|
||||
notificationTitle: "Enregistrement de votre position.",
|
||||
notificationBody: "L'application utilise votre position en arrière plan.",
|
||||
notificationColor: "#FF0000", // (Android) Notification icon color
|
||||
},
|
||||
}), [distanceInterval, timeInterval]);
|
||||
|
||||
defineTask(LOCATION_TASK_NAME, async ({ data, error }) => {
|
||||
if (error) {
|
||||
console.error(error);
|
||||
return;
|
||||
}
|
||||
if (data) {
|
||||
const { locations } = data;
|
||||
if (locations.length > 0) {
|
||||
const firstLocation = locations[0];
|
||||
const { latitude, longitude } = firstLocation.coords;
|
||||
const new_location = [latitude, longitude];
|
||||
try {
|
||||
setLocation(new_location);
|
||||
} catch (e) {
|
||||
console.warn("setLocation failed (probably in background):", e);
|
||||
}
|
||||
emitUpdatePosition(new_location);
|
||||
} else {
|
||||
console.log("No location measured.");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const getLocationAuthorization = useCallback(async () => {
|
||||
const { status : statusForeground } = await Location.requestForegroundPermissionsAsync();
|
||||
const { status : statusBackground } = await Location.requestBackgroundPermissionsAsync();
|
||||
if (statusForeground !== "granted" || statusBackground !== "granted") {
|
||||
Alert.alert("Échec", "Activez la localisation en arrière plan dans les paramètres.");
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const startLocationTracking = useCallback(async () => {
|
||||
if (await getLocationAuthorization()) {
|
||||
if (!(await isTaskRegisteredAsync(LOCATION_TASK_NAME))) {
|
||||
await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, locationUpdateParameters);
|
||||
console.log("Location tracking started.");
|
||||
}
|
||||
}
|
||||
}, [getLocationAuthorization, locationUpdateParameters]);
|
||||
|
||||
const stopLocationTracking = useCallback(async () => {
|
||||
if (await isTaskRegisteredAsync(LOCATION_TASK_NAME)) {
|
||||
await Location.stopLocationUpdatesAsync(LOCATION_TASK_NAME);
|
||||
console.log("Location tracking stopped.");
|
||||
}
|
||||
}, []);
|
||||
export const useLocation = () => {
|
||||
const [location, setLocation] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
getLocationAuthorization();
|
||||
}, [getLocationAuthorization]);
|
||||
let subscription;
|
||||
|
||||
return [location, getLocationAuthorization, startLocationTracking, stopLocationTracking];
|
||||
const startWatching = async () => {
|
||||
const { status } = await Location.requestForegroundPermissionsAsync();
|
||||
|
||||
if (status !== 'granted') return;
|
||||
|
||||
subscription = await Location.watchPositionAsync(
|
||||
LOCATION_PARAMETERS,
|
||||
(location) => setLocation(location.coords)
|
||||
);
|
||||
};
|
||||
|
||||
startWatching();
|
||||
|
||||
return () => {
|
||||
if (subscription) subscription.remove();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { location };
|
||||
};
|
||||
|
||||
@@ -3,11 +3,10 @@ import { useEffect, useRef } from 'react';
|
||||
import DeviceInfo from 'react-native-device-info';
|
||||
// Context
|
||||
import { useTeamConnexion } from "../context/teamConnexionContext";
|
||||
// Hook
|
||||
import { useSocketCommands } from "./useSocketCommands";
|
||||
// Services
|
||||
import { emitBattery, emitDeviceInfo } from "../services/socketEmitter";
|
||||
|
||||
export const useSendDeviceInfo = () => {
|
||||
const { emitBattery, emitDeviceInfo } = useSocketCommands();
|
||||
const { loggedIn } = useTeamConnexion();
|
||||
const isMounted = useRef(true);
|
||||
|
||||
@@ -41,7 +40,7 @@ export const useSendDeviceInfo = () => {
|
||||
isMounted.current = false;
|
||||
clearInterval(batteryCheckInterval);
|
||||
};
|
||||
}, [emitBattery, emitDeviceInfo, loggedIn]);
|
||||
}, [loggedIn]);
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
// Hook
|
||||
import { useLocalStorage } from './useLocalStorage';
|
||||
import { useSocketCommands } from "./useSocketCommands";
|
||||
// Services
|
||||
import { emitLogin, emitLogout } from "../services/socketEmitter";
|
||||
|
||||
export const useSocketAuth = () => {
|
||||
const { emitLogin, emitLogout } = useSocketCommands();
|
||||
const [loggedIn, setLoggedIn] = useState(false);
|
||||
const [savedPassword, setSavedPassword] = useLocalStorage("team_password", null);
|
||||
const isMounted = useRef(true);
|
||||
@@ -42,7 +42,7 @@ export const useSocketAuth = () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
}, [emitLogin, setSavedPassword]);
|
||||
}, [setSavedPassword]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!loggedIn && savedPassword) {
|
||||
@@ -54,7 +54,7 @@ export const useSocketAuth = () => {
|
||||
setLoggedIn(false);
|
||||
setSavedPassword(null);
|
||||
emitLogout();
|
||||
}, [emitLogout, setSavedPassword]);
|
||||
}, [setSavedPassword]);
|
||||
|
||||
return {login, logout, password: savedPassword, loggedIn};
|
||||
};
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
// React
|
||||
import { useCallback } from 'react';
|
||||
// Context
|
||||
import { useSocket } from "../context/socketContext";
|
||||
|
||||
export const useSocketCommands = () => {
|
||||
const { teamSocket } = useSocket();
|
||||
|
||||
const emitLogin = useCallback((password, callback) => {
|
||||
if (!teamSocket?.connected) return;
|
||||
console.log("Try to log in with :", password);
|
||||
teamSocket.emit("login", password, callback);
|
||||
}, [teamSocket]);
|
||||
|
||||
const emitLogout = useCallback(() => {
|
||||
if (!teamSocket?.connected) return;
|
||||
console.log("Logout.");
|
||||
teamSocket.emit("logout");
|
||||
}, [teamSocket]);
|
||||
|
||||
const emitSendPosition = useCallback(() => {
|
||||
if (!teamSocket?.connected) return;
|
||||
console.log("Reveal position.");
|
||||
teamSocket.emit("send_position");
|
||||
}, [teamSocket]);
|
||||
|
||||
const emitUpdatePosition = useCallback((location) => {
|
||||
if (!teamSocket?.connected) return;
|
||||
console.log("Update position :", location);
|
||||
teamSocket.emit("update_position", location);
|
||||
}, [teamSocket]);
|
||||
|
||||
const emitCapture = useCallback((captureCode, callback) => {
|
||||
if (!teamSocket?.connected) return;
|
||||
console.log("Try to capture :", captureCode);
|
||||
teamSocket.emit("capture", captureCode, callback);
|
||||
}, [teamSocket]);
|
||||
|
||||
const emitBattery = useCallback((level) => {
|
||||
if (!teamSocket?.connected) return;
|
||||
console.log("Send battery level.");
|
||||
teamSocket.emit('battery_update', level);
|
||||
}, [teamSocket]);
|
||||
|
||||
const emitDeviceInfo = useCallback((infos) => {
|
||||
if (!teamSocket?.connected) return;
|
||||
console.log("Send device infos.");
|
||||
teamSocket.emit('device_info', infos);
|
||||
}, [teamSocket]);
|
||||
|
||||
return { emitLogin, emitLogout, emitSendPosition, emitUpdatePosition, emitCapture, emitBattery, emitDeviceInfo };
|
||||
};
|
||||
@@ -1,11 +0,0 @@
|
||||
// React
|
||||
import { useEffect } from "react";
|
||||
|
||||
export const useSocketListener = (socket, event, callback) => {
|
||||
useEffect(() => {
|
||||
socket.on(event, callback);
|
||||
return () => {
|
||||
socket.off(event, callback);
|
||||
};
|
||||
}, [callback, event, socket]);
|
||||
};
|
||||
Reference in New Issue
Block a user