Commit Graph
20 Commits
Author SHA1 Message Date
Mak5erandClaude Fable 5 caffc343af refactor: apply full-project audit — bug fixes, performance, deduplication
Full-codebase audit (149 raw findings, 57 verified and applied).

Fixes:
- download resume: recompute Range header per retry attempt; never resume
  preallocated multipart .part files (silent media corruption)
- inline sends: canonical error tail (rate-limit/queue-busy/timeout/failure)
  for all platforms; YouTube inline no longer strands tokens in
  'processing' for 6h
- admin mailing: exclude banned users; fix Telegram error-text matching
- middlewares: instantiate once and share across message/callback/inline
  so antiflood/ban state no longer fragments
- event loop: move ZIP compression, JSON state persistence, admin FS
  walks, PIL/ffmpeg/ffprobe work off the loop
- download queue: prune idle per-user scopes; cancelled leader releases
  joined duplicate requests
- worker subprocess: disable log sinks (stderr error protocol and log
  rotation no longer race the parent)
- third-party loggers route through app handlers instead of lastResort
- tiktok: fix mojibake reaction emoji; per-user settings in doc callback;
  per-URL locks for short-URL expansion; parallel photo-set downloads
- ci: fix broken yt-dlp auto-bump workflow baseline
- db: drop redundant analytics_events indexes (migration 000010)

Refactoring:
- services/inline/send_flow.py: shared inline delivery flow for all five
  platforms (~640 duplicated lines removed)
- services/media/audio_flow.py: shared MP3 pipeline (was duplicated 6x
  across youtube/youtube_inline/soundcloud/spotify)
- CobaltMediaService base + shared Cobalt response parsing
- services/platforms/ytdlp_helpers.py: shared yt-dlp scaffolding
- register_inline_send_handlers: one chosen_inline_result/callback
  registration factory for 8 handlers
- merge pinterest/threads single-media and media-group flows
- logging decorator factory; remove ~11 dead repository methods

Tests: 470 -> 518 passing, coverage 77.3% -> 80.9% (CI gate 74%).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-26 16:25:59 +03:00
Mak5er 635e50b407 feat(settings): add media quality & file options, ZIP multi-photo archives, and categorized /settings UI
- Add video_quality, as_document, audio_format, and file_button to user settings schema and Alembic migrations.
- Categorize /settings into Media & Quality, Appearance & Buttons, and Chat & Clean-up with dynamic back navigation.
- Implement strict document delivery with disable_content_type_detection=True to prevent Telegram video player fallback when as_document is ON.
- Add multi-photo ZIP archive packaging for photo carousels in as_document mode.
- Differentiate DB media file cache entries between video and document types (url#document vs url#video) to eliminate cache collisions.
- Hide redundant Download File inline button when as_document setting is active.
- Remove obsolete referral system (/ref command and links).
2026-07-22 13:18:09 +03:00
Mak5er be4016a8a3 perf: harden downloader and runtime lifecycle 2026-07-09 23:59:34 +03:00
Mak5er 9fdc5681d7 fix: resolve 'Too many open files' leak & handle cosmetic chat action errors gracefully 2026-07-08 21:41:02 +03:00
Mak5er bbb5af1643 fix(downloads): harden media download flows 2026-07-05 22:19:51 +03:00
Mak5er 62050a0f2c perf: comprehensive production audit and hardening (Phase 1-4)
43 files changed, 828 insertions, 408 deletions. Key changes:

== Phase 1 - Critical fixes ==
- Fix shared mutable state in ResilientDownloader (class-level _inflight_downloads)
- Add threading.Lock to request dedup (race condition on concurrent claims)
- Fix ban_middleware fail-closed: DB error -> fallback to 'active' instead of 'restricted'
- Fix COUNT(*) anti-pattern: 5 methods fetched entire user table into memory
- Remove 6 duplicated function definitions in user_messages.py (silent shadowing)
- Extract metadata from Cobalt responses (Instagram no longer discards descriptions)
- Add SSRF validation for COBALT_API_URL (private IP blocking, scheme enforcement)
- Docker: healthcheck, resource limits, restart: on-failure:5
- Fix migration crash-loop (try/except guardrails + dialect detection bug)

== Phase 2 - Performance hardening ==
- Exponential backoff+jitter in cobalt_client and retry_async_operation (removed 9 fixed delays)
- Add asyncio.wait_for timeouts to Instagram/Pinterest downloads
- TikTok preflight size check before download
- SQLAlchemy pool event listeners (perf metrics on checkout/overflow)
- DownloadedFile TTL cleanup (date_added index + daily cron cleanup)
- Per-request UUID request_id in ChatTrackerMiddleware for end-to-end tracing
- private_chat_guard caching (60s TTL, reduces Telegram API calls)
- Antiflood O(k) eviction instead of O(n) full scan
- TikTok: Semaphore(3)+sliding-window rate limiter instead of global asyncio.Lock

== Phase 3 - CI hardening ==
- CI: lint job (ruff + mypy), docker smoke tests migrations, --cov-fail-under=80
- Upgrade dependency-audit Python 3.12 -> 3.14
- Fix 7 '# type: ignore' decorators with ParamSpec
- Migration 000005: ix_analytics_events_user_id + ix_downloaded_files_date_added
- Race-condition tests for dedup, queue shutdown, per-user slots

== Phase 4 - Architecture ==
- .dockerignore (exclude .git, tests, __pycache__, .env from Docker image)
- Consolidate 3 FakeYoutubeDL/DummyYDL classes into conftest.py
- Extract _download_youtube_media() from 70-line closure
- BasePlatformMediaService ABC in services/platforms/__init__.py
- Remove empty profiling/ directory

Tests: 349 passed, 0 failed (4 skipped: PostgreSQL-dependent)
2026-06-16 01:01:06 +03:00
Mak5er 468ba2031b Improve bot onboarding and adaptive downloads 2026-05-27 17:33:59 +03:00
Mak5er 26b7873cd0 fix(concurrency): scope parallel media flows per chat
Scope download queue limits by user and chat so the same user can run downloads across multiple chats without tripping a shared pending cap.

Also coalesce concurrent single-media requests by cache key so duplicate links wait for the first upload and then reuse the cached Telegram file_id instead of downloading the same file again.
2026-04-10 19:22:04 +03:00
Mak5er 77c4cda0b8 Refactor logging paths and stabilize db tests 2026-04-10 00:42:21 +03:00
Mak5er 52d7b22208 fix: block download path traversal 2026-04-08 23:46:47 +03:00
Mak5er bb964728a7 refactor: organize services into domain subpackages 2026-04-07 01:08:39 +03:00
Mak5er 784aee9747 fix: harden inline delivery and bot runtime safeguards
- secure admin callbacks and inline token ownership checks
- stabilize private chat handoff and fail-soft user settings reads
- improve inline album previews with captions, photo file_ids, and API-safe payloads
- fix download manager dedup, resume validation, and size-limit propagation
- add regression coverage for admin, db, runtime, inline, and download flows
2026-04-06 23:07:26 +03:00
Mak5er b427dd5f2f Improve media caching and inline delivery 2026-03-22 02:38:33 +02:00
Mak5er 8adca9f43d Refactor inline delivery, cleanup dependencies, and overhaul logging
What changed:

- unified inline media delivery across TikTok, Instagram, Pinterest, SoundCloud, YouTube, and Twitter around a single editable-message flow with chosen-inline auto start and callback fallback

- added reusable inline request state/services, service icons, album deep links, and single-message inline progress/edit helpers

- enabled inline support for regular YouTube videos, Twitter inline media, and Twitter multi-photo album deep links; aligned Pinterest/Instagram/TikTok inline behaviors

- cleaned dead duplicated inline code, extracted shared inline request guards, and expanded tests around TikTok, Pinterest, SoundCloud, and YouTube handlers

- optimized project setup with trimmed runtime requirements, requirements-dev split, .dockerignore, Docker/compose improvements, and README updates

- rebuilt logging with structured context-aware adapters, request scoped flow decorators, JSONL event/perf logs, queue/download/cobalt timing events, and safer extra field sanitization to avoid LogRecord key collisions
2026-03-13 00:18:29 +02:00
mak5er 1aa4858059 feat: expand cobalt integrations and polish inline album UX
- add Pinterest handler via Cobalt with inline support and tests

- extract reusable Cobalt media helpers and inline album deeplink storage

- add public reusable album deep-links handled from /start without default welcome

- unify inline photo/album copy in user messages and ensure Powered by MaxLoad captions

- add single-photo inline behavior with info keyboard across Instagram/TikTok/Pinterest

- include related stats/service wiring updates and regression tests
2026-02-17 00:57:08 +02:00
mak5er a14785b5fa refactor: extract cobalt client and integrate instagram flow 2026-02-16 23:12:38 +02:00
mak5er 3bfbbe8df2 fixed bug with queues 2026-02-12 01:35:37 +02:00
mak5er 83b425393c feat: add adaptive download queue, retries, and session observability 2026-02-11 17:01:46 +02:00
mak5er c7fed30df2 Improve download UX: status, timeouts, caption truncation
- Add status messages (edit_text) + timeouts for YouTube/TikTok downloads\n- Fix TikTok slowness: short-url expansion timeout/cache, less global locking\n- Truncate captions to Telegram limits and escape HTML\n- Tune downloader concurrency and HTTP session connector\n- Update/add tests; pytest: 56 passed, 6 skipped
2026-02-11 01:08:16 +02:00
mak5er fcf75526cf Refactor YouTube handler to utilize a new resilient downloader
- Introduced a new `ResilientDownloader` class in `utils/download_manager.py` for improved download handling with support for HTTP range requests, retries, and resumable downloads.
- Updated `youtube.py` to replace the previous download logic with the new downloader, enhancing performance and reliability.
- Removed the old `download_manager.py` and `http_client.py` services, consolidating functionality into the `utils` directory.
- Adjusted download methods to log metrics and handle errors more effectively.
- Increased the maximum file size limit for downloads to 1.5 GB to accommodate larger media files.
- Improved handling of YouTube streams, including better fallback mechanisms for downloading media.
- Updated inline query handling for YouTube Shorts to use the new downloader.
2025-12-17 11:41:03 +02:00