Exemplo n.º 1
0
def prompt_server(servers: List[MyPlexResource]):
    old_age = datetime.now() - timedelta(weeks=1)

    def fmt_server(s):
        if s.lastSeenAt < old_age:
            decorator = disabled
        else:
            decorator = comment

        product = decorator(f"{s.product}/{s.productVersion}")
        platform = decorator(f"{s.device}: {s.platform}/{s.platformVersion}")
        click.echo(f"- {highlight(s.name)}: [Last seen: {decorator(str(s.lastSeenAt))}, Server: {product} on {platform}]")
        c: ResourceConnection
        for c in s.connections:
            click.echo(f"    {c.uri}")

    owned_servers = [s for s in servers if s.owned]
    unowned_servers = [s for s in servers if not s.owned]
    sorter = partial(sorted, key=lambda s: s.lastSeenAt)

    server_names = []
    if owned_servers:
        click.echo(success(f"{len(owned_servers)} owned servers found:"))
        for s in sorter(owned_servers):
            fmt_server(s)
            server_names.append(s.name)
    if unowned_servers:
        click.echo(success(f"{len(unowned_servers)} unowned servers found:"))
        for s in sorter(unowned_servers):
            fmt_server(s)
            server_names.append(s.name)

    return inquirer.select(message="Select default server:", choices=sorted(server_names), default=None, style=style, qmark="", pointer=">",).execute()
Exemplo n.º 2
0
def choose_managed_user(account: MyPlexAccount):
    users = [u.title for u in account.users()]
    if not users:
        return None

    click.echo(success("Managed user(s) found:"))
    users = sorted(users)
    users.insert(0, account.username)
    user = inquirer.select(
        message="Select the user you would like to use:",
        choices=users,
        default=None,
        style=style,
        qmark="",
        pointer=">",
    ).execute()

    if user == account.username:
        return None

    # Sanity check, even the user can't input invalid user
    user_account = account.user(user)
    if user_account:
        return user

    return None
Exemplo n.º 3
0
def login():
    """
    Log in to Plex and Trakt if needed
    """

    click.echo(highlight("Checking Plex and Trakt logins"))
    ensure_login()
    click.echo(success("Success!"))
Exemplo n.º 4
0
def login(username: str, password: str):
    if has_plex_token():
        if not click.confirm(PROMPT_PLEX_RELOGIN, default=True):
            return

    account = myplex_login(username, password)
    click.echo(success("Login to MyPlex was successful!"))

    [server, plex] = choose_server(account)
    click.echo(
        success(
            f"Connection to {plex.friendlyName} established successfully!"))

    token = server.accessToken
    user = account.username
    if server.owned:
        managed_user = choose_managed_user(account)
        if managed_user:
            user = managed_user
            token = account.user(managed_user).get_token(
                plex.machineIdentifier)

    CONFIG["PLEX_USERNAME"] = user
    CONFIG["PLEX_TOKEN"] = token
    CONFIG["PLEX_BASEURL"] = plex._baseurl
    if environ.get("PTS_IN_DOCKER"):
        try:
            host_ip = socket.gethostbyname("host.docker.internal")
        except socket.gaierror:
            try:
                host_ip = (check_output(
                    "ip -4 route show default | awk '{ print $3 }'",
                    shell=True).decode().rstrip())
            except Exception:
                host_ip = "172.17.0.1"
        CONFIG["PLEX_FALLBACKURL"] = f"http://{host_ip}:32400"
    else:
        CONFIG["PLEX_FALLBACKURL"] = "http://localhost:32400"
    CONFIG.save()

    click.echo(SUCCESS_MESSAGE)
Exemplo n.º 5
0
from typing import List

import click
from click import Choice, ClickException
from plexapi.exceptions import NotFound, Unauthorized
from plexapi.myplex import MyPlexAccount, MyPlexResource, ResourceConnection
from plexapi.server import PlexServer

from plextraktsync.factory import factory
from plextraktsync.style import (comment, disabled, error, highlight, prompt,
                                 success, title)

PROMPT_PLEX_PASSWORD = prompt("Please enter your Plex password")
PROMPT_PLEX_USERNAME = prompt("Please enter your Plex username or e-mail")
PROMPT_PLEX_RELOGIN = prompt("You already have Plex Access Token, do you want to log in again?")
SUCCESS_MESSAGE = success("Plex Media Server Authentication Token and base URL have been added to .env file")
NOTICE_2FA_PASSWORD = comment(
    "If you have 2 Factor Authentication enabled on Plex "
    "you can append the code to your password below (eg. passwordCODE)"
)
CONFIG = factory.config()

from InquirerPy import get_style, inquirer

style = get_style({"questionmark": "hidden", "question": "ansiyellow", "pointer": "fg:ansiblack bg:ansiyellow", })


def myplex_login(username, password):
    while True:
        username = click.prompt(PROMPT_PLEX_USERNAME, type=str, default=username)
        click.echo(NOTICE_2FA_PASSWORD)
Exemplo n.º 6
0
from json import JSONDecodeError
from os.path import exists

import click
from trakt.errors import ForbiddenException

from plextraktsync.factory import factory
from plextraktsync.path import pytrakt_file
from plextraktsync.style import error, prompt, success, title
from plextraktsync.trakt_api import TraktApi

PROMPT_TRAKT_CLIENT_ID = prompt("Please enter your client id")
PROMPT_TRAKT_CLIENT_SECRET = prompt("Please enter your client secret")
TRAKT_LOGIN_SUCCESS = success(
    "You are now logged into Trakt. "
    "Your Trakt credentials have been added in .env and .pytrakt.json files.")


def trakt_authenticate(api: TraktApi):
    click.echo(title("Sign in to Trakt"))

    click.echo("If you do not have a Trakt client ID and secret:")
    click.echo(
        "      1 - Open http://trakt.tv/oauth/applications on any computer")
    click.echo("      2 - Login to your Trakt account")
    click.echo("      3 - Press the NEW APPLICATION button")
    click.echo("      4 - Set the NAME field = plex")
    click.echo(
        "      5 - Set the REDIRECT URL field = urn:ietf:wg:oauth:2.0:oob")
    click.echo("      6 - Press the SAVE APP button")
    click.echo("")
Exemplo n.º 7
0
def login():
    click.echo(highlight("Checking Plex and Trakt logins"))
    ensure_login()
    click.echo(success("Success!"))