forked from Tendrid/Tornado-PubSub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubsub.py
337 lines (308 loc) · 10.8 KB
/
pubsub.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import settings
import uuid
import tornado.web
class PubSub(object):
channels = {}
master_list = {}
db = None
chan_set = {}
_gate = {}
_collections = {}
users = {}
def connect(self,id):
try:
return self._collections[id]
except:
#todo: try to load collection from db, then fail
return None
class _conn(object):
def __init__(self,raw):
raw = raw[0]
self.gate = pubSubInstance._gate[raw['gate']]
self.loc = raw['loc']
self.db = self.gate.db()
def _buildGates(self):
for comm in __import__("gates.__init__").__all__:
self._gate[comm] = __import__("gates.{0}".format(comm),None,None,'*')
coll = self._gate[settings.DEFAULT_STORAGE].db().getCollections()
for collection in coll:
self._collections[collection.id] = self._conn(coll)
self.db = self._gate[settings.DEFAULT_STORAGE].db()
def _buildCallbacks(self):
# parent callback
def func(cls,param):
#todo: reference parent, adobt rules
pass
self.chan_set["parent"] = func
# set channel history limit callback
def func(cls,param):
cls._setHistoryLimit(param)
self.chan_set["historylimit"] = func
"""BETA"""
def subscribe(self,channel,user):
try:
self.channels[channel].subscribe(user)
except KeyError:
return dict(error='invalid channel')
"""BETA"""
def getChannel(self,channel,default):
try:
return self.channels[channel]
except KeyError:
return None
"""BETA"""
def getList(self,user):
for channel in user.channels:
messages = []
mlist = {}
c = self.channels[channel]
try:
cursor = user.history[channel]
except KeyError:
cursor = None
for item in c.history:
if cursor == item[0]:
break
try:
if not mlist[item[1]]:
mlist[item[1]] = c.library[item[1]]
except KeyError:
mlist[item[1]] = c.library[item[1]]
for item in mlist:
messages.append(mlist[item])
if len(messages) > 0:
return messages
return None
"""BETA"""
def waitForEvent(self, callback, user):
messages = self.getList(user)
if not user.callback:
user.callback = callback
else:
#todo: clean up. not universal.
self.finish(dict(error='Already logged in.',redirect='/reset/user'))
"""Loaders"""
def preLoadData(self,collection_id,announce = False):
try:
col = self._collections[collection_id]
except:
#todo: handle this
print "FAILED TO LOAD COLLECTION"
return None
items = col.db.getChannelItems(col.loc)
for row in items:
try:
self.channels[row['channel']].updateItem(row, collection_id, announce)
except KeyError:
self.loadChannels()
self.channels[row['channel']].updateItem(row, collection_id, announce)
"""BETA"""
def loadChannels(self):
rows = self.db.getChannels()
for row in rows:
if row['channel'] not in self.channels:
print 'adding channel '+ row['channel']
self.channels[row['channel']] = Channel(row)
return self.channels
class Channel():
def __init__(self, raw):
self.subscribers = {}
self.history = []
self.library = {}
self.history_limit = None
self.id = str(raw['id'])
self.path = str(raw['channel'])
self.name = str(raw['name'])
self.description = str(raw['description'])
#inits:
self._config(raw['config'])
def _config(self,params):
if params == None:
return
try:
#TODO: dont use eval. security!
params = eval(params)
except:
#print "error in params"
return
#load settings
for param in params:
if param in settings.CHANNEL_PARAMS:
try:
pubSubInstance.chan_set[param](self, params[param])
except KeyError:
print "Channel callback {0} not set.".format(param)
def _setHistoryLimit(self,limit):
self.history_limit = limit
self.cleanHistory()
def cleanHistory(self):
if self.history_limit:
#pop by oldest from self.history where self.limit > count
#delete by id from self.library where id in popped data
pass
def subscribe(self, user):
self.subscribers[user.id()] = user
user.getUpdate(self)
user.runQueue()
try:
return self.history[0]
except IndexError:
return None
def unsubscribe(self, user):
del self.subscribers[user.id()]
def publish(self, ChannelItem):
self.library[ChannelItem.id] = ChannelItem
self.addToHistory(ChannelItem)
users = self.subscribers.values()
for user in users:
user.getUpdate(self.path)
return users
def addToHistory(self, ci):
self.history.insert(0,[str(uuid.uuid4()), ci.id])
def toDict(self):
return {'id':self.id,'path':self.path,'name':self.name,'description':self.description}
def updateItem(self,raw,collection_id,announce=True):
if raw['id']:
id = str(collection_id)+'_'+str(raw['id'])
try:
pubSubInstance.master_list[id].update(raw,announce)
except KeyError:
pubSubInstance.master_list[id] = ChannelItem(raw,announce)
self.addToHistory(pubSubInstance.master_list[id])
self.library[id] = pubSubInstance.master_list[id]
class ChannelItem():
def __init__(self,raw,announce = False):
self._id = raw['id']
self.id = str(raw['collection_id'])+'_'+str(raw['id'])
self.data = {}
self.channels = []
self.update(raw.copy(),announce)
self.collection = pubSubInstance.connect(raw['collection_id'])
def update(self,raw=None,pub=True):
if not raw:
raw = self.getFromDB()
for k,v in raw.items():
self.attr(k,v)
if pub:
self.publish()
def publish(self):
users = {}
#loop through all channels
for chan in self.channels:
#get a list of users subscribed to channel
for user in chan.publish(self):
users[user.id] = user
#loop through users, execute queues
for user in users.values():
user.runQueue()
def getFromDB(self):
rows = self.collection.db.getChannelItem(self._id)
for row in rows:
return row
def attr(self,key,val=False):
if val != False:
if not val:
val = ''
if key == 'channel':
self.addChan(val)
else:
self.data[key] = val
try:
if key == 'channel':
return self.channels
else:
return self.data[key]
except KeyError:
return None
def toObj(self):
retVal = self.data
retVal['id'] = self.id
retVal['channels'] = []
for chan in self.channels:
retVal['channels'].append(chan.path)
return retVal
def addChan(self,channel):
cls = PubSub
chan = cls.channels[channel]
if chan not in self.channels:
self.channels.append(chan)
class User():
def __init__(self, raw):
self.name = raw['name']
self.history = {}
self.callback = None
self.channels = {}
self.queue = []
def id(self):
return self.name
def auth(self):
#TODO: connect to db or whatever
return true
def subscribe(self,channel,announce=True):
try:
print self.name +' just subscribed to '+channel
hist = pubSubInstance.channels[channel].subscribe(self)
if hist:
self.history[hist[1]] = hist[0]
self.channels[channel] = pubSubInstance.channels[channel]
except KeyError:
#TODO: bubble up these errors
return dict(error='invalid channel')
if announce:
self.loadChannel(channel)
def unsubscribe(self,channel):
try:
print self.name +' just unsubscribed to '+channel
cls = PubSub
cls.channels[channel].unsubscribe(self)
except KeyError:
#TODO: bubble up these errors
return dict(error='invalid channel')
def getChannelCursor(self,channel):
try:
return self.history[channel]
except KeyError:
return None
def getUpdate(self,channel):
cursor = self.getChannelCursor(channel)
try:
mlist = {}
c = pubSubInstance.channels[channel]
for item in c.history:
if cursor == item[0]:
break
try:
if not mlist[item[1]]:
mlist[item[1]] = c.library[item[1]]
except KeyError:
mlist[item[1]] = c.library[item[1]]
for item in mlist:
if mlist[item] not in self.queue:
self.queue.append(mlist[item])
if len(self.queue) > 0:
self.history[c.path] = c.history[0][0]
return self.queue
except KeyError:
return None
def runQueue(self):
if self.queue != [] and self.callback:
messages = self.queue
self.queue = []
callback = self.callback
self.callback = None
callback(messages)
def loadChannel(self,channel):
messages = self.getUpdate(channel)
self.runQueue()
def reset(self):
#this can be done way better
self.callback(False)
self.callback = None
self.history = {}
self.channels = {}
self.queue = []
#init
pubSubInstance = PubSub()
pubSubInstance._buildGates()
pubSubInstance._buildCallbacks()
pubSubInstance.loadChannels()