10 # FOR A PARTICULAR PURPOSE. |
10 # FOR A PARTICULAR PURPOSE. |
11 # |
11 # |
12 |
12 |
13 __docformat__ = 'restructuredtext' |
13 __docformat__ = 'restructuredtext' |
14 |
14 |
15 |
|
16 # import standard library |
|
17 import asyncio |
15 import asyncio |
18 import json |
16 import json |
19 |
17 |
20 # import interfaces |
|
21 |
|
22 # import packages |
|
23 from aiopyramid.websocket.config.gunicorn import WebsocketMapper |
18 from aiopyramid.websocket.config.gunicorn import WebsocketMapper |
24 from aiopyramid.websocket.view import WebsocketConnectionView |
19 from aiopyramid.websocket.view import WebsocketConnectionView |
25 from pyramid.view import view_config |
20 from pyramid.view import view_config |
|
21 |
|
22 from pyams_notify_ws import _ |
26 |
23 |
27 |
24 |
28 users_lock = asyncio.Lock() |
25 users_lock = asyncio.Lock() |
29 users = {} |
26 users = {} |
30 |
27 |
67 except ValueError: |
64 except ValueError: |
68 pass |
65 pass |
69 else: |
66 else: |
70 action = message.get('action') |
67 action = message.get('action') |
71 if action == 'subscribe': |
68 if action == 'subscribe': |
72 if not message.get('principal'): |
69 principal = message.get('principal') |
|
70 translate = self.request.localizer.translate |
|
71 if not principal: |
73 await self.ws.send(json.dumps({'status': 'error', |
72 await self.ws.send(json.dumps({'status': 'error', |
74 'message': "Missing 'principal' argument"})) |
73 'error': translate(_("API Error")), |
|
74 'message': translate(_("Missing principal argument!"))})) |
|
75 return |
|
76 if self.request.unauthenticated_userid != principal.get('id'): |
|
77 await self.ws.send(json.dumps({'status': 'error', |
|
78 'error': translate(_("Authentication Error")), |
|
79 'message': translate(_("Can't subscribe to notifications!"))})) |
75 return |
80 return |
76 async with users_lock: |
81 async with users_lock: |
77 subscription = users.get(self.ws) |
82 subscription = users.get(self.ws) |
78 if subscription is None: |
83 if subscription is None: |
79 subscription = WebsocketSubscription(message.get('principal')) |
84 subscription = WebsocketSubscription(principal) |
80 subscription.update_contexts(message.get('context')) |
85 subscription.update_contexts(message.get('context')) |
81 users[self.ws] = subscription |
86 users[self.ws] = subscription |
82 |
87 |
83 async def on_close(self): |
88 async def on_close(self): |
84 if self.ws in users: |
89 if self.ws in users: |