Source

ginsfsm / ginsfsm / protocols / sockjs / server / c_sockjs_server.py

The default branch has multiple heads

Full commit
# -*- encoding: utf-8 -*-
""" GSockjsServer GObj

.. autoclass:: GSockjsServer
    :members: start_up

"""

from pyramid.traversal import resource_path
from pyramid.security import (
    Allow,
    Everyone,
    DENY_ALL,
)

from ginsfsm.gobj import GObj
from ginsfsm.protocols.sockjs.server.static import (
    GInfo,
    GIFrame,
)
from ginsfsm.protocols.sockjs.server.c_session import GSockjsSession


#-------------------------------------------#
#               Actions
#-------------------------------------------#
def ac_timeout(self, event):
    self.counter += 1
    self.send_event(self.timer, 'EV_SET_TIMER', seconds=self.seconds)


def ac_sample(self, event):
    """ Event attributes:
        * :attr:`data`: example.

    """
    self.broadcast_event('EV_OUTPUT_EVENT', data=event.data)


GSOCKJSSERVER_FSM = {
    'event_list': (
        'EV_INPUT_EVENT:top input',
        'EV_OUTPUT_EVENT:top output',
    ),
    'state_list': (
        'ST_IDLE',
    ),
    'machine': {
        'ST_IDLE':
        (
            ('EV_INPUT_EVENT',      ac_sample,      None),
        ),
    }
}

GSOCKJSSERVER_GCONFIG = {
    'subscriber': [None, None, 0, None,
        "subcriber of all output-events."
        "Default is ``None``, i.e., the parent"
    ],
    'sockjs_app_class': [None, None, 0, None,
        "Class to receive sockjs events."
        "GSockjsServer will create a instance of this class."
    ],
    'permission': [None, None, 0, None, "Pyramid permission"],

    # like tornado settings
    'session_check_interval': [int, 1, 0, None,
        "Sessions check interval in seconds"],
    'disconnect_delay': [int, 5, 0, None,
        "Session expiration in seconds"],
    'heartbeat_delay': [int, 25, 0, None,
        "Heartbeat time in seconds. Do not change this value unless "
        "you absolutely sure that new value will work."
    ],
    'disabled_transports': [tuple, (), 0, None, "Transports disabled"],
    'sockjs_url': [str,
        'http://cdn.sockjs.org/sockjs-0.3.min.js', 0, None, "SockJS location"
    ],
    'response_limit': [int, 128 * 1024, 0, None, "Max response body size"],
    'jsessionid': [bool, True, 0, None,
        "Enable or disable JSESSIONID cookie handling"
    ],
    'verify_ip': [bool, True, 0, None,
        "Enable IP checks for polling transports. If enabled, "
        "all subsequent polling calls should be from the same IP address."
    ],
}


class GSockjsServer(GObj):
    """  GSockjsServer GObj.
    This gobj only works
    with `Pyramid <http://www.pylonsproject.org/>`_ framework.

    .. ginsfsm::
       :fsm: GSOCKJSSERVER_FSM
       :gconfig: GSOCKJSSERVER_GCONFIG

    *Input-Events:*
        * :attr:`'EV_INPUT_EVENT'`: sample input event.

          Event attributes:

              * ``data``: sample event attribute.

    *Output-Events:*
        * :attr:`'EV_OUTPUT_EVENT'`: sample output event.

          Event attributes:

              * ``data``: sample event attribute.

    """
    __acl__ = [
        (Allow, Everyone, 'view'),
        (DENY_ALL),
    ]

    def __init__(self):
        GObj.__init__(self, GSOCKJSSERVER_FSM, GSOCKJSSERVER_GCONFIG)

    def start_up(self):
        """ Initialization zone.
        """
        if self.subscriber is None:
            self.subscriber = self.parent
        self.subscribe_event(None, self.subscriber)

        if self.logger:
            self.logger.debug(
                ">>> sockjs resource path: " + resource_path(self)
            )

        #----------------------------------------------#
        #           Static handlers
        #----------------------------------------------#

        # Info
        self.create_gobj(
            'info',
            GInfo,
            self,
            sockjs_server=self,
        )
        # IFrame
        self.create_gobj(
            'iframe[0-9-.a-z_]*.html',
            GIFrame,
            self,
            __re_name__=True,
            sockjs_server=self,
        )

        #----------------------------------------------#
        #           Session URLs
        #----------------------------------------------#
        self.sockjs_session = self.create_gobj(
            '^\d{3}$',
            GSockjsSession,
            self,
            __re_name__=True,
            sockjs_server=self,
        )


#----------------------------------------------------------------#
#                   Views
#----------------------------------------------------------------#
from ginsfsm.protocols.sockjs.server.basehandler import BaseHandler
from pyramid.view import view_config


@view_config(
    context=GSockjsServer,
    name='',
    attr='get',
    request_method='GET',
)
class GreetingsHandler(BaseHandler):
    """SockJS greetings page handler"""
    def get(self):
        response = self.response
        self.enable_cache()
        response.content_type = 'text/plain; charset=UTF-8'
        data = 'Welcome to SockJS!\n'
        response.body = data
        return response