62 lines
1.9 KiB
JavaScript
62 lines
1.9 KiB
JavaScript
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;
|
||
}
|