code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
responses = []
if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
return responses
for receiver in self._live_receivers(sender):
response = receiver(signal=self, sender=sender, **named)
responses.append((receiver, response))
return responses | def send(self, sender, **named) | Send signal from sender to all connected receivers.
If any receiver raises an error, the error propagates back through send,
terminating the dispatch loop. So it's possible that all receivers
won't be called if an error is raised.
Arguments:
sender
The sender of the signal. Either a specific object or None.
named
Named arguments which will be passed to receivers.
Returns a list of tuple pairs [(receiver, response), ... ]. | 4.287587 | 3.196774 | 1.341223 |
responses = []
if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
return responses
# Call each receiver with whatever arguments it can accept.
# Return a list of tuple pairs [(receiver, response), ... ].
for receiver in self._live_receivers(sender):
try:
response = receiver(signal=self, sender=sender, **named)
except Exception as err:
if not hasattr(err, '__traceback__'):
err.__traceback__ = sys.exc_info()[2]
responses.append((receiver, err))
else:
responses.append((receiver, response))
return responses | def send_robust(self, sender, **named) | Send signal from sender to all connected receivers catching errors.
Arguments:
sender
The sender of the signal. Can be any python object (normally one
registered with a connect if you actually want something to
occur).
named
Named arguments which will be passed to receivers. These
arguments must be a subset of the argument names defined in
providing_args.
Return a list of tuple pairs [(receiver, response), ... ]. May raise
DispatcherKeyError.
If any receiver raises an error (specifically any subclass of
Exception), the error instance is returned as the result for that
receiver. The traceback is always attached to the error at
``__traceback__``. | 3.488684 | 2.705593 | 1.289434 |
receivers = None
if self.use_caching and not self._dead_receivers:
receivers = self.sender_receivers_cache.get(sender)
# We could end up here with NO_RECEIVERS even if we do check this case in
# .send() prior to calling _live_receivers() due to concurrent .send() call.
if receivers is NO_RECEIVERS:
return []
if receivers is None:
with self.lock:
self._clear_dead_receivers()
senderkey = _make_id(sender)
receivers = []
for (receiverkey, r_senderkey), receiver in self.receivers:
if r_senderkey == NONE_ID or r_senderkey == senderkey:
receivers.append(receiver)
if self.use_caching:
if not receivers:
self.sender_receivers_cache[sender] = NO_RECEIVERS
else:
# Note, we must cache the weakref versions.
self.sender_receivers_cache[sender] = receivers
non_weak_receivers = []
for receiver in receivers:
if isinstance(receiver, weakref.ReferenceType):
# Dereference the weak reference.
receiver = receiver()
if receiver is not None:
non_weak_receivers.append(receiver)
else:
non_weak_receivers.append(receiver)
return non_weak_receivers | def _live_receivers(self, sender) | Filter sequence of receivers to get resolved, live receivers.
This checks for weak references and resolves them, then returning only
live receivers. | 3.259155 | 3.232821 | 1.008146 |
def _decorator(func):
self.connect(func, **kwargs)
return func
return _decorator | def receive(self, **kwargs) | A decorator for connecting receivers to this signal. Used by passing in the
keyword arguments to connect::
@post_save.receive(sender=MyModel)
def signal_receiver(sender, **kwargs):
... | 5.622903 | 4.669647 | 1.204139 |
responses = []
if not self.receivers:
return responses
sender_id = _make_id(sender)
if sender_id not in self.sender_status:
self.sender_status[sender_id] = {}
if self.sender_status[sender_id] == named:
return responses
self.sender_status[sender_id] = named
for receiver in self._live_receivers(sender_id):
response = receiver(signal=self, sender=sender, **named)
responses.append((receiver, response))
return responses | def send(self, sender, **named) | Send signal from sender to all connected receivers *only if* the signal's
contents has changed.
If any receiver raises an error, the error propagates back through send,
terminating the dispatch loop, so it is quite possible to not have all
receivers called if a raises an error.
Arguments:
sender
The sender of the signal Either a specific object or None.
named
Named arguments which will be passed to receivers.
Returns a list of tuple pairs [(receiver, response), ... ]. | 2.915796 | 2.496026 | 1.168175 |
self.basicevent.SetBinaryState(BinaryState=int(state))
self._state = int(state) | def set_state(self, state) | Set the state of this device to on or off. | 14.934072 | 8.304901 | 1.798224 |
self.toggle()
gevent.spawn_later(delay, self.toggle) | def blink(self, delay=1) | Toggle the switch once, then again after a delay (in seconds). | 7.280927 | 6.031083 | 1.207234 |
server = getattr(self, "_server", None)
if server is None:
server = WSGIServer(('', self.port), self._handle, log=None)
self._server = server
return server | def server(self) | UDP server to listen for responses. | 3.169393 | 3.226056 | 0.982436 |
# The base implementation using GetBinaryState doesn't work for Maker (always returns 0).
# So pull the switch state from the atrributes instead
if force_update or self._state is None:
return(int(self.maker_attribs.get('switchstate',0)))
return self._state | def get_state(self, force_update=False) | Returns 0 if off and 1 if on. | 14.67965 | 12.014967 | 1.22178 |
server = getattr(self, "_server", None)
if server is None:
log.debug("Binding datagram server to %s", self.bind)
server = DatagramServer(self.bind, self._response_received)
self._server = server
return server | def server(self) | UDP server to listen for responses. | 4.033978 | 3.563764 | 1.131943 |
log.debug("Broadcasting M-SEARCH to %s:%s", self.mcast_ip, self.mcast_port)
request = '\r\n'.join(("M-SEARCH * HTTP/1.1",
"HOST:{mcast_ip}:{mcast_port}",
"ST:upnp:rootdevice",
"MX:2",
'MAN:"ssdp:discover"',
"", "")).format(**self.__dict__)
self.server.sendto(request.encode(), (self.mcast_ip, self.mcast_port)) | def broadcast(self) | Send a multicast M-SEARCH request asking for devices to report in. | 2.685633 | 2.249563 | 1.193846 |
@wraps(f)
def inner(*args, **kwargs):
kwargs['timeout'] = 5
remaining = get_retries() + 1
while remaining:
remaining -= 1
try:
return f(*args, **kwargs)
except (requests.ConnectionError, requests.Timeout):
if not remaining:
raise
gevent.sleep(delay)
return inner | def retry_with_delay(f, delay=60) | Retry the wrapped requests.request function in case of ConnectionError.
Optionally limit the number of retries or set the delay between retries. | 2.947189 | 2.782074 | 1.05935 |
etype = getattr(cls, 'STREAMTYPE', cls.TYPE)
ehash = '%s.%s' % (cls.TAG, etype) if etype else cls.TAG
if ehash in PLEXOBJECTS:
raise Exception('Ambiguous PlexObject definition %s(tag=%s, type=%s) with %s' %
(cls.__name__, cls.TAG, etype, PLEXOBJECTS[ehash].__name__))
PLEXOBJECTS[ehash] = cls
return cls | def registerPlexObject(cls) | Registry of library types we may come across when parsing XML. This allows us to
define a few helper functions to dynamically convery the XML into objects. See
buildItem() below for an example. | 3.626992 | 3.867264 | 0.93787 |
if value is not None:
if func == bool:
return bool(int(value))
elif func in (int, float):
try:
return func(value)
except ValueError:
return float('nan')
return func(value)
return value | def cast(func, value) | Cast the specified value to the specified type (returned by func). Currently this
only support int, float, bool. Should be extended if needed.
Parameters:
func (func): Calback function to used cast to type (int, bool, float).
value (any): value to be cast and returned. | 2.481414 | 3.184339 | 0.779256 |
if not args:
return ''
arglist = []
for key in sorted(args, key=lambda x: x.lower()):
value = compat.ustr(args[key])
arglist.append('%s=%s' % (key, compat.quote(value)))
return '?%s' % '&'.join(arglist) | def joinArgs(args) | Returns a query string (uses for HTTP URLs) where only the value is URL encoded.
Example return value: '?genre=action&type=1337'.
Parameters:
args (dict): Arguments to include in query string. | 3.002712 | 3.177355 | 0.945035 |
parts = attrstr.split(delim, 1)
attr = parts[0]
attrstr = parts[1] if len(parts) == 2 else None
if isinstance(obj, dict):
value = obj[attr]
elif isinstance(obj, list):
value = obj[int(attr)]
elif isinstance(obj, tuple):
value = obj[int(attr)]
elif isinstance(obj, object):
value = getattr(obj, attr)
if attrstr:
return rget(value, attrstr, default, delim)
return value
except: # noqa: E722
return default | def rget(obj, attrstr, default=None, delim='.'): # pragma: no cover
try | Returns the value at the specified attrstr location within a nexted tree of
dicts, lists, tuples, functions, classes, etc. The lookup is done recursivley
for each key in attrstr (split by by the delimiter) This function is heavily
influenced by the lookups used in Django templates.
Parameters:
obj (any): Object to start the lookup in (dict, obj, list, tuple, etc).
attrstr (str): String to lookup (ex: 'foo.bar.baz.value')
default (any): Default value to return if not found.
delim (str): Delimiter separating keys in attrstr. | 2.079649 | 2.210032 | 0.941004 |
libtype = compat.ustr(libtype)
if libtype in [compat.ustr(v) for v in SEARCHTYPES.values()]:
return libtype
if SEARCHTYPES.get(libtype) is not None:
return SEARCHTYPES[libtype]
raise NotFound('Unknown libtype: %s' % libtype) | def searchType(libtype) | Returns the integer value of the library string type.
Parameters:
libtype (str): LibType to lookup (movie, show, season, episode, artist, album, track,
collection)
Raises:
:class:`plexapi.exceptions.NotFound`: Unknown libtype | 3.743247 | 3.642048 | 1.027786 |
threads, results = [], []
job_is_done_event = Event()
for args in listargs:
args += [results, len(results)]
results.append(None)
threads.append(Thread(target=callback, args=args, kwargs=dict(job_is_done_event=job_is_done_event)))
threads[-1].setDaemon(True)
threads[-1].start()
while not job_is_done_event.is_set():
if all([not t.is_alive() for t in threads]):
break
time.sleep(0.05)
return [r for r in results if r is not None] | def threaded(callback, listargs) | Returns the result of <callback> for each set of \*args in listargs. Each call
to <callback> is called concurrently in their own separate threads.
Parameters:
callback (func): Callback function to apply to each set of \*args.
listargs (list): List of lists; \*args to pass each thread. | 2.433922 | 2.784379 | 0.874134 |
if value and value is not None:
if format:
value = datetime.strptime(value, format)
else:
# https://bugs.python.org/issue30684
# And platform support for before epoch seems to be flaky.
# TODO check for others errors too.
if int(value) == 0:
value = 86400
value = datetime.fromtimestamp(int(value))
return value | def toDatetime(value, format=None) | Returns a datetime object from the specified value.
Parameters:
value (str): value to return as a datetime
format (str): Format to pass strftime (optional; if value is a str). | 6.516457 | 7.354274 | 0.886078 |
value = value or ''
itemcast = itemcast or str
return [itemcast(item) for item in value.split(delim) if item != ''] | def toList(value, itemcast=None, delim=',') | Returns a list of strings from the specified value.
Parameters:
value (str): comma delimited string to convert to list.
itemcast (func): Function to cast each list item to (default str).
delim (str): string delimiter (optional; default ','). | 2.703486 | 4.000891 | 0.675721 |
url = None
for part in media.iterParts():
if media.thumb:
url = media.thumb
if part.indexes: # always use bif images if available.
url = '/library/parts/%s/indexes/%s/%s' % (part.id, part.indexes.lower(), media.viewOffset)
if url:
if filename is None:
prettyname = media._prettyfilename()
filename = 'session_transcode_%s_%s_%s' % (media.usernames[0], prettyname, int(time.time()))
url = server.transcodeImage(url, height, width, opacity, saturation)
filepath = download(url, filename=filename)
info['username'] = {'filepath': filepath, 'url': url}
return info | def downloadSessionImages(server, filename=None, height=150, width=150,
opacity=100, saturation=100): # pragma: no cover
info = {}
for media in server.sessions() | Helper to download a bif image or thumb.url from plex.server.sessions.
Parameters:
filename (str): default to None,
height (int): Height of the image.
width (int): width of the image.
opacity (int): Opacity of the resulting image (possibly deprecated).
saturation (int): Saturating of the resulting image.
Returns:
{'hellowlol': {'filepath': '<filepath>', 'url': 'http://<url>'},
{'<username>': {filepath, url}}, ... | 7.072541 | 6.276579 | 1.126815 |
from plexapi import log
# fetch the data to be saved
session = session or requests.Session()
headers = {'X-Plex-Token': token}
response = session.get(url, headers=headers, stream=True)
# make sure the savepath directory exists
savepath = savepath or os.getcwd()
compat.makedirs(savepath, exist_ok=True)
# try getting filename from header if not specified in arguments (used for logs, db)
if not filename and response.headers.get('Content-Disposition'):
filename = re.findall(r'filename=\"(.+)\"', response.headers.get('Content-Disposition'))
filename = filename[0] if filename[0] else None
filename = os.path.basename(filename)
fullpath = os.path.join(savepath, filename)
# append file.ext from content-type if not already there
extension = os.path.splitext(fullpath)[-1]
if not extension:
contenttype = response.headers.get('content-type')
if contenttype and 'image' in contenttype:
fullpath += contenttype.split('/')[1]
# check this is a mocked download (testing)
if mocked:
log.debug('Mocked download %s', fullpath)
return fullpath
# save the file to disk
log.info('Downloading: %s', fullpath)
if showstatus: # pragma: no cover
total = int(response.headers.get('content-length', 0))
bar = tqdm(unit='B', unit_scale=True, total=total, desc=filename)
with open(fullpath, 'wb') as handle:
for chunk in response.iter_content(chunk_size=chunksize):
handle.write(chunk)
if showstatus:
bar.update(len(chunk))
if showstatus: # pragma: no cover
bar.close()
# check we want to unzip the contents
if fullpath.endswith('zip') and unpack:
with zipfile.ZipFile(fullpath, 'r') as handle:
handle.extractall(savepath)
return fullpath | def download(url, token, filename=None, savepath=None, session=None, chunksize=4024,
unpack=False, mocked=False, showstatus=False) | Helper to download a thumb, videofile or other media item. Returns the local
path to the downloaded file.
Parameters:
url (str): URL where the content be reached.
token (str): Plex auth token to include in headers.
filename (str): Filename of the downloaded file, default None.
savepath (str): Defaults to current working dir.
chunksize (int): What chunksize read/write at the time.
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 | 2.678939 | 2.716154 | 0.986299 |
if not isinstance(items, list):
items = [items]
data = {}
if not remove:
for i, item in enumerate(items):
tagname = '%s[%s].tag.tag' % (tag, i)
data[tagname] = item
if remove:
tagname = '%s[].tag.tag-' % tag
data[tagname] = ','.join(items)
data['%s.locked' % tag] = 1 if locked else 0
return data | def tag_helper(tag, items, locked=True, remove=False) | Simple tag helper for editing a object. | 3.028985 | 2.960608 | 1.023096 |
print('Authenticating with Plex.tv as %s..' % opts.username)
return MyPlexAccount(opts.username, opts.password)
# 2. Check Plexconfig (environment variables and config.ini)
config_username = CONFIG.get('auth.myplex_username')
config_password = CONFIG.get('auth.myplex_password')
if config_username and config_password:
print('Authenticating with Plex.tv as %s..' % config_username)
return MyPlexAccount(config_username, config_password)
# 3. Prompt for username and password on the command line
username = input('What is your plex.tv username: ')
password = getpass('What is your plex.tv password: ')
print('Authenticating with Plex.tv as %s..' % username)
return MyPlexAccount(username, password) | def getMyPlexAccount(opts=None): # pragma: no cover
from plexapi import CONFIG
from plexapi.myplex import MyPlexAccount
# 1. Check command-line options
if opts and opts.username and opts.password | Helper function tries to get a MyPlex Account instance by checking
the the following locations for a username and password. This is
useful to create user-friendly command line tools.
1. command-line options (opts).
2. environment variables and config.ini
3. Prompt on the command line. | 2.158956 | 2.005525 | 1.076504 |
return items[0]
# Print all choices to the command line
print()
for index, i in enumerate(items):
name = attr(i) if callable(attr) else getattr(i, attr)
print(' %s: %s' % (index, name))
print()
# Request choice from the user
while True:
try:
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 | def choose(msg, items, attr): # pragma: no cover
# Return the first item if there is only one choice
if len(items) == 1 | Command line helper to display a list of choices, asking the
user to choose one of the options. | 3.157287 | 3.091086 | 1.021417 |
servers = servers = [s for s in account.resources() if 'server' in s.provides]
# If servername specified find and return it
if servername is not None:
for server in servers:
if server.name == servername:
return server.connect()
raise SystemExit('Unknown server name: %s' % servername)
# If servername not specified; allow user to choose
return utils.choose('Choose a Server', servers, 'name').connect() | def _find_server(account, servername=None) | Find and return a PlexServer object. | 4.832023 | 4.547627 | 1.062537 |
data = defaultdict(lambda: dict())
for section in _iter_sections(plex, opts):
print('Fetching watched status for %s..' % section.title)
skey = section.title.lower()
for item in _iter_items(section):
if not opts.watchedonly or item.isWatched:
ikey = _item_key(item)
data[skey][ikey] = item.isWatched
import pprint; pprint.pprint(item.__dict__); break
print('Writing backup file to %s' % opts.filepath)
with open(opts.filepath, 'w') as handle:
json.dump(dict(data), handle, sort_keys=True, indent=2) | def backup_watched(plex, opts) | Backup watched status to the specified filepath. | 3.545466 | 3.390804 | 1.045612 |
with open(opts.filepath, 'r') as handle:
source = json.load(handle)
# Find the differences
differences = defaultdict(lambda: dict())
for section in _iter_sections(plex, opts):
print('Finding differences in %s..' % section.title)
skey = section.title.lower()
for item in _iter_items(section):
ikey = _item_key(item)
sval = source.get(skey,{}).get(ikey)
if sval is None:
raise SystemExit('%s not found' % ikey)
if (sval is not None and item.isWatched != sval) and (not opts.watchedonly or sval):
differences[skey][ikey] = {'isWatched':sval, 'item':item}
print('Applying %s differences to destination' % len(differences))
import pprint; pprint.pprint(differences) | def restore_watched(plex, opts) | Restore watched status from the specified filepath. | 3.960788 | 3.872562 | 1.022782 |
try:
data = json.loads(message)['NotificationContainer']
log.debug('Alert: %s %s %s', *data)
if self._callback:
self._callback(data)
except Exception as err: # pragma: no cover
log.error('AlertListener Msg Error: %s', err) | def _onMessage(self, ws, message) | Called when websocket message is recieved. | 5.747674 | 5.817873 | 0.987934 |
self._data = data
for elem in data:
id = utils.lowerFirst(elem.attrib['id'])
if id in self._settings:
self._settings[id]._loadData(elem)
continue
self._settings[id] = Setting(self._server, elem, self._initpath) | def _loadData(self, data) | Load attribute values from Plex XML response. | 5.687996 | 4.731337 | 1.202196 |
return list(v for id, v in sorted(self._settings.items())) | def all(self) | Returns a list of all :class:`~plexapi.settings.Setting` objects available. | 20.026522 | 12.755095 | 1.57008 |
id = utils.lowerFirst(id)
if id in self._settings:
return self._settings[id]
raise NotFound('Invalid setting id: %s' % id) | def get(self, id) | Return the :class:`~plexapi.settings.Setting` object with the specified id. | 6.035161 | 4.256238 | 1.417957 |
groups = defaultdict(list)
for setting in self.all():
groups[setting.group].append(setting)
return dict(groups) | def groups(self) | Returns a dict of lists for all :class:`~plexapi.settings.Setting`
objects grouped by setting group. | 4.726401 | 2.915859 | 1.620929 |
params = {}
for setting in self.all():
if setting._setValue:
log.info('Saving PlexServer setting %s = %s' % (setting.id, setting._setValue))
params[setting.id] = quote(setting._setValue)
if not params:
raise BadRequest('No setting have been modified.')
querystr = '&'.join(['%s=%s' % (k, v) for k, v in params.items()])
url = '%s?%s' % (self.key, querystr)
self._server.query(url, self._server._session.put)
self.reload() | def save(self) | Save any outstanding settnig changes to the :class:`~plexapi.server.PlexServer`. This
performs a full reload() of Settings after complete. | 4.774801 | 3.760456 | 1.26974 |
self._setValue = None
self.id = data.attrib.get('id')
self.label = data.attrib.get('label')
self.summary = data.attrib.get('summary')
self.type = data.attrib.get('type')
self.default = self._cast(data.attrib.get('default'))
self.value = self._cast(data.attrib.get('value'))
self.hidden = utils.cast(bool, data.attrib.get('hidden'))
self.advanced = utils.cast(bool, data.attrib.get('advanced'))
self.group = data.attrib.get('group')
self.enumValues = self._getEnumValues(data) | def _loadData(self, data) | Load attribute values from Plex XML response. | 2.399426 | 2.173373 | 1.10401 |
if self.type != 'text':
value = utils.cast(self.TYPES.get(self.type)['cast'], value)
return value | def _cast(self, value) | Cast the specifief value to the type of this setting. | 8.199644 | 7.5953 | 1.079568 |
enumstr = data.attrib.get('enumValues')
if not enumstr:
return None
if ':' in enumstr:
return {self._cast(k): v for k, v in [kv.split(':') for kv in enumstr.split('|')]}
return enumstr.split('|') | def _getEnumValues(self, data) | Returns a list of dictionary of valis value for this setting. | 4.343364 | 4.029713 | 1.077835 |
# check a few things up front
if not isinstance(value, self.TYPES[self.type]['type']):
badtype = type(value).__name__
raise BadRequest('Invalid value for %s: a %s is required, not %s' % (self.id, self.type, badtype))
if self.enumValues and value not in self.enumValues:
raise BadRequest('Invalid value for %s: %s not in %s' % (self.id, value, list(self.enumValues)))
# store value off to the side until we call settings.save()
tostr = self.TYPES[self.type]['tostr']
self._setValue = tostr(value) | def set(self, value) | Set a new value for this setitng. NOTE: You must call plex.settings.save() for before
any changes to setting values are persisted to the :class:`~plexapi.server.PlexServer`. | 4.87227 | 4.434237 | 1.098784 |
self._data = data
self.allowCameraUpload = cast(bool, data.attrib.get('allowCameraUpload'))
self.allowChannelAccess = cast(bool, data.attrib.get('allowChannelAccess'))
self.allowMediaDeletion = cast(bool, data.attrib.get('allowMediaDeletion'))
self.allowSharing = cast(bool, data.attrib.get('allowSharing'))
self.allowSync = cast(bool, data.attrib.get('allowSync'))
self.backgroundProcessing = cast(bool, data.attrib.get('backgroundProcessing'))
self.certificate = cast(bool, data.attrib.get('certificate'))
self.companionProxy = cast(bool, data.attrib.get('companionProxy'))
self.diagnostics = utils.toList(data.attrib.get('diagnostics'))
self.eventStream = cast(bool, data.attrib.get('eventStream'))
self.friendlyName = data.attrib.get('friendlyName')
self.hubSearch = cast(bool, data.attrib.get('hubSearch'))
self.machineIdentifier = data.attrib.get('machineIdentifier')
self.multiuser = cast(bool, data.attrib.get('multiuser'))
self.myPlex = cast(bool, data.attrib.get('myPlex'))
self.myPlexMappingState = data.attrib.get('myPlexMappingState')
self.myPlexSigninState = data.attrib.get('myPlexSigninState')
self.myPlexSubscription = cast(bool, data.attrib.get('myPlexSubscription'))
self.myPlexUsername = data.attrib.get('myPlexUsername')
self.ownerFeatures = utils.toList(data.attrib.get('ownerFeatures'))
self.photoAutoTag = cast(bool, data.attrib.get('photoAutoTag'))
self.platform = data.attrib.get('platform')
self.platformVersion = data.attrib.get('platformVersion')
self.pluginHost = cast(bool, data.attrib.get('pluginHost'))
self.readOnlyLibraries = cast(int, data.attrib.get('readOnlyLibraries'))
self.requestParametersInCookie = cast(bool, data.attrib.get('requestParametersInCookie'))
self.streamingBrainVersion = data.attrib.get('streamingBrainVersion')
self.sync = cast(bool, data.attrib.get('sync'))
self.transcoderActiveVideoSessions = int(data.attrib.get('transcoderActiveVideoSessions', 0))
self.transcoderAudio = cast(bool, data.attrib.get('transcoderAudio'))
self.transcoderLyrics = cast(bool, data.attrib.get('transcoderLyrics'))
self.transcoderPhoto = cast(bool, data.attrib.get('transcoderPhoto'))
self.transcoderSubtitles = cast(bool, data.attrib.get('transcoderSubtitles'))
self.transcoderVideo = cast(bool, data.attrib.get('transcoderVideo'))
self.transcoderVideoBitrates = utils.toList(data.attrib.get('transcoderVideoBitrates'))
self.transcoderVideoQualities = utils.toList(data.attrib.get('transcoderVideoQualities'))
self.transcoderVideoResolutions = utils.toList(data.attrib.get('transcoderVideoResolutions'))
self.updatedAt = utils.toDatetime(data.attrib.get('updatedAt'))
self.updater = cast(bool, data.attrib.get('updater'))
self.version = data.attrib.get('version')
self.voiceSearch = cast(bool, data.attrib.get('voiceSearch')) | def _loadData(self, data) | Load attribute values from Plex XML response. | 1.935099 | 1.876126 | 1.031433 |
headers = BASE_HEADERS.copy()
if self._token:
headers['X-Plex-Token'] = self._token
headers.update(kwargs)
return headers | def _headers(self, **kwargs) | Returns dict containing base headers for all requests to the server. | 3.483148 | 2.901296 | 1.200549 |
if not self._library:
try:
data = self.query(Library.key)
self._library = Library(self, data)
except BadRequest:
data = self.query('/library/sections/')
# Only the owner has access to /library
# so just return the library without the data.
return Library(self, data)
return self._library | def library(self) | Library to browse or search your media. | 6.906134 | 6.352863 | 1.08709 |
if not self._settings:
data = self.query(Settings.key)
self._settings = Settings(self, data)
return self._settings | def settings(self) | Returns a list of all server settings. | 5.274389 | 4.812746 | 1.095921 |
data = self.query(Account.key)
return Account(self, data) | def account(self) | Returns the :class:`~plexapi.server.Account` object this server belongs to. | 13.181687 | 9.296058 | 1.417987 |
if self._myPlexAccount is None:
from plexapi.myplex import MyPlexAccount
self._myPlexAccount = MyPlexAccount(token=self._token)
return self._myPlexAccount | def myPlexAccount(self) | Returns a :class:`~plexapi.myplex.MyPlexAccount` object using the same
token to access this server. If you are not the owner of this PlexServer
you're likley to recieve an authentication error calling this. | 2.332323 | 2.08832 | 1.116842 |
try:
ports = {}
account = self.myPlexAccount()
for device in account.devices():
if device.connections and ':' in device.connections[0][6:]:
ports[device.clientIdentifier] = device.connections[0].split(':')[-1]
return ports
except Exception as err:
log.warning('Unable to fetch client ports from myPlex: %s', err)
return ports | def _myPlexClientPorts(self) | Sometimes the PlexServer does not properly advertise port numbers required
to connect. This attemps to look up device port number from plex.tv.
See issue #126: Make PlexServer.clients() more user friendly.
https://github.com/pkkid/python-plexapi/issues/126 | 4.451088 | 4.072197 | 1.093044 |
items = []
ports = None
for elem in self.query('/clients'):
port = elem.attrib.get('port')
if not port:
log.warning('%s did not advertise a port, checking plex.tv.', elem.attrib.get('name'))
ports = self._myPlexClientPorts() if ports is None else ports
port = ports.get(elem.attrib.get('machineIdentifier'))
baseurl = 'http://%s:%s' % (elem.attrib['host'], port)
items.append(PlexClient(baseurl=baseurl, server=self,
token=self._token, data=elem, connect=False))
return items | def clients(self) | Returns list of all :class:`~plexapi.client.PlexClient` objects connected to server. | 5.898507 | 4.532811 | 1.301291 |
for client in self.clients():
if client and client.title == name:
return client
raise NotFound('Unknown client name: %s' % name) | def client(self, name) | Returns the :class:`~plexapi.client.PlexClient` that matches the specified name.
Parameters:
name (str): Name of the client to return.
Raises:
:class:`plexapi.exceptions.NotFound`: Unknown client name | 5.969695 | 4.825984 | 1.23699 |
return Playlist.create(self, title, items=items, limit=limit, section=section, smart=smart, **kwargs) | def createPlaylist(self, title, items=None, section=None, limit=None, smart=None, **kwargs) | Creates and returns a new :class:`~plexapi.playlist.Playlist`.
Parameters:
title (str): Title of the playlist to be created.
items (list<Media>): List of media items to include in the playlist. | 2.903081 | 4.958987 | 0.585418 |
url = self.url('/diagnostics/databases')
filepath = utils.download(url, self._token, None, savepath, self._session, unpack=unpack)
return filepath | def downloadDatabases(self, savepath=None, unpack=False) | Download databases.
Parameters:
savepath (str): Defaults to current working dir.
unpack (bool): Unpack the zip file. | 8.881121 | 11.715631 | 0.758057 |
part = '/updater/check?download=%s' % (1 if download else 0)
if force:
self.query(part, method=self._session.put)
releases = self.fetchItems('/updater/status')
if len(releases):
return releases[0] | def check_for_update(self, force=True, download=False) | Returns a :class:`~plexapi.base.Release` object containing release info.
Parameters:
force (bool): Force server to check for new releases
download (bool): Download if a update is available. | 8.719839 | 7.367838 | 1.1835 |
# We can add this but dunno how useful this is since it sometimes
# requires user action using a gui.
part = '/updater/apply'
release = self.check_for_update(force=True, download=True)
if release and release.version != self.version:
# figure out what method this is..
return self.query(part, method=self._session.put) | def installUpdate(self) | Install the newest version of Plex Media Server. | 19.470888 | 18.577162 | 1.048109 |
results = []
params = {'query': query}
if mediatype:
params['section'] = utils.SEARCHTYPES[mediatype]
if limit:
params['limit'] = limit
key = '/hubs/search?%s' % urlencode(params)
for hub in self.fetchItems(key, Hub):
results += hub.items
return results | def search(self, query, mediatype=None, limit=None) | Returns a list of media items or filter categories from the resulting
`Hub Search <https://www.plex.tv/blog/seek-plex-shall-find-leveling-web-app/>`_
against all items in your Plex library. This searches genres, actors, directors,
playlists, as well as all the obvious media titles. It performs spell-checking
against your search terms (because KUROSAWA is hard to spell). It also provides
contextual search results. So for example, if you search for 'Pernice', it’ll
return 'Pernice Brothers' as the artist result, but we’ll also go ahead and
return your most-listened to albums and tracks from the artist. If you type
'Arnold' you’ll get a result for the actor, but also the most recently added
movies he’s in.
Parameters:
query (str): Query to use when searching your library.
mediatype (str): Optionally limit your search to the specified media type.
limit (int): Optionally limit to the specified number of results per Hub. | 5.078028 | 5.004729 | 1.014646 |
notifier = AlertListener(self, callback)
notifier.start()
return notifier | def startAlertListener(self, callback=None) | Creates a websocket connection to the Plex Server to optionally recieve
notifications. These often include messages from Plex about media scans
as well as updates to currently running Transcode Sessions.
NOTE: You need websocket-client installed in order to use this feature.
>> pip install websocket-client
Parameters:
callback (func): Callback function to call on recieved messages.
raises:
:class:`plexapi.exception.Unsupported`: Websocket-client not installed. | 5.810121 | 9.723975 | 0.597505 |
if media:
transcode_url = '/photo/:/transcode?height=%s&width=%s&opacity=%s&saturation=%s&url=%s' % (
height, width, opacity, saturation, media)
return self.url(transcode_url, includeToken=True) | def transcodeImage(self, media, height, width, opacity=100, saturation=100) | Returns the URL for a transcoded image from the specified media object.
Returns None if no media specified (needed if user tries to pass thumb
or art directly).
Parameters:
height (int): Height to transcode the image to.
width (int): Width to transcode the image to.
opacity (int): Opacity of the resulting image (possibly deprecated).
saturation (int): Saturating of the resulting image. | 3.946712 | 4.216206 | 0.936081 |
if self._token and (includeToken or self._showSecrets):
delim = '&' if '?' in key else '?'
return '%s%s%sX-Plex-Token=%s' % (self._baseurl, key, delim, self._token)
return '%s%s' % (self._baseurl, key) | def url(self, key, includeToken=None) | Build a URL string with proper token argument. Token will be appended to the URL
if either includeToken is True or CONFIG.log.show_secrets is 'true'. | 3.382962 | 3.141255 | 1.076946 |
self._data = data
self.listType = 'video'
self.addedAt = utils.toDatetime(data.attrib.get('addedAt'))
self.key = data.attrib.get('key', '')
self.lastViewedAt = utils.toDatetime(data.attrib.get('lastViewedAt'))
self.librarySectionID = data.attrib.get('librarySectionID')
self.ratingKey = utils.cast(int, data.attrib.get('ratingKey'))
self.summary = data.attrib.get('summary')
self.thumb = data.attrib.get('thumb')
self.title = data.attrib.get('title')
self.titleSort = data.attrib.get('titleSort', self.title)
self.type = data.attrib.get('type')
self.updatedAt = utils.toDatetime(data.attrib.get('updatedAt'))
self.viewCount = utils.cast(int, data.attrib.get('viewCount', 0)) | def _loadData(self, data) | Load attribute values from Plex XML response. | 2.178283 | 1.799459 | 1.210521 |
thumb = self.firstAttr('thumb', 'parentThumb', 'granparentThumb')
return self._server.url(thumb, includeToken=True) if thumb else None | def thumbUrl(self) | Return the first first thumbnail url starting on
the most specific thumbnail for that item. | 16.996281 | 16.298449 | 1.042816 |
art = self.firstAttr('art', 'grandparentArt')
return self._server.url(art, includeToken=True) if art else None | def artUrl(self) | Return the first first art url starting on the most specific for that item. | 14.674559 | 11.317982 | 1.29657 |
return self._server.url(part, includeToken=True) if part else None | def url(self, part) | Returns the full url for something. Typically used for getting a specific image. | 16.260645 | 13.137732 | 1.237706 |
key = '/:/scrobble?key=%s&identifier=com.plexapp.plugins.library' % self.ratingKey
self._server.query(key)
self.reload() | def markWatched(self) | Mark video as watched. | 11.977225 | 10.424392 | 1.148962 |
key = '/:/unscrobble?key=%s&identifier=com.plexapp.plugins.library' % self.ratingKey
self._server.query(key)
self.reload() | def markUnwatched(self) | Mark video unwatched. | 13.812799 | 12.71342 | 1.086474 |
from plexapi.sync import SyncItem, Policy, MediaSettings
myplex = self._server.myPlexAccount()
sync_item = SyncItem(self._server, None)
sync_item.title = title if title else self._defaultSyncTitle()
sync_item.rootTitle = self.title
sync_item.contentType = self.listType
sync_item.metadataType = self.METADATA_TYPE
sync_item.machineIdentifier = self._server.machineIdentifier
section = self._server.library.sectionByID(self.librarySectionID)
sync_item.location = 'library://%s/item/%s' % (section.uuid, quote_plus(self.key))
sync_item.policy = Policy.create(limit, unwatched)
sync_item.mediaSettings = MediaSettings.createVideo(videoQuality)
return myplex.sync(sync_item, client=client, clientId=clientId) | def sync(self, videoQuality, client=None, clientId=None, limit=None, unwatched=False, title=None) | Add current video (movie, tv-show, season or episode) as sync item for specified device.
See :func:`plexapi.myplex.MyPlexAccount.sync()` for possible exceptions.
Parameters:
videoQuality (int): idx of quality of the video, one of VIDEO_QUALITY_* values defined in
:mod:`plexapi.sync` module.
client (:class:`plexapi.myplex.MyPlexDevice`): sync destination, see
:func:`plexapi.myplex.MyPlexAccount.sync`.
clientId (str): sync destination, see :func:`plexapi.myplex.MyPlexAccount.sync`.
limit (int): maximum count of items to sync, unlimited if `None`.
unwatched (bool): if `True` watched videos wouldn't be synced.
title (str): descriptive title for the new :class:`plexapi.sync.SyncItem`, if empty the value would be
generated from metadata of current media.
Returns:
:class:`plexapi.sync.SyncItem`: an instance of created syncItem. | 4.145734 | 3.840067 | 1.0796 |
import plexapi
return {
'X-Plex-Platform': plexapi.X_PLEX_PLATFORM,
'X-Plex-Platform-Version': plexapi.X_PLEX_PLATFORM_VERSION,
'X-Plex-Provides': plexapi.X_PLEX_PROVIDES,
'X-Plex-Product': plexapi.X_PLEX_PRODUCT,
'X-Plex-Version': plexapi.X_PLEX_VERSION,
'X-Plex-Device': plexapi.X_PLEX_DEVICE,
'X-Plex-Device-Name': plexapi.X_PLEX_DEVICE_NAME,
'X-Plex-Client-Identifier': plexapi.X_PLEX_IDENTIFIER,
'X-Plex-Sync-Version': '2',
} | def reset_base_headers() | Convenience function returns a dict of all base X-Plex-* headers for session requests. | 1.654165 | 1.519915 | 1.088327 |
try:
# First: check environment variable is set
envkey = 'PLEXAPI_%s' % key.upper().replace('.', '_')
value = os.environ.get(envkey)
if value is None:
# Second: check the config file has attr
section, name = key.lower().split('.')
value = self.data.get(section, {}).get(name, default)
return cast(value) if cast else value
except: # noqa: E722
return default | def get(self, key, default=None, cast=None) | Returns the specified configuration value or <default> if not found.
Parameters:
key (str): Configuration variable to load in the format '<section>.<variable>'.
default: Default value to use if key not found.
cast (func): Cast the value to the specified type before returning. | 3.8292 | 3.716287 | 1.030383 |
config = defaultdict(dict)
for section in self._sections:
for name, value in self._sections[section].items():
if name != '__name__':
config[section.lower()][name.lower()] = value
return dict(config) | def _asDict(self) | Returns all configuration values as a dictionary. | 3.237458 | 2.794005 | 1.158716 |
self._data = data
self.codec = data.attrib.get('codec')
self.codecID = data.attrib.get('codecID')
self.id = cast(int, data.attrib.get('id'))
self.index = cast(int, data.attrib.get('index', '-1'))
self.language = data.attrib.get('language')
self.languageCode = data.attrib.get('languageCode')
self.selected = cast(bool, data.attrib.get('selected', '0'))
self.streamType = cast(int, data.attrib.get('streamType'))
self.type = cast(int, data.attrib.get('streamType')) | def _loadData(self, data) | Load attribute values from Plex XML response. | 2.380991 | 2.126916 | 1.119457 |
def parse(server, data, initpath): # pragma: no cover seems to be dead code.
STREAMCLS = {1: VideoStream, 2: AudioStream, 3: SubtitleStream}
stype = cast(int, data.attrib.get('streamType'))
cls = STREAMCLS.get(stype, MediaPartStream)
return cls(server, data, initpath) | Factory method returns a new MediaPartStream from xml data. | null | null | null |
|
self._data = data
self.id = cast(int, data.attrib.get('id'))
self.role = data.attrib.get('role')
self.tag = data.attrib.get('tag')
# additional attributes only from hub search
self.key = data.attrib.get('key')
self.librarySectionID = cast(int, data.attrib.get('librarySectionID'))
self.librarySectionTitle = data.attrib.get('librarySectionTitle')
self.librarySectionType = data.attrib.get('librarySectionType')
self.tagType = cast(int, data.attrib.get('tagType'))
self.thumb = data.attrib.get('thumb') | def _loadData(self, data) | Load attribute values from Plex XML response. | 3.041401 | 2.506458 | 1.213426 |
if not self.key:
raise BadRequest('Key is not defined for this tag: %s' % self.tag)
return self.fetchItems(self.key) | def items(self, *args, **kwargs) | Return the list of items within this tag. This function is only applicable
in search results from PlexServer :func:`~plexapi.server.PlexServer.search()`. | 8.311851 | 5.749875 | 1.445571 |
server = [s for s in self._server.resources() if s.clientIdentifier == self.machineIdentifier]
if len(server) == 0:
raise NotFound('Unable to find server with uuid %s' % self.machineIdentifier)
return server[0] | def server(self) | Returns :class:`plexapi.myplex.MyPlexResource` with server of current item. | 5.596581 | 3.717674 | 1.505399 |
server = self.server().connect()
key = '/sync/items/%s' % self.id
return server.fetchItems(key) | def getMedia(self) | Returns list of :class:`~plexapi.base.Playable` which belong to this sync item. | 18.439547 | 8.715915 | 2.115618 |
url = '/sync/%s/item/%s/downloaded' % (self.clientIdentifier, media.ratingKey)
media._server.query(url, method=requests.put) | def markDownloaded(self, media) | Mark the file as downloaded (by the nature of Plex it will be marked as downloaded within
any SyncItem where it presented).
Parameters:
media (base.Playable): the media to be marked as downloaded. | 11.721216 | 10.739705 | 1.091391 |
url = SyncList.key.format(clientId=self.clientIdentifier)
url += '/' + str(self.id)
self._server.query(url, self._server._session.delete) | def delete(self) | Removes current SyncItem | 15.421496 | 12.13785 | 1.27053 |
if videoQuality == VIDEO_QUALITY_ORIGINAL:
return MediaSettings('', '', '')
elif videoQuality < len(VIDEO_QUALITIES['bitrate']):
return MediaSettings(VIDEO_QUALITIES['bitrate'][videoQuality],
VIDEO_QUALITIES['videoQuality'][videoQuality],
VIDEO_QUALITIES['videoResolution'][videoQuality])
else:
raise BadRequest('Unexpected video quality') | def createVideo(videoQuality) | Returns a :class:`~plexapi.sync.MediaSettings` object, based on provided video quality value.
Parameters:
videoQuality (int): idx of quality of the video, one of VIDEO_QUALITY_* values defined in this module.
Raises:
:class:`plexapi.exceptions.BadRequest`: when provided unknown video quality. | 3.916182 | 3.149677 | 1.24336 |
if resolution in PHOTO_QUALITIES:
return MediaSettings(photoQuality=PHOTO_QUALITIES[resolution], photoResolution=resolution)
else:
raise BadRequest('Unexpected photo quality') | def createPhoto(resolution) | Returns a :class:`~plexapi.sync.MediaSettings` object, based on provided photo quality value.
Parameters:
resolution (str): maximum allowed resolution for synchronized photos, see PHOTO_QUALITY_* values in the
module.
Raises:
:class:`plexapi.exceptions.BadRequest` when provided unknown video quality. | 6.915149 | 4.547975 | 1.52049 |
scope = 'all'
if limit is None:
limit = 0
else:
scope = 'count'
return Policy(scope, unwatched, limit) | def create(limit=None, unwatched=False) | Creates a :class:`~plexapi.sync.Policy` object for provided options and automatically sets proper `scope`
value.
Parameters:
limit (int): limit items by count.
unwatched (bool): if True then watched items wouldn't be synced.
Returns:
:class:`~plexapi.sync.Policy`. | 7.801857 | 7.40453 | 1.05366 |
if value:
value = str(value).replace('/library/metadata/', '')
value = value.replace('/children', '')
return value.replace(' ', '-')[:20] | def _clean(self, value) | Clean attr value for display in __repr__. | 8.483644 | 7.740818 | 1.095962 |
# cls is specified, build the object and return
initpath = initpath or self._initpath
if cls is not None:
return cls(self._server, elem, initpath)
# cls is not specified, try looking it up in PLEXOBJECTS
etype = elem.attrib.get('type', elem.attrib.get('streamType'))
ehash = '%s.%s' % (elem.tag, etype) if etype else elem.tag
ecls = utils.PLEXOBJECTS.get(ehash, utils.PLEXOBJECTS.get(elem.tag))
# log.debug('Building %s as %s', elem.tag, ecls.__name__)
if ecls is not None:
return ecls(self._server, elem, initpath)
raise UnknownType("Unknown library type <%s type='%s'../>" % (elem.tag, etype)) | def _buildItem(self, elem, cls=None, initpath=None) | Factory function to build objects based on registered PLEXOBJECTS. | 4.300285 | 3.814122 | 1.127464 |
try:
return self._buildItem(elem, cls, initpath)
except UnknownType:
return None | def _buildItemOrNone(self, elem, cls=None, initpath=None) | Calls :func:`~plexapi.base.PlexObject._buildItem()` but returns
None if elem is an unknown type. | 4.207232 | 2.971714 | 1.415759 |
if isinstance(ekey, int):
ekey = '/library/metadata/%s' % ekey
for elem in self._server.query(ekey):
if self._checkAttrs(elem, **kwargs):
return self._buildItem(elem, cls, ekey)
clsname = cls.__name__ if cls else 'None'
raise NotFound('Unable to find elem: cls=%s, attrs=%s' % (clsname, kwargs)) | def fetchItem(self, ekey, cls=None, **kwargs) | Load the specified key to find and build the first item with the
specified tag and attrs. If no tag or attrs are specified then
the first item in the result set is returned.
Parameters:
ekey (str or int): Path in Plex to fetch items from. If an int is passed
in, the key will be translated to /library/metadata/<key>. This allows
fetching an item only knowing its key-id.
cls (:class:`~plexapi.base.PlexObject`): If you know the class of the
items to be fetched, passing this in will help the parser ensure
it only returns those items. By default we convert the xml elements
with the best guess PlexObjects based on tag and type attrs.
etag (str): Only fetch items with the specified tag.
**kwargs (dict): Optionally add attribute filters on the items to fetch. For
example, passing in viewCount=0 will only return matching items. Filtering
is done before the Python objects are built to help keep things speedy.
Note: Because some attribute names are already used as arguments to this
function, such as 'tag', you may still reference the attr tag byappending
an underscore. For example, passing in _tag='foobar' will return all items
where tag='foobar'. Also Note: Case very much matters when specifying kwargs
-- Optionally, operators can be specified by append it
to the end of the attribute name for more complex lookups. For example,
passing in viewCount__gte=0 will return all items where viewCount >= 0.
Available operations include:
* __contains: Value contains specified arg.
* __endswith: Value ends with specified arg.
* __exact: Value matches specified arg.
* __exists (bool): Value is or is not present in the attrs.
* __gt: Value is greater than specified arg.
* __gte: Value is greater than or equal to specified arg.
* __icontains: Case insensative value contains specified arg.
* __iendswith: Case insensative value ends with specified arg.
* __iexact: Case insensative value matches specified arg.
* __in: Value is in a specified list or tuple.
* __iregex: Case insensative value matches the specified regular expression.
* __istartswith: Case insensative value starts with specified arg.
* __lt: Value is less than specified arg.
* __lte: Value is less than or equal to specified arg.
* __regex: Value matches the specified regular expression.
* __startswith: Value starts with specified arg. | 4.687769 | 3.934572 | 1.191431 |
data = self._server.query(ekey)
items = self.findItems(data, cls, ekey, **kwargs)
librarySectionID = data.attrib.get('librarySectionID')
if librarySectionID:
for item in items:
item.librarySectionID = librarySectionID
return items | def fetchItems(self, ekey, cls=None, **kwargs) | Load the specified key to find and build all items with the specified tag
and attrs. See :func:`~plexapi.base.PlexObject.fetchItem` for more details
on how this is used. | 4.23677 | 3.396014 | 1.247571 |
# filter on cls attrs if specified
if cls and cls.TAG and 'tag' not in kwargs:
kwargs['etag'] = cls.TAG
if cls and cls.TYPE and 'type' not in kwargs:
kwargs['type'] = cls.TYPE
# loop through all data elements to find matches
items = []
for elem in data:
if self._checkAttrs(elem, **kwargs):
item = self._buildItemOrNone(elem, cls, initpath)
if item is not None:
items.append(item)
return items | def findItems(self, data, cls=None, initpath=None, **kwargs) | Load the specified data to find and build all items with the specified tag
and attrs. See :func:`~plexapi.base.PlexObject.fetchItem` for more details
on how this is used. | 3.63256 | 3.69592 | 0.982857 |
for attr in attrs:
value = self.__dict__.get(attr)
if value is not None:
return value | def firstAttr(self, *attrs) | Return the first attribute in attrs that is not None. | 2.900326 | 2.60214 | 1.114593 |
key = key or self._details_key or self.key
if not key:
raise Unsupported('Cannot reload an object not built from a URL.')
self._initpath = key
data = self._server.query(key)
self._loadData(data[0])
return self | def reload(self, key=None) | Reload the data for this object from self.key. | 9.772115 | 8.408197 | 1.162213 |
if 'id' not in kwargs:
kwargs['id'] = self.ratingKey
if 'type' not in kwargs:
kwargs['type'] = utils.searchType(self.type)
part = '/library/sections/%s/all?%s' % (self.librarySectionID,
urlencode(kwargs))
self._server.query(part, method=self._server._session.put) | def edit(self, **kwargs) | Edit an object.
Parameters:
kwargs (dict): Dict of settings to edit.
Example:
{'type': 1,
'id': movie.ratingKey,
'collection[0].tag.tag': 'Super',
'collection.locked': 0} | 5.539909 | 4.060512 | 1.364338 |
if not isinstance(items, list):
items = [items]
value = getattr(self, tag + 's')
existing_cols = [t.tag for t in value if t and remove is False]
d = tag_helper(tag, existing_cols + items, locked, remove)
self.edit(**d)
self.refresh() | def _edit_tags(self, tag, items, locked=True, remove=False) | Helper to edit and refresh a tags.
Parameters:
tag (str): tag name
items (list): list of tags to add
locked (bool): lock this field.
remove (bool): If this is active remove the tags in items. | 5.989997 | 6.408257 | 0.934731 |
key = '%s/refresh' % self.key
self._server.query(key, method=self._server._session.put) | def refresh(self) | Refreshing a Library or individual item causes the metadata for the item to be
refreshed, even if it already has metadata. You can think of refreshing as
"update metadata for the requested item even if it already has some". You should
refresh a Library or individual item if:
* You've changed the Library Metadata Agent.
* You've added "Local Media Assets" (such as artwork, theme music, external
subtitle files, etc.)
* You want to freshen the item posters, summary, etc.
* There's a problem with the poster image that's been downloaded.
* Items are missing posters or other downloaded information. This is possible if
the refresh process is interrupted (the Server is turned off, internet
connection dies, etc). | 10.336423 | 10.953681 | 0.943648 |
if self.TYPE not in ('movie', 'episode', 'track'):
raise Unsupported('Fetching stream URL for %s is unsupported.' % self.TYPE)
mvb = params.get('maxVideoBitrate')
vr = params.get('videoResolution', '')
params = {
'path': self.key,
'offset': params.get('offset', 0),
'copyts': params.get('copyts', 1),
'protocol': params.get('protocol'),
'mediaIndex': params.get('mediaIndex', 0),
'X-Plex-Platform': params.get('platform', 'Chrome'),
'maxVideoBitrate': max(mvb, 64) if mvb else None,
'videoResolution': vr if re.match('^\d+x\d+$', vr) else None
}
# remove None values
params = {k: v for k, v in params.items() if v is not None}
streamtype = 'audio' if self.TYPE in ('track', 'album') else 'video'
# sort the keys since the randomness fucks with my tests..
sorted_params = sorted(params.items(), key=lambda val: val[0])
return self._server.url('/%s/:/transcode/universal/start.m3u8?%s' %
(streamtype, urlencode(sorted_params)), includeToken=True) | def getStreamURL(self, **params) | Returns a stream url that may be used by external applications such as VLC.
Parameters:
**params (dict): optional parameters to manipulate the playback when accessing
the stream. A few known parameters include: maxVideoBitrate, videoResolution
offset, copyts, protocol, mediaIndex, platform.
Raises:
:class:`plexapi.exceptions.Unsupported`: When the item doesn't support fetching a stream URL. | 4.149253 | 3.181002 | 1.304385 |
key = '%s/split' % self.key
return self._server.query(key, method=self._server._session.put) | def split(self) | Split a duplicate. | 11.500339 | 9.532169 | 1.206477 |
key = '%s/unmatch' % self.key
return self._server.query(key, method=self._server._session.put) | def unmatch(self) | Unmatch a media file. | 10.842443 | 7.120789 | 1.522646 |
filepaths = []
locations = [i for i in self.iterParts() if i]
for location in locations:
filename = location.file
if keep_original_name is False:
filename = '%s.%s' % (self._prettyfilename(), location.container)
# So this seems to be a alot slower but allows transcode.
if kwargs:
download_url = self.getStreamURL(**kwargs)
else:
download_url = self._server.url('%s?download=1' % location.key)
filepath = utils.download(download_url, self._server._token, filename=filename,
savepath=savepath, session=self._server._session)
if filepath:
filepaths.append(filepath)
return filepaths | def download(self, savepath=None, keep_original_name=False, **kwargs) | Downloads this items media to the specified location. Returns a list of
filepaths that have been saved to disk.
Parameters:
savepath (str): Title of the track to return.
keep_original_name (bool): Set True to keep the original filename as stored in
the Plex server. False will create a new filename with the format
"<Artist> - <Album> <Track>".
kwargs (dict): If specified, a :func:`~plexapi.audio.Track.getStreamURL()` will
be returned and the additional arguments passed in will be sent to that
function. If kwargs is not specified, the media items will be downloaded
and saved to disk. | 5.643305 | 4.788732 | 1.178455 |
key = '/status/sessions/terminate?sessionId=%s&reason=%s' % (self.session[0].id, quote_plus(reason))
return self._server.query(key) | def stop(self, reason='') | Stop playback for a media item. | 9.998827 | 9.225396 | 1.083837 |
key = '/:/progress?key=%s&identifier=com.plexapp.plugins.library&time=%d&state=%s' % (self.ratingKey,
time, state)
self._server.query(key)
self.reload() | def updateProgress(self, time, state='stopped') | Set the watched progress for this video.
Note that setting the time to 0 will not work.
Use `markWatched` or `markUnwatched` to achieve
that goal.
Parameters:
time (int): milliseconds watched
state (string): state of the video, default 'stopped' | 9.303946 | 8.998857 | 1.033903 |
durationStr = '&duration='
if duration is not None:
durationStr = durationStr + str(duration)
else:
durationStr = durationStr + str(self.duration)
key = '/:/timeline?ratingKey=%s&key=%s&identifier=com.plexapp.plugins.library&time=%d&state=%s%s'
key %= (self.ratingKey, self.key, time, state, durationStr)
self._server.query(key)
self.reload() | def updateTimeline(self, time, state='stopped', duration=None) | Set the timeline progress for this video.
Parameters:
time (int): milliseconds watched
state (string): state of the video, default 'stopped'
duration (int): duration of the item | 4.134237 | 4.817241 | 0.858217 |
key = '/library/sections'
sections = []
for elem in self._server.query(key):
for cls in (MovieSection, ShowSection, MusicSection, PhotoSection):
if elem.attrib.get('type') == cls.TYPE:
section = cls(self._server, elem, key)
self._sectionsByID[section.key] = section
sections.append(section)
return sections | def sections(self) | Returns a list of all media sections in this library. Library sections may be any of
:class:`~plexapi.library.MovieSection`, :class:`~plexapi.library.ShowSection`,
:class:`~plexapi.library.MusicSection`, :class:`~plexapi.library.PhotoSection`. | 4.883887 | 2.934781 | 1.66414 |
for section in self.sections():
if section.title.lower() == title.lower():
return section
raise NotFound('Invalid library section: %s' % title) | def section(self, title=None) | Returns the :class:`~plexapi.library.LibrarySection` that matches the specified title.
Parameters:
title (str): Title of the section to return. | 5.379955 | 4.396319 | 1.223741 |
if not self._sectionsByID or sectionID not in self._sectionsByID:
self.sections()
return self._sectionsByID[sectionID] | def sectionByID(self, sectionID) | Returns the :class:`~plexapi.library.LibrarySection` that matches the specified sectionID.
Parameters:
sectionID (str): ID of the section to return. | 3.69161 | 4.672488 | 0.790074 |
items = []
for section in self.sections():
for item in section.all(**kwargs):
items.append(item)
return items | def all(self, **kwargs) | Returns a list of all media from all library sections.
This may be a very large dataset to retrieve. | 3.430351 | 3.096961 | 1.107651 |
args = {}
if title:
args['title'] = title
if libtype:
args['type'] = utils.searchType(libtype)
for attr, value in kwargs.items():
args[attr] = value
key = '/library/all%s' % utils.joinArgs(args)
return self.fetchItems(key) | def search(self, title=None, libtype=None, **kwargs) | Searching within a library section is much more powerful. It seems certain
attributes on the media objects can be targeted to filter this search down
a bit, but I havent found the documentation for it.
Example: "studio=Comedy%20Central" or "year=1999" "title=Kung Fu" all work. Other items
such as actor=<id> seem to work, but require you already know the id of the actor.
TLDR: This is untested but seems to work. Use library section search when you can. | 3.716791 | 3.565453 | 1.042446 |
try:
return self._server.query('/library/sections/%s' % self.key, method=self._server._session.delete)
except BadRequest: # pragma: no cover
msg = 'Failed to delete library %s' % self.key
msg += 'You may need to allow this permission in your Plex settings.'
log.error(msg)
raise | def delete(self) | Delete a library section. | 6.581513 | 5.660957 | 1.162615 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.