Search by

detain / phlix-plugin-opensubtitles

detain

OpenSubtitles subtitle provider for Phlix — search and download subtitles for movies and TV shows via the OpenSubtitles REST API.

Package info

github.com/detain/phlix-plugin-opensubtitles

Type:phlix-plugin

pkg:composer/detain/phlix-plugin-opensubtitles

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.6.0 2026-10-30 21:10 UTC

This package is auto-updated.

Last update: 2026-12-02 15:46:24 UTC


README

tests

OpenSubtitles subtitle-provider plugin for Phlix — search and download subtitles for movies and TV shows via the OpenSubtitles REST API.

What it does

This plugin integrates OpenSubtitles into the Phlix subtitle pipeline. It allows searching for subtitles by:

  • IMDb ID — find subtitles for a specific movie/TV show
  • Filename — search subtitles by a media filename (its name stem is the search keyword; an embedded tt… IMDb ID is used as an IMDb ID lookup)
  • File hash — match subtitles using the OpenSubtitles moviehash algorithm

Install

The plugin is unsigned by design (signature: null); its supply-chain trust comes from the curated catalog pin described below. Install via the Phlix admin UI:

  1. Log in to your Phlix server as an admin user (users.is_admin = 1).

  2. Browse to /admin/plugins.

  3. Choose an install path:

    • Curated catalog (recommended). The server's plugin catalog (detain/phlix-plugins) carries a verified release entry for this plugin with a pinned artifact sha256. Installing from the catalog on the Plugins page satisfies the host's default-deny supply-chain gate with no operator overrides.

    • Install from URL. Paste an archive URL into the Install from URL form (backed by POST /api/v1/admin/plugins/install, which classifies a remote source by its file extension — so the URL must name an archive, e.g. the GitHub archive-tag form):

      https://github.com/detain/phlix-plugin-opensubtitles/archive/refs/tags/v0.6.0.tar.gz
      

      GitHub answers that URL shape with the single vetted codeload.github.com redirect hop the installer follows. The hop landed on the server's master branch on 2026-11-05 (45922861) and no server release tag carries it yet — on an older released build a URL install is refused with a redirect error until the host is updated (in a server checkout, git describe --contains 45922861 names the first tag built at or after the cure; today it errors — no release contains the commit yet).

  4. A raw plugin.json URL does not work with this plugin, by host design: the installer treats a .json URL as a stub manifest that must carry a top-level source field pointing at the real archive, and this plugin's manifest has none — such installs fail with Stub plugin.json must contain a "source" field pointing at a tarball or zip.

  5. Default-deny supply-chain gate: a remote source that is not pinned in the curated catalog is refused with Refusing to install unverified plugin source …: the catalog entry has no pinned artifact sha256 … The operator escape is PHLIX_PLUGINS_ALLOW_UNVERIFIED=1 in the server environment; it logs a warning and is meant as a temporary override — catalog-pinned installs and local file:// sources never need it.

  6. Enable the plugin. Installing only persists the plugin row; it lands disabled. Flip its toggle on the Plugins page (or send POST /api/v1/admin/plugins/{name}/enable). Until it is enabled the provider is never wired into the subtitle registry and every call throws OpenSubtitles provider is not enabled (see Known errors).

  7. Configure your OpenSubtitles API key in the plugin settings.

Host runtime requirement

Subtitle lookups run inside the Phlix server's async request path. The provider waits on its HTTP round-trips with short cooperative naps (usleep at 1 ms intervals) that rely on the server's runtime yielding them to the event loop — that is, on PHP with ext-swoole, the sleep hook enabled (SWOOLE_HOOK_SLEEP), and provider calls dispatched inside a coroutine, which is how the Phlix server boots its plugin workers (see the server's curated Swoole hook set).

On a host without that runtime the naps never yield, the vendored workerman/http-client callbacks can never be delivered, and every provider call stalls its full ~31-second deadline and then times out — the plugin cannot degrade gracefully on a non-hooked runtime. The plugin detects the stall instead of hiding it: when a wait loop runs its entire deadline without the awaited response settling, it writes one loud error_log fault report per process naming the finding (phlix-opensubtitles-005) and the runtime verdict. A healthy host never sees the line: there the client's own request timeout fires the error callback well before the local deadline, so every wait ends settled.

composer.json deliberately does not declare ext-swoole: the host owns the runtime choice, and a platform requirement would move the estate's security-audit corpus floor. The requirement is declared here and enforced by the detection/report above; installing this plugin on a non-hooked PHP runtime is unsupported by design.

Configuration

Configure these in the Phlix admin Plugins → Configure dialog.

Setting Required Secret Default Description
api_key Yes yes — API key for your OpenSubtitles.com consumer (API application).
username No — — OpenSubtitles.com username. Raises download limits (VIP limits for VIP accounts).
password No yes — OpenSubtitles.com password. Only used with the username.
language No — en Default language for the low-level *Raw searches when the caller omits one — sent verbatim, so provider-domain codes are expected (en, pb). The contract searches filter by the host-passed per-request language list (which normalizes estate BCP-47 codes: pt-BR maps to the provider's legacy pb, other region subtags are stripped, e.g. en-US → en) and ignore this setting.
format No — srt Requested download format: srt, ass, or vtt (anything else falls back to srt). Sent to the API as sub_format on each metered download, where the provider applies any conversion server-side; it never filters searches.
priority No — 10 Fallback ranking weight for subtitle sources the server's ordered subtitles.provider_priority list does not name — lower runs first (0 = highest priority). The list is consulted first and its shipped default already leads with opensubtitles; while this plugin is the only subtitle source in the estate the integer has no observable effect. The list lives in the server's config/subtitles.php (read live, DB-overridable; it has no curated-schema key yet, so it is not exposed in the admin UI).

Where to get your API key

Create a consumer (API application) on OpenSubtitles.com and copy its API key: opensubtitles.com/en/consumers. Providing your account username/password as well is optional but raises your download quota.

Where your settings rest

secret: true masks api_key and password in the admin UI and the logs — it is not at-rest encryption. The host persists plugin settings as plaintext JSON in its plugin_settings table, so read access to the server database — or its backups — recovers the stored values. Treat the database as secret material and rotate the OpenSubtitles consumer key if it is ever exposed.

How it works

The plugin implements the Phlix\Shared\Plugin\LifecycleInterface, Phlix\Shared\Plugin\ConfigurableInterface, and Phlix\Shared\Subtitle\SubtitleSourceInterface contracts and connects to the OpenSubtitles REST API v1:

  1. Login — lazy and conditional — nothing authenticates at install, enable, or boot. On the first search/download with username/password configured, the plugin obtains a session token (POST /login) and sends it as Authorization: Bearer <token> on API-origin requests. The token is refreshed when it reaches its advertised expiry or the server revokes it (a mid-session HTTP 401 costs exactly one refresh-and-retry, never a loop); a confirmed credential rejection suppresses further attempts for the enable cycle. Without username/password the plugin runs anonymously on the api_key alone — lower download limits, full search. The REST v1 API has no user-agent registration endpoint; see "User-Agent & OpenSubtitles ToS" below for what actually satisfies the terms.
  2. Search — queries subtitles by IMDb ID, filename, or moviehash. Each query returns the API first page only — result counts reflect that page, and the reported meta.total_pages is deliberately not followed; narrow the query instead of paging. The contract search methods map estate BCP-47 codes (en-US, pt-BR) into the OpenSubtitles language domain; the low-level *Raw methods send the caller's language verbatim, so they expect provider-domain codes (en, pb) and will silently match nothing if handed an unmapped estate code. The configured language setting is consulted only as the *Raw fallback when the caller passes none — the contract searches filter solely by the host-passed per-request language list and ignore that setting. The configured format does not filter searches; it is the requested download output format (see step 3).
  3. Download — two steps — POST /download with the file id consumes ONE quota unit and returns a temporary HTTPS link plus quota accounting; the plugin then fetches that link with a plain, credential-free HTTPS GET (the consumer key and session token never leave the API origin, and non-HTTPS links are refused). The step-1 body carries the configured format as sub_format — always one of srt, ass, or vtt (unknown settings fall back to srt) — so the provider performs any conversion server-side. Because step 1 meters the quota per call, a file's link is requested at most once per intentional download — never loop download() speculatively, and treat the quota exception below as "stop for this window".

When the account's download quota is exhausted, the shared-contract entry point download() throws Phlix\Shared\Subtitle\Exception\QuotaExceeded — carrying the remaining allowance and the reset time — so callers can stop retrying or fall back to another provider. QuotaExceeded extends RuntimeException, NOT OpenSubtitlesException; catching the plugin's own exception base around download() would miss it. The low-level downloadRaw() signals the same condition as OpenSubtitlesQuotaExceededException (a subclass of OpenSubtitlesException) — the type download() translates from. Once the API reports an exhausted window (remaining: 0 with a future reset_time_utc), further downloads are refused locally with those same two exception types — QuotaExceeded from download(), OpenSubtitlesQuotaExceededException from downloadRaw() — until that reset; the plugin never re-dials a window the vendor declared dead.

Runtime guards

Beyond the API semantics above, the provider enforces local safety guards on every call:

  • Download-link trust gate. The step-2 link returned by POST /download is fetched only when its host is opensubtitles.com or opensubtitles.org (exact or subdomain) over HTTPS on the default port (443); anything else — unparseable URLs included — is refused fail-closed, and that fetch never carries the Api-Key or session token.
  • Response size cap. Download bodies are capped at 10 MiB (MAX_RESPONSE_BYTES): the transfer is aborted mid-stream once the cap is exceeded, and a malformed oversized envelope is caught by the same check.
  • Deferral latches. An HTTP 429 (Retry-After, delta-seconds or HTTP-date) and an exhausted-quota window each latch locally for the advertised duration, clamped to 24 hours (MAX_LATCH_WINDOW_SEC); quota reset times are parsed as UTC. Inside a latched window searches and downloads fail fast without touching the network, and a passed window clears itself on the next call.
  • Strict TLS. Every connection verifies the peer certificate and its hostname on TLS 1.2 or higher; self-signed certificates are rejected and the provider never degrades to an insecure transport. The optional PHLIX_OPENSUBTITLES_CA_BUNDLE environment variable selects the trust anchor; a missing or unreadable bundle fails loudly rather than silently disabling verification.

Known errors

The exact refusal strings raised by this plugin, and what they mean:

  • OpenSubtitles provider is not enabled — the plugin is installed but still disabled: installing only persists the plugin row (Install step 6). Enable it before the subtitle pipeline can use it.
  • OpenSubtitles provider is not configured: the required `api_key` setting is empty; refusing an uncredentialed request — raised by every business call while api_key is empty. The manifest's required: true flag is advisory metadata the host does not enforce at save time; the provider enforces the requirement itself at each call boundary, so no uncredentialed request ever reaches the vendor. Set a consumer API key (Configuration).
  • HTTP response exceeded the 10 MiB cap — a download-link transfer grew past MAX_RESPONSE_BYTES and was aborted (Runtime guards); the oversized response is never buffered.

Install-side refusals — Stub plugin.json must contain a "source" field pointing at a tarball or zip. and Refusing to install unverified plugin source … — come from the host installer, not this plugin; see Install steps 4 and 5.

User-Agent & OpenSubtitles ToS

Every request this plugin makes — API origin and download-link hosts alike — carries the descriptive, contact-bearing User-Agent that OpenSubtitles' terms require:

Phlix-Plugin-OpenSubtitles/<plugin version> (+https://github.com/detain/phlix-plugin-opensubtitles)

The version comes from plugin.json; the contact route is the USER_AGENT_CONTACT_URL constant in the provider. The REST v1 API performs no user-agent registration handshake — the header itself IS the disclosure, and it is the vendor's path back to the maintainer. Non-descriptive or contact-less agents get the consumer key rate-limited or banned, and a ban lands on every Phlix instance sharing the build. Forks and derivatives MUST replace the product name and USER_AGENT_CONTACT_URL with their own identity and contact route before publishing.

API references: REST API docs · consumer (API application) portal.

Development

Setup (PHP >= 8.3). composer.lock is committed on purpose — CI audits exactly those pinned versions (the S246 security-audit gate reads the tracked lock), so install from it rather than re-resolving:

composer install

Local gates (the same commands .github/workflows/test.yml runs):

vendor/bin/phpunit                           # hermetic unit suite (fake transport, no network)
vendor/bin/phpstan analyse src --level=9     # or: composer phpstan
vendor/bin/phpcs src --standard=PSR12        # or: composer phpcs

There is deliberately no composer test script; run vendor/bin/phpunit directly. PSR-12 is gated on src/ only: tests/ follows the repo's snake_case test-method convention, which the raw PSR-12 sniff reports on (a pre-existing backlog) — keep new test code consistent with its neighbors rather than re-casing it.

License

MIT — see LICENSE.