Commit graph

32 commits

Author SHA1 Message Date
vrubelroman
c9972f3d68 fix(cookies): не давать yt-dlp затирать мастер-файл кук, честнее алерты
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 52s
Реальный инцидент: cookies "протухли" за пару дней вместо ~года. Причина —
не срок годности, а сам yt-dlp: --cookies FILE читает И дописывает cookie
jar обратно в файл после каждого запуска (--help: "read cookies from and
dump cookie jar in"), а когда Instagram-экстрактор решает, что сессия
невалидна, он явно чистит sessionid из jar'а — и это тут же сохраняется на
диск через YoutubeDL.close(). Наш собственный health-check (каждые 30 мин)
и обычные скачивания медленно, но верно стирали себе рабочие cookies.

Фикс: yt-dlp больше никогда не видит мастер-файл, только одноразовую копию
в фиксированном /tmp-пути (безопасно — оба сервиса --workers=1, гонок нет).
Проверено: md5sum/mtime мастер-файлов не меняются ни после серии
/cookies/check, ни после реального /download/stream.

Заодно в bot.py: notify_admin_cookie_alert больше не заявляет "это НЕ
cookies" для extraction_failed — на практике это оказалось не всегда
верно (анонимный rate-limit тоже "не cookies" по факту, но валидная
сессия могла бы его обойти). В алерты добавлена проверяемая ссылка
(test_url из /cookies/check), чтобы сразу было видно, что это health-check
дёргает тестовый ролик, а не реальная ссылка пользователя. Новый статус
cookies_incomplete детектирует "файл есть, но sessionid нет" ещё до
сетевых проверок — ловит именно тот случай, что привёл к инциденту.

Отдельно: пользователю теперь показывается понятное сообщение, когда
Instagram сам блокирует контент как возрастной/чувствительный
("can't be seen by certain audiences") — вместо общего "Something went
wrong", раз повторная попытка всё равно не поможет. Админ по-прежнему
получает полный технический текст без изменений.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-31 15:18:13 +00:00
vrubelroman
d597a5e1c5 fix(downloaders): Deno runtime, свежий yt-dlp, честный health-check, смоук-тест
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 2m36s
Возрастные YouTube-видео не скачивались: с cookies yt-dlp отбрасывает клиент
android и остаётся web, которому нужно решить n-challenge, а в образе стоял
Node 20 при требуемом минимуме 22 ("JS runtimes: node-20.19.2 (unsupported)").
Ставим Deno — рекомендованный yt-dlp рантайм и один статический бинарник.

Instagram падал с "empty media response" одинаково с cookies и без них —
дело было не в сессии, а в устаревшем экстракторе: слой pip был закеширован
на yt-dlp 2026.06.09. Поднимаем нижнюю границу до 2026.7.4.

/cookies/check помечал проблемой с cookies ЛЮБОЙ сбой, из-за чего на поломку
JS-рантайма прилетел алерт про протухшие cookies и увёл разбор не туда.
Теперь ответ содержит status: ok | cookies_invalid | extraction_failed |
no_cookies, и админ-бот шлёт разные сообщения. Разбор ответа в bot.py
сохраняет совместимость со старым форматом без поля status.

Добавлен smoke_test.py — гоняет реальные ссылки (включая обе регрессии выше)
через запущенные сервисы и печатает таблицу. Запускать после каждой правки.

Схема получения cookies переведена с крона на разовый ручной экспорт:
cookies-cron/ -> cookies/, удалены скрипты с анти-паттерном
`--cookies-from-browser BROWSER --cookies FILE`, который wiki yt-dlp прямо
запрещает и который сам ломал YouTube-сессию ротацией. Ключевые cookies живут
около года, поэтому обновление по расписанию не нужно — триггером служит алерт
health-check. deliver_cookies.sh только доставляет файлы по scp.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 00:31:16 +00:00
vrubelroman
5092d882e5 feat(bot): proactive cookie health-check + simpler user-facing errors
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 51s
Add /cookies/check to youtube-downloader and instagram-downloader,
polled every 30 min from bot.py; alerts the admin bot on
healthy->broken transitions (with a 24h re-reminder cap while still
broken) and on recovery. Also stop leaking raw exception text to end
users - they now see a plain, friendly English message while the
admin bot still gets full technical detail via notify_admin_error.
2026-07-25 22:30:49 +00:00
vrubelroman
72ba00bdcd fix(youtube): retry without cookies on any yt-dlp failure, not just cookie-worded errors
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 50s
YouTube's SABR-only streaming rollout produces errors like "Signature
solving failed" / "Requested format is not available" that don't
mention cookies, so the existing no-cookies fallback never triggered.
Cookies also disable the android client, which is often the only one
still returning usable formats under this restriction.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-08 10:55:06 +00:00
vrubelroman
772e9fd5b4 chore: remove obsolete per-folder scripts, add cookies-cron reference, update docs
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 1m47s
- Remove get_cookies.sh (targets a container without yt-dlp, already
  broken), get_cookies_local.sh, start_all.sh/stop_all.sh — these
  implement the old per-service-compose startup that now conflicts
  with the unified root docker-compose.yml.
- Add cookies-cron/ — a reference copy of the scripts actually running
  via cron on the separate browser-equipped machine, with setup
  requirements and instructions for standing up a new cron host.
- Update README.md/ARCHITECTURE.md to describe the current unified
  docker-compose + CI/CD deploy flow and host-mounted cookies instead
  of the old per-folder workflow.
2026-06-30 22:16:40 +00:00
vrubelroman
b3550f4aaf fix(cookies): mount youtube/instagram cookies from host instead of baking into image
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 1m45s
Cookies baked into the image (COPY . .) required a full CI/CD rebuild
to refresh, incompatible with the cron job on the fedora machine that
re-extracts cookies from a logged-in browser every 20 minutes and
scp's them to prod. Volume-mount the cookies file instead — yt-dlp
reads it from disk per request, so a fresh scp takes effect
immediately with no container restart. The image-baked copy still
exists as a build-time fallback.

Also refresh the committed cookies snapshot (the cron's source yt-dlp
turned out to be missing on the fedora box, so prior commits had been
carrying years-stale cookies without anyone noticing).
2026-06-30 22:02:14 +00:00
vrubelroman
67dba21ff9 fix(youtube): correct extractor-args separator, soften worker recycling, retry video upload
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 1m53s
EXTRACTOR_ARGS used ':' instead of ';' between player_client and skip
fields, so yt-dlp parsed "android:skip=translated_subs" and "hls" as
bogus player_client values and silently fell back to the web client
only, which fails the n-challenge and returns no formats.

--max-requests=1 fully restarted the gunicorn worker after every
single request, opening a race window that could drop the response
connection right after a successful download; raised to 20 with
jitter to keep the periodic-recycle safety net without doing it on
every request.

reply_video() to Telegram had no retry, so a transient httpx
transport error during upload discarded an already-downloaded video;
added the same 3-attempt retry pattern already used for the
downloader services.
2026-06-30 20:24:46 +00:00
vrubelroman
4d575059b0 fix(youtube-downloader): subprocess yt-dlp CLI — bypass _ssl handshake timeout 2026-06-08 16:17:02 +00:00
vrubelroman
c4d4a77229 fix(downloader): chain fallback aria2c-curl-native + timeouts 2026-06-04 21:30:37 +00:00
vrubelroman
5d3cd92a03 fix: add vk.ru domain support for VK videos 2026-05-09 16:58:12 +03:00
vrubelroman
60a0373d7f fix: remove client-side format cache, prefer first audio track over largest 2026-05-03 17:43:24 +03:00
vrubelroman
c1d8a8235d fix: prefer Russian audio track, add FFmpegFixupStretched, remove broken h264_metadata bsf 2026-05-03 03:22:26 +03:00
vrubelroman
59b1c54668 fix: allow_unplayable_formats removed, reply_video, auto-select 480p, remove file sizes 2026-05-03 02:39:27 +03:00
vrubelroman
839cd57f6f fix: audio-only format, m4a/mp3 support, source URL in caption 2026-05-03 01:56:31 +03:00
vrubelroman
053f6c8afc fix: correct quality selection -- specific format_id first, exclude av01, validate video stream 2026-05-03 01:36:04 +03:00
vrubel
326eabaa99 Fix YouTube 500 error (n-challenge) and Telegram callback_data overflow 2026-04-30 17:21:10 +03:00
vrubelroman
4629535e97 fix: отправка видео как документ (без сжатия Telegram) и исправление format_id для точного выбора качества
- Замена reply_video() на reply_document() в bot.py — Telegram больше не сжимает видео
- Исправление format_id в get_youtube_formats(): конкретные format codes + fallback best[height<=N]
- Замена bestvideo[height<=N]+bestaudio на best[height<=N] — гарантированно работает когда
  YouTube не отдаёт отдельные video-only потоки для низких разрешений
- Добавлено логирование реально скачанного формата для диагностики
2026-04-30 01:36:43 +03:00
vrubelroman
4b7cc403b2 Implement file deletion after successful video sending in bot.py and update YouTube cookies for improved session management. 2026-01-10 22:26:18 +00:00
vrubelroman
551b64777a Update admin bot token, refine VK and Yapfiles URL handling, enhance Docker configuration for Instagram downloader, and improve YouTube downloader's cookie validation and error messaging. 2026-01-10 21:40:07 +00:00
vrubel
5c8456de96 Update .env.example with new admin bot token, modify Docker configuration for Instagram downloader to use host network mode, and enhance YouTube downloader with improved cookie validation and error handling for video downloads. 2026-01-08 19:05:41 +03:00
vrubel
e6c6734768 Enhance YouTube downloader with improved cookie validation and download strategies. Update cookie extraction script for better error handling and user feedback. 2025-12-25 21:38:13 +03:00
vrubel
9a64e1e6b8 вк япфайлс расширил домены 2025-12-25 00:09:47 +03:00
vrubel
88d753b84a Enhance YouTube video download functionality with improved error handling and format options. Update Docker configuration to use environment variable for port and simplify network settings. 2025-12-24 22:41:20 +03:00
vrubel
2d248b9ce0 add admin bot 2025-12-20 22:17:20 +03:00
vrubel
8a20b91c54 stats errors 2025-12-20 05:22:55 +03:00
vrubel
1c99e109b8 optimization scripts update coockies 2025-12-20 04:58:52 +03:00
vrubel
08c1cdf09c Add YouTube cookies to repository 2025-12-17 17:54:39 +03:00
vrubel
fdaaddff98 Improve YouTube cookies handling and script 2025-12-17 17:53:34 +03:00
vrubelroman
1e7f3be3f3 fix bug 2025-12-16 10:54:54 +03:00
vrubelroman
1a54f10ea2 добавили куки для ютуба 2025-12-16 10:15:50 +03:00
vrubelroman
76ce3feecc Добавлена система очередей для обработки загрузки видео, улучшена обработка ошибок и добавлены новые текстовые сообщения для пользователей. Обновлены таймауты HTTP-запросов для поддержки больших файлов. Обновлены конфигурации Docker для всех загрузчиков с использованием Gunicorn. 2025-12-12 15:41:46 +03:00
vrubelroman
436e0cd541 Рефакторинг: микросервисная архитектура
- Разделение на микросервисы: youtube-downloader, instagram-downloader, vk-downloader
- Основной бот в корне проекта, работает через HTTP API с сервисами
- Каждый сервис запускается отдельно в своей папке
- Видео сохраняются в папке video/ и не удаляются
- Обновлена документация и архитектура
- Скрипты для Instagram cookies перенесены в instagram-downloader/
2025-12-11 01:07:04 +03:00