Push avant Clean

This commit is contained in:
MasterAcnolo
2025-11-09 09:04:57 +01:00
parent ac854ae559
commit 4954de5f1a
71 changed files with 1256 additions and 1350 deletions

67
server/discordRPC.js Normal file
View File

@@ -0,0 +1,67 @@
/*
This file is part of Freedom Loader.
Copyright (C) 2025 MasterAcnolo
Freedom Loader is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License.
Freedom Loader is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
const RPC = require("discord-rpc");
const clientId = "1410934537051181146";
const rpc = new RPC.Client({ transport: "ipc" });
let intervalId;
function startRPC() {
rpc.on("ready", () => {
console.log("Connecté à Discord !");
const presence = {
largeImageKey: "icon",
smallImageKey: "acnolo_pfp",
smallImageText: "By MasterAcnolo",
startTimestamp: new Date(),
details: "github.com/MasterAcnolo/Freedom-Loader",
};
rpc.setActivity(presence);
// Met à jour la présence toutes les 15s
intervalId = setInterval(() => {
rpc.setActivity(presence);
}, 15000);
});
rpc.login({ clientId }).catch(err => {
console.error("Erreur Discord RPC :", err);
});
// Gestion propre de la fermeture
const cleanExit = () => {
if (intervalId) clearInterval(intervalId); // stop interval
rpc.destroy(); // déconnecte proprement
console.log("Discord RPC arrêté proprement.");
};
process.on("exit", cleanExit);
process.on("SIGINT", () => {
cleanExit();
process.exit();
});
process.on("SIGTERM", () => {
cleanExit();
process.exit();
});
}
module.exports = { startRPC };

86
server/logger.js Normal file
View File

@@ -0,0 +1,86 @@
/*
This file is part of Freedom Loader.
Copyright (C) 2025 MasterAcnolo
Freedom Loader is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License.
Freedom Loader is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
const { createLogger, format, transports } = require("winston");
const DailyRotateFile = require("winston-daily-rotate-file");
const fs = require("fs");
const path = require("path");
const os = require("os");
// Dossier de logs Windows
const logDir = path.join(os.homedir(), "AppData", "Local", "FreedomLoader", "logs");
// Création du dossier si nécessaire
fs.mkdirSync(logDir, { recursive: true });
// Format commun pour tous les logs
const logFormat = format.combine(
format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
format.printf(({ timestamp, level, message }) => `${timestamp} | ${level.toUpperCase()} | ${message}`)
);
const consoleFormat = format.combine(
format.colorize(),
format.timestamp({ format: "HH:mm:ss" }),
format.printf(({ timestamp, level, message }) => `${timestamp} | ${level} | ${message}`)
);
// Configuration du logger
const logger = createLogger({
level: "info",
format: logFormat,
transports: [
new DailyRotateFile({
dirname: logDir,
filename: "LOGS-%DATE%.log",
datePattern: "YYYY-MM-DD",
zippedArchive: false,
maxFiles: "7d",
format: logFormat,
options: { flags: "a" },
}),
new transports.Console({
format: consoleFormat,
}),
],
});
// Helpers pour sessions
function getSessionStartLine() {
return `--- Démarrage de la session : ${new Date().toISOString()} ---`;
}
function getSessionEndLine() {
return `--- Fin de la session : ${new Date().toISOString()} ---`;
}
function logSessionStart() {
logger.info(getSessionStartLine());
}
function logSessionEnd() {
logger.info(getSessionEndLine());
}
// Export
module.exports = {
logger,
logSessionStart,
logSessionEnd,
logDir,
};

172
server/routes/download.js Normal file
View File

@@ -0,0 +1,172 @@
/*
This file is part of Freedom Loader.
Copyright (C) 2025 MasterAcnolo
Freedom Loader is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License.
Freedom Loader is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
*/
const { app } = require("electron");
const express = require("express");
const router = express.Router();
const { execFile } = require("child_process");
const path = require("path");
const fs = require("fs");
const { Notification } = require("electron");
const logger = require("../logger").logger;
const userYtDlp = path.join(app.getPath("userData"), "yt-dlp.exe");
// Path vers yt-dlp
const ytDlpPath = path.join(process.resourcesPath, "yt-dlp.exe");
const sourceYtDlp = path.join(process.resourcesPath, "yt-dlp.exe");
if (!fs.existsSync(userYtDlp)) {
fs.copyFileSync(sourceYtDlp, userYtDlp);
logger.info(`yt-dlp copié dans le dossier utilisateur : ${userYtDlp}`);
}
// Lancement de la mise à jour une seule fois au démarrage
execFile(userYtDlp, ["-U"], (err, stdout, stderr) => {
if (err) {
logger.warn("Erreur update yt-dlp:", err);
logger.debug(err);
return;
}
logger.info(`Update yt-dlp : ${stdout}`);
});
// Validation simple d'une URL
function isValidUrl(url) {
return /^https?:\/\/.+/.test(url); // Petit Regex qui renvoie true si l'URL est bonne et False si elle est pas bonne
}
router.post("/", (req, res) => {
try {
const options = {
url: req.body.url,
audioOnly: req.body.audioOnly === "1",
quality: req.body.quality || "best",
};
if (!options.url) {
logger.warn("Requête POST /download sans URL");
return res.status(400).send("❌ URL manquante !");
}
if (!isValidUrl(options.url)) {
logger.warn(`URL invalide : ${options.url}`);
return res.status(400).send("❌ URL invalide !");
}
let requestedOutputFolder = req.body.savePath || req.app.locals.outputFolder;
requestedOutputFolder = path.normalize(requestedOutputFolder);
if (
!requestedOutputFolder ||
requestedOutputFolder.length < 3 ||
requestedOutputFolder.includes("System32") ||
requestedOutputFolder.includes("/etc") ||
requestedOutputFolder.includes("\\Windows")
) {
logger.warn(`Chemin potentiellement dangereux refusé : ${requestedOutputFolder}`);
return res.status(400).send("❌ Chemin de sauvegarde non autorisé.");
}
if (!fs.existsSync(requestedOutputFolder)) {
fs.mkdirSync(requestedOutputFolder, { recursive: true });
logger.info(`Dossier de sortie créé : ${requestedOutputFolder}`);
}
const outputTemplate = path.join(requestedOutputFolder, "%(title)s.%(ext)s");
const args = [
"--no-continue",
// "--restrict-filenames",
"--no-overwrites",
"--embed-thumbnail",
"--add-metadata",
"--concurrent-fragments", "8",
"--retries", "10",
"--fragment-retries", "10",
"--ffmpeg-location", path.join(process.resourcesPath, "ffmpeg.exe")
];
if (options.audioOnly) {
args.push("-f", "bestaudio", "--extract-audio", "--audio-format", "mp3");
} else
args.push("--merge-output","mp4")
const qualityMap = {
best: "bestvideo+bestaudio/best/mp4",
medium: "bestvideo[height<=720]+bestaudio/best[height<=720]/mp4",
worst: "worstvideo+worstaudio/worst/mp4",
1080: "bestvideo[height<=1080]+bestaudio/best[height<=1080]/mp4",
720: "bestvideo[height<=720]+bestaudio/best[height<=720]/mp4",
480: "bestvideo[height<=480]+bestaudio/best[height<=480]/mp4",
};
const format = qualityMap[options.quality] || "best";
args.push("-f", format);
args.push("-o", outputTemplate);
args.push(options.url);
logger.info(`Téléchargement demandé : url=${options.url}, audioOnly=${options.audioOnly}, quality=${options.quality}`);
logger.info(`Commande yt-dlp : ${ytDlpPath} ${args.join(" ")}`);
const child = execFile(userYtDlp, args);
child.stdout.on("data", (data) => {
data.toString().split("\n").forEach(line => {
if (line.trim()) logger.info(`[yt-dlp stdout] ${line.trim()}`);
});
});
child.stderr.on("data", (data) => {
data.toString().split("\n").forEach(line => {
if (line.trim()) logger.error(`[yt-dlp stderr] ${line.trim()}`);
});
});
child.on("error", (err) => {
logger.error(`Erreur lancement yt-dlp : ${err.message}`);
res.status(500).send(`❌ Erreur lors de l'exécution : ${err.message}`);
});
child.on("close", (code) => {
logger.info(`yt-dlp terminé avec code de sortie : ${code}`);
if (code === 0) {
const iconPath = path.join(process.resourcesPath, "confirm-icon.png");
const notif = new Notification({
title: "Freedom Loader",
body: "Ton téléchargement est terminé, clique ici pour l'ouvrir.",
icon: iconPath,
});
notif.on("click", () => {
const { shell } = require("electron");
shell.openPath(requestedOutputFolder);
});
notif.show();
res.send("✅ Téléchargement terminé !");
} else {
res.status(500).send(`❌ yt-dlp a échoué avec le code : ${code}`);
}
});
} catch (err) {
logger.error(`Erreur serveur dans /download : ${err.message}`);
res.status(500).send(`Erreur serveur : ${err.message}`);
}
});
module.exports = router;

101
server/routes/info.js Normal file
View File

@@ -0,0 +1,101 @@
/*
This file is part of Freedom Loader.
Copyright (C) 2025 MasterAcnolo
Freedom Loader is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License.
Freedom Loader is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
const express = require("express");
const router = express.Router();
const { execFile } = require("child_process");
const path = require("path");
const fs = require("fs");
const { logger } = require("../logger");
const { app } = require("electron");
const userYtDlp = path.join(app.getPath("userData"), "yt-dlp.exe");
const ytDlpPath = path.join(__dirname, '../../ressources/yt-dlp.exe');
// Copie yt-dlp si besoin
if (!fs.existsSync(userYtDlp)) {
fs.copyFileSync(ytDlpPath, userYtDlp);
logger.info(`yt-dlp copié dans le dossier utilisateur : ${userYtDlp}`);
}
if (!fs.existsSync(ytDlpPath)) {
logger.error(`❌ yt-dlp introuvable à ${ytDlpPath}`);
throw new Error(`yt-dlp introuvable à ${ytDlpPath}`);
}
function isValidUrl(url) {
return typeof url === "string" && /^https?:\/\//.test(url);
}
router.post("/", (req, res) => {
const url = req.body.url;
if (!url || !isValidUrl(url)) {
logger.warn("Requête /info invalide ou URL manquante");
return res.status(400).send("❌ URL invalide ou manquante");
}
logger.info(`Requête /info reçue pour ${url}`);
const args = ["--dump-single-json", "--ignore-errors", "--yes-playlist", url];
execFile(userYtDlp, args, { timeout: 30_000 }, (error, stdout, stderr) => {
if (error) {
logger.error(`Erreur exécution yt-dlp: ${error.message}`);
if (stderr) logger.debug(`stderr: ${stderr}`);
return res.status(500).send("❌ Impossible de récupérer les infos.");
}
try {
const data = JSON.parse(stdout);
if (data._type === "playlist") {
logger.info(`Playlist détectée : ${data.title} (${data.entries.length} vidéos)`);
const playlistPayload = {
type: "playlist",
title: data.title || data.id,
channel: data.uploader,
count: data.entries.length,
videos: (data.entries || []).map(v => ({
id: v.id,
title: v.title,
webpage_url: v.webpage_url,
duration: v.duration,
thumbnail: v.thumbnail,
uploader: v.uploader
}))
};
return res.json(playlistPayload);
}
// Vidéo unique
logger.info(`Vidéo unique récupérée : ${data.title}`);
res.json({
type: "video",
...data
});
} catch (e) {
logger.error(`Erreur parsing JSON: ${e.message}`);
return res.status(500).send("❌ JSON illisible.");
}
});
});
module.exports = router;

106
server/server.js Normal file
View File

@@ -0,0 +1,106 @@
/*
This file is part of Freedom Loader.
Copyright (C) 2025 MasterAcnolo
Freedom Loader is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License.
Freedom Loader is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
const express = require("express");
const fs = require("fs");
const path = require("path");
const { logger, logSessionStart, logSessionEnd } = require("./logger");
const debug = require("debug")("freedom-loader:server");
const app = express();
const PORT = 8787; // Port de l'app
// Dossier de téléchargement Windows
const downloadsPath = path.join(process.env.USERPROFILE, "Downloads");
const outputFolder = path.join(downloadsPath, "Freedom Loader");
// Création du dossier si inexistant
if (!fs.existsSync(outputFolder)) {
try {
fs.mkdirSync(outputFolder, { recursive: true });
logger.info("Dossier Freedom Loader créé dans Téléchargements.");
} catch (err) {
logger.error("Impossible de créer le dossier :", err);
process.exit(1);
}
} else {
logger.info("Dossier Freedom Loader déjà existant.");
}
app.locals.outputFolder = outputFolder;
app.use(express.urlencoded({ extended: true })); // Middleware pour parser les POST en x-www-form-urlencoded
// Fichiers statiques (frontend)
const staticPath = path.join(__dirname, "../public");
debug("Serveur statique sur", staticPath);
app.use(express.static(staticPath));
// Routes API
const infoRoute = require("./routes/info");
const downloadRoute = require("./routes/download");
debug("Routes /download et /info installées");
app.use("/download", downloadRoute);
app.use("/info", infoRoute);
// Route principale
app.get("/", (req, res) => {
debug("Requête GET / servie");
res.sendFile(path.join(__dirname, "../public/index.html"));
});
// Fonction pour démarrer le serveur Express
async function startServer() {
return new Promise((resolve, reject) => {
logSessionStart(); // Début de session
const serverInstance = app.listen(PORT, () => {
logger.info(`Serveur Express prêt sur http://localhost:${PORT}`);
resolve(serverInstance);
});
// Gestion des erreurs serveur
serverInstance.on("error", (err) => {
logger.error("Erreur serveur Express :", err);
reject(err);
});
// Gestion propre de la fermeture du serveur
const gracefulExit = () => {
logSessionEnd();
serverInstance.close(() => {
logger.info("Serveur Express fermé proprement.");
process.exit();
});
};
process.on("SIGINT", gracefulExit);
process.on("SIGTERM", gracefulExit);
});
}
// Export de startServer
module.exports = { startServer };
// Lancement du Discord RPC après que le serveur soit prêt
(async () => {
const { startRPC } = require("./discordRPC");
await startServer(); // on attend que le serveur démarre
startRPC();
})();