Beispiel #1
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()
Beispiel #2
0
def update_external_addon(addon_name):
    logger.info(addon_name)
    
    try:
        #Verificamos que el addon está instalado
        if xbmc.getCondVisibility('System.HasAddon("plugin.video.%s")' % addon_name):
            #Path de actualizaciones de Alfa
            alfa_addon_updates_mig = filetools.join(config.get_runtime_path(), "lib")
            alfa_addon_updates = filetools.join(alfa_addon_updates_mig, addon_name)
            
            #Path de destino en addon externo
            __settings__ = xbmcaddon.Addon(id="plugin.video." + addon_name)
            if addon_name.lower() in ['quasar', 'elementum']:
                addon_path_root = xbmc.translatePath(__settings__.getAddonInfo('Path'))
                addon_path_mig = filetools.join(addon_path_root, filetools.join("resources", "site-packages"))
                addon_path = filetools.join(addon_path_mig, addon_name)
            else:
                addon_path_root = ''
                addon_path_mig = ''
                addon_path = ''
            
            #Hay modificaciones en Alfa? Las copiamos al addon, incuidas las carpetas de migración a PY3
            if filetools.exists(alfa_addon_updates) and filetools.exists(addon_path):
                for root, folders, files in filetools.walk(alfa_addon_updates_mig):
                    if ('future' in root or 'past' in root) and not 'concurrent' in root:
                        for file in files:
                            alfa_addon_updates_mig_folder = root.replace(alfa_addon_updates_mig, addon_path_mig)
                            if not filetools.exists(alfa_addon_updates_mig_folder):
                                filetools.mkdir(alfa_addon_updates_mig_folder)
                            if file.endswith('.pyo') or file.endswith('.pyd'):
                                continue
                            input_file = filetools.join(root, file)
                            output_file = input_file.replace(alfa_addon_updates_mig, addon_path_mig)
                            if not filetools.copy(input_file, output_file, silent=True):
                                logger.error('Error en la copia de MIGRACIÓN: Input: %s o Output: %s' % (input_file, output_file))
                                return False
                
                for root, folders, files in filetools.walk(alfa_addon_updates):
                    for file in files:
                        input_file = filetools.join(root, file)
                        output_file = input_file.replace(alfa_addon_updates, addon_path_mig)
                        if file in ['addon.xml']:
                            filetools.copy(input_file, filetools.join(addon_path_root, file), silent=True)
                            continue
                        if not filetools.copy(input_file, output_file, silent=True):
                            logger.error('Error en la copia: Input: %s o Output: %s' % (input_file, output_file))
                            return False
                return True
            else:
                logger.error('Alguna carpeta no existe: Alfa: %s o %s: %s' % (alfa_addon_updates, addon_name, addon_path_mig))
        # Se ha desinstalado Quasar, reseteamos la opción
        else:
            config.set_setting('addon_quasar_update', False)
            if filetools.exists(filetools.join(config.get_data_path(), "%s.json" % addon_name)):
                filetools.remove(filetools.join(config.get_data_path(), "%s.json" % addon_name))
            return True
    except:
        logger.error(traceback.format_exc())
    
    return False
Beispiel #3
0
def restart_error(item):
    logger.info()
    for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)):
        if fichero.endswith(".json"):
            download_item = Item().fromjson(
                filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero)))

            if not item.contentType == "tvshow" or (
                    item.contentSerieName == download_item.contentSerieName
                    and item.contentChannel == download_item.contentChannel):
                if download_item.downloadStatus == STATUS_CODES.error:
                    if filetools.isfile(
                            os.path.join(config.get_setting("downloadpath"),
                                         download_item.downloadFilename)):
                        filetools.remove(
                            os.path.join(config.get_setting("downloadpath"),
                                         download_item.downloadFilename))

                    update_json(
                        item.path, {
                            "downloadStatus": STATUS_CODES.stoped,
                            "downloadComplete": 0,
                            "downloadProgress": 0
                        })

    platformtools.itemlist_refresh()
Beispiel #4
0
def update_external_addon(addon_name):
    logger.info(addon_name)
    
    #Verificamos que el addon está instalado
    if xbmc.getCondVisibility('System.HasAddon("plugin.video.%s")' % addon_name):
        #Path de actuali<aciones de Alfa
        alfa_addon_updates = filetools.join(config.get_runtime_path(), filetools.join("lib", addon_name))
        
        #Path de destino en addon externo
        __settings__ = xbmcaddon.Addon(id="plugin.video." + addon_name)
        if addon_name.lower() in ['quasar', 'elementum']:
            addon_path = filetools.join(xbmc.translatePath(__settings__.getAddonInfo('Path')), filetools.join("resources", filetools.join("site-packages", addon_name)))
        else:
            addon_path = ''
        
        #Hay modificaciones en Alfa? Las copiamos al addon
        if filetools.exists(alfa_addon_updates) and filetools.exists(addon_path):
            for root, folders, files in os.walk(alfa_addon_updates):
                for file in files:
                    input_file = filetools.join(root, file)
                    output_file = input_file.replace(alfa_addon_updates, addon_path)
                    if filetools.copy(input_file, output_file, silent=True) == False:
                        logger.error('Error en la copia: Input: %s o Output: %s' % (input_file, output_file))
                        return False
            return True
        else:
            logger.error('Alguna carpeta no existe: Alfa: %s o %s: %s' % (alfa_addon_updates, addon_name, addon_path))
    # Se ha desinstalado Quasar, reseteamos la opción
    else:
        config.set_setting('addon_quasar_update', False)
        if filetools.exists(filetools.join(config.get_data_path(), "%s.json" % addon_name)):
            filetools.remove(filetools.join(config.get_data_path(), "%s.json" % addon_name))
        return True
    
    return False
Beispiel #5
0
def setting():
    # support.dbg()
    xbmc.executebuiltin('UpdateLocalAddons')
    xbmc.sleep(1000)
    if filetools.isfile(elementum_setting_file):
        xbmc.executeJSONRPC(
            '{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "plugin.video.elementum", "enabled": true }}'
        )
        Continue = True
        while Continue:
            try:
                __settings__ = xbmcaddon.Addon(id="plugin.video.elementum")
                __settings__.setSetting('skip_burst_search', 'true')
                __settings__.setSetting('greeting_enabled', 'false')
                __settings__.setSetting('do_not_disturb', 'true')
                Continue = False
            except:
                support.info('RIPROVO')
                xbmc.sleep(100)
    else:
        if not filetools.exists(elementum_path):
            filetools.mkdir(elementum_path)
        filetools.copy(kod_setting_file, elementum_setting_file)
        xbmc.sleep(1000)
        xbmc.executeJSONRPC(
            '{"jsonrpc": "2.0", "id":1, "method": "Addons.SetAddonEnabled", "params": { "addonid": "plugin.video.elementum", "enabled": true }}'
        )

    updater.refreshLang()

    if filetools.exists(filename):
        filetools.remove(filename)
Beispiel #6
0
 def download(self):
     __settings__ = xbmcaddon.Addon(id='plugin.video.alfa')                  ### Alfa
     filetools.mkdir(self.dest_path)
     for libname in get_libname(self.platform):
         dest = os.path.join(self.dest_path, libname)
         log("try to fetch %s" % libname)
         url = "%s/%s/%s/%s.zip" % (__libbaseurl__, self.platform['system'], self.platform['version'], libname)
         if libname!='liblibtorrent.so':
             try:
                 self.http = HTTP()
                 self.http.fetch(url, download=dest + ".zip", progress=False)    ### Alfa
                 log("%s -> %s" % (url, dest))
                 xbmc.executebuiltin('XBMC.Extract("%s.zip","%s")' % (dest, self.dest_path), True)
                 filetools.remove(dest + ".zip")
             except:
                 text = 'Failed download %s!' % libname
                 xbmc.executebuiltin("XBMC.Notification(%s,%s,%s,%s)" % (__plugin__,text,750,__icon__))
         else:
             filetools.copy(os.path.join(self.dest_path, 'libtorrent.so'), dest, silent=True)      ### Alfa
         dest_alfa = os.path.join(xbmc.translatePath(__settings__.getAddonInfo('Path')), \
                         'lib', libname)                                     ### Alfa
         filetools.copy(dest, dest_alfa, silent=True)                        ### Alfa
         dest_alfa = os.path.join(xbmc.translatePath(__settings__.getAddonInfo('Profile')), \
                         'custom_code', 'lib', libname)                      ### Alfa
         filetools.copy(dest, dest_alfa, silent=True)                        ### Alfa
     return True
def play(item):
    logger.info()
    itemlist = []

    try:
        from core import filetools
        ficherosubtitulo = filetools.join( config.get_data_path(), 'subtitulo_areadocu.srt' )
        if filetools.exists(ficherosubtitulo):
            try:
                filetools.remove(ficherosubtitulo)
            except IOError:
                logger.info("Error al eliminar el archivo "+ficherosubtitulo)
                raise
        
        data = httptools.downloadpage(item.subtitle, headers={'Referer': item.extra}).data
        filetools.write(ficherosubtitulo, data)
        subtitle = ficherosubtitulo
    except:
        subtitle = ""
        logger.info("Error al descargar el subtítulo")

    extension = item.url.rsplit("|", 1)[0][-4:]
    itemlist.append(['%s %s [directo]' % (extension, item.calidad), item.url, 0, subtitle])
    #itemlist.append(item.clone(subtitle=subtitle))

    return itemlist
def move_to_libray(item):
    try:
      from platformcode import library
    except:
      return
      
    # Copiamos el archivo a la biblioteca
    origen = filetools.join(config.get_setting("downloadpath"), item.downloadFilename)
    destino = filetools.join(config.get_library_path(), *filetools.split(item.downloadFilename))
    
    if not filetools.isdir(filetools.dirname(destino)):
      filetools.mkdir(filetools.dirname(destino))
    
    if filetools.isfile(destino) and filetools.isfile(origen) :
      filetools.remove(destino)

    if filetools.isfile(origen):
      filetools.move(origen, destino)
      if len(filetools.listdir(filetools.dirname(origen))) == 0: 
        filetools.rmdir(filetools.dirname(origen))
      
    else:
      logger.error("No se ha encontrado el archivo: %s" % origen)
    
    if filetools.isfile(destino):
      if item.contentType == "movie" and item.infoLabels["tmdb_id"]:
        library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=destino)
        
        library.save_library_movie(library_item)
        
      elif item.contentType == "episode" and item.infoLabels["tmdb_id"]:
        library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=destino)
        
        tvshow = Item(channel= "descargas", contentType="tvshow", infoLabels = {"tmdb_id": item.infoLabels["tmdb_id"]})
        library.save_library_tvshow(tvshow, [library_item])
Beispiel #9
0
def check_blacklist(domain):
    res = True
    if not filetools.exists(PATH_BL):
        return res
    
    try:
        bl_data = jsontools.load(filetools.read(PATH_BL))
        bl_data_clean = bl_data.copy()
        expiration = config.get_setting('cf_assistant_bl_expiration', default=30) * 60
        if not expiration:
            config.set_setting('cf_assistant_bl_expiration', 30)
            expiration = 30 * 60
        time_today = time.time()
        
        if bl_data:
            for domain_reg, time_rec in list(bl_data_clean.items()):
                if time_today > time_rec + expiration:
                    del bl_data[domain_reg]
            filetools.write(PATH_BL, jsontools.dump(bl_data))
            for domain_reg, time_rec in list(bl_data.items()):
                if domain in domain_reg:
                    res = False
                    break
            else:
                res = True
    except:
        logger.error(traceback.format_exc())
        filetools.remove(PATH_BL)
        res = True

    return res
Beispiel #10
0
def menu(item):
    logger.info()
    if item.downloadServer:
        servidor = item.downloadServer.get("server", "Auto")
    else:
        servidor = "Auto"
    # Opciones disponibles para el menu
    op = [config.get_localized_string(70225), config.get_localized_string(70226), config.get_localized_string(70227),
          "Modificar servidor: %s" % (servidor.capitalize())]

    opciones = []

    # Opciones para el menu
    if item.downloadStatus == 0:  # Sin descargar
        opciones.append(op[0])  # Descargar
        if not item.server: opciones.append(op[3])  # Elegir Servidor
        opciones.append(op[1])  # Eliminar de la lista

    if item.downloadStatus == 1:  # descarga parcial
        opciones.append(op[0])  # Descargar
        if not item.server: opciones.append(op[3])  # Elegir Servidor
        opciones.append(op[2])  # Reiniciar descarga
        opciones.append(op[1])  # Eliminar de la lista

    if item.downloadStatus == 2:  # descarga completada
        opciones.append(op[1])  # Eliminar de la lista
        opciones.append(op[2])  # Reiniciar descarga

    if item.downloadStatus == 3:  # descarga con error
        opciones.append(op[2])  # Reiniciar descarga
        opciones.append(op[1])  # Eliminar de la lista

    # Mostramos el dialogo
    seleccion = platformtools.dialog_select(config.get_localized_string(30163), opciones)

    # -1 es cancelar
    if seleccion == -1: return

    logger.info("opcion=%s" % (opciones[seleccion]))
    # Opcion Eliminar
    if opciones[seleccion] == op[1]:
        filetools.remove(item.path)

    # Opcion inicaiar descarga
    if opciones[seleccion] == op[0]:
        start_download(item)

    # Elegir Servidor
    if opciones[seleccion] == op[3]:
        select_server(item)

    # Reiniciar descarga
    if opciones[seleccion] == op[2]:
        if filetools.isfile(os.path.join(config.get_setting("downloadpath"), item.downloadFilename)):
            filetools.remove(os.path.join(config.get_setting("downloadpath"), item.downloadFilename))

        update_json(item.path, {"downloadStatus": STATUS_CODES.stoped, "downloadComplete": 0, "downloadProgress": 0,
                                "downloadServer": {}})

    platformtools.itemlist_refresh()
Beispiel #11
0
def file(item):
    itemlist = []
    logger.info("[bibiolteca.py] file")
    logger.info("[biblioteca.py] urlfile--->>>" + item.url)

    risp = platformtools.dialog_select('Stream On Demand play video',
                                       ['Guarda', 'Rinomina', 'Elimina'])
    try:

        if risp == 0:
            xbmc.Player().play(item.url)

        elif risp == 1:
            nome = platformtools.dialog_input(item.fulltitle)
            os.renames(item.url, filetools.join(config.get_library_path(),
                                                nome))
            xbmc.executebuiltin("Container.Refresh")

        elif risp == 2:
            if elimina_file(item):
                filetools.remove(item.url)
                xbmc.executebuiltin("Container.Refresh")
    except:
        pass

    return itemlist
Beispiel #12
0
def play(item):
    logger.info()
    itemlist = []

    try:
        from core import filetools
        ficherosubtitulo = filetools.join(config.get_data_path(),
                                          'subtitulo_areadocu.srt')
        if filetools.exists(ficherosubtitulo):
            try:
                filetools.remove(ficherosubtitulo)
            except IOError:
                logger.error("Error al eliminar el archivo " +
                             ficherosubtitulo)
                raise

        data = httptools.downloadpage(item.subtitle,
                                      headers={
                                          'Referer': item.extra
                                      }).data
        filetools.write(ficherosubtitulo, data)
        subtitle = ficherosubtitulo
    except:
        subtitle = ""
        logger.error("Error al descargar el subtítulo")

    extension = item.url.rsplit("|", 1)[0][-4:]
    itemlist.append(
        ['%s %s [directo]' % (extension, item.calidad), item.url, 0, subtitle])

    return itemlist
Beispiel #13
0
def move_to_libray(item):

    download_path = filetools.join(config.get_setting("downloadpath"), item.downloadFilename)
    library_path = filetools.join(config.get_library_path(), *filetools.split(item.downloadFilename))
    final_path = download_path
      
    if config.get_setting("library_add", "descargas") == True and config.get_setting("library_move", "descargas") == True:   
      if not filetools.isdir(filetools.dirname(library_path)):
        filetools.mkdir(filetools.dirname(library_path))
    
      if filetools.isfile(library_path) and filetools.isfile(download_path) :
        filetools.remove(library_path)

      if filetools.isfile(download_path):
        if filetools.move(download_path, library_path):
          final_path = library_path
          
        if len(filetools.listdir(filetools.dirname(download_path))) == 0: 
          filetools.rmdir(filetools.dirname(download_path))
          
    if config.get_setting("library_add", "descargas") == True: 
      if filetools.isfile(final_path):
        if item.contentType == "movie" and item.infoLabels["tmdb_id"]:
          library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=final_path)
          library.save_library_movie(library_item)
          
        elif item.contentType == "episode" and item.infoLabels["tmdb_id"]:
          library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=final_path)
          tvshow = Item(channel= "descargas", contentType="tvshow", infoLabels = {"tmdb_id": item.infoLabels["tmdb_id"]})
          library.save_library_tvshow(tvshow, [library_item])
Beispiel #14
0
def menu(item):
    logger.info()

    # Opciones disponibles para el menu
    op = ["Descargar", "Eliminar de la lista", "Reiniciar descarga", "Descargar desde...", "Reproducir"]

    opciones = []

    # Opciones para el menu
    if item.downloadStatus == 0:  # Sin descargar
        opciones.append(op[0])  # Descargar
        opciones.append(op[3])  # Descargar desde...
        opciones.append(op[1])  # Eliminar de la lista

    if item.downloadStatus == 1:  # descarga parcial
        opciones.append(op[0])  # Descargar
        opciones.append(op[2])  # Reiniciar descarga
        opciones.append(op[1])  # Eliminar de la lista

    if item.downloadStatus == 2:  # descarga completada
        opciones.append(op[4])  # Reproducir
        opciones.append(op[1])  # Eliminar de la lista
        opciones.append(op[2])  # Reiniciar descarga

    if item.downloadStatus == 3:  # descarga con error
        opciones.append(op[2])  # Reiniciar descarga
        opciones.append(op[1])  # Eliminar de la lista

    # Mostramos el dialogo
    seleccion = platformtools.dialog_select("Scegliere un'opzione", opciones)

    # -1 es cancelar
    if seleccion == -1: return

    logger.info("opcion=%s" % (opciones[seleccion]))
    # Opcion Eliminar
    if opciones[seleccion] == op[1]:
        filetools.remove(item.path)

    # Opcion inicaiar descarga
    if opciones[seleccion] == op[0]:
        start_download(item)

    # Opcion inicaiar descarga desde...
    if opciones[seleccion] == op[3]:
        start_download(item, ask=True)

    # Reiniciar descarga
    if opciones[seleccion] == op[2]:
        if filetools.isfile(os.path.join(config.get_setting("downloadpath"), item.downloadFilename)):
            filetools.remove(os.path.join(config.get_setting("downloadpath"), item.downloadFilename))

        update_json(item.path, {"downloadStatus": STATUS_CODES.stoped, "downloadComplete": 0, "downloadProgress": 0})

    # Reproducir
    if opciones[seleccion] == op[4]:
        item.url = filetools.join(DOWNLOAD_PATH, item.downloadFilename)
        return platformtools.play_video(item)

    platformtools.itemlist_refresh()
Beispiel #15
0
 def update(self, dest_path='', platform=''):
     if dest_path: self.dest_path = dest_path
     if platform: self.platform = platform
     if self.check_update():
         for libname in get_libname(self.platform):
             self.libpath = filetools.join(self.dest_path, libname)
             filetools.remove(self.libpath)
         self.download()
Beispiel #16
0
def menu(item):
    logger.info("pelisalacarta.channels.descargas menu")

    # Opciones disponibles para el menu
    op = ["Descargar", "Eliminar de la lista", "Reiniciar descarga"]

    opciones = []

    # Opciones para el menu
    if item.downloadStatus == 0:  # Sin descargar
        opciones.append(op[0])  # Descargar
        opciones.append(op[1])  # Eliminar de la lista

    if item.downloadStatus == 1:  # descarga parcial
        opciones.append(op[0])  # Descargar
        opciones.append(op[2])  # Reiniciar descarga
        opciones.append(op[1])  # Eliminar de la lista

    if item.downloadStatus == 2:  # descarga completada
        opciones.append(op[1])  # Eliminar de la lista
        opciones.append(op[2])  # Reiniciar descarga

    if item.downloadStatus == 3:  # descarga con error
        opciones.append(op[2])  # Reiniciar descarga
        opciones.append(op[1])  # Eliminar de la lista

    # Mostramos el dialogo
    seleccion = platformtools.dialog_select("Elige una opción", opciones)

    # -1 es cancelar
    if seleccion == -1: return

    logger.info("pelisalacarta.channels.descargas menu opcion=%s" %
                (opciones[seleccion]))
    # Opcion Eliminar
    if opciones[seleccion] == op[1]:
        filetools.remove(item.path)

    # Opcion inicaiar descarga
    if opciones[seleccion] == op[0]:
        start_download(item)

    # Reiniciar descarga
    if opciones[seleccion] == op[2]:
        if filetools.isfile(
                os.path.join(config.get_setting("downloadpath"),
                             item.downloadFilename)):
            filetools.remove(
                os.path.join(config.get_setting("downloadpath"),
                             item.downloadFilename))
        JSONItem = Item().fromjson(filetools.read(item.path))
        JSONItem.downloadStatus = 0
        JSONItem.downloadComplete = 0
        JSONItem.downloadProgress = 0
        JSONItem.downloadUrl = ""
        filetools.write(item.path, JSONItem.tojson())

    platformtools.itemlist_refresh()
Beispiel #17
0
def delete_key():
    from core import filetools
    from platformcode import platformtools
    import xbmc

    filetools.remove(xbmc.translatePath( "special://profile/keymaps/kod.xml"))
    platformtools.dialog_notification(config.get_localized_string(70701),config.get_localized_string(70702))

    config.set_setting("shortcut_key", '')
Beispiel #18
0
def acciones_enlace(item):
    logger.info()

    item.__dict__['channel'] = item.__dict__.pop('from_channel')
    item.__dict__['action'] = item.__dict__.pop('from_action')

    if item.downloadStatus == STATUS_CODES.completed:
        acciones = ['Reproducir vídeo', 'Eliminar descarga']

    elif item.downloadStatus == STATUS_CODES.canceled:
        acciones = ['Continuar descarga', 'Eliminar descarga']

    elif item.downloadStatus == STATUS_CODES.error:
        acciones = ['Eliminar descarga']

    ret = platformtools.dialog_select('¿Qué hacer con esta descarga?',
                                      acciones)
    if ret == -1:
        return False  # pedido cancel

    elif acciones[ret] == 'Eliminar descarga':
        if not platformtools.dialog_yesno(
                'Eliminar descarga',
                '¿ Confirmas el borrado de la descarga %s ?' % item.title,
                'Se eliminará el fichero %s y su json con la información.' %
                item.downloadFilename):
            return False

        path_video = filetools.join(download_path, item.downloadFilename)
        if filetools.exists(path_video):
            filetools.remove(path_video)

        if filetools.exists(item.jsonfile):
            filetools.remove(item.jsonfile)

        platformtools.itemlist_refresh()
        return True

    elif acciones[ret] == 'Continuar descarga':
        item.__dict__.pop('jsonfile')
        server_item = Item().fromjson(item.__dict__.pop('server_item'))
        return download_video(server_item, item)

    elif acciones[ret] == 'Reproducir vídeo':
        import xbmcgui, xbmc
        mediaurl = filetools.join(download_path, item.downloadFilename)

        xlistitem = xbmcgui.ListItem(path=mediaurl)
        platformtools.set_infolabels(xlistitem, item, True)

        # se lanza el reproductor (no funciona si el play es desde el diálogo info !?)
        playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        playlist.clear()
        playlist.add(mediaurl, xlistitem)
        xbmc.Player().play(playlist, xlistitem)
        return True
Beispiel #19
0
def clean_ready(item):
    logger.info("pelisalacarta.channels.descargas clean_ready")
    for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)):
        if fichero.endswith(".json"):
            download_item = Item().fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero)))
            if not item.contentType == "tvshow" or (item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
              if download_item.downloadStatus == STATUS_CODES.completed:
                  filetools.remove(os.path.join(DOWNLOAD_LIST_PATH, fichero))

    platformtools.itemlist_refresh()
Beispiel #20
0
def remove_twitter_hashtag_history():
    if filetools.exists(twitter_history_file):
        filetools.remove(twitter_history_file)
        xbmc.executebuiltin(
            "XBMC.Notification(%s,%s,3000,%s)" %
            ("Match Center", "Se ha eliminado la caché",
             filetools.join(config.get_runtime_path(), "icon.png")))
    else:
        xbmcgui.Dialog().ok("Match Center",
                            "No hay historial de Twitter disponible")
Beispiel #21
0
def clean_ready(item):
    logger.info()
    for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)):
        if fichero.endswith(".json"):
            download_item = Item().fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero)))
            if not item.contentType == "tvshow" or (item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
              if download_item.downloadStatus == STATUS_CODES.completed:
                  filetools.remove(os.path.join(DOWNLOAD_LIST_PATH, fichero))

    platformtools.itemlist_refresh()
Beispiel #22
0
def clean_all(item):
    logger.info()
    
    for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)):
        if fichero.endswith(".json"):
          download_item = Item().fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero)))
          if not item.contentType == "tvshow" or (item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
              filetools.remove(os.path.join(DOWNLOAD_LIST_PATH, fichero))

    platformtools.itemlist_refresh()
Beispiel #23
0
def create_json(custom_code_json_path, json_name=json_data_file_name):
    logger.info()

    #Guardamaos el json con la versión de Alfa vacía, para permitir hacer la primera copia
    json_data_file = filetools.join(custom_code_json_path, json_name)
    if filetools.exists(json_data_file):
        filetools.remove(json_data_file)
    result = filetools.write(json_data_file, jsontools.dump({"addon_version": ""}))
    
    return
Beispiel #24
0
def clean_ready(item):
    logger.info("pelisalacarta.channels.descargas clean_ready")
    for fichero in sorted(filetools.listdir(item.url)):
        if fichero.endswith(".json"):
            download_item = Item().fromjson(filetools.read(os.path.join(item.url, fichero)))
            serie_name = "%s [%s]" % (download_item.contentSerieName, download_item.contentChannel)
            if not item.serie_name or item.serie_name == serie_name:
              if download_item.downloadStatus == 2:
                  filetools.remove(os.path.join(item.url, fichero))

    platformtools.itemlist_refresh()
Beispiel #25
0
    def android_workaround(self, new_dest_path):                                ### Alfa (entera)
        import subprocess
        
        for libname in get_libname(self.platform):
            libpath=os.path.join(self.dest_path, libname)
            size=str(os.path.getsize(libpath))
            new_libpath=os.path.join(new_dest_path, libname)

            if filetools.exists(new_libpath):
                new_size=str(os.path.getsize(new_libpath))
                if size != new_size:
                    filetools.remove(new_libpath)
                    if filetools.exists(new_libpath):
                        try:
                            command = ['su', '-c', 'rm', '%s' % new_libpath]
                            p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                            output_cmd, error_cmd = p.communicate()
                            log('Comando ROOT: %s' % str(command))
                        except:
                            log('Sin PERMISOS ROOT: %s' % str(command))
                    
                    if not filetools.exists(new_libpath):
                        log('Deleted: (%s) %s -> (%s) %s' %(size, libpath, new_size, new_libpath))
                    
            if not filetools.exists(new_libpath):
                filetools.copy(libpath, new_libpath, silent=True)                 ### ALFA
                log('Copying... %s -> %s' %(libpath, new_libpath))
                
                if not filetools.exists(new_libpath):
                    try:
                        command = ['su', '-c', 'cp', '%s' % libpath, '%s' % new_libpath]
                        p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                        output_cmd, error_cmd = p.communicate()
                        log('Comando ROOT: %s' % str(command))
                        
                        command = ['su', '-c', 'chmod', '777', '%s' % new_libpath]
                        p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                        output_cmd, error_cmd = p.communicate()
                        log('Comando ROOT: %s' % str(command))
                    except:
                        log('Sin PERMISOS ROOT: %s' % str(command))

                    if not filetools.exists(new_libpath):
                        log('ROOT Copy Failed!')
                
                else:
                    command = ['chmod', '777', '%s' % new_libpath]
                    p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                    output_cmd, error_cmd = p.communicate()
                    log('Comando: %s' % str(command))
            else:
                log('Module exists.  Not copied... %s' % new_libpath)           ### ALFA

        return new_dest_path
Beispiel #26
0
def reset_trakt(item):
    from core import trakt_tools

    data_path = filetools.join(config.get_data_path(), 'settings_channels',
                               'trakt_data.json')
    if filetools.exists(data_path):
        filetools.remove(data_path)
        trakt_tools.auth_trakt()
    else:
        platformtools.dialog_ok(
            "Alfa", "Aun no existen datos de vinculación con Trakt")
Beispiel #27
0
def menu(item):
    logger.info("pelisalacarta.channels.descargas menu")

    # Opciones disponibles para el menu
    op = ["Descargar", "Eliminar de la lista", "Reiniciar descarga"]

    opciones = []

    # Opciones para el menu
    if item.downloadStatus == 0:  # Sin descargar
        opciones.append(op[0])  # Descargar
        opciones.append(op[1])  # Eliminar de la lista

    if item.downloadStatus == 1:  # descarga parcial
        opciones.append(op[0])  # Descargar
        opciones.append(op[2])  # Reiniciar descarga
        opciones.append(op[1])  # Eliminar de la lista

    if item.downloadStatus == 2:  # descarga completada
        opciones.append(op[1])  # Eliminar de la lista
        opciones.append(op[2])  # Reiniciar descarga

    if item.downloadStatus == 3:  # descarga con error
        opciones.append(op[2])  # Reiniciar descarga
        opciones.append(op[1])  # Eliminar de la lista

    # Mostramos el dialogo
    seleccion = platformtools.dialog_select("Elige una opción", opciones)

    # -1 es cancelar
    if seleccion == -1: return

    logger.info("pelisalacarta.channels.descargas menu opcion=%s" % (opciones[seleccion]))
    # Opcion Eliminar
    if opciones[seleccion] == op[1]:
        filetools.remove(item.path)

    # Opcion inicaiar descarga
    if opciones[seleccion] == op[0]:
        start_download(item)

    # Reiniciar descarga
    if opciones[seleccion] == op[2]:
        if filetools.isfile(os.path.join(config.get_setting("downloadpath"), item.downloadFilename)):
            filetools.remove(os.path.join(config.get_setting("downloadpath"), item.downloadFilename))
        JSONItem = Item().fromjson(filetools.read(item.path))
        JSONItem.downloadStatus = 0
        JSONItem.downloadComplete = 0
        JSONItem.downloadProgress = 0
        JSONItem.downloadUrl = ""
        filetools.write(item.path, JSONItem.tojson())

    platformtools.itemlist_refresh()
Beispiel #28
0
def download(item=None):
    ret = True

    if filetools.exists(elementum_path):
        if platformtools.dialog_yesno(config.get_localized_string(70784),
                                      config.get_localized_string(70783)):
            addon_file = filetools.file_open(
                filetools.join(elementum_path, 'addon.xml')).read()
            required = support.match(addon_file,
                                     patron=r'addon="([^"]+)').matches
            for r in required:
                xbmc.executebuiltin('InstallAddon(' + r + ')', wait=True)
            setting()
            platformtools.dialog_ok('Elementum',
                                    config.get_localized_string(70783))
        else:
            ret = False

    else:
        if platformtools.dialog_yesno(config.get_localized_string(70784),
                                      config.get_localized_string(70782)):
            pform = get_platform()
            url = support.match(
                elementum_url,
                patron=r'<a href="([a-zA-Z0-9/\.-]+{}.zip)'.format(
                    pform)).match
            support.info('OS:', pform)
            support.info('Extract IN:', elementum_path)
            support.info('URL:', url)
            if url:
                dl = downloadtools.downloadfile(host + url, filename)
                if dl == -3:
                    filetools.remove(filename)
                    dl = downloadtools.downloadfile(host + url, filename)
                if dl == None:
                    extract()
                    xbmc.sleep(1000)
                    addon_file = filetools.file_open(
                        filetools.join(elementum_path, 'addon.xml')).read()
                    required = support.match(addon_file,
                                             patron=r'addon="([^"]+)').matches
                    for r in required:
                        xbmc.executebuiltin('InstallAddon(' + r + ')',
                                            wait=True)
                    setting()
                else:
                    ret = False
            else:
                ret = False
        else:
            ret = False
    return ret
Beispiel #29
0
def clean_ready(item):
    logger.info("pelisalacarta.channels.descargas clean_ready")
    for fichero in sorted(filetools.listdir(item.url)):
        if fichero.endswith(".json"):
            download_item = Item().fromjson(
                filetools.read(os.path.join(item.url, fichero)))
            serie_name = "%s [%s]" % (download_item.contentSerieName,
                                      download_item.contentChannel)
            if not item.serie_name or item.serie_name == serie_name:
                if download_item.downloadStatus == 2:
                    filetools.remove(os.path.join(item.url, fichero))

    platformtools.itemlist_refresh()
Beispiel #30
0
    def __init__(self, filename=None):

        # If no file is specified, the active_list is used (if not, it is created)
        if filename == None:
            filename = get_lista_activa()

        self.user_favorites_file = os.path.join(config.get_data_path(),
                                                filename)

        if not os.path.exists(self.user_favorites_file):
            fichero_anterior = os.path.join(config.get_data_path(),
                                            'user_favorites.json')
            if os.path.exists(
                    fichero_anterior
            ):  # old format, convert (to delete after some versions)
                jsondata = jsontools.load(filetools.read(fichero_anterior))
                self.user_favorites = jsondata
                self.info_lista = {}
                self.save()
                filetools.remove(fichero_anterior)
            else:
                self.user_favorites = []
        else:
            jsondata = jsontools.load(filetools.read(self.user_favorites_file))
            if not 'user_favorites' in jsondata or not 'info_lista' in jsondata:  # incorrect format
                self.user_favorites = []
            else:
                self.user_favorites = jsondata['user_favorites']
                self.info_lista = jsondata['info_lista']

        if len(self.user_favorites) == 0:
            self.info_lista = {}

            # Create some default folders
            self.user_favorites.append({
                'title':
                config.get_localized_string(30122),
                'items': []
            })
            self.user_favorites.append({
                'title':
                config.get_localized_string(30123),
                'items': []
            })
            self.user_favorites.append({
                'title':
                config.get_localized_string(70149),
                'items': []
            })

            self.save()
Beispiel #31
0
    def __init__(self, filename=None):

        # Si no se especifica ningún fichero se usa la lista_activa (si no la hay se crea)
        if filename == None:
            filename = get_lista_activa()

        self.user_favorites_file = os.path.join(config.get_data_path(),
                                                filename)

        if not os.path.exists(self.user_favorites_file):
            fichero_anterior = os.path.join(config.get_data_path(),
                                            'user_favorites.json')
            if os.path.exists(
                    fichero_anterior
            ):  # formato anterior, convertir (a eliminar después de algunas versiones)
                jsondata = jsontools.load(filetools.read(fichero_anterior))
                self.user_favorites = jsondata
                self.info_lista = {}
                self.save()
                filetools.remove(fichero_anterior)
            else:
                self.user_favorites = []
        else:
            jsondata = jsontools.load(filetools.read(self.user_favorites_file))
            if not 'user_favorites' in jsondata or not 'info_lista' in jsondata:  # formato incorrecto
                self.user_favorites = []
            else:
                self.user_favorites = jsondata['user_favorites']
                self.info_lista = jsondata['info_lista']

        if len(self.user_favorites) == 0:
            self.info_lista = {}

            # Crear algunas carpetas por defecto
            self.user_favorites.append({
                'title':
                config.get_localized_string(30122),
                'items': []
            })
            self.user_favorites.append({
                'title':
                config.get_localized_string(30123),
                'items': []
            })
            self.user_favorites.append({
                'title':
                config.get_localized_string(70149),
                'items': []
            })

            self.save()
Beispiel #32
0
def move_to_libray(item):
    if not config.get_setting("library_move", "descargas") == True:
        return

    try:
        from core import library
    except:
        return

    # Copiamos el archivo a la biblioteca
    origen = filetools.join(config.get_setting("downloadpath"),
                            item.downloadFilename)
    destino = filetools.join(config.get_library_path(),
                             *filetools.split(item.downloadFilename))

    if not filetools.isdir(filetools.dirname(destino)):
        filetools.mkdir(filetools.dirname(destino))

    if filetools.isfile(destino) and filetools.isfile(origen):
        filetools.remove(destino)

    if filetools.isfile(origen):
        filetools.move(origen, destino)
        if len(filetools.listdir(filetools.dirname(origen))) == 0:
            filetools.rmdir(filetools.dirname(origen))

    else:
        logger.error("No se ha encontrado el archivo: %s" % origen)

    if filetools.isfile(destino):
        if item.contentType == "movie" and item.infoLabels["tmdb_id"]:
            library_item = Item(title="Scaricato: %s" % item.downloadFilename,
                                channel="descargas",
                                action="findvideos",
                                infoLabels=item.infoLabels,
                                url=item.downloadFilename)

            library.save_library_movie(library_item)

        elif item.contentType == "episode" and item.infoLabels["tmdb_id"]:
            library_item = Item(title="Scaricato: %s" % item.downloadFilename,
                                channel="descargas",
                                action="findvideos",
                                infoLabels=item.infoLabels,
                                url=item.downloadFilename)

            tvshow = Item(channel="descargas",
                          contentType="tvshow",
                          infoLabels={"tmdb_id": item.infoLabels["tmdb_id"]})
            library.save_library_tvshow(tvshow, [library_item])
Beispiel #33
0
def verify_script_alfa_update_helper():
    logger.info()
    
    import json
    from zipfile import ZipFile
    from core import httptools
    
    addonid = 'script.alfa-update-helper'
    package = addonid + '-0.0.1.zip'
    filetools.remove(filetools.join(xbmc.translatePath('special://home'), 'addons', 'packages', package), True)
    
    # Comprobamos si hay acceso a Github
    url = 'https://github.com/alfa-addon/alfa-repo/raw/master/plugin.video.alfa/addon.xml'
    response = httptools.downloadpage(url, timeout=5, ignore_response_code=True, alfa_s=True)
    if response.code != 200 and not bool(xbmc.getCondVisibility("System.HasAddon(%s)" % addonid)):
        
        # Si no lo hay, descargamos el Script desde Bitbucket y lo salvamos a disco
        url = 'https://bitbucket.org/alfa_addon/alfa-repo/raw/master/script.alfa-update-helper/%s' % package
        response = httptools.downloadpage(url, ignore_response_code=True, alfa_s=True)
        if response.code == 200:
            zip_data = response.data
            addons_path = xbmc.translatePath("special://home/addons")
            pkg_updated = filetools.join(addons_path, 'packages', package)
            with open(pkg_updated, "wb") as f:
                f.write(zip_data)
            
            # Verificamos el .zip
            ret = None
            try:
                with ZipFile(pkg_updated, "r") as zf:
                    ret = zf.testzip()
            except Exception as e:
                ret = str(e)
            if ret is not None:
                logger.error("Corrupted .zip, error: %s" % (str(ret)))
            else:
                # Si el .zip es correcto los extraemos e instalamos
                with ZipFile(pkg_updated, "r") as zf:
                    zf.extractall(addons_path)

                logger.info("Installiing %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)
Beispiel #34
0
def restart_error(item):
    logger.info("pelisalacarta.channels.descargas restart_error")
    for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)):
        if fichero.endswith(".json"):
            download_item = Item().fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero)))
            
            if not item.contentType == "tvshow" or (item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
              if download_item.downloadStatus == STATUS_CODES.error:
                  if filetools.isfile(os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename)):
                      filetools.remove(os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename))
                      
                  update_json(item.path, {"downloadStatus" : STATUS_CODES.stoped, "downloadComplete" :  0 , "downloadProgress" : 0})


    platformtools.itemlist_refresh()
Beispiel #35
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()
Beispiel #36
0
def remove_local_episodes(item):
    logger.info()

    nfo_path = filetools.join(item.path, "tvshow.nfo")
    head_nfo, item_nfo = videolibrarytools.read_nfo(nfo_path)

    for season_episode in item_nfo.local_episodes_list:
        filetools.remove(filetools.join(item.path, season_episode + '.strm'))

    item_nfo.local_episodes_list = []
    item_nfo.local_episodes_path = ''
    filetools.write(nfo_path, head_nfo + item_nfo.tojson())

    update_tvshow(item)

    platformtools.itemlist_refresh()
def eliminar(item):

    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()


    logger.info(item.contentTitle)
    #logger.debug(item.tostring('\n'))

    if item.contentType == 'movie':
        heading = "Eliminar película"
    else:
        heading = "Eliminar serie"

    if item.multicanal:
        # Obtener listado de canales
        opciones = ["Eliminar solo los enlaces de %s" % k.capitalize() for k in item.library_urls.keys() if k !="descargas"]
        opciones.insert(0, heading)

        index = platformtools.dialog_select(config.get_localized_string(30163), opciones)

        if index == 0:
            # Seleccionado Eliminar pelicula/serie
            eliminar_todo(item)

        elif index > 0:
            # Seleccionado Eliminar canal X
            canal = opciones[index].replace("Eliminar solo los enlaces de ", "").lower()

            num_enlaces= 0
            for fd in filetools.listdir(item.path):
                if fd.endswith(canal + '].json'):
                    if filetools.remove(filetools.join(item.path, fd)):
                        num_enlaces += 1

            if num_enlaces > 0:
                # Actualizar .nfo
                head_nfo, item_nfo = library.read_nfo(item.nfo)
                del item_nfo.library_urls[canal]
                filetools.write(item.nfo, head_nfo + item_nfo.tojson())

            msg_txt = "Eliminados %s enlaces del canal %s" % (num_enlaces, canal)
            logger.info(msg_txt)
            platformtools.dialog_notification(heading, msg_txt)
            platformtools.itemlist_refresh()

    else:
        if platformtools.dialog_yesno(heading,
                                      "¿Realmente desea eliminar '%s' de su biblioteca?" % item.infoLabels['title']):
            eliminar_todo(item)
Beispiel #38
0
    def android_workaround(self, new_dest_path):  ### Alfa (entera)

        for libname in get_libname(self.platform):
            libpath = filetools.join(self.dest_path, libname)
            size = str(filetools.getsize(libpath))
            new_libpath = filetools.join(new_dest_path, libname)

            if filetools.exists(new_libpath):
                new_size = str(filetools.getsize(new_libpath))
                if size != new_size:
                    res = filetools.remove(new_libpath, su=True)
                    if res:
                        log('Deleted: (%s) %s -> (%s) %s' %
                            (size, libpath, new_size, new_libpath))

            if not filetools.exists(new_libpath):
                res = filetools.copy(libpath,
                                     new_libpath,
                                     ch_mod='777',
                                     su=True)  ### ALFA

            else:
                log('Module exists.  Not copied... %s' % new_libpath)  ### ALFA

        return new_dest_path
Beispiel #39
0
def restart_error(item):
    logger.info("pelisalacarta.channels.descargas restart_error")
    for fichero in sorted(filetools.listdir(item.url)):
        if fichero.endswith(".json"):
            download_item = Item().fromjson(filetools.read(os.path.join(item.url, fichero)))
            serie_name = "%s [%s]" % (download_item.contentSerieName, download_item.contentChannel)
            if not item.serie_name or item.serie_name == serie_name:
              if download_item.downloadStatus == 3:
                  if filetools.isfile(os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename)):
                      filetools.remove(os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename))
                  download_item.downloadStatus = 0
                  download_item.downloadComplete = 0
                  download_item.downloadProgress = 0
                  download_item.downloadUrl = ""
                  filetools.write(os.path.join(item.url, fichero), download_item.tojson())

    platformtools.itemlist_refresh()
def file(item):
    itemlist = []
    logger.info("[bibiolteca.py] file")
    logger.info("[biblioteca.py] urlfile--->>>" + item.url)

    risp = platformtools.dialog_select('Stream On Demand play video', ['Guarda', 'Rinomina', 'Elimina'])
    try:

        if risp == 0:
            xbmc.Player().play(item.url)

        elif risp == 1:
            nome = platformtools.dialog_input(item.fulltitle)
            os.renames(item.url, filetools.join(config.get_library_path(), nome))
            xbmc.executebuiltin("Container.Refresh")

        elif risp == 2:
            if elimina_file(item):
                filetools.remove(item.url)
                xbmc.executebuiltin("Container.Refresh")
    except:
        pass

    return itemlist
    path = filetools.join(TVSHOWS_PATH, "{0} [{1}]".format(item.contentSerieName.strip().lower(), item.channel).lower())
    if not filetools.exists(path):
        logger.info("streamondemand.platformcode.library save_library_tvshow Creando directorio serie:" + path)
        try:
            filetools.mkdir(path)
        except OSError, exception:
            if exception.errno != errno.EEXIST:
                raise

    filetools.write(filetools.join(path, "tvshow.json"), item.tojson())

    if 'tmdb_id' in item.infoLabels:
        create_nfo_file(item.infoLabels['tmdb_id'], path, "serie")
    else:
        if filetools.exists(filetools.join(path, "tvshow.nfo")):
            filetools.remove(filetools.join(path, "tvshow.nfo"))

    # Guardar los episodios
    insertados, sobreescritos, fallidos = save_library_episodes(path, episodelist, item)

    return insertados, sobreescritos, fallidos


def save_library_episodes(path, episodelist, serie, silent=False):
    """
    guarda en la ruta indicada todos los capitulos incluidos en la lista episodelist
    @type path: str
    @param path: ruta donde guardar los episodios
    @type episodelist: list
    @param episodelist: listado de items que representan los episodios que se van a guardar.
    @type serie: item
def save_library_movie(item):
    """
    guarda en la libreria de peliculas el elemento item, con los valores que contiene.
    @type item: item
    @param item: elemento que se va a guardar.
    @rtype insertados: int
    @return:  el número de elementos insertados
    @rtype sobreescritos: int
    @return:  el número de elementos sobreescritos
    @rtype fallidos: int
    @return:  el número de elementos fallidos o -1 si ha fallado todo
    """
    logger.info("streamondemand.platformcode.library savelibrary_movie")
    insertados = 0
    sobreescritos = 0
    fallidos = 0
    logger.debug(item.tostring('\n'))

    # Itentamos obtener el titulo correcto:
    # 1. contentTitle: Este deveria ser el sitio correcto
    # 2. fulltitle
    # 3. title
    titulo = item.contentTitle
    if not titulo:
        titulo = item.fulltitle
    if not titulo:
        titulo = item.title

    # Colocamos el titulo en su sitio para que tmdb lo localize
    item.contentTitle = titulo

    # Si llegados a este punto no tenemos titulo, salimos
    if not item.contentTitle or not item.channel:
        return 0, 0, -1  # Salimos sin guardar
    # TODO configurar para segun el scraper se llamara a uno u otro
    tmdb.find_and_set_infoLabels_tmdb(item, config.get_setting("scrap_ask_name") == "true")

    # Llegados a este punto podemos tener:
    # Un item con infoLabels con la información actualizada de la peli
    # Un item sin información de la peli (se ha dado a cancelar en la ventana)

    # progress dialog
    p_dialog = platformtools.dialog_progress('streamondemand', 'Aggiunta film...')
    filename = "{0} [{1}].strm".format(item.fulltitle.strip().lower(), item.channel)
    logger.debug(filename)
    fullfilename = filetools.join(MOVIES_PATH, filename)
    addon_name = sys.argv[0].strip()
    if not addon_name or addon_name.startswith("default.py"):
        addon_name = "plugin://plugin.video.streamondemand/"

    if filetools.exists(fullfilename):
        logger.info("streamondemand.platformcode.library savelibrary el fichero existe. Se sobreescribe")
        sobreescritos += 1
    else:
        insertados += 1

    p_dialog.update(100, 'Añadiendo película...', item.contentTitle)
    p_dialog.close()

    item.strm = True

    # Para depuración creamos un .json al lado del .strm, para poder visualizar que parametros se estan guardando
    filetools.write(fullfilename + ".json", item.tojson())

    if filetools.write(fullfilename, '{addon}?{url}'.format(addon=addon_name, url=item.tourl())):
        if 'tmdb_id' in item.infoLabels:
            create_nfo_file(item.infoLabels['tmdb_id'], fullfilename[:-5], "cine")
        else:
            if filetools.exists(fullfilename[:-5] + ".nfo"):
                filetools.remove(fullfilename[:-5] + ".nfo")

        # actualizamos la biblioteca de Kodi con la pelicula
        # TODO arreglar el porque hay que poner la ruta special
        ruta = "special://home/userdata/addon_data/plugin.video.streamondemand/library/CINE/"
        update(ruta)

        return insertados, sobreescritos, fallidos
    else:
        return 0, 0, 1
def addchannel(item):
    from platformcode import platformtools

    import time, os

    logger.info("pelisalacarta.channels.configuracion addchannel")

    tecleado = platformtools.dialog_input("", "Introduzca la URL")
    if not tecleado:
        return
    logger.info("pelisalacarta.channels.configuracion url=%s" % tecleado)

    local_folder = config.get_runtime_path()
    if "canal" in item.title:
        local_folder = filetools.join(local_folder, "channels")
        folder_to_extract = "channels"
        info_accion = "canal"
    else:
        local_folder = filetools.join(local_folder, "servers")
        folder_to_extract = "servers"
        info_accion = "conector"

    # Detecta si es un enlace a un .py o .xml (pensado sobre todo para enlaces de github)
    try:
        extension = tecleado.rsplit(".", 1)[1]
    except:
        extension = ""

    files = []
    zip = False
    if extension == "py" or extension == "xml":
        filename = tecleado.rsplit("/", 1)[1]
        localfilename = filetools.join(local_folder, filename)
        files.append([tecleado, localfilename, filename])
    else:
        import re
        from core import scrapertools

        # Comprueba si la url apunta a una carpeta completa (channels o servers) de github
        if re.search(r"https://github.com/[^\s]+/" + folder_to_extract, tecleado):
            try:
                data = scrapertools.downloadpage(tecleado)
                matches = scrapertools.find_multiple_matches(
                    data, '<td class="content">.*?href="([^"]+)".*?title="([^"]+)"'
                )
                for url, filename in matches:
                    url = "https://raw.githubusercontent.com" + url.replace("/blob/", "/")
                    localfilename = filetools.join(local_folder, filename)
                    files.append([url, localfilename, filename])
            except:
                import traceback

                logger.info("Detalle del error: %s" % traceback.format_exc())
                platformtools.dialog_ok("Error", "La url no es correcta o no está disponible")
                return
        else:
            filename = "new%s.zip" % info_accion
            localfilename = filetools.join(config.get_data_path(), filename)
            files.append([tecleado, localfilename, filename])
            zip = True

    logger.info("pelisalacarta.channels.configuracion localfilename=%s" % localfilename)
    logger.info("pelisalacarta.channels.configuracion descarga fichero...")

    try:
        if len(files) > 1:
            lista_opciones = ["No", "Sí", "Sí (Sobrescribir todos)"]
            overwrite_all = False
        from core import downloadtools

        for url, localfilename, filename in files:
            result = downloadtools.downloadfile(url, localfilename, continuar=False)
            if result == -3:
                if len(files) == 1:
                    dyesno = platformtools.dialog_yesno(
                        "El archivo ya existe",
                        "Ya existe el %s %s." " ¿Desea sobrescribirlo?" % (info_accion, filename),
                    )
                else:
                    if not overwrite_all:
                        dyesno = platformtools.dialog_select(
                            "El archivo %s ya existe, ¿desea sobrescribirlo?" % filename, lista_opciones
                        )
                    else:
                        dyesno = 1
                # Diálogo cancelado
                if dyesno == -1:
                    return
                # Caso de carpeta github, opción sobrescribir todos
                elif dyesno == 2:
                    overwrite_all = True
                elif dyesno:
                    hora_folder = "Copia seguridad [%s]" % time.strftime("%d-%m_%H-%M", time.localtime())
                    backup = filetools.join(config.get_data_path(), "backups", hora_folder, folder_to_extract)
                    if not filetools.exists(backup):
                        os.makedirs(backup)
                    import shutil

                    shutil.copy2(localfilename, filetools.join(backup, filename))
                    result = downloadtools.downloadfile(url, localfilename, continuar=True)
                else:
                    if len(files) == 1:
                        return
                    else:
                        continue
    except:
        import traceback

        logger.info("Detalle del error: %s" % traceback.format_exc())
        return

    if zip:
        try:
            # Lo descomprime
            logger.info("pelisalacarta.channels.configuracion descomprime fichero...")
            from core import ziptools

            unzipper = ziptools.ziptools()
            logger.info("pelisalacarta.channels.configuracion destpathname=%s" % local_folder)
            unzipper.extract(localfilename, local_folder, folder_to_extract, True, True)
        except:
            import traceback

            logger.info("Detalle del error: %s" % traceback.format_exc())
            # Borra el zip descargado
            filetools.remove(localfilename)
            platformtools.dialog_ok("Error", "Se ha producido un error extrayendo el archivo")
            return

        # Borra el zip descargado
        logger.info("pelisalacarta.channels.configuracion borra fichero...")
        filetools.remove(localfilename)
        logger.info("pelisalacarta.channels.configuracion ...fichero borrado")

    platformtools.dialog_ok("Éxito", "Actualización/Instalación realizada correctamente")
def addchannel(item):
    from platformcode import platformtools
    import os
    import time
    logger.info()
    
    tecleado = platformtools.dialog_input("", "Inserire l'URL")
    if not tecleado:
        return
    logger.info("url=%s" % tecleado)

    local_folder = config.get_runtime_path()
    if "canal" in item.title:
        local_folder = filetools.join(local_folder, 'channels')
        folder_to_extract = "channels"
        info_accion = "canal"
    else:
        local_folder = filetools.join(local_folder, 'servers')
        folder_to_extract = "servers"
        info_accion = "conector"

    # Detecta si es un enlace a un .py o .xml (pensado sobre todo para enlaces de github)
    try:
        extension = tecleado.rsplit(".", 1)[1]
    except:
        extension = ""

    files = []
    zip = False
    if extension == "py" or extension == "xml":
        filename = tecleado.rsplit("/", 1)[1]
        localfilename = filetools.join(local_folder, filename)
        files.append([tecleado, localfilename, filename])
    else:
        import re
        from core import scrapertools
        # Comprueba si la url apunta a una carpeta completa (channels o servers) de github
        if re.search(r'https://github.com/[^\s]+/'+folder_to_extract, tecleado):
            try:
                data = scrapertools.downloadpage(tecleado)
                matches = scrapertools.find_multiple_matches(data,
                                                             '<td class="content">.*?href="([^"]+)".*?title="([^"]+)"')
                for url, filename in matches:
                    url = "https://raw.githubusercontent.com" + url.replace("/blob/", "/")
                    localfilename = filetools.join(local_folder, filename)
                    files.append([url, localfilename, filename])
            except:
                import traceback
                logger.info("Detalle del error: %s" % traceback.format_exc())
                platformtools.dialog_ok("Errore", "L'URL non è corretto o non disponibile")
                return
        else:
            filename = 'new%s.zip' % info_accion
            localfilename = filetools.join(config.get_data_path(), filename)
            files.append([tecleado, localfilename, filename])
            zip = True

    logger.info("localfilename=%s" % localfilename)
    logger.info("descarga fichero...")
    
    try:
        if len(files) > 1:
            lista_opciones = ["No", "Si", "Si (Sovrascrivere tutto)"]
            overwrite_all = False
        from core import downloadtools
        for url, localfilename, filename in files:
            result = downloadtools.downloadfile(url, localfilename, continuar=False)
            if result == -3:
                if len(files) == 1:
                    dyesno = platformtools.dialog_yesno("Il file esiste già", "%s %s esiste già. "
                                                                                "Vuoi sovrascrivere?" %
                                                        (info_accion, filename))
                else:
                    if not overwrite_all:
                        dyesno = platformtools.dialog_select("Il file %s esiste già, vuoi sovrascrivere?"
                                                             % filename, lista_opciones)
                    else:
                        dyesno = 1
                # Diálogo cancelado
                if dyesno == -1:
                    return
                # Caso de carpeta github, opción sobrescribir todos
                elif dyesno == 2:
                    overwrite_all = True
                elif dyesno:
                    hora_folder = "Backup [%s]" % time.strftime("%d-%m_%H-%M", time.localtime())
                    backup = filetools.join(config.get_data_path(), 'backups', hora_folder, folder_to_extract)
                    if not filetools.exists(backup):
                        os.makedirs(backup)
                    import shutil
                    shutil.copy2(localfilename, filetools.join(backup, filename))
                    downloadtools.downloadfile(url, localfilename, continuar=True)
                else:
                    if len(files) == 1:
                        return
                    else:
                        continue
    except:
        import traceback
        logger.info("Detalle del error: %s" % traceback.format_exc())
        return

    if zip:
        try:
            # Lo descomprime
            logger.info("descomprime fichero...")
            from core import ziptools
            unzipper = ziptools.ziptools()
            logger.info("destpathname=%s" % local_folder)
            unzipper.extract(localfilename, local_folder, folder_to_extract, True, True)
        except:
            import traceback
            logger.error("Detalle del error: %s" % traceback.format_exc())
            # Borra el zip descargado
            filetools.remove(localfilename)
            platformtools.dialog_ok("Errore", "C'è stato un errore nell'estrazione del file")
            return

        # Borra el zip descargado
        logger.info("borra fichero...")
        filetools.remove(localfilename)
        logger.info("...fichero borrado")

    platformtools.dialog_ok("Successo", "Aggiornamento/installazione eseguita correttamente")