Files
Downloader-Bot/services/storage/analytics_repository.py
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

89 lines
3.4 KiB
Python

from collections import defaultdict
from datetime import datetime, timedelta, timezone
from sqlalchemy import func, select
from services.storage.models import AnalyticsEvent, NON_DOWNLOAD_ACTIONS, StatsSnapshot
class AnalyticsRepositoryMixin:
@staticmethod
def _stats_period_start(period: str) -> datetime:
start_date = datetime.now(timezone.utc)
if period == "Week":
start_date -= timedelta(weeks=1)
elif period == "Month":
start_date -= timedelta(days=30)
elif period == "Year":
start_date -= timedelta(days=365)
return start_date
@staticmethod
def _normalize_stats_date(date_val) -> str:
if isinstance(date_val, str):
return datetime.strptime(date_val, "%Y-%m-%d").strftime("%Y-%m-%d")
return date_val.strftime("%Y-%m-%d")
async def get_download_stats(self, period: str) -> StatsSnapshot:
async with self.SessionLocal() as session:
start_date = self._stats_period_start(period)
result = await session.execute(
select(func.date(AnalyticsEvent.created_at), AnalyticsEvent.action_name, func.count())
.where(
AnalyticsEvent.created_at >= start_date,
AnalyticsEvent.action_name.notin_(NON_DOWNLOAD_ACTIONS),
)
.group_by(func.date(AnalyticsEvent.created_at), AnalyticsEvent.action_name)
.order_by(func.date(AnalyticsEvent.created_at))
)
totals_by_date: dict[str, int] = defaultdict(int)
by_service: dict[str, dict[str, int]] = defaultdict(dict)
service_totals: dict[str, int] = defaultdict(int)
total_downloads = 0
for date_val, action_name, count in result.all():
normalized = self._normalize_stats_date(date_val)
service = self._map_action_to_service(action_name)
totals_by_date[normalized] += count
by_service[service][normalized] = by_service[service].get(normalized, 0) + count
service_totals[service] += count
total_downloads += count
return StatsSnapshot(
totals_by_date=dict(totals_by_date),
by_service={service: dict(values) for service, values in by_service.items()},
service_totals=dict(service_totals),
total_downloads=total_downloads,
)
async def get_downloaded_files_count(self, period: str) -> dict[str, int]:
snapshot = await self.get_download_stats(period)
return snapshot.totals_by_date
@staticmethod
def _map_action_to_service(action_name: str) -> str:
lower = (action_name or "").lower()
if "tiktok" in lower:
return "TikTok"
if "instagram" in lower:
return "Instagram"
if "threads" in lower:
return "Threads"
if "youtube" in lower:
return "YouTube"
if "soundcloud" in lower:
return "SoundCloud"
if "spotify" in lower:
return "Spotify"
if "pinterest" in lower:
return "Pinterest"
if "twitter" in lower or "x_" in lower:
return "Twitter"
return "Other"
async def get_downloaded_files_by_service(self, period: str) -> dict[str, dict[str, int]]:
snapshot = await self.get_download_stats(period)
return snapshot.by_service