Ejemplo n.º 1
0
            except Exception, ex:
                logger.error("Error al obtener los episodios de: %s" %
                             serie.show)
                template = "An exception of type %s occured. Arguments:\n%r"
                message = template % (type(ex).__name__, ex.args)
                logger.error(message)

        else:
            logger.debug("Canal %s no activo no se actualiza" % serie.channel)

    #Sincronizamos los episodios vistos desde la videoteca de Kodi con la de Alfa
    try:
        if config.is_xbmc():  #Si es Kodi, lo hacemos
            from platformcode import xbmc_videolibrary
            xbmc_videolibrary.mark_content_as_watched_on_alfa(path +
                                                              '/tvshow.nfo')
    except:
        logger.error(traceback.format_exc())

    return insertados_total > 0


def check_for_update(overwrite=True):
    logger.info("Actualizando series...")
    p_dialog = None
    serie_actualizada = False
    update_when_finished = False
    hoy = datetime.date.today()
    estado_verify_playcount_series = False

    try:
Ejemplo n.º 2
0
def check_for_update(overwrite=True):
    logger.info("Actualizando series...")
    p_dialog = None
    serie_actualizada = False
    update_when_finished = False
    hoy = datetime.date.today()
    estado_verify_playcount_series = False

    try:
        if config.get_setting("update", "videolibrary") != 0 or overwrite:
            config.set_setting("updatelibrary_last_check",
                               hoy.strftime('%Y-%m-%d'), "videolibrary")

            heading = config.get_localized_string(60389)
            p_dialog = platformtools.dialog_progress_bg(
                config.get_localized_string(20000), heading)
            p_dialog.update(0, '')
            show_list = []

            for path, folders, files in filetools.walk(
                    videolibrarytools.TVSHOWS_PATH):
                show_list.extend([
                    filetools.join(path, f) for f in files if f == "tvshow.nfo"
                ])

            if show_list:
                t = float(100) / len(show_list)

            for i, tvshow_file in enumerate(show_list):
                head_nfo, serie = videolibrarytools.read_nfo(tvshow_file)
                path = filetools.dirname(tvshow_file)

                logger.info("serie=" + serie.contentSerieName)
                p_dialog.update(int(math.ceil((i + 1) * t)), heading,
                                serie.contentSerieName)

                #Verificamos el estado del serie.library_playcounts de la Serie por si está incompleto
                try:
                    estado = False
                    #Si no hemos hecho la verificación o no tiene playcount, entramos
                    estado = config.get_setting("verify_playcount",
                                                "videolibrary")
                    if not estado or estado == False or not serie.library_playcounts:  #Si no se ha pasado antes, lo hacemos ahora
                        serie, estado = videolibrary.verify_playcount_series(
                            serie, path
                        )  #También se pasa si falta un PlayCount por completo
                except:
                    logger.error(traceback.format_exc())
                else:
                    if estado:  #Si ha tenido éxito la actualización...
                        estado_verify_playcount_series = True  #... se marca para cambiar la opción de la Videoteca

                interval = int(serie.active)  # Podria ser del tipo bool

                if not serie.active:
                    # si la serie no esta activa descartar
                    if not overwrite:
                        #Sincronizamos los episodios vistos desde la videoteca de Kodi con la de Alfa, aunque la serie esté desactivada
                        try:
                            if config.is_xbmc():  #Si es Kodi, lo hacemos
                                from platformcode import xbmc_videolibrary
                                xbmc_videolibrary.mark_content_as_watched_on_alfa(
                                    path + '/tvshow.nfo')
                        except:
                            logger.error(traceback.format_exc())

                        continue

                # obtenemos las fecha de actualizacion y de la proxima programada para esta serie
                update_next = serie.update_next
                if update_next:
                    y, m, d = update_next.split('-')
                    update_next = datetime.date(int(y), int(m), int(d))
                else:
                    update_next = hoy

                update_last = serie.update_last
                if update_last:
                    y, m, d = update_last.split('-')
                    update_last = datetime.date(int(y), int(m), int(d))
                else:
                    update_last = hoy

                # si la serie esta activa ...
                if overwrite or config.get_setting("updatetvshows_interval",
                                                   "videolibrary") == 0:
                    # ... forzar actualizacion independientemente del intervalo
                    serie_actualizada = update(path, p_dialog, i, t, serie,
                                               overwrite)
                    if not serie_actualizada:
                        update_next = hoy + datetime.timedelta(days=interval)

                elif interval == 1 and update_next <= hoy:
                    # ...actualizacion diaria
                    serie_actualizada = update(path, p_dialog, i, t, serie,
                                               overwrite)
                    if not serie_actualizada and update_last <= hoy - datetime.timedelta(
                            days=7):
                        # si hace una semana q no se actualiza, pasar el intervalo a semanal
                        interval = 7
                        update_next = hoy + datetime.timedelta(days=interval)

                elif interval == 7 and update_next <= hoy:
                    # ...actualizacion semanal
                    serie_actualizada = update(path, p_dialog, i, t, serie,
                                               overwrite)
                    if not serie_actualizada:
                        if update_last <= hoy - datetime.timedelta(days=14):
                            # si hace 2 semanas q no se actualiza, pasar el intervalo a mensual
                            interval = 30

                        update_next += datetime.timedelta(days=interval)

                elif interval == 30 and update_next <= hoy:
                    # ...actualizacion mensual
                    serie_actualizada = update(path, p_dialog, i, t, serie,
                                               overwrite)
                    if not serie_actualizada:
                        update_next += datetime.timedelta(days=interval)

                if serie_actualizada:
                    update_last = hoy
                    update_next = hoy + datetime.timedelta(days=interval)

                head_nfo, serie = videolibrarytools.read_nfo(
                    tvshow_file)  #Vuelve a leer el.nfo, que ha sido modificado
                if interval != int(serie.active) or update_next.strftime(
                        '%Y-%m-%d'
                ) != serie.update_next or update_last.strftime(
                        '%Y-%m-%d') != serie.update_last:
                    serie.update_last = update_last.strftime('%Y-%m-%d')
                    if update_next > hoy:
                        serie.update_next = update_next.strftime('%Y-%m-%d')
                    serie.active = interval
                    serie.channel = "videolibrary"
                    serie.action = "get_seasons"
                    filetools.write(tvshow_file, head_nfo + serie.tojson())

                if serie_actualizada:
                    if config.get_setting("search_new_content",
                                          "videolibrary") == 0:
                        # Actualizamos la videoteca de Kodi: Buscar contenido en la carpeta de la serie
                        if config.is_xbmc():
                            from platformcode import xbmc_videolibrary
                            xbmc_videolibrary.update(
                                folder=filetools.basename(path))
                    else:
                        update_when_finished = True

            if estado_verify_playcount_series:  #Si se ha cambiado algún playcount, ...
                estado = config.set_setting(
                    "verify_playcount", True, "videolibrary"
                )  #... actualizamos la opción de Videolibrary

            if config.get_setting(
                    "search_new_content",
                    "videolibrary") == 1 and update_when_finished:
                # Actualizamos la videoteca de Kodi: Buscar contenido en todas las series
                if config.is_xbmc():
                    from platformcode import xbmc_videolibrary
                    xbmc_videolibrary.update()

            p_dialog.close()

        else:
            logger.info(
                "No actualiza la videoteca, está desactivado en la configuración de alfa"
            )

    except Exception, ex:
        logger.error("Se ha producido un error al actualizar las series")
        template = "An exception of type %s occured. Arguments:\n%r"
        message = template % (type(ex).__name__, ex.args)
        logger.error(message)

        if p_dialog:
            p_dialog.close()
Ejemplo n.º 3
0
def check_for_update(overwrite=True):
    logger.info("Actualizando series...")

    from core import filetools
    from core import channeltools, videolibrarytools
    from platformcode import platformtools
    from channels import videolibrary
    from lib import generictools
    if config.is_xbmc():
        from platformcode import xbmc_videolibrary

    p_dialog = None
    serie_actualizada = False
    update_when_finished = False
    hoy = datetime.date.today()
    estado_verify_playcount_series = False

    try:
        if config.get_setting("update", "videolibrary") != 0 or overwrite:
            config.set_setting("updatelibrary_last_check",
                               hoy.strftime('%Y-%m-%d'), "videolibrary")

            heading = config.get_localized_string(60389)
            p_dialog = platformtools.dialog_progress_bg(
                config.get_localized_string(20000), heading)
            p_dialog.update(0, '')
            show_list = []

            for path, folders, files in filetools.walk(
                    videolibrarytools.TVSHOWS_PATH):
                show_list.extend([
                    filetools.join(path, f) for f in files if f == "tvshow.nfo"
                ])

            if show_list:
                t = float(100) / len(show_list)

            for i, tvshow_file in enumerate(show_list):
                try:
                    head_nfo, serie = videolibrarytools.read_nfo(tvshow_file)
                    if not serie:
                        logger.error('.nfo erroneo en ' + str(tvshow_file))
                        continue
                    path = filetools.dirname(tvshow_file)

                    ###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial
                    overwrite_forced = False
                    try:
                        serie, serie, overwrite_forced = generictools.redirect_clone_newpct1(
                            serie,
                            head_nfo,
                            serie,
                            path,
                            overwrite,
                            lookup=True)
                    except:
                        logger.error(traceback.format_exc())
                    if overwrite_forced == True:
                        overwrite = True
                        serie.update_next = ''

                    info_status = ''
                    if serie.infoLabels['status']:
                        info_status = serie.infoLabels['status']

                    logger.info("Serie=%s, Activa=%s, Fecha=%s, Status=%s" % (serie.contentSerieName, \
                                str(serie.active), str(serie.update_last), str(info_status)))
                    p_dialog.update(int(math.ceil((i + 1) * t)), heading,
                                    serie.contentSerieName)

                    #Verificamos el estado del serie.library_playcounts de la Serie por si está incompleto
                    try:
                        estado = False
                        #Si no hemos hecho la verificación o no tiene playcount, entramos
                        estado = config.get_setting("verify_playcount",
                                                    "videolibrary")
                        if not estado or estado == False or not serie.library_playcounts:  #Si no se ha pasado antes, lo hacemos ahora
                            serie, estado = videolibrary.verify_playcount_series(
                                serie, path
                            )  #También se pasa si falta un PlayCount por completo
                    except:
                        logger.error(traceback.format_exc())
                    else:
                        if estado:  #Si ha tenido éxito la actualización...
                            estado_verify_playcount_series = True  #... se marca para cambiar la opción de la Videoteca

                    if serie.active:
                        try:
                            interval = int(
                                serie.active)  # Podria ser del tipo bool
                        except:
                            interval = 1
                    else:
                        interval = 0

                    if not serie.active:
                        # si la serie no esta activa descartar
                        if overwrite_forced == False:
                            #Sincronizamos los episodios vistos desde la videoteca de Kodi con la de Alfa, aunque la serie esté desactivada
                            try:
                                if config.is_xbmc():  #Si es Kodi, lo hacemos
                                    xbmc_videolibrary.mark_content_as_watched_on_alfa(
                                        path + '/tvshow.nfo')
                            except:
                                logger.error(traceback.format_exc())

                            continue

                    # obtenemos las fecha de actualizacion y de la proxima programada para esta serie
                    update_next = serie.update_next
                    if update_next:
                        y, m, d = update_next.split('-')
                        update_next = datetime.date(int(y), int(m), int(d))
                    else:
                        update_next = hoy

                    update_last = serie.update_last
                    if update_last:
                        y, m, d = update_last.split('-')
                        update_last = datetime.date(int(y), int(m), int(d))
                    else:
                        update_last = hoy

                    # si la serie esta activa ...
                    if overwrite or config.get_setting(
                            "updatetvshows_interval", "videolibrary") == 0:
                        # ... forzar actualizacion independientemente del intervalo
                        serie_actualizada = update(path, p_dialog, i, t, serie,
                                                   overwrite)
                        if not serie_actualizada:
                            update_next = hoy + datetime.timedelta(
                                days=interval)

                    elif interval == 1 and update_next <= hoy:
                        # ...actualizacion diaria
                        serie_actualizada = update(path, p_dialog, i, t, serie,
                                                   overwrite)
                        if not serie_actualizada and update_last <= hoy - datetime.timedelta(
                                days=7):
                            # si hace una semana q no se actualiza, pasar el intervalo a semanal
                            interval = 7
                            update_next = hoy + datetime.timedelta(
                                days=interval)

                    elif interval == 7 and update_next <= hoy:
                        # ...actualizacion semanal
                        serie_actualizada = update(path, p_dialog, i, t, serie,
                                                   overwrite)
                        if not serie_actualizada:
                            if update_last <= hoy - datetime.timedelta(
                                    days=14):
                                # si hace 2 semanas q no se actualiza, pasar el intervalo a mensual
                                interval = 30

                            update_next += datetime.timedelta(days=interval)

                    elif interval == 30 and update_next <= hoy:
                        # ...actualizacion mensual
                        serie_actualizada = update(path, p_dialog, i, t, serie,
                                                   overwrite)
                        if not serie_actualizada:
                            update_next += datetime.timedelta(days=interval)

                    if serie_actualizada:
                        update_last = hoy
                        update_next = hoy + datetime.timedelta(days=interval)

                    head_nfo, serie = videolibrarytools.read_nfo(
                        tvshow_file
                    )  #Vuelve a leer el.nfo, que ha sido modificado
                    if interval != int(serie.active) or update_next.strftime(
                            '%Y-%m-%d'
                    ) != serie.update_next or update_last.strftime(
                            '%Y-%m-%d') != serie.update_last:
                        serie.update_last = update_last.strftime('%Y-%m-%d')
                        if update_next > hoy:
                            serie.update_next = update_next.strftime(
                                '%Y-%m-%d')
                        if serie.infoLabels[
                                "status"] != "Ended" and serie.infoLabels[
                                    "status"] != "Canceled":
                            serie.active = interval
                        serie.channel = "videolibrary"
                        serie.action = "get_seasons"
                        filetools.write(tvshow_file, head_nfo + serie.tojson())

                    if serie_actualizada and not config.get_setting(
                            'cleanlibrary', 'videolibrary', default=False):
                        if config.get_setting("search_new_content",
                                              "videolibrary") == 0:
                            # Actualizamos la videoteca de Kodi: Buscar contenido en la carpeta de la serie
                            if config.is_xbmc():
                                xbmc_videolibrary.update(
                                    folder=filetools.basename(path))
                                update_when_finished = True
                        else:
                            update_when_finished = True
                except Exception as ex:
                    logger.error(
                        "Se ha producido un error al actualizar la serie %s" %
                        tvshow_file)
                    template = "An exception of type %s occured. Arguments:\n%r"
                    message = template % (type(ex).__name__, ex.args)
                    logger.error(message)
                    logger.error(traceback.format_exc(1))

            if estado_verify_playcount_series:  #Si se ha cambiado algún playcount, ...
                estado = config.set_setting(
                    "verify_playcount", True, "videolibrary"
                )  #... actualizamos la opción de Videolibrary

            #if config.get_setting("search_new_content", "videolibrary") == 1 and update_when_finished:
            if config.is_xbmc() and config.get_setting(
                    'cleanlibrary', 'videolibrary', default=False):
                while xbmc.getCondVisibility(
                        'Library.IsScanningVideo()'):  # Se espera a que acabe
                    time.sleep(1)
                xbmc.executebuiltin('CleanLibrary(video)')
                while xbmc.getCondVisibility(
                        'Library.IsScanningVideo()'):  # Se espera a que acabe
                    time.sleep(1)
                update_when_finished = True
                config.set_setting('cleanlibrary', False, 'videolibrary')
            if update_when_finished:
                # Actualizamos la videoteca de Kodi: Buscar contenido en todas las series
                if config.is_xbmc():
                    xbmc_videolibrary.update()

            p_dialog.close()

        else:
            logger.info(
                "No actualiza la videoteca, está desactivado en la configuración de alfa"
            )

    except Exception as ex:
        logger.error("Se ha producido un error al actualizar las series")
        template = "An exception of type %s occured. Arguments:\n%r"
        message = template % (type(ex).__name__, ex.args)
        logger.error(message)

        if p_dialog:
            p_dialog.close()

    # Sincroniza los "vistos" de la Videoteca de Películas
    from core.item import Item
    item_dummy = Item()
    videolibrary.list_movies(item_dummy, silent=True)

    # Descarga los últimos episodios disponibles, si el canal lo permite
    if config.get_setting("update", "videolibrary") != 0 or overwrite:
        from channels import downloads
        downloads.download_auto(item_dummy)
Ejemplo n.º 4
0
def update(path, p_dialog, i, t, serie, overwrite):
    logger.info("Actualizando " + path)

    from core import filetools
    from core import channeltools, videolibrarytools
    from platformcode import platformtools
    from channels import videolibrary
    from lib import generictools
    if config.is_xbmc():
        from platformcode import xbmc_videolibrary

    insertados_total = 0

    head_nfo, it = videolibrarytools.read_nfo(path + '/tvshow.nfo')
    category = serie.category

    # logger.debug("%s: %s" %(serie.contentSerieName,str(list_canales) ))
    for channel, url in list(serie.library_urls.items()):
        serie.channel = channel
        serie.url = url

        ###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial
        try:
            head_nfo, it = videolibrarytools.read_nfo(
                path +
                '/tvshow.nfo')  #Refresca el .nfo para recoger actualizaciones
            if not it:
                logger.error('.nfo erroneo en ' + str(path))
                continue
            if it.emergency_urls:
                serie.emergency_urls = it.emergency_urls
            serie.category = category
            serie, it, overwrite = generictools.redirect_clone_newpct1(
                serie, head_nfo, it, path, overwrite)
        except:
            logger.error(traceback.format_exc())

        channel_enabled = channeltools.is_enabled(serie.channel)

        if channel_enabled:

            heading = config.get_localized_string(60389)
            p_dialog.update(
                int(math.ceil((i + 1) * t)), heading, "%s: %s" %
                (serie.contentSerieName, serie.channel.capitalize()))
            try:
                pathchannels = filetools.join(config.get_runtime_path(),
                                              "channels",
                                              serie.channel + '.py')
                logger.info("Cargando canal: " + pathchannels)

                if serie.library_filter_show:
                    serie.show = serie.library_filter_show.get(
                        serie.channel, serie.contentSerieName)

                obj = __import__('channels.%s' % serie.channel,
                                 fromlist=["channels.%s" % serie.channel])
                itemlist = getattr(obj, 'episodios')(
                    serie)  #... se procesa Episodios para ese canal

                try:
                    if int(overwrite) == 3:
                        # Sobrescribir todos los archivos (tvshow.nfo, 1x01.nfo, 1x01 [canal].json, 1x01.strm, etc...)
                        insertados, sobreescritos, fallidos, notusedpath = videolibrarytools.save_tvshow(
                            serie, itemlist)
                        #serie= videolibrary.check_season_playcount(serie, serie.contentSeason)
                        #if filetools.write(path + '/tvshow.nfo', head_nfo + it.tojson()):
                        #    serie.infoLabels['playcount'] = serie.playcount
                    else:
                        insertados, sobreescritos, fallidos = videolibrarytools.save_episodes(
                            path,
                            itemlist,
                            serie,
                            silent=True,
                            overwrite=overwrite)
                        #it = videolibrary.check_season_playcount(it, it.contentSeason)
                        #if filetools.write(path + '/tvshow.nfo', head_nfo + it.tojson()):
                        #    serie.infoLabels['playcount'] = serie.playcount
                    insertados_total += insertados

                except Exception as ex:
                    logger.error("Error al guardar los capitulos de la serie")
                    template = "An exception of type %s occured. Arguments:\n%r"
                    message = template % (type(ex).__name__, ex.args)
                    logger.error(message)
                    logger.error(traceback.format_exc())

            except Exception as ex:
                logger.error("Error al obtener los episodios de: %s" %
                             serie.show)
                template = "An exception of type %s occured. Arguments:\n%r"
                message = template % (type(ex).__name__, ex.args)
                logger.error(message)
                logger.error(traceback.format_exc())

            #Si el canal lo permite, se comienza el proceso de descarga de los nuevos episodios descargados
            serie.channel = generictools.verify_channel(serie.channel)
            if insertados > 0 and config.get_setting(
                    'auto_download_new', serie.channel, default=False):
                config.set_setting(
                    "search_new_content", 1,
                    "videolibrary")  # Escaneamos a final todas la series
                serie.sub_action = 'auto'
                serie.category = itemlist[0].category
                from channels import downloads
                downloads.save_download(serie, silent=True)
                if serie.sub_action: del serie.sub_action

        else:
            logger.debug("Canal %s no activo no se actualiza" % serie.channel)

    #Sincronizamos los episodios vistos desde la videoteca de Kodi con la de Alfa
    try:
        if config.is_xbmc() and not config.get_setting(
                'cleanlibrary', 'videolibrary',
                default=False):  #Si es Kodi, lo hacemos
            xbmc_videolibrary.mark_content_as_watched_on_alfa(path +
                                                              '/tvshow.nfo')
    except:
        logger.error(traceback.format_exc())

    return insertados_total > 0
Ejemplo n.º 5
0
def list_tvshows(item):
    logger.info()
    itemlist = []
    dead_list = []
    zombie_list = []
    # Obtenemos todos los tvshow.nfo de la videoteca de SERIES recursivamente
    for raiz, subcarpetas, ficheros in filetools.walk(
            videolibrarytools.TVSHOWS_PATH):
        for f in ficheros:

            if f == "tvshow.nfo":
                tvshow_path = filetools.join(raiz, f)
                # logger.debug(tvshow_path)

                #Sincronizamos los episodios vistos desde la videoteca de Kodi con la de Alfa
                try:
                    if config.is_xbmc():  #Si es Kodi, lo hacemos
                        from platformcode import xbmc_videolibrary
                        xbmc_videolibrary.mark_content_as_watched_on_alfa(
                            tvshow_path)
                except:
                    logger.error(traceback.format_exc())

                head_nfo, item_tvshow = videolibrarytools.read_nfo(tvshow_path)

                if len(item_tvshow.library_urls) > 1:
                    multicanal = True
                else:
                    multicanal = False

                ## verifica la existencia de los canales, en caso de no existir el canal se pregunta si se quieren
                ## eliminar los enlaces de dicho canal

                for canal in item_tvshow.library_urls:
                    canal = generictools.verify_channel(canal)
                    try:
                        channel_verify = __import__(
                            'channels.%s' % canal,
                            fromlist=["channels.%s" % canal])
                        logger.debug('El canal %s parece correcto' %
                                     channel_verify)
                    except:
                        dead_item = Item(
                            multicanal=multicanal,
                            contentType='tvshow',
                            dead=canal,
                            path=raiz,
                            nfo=tvshow_path,
                            library_urls=item_tvshow.library_urls,
                            infoLabels={'title': item_tvshow.contentTitle})
                        if canal not in dead_list and canal not in zombie_list:
                            confirm = platformtools.dialog_yesno(
                                'Videoteca',
                                'Parece que el canal [COLOR red]%s[/COLOR] ya no existe.'
                                % canal.upper(),
                                'Deseas eliminar los enlaces de este canal?')

                        elif canal in zombie_list:
                            confirm = False
                        else:
                            confirm = True

                        if confirm:
                            delete(dead_item)
                            if canal not in dead_list:
                                dead_list.append(canal)
                            continue
                        else:
                            if canal not in zombie_list:
                                zombie_list.append(canal)

                if len(dead_list) > 0:
                    for canal in dead_list:
                        if canal in item_tvshow.library_urls:
                            del item_tvshow.library_urls[canal]

                ### continua la carga de los elementos de la videoteca

                try:  #A veces da errores aleatorios, por no encontrar el .nfo.  Probablemente problemas de timing
                    item_tvshow.title = item_tvshow.contentTitle
                    item_tvshow.path = raiz
                    item_tvshow.nfo = tvshow_path
                    # Menu contextual: Marcar como visto/no visto
                    visto = item_tvshow.library_playcounts.get(
                        item_tvshow.contentTitle, 0)
                    item_tvshow.infoLabels["playcount"] = visto
                    if visto > 0:
                        texto_visto = config.get_localized_string(60020)
                        contador = 0
                    else:
                        texto_visto = config.get_localized_string(60021)
                        contador = 1

                except:
                    logger.error('No encuentra: ' + str(tvshow_path))
                    logger.error(traceback.format_exc())
                    continue

                # Menu contextual: Buscar automáticamente nuevos episodios o no
                if item_tvshow.active and int(item_tvshow.active) > 0:
                    texto_update = config.get_localized_string(60022)
                    value = 0
                    item_tvshow.text_color = "green"
                else:
                    texto_update = config.get_localized_string(60023)
                    value = 1
                    item_tvshow.text_color = "0xFFDF7401"

                # Menu contextual: Eliminar serie/canal
                num_canales = len(item_tvshow.library_urls)
                if "downloads" in item_tvshow.library_urls:
                    num_canales -= 1
                if num_canales > 1:
                    texto_eliminar = config.get_localized_string(60024)
                else:
                    texto_eliminar = config.get_localized_string(60025)

                item_tvshow.context = [{
                    "title": texto_visto,
                    "action": "mark_content_as_watched",
                    "channel": "videolibrary",
                    "playcount": contador
                }, {
                    "title": texto_update,
                    "action": "mark_tvshow_as_updatable",
                    "channel": "videolibrary",
                    "active": value
                }, {
                    "title": texto_eliminar,
                    "action": "delete",
                    "channel": "videolibrary",
                    "multicanal": multicanal
                }, {
                    "title":
                    config.get_localized_string(70269),
                    "action":
                    "update_tvshow",
                    "channel":
                    "videolibrary"
                }]
                # ,{"title": "Cambiar contenido (PENDIENTE)",
                # "action": "",
                # "channel": "videolibrary"}]

                # logger.debug("item_tvshow:\n" + item_tvshow.tostring('\n'))

                ## verifica la existencia de los canales ##
                if len(item_tvshow.library_urls) > 0:
                    itemlist.append(item_tvshow)

    if itemlist:
        itemlist = sorted(itemlist, key=lambda it: it.title.lower())

        itemlist.append(
            Item(channel=item.channel,
                 action="update_videolibrary",
                 thumbnail=item.thumbnail,
                 title=config.get_localized_string(60026),
                 folder=False))

    return itemlist
Ejemplo n.º 6
0
def list_movies(item, silent=False):
    logger.info()
    itemlist = []
    dead_list = []
    zombie_list = []
    for raiz, subcarpetas, ficheros in filetools.walk(
            videolibrarytools.MOVIES_PATH):
        for f in ficheros:
            if f.endswith(".nfo"):
                nfo_path = filetools.join(raiz, f)

                #Sincronizamos las películas vistas desde la videoteca de Kodi con la de Alfa
                try:
                    if config.is_xbmc():  #Si es Kodi, lo hacemos
                        from platformcode import xbmc_videolibrary
                        xbmc_videolibrary.mark_content_as_watched_on_alfa(
                            nfo_path)
                except:
                    logger.error(traceback.format_exc())

                head_nfo, new_item = videolibrarytools.read_nfo(nfo_path)

                if not new_item:  #Si no ha leído bien el .nfo, pasamos a la siguiente
                    continue

                if len(new_item.library_urls) > 1:
                    multicanal = True
                else:
                    multicanal = False

                ## verifica la existencia de los canales, en caso de no existir el canal se pregunta si se quieren
                ## eliminar los enlaces de dicho canal

                for canal_org in new_item.library_urls:
                    canal = generictools.verify_channel(canal_org)
                    try:
                        channel_verify = __import__(
                            'channels.%s' % canal,
                            fromlist=["channels.%s" % canal])
                        logger.debug('El canal %s parece correcto' %
                                     channel_verify)
                    except:
                        dead_item = Item(
                            multicanal=multicanal,
                            contentType='movie',
                            dead=canal,
                            path=raiz,
                            nfo=nfo_path,
                            library_urls=new_item.library_urls,
                            infoLabels={'title': new_item.contentTitle})
                        if canal not in dead_list and canal not in zombie_list:
                            confirm = platformtools.dialog_yesno(
                                'Videoteca',
                                'Parece que el canal [COLOR red]%s[/COLOR] ya no existe.'
                                % canal.upper(),
                                'Deseas eliminar los enlaces de este canal?')

                        elif canal in zombie_list:
                            confirm = False
                        else:
                            confirm = True

                        if confirm:
                            delete(dead_item)
                            if canal not in dead_list:
                                dead_list.append(canal)
                            continue
                        else:
                            if canal not in zombie_list:
                                zombie_list.append(canal)

                if len(dead_list) > 0:
                    for canal in dead_list:
                        if canal in new_item.library_urls:
                            del new_item.library_urls[canal]

                new_item.nfo = nfo_path
                new_item.path = raiz
                new_item.thumbnail = new_item.contentThumbnail
                new_item.text_color = "blue"
                strm_path = new_item.strm_path.replace("\\", "/").rstrip("/")
                if '/' in new_item.path:
                    new_item.strm_path = strm_path

                if not filetools.exists(
                        filetools.join(new_item.path,
                                       filetools.basename(strm_path))):
                    # Si se ha eliminado el strm desde la bilbioteca de kodi, no mostrarlo
                    continue

                # Menu contextual: Marcar como visto/no visto
                visto = new_item.library_playcounts.get(
                    os.path.splitext(f)[0], 0)
                new_item.infoLabels["playcount"] = visto
                if visto > 0:
                    texto_visto = config.get_localized_string(60016)
                    contador = 0
                else:
                    texto_visto = config.get_localized_string(60017)
                    contador = 1

                # Menu contextual: Eliminar serie/canal
                num_canales = len(new_item.library_urls)
                if "downloads" in new_item.library_urls:
                    num_canales -= 1
                if num_canales > 1:
                    texto_eliminar = config.get_localized_string(60018)
                else:
                    texto_eliminar = config.get_localized_string(60019)

                new_item.context = [{
                    "title": texto_visto,
                    "action": "mark_content_as_watched",
                    "channel": "videolibrary",
                    "playcount": contador
                }, {
                    "title": texto_eliminar,
                    "action": "delete",
                    "channel": "videolibrary",
                    "multicanal": multicanal
                }]
                # ,{"title": "Cambiar contenido (PENDIENTE)",
                # "action": "",
                # "channel": "videolibrary"}]
                # logger.debug("new_item: " + new_item.tostring('\n'))
                itemlist.append(new_item)

    if silent == False:
        return sorted(itemlist, key=lambda it: it.title.lower())
    else:
        return
Ejemplo n.º 7
0
def reset_videotlibrary_by_channel(inactive=True):

    ###### LISTA DE CANALES PARA SOBRESCRIBIR SU VIDEOTECA 
    channels_list = []

    if not channels_list or not config.get_setting("update", "videolibrary") or \
                    config.get_setting("videolibrary_backup_scan", "videolibrary"):
        return

    try:
        # Vemos si ya se ha sobrescrito, si no marcamos
        if filetools.exists(ADDON_CUSTOMCODE_JSON):
            json_data = jsontools.load(filetools.read(ADDON_CUSTOMCODE_JSON))
        else:
            json_data = {}
        if json_data.get('reset_videotlibrary_by_channel', ''): return
        json_data['reset_videotlibrary_by_channel'] = channels_list
        if not filetools.write(ADDON_CUSTOMCODE_JSON, jsontools.dump(json_data)):
            logger.error('No se puede actualizar el .json %s' % ADDON_CUSTOMCODE_JSON)
            logger.error('Error sobrescribiendo la Videoteca para los canales: %s' % channels_list)
            return

        logger.info('Sobrescribiendo para canales: %s' % channels_list, force=True)
        from core import videolibrarytools

        # SERIES
        show_list = []
        for path, folders, files in filetools.walk(videolibrarytools.TVSHOWS_PATH):
            for f in files:
                if f == "tvshow.nfo":
                    nfo_path = filetools.join(path, f)
                    head_nfo, it = videolibrarytools.read_nfo(nfo_path)
                    for channel, url in list(it.library_urls.items()):
                        if channel in channels_list:
                            show_list.extend([nfo_path])

        logger.info("Lista de SERIES a sobrescribir: %s" % show_list, force=True)
        if show_list:
            heading = config.get_localized_string(60584)
            p_dialog = platformtools.dialog_progress_bg(config.get_localized_string(60585), heading)
            p_dialog.update(0, '')
            time.sleep(5)

            if show_list:
                t = float(100) / len(show_list)

            for i, tvshow_file in enumerate(show_list):
                videolibrarytools.reset_serie(tvshow_file, p_dialog, i, t, inactive)
            p_dialog.close()

            if config.is_xbmc():
                import xbmc
                from platformcode import xbmc_videolibrary
                xbmc_videolibrary.update(config.get_setting("folder_tvshows"), '_scan_series')      # Se cataloga SERIES en Kodi
                while xbmc.getCondVisibility('Library.IsScanningVideo()'):                          # Se espera a que acabe el scanning
                    time.sleep(1)
                for tvshow_file in show_list:
                    xbmc_videolibrary.mark_content_as_watched_on_alfa(tvshow_file)

        # MOVIES
        movies_list = []
        for path, folders, files in filetools.walk(videolibrarytools.MOVIES_PATH):
            for f in files:
                if f.endswith(".nfo"):
                    nfo_path = filetools.join(path, f)
                    head_nfo, it = videolibrarytools.read_nfo(nfo_path)
                    for channel, url in list(it.library_urls.items()):
                        if channel in channels_list:
                            movies_list.extend([nfo_path])

        logger.info("Lista de PELÍCULAS a sobrescribir: %s" % movies_list, force=True)
        if movies_list:
            heading = config.get_localized_string(60584)
            p_dialog = platformtools.dialog_progress_bg(config.get_localized_string(60585), heading)
            p_dialog.update(0, '')

            if movies_list:
                t = float(100) / len(movies_list)

            for i, movie_nfo in enumerate(movies_list):
                videolibrarytools.reset_movie(movie_nfo, p_dialog, i, t)
            p_dialog.close()

            if config.is_xbmc():
                import xbmc
                from platformcode import xbmc_videolibrary
                xbmc_videolibrary.update(config.get_setting("folder_movies"), '_scan_series')       # Se cataloga SERIES en Kodi
                while xbmc.getCondVisibility('Library.IsScanningVideo()'):                          # Se espera a que acabe el scanning
                    time.sleep(1)
                for movie_nfo in movies_list:
                    xbmc_videolibrary.mark_content_as_watched_on_alfa(movie_nfo)
    except:
        logger.error(traceback.format_exc())
Ejemplo n.º 8
0
def overwrite_tools(item):
    import time
    import videolibrary_service
    from core import videolibrarytools

    seleccion = platformtools.dialog_yesno(config.get_localized_string(60581),
                                           config.get_localized_string(60582),
                                           config.get_localized_string(60583))
    if seleccion == 1:
        # tvshows
        heading = config.get_localized_string(60584)
        p_dialog = platformtools.dialog_progress_bg(
            config.get_localized_string(60585), heading)
        p_dialog.update(0, '')

        show_list = []
        for path, folders, files in filetools.walk(
                videolibrarytools.TVSHOWS_PATH):
            show_list.extend(
                [filetools.join(path, f) for f in files if f == "tvshow.nfo"])

        logger.debug("series_list %s" % show_list)

        if show_list:
            t = float(100) / len(show_list)

        for i, tvshow_file in enumerate(show_list):
            videolibrarytools.reset_serie(tvshow_file, p_dialog, i, t)
        p_dialog.close()

        if config.is_xbmc():
            import xbmc
            from platformcode import xbmc_videolibrary
            xbmc_videolibrary.update(
                config.get_setting("folder_tvshows"),
                '_scan_series')  # Se cataloga SERIES en Kodi
            while xbmc.getCondVisibility(
                    'Library.IsScanningVideo()'
            ):  # Se espera a que acabe el scanning
                time.sleep(1)
            for tvshow_file in show_list:
                xbmc_videolibrary.mark_content_as_watched_on_alfa(tvshow_file)

        # movies
        heading = config.get_localized_string(60586)
        p_dialog = platformtools.dialog_progress_bg(
            config.get_localized_string(60585), heading)
        p_dialog.update(0, '')

        movies_list = []
        for path, folders, files in filetools.walk(
                videolibrarytools.MOVIES_PATH):
            movies_list.extend(
                [filetools.join(path, f) for f in files if f.endswith(".nfo")])

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

        if movies_list:
            t = float(100) / len(movies_list)

        for i, movie_nfo in enumerate(movies_list):
            videolibrarytools.reset_movie(movie_nfo, p_dialog, i, t)
        p_dialog.close()

        if config.is_xbmc():
            import xbmc
            from platformcode import xbmc_videolibrary
            xbmc_videolibrary.update(
                config.get_setting("folder_movies"),
                '_scan_series')  # Se cataloga CINE en Kodi
            while xbmc.getCondVisibility(
                    'Library.IsScanningVideo()'
            ):  # Se espera a que acabe el scanning
                time.sleep(1)
            for movie_nfo in movies_list:
                xbmc_videolibrary.mark_content_as_watched_on_alfa(movie_nfo)
Ejemplo n.º 9
0
def list_movies(item, silent=False):
    logger.info()
    itemlist = []

    for raiz, subcarpetas, ficheros in filetools.walk(
            videolibrarytools.MOVIES_PATH):
        for f in ficheros:
            if f.endswith(".nfo"):
                nfo_path = filetools.join(raiz, f)

                #Sincronizamos las películas vistas desde la videoteca de Kodi con la de Alfa
                try:
                    if config.is_xbmc():  #Si es Kodi, lo hacemos
                        from platformcode import xbmc_videolibrary
                        xbmc_videolibrary.mark_content_as_watched_on_alfa(
                            nfo_path)
                except:
                    pass

                head_nfo, new_item = videolibrarytools.read_nfo(nfo_path)

                new_item.nfo = nfo_path
                new_item.path = raiz
                new_item.thumbnail = new_item.contentThumbnail
                new_item.text_color = "blue"

                if not filetools.exists(
                        filetools.join(new_item.path,
                                       filetools.basename(
                                           new_item.strm_path))):
                    # Si se ha eliminado el strm desde la bilbioteca de kodi, no mostrarlo
                    continue

                ###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial
                try:
                    new_item, new_item, overwrite = generictools.redirect_clone_newpct1(
                        new_item, head_nfo, new_item, raiz)
                except:
                    pass

                # Menu contextual: Marcar como visto/no visto
                visto = new_item.library_playcounts.get(
                    os.path.splitext(f)[0], 0)
                new_item.infoLabels["playcount"] = visto
                if visto > 0:
                    texto_visto = config.get_localized_string(60016)
                    contador = 0
                else:
                    texto_visto = config.get_localized_string(60017)
                    contador = 1

                # Menu contextual: Eliminar serie/canal
                num_canales = len(new_item.library_urls)
                if "downloads" in new_item.library_urls:
                    num_canales -= 1
                if num_canales > 1:
                    texto_eliminar = config.get_localized_string(60018)
                    multicanal = True
                else:
                    texto_eliminar = config.get_localized_string(60019)
                    multicanal = False

                new_item.context = [{
                    "title": texto_visto,
                    "action": "mark_content_as_watched",
                    "channel": "videolibrary",
                    "playcount": contador
                }, {
                    "title": texto_eliminar,
                    "action": "delete",
                    "channel": "videolibrary",
                    "multicanal": multicanal
                }]
                # ,{"title": "Cambiar contenido (PENDIENTE)",
                # "action": "",
                # "channel": "videolibrary"}]
                # logger.debug("new_item: " + new_item.tostring('\n'))
                itemlist.append(new_item)

    if silent == False:
        return sorted(itemlist, key=lambda it: it.title.lower())
    else:
        return
Ejemplo n.º 10
0
def list_tvshows(item):
    logger.info()
    itemlist = []

    # Obtenemos todos los tvshow.nfo de la videoteca de SERIES recursivamente
    for raiz, subcarpetas, ficheros in filetools.walk(
            videolibrarytools.TVSHOWS_PATH):
        for f in ficheros:
            if f == "tvshow.nfo":
                tvshow_path = filetools.join(raiz, f)
                # logger.debug(tvshow_path)

                #Sincronizamos los episodios vistos desde la videoteca de Kodi con la de Alfa
                try:
                    if config.is_xbmc():  #Si es Kodi, lo hacemos
                        from platformcode import xbmc_videolibrary
                        xbmc_videolibrary.mark_content_as_watched_on_alfa(
                            tvshow_path)
                except:
                    pass

                head_nfo, item_tvshow = videolibrarytools.read_nfo(tvshow_path)
                item_tvshow.title = item_tvshow.contentTitle
                item_tvshow.path = raiz
                item_tvshow.nfo = tvshow_path

                # Menu contextual: Marcar como visto/no visto
                visto = item_tvshow.library_playcounts.get(
                    item_tvshow.contentTitle, 0)
                item_tvshow.infoLabels["playcount"] = visto
                if visto > 0:
                    texto_visto = config.get_localized_string(60020)
                    contador = 0
                else:
                    texto_visto = config.get_localized_string(60021)
                    contador = 1

                # Menu contextual: Buscar automáticamente nuevos episodios o no
                if item_tvshow.active and int(item_tvshow.active) > 0:
                    texto_update = config.get_localized_string(60022)
                    value = 0
                    item_tvshow.text_color = "green"
                else:
                    texto_update = config.get_localized_string(60023)
                    value = 1
                    item_tvshow.text_color = "0xFFDF7401"

                # Menu contextual: Eliminar serie/canal
                num_canales = len(item_tvshow.library_urls)
                if "downloads" in item_tvshow.library_urls:
                    num_canales -= 1
                if num_canales > 1:
                    texto_eliminar = config.get_localized_string(60024)
                    multicanal = True
                else:
                    texto_eliminar = config.get_localized_string(60025)
                    multicanal = False

                item_tvshow.context = [{
                    "title": texto_visto,
                    "action": "mark_content_as_watched",
                    "channel": "videolibrary",
                    "playcount": contador
                }, {
                    "title": texto_update,
                    "action": "mark_tvshow_as_updatable",
                    "channel": "videolibrary",
                    "active": value
                }, {
                    "title": texto_eliminar,
                    "action": "delete",
                    "channel": "videolibrary",
                    "multicanal": multicanal
                }, {
                    "title":
                    config.get_localized_string(70269),
                    "action":
                    "update_tvshow",
                    "channel":
                    "videolibrary"
                }]
                # ,{"title": "Cambiar contenido (PENDIENTE)",
                # "action": "",
                # "channel": "videolibrary"}]

                # logger.debug("item_tvshow:\n" + item_tvshow.tostring('\n'))
                itemlist.append(item_tvshow)

    if itemlist:
        itemlist = sorted(itemlist, key=lambda it: it.title.lower())

        itemlist.append(
            Item(channel=item.channel,
                 action="update_videolibrary",
                 thumbnail=item.thumbnail,
                 title=config.get_localized_string(60026),
                 folder=False))

    return itemlist
Ejemplo n.º 11
0
def update(path, p_dialog, i, t, serie, overwrite):
    logger.info("Updating " + path)
    insertados_total = 0

    head_nfo, it = videolibrarytools.read_nfo(path + '/tvshow.nfo')
    # videolibrarytools.check_renumber_options(it)
    videolibrarytools.update_renumber_options(it, head_nfo, path)
    category = serie.category

    # logger.debug("%s: %s" %(serie.contentSerieName,str(list_canales) ))
    for channel, url in serie.library_urls.items():
        serie.channel = channel
        serie.url = url

        ###### Redirección al canal NewPct1.py si es un clone, o a otro canal y url si ha intervención judicial
        try:
            head_nfo, it = videolibrarytools.read_nfo(
                path +
                '/tvshow.nfo')  #Refresca el .nfo para recoger actualizaciones
            if it.emergency_urls:
                serie.emergency_urls = it.emergency_urls
            serie.category = category
        except:
            logger.error(traceback.format_exc())

        channel_enabled = channeltools.is_enabled(serie.channel)

        if channel_enabled:

            heading = config.get_localized_string(20000)
            p_dialog.update(
                int(math.ceil((i + 1) * t)), heading,
                config.get_localized_string(60389) %
                (serie.contentSerieName, serie.channel.capitalize()))
            try:
                pathchannels = filetools.join(config.get_runtime_path(),
                                              "channels",
                                              serie.channel + '.py')
                logger.info("loading channel: " + pathchannels + " " +
                            serie.channel)

                if serie.library_filter_show:
                    serie.show = serie.library_filter_show.get(
                        serie.channel, serie.contentSerieName)

                obj = __import__('channels.%s' % serie.channel,
                                 fromlist=[pathchannels])

                itemlist = obj.episodios(serie)

                try:
                    if int(overwrite) == 3:
                        # Sobrescribir todos los archivos (tvshow.nfo, 1x01.nfo, 1x01 [canal].json, 1x01.strm, etc...)
                        insertados, sobreescritos, fallidos, notusedpath = videolibrarytools.save_tvshow(
                            serie, itemlist)
                        #serie= videolibrary.check_season_playcount(serie, serie.contentSeason)
                        #if filetools.write(path + '/tvshow.nfo', head_nfo + it.tojson()):
                        #    serie.infoLabels['playcount'] = serie.playcount
                    else:
                        insertados, sobreescritos, fallidos = videolibrarytools.save_episodes(
                            path,
                            itemlist,
                            serie,
                            silent=True,
                            overwrite=overwrite)
                        #it = videolibrary.check_season_playcount(it, it.contentSeason)
                        #if filetools.write(path + '/tvshow.nfo', head_nfo + it.tojson()):
                        #    serie.infoLabels['playcount'] = serie.playcount
                    insertados_total += insertados

                except Exception as ex:
                    logger.error(
                        "Error when saving the chapters of the series")
                    template = "An exception of type %s occured. Arguments:\n%r"
                    message = template % (type(ex).__name__, ex.args)
                    logger.error(message)

            except Exception as ex:
                logger.error("Error in obtaining the episodes of: %s" %
                             serie.show)
                template = "An exception of type %s occured. Arguments:\n%r"
                message = template % (type(ex).__name__, ex.args)
                logger.error(message)

        else:
            logger.debug("Channel %s not active is not updated" %
                         serie.channel)

    #Sincronizamos los episodios vistos desde la videoteca de Kodi con la de Alfa
    try:
        if config.is_xbmc():  #Si es Kodi, lo hacemos
            from platformcode import xbmc_videolibrary
            xbmc_videolibrary.mark_content_as_watched_on_alfa(path +
                                                              '/tvshow.nfo')
    except:
        logger.error(traceback.format_exc())

    return insertados_total > 0