Beispiel #1
0
async def add_to_plex(plexname, discordId, note, serverNumber=None):
    if settings.ENABLE_BLACKLIST:
        if db.check_blacklist(plexname):
            return ['blacklist', 'username']
        if db.check_blacklist(discordId):
            return ['blacklist', 'id']
    tempPlex = plex
    if serverNumber is not None:
        tempPlex = PlexServer(settings.PLEX_SERVER_URL[serverNumber],
                              settings.PLEX_SERVER_TOKEN[serverNumber])
    try:
        if db.add_user_to_db(discordId=discordId,
                             username=plexname,
                             note=note,
                             serverNumber=serverNumber):
            tempPlex.myPlexAccount().inviteFriend(user=plexname,
                                                  server=tempPlex,
                                                  sections=None,
                                                  allowSync=False,
                                                  allowCameraUpload=False,
                                                  allowChannels=False,
                                                  filterMovies=None,
                                                  filterTelevision=None,
                                                  filterMusic=None)
            await asyncio.sleep(30)
            px.add_to_tautulli(serverNumber)
            if note != 't':  # Trial members do not have access to Ombi
                px.add_to_ombi()
            return [True, None]
        else:
            print("{} could not be added to the database.".format(plexname))
            return [False, None]
    except Exception as e:
        print(e)
        return [False, None]
Beispiel #2
0
def full_check():
    from_profile = sdr.get_profile_id('Hold')
    to_profile = sdr.get_profile_id('Best')

    plex = PlexServer(conf['plex']['host'], conf['plex']['api'])
    users = [user.title for user in plex.myPlexAccount().users()]
    users.insert(0, plex.myPlexAccount().username)

    series = sdr.get_series()
    for show in series:
        try:
            try:
                tag_id = show['tags'][0]
            except:
                tag_id = 0
            if tag_id == 2:
                logger.info("Starting %s" % show['title'])
                remaining_episodes = show['totalEpisodeCount'] - (
                    show['seasons'][0]['statistics']['totalEpisodeCount']
                    if show['seasons'][0]['seasonNumber'] == 0 else
                    0) - show['episodeCount']
                if remaining_episodes > 0:
                    (last_watched, highest_season,
                     season_count) = find_last_watched(show, users)
                    update_show(show, highest_season, season_count,
                                last_watched)
                else:
                    logger.info("Monitoring All Episodes for %s" %
                                show['title'])
        except Exception as e:
            logger.error('Error on line {}, {}. {}'.format(
                sys.exc_info()[-1].tb_lineno,
                type(e).__name__, e))
def delete_from_plex(id):
    tempPlex = plex
    serverNumber = 0
    try:
        results = db.find_user_in_db("Plex", id)
        plexname = results[0]
        note = results[1]
        if settings.MULTI_PLEX:
            serverNumber = results[2]
            tempPlex = PlexServer(settings.PLEX_SERVER_URL[serverNumber],
                                  settings.PLEX_SERVER_TOKEN[serverNumber])
        if plexname is not None:
            tempPlex.myPlexAccount().removeFriend(user=plexname)
            if note != 't':
                px.delete_from_ombi(
                    plexname
                )  # Error if trying to remove trial user that doesn't exist in Ombi?
            px.delete_from_tautulli(plexname, serverNumber)
            db.remove_user_from_db(id)
            return True, serverNumber
        else:
            return False, serverNumber
    except plexapi.exceptions.NotFound:
        # print("Not found")
        return False, serverNumber
Beispiel #4
0
def getPlexUsers(serverNumber=None):
    """
    Returns all usernames (lowercase for comparison)
    """
    users = []
    tempPlex = plex
    tempServerName = settings.PLEX_SERVER_NAME
    tempServerAltName = settings.PLEX_SERVER_ALT_NAME
    if settings.MULTI_PLEX:
        if serverNumber:  # from specific server
            tempPlex = PlexServer(settings.PLEX_SERVER_URL[serverNumber],
                                  settings.PLEX_SERVER_TOKEN[serverNumber])
            tempServerName = settings.PLEX_SERVER_NAME[serverNumber]
            tempServerAltName = settings.PLEX_SERVER_ALT_NAME[serverNumber]
            for u in tempPlex.myPlexAccount().users():
                for s in u.servers:
                    if s.name == tempServerName or s.name == tempServerAltName:
                        users.append(u.username.lower())
        else:  # from all servers
            for serverNumber in range(len(settings.PLEX_SERVER_URL)):
                tempPlex = PlexServer(settings.PLEX_SERVER_URL[serverNumber],
                                      settings.PLEX_SERVER_TOKEN[serverNumber])
                tempServerName = settings.PLEX_SERVER_NAME[serverNumber]
                tempServerAltName = settings.PLEX_SERVER_ALT_NAME[serverNumber]
                for u in tempPlex.myPlexAccount().users():
                    for s in u.servers:
                        if s.name == tempServerName or s.name == tempServerAltName:
                            users.append(u.username.lower())
    else:  # from the single server
        for u in tempPlex.myPlexAccount().users():
            for s in u.servers:
                if s.name == tempServerName or s.name == tempServerAltName:
                    users.append(u.username.lower())
    return users
Beispiel #5
0
 def delete_from_plex(self, plexname, serverNumber = None):
     tempPlex = plex;
     if serverNumber != None:
         tempPlex = PlexServer(PLEX_SERVER_URLS_LIST[serverNumber],PLEX_SERVER_TOKENS_LIST[serverNumber])
     try:
         tempPlex.myPlexAccount().removeFriend(user=plexname)
         self.delete_from_ombi(plexname) # Error if trying to remove trial user that doesn't exist in Ombi?
         self.delete_from_tautulli(plexname, serverNumber)
         return True
     except plexapi.exceptions.NotFound:
         #print("Not found")
         return False
Beispiel #6
0
 async def add_to_plex(self, plexname, note, serverNumber = None):
     tempPlex = plex;
     if serverNumber != None:
         tempPlex = PlexServer(PLEX_SERVER_URLS_LIST[serverNumber],PLEX_SERVER_TOKENS_LIST[serverNumber])
     try:
         tempPlex.myPlexAccount().inviteFriend(user=plexname,server=plex,sections=None, allowSync=False, allowCameraUpload=False, allowChannels=False, filterMovies=None, filterTelevision=None, filterMusic=None)
         await asyncio.sleep(60)
         self.add_to_tautulli(plexname, serverNumber)
         if note != 't': # Trial members do not have access to Ombi
             self.add_to_ombi(plexname)
         return True
     except Exception as e:
         print(e)
         return False
Beispiel #7
0
def delete_from_plex(plexname, serverNumber=None):
    tempPlex = plex
    if serverNumber:
        tempPlex = PlexServer(settings.PLEX_SERVER_URL[serverNumber],
                              settings.PLEX_SERVER_TOKEN[serverNumber])
    try:
        tempPlex.myPlexAccount().removeFriend(user=plexname)
        px.delete_from_ombi(
            plexname
        )  # Error if trying to remove trial user that doesn't exist in Ombi?
        px.delete_from_tautulli(plexname, serverNumber)
        return True
    except plexapi.exceptions.NotFound:
        print("Couldn't delete user {}".format(plexname))
        return False
Beispiel #8
0
 async def pm_access(self, ctx: commands.Context, PlexUsername: str):
     """
     Check if you or another user has access to the Plex server
     """
     hasAccess = False
     name = PlexUsername
     serverNumber = 0
     if name != None:
         if MULTI_PLEX:
             for i in range(0,len(PLEX_SERVER_URLS_LIST)):
                 tempPlex = PlexServer(PLEX_SERVER_URLS_LIST[i],PLEX_SERVER_TOKENS_LIST[i])
                 for u in tempPlex.myPlexAccount().users():
                     if u.username == name:
                         for s in u.servers:
                             if s.name == PLEX_SERVER_NAMES_LIST[i]:
                                 hasAccess = True
                                 serverNumber = i
                                 break
                         break
                 break
         else:
             for u in plex.myPlexAccount().users():
                 if u.username == name:
                     for s in u.servers:
                         if s.name == PLEX_SERVER_NAME or s.name == PLEX_SERVER_ALT_NAME:
                             hasAccess = True
                             break
                     break
         if hasAccess:
             await ctx.send(("You have" if PlexUsername is None else name + " has") + " access to " + (PLEX_SERVER_NAMES_LIST[serverNumber] if MULTI_PLEX else PLEX_SERVER_NAME))
         else:
             await ctx.send(("You do not have" if PlexUsername is None else name + " does not have") + " access to " + ("any of the Plex servers" if MULTI_PLEX else PLEX_SERVER_NAME))
     else:
         await ctx.send("User not found.")
Beispiel #9
0
def get_episode(series_title, season_number, episode_number, user):
    try:
        pause = 0
        while True:
            pause += 1
            try:
                plex_temp = PlexServer(conf['plex']['host'],
                                       conf['plex']['api'])
                if user != plex_temp.myPlexAccount().username:
                    plex_users = get_user_tokens(plex_temp.machineIdentifier)
                    token = plex_users[user]
                    plex_temp = PlexServer(conf['plex']['host'], token)
                with DisableLogger():
                    episode = plex_temp.library.section(
                        'TV Shows').searchShows(title=series_title)[0].episode(
                            season=season_number, episode=episode_number)
                return episode
            except plexapi.exceptions.NotFound:
                return False
            except:
                time.sleep(pause)
                continue
    except plexapi.exceptions.NotFound:
        return False
    except Exception as e:
        logger.error('Error on line {}, {}, {}'.format(
            sys.exc_info()[-1].tb_lineno,
            type(e).__name__, e))
        logger.error('Error! Code: {c}, Message, {m}'.format(
            c=type(e).__name__, m=str(e)))
        return None
Beispiel #10
0
def hello():
    baseurl = 'http://' + SERVER_IP + ':' + PORT
    plex = PlexServer(baseurl, TOKEN)
    account = plex.myPlexAccount()

    art = None
    showTitle = None
    title = None
    username = None
    sessions = []

    for i in plex.sessions():
        art = i.artUrl
        if i.type == 'episode':
            showTitle = i.grandparentTitle
        else:
            showTitle = ''
        title = i.title
        username = i.usernames[0]

        session = {
            'art': art,
            'showTitle': showTitle,
            'title': title,
            'username': username
        }
        sessions.append(session)

    return render_template('index.html', sessions=sessions)
Beispiel #11
0
def signInLocally():
    """ Returns a :class:`~plexapi.server.PlexServer` by connecting through
        the local network.
    """
    # Get URL and token from config.ini
    plexURL = ""
    plexToken = ""
    config = configparser.ConfigParser()
    try:
        config.read('config.ini')
        plexURL = config['LOGIN']['PLEX_URL']
        plexToken = config['LOGIN']['PLEX_TOKEN']
    except KeyError:
        copyfile("./resources/config_template.ini", "config.ini")
        print("Error reading config.ini. New file created.")

    # Attempt to sign in
    isSignedIn = False
    while not isSignedIn:
        if plexURL == '' or plexToken == '':
            # Get URL and token from user
            plexURL = input("Input server URL [Ex. "
                            "https://192.168.1.50:32400]: ")
            plexToken = input("Input Plex access token [Info here: "
                              "https://bit.ly/2p7RtOu]: ")

        # Sign in
        print("Signing in...")
        try:
            requests.packages.urllib3.disable_warnings()
            session = requests.Session()
            session.verify = False
            plexServer = PlexServer(plexURL, plexToken, session=session)
            account = plexServer.myPlexAccount()
            isSignedIn = True
        except (requests.ConnectionError, requests.exceptions.MissingSchema,
                BadRequest) as error:

            # Connection failed
            if (isinstance(error, requests.ConnectionError)
                    or isinstance(error, requests.exceptions.MissingSchema)):
                print("Error: No server found at the given URL.")
            else:
                print("Error: Invalid API token.")

            # Clear info and try again
            plexURL = ''
            plexToken = ''

    # Give option to sign in as Managed User if server has them
    if account.subscriptionActive and account.homeSize > 1:

        # Sign in as managed user?
        useManagedUser = getYesOrNoFromUser("Sign in as managed user? [Y/n]: ")

        # If yes, sign in as managed user
        if useManagedUser == 'y':
            plexServer = signInManagedUser(plexServer)
    return plexServer
Beispiel #12
0
def delete_from_plex(id):
    """
    Remove a Discord user from Plex
    Returns:
    200 - user found and removed successfully
    400 - user found in database, but not found on Plex
    600 - user found, but not removed
    700 - user not found in database
    500 - unknown error
    """
    tempPlex = plex
    serverNumber = 0
    try:
        results = db.find_user_in_db(ServerOrDiscord="Plex", data=id)
        if not results:
            return 700, serverNumber  # user not found
        plexname = results[0]
        note = results[1]
        if settings.MULTI_PLEX:
            serverNumber = results[2]
            tempPlex = PlexServer(settings.PLEX_SERVER_URL[serverNumber],
                                  settings.PLEX_SERVER_TOKEN[serverNumber])
        if not plexname:
            return 700, serverNumber  # user not found
        else:
            try:
                tempPlex.myPlexAccount().removeFriend(user=plexname)
                if note != 't':
                    px.delete_from_ombi(
                        plexname
                    )  # Error if trying to remove trial user that doesn't exist in Ombi?
                px.delete_from_tautulli(plexname, serverNumber)
                db.remove_user_from_db(id)
                return 200, serverNumber
            except plexapi.exceptions.NotFound:
                return 500, serverNumber  # user not found on Plex
            except Exception as e:
                print(e)
                return 400, serverNumber  # user not removed completely
    except plexapi.exceptions.NotFound:
        # print("Not found")
        return 400, serverNumber  # user not found on Plex
    except Exception as e:
        print(e)
        return 500, serverNumber  # unknown error
Beispiel #13
0
 def countServerSubs(self, serverNumber):
     tempPlex = PlexServer(PLEX_SERVER_URLS_LIST[serverNumber],PLEX_SERVER_TOKENS_LIST[serverNumber])
     tempServerName = PLEX_SERVER_NAMES_LIST[serverNumber]
     count = 0
     for u in tempPlex.myPlexAccount().users():
         for s in u.servers:
             if s.name == tempServerName:
                     count+=1
     return count
Beispiel #14
0
 async def pm_access(self, ctx: commands.Context, PlexUsername: str = None):
     """
     Check if you or another user has access to the Plex server
     """
     hasAccess = False
     serverNumber = 0
     if PlexUsername is None:
         name = db.find_user_in_db(ServerOrDiscord="Plex",
                                   data=ctx.message.author.id)[0]
     else:
         name = PlexUsername
     if name is not None:
         if settings.MULTI_PLEX:
             for i in range(0, len(settings.PLEX_SERVER_URL)):
                 tempPlex = PlexServer(settings.PLEX_SERVER_URL[i],
                                       settings.PLEX_SERVER_TOKEN[i])
                 for u in tempPlex.myPlexAccount().users():
                     if u.username == name:
                         for s in u.servers:
                             if s.name == settings.PLEX_SERVER_NAME[
                                     i] or s.name == settings.PLEX_SERVER_ALT_NAME[
                                         i]:
                                 hasAccess = True
                                 serverNumber = i
                                 break
                         break
                 break
         else:
             for u in plex.myPlexAccount().users():
                 if u.username == name:
                     for s in u.servers:
                         if s.name == settings.PLEX_SERVER_NAME[
                                 0] or s.name == settings.PLEX_SERVER_ALT_NAME[
                                     0]:
                             hasAccess = True
                             break
                     break
         if hasAccess:
             await ctx.send(
                 ("You have" if PlexUsername is None else name + " has") +
                 " access to " +
                 (settings.PLEX_SERVER_NAME[serverNumber] if settings.
                  MULTI_PLEX else settings.PLEX_SERVER_NAME[0]))
         else:
             await ctx.send(
                 ("You do not have" if PlexUsername is None else name +
                  " does not have") + " access to " +
                 ("any of the Plex servers" if settings.
                  MULTI_PLEX else settings.PLEX_SERVER_NAME[0]))
     else:
         await ctx.send("User not found.")
Beispiel #15
0
def full_check():
    plex = PlexServer(config.plex_host, config.plex_api)
    users = [user.title for user in plex.myPlexAccount().users()]
    users.insert(0, plex.myPlexAccount().username)

    series = sdr.get_series()
    for show in random.sample(series, len(series)):
        try:
            try:
                tag_id = show['tags'][0]
            except:
                tag_id = 0  #NEED TAG CONFIG

            if tag_id == 2:  #NEED TAG CONFIG
                logger.info("Starting %s" % show['title'])
                try:
                    remaining_episodes = show['totalEpisodeCount'] - (
                        show['seasons'][0]['statistics']['totalEpisodeCount']
                        if show['seasons'][0]['seasonNumber'] == 0 else
                        0) - show['episodeCount']
                except:
                    remaining_episodes = 0
                if remaining_episodes > 0:
                    (last_watched, highest_season,
                     season_count) = find_last_watched(show, users)
                    update_show(show, highest_season, season_count,
                                last_watched)
                else:
                    logger.info("Monitoring All Episodes for %s" %
                                show['title'])
        except Exception as e:
            logger.error('Error on line {}, {}. {}'.format(
                sys.exc_info()[-1].tb_lineno,
                type(e).__name__, e))
    else:
        if len(series) == 0: logger.info("Not Shows Found")
Beispiel #16
0
def getPlexFriends(serverNumber=None):
    """
    # Returns all usernames of Plex Friends (access in + access out)
    (lowercase for comparison)
    """
    if settings.MULTI_PLEX:
        if serverNumber:  # from a specific server
            tempPlex = PlexServer(settings.PLEX_SERVER_URL[serverNumber],
                                  settings.PLEX_SERVER_TOKEN[serverNumber])
            return [
                u.username.lower() for u in tempPlex.myPlexAccount().users()
            ]
        else:  # from all servers
            users = []
            for i in range(len(settings.PLEX_SERVER_URL)):
                tempPlex = PlexServer(settings.PLEX_SERVER_URL[i],
                                      settings.PLEX_SERVER_TOKEN[i])
                for u in tempPlex.myPlexAccount().users():
                    users.append(u.username.lower())
            return users
    else:  # from the one server
        tempPlex = PlexServer(settings.PLEX_SERVER_URL[0],
                              settings.PLEX_SERVER_TOKEN[0])
        return [u.username.lower() for u in tempPlex.myPlexAccount().users()]
Beispiel #17
0
def countServerSubs(serverNumber=None):
    tempPlex = plex
    tempServerName = settings.PLEX_SERVER_NAME[0]
    tempServerAltName = settings.PLEX_SERVER_ALT_NAME[0]
    if serverNumber and serverNumber >= 0:
        tempPlex = PlexServer(settings.PLEX_SERVER_URL[serverNumber],
                              settings.PLEX_SERVER_TOKEN[serverNumber])
        tempServerName = settings.PLEX_SERVER_NAME[serverNumber]
        tempServerAltName = settings.PLEX_SERVER_ALT_NAME[serverNumber]
    count = 0
    for u in tempPlex.myPlexAccount().users():
        for s in u.servers:
            if s.name == tempServerName or s.name == tempServerAltName:
                count += 1
    return count
Beispiel #18
0
def data():
    baseurl = 'http://' + SERVER_IP + ':' + PORT
    plex = PlexServer(baseurl, TOKEN)
    account = plex.myPlexAccount()

    player = request.form.get('player')

    for client in plex.clients():
        if (player == client.name):
            media = plex.search(request.form.get('title'))
            player.playMedia(media)
            return render_template('success.html',
                                   art=request.form.get('art'),
                                   player=player,
                                   title=request.form.get('title'))

    return render_template('notfound.html', art=request.form.get('art'))
Beispiel #19
0
def main():
    """Main script"""
    plex = PlexServer(PLEX_URL, PLEX_TOKEN)

    PLAYLISTS = [x.title for x in plex.playlists()]
    USERS = [x.title for x in plex.myPlexAccount().users()]

    plex_users = get_user_tokens(plex.machineIdentifier)

    plex_playlists = {playlist.title: playlist.items() for playlist in plex.playlists()}

    for playlist in PLAYLISTS:
        playlist_items = plex_playlists.get(playlist)
        if not playlist_items:
            print("Playlist '{playlist}' not found on the server. Skipping.".format(playlist=playlist))
            continue

        print("Cloning the '{title}' playlist...".format(title=playlist))

        for user in USERS:
            user_token = plex_users.get(user)
            if not user_token:
                print("...User '{user}' not found in shared users. Skipping.".format(user=user))
                continue

            user_plex = PlexServer(PLEX_URL, user_token)

            # Delete the old playlist
            try:
                user_playlist = user_plex.playlist(playlist)
                user_playlist.delete()
            except:
                pass

            # Create a new playlist
            user_plex.createPlaylist(playlist, playlist_items)
            print("...Created playlist for '{user}'.".format(user=user))

    return
Beispiel #20
0
class Plex:
    def __init__(self, url, token, server_name):
        self.url = url
        self.token = token
        self.server_name = server_name
        self.server = PlexServer(url, token)

    def get_users(self):
        return self.server.myPlexAccount().users()

    def user_has_server_access(self, user):
        for s in user.servers:
            if s.name == self.server_name:
                return True
        return False

    def get_playlists(self):
        return self.server.playlists()

    def get_library_sections(self):
        return self.server.library.sections()

    def get_all_section_items(self, section):
        return section.all()
Beispiel #21
0
DAYS = 30
TOP = 5

sess = requests.Session()
# Ignore verifying the SSL certificate
sess.verify = False  # '/path/to/certfile'
# If verify is set to a path to a directory,
# the directory must have been processed using the c_rehash utility supplied
# with OpenSSL.
if sess.verify is False:
    # Disable the warning that the request is insecure, we know that...
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

plex = PlexServer(PLEX_URL, PLEX_TOKEN, session=sess)
account = plex.myPlexAccount()

user_lst = [x.title for x in plex.myPlexAccount().users() if x.servers and x.friend]
sections = plex.library.sections()
sections_dict = {x.key: x.title for x in sections}
filters_lst = list(set([y for x in sections if x.type != 'photo' for y in x.ALLOWED_FILTERS]))
playlist_lst = [x.title for x in plex.playlists()]
today = datetime.datetime.now().date()
weeknum = datetime.date(today.year, today.month, today.day).isocalendar()[1]


def actions():
    """
    add - create new playlist for admin or users
    remove - remove playlist type or name from admin or users
    update - remove playlist type and create new playlist type for admin or users
Beispiel #22
0
sess = requests.Session()
# Ignore verifying the SSL certificate
sess.verify = False  # '/path/to/certfile'
# If verify is set to a path to a directory,
# the directory must have been processed using the c_rehash utility supplied
# with OpenSSL.
if sess.verify is False:
    # Disable the warning that the request is insecure, we know that...
    import urllib3

    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

plex = PlexServer(PLEX_URL, PLEX_TOKEN, session=sess)


user_lst = [x.title for x in plex.myPlexAccount().users()]
sections_lst = [x.title for x in plex.library.sections()]
movies_keys = [x.key for x in plex.library.sections() if x.type == 'movie']
show_keys = [x.key for x in plex.library.sections() if x.type == 'show']


def get_ratings_lst(section_id):
    headers = {'Accept': 'application/json'}
    params = {'X-Plex-Token': PLEX_TOKEN}
    content = requests.get("{}/library/sections/{}/contentRating".format(PLEX_URL, section_id),
                           headers=headers, params=params)

    # print(json.dumps(content.json(), indent=4, sort_keys=True))
    ratings_keys = content.json()['MediaContainer']['Directory']
    ratings_lst = [x['title'] for x in ratings_keys]
    return ratings_lst
TAUTULLI_URL = TAUTULLI_URL or CONFIG.data['auth'].get('tautulli_baseurl')
TAUTULLI_APIKEY = TAUTULLI_APIKEY or CONFIG.data['auth'].get('tautulli_apikey')
USERNAME_IGNORE = [username.lower() for username in USERNAME_IGNORE]
SESSION = Session()
# Ignore verifying the SSL certificate
SESSION.verify = False  # '/path/to/certfile'
# If verify is set to a path to a directory,
# the directory must have been processed using the c_rehash utility supplied with OpenSSL.
if not SESSION.verify:
    # Disable the warning that the request is insecure, we know that...
    from urllib3 import disable_warnings
    from urllib3.exceptions import InsecureRequestWarning
    disable_warnings(InsecureRequestWarning)

SERVER = PlexServer(baseurl=PLEX_URL, token=PLEX_TOKEN, session=SESSION)
ACCOUNT = SERVER.myPlexAccount()
SECTIONS = [section.title for section in SERVER.library.sections()]
PLEX_USERS = {user.id: user.title for user in ACCOUNT.users()}
PLEX_USERS.update({int(ACCOUNT.id): ACCOUNT.title})
IGNORED_UIDS = [uid for uid, username in PLEX_USERS.items() if username.lower() in USERNAME_IGNORE]
IGNORED_UIDS.extend((int(ACCOUNT.id), 0))
# Get the Tautulli history.
PARAMS = {
    'cmd': 'get_users_table',
    'order_column': 'last_seen',
    'order_dir': 'asc',
    'length': 200,
    'apikey': TAUTULLI_APIKEY
}
TAUTULLI_USERS = []
try:
Beispiel #24
0
# Ignore verifying the SSL certificate
sess.verify = False  # '/path/to/certfile'
# If verify is set to a path to a directory,
# the directory must have been processed using the c_rehash utility supplied
# with OpenSSL.
if sess.verify is False:
    # Disable the warning that the request is insecure, we know that...
    import urllib3

    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

plex = PlexServer(PLEX_URL, PLEX_TOKEN, session=sess)

user_lst = {
    x.title: x.email if x.email else x.title
    for x in plex.myPlexAccount().users() if x.title
}
user_choices = list(set(user_lst.values())) + list(user_lst.keys())
sections_lst = [x.title for x in plex.library.sections()]
movies_keys = [x.key for x in plex.library.sections() if x.type == 'movie']
show_keys = [x.key for x in plex.library.sections() if x.type == 'show']

json_check = sorted([
    f for f in os.listdir('.') if os.path.isfile(f) and f.endswith(".json")
    and f.startswith(plex.friendlyName)
],
                    key=os.path.getmtime)

my_server_names = []
# Find all owners server names. For owners with multiple servers.
for res in plex.myPlexAccount().resources():
Beispiel #25
0
sess = requests.Session()
# Ignore verifying the SSL certificate
sess.verify = False  # '/path/to/certfile'
# If verify is set to a path to a directory,
# the directory must have been processed using the c_rehash utility supplied
# with OpenSSL.
if sess.verify is False:
    # Disable the warning that the request is insecure, we know that...
    import urllib3

    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

plex = PlexServer(PLEX_URL, PLEX_TOKEN, session=sess)

user_lst = [x.title for x in plex.myPlexAccount().users()]
sections_lst = [x.title for x in plex.library.sections()]
movies_keys = [x.key for x in plex.library.sections() if x.type == 'movie']
show_keys = [x.key for x in plex.library.sections() if x.type == 'show']

json_check = sorted([
    f for f in os.listdir('.') if os.path.isfile(f) and f.endswith(".json")
    and f.startswith(plex.friendlyName)
],
                    key=os.path.getmtime)

my_server_names = []
# Find all owners server names. For owners with multiple servers.
for res in plex.myPlexAccount().resources():
    if res.provides == 'server' and res.owned == True:
        my_server_names.append(res.name)
Beispiel #26
0
import requests
import argparse
from plexapi.server import PlexServer, CONFIG

# Using CONFIG file
PLEX_URL = ''
PLEX_TOKEN = ''
PLEX_URL = CONFIG.data['auth'].get('server_baseurl', PLEX_URL)
PLEX_TOKEN = CONFIG.data['auth'].get('server_token', PLEX_TOKEN)

sess = requests.Session()
sess.verify = False
plex = PlexServer(PLEX_URL, PLEX_TOKEN, session=sess)

sections_lst = [x.title for x in plex.library.sections()]
user_lst = [x.title for x in plex.myPlexAccount().users()]
# Adding admin account name to list
user_lst.append(plex.myPlexAccount().title)


def get_account(user):
    if user == plex.myPlexAccount().title:
        server = plex
    else:
        # Access Plex User's Account
        userAccount = plex.myPlexAccount().user(user)
        token = userAccount.get_token(plex.machineIdentifier)
        server = PlexServer(PLEX_URL, token)
    return server

Beispiel #27
0
if not PLEX_TOKEN:
    PLEX_TOKEN = CONFIG.data['auth'].get('server_token', '')

sess = requests.Session()
# Ignore verifying the SSL certificate
sess.verify = False  # '/path/to/certfile'
# If verify is set to a path to a directory,
# the directory must have been processed using the c_rehash utility supplied
# with OpenSSL.
if sess.verify is False:
    # Disable the warning that the request is insecure, we know that...
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

plex = PlexServer(PLEX_URL, PLEX_TOKEN, session=sess)
account = plex.myPlexAccount()


def actions():
    """
    deck - Items that are On Deck
    watch - Items that are Continue Watching
    """
    return ['deck', 'watch']


def get_con_watch(server, off_deck=None):
    """

    Parameters
    ----------
Beispiel #28
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Remove current Plex Server and a Client from MyPlex account. Useful when running tests in CI.
"""
from plexapi.myplex import MyPlexAccount
from plexapi.server import PlexServer
from plexapi import X_PLEX_IDENTIFIER

if __name__ == '__main__':
    myplex = MyPlexAccount()
    plex = PlexServer(token=myplex.authenticationToken)
    for device in plex.myPlexAccount().devices():
        if device.clientIdentifier == plex.machineIdentifier:
            print('Removing device "%s", with id "%s"' %
                  (device.name, device.clientIdentifier))
            device.delete()

    # If we suddenly remove the client first we wouldn't be able to authenticate to delete the server
    for device in plex.myPlexAccount().devices():
        if device.clientIdentifier == X_PLEX_IDENTIFIER:
            print('Removing device "%s", with id "%s"' %
                  (device.name, device.clientIdentifier))
            device.delete()
            break
sess = requests.Session()
# Ignore verifying the SSL certificate
sess.verify = False  # '/path/to/certfile'
# If verify is set to a path to a directory,
# the directory must have been processed using the c_rehash utility supplied
# with OpenSSL.
if sess.verify is False:
    # Disable the warning that the request is insecure, we know that...
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

plex = PlexServer(PLEX_URL, PLEX_TOKEN, session=sess)

sections_lst = [x.title for x in plex.library.sections()]
admin = {plex.myPlexAccount().id: plex.myPlexAccount().title}
users_dict = {x.id: x.title for x in plex.myPlexAccount().users() if x.servers}
users_dict.update(admin)
today = time.mktime(datetime.datetime.today().timetuple())


def get_users_table():
    # Get the Tautulli history.
    payload = {
        'apikey': TAUTULLI_APIKEY,
        'cmd': 'get_users_table',
        'order_column': 'last_seen',
        'order_dir': 'asc'
    }

    try:
Beispiel #30
0
            if _meta:
                metadata = Metadata(_meta)
                metadata.transcode_count = transcode_count
                transcoding_lst.append(metadata)
            else:
                print("Metadata error found with rating_key: ({})".format(
                    rating_key))

    return transcoding_lst


if __name__ == '__main__':

    session = Connection().session
    plex = PlexServer(PLEX_URL, PLEX_TOKEN, session=session)
    all_users = plex.myPlexAccount().users()
    all_users.append(plex.myPlexAccount())
    users = {
        user.title: User(name=user.title, email=user.email, userid=user.id)
        for user in all_users
    }

    user_choices = []
    for user in users.values():
        if user.email:
            user_choices.append(user.email)
        user_choices.append(user.userid)
        user_choices.append(user.name)
    sections_lst = [x.title for x in plex.library.sections()]

    parser = argparse.ArgumentParser(