"""Download MoveKit videos and posters to assets/ and write catalog.json, status.json and README.md (how an app serves and plays the files). movekit-import version 2026.11.29.2 Save it as movekit/import.py and run it from the project root (Python 3.9 or newer, standard library only): python3 movekit/import.py Its folders are relative to the folder it is run from, wherever the script is. With --install it only puts a copy of itself at movekit/import.py: when there is none there, or an older one. With no key it imports the sample exercises. With a key it imports what the account owns, plus any sample exercise the account does not own. The key is MOVEKIT_API_KEY from the environment, or a MOVEKIT_API_KEY= line in .env.local, then .env, in the current folder. Optional environment variables: MOVEKIT_API_BASE_URL (https://api.movekit.com/v1), MOVEKIT_IMPORT_DIR (./movekit), MOVEKIT_IMPORT_LIMIT (0 for all files), MOVEKIT_ASSETS_DIR (/assets: where the videos and posters go, for example a web app's public/movekit, while catalog.json stays in the import folder). The shipped app must read these local files and never call the API at runtime. """ import errno import hashlib import http.client import json import os import posixpath import random import re import shutil import signal import stat import sys import time from datetime import datetime, timedelta, timezone from urllib.error import HTTPError from urllib.parse import urlencode, urlsplit from urllib.request import HTTPRedirectHandler, Request, build_opener # White space as JavaScript's trim() and dotenv cut it, the same in both importers: Python's own strip() also cuts # \x1c to \x1f and \x85, so a key ending in one of those would be sent here and refused by Node. KEY_SPACE = "\t\n\x0b\x0c\r \xa0            

   " SPACE = "[\t\n\x0b\x0c\r \xa0  - 

   ]" # Any character but a line ending, as "." is in JavaScript. IN_LINE = "[^\n\r

]" def read_key(): """The key: the environment wins, then the last MOVEKIT_API_KEY= line in .env.local, then .env, read as dotenv reads them (white space and a byte order mark around it, quotes, an inline " # comment" after an unquoted value; a later line wins; a line with nothing after "=" means no key, and the next file is not read). A key that still holds white space or a control character is refused in main(), never printed.""" def clean(value): value = value.strip(KEY_SPACE) match = re.fullmatch(r"""(["'])(.*)\1""", value, re.S) return (match.group(2) if match else value).strip(KEY_SPACE) from_environment = clean(os.environ.get("MOVEKIT_API_KEY", "")) if from_environment: return from_environment, "MOVEKIT_API_KEY in the environment" for name in (".env.local", ".env"): try: # Lines end at a newline (and a carriage return before it); a carriage return inside a line stays in the # value, so a key broken by one is refused, never cut and sent. with open(name, encoding="utf-8-sig", errors="replace", newline="") as handle: lines = [line[:-1] if line.endswith("\r") else line for line in handle.read().split("\n")] except OSError: continue # A file that has the line, even with nothing after "=", decides: an empty value is no key, as dotenv reads it. value = None for line in lines: match = re.match(r"%s*(?:export%s+)?MOVEKIT_API_KEY%s*=([^\n]*)$" % (SPACE, SPACE, SPACE), line) if not match: continue raw = match.group(1).strip(KEY_SPACE) quoted_value = re.match(r"""(["'])(%s*?)\1""" % IN_LINE, raw) value = quoted_value.group(2).strip(KEY_SPACE) if quoted_value else re.sub(r"(?:^|%s+)#%s*$" % (SPACE, IN_LINE), "", raw).strip(KEY_SPACE) if value is not None: return (value, "MOVEKIT_API_KEY in %s" % name) if value else ("", "", name) return "", "" # The key, where it came from, and the file whose empty MOVEKIT_API_KEY= line decided there is none ("" if none did). API_KEY, KEY_FROM, KEY_EMPTY_IN = (read_key() + ("",))[:3] def redact(value): """The one function every printed line and every written file passes through: the key, and anything shaped like a MoveKit key, never leaves the process.""" text = str(value) if API_KEY: text = text.replace(API_KEY, "[key hidden]") return re.sub(r"mk_(?:live|test)_[A-Za-z0-9_-]+", "[key hidden]", text) class Output: """stdout and stderr through redact(); a closed pipe (| head) stops the output, never the run.""" def __init__(self, stream): self.stream = stream self.closed_pipe = False def write(self, text): if not self.closed_pipe: try: self.stream.write(redact(text)) except (OSError, ValueError): self.close_pipe() return len(text) def flush(self): if not self.closed_pipe: try: self.stream.flush() except (OSError, ValueError): self.close_pipe() def close_pipe(self): # What is still buffered goes nowhere, so Python's own flush at exit cannot fail on the closed pipe either. self.closed_pipe = True try: os.dup2(os.open(os.devnull, os.O_WRONLY), self.stream.fileno()) except (OSError, ValueError, AttributeError): pass sys.stdout = Output(sys.stdout) sys.stderr = Output(sys.stderr) def say(text, out=False): """Every line the importer prints, through redact(): the key never reaches the terminal or a log, whatever an error message quotes. To stderr, or to stdout for the one JSON line; the guard refuses any other way to print.""" (sys.stdout if out else sys.stderr).write(redact(text) + "\n") API_BASE = os.environ.get("MOVEKIT_API_BASE_URL", "https://api.movekit.com/v1").rstrip("/") # The route that ran it: the prompt and the skill set MOVEKIT_VIA on their first run; a copy inside a skill folder is the skill's. VIA = os.environ["MOVEKIT_VIA"] if os.environ.get("MOVEKIT_VIA") in ("prompt", "skill") else "skill" if "/skills/movekit/" in os.path.abspath(__file__).replace(os.sep, "/") else "docs" # Sent on every request. The delivery network refuses Python's default client name. USER_AGENT = "movekit-import/1 (via=%s)" % VIA # The import folder, relative to the folder the importer is run from (the project root), wherever the script itself is. # An absolute folder is taken by its real path, so the paths written stay inside the project when they are. IMPORT_DIR = (os.path.realpath(os.environ["MOVEKIT_IMPORT_DIR"]) if os.path.isabs(os.environ["MOVEKIT_IMPORT_DIR"]) else os.environ["MOVEKIT_IMPORT_DIR"]) if os.environ.get("MOVEKIT_IMPORT_DIR") else "./movekit" MARKER = "movekit-import" # A file name this importer gives a file it downloads: only such files are ever copied from or reported as unused. IMPORTER_FILE = re.compile(r"ex[0-9]+-(?:video|poster)-[A-Za-z0-9_-]+\.(?:mp4|jpg|webp|png)") # The temporary file of a download or a copy a stopped run left: reported with the unused files, never touched. IMPORTER_PART = re.compile(r"ex[0-9]+-(?:video|poster)-[A-Za-z0-9_-]+\.(?:mp4|jpg|webp|png)(?:\.[0-9a-f]{8})?(?:\.copy)?\.part") def read_json(file_path): try: with open(file_path, encoding="utf-8") as handle: return json.load(handle) except (OSError, ValueError): return None def own_file(file_path, own): """catalog.json or status.json: absent, the importer's own (its data), or a file of that name that is not.""" try: info = os.lstat(file_path) except (OSError, ValueError): return {"file": file_path, "own": False, "foreign": False, "data": None} data = read_json(file_path) if stat.S_ISREG(info.st_mode) else None if own(data): return {"file": file_path, "own": True, "foreign": False, "data": data} return {"file": file_path, "own": False, "foreign": True, "data": None} def own_catalog(data): """The importer's own catalog.json: it carries "generatedBy": "movekit-import", or it is one an earlier importer wrote, which had nothing but "exercises": an array of at least one row, each with a string id and both files, every file's path ending in a name this importer gives. An empty array proves nothing, so it is not the importer's.""" if not isinstance(data, dict): return False if data.get("generatedBy") == MARKER: return isinstance(data.get("exercises"), list) def file_ok(file): return isinstance(file, dict) and isinstance(file.get("path"), str) and IMPORTER_FILE.fullmatch(posixpath.basename(file["path"].replace("\\", "/"))) is not None return list(data.keys()) == ["exercises"] and isinstance(data["exercises"], list) and len(data["exercises"]) > 0 and all( isinstance(row, dict) and isinstance(row.get("id"), str) and isinstance(row.get("files"), dict) and all(file_ok(row["files"].get(kind)) for kind in ("video", "poster")) for row in data["exercises"]) def own_status(data): """The importer's own status.json: it carries "generatedBy": "movekit-import", or it is one an earlier importer wrote: mode sample or account, readme "README.md", a rerun command and a missing list.""" if not isinstance(data, dict): return False return data.get("generatedBy") == MARKER or (data.get("mode") in ("sample", "account") and data.get("readme") == "README.md" and isinstance(data.get("rerun"), str) and isinstance(data.get("missing"), list)) def recorded_folder(value): """A folder the last run recorded, relative to the import folder; never an absolute one.""" return value if isinstance(value, str) and value and not os.path.isabs(value) and "\0" not in value else None def inside_project(target): """Inside the current folder or the import folder, as written or by real path (a project reached through a link): the only places a recorded path may point.""" def within(root, child): try: relative = os.path.relpath(child, root) except ValueError: return False return relative == "." or (not relative.startswith("..") and not os.path.isabs(relative)) real = os.path.realpath(target) return any(within(root, target) or within(os.path.realpath(root), real) for root in (os.path.abspath(os.curdir), os.path.abspath(IMPORT_DIR))) def given_folder(value): """A folder from the environment: an absolute one by its real path (through any link in it), a relative one as given; "" when unset.""" return (os.path.realpath(value) if os.path.isabs(value) else value) if value else "" def last_clips_folder(): """The folder the last run put the clips in, relative to the import folder: the folder a stopped run was filling (its mark), else the one folder every file path in the last catalog.json shares, else status.json's assetsDir; None when none says (a first run).""" mark = LAST_STATUS.get("lastRunFailed") if isinstance(LAST_STATUS, dict) else None stopped = recorded_folder(mark.get("assetsDir")) if isinstance(mark, dict) else None if stopped: return stopped folders = set() exercises = LAST_CATALOG.get("exercises") if isinstance(LAST_CATALOG, dict) else None for record in exercises if isinstance(exercises, list) else []: files = record.get("files") if isinstance(record, dict) else None for file in files.values() if isinstance(files, dict) else []: if isinstance(file, dict) and isinstance(file.get("path"), str) and file["path"]: folders.add(posixpath.dirname(file["path"].replace("\\", "/")) or ".") if len(folders) == 1: return recorded_folder(next(iter(folders))) return recorded_folder(LAST_STATUS.get("assetsDir") if isinstance(LAST_STATUS, dict) else None) # The importer never deletes, moves or overwrites a file except the ones it writes in this run: its own temporary # files (*..part) and, through them, catalog.json, status.json, its own README.md and the clip files it is # placing. A file it no longer uses stays where it is and is reported (blind review, 20 Nov 2026, evening). # catalog.json and status.json are read, written or marked only when they are absent or the importer's own # (own_catalog, own_status); a file of either name that is not stops the run before anything is written. class FrozenDict(dict): """Round sixteen (L1): a dict that can only be read: the last catalogue and status, and everything read from them.""" def refuse(self, *args, **kwargs): raise TypeError("the last catalogue and status are read only") __setitem__ = __delitem__ = __ior__ = clear = pop = popitem = setdefault = update = refuse class FrozenList(list): """Round sixteen (L1): a list that can only be read.""" def refuse(self, *args, **kwargs): raise TypeError("the last catalogue and status are read only") __setitem__ = __delitem__ = __iadd__ = __imul__ = append = extend = insert = pop = remove = clear = sort = reverse = refuse def frozen(value): """Round sixteen (L1): a read-only copy, to the leaves, of a value read from JSON.""" if isinstance(value, dict): return FrozenDict((key, frozen(item)) for key, item in value.items()) if isinstance(value, list): return FrozenList(frozen(item) for item in value) return value # Round sixteen (L1): read only to the leaves, so nothing read from them, under any name, can be changed. LAST_CATALOG_FILE = frozen(own_file(os.path.join(IMPORT_DIR, "catalog.json"), own_catalog)) LAST_STATUS_FILE = frozen(own_file(os.path.join(IMPORT_DIR, "status.json"), own_status)) LAST_CATALOG = LAST_CATALOG_FILE["data"] if LAST_CATALOG_FILE["own"] else None LAST_STATUS = LAST_STATUS_FILE["data"] if LAST_STATUS_FILE["own"] else None LAST_FOLDER = last_clips_folder() # A recorded folder outside the folder the importer runs from and the import folder is never switched away from in # silence: a run without MOVEKIT_ASSETS_DIR stops and says which value to set (main()). LAST_FOLDER_OUTSIDE = LAST_FOLDER is not None and not inside_project(os.path.abspath(os.path.join(IMPORT_DIR, LAST_FOLDER))) # The last run's clips folder, absolute (/assets when nothing says otherwise). PREVIOUS_ASSETS = os.path.abspath(os.path.join(IMPORT_DIR, LAST_FOLDER or "assets")) # The videos and posters only. A web app can serve this folder while catalog.json, status.json and README.md stay unserved. # MOVEKIT_ASSETS_DIR wins when it is set, as given, even outside the project (a monorepo's shared package). Without it, # a run keeps the folder the last run used; the default is /assets. RECORDED_ASSETS = None if os.environ.get("MOVEKIT_ASSETS_DIR") or LAST_FOLDER_OUTSIDE else LAST_FOLDER ASSETS_KEPT = bool(RECORDED_ASSETS and RECORDED_ASSETS != "assets") ASSETS_DIR = given_folder(os.environ.get("MOVEKIT_ASSETS_DIR")) or (os.path.abspath(os.path.join(IMPORT_DIR, RECORDED_ASSETS)) if ASSETS_KEPT else os.path.join(IMPORT_DIR, "assets")) # The clips folder outside the folder the importer runs from (set by MOVEKIT_ASSETS_DIR): named in one summary line. ASSETS_OUTSIDE = not inside_project(os.path.abspath(ASSETS_DIR)) IMPORT_LIMIT = int(os.environ.get("MOVEKIT_IMPORT_LIMIT", "0").strip()) if re.fullmatch(r"[0-9]+", os.environ.get("MOVEKIT_IMPORT_LIMIT", "0").strip()) else None # A name no earlier run and no other file uses, for this run's temporary files: an existing file is never opened, # appended to or removed because it happens to carry a temporary name. RUN_ID = os.urandom(4).hex() REQUEST_TIMEOUT = 30 # Only tests set MOVEKIT_TEST_TIME_SCALE, a number from 0.001 to 1: it shortens the download timings below by that # factor. Anything else (unset, 0, more than 1, not a number) counts as 1, so it can never make a run slower. TIME_SCALE = float(os.environ["MOVEKIT_TEST_TIME_SCALE"]) if re.fullmatch(r"0(?:\.[0-9]+)?|1(?:\.0+)?|\.[0-9]+", os.environ.get("MOVEKIT_TEST_TIME_SCALE", "")) and float(os.environ["MOVEKIT_TEST_TIME_SCALE"]) >= 0.001 else 1 # A download that sends nothing for this long is a failed try (a slow one that keeps sending goes on). DOWNLOAD_IDLE = 30 * TIME_SCALE RATE_LIMIT_RETRIES = 3 BATCH_SIZE = 50 # A grant this close to its expiresAt is replaced before the download starts. GRANT_REFRESH_MARGIN = 30 # A download the delivery host could not serve just now (502, 503, 504, a connection reset or ended early, nothing sent # for 30 s) is tried again from the bytes already here, after 1, 2, 4, 8 and 16 s (or what Retry-After says, at most a # minute): 6 tries at most, and none later than 90 s after the file's first failure. A link the host says is spent or # expired is replaced by a fresh one, and the same count goes on. A file still failing is held back like any other: the # rest of the run goes on. # The run's budget for passing faults is 3 minutes in all: each failed try counts its own time up to the idle timeout # (30 s; a long transfer that breaks late is not charged its whole length, yet every failure costs something), and the # waits between tries count in full. Once it is spent, a file still gets one try, and one that fails is held back at # once; after 3 such failures (FAILURES_AFTER_BUDGET, counted from the moment the budget ran out and never reset by a # file that arrives), every file left is held back without a try. So the time a run spends on failures is at most about # 5 minutes, however many files and whatever share of them fail: 3 minutes of budget, the try running when it ran out # (30 s at most), and 3 more failed tries of 30 s at most. A host that fails 2 of every 3 files costs that plus the time # the files that do arrive take to download. # And whatever a try sends before it fails: the failed tries' own time in full and the waits, counted from the first # failure, are capped at 5 minutes (FAILURE_TIME_CAP). A wait that would go past it is not taken, and once it is reached # every file left is held back without a try and no more links are asked for. # Each try also has a deadline (round fifteen): 60 s (TRY_MIN), or the time the bytes still to come take at 50 KB/s # (TRY_MIN_RATE), whichever is longer, checked as each piece arrives. A connection slower than 50 KB/s (400 kbit/s) # cannot bring clips in useful time, and a slow try keeps its bytes for the next one, so a slow host still finishes over # several tries while one that drips bytes for ever is ended. The most a run spends on failures is so 5 minutes plus the # try running when the cap is reached: its deadline and one more piece or silent wait (30 s at most). DOWNLOAD_RETRIES = 5 DOWNLOAD_RETRY_WINDOW = 90 * TIME_SCALE RUN_RETRY_BUDGET = 180 * TIME_SCALE RETRY_AFTER_CAP = 60 * TIME_SCALE FAILURES_AFTER_BUDGET = 3 FAILURE_TIME_CAP = 300 * TIME_SCALE TRY_MIN = 60 * TIME_SCALE TRY_MIN_RATE = 50000 PASSING_STATUSES = {502, 503, 504} # Time spent on passing faults this run (failed tries and waits), and the files that failed after it ran out. RETRY_SPENT = [0.0] FAILED_AFTER_BUDGET = [0] FAILURE_TIME = [0.0] # Round sixteen (M1), round seventeen: link renewals. A renewal asks again for every file left in its batch, so it is made # only when it can help: the first in a batch at any time, then one more whenever bytes arrived since the last (a host # that answers 410 to everything gets one; a slow line that works gets as many as it needs), and at most # RENEWALS_PER_FILE for any one file in a run. Links that look expired as they arrive mean this computer's clock is ahead # of MoveKit's: the files are held, the run says so once and asks for no more. RENEWALS_PER_FILE = 3 # Bytes the delivery host has sent this run, all files together: what tells a renewal that the line is working. BYTES_RECEIVED = [0] # Round sixteen (M2): a try cut at its deadline that still brought at least 10 KB/s is a slow line, not a failing one. STEADY_RATE = 10000 # How far this computer's clock is ahead of MoveKit's, in seconds, from the Date of the API's last answer (None: unknown). CLOCK_AHEAD = [None] CHUNK = 1024 * 1024 EXTENSIONS = {"video/mp4": "mp4", "image/jpeg": "jpg", "image/webp": "webp", "image/png": "png"} ASSET_ID = re.compile(r"ex[0-9]+-(?:video|poster)") SAFE_VERSION = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:+-]{0,127}") PACKS_URL = "https://movekit.com/packs" KEYS_URL = "https://movekit.com/account/purchases?from=api#api-keys" PROGRESS_EVERY = 10 # No control characters, C0 or C1: the Hosted line is printed to a terminal and written to files. CONTROL = re.compile(r"[\x00-\x1f\x7f-\x9f]") # Tries of the download links request when the API answers with a server error (parallel CI runs can contend). LINK_ATTEMPTS = 4 # Refusals that hold one file back until 00:00 UTC; refusals that hold back every later file of the same kind (sample or account). DAILY_REFUSALS = {"link_limit_exceeded", "sample_busy", "daily_request_limit"} WHOLE_DAY_REFUSALS = {"sample_busy", "daily_request_limit"} # The README's first line: a README that does not start with it is the project's own and is never overwritten. README_MARKER = "" README_OURS = ("