-
Notifications
You must be signed in to change notification settings - Fork 0
/
nserv.py
89 lines (73 loc) · 2.12 KB
/
nserv.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
import json
import os.path
import logging
from ConfigParser import ConfigParser
from gredis.client import AsyncRedis
from tornado.ioloop import IOLoop
from tornado import gen
from tornado.websocket import WebSocketHandler, WebSocketClosedError
from tornado.web import (
Application,
StaticFileHandler,
url
)
config = ConfigParser()
config.read('nserv.ini')
logging.basicConfig(level=config.get('logging', 'level'))
redis = AsyncRedis(
config.get('redis', 'host'),
config.get('redis', 'port'),
)
class NotificationHandler(WebSocketHandler):
"""
Websocket handler for "pushing" notifications to the client
"""
@gen.coroutine
def open(self):
logging.debug('Client connected to NotificationHandler')
pubsub = redis.pubsub()
yield pubsub.subscribe(config.get('redis' , 'channel'))
while True:
message = yield pubsub.get_message(True)
if message['type'] == 'message':
try:
logging.debug('Notification {0} was sent'.format(message['data']))
self.write_message(message['data'])
except WebSocketClosedError:
return
def check_origin(self, origin):
"""
Always pass cross-origin check
"""
return True
def notify(text, level):
# publish notification synchroniously (blocking)
redis.to_blocking_client().publish(
config.get('redis', 'channel'),
json.dumps(dict(
text=text,
level=level
))
)
def main():
# path for html + js
static_path = os.path.join(
os.path.dirname(__file__),
'ui'
)
app = Application(
[
url(r'/notifications', NotificationHandler),
url(r'/(.*)', StaticFileHandler, dict(
path=static_path,
default_filename='index.html'
)),
],
)
app.listen(config.get('web', 'port'))
logging.info('Starting notification server on port {0}'.format(
config.get('web', 'port')
))
IOLoop.current().start()
if __name__ == '__main__':
main()