diff --git a/src/main/services/donwloaders/downloader.ts b/src/main/services/donwloaders/downloader.ts index c13d4d01..b7c3df23 100644 --- a/src/main/services/donwloaders/downloader.ts +++ b/src/main/services/donwloaders/downloader.ts @@ -69,10 +69,22 @@ export class Downloader { }); } else { try { - const torrent = await RealDebridClient.addMagnet(repack.magnet); - if (torrent && torrent.id) { - await RealDebridClient.selectAllFiles(torrent.id); - const { links } = await RealDebridClient.getInfo(torrent.id); + // Lets try first to find the torrent on RealDebrid + const torrents = await RealDebridClient.getAllTorrents(); + const hash = RealDebridClient.extractSHA1FromMagnet(repack.magnet); + let torrent = torrents.find((t) => t.hash === hash); + + if (!torrent) { + // Torrent is missing, lets add it + const magnet = await RealDebridClient.addMagnet(repack.magnet); + if (magnet && magnet.id) { + await RealDebridClient.selectAllFiles(magnet.id); + torrent = await RealDebridClient.getInfo(magnet.id); + } + } + + if (torrent) { + const { links } = torrent; const { download } = await RealDebridClient.unrestrictLink(links[0]); this.lastHttpDownloader = new HTTPDownloader(); this.lastHttpDownloader.download( diff --git a/src/main/services/donwloaders/real-debrid.ts b/src/main/services/donwloaders/real-debrid.ts index c502d3ad..7f9ccb48 100644 --- a/src/main/services/donwloaders/real-debrid.ts +++ b/src/main/services/donwloaders/real-debrid.ts @@ -52,9 +52,23 @@ export class RealDebridClient { return response.json() as Promise; } + static async getAllTorrents() { + const response = await fetch(`${base}/torrents`, { + headers: { + Authorization: `Bearer ${await this.getApiToken()}`, + }, + }); + + return response.json() as Promise; + } + static getApiToken() { return userPreferencesRepository .findOne({ where: { id: 1 } }) .then((userPreferences) => userPreferences!.realDebridApiToken); } + + static extractSHA1FromMagnet(magnet: string) { + return magnet.match(/btih:([0-9a-fA-F]*)/)?.[1].toLowerCase(); + } }