SamsonGame/Assets/Scripts/Game/Time/NetTime.cs

57 lines
1.4 KiB
C#
Raw Permalink Normal View History

2021-12-29 20:50:11 +03:00
using System;
using System.Globalization;
using System.Net;
using Cysharp.Threading.Tasks;
using UniRx;
public class NetTime : LazySingleton<NetTime>
{
public readonly ReactiveProperty<bool> IsAvailable = new ReactiveProperty<bool>();
public IObservable<bool> IsAvailableAsObservable() => IsAvailable;
public DateTime Time => DateTime.Now + _timeDelta;
private TimeSpan _timeDelta = TimeSpan.Zero;
private static async UniTask<DateTime> GetTimeAsync()
{
using (var response =
await WebRequest.Create("https://www.google.com").GetResponseAsync())
return DateTime.ParseExact(response.Headers["date"],
"ddd, dd MMM yyyy HH:mm:ss 'GMT'",
CultureInfo.InvariantCulture.DateTimeFormat,
DateTimeStyles.AssumeUniversal);
}
private void Awake()
{
UniTask.Run(CacheTimeAsync);
}
private void OnApplicationFocus(bool hasFocus)
{
if (hasFocus == false)
{
IsAvailable.Value = false;
return;
}
UniTask.Run(CacheTimeAsync);
}
private async void CacheTimeAsync()
{
try
{
var googleTime = await GetTimeAsync();
var deviceTime = DateTime.Now;
_timeDelta = googleTime - deviceTime;
IsAvailable.Value = true;
}
catch (Exception)
{
Log.Error("Can't connect with google.");
}
}
}