From a855d8ac650dd6644891567fd94276997dc11e02 Mon Sep 17 00:00:00 2001 From: Anton Franzluebbers Date: Thu, 23 Jun 2022 22:27:28 -0400 Subject: [PATCH] switched to sqlite, added support for streamer_ vals --- .gitignore | 3 +- velconnect/CreateDB.sql | 7 +- velconnect/api.py | 70 +++--- velconnect/db.py | 59 +++--- velconnect/templates/api.html | 40 ++-- velconnect/templates/failure.html | 2 +- velconnect/templates/index.html | 342 ++++++++++++++++-------------- velconnect/templates/success.html | 12 +- 8 files changed, 273 insertions(+), 262 deletions(-) diff --git a/.gitignore b/.gitignore index 4f08dce..25facc8 100644 --- a/.gitignore +++ b/.gitignore @@ -9,4 +9,5 @@ spectre/ velconnect_backup.sql discord_bot/graph.png discord_bot/config.py -env_win/ \ No newline at end of file +env_win/ +velconnect.db \ No newline at end of file diff --git a/velconnect/CreateDB.sql b/velconnect/CreateDB.sql index 0da9cd6..716008c 100644 --- a/velconnect/CreateDB.sql +++ b/velconnect/CreateDB.sql @@ -9,11 +9,9 @@ CREATE TABLE `Room` ( `modified_by` VARCHAR(64), -- array of hw_ids of users allowed. Always includes the owner. Null for public `whitelist` JSON, - CHECK (JSON_VALID(`whitelist`)), `tv_url` VARCHAR(1024), `carpet_color` VARCHAR(9), - `room_details` JSON, - CHECK (JSON_VALID(`room_details`)) + `room_details` JSON ); DROP TABLE IF EXISTS `Headset`; CREATE TABLE `Headset` ( @@ -35,8 +33,7 @@ CREATE TABLE `Headset` ( -- Stuff like player color, nickname, whiteboard state `user_details` JSON, `streamer_stream_id` VARCHAR(64), - `streamer_control_id` VARCHAR(64), - CHECK (JSON_VALID(`user_details`)) + `streamer_control_id` VARCHAR(64) ); DROP TABLE IF EXISTS `APIKey`; CREATE TABLE `APIKey` ( diff --git a/velconnect/api.py b/velconnect/api.py index 4dafa7c..6289103 100644 --- a/velconnect/api.py +++ b/velconnect/api.py @@ -26,7 +26,7 @@ oauth2_scheme = OAuth2PasswordBearer( def api_key_auth(api_key: str = Depends(oauth2_scheme)): return True values = query( - "SELECT * FROM `APIKey` WHERE `key`=%(key)s;", {'key': api_key}) + "SELECT * FROM `APIKey` WHERE `key`=:key;", {'key': api_key}) if not (len(values) > 0 and values['auth_level'] < 0): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, @@ -71,7 +71,7 @@ def get_all_headsets(): @router.get('/pair_headset/{pairing_code}') def pair_headset(pairing_code: str): - values = query("SELECT * FROM `Headset` WHERE `pairing_code`=%(pairing_code)s;", + values = query("SELECT * FROM `Headset` WHERE `pairing_code`=:pairing_code;", {'pairing_code': pairing_code}) if len(values) == 1: print(values[0]['hw_id']) @@ -81,36 +81,33 @@ def pair_headset(pairing_code: str): class UpdatePairingCode(BaseModel): hw_id: str - pairing_code: str + pairing_code: int @router.post('/update_pairing_code') -def update_paring_code(data: UpdatePairingCode): +def update_pairing_code(data: UpdatePairingCode): """This also creates a headset if it doesn't exist""" - if 'hw_id' not in data: - return 'Must supply hw_id', 400 - if 'pairing_code' not in data: - return 'Must supply pairing_code', 400 + print("Update pairing code") + print(data) + + create_headset(data.hw_id) insert(""" - INSERT INTO `Headset`( - `hw_id`, - `pairing_code`, - `last_used` - ) VALUES ( - %(hw_id)s, - %(pairing_code)s, - CURRENT_TIMESTAMP - ) - ON DUPLICATE KEY UPDATE - pairing_code=%(pairing_code)s, - last_used=CURRENT_TIMESTAMP; - """, data) + UPDATE `Headset` + SET `pairing_code`=:pairing_code, `last_used`=CURRENT_TIMESTAMP + WHERE `hw_id`=:hw_id; + """, data.dict()) return {'success': True} +def create_headset(hw_id: str): + insert(""" + INSERT OR IGNORE INTO Headset(hw_id) VALUES (:hw_id); + """, {'hw_id': hw_id}) + + @router.get('/get_state/{hw_id}') def get_headset_details(hw_id: str): data = get_headset_details_db(hw_id) @@ -122,7 +119,7 @@ def get_headset_details(hw_id: str): def get_headset_details_db(hw_id): headsets = query(""" - SELECT * FROM `Headset` WHERE `hw_id`=%(hw_id)s; + SELECT * FROM `Headset` WHERE `hw_id`=:hw_id; """, {'hw_id': hw_id}) if len(headsets) == 0: return None @@ -134,8 +131,11 @@ def get_headset_details_db(hw_id): @router.post('/set_headset_details/{hw_id}') def set_headset_details_generic(hw_id: str, data: dict): + print("Data:") print(data) + # create_headset(hw_id) + allowed_keys = [ 'current_room', 'pairing_code', @@ -143,13 +143,15 @@ def set_headset_details_generic(hw_id: str, data: dict): 'user_name', 'avatar_url', 'user_details', + 'streamer_stream_id', + 'streamer_control_id', ] for key in data: if key in allowed_keys: if key == 'current_room': create_room(data['current_room']) - insert("UPDATE `Headset` SET " + key + - "=%(value)s, modified_by=%(sender_id)s WHERE `hw_id`=%(hw_id)s;", {'value': data[key], 'hw_id': hw_id, 'sender_id': data['sender_id']}) + insert(f"UPDATE `Headset` SET {key}=:value, modified_by=:sender_id WHERE `hw_id`=:hw_id;", { + 'value': data[key], 'hw_id': hw_id, 'sender_id': data['sender_id']}) return {'success': True} @@ -167,7 +169,7 @@ def set_room_details_generic(room_id: str, data: dict): for key in data: if key in allowed_keys: insert("UPDATE `Room` SET " + key + - "=%(value)s, modified_by=%(sender_id)s WHERE `room_id`=%(room_id)s;", {'value': data[key], 'room_id': room_id, 'sender_id': data['sender_id']}) + "=:value, modified_by=:sender_id WHERE `room_id`=:room_id;", {'value': data[key], 'room_id': room_id, 'sender_id': data['sender_id']}) return {'success': True} @@ -178,7 +180,7 @@ def get_room_details(room_id: str): def get_room_details_db(room_id): values = query(""" - SELECT * FROM `Room` WHERE room_id=%(room_id)s; + SELECT * FROM `Room` WHERE room_id=:room_id; """, {'room_id': room_id}) if len(values) == 1: return values[0] @@ -188,9 +190,9 @@ def get_room_details_db(room_id): def create_room(room_id): insert(""" - INSERT IGNORE INTO `Room`(room_id) + INSERT OR IGNORE INTO `Room`(room_id) VALUES( - %(room_id)s + :room_id ); """, {'room_id': room_id}) return {'room_id': room_id} @@ -202,12 +204,12 @@ def update_user_count(data: dict): REPLACE INTO `UserCount` VALUES( CURRENT_TIMESTAMP, - %(hw_id)s, - %(room_id)s, - %(total_users)s, - %(room_users)s, - %(version)s, - %(platform)s + :hw_id, + :room_id, + :total_users, + :room_users, + :version, + :platform ); """, data) return {'success': True} diff --git a/velconnect/db.py b/velconnect/db.py index f2f3031..92df736 100644 --- a/velconnect/db.py +++ b/velconnect/db.py @@ -1,47 +1,50 @@ -# from config import * -import pymysql -from pymysql import converters -from config_mysql import * +import sqlite3 +import os +import traceback -def connectToDB(): - conv = converters.conversions.copy() - conv[246] = float # convert decimals to floats - conn = pymysql.connect( - host=MYSQL_DATABASE_HOST, - user=MYSQL_DATABASE_USER, - password=MYSQL_DATABASE_PASSWORD, - db=MYSQL_DATABASE_DB, - cursorclass=pymysql.cursors.DictCursor, - conv=conv, - ssl={"fake_flag_to_enable_tls": True}, - ) +def create_or_connect(): + db_name = 'velconnect.db' + create = False + if not os.path.exists(db_name, ): + create = True + + conn = sqlite3.connect(db_name) + conn.row_factory = sqlite3.Row curr = conn.cursor() + if create: + # create the db + with open('CreateDB.sql', 'r') as f: + curr.executescript(f.read()) + conn.set_trace_callback(print) return conn, curr def query(query: str, data: dict = None) -> list: try: - conn, curr = connectToDB() - curr.execute(query, data) - values = [dict(row) for row in curr.fetchall()] - curr.close() + conn, curr = create_or_connect() + if data is not None: + curr.execute(query, data) + else: + curr.execute(query) + values = curr.fetchall() + conn.close() return values - except Exception: - print(curr._last_executed) - curr.close() + except: + print(traceback.print_exc()) + conn.close() raise def insert(query: str, data: dict = None) -> bool: try: - conn, curr = connectToDB() + conn, curr = create_or_connect() curr.execute(query, data) conn.commit() - curr.close() + conn.close() return True - except Exception: - print(curr._last_executed) - curr.close() + except: + print(traceback.print_exc()) + conn.close() raise diff --git a/velconnect/templates/api.html b/velconnect/templates/api.html index ecda3c5..40e27d4 100644 --- a/velconnect/templates/api.html +++ b/velconnect/templates/api.html @@ -1,24 +1,20 @@ - - - - - - - - + -
- -
-
- - \ No newline at end of file + + + + + + + + + +
+ +
+
+ + + \ No newline at end of file diff --git a/velconnect/templates/failure.html b/velconnect/templates/failure.html index b9f3a2f..21f3dfd 100644 --- a/velconnect/templates/failure.html +++ b/velconnect/templates/failure.html @@ -10,7 +10,7 @@ - +