Ejemplo n.º 1
0
def check_update_to_others(verbose=False, app=True):
    logger.info()
    
    try:
        list_folder = os.listdir(os.path.join(config.get_runtime_path(), 'tools'))
        for folder in list_folder:
            in_folder = os.path.join(config.get_runtime_path(), 'tools', folder)
            if not os.path.isdir(in_folder):
                continue

            out_folder = os.path.join(config.translatePath('special://home/addons'), folder)
            if os.path.exists(out_folder):
                
                copytree(in_folder, out_folder)
                
                logger.info('%s updated' % folder)
    except:
        logger.error('Error al actualizar OTROS paquetes')
        logger.error(traceback.format_exc())
        
    if app:
        try:
            from lib import alfa_assistant
            res, addonid = alfa_assistant.update_alfa_assistant(verbose=verbose)
        except:
            logger.error("Alfa Assistant.  Error en actualización")
            logger.error(traceback.format_exc())
Ejemplo n.º 2
0
    def check_addon_monitor():
        logger.info()

        # Obtiene el íntervalo entre actualizaciones y si se quieren mensajes
        try:
            timer = int(
                config.get_setting('addon_update_timer')
            )  # Intervalo entre actualizaciones, en Ajustes de Alfa
            if timer <= 0:
                try:
                    user_type = base64.b64decode(
                        config.get_setting('proxy_dev')).decode('utf-8')
                except:
                    user_type = 'user'
                if user_type == 'user':
                    config.set_setting(
                        'addon_update_timer',
                        12)  # Si es usuario se fuerza a 12 horas
                    timer = 12
                else:
                    return  # 0.  No se quieren actualizaciones
            verbose = config.get_setting('addon_update_message')
        except:
            logger.error(traceback.format_exc())
            timer = 12  # Por defecto cada 12 horas
            verbose = False  # Por defecto, sin mensajes
        timer = timer * 3600  # Lo pasamos a segundos

        if config.get_platform(
                True)['num_version'] >= 14:  # Si es Kodi, lanzamos el monitor
            monitor = xbmc.Monitor()
        else:  # Lanzamos solo una actualización y salimos
            check_addon_updates(verbose)  # Lanza la actualización
            return

        while not monitor.abortRequested(
        ):  # Loop infinito hasta cancelar Kodi

            check_addon_updates(verbose)  # Lanza la actualización

            if monitor.waitForAbort(
                    timer
            ):  # Espera el tiempo programado o hasta que cancele Kodi
                break  # Cancelación de Kodi, salimos

        check_update_to_others(
            verbose=False, app=False
        )  # Actualizamos otros add-ons antes de irnos, para el siguiente inicio
        #Borra el .zip de instalación de Alfa de la carpeta Packages, por si está corrupto, y que así se pueda descargar de nuevo
        version = 'plugin.video.alfa-%s.zip' % config.get_addon_version(
            with_fix=False, from_xml=True)
        packages_path = os.path.join(config.translatePath('special://home'),
                                     'addons', 'packages', version)
        if os.path.exists(packages_path):
            os.remove(packages_path)
        return
Ejemplo n.º 3
0
def check_update_to_others(verbose=False, app=True):
    logger.info()
    folder = ''
    folder_list = []

    try:
        list_folder = os.listdir(
            os.path.join(config.get_runtime_path(), 'tools'))
        for folder in sorted(list_folder):
            in_folder = os.path.join(config.get_runtime_path(), 'tools',
                                     folder)
            if not os.path.isdir(in_folder):
                continue
            if 'patch#' in folder:
                for folder_patch in sorted(os.listdir(in_folder)):
                    in_folder_patch = os.path.join(in_folder, folder_patch)
                    if not os.path.isdir(in_folder):
                        continue
                    folder_list += [os.path.join(folder, folder_patch)]
            else:
                folder_list += [folder]

        for folder in folder_list:
            in_folder = os.path.join(config.get_runtime_path(), 'tools',
                                     folder)
            out_folder = os.path.join(
                config.translatePath('special://home/addons'),
                os.path.split(in_folder)[1])
            if not os.path.exists(out_folder):
                continue
            if not check_dependencies(in_folder):
                continue

            logger.info('Updating: %s' % folder, force=True)
            copytree(in_folder, out_folder)
            if os.path.exists(os.path.join(out_folder, ALFA_DEPENDENCIES)):
                os.remove(os.path.join(out_folder, ALFA_DEPENDENCIES))

    except:
        logger.error('Error al actualizar OTROS paquetes: %s' % folder)
        logger.error(traceback.format_exc())

    if app:
        try:
            from lib import alfa_assistant
            res, addonid = alfa_assistant.update_alfa_assistant(
                verbose=verbose)
        except:
            logger.error("Alfa Assistant.  Error en actualización")
            logger.error(traceback.format_exc())
Ejemplo n.º 4
0
def run(item=None):
    logger.info()

    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:
            if config.get_setting("start_page"):

                if not config.get_setting("custom_start"):

                    category = config.get_setting("category")

                    if isinstance(category, int):
                        category = config.get_localized_string(
                            config.get_setting("category")).lower()

                    item = Item(channel="news",
                                action="news",
                                news=category.lower(),
                                startpage=True)
                else:
                    from channels import side_menu
                    item = Item()
                    item = side_menu.check_user_home(item)
                    item.startpage = True
            else:
                item = Item(channel="channelselector",
                            action="getmainlist",
                            viewmode="movie")
        if not config.get_setting('show_once'):
            from platformcode import configurator
            configurator.show_window()

    logger.info(item.tostring())

    # If item has no action, stops here
    if item.action == "":
        logger.info("Item sin accion")
        return

    # Cleans infoLabels["playcount"] if set by generictools
    if item.video_path:
        item.infoLabels["playcount"] = 1
        del item.infoLabels["playcount"]

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

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

        elif item.channel == 'channelselector':
            import channelselector

            # Action for addon install on channelselector
            if item.action == "install_alfa":
                channelselector.install_alfa()

            else:
                # Action for main menu in channelselector
                if item.action == "getmainlist":
                    itemlist = channelselector.getmainlist()

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

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

                platformtools.render_items(itemlist, item)

        elif item.action == "keymap":
            from platformcode import keymaptools
            if item.open:
                return keymaptools.open_shortcut_menu()
            else:
                return keymaptools.set_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 == "function":
            """
            {
                "action": "function",
                "folder": "lib",
                "function": "alfa_assistant",
                "method": "install_alfa_assistant",
                "options": "auto"
            }
            """
            # Checks if function file exists
            function_file = os.path.join(config.get_runtime_path(),
                                         item.folder, item.function + ".py")
            logger.info("function_file=%s" % function_file)

            function = None

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

                logger.info(
                    "Running function %s(%s) | %s" %
                    (function.__name__, item.options, function.__file__))

                getattr(function, item.method)(item.options)

            else:
                logger.error(
                    "ERROR Running function %s(%s) | %s" %
                    (function.__name__, item.options, function.__file__))

        # Action in certain channel specified in "action" and "channel" parameters
        else:

            # Entry point for a channel is the "mainlist" action, so here we check parental control
            if item.action == "mainlist":

                # Parental control
                # If it is an adult channel, and user has configured pin, asks for it
                if channeltools.is_adult(item.channel) and config.get_setting(
                        "adult_request_password"):
                    tecleado = platformtools.dialog_input(
                        "", config.get_localized_string(60334), True)
                    if tecleado is None or tecleado != config.get_setting(
                            "adult_password"):
                        return

            # # Actualiza el canal individual
            # if (item.action == "mainlist" and item.channel != "channelselector" and
            #             config.get_setting("check_for_channel_updates") == True):
            #     from core import updater
            #     updater.update_channel(item.channel)

            # Checks if channel exists
            channel_file = os.path.join(config.get_runtime_path(), 'channels',
                                        item.channel + ".py")
            logger.info("channel_file=%s" % channel_file)

            channel = None

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

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

            if item.channel == "test" and item.contentChannel:
                if item.parameters == "test_channel":
                    getattr(channel, item.action)(item.contentChannel)

            # Calls redirection if Alfavorites findvideos, episodios, seasons
            if item.context and 'alfavorites' in str(item.context) \
                            and item.action in ['findvideos', 'episodios', 'seasons', 'play']:
                try:
                    from lib import generictools
                    item, it, overwrite = generictools.redirect_clone_newpct1(
                        item)
                except:
                    import traceback
                    logger.error(traceback.format_exc())

            # Special play action
            if item.action == "play":
                #define la info para trakt
                try:
                    trakt_tools.set_trakt_info(item)
                except:
                    pass
                logger.info("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.info("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 canal
                    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.info("Executing core 'play' method")
                    platformtools.play_video(item)

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

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

                # If not, uses the generic findvideos function
                else:
                    logger.info("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":
                videolibrarytools.add_movie(item)

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

            # Special action for downloading all episodes from a serie
            elif item.action == "download_all_episodes":
                from channels 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":
                logger.info("item.action=%s" % item.action.upper())

                # last_search = ""
                # last_search_active = config.get_setting("last_search", "search")
                # if last_search_active:
                #     try:
                #         current_saved_searches_list = list(config.get_setting("saved_searches_list", "search"))
                #         last_search = current_saved_searches_list[0]
                #     except:
                #         pass

                last_search = channeltools.get_channel_setting(
                    'Last_searched', 'search', '')

                tecleado = platformtools.dialog_input(last_search)

                if tecleado is not None:
                    if "http" not in tecleado:
                        channeltools.set_channel_setting(
                            'Last_searched', tecleado, 'search')
                    itemlist = channel.search(item, tecleado)
                else:
                    return

                platformtools.render_items(itemlist, item)

            # For all other actions
            else:
                logger.info("Executing channel '%s' method" % item.action)
                itemlist = getattr(channel, item.action)(item)
                if config.get_setting('trakt_sync'):
                    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)
                elif not config.get_setting('install_trakt'):
                    config.set_setting('install_trakt', True)

                platformtools.render_items(itemlist, item)

    except urllib2.URLError as e:
        import traceback
        logger.error(traceback.format_exc())

        # Grab inner and third party errors
        if hasattr(e, 'reason'):
            logger.error("Razon del error, codigo: %s | Razon: %s" %
                         (str(e.reason[0]), str(e.reason[1])))
            texto = config.get_localized_string(
                30050)  # "No se puede conectar con el sitio web"
            platformtools.dialog_ok("alfa", texto)

        # Grab server response errors
        elif hasattr(e, 'code'):
            logger.error("Codigo de error HTTP : %d" % e.code)
            # "El sitio web no funciona correctamente (error http %d)"
            platformtools.dialog_ok(
                "alfa",
                config.get_localized_string(30051) % e.code)
    except WebErrorException as e:
        import traceback
        logger.error(traceback.format_exc())

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

        platformtools.dialog_ok(
            config.get_localized_string(59985) + canal,
            config.get_localized_string(60013) % (e))
    except:
        import traceback
        logger.error(traceback.format_exc())

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

        try:
            if config.get_platform(True)['num_version'] < 14:
                log_name = "xbmc.log"
            else:
                log_name = "kodi.log"
            log_message = config.get_localized_string(
                50004) + config.translatePath("special://logpath") + log_name
        except:
            log_message = ""

        if canal:
            platformtools.dialog_ok(
                config.get_localized_string(60087) % canal,
                config.get_localized_string(60014), log_message)
        else:
            platformtools.dialog_ok(config.get_localized_string(60038),
                                    config.get_localized_string(60015),
                                    log_message)