0
# Playlists and Playback Queues
1
2
Playlist creation, management, and playback queue operations. Supports both audio and video playlists with full CRUD operations, queue manipulation, and integrated playback control for organized media consumption and automated playback sequences.
3
4
## Capabilities
5
6
### Playlist - Media Playlist Management
7
8
Comprehensive playlist operations for creating, managing, and playing organized collections of media items.
9
10
```python { .api }
11
class Playlist(PlexPartialObject, Playable):
12
TYPE = 'playlist'
13
14
@property
15
def title(self):
16
"""Playlist title."""
17
18
@property
19
def summary(self):
20
"""Playlist description."""
21
22
@property
23
def playlistType(self):
24
"""Playlist type ('audio', 'video', 'photo')."""
25
26
@property
27
def leafCount(self):
28
"""Number of items in playlist."""
29
30
@property
31
def duration(self):
32
"""Total playlist duration in milliseconds."""
33
34
@property
35
def addedAt(self):
36
"""Date playlist was created."""
37
38
@property
39
def updatedAt(self):
40
"""Date playlist was last modified."""
41
42
def items(self, **kwargs):
43
"""
44
Get items in this playlist.
45
46
Args:
47
**kwargs: Filter parameters
48
49
Returns:
50
List[MediaObject]: Playlist items (Movies, Episodes, Tracks, etc.)
51
"""
52
53
def addItems(self, items):
54
"""
55
Add items to playlist.
56
57
Args:
58
items (List[MediaObject] | MediaObject): Items to add
59
"""
60
61
def removeItems(self, items):
62
"""
63
Remove items from playlist.
64
65
Args:
66
items (List[MediaObject] | MediaObject): Items to remove
67
"""
68
69
def moveItem(self, item, after=None):
70
"""
71
Move item to new position in playlist.
72
73
Args:
74
item (MediaObject): Item to move
75
after (MediaObject, optional): Item to move after (None for beginning)
76
"""
77
78
def clear(self):
79
"""Remove all items from playlist."""
80
81
def copyToUser(self, user):
82
"""
83
Copy playlist to another user.
84
85
Args:
86
user (MyPlexUser): Target user
87
88
Returns:
89
Playlist: Copied playlist
90
"""
91
92
def edit(self, title=None, summary=None):
93
"""
94
Edit playlist metadata.
95
96
Args:
97
title (str, optional): New playlist title
98
summary (str, optional): New playlist description
99
"""
100
101
def delete(self):
102
"""Delete this playlist."""
103
104
def play(self, client=None):
105
"""
106
Play this playlist.
107
108
Args:
109
client (PlexClient, optional): Client to play on
110
"""
111
```
112
113
### PlayQueue - Playback Queue Management
114
115
Temporary playback queues for organizing immediate playback sequences with dynamic queue manipulation.
116
117
```python { .api }
118
class PlayQueue:
119
TYPE = 'playqueue'
120
121
@property
122
def playQueueID(self):
123
"""Unique playqueue identifier."""
124
125
@property
126
def playQueueSelectedItemID(self):
127
"""Currently selected item ID."""
128
129
@property
130
def playQueueSelectedItemOffset(self):
131
"""Current playback offset in selected item."""
132
133
@property
134
def playQueueTotalCount(self):
135
"""Total number of items in queue."""
136
137
@property
138
def playQueueVersion(self):
139
"""Queue version for sync purposes."""
140
141
def items(self):
142
"""
143
Get items in this playqueue.
144
145
Returns:
146
List[MediaObject]: Queue items
147
"""
148
149
def addItem(self, item, playNext=False):
150
"""
151
Add item to playqueue.
152
153
Args:
154
item (MediaObject): Item to add
155
playNext (bool): Whether to play this item next
156
"""
157
158
def removeItem(self, item):
159
"""
160
Remove item from playqueue.
161
162
Args:
163
item (MediaObject): Item to remove
164
"""
165
166
def moveItem(self, item, after=None):
167
"""
168
Move item within playqueue.
169
170
Args:
171
item (MediaObject): Item to move
172
after (MediaObject, optional): Item to move after
173
"""
174
175
def clear(self):
176
"""Clear all items from playqueue."""
177
178
def refresh(self):
179
"""Refresh playqueue data from server."""
180
```
181
182
## Playlist Management Examples
183
184
### Creating Playlists
185
186
```python
187
# Create a new audio playlist
188
music_section = plex.library.section('Music')
189
favorite_tracks = [
190
music_section.get('The Beatles').album('Abbey Road').track('Come Together'),
191
music_section.get('Pink Floyd').album('Dark Side of the Moon').track('Time'),
192
music_section.get('Led Zeppelin').album('IV').track('Stairway to Heaven')
193
]
194
195
# Create playlist (done through server)
196
favorites_playlist = plex.createPlaylist('My Favorites', items=favorite_tracks)
197
198
# Create video playlist
199
movies_section = plex.library.section('Movies')
200
action_movies = [
201
movies_section.get('Die Hard'),
202
movies_section.get('Terminator 2'),
203
movies_section.get('The Matrix')
204
]
205
206
action_playlist = plex.createPlaylist('Action Night', items=action_movies)
207
```
208
209
### Managing Existing Playlists
210
211
```python
212
# Get existing playlists
213
all_playlists = plex.playlists()
214
audio_playlists = plex.playlists(playlistType='audio')
215
video_playlists = plex.playlists(playlistType='video')
216
217
# Get specific playlist
218
my_playlist = None
219
for playlist in all_playlists:
220
if playlist.title == 'My Favorites':
221
my_playlist = playlist
222
break
223
224
# Add items to playlist
225
new_track = plex.library.section('Music').get('Queen').album('A Night at the Opera').track('Bohemian Rhapsody')
226
my_playlist.addItems(new_track)
227
228
# Add multiple items
229
more_tracks = [
230
plex.library.section('Music').get('AC/DC').album('Back in Black').track('Back in Black'),
231
plex.library.section('Music').get('Metallica').album('Master of Puppets').track('Master of Puppets')
232
]
233
my_playlist.addItems(more_tracks)
234
```
235
236
### Playlist Manipulation
237
238
```python
239
playlist = plex.playlists()[0] # Get first playlist
240
241
# View playlist contents
242
items = playlist.items()
243
print(f"Playlist: {playlist.title}")
244
print(f"Items: {playlist.leafCount}")
245
print(f"Duration: {playlist.duration // 60000} minutes")
246
247
for i, item in enumerate(items, 1):
248
print(f"{i}. {item.title}")
249
250
# Reorder items
251
first_item = items[0]
252
third_item = items[2]
253
playlist.moveItem(first_item, after=third_item) # Move first item after third
254
255
# Remove items
256
playlist.removeItems(items[-1]) # Remove last item
257
258
# Edit playlist metadata
259
playlist.edit(
260
title='Updated Playlist Name',
261
summary='This playlist has been updated'
262
)
263
```
264
265
### Playlist Playback
266
267
```python
268
# Play entire playlist
269
playlist = plex.playlists()[0]
270
client = plex.client('Living Room TV')
271
272
# Start playlist playback
273
playlist.play(client)
274
275
# Play specific item from playlist
276
items = playlist.items()
277
client.playMedia(items[2]) # Play third item
278
```
279
280
## PlayQueue Operations
281
282
### Creating and Managing PlayQueues
283
284
```python
285
# Create playqueue from media items
286
movies = plex.library.section('Movies').search(genre='Action')
287
movie_queue = plex.createPlayQueue(movies[:5]) # First 5 action movies
288
289
# Create playqueue from playlist
290
playlist = plex.playlists()[0]
291
playlist_queue = plex.createPlayQueue(playlist)
292
293
# Get existing playqueues (typically from active sessions)
294
sessions = plex.sessions()
295
for session in sessions:
296
if hasattr(session, 'playQueue'):
297
queue = session.playQueue
298
print(f"Active queue: {queue.playQueueTotalCount} items")
299
```
300
301
### Queue Manipulation
302
303
```python
304
# Work with playqueue
305
queue = plex.createPlayQueue(plex.library.section('Music').all()[:10])
306
307
# Add item to queue
308
new_track = plex.library.section('Music').get('Artist').track('Song')
309
queue.addItem(new_track)
310
311
# Add item to play next
312
urgent_track = plex.library.section('Music').get('Artist').track('Priority Song')
313
queue.addItem(urgent_track, playNext=True)
314
315
# Remove item
316
queue_items = queue.items()
317
queue.removeItem(queue_items[3]) # Remove 4th item
318
319
# Reorder queue
320
queue.moveItem(queue_items[0], after=queue_items[4]) # Move first item after fifth
321
322
# Clear entire queue
323
queue.clear()
324
```
325
326
## Advanced Playlist Features
327
328
### Smart Playlists and Filtering
329
330
```python
331
# Create genre-based playlists
332
rock_section = plex.library.section('Music')
333
rock_tracks = rock_section.search(genre='Rock')
334
rock_playlist = plex.createPlaylist('Rock Collection', items=rock_tracks)
335
336
# Create decade-based playlists
337
eighties_music = rock_section.search(decade=1980)
338
eighties_playlist = plex.createPlaylist('80s Hits', items=eighties_music)
339
340
# Create rating-based playlists
341
highly_rated = plex.library.section('Movies').search(rating__gte=8.0)
342
top_movies = plex.createPlaylist('Top Rated Movies', items=highly_rated)
343
```
344
345
### Playlist Sharing and Copying
346
347
```python
348
# Copy playlist to another user (requires appropriate permissions)
349
my_playlist = plex.playlists()[0]
350
target_user = plex.myPlexAccount().user('friend@example.com')
351
352
try:
353
copied_playlist = my_playlist.copyToUser(target_user)
354
print(f"Copied playlist: {copied_playlist.title}")
355
except Exception as e:
356
print(f"Failed to copy playlist: {e}")
357
```
358
359
### Playlist Analytics
360
361
```python
362
def analyze_playlist(playlist):
363
"""Analyze playlist composition and statistics."""
364
items = playlist.items()
365
366
# Basic stats
367
print(f"Playlist: {playlist.title}")
368
print(f"Total items: {len(items)}")
369
print(f"Total duration: {playlist.duration // 60000} minutes")
370
print(f"Created: {playlist.addedAt}")
371
print(f"Last updated: {playlist.updatedAt}")
372
373
# Content analysis
374
if playlist.playlistType == 'audio':
375
artists = {}
376
genres = {}
377
378
for track in items:
379
# Count artists
380
artist_name = track.artist().title
381
artists[artist_name] = artists.get(artist_name, 0) + 1
382
383
# Count genres
384
for genre in track.album().genres:
385
genres[genre.tag] = genres.get(genre.tag, 0) + 1
386
387
print(f"Top artists: {sorted(artists.items(), key=lambda x: x[1], reverse=True)[:5]}")
388
print(f"Top genres: {sorted(genres.items(), key=lambda x: x[1], reverse=True)[:3]}")
389
390
elif playlist.playlistType == 'video':
391
years = {}
392
genres = {}
393
394
for item in items:
395
# Count years
396
year = getattr(item, 'year', None)
397
if year:
398
years[year] = years.get(year, 0) + 1
399
400
# Count genres
401
for genre in getattr(item, 'genres', []):
402
genres[genre.tag] = genres.get(genre.tag, 0) + 1
403
404
print(f"Top years: {sorted(years.items(), key=lambda x: x[1], reverse=True)[:5]}")
405
print(f"Top genres: {sorted(genres.items(), key=lambda x: x[1], reverse=True)[:3]}")
406
407
# Analyze all playlists
408
for playlist in plex.playlists():
409
analyze_playlist(playlist)
410
print("-" * 50)
411
```
412
413
### Automated Playlist Management
414
415
```python
416
import schedule
417
import time
418
419
def update_recent_additions_playlist():
420
"""Automatically update a 'Recent Additions' playlist."""
421
try:
422
# Get or create recent additions playlist
423
recent_playlist = None
424
for playlist in plex.playlists():
425
if playlist.title == 'Recent Additions':
426
recent_playlist = playlist
427
break
428
429
if not recent_playlist:
430
recent_playlist = plex.createPlaylist('Recent Additions', items=[])
431
432
# Clear existing items
433
recent_playlist.clear()
434
435
# Add recent items from all sections
436
recent_items = []
437
for section in plex.library.sections():
438
if section.type in ['movie', 'show', 'artist']:
439
section_recent = section.recentlyAdded()[:10] # 10 per section
440
recent_items.extend(section_recent)
441
442
# Add to playlist
443
if recent_items:
444
recent_playlist.addItems(recent_items)
445
print(f"Updated 'Recent Additions' playlist with {len(recent_items)} items")
446
447
except Exception as e:
448
print(f"Failed to update recent additions playlist: {e}")
449
450
# Schedule automatic updates
451
schedule.every().day.at("06:00").do(update_recent_additions_playlist)
452
453
# Run scheduler (simplified example)
454
# while True:
455
# schedule.run_pending()
456
# time.sleep(3600) # Check every hour
457
```