fix: pass magnet link directly to add-torrent API, avoid search_by_id lookup

This commit is contained in:
vrubelroman 2026-06-03 10:49:29 +00:00
parent b971294909
commit fb2aa5a60a
2 changed files with 62 additions and 15 deletions

View file

@ -469,6 +469,11 @@ async def search_torrent_by_id(torrent_id: str) -> dict:
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
# Если 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,11 +1241,40 @@ async def add_torrent_to_client(torrent_id: str = Form(...)):
if torrent_url:
print(f"Trying to add via .torrent file: {torrent_url}")
# Сначала пробуем скачать .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}")

View file

@ -215,7 +215,7 @@
<div class="torrent-actions">
<a href="{{ torrent.magnet }}" class="btn btn-primary">Magnet</a>
<a href="{{ torrent.download_url }}" class="btn btn-success">Скачать .torrent</a>
<button onclick="addToTorrentClient('{{ torrent.id }}')" class="btn btn-secondary">Добавить в клиент</button>
<button onclick="addToTorrentClient('{{ torrent.id }}', '{{ torrent.magnet|e }}', '{{ torrent.title|e }}')" class="btn btn-secondary">Добавить в клиент</button>
</div>
</div>
{% endfor %}
@ -228,16 +228,18 @@
</div>
<script>
function addToTorrentClient(torrentId) {
function addToTorrentClient(torrentId, magnet, title) {
// Показываем индикатор загрузки
const button = event.target;
const originalText = button.textContent;
button.textContent = '⏳ Получаем magnet...';
button.textContent = '⏳ Добавляем...';
button.disabled = true;
// Отправляем ID торрента для получения magnet-ссылки
// Отправляем ID + magnet + название
const formData = new FormData();
formData.append('torrent_id', torrentId);
formData.append('magnet', magnet || '');
formData.append('torrent_title', title || '');
fetch('/api/add-torrent', {
method: 'POST',