Example #1
0
    def connect(self, ssl=None):
        """Connect to the first server.

        Args:
            ssl (None, optional): Use SSL?

        Returns:
            TYPE: Plexserver

        Raises:
            NotFound: Unable to connect to resource: name
        """
        # Try connecting to all known resource connections in parellel, but
        # only return the first server (in order) that provides a response.
        listargs = [[c] for c in self.connections]
        results = utils.threaded(self._connect, listargs)
        # At this point we have a list of result tuples containing (url, token, PlexServer)
        # or (url, token, None) in the case a connection could not be
        # established.
        for url, token, result in results:
            okerr = 'OK' if result else 'ERR'
            log.info('Testing device connection: %s?X-Plex-Token=%s %s', url,
                     token, okerr)
        results = [r[2] for r in results if r and r[2] is not None]
        if not results:
            raise NotFound('Unable to connect to resource: %s' % self.name)
        log.info('Connecting to server: %s?X-Plex-Token=%s',
                 results[0].baseurl, results[0].token)

        return results[0]
Example #2
0
    def connect(self):
        """ Returns a new :class:`~plexapi.client.PlexClient` object. Sometimes there is more than
            one address specified for a server or client. After trying to connect to all
            available addresses for this resource and assuming at least one connection was
            successful, the PlexClient object is built and returned.

            Raises:
                :class:`~plexapi.exceptions.NotFound`: When unable to connect to any addresses for this device.
        """
        # Try connecting to all known resource connections in parellel, but
        # only return the first server (in order) that provides a response.
        listargs = [[c] for c in self.connections]
        results = utils.threaded(self._connect, listargs)
        # At this point we have a list of result tuples containing (url, token, PlexServer)
        # or (url, token, None) in the case a connection could not be
        # established.
        for url, token, result in results:
            okerr = 'OK' if result else 'ERR'
            log.info('Testing device connection: %s?X-Plex-Token=%s %s', url,
                     token, okerr)
        results = [r[2] for r in results if r and r[2] is not None]
        if not results:
            raise NotFound('Unable to connect to resource: %s' % self.name)
        log.info('Connecting to server: %s?X-Plex-Token=%s',
                 results[0].baseurl, results[0].token)
        return results[0]
Example #3
0
    def connect(self, ssl=None, timeout=None):
        """ Returns a new :class:`~server.PlexServer` or :class:`~client.PlexClient` object.
            Often times there is more than one address specified for a server or client.
            This function will prioritize local connections before remote and HTTPS before HTTP.
            After trying to connect to all available addresses for this resource and
            assuming at least one connection was successful, the PlexServer object is built and returned.

            Parameters:
                ssl (optional): Set True to only connect to HTTPS connections. Set False to
                    only connect to HTTP connections. Set None (default) to connect to any
                    HTTP or HTTPS connection.

            Raises:
                :class:`~plexapi.exceptions.NotFound`: When unable to connect to any addresses for this resource.
        """
        # Sort connections from (https, local) to (http, remote)
        # Only check non-local connections unless we own the resource
        connections = sorted(self.connections, key=lambda c: c.local, reverse=True)
        owned_or_unowned_non_local = lambda x: self.owned or (not self.owned and not x.local)
        https = [c.uri for c in connections if owned_or_unowned_non_local(c)]
        http = [c.httpuri for c in connections if owned_or_unowned_non_local(c)]
        cls = PlexServer if 'server' in self.provides else PlexClient
        # Force ssl, no ssl, or any (default)
        if ssl is True: connections = https
        elif ssl is False: connections = http
        else: connections = https + http
        # Try connecting to all known resource connections in parellel, but
        # only return the first server (in order) that provides a response.
        listargs = [[cls, url, self.accessToken, timeout] for url in connections]
        log.info('Testing %s resource connections..', len(listargs))
        results = utils.threaded(_connect, listargs)
        return _chooseConnection('Resource', self.name, results)
Example #4
0
    def connect(self, ssl=None, timeout=None):
        """ Returns a new :class:`~server.PlexServer` or :class:`~client.PlexClient` object.
            Often times there is more than one address specified for a server or client.
            This function will prioritize local connections before remote and HTTPS before HTTP.
            After trying to connect to all available addresses for this resource and
            assuming at least one connection was successful, the PlexServer object is built and returned.

            Parameters:
                ssl (optional): Set True to only connect to HTTPS connections. Set False to
                    only connect to HTTP connections. Set None (default) to connect to any
                    HTTP or HTTPS connection.

            Raises:
                :class:`~plexapi.exceptions.NotFound`: When unable to connect to any addresses for this resource.
        """
        # Sort connections from (https, local) to (http, remote)
        # Only check non-local connections unless we own the resource
        connections = sorted(self.connections, key=lambda c: c.local, reverse=True)
        owned_or_unowned_non_local = lambda x: self.owned or (not self.owned and not x.local)
        https = [c.uri for c in connections if owned_or_unowned_non_local(c)]
        http = [c.httpuri for c in connections if owned_or_unowned_non_local(c)]
        cls = PlexServer if 'server' in self.provides else PlexClient
        # Force ssl, no ssl, or any (default)
        if ssl is True: connections = https
        elif ssl is False: connections = http
        else: connections = https + http
        # Try connecting to all known resource connections in parellel, but
        # only return the first server (in order) that provides a response.
        listargs = [[cls, url, self.accessToken, timeout] for url in connections]
        log.info('Testing %s resource connections..', len(listargs))
        results = utils.threaded(_connect, listargs)
        return _chooseConnection('Resource', self.name, results)
Example #5
0
def test_utils_threaded():
    def _squared(num, results, i):
        time.sleep(0.5)
        results[i] = num * num
    starttime = time.time()
    results = utils.threaded(_squared, [[1], [2], [3], [4], [5]])
    assert results == [1, 4, 9, 16, 25]
    assert (time.time() - starttime) < 1
Example #6
0
def _test_servers(servers):
    seen = set()
    print('\nServer Clients:')
    listargs = [[PlexServer, s, t, 5] for s, t in servers.items()]
    results = utils.threaded(_connect, listargs)
    for url, token, plex, runtime in results:
        clients = plex.clients() if plex else []
        if plex and clients:
            for c in plex.clients():
                if c._baseurl not in seen:
                    print(FORMAT2 % (c.product, c.title, token, c._baseurl,
                                     plex.friendlyName))
                    seen.add(c._baseurl)
Example #7
0
    def connect(self, timeout=None):
        """ Returns a new :class:`~plexapi.client.PlexClient` object. Sometimes there is more than
            one address specified for a server or client. After trying to connect to all available
            addresses for this client and assuming at least one connection was successful, the
            PlexClient object is built and returned.

            Raises:
                :class:`~plexapi.exceptions.NotFound`: When unable to connect to any addresses for this device.
        """
        listargs = [[PlexClient, url, self.token, timeout]
                    for url in self.connections]
        log.info('Testing %s device connections..', len(listargs))
        results = utils.threaded(_connect, listargs)
        _chooseConnection('Device', self.name, results)
Example #8
0
    def connect(self, timeout=None):
        """ Returns a new :class:`~plexapi.client.PlexClient` or :class:`~plexapi.server.PlexServer`
            Sometimes there is more than one address specified for a server or client.
            After trying to connect to all available addresses for this client and assuming
            at least one connection was successful, the PlexClient object is built and returned.

            Raises:
                :class:`~plexapi.exceptions.NotFound`: When unable to connect to any addresses for this device.
        """
        cls = PlexServer if 'server' in self.provides else PlexClient
        listargs = [[cls, url, self.token, timeout] for url in self.connections]
        log.info('Testing %s device connections..', len(listargs))
        results = utils.threaded(_connect, listargs)
        return _chooseConnection('Device', self.name, results)
def _test_servers(servers):
    items, seen = [], set()
    print('Finding Plex clients..')
    listargs = [[PlexServer, s, t, 5] for s,t in servers.items()]
    results = utils.threaded(_connect, listargs)
    for url, token, plex, runtime in results:
        clients = plex.clients() if plex else []
        if plex and clients:
            for c in plex.clients():
                if c._baseurl not in seen:
                    extras = [plex.friendlyName] + c.protocolCapabilities
                    items.append(FORMAT % ('Client', '--', c.product, c.title, token, c._baseurl, ','.join(extras)))
                    seen.add(c._baseurl)
    return items
Example #10
0
 def connect(self, ssl=None):
     # Try connecting to all known resource connections in parellel, but
     # only return the first server (in order) that provides a response.
     listargs = [[c] for c in self.connections]
     results = utils.threaded(self._connect, listargs)
     # At this point we have a list of result tuples containing (url, token, PlexServer)
     # or (url, token, None) in the case a connection could not be established.
     for url, token, result in results:
         okerr = 'OK' if result else 'ERR'
         log.info('Testing device connection: %s?X-Plex-Token=%s %s', url, token, okerr)
     results = list(filter(None, [r[2] for r in results if r]))
     if not results:
         raise NotFound('Unable to connect to resource: %s' % self.name)
     log.info('Connecting to server: %s?X-Plex-Token=%s', results[0].baseurl, results[0].token)
     return results[0]
Example #11
0
def _test_servers(servers):
    items, seen = [], set()
    print('Finding Plex clients..')
    listargs = [[PlexServer, s, t, 5] for s, t in servers.items()]
    results = utils.threaded(_connect, listargs)
    for url, token, plex, runtime in results:
        clients = plex.clients() if plex else []
        if plex and clients:
            for c in plex.clients():
                if c._baseurl not in seen:
                    extras = [plex.friendlyName] + c.protocolCapabilities
                    items.append(FORMAT %
                                 ('Client', '--', c.product, c.title, token,
                                  c._baseurl, ','.join(extras)))
                    seen.add(c._baseurl)
    return items
Example #12
0
    def connect(self, ssl=None):
        """ Returns a new :class:`~server.PlexServer` object. Often times there is more than
            one address specified for a server or client. This function will prioritize local
            connections before remote and HTTPS before HTTP. After trying to connect to all
            available addresses for this resource and assuming at least one connection was
            successful, the PlexServer object is built and returned.

            Parameters:
                ssl (optional): Set True to only connect to HTTPS connections. Set False to
                    only connect to HTTP connections. Set None (default) to connect to any
                    HTTP or HTTPS connection.

            Raises:
                :class:`~plexapi.exceptions.NotFound`: When unable to connect to any addresses for this resource.
        """
        # Sort connections from (https, local) to (http, remote)
        # Only check non-local connections unless we own the resource
        forcelocal = lambda c: self.owned or c.local
        connections = sorted(self.connections,
                             key=lambda c: c.local,
                             reverse=True)
        https = [c.uri for c in self.connections if forcelocal(c)]
        http = [c.httpuri for c in self.connections if forcelocal(c)]
        # Force ssl, no ssl, or any (default)
        if ssl is True: connections = https
        elif ssl is False: connections = http
        else: connections = https + http
        # Try connecting to all known resource connections in parellel, but
        # only return the first server (in order) that provides a response.
        listargs = [[c] for c in connections]
        results = utils.threaded(self._connect, listargs)
        # At this point we have a list of result tuples containing (url, token, PlexServer)
        # or (url, token, None) in the case a connection could not be
        # established.
        for url, token, result in results:
            okerr = 'OK' if result else 'ERR'
            log.info('Testing resource connection: %s?X-Plex-Token=%s %s', url,
                     token, okerr)
        results = [r[2] for r in results if r and r[2] is not None]
        if not results:
            raise NotFound('Unable to connect to resource: %s' % self.name)
        log.info('Connecting to server: %s?X-Plex-Token=%s',
                 results[0].baseurl, results[0].token)
        return results[0]
Example #13
0
    def connect(self, ssl=None):
        """Connect.

        Args:
            ssl (None, optional): Use ssl.

        Returns:
            class: Plexserver

        Raises:
            NotFound: Unable to connect to resource: name
        """

        # Sort connections from (https, local) to (http, remote)
        # Only check non-local connections unless we own the resource
        forcelocal = lambda c: self.owned or c.local
        connections = sorted(self.connections,
                             key=lambda c: c.local,
                             reverse=True)
        https = [c.uri for c in self.connections if forcelocal(c)]
        http = [c.httpuri for c in self.connections if forcelocal(c)]
        connections = https + http
        # Try connecting to all known resource connections in parellel, but
        # only return the first server (in order) that provides a response.
        listargs = [[c] for c in connections]
        results = utils.threaded(self._connect, listargs)
        # At this point we have a list of result tuples containing (url, token, PlexServer)
        # or (url, token, None) in the case a connection could not be
        # established.
        for url, token, result in results:
            okerr = 'OK' if result else 'ERR'
            log.info('Testing resource connection: %s?X-Plex-Token=%s %s', url,
                     token, okerr)

        results = [r[2] for r in results if r and r is not None]
        if not results:
            raise NotFound('Unable to connect to resource: %s' % self.name)
        log.info('Connecting to server: %s?X-Plex-Token=%s',
                 results[0].baseurl, results[0].token)

        return results[0]
Example #14
0
 def connect(self, ssl=None):
     # Sort connections from (https, local) to (http, remote)
     # Only check non-local connections unless we own the resource
     forcelocal = lambda c: self.owned or c.local
     connections = sorted(self.connections, key=lambda c:c.local, reverse=True)
     https = [c.uri for c in self.connections if forcelocal(c)]
     http = [c.httpuri for c in self.connections if forcelocal(c)]
     connections = https + http
     # Try connecting to all known resource connections in parellel, but
     # only return the first server (in order) that provides a response.
     listargs = [[c] for c in connections]
     results = utils.threaded(self._connect, listargs)
     # At this point we have a list of result tuples containing (url, token, PlexServer)
     # or (url, token, None) in the case a connection could not be established.
     for url, token, result in results:
         okerr = 'OK' if result else 'ERR'
         log.info('Testing resource connection: %s?X-Plex-Token=%s %s', url, token, okerr)
     results = list(filter(None, [r[2] for r in results if r]))
     if not results:
         raise NotFound('Unable to connect to resource: %s' % self.name)
     log.info('Connecting to server: %s?X-Plex-Token=%s', results[0].baseurl, results[0].token)
     return results[0]
Example #15
0
def sync_tv(masterLibrary, master, slave, library):
    # key = '/library/sections/{}/all?type=4&viewCount>=0'.format(masterLibrary.key)
    # fullContent = masterLibrary.fetchItems(key)

    fullContent = masterLibrary.searchEpisodes(unwatched=False)
    syncResult = []
    masterWatchedGUIDs = []

    with tqdm(total=len(fullContent)) as pbar:
        pbar.write('Compiling list of watched content on master...')
        for content in fullContent:
            masterWatchedGUIDs.append([content, pbar])

        l = masterWatchedGUIDs
        n = 50
        threadWork = [l[i:i + n] for i in range(0, len(l), n)]
        threaded(updateGuid, threadWork)
        # pool = ThreadPool(8)
        # syncResult = pool.map(updateGuid, masterWatchedGUIDs)
        # pool.close()
        # pool.join()

    print(vars(syncResult))
    return 0

    slaveWatchedContent = slave.library.section(library).searchEpisodes(
        unwatched=False)
    slaveWatchedGUIDs = []
    slaveUnwatched = {}

    with tqdm(total=len(slaveWatchedContent)) as pbar:
        pbar.write('Compiling list of watched content on slave...')
        for content in slaveWatchedContent:
            slaveWatchedGUIDs.append(formatString)
            pbar.update(1)

    s = set(slaveWatchedGUIDs)
    updateContentGUIDs = [x for x in masterWatchedGUIDs if x not in s]

    if len(updateContentGUIDs) > 0:
        slaveUnwatchedContent = slave.library.section(library).search(
            unwatched=True)
        for content in slaveUnwatchedContent:
            slaveUnwatched[content.guid] = content
        toMarkWatched = []
        with tqdm(total=len(updateContentGUIDs)) as pbar:
            for guid in updateContentGUIDs:
                slaveContent = slaveUnwatched.get(guid)
                if (slaveContent is None):
                    if verbose:
                        pbar.write('{} not found on {}!'.format(
                            guid, slave.friendlyName))
                    pbar.update(1)
                    continue
                if slaveContent.viewCount == 0:
                    if verbose or dryrun:
                        pbar.write('{}:{} - {} is unwatched on {}!'.format(
                            slaveContent.grandparentTitle,
                            slaveContent.seasonEpisode, slaveContent.title,
                            slave.friendlyName))
                    if not dryrun:
                        toMarkWatched.append([slaveContent, pbar])
                        # if verbose:
                        #     pbar.write('{} marked as watched on {}.'.format(title,slave.friendlyName))
                        #     pbar.write('--------')
                    # syncedCount += 1
            if verbose:
                pbar.write('Batch processing unwatched files...')
            # syncResult = threaded(markWatched, toMarkWatched)
            if len(toMarkWatched) > 0:
                pool = ThreadPool()
                syncResult = pool.map(markWatched, toMarkWatched)
                pool.close()
                pool.join()
    return sum(syncResult)