SampleScript.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. using UnityEngine;
  2. using SimpleFirebaseUnity;
  3. using SimpleFirebaseUnity.MiniJSON;
  4. using System.Collections.Generic;
  5. using System.Collections;
  6. using System;
  7. public class SampleScript : MonoBehaviour
  8. {
  9. static int debug_idx = 0;
  10. [SerializeField]
  11. TextMesh textMesh;
  12. // Use this for initialization
  13. void Start()
  14. {
  15. textMesh.text = "";
  16. StartCoroutine (Tests ());
  17. }
  18. void GetOKHandler(FirebaseDatabase sender, DataSnapshot snapshot)
  19. {
  20. DoDebug("[OK] Get from key: <" + sender.FullKey + ">");
  21. DoDebug("[OK] Raw Json: " + snapshot.RawJson);
  22. Dictionary<string, object> dict = snapshot.Value<Dictionary<string, object>>();
  23. List<string> keys = snapshot.Keys;
  24. if (keys != null)
  25. foreach (string key in keys)
  26. {
  27. DoDebug(key + " = " + dict[key].ToString());
  28. }
  29. }
  30. void GetFailHandler(FirebaseDatabase sender, FirebaseError err)
  31. {
  32. DoDebug("[ERR] Get from key: <" + sender.FullKey + ">, " + err.Message + " (" + (int)err.Status + ")");
  33. }
  34. void SetOKHandler(FirebaseDatabase sender, DataSnapshot snapshot)
  35. {
  36. DoDebug("[OK] Set from key: <" + sender.FullKey + ">");
  37. }
  38. void SetFailHandler(FirebaseDatabase sender, FirebaseError err)
  39. {
  40. DoDebug("[ERR] Set from key: <" + sender.FullKey + ">, " + err.Message + " (" + (int)err.Status + ")");
  41. }
  42. void UpdateOKHandler(FirebaseDatabase sender, DataSnapshot snapshot)
  43. {
  44. DoDebug("[OK] Update from key: <" + sender.FullKey + ">");
  45. }
  46. void UpdateFailHandler(FirebaseDatabase sender, FirebaseError err)
  47. {
  48. DoDebug("[ERR] Update from key: <" + sender.FullKey + ">, " + err.Message + " (" + (int)err.Status + ")");
  49. }
  50. void DelOKHandler(FirebaseDatabase sender, DataSnapshot snapshot)
  51. {
  52. DoDebug("[OK] Del from key: <" + sender.FullKey + ">");
  53. }
  54. void DelFailHandler(FirebaseDatabase sender, FirebaseError err)
  55. {
  56. DoDebug("[ERR] Del from key: <" + sender.FullKey + ">, " + err.Message + " (" + (int)err.Status + ")");
  57. }
  58. void PushOKHandler(FirebaseDatabase sender, DataSnapshot snapshot)
  59. {
  60. DoDebug("[OK] Push from key: <" + sender.FullKey + ">");
  61. }
  62. void PushFailHandler(FirebaseDatabase sender, FirebaseError err)
  63. {
  64. DoDebug("[ERR] Push from key: <" + sender.FullKey + ">, " + err.Message + " (" + (int)err.Status + ")");
  65. }
  66. void GetRulesOKHandler(FirebaseDatabase sender, DataSnapshot snapshot)
  67. {
  68. DoDebug("[OK] GetRules");
  69. DoDebug("[OK] Raw Json: " + snapshot.RawJson);
  70. }
  71. void GetRulesFailHandler(FirebaseDatabase sender, FirebaseError err)
  72. {
  73. DoDebug("[ERR] GetRules, " + err.Message + " (" + (int)err.Status + ")");
  74. }
  75. void GetTimeStamp(FirebaseDatabase sender, DataSnapshot snapshot)
  76. {
  77. long timeStamp = snapshot.Value<long> ();
  78. DateTime dateTime = FirebaseDatabase.TimeStampToDateTime (timeStamp);
  79. DoDebug ("[OK] Get on timestamp key: <" + sender.FullKey + ">");
  80. DoDebug("Date: " + timeStamp + " --> " + dateTime.ToString ());
  81. }
  82. void DoDebug(string str)
  83. {
  84. Debug.Log(str);
  85. if (textMesh != null)
  86. {
  87. textMesh.text += (++debug_idx + ". " + str) + "\n";
  88. }
  89. }
  90. IEnumerator Tests()
  91. {
  92. // Inits Firebase using Firebase Secret Key as Auth
  93. // The current provided implementation not yet including Auth Token Generation
  94. // If you're using this sample Firebase End,
  95. // there's a possibility that your request conflicts with other simple-firebase-c# user's request
  96. FirebaseDatabase firebase = FirebaseDatabase.CreateNew ("simple-firebase-csharp.firebaseio.com", "UPaocwJVKvhnKL1orrf5XwWHMz3HUzckgCnGp6id");
  97. // Init callbacks
  98. firebase.OnGetSuccess += GetOKHandler;
  99. firebase.OnGetFailed += GetFailHandler;
  100. firebase.OnSetSuccess += SetOKHandler;
  101. firebase.OnSetFailed += SetFailHandler;
  102. firebase.OnUpdateSuccess += UpdateOKHandler;
  103. firebase.OnUpdateFailed += UpdateFailHandler;
  104. firebase.OnPushSuccess += PushOKHandler;
  105. firebase.OnPushFailed += PushFailHandler;
  106. firebase.OnDeleteSuccess += DelOKHandler;
  107. firebase.OnDeleteFailed += DelFailHandler;
  108. // Get child node from firebase, if false then all the callbacks are not inherited.
  109. FirebaseDatabase temporary = firebase.Child ("temporary", true);
  110. FirebaseDatabase lastUpdate = firebase.Child ("lastUpdate");
  111. lastUpdate.OnGetSuccess += GetTimeStamp;
  112. // Make observer on "last update" time stamp
  113. FirebaseObserver observer = new FirebaseObserver(lastUpdate, 1f);
  114. observer.OnChange += (FirebaseDatabase sender, DataSnapshot snapshot)=>{
  115. DoDebug("[OBSERVER] Last updated changed to: " + snapshot.Value<long>());
  116. };
  117. observer.Start ();
  118. DoDebug ("[OBSERVER] FirebaseObserver on " + lastUpdate.FullKey +" started!");
  119. // Print details
  120. DoDebug("Firebase endpoint: " + firebase.Endpoint);
  121. DoDebug("Firebase key: " + firebase.Key);
  122. DoDebug("Firebase fullKey: " + firebase.FullKey);
  123. DoDebug("Firebase child key: " + temporary.Key);
  124. DoDebug("Firebase child fullKey: " + temporary.FullKey);
  125. // Unnecessarily skips a frame, really, unnecessary.
  126. yield return null;
  127. // Create a FirebaseQueue
  128. FirebaseQueue firebaseQueue = new FirebaseQueue();
  129. // Test #1: Test all firebase commands, using FirebaseQueueManager
  130. // The requests should be running in order
  131. firebaseQueue.AddQueueSet (firebase, GetSampleScoreBoard (), FirebaseParam.Empty.PrintSilent ());
  132. firebaseQueue.AddQueuePush (firebase.Child ("broadcasts", true), "{ \"name\": \"simple-firebase-csharp\", \"message\": \"awesome!\"}", true);
  133. firebaseQueue.AddQueueSetTimeStamp (firebase, "lastUpdate");
  134. firebaseQueue.AddQueueGet (firebase, "print=pretty");
  135. firebaseQueue.AddQueueUpdate (firebase.Child ("layout", true), "{\"x\": 5.8, \"y\":-94}", true);
  136. firebaseQueue.AddQueueGet (firebase.Child ("layout", true));
  137. firebaseQueue.AddQueueGet (lastUpdate);
  138. //Deliberately make an error for an example
  139. DoDebug("[WARNING] There is one invalid request below which will gives error, only for example on error handling.");
  140. firebaseQueue.AddQueueGet (firebase, FirebaseParam.Empty.LimitToLast(-1));
  141. // (~~ -.-)~~
  142. DoDebug ("==== Wait for seconds 15f ======");
  143. yield return new WaitForSeconds (15f);
  144. DoDebug ("==== Wait over... ====");
  145. // Test #2: Calls without using FirebaseQueueManager
  146. // The requests could overtake each other (ran asynchronously)
  147. firebase.Child("broadcasts", true).Push("{ \"name\": \"dikra\", \"message\": \"hope it runs well...\"}", true);
  148. firebase.GetValue(FirebaseParam.Empty.OrderByKey().LimitToFirst(2));
  149. temporary.GetValue ();
  150. firebase.GetValue (FirebaseParam.Empty.OrderByKey().LimitToLast(2));
  151. temporary.GetValue ();
  152. firebase.Child ("scores", true).GetValue(FirebaseParam.Empty.OrderByChild ("rating").LimitToFirst(2));
  153. firebase.GetRules (GetRulesOKHandler, GetRulesFailHandler);
  154. // ~~(-.- ~~)
  155. yield return null;
  156. DoDebug ("==== Wait for seconds 15f ======");
  157. yield return new WaitForSeconds (15f);
  158. DoDebug ("==== Wait over... ====");
  159. // Test #3: Delete the frb_child and broadcasts
  160. firebaseQueue.AddQueueGet (firebase);
  161. firebaseQueue.AddQueueDelete(temporary);
  162. // please notice that the OnSuccess/OnFailed handler is not inherited since Child second parameter not set to true.
  163. DoDebug("'broadcasts' node is deleted silently.");
  164. firebaseQueue.AddQueueDelete (firebase.Child ("broadcasts"));
  165. firebaseQueue.AddQueueGet (firebase);
  166. // ~~(-.-)~~
  167. yield return null;
  168. DoDebug ("==== Wait for seconds 15f ======");
  169. yield return new WaitForSeconds (15f);
  170. DoDebug ("==== Wait over... ====");
  171. observer.Stop ();
  172. DoDebug ("[OBSERVER] FirebaseObserver on " + lastUpdate.FullKey +" stopped!");
  173. }
  174. Dictionary<string, object> GetSampleScoreBoard()
  175. {
  176. Dictionary<string, object> scoreBoard = new Dictionary<string, object> ();
  177. Dictionary<string, object> scores = new Dictionary<string, object> ();
  178. Dictionary<string, object> p1 = new Dictionary<string, object> ();
  179. Dictionary<string, object> p2 = new Dictionary<string, object> ();
  180. Dictionary<string, object> p3 = new Dictionary<string, object> ();
  181. p1.Add ("name", "simple");
  182. p1.Add("score", 80);
  183. p2.Add ("name", "firebase");
  184. p2.Add ("score", 100);
  185. p3.Add ("name", "csharp");
  186. p3.Add ("score", 60);
  187. scores.Add ("p1", p1);
  188. scores.Add ("p2", p2);
  189. scores.Add ("p3", p3);
  190. scoreBoard.Add ("scores", scores);
  191. scoreBoard.Add("layout", Json.Deserialize("{\"x\": 0, \"y\":10}") as Dictionary<string, object>);
  192. scoreBoard.Add ("resizable", true);
  193. scoreBoard.Add("temporary" , "will be deleted later");
  194. return scoreBoard;
  195. }
  196. }