-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfirebase_sync.py
More file actions
253 lines (207 loc) · 8.66 KB
/
firebase_sync.py
File metadata and controls
253 lines (207 loc) · 8.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
"""
Firebase synchronization module for queue overlay.
This module handles pushing queue state to Firebase Realtime Database
so that the OBS overlay can display real-time queue updates.
"""
import os
import json
from typing import List, Dict, Optional
import requests
class FirebaseSync:
"""Manages Firebase Realtime Database synchronization for the queue."""
def __init__(self, firebase_url: Optional[str] = None, service_account_path: Optional[str] = None):
"""
Initialize Firebase sync.
Args:
firebase_url: Firebase Realtime Database URL (e.g., https://your-project.firebaseio.com)
If not provided, will check config file, then environment variable.
service_account_path: Path to Firebase service account JSON file
If not provided, will check config file, then environment variable.
"""
# Try to load from config file first
config = self._load_config()
self.firebase_url = firebase_url or config.get('firebase_url') or os.environ.get('FIREBASE_URL')
if not self.firebase_url:
raise ValueError(
"Firebase URL must be provided via:\n"
" 1. firebase_config.json file\n"
" 2. FIREBASE_URL environment variable\n"
" 3. Or passed directly to FirebaseSync()"
)
# Remove trailing slash if present
self.firebase_url = self.firebase_url.rstrip('/')
# Initialize authentication
self.access_token = None
service_account_path = service_account_path or config.get('service_account_path') or os.environ.get('FIREBASE_SERVICE_ACCOUNT')
if service_account_path:
try:
import firebase_admin
from firebase_admin import credentials, db
# Initialize Firebase Admin SDK
if not firebase_admin._apps:
cred = credentials.Certificate(service_account_path)
firebase_admin.initialize_app(cred, {
'databaseURL': self.firebase_url
})
self.use_admin_sdk = True
self.db = db
print(f"Firebase sync initialized with Admin SDK: {self.firebase_url}")
except ImportError:
print("Warning: firebase-admin not installed. Install with: pip install firebase-admin")
print("Falling back to REST API (requires test mode or custom auth)")
self.use_admin_sdk = False
except Exception as e:
print(f"Warning: Failed to initialize Firebase Admin SDK: {e}")
print("Falling back to REST API (requires test mode or custom auth)")
self.use_admin_sdk = False
else:
self.use_admin_sdk = False
print(f"Firebase sync initialized with REST API: {self.firebase_url}")
print("Note: For production mode, set FIREBASE_SERVICE_ACCOUNT environment variable")
self.enabled = True
def _load_config(self) -> Dict:
"""
Load configuration from firebase_config.json if it exists.
Returns:
Dictionary with config values, or empty dict if file doesn't exist
"""
config_path = os.path.join(os.path.dirname(__file__), 'firebase_config.json')
if os.path.exists(config_path):
try:
with open(config_path, 'r') as f:
return json.load(f)
except Exception as e:
print(f"Warning: Could not load firebase_config.json: {e}")
return {}
def _format_queue_data(self, processing_requests: List[Dict], ready_requests: List[Dict]) -> Dict:
"""
Format queue data for Firebase.
Args:
processing_requests: List of songs currently being processed
ready_requests: List of songs ready to play
Returns:
Formatted dictionary for Firebase
"""
return {
"processing": [
{
"user": item.get('user', 'Unknown'),
"search": item.get('search', ''),
}
for item in processing_requests
],
"ready": [
{
"user": item.get('user', 'Unknown'),
"song": os.path.basename(item.get('location', '')) if item.get('location') else item.get('search', 'Unknown'),
}
for item in ready_requests
],
"timestamp": self._get_timestamp()
}
def _get_timestamp(self) -> int:
"""Get current timestamp in milliseconds."""
from time import time
return int(time() * 1000)
def update_queue(self, processing_requests: List[Dict], ready_requests: List[Dict]) -> bool:
"""
Update the queue state in Firebase.
Args:
processing_requests: Current processing queue
ready_requests: Current ready queue
Returns:
True if successful, False otherwise
"""
if not self.enabled:
return False
try:
data = self._format_queue_data(processing_requests, ready_requests)
if self.use_admin_sdk:
# Use Admin SDK (automatically authenticated)
ref = self.db.reference('/queue')
ref.set(data)
else:
# Use REST API (requires test mode or custom auth)
url = f"{self.firebase_url}/queue.json"
response = requests.put(url, json=data, timeout=5)
response.raise_for_status()
return True
except requests.exceptions.RequestException as e:
print(f"Failed to update Firebase: {e}")
return False
except Exception as e:
print(f"Unexpected error updating Firebase: {e}")
return False
def update_now_playing(self, song_info: Optional[Dict]) -> bool:
"""
Update the currently playing song in Firebase.
Args:
song_info: Dictionary with 'song' and 'user' keys, or None if nothing playing
Returns:
True if successful, False otherwise
"""
if not self.enabled:
return False
try:
data = song_info if song_info else {"song": None, "user": None}
data["timestamp"] = self._get_timestamp()
if self.use_admin_sdk:
# Use Admin SDK (automatically authenticated)
ref = self.db.reference('/nowPlaying')
ref.set(data)
else:
# Use REST API (requires test mode or custom auth)
url = f"{self.firebase_url}/nowPlaying.json"
response = requests.put(url, json=data, timeout=5)
response.raise_for_status()
return True
except requests.exceptions.RequestException as e:
print(f"Failed to update now playing in Firebase: {e}")
return False
except Exception as e:
print(f"Unexpected error updating now playing: {e}")
return False
def clear_all(self) -> bool:
"""
Clear all data from Firebase.
Returns:
True if successful, False otherwise
"""
if not self.enabled:
return False
try:
if self.use_admin_sdk:
# Use Admin SDK
ref = self.db.reference('/')
ref.delete()
else:
# Use REST API
url = f"{self.firebase_url}/.json"
response = requests.delete(url, timeout=5)
response.raise_for_status()
print("Firebase data cleared")
return True
except requests.exceptions.RequestException as e:
print(f"Failed to clear Firebase: {e}")
return False
except Exception as e:
print(f"Unexpected error clearing Firebase: {e}")
return False
# Singleton instance
_firebase_instance: Optional[FirebaseSync] = None
def get_firebase_sync(firebase_url: Optional[str] = None) -> Optional[FirebaseSync]:
"""
Get or create the Firebase sync singleton instance.
Args:
firebase_url: Firebase URL (only used on first call)
Returns:
FirebaseSync instance, or None if Firebase URL not configured
"""
global _firebase_instance
if _firebase_instance is None:
try:
_firebase_instance = FirebaseSync(firebase_url)
except ValueError as e:
print(f"Firebase not configured: {e}")
return None
return _firebase_instance