Source

gevent_cometd / gevent_cometd / webapp / start.py

import json
import pkg_resources
import random
import uuid
from mako.template import Template

from pyramid.response import Response  # explicit response objects, no TL
from paste.httpserver import serve  # explicitly WSGI
from pyramid.view import view_config

from gevent_cometd import statics
from gevent_cometd.util import cometd_request, add_cors_headers


config = {
          'cometd.server':{'server':'http://127.0.0.1:8088', 'secret':'secret'},
          'webapp_url':'http://127.0.0.1:8080'
          }

#
#
# views
#
#

@view_config(route_name='connect')
def connect(request):
    """handle authorization of users trying to connect"""
    # handle preflight request
    if request.method == 'OPTIONS':
        res = Response('la la la')
        add_cors_headers(res)
        return res

    channels = request.json_body['channels']
    payload = { "user": request.params.get('user', 'anon_%s' % random.randint(1, 999999)),
                "conn_id": str(uuid.uuid4()),
                "channels": channels
            }
    response = cometd_request('/connect', payload, servers=[config['cometd.server']])
    payload['status'] = response[0]['status']
    res = Response(json.dumps(payload))
    add_cors_headers(res)
    return res


@view_config(route_name='subscribe')
def subscribe(request):
    """"can be used to subscribe specific connection to other channels"""
    # handle preflight request
    if request.method == 'OPTIONS':
        res = Response('la la la')
        add_cors_headers(res)
        return res
    request_data = request.json_body
    response = request_data.get('channels', [])
    payload = { "conn_id": request_data.get('conn_id', ''),
                "channels": request_data.get('channels', [])
                }
    cometd_request('/subscribe', payload, servers=[config['cometd.server']])
    res = Response(json.dumps(response))
    add_cors_headers(res)
    return res


@view_config(route_name='message')
def message(request):
    """send message to channel/users"""
    request_data = request.json_body
    payload = {
             'type': 'message',
             "user": request_data.get('user', 'system'),
             "channel": request_data.get('channel', 'unknown_channel'),
             'message':request_data.get('message')
             }
    cometd_request('/message', [payload], servers=[config['cometd.server']])
    res = Response('')
    add_cors_headers(res)
    return res

@view_config(route_name='channel_config')
def channel_config(request):
    """configure channel defaults"""
    payload = [('pub_chan', {
                           "presence":True,
                           "store_history":True,
                           "history_size":20
                           }),
               ('pub_chan2', {
                           "presence":True,
                           "salvagable": True,
                           "store_history":True,
                           "history_size":30
                           })
             ]
    cometd_request('/channel_config', payload, servers=[config['cometd.server']])
    res = Response('')
    add_cors_headers(res)
    return res


@view_config(route_name='index')
def demo(request):
    tmpl = Template(statics['templates']['demo.mak'])
    html = tmpl.render(request=request, config=config)
    return Response(html)


#
# start app
#

def start_app():
    from pyramid.config import Configurator
    config = Configurator()  # no global application object.
    config.scan('gevent_cometd.webapp')
    config.add_static_view('static', 'gevent_cometd:static')
    config.add_route('connect', '/connect')
    config.add_route('message', '/message')
    config.add_route('subscribe', '/subscribe')
    config.add_route('channel_config', '/channel_config')
    config.add_route('index', '/')
    app = config.make_wsgi_app()  # explicitly WSGI
    serve(app, host='0.0.0.0')  # explicitly WSGI