-
Notifications
You must be signed in to change notification settings - Fork 4
/
gevent-websocket.py
executable file
·176 lines (136 loc) · 5.44 KB
/
gevent-websocket.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#!/usr/bin/env python
"""
Websocket Gevent Webserver
"""
__copyright__ = """
Copyright (C) by Wilco Baan Hofman <[email protected]> 2013
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from gevent import monkey
monkey.patch_all()
from videoconference.wsgi import application
import simplejson as json
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
from websockets.websockethandler import Handler
from websockets.sockets import WebSockets
from scheduler.models import MCU, Reservation
from django.contrib.sessions.backends.db import SessionStore
from django.contrib.auth.models import User
from importlib import import_module
from django.http import parse_cookie
from django.contrib.sessions.models import Session
from django.utils import timezone
from copy import copy
import socket
from geventwebsocket.python_fixes import makefile
import uwsgi
class WSGIMiddlewareHandler(WebSocketHandler):
def __init__(self, environ, start_response, application):
self.environ = environ
self.socket = socket.fromfd(uwsgi.connection_fd(), socket.AF_INET, socket.SOCK_STREAM)
self.rfile = makefile(self.socket)
self.application = application
self.start_response = start_response
self.request_version = environ['SERVER_PROTOCOL']
def log_request(self):
pass
def ws_middleware(wrapped_app):
def application(environ, start_response):
handler = WSGIMiddlewareHandler(environ, start_response, wrapped_app)
upgrade = environ.get('HTTP_UPGRADE', '').lower()
if upgrade == 'websocket':
connection = environ.get('HTTP_CONNECTION', '').lower()
if 'upgrade' in connection:
return handler._handle_websocket()
return wrapped_app(environ, start_response)
return application
global_sockets = WebSockets()
def websocket_app(environ, start_response):
if not 'wsgi.websocket' in environ:
print "Not a websocket"
return
ws = environ["wsgi.websocket"]
print ws
# Important to call, otherwise we may get stale user sessions
SessionStore.clear_expired()
# Get the session object and implicitly check if the session is valid
cookie = parse_cookie(environ['HTTP_COOKIE'])
if not 'sessionid' in cookie:
print "No session cookie"
return
s = SessionStore(session_key=cookie['sessionid'])
if not '_auth_user_id' in s:
print "Invalid session"
return
user = User.objects.get(pk=s['_auth_user_id'])
if not user:
print "Invalid user"
return
path = environ['PATH_INFO'].split('/')
if len(path) < 3 or path[1] != 'websocket' or path[2] != 'conference' or not path[3].isdigit():
print "Invalid path"
return
conference_id = int(path[3])
conference = Reservation.objects.get(pk=conference_id)
if conference.user != user:
print "User not owner of this conference"
return
#if conference.end_time < timezone.now() or conference.begin_time > timezone.now():
# print "Conference not currently in progress"
# return
# FIXME Hardcoded
backend_info = {
'mcu': '127.0.0.1',
'room': 'room101',
}
socket_info = copy(global_sockets)
socket_info.subscribe(ws, conference)
interface = Handler(backend_info=backend_info, conference=conference, sockets=socket_info)
while True:
try:
data = ws.receive()
if data is None:
socket_info.close(socket_info.local)
return
try:
message = json.loads(data)
except Exception as e:
print repr(e), data
return
handlers = {
'LIST_MOSAIC': 'list_mosaic',
'LIST_PARTICIPANTS': 'list_participants',
'MOVE_PARTICIPANT': 'move_participant',
'REMOVE_PARTICIPANT': 'remove_participant',
'OFFER_SDP': 'offer_sdp',
'SDP_OK': 'sdp_ok',
}
if not 'message_type' in message:
print "Message has no message type"
return
if not message['message_type'] in handlers:
print "No handler for message type", message['message_type']
return
print message['message_type'], "received"
# Find and call the method in the MCUInterface class instance
func = getattr(interface, handlers[message['message_type']])
func(message['data'])
except:
socket_info.close(socket_info.local)
ws.close()
raise
if __name__ == "__main__":
server = pywsgi.WSGIServer(("", 8000), websocket_app, handler_class=WebSocketHandler)
server.serve_forever()
else:
application = ws_middleware(websocket_app)