コード例 #1
1
    def query(self, query):
        result = {
            'result': [],
        }

        http = ModuleManager.call_module_method(
            'http_lib',
            'get',
            'https://encrypted.google.com/search?q=%s&num=10000' % quote(query)
        )

        if not 'html' in http:
            result['error'] = 'No server responce'
            return result

        soup = bs4(http['html'])

        for title in soup.find_all('h3', attrs={'class': 'r'}):
            element = title.find('a')
            # parse google url
            g_url = urlparse(element['href'])
            g_args = parse_qs(g_url.query)
            url = g_args['q'][0]

            result['result'].append({
                'title': element.text,
                'url': url,
            })

        return result
コード例 #2
0
    def get_camera_list(self):
        """Get cameras devices"""
        # get cache
        current_time = time.time()
        if self.cache_delay > current_time - self.__cache_time:
            return self.__cache_camera_list

        camera_list = {}

        for module_name in ModuleManager.get_active_modules():
            devices = getattr(ModuleManager.get(module_name), 'devices', {})

            for device in devices.values():
                name = device.name
                num = 0

                # duplicate ?
                while name in camera_list:
                    num += 1
                    name = '%s%d' % (device.name, num)

                camera_list[device.name] = device

        self.__cache_camera_list = camera_list
        self.__cache_time = current_time
        return camera_list
コード例 #3
0
def stop():
    """Stop daemon."""
    global __is_running

    if not __is_running:
        return

    Log.info('stop deamon')
    __is_running = False
    ModuleManager.stop_all()
    sys.exit(0)
コード例 #4
0
def update_module(module_name):
    """Update a module.

    :param module_name: module name
    :return: is sucess
    """
    if not ModuleManager.get(module_name):
        Log.error("Module not installed")
        return False
コード例 #5
0
    def started(self):
        """Register mapping url to web server"""
        template_folder = os.path.join(self.module_path, 'templates')
        app = Blueprint('Auth',
                        __name__,
                        url_prefix='/auth',
                        template_folder=template_folder)

        # url mapping
        app.add_url_rule('/', 'index', view_func=self._index)
        app.add_url_rule('/login',
                         'login',
                         view_func=self._login,
                         methods=['GET', 'POST'])
        app.add_url_rule('/logout', 'logout', view_func=self._logout)
        app.add_url_rule('/users', 'users', view_func=self._users)
        app.add_url_rule('/user',
                         'new_user',
                         view_func=self._user,
                         methods=['GET', 'POST'])
        app.add_url_rule('/user/<user_name>',
                         'user',
                         view_func=self._user,
                         methods=['GET', 'POST'])

        # register to flask
        module = ModuleManager.get('web')
        if not module:
            self.add_critical('no module name "web"')
            raise FileNotFoundError

        module.add_blueprint(app)
        login_manager = LoginManager()
        login_manager.login_view = '%s.login' % app.name
        login_manager.init_app(module.flask)
        login_manager.user_loader(auth.load)

        # set url to login required
        exclude_login_required_url = [
            'static', login_manager.login_view
        ] + DataFileManager.load(self.name, 'exclude_login_required_url', [])

        def filter_app(get_apps_handler):
            def inner():
                return [
                    app for app in get_apps_handler()
                    if current_user.can_access(app['name'])
                ]

            return inner

        for endpoint, view_func in module.flask.view_functions.copy().items():
            if endpoint not in exclude_login_required_url:
                module.flask.view_functions[endpoint] = login_required(
                    view_func)
                module.get_apps = filter_app(module.get_apps)
コード例 #6
0
 async def execute(self, message: discord.Message, args: list,
                   keys: DotDict) -> CommandResult:
     module_manager = ModuleManager()
     embed = self.bot.get_special_embed(
         title="Список%s команд" %
         (" доступных" if "all" not in keys else ""),
         description="Ваши права discord: %s\nВаши права future: %s" %
         (hex(message.author.guild_permissions.value),
          bin(module_manager.get_sp_permissions(message.author.id))),
         color=0xb63a6b)
     for command in module_manager.commands.values():
         if "all" in keys or module_manager.check_permissions(message.author.guild_permissions, command.permissions) \
                 and module_manager.check_sp_permissions(message.author.id, command.future_permissions):
             embed.add_field(name="%s%s %s" %
                             (cmd_prefix, command.name, command.arguments),
                             value=command.description,
                             inline=False)
     await message.channel.send(embed=embed)
     return CommandResult.success
コード例 #7
0
def start():
    """Start daemon."""
    global __is_running
    settings.load_conf()

    ModuleManager.init_all()
    ModuleManager.load_config_all()
    ModuleManager.start_all()

    __is_running = True

    try:
        ModuleManager.run_loop()
    except KeyboardInterrupt:
        pass

    stop()
コード例 #8
0
    def started(self):
        """Register mapping url to web server"""
        template_folder = os.path.join(self.module_path, 'templates')
        app = Blueprint('Auth', __name__, url_prefix='/auth',
                        template_folder=template_folder)

        # url mapping
        app.add_url_rule('/', 'index', view_func=self._index)
        app.add_url_rule('/login', 'login', view_func=self._login,
                         methods=['GET', 'POST'])
        app.add_url_rule('/logout', 'logout', view_func=self._logout)
        app.add_url_rule('/users', 'users', view_func=self._users)
        app.add_url_rule('/user', 'new_user', view_func=self._user,
                         methods=['GET', 'POST'])
        app.add_url_rule('/user/<user_name>', 'user', view_func=self._user,
                         methods=['GET', 'POST'])

        # register to flask
        module = ModuleManager.get('web')
        if not module:
            self.add_critical('no module name "web"')
            raise FileNotFoundError

        module.add_blueprint(app)
        login_manager = LoginManager()
        login_manager.login_view = '%s.login' % app.name
        login_manager.init_app(module.flask)
        login_manager.user_loader(auth.load)

        # set url to login required
        exclude_login_required_url = [
            'static',
            login_manager.login_view
        ] + DataFileManager.load(self.name, 'exclude_login_required_url', [])

        def filter_app(get_apps_handler):
            def inner():
                return [app for app in get_apps_handler() if
                        current_user.can_access(app['name'])]
            return inner

        for endpoint, view_func in module.flask.view_functions.copy().items():
            if endpoint not in exclude_login_required_url:
                module.flask.view_functions[endpoint] = login_required(view_func)
                module.get_apps = filter_app(module.get_apps)
コード例 #9
0
def install_module(module_name):
    """Install a new module.

    :param module_name: module name
    :return: is sucess
    """
    module_path = os.path.join(MODULES_PATH, module_name)
    if os.path.exists(module_path):
        return False

    infos = get_module_infos(module_name)
    if not infos:
        Log.error('Module "%s" not found' % module_name)
        return False

    # install module
    zip_file = BytesIO(requests.get(infos["zip_url"]).content)
    with ZipFile(zip_file) as z:
        # security + locate path files
        content_dir = ""
        for member in z.namelist():
            if member.startswith("/") or "./" in member:
                msg = 'Security threat on "%s" module install (%s)' % (module_name, member)
                Log.critical(msg)
                EventManager.fire(EventManager.Event("security_thread", __package__, msg=msg))
                return False

            if "Module.py" in member:
                content_dir = member.replace("Module.py", "")

        # unzip
        os.makedirs(module_path)
        for member in z.namelist():
            # skip directories
            if not os.path.basename(member):
                continue

            # unzip
            path = os.path.join(module_path, member.replace(content_dir, ""))
            with z.open(member) as s, open(path, "wb") as t:
                shutil.copyfileobj(s, t)

    # starting module
    ModuleManager.reindex_modules()
    ModuleManager.init(module_name)
    ModuleManager.start(module_name)
    return True
コード例 #10
0
 def call(self, module_name, method_name, *arg, **kwargs):
     """call a method of other module."""
     return ModuleManager.call(module_name, method_name, *arg, **kwargs)
コード例 #11
0
 async def execute(self, message: discord.Message, args: list,
                   keys: DotDict) -> CommandResult:
     if len(args) < 2:
         return CommandResult.arguments_insufficient
     if args[0] == "add":
         perm = args[1]
         try:
             perm = FuturePermission[perm.upper()]
         except KeyError:
             raise CommandException("Permission \"%s\" don't exists." %
                                    perm.upper())
         embed = self.bot.get_ok_embed(title="Установка прав")
         success = 0
         failure = 0
         for mention in message.mentions:
             perms = ModuleManager().get_sp_permissions(mention.id)
             if perms & perm.value == perm.value:
                 embed.add_field(
                     name=
                     "Установка разрешения %s пользователю %s не удалась." %
                     (perm, str(mention)),
                     value="Он уже имеет такое разрешение")
                 failure += 1
             else:
                 try:
                     db_perms: SPPermissions = SPPermissions.objects.get(
                         user_id=mention.id)
                 except SPPermissions.DoesNotExist:
                     db_perms: SPPermissions = SPPermissions()
                     db_perms.user_id = mention.id
                 db_perms.permissions |= perm.value
                 db_perms.save()
                 embed.add_field(name="%s - успешно" % str(mention),
                                 value="Текущие права: %s" %
                                 bin(db_perms.permissions))
                 success += 1
         embed.description = "%s успешно\n%s с ошибками" % (success,
                                                            failure)
         await message.channel.send(embed=embed)
     elif args[0] == "remove":
         perm = args[1]
         try:
             perm = FuturePermission[perm.upper()]
         except KeyError:
             raise CommandException("Permission \"%s\" don't exists." %
                                    perm.upper())
         embed = self.bot.get_ok_embed(title="Удаление прав")
         success = 0
         failure = 0
         for mention in message.mentions:
             perms = ModuleManager().get_sp_permissions(mention.id)
             if perms & perm.value != perm.value:
                 embed.add_field(
                     name=
                     "Удаление разрешения %s у пользователя %s невозможно."
                     % (perm, str(mention)),
                     value="Он не имеет такого разрешения.")
                 failure += 1
             else:
                 try:
                     db_perms: SPPermissions = SPPermissions.objects.get(
                         user_id=mention.id)
                 except SPPermissions.DoesNotExist:
                     db_perms: SPPermissions = SPPermissions()
                     db_perms.user_id = mention.id
                 db_perms.permissions ^= perm.value
                 db_perms.save()
                 embed.add_field(name="%s - успешно" % str(mention),
                                 value="Текущие права: %s" %
                                 bin(db_perms.permissions))
                 success += 1
         embed.description = "%s успешно\n%s с ошибками" % (success,
                                                            failure)
         await message.channel.send(embed=embed)
     else:
         return CommandResult.arguments_insufficient
     return CommandResult.success
コード例 #12
0
 def new_client(self, socket, ip, port, client_key):
     personnality = ModuleManager.get('personnality')
     if personnality:
         self.send(personnality.get_greeting().capitalize() + ' ' + personnality.get_user_name() + '.', client_key)
コード例 #13
0
    def load_configuration(self):
        web_interface = ModuleManager.get('web_interface')
        if web_interface:
            web_interface.add_home_page('Private', '/private', 'Private zone')

            web_interface.register_blueprint(home.app)