feat: ajout des telechargments par episodes / saisons
This commit is contained in:
1 parent
215379eca4
commit
247694ab3e
12 files changed
+111
-31
No files matched your search
@@ -15,8 +15,10 @@ const router = Router()
|
||||
router.post('/download', requireAuth, async (req, res) => {
|
||||
const url = req.body.magnet ?? req.body.torrent_url
|
||||
if (!url) { res.status(400).json({ error: 'torrent_url ou magnet requis' }); return }
|
||||
logger.info('api', 'Téléchargement demandé')
|
||||
const results = await dispatchDownload(url)
|
||||
const file_index: number | null = req.body.file_index != null ? Number(req.body.file_index) : null
|
||||
const file_path: string | null = req.body.file_path ?? null
|
||||
logger.info('api', `Téléchargement demandé${file_index != null ? ` (fichier #${file_index})` : ''}`)
|
||||
const results = await dispatchDownload(url, { file_index, file_path })
|
||||
res.status(results.every((r: any) => r.ok) ? 200 : 207).json({ results })
|
||||
})
|
||||
|
||||
|
||||
@@ -88,7 +88,8 @@ router.get('/series/:id', requireAuth, async (req, res) => {
|
||||
}
|
||||
for (const ep of season.episodes ?? []) {
|
||||
for (const t of (ep.torrents ?? [])) {
|
||||
episodeTorrentMap[ep.id] = { torrent_url: t.torrent_url, magnet: t.magnet, type: 'episode', raw: t.title, manual: t.manual ?? false, fankai: t.fankai ?? true }
|
||||
const pathEntry = (ep.paths ?? []).find((p: any) => typeof p === 'object' && p.infohash?.toLowerCase() === t.infohash?.toLowerCase())
|
||||
episodeTorrentMap[ep.id] = { torrent_url: t.torrent_url, magnet: t.magnet, type: 'episode', raw: t.title, manual: t.manual ?? false, fankai: t.fankai ?? true, file_index: pathEntry?.file_index ?? null, file_path: pathEntry?.path ?? null }
|
||||
availableEpisodeIds.add(ep.id)
|
||||
const orgFiles = organized[t.infohash?.toLowerCase()] ?? {}
|
||||
const isOrg = orgFiles[String(ep.id)] !== undefined
|
||||
|
||||
@@ -50,11 +50,16 @@ export interface TorrentInfo {
|
||||
category : string
|
||||
}
|
||||
|
||||
export interface DownloadOptions {
|
||||
file_index?: number | null
|
||||
file_path?: string | null
|
||||
}
|
||||
|
||||
export interface TorrentClientDriver {
|
||||
definition : TorrentClientDefinition
|
||||
test : (config: Record<string, string | number>) => Promise<{ ok: boolean; message: string }>
|
||||
healthcheck : (config: Record<string, string | number>) => Promise<{ online: boolean; version?: string }>
|
||||
add : (config: Record<string, string | number>, url: string) => Promise<void>
|
||||
add : (config: Record<string, string | number>, url: string, options?: DownloadOptions) => Promise<void>
|
||||
list : (config: Record<string, string | number>, category?: string) => Promise<TorrentInfo[]>
|
||||
remove : (config: Record<string, string | number>, hash: string, deleteFiles?: boolean) => Promise<void>
|
||||
}
|
||||
@@ -208,7 +213,7 @@ function remapSavePath(savePath: string, remotePath: string, localPath: string):
|
||||
|
||||
// ─── Dispatch download ─────────────────────────────────────────────────────────
|
||||
|
||||
export async function dispatchDownload(url: string): Promise<{ uuid: string; name: string; ok: boolean; error?: string }[]> {
|
||||
export async function dispatchDownload(url: string, options?: DownloadOptions): Promise<{ uuid: string; name: string; ok: boolean; error?: string }[]> {
|
||||
const clients = loadClients()
|
||||
|
||||
if (clients.length === 0) {
|
||||
@@ -226,7 +231,7 @@ export async function dispatchDownload(url: string): Promise<{ uuid: string; nam
|
||||
continue
|
||||
}
|
||||
try {
|
||||
await driver.add(client.config, url)
|
||||
await driver.add(client.config, url, options)
|
||||
logger.info('torrent-clients', `Téléchargement envoyé à "${client.name}"`)
|
||||
results.push({ uuid: client.uuid, name: client.name, ok: true })
|
||||
} catch (err) {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* qBittorrent Driver
|
||||
*/
|
||||
|
||||
import type { TorrentClientDriver, TorrentInfo } from './index.js'
|
||||
import type { TorrentClientDriver, TorrentInfo, DownloadOptions } from './index.js'
|
||||
import { logger } from '../logger.js'
|
||||
|
||||
function mapState(state: string): TorrentInfo['state'] {
|
||||
@@ -34,6 +34,37 @@ async function qbLogin(config: Record<string, string | number>): Promise<string>
|
||||
return sid
|
||||
}
|
||||
|
||||
async function qbSetFilePriority(config: Record<string, string | number>, hash: string, fileIndex: number): Promise<void> {
|
||||
for (let attempt = 0; attempt < 15; attempt++) {
|
||||
await new Promise(r => setTimeout(r, 2000))
|
||||
try {
|
||||
const sid = await qbLogin(config)
|
||||
const res = await fetch(`${config.url}/api/v2/torrents/files?hash=${hash}`, {
|
||||
headers: { Cookie: `SID=${sid}` },
|
||||
})
|
||||
if (!res.ok) continue
|
||||
const files: any[] = await res.json()
|
||||
if (!Array.isArray(files) || files.length === 0) continue
|
||||
const unwanted = files.map((_, i) => i).filter(i => i !== fileIndex)
|
||||
if (unwanted.length > 0) {
|
||||
const form = new FormData()
|
||||
form.append('hash', hash)
|
||||
form.append('id', unwanted.join('|'))
|
||||
form.append('priority', '0')
|
||||
await fetch(`${config.url}/api/v2/torrents/filePrio`, { method: 'POST', body: form, headers: { Cookie: `SID=${sid}` } })
|
||||
}
|
||||
const form2 = new FormData()
|
||||
form2.append('hash', hash)
|
||||
form2.append('id', String(fileIndex))
|
||||
form2.append('priority', '1')
|
||||
await fetch(`${config.url}/api/v2/torrents/filePrio`, { method: 'POST', body: form2, headers: { Cookie: `SID=${sid}` } })
|
||||
logger.info('qbittorrent', `Priorité fichier ${fileIndex} définie pour ${hash.slice(0, 8)}…`)
|
||||
return
|
||||
} catch {}
|
||||
}
|
||||
throw new Error(`Timeout : métadonnées non disponibles pour ${hash.slice(0, 8)}…`)
|
||||
}
|
||||
|
||||
const QB: TorrentClientDriver = {
|
||||
definition: {
|
||||
id : 'qbittorrent',
|
||||
@@ -103,7 +134,7 @@ const QB: TorrentClientDriver = {
|
||||
} satisfies TorrentInfo))
|
||||
},
|
||||
|
||||
async add(config, url) {
|
||||
async add(config, url, options?: DownloadOptions) {
|
||||
const sid = await qbLogin(config)
|
||||
const form = new FormData()
|
||||
form.append('urls', url)
|
||||
@@ -117,6 +148,17 @@ const QB: TorrentClientDriver = {
|
||||
const text = await res.text()
|
||||
if (text !== 'Ok.') throw new Error(`Ajout échoué : ${text}`)
|
||||
logger.info('qbittorrent', `Torrent ajouté avec succès (catégorie: ${config.category ?? 'aucune'}${config.savePath ? `, dossier: ${config.savePath}` : ''})`)
|
||||
if (options?.file_index != null) {
|
||||
const hashMatch = url.match(/xt=urn:btih:([a-fA-F0-9]{40,})/i)
|
||||
const hash = hashMatch?.[1]?.toLowerCase() ?? null
|
||||
if (hash) {
|
||||
qbSetFilePriority(config, hash, options.file_index).catch(err =>
|
||||
logger.warn('qbittorrent', `Priorité fichier non appliquée : ${err instanceof Error ? err.message : err}`)
|
||||
)
|
||||
} else {
|
||||
logger.warn('qbittorrent', `file_index ignoré : hash non extractible depuis l'URL`)
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async remove(config, hash, deleteFiles = false) {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* Compatible ruTorrent (via /RPC2) et rTorrent standalone (via /RPC2 ou /XMLRPC).
|
||||
*/
|
||||
|
||||
import type { TorrentClientDriver, TorrentInfo } from './index.js'
|
||||
import type { TorrentClientDriver, TorrentInfo, DownloadOptions } from './index.js'
|
||||
import { logger } from '../logger.js'
|
||||
|
||||
// ─── XML-RPC helpers ──────────────────────────────────────────
|
||||
@@ -220,7 +220,7 @@ const RT: TorrentClientDriver = {
|
||||
})
|
||||
},
|
||||
|
||||
async add(config, url) {
|
||||
async add(config, url, options?: DownloadOptions) {
|
||||
// load_start charge et démarre le torrent
|
||||
const method = url.startsWith('magnet:') ? 'load.start' : 'load.start'
|
||||
const args: any[] = ['', url]
|
||||
@@ -234,6 +234,30 @@ const RT: TorrentClientDriver = {
|
||||
}
|
||||
|
||||
await rpcCall(config, method, args)
|
||||
if (options?.file_index != null) {
|
||||
// Wait for torrent metadata then set file priorities
|
||||
const hashMatch = url.match(/xt=urn:btih:([a-fA-F0-9]{40,})/i)
|
||||
const hash = hashMatch?.[1]?.toUpperCase() ?? null
|
||||
if (hash) {
|
||||
;(async () => {
|
||||
for (let attempt = 0; attempt < 15; attempt++) {
|
||||
await new Promise(r => setTimeout(r, 2000))
|
||||
try {
|
||||
const fileCount: number = await rpcCall(config, 'f.multicall', [hash, '', 'f.size_bytes='])
|
||||
.then((r: any) => Array.isArray(r) ? r.length : 0)
|
||||
if (fileCount === 0) continue
|
||||
for (let i = 0; i < fileCount; i++) {
|
||||
const priority = i === options.file_index ? 1 : 0
|
||||
await rpcCall(config, 'f.priority.set', [hash, i, priority])
|
||||
}
|
||||
logger.info('rtorrent', `Priorité fichier ${options.file_index} définie pour ${hash.slice(0, 8)}…`)
|
||||
return
|
||||
} catch {}
|
||||
}
|
||||
logger.warn('rtorrent', `Priorité fichier non appliquée : timeout pour ${hash.slice(0, 8)}…`)
|
||||
})()
|
||||
}
|
||||
}
|
||||
logger.info('rtorrent', `Torrent ajouté avec succès${config.savePath ? ` (dossier: ${config.savePath})` : ''}`)
|
||||
},
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Synology Download Station Driver
|
||||
*/
|
||||
|
||||
import type { TorrentClientDriver, TorrentInfo } from './index.js'
|
||||
import type { TorrentClientDriver, TorrentInfo, DownloadOptions } from './index.js'
|
||||
import { logger } from '../logger.js'
|
||||
|
||||
// Synology Download Station task status codes
|
||||
@@ -130,7 +130,8 @@ const DS: TorrentClientDriver = {
|
||||
})
|
||||
},
|
||||
|
||||
async add(config, url) {
|
||||
async add(config, url, options?: DownloadOptions) {
|
||||
if (options?.file_index != null) logger.warn('synology-ds', 'Sélection de fichier non supportée — téléchargement complet')
|
||||
const sid = await dsLogin(config)
|
||||
|
||||
const extra: Record<string, string> = { uri: url }
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Transmission Driver
|
||||
*/
|
||||
|
||||
import type { TorrentClientDriver, TorrentInfo } from './index.js'
|
||||
import type { TorrentClientDriver, TorrentInfo, DownloadOptions } from './index.js'
|
||||
import { logger } from '../logger.js'
|
||||
|
||||
function mapState(status: number): TorrentInfo['state'] {
|
||||
@@ -122,7 +122,7 @@ const TR: TorrentClientDriver = {
|
||||
} satisfies TorrentInfo))
|
||||
},
|
||||
|
||||
async add(config, url) {
|
||||
async add(config, url, options?: DownloadOptions) {
|
||||
const args: Record<string, unknown> = { filename: url }
|
||||
|
||||
if (config.savePath) {
|
||||
@@ -133,6 +133,10 @@ const TR: TorrentClientDriver = {
|
||||
args['labels'] = [String(config.category)]
|
||||
}
|
||||
|
||||
if (options?.file_index != null) {
|
||||
args['files-wanted'] = [options.file_index]
|
||||
}
|
||||
|
||||
await trRequest(config, 'torrent-add', args)
|
||||
logger.info('transmission', `Torrent ajouté avec succès (catégorie: ${config.category ?? 'aucune'}${config.savePath ? `, dossier: ${config.savePath}` : ''})`)
|
||||
},
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* uTorrent Driver
|
||||
*/
|
||||
|
||||
import type { TorrentClientDriver, TorrentInfo } from './index.js'
|
||||
import type { TorrentClientDriver, TorrentInfo, DownloadOptions } from './index.js'
|
||||
import { logger } from '../logger.js'
|
||||
|
||||
// uTorrent status flags (bitmask) :
|
||||
@@ -141,7 +141,8 @@ const UT: TorrentClientDriver = {
|
||||
})
|
||||
},
|
||||
|
||||
async add(config, url) {
|
||||
async add(config, url, options?: DownloadOptions) {
|
||||
if (options?.file_index != null) logger.warn('utorrent', 'Sélection de fichier non supportée — téléchargement complet')
|
||||
const session = await utGetSession(config)
|
||||
const auth = btoa(`${config.username ?? ''}:${config.password ?? ''}`)
|
||||
|
||||
|
||||
Reference in new issue
Block a user