videoDownloadTGbot/instagram-downloader/app.py
vrubelroman 60312b0096
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 2m1s
refactor: общий модуль загрузчиков, классы ошибок, UX бота, тесты
Загрузчики:
- общий downloader_common (make_app): единый /download/stream, контракт
  ошибок {error, code}, X-Video-Title, workdir на запрос, потоковая отдача
- лимит 50 МБ до скачивания, noplaylist, killpg для зависших yt-dlp
- YouTube до 720p (tv_embedded → web,android → без кук), бюджет 300 с
- gunicorn gthread + семафор, конечные таймауты, healthcheck
- Yapfiles: разбор direct_link, страница входа → login_required

Бот:
- одна fetch_from_service вместо пяти, db.py (WAL, events)
- ошибки по классам и по-русски, очередь с «впереди N», лимит 3 на пользователя
- подпись с названием и автором; ссылка удаляется, видео не ответом —
  без цитаты «Удалённое сообщение»
- токен не пишется в лог, удалён мёртвый код выбора качества и broadcast.py
- admin_bot: /stat в HTML, тихие и сгруппированные алерты, гистерезис кук,
  рассылка с предпросмотром и только в личные чаты

Инфра: ротация логов, один образ на bot и admin_bot, теги SHA + latest,
gzip при передаче на прод. Тесты: 454 pytest, смоук на 18 проверок.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 12:37:01 +00:00

141 lines
7.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Instagram Video Downloader Service (yt-dlp Python API). Общая часть — downloader_common."""
import logging
import os
import shutil
import uuid
from pathlib import Path
import yt_dlp
from flask import jsonify
from downloader_common import (
DownloadError, DownloadResult, YdlLogCapture, base_ydl_opts, classify_error,
find_downloaded_file, make_app,
)
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
COOKIES_FILE = Path(os.getenv('INSTAGRAM_COOKIES_FILE', 'instagram_cookies.txt'))
# yt-dlp трактует cookiefile как read-write и при невалидной сессии сам стирает sessionid
# из jar'а на диске — однажды это молча уничтожило единственный экземпляр cookies. Поэтому
# yt-dlp всегда получает одноразовую копию. Фиксированное имя безопасно: сервис в один воркер.
COOKIES_SCRATCH = Path('/tmp/instagram_cookies_scratch.txt')
INSTAGRAM_COOKIE_TEST_URL = os.getenv(
'INSTAGRAM_COOKIE_TEST_URL',
'https://www.instagram.com/reel/Cvuh19eNWv_/', # стабильный публичный ролик (NASA)
)
def _read_cookie(name: str, cookies_file: Path = COOKIES_FILE) -> str | None:
"""Значение cookie `name` для instagram.com из Netscape-файла."""
try:
with open(cookies_file) as f:
for line in f:
if line.startswith('#') or not line.strip():
continue
parts = line.rstrip('\n').split('\t')
if len(parts) >= 7 and 'instagram' in parts[0].lower() and parts[5] == name:
return parts[6]
except OSError as e:
logger.warning(f'Не удалось прочитать cookies: {e}')
return None
def _has_instagram_sessionid(cookies_file: Path) -> bool:
"""Без sessionid yt-dlp считает сессию неавторизованной и всегда идёт анонимным путём —
тогда прод часами шлёт непонятный "rate-limit for accessing posts anonymously"."""
return _read_cookie('sessionid', cookies_file) is not None
def _cookie_opts() -> dict:
shutil.copy2(COOKIES_FILE, COOKIES_SCRATCH)
headers = {'Referer': 'https://www.instagram.com/', 'X-Requested-With': 'XMLHttpRequest'}
csrf = _read_cookie('csrftoken')
if csrf:
headers['X-CSRFToken'] = csrf
return {'cookiefile': str(COOKIES_SCRATCH), 'http_headers': headers}
def download_instagram(url: str, workdir: Path) -> DownloadResult:
"""Сначала с cookies, при неудаче — без них: протухшая сессия заставляет yt-dlp ходить
в API, который отдаёт 404, тогда как анонимный путь для публичных постов работает."""
modes = [True, False] if COOKIES_FILE.exists() else [False]
last_error: Exception | None = None
for use_cookies in modes:
log = YdlLogCapture('[IG]')
opts = {**base_ydl_opts(workdir, log), 'format': 'best'}
if use_cookies:
opts.update(_cookie_opts())
try:
with yt_dlp.YoutubeDL(opts) as ydl:
info = ydl.extract_info(url, download=True)
path = find_downloaded_file(workdir, log.text)
return DownloadResult(path, (info or {}).get('title') or path.stem)
except Exception as e:
last_error = e
code, _ = classify_error(str(e)) if not isinstance(e, DownloadError) else (e.code, 0)
logger.warning(f"Instagram {'с cookies' if use_cookies else 'без cookies'}: {code}: {e}")
if code in ('too_large', 'sensitive_content', 'unsupported_url'):
break
for f in workdir.iterdir():
f.unlink(missing_ok=True)
raise last_error or DownloadError('Неизвестная ошибка при скачивании с Instagram')
def _probe_extract(url: str, cookies_file: Path | None) -> tuple[bool, str]:
"""Метаданные без скачивания. Возвращает (получилось, текст ошибки)."""
opts = {'quiet': True, 'no_warnings': True, 'socket_timeout': 20, 'noplaylist': True}
# Своя одноразовая копия: /cookies/check идёт во второй нити параллельно со скачиванием,
# которое пользуется COOKIES_SCRATCH.
scratch = COOKIES_SCRATCH.with_name(f'{COOKIES_SCRATCH.stem}_check_{uuid.uuid4().hex[:8]}.txt')
if cookies_file is not None:
shutil.copy2(cookies_file, scratch)
opts.update({'cookiefile': str(scratch),
'http_headers': {'Referer': 'https://www.instagram.com/'}})
try:
with yt_dlp.YoutubeDL(opts) as ydl:
ydl.extract_info(url, download=False)
return True, ''
except Exception as e:
return False, str(e)
finally:
scratch.unlink(missing_ok=True)
def extra_routes(app):
@app.route('/cookies/check', methods=['POST'])
def cookies_check():
"""Способен ли сервис прямо сейчас скачать публичное видео.
Повторяет путь download_instagram: сначала с cookies, при неудаче — без. Если
cookies-путь сломан, а анонимный работает — для пользователя это не авария
(обновление cookies это не лечит), статус остаётся ok, причина — в detail.
"""
base = {'test_url': INSTAGRAM_COOKIE_TEST_URL}
if not COOKIES_FILE.exists():
return jsonify({**base, 'cookies_present': False, 'cookies_valid': None,
'status': 'no_cookies', 'detail': 'cookies file missing'}), 200
if not _has_instagram_sessionid(COOKIES_FILE):
return jsonify({**base, 'cookies_present': True, 'cookies_valid': False,
'status': 'cookies_incomplete',
'detail': 'в файле нет sessionid для instagram.com — это не рабочая '
'сессия, yt-dlp всегда идёт анонимным путём'}), 200
ok_with, err_with = _probe_extract(INSTAGRAM_COOKIE_TEST_URL, COOKIES_FILE)
if ok_with:
return jsonify({**base, 'cookies_present': True, 'cookies_valid': True,
'status': 'ok', 'detail': ''}), 200
ok_without, err_without = _probe_extract(INSTAGRAM_COOKIE_TEST_URL, None)
if ok_without:
return jsonify({**base, 'cookies_present': True, 'cookies_valid': None, 'status': 'ok',
'detail': f'cookies-путь сломан, но fallback без cookies работает: '
f'{err_with[-400:]}'}), 200
# Не работает и анонимный путь: однозначно валить на cookies нельзя — отдаём как есть.
return jsonify({**base, 'cookies_present': True, 'cookies_valid': None,
'status': 'extraction_failed', 'detail': err_without[-500:]}), 200
app = make_app('instagram', ('instagram.com',), download_instagram, extra_routes)
if __name__ == '__main__':
app.run(host=os.getenv('HOST', '0.0.0.0'), port=int(os.getenv('PORT', 5000)), debug=False)