Skip to content

Commit 51e5439

Browse files
committed
Minor cleanup and tweaks
1 parent 5461ad2 commit 51e5439

File tree

12 files changed

+45
-32
lines changed

12 files changed

+45
-32
lines changed

.dockerignore

+4-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,10 @@
33
.github
44
.gitignore
55
CONTRIBUTING.md
6-
data
76
Dockerfile
7+
lint.bat
88
pyrightconfig.json
9+
10+
__pycache__
911
assets/showcase.psd
12+
data

.github/workflows/release.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ jobs:
1818
- name: Create release ZIP file
1919
run: |-
2020
mv .github/release-notes ../
21-
rm -rf .git .github .gitignore .dockerignore Dockerfile CONTRIBUTING.md pyrightconfig.json
21+
xargs rm -rf < .dockerignore
2222
mkdir ${{ github.event.repository.name }}
2323
mv * ${{ github.event.repository.name }} || true
2424
zip -r $RELEASE_ZIP_FILENAME ${{ github.event.repository.name }}

.gitignore

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
1-
data
1+
__pycache__
22
assets/showcase.psd
3+
data

config/constants.py

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
isUnix = sys.platform in ["linux", "darwin"]
1616
processID = os.getpid()
1717
isInteractive = sys.stdin and sys.stdin.isatty()
18+
plexServerNameInput = os.environ.get("DRPP_PLEX_SERVER_NAME_INPUT")
1819
noPipInstall = os.environ.get("DRPP_NO_PIP_INSTALL", "") == "true"
1920
isInContainer = os.environ.get("DRPP_IS_IN_CONTAINER", "") == "true"
2021
runtimeDirectory = "/run/app" if isInContainer else os.environ.get("XDG_RUNTIME_DIR", os.environ.get("TMPDIR", os.environ.get("TMP", os.environ.get("TEMP", "/tmp"))))

core/config.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,9 @@ def loadConfig() -> None:
4949
try:
5050
with open(configFilePath, "r", encoding = "UTF-8") as configFile:
5151
if configFileType == "yaml":
52-
loadedConfig = yaml.safe_load(configFile) or {}
52+
loadedConfig = yaml.safe_load(configFile) or {} # pyright: ignore[reportUnknownVariableType]
5353
else:
54-
loadedConfig = json.load(configFile) or {}
54+
loadedConfig = json.load(configFile) or {} # pyright: ignore[reportUnknownVariableType]
5555
except:
5656
os.rename(configFilePath, f"{configFilePathBase}-{time.time():.0f}.{configFileExtension}")
5757
logger.exception("Failed to parse the config file. A new one will be created.")

core/imgur.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,13 @@
66
import models.imgur
77
import requests
88

9-
def uploadToImgur(url: str, maxSize: int = 0) -> Optional[str]:
9+
def uploadToImgur(url: str) -> Optional[str]:
1010
try:
1111
originalImageBytesIO = io.BytesIO(requests.get(url).content)
1212
originalImage = Image.open(originalImageBytesIO)
1313
newImage = Image.new("RGB", originalImage.size)
14-
newImage.putdata(originalImage.getdata()) # pyright: ignore[reportUnknownMemberType,reportUnknownArgumentType]
14+
newImage.putdata(originalImage.getdata()) # pyright: ignore[reportArgumentType]
15+
maxSize = config["display"]["posters"]["maxSize"]
1516
if maxSize:
1617
newImage.thumbnail((maxSize, maxSize))
1718
newImageBytesIO = io.BytesIO()

core/plex.py

+11-12
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
1-
# pyright: reportUnknownArgumentType=none,reportUnknownMemberType=none,reportUnknownVariableType=none
1+
# pyright: reportUnknownArgumentType=none,reportUnknownMemberType=none,reportUnknownVariableType=none,reportTypedDictNotRequiredAccess=none,reportOptionalMemberAccess=none,reportMissingTypeStubs=none
22

33
from .config import config
44
from .discord import DiscordIpcService
55
from .imgur import uploadToImgur
66
from config.constants import name, plexClientID
77
from plexapi.alert import AlertListener
8-
from plexapi.base import PlexSession, PlexPartialObject
98
from plexapi.media import Genre, Guid
109
from plexapi.myplex import MyPlexAccount, PlexServer
1110
from typing import Optional
@@ -56,7 +55,7 @@ def __init__(self, token: str, serverConfig: models.config.Server):
5655
self.daemon = True
5756
self.token = token
5857
self.serverConfig = serverConfig
59-
self.logger = LoggerWithPrefix(f"[{self.serverConfig['name']}] ") # pyright: ignore[reportTypedDictNotRequiredAccess]
58+
self.logger = LoggerWithPrefix(f"[{self.serverConfig['name']}] ")
6059
self.discordIpcService = DiscordIpcService(self.serverConfig.get("ipcPipeNumber"))
6160
self.updateTimeoutTimer: Optional[threading.Timer] = None
6261
self.connectionCheckTimer: Optional[threading.Timer] = None
@@ -94,7 +93,7 @@ def run(self) -> None:
9493
if not self.server:
9594
raise Exception("Server not found")
9695
except Exception as e:
97-
self.logger.error("Failed to connect to %s '%s': %s", self.productName, self.serverConfig["name"], e) # pyright: ignore[reportTypedDictNotRequiredAccess]
96+
self.logger.error("Failed to connect to %s '%s': %s", self.productName, self.serverConfig["name"], e)
9897
self.logger.error("Reconnecting in 10 seconds")
9998
time.sleep(10)
10099

@@ -154,19 +153,19 @@ def handleAlert(self, alert: models.plex.Alert) -> None:
154153
self.logger.debug("Received alert: %s", stateNotification)
155154
ratingKey = int(stateNotification["ratingKey"])
156155
assert self.server
157-
item: PlexPartialObject = self.server.fetchItem(ratingKey)
156+
item = self.server.fetchItem(ratingKey)
158157
if item.key and item.key.startswith("/livetv"):
159158
mediaType = "live_episode"
160159
else:
161-
mediaType: str = item.type
160+
mediaType = item.type
162161
if mediaType not in validMediaTypes:
163162
self.logger.debug("Unsupported media type '%s', ignoring", mediaType)
164163
return
165164
state = stateNotification["state"]
166165
sessionKey = int(stateNotification["sessionKey"])
167166
viewOffset = int(stateNotification["viewOffset"])
168167
try:
169-
libraryName: str = item.section().title
168+
libraryName = item.section().title
170169
except:
171170
libraryName = "ERROR"
172171
if "blacklistedLibraries" in self.serverConfig and libraryName in self.serverConfig["blacklistedLibraries"]:
@@ -195,15 +194,15 @@ def handleAlert(self, alert: models.plex.Alert) -> None:
195194
return
196195
if self.isServerOwner:
197196
self.logger.debug("Searching sessions for session key %s", sessionKey)
198-
sessions: list[PlexSession] = self.server.sessions()
197+
sessions = self.server.sessions()
199198
if len(sessions) < 1:
200199
self.logger.debug("Empty session list, ignoring")
201200
return
202201
for session in sessions:
203202
self.logger.debug("%s, Session Key: %s, Usernames: %s", session, session.sessionKey, session.usernames)
204203
if session.sessionKey == sessionKey:
205204
self.logger.debug("Session found")
206-
sessionUsername: str = session.usernames[0]
205+
sessionUsername = session.usernames[0]
207206
if sessionUsername.lower() == self.listenForUser.lower():
208207
self.logger.debug("Username '%s' matches '%s', continuing", sessionUsername, self.listenForUser)
209208
break
@@ -268,7 +267,7 @@ def handleAlert(self, alert: models.plex.Alert) -> None:
268267
thumbUrl = getCacheKey(thumb)
269268
if not thumbUrl or not isinstance(thumbUrl, str):
270269
self.logger.debug("Uploading poster to Imgur")
271-
thumbUrl = uploadToImgur(self.server.url(thumb, True), config["display"]["posters"]["maxSize"])
270+
thumbUrl = uploadToImgur(self.server.url(thumb, True))
272271
setCacheKey(thumb, thumbUrl)
273272
activity: models.discord.Activity = {
274273
"details": truncate(title, 128),
@@ -326,9 +325,9 @@ def handleAlert(self, alert: models.plex.Alert) -> None:
326325
if state == "playing":
327326
currentTimestamp = int(time.time())
328327
if config["display"]["useRemainingTime"]:
329-
activity["timestamps"] = {"end": round(currentTimestamp + ((item.duration - viewOffset) / 1000))}
328+
activity["timestamps"] = { "end": round(currentTimestamp + ((item.duration - viewOffset) / 1000)) }
330329
else:
331-
activity["timestamps"] = {"start": round(currentTimestamp - (viewOffset / 1000))}
330+
activity["timestamps"] = { "start": round(currentTimestamp - (viewOffset / 1000)) }
332331
if not self.discordIpcService.connected:
333332
self.discordIpcService.connect()
334333
if self.discordIpcService.connected:

lint.bat

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
@echo off
2+
pyright --pythonversion 3.10.0

main.py

+12-6
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,15 @@
1313
uid, gid = statResult.st_uid, statResult.st_gid
1414
else:
1515
if noRuntimeDirChown:
16-
logger.warning(f"DRPP_NO_RUNTIME_DIR_CHOWN is set to true. Manually ensure appropriate ownership of {runtimeDirectory}")
16+
logger.warning(f"Environment variable DRPP_NO_RUNTIME_DIR_CHOWN is set to true. Manually ensure appropriate ownership of {runtimeDirectory}")
1717
else:
1818
os.system(f"chmod 700 {runtimeDirectory}")
1919
os.system(f"chown -R {uid}:{gid} {runtimeDirectory}")
2020
os.system(f"chown -R {uid}:{gid} {containerCwd}")
2121
os.setgid(gid) # pyright: ignore[reportAttributeAccessIssue,reportUnknownMemberType]
2222
os.setuid(uid) # pyright: ignore[reportAttributeAccessIssue,reportUnknownMemberType]
2323
else:
24-
logger.warning(f"Not running as the superuser. Manually ensure appropriate ownership of mounted contents")
24+
logger.warning("Not running as the superuser. Manually ensure appropriate ownership of mounted contents")
2525

2626
from config.constants import noPipInstall
2727
import sys
@@ -43,7 +43,7 @@ def parsePipPackages(packagesStr: str) -> dict[str, str]:
4343
except Exception as e:
4444
logger.exception("An unexpected error occured during automatic installation of dependencies. Install them manually by running the following command: python -m pip install -U -r requirements.txt")
4545

46-
from config.constants import dataDirectoryPath, logFilePath, name, version, isInteractive
46+
from config.constants import dataDirectoryPath, logFilePath, name, version, isInteractive, plexServerNameInput
4747
from core.config import config, loadConfig, saveConfig
4848
from core.discord import DiscordIpcService
4949
from core.plex import PlexAlertListener, initiateAuth, getAuthToken
@@ -72,7 +72,6 @@ def init() -> None:
7272
loadCache()
7373

7474
def main() -> None:
75-
init()
7675
if not config["users"]:
7776
logger.info("No users found in the config file")
7877
user = authNewUser()
@@ -104,9 +103,15 @@ def authNewUser() -> Optional[models.config.User]:
104103
authToken = getAuthToken(id, code)
105104
if authToken:
106105
logger.info("Authentication successful")
107-
serverName = os.environ.get("DRPP_PLEX_SERVER_NAME_INPUT")
106+
serverName = plexServerNameInput
108107
if not serverName:
109-
serverName = input("Enter the name of the Plex Media Server you wish to connect to: ") if isInteractive else "ServerName"
108+
if isInteractive:
109+
serverName = input("Enter the name of the Plex Media Server to connect to: ")
110+
else:
111+
serverName = "ServerName"
112+
logger.warning("Environment variable DRPP_PLEX_SERVER_NAME_INPUT is not set and the environment is non-interactive")
113+
logger.warning("\"ServerName\" will be used as a placeholder for the name of the Plex Media Server to connect to")
114+
logger.warning("Change this by editing the config file and restarting the script")
110115
return { "token": authToken, "servers": [{ "name": serverName }] }
111116
time.sleep(5)
112117
else:
@@ -134,6 +139,7 @@ def testIpc(pipeNumber: int) -> None:
134139
mode = sys.argv[1] if len(sys.argv) > 1 else ""
135140
try:
136141
if not mode:
142+
init()
137143
main()
138144
elif mode == "test-ipc":
139145
testIpc(int(sys.argv[2]) if len(sys.argv) > 2 else -1)

pyrightconfig.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
{
2-
"reportMissingTypeStubs": "information"
2+
"strict": ["**"]
33
}

requirements.txt

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
PlexAPI==4.15.9
2-
requests==2.31.0
3-
websocket-client==1.7.0
4-
PyYAML==6.0.1
5-
Pillow==10.2.0
1+
PlexAPI==4.15.16
2+
requests==2.32.3
3+
websocket-client==1.8.0
4+
PyYAML==6.0.2
5+
Pillow==10.4.0

utils/text.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
def formatSeconds(seconds: int | float, joiner: Optional[str] = None) -> str:
44
seconds = round(seconds)
5-
timeValues = {"h": seconds // 3600, "m": seconds // 60 % 60, "s": seconds % 60}
5+
timeValues = { "h": seconds // 3600, "m": seconds // 60 % 60, "s": seconds % 60 }
66
if not joiner:
77
return "".join(str(v) + k for k, v in timeValues.items() if v > 0)
88
if timeValues["h"] == 0:

0 commit comments

Comments
 (0)