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.
 
 
 
 
 
 

156 lines
5.4 KiB

import os.path
from tornado import gen, web, websocket, escape, options
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer
from tornado.options import parse_command_line
import psycopg2
import momoko
import json
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 BaseHandler(web.RequestHandler):
@property
def db(self):
return self.application.db
class TestHandler(web.RequestHandler):
@property
def db(self):
return self.application.db
@gen.coroutine
def get(self, *args, **kwargs):
sql = "SELECT text,created FROM chat_message"
cursor = yield self.db.execute(sql)
data = cursor.fetchall()
for d in data:
print(d[1])
print(type(d[1]))
print(str(d[1]))
class NotificationHandler(websocket.WebSocketHandler):
@property
def db(self):
return self.application.db
class TutorialHandler(websocket.WebSocketHandler):
@property
def db(self):
return self.application.db
waiters = set()
def open(self, *args, **kwargs):
self.user_id = kwargs.get('user_id',1)
self.waiters.add((self.user_id, self))
# @gen.coroutine
def on_message(self, message):
parsed = escape.json_decode(message)
if 'dummy' in parsed:
return
if parsed['format_type'] == 'add_message_contact':
self.add_message_for_contact(parsed['data']['chat_message'], parsed['data']['sender_id'],
parsed['data']['recipent_id'])
elif parsed['format_type'] == 'add_message_order':
self.add_message_for_order(parsed['data']['chat_message'], parsed['data']['sender_id'],
parsed['data']['recipent_id'], parsed['data']['order_id'])
elif parsed['format_type'] == 'order_message':
self.get_messages_from_order_chat(parsed['order_id'])
else:
self.get_messages_from_order(parsed['user_id'])
def on_close(self):
self.waiters.remove((self.user_id, self))
# insert_sql = "INSERT INTO chat_message (id,text,created,order_id, user_id) VALUES (DEFAULT,'{0}',NOW(),6,4)".format(str(parsed['message']))
# yield self.db.execute(insert_sql)
#
# # cursor = yield self.db.execute("SELECT * FROM chat_message")
# # data = cursor.fetchall()
# for waiter in self.waiters:
# waiter.write_message({'msg': parsed['message']})
@gen.coroutine
def add_message_for_contact(self, message, sender_id, recipent_id):
insert_sql = "INSERT INTO chat_message (id,text,created,order_id, sender_id,recipent_id, private_type) " \
"VALUES (DEFAULT,'{0}',NOW(),NULL,{1},{2},'true')".format(message, sender_id, recipent_id)
yield self.db.execute(insert_sql)
waiters = tuple(w for c, w in self.waiters if c == recipent_id)
for waiter in waiters:
waiter.write_message({'msg': message, 'answer_type': 'add_contact'})
@gen.coroutine
def add_message_for_order(self, message, sender_id,recipent_id, order_id):
insert_sql = "INSERT INTO chat_message (id,text,created,order_id, sender_id,recipent_id, private_type) " \
"VALUES (DEFAULT,'{0}',NOW(),{1},{2},{3},'false')".format(message,order_id, sender_id, recipent_id)
yield self.db.execute(insert_sql)
waiters = tuple(w for c, w in self.waiters if c == recipent_id)
for waiter in waiters:
waiter.write_message({'msg': message, 'answer_type': 'add_order'})
@gen.coroutine
def get_messages_from_order(self, order_id):
sql = "SELECT text FROM chat_message WHERE recipent_id=" + order_id
cursor = yield self.db.execute(sql)
messages = cursor.fetchall()
for msg in messages:
for waiter in self.waiters:
waiter.write_message(json.dumps({'msg': msg[0], 'answer_type': 'order'}))
@gen.coroutine
def get_messages_from_order_chat(self, order_id):
sql = "SELECT text FROM chat_message WHERE order_id=" + order_id
cursor = yield self.db.execute(sql)
messages = cursor.fetchall()
for msg in messages:
for waiter in self.waiters:
waiter.write_message({'msg': msg[0], 'answer_type': 'contact'})
def check_origin(self, origin):
return True
class Application(web.Application):
def __init__(self):
handlers = [
(r"/chat/(?P<user_id>\d+)/", TutorialHandler),
(r"/test", TestHandler),
]
super().__init__(handlers=handlers, **settings)
if __name__ == '__main__':
parse_command_line()
application = Application()
ioloop = IOLoop.instance()
application.db = momoko.Pool(
dsn='dbname=archilance user=postgres password=postgres host=localhost',
size=1,
ioloop=ioloop,
)
future = application.db.connect()
ioloop.add_future(future, lambda f: ioloop.stop())
ioloop.start()
future.result()
http_server = HTTPServer(application)
http_server.listen(8888, 'localhost')
ioloop.start()