1
|
1 from twisted.application import service |
|
2 from twisted.python import components, failure |
|
3 from twisted.internet import defer, reactor |
|
4 |
|
5 class IBackendService(components.Interface): |
|
6 """ Interface to a backend service of a pubsub service """ |
|
7 |
2
|
8 def do_publish(self, node, publisher, item): |
|
9 """ Returns a deferred that returns """ |
|
10 |
1
|
11 class BackendException(Exception): |
|
12 def __init__(self, msg = ''): |
|
13 self.msg = msg |
|
14 |
|
15 def __str__(self): |
|
16 return self.msg |
|
17 |
|
18 class NodeNotFound(BackendException): |
|
19 #def __init__(self, msg = 'Node not found'): |
|
20 # BackendException.__init__(self, msg) |
|
21 pass |
|
22 |
|
23 class NotAuthorized(BackendException): |
|
24 pass |
|
25 |
|
26 class MemoryBackendService(service.Service): |
|
27 |
|
28 __implements__ = IBackendService, |
|
29 |
|
30 def __init__(self): |
|
31 self.nodes = {"ralphm/test": 'test'} |
2
|
32 self.subscribers = {"ralphm/test": ["ralphm@ik.nu", "ralphm@doe.ik.nu"] } |
|
33 self.affiliations = {"ralphm/test": { "ralphm@ik.nu": "owner", "ralphm@se-135.se.wtb.tue.nl": 'publisher', 'ralphm@doe.ik.nu': 'publisher' } } |
1
|
34 |
|
35 def do_publish(self, node, publisher, item): |
|
36 try: |
|
37 try: |
|
38 result = self.nodes[node] |
|
39 except KeyError: |
|
40 raise NodeNotFound |
|
41 |
|
42 try: |
|
43 affiliation = self.affiliations[node][publisher] |
|
44 if affiliation not in ['owner', 'publisher']: |
|
45 raise NotAuthorized |
|
46 except KeyError: |
|
47 raise NotAuthorized() |
2
|
48 |
1
|
49 print "publish by %s to %s" % (publisher, node) |
2
|
50 |
|
51 recipients = self.get_subscribers(node) |
|
52 recipients.addCallback(self.magic_filter, node, item) |
|
53 recipients.addCallback(self.pubsub_service.do_notification, node, item) |
|
54 |
1
|
55 return defer.succeed(result) |
|
56 except: |
|
57 f = failure.Failure() |
|
58 return defer.fail(f) |
|
59 |
2
|
60 def magic_filter(self, subscribers, node, item): |
|
61 return subscribers |
|
62 |
1
|
63 def get_subscribers(self, node): |
|
64 d = defer.Deferred() |
|
65 try: |
|
66 result = self.subscribers[node] |
|
67 except: |
|
68 f = failure.Failure() |
|
69 reactor.callLater(0, d.errback, f) |
|
70 else: |
|
71 reactor.callLater(0, d.callback, result) |
|
72 |
|
73 return d |
|
74 |