-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirebaseFetcher.cs
More file actions
705 lines (615 loc) · 22.5 KB
/
FirebaseFetcher.cs
File metadata and controls
705 lines (615 loc) · 22.5 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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
using System;
using System.Collections;
using UnityEngine;
using Firebase;
using Firebase.Auth;
using Firebase.Firestore;
using Firebase.Extensions;
using System.Threading.Tasks;
using TMPro;
using UnityEngine.Networking;
// Simple TeamData structure
[System.Serializable]
public class TeamData
{
public int teamNumber;
public string uid;
public string teamName;
public string player1;
public string player2;
public string email;
public int score;
}
public class FirebaseFetcher : MonoBehaviour
{
public enum DataBackend
{
Firestore,
RealtimeDatabase
}
public enum ConnectionMethod
{
DirectFirebaseOnly,
RestFallbackIfNeeded,
RestOnly
}
[Header("Debug")]
public bool enableDebugLogs = true;
[Header("Verification Panel UI")]
public GameObject verificationPanel;
public TextMeshProUGUI teamDetailsText;
public UnityEngine.UI.Button verifyTeamButton;
[Header("Connection Settings")]
public ConnectionMethod connectionMethod = ConnectionMethod.RestFallbackIfNeeded;
[Tooltip("Required for REST fallback: Your Firebase Project ID (e.g., arth-33ed6)")]
public string firebaseProjectId = "";
[Tooltip("When enabled, logs the raw REST response JSON for debugging")]
public bool logRestResponses = false;
[Header("Realtime Database Settings")]
public DataBackend dataBackend = DataBackend.RealtimeDatabase;
[Tooltip("Base URL to your RTDB, e.g., https://your-project-id-default-rtdb.region.firebasedatabase.app")]
public string realtimeDatabaseBaseUrl = "";
[Tooltip("Optional auth token or database secret to append as ?auth=TOKEN. Leave empty if rules allow public read for testing.")]
public string realtimeDatabaseAuthToken = "";
// Firebase instances
private FirebaseFirestore db;
private bool isFirebaseReady = false;
// Cached team data
private TeamData cachedTeamData;
private bool isTeamDataLoaded = false;
// Events
public static event System.Action<TeamData> OnTeamDataFetched;
public static event System.Action<string> OnTeamDataFetchFailed;
public static event System.Action OnTeamVerified;
// Singleton
private static FirebaseFetcher instance;
public static FirebaseFetcher Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<FirebaseFetcher>();
if (instance == null)
{
GameObject go = new GameObject("FirebaseFetcher");
instance = go.AddComponent<FirebaseFetcher>();
}
}
return instance;
}
}
void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else if (instance != this)
{
Destroy(gameObject);
}
}
void Start()
{
// Setup UI
if (verifyTeamButton != null)
{
verifyTeamButton.onClick.AddListener(OnVerifyTeamClicked);
}
if (verificationPanel != null)
{
verificationPanel.SetActive(false);
}
// Initialize Firebase unless REST-only mode or using Realtime Database
if (dataBackend == DataBackend.Firestore && connectionMethod != ConnectionMethod.RestOnly)
{
StartCoroutine(InitializeFirebaseSimple());
}
}
private IEnumerator InitializeFirebaseSimple()
{
Log("Initializing Firebase...");
// Only initialize on mobile devices to prevent desktop config conflicts
#if UNITY_ANDROID || UNITY_IOS
var dependencyTask = FirebaseApp.CheckAndFixDependenciesAsync();
// Add timeout for dependency check
float timeout = 15f;
float elapsed = 0f;
while (!dependencyTask.IsCompleted && elapsed < timeout)
{
elapsed += Time.deltaTime;
yield return null;
}
if (elapsed >= timeout)
{
LogError("❌ Firebase initialization timeout");
isFirebaseReady = false;
yield break;
}
// Handle the result without try-catch in coroutine
if (dependencyTask.IsFaulted)
{
LogError($"❌ Firebase initialization exception: {dependencyTask.Exception?.GetBaseException()?.Message}");
isFirebaseReady = false;
yield break;
}
if (dependencyTask.Result == DependencyStatus.Available)
{
// Initialize Firebase app first
var app = FirebaseApp.DefaultInstance;
if (app == null)
{
LogError("❌ Failed to get Firebase App");
isFirebaseReady = false;
yield break;
}
db = FirebaseFirestore.DefaultInstance;
if (db != null)
{
Log("✅ Firebase ready!");
isFirebaseReady = true;
}
else
{
LogError("❌ Failed to get Firestore");
isFirebaseReady = false;
}
}
else
{
LogError($"❌ Firebase dependencies failed: {dependencyTask.Result}");
isFirebaseReady = false;
}
#else
// In Unity Editor - skip Firebase to prevent desktop config generation
Log("⚠️ Firebase disabled in editor to prevent crashes. Build to device to test.");
isFirebaseReady = false;
#endif
}
public void FetchTeamData(string uid)
{
if (string.IsNullOrEmpty(uid))
{
LogError("UID cannot be empty");
OnTeamDataFetchFailed?.Invoke("UID cannot be empty");
return;
}
// If using Realtime Database, go via RTDB path (REST)
if (dataBackend == DataBackend.RealtimeDatabase)
{
if (string.IsNullOrWhiteSpace(realtimeDatabaseBaseUrl))
{
LogError("Realtime Database base URL is not set");
OnTeamDataFetchFailed?.Invoke("Configuration error: RTDB URL missing");
return;
}
StartCoroutine(FetchTeamDataRealtimeCoroutine(uid));
return;
}
// REST-only mode (Firestore)
if (connectionMethod == ConnectionMethod.RestOnly)
{
if (string.IsNullOrWhiteSpace(firebaseProjectId))
{
LogError("Project ID is required for REST-only mode");
OnTeamDataFetchFailed?.Invoke("Configuration error: Project ID missing");
return;
}
Log($"[REST-Only] Fetching UID: {uid}");
StartCoroutine(FetchTeamDataRestCoroutine(uid));
return;
}
// Prefer Firebase SDK if ready
if (isFirebaseReady && db != null)
{
Log($"Fetching team data for UID: {uid} (Firebase SDK)");
StartCoroutine(FetchTeamDataCoroutine(uid));
return;
}
// If SDK is not ready, optionally fall back to REST
if (connectionMethod == ConnectionMethod.RestFallbackIfNeeded)
{
if (string.IsNullOrWhiteSpace(firebaseProjectId))
{
LogError("Firebase not ready and Project ID not set for REST fallback");
OnTeamDataFetchFailed?.Invoke("Firebase not ready");
return;
}
Log($"Firebase not ready. Falling back to REST for UID: {uid}");
StartCoroutine(FetchTeamDataRestCoroutine(uid));
}
else
{
LogError("Firebase not ready");
OnTeamDataFetchFailed?.Invoke("Firebase not ready");
}
}
private IEnumerator FetchTeamDataCoroutine(string uid)
{
var fetchTask = FetchTeamDataAsync(uid);
// Add timeout protection
float timeout = 15f;
float elapsed = 0f;
while (!fetchTask.IsCompleted && elapsed < timeout)
{
elapsed += Time.deltaTime;
yield return null;
}
// Check for timeout
if (elapsed >= timeout)
{
LogError("❌ Firebase fetch timeout");
// Ensure UI updates happen on main thread
UnityMainThreadDispatcher.Instance.Enqueue(() => {
OnTeamDataFetchFailed?.Invoke("Request timeout - please try again");
});
yield break;
}
// Handle task completion on main thread
if (fetchTask.IsFaulted)
{
string error = fetchTask.Exception != null ? fetchTask.Exception.GetBaseException().Message : "Firebase fetch failed";
LogError($"❌ {error}");
// Ensure UI updates happen on main thread
UnityMainThreadDispatcher.Instance.Enqueue(() => {
OnTeamDataFetchFailed?.Invoke(error);
});
// Optional REST fallback
if (connectionMethod == ConnectionMethod.RestFallbackIfNeeded && !string.IsNullOrWhiteSpace(firebaseProjectId))
{
Log("Attempting REST fallback after Firebase fetch faulted...");
StartCoroutine(FetchTeamDataRestCoroutine(uid));
}
}
else if (fetchTask.Result != null)
{
TeamData teamData = fetchTask.Result;
cachedTeamData = teamData;
isTeamDataLoaded = true;
Log($"✅ Team data fetched: {teamData.teamName}");
// Ensure UI updates happen on main thread
UnityMainThreadDispatcher.Instance.Enqueue(() => {
try
{
ShowVerificationPanel(teamData);
OnTeamDataFetched?.Invoke(teamData);
}
catch (System.Exception e)
{
LogError($"UI update error: {e.Message}");
}
});
}
else
{
LogError($"❌ Team not found: {uid}");
// Ensure UI updates happen on main thread
UnityMainThreadDispatcher.Instance.Enqueue(() => {
OnTeamDataFetchFailed?.Invoke($"Team not found: {uid}");
});
// Optional REST fallback if SDK returned not found
if (connectionMethod == ConnectionMethod.RestFallbackIfNeeded && !string.IsNullOrWhiteSpace(firebaseProjectId))
{
Log("Attempting REST fallback after 'not found' response...");
StartCoroutine(FetchTeamDataRestCoroutine(uid));
}
}
}
private async Task<TeamData> FetchTeamDataAsync(string uid)
{
try
{
DocumentReference teamDocRef = db.Collection("teams").Document(uid);
DocumentSnapshot teamSnapshot = await teamDocRef.GetSnapshotAsync();
if (teamSnapshot.Exists)
{
var data = teamSnapshot.ToDictionary();
TeamData teamData = new TeamData
{
uid = uid,
teamName = GetField(data, "teamName"),
teamNumber = GetIntField(data, "teamNumber"),
player1 = GetField(data, "player1"),
player2 = GetField(data, "player2"),
email = GetField(data, "email"),
score = GetIntField(data, "score")
};
return teamData;
}
return null;
}
catch (System.Exception e)
{
Log($"Firebase exception: {e.Message}");
throw;
}
}
// ---------------- REST FALLBACK ----------------
private IEnumerator FetchTeamDataRestCoroutine(string uid)
{
if (string.IsNullOrWhiteSpace(firebaseProjectId))
{
LogError("REST fallback requires a valid Firebase Project ID");
OnTeamDataFetchFailed?.Invoke("Configuration error: Project ID missing");
yield break;
}
string url = $"https://firestore.googleapis.com/v1/projects/{firebaseProjectId}/databases/(default)/documents/teams/{uid}";
Log($"[REST] GET {url}");
using (var request = UnityWebRequest.Get(url))
{
request.timeout = 15;
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
LogError($"[REST] Request failed: {request.error}");
OnTeamDataFetchFailed?.Invoke($"Network error: {request.error}");
yield break;
}
string json = request.downloadHandler.text;
if (logRestResponses) Log($"[REST] Response: {json}");
FirestoreDocument doc = null;
try
{
doc = JsonUtility.FromJson<FirestoreDocument>(json);
}
catch (Exception ex)
{
LogError($"[REST] JSON parse error: {ex.Message}");
}
if (doc == null || doc.fields == null)
{
LogError("[REST] Invalid document or missing fields");
OnTeamDataFetchFailed?.Invoke("Invalid server response");
yield break;
}
TeamData teamData = new TeamData
{
uid = !string.IsNullOrEmpty(doc.fields.uid?.stringValue) ? doc.fields.uid.stringValue : uid,
teamName = doc.fields.teamName?.stringValue ?? string.Empty,
teamNumber = ParseIntSafe(doc.fields.teamNumber?.integerValue),
player1 = doc.fields.player1?.stringValue ?? string.Empty,
player2 = doc.fields.player2?.stringValue ?? string.Empty,
email = doc.fields.email?.stringValue ?? string.Empty,
score = ParseIntSafe(doc.fields.score?.integerValue)
};
cachedTeamData = teamData;
isTeamDataLoaded = true;
// We are already on the main thread inside a coroutine
ShowVerificationPanel(teamData);
try
{
OnTeamDataFetched?.Invoke(teamData);
}
catch (Exception e)
{
LogError($"Event error: {e.Message}");
}
}
}
private int ParseIntSafe(string value)
{
if (string.IsNullOrEmpty(value)) return 0;
if (int.TryParse(value, out var result)) return result;
return 0;
}
// ---------------- REALTIME DATABASE (REST) ----------------
private IEnumerator FetchTeamDataRealtimeCoroutine(string uid)
{
// Expect schema: /26SIG/{uid} → TeamData-like fields
// Build URL: <base>/26SIG/<uid>.json[?auth=TOKEN]
string path = $"26SIG/{uid}.json";
string baseUrl = realtimeDatabaseBaseUrl?.TrimEnd('/');
if (string.IsNullOrWhiteSpace(baseUrl))
{
LogError("RTDB base URL missing");
OnTeamDataFetchFailed?.Invoke("Configuration error: RTDB URL missing");
yield break;
}
string url = $"{baseUrl}/{path}";
if (!string.IsNullOrWhiteSpace(realtimeDatabaseAuthToken))
{
url += (url.Contains("?") ? "&" : "?") + "auth=" + realtimeDatabaseAuthToken;
}
Log($"[RTDB] GET {url}");
using (var request = UnityWebRequest.Get(url))
{
request.timeout = 15;
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
LogError($"[RTDB] Request failed: {request.error}");
OnTeamDataFetchFailed?.Invoke($"Network error: {request.error}");
yield break;
}
string json = request.downloadHandler.text;
if (logRestResponses) Log($"[RTDB] Response: {json}");
// Parse minimal JSON fields without external packages
// Expected flat object or null
if (string.IsNullOrWhiteSpace(json) || json == "null")
{
LogError("[RTDB] Team not found");
OnTeamDataFetchFailed?.Invoke($"Team not found: {uid}");
yield break;
}
// Very lightweight JSON extraction
TeamData teamData = new TeamData
{
uid = ExtractJsonString(json, "uid") ?? uid,
teamName = ExtractJsonString(json, "teamName") ?? string.Empty,
teamNumber = ExtractJsonInt(json, "teamNumber"),
player1 = ExtractJsonString(json, "player1") ?? string.Empty,
player2 = ExtractJsonString(json, "player2") ?? string.Empty,
email = ExtractJsonString(json, "email") ?? string.Empty,
score = ExtractJsonInt(json, "score")
};
cachedTeamData = teamData;
isTeamDataLoaded = true;
ShowVerificationPanel(teamData);
try { OnTeamDataFetched?.Invoke(teamData); } catch (Exception e) { LogError($"Event error: {e.Message}"); }
}
}
private string ExtractJsonString(string json, string key)
{
// naive but robust for simple flat JSON: "key":"value"
try
{
string marker = $"\"{key}\"";
int idx = json.IndexOf(marker, StringComparison.Ordinal);
if (idx < 0) return null;
int colon = json.IndexOf(':', idx);
if (colon < 0) return null;
int firstQuote = json.IndexOf('"', colon + 1);
if (firstQuote < 0) return null;
int secondQuote = json.IndexOf('"', firstQuote + 1);
if (secondQuote < 0) return null;
return json.Substring(firstQuote + 1, secondQuote - firstQuote - 1);
}
catch { return null; }
}
private int ExtractJsonInt(string json, string key)
{
try
{
string marker = $"\"{key}\"";
int idx = json.IndexOf(marker, StringComparison.Ordinal);
if (idx < 0) return 0;
int colon = json.IndexOf(':', idx);
if (colon < 0) return 0;
int start = colon + 1;
// skip spaces
while (start < json.Length && char.IsWhiteSpace(json[start])) start++;
int end = start;
while (end < json.Length && (char.IsDigit(json[end]) || json[end] == '-')) end++;
var numStr = json.Substring(start, end - start);
if (int.TryParse(numStr, out var val)) return val;
return 0;
}
catch { return 0; }
}
[Serializable]
private class FirestoreDocument
{
public FirestoreFields fields;
}
[Serializable]
private class FirestoreFields
{
public FirestoreString teamName;
public FirestoreInteger teamNumber;
public FirestoreString uid;
public FirestoreString player1;
public FirestoreString player2;
public FirestoreString email;
public FirestoreInteger score;
}
[Serializable]
private class FirestoreString
{
public string stringValue;
}
[Serializable]
private class FirestoreInteger
{
public string integerValue;
}
private void ShowVerificationPanel(TeamData teamData)
{
if (verificationPanel == null || teamDetailsText == null)
{
Log("Verification panel not assigned - skipping");
return;
}
string displayText = $"Team Details:\n\n" +
$"Team Name: {teamData.teamName}\n" +
$"Team Number: {teamData.teamNumber}\n" +
$"Players: {teamData.player1} & {teamData.player2}\n" +
$"Email: {teamData.email}\n" +
$"UID: {teamData.uid}\n\n" +
$"Please verify this information is correct.";
teamDetailsText.text = displayText;
verificationPanel.SetActive(true);
}
private void OnVerifyTeamClicked()
{
Log("User verified team data");
if (verificationPanel != null)
{
verificationPanel.SetActive(false);
}
OnTeamVerified?.Invoke();
}
// Helper methods
private string GetField(System.Collections.Generic.IDictionary<string, object> data, string fieldName)
{
if (data.ContainsKey(fieldName) && data[fieldName] != null)
{
return data[fieldName].ToString();
}
return "";
}
private int GetIntField(System.Collections.Generic.IDictionary<string, object> data, string fieldName)
{
if (data.ContainsKey(fieldName) && data[fieldName] != null)
{
if (int.TryParse(data[fieldName].ToString(), out int result))
{
return result;
}
}
return 0;
}
public TeamData GetCachedTeamData()
{
return cachedTeamData;
}
public bool IsTeamDataLoaded()
{
return isTeamDataLoaded;
}
public bool IsFirebaseReady()
{
return isFirebaseReady;
}
// Returns whether a fetch can be attempted given current connection method and configuration
public bool IsFetchAvailable()
{
switch (connectionMethod)
{
case ConnectionMethod.RestOnly:
return !string.IsNullOrWhiteSpace(firebaseProjectId);
case ConnectionMethod.RestFallbackIfNeeded:
return (isFirebaseReady && db != null) || !string.IsNullOrWhiteSpace(firebaseProjectId);
case ConnectionMethod.DirectFirebaseOnly:
default:
return isFirebaseReady && db != null;
}
}
public void ClearCache()
{
cachedTeamData = null;
isTeamDataLoaded = false;
Log("Cache cleared");
}
private void Log(string message)
{
if (enableDebugLogs)
Debug.Log($"[FirebaseFetcher] {message}");
}
private void LogError(string message)
{
Debug.LogError($"[FirebaseFetcher] {message}");
}
void OnDestroy()
{
if (instance == this)
{
instance = null;
}
if (verifyTeamButton != null)
{
verifyTeamButton.onClick.RemoveListener(OnVerifyTeamClicked);
}
}
}