#!/usr/bin/env python3 """Log the full length of the current page's video to Traggo as one finished span.""" import json import os import re import shlex import shutil import subprocess import sys import urllib.error import urllib.request from datetime import datetime, timedelta from html import unescape API = "https://time.rcjohnstone.com/graphql" TOKEN_PATH = os.path.expanduser("~/.config/traggo/token") TAGS = [ {"key": "language", "value": "spanish"}, {"key": "mode", "value": "listening"}, ] YTDLP_TIMEOUT = 45 HTTP_TIMEOUT = 20 UA = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/124.0.0.0 Safari/537.36") FIFO = os.environ.get("QUTE_FIFO") class ProbeError(Exception): pass def report(kind, text): text = " ".join(text.split()) line = "message-{} {}\n".format(kind, shlex.quote(text)) if FIFO: with open(FIFO, "a") as fh: fh.write(line) else: sys.stderr.write(line) def die(text): report("error", "traggo: " + text) sys.exit(1) def human(secs): hours, rem = divmod(secs, 3600) mins, s = divmod(rem, 60) if hours: return "{}h{:02d}m".format(hours, mins) if mins: return "{}m".format(mins) return "{}s".format(s) def ytdlp_argv(): local = shutil.which("yt-dlp") if local: return [local] # qutebrowser runs inside distrobox, so reach the host's copy if the container lacks one. host = shutil.which("distrobox-host-exec") if host: return [host, "yt-dlp"] raise ProbeError("yt-dlp not found") def probe_ytdlp(url): argv = ytdlp_argv() + [ "--skip-download", "--no-warnings", # We only ever want metadata, so a stale extractor failing on formats must not abort. "--ignore-no-formats-error", "--print", "%(duration)s|%(title)s", url, ] try: proc = subprocess.run(argv, capture_output=True, text=True, timeout=YTDLP_TIMEOUT) except subprocess.TimeoutExpired: raise ProbeError("yt-dlp timed out after {}s".format(YTDLP_TIMEOUT)) except OSError as exc: raise ProbeError("yt-dlp failed to start: {}".format(exc)) line = next((ln for ln in reversed(proc.stdout.splitlines()) if "|" in ln), "") if not line: detail = " ".join(proc.stderr.split())[:160] or "no output" raise ProbeError("yt-dlp: " + detail) raw, _, title = line.partition("|") raw = raw.strip() if not raw.isdigit() or int(raw) <= 0: raise ProbeError("yt-dlp gave no duration (got {!r})".format(raw)) return int(raw), title.strip() def probe_html(url): req = urllib.request.Request(url, headers={ "User-Agent": UA, "Accept-Language": "en-US,en;q=0.9"}) try: page = urllib.request.urlopen(req, timeout=HTTP_TIMEOUT).read().decode( "utf-8", "replace") except Exception as exc: raise ProbeError("page fetch failed: {}".format(exc)) match = re.search(r'"lengthSeconds":"(\d+)"', page) if not match: raise ProbeError("no lengthSeconds in page") secs = int(match.group(1)) if secs <= 0: raise ProbeError("page reported zero length") title = re.search(r'