-
Notifications
You must be signed in to change notification settings - Fork 27
/
MeteorClient.py
356 lines (284 loc) · 11.3 KB
/
MeteorClient.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import time
import datetime
from DDPClient import DDPClient
from pyee import EventEmitter
import hashlib
class MeteorClientException(Exception):
"""Custom Exception"""
pass
class CollectionData(object):
def __init__(self):
self.data = {}
def add_data(self, collection, id, fields):
if collection not in self.data:
self.data[collection] = {}
if not id in self.data[collection]:
self.data[collection][id] = {}
for key, value in fields.items():
self.data[collection][id][key] = value
def change_data(self, collection, id, fields, cleared):
for key, value in fields.items():
self.data[collection][id][key] = value
for key in cleared:
del self.data[collection][id][key]
def remove_data(self, collection, id):
del self.data[collection][id]
class MeteorClient(EventEmitter):
def __init__(self, url, auto_reconnect=True, auto_reconnect_timeout=0.5, debug=False):
EventEmitter.__init__(self)
self.collection_data = CollectionData()
self.ddp_client = DDPClient(url, auto_reconnect=auto_reconnect,
auto_reconnect_timeout=auto_reconnect_timeout, debug=debug)
self.ddp_client.on('connected', self.connected)
self.ddp_client.on('socket_closed', self.closed)
self.ddp_client.on('failed', self.failed)
self.ddp_client.on('added', self.added)
self.ddp_client.on('changed', self.changed)
self.ddp_client.on('removed', self.removed)
self.ddp_client.on('reconnected', self._reconnected)
self.connected = False
self.subscriptions = {}
self._login_data = None
self._login_token = None
def connect(self):
"""Connect to the meteor server"""
self.ddp_client.connect()
def close(self):
"""Close connection with meteor server"""
self.ddp_client.close()
def _reconnected(self):
"""Reconnect
Currently we get a new session every time so we have
to clear all the data an resubscribe"""
if self._login_data or self._login_token:
def reconnect_login_callback(error, result):
if error:
if self._login_token:
self._login_token = None
self._login(self._login_data,
callback=reconnect_login_callback)
return
else:
raise MeteorClientException(
'Failed to re-authenticate during reconnect')
self.connected = True
self._resubscribe()
if self._login_token:
self._resume(self._login_token,
callback=reconnect_login_callback)
else:
self._login(self._login_data,
callback=reconnect_login_callback)
else:
self._resubscribe()
def _resubscribe(self):
self.collection_data.data = {}
cur_subs = self.subscriptions.items()
self.subscriptions = {}
for name, value in cur_subs:
self.subscribe(name, value['params'])
self.emit('reconnected')
#
# Account Management
#
def login(self, user, password, token=None, callback=None):
"""Login with a username and password
Arguments:
user - username or email address
password - the password for the account
Keyword Arguments:
token - meteor resume token
callback - callback function containing error as first argument and login data"""
# TODO: keep the tokenExpires around so we know the next time
# we need to authenticate
# hash the password
hashed = hashlib.sha256(password).hexdigest()
# handle username or email address
if '@' in user:
user_object = {
'email': user
}
else:
user_object = {
'username': user
}
password_object = {
'algorithm': 'sha-256',
'digest': hashed
}
self._login_token = token
self._login_data = {'user': user_object, 'password': password_object}
if token:
self._resume(token, callback=callback)
else:
self._login(self._login_data, callback=callback)
def _resume(self, token, callback=None):
login_data = {'resume': token}
self._login(login_data, callback=callback)
def _login(self, login_data, callback=None):
self.emit('logging_in')
def logged_in(error, data):
if error:
if self._login_token:
self._login_token = None
self._login(self._login_data, callback=callback)
return
if callback:
callback(error, None)
return
self._login_token = data['token']
if callback:
callback(None, data)
self.emit('logged_in', data)
self.ddp_client.call('login', [login_data], callback=logged_in)
def logout(self, callback=None):
"""Logout a user
Keyword Arguments:
callback - callback function called when the user has been logged out"""
self.ddp_client.call('logout', [], callback=callback)
self.emit('logged_out')
#
# Meteor Method Call
#
def call(self, method, params, callback=None):
"""Call a remote method
Arguments:
method - remote method name
params - remote method parameters
Keyword Arguments:
callback - callback function containing return data"""
self._wait_for_connect()
self.ddp_client.call(method, params, callback=callback)
#
# Subscription Management
#
def subscribe(self, name, params=[], callback=None):
"""Subscribe to a collection
Arguments:
name - the name of the publication
params - the subscription parameters
Keyword Arguments:
callback - a function callback that returns an error (if exists)"""
self._wait_for_connect()
def subscribed(error, sub_id):
if error:
self._remove_sub_by_id(sub_id)
if callback:
callback(error.get('reason'))
return
if callback:
callback(None)
self.emit('subscribed', name)
if name in self.subscriptions:
raise MeteorClientException('Already subcribed to {}'.format(name))
sub_id = self.ddp_client.subscribe(name, params, subscribed)
self.subscriptions[name] = {
'id': sub_id,
'params': params
}
def unsubscribe(self, name):
"""Unsubscribe from a collection
Arguments:
name - the name of the publication"""
self._wait_for_connect()
if name not in self.subscriptions:
raise MeteorClientException('No subscription for {}'.format(name))
self.ddp_client.unsubscribe(self.subscriptions[name]['id'])
del self.subscriptions[name]
self.emit('unsubscribed', name)
#
# Collection Management
#
def find(self, collection, selector={}):
"""Find data in a collection
Arguments:
collection - collection to search
Keyword Arguments:
selector - the query (default returns all items in a collection)"""
results = []
for _id, doc in self.collection_data.data.get(collection, {}).items():
doc.update({'_id': _id})
if selector == {}:
results.append(doc)
for key, value in selector.items():
if key in doc and doc[key] == value:
results.append(doc)
return results
def find_one(self, collection, selector={}):
"""Return one item from a collection
Arguments:
collection - collection to search
Keyword Arguments:
selector - the query (default returns first item found)"""
for _id, doc in self.collection_data.data.get(collection, {}).items():
doc.update({'_id': _id})
if selector == {}:
return doc
for key, value in selector.items():
if key in doc and doc[key] == value:
return doc
return None
def insert(self, collection, doc, callback=None):
"""Insert an item into a collection
Arguments:
collection - the collection to be modified
doc - The document to insert. May not yet have an _id attribute,
in which case Meteor will generate one for you.
Keyword Arguments:
callback - Optional. If present, called with an error object as the first argument and,
if no error, the _id as the second."""
self.call("/" + collection + "/insert", [doc], callback=callback)
def update(self, collection, selector, modifier, callback=None):
"""Insert an item into a collection
Arguments:
collection - the collection to be modified
selector - specifies which documents to modify
modifier - Specifies how to modify the documents
Keyword Arguments:
callback - Optional. If present, called with an error object as the first argument and,
if no error, the number of affected documents as the second."""
self.call("/" + collection + "/update", [selector, modifier], callback=callback)
def remove(self, collection, selector, callback=None):
"""Remove an item from a collection
Arguments:
collection - the collection to be modified
selector - Specifies which documents to remove
Keyword Arguments:
callback - Optional. If present, called with an error object as its argument."""
self.call("/" + collection + "/remove", [selector], callback=callback)
#
# Event Handlers
#
def connected(self):
self.connected = True
self.emit('connected')
def closed(self, code, reason):
self.connected = False
self.emit('closed', code, reason)
def failed(self, data):
self.emit('failed', str(data))
def added(self, collection, id, fields):
self.collection_data.add_data(collection, id, fields)
self.emit('added', collection, id, fields)
def changed(self, collection, id, fields, cleared):
self.collection_data.change_data(collection, id, fields, cleared)
self.emit('changed', collection, id, fields, cleared)
def removed(self, collection, id):
self.collection_data.remove_data(collection, id)
self.emit('removed', collection, id)
#
# Helper functions
#
def _time_from_start(self, start):
now = datetime.datetime.now()
return now - start
def _remove_sub_by_id(self, sub_id):
for name, cur_sub_id in self.subscriptions.items():
if cur_sub_id == sub_id:
del self.subscriptions[name]
def _wait_for_connect(self):
start = datetime.datetime.now()
while not self.connected and self._time_from_start(start).seconds < 5:
time.sleep(0.1)
if not self.connected:
raise MeteorClientException('Could not subscribe because a connection has not been established')