def get_tmdb_data(self, data_in):
        self.otmdb = None
        #logger.debug(str(data_in))

        if self.listData:
            infoLabels = InfoLabels()

            # Datos comunes a todos los listados
            infoLabels = Tmdb().get_infoLabels(infoLabels=infoLabels,
                                               origen=data_in)
            infoLabels["language"] = self.get_language(
                infoLabels["original_language"])
            infoLabels["puntuacion"] = str(
                data_in["vote_average"]) + "/10 (" + str(
                    data_in["vote_count"]) + ")"

            self.from_tmdb = False
            self.result = infoLabels

        else:
            if isinstance(data_in, Item):
                self.from_tmdb = True
                self.get_item_info(data_in)

                # Modo Pelicula
                if not self.item_serie:
                    encontrado = self.get_tmdb_movie_data(self.item_title)
                    if not encontrado:
                        encontrado = self.get_tmdb_tv_data(self.item_title)

                else:
                    encontrado = self.get_tmdb_tv_data(self.item_serie)
                    if not encontrado:
                        encontrado = self.get_tmdb_movie_data(self.item_serie)

            if isinstance(data_in, dict):
                self.from_tmdb = False
                self.result = InfoLabels(data_in)
Exemplo n.º 2
0
def callback_cuadro_completar(item, dict_values):
    # logger.debug(dict_values)
    global dict_default

    if dict_values.get("title", None):
        # Adaptar dict_values a infoLabels validos
        dict_values['mediatype'] = ['movie', 'tvshow'][dict_values['mediatype']]
        for k, v in dict_values.items():
            if k in dict_default and dict_default[k] == dict_values[k]:
                del dict_values[k]

        if isinstance(item.infoLabels, InfoLabels):
            infoLabels = item.infoLabels
        else:
            infoLabels = InfoLabels()

        infoLabels.update(dict_values)
        item.infoLabels = infoLabels

        if item.infoLabels['code']:
            return True

    return False
Exemplo n.º 3
0
def find_and_set_infoLabels(item):
    logger.info()
    # logger.info("item es %s" % item)

    p_dialog = None
    if not item.contentSeason:
        p_dialog = platformtools.dialog_progress_bg(
            config.get_localized_string(60296),
            config.get_localized_string(60293))

    global otvdb_global
    tvdb_result = None

    title = item.contentSerieName
    # Si el titulo incluye el (año) se lo quitamos
    year = scrapertools.find_single_match(title, "^.+?\s*(\(\d{4}\))$")
    if year:
        title = title.replace(year, "").strip()
        item.infoLabels['year'] = year[1:-1]

    if not item.infoLabels.get("tvdb_id"):
        if not item.infoLabels.get("imdb_id"):
            otvdb_global = Tvdb(search=title, year=item.infoLabels['year'])
        else:
            otvdb_global = Tvdb(imdb_id=item.infoLabels.get("imdb_id"))

    elif not otvdb_global or otvdb_global.get_id(
    ) != item.infoLabels['tvdb_id']:
        otvdb_global = Tvdb(tvdb_id=item.infoLabels['tvdb_id'])

    if not item.contentSeason:
        p_dialog.update(50, config.get_localized_string(60296),
                        config.get_localized_string(60295))
    results, info_load = otvdb_global.get_list_results()
    logger.debug("results es %s" % results)

    if not item.contentSeason:
        p_dialog.update(100, config.get_localized_string(60296),
                        config.get_localized_string(60297) % len(results))
        p_dialog.close()

    if len(results) > 1:
        tvdb_result = platformtools.show_video_info(
            results,
            item=item,
            scraper=Tvdb,
            caption=config.get_localized_string(60298) % title)
    elif len(results) > 0:
        tvdb_result = results[0]

    # todo revisar
    if isinstance(item.infoLabels, InfoLabels):
        logger.debug("es instancia de infoLabels")
        infoLabels = item.infoLabels
    else:
        logger.debug("NO ES instancia de infoLabels")
        infoLabels = InfoLabels()

    if tvdb_result:
        infoLabels['tvdb_id'] = tvdb_result['id']
        infoLabels['url_scraper'] = [
            "http://thetvdb.com/index.php?tab=series&id=%s" %
            infoLabels['tvdb_id']
        ]
        if not info_load:
            if otvdb_global.get_id() != infoLabels['tvdb_id']:
                otvdb_global = Tvdb(tvdb_id=infoLabels['tvdb_id'])
            otvdb_global.get_images(infoLabels['tvdb_id'], image="poster")
            otvdb_global.get_images(infoLabels['tvdb_id'], image="fanart")
            otvdb_global.get_tvshow_cast(infoLabels['tvdb_id'])

        item.infoLabels = infoLabels
        set_infoLabels_item(item)

        return True

    else:
        item.infoLabels = infoLabels
        return False
Exemplo n.º 4
0
    def get_infoLabels(self, infoLabels=None, origen=None):
        """
        @param infoLabels: Informacion extra de la pelicula, serie, temporada o capitulo.
        @type infoLabels: dict
        @param origen: Diccionario origen de donde se obtiene los infoLabels, por omision self.result
        @type origen: dict
        @return: Devuelve la informacion extra obtenida del objeto actual. Si se paso el parametro infoLables, el valor
        devuelto sera el leido como parametro debidamente actualizado.
        @rtype: dict
        """

        # TODO revisar
        if infoLabels:
            # logger.debug("es instancia de infoLabels")
            ret_infoLabels = InfoLabels(infoLabels)
        else:
            # logger.debug("NO ES instancia de infoLabels")
            ret_infoLabels = InfoLabels()
            # fix
            ret_infoLabels['mediatype'] = 'tvshow'

        # Iniciar listados
        l_castandrole = ret_infoLabels.get('castandrole', [])

        # logger.debug("self.result %s" % self.result)

        if not origen:
            origen = self.result

        # todo revisar
        # if 'credits' in origen.keys():
        #     dic_origen_credits = origen['credits']
        #     origen['credits_cast'] = dic_origen_credits.get('cast', [])
        #     origen['credits_crew'] = dic_origen_credits.get('crew', [])
        #     del origen['credits']

        items = origen.items()

        for k, v in items:
            if not v:
                continue

            if k == 'overview':
                ret_infoLabels['plot'] = v

            elif k == 'runtime':
                ret_infoLabels['duration'] = int(v) * 60

            elif k == 'firstAired':
                ret_infoLabels['year'] = int(v[:4])
                ret_infoLabels['premiered'] = v.split("-")[2] + "/" + v.split(
                    "-")[1] + "/" + v.split("-")[0]

            # todo revisar
            # elif k == 'original_title' or k == 'original_name':
            #     ret_infoLabels['originaltitle'] = v

            elif k == 'siteRating':
                ret_infoLabels['rating'] = float(v)

            elif k == 'siteRatingCount':
                ret_infoLabels['votes'] = v

            elif k == 'status':
                # se traduce los estados de una serie
                ret_infoLabels['status'] = DICT_STATUS.get(v, v)

            # no soy partidario de poner la cadena como studio pero es como lo hace el scraper de manera genérica
            elif k == 'network':
                ret_infoLabels['studio'] = v

            elif k == 'image_poster':
                # obtenemos la primera imagen de la lista
                ret_infoLabels['thumbnail'] = HOST_IMAGE + v[0]['fileName']

            elif k == 'image_fanart':
                # obtenemos la primera imagen de la lista
                ret_infoLabels['fanart'] = HOST_IMAGE + v[0]['fileName']

            # # no disponemos de la imagen de fondo
            # elif k == 'banner':
            #     ret_infoLabels['fanart'] = HOST_IMAGE + v

            elif k == 'id':
                ret_infoLabels['tvdb_id'] = v

            elif k == 'imdbId':
                ret_infoLabels['imdb_id'] = v
                # no se muestra
                # ret_infoLabels['code'] = v

            elif k in "rating":
                # traducimos la clasificación por edades (content rating system)
                ret_infoLabels['mpaa'] = DICT_MPAA.get(v, v)

            elif k in "genre":
                genre_list = ""
                for index, i in enumerate(v):
                    if index > 0:
                        genre_list += ", "

                    # traducimos los generos
                    genre_list += DICT_GENRE.get(i, i)

                ret_infoLabels['genre'] = genre_list

            elif k == 'seriesName':  # or k == 'name' or k == 'title':
                # if len(origen.get('aliases', [])) > 0:
                #     ret_infoLabels['title'] = v + " " + origen.get('aliases', [''])[0]
                # else:
                #     ret_infoLabels['title'] = v
                # logger.info("el titulo es %s " % ret_infoLabels['title'])
                ret_infoLabels['title'] = v

            elif k == 'cast':
                dic_aux = dict(
                    (name, character) for (name, character) in l_castandrole)
                l_castandrole.extend([(p['name'], p['role']) for p in v
                                      if p['name'] not in dic_aux.keys()])

            else:
                logger.debug("Atributos no añadidos: %s=%s" % (k, v))
                pass

        # Ordenar las listas y convertirlas en str si es necesario
        if l_castandrole:
            ret_infoLabels['castandrole'] = l_castandrole

        logger.debug("ret_infoLabels %s" % ret_infoLabels)

        return ret_infoLabels
Exemplo n.º 5
0
    def get_infoLabels(self, infoLabels=None, origen=None):
        """
        @param infoLabels: Extra information about the movie, series, season or chapter.
        @type infoLabels: dict
        @param origen: Diccionario origen de donde se obtiene los infoLabels, por omision self.result
        @type origen: dict
        @return: Returns the extra information obtained from the current object. If the infoLables parameter was passed,
        the value returned will be read as a parameter duly updated.
        @rtype: dict
        """

        if infoLabels:
            # logger.debug("es instancia de infoLabels")
            ret_infoLabels = InfoLabels(infoLabels)
        else:
            # logger.debug("NO ES instancia de infoLabels")
            ret_infoLabels = InfoLabels()
            # fix
            ret_infoLabels['mediatype'] = 'tvshow'

        # Start Listings
        l_castandrole = ret_infoLabels.get('castandrole', [])

        # logger.debug("self.result %s" % self.result)

        if not origen:
            origen = self.result

        # todo revisar
        # if 'credits' in origen.keys():
        #     dic_origen_credits = origen['credits']
        #     origen['credits_cast'] = dic_origen_credits.get('cast', [])
        #     origen['credits_crew'] = dic_origen_credits.get('crew', [])
        #     del origen['credits']

        items = list(origen.items())

        for k, v in items:
            if not v:
                continue

            if k == 'overview':
                ret_infoLabels['plot'] = v

            elif k == 'runtime':
                ret_infoLabels['duration'] = int(v) * 60

            elif k == 'firstAired':
                ret_infoLabels['year'] = int(v[:4])
                ret_infoLabels['premiered'] = v.split("-")[2] + "/" + v.split(
                    "-")[1] + "/" + v.split("-")[0]

            # todo revisar
            # elif k == 'original_title' or k == 'original_name':
            #     ret_infoLabels['originaltitle'] = v

            elif k == 'siteRating':
                ret_infoLabels['rating'] = float(v)

            elif k == 'siteRatingCount':
                ret_infoLabels['votes'] = v

            elif k == 'status':
                # se traduce los estados de una serie
                ret_infoLabels['status'] = v

            # I am not in favor of putting the chain as a studio but it is how the scraper does it in a generic way
            elif k == 'network':
                ret_infoLabels['studio'] = v

            elif k == 'image_poster':
                # obtenemos la primera imagen de la lista
                ret_infoLabels['thumbnail'] = HOST_IMAGE + v[0]['fileName']

            elif k == 'image_fanart':
                # obtenemos la primera imagen de la lista
                ret_infoLabels['fanart'] = HOST_IMAGE + v[0]['fileName']

            # # no disponemos de la imagen de fondo
            # elif k == 'banner':
            #     ret_infoLabels['fanart'] = HOST_IMAGE + v

            elif k == 'id':
                ret_infoLabels['tvdb_id'] = v

            elif k == 'imdbId':
                ret_infoLabels['imdb_id'] = v
                # no se muestra
                # ret_infoLabels['code'] = v

            elif k in "rating":
                # we translate the age rating (content rating system)
                ret_infoLabels['mpaa'] = v

            elif k in "genre":
                genre_list = ""
                for index, i in enumerate(v):
                    if index > 0:
                        genre_list += ", "

                    # traducimos los generos
                    genre_list += i

                ret_infoLabels['genre'] = genre_list

            elif k == 'seriesName':  # or k == 'name' or k == 'title':
                # if len(origen.get('aliases', [])) > 0:
                #     ret_infoLabels['title'] = v + " " + origen.get('aliases', [''])[0]
                # else:
                #     ret_infoLabels['title'] = v
                # logger.info("el titulo es %s " % ret_infoLabels['title'])
                ret_infoLabels['title'] = v

            elif k == 'cast':
                dic_aux = dict(
                    (name, character) for (name, character) in l_castandrole)
                l_castandrole.extend([(p['name'], p['role']) for p in v
                                      if p['name'] not in list(dic_aux.keys())
                                      ])

            else:
                logger.debug("Attributes not added: %s=%s" % (k, v))
                pass

        # Sort the lists and convert them to str if necessary
        if l_castandrole:
            ret_infoLabels['castandrole'] = l_castandrole

        logger.debug("ret_infoLabels %s" % ret_infoLabels)

        return ret_infoLabels
Exemplo n.º 6
0
def find_and_set_infoLabels(item):
    logger.info()
    # logger.info("item es %s" % item)

    p_dialog = None
    if not item.contentSeason:
        p_dialog = platformtools.dialog_progress_bg(
            "Cercando informazioni della serie", "Attendere prego...")

    global otvdb_global
    tvdb_result = None

    title = item.contentSerieName
    # Si el titulo incluye el (año) se lo quitamos
    year = scrapertools.find_single_match(title, "^.+?\s*(\(\d{4}\))$")
    if year:
        title = title.replace(year, "").strip()
        item.infoLabels['year'] = year[1:-1]

    if not item.infoLabels.get("tvdb_id"):
        if not item.infoLabels.get("imdb_id"):
            otvdb_global = Tvdb(search=title, year=item.infoLabels['year'])
        else:
            otvdb_global = Tvdb(imdb_id=item.infoLabels.get("imdb_id"))

    elif not otvdb_global or otvdb_global.get_id(
    ) != item.infoLabels['tvdb_id']:
        otvdb_global = Tvdb(tvdb_id=item.infoLabels['tvdb_id']
                            )  # , tipo=tipo_busqueda, idioma_busqueda="es")

    if not item.contentSeason:
        p_dialog.update(50, "Cercando informazioni della serie",
                        "Ottenendo risultati...")
    results = otvdb_global.get_list_results()
    logger.debug("results es %s" % results)

    if not item.contentSeason:
        p_dialog.update(100, "Cercando informazioni della serie",
                        "Trovate %s possibili corrispondenze" % len(results))
        p_dialog.close()

    if len(results) > 1:
        tvdb_result = platformtools.show_video_info(
            results,
            item=item,
            scraper=Tvdb,
            caption="[%s]: Selezionare la serie corretta" % title)
    elif len(results) > 0:
        tvdb_result = results[0]

    # todo revisar
    if isinstance(item.infoLabels, InfoLabels):
        logger.debug("es instancia de infoLabels")
        infoLabels = item.infoLabels
    else:
        logger.debug("NO ES instancia de infoLabels")
        infoLabels = InfoLabels()

    if tvdb_result:
        infoLabels['tvdb_id'] = tvdb_result['id']
        infoLabels['url_scraper'] = [
            "http://thetvdb.com/index.php?tab=series&id=%s" %
            infoLabels['tvdb_id']
        ]
        if not info_load:
            if otvdb_global.get_id() != infoLabels['tvdb_id']:
                otvdb_global = Tvdb(tvdb_id=infoLabels['tvdb_id'])
            otvdb_global.get_images(infoLabels['tvdb_id'], image="poster")
            otvdb_global.get_images(infoLabels['tvdb_id'], image="fanart")
            otvdb_global.get_tvshow_cast(infoLabels['tvdb_id'])

        item.infoLabels = infoLabels
        set_infoLabels_item(item)

        return True

    else:
        item.infoLabels = infoLabels
        return False
Exemplo n.º 7
0
    def get_infoLabels(self, infoLabels=None, origen=None):
        """
            :param infoLabels: Informacion extra del anime
            :type infoLabels: Dict

            :param origen: Diccionario desde donde se obtienen los infoLabels, por defecto self.result
            :type origen: Dict

            :return: Devuelve la información extra obtenida del objeto actual. Si se paso el parametro infoLabels, el valor
            devuelto sera el leído como parámetro debidamente actualizado.
            :rtype: Dict
        """
        logger.info()

        if not "request_hash" in self.result:
            self.__by_id()

        if infoLabels:
            ret_infoLabels = InfoLabels(infoLabels)
        else:
            ret_infoLabels = InfoLabels()

        if not origen:
            origen = self.result

        items = list(origen.items())

        # Información de temporada/episodio
        if isinstance(ret_infoLabels.get('season'), int):
            if self.temporada.get(ret_infoLabels['season']):
                # Si hay datos cargados de la temporada indicada
                episodio = -1
                if ret_infoLabels.get('episode'):
                    episodio = ret_infoLabels['episode']

                items.extend(list(self.get_episodio(ret_infoLabels['season'], episodio).items()))

        for key, value in items:
            if not value:
                continue
            elif isinstance(value, str):
                value = re.sub(r"\n|\r|\t", "", value)
                # fix
                if value == "None":
                    continue

            if key == 'synopsis':
                ret_infoLabels['plot'] = value

            elif key == 'type':
                ret_infoLabels['mediatype'] = self.get_contentType(origen)
                ret_infoLabels['type'] = value
                if ret_infoLabels['mediatype'] == "movie":
                    ret_infoLabels.pop("tvshowtitle", "")

            elif key == 'duration':
                duration = 0
                time = scrapertools.find_single_match(value, "(?:(\d+).hr.+?|)(\d+).min")
                if time[0]:
                    duration += int(time[0] * 60)
                duration += int(time[1])
                ret_infoLabels['duration'] = int(duration * 60)

            elif key in ['aired', "start_date"]:
                ret_infoLabels['year'] = self.get_airdate(origen).split("/")[0]
                ret_infoLabels['release_date'] = self.get_airdate(origen)
                ret_infoLabels['aired'] = ret_infoLabels['release_date']
                ret_infoLabels['premiered'] = ret_infoLabels['release_date']

            elif key == 'image_url':
                ret_infoLabels['thumbnail'] = value

            elif key == 'background' and value:
                ret_infoLabels['fanart'] = value

            elif key == 'mal_id':
                ret_infoLabels['code'] = value
                ret_infoLabels['mal_id'] = value
                ret_infoLabels['id'] = value

            elif key == 'genres':
                ret_infoLabels['genre'] = self.get_generos(origen)

            elif key == 'name' or key == 'title':
                ret_infoLabels['title'] = value

            elif key == 'studios':
                ret_infoLabels['studio'] = ", ".join(i['name'] for i in value)

            elif key == 'trailer_url':
                ret_infoLabels['trailer'] = value

            elif key in ['title_japanese']:
                ret_infoLabels['originaltitle'] = value

            elif key == 'score':
                ret_infoLabels['rating'] = float(value)

            elif key == 'scored_by':
                ret_infoLabels['votes'] = value

            elif isinstance(value, str) or isinstance(value, int) or isinstance(value, float):
                ret_infoLabels[key] = value

            else:
                # logger.debug("Atributos no añadidos: " + key +'= '+ str(v))
                pass

        if ret_infoLabels["mediatype"] == "movie" and "episodes" in ret_infoLabels:
            ret_infoLabels.pop("episodes", "")

        return ret_infoLabels
Exemplo n.º 8
0
def find_and_set_infoLabels(item):
    logger.info()
    # logger.info("item es %s" % item)

    p_dialog = None
    if not item.contentSeason:
        p_dialog = platformtools.dialog_progress_bg(
            "Buscando información de la serie", "Espere por favor...")

    global otvdb_global
    tvdb_result = None

    title = item.contentSerieName
    # Si el titulo incluye el (año) se lo quitamos
    year = scrapertools.find_single_match(title, "^.+?\s*(\(\d{4}\))$")
    if year:
        title = title.replace(year, "").strip()
        item.infoLabels['year'] = year[1:-1]

    if not item.infoLabels.get("tvdb_id"):
        if not item.infoLabels.get("imdb_id"):
            otvdb_global = Tvdb(search=title, year=item.infoLabels['year'])
        else:
            otvdb_global = Tvdb(imdb_id=item.infoLabels.get("imdb_id"))

    elif not otvdb_global or otvdb_global.get_id(
    ) != item.infoLabels['tvdb_id']:
        otvdb_global = Tvdb(tvdb_id=item.infoLabels['tvdb_id'])

    if not item.contentSeason:
        p_dialog.update(50, "Buscando información de la serie",
                        "Obteniendo resultados...")
    results, info_load = otvdb_global.get_list_results()
    logger.debug("results es %s" % results)

    if not item.contentSeason:
        p_dialog.update(100, "Buscando información de la serie",
                        "Encontrados %s posibles coincidencias" % len(results))
        p_dialog.close()

    if len(results) > 1:
        logger.debug('TODO platformtools.show_video_info')
        # ~ tvdb_result = platformtools.show_video_info(results, item=item, scraper=Tvdb,
        # ~ caption="[%s]: Selecciona la serie correcta" % title)
    elif len(results) > 0:
        tvdb_result = results[0]

    # todo revisar
    if isinstance(item.infoLabels, InfoLabels):
        logger.debug("es instancia de infoLabels")
        infoLabels = item.infoLabels
    else:
        logger.debug("NO ES instancia de infoLabels")
        infoLabels = InfoLabels()

    if tvdb_result:
        infoLabels['tvdb_id'] = tvdb_result['id']
        infoLabels['url_scraper'] = [
            "https://thetvdb.com/index.php?tab=series&id=%s" %
            infoLabels['tvdb_id']
        ]
        if not info_load:
            if otvdb_global.get_id() != infoLabels['tvdb_id']:
                otvdb_global = Tvdb(tvdb_id=infoLabels['tvdb_id'])
            otvdb_global.get_images(infoLabels['tvdb_id'], image="poster")
            otvdb_global.get_images(infoLabels['tvdb_id'], image="fanart")
            otvdb_global.get_tvshow_cast(infoLabels['tvdb_id'])

        item.infoLabels = infoLabels
        set_infoLabels_item(item)

        return True

    else:
        item.infoLabels = infoLabels
        return False
Exemplo n.º 9
0
def find_and_set_infoLabels(item):
    logger.info()
    global omal_global
    mal_result = None

    tipos_busqueda_validos = ["ova", "ona", "special", "movie", "tv"]
    if item.contentType in tipos_busqueda_validos:
        tipo_busqueda = item.contentType
    elif item.contentType in ["tvshow"]:
        tipo_busqueda = "tv"
    else:
        tipo_busqueda = ""

    if tipo_busqueda in ["movie", "special"] or item.contentTitle:
        tipo_contenido = config.get_localized_string(70283)
        title = item.contentTitle
    elif tipo_busqueda in ["tv"] or item.contentSerieName:
        tipo_contenido = config.get_localized_string(60245)
        title = item.contentSerieName
    else:
        tipo_contenido = ""
        title = item.title

    # Si el titulo incluye el (año) se lo quitamos
    year = scrapertools.find_single_match(title, "^.+?\s*(\(\d{4}\))$")
    if year:
        title = title.replace(year, "").strip()
        item.infoLabels['year'] = year[1:-1]
    
    # Si no tenemos ID de MAL, buscamos por texto
    if not item.infoLabels.get("mal_id"):
        omal_global = MAL(texto_buscado=title, tipo=tipo_busqueda, year=item.infoLabels['year'])

    # Si hay ID de MAL pero no se ha buscado o el ID de MAL no coincide con el del resultado, buscamos por ID
    elif not omal_global or str(omal_global.result.get("mal_id")) != item.infoLabels['mal_id']:
        omal_global = MAL(id_mal=item.infoLabels['mal_id'])

    results = omal_global.get_results_list()

    # Si hay más de un resultado, preguntamos cuál es el correcto
    # Esta acción ocurrirá siempre que no se provea un mal_id (por el contenido relacionado que devuelve)
    if len(results) > 1:
        from platformcode import platformtools
        mal_result = platformtools.show_video_info(results, item=item, caption=config.get_localized_string(60247) % (title, tipo_contenido))

    # Si solo hay un resultado, lo seleccionamos
    elif len(results) > 0:
        mal_result = results[0]

    # Comprobaciones
    if isinstance(item.infoLabels, InfoLabels):
        infoLabels = item.infoLabels
    else:
        infoLabels = InfoLabels()

    if mal_result:
        infoLabels['mal_id'] = mal_result['mal_id']
        item.infoLabels = infoLabels
        set_infoLabels_item(item)
        return True

    else:
        item.infoLabels = infoLabels
        return False
Exemplo n.º 10
0
    def get_infoLabels(self, infoLabels=None, origen=None):
        """
        @param infoLabels: Extra information about the movie, series, season or chapter.
        @type infoLabels: dict
        @param origen: Diccionario origen de donde se obtiene los infoLabels, por omision self.result
        @type origen: dict
        @return: Returns the extra information obtained from the current object. If the infoLables parameter was passed,
        the value returned will be read as a parameter duly updated.
        @rtype: dict
        """

        if infoLabels:
            # logger.debug("es instancia de infoLabels")
            ret_infoLabels = InfoLabels(infoLabels)
        else:
            # logger.debug("NO ES instancia de infoLabels")
            ret_infoLabels = InfoLabels()
            # fix
            ret_infoLabels['mediatype'] = 'tvshow'

        # Start Listings
        l_castandrole = ret_infoLabels.get('castandrole', [])

        # logger.debug("self.result %s" % self.result)

        if not origen:
            origen = self.result

        ret_infoLabels['title'] = origen['seriesName']
        ret_infoLabels['tvdb_id'] = origen['id']
        thumbs = requests.get(HOST + '/series/' + str(origen['id']) + '/images/query?keyType=poster').json()
        if 'data' in thumbs:
            ret_infoLabels['thumbnail'] = HOST_IMAGE + thumbs['data'][0]['fileName']
        elif 'poster' in origen and origen['poster']:
            ret_infoLabels['thumbnail'] = HOST_IMAGE + origen['poster']
        fanarts = requests.get(HOST + '/series/' + str(origen['id']) + '/images/query?keyType=fanart').json()
        if 'data' in fanarts:
            ret_infoLabels['fanart'] = HOST_IMAGE + fanarts['data'][0]['fileName']
        elif 'fanart' in origen and origen['fanart']:
            ret_infoLabels['fanart'] = HOST_IMAGE + origen['fanart']
        if 'overview' in origen and origen['overview']:
            ret_infoLabels['plot'] = origen['overview']
        if 'duration' in origen and origen['duration']:
            ret_infoLabels['duration'] = int(origen['duration']) * 60
        if 'firstAired' in origen and origen['firstAired']:
            ret_infoLabels['year'] = int(origen['firstAired'][:4])
            ret_infoLabels['premiered'] = origen['firstAired'].split("-")[2] + "/" + origen['firstAired'].split("-")[1] + "/" + origen['firstAired'].split("-")[0]
        if 'siteRating' in origen and origen['siteRating']:
            ret_infoLabels['rating'] = float(origen['siteRating'])
        if 'siteRatingCount' in origen and origen['siteRatingCount']:
            ret_infoLabels['votes'] = origen['siteRatingCount']
        if 'status' in origen and origen['status']:
            ret_infoLabels['status'] = origen['status']
        if 'network' in origen and origen['network']:
            ret_infoLabels['studio'] = origen['network']
        if 'imdbId' in origen and origen['rating']:
            ret_infoLabels['imdb_id'] = origen['imdbId']
        if 'rating' in origen and origen['rating']:
            ret_infoLabels['mpaa'] = origen['rating']
        if 'genre' in origen and origen['genre']:
            for genre in origen['genre']:
                genre_list = ""
                genre_list += genre + ', '
                ret_infoLabels['genre'] = genre_list.rstrip(', ')
        if 'cast' in origen and origen['cast']:
            dic_aux = dict((name, character) for (name, character) in l_castandrole)
            l_castandrole.extend([(p['name'], p['role']) for p in origen['cast'] if p['name'] not in list(dic_aux.keys())])
            ret_infoLabels['castandrole'] = l_castandrole


        return ret_infoLabels
Exemplo n.º 11
0
def find_and_set_infoLabels(item):
    logger.debug()
    # from core.support import dbg;dbg()
    # logger.debug("item es %s" % item)

    p_dialog = None
    if not item.contentSeason:
        p_dialog = platformtools.dialog_progress_bg(config.get_localized_string(60296), config.get_localized_string(60293))

    global otvdb_global
    tvdb_result = None

    title = item.contentSerieName
    # If the title includes the (year) we will remove it
    year = scrapertools.find_single_match(title, r"^.+?\s*(\(\d{4}\))$")
    if year:
        title = title.replace(year, "").strip()
        item.infoLabels['year'] = year[1:-1]

    if item.infoLabels.get("tvdb_id", '') in ['', 'None']:
        if item.infoLabels['year']:
            otvdb_global = Tvdb(search=title, year=item.infoLabels['year'])
        elif item.infoLabels.get("imdb_id"):
            otvdb_global = Tvdb(imdb_id=item.infoLabels.get("imdb_id"))
        else:
            otvdb_global = Tvdb(search=title)

    elif not otvdb_global or otvdb_global.get_id() != item.infoLabels['tvdb_id']:
        otvdb_global = Tvdb(tvdb_id=item.infoLabels['tvdb_id'])

    if not item.contentSeason:
        p_dialog.update(50, config.get_localized_string(60296) + '\n' + config.get_localized_string(60295))
    results, info_load = otvdb_global.get_list_results()
    logger.debug("results: %s" % results)

    if not item.contentSeason:
        p_dialog.update(100, config.get_localized_string(60296) + '\n' + config.get_localized_string(60297) % len(results))
        p_dialog.close()

    if len(results) > 1:
        tvdb_result = platformtools.show_video_info(results, item=item, scraper=Tvdb, caption=config.get_localized_string(60298) % title)
        # if not tvdb_result:
        #     res =  platformtools.dialog_info(item, 'tvdb')
        #     if not res.exit: return find_and_set_infoLabels(res)
    elif len(results) > 0:
        tvdb_result = results[0]

    # else:
    #     res =  platformtools.dialog_info(item, 'tvdb')
    #     if not res.exit: return find_and_set_infoLabels(res)

    # todo revisar
    if isinstance(item.infoLabels, InfoLabels):
        logger.debug("is an instance of infoLabels")
        infoLabels = item.infoLabels
    else:
        logger.debug("NOT an instance of infoLabels")
        infoLabels = InfoLabels()

    if tvdb_result:
        infoLabels['tvdb_id'] = tvdb_result['id']
        infoLabels['url_scraper'] = ["http://thetvdb.com/index.php?tab=series&id=%s" % infoLabels['tvdb_id']]
        if not info_load:
            if otvdb_global.get_id() != infoLabels['tvdb_id']:
                otvdb_global = Tvdb(tvdb_id=infoLabels['tvdb_id'])
            otvdb_global.get_images(infoLabels['tvdb_id'], image="poster")
            otvdb_global.get_images(infoLabels['tvdb_id'], image="fanart")
            otvdb_global.get_tvshow_cast(infoLabels['tvdb_id'])

        item.infoLabels = infoLabels
        set_infoLabels_item(item)

        return True

    else:
        item.infoLabels = infoLabels
        return False
Exemplo n.º 12
0
def find_and_set_infoLabels(item):
    logger.info()
    logger.info("item es %s" % item)

    if not item.contentSeason:
        from platformcode import platformtools
        p_dialog = platformtools.dialog_progress_bg(
            "Buscando información de la serie", "Espere por favor...")

    global otvdb_global
    tvdb_result = None

    title = item.contentSerieName
    # Si el titulo incluye el (año) se lo quitamos
    year = scrapertools.find_single_match(title, "^.+?\s*(\(\d{4}\))$")
    if year:
        title = title.replace(year, "").strip()
        item.infoLabels['year'] = year[1:-1]

    if not item.infoLabels.get("tvdb_id"):
        if not item.infoLabels.get("imdb_id"):
            otvdb_global = Tvdb(search=title, year=item.infoLabels['year'])
        else:
            otvdb_global = Tvdb(imdb_id=item.infoLabels.get("imdb_id"))

    elif not otvdb_global or otvdb_global.result.get(
            "id") != item.infoLabels['tvdb_id']:
        otvdb_global = Tvdb(tvdb_id=item.infoLabels['tvdb_id']
                            )  # , tipo=tipo_busqueda, idioma_busqueda="es")

    if not item.contentSeason:
        p_dialog.update(50, "Buscando información de la serie",
                        "Obteniendo resultados...")
    results = otvdb_global.get_list_results()
    logger.debug("results es %s" % results)

    if not item.contentSeason:
        p_dialog.update(100, "Buscando información de la serie",
                        "Encontrados %s posibles coincidencias" % len(results))
        p_dialog.close()

    if len(results) > 1:
        tvdb_result = platformtools.show_video_info(
            results,
            item=item,
            scraper=Tvdb,
            caption="[%s]: Selecciona la serie correcta" % title)
    elif len(results) > 0:
        tvdb_result = results[0]

    # todo revisar
    if isinstance(item.infoLabels, InfoLabels):
        logger.debug("es instancia de infoLabels")
        infoLabels = item.infoLabels
    else:
        logger.debug("NO ES instancia de infoLabels")
        infoLabels = InfoLabels()

    if tvdb_result:
        infoLabels['tvdb_id'] = tvdb_result['id']
        item.infoLabels = infoLabels
        set_infoLabels_item(item)

        return True

    else:
        item.infoLabels = infoLabels
        return False
Exemplo n.º 13
0
def listado(item):
    logger.info()
    itemlist = []

    try:
        data_dict = jsontools.load_json(httptools.downloadpage(item.url).data)
    except:
        return itemlist  # Devolvemos lista vacia

    #Filtrado y busqueda
    if item.filtro:
        for i in data_dict["result"][:]:
            if (item.filtro[0] == "genero" and item.filtro[1] not in i['genre'].lower()) or \
                (item.filtro[0] == "search" and item.filtro[1] not in i['title'].lower()):
                data_dict["result"].remove(i)

    if not item.page:
        item.page = 0

    offset = int(item.page) * 30
    limit = offset + 30

    for i in data_dict["result"][offset:limit]:
        infoLabels = InfoLabels()
        idioma = ''

        if item.extra == "movie":
            action = "findvideos"
            #viewcontent = 'movies'
            infoLabels["title"] = i["title"]
            title = '%s (%s)' % (i["title"], i['year'])
            url = urlparse.urljoin(__url_base__,
                                   "ver-pelicula-online/" + str(i["id"]))

        elif item.extra == "series":
            action = "get_temporadas"
            #viewcontent = 'seasons'
            title = i["title"]
            infoLabels['tvshowtitle'] = i["title"]
            url = urlparse.urljoin(__url_base__,
                                   "episodio-online/" + str(i["id"]))

        else:  #item.extra=="series_novedades":
            action = "findvideos"
            #viewcontent = 'episodes'
            infoLabels['tvshowtitle'] = i["title"]
            infoLabels['season'] = i['season']
            infoLabels['episode'] = i['episode'].zfill(2)
            flag = scrapertools.find_single_match(i["label"],
                                                  '(\s*\<img src=.*\>)')
            idioma = i["label"].replace(flag, "")
            title = '%s %sx%s (%s)' % (i["title"], infoLabels["season"],
                                       infoLabels["episode"], idioma)
            url = urlparse.urljoin(__url_base__,
                                   "episodio-online/" + str(i["id"]))

        if i.has_key("poster") and i["poster"]:
            thumbnail = re.compile("/w\d{3}/").sub("/w500/", i["poster"])
        else:
            thumbnail = item.thumbnail
        if i.has_key("background") and i["background"]:
            fanart = i["background"]
        else:
            fanart = item.fanart

        # Rellenamos el diccionario de infoLabels
        infoLabels['title_id'] = i[
            'id']  # title_id: identificador de la pelicula/serie en pepecine.com
        if i['genre']: infoLabels['genre'] = i['genre']
        if i['year']: infoLabels['year'] = i['year']
        #if i['tagline']: infoLabels['plotoutline']=i['tagline']
        if i['plot']:
            infoLabels['plot'] = i['plot']
        else:
            infoLabels['plot'] = ""
        if i['runtime']: infoLabels['duration'] = int(i['runtime']) * 60
        if i['imdb_rating']:
            infoLabels['rating'] = i['imdb_rating']
        elif i['tmdb_rating']:
            infoLabels['rating'] = i['tmdb_rating']
        if i['tmdb_id']: infoLabels['tmdb_id'] = i['tmdb_id']
        if i['imdb_id']: infoLabels['imdb_id'] = i['imdb_id']

        newItem = Item(
            channel=item.channel,
            action=action,
            title=title,
            url=url,
            extra=item.extra,
            fanart=fanart,
            thumbnail=thumbnail,
            viewmode="movie_with_plot",  #viewcontent=viewcontent,
            language=idioma,
            text_color="0xFFFFCE9C",
            infoLabels=infoLabels)
        newItem.year = i['year']
        newItem.contentTitle = i['title']
        if 'season' in infoLabels and infoLabels['season']:
            newItem.contentSeason = infoLabels['season']
        if 'episode' in infoLabels and infoLabels['episode']:
            newItem.contentEpisodeNumber = infoLabels['episode']
        itemlist.append(newItem)

    # Obtenemos los datos basicos mediante multihilos
    tmdb.set_infoLabels(itemlist)

    # Paginacion
    if len(data_dict["result"]) > limit:
        itemlist.append(
            item.clone(text_color="0xFF994D00",
                       title=">> Pagina siguiente >>",
                       page=item.page + 1))

    return itemlist
Exemplo n.º 14
0
def find_and_set_infoLabels(item):
    """
    función que se llama para buscar y setear los infolabels
    :param item:
    :return:
    """

    global scraper_global
    logger.debug("item:\n" + item.tostring('\n'))

    params = {}

    if item.contentType == "movie":
        tipo_contenido = "pelicula"
        title = item.contentTitle
        # get scraper pelis
        scraper = Tmdb()
        # para tmdb
        tipo_busqueda = "movie"

    else:
        tipo_contenido = "serie"
        title = item.contentSerieName
        # get scraper series
        scraper = Tmdb()
        # para tmdb
        tipo_busqueda = "tv"

    # esto ya está en el scraper tmdb
    # title = re.sub('\[\\\?(B|I|COLOR)\s?[^\]]*\]', '', title)

    # Si el titulo incluye el (año) se lo quitamos
    year = scrapertools.find_single_match(title, "^.+?\s*(\(\d{4}\))$")
    if year:
        title = title.replace(year, "").strip()
        item.infoLabels['year'] = year[1:-1]

    scraper_result = None
    results = []
    while not scraper_result:
        # para tmdb
        if isinstance(scraper, Tmdb):
            logger.debug("scraper es Tmbdb")
            params["texto_buscado"] = title
            params["tipo"] = tipo_busqueda
            params["year"] = item.infoLabels['year']

        if not results:
            if not item.infoLabels.get("tmdb_id"):
                if not item.infoLabels.get("imdb_id"):
                    scraper_global = scraper(**params)
                else:
                    logger.info("tiene imdb")
                    # para tmdb
                    if isinstance(scraper, Tmdb):
                        params["external_id"] = item.infoLabels.get("imdb_id")
                        params["external_source"] = "imdb_id"

                    scraper_global = scraper(**params)

            elif not scraper_global or scraper_global.result.get(
                    "id") != item.infoLabels['tmdb_id']:
                # para tmdb
                if isinstance(scraper, Tmdb):
                    params["id_Tmdb"] = item.infoLabels['tmdb_id']
                    params["idioma_busqueda"] = "es"

                scraper_global = scraper(**params)

            results = scraper_global.get_list_resultados()

        if len(results) > 1:
            scraper_result = platformtools.show_video_info(
                results,
                item=item,
                scraper=scraper,
                caption="[%s]: Selecciona la %s correcta" %
                (title, tipo_contenido))

        elif len(results) > 0:
            scraper_result = results[0]

        if scraper_result is None:
            index = -1
            if tipo_contenido == "serie":
                # Si no lo encuentra la serie por si solo, presentamos una lista de opciones
                opciones = ["Introducir otro nombre", "Buscar en TheTvDB.com"]
                index = platformtools.dialog_select(
                    "%s no encontrada" % tipo_contenido.capitalize(), opciones)

            elif platformtools.dialog_yesno(
                    "Película no encontrada",
                    "No se ha encontrado la película:", title,
                    '¿Desea introducir otro nombre?'):
                index = 0

            if index < 0:
                logger.debug(
                    "he pulsado 'cancelar' en la ventana '%s no encontrada'" %
                    tipo_contenido.capitalize())
                break

            if index == 0:  # "Introducir otro nombre"
                # Pregunta el titulo
                it = platformtools.dialog_input(
                    title,
                    "Introduzca el nombre de la %s a buscar" % tipo_contenido)
                if it is not None:
                    title = it
                    item.infoLabels['year'] = ""
                    # reseteamos los resultados
                    results = []
                else:
                    logger.debug(
                        "he pulsado 'cancelar' en la ventana 'introduzca el nombre correcto'"
                    )
                    break

            if index == 1:  # "Buscar en TheTvDB.com"
                results = tvdb_series_by_title(title)

    if isinstance(item.infoLabels, InfoLabels):
        infoLabels = item.infoLabels
    else:
        infoLabels = InfoLabels()

    if scraper_result:
        if 'id' in scraper_result:
            # resultados obtenidos de tmdb
            infoLabels['tmdb_id'] = scraper_result['id']
            infoLabels[
                'url_scraper'] = "https://www.themoviedb.org/tv/%s" % infoLabels[
                    'tmdb_id']
            item.infoLabels = infoLabels
            tmdb.set_infoLabels_item(item)

        elif 'tvdb_id' in scraper_result:
            # resultados obtenidos de tvdb
            infoLabels.update(scraper_result)
            item.infoLabels = infoLabels

        # logger.debug("item:\n" + item.tostring('\n'))
        return True
    else:
        item.infoLabels = infoLabels
        return False