Helpers + Clean Download et Info

This commit is contained in:
MasterAcnolo
2025-11-09 10:35:19 +01:00
parent 4954de5f1a
commit 599e09fa9f
12 changed files with 178 additions and 326 deletions

6
config.js Normal file
View File

@@ -0,0 +1,6 @@
module.exports = {
version: "1.3.0",
applicationPort: "8787",
debugMode: true,
DiscordRPCID: "1410934537051181146",
}

28
main.js
View File

@@ -1,21 +1,4 @@
/*
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 config = require("./config.js")
const { app, BrowserWindow, ipcMain, dialog, Menu, shell } = require("electron");
const path = require("path");
const os = require("os");
@@ -37,7 +20,7 @@ async function createWindow() {
}
mainWindow = new BrowserWindow({
title: "Freedom Loader 1.3.0",
title: `Freedom Loader ${config.version}`,
width: 750,
height: 800,
minWidth: 750,
@@ -50,7 +33,7 @@ async function createWindow() {
});
try {
await mainWindow.loadURL(`http://localhost:8787`);
await mainWindow.loadURL(`http://localhost:${config.applicationPort}`);
logger.info("Fenêtre chargée");
} catch (err) {
logger.error("Erreur chargement fenêtre:", err);
@@ -108,6 +91,10 @@ app.whenReady().then(async () => {
try {
await expressServer.startServer();
logger.info("Serveur Express démarré");
const { startRPC } = require("./server/discordRPC");
startRPC();
await createWindow();
setupMenu();
} catch (err) {
@@ -116,6 +103,7 @@ app.whenReady().then(async () => {
}
});
app.on("window-all-closed", () => {
logger.info("Toutes fenêtres fermées, quitte l'app");
if (process.platform !== "darwin") app.quit();

View File

@@ -69,7 +69,6 @@ document.addEventListener("DOMContentLoaded", () => {
return;
}
// Playlist
if (data.type === "playlist") {
infoDiv.innerHTML = `
<p style="color:orange;"><strong>Playlist détectée ${data.count} vidéos</strong></p>

View File

@@ -1,23 +1,8 @@
/*
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 config = require('../config');
const RPC = require("discord-rpc");
const clientId = "1410934537051181146";
const clientId = `${config.DiscordRPCID}`;
const rpc = new RPC.Client({ transport: "ipc" });
let intervalId;
@@ -64,4 +49,4 @@ function startRPC() {
});
}
module.exports = { startRPC };
module.exports = { startRPC };

View File

@@ -0,0 +1,34 @@
const path = require("path");
function buildYtDlpArgs({ url, audioOnly, quality, outputFolder }) {
const args = [
"--no-continue",
"--no-overwrites",
"--embed-thumbnail",
"--add-metadata",
"--concurrent-fragments", "8",
"--retries", "10",
"--fragment-retries", "10",
"--ffmpeg-location", path.join(process.resourcesPath, "ffmpeg.exe")
];
if (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",
};
args.push("-f", qualityMap[quality] || "best");
args.push("-o", path.join(outputFolder, "%(title)s.%(ext)s"));
args.push(url);
return args;
}
module.exports = { buildYtDlpArgs };

16
server/helpers/notify.js Normal file
View File

@@ -0,0 +1,16 @@
const { Notification, shell } = require("electron");
const path = require("path");
function notifyDownloadFinished(folder) {
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", () => shell.openPath(folder));
notif.show();
}
module.exports = { notifyDownloadFinished };

13
server/helpers/path.js Normal file
View File

@@ -0,0 +1,13 @@
const path = require("path");
const fs = require("fs");
const { app } = require("electron");
const userYtDlp = path.join(app.getPath("userData"), "yt-dlp.exe");
const sourceYtDlp = path.join(process.resourcesPath, "yt-dlp.exe");
if (!fs.existsSync(userYtDlp)) fs.copyFileSync(sourceYtDlp, userYtDlp);
module.exports = {
userYtDlp,
sourceYtDlp
};

View File

@@ -0,0 +1,19 @@
const path = require("path");
function isValidUrl(url) {
try {
new URL(url);
return true;
} catch {
return false;
}
}
function isSafePath(folder) {
if (!folder || folder.length < 3) return false;
const unsafe = ["System32", "/etc", "\\Windows"];
const resolved = path.resolve(folder);
return !unsafe.some(u => resolved.includes(u));
}
module.exports = { isValidUrl, isSafePath };

View File

@@ -1,26 +1,9 @@
/*
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");
const config = require("../config")
// Dossier de logs Windows
const logDir = path.join(os.homedir(), "AppData", "Local", "FreedomLoader", "logs");
@@ -28,18 +11,11 @@ const logDir = path.join(os.homedir(), "AppData", "Local", "FreedomLoader", "log
// 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",
@@ -55,12 +31,11 @@ const logger = createLogger({
options: { flags: "a" },
}),
new transports.Console({
format: consoleFormat,
format: logFormat,
}),
],
});
// Helpers pour sessions
function getSessionStartLine() {
return `--- Démarrage de la session : ${new Date().toISOString()} ---`;
}
@@ -71,16 +46,16 @@ function getSessionEndLine() {
function logSessionStart() {
logger.info(getSessionStartLine());
logger.info(`Version de l'Application: ${config.version}`)
}
function logSessionEnd() {
logger.info(getSessionEndLine());
}
// Export
module.exports = {
logger,
logSessionStart,
logSessionEnd,
logDir,
};
};

View File

@@ -1,51 +1,16 @@
/*
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 { execFile } = require("child_process");
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");
const { logger } = require("../logger");
const config = require("../../config");
const { isValidUrl, isSafePath } = require("../helpers/validation");
const { buildYtDlpArgs } = require("../helpers/buildArgs");
const { notifyDownloadFinished } = require("../helpers/notify");
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
}
const { userYtDlp } = require("../helpers/path");
router.post("/", (req, res) => {
try {
@@ -53,116 +18,36 @@ router.post("/", (req, res) => {
url: req.body.url,
audioOnly: req.body.audioOnly === "1",
quality: req.body.quality || "best",
outputFolder: req.body.savePath || path.join(process.env.USERPROFILE, "Downloads", "Freedom Loader"),
};
if (!options.url) {
logger.warn("Requête POST /download sans URL");
return res.status(400).send("❌ URL manquante !");
}
if (!options.url || !isValidUrl(options.url)) return res.status(400).send("❌ URL invalide !");
if (!isValidUrl(options.url)) {
logger.warn(`URL invalide : ${options.url}`);
return res.status(400).send("❌ URL invalide !");
}
if (!isSafePath(options.outputFolder)) return res.status(400).send("❌ Chemin de sauvegarde non autorisé.");
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(" ")}`);
fs.mkdirSync(options.outputFolder, { recursive: true });
const args = buildYtDlpArgs(options);
logger.info(args)
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.on("error", err => {
logger.error(`Erreur yt-dlp : ${err.message}`);
res.status(500).send(`❌ Erreur yt-dlp : ${err.message}`);
});
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}`);
child.on("close", 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();
notifyDownloadFinished(options.outputFolder);
res.send("✅ Téléchargement terminé !");
} else {
res.status(500).send(`❌ yt-dlp a échoué avec le code : ${code}`);
}
} else res.status(500).send(`❌ yt-dlp a échoué avec le code : ${code}`);
});
if (config.debugMode == true) {
child.stdout.on("data", data => data.toString().split("\n").forEach(line => line.trim() && logger.info(`[yt-dlp stdout] ${line}`)));
child.stderr.on("data", data => data.toString().split("\n").forEach(line => line.trim() && logger.error(`[yt-dlp stderr] ${line}`)));
}
} catch (err) {
logger.error(`Erreur serveur dans /download : ${err.message}`);
res.status(500).send(`Erreur serveur : ${err.message}`);

View File

@@ -1,71 +1,42 @@
/*
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 { userYtDlp } = require("../helpers/path");
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}`);
}
// const ytDlpPath = path.join(__dirname, '../../ressources/yt-dlp.exe');
// const userYtDlp = path.join(process.env.APPDATA || process.env.USERPROFILE, 'FreedomLoader', 'yt-dlp.exe');
function isValidUrl(url) {
return typeof url === "string" && /^https?:\/\//.test(url);
try {
new URL(url);
return true;
} catch {
return false;
}
}
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");
}
const { url } = req.body;
if (!url || !isValidUrl(url)) 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) => {
execFile(userYtDlp, args, { timeout: 30_000, maxBuffer: 10 * 1024 * 1024 }, (error, stdout, stderr) => {
if (error) {
logger.error(`Erreur exécution yt-dlp: ${error.message}`);
logger.error(`Erreur yt-dlp: ${error.message}`);
if (stderr) logger.debug(`stderr: ${stderr}`);
return res.status(500).send("❌ Impossible de récupérer les infos.");
}
if (!stdout) return res.status(500).send("❌ Aucune donnée reçue.");
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,
@@ -74,22 +45,19 @@ router.post("/", (req, res) => {
videos: (data.entries || []).map(v => ({
id: v.id,
title: v.title,
webpage_url: v.webpage_url,
url: v.webpage_url,
duration: v.duration,
thumbnail: v.thumbnail,
uploader: v.uploader
}))
};
logger.info(`Playlist détectée : ${playlistPayload.title} (${playlistPayload.count} vidéos)`);
return res.json(playlistPayload);
}
// Vidéo unique
logger.info(`Vidéo unique récupérée : ${data.title}`);
res.json({
type: "video",
...data
});
res.json({ type: "video", ...data });
} catch (e) {
logger.error(`Erreur parsing JSON: ${e.message}`);

View File

@@ -1,90 +1,62 @@
/*
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 config = require("../config");
const { execFile } = require("child_process");
const { userYtDlp } = require("./helpers/path");
const app = express();
const PORT = config.applicationPort;
const PORT = 8787; // Port de l'app
// Dossier de téléchargement
const outputFolder = path.join(process.env.USERPROFILE, "Downloads", "Freedom Loader");
// 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.");
// Création du dossier si nécessaire
try {
fs.mkdirSync(outputFolder, { recursive: true });
logger.info(`Dossier Freedom Loader prêt dans ${outputFolder}`);
} catch (err) {
logger.error("Impossible de créer le dossier :", err);
process.exit(1);
}
app.locals.outputFolder = outputFolder;
// Mise à jour yt-dlp au démarrage
execFile(userYtDlp, ["-U"], (err, stdout, stderr) => {
if (err) logger.warn("Erreur update yt-dlp:", err);
else logger.info(`Update yt-dlp : ${stdout}`);
});
app.use(express.urlencoded({ extended: true })); // Middleware pour parser les POST en x-www-form-urlencoded
// Middlewares
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "../public")));
// Fichiers statiques (frontend)
const staticPath = path.join(__dirname, "../public");
debug("Serveur statique sur", staticPath);
app.use(express.static(staticPath));
// Routes
app.use("/download", require("./routes/download"));
app.use("/info", require("./routes/info"));
// 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
// Fonction pour démarrer le serveur
async function startServer() {
return new Promise((resolve, reject) => {
logSessionStart(); // Début de session
logSessionStart();
const serverInstance = app.listen(PORT, () => {
const server = app.listen(PORT, () => {
logger.info(`Serveur Express prêt sur http://localhost:${PORT}`);
resolve(serverInstance);
resolve(server);
});
// Gestion des erreurs serveur
serverInstance.on("error", (err) => {
server.on("error", (err) => {
logger.error("Erreur serveur Express :", err);
reject(err);
});
// Gestion propre de la fermeture du serveur
const gracefulExit = () => {
logSessionEnd();
serverInstance.close(() => {
server.close(() => {
logger.info("Serveur Express fermé proprement.");
process.exit();
});
@@ -95,12 +67,4 @@ async function startServer() {
});
}
// 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();
})();
module.exports = { startServer };