Ejemplo n.º 1
0
def tmdb_get_metadata(config_path, data, type):
    # Instantiate TMDB objects
    tmdb_id = int(data)

    api_key = config_tools.TMDB(config_path).apikey
    language = config_tools.TMDB(config_path).language
    is_movie = config_tools.Plex(config_path).library_type == "movie"

    if type in ["overview", "poster", "backdrop"]:
        collection = Collection()
        collection.api_key = api_key
        collection.language = language
        try:
            if type == "overview":
                meta = collection.details(tmdb_id).overview
            elif type == "poster":
                meta = collection.details(tmdb_id).poster_path
            elif type == "backdrop":
                meta = collection.details(tmdb_id).backdrop_path
        except AttributeError:
            media = Movie() if is_movie else TV()
            media.api_key = api_key
            media.language = language
            try:
                if type == "overview":
                    meta = media.details(tmdb_id).overview
                elif type == "poster":
                    meta = media.details(tmdb_id).poster_path
                elif type == "backdrop":
                    meta = media.details(tmdb_id).backdrop_path
            except AttributeError:
                raise ValueError(
                    "| TMDb Error: TMBd {} ID: {} not found".format(
                        "Movie/Collection" if is_movie else "Show", tmdb_id))
    elif type in ["biography", "profile", "name"]:
        person = Person()
        person.api_key = api_key
        person.language = language
        try:
            if type == "biography":
                meta = person.details(tmdb_id).biography
            elif type == "profile":
                meta = person.details(tmdb_id).profile_path
            elif type == "name":
                meta = person.details(tmdb_id).name
        except AttributeError:
            raise ValueError(
                "| TMDb Error: TMBd Actor ID: {} not found".format(tmdb_id))
    else:
        raise RuntimeError(
            "type {} not yet supported in tmdb_get_metadata".format(type))

    if meta is None:
        raise ValueError("| TMDb Error: TMDB ID {} has no {}".format(
            tmdb_id, type))
    elif type in ["profile", "poster", "backdrop"]:
        return "https://image.tmdb.org/t/p/original" + meta
    else:
        return meta
def tmdb_get_summary(data, type):
    collection = Collection()
    person = Person()
    collection.api_key = config_tools.TMDB().apikey
    person.api_key = collection.api_key
    collection.language = config_tools.TMDB().language
    person.language = collection.language

    if type == "overview":
        return collection.details(data).overview
    elif type == "biography":
        return person.details(data).biography
def tmdb_get_summary(config_path, data, type):
    # Instantiate TMDB objects
    collection = Collection()
    collection.api_key = config_tools.TMDB(config_path).apikey
    collection.language = config_tools.TMDB(config_path).language
    
    person = Person()
    person.api_key = collection.api_key
    person.language = collection.language

    # Return object based on type
    if type == "overview":          return collection.details(data).overview
    elif type == "biography":       return person.details(data).biography
    elif type == "poster_path":     return collection.details(data).poster_path
    elif type == "profile_path":    return person.details(data).profile_path
    else: raise RuntimeError("type not yet supported in tmdb_get_summary")
Ejemplo n.º 4
0
def tmdb_get_movies(config_path, plex, data):
    try:
        tmdb_id = re.search('.*?(\\d+)', data)
        tmdb_id = tmdb_id.group(1)
    except AttributeError:  # Bad URL Provided
        return

    t_movie = Movie()
    tmdb = Collection()
    tmdb.api_key = config_tools.TMDB(
        config_path).apikey  # Set TMDb api key for Collection
    if tmdb.api_key == "None":
        raise KeyError("Invalid TMDb API Key")
    t_movie.api_key = tmdb.api_key  # Copy same api key to Movie
    t_col = tmdb.details(tmdb_id)
    t_movs = []
    for tmovie in t_col.parts:
        t_movs.append(tmovie['id'])

    # Create dictionary of movies and their guid
    # GUIDs reference from which source Plex has pulled the metadata
    p_m_map = {}
    p_movies = plex.Library.all()
    for m in p_movies:
        guid = m.guid
        if "themoviedb://" in guid:
            guid = guid.split('themoviedb://')[1].split('?')[0]
        elif "imdb://" in guid:
            guid = guid.split('imdb://')[1].split('?')[0]
        else:
            guid = "None"
        p_m_map[m] = guid

    matched = []
    missing = []
    # We want to search for a match first to limit TMDb API calls
    # Too many rapid calls can cause a momentary block
    # If needed in future maybe add a delay after x calls to let the limit reset
    for mid in t_movs:  # For each TMBd ID in TMBd Collection
        match = False
        for m in p_m_map:  # For each movie in Plex
            if "tt" not in p_m_map[
                    m] != "None":  # If the Plex movie's guid does not start with tt
                if int(p_m_map[m]) == int(mid):
                    match = True
                    break
        if not match:
            imdb_id = t_movie.details(mid).entries['imdb_id']
            for m in p_m_map:
                if "tt" in p_m_map[m]:
                    if p_m_map[m] == imdb_id:
                        match = True
                        break
        if match:
            matched.append(m)
        else:
            missing.append(t_movie.details(mid).entries['imdb_id'])

    return matched, missing
def imdb_get_movies(config_path, plex, data):
    title_ids = data[1]
    print("| {} Movies found on IMDb".format(len(title_ids)))
    tmdb = TMDb()
    tmdb.api_key = config_tools.TMDB(config_path).apikey
    movie = Movie()
    imdb_map = {}
    matched_imdb_movies = []
    missing_imdb_movies = []
    current_length = 0
    current_count = 0
    plex_tools.create_cache(config_path)
    plex_movies = plex.Library.all()
    for m in plex_movies:
        current_count += 1
        print_display = "| Processing: {}/{} {}".format(current_count, len(plex_movies), m.title)
        print(adjust_space(current_length, print_display), end="\r")
        current_length = len(print_display)
        if 'plex://' in m.guid:
            item = m
            # Check cache for imdb_id
            imdb_id = plex_tools.query_cache(config_path, item.guid, 'imdb_id')
            if not imdb_id:
                imdb_id, tmdb_id = plex_tools.alt_id_lookup(plex, item)
                print(adjust_space(current_length, "| Cache | + | {} | {} | {} | {}".format(item.guid, imdb_id, tmdb_id, item.title)))
                plex_tools.update_cache(config_path, item.guid, imdb_id=imdb_id, tmdb_id=tmdb_id)
        elif 'themoviedb://' in m.guid:
            if not tmdb.api_key == "None":
                tmdb_id = m.guid.split('themoviedb://')[1].split('?')[0]
                tmdbapi = movie.details(tmdb_id)
                imdb_id = tmdbapi.imdb_id if hasattr(tmdbapi, 'imdb_id') else None
            else:
                imdb_id = None
        elif 'imdb://' in m.guid:
            imdb_id = m.guid.split('imdb://')[1].split('?')[0]
        else:
            imdb_id = None

        if imdb_id and imdb_id in title_ids:
            imdb_map[imdb_id] = m
        else:
            imdb_map[m.ratingKey] = m

    print(adjust_space(current_length, "| Processed {} Movies".format(len(plex_movies))))

    for imdb_id in title_ids:
        movie = imdb_map.pop(imdb_id, None)
        if movie:
            matched_imdb_movies.append(plex.Server.fetchItem(movie.ratingKey))
        else:
            missing_imdb_movies.append(imdb_id)

    return matched_imdb_movies, missing_imdb_movies
Ejemplo n.º 6
0
def tvdb_get_tmdb(config_path, tvdb_id):
    movie = Movie()
    movie.api_key = config_tools.TMDB(config_path).apikey
    search = movie.external(external_id=tvdb_id,
                            external_source="tvdb_id")['tv_results']
    if len(search) == 1:
        try:
            return str(search[0]['id'])
        except IndexError:
            return None
    else:
        return None
Ejemplo n.º 7
0
def imdb_get_movies(config_path, plex, plex_map, data):
    title_ids = data[1]
    print("| {} Movies found on IMDb".format(len(title_ids)))
    t_movie = Movie()
    t_movie.api_key = config_tools.TMDB(config_path).apikey
    matched = []
    missing = []
    for imdb_id in title_ids:
        tmdb_id = imdb_get_tmdb(config_path, imdb_id)
        if tmdb_id in plex_map:
            matched.append(plex.Server.fetchItem(plex_map[tmdb_id]))
        else:
            missing.append(tmdb_id)
    return matched, missing
Ejemplo n.º 8
0
def imdb_get_movies(config_path, plex, data):
    tmdb = TMDb()
    movie = Movie()
    tmdb.api_key = config_tools.TMDB(config_path).apikey
    imdb_url = data
    if imdb_url[-1:] == " ":
        imdb_url = imdb_url[:-1]
    imdb_map = {}
    library_language = plex.Library.language
    try:
        r = requests.get(imdb_url,
                         headers={'Accept-Language': library_language})
    except requests.exceptions.MissingSchema:
        return
    tree = html.fromstring(r.content)
    title_ids = tree.xpath("//div[contains(@class, 'lister-item-image')]"
                           "//a/img//@data-tconst")
    if title_ids:
        for m in plex.Library.all():
            if 'themoviedb://' in m.guid:
                if not tmdb.api_key == "None":
                    tmdb_id = m.guid.split('themoviedb://')[1].split('?')[0]
                    tmdbapi = movie.details(tmdb_id)
                    imdb_id = tmdbapi.imdb_id
                else:
                    imdb_id = None
            elif 'imdb://' in m.guid:
                imdb_id = m.guid.split('imdb://')[1].split('?')[0]
            else:
                imdb_id = None

            if imdb_id and imdb_id in title_ids:
                imdb_map[imdb_id] = m
            else:
                imdb_map[m.ratingKey] = m

        matched_imbd_movies = []
        missing_imdb_movies = []
        for imdb_id in title_ids:
            movie = imdb_map.pop(imdb_id, None)
            if movie:
                matched_imbd_movies.append(
                    plex.Server.fetchItem(movie.ratingKey))
            else:
                missing_imdb_movies.append(imdb_id)

        return matched_imbd_movies, missing_imdb_movies
Ejemplo n.º 9
0
def tmdb_get_imdb(config_path, tmdb_id):
    movie = Movie()
    movie.api_key = config_tools.TMDB(config_path).apikey
    search = movie.external_ids(tmdb_id)['imdb_id']
    if search:
        return str(search)
Ejemplo n.º 10
0
def tmdb_get_tvdb(config_path, tmdb_id):
    show = TV()
    show.api_key = config_tools.TMDB(config_path).apikey
    return show.external_ids(tmdb_id)['tvdb_id']
Ejemplo n.º 11
0
def tmdb_get_shows(config_path, plex, plex_map, data, method):
    config_tools.TraktClient(config_path)

    t_tvs = []
    t_tv = TV()
    t_tv.api_key = config_tools.TMDB(config_path).apikey
    if t_tv.api_key == "None":
        raise KeyError("Invalid TMDb API Key")

    count = 0
    if method in ["tmdb_discover", "tmdb_company", "tmdb_network"]:
        if method in ["tmdb_company", "tmdb_network"]:
            tmdb = Company() if method == "tmdb_company" else Network()
            tmdb.api_key = t_tv.api_key
            tmdb_id = int(data)
            tmdb_name = str(tmdb.details(tmdb_id))
            discover_method = "with_companies" if method == "tmdb_company" else "with_networks"
            attrs = {discover_method: tmdb_id}
            limit = 0
        else:
            attrs = data.copy()
            limit = int(attrs.pop('limit'))
        discover = Discover()
        discover.api_key = t_tv.api_key
        discover.discover_tv_shows(attrs)
        total_pages = int(os.environ["total_pages"])
        total_results = int(os.environ["total_results"])
        amount = total_results if limit == 0 or total_results < limit else limit
        if method in ["tmdb_company", "tmdb_network"]:
            print("| Processing {}: {} ({} {} shows)".format(
                method, tmdb_id, amount, tmdb_name))
        else:
            print("| Processing {}: {} shows".format(method, amount))
            for attr, value in attrs.items():
                print("|            {}: {}".format(attr, value))
        for x in range(total_pages):
            attrs["page"] = x + 1
            tmdb_shows = discover.discover_tv_shows(attrs)
            for tshow in tmdb_shows:
                count += 1
                t_tvs.append(tshow.id)
                if count == data:
                    break
            if count == data:
                break
    elif method in [
            "tmdb_popular", "tmdb_top_rated", "tmdb_trending_daily",
            "tmdb_trending_weekly"
    ]:
        trending = Trending()
        trending.api_key = t_tv.api_key
        for x in range(int(int(data) / 20) + 1):
            if method == "tmdb_popular":
                tmdb_shows = t_tv.popular(x + 1)
            elif method == "tmdb_top_rated":
                tmdb_shows = t_tv.top_rated(x + 1)
            elif method == "tmdb_trending_daily":
                tmdb_shows = trending.tv_day(x + 1)
            elif method == "tmdb_trending_weekly":
                tmdb_shows = trending.tv_week(x + 1)
            for tshow in tmdb_shows:
                count += 1
                t_tvs.append(tshow.id)
                if count == amount:
                    break
            if count == amount:
                break
        print("| Processing {}: {} Items".format(method, data))
    else:
        tmdb_id = int(data)
        if method == "tmdb_list":
            tmdb = List()
            tmdb.api_key = t_tv.api_key
            try:
                t_col = tmdb.details(tmdb_id)
                tmdb_name = str(t_col)
                for ttv in t_col:
                    if ttv.media_type == "tv":
                        t_tvs.append(ttv.id)
            except:
                raise ValueError(
                    "| Config Error: TMDb List: {} not found".format(tmdb_id))
        else:
            try:
                t_tv.details(tmdb_id).number_of_seasons
                tmdb_name = str(t_tv.details(tmdb_id))
                t_tvs.append(tmdb_id)
            except:
                raise ValueError(
                    "| Config Error: TMDb ID: {} not found".format(tmdb_id))
        print("| Processing {}: ({}) {}".format(method, tmdb_id, tmdb_name))

    matched = []
    missing = []
    for mid in t_tvs:
        tvdb_id = tmdb_get_tvdb(config_path, mid)
        if tvdb_id is None:
            print(
                "| TMDb Error: tmdb_id: {} ({}) has no associated tvdb_id. Try just using tvdb_id instead"
                .format(mid,
                        t_tv.details(mid).name))
        elif tvdb_id in plex_map:
            matched.append(plex.Server.fetchItem(plex_map[tvdb_id]))
        else:
            missing.append(tvdb_id)

    return matched, missing
Ejemplo n.º 12
0
def tmdb_get_movies(config_path, plex, plex_map, data, method):
    t_movs = []
    t_movie = Movie()
    t_movie.api_key = config_tools.TMDB(
        config_path).apikey  # Set TMDb api key for Movie
    if t_movie.api_key == "None":
        raise KeyError("Invalid TMDb API Key")

    count = 0
    if method == "tmdb_discover":
        attrs = data.copy()
        discover = Discover()
        discover.api_key = t_movie.api_key
        discover.discover_movies(attrs)
        total_pages = int(os.environ["total_pages"])
        total_results = int(os.environ["total_results"])
        limit = int(attrs.pop('limit'))
        amount = total_results if limit == 0 or total_results < limit else limit
        print("| Processing {}: {} movies".format(method, amount))
        for attr, value in attrs.items():
            print("|            {}: {}".format(attr, value))
        for x in range(total_pages):
            attrs["page"] = x + 1
            tmdb_movies = discover.discover_movies(attrs)
            for tmovie in tmdb_movies:
                count += 1
                t_movs.append(tmovie.id)
                if count == amount:
                    break
            if count == amount:
                break
    elif method in [
            "tmdb_popular", "tmdb_top_rated", "tmdb_now_playing",
            "tmdb_trending_daily", "tmdb_trending_weekly"
    ]:
        trending = Trending()
        trending.api_key = t_movie.api_key
        for x in range(int(int(data) / 20) + 1):
            if method == "tmdb_popular":
                tmdb_movies = t_movie.popular(x + 1)
            elif method == "tmdb_top_rated":
                tmdb_movies = t_movie.top_rated(x + 1)
            elif method == "tmdb_now_playing":
                tmdb_movies = t_movie.now_playing(x + 1)
            elif method == "tmdb_trending_daily":
                tmdb_movies = trending.movie_day(x + 1)
            elif method == "tmdb_trending_weekly":
                tmdb_movies = trending.movie_week(x + 1)
            for tmovie in tmdb_movies:
                count += 1
                t_movs.append(tmovie.id)
                if count == data:
                    break
            if count == data:
                break
        print("| Processing {}: {} Items".format(method, data))
    else:
        tmdb_id = int(data)
        if method == "tmdb_list":
            tmdb = List()
            tmdb.api_key = t_movie.api_key
            try:
                t_col = tmdb.details(tmdb_id)
                tmdb_name = str(t_col)
                for tmovie in t_col:
                    if tmovie.media_type == "movie":
                        t_movs.append(tmovie.id)
            except:
                raise ValueError(
                    "| Config Error: TMDb List: {} not found".format(tmdb_id))
        elif method == "tmdb_company":
            tmdb = Company()
            tmdb.api_key = t_movie.api_key
            tmdb_name = str(tmdb.details(tmdb_id))
            company_movies = tmdb.movies(tmdb_id)
            for tmovie in company_movies:
                t_movs.append(tmovie.id)
        else:
            tmdb = Collection()
            tmdb.api_key = t_movie.api_key
            t_col = tmdb.details(tmdb_id)
            tmdb_name = str(t_col)
            try:
                for tmovie in t_col.parts:
                    t_movs.append(tmovie['id'])
            except AttributeError:
                try:
                    t_movie.details(tmdb_id).imdb_id
                    tmdb_name = str(t_movie.details(tmdb_id))
                    t_movs.append(tmdb_id)
                except:
                    raise ValueError(
                        "| Config Error: TMDb ID: {} not found".format(
                            tmdb_id))
        print("| Processing {}: ({}) {}".format(method, tmdb_id, tmdb_name))

    matched = []
    missing = []
    for mid in t_movs:
        mid = str(mid)
        if mid in plex_map:
            matched.append(plex.Server.fetchItem(plex_map[mid]))
        else:
            missing.append(mid)

    return matched, missing
Ejemplo n.º 13
0
def tmdb_get_tvdb(config_path, tmdb_id):
    show = TV()
    show.api_key = config_tools.TMDB(config_path).apikey
    search = show.external_ids(tmdb_id)['tvdb_id']
    if search:
        return str(search)
Ejemplo n.º 14
0
def tmdb_get_imdb(config_path, tmdb_id):
    movie = Movie()
    movie.api_key = config_tools.TMDB(config_path).apikey
    return movie.external_ids(tmdb_id)['imdb_id']
def tmdb_get_movies(config_path, plex, data, is_list=False):
    tmdb_id = int(data)
    t_movs = []
    t_movie = Movie()
    t_movie.api_key = config_tools.TMDB(
        config_path).apikey  # Set TMDb api key for Movie
    if t_movie.api_key == "None":
        raise KeyError("Invalid TMDb API Key")

    tmdb = List() if is_list else Collection()
    tmdb.api_key = t_movie.api_key
    t_col = tmdb.details(tmdb_id)

    if is_list:
        try:
            for tmovie in t_col:
                if tmovie.media_type == "movie":
                    t_movs.append(tmovie.id)
        except:
            raise ValueError(
                "| Config Error: TMDb List: {} not found".format(tmdb_id))
    else:
        try:
            for tmovie in t_col.parts:
                t_movs.append(tmovie['id'])
        except AttributeError:
            try:
                t_movie.details(tmdb_id).imdb_id
                t_movs.append(tmdb_id)
            except:
                raise ValueError(
                    "| Config Error: TMDb ID: {} not found".format(tmdb_id))

    # Create dictionary of movies and their guid
    # GUIDs reference from which source Plex has pulled the metadata
    p_m_map = {}
    p_movies = plex.Library.all()
    for m in p_movies:
        guid = m.guid
        if "themoviedb://" in guid:
            guid = guid.split('themoviedb://')[1].split('?')[0]
        elif "imdb://" in guid:
            guid = guid.split('imdb://')[1].split('?')[0]
        elif "plex://" in guid:
            guid = guid.split('plex://')[1].split('?')[0]
        else:
            guid = "None"
        p_m_map[m] = guid

    matched = []
    missing = []
    plex_tools.create_cache(config_path)
    # We want to search for a match first to limit TMDb API calls
    # Too many rapid calls can cause a momentary block
    # If needed in future maybe add a delay after x calls to let the limit reset
    for mid in t_movs:  # For each TMBd ID in TMBd Collection
        match = False
        for m in p_m_map:  # For each movie in Plex
            item = m
            agent_type = urlparse(m.guid).scheme.split('.')[-1]
            # Plex movie agent
            if agent_type == 'plex':
                # Check cache for tmdb_id
                tmdb_id = plex_tools.query_cache(config_path, item.guid,
                                                 'tmdb_id')
                imdb_id = plex_tools.query_cache(config_path, item.guid,
                                                 'imdb_id')
                if not tmdb_id:
                    imdb_id, tmdb_id = plex_tools.alt_id_lookup(plex, item)
                    print("| Cache | + | {} | {} | {} | {}".format(
                        item.guid, imdb_id, tmdb_id, item.title))
                    plex_tools.update_cache(config_path,
                                            item.guid,
                                            imdb_id=imdb_id,
                                            tmdb_id=tmdb_id)
                if int(tmdb_id) == int(mid):
                    match = True
                    break
            elif agent_type == 'themoviedb':
                if int(p_m_map[m]) == int(mid):
                    match = True
                    break
            elif agent_type == 'imdb':
                imdb_id = t_movie.details(mid).imdb_id
                for m in p_m_map:
                    if "tt" in p_m_map[m]:
                        if p_m_map[m] == imdb_id:
                            match = True
                            break
        if match:
            matched.append(m)
        else:
            # Duplicate TMDb call?
            missing.append(t_movie.details(mid).imdb_id)

    return matched, missing
def tmdb_get_shows(config_path, plex, data, method):
    config_tools.TraktClient(config_path)

    t_tvs = []
    t_tv = TV()
    t_tv.api_key = config_tools.TMDB(config_path).apikey  # Set TMDb api key for Movie
    if t_tv.api_key == "None":
        raise KeyError("Invalid TMDb API Key")
    discover = Discover()
    discover.api_key = t_tv.api_key

    count = 0
    if method == "tmdb_discover":
        discover.discover_tv_shows(data)
        total_pages = int(os.environ["total_pages"])
        total_results = int(os.environ["total_results"])
        limit = int(data.pop('limit'))
        amount = total_results if total_results < limit else limit
        print("| Processing {}: {} items".format(method, amount))
        for attr, value in data.items():
            print("|            {}: {}".format(attr, value))
        for x in range(total_pages):
            data["page"] = x + 1
            tmdb_shows = discover.discover_tv_shows(data)
            for tshow in tmdb_shows:
                count += 1
                t_tvs.append(tshow.id)
                if count == amount:
                    break
            if count == amount:
                break
        run_discover(data)
    elif method in ["tmdb_popular", "tmdb_top_rated", "tmdb_trending_daily", "tmdb_trending_weekly"]:
        #trending = Trending()                  #TURNON:Trending
        #trending.api_key = t_movie.api_key     #TURNON:Trending
        for x in range(int(data / 20) + 1):
            if method == "tmdb_popular":
                tmdb_shows = t_tv.popular(x + 1)
            elif method == "tmdb_top_rated":
                tmdb_shows = t_tv.top_rated(x + 1)
            #elif method == "tmdb_trending_daily":      #TURNON:Trending
            #    tmdb_shows = trending.tv_day(x + 1)    #TURNON:Trending
            #elif method == "tmdb_trending_weekly":     #TURNON:Trending
            #    tmdb_shows = trending.tv_week(x + 1)   #TURNON:Trending
            for tshow in tmdb_shows:
                count += 1
                t_tvs.append(tshow.id)
                if count == amount:
                    break
            if count == amount:
                break
        print("| Processing {}: {} Items".format(method, data))
    else:
        tmdb_id = int(data)
        if method == "tmdb_list":
            tmdb = List()
            tmdb.api_key = t_tv.api_key
            try:
                t_col = tmdb.details(tmdb_id)
                tmdb_name = str(t_col)
                for ttv in t_col:
                    if ttv.media_type == "tv":
                        t_tvs.append(ttv.id)
            except:
                raise ValueError("| Config Error: TMDb List: {} not found".format(tmdb_id))
        elif method in ["tmdb_company", "tmdb_network"]:
            if method == "tmdb_company":
                tmdb = Company()
                tmdb.api_key = t_tv.api_key
                tmdb_name = str(tmdb.details(tmdb_id))
            else:
                #tmdb = Network()                           #TURNON:Trending
                #tmdb.api_key = t_tv.api_key                #TURNON:Trending
                tmdb_name = ""#str(tmdb.details(tmdb_id))   #TURNON:Trending
            discover_method = "with_companies" if method == "tmdb_company" else "with_networks"
            tmdb_shows = discover.discover_tv_shows({discover_method: tmdb_id})
            for tshow in tmdb_shows:
                t_tvs.append(tshow.id)
        else:
            try:
                t_tv.details(tmdb_id).number_of_seasons
                tmdb_name = str(t_tv.details(tmdb_id))
                t_tvs.append(tmdb_id)
            except:
                raise ValueError("| Config Error: TMDb ID: {} not found".format(tmdb_id))
        print("| Processing {}: ({}) {}".format(method, tmdb_id, tmdb_name))

    p_tv_map = {}
    for item in plex.Library.all():
        guid = urlparse(item.guid)
        item_type = guid.scheme.split('.')[-1]
        if item_type == 'thetvdb':
            tvdb_id = guid.netloc
        elif item_type == 'themoviedb':
            tvdb_id = get_tvdb_id_from_tmdb_id(guid.netloc)
        else:
            tvdb_id = None
        p_tv_map[item] = tvdb_id

    matched = []
    missing = []
    for mid in t_tvs:
        match = False
        tvdb_id = get_tvdb_id_from_tmdb_id(mid)
        if tvdb_id is None:
            print("| Trakt Error: tmbd_id: {} could not converted to tvdb_id try just using tvdb_id instead".format(mid))
        else:
            for t in p_tv_map:
                if p_tv_map[t] and "tt" not in p_tv_map[t] != "None":
                    if p_tv_map[t] is not None and int(p_tv_map[t]) == int(tvdb_id):
                        match = True
                        break
        if match:
            matched.append(t)
        else:
            missing.append(tvdb_id)

    return matched, missing
def tmdb_get_movies(config_path, plex, data, method):
    t_movs = []
    t_movie = Movie()
    t_movie.api_key = config_tools.TMDB(config_path).apikey  # Set TMDb api key for Movie
    if t_movie.api_key == "None":
        raise KeyError("Invalid TMDb API Key")

    count = 0
    if method == "tmdb_discover":
        discover = Discover()
        discover.api_key = t_movie.api_key
        discover.discover_movies(data)
        total_pages = int(os.environ["total_pages"])
        total_results = int(os.environ["total_results"])
        limit = int(data.pop('limit'))
        amount = total_results if total_results < limit else limit
        print("| Processing {}: {} items".format(method, amount))
        for attr, value in data.items():
            print("|            {}: {}".format(attr, value))
        for x in range(total_pages):
            data["page"] = x + 1
            tmdb_movies = discover.discover_movies(data)
            for tmovie in tmdb_movies:
                count += 1
                t_movs.append(tmovie.id)
                if count == amount:
                    break
            if count == amount:
                break
    elif method in ["tmdb_popular", "tmdb_top_rated", "tmdb_now_playing", "tmdb_trending_daily", "tmdb_trending_weekly"]:
        #trending = Trending()                  #TURNON:Trending
        #trending.api_key = t_movie.api_key     #TURNON:Trending
        for x in range(int(data / 20) + 1):
            if method == "tmdb_popular":
                tmdb_movies = t_movie.popular(x + 1)
            elif method == "tmdb_top_rated":
                tmdb_movies = t_movie.top_rated(x + 1)
            elif method == "tmdb_now_playing":
                tmdb_movies = t_movie.now_playing(x + 1)
            #elif method == "tmdb_trending_daily":          #TURNON:Trending
            #    tmdb_movies = trending.movie_day(x + 1)    #TURNON:Trending
            #elif method == "tmdb_trending_weekly":         #TURNON:Trending
            #    tmdb_movies = trending.movie_week(x + 1)   #TURNON:Trending
            for tmovie in tmdb_movies:
                count += 1
                t_movs.append(tmovie.id)
                if count == data:
                    break
            if count == data:
                break
        print("| Processing {}: {} Items".format(method, data))
    else:
        tmdb_id = int(data)
        if method == "tmdb_list":
            tmdb = List()
            tmdb.api_key = t_movie.api_key
            try:
                t_col = tmdb.details(tmdb_id)
                tmdb_name = str(t_col)
                for tmovie in t_col:
                    if tmovie.media_type == "movie":
                        t_movs.append(tmovie.id)
            except:
                raise ValueError("| Config Error: TMDb List: {} not found".format(tmdb_id))
        elif method == "tmdb_company":
            tmdb = Company()
            tmdb.api_key = t_movie.api_key
            tmdb_name = str(tmdb.details(tmdb_id))
            company_movies = tmdb.movies(tmdb_id)
            for tmovie in company_movies:
                t_movs.append(tmovie.id)
        else:
            tmdb = Collection()
            tmdb.api_key = t_movie.api_key
            t_col = tmdb.details(tmdb_id)
            tmdb_name = str(t_col)
            try:
                for tmovie in t_col.parts:
                    t_movs.append(tmovie['id'])
            except AttributeError:
                try:
                    t_movie.details(tmdb_id).imdb_id
                    tmdb_name = str(t_movie.details(tmdb_id))
                    t_movs.append(tmdb_id)
                except:
                    raise ValueError("| Config Error: TMDb ID: {} not found".format(tmdb_id))
        print("| Processing {}: ({}) {}".format(method, tmdb_id, tmdb_name))


    # Create dictionary of movies and their guid
    # GUIDs reference from which source Plex has pulled the metadata
    p_m_map = {}
    p_movies = plex.Library.all()
    for m in p_movies:
        guid = m.guid
        if "themoviedb://" in guid:
            guid = guid.split('themoviedb://')[1].split('?')[0]
        elif "imdb://" in guid:
            guid = guid.split('imdb://')[1].split('?')[0]
        elif "plex://" in guid:
            guid = guid.split('plex://')[1].split('?')[0]
        else:
            guid = "None"
        p_m_map[m] = guid

    matched = []
    missing = []
    plex_tools.create_cache(config_path)
    # We want to search for a match first to limit TMDb API calls
    # Too many rapid calls can cause a momentary block
    # If needed in future maybe add a delay after x calls to let the limit reset
    for mid in t_movs:  # For each TMBd ID in TMBd Collection
        match = False
        for m in p_m_map:  # For each movie in Plex
            item = m
            agent_type = urlparse(m.guid).scheme.split('.')[-1]
            # Plex movie agent
            if agent_type == 'plex':
                # Check cache for tmdb_id
                tmdb_id = plex_tools.query_cache(config_path, item.guid, 'tmdb_id')
                imdb_id = plex_tools.query_cache(config_path, item.guid, 'imdb_id')
                if not tmdb_id:
                    imdb_id, tmdb_id = plex_tools.alt_id_lookup(plex, item)
                    print("| Cache | + | {} | {} | {} | {}".format(item.guid, imdb_id, tmdb_id, item.title))
                    plex_tools.update_cache(config_path, item.guid, imdb_id=imdb_id, tmdb_id=tmdb_id)
                if int(tmdb_id) == int(mid):
                    match = True
                    break
            elif agent_type == 'themoviedb':
                if int(p_m_map[m]) == int(mid):
                    match = True
                    break
            elif agent_type == 'imdb':
                imdb_id = t_movie.details(mid).imdb_id
                for m in p_m_map:
                    if "tt" in p_m_map[m]:
                        if p_m_map[m] == imdb_id:
                            match = True
                            break
        if match:
            matched.append(m)
        else:
            # Duplicate TMDb call?
            missing.append(t_movie.details(mid).imdb_id)

    return matched, missing
def tmdb_get_shows(config_path, plex, data, is_list=False):
    config_tools.TraktClient(config_path)

    tmdb_id = int(data)

    t_tvs = []
    t_tv = TV()
    t_tv.api_key = config_tools.TMDB(
        config_path).apikey  # Set TMDb api key for Movie
    if t_tv.api_key == "None":
        raise KeyError("Invalid TMDb API Key")

    if is_list:
        tmdb = List()
        tmdb.api_key = t_tv.api_key
        try:
            t_col = tmdb.details(tmdb_id)
            for ttv in t_col:
                if ttv.media_type == "tv":
                    t_tvs.append(ttv.id)
        except:
            raise ValueError(
                "| Config Error: TMDb List: {} not found".format(tmdb_id))
    else:
        try:
            t_tv.details(tmdb_id).number_of_seasons
            t_tvs.append(tmdb_id)
        except:
            raise ValueError(
                "| Config Error: TMDb ID: {} not found".format(tmdb_id))

    p_tv_map = {}
    for item in plex.Library.all():
        guid = urlparse(item.guid)
        item_type = guid.scheme.split('.')[-1]
        if item_type == 'thetvdb':
            tvdb_id = guid.netloc
        elif item_type == 'themoviedb':
            tvdb_id = get_tvdb_id_from_tmdb_id(guid.netloc)
        else:
            tvdb_id = None
        p_tv_map[item] = tvdb_id

    matched = []
    missing = []
    for mid in t_tvs:
        match = False
        tvdb_id = get_tvdb_id_from_tmdb_id(mid)
        if tvdb_id is None:
            print(
                "| Trakt Error: tmbd_id: {} could not converted to tvdb_id try just using tvdb_id instead"
                .format(mid))
        else:
            for t in p_tv_map:
                if p_tv_map[t] and "tt" not in p_tv_map[t] != "None":
                    if p_tv_map[t] is not None and int(
                            p_tv_map[t]) == int(tvdb_id):
                        match = True
                        break
        if match:
            matched.append(t)
        else:
            missing.append(tvdb_id)

    return matched, missing
Ejemplo n.º 19
0
def add_to_radarr(config_path, missing):
    config_tmdb = config_tools.TMDB(config_path)
    config_radarr = config_tools.Radarr(config_path)

    tmdb = TMDb()
    tmdb.api_key = config_tmdb.apikey
    tmdb.language = config_tmdb.language

    movie = Movie()
    for m in missing:
        # Get TMDb ID data from IMDb ID
        search = movie.external(external_id=str(m),
                                external_source="imdb_id")['movie_results']
        if len(search) == 1:
            tmdb_details = search[0]
        else:
            print("| --- Unable to match TMDb ID for IMDb ID {}, skipping".
                  format(m))
            continue

        # Validate TMDb information (very few TMDb entries don't yet have basic information)
        try:
            tmdb_title = tmdb_details['title']
            tmdb_id = tmdb_details['id']
        except IndexError:
            print(
                "| --- Unable to fetch necessary TMDb information for IMDb ID {}, skipping"
                .format(m))
            continue

        # Validate TMDb year (several TMDb entries don't yet have release dates)
        try:
            # This might be overly punitive
            tmdb_year = tmdb_details['release_date'].split("-")[0]
        except KeyError:
            print(
                "| --- {} does not have a release date on TMDb yet, skipping".
                format(tmdb_title))
            continue

        if tmdb_year.isdigit() == False:
            print(
                "| --- {} does not have a release date on TMDb yet, skipping".
                format(tmdb_title))
            continue

        tmdb_poster = "https://image.tmdb.org/t/p/original{}".format(
            tmdb_details['poster_path'])

        titleslug = "{} {}".format(tmdb_title, tmdb_year)
        titleslug = re.sub(r'([^\s\w]|_)+', '', titleslug)
        titleslug = titleslug.replace(" ", "-")
        titleslug = titleslug.lower()

        payload = {
            "title": tmdb_title,
            "qualityProfileId": config_radarr.quality_profile_id,
            "year": int(tmdb_year),
            "tmdbid": str(tmdb_id),
            "titleslug": titleslug,
            "monitored": "true",
            "rootFolderPath": config_radarr.root_folder_path,
            "images": [{
                "covertype": "poster",
                "url": tmdb_poster
            }],
            "addOptions": {
                "searchForMovie": config_radarr.search_movie
            }
        }

        if config_radarr.version == "v3":
            slug = "/api/v3/movie"
        else:
            slug = "/api/movie"
        url = config_radarr.url + slug
        querystring = {"apikey": "{}".format(config_radarr.token)}

        response = requests.post(url, json=payload, params=querystring)

        if response.status_code < 400:
            print("| +++ {}: Added to Radarr".format(tmdb_title))
        else:
            print("| --- {}: {} {}".format(tmdb_title,
                                           response.json()[0]['errorMessage'],
                                           response.status_code))