forked from EthanC/Perplex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
perplex.py
422 lines (307 loc) · 13.4 KB
/
perplex.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
import json
import urllib.parse
from datetime import datetime
from pathlib import Path
from sys import exit, stderr
from time import sleep
from typing import Any, Dict, List, Optional, Self, Union
import httpx
from httpx import Response
from loguru import logger
from plexapi.audio import TrackSession
from plexapi.media import Media
from plexapi.myplex import MyPlexAccount, MyPlexResource, PlexServer
from plexapi.video import EpisodeSession, MovieSession
from pypresence import Presence
class Perplex:
"""
Discord Rich Presence implementation for Plex.
https://github.com/EthanC/Perplex
"""
def Initialize(self: Self) -> None:
"""Initialize Perplex and begin primary functionality."""
logger.info("Perplex")
logger.info("https://github.com/EthanC/Perplex")
self.config: Dict[str, Any] = Perplex.LoadConfig(self)
Perplex.SetupLogging(self)
plex: MyPlexAccount = Perplex.LoginPlex(self)
discord: Presence = Perplex.LoginDiscord(self)
while True:
session: Optional[
Union[MovieSession, EpisodeSession, TrackSession]
] = Perplex.FetchSession(self, plex)
if session:
logger.success(f"Fetched active media session")
if type(session) is MovieSession:
status: Dict[str, Any] = Perplex.BuildMoviePresence(self, session)
elif type(session) is EpisodeSession:
status: Dict[str, Any] = Perplex.BuildEpisodePresence(self, session)
elif type(session) is TrackSession:
status: Dict[str, Any] = Perplex.BuildTrackPresence(self, session)
success: bool = Perplex.SetPresence(self, discord, status)
# Reestablish a failed Discord Rich Presence connection
if not success:
discord = Perplex.LoginDiscord(self)
else:
try:
discord.clear()
except Exception:
pass
# Presence updates have a rate limit of 1 update per 15 seconds
# https://discord.com/developers/docs/rich-presence/how-to#updating-presence
logger.info("Sleeping for 15s...")
sleep(15.0)
def LoadConfig(self: Self) -> Dict[str, Any]:
"""Load the configuration values specified in config.json"""
try:
with open("config.json", "r") as file:
config: Dict[str, Any] = json.loads(file.read())
except Exception as e:
logger.critical(f"Failed to load configuration, {e}")
exit(1)
logger.success("Loaded configuration")
return config
def SetupLogging(self: Self) -> None:
"""Setup the logger using the configured values."""
settings: Dict[str, Any] = self.config["logging"]
if (level := settings["severity"].upper()) != "DEBUG":
try:
logger.remove()
logger.add(stderr, level=level)
logger.success(f"Set logger severity to {level}")
except Exception as e:
# Fallback to default logger settings
logger.add(stderr, level="DEBUG")
logger.error(f"Failed to set logger severity to {level}, {e}")
def LoginPlex(self: Self) -> MyPlexAccount:
"""Authenticate with Plex using the configured credentials."""
settings: Dict[str, Any] = self.config["plex"]
account: Optional[MyPlexAccount] = None
if Path("auth.txt").is_file():
try:
with open("auth.txt", "r") as file:
auth: str = file.read()
account = MyPlexAccount(token=auth)
except Exception as e:
logger.error(f"Failed to authenticate with Plex using token, {e}")
if not account:
username: str = settings["username"]
password: str = settings["password"]
if settings["twoFactor"]:
print(f"Enter Verification Code: ", end="")
code: str = input()
if (code == "") or (code.isspace()):
logger.warning(
"Two-Factor Authentication is enabled but code was not supplied"
)
else:
password = f"{password}{code}"
try:
account = MyPlexAccount(username, password)
except Exception as e:
logger.critical(f"Failed to authenticate with Plex, {e}")
exit(1)
logger.success("Authenticated with Plex")
try:
with open("auth.txt", "w+") as file:
file.write(account.authenticationToken)
except Exception as e:
logger.error(
f"Failed to save Plex authentication token for future logins, {e}"
)
return account
def LoginDiscord(self: Self) -> Presence:
"""Authenticate with Discord using the configured credentials."""
client: Optional[Presence] = None
while not client:
try:
client = Presence(self.config["discord"]["appId"])
client.connect()
except Exception as e:
logger.error(f"Failed to connect to Discord ({e}) retry in 15s...")
sleep(15.0)
logger.success("Authenticated with Discord")
return client
def FetchSession(
self: Self, client: MyPlexAccount
) -> Optional[Union[MovieSession, EpisodeSession, TrackSession]]:
"""
Connect to the configured Plex Media Server and return the active
media session.
"""
settings: Dict[str, Any] = self.config["plex"]
resource: Optional[MyPlexResource] = None
server: Optional[PlexServer] = None
for entry in settings["servers"]:
for result in client.resources():
if entry.lower() == result.name.lower():
resource = result
break
if resource:
break
if not resource:
logger.critical("Failed to locate configured Plex Media Server")
exit(1)
try:
server = resource.connect()
except Exception as e:
logger.critical(
f"Failed to connect to configured Plex Media Server ({resource.name}), {e}"
)
exit(1)
sessions: List[Media] = server.sessions()
active: Optional[Union[MovieSession, EpisodeSession, TrackSession]] = None
if len(sessions) > 0:
i: int = 0
for entry in settings["users"]:
for result in sessions:
if entry.lower() in [alias.lower() for alias in result.usernames]:
active = sessions[i]
break
i += 1
if not active:
logger.info("No active media sessions found for configured users")
return
if type(active) is MovieSession:
return active
elif type(active) is EpisodeSession:
return active
elif type(active) is TrackSession:
return active
logger.error(f"Fetched active media session of unknown type: {type(active)}")
def BuildMoviePresence(self: Self, active: MovieSession) -> Dict[str, Any]:
"""Build a Discord Rich Presence status for the active movie session."""
minimal: bool = self.config["discord"]["minimal"]
result: Dict[str, Any] = {}
metadata: Optional[Dict[str, Any]] = Perplex.FetchMetadata(
self, active.title, active.year, "movie"
)
if minimal:
result["primary"] = active.title
else:
result["primary"] = f"{active.title} ({active.year})"
details: List[str] = []
if len(active.genres) > 0:
details.append(active.genres[0].tag)
if len(active.directors) > 0:
details.append(f"Dir. {active.directors[0].tag}")
if len(details) > 1:
result["secondary"] = ", ".join(details)
if not metadata:
# Default to image uploaded via Discord Developer Portal
result["image"] = "movie"
result["buttons"] = []
else:
mId: int = metadata["id"]
mType: str = metadata["media_type"]
imgPath: str = metadata["poster_path"]
result["image"] = f"https://image.tmdb.org/t/p/original{imgPath}"
result["buttons"] = [
{"label": "TMDB", "url": f"https://themoviedb.org/{mType}/{mId}"}
]
result["remaining"] = int((active.duration / 1000) - (active.viewOffset / 1000))
result["imageText"] = active.title
logger.trace(result)
return result
def BuildEpisodePresence(self: Self, active: EpisodeSession) -> Dict[str, Any]:
"""Build a Discord Rich Presence status for the active episode session."""
result: Dict[str, Any] = {}
metadata: Optional[Dict[str, Any]] = Perplex.FetchMetadata(
self, active.show().title, active.show().year, "tv"
)
result["primary"] = active.show().title
result["secondary"] = active.title
result["remaining"] = int((active.duration / 1000) - (active.viewOffset / 1000))
result["imageText"] = active.show().title
if (active.seasonNumber) and (active.episodeNumber):
result["secondary"] += f" (S{active.seasonNumber}:E{active.episodeNumber})"
if not metadata:
# Default to image uploaded via Discord Developer Portal
result["image"] = "tv"
result["buttons"] = []
else:
mId: int = metadata["id"]
mType: str = metadata["media_type"]
imgPath: str = metadata["poster_path"]
result["image"] = f"https://image.tmdb.org/t/p/original{imgPath}"
result["buttons"] = [
{"label": "TMDB", "url": f"https://themoviedb.org/{mType}/{mId}"}
]
logger.trace(result)
return result
def BuildTrackPresence(self: Self, active: TrackSession) -> Dict[str, Any]:
"""Build a Discord Rich Presence status for the active music session."""
result: Dict[str, Any] = {}
result["primary"] = active.titleSort
result["secondary"] = f"by {active.artist().title}"
result["remaining"] = int((active.duration / 1000) - (active.viewOffset / 1000))
result["imageText"] = active.parentTitle
# Default to image uploaded via Discord Developer Portal
result["image"] = "music"
result["buttons"] = []
logger.trace(result)
return result
def FetchMetadata(
self: Self, title: str, year: int, format: str
) -> Optional[Dict[str, Any]]:
"""Fetch metadata for the provided title from TMDB."""
settings: Dict[str, Any] = self.config["tmdb"]
key: str = settings["apiKey"]
if not settings["enable"]:
logger.warning(f"TMDB disabled, some features will not be available")
return
try:
res: Response = httpx.get(
f"https://api.themoviedb.org/3/search/multi?api_key={key}&query={urllib.parse.quote(title)}"
)
res.raise_for_status()
logger.debug(f"(HTTP {res.status_code}) GET {res.url}")
logger.trace(res.text)
except Exception as e:
logger.error(f"Failed to fetch metadata for {title} ({year}), {e}")
return
data: Dict[str, Any] = res.json()
for entry in data.get("results", []):
if format == "movie":
if entry["media_type"] != format:
continue
elif title.lower() != entry["title"].lower():
continue
elif not entry["release_date"].startswith(str(year)):
continue
elif format == "tv":
if entry["media_type"] != format:
continue
elif title.lower() != entry["name"].lower():
continue
elif not entry["first_air_date"].startswith(str(year)):
continue
return entry
logger.warning(f"Could not locate metadata for {title} ({year})")
def SetPresence(self: Self, client: Presence, data: Dict[str, Any]) -> bool:
"""Set the Rich Presence status for the provided Discord client."""
title: str = data["primary"]
data["buttons"].append(
{"label": "Get Perplex", "url": "https://github.com/EthanC/Perplex"}
)
try:
client.update(
details=title,
state=data.get("secondary"),
end=int(datetime.now().timestamp() + data["remaining"]),
large_image=data["image"],
large_text=data["imageText"],
small_image="plex",
small_text="Plex",
buttons=data["buttons"],
)
except Exception as e:
logger.error(f"Failed to set Discord Rich Presence to {title}, {e}")
return False
logger.success(f"Set Discord Rich Presence to {title}")
return True
if __name__ == "__main__":
try:
Perplex.Initialize(Perplex)
except KeyboardInterrupt:
exit()