Files
dupe/server/modules/state.js

62 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import fs from "fs";
import path from "path";
export function discoverSavedTorrents(downloadDir) {
if (!downloadDir || !fs.existsSync(downloadDir)) return [];
const entries = fs.readdirSync(downloadDir, { withFileTypes: true });
const folders = entries.filter((e) => e.isDirectory()).map((e) => e.name);
const candidates = [];
for (const name of folders) {
const savePath = path.join(downloadDir, name);
const infoPath = path.join(savePath, "info.json");
if (!fs.existsSync(infoPath)) continue;
try {
const info = JSON.parse(fs.readFileSync(infoPath, "utf-8"));
const magnetURI = info.magnetURI || info.magnet || null;
const infoHash = info.infoHash || null;
candidates.push({
folder: name,
savePath,
infoPath,
infoHash,
magnetURI,
added: info.added || fs.statSync(infoPath).mtimeMs,
name: info.name || name
});
} catch (err) {
console.warn(`⚠️ info.json okunamadı (${infoPath}): ${err.message}`);
}
}
return candidates;
}
export function restoreTorrentsFromDisk({ downloadDir, client, register }) {
const candidates = discoverSavedTorrents(downloadDir);
const restored = [];
for (const candidate of candidates) {
if (!candidate.magnetURI) {
console.warn(`⚠️ ${candidate.folder} için magnetURI yok, atlanıyor.`);
continue;
}
try {
const torrent = client.add(candidate.magnetURI, {
path: candidate.savePath,
announce: []
});
if (typeof register === "function") {
register(torrent, {
savePath: candidate.savePath,
added: candidate.added,
restored: true
});
}
restored.push({ infoHash: torrent.infoHash || candidate.infoHash, folder: candidate.folder });
} catch (err) {
console.warn(`⚠️ ${candidate.folder} yeniden eklenemedi: ${err.message}`);
}
}
return restored;
}