You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
102 lines
2.8 KiB
102 lines
2.8 KiB
import logging
|
|
import datetime
|
|
import os.path
|
|
from redis import StrictRedis
|
|
from tornado import web, websocket, escape, options, locale, ioloop
|
|
from tornado.httpserver import HTTPServer
|
|
|
|
r = StrictRedis(db=1)
|
|
|
|
logger = logging.getLogger('handlers')
|
|
|
|
settings = {
|
|
'cookie_secret': '__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__',
|
|
'template_path': os.path.join(os.path.dirname(__file__), 'templates'),
|
|
'static_path': os.path.join(os.path.dirname(__file__), 'static'),
|
|
'login_url': '/login',
|
|
'xsrf_cookies': True,
|
|
'debug': True,
|
|
'autoreload': True,
|
|
'server_traceback': True,
|
|
}
|
|
|
|
|
|
class Application(web.Application):
|
|
def __init__(self):
|
|
handlers = [
|
|
(r"/",ChannelHandler),
|
|
(r"/chatsocket/(?P<channel>\w+)/", ChatSocketHandler)
|
|
]
|
|
super().__init__(handlers=handlers, **settings)
|
|
|
|
|
|
class ChannelHandler(web.RequestHandler):
|
|
def get(self, *args, **kwargs):
|
|
title = kwargs.get('channel', 'main')
|
|
self.chnl = kwargs.get('channel', 'main')
|
|
cache = r.lrange('channels:{}'.format(title), 0, -1)
|
|
messages =(escape.json_decode(x) for x in cache) if cache else []
|
|
print(messages)
|
|
|
|
self.render('index2.html',messages=messages)
|
|
|
|
|
|
class ChatSocketHandler(websocket.WebSocketHandler):
|
|
|
|
waiters = set()
|
|
|
|
def open(self, *args, **kwargs):
|
|
self.chnl = kwargs.get('channel', 'main')
|
|
self.waiters.add((self.chnl, self))
|
|
# self.chnl_key = 'channels:{}:users'.format(self.chnl)
|
|
# count = int(r.zcard(self.chnl_key))
|
|
# r.zadd(self.chnl_key, count+1, "mukhtar")
|
|
# users = r.zrange(self.chnl_key,0,-1)
|
|
# self.send_updates()
|
|
|
|
def on_close(self):
|
|
self.waiters.remove(self.chnl, self)
|
|
|
|
def on_message(self, message):
|
|
parsed = escape.json_decode(message)
|
|
if 'dummy' in parsed:
|
|
return
|
|
|
|
chat = {
|
|
'parent': 'inbox',
|
|
'body': parsed['message'],
|
|
'user': 'Mukhtar',
|
|
'time': datetime.datetime.now().strftime('%H:%M:%S %Y-%m-%d')
|
|
}
|
|
self.update_channel_history(chat)
|
|
self.send_updates(parsed);
|
|
|
|
def update_channel_history(self,chat):
|
|
chnl = 'channels:{}'.format(self.chnl)
|
|
r.rpush(chnl, escape.json_encode(chat))
|
|
r.ltrim(chnl, -25, -1)
|
|
|
|
def send_updates(self, chat):
|
|
chnl_waiters = tuple(w for c, w in self.waiters)
|
|
for waiter in chnl_waiters:
|
|
try:
|
|
waiter.write_message(chat)
|
|
except:
|
|
pass
|
|
|
|
def __del__(self):
|
|
r.zrem(self.chnl_key, self.current_user)
|
|
self.log('PUSHED OUT')
|
|
|
|
|
|
def main():
|
|
options.parse_command_line()
|
|
app = Application()
|
|
server = HTTPServer(app)
|
|
server.listen(8888)
|
|
loop = ioloop.IOLoop.current()
|
|
loop.start()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|
|
|