Update firebase/firebase_config.py
Browse files- firebase/firebase_config.py +45 -9
firebase/firebase_config.py
CHANGED
|
@@ -3,17 +3,53 @@
|
|
| 3 |
import firebase_admin
|
| 4 |
from firebase_admin import credentials, firestore
|
| 5 |
import os
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
def init_firebase():
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
def log_message_to_firestore(message_dict):
|
| 15 |
db = init_firebase()
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import firebase_admin
|
| 4 |
from firebase_admin import credentials, firestore
|
| 5 |
import os
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
FALLBACK_LOG_PATH = "data/logs.json"
|
| 9 |
|
| 10 |
def init_firebase():
|
| 11 |
+
try:
|
| 12 |
+
if not firebase_admin._apps:
|
| 13 |
+
cred_path = "firebase_credentials.json"
|
| 14 |
+
if not os.path.exists(cred_path):
|
| 15 |
+
raise FileNotFoundError("Firebase credentials file not found.")
|
| 16 |
+
|
| 17 |
+
cred = credentials.Certificate(cred_path)
|
| 18 |
+
firebase_admin.initialize_app(cred)
|
| 19 |
+
return firestore.client()
|
| 20 |
+
except Exception as e:
|
| 21 |
+
print(f"[Firebase ERROR] {e}")
|
| 22 |
+
return None
|
| 23 |
|
| 24 |
def log_message_to_firestore(message_dict):
|
| 25 |
db = init_firebase()
|
| 26 |
+
if db:
|
| 27 |
+
try:
|
| 28 |
+
chat_ref = db.collection("conversations").document("bot_talk_log")
|
| 29 |
+
chat_ref.set({"messages": firestore.ArrayUnion([message_dict])}, merge=True)
|
| 30 |
+
return
|
| 31 |
+
except Exception as e:
|
| 32 |
+
print(f"[Firestore ERROR] {e}")
|
| 33 |
+
|
| 34 |
+
# Fallback if Firebase not available
|
| 35 |
+
log_to_local_file(message_dict)
|
| 36 |
+
|
| 37 |
+
def log_to_local_file(message_dict):
|
| 38 |
+
os.makedirs("data", exist_ok=True)
|
| 39 |
+
|
| 40 |
+
# Read existing logs
|
| 41 |
+
if os.path.exists(FALLBACK_LOG_PATH):
|
| 42 |
+
with open(FALLBACK_LOG_PATH, "r") as f:
|
| 43 |
+
try:
|
| 44 |
+
logs = json.load(f)
|
| 45 |
+
except json.JSONDecodeError:
|
| 46 |
+
logs = []
|
| 47 |
+
else:
|
| 48 |
+
logs = []
|
| 49 |
+
|
| 50 |
+
logs.append(message_dict)
|
| 51 |
+
|
| 52 |
+
with open(FALLBACK_LOG_PATH, "w") as f:
|
| 53 |
+
json.dump(logs, f, indent=2)
|
| 54 |
+
|
| 55 |
+
print("[Local LOG] Message saved to fallback log.")
|