Search by

detain / phlix-plugin-trakt

detain

Trakt scrobbler plugin for Phlix — scrobbles playback to Trakt.tv and syncs watch history over the Trakt OAuth API.

Package info

github.com/detain/phlix-plugin-trakt

Type:phlix-plugin

pkg:composer/detain/phlix-plugin-trakt

Statistics

Installs: 7

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

v1.5.0 2026-10-30 20:50 UTC

This package is auto-updated.

Last update: 2026-12-04 10:43:07 UTC


README

tests

Trakt scrobbler plugin for Phlix — scrobbles playback to Trakt.tv and syncs your watch history over the Trakt OAuth API.

Overview

Connects a Phlix server to your Trakt.tv account:

  • Scrobbles playback (start / pause / resume / stop) so Trakt shows what you're watching in real time and marks items watched at the end.
  • Two-way history sync — PULLS your Trakt watch history into Phlix on the configurable sync_interval_minutes interval; PUSHES Phlix completions back to Trakt event-driven (on playback stop at ≥ 90%), never on the interval. The push fires from inside the playback-stop scrobble path, so it needs both toggles: with scrobble_enabled off nothing is pushed even while pull sync stays on, and with sync_enabled off neither pulls nor pushes happen while scrobbles alone still flow. The full gate matrix is in Settings.
  • Authenticates via OAuth, refreshing tokens automatically.

It subscribes to phlix.playback.started, phlix.playback.paused, phlix.playback.resumed, and phlix.playback.stopped.

Requirements

Requires a Phlix server at version 1.2.4 or newer. The floor is set by the newest of three host-side pieces this plugin depends on:

  • Per-user OAuth state — this plugin is only usable once its host has completed the Trakt authorization ceremony, and that ceremony runs entirely host-side (the server's Phlix\Server\Integrations\Trakt\* state-store copies; the plugin's own state-store family was retired in S-trakt-11, finding phlix-trakt-029). Every state INSERT there writes the user_id column of oauth_state_store, added by server migration 110_oauth_state_store_user_id.sql. As measured 2026-12-01 that migration is in no released server tag, so the floor sits beyond the last release (1.2.3) at the first server version that can carry it.
  • Settings metadata — the manifest's link and link_text keys validate only against the host manifest schema from the phlix-shared v0.19.0 line (server tags 1.2.1+); server 1.2.0's older schema rejects them outright. The tier key needs the phlix-shared v0.43.0 line (commit ce6c60b), which no released server tag vendors — server v1.2.3 still pins shared ^0.20.0 — so tier admission also rides on the first future release (>= 1.2.4), as with migration 110.
  • Host tick wiring — the playback-cadence hooks resolve the entry instance through PluginLoader::getEntryInstance, first shipped in server 1.2.3.

plugin.json.phlix_min_server_version carries the same floor and tests/Unit/TraktManifestTest.php pins the two surfaces together. Because the host enforces the floor with version_compare(Version::STRING, …) and server releases currently report 1.2.3, installs from this repository's master are refused on every tagged host until a >= 1.2.4 server is released — that is the honest state of this dependency set, not a bug in the version check.

PHP extensions

Beyond the server version, the plugin needs three PHP extensions loaded in the interpreter that runs the host server. All three are hard require entries in this package's composer.json, so a composer install on a PHP build without them fails before the plugin is ever enabled:

  • ext-curl — the blocking HTTP fallback in src/HttpClient.php, used for every request made outside a coroutine context (inside one, the async path rides the host's Workerman HTTP client). Its response reader enforces the response-body ceiling while streaming.
  • ext-mbstring — UTF-8-safe bounding of remote-sourced error text (src/RemoteText.php) before it is echoed into exception messages and log lines.
  • ext-sodium — libsodium's authenticated crypto_secretbox (XSalsa20-Poly1305) backs src/SodiumTokenCipher.php, which encrypts OAuth tokens at rest with the host-provided token_encryption_key.

On the reference deployment (apt-based PHP), they install as php-curl, php-mbstring and php-sodium (packages vary by distro — ext-sodium ships with PHP on many builds, and mbstring/curl commonly do too; verify with php -m | grep -Ei 'curl|mbstring|sodium').

Install

From the Phlix admin Plugins section, paste this repo's URL:

https://github.com/detain/phlix-plugin-trakt

…or from the CLI:

php bin/phlix plugin:install https://github.com/detain/phlix-plugin-trakt

Installs resolve through the host's catalog trust model. A catalog entry pins the artifact (a 40-hex commit ref plus its sha256) and the server verifies both before loading anything. A repository URL that is not in the catalog is un-pinned: the host refuses it by default, and installs it only when the server runs with PHLIX_PLUGINS_ALLOW_UNVERIFIED=1 — a deliberate opt-out for operators who vouch for the source themselves. Release-line commits reach installs through the catalog's dev channel.

Set redirect_uri before you authorize. The redirect URI you register on your Trakt API app must match the one Phlix sends, byte for byte. If no redirect_uri is configured, the plugin falls back to the historic built-in default https://localhost/api/v1/oauth/trakt/callback (kept unchanged so existing registrations keep working) and logs a warning. That localhost value only suits a local install: for any other host, set TRAKT_REDIRECT_URI (or the trakt.redirect_uri admin setting) to your server's real callback URL and register the same URL with Trakt. See Settings below.

Authorizing Trakt

The OAuth ceremony runs host-side: the Phlix server performs the authorization redirect, exchanges the code and stores the resulting tokens; the plugin never shows an authorize button — it reads back what the server stored. In order:

  1. Install the plugin (above). Leave it disabled until step 3 — with no account connected the toggles have nothing to gate.
  2. Set the API credentials host-side. On the admin Services page (/app/admin/services, Trakt.tv section) enter your Trakt client_id and client_secret — they save as the trakt.client_id / trakt.client_secret admin keys, which take precedence over the TRAKT_CLIENT_ID / TRAKT_CLIENT_SECRET environment variables. Create a Trakt API application at https://app.trakt.tv/settings/apps/api/new only if you self-host your own Trakt credentials. Set redirect_uri first (warning above).
  3. Press "Connect to Trakt" on that same page. Your browser is sent to https://trakt.tv/oauth/authorize, Trakt returns to the server callback (/api/v1/oauth/trakt/callback), and the server exchanges the code. The username / access_token / refresh_token / expires_at settings then appear filled — you never type them.
  4. Enable the plugin (the enabled master switch) and choose the behavior toggles (scrobble_enabled, sync_enabled).

Settings

Setting Type Required Secret Tier Default Description
enabled boolean No No standard false Master switch for the integration: turns Trakt scrobbling and history sync on or off — every other Trakt setting does nothing while this is off. Optional; default off.
username string No No advanced "" The Trakt account Phlix is connected to; set automatically when the Trakt authorization (OAuth) flow completes. The plugin stays idle until it is present.
access_token string No Yes advanced null Obtained automatically when the Trakt authorization (OAuth) flow completes — you do not enter this by hand. Self-host API credentials (client id/secret/redirect URI) are set host-side on the Phlix server (TRAKT_* environment variables or admin Settings), not in this field; see the README.
refresh_token string No Yes advanced null Set automatically when the Trakt authorization (OAuth) flow completes; used to renew the access token. Not entered by hand.
expires_at integer No Yes advanced null Unix timestamp when the access token expires. Managed automatically.
sync_enabled boolean No No advanced true Pulls Trakt watch history into Phlix and lets finished Phlix items be pushed to Trakt; like every Trakt behavior, this is gated by the master switch above. Pulled completions are sized from the Trakt entry runtime when present, else from the local media item duration. Pushing completions additionally requires scrobbling to be enabled. Optional; default on.
sync_interval_minutes integer No No advanced 30 How often this plugin's own scheduled Trakt→Phlix history pull runs (minutes), and the window the shared trakt.sync_last_run_at completion stamp is gated against: an enable, or a tick, that finds a scheduled pull completed more recently than this interval stays quiet while the other scheduler keeps the cadence. The host server may also run its own watch-history sweep on a separate cadence; both coordinate through that stamp. Bounds: values below 1 fall back to the default 30 and values above 10080 (7 days) are clamped to it — both substitutions are logged. Saving a change while the plugin is enabled re-arms the timer live, no restart needed. Optional; default 30.
scrobble_enabled boolean No No advanced true Report playback start, pause, resume and stop to Trakt as you watch; like every Trakt behavior, this is gated by the master switch above. Optional; default on.

Which toggles gate which behavior (all three rows also require the master enabled switch and completed authorization — tokens plus username, which together are the plugin's configured state):

Behavior Needs scrobble_enabled Needs sync_enabled
Scrobble start / pause / resume / stop Yes —
Scheduled and on-demand history pull (Trakt→Phlix) — Yes
Completion push on stop at ≥ 90% (Phlix→Trakt) Yes Yes

access_token / refresh_token / expires_at are written by the Trakt authorization (OAuth) flow. There is nothing to fill in here — press Connect to Trakt on the admin Services page (see Authorizing Trakt under Install). Create a Trakt API application at https://app.trakt.tv/settings/apps/api/new only if you self-host your own Trakt credentials.

Self-host credentials are configured host-side, not in this table. Your app's client_id / client_secret / redirect_uri live on the Phlix server, which supplies them to the plugin at runtime: set the TRAKT_CLIENT_ID, TRAKT_CLIENT_SECRET and TRAKT_REDIRECT_URI environment variables, or enter them in the admin Settings page — the trakt.client_id / trakt.client_secret / trakt.redirect_uri keys there take precedence. The server's config/scrobblers/trakt.php documents that layer, and its token_encryption_key is what the plugin uses to encrypt OAuth tokens at rest.

Credential resolution tiers

The plugin resolves its operator credentials through three tiers, lowest precedence first:

  1. Config file — <phlix>/config/scrobblers/trakt.php (client_id, client_secret, redirect_uri, token_encryption_key).
  2. Environment — TRAKT_CLIENT_ID, TRAKT_CLIENT_SECRET, TRAKT_REDIRECT_URI, TRAKT_TOKEN_ENCRYPTION_KEY. These are read by the plugin itself (via getenv(), then $_ENV, then $_SERVER), so they work in any install shape; an empty value counts as unset.
  3. Admin Settings — trakt.client_id, trakt.client_secret, trakt.redirect_uri, applied when the host binds its Phlix\Admin\SettingsRepository implementation in the plugin container.

A saved admin value beats an environment value; an environment value beats a file literal. The file path itself resolves relative to the plugin's placement — under a standard host install it lands on the server file above, but where that path does not exist the env and admin tiers still supply everything needed to initialize the Trakt API client.

What a plugin install must provide for persistence

Resolving credentials makes scrobbling and sync run; saving the OAuth tokens needs a persistence writer, because the plugin never writes the server's database by itself:

  • Bind a Phlix\Plugins\Scrobbler\Trakt\TraktSettingsRepository implementation in the plugin container to persist settings and rotated tokens. Without it the plugin refuses token refresh once a link exists (PG-139) and refuses to establish a new encrypted link without a key (TRK-4) — fail-safe by design: Trakt one-time-rotates refresh tokens, and rotating one into memory that cannot be persisted destroys the link.
  • Bind a Phlix\Plugins\Scrobbler\Trakt\TokenCipher implementation, or provide token_encryption_key (env TRAKT_TOKEN_ENCRYPTION_KEY or the config file entry) — either one lets the plugin encrypt new links at rest. With a pre-existing link and no cipher the plugin keeps storing it unencrypted and says so in the log.

Rate Limits and Scheduling

Trakt throttles by request rate and answers HTTP 429 with a Retry-After hint. The plugin parses it and surfaces it as TraktRateLimitException::$retryAfter, but deliberately does not auto-retry: a scrobble that hits 429 is logged and dropped, and the next history pull simply waits for its regular tick — a blind deferred retry against a sustained rate limiter would queue load instead of relieving it. For the same reason the X-Ratelimit-* headers on successful (2xx) responses are not carried: nothing in the plugin budgets against them today, so surfacing them would be theater. retryAfter stays on the typed exception as an informational value for hosts that choose to consume it.

History pulling also has two independent schedulers: the plugin's own periodic timer (armed from sync_interval_minutes on enable, and re-armed live when a settings save moves the cadence or the sync gates — no restart; a saved value below 1 falls back to the default and one above 10080 minutes (7 days) is clamped, both substitutions logged) and the host server's scheduled watch-history sweep. They now coordinate through a shared completion ledger, the host-persisted trakt.sync_last_run_at setting: when this plugin enables in a resident process it reads that stamp first, and a pull completed inside the interval suppresses its own arm (the active scheduler keeps the cadence). Ticks that did arm re-check the same stamp before pulling, and a completed scheduled pull refreshes it — so across the host's many resident processes the first scheduled pull of an interval wins and the rest self-silence instead of multiplying full pulls. If the store cannot be resolved — or it offers no write leg, so nothing could refresh the ledger — the plugin falls back to arming ungated exactly as before. On-demand paths (the admin sync, syncHistoryFromTrakt) stay ungated, and the host stamps those around its own sweep. One residual remains: a process that skipped arming at enable only re-checks the ledger at its next enable, so it stays quiet while the host sweep is healthy.

Each scheduled pull itself is a delta walk: the syncer remembers the newest watched_at it has seen for the configured user (in-process, per username — a restart simply re-pulls, which is safe) and sends it as Trakt's start_at history filter, so an idle account costs almost no bandwidth instead of re-pulling the full 10,000-entry window every tick. Pages are requested at Trakt's maximum of 1,000 entries (ten pages per walk, same bounded worst case as before at a tenth of the requests), local media-item lookups for both paths compare external ids in the same JSON-quoted domain, and completions that need a duration are sized from a single batched metadata read rather than one query per entry. History entries that resolve to no local media item are no longer silent: each is debug-logged, and a tick that dropped any warns once with the count and carries items_unresolved in its completion line, so items_written: 0 is distinguishable from "nothing new". Delta walks advance past entries that failed to resolve, so a history row whose media item joined the library only later is retried at the next full pull (a process restart).

Troubleshooting

Every failure the plugin cannot recover from by itself is logged with the Trakt plugin: prefix. The exact phrases, and what to do about them:

  • expired access token and refresh failed (manual re-authorization required) — warnings on scrobble start skipped / scrobble pause skipped / scrobble stop skipped / history push dropped / history pull skipped (a resume rides the scrobble start message) — or the error form still unauthorized after refresh; manual re-authorization required on a history push/pull. The refresh grant is dead; the usual causes are a password change or a revoke on Trakt, which end it. Scrobbles are skipped and the history legs stay unauthorized until you re-authorize: press Connect to Trakt again on the admin Services page. One completed OAuth flow replaces the whole token set.
  • stored tokens could not be decrypted (key rotation or corruption); re-link required — the server's token_encryption_key changed (or a stored envelope was damaged), so the plugin cannot read its own token store, and it will never fall back to plaintext. Re-authorize once; the tokens are re-encrypted under the current key.
  • refusing to persist a newly linked account unencrypted; no token cipher (configure token_encryption_key or bind Phlix\Plugins\Scrobbler\Trakt\TokenCipher, then re-link) — the first ever link on a host with no token cipher fails closed: the fresh tokens are dropped rather than written in plaintext (your other settings are kept). Configure token_encryption_key (the server's config/scrobblers/trakt.php documents that layer) and re-authorize. A pre-existing link on a cipher-less host degrades instead, warning no token cipher available; storing OAuth tokens unencrypted.
  • operator config is missing client_id, client_secret; Trakt OAuth API client was not initialized — the plugin process has no API credentials, so every Trakt leg stays inert. Because the Services page reads the stored tokens, the account can still show Connected while no traffic flows (estate finding phlix-trakt-003; its host-side half is tracked there). Save the credentials as the trakt.client_id / trakt.client_secret admin keys (they take precedence) or set the TRAKT_CLIENT_ID / TRAKT_CLIENT_SECRET environment variables, then restart the host or re-toggle the plugin.
  • operator config has no redirect_uri; falling back to the built-in default — the callback is the historic https://localhost/... placeholder, which cannot match a real Trakt app registration on any other host; the exchange fails at Trakt, not here. See the redirect_uri warning under Install.
  • HTTP 429 responses are logged with the parsed Retry-After hint and dropped by design — the next scheduled tick resumes normally (see Rate Limits and Scheduling).

Development

composer install
vendor/bin/phpunit                       # default: deterministic Unit suite
vendor/bin/phpunit --testsuite Network   # live httpbin round trips, on demand
vendor/bin/phpstan analyse src --level=9 # CI static-analysis gate
vendor/bin/phpcs src --standard=PSR12    # CI coding-standards gate
php scripts/security-audit-check.php     # audit composer.lock (runtime + dev)

These deterministic gates run in CI on PHP 8.3, 8.4 and 8.5. The phpstan config (phpstan.neon) carries seven class.notFound baseline entries — one per concrete host class src/ names that is absent from this package's dependency closure: Phlix\Auth\WatchHistory, Phlix\Media\Library\MediaItem, Phlix\Media\Library\ItemRepository, Phlix\Admin\SettingsRepository, Workerman\MySQL\Connection, Workerman\Timer, Workerman\Http\Client. Per the PG-138 rule the baseline enumerates one concrete message per class and never widens to a wildcard or a category (the older nine-wildcard config was retired precisely because new type errors slipped through it unnoticed); Workerman\Http\Response is deliberately not listed, because src/ never names it. The plugin's own typed code is analysed at level 9 with no per-line suppressions.

The entry class is Phlix\Plugins\Scrobbler\Trakt\TraktPlugin (implements Phlix\Shared\Plugin\LifecycleInterface and Phlix\Shared\Plugin\ConfigurableInterface). It runs inside a Phlix server host, which provides the playback/library services at runtime. Host-supplied names (Phlix\Auth\WatchHistory, Phlix\Admin\SettingsRepository, Phlix\Common\Http\EventLoopTls, Phlix\Common\Runtime\WorkerContext, Phlix\Common\Uuid, Phlix\Media\Library\MediaItem, Workerman\Http\Client, Workerman\Http\Response, Workerman\MySQL\Connection, Workerman\Timer) are provided by the test harness so the unit suite runs standalone: the four Workerman\* names are class stubs in files under tests/stubs/ that tests/bootstrap.php requires, and the six Phlix\* names are class_alias bindings defined inline in that bootstrap. Two names you may grep for are deliberately not in the harness list: Workerman\Worker survives only in a historical-approach docblock in src/HttpClient.php and nothing stubs it, and Phlix\Media\Library\ItemRepository is the one host class src/ names without a stub — it is covered by the phpstan baseline above, and the tests that need it alias a local fake inside tests/Unit/TraktPluginTest.php. tests/Unit/TraktManifestTest.php re-censuses this list on every run. phpunit.xml sets the default suite to Unit and excludes tests/Network/HttpClientNetworkTest.php, which talks to a third-party service.

License

MIT — see LICENSE.