-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.py
153 lines (125 loc) · 4.75 KB
/
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
from app import app
import uuid
import logging
import json
from flask import (
request, current_app,
)
log = logging.getLogger(__name__)
print 'websocket'
class MultiDictionary(object):
def __init__(self):
self.dict = {}
def add(self, k, v):
self.dict.setdefault(k, set()).add(v)
def remove_val(self, k, v):
self.dict.setdefault(k, set()).remove(v)
if len(self.dict[k]) == 0:
self.remove(k)
def remove(self, k):
del self.dict[k]
def get(self, *args):
return self.dict.get(*args)
class WebSocketManager(object):
def __init__(self):
self.sockets = {}
self.topic_clientid_map = MultiDictionary()
self.clientid_topic_map = MultiDictionary()
self.auth_functions = {}
def remove_clientid(self, clientid):
topics = self.clientid_topic_map.get(clientid)
for topic in topics:
self.topic_clientid_map.remove_val(topic, clientid)
def remove_topic(self, topic):
clientids = self.topic_clientid_map.get(topic)
for clientid in clientids:
self.clientid_topic_map.remove_val(clientid, topic)
def subscribe_socket(self, socket, topic, clientid=None):
if clientid is None :
clientid = str(uuid.uuid4())
self.subscribe(clientid, topic)
self.add_socket(socket, clientid)
def can_subscribe(self, clientid, topic):
#auth goes here
return True
def register_auth(self, authtype, func):
self.auth_functions[authtype] = func
def auth(self, authtoken, topic):
#authtoken - some string, whatever you want it to be
#topic - string topic, of syntax type:value.
#topic type maps to auth function
authtype, topic = topic.split(":", 1)
if self.auth_functions.get(authtype):
return self.auth_functions[authtype](authtoken, topic)
else:
return True
def subscribe(self, clientid, topic):
if self.can_subscribe(clientid, topic):
self.topic_clientid_map.add(topic, clientid)
self.clientid_topic_map.add(clientid, topic)
def add_socket(self, socket, clientid):
self.sockets[clientid] = socket
def remove_socket(self, clientid):
del self.sockets[clientid]
def send(self, topic, msg, exclude=None):
if exclude is None:
exclude = set()
for clientid in tuple(self.topic_clientid_map.get(topic, [])):
if clientid in exclude:
continue
socket = self.sockets[clientid]
try:
socket.send(topic + ":" + msg)
except Exception as e: #what exception is this?if a client disconnects
log.exception(e)
self.remove_socket(clientid)
self.remove_clientid(clientid)
def run_socket(socket, manager, clientid=None):
clientid = clientid if clientid is not None else str(uuid.uuid4())
log.debug("CLIENTID %s", clientid)
while True:
msg = socket.receive()
if msg is None:
manager.remove_socket(clientid)
manager.remove_clientid(clientid)
break
msgobj = json.loads(msg)
if msgobj['msgtype'] == 'subscribe':
if manager.auth(msgobj.get('auth'), msgobj['topic']):
manager.add_socket(socket, clientid)
manager.subscribe(clientid, msgobj['topic'])
msg = json.dumps({
'msgtype' : 'status',
'status' : ['subscribesuccess', msgobj['topic'], clientid]
})
socket.send(msgobj['topic'] + ":" + msg)
else:
msg = json.dumps({
'msgtype' : 'error',
'error_msg' : 'unauthorized'
})
socket.send(msgobj['topic'] + ":" + msg)
return
def pub_from_redis(redisconn, wsmanager):
ps = redisconn.pubsub()
ps.psubscribe("*")
for message in ps.listen():
wsmanager.send(message['channel'], message['data'])
#web socket subscriber
@app.route('/sub')
def sub():
print 'SUB'
if request.environ.get('wsgi.websocket'):
ws = request.environ['wsgi.websocket']
run_socket(
ws,
app.wsmanager,
)
return "done"
from werkzeug.contrib.securecookie import SecureCookie
class SecureCookie(SecureCookie):
serialization_method = json
def secure_encode(adict, secretkey):
return SecureCookie(data=adict, secretkey=secretkey, new=True).serialize()
def secure_decode(astring, secretkey):
return SecureCookie.unserialize(astring, secretkey)