836 lines
29 KiB
Python
836 lines
29 KiB
Python
import copy
|
||
import datetime
|
||
import html
|
||
import json
|
||
import os
|
||
import shlex
|
||
import shutil
|
||
import time
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
import qbittorrentapi
|
||
import requests
|
||
from dotenv import load_dotenv
|
||
|
||
BASE_DIR = Path(__file__).resolve().parent
|
||
load_dotenv(BASE_DIR / ".env")
|
||
|
||
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "").strip()
|
||
TELEGRAM_ALLOWED_CHAT_IDS = [
|
||
c.strip() for c in os.getenv("TELEGRAM_ALLOWED_CHAT_IDS", "").split(",") if c.strip()
|
||
]
|
||
|
||
QBIT_HOST = os.getenv("QBIT_HOST", "http://localhost:8080").strip()
|
||
QBIT_USERNAME = os.getenv("QBIT_USERNAME", "admin").strip()
|
||
QBIT_PASSWORD = os.getenv("QBIT_PASSWORD", "").strip()
|
||
|
||
PLEX_ENABLED = os.getenv("PLEX_ENABLED", "false").strip().lower() in ("1", "true", "yes", "y", "on")
|
||
PLEX_BASE_URL = os.getenv("PLEX_BASE_URL", "http://127.0.0.1:32400").rstrip("/")
|
||
PLEX_TOKEN = os.getenv("PLEX_TOKEN", "").strip()
|
||
PLEX_SECTIONS_RAW = os.getenv("PLEX_SECTIONS", "").strip()
|
||
|
||
DOWNLOAD_RULES_PATH = Path(os.getenv("DOWNLOAD_RULES_PATH", "")).expanduser()
|
||
DOWNLOAD_TEMPLATE_PATH = Path(os.getenv("DOWNLOAD_TEMPLATE_PATH", "download_template.json"))
|
||
# If FEEDS_PATH is not set, default to feeds.json beside qBittorrent's download_rules.json.
|
||
# This lets TorrentOps read qBittorrent's live/exported RSS feed list from:
|
||
# C:\Users\<YOU>\AppData\Roaming\qBittorrent\rss\feeds.json
|
||
FEEDS_PATH_RAW = os.getenv("FEEDS_PATH", "").strip()
|
||
if FEEDS_PATH_RAW:
|
||
FEEDS_PATH = Path(FEEDS_PATH_RAW)
|
||
elif DOWNLOAD_RULES_PATH:
|
||
FEEDS_PATH = DOWNLOAD_RULES_PATH.parent / "feeds.json"
|
||
else:
|
||
FEEDS_PATH = Path("feeds.json")
|
||
|
||
DOWNLOAD_ROOT_DEFAULT = os.getenv("DOWNLOAD_ROOT_DEFAULT", "anime").strip()
|
||
DOWNLOAD_ROOTS_RAW = os.getenv("DOWNLOAD_ROOTS", "anime=O:/Media/Anime").strip()
|
||
|
||
CREATE_SAVE_PATH = os.getenv("CREATE_SAVE_PATH", "true").strip().lower() in ("1", "true", "yes", "y", "on")
|
||
BACKUP_RULES_JSON = os.getenv("BACKUP_RULES_JSON", "true").strip().lower() in ("1", "true", "yes", "y", "on")
|
||
REFRESH_RSS_AFTER_ADD = os.getenv("REFRESH_RSS_AFTER_ADD", "true").strip().lower() in ("1", "true", "yes", "y", "on")
|
||
UPDATE_LOCAL_RULES_JSON = os.getenv("UPDATE_LOCAL_RULES_JSON", "true").strip().lower() in ("1", "true", "yes", "y", "on")
|
||
REQUIRE_CONFIRM = os.getenv("REQUIRE_CONFIRM", "true").strip().lower() in ("1", "true", "yes", "y", "on")
|
||
PRUNE_DAYS_AFTER = int(os.getenv("PRUNE_DAYS_AFTER", "30"))
|
||
|
||
PENDING_RULES: dict[str, dict[str, Any]] = {}
|
||
PENDING_PRUNES: dict[str, dict[str, Any]] = {}
|
||
|
||
|
||
def parse_download_roots(raw: str) -> dict[str, str]:
|
||
roots = {}
|
||
for entry in raw.split(","):
|
||
entry = entry.strip()
|
||
if not entry or "=" not in entry:
|
||
continue
|
||
key, value = entry.split("=", 1)
|
||
roots[key.strip()] = value.strip().replace("\\", "/").rstrip("/")
|
||
return roots
|
||
|
||
|
||
DOWNLOAD_ROOTS = parse_download_roots(DOWNLOAD_ROOTS_RAW)
|
||
|
||
def parse_plex_sections(raw: str) -> dict[str, str]:
|
||
sections: dict[str, str] = {}
|
||
for entry in raw.split(","):
|
||
entry = entry.strip()
|
||
if not entry or "=" not in entry:
|
||
continue
|
||
key, value = entry.split("=", 1)
|
||
if key.strip() and value.strip():
|
||
sections[key.strip().lower()] = value.strip()
|
||
return sections
|
||
|
||
PLEX_SECTIONS = parse_plex_sections(PLEX_SECTIONS_RAW)
|
||
|
||
|
||
def local_path(path: Path) -> Path:
|
||
return path if path.is_absolute() else BASE_DIR / path
|
||
|
||
|
||
def current_quarter_label() -> str:
|
||
now = datetime.datetime.now()
|
||
quarter = ((now.month - 1) // 3) + 1
|
||
return f"{now.year}_Q{quarter}"
|
||
|
||
|
||
def telegram_api(method: str, payload: dict | None = None):
|
||
if not TELEGRAM_BOT_TOKEN:
|
||
raise RuntimeError("Missing TELEGRAM_BOT_TOKEN in .env")
|
||
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/{method}"
|
||
response = requests.post(url, json=payload or {}, timeout=60)
|
||
response.raise_for_status()
|
||
return response.json()
|
||
|
||
|
||
def send_message(chat_id: str, text: str):
|
||
telegram_api("sendMessage", {
|
||
"chat_id": chat_id,
|
||
"text": text[:3900],
|
||
"parse_mode": "HTML",
|
||
"disable_web_page_preview": True,
|
||
})
|
||
|
||
|
||
def is_allowed(chat_id: str) -> bool:
|
||
return not TELEGRAM_ALLOWED_CHAT_IDS or str(chat_id) in TELEGRAM_ALLOWED_CHAT_IDS
|
||
|
||
|
||
def load_json(path: Path):
|
||
with local_path(path).open("r", encoding="utf-8") as f:
|
||
return json.load(f)
|
||
|
||
|
||
def write_json(path: Path, data):
|
||
p = local_path(path)
|
||
p.parent.mkdir(parents=True, exist_ok=True)
|
||
with p.open("w", encoding="utf-8") as f:
|
||
json.dump(data, f, indent=4, ensure_ascii=False)
|
||
f.write("\n")
|
||
|
||
|
||
def backup_file(path: Path) -> Path | None:
|
||
p = local_path(path)
|
||
if not p.exists():
|
||
return None
|
||
stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
||
backup = p.with_name(f"{p.stem}_{stamp}{p.suffix}.bak")
|
||
shutil.copy2(p, backup)
|
||
return backup
|
||
|
||
|
||
def get_feed_items() -> list[tuple[int, str, str]]:
|
||
feeds = load_json(FEEDS_PATH)
|
||
return [
|
||
(i, name, value["url"])
|
||
for i, (name, value) in enumerate(feeds.items(), start=1)
|
||
if isinstance(value, dict) and value.get("url")
|
||
]
|
||
|
||
|
||
def get_feed_urls(feed_numbers: str) -> tuple[list[str], list[str]]:
|
||
numbers = []
|
||
for part in feed_numbers.split(","):
|
||
part = part.strip()
|
||
if not part:
|
||
continue
|
||
if not part.isdigit():
|
||
raise ValueError(f"Feed number must be numeric: {part}")
|
||
numbers.append(int(part))
|
||
|
||
if not numbers:
|
||
raise ValueError("At least one feed number is required.")
|
||
|
||
items = get_feed_items()
|
||
lookup = {i: (name, url) for i, name, url in items}
|
||
urls = []
|
||
names = []
|
||
|
||
for n in numbers:
|
||
if n not in lookup:
|
||
raise ValueError(f"Unknown feed number: {n}. Send /feeds to view options.")
|
||
name, url = lookup[n]
|
||
urls.append(url)
|
||
names.append(f"{n}. {name}")
|
||
|
||
return urls, names
|
||
|
||
|
||
def normalize_command_quotes(raw: str) -> str:
|
||
return (
|
||
raw.replace("“", '\"')
|
||
.replace("”", '\"')
|
||
.replace("„", '\"')
|
||
.replace("‟", '\"')
|
||
.replace("‘", "'")
|
||
.replace("’", "'")
|
||
.replace("‚", "'")
|
||
.replace("‛", "'")
|
||
)
|
||
|
||
|
||
def parse_add_args(raw: str):
|
||
raw = normalize_command_quotes(raw)
|
||
|
||
try:
|
||
parts = shlex.split(raw)
|
||
except ValueError as exc:
|
||
raise ValueError("Could not parse command. Use quotes around name, query, and optional exclusions.") from exc
|
||
|
||
if len(parts) < 4:
|
||
raise ValueError(
|
||
'Use: /add "name" "query" ["exclude"] season [root] feeds\n'
|
||
'Example: /add "Frieren" "Sousou no Frieren" 2 anime 5\n'
|
||
'With exclusions: /add "Ghost in the Shell" "Koukaku 265" "Dual Audio HEVC" 1 anime 7'
|
||
)
|
||
|
||
name = parts[0].strip()
|
||
query = parts[1].strip()
|
||
|
||
if parts[2].isdigit():
|
||
exclude = ""
|
||
season_index = 2
|
||
else:
|
||
if len(parts) < 5:
|
||
raise ValueError(
|
||
'Use: /add "name" "query" ["exclude"] season [root] feeds\n'
|
||
'Example: /add "Frieren" "Sousou no Frieren" 2 anime 5\n'
|
||
'With exclusions: /add "Ghost in the Shell" "Koukaku 265" "Dual Audio HEVC" 1 anime 7'
|
||
)
|
||
exclude = parts[2].strip()
|
||
season_index = 3
|
||
|
||
try:
|
||
season = int(parts[season_index])
|
||
except ValueError as exc:
|
||
raise ValueError("Season must be a whole number.") from exc
|
||
|
||
remaining = parts[season_index + 1:]
|
||
if len(remaining) == 1:
|
||
root_key = DOWNLOAD_ROOT_DEFAULT
|
||
feeds = remaining[0].strip()
|
||
elif len(remaining) == 2:
|
||
root_key = remaining[0].strip()
|
||
feeds = remaining[1].strip()
|
||
else:
|
||
raise ValueError(
|
||
'Use: /add "name" "query" ["exclude"] season [root] feeds\n'
|
||
'Example: /add "Frieren" "Sousou no Frieren" 2 anime 5\n'
|
||
'With exclusions: /add "Ghost in the Shell" "Koukaku 265" "Dual Audio HEVC" 1 anime 7'
|
||
)
|
||
|
||
return name, query, exclude, season, root_key, feeds
|
||
|
||
|
||
def get_template():
|
||
template = load_json(DOWNLOAD_TEMPLATE_PATH)
|
||
key = next(iter(template.keys()))
|
||
return key, template[key]
|
||
|
||
|
||
def build_rule(name: str, query: str, exclude: str, season: int, root_key: str, feed_numbers: str):
|
||
if root_key not in DOWNLOAD_ROOTS:
|
||
raise ValueError(f"Unknown download root '{root_key}'. Available: {', '.join(DOWNLOAD_ROOTS.keys())}")
|
||
|
||
quarter = current_quarter_label()
|
||
root = DOWNLOAD_ROOTS[root_key]
|
||
feed_urls, feed_names = get_feed_urls(feed_numbers)
|
||
template_key, template_rule = get_template()
|
||
|
||
rule_name = template_key.replace("<quarter>", quarter).replace("<name>", name)
|
||
rule = copy.deepcopy(template_rule)
|
||
|
||
save_path = str(rule.get("savePath", ""))
|
||
save_path = save_path.replace("<download>", root).replace("<name>", name).replace("<season>", str(season))
|
||
|
||
rule["affectedFeeds"] = feed_urls
|
||
rule["mustContain"] = query
|
||
|
||
must_not_contain = ["batch"]
|
||
if exclude:
|
||
must_not_contain.append(exclude)
|
||
rule["mustNotContain"] = " ".join(must_not_contain)
|
||
rule["savePath"] = save_path
|
||
rule["lastMatch"] = ""
|
||
rule["previouslyMatchedEpisodes"] = []
|
||
|
||
return {
|
||
"rule_name": rule_name,
|
||
"rule": rule,
|
||
"name": name,
|
||
"query": query,
|
||
"exclude": exclude,
|
||
"season": season,
|
||
"root_key": root_key,
|
||
"root": root,
|
||
"feed_names": feed_names,
|
||
"feed_urls": feed_urls,
|
||
"quarter": quarter,
|
||
"save_path": save_path,
|
||
}
|
||
|
||
|
||
def preview_text(p):
|
||
feeds = "\n".join(f"- {html.escape(x)}" for x in p["feed_names"])
|
||
return (
|
||
"📋 <b>TorrentOps Rule Preview</b>\n\n"
|
||
f"<b>Rule:</b> <code>{html.escape(p['rule_name'])}</code>\n"
|
||
f"<b>Name:</b> {html.escape(p['name'])}\n"
|
||
f"<b>Query:</b> <code>{html.escape(p['query'])}</code>\n"
|
||
f"<b>Season:</b> {p['season']}\n"
|
||
f"<b>Quarter:</b> {html.escape(p['quarter'])}\n"
|
||
f"<b>Download root:</b> <code>{html.escape(p['root_key'])}</code>\n"
|
||
f"<b>Save path:</b> <code>{html.escape(p['save_path'])}</code>\n"
|
||
f"<b>mustNotContain:</b> <code>{html.escape(p['rule'].get('mustNotContain', ''))}</code>\n\n"
|
||
f"<b>Feeds:</b>\n{feeds}\n\n"
|
||
"Reply with:\n<code>/confirm</code>\n<code>/cancel</code>"
|
||
)
|
||
|
||
|
||
def qbit_client():
|
||
client = qbittorrentapi.Client(host=QBIT_HOST, username=QBIT_USERNAME, password=QBIT_PASSWORD)
|
||
client.auth_log_in()
|
||
return client
|
||
|
||
|
||
def refresh_all_rss_feeds() -> int:
|
||
"""Trigger qBittorrent to refresh all configured RSS feeds."""
|
||
client = qbit_client()
|
||
|
||
try:
|
||
items = client.rss_items(with_data=False)
|
||
except TypeError:
|
||
items = client.rss_items()
|
||
|
||
if not isinstance(items, dict):
|
||
raise RuntimeError("Unexpected RSS items response from qBittorrent.")
|
||
|
||
refreshed = 0
|
||
|
||
for item_path in items.keys():
|
||
try:
|
||
client.rss_refresh_item(item_path=item_path)
|
||
refreshed += 1
|
||
except Exception as exc:
|
||
print(f"RSS refresh failed for {item_path}: {exc}")
|
||
|
||
return refreshed
|
||
|
||
|
||
def handle_rss_update(chat_id: str):
|
||
refreshed = refresh_all_rss_feeds()
|
||
send_message(
|
||
chat_id,
|
||
"✅ <b>qBittorrent RSS refresh triggered.</b>\n\n"
|
||
f"<b>Feeds/items refreshed:</b> <code>{refreshed}</code>",
|
||
)
|
||
|
||
|
||
def apply_rule(p):
|
||
client = qbit_client()
|
||
client.rss_set_rule(rule_name=p["rule_name"], rule_def=p["rule"])
|
||
|
||
if REFRESH_RSS_AFTER_ADD:
|
||
try:
|
||
for selected in p["feed_names"]:
|
||
feed_name = selected.split(". ", 1)[1] if ". " in selected else selected
|
||
client.rss_refresh_item(item_path=feed_name)
|
||
except Exception as exc:
|
||
print(f"RSS refresh skipped/failed: {exc}")
|
||
|
||
|
||
def update_local_rules(p):
|
||
if not UPDATE_LOCAL_RULES_JSON:
|
||
return None
|
||
|
||
rules_path = local_path(DOWNLOAD_RULES_PATH)
|
||
if not rules_path.exists():
|
||
raise FileNotFoundError(f"download_rules.json not found: {rules_path}")
|
||
|
||
rules = load_json(DOWNLOAD_RULES_PATH)
|
||
if p["rule_name"] in rules:
|
||
raise ValueError(f"Rule already exists: {p['rule_name']}")
|
||
|
||
backup = backup_file(DOWNLOAD_RULES_PATH) if BACKUP_RULES_JSON else None
|
||
rules[p["rule_name"]] = p["rule"]
|
||
write_json(DOWNLOAD_RULES_PATH, rules)
|
||
return backup
|
||
|
||
|
||
def confirm_rule(chat_id: str):
|
||
p = PENDING_RULES.get(chat_id)
|
||
if not p:
|
||
send_message(chat_id, "No pending rule. Use /add first.")
|
||
return
|
||
|
||
try:
|
||
if CREATE_SAVE_PATH:
|
||
Path(p["save_path"]).mkdir(parents=True, exist_ok=True)
|
||
|
||
backup = update_local_rules(p)
|
||
apply_rule(p)
|
||
del PENDING_RULES[chat_id]
|
||
|
||
backup_line = f"\n<b>Backup:</b> <code>{html.escape(str(backup))}</code>" if backup else ""
|
||
send_message(
|
||
chat_id,
|
||
"✅ <b>Rule applied.</b>\n\n"
|
||
f"<b>Rule:</b> <code>{html.escape(p['rule_name'])}</code>\n"
|
||
f"<b>Save path:</b> <code>{html.escape(p['save_path'])}</code>"
|
||
f"{backup_line}",
|
||
)
|
||
except Exception as exc:
|
||
send_message(chat_id, f"⚠️ <b>Failed to apply rule:</b>\n<code>{html.escape(str(exc))}</code>")
|
||
|
||
|
||
def feeds_text(filter_text: str = ""):
|
||
items = get_feed_items()
|
||
if filter_text:
|
||
needle = filter_text.lower()
|
||
items = [x for x in items if needle in x[1].lower() or needle in x[2].lower()]
|
||
if not items:
|
||
return "No matching feeds."
|
||
lines = ["<b>Feeds:</b>"]
|
||
for i, name, url in items:
|
||
lines.append(f"{i}. <b>{html.escape(name)}</b>\n<code>{html.escape(url)}</code>")
|
||
return "\n\n".join(lines)
|
||
|
||
|
||
def rules_text(limit=30):
|
||
try:
|
||
rules = qbit_client().rss_rules()
|
||
names = list(rules.keys()) if isinstance(rules, dict) else []
|
||
except Exception:
|
||
rules = load_json(DOWNLOAD_RULES_PATH)
|
||
names = list(rules.keys()) if isinstance(rules, dict) else []
|
||
shown = names[-limit:]
|
||
if not shown:
|
||
return "No RSS rules found."
|
||
return "<b>Latest rules:</b>\n" + "\n".join(f"- {html.escape(x)}" for x in shown)
|
||
|
||
|
||
def current_text():
|
||
quarter = current_quarter_label()
|
||
rules = load_json(DOWNLOAD_RULES_PATH)
|
||
matches = [name for name in rules if name.startswith(quarter)]
|
||
if not matches:
|
||
return f"No rules found for <b>{html.escape(quarter)}</b>."
|
||
return f"<b>Rules for {html.escape(quarter)}:</b>\n" + "\n".join(f"- {html.escape(x)}" for x in matches)
|
||
|
||
|
||
def search_text(query: str):
|
||
if not query:
|
||
return "Use: <code>/search <text></code>"
|
||
rules = load_json(DOWNLOAD_RULES_PATH)
|
||
needle = query.lower()
|
||
matches = []
|
||
for name, rule in rules.items():
|
||
blob = f"{name} {rule.get('mustContain', '')} {rule.get('savePath', '')}".lower()
|
||
if needle in blob:
|
||
matches.append((name, rule))
|
||
if not matches:
|
||
return f"No rules matched: <code>{html.escape(query)}</code>"
|
||
lines = [f"<b>Matches for {html.escape(query)}:</b>"]
|
||
for name, rule in matches[:25]:
|
||
lines.append(
|
||
f"- <b>{html.escape(name)}</b>\n"
|
||
f" Query: <code>{html.escape(str(rule.get('mustContain', '')))}</code>\n"
|
||
f" Path: <code>{html.escape(str(rule.get('savePath', '')))}</code>"
|
||
)
|
||
return "\n".join(lines)
|
||
|
||
|
||
|
||
|
||
|
||
def plex_request(path: str, params: dict | None = None):
|
||
if not PLEX_ENABLED:
|
||
raise RuntimeError("Plex integration is disabled. Set PLEX_ENABLED=true in .env.")
|
||
if not PLEX_TOKEN:
|
||
raise RuntimeError("Missing PLEX_TOKEN in .env.")
|
||
|
||
params = params or {}
|
||
params["X-Plex-Token"] = PLEX_TOKEN
|
||
|
||
response = requests.get(f"{PLEX_BASE_URL}{path}", params=params, timeout=30)
|
||
response.raise_for_status()
|
||
return response
|
||
|
||
def plex_refresh_all():
|
||
plex_request("/library/sections/all/refresh")
|
||
|
||
def plex_refresh_section(section_id: str):
|
||
section_id = str(section_id).strip()
|
||
if not section_id:
|
||
raise ValueError("Plex section ID cannot be empty.")
|
||
plex_request(f"/library/sections/{section_id}/refresh")
|
||
|
||
def plex_get_sections() -> list[dict]:
|
||
import xml.etree.ElementTree as ET
|
||
response = plex_request("/library/sections")
|
||
root = ET.fromstring(response.text)
|
||
sections = []
|
||
for directory in root.findall(".//Directory"):
|
||
sections.append({
|
||
"key": directory.attrib.get("key", ""),
|
||
"title": directory.attrib.get("title", ""),
|
||
"type": directory.attrib.get("type", ""),
|
||
})
|
||
return sections
|
||
|
||
def format_plex_sections() -> str:
|
||
if not PLEX_ENABLED:
|
||
return "Plex integration is disabled. Set <code>PLEX_ENABLED=true</code> in .env."
|
||
|
||
sections = plex_get_sections()
|
||
if not sections:
|
||
return "No Plex library sections found."
|
||
|
||
lines = ["<b>Plex libraries:</b>"]
|
||
for section in sections:
|
||
key = html.escape(str(section.get("key", "")))
|
||
title = html.escape(str(section.get("title", "")))
|
||
section_type = html.escape(str(section.get("type", "")))
|
||
aliases = [alias for alias, sid in PLEX_SECTIONS.items() if str(sid) == str(section.get("key", ""))]
|
||
alias_text = f" — aliases: <code>{html.escape(', '.join(aliases))}</code>" if aliases else ""
|
||
lines.append(f"- <code>{key}</code> — <b>{title}</b> ({section_type}){alias_text}")
|
||
|
||
if PLEX_SECTIONS:
|
||
lines.append("")
|
||
lines.append("<b>Configured aliases:</b>")
|
||
for alias, sid in PLEX_SECTIONS.items():
|
||
lines.append(f"- <code>{html.escape(alias)}</code> → section <code>{html.escape(str(sid))}</code>")
|
||
|
||
return "\n".join(lines)
|
||
|
||
def handle_plexscan(chat_id: str, text: str):
|
||
target = text.replace("/plexscan", "", 1).strip().lower()
|
||
|
||
if not target:
|
||
plex_refresh_all()
|
||
send_message(chat_id, "✅ <b>Plex scan started.</b>\n\n<b>Target:</b> all libraries")
|
||
return
|
||
|
||
section_id = PLEX_SECTIONS.get(target, target)
|
||
if not str(section_id).isdigit():
|
||
raise ValueError("Unknown Plex library alias. Use /plexlibs to view section IDs, then configure PLEX_SECTIONS or pass the numeric ID.")
|
||
|
||
plex_refresh_section(section_id)
|
||
send_message(
|
||
chat_id,
|
||
f"✅ <b>Plex scan started.</b>\n\n"
|
||
f"<b>Target:</b> <code>{html.escape(target)}</code>\n"
|
||
f"<b>Section ID:</b> <code>{html.escape(str(section_id))}</code>",
|
||
)
|
||
|
||
def parse_last_match(last_match: str) -> datetime.datetime | None:
|
||
"""Parse qBittorrent lastMatch like: 06 May 2026 16:16:48 +0000."""
|
||
if not last_match or not str(last_match).strip():
|
||
return None
|
||
|
||
try:
|
||
return datetime.datetime.strptime(str(last_match).strip(), "%d %b %Y %H:%M:%S %z")
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
def get_prunable_rules(days_after: int) -> list[dict[str, Any]]:
|
||
"""Return rules whose lastMatch is older than days_after.
|
||
|
||
Rules with blank or unparsable lastMatch are skipped for safety.
|
||
"""
|
||
rules = load_json(DOWNLOAD_RULES_PATH)
|
||
if not isinstance(rules, dict):
|
||
raise ValueError("download_rules.json must be a JSON object.")
|
||
|
||
now = datetime.datetime.now(datetime.timezone.utc)
|
||
prunable = []
|
||
|
||
for rule_name, rule in rules.items():
|
||
if not isinstance(rule, dict):
|
||
continue
|
||
|
||
last_match_raw = rule.get("lastMatch", "")
|
||
last_match_dt = parse_last_match(last_match_raw)
|
||
|
||
# Skip blank/unparseable lastMatch for safety.
|
||
if not last_match_dt:
|
||
continue
|
||
|
||
age_days = (now - last_match_dt.astimezone(datetime.timezone.utc)).days
|
||
|
||
if age_days >= days_after:
|
||
prunable.append({
|
||
"rule_name": rule_name,
|
||
"last_match": last_match_raw,
|
||
"age_days": age_days,
|
||
"mustContain": rule.get("mustContain", ""),
|
||
"savePath": rule.get("savePath", ""),
|
||
})
|
||
|
||
prunable.sort(key=lambda item: item["age_days"], reverse=True)
|
||
return prunable
|
||
|
||
|
||
def prune_preview_text(days_after: int, prunable: list[dict[str, Any]]) -> str:
|
||
if not prunable:
|
||
return (
|
||
f"✅ No rules found older than <b>{days_after}</b> day(s).\n\n"
|
||
"Rules with blank or unparsable <code>lastMatch</code> are skipped for safety."
|
||
)
|
||
|
||
lines = [
|
||
"🧹 <b>TorrentOps Prune Preview</b>",
|
||
"",
|
||
f"<b>Threshold:</b> {days_after} day(s)",
|
||
f"<b>Rules to remove:</b> {len(prunable)}",
|
||
"",
|
||
]
|
||
|
||
for item in prunable[:30]:
|
||
lines.append(
|
||
f"- <b>{html.escape(item['rule_name'])}</b>\n"
|
||
f" Age: <code>{item['age_days']} day(s)</code>\n"
|
||
f" Last match: <code>{html.escape(str(item['last_match']))}</code>\n"
|
||
f" Query: <code>{html.escape(str(item.get('mustContain', '')))}</code>"
|
||
)
|
||
|
||
if len(prunable) > 30:
|
||
lines.append(f"\n…and {len(prunable) - 30} more.")
|
||
|
||
lines.append(
|
||
"\nReply with:\n"
|
||
"<code>/prune_confirm</code> to back up and remove these rules\n"
|
||
"<code>/prune_cancel</code> to discard"
|
||
)
|
||
|
||
return "\n".join(lines)
|
||
|
||
|
||
def prepare_prune(chat_id: str, days_after: int | None = None):
|
||
days = int(days_after if days_after is not None else PRUNE_DAYS_AFTER)
|
||
if days < 1:
|
||
raise ValueError("Prune threshold must be at least 1 day.")
|
||
|
||
prunable = get_prunable_rules(days)
|
||
PENDING_PRUNES[chat_id] = {
|
||
"days_after": days,
|
||
"rule_names": [item["rule_name"] for item in prunable],
|
||
"created_at": datetime.datetime.now().isoformat(timespec="seconds"),
|
||
}
|
||
|
||
send_message(chat_id, prune_preview_text(days, prunable))
|
||
|
||
|
||
def confirm_prune(chat_id: str):
|
||
pending = PENDING_PRUNES.get(chat_id)
|
||
if not pending:
|
||
send_message(chat_id, "No pending prune. Use /prune first.")
|
||
return
|
||
|
||
rule_names = pending.get("rule_names", [])
|
||
days_after = pending.get("days_after", PRUNE_DAYS_AFTER)
|
||
|
||
if not rule_names:
|
||
del PENDING_PRUNES[chat_id]
|
||
send_message(chat_id, f"No rules to prune for threshold: <b>{days_after}</b> day(s).")
|
||
return
|
||
|
||
try:
|
||
rules = load_json(DOWNLOAD_RULES_PATH)
|
||
if not isinstance(rules, dict):
|
||
raise ValueError("download_rules.json must be a JSON object.")
|
||
|
||
backup = backup_file(DOWNLOAD_RULES_PATH) if BACKUP_RULES_JSON else None
|
||
|
||
removed = []
|
||
for rule_name in rule_names:
|
||
if rule_name in rules:
|
||
del rules[rule_name]
|
||
removed.append(rule_name)
|
||
|
||
write_json(DOWNLOAD_RULES_PATH, rules)
|
||
del PENDING_PRUNES[chat_id]
|
||
|
||
backup_line = f"\n<b>Backup:</b> <code>{html.escape(str(backup))}</code>" if backup else ""
|
||
send_message(
|
||
chat_id,
|
||
f"✅ <b>Prune complete.</b>\n\n"
|
||
f"<b>Threshold:</b> {days_after} day(s)\n"
|
||
f"<b>Removed:</b> {len(removed)} rule(s)"
|
||
f"{backup_line}"
|
||
)
|
||
except Exception as exc:
|
||
send_message(chat_id, f"⚠️ <b>Prune failed:</b>\n<code>{html.escape(str(exc))}</code>")
|
||
|
||
|
||
|
||
def status_text():
|
||
roots = ", ".join(f"{k}={v}" for k, v in DOWNLOAD_ROOTS.items()) or "None"
|
||
return (
|
||
"✅ <b>TorrentOps status</b>\n\n"
|
||
f"<b>qBittorrent:</b> <code>{html.escape(QBIT_HOST)}</code>\n"
|
||
f"<b>Rules path exists:</b> {'yes' if local_path(DOWNLOAD_RULES_PATH).exists() else 'no'}\n"
|
||
f"<b>Template path exists:</b> {'yes' if local_path(DOWNLOAD_TEMPLATE_PATH).exists() else 'no'}\n"
|
||
f"<b>Feeds path exists:</b> {'yes' if local_path(FEEDS_PATH).exists() else 'no'}\n"
|
||
f"<b>Download roots:</b> <code>{html.escape(roots)}</code>\n"
|
||
f"<b>Plex enabled:</b> {'yes' if PLEX_ENABLED else 'no'}\n"
|
||
f"<b>Plex URL:</b> <code>{html.escape(PLEX_BASE_URL)}</code>\n"
|
||
f"<b>Pending previews:</b> {len(PENDING_RULES)}\n"
|
||
f"<b>Pending prune previews:</b> {len(PENDING_PRUNES)}\n"
|
||
f"<b>Prune threshold:</b> {PRUNE_DAYS_AFTER} day(s)"
|
||
)
|
||
|
||
|
||
def help_text():
|
||
return (
|
||
"🌊 <b>TorrentOps</b>\n\n"
|
||
'<b>/add "name" "query" ["exclude"] season [root] feeds</b>\n'
|
||
'Example: <code>/add "Frieren" "Sousou no Frieren" 2 anime 5</code>\n'
|
||
'With exclusions: <code>/add "Ghost in the Shell" "Koukaku 265" "Dual Audio HEVC" 1 anime 7</code>\n\n'
|
||
"<b>/confirm</b> - apply pending preview\n"
|
||
"<b>/cancel</b> - discard pending preview\n"
|
||
"<b>/feeds [filter]</b> - list feeds\n"
|
||
"<b>/rules</b> - latest rules\n"
|
||
"<b>/current</b> - current quarter rules\n"
|
||
"<b>/search <text></b> - search rules\n"
|
||
"<b>/plexscan [alias_or_section_id]</b> - refresh Plex libraries\n"
|
||
"<b>/plexlibs</b> - list Plex libraries\n"
|
||
"<b>/rss</b> or <b>/rssupdate</b> - refresh all qBittorrent RSS feeds\n"
|
||
"<b>/prune [days]</b> - preview old rules to remove\n"
|
||
"<b>/prune_confirm</b> - back up and remove previewed rules\n"
|
||
"<b>/prune_cancel</b> - discard prune preview\n"
|
||
"<b>/status</b> - bot status\n"
|
||
"<b>/help</b> - this menu"
|
||
)
|
||
|
||
|
||
def handle_message(chat_id: str, text: str):
|
||
if not is_allowed(chat_id):
|
||
print(f"Ignored unauthorized chat_id: {chat_id}")
|
||
return
|
||
text = text.strip()
|
||
try:
|
||
if text.startswith("/start") or text.startswith("/help"):
|
||
send_message(chat_id, help_text())
|
||
elif text.startswith("/feeds"):
|
||
send_message(chat_id, feeds_text(text.replace("/feeds", "", 1).strip()))
|
||
elif text.startswith("/add"):
|
||
raw = text.replace("/add", "", 1).strip()
|
||
p = build_rule(*parse_add_args(raw))
|
||
try:
|
||
rules = load_json(DOWNLOAD_RULES_PATH)
|
||
if p["rule_name"] in rules:
|
||
send_message(chat_id, f"⚠️ Rule already exists: <code>{html.escape(p['rule_name'])}</code>")
|
||
return
|
||
except Exception:
|
||
pass
|
||
PENDING_RULES[chat_id] = p
|
||
if REQUIRE_CONFIRM:
|
||
send_message(chat_id, preview_text(p))
|
||
else:
|
||
confirm_rule(chat_id)
|
||
elif text.startswith("/confirm"):
|
||
confirm_rule(chat_id)
|
||
elif text.startswith("/cancel"):
|
||
if chat_id in PENDING_RULES:
|
||
del PENDING_RULES[chat_id]
|
||
send_message(chat_id, "🧹 Pending rule discarded.")
|
||
else:
|
||
send_message(chat_id, "No pending rule to cancel.")
|
||
elif text.startswith("/rules"):
|
||
send_message(chat_id, rules_text())
|
||
elif text.startswith("/current"):
|
||
send_message(chat_id, current_text())
|
||
elif text.startswith("/search"):
|
||
send_message(chat_id, search_text(text.replace("/search", "", 1).strip()))
|
||
elif text.startswith("/rssupdate") or text.startswith("/rss"):
|
||
handle_rss_update(chat_id)
|
||
elif text.startswith("/plexlibs"):
|
||
send_message(chat_id, format_plex_sections())
|
||
elif text.startswith("/plexscan"):
|
||
handle_plexscan(chat_id, text)
|
||
elif text.startswith("/prune_confirm"):
|
||
confirm_prune(chat_id)
|
||
elif text.startswith("/prune_cancel"):
|
||
if chat_id in PENDING_PRUNES:
|
||
del PENDING_PRUNES[chat_id]
|
||
send_message(chat_id, "🧹 Pending prune discarded.")
|
||
else:
|
||
send_message(chat_id, "No pending prune to cancel.")
|
||
elif text.startswith("/prune"):
|
||
raw_days = text.replace("/prune", "", 1).strip()
|
||
days = int(raw_days) if raw_days else PRUNE_DAYS_AFTER
|
||
prepare_prune(chat_id, days)
|
||
elif text.startswith("/status"):
|
||
send_message(chat_id, status_text())
|
||
else:
|
||
send_message(chat_id, "Unknown command. Send /help.")
|
||
except Exception as exc:
|
||
send_message(chat_id, f"⚠️ <b>Error:</b>\n<code>{html.escape(str(exc))}</code>")
|
||
|
||
|
||
def main():
|
||
if not TELEGRAM_BOT_TOKEN:
|
||
raise RuntimeError("Missing TELEGRAM_BOT_TOKEN in .env")
|
||
|
||
print("TorrentOps running.")
|
||
print(f"Allowed chat IDs: {TELEGRAM_ALLOWED_CHAT_IDS or 'ALL - not recommended'}")
|
||
print(f"qBittorrent host: {QBIT_HOST}")
|
||
|
||
offset = None
|
||
|
||
for chat_id in TELEGRAM_ALLOWED_CHAT_IDS:
|
||
try:
|
||
send_message(chat_id, "✅ TorrentOps started. Send /help.")
|
||
except Exception as exc:
|
||
print(f"Could not send startup message to {chat_id}: {exc}")
|
||
|
||
while True:
|
||
try:
|
||
payload = {"timeout": 10}
|
||
if offset is not None:
|
||
payload["offset"] = offset
|
||
|
||
updates = telegram_api("getUpdates", payload).get("result", [])
|
||
|
||
for update in updates:
|
||
offset = update["update_id"] + 1
|
||
message = update.get("message", {})
|
||
chat_id = str(message.get("chat", {}).get("id", ""))
|
||
text = message.get("text", "")
|
||
if chat_id and text:
|
||
handle_message(chat_id, text)
|
||
|
||
time.sleep(1)
|
||
except KeyboardInterrupt:
|
||
print("TorrentOps stopped.")
|
||
break
|
||
except Exception as exc:
|
||
print(f"Loop error: {exc}")
|
||
time.sleep(5)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|