Files
homelabstack/stacks/media/qbittorrent/on-complete.py
T
ginnoirandClaude Opus 5.5 a50849b766 fix(media): on-complete hook reads author/title from end of MAM save path
autobrr's {{ .Category }} renders as "Audiobook/Non-Fiction", so the save
path is <Category>/<SubCategory>/<Author>/<Title>; indexing from the front
would have filed books under the subcategory as author.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 20:56:51 -05:00

111 lines
4.5 KiB
Python

#!/usr/bin/env python3
"""qBittorrent "run on torrent finished" hook.
Host-managed copy lives at /config/qbittorrent/scripts/on-complete.py (container
path /config/scripts/on-complete.py); this file is the canonical source, scp it
over after editing. AutoRun program in qBittorrent.conf:
python3 /config/scripts/on-complete.py "%I" "%L" "%F" "%D" <cross-seed apikey>
1. Every torrent: notify cross-seed's webhook (what the old inline curl did).
2. Category "mam" (autobrr MyAnonamouse grabs): file the payload into the book
libraries without touching the seeding copy. autobrr saves MAM grabs to
/storage1/complete/mam/<Category>/<SubCategory>/<Author>/<Title>/ so the path carries the
metadata the .torrent name lacks.
- Audiobook -> hardlinked into /storage1/Media/Audiobooks/<Author>/<Title>/
(Audiobookshelf). Never use ABS "embed metadata" on these: it rewrites the
shared inode and breaks the seed.
- Ebook -> COPIED into the CWA ingest folder. CWA edits and then deletes
ingest files, so a hardlink would corrupt the seeding data.
"""
import os
import shutil
import sys
import urllib.parse
import urllib.request
from datetime import datetime
MAM_ROOT = "/storage1/complete/mam"
AUDIOBOOKS = "/storage1/Media/Audiobooks"
EBOOK_INGEST = "/storage1/complete/books-ingest"
AUDIO_EXT = {".m4b", ".m4a", ".mp3", ".flac", ".ogg", ".opus", ".aac", ".wma"}
# Sidecars ABS uses for covers/metadata.
AUDIO_SIDECAR_EXT = {".jpg", ".jpeg", ".png", ".webp", ".opf", ".nfo", ".cue"}
EBOOK_EXT = {".epub", ".azw3", ".azw", ".mobi", ".pdf", ".kepub", ".fb2", ".cbz", ".cbr"}
LOG = "/config/scripts/on-complete.log"
def log(msg):
with open(LOG, "a", encoding="utf-8") as f:
f.write(f"{datetime.now():%Y-%m-%d %H:%M:%S} {msg}\n")
def notify_cross_seed(info_hash, apikey):
data = urllib.parse.urlencode({"infoHash": info_hash, "includeSingleEpisodes": "true"}).encode()
url = "http://cross-seed:2468/api/webhook?" + urllib.parse.urlencode({"apikey": apikey})
try:
urllib.request.urlopen(urllib.request.Request(url, data=data, method="POST"), timeout=30)
except Exception as e: # cross-seed being down must not block filing
log(f"cross-seed webhook failed for {info_hash}: {e}")
def payload_files(content_path):
"""Yield (abs_path, path relative to the torrent's root) for every file."""
if os.path.isfile(content_path):
yield content_path, os.path.basename(content_path)
return
for dirpath, _, names in os.walk(content_path):
for n in names:
p = os.path.join(dirpath, n)
yield p, os.path.relpath(p, content_path)
def file_mam(content_path, save_path):
rel = os.path.relpath(save_path, MAM_ROOT).split(os.sep)
if len(rel) < 3 or rel[0].startswith(".."):
log(f"mam: unexpected save path {save_path!r}, skipping")
return
# autobrr's Category renders as "Audiobook/Non-Fiction", so the path is
# <Category>/<SubCategory>/<Author>/<Title>; take author/title from the end.
category, author, title = rel[0], rel[-2], rel[-1]
linked = 0
if category.lower() == "audiobook":
dest = os.path.join(AUDIOBOOKS, author, title)
for src, r in payload_files(content_path):
ext = os.path.splitext(src)[1].lower()
if ext not in AUDIO_EXT | AUDIO_SIDECAR_EXT:
continue
target = os.path.join(dest, r)
if os.path.exists(target):
continue
os.makedirs(os.path.dirname(target), exist_ok=True)
os.link(src, target)
linked += 1
log(f"mam audiobook: {linked} file(s) -> {dest}")
elif category.lower() == "ebook":
for src, _ in payload_files(content_path):
if os.path.splitext(src)[1].lower() not in EBOOK_EXT:
continue
target = os.path.join(EBOOK_INGEST, os.path.basename(src))
if os.path.exists(target):
continue
shutil.copy2(src, target)
linked += 1
log(f"mam ebook: {linked} file(s) copied to ingest from {content_path}")
else:
log(f"mam: category {category!r} not filed ({content_path})")
def main():
info_hash, category, content_path, save_path, apikey = sys.argv[1:6]
notify_cross_seed(info_hash, apikey)
if category == "mam":
try:
file_mam(content_path, save_path)
except Exception as e:
log(f"mam: filing failed for {content_path}: {e!r}")
if __name__ == "__main__":
main()