This commit is contained in:
2000-Trek 2023-11-25 00:05:33 +01:00
parent dcd7a71d83
commit 2d6d14ebba
3 changed files with 42 additions and 31 deletions

View file

@ -4,17 +4,25 @@ from flask_socketio import SocketIO, join_room, leave_room
from flask_session import Session
from markupsafe import escape
from .db import get_db
from datetime import datetime
#flask_config
DATABASE = './Website/mate.db'
def create_logs(app):
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)
app.logger = logging.getLogger('db')
#def create_logs(app):
# 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)
# app.logger = logging.getLogger('db')
#
# app.logger.info("Website is starting")
app.logger.info("Website is starting")
def log(type=None, userid=None, before=None, after=None):
db = get_db()
c = db.cursor()
c.execute("INSERT or IGNORE INTO transaction_log (timestamp, userid, type, before, after) VALUES (?, ?, ?, ?, ?)", [datetime.now(), userid, type, before, after])
db.commit()
db.close()
def create_app(test_config=None):
app = Flask(__name__)
@ -30,8 +38,8 @@ def create_app(test_config=None):
os.makedirs(app.instance_path)
except OSError:
pass
with app.app_context():
create_logs(app)
#with app.app_context():
# create_logs(app)
Session(app)
socketio = SocketIO(app)
@ -93,6 +101,17 @@ def create_app(test_config=None):
<br></br>
''' + text + '</html>'
@app.route("/transactionlist")
def transactionlist():
db = get_db()
c = db.cursor()
text = ""
c.execute("SELECT * FROM transaction_log ORDER BY ROWID DESC LIMIT 100")
transactionlist = c.fetchall()
for i in transactionlist:
text = text + f"<p>{i[0]} userid: {i[1]} {i[2]} {i[3]} to {i[4]}</p>"
return text
@app.route("/list/user", methods=['GET'])
def user_info():
db = get_db()
@ -147,8 +166,8 @@ def create_app(test_config=None):
c.execute(f"DELETE FROM tags WHERE userid=?", [user_id])
app.logger.info(f"Deleted all tags from user ?", [user_id])
c.execute(f"DELETE FROM users WHERE id=?", [user_id])
app.logger.info(f"Deleted user ?", [user_id])
db.commit()
log(type="removeuser", userid=user_id, before=user_name)
socketio.emit("update", "update")
return f'<title>remove user</title><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>'
else:
@ -168,7 +187,7 @@ def create_app(test_config=None):
socketio.emit("update", "update")
c.execute(f"SELECT * FROM users WHERE username=?", [username])
user = c.fetchone()
app.logger.info(f"Added user id: {user[0]} name: {user[2]}")
log(type="adduser", userid=user[0], after=user[1])
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">
@ -198,7 +217,7 @@ def create_app(test_config=None):
db.commit()
c.execute(f"SELECT * FROM users WHERE id={user_id}")
user = c.fetchone()
app.logger.info(f"Changed the balance from user {user[0]} from {balance_old} to {user[2]}")
log(type="balance", userid=user[0], before=balance_old, after=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>
@ -304,7 +323,7 @@ def create_app(test_config=None):
db.commit()
c.execute(f"SELECT * FROM users WHERE id = {userid}")
user_new = c.fetchone()
app.logger.info(f"Changed the balance from user {user[0]} from {user[2]} to {user_new[2]}")
log(type="balance", userid=user[0], before=user[2], after=user_new[2])
socketio.emit("update", "update")
return make_response(json.dumps({"mode":"balance", "username":user[1], "balance":user_new[2]}))
else:
@ -327,7 +346,7 @@ def create_app(test_config=None):
state = queue_item[1]
c.execute(f"SELECT * FROM users WHERE id=?", [user])
username = c.fetchone()[1]
user_id = c.fetchone()[0]
if state == "add":
c.execute(f"SELECT * FROM tags WHERE tagid={tag_id}")
if c.fetchall() != []:
@ -336,8 +355,7 @@ def create_app(test_config=None):
return make_response(json.dumps({"mode":"error","error":"170"}))
else:
c.execute(f"INSERT OR IGNORE INTO tags (tagid, userid) VALUES ({tag_id}, ?)", [user])
message = f"Added {tag_id} to {username}"
app.logger.info(message)
log(type="addtag", userid=user_id ,after=tag_id)
finished = queue_item
db.commit()
return make_response(json.dumps({"mode":"message","username":"{}".format(username),"message":"A tag was added"}))
@ -346,8 +364,7 @@ def create_app(test_config=None):
tags = c.fetchall()
if tags != []:
c.execute(f"DELETE FROM tags WHERE (tagid = {tag_id} AND userid = ?)", [user])
message = f"Removed {tag_id} from {username}"
app.logger.info(message)
log(type="removetag", userid=user_id, before=tag_id)
finished = queue_item
db.commit()
return make_response(json.dumps({"mode":"message","username":"{}".format(username),"message":"A tag was removed"}))
@ -370,7 +387,7 @@ def create_app(test_config=None):
db.commit()
c.execute(f"SELECT * FROM users WHERE id={tag[1]}")
user = c.fetchone()
app.logger.info(f"Changed the balance from user {user[0]} from {balance_old} to {user[2]}")
log(type="balance", userid=user[0], before=balance_old, after=user[2])
socketio.emit("update", "update")
return make_response(json.dumps({"mode":"balance", "username":user[1], "balance":user[2]}))
else:

View file

@ -1,13 +0,0 @@
import sys
filename = sys.argv[1]
db_log = []
with open(filename, 'r') as f:
for line in f:
if "db" in line:
db_log.append(line)
with open("restore_log", "x") as f:
for i in db_log:
f.write(i)
f.close

View file

@ -6,9 +6,16 @@ CREATE TABLE IF NOT EXISTS "users" (
PRIMARY KEY("id")
);
CREATE TABLE IF NOT EXISTS "tags" (
"tagid" INEGER NOT NULL,
"tagid" INTEGER NOT NULL,
"userid" INTEGER,
FOREIGN KEY("userid") REFERENCES "users"("id"),
PRIMARY KEY("tagid")
);
CREATE TABLE IF NOT EXISTS "transaction_log" (
"timestamp" INTEGER NOT NULL,
"userid" INTEGER NOT NULL,
"type" TEXT NOT NULL,
"before" TEXT,
"after" TEXT
);
COMMIT;