| | 1 | | using System.Collections; |
| | 2 | | using System.Collections.Generic; |
| | 3 | | using UnityEngine; |
| | 4 | | using System; |
| | 5 | | using UnityEngine.Networking; |
| | 6 | |
|
| | 7 | | namespace DCL.ServerTime |
| | 8 | | { |
| | 9 | | public class WorldTimer |
| | 10 | | { |
| | 11 | | public delegate void OnTimeUpdated(DateTime serverTime); |
| | 12 | | public event OnTimeUpdated OnTimeChanged; |
| | 13 | |
|
| | 14 | | public float serverHitFrequency; |
| 0 | 15 | | public string serverURL = "https://peer.decentraland.org/lambdas/health"; |
| | 16 | |
|
| | 17 | | private bool initialized = false; |
| 0 | 18 | | private DateTime lastTimeFromServer = DateTime.Now.ToUniversalTime(); |
| 0 | 19 | | private DateTime lastTimeFromSystem = DateTime.Now; |
| | 20 | | private TimeSpan timeOffset; |
| | 21 | | private bool stopTimer = false; |
| | 22 | | UnityWebRequest webRequest; |
| | 23 | |
|
| 0 | 24 | | public WorldTimer() { GetTimeFromServer(); } |
| | 25 | |
|
| | 26 | | void GetTimeFromServer() |
| | 27 | | { |
| 0 | 28 | | webRequest = UnityWebRequest.Get(serverURL); |
| 0 | 29 | | UnityWebRequestAsyncOperation temp = webRequest.SendWebRequest(); |
| 0 | 30 | | temp.completed += WebRequestCompleted; |
| 0 | 31 | | } |
| | 32 | |
|
| | 33 | | private void WebRequestCompleted(AsyncOperation obj) |
| | 34 | | { |
| 0 | 35 | | switch (webRequest.result) |
| | 36 | | { |
| | 37 | | case UnityWebRequest.Result.InProgress: |
| | 38 | | break; |
| | 39 | | case UnityWebRequest.Result.Success: |
| 0 | 40 | | string responseHeaderTime = webRequest.GetResponseHeader("date"); |
| 0 | 41 | | UpdateTimeWithServerTime(responseHeaderTime); |
| 0 | 42 | | initialized = true; |
| | 43 | | break; |
| | 44 | | case UnityWebRequest.Result.ConnectionError: |
| | 45 | | break; |
| | 46 | | case UnityWebRequest.Result.ProtocolError: |
| | 47 | | break; |
| | 48 | | case UnityWebRequest.Result.DataProcessingError: |
| | 49 | | break; |
| | 50 | | default: |
| | 51 | | break; |
| | 52 | | } |
| | 53 | |
|
| 0 | 54 | | webRequest.Dispose(); |
| 0 | 55 | | } |
| | 56 | |
|
| | 57 | | void UpdateTimeWithServerTime(string datetime) |
| | 58 | | { |
| | 59 | | DateTime serverTime; |
| 0 | 60 | | if (DateTime.TryParse(datetime, out serverTime)) |
| | 61 | | { |
| | 62 | | // Update last server time |
| 0 | 63 | | lastTimeFromServer = serverTime.ToUniversalTime(); |
| | 64 | | // Update current time from the system |
| 0 | 65 | | lastTimeFromSystem = DateTime.Now; |
| | 66 | |
|
| | 67 | | // Fire Event |
| 0 | 68 | | OnTimeChanged?.Invoke(lastTimeFromServer); |
| | 69 | | } |
| 0 | 70 | | } |
| | 71 | |
|
| | 72 | | public DateTime GetCurrentTime() |
| | 73 | | { |
| 0 | 74 | | TimeSpan systemTimeOffset = DateTime.Now - lastTimeFromSystem; |
| 0 | 75 | | return lastTimeFromServer.ToUniversalTime().Add(systemTimeOffset); |
| | 76 | | } |
| | 77 | | } |
| | 78 | | } |