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, respo...
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 send...
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._l...
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 ...
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 .se...
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....
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. ...
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", ...
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 re...
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...
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(...
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. Para...
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) threa...
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 t...
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)...
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: ...
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). satu...
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(save...
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, defa...
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) ...
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...
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 ...
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 = inp...
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 serve...
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_...
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 ...
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 ...
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.at...
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.enumV...
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(bo...
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 j...
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 po...
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 por...
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 t...
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 +...
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. I...
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. ...
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 transcod...
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('librarySecti...
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....
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 ...
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-...
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().spl...
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 ...
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.languageCo...
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...
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],...
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 ...
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: :c...
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: ...
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('stream...
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('Una...
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 ...
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...
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)) s...
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: ...
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': pa...
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,...
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...
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 ...
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' ke...
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) ...
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...
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.' ...
def delete(self)
Delete a library section.
6.581513
5.660957
1.162615