-
Notifications
You must be signed in to change notification settings - Fork 0
/
younoty-server.py
276 lines (176 loc) · 7.87 KB
/
younoty-server.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
import tornado.ioloop, tornado.web, tornado.websocket, tornado.httpserver ,tornadoredis
import logging, json, urlparse, redis
import base64 as b64
from time import gmtime, strftime
from tornado.options import parse_command_line, define,options
from tornado import gen
"""
**YouNoty**
Real time notification system for IM and push notification based on tornado and redis
orsidev on https://github.com/orsi-dev
usage: python younoty.py --port=(int)
:TODO = separate sender to receiver classes
"""
REDIS_SERVER = '127.0.0.1'
REDIS_PORT = 6379
REDIS_DB = 1
REDIS_CHANNEL = None
define('port', default=8888, help='run on the given port', type=int)
logging.basicConfig(filename='younoty-error.log', format='%(asctime)s %(message)s', level=logging.DEBUG, filemode="a+") #configurazione file log
#logging = logging.getLogger('base.tornado')
# store clients in dictionary..
clients = dict() #BISOGNA MAPPARE OGNI ATTIVITA SU UN PROCESSO
pool = tornadoredis.ConnectionPool(host=REDIS_SERVER, port=REDIS_PORT, max_connections=20, wait_for_available=True)
"""
SENDER Handler
127.0.0.0.1:8888/msg?message={"client_id":"158","att_id":"13", "msg":"hello there"}
client_id = receiver id
att_id = channel id
127.0.0.0.1:8888/msg?message=eyJjbGllbnRfaWQiOiIxNTgiLCJhdHRfaWQiOiIxMyIsICJtc2ciOiJoZWxsbyB0aGVyZSJ9
if client is offline store notification into redis list
else send publish command with message to subscriber
"""
#metodo di conversione da base64
def base64decoder_(string):
"""
base64 decoder for sender and receiver strings
:type string: object
"""
base_decode = string
decoded = b64.b64decode(base_decode)
return decoded
class NewMessage(tornado.web.RequestHandler): #TODO convert json into base64 with base64decoder_
def check_origin(self, origin):
"""
Check if incoming connection is in supported domain
:param origin (str): Origin/Domain of connection
"""
return True
@tornado.web.asynchronous
@tornado.gen.engine
def get(self):
"""
method get to send the value of querystring argument (:message)
and publish data into redis channel or save into a list
"""
try:
message = self.get_argument("message")
queryParDecoded = base64decoder_(str(message))
body_ = json.loads(str(queryParDecoded))
#print(body_)
body_["created_at"] = strftime("%Y-%m-%d %H:%M:%S", gmtime())
k = list(clients.keys())
namespace_Redis_List = str(body_['att_id'])+':'+str(body_['client_id'])
if body_['client_id'] in k: #if user is logged in
with tornadoredis.Client(connection_pool=pool) as c:
r = redis.StrictRedis(host=REDIS_SERVER, port=REDIS_PORT, db=REDIS_DB) #redis persistance notification
r.lpush(namespace_Redis_List, json.dumps(body_))
foo = yield tornado.gen.Task(c.publish, str(body_['att_id']), queryParDecoded)
self.write('sent: %s' % (message))
self.finish(str(foo))
else: #if user is out of dictionary
body_["ricevuta"] = 0
r = redis.StrictRedis(host=REDIS_SERVER, port=REDIS_PORT, db=REDIS_DB)
r.lpush(namespace_Redis_List, json.dumps(body_))
self.write('sent: %s' % (json.dumps(body_)))
self.finish(str(r))
except Exception,e:
logging.debug(e)
pass
'''
RECEIVER Handler
Json sample for subscription
{"client_id" : "1","att_id" : "13"} = eyJjbGllbnRfaWQiIDogIjEiLCJhdHRfaWQiIDogIjEzIn0=
client_id = receiver id
att_id = channel id
127.0.0.1:{websocketport}/ws-noty?UID=eyJjbGllbnRfaWQiIDogIjEiLCJhdHRfaWQiIDogIjEzIn0=
'''
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def __init__(self, *args, **kwargs):
self.client_id = None
self._redis_client = None
super(WebSocketHandler, self).__init__(*args, **kwargs)
qrs = self.get_argument("UID")
queryParDecoded = base64decoder_(str(qrs))
convQSD = eval(queryParDecoded)
self._connect_to_redis()
#self._chkunread()
self._getUnreadMesg(idatt=convQSD['att_id'], iduser=convQSD['client_id'])
self._chkunread(idatt=convQSD['att_id'], iduser=convQSD['client_id'])
self._listen(att=convQSD['att_id'])
def open(self, *args):
"""
tornado open method get :UID argoument from querystring and open the websocket connection
"""
self.qrs = self.get_argument("UID")
queryParDecoded = base64decoder_(str(self.qrs))
convQSD = eval(queryParDecoded)
self.client_id = convQSD['client_id']
self.stream.set_nodelay(True)
clients[self.client_id] = self
def on_message(self, message):
"""
TODO: DO EVERYTHING ON WEBSOCKET MESSAGE RECEIVED
:param message (str, not-parsed JSON): data from client (web browser)
"""
@gen.coroutine
def _on_update(self, message):
try:
body = json.loads(message.body)
if self.client_id == body['client_id']:
self.write_message(message.body)
except Exception, e:
logging.debug(e)
pass
@tornado.gen.engine
def _listen(self, att):
yield tornado.gen.Task(self._redis_client.subscribe, att)
self._redis_client.listen(self._on_update)
@tornado.web.asynchronous
@tornado.gen.engine
def _getUnreadMesg(self,idatt ,iduser): #ritorna il contenuto delle notifiche da gestire
"""
method for handling messages when the subscriber if offline
:param idatt = channel ; iduser = client_id
"""
r = yield tornado.gen.Task(self._redis_client.lrange, str(idatt)+':'+str(iduser), 0, -1)
i = 0
for name in r:
bodyNoty = json.loads(name)
if "ricevuta" in bodyNoty: # controllo la chiave 'ricevuta' se non esiste vuol dire che e' stata gia letta
if bodyNoty["ricevuta"] == 0:
self.write_message(name)
del bodyNoty["ricevuta"]
r = redis.StrictRedis(host=REDIS_SERVER, port=REDIS_PORT, db=REDIS_DB)
r.lset(str(idatt)+':'+str(iduser), i, json.dumps(bodyNoty))
else:
pass
i += 1
@tornado.web.asynchronous
@tornado.gen.engine
def _chkunread(self,idatt,iduser): #ritorna il numero di notifiche da gestire
yield tornado.gen.Task(self._redis_client.llen, '13:158') #yield tornado.gen.Task(self._redis_client.subscribe, 'REDIS_UPDATES_CHANNEL')
def on_close(self):
if self.client_id in clients:
del clients[self.client_id]
self._redis_client.punsubscribe('*')
self._redis_client.disconnect()
def check_origin(self, origin):
"""
Check if incoming connection is in supported domain
:param origin (str): Origin/Domain of connection
"""
return True
def _connect_to_redis(self):
self._redis_client = tornadoredis.Client(host=REDIS_SERVER, port=REDIS_PORT, selected_db=REDIS_DB)
self._redis_client.connect()
application = tornado.web.Application([
(r'/ws-noty', WebSocketHandler), #RICEVER
(r'/msg', NewMessage), #SENDER
])
if __name__ == "__main__":
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(application)
c = http_server.listen(options.port)
print '*** YouNoty Server Started at ' + str(options.port) + ' port ***'
tornado.ioloop.IOLoop.instance().start()