async def connect(self) -> None:
        while True:
            try:
                if self.token:
                    self.plex_account = MyPlexAccount(self.username,
                                                      token=self.token)
                else:
                    self.plex_account = MyPlexAccount(self.username,
                                                      self.password)

                log.info(f'Logged into Plex as {self.username}.')

                self.plex_server = self.plex_account.resource(
                    self.server).connect()
                log.info(f'Connected to Plex {self.server} server.')
                break

            except Exception as err:
                log.error(f'Failed to connect to Plex: {err}')
                log.debug('Attempting reconnection in 10 seconds..')

                await asyncio.sleep(10)

        log.debug('Attempting to open IPC connection to Discord..')
        await super().connect()
        log.info('IPC connection established to Discord.')

        self.connected.set()
예제 #2
0
파일: utils.py 프로젝트: Tautulli/Tautulli
def getMyPlexAccount(opts=None):  # pragma: no cover
    """ 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.
    """
    from plexapi import CONFIG
    from plexapi.myplex import MyPlexAccount
    # 1. Check command-line options
    if opts and opts.username and opts.password:
        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)
    config_token = CONFIG.get('auth.server_token')
    if config_token:
        print('Authenticating with Plex.tv with token')
        return MyPlexAccount(token=config_token)
    # 3. Prompt for username and password on the command line
    username = input('What is your plex.tv username: '******'What is your plex.tv password: '******'Authenticating with Plex.tv as %s..' % username)
    return MyPlexAccount(username, password)
예제 #3
0
	def connect(self, server, username, password='', token=''):
		self.logger.info(f'Connecting to the Plex Server {server} with username {username}.')
		connection_attempts_left = self.maximum_connection_attempts
		while connection_attempts_left > 0:
			time.sleep(1)  # important. Otherwise, the above print statement can be flushed after
			if (not password) & (not token):
				password = getpass.getpass()
			try:
				if (password):
					self.account = MyPlexAccount(username=username, password=password)
				elif (token):
					self.account = MyPlexAccount(username=username, token=token)
				break
			except NotFound:
				print(f'Username {username}, password or token wrong for server {server}.')
				password = ''
				connection_attempts_left -= 1
			except BadRequest as error:
				self.logger.warning('Failed to connect: {}'.format(error))
				connection_attempts_left -= 1
		if connection_attempts_left == 0 or self.account is None:
			self.logger.error('Exiting after {} failed attempts ...'.format(self.maximum_connection_attempts))
			exit(1)

		self.logger.info('Connecting to remote player {} on the server {}'.format(self.name(), server))
		try:
			self.plex_api_connection = self.account.resource(server).connect(timeout=5)
			self.logger.info('Successfully connected')
		except NotFound:
			# This also happens if the user is not the owner of the server
			self.logger.error('Error: Unable to connect')
			exit(1)

		self.logger.info('Looking for music libraries')
		music_libraries = {
			section.key:
				section for section
				in self.plex_api_connection.library.sections()
				if section.type == 'artist'}

		if len(music_libraries) == 0:
			self.logger.error('No music library found')
			exit(1)
		elif len(music_libraries) == 1:
			self.music_library = list(music_libraries.values())[0]
			self.logger.debug('Found 1 music library')
		else:
			print('Found multiple music libraries:')
			for key, library in music_libraries.items():
				print('\t[{}]: {}'.format(key, library.title))

			choice = input('Select the library to sync with: ')
			self.music_library = music_libraries[int(choice)]
예제 #4
0
def get_plex():
    if settings.PLEX_CONFIG.get('baseurl'):
        return PlexServer(**settings.PLEX_CONFIG)
    elif settings.MYPLEX_CONFIG.get('token'):
        account = MyPlexAccount(settings.MYPLEX_CONFIG.get('token'))
    elif settings.MYPLEX_CONFIG.get('username'):
        account = MyPlexAccount(settings.MYPLEX_CONFIG.get('username'),
                                settings.MYPLEX_CONFIG.get('password'))

    plex = account.resource(settings.MYPLEX_CONFIG.get('server')).connect()
    logger.debug("Using Plex account auth token {}".format(
        account.authenticationToken))

    return plex
예제 #5
0
 def __init__(self, settings):
     self.__settings = settings
     try:
         account = MyPlexAccount(settings.plex["user"], settings.plex["password"])
         self.__plex = account.resource(settings.plex["servername"]).connect()
     except:
         print("Could not connect to Plex API")
예제 #6
0
def signInOnline():
    """ Returns a :class:`~plexapi.server.PlexServer` by connecting online
        through MyPlex.
    """
    # Attempt to sign on
    isSignedIn = False
    while not isSignedIn:

        # Get login info from user
        username = input("Plex username: "******"Plex password: "******"Plex server name: ")

        # Sign in via MyPlex
        print("Signing in (this may take awhile)...")
        try:
            account = MyPlexAccount(username, password)
            plexServer = account.resource(serverName).connect()
            isSignedIn = True
        except BadRequest:
            print("Error: Login failed. Are your credentials correct?")
        except NotFound:
            print("Error: Server '%s' not found linked to your account." %
                  serverName)
    return plexServer
예제 #7
0
def build_config():
    if not os.path.exists(config_path):
        print("Dumping default config to: %s" % config_path)

        configs = dict(url='', token='', auto_delete=False)

        # Get URL
        configs['url'] = input("Plex Server URL: ")

        # Get Credentials for plex.tv
        user = input("Plex Username: ")
        password = getpass('Plex Password: '******'token'] = account.authenticationToken

        with open(config_path, 'w') as fp:
            json.dump(prefilled_default_config(configs),
                      fp,
                      sort_keys=True,
                      indent=2)

        return True

    else:
        return False
예제 #8
0
def cli(debug, username, password, servername, url, token, config):
    """ Entry point for the CLI."""
    global PMS

    # click.echo('debug %s' % debug)
    # click.echo('username %s' % username)
    # click.echo('password %s' % password)
    # click.echo('servername %s' % servername)
    # click.echo('url %s' % url)
    # click.echo('token %s' % token)
    # click.echo('config %s' % config)

    if debug:
        LOG.setLevel(logging.DEBUG)
    else:
        LOG.setLevel(logging.INFO)

    if username and password and servername:
        from plexapi.myplex import MyPlexAccount

        acc = MyPlexAccount(username, password)
        PMS = acc.resource(servername).connect()

    elif url and token:
        PMS = PlexServer(url, token)
    else:
        PMS = PlexServer('', '')  # plexapi will pull config file..

    # CONFIG is unused atm.
    click.echo('Watching for media on %s' % PMS.friendlyName)
def get_plex_server():

    PlexMethod = MyPlexAccount
    if fpssConfig['plexmethod'] == 'MyPlexAccount':
        # Use the My Plex Account method of connecting
        #account = MyPlexAccount(fpssConfig['plexusername'], fpssConfig['plexpassword'], token=fpssConfig['plexauthtoken'], timeout=5)
        account = MyPlexAccount(fpssConfig['plexusername'],
                                fpssConfig['plexpassword'],
                                timeout=5)
        cons = account.resource(fpssConfig['plexserver']).connections
        print("Connections available:", len(cons), "Access Token:",
              account.resource(fpssConfig['plexserver']).accessToken)

        for r in range(0, len(cons)):
            conr = cons[r]
            #print(dir(conr))
            print(conr.address, conr.httpuri, conr.protocol, conr.key,
                  conr.uri, conr.local)
            #print(cons[r])
            #exit()

        try:
            pms = account.resource(fpssConfig['plexserver']).connect()
        except plexapi.exceptions.NotFound:
            print("Could not connect to plex")
            exit(-1)

    else:

        baseurl = fpssConfig['plexmethod']
        pms = PlexServer(baseurl, fpssConfig['plexauthtoken'])

    return pms
예제 #10
0
 def __init__(self, opts):
     self.opts = opts                                            # command line options
     self.clsnames = [c for c in opts.clsnames.split(',') if c]  # list of clsnames to report (blank=all)
     self.account = MyPlexAccount()                              # MyPlexAccount instance
     self.plex = PlexServer()                                    # PlexServer instance
     self.total = 0                                              # Total objects parsed
     self.attrs = defaultdict(dict)                              # Attrs result set
예제 #11
0
def _list_devices(account, servers):
    print('\nDevices:')
    for d in MyPlexAccount(username, password).devices():
        if d.token:
            for conn in d.connections:
                print(FORMAT % (d.product, d.name, d.token, conn))
                servers[conn] = d.token
예제 #12
0
def inviteFriend():
    request_data = request.get_json()
    username = request_data['username']
    password = request_data['password']
    friend_username = request_data['friendusername']
    print(username)
    print(password)
    print(friend_username)
    try:
        a = MyPlexAccount(username=f"{username}",
                          password=f"{password}",
                          token=token,
                          session=None,
                          timeout=None)
        a.inviteFriend(user=f"{friend_username}",
                       server=plex,
                       sections=None,
                       allowSync=False,
                       allowCameraUpload=False,
                       allowChannels=False,
                       filterMovies=None,
                       filterTelevision=None,
                       filterMusic=None)
        return "invited successfully"
    except:
        return "you aleady requested or username is wrong"
예제 #13
0
파일: plex.py 프로젝트: Ratxi/hoodex
    def _connect_server(self, user, password, server):
        print("Connecting to plex server {server} with user: {user}...".format(
            server=server, user=user))

        self.account = MyPlexAccount(user, password)
        self.server = self.account.resource(server).connect()
        self.token = self.account.resource(server).accessToken
예제 #14
0
def authenticate():
    method = plex_settings['authentication_method'].lower()

    try:
        # Direct connection
        if method == 'direct':
            base_url = plex_settings['base_url']
            token = plex_settings['token']
            plex = PlexServer(base_url, token)
        # Myplex connection
        elif method == 'myplex':
            plex_server = plex_settings['server']
            plex_user = plex_settings['myplex_user']
            plex_password = plex_settings['myplex_password']
            account = MyPlexAccount(plex_user, plex_password)
            plex = account.resource(plex_server).connect()
        else:
            logger.critical(
                '[PLEX] Failed to authenticate due to invalid settings or authentication info, exiting...')
            sys.exit()
        return plex
    except Exception as e:
        logger.error(
            'Unable to authenticate to Plex Media Server, traceback: %s' %
            (e))
        return None
예제 #15
0
    def __init__(self, name, plex_url, plex_user, plex_password, plex_server,
                 plex_token):
        """Initialize the sensor."""
        from plexapi.myplex import MyPlexAccount
        from plexapi.server import PlexServer

        self._name = name
        self._state = 0
        self._media_attrs = {}
        self._sessions = None
        self._session = None
        self._sessioncount = 0
        self._session_type = None
        self._plex_url = plex_url
        self._plex_token = plex_token
        """Set all Media Items to None."""
        # General
        self._media_content_type = None
        self._media_title = None
        # TV Show
        self._media_episode = None
        self._media_season = None
        self._media_series_title = None

        if plex_token:
            self._server = PlexServer(plex_url, plex_token)
        elif plex_user and plex_password:
            user = MyPlexAccount(plex_user, plex_password)
            server = plex_server if plex_server else user.resources()[0].name
            self._server = user.resource(server).connect()
        else:
            self._server = PlexServer(plex_url)
예제 #16
0
def get_pms(url=None,
            token=None,
            username=None,
            password=None,
            servername=None,
            verify_ssl=None):  # pragma: no cover

    url = url or CONFIG['server'].get('url')
    token = token or CONFIG['server'].get('token')
    verify_ssl = verify_ssl or CONFIG['server'].get('verify_ssl', False)
    servername = servername or CONFIG['server'].get('name')

    if url and token:
        url = url.rstrip('/')
        sess = requests.Session()
        if not verify_ssl:
            # Disable the urllib3 warning as the user
            # has choosen to not verify the http request.
            # why the f**k isnt this default?
            requests.packages.urllib3.disable_warnings()
            sess.verify = False
        PMS = PlexServer(url, token, sess)

    elif username and password and servername:
        acc = MyPlexAccount(username, password)
        PMS = acc.resource(servername).connect()

    assert PMS is not None, 'You need to add a url and token or username password and servername'

    LOG.debug('Getting server %s', PMS.friendlyName)

    return PMS
예제 #17
0
def get_pms(url=None,
            token=None,
            username=None,
            password=None,
            servername=None,
            verify_ssl=None):
    from plexapi.myplex import MyPlexAccount
    from plexapi.server import PlexServer

    url = url or CONFIG.get('url')
    token = token or CONFIG.get('token')
    verify_ssl = verify_ssl or CONFIG.get('verify_ssl', False)

    if url and token:
        sess = requests.Session()
        if not verify_ssl:
            sess.verify = False
        PMS = PlexServer(url, token, sess)

    elif username and password and servername:
        acc = MyPlexAccount(username, password)
        PMS = acc.resource(servername).connect()

    LOG.debug('Getting server %s', PMS.friendlyName)

    return PMS
예제 #18
0
def get_plex_account(opts):
    """ Authenitcate with Plex using the command line options. """
    if not opts.unclaimed:
        if opts.token:
            return MyPlexAccount(token=opts.token)
        return plexapi.utils.getMyPlexAccount(opts)
    return None
예제 #19
0
def connect_to_plex(username, password, server_name):
    """Connect to Plex"""

    account = MyPlexAccount(username, password)
    plex = account.resource(server_name).connect()

    return plex
예제 #20
0
def dub(username: str = username,
        password: str = password,
        servername: str = servername,
        show: str = show,
        lang: str = lang):
    """Set the default dubs for every episode of the show."""
    account = MyPlexAccount(username, password)
    plex: PlexServer = account.resource(servername).connect()

    try:
        not_found_dubs_count = 0
        for part in _get_media_parts(plex, show):
            is_found = False
            for audio in part.audioStreams():
                if audio.languageCode == lang:
                    part.setDefaultAudioStream(audio)
                    is_found = True
                    break
            if not is_found:
                not_found_dubs_count += 1
                if GLOBAL_OPTIONS['verbose']:
                    typer.echo(
                        f'Audio for "{lang}" not found for file: {part.file}',
                        err=True)

        if not_found_dubs_count != 0:
            typer.echo(f'{not_found_dubs_count} dubs were not found', err=True)
            raise typer.Abort()
    except NotFound as e:
        typer.echo("Show, media item, or device is not found.", err=True)
        typer.echo(e, err=True)
        raise typer.Abort()

    typer.echo('Success!')
예제 #21
0
def main():
    args = get_args()
    if args.debug:
        logger.setLevel(logging.DEBUG)
    if args.account:
        # ## Connect via Account
        account = MyPlexAccount(args.username, args.password)
        plex = account.resource(args.resource).connect()
    elif args.server:
        # ## Connect via Direct URL
        baseurl = args.baseurl
        token = args.token
        plex = PlexServer(baseurl, token)
    else:
        exit(1)

    all_shows = plex.library.section('TV Shows')
    # shows = get_unwatched_shows(all_shows.all())
    episodes = get_random_episodes(all_shows, n=args.number)
    for episode in episodes:
        season_episode = episode.seasonEpisode
        # skipped = skipped_missing(all_shows.get(title=episode.grandparentTitle), episode)

    # playlist = Playlist(plex, )
    plex.playlist(title=args.name).delete()
    Playlist.create(server=plex, title=args.name, items=episodes)
예제 #22
0
    def __init__(self):
        MycroftSkill.__init__(self)
        # List of services. Names in config must match API names.
        self.services = self.settings.get('services').lower().split(',')

        # Some titles are only available in certain countries
        self.country = self.settings.get('country').lower()

        # RapidAPI keys for Utelly API and IMDB API
        self.header_apiKey = self.settings.get('x-rapidapi-key')

        # Plex info
        self.plexAccount = MyPlexAccount(self.settings.get('plexUsername'), self.settings.get('plexPassword'))
        self.plexServers = []

        # Service host info - from Rapid API
        self.header_utellyHost = self.settings.get('utellyHost')
        self.header_imdbHost = self.settings.get('imdbHost')

        # URLs for each service - from Rapid API
        self.utellyUrl = f'https://{self.header_utellyHost}/idlookup'
        self.imdbUrl = f'https://{self.header_imdbHost}/title/find'

        # If this is set to true, then the skill will offer to download a title if it can't be found.
        # Is there a way for this skill to just check if the other skill is loaded?
        self.couchPotato = self.settings.get('couchPotato')
예제 #23
0
def get_pms(url=None,
            token=None,
            username=None,
            password=None,
            servername=None,
            verify_ssl=None):  # pragma: no cover

    url = url or CONFIG['server'].get('url')
    token = token or CONFIG['server'].get('token')
    verify_ssl = verify_ssl or CONFIG['server'].get('verify_ssl', False)
    servername = servername or CONFIG['server'].get('name')

    if url and token:
        sess = requests.Session()
        if not verify_ssl:
            sess.verify = False
        PMS = PlexServer(url, token, sess)

    elif username and password and servername:
        acc = MyPlexAccount(username, password)
        PMS = acc.resource(servername).connect()

    assert PMS is not None, 'You need to add a url and token or username password and servername'

    LOG.debug('Getting server %s', PMS.friendlyName)

    return PMS
예제 #24
0
    def __init__(self, name, plex_url, plex_user, plex_password, plex_server,
                 plex_token, verify_ssl):
        """Initialize the sensor."""
        from plexapi.myplex import MyPlexAccount
        from plexapi.server import PlexServer
        from requests import Session

        self._name = name
        self._state = 0
        self._now_playing = []

        cert_session = None
        if not verify_ssl:
            _LOGGER.info("Ignoring SSL verification")
            cert_session = Session()
            cert_session.verify = False

        if plex_token:
            self._server = PlexServer(plex_url, plex_token, cert_session)
        elif plex_user and plex_password:
            user = MyPlexAccount(plex_user, plex_password)
            server = plex_server if plex_server else user.resources()[0].name
            self._server = user.resource(server).connect()
        else:
            self._server = PlexServer(plex_url, None, cert_session)
예제 #25
0
def build_config():
    if not os.path.exists(config_path):
        print("Dumping default config to: %s" % config_path)

        configs = dict(url='', token='', auto_delete=False)

        # Get URL
        configs['url'] = input("Plex Server URL: ")

        # Get Credentials for plex.tv
        user = input("Plex Username: "******"Auto Delete duplicates? [y/n]: ")
            if auto_del.strip().lower() == 'y':
                configs['auto_delete'] = True
            elif auto_del.strip().lower() == 'n':
                configs['auto_delete'] = False

        account = MyPlexAccount(user, password)
        configs['token'] = account.authenticationToken

        with open(config_path, 'w') as fp:
            json.dump(prefilled_default_config(configs),
                      fp,
                      sort_keys=True,
                      indent=2)

        return True

    else:
        return False
예제 #26
0
 def login(self, username, password):
     try:
         self._account = MyPlexAccount(username, password)
         self.set_token(self._account._token, self._account.username,
                        self._account.email, self._account.uuid)
         self.emit('login-status', True, '')
     except:
         self.emit('login-status', False, 'Login failed')
예제 #27
0
def plex_account_test(servername, username, password):
    account = MyPlexAccount(username, password)
    # returns a PlexServer instance
    plex_server = account.resource(servername).connect()
    playlists = plex_server.playlists()
    for playlist in playlists:
        print("Playlist Title: {}".format(playlist.title))
        print("Playlist Items: {}".format(playlist.items))
예제 #28
0
def get_friends(config):
    token = config['plex']['token']
    account = MyPlexAccount(token)
    columns = ['email', 'cleaned_email']
    friends = [(user.email, clean_email(user.email))
               for user in account.users() if user.friend]
    frame = pd.DataFrame(friends, columns=columns)
    return frame
예제 #29
0
def connect_to_plex(username, password, server):
    """
    Takes the plex username, password and server name in order to
    establish a connection and retrieve data.
    """
    account = MyPlexAccount(username, password)
    my_plex = account.resource(server).connect()
    return my_plex
예제 #30
0
def plex(request, sess):
    assert SERVER_BASEURL, "Required SERVER_BASEURL not specified."

    if request.param == TEST_AUTHENTICATED:
        token = MyPlexAccount(session=sess).authenticationToken
    else:
        token = None
    return PlexServer(SERVER_BASEURL, token, session=sess)