-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
128 lines (113 loc) · 4.09 KB
/
app.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
import tornado.ioloop
import tornado.web
import tornado.websocket
from elasticsearch import Elasticsearch
from datetime import datetime
from tornado.escape import json_encode
import json
ELASTIC_INDEX = "simple-chat-tornado"
es = Elasticsearch()
ROOMS = {}
dtjson = lambda obj: (
obj.isoformat() if isinstance(obj, datetime) else None
)
class StaticFileHandler(tornado.web.StaticFileHandler):
def set_extra_headers(self, path):
self.set_header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')
class IndexHandler(tornado.web.RequestHandler):
def get(request):
with open('index.html') as f:
request.write(f.read())
class ChatroomsHandler(tornado.web.RequestHandler):
def get(request):
size = es.search(index=ELASTIC_INDEX, doc_type="chatroom")['hits']['total']
res = es.search(index=ELASTIC_INDEX, doc_type="chatroom", body={
"query": {"match_all": {}},
"sort": [
{ "timestamp": { "order":"desc" } }
],
"size": size
})
answer = []
for hit in res['hits']['hits']:
room = {
"_id": hit["_id"],
"title": hit["_source"]['title'],
"timestamp": hit["_source"]['timestamp'],
"updated": hit["_source"]['timestamp']
}
answer.insert(0, room)
request.write(json_encode(answer))
def post(self):
data = json.loads(self.request.body)
doc = {
"title": data['title'],
"timestamp": datetime.now(),
"updated": datetime.now()
}
res = es.index(index=ELASTIC_INDEX, doc_type="chatroom", body=doc)
doc['_id'] = res['_id']
self.write(json.dumps(doc, default=dtjson))
class ChatroomHandler(tornado.web.RequestHandler):
def get(self, room):
roo = es.get(index=ELASTIC_INDEX, doc_type="chatroom", id=room)
msgs = es.search(index=ELASTIC_INDEX, doc_type="message", body={
"query": {
"match": {
"room":room
}
},
"sort": [
{"timestamp": { "order":"desc"} }
],
"size": 50
})
messages = []
for hit in msgs['hits']['hits']:
messages.insert(0, {
"username": hit["_source"]["username"],
"message": hit["_source"]["message"],
"timestamp": hit["_source"]["timestamp"]
})
answer = {
"_id": room,
"title": roo['_source']['title'],
"messages": messages
}
self.write(json_encode(answer))
def post(self, room_id):
data = json.loads(self.request.body)
doc = {
"username": data['username'],
"message": data['message'],
"room": room_id,
"timestamp": datetime.now()
}
es.index(index=ELASTIC_INDEX, doc_type="message", body=doc)
for item in ROOMS[room_id]:
item.write_message(json.dumps(doc, default=dtjson))
def delete(self, room_id):
es.delete(index=ELASTIC_INDEX, doc_type="chatroom", id=room_id)
class RoomSocket(tornado.websocket.WebSocketHandler):
def open(self, room_id):
self.room_id = room_id
if not room_id in ROOMS:
ROOMS[room_id] = []
ROOMS[room_id].append(self)
def on_close(self):
ROOMS[self.room_id].remove(self)
if len(ROOMS[self.room_id]) is 0:
ROOMS.pop(self.room_id, None)
app = tornado.web.Application([
(r'/', IndexHandler),
(r'/chatroom/.*', IndexHandler),
(r'/chatrooms', ChatroomsHandler),
(r'/chatrooms/([a-zA-Z0-9-_]{22})', ChatroomHandler),
(r'/assets/(.*)', StaticFileHandler, {'path': 'bower_components'}),
(r'/styles/(.*)', StaticFileHandler, {'path': 'styles'}),
(r'/scripts/(.*)', StaticFileHandler, {'path': 'scripts'}),
(r'/angular_templates/(.*)', StaticFileHandler, {'path': 'angular_templates'}),
(r'/roomsocket/(.*)', RoomSocket)
])
app.listen(8888)
tornado.ioloop.IOLoop.instance().start()