File size: 11,148 Bytes
a22ef44 4a88a69 a22ef44 37830f0 a22ef44 ec3c6bd a22ef44 37830f0 fe35780 f74ed50 1e673da f74ed50 7c756c9 4ff62fe 37830f0 a22ef44 ec3c6bd d7c0046 ec3c6bd 581f9da ec3c6bd d7c0046 ec3c6bd a22ef44 8e64873 fe35780 |
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 |
from flask import *
from flask_socketio import SocketIO, emit, join_room
from flask_sock import Sock
import json, hashlib, sqlite3, time
def check_user(username, passwd, k, update=False, data={}):
_ = False
while not (_):
try:
con = sqlite3.connect("database.db")
cur = con.cursor()
cur.execute("SELECT * FROM userinfo")
if cur.arraysize < 2:
cur.executemany(
"INSERT INTO userinfo(username, passwd, infos, messages) VALUES(?, ?, ?, ?)",
[("database", "azertyuiop",
json.dumps({"creation_date": time.ctime()}), "")])
cur.execute("SELECT * FROM userinfo")
size = cur.arraysize
while size > 0:
db = cur.fetchmany(512)
for info in db:
size -= 1
if info[0] == username:
if passwd == "noPasswdButCookies":
if (json.loads(info[2])['cookies']
== k) and not (update):
cur.close()
con.close()
return (info[2], info[3])
if update:
d = json.loads(info[3])
for key in data:
if d.get(key) == None:
d[key] = data[key]
else:
d[key] = d[key] + data[key]
requete_mise_a_jour = "UPDATE userinfo SET username = ?, passwd = ?, infos = ?, messages = ? WHERE messages = ?"
cur.execute(requete_mise_a_jour,
(info[0], info[1], info[2],
json.dumps(d), info[3]))
con.commit()
cur.close()
con.close()
return ""
if info[1] == passwd:
cur.close()
con.close()
return (info[2], info[3])
else:
cur.close()
con.close()
return "bad password"
cur.executemany(
"INSERT INTO userinfo(username, passwd, infos, messages) VALUES(?, ?, ?, ?)",
[(username, passwd,
json.dumps({
"creation_date": time.ctime(),
"cookies": k
}), json.dumps({
"general;": [],
"generale;": []
}))])
con.commit()
cur.close()
con.close()
return (json.dumps({
"creation_date": time.ctime(),
"cookies": k
}), json.dumps({
"general;": [],
"generale;": []
}))
except Exception as e:
print(e)
def initDB():
con = sqlite3.connect("database.db")
cur = con.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS userinfo(username, passwd, infos, messages)"
)
cur.executemany(
"INSERT INTO userinfo(username, passwd, infos, messages) VALUES(?, ?, ?, ?)",
[("database", "azertyuiop", json.dumps({"creation_date": time.ctime()
}), "")])
con.commit()
cur.close()
con.close()
initDB()
app = Flask(__name__)
sock = Sock(app)
app.config['SOCK_SERVER_OPTIONS'] = {'ping_interval': 25}
app.config['SECRET_KEY'] = 'fhdvidushdujxjddfkidfjojcvndhfxnvkdnvid'
app.config['tab'] = {'usid': {123456789: {'tmp-img': ""}}, "Tempo": 0, "any": b''}
socketio = SocketIO(app)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
cookie_value = request.cookies.get('uid')
if cookie_value:
return redirect("/chat")
return send_file("html_css_js/login.html")
else:
username = request.form.get('username')
passwd = request.form.get('password')
if (username != None) and (passwd != None):
k = hashlib.sha1(passwd.encode() +
str(time.time()).encode()).hexdigest()
h = hashlib.sha256(passwd.encode()).hexdigest()
r = cku = check_user(username, h, k)
if len(cku) == 2:
resp = make_response(redirect("/chat"))
resp.set_cookie('username', username)
resp.set_cookie('uid', k)
return resp
else:
return r
@app.route('/chat')
def chat():
uid = request.cookies.get('uid')
username = request.cookies.get('username')
if (username != None) and (uid != None):
cku = check_user(username, "noPasswdButCookies", uid)
if len(cku) == 2:
rooms = ""
oldMessage = ""
rooms_messages = json.loads(cku[1])
for room in rooms_messages:
rooms += f"<div class='menu-item' onclick='sendnew(\"{room}\");'>{room}</div>\n\r"
else:
return redirect('/')
return open("templates/heremeknown.html", "rb").read().replace(
b"{{ rooms }}", rooms.encode()).replace(
b"{{ username }}", username.encode()).replace(
b"{{ oldMessage }}", oldMessage.encode()).replace(
b"{{ roomID }}", b"Message a envoyer dans general;...")
else:
return redirect('/')
@app.route('/upload-img')
def upload_img():
return send_file("cloud-computing.png")
@sock.route('/pred')
def pred(ws):
data = ws.receive()
print(data)
ws.send(data)
ws.close()
@socketio.on('message')
def handle_message(message):
r = message
username = ""
cookie = ""
roomID = ""
msg = ""
try:
if (len(json.loads(message['data'])['message']) > 0):
app.config['tab']['usid'][json.loads(message['data'])['usid']] = {
'tmp-img': ""
}
join_room(json.loads(message['data'])['roomID'])
k = json.loads(message['data'])
if k['message'].startswith('\n'):
k['message'] = k['message'][1:]
username = k["usid"]
cookie = k["cookies"].split("; ")[1].replace("uid=", "")
if cookie.find("username") != -1:
cookie = k["cookies"].split("; ")[0].replace("uid=", "")
roomID = k["roomID"]
print(username, roomID)
msg = k['message']
if msg == "Connected!":
cku = check_user(username, "noPasswdButCookies", cookie)
messages = json.loads(cku[1]).get(roomID)
for Msg in messages:
usid = Msg.split(": \n")[0]
emit(
'message', {
'data':
json.dumps(
{
'message': Msg.replace(usid + ": \n", ""),
"usid": usid,
"stat": 'restoreHistory'
})
})
r = {'data': json.dumps(k)}
k["cookies"] = ""
check_user(username,
"noPasswdButCookies",
cookie,
update=True,
data={roomID: [msg]})
except Exception as e:
a = 1
try:
if r['data'].find('donotsend: true') == -1:
emit('message', r, room=json.loads(message['data'])['roomID'])
except Exception as e:
a = 1
@app.route('/broad/<cast>', methods=['GET', 'POST'])
def broadcast_(cast):
if hashlib.sha3_512(cast.encode()).hexdigest() == "c10b86e1cd5716b477e6d9f0e2cbb0924121a051f93b82f24cb8bd8f48cd174af1dafab777593782514c05febc88891bb901a3e22ea355dc9879b9721932ca3f":
app.config['tab']['Tempo'] = time.time()
if app.config['tab'].get('any') != None:
if len(app.config['tab']['any']) > 0:
dat = app.config['tab']['any'][:50000000]
app.config['tab']['any'] = app.config['tab']['any'][len(dat):]
return dat
if hashlib.sha3_512(cast.encode()).hexdigest() == "a5655419a578cad25998324e9216f83b09a3ae9da30b4425cbd8527e3e87d2ab7b09a77df783238aede3a7e69ea0b9e71060ec2f7274c1ef7187ddfe6a0fa57c":
if (time.time() - app.config['tab']['Tempo']) < 120:
app.config['tab']['any'] += request.data
if len(request.data) > 25000000:
time.sleep(0.25)
return "Up"
return "To"
return ""
@socketio.on('image')
def recv_images(
image
): # {'data': "{'usid': 1234, 'buf': 'b64MCQU', 'endded': 'bool', 'type': 'png'}"}
if app.config['tab']['usid'][json.loads(
image['data']).get('usid')] != None:
if json.loads(image['data'])['endded'] != 'true':
app.config['tab']['usid'][json.loads(
image['data'])['usid']]['tmp-img'] += json.loads(
image['data'])['buf']
else:
data = json.dumps({
'usid':
json.loads(image['data'])['usid'],
'ext':
json.loads(image['data'])['type'],
'file':
app.config['tab']['usid'][json.loads(
image['data'])['usid']]['tmp-img']
})
app.config['tab']['usid'][json.loads(
image['data'])['usid']]['tmp-img'] = ''
data = json.loads(data)
data["cookies"] = ""
data = json.dumps(data)
emit('message', {'data': data},
room=json.loads(image['data'])['roomID'])
@socketio.on('save')
def handle_message(message):
r = message
username = ""
cookie = ""
roomID = ""
msg = ""
try:
if (len(json.loads(message['data'])['message']) > 0):
k = json.loads(message['data'])
if k['message'].startswith('\n'):
k['message'] = k['message'][1:]
username = k["usid"]
cookie = k["cookies"].split("; ")[1].replace("uid=", "")
if cookie.find("username") != -1:
cookie = k["cookies"].split("; ")[0].replace("uid=", "")
roomID = k["roomID"]
msg = k['message']
r = {'data': json.dumps(k)}
k["cookies"] = ""
check_user(username,
"noPasswdButCookies",
cookie,
update=True,
data={roomID: [msg]})
except Exception as e:
a = 1
if __name__ == '__main__':
socketio.run(app, host="0.0.0.0", port=7860)
#app.run(host="0.0.0.0", port=7860)
#sock.run(host="0.0.0.0", port=7860)
|