diff --git a/app/app.py b/app/app.py index 1c486c7..372c532 100644 --- a/app/app.py +++ b/app/app.py @@ -468,7 +468,12 @@ async def search_torrent_by_id(torrent_id: str) -> dict: print(f"torapi-qbit fallback: got magnet hash {fb_hash[:10]}...") except Exception as fbe: print(f"torapi-qbit fallback failed: {fbe}") - + + # Если хэш всё ещё пустой — пропускаем этого провайдера + if not hash_value and not re.search(r'urn:btih:([a-fA-F0-9]{40}|[a-zA-Z0-9]{32})', magnet): + print(f"Skipping {provider_name}: no valid magnet hash") + continue + # Парсим результат в стандартный формат torrent = { "title": torrent_name, @@ -1131,7 +1136,7 @@ async def torrents_page(request: Request, movie_title: str, year: str = None): ) @app.post("/api/add-torrent") -async def add_torrent_to_client(torrent_id: str = Form(...)): +async def add_torrent_to_client(torrent_id: str = Form(...), magnet: str = Form(""), torrent_title: str = Form("")): """Добавление торрента в qBittorrent через прямое API""" try: print(f"Attempting to add torrent with ID: {torrent_id}") @@ -1139,10 +1144,21 @@ async def add_torrent_to_client(torrent_id: str = Form(...)): if not torrent_id or torrent_id.strip() == '': return {"status": "error", "message": "ID торрента не указан"} - # Получаем информацию о торренте по ID - torrent_info = await search_torrent_by_id(torrent_id) + # Если magnet передан напрямую (из результатов поиска), используем его + if magnet and magnet.startswith('magnet:'): + print(f"Using direct magnet link: {magnet[:100]}...") + torrent_info = { + "title": torrent_title or torrent_id, + "hash": "", + "magnet": magnet, + "torrent_url": "" + } + else: + # Fallback: ищем по ID через TorAPI + torrent_info = await search_torrent_by_id(torrent_id) + if not torrent_info: - print(f"Torrent info is None for ID: {torrent_id}") + print(f"Torrent info not found for ID: {torrent_id}") return {"status": "error", "message": f"Торрент с ID {torrent_id} не найден. Проверьте логи для деталей."} print(f"Found torrent info: title={torrent_info.get('title', 'Unknown')[:50]}, magnet={'present' if torrent_info.get('magnet') else 'missing'}, torrent_url={'present' if torrent_info.get('torrent_url') else 'missing'}") @@ -1225,13 +1241,42 @@ async def add_torrent_to_client(torrent_id: str = Form(...)): if torrent_url: print(f"Trying to add via .torrent file: {torrent_url}") - add_response = await client.post( - f"{qb_url}/api/v2/torrents/add", - data={"urls": torrent_url} - ) - print(f"Add via .torrent response status: {add_response.status_code}") - print(f"Add via .torrent response text: {add_response.text}") + # Сначала пробуем скачать .torrent через NL-прокси (обходит DPI) + try: + proxy_base = os.getenv("TMDB_PROXY_URL", "http://localhost:8001") + print(f"Downloading .torrent via NL proxy: {proxy_base}/proxy-torrent") + proxy_resp = await client.get( + f"{proxy_base}/proxy-torrent", + params={"url": torrent_url}, + timeout=30.0 + ) + if proxy_resp.status_code == 200: + torrent_content = proxy_resp.content + print(f"Downloaded .torrent via NL proxy: {len(torrent_content)} bytes") + + # Загружаем файл в qBittorrent + add_response = await client.post( + f"{qb_url}/api/v2/torrents/add", + files={"torrents": ("torrent.torrent", torrent_content, "application/x-bittorrent")} + ) + print(f"Add via .torrent file upload response: {add_response.status_code} - {add_response.text}") + else: + print(f"NL proxy failed: {proxy_resp.status_code}, sending URL directly to qBittorrent") + add_response = await client.post( + f"{qb_url}/api/v2/torrents/add", + data={"urls": torrent_url} + ) + print(f"Add via .torrent response status: {add_response.status_code}") + print(f"Add via .torrent response text: {add_response.text}") + except Exception as proxy_err: + print(f"NL proxy error: {proxy_err}, falling back to direct URL") + add_response = await client.post( + f"{qb_url}/api/v2/torrents/add", + data={"urls": torrent_url} + ) + print(f"Add via .torrent response status: {add_response.status_code}") + print(f"Add via .torrent response text: {add_response.text}") if add_response.status_code == 200 and add_response.text.strip() == "Ok.": # Проверяем, что торрент действительно добавился diff --git a/app/templates/torrents.html b/app/templates/torrents.html index d1afc0a..ecc9bf9 100644 --- a/app/templates/torrents.html +++ b/app/templates/torrents.html @@ -215,7 +215,7 @@
Magnet Скачать .torrent - +
{% endfor %} @@ -228,16 +228,18 @@