Extend balanced commercial scheduling to all episode channels
This commit is contained in:
175
scripts/channel-commercials.py
Normal file
175
scripts/channel-commercials.py
Normal file
@@ -0,0 +1,175 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Refresh configured episode channels from the local Commercials library."""
|
||||
import argparse
|
||||
import collections
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import random
|
||||
import subprocess
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
STATE = ROOT / "data" / "channel-commercials"
|
||||
MEDIA_EXTENSIONS = {".mp4", ".mkv", ".mov", ".m4v", ".webm", ".avi", ".ts"}
|
||||
|
||||
|
||||
def api(path, body=None, method=None):
|
||||
port = os.environ.get("TUNARR_LOOPBACK_PORT", "14242")
|
||||
payload = None if body is None else json.dumps(body).encode()
|
||||
request = urllib.request.Request(
|
||||
f"http://127.0.0.1:{port}/api{path}", payload,
|
||||
{"Content-Type": "application/json"} if payload else {}, method=method,
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=90) as response:
|
||||
data = response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
error.add_note(error.read().decode(errors="replace")[:500])
|
||||
raise
|
||||
return json.loads(data) if data else None
|
||||
|
||||
|
||||
def save_json(path, value):
|
||||
temporary = path.with_suffix(".tmp")
|
||||
temporary.write_text(json.dumps(value))
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def stored_items(channel_id):
|
||||
result = subprocess.check_output(
|
||||
["docker", "compose", "exec", "-T", "tunarr", "cat",
|
||||
f"/config/tunarr/channel-lineups/{channel_id}.json"], cwd=ROOT,
|
||||
)
|
||||
return json.loads(result)["items"]
|
||||
|
||||
|
||||
def rotation(clips, rng):
|
||||
previous = None
|
||||
while True:
|
||||
batch = list(clips)
|
||||
rng.shuffle(batch)
|
||||
if len(batch) > 1 and batch[0]["uuid"] == previous:
|
||||
batch[0], batch[1] = batch[1], batch[0]
|
||||
for clip in batch:
|
||||
previous = clip["uuid"]
|
||||
yield clip
|
||||
|
||||
|
||||
def build_lineup(episodes, short, long, filler):
|
||||
rng = random.Random("|".join(clip["uuid"] for clip in short + long))
|
||||
short_cycle, long_cycle = rotation(short, rng), rotation(long, rng)
|
||||
|
||||
def ad(clip, position):
|
||||
return {"type": "filler", "id": clip["uuid"], "duration": clip["duration"],
|
||||
"fillerListId": filler, "fillerType": position}
|
||||
|
||||
lineup = []
|
||||
for episode in episodes:
|
||||
duration = episode["durationMs"]
|
||||
points = [0, duration // 4, duration // 2, duration * 3 // 4, duration]
|
||||
lineup.append(ad(next(long_cycle), "pre"))
|
||||
for index, (start, stop) in enumerate(zip(points, points[1:])):
|
||||
if index:
|
||||
lineup.extend(ad(next(short_cycle), "mid") for _ in range(2))
|
||||
lineup.append({"type": "content", "id": episode["id"],
|
||||
"duration": stop - start, "startOffsetMs": start})
|
||||
return lineup
|
||||
|
||||
|
||||
def refresh(apply_active):
|
||||
source = next(item for item in api("/media-sources") if item["name"] == "Commercials")
|
||||
library = source["libraries"][0]["id"]
|
||||
files = {
|
||||
str(path.relative_to(ROOT / "data/commercials")): [path.stat().st_size, path.stat().st_mtime_ns]
|
||||
for path in sorted((ROOT / "data/commercials").rglob("*"))
|
||||
if path.is_file() and path.suffix.lower() in MEDIA_EXTENSIONS
|
||||
}
|
||||
observed = STATE / "observed.json"
|
||||
scanned = STATE / "scanned.json"
|
||||
prior = json.loads(observed.read_text()) if observed.exists() else None
|
||||
if files != prior:
|
||||
save_json(observed, files)
|
||||
if not apply_active:
|
||||
return
|
||||
if not scanned.exists() or files != json.loads(scanned.read_text()):
|
||||
api(f'/media-sources/{source["id"]}/scan', method="POST")
|
||||
save_json(scanned, files)
|
||||
|
||||
clips = []
|
||||
page = 0
|
||||
while True:
|
||||
result = api("/programs/search", {"query": {}, "libraryId": library,
|
||||
"page": page, "limit": 100})
|
||||
clips.extend(result["results"])
|
||||
page += 1
|
||||
if page >= result["totalPages"]:
|
||||
break
|
||||
expected = {"/commercials/" + name for name in files}
|
||||
clips = sorted(
|
||||
(clip for clip in clips if clip.get("externalId") in expected
|
||||
and clip.get("state") == "ok" and clip.get("duration", 0) > 0),
|
||||
key=lambda clip: clip["uuid"],
|
||||
)
|
||||
if {clip["externalId"] for clip in clips} != expected:
|
||||
return
|
||||
short = [clip for clip in clips if clip["duration"] <= 30_000]
|
||||
long = [clip for clip in clips if clip["duration"] >= 60_000]
|
||||
if not short or not long:
|
||||
return
|
||||
|
||||
signature = [[clip["uuid"], clip["duration"]] for clip in clips]
|
||||
filler = next(item for item in api("/filler-lists") if item["name"] == "Commercials")
|
||||
filler_path = f'/filler-lists/{filler["id"]}'
|
||||
members = [{"type": "content", "id": clip["uuid"], "duration": clip["duration"],
|
||||
"program": clip} for clip in clips]
|
||||
current = api(filler_path + "/programs")
|
||||
if {item["id"] for item in current} != {clip["uuid"] for clip in clips}:
|
||||
api(filler_path, {"programs": members}, method="PUT")
|
||||
|
||||
configured = json.loads((STATE / "channels.json").read_text())
|
||||
for channel_id, name in configured.items():
|
||||
applied = STATE / f"{channel_id}-applied.json"
|
||||
if applied.exists() and signature == json.loads(applied.read_text()):
|
||||
continue
|
||||
if not apply_active and api(f"/channels/{channel_id}")["sessions"]:
|
||||
continue
|
||||
apply_lineup(channel_id, name, short, long, filler["id"], apply_active)
|
||||
save_json(applied, signature)
|
||||
|
||||
|
||||
def apply_lineup(channel_id, name, short, long, filler_id, apply_active):
|
||||
episodes = json.loads((STATE / f"{channel_id}-episodes.json").read_text())
|
||||
lineup = build_lineup(episodes, short, long, filler_id)
|
||||
api(f"/channels/{channel_id}/programming", {"type": "manual", "append": False, "lineup": lineup})
|
||||
expected_items = [
|
||||
{"type": "content", "id": entry["id"], "durationMs": entry["duration"],
|
||||
**({"startOffsetMs": entry["startOffsetMs"]} if entry["type"] == "content"
|
||||
else {"fillerListId": filler_id, "fillerType": entry["fillerType"]})}
|
||||
for entry in lineup
|
||||
]
|
||||
assert stored_items(channel_id) == expected_items, "Saved lineup differs from requested lineup"
|
||||
if apply_active:
|
||||
try:
|
||||
api(f"/channels/{channel_id}/sessions", method="DELETE")
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code != 404:
|
||||
raise
|
||||
counts = collections.Counter(item["id"] for item in lineup if item["type"] == "filler")
|
||||
print(f"{name}: verified {len(episodes)} episodes and {sum(counts.values())} ads. Plays by clip: {dict(counts)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--apply-active", action="store_true",
|
||||
help="apply immediately and restart the channel's active stream")
|
||||
args = parser.parse_args()
|
||||
STATE.mkdir(exist_ok=True)
|
||||
with (STATE / "lock").open("a") as lock:
|
||||
try:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
raise SystemExit(0)
|
||||
refresh(args.apply_active)
|
||||
Reference in New Issue
Block a user