ProtocolHandler.py 2.67 KB
"""
@author Georg Hopp
"""
from contextlib import contextmanager

from Connection import Connection
from Event.EventHandler import EventHandler

class ProtocolHandler(EventHandler):
    def __init__(self):
        super(ProtocolHandler, self).__init__()

        self._event_methods = {
            Connection.eventId('new_data') : self._parse,
            Connection.eventId('send_msg') : self._compose,
            Connection.eventId('upgrade')  : self._upgrade
        }

    def _parse(self, event):
        for message in event.subject:
            try:
                """
                only because websockets currently have no message
                class which would handle this correctly...so we
                just ignore this problem here.
                """
                if message.isCloseMessage():
                    self.issueEvent(event.subject, 'new_msg', message)
                    if message.isResponse():
                        event.subject.setClose()    # setting this results in
                                                    # closing the endpoint as
                                                    # soon as everything was tried
                elif message.isUpgradeMessage():
                    if message.isRequest():
                        protocol = event.subject.getProtocol()
                        response = protocol.createUpgradeResponse(message)
                        self.issueEvent(event.subject, 'send_msg', response)
                    else:
                        protocol = event.subject.getProtocol()
                        self.issueEvent(event.subject, 'upgrade', message)
                else:
                    self.issueEvent(event.subject, 'new_msg', message)
            except Exception:
                pass

    def _compose(self, event):
        endpoint = event.subject
        message  = event.data

        if endpoint.compose(message):
            self.issueEvent(endpoint, 'write_ready')

            try:
                """
                only because websockets currently have no message
                class which would handle this correctly...so we
                just ignore this problem here.
                """
                if message.isResponse():
                    if message.isCloseMessage():
                        endpoint.setClose()
                    if message.isUpgradeMessage():
                        self.issueEvent(endpoint, 'upgrade', message)
            except Exception:
                pass

    def _upgrade(self, event):
        protocol  = event.subject.getProtocol()
        new_proto = protocol.upgrade(event.data)
        event.subject.setProtocol(new_proto)

# vim: set ft=python et ts=4 sw=4 sts=4: