123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855 |
-
- using UnityEngine;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Text;
- using System.Net;
- namespace SimpleFirebaseUnity
- {
- using MiniJSON;
- [Serializable]
- public class FirebaseDatabase
- {
- const string SERVER_VALUE_TIMESTAMP = "{\".sv\": \"timestamp\"}";
- public Action<FirebaseDatabase, DataSnapshot> OnGetSuccess;
- public Action<FirebaseDatabase, FirebaseError> OnGetFailed;
- public Action<FirebaseDatabase, DataSnapshot> OnSetSuccess;
- public Action<FirebaseDatabase, FirebaseError> OnSetFailed;
- public Action<FirebaseDatabase, DataSnapshot> OnUpdateSuccess;
- public Action<FirebaseDatabase, FirebaseError> OnUpdateFailed;
- public Action<FirebaseDatabase, DataSnapshot> OnPushSuccess;
- public Action<FirebaseDatabase, FirebaseError> OnPushFailed;
- public Action<FirebaseDatabase, DataSnapshot> OnDeleteSuccess;
- public Action<FirebaseDatabase, FirebaseError> OnDeleteFailed;
- protected FirebaseDatabase parent;
- internal FirebaseRoot root;
- protected string key;
- protected string fullKey;
- #region GET-SET
- /// <summary>
- /// Parent of current firebase pointer
- /// </summary>
- public FirebaseDatabase Parent
- {
- get
- {
- return parent;
- }
- }
- /// <summary>
- /// Root firebase pointer of the endpoint
- /// </summary>
- public FirebaseDatabase Root
- {
- get
- {
- return root;
- }
- }
- /// <summary>
- /// Returns .json endpoint to this Firebase point
- /// </summary>
- public virtual string Endpoint
- {
- get
- {
- return "https://" + Host + FullKey + "/.json";
- }
- }
- /// <summary>
- /// Returns main host of Firebase
- /// </summary>
- public virtual string Host
- {
- get
- {
- return root.Host;
- }
- }
- /// <summary>
- /// Returns full key path to current pointer from root endpoint
- /// </summary>
- public string FullKey
- {
- get
- {
- return fullKey;
- }
- }
- /// <summary>
- /// Returns key of current pointer
- /// </summary>
- public string Key
- {
- get
- {
- return key;
- }
- }
- /// <summary>
- /// Credential for auth parameter. If no credential set to empty string
- /// </summary>
- public virtual string Credential
- {
- get
- {
- return root.Credential;
- }
- set
- {
- root.Credential = value;
- }
- }
- /// <summary>
- /// Gets the rules endpoint.
- /// </summary>
- /// <value>The rules endpoint.</value>
- public virtual string RulesEndpoint
- {
- get
- {
- return root.RulesEndpoint;
- }
- }
- /**** CONSTRUCTOR ****/
- /// <summary>
- /// Create new Firebase endpoint
- /// </summary>
- /// <param name="_parent">Parent Firebase pointer</param>
- /// <param name="_key">Key under parent Firebase</param>
- /// <param name="_root">Root Firebase pointer</param>
- /// <param name="inheritCallback">If set to <c>true</c> inherit callback.</param>
- internal FirebaseDatabase(FirebaseDatabase _parent, string _key, FirebaseRoot _root, bool inheritCallback = false)
- {
- parent = _parent;
- key = _key;
- root = _root;
- fullKey = parent.FullKey + "/" + key;
- if (inheritCallback)
- {
- OnGetSuccess = parent.OnGetSuccess;
- OnGetFailed = parent.OnGetFailed;
- OnSetSuccess = parent.OnSetSuccess;
- OnSetFailed = parent.OnSetFailed;
- OnUpdateSuccess = parent.OnUpdateSuccess;
- OnUpdateFailed = parent.OnUpdateFailed;
- OnPushSuccess = parent.OnPushSuccess;
- OnPushFailed = parent.OnPushFailed;
- OnDeleteSuccess = parent.OnDeleteSuccess;
- OnDeleteFailed = parent.OnDeleteFailed;
- }
- }
- internal FirebaseDatabase()
- {
- parent = null;
- key = string.Empty;
- root = null;
- }
- #endregion
- #region BASIC FUNCTIONS
- /// <summary>
- /// Get Firebase child from given key
- /// </summary>
- /// <param name="_key">A string</param>
- /// <param name="inheritCallback">If set to <c>true</c> inherit callback.</param>
- public FirebaseDatabase Child(string _key, bool inheritCallback = false)
- {
- return new FirebaseDatabase(this, _key, root, inheritCallback);
- }
- /// <summary>
- /// Get Firebase childs from given keys
- /// </summary>
- /// <param name="_keys">List of string</param>
- public List<FirebaseDatabase> Childs(List<string> _keys)
- {
- List<FirebaseDatabase> childs = new List<FirebaseDatabase>();
- foreach (string k in _keys)
- childs.Add(Child(k));
- return childs;
- }
- /// <summary>
- /// Get Firebase childs from given keys
- /// </summary>
- /// <param name="_keys">Array of string</param>
- public List<FirebaseDatabase> Childs(string[] _keys)
- {
- List<FirebaseDatabase> childs = new List<FirebaseDatabase>();
- foreach (string k in _keys)
- childs.Add(Child(k));
- return childs;
- }
- /// <summary>
- /// Get a fresh copy of this Firebase object
- /// </summary>
- /// <param name="inheritCallback">If set to <c>true</c> inherit callback.</param>
- public FirebaseDatabase Copy(bool inheritCallback = false)
- {
- FirebaseDatabase temp;
- if (parent == null)
- temp = root.Copy();
- else
- temp = new FirebaseDatabase(parent, key, root);
- if (inheritCallback)
- {
- temp.OnGetSuccess = OnGetSuccess;
- temp.OnGetFailed = OnGetFailed;
- temp.OnSetSuccess = OnSetSuccess;
- temp.OnSetFailed = OnSetFailed;
- temp.OnUpdateSuccess = OnUpdateSuccess;
- temp.OnUpdateFailed = OnUpdateFailed;
- temp.OnPushSuccess = OnPushSuccess;
- temp.OnPushFailed = OnPushFailed;
- temp.OnDeleteSuccess = OnDeleteSuccess;
- temp.OnDeleteFailed = OnDeleteFailed;
- }
- return temp;
- }
- #endregion
- #region REST FUNCTIONS
- /// <summary>
- /// Fetch data from Firebase. Calls OnGetSuccess on success, OnGetFailed on failed.
- /// OnGetSuccess action contains the corresponding Firebase and the fetched Snapshot
- /// OnGetFailed action contains the error exception
- /// </summary>
- /// <param name="query">REST call parameters wrapped in FirebaseQuery class</param>
- /// <returns></returns>
- public void GetValue(FirebaseParam query)
- {
- GetValue(query.Parameter);
- }
- /// <summary>
- /// Fetch data from Firebase. Calls OnGetSuccess on success, OnGetFailed on failed.
- /// OnGetSuccess action contains the corresponding Firebase and the fetched Snapshot
- /// OnGetFailed action contains the error exception
- /// </summary>
- /// <param name="param">REST call parameters on a string. Example: "orderBy=\"$key\""print=pretty"shallow=true"></param>
- /// <returns></returns>
- public void GetValue(string param = "")
- {
- try
- {
- if (Credential != "")
- {
- param = (new FirebaseParam(param).Auth(Credential)).Parameter;
- }
- string url = Endpoint;
- param = WWW.EscapeURL(param);
- if (param != "")
- url += "?" + param;
- root.StartCoroutine(RequestCoroutine(url, null, null, OnGetSuccess, OnGetFailed));
- }
- catch (WebException webEx)
- {
- if (OnGetFailed != null) OnGetFailed(this, FirebaseError.Create(webEx));
- }
- catch (Exception ex)
- {
- if (OnGetFailed != null) OnGetFailed(this, new FirebaseError(ex.Message));
- }
- }
- /// <summary>
- /// Set value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
- /// OnUpdateSuccess action contains the corresponding Firebase and the response Snapshot
- /// OnUpdateFailed action contains the error exception
- /// </summary>
- /// <param name="json">String</param>
- /// <param name="isJson">True if string is json (necessary to differentiate with the other overloading)</param>
- /// <param name="param">REST call parameters on a string. Example: "auth=ASDF123"</param>
- /// <returns></returns>
- public void SetValue(string json, bool isJson, string param = "")
- {
- if (!isJson)
- SetValue(json, param);
- else
- SetValue(Json.Deserialize(json), param);
- }
- /// <summary>
- /// Set value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
- /// OnSetSuccess action contains the corresponding Firebase and the response Snapshot
- /// OnSetFailed action contains the error exception
- /// </summary>
- /// <param name="_val">Set value</param>
- /// <param name="param">REST call parameters on a string. Example: "auth=ASDF123"</param>
- /// <returns></returns>
- public void SetValue(object _val, string param = "")
- {
- try
- {
- if (Credential != "")
- {
- param = (new FirebaseParam(param).Auth(Credential)).Parameter;
- }
- string url = Endpoint;
- param = WWW.EscapeURL(param);
- if (param != string.Empty)
- url += "?" + param;
- Dictionary<string, string> headers = new Dictionary<string, string>();
- headers.Add("Content-Type", "application/json");
- headers.Add("X-HTTP-Method-Override", "PUT");
- //UTF8Encoding encoding = new UTF8Encoding();
- byte[] bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(Json.Serialize(_val));
- root.StartCoroutine(RequestCoroutine(url, bytes, headers, OnSetSuccess, OnSetFailed));
- }
- catch (WebException webEx)
- {
- if (OnSetFailed != null) OnSetFailed(this, FirebaseError.Create(webEx));
- }
- catch (Exception ex)
- {
- if (OnSetFailed != null) OnSetFailed(this, new FirebaseError(ex.Message));
- }
- }
- /// <summary>
- /// Set value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
- /// OnSetSuccess action contains the corresponding Firebase and the response Snapshot
- /// OnSetFailed action contains the error exception
- /// </summary>
- /// <param name="json">String</param>
- /// <param name="isJson">True if string is json (necessary to differentiate the other overloading)</param>
- /// <param name="query">REST call parameters wrapped in FirebaseQuery class</param>
- /// <returns></returns>
- public void SetValue(string json, bool isJson, FirebaseParam query)
- {
- if (!isJson)
- SetValue(json, query.Parameter);
- else
- SetValue(Json.Deserialize(json), query.Parameter);
- }
- /// <summary>
- /// Set value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
- /// OnSetSuccess action contains the corresponding Firebase and the response Snapshot
- /// OnSetFailed action contains the error exception
- /// </summary>
- /// <param name="_val">Update value</param>
- /// <param name="query">REST call parameters wrapped in FirebaseQuery class</param>
- /// <returns></returns>
- public void SetValue(object _val, FirebaseParam query)
- {
- SetValue(_val, query.Parameter);
- }
- /// <summary>
- /// Update value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
- /// OnUpdateSuccess action contains the corresponding Firebase and the response Snapshot
- /// OnUpdateFailed action contains the error exception
- /// </summary>
- /// <param name="_val">Set value</param>
- /// <param name="param">REST call parameters on a string. Example: "auth=ASDF123"</param>
- /// <returns></returns>
- public void UpdateValue(object _val, string param = "")
- {
- try
- {
- if (!(_val is Dictionary<string, object>))
- {
- if (OnUpdateFailed != null)
- OnUpdateFailed(this, new FirebaseError((HttpStatusCode)400, "Invalid data; couldn't parse JSON object. Are you sending a JSON object with valid key names?"));
- return;
- }
- if (Credential != "")
- {
- param = (new FirebaseParam(param).Auth(Credential)).Parameter;
- }
- string url = Endpoint;
- param = WWW.EscapeURL(param);
- if (param != string.Empty)
- url += "?" + param;
- Dictionary<string, string> headers = new Dictionary<string, string>();
- headers.Add("Content-Type", "application/json");
- headers.Add("X-HTTP-Method-Override", "PATCH");
- //UTF8Encoding encoding = new UTF8Encoding();
- byte[] bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(Json.Serialize(_val));
- root.StartCoroutine(RequestCoroutine(url, bytes, headers, OnUpdateSuccess, OnUpdateFailed));
- }
- catch (WebException webEx)
- {
- if (OnUpdateFailed != null) OnUpdateFailed(this, FirebaseError.Create(webEx));
- }
- catch (Exception ex)
- {
- if (OnUpdateFailed != null) OnUpdateFailed(this, new FirebaseError(ex.Message));
- }
- }
- /// <summary>
- /// Update value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
- /// OnUpdateSuccess action contains the corresponding Firebase and the response Snapshot
- /// OnUpdateFailed action contains the error exception
- /// </summary>
- /// <param name="json">String</param>
- /// <param name="isJson">True if string is json (necessary to differentiate the other overloading)</param>
- /// <param name="query">REST call parameters wrapped in FirebaseQuery class</param>
- /// <returns></returns>
- public void UpdateValue(string json, bool isJson, FirebaseParam query)
- {
- if (!isJson)
- UpdateValue(json, query.Parameter);
- else
- UpdateValue(Json.Deserialize(json), query.Parameter);
- }
- /// <summary>
- /// Update value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
- /// OnUpdateSuccess action contains the corresponding Firebase and the response Snapshot
- /// OnUpdateFailed action contains the error exception
- /// </summary>
- /// <param name="_val">Update value</param>
- /// <param name="query">REST call parameters wrapped in FirebaseQuery class</param>
- /// <returns></returns>
- public void UpdateValue(object _val, FirebaseParam query)
- {
- UpdateValue(_val, query.Parameter);
- }
- /// <summary>
- /// Push a value (with random new key) on a key in Firebase. Calls OnPushSuccess on success, OnPushFailed on failed.
- /// OnPushSuccess action contains the corresponding Firebase and the response Snapshot
- /// OnPushFailed action contains the error exception
- /// </summary>
- /// <param name="json">String</param>
- /// <param name="isJson">True if string is json (necessary to differentiate with the other overloading)</param>
- /// <param name="param">REST call parameters on a string. Example: "auth=ASDF123"</param>
- /// <returns></returns>
- public void Push(string json, bool isJson, string param = "")
- {
- if (!isJson)
- Push(json, param);
- else
- Push(Json.Deserialize(json), param);
- }
- /// <summary>
- /// Update value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
- /// OnUpdateSuccess action contains the corresponding Firebase and the response Snapshot
- /// OnUpdateFailed action contains the error exception
- /// </summary>
- /// <param name="_val">New value</param>
- /// <param name="param">REST call parameters on a string. Example: "auth=ASDF123"</param>
- /// <returns></returns>
- public void Push(object _val, string param = "")
- {
- try
- {
- if (Credential != "")
- {
- param = (new FirebaseParam(param).Auth(Credential)).Parameter;
- }
- string url = Endpoint;
- param = WWW.EscapeURL(param);
- if (param != string.Empty)
- url += "?" + param;
- //UTF8Encoding encoding = new UTF8Encoding();
- byte[] bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(Json.Serialize(_val));
- root.StartCoroutine(RequestCoroutine(url, bytes, null, OnPushSuccess, OnPushFailed));
- }
- catch (WebException webEx)
- {
- if (OnPushFailed != null) OnPushFailed(this, FirebaseError.Create(webEx));
- }
- catch (Exception ex)
- {
- if (OnPushFailed != null) OnPushFailed(this, new FirebaseError(ex.Message));
- }
- }
- /// <summary>
- /// Push a value (with random new key) on a key in Firebase. Calls OnPushSuccess on success, OnPushFailed on failed.
- /// OnPushSuccess action contains the corresponding Firebase and the response Snapshot
- /// OnPushFailed action contains the error exception
- /// </summary>
- /// <param name="json">String</param>
- /// <param name="isJson">True if string is json (necessary to differentiate with the other overloading)</param>
- /// <param name="param">REST call parameters on a string. Example: "auth=ASDF123"</param>
- /// <returns></returns>
- public void Push(string json, bool isJson, FirebaseParam query)
- {
- if (!isJson)
- Push(json, query.Parameter);
- else
- Push(Json.Deserialize(json), query.Parameter);
- }
- /// <summary>
- /// Push a value (with random new key) on a key in Firebase. Calls OnPushSuccess on success, OnPushFailed on failed.
- /// OnPushSuccess action contains the corresponding Firebase and the response Snapshot
- /// OnPushFailed action contains the error exception
- /// </summary>
- /// <param name="_val">New value</param>
- /// <param name="query">REST call parameters wrapped in FirebaseQuery class</param>
- /// <returns></returns>
- public void Push(object _val, FirebaseParam query)
- {
- Push(_val, query.Parameter);
- }
- /// <summary>
- /// Delete a key in Firebase. Calls OnDeleteSuccess on success, OnDeleteFailed on failed.
- /// OnDeleteSuccess action contains the corresponding Firebase and the response Snapshot
- /// OnDeleteFailed action contains the error exception
- /// </summary>
- /// <param name="param">REST call parameters on a string. Example: "auth=ASDF123"</param>
- /// <returns></returns>
- public void Delete(string param = "")
- {
- try
- {
- if (Credential != "")
- {
- param = (new FirebaseParam(param).Auth(Credential)).Parameter;
- }
- string url = Endpoint;
- param = WWW.EscapeURL(param);
- if (param != string.Empty)
- url += "?" + param;
- Dictionary<string, string> headers = new Dictionary<string, string>();
- headers.Add("Content-Type", "application/json");
- headers.Add("X-HTTP-Method-Override", "DELETE");
- //UTF8Encoding encoding = new UTF8Encoding();
- byte[] bytes = Encoding.GetEncoding("iso-8859-1").GetBytes("{ \"dummy\" : \"dummies\"}");
- root.StartCoroutine(RequestCoroutine(url, bytes, headers, OnDeleteSuccess, OnDeleteFailed));
- }
- catch (WebException webEx)
- {
- if (OnDeleteFailed != null) OnDeleteFailed(this, FirebaseError.Create(webEx));
- }
- catch (Exception ex)
- {
- if (OnDeleteFailed != null) OnDeleteFailed(this, new FirebaseError(ex.Message));
- }
- }
- /// <summary>
- /// Delete a key in Firebase. Calls OnDeleteSuccess on success, OnDeleteFailed on failed.
- /// OnDeleteSuccess action contains the corresponding Firebase and the response Snapshot
- /// OnDeleteFailed action contains the error exception
- /// </summary>
- /// <param name="query">REST call parameters wrapped in FirebaseQuery class</param>
- /// <returns></returns>
- public void Delete(FirebaseParam query)
- {
- Delete(query.Parameter);
- }
- /// <summary>
- /// Sets the time stamp with the time since UNIX epoch by server value (in milliseconds).
- /// </summary>
- /// <param name="keyName">Key name.</param>
- public void SetTimeStamp(string keyName)
- {
- Child(keyName).SetValue(SERVER_VALUE_TIMESTAMP, true);
- }
- /// <summary>
- /// Sets the time stamp with the time since UNIX epoch by server value (in milliseconds).
- /// </summary>
- /// <param name="keyName">Key name.</param>
- /// <param name="OnSuccess">On success callback.</param>
- /// <param name="OnFailed">On fail callback.</param>
- public void SetTimeStamp(string keyName, Action<FirebaseDatabase, DataSnapshot> OnSuccess, Action<FirebaseDatabase, FirebaseError> OnFailed)
- {
- FirebaseDatabase temp = Child("");
- temp.OnSetSuccess += OnSuccess;
- temp.OnSetFailed += OnFailed;
- temp.SetValue(SERVER_VALUE_TIMESTAMP, true);
- }
- /// <summary>
- /// Gets Firebase Rules. Returned value is treated the same as returned value on Get request, packaged in DataSnapshot. Please note that FIREBASE_SECRET is required. If secret parameter is not set, it will use the Credential that has been set when CreateNew called.
- /// </summary>
- /// <param name="OnSuccess">On success callback.</param>
- /// <param name="OnFailed">On failed callback.</param>
- /// <param name="secret">Firebase Secret.</param>
- public void GetRules(Action<FirebaseDatabase, DataSnapshot> OnSuccess, Action<FirebaseDatabase, FirebaseError> OnFailed, string secret = "")
- {
- try
- {
- if (string.IsNullOrEmpty(secret))
- {
- if (!string.IsNullOrEmpty(Credential))
- secret = Credential;
- }
- string url = RulesEndpoint;
- url += "?auth=" + secret;
- root.StartCoroutine(RequestCoroutine(url, null, null, OnSuccess, OnFailed));
- }
- catch (WebException webEx)
- {
- if (OnFailed != null) OnFailed(this, FirebaseError.Create(webEx));
- }
- catch (Exception ex)
- {
- if (OnFailed != null) OnFailed(this, new FirebaseError(ex.Message));
- }
- }
- /// <summary>
- /// Sets Firebase Rules. Returned value is treated the same as returned value on Set request, packaged in DataSnapshot.Please note that FIREBASE_SECRET is required. If secret parameter is not set, it will use the Credential that has been set when CreateNew called.
- /// </summary>
- /// <param name="json">Valid rules Json.</param>
- /// <param name="OnSuccess">On success callback.</param>
- /// <param name="OnFailed">On failed callback.</param>
- /// <param name="secret">Firebase Secret.</param>
- public void SetRules(string json, Action<FirebaseDatabase, DataSnapshot> OnSuccess, Action<FirebaseDatabase, FirebaseError> OnFailed, string secret = "")
- {
- try
- {
- if (string.IsNullOrEmpty(secret))
- {
- if (!string.IsNullOrEmpty(Credential))
- secret = Credential;
- }
- string url = RulesEndpoint;
- url += "?auth=" + secret;
- Dictionary<string, string> headers = new Dictionary<string, string>();
- headers.Add("Content-Type", "application/json");
- headers.Add("X-HTTP-Method-Override", "PUT");
- //UTF8Encoding encoding = new UTF8Encoding();
- byte[] bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(json);
- root.StartCoroutine(RequestCoroutine(url, bytes, headers, OnSuccess, OnFailed));
- }
- catch (WebException webEx)
- {
- if (OnFailed != null) OnFailed(this, FirebaseError.Create(webEx));
- }
- catch (Exception ex)
- {
- if (OnFailed != null) OnFailed(this, new FirebaseError(ex.Message));
- }
- }
- /// <summary>
- /// Sets Firebase Rules silently. Please note that FIREBASE_SECRET is required. If secret parameter is not set, it will use the Credential that has been set when CreateNew called.
- /// </summary>
- /// <param name="json">Valid rules Json.</param>
- /// <param name="secret">Firebase Secret.</param>
- public void SetRules(string json, string secret = "")
- {
- SetRules(json, null, null, secret);
- }
- /// <summary>
- /// Sets Firebase Rules silently. Please note that FIREBASE_SECRET is required. If secret parameter is not set, it will use the Credential that has been set when CreateNew called.Sets the rules.
- /// </summary>
- /// <param name="rules">Valid rules that could be serialized into json.</param>
- /// <param name="OnSuccess">On success.</param>
- /// <param name="OnFailed">On failed.</param>
- /// <param name="secret">Firebase Secret.</param>
- public void SetRules(Dictionary<string, object> rules, Action<FirebaseDatabase, DataSnapshot> OnSuccess, Action<FirebaseDatabase, FirebaseError> OnFailed, string secret = "")
- {
- SetRules(Json.Serialize(rules), OnSuccess, OnFailed, secret);
- }
- /// <summary>
- /// Sets Firebase Rules silently. Please note that FIREBASE_SECRET is required. If secret parameter is not set, it will use the Credential that has been set when CreateNew called.Sets the rules.
- /// </summary>
- /// <param name="rules">Valid rules that could be serialized into json.</param>
- /// <param name="secret">Firebase Secret.</param>
- public void SetRules(Dictionary<string, object> rules, string secret = "")
- {
- SetRules(Json.Serialize(rules), null, null, secret);
- }
- #endregion
- #region REQUEST COROUTINE
- protected IEnumerator RequestCoroutine(string url, byte[] postData, Dictionary<string, string> headers, Action<FirebaseDatabase, DataSnapshot> OnSuccess, Action<FirebaseDatabase, FirebaseError> OnFailed)
- {
- using (WWW www = (headers != null) ? new WWW(url, postData, headers) : (postData != null) ? new WWW(url, postData) : new WWW(url))
- {
- // Wait until load done
- yield return www;
- if (!string.IsNullOrEmpty(www.error))
- {
- HttpStatusCode status = 0;
- string errMessage = "";
- // Parse status code
- if (www.responseHeaders.ContainsKey("STATUS"))
- {
- string str = www.responseHeaders["STATUS"] as string;
- string[] components = str.Split(' ');
- int code = 0;
- if (components.Length >= 3 && int.TryParse(components[1], out code))
- status = (HttpStatusCode)code;
- }
- if (www.error.Contains("crossdomain.xml") || www.error.Contains("Couldn't resolve"))
- {
- errMessage = "No internet connection or crossdomain.xml policy problem";
- }
- else {
- // Parse error message
- try
- {
- if (!string.IsNullOrEmpty(www.text))
- {
- Dictionary<string, object> obj = Json.Deserialize(www.text) as Dictionary<string, object>;
- if (obj != null && obj.ContainsKey("error"))
- errMessage = obj["error"] as string;
- }
- }
- catch
- {
- }
- }
- if (OnFailed != null)
- {
- if (string.IsNullOrEmpty(errMessage))
- errMessage = www.error;
- if (errMessage.Contains("Failed downloading"))
- {
- errMessage = "Request failed with no info of error.";
- }
- OnFailed(this, new FirebaseError(status, errMessage));
- }
- #if UNITY_EDITOR
- Debug.LogWarning(www.error + " (" + (int)status + ")\nResponse Message: " + errMessage);
- #endif
- }
- else
- {
- DataSnapshot snapshot = new DataSnapshot(www.text);
- if (OnSuccess != null) OnSuccess(this, snapshot);
- }
- }
- }
- #endregion
- #region STATIC FUNCTIONS
- /// <summary>
- /// Creates new Firebase pointer at a valid Firebase url
- /// </summary>
- /// <param name="host">Example: "hostname.firebaseio.com" (with no https://)</param>
- /// <param name="credential">Credential value for auth parameter</param>
- /// <returns></returns>
- public static FirebaseDatabase CreateNew(string host, string credential = "")
- {
- return new FirebaseRoot(host, credential);
- }
- /// <summary>
- /// Converts unix time stamp into DateTime
- /// </summary>
- /// <returns>The stamp to date time.</returns>
- /// <param name="unixTimeStamp">Unix time stamp.</param>
- public static DateTime TimeStampToDateTime(long unixTimeStamp)
- {
- DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
- dateTime = dateTime.AddMilliseconds(unixTimeStamp).ToLocalTime();
- return dateTime;
- }
- #endregion
- }
- }
|