using Firebase.Database; using Firebase.Extensions; using Firebase.Storage; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Policy; using System.Threading.Tasks; using UnityEditor; using UnityEngine; using UnityEngine.Networking; public class StorageManager : MonoBehaviour { public static StorageManager Instance; public CameraManager cameraManager; private StorageReference storage; private DatabaseReference realtimeDB; void Awake() { Instance = this; FirebaseInitializer.Instance.onFirebaseReady += Initialize; } void Initialize() { FirebaseInitializer.Instance.onFirebaseReady -= Initialize; storage = FirebaseStorage.DefaultInstance.RootReference; realtimeDB = FirebaseDatabase.DefaultInstance.RootReference; } public void DeleteFileOfRoom(Room _room, Action callBack_OnFinish) { List deleteTasks = new List(); foreach(Player player in _room.players.Values.ToList()) { foreach(Proposition proposition in _room.GetPropositionsForPlayer(player)) { if (proposition != null) { if(proposition.photoUrl != null) { Debug.Log($"Adding a task to delete {proposition.photoUrl}", this); deleteTasks.Add(Task.Run(async () => { string temp = proposition.photoUrl; StorageReference imageRef = FirebaseStorage.DefaultInstance.GetReferenceFromUrl(temp); Debug.Log($"deleting {temp}", this); await imageRef.DeleteAsync(); })); } } } } if(deleteTasks.Count > 0) { RunDeleteTasks(deleteTasks, callBack_OnFinish); } else { Debug.Log($"There is no files to delete for room {_room.code}", this); callBack_OnFinish.Invoke(); } } private void RunDeleteTasks(List deleteTasks, Action callback_OnFinish) { int taskCount = deleteTasks.Count; Debug.Log($"There are {taskCount} files to delete", this); Task.WhenAll(deleteTasks).ContinueWith(_ => { Debug.Log($"all delete tasks are done", this); callback_OnFinish?.Invoke(); }); } /* private IEnumerator RunDeleteTasks(List deleteTasks, Action callback_OnFinish) { int taskCount = deleteTasks.Count; Debug.Log($"There are {taskCount} files to delete", this); foreach (Task task in deleteTasks) { task.ContinueWith((completedTask) => { // This code will be executed when the task is completed. taskCount--; }); // Start the task task.Start(); } while (taskCount > 0) { yield return null; } callback_OnFinish?.Invoke(); } private Task DeletePhoto(string _gsURL) { string temp = _gsURL; StorageReference imageRef = FirebaseStorage.DefaultInstance.GetReferenceFromUrl(temp); Debug.Log($"deleting {temp}", this); return imageRef.DeleteAsync(); }*/ public void UploadPhoto(string roomCode, string playerId, int question, int proposition, Action callback_OnPhotoUploaded) { Texture2D photo = cameraManager.GetPhoto(); byte[] photoBytes = ImageConversion.EncodeToJPG(photo); string imageUuid = Guid.NewGuid().ToString(); string root = "gs://ggj2024-5cb41.appspot.com/"; string path = $"{roomCode}/{playerId}/{imageUuid}.png"; StorageReference imageRef = storage.Child(path); imageRef.PutBytesAsync(photoBytes).ContinueWithOnMainThread(task => { if (task.IsFaulted || task.IsCanceled) { callback_OnPhotoUploaded?.Invoke(false); Debug.LogException(task.Exception); // Uh-oh, an error occurred! } else { callback_OnPhotoUploaded?.Invoke(true); realtimeDB .Child("rooms") .Child(roomCode) .Child("questions") .Child(question.ToString()) .Child("propositions") .Child(proposition.ToString()) .Child("photoUrl") .SetValueAsync(root + path); } }); } public static IEnumerator DownloadImage_Coroutine(string _url, Action callback_OnTextureDownloaded) { UnityWebRequest request = UnityWebRequestTexture.GetTexture(_url); yield return request.SendWebRequest(); if (request.result != UnityWebRequest.Result.Success) { Debug.LogError(request.error); } else { callback_OnTextureDownloaded?.Invoke(((DownloadHandlerTexture)request.downloadHandler).texture); } } public static void ConvertGoogleStorageURLToHttpsUrl(string _gsURL, Action callback_OnURLFound) { StorageReference imageRef = FirebaseStorage.DefaultInstance.GetReferenceFromUrl(_gsURL); imageRef.GetDownloadUrlAsync().ContinueWithOnMainThread(task => { if (task.IsFaulted || task.IsCanceled) { Debug.LogException(task.Exception); } else { //Debug.Log("Image HTTPS URL: " + task.Result); callback_OnURLFound?.Invoke(task.Result.ToString()); } }); } }