dart_plex 0.3.1
dart_plex: ^0.3.1 copied to clipboard
Dart client for Plex Media Server and plex.tv. Supports JWT sign-in, library browsing, playlists, streaming, search and more, on Android, iOS, Linux, macOS, Windows and the web.
0.3.1 14-11-2026 #
All platforms #
Deprecated
account.friends(): plex.tv removed the route (410 Gone) and has no REST replacement.connectedUsers()lists the users the account shares with.transcoder.startUrl()andstreaming.universalVideoUrl(): PMS refuses a start without a decision, whichstartVideoTranscode()andstartAudioTranscode()make first.
Changed
- The token goes only to the connected server and to plex.tv. A full URL to another host is requested without it, unless
extraHeadersnames one. PlexMetadataType.photois13andphotoAlbumis14, as PMS has them, instead of the other way round.- A URL a player opens (
streamUrl(),transcodeUrl(),compositeImageUrl()and the like) throws astateerror beforeconnect()instead of starting withnull. - Those URLs form-encode the token, put it last and leave it out when there is none, instead of sending
X-Plex-Token=empty. - An id in a request path is one encoded segment, so a
/or a?in it cannot name another route. An empty id,.or..throws anArgumentError. - A call that returns a
Futurereports a wrong argument through it, never while it is being called. playQueues.addItems(),epg.lineupChannels(),server.securityResources(),collections.create()andtranscoder.imageUrl()check their arguments in release builds too.connect()throws astateerror at once for a URL withouthttp://orhttps://, or without a host.PlexClient.close()also closes the notification WebSocket and event stream.connectEventSource()sends its request at the first listener, so a failure to open reaches the stream instead of being lost.- An event stream that is silent for 60 seconds ends with a
timeouterror;idleTimeout: nullturns that off. - The event stream sends the token in a header, not in the query.
connectWebSocket()gives up afterconnectTimeout(30 seconds), and a401or403on the handshake is anautherror.server.ping()rethrows a cancellation and astateerror instead of answeringfalse.PlexHomeUser.protectedis the PIN flag alone; an account with a password and no PIN is no longer protected.- A timestamp without a zone is read as UTC, not as the device's local time.
PlexFilter.tag(),of(),number(),text()andflag()hold an unmodifiable list.- A failed TLS handshake is a
connectionerror instead ofunknown. - A token renewer that throws is the
causeof the401it could not renew. - The models are libraries of their own, one file per area, and the larger sub-APIs are split by concern. Nothing exported changed.
Fixed
collections.removeItem()sendsDELETE, which removes the item; PMS answers404to thePUTof the API document.hubs.continueWatching()reads the items inside its hub, so it no longer always comes back empty.- A hub from
hubs.manage()has its identifier, whichupdateVisibility(),deleteCustom()andmove()need. account.switchHomeUser()reads plex.tv's<user>answer, whose children repeat its attributes, instead of failing with aparseerror.- Event-stream notifications have their real
typeand the WebSocket's shape, soevents()reads them; the server'spingis no longer delivered. - A second
connectWebSocket()while the first is connecting throws astateerror instead of leaking a socket. pollJwtPin()throughwithCancelToken()views asks plex.tv for one nonce, not one per view.- A date out of range or a number that is not finite reads as
nullinstead of failing the whole page. - Lyrics lines that share a time keep the order of the file.
- Malformed plex.tv XML (a wrong closing tag, text after the root, absurd nesting) throws a
FormatException, never aStackOverflowError.
Added
connectWebSocket(connectTimeout:),connectEventSource(idleTimeout:), andwebSocketCloseCode,webSocketCloseReasonandmalformedFrameCountonnotifications.- The CI also checks the API docs, the web build and the pub.dev score, and runs on
quality/*branches.
0.3.0 8-11-2026 #
All platforms #
Breaking
- The package needs Dart
3.10or later. PlexClientand the sub-APIs have new members, so a fake that implements one must add them.- The names 0.2 deprecated are gone:
PlexDVRsApi,isRetriable,timeline(state:)andplayQueueItemId:(playStateis required), thePlexPlaybackApi.state*constants,universalAudioUrl()andnearestToTrack(excludeParentID:, excludeGrandparentID:). - A lookup returns
nullwhen the answer holds nothing:subscriptions.get(),devices.details(),dvrs.get(),downloadQueue.get()anditem(),liveTv.liveSession()andlibrary.person(), and alsosubscriptions.create(). - The other creates,
downloadQueue.create()among them, throw aparseerror on such an answer. The Errors and paging topic states the rule. downloadQueue,liveTv,dvrs,devices,subscriptionsandepgreturn typed models instead of maps:PlexDownloadQueue,PlexDownloadQueueItem,PlexDvr,PlexTunerDevice,PlexMediaGrabber,PlexDeviceChannel,PlexMediaSubscription,PlexMediaGrabOperation,PlexEpgCountry,PlexEpgLanguage,PlexLineup,PlexEpgChannelandPlexChannelMapping.liveTv.sessions()andliveSession()returnPlexMetadata.library.tags(),matches(),person()andsectionDetails(),playlists.generators(),updater.status(),server.securityResources()andbackgroundTasks(), andproviders.list()andadd()return typed models instead of maps:PlexTag,PlexMetadata,PlexPerson,PlexSectionDetails,PlexPlayQueueGenerator,PlexUpdaterStatus,PlexSecurityResource,PlexTranscodeJobandPlexMediaProvider.streaming.lyrics()returnsPlexLyrics, with the lines read as LRC and the text intext.account.tokenDetails()returns thePlexUserthe server token belongs to, from plex.tv, instead of asking the server, which answered an empty container.account.connectedUsers()returnsPlexAccountUsers fromplex.tv/api/users/, instead of asking the server, which answered an empty container.downloadQueue.itemMedia()isitemMediaUrl(), as the route answers the file, not JSON.itemMediaUrl()throws astateerror beforeconnect(), and leaves out an absent token.- The download queue takes
intids (queueId:,itemId:), as its models give them. playlists.generatorItems()andreprocessGenerator()take anintgeneratorId:, asPlexPlayQueueGenerator.idis.- The bitrate caps are named
max…BitrateKbps:startAudioTranscode()andmusicProfileExtra()takemaxAudioBitrateKbpsinstead ofmaxBitrateKbps, anduniversalVideoUrl()takesmaxVideoBitrateKbpsandmaxAudioBitrateKbpsinstead ofvideoBitrateandaudioBitrate. startAudioTranscode()anduniversalVideoUrl()take aPlexStreamingProtocolinstead of a string.universalVideoUrl()takes the protocol's container whencontainerisnull.sortparameters take aPlexSort:sort: PlexSort.addedAt.descinstead ofsort: 'addedAt:desc'.- Playlist and play queue types take a
PlexMediaType,addSection()aPlexLibraryType,firstCharacters()andcollections.create()aPlexMetadataType, and the marker calls aPlexMarkerType. library.tags()andsectionCommon()require atype, as the server answers 400 without one.connect(accessToken:)keeps the token it replaces as the account token, for plex.tv calls.clearSession()also drops the account token and the JWT session.PlexErrorTypehas a new value,passRequired, which aswitchover the type must handle.- A
498is anautherror.
Added
- plex.tv JWT sign-in:
PlexDeviceKey(an Ed25519 key pair, pure Dart, on every platform),account.createJwtPin(),pollJwtPin(),authAppUrl(),registerJwtKey(),authNonce(),exchangeDeviceJwt()andrefreshJwt(). PlexDeviceKey.privateKeyandpublicKeyare copies.PlexJwtreads a token's expiry.PlexJwt.parse()throws aparseerror for anexp,iatorthumbprintclaim of the wrong type.PlexClient.useJwt()with aPlexJwtSessionrefreshes the 7-day JWT before it expires and after a401or498.PlexJwtSessionhands each new token toonChangedto persist.- A token received in a run is timed from its arrival by its
exp - iat, so a skewed device clock does not refresh it on every call. - A token issued for less than two days is refreshed at half its lifetime.
- A refreshed token bound to another key is refused.
- When the first refresh fails,
useJwt()leaves the client as it was. PlexClient.tokenRenewer, aPlexTokenRenewer, is called with the connection's token when the server refuses it with401or498, and the request is retried once with the new one.- A request that sets
X-Plex-TokeninextraHeaders, or that the renewer makes itself, is not renewed. PlexClient.accountTokenandsetAccountToken(), the plex.tv token apart from the server's.PlexClient.connectToResource()andaccount.findConnection()try every connection at once, and the best that answers with the resource's machine identifier wins.- A
401on the resource token falls back to the tokenaccount.devices()lists for the server (account.serverTokenFromDevices()). - When no token works, the client keeps its previous server and tokens.
PlexResource.rankedConnections(),PlexServerConnection.kind,httpUri,rawandbracketIpv6(),PlexClient.connectTo(),connectionandconnectionKind.- An unbracketed IPv6 host in
PlexServerConnection.uri, or in the URL given toconnect(), is put in brackets. streaming.startVideoTranscode(),PlexVideoTranscodeandPlexStreamingApi.videoProfileExtra().PlexErrorType.passRequiredandPlexException.isPassRequired, for playback refused for want of a Plex Pass or Remote Watch Pass.- A decision, or a 4xx other than
401,404and498, ispassRequiredwhen its text says so. An HTML page does not count. - A bare
403stays anautherror. decisionUniversal()returns a pass refusal as it is.PlexException.bodyholds the whole error answer.PlexException.withType()copies an exception with another type.PlexTranscodeDecision.fromJson(),textandisPassRequired.account.homeUsers(),managedUsers(),switchHomeUser(),friends(),devices(),geoip(),watchlist()withPlexWatchlistFilter,addToWatchlist(),removeFromWatchlist()andPlexAccountApi.discoverKeyOf().library.folder(), for/library/sections/{id}/folder.library.item(includeMarkers:, includeChapters:),PlexMetadata.markers,chapters,markersOf(),images,squareArt,logoandeditionTitle.- A marker of type
credit, the API document's spelling, reads asPlexMarkerType.credits, the one PMS sends. PlexSort.then(), for ties.PlexSort.ascanddescchange the direction of the last field only.PlexLyricsreads the LRC ID tagsar,ti,al,au,by,length,offset,re,veand#.- Any other bracketed line of the lyrics, such as
[Chorus: Jay-Z], is text. PlexLyricCue.endholds when a word ends.rawonPlexChannelMapping,PlexMediaGrabber,PlexDeviceChannel,PlexEpgLanguage,PlexEpgChannel,PlexRelease,PlexSectionViewandPlexImage.PlexEpgChannel.signalQualityandsignalStrength, andPlexTunerDevice.lineupType.PlexStream.canNormalizeLoudness,albumRange,startRamp,endRamp,audioChannelLayout,displayTitleandextendedDisplayTitle.PlexFilter.atmos(),dolbyVision(),hdr(),videoCodec(),audioCodec(),subtitleCodec(),audioLayout(),audioLanguage(),subtitleLanguage(),inProgress()andduplicate().PlexUser.restricted,home,homeAdmin,protected,subscriptionFeatures,titleandraw, andPlexResource.raw.- A dependency on
cryptography^2.9.0, for the Ed25519 signatures of the JWT sign-in. - A CI workflow: analysis and tests at the SDK floor and on stable, formatting, a publish dry run, the transport drift check and, on demand, the integration suite.
Changed
PlexResource.bestConnection()followsrankedConnections(): local, remote, relay; HTTPS before HTTP; IPv4 before IPv6.bestConnection()leaves out the local addresses of a server neither owned nor shared through Plex Home.- An empty value in
extraHeadersremoves that header:{'X-Plex-Token': ''}sends none. - The value of an
X-Plex-Token,deviceJWTorpinquery parameter readsREDACTEDinPlexException.path,messageandtoString(). - A flag reads
true,1,"1"and"true"in every model. - The pinned API document is LukeHagar/plex-api-spec@23137a920c17.
- The drift test skips when the document cannot be fetched.
- The tests read PMS 1.43.2's own answers from
test/fixtures/real/. - The package description lists the web.
Fixed
liveTv.dvrs()reads theDVRspelling of the API document as well as the server'sDvr.- A
PlexTagfrom/library/tagshas its name and filter.
0.2.0 11-10-2026 #
A revision of the whole package. See MIGRATION.md for the changes to make in an app.
Breaking #
- The transport is
package:http, not Dio. Pass anyhttp.ClientashttpClient:(dio:is gone).request()and its siblings return aPlexResponse<T>and take aPlexResponseTypeand aPlexCancelToken.PlexException.fromDioandfetchBytes()are gone. - Every id is a named parameter:
library.item(ratingKey: …),playlists.items(playlistId: …),playback.scrobble(ratingKey: …)and so on. server.identity(),server.info(),sessions.history(),activities.list(),butler.tasks()andpreferences.all()return typed models instead of maps.preferences.byId()returnsnullfor an unknown id.- The API exposes
Object?instead ofdynamicin its maps and lists. - Models,
PlexException,PlexCredentials,PlexFilter,PlexNotificationandPlexTranscodeDecisionarefinal.PlexClientand the sub-APIs gained members, so a fake that implements one must add them. PlexMediaContainer.rawholds the envelope's own fields, without the entry array.playback.timeline()takes exactly one ofplayState:and the deprecatedstate:, and throwsArgumentErrorfor a duration of zero or less, a negative time orPlexPlayState.unknown.playlists.items(),library.children()andallLeaves()throwArgumentErrorfor astartwithout asize.library.autocomplete()requires aPlexMetadataType type.streaming.stopUniversal()returns normally when the session is already gone.- An empty answer without a JSON content type is
nullinPlexResponse.data, not"". Query values that are not strings are form-encoded, and aList<int>body is sent as bytes.
Added #
PlexClient.withCancelToken(), a view of the client whose calls one token cancels, andPlexClient.close().PlexRetryPolicy: opt-in resend ofGETandHEADafter a network failure,502,503,504or429, with backoff andRetry-After.PlexException.isNetworkFailure,isTransient,isNotFound,isCancelledandretryAfter.requestStream(), anddownloadToFile()in the newpackage:dart_plex/io.dart.library.children()with paging and sort,countChildren(),allLeaves()with paging,grandchildren(),recentlyAdded()andsearch.section().playlists.list()andcount()takefilters:andsort:.streaming.startAudioTranscode(), which makes the decision and caps the bitrate the way the server accepts, andPlexStreamingApi.musicProfileExtra().- Typed notification events:
PlexEventwithPlexPlaySessionEvent,PlexLibraryItemEvent,PlexActivityEvent,PlexStatusEventandPlexUnknownEvent, throughnotification.eventsorstream.events(). timeline(playState:, playQueueItemID:).PlexMetadata.roles,playlistItemId,playQueueItemId,audioStream,originallyAvailableAt,parentYear,leafCount,viewedLeafCount,childCount,skipCount,lastRatedAt,librarySectionId,librarySectionTitle,parentGuid,grandparentGuid,distance,scoreandultraBlurColors.PlexMetadata.thumbVersion,artVersion,parentThumbVersion,grandparentThumbVersionandPlexArtwork.versionOf(), for artwork cache keys.PlexStream.gain,albumGain,peak,albumPeak,loudnessandlra.PlexPaging.pages()anditems().
Changed #
- Large responses are decoded, inflated and parsed into models on a background isolate, above
jsonIsolateThreshold(50 KB by default). scrobble(),unscrobble(),rate()andsetFavorite()are sent asPUT.timeline()sends a time past the duration as the duration.PlexDVRsApiisPlexDvrsApi; the old name is a deprecated typedef.streaming.universalAudioUrl()is deprecated: usestartAudioTranscode().timeline(state: String)and thePlexPlaybackApi.state*constants are deprecated: useplayState:.timeline(playQueueItemId: String)is deprecated: useplayQueueItemID: int.nearestToTrack(excludeParentID:, excludeGrandparentID:)are deprecated: useexcludeParentRatingKeyandexcludeGrandparentRatingKey.isRetriableis deprecated: useisNetworkFailure, orisTransientto include 5xx and 429.- The pinned API document is LukeHagar/plex-api-spec@3f0fb272b29c, and a contract test checks every request against it.
Fixed #
library.firstCharacters()calls/firstCharacter: the old route answered 404.library.setItemArtwork(data:)uploads the bytes instead of their text.notifications.connectEventSource()keeps a quiet stream open, and closing it before the server answers cancels the request.- A gzip body cut short fails instead of coming back short.
- Two
createcalls throw aPlexExceptionof typeparse, not a bareException, when the server answers no item.
0.1.3 22-09-2026 #
0.1.2 09-09-2026 #
Fixed #
streaming.lyrics()returns readable text whatever the file's encoding: accented characters in a UTF-8.lrccame back mangled, and a UTF-16 one full of NUL.notifications.connectEventSource()decodes the event stream as a whole, so a multi-byte character split across two network chunks no longer becomes U+FFFD.
0.1.1 12-08-2026 #
Breaking #
library.allByType()andcountByType()takefilters, a list ofPlexFilter, instead offilter: writefilters: [PlexFilter.genre(6)]forfilter: 'genre=6'. Several filters are combined with AND.library.allByType()loses itstitleargument: usePlexFilter.titleContains()orPlexFilter.titleIs().library.genres()returnsList<PlexTag>instead ofList<PlexMetadata>. Pass a tag toPlexFilter.of(tag); usetag.titlefor its name.library.filters()returnsList<PlexLibraryFilter>:field,valueTypeandvaluesKeyreplaceraw['filter'],raw['filterType']andkey.library.updateSectionItems()names its argumentfilterExpressioninstead offilters. The request is unchanged.
Added #
PlexFilter, a typed library filter:genre(),tag(),year(),yearAfter(),yearBefore(),ratingAbove(),rated(),unplayed(),played(),titleContains(),titleIs(),firstCharacter(),studio(),contentRating(),resolution(), andnumber(),text(),flag()and a plain constructor for other fields.PlexFilter.of(tag), the filter for a genre, mood or style the server returned.library.filterValues(): the values a facet can take.PlexTag,PlexLibraryFilterandPlexFilterValueType.
Fixed #
- Filtering a library section works.
filter: ...was sent as a parameter namedfilter, which Plex ignores, so every filtered call returned the whole section. Filters travel as one parameter per condition, with the operator in the name:?genre=6,?year>>=2009,?unwatched=1. library.countByType()sends the same request asallByType()with a page size of zero, so a count matches the page it counts, filters included.
0.1.0 30-06-2026 #
Breaking #
liveTv.history(),liveTv.subscriptions()andliveTv.cancelSubscription()are gone: their routes do not exist. Usesessions.history()andPlexClient.subscriptions.streaming.directFileUrl()takes the item's file key instead of a part id and container.server.securityResources()requires asource.server.transientToken()takes notypeorscopeand returns the token string.transcoder.imageUrl():chromaSubsamplingis a number from 0 to 3.devices.setChannelMap()sends the mapping and the enabled channels the way Plex reads them.epg.bestLineup()requiresdeviceandlineupGroup.epg.lineupChannels()takes a list of lineups.playlists.moveItem(),playQueues.moveItem()andsubscriptions.reorder()move an item to the front whenafteris left out.PlexStream.selectedmeans the user picked the stream; the file default isPlexStream.isDefault.PlexHub.keyfetches a hub's content;hubKeyis the optional re-fetch key.subscriptions.create():typeis a number.notifications.connectWebSocket()returns aFuturethat completes once the socket is open, and a failed connection throws.
Added #
library.editItem(),deleteMetadataItem(),setItemArtwork()andupdateSectionItems().hubs.forMetadata(): the related rows of one item.sessions.historyItem(): one playback history entry.playlists.upload(): import an m3u playlist from a path on the server.PlexClient.clearSession(): drop the token and stay connected.
Changed #
collections.create()makes empty, named, typed and smart collections.playQueues.create()takes akeyfor the starting item.search.voice()takes atype.streaming.decisionUniversal()takes atranscodeType.PlexCredentialsaccepts the optionalX-Plex-Model,X-Plex-Device-VendorandX-Plex-Marketplaceheaders.request()andrequestBytes()take aCancelToken; a cancelled request isPlexErrorType.cancelled.PlexExceptionkeeps the original stack trace.PlexClient.fetchBytesis deprecated: userequestBytes.
Fixed #
addSection()andeditSection()apply the library settings they are given.- The transcode decision reads error codes as errors, so
isPlayable,isDirectandisTranscodeare right. playlists.generators()reads the right field.preferences.byId()returns the setting in the same shape asall().sessions.history()includes the start and end dates it is given.transcoder.imageUrl(),subtitlesUrl()andstartUrl()throw before connecting instead of returning a broken URL.subscriptions.editPreferences()sends the settings in the form Plex reads.- A body that cannot be decoded is a
parseerror. PlexResource.providesis empty when a resource advertises nothing.PlexMetadataType.photoAlbumuses the value Plex sends.
0.0.1 25-05-2026 #
Added #
- Initial release, for Plex Media Server
v1.43.x. - Sign-in with username and password, and the PIN link flow.
- The PMS HTTP client with the
X-Plex-*identity headers. PlexExceptionwith a semanticPlexErrorType.- Music endpoints: libraries, sections, items by type, playlists, artwork, audio streaming, playback reporting, search and favourites.
- Play queues, with
PlexPlayQueue. - Notifications over WebSocket and Server-Sent Events.
- Typed models, each with a
rawmap.
