Merge branch 'dev' into feat/downloader-speed

Catch the branch up with dev (45 commits) so testers can run the perf work
against current dev.

Conflict resolutions:
- downloaders/requests.py: keep the branch's racing-gated read1, adaptive
  controller speed reporting and byte-range slice guards; take dev's
  content-encoding checks (raw reads are skipped on an encoded body) and its
  rolling SpeedWindow for the no-controller speed fallback. The single-URL
  ranged-parallel gate now requires no speed limit and no caller Range.
- service.py / session.py: keep the branch's TimeoutHTTPAdapter and retry
  config, raise POOL_MAX_SIZE to 64 so dev's pool-starvation fix survives
  (pool_block=True stalls threads on a pool smaller than the in-flight count).
- docs: dev split configuration.md into per-area pages, so the branch's rnet
  network option rows moved to reference/configuration/network.md.
This commit is contained in:
imSp4rky
2026-08-07 10:45:47 -06:00
104 changed files with 8567 additions and 1375 deletions
+2 -2
View File
@@ -71,7 +71,7 @@ def measure_real_bitrate(
elif track.descriptor == Track.Descriptor.ISM:
segments = extract_ism(track, session)
else:
# Descriptor.URL: a single file. Some services (e.g. AMZN) parse a DASH
# Descriptor.URL: a single file. Some services parse a DASH
# manifest then collapse each representation to its single BaseURL and
# flip the descriptor to URL, leaving the manifest (and its duration) in
# track.data — recover the duration from there, else probe the file.
@@ -375,7 +375,7 @@ def extract_url(track: "Track", session: Union[Session, RnetSession], *, log: lo
duration = duration_ticks / timescale
if not duration or duration <= 0:
# Services like AMZN clear the manifest data after collapsing to a single
# Some services clear the manifest data after collapsing to a single
# file; fall back to reading the duration straight from the remote file.
duration = ffprobe_duration(url, session, log=log)
+44 -13
View File
@@ -174,11 +174,18 @@ class SeasonRange(click.ParamType):
MIN_EPISODE = 0
MAX_EPISODE = 999
MIN_PART = 1
MAX_PART = 99
def parse_tokens(self, *tokens: str) -> list[str]:
"""
Parse multiple tokens or ranged tokens as '{s}x{e}' strings.
An episode split into separately playable parts is addressed as '{s}x{e}.{p}'.
A part range must stay inside one episode, since how many parts an episode has
is not knowable here. A part-qualified exclusion cannot be removed from the
computed keys (they are base keys), so it becomes a '!' key resolved at match time.
Supports exclusioning by putting a `-` before the token.
Example:
@@ -189,6 +196,10 @@ class SeasonRange(click.ParamType):
["2x1", "2x3", "2x4", "2x5"]
>>> sr.parse_tokens("S01-S05", "-S03", "-S02E01")
["1x0", "1x1", ..., "2x0", (...), "2x2", (...), "4x0", ..., "5x0", ...]
>>> sr.parse_tokens("S01E01.1-S01E01.3")
["1x1.1", "1x1.2", "1x1.3"]
>>> sr.parse_tokens("S01E01", "-S01E01.2")
["1x1", "!1x1.2"]
"""
if len(tokens) == 0:
return []
@@ -199,36 +210,56 @@ class SeasonRange(click.ParamType):
if exclude:
token = token[1:]
parsed = [
re.match(r"^S(?P<season>\d+)(E(?P<episode>\d+))?$", x, re.IGNORECASE) for x in re.split(r"[:-]", token)
re.match(r"^S(?P<season>\d+)(E(?P<episode>\d+)(\.(?P<part>\d+))?)?$", x, re.IGNORECASE)
for x in re.split(r"[:-]", token)
]
if len(parsed) > 2:
self.fail(f"Invalid token, only a left and right range is acceptable: {token}")
if len(parsed) == 1:
# the same match object is read with different per-side defaults, so a bare
# S01 spans from MIN_EPISODE to MAX_EPISODE
parsed.append(parsed[0])
if any(x is None for x in parsed):
self.fail(f"Invalid token, syntax error occurred: {token}")
from_season, from_episode = [
int(v) if v is not None else self.MIN_EPISODE
for k, v in parsed[0].groupdict().items()
if parsed[0] # type: ignore[union-attr]
]
to_season, to_episode = [
int(v) if v is not None else self.MAX_EPISODE
for k, v in parsed[1].groupdict().items()
if parsed[1] # type: ignore[union-attr]
]
left, right = parsed[0], parsed[1]
from_season = int(left.group("season")) # type: ignore[union-attr]
from_episode_raw = left.group("episode") # type: ignore[union-attr]
from_episode = int(from_episode_raw) if from_episode_raw is not None else self.MIN_EPISODE
from_part_raw = left.group("part") # type: ignore[union-attr]
from_part = int(from_part_raw) if from_part_raw is not None else None
to_season = int(right.group("season")) # type: ignore[union-attr]
to_episode_raw = right.group("episode") # type: ignore[union-attr]
to_episode = int(to_episode_raw) if to_episode_raw is not None else self.MAX_EPISODE
to_part_raw = right.group("part") # type: ignore[union-attr]
to_part = int(to_part_raw) if to_part_raw is not None else None
if from_season > to_season:
self.fail(f"Invalid range, left side season cannot be bigger than right side season: {token}")
if from_season == to_season and from_episode > to_episode:
self.fail(f"Invalid range, left side episode cannot be bigger than right side episode: {token}")
if (from_part is None) != (to_part is None):
self.fail(f"Invalid range, a part must be given on both sides or on neither: {token}")
if from_part is not None and to_part is not None:
if (from_season, from_episode) != (to_season, to_episode):
self.fail(f"Invalid range, a part range must stay within one episode: {token}")
if not all(self.MIN_PART <= p <= self.MAX_PART for p in (from_part, to_part)):
self.fail(f"Invalid part, must be between {self.MIN_PART} and {self.MAX_PART}: {token}")
if from_part > to_part:
self.fail(f"Invalid range, left side part cannot be bigger than right side part: {token}")
for p in range(from_part, to_part + 1):
(computed if not exclude else exclusions).append(f"{from_season}x{from_episode}.{p}")
continue
for s in range(from_season, to_season + 1):
for e in range(
from_episode if s == from_season else 0, (self.MAX_EPISODE if s < to_season else to_episode) + 1
):
(computed if not exclude else exclusions).append(f"{s}x{e}")
for exclusion in exclusions:
if exclusion in computed:
computed.remove(exclusion)
if "." in exclusion:
computed.append(f"!{exclusion}") # base key stays; resolved at match time
else:
# a base exclusion must drop that episode's part keys too, or they still match
prefix = f"{exclusion}."
computed = [k for k in computed if k != exclusion and not k.startswith(prefix)]
return list(set(computed))
def convert(
+116
View File
@@ -0,0 +1,116 @@
"""Release-group tag rule engine for output filename templates."""
from __future__ import annotations
import logging
import operator
import re
from collections.abc import Mapping
from typing import Any, Callable, Optional
log = logging.getLogger(__name__)
_OPS: dict[str, Callable[[Any, Any], bool]] = {
">=": operator.ge,
"<=": operator.le,
"!=": operator.ne,
"==": operator.eq,
">": operator.gt,
"<": operator.lt,
"=": operator.eq,
}
_ORDERING = (">=", "<=", ">", "<")
_NUMBER = re.compile(r"\d+(?:\.\d+)?")
def evaluate_tag_rules(rules: Any, context: dict[str, Any]) -> Optional[str]:
"""Evaluate tag rules against a filename template context.
Rules are evaluated in order; the first matching rule's tag is returned.
Conditions are AND-ed, compared case-insensitively, and a list matches if
any entry matches. A value may lead with a comparison operator, e.g.
">=2160" or "!=DV".
Args:
rules: Rules straight from the user's YAML, so any shape is possible.
Each valid rule is a mapping with a ``when`` mapping and a ``tag``.
context: The already-built filename template context.
Returns:
The tag string from the first matching rule, or ``None`` if none match.
"""
if not isinstance(rules, list):
log.warning("tag_rules must be a list of rules, ignoring: %r", rules)
return None
for rule in rules:
if not isinstance(rule, Mapping):
log.warning("Tag rule must be a mapping of 'when' and 'tag', skipping: %r", rule)
continue
when = rule.get("when")
tag = rule.get("tag")
if when is not None and not isinstance(when, Mapping):
log.warning("Tag rule 'when' must be a mapping of conditions, skipping: %s", rule)
continue
if not when or not tag:
log.warning("Tag rule needs both 'when' conditions and a 'tag', skipping: %s", rule)
continue
if isinstance(tag, bool) or any(_has_bool(value) for value in when.values()):
log.warning("Tag rule has a YAML boolean, quote the value to use it as text, skipping: %s", rule)
continue
if not isinstance(tag, (str, int, float)):
log.warning("Tag rule 'tag' must be text or a number, skipping: %s", rule)
continue
unknown = [key for key in when if key not in context]
if unknown:
log.warning("Tag rule has unknown 'when' key(s) %s, skipping: %s", ", ".join(sorted(unknown)), rule)
continue
if all(_matches(expected, context[key]) for key, expected in when.items()):
log.debug("Tag rule matched: %s -> %s", rule, tag)
return str(tag)
return None
def _has_bool(expected: Any) -> bool:
"""Check for a YAML boolean, which is an unquoted word the user meant as text."""
values = expected if isinstance(expected, list) else [expected]
return any(isinstance(x, bool) for x in values)
def _matches(expected: Any, actual: Any) -> bool:
"""Check one condition, where a list matches on any entry."""
values = expected if isinstance(expected, list) else [expected]
return any(_matches_one(x, actual) for x in values)
def _matches_one(expected: Any, actual: Any) -> bool:
"""Check a single value, which may carry a leading comparison operator."""
text = "" if expected is None else str(expected)
for op in sorted(_OPS, key=len, reverse=True):
if text.startswith(op):
return _compare(op, text[len(op) :].strip(), actual)
return str(actual or "").lower() == text.lower()
def _compare(op: str, operand: str, actual: Any) -> bool:
"""Compare against an operand, numerically when the operand is a number."""
if not operand:
log.warning("Tag rule condition '%s' has no value to compare against, condition failed", op)
return False
try:
wanted = float(operand)
except ValueError:
if op in _ORDERING:
log.warning("Tag rule condition '%s%s' needs a numeric operand, condition failed", op, operand)
return False
return _OPS[op](str(actual or "").lower(), operand.lower())
found = _NUMBER.search(str(actual or ""))
if not found:
return op == "!="
return _OPS[op](float(found.group()), wanted)
+22 -8
View File
@@ -86,6 +86,7 @@ def tag_file(
title: Title,
tmdb_id: Optional[int] = None,
imdb_id: Optional[str] = None,
tvdb_id: Optional[int] = None,
) -> None:
log.debug("Tagging file %s with title %r", path, title)
custom_tags: dict[str, str] = {}
@@ -118,7 +119,7 @@ def tag_file(
if config.tag_imdb_tmdb:
try:
providers = get_available_providers()
if not providers:
if not providers and tvdb_id is None:
log.debug("No metadata providers available; skipping tag lookup")
apply_tags(path, custom_tags)
return
@@ -130,9 +131,11 @@ def tag_file(
imdbapi = get_provider("imdbapi")
if imdbapi:
result = imdbapi.get_by_id(imdb_id, kind)
if result:
result.external_ids.imdb_id = imdb_id
enrich_ids(result)
if not result:
# IMDxAPI is off or had no answer; the ID alone still resolves the others
result = MetadataResult(title=name, year=year, kind=kind)
result.external_ids.imdb_id = imdb_id
enrich_ids(result)
elif tmdb_id is not None:
tmdb = get_provider("tmdb")
if tmdb:
@@ -140,17 +143,28 @@ def tag_file(
if result:
ext = tmdb.get_external_ids(tmdb_id, kind)
result.external_ids = ext
enrich_ids(result)
else:
# Search across providers in priority order
result = search_metadata(name, year, kind)
# If we got a TMDB ID from search but no full external IDs, fetch them
if result and result.external_ids.tmdb_id and not result.external_ids.imdb_id:
# If we got a TMDB ID from search but not the other IDs, fetch them
if (
result
and result.external_ids.tmdb_id
and not (result.external_ids.imdb_id and result.external_ids.tvdb_id)
):
ext = fetch_external_ids(result.external_ids.tmdb_id, kind)
if ext.imdb_id:
if ext.imdb_id and not result.external_ids.imdb_id:
result.external_ids.imdb_id = ext.imdb_id
if ext.tvdb_id:
if ext.tvdb_id and not result.external_ids.tvdb_id:
result.external_ids.tvdb_id = ext.tvdb_id
enrich_ids(result)
if tvdb_id is not None:
if result is None:
result = MetadataResult(kind=kind)
result.external_ids.tvdb_id = tvdb_id
if result and result.external_ids:
standard_tags = _build_tags_from_ids(result.external_ids, kind)
+22 -17
View File
@@ -9,6 +9,16 @@ from unshackle.core.utilities import sanitize_filename
log = logging.getLogger(__name__)
def detect_spacer(template: str) -> str:
"""Dot or space, whichever the template uses between its variables.
Falls back to a dot (scene style) when the template has nothing between two
variables, such as a folder path segment with only one variable.
"""
separator_text = "".join(re.findall(r"\}([^{]*)\{", template))
return " " if separator_text.count(" ") > separator_text.count(".") else "."
class TemplateFormatter:
"""
Template formatter for custom filename patterns.
@@ -17,13 +27,17 @@ class TemplateFormatter:
Example: '{title}.{year}.{quality?}.{source}-{tag}'
"""
def __init__(self, template: str):
def __init__(self, template: str, spacer: str | None = None):
"""Initialize the template formatter.
Args:
template: Template string with variables in {variable} format
spacer: Force a separator style instead of detecting it from `template`.
Folder paths pass the style of the whole path, so every segment is
spaced alike even when it holds a single variable.
"""
self.template = template
self.spacer = spacer or detect_spacer(template)
self.variables = self._extract_variables()
def _extract_variables(self) -> list[str]:
@@ -95,24 +109,15 @@ class TemplateFormatter:
# Clean up multiple consecutive dots/separators and other artifacts
result = re.sub(r"\.{2,}", ".", result) # Multiple dots -> single dot
result = re.sub(r"\s{2,}", " ", result) # Multiple spaces -> single space
result = re.sub(r"-{2,}", "-", result) # Multiple dashes -> single dash
result = re.sub(r"^[\.\s\-]+|[\.\s\-]+$", "", result) # Remove leading/trailing dots, spaces, dashes
result = re.sub(r"\.-", "-", result) # Remove dots before dashes (for dot-based templates)
result = re.sub(r"[\.\s]+\)", ")", result) # Remove dots/spaces before closing parentheses
result = re.sub(r"\(\s*\)", "", result) # Remove empty parentheses (empty conditional)
result = re.sub(r"[\.\s]+([)\]])", r"\1", result) # Remove dots/spaces before closing bracket
result = re.sub(r"\(\s*\)|\[\s*\]", "", result) # Remove empty brackets (empty conditional)
# bracket removal is what creates neighbouring separators, so collapse after it
result = re.sub(r"\s{2,}", " ", result) # Multiple spaces -> single space
result = re.sub(r"(?:-\s*)+-", "-", result) # Multiple dashes (with optional spaces) -> single dash
result = re.sub(r"^[\.\s\-]+|[\.\s\-]+$", "", result) # Remove leading/trailing dots, spaces, dashes
# Determine the appropriate separator based on template style
# Count separator characters between variables (between } and {)
between_vars = re.findall(r"\}([^{]*)\{", self.template)
separator_text = "".join(between_vars)
dot_count = separator_text.count(".")
space_count = separator_text.count(" ")
if space_count > dot_count:
result = sanitize_filename(result, spacer=" ")
else:
result = sanitize_filename(result, spacer=".")
result = sanitize_filename(result, spacer=self.spacer)
if not result or result.isspace():
log.warning("Template formatting resulted in empty filename, using fallback")