Esempio n. 1
0
def overwrite_tools(item):
    import library_service
    from core import library

    seleccion = platformtools.dialog_yesno("Sovrascrivere la libreria?",
                                           "Richiede un certo tempo.",
                                           "Continuare?")
    if seleccion == 1:
        heading = 'Sovrascrivo la libreria....'
        p_dialog = platformtools.dialog_progress_bg('Stefano', heading)
        p_dialog.update(0, '')

        import glob
        show_list = glob.glob(
            filetools.join(library.TVSHOWS_PATH, u'/*/tvshow.sod'))

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

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

            if not serie.active:
                # si la serie no esta activa descartar
                continue

            # Eliminamos la carpeta con la serie ...
            filetools.rmdirtree(path)

            # ... y la volvemos a añadir
            library_service.update(path, p_dialog, i, t, serie, 3)

        p_dialog.close()
Esempio n. 2
0
def export_videolibrary(item):
    logger.info()

    zip_file_folder = platformtools.dialog_browse(3, config.get_localized_string(80002))
    if zip_file_folder == "":
        return
    zip_file = xbmc.translatePath(zip_file_folder + "KoD_video_library-" + str(datetime.date.today()) + ".zip")

    p_dialog = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(80003))
    p_dialog.update(0)

    if filetools.exists(temp_path):
        filetools.rmdirtree(temp_path)
    filetools.mkdir(temp_path)
    p_dialog.update(25)
    filetools.mkdir(movies_path)
    copy_tree(videolibrarytools.MOVIES_PATH, movies_path)
    p_dialog.update(50)
    filetools.mkdir(tvshows_path)
    copy_tree(videolibrarytools.TVSHOWS_PATH, tvshows_path)
    p_dialog.update(75)

    zipper = ziptools.ziptools()
    zipper.zip(temp_path, zip_file)

    filetools.rmdirtree(temp_path)

    p_dialog.update(100)
    xbmc.sleep(1000)
    p_dialog.close()
    platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80004), time=5000, sound=False)
Esempio n. 3
0
    def delete_all(_item):
        for file in filetools.listdir(_item.path):
            if file.endswith(".strm") or file.endswith(".nfo") or file.endswith(".json")or file.endswith(".torrent"):
                filetools.remove(filetools.join(_item.path, file))

        if _item.contentType == 'movie':
            heading = config.get_localized_string(70084)
        else:
            heading = config.get_localized_string(70085)

        if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
            from platformcode import xbmc_videolibrary
            if _item.local_episodes_path:
                platformtools.dialog_ok(heading, config.get_localized_string(80047) % _item.infoLabels['title'])
            path_list = [_item.extra]
            xbmc_videolibrary.clean(path_list)

        raiz, carpeta_serie, ficheros = next(filetools.walk(_item.path))
        if ficheros == []:
            filetools.rmdir(_item.path)
        elif platformtools.dialog_yesno(heading, config.get_localized_string(70081) % filetools.basename(_item.path)):
            filetools.rmdirtree(_item.path)

        logger.info("All links removed")
        xbmc.sleep(1000)
        platformtools.itemlist_refresh()
def update_biblio(item):
    logger.info()

    # Actualizar las series activas sobreescribiendo
    import library_service
    if item.extra == "overwrite_everything":
        if config.is_xbmc():
            seleccion = platformtools.dialog_yesno(config.PLUGIN_NAME,
                                                   "Avviso: devi attendere.",
                                                   "Vuoi continuare ?")
            if seleccion == 1:
                library_service.check_for_update(overwrite="everything")

        else:
            library_service.check_for_update(overwrite="everything")
    else:
        library_service.check_for_update(overwrite=True)

    # Eliminar las carpetas de peliculas que no contengan archivo strm
    for raiz, subcarpetas, ficheros in filetools.walk(library.MOVIES_PATH):
        strm = False
        for f in ficheros:
            if f.endswith(".strm"):
                strm = True
                break

        if ficheros and not strm:
            logger.debug("Borrando carpeta de pelicula eliminada: %s" % raiz)
            filetools.rmdirtree(raiz)
def update_biblio(item):
    logger.info()

    # Actualizar las series activas sobreescribiendo
    import library_service
    if item.extra == "overwrite_everything":
        if config.is_xbmc():
            seleccion = platformtools.dialog_yesno(config.PLUGIN_NAME,
                                                   "Avviso: devi attendere.",
                                                   "Vuoi continuare ?")
            if seleccion == 1:
                library_service.check_for_update(overwrite="everything")

        else:
            library_service.check_for_update(overwrite="everything")
    else:
        library_service.check_for_update(overwrite=True)

    # Eliminar las carpetas de peliculas que no contengan archivo strm
    for raiz, subcarpetas, ficheros in filetools.walk(library.MOVIES_PATH):
        strm = False
        for f in ficheros:
            if f.endswith(".strm"):
                strm = True
                break

        if ficheros and not strm:
            logger.debug("Borrando carpeta de pelicula eliminada: %s" % raiz)
            filetools.rmdirtree(raiz)
Esempio n. 6
0
def overwrite_tools(item):
    import library_service
    from core import library

    seleccion = platformtools.dialog_yesno("Sobrescribir toda la biblioteca",
                                           "Esto puede llevar algun tiempo.",
                                           "¿Desea continuar?")
    if seleccion == 1:
        heading = 'Sobrescribiendo biblioteca....'
        p_dialog = platformtools.dialog_progress_bg('mitvspain', heading)
        p_dialog.update(0, '')

        import glob
        show_list = glob.glob(filetools.join(library.TVSHOWS_PATH, u'/*/tvshow.nfo'))

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

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

            if not serie.active:
                # si la serie no esta activa descartar
                continue

            # Eliminamos la carpeta con la serie ...
            filetools.rmdirtree(path)

            # ... y la volvemos a añadir
            library_service.update(path, p_dialog, i, t, serie, 3)

        p_dialog.close()
Esempio n. 7
0
    def eliminar_todo(item):
        filetools.rmdirtree(item.path)
        if config.is_xbmc():
            import xbmc
            # esperamos 3 segundos para dar tiempo a borrar los ficheros
            xbmc.sleep(3000)
            # TODO mirar por qué no funciona al limpiar en la biblioteca de Kodi al añadirle un path
            # limpiamos la biblioteca de Kodi
            library.clean()

        logger.info("Eliminados todos los enlaces")
        platformtools.itemlist_refresh()
Esempio n. 8
0
    def eliminar_todo(item):
        filetools.rmdirtree(item.path)
        if config.is_xbmc():
            import xbmc
            # esperamos 3 segundos para dar tiempo a borrar los ficheros
            xbmc.sleep(3000)
            # TODO mirar por qué no funciona al limpiar en la biblioteca de Kodi al añadirle un path
            # limpiamos la biblioteca de Kodi
            library.clean()

        logger.info("Eliminados todos los enlaces")
        platformtools.itemlist_refresh()
Esempio n. 9
0
def delete_file(item):
    logger.info()
    from core import filetools

    msg = config.get_localized_string(60044) % item.url_org or item.url
    if platformtools.dialog_yesno(config.get_localized_string(70221), msg):

        for file in [item.url, item.url_org]:
            if filetools.isdir(file):
                filetools.rmdirtree(file, silent=True)
                logger.info('Deleting folder: %s' % file)
            elif filetools.isfile(file):
                filetools.remove(file, silent=True)
                logger.info('Deleting file: %s' % file)

        platformtools.itemlist_refresh()
Esempio n. 10
0
 def __init__(self, key, referer):
     if sys.version_info[0] < 3:
         self.rc = None
         platformtools.dialog_ok(
             'reCAPTCHA',
             'Il sito sta mostrando la schermata "Non sono un robot".\nQuesta schermata tuttavia è superabile solo da kodi 19'
         )
     else:
         prog = platformtools.dialog_progress(
             'Caricamento reCAPTCHA',
             'Il sito sta mostrando la schermata "Non sono un robot"')
         filetools.rmdirtree(temp_dir)
         self.rc = ReCaptcha(api_key=key,
                             site_url=referer,
                             user_agent=httptools.get_user_agent(),
                             lang=lang)
         prog.close()
Esempio n. 11
0
def update_videolibrary(item):
    logger.info()

    # Actualizar las series activas sobreescribiendo
    import videolibrary_service
    videolibrary_service.check_for_update(overwrite=True)

    # Eliminar las carpetas de peliculas que no contengan archivo strm
    for raiz, subcarpetas, ficheros in filetools.walk(videolibrarytools.MOVIES_PATH):
        strm = False
        for f in ficheros:
            if f.endswith(".strm"):
                strm = True
                break

        if ficheros and not strm:
            logger.debug("Borrando carpeta de pelicula eliminada: %s" % raiz)
            filetools.rmdirtree(raiz)
Esempio n. 12
0
def update_biblio(item):
    logger.info()

    # Actualizar las series activas sobreescribiendo
    import library_service
    library_service.check_for_update(overwrite=True)

    # Eliminar las carpetas de peliculas que no contengan archivo strm
    for raiz, subcarpetas, ficheros in filetools.walk(library.MOVIES_PATH):
        strm = False
        for f in ficheros:
            if f.endswith(".strm"):
                strm = True
                break

        if ficheros and not strm:
            logger.debug("Borrando carpeta de pelicula eliminada: %s" % raiz)
            filetools.rmdirtree(raiz)
Esempio n. 13
0
def update_videolibrary(item=''):
    logger.info()

    # Update active series by overwriting
    import service
    service.check_for_update(overwrite=True)

    # Delete movie folders that do not contain strm file
    for raiz, subcarpetas, ficheros in filetools.walk(videolibrarytools.MOVIES_PATH):
        strm = False
        for f in ficheros:
            if f.endswith(".strm"):
                strm = True
                break

        if ficheros and not strm:
            logger.debug("Deleting deleted movie folder: %s" % raiz)
            filetools.rmdirtree(raiz)
Esempio n. 14
0
def updatebiblio(item):
    logger.info("pelisalacarta.channels.ayuda updatebiblio")

    # Actualizar las series activas sobreescribiendo
    import library_service
    library_service.main()

    # Eliminar las carpetas de peliculas que no contengan archivo strm
    from platformcode import library
    for raiz, subcarpetas, ficheros in filetools.walk(library.MOVIES_PATH):
        strm = False
        for f in ficheros:
            if f.endswith(".strm"):
                strm = True
                break

        if ficheros and not strm:
            logger.debug("Borrando carpeta de pelicula eliminada: %s" % raiz)
            filetools.rmdirtree(raiz)
Esempio n. 15
0
def updatebiblio(item):
    logger.info("pelisalacarta.channels.ayuda updatebiblio")

    # Actualizar las series activas sobreescribiendo
    import library_service
    library_service.main()

    # Eliminar las carpetas de peliculas que no contengan archivo strm
    from platformcode import library
    for raiz, subcarpetas, ficheros in filetools.walk(library.MOVIES_PATH):
        strm = False
        for f in ficheros:
            if f.endswith(".strm"):
                strm = True
                break

        if ficheros and not strm:
            logger.debug("Borrando carpeta de pelicula eliminada: %s" % raiz)
            filetools.rmdirtree(raiz)
Esempio n. 16
0
    def eliminar_todo(_item):
        path = (_item.path).decode("utf8")
        ficheros = os.listdir(path)
        for file in ficheros:
            if file.endswith(".strm") or file.endswith(".sod") or file.endswith(".json"):
                os.remove(filetools.join(path, file))
        if not os.listdir(path):
            filetools.rmdirtree(path)

        if config.is_xbmc():
            import xbmc
            # esperamos 3 segundos para dar tiempo a borrar los ficheros
            xbmc.sleep(3000)
            # TODO mirar por qué no funciona al limpiar en la biblioteca de Kodi al añadirle un path
            # limpiamos la biblioteca de Kodi
            from platformcode import xbmc_library
            xbmc_library.clean()

        logger.info("Eliminados todos los enlaces")
        platformtools.itemlist_refresh()
Esempio n. 17
0
def import_videolibrary(item):
    logger.info()

    zip_file = u'' + platformtools.dialog_browse(
        1, config.get_localized_string(80005), mask=".zip")
    if zip_file == "":
        return
    if not platformtools.dialog_yesno(config.get_localized_string(20000),
                                      config.get_localized_string(80006)):
        return

    p_dialog = platformtools.dialog_progress_bg(
        config.get_localized_string(20000), config.get_localized_string(80007))
    p_dialog.update(0)

    if filetools.exists(temp_path):
        filetools.rmdirtree(temp_path)
    filetools.mkdir(temp_path)

    unzipper = ziptools.ziptools()
    unzipper.extract(zip_file, temp_path)
    p_dialog.update(20)

    if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
        xbmc_videolibrary.clean()
    p_dialog.update(30)
    filetools.rmdirtree(videolibrary_movies_path)
    filetools.rmdirtree(videolibrary_tvshows_path)
    p_dialog.update(50)

    config.verify_directories_created()
    if filetools.exists(movies_path):
        copy_tree(movies_path, videolibrary_movies_path)
    p_dialog.update(70)
    if filetools.exists(tvshows_path):
        copy_tree(tvshows_path, videolibrary_tvshows_path)
    p_dialog.update(90)
    filetools.rmdirtree(temp_path)

    p_dialog.update(100)
    xbmc.sleep(1000)
    p_dialog.close()
    platformtools.dialog_notification(config.get_localized_string(20000),
                                      config.get_localized_string(80008),
                                      time=5000,
                                      sound=False)

    videolibrary.update_videolibrary()
    if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
        xbmc_videolibrary.update()
Esempio n. 18
0
def download_and_install(remote_file_name, local_file_name):
    logger.info("Stefano.core.updater download_and_install from " +
                remote_file_name + " to " + local_file_name)

    if os.path.exists(local_file_name):
        os.remove(local_file_name)

    # Descarga el fichero
    inicio = time.clock()
    from core import downloadtools
    downloadtools.downloadfile(remote_file_name,
                               local_file_name,
                               continuar=False)
    fin = time.clock()
    logger.info("Stefano.core.updater Descargado en %d segundos " %
                (fin - inicio + 1))

    logger.info("Stefano.core.updater descomprime fichero...")
    import xbmc
    from core import filetools
    path_channels = xbmc.translatePath(
        "special://home/addons/plugin.video.Stefano/channels")
    filetools.rmdirtree(path_channels)
    path_servers = xbmc.translatePath(
        "special://home/addons/plugin.video.Stefano/servers")
    filetools.rmdirtree(path_servers)
    import ziptools
    unzipper = ziptools.ziptools()

    # Lo descomprime en "addons" (un nivel por encima del plugin)
    installation_target = os.path.join(config.get_runtime_path(), "..")
    logger.info("Stefano.core.updater installation_target=%s" %
                installation_target)

    unzipper.extract(local_file_name, installation_target)

    # Borra el zip descargado
    logger.info("Stefano.core.updater borra fichero...")
    os.remove(local_file_name)
    logger.info("Stefano.core.updater ...fichero borrado")
Esempio n. 19
0
def reset(item):
    logger.info("Stefano.channels.ayuda reset")
    itemlist = []
    risp = platformtools.dialog_yesno(
        "Reset Stream On Demand",
        " ",
        "Sei sicuro di voler resettare tutte le impostazioni di SoD ?",
        " ",
        nolabel="Annulla",
        yeslabel="Conferma")
    if risp == 0:
        logger.info("Annulla")
    if risp == 1:
        logger.info("Conferma")
        path = xbmc.translatePath(
            "special://profile/addon_data/plugin.video.Stefano")
        filetools.rmdirtree(path)
        config.verify_directories_created()
        platformtools.dialog_ok(
            "Reset Stream On Demand", " ",
            "Reset delle impostazioni è avvenuto con successo!", " ")

    return platformtools.itemlist_refresh()
Esempio n. 20
0
def delete_videolibrary(item):
    logger.info()

    if not platformtools.dialog_yesno(config.get_localized_string(20000), config.get_localized_string(80037)):
        return

    p_dialog = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(80038))
    p_dialog.update(0)

    if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
        from platformcode import xbmc_videolibrary
        xbmc_videolibrary.clean()
    p_dialog.update(10)
    filetools.rmdirtree(videolibrarytools.MOVIES_PATH)
    p_dialog.update(50)
    filetools.rmdirtree(videolibrarytools.TVSHOWS_PATH)
    p_dialog.update(90)

    config.verify_directories_created()
    p_dialog.update(100)
    xbmc.sleep(1000)
    p_dialog.close()
    platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80039), time=5000, sound=False)
Esempio n. 21
0
def overwrite_tools(item):
    import library_service
    from core import library


    seleccion = platformtools.dialog_yesno("Sobrescribir toda la biblioteca",
                                           "Esto puede llevar algun tiempo.",
                                           "¿Desea continuar?")
    if seleccion == 1:
        heading = 'Sobrescribiendo biblioteca....'
        p_dialog = platformtools.dialog_progress_bg('pelisalacarta', heading)
        p_dialog.update(0, '')
        show_list = []

        for path, folders, files in filetools.walk(library.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 = library.read_nfo(tvshow_file)
            path = filetools.dirname(tvshow_file)

            if not serie.active:
                # si la serie no esta activa descartar
                continue

            # Eliminamos la carpeta con la serie ...
            filetools.rmdirtree(path)

            # ... y la volvemos a añadir
            library_service.update(path, p_dialog, i, t, serie, 3)


        p_dialog.close()
Esempio n. 22
0
def download(item=None):
    if filetools.exists(quasar_path):
        xbmc.executeJSONRPC(
            '{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "plugin.video.quasar", "enabled": false }}'
        )
        sleep(1)
        filetools.rmdirtree(quasar_path)

    if filetools.exists(filename):
        filetools.remove(filename)
        return download()
    else:
        platform = get_platform()
        support.log('OS:', platform)
        support.log('Extract IN:', quasar_path)
        url = support.match(
            quasar_url,
            patronBlock=
            r'<div class="release-entry">(.*?)<!-- /.release-body -->',
            patron=r'<a href="([a-zA-Z0-9/\.-]+%s.zip)' % platform).match
        support.log('URL:', url)
        if url:
            downloadtools.downloadfile(host + url, filename)
            extract()
Esempio n. 23
0
def import_videolibrary(item):
    logger.info()

    zip_file = platformtools.dialog_browse(1,
                                           config.get_localized_string(80005))
    if zip_file == "":
        return
    if not platformtools.dialog_yesno(config.get_localized_string(20000),
                                      config.get_localized_string(80006)):
        return

    p_dialog = platformtools.dialog_progress_bg(
        config.get_localized_string(20000), config.get_localized_string(80007))
    p_dialog.update(0)

    if filetools.exists(temp_path):
        filetools.rmdirtree(temp_path)
    filetools.mkdir(temp_path)

    unzipper = ziptools.ziptools()
    unzipper.extract(zip_file, temp_path)
    p_dialog.update(25)

    filetools.rmdirtree(videolibrarytools.VIDEOLIBRARY_PATH)
    p_dialog.update(50)
    if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
        xbmc.sleep(5000)
        xbmc_videolibrary.clean()

    config.verify_directories_created()
    if filetools.exists(movies_path):
        copy_tree(movies_path, videolibrarytools.MOVIES_PATH)
    p_dialog.update(70)
    if filetools.exists(tvshows_path):
        copy_tree(tvshows_path, videolibrarytools.TVSHOWS_PATH)
    p_dialog.update(90)
    filetools.rmdirtree(temp_path)

    p_dialog.update(100)
    xbmc.sleep(2000)
    p_dialog.close()
    platformtools.dialog_ok(config.get_localized_string(20000),
                            config.get_localized_string(80008))

    if platformtools.dialog_yesno(config.get_localized_string(20000),
                                  config.get_localized_string(80009)):
        import service
        service.check_for_update(overwrite=True)

    if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
        xbmc_videolibrary.update()
Esempio n. 24
0
def init():
    logger.info()
    """
    Todo el código añadido al add-on se borra con cada actualización.  Esta función permite restaurarlo automáticamente con cada actualización.  Esto permite al usuario tener su propio código, bajo su responsabilidad, y restaurarlo al add-on cada vez que se actualiza.
    
    El mecanismo funciona copiando el contenido de la carpeta-arbol "./userdata/addon_data/plugin.video.alfa/custom_code/..." sobre
    las carpetas de código del add-on.  No verifica el contenido, solo vuelca(reemplaza) el contenido de "custom_code".
    
    El usuario almacenará en las subcarpetas de "custom_code" su código actualizado y listo para ser copiado en cualquier momento.
    Si no se desea que copie algo, simplemente se borra de "custom_code" y ya no se copiará en la próxima actualización.
    
    Los pasos que sigue esta función, son los siguientes:
    
    1.- La función se llama desde videolibrary_service.py, desde la función inicial:
            # Copia Custom code a las carpetas de Alfa desde la zona de Userdata
            from platformcode import custom_code
            custom_code.init()
            
    2.- En el inicio de Kodi, comprueba si existe la carpeta "custom_code" en "./userdata/addon_data/plugin.video.alfa/".  
        Si no existe, la crea y sale sin más, dando al ususario la posibilidad de copiar sobre esa estructura su código, 
        y que la función la vuelque sobre el add-on en el próximo inicio de Kodi.
        
    3.- En el siguiente inicio de Kodi, comprueba si existe el custom_code.json en la carpeta root del add-on.
        Si no existe, lo crea con el número de versión del add-on vacío, para permitir que se copien los archivos en esta pasada.
        
    4.- Verifica que el número de versión del add-on es diferente de el de custom_code.json.  Si es la misma versión, 
        se sale porque ya se realizo la copia anteriormente.
        Si la versión es distinta, se realiza el volcado de todos los archivos de la carpeta-árbol "custom_code" sobre el add-on.
        Si la carpeta de destino no existe, dará un error y se cancelará la copia.  Se considera que no tienen sentido nuevas carpetas.
        
    5.- Si la copia ha terminado con éxito, se actualiza el custom_code.json con el número de versión del add-on,
        para que en inicios sucesivos de Kodi no se realicen las copias, hasta que el add-on cambie de versión.
        En el número de versión del add-on no se considera el número de fix.
        
    Tiempos:    Copiando 7 archivos de prueba, el proceso ha tardado una décima de segundo.
    """

    try:
        #Borra el .zip de instalación de Alfa de la carpeta Packages, por si está corrupto, y que así se pueda descargar de nuevo
        version = 'plugin.video.alfa-%s.zip' % config.get_addon_version(
            with_fix=False)
        filetools.remove(
            filetools.join(xbmc.translatePath('special://home'), 'addons',
                           'packages', version), True)

        #Borrar contenido de carpeta de Torrents
        filetools.rmdirtree(filetools.join(config.get_videolibrary_path(),
                                           'temp_torrents_Alfa'),
                            silent=True)

        #Verifica si Kodi tiene algún achivo de Base de Datos de Vídeo de versiones anteriores, entonces los borra
        verify_Kodi_video_DB()

        #LIBTORRENT: se descarga el binario de Libtorrent cada vez que se actualiza Alfa
        try:
            threading.Thread(target=update_libtorrent).start(
            )  # Creamos un Thread independiente, hasta el fin de Kodi
            time.sleep(2)  # Dejamos terminar la inicialización...
        except:  # Si hay problemas de threading, nos vamos
            logger.error(traceback.format_exc())

        #QUASAR: Preguntamos si se hacen modificaciones a Quasar
        if not filetools.exists(filetools.join(config.get_data_path(), "quasar.json")) \
                    and not config.get_setting('addon_quasar_update', default=False):
            question_update_external_addon("quasar")

        #QUASAR: Hacemos las modificaciones a Quasar, si está permitido, y si está instalado
        if config.get_setting('addon_quasar_update', default=False) or \
                    (filetools.exists(filetools.join(config.get_data_path(), \
                    "quasar.json")) and not xbmc.getCondVisibility('System.HasAddon("plugin.video.quasar")')):
            if not update_external_addon("quasar"):
                platformtools.dialog_notification(
                    "Actualización Quasar", "Ha fallado. Consulte el log")

        #Existe carpeta "custom_code" ? Si no existe se crea y se sale
        custom_code_dir = filetools.join(config.get_data_path(), 'custom_code')
        if not filetools.exists(custom_code_dir):
            create_folder_structure(custom_code_dir)
            return

        else:
            #Existe "custom_code.json" ? Si no existe se crea
            custom_code_json_path = config.get_runtime_path()
            custom_code_json = filetools.join(custom_code_json_path,
                                              'custom_code.json')
            if not filetools.exists(custom_code_json):
                create_json(custom_code_json_path)

            #Se verifica si la versión del .json y del add-on son iguales.  Si es así se sale.  Si no se copia "custom_code" al add-on
            verify_copy_folders(custom_code_dir, custom_code_json_path)

        #Si se han quedado "colgadas" descargas con archivos .RAR, se intenta identificarlos y reactivar el UnRar
        reactivate_unrar(init=True, mute=True)

        #Inicia un rastreo de vídeos decargados desde .torrent: marca los VISTOS y elimina los controles de los BORRADOS
        from servers import torrent
        try:
            threading.Thread(target=torrent.mark_torrent_as_watched).start(
            )  # Creamos un Thread independiente, hasta el fin de Kodi
            time.sleep(2)  # Dejamos terminar la inicialización...
        except:  # Si hay problemas de threading, nos vamos
            logger.error(traceback.format_exc())
    except:
        logger.error(traceback.format_exc())
Esempio n. 25
0
def delete_cache(url):
    folder = filetools.join(config.get_data_path(), 'thumbs_copiapop')
    filetools.rmdirtree(folder)
    if config.is_xbmc():
        import xbmc
        xbmc.executebuiltin("Container.Refresh")
Esempio n. 26
0
def verify_directories_created():
    import logger

    from core import filetools

    # Force download path if empty
    download_path = get_setting("downloadpath")
    if download_path == "":
        download_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/downloads"

        set_setting("downloadpath", download_path)

    # Force download list path if empty
    download_list_path = get_setting("downloadlistpath")
    if download_list_path == "":
        download_list_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/downloads/list"

        set_setting("downloadlistpath", download_list_path)

    # Force bookmark path if empty
    bookmark_path = get_setting("bookmarkpath")
    if bookmark_path == "":
        bookmark_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/downloads/list"

        set_setting("bookmarkpath", bookmark_path)

    # Create data_path if not exists
    if not os.path.exists(get_data_path()):
        logger.debug("Creating data_path " + get_data_path())

        filetools.mkdir(get_data_path())

    # xbmc.log("Es una plataforma XBMC")
    if download_path.startswith("special://"):
        # Translate from special and create download_path if not exists
        download_path = xbmc.translatePath(download_path)
        texto = "(from special)"
    else:
        texto = ""

    # TODO si tiene smb se debería poder dejar que cree? filetools permite crear carpetas para SMB
    if not download_path.lower().startswith("smb") and not filetools.exists(
            download_path):
        logger.debug("Creating download_path" + texto + ": " + download_path)
        filetools.mkdir(download_path)

    if download_list_path.startswith("special://"):
        # Create download_list_path if not exists
        download_list_path = xbmc.translatePath(download_list_path)
        texto = "(from special)"
    else:
        texto = ""

    # TODO si tiene smb se debería poder dejar que cree? filetools permite crear carpetas para SMB
    if not download_list_path.lower().startswith(
            "smb") and not filetools.exists(download_list_path):
        logger.debug("Creating download_list_path" + texto + ": " +
                     download_list_path)
        filetools.mkdir(download_list_path)

    if bookmark_path.startswith("special://"):
        # Create bookmark_path if not exists
        bookmark_path = xbmc.translatePath(bookmark_path)
        texto = "(from special)"
    else:
        texto = ""

    # TODO si tiene smb se debería poder dejar que cree? filetools permite crear carpetas para SMB
    if not bookmark_path.lower().startswith("smb") and not filetools.exists(
            bookmark_path):
        logger.debug("Creating bookmark_path" + texto + ": " + bookmark_path)
        filetools.mkdir(bookmark_path)

    # Create settings_path is not exists
    settings_path = filetools.join(get_data_path(), "settings_channels")
    if not filetools.exists(settings_path):
        logger.debug("Creating settings_path " + settings_path)
        filetools.mkdir(settings_path)

    # Checks that a directory "xbmc" is not present on platformcode
    old_xbmc_directory = os.path.join(get_runtime_path(), "platformcode",
                                      "xbmc")
    if os.path.exists(old_xbmc_directory):
        logger.debug("Removing old platformcode.xbmc directory")
        filetools.rmdirtree(old_xbmc_directory)
Esempio n. 27
0
def move_videolibrary(current_path, new_path, current_movies_folder, new_movies_folder, current_tvshows_folder, new_tvshows_folder):
    logger.info()

    backup_current_path = current_path
    backup_new_path = new_path

    logger.info('current_path: ' + current_path)
    logger.info('new_path: ' + new_path)
    logger.info('current_movies_folder: ' + current_movies_folder)
    logger.info('new_movies_folder: ' + new_movies_folder)
    logger.info('current_tvshows_folder: ' + current_tvshows_folder)
    logger.info('new_tvshows_folder: ' + new_tvshows_folder)

    notify = False
    progress = platformtools.dialog_progress_bg(config.get_localized_string(20000), config.get_localized_string(80011))
    current_path = u'' + xbmc.translatePath(current_path)
    new_path = u'' + xbmc.translatePath(new_path)
    current_movies_path = u'' + filetools.join(current_path, current_movies_folder)
    new_movies_path = u'' + filetools.join(new_path, new_movies_folder)
    current_tvshows_path = u'' + filetools.join(current_path, current_tvshows_folder)
    new_tvshows_path = u'' + filetools.join(new_path, new_tvshows_folder)

    logger.info('current_movies_path: ' + current_movies_path)
    logger.info('new_movies_path: ' + new_movies_path)
    logger.info('current_tvshows_path: ' + current_tvshows_path)
    logger.info('new_tvshows_path: ' + new_tvshows_path)

    from platformcode import xbmc_videolibrary
    movies_path, tvshows_path = xbmc_videolibrary.check_sources(new_movies_path, new_tvshows_path)
    logger.info('check_sources: ' + str(movies_path) + ', ' + str(tvshows_path))
    if movies_path or tvshows_path:
        if not movies_path:
            filetools.rmdir(new_movies_path)
        if not tvshows_path:
            filetools.rmdir(new_tvshows_path)
        config.set_setting("videolibrarypath", backup_current_path)
        config.set_setting("folder_movies", current_movies_folder)
        config.set_setting("folder_tvshows", current_tvshows_folder)
        xbmc_videolibrary.update_sources(backup_current_path, backup_new_path)
        progress.update(100)
        xbmc.sleep(1000)
        progress.close()
        platformtools.dialog_ok(config.get_localized_string(20000), config.get_localized_string(80028))
        return

    config.verify_directories_created()
    progress.update(10, config.get_localized_string(20000) + '\n' + config.get_localized_string(80012))
    if current_movies_path != new_movies_path:
        if filetools.listdir(current_movies_path):
            dir_util.copy_tree(current_movies_path, new_movies_path)
            notify = True
        filetools.rmdirtree(current_movies_path)
    progress.update(40)
    if current_tvshows_path != new_tvshows_path:
        if filetools.listdir(current_tvshows_path):
            dir_util.copy_tree(current_tvshows_path, new_tvshows_path)
            notify = True
        filetools.rmdirtree(current_tvshows_path)
    progress.update(70)
    if current_path != new_path and not filetools.listdir(current_path) and not "plugin.video.kod\\videolibrary" in current_path:
        filetools.rmdirtree(current_path)

    xbmc_videolibrary.update_sources(backup_new_path, backup_current_path)
    if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
        xbmc_videolibrary.update_db(backup_current_path, backup_new_path, current_movies_folder, new_movies_folder, current_tvshows_folder, new_tvshows_folder, progress)
    else:
        progress.update(100)
        xbmc.sleep(1000)
        progress.close()
    if notify:
        platformtools.dialog_notification(config.get_localized_string(20000), config.get_localized_string(80014), time=5000, sound=False)
Esempio n. 28
0
def bt_client(mediaurl, xlistitem, rar_files, subtitle=None, password=None, item=None):
    logger.info()
    
    # Importamos el cliente
    from btserver import Client

    played = False
    debug = False

    save_path_videos = filetools.join(config.get_setting("bt_download_path", server="torrent", 
               default=config.get_setting("downloadpath")), 'BT-torrents')
    if not save_path_videos:
        save_path_videos = filetools.join(config.get_data_path(), 'BT-torrents')
        
    UNRAR = config.get_setting("unrar_path", server="torrent", default="")
    BACKGROUND = config.get_setting("mct_background_download", server="torrent", default=True)
    RAR = config.get_setting("mct_rar_unpack", server="torrent", default=True)
    try:
        BUFFER = int(config.get_setting("bt_buffer", server="torrent", default="50"))
    except:
        BUFFER = 50
    DOWNLOAD_LIMIT = config.get_setting("mct_download_limit", server="torrent", default="")
    if DOWNLOAD_LIMIT:
        try:
            DOWNLOAD_LIMIT = int(DOWNLOAD_LIMIT)
        except:
            DOWNLOAD_LIMIT = 0
    else:
        DOWNLOAD_LIMIT = 0
    UPLOAD_LIMIT = 100
    
    torr_client = 'BT'
    rar_file = ''
    rar_names = []
    rar = False
    rar_res = False
    bkg_user = False
    video_names = []
    video_file = ''
    video_path = ''
    videourl = ''
    msg_header = 'Alfa %s Cliente Torrent' % torr_client
    extensions_list = ['.aaf', '.3gp', '.asf', '.avi', '.flv', '.mpeg',
                       '.m1v', '.m2v', '.m4v', '.mkv', '.mov', '.mpg',
                       '.mpe', '.mp4', '.ogg', '.rar', '.wmv', '.zip']
    
    for entry in rar_files:
        for file, path in entry.items():
            if file == 'path' and '.rar' in str(path):
                for file_r in path:
                    rar_names += [file_r]
                    rar = True
                    if RAR and BACKGROUND:
                        bkg_user = True
            elif file == 'path' and not '.rar' in str(path):
                for file_r in path:
                    if os.path.splitext(file_r)[1] in extensions_list:
                        video_names += [file_r]
            elif file == '__name':
                video_path = path
    if rar: rar_file = '%s/%s' % (video_path, rar_names[0])
    erase_file_path = filetools.join(save_path_videos, video_path)
    video_path = erase_file_path
    if video_names: video_file = video_names[0]
    if not video_file and mediaurl.startswith('magnet'):
        video_file = urllib.unquote_plus(scrapertools.find_single_match(mediaurl, '(?:\&|&amp;)dn=([^\&]+)\&'))
        erase_file_path = filetools.join(save_path_videos, video_file)
    
    if rar and RAR and not UNRAR:
        if not platformtools.dialog_yesno(msg_header, 'Se ha detectado un archivo .RAR en la descarga', \
                    'No tiene instalado el extractor UnRAR', '¿Desea descargarlo en cualquier caso?'):
            return

    # Iniciamos el cliente:
    c = Client(url=mediaurl, is_playing_fnc=xbmc_player.isPlaying, wait_time=None, auto_shutdown=False, timeout=10,
               temp_path=save_path_videos, print_status=debug, auto_delete=False)
    
    activo = True
    finalizado = False
    dp_cerrado = True

    # Mostramos el progreso
    if rar and RAR and BACKGROUND:                                                  # Si se descarga un RAR...
        progreso = platformtools.dialog_progress_bg(msg_header)
        platformtools.dialog_notification("Descarga de RAR en curso", "Puedes realizar otras tareas en Kodi mientrastanto. " + \
                "Te informaremos...", time=10000)
    else:
        progreso = platformtools.dialog_progress('Alfa %s Cliente Torrent' % torr_client, '')
    dp_cerrado = False

    # Mientras el progreso no sea cancelado ni el cliente cerrado
    while not c.closed and not xbmc.abortRequested:
        # Obtenemos el estado del torrent
        s = c.status
        if debug:
            # Montamos las tres lineas con la info del torrent
            txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \
                  (s.progress_file, s.file_size, s.str_state, s._download_rate)
            txt2 = 'S: %d(%d) P: %d(%d) | DHT:%s (%d) | Trakers: %d | Pi: %d(%d)' % \
                   (s.num_seeds, s.num_complete, s.num_peers, s.num_incomplete, s.dht_state, s.dht_nodes,
                    s.trackers, s.pieces_sum, s.pieces_len)
            txt3 = 'Origen Peers TRK: %d DHT: %d PEX: %d LSD %d ' % \
                   (s.trk_peers, s.dht_peers, s.pex_peers, s.lsd_peers)
        else:
            txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \
                  (s.progress_file, s.file_size, s.str_state, s._download_rate)
            txt2 = 'S: %d(%d) P: %d(%d) | DHT:%s (%d) | Trakers: %d | Pi: %d(%d)' % \
                   (s.num_seeds, s.num_complete, s.num_peers, s.num_incomplete, s.dht_state, s.dht_nodes,
                    s.trackers, s.pieces_sum, s.pieces_len)
            txt3 = video_file

        if rar and RAR and BACKGROUND or bkg_user:
            progreso.update(s.buffer, txt, txt2)
        else:
            progreso.update(s.buffer, txt, txt2, txt3)
        time.sleep(1)

        if (not bkg_user and progreso.iscanceled()) and (not (rar and RAR and BACKGROUND) and progreso.iscanceled()):
            
            if not dp_cerrado:
                progreso.close()
                dp_cerrado = True
            if 'Finalizado' in s.str_state or 'Seeding' in s.str_state:
                """
                if not rar and platformtools.dialog_yesno(msg_header, config.get_localized_string(70198)):
                    played = False
                    dp_cerrado = False
                    progreso = platformtools.dialog_progress(msg_header, '')
                    progreso.update(s.buffer, txt, txt2, txt3)
                else:
                """
                dp_cerrado = False
                progreso = platformtools.dialog_progress(msg_header, '')
                break

            else:
                if platformtools.dialog_yesno(msg_header, "¿Borramos los archivo descargados? (incompletos)",  
                                "Selecciona NO para seguir descargando en segundo plano"):
                    dp_cerrado = False
                    progreso = platformtools.dialog_progress(msg_header, '')
                    break

                else:
                    bkg_user = True
                    if not dp_cerrado: progreso.close()
                    dp_cerrado = False
                    progreso = platformtools.dialog_progress_bg(msg_header)
                    progreso.update(s.buffer, txt, txt2)
                    if not c.closed:
                        c.set_speed_limits(DOWNLOAD_LIMIT, UPLOAD_LIMIT)        # Bajamos la velocidad en background

        # Si el buffer se ha llenado y la reproduccion no ha sido iniciada, se inicia
        if ((s.pieces_sum >= BUFFER  or 'Finalizado' in s.str_state or 'Seeding' in s.str_state) and not rar and not bkg_user) or \
                    (s.pieces_sum >= s.pieces_len - 3 and s.pieces_len > 0 and ('Finalizado' in s.str_state or 'Seeding' \
                    in s.str_state) and (rar or bkg_user)) and not played:
            
            if rar and RAR and UNRAR:
                c.stop()
                activo = False
                finalizado = True
                bkg_user = False
                dp_cerrado = False
                video_file, rar_res, video_path, erase_file_path = extract_files(rar_file, \
                                save_path_videos, password, progreso, item, torr_client)  # ... extraemos el vídeo del RAR
                if rar_res and not xbmc.abortRequested:
                    time.sleep(1)
                else:
                    break
            elif (rar and not UNRAR) or (rar and not RAR):
                break
            elif bkg_user:
                finalizado = True
                break
            
            # Cerramos el progreso
            if not dp_cerrado:
                progreso.close()
                dp_cerrado = True

            # Reproducimos el vídeo extraido, si no hay nada en reproducción
            if not c.closed:
                c.set_speed_limits(DOWNLOAD_LIMIT, UPLOAD_LIMIT)        # Bajamos la velocidad en background
            bkg_auto = True
            while xbmc_player.isPlaying() and not xbmc.abortRequested:
                time.sleep(3)      
            
            # Obtenemos el playlist del torrent
            #videourl = c.get_play_list()
            if not rar_res:                                             # Es un Magnet ?
                video_file = filetools.join(save_path_videos, s.file_name)
                if erase_file_path == save_path_videos:
                    erase_file_path = video_file
                videourl = video_file
            else:
                videourl = filetools.join(video_path, video_file)

            # Iniciamos el reproductor
            playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            playlist.clear()
            playlist.add(videourl, xlistitem)
            # xbmc_player = xbmc_player
            log("##### videourl: %s" % videourl)
            xbmc_player.play(playlist)

            # Marcamos como reproducido para que no se vuelva a iniciar
            played = True
            
            mark_auto_as_watched(item)
            
            # Y esperamos a que el reproductor se cierre
            bkg_auto = True
            dp_cerrado = True
            while xbmc_player.isPlaying() and not xbmc.abortRequested:
                time.sleep(1)
                
                if xbmc.getCondVisibility('Player.Playing'):
                    if not dp_cerrado:
                        dp_cerrado = True
                        progreso.close()
                
                if xbmc.getCondVisibility('Player.Paused') and not rar_res:
                    if not c.closed: s = c.status
                    txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \
                          (s.progress_file, s.file_size, s.str_state, s._download_rate)
                    txt2 = 'S: %d(%d) P: %d(%d) | DHT:%s (%d) | Trakers: %d | Pi: %d(%d)' % \
                           (s.num_seeds, s.num_complete, s.num_peers, s.num_incomplete, s.dht_state, s.dht_nodes,
                            s.trackers, s.pieces_sum, s.pieces_len)
                    txt3 = video_file[:99]
                    if dp_cerrado:
                        dp_cerrado = False
                        progreso = xbmcgui.DialogProgressBG()
                        progreso.create(msg_header)
                    progreso.update(s.buffer, msg_header, '[CR][CR]' + txt + '[CR]' + txt2)
            
            if not dp_cerrado:
                dp_cerrado = True
                progreso.close()
            
            # Miramos si se ha completado la descarga para borrar o no los archivos
            if activo:
                s = c.status
            if s.pieces_sum == s.pieces_len:
                finalizado = True
                break

            if platformtools.dialog_yesno(msg_header, "¿Borramos los archivo descargados? (incompletos)",  
                                "Selecciona NO para seguir descargando en segundo plano"):
                progreso = platformtools.dialog_progress(msg_header, '')
                dp_cerrado = False
                break
            else:
                bkg_user = True
                played = False
                if not dp_cerrado: progreso.close()
                progreso = platformtools.dialog_progress_bg(msg_header)
                progreso.update(s.buffer, txt, txt2)
                dp_cerrado = False
                continue
            
            # Cuando este cerrado,  Volvemos a mostrar el dialogo
            if not (rar and bkg_user):
                progreso = platformtools.dialog_progress(msg_header, '')
                progreso.update(s.buffer, txt, txt2, txt3)
                dp_cerrado = False
                
            break

    if not dp_cerrado:
        if rar or bkg_user:
            progreso.update(100, config.get_localized_string(70200), " ")
        else:
            progreso.update(100, config.get_localized_string(70200), " ", " ")

    # Detenemos el cliente
    if activo and not c.closed:
        c.stop()
        activo = False

    # Cerramos el progreso
    if not dp_cerrado:
        progreso.close()
        dp_cerrado = True
    
    # Y borramos los archivos de descarga restantes
    time.sleep(1)
    if filetools.exists(erase_file_path) and not bkg_user:
        if finalizado and not platformtools.dialog_yesno(msg_header, '¿Borrarmos los archivos descargados? (completos)'):
            return
        log("##### erase_file_path: %s" % erase_file_path)
        for x in range(10):
            if filetools.isdir(erase_file_path):
                if erase_file_path != save_path_videos:
                    filetools.rmdirtree(erase_file_path)
                else:
                    break
            else:
                filetools.remove(erase_file_path)
            time.sleep(5)
            if not filetools.exists(erase_file_path):
                break
Esempio n. 29
0
def init():
    logger.info()

    """
    Todo el código añadido al add-on se borra con cada actualización.  Esta función permite restaurarlo automáticamente con cada actualización.  Esto permite al usuario tener su propio código, bajo su responsabilidad, y restaurarlo al add-on cada vez que se actualiza.
    
    El mecanismo funciona copiando el contenido de la carpeta-arbol "./userdata/addon_data/plugin.video.alfa/custom_code/..." sobre
    las carpetas de código del add-on.  No verifica el contenido, solo vuelca(reemplaza) el contenido de "custom_code".
    
    El usuario almacenará en las subcarpetas de "custom_code" su código actualizado y listo para ser copiado en cualquier momento.
    Si no se desea que copie algo, simplemente se borra de "custom_code" y ya no se copiará en la próxima actualización.
    
    Los pasos que sigue esta función, son los siguientes:
    
    1.- La función se llama desde videolibrary_service.py, desde la función inicial:
            # Copia Custom code a las carpetas de Alfa desde la zona de Userdata
            from platformcode import custom_code
            custom_code.init()
            
    2.- En el inicio de Kodi, comprueba si existe la carpeta "custom_code" en "./userdata/addon_data/plugin.video.alfa/".  
        Si no existe, la crea y sale sin más, dando al ususario la posibilidad de copiar sobre esa estructura su código, 
        y que la función la vuelque sobre el add-on en el próximo inicio de Kodi.
        
    3.- En el siguiente inicio de Kodi, comprueba si existe el custom_code.json en la carpeta root del add-on.
        Si no existe, lo crea con el número de versión del add-on vacío, para permitir que se copien los archivos en esta pasada.
        
    4.- Verifica que el número de versión del add-on es diferente de el de custom_code.json.  Si es la misma versión, 
        se sale porque ya se realizo la copia anteriormente.
        Si la versión es distinta, se realiza el volcado de todos los archivos de la carpeta-árbol "custom_code" sobre el add-on.
        Si la carpeta de destino no existe, dará un error y se cancelará la copia.  Se considera que no tienen sentido nuevas carpetas.
        
    5.- Si la copia ha terminado con éxito, se actualiza el custom_code.json con el número de versión del add-on,
        para que en inicios sucesivos de Kodi no se realicen las copias, hasta que el add-on cambie de versión.
        En el número de versión del add-on no se considera el número de fix.
        
    Tiempos:    Copiando 7 archivos de prueba, el proceso ha tardado una décima de segundo.
    """

    try:
        #Limpiamos los mensajes de ayuda obsoletos y restauramos los que tienen "version": True.  Por cada nueva versión
        if not filetools.exists(ADDON_CUSTOMCODE_JSON):
            from platformcode import help_window
            help_window.clean_watched_new_version()
        
        #Se realizan algunas funciones con cada nueva versión de Alfa
        if not filetools.exists(ADDON_CUSTOMCODE_JSON):
            config.set_setting('cf_assistant_ua', '')                   # Se limpia CF_UA. Mejora de rendimiento en httptools CF
            
        #Se verifica si están bien las rutas a la videoteca
        config.verify_directories_created()
        
        #Comprime la BD de cache de TMDB para evitar que crezca demasiado
        bd_tmdb_maintenance()
        if config.get_setting('tmdb_cache_expire', default=4) == 4:
            config.set_setting('tmdb_cache_expire', 2)

        #Borra el .zip de instalación de Alfa de la carpeta Packages, por si está corrupto, y que así se pueda descargar de nuevo
        #version = 'plugin.video.alfa-%s.zip' % ADDON_VERSION
        #filetools.remove(filetools.join('special://home', 'addons', 'packages', version), True)

        #Verifica si es necesario instalar script.alfa-update-helper
        verify_script_alfa_update_helper()
        
        #Borrar contenido de carpeta de Torrents y de Subtitles
        filetools.rmdirtree(filetools.join(config.get_videolibrary_path(), 'temp_torrents_arch'), silent=True)
        filetools.rmdirtree(filetools.join(config.get_videolibrary_path(), 'temp_torrents_Alfa'), silent=True)
        subtitle_path = config.get_kodi_setting("subtitles.custompath")
        if subtitle_path and filetools.exists(subtitle_path):
            for file in filetools.listdir(subtitle_path):
                if not file.endswith('.srt'): continue
                file_path = filetools.join(subtitle_path, file)
                ret = filetools.remove(file_path, silent=True)
                if not ret: logger.error('ERROR on REMOVING subtitle: ' + file_path)

        #Verifica si Kodi tiene algún achivo de Base de Datos de Vídeo de versiones anteriores, entonces los borra
        verify_Kodi_video_DB()
        
        #Verifica si la Base de Datos de Vídeo tiene la fuente de CINE con useFolderNames=1
        try:
            threading.Thread(target=set_Kodi_video_DB_useFolderNames).start()   # Creamos un Thread independiente por si la DB está Scanning
            time.sleep(1)                                                       # Dejamos terminar la inicialización...
        except:                                                                 # Si hay problemas de threading, nos vamos
            logger.error(traceback.format_exc())
        
        #LIBTORRENT: se descarga el binario de Libtorrent cada vez que se actualiza Alfa
        update_libtorrent()
        
        #TORREST: Modificaciones temporales
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.torrest")'):
            try:
                __settings__ = xbmcaddon.Addon(id="plugin.video.torrest")
                if __settings__.getSetting("s:check_available_space") == 'true':
                    __settings__.setSetting("s:check_available_space", "false") # No comprobar espacio disponible hasta que lo arreglen
                #if not filetools.exists(filetools.join(config.get_data_path(), "quasar.json")) \
                #    and not config.get_setting('addon_quasar_update', default=False):
                #    question_update_external_addon("torrest")
            except:
                pass

        #QUASAR: Preguntamos si se hacen modificaciones a Quasar
        if not filetools.exists(filetools.join(config.get_data_path(), "quasar.json")) \
                    and not config.get_setting('addon_quasar_update', default=False):
            question_update_external_addon("quasar")
        
        #QUASAR: Hacemos las modificaciones a Quasar, si está permitido, y si está instalado
        if config.get_setting('addon_quasar_update', default=False) or \
                    (filetools.exists(filetools.join(config.get_data_path(), \
                    "quasar.json")) and xbmc.getCondVisibility('System.HasAddon("plugin.video.quasar")')):
            if not update_external_addon("quasar"):
                platformtools.dialog_notification("Actualización Quasar", "Ha fallado. Consulte el log")
        
        #Existe carpeta "custom_code" ? Si no existe se crea y se sale
        custom_code_dir = filetools.join(ADDON_USERDATA_PATH, 'custom_code')
        custom_code_json_path = ADDON_PATH
        custom_code_json = ADDON_CUSTOMCODE_JSON
        if not filetools.exists(custom_code_dir):
            create_folder_structure(custom_code_dir)
        #Existe "custom_code.json" ? Si no existe se crea
        if not filetools.exists(custom_code_json):
            create_json(custom_code_json_path)
        #Se verifica si la versión del .json y del add-on son iguales.  Si es así se sale.  Si no se copia "custom_code" al add-on
        verify_copy_folders(custom_code_dir, custom_code_json_path)
        
        #Si se han quedado "colgadas" descargas con archivos .RAR, se intenta identificarlos y reactivar el UnRar
        reactivate_unrar(init=True, mute=True)
        
        #Inicia un rastreo de vídeos decargados desde .torrent: marca los VISTOS y elimina los controles de los BORRADOS
        from servers.torrent import mark_torrent_as_watched
        try:
            threading.Thread(target=mark_torrent_as_watched).start()            # Creamos un Thread independiente, hasta el fin de Kodi
            time.sleep(2)                                                       # Dejamos terminar la inicialización...
        except:                                                                 # Si hay problemas de threading, nos vamos
            logger.error(traceback.format_exc())

        #Ejecuta la sobrescritura de la videoteca para los canales seleccionados
        reset_videotlibrary_by_channel()

    except:
        logger.error(traceback.format_exc())
Esempio n. 30
0
def install_alfa_now(silent=True):
    logger.info()
    import json
    from core import ziptools
    from core import httptools

    try:
        versiones = config.get_versions_from_repo()
    except:
        versiones = {}
        logger.error(traceback.format_exc())
    if not versiones:
        return
    
    addons_path = filetools.translatePath("special://home/addons")
    alfa_addon = ['plugin.video.alfa', '3.4.2', '*']
    addonid = alfa_addon[0]
    new_version = versiones.get(addonid, alfa_addon[1])
    package = addonid + '-%s.zip' % new_version

    logger.info("Downloading %s" % package)
    url = '%s%s/%s' % (versiones.get('url', ''), addonid, package)
    response = httptools.downloadpage(url, ignore_response_code=True, alfa_s=True, json_to_utf8=False)
    if response.code == 200:
        zip_data = response.data
        pkg_updated = filetools.join(addons_path, 'packages', package)
        res = filetools.write(pkg_updated, zip_data, mode='wb')
        
        if res and filetools.exists(pkg_updated):
            logger.info("backing and removing installed version... %s" % package)
            backup_path = filetools.join(addons_path, "temp", addonid)
            if filetools.exists(backup_path):
                res = filetools.rmdirtree(backup_path, silent=silent)
                if not res: return
            time.sleep(3)
            if not filetools.exists(backup_path):
                filetools.copy(ADDON_PATH, backup_path)
                time.sleep(3)
                res = filetools.rmdirtree(ADDON_PATH, silent=silent)
                time.sleep(3)
                if filetools.exists(ADDON_PATH):
                    logger.error("backing and removing installed version FAILED ... %s" % package)
                    filetools.copy(backup_path, ADDON_PATH)
                    time.sleep(3)
                    return
            else:
                logger.error("backing and removing installed version FAILED ... %s" % package)
                return
        else:
            logger.error("Unable to download %s" % package)
            return

        # Si el .zip es correcto los extraemos e instalamos
        try:
            unzipper = ziptools.ziptools()
            unzipper.extract(pkg_updated, addons_path, silent=silent)
            time.sleep(3)
        except:
            try:
                xbmc.executebuiltin('Extract("%s", "%s")' % (pkg_updated, addons_path))
                time.sleep(3)
            except:
                filetools.copy(backup_path, ADDON_PATH)
                time.sleep(3)
                return

        logger.info("Installing %s" % package)
        xbmc.executebuiltin('UpdateLocalAddons')
        time.sleep(2)
        method = "Addons.SetAddonEnabled"
        xbmc.executeJSONRPC(
            '{"jsonrpc": "2.0", "id":1, "method": "%s", "params": {"addonid": "%s", "enabled": true}}' % (method, addonid))
        profile = json.loads(xbmc.executeJSONRPC('{"jsonrpc": "2.0", "id":1, "method": "Profiles.GetCurrentProfile"}'))
        logger.info("Reloading Profile...")
        user = profile["result"]["label"]
        xbmc.executebuiltin('LoadProfile(%s)' % user)
Esempio n. 31
0
def overwrite_tools(item):
    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"])

        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)

            if not serie.active:
                # si la serie no esta activa descartar
                continue

            # Eliminamos la carpeta con la serie ...
            filetools.rmdirtree(path)

            # ... y la volvemos a añadir
            videolibrary_service.update(path, p_dialog, i, t, serie, 3)
        p_dialog.close()

        # movies
        heading = config.get_localized_string(60586)
        p_dialog2 = platformtools.dialog_progress_bg(
            config.get_localized_string(60585), heading)
        p_dialog2.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(".json")
            ])

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

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

        for i, movie_json in enumerate(movies_list):
            try:
                from core import jsontools
                path = filetools.dirname(movie_json)
                movie = Item().fromjson(filetools.read(movie_json))

                # Eliminamos la carpeta con la pelicula ...
                filetools.rmdirtree(path)

                import math
                heading = config.get_localized_string(60587)

                p_dialog2.update(
                    int(math.ceil((i + 1) * t)), heading, "%s: %s" %
                    (movie.contentTitle, movie.channel.capitalize()))
                # ... y la volvemos a añadir
                videolibrarytools.save_movie(movie)
            except Exception, ex:
                logger.error("Error al crear de nuevo la película")
                template = "An exception of type %s occured. Arguments:\n%r"
                message = template % (type(ex).__name__, ex.args)
                logger.error(message)

        p_dialog2.close()
Esempio n. 32
0
def caching_torrents(url,
                     referer=None,
                     post=None,
                     torrents_path=None,
                     timeout=10,
                     lookup=False,
                     data_torrent=False):
    if torrents_path != None:
        logger.info("path = " + torrents_path)
    else:
        logger.info()
    if referer and post:
        logger.info('REFERER: ' + referer)
    from core import httptools
    torrent_file = ''
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Referer': referer
    }  #Necesario para el Post del .Torrent
    """
    Descarga en el path recibido el .torrent de la url recibida, y pasa el decode
    Devuelve el path real del .torrent, o el path vacío si la operación no ha tenido éxito
    """

    videolibrary_path = config.get_videolibrary_path(
    )  #Calculamos el path absoluto a partir de la Videoteca
    if torrents_path == None:
        if not videolibrary_path:
            torrents_path = ''
            if data_torrent:
                return (torrents_path, torrent_file)
            return torrents_path  #Si hay un error, devolvemos el "path" vacío
        torrents_path = filetools.join(
            videolibrary_path, 'temp_torrents_Alfa',
            'cliente_torrent_Alfa.torrent')  #path de descarga temporal
    if '.torrent' not in torrents_path:
        torrents_path += '.torrent'  #path para dejar el .torrent
    torrents_path_encode = filetools.encode(
        torrents_path)  #encode utf-8 del path

    if url.endswith(".rar") or url.startswith(
            "magnet:"):  #No es un archivo .torrent
        logger.error('No es un archivo Torrent: ' + url)
        torrents_path = ''
        if data_torrent:
            return (torrents_path, torrent_file)
        return torrents_path  #Si hay un error, devolvemos el "path" vacío

    try:
        #Descargamos el .torrent
        if referer and post:  #Descarga con POST
            response = httptools.downloadpage(url,
                                              headers=headers,
                                              post=post,
                                              follow_redirects=False,
                                              timeout=timeout)
        else:  #Descarga sin post
            response = httptools.downloadpage(url, timeout=timeout)
        if not response.sucess:
            logger.error('Archivo .torrent no encontrado: ' + url)
            torrents_path = ''
            if data_torrent:
                return (torrents_path, torrent_file)
            return torrents_path  #Si hay un error, devolvemos el "path" vacío
        torrent_file = response.data

        if "used CloudFlare" in torrent_file:  #Si tiene CloudFlare, usamos este proceso
            response = httptools.downloadpage(
                "http://anonymouse.org/cgi-bin/anon-www.cgi/" + url.strip(),
                timeout=timeout)
            if not response.sucess:
                logger.error('Archivo .torrent no encontrado: ' + url)
                torrents_path = ''
                if data_torrent:
                    return (torrents_path, torrent_file)
                return torrents_path  #Si hay un error, devolvemos el "path" vacío
            torrent_file = response.data

        #Si es un archivo .ZIP tratamos de extraer el contenido
        if torrent_file.startswith("PK"):
            logger.info('Es un archivo .ZIP: ' + url)

            torrents_path_zip = filetools.join(
                videolibrary_path, 'temp_torrents_zip')  #Carpeta de trabajo
            torrents_path_zip = filetools.encode(torrents_path_zip)
            torrents_path_zip_file = filetools.join(
                torrents_path_zip, 'temp_torrents_zip.zip')  #Nombre del .zip

            import time
            filetools.rmdirtree(
                torrents_path_zip)  #Borramos la carpeta temporal
            time.sleep(1)  #Hay que esperar, porque si no da error
            filetools.mkdir(torrents_path_zip)  #La creamos de nuevo

            if filetools.write(torrents_path_zip_file,
                               torrent_file):  #Salvamos el .zip
                torrent_file = ''  #Borramos el contenido en memoria
                try:  #Extraemos el .zip
                    from core import ziptools
                    unzipper = ziptools.ziptools()
                    unzipper.extract(torrents_path_zip_file, torrents_path_zip)
                except:
                    import xbmc
                    xbmc.executebuiltin(
                        'XBMC.Extract("%s", "%s")' %
                        (torrents_path_zip_file, torrents_path_zip))
                    time.sleep(1)

                import os
                for root, folders, files in os.walk(
                        torrents_path_zip
                ):  #Recorremos la carpeta para leer el .torrent
                    for file in files:
                        if file.endswith(".torrent"):
                            input_file = filetools.join(
                                root, file)  #nombre del .torrent
                            torrent_file = filetools.read(
                                input_file)  #leemos el .torrent

            filetools.rmdirtree(
                torrents_path_zip)  #Borramos la carpeta temporal

        #Si no es un archivo .torrent (RAR, HTML,..., vacío) damos error
        if not scrapertools.find_single_match(torrent_file, '^d\d+:.*?\d+:'):
            logger.error('No es un archivo Torrent: ' + url)
            torrents_path = ''
            if data_torrent:
                return (torrents_path, torrent_file)
            return torrents_path  #Si hay un error, devolvemos el "path" vacío

        #Salvamos el .torrent
        if not lookup:
            if not filetools.write(torrents_path_encode, torrent_file):
                logger.error('ERROR: Archivo .torrent no escrito: ' +
                             torrents_path_encode)
                torrents_path = ''  #Si hay un error, devolvemos el "path" vacío
                torrent_file = ''  #... y el buffer del .torrent
                if data_torrent:
                    return (torrents_path, torrent_file)
                return torrents_path
    except:
        torrents_path = ''  #Si hay un error, devolvemos el "path" vacío
        torrent_file = ''  #... y el buffer del .torrent
        logger.error('Error en el proceso de descarga del .torrent: ' + url +
                     ' / ' + torrents_path_encode)
        logger.error(traceback.format_exc())

    #logger.debug(torrents_path)
    if data_torrent:
        return (torrents_path, torrent_file)
    return torrents_path
Esempio n. 33
0
def remove_files( download, torrent_file, video_file, ses, h, ren_video_file="", item={} ):
    dialog_view = False
    torrent = False

    if os.path.isfile( torrent_file ):
        dialog_view = True
        torrent = True

    if download > 0:
        dialog_view = True
    if bkg_user and not extracted_rar:
        dialog_view = False
    
    if erase_file_path and erase_file_path != \
                            os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
        ren_video_file = erase_file_path
    if filetools.isfile(ren_video_file) and filetools.split(ren_video_file)[0] != \
                            os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
        ren_video_file = filetools.split(ren_video_file)[0]
    elif filetools.isdir(ren_video_file) and ren_video_file == \
                            os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
        ren_video_file = ''

    # Actualizado .json de control de descargas
    if not torrent_file or item.downloadProgress == 0:
        item.downloadProgress = 0
        #log("##### .torrent borrado: %s" % erase_file_path)
    else:
        item.downloadProgress = 100
    torr.update_control(item, function='mct_remove_files')
    if item.downloadStatus in [2, 4] and item.downloadProgress in [100]:
        dialog_view = False
    
    if dialog_view and ren_video_file:
        if h.status().num_pieces >= tot_piece_set:
            d = xbmcgui.Dialog()
            ok = d.yesno(msg_header, '¿Borrarmos los archivos descargados? (completos)' + '\n' +  video_file)
        else:
            ok = True

        # -- SI -------------------------------------------------
        if ok:
            # -- Borrar archivo - torrent -----------------------
            if torrent:
                try:
                    os.remove( torrent_file )
                except:
                    pass
            # -- Borrar carpeta/archivos y sesión - vídeo -------
            try:
                ses.remove_torrent( h, 1 )
                ses_lt = False
            except:
                ses_lt = False
            try:
                if os.path.isdir(ren_video_file):
                    filetools.rmdirtree(ren_video_file, silent=True)
                elif os.path.exists(ren_video_file) and os.path.isfile(ren_video_file): 
                    os.remove(ren_video_file)
                log("##### erase_file_path: %s" % ren_video_file)
            except:
                log("##### erase_file_path: %s" % ren_video_file)

            log("### End session #########")
        else:
            # -- Borrar sesión ----------------------------------
            try:
                ses.remove_torrent( h )
                ses_lt = False
            except:
                ses_lt = False
            log("### End session #########")
    else:
        # -- Borrar sesión --------------------------------------
        try:
            ses.remove_torrent( h )
            ses_lt = False
        except:
            ses_lt = False
        # -- Borrar archivo - torrent -----------------------
        if torrent:
            try:
                os.remove( torrent_file )
            except:
                pass
        log("### End session #########")
        
    filetools.remove(filetools.join( DOWNLOAD_PATH , "MCT-torrent-videos",  '.' + \
                os.path.splitext(filetools.basename(torrent_file))[0].lower() + '.parts'), silent=True)

    return                        
Esempio n. 34
0
def play(url, xlistitem={}, is_view=None, subtitle="", password="", item=None):
    allocate = True
    
    try:
        log("XXX KODI XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
        log("OS platform: %s %s" % (platform.system(),platform.release()))
        log("xbmc/kodi version: %s" % xbmc.getInfoLabel( "System.BuildVersion" ))
        xbmc_version = int(xbmc.getInfoLabel( "System.BuildVersion" )[:2])
        log("Architecture: %s %s" % (str(platform.machine()), \
                        str(sys.maxsize > 2 ** 32 and "64-bit" or "32-bit")))
        log("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX KODI & platform XXXX")
    except:
        log(traceback.format_exc())

    # -- adfly: ------------------------------------
    if url.startswith("http://adf.ly/"):
        try:
            data = httptools.downloadpage(url).data
            url = decode_adfly(data)
        except:
            ddd = xbmcgui.Dialog()
            ddd.ok( msg_header + ": Sin soporte adf.ly", "El script no tiene soporte para el acortador de urls adf.ly." + '\n' + " " + '\n' + "url: " + url )
            return

    """
    # -- Necesario para algunas webs ----------------------------
    if not url.endswith(".torrent") and not url.startswith("magnet"):
        #t_file = httptools.downloadpage(url, follow_redirects=False).headers["location"]
        t_file = scrapertools.get_header_from_response(url, header_to_get="location")
        if t_file:
            if len(t_file) > 0:
                url = t_file
                t_file = httptools.downloadpage(url, follow_redirects=False).headers["location"]
            if len(t_file) > 0:
                url = t_file
    """

    # -- Crear dos carpetas en descargas para los archivos ------
    save_path_videos = os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" )
    save_path_torrents = os.path.join( DOWNLOAD_PATH , "MCT-torrents" )
    if not os.path.exists( save_path_torrents ): os.mkdir(save_path_torrents)
    video_path = ''
    global bkg_user
    bkg_user = False
    dp_BG = False
    DOWNGROUND = False
    torrent_stop = False
    BACKGROUND = config.get_setting("mct_background_download", server="torrent", default=True)
    if item.downloadFilename and item.downloadStatus in [2, 4]:                 # Descargas AUTO
        BACKGROUND = True
        DOWNGROUND = True
        bkg_user = True
    global ses_lt
    ses_lt = False
    if item:
        if item.contentType == 'movie':
            video_path = '%s-%s' % (item.contentTitle, item.infoLabels['tmdb_id'])
        else:
            video_path = '%s-%sx%s-%s' % (item.contentSerieName, item.contentSeason, \
                            item.contentEpisodeNumber, item.infoLabels['tmdb_id'])
        item.rar_path = video_path

    # -- Usar - archivo torrent desde web, magnet o HD ---------
    if not os.path.isfile(url) and not url.startswith("magnet"):
        # -- http - crear archivo torrent -----------------------
        data = url_get(url)

        # -- El nombre del torrent será el que contiene en los --
        # -- datos.                                             -
        re_name = urllib.unquote( scrapertools.find_single_match(data,':name\d+:(.*?)\d+:') )
        
        import bencode, hashlib
        decodedDict = bencode.bdecode(data)
        if not PY3:
            re_name = hashlib.sha1(bencode.bencode(decodedDict[b"info"])).hexdigest()
        else:
            re_name = hashlib.sha1(bencode.bencode(decodedDict["info"])).hexdigest()
        
        torrent_file = os.path.join(save_path_torrents, encode(re_name.upper() + '.torrent'))

        f = open(torrent_file,'wb')
        f.write(data)
        f.close()
    elif os.path.isfile(url):
        # -- file - para usar torrens desde el HD ---------------
        torrent_file = filetools.join(save_path_torrents, filetools.basename(url).upper()).replace('.TORRENT', '.torrent')
        filetools.copy(url, torrent_file, silent=True)
    else:
        # -- magnet ---------------------------------------------
        torrent_file = url
    torrent_file = torrent_file.replace('.TORRENT', '.torrent')
    # -----------------------------------------------------------

    # -- MCT - MiniClienteTorrent -------------------------------
    try:
        log("XXX libtorrent pathname: %s" % str(LIBTORRENT_PATH))
        ses = lt.session()
    except Exception as e:
        do = xbmcgui.Dialog()
        e = e1 or e2
        do.ok('ERROR en el cliente MCT Libtorrent', 'Módulo no encontrado o imcompatible con el dispositivo.' + '\n' + 
                    'Reporte el fallo adjuntando un "log".' + '\n' + str(e))
        return
        
    log("XXX libtorrent version: %s" % lt.version)
    log("##### Torrent file: %s ##" % torrent_file)

    ses.add_dht_router("router.bittorrent.com",6881)
    ses.add_dht_router("router.utorrent.com",6881)
    ses.add_dht_router("dht.transmissionbt.com",6881)

    trackers = [
        "udp://tracker.openbittorrent.com:80/announce",
        "http://tracker.torrentbay.to:6969/announce",
        "http://tracker.pow7.com/announce",
        "udp://tracker.ccc.de:80/announce",
        "udp://open.demonii.com:1337",

        "http://9.rarbg.com:2710/announce",
        "http://bt.careland.com.cn:6969/announce",
        "http://explodie.org:6969/announce",
        "http://mgtracker.org:2710/announce",
        "http://tracker.best-torrents.net:6969/announce",
        "http://tracker.tfile.me/announce",
        "http://tracker1.wasabii.com.tw:6969/announce",
        "udp://9.rarbg.com:2710/announce",
        "udp://9.rarbg.me:2710/announce",
        "udp://coppersurfer.tk:6969/announce",

        "http://www.spanishtracker.com:2710/announce",
        "http://www.todotorrents.com:2710/announce",
    ]

    video_file = ""
    # -- magnet2torrent -----------------------------------------
    if torrent_file.startswith("magnet"):
        try:
            import zlib
            btih = hex(zlib.crc32(scrapertools.find_single_match(torrent_file, 'magnet:\?xt=urn:(?:[A-z0-9:]+|)([A-z0-9]{32})')) & 0xffffffff)
            t_hash = scrapertools.find_single_match(torrent_file, 'xt=urn:btih:([^\&]+)\&')
            files = [f for f in os.listdir(save_path_torrents) if os.path.isfile(os.path.join(save_path_torrents, f))]
            for file in files:
                if btih in os.path.basename(file):
                    torrent_file = os.path.join(save_path_torrents, file)
        except:
            pass

    if torrent_file.startswith("magnet"):
        try:
            tempdir = tempfile.mkdtemp()
        except IOError:
            tempdir = os.path.join(save_path_torrents , "temp")
            if not os.path.exists(tempdir):
                os.mkdir(tempdir)
        params = {
            'save_path': tempdir,
            'trackers': trackers,
            'storage_mode': lt.storage_mode_t.storage_mode_allocate
        }
        """
        ,
            'paused': False,
            'auto_managed': True,
            'duplicate_is_error': True
        """
        h = lt.add_magnet_uri(ses, torrent_file, params)
        dp = xbmcgui.DialogProgress()
        dp.create(msg_header)
        while not h.has_metadata():
            message, porcent, msg_file, s, download = getProgress(h, "Creando torrent desde magnet")
            dp.update(porcent, message + '\n' + msg_file + '\n' + ' ')
            if s.state == 1: download = 1
            if dp.iscanceled():
                dp.close()
                remove_files( download, torrent_file, video_file, ses, h, '', item )
                return
            h.force_dht_announce()
            xbmc.sleep(1000)

        dp.close()
        info = h.get_torrent_info()
        data = lt.bencode( lt.create_torrent(info).generate() )

        #torrent_file = os.path.join(save_path_torrents, unicode(info.name()+"-"+btih, "'utf-8'", errors="replace") + ".torrent")
        torrent_file = os.path.join(save_path_torrents, t_hash.upper()+".torrent")
        f = open(torrent_file,'wb')
        f.write(data)
        f.close()
        ses.remove_torrent(h)
        filetools.rmdirtree(tempdir)
    # -----------------------------------------------------------

    # -- Archivos torrent ---------------------------------------
    e = lt.bdecode(open(torrent_file, 'rb').read())
    info = lt.torrent_info(e)

    # -- El más gordo o uno de los más gordo se entiende que es -
    # -- el vídeo o es el vídeo que se usará como referencia    -
    # -- para el tipo de archivo                                -
    log("##### Archivos ## %s ##" % len(info.files()))
    _index_file, _video_file, _size_file = get_video_file(info)

    # -- Prioritarizar/Seleccionar archivo-----------------------
    _index, video_file, video_size, len_files = get_video_files_sizes( info )
    if len_files == 0:
        dp = xbmcgui.Dialog().ok("No se puede reproducir", "El torrent no contiene ningún archivo de vídeo")

    if _index < 0:
        log("##### parts = %s #########" % str(video_file))
        log("##### video_size = %s #########" % str(video_size))
        log("##### _index = %s #########" % str(_index))
        #if _index == -1:
        #    _index = _index_file
        #    video_size = _size_file
        video_file = _video_file
    else:
        log("##### video_size = %s #########" % str(video_size))
        log("##### _index = %s #########" % str(_index))
    _video_file_ext = os.path.splitext( _video_file )[1]
    log("##### _video_file ## %s ##" % str(_video_file))
    log("##### _video_file_ext ## %s ##" % _video_file_ext)

    if url.startswith('magnet:') or _index > 0:
        item.downloadFilename = ':%s: %s' % ('MCT', video_file)
    item.downloadQueued = 0
    time.sleep(1)
    torr.update_control(item, function='mct_start')

    dp_cerrado = True
    rar = False
    global extracted_rar
    extracted_rar = False
    global erase_file_path
    erase_file_path = ''
    
    if _video_file_ext == ".rar":
        rar = True
        filename = video_file
        if "/" in filename:
            filename = filename.split("/")[1]
        if (RAR and BACKGROUND):
            xbmcgui.Dialog().notification("Encontrado archivo .RAR de %.2f MB" % (video_size / 1048576.0),
                                        "Puedes realizar otras tareas en Kodi mientrastanto. " + \
                                        "Te informaremos...", time=10000)
            dialog = True
        else:
            dialog = xbmcgui.Dialog().yesno("Encontrado archivo .RAR...", "Nombre: %s" % filename + '\n' + 
                                        "Tamaño: %.2f MB" % (video_size / 1048576.0) + '\n' + 
                                        "¿Descargar en segundo plano? Cancelar en menú Descargas")
        if dialog:
            dp_cerrado = False
            dp = xbmcgui.DialogProgressBG()
            dp.create(msg_header)
            dp_BG = True

    if (_video_file_ext == ".avi" or _video_file_ext == ".mp4" or _video_file_ext == ".mkv") and allocate:
        log("##### storage_mode_t.storage_mode_allocate ("+_video_file_ext+") #####")
        h = ses.add_torrent( { 'ti':info, 'save_path': save_path_videos, 'trackers':trackers, 'storage_mode':lt.storage_mode_t.storage_mode_allocate } )
    else:
        log("##### storage_mode_t.storage_mode_sparse ("+_video_file_ext+") #####")
        h = ses.add_torrent( { 'ti':info, 'save_path': save_path_videos, 'trackers':trackers, 'storage_mode':lt.storage_mode_t.storage_mode_sparse } )
        allocate = True

    ses_lt = True
    # -----------------------------------------------------------

    # -- Descarga secuencial - trozo 1, trozo 2, ... ------------
    h.set_sequential_download(True)

    h.force_reannounce()
    h.force_dht_announce()

    # -- Inicio de variables para 'pause' automático cuando el  -
    # -- el vídeo se acerca a una pieza sin completar           -
    is_greater_num_pieces = False
    is_greater_num_pieces_plus = False
    is_greater_num_pieces_pause = False

    porcent4first_pieces = int( video_size * 0.000000005 )
    porcent4first_pieces = BUFFER
    if porcent4first_pieces < BUFFER: porcent4first_pieces = BUFFER
    if porcent4first_pieces > 100: porcent4first_pieces = 100
    porcent4last_pieces = int(old_div(porcent4first_pieces,2))

    num_pieces_to_resume = int( video_size * 0.0000000025 )
    if num_pieces_to_resume < 10: num_pieces_to_resume = 10
    if num_pieces_to_resume > 25: num_pieces_to_resume = 25

    log("##### porcent4first_pieces ## %s ##" % porcent4first_pieces)
    log("##### porcent4last_pieces ## %s ##" % porcent4last_pieces)
    log("##### num_pieces_to_resume ## %s ##" % num_pieces_to_resume)

    # -- Prioritarizar o seleccionar las piezas del archivo que -
    # -- se desea reproducir con 'file_priorities'              -
    piece_set = set_priority_pieces(h, _index, video_file, video_size,
                                    porcent4first_pieces, porcent4last_pieces, allocate)
    global tot_piece_set
    tot_piece_set = len(piece_set)
    log("##### total piece_set ## %s ##" % len(piece_set))

    if dp_cerrado:
        if bkg_user:
            dp = xbmcgui.DialogProgressBG()
            dp.create(msg_header)
            dp_BG = True
        else:
            # -- Crear diálogo de progreso para el primer bucle ---------
            dp = xbmcgui.DialogProgress()
            dp.create(msg_header)

    _pieces_info = {}

    ren_video_file = os.path.join( save_path_videos, video_file )
    # -- Doble bucle anidado ------------------------------------
    # -- Descarga - Primer bucle
    x = 1
    while not h.is_seed():
        x += 1
        s = h.status()

        xbmc.sleep(1000)
        if not dp_cerrado and not BACKGROUND:
            dp.close()
            dp_cerrado = True
            dp = xbmcgui.DialogProgress()
            dp.create(msg_header)

        # -- Recuperar los datos del progreso -------------------
        message, porcent, msg_file, s, download = getProgress(h, video_file, _pf=_pieces_info)
        
        # Si se ha borrado el .torrent es porque se quiere cancelar la sesión
        #log("##### x: %s" % str(x))
        #log("##### exists: %s" % str(filetools.exists(torrent_file)))
        if ((download > 1 and (str(x).endswith('0') or str(x).endswith('5'))) \
                        or (download == 0 and x > 30)) and not filetools.exists(torrent_file):
            
            log('LISTADO de .torrent %s' % (filetools.listdir(filetools.dirname(torrent_file))))
            if filetools.exists(torrent_file.replace('.torrent', '.pause')) or filetools.exists(torrent_file.replace('.TORRENT', '.pause')):
                torrent_paused = True
                torrent_stop = True
                action = 'pause'
                item.downloadProgress = -1
                res = filetools.remove(torrent_file.replace('.torrent', '.pause').replace('.TORRENT', '.pause'), silent=True)
                #res = filetools.rename(torrent_file.replace('.torrent', '.pause').replace('.TORRENT', '.pause'), \
                #                        filetools.basename(torrent_file), strict=True, silent=True)
                log("##### Progreso: %s, .torrent pausado: %s" % (str(porcent), video_file))
            elif filetools.exists(torrent_file.replace('.torrent', '.reset')) or filetools.exists(torrent_file.replace('.TORRENT', '.reset')):
                torrent_reseted = True
                torrent_stop = True
                action = 'reset'
                item.downloadProgress = 0
                res = filetools.remove(torrent_file.replace('.torrent', '.reset').replace('.TORRENT', '.reset'), silent=True)
                #res = filetools.rename(torrent_file.replace('.torrent', '.reset').replace('.TORRENT', '.reset'), \
                #                        filetools.basename(torrent_file), strict=True, silent=True)
                log("##### Progreso: %s, .torrent reseteado: %s" % (str(porcent), video_file))
            else:
                torrent_deleted = True
                torrent_stop = True
                action = 'delete'
                item.downloadProgress = 0
                res = True
                log("##### Progreso: %s, .torrent borrado: %s" % (str(porcent), video_file))

            if not res:
                log('ERROR borrando por -%s- el .torrent %s' % (action, filetools.listdir(filetools.dirname(torrent_file))))
            
            if item.downloadProgress == 0 or torrent_stop:
                remove_files( 1, torrent_file, video_file, ses, h, ren_video_file, item )
                bkg_user = False
            dp.close()
            return

        # -- Si hace 'checking' existe descarga -----------------
        # -- 'download' Se usará para saber si hay datos        -
        # -- descargados para el diálogo de 'remove_files'      -
        if s.state == 1: download = 1

        if (s.state == 5 or s.state == 4) and rar:
            # -- Borrar sesión para que libere los archivos y se pueda renombrar la carpeta -------
            ses.pause()
            #video_file, rar, play_file = extract_files(video_file, save_path_videos, password, dp, item=item)
            video_file, rar, play_file, erase_path = torr.extract_files(video_file, \
                            save_path_videos, password, dp, item=item, torr_client='MCT')   # ... extraemos el vídeo del RAR
                            
            item.downloadFilename = play_file.replace(save_path_videos, '')
            item.downloadFilename = filetools.join(item.downloadFilename, video_file)
            item.downloadFilename = ':%s: %s' % ('MCT', item.downloadFilename)
            
            dp.close()
            
            erase_file_path = erase_path
            ren_video_file = erase_file_path
            extracted_rar = rar
            if not play_file:
                remove_files( download, torrent_file, erase_file_path, ses, h, ren_video_file, item )
                return
            is_view = "Ok"
            save_path_videos = play_file
            xbmc.sleep(3000)

        # -- Player - play --------------------------------------
        # -- Comprobar si se han completado las piezas para el  -
        # -- inicio del vídeo                                   -
        first_pieces = True
        #if not extracted_rar:
        _c = 0
        for i in range( piece_set[0], piece_set[porcent4first_pieces] ):
            first_pieces &= h.have_piece(i)
            if h.have_piece(i): _c+= 1
        _pieces_info = {'current': 0, 'continuous': "%s/%s" % (_c, porcent4first_pieces), \
                        'continuous2': "", 'have': h.status().num_pieces, 'len': len(piece_set)}

        last_pieces = True
        if not allocate:
            _c = len(piece_set)-1; _cc = 0
            for i in range(len(piece_set)-porcent4last_pieces, len(piece_set)):
                last_pieces &= h.have_piece(i)
                if h.have_piece(i): _c-= 1; _cc+=1
            _pieces_info['continuous2'] = "[%s/%s] " % (_cc, porcent4last_pieces)

        if is_view != "Ok" and h.status().num_pieces >= BUFFER and not rar and not bkg_user \
                            or ((s.state == 5 or s.state == 4) and bkg_user):
            _pieces_info['continuous2'] = ""
            log("##### porcent [%.2f%%]" % (s.progress * 100))
            dp.close()
            dp_cerrado = True
            if not bkg_user:
                is_view = "Ok"
            else:
                remove_files( download, torrent_file, video_file, ses, h, ren_video_file, item )
                return

        if is_view == "Ok":
            # -- Esperando a que termine otra reproducción --------------------------
            while xbmc.Player().isPlaying():
                xbmc.sleep(3000)
                
            # -- Player - Ver el vídeo --------------------------
            playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO )
            playlist.clear()

            ren_video_file = os.path.join( save_path_videos, video_file )
            try:
                playlist.add( ren_video_file, xlistitem )
            except:
                playlist.add( ren_video_file )

            if xbmc_version < 17:
                player = play_video( xbmc.PLAYER_CORE_AUTO )
            else:
                player = play_video()
            
            if subtitle:
                time.sleep(0.5)
                player.setSubtitles(item.subtitle)                              # Activamos los subtítulos
            
            player.play(playlist)

            # -- Contador de cancelaciones para la ventana de   -
            # -- 'pause' automático                             -
            is_greater_num_pieces_canceled = 0
            continuous_pieces = 0
            porcent_time = 0.00
            current_piece = 0
            set_next_continuous_pieces = porcent4first_pieces

            # -- Impedir que kodi haga 'resume' a un archivo ----
            # -- que se reprodujo con anterioridad y que se     -
            # -- eliminó para impedir que intente la reprucción -
            # -- en una pieza que aún no se ha completado y se  -
            # -- active 'pause' automático                      -
            not_resume = True

            # -- Bandera subTítulos
            _sub = False

            # -- Segundo bucle - Player - Control de eventos ----
            bkg_auto = True
            log("##### PLAY %s" % (h.status().num_pieces))
            if item: torr.mark_auto_as_watched(item)
            if ses_lt:
                h.set_download_limit(DOWNLOAD_LIMIT)
                h.set_upload_limit(UPLOAD_LIMIT)
            while player.isPlaying():

                # -- Impedir que kodi haga 'resume' al inicio ---
                # -- de la descarga de un archivo conocido      -
                if not_resume:
                    player.seekTime(0)
                    not_resume = False

                # -- Control 'pause' automático                 -
                continuous_pieces = count_completed_continuous_pieces(h, piece_set)

                if xbmc.Player().isPlaying() and not rar:

                    # -- Porcentage del progreso del vídeo ------
                    # -- En kodi 18.x se debe controlar         -
                    # -- ZeroDivisionError: float division by   -
                    # -- zero                                   -
                    player_getTime = player.getTime()
                    player_getTotalTime = player.getTotalTime()
                    try: porcent_time = old_div(player_getTime, player_getTotalTime) * 100
                    except: porcent_time = 0

                    # -- Pieza que se está reproduciendo --------
                    # -- En kodi 18.x se debe controlar         -
                    # -- ZeroDivisionError: float division by   -
                    # -- zero                                   -
                    try: current_piece = int( old_div(porcent_time, 100) * len(piece_set) )
                    except:  current_piece = 0

                    # -- Banderas de control --------------------
                    is_greater_num_pieces = (current_piece > continuous_pieces - num_pieces_to_resume)
                    #is_greater_num_pieces_plus = (current_piece + porcent4first_pieces > continuous_pieces)
                    is_greater_num_pieces_plus = (current_piece + BUFFER > continuous_pieces)
                    #is_greater_num_pieces_finished = (current_piece + porcent4first_pieces >= len(piece_set))
                    is_greater_num_pieces_finished = (current_piece + BUFFER >= len(piece_set))

                    # -- Activa 'pause' automático --------------
                    if is_greater_num_pieces and not player.paused and not is_greater_num_pieces_finished:
                        is_greater_num_pieces_pause = True
                        player.pause()

                    if continuous_pieces >= set_next_continuous_pieces:
                        set_next_continuous_pieces = continuous_pieces + num_pieces_to_resume
                    next_continuous_pieces = str(continuous_pieces - current_piece) + "/" + str(set_next_continuous_pieces - current_piece)
                    _pieces_info = {'current': current_piece, 'continuous': next_continuous_pieces , 'continuous2': _pieces_info['continuous2'], 'have': h.status().num_pieces, 'len': len(piece_set)}

                # -- Cerrar el diálogo de progreso --------------
                if player.resumed:
                    dp.close()

                # -- Mostrar el diálogo de progreso -------------
                if player.paused and dp_cerrado and not rar:
                    # -- Crear diálogo si no existe -------------
                    log("##### PAUSED %s" % (h.status().num_pieces))
                    if not player.statusDialogoProgress:
                        dp = xbmcgui.DialogProgressBG()
                        dp.create(msg_header)
                        dp_BG = True
                        player.setDialogoProgress()

                    # -- Diálogos de estado en el visionado -----
                    if not h.is_seed():
                        # -- Recuperar los datos del progreso ---
                        message, porcent, msg_file, s, download = getProgress(h, video_file, _pf=_pieces_info)
                        if dp_BG:
                            dp.update(porcent, message, msg_file)
                        else:
                            dp.update(porcent, message + '\n' + msg_file + '\n' + ' ')
                    else:
                        if dp_BG:
                            dp.update(100, "Descarga completa: ", video_file)
                        else:
                            dp.update(100, "Descarga completa: " + '\n' + video_file + '\n' + ' ')

                    # -- Se canceló el progreso en el visionado -
                    # -- Continuar                              -
                    if not bkg_auto and dp.iscanceled():
                        dp.close()
                        player.pause()

                    # -- Se canceló el progreso en el visionado -
                    # -- en la ventana de 'pause' automático.   -
                    # -- Parar si el contador llega a 3         -
                    if not bkg_auto and dp.iscanceled() and is_greater_num_pieces_pause:
                        is_greater_num_pieces_canceled+= 1
                        if is_greater_num_pieces_canceled == 3:
                            player.stop()

                    # -- Desactiva 'pause' automático y ---------
                    # -- reinicia el contador de cancelaciones  -
                    if not is_greater_num_pieces_plus and is_greater_num_pieces_pause:
                        dp.close()
                        player.pause()
                        is_greater_num_pieces_pause = False
                        is_greater_num_pieces_canceled = 0
                    
                    # -- El usuario cancelo el visionado --------
                    # -- Terminar                               -
                    if player.ended:
                        # -- Diálogo eliminar archivos ----------
                        remove_files( download, torrent_file, video_file, ses, h, ren_video_file, item )
                        return
                
                xbmc.sleep(1000)
                
        # -- Kodi - Se cerró el visionado -----------------------
        # -- Continuar | Terminar                               -
        if is_view == "Ok" and not xbmc.Player().isPlaying():
            dp.close()
            
            if h.status().num_pieces < tot_piece_set:
                # -- Diálogo continuar o terminar ---------------
                # Preguntamos si el usuario quiere pasar a backgroung
                ok = xbmcgui.Dialog().yesno(msg_header, "¿Borramos los archivo descargados? (incompletos)" + '\n' + 
                                    "Selecciona NO para seguir descargando en segundo plano")
            else: ok = True
            # -- NO ---------------------------------------------
            if not ok:
                is_view=None
                bkg_user = True
                dp_cerrado = False
                dp = xbmcgui.DialogProgressBG()
                dp.create(msg_header)
                dp_BG = True
            
            else:
                # -- Terminar: ----------------------------------
                # -- Comprobar si el vídeo pertenece a una ------
                # -- lista de archivos                          -
                remove_files( download, torrent_file, video_file, ses, h, ren_video_file, item )
                if item.path.endswith('.json'):
                    log("##### BORRANDO Archivo de CONTROL %s" % item.path)
                    filetools.remove(filetools.join(config.get_setting("downloadlistpath"), item.path))
                dp.close()
                return
                """
                #_index, video_file, video_size, len_files = get_video_files_sizes( info )
                if _index < 0 or len_files == 1:
                    # -- Diálogo eliminar archivos --------------
                    #video_file = _video_file
                    remove_files( download, torrent_file, video_file, ses, h, ren_video_file )
                    dp.close()
                    return
                else:
                    # -- Lista de archivos. Diálogo de opciones -
                    piece_set = set_priority_pieces(h, _index, video_file, video_size,
                                                    porcent4first_pieces, porcent4last_pieces, allocate)
                    is_view=None
                    dp = xbmcgui.DialogProgress()
                    dp.create(msg_header)
                """

        # -- Mostar progeso antes del visionado -----------------
        if is_view != "Ok" :
            if dp_BG:
                dp.update(porcent, message, msg_file)
            else:
                dp.update(porcent, message + '\n' + msg_file + '\n' + ' ')

        # -- Se canceló el progreso antes del visionado ---------
        # -- Dar otra oportunidad en background o Terminar                                           -
        if not bkg_user and dp_cerrado and dp.iscanceled():
            dp.close()
            # Preguntamos si el usuario quiere pasar a backgroung
            dialog = xbmcgui.Dialog().yesno(msg_header, "¿Borramos los archivo descargados? (incompletos)", 
                                        "Seleccione NO para seguir descargando en segundo plano")
            if not dialog:
                bkg_user = True
                dp_cerrado = False
                dp = xbmcgui.DialogProgressBG()
                dp.create(msg_header)
                dp_BG = True
                if ses_lt: h.set_download_limit(DOWNLOAD_LIMIT)
                
            else:
                remove_files( download, torrent_file, video_file, ses, h, ren_video_file, item )
                if item.path.endswith('.json'):
                    log("##### BORRANDO Archivo de CONTROL %s" % item.path)
                    filetools.remove(filetools.join(config.get_setting("downloadlistpath"), item.path))
                return
                # -- Comprobar si el vídeo pertenece a una lista de -
                # -- archivos                                       -
                #_index, video_file, video_size, len_files = get_video_files_sizes( info )
                if _index < 0 or len_files == 1:
                    # -- Diálogo eliminar archivos ------------------
                    #video_file = _video_file
                    remove_files( download, torrent_file, video_file, ses, h, ren_video_file, item )
                    return
                else:
                    # -- Lista de archivos. Diálogo de opciones -----
                    piece_set = set_priority_pieces(h, _index, video_file, video_size,
                                                    porcent4first_pieces, porcent4last_pieces, allocate)
                    is_view=None
                    dp = xbmcgui.DialogProgress()
                    dp.create(msg_header)

    # -- Kodi - Error? - No debería llegar aquí -----------------
    if is_view == "Ok" and not xbmc.Player().isPlaying():
        dp.close()
        # -- Diálogo eliminar archivos --------------------------
        remove_files( download, torrent_file, video_file, ses, h, ren_video_file, item )

    return
Esempio n. 35
0
def remove_files( download, torrent_file, video_file, ses, h, ren_video_file="", erase_file_path='' ):
    dialog_view = False
    torrent = False

    if os.path.isfile( torrent_file ):
        dialog_view = True
        torrent = True

    if download > 0:
        dialog_view = True
    if bkg_user and not extracted_rar:
        dialog_view = False

    if erase_file_path and erase_file_path != os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
        ren_video_file = erase_file_path
    if filetools.isfile(ren_video_file) and filetools.split(ren_video_file)[0] !=  os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
        ren_video_file = filetools.split(ren_video_file)[0]
    elif filetools.isdir(ren_video_file) and ren_video_file ==  os.path.join( DOWNLOAD_PATH , "MCT-torrent-videos" ):
        ren_video_file = ''

    if dialog_view and ren_video_file:
        if h.status().num_pieces >= tot_piece_set:
            d = xbmcgui.Dialog()
            ok = d.yesno(msg_header, config.get_localized_string(30031), video_file)
        else:
            ok = True

        # -- SI -------------------------------------------------
        if ok:
            # -- Borrar archivo - torrent -----------------------
            if torrent:
                try:
                    os.remove( torrent_file )
                except:
                    pass
            # -- Borrar carpeta/archivos y sesión - vídeo -------
            try:
                ses.remove_torrent( h, 1 )
                ses_lt = False
            except:
                ses_lt = False
            try:
                if os.path.isdir(ren_video_file):
                    filetools.rmdirtree(ren_video_file, silent=True)
                elif os.path.exists(ren_video_file) and os.path.isfile(ren_video_file):
                    os.remove(ren_video_file)
                log("##### erase_file_path: %s" % ren_video_file)
            except:
                log("##### erase_file_path: %s" % ren_video_file)

            log("### End session #########")
        else:
            # -- Borrar sesión ----------------------------------
            try:
                ses.remove_torrent( h )
                ses_lt = False
            except:
                ses_lt = False
            log("### End session #########")
    else:
        # -- Borrar sesión --------------------------------------
        try:
            ses.remove_torrent( h )
            ses_lt = False
        except:
            ses_lt = False
        # -- Borrar archivo - torrent -----------------------
        if torrent:
            try:
                os.remove( torrent_file )
            except:
                pass
        log("### End session #########")

    return
Esempio n. 36
0
def verify_directories_created():
    import logger

    from core import filetools

    # Force download path if empty
    download_path = get_setting("downloadpath")
    if download_path == "":
        if is_xbmc():
            download_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/downloads"
        else:
            download_path = filetools.join(get_data_path(), "downloads")

        set_setting("downloadpath", download_path)

    # Force download list path if empty
    download_list_path = get_setting("downloadlistpath")
    if download_list_path == "":
        if is_xbmc():
            download_list_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/downloads/list"
        else:
            download_list_path = filetools.join(get_data_path(), "downloads", "list")

        set_setting("downloadlistpath", download_list_path)

    # Force bookmark path if empty
    bookmark_path = get_setting("bookmarkpath")
    if bookmark_path == "":
        if is_xbmc():
            bookmark_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/downloads/list"
        else:
            bookmark_path = filetools.join(get_data_path(), "bookmarks")

        set_setting("bookmarkpath", bookmark_path)

    # Create data_path if not exists
    if not os.path.exists(get_data_path()):
        logger.debug("Creating data_path " + get_data_path())

        filetools.mkdir(get_data_path())

    if is_xbmc():
        # xbmc.log("Es una plataforma XBMC")
        if download_path.startswith("special://"):
            # Translate from special and create download_path if not exists
            download_path = xbmc.translatePath(download_path)
            texto = "(from special)"
        else:
            texto = ""

        # TODO si tiene smb se debería poder dejar que cree? filetools permite crear carpetas para SMB
        if not download_path.lower().startswith("smb") and not filetools.exists(download_path):
            logger.debug("Creating download_path" + texto + ": " + download_path)
            filetools.mkdir(download_path)

        if download_list_path.startswith("special://"):
            # Create download_list_path if not exists
            download_list_path = xbmc.translatePath(download_list_path)
            texto = "(from special)"
        else:
            texto = ""

        # TODO si tiene smb se debería poder dejar que cree? filetools permite crear carpetas para SMB
        if not download_list_path.lower().startswith("smb") and not filetools.exists(download_list_path):
            logger.debug("Creating download_list_path" + texto + ": " + download_list_path)
            filetools.mkdir(download_list_path)

        if bookmark_path.startswith("special://"):
            # Create bookmark_path if not exists
            bookmark_path = xbmc.translatePath(bookmark_path)
            texto = "(from special)"
        else:
            texto = ""

        # TODO si tiene smb se debería poder dejar que cree? filetools permite crear carpetas para SMB
        if not bookmark_path.lower().startswith("smb") and not filetools.exists(bookmark_path):
            logger.debug("Creating bookmark_path" + texto + ": " + bookmark_path)
            filetools.mkdir(bookmark_path)

    # Create library_path if not exists
    # TODO si tiene smb se debería poder dejar que cree? filetools permite crear carpetas para SMB
    if not get_library_path().lower().startswith("smb") and not os.path.exists(get_library_path()):
        librarypath = get_library_path()
        logger.debug("Creating library_path " + librarypath)
        if filetools.mkdir(librarypath):
            set_setting("library_version", "v4")

    # Create settings_path is not exists
    settings_path = filetools.join(get_data_path(), "settings_channels")
    if not filetools.exists(settings_path):
        logger.debug("Creating settings_path " + settings_path)
        filetools.mkdir(settings_path)

    # Checks that a directory "xbmc" is not present on platformcode
    old_xbmc_directory = os.path.join(get_runtime_path(), "platformcode", "xbmc")
    if os.path.exists(old_xbmc_directory):
        logger.debug("Removing old platformcode.xbmc directory")
        filetools.rmdirtree(old_xbmc_directory)
Esempio n. 37
0
def delete_cache(url):
    folder = filetools.join(config.get_data_path(), 'thumbs_copiapop')
    filetools.rmdirtree(folder)
    if config.is_xbmc():
        import xbmc
        xbmc.executebuiltin("Container.Refresh")