Personal entertainment-media skills for NanoClaw: Trakt watch-history sync, TV-show and audiobook recommendations, watchlist release checks, YouTube channel-comment digests, and Audible backup — with a weekly cadence companion. NanoClaw per-chat overlay tile.
91%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
Low
Low-risk findings worth noting
#!/usr/bin/env python3
"""Upload and schedule one Short from a OneCLI-enabled NanoClaw container.
Arguments: --video and --thumbnail are local files (JPEG/PNG thumbnail).
Pass --title, --description, literal --tag values (repeat for multiple tags),
and --publish-at (future RFC 3339 instant, at whole-second precision).
OneCLI supplies OAuth and enforces its existing approvals. Do not modify the
input files during the run or approve a pending upload after its publish time.
Stdout on success: JSON with id, privacyStatus and publishAt from the read-back
(id is obtained from the upload and matched to the read-back).
Exit 0 confirms the API schedule and thumbnail request, not public release.
Exit 1 prints JSON with error and, if known, id and the last observed status
fields, with a diagnostic on stderr. Exit 2 means invalid CLI usage/input.
The script never starts a second session to recover an interrupted upload.
"""
import argparse
import hashlib
import json
import os
import re
import sys
from datetime import UTC, datetime
from email.message import Message
from email.utils import parsedate_to_datetime
from http.client import HTTPException
from pathlib import Path
from tempfile import NamedTemporaryFile
from time import sleep
from typing import BinaryIO
from urllib.error import HTTPError
from urllib.parse import parse_qs, urlencode, urlsplit
from urllib.request import (
HTTPRedirectHandler,
OpenerDirector,
ProxyHandler,
Request,
build_opener,
getproxies,
proxy_bypass,
)
HOST = "www.googleapis.com"
ORIGIN = f"https://{HOST}"
UPLOAD_PATH = "/upload/youtube/v3/videos"
TIMEOUT_SECONDS = 120 # A media PUT can wait on the existing OneCLI approval.
VIDEO_TYPE = "application/octet-stream"
class UploadError(Exception):
"""An actionable diagnostic safe to report without raw provider data."""
class NoRedirect(HTTPRedirectHandler):
# A redirect must never forward OAuth, media or the resumable session URL.
def http_error_302(self, req, fp, code, msg, headers):
# Stop before urllib parses Location. The resumable state machine still
# receives 308 and its Range header as an ordinary status response.
raise HTTPError(req.full_url, code, "Redirect not followed", headers, fp)
http_error_301 = http_error_303 = http_error_307 = http_error_308 = http_error_302
def request(
opener: OpenerDirector,
method: str,
url: str,
data: bytes | BinaryIO | None = None,
**headers: str,
) -> tuple[int, Message, bytes]:
req = Request(
url, data=data, method=method, headers={"Authorization": "Bearer onecli-managed", **headers}
)
try:
with opener.open(req, timeout=TIMEOUT_SECONDS) as response:
return response.status, response.headers, response.read()
except HTTPError as exc:
with exc:
return exc.code, exc.headers, b""
except ValueError:
raise UploadError("The gateway request could not be constructed.") from None
def api_call(
opener: OpenerDirector,
operation: str,
method: str,
url: str,
data: bytes | BinaryIO | None = None,
**headers: str,
) -> tuple[Message, bytes]:
try:
status, response_headers, body = request(opener, method, url, data, **headers)
except (OSError, HTTPException) as exc:
raise UploadError(f"{operation} did not respond. Check the OneCLI gateway.") from exc
if status != 200:
raise UploadError(f"{operation} returned HTTP {status}. Check OneCLI and YouTube access.")
return response_headers, body
def json_object(body: bytes, operation: str) -> dict:
try:
payload = json.loads(body)
except (ValueError, RecursionError) as exc:
raise UploadError(f"{operation} returned unreadable JSON.") from exc
if not isinstance(payload, dict):
raise UploadError(f"{operation} did not return a JSON object.")
return payload
def session_url(locations: list[str]) -> str:
if len(locations) == 1:
location = locations[0]
# urlsplit normalizes some control characters, so reject them before parsing.
if re.fullmatch(r"[!-~]+", location) and not any(c in location for c in ("\\", "#")):
try:
parts = urlsplit(location)
except ValueError:
pass
else:
upload_ids = parse_qs(parts.query, keep_blank_values=True).get("upload_id", [])
if (
(parts.scheme, parts.netloc, parts.path) == ("https", HOST, UPLOAD_PATH)
and len(upload_ids) == 1
and upload_ids[0]
):
return location
raise UploadError("YouTube returned a missing or unsafe upload session URL. No video was sent.")
def wait_to_resume(headers: Message, publish_at: datetime) -> None:
values = headers.get_all("Retry-After", [])
if not values:
return
if len(values) != 1:
raise UploadError("YouTube returned multiple Retry-After values.")
retry_after = values[0]
now = datetime.now(UTC)
try:
delay = (
int(retry_after)
if re.fullmatch(r"[0-9]{1,9}", retry_after)
else max(0, (parsedate_to_datetime(retry_after) - now).total_seconds())
)
except (TypeError, ValueError, OverflowError) as exc:
raise UploadError("YouTube returned an invalid Retry-After value.") from exc
if delay > 120 or delay >= (publish_at - now).total_seconds():
raise UploadError("YouTube requested a retry outside the allowed upload window.")
sleep(delay)
def upload_video(
opener: OpenerDirector, session: str, video: BinaryIO, size: int, publish_at: datetime
) -> str:
offset = 0
try:
for attempt in range(2):
if publish_at <= datetime.now(UTC):
raise UploadError("The requested publish time has passed.")
video.seek(offset)
try:
media_headers = {"Content-Type": VIDEO_TYPE, "Content-Length": str(size - offset)}
if offset:
media_headers["Content-Range"] = f"bytes {offset}-{size - 1}/{size}"
response = request(opener, "PUT", session, video, **media_headers)
except (OSError, HTTPException):
response = None
if response is None or response[0] in (500, 502, 503, 504):
if response is not None and response[1].get("Retry-After"):
raise UploadError(f"Media PUT returned HTTP {response[0]} with Retry-After.")
# A lost response (including a timed-out approval) is not a failed upload.
# Probe only the original session without sending any media.
response = request(
opener,
"PUT",
session,
b"",
**{"Content-Length": "0", "Content-Range": f"bytes */{size}"},
)
status, headers, body = response
if status in (200, 201):
video_id = json_object(body, "Media PUT").get("id")
if isinstance(video_id, str) and re.fullmatch(r"[A-Za-z0-9_-]+", video_id):
return video_id
raise UploadError("Media PUT did not return a video ID.")
if status != 308:
raise UploadError(f"Upload session returned HTTP {status}.")
ranges = headers.get_all("Range", [])
match = re.fullmatch(r"bytes=0-([0-9]{1,12})", ranges[0]) if len(ranges) == 1 else None
next_byte = int(match[1]) + 1 if match else 0
# No progress can also mean the original PUT is still waiting for approval.
if attempt or not offset < next_byte < size:
raise UploadError("The upload session is incomplete and could not be resumed.")
wait_to_resume(headers, publish_at)
offset = next_byte
except (OSError, HTTPException, UploadError) as exc:
detail = str(exc) if isinstance(exc, UploadError) else "Upload session did not respond."
raise UploadError(
f"{detail} Check OneCLI approvals and YouTube Studio before starting another upload."
) from exc
raise AssertionError("Upload loop must return or fail")
def read_schedule(opener: OpenerDirector, result: dict, publish_at: datetime) -> dict:
query = urlencode({"part": "status,processingDetails", "id": result["id"]})
_, body = api_call(opener, "videos.list", "GET", f"{ORIGIN}/youtube/v3/videos?{query}")
items = json_object(body, "videos.list").get("items")
if not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict):
raise UploadError("videos.list did not return the uploaded video.")
item = items[0]
if item.get("id") != result["id"] or not isinstance(item.get("status"), dict):
raise UploadError("videos.list did not return status for the uploaded video.")
status = item["status"]
privacy = status.get("privacyStatus")
timestamp = status.get("publishAt")
try:
observed_time = datetime.fromisoformat(timestamp)
except (TypeError, ValueError):
observed_time = None
result["privacyStatus"] = privacy if privacy in ("private", "unlisted", "public") else None
result["publishAt"] = timestamp if observed_time is not None else None
if privacy != "private" or observed_time != publish_at:
raise UploadError("YouTube did not confirm the requested private schedule.")
return item
def finish_video(
opener: OpenerDirector, result: dict, publish_at: datetime, thumb: BinaryIO, thumb_type: str
) -> None:
for attempt in range(13):
if attempt:
sleep(10)
item = read_schedule(opener, result, publish_at)
processing = item.get("processingDetails")
processing_status = (
processing.get("processingStatus") if isinstance(processing, dict) else None
)
if processing_status == "succeeded":
break
if processing_status in ("failed", "terminated"):
raise UploadError("YouTube did not process the uploaded video successfully.")
else:
raise UploadError("YouTube is still processing the Short. Set its thumbnail in Studio.")
query = urlencode({"uploadType": "media", "videoId": result["id"]})
_, body = api_call(
opener,
"thumbnails.set",
"POST",
f"{ORIGIN}/upload/youtube/v3/thumbnails/set?{query}",
thumb,
**{"Content-Type": thumb_type, "Content-Length": str(os.fstat(thumb.fileno()).st_size)},
)
items = json_object(body, "thumbnails.set").get("items")
if not isinstance(items, list) or not any(
isinstance(item, dict)
and any(
isinstance(thumbnail, dict)
and isinstance(thumbnail.get("url"), str)
and thumbnail["url"].startswith("https://")
for thumbnail in item.values()
)
for item in items
):
raise UploadError("YouTube did not confirm the thumbnail.")
RECEIPT_DIR = Path("/workspace/group/youtube-upload-receipts")
def operation_receipt(metadata: dict, video: BinaryIO, thumb: BinaryIO) -> Path:
key = hashlib.sha256(json.dumps(metadata, sort_keys=True).encode())
for file in (video, thumb):
digest = hashlib.sha256()
while chunk := file.read(1024 * 1024):
digest.update(chunk)
key.update(digest.digest())
file.seek(0)
return RECEIPT_DIR / f"{key.hexdigest()}.json"
def save_receipt(path: Path, status: str, result: dict) -> None:
with NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent, delete=False) as temporary:
pending = Path(temporary.name)
try:
json.dump({"schema_version": 1, "status": status, "result": result}, temporary)
temporary.flush()
os.fsync(temporary.fileno())
os.replace(pending, path)
finally:
pending.unlink(missing_ok=True)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Upload and schedule one Short.", allow_abbrev=False
)
parser.add_argument("--video", type=Path, required=True)
parser.add_argument("--thumbnail", type=Path, required=True)
parser.add_argument("--title", required=True)
parser.add_argument("--description", required=True)
parser.add_argument("--tag", action="append", required=True)
parser.add_argument("--publish-at", required=True)
args = parser.parse_args(argv)
try:
if not re.fullmatch(
r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}"
r"(?:Z|[+-](?:[01][0-9]|2[0-3]):[0-5][0-9])",
args.publish_at,
):
raise ValueError
publish_at = datetime.fromisoformat(args.publish_at).astimezone(UTC)
except (ValueError, OverflowError):
parser.error("--publish-at must be an RFC 3339 timestamp with seconds and a time zone")
if not args.title.strip() or any(not tag.strip() for tag in args.tag):
parser.error("--title and each --tag must be nonempty")
thumb_type = {".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png"}.get(
args.thumbnail.suffix.lower()
)
if not thumb_type or not args.thumbnail.is_file() or not args.video.is_file():
parser.error("provide an existing video file and a .jpg, .jpeg or .png thumbnail file")
result = {}
try:
proxies = getproxies()
if not proxies.get("https") or proxy_bypass(HOST):
raise UploadError("The OneCLI HTTPS proxy is required and must route the YouTube host.")
try:
proxy = urlsplit(proxies["https"])
if proxy.scheme != "http" or not proxy.hostname or proxy.port == 0:
raise ValueError
except ValueError:
raise UploadError("The OneCLI HTTPS proxy address is invalid.") from None
opener = build_opener(ProxyHandler(proxies), NoRedirect())
with args.video.open("rb") as video, args.thumbnail.open("rb") as thumb:
size = os.fstat(video.fileno()).st_size
if not size or not os.fstat(thumb.fileno()).st_size:
parser.error("the video and thumbnail files must not be empty")
metadata = {
"snippet": {
"title": args.title,
"description": args.description,
"tags": args.tag,
"categoryId": "22", # People & Blogs, the default in YouTube's upload example.
},
"status": {
"privacyStatus": "private",
"publishAt": publish_at.isoformat().replace("+00:00", "Z"),
"selfDeclaredMadeForKids": False,
},
}
receipt = operation_receipt(metadata, video, thumb)
past_schedule = (
"--publish-at must be in the future (YouTube publishes past times immediately)"
)
if publish_at <= datetime.now(UTC) and not receipt.exists():
parser.error(past_schedule)
receipt.parent.mkdir(mode=0o700, exist_ok=True)
try:
descriptor = os.open(receipt, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
except FileExistsError:
try:
saved = json_object(receipt.read_bytes(), "Upload receipt")
if saved.get("schema_version") == 1:
recorded = saved.get("result")
if isinstance(recorded, dict):
video_id = recorded.get("id")
if isinstance(video_id, str) and re.fullmatch(
r"[A-Za-z0-9_-]+", video_id
):
result["id"] = video_id
except (OSError, UploadError):
saved = {}
if (
saved.get("schema_version") == 1
and saved.get("status") == "complete"
and "id" in result
):
read_schedule(opener, result, publish_at)
print(json.dumps(result))
return 0
raise UploadError(
"An upload is already recorded. Reconcile it in YouTube Studio."
) from None
os.close(descriptor)
if publish_at <= datetime.now(UTC):
receipt.unlink()
parser.error(past_schedule)
# Claim before the first write to YouTube. An interrupted local write
# still leaves a claim that refuses another videos.insert.
save_receipt(receipt, "pending", result)
headers, _ = api_call(
opener,
"videos.insert session creation",
"POST",
f"{ORIGIN}{UPLOAD_PATH}?uploadType=resumable&part=snippet,status",
json.dumps(metadata).encode(),
**{
"Content-Type": "application/json; charset=UTF-8",
"X-Upload-Content-Type": VIDEO_TYPE,
"X-Upload-Content-Length": str(size),
},
)
session = session_url(headers.get_all("Location", []))
result["id"] = upload_video(opener, session, video, size, publish_at)
save_receipt(receipt, "pending", result)
finish_video(opener, result, publish_at, thumb, thumb_type)
save_receipt(receipt, "complete", result)
except (OSError, UploadError) as exc:
message = (
str(exc)
if isinstance(exc, UploadError)
else "Could not read the input files or persist the upload receipt."
)
if "id" in result:
message += " Work on the existing video rather than running another upload."
print(json.dumps({**result, "error": message}))
print(message, file=sys.stderr)
return 1
print(json.dumps(result))
return 0
if __name__ == "__main__":
sys.exit(main())