Writing a platform
A platform is where sources come from: YouTube, Stremio, Spotify, Jellyfin. A source is one video, episode or track the learner watched or listened to. Each platform is one Python object that tells AutoMiner how to recognise that platform’s watches, how to fetch subtitles and media for a source, what the platform’s Settings section shows, and which programs it needs. The terms are defined in the glossary.
This page is for a developer adding a platform. Today the only way to add one is to
write it into AutoMiner’s code, next to the built-in platforms in
core/autominer/platforms/. Uploading a
platform as a pack is planned but not built; see Packs. What the built-in
platforms do for a learner is in Sources and the pages for
YouTube, Stremio,
Spotify and Jellyfin.
How a platform fits in
Section titled “How a platform fits in”A watch reaches AutoMiner as events. A source is fetched and mined after the watch ends (the whole path is in Architecture and Sources):
- A producer posts events to
POST /v1/events. The producer is the platform’s tracker (code inside AutoMiner that polls the platform’s service, like Stremio’s and Spotify’s), or an outside client such as the Chrome extension. YouTube’s phone patch posts to its own route,POST /v1/ingest/youtube-android, which turns each report into the same events. Thesourceof an event’smediaobject is the platform’sname; the event’s ownsourceis that name or one of the platform’ssurfaces. ingest.ingestdrops the event when that platform is not installed. Otherwise it creates or updates themediarow (one row per source,media.source= the platform name) and an alias<name>:<source_id>.- On
session.end,ingest._dispatch_mining_jobchecks that mining is on for the platform (mine.enabled:<name>) and that the platform has afetchjob, asksfetch_on_capture(media)andfetch_payload(media), and queues the fetch job. Pressing mine by hand (media_actions.mine_now) queues the same job withpressed: true. - The job worker runs the platform’s
fetch_handler. By default that is the shared fetch step (fetch.handle_fetch): pick the language, then try the platform’s own subtitles, subtitles inside the media file, outside subtitles, and finally speech recognition (ASR). - The stored subtitle lines are handed to the
minejob, which makes card candidates.
| File | What it holds |
|---|---|
platforms/interface.py |
Platform, the data classes it passes around (Source, Details, Subtitles, Found, Card), the exceptions NotInLanguage and NotFetchable, shared_fetch_step, and retired_command. |
platforms/__init__.py |
The registry PLATFORMS, register, lookups (of, by_job), install state (install, uninstall, installed), the job table (jobs), and page_table for the web UI. |
platforms/youtube.py, stremio.py, spotify.py, jellyfin.py |
The four built-in platforms. Each module defines PLATFORM. |
fetch.py |
The shared fetch step. |
trackers.py |
Runs each installed platform’s tracker inside autominer serve. |
Register the platform
Section titled “Register the platform”A platform is a frozen dataclass. Subclass Platform to override methods, create one
instance named PLATFORM, and add the module to the tuple in platforms/__init__.py:
PLATFORMS: dict[str, Platform] = {}UNKNOWN = Platform(name="", title="")
def register(platform: Platform) -> Platform: PLATFORMS[platform.name] = platform return platform
for _built_in in (youtube, stremio, jellyfin, spotify): register(_built_in.PLATFORM)Register at import time, in that tuple. Core code reads PLATFORMS when it is called,
never when its module is imported, so a platform registered later is in every table, for
example admission.doors(), dependencies.value_checks() and retention.busy_job_kinds().
tests/test_no_registry_snapshots.py fails
on a table built from PLATFORMS at import, on a write into PLATFORMS outside
platforms/__init__.py, and on core code outside platforms/ that reads a platform
module’s PLATFORM directly.
platforms.of(source) returns the platform for a media.source value, or UNKNOWN (a
bare Platform whose methods all return their defaults). Core Python calls a platform
through these lookups instead of checking its name; a test enforces it (see below).
Choosing the name
Section titled “Choosing the name”name is the platform’s id everywhere: the source of its events, the media.source
column, the alias prefix, the suffix of per-platform settings keys such as
mine.enabled:<name>, the program folder programs/<name>, and the tracker lock file
state/<name>-tracker.lock. Use one short lowercase ASCII word. The Settings page
builds element ids from it (platYoutube for youtube) and lower-cases the id to find
the platform again, so a name with capitals breaks.
The name must not be a word the core already uses as a string.
tests/test_no_platform_names.py fails on
any string constant in core/autominer that is a platform’s name, its title in lower
case, or the media kind in its twin, outside the files listed in
BUILT_IN_PLATFORM_CODE. For example, a platform named shelf fails at once, because
page_table in platforms/__init__.py has a "shelf" key. The same test fails on such
a name used as code (an id, a key, a property) in core/static (.html, .js and
.css, not the i18n catalogs), except for the names listed in STATIC_DECLARED: a
built-in platform’s own panel code and the Stremio key rows that wait for
#1507.
What a platform declares
Section titled “What a platform declares”These are the fields of Platform. Only name and title are required.
Identity and jobs
Section titled “Identity and jobs”| Field | Default | Read by | What it does |
|---|---|---|---|
name |
required | everywhere | The id, see above. |
title |
required | the web UI, messages | The display name. A source whose title equals any platform’s title counts as having no real title yet (platforms.site_name). |
fetch |
None |
platforms.jobs, ingest, media_actions, page_table |
The job kind that fetches a source, such as fetch.yt. None means the platform records watches but never mines: Jellyfin is only Platform(name="jellyfin", title="Jellyfin", mark="jellyfin"). A platform with fetch gets a Settings section and a row in the setup checklist. |
fetch_handler |
shared_fetch_step |
platforms.jobs |
(conn, job_row) -> None, the function that runs the fetch job. Spotify replaces it with its own fetch_episode. |
video |
None |
platforms.jobs, media_actions.video_kind |
A second job kind that fetches only the media again: YouTube’s fetch.video, Spotify’s fetch.audio. |
video_handler |
None |
platforms.jobs |
The handler for video. |
retry_failed |
False |
ingest._dispatch_mining_job |
True: a new watch queues the fetch again even when the last one failed or was skipped. YouTube sets it. |
judged |
True |
judge.judge_mode, dependencies, page_table |
False turns 判定 (the check that subtitles are timed to the audio) off for this platform’s sources; the setup checklist shows clip scoring instead, and Settings draws no 判定 tab for it. Spotify sets it; its lines come from ASR. |
platforms.jobs() wraps both handlers so that a job for a platform that is not
installed is skipped:
def _when_installed(platform: Platform, handler: JobHandler) -> JobHandler: @functools.wraps(handler) def run(conn, job_row) -> None: if not installed(conn, platform.name): from ..jobs import SkipJob
raise SkipJob(f"{platform.title} はインストールされていません") handler(conn, job_row)
return runWatches and tracking
Section titled “Watches and tracking”| Field | Default | Read by | What it does |
|---|---|---|---|
watch |
None |
media_actions.watch_url |
A URL template with {id} (the URL-quoted platform source id). Today and Sources rows link back to the platform with it. |
twin |
None |
ingest |
(media kind, id prefix). For media of that kind, <prefix><id> and <id> are the same source, and the prefix is stripped from platform_source_id. Spotify: ("podcast", "episode:"). |
positions |
False |
mine.holds_to_watched, page_table |
The platform’s watches report playback positions, so its Settings section offers 見たところだけ (mine only what was watched). |
surfaces |
() |
ledger/stats.py |
Other event source names that count as this platform in Today’s per-platform totals. YouTube: ("youtube_android_revanced",). |
adapter_device |
None |
ledger/stats.py, Spotify’s coarse |
The device value the platform’s tracker posts with. Today’s per-device totals fold it into one api row. |
doors |
() |
admission.doors() |
Extra admission door names for ingest routes the platform owns. YouTube: ("youtube-android",). The route itself is written in app.py; a platform cannot add routes through the interface. |
video_id_field |
None |
ingest.attach_anime_identity |
The name of a field in an event’s media that carries the platform’s video id, used to link a source to an anime identity. Stremio: "stremio_video_id". |
secrets_at_start |
False |
config_setup, help_text |
The tracker reads its secrets once when it starts, so autominer secret set says to restart AutoMiner. Spotify sets it. |
Subtitles
Section titled “Subtitles”| Field | Default | Read by | What it does |
|---|---|---|---|
native_label |
"配信元の字幕" |
subtracks |
The name of the platform’s own subtitle track in a source’s list of subtitle tracks. |
auto_label |
None |
subtracks |
The name of its automatic captions. Without it they are called 自動字幕. |
embedded_subtitles |
False |
fetch |
The media file can carry subtitle tracks. When the platform has no subtitles of its own, the shared step downloads the media and reads them. Stremio sets it. |
subtitle_pool |
True |
Platform.outside_subtitles, freshness.own_transcript |
The default outside_subtitles adopts the first readable file from the subtitle pool (subtitles collected from outside sites). YouTube and Spotify turn it off. |
refetch_subtitles |
False |
freshness.parse_reload |
When stored lines must be parsed again and no subtitle file is kept on disk, the platform’s subtitles can be fetched again instead. YouTube sets it. |
Shelves, artwork and audio
Section titled “Shelves, artwork and audio”| Field | Default | Read by | What it does |
|---|---|---|---|
shelf |
None |
fetch.store_shelf, the Sources page, push.note_tags, ledger/stats.py |
"channel" or "series": how the Sources page groups the platform’s sources, and which media columns Details.shelf fills (channel_id, channel_name, channel_handle, or series). With "channel", a card’s series tag comes from the title, not the series. |
audio |
False |
many | The platform’s sources are audio episodes. platforms.is_episode(media) is audio and fetch_on_capture(media); episodes get a cover instead of a video frame, ASR reads their audio, and they cannot be fetched again as video. |
mark |
None |
every page | The brand mark, drawn from core/static/brands/<mark>.svg. |
artwork |
None |
assets, the thumbnail route in app.py |
Set it when thumbnails come from the platform (its thumbnail method) instead of a frame of the local video. The value is added to the thumbnail URL as ?artwork=<value>. Stremio: "cinemeta-v1". |
Settings page and programs
Section titled “Settings page and programs”| Field | Default | Read by | What it does |
|---|---|---|---|
settings |
() |
page_table, the Settings page |
Declared settings rows. See Settings a platform declares. |
cards |
() |
page_table, the Settings page |
The cards in the platform’s Settings section. |
programs |
() |
platforms.install, YouTube’s tick |
Pinned programs downloaded when the platform is installed. See Programs. |
What a platform does
Section titled “What a platform does”These are the methods of Platform. Each has a default, so override only what your
platform needs.
Fetching
Section titled “Fetching”| Method | Default | Called by |
|---|---|---|
identify(conn, job_row, media, hook) -> Source |
A Source from the media row’s id, platform_source_id and title. Raises ValueError when there is no platform id. |
The shared fetch step, first. Also asr when an audio episode has no local audio. |
fetch_payload(media) -> dict | None |
None |
ingest and media_actions when they queue the fetch job. Raise NotFetchable(message) to refuse: a watch then queues nothing, and a press shows the message. |
fetch_on_capture(media) -> bool |
True |
ingest: whether a finished watch queues a fetch. Spotify only fetches podcasts. |
describe(source) -> Iterable[Details] |
() |
The shared step, after the language is known. Each Details can carry a title, a duration_s and a shelf dict; the step writes them to the media row as they arrive. |
get_media(conn, source, hook) -> str | None |
Raises NotImplementedError |
The shared step, when it needs the media file. Return a local path. |
get_audio(source) -> str | None |
None |
The shared step, before it hands a source to ASR. Return a local audio path if the platform can get an audio-only file; otherwise ASR gets the media file the step downloaded, if any. |
transcribe_in_job(conn, job_id, source, lang, notes, hook) -> bool |
False |
The shared step, when no subtitles were found. Return True when your code has dealt with the source (Stremio transcribes the file it already holds). |
hook(stage, info) is the job’s progress hook: hook("download", {"message": video_id})
shows a stage and a message on the job’s line. Every stage name you pass needs a label
in JOB_STAGE_LABELS in core/static/shell.js;
tests/test_job_stage_labels.py checks it. The
platform modules and the shared step use resolve, download, subtitles and asr.
get_media should record the file on the media row, as YouTube’s
fetch_yt.ensure_video and Stremio’s get_media do; the shared step only uses the
path it returns. source_retained = 1 is also what lets uninstalling the platform
delete the file. From Stremio:
conn.execute( "UPDATE media SET uri = ?, source_retained = 1, source_archived_uri = NULL," " source_deleted_at = NULL WHERE id = ?", (f"file://{path}", source.media_id))conn.commit()return pathInside the shared step an exception from get_media is printed and treated as no
media: the job payload records "video": "failed", and a source with subtitles is
still mined. YouTube’s tick later queues its video job for such sources.
Source carries what the fetch needs. Subclass it to carry more, as Spotify’s
Episode (show, guid, publication date) and Stremio’s Title (job id, wanted release,
audio tracks) do:
@dataclass(frozen=True)class Source: media_id: str id: str title: str | None = None language: str | None = None skip_other_languages: bool = False manual_subtitles_only: bool = False file: str | None = NoneSubtitles
Section titled “Subtitles”| Method | Default | Called by |
|---|---|---|
own_subtitles(source, lang) -> Subtitles | None |
None |
The shared step. Return Subtitles(text, fmt, auto), where fmt is "srt" or "vtt" and auto marks automatic captions. Raise NotInLanguage when the platform has subtitles, but only in other languages. |
outside_subtitles(conn, source, lang, hook) -> Found | None |
The subtitle pool, when subtitle_pool is on |
The shared step, after own and embedded subtitles. Return Found(cues, native=False), where cues is a list of {"t0", "t1", "text"} dicts. Stremio searches Jimaku here. |
stored(conn, source, lang, count, hook) -> None |
Reports "{count} セグメント" |
The shared step, after the lines are stored. |
Health, Settings and the command line
Section titled “Health, Settings and the command line”| Method | Default | Called by |
|---|---|---|
tick(conn) -> None |
nothing | The job worker’s idle tick, only while the platform is installed. YouTube retries live streams, re-queues refused downloads and keeps its programs current here. |
tracker() -> Tracker | None |
None |
The tracker supervisor. See Trackers. |
value_checks() -> dict[str, check] |
{} |
dependencies.value_checks(). Maps a settings key to check(conn, value) -> str | None; PUT /v1/settings/{key} refuses a value with HTTP 422 and the returned text. |
fetch_stage(conn, facts) -> (state, text, go) |
("ok", title, None) |
The setup checklist’s 取得 (fetch) stage for this platform. state is "ok", "warn" or "err"; go is the id of a Settings element the stage links to, or None. |
doctor(key, rows, env) |
None |
autominer doctor, for each feature key. Return (state, problems, details) for a feature you own, None otherwise. |
probe(key, env, db_path) |
None |
autominer doctor --online, for each configured feature. Return (status, detail), such as doctor.probe_http(...), for a key you own. |
commands(sub) -> None |
nothing | autominer’s argument parser (platform commands). Add subcommands with set_defaults(platform_command=func); retired_command(sub, name) keeps an old command name printing a notice. |
coarse(device, kind) -> bool |
False |
Today’s list: whether a closed session with no watched intervals still lists its source. |
Artwork and shelves
Section titled “Artwork and shelves”| Method | Default | Called by |
|---|---|---|
channel(media) -> dict | None |
None |
GET /v1/media/{id}/channel, when the row has no channel yet. |
thumbnail(media) -> Path | None |
None |
assets.media_thumbnail, when artwork is set. |
series(media) -> dict | None |
None |
GET /v1/media/{id}/series for non-audio platforms. None: not part of a series. {}: nothing to show yet. Otherwise name, year, runtime, description, has_background, has_logo. |
series_image(media, which) -> Path | None |
None |
GET /v1/media/{id}/series/background and /logo. |
cover(media, wait) -> Path | None |
None |
Thumbnails and the series banner of audio episodes. Spotify’s waits for a cover lookup in progress when wait is true and returns at once otherwise. |
cover_may_come(media, conn) -> bool |
False |
Whether a missing episode cover is worth waiting for. |
The shared fetch step
Section titled “The shared fetch step”shared_fetch_step calls fetch.handle_fetch. Most platforms keep it and override the
methods it calls. In order:
- Identify.
platform.identify(...)returns theSource. - Language. If the source carries both a
fileand alanguage, that language is used. Otherwise the language is detected from the source’s language tag and title, and a language the learner set by hand on the source wins. When the source names a language the learner does not study, the job is skipped with 対象言語以外の動画 ifskip_other_languagesis on and mine was not pressed, or if mine was pressed while more than one language is studied and the source has no candidates yet. - Details. Each
Detailsfromplatform.describe(source)is written tomedia. - Hearing the language. With more than one studied language and nothing that tells the language, the step gets the media and probes which language is spoken.
- The platform’s own subtitles.
platform.own_subtitles(source, lang). - Embedded subtitles. If there are none and
embedded_subtitlesis on, the step gets the media and reads its subtitle tracks. - Outside subtitles.
platform.outside_subtitles(conn, source, lang, hook). - Manual only. If
source.manual_subtitles_onlyis set and the subtitles found are automatic or missing, the job is skipped, unless the learner pressed mine. - Media. If the language is mined and there are subtitles or a usable ASR provider, the step gets the media so clips can be cut.
- No subtitles.
platform.transcribe_in_job(...)gets the first try. Otherwise the source goes to theasrjob withplatform.get_audio(source)or the media path. - Store. The lines are stored (as
suborauto-sub),platform.stored(...)runs, and the source goes tomine. Automatic captions in a mined language go to ASR instead, when a provider is set up and the cost limits allow it.
The core of steps 5 to 7 in fetch.py:
try: own, why_none = platform.own_subtitles(source, lang), "字幕なし"except platforms.NotInLanguage: own, why_none = None, f"{extract_subs.language_name(lang)}ではない字幕のみ"if own is None and platform.embedded_subtitles and not media_tried: video_path, media_tried = media_path(), Truenotes: dict = {}found = (_own(own) or _embedded(platform, video_path, lang, notes, hook) or platform.outside_subtitles(conn, source, lang, hook))To skip the step entirely, set fetch_handler to your own (conn, job_row) function.
Spotify does: its episodes have no subtitles, so fetch_episode gets the audio and hands
the source straight to ASR with media_actions.hand_off.
A handler, or any method it calls, can end the job with these exceptions from
autominer.jobs: SkipJob(message) marks it skipped; RetryLater(message) parks it
and runs it again after 30 minutes, doubling the wait up to 6 hours, and fails it after
3 days; any other exception marks it failed with the message.
Trackers: how watches are reported
Section titled “Trackers: how watches are reported”A tracker notices what the learner watches on the platform’s own service and
reports it. It runs inside autominer serve while the platform is installed.
tracker() returns a function track(stop: threading.Event) -> None, or None when
there is nothing to run yet. Return None until the platform’s credentials are set.
Stremio’s:
def tracker(self): from .. import settings_registry from ..adapters import stremio
return stremio.track if settings_registry.configured("stremio.tracking") else NoneThe supervisor in trackers.py does the rest:
- Every 30 seconds, and right after a platform is installed or uninstalled from the UI,
it calls
tracker()for each installed platform whose tracker is not already running or paused. - It takes a lock file in
<AUTOMINER_HOME>/state/<name>-tracker.lock, so two AutoMiners on one home track a platform once. The second showsstandby. - It runs
track(stop)on its own thread,autominer-tracker-<name>. - If
track(ortracker()itself) raises anything, evenSystemExit, the tracker is paused until AutoMiner restarts and its error shows in/healthz(trackers) andautominer doctor. Iftrackreturns, it is started again on the next check. - Uninstalling the platform or stopping the server sets
stop. AUTOMINER_TRACKING=0runs no tracker at all.
So track should loop until stop is set and catch the errors it expects. Stremio’s,
from adapters/stremio.py:
def track(stop: threading.Event) -> None: poller = StremioPoller() print(f"stremio adapter: polling every {_cfg('STREMIO_POLL_S')}s -> {core_url()}") while True: try: poller.tick() except Exception as exc: print(f"stremio adapter error: {exc}") if stop.wait(_cfg("STREMIO_POLL_S")): returnA tracker reports a watch the way every producer does: it posts event envelopes over
HTTP to AUTOMINER_CORE_URL (by default the address autominer serve listens on), with
headers that name the producer:
def post_event(env: dict) -> dict: r = requests.post( f"{core_url()}/v1/events", json=env, timeout=10, headers={"X-AutoMiner-Client": "stremio-adapter", "X-AutoMiner-Durable": str(DURABLE_CONTRACT), "X-AutoMiner-Client-Version": producers.local_build()}, ) r.raise_for_status() return r.json()What those headers mean, and when the core refuses a post, is in
producer admission. While the secret AUTOMINER_PREVIEW_TOKEN
is set, every /v1 request must also carry it in X-Preview-Token; the built-in
trackers do not send it, so their posts are refused then (see
Access).
An envelope needs source (the platform name), device, session_id, kind and ts.
kind is one of session.start, position, pause, resume, seek, session.end,
fetched and asr.done. The event that introduces a source carries a media object
with at least kind, source, source_id and title, and optionally lang, series,
episode, duration_s and uri. Later events of the same session can leave media
out. Spotify’s, from adapters/spotify.py:
def envelopes_for(play: dict) -> list[dict]: media = media_block(play) ts = _normalise_ts(play["played_at"]) session_id = f"spotify:phone:{play['episode_id']}:{play['played_at']}" return [ _envelope(session_id, media, "session.start", 0.0, ts), _envelope(session_id, media, "session.end", None, ts), ]A fetch is queued on session.end. A platform whose watches come from an outside
client (YouTube’s come from the Chrome extension and the phone) needs no tracker. A
tracker’s paused state shows only in /healthz and autominer doctor today; showing it
in Settings is #1528.
Settings a platform declares
Section titled “Settings a platform declares”A platform has two kinds of settings.
Settings rows are values the learner edits in the platform’s Settings section. They
live in the settings table. Declare each one as a
settings_registry.Setting in
Platform.settings, with the row’s key as name, a type (str, int, float,
bool, path or url), a default, a label, help and advanced. The first of
YouTube’s two rows:
Setting("fetch.yt_japanese_only", "bool", False, label="学習中の言語の動画だけマイニング", help="ON にすると、音声が<strong>学習中のどの言語でもないと分かった</strong>" " YouTube 動画はマイニングしません (学習中の言語の字幕があっても)。" "言語が不明な動画はマイニングします。既定 = OFF。")- The page draws a checkbox for
bool, a number input forintandfloat, and a text input otherwise, withdefaultas the placeholder.helpis inserted as HTML. Rows withadvanced=Truesit under 詳細設定 (advanced settings). - The page saves a row with
PUT /v1/settings/{key}. Add a check invalue_checks()to refuse bad values; Spotify checks its polling paces and daily read limit this way. - Your code reads the row itself, as
fetch_yt.japanese_only(conn)does, and must treat a missing row asdefault. - Keys must be unique across platforms, and every row needs a
label(tests/ui/test_platform_sections_drawn.py). - A row with
secret=Trueis not drawn. None of the built-ins declares one; where a platform’s secret will live is part of packs (#1507).
Credentials and environment settings, such as STREMIO_AUTH_KEY or the Spotify
client id, are registered in the settings registry in
settings_registry.py, with a Feature that
groups them and services naming the platform. settings_registry.configured(feature)
tells a tracker whether they are all set, and autominer doctor reports on the
feature. The Feature‘s label is the name the web UI shows for it, such as
Stremio の視聴記録. Configuration explains the registry, the .env file and
secrets. The registry is still core code, so the name guard test lists the built-ins’
lines in it under DECLARED in
tests/test_no_platform_names.py.
cards lays out the platform’s Settings section. A Card has a title, a mono tag
shown after the title, help (HTML), and a panel:
cards=( Card("マイニング"), Card("スマホ", "Morphe", "Android の YouTube で見た動画を記録します。" "Morphe Manager で YouTube に AutoMiner のパッチを当て、" "そのときにサーバーの URL と秘密の値を入れます。" "秘密の値を作り直すと、前の値で当てたスマホは記録を送れなくなります" " (記録はスマホに残り、新しい値で当て直すと送られます)。", "phone"),)The first card holds the settings rows. With no cards, the rows sit in one untitled
card. A panel names page code in PLATFORM_PANELS in
core/static/settings.html that draws the card’s body
and loads its state. The panels that exist are phone (YouTube), acquire (Stremio),
and account and feeds (Spotify). A new panel is a change to the page; names of
the platform in its code go under STATIC_DECLARED in the name guard test.
How the UI picks a platform up
Section titled “How the UI picks a platform up”GET /v1/source-kinds returns page_table() with each platform’s installed state:
def page_table() -> dict: return {k: {"title": v.title, "mines": v.fetch is not None, "fetch": v.fetch, "judged": v.judged, "columns": True, "shelf": v.shelf, "audio": v.audio, "mark": v.mark, "positions": v.positions, "settings": [declared(s) for s in v.settings], "cards": [asdict(c) for c in v.cards]} for k, v in PLATFORMS.items()}From that table, without naming any platform:
- Settings → Sources → プラットフォーム → 追加 lists every platform with an install
(+) or uninstall (trash) button, which call
POST /v1/platforms/{name}/installand/uninstall. Installing downloads the platform’s programs and starts its tracker, if it has one. Uninstalling cancels its queued and running fetch jobs, stops its tracker, deletes the files it downloaded and its programs, and keeps its settings, sources, clips and cards. - Each installed platform with
minesgets one section in Settings → Sources: its mark and title, a select for 全部 / 見たところだけ / マイニングしない (all, only what was watched whenpositionsis on, off), then its cards and settings rows. - Each platform with
minesgets a<title> のみ(that platform only) row in every per-platform override grid in Settings, such as the clip offsets and the days a video is kept; these save<key>:<name>. Eachjudgedplatform gets a 判定 tab and chip (the chip hidden while the platform does not mine), and a voice-separation row when it also mines. - The Sources page takes titles, shelves, marks and
audiofrom it, and Today takes titles, marks and the label of eachfetchjob. - The setup checklist shows the platform’s
fetch_stage.
The pages describes these Settings rows. Outside the built-in
platforms’ own panels and the Stremio key rows, no code in core/static names a
platform any more (#1526, closed).
A new platform still needs a few files there:
- a mark at
core/static/brands/<mark>.svg(checked bytests/operations/test_settings_dependencies.py), - a
JOB_LABELSentry incore/static/shell.jsfor each job kind it adds (checked bytests/test_job_stage_labels.py), - English entries in
core/static/i18n_en.jsorcore/static/i18n/en_settings.jsfor its Japanese labels and help, or they stay Japanese in the English UI.
Programs
Section titled “Programs”A platform can pin programs it downloads when it is installed. YouTube pins yt-dlp and a
PO-token provider this way. A pinned.Program maps (sys.platform, machine) to a
Pin(name, url, size, sha256), where machine is x86_64 or arm64; ("any", "any")
is the fallback. From platforms/youtube.py:
def _ytdlp(asset: str, size: int, sha256: str) -> pinned.Pin: return pinned.Pin("yt-dlp.exe" if asset.endswith(".exe") else "yt-dlp", f"{YTDLP_RELEASES}/download/{YTDLP_TAG}/{asset}", size, sha256)
_MACOS = _ytdlp("yt-dlp_macos", 37478576, "57654854886d0398a798895aadf5173e2749fbb5e249b9f3728022ab376e11fb")YTDLP = pinned.Program("yt-dlp", check=("--version",), pins={ ("win32", "x86_64"): _ytdlp( "yt-dlp.exe", 23627865, "622ed48023cac1daa52a3bf3a6ac38f03514de214b5f0fa069389fd0f6d17e5c"), ("win32", "arm64"): _ytdlp( "yt-dlp_arm64.exe", 22824772, "9bb324203d02970b70dab6c9f6a48bd5ff185db7859d562cdacd1dc655ccb72a"), ("linux", "x86_64"): _ytdlp( "yt-dlp_linux", 41184064, "249ddb058234276bc449b9cd9492aad9f133bda5923c61a9e39983ae114ef17d"), ("linux", "arm64"): _ytdlp( "yt-dlp_linux_aarch64", 40807480, "fb847a2e4a9ddc8cf5fcfb4bb7f42ba8969ecf72068def0278074f9d300bd13c"), ("darwin", "x86_64"): _MACOS, ("darwin", "arm64"): _MACOS,})The platform lists its programs in programs=(YTDLP, POT_PLUGIN, BGUTIL_POT).
platforms.install downloads each program into <AUTOMINER_HOME>/programs/<name>/
and checks its size and SHA-256. A program with check arguments must then run with
them, or it is deleted and the install is refused. The install is also refused when a
program pins nothing for this machine. A program with optional=True is skipped in
both cases instead; a failed download or checksum still refuses the install. A program
already in the folder is not downloaded again. A refused install answers POST /v1/platforms/{name}/install with
HTTP 502 and the reason, and the platform stays uninstalled. uninstall deletes the
folder, and pinned.home(name) gives the folder to your code. There is no general
updater: YouTube’s tick installs programs it lacks and updates yt-dlp itself.
Walkthrough: a minimal platform
Section titled “Walkthrough: a minimal platform”This walks through a platform for a made-up service, Acme, that has an id per video,
subtitle files, and downloadable videos. acme_api stands for your own module that
talks to the service; it is not part of AutoMiner.
1. Record watches only. The smallest platform is Jellyfin’s whole module:
from __future__ import annotations
from .interface import Platform
PLATFORM = Platform(name="jellyfin", title="Jellyfin", mark="jellyfin")Events with source: "jellyfin" are now recorded while it is installed, and the pages
show its title and mark. Nothing is mined.
2. Mine. Give the platform a fetch job and a way to get media. The shared step’s
default identify already reads media.platform_source_id, which ingest filled from
the event’s source_id. This is the shape of the test platform in
tests/sources/test_shared_fetch_step.py:
@dataclass(frozen=True)class Shelf(Platform): def get_media(self, conn, source, hook): ASKED.append(("media", source.id)) return f"/lib/{source.id}.mkv"
def get_audio(self, source): ASKED.append(("audio", source.id)) return f"/lib/{source.id}.m4a"
SHELF = Shelf(name="shelf", title="Shelf", fetch="fetch.shelf", subtitle_pool=False)With no subtitles of its own, a source of this platform goes to ASR with its audio.
3. Bring its own subtitles and details. Override own_subtitles and describe.
YouTube’s:
def own_subtitles(self, source: Source, lang: str) -> Subtitles | None: from .. import fetch_yt
try: got = fetch_yt.fetch_subtitles(source.id, lang=lang) except fetch_yt.ForeignTracksError as e: raise NotInLanguage(", ".join(e.tracks)) from e return Subtitles(*got) if got else None4. Put it together. core/autominer/platforms/acme.py:
from __future__ import annotations
from dataclasses import dataclass
from .. import acme_api, settings_registryfrom .interface import Details, Platform, Source, Subtitles
@dataclass(frozen=True)class Acme(Platform): def describe(self, source: Source): yield Details(duration_s=acme_api.duration(source.id))
def own_subtitles(self, source: Source, lang: str) -> Subtitles | None: text = acme_api.subtitles(source.id, lang) return Subtitles(text, "vtt", auto=False) if text else None
def get_media(self, conn, source: Source, hook) -> str | None: hook("download", {"message": source.id}) path = acme_api.download(source.id, settings_registry.sources_dir("Acme", source.id)) conn.execute( "UPDATE media SET uri = ?, source_retained = 1, source_archived_uri = NULL," " source_deleted_at = NULL WHERE id = ?", (f"file://{path}", source.media_id)) conn.commit() return path
PLATFORM = Acme(name="acme", title="Acme", fetch="fetch.acme", watch="https://acme.example/watch/{id}", mark="acme", subtitle_pool=False)settings_registry.sources_dir(...) returns a folder under the sources store and raises
SourcesUnavailable when the store cannot be used; it does not create the folder.
5. Register it. Import acme in platforms/__init__.py and add it to the tuple
(youtube, stremio, jellyfin, spotify).
6. Add a tracker, if Acme’s watches do not come from an outside client: a
track(stop) loop that posts envelopes with source: "acme", returned by tracker()
once Acme’s credentials are configured. Register the credentials in
settings_registry.py as described above.
7. Add settings, if the learner needs any: settings=(Setting(...),) and, for
checks, value_checks().
8. Fill in the page: core/static/brands/acme.svg, a JOB_LABELS entry for
fetch.acme, and English catalog entries for Japanese strings.
9. Pass the guard: add "platforms/acme.py" and "acme_api.py" to the
BUILT_IN_PLATFORM_CODE dict in tests/test_no_platform_names.py, each with a line
saying what the file is.
Testing a platform
Section titled “Testing a platform”The platform tests are in core/tests. Read these first:
| Test | What it shows |
|---|---|
sources/test_shared_fetch_step.py |
A test platform run through the shared step: ASR fallback, embedded subtitles, a held file, the subtitle pool, a missing id. |
operations/test_platform_installs.py |
Install state: no intake, fetch or tracker while not installed; uninstall and install again. |
adapters/test_trackers.py |
The tracker supervisor: paused on error, restarted on return, standby, AUTOMINER_TRACKING=0. |
ui/test_platform_sections_drawn.py |
The Settings sections drawn from page_table, including a platform table entry no built-in has. Most cases need Node. |
ui/test_platform_scoped_rows_drawn.py |
The per-platform override rows, 判定 tabs and Today’s fetch labels drawn from page_table, for that made-up platform too. Most cases need Node. |
sources/test_youtube_programs.py |
Pinned programs: download, checksum mismatch, a program that does not run. |
test_no_platform_names.py |
No platform name in core Python outside the platforms’ own files, and none in core/static code outside the listed panels. |
test_no_registry_snapshots.py |
No table built from PLATFORMS at import, no write into it outside platforms/__init__.py, and no direct read of a platform module’s PLATFORM outside platforms/. |
Fixtures in tests/conftest.py apply to every test:
_every_platform_installedmakesplatforms.installedreturnTrue. Use theplatform_installsfixture to get the real install state back._no_program_downloadsstubs outpinned.installand YouTube’skeep_programs. Use theprogram_downloadsfixture to download for real.
To run a test platform, put it in PLATFORMS with monkeypatch.setitem, queue its
fetch job and run the worker once. This test, written the way
test_shared_fetch_step.py is, puts an Acme with fixed subtitles through the shared
step:
from __future__ import annotations
from dataclasses import dataclass
import pytest
from autominer import db, jobs, platformsfrom autominer import lang as lang_profilesfrom autominer.platforms import Details, Platform, Source, Subtitles
VTT = "WEBVTT\n\n00:00:00.000 --> 00:00:01.500\nこんにちは\n\n00:00:01.500 --> 00:00:03.000\nまたね\n"ASKED: list = []
@dataclass(frozen=True)class Acme(Platform): def describe(self, source: Source): yield Details(duration_s=180.0)
def own_subtitles(self, source: Source, lang: str) -> Subtitles | None: ASKED.append(("subtitles", source.id, lang)) return Subtitles(VTT, "vtt", auto=False)
def get_media(self, conn, source: Source, hook) -> str | None: ASKED.append(("media", source.id)) return f"/library/{source.id}.mkv"
ACME = Acme(name="acme", title="Acme", fetch="fetch.acme", subtitle_pool=False)
@pytest.fixture()def conn(tmp_path, monkeypatch): path = str(tmp_path / "test.db") db.init_db(path) monkeypatch.setenv("AUTOMINER_DB", path) monkeypatch.delenv(lang_profiles.LANG_SETTING, raising=False) lang_profiles.invalidate() monkeypatch.setattr(jobs, "HANDLERS", {}) monkeypatch.setitem(platforms.PLATFORMS, ACME.name, ACME) ASKED.clear() c = db.connect(path) c.execute("INSERT INTO media (id, kind, lang, title, source, platform_source_id)" " VALUES ('m1', 'video', 'ja', 'Episode 1', 'acme', 'ep1')") c.commit() yield c c.close() lang_profiles.invalidate()
def _work(conn): class Stop: left = 1
def is_set(self): self.left -= 1 return self.left < 0
def wait(self, _timeout=None): return False
jobs.worker_loop(lambda: conn, Stop(), poll_s=0)
def test_acme_subtitles_are_stored_and_mined(conn): jobs.enqueue(conn, "fetch.acme", "m1") _work(conn) done = [(r["kind"], r["status"]) for r in conn.execute("SELECT kind, status FROM job ORDER BY rowid")] assert done == [("fetch.acme", "done"), ("mine", "queued")] assert conn.execute("SELECT COUNT(*) FROM segment WHERE origin = 'sub'").fetchone()[0] == 2 assert ASKED == [("subtitles", "ep1", "ja"), ("media", "ep1")] assert conn.execute("SELECT duration_s FROM media").fetchone()[0] == 180.0The order in ASKED is the shared step’s: subtitles first, then the media for clips.
To test a tracker, subclass Platform with a tracker() that returns your function, as
_Tracked in test_trackers.py does, and read /healthz from a TestClient.
Run the platform tests and the core suite as CONTRIBUTING says:
python -m pytest core/tests/sources/test_shared_fetch_step.py core/tests/test_no_platform_names.py \ core/tests/test_no_registry_snapshots.py core/tests/operations/test_platform_installs.py \ core/tests/adapters/test_trackers.py \ core/tests/ui/test_platform_sections_drawn.py core/tests/ui/test_platform_scoped_rows_drawn.py \ core/tests/test_job_stage_labels.py -qpython -m pytest core/tests -q -rs -p no:cacheprovider -k 'not mobile'Checklist
Section titled “Checklist”-
core/autominer/platforms/<name>.pydefinesPLATFORM, a frozen dataclass instance ofPlatformor a subclass. -
nameis one lowercase word that no core string uses;titleis set. - The module is in the tuple in
platforms/__init__.py. - To mine:
fetchis set, andget_media(andown_subtitles,describe,get_audiowhere the service offers them) are overridden. -
get_mediarecords the file on themediarow withsource_retained = 1. -
shelf,audio,positions,twin,watchand the subtitle flags match the service. - Watches arrive: a tracker that loops until
stop, catches its expected errors and returnsNoneuntil configured, or an outside client that postssource: <name>. - Credentials are registered in
settings_registry.py; settings rows are declared insettingswith alabel, andvalue_checksrefuses bad values. -
core/static/brands/<mark>.svg,JOB_LABELSfor each new job kind, and labels for any new progress stage exist. - English catalog entries exist for the Japanese labels and help.
- The platform’s files are in
BUILT_IN_PLATFORM_CODE. - Tests run the platform through its fetch (and its tracker, if any), and the core suite passes.
- The code has no comments or docstrings (
core/tests/test_no_comments.py).