Example #1
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
Example #2
0
def set_server_setting(name, value, server):
    # Creamos la carpeta si no existe
    if not filetools.exists(
            filetools.join(config.get_data_path(), "settings_servers")):
        filetools.mkdir(
            filetools.join(config.get_data_path(), "settings_servers"))

    file_settings = filetools.join(config.get_data_path(), "settings_servers",
                                   server + "_data.json")
    dict_settings = {}

    dict_file = None

    if filetools.exists(file_settings):
        # Obtenemos configuracion guardada de ../settings/channel_data.json
        try:
            dict_file = jsontools.load(filetools.read(file_settings))
            dict_settings = dict_file.get('settings', {})
        except EnvironmentError:
            logger.info("ERROR al leer el archivo: %s" % file_settings)

    dict_settings[name] = value

    # comprobamos si existe dict_file y es un diccionario, sino lo creamos
    if dict_file is None or not dict_file:
        dict_file = {}

    dict_file['settings'] = dict_settings

    # Creamos el archivo ../settings/channel_data.json
    if not filetools.write(file_settings, jsontools.dump(dict_file)):
        logger.info("ERROR al salvar el archivo: %s" % file_settings)
        return None

    return value
def save_library_tvshow(item, episodelist):
    """
    guarda en la libreria de series la serie con todos los capitulos incluidos en la lista episodelist
    @type item: item
    @param item: item que representa la serie a guardar
    @type episodelist: list
    @param episodelist: listado de items que representan los episodios que se van a guardar.
    @rtype insertados: int
    @return:  el número de episodios insertados
    @rtype sobreescritos: int
    @return:  el número de episodios sobreescritos
    @rtype fallidos: int
    @return:  el número de episodios fallidos o -1 si ha fallado toda la serie
    """
    logger.info()
    # logger.debug(item.tostring('\n'))
    path = ""

    # Si llegados a este punto no tenemos titulo o tmdb_id, salimos
    if not (item.contentSerieName or item.infoLabels['tmdb_id']) or not item.channel:
        logger.debug("NO ENCONTRADO contentSerieName NI tmdb_id")
        return 0, 0, -1  # Salimos sin guardar

    # TODO configurar para segun el scraper se llame a uno u otro
    scraper_return = scraper.find_and_set_infoLabels(item)

    # Llegados a este punto podemos tener:
    #  scraper_return = True: Un item con infoLabels con la información actualizada de la serie
    #  scraper_return = False: Un item sin información de la peli (se ha dado a cancelar en la ventana)
    #  item.infoLabels['code'] == "" : No se ha encontrado el identificador de IMDB necesario para continuar, salimos
    if not scraper_return or not item.infoLabels['code']:
        # TODO de momento si no hay resultado no añadimos nada,
        # aunq podriamos abrir un cuadro para introducir el identificador/nombre a mano
        logger.debug("NO ENCONTRADO EN SCRAPER O NO TIENE IMDB_ID")
        return 0, 0, -1

    _id = item.infoLabels['code']
    if config.get_setting("original_title_folder", "biblioteca") == 1 and item.infoLabels['originaltitle']:
        base_name = item.infoLabels['originaltitle']
    elif item.infoLabels['title']:
        base_name = item.infoLabels['title']
    else:
        base_name = item.contentSerieName

    base_name = filetools.validate_path(base_name.replace('/', '-')).lower()

    for raiz, subcarpetas, ficheros in filetools.walk(TVSHOWS_PATH):
        for c in subcarpetas:
            if c.endswith("[%s]" % _id):
                path = filetools.join(raiz, c)
                break

    if not path:
        path = filetools.join(TVSHOWS_PATH, ("%s [%s]" % (base_name, _id)).strip())
        logger.info("Creando directorio serie: " + path)
        try:
            filetools.mkdir(path)
        except OSError, exception:
            if exception.errno != errno.EEXIST:
                raise
Example #4
0
def set_server_setting(name, value, server):
    # We create the folder if it does not exist
    if not filetools.exists(filetools.join(config.get_data_path(), "settings_servers")):
        filetools.mkdir(filetools.join(config.get_data_path(), "settings_servers"))

    file_settings = filetools.join(config.get_data_path(), "settings_servers", server + "_data.json")
    dict_settings = {}

    dict_file = None

    if filetools.exists(file_settings):
        # We get saved configuration from ../settings/channel_data.json
        try:
            dict_file = jsontools.load(filetools.read(file_settings))
            dict_settings = dict_file.get('settings', {})
        except EnvironmentError:
            logger.error("ERROR when reading the file: %s" % file_settings)

    dict_settings[name] = value

    # we check if dict_file exists and it is a dictionary, if not we create it
    if dict_file is None or not dict_file:
        dict_file = {}

    dict_file['settings'] = dict_settings

    # We create the file ../settings/channel_data.json
    if not filetools.write(file_settings, jsontools.dump(dict_file)):
        logger.error("ERROR saving file: %s" % file_settings)
        return None

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

    if filetools.isfile(origen):
      filetools.move(origen, destino)
      if len(filetools.listdir(filetools.dirname(origen))) == 0: 
        filetools.rmdir(filetools.dirname(origen))
      
    else:
      logger.error("No se ha encontrado el archivo: %s" % origen)
    
    if filetools.isfile(destino):
      if item.contentType == "movie" and item.infoLabels["tmdb_id"]:
        library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=destino)
        
        library.save_library_movie(library_item)
        
      elif item.contentType == "episode" and item.infoLabels["tmdb_id"]:
        library_item = Item(title="Descargado: %s" % item.downloadFilename, channel= "descargas", action="findvideos", infoLabels=item.infoLabels, url=destino)
        
        tvshow = Item(channel= "descargas", contentType="tvshow", infoLabels = {"tmdb_id": item.infoLabels["tmdb_id"]})
        library.save_library_tvshow(tvshow, [library_item])
Example #6
0
def verify_directories_created():
    from core import logger
    from core import filetools

    config_paths = [["librarypath", "library"], ["downloadpath", "downloads"],
                    ["downloadlistpath", "downloads/list"],
                    ["settings_path", "settings_channels"]]

    for path, default in config_paths:
        saved_path = get_setting(path)
        if not saved_path and path == "librarypath":
            saved_path = search_library_path()
            if saved_path:
                set_setting(path, saved_path)

        if not saved_path:
            saved_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/" + default
            set_setting(path, saved_path)

        saved_path = xbmc.translatePath(saved_path)
        if not filetools.exists(saved_path):
            logger.debug("Creating %s: %s" % (path, saved_path))
            filetools.mkdir(saved_path)

        # Biblioteca
        if path == "librarypath":
            set_setting("library_version", "v4")
Example #7
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)
Example #8
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
Example #9
0
def save_library_tvshow(item, episodelist):
    """
    guarda en la libreria de series la serie con todos los capitulos incluidos en la lista episodelist
    @type item: item
    @param item: item que representa la serie a guardar
    @type episodelist: list
    @param episodelist: listado de items que representan los episodios que se van a guardar.
    @rtype insertados: int
    @return:  el número de episodios insertados
    @rtype sobreescritos: int
    @return:  el número de episodios sobreescritos
    @rtype fallidos: int
    @return:  el número de episodios fallidos o -1 si ha fallado toda la serie
    """
    logger.info()
    # logger.debug(item.tostring('\n'))
    path = ""

    # Si llegados a este punto no tenemos titulo o tmdb_id, salimos
    if not (item.contentSerieName or item.infoLabels['tmdb_id']) or not item.channel:
        logger.debug("NO ENCONTRADO contentSerieName NI tmdb_id")
        return 0, 0, -1  # Salimos sin guardar

    # TODO configurar para segun el scraper se llame a uno u otro
    scraper_return = scraper.find_and_set_infoLabels(item)

    # Llegados a este punto podemos tener:
    #  scraper_return = True: Un item con infoLabels con la información actualizada de la serie
    #  scraper_return = False: Un item sin información de la peli (se ha dado a cancelar en la ventana)
    #  item.infoLabels['code'] == "" : No se ha encontrado el identificador de IMDB necesario para continuar, salimos
    if not scraper_return or not item.infoLabels['code']:
        # TODO de momento si no hay resultado no añadimos nada,
        # aunq podriamos abrir un cuadro para introducir el identificador/nombre a mano
        logger.debug("NO ENCONTRADO EN SCRAPER O NO TIENE IMDB_ID")
        return 0, 0, -1

    _id = item.infoLabels['code']
    if config.get_setting("original_title_folder", "biblioteca") == 1 and item.infoLabels['originaltitle']:
        base_name = item.infoLabels['originaltitle']
    elif item.infoLabels['title']:
        base_name = item.infoLabels['title']
    else:
        base_name = item.contentSerieName

    base_name = filetools.validate_path(base_name).lower()

    for raiz, subcarpetas, ficheros in filetools.walk(TVSHOWS_PATH):
        for c in subcarpetas:
            if c.endswith("[%s]" % _id):
                path = filetools.join(raiz, c)
                break

    if not path:
        path = filetools.join(TVSHOWS_PATH, ("%s [%s]" % (base_name, _id)).strip())
        logger.info("Creando directorio serie: " + path)
        try:
            filetools.mkdir(path)
        except OSError, exception:
            if exception.errno != errno.EEXIST:
                raise
Example #10
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])
Example #11
0
def verify_directories_created():
    from platformcode import logger
    from core import filetools

    config_paths = [["videolibrarypath", "library"],
                    ["downloadpath", "downloads"],
                    ["downloadlistpath", "downloads/list"],
                    ["bookmarkpath", "favorites"],
                    ["settings_path", "settings_channels"]]

    for path, default in config_paths:
        saved_path = get_setting(path)
        if not saved_path:
            saved_path = filetools.join(get_data_path(), *default.split("/"))
            set_setting(path, saved_path)

        if not filetools.exists(saved_path):
            logger.debug("Creating %s: %s" % (path, saved_path))
            filetools.mkdir(saved_path)

    config_paths = [["folder_movies", "CINE"], ["folder_tvshows", "SERIES"]]

    for path, default in config_paths:
        saved_path = get_setting(path)

        if not saved_path:
            saved_path = default
            set_setting(path, saved_path)

        content_path = filetools.join(get_videolibrary_path(), saved_path)
        if not filetools.exists(content_path):
            logger.debug("Creating %s: %s" % (path, content_path))

            # si se crea el directorio
            filetools.mkdir(content_path)
Example #12
0
def get_server_setting(name, server, default=None):
    """
        Retorna el valor de configuracion del parametro solicitado.

        Devuelve el valor del parametro 'name' en la configuracion propia del servidor 'server'.

        Busca en la ruta \addon_data\plugin.video.addon\settings_servers el archivo server_data.json y lee
        el valor del parametro 'name'. Si el archivo server_data.json no existe busca en la carpeta servers el archivo 
        server.json y crea un archivo server_data.json antes de retornar el valor solicitado. Si el parametro 'name'
        tampoco existe en el el archivo server.json se devuelve el parametro default.


        @param name: nombre del parametro
        @type name: str
        @param server: nombre del servidor
        @type server: str
        @param default: valor devuelto en caso de que no exista el parametro name
        @type default: any

        @return: El valor del parametro 'name'
        @rtype: any

        """
    # Creamos la carpeta si no existe
    if not filetools.exists(
            filetools.join(config.get_data_path(), "settings_servers")):
        filetools.mkdir(
            filetools.join(config.get_data_path(), "settings_servers"))

    file_settings = filetools.join(config.get_data_path(), "settings_servers",
                                   server + "_data.json")
    dict_settings = {}
    dict_file = {}
    if filetools.exists(file_settings):
        # Obtenemos configuracion guardada de ../settings/channel_data.json
        try:
            dict_file = jsontools.load(filetools.read(file_settings))
            if isinstance(dict_file, dict) and 'settings' in dict_file:
                dict_settings = dict_file['settings']
        except EnvironmentError:
            logger.info("ERROR al leer el archivo: %s" % file_settings)

    if not dict_settings or name not in dict_settings:
        # Obtenemos controles del archivo ../servers/server.json
        try:
            list_controls, default_settings = get_server_controls_settings(
                server)
        except:
            default_settings = {}
        if name in default_settings:  # Si el parametro existe en el server.json creamos el server_data.json
            default_settings.update(dict_settings)
            dict_settings = default_settings
            dict_file['settings'] = dict_settings
            # Creamos el archivo ../settings/channel_data.json
            if not filetools.write(file_settings, jsontools.dump(dict_file)):
                logger.info("ERROR al salvar el archivo: %s" % file_settings)

    # Devolvemos el valor del parametro local 'name' si existe, si no se devuelve default
    return dict_settings.get(name, default)
Example #13
0
def get_server_setting(name, server, default=None):
    """
        Returns the configuration value of the requested parameter.

        Returns the value of the parameter 'name' in the own configuration of the server 'server'.

        Look in the path \addon_data\plugin.video.addon\settings_servers for the file server_data.json and read
        the value of the parameter 'name'. If the server_data.json file does not exist look in the servers folder for the file
        server.json and create a server_data.json file before returning the requested value. If the parameter 'name'
        also does not exist in the server.json file the default parameter is returned.


        @param name: parameter name
        @type name: str
        @param server: server name
        @type server: str
        @param default: return value in case the name parameter does not exist
        @type default: any

        @return: The parameter value 'name'
        @rtype: any

        """
    # We create the folder if it does not exist
    if not filetools.exists(
            filetools.join(config.get_data_path(), "settings_servers")):
        filetools.mkdir(
            filetools.join(config.get_data_path(), "settings_servers"))

    file_settings = filetools.join(config.get_data_path(), "settings_servers",
                                   server + "_data.json")
    dict_settings = {}
    dict_file = {}
    if filetools.exists(file_settings):
        # We get saved configuration from ../settings/channel_data.json
        try:
            dict_file = jsontools.load(filetools.read(file_settings))
            if isinstance(dict_file, dict) and 'settings' in dict_file:
                dict_settings = dict_file['settings']
        except EnvironmentError:
            logger.info("ERROR when reading the file: %s" % file_settings)

    if not dict_settings or name not in dict_settings:
        # We get controls from the file ../servers/server.json
        try:
            list_controls, default_settings = get_server_controls_settings(
                server)
        except:
            default_settings = {}
        if name in default_settings:  # If the parameter exists in the server.json we create the server_data.json
            default_settings.update(dict_settings)
            dict_settings = default_settings
            dict_file['settings'] = dict_settings
            # We create the file ../settings/channel_data.json
            if not filetools.write(file_settings, jsontools.dump(dict_file)):
                logger.info("ERROR saving file: %s" % file_settings)

    # We return the value of the local parameter 'name' if it exists, if default is not returned
    return dict_settings.get(name, default)
Example #14
0
def set_channel_setting(name, value, channel):
    from core import filetools
    """
    Sets the configuration value of the indicated parameter.

    Set 'value' as the value of the parameter 'name' in the own configuration of the channel 'channel'.
    Returns the changed value or None if the assignment could not be completed.

    If the name of the channel is specified, search in the path \addon_data\plugin.video.kod\settings_channels the
    channel_data.json file and set the parameter 'name' to the value indicated by 'value'.
    If the parameter 'name' does not exist, it adds it, with its value, to the corresponding file.

    @param name: parameter name
    @type name: str
    @param value: parameter value
    @type value: str
    @param channel: channel name
    @type channel: str

    @return: 'value' if the value could be set and None otherwise
    @rtype: str, None

    """
    # We create the folder if it does not exist
    if not filetools.exists(
            filetools.join(config.get_data_path(), "settings_channels")):
        filetools.mkdir(
            filetools.join(config.get_data_path(), "settings_channels"))

    file_settings = filetools.join(config.get_data_path(), "settings_channels",
                                   channel + "_data.json")
    dict_settings = {}

    dict_file = None

    if filetools.exists(file_settings):
        # We get saved settings from ../settings/channel_data.json
        try:
            dict_file = jsontools.load(filetools.read(file_settings))
            dict_settings = dict_file.get('settings', {})
        except EnvironmentError:
            logger.error("ERROR when reading the file: %s" % file_settings)

    dict_settings[name] = value

    # we check if dict_file exists and it is a dictionary, if not we create it
    if dict_file is None or not dict_file:
        dict_file = {}

    dict_file['settings'] = dict_settings

    # Creamos el archivo ../settings/channel_data.json
    json_data = jsontools.dump(dict_file)
    if not filetools.write(file_settings, json_data, silent=True):
        logger.error("ERROR saving file: %s" % file_settings)
        return None

    return value
Example #15
0
def set_channel_setting(name, value, channel):
    from core import filetools
    """
    Fija el valor de configuracion del parametro indicado.

    Establece 'value' como el valor del parametro 'name' en la configuracion propia del canal 'channel'.
    Devuelve el valor cambiado o None si la asignacion no se ha podido completar.

    Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.kod\settings_channels el
    archivo channel_data.json y establece el parametro 'name' al valor indicado por 'value'.
    Si el parametro 'name' no existe lo añade, con su valor, al archivo correspondiente.

    @param name: nombre del parametro
    @type name: str
    @param value: valor del parametro
    @type value: str
    @param channel: nombre del canal
    @type channel: str

    @return: 'value' en caso de que se haya podido fijar el valor y None en caso contrario
    @rtype: str, None

    """
    # Creamos la carpeta si no existe
    if not filetools.exists(
            filetools.join(config.get_data_path(), "settings_channels")):
        filetools.mkdir(
            filetools.join(config.get_data_path(), "settings_channels"))

    file_settings = filetools.join(config.get_data_path(), "settings_channels",
                                   channel + "_data.json")
    dict_settings = {}

    dict_file = None

    if filetools.exists(file_settings):
        # Obtenemos configuracion guardada de ../settings/channel_data.json
        try:
            dict_file = jsontools.load(filetools.read(file_settings))
            dict_settings = dict_file.get('settings', {})
        except EnvironmentError:
            logger.error("ERROR al leer el archivo: %s" % file_settings)

    dict_settings[name] = value

    # comprobamos si existe dict_file y es un diccionario, sino lo creamos
    if dict_file is None or not dict_file:
        dict_file = {}

    dict_file['settings'] = dict_settings

    # Creamos el archivo ../settings/channel_data.json
    json_data = jsontools.dump(dict_file)
    if not filetools.write(file_settings, json_data, silent=True):
        logger.error("ERROR al salvar el archivo: %s" % file_settings)
        return None

    return value
Example #16
0
def download_thumb(filename, url):
    lock = threading.Lock()
    lock.acquire()
    folder = filetools.join(config.get_data_path(), 'thumbs_kbagi')
    if not filetools.exists(folder):
        filetools.mkdir(folder)
    lock.release()
    if not filetools.exists(filename):
        downloadtools.downloadfile(url, filename, silent=True)
    return filename
Example #17
0
def rename(File):
    jsonPath = xbmc.translatePath(config.get_setting('downloadlistpath'))
    json = jsontools.load(open(filetools.join(jsonPath, File), "r").read())
    filePath = filetools.join(xbmc.translatePath(config.get_setting('downloadpath')), json['downloadFilename'])

    if json['infoLabels']['mediatype'] == 'movie':
        if filetools.isdir(filePath):
            extension = ''
            files = filetools.listdir(filePath)
            oldName = json['downloadFilename']
            newName = json['backupFilename']
            for f in files:
                ext = os.path.splitext(f)[-1]
                if ext in extensions_list: extension = ext
                filetools.rename(filetools.join(filePath, f), f.replace(oldName, newName))
            filetools.rename(filePath, newName)
            jsontools.update_node(filetools.join(newName, newName + extension), File, 'downloadFilename', jsonPath)

        else:
            oldName = json['downloadFilename']
            newName = json['backupFilename'] + os.path.splitext(oldName)[-1]
            filetools.rename(filePath, newName)
            jsontools.update_node(newName, File, 'downloadFilename', jsonPath)
    else:
        sep = '/' if filePath.lower().startswith("smb://") else os.sep
        FolderName = json['backupFilename'].split(sep)[0]
        Title = re.sub(r'(\s*\[[^\]]+\])', '', FolderName)
        if filetools.isdir(filePath):
            files = filetools.listdir(filePath)
            file_dict = {}
            for f in files:
                title = process_filename(f, Title, ext=False)
                ext = os.path.splitext(f)[-1]
                name = os.path.splitext(f)[0]
                if title not in file_dict and ext in extensions_list:
                    file_dict[title] = name

            for title, name in file_dict.items():
                for f in files:
                    if name in f:
                        filetools.rename(filetools.join(filePath, f), f.replace(name, title))

            filetools.rename(filePath, FolderName)
            jsontools.update_node(FolderName, File, 'downloadFilename', jsonPath)
        else:
            filename = filetools.split(filePath)[-1]
            title = process_filename(filename, Title)
            NewFolder = filetools.join(config.get_setting('downloadpath'), FolderName)
            if not filetools.isdir(NewFolder):
                filetools.mkdir(NewFolder)
            from_folder = filetools.join(config.get_setting('downloadpath'), filename)
            to_folder = filetools.join(config.get_setting('downloadpath'), FolderName, title)
            filetools.move(from_folder, to_folder)
            jsontools.update_node(filetools.join(FolderName, title), File, 'downloadFilename', jsonPath)
Example #18
0
def create_tvshows_from_xml():
    logger.info("pelisalacarta.platformcode.library_service create_tvshows_from_xml")

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

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

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

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

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

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

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

                        library.save_library_tvshow(serie, list())

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

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

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

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

        return True

    return False
def verify_directories_created():
    from core import logger
    from core import filetools
    from platformcode import xbmc_library

    config_paths = [["librarypath",      "library"],
                    ["downloadpath",     "downloads"],
                    ["downloadlistpath", "downloads/list"],
                    ["settings_path",    "settings_channels"]]

    for path, default in config_paths:
        saved_path = get_setting(path)

        # Biblioteca
        if path == "librarypath":
            set_setting("library_version", "v4")
            if not saved_path:
                saved_path = xbmc_library.search_library_path()
                if saved_path:
                    set_setting(path, saved_path)

        if not saved_path:
            saved_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/" + default
            set_setting(path, saved_path)


        if get_setting("library_set_content")== "true" and path in ["librarypath","downloadpath"]:
            xbmc_library.add_sources(saved_path)

        saved_path = xbmc.translatePath(saved_path)
        if not filetools.exists(saved_path):
            logger.debug("Creating %s: %s" % (path, saved_path))
            filetools.mkdir(saved_path)


    config_paths = [["folder_movies", "CINE"],
                    ["folder_tvshows", "SERIES"]]

    for path, default in config_paths:
        saved_path = get_setting(path)

        if not saved_path:
            saved_path = default
            set_setting(path, saved_path)

        content_path = filetools.join(get_library_path(), saved_path)
        if not filetools.exists(content_path):
            logger.debug("Creating %s: %s" % (path, content_path))
            if filetools.mkdir(content_path) and get_setting("library_set_content")== "true":
                xbmc_library.set_content(default)

        elif get_setting("library_ask_set_content") == "active":
            xbmc_library.set_content(default)
Example #20
0
def create_tvshows_from_xml():
    logger.info("streamondemand.platformcode.library_service create_tvshows_from_xml")

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

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

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

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

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

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

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

                        library.save_library_tvshow(serie, list())

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

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

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

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

        return True

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

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

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

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

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

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

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

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

                        library.save_library_tvshow(serie, list())

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

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

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

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

        return True

    return False
Example #22
0
def download_from_url(url, item):
    logger.info("Intentando descargar: %s" % (url))
    if url.lower().endswith(".m3u8") or url.lower().startswith("rtmp"):
        save_server_statistics(item.server, 0, False)
        return {"downloadStatus": STATUS_CODES.error}

    # Obtenemos la ruta de descarga y el nombre del archivo
    item.downloadFilename = item.downloadFilename.replace('/','-')
    download_path = filetools.dirname(filetools.join(DOWNLOAD_PATH, item.downloadFilename))
    file_name = filetools.basename(filetools.join(DOWNLOAD_PATH, item.downloadFilename))

    # Creamos la carpeta si no existe

    if not filetools.exists(download_path):
        filetools.mkdir(download_path)

    # Lanzamos la descarga
    d = Downloader(url, download_path, file_name,
                   max_connections=1 + int(config.get_setting("max_connections", "downloads")),
                   block_size=2 ** (17 + int(config.get_setting("block_size", "downloads"))),
                   part_size=2 ** (20 + int(config.get_setting("part_size", "downloads"))),
                   max_buffer=2 * int(config.get_setting("max_buffer", "downloads")))
    d.start_dialog(config.get_localized_string(60332))

    # Descarga detenida. Obtenemos el estado:
    # Se ha producido un error en la descarga   
    if d.state == d.states.error:
        logger.info("Error al intentar descargar %s" % (url))
        status = STATUS_CODES.error

    # La descarga se ha detenifdo
    elif d.state == d.states.stopped:
        logger.info("Descarga detenida")
        status = STATUS_CODES.canceled

    # La descarga ha finalizado
    elif d.state == d.states.completed:
        logger.info("Descargado correctamente")
        status = STATUS_CODES.completed

        if item.downloadSize and item.downloadSize != d.size[0]:
            status = STATUS_CODES.error

    save_server_statistics(item.server, d.speed[0], d.state != d.states.error)

    dir = os.path.dirname(item.downloadFilename)
    file = filetools.join(dir, d.filename)

    if status == STATUS_CODES.completed:
        move_to_libray(item.clone(downloadFilename=file))

    return {"downloadUrl": d.download_url, "downloadStatus": status, "downloadSize": d.size[0],
            "downloadProgress": d.progress, "downloadCompleted": d.downloaded[0], "downloadFilename": file}
def create_tvshows_from_xml():
    logger.info("pelisalacarta.platformcode.library_service create_tvshows_from_xml")

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

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

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

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

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

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

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

                        library.save_library_tvshow(serie, list())

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

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

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

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

        return True

    return False
def verify_directories_created():
    from core import logger
    from core import filetools
    from platformcode import xbmc_library

    config_paths = [["librarypath", "library"], ["downloadpath", "downloads"],
                    ["downloadlistpath", "downloads/list"],
                    ["settings_path", "settings_channels"]]

    for path, default in config_paths:
        saved_path = get_setting(path)

        # Biblioteca
        if path == "librarypath":
            set_setting("library_version", "v4")
            if not saved_path:
                saved_path = xbmc_library.search_library_path()
                if saved_path:
                    set_setting(path, saved_path)

        if not saved_path:
            saved_path = "special://profile/addon_data/plugin.video." + PLUGIN_NAME + "/" + default
            set_setting(path, saved_path)

        if get_setting("library_set_content") == "true" and path in [
                "librarypath", "downloadpath"
        ]:
            xbmc_library.add_sources(saved_path)

        saved_path = xbmc.translatePath(saved_path)
        if not filetools.exists(saved_path):
            logger.debug("Creating %s: %s" % (path, saved_path))
            filetools.mkdir(saved_path)

    config_paths = [["folder_movies", "CINE"], ["folder_tvshows", "SERIES"]]

    for path, default in config_paths:
        saved_path = get_setting(path)

        if not saved_path:
            saved_path = default
            set_setting(path, saved_path)

        content_path = filetools.join(get_library_path(), saved_path)
        if not filetools.exists(content_path):
            logger.debug("Creating %s: %s" % (path, content_path))
            if filetools.mkdir(content_path) and get_setting(
                    "library_set_content") == "true":
                xbmc_library.set_content(default)

        elif get_setting("library_ask_set_content") == "active":
            xbmc_library.set_content(default)
Example #25
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()
Example #26
0
def import_videolibrary(item):
    logger.info()

    zip_file = unicode(
        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):
        shutil.rmtree(temp_path)
    filetools.mkdir(videolibrary_temp_path)

    unzip(videolibrary_temp_path, zip_file)
    p_dialog.update(20)

    if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
        xbmc_videolibrary.clean()
    p_dialog.update(30)
    shutil.rmtree(videolibrary_movies_path)
    shutil.rmtree(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)
    shutil.rmtree(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()
Example #27
0
def download_thumb(filename, url):
    from core import downloadtools

    lock = threading.Lock()
    lock.acquire()
    folder = filetools.join(config.get_data_path(), 'thumbs_copiapop')
    if not filetools.exists(folder):
        filetools.mkdir(folder)
    lock.release()

    if not filetools.exists(filename):
        downloadtools.downloadfile(url, filename, silent=True)

    return filename
Example #28
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])
Example #29
0
def savecurrenthash(_hash, file):
    if " OR " in _hash:
        _hash = _hash.split(" OR ", 1)[0]

    _hash = unicode(_hash, "utf-8", errors="replace").encode("utf-8")
    media_dict = {"hash": _hash}

    if not filetools.exists(file):
        if not filetools.exists(
                filetools.join(config.get_data_path(), 'matchcenter')):
            filetools.mkdir(
                filetools.join(config.get_data_path(), 'matchcenter'))
    filetools.write(file, jsontools.dump_json(media_dict))
    return
Example #30
0
def set_server_setting(name, value, server):
    global alfa_caching, alfa_servers
    # Creamos la carpeta si no existe
    if not filetools.exists(
            filetools.join(config.get_data_path(), "settings_servers")):
        filetools.mkdir(
            filetools.join(config.get_data_path(), "settings_servers"))

    file_settings = filetools.join(config.get_data_path(), "settings_servers",
                                   server + "_data.json")
    dict_settings = {}

    dict_file = None

    if kodi:
        alfa_caching = bool(window.getProperty("alfa_caching"))
        alfa_servers = json.loads(window.getProperty("alfa_servers"))
    if alfa_caching and alfa_servers.get(server):
        dict_settings = alfa_servers[server].copy()

    elif filetools.exists(file_settings):
        # Obtenemos configuracion guardada de ../settings/channel_data.json
        try:
            dict_file = jsontools.load(filetools.read(file_settings))
            dict_settings = dict_file.get('settings', {})
        except EnvironmentError:
            logger.info("ERROR al leer el archivo: %s" % file_settings)

    dict_settings[name] = value
    if alfa_caching:
        alfa_caching = bool(window.getProperty("alfa_caching"))
        if alfa_caching:
            alfa_servers[server] = dict_settings.copy()
            window.setProperty("alfa_servers", json.dumps(alfa_servers))
        else:
            alfa_servers = {}
            window.setProperty("alfa_servers", json.dumps(alfa_servers))

    # comprobamos si existe dict_file y es un diccionario, sino lo creamos
    if dict_file is None or not dict_file:
        dict_file = {}

    dict_file['settings'] = dict_settings

    # Creamos el archivo ../settings/channel_data.json
    if not filetools.write(file_settings, jsontools.dump(dict_file)):
        logger.info("ERROR al salvar el archivo: %s" % file_settings)
        return None

    return value
def save_library_tvshow(item, episodelist):
    """
    guarda en la libreria de series la serie con todos los capitulos incluidos en la lista episodelist
    @type item: item
    @param item: item que representa la serie a guardar
    @type episodelist: list
    @param episodelist: listado de items que representan los episodios que se van a guardar.
    @rtype insertados: int
    @return:  el número de episodios insertados
    @rtype sobreescritos: int
    @return:  el número de episodios sobreescritos
    @rtype fallidos: int
    @return:  el número de episodios fallidos o -1 si ha fallado toda la serie
    """
    logger.info("streamondemand.platformcode.library save_library_tvshow")

    # Itentamos obtener el titulo correcto:
    # 1. contentSerieName: Este deveria ser el sitio correcto
    # 2. show
    titulo = item.contentSerieName
    if not titulo:
        titulo = item.show

    # Colocamos el titulo en su sitio para que tmdb lo localize
    item.contentSerieName = titulo
    # establecemos "active" para que se actualice cuando se llame a library_service
    item.active = True

    # Si llegados a este punto no tenemos titulo, salimos
    if not item.contentSerieName or not item.channel:
        return 0, 0, -1  # Salimos sin guardar

    # TODO configurar para segun el scraper se llame a uno u otro
    tmdb.find_and_set_infoLabels_tmdb(
        item,
        config.get_setting("scrap_ask_name") == "true")

    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
Example #32
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(20)

    if config.is_xbmc() and config.get_setting("videolibrary_kodi"):
        xbmc_videolibrary.clean()
    p_dialog.update(30)
    filetools.rmdirtree(videolibrarytools.MOVIES_PATH)
    filetools.rmdirtree(videolibrarytools.TVSHOWS_PATH)
    p_dialog.update(50)

    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(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()
def save_library_tvshow(item, episodelist):
    """
    guarda en la libreria de series la serie con todos los capitulos incluidos en la lista episodelist
    @type item: item
    @param item: item que representa la serie a guardar
    @type episodelist: list
    @param episodelist: listado de items que representan los episodios que se van a guardar.
    @rtype insertados: int
    @return:  el número de episodios insertados
    @rtype sobreescritos: int
    @return:  el número de episodios sobreescritos
    @rtype fallidos: int
    @return:  el número de episodios fallidos o -1 si ha fallado toda la serie
    """
    logger.info("streamondemand.platformcode.library save_library_tvshow")

    # Itentamos obtener el titulo correcto:
    # 1. contentSerieName: Este deveria ser el sitio correcto
    # 2. show
    titulo = item.contentSerieName
    if not titulo:
        titulo = item.show

    # Colocamos el titulo en su sitio para que tmdb lo localize
    item.contentSerieName = titulo
    # establecemos "active" para que se actualice cuando se llame a library_service
    item.active = True

    # Si llegados a este punto no tenemos titulo, salimos
    if not item.contentSerieName or not item.channel:
        return 0, 0, -1  # Salimos sin guardar

    # TODO configurar para segun el scraper se llame a uno u otro
    tmdb.find_and_set_infoLabels_tmdb(item, config.get_setting("scrap_ask_name") == "true")

    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
Example #34
0
def copy_file(item):
    logger.info()
    from core import filetools

    MIS_TORRENT_FOLDER = filetools.join(
        config.get_setting('downloadpath', default=''), 'Mis_Torrents')
    MIS_TORRENT_BTDIGG_FOLDER = filetools.join(MIS_TORRENT_FOLDER,
                                               'BTDigg - resultados')

    if not filetools.exists(MIS_TORRENT_BTDIGG_FOLDER):
        filetools.mkdir(MIS_TORRENT_BTDIGG_FOLDER)

    path = filetools.join(MIS_TORRENT_BTDIGG_FOLDER,
                          filetools.validate_path(item.copytitle) + '.magnet')
    filetools.write(path, item.url, silent=True)

    platformtools.dialog_notification(
        'Copiando MAGNET',
        filetools.validate_path(item.copytitle) + '.magnet')
Example #35
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)
Example #36
0
def verify_directories_created():
    from core import logger
    from core import filetools

    config_paths = [["librarypath", "library"], ["downloadpath", "downloads"],
                    ["downloadlistpath", "downloads/list"],
                    ["bookmarkpath", "favorites"],
                    ["settings_path", "settings_channels"]]

    for path, default in config_paths:
        saved_path = get_setting(path)
        if not saved_path:
            saved_path = filetools.join(get_data_path(), *default.split("/"))
            set_setting(path, saved_path)

        if not filetools.exists(saved_path):
            logger.debug("Creating %s: %s" % (path, saved_path))
            filetools.mkdir(saved_path)

            #Biblioteca
            if path == "librarypath":
                set_setting("library_version", "v4")
Example #37
0
    def extract(self, file, dir, folder_to_extract="", overwrite_question=False, backup=False):
        logger.info("file= %s" % file)
        logger.info("dir= %s" % dir)

        if not dir.endswith(':') and not filetools.exists(dir):
            filetools.mkdir(dir)

        zf = zipfile.ZipFile(filetools.file_open(file, vfs=False))
        if not folder_to_extract:
            self._createstructure(file, dir)
        num_files = len(zf.namelist())

        for nameo in zf.namelist():
            name = nameo.replace(':', '_').replace('<', '_').replace('>', '_').replace('|', '_').replace('"', '_').replace('?', '_').replace('*', '_')
            logger.info("name=%s" % nameo)
            if not name.endswith('/'):
                logger.info("it's not a directory")
                try:
                    (path, filename) = filetools.split(filetools.join(dir, name))
                    logger.info("path=%s" % path)
                    logger.info("name=%s" % name)
                    if folder_to_extract:
                        if path != filetools.join(dir, folder_to_extract):
                            break
                    else:
                        filetools.mkdir(path)
                except:
                    pass
                if folder_to_extract:
                    outfilename = filetools.join(dir, filename)

                else:
                    outfilename = filetools.join(dir, name)
                logger.info("outfilename=%s" % outfilename)
                try:
                    if filetools.exists(outfilename) and overwrite_question:
                        from platformcode import platformtools
                        dyesno = platformtools.dialog_yesno("File already exists "," File %s to unzip already exists, do you want to overwrite it?" % filetools.basename(outfilename))
                        if not dyesno:
                            break
                        if backup:
                            import time
                            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):
                                filetools.mkdir(backup)
                            filetools.copy(outfilename, filetools.join(backup, filetools.basename(outfilename)))

                    if not filetools.write(outfilename, zf.read(nameo), silent=True, vfs=VFS):  #TRUNCA en FINAL en Kodi 19 con VFS
                        logger.error("File error " + nameo)
                except:
                    import traceback
                    logger.error(traceback.format_exc())
                    logger.error("File error " + nameo)

        try:
            zf.close()
        except:
            logger.info("Error closing .zip " + file)
Example #38
0
def verify_directories_created():
    from core import logger
    from core import filetools

    config_paths = [["librarypath",      "library"],
                    ["downloadpath",     "downloads"],
                    ["downloadlistpath", "downloads/list"],
                    ["settings_path",    "settings_channels"]]

    for path, default in config_paths:
        saved_path = get_setting(path)
        if not saved_path:
            saved_path = "special://profile/plugin_data/video/pelisalacarta/" + default
            set_setting(path, saved_path)

        saved_path = xbmc.translatePath(saved_path)
        if not filetools.exists(saved_path):
            logger.debug("Creating %s: %s" % (path, saved_path))
            filetools.mkdir(saved_path)

        # Biblioteca
        if path == "librarypath":
            set_setting("library_version", "v4")
Example #39
0
def verify_directories_created():
    from core import logger
    from core import filetools

    config_paths = [["librarypath",      "library"],
                    ["downloadpath",     "downloads"],
                    ["downloadlistpath", "downloads/list"],
                    ["bookmarkpath",     "favorites"],
                    ["settings_path",    "settings_channels"]]
    
    
    for path, default in config_paths:
      saved_path = get_setting(path)
      if not saved_path:
        saved_path = filetools.join(get_data_path() , *default.split("/"))
        set_setting(path, saved_path)

      if not filetools.exists(saved_path): 
        logger.debug("Creating %s: %s" % (path, saved_path))
        filetools.mkdir(saved_path)
        
        #Biblioteca
        if path == "librarypath":
          set_setting("library_version", "v4")
# Make sure "Allow control of XBMC via HTTP" is set to ON in Settings ->
# Services -> Webserver
xbmc_host = config.get_setting("xbmc_host")
# Configured in Settings -> Services -> Webserver -> Port
xbmc_port = int(config.get_setting("xbmc_port"))
# Base URL of the json RPC calls. For GET calls we append a "request" URI
# parameter. For POSTs, we add the payload as JSON the the HTTP request body
xbmc_json_rpc_url = "http://" + xbmc_host + ":" + str(xbmc_port) + "/jsonrpc"

DEBUG = config.get_setting("debug")

FOLDER_LIBRARY = "/library" 
LIBRARY_PATH = xbmc.translatePath("special://profile/addon_data/plugin.video." + PLUGIN_NAME + FOLDER_LIBRARY)
if not filetools.exists(LIBRARY_PATH):
    logger.info("streamondemand.platformcode.library Library path doesn't exist:" + LIBRARY_PATH)
    filetools.mkdir(LIBRARY_PATH)

# TODO permitir cambiar las rutas y nombres en settings para 'cine' y 'series'
FOLDER_MOVIES = "CINE"  # config.get_localized_string(30072)
MOVIES_PATH = filetools.join(LIBRARY_PATH, FOLDER_MOVIES)
if not filetools.exists(MOVIES_PATH):
    logger.info("streamondemand.platformcode.library Movies path doesn't exist:" + MOVIES_PATH)
    filetools.mkdir(MOVIES_PATH)

FOLDER_TVSHOWS = "SERIES"  # config.get_localized_string(30073)
TVSHOWS_PATH = filetools.join(LIBRARY_PATH, FOLDER_TVSHOWS)
if not filetools.exists(TVSHOWS_PATH):
    logger.info("streamondemand.platformcode.library Tvshows path doesn't exist:" + TVSHOWS_PATH)
    filetools.mkdir(TVSHOWS_PATH)

TVSHOW_FILE = "series.json"
def establecer_contenido(content_type, silent=False):
    if config.is_xbmc():
        continuar = False
        msg_text = "Cartella Libreria personalizzata"

        librarypath = config.get_setting("librarypath")
        if librarypath == "":
            continuar = True
            if content_type == FOLDER_MOVIES:
                if not xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'):
                    if not silent:
                        # Preguntar si queremos instalar metadata.themoviedb.org
                        install = platformtools.dialog_yesno("The Movie Database",
                                                             "TheMovieDB. non presente.",
                                                             "Installare adesso?")
                    else:
                        install = True

                    if install:
                        try:
                            # Instalar metadata.themoviedb.org
                            xbmc.executebuiltin('xbmc.installaddon(metadata.themoviedb.org)', True)
                            logger.info("Instalado el Scraper de películas de TheMovieDB")
                        except:
                            pass

                    continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'))
                    if not continuar:
                        msg_text = "The Movie Database non installato."

            else: # SERIES
                # Instalar The TVDB
                if not xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'):
                    if not silent:
                        # Preguntar si queremos instalar metadata.tvdb.com
                        install = platformtools.dialog_yesno("The TVDB",
                                                             "The TVDB non presente.",
                                                             "Installare adesso?")
                    else:
                        install = True

                    if install:
                        try:
                            # Instalar metadata.tvdb.com
                            xbmc.executebuiltin('xbmc.installaddon(metadata.tvdb.com)', True)
                            logger.info("Instalado el Scraper de series de The TVDB")
                        except:
                            pass

                    continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'))

                    if not continuar:
                        msg_text = "The TVDB non installato."

                # Instalar TheMovieDB
                if continuar and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
                    continuar = False
                    if not silent:
                        # Preguntar si queremos instalar metadata.tvshows.themoviedb.org
                        install = platformtools.dialog_yesno("The Movie Database",
                                                             "TheMovieDB non presente.",
                                                             "Installare adesso?")
                    else:
                        install = True

                    if install:
                        try:
                            # Instalar metadata.tvshows.themoviedb.org
                            # 1º Probar desde el repositorio ...
                            xbmc.executebuiltin('xbmc.installaddon(metadata.tvshows.themoviedb.org)', True)
                            if not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
                                    # ...si no funciona descargar e instalar desde la web
                                    url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip"
                                    path_down = xbmc.translatePath(
                                        "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip")
                                    path_unzip = xbmc.translatePath("special://home/addons/")
                                    header = ("User-Agent",
                                              "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013")

                                    from core import downloadtools
                                    from core import ziptools

                                    downloadtools.downloadfile(url, path_down, continuar=True, headers=[header])
                                    unzipper = ziptools.ziptools()
                                    unzipper.extract(path_down, path_unzip)
                                    xbmc.executebuiltin('xbmc.UpdateLocalAddons')

                            strSettings = '<settings>\n' \
                                          '    <setting id="fanart" value="true" />\n' \
                                          '    <setting id="keeporiginaltitle" value="false" />\n' \
                                          '    <setting id="language" value="it" />\n' \
                                          '</settings>'
                            path_settings = xbmc.translatePath("special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml")
                            tv_themoviedb_addon_path = filetools.dirname(path_settings)
                            if not filetools.exists(tv_themoviedb_addon_path):
                                filetools.mkdir(tv_themoviedb_addon_path)
                            if filetools.write(path_settings,strSettings):
                                continuar = True
                        except:
                            pass

                    continuar = (install and continuar)
                    if not continuar:
                        msg_text = "The Movie Database non installato."

            idPath = 0
            idParentPath = 0
            strPath = ""
            if continuar:
                continuar = False
                librarypath = "special://home/userdata/addon_data/plugin.video." + config.PLUGIN_NAME + "/library/"

                # Buscamos el idPath
                sql = 'SELECT MAX(idPath) FROM path'
                nun_records, records = execute_sql_kodi(sql)
                if nun_records == 1:
                    idPath = records[0][0] + 1


                # Buscamos el idParentPath
                sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % \
                                            librarypath.replace('/profile/', '/%/').replace('/home/userdata/', '/%/')
                nun_records, records = execute_sql_kodi(sql)
                if nun_records == 1:
                    idParentPath = records[0][0]
                    librarypath = records[0][1]
                    continuar = True
                else:
                    # No existe librarypath en la BD: la insertamos
                    sql = 'INSERT INTO path (idPath, strPath,  scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \
                          '(%s, "%s", 0, 0, 0, 0)' % (idPath, librarypath)
                    nun_records, records = execute_sql_kodi(sql)
                    if nun_records == 1:
                        continuar = True
                        idParentPath = idPath
                        idPath += 1
                    else:
                        msg_text = "Impossibile impostare librarypath in BD"

            if continuar:
                continuar = False

                # Fijamos strContent, strScraper, scanRecursive y strSettings
                if content_type == FOLDER_MOVIES:
                    strContent = 'movies'
                    strScraper = 'metadata.themoviedb.org'
                    scanRecursive = 2147483647
                    strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \
                                  "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \
                                  "<setting id='language' value='it' /><setting id='tmdbcertcountry' value='us' />" \
                                  "<setting id='trailer' value='true' /></settings>"
                    strActualizar = "Configurare lo scraper per i film in italiano?"

                else:
                    strContent = 'tvshows'
                    strScraper = 'metadata.tvdb.com'
                    scanRecursive = 0
                    strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \
                                  "<setting id='absolutenumber' value='false' />" \
                                  "<setting id='dvdorder' value='false' />" \
                                  "<setting id='fallback' value='true' />" \
                                  "<setting id='fanart' value='true' />" \
                                  "<setting id='language' value='it' /></settings>"
                    strActualizar = "Configurare lo scraper per le serie in italiano?"

                # Fijamos strPath
                strPath = librarypath + content_type + "/"
                logger.info("%s: %s" % (content_type, strPath))

                # Comprobamos si ya existe strPath en la BD para evitar duplicados
                sql = 'SELECT idPath FROM path where strPath="%s"' % strPath
                nun_records, records = execute_sql_kodi(sql)
                sql = ""
                if nun_records == 0:
                    # Insertamos el scraper
                    sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \
                          'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, 0, ' \
                          '"%s", 0, 0, %s)' % (
                          idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath)
                else:
                    if not silent:
                        # Preguntar si queremos configurar themoviedb.org como opcion por defecto
                        actualizar = platformtools.dialog_yesno("The TVDB", strActualizar)
                    else:
                        actualizar = True

                    if actualizar:
                        # Actualizamos el scraper
                        idPath = records[0][0]
                        sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \
                              'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath)

                if sql:
                    nun_records, records = execute_sql_kodi(sql)
                    if nun_records == 1:
                        continuar = True

                if not continuar:
                    msg_text = "Error al configurar el scraper en la BD."

        if not continuar:
            heading = "Libreria non %s configurata" % content_type
            #msg_text = "Assicurarsi di aver installato l'add-on The Movie Database"
        elif content_type == FOLDER_TVSHOWS and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
            heading = "Libreria %s configurata" % content_type
            msg_text = "Kodi deve essere riavviato affinché le modifiche abbiano effetto."
        else:
            heading = "Libreria %s configurata" % content_type
            msg_text = "Complimenti la libreria di Kodi è stata configurata correttamente."
        platformtools.dialog_notification(heading, msg_text, icon=1, time=10000)
        logger.info("%s: %s" % (heading,msg_text))
def convert_old_to_v4():
    logger.info()
    path_series_xml = filetools.join(config.get_data_path(), "series.xml")
    path_series_json = filetools.join(config.get_data_path(), "series.json")
    series_insertadas = 0
    series_fallidas = 0
    version = 'v?'

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

    path_cine_old = filetools.join(library.LIBRARY_PATH, "CINE_OLD_" + new_name)
    if filetools.rename(library.MOVIES_PATH,  "CINE_OLD_" + new_name):
        if not filetools.mkdir(library.MOVIES_PATH):
            logger.error("ERROR, no se ha podido crear la nueva carpeta de CINE")
            return False
    else:
        logger.error("ERROR, no se ha podido renombrar la antigua carpeta de CINE")
        return False

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

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

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

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

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

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

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

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

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

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

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

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

        movies_insertadas = 0
        movies_fallidas = 0
        for raiz, subcarpetas, ficheros in filetools.walk(path_cine_old):
            for f in ficheros:
                if f.endswith(".strm.json"):
                    try:
                        movie = Item().fromjson(filetools.read(filetools.join(raiz, f)))
                        insertados, sobreescritos, fallidos = library.save_library_movie(movie)
                        if fallidos == 0:
                            movies_insertadas += 1
                            platformtools.dialog_notification("Película actualizada", movie.infoLabels['title'])
                        else:
                            movies_fallidas += 1
                    except:
                        movies_fallidas += 1

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

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

    # Por ultimo limpia la libreria, por que las rutas anteriores ya no existen
    if config.is_xbmc():
      from platformcode import xbmc_library
      xbmc_library.clean()

    return True
Example #43
0
def download_from_url(url, item):
    logger.info("pelisalacarta.channels.descargas download_from_url - Intentando descargar: %s" % (url))
    if url.lower().endswith(".m3u8") or url.lower().startswith("rtmp"):
      save_server_statistics(item.server, 0, False)
      return {"downloadStatus": STATUS_CODES.error}

    # Obtenemos la ruta de descarga y el nombre del archivo
    download_path = filetools.dirname(filetools.join(config.get_setting("downloadpath"), item.downloadFilename))
    file_name = filetools.basename(filetools.join(config.get_setting("downloadpath"), item.downloadFilename))

    # Creamos la carpeta si no existe
    if not filetools.exists(download_path):
        filetools.mkdir(download_path)

    # Mostramos el progreso
    progreso = platformtools.dialog_progress("Descargas", "Iniciando descarga...")

    # Lanzamos la descarga
    d = Downloader(url, filetools.encode(download_path), filetools.encode(file_name))
    d.start()

    # Monitorizamos la descarga hasta que se termine o se cancele
    while d.state == d.states.downloading and not progreso.iscanceled():
        time.sleep(0.1)
        line1 = "%s" % (filetools.decode(d.filename))
        line2 = "%.2f%% - %.2f %s de %.2f %s a %.2f %s/s (%d/%d)" % (
        d.progress, d.downloaded[1], d.downloaded[2], d.size[1], d.size[2], d.speed[1], d.speed[2], d.connections[0],
        d.connections[1])
        line3 = "Tiempo restante: %s" % (d.remaining_time)
        progreso.update(int(d.progress), line1, line2, line3)

    # Descarga detenida. Obtenemos el estado:
    # Se ha producido un error en la descarga
    if d.state == d.states.error:
        logger.info("pelisalacarta.channels.descargas download_video - Error al intentar descargar %s" % (url))
        d.stop()
        progreso.close()
        status = STATUS_CODES.error

    # Aun está descargando (se ha hecho click en cancelar)
    elif d.state == d.states.downloading:
        logger.info("pelisalacarta.channels.descargas download_video - Descarga detenida")
        d.stop()
        progreso.close()
        status = STATUS_CODES.canceled

    # La descarga ha finalizado
    elif d.state == d.states.completed:
        logger.info("pelisalacarta.channels.descargas download_video - Descargado correctamente")
        progreso.close()
        status = STATUS_CODES.completed

        if item.downloadSize and item.downloadSize != d.size[0]:
            status = STATUS_CODES.error

    
    save_server_statistics(item.server, d.speed[0], d.state != d.states.error)
    
    if progreso.iscanceled():
      status = STATUS_CODES.canceled
      
    dir = os.path.dirname(item.downloadFilename)
    file = filetools.join(dir, filetools.decode(d.filename))
    
    if status == STATUS_CODES.completed:
        move_to_libray(item.clone(downloadFilename =  file))
        
    return {"downloadUrl": d.download_url, "downloadStatus": status, "downloadSize": d.size[0],
            "downloadProgress": d.progress, "downloadCompleted": d.downloaded[0], "downloadFilename": file}
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)
def set_content(content_type, silent=False):
    """
    Procedimiento para auto-configurar la biblioteca de kodi con los valores por defecto
    @type content_type: str ('CINE' o 'SERIES')
    @param content_type: tipo de contenido para configurar, series o peliculas
    """
    if config.is_xbmc():
        continuar = True
        msg_text = ""
        librarypath = config.get_setting("librarypath")

        if content_type == 'CINE':
            if not xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'):
                if not silent:
                    # Preguntar si queremos instalar metadata.themoviedb.org
                    install = platformtools.dialog_yesno("The Movie Database",
                                                         "TheMovieDB non presente.",
                                                         "Installare ora?")
                else:
                    install = True

                if install:
                    try:
                        # Instalar metadata.themoviedb.org
                        xbmc.executebuiltin('xbmc.installaddon(metadata.themoviedb.org)', True)
                        logger.info("Instalado el Scraper de películas de TheMovieDB")
                    except:
                        pass

                continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.themoviedb.org)'))
                if not continuar:
                    msg_text = "The Movie Database no instalado."

        else: # SERIES
            # Instalar The TVDB
            if not xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'):
                if not silent:
                    # Preguntar si queremos instalar metadata.tvdb.com
                    install = platformtools.dialog_yesno("The TVDB",
                                                         "The TVDB non presente.",
                                                         "Installare ora?")
                else:
                    install = True

                if install:
                    try:
                        # Instalar metadata.tvdb.com
                        xbmc.executebuiltin('xbmc.installaddon(metadata.tvdb.com)', True)
                        logger.info("Instalado el Scraper de series de The TVDB")
                    except:
                        pass

                continuar = (install and xbmc.getCondVisibility('System.HasAddon(metadata.tvdb.com)'))
                if not continuar:
                    msg_text = "The TVDB no instalado."

            # Instalar TheMovieDB
            if continuar and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
                continuar = False
                if not silent:
                    # Preguntar si queremos instalar metadata.tvshows.themoviedb.org
                    install = platformtools.dialog_yesno("The Movie Database",
                                                         "TheMovieDB non presente.",
                                                         "Installare ora?")
                else:
                    install = True

                if install:
                    try:
                        # Instalar metadata.tvshows.themoviedb.org
                        # 1º Probar desde el repositorio ...
                        xbmc.executebuiltin('xbmc.installaddon(metadata.tvshows.themoviedb.org)', True)
                        if not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
                                # ...si no funciona descargar e instalar desde la web
                                url = "http://mirrors.kodi.tv/addons/jarvis/metadata.tvshows.themoviedb.org/metadata.tvshows.themoviedb.org-1.3.1.zip"
                                path_down = xbmc.translatePath(
                                    "special://home/addons/packages/metadata.tvshows.themoviedb.org-1.3.1.zip")
                                path_unzip = xbmc.translatePath("special://home/addons/")
                                header = ("User-Agent",
                                          "Kodi/15.2 (Windows NT 10.0; WOW64) App_Bitness/32 Version/15.2-Git:20151019-02e7013")

                                from core import downloadtools
                                from core import ziptools

                                downloadtools.downloadfile(url, path_down, continuar=True, headers=[header])
                                unzipper = ziptools.ziptools()
                                unzipper.extract(path_down, path_unzip)
                                xbmc.executebuiltin('UpdateLocalAddons')

                        strSettings = '<settings>\n' \
                                      '    <setting id="fanart" value="true" />\n' \
                                      '    <setting id="keeporiginaltitle" value="false" />\n' \
                                      '    <setting id="language" value="it" />\n' \
                                      '</settings>'
                        path_settings = xbmc.translatePath("special://profile/addon_data/metadata.tvshows.themoviedb.org/settings.xml")
                        tv_themoviedb_addon_path = filetools.dirname(path_settings)
                        if not filetools.exists(tv_themoviedb_addon_path):
                            filetools.mkdir(tv_themoviedb_addon_path)
                        if filetools.write(path_settings,strSettings):
                            continuar = True

                    except:
                        pass

                continuar = (install and continuar)
                if not continuar:
                    msg_text = "The Movie Database non installato."

        idPath = 0
        idParentPath = 0
        strPath = ""
        if continuar:
            continuar = False

            # Buscamos el idPath
            sql = 'SELECT MAX(idPath) FROM path'
            nun_records, records = execute_sql_kodi(sql)
            if nun_records == 1:
                idPath = records[0][0] + 1

            sql_librarypath = librarypath
            if sql_librarypath.startswith("special://"):
                sql_librarypath = sql_librarypath.replace('/profile/', '/%/').replace('/home/userdata/', '/%/')
                sep = '/'
            elif sql_librarypath.startswith("smb://"):
                sep = '/'
            else:
                sep = os.sep

            if not sql_librarypath.endswith(sep):
                sql_librarypath += sep

            # Buscamos el idParentPath
            sql = 'SELECT idPath, strPath FROM path where strPath LIKE "%s"' % sql_librarypath
            nun_records, records = execute_sql_kodi(sql)
            if nun_records == 1:
                idParentPath = records[0][0]
                librarypath = records[0][1][:-1]
                continuar = True
            else:
                # No existe librarypath en la BD: la insertamos
                sql_librarypath = librarypath
                if not sql_librarypath.endswith(sep):
                    sql_librarypath += sep

                sql = 'INSERT INTO path (idPath, strPath,  scanRecursive, useFolderNames, noUpdate, exclude) VALUES ' \
                      '(%s, "%s", 0, 0, 0, 0)' % (idPath, sql_librarypath)
                nun_records, records = execute_sql_kodi(sql)
                if nun_records == 1:
                    continuar = True
                    idParentPath = idPath
                    idPath += 1
                else:
                    msg_text = "Omesso di impostare LibraryPath in BD"

        if continuar:
            continuar = False

            # Fijamos strContent, strScraper, scanRecursive y strSettings
            if content_type == 'CINE':
                strContent = 'movies'
                strScraper = 'metadata.themoviedb.org'
                scanRecursive = 2147483647
                strSettings = "<settings><setting id='RatingS' value='TMDb' /><setting id='certprefix' value='Rated ' />" \
                              "<setting id='fanart' value='true' /><setting id='keeporiginaltitle' value='false' />" \
                              "<setting id='language' value='it' /><setting id='tmdbcertcountry' value='us' />" \
                              "<setting id='trailer' value='true' /></settings>"
                strActualizar = "Si desidera configurare questo scraper in italiano come opzione predefinita per i film ?"
                if not librarypath.endswith(sep):
                    librarypath += sep
                strPath = librarypath + config.get_setting("folder_movies") + sep
            else:
                strContent = 'tvshows'
                strScraper = 'metadata.tvdb.com'
                scanRecursive = 0
                strSettings = "<settings><setting id='RatingS' value='TheTVDB' />" \
                              "<setting id='absolutenumber' value='false' />" \
                              "<setting id='dvdorder' value='false' />" \
                              "<setting id='fallback' value='true' />" \
                              "<setting id='fanart' value='true' />" \
                              "<setting id='language' value='it' /></settings>"
                strActualizar = "Si desidera configurare questo scraper in italiano come opzione predefinita per le serie ?"
                if not librarypath.endswith(sep):
                    librarypath += sep
                strPath = librarypath + config.get_setting("folder_tvshows") + sep

            logger.info("%s: %s" % (content_type, strPath))
            # Comprobamos si ya existe strPath en la BD para evitar duplicados
            sql = 'SELECT idPath FROM path where strPath="%s"' % strPath
            nun_records, records = execute_sql_kodi(sql)
            sql = ""
            if nun_records == 0:
                # Insertamos el scraper
                sql = 'INSERT INTO path (idPath, strPath, strContent, strScraper, scanRecursive, useFolderNames, ' \
                      'strSettings, noUpdate, exclude, idParentPath) VALUES (%s, "%s", "%s", "%s", %s, 0, ' \
                      '"%s", 0, 0, %s)' % (
                      idPath, strPath, strContent, strScraper, scanRecursive, strSettings, idParentPath)
            else:
                if not silent:
                    # Preguntar si queremos configurar themoviedb.org como opcion por defecto
                    actualizar = platformtools.dialog_yesno("The TVDB", strActualizar)
                else:
                    actualizar = True

                if actualizar:
                    # Actualizamos el scraper
                    idPath = records[0][0]
                    sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \
                          'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath)

            if sql:
                nun_records, records = execute_sql_kodi(sql)
                if nun_records == 1:
                    continuar = True

            if not continuar:
                msg_text = "Omesso impostare LibraryPath in BD"


        if not continuar:
            heading = "Biblioteca %s no configurada" % content_type
        elif content_type == 'SERIES' and not xbmc.getCondVisibility('System.HasAddon(metadata.tvshows.themoviedb.org)'):
            heading = "Biblioteca %s configurata" % content_type
            msg_text = "Riavviare Kodi per attuare le modifiche."
        else:
            heading = "Biblioteca %s configurata" % content_type
            msg_text = "Libreria di Kodi configurata correttamente."
        platformtools.dialog_notification(heading, msg_text, icon=1, time=10000)
        logger.info("%s: %s" % (heading,msg_text))
Example #46
0
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("pelisalacarta.platformcode.library save_library_movie")
    # logger.debug(item.tostring('\n'))
    insertados = 0
    sobreescritos = 0
    fallidos = 0
    path = ""

    # Itentamos obtener el titulo correcto:
    # 1. contentTitle: Este deberia ser el sitio correcto, ya que title suele contener "Añadir a la biblioteca..."
    # 2. fulltitle
    # 3. title
    if not item.contentTitle:
        # Colocamos el titulo correcto en su sitio para que tmdb lo localize
        if item.fulltitle:
            item.contentTitle = item.fulltitle
        else:
            item.contentTitle = item.title

    # Si llegados a este punto no tenemos titulo, salimos
    if not item.contentTitle or not item.channel:
        logger.debug("NO ENCONTRADO contentTitle")
        return 0, 0, -1  # Salimos sin guardar

    # TODO configurar para segun el scraper se llamara a uno u otro
    tmdb_return = tmdb.find_and_set_infoLabels_tmdb(item)

    # Llegados a este punto podemos tener:
    #  tmdb_return = True: Un item con infoLabels con la información actualizada de la peli
    #  tmdb_return = False: Un item sin información de la peli (se ha dado a cancelar en la ventana)
    #  item.infoLabels['imdb_id'] == "" : No se ha encontrado el identificador de IMDB necesario para continuar, salimos
    if not tmdb_return or not item.infoLabels['imdb_id']:
        # TODO de momento si no hay resultado no añadimos nada,
        # aunq podriamos abrir un cuadro para introducir el identificador/nombre a mano
        logger.debug("NO ENCONTRADO EN TMDB O NO TIENE IMDB_ID")
        return 0, 0, -1

    _id = item.infoLabels['imdb_id']

    # progress dialog
    p_dialog = platformtools.dialog_progress('pelisalacarta', 'Añadiendo película...')

    base_name = filetools.text2filename(item.contentTitle)

    for raiz, subcarpetas, ficheros in filetools.walk(MOVIES_PATH):
        for c in subcarpetas:
            if c.endswith("[%s]" % _id):
                path = filetools.join(raiz, c)
                break

    if not path:
        # Crear carpeta
        path = filetools.join(MOVIES_PATH, ("%s [%s]" % (base_name, _id)).strip())
        logger.info("pelisalacarta.platformcode.library save_library_movie Creando directorio pelicula:" + path)
        try:
            filetools.mkdir(path)
        except OSError, exception:
            if exception.errno != errno.EEXIST:
                raise
Example #47
0
def save_library_tvshow(item, episodelist):
    """
    guarda en la libreria de series la serie con todos los capitulos incluidos en la lista episodelist
    @type item: item
    @param item: item que representa la serie a guardar
    @type episodelist: list
    @param episodelist: listado de items que representan los episodios que se van a guardar.
    @rtype insertados: int
    @return:  el número de episodios insertados
    @rtype sobreescritos: int
    @return:  el número de episodios sobreescritos
    @rtype fallidos: int
    @return:  el número de episodios fallidos o -1 si ha fallado toda la serie
    """
    logger.info("pelisalacarta.platformcode.library save_library_tvshow")
    # logger.debug(item.tostring('\n'))
    path = ""

    ''''# Itentamos obtener el titulo correcto:
    # 1. contentSerieName: Este deberia ser el sitio correcto
    # 2. show
    if not item.contentSerieName:
        # Colocamos el titulo en su sitio para que tmdb lo localize
        item.contentSerieName = item.show'''

    # Si llegados a este punto no tenemos titulo o tmdb_id, salimos
    if not (item.contentSerieName or item.infoLabels['tmdb_id']) or not item.channel:
        logger.debug("NO ENCONTRADO contentSerieName NI tmdb_id")
        return 0, 0, -1  # Salimos sin guardar

    # TODO configurar para segun el scraper se llame a uno u otro
    tmdb_return = tmdb.find_and_set_infoLabels_tmdb(item)

    # Llegados a este punto podemos tener:
    #  tmdb_return = True: Un item con infoLabels con la información actualizada de la serie
    #  tmdb_return = False: Un item sin información de la peli (se ha dado a cancelar en la ventana)
    #  item.infoLabels['imdb_id'] == "" : No se ha encontrado el identificador de IMDB necesario para continuar, salimos
    if not tmdb_return or not item.infoLabels['imdb_id']:
        # TODO de momento si no hay resultado no añadimos nada,
        # aunq podriamos abrir un cuadro para introducir el identificador/nombre a mano
        logger.debug("NO ENCONTRADO EN TMDB O NO TIENE IMDB_ID")
        return 0, 0, -1

    _id = item.infoLabels['imdb_id']
    if item.infoLabels['title']:
        base_name = item.infoLabels['title']
    else:
        base_name = item.contentSerieName

    base_name = filetools.text2filename(base_name)

    for raiz, subcarpetas, ficheros in filetools.walk(TVSHOWS_PATH):
        for c in subcarpetas:
            if c.endswith("[%s]" % _id):
                path = filetools.join(raiz, c)
                break

    if not path:
        path = filetools.join(TVSHOWS_PATH, ("%s [%s]" % (base_name, _id)).strip())
        logger.info("Creando directorio serie: " + path)
        try:
            filetools.mkdir(path)
        except OSError, exception:
            if exception.errno != errno.EEXIST:
                raise
Example #48
0
                        idPath = records[0][0]
                        sql = 'UPDATE path SET strContent="%s", strScraper="%s", scanRecursive=%s, strSettings="%s" ' \
                              'WHERE idPath=%s' % (strContent, strScraper, scanRecursive, strSettings, idPath)

                if sql:
                    nun_records, records = execute_sql_kodi(sql)
                    if nun_records == 1:
                        continuar = True
                        logger.info("Biblioteca  %s configurada" % content_type)

        if not continuar:
            heading = "Biblioteca no configurada"
            msg_text = "Asegurese de tener instalado el scraper de The Movie Database"
            platformtools.dialog_notification(heading, msg_text, icon=1, time=8000)
            logger.info("%s: %s" % (heading,msg_text))



'''
Main
'''
if not filetools.exists(MOVIES_PATH):
    logger.info("pelisalacarta.platformcode.library Movies path doesn't exist:" + MOVIES_PATH)
    if filetools.mkdir(MOVIES_PATH):
        establecer_contenido(FOLDER_MOVIES)


if not filetools.exists(TVSHOWS_PATH):
    logger.info("pelisalacarta.platformcode.library Tvshows path doesn't exist:" + TVSHOWS_PATH)
    if filetools.mkdir(TVSHOWS_PATH):
        establecer_contenido(FOLDER_TVSHOWS)
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()
    # logger.debug(item.tostring('\n'))
    insertados = 0
    sobreescritos = 0
    fallidos = 0
    path = ""

    # Itentamos obtener el titulo correcto:
    # 1. contentTitle: Este deberia ser el sitio correcto, ya que title suele contener "Añadir a la biblioteca..."
    # 2. fulltitle
    # 3. title
    if not item.contentTitle:
        # Colocamos el titulo correcto en su sitio para que scraper lo localize
        if item.fulltitle:
            item.contentTitle = item.fulltitle
        else:
            item.contentTitle = item.title

    # Si llegados a este punto no tenemos titulo, salimos
    if not item.contentTitle or not item.channel:
        logger.debug("NO ENCONTRADO contentTitle")
        return 0, 0, -1  # Salimos sin guardar

    scraper_return = scraper.find_and_set_infoLabels(item)

    # Llegados a este punto podemos tener:
    #  scraper_return = True: Un item con infoLabels con la información actualizada de la peli
    #  scraper_return = False: Un item sin información de la peli (se ha dado a cancelar en la ventana)
    #  item.infoLabels['code'] == "" : No se ha encontrado el identificador de IMDB necesario para continuar, salimos
    if not scraper_return or not item.infoLabels['code']:
        # TODO de momento si no hay resultado no añadimos nada,
        # aunq podriamos abrir un cuadro para introducir el identificador/nombre a mano
        logger.debug("NO ENCONTRADO EN SCRAPER O NO TIENE code")
        return 0, 0, -1

    _id = item.infoLabels['code'][0]

    # progress dialog
    p_dialog = platformtools.dialog_progress('streamondemand', 'Aggiunta film...')

    if config.get_setting("original_title_folder", "biblioteca") == 1 and item.infoLabels['originaltitle']:
        base_name = item.infoLabels['originaltitle']
    else:
        base_name = item.contentTitle

    base_name = unicode(filetools.validate_path(base_name.replace('/', '-')), "utf8").lower().encode("utf8")

    for raiz, subcarpetas, ficheros in filetools.walk(MOVIES_PATH):
        for c in subcarpetas:
            code = scrapertools.find_single_match(c, '\[(.*?)\]')
            if code and code in item.infoLabels['code']:
                path = filetools.join(raiz, c)
                _id = code
                break

    if not path:
        # Crear carpeta
        path = filetools.join(MOVIES_PATH, ("%s [%s]" % (base_name, _id)).strip())
        logger.info("Creando directorio pelicula:" + path)
        if not filetools.mkdir(path):
            logger.debug("No se ha podido crear el directorio")
            return 0, 0, -1

    nfo_path = filetools.join(path, "%s [%s].nfo" % (base_name, _id))
    strm_path = filetools.join(path, "%s.strm" % base_name)
    json_path = filetools.join(path, ("%s [%s].json" % (base_name, item.channel.lower())))

    nfo_exists = filetools.exists(nfo_path)
    strm_exists = filetools.exists(strm_path)
    json_exists = filetools.exists(json_path)

    if not nfo_exists:
        # Creamos .nfo si no existe
        logger.info("Creando .nfo: " + nfo_path)
        head_nfo = scraper.get_nfo(item)

        item_nfo = Item(title=item.contentTitle, channel="biblioteca", action='findvideos',
                        library_playcounts={"%s [%s]" % (base_name, _id): 0}, infoLabels=item.infoLabels,
                        library_urls={})

    else:
        # Si existe .nfo, pero estamos añadiendo un nuevo canal lo abrimos
        head_nfo, item_nfo = read_nfo(nfo_path)

    if not strm_exists:
        # Crear base_name.strm si no existe
        item_strm = Item(channel='biblioteca', action='play_from_library',
                               strm_path=strm_path.replace(MOVIES_PATH, ""), contentType='movie',
                               contentTitle = item.contentTitle)
        strm_exists = filetools.write(strm_path, '%s?%s' % (addon_name, item_strm.tourl()))
        item_nfo.strm_path = strm_path.replace(MOVIES_PATH, "")

    # Solo si existen item_nfo y .strm continuamos
    if item_nfo and strm_exists:

        if json_exists:
            logger.info("El fichero existe. Se sobreescribe")
            sobreescritos += 1
        else:
            insertados += 1

        if filetools.write(json_path, item.tojson()):
            p_dialog.update(100, 'Aggiunta film...', item.contentTitle)
            item_nfo.library_urls[item.channel] = item.url

            if filetools.write(nfo_path, head_nfo + item_nfo.tojson()):
                # actualizamos la biblioteca de Kodi con la pelicula
                if config.is_xbmc():
                    from platformcode import xbmc_library
                    xbmc_library.update(FOLDER_MOVIES, filetools.basename(path) + "/")

                p_dialog.close()
                return insertados, sobreescritos, fallidos

    # Si llegamos a este punto es por q algo ha fallado
    logger.error("No se ha podido guardar %s en la biblioteca" % item.contentTitle)
    p_dialog.update(100, 'Aggiunta fallita...', item.contentTitle)
    p_dialog.close()
    return 0, 0, -1
logger.info("LIBRARY_PATH (RAW): " + LIBRARY_PATH)
# logger.info("MOVIES_PATH (RAW): " + MOVIES_PATH)
# logger.info("TVSHOWS_PATH (RAW): " + TVSHOWS_PATH)
logger.info("FOLDER_MOVIES (RAW): " + FOLDER_MOVIES)
logger.info("FOLDER_TVSHOWS (RAW): " + FOLDER_TVSHOWS)

addon_name = "plugin://plugin.video.streamondemand/"

# TODO: mover todo esto a config.verify_directories_created()
if not filetools.exists(LIBRARY_PATH):
    logger.info("Library path doesn't exist:" + LIBRARY_PATH)
    config.verify_directories_created()

if not filetools.exists(MOVIES_PATH):
    logger.info("Movies path doesn't exist:" + MOVIES_PATH)
    if filetools.mkdir(MOVIES_PATH) and config.is_xbmc():
        if config.is_xbmc():
            from platformcode import xbmc_library

            xbmc_library.establecer_contenido(FOLDER_MOVIES)

if not filetools.exists(TVSHOWS_PATH):
    logger.info("Tvshows path doesn't exist:" + TVSHOWS_PATH)
    if filetools.mkdir(TVSHOWS_PATH) and config.is_xbmc():
        if config.is_xbmc():
            from platformcode import xbmc_library

            xbmc_library.establecer_contenido(FOLDER_TVSHOWS)


def read_nfo(path_nfo, item=None):