コード例 #1
0
ファイル: __init__.py プロジェクト: sh-ft/mudwyrm_users
 def __init__(self, to_mud, to_console):
     """Called when a session is being opened.
     
     Both arguments are function objects:
     
     ``to_mud(text, type='raw')``
         Send a message to the mud. Message type can be either 'raw'
         for normal text, or 'gmcp' for GMCP messages.
         
     ``to_console(message)``
         Send a message to the console (JSON-serializable object).
     """
     self.to_mud = to_mud
     self.to_console = to_console
     self._parser = MudParser(strip_unsupported=False, no_bright_bg=True)
     self._script_output = { 'echo': [], 'debug': [], 'warning': [],
         'error': [], 'send': [] }
     self._buffering_script_output = False
     self._call_stack = []
     
     db_url = 'sqlite:///%s/data/database.db' % os.path.dirname(__file__)
     self._sqlengine = sqlalchemy.create_engine(db_url, echo=True)
     database.init(self._sqlengine)
     self.db = database.DBSession()
     self._load_scripts()
     database.create_tables(self._sqlengine)
コード例 #2
0
ファイル: __init__.py プロジェクト: sh-ft/mudwyrm_users
class Processor(BaseProcessor):
    def __init__(self, to_mud, to_console):
        """Called when a session is being opened.
        
        Both arguments are function objects:
        
        ``to_mud(text, type='raw')``
            Send a message to the mud. Message type can be either 'raw'
            for normal text, or 'gmcp' for GMCP messages.
            
        ``to_console(message)``
            Send a message to the console (JSON-serializable object).
        """
        self.to_mud = to_mud
        self.to_console = to_console
        self._parser = MudParser(strip_unsupported=False, no_bright_bg=True)
        self._script_output = { 'echo': [], 'debug': [], 'warning': [],
            'error': [], 'send': [] }
        self._buffering_script_output = False
        self._call_stack = []
        
        db_url = 'sqlite:///%s/data/database.db' % os.path.dirname(__file__)
        self._sqlengine = sqlalchemy.create_engine(db_url, echo=True)
        database.init(self._sqlengine)
        self.db = database.DBSession()
        self._load_scripts()
        database.create_tables(self._sqlengine)
        
    def shutdown(self):
        """Called when a session is being closed."""
        database.DBSession.remove()
        
    def reload(self):
        """Called when scripts reloading is requested."""
        database.DBSession.remove()
        database.init(self._sqlengine)
        self.db = database.DBSession()
        self._reload_scripts()
        database.create_tables(self._sqlengine)
    
    def from_mud(self, message, type):
        """Called when a message has been received from the mud."""
        if type == 'raw':
            self._recent_events = self._current_events
            self._current_events = {}
            self._recently_finished_actions = []
            formatted_message, stripped_line = self._parser.parse(message)
            self._process_triggers(stripped_line, formatted_message)
        elif type == 'gmcp':
            self.raise_event('GMCP', message=message)
        
    def from_console(self, message):
        """Called when a message has been received from the console."""
        message = AttrDict(message)
        if message.type == 'text':
            self._process_aliases(message.text)
        self.raise_event('ConsoleMessage', message=message)
        
    def _dispatch_output(self, type, message):
        if type == 'send':
            self.to_mud(message['text'])
        self.to_console(message)
            
    def _dispatch_all_buffered_output(self):
        for t, v in self._script_output.iteritems():
            for d in v:
                self._dispatch_output(t, d)
                
    def _handle_output(self, type, message_type, text):
        message = {
            'type': message_type,
            'text': text
        }
        if self._call_stack:
            message['debug_info'] = {
                'call_stack': list(self._call_stack)
            }
        if self._buffering_script_output:
            self._script_output[type].append(message)
        else:
            self._dispatch_output(type, message)
        
    def echo(self, text):
        """Send a text message to the console."""
        self._handle_output('echo', 'script', text)
        
    def hecho(self, formatted_text):
        """Send a highlights message to the console."""
        message = {
            'type': 'highlight',
            'formatted_text': ConsoleMessage.construct(formatted_text).to_dict()
        }
        self.to_console(message)
        
    def notification(self, title, text):
        """Send a notification message to the console."""
        message = {
            'type': 'notification',
            'title': title,
            'text': text
        }
        self.to_console(message)
        
    def debug(self, text):
        """Send a debug message to the console."""
        self._handle_output('debug', 'script_debug', text)
        
    def warning(self, text):
        """Send a warning message to the console."""
        self._handle_output('warning', 'script_warning', text)
        
    def error(self, text):
        """Send an error message to the console."""
        self._handle_output('error', 'script_error', text)
        
    def send(self, text):
        """Send a text message to the mud."""
        self._handle_output('send', 'user', text)
        
    def gmcp(self, message):
        """Send a GMCP message to the mud."""
        self.to_mud(message, type='gmcp')
            
    def raise_event(self, event_name, **args):
        """Raise an event and process it calling event handlers' callbacks."""
        handled = False
        self._current_events[event_name] = AttrDict(args)
        
        def process(handler, action=None):
            handler_args = AttrDict(args)
            following_test_passed = True
            if 'following' in handler.params:
                event_name = handler.params['following']
                if event_name in self._recent_events:
                    handler_args['event_args'] = self._recent_events[event_name]
                else:
                    following_test_passed = False
            if not following_test_passed:
                return False
            self._call_stack.append(self._script_object_info(handler, action))
            try:
                if not action:
                    if handler():
                        handler.callback(**handler_args)
                        return True
                else:
                    if handler(action):
                        handler_args['action'] = action
                        handler.callback(**handler_args)
                        if event_handler.params.get('finish_action', False):
                            self.finish_action(action)
                        return True
            except Exception, e:
                handler_name = handler.__name__
                if action:
                    handler_name = action.__name__ + '.' + handler_name
                self.error("%s has been raised in event handler %s: %s. %s"
                        % (e.__class__.__name__, handler_name,
                           str(e.args), traceback.format_exc()))
            finally: