Example #1
0
    def onClick(self, control):
        if control == 3075:
            config.set_setting("show_once", True)
            self.close()
        control = self.getControl(control).getLabel().lower()
        if control == "comenzar":
            self.close_greeter()
        elif control == "videoteca":
            xbmc_videolibrary.ask_set_content(1, silent=True)
            config.set_setting('show_once', True)
        elif control == "cliente torrent":
            from channels import setting
            setting.setting_torrent(Item())
        elif control == "titulos inteligentes":
            from platformcode import colors
            from platformcode import unify
            unify.init_colors()
            colors.show_window()
        elif control == "set de iconos":
            from channels import setting
            setting.icon_set_selector()
        elif control == "ajustes avanzados":
            self.close()
            config.open_settings()

        elif control == "continuar":
            config.set_setting("show_once", True)
            self.close()
Example #2
0
def open_settings():
    settings_pre = get_all_settings_addon()
    __settings__.openSettings()
    settings_post = get_all_settings_addon()

    # cb_validate_config (util para validar cambios realizados en el cuadro de dialogo)
    if settings_post.get('adult_aux_intro_password', None):
        # Hemos accedido a la seccion de Canales para adultos
        from platformcode import platformtools
        if 'adult_password' not in settings_pre:
            adult_password = set_setting('adult_password', '0000')
        else:
            adult_password = settings_pre['adult_password']

        if settings_post['adult_aux_intro_password'] == adult_password:
            # La contraseña de acceso es correcta

            # Cambio de contraseña
            if settings_post['adult_aux_new_password1']:
                if settings_post['adult_aux_new_password1'] == settings_post[
                        'adult_aux_new_password2']:
                    set_setting('adult_password',
                                settings_post['adult_aux_new_password1'])
                else:
                    platformtools.dialog_ok(
                        "Canales para adultos",
                        "Los campos 'Nueva contraseña' y 'Confirmar nueva contraseña' no coinciden.",
                        "Entre de nuevo en 'Preferencias' para cambiar la contraseña"
                    )

        else:
            platformtools.dialog_ok(
                "Canales para adultos", "La contraseña no es correcta.",
                "Los cambios realizados en esta sección no se guardaran.")

            # Deshacer cambios
            set_setting("adult_mode", settings_pre.get("adult_mode", 0))
            set_setting("adult_request_password",
                        settings_pre.get("adult_request_password", True))

        # Borramos settings auxiliares
        set_setting('adult_aux_intro_password', '')
        set_setting('adult_aux_new_password1', '')
        set_setting('adult_aux_new_password2', '')

    # si se ha cambiado la ruta de la videoteca llamamos a comprobar directorios para que lo cree y pregunte
    # automaticamente si configurar la videoteca
    if settings_pre.get("videolibrarypath", None) != settings_post.get("videolibrarypath", None) or \
        settings_pre.get("folder_movies", None) != settings_post.get("folder_movies", None) or \
            settings_pre.get("folder_tvshows", None) != settings_post.get("folder_tvshows", None):
        verify_directories_created()

    else:
        # si se ha puesto que se quiere autoconfigurar y se había creado el directorio de la videoteca
        if not settings_pre.get("videolibrary_kodi", None) and settings_post.get("videolibrary_kodi", None) \
                and settings_post.get("videolibrary_kodi_flag", None) == 1:
            from platformcode import xbmc_videolibrary
            xbmc_videolibrary.ask_set_content(2, silent=True)
Example #3
0
    def onSettingsChanged(self):
        logger.debug('settings changed')
        settings_post = config.get_all_settings_addon()
        from platformcode import xbmc_videolibrary

        if self.settings_pre.get('downloadpath', None) != settings_post.get(
                'downloadpath', None):
            xbmc_videolibrary.update_sources(
                settings_post.get('downloadpath', None),
                self.settings_pre.get('downloadpath', None))

        # si se ha cambiado la ruta de la videoteca llamamos a comprobar directorios para que lo cree y pregunte
        # automaticamente si configurar la videoteca
        if self.settings_pre.get("videolibrarypath", None) != settings_post.get("videolibrarypath", None) or \
                self.settings_pre.get("folder_movies", None) != settings_post.get("folder_movies", None) or \
                self.settings_pre.get("folder_tvshows", None) != settings_post.get("folder_tvshows", None):
            videolibrary.move_videolibrary(
                self.settings_pre.get("videolibrarypath", None),
                settings_post.get("videolibrarypath", None),
                self.settings_pre.get("folder_movies", None),
                settings_post.get("folder_movies", None),
                self.settings_pre.get("folder_tvshows", None),
                settings_post.get("folder_tvshows", None))

        # si se ha puesto que se quiere autoconfigurar y se había creado el directorio de la videoteca
        if not self.settings_pre.get("videolibrary_kodi",
                                     None) and settings_post.get(
                                         "videolibrary_kodi", None):
            xbmc_videolibrary.ask_set_content(silent=True)
        elif self.settings_pre.get(
                "videolibrary_kodi",
                None) and not settings_post.get("videolibrary_kodi", None):
            xbmc_videolibrary.clean()

        if self.settings_pre.get('addon_update_timer') != settings_post.get(
                'addon_update_timer'):
            schedule.clear('updater')
            self.scheduleUpdater()

        if self.update_setting != config.get_setting(
                "update",
                "videolibrary") or self.update_hour != config.get_setting(
                    "everyday_delay", "videolibrary") * 4:
            schedule.clear('videolibrary')
            self.scheduleVideolibrary()

        if self.settings_pre.get('elementum_on_seed') != settings_post.get(
                'elementum_on_seed') and settings_post.get(
                    'elementum_on_seed'):
            if not platformtools.dialog_yesno(
                    config.get_localized_string(70805),
                    config.get_localized_string(70806)):
                config.set_setting('elementum_on_seed', False)

        self.settings_pre = settings_post
Example #4
0
def showOnce():
    if not config.get_all_settings_addon():
        logger.error('corrupted settings.xml!!')
        settings_xml = filetools.join(config.get_data_path(), 'settings.xml')
        settings_bak = filetools.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)
Example #5
0
def verify_directories_created():
    from core import logger
    from core import filetools
    from platformcode import xbmc_videolibrary

    config_paths = [["videolibrarypath", "videolibrary"],
                    ["downloadpath", "downloads"],
                    ["downloadlistpath", "downloads/list"],
                    ["settings_path", "settings_channels"]]

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

        # videoteca
        if path == "videolibrarypath":
            if not saved_path:
                saved_path = xbmc_videolibrary.search_library_path()
                if saved_path:
                    set_setting(path, saved_path)

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

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

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

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

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

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

            # si se crea el directorio
            if filetools.mkdir(content_path):
                if flag_call:
                    # le pasamos el valor para que sepamos que se ha pasado por creación de directorio
                    xbmc_videolibrary.ask_set_content(1)
                    flag_call = False

    try:
        from core import scrapertools
        # Buscamos el archivo addon.xml del skin activo
        skindir = filetools.join(xbmc.translatePath("special://home"),
                                 'addons', xbmc.getSkinDir(), 'addon.xml')
        # Extraemos el nombre de la carpeta de resolución por defecto
        folder = ""
        data = filetools.read(skindir)
        res = scrapertools.find_multiple_matches(data, '(<res .*?>)')
        for r in res:
            if 'default="true"' in r:
                folder = scrapertools.find_single_match(r, 'folder="([^"]+)"')
                break

        # Comprobamos si existe en el addon y sino es así, la creamos
        default = filetools.join(get_runtime_path(), 'resources', 'skins',
                                 'Default')
        if folder and not filetools.exists(filetools.join(default, folder)):
            filetools.mkdir(filetools.join(default, folder))

        # Copiamos el archivo a dicha carpeta desde la de 720p si éste no existe o si el tamaño es diferente
        if folder and folder != '720p':
            for root, folders, files in filetools.walk(
                    filetools.join(default, '720p')):
                for f in files:
                    if not filetools.exists(filetools.join(default, folder, f)) or \
                            (filetools.getsize(filetools.join(default, folder, f)) !=
                                 filetools.getsize(filetools.join(default, '720p', f))):
                        filetools.copy(filetools.join(default, '720p', f),
                                       filetools.join(default, folder, f),
                                       True)
    except:
        import traceback
        logger.error("Al comprobar o crear la carpeta de resolución")
        logger.error(traceback.format_exc())
Example #6
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"))
Example #7
0
def run(item=None):
    logger.info()

    if not item:
        # Extract item from sys.argv
        if sys.argv[2]:
            item = Item().fromurl(sys.argv[2])

        # 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").lower()
                    item = Item(channel="news",
                                action="novedades",
                                extra=category,
                                mode='silent')
                else:
                    from channels import side_menu
                    item = Item()
                    item = side_menu.check_user_home(item)
                    item.start = True
            else:
                item = Item(channel="channelselector",
                            action="getmainlist",
                            viewmode="movie")
        if not config.get_setting('show_once'):
            from platformcode import xbmc_videolibrary
            xbmc_videolibrary.ask_set_content(1)
            config.set_setting('show_once', True)

    logger.info(item.tostring())

    try:
        # If item has no action, stops here
        if item.action == "":
            logger.info("Item sin accion")
            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.action == "script":
            from core import tmdb
            if tmdb.drop_bd():
                platformtools.dialog_notification("Alfa",
                                                  "caché eliminada",
                                                  time=2000,
                                                  sound=False)

        # 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(
                        "", "Contraseña para canales de adultos", 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__))

            # 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("alfa",
                                                "No hay nada para reproducir")

                # 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

                tecleado = platformtools.dialog_input(last_search)
                if tecleado is not None:
                    if last_search_active and not tecleado.startswith("http"):
                        from channels import search
                        search.save_search(tecleado)

                    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)
                else:
                    config.set_setting('install_trakt', True)

                platformtools.render_items(itemlist, item)

    except urllib2.URLError, 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)
Example #8
0
    def onSettingsChanged(self):
        logger.debug('settings changed')
        settings_post = config.get_all_settings_addon()
        if settings_post:  # backup settings
            filetools.copy(
                os.path.join(config.get_data_path(), "settings.xml"),
                os.path.join(config.get_data_path(), "settings.bak"), True)
            logger.debug({
                k: self.settings_pre[k]
                for k in self.settings_pre if k in settings_post
                and self.settings_pre[k] != settings_post[k]
            })
        from platformcode import xbmc_videolibrary

        if self.settings_pre.get('downloadpath', None) != settings_post.get(
                'downloadpath', None):
            xbmc_videolibrary.update_sources(
                settings_post.get('downloadpath', None),
                self.settings_pre.get('downloadpath', None))

        # If the path of the video library has been changed, we call to check directories so that it creates it and automatically asks if to configure the video library
        if self.settings_pre.get("videolibrarypath", None) and self.settings_pre.get("videolibrarypath", None) != settings_post.get("videolibrarypath", None) or \
            self.settings_pre.get("folder_movies", None) and self.settings_pre.get("folder_movies", None) != settings_post.get("folder_movies", None) or \
            self.settings_pre.get("folder_tvshows", None) and self.settings_pre.get("folder_tvshows", None) != settings_post.get("folder_tvshows", None):
            videolibrary.move_videolibrary(
                self.settings_pre.get("videolibrarypath", ''),
                settings_post.get("videolibrarypath", ''),
                self.settings_pre.get("folder_movies", ''),
                settings_post.get("folder_movies", ''),
                self.settings_pre.get("folder_tvshows", ''),
                settings_post.get("folder_tvshows", ''))

        # if you want to autoconfigure and the video library directory had been created
        if not self.settings_pre.get("videolibrary_kodi",
                                     None) and settings_post.get(
                                         "videolibrary_kodi", None):
            xbmc_videolibrary.ask_set_content(silent=True)
        elif self.settings_pre.get(
                "videolibrary_kodi",
                None) and not settings_post.get("videolibrary_kodi", None):
            xbmc_videolibrary.clean()

        if self.settings_pre.get('addon_update_timer') != settings_post.get(
                'addon_update_timer'):
            schedule.clear('updater')
            self.scheduleUpdater()

        if self.update_setting != config.get_setting(
                "update",
                "videolibrary") or self.update_hour != config.get_setting(
                    "everyday_delay", "videolibrary") * 4:
            schedule.clear('videolibrary')
            self.scheduleVideolibrary()

        if self.settings_pre.get('elementum_on_seed') != settings_post.get(
                'elementum_on_seed') and settings_post.get(
                    'elementum_on_seed'):
            if not platformtools.dialog_yesno(
                    config.get_localized_string(70805),
                    config.get_localized_string(70806)):
                config.set_setting('elementum_on_seed', False)

        self.settings_pre = settings_post
Example #9
0
def open_settings():
    settings_pre = get_all_settings_addon()
    __settings__.openSettings()
    settings_post = get_all_settings_addon()

    # cb_validate_config (util para validar cambios realizados en el cuadro de dialogo)
    if settings_post.get('adult_aux_intro_password', None):
        # Hemos accedido a la seccion de Canales para adultos
        from platformcode import platformtools
        if 'adult_password' not in settings_pre:
            adult_password = set_setting('adult_password', '0000')
        else:
            adult_password = settings_pre['adult_password']

        if settings_post['adult_aux_intro_password'] == adult_password:
            # La contraseña de acceso es correcta

            # Cambio de contraseña
            if settings_post['adult_aux_new_password1']:
                if settings_post['adult_aux_new_password1'] == settings_post[
                        'adult_aux_new_password2']:
                    set_setting('adult_password',
                                settings_post['adult_aux_new_password1'])
                else:
                    platformtools.dialog_ok(get_localized_string(60305),
                                            get_localized_string(60306),
                                            get_localized_string(60307))

        else:
            platformtools.dialog_ok(get_localized_string(60305),
                                    get_localized_string(60309),
                                    get_localized_string(60310))

            # Deshacer cambios
            set_setting("adult_mode", settings_pre.get("adult_mode", 0))
            set_setting("adult_request_password",
                        settings_pre.get("adult_request_password", True))

        # Borramos settings auxiliares
        set_setting('adult_aux_intro_password', '')
        set_setting('adult_aux_new_password1', '')
        set_setting('adult_aux_new_password2', '')

    from specials import videolibrary
    from platformcode import xbmc_videolibrary
    if settings_pre.get('downloadpath', None) != settings_post.get(
            'downloadpath', None):
        xbmc_videolibrary.update_sources(
            settings_post.get('downloadpath', None),
            settings_pre.get('downloadpath', None))

    # si se ha cambiado la ruta de la videoteca llamamos a comprobar directorios para que lo cree y pregunte
    # automaticamente si configurar la videoteca
    if settings_pre.get("videolibrarypath", None) != settings_post.get("videolibrarypath", None) or \
                        settings_pre.get("folder_movies", None) != settings_post.get("folder_movies", None) or \
                        settings_pre.get("folder_tvshows", None) != settings_post.get("folder_tvshows", None):
        videolibrary.move_videolibrary(
            settings_pre.get("videolibrarypath", None),
            settings_post.get("videolibrarypath", None),
            settings_pre.get("folder_movies", None),
            settings_post.get("folder_movies", None),
            settings_pre.get("folder_tvshows", None),
            settings_post.get("folder_tvshows", None))

    # si se ha puesto que se quiere autoconfigurar y se había creado el directorio de la videoteca
    if not settings_pre.get("videolibrary_kodi", None) and settings_post.get(
            "videolibrary_kodi", None):
        xbmc_videolibrary.ask_set_content(silent=True)
    elif settings_pre.get("videolibrary_kodi", None) and not settings_post.get(
            "videolibrary_kodi", None):
        xbmc_videolibrary.clean_db()
Example #10
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"):
                    dictCategory = {
                        config.get_localized_string(70137): 'peliculas',
                        config.get_localized_string(30123): 'series',
                        config.get_localized_string(30124): 'anime',
                        config.get_localized_string(70018): 'infantiles',
                        config.get_localized_string(60513): 'documentales',
                        config.get_localized_string(70013): 'terror',
                        config.get_localized_string(70014): 'castellano',
                        config.get_localized_string(59976): 'latino',
                        config.get_localized_string(70171): 'torrent',
                    }
                    if not config.get_setting(
                            "category") in dictCategory.keys():
                        config.set_setting('category',
                                           config.get_localized_string(70137))
                    category = dictCategory[config.get_setting("category")]
                    item = Item(channel="news",
                                action="novedades",
                                extra=category,
                                mode='silent')
                else:
                    from specials import side_menu
                    item = Item()
                    item = side_menu.check_user_home(item)
                    item.start = True
            else:
                item = Item(channel="channelselector",
                            action="getmainlist",
                            viewmode="movie")
        if not config.get_setting('show_once'):
            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.info("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.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":
            import base64
            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
        else:
            # Entry point for a channel is the "mainlist" action, so here we check parental control
            if item.action == "mainlist":
                from core import channeltools
                #updater.checkforupdates() beta version checking for update, still disabled

                # 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
            if os.path.isfile(
                    os.path.join(config.get_runtime_path(), 'channels',
                                 item.channel + ".py")):
                CHANNELS = 'channels'
            elif os.path.isfile(
                    os.path.join(config.get_runtime_path(), 'channels', 'p**n',
                                 item.channel + ".py")):
                CHANNELS = 'channels.p**n'
            else:
                CHANNELS = 'specials'

            if CHANNELS != 'channels.p**n':
                channel_file = os.path.join(config.get_runtime_path(),
                                            CHANNELS, item.channel + ".py")
            else:
                channel_file = os.path.join(config.get_runtime_path(),
                                            'channels', 'p**n',
                                            item.channel + ".py")

            logger.info("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.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":
                from core import servertools

                # 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":
                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":
                logger.info("item.action=%s" % item.action.upper())
                from core import channeltools

                # 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', '')
                if channeltools.get_channel_setting('last_search', 'search'):
                    last_search = channeltools.get_channel_setting(
                        'Last_searched', 'search', '')
                else:
                    last_search = ''

                tecleado = platformtools.dialog_input(last_search)

                if tecleado is not None:
                    channeltools.set_channel_setting('Last_searched', tecleado,
                                                     'search')
                    if 'search' in dir(channel):
                        itemlist = channel.search(item, tecleado)
                    else:
                        from core import support
                        itemlist = support.search(channel, item, tecleado)
                else:
                    return

                platformtools.render_items(itemlist, item)

            # For all other actions
            else:
                # import web_pdb; web_pdb.set_trace()
                logger.info("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 urllib2.URLError as e:
        import traceback
        logger.error(traceback.format_exc())

        # Grab inner and third party errors
        if hasattr(e, 'reason'):
            logger.error("Reason for the error, code: %s | Reason: %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(config.get_localized_string(20000), texto)

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

        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
        from core import scrapertools

        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:
            import xbmc
            if config.get_platform(True)['num_version'] < 14:
                log_name = "xbmc.log"
            else:
                log_name = "kodi.log"
            log_message = config.get_localized_string(
                50004) + xbmc.translatePath("special://logpath") + log_name
        except:
            log_message = ""

        if canal:
            if item.url:
                if platformtools.dialog_yesno(
                        config.get_localized_string(60087) % canal,
                        config.get_localized_string(60014),
                        log_message,
                        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) % canal,
                    config.get_localized_string(60014), log_message)
        else:
            platformtools.dialog_ok(config.get_localized_string(60038),
                                    config.get_localized_string(60015),
                                    log_message)