Last active
February 17, 2021 17:20
-
-
Save alyssadev/04da3d740e8b7e316b2ea1c5d9637612 to your computer and use it in GitHub Desktop.
A script to let you play things from a given plex host using a token from your environment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# python3 plexbrowse.py | while read p; do mpv "$p"; done | |
# use --host to set the hostname of the server to access | |
# set PLEX_TOKEN in your environment with your X-Plex-Token | |
import requests | |
from os import environ | |
from os.path import basename | |
import xml.etree.ElementTree as ET | |
from sys import stderr | |
token = environ["PLEX_TOKEN"] | |
def get(*args, **kwargs): | |
if "params" not in kwargs: | |
kwargs["params"] = {} | |
kwargs["params"]["X-Plex-Token"] = token | |
return requests.get(*args, **kwargs) | |
def parse(xml): | |
return ET.fromstring(xml) | |
def get_plex(host, path): | |
return parse(get(f"https://{host}{path}").content) | |
def pick_item(items, title=lambda i: i.attrib["title"]): | |
print("\n".join("{} {}".format(n, title(i)) for n, i in enumerate(items)), file=stderr) | |
print("> ", end="", file=stderr) | |
selected = int(input()) | |
if len(items) < selected: | |
return False | |
return items[selected] | |
def main(): | |
from argparse import ArgumentParser | |
parser = ArgumentParser() | |
parser.add_argument("--host", default="plex.wa.alyssasmith.id.au") | |
args = parser.parse_args() | |
section = pick_item(get_plex(args.host, "/library/sections").findall("Directory")) | |
item = pick_item(get_plex(args.host, f"/library/sections/{section.attrib['key']}/all").findall("Directory")) | |
videos = get_plex(args.host, item.attrib["key"].replace("children", "allLeaves")).findall("Video") | |
medias = [] | |
for v in videos: | |
medias += v.findall("Media") | |
parts = {} | |
for m in medias: | |
for p in m.findall("Part"): | |
parts[basename(p.attrib["file"])] = p.attrib["key"] | |
filenames = list(parts.keys()) | |
selected = parts[pick_item(filenames, title=lambda i: i)] | |
print(f"https://{args.host}{selected}?X-Plex-Token={token}") | |
return 0 | |
if __name__ == "__main__": | |
from sys import exit | |
try: | |
exit(main()) | |
except KeyboardInterrupt: | |
exit(255) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment