### Command-line Usage of qbit-race Tool Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Demonstrates various ways to execute the qbit-race command from command line, including setup with full paths after npm installation and manual testing with torrent hash. Supports different installation methods like direct system installation and n package manager. ```shell # /home/username/n/bin/qbit-race completed -i "%I" && /path/to/other-script.sh # Example with full path after npm global install: # Ubuntu/Debian: /usr/bin/qbit-race completed -i "%I" # With n: /home/username/n/bin/qbit-race completed -i "%I" # Test the hook manually: qbit-race completed -i "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2" ``` -------------------------------- ### Start Prometheus Metrics Exporter - Bash Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Starts an HTTP server exposing qBittorrent metrics in Prometheus format for monitoring. No inputs required; runs on configured IP and port. Outputs metrics endpoint; limitations include network access and Prometheus setup, often run with pm2 for persistence. ```bash # Start metrics server (runs on configured IP:port) qbit-race metrics # Default: http://127.0.0.1:9999/metrics # Use with pm2 for production pm2 start "qbit-race metrics" --name=qbit-race-exporter # Prometheus scrape config: # scrape_configs: # - job_name: 'qbit-race' # scrape_interval: 15s # static_configs: # - targets: ['127.0.0.1:9999'] ``` -------------------------------- ### Install PM2 Process Manager (Shell) Source: https://github.com/ckcr4lyf/qbit-race/blob/master/README.md Installs PM2 globally via npm for managing the metrics server. No inputs; sets up PM2 for process management. Requires npm; essential for running background servers but may conflict with existing installations. ```shell npm i -g pm2 ``` -------------------------------- ### Start Prometheus Metrics Server (Shell) Source: https://github.com/ckcr4lyf/qbit-race/blob/master/README.md Uses PM2 to start the qbit-race metrics exporter as a background process. Configures server based on config file; exposes metrics on specified IP and port. Requires PM2 and valid config; suitable for monitoring but demands accessible address for Prometheus. ```shell pm2 start "qbit-race metrics" --name=qbit-race-prom-exporter ``` -------------------------------- ### AutoDL‑irssi integration command examples (Bash) Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Provides command‑line arguments for AutoDL‑irssi filters to invoke qbit‑race with various categories, extra tags, and options. Includes a sample configuration file snippet for filter definition. No additional software beyond AutoDL‑irssi and qbit‑race binary is needed. ```bash # In AutoDL-irssi filter configuration: # Action: Run Program # Command: /home/username/n/bin/qbit-race # Arguments: add -p "$(TorrentPathName)" --category "autodl" # Advanced arguments with tags: # Arguments: add -p "$(TorrentPathName)" --category "race" --extra-tags "$(Tracker),$(Category1)" # Filter categories: # Arguments for TV shows: add -p "$(TorrentPathName)" --category "tv-shows" # Arguments for movies: add -p "$(TorrentPathName)" --category "movies" # Disable tracker tags for specific filter: # Arguments: add -p "$(TorrentPathName)" --no-tracker-tags # Configuration file (~/.autodl/autodl.cfg): # [options] # gui-server-port = 12345 # gui-server-password = mypassword # # [filter example_filter] # match-releases = *Ubuntu*,*Debian* # match-sites = tracker.example.com # upload-type = exec # upload-command = /home/username/n/bin/qbit-race # upload-args = add -p "$(TorrentPathName)" --category "linux-isos" --extra-tags "$(Tracker)" ``` -------------------------------- ### Start Prometheus Metrics HTTP Server Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Launch HTTP server to expose qBittorrent metrics in Prometheus format. Connects to qBittorrent API and serves metrics on configured IP and port. Default endpoint: http://127.0.0.1:9999/metrics. Requires qBittorrent credentials and Prometheus settings configuration. ```typescript import { startMetricsServer } from './server/appFactory.js'; import { loginV2 } from './qbittorrent/auth.js'; import { loadConfig } from './utils/configV2.js'; const config = loadConfig(); const api = await loginV2(config.QBITTORRENT_SETTINGS); // Start metrics server on configured IP and port startMetricsServer(config, api); // Server starts on http://{PROMETHEUS_SETTINGS.ip}:{PROMETHEUS_SETTINGS.port} // Default: http://127.0.0.1:9999 // Access metrics endpoint // GET http://127.0.0.1:9999/metrics // Returns Prometheus-formatted metrics: // qbit_dl_bytes 123456789 // qbit_dl_rate_bytes 1234567 // qbit_ul_bytes 987654321 // qbit_ul_rate_bytes 987654 // up 1 // qbit_torrents_state{state="downloading"} 2 // qbit_torrents_state{state="uploading"} 15 ``` -------------------------------- ### Manage Torrent Tags (TypeScript) Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Demonstrates how to add and manage tags for organizing torrents. Includes examples of adding tags to individual and multiple torrents, and dynamically adding tracker hostnames as tags. ```typescript // Add single tag to single torrent await api.addTags([ { hash: 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2' } ], ['linux']); // Add multiple tags to single torrent await api.addTags([ { hash: 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2' } ], ['linux', 'iso', 'ubuntu']); // Add tags to multiple torrents const torrents = await api.getTorrents(); const linuxTorrents = torrents.filter(t => t.name.toLowerCase().includes('linux')); await api.addTags(linuxTorrents, ['linux-distro']); // Add tracker hostname as tag const trackers = await api.getTrackers('a1b2c3d4e5f6...'); const workingTracker = trackers.find(t => t.status === 2); if (workingTracker) { const hostname = new URL(workingTracker.url).hostname; await api.addTags([{ hash: 'a1b2c3d4e5f6...' }], [hostname]); } ``` -------------------------------- ### Get Path to Post-Race Script (Shell) Source: https://github.com/ckcr4lyf/qbit-race/blob/master/README.md Navigates to the script directory and outputs the full path to the post-race script. No inputs required; outputs a file path for qBittorrent configuration. Assumes script exists in ~/scripts/qbit-race/bin; limited to local filesystem. ```shell cd ~/scripts/qbit-race/bin echo "$(pwd)/post_race.mjs" ``` -------------------------------- ### GET /api/v2/torrents/info Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Retrieves detailed information about torrents, either all torrents or specific ones by hash. Used for getting torrent properties like state, category, ratio, and tags to enable filtering and conditional operations. Supports querying for single or multiple torrents. ```APIDOC ## GET /api/v2/torrents/info ### Description Fetches information about torrents, including state, category, ratio, and tags for monitoring and automation. ### Method GET ### Endpoint /api/v2/torrents/info ### Parameters #### Query Parameters - **hashes** (string) - Optional - Single hash or comma-separated for specific torrents. ### Request Example N/A (GET request) ### Response #### Success Response (200) Array of torrent objects. - **hash** (string) - Torrent hash. - **category** (string) - Current category. - **state** (string/enum) - Torrent state (e.g., "uploading", "pausedUP"). - **ratio** (number) - Share ratio. - **tags** (string) - Comma-separated tags. #### Response Example ```json [ { "hash": "a1b2c3d4e5f6a1b2c3d4e5f6...", "category": "race", "state": "uploading", "ratio": 2.0, "tags": "tag1" } ] ``` ``` -------------------------------- ### Configure Prometheus to scrape qbit-race metrics Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Defines a Prometheus scrape configuration for both local and remote qbit-race instances. Includes global scrape intervals and example PromQL queries for download, upload, and torrent state metrics. No external dependencies beyond Prometheus itself. ```yaml # prometheus.yml global: scrape_interval: 15s evaluation_interval: 15s scrape_configs: - job_name: 'qbit-race' scrape_interval: 30s static_configs: - targets: ['127.0.0.1:9999'] labels: instance: 'seedbox-1' environment: 'production' # If running on remote server - job_name: 'qbit-race-remote' static_configs: - targets: ['192.168.1.100:9999'] labels: instance: 'dedicated-server' # Example PromQL queries: # Rate of download: rate(qbit_dl_bytes[5m]) # Rate of upload_ul_bytes[5m]) # Total downloading torrents: qbit_torrents_state{state="downloading"} # Total seeding torrents: qbit_torrents_state{state="uploading"} ``` -------------------------------- ### Retrieve Torrent Information (TypeScript) Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Illustrates how to retrieve torrent information from qBittorrent using the API client. Includes examples of retrieving all torrents, specific torrents by infohash, and filtering torrents by state and ratio. ```typescript import { TorrentState } from './qbittorrent/api.js'; // Get all torrents const allTorrents = await api.getTorrents(); console.log(`Total torrents: ${allTorrents.length}`); // Get specific torrents by infohash const specificTorrents = await api.getTorrents([ 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2', 'f6e5d4c3b2a1f6e5d4c3b2a1f6e5d4c3b2a1f6e5' ]); // Get single torrent (throws error if not found) const torrent = await api.getTorrent('a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2'); console.log(`Name: ${torrent.name}`); console.log(`Ratio: ${torrent.ratio.toFixed(2)}`); console.log(`State: ${torrent.state}`); console.log(`Category: ${torrent.category}`); console.log(`Size: ${torrent.size} bytes`); console.log(`Tags: ${torrent.tags}`); // Filter torrents by state const downloading = allTorrents.filter(t => t.state === TorrentState.downloading); const seeding = allTorrents.filter(t => t.state === TorrentState.uploading); console.log(`Downloading: ${downloading.length}, Seeding: ${seeding.length}`); // Filter by ratio const highRatio = allTorrents.filter(t => t.ratio >= 2.0); console.log(`Torrents with ratio >= 2.0: ${highRatio.length}`); ``` -------------------------------- ### Configure qbit-race logger instances (TypeScript) Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Shows how to create logger objects with `getLoggerV3`, directing output to a default file, console‑only, or a custom log path. Includes examples of logging debug messages with additional metadata during API interactions. No external logging libraries required beyond the project's internal logger module. ```typescript import { getLoggerV3 } from './utils/logger.js'; // Default logger (writes to ~/.config/qbit-race/logs.txt) const logger = getLoggerV3(); logger.debug('Application started'); logger.debug('Config loaded', { concurrent_races: 2 }); // Logger without file output (console only) const consoleLogger = getLoggerV3({ skipFile true }); consoleLogger.debug('This only appears in console'); // Custom log file const customLogger = getLoggerV3({ logfile: '/var/log/qbit-race-custom.log' }); customLogger.debug('Writing to custom log file'); // Use in API calls logger.debug('Authenticating with qBittorrent'); const api = await loginV2(config.QBITTORRENT_SETTINGS); logger.debug('Authentication successful'); logger.debug('Adding torrent', { name: torrentName, hash: infohash }); await api.addTorrent(torrentData); logger.debug('Torrent added successfully'); ``` -------------------------------- ### GET /api/v2/transfer/info Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Fetches global transfer statistics including current speeds and session totals for downloads and uploads. This endpoint is used for monitoring performance and calculating session ratios. No parameters are required. ```APIDOC ## GET /api/v2/transfer/info ### Description Retrieves global transfer statistics for download and upload rates and totals. ### Method GET ### Endpoint /api/v2/transfer/info ### Parameters No parameters. ### Request Example N/A (GET request) ### Response #### Success Response (200) Transfer info object. - **dl_info_speed** (integer) - Current download speed in bytes/s. - **dl_info_data** (integer) - Total downloaded in session. - **up_info_speed** (integer) - Current upload speed in bytes/s. - **up_info_data** (integer) - Total uploaded in session. #### Response Example ```json { "dl_info_speed": 123456, "dl_info_data": 987654321, "up_info_speed": 789012, "up_info_data": 456789123 } ``` ``` -------------------------------- ### GET /api/v2/torrents/trackers Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Retrieves the list of trackers associated with a specific torrent by hash. Used to check tracker status for identifying non-functional torrents. The response includes status codes for each tracker. ```APIDOC ## GET /api/v2/torrents/trackers ### Description Gets trackers for a torrent to evaluate their working status. ### Method GET ### Endpoint /api/v2/torrents/trackers ### Parameters #### Query Parameters - **hash** (string) - Required - The torrent hash. ### Request Example N/A (GET request with query) ### Response #### Success Response (200) Array of tracker objects. - **status** (integer) - Tracker status (2 indicates working). - **url** (string) - Tracker URL. #### Response Example ```json [ { "status": 2, "url": "http://tracker.example.com/announce" } ] ``` ``` -------------------------------- ### Tag Errored Torrents (Shell) Source: https://github.com/ckcr4lyf/qbit-race/blob/master/README.md Runs an npm script to tag torrents with no working trackers as 'error'. No direct inputs; modifies torrents in qBittorrent. Depends on npm and project setup; useful for error sorting but may require manual re-run. ```shell npm run tag_unreg ``` -------------------------------- ### Validate Discord Webhook in Shell Source: https://github.com/ckcr4lyf/qbit-race/blob/master/README.md Command to validate the Discord webhook configuration in qbit-race. Requires qbit-race to be installed and webhook URL set in config. Sends a test notification to check if Discord integration works. ```bash qbit-race validate ``` -------------------------------- ### Async sleep utility for TypeScript Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Demonstrates the `sleep` helper to pause execution asynchronously, useful for rate‑limited loops or retry logic. Includes an example reannounce loop that waits between tracker requests and skips sleep in CI environments. Requires the utilities module providing `sleep`. ```typescript import { sleep } from './helpers/utilities.js'; console.log('Starting...'); await sleep(2000); // Wait 2 seconds console.log('2 seconds later'); // Use in reannounce loop const REANNOUNCE_INTERVAL = 5000; for (let i = 0; i < 30; i++) { await api.reannounce(infohash); console.log(`Reannounce attempt ${i + 1}`); const trackers = await api.getTrackers(infohash); const working = trackers.some(t => t.status === 2); if (working) { console.log('Tracker responded!'); break; } await sleep(REANNOUNCE_INTERVAL); } // Note: Automatically skipped in CI environments ``` -------------------------------- ### Add Torrent without Tracker Tags (Shell) Source: https://github.com/ckcr4lyf/qbit-race/blob/master/README.md This command adds a torrent to qBittorrent without tagging it with tracker hostnames, useful for cleaner organization in modern versions. It requires qbit-race installed and a valid torrent path as input; output is the torrent added to qBittorrent with specified options. Limitations include dependency on qbit-race and proper path formatting. ```shell qbit-race add -p "$(TorrentPathName)" --no-tracker-tags ``` -------------------------------- ### Configure qBittorrent Post-Race Script (Shell) Source: https://github.com/ckcr4lyf/qbit-race/blob/master/README.md Shows the command to execute post-race script in qBittorrent settings. Takes arguments like info hash, name, and trackers; resumes torrents and sends notifications. Requires qBittorrent and correct script path; output varies by torrent completion. ```shell /home/username/scripts/qbit-race/bin/post_race.js "%I" "%N" "%T" ``` -------------------------------- ### Complete Torrent Racing Workflow Implementation Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Full end-to-end TypeScript implementation showing how to set up configuration, authenticate with qBittorrent, add torrents for racing, monitor progress, and handle completion events. Includes settings for concurrent races, Discord notifications, and category management. ```typescript import { loginV2 } from './qbittorrent/auth.js'; import { loadConfig, makeConfigIfNotExist } from './utils/configV2.js'; import { addTorrentToRace } from './racing/add.js'; import { postRaceResumeV2 } from './racing/completed.js'; import { getTorrentMetainfo } from './helpers/torrent.js'; import { readFileSync } from 'fs'; // 1. Setup configuration makeConfigIfNotExist(); const config = loadConfig(); // 2. Customize racing settings config.CONCURRENT_RACES = 2; config.PAUSE_RATIO = 1.5; config.PAUSE_SKIP_TAGS = ['permaseeding', 'long-term']; config.REANNOUNCE_INTERVAL = 3000; // 3 seconds config.REANNOUNCE_LIMIT = 40; // 3. Configure Discord notifications config.DISCORD_NOTIFICATIONS.enabled = true; config.DISCORD_NOTIFICATIONS.webhook = 'https://discord.com/api/webhooks/...'; // 4. Configure category changes config.CATEGORY_FINISH_CHANGE = { 'racing': 'completed', 'download': 'seeding' }; // 5. Authenticate with qBittorrent const api = await loginV2(config.QBITTORRENT_SETTINGS); // 6. Parse and add torrent const torrentPath = '/home/user/torrents/ubuntu-22.04.torrent'; const torrentData = readFileSync(torrentPath); const metadata = getTorrentMetainfo(torrentData); console.log(`Racing: ${metadata.name}`); console.log(`Tracker: ${metadata.tracker}`); console.log(`Hash: ${metadata.hash}`); // 7. Add torrent and start racing await addTorrentToRace( api, config, torrentPath, { trackerTags: true, extraTags: 'priority' }, 'racing' ); console.log('Torrent added and racing started'); // 8. Monitor torrent progress const checkProgress = async () => { const torrent = await api.getTorrent(metadata.hash); console.log(`Progress: ${(torrent.progress * 100).toFixed(2)}%`); console.log(`Download: ${humanFileSize(torrent.downloaded, false, 2)}`); console.log(`Upload: ${humanFileSize(torrent.uploaded, false, 2)}`); console.log(`Ratio: ${torrent.ratio.toFixed(2)}`); }; // 9. When torrent completes (called by qBittorrent hook) // await postRaceResumeV2(api, config, metadata.hash); // 10. Query all racing torrents const allTorrents = await api.getTorrents(); const racing = allTorrents.filter(t => t.category === 'racing'); console.log(`Active races: ${racing.length}`); ``` -------------------------------- ### Load Configuration with TypeScript Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Demonstrates loading configuration files using the `loadConfig`, `makeConfigIfNotExist`, and `getFilePathInConfigDir` functions. This snippet also shows how to access configuration values, modify settings at runtime, and check for enabled features. ```typescript import { loadConfig, makeConfigIfNotExist, getFilePathInConfigDir } from './utils/configV2.js'; // Initialize config file if it doesn't exist makeConfigIfNotExist(); // Load configuration from disk const config = loadConfig(); console.log(`Reannounce interval: ${config.REANNOUNCE_INTERVAL}ms`); console.log(`Concurrent races: ${config.CONCURRENT_RACES}`); // Get path to custom file in config directory const customLogPath = getFilePathInConfigDir('custom-logs.txt'); // Returns: /home/username/.config/qbit-race/custom-logs.txt // Modify settings at runtime config.CONCURRENT_RACES = 2; config.PAUSE_RATIO = 1.5; // Example: Check if Discord is enabled if (config.DISCORD_NOTIFICATIONS.enabled) { console.log('Discord notifications are active'); } ``` -------------------------------- ### Systemd Service Configuration for Metrics Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Complete systemd service file configuration to run qbit-race metrics exporter as a background service. Includes service unit settings, user configuration, working directory, restart policies, and management commands for deployment and monitoring. ```ini # /etc/systemd/system/qbit-race-metrics.service [Unit] Description=qbit-race Prometheus Metrics Exporter After=network.target [Service] Type=simple User=seedbox WorkingDirectory=/home/seedbox ExecStart=/home/seedbox/n/bin/qbit-race metrics Restart=always RestartSec=10 StandardOutput=journal StandardError=journal [Install] WantedBy=multi-user.target # Commands: # sudo systemctl daemon-reload # sudo systemctl enable qbit-race-metrics # sudo systemctl start qbit-race-metrics # sudo systemctl status qbit-race-metrics # journalctl -u qbit-race-metrics -f ``` -------------------------------- ### qbit-race Configuration Structure - JSON Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Defines the complete configuration structure with all available options and their defaults for qbit-race. Configures settings like reannounce intervals, pausing logic, qBittorrent credentials, Discord notifications, and Prometheus exporter. No direct inputs/outputs; limitations include valid JSON syntax and correct key names. ```json { "REANNOUNCE_INTERVAL": 5000, "REANNOUNCE_LIMIT": 30, "PAUSE_RATIO": 1.0, "PAUSE_SKIP_TAGS": ["permaseeding", "long-term"], "PAUSE_SKIP_CATEGORIES": ["perma", "archived"], "CONCURRENT_RACES": 1, "COUNT_STALLED_DOWNLOADS": false, "SKIP_RESUME": false, "QBITTORRENT_SETTINGS": { "url": "http://localhost:8080", "username": "admin", "password": "adminadmin" }, "DISCORD_NOTIFICATIONS": { "enabled": true, "webhook": "https://discord.com/api/webhooks/123456789/abcdefg", "botUsername": "qBittorrent Racer", "botAvatar": "https://i.imgur.com/example.png" }, "PROMETHEUS_SETTINGS": { "ip": "127.0.0.1", "port": 9999 }, "CATEGORY_FINISH_CHANGE": { "downloading": "seeding", "race": "completed" } } ``` -------------------------------- ### Authenticate with qBittorrent API (TypeScript) Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Shows how to authenticate with the qBittorrent WebUI and obtain an API client instance using the `loginV2` function. It demonstrates both default and custom authentication settings. The API automatically handles version differences (v4/v5). ```typescript import { loginV2 } from './qbittorrent/auth.js'; import { loadConfig } from './utils/configV2.js'; const config = loadConfig(); // Authenticate with qBittorrent const api = await loginV2(config.QBITTORRENT_SETTINGS); // The API instance automatically detects qBittorrent version (v4/v5) // and handles API differences transparently // Example with custom settings const customApi = await loginV2({ url: 'http://192.168.1.100:8080', username: 'admin', password: 'mypassword' }); ``` -------------------------------- ### qBittorrent post‑completion hook script (Bash) Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Shows the command to set in qBittorrent's "Run external program on torrent completion" field, invoking qbit‑race with the completed torrent's infohash. Uses the `%I` placeholder provided by qBittorrent. Suitable for Linux environments where the qbit‑race binary is accessible. ```bash # qBittorrent Settings > Downloads > "Run external program on torrent completion" # Enter: /home/username/n/bin/qbit-race completed -i "%I" # Where %I is the infohash placeholder # Multiple commands (not recommended, use completed command instead): ``` -------------------------------- ### Add Torrent with Extra Tags (Shell) Source: https://github.com/ckcr4lyf/qbit-race/blob/master/README.md This command adds a torrent with additional comma-separated tags for better categorization. Requires qbit-race and torrent path; output includes the torrent with applied tags. Limited by tag parsing and qBittorrent tag support. ```shell qbit-race add -p "$(TorrentPathName)" --extra-tags "linux,foss" ``` -------------------------------- ### Manage Tracker Information (TypeScript) Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Demonstrates how to retrieve and manage tracker information for torrents, including filtering working trackers and reannouncing to trackers. ```typescript // Get all trackers for a torrent const trackers = await api.getTrackers('a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2'); // Filter working trackers (status = 2) const workingTrackers = trackers.filter(t => t.status === 2); console.log('Working trackers:'); workingTrackers.forEach(tracker => { console.log(` - ${tracker.url}`); }); // Check if torrent has any working trackers const hasWorkingTracker = trackers.some(t => t.status === 2); if (!hasWorkingTracker) { console.log('Warning: No working trackers!'); } // Reannounce to tracker await api.reannounce('a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2'); console.log('Reannounce sent to tracker') ``` -------------------------------- ### Add Torrent with qbit-race in Shell Source: https://github.com/ckcr4lyf/qbit-race/blob/master/README.md Shell command to run qbit-race in AutoDL action for adding torrents. It requires the path to qbit-race executable and the torrent path variable provided by AutoDL. Takes the torrent path as input parameter and adds the torrent to qBittorrent. ```bash /home/username/n/bin/qbit-race add -p "$(TorrentPathName)" ``` -------------------------------- ### Add Torrents to qBittorrent (TypeScript) Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Shows how to add new torrent files to qBittorrent with or without category assignment. It reads torrent data from a file and demonstrates how categories can be created if they don't already exist. ```typescript import { readFileSync } from 'fs'; // Read torrent file const torrentData = readFileSync('/path/to/ubuntu-22.04.torrent'); // Add torrent without category await api.addTorrent(torrentData); // Add torrent with category await api.addTorrent(torrentData, 'linux-isos'); // Add with category (creates category if doesn't exist) await api.addTorrent(torrentData, 'new-category'); console.log('Torrent added successfully') ``` -------------------------------- ### Add New Torrent for Racing - Bash Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Adds a new torrent file to qBittorrent, initiating racing workflow including pausing lower-priority torrents, reannouncing to trackers, and notifications. Requires a valid torrent file path as input; optional parameters include category and extra tags. Outputs addition confirmation or errors; limitations include valid file paths and permissions. ```bash # Basic torrent addition qbit-race add -p "/path/to/ubuntu-22.04.torrent" # Add with category for organization qbit-race add -p "/path/to/archlinux-2024.iso.torrent" --category "linux-isos" # Add with extra tags and disable automatic tracker tagging qbit-race add -p "/path/to/debian.torrent" \ --extra-tags "debian,stable" \ --no-tracker-tags # AutoDL-irssi integration example # In AutoDL filter, set Arguments to: add -p "$(TorrentPathName)" --category "race" --extra-tags "autodl" ``` -------------------------------- ### Retrieving Transfer Metrics in TypeScript Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt This code fetches and displays download/upload speeds and session totals from qBittorrent, with optional human-readable formatting via utilities. Inputs are none beyond API access; outputs include console logs of rates and ratios. Limitations: raw bytes require conversion for readability, and assumes utility import for formatting. ```typescript // Get current transfer information const transferInfo = await api.getTransferInfo(); console.log('Download stats:'); console.log(` Current speed: ${transferInfo.dl_info_speed} bytes/s`); console.log(` Session total: ${transferInfo.dl_info_data} bytes`); console.log('Upload stats:'); console.log(` Current speed: ${transferInfo.up_info_speed} bytes/s`); console.log(` Session total: ${transferInfo.up_info_data} bytes`); // Convert to human-readable format import { humanFileSize } from './helpers/utilities.js'; console.log(`Download rate: ${humanFileSize(transferInfo.dl_info_speed, false, 2)}/s`); console.log(`Upload rate: ${humanFileSize(transferInfo.up_info_speed, false, 2)}/s`); // Calculate session ratio const sessionRatio = transferInfo.up_info_data / transferInfo.dl_info_data; console.log(`Session ratio: ${sessionRatio.toFixed(2)}`); ``` -------------------------------- ### Add New Torrent for Racing (TypeScript) Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Adds a new torrent to qBittorrent with racing logic. Handles configuration loading, authentication, and provides options for tracker tags and categories. Includes comprehensive error handling and notification system. ```typescript import { addTorrentToRace } from './racing/add.js'; import { loginV2 } from './qbittorrent/auth.js'; import { loadConfig } from './utils/configV2.js'; const config = loadConfig(); const api = await loginV2(config.QBITTORRENT_SETTINGS); // Basic add await addTorrentToRace( api, config, '/path/to/ubuntu-22.04.torrent', { trackerTags: true, extraTags: undefined } ); // Add with category await addTorrentToRace( api, config, '/path/to/archlinux.torrent', { trackerTags: true, extraTags: undefined }, 'linux-isos' ); // Add with extra tags and no tracker tags await addTorrentToRace( api, config, '/path/to/debian.torrent', { trackerTags: false, extraTags: 'debian,priority' } ); ``` -------------------------------- ### Race Existing Torrent - Bash Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Applies racing logic to an existing torrent by pausing others, reannouncing to trackers, and managing concurrent limits. Requires torrent infohash as input; optional extra tags and no-tracker-tags flag. Outputs racing initiation status; limitations include valid infohash and available trackers. ```bash # Race an existing torrent by infohash qbit-race race -i "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2" # Race with extra tags qbit-race race -i "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2" \ --extra-tags "priority,linux" # Race without automatic tracker tags qbit-race race -i "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2" \ --no-tracker-tags ``` -------------------------------- ### Race Existing Torrent (TypeScript) Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Applies racing logic to existing torrents in qBittorrent. Includes options for custom tags and handles concurrent race limits, torrent pausing, and reannouncing. Provides notifications for race status. ```typescript import { raceExisting } from './racing/common.js'; const infohash = 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2'; // Basic race await raceExisting(api, config, infohash, { trackerTags: true, extraTags: undefined }); // Race with custom tags await raceExisting(api, config, infohash, { trackerTags: false, extraTags: 'priority,manual-race' }); ``` -------------------------------- ### Human‑readable file size conversion (TypeScript) Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Shows usage of thehumanFileSize` helper to convert byte counts into SI or binary units with configurable decimal precision. Demonstrates binary (1024‑based) and SI (1000‑based) outputs, as well as custom decimal places. Intended for displaying torrent sizes in a UI. ```typescript import { humanFileSize } from './helpers/utilities.js'; // Binary units (1024-based) console.log(humanFileSize(1024, false, 2)); // "1.00 KiB" console.log(humanFileSize(2621440, false, 2)); // "2.50 MiB" console.log(humanFileSize(3667148308, false, 2)); // "3.41 GiB" console.log(humanFileSize(1099511627776, false, 2)); // "1.00 TiB" // SI units (1000-based) console.log(humanFileSize(1000, true, 2)); // "1.00 kB" console.log(humanFileSize(2500000, true, 2)); // "2.50 MB" console.log(humanFileSize(3500000000, true, 2)); // "3.50 GB" // Custom decimal places console.log(humanFileSize(1536, false, 0)); // "2 KiB" console.log(humanFileSize(1536, false, 1)); // "1.5 KiB" console.log(humanFileSize(1536, false, 3)); // "1.500 KiB" // Use in torrent display const torrents = await api.getTorrents(); torrents.forEach(t => { console.log(`${t.name}: ${humanFileSize(t.size, false, 2)}`); }); ``` -------------------------------- ### Managing Torrent Categories in TypeScript Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt This snippet demonstrates setting, changing, and bulk-updating torrent categories for organization and automation. It relies on the qBittorrent API client and a config object for completion rules; inputs are torrent hashes and category strings, outputs are updated torrent states with logs. Limitations include requiring valid hashes and API connectivity; automated changes only apply to configured categories. ```typescript // Set torrent category await api.setCategory('a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2', 'completed'); // Change category on completion (automated) const completedTorrent = await api.getTorrent('a1b2c3d4e5f6...'); if (completedTorrent.state === TorrentState.uploading) { // Category exists in CATEGORY_FINISH_CHANGE config if (config.CATEGORY_FINISH_CHANGE[completedTorrent.category]) { const newCategory = config.CATEGORY_FINISH_CHANGE[completedTorrent.category]; await api.setCategory(completedTorrent.hash, newCategory); console.log(`Changed category from ${completedTorrent.category} to ${newCategory}`); } } // Bulk category change const torrents = await api.getTorrents(); const raceTorrents = torrents.filter(t => t.category === 'race' && t.state === TorrentState.uploading); for (const torrent of raceTorrents) { await api.setCategory(torrent.hash, 'seeding'); } ``` -------------------------------- ### Handle Torrent Completion - Bash Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Performs post-race cleanup upon torrent completion, including category changes, notifications, and resuming paused torrents. Requires torrent infohash as input. Outputs completion handling status; integrates with qBittorrent's external program trigger; limitations include correct infohash and configured categories. ```bash # Handle torrent completion qbit-race completed -i "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2" # qBittorrent integration # In qBittorrent Settings > Downloads > "Run external program on torrent completion": # /path/to/qbit-race completed -i "%I" ``` -------------------------------- ### Monitor PM2 Processes (Shell) Source: https://github.com/ckcr4lyf/qbit-race/blob/master/README.md Opens PM2 monitor to view running processes like the metrics server. No inputs; provides real-time status. Depends on PM2; useful for troubleshooting but requires terminal access. ```shell pm2 monit ``` -------------------------------- ### Post-Race Completion Handler (TypeScript) Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Handles torrent completion events with configurable category changes and torrent resumption. Includes notification system and checks for active downloads before resuming paused torrents. ```typescript import { postRaceResumeV2 } from './racing/completed.js'; const completedHash = 'a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2'; // Handle completion await postRaceResumeV2(api, config, completedHash); // Example: Configure category changes config.CATEGORY_FINISH_CHANGE = { 'racing': 'completed', 'download-hdd': 'seed-archive', 'download-ssd': 'seed-ssd' }; ``` -------------------------------- ### Validate qBittorrent Connection - Bash Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Tests the connection to qBittorrent and sends a test Discord notification if enabled. Depends on qBittorrent being accessible and credentials configured. Outputs connection status and any issues; limited by network availability and correct webhook URLs. ```bash # Validate qBittorrent connection and Discord webhook qbit-race validate # This will: # 1. Attempt to authenticate with qBittorrent # 2. Send a test Discord notification (if enabled) # 3. Report any connection issues ``` -------------------------------- ### Tag Torrents with Tracker Errors - Bash Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Identifies and tags torrents with no working trackers for easy filtering and management. Takes no input but checks all torrents; outputs tagged torrent list or dry-run preview. Limitations include dependency on qBittorrent API and current torrent statuses. ```bash # Tag all torrents with tracker errors qbit-race tag-error # Dry run to see which torrents would be tagged qbit-race tag-error --dry-run # Example output: # Found 3 torrents with no working trackers # Tagged: Ubuntu 20.04 (hash: abc123...) # Tagged: Debian 11 (hash: def456...) # Tagged: Arch 2023 (hash: ghi789...) ``` -------------------------------- ### Generate Prometheus Metrics Programmatically Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Generate Prometheus metrics strings programmatically without HTTP server. Creates metrics for transfer info and torrent states using helper functions. Outputs formatted Prometheus metrics for download/upload rates and torrent state counts. ```typescript import { makeMetrics, stateMetrics } from './helpers/preparePromMetrics.js'; // Get transfer info const transferInfo = await api.getTransferInfo(); // Generate transfer metrics const metrics = makeMetrics(transferInfo); console.log(metrics); // Output: // qbit_dl_bytes 123456789 // qbit_dl_rate_bytes 1234567 // qbit_ul_bytes 987654321 // qbit_ul_rate_bytes 987654 // up 1 // Get torrent state metrics const torrents = await api.getTorrents(); const stateMetricsStr = stateMetrics(torrents); console.log(stateMetricsStr); // Output: // qbit_torrents_state{state="downloading"} 2 // qbit_torrents_state{state="uploading"} 15 // qbit_torrents_state{state="pausedUP"} 5 // qbit_torrents_state{state="stalledDL"} 1 ``` -------------------------------- ### POST /api/v2/torrents/resume Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Resumes previously paused torrents by their hashes. Ideal for resuming all paused downloads or uploads after a condition is met. Supports bulk operations with an array of torrent identifiers. ```APIDOC ## POST /api/v2/torrents/resume ### Description Resumes the specified paused torrents to continue activity. ### Method POST ### Endpoint /api/v2/torrents/resume ### Parameters #### Request Body - **hashes** (array of strings) - Required - List of torrent hashes to resume. ### Request Example ```json { "hashes": ["a1b2c3d4e5f6a1b2c3d4e5f6..."] } ``` ### Response #### Success Response (200) No content. ``` -------------------------------- ### Pre-Race Checks and Filtering (TypeScript) Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Performs pre-race checks including concurrent race limit verification and identifies torrents to pause based on ratio, categories, and tags. Includes dry-run capability for testing. ```typescript import { concurrentRacesCheck, getTorrentsToPause } from './racing/preRace.js'; const allTorrents = await api.getTorrents(); // Check if we can start a new race const canRace = concurrentRacesCheck(config, allTorrents); if (!canRace) { console.log('Concurrent race limit reached, skipping this torrent'); process.exit(0); } console.log('Safe to start new race'); // Get torrents that should be paused const toPause = getTorrentsToPause(config, allTorrents); console.log(`Found ${toPause.length} torrents to pause`); // Preview which torrents would be paused toPause.forEach(torrent => { console.log(` - ${torrent.name} (ratio: ${torrent.ratio.toFixed(2)})`); }); // Pause them await api.pauseTorrents(toPause); ``` -------------------------------- ### Send Torrent Added Discord Notification Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Send Discord webhook notification when a new torrent is added to the system. Builds formatted message with torrent name, size, trackers, and reannounce count. Requires Discord webhook configuration and torrent metadata. ```typescript import { sendMessageV2 } from './discord/api.js'; import { buildTorrentAddedBody } from './discord/messages.js'; import { humanFileSize } from './helpers/utilities.js'; const discordSettings = config.DISCORD_NOTIFICATIONS; // Build notification for added torrent const message = buildTorrentAddedBody(discordSettings, { name: 'Ubuntu 22.04 LTS Desktop', trackers: ['torrent.ubuntu.com', 'tracker2.ubuntu.com'], size: 3 * 1024 * 1024 * 1024, // 3 GiB reannounceCount: 2 }); // Send to Discord await sendMessageV2(discordSettings.webhook, message); // Message format: // Content: "Added Ubuntu 22.04 LTS Desktop (3.00 GiB)" // Embed fields: // - Trackers: torrent.ubuntu.com, tracker2.ubuntu.com // - Size: 3.00 GiB // - Reannounce Count: 2 ``` -------------------------------- ### Set Torrent Category in AutoDL (Shell) Source: https://github.com/ckcr4lyf/qbit-race/blob/master/README.md Adds category specification to autoDL arguments for automatic torrent categorization. Input includes info hash, name, tracker, and path; creates category if it doesn't exist. Depends on autoDL and qbit-race; useful for organizing downloads but may not handle special characters well. ```shell "$(InfoHash)" "$(InfoName)" "$(Tracker)" "$(TorrentPathName)" --category "never open" ``` -------------------------------- ### Extract Torrent Metadata in TypeScript Source: https://context7.com/ckcr4lyf/qbit-race/llms.txt Parse .torrent files to extract metadata including name, infohash, and tracker information. Uses helper functions to read and process torrent files. Input: torrent file buffer. Output: metadata object with name, hash, and tracker properties. ```typescript import { getTorrentMetainfo } from './helpers/torrent.js'; import { readFileSync } from 'fs'; // Read and parse torrent file const torrentData = readFileSync('/path/to/ubuntu-22.04.torrent'); const metadata = getTorrentMetainfo(torrentData); console.log('Torrent information:'); console.log(` Name: ${metadata.name}`); console.log(` Infohash: ${metadata.hash}`); console.log(` Tracker: ${metadata.tracker}`); // Example output: // Torrent information: // Name: Ubuntu 22.04 LTS Desktop // Hash: a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2 // Tracker: torrent.ubuntu.com // Use metadata before adding const meta = getTorrentMetainfo(torrentData); console.log(`Adding ${meta.name} from ${meta.tracker}`); await api.addTorrent(torrentData); // Extract just tracker hostname const trackerUrl = new URL(`http://${metadata.tracker}`); console.log(`Tracker hostname: ${trackerUrl.hostname}`); ```