Пример #1
0
 def find_match(self, message, banphrase_id=None):
     match = None
     if banphrase_id is not None:
         match = find(lambda banphrase: banphrase.id == banphrase_id, self.banphrases)
     if match is None:
         match = find(lambda banphrase: banphrase.exact_match(message), self.banphrases)
     return match
Пример #2
0
    def modules_edit(module_id, **options):
        module_manager = ModuleManager(None).load(do_reload=False)
        current_module = find(lambda m: m.ID == module_id, module_manager.all_modules)

        if current_module is None:
            return render_template('admin/module_404.html'), 404

        sub_modules = []
        for module in module_manager.all_modules:
            module.db_module = None

        with DBManager.create_session_scope() as db_session:
            for db_module in db_session.query(Module):
                module = find(lambda m: m.ID == db_module.id, module_manager.all_modules)
                if module:
                    module.db_module = db_module
                    if module.PARENT_MODULE == current_module.__class__:
                        sub_modules.append(module)

            if current_module.db_module is None:
                return render_template('admin/module_404.html'), 404

            if request.method == 'POST':
                form_values = {key: value for key, value in request.form.items()}
                res = current_module.parse_settings(**form_values)
                if res is False:
                    return render_template('admin/module_404.html'), 404

                current_module.db_module.settings = json.dumps(res)
                db_session.commit()

                settings = None
                try:
                    settings = json.loads(current_module.db_module.settings)
                except (TypeError, ValueError):
                    pass
                current_module.load(settings=settings)

                payload = {
                        'id': current_module.db_module.id,
                        }

                SocketClientManager.send('module.update', payload)

                AdminLogManager.post('Module edited', options['user'], current_module.NAME)

                return render_template('admin/configure_module.html',
                        module=current_module,
                        sub_modules=sub_modules)
            else:
                settings = None
                try:
                    settings = json.loads(current_module.db_module.settings)
                except (TypeError, ValueError):
                    pass
                current_module.load(settings=settings)

                return render_template('admin/configure_module.html',
                        module=current_module,
                        sub_modules=sub_modules)
Пример #3
0
 def find_match(self, message, id=None):
     match = None
     if id is not None:
         match = find(lambda banphrase: banphrase.id == id, self.banphrases)
     if match is None:
         match = find(lambda banphrase: banphrase.exact_match(message), self.banphrases)
     return match
Пример #4
0
    def command_detailed(raw_command_string):
        command_string_parts = raw_command_string.split("-")
        command_string = command_string_parts[0]
        command_id = None
        try:
            command_id = int(command_string)
        except ValueError:
            pass

        bot_commands_list = get_commands_list()

        if command_id is not None:
            command = find(lambda c: c["id"] == command_id, bot_commands_list)
        else:
            command = find(lambda c: c["resolve_string"] == command_string,
                           bot_commands_list)

        if command is None:
            # XXX: Is it proper to have it return a 404 code as well?
            return render_template("command_404.html")

        examples = command["examples"]

        return render_template("command_detailed.html",
                               command=command,
                               examples=examples)
Пример #5
0
    def command_detailed(raw_command_string):
        command_string_parts = raw_command_string.split('-')
        command_string = command_string_parts[0]
        command_id = None
        try:
            command_id = int(command_string)
        except ValueError:
            pass

        bot_commands_list = get_commands_list()

        if command_id is not None:
            command = find(lambda c: c['id'] == command_id, bot_commands_list)
        else:
            command = find(lambda c: c['resolve_string'] == command_string, bot_commands_list)

        if command is None:
            # XXX: Is it proper to have it return a 404 code as well?
            return render_template('command_404.html')

        examples = command['examples']

        return render_template('command_detailed.html',
                command=command,
                examples=examples)
Пример #6
0
 def find_match(self, message, id=None):
     match = None
     if id is not None:
         match = find(lambda autoresponse: autoresponse.id == id,
                      self.autoresponses)
     if match is None:
         match = find(
             lambda autoresponse: autoresponse.exact_match(message),
             self.autoresponses)
     return match
Пример #7
0
    def pleblist_history_stream(stream_id):
        with DBManager.create_session_scope() as session:
            stream = session.query(Stream).filter_by(id=stream_id).one_or_none()
            if stream is None:
                return render_template('pleblist_history_404.html'), 404

            previous_stream = session.query(Stream).filter_by(id=stream_id - 1).one_or_none()
            next_stream = session.query(Stream).filter_by(id=stream_id + 1).one_or_none()

            # Fetch all associated stream chunks so we can associate songs to a certain stream chunk
            stream_chunks = session.query(StreamChunk).filter(StreamChunk.stream_id == stream.id).all()

            q = session.query(PleblistSong).filter(PleblistSong.stream_id == stream.id).order_by(PleblistSong.id.asc())
            songs = []
            queue_index = 0
            queue_time = 0
            for song in q:
                if song.song_info is None:
                    continue

                data = {
                        'song_duration': song.song_info.duration if song.skip_after is None else song.skip_after,
                        }

                if song.date_played is None:
                    # Song has not been played
                    # Figure out when it will be played~
                    data['queue_index'] = queue_index
                    data['queue_time'] = queue_time
                    queue_index = queue_index + 1
                    queue_time = queue_time + data['song_duration']
                else:
                    # Song has already been played
                    # Figure out a link to the vod URL
                    stream_chunk = find(lambda stream_chunk: stream_chunk.chunk_start <= song.date_played and (stream_chunk.chunk_end is None or stream_chunk.chunk_end >= song.date_played), stream_chunks)
                    if stream_chunk is not None:
                        vodtime_in_seconds = (song.date_played - stream_chunk.chunk_start).total_seconds() - data['song_duration']
                        data['vod_url'] = '{}?t={}'.format(stream_chunk.video_url, seconds_to_vodtime(vodtime_in_seconds))

                songs.append((data, song))

            total_length_left = sum([song.skip_after or song.song_info.duration if song.date_played is None and song.song_info is not None else 0 for _, song in songs])

            first_unplayed_song = find(lambda song: song[1].date_played is None, songs)

            return render_template('pleblist_history.html',
                    stream=stream,
                    previous_stream=previous_stream,
                    next_stream=next_stream,
                    songs=songs,
                    total_length_left=total_length_left,
                    first_unplayed_song=first_unplayed_song,
                    stream_chunks=stream_chunks)
Пример #8
0
    def reload(self):
        # TODO: Make disable/enable better, so we don't need to disable modules
        # that we're just going to enable again further down below.
        for module in self.modules:
            log.debug('Disabling {module.NAME}'.format(module=module))
            module.disable(self.bot)

        self.modules = []

        with DBManager.create_session_scope() as db_session:
            for enabled_module in db_session.query(Module).filter_by(enabled=True):
                module = find(lambda m: m.ID == enabled_module.id, self.all_modules)
                if module is not None:
                    options = {}
                    if enabled_module.settings is not None:
                        try:
                            options['settings'] = json.loads(enabled_module.settings)
                        except ValueError:
                            log.warn('Invalid JSON')

                    self.modules.append(module.load(**options))
                    log.debug('Enabling {module.NAME}'.format(module=module))
                    module.enable(self.bot)

        to_be_removed = []
        self.modules.sort(key=lambda m: 1 if m.PARENT_MODULE is not None else 0)
        for module in self.modules:
            if module.PARENT_MODULE is None:
                module.submodules = []
            else:
                parent = find(lambda m: m.__class__ == module.PARENT_MODULE, self.modules)
                if parent is not None:
                    parent.submodules.append(module)
                    module.parent_module = parent
                else:
                    log.warn('Missing parent for module {}, disabling it.'.format(module.NAME))
                    module.parent_module = None
                    to_be_removed.append(module)

        for module in to_be_removed:
            log.debug('Disabling (2) {module.NAME}'.format(module=module))
            module.disable(self.bot)
            self.modules.remove(module)

        # Perform a last on_loaded call on each module.
        # This is used for things that require submodules to be loaded properly
        # i.e. the quest system
        for module in self.modules:
            module.on_loaded()
Пример #9
0
    def on_banphrase_update(self, data, conn):
        try:
            banphrase_id = int(data['id'])
        except (KeyError, ValueError):
            log.warn('No banphrase ID found in on_banphrase_update')
            return False

        updated_banphrase = find(lambda banphrase: banphrase.id == banphrase_id, self.banphrases)
        if updated_banphrase:
            with DBManager.create_session_scope(expire_on_commit=False) as db_session:
                db_session.add(updated_banphrase)
                db_session.refresh(updated_banphrase)
                db_session.expunge(updated_banphrase)
        else:
            with DBManager.create_session_scope(expire_on_commit=False) as db_session:
                updated_banphrase = db_session.query(Banphrase).filter_by(id=banphrase_id).one_or_none()
                db_session.expunge_all()
                if updated_banphrase is not None:
                    self.db_session.add(updated_banphrase.data)

        if updated_banphrase:
            if updated_banphrase not in self.banphrases:
                self.banphrases.append(updated_banphrase)
            if updated_banphrase.enabled is True and updated_banphrase not in self.enabled_banphrases:
                self.enabled_banphrases.append(updated_banphrase)

        for banphrase in self.enabled_banphrases:
            if banphrase.enabled is False:
                self.enabled_banphrases.remove(banphrase)
Пример #10
0
    def on_managers_loaded(self, **rest):
        # This function is used to resume a quest in case the bot starts when the stream is already live
        if not self.current_quest_key:
            log.error(
                "Current quest key not set when on_managers_loaded event fired, something is wrong"
            )
            return

        if self.current_quest:
            # There's already a quest chosen for today
            return

        redis = RedisManager.get()

        current_quest_id = redis.get(self.current_quest_key)

        log.info(f"Try to load submodule with ID {current_quest_id}")

        if not current_quest_id:
            # No "current quest" was chosen by an above manager
            return

        current_quest_id = current_quest_id
        quest = find(lambda m: m.ID == current_quest_id, self.submodules)

        if not quest:
            log.info("No quest with id %s found in submodules (%s)",
                     current_quest_id, self.submodules)
            return

        self.current_quest = quest
        self.current_quest.quest_module = self
        self.current_quest.start_quest()
        log.info(f"Resumed quest {quest.get_objective()}")
Пример #11
0
    def pleblist_history_stream(stream_id):
        with DBManager.create_session_scope() as session:
            stream = session.query(Stream).filter_by(id=stream_id).one_or_none()
            if stream is None:
                return render_template('pleblist_history_404.html'), 404

            previous_stream = session.query(Stream).filter_by(id=stream_id - 1).one_or_none()
            next_stream = session.query(Stream).filter_by(id=stream_id + 1).one_or_none()

            q = session.query(PleblistSong, User).outerjoin(User, PleblistSong.user_id == User.id).filter(PleblistSong.stream_id == stream.id).order_by(PleblistSong.id.asc(), PleblistSong.id.asc())
            songs = []
            for song, user in q:
                song.user = user
                songs.append(song)

            total_length_left = sum([song.skip_after or song.song_info.duration if song.date_played is None and song.song_info is not None else 0 for song in songs])

            first_unplayed_song = find(lambda song: song.date_played is None, songs)
            stream_chunks = session.query(StreamChunk).filter(StreamChunk.stream_id == stream.id).all()

            return render_template('pleblist_history.html',
                    stream=stream,
                    previous_stream=previous_stream,
                    next_stream=next_stream,
                    songs=songs,
                    total_length_left=total_length_left,
                    first_unplayed_song=first_unplayed_song,
                    stream_chunks=stream_chunks)
Пример #12
0
    def parse_settings(self, **in_settings):
        ret = {}
        for key, value in in_settings.items():
            setting = find(
                lambda setting, setting_key=key: setting.key == setting_key,
                self.SETTINGS)
            if setting is None:
                # We were passed a setting that's not available for this module
                return False
            log.debug(f"{key}: {value}")
            res, new_value = setting.validate(value)
            if res is False:
                # Something went wrong when validating one of the settings
                log.warning(new_value)
                return False

            ret[key] = new_value

        for setting in self.SETTINGS:
            if setting.type == "boolean":
                if setting.key not in ret:
                    ret[setting.key] = False
                    log.debug("{}: {} - special".format(setting.key, False))

        return ret
Пример #13
0
def validate_module(module_id):
    module = find(lambda m: m.ID == module_id, pajbot.modules.available_modules)

    if module is None:
        return False

    return module.MODULE_TYPE not in (ModuleType.TYPE_ALWAYS_ENABLED, )
Пример #14
0
def validate_module(module_id):
    module = find(lambda m: m.ID == module_id, pajbot.modules.available_modules)

    if module is None:
        return False

    return module.MODULE_TYPE not in (ModuleType.TYPE_ALWAYS_ENABLED,)
Пример #15
0
    def on_banphrase_update(self, data, conn):
        try:
            banphrase_id = int(data['id'])
        except (KeyError, ValueError):
            log.warn('No banphrase ID found in on_banphrase_update')
            return False

        updated_banphrase = find(
            lambda banphrase: banphrase.id == banphrase_id, self.banphrases)
        if updated_banphrase:
            with DBManager.create_session_scope(
                    expire_on_commit=False) as db_session:
                db_session.add(updated_banphrase)
                db_session.refresh(updated_banphrase)
                db_session.expunge(updated_banphrase)
        else:
            with DBManager.create_session_scope(
                    expire_on_commit=False) as db_session:
                updated_banphrase = db_session.query(Banphrase).filter_by(
                    id=banphrase_id).one_or_none()
                db_session.expunge_all()
                if updated_banphrase is not None:
                    self.db_session.add(updated_banphrase.data)

        if updated_banphrase:
            if updated_banphrase not in self.banphrases:
                self.banphrases.append(updated_banphrase)
            if updated_banphrase.enabled is True and updated_banphrase not in self.enabled_banphrases:
                self.enabled_banphrases.append(updated_banphrase)

        for banphrase in self.enabled_banphrases:
            if banphrase.enabled is False:
                self.enabled_banphrases.remove(banphrase)
Пример #16
0
 def remove_handler(event, method):
     handler = None
     try:
         handler = find(lambda h: HandlerManager.method_matches(h, method), HandlerManager.handlers[event])
         if handler is not None:
             HandlerManager.handlers[event].remove(handler)
     except KeyError:
         # No handlers for this event found
         log.error('remove_handler No handler for {} found.'.format(event))
Пример #17
0
 def remove_handler(event: str, method: Callable[..., bool]) -> None:
     try:
         handler = find(lambda h: h[0] == method,
                        HandlerManager.handlers[event])
         if handler is not None:
             HandlerManager.handlers[event].remove(handler)
     except KeyError:
         # No handlers for this event found
         log.error(f"remove_handler No handler for {event} found.")
Пример #18
0
    def privmsg(self, channel, message, increase_message=True):
        if increase_message:
            conn = find(lambda c: c.conn.is_connected() and c.num_msgs_sent < self.message_limit, self.connlist)
        else:
            conn = find(lambda c: c.conn.is_connected(), self.connlist)

        if conn is None:
            log.error('No available connections to send messages from. Delaying message a few seconds.')
            self.reactor.execute_delayed(2, self.privmsg, (channel, message, increase_message))
            return False

        conn.conn.privmsg(channel, message)
        if increase_message:
            conn.num_msgs_sent += 1
            self.reactor.execute_delayed(31, conn.reduce_msgs_sent)

            if conn.num_msgs_sent >= self.message_limit:
                self.run_maintenance()
Пример #19
0
 def remove_handler(event, method):
     handler = None
     try:
         handler = find(lambda h: HandlerManager.method_matches(h, method), HandlerManager.handlers[event])
         if handler is not None:
             HandlerManager.handlers[event].remove(handler)
     except KeyError:
         # No handlers for this event found
         log.error("remove_handler No handler for {} found.".format(event))
Пример #20
0
 def tick(self):
     if self.bot.is_online:
         for timer in self.online_timers:
             timer.time_to_send_online -= 1
         timer = find(lambda timer: timer.time_to_send_online <= 0, self.online_timers)
         if timer:
             timer.run(self.bot)
             timer.time_to_send_online = timer.interval_online
             self.online_timers.remove(timer)
             self.online_timers.append(timer)
     else:
         for timer in self.offline_timers:
             timer.time_to_send_offline -= 1
         timer = find(lambda timer: timer.time_to_send_offline <= 0, self.offline_timers)
         if timer:
             timer.run(self.bot)
             timer.time_to_send_offline = timer.interval_offline
             self.offline_timers.remove(timer)
             self.offline_timers.append(timer)
Пример #21
0
    def modules(**options) -> ResponseReturnValue:
        module_manager = ModuleManager(None).load(do_reload=False)
        with DBManager.create_session_scope() as db_session:
            for db_module in db_session.query(Module):
                module = find(lambda m: m.ID == db_module.id,
                              module_manager.all_modules)
                if module:
                    module.db_module = db_module

            return render_template("admin/modules.html",
                                   modules=module_manager.all_modules)
Пример #22
0
 def on_module_update(self, data, conn):
     log.info('ModuleManager: module.update begin ({})'.format(data))
     # self.reload()
     new_state = data.get('new_state', None)
     if new_state is True:
         self.enable_module(data['id'])
     elif new_state is False:
         self.disable_module(data['id'])
     else:
         module = find(lambda m: m.ID == data['id'], self.all_modules)
         self.load_module(module)
     log.info('ModuleManager: module.update done')
Пример #23
0
    def modules(**options):
        module_manager = ModuleManager(None).load(do_reload=False)
        for module in module_manager.all_modules:
            module.db_module = None
        with DBManager.create_session_scope() as db_session:
            for db_module in db_session.query(Module):
                module = find(lambda m: m.ID == db_module.id, module_manager.all_modules)
                if module:
                    module.db_module = db_module

            return render_template('admin/modules.html',
                    modules=module_manager.all_modules)
Пример #24
0
    def get(self, raw_command_id):
        command_string = raw_command_id
        command_id = None

        try:
            command_id = int(command_string)
        except (ValueError, TypeError):
            pass

        if command_id:
            command = find(lambda c: c['id'] == command_id, pajbot.web.utils.get_cached_commands())
        else:
            command = find(lambda c: c['resolve_string'] == command_string, pajbot.web.utils.get_cached_commands())

        if not command:
            return {
                'message': 'A command with the given ID was not found.'
            }, 404

        return {
                'command': command
                }, 200
Пример #25
0
    def disable_module(self, module_id, reload_commands=False):
        module = find(lambda m: m.ID == module_id, self.all_modules)
        if module is None:
            log.error('No module with the ID {} found.'.format(module_id))
            return False

        module.disable(self.bot)

        if module not in self.modules:
            log.error('Module {} is not in the list of enabled modules pajaW'.format(module_id))
            return False

        self.modules.remove(module)
Пример #26
0
    def get(raw_command_id):
        command_string = raw_command_id
        command_id = None

        try:
            command_id = int(command_string)
        except (ValueError, TypeError):
            pass

        if command_id:
            command = find(lambda c: c["id"] == command_id,
                           pajbot.web.utils.get_cached_commands())
        else:
            command = find(lambda c: c["resolve_string"] == command_string,
                           pajbot.web.utils.get_cached_commands())

        if not command:
            return {
                "message": "A command with the given ID was not found."
            }, 404

        return {"command": command}, 200
Пример #27
0
    def privmsg(self, channel, message, increase_message=True):
        if increase_message:
            conn = find(
                lambda c: c.conn.is_connected() and c.num_msgs_sent < self.
                message_limit, self.connlist)
        else:
            conn = find(lambda c: c.conn.is_connected(), self.connlist)

        if conn is None:
            log.error(
                'No available connections to send messages from. Delaying message a few seconds.'
            )
            self.reactor.execute_delayed(2, self.privmsg,
                                         (channel, message, increase_message))
            return False

        conn.conn.privmsg(channel, message)
        if increase_message:
            conn.num_msgs_sent += 1
            self.reactor.execute_delayed(31, conn.reduce_msgs_sent)

            if conn.num_msgs_sent >= self.message_limit:
                self.run_maintenance()
Пример #28
0
    def reload(self):
        # TODO: Make disable/enable better, so we don't need to disable modules
        # that we're just going to enable again further down below.
        for module in self.modules:
            module.disable(self.bot)

        self.modules = []

        with DBManager.create_session_scope() as db_session:
            for enabled_module in db_session.query(Module).filter_by(
                    enabled=True):
                module = self.get_module(enabled_module.id)
                if module is not None:
                    options = {}
                    if enabled_module.settings is not None:
                        try:
                            options["settings"] = json.loads(
                                enabled_module.settings)
                        except ValueError:
                            log.warning("Invalid JSON")

                    self.modules.append(module.load(**options))
                    module.enable(self.bot)

        to_be_removed = []
        self.modules.sort(
            key=lambda m: 1 if m.PARENT_MODULE is not None else 0)
        for module in self.modules:
            if module.PARENT_MODULE is None:
                module.submodules = []
            else:
                parent = find(lambda m: m.__class__ == module.PARENT_MODULE,
                              self.modules)
                if parent is not None:
                    parent.submodules.append(module)
                    module.parent_module = parent
                else:
                    # log.warning('Missing parent for module {}, disabling it.'.format(module.NAME))
                    module.parent_module = None
                    to_be_removed.append(module)

        for module in to_be_removed:
            module.disable(self.bot)
            self.modules.remove(module)

        # Perform a last on_loaded call on each module.
        # This is used for things that require submodules to be loaded properly
        # i.e. the quest system
        for module in self.modules:
            module.on_loaded()
Пример #29
0
    def on_timer_remove(self, data, conn):
        try:
            timer_id = int(data['id'])
        except (KeyError, ValueError):
            log.warn('No timer ID found in on_timer_update')
            return False

        removed_timer = find(lambda timer: timer.id == timer_id, self.timers)
        if removed_timer:
            if removed_timer in self.timers:
                self.timers.remove(removed_timer)
            if removed_timer in self.online_timers:
                self.online_timers.remove(removed_timer)
            if removed_timer in self.offline_timers:
                self.offline_timers.remove(removed_timer)
Пример #30
0
    def enable_module(self, module_id):
        log.debug('Enabling module {}'.format(module_id))
        module = find(lambda m: m.ID == module_id, self.all_modules)
        if module is None:
            log.error('No module with the ID {} found.'.format(module_id))
            return False

        module.enable(self.bot)

        if module in self.modules:
            log.error('Module {} is already in the list of enabled modules pajaW'.format(module_id))
            return False

        self.modules.append(module)

        self.load_module(module)
Пример #31
0
    def on_command_update(self, data):
        try:
            command_id = int(data["command_id"])
        except (KeyError, ValueError):
            log.warning("No command ID found in on_command_update")
            return

        command = find(lambda command: command.id == command_id, self.db_commands.values())
        if command is not None:
            self.remove_command_aliases(command)

        self.load_by_id(command_id)

        log.debug("Reloaded command with id {}".format(command_id))

        self.rebuild()
Пример #32
0
    def on_command_update(self, data, conn):
        try:
            command_id = int(data['command_id'])
        except (KeyError, ValueError):
            log.warn('No command ID found in on_command_update')
            return False

        command = find(lambda command: command.id == command_id, self.db_commands.values())
        if command is not None:
            self.remove_command_aliases(command)

        self.load_by_id(command_id)

        log.debug('Reloaded command with id {}'.format(command_id))

        self.rebuild()
Пример #33
0
    def on_banphrase_remove(self, data, conn):
        try:
            banphrase_id = int(data['id'])
        except (KeyError, ValueError):
            log.warn('No banphrase ID found in on_banphrase_remove')
            return False

        removed_banphrase = find(lambda banphrase: banphrase.id == banphrase_id, self.banphrases)
        if removed_banphrase:
            if removed_banphrase.data and removed_banphrase.data in self.db_session:
                self.db_session.expunge(removed_banphrase.data)

            if removed_banphrase in self.enabled_banphrases:
                self.enabled_banphrases.remove(removed_banphrase)

            if removed_banphrase in self.banphrases:
                self.banphrases.remove(removed_banphrase)
Пример #34
0
def test_find_iterate():
    from pajbot.utils import find

    d = {
        "foo": True,
        "bar": True,
        "xD": False,
    }

    haystack = ["foo", "baz", "bar"]

    for k, v in d.items():
        needle = find(lambda t: t == k, haystack)
        if v:
            assert needle == k
        else:
            assert needle is None
Пример #35
0
    def on_timer_remove(self, data):
        try:
            timer_id = int(data["id"])
        except (KeyError, ValueError):
            log.warning("No timer ID found in on_timer_update")
            return False

        removed_timer = find(lambda timer: timer.id == timer_id, self.timers)
        if removed_timer:
            if removed_timer in self.timers:
                self.timers.remove(removed_timer)
            if removed_timer in self.online_timers:
                self.online_timers.remove(removed_timer)
            if removed_timer in self.offline_timers:
                self.offline_timers.remove(removed_timer)

        return True
Пример #36
0
    def on_banphrase_remove(self, data):
        try:
            banphrase_id = int(data["id"])
        except (KeyError, ValueError):
            log.warning("No banphrase ID found in on_banphrase_remove")
            return False

        removed_banphrase = find(lambda banphrase: banphrase.id == banphrase_id, self.banphrases)
        if removed_banphrase:
            if removed_banphrase.data and removed_banphrase.data in self.db_session:
                self.db_session.expunge(removed_banphrase.data)

            if removed_banphrase in self.enabled_banphrases:
                self.enabled_banphrases.remove(removed_banphrase)

            if removed_banphrase in self.banphrases:
                self.banphrases.remove(removed_banphrase)
Пример #37
0
    def on_timer_update(self, data):
        try:
            timer_id = int(data["id"])
        except (KeyError, ValueError):
            log.warning("No timer ID found in on_timer_update")
            return False

        updated_timer = find(lambda timer: timer.id == timer_id, self.timers)
        if updated_timer:
            with DBManager.create_session_scope(
                    expire_on_commit=False) as db_session:
                db_session.add(updated_timer)
                db_session.refresh(updated_timer)
                updated_timer.refresh_action()
                db_session.expunge(updated_timer)
        else:
            with DBManager.create_session_scope(
                    expire_on_commit=False) as db_session:
                updated_timer = db_session.query(Timer).filter_by(
                    id=timer_id).one_or_none()

        # Add the updated timer to the timer lists if required
        if updated_timer:
            if updated_timer not in self.timers:
                self.timers.append(updated_timer)

            if updated_timer not in self.online_timers:
                if updated_timer.interval_online > 0:
                    self.online_timers.append(updated_timer)
                    updated_timer.refresh_tts()

            if updated_timer not in self.offline_timers:
                if updated_timer.interval_offline > 0:
                    self.offline_timers.append(updated_timer)
                    updated_timer.refresh_tts()

        for timer in self.online_timers:
            if timer.enabled is False or timer.interval_online <= 0:
                self.online_timers.remove(timer)

        for timer in self.offline_timers:
            if timer.enabled is False or timer.interval_offline <= 0:
                self.offline_timers.remove(timer)

        return True
Пример #38
0
    def on_managers_loaded(self):
        if self.current_quest is None:
            redis = RedisManager.get()

            current_quest_id = redis.get(self.current_quest_key)

            log.info('Try to load submodule with ID {}'.format(current_quest_id))

            if current_quest_id is not None:
                current_quest_id = current_quest_id
                quest = find(lambda m: m.ID == current_quest_id, self.submodules)

                if quest is not None:
                    log.info('Resumed quest {}'.format(quest.get_objective()))
                    self.current_quest = quest
                    self.current_quest.start_quest()
                else:
                    log.info('No quest with id {} found in submodules ({})'.format(current_quest_id, self.submodules))
Пример #39
0
    def on_command_remove(self, data):
        try:
            command_id = int(data["command_id"])
        except (KeyError, ValueError):
            log.warning("No command ID found in on_command_update")
            return

        command = find(lambda command: command.id == command_id, self.db_commands.values())
        if command is None:
            log.warning("Invalid ID sent to on_command_update")
            return

        self.db_session.expunge(command.data)
        self.remove_command_aliases(command)

        log.debug("Remove command with id {}".format(command_id))

        self.rebuild()
Пример #40
0
    def on_command_remove(self, data, conn):
        try:
            command_id = int(data['command_id'])
        except (KeyError, ValueError):
            log.warn('No command ID found in on_command_update')
            return False

        command = find(lambda command: command.id == command_id, self.db_commands.values())
        if command is None:
            log.warn('Invalid ID sent to on_command_update')
            return False

        self.db_session.expunge(command.data)
        self.remove_command_aliases(command)

        log.debug('Remove command with id {}'.format(command_id))

        self.rebuild()
Пример #41
0
    def _disable_orphan_modules(self) -> None:
        to_be_removed: List[BaseModule] = []
        self.modules.sort(key=lambda m: 1 if m.PARENT_MODULE is not None else 0)
        for module in self.modules:
            if module.PARENT_MODULE is None:
                module.submodules = []
            else:
                parent = find(lambda m: m.__class__ == module.PARENT_MODULE, self.modules)
                if parent is not None:
                    parent.submodules.append(module)
                    module.parent_module = parent
                else:
                    # log.warning('Missing parent for module {}, disabling it.'.format(module.NAME))
                    module.parent_module = None
                    to_be_removed.append(module)

        for module in to_be_removed:
            module.disable(self.bot)
            self.modules.remove(module)
Пример #42
0
    def on_autoresponse_remove(self, data, conn):
        try:
            autoresponse_id = int(data['id'])
        except (KeyError, ValueError):
            log.warn('No autoresponse ID found in on_autoresponse_remove')
            return False

        removed_autoresponse = find(
            lambda autoresponse: autoresponse.id == autoresponse_id,
            self.autoresponses)
        if removed_autoresponse:
            if removed_autoresponse.data and removed_autoresponse.data in self.db_session:
                self.db_session.expunge(removed_autoresponse.data)

            if removed_autoresponse in self.enabled_autoresponses:
                self.enabled_autoresponses.remove(removed_autoresponse)

            if removed_autoresponse in self.autoresponses:
                self.autoresponses.remove(removed_autoresponse)
Пример #43
0
    def load(self, do_reload=True):
        """ Load module classes """

        from pajbot.modules import available_modules

        self.all_modules = [module(self.bot) for module in available_modules]

        with DBManager.create_session_scope() as db_session:
            # Make sure there's a row in the DB for each module that's available
            db_modules = db_session.query(Module).all()
            for module in self.all_modules:
                mod = find(lambda db_module, registered_module=module: db_module.id == registered_module.ID, db_modules)
                if mod is None:
                    log.info("Creating row in DB for module {}".format(module.ID))
                    mod = Module(module.ID, enabled=module.ENABLED_DEFAULT)
                    db_session.add(mod)

        if do_reload is True:
            self.reload()

        return self
Пример #44
0
    def load(self, do_reload=True):
        """ Load module classes """

        from pajbot.modules import available_modules

        self.all_modules = [module() for module in available_modules]

        with DBManager.create_session_scope() as db_session:
            # Make sure there's a row in the DB for each module that's available
            db_modules = db_session.query(Module).all()
            for module in self.all_modules:
                mod = find(lambda m: m.id == module.ID, db_modules)
                if mod is None:
                    log.info('Creating row in DB for module {}'.format(module.ID))
                    mod = Module(module.ID, enabled=module.ENABLED_DEFAULT)
                    db_session.add(mod)

        if do_reload is True:
            self.reload()

        return self
Пример #45
0
    def pleblist_history_stream(stream_id):
        with DBManager.create_session_scope() as session:
            stream = session.query(Stream).filter_by(
                id=stream_id).one_or_none()
            if stream is None:
                return render_template('pleblist_history_404.html'), 404

            previous_stream = session.query(Stream).filter_by(id=stream_id -
                                                              1).one_or_none()
            next_stream = session.query(Stream).filter_by(id=stream_id +
                                                          1).one_or_none()

            q = session.query(PleblistSong, User).outerjoin(
                User, PleblistSong.user_id == User.id).filter(
                    PleblistSong.stream_id == stream.id).order_by(
                        PleblistSong.id.asc(), PleblistSong.id.asc())
            songs = []
            for song, user in q:
                song.user = user
                songs.append(song)

            total_length_left = sum([
                song.skip_after or song.song_info.duration if
                song.date_played is None and song.song_info is not None else 0
                for song in songs
            ])

            first_unplayed_song = find(lambda song: song.date_played is None,
                                       songs)
            stream_chunks = session.query(StreamChunk).filter(
                StreamChunk.stream_id == stream.id).all()

            return render_template('pleblist_history.html',
                                   stream=stream,
                                   previous_stream=previous_stream,
                                   next_stream=next_stream,
                                   songs=songs,
                                   total_length_left=total_length_left,
                                   first_unplayed_song=first_unplayed_song,
                                   stream_chunks=stream_chunks)
Пример #46
0
    def on_managers_loaded(self):
        if self.current_quest is None:
            redis = RedisManager.get()

            current_quest_id = redis.get(self.current_quest_key)

            log.info(
                'Try to load submodule with ID {}'.format(current_quest_id))

            if current_quest_id is not None:
                current_quest_id = current_quest_id
                quest = find(lambda m: m.ID == current_quest_id,
                             self.submodules)

                if quest is not None:
                    log.info('Resumed quest {}'.format(quest.get_objective()))
                    self.current_quest = quest
                    self.current_quest.start_quest()
                else:
                    log.info(
                        'No quest with id {} found in submodules ({})'.format(
                            current_quest_id, self.submodules))
Пример #47
0
    def parse_settings(self, **in_settings):
        ret = {}
        for key, value in in_settings.items():
            setting = find(lambda setting: setting.key == key, self.SETTINGS)
            if setting is None:
                # We were passed a setting that's not available for this module
                return False
            log.debug('{}: {}'.format(key, value))
            res, new_value = setting.validate(value)
            if res is False:
                # Something went wrong when validating one of the settings
                log.warn(new_value)
                return False

            ret[key] = new_value

        for setting in self.SETTINGS:
            if setting.type == 'boolean':
                if setting.key not in ret:
                    ret[setting.key] = False
                    log.debug('{}: {} - special'.format(setting.key, False))

        return ret
Пример #48
0
 def check_message(self, message, user):
     match = find(lambda banphrase: banphrase.match(message, user), self.enabled_banphrases)
     return match or False
Пример #49
0
 def get_module(self, module_id):
     return find(lambda m: m.ID == module_id, self.all_modules)