Esempio n. 1
0
 def validate_password(self, field, value):
     if not value:
         return value
     try:
         MyPlexUser.signin(self.fields.username.value, value)
         return value
     except Unauthorized:
         raise ValidationError('Invalid username or password.')
Esempio n. 2
0
 def validate_password(self, field, value):
     if not value:
         return value
     try:
         MyPlexUser.signin(self.fields.username.value, value)
         return value
     except Unauthorized:
         raise ValidationError('Invalid username or password.')
Esempio n. 3
0
def main():
    config = __import__('config')
    user = MyPlexUser.signin(config.username, config.password)

    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
        for resource in user.resources():
            executor.submit(parse_resource, user, resource)

    print('Servers data parsed')
    paris = pytz.timezone('Europe/Paris')
    ordered = reversed(sorted(data, key=lambda x: paris.localize(x.addedAt)))
    print('Media sorted')

    fg = FeedGenerator()
    fg.id('http://satreix.fr/feeds/plex.rss')
    fg.generator('plex-feed')
    fg.title('PLEX feed')
    fg.subtitle('Newly added media content')
    fg.author({'name': 'satreix', 'email': '*****@*****.**'})
    fg.link(href='http://satreix.fr', rel='alternate')
    fg.logo('https://plex.tv/assets/img/googleplus-photo-cb6f717c8cfd8b48df6dbb09aa369198.png')
    fg.link(href='http://satreix.fr/feeds/plex.rss', rel='self')
    fg.language('en')

    for elt in list(ordered)[:50]:
        fe = fg.add_entry()
        fe.id(elt.getStreamUrl())
        fe.title('{} - {}'.format(elt.title, elt.server.friendlyName))
        fe.pubdate(paris.localize(elt.addedAt))
        fe.description(elt.summary, True)

    fg.rss_file('plex.rss', pretty=True)
    print('File written')
Esempio n. 4
0
 def _connect_plex(self):
     """
     Attempts to authenticate to the Plex API and returns the resulting MyPlexUser object
     :return: plexapi.MyPlexUser
     """
     try:
         return MyPlexUser.signin(self.plex_user, self.plex_password)
     except (Unauthorized, BadRequest) as error:
         sys.exit("Failed to authenticate to the Plex API: " + str(error))
Esempio n. 5
0
 def _connect_plex(self):
     """
     Attempts to authenticate to the Plex API and returns the resulting MyPlexUser object
     :return: plexapi.MyPlexUser
     """
     try:
         return MyPlexUser.signin(self.plex_user, self.plex_password)
     except (Unauthorized, BadRequest) as error:
         sys.exit("Failed to authenticate to the Plex API: " + str(error))
Esempio n. 6
0
def fetch_plex_instance(pkmeter, username=None, password=None, host=None):
    username = username or pkmeter.config.get('plexserver', 'username', from_keyring=True)
    password = password or pkmeter.config.get('plexserver', 'password', from_keyring=True)
    host = host or pkmeter.config.get('plexserver', 'host', '')
    if username:
        log.info('Logging into MyPlex with user %s', username)
        user = MyPlexUser.signin(username, password)
        return user.getResource(host).connect()
    log.info('Connecting to Plex host: %s', host)
    return PlexServer(host)
Esempio n. 7
0
def fetch_server(args):
    if args.resource and args.username and args.password:
        log(0, 'Signing in as MyPlex user %s..' % args.username)
        user = MyPlexUser.signin(args.username, args.password)
        log(0, 'Connecting to Plex server %s..' % args.resource)
        return user.resource(args.resource).connect(), user
    elif args.baseurl and args.token:
        log(0, 'Connecting to Plex server %s..' % args.baseurl)
        return server.PlexServer(args.baseurl, args.token), None
    return server.PlexServer(), None
Esempio n. 8
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up the plex platform. """
    from plexapi.myplex import MyPlexUser
    from plexapi.exceptions import BadRequest

    name = config.get('name', '')
    user = config.get('user', '')
    password = config.get('password', '')
    plexuser = MyPlexUser.signin(user, password)
    plexserver = plexuser.getResource(name).connect()
    plex_clients = {}
    plex_sessions = {}

    @util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
    def update_devices():
        """ Updates the devices objects. """
        try:
            devices = plexuser.devices()
        except BadRequest:
            _LOGGER.exception("Error listing plex devices")
            return

        new_plex_clients = []
        for device in devices:
            if (all(x not in ['client', 'player'] for x in device.provides)
                    or 'PlexAPI' == device.product):
                continue

            if device.clientIdentifier not in plex_clients:
                new_client = PlexClient(device, plex_sessions, update_devices,
                                        update_sessions)
                plex_clients[device.clientIdentifier] = new_client
                new_plex_clients.append(new_client)
            else:
                plex_clients[device.clientIdentifier].set_device(device)

        if new_plex_clients:
            add_devices(new_plex_clients)

    @util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
    def update_sessions():
        """ Updates the sessions objects. """
        try:
            sessions = plexserver.sessions()
        except BadRequest:
            _LOGGER.exception("Error listing plex sessions")
            return

        plex_sessions.clear()
        for session in sessions:
            plex_sessions[session.player.machineIdentifier] = session

    update_devices()
    update_sessions()
Esempio n. 9
0
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up the plex platform. """
    from plexapi.myplex import MyPlexUser
    from plexapi.exceptions import BadRequest

    name = config.get('name', '')
    user = config.get('user', '')
    password = config.get('password', '')
    plexuser = MyPlexUser.signin(user, password)
    plexserver = plexuser.getResource(name).connect()
    plex_clients = {}
    plex_sessions = {}

    @util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
    def update_devices():
        """ Updates the devices objects """
        try:
            devices = plexuser.devices()
        except BadRequest:
            _LOGGER.exception("Error listing plex devices")
            return

        new_plex_clients = []
        for device in devices:
            if (all(x not in ['client', 'player'] for x in device.provides)
                    or 'PlexAPI' == device.product):
                continue

            if device.clientIdentifier not in plex_clients:
                new_client = PlexClient(device, plex_sessions, update_devices,
                                        update_sessions)
                plex_clients[device.clientIdentifier] = new_client
                new_plex_clients.append(new_client)
            else:
                plex_clients[device.clientIdentifier].set_device(device)

        if new_plex_clients:
            add_devices(new_plex_clients)

    @util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
    def update_sessions():
        """ Updates the sessions objects """
        try:
            sessions = plexserver.sessions()
        except BadRequest:
            _LOGGER.exception("Error listing plex sessions")
            return

        plex_sessions.clear()
        for session in sessions:
            plex_sessions[session.player.machineIdentifier] = session

    update_devices()
    update_sessions()
Esempio n. 10
0
def fetch_plex_instance(pkmeter, username=None, password=None, host=None):
    username = username or pkmeter.config.get(
        'plexserver', 'username', from_keyring=True)
    password = password or pkmeter.config.get(
        'plexserver', 'password', from_keyring=True)
    host = host or pkmeter.config.get('plexserver', 'host', '')
    if username:
        log.info('Logging into MyPlex with user %s', username)
        user = MyPlexUser.signin(username, password)
        return user.getResource(host).connect()
    log.info('Connecting to Plex host: %s', host)
    return PlexServer(host)
Esempio n. 11
0
    def __init__(self, name, plex_url, plex_user, plex_password, plex_server):
        """Initialize the sensor."""
        self._name = name
        self._state = 0
        self._now_playing = []

        if plex_user and plex_password:
            from plexapi.myplex import MyPlexUser
            user = MyPlexUser.signin(plex_user, plex_password)
            server = plex_server if plex_server else user.resources()[0].name
            self._server = user.getResource(server).connect()
        else:
            from plexapi.server import PlexServer
            self._server = PlexServer(plex_url)

        self.update()
Esempio n. 12
0
    def __init__(self, name, plex_url, plex_user, plex_password, plex_server):
        """Initialize the sensor."""
        self._name = name
        self._state = 0
        self._now_playing = []

        if plex_user and plex_password:
            from plexapi.myplex import MyPlexUser
            user = MyPlexUser.signin(plex_user, plex_password)
            server = plex_server if plex_server else user.resources()[0].name
            self._server = user.getResource(server).connect()
        else:
            from plexapi.server import PlexServer
            self._server = PlexServer(plex_url)

        self.update()
Esempio n. 13
0
def get_server(uri=DEFAULT_URI, username=None, password=None, servername=None):
    """ Get Plex server object for further processing.

    :param uri: Server URI. Expects "http://IP-ADDRESS:PORT", where IP-ADDRESS can be a hostname, and PORT is usually 32400
    :param username: Plex username. Needed if uri fails. User is prompted if parameter is not provided. $PLEX_USERNAME
    :param password: Plex password. Recommended practice is to leave this as None and respond to the prompt. $PLEX_PASSWORD
    :param servername: Server name. User is prompted with a list of servers available to their username if parameter is not provided
    :returns: Server object
    :rtype: plexapi.server.PlexServer
    """

    try:
        return PlexServer(uri)
    except NotFound:
        pass
    if not username and not password:
        info("Could not get server object, maybe you need to be authenticated?")
    username = username if username else os.environ.get("PLEX_USERNAME", None) or prompt("Plex username: "******"PLEX_PASSWORD", None) or getpass("Plex password: "******"Servers: " + ", ".join(a.name for a in user.resources()))
        servername = prompt("Please enter server name (or specify with --servername). If you don't know it, press enter and I'll (very slowly!) search for the correct server: ") or None
    if servername:
        return user.getResource(servername).connect()
    else:
        info("OK, beginning the search process.")
    # necessary to match correct server
    if uri.count(":") >= 2:
        ip = ":".join(urlparse(uri).netloc.split(":")[:-1])
    else:
        ip = urlparse(uri).netloc
    info("Getting IP for {}".format(ip))
    ip = gethostbyname(ip)
    info("Got IP from hostname: {}".format(ip) if ip not in uri else "Searching for {}".format(ip))
    for srv in user.resources():
        try:
            server = srv.connect()
            if ip in server.baseuri:
                info("Found server: {}".format(srv.name))
                return server
        except NotFound:
            info("Couldn't connect to {}".format(srv.name))
    info("Couldn't find server in your user's server list.")
    return 10
Esempio n. 14
0
async def invite_member(member):
    server_id = '503c85f2d47514dbfc3260c2a29ccb9cb113b071'
    account = plex.signin(environ.get('PLEX_EMAIL'), environ.get('PLEX_PASSWORD'))

    headers = plexapi.BASE_HEADERS
    headers['X-Plex-Token'] = account.authenticationToken
    print(account.authenticationToken)
    headers['Content-Type'] = 'application/json'
    data = {
        'server_id': server_id,
        'shared_server': {
            'library_section_ids': [],
            'invited_email': member
        },
        'shared_settings': []
    }

    res = await post('https://plex.tv/api/servers/%s/shared_servers' % server_id, headers=headers, data=dumps(data))
    data = await res.text()
Esempio n. 15
0
async def invite_member(member):
    server_id = '503c85f2d47514dbfc3260c2a29ccb9cb113b071'
    account = plex.signin(environ.get('PLEX_EMAIL'),
                          environ.get('PLEX_PASSWORD'))

    headers = plexapi.BASE_HEADERS
    headers['X-Plex-Token'] = account.authenticationToken
    print(account.authenticationToken)
    headers['Content-Type'] = 'application/json'
    data = {
        'server_id': server_id,
        'shared_server': {
            'library_section_ids': [],
            'invited_email': member
        },
        'shared_settings': []
    }

    res = await post('https://plex.tv/api/servers/%s/shared_servers' %
                     server_id,
                     headers=headers,
                     data=dumps(data))
    data = await res.text()
Esempio n. 16
0
def fetch_server(args):
    if args.server:
        user = MyPlexUser.signin(args.username, args.password)
        return user.getServer(args.server).connect(), user
    return server.PlexServer(), None
Esempio n. 17
0
def fetch_server(args):
    if args.resource:
        user = MyPlexUser.signin(args.username, args.password)
        return user.getResource(args.resource).connect(), user
    return server.PlexServer(), None
Esempio n. 18
0
from __future__ import print_function

import logging

import dotenv
from getenv import env
from plexapi.myplex import MyPlexUser

from alexa import Response

dotenv.read_dotenv()

logger = logging.getLogger(__name__)

APP_ID = 'amzn1.echo-sdk-ams.app.{}'.format(env('ALEXA_APP_ID'))
PLEX_USER = MyPlexUser.signin(env('PMS_USERNAME'), env('PMS_PASSWORD'))
PLEX_SERVER = PLEX_USER.getResource(env('PMS_SERVERNAME')).connect()
PLEX_CLIENT = PLEX_SERVER.client(env('PMS_CLIENT'))


def get_welcome_response():
    '''
    Get the welcome response when waiting for more.
    '''
    return Response(
        'Plex is listening..',
        'Welcome',
        should_end_session=False,
    ).to_dict()

Esempio n. 19
0
from plexapi.myplex import MyPlexUser
import argparse
from sort import Sorter

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Run demo script')
    parser.add_argument('-u', '--username', help='Username for the Plex server.')
    parser.add_argument('-p', '--password', help='Password for the Plex server.')
    args = parser.parse_args()

    user = MyPlexUser.signin(args.username, args.password)

    server_name = user.servers()[0].name
    server = user.getServer(server_name).connect()

    media_center = server.client('420-MediaCenter')
    up = server.library.section('Movies').get('Up')
    avatar = server.library.section('Movies').get('Avatar')

    bobs = server.library.section('TV Shows').search('Bob\'s Burgers')[0]

    sorter = Sorter()
    eps = bobs.episodes()
    sorter.sort(eps)

    queue = media_center.server.createPlayQueue(eps[0])
    queue.addList(eps[1:])
    media_center.playPlayQueue(queue, eps[0])
Esempio n. 20
0
from __future__ import print_function

import logging

import dotenv
from getenv import env
from plexapi.myplex import MyPlexUser

from alexa import Response

dotenv.read_dotenv()

logger = logging.getLogger(__name__)

APP_ID = 'amzn1.echo-sdk-ams.app.{}'.format(env('ALEXA_APP_ID'))
PLEX_USER = MyPlexUser.signin(env('PMS_USERNAME'), env('PMS_PASSWORD'))
PLEX_SERVER = PLEX_USER.getResource(env('PMS_SERVERNAME')).connect()
PLEX_CLIENT = PLEX_SERVER.client(env('PMS_CLIENT'))


def get_welcome_response():
    '''
    Get the welcome response when waiting for more.
    '''
    return Response(
        'Plex is listening..',
        'Welcome',
        should_end_session=False,
    ).to_dict()