261 lines
9.9 KiB
Python
261 lines
9.9 KiB
Python
import queue
|
|
from flask import Flask, render_template, request, make_response, session
|
|
from flask_socketio import SocketIO, join_room, leave_room #https://pythonprogramminglanguage.com/python-flask-websocket/
|
|
from flask_session import Session
|
|
import sqlite3
|
|
import time
|
|
import atexit
|
|
import sys
|
|
import uuid
|
|
|
|
db_path = 'mate.db'
|
|
conn = sqlite3.connect(db_path, check_same_thread=False)
|
|
c = conn.cursor()
|
|
|
|
app = Flask(__name__)
|
|
key = str(uuid.uuid4().hex)
|
|
app.config['SESSION_TYPE'] = 'filesystem'
|
|
print(key)
|
|
app.config['SECRET_KEY'] = key
|
|
Session(app)
|
|
socketio = SocketIO(app)
|
|
|
|
|
|
|
|
status = True
|
|
users = queue.Queue()
|
|
finished = None
|
|
|
|
def exit_handler():
|
|
conn.close()
|
|
sys.exit("Program sucsesfully exited")
|
|
|
|
#website
|
|
@app.route("/")
|
|
def index():
|
|
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>'
|
|
|
|
@app.route("/list")
|
|
def list():
|
|
c.execute("SELECT * FROM users")
|
|
users = c.fetchall()
|
|
text = ""
|
|
for i in users:
|
|
text = text + f'<p><a href="list/user?user={i[1]}">{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>'
|
|
return '''<!DOCTYPE html>
|
|
<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">
|
|
var socket = io();
|
|
socket.on("update", function(){
|
|
window.location="http://matekasse.server.c3h/list"
|
|
});
|
|
</script>
|
|
<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>
|
|
''' + text + '</html>'
|
|
|
|
@app.route("/list/user", methods=['GET'])
|
|
def user_info():
|
|
username = request.args.get("user")
|
|
c.execute("SELECT * FROM users WHERE username = '%s'" % username)
|
|
user_list = c.fetchall()
|
|
if user_list != []:
|
|
user = user_list[0]
|
|
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>"
|
|
return f"""<!DOCTYPE html>
|
|
<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">
|
|
var socket = io();
|
|
""" + 'socket.on("update", function(){ window.location="http://matekasse.server.c3h/list/user?user=' + username + '"});' + f"""
|
|
</script>
|
|
<p> {user[1]} : {user[2]} <p>
|
|
<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>
|
|
</p>
|
|
<br></br>
|
|
<p>Tags:</p>
|
|
{text}
|
|
<br></br>
|
|
<form action="/removeuser/confirmation" method="get"><input name="id" type="hidden" value="\{user[0]}"><button type="submit">Remove User</button></form>
|
|
</html>
|
|
"""
|
|
else:
|
|
return "User does not exists"
|
|
|
|
@app.route("/adduser")
|
|
def new_user():
|
|
return render_template("adduser.html")
|
|
|
|
@app.route("/removeuser/confirmation", methods=['GET'])
|
|
def confirm_remove_user():
|
|
user_id = request.args.get("id")
|
|
return f'Do your realy want to <a href="/removeuser?id={user_id}">remove the user</a>'
|
|
|
|
@app.route("/removeuser", methods=['GET'])
|
|
def remove_user():
|
|
user_id = request.args.get("id")
|
|
c.execute(f"SELECT * FROM users WHERE id={user_id}")
|
|
user_name = c.fetchall()[0][1]
|
|
c.execute(f"DELETE FROM tags WHERE userid={user_id}")
|
|
c.execute(f"DELETE FROM users WHERE id={user_id}")
|
|
conn.commit()
|
|
return f'<p>Deleted user {user_name}</p><a href="/list">return to the tags and user list</a>'
|
|
|
|
@app.route("/adduser/user", methods=['GET'])
|
|
def adduser():
|
|
user = request.args.get("username")
|
|
c.execute(f"SELECT * FROM users WHERE username='{str(user)}'")
|
|
if c.fetchall() == []:
|
|
c.execute("INSERT or IGNORE INTO users (username, balance) VALUES ('%s', 0)" % user)
|
|
conn.commit()
|
|
return 'Added user <a href="/list">user and tag list</a> <p>The creator of this website accepts no liability for any linguistic or technical errors!</p>'
|
|
else:
|
|
return 'User already exists <a href="/list">user and tag list</a> <p>The creator of this website accepts no liability for any linguistic or technical errors!</p>'
|
|
|
|
|
|
@app.route("/change", methods=['GET'])
|
|
def change():
|
|
user_id = int(request.args.get("id"))
|
|
try:
|
|
change = int(request.args.get("change"))
|
|
except ValueError:
|
|
return '<p>Please enter a number!</p><a href="/list">tags and user list</a>'
|
|
c.execute(f"UPDATE users SET balance = balance + {change} WHERE id={user_id}")
|
|
conn.commit()
|
|
if change < 0:
|
|
text = "removed from"
|
|
change_text = change * -1
|
|
elif change > 0:
|
|
text = "added to"
|
|
change_text = change
|
|
elif change == 0:
|
|
return "<p>Nothing was done!</p>"
|
|
c.execute(f"SELECT * FROM users WHERE id={user_id}")
|
|
user = c.fetchall()[0][1]
|
|
return f'<p>{change_text} was {text} {user}</p> <a href="/list">back to the list</a>'
|
|
|
|
@app.route("/addtag", methods=['GET'])
|
|
def get_addtag_request():
|
|
global users
|
|
try:
|
|
user_id = int(request.args.get("id"))
|
|
except: #except im Normalen Code!
|
|
return "Wrong user id!"
|
|
session_id = uuid.uuid4()
|
|
session[id] = session_id
|
|
users.put([user_id, "add", session_id])
|
|
return render_template("addtag.html", user=user_id)
|
|
|
|
@socketio.on('addtag')
|
|
def request_addtag(data):
|
|
global finished
|
|
join_room(session[id])
|
|
if len(users.queue) > 0:
|
|
user = users.queue[len(users.queue) - 1]
|
|
if user == [data["data"], "add", session[id]]:
|
|
socketio.emit("wait", "wait", to=session[id])
|
|
i = 0
|
|
while finished != [data["data"], "add", session[id]]:
|
|
time.sleep(1)
|
|
i += 1
|
|
if i > 20:
|
|
socketio.emit("error", "timeout", to=session[id])
|
|
notimportant = users.get()
|
|
break
|
|
else:
|
|
finished = None
|
|
c.execute(f"SELECT * FROM users WHERE id ={user[0]}")
|
|
username = c.fetchall()[0][1]
|
|
socketio.emit("finished", f"Added tag to {username}", to=session[id]) #print tagid
|
|
else:
|
|
socketio.emit("busy", "busy", to=session[id])
|
|
else:
|
|
socketio.emit("error", "error", to=session[id])
|
|
leave_room(session[id])
|
|
|
|
@app.route("/removetag", methods=['GET'])
|
|
def get_removetag_request():
|
|
global users
|
|
try:
|
|
user_id = int(request.args.get("id"))
|
|
except: #except im Normalen Code!
|
|
return "Wrong user id!"
|
|
session_id = uuid.uuid4()
|
|
session[id] = session_id
|
|
users.put([user_id, "remove", session_id])
|
|
return render_template("removetag.html", user=user_id)
|
|
|
|
@socketio.on('removetag')
|
|
def request_removetag(data):
|
|
global finished
|
|
join_room(session[id])
|
|
if len(users.queue) > 0:
|
|
queue_item = users.queue[len(users.queue) - 1]
|
|
user = queue_item[0]
|
|
if queue_item == [data["data"], "remove", session[id]]:
|
|
socketio.emit("wait", "wait", to=session[id])
|
|
i = 0
|
|
print(session[id])
|
|
while finished != [data["data"], "remove", session[id]]:
|
|
time.sleep(1)
|
|
i += 1
|
|
if i > 20:
|
|
socketio.emit("error", "timeout", to=session[id])
|
|
notimportant = users.get()
|
|
break
|
|
else:
|
|
finished = None
|
|
c.execute(f"SELECT * FROM users WHERE id ={user}")
|
|
username = c.fetchall()[0][1]
|
|
socketio.emit("finished", f"removed tag from {username}")
|
|
else:
|
|
socketio.emit("busy", "busy", to=session[id])
|
|
else:
|
|
socketio.emit("error", "error", to=session[id])
|
|
leave_room(session[id])
|
|
|
|
#api
|
|
@app.route("/api/tag_id", methods=['GET'])
|
|
def get_id():
|
|
global finished
|
|
tag_id = int(request.args.get("id"))
|
|
c.execute(f"SELECT * FROM tags WHERE tagid ={tag_id}")
|
|
|
|
tag_list = c.fetchall()
|
|
if users.qsize() > 0:
|
|
queue_item = users.get()
|
|
print(queue_item)
|
|
user = queue_item[0]
|
|
print(f"user: {user}")
|
|
state = queue_item[1]
|
|
print(state)
|
|
if state == "add":
|
|
c.execute(f"INSERT OR IGNORE INTO tags (tagid, userid) VALUES ({tag_id}, {user})")
|
|
elif state == "remove":
|
|
c.execute(f"DELETE FROM tags WHERE (tagid = {tag_id} AND userid = {user}) ")
|
|
conn.commit()
|
|
finished = queue_item
|
|
socketio.emit("update", "update")
|
|
return make_response("True")
|
|
|
|
elif tag_list != []:
|
|
tag = tag_list[0]
|
|
if users.qsize() == 0:
|
|
c.execute(f"UPDATE users SET balance = balance - 1 WHERE id={tag[1]}")
|
|
conn.commit()
|
|
socketio.emit("update", "update")
|
|
return make_response("True")
|
|
socketio.emit("update", "update")
|
|
return make_response("False")
|
|
|
|
def main():
|
|
atexit.register(exit_handler)
|
|
socketio.run(app, host='0.0.0.0', port=5000)
|