Files
timelapse-frontend/js/core/routes.js

289 lines
8.2 KiB
JavaScript

// Global variables
let global_project_list;
let current_project = "";
let active_camera_project = null; // ID du projet actuellement utilisé par la caméra
function formatDate(isoString) {
const date = new Date(isoString);
const options = {
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
timeZoneName: "short",
};
return date.toLocaleString("en-US", options);
}
// Function to get data from API
function getAllProject() {
return $.ajax({
url: api_url.concat("/projects"),
method: "GET",
dataType: "json"
}).then((data) => {
return data;
});
}
function getSingleProject(id) {
return $.ajax({
url: api_url.concat("/projects/"+id),
method: "GET",
dataType: "json"
}).then((data) => {
return data;
});
}
async function getDataMetrics(projectId){
try {
const response = await $.ajax({
url: api_url.concat(`/projects/${projectId}/measurements`),
method: "GET",
dataType: "json",
});
return response;
} catch (error) {
console.log("no data for this project")
return error.status;
}
}
async function getDataProjectVideosFromApi(id) {
try {
const response = await $.ajax({
url: api_url.concat(`/projects/${id}/videos`),
method: "GET",
dataType: "json",
});
// If the request is successful, store the data in the cache and return it
return response;
} catch (error) {
return(error.status)
}
}
async function getDataVideoFromApi(id) {
try {
const response = await $.ajax({
url: api_url.concat(`/videos/${id}`),
method: "GET",
dataType: "json",
});
// If the request is successful, store the data in the cache and return it
return response;
} catch (error) {
alert("Error fetching data:", error);
throw error; // Re-throw the error to handle it outside the function if needed
}
}
async function postNewVideo(project_id, measurements_id, name_video, resolution, duration) {
try {
const measures = JSON.stringify(measurements_id);
const mydata = JSON.stringify({
project_id: project_id,
measurement_ids: measures, // Ensure this matches the expected field name
name: name_video,
resolution: resolution,
duration: duration
});
const response = await $.ajax({
url: api_url.concat(`/videos/`),
method: "POST",
dataType: "json",
contentType: "application/json",
data: mydata
});
alert("Video posted successfully:", response);
} catch (error) {
alert("Error posting video:", error);
throw error;
}
}
async function PostNewProject(nameProject, description){
try {
if(description.length==0){
description="Non renseignée"
}
const mydata = JSON.stringify({
name: nameProject,
description: description
});
const response = await $.ajax({
url: api_url.concat(`/projects`),
method: "POST",
dataType: "json",
contentType: "application/json",
data: mydata
});
alert("Video posted successfully:", response);
location.reload();
} catch (error) {
alert("Error posting video:", error);
throw error;
}
}
async function deleteProject(id){
try {
const response = await $.ajax({
url: api_url.concat(`/projects/${id}`),
method: "DELETE",
}).then(()=>{
alert("Projet supprimé avec succès")
location.reload();
})
} catch (error) {
alert("Error deleting project, project id :"+ id+"\n error :"+error);
throw error;
}
}
async function deleteVideo(id){
try {
const response = await $.ajax({
url: api_url.concat(`/videos/${id}`),
method: "DELETE",
}).then(()=>{
alert("Video supprimé avec succès")
location.reload();
})
} catch (error) {
alert("Error deleting video, video id :"+ id+"\n error :"+error);
throw error;
}
}
async function renderVideo(id){
try {
const mydata = JSON.stringify({
info:"none"
});
const response = await $.ajax({
url: api_url.concat(`/videos/render/`+id),
method: "POST",
dataType: "json",
contentType: "application/json",
data: mydata
});
alert("Video rendered successfully:", response);
} catch (error) {
alert("Error rendering video:", error);
throw error;
}
}
async function start_timelapse(id,frequency,nbimages){
try {
// Vérifier si un autre projet est déjà actif avec la caméra
if (active_camera_project !== null && active_camera_project !== id) {
const confirmation = confirm(`Un autre projet (ID: ${active_camera_project}) est déjà en cours avec la caméra. Voulez-vous arrêter ce projet et configurer la caméra pour le projet actuel?`);
if (!confirmation) {
alert("Configuration annulée. La caméra reste configurée pour le projet précédent.");
return false;
}
// Si l'utilisateur confirme, on continue et on va redéfinir active_camera_project
}
// Utilisation de plusieurs formats possibles pour garantir que le backend reçoit l'ID
const mydata = JSON.stringify({
project_id: id, // Format avec underscore (convention standard REST)
projectId: id, // Format camelCase
id: id, // Format simple
interval: frequency,
nb_images: nbimages
});
console.log("Données envoyées à /procedure/start:", mydata); // Log pour débogage
const response = await $.ajax({
url: api_url.concat(`/procedure/start`),
method: "POST",
dataType: "json",
contentType: "application/json",
data: mydata
});
// Définir ce projet comme le projet actif pour la caméra
active_camera_project = id;
alert("Configuration de la caméra réussie");
return response;
} catch (error) {
console.error("Erreur détaillée:", error); // Log plus détaillé de l'erreur
alert("Erreur lors de la configuration de la caméra: " + error);
throw error;
}
}
async function stopCamera(id){
try {
const mydata = JSON.stringify({
info:"None"
});
const response = await $.ajax({
url: api_url.concat(`/procedure/stop`),
method: "POST",
dataType: "json",
contentType: "application/json",
data: mydata
});
// Réinitialiser le statut du projet actif sur la caméra
active_camera_project = null;
alert("La caméra a été arrêtée avec succès");
return response;
} catch (error) {
alert("Erreur lors de l'arrêt de la caméra : " + error);
throw error;
}
}
async function manualUpload(imageFile, projectId, timestamp, temperature, humidity) {
try {
// Vérifier que l'upload est fait pour le projet actif de la caméra
if (active_camera_project === null) {
alert("Aucun projet n'est actif avec la caméra. Veuillez configurer un projet avant d'effectuer un upload manuel.");
return false;
}
if (projectId !== active_camera_project) {
alert(`L'upload manuel n'est possible que pour le projet actif (ID: ${active_camera_project}). Vous essayez d'uploader pour le projet ${projectId}.`);
return false;
}
// Create FormData to send the file and metadata
const formData = new FormData();
formData.append('image', imageFile);
formData.append('projectId', projectId);
formData.append('timestamp', timestamp);
formData.append('temperature', temperature);
formData.append('humidity', humidity);
const response = await $.ajax({
url: api_url.concat("/camera/upload"),
method: "POST",
data: formData,
processData: false, // Prevents jQuery from converting FormData to string
contentType: false, // Lets browser set the content type with boundary
});
alert("Image téléchargée avec succès");
return response;
} catch (error) {
alert("Erreur lors du téléchargement de l'image : " + error);
throw error;
}
}