PlexPlaylistSync/app/utils/plex_client.py
2025-07-08 19:17:18 +09:00

50 lines
1.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from plexapi.myplex import MyPlexAccount
from plexapi.server import PlexServer
from urllib.parse import urlparse
from app.utils.common import str_is_empty
def build_plex_url(scheme, url, port="32400"):
"""Build a full Plex URL from scheme, url, and port."""
# 如果url不以http://或https://开头则添加scheme
full_url = url
if not full_url.startswith("http://") and not full_url.startswith("https://"):
full_url = f"{scheme}://{url}"
parsed = urlparse(full_url)
if parsed.scheme in ("http", "https"):
netloc = parsed.netloc or parsed.path
if ":" not in netloc and port:
netloc = f"{netloc}:{port}"
base_url = f"{parsed.scheme}://{netloc}"
else:
base_url = f"http://{url}:{port}"
return base_url
def connect_plex(username, password, token, scheme, url, port="32400"):
"""Return a connected PlexServer instance and update config with token and server info."""
# 如果token存在且不为空则使用token连接
if not str_is_empty(token):
return connect_plex_with_token(token, scheme, url, port)
else:
return connect_plex_with_pw(username, password, scheme, url, port)
def connect_plex_with_pw(username, password, scheme, url, port="32400"):
"""Return a connected PlexServer instance and update config with token and server info."""
# url 初始化
base_url = build_plex_url(scheme, url, port)
# account 初始化
account = MyPlexAccount(username, password)
# token 获取
token = account.authenticationToken
server = PlexServer(base_url, token)
return server, token
def connect_plex_with_token(token, scheme, url, port="32400"):
"""Return a connected PlexServer instance using a token."""
# URL 初始化
base_url = build_plex_url(scheme, url, port)
server = PlexServer(base_url, token)
return server, token