Merge pull request #189 from pkkid/better_cli

Better cli
This commit is contained in:
Hellowlol 2017-10-01 23:31:36 +02:00 committed by GitHub
commit 6dcc5bd7b3
5 changed files with 68 additions and 39 deletions

View file

@ -9,7 +9,6 @@ from plexapi.base import PlexObject
from plexapi.compat import ElementTree
from plexapi.exceptions import BadRequest, Unsupported
from plexapi.playqueue import PlayQueue
from plexapi.utils import cast
DEFAULT_MTYPE = 'video'

View file

@ -8,7 +8,7 @@ from plexapi import log, logfilter, utils
from plexapi.base import PlexObject
from plexapi.exceptions import BadRequest, NotFound
from plexapi.client import PlexClient
from plexapi.compat import ElementTree, quote
from plexapi.compat import ElementTree
from plexapi.library import LibrarySection
from plexapi.server import PlexServer
from plexapi.utils import joinArgs
@ -243,7 +243,6 @@ class MyPlexAccount(PlexObject):
machineId = server.machineIdentifier if isinstance(server, PlexServer) else server
sectionIds = self._getSectionIds(machineId, sections)
headers = {'Content-Type': 'application/json'}
# Determine whether user has access to the shared server.
user_servers = [s for s in user.servers if s.machineIdentifier == machineId]
if user_servers and sectionIds:
@ -251,12 +250,11 @@ class MyPlexAccount(PlexObject):
params = {'server_id': machineId, 'shared_server': {'library_section_ids': sectionIds}}
url = self.FRIENDSERVERS.format(machineId=machineId, serverId=serverId)
else:
params = {'server_id': machineId,
'shared_server': {'library_section_ids': sectionIds, "invited_id": user.id}}
params = {'server_id': machineId, 'shared_server': {'library_section_ids': sectionIds,
"invited_id": user.id}}
url = self.FRIENDINVITE.format(machineId=machineId)
# Remove share sections, add shares to user without shares, or update shares
if sectionIds:
# Remove share sections, add shares to user without shares, or update shares
if removeSections is True:
response_servers = self.query(url, self._session.delete, json=params, headers=headers)
elif 'invited_id' in params.get('shared_server', ''):
@ -265,27 +263,24 @@ class MyPlexAccount(PlexObject):
response_servers = self.query(url, self._session.put, json=params, headers=headers)
else:
log.warning('Section name, number of section object is required changing library sections')
# Update friend filters
url = self.FRIENDUPDATE.format(userId=user.id)
d = {}
params = {}
if isinstance(allowSync, bool):
d['allowSync'] = '1' if allowSync else '0'
params['allowSync'] = '1' if allowSync else '0'
if isinstance(allowCameraUpload, bool):
d['allowCameraUpload'] = '1' if allowCameraUpload else '0'
params['allowCameraUpload'] = '1' if allowCameraUpload else '0'
if isinstance(allowChannels, bool):
d['allowChannels'] = '1' if allowChannels else '0'
params['allowChannels'] = '1' if allowChannels else '0'
if isinstance(filterMovies, dict):
d['filterMovies'] = self._filterDictToStr(filterMovies or {}) #'1' if allowChannels else '0'
params['filterMovies'] = self._filterDictToStr(filterMovies or {}) # '1' if allowChannels else '0'
if isinstance(filterTelevision, dict):
d['filterTelevision'] = self._filterDictToStr(filterTelevision or {})
params['filterTelevision'] = self._filterDictToStr(filterTelevision or {})
if isinstance(allowChannels, dict):
d['filterMusic'] = self._filterDictToStr(filterMusic or {})
if d:
url += joinArgs(d)
params['filterMusic'] = self._filterDictToStr(filterMusic or {})
if params:
url += joinArgs(params)
response_filters = self.query(url, self._session.put)
return response_servers, response_filters
def user(self, username):

View file

@ -243,11 +243,12 @@ def download(url, filename=None, savepath=None, session=None, chunksize=4024,
mocked (bool): Helper to do evertything except write the file.
unpack (bool): Unpack the zip file.
showstatus(bool): Display a progressbar.
Example:
>>> download(a_episode.getStreamURL(), a_episode.location)
/path/to/file
"""
from plexapi import log
# fetch the data to be saved
session = session or requests.Session()
@ -356,7 +357,12 @@ def choose(msg, items, attr):
# Request choice from the user
while True:
try:
number = int(input('%s: ' % msg))
return items[number]
inp = input('%s: ' % msg)
if any(s in inp for s in (':', '::', '-')):
idx = slice(*map(lambda x: int(x.strip()) if x.strip() else None, inp.split(':')))
return items[idx]
else:
return items[int(inp)]
except (ValueError, IndexError):
pass

View file

@ -233,7 +233,7 @@ def test_server_account(plex):
assert account.signInState == 'ok'
assert isinstance(account.subscriptionActive, bool)
if account.subscriptionActive: assert len(account.subscriptionFeatures)
else: assert account.subscriptionFeatures == ['mediaproviders-news-platform-specific']
else: assert sorted(account.subscriptionFeatures) == ['download_certificates', 'federated-auth', 'news']
assert account.subscriptionState == 'Active' if account.subscriptionActive else 'Unknown'
assert re.match(utils.REGEX_EMAIL, account.username)

View file

@ -7,7 +7,11 @@ manually searching the items from the command line wizard.
Original contribution by lad1337.
"""
import argparse, re
import argparse
import os
import re
import shutil
from plexapi import utils
from plexapi.compat import unquote
from plexapi.video import Episode, Movie, Show
@ -17,15 +21,31 @@ VALID_TYPES = (Movie, Episode, Show)
def search_for_item(url=None):
if url: return get_item_from_url(opts.url)
server = utils.choose('Choose a Server', account.resources(), 'name').connect()
servers = [s for s in account.resources() if 'server' in s.provides]
server = utils.choose('Choose a Server', servers, 'name').connect()
query = input('What are you looking for?: ')
item = []
items = [i for i in server.search(query) if i.__class__ in VALID_TYPES]
item = utils.choose('Choose result', items, lambda x: '(%s) %s' % (x.type.title(), x.title[0:60]))
if isinstance(item, Show):
display = lambda i: '%s %s %s' % (i.grandparentTitle, i.seasonEpisode, i.title)
item = utils.choose('Choose episode', item.episodes(), display)
if not isinstance(item, (Movie, Episode)):
raise SystemExit('Unable to download %s' % item.__class__.__name__)
items = utils.choose('Choose result', items, lambda x: '(%s) %s' % (x.type.title(), x.title[0:60]))
if not isinstance(items, list):
items = [items]
for i in items:
if isinstance(i, Show):
display = lambda i: '%s %s %s' % (i.grandparentTitle, i.seasonEpisode, i.title)
selected_eps = utils.choose('Choose episode', i.episodes(), display)
if isinstance(selected_eps, list):
item += selected_eps
else:
item.append(selected_eps)
else:
item.append(i)
if not isinstance(item, list):
item = [item]
return item
@ -47,16 +67,25 @@ def get_item_from_url(url):
if __name__ == '__main__':
# Command line parser
from plexapi import CONFIG
from tqdm import tqdm
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--username', help='Your Plex username')
parser.add_argument('--password', help='Your Plex password')
parser.add_argument('-u', '--username', help='Your Plex username',
default=CONFIG.get('auth.myplex_username'))
parser.add_argument('-p', '--password', help='Your Plex password',
default=CONFIG.get('auth.myplex_password'))
parser.add_argument('--url', default=None, help='Download from URL (only paste after !)')
opts = parser.parse_args()
# Search item to download
account = utils.getMyPlexAccount(opts)
item = search_for_item(opts.url)
# Download the item
print("Downloading '%s' from %s.." % (item._prettyfilename(), item._server.friendlyName))
filepaths = item.download('./', showstatus=True)
for filepath in filepaths:
print(' %s' % filepath)
items = search_for_item(opts.url)
for item in items:
for part in item.iterParts():
# We do this manually since we dont want to add a progress to Episode etc
filename = '%s.%s' % (item._prettyfilename(), part.container)
url = item._server.url('%s?download=1' % part.key)
filepath = utils.download(url, filename=filename, savepath=os.getcwd(),
session=item._server._session, showstatus=True)
#print(' %s' % filepath)