FirebaseDatabase.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. 
  2. using UnityEngine;
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Text;
  7. using System.Net;
  8. namespace SimpleFirebaseUnity
  9. {
  10. using MiniJSON;
  11. [Serializable]
  12. public class FirebaseDatabase
  13. {
  14. const string SERVER_VALUE_TIMESTAMP = "{\".sv\": \"timestamp\"}";
  15. public Action<FirebaseDatabase, DataSnapshot> OnGetSuccess;
  16. public Action<FirebaseDatabase, FirebaseError> OnGetFailed;
  17. public Action<FirebaseDatabase, DataSnapshot> OnSetSuccess;
  18. public Action<FirebaseDatabase, FirebaseError> OnSetFailed;
  19. public Action<FirebaseDatabase, DataSnapshot> OnUpdateSuccess;
  20. public Action<FirebaseDatabase, FirebaseError> OnUpdateFailed;
  21. public Action<FirebaseDatabase, DataSnapshot> OnPushSuccess;
  22. public Action<FirebaseDatabase, FirebaseError> OnPushFailed;
  23. public Action<FirebaseDatabase, DataSnapshot> OnDeleteSuccess;
  24. public Action<FirebaseDatabase, FirebaseError> OnDeleteFailed;
  25. protected FirebaseDatabase parent;
  26. internal FirebaseRoot root;
  27. protected string key;
  28. protected string fullKey;
  29. #region GET-SET
  30. /// <summary>
  31. /// Parent of current firebase pointer
  32. /// </summary>
  33. public FirebaseDatabase Parent
  34. {
  35. get
  36. {
  37. return parent;
  38. }
  39. }
  40. /// <summary>
  41. /// Root firebase pointer of the endpoint
  42. /// </summary>
  43. public FirebaseDatabase Root
  44. {
  45. get
  46. {
  47. return root;
  48. }
  49. }
  50. /// <summary>
  51. /// Returns .json endpoint to this Firebase point
  52. /// </summary>
  53. public virtual string Endpoint
  54. {
  55. get
  56. {
  57. return "https://" + Host + FullKey + "/.json";
  58. }
  59. }
  60. /// <summary>
  61. /// Returns main host of Firebase
  62. /// </summary>
  63. public virtual string Host
  64. {
  65. get
  66. {
  67. return root.Host;
  68. }
  69. }
  70. /// <summary>
  71. /// Returns full key path to current pointer from root endpoint
  72. /// </summary>
  73. public string FullKey
  74. {
  75. get
  76. {
  77. return fullKey;
  78. }
  79. }
  80. /// <summary>
  81. /// Returns key of current pointer
  82. /// </summary>
  83. public string Key
  84. {
  85. get
  86. {
  87. return key;
  88. }
  89. }
  90. /// <summary>
  91. /// Credential for auth parameter. If no credential set to empty string
  92. /// </summary>
  93. public virtual string Credential
  94. {
  95. get
  96. {
  97. return root.Credential;
  98. }
  99. set
  100. {
  101. root.Credential = value;
  102. }
  103. }
  104. /// <summary>
  105. /// Gets the rules endpoint.
  106. /// </summary>
  107. /// <value>The rules endpoint.</value>
  108. public virtual string RulesEndpoint
  109. {
  110. get
  111. {
  112. return root.RulesEndpoint;
  113. }
  114. }
  115. /**** CONSTRUCTOR ****/
  116. /// <summary>
  117. /// Create new Firebase endpoint
  118. /// </summary>
  119. /// <param name="_parent">Parent Firebase pointer</param>
  120. /// <param name="_key">Key under parent Firebase</param>
  121. /// <param name="_root">Root Firebase pointer</param>
  122. /// <param name="inheritCallback">If set to <c>true</c> inherit callback.</param>
  123. internal FirebaseDatabase(FirebaseDatabase _parent, string _key, FirebaseRoot _root, bool inheritCallback = false)
  124. {
  125. parent = _parent;
  126. key = _key;
  127. root = _root;
  128. fullKey = parent.FullKey + "/" + key;
  129. if (inheritCallback)
  130. {
  131. OnGetSuccess = parent.OnGetSuccess;
  132. OnGetFailed = parent.OnGetFailed;
  133. OnSetSuccess = parent.OnSetSuccess;
  134. OnSetFailed = parent.OnSetFailed;
  135. OnUpdateSuccess = parent.OnUpdateSuccess;
  136. OnUpdateFailed = parent.OnUpdateFailed;
  137. OnPushSuccess = parent.OnPushSuccess;
  138. OnPushFailed = parent.OnPushFailed;
  139. OnDeleteSuccess = parent.OnDeleteSuccess;
  140. OnDeleteFailed = parent.OnDeleteFailed;
  141. }
  142. }
  143. internal FirebaseDatabase()
  144. {
  145. parent = null;
  146. key = string.Empty;
  147. root = null;
  148. }
  149. #endregion
  150. #region BASIC FUNCTIONS
  151. /// <summary>
  152. /// Get Firebase child from given key
  153. /// </summary>
  154. /// <param name="_key">A string</param>
  155. /// <param name="inheritCallback">If set to <c>true</c> inherit callback.</param>
  156. public FirebaseDatabase Child(string _key, bool inheritCallback = false)
  157. {
  158. return new FirebaseDatabase(this, _key, root, inheritCallback);
  159. }
  160. /// <summary>
  161. /// Get Firebase childs from given keys
  162. /// </summary>
  163. /// <param name="_keys">List of string</param>
  164. public List<FirebaseDatabase> Childs(List<string> _keys)
  165. {
  166. List<FirebaseDatabase> childs = new List<FirebaseDatabase>();
  167. foreach (string k in _keys)
  168. childs.Add(Child(k));
  169. return childs;
  170. }
  171. /// <summary>
  172. /// Get Firebase childs from given keys
  173. /// </summary>
  174. /// <param name="_keys">Array of string</param>
  175. public List<FirebaseDatabase> Childs(string[] _keys)
  176. {
  177. List<FirebaseDatabase> childs = new List<FirebaseDatabase>();
  178. foreach (string k in _keys)
  179. childs.Add(Child(k));
  180. return childs;
  181. }
  182. /// <summary>
  183. /// Get a fresh copy of this Firebase object
  184. /// </summary>
  185. /// <param name="inheritCallback">If set to <c>true</c> inherit callback.</param>
  186. public FirebaseDatabase Copy(bool inheritCallback = false)
  187. {
  188. FirebaseDatabase temp;
  189. if (parent == null)
  190. temp = root.Copy();
  191. else
  192. temp = new FirebaseDatabase(parent, key, root);
  193. if (inheritCallback)
  194. {
  195. temp.OnGetSuccess = OnGetSuccess;
  196. temp.OnGetFailed = OnGetFailed;
  197. temp.OnSetSuccess = OnSetSuccess;
  198. temp.OnSetFailed = OnSetFailed;
  199. temp.OnUpdateSuccess = OnUpdateSuccess;
  200. temp.OnUpdateFailed = OnUpdateFailed;
  201. temp.OnPushSuccess = OnPushSuccess;
  202. temp.OnPushFailed = OnPushFailed;
  203. temp.OnDeleteSuccess = OnDeleteSuccess;
  204. temp.OnDeleteFailed = OnDeleteFailed;
  205. }
  206. return temp;
  207. }
  208. #endregion
  209. #region REST FUNCTIONS
  210. /// <summary>
  211. /// Fetch data from Firebase. Calls OnGetSuccess on success, OnGetFailed on failed.
  212. /// OnGetSuccess action contains the corresponding Firebase and the fetched Snapshot
  213. /// OnGetFailed action contains the error exception
  214. /// </summary>
  215. /// <param name="query">REST call parameters wrapped in FirebaseQuery class</param>
  216. /// <returns></returns>
  217. public void GetValue(FirebaseParam query)
  218. {
  219. GetValue(query.Parameter);
  220. }
  221. /// <summary>
  222. /// Fetch data from Firebase. Calls OnGetSuccess on success, OnGetFailed on failed.
  223. /// OnGetSuccess action contains the corresponding Firebase and the fetched Snapshot
  224. /// OnGetFailed action contains the error exception
  225. /// </summary>
  226. /// <param name="param">REST call parameters on a string. Example: &quot;orderBy=&#92;"$key&#92;"&quot;print=pretty&quot;shallow=true"></param>
  227. /// <returns></returns>
  228. public void GetValue(string param = "")
  229. {
  230. try
  231. {
  232. if (Credential != "")
  233. {
  234. param = (new FirebaseParam(param).Auth(Credential)).Parameter;
  235. }
  236. string url = Endpoint;
  237. param = WWW.EscapeURL(param);
  238. if (param != "")
  239. url += "?" + param;
  240. root.StartCoroutine(RequestCoroutine(url, null, null, OnGetSuccess, OnGetFailed));
  241. }
  242. catch (WebException webEx)
  243. {
  244. if (OnGetFailed != null) OnGetFailed(this, FirebaseError.Create(webEx));
  245. }
  246. catch (Exception ex)
  247. {
  248. if (OnGetFailed != null) OnGetFailed(this, new FirebaseError(ex.Message));
  249. }
  250. }
  251. /// <summary>
  252. /// Set value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
  253. /// OnUpdateSuccess action contains the corresponding Firebase and the response Snapshot
  254. /// OnUpdateFailed action contains the error exception
  255. /// </summary>
  256. /// <param name="json">String</param>
  257. /// <param name="isJson">True if string is json (necessary to differentiate with the other overloading)</param>
  258. /// <param name="param">REST call parameters on a string. Example: "auth=ASDF123"</param>
  259. /// <returns></returns>
  260. public void SetValue(string json, bool isJson, string param = "")
  261. {
  262. if (!isJson)
  263. SetValue(json, param);
  264. else
  265. SetValue(Json.Deserialize(json), param);
  266. }
  267. /// <summary>
  268. /// Set value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
  269. /// OnSetSuccess action contains the corresponding Firebase and the response Snapshot
  270. /// OnSetFailed action contains the error exception
  271. /// </summary>
  272. /// <param name="_val">Set value</param>
  273. /// <param name="param">REST call parameters on a string. Example: "auth=ASDF123"</param>
  274. /// <returns></returns>
  275. public void SetValue(object _val, string param = "")
  276. {
  277. try
  278. {
  279. if (Credential != "")
  280. {
  281. param = (new FirebaseParam(param).Auth(Credential)).Parameter;
  282. }
  283. string url = Endpoint;
  284. param = WWW.EscapeURL(param);
  285. if (param != string.Empty)
  286. url += "?" + param;
  287. Dictionary<string, string> headers = new Dictionary<string, string>();
  288. headers.Add("Content-Type", "application/json");
  289. headers.Add("X-HTTP-Method-Override", "PUT");
  290. //UTF8Encoding encoding = new UTF8Encoding();
  291. byte[] bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(Json.Serialize(_val));
  292. root.StartCoroutine(RequestCoroutine(url, bytes, headers, OnSetSuccess, OnSetFailed));
  293. }
  294. catch (WebException webEx)
  295. {
  296. if (OnSetFailed != null) OnSetFailed(this, FirebaseError.Create(webEx));
  297. }
  298. catch (Exception ex)
  299. {
  300. if (OnSetFailed != null) OnSetFailed(this, new FirebaseError(ex.Message));
  301. }
  302. }
  303. /// <summary>
  304. /// Set value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
  305. /// OnSetSuccess action contains the corresponding Firebase and the response Snapshot
  306. /// OnSetFailed action contains the error exception
  307. /// </summary>
  308. /// <param name="json">String</param>
  309. /// <param name="isJson">True if string is json (necessary to differentiate the other overloading)</param>
  310. /// <param name="query">REST call parameters wrapped in FirebaseQuery class</param>
  311. /// <returns></returns>
  312. public void SetValue(string json, bool isJson, FirebaseParam query)
  313. {
  314. if (!isJson)
  315. SetValue(json, query.Parameter);
  316. else
  317. SetValue(Json.Deserialize(json), query.Parameter);
  318. }
  319. /// <summary>
  320. /// Set value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
  321. /// OnSetSuccess action contains the corresponding Firebase and the response Snapshot
  322. /// OnSetFailed action contains the error exception
  323. /// </summary>
  324. /// <param name="_val">Update value</param>
  325. /// <param name="query">REST call parameters wrapped in FirebaseQuery class</param>
  326. /// <returns></returns>
  327. public void SetValue(object _val, FirebaseParam query)
  328. {
  329. SetValue(_val, query.Parameter);
  330. }
  331. /// <summary>
  332. /// Update value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
  333. /// OnUpdateSuccess action contains the corresponding Firebase and the response Snapshot
  334. /// OnUpdateFailed action contains the error exception
  335. /// </summary>
  336. /// <param name="_val">Set value</param>
  337. /// <param name="param">REST call parameters on a string. Example: "auth=ASDF123"</param>
  338. /// <returns></returns>
  339. public void UpdateValue(object _val, string param = "")
  340. {
  341. try
  342. {
  343. if (!(_val is Dictionary<string, object>))
  344. {
  345. if (OnUpdateFailed != null)
  346. OnUpdateFailed(this, new FirebaseError((HttpStatusCode)400, "Invalid data; couldn't parse JSON object. Are you sending a JSON object with valid key names?"));
  347. return;
  348. }
  349. if (Credential != "")
  350. {
  351. param = (new FirebaseParam(param).Auth(Credential)).Parameter;
  352. }
  353. string url = Endpoint;
  354. param = WWW.EscapeURL(param);
  355. if (param != string.Empty)
  356. url += "?" + param;
  357. Dictionary<string, string> headers = new Dictionary<string, string>();
  358. headers.Add("Content-Type", "application/json");
  359. headers.Add("X-HTTP-Method-Override", "PATCH");
  360. //UTF8Encoding encoding = new UTF8Encoding();
  361. byte[] bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(Json.Serialize(_val));
  362. root.StartCoroutine(RequestCoroutine(url, bytes, headers, OnUpdateSuccess, OnUpdateFailed));
  363. }
  364. catch (WebException webEx)
  365. {
  366. if (OnUpdateFailed != null) OnUpdateFailed(this, FirebaseError.Create(webEx));
  367. }
  368. catch (Exception ex)
  369. {
  370. if (OnUpdateFailed != null) OnUpdateFailed(this, new FirebaseError(ex.Message));
  371. }
  372. }
  373. /// <summary>
  374. /// Update value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
  375. /// OnUpdateSuccess action contains the corresponding Firebase and the response Snapshot
  376. /// OnUpdateFailed action contains the error exception
  377. /// </summary>
  378. /// <param name="json">String</param>
  379. /// <param name="isJson">True if string is json (necessary to differentiate the other overloading)</param>
  380. /// <param name="query">REST call parameters wrapped in FirebaseQuery class</param>
  381. /// <returns></returns>
  382. public void UpdateValue(string json, bool isJson, FirebaseParam query)
  383. {
  384. if (!isJson)
  385. UpdateValue(json, query.Parameter);
  386. else
  387. UpdateValue(Json.Deserialize(json), query.Parameter);
  388. }
  389. /// <summary>
  390. /// Update value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
  391. /// OnUpdateSuccess action contains the corresponding Firebase and the response Snapshot
  392. /// OnUpdateFailed action contains the error exception
  393. /// </summary>
  394. /// <param name="_val">Update value</param>
  395. /// <param name="query">REST call parameters wrapped in FirebaseQuery class</param>
  396. /// <returns></returns>
  397. public void UpdateValue(object _val, FirebaseParam query)
  398. {
  399. UpdateValue(_val, query.Parameter);
  400. }
  401. /// <summary>
  402. /// Push a value (with random new key) on a key in Firebase. Calls OnPushSuccess on success, OnPushFailed on failed.
  403. /// OnPushSuccess action contains the corresponding Firebase and the response Snapshot
  404. /// OnPushFailed action contains the error exception
  405. /// </summary>
  406. /// <param name="json">String</param>
  407. /// <param name="isJson">True if string is json (necessary to differentiate with the other overloading)</param>
  408. /// <param name="param">REST call parameters on a string. Example: "auth=ASDF123"</param>
  409. /// <returns></returns>
  410. public void Push(string json, bool isJson, string param = "")
  411. {
  412. if (!isJson)
  413. Push(json, param);
  414. else
  415. Push(Json.Deserialize(json), param);
  416. }
  417. /// <summary>
  418. /// Update value of a key on Firebase. Calls OnUpdateSuccess on success, OnUpdateFailed on failed.
  419. /// OnUpdateSuccess action contains the corresponding Firebase and the response Snapshot
  420. /// OnUpdateFailed action contains the error exception
  421. /// </summary>
  422. /// <param name="_val">New value</param>
  423. /// <param name="param">REST call parameters on a string. Example: "auth=ASDF123"</param>
  424. /// <returns></returns>
  425. public void Push(object _val, string param = "")
  426. {
  427. try
  428. {
  429. if (Credential != "")
  430. {
  431. param = (new FirebaseParam(param).Auth(Credential)).Parameter;
  432. }
  433. string url = Endpoint;
  434. param = WWW.EscapeURL(param);
  435. if (param != string.Empty)
  436. url += "?" + param;
  437. //UTF8Encoding encoding = new UTF8Encoding();
  438. byte[] bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(Json.Serialize(_val));
  439. root.StartCoroutine(RequestCoroutine(url, bytes, null, OnPushSuccess, OnPushFailed));
  440. }
  441. catch (WebException webEx)
  442. {
  443. if (OnPushFailed != null) OnPushFailed(this, FirebaseError.Create(webEx));
  444. }
  445. catch (Exception ex)
  446. {
  447. if (OnPushFailed != null) OnPushFailed(this, new FirebaseError(ex.Message));
  448. }
  449. }
  450. /// <summary>
  451. /// Push a value (with random new key) on a key in Firebase. Calls OnPushSuccess on success, OnPushFailed on failed.
  452. /// OnPushSuccess action contains the corresponding Firebase and the response Snapshot
  453. /// OnPushFailed action contains the error exception
  454. /// </summary>
  455. /// <param name="json">String</param>
  456. /// <param name="isJson">True if string is json (necessary to differentiate with the other overloading)</param>
  457. /// <param name="param">REST call parameters on a string. Example: "auth=ASDF123"</param>
  458. /// <returns></returns>
  459. public void Push(string json, bool isJson, FirebaseParam query)
  460. {
  461. if (!isJson)
  462. Push(json, query.Parameter);
  463. else
  464. Push(Json.Deserialize(json), query.Parameter);
  465. }
  466. /// <summary>
  467. /// Push a value (with random new key) on a key in Firebase. Calls OnPushSuccess on success, OnPushFailed on failed.
  468. /// OnPushSuccess action contains the corresponding Firebase and the response Snapshot
  469. /// OnPushFailed action contains the error exception
  470. /// </summary>
  471. /// <param name="_val">New value</param>
  472. /// <param name="query">REST call parameters wrapped in FirebaseQuery class</param>
  473. /// <returns></returns>
  474. public void Push(object _val, FirebaseParam query)
  475. {
  476. Push(_val, query.Parameter);
  477. }
  478. /// <summary>
  479. /// Delete a key in Firebase. Calls OnDeleteSuccess on success, OnDeleteFailed on failed.
  480. /// OnDeleteSuccess action contains the corresponding Firebase and the response Snapshot
  481. /// OnDeleteFailed action contains the error exception
  482. /// </summary>
  483. /// <param name="param">REST call parameters on a string. Example: "auth=ASDF123"</param>
  484. /// <returns></returns>
  485. public void Delete(string param = "")
  486. {
  487. try
  488. {
  489. if (Credential != "")
  490. {
  491. param = (new FirebaseParam(param).Auth(Credential)).Parameter;
  492. }
  493. string url = Endpoint;
  494. param = WWW.EscapeURL(param);
  495. if (param != string.Empty)
  496. url += "?" + param;
  497. Dictionary<string, string> headers = new Dictionary<string, string>();
  498. headers.Add("Content-Type", "application/json");
  499. headers.Add("X-HTTP-Method-Override", "DELETE");
  500. //UTF8Encoding encoding = new UTF8Encoding();
  501. byte[] bytes = Encoding.GetEncoding("iso-8859-1").GetBytes("{ \"dummy\" : \"dummies\"}");
  502. root.StartCoroutine(RequestCoroutine(url, bytes, headers, OnDeleteSuccess, OnDeleteFailed));
  503. }
  504. catch (WebException webEx)
  505. {
  506. if (OnDeleteFailed != null) OnDeleteFailed(this, FirebaseError.Create(webEx));
  507. }
  508. catch (Exception ex)
  509. {
  510. if (OnDeleteFailed != null) OnDeleteFailed(this, new FirebaseError(ex.Message));
  511. }
  512. }
  513. /// <summary>
  514. /// Delete a key in Firebase. Calls OnDeleteSuccess on success, OnDeleteFailed on failed.
  515. /// OnDeleteSuccess action contains the corresponding Firebase and the response Snapshot
  516. /// OnDeleteFailed action contains the error exception
  517. /// </summary>
  518. /// <param name="query">REST call parameters wrapped in FirebaseQuery class</param>
  519. /// <returns></returns>
  520. public void Delete(FirebaseParam query)
  521. {
  522. Delete(query.Parameter);
  523. }
  524. /// <summary>
  525. /// Sets the time stamp with the time since UNIX epoch by server value (in milliseconds).
  526. /// </summary>
  527. /// <param name="keyName">Key name.</param>
  528. public void SetTimeStamp(string keyName)
  529. {
  530. Child(keyName).SetValue(SERVER_VALUE_TIMESTAMP, true);
  531. }
  532. /// <summary>
  533. /// Sets the time stamp with the time since UNIX epoch by server value (in milliseconds).
  534. /// </summary>
  535. /// <param name="keyName">Key name.</param>
  536. /// <param name="OnSuccess">On success callback.</param>
  537. /// <param name="OnFailed">On fail callback.</param>
  538. public void SetTimeStamp(string keyName, Action<FirebaseDatabase, DataSnapshot> OnSuccess, Action<FirebaseDatabase, FirebaseError> OnFailed)
  539. {
  540. FirebaseDatabase temp = Child("");
  541. temp.OnSetSuccess += OnSuccess;
  542. temp.OnSetFailed += OnFailed;
  543. temp.SetValue(SERVER_VALUE_TIMESTAMP, true);
  544. }
  545. /// <summary>
  546. /// 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.
  547. /// </summary>
  548. /// <param name="OnSuccess">On success callback.</param>
  549. /// <param name="OnFailed">On failed callback.</param>
  550. /// <param name="secret">Firebase Secret.</param>
  551. public void GetRules(Action<FirebaseDatabase, DataSnapshot> OnSuccess, Action<FirebaseDatabase, FirebaseError> OnFailed, string secret = "")
  552. {
  553. try
  554. {
  555. if (string.IsNullOrEmpty(secret))
  556. {
  557. if (!string.IsNullOrEmpty(Credential))
  558. secret = Credential;
  559. }
  560. string url = RulesEndpoint;
  561. url += "?auth=" + secret;
  562. root.StartCoroutine(RequestCoroutine(url, null, null, OnSuccess, OnFailed));
  563. }
  564. catch (WebException webEx)
  565. {
  566. if (OnFailed != null) OnFailed(this, FirebaseError.Create(webEx));
  567. }
  568. catch (Exception ex)
  569. {
  570. if (OnFailed != null) OnFailed(this, new FirebaseError(ex.Message));
  571. }
  572. }
  573. /// <summary>
  574. /// 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.
  575. /// </summary>
  576. /// <param name="json">Valid rules Json.</param>
  577. /// <param name="OnSuccess">On success callback.</param>
  578. /// <param name="OnFailed">On failed callback.</param>
  579. /// <param name="secret">Firebase Secret.</param>
  580. public void SetRules(string json, Action<FirebaseDatabase, DataSnapshot> OnSuccess, Action<FirebaseDatabase, FirebaseError> OnFailed, string secret = "")
  581. {
  582. try
  583. {
  584. if (string.IsNullOrEmpty(secret))
  585. {
  586. if (!string.IsNullOrEmpty(Credential))
  587. secret = Credential;
  588. }
  589. string url = RulesEndpoint;
  590. url += "?auth=" + secret;
  591. Dictionary<string, string> headers = new Dictionary<string, string>();
  592. headers.Add("Content-Type", "application/json");
  593. headers.Add("X-HTTP-Method-Override", "PUT");
  594. //UTF8Encoding encoding = new UTF8Encoding();
  595. byte[] bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(json);
  596. root.StartCoroutine(RequestCoroutine(url, bytes, headers, OnSuccess, OnFailed));
  597. }
  598. catch (WebException webEx)
  599. {
  600. if (OnFailed != null) OnFailed(this, FirebaseError.Create(webEx));
  601. }
  602. catch (Exception ex)
  603. {
  604. if (OnFailed != null) OnFailed(this, new FirebaseError(ex.Message));
  605. }
  606. }
  607. /// <summary>
  608. /// 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.
  609. /// </summary>
  610. /// <param name="json">Valid rules Json.</param>
  611. /// <param name="secret">Firebase Secret.</param>
  612. public void SetRules(string json, string secret = "")
  613. {
  614. SetRules(json, null, null, secret);
  615. }
  616. /// <summary>
  617. /// 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.
  618. /// </summary>
  619. /// <param name="rules">Valid rules that could be serialized into json.</param>
  620. /// <param name="OnSuccess">On success.</param>
  621. /// <param name="OnFailed">On failed.</param>
  622. /// <param name="secret">Firebase Secret.</param>
  623. public void SetRules(Dictionary<string, object> rules, Action<FirebaseDatabase, DataSnapshot> OnSuccess, Action<FirebaseDatabase, FirebaseError> OnFailed, string secret = "")
  624. {
  625. SetRules(Json.Serialize(rules), OnSuccess, OnFailed, secret);
  626. }
  627. /// <summary>
  628. /// 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.
  629. /// </summary>
  630. /// <param name="rules">Valid rules that could be serialized into json.</param>
  631. /// <param name="secret">Firebase Secret.</param>
  632. public void SetRules(Dictionary<string, object> rules, string secret = "")
  633. {
  634. SetRules(Json.Serialize(rules), null, null, secret);
  635. }
  636. #endregion
  637. #region REQUEST COROUTINE
  638. protected IEnumerator RequestCoroutine(string url, byte[] postData, Dictionary<string, string> headers, Action<FirebaseDatabase, DataSnapshot> OnSuccess, Action<FirebaseDatabase, FirebaseError> OnFailed)
  639. {
  640. using (WWW www = (headers != null) ? new WWW(url, postData, headers) : (postData != null) ? new WWW(url, postData) : new WWW(url))
  641. {
  642. // Wait until load done
  643. yield return www;
  644. if (!string.IsNullOrEmpty(www.error))
  645. {
  646. HttpStatusCode status = 0;
  647. string errMessage = "";
  648. // Parse status code
  649. if (www.responseHeaders.ContainsKey("STATUS"))
  650. {
  651. string str = www.responseHeaders["STATUS"] as string;
  652. string[] components = str.Split(' ');
  653. int code = 0;
  654. if (components.Length >= 3 && int.TryParse(components[1], out code))
  655. status = (HttpStatusCode)code;
  656. }
  657. if (www.error.Contains("crossdomain.xml") || www.error.Contains("Couldn't resolve"))
  658. {
  659. errMessage = "No internet connection or crossdomain.xml policy problem";
  660. }
  661. else {
  662. // Parse error message
  663. try
  664. {
  665. if (!string.IsNullOrEmpty(www.text))
  666. {
  667. Dictionary<string, object> obj = Json.Deserialize(www.text) as Dictionary<string, object>;
  668. if (obj != null && obj.ContainsKey("error"))
  669. errMessage = obj["error"] as string;
  670. }
  671. }
  672. catch
  673. {
  674. }
  675. }
  676. if (OnFailed != null)
  677. {
  678. if (string.IsNullOrEmpty(errMessage))
  679. errMessage = www.error;
  680. if (errMessage.Contains("Failed downloading"))
  681. {
  682. errMessage = "Request failed with no info of error.";
  683. }
  684. OnFailed(this, new FirebaseError(status, errMessage));
  685. }
  686. #if UNITY_EDITOR
  687. Debug.LogWarning(www.error + " (" + (int)status + ")\nResponse Message: " + errMessage);
  688. #endif
  689. }
  690. else
  691. {
  692. DataSnapshot snapshot = new DataSnapshot(www.text);
  693. if (OnSuccess != null) OnSuccess(this, snapshot);
  694. }
  695. }
  696. }
  697. #endregion
  698. #region STATIC FUNCTIONS
  699. /// <summary>
  700. /// Creates new Firebase pointer at a valid Firebase url
  701. /// </summary>
  702. /// <param name="host">Example: "hostname.firebaseio.com" (with no https://)</param>
  703. /// <param name="credential">Credential value for auth parameter</param>
  704. /// <returns></returns>
  705. public static FirebaseDatabase CreateNew(string host, string credential = "")
  706. {
  707. return new FirebaseRoot(host, credential);
  708. }
  709. /// <summary>
  710. /// Converts unix time stamp into DateTime
  711. /// </summary>
  712. /// <returns>The stamp to date time.</returns>
  713. /// <param name="unixTimeStamp">Unix time stamp.</param>
  714. public static DateTime TimeStampToDateTime(long unixTimeStamp)
  715. {
  716. DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
  717. dateTime = dateTime.AddMilliseconds(unixTimeStamp).ToLocalTime();
  718. return dateTime;
  719. }
  720. #endregion
  721. }
  722. }