Exemple #1
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])
Exemple #2
0
def get_channel_json(channel_name):
    logger.debug("channel_name=" + channel_name)
    from core import filetools
    channel_json = None
    try:
        channel_path = filetools.join(config.get_runtime_path(), "channels",
                                      channel_name + ".json")
        if not filetools.isfile(channel_path):
            channel_path = filetools.join(config.get_runtime_path(),
                                          "specials", channel_name + ".json")
            if not filetools.isfile(channel_path):
                channel_path = filetools.join(config.get_runtime_path(),
                                              "servers",
                                              channel_name + ".json")
                if not filetools.isfile(channel_path):
                    channel_path = filetools.join(config.get_runtime_path(),
                                                  "servers", "debriders",
                                                  channel_name + ".json")

        if filetools.isfile(channel_path):
            logger.debug("channel_data=" + channel_path)
            channel_json = jsontools.load(filetools.read(channel_path))
            logger.debug("channel_json= %s" % channel_json)

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

    return channel_json
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])
Exemple #4
0
def get_server_parameters(server):
    """
    Get data from server
    @param server: Server name
    @type server: str

    @return: server data
    @rtype: dict
    """
    # logger.info("server %s" % server)
    global dict_servers_parameters
    server = server.split('.')[0]
    if not server:
        return {}

    if server not in dict_servers_parameters and server not in ['servers']:
        try:
            path = ''
            # Servers
            if filetools.isfile(filetools.join(config.get_runtime_path(), "servers", server + ".json")):
                path = filetools.join(config.get_runtime_path(), "servers", server + ".json")

            # Debriders
            elif filetools.isfile(filetools.join(config.get_runtime_path(), "servers", "debriders", server + ".json")):
                path = filetools.join(config.get_runtime_path(), "servers", "debriders", server + ".json")

            # When the server is not well defined in the channel (there is no connector), it shows an error because there is no "path" and the channel has to be checked
            dict_server = jsontools.load(filetools.read(path))

            dict_server["name"] = translate_server_name(dict_server["name"])

            # Images: url and local files are allowed inside "resources / images"
            if dict_server.get("thumbnail") and "://" not in dict_server["thumbnail"]:
                dict_server["thumbnail"] = filetools.join(config.get_runtime_path(), "resources", "media",
                                                        "servers", dict_server["thumbnail"])
            for k in ['premium', 'id']:
                dict_server[k] = dict_server.get(k, list())

                if isinstance(dict_server[k], str):
                    dict_server[k] = [dict_server[k]]

            if "find_videos" in dict_server:
                dict_server['find_videos']["patterns"] = dict_server['find_videos'].get("patterns", list())
                dict_server['find_videos']["ignore_urls"] = dict_server['find_videos'].get("ignore_urls", list())

            if "settings" in dict_server:
                dict_server['has_settings'] = True
            else:
                dict_server['has_settings'] = False

            dict_servers_parameters[server] = dict_server

        except:
            mensaje = config.get_localized_string(59986) % server
            import traceback
            logger.error(mensaje + traceback.format_exc())
            return {}

    return dict_servers_parameters[server]
Exemple #5
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])
Exemple #6
0
def get_versions_from_repo(urls=[], xml_repo='addons.xml'):
    '''
    Devuelve los números de versiones de los addons y repos incluidos en el Alfa Repo, así como la url desde donde se ha descargado
    '''
    from core import httptools
    from core import filetools

    versiones = {}
    if not urls:
        url_base = [
            'https://github.com/alfa-addon/alfa-repo/raw/master/',
            'https://gitlab.com/addon-alfa/alfa-repo/-/raw/master/'
        ]
    elif isinstance(urls, (list, tuple)):
        url_base = urls
    else:
        url_base = [urls]

    for url in url_base:
        response = httptools.downloadpage(url + xml_repo,
                                          timeout=5,
                                          ignore_response_code=True,
                                          alfa_s=True)
        if response.code != 200: continue
        try:
            import xmltodict
            xml = xmltodict.parse(response.data)
            for addon in xml["addons"]["addon"]:
                versiones[addon["@id"]] = addon["@version"]
            versiones['url'] = url
            response = httptools.downloadpage(url + xml_repo + '.md5',
                                              timeout=5,
                                              ignore_response_code=True,
                                              alfa_s=True)

            if response.code == 200 and response.data:
                versiones['repository.alfa-addon.md5'] = response.data

            for f in sorted(filetools.listdir("special://userdata/Database"),
                            reverse=True):
                path_f = filetools.join("special://userdata/Database", f)
                if filetools.isfile(path_f) and f.lower().startswith(
                        'addons') and f.lower().endswith('.db'):
                    versiones['addons_db'] = path_f
                    break

            versiones = filetools.decode(versiones)
            break
        except:
            import traceback
            from platformcode import logger
            logger.error("Unable to download repo xml: %s" % versiones)
            versiones = {}
            logger.error(traceback.format_exc())
    else:
        from platformcode import logger
        logger.error("Unable to download repo xml: %s, %s" %
                     (xml_repo, url_base))

    return versiones
Exemple #7
0
def elementum_download(item):
    elementum_setting, elementum_host, TorrentPath = setting()

    if elementum_setting:
        set_elementum(True)
        time.sleep(3)
        if config.get_setting('downloadpath').startswith('smb'):
            select = platformtools.dialog_yesno(
                'Elementum', config.get_localized_string(70807))
            if select:
                xbmc.executebuiltin(
                    "RunPlugin(plugin://plugin.video.kod/?eyJjaGFubmVsIjoic2hvcnRjdXRzIiwgImFjdGlvbiI6IlNldHRpbmdPblBvc2l0aW9uIiwgImNhdGVnb3J5Ijo2LCAic2V0dGluZyI6MX0=)"
                )
        else:
            TorrentName = match(item.url,
                                patron=r'btih(?::|%3A)([^&%]+)',
                                string=True).match
            post = 'uri=%s&file=null&all=1' % urllib.quote_plus(item.url)
            match(elementum_host + 'add',
                  post=post,
                  timeout=5,
                  alfa_s=True,
                  ignore_response_code=True)
            while not filetools.isfile(
                    filetools.join(
                        elementum_setting.getSetting('torrents_path'),
                        TorrentName + '.torrent')):
                time.sleep(1)

            monitor_update(TorrentPath, TorrentName)
Exemple #8
0
def menu(item):
    logger.info()

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

    opciones = []

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

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

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

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

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

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

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

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

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

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

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

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

    platformtools.itemlist_refresh()
Exemple #9
0
def restart_error(item):
    logger.info()
    for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)):
        if fichero.endswith(".json"):
            download_item = Item().fromjson(
                filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero)))

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

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

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

    opciones = []

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

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

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

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

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

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

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

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

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

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

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

    platformtools.itemlist_refresh()
Exemple #11
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)
Exemple #12
0
def downloadfileRTMP(url, nombrefichero, silent):
    ''' No usa librtmp ya que no siempre está disponible.
        Lanza un subproceso con rtmpdump. En Windows es necesario instalarlo.
        No usa threads así que no muestra ninguna barra de progreso ni tampoco
        se marca el final real de la descarga en el log info.
    '''
    Programfiles = os.getenv('Programfiles')
    if Programfiles:  # Windows
        rtmpdump_cmd = Programfiles + "/rtmpdump/rtmpdump.exe"
        nombrefichero = '"' + nombrefichero + '"'  # Windows necesita las comillas en el nombre
    else:
        rtmpdump_cmd = "/usr/bin/rtmpdump"

    if not filetools.isfile(rtmpdump_cmd) and not silent:
        from platformcode import platformtools
        advertencia = platformtools.dialog_ok(
            "Falta " + rtmpdump_cmd, "Comprueba que rtmpdump está instalado")
        return True

    valid_rtmpdump_options = [
        "help", "url", "rtmp", "host", "port", "socks", "protocol", "playpath",
        "playlist", "swfUrl", "tcUrl", "pageUrl", "app", "swfhash", "swfsize",
        "swfVfy", "swfAge", "auth", "conn", "flashVer", "live", "subscribe",
        "realtime", "flv", "resume", "timeout", "start", "stop", "token",
        "jtv", "hashes", "buffer", "skip", "quiet", "verbose", "debug"
    ]  # for rtmpdump 2.4

    url_args = url.split(' ')
    rtmp_url = url_args[0]
    rtmp_args = url_args[1:]

    rtmpdump_args = ["--rtmp", rtmp_url]
    for arg in rtmp_args:
        n = arg.find('=')
        if n < 0:
            if arg not in valid_rtmpdump_options:
                continue
            rtmpdump_args += ["--" + arg]
        else:
            if arg[:n] not in valid_rtmpdump_options:
                continue
            rtmpdump_args += ["--" + arg[:n], arg[n + 1:]]

    try:
        rtmpdump_args = [rtmpdump_cmd] + rtmpdump_args + ["-o", nombrefichero]
        from os import spawnv, P_NOWAIT
        logger.info("Iniciando descarga del fichero: %s" %
                    " ".join(rtmpdump_args))
        rtmpdump_exit = spawnv(P_NOWAIT, rtmpdump_cmd, rtmpdump_args)
        if not silent:
            from platformcode import platformtools
            advertencia = platformtools.dialog_ok(
                "La opción de descarga RTMP es experimental",
                "y el vídeo se descargará en segundo plano.",
                "No se mostrará ninguna barra de progreso.")
    except:
        return True

    return
Exemple #13
0
def downloadfileRTMP(url, nombrefichero, silent):
    ''' 
    Do not use librtmp as it is not always available.
    Launch a thread with rtmpdump. In Windows it is necessary to install it.
    It doesn't use threads so it doesn't show any progress bar nor the actual end of the download is marked in the log info.
    '''
    Programfiles = os.getenv('Programfiles')
    if Programfiles:  # Windows
        rtmpdump_cmd = Programfiles + "/rtmpdump/rtmpdump.exe"
        nombrefichero = '"' + nombrefichero + '"'  # Windows needs the quotes in the name
    else:
        rtmpdump_cmd = "/usr/bin/rtmpdump"

    if not filetools.isfile(rtmpdump_cmd) and not silent:
        from platformcode import platformtools
        advertencia = platformtools.dialog_ok(
            "Lack " + rtmpdump_cmd, "Check that rtmpdump is installed")
        return True

    valid_rtmpdump_options = [
        "help", "url", "rtmp", "host", "port", "socks", "protocol", "playpath",
        "playlist", "swfUrl", "tcUrl", "pageUrl", "app", "swfhash", "swfsize",
        "swfVfy", "swfAge", "auth", "conn", "flashVer", "live", "subscribe",
        "realtime", "flv", "resume", "timeout", "start", "stop", "token",
        "jtv", "hashes", "buffer", "skip", "quiet", "verbose", "debug"
    ]  # for rtmpdump 2.4

    url_args = url.split(' ')
    rtmp_url = url_args[0]
    rtmp_args = url_args[1:]

    rtmpdump_args = ["--rtmp", rtmp_url]
    for arg in rtmp_args:
        n = arg.find('=')
        if n < 0:
            if arg not in valid_rtmpdump_options:
                continue
            rtmpdump_args += ["--" + arg]
        else:
            if arg[:n] not in valid_rtmpdump_options:
                continue
            rtmpdump_args += ["--" + arg[:n], arg[n + 1:]]

    try:
        rtmpdump_args = [rtmpdump_cmd] + rtmpdump_args + ["-o", nombrefichero]
        from os import spawnv, P_NOWAIT
        logger.info("Initiating file download: %s" % " ".join(rtmpdump_args))
        rtmpdump_exit = spawnv(P_NOWAIT, rtmpdump_cmd, rtmpdump_args)
        if not silent:
            from platformcode import platformtools
            advertencia = platformtools.dialog_ok(
                "RTMP download option is experimental",
                "and the video will download in the background.",
                "No progress bar will be displayed.")
    except:
        return True

    return
Exemple #14
0
def menu(item):
    logger.info("pelisalacarta.channels.descargas menu")

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

    opciones = []

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

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

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

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

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

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

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

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

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

    platformtools.itemlist_refresh()
Exemple #15
0
 def get_played_time(item):
     if item.contentType == 'movie': nfo_path = item.nfo
     else: nfo_path = item.strm_path.replace('strm','nfo')
     if nfo_path and filetools.isfile(nfo_path):
         from core import videolibrarytools
         head_nfo, item_nfo = videolibrarytools.read_nfo(nfo_path)
         sleep(1)
         played_time = platformtools.get_played_time(item_nfo)
     else: played_time = 0
     return played_time
Exemple #16
0
def get_channel_json(channel_name):
    channel_json = {}
    try:
        channel_path = filetools.join(config.get_runtime_path(), "channels", channel_name + ".json")
        if filetools.isfile(channel_path):
            channel_json = jsontools.load(filetools.read(channel_path))

    except Exception, ex:
        template = "An exception of type %s occured. Arguments:\n%r"
        message = template % (type(ex).__name__, ex.args)
        logger.error(" %s" % message)
Exemple #17
0
def menu(item):
    logger.info("pelisalacarta.channels.descargas menu")

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

    opciones = []

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

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

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

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

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

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

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

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

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

    platformtools.itemlist_refresh()
Exemple #18
0
def elementum_download(item):
    elementum_setting, elementum_host, TorrentPath = setting()

    if elementum_setting:
        set_elementum(True)
        time.sleep(3)
        TorrentName = match(item.url, patron=r'btih(?::|%3A)([^&%]+)', string=True).match
        post = 'uri=%s&file=null&all=1' % urllib.quote_plus(item.url)
        match(elementum_host  + 'add', post=post, timeout=5, alfa_s=True, ignore_response_code=True)
        while not filetools.isfile(filetools.join(elementum_setting.getSetting('torrents_path'), TorrentName + '.torrent')):
            time.sleep(1)

        monitor_update(TorrentPath, TorrentName)
Exemple #19
0
def get_thumb(thumb_name, view="thumb_"):
    from core import filetools
    if thumb_name.startswith('http'):
        return thumb_name
    elif config.get_setting('enable_custom_theme') and config.get_setting(
            'custom_theme') and filetools.isfile(
                config.get_setting('custom_theme') + view + thumb_name):
        media_path = config.get_setting('custom_theme')
    else:
        icon_pack_name = config.get_setting('icon_set', default="default")
        media_path = filetools.join(
            "https://raw.githubusercontent.com/kodiondemand/media/master/themes",
            icon_pack_name)
    return filetools.join(media_path, view + thumb_name)
def restart_error(item):
    logger.info("pelisalacarta.channels.descargas restart_error")
    for fichero in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)):
        if fichero.endswith(".json"):
            download_item = Item().fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero)))
            
            if not item.contentType == "tvshow" or (item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
              if download_item.downloadStatus == STATUS_CODES.error:
                  if filetools.isfile(os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename)):
                      filetools.remove(os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename))
                      
                  update_json(item.path, {"downloadStatus" : STATUS_CODES.stoped, "downloadComplete" :  0 , "downloadProgress" : 0})


    platformtools.itemlist_refresh()
Exemple #21
0
def delete_file(item):
    logger.info()
    from core import filetools

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

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

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

    platformtools.itemlist_refresh()
Exemple #23
0
def get_channel_json(channel_name):
    # logger.info("channel_name=" + channel_name)
    from . import filetools
    channel_json = None
    try:
        channel_path = filetools.join(config.get_runtime_path(), "channels",
                                      channel_name + ".json")
        if filetools.isfile(channel_path):
            # logger.info("channel_data=" + channel_path)
            channel_json = jsontools.load(filetools.read(channel_path))
            # logger.info("channel_json= %s" % channel_json)

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

    return channel_json
Exemple #24
0
def get_server_position(server):
    if filetools.isfile(STATS_FILE):
        servers = jsontools.load(filetools.read(STATS_FILE))
    else:
        servers = {}

    if server in servers:
        pos = [
            s for s in sorted(
                servers,
                key=lambda x: (old_div(sum(servers[x]["speeds"]), (len(servers[
                    x]["speeds"]) or 1)), float(sum(servers[x]["success"])) /
                               (len(servers[x]["success"]) or 1)),
                reverse=True)
        ]
        return pos.index(server) + 1
    else:
        return 0
Exemple #25
0
def save_server_statistics(server, speed, success):
    if filetools.isfile(STATS_FILE):
        servers = jsontools.load(filetools.read(STATS_FILE))
    else:
        servers = {}

    if not server in servers:
        servers[server] = {"success": [], "count": 0, "speeds": [], "last": 0}

    servers[server]["count"] += 1
    servers[server]["success"].append(bool(success))
    servers[server]["success"] = servers[server]["success"][-5:]
    servers[server]["last"] = time.time()
    if success:
        servers[server]["speeds"].append(speed)
        servers[server]["speeds"] = servers[server]["speeds"][-5:]

    filetools.write(STATS_FILE, jsontools.dump(servers))
    return
Exemple #26
0
def get_node_from_file(name_file, node, path=None, display=True):
    """
    Obtiene el nodo de un fichero JSON

    @param name_file: Puede ser el nombre de un canal o server (sin incluir extension)
     o bien el nombre de un archivo json (con extension)
    @type name_file: str
    @param node: nombre del nodo a obtener
    @type node: str
    @param path: Ruta base del archivo json. Por defecto la ruta de settings_channels.
    @return: dict con el nodo a devolver
    @rtype: dict
    """
    if display: logger.info()
    from platformcode import config
    from core import filetools

    dict_node = {}

    if not name_file.endswith(".json"):
        name_file += "_data.json"

    if not path:
        path = filetools.join(config.get_data_path(), "settings_channels")

    fname = filetools.join(path, name_file)

    if filetools.isfile(fname):
        data = filetools.read(fname)
        dict_data = load(data)

        check_to_backup(data, fname, dict_data, display=display)

        if node in dict_data:
            dict_node = dict_data[node]

    #logger.debug("dict_node: %s" % dict_node)

    return dict_node
Exemple #27
0
def elementum_monitor():
    path = xbmc.translatePath(config.get_setting('downloadlistpath'))
    elementum_setting, elementum_host, TorrentPath = setting()
    # active_torrent = filetools.listdir(TorrentPath)

    if elementum_setting:
        # check if command file exist
        if filetools.isfile(monitor):
            json = jsontools.load(open(monitor, "r").read())
            Monitor = json['monitor']
        # else create it
        else:
            Monitor = jsontools.load('{"monitor":{},"settings":{}}')
            json = jsontools.dump(Monitor)
            filetools.write(monitor, json, silent=True)

        if len(Monitor) > 0:
            try:
                data = requests.get(elementum_host + '/list').json()
            except:
                data = ''
            if data:
                for it in data:
                    progress = round(it['progress'], 2)
                    status = it['status']
                    name = it['id']
                    if name in Monitor:
                        jsontools.update_node(progress, Monitor[name]['file'], 'downloadProgress', path, silent=True)
                        jsontools.update_node(4, Monitor[name]['file'], 'downloadStatus', path, silent=True)
                        if status in ['Paused']:
                            jsontools.update_node(0, Monitor[name]['file'], 'downloadStatus', path, silent=True)
                        if status in ['Seeding', 'Finished'] and not config.get_setting('elementum_on_seed'):
                            monitor_update(TorrentPath, name, remove=True)
                            dlJson = jsontools.load(open(filetools.join(path, Monitor[name]['file']), "r").read())
                            jsontools.update_node(dlJson['downloadSize'], Monitor[name]['file'], 'downloadCompleted', path, silent=True)
                            jsontools.update_node(2, Monitor[name]['file'], 'downloadStatus', path, silent=True)
                            requests.get(elementum_host + 'pause/' + name)
                            filetools.remove(filetools.join(TorrentPath, name + '.torrent'))
                            filetools.remove(filetools.join(TorrentPath, name + '.fastresume'))
Exemple #28
0
def get_node_from_file(name_file, node, path=None):
    """
    Gets the node of a JSON file

    @param name_file: It can be the name of a channel or server (not including extension) or the name of a json file (with extension)
    @type name_file: str
    @param node: name of the node to obtain
    @type node: str
    @param path: Base path of the json file. By default the path of settings_channels.
    @return: dict with the node to return
    @rtype: dict
    """
    logger.debug()
    from platformcode import config
    from core import filetools

    dict_node = {}

    if not name_file.endswith(".json"):
        name_file += "_data.json"

    if not path:
        path = filetools.join(config.get_data_path(), "settings_channels")

    fname = filetools.join(path, name_file)

    if filetools.isfile(fname):
        data = filetools.read(fname)
        dict_data = load(data)

        check_to_backup(data, fname, dict_data)

        if node in dict_data:
            dict_node = dict_data[node]

    #logger.debug("dict_node: %s" % dict_node)

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

    platformtools.itemlist_refresh()
Exemple #30
0
def view_mode(item):
    logger.info(str(item))
    import xbmc
    from core import filetools, jsontools
    from core.support import typo
    from platformcode import config, platformtools

    skin_name = xbmc.getSkinDir()
    config.set_setting('skin_name', skin_name)

    path = filetools.join(config.get_runtime_path(), 'resources', 'views',
                          skin_name + '.json')
    if filetools.isfile(path):
        json_file = open(path, "r").read()
        json = jsontools.load(json_file)

        Type = 'addon' if item.type in ['channel', 'server'] else item.type
        skin = json[Type]

        list_type = []
        for key in skin:
            list_type.append(key)
        list_type.sort()
        list_type.insert(0, config.get_localized_string(70003))

        select = platformtools.dialog_select(
            config.get_localized_string(70754), list_type)
        value = list_type[select] + ' , ' + str(
            skin[list_type[select]] if list_type[select] in skin else 0)
        config.set_setting('view_mode_%s' % item.type, value)
    else:
        platformtools.dialog_ok(
            config.get_localized_string(30141),
            config.get_localized_string(30142) % typo(
                skin_name.replace('skin.', '').replace('.', ' '),
                'capitalize bold'))
Exemple #31
0
def mark_content_as_watched2(item):
    logger.info()
    # logger.debug("item:\n" + item.tostring('\n'))
    if filetools.isfile(item.nfo):
        head_nfo, it = videolibrarytools.read_nfo(item.nfo)
        name_file = ""
        if item.contentType == 'movie' or item.contentType == 'tvshow':
            name_file = os.path.splitext(filetools.basename(item.nfo))[0]

            if name_file != 'tvshow' :
                it.library_playcounts.update({name_file: item.playcount})

        if item.contentType == 'episode' or item.contentType == 'tvshow' or item.contentType == 'list' or name_file == 'tvshow':
            name_file = os.path.splitext(filetools.basename(item.strm_path))[0]
            num_season = name_file [0]
            item.__setattr__('contentType', 'episode')
            item.__setattr__('contentSeason', num_season)

        else:
            name_file = item.contentTitle

        if not hasattr(it, 'library_playcounts'):
            it.library_playcounts = {}
        it.library_playcounts.update({name_file: item.playcount})

        # it is verified that if all the episodes of a season are marked, tb the season is marked
        if item.contentType != 'movie':
            it = check_season_playcount(it, item.contentSeason)

        # We save the changes to item.nfo
        if filetools.write(item.nfo, head_nfo + it.tojson()):
            item.infoLabels['playcount'] = item.playcount

            if config.is_xbmc():
                from platformcode import xbmc_videolibrary
                xbmc_videolibrary.mark_content_as_watched_on_kodi(item , item.playcount)
Exemple #32
0
def findvideos(item):
    logger.info()
    from core import filetools
    from lib import generictools

    itemlist = []
    size = ''
    torrent_params = {
        'url': item.url,
        'torrents_path': None,
        'local_torr': item.torrents_path,
        'lookup': False,
        'force': True,
        'data_torrent': True,
        'subtitles': True,
        'file_list': True
    }

    #logger.debug(item)

    FOLDER_MOVIES = config.get_setting("folder_movies")
    FOLDER_TVSHOWS = config.get_setting("folder_tvshows")
    FOLDER = FOLDER_TVSHOWS if item.infoLabels[
        'mediatype'] == 'episode' else FOLDER_MOVIES
    VIDEOLIBRARY_PATH = config.get_videolibrary_path()
    MOVIES_PATH = filetools.join(VIDEOLIBRARY_PATH, FOLDER_MOVIES)
    TVSHOWS_PATH = filetools.join(VIDEOLIBRARY_PATH, FOLDER_TVSHOWS)
    VIDEO_FOLDER = filetools.join(VIDEOLIBRARY_PATH, FOLDER)

    # Viene desde Kodi/Videoteca de una canal desactivado
    if not item.list_type:
        if item.emergency_urls:
            # Llamamos al método para crear el título general del vídeo, con toda la información obtenida de TMDB
            item.infoLabels['playcount'] = 0
            if item.contentChannel == 'videolibrary':
                item.armagedon = True  # Lo marcammos como URLs de Emergencia
            item.channel_recovery = 'url'
            item, itemlist = generictools.post_tmdb_findvideos(item, itemlist)

            for x, link in enumerate(item.emergency_urls[0]):
                quality = item.quality
                if link.startswith('magnet'):
                    link_path = link
                    item.torrents_path = ''
                else:
                    link_path = filetools.join(VIDEO_FOLDER, link)

                if link_path.startswith('magnet') or filetools.isfile(
                        link_path):
                    if btdigg_magnet in link_path and len(
                            item.emergency_urls) > 3 and len(
                                item.emergency_urls[3]) >= x + 1:
                        try:
                            z, quality, size = item.emergency_urls[3][x].split(
                                '#')
                        except:
                            pass
                    else:
                        torrent_params['url'] = link_path
                        torrent_params['torrents_path'] = link_path
                        torrent_params['local_torr'] = link_path
                        torrent_params = generictools.get_torrent_size(
                            link_path,
                            torrent_params=torrent_params,
                            item=item)  # Tamaño en el .torrent
                        size = torrent_params['size']
                        item.torrents_path = torrent_params['torrents_path']
                    if size:
                        # Generamos una copia de Item para trabajar sobre ella
                        item_local = item.clone()

                        item_local.channel = 'url'
                        item_local.url = link_path
                        if btdigg_magnet in item_local.url:
                            item_local.btdigg = True
                        item_local.torrent_info = size

                        item_local.quality = quality
                        # Si viene de la Videoteca de Kodi, mostramos que son URLs de Emergencia
                        if item_local.contentChannel == 'videolibrary':
                            item_local.quality = '[COLOR hotpink][E][/COLOR] [COLOR limegreen]%s[/COLOR]' % item_local.quality

                        #Ahora pintamos el link del Torrent
                        item_local.title = '[[COLOR yellow]?[/COLOR]] [COLOR yellow][Torrent][/COLOR] ' \
                                        + '[COLOR limegreen][%s][/COLOR] [COLOR red]%s[/COLOR] %s' % \
                                        (item_local.quality, str(item_local.language), \
                                        item_local.torrent_info)

                        # Preparamos título y calidad, quitando etiquetas vacías
                        item_local.title = re.sub(
                            r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '',
                            item_local.title)
                        item_local.title = re.sub(
                            r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '',
                            item_local.title)
                        item_local.title = item_local.title.replace("--", "").replace("[]", "")\
                                        .replace("()", "").replace("(/)", "").replace("[/]", "")\
                                        .replace("|", "").strip()

                        item_local.quality = re.sub(
                            r'\s?\[COLOR \w+\]\[\[?\s?\]?\]\[\/COLOR\]', '',
                            item_local.quality)
                        item_local.quality = re.sub(
                            r'\s?\[COLOR \w+\]\s?\[\/COLOR\]', '',
                            item_local.quality)
                        item_local.quality = item_local.quality.replace("--", "").replace("[]", "")\
                                        .replace("()", "").replace("(/)", "").replace("[/]", "")\
                                        .replace("|", "").strip()

                        if not size or 'Magnet' in size:
                            item_local.alive = "??"  #Calidad del link sin verificar
                        elif 'ERROR' in size and 'Pincha' in size:
                            item_local.alive = "ok"  #link en error, CF challenge, Chrome disponible
                        elif 'ERROR' in size and 'Introduce' in size:
                            item_local.alive = "??"  #link en error, CF challenge, ruta de descarga no disponible
                            item_local.channel = 'setting'
                            item_local.action = 'setting_torrent'
                            item_local.unify = False
                            item_local.folder = False
                            item_local.item_org = item.tourl()
                        elif 'ERROR' in size:
                            item_local.alive = "no"  #Calidad del link en error, CF challenge?
                        else:
                            item_local.alive = "ok"  #Calidad del link verificada

                        item_local.action = "play"  #Visualizar vídeo
                        item_local.server = "torrent"  #Seridor Torrent

                        itemlist.append(item_local)  #Pintar pantalla
                        #logger.debug(item_local)

        return itemlist
Exemple #33
0
def execute_sql_kodi(sql):
    """
    Ejecuta la consulta sql contra la base de datos de kodi
    @param sql: Consulta sql valida
    @type sql: str
    @return: Numero de registros modificados o devueltos por la consulta
    @rtype nun_records: int
    @return: lista con el resultado de la consulta
    @rtype records: list of tuples
    """
    logger.info("pelisalacarta.platformcode.library execute_sql_kodi")
    file_db = ""
    nun_records = 0
    records = None

    # Buscamos el nombre de la BBDD de videos segun la version de kodi
    code_db = {'10': 'MyVideos37.db', '11': 'MyVideos60.db', '12': 'MyVideos75.db', '13': 'MyVideos78.db',
               '14': 'MyVideos90.db', '15': 'MyVideos93.db', '16': 'MyVideos99.db', '17': 'MyVideos107.db'}

    video_db = code_db.get(xbmc.getInfoLabel("System.BuildVersion").split(".", 1)[0], '')
    if video_db:
        file_db = filetools.join(xbmc.translatePath("special://userdata/Database"), video_db)

    # metodo alternativo para localizar la BBDD
    if not file_db or not filetools.exists(file_db):
        file_db = ""
        for f in filetools.listdir(xbmc.translatePath("special://userdata/Database")):
            path_f = filetools.join(xbmc.translatePath("special://userdata/Database"), f)

            if filetools.isfile(path_f) and f.lower().startswith('myvideos') and f.lower().endswith('.db'):
                file_db = path_f
                break

    if file_db:
        logger.info("Archivo de BD: %s" % file_db)
        conn = None
        try:
            import sqlite3
            conn = sqlite3.connect(file_db)
            cursor = conn.cursor()

            logger.info("Ejecutando sql: %s" % sql)
            cursor.execute(sql)
            conn.commit()

            records = cursor.fetchall()
            if sql.lower().startswith("select"):
                nun_records = len(records)
                if nun_records == 1 and records[0][0] is None:
                    nun_records = 0
                    records = []
            else:
                nun_records = conn.total_changes

            conn.close()
            logger.info("Consulta ejecutada. Registros: %s" % nun_records)

        except:
            logger.error("Error al ejecutar la consulta sql")
            if conn:
                conn.close()

    else:
        logger.debug("Base de datos no encontrada")

    return nun_records, records
Exemple #34
0
def execute_sql_kodi(sql):
    """
    Ejecuta la consulta sql contra la base de datos de kodi
    @param sql: Consulta sql valida
    @type sql: str
    @return: Numero de registros modificados o devueltos por la consulta
    @rtype nun_records: int
    @return: lista con el resultado de la consulta
    @rtype records: list of tuples
    """
    logger.info()
    file_db = ""
    nun_records = 0
    records = None

    # Buscamos el archivo de la BBDD de videos segun la version de kodi
    video_db = config.get_platform(True)['video_db']
    if video_db:
        file_db = filetools.join(xbmc.translatePath("special://userdata/Database"), video_db)

    # metodo alternativo para localizar la BBDD
    if not file_db or not filetools.exists(file_db):
        file_db = ""
        for f in filetools.listdir(xbmc.translatePath("special://userdata/Database")):
            path_f = filetools.join(xbmc.translatePath("special://userdata/Database"), f)

            if filetools.isfile(path_f) and f.lower().startswith('myvideos') and f.lower().endswith('.db'):
                file_db = path_f
                break

    if file_db:
        logger.info("Archivo de BD: %s" % file_db)
        conn = None
        try:
            import sqlite3
            conn = sqlite3.connect(file_db)
            cursor = conn.cursor()

            logger.info("Ejecutando sql: %s" % sql)
            cursor.execute(sql)
            conn.commit()

            records = cursor.fetchall()
            if sql.lower().startswith("select"):
                nun_records = len(records)
                if nun_records == 1 and records[0][0] is None:
                    nun_records = 0
                    records = []
            else:
                nun_records = conn.total_changes

            conn.close()
            logger.info("Consulta ejecutada. Registros: %s" % nun_records)

        except:
            logger.error("Error al ejecutar la consulta sql")
            if conn:
                conn.close()

    else:
        logger.debug("Base de datos no encontrada")

    return nun_records, records
Exemple #35
0
def run(item=None):
    # from core.support import dbg;dbg()
    logger.debug()
    if not item:
        # Extract item from sys.argv
        if sys.argv[2]:
            sp = sys.argv[2].split('&')
            url = sp[0]
            item = Item().fromurl(url)
            if len(sp) > 1:
                for e in sp[1:]:
                    key, val = e.split('=')
                    item.__setattr__(key, val)
        # If no item, this is mainlist
        else:
            item = Item(channel="channelselector",
                        action="getmainlist",
                        viewmode="movie")
        if not config.get_setting('show_once'):
            if not config.get_all_settings_addon():
                logger.error('corrupted settings.xml!!')
                settings_xml = os.path.join(config.get_data_path(),
                                            "settings.xml")
                settings_bak = os.path.join(config.get_data_path(),
                                            "settings.bak")
                if filetools.exists(settings_bak):
                    filetools.copy(settings_bak, settings_xml, True)
                    logger.info('restored settings.xml from backup')
                else:
                    filetools.write(settings_xml,
                                    '<settings version="2">\n</settings>'
                                    )  # resetted settings
            else:
                from platformcode import xbmc_videolibrary
                xbmc_videolibrary.ask_set_content(silent=False)
                config.set_setting('show_once', True)

    logger.info(item.tostring())

    try:
        if not config.get_setting('tmdb_active'):
            config.set_setting('tmdb_active', True)

        # If item has no action, stops here
        if item.action == "":
            logger.debug("Item without action")
            return

        # Action for main menu in channelselector
        elif item.action == "getmainlist":
            import channelselector

            itemlist = channelselector.getmainlist()

            platformtools.render_items(itemlist, item)

        # Action for channel types on channelselector: movies, series, etc.
        elif item.action == "getchanneltypes":
            import channelselector
            itemlist = channelselector.getchanneltypes()

            platformtools.render_items(itemlist, item)

        # Action for channel listing on channelselector
        elif item.action == "filterchannels":
            import channelselector
            itemlist = channelselector.filterchannels(item.channel_type)

            platformtools.render_items(itemlist, item)

        # Special action for playing a video from the library
        elif item.action == "play_from_library":
            play_from_library(item)
            return

        elif item.action == "keymap":
            from platformcode import keymaptools
            if item.open:
                return keymaptools.open_shortcut_menu()
            else:
                return keymaptools.set_key()

        elif item.channel == "infoplus":
            from platformcode import infoplus
            return infoplus.Main(item)

        elif item.channel == "backup":
            from platformcode import backup
            return getattr(backup, item.action)(item)

        elif item.channel == "elementum_download":
            from platformcode import elementum_download
            return getattr(elementum_download, item.action)(item)

        elif item.channel == "shortcuts":
            from platformcode import shortcuts
            return getattr(shortcuts, item.action)(item)

        elif item.channel == "autorenumber":
            from platformcode import autorenumber
            return getattr(autorenumber, item.action)(item)

        elif item.action == "delete_key":
            from platformcode import keymaptools
            return keymaptools.delete_key()

        elif item.action == "script":
            from core import tmdb
            if tmdb.drop_bd():
                platformtools.dialog_notification(
                    config.get_localized_string(20000),
                    config.get_localized_string(60011),
                    time=2000,
                    sound=False)
        elif item.action == "itemInfo":
            platformtools.dialog_textviewer('Item info', item.parent)
        elif item.action == "open_browser":
            import webbrowser
            if not webbrowser.open(item.url):
                import xbmc
                if xbmc.getCondVisibility(
                        'system.platform.linux') and xbmc.getCondVisibility(
                            'system.platform.android'):  # android
                    xbmc.executebuiltin(
                        'StartAndroidActivity("", "android.intent.action.VIEW", "", "%s")'
                        % (item.url))
                else:
                    try:
                        import urllib.request as urllib
                    except ImportError:
                        import urllib
                    short = urllib.urlopen(
                        'https://u.nu/api.php?action=shorturl&format=simple&url='
                        + item.url).read().decode('utf-8')
                    platformtools.dialog_ok(
                        config.get_localized_string(20000),
                        config.get_localized_string(70740) % short)
        # Action in certain channel specified in "action" and "channel" parameters
        elif item.action == "check_channels":
            from platformcode import checkhost
            checkhost.check_channels()
        else:
            # Checks if channel exists
            if os.path.isfile(
                    os.path.join(config.get_runtime_path(), 'channels',
                                 item.channel + ".py")):
                CHANNELS = 'channels'
            else:
                CHANNELS = 'specials'

            channel_file = os.path.join(config.get_runtime_path(), CHANNELS,
                                        item.channel + ".py")

            logger.debug("channel_file= " + channel_file + ' - ' + CHANNELS +
                         ' - ' + item.channel)

            channel = None

            if os.path.exists(channel_file):
                try:
                    channel = __import__('%s.%s' % (CHANNELS, item.channel),
                                         None, None,
                                         ['%s.%s' % (CHANNELS, item.channel)])
                except ImportError:
                    exec("import " + CHANNELS + "." + item.channel +
                         " as channel")

            logger.info("Running channel %s | %s" %
                        (channel.__name__, channel.__file__))

            # Special play action
            if item.action == "play":
                # define la info para trakt
                try:
                    from core import trakt_tools
                    trakt_tools.set_trakt_info(item)
                except:
                    pass
                logger.debug("item.action=%s" % item.action.upper())
                # logger.debug("item_toPlay: " + "\n" + item.tostring('\n'))

                # First checks if channel has a "play" function
                if hasattr(channel, 'play'):
                    logger.debug("Executing channel 'play' method")
                    itemlist = channel.play(item)
                    b_favourite = item.isFavourite
                    # Play should return a list of playable URLS
                    if len(itemlist) > 0 and isinstance(itemlist[0], Item):
                        item = itemlist[0]
                        if b_favourite:
                            item.isFavourite = True
                        platformtools.play_video(item)

                    # Permitir varias calidades desde play en el Channel
                    elif len(itemlist) > 0 and isinstance(itemlist[0], list):
                        item.video_urls = itemlist
                        platformtools.play_video(item)

                    # If not, shows user an error message
                    else:
                        platformtools.dialog_ok(
                            config.get_localized_string(20000),
                            config.get_localized_string(60339))

                # If player don't have a "play" function, not uses the standard play from platformtools
                else:
                    logger.debug("Executing core 'play' method")
                    platformtools.play_video(item)

            # Special action for findvideos, where the plugin looks for known urls
            elif item.action == "findvideos":
                from core import servertools

                # First checks if channel has a "findvideos" function
                if hasattr(channel, 'findvideos'):
                    itemlist = getattr(channel, item.action)(item)

                # If not, uses the generic findvideos function
                else:
                    logger.debug("No channel 'findvideos' method, "
                                 "executing core method")
                    itemlist = servertools.find_video_items(item)

                if config.get_setting("max_links", "videolibrary") != 0:
                    itemlist = limit_itemlist(itemlist)

                from platformcode import subtitletools
                subtitletools.saveSubtitleName(item)

                platformtools.render_items(itemlist, item)

            # Special action for adding a movie to the library
            elif item.action == "add_pelicula_to_library":
                from core import videolibrarytools
                videolibrarytools.add_movie(item)

            # Special action for adding a serie to the library
            elif item.action == "add_serie_to_library":
                from core import videolibrarytools
                videolibrarytools.add_tvshow(item, channel)

            # Special action for downloading all episodes from a serie
            elif item.action == "download_all_episodes":
                from specials import downloads
                item.action = item.extra
                del item.extra
                downloads.save_download(item)

            # Special action for searching, first asks for the words then call the "search" function
            elif item.action == "search":
                # from core.support import dbg;dbg()
                if filetools.isfile(temp_search_file) and config.get_setting(
                        'videolibrary_kodi'):
                    itemlist = []
                    f = filetools.read(temp_search_file)
                    strList = f.split(',')
                    if strList[0] == '[V]' and strList[1] == item.channel:
                        for it in strList:
                            if it and it not in ['[V]', item.channel]:
                                itemlist.append(Item().fromurl(it))
                        filetools.write(temp_search_file, f[4:])
                        return platformtools.render_items(itemlist, item)
                    else:
                        filetools.remove(temp_search_file)

                logger.debug("item.action=%s" % item.action.upper())
                from core import channeltools

                if config.get_setting('last_search'):
                    last_search = channeltools.get_channel_setting(
                        'Last_searched', 'search', '')
                else:
                    last_search = ''

                search_text = platformtools.dialog_input(last_search)

                if search_text is not None:
                    channeltools.set_channel_setting('Last_searched',
                                                     search_text, 'search')
                    itemlist = new_search(item.clone(text=search_text),
                                          channel)
                else:
                    return

                platformtools.render_items(itemlist, item)

            # For all other actions
            else:
                # import web_pdb; web_pdb.set_trace()
                logger.debug("Executing channel '%s' method" % item.action)
                itemlist = getattr(channel, item.action)(item)
                if config.get_setting('trakt_sync'):
                    from core import trakt_tools
                    token_auth = config.get_setting("token_trakt", "trakt")
                    if not token_auth:
                        trakt_tools.auth_trakt()
                    else:
                        import xbmc
                        if not xbmc.getCondVisibility(
                                'System.HasAddon(script.trakt)'
                        ) and config.get_setting('install_trakt'):
                            trakt_tools.ask_install_script()
                    itemlist = trakt_tools.trakt_check(itemlist)
                else:
                    config.set_setting('install_trakt', True)

                platformtools.render_items(itemlist, item)

    except WebErrorException as e:
        import traceback
        from core import scrapertools

        logger.error(traceback.format_exc())

        platformtools.dialog_ok(
            config.get_localized_string(59985) % e.channel,
            config.get_localized_string(60013) % e.url)
    except Exception as e:
        import traceback
        from core import scrapertools

        logger.error(traceback.format_exc())

        patron = 'File "' + os.path.join(config.get_runtime_path(), "channels",
                                         "").replace("\\",
                                                     "\\\\") + r'([^.]+)\.py"'
        Channel = scrapertools.find_single_match(traceback.format_exc(),
                                                 patron)

        if Channel or e.__class__ == logger.ChannelScraperException:
            if item.url:
                if platformtools.dialog_yesno(
                        config.get_localized_string(60087) % Channel,
                        config.get_localized_string(60014),
                        nolabel='ok',
                        yeslabel=config.get_localized_string(70739)):
                    run(Item(action="open_browser", url=item.url))
            else:
                platformtools.dialog_ok(
                    config.get_localized_string(60087) % Channel,
                    config.get_localized_string(60014))
        else:
            if platformtools.dialog_yesno(config.get_localized_string(60038),
                                          config.get_localized_string(60015)):
                run(Item(channel="setting", action="report_menu"))
def execute_sql_kodi(sql):
    """
    Ejecuta la consulta sql contra la base de datos de kodi
    @param sql: Consulta sql valida
    @type sql: str
    @return: Numero de registros modificados o devueltos por la consulta
    @rtype nun_records: int
    @return: lista con el resultado de la consulta
    @rtype records: list of tuples
    """
    logger.info()
    file_db = ""
    nun_records = 0
    records = None

    # Buscamos el archivo de la BBDD de videos segun la version de kodi
    video_db = config.get_platform(True)['video_db']
    if video_db:
        file_db = filetools.join(xbmc.translatePath("special://userdata/Database"), video_db)

    # metodo alternativo para localizar la BBDD
    if not file_db or not filetools.exists(file_db):
        file_db = ""
        for f in filetools.listdir(xbmc.translatePath("special://userdata/Database")):
            path_f = filetools.join(xbmc.translatePath("special://userdata/Database"), f)

            if filetools.isfile(path_f) and f.lower().startswith('myvideos') and f.lower().endswith('.db'):
                file_db = path_f
                break

    if file_db:
        logger.info("Archivo de BD: %s" % file_db)
        conn = None
        try:
            import sqlite3
            conn = sqlite3.connect(file_db)
            cursor = conn.cursor()

            logger.info("Ejecutando sql: %s" % sql)
            cursor.execute(sql)
            conn.commit()

            records = cursor.fetchall()
            if sql.lower().startswith("select"):
                nun_records = len(records)
                if nun_records == 1 and records[0][0] is None:
                    nun_records = 0
                    records = []
            else:
                nun_records = conn.total_changes

            conn.close()
            logger.info("Consulta ejecutada. Registros: %s" % nun_records)

        except:
            logger.error("Error al ejecutar la consulta sql")
            if conn:
                conn.close()

    else:
        logger.debug("Base de datos no encontrada")

    return nun_records, records