hydra/src/main/services/real-debrid.ts

105 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-05-12 15:29:12 +03:00
import { Game } from "@main/entity";
2024-05-28 16:01:28 +03:00
import axios, { AxiosInstance } from "axios";
import type {
RealDebridAddMagnet,
RealDebridTorrentInfo,
RealDebridUnrestrictLink,
2024-05-28 16:01:28 +03:00
RealDebridUser,
} from "@types";
const base = "https://api.real-debrid.com/rest/1.0";
export class RealDebridClient {
private static instance: AxiosInstance;
static async addMagnet(magnet: string) {
2024-05-13 01:43:00 +03:00
const searchParams = new URLSearchParams({ magnet });
const response = await this.instance.post<RealDebridAddMagnet>(
"/torrents/addMagnet",
searchParams.toString()
);
return response.data;
}
static async getInfo(id: string) {
const response = await this.instance.get<RealDebridTorrentInfo>(
`/torrents/info/${id}`
);
return response.data;
}
2024-05-28 16:01:28 +03:00
static async getUser() {
const response = await this.instance.get<RealDebridUser>(`/user`);
return response.data;
}
static async selectAllFiles(id: string) {
2024-05-13 01:43:00 +03:00
const searchParams = new URLSearchParams({ files: "all" });
await this.instance.post(
`/torrents/selectFiles/${id}`,
searchParams.toString()
);
}
static async unrestrictLink(link: string) {
2024-05-13 01:43:00 +03:00
const searchParams = new URLSearchParams({ link });
const response = await this.instance.post<RealDebridUnrestrictLink>(
"/unrestrict/link",
searchParams.toString()
);
return response.data;
}
static async getAllTorrentsFromUser() {
const response =
await this.instance.get<RealDebridTorrentInfo[]>("/torrents");
return response.data;
}
static extractSHA1FromMagnet(magnet: string) {
return magnet.match(/btih:([0-9a-fA-F]*)/)?.[1].toLowerCase();
}
static async getDownloadUrl(game: Game) {
const torrents = await RealDebridClient.getAllTorrentsFromUser();
const hash = RealDebridClient.extractSHA1FromMagnet(game!.repack.magnet);
let torrent = torrents.find((t) => t.hash === hash);
2024-05-28 16:01:28 +03:00
// User haven't downloaded this torrent yet
if (!torrent) {
const magnet = await RealDebridClient.addMagnet(game!.repack.magnet);
2024-05-28 16:01:28 +03:00
if (magnet) {
await RealDebridClient.selectAllFiles(magnet.id);
torrent = await RealDebridClient.getInfo(magnet.id);
2024-05-28 16:01:28 +03:00
const { links } = torrent;
const { download } = await RealDebridClient.unrestrictLink(links[0]);
2024-05-28 16:01:28 +03:00
if (!download) {
throw new Error("Torrent not cached on Real Debrid");
}
2024-05-28 16:01:28 +03:00
return download;
}
}
throw new Error();
}
2024-05-28 16:01:28 +03:00
static authorize(apiToken: string) {
this.instance = axios.create({
baseURL: base,
headers: {
Authorization: `Bearer ${apiToken}`,
},
});
}
}