-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
446 lines (390 loc) · 15.5 KB
/
main.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
from flask import Flask, request, redirect, render_template, make_response, session, send_from_directory
from flask_socketio import SocketIO
import MySQLdb
import unicodedata
import markdown
import random
import datetime
import time
from passlib.context import CryptContext
import secrets
import re
from config import Config
import pymdownx.emoji
import base64
import requests
app = Flask(__name__)
app.config['SECRET_KEY'] = 'odL1}0a=}E:ybjfY.%rH"Ys5?6;J<^'
socketio = SocketIO(app)
@app.route("/")
def home():
return render_template("index.html")
@app.route("/about")
def about():
return render_template("about.html")
# Minified channel switcher
@app.route("/chanswitch", methods=['GET', 'POST'])
def chanswitch():
if request.method == "GET":
return "Invalid Request."
if request.method == "POST":
channel = request.form['channel'].lower()
if "g-" in request.form['channel']:
return redirect("/group/" + channel.strip('g-'))
else:
return redirect("/chat/" + channel)
def strip_accents(text):
return "".join(char for char in
unicodedata.normalize('NFKD', text)
if unicodedata.category(char) != 'Mn')
# Send messages from previous chat sessions
@socketio.on("getprevmsg")
def send_prev_msg(json, methods=['GET', 'POST']):
if json['group'] == "yes":
msgs = query("SELECT * FROM privatemessages WHERE channel = %s ORDER BY id DESC LIMIT 15;", [json['channel']])
else:
msgs = query("SELECT * FROM messages WHERE channel = %s ORDER BY id DESC LIMIT 15;", [json['channel']])
key = json['key']
for r in msgs[::-1]:
json2 = {}
json2['message'] = markdown.markdown(r[0], extensions=['pymdownx.tilde', 'pymdownx.emoji'], extension_configs = {"pymdownx.emoji": {"emoji_generator":pymdownx.emoji.to_alt}})
usr = query("SELECT * FROM users WHERE nickname = %s", [r[1]])
if usr[0][6] == "yes":
json2['user_name'] = "<i class='fa fa-gavel'></i> " + r[1]
else:
json2['user_name'] = r[1]
json2['channel'] = json['channel']
json2['key'] = key
time = r[3]
json2['timestamp'] = time.strftime('%d/%m/%Y %H:%M:%S')
socketio.emit("recvprevmsg", json2)
# Return chat window
@app.route("/m/chat/<string:channel>", methods=['GET', 'POST'])
def chatembedmobile(channel):
if "g-" in channel:
return redirect("/chat/"+channel.replace("g-", ""))
token = request.cookies.get("pychatToken")
users = query("SELECT * FROM users WHERE token = %s", [token])
if not users:
return redirect("/login")
if request.method == "GET":
key = random.getrandbits(10)
return render_template("pychatmobile.html", channel=channel, username=users[0][0], key=key, group="no")
@app.route("/chat/<string:channel>", methods=['GET', 'POST'])
def chatembed(channel):
if "g-" in channel:
return redirect("/chat/"+channel.replace("g-", ""))
token = request.cookies.get("pychatToken")
users = query("SELECT * FROM users WHERE token = %s", [token])
if not users:
return redirect("/login")
if request.method == "GET":
key = random.getrandbits(10)
return render_template("chat.html", channel=channel, username=users[0][0], key=key, ip=request.environ['REMOTE_ADDR'], group="no")
@app.route("/group/<string:channel>", methods=['GET', 'POST'])
def groupchat(channel):
token = request.cookies.get("pychatToken")
users = query("SELECT * FROM users WHERE token = %s", [token])
if not users:
return redirect("/login")
try:
if users[0][0] in query("SELECT * FROM privatechannels WHERE channame = %s", [channel])[0][2]:
key = random.getrandbits(10)
return render_template("chat.html", channel="g-"+channel, username=users[0][0], key=key,
ip=request.environ['REMOTE_ADDR'], group="yes")
except IndexError:
return "Sorry idiot but you're not allowed to access this chat room."
@app.route("/m/group/<string:channel>", methods=['GET', 'POST'])
def groupchatmobile(channel):
token = request.cookies.get("pychatToken")
users = query("SELECT * FROM users WHERE token = %s", [token])
if not users:
return redirect("/login")
try:
if users[0][0] in query("SELECT * FROM privatechannels WHERE channame = %s", [channel])[0][2]:
key = random.getrandbits(10)
return render_template("pychatmobile.html", channel="g-"+channel, username=users[0][0], key=key,
ip=request.environ['REMOTE_ADDR'], group="yes")
except IndexError:
return "Sorry idiot but you're not allowed to access this chat room."
# Login
@app.route("/login", methods=['GET', 'POST'])
def login():
if request.method == "GET":
return render_template("login.html")
if request.method == "POST":
username = request.form['username']
users = query("SELECT * FROM users WHERE nickname = %s", [username])
if not users:
return "Invalid username."
if users:
if check_encrypted_password(request.form['password'], users[0][1]):
token = users[0][2]
resp = make_response(redirect("/chat/general"))
resp.set_cookie('pychatToken', token)
return resp
else:
return "Your password was incorrect."
# Login
@app.route("/loginmobile", methods=['GET', 'POST'])
def loginmobile():
if request.method == "POST":
return "Invalid Request."
if request.method == "GET":
if request.args['token']:
users = query("SELECT * FROM users WHERE token = %s", [request.args['token']])
if users:
token = users[0][2]
resp = make_response(redirect("/m/chat/general"))
resp.set_cookie('pychatToken', token)
return resp
username = request.args['username']
users = query("SELECT * FROM users WHERE nickname = %s", [username])
if not users:
return "Invalid username."
if users:
if check_encrypted_password(request.args['password'], users[0][1]):
token = users[0][2]
resp = make_response(redirect("/m/chat/general"))
resp.set_cookie('pychatToken', token)
return resp
else:
return "Incorrect Password"
# Login
@app.route("/getcookie", methods=['GET', 'POST'])
def getcookie():
if request.method == "GET":
return "Invalid Request."
if request.method == "POST":
username = request.form['username']
users = query("SELECT * FROM users WHERE nickname = %s", [username])
if not users:
return "Invalid username."
if users:
if check_encrypted_password(request.form['password'], users[0][1]):
token = users[0][2]
return token
else:
return "Incorrect Password"
# Handle chat
@socketio.on("chatsend")
def handle_chat(json, methods=['GET', 'POST']):
now = datetime.datetime.now()
f = '%d/%m/%Y %H:%M:%S'
content = json['message']
channel = json['channel']
if not channel == joined[json['user_name']]:
return
if json['token'] == "":
token = request.cookies.get("pychatToken")
else:
token = json['token']
users = query("SELECT * FROM users WHERE token = %s", [token])
if channel == "rules" or channel == "announcements":
return
if users[0][5] == "yes":
return
json['user_name'] = users[0][0]
if "g-" in channel:
if users[0][0] not in str(query("SELECT * FROM privatechannels WHERE channame = %s", [channel.strip("g-")])):
return
author = json['user_name']
if users[0][6] == "yes":
json['user_name'] = "<i class='fa fa-gavel'></i> " + author
json['timestamp'] = now.strftime(f)
content = content.replace('<','<').replace('>','>')
content = content.strip("#")
content = content.strip("`")
channels = query("SELECT * FROM privatechannels WHERE channame = %s", [channel.strip("g-")])
if content.isspace() or content == "":
return
if json['group'] == "yes":
if channels[0][4] == "yes":
pass
else:
query("INSERT INTO privatemessages (content, author, channel) VALUES (%s,%s,%s);", (content, author, channel))
else:
query("INSERT INTO messages (content, author, channel) VALUES (%s,%s,%s);", (content, author, channel))
content = content.replace("/shrug", " ¯\\\_(ツ)_/¯")
content = strip_accents(content)
json['message'] = markdown.markdown(content, extensions=['pymdownx.tilde', 'pymdownx.emoji'], extension_configs = {"pymdownx.emoji": {"emoji_generator":pymdownx.emoji.to_alt}})
for k, r in sockettokens.items():
if r == channel:
socketio.emit('chatrecieve', json, room=k)
else:
pass
@socketio.on("image")
def imagehandler(json, methods=["GET", "POST"]):
ree = base64.b64decode(json)
f = open('myimage.jpeg', 'wb')
f.write(ree)
f.close()
files = {'file': open("myimage.jpeg", "rb")}
response = requests.post("https://cdn.thanoscar.club/upload/9e29cc9178e37f5e91d9519cb9c44031bc1e8fea",
files=files)
client = request.sid
json2 = {}
json2['url'] = response.url
socketio.emit("imageurl", json2, room=client)
print(response.url)
# Signup
@app.route("/signup", methods=['GET', 'POST'])
def signup():
if request.method == "GET":
return render_template("signup.html")
if request.method == "POST":
if not request.form['password'] and request.form['email'] and request.form['username']:
return "Sorry, but you're missing something. Go back and try again"
username = request.form['username'].replace("<", "")
username = username.replace(">", "")
username = username.lower()
iftehuser = query("SELECT * FROM users WHERE nickname = %s", [username])
if username in iftehuser:
return "Sorry, someone already has that username. Go back and pick another"
encryptedpassword = encrypt_password(request.form['password'])
token = secrets.token_hex(20)
email = request.form['email']
query("INSERT INTO users (nickname, password, token, email, muted) VALUES (%s,%s,%s,%s,\"no\")", (username, encryptedpassword, token, email))
resp = make_response(redirect("/chat/general"))
resp.set_cookie('pychatToken', token)
return resp
# Logout
@app.route("/logout")
def logout():
resp = make_response(redirect("/"))
resp.set_cookie('pychatToken', expires=0)
return resp
### BEGIN BOT
# Join messages
@socketio.on("joinree")
def joinree(json):
print("gotcha")
channel = json['channel']
if request.referrer:
ree3 = request.referrer
else:
ree3 = json['referrer']
if "/group/" in ree3:
re1 = channel.strip("g-")
re1 = "/group/" + re1
if not re1 in ree3:
return
if "/chat/" in ree3:
re1 = "/chat/" + channel
if not re1 in ree3:
return
if json['token'] == "":
user = request.cookies.get("pychatToken")
else:
user = json['token']
users = query("SELECT * FROM users WHERE token = %s", [user])
json2 = {}
print(json['token'])
print(user)
json2['author'] = users[0][0]
print("gotcha2")
if users[0][6] == "yes":
json2['staff'] = "yes"
json2['channel'] = channel
json2['key'] = json['key']
socketio.emit("userconn", json2)
try:
joined[users[0][0]] = channel
print(request.sid)
sockettokens[request.sid] = channel
except KeyError:
pass
for r, v in joined.items():
print("gotcha3")
user2 = query("SELECT * FROM users WHERE nickname = %s", [r])
json3 = {}
print("Sent user" + r)
json3['key'] = json['key']
if user2[0][6] == "yes":
json3['staff'] = "yes"
json3['author'] = r
json3['channel'] = v
socketio.emit("userconn", json3)
# D e s t r u c t i v e m e s s a g e s
@app.route("/destructionon/<string:channel>")
def deson(channel):
channel = query("SELECT * FROM privatechannels WHERE authkey = %s", [channel])
channelt = channel[0][1]
json4 = {}
json4['channel'] = "g-" + channelt
socketio.emit("deson", json4)
@app.route("/destructionoff/<string:channel>")
def desoff(channel):
channel = query("SELECT * FROM privatechannels WHERE authkey = %s", [channel])
channelt = channel[0][1]
json4 = {}
json4['channel'] = "g-" + channelt
socketio.emit("desoff", json4)
# When a user leaves :(
@socketio.on("leave")
def leave(json2):
print("Disconnecc")
user = request.cookies.get("pychatToken")
user = query("SELECT * FROM users WHERE token = %s", [user])
print(user[0][0])
try:
del joined[user[0][0]]
except KeyError:
pass
json = {}
json['author'] = user[0][0]
json['channel'] = json2['channel']
socketio.emit("userdiss", json)
# These seeminly random paths are required for mobile so don't touch m8
@app.route("/m/chat/index.js")
def indexjs():
return send_from_directory("static/js", "index.js")
@app.route("/m/chat/manifest.json")
def manifest():
return send_from_directory("static/js", "manifest.json")
@app.route("/m/chat/service-worker.js")
def srvworker():
return send_from_directory("static/js", "service-worker.js")
@app.route("/m/chat/WebPushManager.js")
def webpushmgr():
return send_from_directory("static/js", "WebPushManager.js")
# Same but for private
@app.route("/m/group/index.js")
def indexjsp():
return send_from_directory("static/js", "index.js")
@app.route("/m/group/manifest.json")
def manifestp():
return send_from_directory("static/js", "manifest.json")
@app.route("/m/group/service-worker.js")
def srvworkerp():
return send_from_directory("static/js", "service-worker.js")
@app.route("/m/group/WebPushManager.js")
def webpushmgrp():
return send_from_directory("static/js", "WebPushManager.js")
# Misc Functions
def query(query, values):
conn.ping(True)
cur = conn.cursor()
cur.execute(query, values)
conn.commit()
return cur.fetchall()
def convertSQLDateTimeToTimestamp(value):
return time.mktime(time.strptime(value, '%Y-%m-%d %H:%M:%S'))
def encrypt_password(password):
return pwd_context.encrypt(password)
def check_encrypted_password(password, hashed):
return pwd_context.verify(password, hashed)
if __name__ == '__main__':
conn = MySQLdb.connect(host=Config.host, # your host, usually localhost
user=Config.user, # your username
passwd=Config.passwd, # your password
db=Config.db)
random.seed()
pwd_context = CryptContext(
schemes=["pbkdf2_sha256"],
default="pbkdf2_sha256",
pbkdf2_sha256__default_rounds=30000
)
joined = {}
sockettokens = {}
socketio.run(app, host="0.0.0.0")