0
# Server Connection and Authentication
1
2
Core functionality for connecting to Plex servers using MyPlex cloud authentication or direct server tokens. Handles server discovery, resource enumeration, and connection management with support for both local and remote servers.
3
4
## Capabilities
5
6
### PlexServer - Direct Server Connection
7
8
Main entry point for direct connection to a Plex Media Server using baseurl and authentication token.
9
10
```python { .api }
11
class PlexServer:
12
def __init__(self, baseurl=None, token=None, session=None, timeout=None):
13
"""
14
Initialize connection to a Plex Media Server.
15
16
Args:
17
baseurl (str): Base URL for the Plex server (default: 'http://localhost:32400')
18
token (str): Required Plex authentication token
19
session (requests.Session, optional): Custom session object for HTTP requests
20
timeout (int): Timeout in seconds for initial connection (default: config.TIMEOUT)
21
"""
22
23
@property
24
def library(self):
25
"""Access to server's media library."""
26
27
def clients(self):
28
"""
29
List all clients connected to the server.
30
31
Returns:
32
List[PlexClient]: Connected client devices
33
"""
34
35
def client(self, name):
36
"""
37
Get a specific client by name.
38
39
Args:
40
name (str): Client name to find
41
42
Returns:
43
PlexClient: Matching client device
44
"""
45
46
def sessions(self):
47
"""
48
List all active playback sessions.
49
50
Returns:
51
List[Session]: Active sessions
52
"""
53
54
def playlists(self, playlistType=None):
55
"""
56
List server playlists.
57
58
Args:
59
playlistType (str, optional): Filter by playlist type ('audio', 'video', 'photo')
60
61
Returns:
62
List[Playlist]: Server playlists
63
"""
64
65
def search(self, query, mediatype=None, **kwargs):
66
"""
67
Search across all libraries.
68
69
Args:
70
query (str): Search query string
71
mediatype (str, optional): Filter by media type
72
**kwargs: Additional search parameters
73
74
Returns:
75
List[MediaObject]: Search results
76
"""
77
78
def query(self, key, method=None, **kwargs):
79
"""
80
Execute raw API query against the server.
81
82
Args:
83
key (str): API endpoint path
84
method (str, optional): HTTP method ('GET', 'POST', 'PUT', 'DELETE')
85
**kwargs: Request parameters
86
87
Returns:
88
requests.Response: Raw API response
89
"""
90
91
def downloadDatabases(self, savepath=None, unpack=False):
92
"""
93
Download server databases for troubleshooting.
94
95
Args:
96
savepath (str, optional): Directory to save files (default: current dir)
97
unpack (bool): Whether to unpack the downloaded zip file
98
99
Returns:
100
str: Path to downloaded file
101
"""
102
103
def downloadLogs(self, savepath=None, unpack=False):
104
"""
105
Download server log files for troubleshooting.
106
107
Args:
108
savepath (str, optional): Directory to save files (default: current dir)
109
unpack (bool): Whether to unpack the downloaded zip file
110
111
Returns:
112
str: Path to downloaded file
113
"""
114
115
def check_for_update(self, force=True, download=False):
116
"""
117
Check for available server updates.
118
119
Args:
120
force (bool): Force server to check for new releases
121
download (bool): Download update if available
122
123
Returns:
124
Release: Release info object if update available, None otherwise
125
"""
126
127
def installUpdate(self):
128
"""
129
Install the newest version of Plex Media Server.
130
Note: May require user interaction via GUI.
131
132
Returns:
133
requests.Response: Installation response
134
"""
135
136
def currentBackgroundProcess(self):
137
"""
138
Get currently running background processes.
139
140
Returns:
141
List[TranscodeJob]: Active transcode and processing jobs
142
"""
143
144
def myPlexAccount(self):
145
"""
146
Get MyPlex account information for this server.
147
148
Returns:
149
MyPlexAccount: Associated MyPlex account
150
"""
151
```
152
153
### MyPlexAccount - Cloud Authentication
154
155
MyPlex (plex.tv) account authentication and server resource discovery. Provides access to all servers and shared content associated with a Plex account.
156
157
```python { .api }
158
class MyPlexAccount:
159
def __init__(self, username=None, password=None, token=None, session=None, timeout=None):
160
"""
161
Authenticate with MyPlex using credentials or token.
162
163
Args:
164
username (str, optional): MyPlex username/email
165
password (str, optional): MyPlex password
166
token (str, optional): MyPlex authentication token
167
session (requests.Session, optional): Custom session object
168
timeout (int): Timeout for authentication request
169
"""
170
171
def resources(self):
172
"""
173
List all available Plex server resources.
174
175
Returns:
176
List[MyPlexResource]: Available server resources
177
"""
178
179
def resource(self, name):
180
"""
181
Get a specific server resource by name.
182
183
Args:
184
name (str): Server name to find
185
186
Returns:
187
MyPlexResource: Matching server resource
188
"""
189
190
def servers(self):
191
"""
192
List owned Plex servers.
193
194
Returns:
195
List[PlexServer]: Owned servers
196
"""
197
198
def users(self):
199
"""
200
List home users and shared users.
201
202
Returns:
203
List[MyPlexUser]: Associated users
204
"""
205
206
def webhooks(self):
207
"""
208
List registered webhooks.
209
210
Returns:
211
List[dict]: Webhook configurations
212
"""
213
214
def addWebhook(self, url, **kwargs):
215
"""
216
Register a new webhook.
217
218
Args:
219
url (str): Webhook URL to register
220
**kwargs: Additional webhook parameters
221
"""
222
223
def deleteWebhook(self, url):
224
"""
225
Remove a registered webhook.
226
227
Args:
228
url (str): Webhook URL to remove
229
"""
230
```
231
232
### MyPlexResource - Server Resource Management
233
234
Represents a Plex server resource discovered through MyPlex, providing connection capabilities and resource information.
235
236
```python { .api }
237
class MyPlexResource:
238
def connect(self, ssl=None, timeout=None):
239
"""
240
Establish connection to this server resource.
241
242
Args:
243
ssl (bool, optional): Force SSL connection
244
timeout (int, optional): Connection timeout
245
246
Returns:
247
PlexServer: Connected server instance
248
"""
249
250
@property
251
def name(self):
252
"""Server resource name."""
253
254
@property
255
def connections(self):
256
"""Available connection options."""
257
258
@property
259
def owned(self):
260
"""Whether this resource is owned by the account."""
261
```
262
263
### Authentication Examples
264
265
**MyPlex Authentication (Recommended):**
266
267
```python
268
from plexapi.myplex import MyPlexAccount
269
270
# Using username and password
271
account = MyPlexAccount('user@example.com', 'password')
272
plex = account.resource('My Server').connect()
273
274
# Using authentication token
275
account = MyPlexAccount(token='your-myplex-token')
276
servers = account.servers()
277
plex = servers[0]
278
```
279
280
**Direct Server Connection:**
281
282
```python
283
from plexapi.server import PlexServer
284
285
# Local server connection
286
plex = PlexServer('http://192.168.1.100:32400', 'server-token')
287
288
# Remote server connection
289
plex = PlexServer('https://remote.example.com:32400', 'server-token')
290
```
291
292
**Configuration-based Connection:**
293
294
```python
295
import plexapi
296
from plexapi.server import PlexServer
297
298
# Using configuration file values
299
plex = PlexServer() # Uses config values for baseurl and token
300
```
301
302
## Error Handling
303
304
Common authentication and connection exceptions:
305
306
```python { .api }
307
# Exception classes for connection errors
308
class Unauthorized(BadRequest):
309
"""Raised when authentication fails."""
310
311
class BadRequest(PlexApiException):
312
"""Raised for HTTP 400 errors."""
313
314
class NotFound(PlexApiException):
315
"""Raised when server or resource not found."""
316
```
317
318
Handle connection errors:
319
320
```python
321
from plexapi.exceptions import Unauthorized, NotFound
322
from plexapi.server import PlexServer
323
324
try:
325
plex = PlexServer('http://plex-server:32400', 'invalid-token')
326
except Unauthorized:
327
print("Invalid authentication token")
328
except NotFound:
329
print("Server not found or unreachable")
330
```
331
332
## Advanced Connection Features
333
334
### Session Management
335
336
Use custom session objects for advanced HTTP configuration:
337
338
```python
339
import requests
340
from plexapi.server import PlexServer
341
342
# Custom session with SSL verification disabled
343
session = requests.Session()
344
session.verify = False
345
346
plex = PlexServer('https://plex-server:32400', 'token', session=session)
347
```
348
349
### Connection Timeouts
350
351
Configure connection timeouts for slow networks:
352
353
```python
354
from plexapi.server import PlexServer
355
356
# 60 second connection timeout
357
plex = PlexServer('http://plex-server:32400', 'token', timeout=60)
358
```
359
360
### Server Discovery
361
362
Use GDM (Good Day Mate) for automatic server discovery:
363
364
```python
365
from plexapi.gdm import GDM
366
367
gdm = GDM()
368
gdm.scan()
369
370
for server in gdm.entries:
371
print(f"Found server: {server['name']} at {server['host']}:{server['port']}")
372
```