From 223f95364866278baa5d2640177665cc6f827115 Mon Sep 17 00:00:00 2001
From: Patrick_Pluto <patrick_pluto@noreply.codeberg.org>
Date: Mon, 30 Sep 2024 15:26:31 +0200
Subject: [PATCH] fixed some database backend stuff

---
 .gitignore                         |  2 ++
 app/backend/InputOutputHandler.tsx | 11 +++++++++--
 app/backend/database.ts            | 31 +++++++++++++++---------------
 app/backend/threads/PostWorker.js  | 11 ++++++-----
 app/backend/voice_backend.ts       |  1 -
 app/components/Models.tsx          |  3 +++
 py/api.py                          | 16 +++++++--------
 py/db.py                           | 24 +++++++++++++----------
 8 files changed, 58 insertions(+), 41 deletions(-)

diff --git a/.gitignore b/.gitignore
index 93a7e59..fb2020f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -43,3 +43,5 @@ __pycache__/
 key.pem
 cert.pem
 api_key.txt
+
+database.json
diff --git a/app/backend/InputOutputHandler.tsx b/app/backend/InputOutputHandler.tsx
index 92fa6df..0bde2f5 100644
--- a/app/backend/InputOutputHandler.tsx
+++ b/app/backend/InputOutputHandler.tsx
@@ -9,7 +9,6 @@ import { resolve } from "path";
 import { FFmpeg } from "@ffmpeg/ffmpeg";
 import { fetchFile, toBlobURL } from "@ffmpeg/util"
 
-
 const InputOutputBackend: React.FC = () => {
   // # variables
   type Message = {
@@ -174,7 +173,15 @@ const InputOutputBackend: React.FC = () => {
         if (postWorkerRef.current) {
           addMessage("user", inputValue)
           console.log("input:", inputValue);
-          postWorkerRef.current.postMessage({ messages: [...messages, { role: "user", content: inputValue }], ai_model: "llama3.2", access_token: accessToken })
+          const type = localStorage.getItem('type')
+          var api_key: string = ""
+          if (type != null && type != 'local') {
+            const try_key = localStorage.getItem(type)
+            if (try_key) {
+              api_key = try_key
+            }
+          }
+          postWorkerRef.current.postMessage({ messages: [...messages, { role: "user", content: inputValue }], ai_model: localStorage.getItem('model'), model_type: type, access_token: accessToken, api_key: api_key })
           startGetWorker()
         }
       }
diff --git a/app/backend/database.ts b/app/backend/database.ts
index 054302b..45fd103 100644
--- a/app/backend/database.ts
+++ b/app/backend/database.ts
@@ -18,27 +18,28 @@ if all went well, you will get the status 200 in response.data.status
 to check if the request was accepted or declined, check response.data.response, it will be either true or false depending on if it worked, or not.
 */
 
-export const sendToDatabase = (data: any): Promise<boolean> => {
-  return axios.post("http://localhost:5000/interstellar_ai/db", data)
-    .then(response => {
-      const status = response.data.status;
-      const success = response.data.response;
-      postMessage({ status, success });
-      return success;  // Ensure success is returned to the caller
-    })
-    .catch(error => {
-      postMessage({ status: 500, success: false });
-      return false;  // Return false in case of an error
-    });
+export const sendToDatabase = async (data: any): Promise<boolean> => {
+  try {
+    const response = await axios.post("http://localhost:5000/interstellar_ai/db", data);
+    const status = response.data.status;
+    const success = response.data.response;
+    postMessage({ status, success });
+    console.log(status);
+    return success;
+  } catch (error) {
+    postMessage({ status: 500, success: false });
+    console.log("NO");
+    return false;
+  }
 };
 
 // Functions for each action
 export const createAccount = async (username: string, email: string, password: string) => {
   const data = {
     action: "create_account",
-    username,
-    email,
-    password,
+    username: username,
+    email: email,
+    password: password,
   };
   return await sendToDatabase(data);
 };
diff --git a/app/backend/threads/PostWorker.js b/app/backend/threads/PostWorker.js
index 9fb01e2..bae9989 100644
--- a/app/backend/threads/PostWorker.js
+++ b/app/backend/threads/PostWorker.js
@@ -1,14 +1,15 @@
 import axios from "axios";
 
 onmessage = (e) => {
-    const { messages, ai_model = "llama3.2", access_token } = e.data
-    
+    const { messages, ai_model, model_type, access_token, api_key } = e.data
+
 
     const Message = {
         messages: messages,
-        ai_model: "llama3.2",
-        model_type: "local",
-        access_token: access_token
+        ai_model: ai_model,
+        model_type: model_type,
+        access_token: access_token,
+        api_key: api_key
     }
 
     console.log(Message);
diff --git a/app/backend/voice_backend.ts b/app/backend/voice_backend.ts
index ca8a998..c91a058 100644
--- a/app/backend/voice_backend.ts
+++ b/app/backend/voice_backend.ts
@@ -6,7 +6,6 @@ export const sendToVoiceRecognition = (audio_data: Blob): Promise<string> => {
     const formdata = new FormData()
     formdata.append("audio", audio_data)
 
-    const dataSend = { option: "offline", type: "basic", audio: audio_data }
     return axios.post("http://localhost:5000/interstellar_ai/api/voice_recognition", formdata)
         .then((response) => {
             console.log(response.data)
diff --git a/app/components/Models.tsx b/app/components/Models.tsx
index 1f9dc56..a839a1c 100644
--- a/app/components/Models.tsx
+++ b/app/components/Models.tsx
@@ -240,6 +240,9 @@ const Models: React.FC = () => {
     console.log(model)
     console.log(category)
     console.log(modelList[category][model as keyof typeof modelList[typeof category]]);
+    console.log(modelList[category]['model_type' as keyof typeof modelList[typeof category]])
+    localStorage.setItem("model", modelList[category][model as keyof typeof modelList[typeof category]])
+    localStorage.setItem("type", modelList[category]['model_type' as keyof typeof modelList[typeof category]])
   }
 
   return (
diff --git a/py/api.py b/py/api.py
index 75fbfd4..7683afe 100644
--- a/py/api.py
+++ b/py/api.py
@@ -89,20 +89,20 @@ class API:
 
         @self.app.route('/interstellar_ai/db', methods=['POST'])
         def db_manipulate():
-            action = request.args.get('action')
-            data = request.args.get('data')
+            sent_data = request.get_json()
+            action = sent_data.get('action')
             if action == "create_account":
-                return jsonify({'status': 200, 'response': self.db.add_user(data)})
+                return jsonify({'status': 200, 'response': self.db.add_user(sent_data)})
             elif action == "change_password":
-                return jsonify({'status': 200, 'response': self.db.update_password(data)})
+                return jsonify({'status': 200, 'response': self.db.update_password(sent_data)})
             elif action == "get_data":
-                return jsonify({'status': 200, 'response': self.db.get_data(data)})
+                return jsonify({'status': 200, 'response': self.db.get_data(sent_data)})
             elif action == "change_data":
-                return jsonify({'status': 200, 'response': self.db.change_data(data)})
+                return jsonify({'status': 200, 'response': self.db.change_data(sent_data)})
             elif action == "check_credentials":
-                return jsonify({'status': 200, 'response': self.db.check_credentials(data)})
+                return jsonify({'status': 200, 'response': self.db.check_credentials(sent_data)})
             elif action == "delete_account":
-                return jsonify({'status': 200, 'response': self.db.delete_user(data)})
+                return jsonify({'status': 200, 'response': self.db.delete_user(sent_data)})
 
             return jsonify({'status': 401, 'response': "Invalid action"})
 
diff --git a/py/db.py b/py/db.py
index 3f66ac7..a20cd84 100644
--- a/py/db.py
+++ b/py/db.py
@@ -10,10 +10,10 @@ class DB:
 
     def ensure_username(self, data):
         if hasattr(data, 'username'):
-            return data.get['username']
+            return data.get('username')
         elif hasattr(data, 'email'):
             for index, entry in self.database:
-                if entry.get['email'] == data.get['email']:
+                if entry.get('email') == data.get('email'):
                     return index
 
     @staticmethod
@@ -23,19 +23,22 @@ class DB:
         return hashed_password
 
     def add_user(self, data):
-        username = data.get['username']
-        password = data.get['password']
-        email = data.get['email']
+        username = data.get('username')
+        password = data.get('password')
+        email = data.get('email')
         hashed_password = self.hash_password(password)
         user_data = {"hashed_password": hashed_password, "email": email, "data": None}
         if username not in self.database:
             self.database[username] = user_data
+            print("yes")
+            self.save_database()
             return True
+        print("fail")
         return False
 
     def delete_user(self, data):
         username = self.ensure_username(data)
-        data = data.get['data']
+        data = data.get('data')
         if not self.check_credentials(data):
             return False
 
@@ -45,7 +48,7 @@ class DB:
 
     def change_data(self, data):
         username = self.ensure_username(data)
-        data = data.get['data']
+        data = data.get('data')
         if not self.check_credentials(data):
             return False
 
@@ -55,7 +58,7 @@ class DB:
 
     def update_password(self, data):
         username = self.ensure_username(data)
-        new_password = data.get['new_password']
+        new_password = data.get('new_password')
         if not self.check_credentials(data):
             return False
 
@@ -66,7 +69,7 @@ class DB:
 
     def check_credentials(self, data):
         username = self.ensure_username(data)
-        password = data.get['password']
+        password = data.get('password')
         if username not in self.database:
             return False
 
@@ -79,7 +82,7 @@ class DB:
         if not self.check_credentials(data):
             return None
 
-        send_back = self.database[username].get['data']
+        send_back = self.database(username).get('data')
         return send_back
 
     def save_database(self):
@@ -90,6 +93,7 @@ class DB:
 
         else:
             with open("database.json", 'w') as file:
+                print("saving")
                 json.dump(self.database, file)
 
     def load_database(self):