Beispiel #1
0
def call_browser(item, lookup=False):
    from lib import generictools

    if lookup:
        browser, resultado = generictools.call_browser(item.url, lookup=lookup)
    else:
        browser, resultado = generictools.call_browser(item.url)

    return browser, resultado
Beispiel #2
0
def mainlist(item):
    logger.info()

    itemlist = list()

    if alfa_assistant.is_alfa_installed():

        autoplay.init(item.channel, list_servers, list_quality)

        itemlist.append(Item(channel=item.channel, action="novedades_episodios", title="Últimos episodios",
                             url=HOST+'anime-online.html', thumbnail="https://i.imgur.com/w941jbR.png"))

        itemlist.append(Item(channel=item.channel, action="novedades_anime", title="Últimos animes",
                             url=HOST+'anime-online.html', thumbnail="https://i.imgur.com/hMu5RR7.png"))

        itemlist.append(Item(channel=item.channel, action="listado", title="Animes",
                             url=HOST + "animes/nombre/lista", thumbnail='https://i.imgur.com/50lMcjW.png'))

        itemlist.append(Item(channel=item.channel, action="search_section",
                             title="Géneros", url=HOST + "animes",
                             extra="genre", thumbnail='https://i.imgur.com/Xj49Wa7.png'))

        itemlist.append(Item(channel=item.channel, action="search", title="Buscar...",
                             thumbnail='https://i.imgur.com/4jH5gpT.png'))


        itemlist = renumbertools.show_option(item.channel, itemlist)

        autoplay.show_option(item.channel, itemlist)
    else:
        from lib import generictools
        browser, res = generictools.call_browser('', lookup=True)
        if not browser:
            action = ''
        else:
            action = 'call_browser'
        from channelselector import get_thumb
        from core import channeltools
        channel_name = channeltools.get_channel_parameters(item.channel)["title"]
        itemlist.append(Item(channel=item.channel, action=action, title="Para utilizar {} se requiere Alfa Assistant. [COLOR=yellow]Haz clic para + info[/COLOR] [COLOR=green](https://alfa-addon.com/threads/manual-de-alfa-assistant-herramienta-de-apoyo.3797/)[/COLOR]".format(channel_name),
                             thumbnail=get_thumb("update.png"), url="https://alfa-addon.com/threads/manual-de-alfa-assistant-herramienta-de-apoyo.3797/"))

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

    if alfa_assistant.is_alfa_installed():

        data = httptools.downloadpage(item.url).data
        bloque = scrapertools.find_single_match(data, 'Server</span>(.*?)id="choose_quality"')
        matches = scrapertools.find_multiple_matches(bloque, '<option sv="[^"]+" value="([^"]+)"')
        headers = {"Referer" : item.url}

        for url in matches:
            xserver = scrapertools.find_single_match(url, 's=([a-zA-Z0-9]+)')
            source = HOST + "get_video_info_v2?s=%s" % xserver
            link = get_link(source, url)
            if link:
                itemlist.append(Item(channel=item.channel, action="play", url=link, 
                                title=xserver.capitalize(),plot=item.plot, thumbnail=item.thumbnail,
                                contentTitle=item.title, language='VOSE', server="directo"))
        #~itemlist = servertools.get_servers_itemlist(itemlist, lambda x: x.title % x.server.capitalize())

        # Requerido para AutoPlay
        autoplay.start(itemlist, item)
    else:
        from lib import generictools
        browser, res = generictools.call_browser('', lookup=True)
        if not browser:
            action = ''
        else:
            action = 'call_browser'
        from channelselector import get_thumb
        from core import channeltools
        channel_name = channeltools.get_channel_parameters(item.channel)["title"]
        itemlist.append(Item(channel=item.channel, action=action, title="Para utilizar {} se requiere Alfa Assistant. [COLOR=yellow]Haz clic para + info[/COLOR] [COLOR=green](https://alfa-addon.com/threads/manual-de-alfa-assistant-herramienta-de-apoyo.3797/)[/COLOR]".format(channel_name),
                             thumbnail=get_thumb("update.png"), url="https://alfa-addon.com/threads/manual-de-alfa-assistant-herramienta-de-apoyo.3797/"))

    return itemlist
Beispiel #4
0
def getmainlist(view="thumb_"):
    logger.info()
    itemlist = list()

    # Añade los canales que forman el menú principal

    itemlist.append(
        Item(title=config.get_localized_string(30130),
             channel="news",
             action="mainlist",
             thumbnail=get_thumb("news.png", view),
             category=config.get_localized_string(30119),
             viewmode="thumbnails",
             context=[{
                 "title": config.get_localized_string(70285),
                 "channel": "news",
                 "action": "news_setting"
             }]))

    itemlist.append(
        Item(title=config.get_localized_string(30118),
             channel="channelselector",
             action="getchanneltypes",
             thumbnail=get_thumb("channels.png", view),
             view=view,
             category=config.get_localized_string(30119),
             viewmode="thumbnails"))

    itemlist.append(
        Item(title="Lista de deseos",
             channel="info_popup",
             action="mainlist",
             thumbnail=get_thumb("wishlist.png", view),
             category="wishlist",
             viewmode="thumbnails",
             context=[{
                 "title": "Configurar Lista de deseos",
                 "channel": "info_popup",
                 "action": "show_settings"
             }]))

    itemlist.append(
        Item(title=config.get_localized_string(70527),
             channel="alfavorites",
             action="mainlist",
             thumbnail=get_thumb("mylink.png", view),
             view=view,
             category=config.get_localized_string(70527),
             viewmode="thumbnails"))

    itemlist.append(
        Item(title=config.get_localized_string(30103),
             channel="search",
             action="mainlist",
             thumbnail=get_thumb("search.png", view),
             category=config.get_localized_string(30119),
             viewmode="list",
             context=[{
                 "title": config.get_localized_string(70286),
                 "channel": "search",
                 "action": "opciones",
                 "goto": True
             }]))

    itemlist.append(
        Item(title=config.get_localized_string(30102),
             channel="favorites",
             action="mainlist",
             thumbnail=get_thumb("favorites.png", view),
             category=config.get_localized_string(30102),
             viewmode="thumbnails"))

    if config.get_videolibrary_support():
        itemlist.append(
            Item(title=config.get_localized_string(30131),
                 channel="videolibrary",
                 action="mainlist",
                 thumbnail=get_thumb("videolibrary.png", view),
                 category=config.get_localized_string(30119),
                 viewmode="thumbnails",
                 context=[{
                     "title": config.get_localized_string(70287),
                     "channel": "videolibrary",
                     "action": "channel_config"
                 }]))

    itemlist.append(
        Item(title=config.get_localized_string(30101),
             channel="downloads",
             action="mainlist",
             thumbnail=get_thumb("downloads.png", view),
             viewmode="list",
             context=[{
                 "title": config.get_localized_string(70288),
                 "channel": "setting",
                 "config": "downloads",
                 "action": "channel_config"
             }]))

    thumb_setting = "setting_%s.png" % 0  # config.get_setting("plugin_updates_available")

    itemlist.append(
        Item(title=config.get_localized_string(30100),
             channel="setting",
             action="mainlist",
             thumbnail=get_thumb(thumb_setting, view),
             category=config.get_localized_string(30100),
             viewmode="list"))

    if config.is_xbmc():
        itemlist.append(
            Item(title=config.get_localized_string(70761),
                 channel="setting",
                 action="report_menu",
                 thumbnail=get_thumb("error.png", view),
                 category=config.get_localized_string(30104),
                 viewmode="list"))

    itemlist.append(
        Item(title=config.get_localized_string(30104) + " (" +
             config.get_localized_string(20000) + " " +
             config.get_addon_version(with_fix=False, from_xml=True) + ")",
             channel="help",
             action="mainlist",
             thumbnail=os.path.join(config.get_runtime_path(), "resources",
                                    'Screenshot.jpg'),
             category=config.get_localized_string(30104),
             viewmode="list"))

    try:
        versiones = config.get_versions_from_repo()
    except:
        versiones = {}
        logger.error(traceback.format_exc())
    if versiones and config.get_addon_version(with_fix=False,
                                              from_xml=True) != versiones.get(
                                                  'plugin.video.alfa', ''):
        itemlist.append(
            Item(
                title=
                "[COLOR hotpink][B]Actualizar a versión[/B][/COLOR] [COLOR gold][B]%s[/B][/COLOR] (versión instalada: %s)"
                % (versiones['plugin.video.alfa'],
                   config.get_addon_version(with_fix=False, from_xml=True)),
                channel="channelselector",
                action="install_alfa",
                thumbnail=os.path.join(config.get_runtime_path(), "resources",
                                       'Screenshot.jpg'),
                category=config.get_localized_string(30104),
                viewmode="list"))

    from lib import generictools
    browser, res = generictools.call_browser('', lookup=True)
    if not browser:
        action = ''
        itemlist.append(
            Item(channel="setting",
                 action=action,
                 url='https://alfa-addon.com/foros/tutoriales.11/',
                 title=config.get_localized_string(70758) + " [COLOR gold](" +
                 config.get_localized_string(70759) +
                 ": Chrome, Firefox, Opera)[/COLOR]:",
                 thumbnail=get_thumb("help.png", view),
                 unify=False,
                 folder=False,
                 category=config.get_localized_string(30104),
                 viewmode="list"))
    else:
        action = 'call_browser'
        itemlist.append(
            Item(channel="setting",
                 action=action,
                 url='https://alfa-addon.com/foros/tutoriales.11/',
                 title=config.get_localized_string(70758) +
                 (" [COLOR limegreen]" + config.get_localized_string(70760) +
                  "[/COLOR]") % browser,
                 thumbnail=get_thumb("help.png", view),
                 unify=False,
                 folder=False,
                 category=config.get_localized_string(30104),
                 viewmode="list"))

    itemlist.append(
        Item(
            channel="setting",
            action=action,
            url=
            'https://alfa-addon.com/threads/si-tienes-android-10-y-kodi-19-vas-a-tener-problemas-con-los-torrents.4211/',
            title=
            "-     [COLOR yellow]Si tienes Android 10+ y Kodi 19+ vas a tener problemas con los torrents[/COLOR]   "
            +
            "https://alfa-addon.com/threads/si-tienes-android-10-y-kodi-19-vas-a-tener-problemas-con-los-torrents.4211/",
            thumbnail=get_thumb("help.png", view),
            unify=False,
            folder=False,
            category=config.get_localized_string(30104),
            viewmode="list"))

    itemlist.append(
        Item(
            channel="setting",
            action=action,
            url=
            'https://alfa-addon.com/threads/torrest-el-gestor-de-torrents-definitivo.4085/',
            title=
            "-     [COLOR yellow]Torrest: el gestor de torrents definitivo[/COLOR]   "
            +
            "https://alfa-addon.com/threads/torrest-el-gestor-de-torrents-definitivo.4085/",
            thumbnail=get_thumb("help.png", view),
            unify=False,
            folder=False,
            category=config.get_localized_string(30104),
            viewmode="list"))

    return itemlist
Beispiel #5
0
def getmainlist(view="thumb_"):
    logger.info()
    itemlist = list()

    # Añade los canales que forman el menú principal

    get_string = config.get_localized_string
    addon_version = config.get_addon_version(with_fix=False, from_xml=True)

    itemlist.append(
        Item(
            title = get_string(30130),
            channel = "news",
            action = "mainlist",
            thumbnail = get_thumb("news.png", view),
            category = get_string(30119),
            viewmode = "thumbnails",
            context = [
                {
                    "title": get_string(70285),
                    "channel": "news", 
                    "action":"news_setting"
                }
            ]
        )
    )

    itemlist.append(
        Item(
            title = get_string(30118),
            channel = "channelselector",
            action = "getchanneltypes",
            thumbnail = get_thumb("channels.png", view),
            view = view,
            category = get_string(30119),
            viewmode = "thumbnails"
        )
    )

    itemlist.append(
        Item(
            title = get_string(80787),
            channel = "info_popup",
            action = "mainlist",
            thumbnail = get_thumb("wishlist.png", view),
            category = "wishlist",
            viewmode = "thumbnails",
            context = [
                {
                    "title": get_string(80788),
                    "channel": "info_popup",
                    "action": "show_settings"
                }
            ]
        )
    )

    itemlist.append(
        Item(
            title = get_string(70527),
            channel = "alfavorites",
            action ="mainlist",
            thumbnail = get_thumb("mylink.png", view),
            view = view,
            category = get_string(70527),
            viewmode = "thumbnails"
        )
    )

    itemlist.append(
        Item(
            title = get_string(30103),
            channel = "search",
            action = "mainlist",
            thumbnail = get_thumb("search.png", view),
            category = get_string(30119),
            viewmode = "list",
            context = [
                {
                    "title": get_string(70286),
                    "channel": "search",
                    "action": "opciones",
                    "goto": True
                }
            ]
        )
    )

    itemlist.append(
        Item(
            title = get_string(30102),
            channel = "favorites",
            action = "mainlist",
            thumbnail = get_thumb("favorites.png", view),
            category = get_string(30102),
            viewmode = "thumbnails"
        )
    )

    if config.get_videolibrary_support():
        itemlist.append(
            Item(
                title = get_string(30131),
                channel = "videolibrary",
                action = "mainlist",
                thumbnail = get_thumb("videolibrary.png", view),
                category = get_string(30119),
                viewmode = "thumbnails",
                context = [
                    {
                        "title": get_string(70287),
                        "channel": "videolibrary",
                        "action": "channel_config"
                    }
                ]
            )
        )

    itemlist.append(
        Item(
            title = get_string(30101),
            channel = "downloads",
            action = "mainlist",
            thumbnail = get_thumb("downloads.png", view),
            viewmode = "list",
            context = [
                {
                    "title": get_string(70288),
                    "channel": "setting",
                    "config": "downloads",
                    "action": "channel_config"
                }
            ]
        )
    )

    # fix = config.get_addon_version_fix()
    thumb_setting = "setting_%s.png" % 0 # int(fix[4:])

    itemlist.append(
        Item(
            title = get_string(30100),
            channel = "setting",
            action = "mainlist",
            thumbnail = get_thumb(thumb_setting, view),
            category = get_string(30100),
            viewmode = "list"
        )
    )

    if config.is_xbmc():
        itemlist.append(
            Item(
                title = get_string(70761),
                channel = "report",
                action = "mainlist",
                thumbnail = get_thumb("error.png", view),
                category = get_string(30104),
                viewmode = "list"
            )
        )

    itemlist.append(
        Item(
            title = '{} ({} {})'.format(get_string(30104), get_string(20000), addon_version),
            channel = "help",
            action = "mainlist",
            thumbnail = os.path.join(config.get_runtime_path(), "resources", 'Screenshot.jpg'),
            category = get_string(30104),
            viewmode = "list"
        )
    )
                         
    try:
        versiones = config.get_versions_from_repo()
    except:
        versiones = {}
        import traceback
        logger.error(traceback.format_exc())

    if versiones and addon_version != versiones.get('plugin.video.alfa', ''):
        itemlist.append(
            Item(
                title = "[COLOR hotpink][B]Actualizar a versión[/B][/COLOR] [COLOR gold][B]%s[/B][/COLOR] (versión instalada: %s)" %  (versiones['plugin.video.alfa'], addon_version),
                channel = "channelselector",
                action = "install_alfa",
                thumbnail = os.path.join(config.get_runtime_path(), "resources", 'Screenshot.jpg'),
                category = get_string(30104),
                viewmode = "list"
            )
        )

    from lib import generictools
    browser, res = generictools.call_browser('', lookup=True)
    browser_dict = {}

    if browser:
        browser_dict['action'] = 'call_browser'
        browser_dict['title'] = '{} [COLOR limegreen]{}[/COLOR]'.format(get_string(70758), get_string(70760) % browser)
    else:
        browser_dict['action'] = ''
        browser_dict['title'] = '{} [COLOR gold]({}: Chrome, Firefox, Opera)[/COLOR]:'.format(get_string(70758), get_string(70759))

    itemlist.append(
        Item(
            channel = "setting",
            action = browser_dict['action'],
            url = 'https://alfa-addon.com/foros/tutoriales.11/', 
            title = browser_dict['title'],
            thumbnail = get_thumb("help.png", view),
            unify = False,
            folder = False, 
            category = get_string(30104),
            viewmode = "list"
        )
    )
    
    itemlist.append(
        Item(
            channel = "setting",
            action = browser_dict['action'],
            url = 'https://alfa-addon.com/threads/dontorrent-potenciado-con-busquedas-en-btdigg.4798/', 
            title = "-     [COLOR yellow]Dontorrent potenciado con búsquedas en [COLOR limegreen]BT[/COLOR][COLOR red]Digg[/COLOR][/COLOR]   " + 
                    "https://alfa-addon.com/threads/dontorrent-potenciado-con-busquedas-en-btdigg.4798/",
            thumbnail = get_thumb("on_the_air.png", view),
            unify = False,
            folder = False,
            category = get_string(30104),
            viewmode = "list"
        )
    )

    return itemlist
Beispiel #6
0
def install_alfa_assistant(update=False, remote='', verbose=False):
    if update:
        logger.info('update=%s' % str(update))
    # Si ya está instalada, devolvemos el control
    app_name = 'com.alfa.alfamobileassistant'
    if not verbose: verbose = config.get_setting('addon_update_message')        # Verbose en la actualización/instalación
    assistant_flag_install = config.get_setting('assistant_flag_install', default=True)
    addonid = 'alfa-mobile-assistant'
    download = addonid + '.apk'
    package = addonid + '.apk'
    version = addonid + '.version'
    forced_menu = False
    respuesta = False
    alfa_s = True
    addons_path = config.get_runtime_path()
    if filetools.exists(filetools.join(addons_path, 'channels', 'custom.py')):
        alfa_s = False

    if not remote:
        ANDROID_STORAGE = os.getenv('ANDROID_STORAGE')
        if not ANDROID_STORAGE: ANDROID_STORAGE = '/storage'
    else:
        # Remote es la url de un servidor FTP o SMB activo que apunta a la ruta "/storage" del dispositivo Android
        ANDROID_STORAGE = remote
        if ANDROID_STORAGE.endswith('/'):
            ANDROID_STORAGE = ANDROID_STORAGE[:-1]
    apk_files = '%s/%s/%s/%s/%s/%s' % (ANDROID_STORAGE, 'emulated', '0', 'Android', 'data', app_name)
    if ASSISTANT_MODE == 'este' and not filetools.exists(filetools.dirname(apk_files)):
        apk_files_alt = scrapertools.find_single_match(os.getenv('HOME'), '(.*?)\/\w*.\w*.\w*\/files')
        logger.info('HOME: ' + apk_files_alt)
        if apk_files_alt and filetools.exists(apk_files_alt):
            apk_files = '%s/%s' % (apk_files_alt, app_name)

    version_path = filetools.join(config.get_data_path(), version)
    version_act = filetools.read(version_path, silent=True)
    if not version_act: version_act = '0.0.0'
    
    # Averiguamos si es instalacción, update, o forzado desde el Menú de Ajustes
    if not update and ASSISTANT_MODE == 'este' and filetools.exists(apk_files):
        return version_act, app_name
    if ASSISTANT_MODE == 'este' and not update:
        check_permissions_alfa_assistant()                                      # activamos la app por si no se ha inicializado
        time.sleep(1)
        if filetools.exists(apk_files):
            return version_act, app_name
    # Mirarmos si la app está activa y obtenemos el nº de versión
    version_dict = get_generic_call('getWebViewInfo', timeout=2-EXTRA_TIMEOUT, alfa_s=True)
    if isinstance(version_dict, dict):
        version_app = version_dict.get('assistantVersion', '')
        try:
            android_version = int(scrapertools.find_single_match(version_dict.get('userAgent', ''), r"Android\s*(\d+)"))
        except:
            android_version = 8
    else:
        version_app = version_dict
        android_version = 8
    if version_app and not update:
        return version_app, app_name
    
    if version_app:
        app_active = True
    else:
        app_active = False
        if ASSISTANT_MODE == "este":
            execute_in_alfa_assistant_with_cmd('open')                          # activamos la app por si no se ha inicializado
            time.sleep(5)
            version_dict = get_generic_call('getWebViewInfo', timeout=2-EXTRA_TIMEOUT, alfa_s=True)
            if isinstance(version_dict, dict):
                version_app = version_dict.get('assistantVersion', '')
                try:
                    android_version = int(scrapertools.find_single_match(version_dict.get('userAgent', ''), r"Android\s*(\d+)"))
                except:
                    android_version = 8
            else:
                version_app = version_dict
                android_version = 8
    version_actual = filetools.read(version_path, silent=True)
    if not version_actual and version_app:
        version_actual = version_app
        filetools.write(version_path, version_actual, mode='wb', silent=True)
    elif not version_actual:
        version_actual = '0.0.0'

    if ASSISTANT_MODE != 'este':
        if not version_app:
            if verbose or (update and not isinstance(update, bool)):
                platformtools.dialog_notification("Active Alfa Assistant", 
                            "o Instale manualmente desde [COLOR yellow]https://bit.ly/2Zwpfzq[/COLOR]")
            logger.info("Active Alfa Assistant, o Instale manualmente desde [COLOR yellow]https://bit.ly/2Zwpfzq[/COLOR]", force=True)
            config.set_setting('assistant_flag_install', False)
            return version_app, app_name
        else:
            config.set_setting('assistant_flag_install', True)
            if not update:
                return version_app, app_name
    elif not update and not assistant_flag_install and not filetools.exists(apk_files):
        logger.info('NO está instalada. El usuario no quiere instalaciñon automática: %s' % app_name)
        return False, app_name
    elif update and isinstance(update, bool) and not filetools.exists(apk_files):
        logger.info('NO está instalada. No se va a actualizar: %s' % app_name)
        return False, app_name
    elif update and not isinstance(update, bool) and not filetools.exists(apk_files):
        logger.info('NO está instalada. Viene del Menú y se va a instalar: %s' % app_name)
        update = False
        forced_menu = True
    elif not remote and not xbmc.getCondVisibility("system.platform.android"):
        logger.info('El sistema local no es Android: %s' % app_name)
        return False, app_name

    logger.info('assistant_mode=%s, update=%s, forced_menu=%s, assistant_flag_install=%s, version_actual=%s, version_app=%s, android=%s, app_active=%s' \
            % (ASSISTANT_MODE, str(update), str(forced_menu), str(assistant_flag_install), version_actual, \
            version_app, str(android_version), str(app_active)))
    
    # Si no está instalada, o se quiere actualizar, empezamos el proceso
    alfa_assistant_pwd = ''
    assistant_urls = ['https://github.com/alfa-addon/alfa-repo/raw/master/downloads/assistant/%s' % version, \
            'https://bitbucket.org/alfa_addon/alfa-repo/raw/master/downloads/assistant/%s' % version]
    
    apk_updated = filetools.join(addons_path, 'tools')
    apk_path = filetools.join(apk_updated, download)
    apk_apk = filetools.join(apk_updated, package)
    upk_install_path = filetools.join('special://xbmc/', 'files').replace('/cache/apk/assets', '')
    if not remote:
        apk_install = filetools.join(ANDROID_STORAGE, 'emulated', '0', 'Download')
        apk_install_SD = filetools.join(apk_install, package)
    else:
        apk_install = '%s/%s/%s/%s' % (ANDROID_STORAGE, 'emulated', '0', 'Download')
        apk_install_SD = '%s/%s' % (apk_install, package)

    if not update and not remote and not forced_menu:
        # Probamos a iniciar por si se ha instalado manualmente y no se ha iniciado la estrucutra de archivos
        check_permissions_alfa_assistant()
        try:
            command = ['pm', 'list', 'packages']
            p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            PM_LIST, error_cmd = p.communicate()
            if PY3 and isinstance(label_a, bytes):
                PM_LIST = PM_LIST.decode()
            if app_name in PM_LIST:
                logger.info('Ya instalada. Volvemos: %s' % app_name)
                return version_actual, app_name
        except:
            logger.error(traceback.format_exc(1))
    
    if not update and not forced_menu and not platformtools.dialog_yesno("Instalación Alfa Assistant", \
                    "¿Desea instalar la App [COLOR yellow][B]%s[/B][/COLOR]\n" % app_name +
                    " como ayuda para acceder a ciertos canales y servidores?"):
        config.set_setting('assistant_flag_install', False)
        return respuesta, app_name
    elif update and not isinstance(update, bool):
        platformtools.dialog_notification("Instalación Alfa Assistant", "Comienza la actualización")
    elif forced_menu:
        platformtools.dialog_notification("Instalación Alfa Assistant", "Comienza la instalación")

    # Comprobamos si el dispositivo está rooteado
    is_rooted = config.is_rooted(silent=True)                                   # ¡OJO! puede pedir permisos root en algunos dispositivos
    if is_rooted == 'rooted' and ASSISTANT_MODE == 'este':                      # El dispositivo esta rooteado?
        update_install = 'py'                                                   # Se actualiza desde esta función
    else:
        update_install = 'app'                                                  # Se actualiza desde la app
    cmd = 'update'                                                              # Comando de la app para auto actualizarse
    dataURI = 'Version:%s'                                                      # Versión a actualizar
    
    # Comprobamos si hay acceso a Github o BitBucket
    for assistant_rar in assistant_urls:
        response = httptools.downloadpage(assistant_rar, timeout=5, ignore_response_code=True, alfa_s=alfa_s, json_to_utf8=False)
        if response.sucess:
            break
    
    # Descargamos el archivo de version.  Si hay error avisamos, pero continuamos
    if not response.sucess:
        if update and isinstance(update, bool):
            logger.error("Error en la descarga de control de versión. No se puede actualizar: %s" % str(response.code))
            return respuesta, app_name
        platformtools.dialog_notification("Instalación Alfa Assistant", "Error en la descarga de control de versión. Seguimos")
        logger.error("Error en la descarga de control de versión. Seguimos...: %s" % str(response.code))

    #Si es una actualización programada, comprobamos las versiones de Github y de lo instalado
    if update and isinstance(update, bool):
        if version_actual != response.data:
            if version_app:
                version_actual = version_app
                filetools.write(version_path, version_actual, mode='wb', silent=True)
        if version_actual == response.data:
            if verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Ya está actualizado a version %s" % response.data)
            logger.info("Alfa Assistant ya actualizado a versión: %s" % response.data)
            if not app_active and ASSISTANT_MODE == "este":
                execute_in_alfa_assistant_with_cmd('quit')                      # desactivamos la app si no estaba iniciada
            return version_actual, app_name

    # Guardamos archivo de versión
    if remote:
        version_path = '%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s' % (ANDROID_STORAGE, 'emulated', '0', 'Android', 
                        'data', 'org.xbmc.kodi', 'files', '.kodi', 'addons', 'plugin.video.alfa', 
                        'tools', version)
        if not filetools.exists(filetools.dirname(version_path)):
            logger.error("Ruta a carpeta remota de versión no es estándar: %s" % version_path)
            version_path = ''
    version_old = version_actual
    version_actual = response.data
    if version_path:
        res = filetools.write(version_path, response.data, mode='wb', silent=True)
        if not res:
            if not update: platformtools.dialog_notification("Instalación Alfa Assistant", \
                            "Error en la escritura de control de versión. Seguimos...")
            logger.error("Error en la escritura de control de versión. Seguimos...: %s" % assistant_rar)

    # Descargamos y guardamos el .APK
    assistant_rar = assistant_rar.replace(version, download)                    # Sustituir en la url la versión por el apk
    res = False
    if not update: platformtools.dialog_notification("Instalación Alfa Assistant", "Descargando APK")
    logger.info('Descargando de_ %s' % assistant_rar)
    response = httptools.downloadpage(assistant_rar, timeout=5, ignore_response_code=True, alfa_s=alfa_s, json_to_utf8=False)
    if not response.sucess:
        if not update or verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Error en la descarga del .apk")
        response.data = ''
        logger.error("Error en la descarga del .apk: %s" % str(response.code))
    else:
        # Guardamos archivo descargado de APK
        res = filetools.write(apk_path, response.data, mode='wb', silent=True)
        if not res:
            if not update or verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Error en la escritura del APK")
            logger.error("Error en la escritura del APK: %s" % apk_path)
        
        else:
            if '.rar' in download:
                # Empezando la extracción del .rar del APK
                try:
                    import rarfile
                    archive = rarfile.RarFile(apk_path)
                    if alfa_assistant_pwd: archive.setpassword(alfa_assistant_pwd)
                    archive.extractall(apk_updated)
                except:
                    logger.error(traceback.format_exc(1))
            elif '.zip' in download:
                # Empezando la extracción del .rar del APK
                try:
                    import ziptools
                    archive = ziptools.ziptools()
                    #if alfa_assistant_pwd: archive.setpassword(alfa_assistant_pwd)      # No hay password en .zip
                    archive.extract(filetools.basename(apk_updated), filetools.dirname(apk_updated))
                except:
                    xbmc.executebuiltin('Extract("%s","%s")' % (filetools.basename(apk_updated), filetools.dirname(apk_updated)))
                    time.sleep(1)

            # Verificado si está el APK, y si está y es LOCAL lo instalamos
            if ASSISTANT_MODE == "este":
                res = filetools.copy(apk_apk, apk_install_SD, silent=True)
                if not res or not filetools.exists(apk_install_SD):
                    if not update or verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Error de Extracción o Copia %s" % package)
                    logger.error("Error de Extracción o copia %s" % package)
                
                # Si está rooteado se instala/actualiza directamente
                elif update_install == 'py' and res and filetools.exists(apk_install_SD):

                    # Instalamos: nueva o actualización. 
                    if not update: platformtools.dialog_notification("Instalación Alfa Assistant", "Installando %s" % package)
                    logger.info("Installing %s" % package)
                    
                    # Instalación Remota
                    if remote:
                        filetools.remove(apk_apk, silent=True)
                        platformtools.dialog_notification("Alfa Assistant: Descarga Remota terminada", "Instale manualmente desde: %s" % apk_install_SD)
                        logger.info("Alfa Assistant: Descarga Remota terminada. Instale manualmente desde: %s" % apk_install_SD)
                        return version_actual, app_name

                    # Instalación Local
                    if not filetools.exists(upk_install_path):
                        filetools.mkdir(upk_install_path)
                    upk_install_path = filetools.join(upk_install_path, package)
                    res = filetools.copy(apk_install_SD, upk_install_path, ch_mod='777')    # Copiamos APK a la partición del Sistema, y cambiamos permisos
                    if not res:
                        if not update or verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Error de Copia %s" % package)
                        logger.error(str(filetools.listdir(apk_install)))
                        logger.error(filetools.file_info(filetools.dirname(upk_install_path)))
                        logger.error(str(filetools.listdir(filetools.dirname(upk_install_path), file_inf=True)))
                    else:

                        # Intenta la instalación vía ROOT y si no funciona como NO ROOT
                        
                        # Marcamos la opción de instalación, -r si es actualización, -g (todos los permisos granted) si es instalación
                        if filetools.exists(apk_files):
                            pm_opt = '-r'
                        else:
                            pm_opt = '-g'
                        
                        # Listamos todas las opciones de comandos, según las variantes de Android
                        command_list = [
                                        ['adb', 'install', '%s' % upk_install_path],
                                        ['su', '-c', 'pm install %s %s' % (pm_opt, upk_install_path)],
                                        ['su', '-c', 'pm', 'install', pm_opt, '%s' % upk_install_path],
                                        ['su', '-0', 'pm install %s %s' % (pm_opt, upk_install_path)],
                                        ['su', '-0', 'pm', 'install', pm_opt, '%s' % upk_install_path]
                                       ]
                        
                        for command in command_list:
                            try:
                                logger.info(command, force=True)
                                p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                                output_cmd, error_cmd = p.communicate()
                                if error_cmd:
                                    if error_cmd.startswith('su:'): continue
                                    if update:
                                        ver_upd = get_generic_call('ping', timeout=2-EXTRA_TIMEOUT, alfa_s=True)
                                        if not ver_upd:
                                            execute_in_alfa_assistant_with_cmd('open')  # activamos la app por si no se ha inicializado
                                            time.sleep(5)
                                            ver_upd = get_generic_call('ping', timeout=2-EXTRA_TIMEOUT, alfa_s=True)
                                            execute_in_alfa_assistant_with_cmd('quit')
                                        if ver_upd == version_actual:
                                            logger.debug(str(error_cmd), force=True)
                                            error_cmd = ''
                                    else:
                                        check_permissions_alfa_assistant()
                                        time.sleep(1)
                                        if filetools.exists(apk_files):
                                            logger.debug(str(error_cmd), force=True)
                                            error_cmd = ''
                                    if error_cmd:
                                        logger.error(str(error_cmd))
                                    else:
                                        respuesta = version_actual
                                        break
                                else:
                                    respuesta = version_actual
                                    break
                            except Exception as e:
                                if not PY3:
                                    e = unicode(str(e), "utf8", errors="replace").encode("utf8")
                                logger.error('Command ERROR: %s, %s' % (str(command), str(e)))
                                continue
      
    # Ùltimo resorte: instalación manual desde GitHub o actualización desde la app
    if not respuesta and update:
        
        # Si hay que actualizar se verifica el vehículo de instalación
        logger.info("Instalación Alfa Assistant. Actualización desde la app de %s a %s" % (version_old, version_actual))
        version_mod = version_actual
        if not isinstance(update, bool):
            version_mod = '9.9.999'                                             # Intenta forzar la actualización si viene desde el Menú
        if ASSISTANT_MODE == "este":
            if android_version >= 10:
                app_active = False
                respuesta = execute_in_alfa_assistant_with_cmd(cmd, dataURI=dataURI % version_mod)
            else:
                if not app_active:
                    execute_in_alfa_assistant_with_cmd('openAndQuit')           # activamos la app por si no se ha inicializado
                    time.sleep(5)
                app_active = False
                respuesta = get_generic_call(cmd, version=version_mod, alfa_s=alfa_s)
        else:
            if app_active:
                respuesta = get_generic_call(cmd, version=version_mod, alfa_s=alfa_s)

        if not respuesta and ASSISTANT_MODE != "este":
            if verbose or not isinstance(update, bool):
                platformtools.dialog_notification("Instalación Alfa Assistant", "Intente la actualización manualmente %s" % version_actual)
            logger.info("Instalación Alfa Assistant. Intente la actualización manualmente %s" % version_actual)
            return False, app_name
        elif not respuesta:
            # Update local
            #respuesta = execute_in_alfa_assistant_with_cmd(cmd, dataURI=dataURI % version_mod)
            if not respuesta:
                if verbose or not isinstance(update, bool):
                    platformtools.dialog_notification("Instalación Alfa Assistant", "Actualización en error %s. REINTENTANDO" % version_actual)
                logger.info("Instalación Alfa Assistant. Actualización en error %s. REINTENTANDO" % version_actual)
        else:
            respuesta = version_actual
        
    if not respuesta:
        config.set_setting('assistant_flag_install', False)                     # No vuelve a intentar la instalación
        try:
            #xbmc.executebuiltin('StartAndroidActivity("","android.intent.action.VIEW","application/vnd.android.package-archive","file:%s")' % apk_install_SD)
            
            if ASSISTANT_MODE == "este":
                from lib import generictools
                assistant_rar = assistant_rar.replace('/raw/', '/tree/')            # Apuntar a la web de descargas
                browser, res = generictools.call_browser(assistant_rar, lookup=True)
                if browser:
                    filetools.remove(apk_install_SD, silent=True)
                    platformtools.dialog_ok("Alfa Assistant: Instale desde [COLOR yellow]%s[/COLOR]" % browser.capitalize(), 
                                    "O Instale manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_install_SD)
                    logger.info('Browser: %s, Ruta: %s' % (browser.capitalize(), apk_install_SD))
                    time.sleep(5)
                    browser, res = generictools.call_browser(assistant_rar, dataType='application/vnd.android.package-archive')
                    filetools.remove(apk_path, silent=True)
                    filetools.remove(upk_install_path, silent=True)
                else:
                    logger.error('Error de Instalación: NO Browser, Ruta: %s' % apk_install_SD)
                    raise
            else:
                logger.error('Error de Instalación: no se puede instalar en remoto: %s' % ASSISTANT_SERVER)
                raise
        except:
            if ASSISTANT_MODE == "este":
                platformtools.dialog_ok("Alfa Assistant: Error", "Instale manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_install_SD)
                logger.error("Alfa Assistant: Error. Instale manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_install_SD)
                filetools.remove(apk_path, silent=True)
                filetools.remove(upk_install_path, silent=True)
            else:
                platformtools.dialog_ok("Alfa Assistant: Error", "Copie a Android manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_apk)
                logger.error("Alfa Assistant: Error. Copie a Android manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_apk)
            logger.error(traceback.format_exc(1))

    if respuesta:
        if update:
            if verbose or not isinstance(update, bool): platformtools.dialog_notification("Alfa Assistant", \
                                "Actualización con exito: %s" % respuesta)
            logger.info("Actualización terminada con éxito: %s" % respuesta)
        else:
            platformtools.dialog_notification("Alfa Assistant", "Instalación con exito: %s" % respuesta)
            logger.info("Instalación terminada con éxito: %s" % respuesta)
        filetools.remove(apk_path, silent=True)
        filetools.remove(apk_install_SD, silent=True)
        filetools.remove(upk_install_path, silent=True)
        if not update and not forced_menu:
            time.sleep(1)
            check_permissions_alfa_assistant()
            time.sleep(1)
        if app_active and ASSISTANT_MODE == "este":
            execute_in_alfa_assistant_with_cmd('open')                          # re-activamos la app para dejarla como estaba
        
    return respuesta, app_name
Beispiel #7
0
def getmainlist(view="thumb_"):
    logger.info()
    itemlist = list()

    # Añade los canales que forman el menú principal
    itemlist.append(
        Item(title=config.get_localized_string(30130),
             channel="news",
             action="mainlist",
             thumbnail=get_thumb("news.png", view),
             category=config.get_localized_string(30119),
             viewmode="thumbnails",
             context=[{
                 "title": config.get_localized_string(70285),
                 "channel": "news",
                 "action": "menu_opciones",
                 "goto": True
             }]))

    itemlist.append(
        Item(title=config.get_localized_string(30118),
             channel="channelselector",
             action="getchanneltypes",
             thumbnail=get_thumb("channels.png", view),
             view=view,
             category=config.get_localized_string(30119),
             viewmode="thumbnails"))

    itemlist.append(
        Item(title=config.get_localized_string(70527),
             channel="alfavorites",
             action="mainlist",
             thumbnail=get_thumb("mylink.png", view),
             view=view,
             category=config.get_localized_string(70527),
             viewmode="thumbnails"))

    itemlist.append(
        Item(title=config.get_localized_string(30103),
             channel="search",
             action="mainlist",
             thumbnail=get_thumb("search.png", view),
             category=config.get_localized_string(30119),
             viewmode="list",
             context=[{
                 "title": config.get_localized_string(70286),
                 "channel": "search",
                 "action": "opciones",
                 "goto": True
             }]))

    itemlist.append(
        Item(title=config.get_localized_string(30102),
             channel="favorites",
             action="mainlist",
             thumbnail=get_thumb("favorites.png", view),
             category=config.get_localized_string(30102),
             viewmode="thumbnails"))

    if config.get_videolibrary_support():
        itemlist.append(
            Item(title=config.get_localized_string(30131),
                 channel="videolibrary",
                 action="mainlist",
                 thumbnail=get_thumb("videolibrary.png", view),
                 category=config.get_localized_string(30119),
                 viewmode="thumbnails",
                 context=[{
                     "title": config.get_localized_string(70287),
                     "channel": "videolibrary",
                     "action": "channel_config"
                 }]))

    itemlist.append(
        Item(title=config.get_localized_string(30101),
             channel="downloads",
             action="mainlist",
             thumbnail=get_thumb("downloads.png", view),
             viewmode="list",
             context=[{
                 "title": config.get_localized_string(70288),
                 "channel": "setting",
                 "config": "downloads",
                 "action": "channel_config"
             }]))

    thumb_setting = "setting_%s.png" % 0  # config.get_setting("plugin_updates_available")

    itemlist.append(
        Item(title=config.get_localized_string(30100),
             channel="setting",
             action="mainlist",
             thumbnail=get_thumb(thumb_setting, view),
             category=config.get_localized_string(30100),
             viewmode="list"))

    if config.is_xbmc():
        itemlist.append(
            Item(title="Reportar un fallo",
                 channel="setting",
                 action="report_menu",
                 thumbnail=get_thumb("error.png", view),
                 category=config.get_localized_string(30104),
                 viewmode="list"))

    itemlist.append(
        Item(title=config.get_localized_string(30104) + " (" +
             config.get_localized_string(20000) + " " +
             config.get_addon_version(with_fix=False) + ")",
             channel="help",
             action="mainlist",
             thumbnail=os.path.join(config.get_runtime_path(), "resources",
                                    'Screenshot.jpg'),
             category=config.get_localized_string(30104),
             viewmode="list"))

    from lib import generictools
    browser, res = generictools.call_browser('', lookup=True)
    if not browser:
        action = ''
        itemlist.append(
            Item(
                channel="setting",
                action=action,
                url='https://alfa-addon.com/foros/tutoriales.11/',
                title=
                "Tutoriales relevantes [COLOR gold](Instala un browser externo: Chrome, Firefox, Opera)[/COLOR]:",
                thumbnail=get_thumb("help.png", view),
                unify=False,
                folder=False,
                category=config.get_localized_string(30104),
                viewmode="list"))
    else:
        action = 'call_browser'
        itemlist.append(
            Item(
                channel="setting",
                action=action,
                url='https://alfa-addon.com/foros/tutoriales.11/',
                title=
                "Tutoriales relevantes [COLOR limegreen](pincha para usar [I]%s[/I])[/COLOR]:"
                % browser,
                thumbnail=get_thumb("help.png", view),
                unify=False,
                folder=False,
                category=config.get_localized_string(30104),
                viewmode="list"))

    itemlist.append(
        Item(
            channel="setting",
            action=action,
            url=
            'https://alfa-addon.com/threads/manual-de-alfa-mobile-assistant-herramienta-de-apoyo.3797/',
            title=
            "-     [COLOR yellow]Manual de Alfa Mobile Assistant (herramienta de apoyo)[/COLOR]   "
            +
            "https://alfa-addon.com/threads/manual-de-alfa-mobile-assistant-herramienta-de-apoyo.3797/",
            thumbnail=get_thumb("help.png", view),
            unify=False,
            folder=False,
            category=config.get_localized_string(30104),
            viewmode="list"))

    return itemlist
Beispiel #8
0
def mainlist(item):
    logger.info()

    if not config.get_setting("debug"):
        config.set_setting("debug", True)
    if not config.get_setting("report_started", default=False):
        msg = "Por favor reproduzca el problema y vuelva a esta sección"
        platformtools.dialog_ok("Alfa - Reporte de errores", msg)
        config.set_setting("report_started", True)
        return
    else:
        itemlist = []
        thumb_next = get_thumb("next.png")
        item = report_send(item)

        # Se devuelve control con item.url actualizado, así aparecerá en el menú la URL del informe
        if item.url:
            from lib.generictools import call_browser
            browser, res = call_browser(item, lookup=True)
            titles = {
                'report_title':
                'Ha terminado de generar el informe de fallo,',
                'report_text':
                '[COLOR limegreen]Repórtelo en el Foro de Alfa: [/COLOR][COLOR yellow](pinche para usar [I]%s[/I])[/COLOR]'
                % browser,
                'forum':
                '**- [COLOR yellow] https://alfa-addon.com/foros/ayuda.12/ [/COLOR] -**',
                'log':
                '**- LOG: [COLOR gold]%s[/COLOR] -**' % item.url
            }
            urls = {
                'forum': 'https://alfa-addon.com/foros/ayuda.12/',
                'log': item.url,
                'log_one_use': item.url
            }
            actions = {
                'browser': 'call_browser',
                'browser_one_use': 'call_browser'
            }

            if not browser:
                titles['report_title'] = 'Repórtelo en el Foro de Alfa: '
                urls['forum'] = ''
                actions['browser'] = ''

            if item.one_use:
                urls['log_one_use'] = ''
                actions['browser_one_use'] = ''

            itemlist.append(
                Item(channel=item.channel,
                     folder=False,
                     text_color='limegreen',
                     thumbnail=thumb_next,
                     title=titles['report_title']))

            itemlist.append(
                Item(action=actions['browser'],
                     channel='setting',
                     folder=False,
                     thumbnail=thumb_next,
                     title=titles['report_text'],
                     url=urls['forum']))

            itemlist.append(
                Item(action=actions['browser'],
                     channel='setting',
                     folder=False,
                     thumbnail=thumb_next,
                     title=titles['forum'],
                     unify=False,
                     url=urls['forum']))

            itemlist.append(
                Item(action=actions['browser_one_use'],
                     channel='setting',
                     folder=False,
                     thumbnail=thumb_next,
                     title=titles['log'],
                     unify=False,
                     url=urls['log_one_use']))

            if item.one_use:
                itemlist.append(
                    Item(
                        channel=item.channel,
                        folder=False,
                        text_color='orange',
                        thumbnail=thumb_next,
                        title='NO ACCEDA al INFORME: se BORRARÁ',
                    ))
                itemlist.append(
                    Item(
                        channel=item.channel,
                        folder=False,
                        text_color='orange',
                        thumbnail=thumb_next,
                        title='ya que es de un solo uso',
                    ))

        return itemlist