# -*- coding: utf-8 -*- """Clip retention: materials must not stay on disk longer than 48h. Policy: 1) Prefer using clips to fill remaining platform quotas (accelerate upload_at) 2) Then delete files older than max_age_hours and clear job clip_path when safe """ from __future__ import annotations import time from pathlib import Path from typing import Any from .config import settings _DEFAULT_MAX_AGE_H = 48.0 def _max_age_sec(cfg: dict[str, Any]) -> float: try: h = float(cfg.get("clips_max_age_hours") or _DEFAULT_MAX_AGE_H) except Exception: h = _DEFAULT_MAX_AGE_H return max(1.0, min(168.0, h)) * 3600.0 def _iter_clip_files() -> list[Path]: root = Path(settings.clips_dir) out: list[Path] = [] if not root.is_dir(): return out for p in root.rglob("*.mp4"): try: if p.is_file(): out.append(p) except OSError: continue return out def _accelerate_jobs_for_path(path: str, now: float) -> int: from . import db n = 0 soon = now + 30.0 updates = ( ( "shorts_jobs", "UPDATE shorts_jobs SET upload_at = ?, updated_at = ?, error = 'retention_rush' " "WHERE clip_path = ? AND status IN ('recorded','scheduled') AND IFNULL(youtube_video_id,'') = ''", ), ( "tiktok_jobs", "UPDATE tiktok_jobs SET upload_at = ?, updated_at = ?, error = 'retention_rush' " "WHERE clip_path = ? AND status IN ('recorded','scheduled') AND IFNULL(tiktok_video_id,'') = ''", ), ( "x_clip_jobs", "UPDATE x_clip_jobs SET upload_at = ?, updated_at = ?, error = 'retention_rush' " "WHERE clip_path = ? AND status IN ('recorded','scheduled') AND IFNULL(tweet_id,'') = ''", ), ( "yt_long_jobs", "UPDATE yt_long_jobs SET upload_at = ?, updated_at = ?, error = 'retention_rush' " "WHERE clip_path = ? AND status IN ('recorded','scheduled') AND IFNULL(youtube_video_id,'') = ''", ), ) try: with db._lock: conn = db._connect() try: for _name, sql in updates: try: cur = conn.execute(sql, (soon, now, path)) n += int(cur.rowcount or 0) except Exception: continue conn.commit() finally: conn.close() except Exception: pass return n def _clear_path_refs(path: str, now: float) -> None: from . import db try: with db._lock: conn = db._connect() try: for table in ("shorts_jobs", "tiktok_jobs", "x_clip_jobs", "yt_long_jobs"): try: conn.execute( f"UPDATE {table} SET clip_path = '', updated_at = ? WHERE clip_path = ?", (now, path), ) except Exception: continue conn.commit() finally: conn.close() except Exception: pass def _job_still_needs_file(path: str) -> bool: from . import db checks = ( "SELECT 1 FROM shorts_jobs WHERE clip_path=? AND status IN ('uploading','recording') LIMIT 1", "SELECT 1 FROM tiktok_jobs WHERE clip_path=? AND status IN ('uploading','recording') LIMIT 1", "SELECT 1 FROM x_clip_jobs WHERE clip_path=? AND status IN ('posting','recording') LIMIT 1", "SELECT 1 FROM yt_long_jobs WHERE clip_path=? AND status IN ('uploading','recording') LIMIT 1", ) try: with db._lock: conn = db._connect() try: for sql in checks: try: if conn.execute(sql, (path,)).fetchone(): return True except Exception: continue finally: conn.close() except Exception: return True return False def purge_stale_clips(cfg: dict[str, Any] | None = None) -> dict[str, Any]: """Rush pending uploads for old clips, then delete files older than retention window.""" from . import db settings_map = cfg if cfg is not None else db.get_settings_map() max_age = _max_age_sec(settings_map) now = time.time() rushed = 0 deleted = 0 skipped_inflight = 0 examined = 0 for path in _iter_clip_files(): examined += 1 try: mtime = path.stat().st_mtime except OSError: continue age = now - mtime if age < max_age * 0.85: continue variants = {str(path)} try: variants.add(str(path.resolve())) except OSError: pass if age < max_age: for sp in variants: rushed += _accelerate_jobs_for_path(sp, now) continue if any(_job_still_needs_file(sp) for sp in variants): skipped_inflight += 1 continue for sp in variants: _accelerate_jobs_for_path(sp, now) try: path.unlink(missing_ok=True) deleted += 1 for sp in variants: _clear_path_refs(sp, now) except OSError: continue return { "ok": True, "examined": examined, "rushed": rushed, "deleted": deleted, "skipped_inflight": skipped_inflight, "max_age_hours": max_age / 3600.0, }