major cleanup. Sir, yes, sir!

This commit is contained in:
2023-01-31 20:03:26 +01:00
parent efc8f565bf
commit 6ebf34c4a9
12 changed files with 448 additions and 340 deletions

85
app.py Executable file → Normal file
View File

@@ -1,43 +1,58 @@
#!/usr/bin/env python3
from flask import Flask, render_template, url_for, request, redirect, Response, abort, session
from flask_sock import Sock
from flask_sqlalchemy import SQLAlchemy
from werkzeug.middleware.proxy_fix import ProxyFix
from datetime import datetime
import magic
import random
import string
import asyncio
import websockets
import json
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
app.secret_key = '029c0gji3jfo3o8h938vhwtfmh3t39th'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cloudvars.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
sock = Sock(app)
clients = {}
vars = {}
class variables(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
namespace = db.Column(db.String(64), nullable=False)
project = db.Column(db.String(64), nullable=False)
name = db.Column(db.String(64), nullable=False)
value = db.Column(db.String(64), nullable=True)
async def handshake(ws,data):
project_id = data.get('project_id','')
user = data.get('user')
print(f"{project_id} new user connected from {ws.host}:{ws.port}")
if not clients.get(project_id):
clients[project_id] = []
clients[project_id].append(ws)
await get_variables(ws,project_id,user)
return (project_id,user)
@app.context_processor
def get_date():
date = datetime.now()
return { "now": date.strftime("%Y-%m-%d") }
async def get_variables(ws,project_id,user):
for name,value in vars.get(project_id,{}).items():
if not name:
continue
await ws.send(json.dumps({"method":"set","name":name,"value":value}))
@sock.route('/')
def echo(sock):
while True:
data = json.loads(sock.receive())
sock.send(json.dumps({"method":"set","name":"test","value":"abcd"}))
async def set_variable(project_id,var):
if not vars.get(project_id,''):
vars[project_id] = {}
vars[project_id][var.get('name','')] = var.get('value','')
await websockets.broadcast(clients.get(project_id,[]),json.dumps(var))
@app.route('/', methods = ['GET'])
def index():
return render_template('index.html')
async def disconnect(project_id,user):
print("disconnecting",user)
clients.get(project_id,[]).pop(user)
async def process(ws, path):
project_id = ""
user = ""
async for msg in ws:
print(f"< {user} - {msg}")
try:
data = json.loads(msg)
method = data.get('method','')
if method == 'handshake':
project_id,user = await handshake(ws,data)
if method in ['set','create']:
await set_variable(project_id,data)
finally:
pass
await disconnect(project_id,ws)
if __name__ == "__main__":
app.run(debug=True)
try:
start_server = websockets.serve(process, 'localhost', 5000, compression=None)
finally:
pass
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()