forked from 0xa71a5/South-by-Southeast-ChatRoom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunMe.py
357 lines (335 loc) · 14.2 KB
/
runMe.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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# -*- coding:utf-8 -*-
import os
import sys
import json
import time
import tornado.httpserver
import tornado.web
import tornado.ioloop
import md5
import thread
from tornado import websocket
import random
import uuid
import sendmail
import sqlite3
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
themeColor=['red','blue','green','black','gray','yellow']
count=0
listenPort=80
#address="www.shadowwalker.cn"
address="127.0.0.1"
sessions={}
log=open("log.txt","a")
def getTime():
return '['+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+'] '
def SessionExsit(uid):
global sessions
print "[+]SessionExsit(),enter"
if(uid in sessions):
if(sessions[uid]['sessioncount']!=0):
print "[-]sessions[{}]['sessioncount']={},return True exsit".format(uid,sessions[uid]['sessioncount'])
return True
else:
print "[-]sessions[{}]['sessioncount']={},return False exsit".format(uid,sessions[uid]['sessioncount'])
return False
else:
print "[-]sessions[{}] doesnt exsit,return False exsit".format(uid)
return False
def CheckUserRegisted(username):
sql=sqlite3.connect("chatroom.db")
cur=sql.execute("select id from user where name='{}'".format(username))
res=cur.fetchall()
if(len(res)!=0):
return True
return False
class Index(tornado.web.RequestHandler):
def get(self):
global listenPort
print "[+]Enter get index"
if(self.get_secure_cookie('status')!='logined'):
print "[-]Not login ,redirect to login.html"
self.redirect('login.html')
return
if(SessionExsit(self.get_secure_cookie('uid'))):
print "[-]Already logined,redirect to login.html"
self.redirect('login.html?error=3')
return
self.render('chatTemplate.html',lp=listenPort,ipAddress=address)
class VerifyHandler(tornado.web.RequestHandler):
def get(self):
action=self.get_argument('action')
print '[verify]',action
sql=sqlite3.connect("chatroom.db")
cur=sql.execute("select name from user where verify='{}'".format(action))
res=cur.fetchall()
if(len(res)!=0):#使能账户
sql.execute("update user set valid=1 where verify='{}'".format(action))
else:
print "[-]Wrong check"
self.render('login.html')
sql.commit()
sql.close()
class LogoutHandler(tornado.web.RequestHandler):
def get(self):
uid=self.get_secure_cookie('uid')
sessions.pop(uid,1)
print "[+]logout remove session uid",uid
print "[+]after remove,new seesions=",sessions
self.redirect('login.html')
class LoginHandler(tornado.web.RequestHandler):
def get(self):
self.render('login.html')
def post(self):
global sessions
username=self.get_argument('txtName')
password=self.get_argument('txtPwd')
sql=sqlite3.connect("chatroom.db")
cur=sql.execute("select id from user where name='{}' and password='{}' and valid=1".format(username,password))
res=cur.fetchall()
if(len(res)!=0):#密码匹配
salt="e53af9306298b57ffd2f63714e2e6313"
self.set_secure_cookie('status','logined')
uid=md5.md5(salt+username).hexdigest()
print "[+]login index,test if exsit session"
if(SessionExsit(uid)):
#不同浏览器尝试登陆同一个账户
self.redirect('login.html?error=4')
print "[-]login post session exsit ,redirect to login.html with get"
return
self.set_secure_cookie('uid',uid)
sessions[uid]={}#创建会话变量
sessions[uid]['username']=username
sessions[uid]['sessioncount']=0
sessions[uid]['chatroom']="mainroom"
self.redirect("/")
else:
cur=sql.execute("select id from user where name='{}' and password='{}' and valid=0".format(username,password))
res=cur.fetchall()
self.set_secure_cookie('status','notLogin')
if(len(res)!=0):
self.redirect('login.html?error=0')
else:
self.redirect('login.html?error=1')
class RegisterHandler(tornado.web.RequestHandler):
def get(self):
self.render('register.html')
def post(self):
username=self.get_argument('txtName')
password=self.get_argument('txtPwd')
sex=self.get_argument('sex')
txtEmail=self.get_argument('txtEmail')
txtColege=self.get_argument('txtColege')
print "[Regist]",username,password,sex,txtEmail,txtColege
if(CheckUserRegisted(username)):
#已经被人注册了
print "[-]username already registed"
self.redirect('/register.html?error=1')
return
sql=sqlite3.connect("chatroom.db")
sql.execute("insert into user (name,password,email,gender,verify,valid) values('{}','{}','{}','{}','{}','{}')".format(username,password,txtEmail,sex,md5.md5(username).hexdigest(),0))
sql.commit()
sql.close()
varifyUrl="http://"+address+"/verify?action="+md5.md5(username).hexdigest()
mailword='{},welcome,thanks for your registering!Please confirm your regist!\n{}'.format(username,varifyUrl)
sendmail.SendMail(txtEmail,"[Chatroom]Confirm regist",mailword)
self.redirect('/login.html')
def combineInfo(message_="[]",toWho_="everyone",id_=0,userName_="Annormous",status_="chat",color_="black"):
strJ="{message:'"+message_+"',toWho:'"+toWho_+"',id:"+str(id_)+",userName:'"+userName_+"',status:'"+status_+"',color:'"+color_+"'}"
return strJ
class SocketHandler(tornado.websocket.WebSocketHandler):
clients =set()
roomContainer=dict()
global themeColor
global sessions
@staticmethod
def repeat_user_name(username):
for u in SocketHandler.clients:
if u.my_user_name==username:
return True
return False
@staticmethod
def send_to_all(message,roomid=""):
if(roomid==""):
for c in SocketHandler.clients:
c.write_message(message)
else:
for c in SocketHandler.roomContainer[roomid]:
c.write_message(message)
@staticmethod
def update_member(ss,roomid=""):
if(roomid==""):
clientInfo="{"
for c in SocketHandler.clients:
clientInfo=clientInfo+c.my_user_name+":"+"{},".format(roomid)
clientInfo=clientInfo+"}"
if(clientInfo[-2]==','):
clientInfo=clientInfo[:-2]+"}"
dataToSend=combineInfo(message_=clientInfo,status_='updateMember')
print "[+]updateMemeber self"
ss.write_message(dataToSend)
else:
clientInfo="{"
for c in SocketHandler.roomContainer[roomid]:
clientInfo=clientInfo+c.my_user_name+":"+"1,"
clientInfo=clientInfo+"}"
if(clientInfo[-2]==','):
clientInfo=clientInfo[:-2]+"}"
dataToSend=combineInfo(message_=clientInfo,status_='updateMember')
print "[+]updateMemeber self"
ss.write_message(dataToSend)
@staticmethod
def update_member_to_all(roomid):
if(roomid==""):
clientInfo="{"
for c in SocketHandler.clients:
clientInfo=clientInfo+c.my_user_name+":"+"1,"
clientInfo=clientInfo+"}"
if(clientInfo[-2]==','):
clientInfo=clientInfo[:-2]+"}"
dataToSend=combineInfo(message_=clientInfo,status_='updateMember')
print "[+]updateMemeber all"
SocketHandler.send_to_all(dataToSend)
else:
clientInfo="{"
for c in SocketHandler.clients:
clientInfo=clientInfo+c.my_user_name+":"+"1,"
clientInfo=clientInfo+"}"
if(clientInfo[-2]==','):
clientInfo=clientInfo[:-2]+"}"
dataToSend=combineInfo(message_=clientInfo,status_='updateMember')
print "[+]updateMemeber all"
SocketHandler.send_to_all(dataToSend,roomid)
def open(self):
self.my_color_name="black"
self.my_chatroom="1"
#self.my_user_name='Anonymous'+str(id(self))[-6:]
uid=self.get_secure_cookie('uid')
if(uid not in sessions):
print "[-]ws open found no session ,redirect to login.html"
dataToSend=combineInfo(id_=id(self),userName_="",status_='redirect',color_=self.my_color_name)
self.write_message(dataToSend)#出现未曾用过的sessionid 重定向到登陆界面
return
self.my_user_name=sessions[uid]['username']
sessions[uid]['sessioncount']+=1
print "[+]",self.my_user_name + ' has joined'
print "[+]sessioncount=",sessions[uid]['sessioncount']
logStr=getTime()+self.my_user_name+' joined\n'
log.write(logStr)
log.flush()
print "[+]New ws connection ,session id:",self.get_secure_cookie('uid')
self.my_color_name=themeColor[int(random.random()*6)]
print 'Color:',self.my_color_name
dataToSend=combineInfo(id_=id(self),userName_=self.my_user_name,status_='varify',color_=self.my_color_name)
self.write_message(dataToSend)
SocketHandler.clients.add(self)
SocketHandler.roomContainer[self.my_chatroom].add(self)
dataToSend=combineInfo(userName_=self.my_user_name,status_='join')
print "[+]join all"
SocketHandler.send_to_all(dataToSend,self.my_chatroom)
SocketHandler.update_member(self,self.my_chatroom)
def on_close(self):
uid=self.get_secure_cookie('uid')
if(uid not in sessions):
print "[-]ws close found no session "
return
SocketHandler.clients.remove(self)
SocketHandler.roomContainer[self.my_chatroom].remove(self)
#sessions.pop(uid,1)#newadd1
dataToSend=combineInfo(userName_=self.my_user_name,status_='remove')
print "[+]remove all"
SocketHandler.send_to_all(dataToSend,self.my_chatroom)
print str(id(self)) + ' has left'
logStr=getTime()+self.my_user_name+' left\n'
def on_message(self, message):
message = json.loads(message)
print 'on_message:',message
if(message['status']=='chat'):
tmp=message['message']
logStr=getTime()+self.my_user_name+': '+tmp+'\n'
log.write(logStr)
log.flush()
tmp=tmp.replace('\n','<br>')
tmp=tmp.replace('<script>','$hack')
tmp=tmp.replace('</script>','$hack')
message['message']=tmp
print "replace ",tmp
dataToSend=combineInfo(userName_=message['userName'],id_=message['id'],message_=message['message'],toWho_="everyone",status_="chat",color_=message['color'])
SocketHandler.send_to_all(dataToSend,self.my_chatroom)
elif(message['status']=='userNameChange'):
tmpSession={'userName':message['userName'],'id':str(id(self)),'color':self.my_color_name}
logStr=getTime()+self.my_user_name+' try to change nick name to '+message['userName']+'\n'
log.write(logStr)
log.flush()
if(SocketHandler.repeat_user_name(message['userName'])):
dataToSend=combineInfo(message_="repeat",id_=id(self),userName_=self.my_user_name,status_='varify',color_=self.my_color_name)
print "[+]repeat self"
self.write_message(dataToSend)
else:
dataToSend=combineInfo(id_=id(self),userName_=message['userName'],status_='varify',color_=self.my_color_name)
self.write_message(dataToSend)
self.my_user_name=message['userName']
print "[+]updateName all"
SocketHandler.update_member_to_all(self.my_chatroom)
elif(message['status']=='updateMember'):
print "query for update member"
SocketHandler.update_member(self,self.my_chatroom)
elif(message['status']=='changeRoom'):
tmp=str(message['message'])
originRoom=self.my_chatroom
self.my_chatroom=tmp
newRoom=tmp
#先删除原来房间的set 在增加新的房间的set
SocketHandler.roomContainer[originRoom].remove(self)
SocketHandler.roomContainer[newRoom].add(self)
#通知原房间所有用户一个user消失了
dataToSend=combineInfo(userName_=self.my_user_name,status_='remove')
print "[+]remove from origin room"
SocketHandler.send_to_all(dataToSend,originRoom)
#通知新的房间所有用户一个user出现了
dataToSend=combineInfo(userName_=self.my_user_name,status_='join')
print "[+]join to new root"
SocketHandler.send_to_all(dataToSend,newRoom)
#更新我的成员列表
SocketHandler.update_member(self,self.my_chatroom)
#发送消息 告知更改mainroomName的html内容
print "[+]Change chatting room to [{}] completed".format(tmp)
#print sessions
def checkTast():
time.sleep(1)
count=0
while True:
count=count+1
print "System beep "+str(count)
SocketHandler.send_to_all("{'stamp':"+str(count)+"}")
time.sleep(10)
if __name__ == '__main__':
global address
app = tornado.web.Application([
('/', Index),
('/soc', SocketHandler),
('/login.html',LoginHandler),
('/login.action',LoginHandler),
('/register.html',RegisterHandler),
('/verify',VerifyHandler),
('/logout.html',LogoutHandler)
],cookie_secret='abcd',
template_path=os.path.join(os.path.dirname(__file__), "template"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
)
print "Running"
if(len(sys.argv)!=2):
address="127.0.0.1"
else:
address="www.shadowwalker.cn"
#初始化聊天室列表
SocketHandler.roomContainer["1"]=set()
SocketHandler.roomContainer["2"]=set()
SocketHandler.roomContainer["3"]=set()
SocketHandler.roomContainer["4"]=set()
#####
thread.start_new_thread(checkTast,())
app.listen(listenPort)
tornado.ioloop.IOLoop.instance().start()