Comprehensive media library access including browsing sections, searching content, managing metadata, and working with movies, TV shows, music, and photos.
Main interface for browsing and searching across all media libraries.
class Library:
def sections(self):
"""
Get all library sections.
Returns:
list: List of LibrarySection objects (MovieSection, ShowSection, etc.)
"""
def section(self, name):
"""
Get library section by name.
Args:
name (str): Section name (e.g., 'Movies', 'TV Shows')
Returns:
LibrarySection: Specific section object
Raises:
NotFound: If section with specified name doesn't exist
"""
def search(self, title=None, libtype=None, **kwargs):
"""
Search across entire library.
Args:
title (str, optional): Title to search for
libtype (str, optional): Media type ('movie', 'show', 'artist', 'photo')
**kwargs: Additional search filters
Returns:
list: List of matching media objects
"""
def recentlyAdded(self):
"""
Get recently added media across all sections.
Returns:
list: List of recently added media objects
"""
def onDeck(self):
"""
Get on deck (in-progress) media.
Returns:
list: List of media objects that are in progress
"""
def sectionByID(self, sectionId):
"""
Get library section by ID.
Args:
sectionId (int): Section ID number
Returns:
LibrarySection: Specific section object
Raises:
NotFound: If section with specified ID doesn't exist
"""
def cleanBundles(self):
"""Clean unused metadata bundles to free disk space."""
def emptyTrash(self):
"""Empty the library trash for all sections."""
def optimize(self):
"""Optimize library database for better performance."""Base functionality for all library sections.
class LibrarySection:
"""Base class for all media library sections."""
def get(self, title, year=None):
"""
Get specific item by title.
Args:
title (str): Item title to find
year (int, optional): Year for disambiguation
Returns:
Media object matching the title
Raises:
NotFound: If no item matches the criteria
"""
def all(self):
"""
Get all items in section.
Returns:
list: All media items in this section
"""
def search(self, title=None, **kwargs):
"""
Search within this section.
Args:
title (str, optional): Title to search for
**kwargs: Additional filters (year, genre, etc.)
Returns:
list: List of matching items
"""
def refresh(self):
"""Refresh section metadata from disk."""
def update(self):
"""Update section settings and configuration."""
def history(self, maxresults=None, mindate=None):
"""
Get playback history for this section.
Args:
maxresults (int, optional): Maximum number of results
mindate (datetime, optional): Earliest date to include
Returns:
list: List of historical playback records
"""Specialized functionality for movie collections.
class MovieSection(LibrarySection):
"""Movie library section with movie-specific features."""
def recentlyAdded(self):
"""Get recently added movies."""
def recentlyViewed(self):
"""Get recently watched movies."""
def decade(self):
"""Get movies grouped by decade."""
def genre(self):
"""Get movies grouped by genre."""
def contentRating(self):
"""Get movies grouped by content rating."""
def unwatched(self):
"""Get unwatched movies."""
def watched(self):
"""Get watched movies."""
def collections(self):
"""
Get movie collections in this section.
Returns:
list: List of Collection objects
"""Specialized functionality for TV show collections.
class ShowSection(LibrarySection):
"""TV show library section with show-specific features."""
def seasons(self):
"""Get all seasons across all shows."""
def episodes(self):
"""Get all episodes across all shows."""
def recentlyAired(self):
"""Get recently aired episodes."""
def recentlyAdded(self):
"""Get recently added shows and episodes."""Specialized functionality for music collections.
class MusicSection(LibrarySection):
"""Music library section with music-specific features."""
def artists(self):
"""Get all artists."""
def albums(self):
"""Get all albums."""
def tracks(self):
"""Get all tracks."""
def playlists(self):
"""Get music playlists."""
def stations(self):
"""Get radio stations."""Specialized functionality for photo collections.
class PhotoSection(LibrarySection):
"""Photo library section with photo-specific features."""
def photoalbums(self):
"""Get photo albums."""
def photos(self):
"""Get all photos."""
def years(self):
"""Get photos grouped by year."""
def tags(self):
"""Get photo tags."""Rich movie objects with comprehensive metadata.
class Movie:
"""Feature film with rich metadata."""
@property
def title(self): ...
@property
def year(self): ...
@property
def summary(self): ...
@property
def rating(self): ...
@property
def duration(self): ...
@property
def contentRating(self): ...
@property
def genres(self):
"""List of genre tags."""
@property
def directors(self):
"""List of director objects."""
@property
def writers(self):
"""List of writer objects."""
@property
def roles(self):
"""List of cast member objects."""
def play(self, client=None):
"""Play movie on specified client."""
def markPlayed(self):
"""Mark movie as watched."""
def markUnplayed(self):
"""Mark movie as unwatched."""
def uploadSubtitles(self, filepath):
"""
Upload subtitle file for this movie.
Args:
filepath (str): Path to subtitle file to upload
"""
def searchSubtitles(self, language='en'):
"""
Search for available subtitles.
Args:
language (str): Language code for subtitles
Returns:
list: List of available subtitle results
"""
def downloadSubtitles(self, subtitle, filepath=None):
"""
Download subtitle file.
Args:
subtitle: Subtitle object to download
filepath (str, optional): Path to save subtitle file
"""
def removeSubtitles(self, subtitle):
"""
Remove subtitle track.
Args:
subtitle: Subtitle track to remove
"""
def optimize(self, **kwargs):
"""
Optimize video file with transcoding.
Args:
**kwargs: Optimization parameters
"""Hierarchical TV show structure with shows, seasons, and episodes.
class Show:
"""TV series container with seasons and episodes."""
@property
def title(self): ...
@property
def year(self): ...
@property
def summary(self): ...
def seasons(self):
"""Get all seasons for this show."""
def season(self, seasonNumber):
"""Get specific season by number."""
def episodes(self):
"""Get all episodes across all seasons."""
def episode(self, season=None, episode=None):
"""Get specific episode."""
def watched(self):
"""Get watched episodes."""
def unwatched(self):
"""Get unwatched episodes."""
class Season:
"""TV show season container."""
@property
def show(self):
"""Parent show object."""
@property
def seasonNumber(self): ...
def episodes(self):
"""Get all episodes in this season."""
def episode(self, episode):
"""Get specific episode by number."""
class Episode:
"""Individual TV episode."""
@property
def show(self):
"""Parent show object."""
@property
def season(self):
"""Parent season object."""
@property
def episodeNumber(self): ...
@property
def seasonNumber(self): ...
@property
def title(self): ...
@property
def summary(self): ...Hierarchical music structure with artists, albums, and tracks.
class Artist:
"""Music artist or band."""
@property
def title(self): ...
@property
def summary(self): ...
def albums(self):
"""Get all albums by this artist."""
def album(self, title):
"""Get specific album by title."""
def tracks(self):
"""Get all tracks by this artist."""
def track(self, title):
"""Get specific track by title."""
class Album:
"""Music album with track listing."""
@property
def title(self): ...
@property
def year(self): ...
@property
def artist(self):
"""Album artist object."""
def tracks(self):
"""Get all tracks on this album."""
def track(self, title):
"""Get specific track by title."""
class Track:
"""Individual music track."""
@property
def title(self): ...
@property
def artist(self):
"""Track artist object."""
@property
def album(self):
"""Parent album object."""
@property
def trackNumber(self): ...
@property
def discNumber(self): ...
@property
def duration(self): ...
def sonicallySimilar(self, **kwargs):
"""
Find tracks sonically similar to this track.
Args:
**kwargs: Search parameters for similarity matching
Returns:
list: List of similar Track objects
"""Photo albums and individual photos with EXIF data.
class Photoalbum:
"""Photo album container."""
@property
def title(self): ...
def photos(self):
"""Get all photos in this album."""
def photo(self, title):
"""Get specific photo by title."""
class Photo:
"""Individual photo with EXIF metadata."""
@property
def title(self): ...
@property
def year(self): ...
@property
def originallyAvailableAt(self): ...
# EXIF properties
@property
def make(self): ... # Camera manufacturer
@property
def model(self): ... # Camera model
@property
def lens(self): ... # Lens information
@property
def iso(self): ... # ISO setting
@property
def aperture(self): ... # Aperture setting
@property
def exposure(self): ... # Exposure timeRich metadata support for organizing and filtering content.
# Tag classes for organizing content
class Genre:
"""Genre classification tag."""
@property
def tag(self): ...
@property
def count(self): ...
class Director:
"""Director information."""
@property
def tag(self): ... # Director name
@property
def role(self): ... # Director role
class Role:
"""Cast member information."""
@property
def tag(self): ... # Actor name
@property
def role(self): ... # Character name
@property
def thumb(self): ... # Actor photo
class Collection:
"""Collection membership."""
@property
def tag(self): ... # Collection name
# Additional metadata classes
class Country:
"""Country of origin."""
class Studio:
"""Production studio."""
class Writer:
"""Writer/screenplay credits."""from plexapi.server import PlexServer
plex = PlexServer('http://localhost:32400', token='your-token')
# Get all library sections
sections = plex.library.sections()
for section in sections:
print(f"{section.title}: {section.type}")
# Access specific sections
movies = plex.library.section('Movies')
shows = plex.library.section('TV Shows')
music = plex.library.section('Music')
# Access section by ID (useful when section names change)
section_1 = plex.library.sectionByID(1) # First library section# Get specific movie
movie = movies.get('The Matrix', year=1999)
print(f"Duration: {movie.duration // 60000} minutes")
print(f"Rating: {movie.rating}")
# Browse movie metadata
for genre in movie.genres:
print(f"Genre: {genre.tag}")
for actor in movie.roles[:5]: # First 5 actors
print(f"{actor.tag} as {actor.role}")
# Search for movies
action_movies = movies.search(genre='Action')
recent_movies = movies.recentlyAdded()# Get specific show
show = shows.get('The Office')
print(f"Seasons: {len(show.seasons())}")
# Get specific episode
episode = show.episode(season=2, episode=1)
print(f"S{episode.seasonNumber:02d}E{episode.episodeNumber:02d}: {episode.title}")
# Browse episodes
season_1 = show.season(1)
for ep in season_1.episodes():
status = "✓" if ep.isWatched else "○"
print(f"{status} {ep.title}")# Browse music library
music = plex.library.section('Music')
artists = music.artists()
# Get specific artist
artist = music.get('The Beatles')
albums = artist.albums()
# Get specific album and tracks
album = artist.album('Abbey Road')
for track in album.tracks():
print(f"{track.trackNumber}. {track.title} ({track.duration // 1000}s)")# Browse photo library
photos = plex.library.section('Photos')
albums = photos.photoalbums()
# Get specific album
vacation = photos.get('Summer Vacation 2023')
for photo in vacation.photos():
print(f"{photo.title} - {photo.year}")
if photo.make:
print(f" Camera: {photo.make} {photo.model}")# Search across all libraries
results = plex.search('star wars')
for item in results:
print(f"{item.title} ({item.type})")
# Library-wide search with filters
movies = plex.library.search(libtype='movie', year=2020)
shows = plex.library.search(libtype='show', genre='Comedy')
# Advanced section search
action_movies = movie_section.search(
genre='Action',
year__gte=2010, # Released 2010 or later
rating__gte=7.0 # Rating 7.0 or higher
)# Clean up library
plex.library.cleanBundles() # Remove unused metadata bundles
plex.library.emptyTrash() # Empty all library trash
plex.library.optimize() # Optimize database
# Section-specific maintenance
movies = plex.library.section('Movies')
movies.refresh() # Refresh metadata from disk
movies.update() # Update section configuration
# View section history
history = movies.history(maxresults=50)
for entry in history:
print(f"{entry.user.title} watched {entry.title} on {entry.viewedAt}")# Get a movie for subtitle operations
movie = plex.library.section('Movies').get('The Matrix')
# Search for available subtitles
subtitle_results = movie.searchSubtitles('en')
for result in subtitle_results:
print(f"Subtitle: {result.language} - {result.provider}")
# Upload custom subtitle file
movie.uploadSubtitles('/path/to/matrix_subtitles.srt')
# Download subtitle
if subtitle_results:
movie.downloadSubtitles(subtitle_results[0], '/path/to/download/')
# Remove subtitle track
existing_subtitles = movie.subtitleStreams()
if existing_subtitles:
movie.removeSubtitles(existing_subtitles[0])
# Optimize video file
movie.optimize(
deviceProfile='Universal TV',
videoQuality=8,
audioQuality=8
)# Find similar tracks
track = plex.library.section('Music').get('The Beatles').album('Abbey Road').track('Come Together')
# Get sonically similar tracks
similar_tracks = track.sonicallySimilar(limit=20)
for similar in similar_tracks:
print(f"Similar: {similar.artist().title} - {similar.title}")
# Create playlist from similar tracks
from plexapi.playlist import Playlist
similar_playlist = Playlist.create(
server=plex,
title=f'Similar to {track.title}',
items=similar_tracks[:10]
)# Complex movie searches
# Movies from 2020+ with specific genres and ratings
modern_hits = movies.search(
year__gte=2020,
genre=['Action', 'Thriller'],
rating__gte=7.5,
contentRating__in=['PG-13', 'R']
)
# Unwatched movies by specific director
nolan_unwatched = movies.search(
director='Christopher Nolan',
unwatched=True
)
# TV show searches
# Shows with specific number of seasons
long_series = shows.search(
unwatched=False, # Shows you've watched
year__lte=2010, # Older shows
leafCount__gte=50 # At least 50 episodes
)
# Music searches with advanced filters
# High-rated albums from specific decade
classic_albums = music.search(
libtype='album',
year__gte=1970,
year__lte=1979,
rating__gte=4.0
)
# Recently added tracks by genre
new_rock = music.search(
libtype='track',
genre='Rock',
addedAt__gte=datetime.now() - timedelta(days=30)
)import datetime
from datetime import timedelta
# Find content added in last week across all libraries
recent_cutoff = datetime.datetime.now() - timedelta(days=7)
all_recent = plex.library.search(addedAt__gte=recent_cutoff)
print(f"Found {len(all_recent)} items added in last week:")
for item in all_recent[:10]: # Show first 10
section_name = item.section().title
print(f"- {item.title} ({item.type}) in {section_name}")
# Search for specific actor across all movie libraries
actor_name = "Tom Hanks"
actor_movies = plex.library.search(
libtype='movie',
actor=actor_name
)
print(f"\n{actor_name} appears in {len(actor_movies)} movies:")
for movie in actor_movies:
print(f"- {movie.title} ({movie.year})")
# Find all content with specific keyword in title
keyword_results = plex.library.search(title='star')
by_type = {}
for item in keyword_results:
item_type = item.type
if item_type not in by_type:
by_type[item_type] = []
by_type[item_type].append(item)
for media_type, items in by_type.items():
print(f"\n{media_type.title()}s with 'star' in title: {len(items)}")
for item in items[:5]: # Show first 5 of each type
print(f" - {item.title}")