wrolpi/modules/torrents/lib.py
lrnselfreliance 2c3300b8b0
Torrents over a fail-closed VPN (#1026)
Torrents reach the Internet only through a fail-closed VPN (WireGuard or
OpenVPN, any provider), so peers never see a WROLPi's own address.

- A network namespace (Pi/Debian) or the vpn container (Docker) with an
  nftables kill switch; NAT-PMP or fixed port forwarding.
- qBittorrent inside it, sandboxed; torrents kept in config/torrents/.
- Torrent download form, Torrents page, Share as torrent, nav warning, and
  VPN settings in both Controller UIs.
- Help docs: Torrents, and The VPN for Torrents.

QA'd on a Raspberry Pi with a real provider over WireGuard and OpenVPN.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 14:26:24 -07:00

604 lines
26 KiB
Python

"""
Torrents: qBittorrent, inside the VPN's network namespace, kept as config/torrents/ says.
Each torrent is `config/torrents/<hash>.yaml`, with its `.torrent` file beside it, so a restored WROLPi re-adds
(and re-checks, never re-downloads) every torrent. There is no database. The torrents can also be managed in
qBittorrent's own WebUI (port 8091), so WROLPi follows it too:
- A torrent WROLPi knows carries the `wrolpi` tag in qBittorrent. An untagged torrent (added in the WebUI) is
adopted into the config once its metadata has arrived.
- qBittorrent keeps its tags in its profile. Without the `wrolpi` tag, the profile is new (first start, or a
restore), and every torrent in the config is added. With it, a torrent missing from qBittorrent was removed in the
WebUI, and leaves the config; a tagged torrent missing from the config was removed from the config, and leaves
qBittorrent (its files are kept).
- `paused` in the config is what the user wants. WROL Mode stops torrents with the `wrolpi-wrol-mode` tag, so they
are started again when it ends; any other stop or start of a torrent is the user's, and is saved.
"""
import asyncio
import base64
import hashlib
import pathlib
import re
import time
import urllib.parse
from dataclasses import dataclass, field
from typing import List, Optional
import aiohttp
from wrolpi import flags
from wrolpi.api_utils import perpetual_signal
from wrolpi.common import MultiFileConfig, get_media_directory, logger, wrol_mode_enabled, \
get_relative_to_media_directory, get_wrolpi_config
from wrolpi.errors import ValidationError
from wrolpi.vars import DOCKERIZED, PYTEST
from modules.torrents.qbittorrent import QBittorrent, QBittorrentError, QBittorrentUnavailable
logger = logger.getChild(__name__)
TAG = 'wrolpi'
WROL_MODE_TAG = 'wrolpi-wrol-mode'
TUNNEL_INTERFACE = 'vpn0'
# Where torrents are saved unless asked otherwise, relative to the media directory.
DEFAULT_SAVE_PATH = 'torrents'
STOPPED_STATES = {'stoppedUP', 'stoppedDL'}
# Downloaded, and being (or ready to be) seeded.
COMPLETE_STATES = {'uploading', 'stalledUP', 'forcedUP', 'queuedUP', 'stoppedUP', 'checkingUP'}
SYNC_SECONDS = 10
CONTROLLER_URL = 'http://controller' if DOCKERIZED else 'http://127.0.0.1'
@dataclass
class TorrentConfigValidator:
version: int
slug: str
name: str
save_path: str
paused: bool = False
magnet: str = None
complete: bool = False
# Stop seeding at this ratio / after this many minutes seeding. None: never.
seed_ratio_limit: float = None
seed_time_limit: int = None
class TorrentsConfig(MultiFileConfig):
subdirectory = 'torrents'
name = 'torrents'
validator = TorrentConfigValidator
default_entity = dict(version=0, slug=None, name=None, save_path=DEFAULT_SAVE_PATH, paused=False, magnet=None,
complete=False, seed_ratio_limit=None, seed_time_limit=None)
def get_torrent_file(self, slug: str) -> pathlib.Path:
return self.get_directory() / f'{slug}.torrent'
def update(self, slug: str, **values):
entity = self.get(slug)
if entity is None:
return
entity.update(values)
self.replace(slug, entity)
def delete(self, slug: str):
with self.save_lock():
self._configs.pop(slug, None)
self.get_file(slug).unlink(missing_ok=True)
self.get_torrent_file(slug).unlink(missing_ok=True)
TORRENTS_CONFIG = TorrentsConfig()
TEST_TORRENTS_CONFIG: Optional[TorrentsConfig] = None
def get_torrents_config() -> TorrentsConfig:
if isinstance(TEST_TORRENTS_CONFIG, TorrentsConfig):
return TEST_TORRENTS_CONFIG
return TORRENTS_CONFIG
def set_test_torrents_config(enabled: bool):
global TEST_TORRENTS_CONFIG
TEST_TORRENTS_CONFIG = TorrentsConfig() if enabled else None
def save_path_of(entity: dict) -> str:
"""The absolute directory qBittorrent saves a torrent in."""
save_path = pathlib.Path(entity.get('save_path') or DEFAULT_SAVE_PATH)
return str(save_path if save_path.is_absolute() else get_media_directory() / save_path)
def config_save_path(save_path: str) -> str:
"""How the config records qBittorrent's save path: relative to the media directory when it is in it."""
try:
return str(get_relative_to_media_directory(save_path))
except ValueError:
return save_path
MAX_TORRENT_FILE_BYTES = 20 * 1024 * 1024
HASH_RE = re.compile(r'^[0-9a-f]{40}$')
def bdecode(data: bytes, start: int = 0):
"""Decode the bencoded value (a .torrent file's) which starts at `start`. Returns (value, where it ends)."""
def decode(i: int):
c = data[i:i + 1]
if c == b'i':
end = data.index(b'e', i)
return int(data[i + 1:end]), end + 1
if c in (b'l', b'd'):
i += 1
items = []
while data[i:i + 1] != b'e':
item, i = decode(i)
items.append(item)
if c == b'l':
return items, i + 1
return dict(zip(items[::2], items[1::2])), i + 1
if c.isdigit():
colon = data.index(b':', i)
length = int(data[i:colon])
return data[colon + 1:colon + 1 + length], colon + 1 + length
raise ValueError(f'Not bencoded data at {i}')
return decode(start)
def torrent_identity(torrent: bytes) -> tuple[str, str]:
"""(hash, name) of a .torrent file, the hash as qBittorrent names it (see `torrent_id`)."""
v1, v2, name = torrent_info_hashes(torrent)
return torrent_id(v1, v2), name
def torrent_id(v1: Optional[str], v2: Optional[str]) -> str:
"""qBittorrent names a torrent by libtorrent's "best" info hash: the v2 (SHA-256) hash truncated to 40 characters
when it has one (a v2 or hybrid torrent), otherwise the v1 (SHA-1) hash."""
return v2[:40] if v2 else v1
def torrent_magnet(torrent: bytes) -> str:
"""A magnet link for a .torrent file, with both info hashes of a hybrid torrent."""
v1, v2, name = torrent_info_hashes(torrent)
return magnet_link(v1, v2, name)
def torrent_info_hashes(torrent: bytes) -> tuple[Optional[str], Optional[str], str]:
"""(v1 SHA-1 info hash or None, v2 SHA-256 info hash or None, name) of a .torrent file."""
if len(torrent) > MAX_TORRENT_FILE_BYTES:
raise ValidationError('That file is too large to be a .torrent file')
try:
if torrent[:1] != b'd':
raise ValueError('Not a dictionary')
# Walk the top-level dictionary to find the info dictionary exactly as it is written; that is what is hashed.
info = raw_info = None
i = 1
while torrent[i:i + 1] != b'e':
key, i = bdecode(torrent, i)
value_start = i
value, i = bdecode(torrent, i)
if key == b'info':
info, raw_info = value, torrent[value_start:i]
if not isinstance(info, dict):
raise ValueError('No info dictionary')
except (ValueError, KeyError, TypeError, IndexError) as e:
raise ValidationError('That is not a .torrent file') from e
# v1 torrents have `pieces`; v2 torrents have `meta version` 2 (a hybrid torrent has both).
v1 = hashlib.sha1(raw_info).hexdigest() if b'pieces' in info else None
v2 = hashlib.sha256(raw_info).hexdigest() if info.get(b'meta version') == 2 else None
if not v1 and not v2:
raise ValidationError('That is not a .torrent file')
name = info.get(b'name.utf-8') or info.get(b'name') or torrent_id(v1, v2).encode()
return v1, v2, name.decode('utf-8', errors='replace')
def magnet_identity(magnet: str) -> tuple[str, str]:
"""(hash, name) of a magnet link, the hash as qBittorrent names it (see `torrent_id`)."""
query = urllib.parse.parse_qs(urllib.parse.urlparse(magnet).query)
v1 = v2 = None
for xt in query.get('xt', []):
lower = xt.lower()
if lower.startswith('urn:btih:'):
value = xt[len('urn:btih:'):]
if len(value) == 32:
# Base32, as some magnet links write it.
value = base64.b32decode(value.upper()).hex()
if HASH_RE.match(value.lower()):
v1 = value.lower()
elif lower.startswith('urn:btmh:1220') and re.fullmatch(r'[0-9a-f]{64}', lower[len('urn:btmh:1220'):]):
# A v2 info hash: a SHA-256 multihash.
v2 = lower[len('urn:btmh:1220'):]
if not v1 and not v2:
raise ValidationError('That magnet link has no BitTorrent info hash (xt=urn:btih:... or xt=urn:btmh:...)')
hash_ = torrent_id(v1, v2)
return hash_, (query.get('dn') or [hash_])[0]
def magnet_link(v1: Optional[str], v2: Optional[str], name: str) -> str:
xts = ([f'xt=urn:btih:{v1}'] if v1 else []) + ([f'xt=urn:btmh:1220{v2}'] if v2 else [])
return f'magnet:?{"&".join(xts)}&dn={urllib.parse.quote(name)}'
def check_save_path(save_path: str) -> str:
"""A save path relative to the media directory, which must stay in it (torrents are only saved in the library)."""
save_path = save_path or DEFAULT_SAVE_PATH
media_directory = get_media_directory()
path = pathlib.Path(save_path)
absolute = (path if path.is_absolute() else media_directory / path).resolve()
if absolute != media_directory and media_directory not in absolute.parents:
raise ValidationError('Torrents can only be saved in the media directory')
if absolute == media_directory / 'config' or media_directory / 'config' in absolute.parents:
raise ValidationError("Torrents cannot be saved in WROLPi's config directory")
return str(absolute.relative_to(media_directory)) or '.'
async def add_torrent(save_path: str = None, torrent: bytes = None, magnet: str = None,
client: QBittorrent = None, skip_checking: bool = False) -> dict:
"""Add a torrent from a .torrent file's bytes, or a magnet link: to the config (the source of truth), then to
qBittorrent. Returns its config."""
client = client or QBittorrent()
config = get_torrents_config()
save_path = check_save_path(save_path)
if torrent:
hash_, name = torrent_identity(torrent)
magnet = torrent_magnet(torrent)
elif magnet:
hash_, name = magnet_identity(magnet)
else:
raise ValidationError('A .torrent file or a magnet link is required')
if config.get(hash_) is None:
config.create(hash_, dict(slug=hash_, name=name, save_path=save_path, magnet=magnet))
if torrent:
config.get_torrent_file(hash_).write_bytes(torrent)
if hash_ not in {t['hash'] for t in await client.torrents()}:
await add_from_config(client, config.get(hash_), stopped=wrol_mode_enabled(), skip_checking=skip_checking)
return config.get(hash_)
async def remove_torrent(hash_: str, delete_files: bool = False, client: QBittorrent = None):
client = client or QBittorrent()
await client.delete([hash_], delete_files=delete_files)
get_torrents_config().delete(hash_)
async def set_paused(hash_: str, paused: bool, client: QBittorrent = None):
client = client or QBittorrent()
config = get_torrents_config()
if config.get(hash_) is None:
raise ValidationError('Unknown torrent')
config.update(hash_, paused=paused)
if paused:
await client.stop([hash_])
elif not wrol_mode_enabled():
await client.start([hash_])
def set_share_limits(hash_: str, seed_ratio_limit: float = None, seed_time_limit: int = None):
"""None is no limit. The torrents worker applies them."""
if seed_ratio_limit is not None and seed_ratio_limit < 0:
raise ValidationError('The ratio limit cannot be negative')
if seed_time_limit is not None and seed_time_limit < 0:
raise ValidationError('The seeding time limit cannot be negative')
config = get_torrents_config()
if config.get(hash_) is None:
raise ValidationError('Unknown torrent')
config.update(hash_, seed_ratio_limit=seed_ratio_limit, seed_time_limit=seed_time_limit)
async def get_vpn_status() -> dict:
"""The Controller's report of the VPN torrents use; {} when the Controller cannot be reached."""
try:
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=5)) as session:
async with session.get(f'{CONTROLLER_URL}/api/vpn/status') as response:
return await response.json() if response.status == 200 else {}
except (aiohttp.ClientError, TimeoutError, ValueError):
return {}
def desired_preferences(vpn_status: dict) -> dict:
preferences = {
# Torrents use only the tunnel. (The kill switch already blocks everything else.)
'current_network_interface': TUNNEL_INTERFACE,
'current_interface_address': '',
# The router UPnP or NAT-PMP would ask is the VPN's; the tunnel asks for the port itself.
'upnp': False,
# Nothing to discover on the tunnel's "local" network.
'lsd': False,
# A file still downloading is never mistaken for a finished one.
'incomplete_files_ext': True,
'save_path': str(get_media_directory() / DEFAULT_SAVE_PATH),
'random_port': False,
# Peers are not told which client (and version) this is, so a known flaw in one cannot be aimed at it.
'anonymous_mode': True,
# Running a program would be code execution for anyone who can reach the WebUI.
'autorun_enabled': False,
'autorun_on_torrent_added_enabled': False,
}
wrolpi_config = get_wrolpi_config()
# qBittorrent's limits are bytes per second; 0 is unlimited.
preferences['up_limit'] = (wrolpi_config.torrent_upload_limit or 0) * 1024
preferences['dl_limit'] = (wrolpi_config.torrent_download_limit or 0) * 1024
if port := vpn_status.get('forwarded_port'):
# Peers connect to the port the VPN forwards.
preferences['listen_port'] = port
return preferences
async def enforce_preferences(client: QBittorrent, vpn_status: dict) -> dict:
"""Set the preferences which differ from what WROLPi needs; returns those changed."""
current = await client.preferences()
changed = {k: v for k, v in desired_preferences(vpn_status).items() if current.get(k) != v}
if changed:
logger.info(f'Setting qBittorrent preferences: {changed}')
await client.set_preferences(changed)
return changed
async def add_from_config(client: QBittorrent, entity: dict, stopped: bool, skip_checking: bool = False):
config = get_torrents_config()
torrent_file = config.get_torrent_file(entity['slug'])
torrent = torrent_file.read_bytes() if torrent_file.is_file() else None
if not torrent and not entity.get('magnet'):
logger.error(f'Cannot add torrent {entity["name"]}: it has no .torrent file and no magnet link')
return
pathlib.Path(save_path_of(entity)).mkdir(parents=True, exist_ok=True)
tags = [TAG, WROL_MODE_TAG] if stopped and not entity.get('paused') else [TAG]
await client.add(save_path_of(entity), torrent=torrent, url=None if torrent else entity['magnet'], tags=tags,
stopped=stopped, skip_checking=skip_checking)
logger.info(f'Added torrent {entity["name"]} to qBittorrent')
async def adopt(client: QBittorrent, torrent: dict) -> bool:
"""Add a torrent added in qBittorrent's WebUI to the config, once its metadata has arrived."""
exported = await client.export(torrent['hash'])
if not exported:
return False
config = get_torrents_config()
slug = torrent['hash']
config.get_torrent_file(slug).parent.mkdir(parents=True, exist_ok=True)
config.get_torrent_file(slug).write_bytes(exported)
if config.get(slug) is None:
# (WROLPi may have recorded it already, e.g. while it was still adding the torrent.)
config.create(slug, dict(slug=slug, name=torrent['name'], save_path=config_save_path(torrent['save_path']),
paused=torrent['state'] in STOPPED_STATES, magnet=torrent.get('magnet_uri')))
await client.add_tags([slug], TAG)
logger.info(f'Adopted torrent {torrent["name"]} added in qBittorrent')
return True
# How long a torrent may be in the config, but not yet in qBittorrent, before it is added from the config (another
# process may be adding it).
ADD_GRACE_SECONDS = 30
@dataclass
class ReconcileState:
"""What reconcile has seen, across its passes. A torrent is forgotten (removed in the WebUI) only once it has been
seen in qBittorrent; one never seen is being added, or must be added."""
seen: set = field(default_factory=set)
missing_since: dict = field(default_factory=dict)
RECONCILE_STATE = ReconcileState()
async def reconcile(client: QBittorrent, wrol_mode: bool, state: ReconcileState = None) -> dict:
"""Make qBittorrent and the config agree; returns what was done (for tests and logs)."""
state = state or ReconcileState()
config = get_torrents_config()
done = dict(added=[], adopted=[], forgotten=[], removed=[], stopped=[], started=[], completed=[])
torrents = {t['hash']: t for t in await client.torrents()}
entities = {e['slug']: e for e in config.all()}
if TAG not in await client.tags():
# A new qBittorrent profile: add every torrent the config has.
await client.create_tags(TAG, WROL_MODE_TAG)
for slug, entity in entities.items():
if slug not in torrents:
await add_from_config(client, entity, stopped=wrol_mode or bool(entity.get('paused')))
done['added'].append(slug)
return done
for slug, torrent in torrents.items():
tags = {t.strip() for t in (torrent.get('tags') or '').split(',') if t.strip()}
if TAG not in tags:
if await adopt(client, torrent):
done['adopted'].append(slug)
continue
entity = entities.get(slug)
if entity is None:
# Removed from the config: removed from qBittorrent, its files kept.
await client.delete([slug], delete_files=False)
done['removed'].append(slug)
state.seen.discard(slug)
continue
state.seen.add(slug)
stopped = torrent['state'] in STOPPED_STATES
if wrol_mode:
if not stopped:
await client.add_tags([slug], WROL_MODE_TAG)
await client.stop([slug])
done['stopped'].append(slug)
elif WROL_MODE_TAG in tags:
# Stopped by WROL Mode, which has ended.
await client.remove_tags([slug], WROL_MODE_TAG)
if not entity.get('paused'):
await client.start([slug])
done['started'].append(slug)
elif stopped != bool(entity.get('paused')):
# Stopped or started in the WebUI: that is what the user wants now.
config.update(slug, paused=stopped)
ratio_limit = -1 if entity.get('seed_ratio_limit') is None else entity['seed_ratio_limit']
time_limit = -1 if entity.get('seed_time_limit') is None else entity['seed_time_limit']
if torrent.get('ratio_limit') != ratio_limit or torrent.get('seeding_time_limit') != time_limit:
await client.set_share_limits([slug], ratio_limit, time_limit)
if not entity.get('complete') and torrent['state'] in COMPLETE_STATES and torrent.get('progress', 0) >= 1:
config.update(slug, complete=True)
done['completed'].append(slug)
index_downloaded(torrent)
if not config.get_torrent_file(slug).is_file() and (exported := await client.export(slug)):
config.get_torrent_file(slug).write_bytes(exported)
now = time.monotonic()
missing = entities.keys() - torrents.keys()
state.missing_since = {slug: since for slug, since in state.missing_since.items() if slug in missing}
for slug in missing:
if slug in state.seen:
# Removed in the WebUI.
config.delete(slug)
state.seen.discard(slug)
done['forgotten'].append(slug)
elif now - state.missing_since.setdefault(slug, now) >= ADD_GRACE_SECONDS:
# Never shown by qBittorrent: its add failed, or the config was restored.
entity = entities[slug]
await add_from_config(client, entity, stopped=wrol_mode or bool(entity.get('paused')))
del state.missing_since[slug]
done['added'].append(slug)
return done
def index_downloaded(torrent: dict):
"""Index a finished torrent's files, as any other download's."""
from wrolpi.files.worker import file_worker
content_path = pathlib.Path(torrent.get('content_path') or torrent['save_path'])
try:
content_path.relative_to(get_media_directory())
except ValueError:
logger.warning(f'Not indexing torrent {torrent["name"]}: it is outside the media directory')
return
file_worker.queue_refresh([content_path], expand_stems=True)
TORRENT_DOWNLOADER = 'torrent'
# qBittorrent's ETA for "never".
ETA_UNKNOWN = 8640000
def format_eta(seconds: int) -> Optional[str]:
if seconds is None or seconds < 0 or seconds >= ETA_UNKNOWN:
return None
hours, rest = divmod(int(seconds), 3600)
minutes, seconds = divmod(rest, 60)
return f'{hours}:{minutes:02}:{seconds:02}' if hours else f'{minutes}:{seconds:02}'
def sync_download_rows(torrents: dict):
"""Show each torrent's progress on its Download (the Downloads page), which finished when it was added: no
download worker waits days for a torrent. It is shown as completed once the torrent is."""
from wrolpi.db import get_db_session
from wrolpi.downloader import Download, set_download_progress, clear_download_progress
from wrolpi.dates import now
with get_db_session(commit=True) as session:
for download in session.query(Download).filter(Download.downloader == TORRENT_DOWNLOADER):
torrent = torrents.get((download.info_json or {}).get('torrent_hash'))
if not torrent:
clear_download_progress(download.id)
elif torrent.get('progress', 0) < 1:
set_download_progress(download.id, dict(
percent=round(torrent.get('progress', 0) * 100, 1),
speed=torrent.get('dlspeed'),
eta=format_eta(torrent.get('eta')),
bytes_downloaded=torrent.get('completed'),
total_bytes=torrent.get('size'),
))
download.last_successful_download = None
else:
clear_download_progress(download.id)
if download.last_successful_download is None:
download.last_successful_download = now()
async def sync_torrents(client: QBittorrent = None) -> Optional[dict]:
"""One pass: qBittorrent's preferences, and the config; None when qBittorrent cannot be reached."""
client = client or QBittorrent()
vpn_status = await get_vpn_status()
try:
await client.version()
except QBittorrentUnavailable:
publish_summary(len(get_torrents_config().slugs), vpn_status.get('state'), running=False)
return None
await enforce_preferences(client, vpn_status)
done = await reconcile(client, wrol_mode_enabled(), RECONCILE_STATE)
torrents = await client.torrents()
await asyncio.to_thread(sync_download_rows, {t['hash']: t for t in torrents})
publish_summary(len(torrents), vpn_status.get('state'), running=True)
return done
def publish_summary(count: int, vpn_state: Optional[str], running: bool):
"""What /api/status tells the navigation: torrents exist, and whether the VPN they need is connected."""
from wrolpi.api_utils import api_app
try:
api_app.shared_ctx.torrents_summary.update(count=count, vpn_state=vpn_state, running=running)
except AttributeError:
# The shared context is not attached (some unit tests).
pass
@perpetual_signal(sleep=SYNC_SECONDS)
async def torrents_worker():
if PYTEST or not flags.media_mounted.is_set() or not get_torrents_config().successful_import:
return
try:
done = await sync_torrents()
except (QBittorrentError, QBittorrentUnavailable, OSError) as e:
logger.warning(f'Could not sync torrents with qBittorrent: {e}')
return
if done and any(done.values()):
logger.info(f'Synced torrents with qBittorrent: { {k: v for k, v in done.items() if v} }')
async def get_torrents_status(client: QBittorrent = None) -> dict:
"""qBittorrent's state, the VPN's, and every torrent, for the API."""
client = client or QBittorrent()
config = get_torrents_config()
vpn_status = await get_vpn_status()
try:
transfer, torrents = await asyncio.gather(client.transfer_info(), client.torrents())
except (QBittorrentUnavailable, QBittorrentError) as e:
return dict(running=False, error=str(e), vpn=vpn_status, torrents=[],
limits=dict(upload=get_wrolpi_config().torrent_upload_limit,
download=get_wrolpi_config().torrent_download_limit),
trackers=get_wrolpi_config().torrent_trackers)
return dict(
running=True,
error=None,
vpn=vpn_status,
# connected (peers can reach this WROLPi), firewalled, or disconnected.
connection_status=transfer.get('connection_status'),
upload_speed=transfer.get('up_info_speed'),
download_speed=transfer.get('dl_info_speed'),
limits=dict(upload=get_wrolpi_config().torrent_upload_limit,
download=get_wrolpi_config().torrent_download_limit),
trackers=get_wrolpi_config().torrent_trackers,
torrents=[torrent_status(t, config.get(t['hash'])) for t in torrents],
)
def torrent_status(torrent: dict, entity: Optional[dict]) -> dict:
entity = entity or {}
return dict(
hash=torrent['hash'],
name=torrent['name'],
size=torrent.get('size'),
progress=torrent.get('progress'),
state=torrent.get('state'),
ratio=torrent.get('ratio'),
uploaded=torrent.get('uploaded'),
upload_speed=torrent.get('upspeed'),
download_speed=torrent.get('dlspeed'),
eta=format_eta(torrent.get('eta')),
peers=torrent.get('num_leechs'),
seeds=torrent.get('num_seeds'),
save_path=config_save_path(torrent.get('save_path') or ''),
# Managed by WROLPi (in config/torrents/); otherwise not yet adopted (e.g. waiting for a magnet's metadata).
managed=bool(entity),
paused=entity.get('paused', torrent.get('state') in STOPPED_STATES),
seed_ratio_limit=entity.get('seed_ratio_limit'),
seed_time_limit=entity.get('seed_time_limit'),
magnet=entity.get('magnet') or torrent.get('magnet_uri'),
)