matekasse/main.py

369 lines
15 KiB
Python
Raw Normal View History

2023-07-05 20:23:42 +00:00
from crypt import methods
2023-06-23 18:36:26 +00:00
from fileinput import filename
2023-06-23 18:23:41 +00:00
import queue, sqlite3, time, atexit, sys, uuid, json, urllib.parse, logging, datetime, os
2023-06-23 18:36:26 +00:00
from flask import Flask, render_template, request, make_response, session, url_for
2023-06-16 17:29:49 +00:00
from flask_socketio import SocketIO, join_room, leave_room
2023-06-09 20:44:36 +00:00
from flask_session import Session
2023-06-21 20:30:35 +00:00
from markupsafe import escape
2023-05-31 18:33:45 +00:00
2023-06-23 20:39:02 +00:00
#db_config test
2023-05-31 18:33:45 +00:00
db_path = 'mate.db'
2023-05-31 19:23:40 +00:00
conn = sqlite3.connect(db_path, check_same_thread=False)
2023-05-31 18:33:45 +00:00
c = conn.cursor()
2023-06-22 10:29:27 +00:00
#flask_config
2023-05-31 18:33:45 +00:00
app = Flask(__name__)
2023-06-09 20:27:45 +00:00
key = str(uuid.uuid4().hex)
2023-06-09 20:57:59 +00:00
app.config['SESSION_TYPE'] = 'filesystem'
2023-06-09 20:54:01 +00:00
app.config['SECRET_KEY'] = key
2023-06-09 20:39:09 +00:00
Session(app)
2023-06-09 19:47:15 +00:00
socketio = SocketIO(app)
2023-06-22 10:29:27 +00:00
#logging_config
2023-06-23 17:49:49 +00:00
now = datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')
logging.basicConfig(filename=f"logs/matekasse-{now}.log",filemode='w', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ,encoding='utf-8', level=logging.INFO)
2023-06-22 10:29:27 +00:00
db_log = logging.getLogger('db')
website_log = logging.getLogger('website')
2023-06-09 19:47:15 +00:00
2023-06-22 10:29:27 +00:00
#var
2023-05-31 18:33:45 +00:00
status = True
users = queue.Queue()
finished = None
2023-06-14 19:37:51 +00:00
message = None
2023-05-31 18:33:45 +00:00
def exit_handler():
2023-06-22 10:46:15 +00:00
conn.commit()
2023-05-31 18:33:45 +00:00
conn.close()
2023-06-22 10:46:15 +00:00
website_log.info("Website exited")
2023-05-31 18:33:45 +00:00
sys.exit("Program sucsesfully exited")
2023-06-23 20:33:55 +00:00
#website
2023-06-23 18:23:41 +00:00
@app.route('/favicon.ico')
def favicon():
2023-06-23 22:05:02 +00:00
return url_for('static', filename='Logo_CCC.svg.png')
@app.route('/socket.io.js')
def socketiojs():
return url_for('static', filename='socket.io.js')
2023-06-23 18:23:41 +00:00
2023-05-31 18:33:45 +00:00
@app.route("/")
def index():
2023-06-23 20:58:25 +00:00
return """
<a href="/list">user and tag list</a>
<p>The creator of this website accepts no liability for any linguistic or technical errors!</p>
<br style="line-height: 500%;"></br>
2023-07-05 17:15:17 +00:00
<a href="/documentation">Doumentation</a><script src="/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous">
2023-06-23 20:58:25 +00:00
</script>
<script type="text/javascript" charset="utf-8">
window.location="http://matekasse.server.c3h/list"
</script>
"""
2023-05-31 18:33:45 +00:00
@app.route("/list")
def list():
c.execute("SELECT * FROM users")
users = c.fetchall()
text = ""
for i in users:
2023-06-23 19:22:10 +00:00
text = text + f'<p><a href="list/user?id={i[0]}">{escape(i[1])}</a>: {i[2]} <form action="/change" method="get"><input name="id" type="hidden" value="{i[0]}"> Change balance: <input name="change"><input type="submit"></form></p> <br style="line-height: 50%;"></br>'
2023-06-23 21:24:14 +00:00
return '''<!DOCTYPE html>
<html lang="en">
2023-06-23 18:23:41 +00:00
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
2023-06-14 18:55:54 +00:00
<script type="text/javascript" charset="utf-8">
var socket = io();
socket.on("update", function(){
window.location="http://matekasse.server.c3h/list"
});
</script>
2023-06-23 21:24:14 +00:00
<p><a href="/list">user and tag list</a> | <a href="/documentation">Documentation</a></p>
2023-06-23 20:58:25 +00:00
<p>1 Credit = 1,50 Euro</p>
2023-06-14 18:55:54 +00:00
<form action="/list/user" method="get"> Search for User: <input name="user"><input type="submit"></form>
<form action="/adduser" method="get"><button type="submit">Add User</button></form>
<br></br>
2023-06-23 21:24:14 +00:00
''' + text + '<a href="/documentation">Doumentation</a></html>'
2023-05-31 18:33:45 +00:00
@app.route("/list/user", methods=['GET'])
2023-05-31 20:29:47 +00:00
def user_info():
2023-06-23 19:26:01 +00:00
id = request.args.get("id")
2023-07-05 20:04:12 +00:00
c.execute(f"SELECT * FROM users WHERE id=?", [id])
2023-06-14 16:54:58 +00:00
user_list = c.fetchall()
if user_list != []:
user = user_list[0]
2023-06-09 22:09:52 +00:00
c.execute(f"SELECT * FROM tags WHERE userid={user[0]}")
tags = c.fetchall()
text = ""
for tag in tags:
text = text + f"<p>{tag[0]}</p>"
2023-06-14 19:13:03 +00:00
return f"""<!DOCTYPE html>
2023-06-14 19:06:50 +00:00
<html lang="en">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf-8">
2023-06-14 19:20:44 +00:00
var socket = io();
2023-06-23 19:22:10 +00:00
""" + 'socket.on("update", function(){ window.location="http://matekasse.server.c3h/list/user?id=' + id + '"});' + f"""
2023-06-14 19:20:44 +00:00
</script>
2023-06-23 21:24:14 +00:00
<p><a href="/list">user and tag list</a> | <a href="/documentation">Documentation</a></p>
2023-06-21 20:30:35 +00:00
<p> {escape(user[1])} : {user[2]} <p>
2023-06-14 19:13:03 +00:00
<form action="/addtag" method="get"><input name="id" type="hidden" value="{user[0]}"><button type="submit">Add Tag</button></form>
<form action="/removetag" method="get"><input name="id" type="hidden" value="{user[0]}"><button type="submit">Remove Tag</button></form>
</p><form action="/change" method="get"><input name="id" type="hidden" value="{user[0]}"> Change balance: <input name="change"><input type="submit"></form>
2023-06-14 19:06:50 +00:00
</p>
<br></br>
<p>Tags:</p>
2023-06-14 19:13:03 +00:00
{text}
2023-06-14 19:06:50 +00:00
<br></br>
2023-06-14 19:26:03 +00:00
<form action="/removeuser/confirmation" method="get"><input name="id" type="hidden" value="{user[0]}"><button type="submit">Remove User</button></form>
2023-06-14 19:06:50 +00:00
</html>
"""
2023-05-31 18:33:45 +00:00
else:
2023-06-21 19:33:23 +00:00
return "Error: 043"
2023-05-31 18:33:45 +00:00
@app.route("/adduser")
def new_user():
return render_template("adduser.html")
2023-06-14 17:49:28 +00:00
@app.route("/removeuser/confirmation", methods=['GET'])
2023-06-14 17:48:21 +00:00
def confirm_remove_user():
user_id = request.args.get("id")
2023-06-23 21:24:14 +00:00
return f'<p><a href="/list">user and tag list</a> | <a href="/documentation">Documentation</a></p> <p>Do your realy want to <a href="/removeuser?id={user_id}">remove the user</a></p>'
2023-06-14 17:48:21 +00:00
2023-06-14 16:28:45 +00:00
@app.route("/removeuser", methods=['GET'])
2023-06-09 22:09:52 +00:00
def remove_user():
2023-06-14 16:56:26 +00:00
user_id = request.args.get("id")
2023-07-05 20:05:50 +00:00
c.execute(f"SELECT * FROM users WHERE id=?", [user_id])
2023-06-21 20:33:47 +00:00
users = c.fetchall()
if users != []:
user_name = users[0][1]
2023-07-14 18:58:44 +00:00
c.execute(f"DELETE FROM tags WHERE userid=?", [user_id])
db_log.info(f"Deleted all tags from user ?", [user_id])
c.execute(f"DELETE FROM users WHERE id=?", [user_id])
db_log.info(f"Deleted user ?", [user_id])
2023-06-21 20:33:47 +00:00
conn.commit()
socketio.emit("update", "update")
2023-06-23 21:24:14 +00:00
return f'<p><p><a href="/list">user and tag list</a> | <a href="/documentation">Documentation</a></p> <p>Deleted user {escape(user_name)}</p><a href="/list">return to the tags and user list</a></p>'
2023-06-21 20:33:47 +00:00
else:
return "Error: 043"
2023-05-31 18:33:45 +00:00
@app.route("/adduser/user", methods=['GET'])
def adduser():
2023-06-23 17:15:12 +00:00
username = request.args.get("username")
c.execute("SELECT * FROM users WHERE username=?", [username])
2023-05-31 18:33:45 +00:00
if c.fetchall() == []:
2023-06-23 17:15:12 +00:00
c.execute("INSERT or IGNORE INTO users (username, balance) VALUES (?, 0)", [username])
2023-05-31 18:33:45 +00:00
conn.commit()
2023-06-16 17:29:49 +00:00
socketio.emit("update", "update")
2023-06-23 17:17:29 +00:00
c.execute(f"SELECT * FROM users WHERE username=?", [username])
2023-06-23 17:15:12 +00:00
user = c.fetchall()[0]
2023-06-23 17:33:26 +00:00
db_log.info(f"Added user id: {user[0]} name: {user[2]}")
return """<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf-8">
window.location="http://matekasse.server.c3h/list";
</script>
</html>
"""
2023-05-31 18:33:45 +00:00
else:
2023-06-23 21:24:14 +00:00
return '<p><a href="/list">user and tag list</a> | <a href="/documentation">Documentation</a></p><p>Error: 170</p> '
2023-05-31 18:33:45 +00:00
@app.route("/change", methods=['GET'])
def change():
try:
2023-07-05 21:15:44 +00:00
user_id = request.args.get("id")
2023-05-31 18:33:45 +00:00
change = int(request.args.get("change"))
2023-06-23 20:35:58 +00:00
except:
2023-06-21 19:33:23 +00:00
return '<p>Error: 095</p><a href="/list">tags and user list</a>'
2023-07-05 21:15:44 +00:00
c.execute(f"SELECT * FROM users WHERE id=?", [user_id])
2023-06-22 10:29:27 +00:00
users = c.fetchall()
if users != []:
balance_old = users[0][2]
c.execute(f"UPDATE users SET balance = balance + {change} WHERE id={user_id}")
2023-06-23 17:08:14 +00:00
conn.commit()
2023-06-22 10:29:27 +00:00
c.execute(f"SELECT * FROM users WHERE id={user_id}")
user = c.fetchall()[0]
db_log.info(f"Changed the balance from user {user[0]} from {balance_old} to {user[2]}")
socketio.emit("update", "update")
return """<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
<script type="text/javascript" charset="utf-8">
window.location="http://matekasse.server.c3h/list";
</script>
</html>
"""
else:
2023-06-23 21:24:14 +00:00
return '<p><a href="/list">user and tag list</a> | <a href="/documentation">Documentation</a></p> <p>Error: 043</p>'
2023-05-31 18:33:45 +00:00
@app.route("/addtag", methods=['GET'])
def get_addtag_request():
global users
try:
user_id = int(request.args.get("id"))
except: #except im Normalen Code!
2023-06-21 19:33:23 +00:00
return "Error: 095"
2023-06-09 19:22:25 +00:00
session_id = uuid.uuid4()
2023-06-09 20:23:01 +00:00
session[id] = session_id
2023-06-09 19:22:25 +00:00
users.put([user_id, "add", session_id])
2023-05-31 18:33:45 +00:00
return render_template("addtag.html", user=user_id)
@socketio.on('addtag')
def request_addtag(data):
global finished
2023-06-14 19:35:11 +00:00
global message
2023-06-09 21:16:16 +00:00
join_room(session[id])
2023-05-31 18:33:45 +00:00
if len(users.queue) > 0:
user = users.queue[len(users.queue) - 1]
2023-06-09 19:22:25 +00:00
if user == [data["data"], "add", session[id]]:
2023-06-09 21:16:16 +00:00
socketio.emit("wait", "wait", to=session[id])
2023-05-31 18:33:45 +00:00
i = 0
2023-06-09 19:22:25 +00:00
while finished != [data["data"], "add", session[id]]:
2023-05-31 18:33:45 +00:00
time.sleep(1)
i += 1
if i > 20:
2023-06-21 19:33:23 +00:00
socketio.emit("error", "352", to=session[id])
2023-06-09 17:11:45 +00:00
notimportant = users.get()
2023-05-31 20:29:47 +00:00
break
else:
finished = None
2023-06-21 19:33:23 +00:00
socketio.emit("finished", f"{message}", to=session[id])
2023-05-31 18:33:45 +00:00
else:
2023-06-09 21:16:16 +00:00
socketio.emit("busy", "busy", to=session[id])
2023-05-31 18:33:45 +00:00
else:
2023-06-21 19:33:23 +00:00
socketio.emit("error", "418", to=session[id])
2023-06-09 21:19:11 +00:00
leave_room(session[id])
2023-05-31 18:33:45 +00:00
2023-06-09 19:22:25 +00:00
@app.route("/removetag", methods=['GET'])
2023-06-09 19:26:17 +00:00
def get_removetag_request():
2023-06-09 19:22:25 +00:00
global users
try:
user_id = int(request.args.get("id"))
except: #except im Normalen Code!
return "Wrong user id!"
session_id = uuid.uuid4()
2023-06-09 20:59:30 +00:00
session[id] = session_id
2023-06-09 21:01:55 +00:00
users.put([user_id, "remove", session_id])
2023-06-09 19:22:25 +00:00
return render_template("removetag.html", user=user_id)
@socketio.on('removetag')
2023-06-09 19:26:17 +00:00
def request_removetag(data):
2023-06-09 19:22:25 +00:00
global finished
2023-06-14 19:35:11 +00:00
global message
2023-06-09 21:19:11 +00:00
join_room(session[id])
2023-06-09 19:22:25 +00:00
if len(users.queue) > 0:
2023-06-09 22:09:52 +00:00
queue_item = users.queue[len(users.queue) - 1]
2023-06-14 18:32:50 +00:00
user = queue_item[0]
2023-06-09 22:09:52 +00:00
if queue_item == [data["data"], "remove", session[id]]:
2023-06-09 21:19:11 +00:00
socketio.emit("wait", "wait", to=session[id])
2023-06-09 19:22:25 +00:00
i = 0
while finished != [data["data"], "remove", session[id]]:
time.sleep(1)
i += 1
if i > 20:
2023-06-21 19:33:23 +00:00
socketio.emit("error", "352", to=session[id])
2023-06-09 19:22:25 +00:00
notimportant = users.get()
break
else:
finished = None
2023-06-21 19:33:23 +00:00
socketio.emit("finished", f"{message}", to=session[id])
2023-06-09 19:22:25 +00:00
else:
2023-06-09 21:19:11 +00:00
socketio.emit("busy", "busy", to=session[id])
2023-06-09 19:22:25 +00:00
else:
2023-06-21 19:33:23 +00:00
socketio.emit("error", "418", to=session[id])
2023-06-09 21:19:11 +00:00
leave_room(session[id])
2023-06-09 19:22:25 +00:00
2023-05-31 18:33:45 +00:00
#api
2023-07-05 20:23:42 +00:00
@app.route("/api/change", methods=['GET'])
def api_change():
userid = request.args.get("id")
c.execute("SELECT * FROM users WHERE id=?", [userid])
user_list = c.fetchall()
if user_list != []:
user = user_list[0]
try:
change = int(request.args.get("change"))
except:
return make_response(json.dumps({"mode":"error","error":"095"}))
if change == None:
change = 1
c.execute(f"UPDATE users SET balance = balance + {change} WHERE id={user[0]}")
2023-07-05 20:41:40 +00:00
c.execute(f"SELECT * FROM users WHERE id = {userid}")
user_new = c.fetchall()[0]
db_log.info(f"Changed the balance from user {user[0]} from {user[2]} to {user_new[2]}")
2023-07-05 20:23:42 +00:00
socketio.emit("update", "update")
return make_response(json.dumps({"mode":"balance", "username":user[1], "balance":user[2]}))
2023-07-05 21:11:17 +00:00
else:
return make_response(json.dumps({"mode":"error","error":"043"}))
2023-07-05 20:23:42 +00:00
2023-05-31 18:33:45 +00:00
@app.route("/api/tag_id", methods=['GET'])
def get_id():
global finished
2023-06-14 19:39:13 +00:00
global message
2023-06-23 22:09:15 +00:00
tag_id = request.args.get("id")
2023-07-05 21:13:35 +00:00
c.execute(f"SELECT * FROM tags WHERE tagid=?", [tag_id])
2023-05-31 18:33:45 +00:00
2023-06-09 21:24:44 +00:00
tag_list = c.fetchall()
if users.qsize() > 0:
2023-06-09 19:22:25 +00:00
queue_item = users.get()
user = queue_item[0]
state = queue_item[1]
2023-07-15 12:42:40 +00:00
c.execute(f"SELECT * FROM users WHERE id=?", [user])
2023-06-21 19:33:23 +00:00
username = c.fetchall()[0][1]
2023-06-09 19:22:25 +00:00
if state == "add":
2023-06-14 19:35:11 +00:00
c.execute(f"SELECT * FROM tags WHERE tagid={tag_id}")
if c.fetchall() != []:
2023-06-21 19:33:23 +00:00
message = "Error: 170"
2023-06-21 17:39:13 +00:00
finished = queue_item
2023-07-05 19:17:36 +00:00
return make_response(json.dumps({"mode":"error","error":"170"}))
2023-06-14 19:35:11 +00:00
else:
2023-07-15 12:42:40 +00:00
c.execute(f"INSERT OR IGNORE INTO tags (tagid, userid) VALUES ({tag_id}, ?)", [user])
2023-06-21 19:33:23 +00:00
message = f"Added {tag_id} to {username}"
2023-06-22 10:29:27 +00:00
db_log.info(message)
2023-06-21 17:39:13 +00:00
finished = queue_item
2023-06-22 10:29:27 +00:00
conn.commit()
2023-07-15 12:42:40 +00:00
return make_response(json.dumps({"mode":"message","username":"%s".format(username),"message":"A tag was added"}))
2023-06-09 19:22:25 +00:00
elif state == "remove":
2023-07-15 12:42:40 +00:00
c.execute(f"SELECT * FROM tags WHERE (tagid = {tag_id} AND userid = ?)", [user])
2023-06-14 19:43:41 +00:00
tags = c.fetchall()
if tags != []:
2023-07-15 12:42:40 +00:00
c.execute(f"DELETE FROM tags WHERE (tagid = {tag_id} AND userid = ?)", [user])
2023-06-21 19:33:23 +00:00
message = f"Removed {tag_id} from {username}"
2023-06-22 10:29:27 +00:00
db_log.info(message)
2023-06-21 17:39:13 +00:00
finished = queue_item
2023-06-22 10:29:27 +00:00
conn.commit()
2023-07-15 12:42:40 +00:00
return make_response(json.dumps({"mode":"message","username":"%s".format(username),"message":"A tag was removed"}))
2023-06-14 19:35:11 +00:00
else:
2023-06-22 10:29:27 +00:00
message = "054"
2023-06-21 17:39:13 +00:00
finished = queue_item
2023-07-05 19:17:36 +00:00
return make_response(json.dumps({"mode":"error","error":"054"}))
2023-06-09 19:22:25 +00:00
finished = queue_item
2023-06-14 18:58:22 +00:00
socketio.emit("update", "update")
2023-07-05 19:17:36 +00:00
return make_response(json.dumps({"mode":"error","error":"418"}))
2023-06-09 21:24:44 +00:00
elif tag_list != []:
tag = tag_list[0]
2023-06-22 10:29:27 +00:00
c.execute(f"SELECT * FROM users WHERE id={tag[1]}")
2023-07-05 17:10:01 +00:00
user_list = c.fetchall()
if user_list != []:
balance_old = user_list[0][2]
2023-06-22 10:29:27 +00:00
if users.qsize() == 0:
c.execute(f"UPDATE users SET balance = balance - 1 WHERE id={tag[1]}")
conn.commit()
c.execute(f"SELECT * FROM users WHERE id={tag[1]}")
user = c.fetchall()[0]
db_log.info(f"Changed the balance from user {user[0]} from {balance_old} to {user[2]}")
socketio.emit("update", "update")
2023-07-05 19:17:36 +00:00
return make_response(json.dumps({"mode":"balance", "username":user[1], "balance":user[2]}))
2023-06-22 10:29:27 +00:00
else:
2023-07-05 19:17:36 +00:00
return make_response(json.dumps({"mode":"error", "error":"043"}))
2023-06-14 18:58:22 +00:00
socketio.emit("update", "update")
2023-07-05 19:17:36 +00:00
return make_response(json.dumps({"mode":"error","error":"054"}))
2023-05-31 18:33:45 +00:00
2023-06-21 18:01:16 +00:00
#Documentation
2023-06-21 18:12:06 +00:00
@app.route("/documentation")
2023-06-21 18:01:16 +00:00
def documentation():
return render_template("documentation.html")
2023-06-21 18:12:06 +00:00
2023-05-31 18:33:45 +00:00
def main():
atexit.register(exit_handler)
2023-06-22 10:46:15 +00:00
website_log.info("Website is starting")
2023-06-23 18:32:40 +00:00
socketio.run(app, host='0.0.0.0', port=5000, cors_allowed_origins="*")