Skip to main content

dart_plex 0.2.2 copy "dart_plex: ^0.2.2" to clipboard
dart_plex: ^0.2.2 copied to clipboard

Dart client for Plex Media Server. Supports authentication, library browsing, playlists, streaming, search and more. Targets macOS, Windows, Linux, iOS and Android.

dart_plex #

Plex Media Server client for Flutter and Dart.

logo dart_plex is a Dart client for Plex Media Server 1.43. It covers libraries, playlists, streaming, playback reporting, play queues and search through typed Dart objects, and handles plex.tv sign-in and server discovery.

Installation #

Add dart_plex to your pubspec.yaml:

dependencies:
  dart_plex: ^0.2.2

Features #

Pure Dart
no native plugin and no Flutter dependency. The main library also runs on the web; only the file helpers in io.dart need dart:io.
Typed models
libraries, items, media, streams, hubs, server info, history and events are typed Dart objects, each with a raw map for the fields it does not lift.
Both sign-in flows
the PIN flow at plex.tv/link and username and password.
Server discovery
fetchResources() lists owned and shared servers; bestConnection() picks local first, then HTTPS, then relay.
One client
a PlexClient holds the identity, the server and the token, and every sub-API works through it.
Audio streaming
startAudioTranscode() starts an HLS or DASH transcode with a bitrate cap; directFileUrl() gives the original file.
Your HTTP stack
any http.Client: the default dart:io one, cupertino_http or cronet_http for HTTP/2 and the system proxy, a MockClient in tests.
Off the calling isolate
large responses are inflated, decoded and parsed into models on a background isolate.
Cancellation and retries
withCancelToken() makes every call of a page cancellable; an opt-in PlexRetryPolicy resends idempotent requests after transient failures.
Live events
the server's notifications decoded into a sealed PlexEvent type: play states, library changes, scans.
Typed errors
every failure is a PlexException you can branch on: auth, not found, network, transient, cancelled.
Escape hatch
request(), requestBytes() and requestStream() reach endpoints the typed sub-APIs do not cover.

Quick start #

import 'package:dart_plex/dart_plex.dart';

Future<void> main() async {
  final plex = PlexClient(
    credentials: const PlexCredentials(
      clientIdentifier: 'PUT-YOUR-UUID-HERE', // stable per install
      product: 'MyApp',
      version: '1.0.0',
      device: 'iPhone',
      deviceName: 'My iPhone',
      platform: 'iOS',
    ),
  );

  // 1. Sign in: the user enters the code at plex.tv/link.
  final pin = await plex.account.createPin();
  print('Enter ${pin.code} at https://plex.tv/link');
  var state = pin;
  while (!state.isAuthenticated) {
    await Future<void>.delayed(const Duration(seconds: 2));
    state = await plex.account.pollPin(id: pin.id);
  }
  plex.setToken(state.authToken);

  // 2. Find the user's server and connect to it.
  final servers = await plex.account.fetchResources();
  final server = servers.firstWhere((s) => s.owned);
  plex.connect(server.bestConnection()!.uri, accessToken: server.accessToken);

  // 3. Browse the music library.
  final sections = await plex.library.sections();
  final music = sections.firstWhere((s) => s.type == PlexLibraryType.music);
  final albums = await plex.library.allByType(
    sectionId: music.id,
    type: PlexMetadataType.album,
    sort: 'titleSort:asc',
  );

  // 4. Stream the first track of the first album.
  final tracks =
      await plex.library.children(ratingKey: albums.items.first.ratingKey);
  final transcode = await plex.streaming.startAudioTranscode(
    ratingKey: tracks.first.ratingKey,
    session: 'a-uuid-per-playback',
    maxBitrateKbps: 192,
  );
  print(transcode.url); // hand this to your audio engine

  // 5. Release the HTTP client.
  plex.close();
}

How it works #

PlexClient holds the identity of your app, the server and the token. Each part of the Plex API is a sub-API on it (plex.library, plex.playlists, plex.streaming and so on), and every call goes through one connection, the same transport dart_jellyfin uses.

Architecture: your code calls PlexClient; PlexConnection sends through an http.Client and parses large answers on a background isolate into typed models

Working with the client #

A client for tests #

final plex = PlexClient(
  credentials: credentials,
  httpClient: MockClient((request) async => http.Response(
        '{"MediaContainer":{"size":0,"Directory":[]}}',
        200,
        headers: {'content-type': 'application/json'},
      )),
);

Any http.Client works, such as cupertino_http or cronet_http for HTTP/2 and the system proxy. See Client and sign-in for the constructor options, credentials, both sign-in flows and how a connection is picked.

The server #

final info = await plex.server.info();
print('${info.friendlyName} ${info.version}, sonic analysis: ${info.musicAnalysis}');

final running = await plex.activities.list();
final scan = running.where((a) => a.cancellable).firstOrNull;
if (scan != null) await plex.activities.cancel(activityId: scan.uuid);

See Server for butler tasks, settings, the log, updates and the other admin calls.

Filtered browsing #

final page = await plex.library.allByType(
  sectionId: music.id,
  type: PlexMetadataType.album,
  filters: [PlexFilter.genre(6), PlexFilter.yearAfter(2009)],
  sort: 'addedAt:desc',
);
print('Got ${page.items.length} of ${page.totalSize}');

See Library for sections, filters, facets, collections, editing and sonic radio.

Reporting a play #

await plex.playback.timeline(
  ratingKey: track.ratingKey,
  playState: PlexPlayState.playing,
  timeMs: 42000,
  durationMs: track.durationMs!,
);

Send a report on every state change and every 10 s while playing. See Playback and play queues for when a play counts, ratings, sessions, history and server play queues.

A playlist #

final playlist = await plex.playlists.create(
  title: 'My Mix',
  type: 'audio',
  machineIdentifier: machineId,
  itemRatingKeys: const ['12345', '12346'],
);

See Playlists for listing, editing entries, smart playlists and import.

A transcode to keep alive #

final transcode = await plex.streaming.startAudioTranscode(
  ratingKey: track.ratingKey,
  session: sessionId,
  maxBitrateKbps: 128,
);
await plex.streaming.pingUniversal(session: sessionId); // every 30 s while paused
await plex.streaming.stopUniversal(session: sessionId); // when the user leaves

The calls return URLs and never fetch the audio. See Streaming for direct files, video decisions, transcoder URLs, lyrics and loudness.

Live TV #

final dvrs = await plex.liveTv.dvrs();
await plex.dvrs.tuneChannel(dvrId: dvrId, channel: '2.1');
final rules = await plex.subscriptions.list();

Most Live TV calls return the server's maps. See Live TV for sessions, DVRs, recording rules, tuners and the program guide.

Errors #

try {
  await plex.library.sections();
} on PlexException catch (e) {
  if (e.isAuthError) await signInAgain();
  else if (e.isTransient) scheduleRetry(e.retryAfter);
  else showError(e.message);
}

See Errors and paging for the error types, cancel tokens, the retry policy and paging. Raw requests reach the endpoints the sub-APIs do not cover.

Search as you type #

searchToken?.cancel(); // drop the previous keystroke's request
final token = searchToken = PlexCancelToken();
final hubs = await plex.withCancelToken(token).search.hubs(query: text);

See Search for hub, section, flat and voice search.

Live events #

final frames = await plex.notifications.connectWebSocket();
frames.events().listen((event) {
  if (event is PlexActivityEvent && event.isLibraryScan && event.isEnded) {
    reloadLibrary();
  }
});

See Events and downloads for every event type and for downloads to disk.

Artwork #

final url = plex.images.transcodeUrl(sourcePath: album.thumb!, width: 300, height: 300);
final cacheKey = '${album.ratingKey}@${album.thumbVersion}';

See Images and hubs for artwork versions, UltraBlur backdrops and the home screen's hubs.


Documentation #

  • API reference, with these guides:
    • Client and sign-in: the client, credentials, the HTTP stack, tests, the PIN flow and server discovery
    • Server: identity, activities, butler tasks, settings and administration
    • Library: sections, items, filters, collections, editing and sonic radio
    • Playlists: listing, creating and editing playlists, smart playlists and import
    • Search: hub, section, flat and voice search
    • Playback and play queues: timeline reports, ratings, sessions, history and play queues
    • Streaming: audio and video transcodes, direct files, lyrics and loudness
    • Images and hubs: resized artwork, cache keys, UltraBlur and hubs
    • Live TV: live sessions, DVRs, recording rules, tuners and the guide
    • Errors and paging: typed errors, cancellation, retries and paging
    • Events and downloads: notifications, typed events, downloads and download queues
    • Raw requests: request(), requestBytes() and requestStream()
  • Example
  • CHANGELOG and MIGRATION

Project background #

I wrote the typed models, the sub-APIs and the transport with Claude Code.

Plex is a trademark of Plex, Inc. dart_plex is not affiliated with it.


Developed by Alessandro Di Ronza

6
likes
0
points
1.28k
downloads

Publisher

verified publisherales-drnz.com

Weekly Downloads

Dart client for Plex Media Server. Supports authentication, library browsing, playlists, streaming, search and more. Targets macOS, Windows, Linux, iOS and Android.

Repository (GitHub)
View/report issues

Topics

#plex #media-server #music #streaming #api-client

License

unknown (license)

Dependencies

http, meta, web_socket_channel

More

Packages that depend on dart_plex