// Copyright (c) 2026 Gordon Bolton. MIT License. const axios = require('axios'); const { logToFile } = require('./logger'); const { getQbittorrentInstances } = require('./config'); class QBittorrentClient { constructor(instance) { this.id = instance.id; this.name = instance.name; this.url = instance.url; this.username = instance.username; this.password = instance.password; this.authCookie = null; // Sync API incremental state this.lastRid = 0; this.torrentMap = new Map(); this.fallbackThisCycle = false; } async login() { try { logToFile(`[qBittorrent:${this.name}] Attempting login...`); const response = await axios.post(`${this.url}/api/v2/auth/login`, `username=${encodeURIComponent(this.username)}&password=${encodeURIComponent(this.password)}`, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, maxRedirects: 0, validateStatus: (status) => status >= 200 && status < 400 } ); if (response.headers['set-cookie']) { this.authCookie = response.headers['set-cookie'][0]; logToFile(`[qBittorrent:${this.name}] Login successful`); return true; } logToFile(`[qBittorrent:${this.name}] Login failed - no cookie`); return false; } catch (error) { logToFile(`[qBittorrent:${this.name}] Login error: ${error.message}`); return false; } } async makeRequest(endpoint, config = {}) { const url = `${this.url}${endpoint}`; if (!this.authCookie) { const loggedIn = await this.login(); if (!loggedIn) { throw new Error(`Failed to authenticate with ${this.name}`); } } try { const response = await axios.get(url, { ...config, headers: { ...config.headers, 'Cookie': this.authCookie } }); return response; } catch (error) { // If unauthorized, try re-authenticating once if (error.response && error.response.status === 403) { logToFile(`[qBittorrent:${this.name}] Auth expired, re-authenticating...`); this.authCookie = null; const loggedIn = await this.login(); if (loggedIn) { return axios.get(url, { ...config, headers: { ...config.headers, 'Cookie': this.authCookie } }); } } throw error; } } /** * Fetches incremental torrent data using the qBittorrent Sync API. * * The Sync API uses a response ID (rid) to send only changed fields: * - First call uses rid=0 to get the full torrent list. * - Subsequent calls send the last received rid; qBittorrent returns * delta updates (changed fields only), new torrents, and removed hashes. * - If full_update is true, the server is sending a full refresh and * we rebuild our local map from scratch. * * @returns {Promise} Array of complete torrent objects. */ async getMainData() { const response = await this.makeRequest(`/api/v2/sync/maindata?rid=${this.lastRid}`); const data = response.data; if (data.full_update) { // Full refresh: rebuild the entire map this.torrentMap.clear(); if (data.torrents) { for (const [hash, props] of Object.entries(data.torrents)) { this.torrentMap.set(hash, { ...props, hash }); } } } else { // Delta update: merge changed fields into existing torrent objects if (data.torrents) { for (const [hash, delta] of Object.entries(data.torrents)) { const existing = this.torrentMap.get(hash) || { hash }; this.torrentMap.set(hash, { ...existing, ...delta }); } } } // Remove torrents that the server reports as deleted if (data.torrents_removed) { for (const hash of data.torrents_removed) { this.torrentMap.delete(hash); } } // Ensure every torrent has a computed 'completed' field for downstream consumers for (const torrent of this.torrentMap.values()) { if (torrent.completed === undefined && torrent.size !== undefined && torrent.progress !== undefined) { torrent.completed = Math.round(torrent.size * torrent.progress); } } this.lastRid = data.rid; return Array.from(this.torrentMap.values()); } /** * Legacy full-list fetch. Used as a fallback when the Sync API fails. */ async getTorrentsLegacy() { try { const response = await this.makeRequest('/api/v2/torrents/info'); logToFile(`[qBittorrent:${this.name}] Retrieved ${response.data.length} torrents (legacy)`); return response.data; } catch (error) { logToFile(`[qBittorrent:${this.name}] Error fetching torrents (legacy): ${error.message}`); throw error; } } /** * Returns the current list of torrents for this instance. * Uses the Sync API for incremental updates; falls back to torrents/info * at most once per polling cycle if the Sync API call fails. */ async getTorrents() { try { if (this.fallbackThisCycle) { logToFile(`[qBittorrent:${this.name}] Already fell back this cycle, using legacy`); const torrents = await this.getTorrentsLegacy(); return torrents.map(torrent => ({ ...torrent, instanceId: this.id, instanceName: this.name })); } const torrents = await this.getMainData(); logToFile(`[qBittorrent:${this.name}] Sync: ${torrents.length} torrents (rid=${this.lastRid})`); return torrents.map(torrent => ({ ...torrent, instanceId: this.id, instanceName: this.name })); } catch (error) { logToFile(`[qBittorrent:${this.name}] Sync failed, falling back to legacy: ${error.message}`); this.fallbackThisCycle = true; try { const torrents = await this.getTorrentsLegacy(); return torrents.map(torrent => ({ ...torrent, instanceId: this.id, instanceName: this.name })); } catch (fallbackError) { logToFile(`[qBittorrent:${this.name}] Fallback also failed: ${fallbackError.message}`); return []; } } } } // Persist clients so auth cookies survive between requests let persistedClients = null; function getClients() { if (persistedClients) return persistedClients; const instances = getQbittorrentInstances(); if (instances.length === 0) { logToFile('[qBittorrent] No instances configured'); return []; } logToFile(`[qBittorrent] Created ${instances.length} persistent client(s)`); persistedClients = instances.map(inst => new QBittorrentClient(inst)); return persistedClients; } async function getAllTorrents() { const clients = getClients(); if (clients.length === 0) { return []; } // Reset fallback flags at the start of each poll cycle so every cycle // gets one chance to use the Sync API before falling back. for (const client of clients) { client.fallbackThisCycle = false; } const results = await Promise.all( clients.map(client => client.getTorrents().catch(err => { logToFile(`[qBittorrent] Error from ${client.name}: ${err.message}`); return []; })) ); const allTorrents = results.flat(); logToFile(`[qBittorrent] Total torrents from all instances: ${allTorrents.length}`); return allTorrents; } function formatBytes(bytes) { if (bytes === 0) return '0 B'; const k = 1024; const sizes = ['B', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; } function formatSpeed(bytesPerSecond) { return formatBytes(bytesPerSecond) + '/s'; } function formatEta(seconds) { if (seconds < 0 || seconds === 8640000) return '∞'; // qBittorrent uses 8640000 for unknown const days = Math.floor(seconds / 86400); const hours = Math.floor((seconds % 86400) / 3600); const minutes = Math.floor((seconds % 3600) / 60); if (days > 0) return `${days}d ${hours}h ${minutes}m`; if (hours > 0) return `${hours}h ${minutes}m`; return `${minutes}m`; } function mapTorrentToDownload(torrent) { const totalSize = torrent.size; const downloadedSize = torrent.completed; const progress = torrent.progress * 100; // Map qBittorrent states to our status const stateMap = { 'downloading': 'Downloading', 'stalledDL': 'Downloading', 'metaDL': 'Downloading', 'forcedDL': 'Downloading', 'allocating': 'Downloading', 'uploading': 'Seeding', 'stalledUP': 'Seeding', 'forcedUP': 'Seeding', 'queuedUP': 'Queued', 'queuedDL': 'Queued', 'checkingUP': 'Checking', 'checkingDL': 'Checking', 'checkingResumeData': 'Checking', 'moving': 'Moving', 'pausedUP': 'Paused', 'pausedDL': 'Paused', 'stoppedUP': 'Stopped', 'stoppedDL': 'Stopped', 'error': 'Error', 'missingFiles': 'Error', 'unknown': 'Unknown' }; const status = stateMap[torrent.state] || torrent.state; return { type: 'torrent', title: torrent.name, instanceName: torrent.instanceName, status: status, progress: progress.toFixed(1), size: formatBytes(totalSize), rawSize: totalSize, rawDownloaded: downloadedSize, speed: formatSpeed(torrent.dlspeed), rawSpeed: torrent.dlspeed, eta: formatEta(torrent.eta), rawEta: torrent.eta, seeds: torrent.num_seeds, peers: torrent.num_leechs, availability: (torrent.availability * 100).toFixed(1), hash: torrent.hash, category: torrent.category, tags: torrent.tags, savePath: torrent.content_path || torrent.save_path || null, addedOn: torrent.added_on || null, qbittorrent: true }; } module.exports = { getTorrents: getAllTorrents, getClients, mapTorrentToDownload, formatBytes, formatSpeed, formatEta, QBittorrentClient };