57 lines
1.4 KiB
C#
57 lines
1.4 KiB
C#
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.");
|
|
}
|
|
}
|
|
}
|