277 lines
8.0 KiB
Python
Executable File
277 lines
8.0 KiB
Python
Executable File
#!/home/lucas/scripts/.venv/bin/python3
|
|
|
|
import argparse
|
|
import logging
|
|
import re
|
|
|
|
import requests
|
|
from requests.adapters import HTTPAdapter
|
|
from urllib3.util.retry import Retry
|
|
|
|
from serverlibrary import CustomLogger, parser_add_loglevel, setup_logging
|
|
|
|
logging.setLoggerClass(CustomLogger)
|
|
logger: CustomLogger = logging.getLogger(__name__) # type: ignore[assignment]
|
|
# ============================================================================
|
|
# CONFIG
|
|
# ============================================================================
|
|
ip_address = "192.168.0.4"
|
|
INSTANCES = [
|
|
{
|
|
"name": "whisparr",
|
|
"url": f"http://{ip_address}:6969",
|
|
"api_key": "3a5403b7a36f4e679398d959cdd39b1b",
|
|
},
|
|
{
|
|
"name": "radarr-de",
|
|
"url": f"http://{ip_address}:7879",
|
|
"api_key": "29f67f0ac8894357b22ea3f7fc1abfdf",
|
|
},
|
|
{
|
|
"name": "radarr-en",
|
|
"url": f"http://{ip_address}:7878",
|
|
"api_key": "4332aee075c748f2acee41aa26f06007",
|
|
},
|
|
{
|
|
"name": "sonarr-de",
|
|
"url": f"http://{ip_address}:8990",
|
|
"api_key": "707d4fcbb3d74822ba990c6a8b7278e9",
|
|
},
|
|
{
|
|
"name": "sonarr-en",
|
|
"url": f"http://{ip_address}:8989",
|
|
"api_key": "e2005c5c204840878f8eb37d1ac6aa0e",
|
|
},
|
|
{
|
|
"name": "lidarr",
|
|
"url": f"http://{ip_address}:8686",
|
|
"api_key": "bb41cbf2b17e439290f90ecfaeb24dff",
|
|
},
|
|
{
|
|
"name": "prowlarr",
|
|
"url": f"http://{ip_address}:9696",
|
|
"api_key": "317f5dd6c06446c6a352a621be607acb",
|
|
},
|
|
# {
|
|
# "name": "listenarr",
|
|
# "url": f"http://{ip_address}:7878",
|
|
# "api_key": "READARR_API_KEY",
|
|
# },
|
|
]
|
|
|
|
PRIVATE_CLIENT = "qbittorrent-private"
|
|
PUBLIC_CLIENT = "qbittorrent-public"
|
|
USENET_CLIENT = "rundfunkarr"
|
|
|
|
PRIVATE_INDEXER_REGEX = re.compile(
|
|
r"(BitTorrentFiles|Nordic\s*Quality|Fun\s*Zone|Seed\s*Core|The\s*Brothers|"
|
|
r"Porno\s*Lab|Golden\s*Gate|MV\s*Group|0DayFiles)",
|
|
re.IGNORECASE,
|
|
)
|
|
|
|
|
|
|
|
DRY_RUN = False
|
|
|
|
# ============================================================================
|
|
|
|
session = requests.Session()
|
|
|
|
retry_strategy = Retry(
|
|
total=3,
|
|
connect=3,
|
|
read=3,
|
|
backoff_factor=2,
|
|
status_forcelist=[429, 500, 502, 503, 504],
|
|
allowed_methods=["GET", "PUT", "POST"],
|
|
)
|
|
|
|
adapter = HTTPAdapter(max_retries=retry_strategy)
|
|
|
|
session.mount("http://", adapter)
|
|
session.mount("https://", adapter)
|
|
|
|
def get_api_version(base_url, api_key):
|
|
r = requests.get(
|
|
f"{base_url}/api",
|
|
headers={"X-Api-Key": api_key},
|
|
timeout=30,
|
|
)
|
|
r.raise_for_status()
|
|
return r.json()["current"]
|
|
|
|
|
|
def api_get(base_url, api_key, endpoint, retries=3):
|
|
|
|
for attempt in range(1, retries + 1):
|
|
try:
|
|
logger.trace(f"Call endpoint {endpoint}")
|
|
r = requests.get(
|
|
f"{base_url}{endpoint}",
|
|
headers={"X-Api-Key": api_key},
|
|
timeout=30,
|
|
)
|
|
r.raise_for_status()
|
|
return r.json()
|
|
|
|
except requests.HTTPError as e:
|
|
logger.info(f"Status: {e.response.status_code}")
|
|
logger.info(f"Response: {e.response.text}")
|
|
raise
|
|
except Exception as e:
|
|
logger.info(f"GET failed ({attempt}/{retries}): {e}")
|
|
raise
|
|
|
|
# if attempt < retries:
|
|
# time.sleep(2**attempt)
|
|
|
|
def api_put(base_url, api_key, endpoint, payload, retries=3):
|
|
for attempt in range(1, retries + 1):
|
|
try:
|
|
logger.trace(f"Put to endpoint: {endpoint}")
|
|
r = requests.put(
|
|
f"{base_url}{endpoint}",
|
|
headers={
|
|
"X-Api-Key": api_key,
|
|
"Content-Type": "application/json",
|
|
},
|
|
json=payload,
|
|
timeout=30,
|
|
)
|
|
r.raise_for_status()
|
|
return r.json() if r.content else None
|
|
except requests.HTTPError as e:
|
|
logger.info(f"Status: {e.response.status_code}")
|
|
logger.info(f"Response: {e.response.text}")
|
|
raise
|
|
except Exception as e:
|
|
logger.info(f"PUT failed ({attempt}/{retries}): {e}")
|
|
raise
|
|
|
|
# if attempt < retries:
|
|
# time.sleep(2**attempt)
|
|
|
|
|
|
def get_download_client_ids(base_url, endpoint, api_key) -> dict[str, dict[str, int]]:
|
|
clients = api_get(base_url, api_key, endpoint)
|
|
|
|
client_return = {
|
|
"torrent": {"private_id": -1, "public_id": -1},
|
|
"usenet": {"rundfunkarr_id": -1},
|
|
}
|
|
if not clients:
|
|
return client_return
|
|
|
|
for client in clients:
|
|
if client["protocol"].casefold() == "torrent" and client.get("removeCompletedDownloads") is True:
|
|
client["removeCompletedDownloads"] = False
|
|
if DRY_RUN:
|
|
logger.info(f"DRY {client['name']} -> removeCompletedDownloads=False")
|
|
else:
|
|
api_put(base_url, api_key, f"{endpoint}/{client['id']}", client)
|
|
logger.info(f"SET {client['name']} -> removeCompletedDownloads=False")
|
|
|
|
if client["name"].casefold() == PRIVATE_CLIENT:
|
|
client_return["torrent"]["private_id"] = int(client["id"])
|
|
|
|
if client["name"].casefold() == PUBLIC_CLIENT:
|
|
client_return["torrent"]["public_id"] = int(client["id"])
|
|
|
|
if USENET_CLIENT in client["name"].casefold():
|
|
client_return["usenet"]["rundfunkarr_id"] = int(client["id"])
|
|
|
|
return client_return
|
|
|
|
|
|
def process_instance(instance):
|
|
name = instance["name"]
|
|
url = instance["url"]
|
|
api_key = instance["api_key"]
|
|
|
|
logger.info(f"{'=' * 80}")
|
|
logger.info(f"Processing: {name}")
|
|
logger.info(f"{'=' * 80}")
|
|
|
|
api_version = get_api_version(url, api_key)
|
|
endpoint_download = f"/api/{api_version}/downloadclient"
|
|
|
|
client_ids = get_download_client_ids(url, endpoint_download, api_key)
|
|
private_id = client_ids["torrent"]["private_id"]
|
|
public_id = client_ids["torrent"]["public_id"]
|
|
rundfunkarr_id = client_ids["usenet"]["rundfunkarr_id"]
|
|
|
|
if private_id <= 0 or public_id <= 0:
|
|
logger.error(f"IDs found: {api_get(url, api_key, endpoint_download)}")
|
|
|
|
if private_id <= 0:
|
|
logger.error(f"ERROR: '{PRIVATE_CLIENT}' not found")
|
|
return
|
|
|
|
if public_id <= 0:
|
|
logger.error(f"ERROR: '{PUBLIC_CLIENT}' not found")
|
|
return
|
|
|
|
logger.info(f"{PRIVATE_CLIENT} id: {private_id}")
|
|
logger.info(f"{PUBLIC_CLIENT} id: {public_id}")
|
|
|
|
indexers = api_get(url, api_key, f"/api/{api_version}/indexer")
|
|
if not indexers:
|
|
return
|
|
for indexer in indexers:
|
|
idx_id = indexer["id"]
|
|
idx_name = indexer["name"]
|
|
logger.info(idx_name)
|
|
|
|
if idx_name.casefold().startswith(USENET_CLIENT) and rundfunkarr_id > 0:
|
|
target_id = rundfunkarr_id
|
|
target_name = USENET_CLIENT
|
|
elif PRIVATE_INDEXER_REGEX.search(idx_name):
|
|
target_id = private_id
|
|
target_name = PRIVATE_CLIENT
|
|
else:
|
|
target_id = public_id
|
|
target_name = PUBLIC_CLIENT
|
|
|
|
current_id = indexer.get("downloadClientId")
|
|
|
|
if current_id == target_id:
|
|
logger.info(f"SKIP {idx_name} -> {target_name}")
|
|
continue
|
|
|
|
indexer["downloadClientId"] = target_id
|
|
|
|
if DRY_RUN:
|
|
logger.info(f"DRY {idx_name} -> {target_name}")
|
|
continue
|
|
endpoint_indexer = f"/api/{api_version}/indexer/{idx_id}?forceSave=true"
|
|
|
|
try:
|
|
api_put(
|
|
url,
|
|
api_key,
|
|
endpoint_indexer,
|
|
indexer,
|
|
)
|
|
|
|
logger.info(f"SET {idx_name} -> {target_name}")
|
|
|
|
except Exception as e:
|
|
logger.error(f"FAIL {idx_name}: {e}")
|
|
raise
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(
|
|
description="Write settings for mediaarr indexers",
|
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
|
)
|
|
|
|
parser_add_loglevel(parser)
|
|
args = parser.parse_args()
|
|
setup_logging(args.log_level)
|
|
for instance in INSTANCES:
|
|
process_instance(instance)
|
|
|
|
if __name__ == "__main__":
|
|
main()
|