Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🚀 Nouveau compte : Ajout des instance depuis les datasets de Papillon #502

Merged
merged 3 commits into from
Dec 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/consts/datasets.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"kofi-supporters": "https://raw.githubusercontent.com/PapillonApp/datasets/main/kofi-supporters.json",
"changelog": "https://raw.githubusercontent.com/PapillonApp/datasets/main/updates/[version].json",
"illustrations": "https://raw.githubusercontent.com/PapillonApp/datasets/refs/heads/main/illustrations/index.json"
"illustrations": "https://raw.githubusercontent.com/PapillonApp/datasets/refs/heads/main/illustrations/index.json",
"establishment": "https://raw.githubusercontent.com/PapillonApp/datasets/refs/heads/main/establishment/[postcode].json"
}
63 changes: 63 additions & 0 deletions src/services/pronote/dataset_geolocation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import pronote from "pawnote";
import datasets from "../../consts/datasets.json";

const getInstancesFromDataset = async (longitude: number, latitude: number): Promise<pronote.GeolocatedInstance[]> => {
let adress_api_fetch = await fetch(`https://api-adresse.data.gouv.fr/reverse/?lon=${longitude}&lat=${latitude}&limit=1`);
try {
let adress_api = await adress_api_fetch.json();
if (adress_api.features.length === 0) {
return [];
}
let postcode = adress_api.features[0].properties.postcode;
postcode = postcode[0] + postcode[1] + "000";

let instances_fetch = await fetch(datasets.establishment.replace("[postcode]", postcode));
try {
let instances = await instances_fetch.json();

const calculateHaversineDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => {
const toRadians = (degrees: number) => degrees * (Math.PI / 180);
const R = 6371; // Earth's radius in kilometers

const dLat = toRadians(lat2 - lat1);
const dLon = toRadians(lon2 - lon1);

const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRadians(lat1)) * Math.cos(toRadians(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

return R * c;
};

return instances.map((instance: any) => {
const distance = calculateHaversineDistance(
latitude,
longitude,
instance.lat,
instance.long
);

console.log("User location:", { latitude, longitude });
console.log("Instance location:", { latitude: instance.lat, longitude: instance.long });
console.log("Calculated distance:", distance);

return {
name: instance.name.toUpperCase(),
url: instance.url,
distance,
longitude: instance.long,
latitude: instance.lat,
};
});
} catch (error) {
console.error("Error fetching instances:", error);
return [];
}
} catch (error) {
console.error("Error fetching address:", error);
return [];
}
};

export default getInstancesFromDataset;
3 changes: 2 additions & 1 deletion src/views/login/pronote/PronoteGeolocation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ const PronoteGeolocation: Screen<"PronoteGeolocation"> = ({ navigation }) => {
style={[styles.terms_text, { color: colors.text + "59" }]}
>
Votre position est nécessaire pour trouver les instances PRONOTE à proximité.
Elle n'est pas stockée et ne sera pas partagée.
Elle sera envoyée à Pronote et à l'api adresse du gouvernement pour trouver les établissements.
Elle n'est pas stockée.
</Text>
</SafeAreaView>
);
Expand Down
79 changes: 73 additions & 6 deletions src/views/login/pronote/PronoteInstanceSelector.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import React, { useEffect, useState } from "react";
import type { Screen } from "@/router/helpers/types";
import { TextInput, TouchableOpacity, View, StyleSheet, ActivityIndicator, Keyboard, KeyboardEvent } from "react-native";
import {
TextInput,
TouchableOpacity,
View,
StyleSheet,
ActivityIndicator,
Keyboard,
KeyboardEvent,
Text
} from "react-native";
import pronote from "pawnote";
import Reanimated, { LinearTransition, FlipInXDown, FadeInUp, FadeOutUp, ZoomIn, ZoomOut, Easing, ZoomInEasyDown } from "react-native-reanimated";
import determinateAuthenticationView from "@/services/pronote/determinate-authentication-view";
Expand All @@ -14,6 +23,7 @@ import { useTheme } from "@react-navigation/native";
import { Search, X, GraduationCap, } from "lucide-react-native";
import { useAlert } from "@/providers/AlertProvider";
import { Audio } from "expo-av";
import getInstancesFromDataset from "@/services/pronote/dataset_geolocation";

const PronoteInstanceSelector: Screen<"PronoteInstanceSelector"> = ({
route: { params },
Expand Down Expand Up @@ -74,15 +84,48 @@ const PronoteInstanceSelector: Screen<"PronoteInstanceSelector"> = ({
};
}, []);

const playSound = () => sound?.replayAsync();

useEffect(() => {
useEffect(() => {
if (params) {
void async function () {
const instances = await pronote.geolocation(params);
const dataset_instances = await getInstancesFromDataset(params.longitude, params.latitude);
const pronote_instances = await pronote.geolocation(params);

// On calcule la distance entre les instances et l'utilisateur.
let instances = pronote_instances.map((instance) => {
const toRadians = (degrees: number) => degrees * (Math.PI / 180);
const R = 6371; // Earth's radius in kilometers

const lat1 = toRadians(params.latitude);
const lon1 = toRadians(params.longitude);
const lat2 = toRadians(instance.latitude);
const lon2 = toRadians(instance.longitude);

const dLat = lat2 - lat1;
const dLon = lon2 - lon1;

const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distance = R * c;

return {
...instance,
distance, // Distance in kilometers
};
});

// On limite à 20 instances.
instances.splice(20);

// On ajoute les instances trouvées par l'API adresse.
instances.push(...dataset_instances);

// On trie par distance.
instances.sort((a, b) => a.distance - b.distance);

// On met à jour les instances.
setInstances(instances);
setOriginalInstances(instances);
}();
Expand Down Expand Up @@ -248,15 +291,39 @@ const PronoteInstanceSelector: Screen<"PronoteInstanceSelector"> = ({
color={colors.text + "88"}
/>
}
text={instance.name}
onPress={async () => {
determinateAuthenticationView(
instance.url,
navigation,
showAlert
);
}}
/>
>
<Text
style={{
fontSize: 18,
fontFamily: "medium",
width: "100%",
color: colors.text + "88"
}}
numberOfLines={1}
ellipsizeMode="tail"
>
{instance.name}
</Text>
<Text
style={{
fontSize: 15,
fontFamily: "medium",
width: "100%",
color: colors.text + "55",
}}
numberOfLines={1}
ellipsizeMode="tail"
>
{`à ${instance.distance.toFixed(2)}km de toi`}
</Text>
</DuoListPressable>
</Reanimated.View>
))}
</Reanimated.View>
Expand Down
Loading