def create_tvshows_from_json(_actualizado):
    logger.info(
        "streamondemand.platformcode.library_service create_tvshows_from_json")
    fname = filetools.join(config.get_data_path(), library.TVSHOW_FILE)

    if filetools.exists(fname):
        if not _actualizado:
            platformtools.dialog_ok(
                "Biblioteca: Actualizando formato",
                "Espere por favor mientras se completa el proceso")

        try:
            data = jsontools.loads(filetools.read(fname))
            for tvshow in data:
                for channel in data[tvshow]["channels"]:

                    serie = Item(contentSerieName=data[tvshow]["channels"]
                                 [channel]["tvshow"],
                                 url=data[tvshow]["channels"][channel]["url"],
                                 channel=channel,
                                 action="episodios",
                                 title=data[tvshow]["name"],
                                 active=True)
                    if not tvshow.startswith("t_"):
                        serie.infoLabels["tmdb_id"] = tvshow
                    library.save_library_tvshow(serie, list())

            filetools.rename(fname, "series.json.old")

        except EnvironmentError:
            logger.info("ERROR al leer el archivo: {0}".format(fname))
Пример #2
0
def move_to_libray(item):
    try:
      from platformcode import library
    except:
      return
      
    # Copiamos el archivo a la biblioteca
    origen = filetools.join(config.get_setting("downloadpath"), item.downloadFilename)
    destino = filetools.join(config.get_library_path(), *filetools.split(item.downloadFilename))
    
    if not filetools.isdir(filetools.dirname(destino)):
      filetools.mkdir(filetools.dirname(destino))
    
    if filetools.isfile(destino) and filetools.isfile(origen) :
      filetools.remove(destino)

    if filetools.isfile(origen):
      filetools.move(origen, destino)
      if len(filetools.listdir(filetools.dirname(origen))) == 0: 
        filetools.rmdir(filetools.dirname(origen))
      
    else:
      logger.error("No se ha encontrado el archivo: %s" % origen)
    
    if filetools.isfile(destino):
      if item.contentType == "movie" and item.infoLabels["tmdb_id"]:
        library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=destino)
        
        library.save_library_movie(library_item)
        
      elif item.contentType == "episode" and item.infoLabels["tmdb_id"]:
        library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=destino)
        
        tvshow = Item(channel= "descargas", contentType="tvshow", infoLabels = {"tmdb_id": item.infoLabels["tmdb_id"]})
        library.save_library_tvshow(tvshow, [library_item])
Пример #3
0
def create_tvshows_from_json(_actualizado):
    logger.info("pelisalacarta.platformcode.library_service create_tvshows_from_json")
    fname = filetools.join(config.get_data_path(), library.TVSHOW_FILE)

    if filetools.exists(fname):
        if not _actualizado:
            platformtools.dialog_ok("Biblioteca: Actualizando formato",
                                    "Espere por favor mientras se completa el proceso")

        try:
            data = jsontools.loads(filetools.read(fname))
            for tvshow in data:
                for channel in data[tvshow]["channels"]:

                    serie = Item(contentSerieName=data[tvshow]["channels"][channel]["tvshow"],
                                 url=data[tvshow]["channels"][channel]["url"], channel=channel, action="episodios",
                                 title=data[tvshow]["name"], active=True)
                    if not tvshow.startswith("t_"):
                        serie.infoLabels["tmdb_id"] = tvshow
                    library.save_library_tvshow(serie, list())

            filetools.rename(fname, "series.json.old")

        except EnvironmentError:
            logger.info("ERROR al leer el archivo: {0}".format(fname))
Пример #4
0
def create_tvshows_from_xml():
    logger.info("pelisalacarta.platformcode.library_service create_tvshows_from_xml")

    fname = filetools.join(config.get_data_path(), library.TVSHOW_FILE_OLD)
    if filetools.exists(fname):
        platformtools.dialog_ok("Biblioteca: Se va a actualizar al nuevo formato",
                                "Seleccione el nombre correcto de cada serie, si no está seguro pulse 'Cancelar'.",
                                "Hay nuevas opciones en 'Biblioteca' y en la 'configuración' del addon.")

        filetools.rename(library.TVSHOWS_PATH,  "SERIES_OLD")

        if not filetools.exists(library.TVSHOWS_PATH):
            filetools.mkdir(library.TVSHOWS_PATH)

            if filetools.exists(library.TVSHOWS_PATH):
                try:
                    data = filetools.read(fname)
                    for line in data.splitlines():
                        aux = line.rstrip('\n').split(",")
                        tvshow = aux[0].strip()
                        url = aux[1].strip()
                        channel = aux[2].strip()

                        serie = Item(contentSerieName=tvshow, url=url, channel=channel, action="episodios",
                                     title=tvshow, active=True)

                        patron = "^(.+)[\s]\((\d{4})\)$"
                        matches = re.compile(patron, re.DOTALL).findall(serie.contentSerieName)

                        if matches:
                            serie.infoLabels['title'] = matches[0][0]
                            serie.infoLabels['year'] = matches[0][1]
                        else:
                            serie.infoLabels['title'] = tvshow

                        library.save_library_tvshow(serie, list())

                    filetools.rename(fname, "series.xml.old")

                    # Por ultimo limpia la libreria, por que las rutas anteriores ya no existen
                    library.clean()

                except EnvironmentError:
                    logger.info("ERROR al leer el archivo: {0}".format(fname))

            else:
                logger.info("ERROR, no se ha podido crear la nueva carpeta de SERIES")
        else:
            logger.info("ERROR, no se ha podido renombrar la antigua carpeta de SERIES")

        return True

    return False
Пример #5
0
def create_tvshows_from_xml():
    logger.info("pelisalacarta.platformcode.library_service create_tvshows_from_xml")

    fname = filetools.join(config.get_data_path(), library.TVSHOW_FILE_OLD)
    if filetools.exists(fname):
        platformtools.dialog_ok("Biblioteca: Se va a actualizar al nuevo formato",
                                "Seleccione el nombre correcto de cada serie, si no está seguro pulse 'Cancelar'.",
                                "Hay nuevas opciones en 'Biblioteca' y en la 'configuración' del addon.")

        filetools.rename(library.TVSHOWS_PATH,  "SERIES_OLD")

        if not filetools.exists(library.TVSHOWS_PATH):
            filetools.mkdir(library.TVSHOWS_PATH)

            if filetools.exists(library.TVSHOWS_PATH):
                try:
                    data = filetools.read(fname)
                    for line in data.splitlines():
                        aux = line.rstrip('\n').split(",")
                        tvshow = aux[0].strip()
                        url = aux[1].strip()
                        channel = aux[2].strip()

                        serie = Item(contentSerieName=tvshow, url=url, channel=channel, action="episodios",
                                     title=tvshow, active=True)

                        patron = "^(.+)[\s]\((\d{4})\)$"
                        matches = re.compile(patron, re.DOTALL).findall(serie.contentSerieName)

                        if matches:
                            serie.infoLabels['title'] = matches[0][0]
                            serie.infoLabels['year'] = matches[0][1]
                        else:
                            serie.infoLabels['title'] = tvshow

                        library.save_library_tvshow(serie, list())

                    filetools.rename(fname, "series.xml.old")

                    # Por ultimo limpia la libreria, por que las rutas anteriores ya no existen
                    library.clean()

                except EnvironmentError:
                    logger.info("ERROR al leer el archivo: {0}".format(fname))

            else:
                logger.info("ERROR, no se ha podido crear la nueva carpeta de SERIES")
        else:
            logger.info("ERROR, no se ha podido renombrar la antigua carpeta de SERIES")

        return True

    return False
def create_tvshows_from_xml():
    logger.info("fusionse.platformcode.library_service create_tvshows_from_xml")

    fname = filetools.join(config.get_data_path(), library.TVSHOW_FILE_OLD)
    if filetools.exists(fname):
        platformtools.dialog_ok("Libreria: Si aggiornerà al nuovo formato",
                                 "Selezionare il nome corretto di ogni serie, se non siete sicuri potete 'Annulla'.",
                                 "Ci sono nuove opzioni per la 'Libreria' in 'configurazione'.")

        filetools.rename(library.TVSHOWS_PATH, "SERIES_OLD")

        if not filetools.exists(library.TVSHOWS_PATH):
            filetools.mkdir(library.TVSHOWS_PATH)

            if filetools.exists(library.TVSHOWS_PATH):
                try:
                    data = filetools.read(fname)
                    for line in data.splitlines():
                        aux = line.rstrip('\n').split(",")
                        tvshow = aux[0].strip()
                        url = aux[1].strip()
                        channel = aux[2].strip()

                        serie = Item(contentSerieName=tvshow, url=url, channel=channel, action="episodios",
                                     title=tvshow, active=True)

                        patron = "^(.+)[\s]\((\d{4})\)$"
                        matches = re.compile(patron, re.DOTALL).findall(serie.contentSerieName)

                        if matches:
                            serie.infoLabels['title'] = matches[0][0]
                            serie.infoLabels['year'] = matches[0][1]
                        else:
                            serie.infoLabels['title'] = tvshow

                        library.save_library_tvshow(serie, list())

                    filetools.rename(fname, "series.xml.old")

                    # Por ultimo limpia la libreria, por que las rutas anteriores ya no existen
                    library.clean()

                except EnvironmentError:
                    logger.info("ERROR al leer el archivo: {0}".format(fname))

            else:
                logger.info("ERROR, no se ha podido crear la nueva carpeta de SERIES")
        else:
            logger.info("ERROR, no se ha podido renombrar la antigua carpeta de SERIES")

        return True

    return False
Пример #7
0
def create_tvshows_from_xml():
    logger.info("streamondemand.platformcode.library_service create_tvshows_from_xml")

    fname = filetools.join(config.get_data_path(), library.TVSHOW_FILE_OLD)
    if filetools.exists(fname):
        platformtools.dialog_ok("Libreria: Si aggiornerà al nuovo formato",
                                 "Selezionare il nome corretto di ogni serie, se non siete sicuri potete 'Annulla'.",
                                 "Ci sono nuove opzioni per la 'Libreria' in 'configurazione'.")

        filetools.rename(library.TVSHOWS_PATH, "SERIES_OLD")

        if not filetools.exists(library.TVSHOWS_PATH):
            filetools.mkdir(library.TVSHOWS_PATH)

            if filetools.exists(library.TVSHOWS_PATH):
                try:
                    data = filetools.read(fname)
                    for line in data.splitlines():
                        aux = line.rstrip('\n').split(",")
                        tvshow = aux[0].strip()
                        url = aux[1].strip()
                        channel = aux[2].strip()

                        serie = Item(contentSerieName=tvshow, url=url, channel=channel, action="episodios",
                                     title=tvshow, active=True)

                        patron = "^(.+)[\s]\((\d{4})\)$"
                        matches = re.compile(patron, re.DOTALL).findall(serie.contentSerieName)

                        if matches:
                            serie.infoLabels['title'] = matches[0][0]
                            serie.infoLabels['year'] = matches[0][1]
                        else:
                            serie.infoLabels['title'] = tvshow

                        library.save_library_tvshow(serie, list())

                    filetools.rename(fname, "series.xml.old")

                    # Por ultimo limpia la libreria, por que las rutas anteriores ya no existen
                    library.clean()

                except EnvironmentError:
                    logger.info("ERROR al leer el archivo: {0}".format(fname))

            else:
                logger.info("ERROR, no se ha podido crear la nueva carpeta de SERIES")
        else:
            logger.info("ERROR, no se ha podido renombrar la antigua carpeta de SERIES")

        return True

    return False
Пример #8
0
def series_library(item):
    logger.info("pelisalacarta.channels.tvvip series_library")
    # Funcion unicamente para añadir/actualizar series a la libreria
    itemlist = []
    lista_episodios = []
    show = item.show.strip()

    data_serie = scrapertools.anti_cloudflare(item.url, host=host, headers=headers)
    data_serie = jsontools.load_json(data_serie)
    # Para series que en la web se listan divididas por temporadas
    if data_serie["sortedPlaylistChilds"]:
        for season_name in data_serie["sortedPlaylistChilds"]:
            url_season = "http://tv-vip.com/json/playlist/%s/index.json" % season_name['id']
            data = scrapertools.anti_cloudflare(url_season, host=host, headers=headers)
            data = jsontools.load_json(data)

            if data["sortedRepoChilds"]:
                for child in data["sortedRepoChilds"]:
                    url = "http://tv-vip.com/json/repo/%s/index.json" % child["id"]
                    fulltitle = child['name'].rsplit(" ", 1)[0] + " - " + child['name'].rsplit(" ", 1)[1]
                    try:
                        check_filename = scrapertools.get_season_and_episode(fulltitle)
                    except:
                        fulltitle += " " + str(data['seasonNumber']) + "x00"
                    lista_episodios.append(
                            item.clone(action="findvideos", server="", title=fulltitle,
                                       extra=url, url=item.url, fulltitle=fulltitle, show=show))
            else:
                for child in data["repoChilds"]:
                    url = "http://tv-vip.com/json/repo/%s/index.json" % child
                    fulltitle = child.capitalize().replace('_', ' ')
                    try:
                        check_filename = scrapertools.get_season_and_episode(fulltitle)
                    except:
                        fulltitle += " " + str(data['seasonNumber']) + "x00"
                    lista_episodios.append(
                            item.clone(action="findvideos", server="", title=fulltitle,
                                       extra=url, url=item.url, fulltitle=fulltitle, show=show))
    # Para series directas de una sola temporada
    else:
        data = data_serie
        if data["sortedRepoChilds"]:
            for child in data["sortedRepoChilds"]:
                url = "http://tv-vip.com/json/repo/%s/index.json" % child["id"]
                fulltitle = child['name'].rsplit(" ", 1)[0] + " - " + child['name'].rsplit(" ", 1)[1]
                try:
                    check_filename = scrapertools.get_season_and_episode(fulltitle)
                except:
                    fulltitle += " 1x00"
                lista_episodios.append(item.clone(action="findvideos", server="", title=fulltitle, url=item.url,
                                                  extra=url, fulltitle=fulltitle, show=show))
        else:
            for child in data["repoChilds"]:
                url = "http://tv-vip.com/json/repo/%s/index.json" % child
                fulltitle = child.capitalize().replace('_', ' ')
                try:
                    check_filename = scrapertools.get_season_and_episode(fulltitle)
                except:
                    fulltitle += " 1x00"
                lista_episodios.append(item.clone(action="findvideos", server="", title=fulltitle, url=item.url,
                                                  extra=url, fulltitle=fulltitle, show=show))
    try:
        from platformcode import library
        library.save_library_tvshow(item, lista_episodios)
        if "Añadir esta serie" in item.title:
            library.save_tvshow_in_file(item)
        error = False
    except:
        import traceback
        logger.info(traceback.format_exc())
        error = True

    if not error:
        itemlist.append(Item(channel=item.channel, title='Serie añadida correctamente a la biblioteca',
                             action="", folder=False))
    else:
        itemlist.append(Item(channel=item.channel, title='ERROR. Han ocurrido uno o varios errores en el proceso',
                             action="", folder=False))

    return itemlist
Пример #9
0
def main():
    logger.info("pelisalacarta.library_service Actualizando series...")

    directorio = library.join_path(config.get_library_path(), "SERIES")
    logger.info("directorio="+directorio)

    if not library.path_exists(directorio):
        library.make_dir(directorio)

    library.check_tvshow_xml()

    try:

        if config.get_setting("updatelibrary") == "true":

            data, dict_data = lib_data()

            heading = 'Actualizando biblioteca....'
            p_dialog = platformtools.dialog_progress_bg('pelisalacarta', heading)
            p_dialog.update(0, '')
            i = 0
            # fix float porque la division se hace mal en python 2.x
            t = float(100) / len(dict_data.keys())

            for tvshow_id in dict_data.keys():
                logger.info("pelisalacarta.library_service serie="+dict_data[tvshow_id]["name"])

                for channel in dict_data[tvshow_id]["channels"].keys():
                    carpeta = "{0} [{1}]".format(library.title_to_filename(
                        dict_data[tvshow_id]["channels"][channel]["tvshow"].lower()), channel)
                    # carpeta = dict_serie[tvshow_id]["channels"][channel]["path"]
                    ruta = library.join_path(config.get_library_path(), "SERIES", carpeta)
                    logger.info("pelisalacarta.library_service ruta =#"+ruta+"#")

                    i += 1
                    if library.path_exists(ruta):
                        logger.info("pelisalacarta.library_service Actualizando "+carpeta)
                        logger.info("pelisalacarta.library_service url " +
                                    dict_data[tvshow_id]["channels"][channel]["url"])

                        p_dialog.update(int(math.ceil(i * t)), heading, dict_data[tvshow_id]["name"])

                        item = Item(url=dict_data[tvshow_id]["channels"][channel]["url"],
                                    show=dict_data[tvshow_id]["channels"][channel]["tvshow"], channel=channel)

                        try:
                            pathchannels = library.join_path(config.get_runtime_path(), 'channels', channel + '.py')
                            logger.info("pelisalacarta.library_service Cargando canal  " + pathchannels + " " + channel)
                            obj = imp.load_source(channel, pathchannels)
                            itemlist = obj.episodios(item)

                            try:
                                library.save_library_tvshow(item, itemlist)
                            except Exception as ex:
                                logger.info("pelisalacarta.library_service Error al guardar los capitulos de la serie")
                                template = "An exception of type {0} occured. Arguments:\n{1!r}"
                                message = template.format(type(ex).__name__, ex.args)
                                logger.info(message)

                        except Exception as ex:
                            logger.error("Error al obtener los episodios de: {0}".
                                         format(dict_data[tvshow_id]["channels"][channel]["tvshow"]))
                            template = "An exception of type {0} occured. Arguments:\n{1!r}"
                            message = template.format(type(ex).__name__, ex.args)
                            logger.info(message)
                    else:
                        logger.info("pelisalacarta.library_service No actualiza {0} (no existe el directorio)".
                                    format(dict_data[tvshow_id]["name"]))

                        p_dialog.update(int(math.ceil(i * t)), 'Error al obtener ruta...', dict_data[tvshow_id]["name"])

            p_dialog.close()
            library.update()
        else:
            logger.info("No actualiza la biblioteca, está desactivado en la configuración de pelisalacarta")

    except Exception as ex:
        import traceback
        logger.info(traceback.format_exc())

        if p_dialog:
            p_dialog.close()
Пример #10
0
def convert_old_to_v4():
    logger.info("pelisalacarta.platformcode.library_service convert_old_to_v4")
    path_series_xml = filetools.join(config.get_data_path(), "series.xml")
    path_series_json = filetools.join(config.get_data_path(), "series.json")
    series_insertadas = 0
    series_fallidas = 0
    version = 'v?'

    # Renombrar carpeta Series y crear una vacia
    import time
    new_name = "SERIES_OLD_" + str(time.time())
    path_series_old = filetools.join(library.LIBRARY_PATH, new_name)
    if filetools.rename(library.TVSHOWS_PATH, new_name):
        if not filetools.mkdir(library.TVSHOWS_PATH):
            logger.info(
                "ERROR, no se ha podido crear la nueva carpeta de SERIES")
            return False
    else:
        logger.error(
            "ERROR, no se ha podido renombrar la antigua carpeta de SERIES")
        return False

    # Convertir libreria de v1(xml) a v4
    if filetools.exists(path_series_xml):
        try:
            data = filetools.read(path_series_xml)
            for line in data.splitlines():
                try:
                    aux = line.rstrip('\n').split(",")
                    tvshow = aux[0].strip()
                    url = aux[1].strip()
                    channel = aux[2].strip()

                    serie = Item(contentSerieName=tvshow,
                                 url=url,
                                 channel=channel,
                                 action="episodios",
                                 title=tvshow,
                                 active=True)

                    patron = "^(.+)[\s]\((\d{4})\)$"
                    matches = re.compile(patron, re.DOTALL).findall(
                        serie.contentSerieName)

                    if matches:
                        serie.infoLabels['title'] = matches[0][0]
                        serie.infoLabels['year'] = matches[0][1]
                    else:
                        serie.infoLabels['title'] = tvshow

                    insertados, sobreescritos, fallidos = library.save_library_tvshow(
                        serie, list())
                    if fallidos == 0:
                        series_insertadas += 1
                        platformtools.dialog_notification(
                            "Serie actualizada", serie.infoLabels['title'])
                    else:
                        series_fallidas += 1
                except:
                    series_fallidas += 1

            filetools.rename(path_series_xml, "series.xml.old")
            version = 'v4'

        except EnvironmentError:
            logger.info("ERROR al leer el archivo: %s" % path_series_xml)
            return False

    # Convertir libreria de v2(json) a v4
    if filetools.exists(path_series_json):
        try:
            data = jsontools.load_json(filetools.read(path_series_json))
            for tvshow in data:
                for channel in data[tvshow]["channels"]:
                    try:
                        serie = Item(
                            contentSerieName=data[tvshow]["channels"][channel]
                            ["tvshow"],
                            url=data[tvshow]["channels"][channel]["url"],
                            channel=channel,
                            action="episodios",
                            title=data[tvshow]["name"],
                            active=True)
                        if not tvshow.startswith("t_"):
                            serie.infoLabels["tmdb_id"] = tvshow

                        insertados, sobreescritos, fallidos = library.save_library_tvshow(
                            serie, list())
                        if fallidos == 0:
                            series_insertadas += 1
                            platformtools.dialog_notification(
                                "Serie actualizada", serie.infoLabels['title'])
                        else:
                            series_fallidas += 1
                    except:
                        series_fallidas += 1

            filetools.rename(path_series_json, "series.json.old")
            version = 'v4'

        except EnvironmentError:
            logger.info("ERROR al leer el archivo: %s" % path_series_json)
            return False

    # Convertir libreria de v3 a v4
    if version != 'v4':
        # Obtenemos todos los tvshow.json de la biblioteca de SERIES_OLD recursivamente
        for raiz, subcarpetas, ficheros in filetools.walk(path_series_old):
            for f in ficheros:
                if f == "tvshow.json":
                    try:
                        serie = Item().fromjson(
                            filetools.read(filetools.join(raiz, f)))
                        insertados, sobreescritos, fallidos = library.save_library_tvshow(
                            serie, list())
                        if fallidos == 0:
                            series_insertadas += 1
                            platformtools.dialog_notification(
                                "Serie actualizada", serie.infoLabels['title'])
                        else:
                            series_fallidas += 1
                    except:
                        series_fallidas += 1

    config.set_setting("library_version", 'v4')

    platformtools.dialog_notification(
        "Biblioteca actualizada al nuevo formato",
        "%s series convertidas y %s series descartadas. A continuación se va a "
        "obtener la información de todos los episodios" %
        (series_insertadas, series_fallidas),
        time=12000)

    # Por ultimo limpia la libreria, por que las rutas anteriores ya no existen
    library.clean()

    return True
Пример #11
0
def convert_old_to_v4():
    logger.info("pelisalacarta.platformcode.library_service convert_old_to_v4")
    path_series_xml = filetools.join(config.get_data_path(), "series.xml")
    path_series_json = filetools.join(config.get_data_path(), "series.json")
    series_insertadas = 0
    series_fallidas = 0
    version = 'v?'

    # Renombrar carpeta Series y crear una vacia
    import time
    new_name = "SERIES_OLD_" + str(time.time())
    path_series_old = filetools.join(library.LIBRARY_PATH, new_name)
    if filetools.rename(library.TVSHOWS_PATH,  new_name):
        if not filetools.mkdir(library.TVSHOWS_PATH):
            logger.info("ERROR, no se ha podido crear la nueva carpeta de SERIES")
            return False
    else:
        logger.error("ERROR, no se ha podido renombrar la antigua carpeta de SERIES")
        return False

    # Convertir libreria de v1(xml) a v4
    if filetools.exists(path_series_xml):
        try:
            data = filetools.read(path_series_xml)
            for line in data.splitlines():
                try:
                    aux = line.rstrip('\n').split(",")
                    tvshow = aux[0].strip()
                    url = aux[1].strip()
                    channel = aux[2].strip()

                    serie = Item(contentSerieName=tvshow, url=url, channel=channel, action="episodios",
                                 title=tvshow, active=True)

                    patron = "^(.+)[\s]\((\d{4})\)$"
                    matches = re.compile(patron, re.DOTALL).findall(serie.contentSerieName)

                    if matches:
                        serie.infoLabels['title'] = matches[0][0]
                        serie.infoLabels['year'] = matches[0][1]
                    else:
                        serie.infoLabels['title'] = tvshow

                    insertados, sobreescritos, fallidos = library.save_library_tvshow(serie, list())
                    if fallidos == 0:
                        series_insertadas += 1
                        platformtools.dialog_notification("Serie actualizada", serie.infoLabels['title'])
                    else:
                        series_fallidas += 1
                except:
                    series_fallidas += 1

            filetools.rename(path_series_xml, "series.xml.old")
            version = 'v4'

        except EnvironmentError:
            logger.info("ERROR al leer el archivo: %s" % path_series_xml)
            return False

    # Convertir libreria de v2(json) a v4
    if filetools.exists(path_series_json):
        try:
            data = jsontools.load_json(filetools.read(path_series_json))
            for tvshow in data:
                for channel in data[tvshow]["channels"]:
                    try:
                        serie = Item(contentSerieName=data[tvshow]["channels"][channel]["tvshow"],
                                     url=data[tvshow]["channels"][channel]["url"], channel=channel, action="episodios",
                                     title=data[tvshow]["name"], active=True)
                        if not tvshow.startswith("t_"):
                            serie.infoLabels["tmdb_id"] = tvshow

                        insertados, sobreescritos, fallidos = library.save_library_tvshow(serie, list())
                        if fallidos == 0:
                            series_insertadas += 1
                            platformtools.dialog_notification("Serie actualizada", serie.infoLabels['title'])
                        else:
                            series_fallidas += 1
                    except:
                        series_fallidas += 1

            filetools.rename(path_series_json, "series.json.old")
            version = 'v4'

        except EnvironmentError:
            logger.info("ERROR al leer el archivo: %s" % path_series_json)
            return False

    # Convertir libreria de v3 a v4
    if version != 'v4':
        # Obtenemos todos los tvshow.json de la biblioteca de SERIES_OLD recursivamente
        for raiz, subcarpetas, ficheros in filetools.walk(path_series_old):
            for f in ficheros:
                if f == "tvshow.json":
                    try:
                        serie = Item().fromjson(filetools.read(filetools.join(raiz, f)))
                        insertados, sobreescritos, fallidos = library.save_library_tvshow(serie, list())
                        if fallidos == 0:
                            series_insertadas += 1
                            platformtools.dialog_notification("Serie actualizada", serie.infoLabels['title'])
                        else:
                            series_fallidas += 1
                    except:
                        series_fallidas += 1

    config.set_setting("library_version", 'v4')

    platformtools.dialog_notification("Biblioteca actualizada al nuevo formato",
                                      "%s series convertidas y %s series descartadas. A continuación se va a "
                                      "obtener la información de todos los episodios" %
                                      (series_insertadas, series_fallidas), time=12000)

    # Por ultimo limpia la libreria, por que las rutas anteriores ya no existen
    library.clean()

    return True