Exemple #1
0
    //public static void ChangeCurrentPlayerInBackend(string strUserId, string strPlayerId, PostUserCallback callback)
    //{
    //    auth.SignInWithEmailAndPasswordAsync(YipliHelper.userName, YipliHelper.password).ContinueWith(task =>
    //    {
    //        if (task.IsCanceled)
    //        {
    //            Debug.LogError("SignInAnonymouslyAsync was canceled.");
    //            return;
    //        }
    //        if (task.IsFaulted)
    //        {
    //            Debug.LogError("SignInAnonymouslyAsync encountered an error: " + task.Exception);
    //            return;
    //        }

    //        Firebase.Auth.FirebaseUser newUser = task.Result;
    //        Debug.LogFormat("User signed in successfully: {0} ({1})",
    //            newUser.DisplayName, newUser.UserId);

    //        //FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://yipli-project.firebaseio.com/");
    //        DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;

    //        reference.Child("profiles/users").Child(strUserId).Child("current-player-id").SetValueAsync(strPlayerId);
    //    });
    //}

    /* The function call to be allowed only if network is available */
    //public static async Task<DataSnapshot> GetGameData(string userId, string playerId, string gameId, PostUserCallback callback)
    //{
    //    DataSnapshot snapshot = null;
    //    if (userId.Equals(null) || playerId.Equals(null) || gameId.Equals(null))
    //    {
    //        Debug.Log("User ID not found");
    //    }
    //    else
    //    {
    //        try
    //        {
    //            Firebase.Auth.FirebaseUser newUser = await auth.SignInWithEmailAndPasswordAsync(YipliHelper.userName, YipliHelper.password);
    //            Debug.LogFormat("User signed in successfully: {0} ({1})",
    //            newUser.DisplayName, newUser.UserId);

    //            //FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://yipli-project.firebaseio.com/");
    //            DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;
    //            snapshot = await reference.Child("profiles/users/" + userId).Child("players").Child(playerId).Child("activity-statistics/games-statistics").Child(gameId).Child("game-data").GetValueAsync();
    //        }
    //        catch(Exception exp)
    //        {
    //            Debug.Log("Failed to GetGameData : " + exp.Message);
    //        }
    //    }
    //    return snapshot;
    //}

    /* The function call to be allowed only if network is available */
    //public static async Task<List<YipliPlayerInfo>> GetAllPlayerdetails(string userId, PostUserCallback callback)
    //{
    //    List<YipliPlayerInfo> players = new List<YipliPlayerInfo>();
    //    DataSnapshot snapshot = null;
    //    if (userId.Equals(null))
    //    {
    //        Debug.Log("User ID not found");
    //    }
    //    else
    //    {
    //        try
    //        {
    //            Firebase.Auth.FirebaseUser newUser = await auth.SignInWithEmailAndPasswordAsync(YipliHelper.userName, YipliHelper.password);
    //            Debug.LogFormat("User signed in successfully: {0} ({1})",
    //            newUser.DisplayName, newUser.UserId);

    //            //FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://yipli-project.firebaseio.com/");
    //            DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;
    //            snapshot = await reference.Child("profiles/users/" + userId).Child("players").GetValueAsync();

    //            foreach (var childSnapshot in snapshot.Children)
    //            {
    //                YipliPlayerInfo playerInstance = new YipliPlayerInfo(childSnapshot, childSnapshot.Key);
    //                if(playerInstance.playerId != null)
    //                {
    //                    players.Add(playerInstance);
    //                }
    //                else
    //                {
    //                    Debug.Log("Skipping this instance of player, backend seems corrupted.");
    //                }
    //            }
    //        }
    //        catch(Exception exp)
    //        {
    //            Debug.Log("Failed to GetAllPlayerdetails : " + exp.Message);
    //            return null;
    //        }
    //    }
    //    return players;
    //}

    ///* The function call to be allowed only if network is available */
    //public static async Task<YipliPlayerInfo> GetCurrentPlayerdetails(string userId, PostUserCallback callback)
    //{
    //    Debug.Log("Getting the Default player from backend");

    //    DataSnapshot snapshot = null;
    //    YipliPlayerInfo defaultPlayer = new YipliPlayerInfo();//Cant return null defaultPlayer. Initialze the default player.

    //    if (userId.Equals(null) || userId.Equals(""))
    //    {
    //        Debug.Log("User ID not found");
    //    }
    //    else
    //    {
    //        try
    //        {
    //            Firebase.Auth.FirebaseUser newUser = await auth.SignInWithEmailAndPasswordAsync(YipliHelper.userName, YipliHelper.password);
    //            Debug.LogFormat("User signed in successfully: {0} ({1})",
    //            newUser.DisplayName, newUser.UserId);

    //            //FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://yipli-project.firebaseio.com/");
    //            DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;

    //            //First get the current player id from user Id
    //            snapshot = await reference.Child("profiles/users").Child(userId).GetValueAsync();
    //            string playerId = snapshot.Child("current-player-id").Value?.ToString() ?? "";

    //            //Now get the complete player details from Player Id
    //            DataSnapshot defaultPlayerSnapshot = await reference.Child("profiles/users/" + userId + "/players/" + playerId).GetValueAsync();

    //            defaultPlayer = new YipliPlayerInfo(defaultPlayerSnapshot, defaultPlayerSnapshot.Key);

    //            if (defaultPlayer.playerId != null)
    //            {
    //                //Do Nothing
    //                Debug.Log("Found Default player : " + defaultPlayer.playerId);
    //            }
    //            else
    //            {
    //                //Case to handle if the default player object doesnt exist in backend/or is corrupted
    //                Debug.Log("Default Player Not found. Returning null.");
    //                return null;
    //            }
    //        }
    //        catch(Exception exp)
    //        {
    //            //If couldnt get defualt player details from the backend, return null.
    //            Debug.Log("Failed to GetAllPlayerdetails: " + exp.Message);
    //            return null;
    //        }
    //    }

    //    return defaultPlayer;
    //}


    // Mat related queries

    /* The function call to be allowed only if network is available */
    //public static async Task<YipliMatInfo> GetCurrentMatDetails(string userId, PostUserCallback callback)
    //{
    //    Debug.Log("Getting the Default mat from backend");
    //    DataSnapshot snapshot = null;
    //    YipliMatInfo defaultMat = new YipliMatInfo();

    //    if (userId.Equals(null) || userId.Equals(""))
    //    {
    //        Debug.Log("User ID not found");
    //    }
    //    else
    //    {
    //        try
    //        {
    //            Firebase.Auth.FirebaseUser newUser = await auth.SignInWithEmailAndPasswordAsync(YipliHelper.userName, YipliHelper.password);
    //            Debug.LogFormat("User signed in successfully: {0} ({1})",
    //            newUser.DisplayName, newUser.UserId);

    //            //FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://yipli-project.firebaseio.com/");
    //            DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;

    //            //First get the current mat id from user Id
    //            snapshot = await reference.Child("profiles/users").Child(userId).GetValueAsync();

    //            string matId = snapshot.Child("current-mat-id").Value?.ToString() ?? "";
    //            //Now get the complete player details from Player Id
    //            DataSnapshot defaultMatSnapshot = await reference.Child("profiles/users/" + userId + "/mats/" + matId).GetValueAsync();
    //            defaultMat = new YipliMatInfo(defaultMatSnapshot, defaultMatSnapshot.Key);

    //            if (defaultMat.matId != null)
    //            {
    //                //Do Nothing
    //                Debug.Log("Found Default mat : " + defaultMat.matId);
    //            }
    //            else
    //            {
    //                //Case to handle if the default mat object doesnt exist in backend/or is corrupted
    //                return null;
    //            }
    //        }
    //        catch(Exception exp)
    //        {
    //            Debug.Log("Failed to GetAllMatdetails : " + exp.Message);
    //            return null;
    //        }
    //    }
    //    return defaultMat;
    //}

    /* The function call to be allowed only if network is available */
    //public static async Task<List<YipliMatInfo>> GetAllMatDetails(string userId, PostUserCallback callback)
    //{
    //    List<YipliMatInfo> mats = new List<YipliMatInfo>();
    //    DataSnapshot snapshot = null;
    //    if (userId.Equals(null) || userId.Equals(""))
    //    {
    //        Debug.Log("User ID not found");
    //    }
    //    else
    //    {
    //        try
    //        {
    //            Firebase.Auth.FirebaseUser newUser = await auth.SignInWithEmailAndPasswordAsync(YipliHelper.userName, YipliHelper.password);
    //            Debug.LogFormat("User signed in successfully: {0} ({1})",
    //            newUser.DisplayName, newUser.UserId);

    //            //FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://yipli-project.firebaseio.com/");
    //            DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;
    //            snapshot = await reference.Child("profiles/users/" + userId + "/mats").GetValueAsync();

    //            foreach (var childSnapshot in snapshot.Children)
    //            {
    //                YipliMatInfo matInstance = new YipliMatInfo(childSnapshot, childSnapshot.Key);
    //                if(matInstance.matId != null)
    //                {
    //                    mats.Add(matInstance);
    //                }
    //                else
    //                {
    //                    Debug.Log("Skipping this instance of mat, backend seems corrupted.");
    //                }
    //            }
    //        }
    //        catch(Exception exp)
    //        {
    //            Debug.Log("Failed to GetAllPlayerdetails : " + exp.Message);
    //        }
    //    }
    //    return mats;
    //}


    /*
     * profilePicUrl : Player profile pic property stored already
     * onDeviceProfilePicPath : Path to store the image locally
     */
    public static async Task <Sprite> GetImageAsync(string profilePicUrl, string onDeviceProfilePicPath)
    {
        Debug.Log("Local path : " + onDeviceProfilePicPath);

        // Get a reference to the storage service, using the default Firebase App
        Firebase.Storage.StorageReference storage_ref = yipliStorage.GetReferenceFromUrl(profilePicRootUrl + profilePicUrl);

        Debug.Log("File download started.");

        try
        {
            // Start downloading a file and store it at local_url path
            await storage_ref.GetFileAsync(onDeviceProfilePicPath);

            byte[]    bytes   = System.IO.File.ReadAllBytes(onDeviceProfilePicPath);
            Texture2D texture = new Texture2D(1, 1);
            texture.LoadImage(bytes);
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));

            Debug.Log("Profile image downloaded.");
            return(sprite);
        }
        catch (Exception exp)
        {
            Debug.Log("Failed to download Profile image : " + exp.Message);
            return(null);
        }
    }
Exemple #2
0
    // Start is called before the first frame update
    void Start()
    {
#if UNITY_ANDROID
        assetReferance = storage.GetReferenceFromUrl(storageBaseURL + "/AssetBundles/Android/StandardPackages/Animals");
#endif
#if UNITY_IOS
        assetReferance = storage.GetReferenceFromUrl(storageBaseURL + "/AssetBundles/iOS/StandardPackages/Animals");
#endif

        StartCoroutine(UpdateUI());
    }
    // mp4 movie upload...  테스트 안 해봤음.
    IEnumerator UploadProcessByteBufferMP4Format()
    {
        yield return(new WaitForEndOfFrame());

        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;
        // Create a storage reference from our storage service
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://fir-authtest22.appspot.com");

        string local_file = "";

        if (Application.platform == RuntimePlatform.Android)
        {
            local_file = Application.persistentDataPath + "/" + fileName;
        }
        else
        {
            local_file = "C:/Users/Gana/Downloads/Test_imgs/" + fileName;
        }

        Firebase.Storage.StorageReference rivers_ref = storage_ref.Child("stuff/" + fileName);
        WWW www = new WWW("file:///" + local_file);

        while (!www.isDone)
        {
            yield return(null);
        }

        Texture2D tmpTexture = new Texture2D(www.texture.width, www.texture.height, TextureFormat.RGB24, false);

        tmpTexture.SetPixels(www.texture.GetPixels());
        tmpTexture.Apply();
        byte[] bytes = tmpTexture.EncodeToPNG();

        var TmpTask = rivers_ref.PutBytesAsync(bytes, null, new Firebase.Storage.StorageProgress <Firebase.Storage.UploadState>(state =>
        {
            Debug.Log(string.Format("Progress: {0} of {1} bytes transferred.", state.BytesTransferred, state.TotalByteCount));
            PercentView(state.BytesTransferred, state.TotalByteCount);
        }), System.Threading.CancellationToken.None, null).ContinueWith(task =>
        {
            Debug.Log(string.Format("OnClickUpload::IsCompleted:{0} IsCanceled:{1} IsFaulted:{2}", task.IsCompleted, task.IsCanceled, task.IsFaulted));

            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
                // Uh-oh, an error occurred!
            }
            else
            {
                // Metadata contains file metadata such as size, content-type, and download URL.
                Firebase.Storage.StorageMetadata metadata = task.Result;
                Debug.Log("Finished uploading...");
                //foreach (var entry in metadata.DownloadUrls)
                //    Debug.Log("download url = " + entry);
            }
        });

        yield return(new WaitUntil(() => TmpTask.IsCompleted));

        PrintState("uploading complete..");
    }
Exemple #4
0
    public void DownloadLanguageFile(string filePath, string version, Action successAction, Action errorAction, Action <float> updateAction, LoadingViewController loadingView)
    {
        languageFileSuccessCallback = successAction;
        languageFileErrorCallback   = errorAction;
        updateCallback = updateAction;

        languageFileVersion = version;
        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;
        // Points to the root reference
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://flickpool-84778.appspot.com/");

        Firebase.Storage.StorageReference file_ref = storage_ref.Child(filePath);

        file_ref.GetDownloadUrlAsync().ContinueWith((Task <Uri> task) => {
            if (!task.IsFaulted && !task.IsCanceled)
            {
                Debug.Log("Download URL: " + task.Result);
                loadingView.StartCoroutine(DownloadFile(task.Result.ToString(), Utility.GetPathForDownloadedLanguageFile()));
            }
            else
            {
                Debug.Log("error downloading");
                LanguageFileSyncFailed();
            }
        });
    }
    public void BuildTarget()
    {
        if (udt_FrameQuality == ImageTargetBuilder.FrameQuality.FRAME_QUALITY_HIGH)
        {
            udt_targetBuildingBehavior.BuildNewTarget(targetCounter.ToString(), targetBehavior.GetSize().x);

            Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;

            Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://ar-demo-1f5c9.appspot.com");

            Firebase.Storage.StorageReference file_ref = storage_ref.Child("images/" + FileControl.FilePath);

            file_ref.PutFileAsync("./Assets/Resources/" + FileControl.FilePath + ".txt").ContinueWith((Task <StorageMetadata> task) =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    Debug.Log("STILL HERE");
                    Debug.Log(task.Exception.ToString());
                    // Uh-oh, an error occurred!
                }
                else
                {
                    // Metadata contains file metadata such as size, content-type, and download URL.
                    Firebase.Storage.StorageMetadata metadata = task.Result;
                    //string download_url = metadata.DownloadUrl.ToString();
                    //Debug.Log("Finished uploading...");
                    //Debug.Log("download url = " + download_url);
                }
            });
        }
    }
    IEnumerator DeleteProcess()
    {
        yield return(new WaitForEndOfFrame());

        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;
        // Create a storage reference from our storage service
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://eduplatform-97d55.appspot.com/");
        // Create a reference to the file you want to upload
        Firebase.Storage.StorageReference rivers_ref = storage_ref.Child("ccc/" + fileName);                                                                         // 삭제하려는 파일의 레퍼런스...

        // Delete the file
        Task tmpTask = rivers_ref.DeleteAsync().ContinueWith(task => {
            if (task.IsCompleted)
            {
                Debug.Log("File deleted successfully.");
            }
            else
            {
                Debug.Log("error...");
            }
        });

        yield return(new WaitUntil(() => tmpTask.IsCompleted));

        PrintState("delete file complete");
    }
    IEnumerator AssetBudleDownloadLocal()                                                                               // 로컬 방식 다운로드..
    {
        bLoading = true;
        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;
        // Create a storage reference from our storage service
        //Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://fir-authtest22.appspot.com");
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://eduplatform-97d55.appspot.com/");
        // Create a reference to the file you want to upload
        Firebase.Storage.StorageReference rivers_ref = storage_ref.Child("AssetBundleTest1/" + assetBundleName);                            // 업로드 확인해야 함...

        string local_file = "";

        if (Application.platform == RuntimePlatform.Android)
        {
            if (!Directory.Exists(Application.persistentDataPath + "/" + "AssetBundle"))                                                    //폴더가 있는지 체크하고 없으면 만든다.
            {
                Directory.CreateDirectory(Application.persistentDataPath + "/" + "AssetBundle");
            }
            if (File.Exists(Application.persistentDataPath + "/" + "AssetBundle" + "/" + assetBundleName))
            {
                StartCoroutine(AssetBundleLoadFromLocal());                                                                                                 // 에셋번들 로드...
                yield break;
            }
            local_file = Application.persistentDataPath + "/" + "AssetBundle" + "/" + assetBundleName;
        }
        else
        {
            if (File.Exists("C:/Users/Gana/Downloads/AssetBundle/AssetBundle_PC" + "/" + assetBundleName))
            {
                StartCoroutine(AssetBundleLoadFromLocal());
                yield break;
            }
            local_file = "C:/Users/Gana/Downloads/AssetBundle/AssetBundle_PC" + "/" + assetBundleName;
        }

        Task TmpTask = rivers_ref.GetFileAsync(local_file, new Firebase.Storage.StorageProgress <Firebase.Storage.DownloadState>(state =>
        {
            // 다운로드 진행률....
            Debug.Log(string.Format("Progress: {0} of {1} bytes transferred.", state.BytesTransferred, state.TotalByteCount));
            PercentView(state.BytesTransferred, state.TotalByteCount);
        })).ContinueWith(task => {
            Debug.Log(string.Format("OnClickDownload::IsCompleted:{0} IsCanceled:{1} IsFaulted:{2}", task.IsCompleted, task.IsCanceled, task.IsFaulted));
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
                bLoading = false;
            }
            else
            {
                Debug.Log("Finished downloading...");
            }
        });

        yield return(new WaitUntil(() => TmpTask.IsCompleted));

        PrintState("Downloading Complete");
        StartCoroutine(AssetBundleLoadFromLocal());
    }
Exemple #8
0
    void OnDestroy()
    {
        // Write and save game data to .json file
        string saveText = JsonUtility.ToJson(listw);

        Debug.Log("readAler: " + saveText);

        string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");


        if (!Directory.Exists(out_folder))
        {
            Directory.CreateDirectory(out_folder);
        }

        if (!Directory.Exists(out_folder + gameObject.name + "/" + "pickup/"))
        {
            Directory.CreateDirectory(out_folder + gameObject.name + "/" + "pickup/");
        }

        string filename       = "pickup_" + datetime + ".json";
        string local_filepath = out_folder + gameObject.name + "/" + "pickup/" + filename;

        File.WriteAllText(local_filepath, saveText); // TODO @Matthew: This takes 2 arguments, the filepath and the json saveText var

        // Get a reference to Firebase cloud storage service
        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;

        // Create storage reference from our storage service bucket
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://unityoptics-eafc0.appspot.com");

        //  Create a reference to newly created .json file
        Firebase.Storage.StorageReference game_data_ref = storage_ref.Child(filename);

        // Create reference to 'gameData/filename'
        Firebase.Storage.StorageReference game_data_json_ref =
            storage_ref.Child("gameData/" + gameObject.name + "/" + "pickup/" + filename);

        // Upload Files to Cloud FireStore
        game_data_json_ref.PutFileAsync(local_filepath)
        .ContinueWith((System.Threading.Tasks.Task <StorageMetadata> task) => {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
                // Error Occured
            }
            else
            {
                //Metadata contains file metadata such as size, content-type, and download URL.
                Firebase.Storage.StorageMetadata metadata = task.Result;
                // string download_url = metadata.DownloadUrl.ToString();
                Debug.Log("Finished uploading...");
                // Debug.Log("download url = " + download_url);
            }
        });
    }
    IEnumerator DownloadCacheImgByBuffer()                                                                      // 이미지를 로컬에 저장하지 않고, cache 메모리에 저장 후 화면에 표시..
    {
        bool bError = false;

        byte[] fileContents2 = null;

        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;
        // Create a storage reference from our storage service
        //Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://fir-authtest22.appspot.com");
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://eduplatform-97d55.appspot.com/");
        // Create a reference to the file you want to upload
        Firebase.Storage.StorageReference rivers_ref = storage_ref.Child("ccc/" + fileName);

        // 최대 사이즈 지정할 수 있음..
        const long maxAllowedSize = 5 * 1024 * 1024;                                    // 최대사이즈 일단 5mb
        var        TmpTask        = rivers_ref.GetBytesAsync(maxAllowedSize, new Firebase.Storage.StorageProgress <Firebase.Storage.DownloadState>(state =>
        {
            // 다운로드 진행율 표시...
            Debug.Log(string.Format("Progress: {0} of {1} bytes transferred.", state.BytesTransferred, state.TotalByteCount));
            PercentView(state.BytesTransferred, state.TotalByteCount);
        })).ContinueWith((System.Threading.Tasks.Task <byte[]> task) => {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
                // Uh-oh, an error occurred!
                bError = true;
            }
            else if (task.IsCompleted)
            {
                Debug.Log("Finished downloading!");
                fileContents2 = task.Result;
                bError        = false;
            }
        });

        yield return(new WaitUntil(() => TmpTask.IsCompleted));

        if (false == bError)
        {
            Texture2D tmpTexture = new Texture2D(16, 16, TextureFormat.RGB24, false);
            bool      isLoaded   = tmpTexture.LoadImage(fileContents2);
            while (!isLoaded)
            {
                yield return(null);
            }

            tmpTexture.name = "tmpTexutre";
            rawImage.gameObject.SetActive(true);
            rawImage.texture = tmpTexture;
            PrintState("image view");
        }
        else if (true == bError)
        {
            PrintState("Error...");
        }
    }
Exemple #10
0
    public void clickUpload()
    {
        uploadPanel.SetActive(false);
        uploadStatus.SetActive(true);
        closeStatus.SetActive(false);

        status.text = "Sedang mempersiapkan file.";
        StartCoroutine(AnimateText());
        try {
            // Get a reference to the storage service, using the default Firebase App
            Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;

            // Create a storage reference from our storage service
            Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://buddhist-festival-ar-2018.appspot.com");

            // Create a child reference
            // images_ref now points to "images"
            Firebase.Storage.StorageReference images_ref = storage_ref.Child("Lomba Foto/" + PlayerPrefs.GetString("Nama", "") + "_" + PlayerPrefs.GetString("Telepon", "") + "/" + SaveLoad.imageName[activeIndex]);

            // Data in memory
            byte[] custom_bytes = SaveLoad.imageTexture[activeIndex].EncodeToPNG();

            status.text = "Sedang Meng-upload Foto";

            // Create file metadata including the content type
            //Firebase.Storage.MetadataChange new_metadata = new Firebase.Storage.MetadataChange();
            //new_metadata.ContentType = "image/png";

            // Upload the file to the path "images/rivers.jpg"
            images_ref.PutBytesAsync(custom_bytes)
            .ContinueWith((task) => {
                if (task.IsFaulted || task.IsCanceled)
                {
                    //status.text = "Gagal mengupload foto.\n Pesan error:\n"+ task.Exception.ToString();
                    status.text = "Gagal mengupload foto.";
                    isanimate   = false;
                    closeStatus.SetActive(true);
                    // Uh-oh, an error occurred!
                }
                else
                {
                    // Metadata contains file metadata such as size, content-type, and download URL.
                    //Firebase.Storage.StorageMetadata metadata = task.Result;
                    status.text = "Upload selesai. Terima kasih sudah berpartisipasi dalam lomba foto.";
                    isanimate   = false;
                    closeStatus.SetActive(true);
                }
            });
        } catch (System.Exception ex) {
            //status.text = "Gagal mengupload foto.\n Pesan error:\n"+ ex.ToString();
            status.text = "Gagal mengupload foto.";
            isanimate   = false;
            closeStatus.SetActive(true);
        }
    }
    // Use this for initialization
    void Start()
    {
        captureButton = GameObject.Find("Capture");
        errorText     = GameObject.Find("Error").GetComponent <Text>();

        // Get a reference to the storage service, using the default Firebase App
        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;

        // Create a storage reference from our storage service
        Firebase.Storage.StorageReference storage_ref =
            storage.GetReferenceFromUrl("gs://buddhist-festival-ar-2018.appspot.com");
    }
    // 파이어 베이스에서 내려받음....
    IEnumerator AssetBudleDownLoad(string _strUrl, string _strDir, string _strBundleName)
    {
        string assetBundleName = _strBundleName;

        bLoading = true;
        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;
        // Create a storage reference from our storage service
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://sohn123-f1d8d.appspot.com/");
        // Create a reference to the file you want to upload
        //Firebase.Storage.StorageReference rivers_ref = storage_ref.Child("AssetBundle/" + assetBundleName);                            // 업로드 확인해야 함...
        Firebase.Storage.StorageReference rivers_ref = storage_ref.Child(_strUrl);                                                                              // 업로드 확인해야 함...


        string local_file = "";

        if (Application.platform == RuntimePlatform.Android)
        {
            // 아래 수정 해야 함....
            if (!Directory.Exists(Application.persistentDataPath + "/AssetBundle/ " + _strDir))                                                    //폴더가 있는지 체크하고 없으면 만든다.
            {
                Directory.CreateDirectory(Application.persistentDataPath + "/AssetBundle/ " + _strDir);
            }
            local_file = Application.persistentDataPath + "/AssetBundle/" + _strDir + "/" + _strBundleName;
        }
        else
        {
            local_file = "C:/Users/Gana/Downloads/AssetBundle/" + _strDir + "/" + _strBundleName;                                                // PC ....
        }

        Task TmpTask = rivers_ref.GetFileAsync(local_file, new Firebase.Storage.StorageProgress <Firebase.Storage.DownloadState>(state =>
        {
            // 다운로드 진행률....
            //Debug.Log(string.Format("Progress: {0} of {1} bytes transferred.", state.BytesTransferred, state.TotalByteCount));
            PercentView(state.BytesTransferred, state.TotalByteCount);
        })).ContinueWith(task => {
            //Debug.Log(string.Format("OnClickDownload::IsCompleted:{0} IsCanceled:{1} IsFaulted:{2}", task.IsCompleted, task.IsCanceled, task.IsFaulted));
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
                bLoading = false;
            }
            else
            {
                //Debug.Log("Finished downloading...");
            }
        });

        yield return(new WaitUntil(() => TmpTask.IsCompleted));

        //PrintState("Downloading Complete");
        //StartCoroutine(AssetBundleLoadFromLocal());
        Debug.Log("Finished");
    }
Exemple #13
0
    public void NextOnClick()
    {
        byte[] image = texture.EncodeToPNG();

        website  = websiteField.GetComponent <Text>().text;
        facebook = facebookField.GetComponent <Text>().text;
        linkedIn = linkedInField.GetComponent <Text>().text;
        phone    = phoneField.GetComponent <Text>().text;

        string card_id = PlayerPrefs.GetString("card_id");

        if (!string.IsNullOrEmpty(card_id))
        {
            if (!string.IsNullOrEmpty(website) && !string.IsNullOrEmpty(facebook) && !string.IsNullOrEmpty(linkedIn) && !string.IsNullOrEmpty(phone))
            {
                storage          = Firebase.Storage.FirebaseStorage.DefaultInstance;
                storageReference = storage.GetReferenceFromUrl("gs://card-677f1.appspot.com/augment_images/");
                Firebase.Storage.StorageReference targetReference = storageReference.Child(authUser.UserId + card_id);
                databaseReference = FirebaseDatabase.DefaultInstance.RootReference;

                targetReference.PutBytesAsync(image)
                .ContinueWith((Task <StorageMetadata> task) => {
                    if (task.IsFaulted || task.IsCanceled)
                    {
                        Debug.Log(task.Exception.ToString());
                        // Uh-oh, an error occurred!
                    }
                    else
                    {
                        targetReference.GetDownloadUrlAsync().ContinueWith((Task <Uri> uriTask) =>
                        {
                            string download_url = uriTask.Result.ToString();
                            Debug.Log("Finished uploading...");
                            Debug.Log("download url = " + download_url);
                            DatabaseReference childReference = databaseReference.Child("cards").Child(card_id);
                            childReference.Child("website").SetValueAsync(website);
                            childReference.Child("facebook").SetValueAsync(facebook);
                            childReference.Child("linkedIn").SetValueAsync(linkedIn);
                            childReference.Child("phone").SetValueAsync(phone);
                            childReference.Child("photo").SetValueAsync(download_url);
                        });
                    }
                });

                SceneManager.LoadScene("HomeScene");
            }

            else
            {
                print("ERROR IN FIELDS");
            }
        }
    }
Exemple #14
0
    // Start is called before the first frame update
    void Start()
    {
        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;

        // Get the root reference location of the database.
        storage_ref = storage.GetReferenceFromUrl("gs://doodle-maze-2020.appspot.com");

        // Ensures members of this class can be accessed by other scripts in different scenes
        DontDestroyOnLoad(this.gameObject);

        // Disable screen dimming
        Screen.sleepTimeout = SleepTimeout.NeverSleep;
    }
    IEnumerator DownloadByBufferTxt()                                                                                  // 텍스트를 로컬에 저장하지 않고, cache 메모리에 저장 후 화면에 표시.. 한글은 UTF-8 만 가능.
    {
        bool bError = false;

        byte[] fileContents = null;

        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;
        // Create a storage reference from our storage service
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://eduplatform-97d55.appspot.com/");
        // Create a reference to the file you want to upload
        Firebase.Storage.StorageReference rivers_ref = storage_ref.Child("ccc/text_1.txt");

        // 최대 사이즈....
        const long maxAllowedSize = 2 * 1024 * 1024;    // 2mb
        var        TmpTask        = rivers_ref.GetBytesAsync(maxAllowedSize, new Firebase.Storage.StorageProgress <Firebase.Storage.DownloadState>(state =>
        {
            // 다운로드 진행율 표시...
            Debug.Log(string.Format("Progress: {0} of {1} bytes transferred.", state.BytesTransferred, state.TotalByteCount));
            PercentView(state.BytesTransferred, state.TotalByteCount);
        })).ContinueWith((System.Threading.Tasks.Task <byte[]> task) => {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
                // Uh-oh, an error occurred!
                bError = true;
            }
            else if (task.IsCompleted)
            {
                Debug.Log("Finished downloading!");
                fileContents = task.Result;
                bError       = false;
            }
        });

        yield return(new WaitUntil(() => TmpTask.IsCompleted));

        if (false == bError)
        {
            string testText = System.Text.Encoding.UTF8.GetString(fileContents);                                       // UTF8로 인코딩하여서 변환...
            PrintState("lyrics: " + testText);
        }
        else if (true == bError)
        {
            PrintState("Error...");
        }
    }
Exemple #16
0
    void Test()
    {
        Debug.Log("downloading image");
        Firebase.Storage.FirebaseStorage  storage     = Firebase.Storage.FirebaseStorage.DefaultInstance;
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://stargaze-embedded.appspot.com/image.jpg");

        // Create local filesystem URL
        string local_url = "file:///local/images/image.jpg";

        // Download to the local filesystem
        storage_ref.GetFileAsync(local_url).ContinueWith(task => {
            if (!task.IsFaulted && !task.IsCanceled)
            {
                Debug.Log("File downloaded.");
            }
        });
    }
    IEnumerator LocalDownloadXmlQuiz(string _fileName)
    {
        // test....
        fileName = _fileName;
        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;
        // Create a storage reference from our storage service
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://eduplatform-97d55.appspot.com/");                                         // 파이어베이스 계정에 할당된 주소...
        // Create a reference to the file you want to upload
        Firebase.Storage.StorageReference rivers_ref = storage_ref.Child("XmlFile_Chuncheon/" + fileName);                                                          // 하위 폴더...

        string local_file = "";

        // 경로 지정....
        if (Application.platform == RuntimePlatform.Android)
        {
            local_file = Application.persistentDataPath + "/" + fileName;                                           // android 의 접근 가능한 주소,, 폴더 추가 가능..
        }
        else
        {
            local_file = Application.streamingAssetsPath + "/" + fileName;
        }

        Task TmpTask = rivers_ref.GetFileAsync(local_file, new Firebase.Storage.StorageProgress <Firebase.Storage.DownloadState>(state =>
        {
            // 다운로드 진행율 표시...
            Debug.Log(string.Format("Progress: {0} of {1} bytes transferred.", state.BytesTransferred, state.TotalByteCount));
            //PercentView(state.BytesTransferred, state.TotalByteCount);
        })).ContinueWith(task => {
            Debug.Log(string.Format("OnClickDownload::IsCompleted:{0} IsCanceled:{1} IsFaulted:{2}", task.IsCompleted, task.IsCanceled, task.IsFaulted));
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
                // Uh-oh, an error occurred!
                Debug.Log("Oops,, Error..");
            }
            else
            {
                Debug.Log("Finished downloading...");
            }
        });

        yield return(new WaitUntil(() => TmpTask.IsCompleted));

        bXmlFileQuiz = true;
    }
Exemple #18
0
    void InitializeFirebase()
    {
        FirebaseApp app = FirebaseApp.DefaultInstance;

        app.SetEditorDatabaseUrl("https://vr-one-4e3bb.firebaseio.com/");

        // Get a reference to the storage service, using the default Firebase App
        storage = Firebase.Storage.FirebaseStorage.DefaultInstance;

        // Create a storage reference from our storage service
        storage_ref = storage.GetReferenceFromUrl("gs://vr-one-4e3bb.appspot.com/");
        //Firebase.Storage.StorageReference images_ref = storage_ref.Child ("map");
        screenshot_ref = storage_ref.Child("map/Screenshot.png");



        //items = new ArrayList();
    }
    // 로컬 다운로드...
    IEnumerator LocalDownloadStart()
    {
        // 로컬 방식....
        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;
        // Create a storage reference from our storage service
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://fir-authtest22.appspot.com");
        // Create a reference to the file you want to upload
        Firebase.Storage.StorageReference rivers_ref = storage_ref.Child("AssetBundleTest1/" + fileName);

        string local_file = "";

        if (Application.platform == RuntimePlatform.Android)
        {
            local_file = Application.persistentDataPath + "/" + fileName;                           // android 의 접근 가능한 주소,, 폴더 추가 가능..
        }
        else
        {
            local_file = "C:/Users/Gana/Downloads/AsssetBundle/" + fileName;
        }

        //var TmpTask = rivers_ref.GetFileAsync(local_file).ContinueWith(task => {
        var TmpTask = rivers_ref.GetFileAsync(local_file, new Firebase.Storage.StorageProgress <Firebase.Storage.DownloadState>(state =>
        {
            Debug.Log(string.Format("Progress: {0} of {1} bytes transferred.", state.BytesTransferred, state.TotalByteCount));
            PercentView(state.BytesTransferred, state.TotalByteCount);
        })).ContinueWith(task => {
            Debug.Log(string.Format("OnClickDownload::IsCompleted:{0} IsCanceled:{1} IsFaulted:{2}", task.IsCompleted, task.IsCanceled, task.IsFaulted));
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
                // Uh-oh, an error occurred!
                //authUI.ShowNotice("Error....");
                Debug.Log("Oops,, Error..");
            }
            else
            {
                Debug.Log("Finished downloading...");
            }
        });

        yield return(new WaitUntil(() => TmpTask.IsCompleted));

        PrintState("Finished downloading...");
    }
    //================================================= METADATA  ==================================================//
    // Storage 상의 메타데이터 추가 및 교체..
    public void MetadataChange()
    {
        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;
        // Create a storage reference from our storage service
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://fir-authtest22.appspot.com");
        // Create a reference to the file you want to upload
        Firebase.Storage.StorageReference rivers_ref = storage_ref.Child("Test1/test_arrow.png");

        var new_metadata = new Firebase.Storage.MetadataChange();

        //new_metadata.CacheControl = "public,max-age=300";
        new_metadata.ContentType = "image/png";
        // 아래처럼 Dictionary 활용하여서 추가할 수 있음..
        // Issue 사항은 추가되면 수정은 가능하지만 삭제가 불가능한 것 같음..

        /*
         * var new_metadata = new Firebase.Storage.MetadataChange
         * {
         *  CustomMetadata = new Dictionary<string, string>
         *  {
         *      {"story", "story for test" },
         *      {"tag", "hmm...." },
         *  }
         * };
         */
        // Update metadata properties
        Task tmpTask = rivers_ref.UpdateMetadataAsync(new_metadata).ContinueWith(task => {
            if (!task.IsFaulted && !task.IsCanceled)
            {
                // access the updated meta data
                Firebase.Storage.StorageMetadata meta = task.Result;
                Debug.Log("change..");
            }
        });
        //yield return new WaitUntil(() => tmpTask.IsCompleted);
        // do someting...
    }
    void UploadImage()
    {
        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;

        // Create a root reference
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl(firebaseStorageBucket);

        // File located on disk
        string local_file = localFilePath;

        // Create a reference to the file you want to upload
        Firebase.Storage.StorageReference image_ref = storage_ref.Child(remoteFilePath);

        // Upload the file to the path "images/rivers.jpg"
        image_ref.PutFileAsync(local_file)
        .ContinueWith((Task <StorageMetadata> task) => {
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
                // Uh-oh, an error occurred!
            }
            else
            {
                // Metadata contains file metadata such as size, content-type, and download URL.
                Firebase.Storage.StorageMetadata metadata = task.Result;
                string download_url = metadata.DownloadUrl.ToString();

                //fix the encoding problem
                string tempStr = remoteFilePath;
                downloadURL    = download_url.Replace(tempStr, remoteFilePath.Replace("/", "%2F"));

                Debug.Log("Finished uploading");
                //Debug.Log("download url = " + download_url);
            }
        });
    }
Exemple #22
0
    // 이전 씬에서 클릭한 버튼의 오브젝트 명을 토대로 데이터베이스로부터 설명하기 위한 값들을 받아옴.
    private void getData()
    {
        reference.Child("Database").GetValueAsync().ContinueWith(task =>
        {
            if (task.IsFaulted)
            {
                Debug.Log(task.Exception.Message);
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;

                urltext      = snapshot.Child(ReviewDatabase.namepass).Child("img").Value.ToString();
                gs_reference = storage.GetReferenceFromUrl(urltext);
                Debug.Log(gs_reference);
                parsing();

                foodname.text = snapshot.Child(ReviewDatabase.namepass).Child("name").Value.ToString();
                Debug.Log(snapshot.Child(ReviewDatabase.namepass).Child("name").Value.ToString());
                explain.text = snapshot.Child(ReviewDatabase.namepass).Child("explain").Value.ToString();
                recipe.text  = snapshot.Child(ReviewDatabase.namepass).Child("recipe").Value.ToString();
            }
        });
    }
Exemple #23
0
    public void saveRemember(Remember remember)
    {
        //Save Data Remember
        Dictionary <string, System.Object> entry = remember.ToDictionary();

        string rememberCode = dataReference.Push().Key;

        remember.SetCode(rememberCode);
        dataReference.Child(rememberCode).SetValueAsync(entry).ContinueWith((task) =>
        {
            if (task.IsCompleted)
            {
                Debug.Log("Data saved successfully!");
            }
            else
            {
            };
        });;


        //Save Media Data Remember
        GameObject mainCameraUI  = GameObject.Find(Util.ARCamera);
        GameObject buttonLoading = mainCameraUI.GetComponent <UIController>().buttonLoading;


        mainCameraUI.GetComponent <UIController>().buttonCancelMedia.SetActive(false);
        mainCameraUI.GetComponent <UIController>().buttonSaveMedia.SetActive(false);

        buttonLoading.SetActive(true);
        // Create a reference to the file you want to upload
        Firebase.Storage.FirebaseStorage  storage     = Firebase.Storage.FirebaseStorage.DefaultInstance;
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl(FirebaseUtil.ROOTNODE_STORAGE);
        Firebase.Storage.StorageReference rivers_ref  = storage_ref.Child(remember.GetCode() + ".jpeg");
        rivers_ref.PutBytesAsync(remember.GetMedia(), null, new Firebase.Storage.StorageProgress <Firebase.Storage.UploadState>(state =>
        {
            Debug.Log(string.Format("Progress: {0} of {1} bytes transferred.", state.BytesTransferred, state.TotalByteCount));
            decimal bytesTrasferred   = System.Convert.ToDecimal(state.BytesTransferred);
            decimal totalByteCount    = System.Convert.ToDecimal(state.TotalByteCount);
            decimal progress          = ((bytesTrasferred / totalByteCount) * 100);
            decimal progressLoadingUI = (progress / 100);

            buttonLoading.GetComponent <LoadingController>().progressFillImage(progressLoadingUI);
        }), System.Threading.CancellationToken.None, null).ContinueWith(task =>
        {
            Debug.Log(string.Format("OnClickUpload::IsCompleted:{0} IsCanceled:{1} IsFaulted:{2}", task.IsCompleted, task.IsCanceled, task.IsFaulted));
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
                // Uh-oh, an error occurred!
            }

            else
            {
                // Metadata contains file metadata such as size, content-type, and download URL.
                Firebase.Storage.StorageMetadata metadata = task.Result;
                GameObject buttonTimer = mainCameraUI.GetComponent <UIController>().buttonTimer;
                buttonTimer.gameObject.SetActive(true);


                if (remember.GetTypeMedia().Equals("Image"))
                {
                    GameObject rememberGO = Instantiate(Resources.Load <GameObject>("Prefabs/Remember/RememberPhoto"));
                    rememberGO.GetComponent <RememberPhotoController>().AddRemember(remember);
                    rememberGO.GetComponent <RememberPhotoController>().UpdateTexture();
                }
                else
                {
                    GameObject rememberGO = Instantiate(Resources.Load <GameObject>("Prefabs/Remember/RememberVideo"));
                    rememberGO.GetComponent <RememberVideoController>().AddRemember(remember);
                    rememberGO.GetComponent <RememberVideoController>().UpdateTexture();
                }
                Debug.Log("Finished uploading...");

                Destroy(this.gameObject);
            }
        });
    }
Exemple #24
0
    /*
     * Function that performs the following:
     *  1. Pulls input from the unity form
     *  2. Validates the input
     *  3. Attempts to authenticate the user with username/password using FirebaseAuth
     *  4. If the user is authenticated, a map is checked for at the location {app_url}/app_height_maps/{user_id}/mobile_height_map.raw"
     *      a. if the map is found, continues with game loop. Terrain will be build on next scene load.
     *      b. if map is not found, populates text box with error message
     *
     * TODO: For final product, the .raw height map might have an additional 20 bytes of position data that will need to be read to place the game objects.
     *
     */
    public async void StartAuthFlowAsync()
    {
        Debug.Log("Starting AuthFlow");

        // Get auth instance
        Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
        string email       = emailField.GetComponent <InputField>().text;
        string password    = passField.GetComponent <InputField>().text;
        bool   auth_result = false;

        // Validate input
        if (!ValidateEmailPass(email, password))
        {
            SetErrorTextBox(true, "Invalid Username/Password");
            return;
        }

        //attempt to sign the user in, wait to proceed
        await auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWith(task =>
        {
            if (task.IsCanceled)
            {
                Debug.LogError("SignInWithCustomTokenAsync was canceled.");
                return;
            }
            if (task.IsFaulted)
            {
                Debug.LogError("SignInWithCustomTokenAsync encountered an error: " + task.Exception);
                return;
            }
            curUser     = task.Result;
            auth_result = true;
        });

        //if the user was able to log in, continue with file download attempt
        if (curUser != null && auth_result)
        {
            const long maxSize = 3 * 1024 * 1024;                                      //3mb limit (1025x1025x16bit + 32 bytes position data map should always be ~ 2MB)
            string     path    = app_folder + "/" + curUser.UserId + "/" + file_name;; //{app_url}/app_height_maps/{userID}/mobile_height_map.raw

            // Get storage instance
            Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;
            string url = storage.RootReference + path;
            Firebase.Storage.StorageReference gs_reference = storage.GetReferenceFromUrl(url);

            // Download the .raw heightmap file
            await gs_reference.GetBytesAsync(maxSize).ContinueWith((Task <byte[]> task) =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    Debug.Log(task.Exception.ToString());
                    heightData = null;
                }
                else
                {
                    heightData = task.Result;
                    CheckForHighScore();
                }
            });

            if (heightData != null)
            {
                //something was able to be downloaded
                SetErrorTextBox(false);
                sceneLoader.GetComponent <SceneLoader>().LoadNextScene();
            }
            else
            {
                //file was unable to be downloaded
                SetErrorTextBox(true, "No heightmap available!");
            }
        }
        else
        {
            // problem authorizing the user
            SetErrorTextBox(true, "Authorization Failed!");
        }
    }
    // 로컬 방식 업로드 부분... 로컬 방식이기 때문에 모든 포멧이든 다 된다.
    IEnumerator UploadProcessLocal()
    {
        bool   bError = false;
        string bMsg   = "";

        PrintState("upload begin...");

        // Get a reference to the storage service, using the default Firebase App
        Firebase.Storage.FirebaseStorage storage = Firebase.Storage.FirebaseStorage.DefaultInstance;
        // Create a storage reference from our storage service
        Firebase.Storage.StorageReference storage_ref = storage.GetReferenceFromUrl("gs://eduplatform-97d55.appspot.com/");                          // FireaBase 계정의 address 적는 곳.
        // Create a reference to 'images/mountains.jpg'
        // While the file names are the same, the references point to different files
        //mountains_ref.Name == mountain_images_ref.Name; // true
        //mountains_ref.Path == mountain_images_ref.Path; // false

        string local_file = "";

        if (Application.platform == RuntimePlatform.Android)
        {
            local_file = "file:// " + Application.persistentDataPath + "/" + fileName;                        // android 휴대폰의 접근 가능한 로컬 주소
        }
        else
        {
            local_file = "C:/Users/Gana/Downloads/project_stuff/" + fileName;                               // pc 의 로컬 주소..
        }
        Firebase.Storage.StorageReference rivers_ref = storage_ref.Child("stuff/" + fileName);              // 스토리지에 레퍼런스 먼저 만들기..
        // metadata.. 추가할 것 이 있으면 추가,,, 필요 없을 시에 null 로..
        //var new_metadata = new Firebase.Storage.MetadataChange();
        //new_metadata.ContentType = "lyrics/text";
        // 메타데이터 추가시에....
        // Task TmpTask = rivers_ref.PutFileAsync(local_file, null, new Firebase.Storage.StorageProgress<Firebase.Storage.UploadState>(state =>

        Task TmpTask = rivers_ref.PutFileAsync(local_file, null, new Firebase.Storage.StorageProgress <Firebase.Storage.UploadState>(state =>
        {
            // Process 의 진행율을 보여주는 부분..
            Debug.Log(string.Format("Progress: {0} of {1} bytes transferred.", state.BytesTransferred, state.TotalByteCount));
            PercentView(state.BytesTransferred, state.TotalByteCount);
        }), System.Threading.CancellationToken.None, null).ContinueWith(task =>
        {
            Debug.Log(string.Format("OnClickUpload::IsCompleted:{0} IsCanceled:{1} IsFaulted:{2}", task.IsCompleted, task.IsCanceled, task.IsFaulted));
            if (task.IsFaulted || task.IsCanceled)
            {
                Debug.Log(task.Exception.ToString());
                // Uh-oh, an error occurred!
                bError = true;
                bMsg   = "error: " + task.Exception.ToString();
            }
            else if (task.IsCompleted)
            {
                // Metadata contains file metadata such as size, content-type, and download URL.
                Firebase.Storage.StorageMetadata metadata = task.Result;
                Debug.Log("Finished uploading...");
                bError = false;
            }
        });

        yield return(new WaitUntil(() => TmpTask.IsCompleted));              // 업로드가 완전히 완료된 후에 나머지를 처리한다.

        if (false == bError)
        {
            PrintState("upload complete...");
        }
        else if (true == bError)
        {
            PrintState(bMsg);
        }
    }
Exemple #26
0
 // Start is called before the first frame update
 void Start()
 {
     storage     = Firebase.Storage.FirebaseStorage.DefaultInstance;
     storage_ref = storage.GetReferenceFromUrl("gs://pare-58bd5.appspot.com");
 }
Exemple #27
0
 // Start is called before the first frame update
 void Start()
 {
     storage     = Firebase.Storage.FirebaseStorage.DefaultInstance;
     penguin_ref = storage.GetReferenceFromUrl("gs://pare-58bd5.appspot.com/Assets/AssetBundles/penguin1-Android");
 }