from dataclasses import dataclass from typing import Optional from sanic import Blueprint, response from sanic.request import Request from sanic_ext import validate from sanic_ext.extensions.openapi import openapi from modules.torrents import lib, share from wrolpi.api_utils import json_response from wrolpi.common import get_wrolpi_config, wrol_mode_check from wrolpi.downloader import download_manager from wrolpi.errors import ValidationError torrents_bp = Blueprint('Torrents', '/api/torrents') @dataclass class ShareLimitsRequest: seed_ratio_limit: Optional[float] = None seed_time_limit: Optional[int] = None @dataclass class ShareRequest: path: str trackers: Optional[list] = None web_seeds: Optional[list] = None # Make these trackers the ones offered next time. remember_trackers: bool = False @dataclass class LimitsRequest: upload: int = 0 download: int = 0 @torrents_bp.get('/') @openapi.description("Every torrent, qBittorrent's state, and the VPN's (torrents reach the Internet only through it)") async def get_torrents(_: Request): return json_response(await lib.get_torrents_status()) @torrents_bp.post('/upload') @openapi.description('Download a .torrent file (multipart field `torrent`) into `destination` (form field, relative ' 'to the media directory). Its progress is shown on the Downloads page.') @wrol_mode_check async def upload_torrent(request: Request): file = request.files.get('torrent') if request.files else None if not file: raise ValidationError('Choose a .torrent file') torrent = file.body hash_, name = lib.torrent_identity(torrent) save_path = lib.check_save_path(request.form.get('destination') or lib.DEFAULT_SAVE_PATH) torrent_file = lib.get_torrents_config().get_torrent_file(hash_) torrent_file.parent.mkdir(parents=True, exist_ok=True) torrent_file.write_bytes(torrent) # Its magnet link names it on the Downloads page; the downloader uses the saved file. A write block, as # post_download explains. with request.ctx.db.write() as session: download_manager.create_downloads(session, [lib.torrent_magnet(torrent)], lib.TORRENT_DOWNLOADER, reset_attempts=True, destination=lib.get_media_directory() / save_path) return json_response(dict(hash=hash_, name=name)) @torrents_bp.post('//pause') @wrol_mode_check async def pause_torrent(_: Request, hash_: str): await lib.set_paused(hash_, True) return response.empty() @torrents_bp.post('//resume') @wrol_mode_check async def resume_torrent(_: Request, hash_: str): await lib.set_paused(hash_, False) return response.empty() @torrents_bp.put('//limits') @openapi.definition(body=ShareLimitsRequest, summary='Stop seeding at a ratio / after minutes seeding (null: never)') @validate(ShareLimitsRequest) @wrol_mode_check async def put_share_limits(_: Request, hash_: str, body: ShareLimitsRequest): lib.set_share_limits(hash_, body.seed_ratio_limit, body.seed_time_limit) return response.empty() @torrents_bp.delete('/') @openapi.description('Remove a torrent. Its files are kept unless `delete_files=true`.') @wrol_mode_check async def delete_torrent(request: Request, hash_: str): await lib.remove_torrent(hash_, delete_files=request.args.get('delete_files') == 'true') return response.empty() @torrents_bp.get('//torrent') @openapi.description("A torrent's .torrent file, to share it") async def get_torrent_file(_: Request, hash_: str): config = lib.get_torrents_config() entity = config.get(hash_) torrent_file = config.get_torrent_file(hash_) if not entity or not torrent_file.is_file(): raise ValidationError('That torrent has no .torrent file yet') return await response.file(torrent_file, mime_type='application/x-bittorrent', filename=f'{entity["name"]}.torrent') @torrents_bp.put('/limits') @openapi.definition(body=LimitsRequest, summary="Torrents' total upload and download limits, in KiB/s (0: none)") @validate(LimitsRequest) @wrol_mode_check async def put_limits(_: Request, body: LimitsRequest): if body.upload < 0 or body.download < 0: raise ValidationError('A speed limit cannot be negative') wrolpi_config = get_wrolpi_config() wrolpi_config.torrent_upload_limit = body.upload wrolpi_config.torrent_download_limit = body.download return response.empty() @torrents_bp.post('/share') @openapi.definition(body=ShareRequest, summary='Make a torrent of a file or directory in the library (`path`, relative to the media ' 'directory), and seed it. Returns the Job making it.') @validate(ShareRequest) @wrol_mode_check async def share_torrent(_: Request, body: ShareRequest): trackers = share.check_trackers(body.trackers) job_id = share.share(body.path, trackers, body.web_seeds or []) # Only once the request was accepted. if body.remember_trackers: get_wrolpi_config().torrent_trackers = trackers return json_response(dict(job_id=job_id), status=201)