using Godot; using System; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading; using System.Web; using BITKit; using BITKit.Auth; using BITKit.Net.Http; using Cysharp.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Environment = System.Environment; using HttpClient = System.Net.Http.HttpClient; namespace IDIS.License; public class LicenseBin { public DateTime ExpirationDate=DateTime.Now; public string Token; } public partial class LicenseService : EntityComponent,IAuthService { private static readonly HttpClient _httpClient = new(); [Export] private string _requestAuthorizeUrl; [Export] private string _revokeAuthorizeUrl; public bool IsAuthorized { get;private set; } public bool IsAuthorizing { get;private set; } public event Action OnAuthorize; public event Action OnAuthorized; public event Action UnAuthorize; public event Action OnAuthorizeFailure; private CancellationTokenSource _cancellationTokenSource; private CancellationToken _cancellationToken=>_cancellationTokenSource.Token; private IHttpListenerService _httpListenerService; private readonly string path = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "iFactory", "License.bin" ); public override void BuildService(IServiceCollection serviceCollection) { serviceCollection.AddSingleton(this); } public override void _EnterTree() { _cancellationTokenSource = new CancellationTokenSource(); } public override void _ExitTree() { _cancellationTokenSource.Cancel(); } public override void OnAwake() { _httpListenerService = Entity.ServiceProvider.GetRequiredService(); _httpListenerService.OnRequest += OnRequest; } public override void OnStart() { BIT4Log.Log("准备文件中,二进制授权文件路径:"+path); if (IsAuthorized || IsAuthorizing) return; if (File.Exists(path) is false) return; var json = File.ReadAllText(path); var licenseBin = JsonConvert.DeserializeObject(json); if(licenseBin.ExpirationDate($"授权成功:{message}"); var licenseBin = new LicenseBin { Token = rawToken, ExpirationDate = DateTime.Now.AddDays(7) }; PathHelper.EnsureDirectoryCreated(path); await File.WriteAllTextAsync(path, JsonConvert.SerializeObject(licenseBin), _cancellationToken); IsAuthorized = true; } else { OnAuthorizeFailure?.Invoke(message); BIT4Log.Log($"当前Token:{rawToken}"); BIT4Log.Log($"授权失败:{message}"); } } public UniTask CancelAuthorizationAsync() { if (IsAuthorized is false) { throw new InvalidOperationException("未授权"); } var url = _revokeAuthorizeUrl.Replace("{x}",_requestAuthorizeUrl); UnAuthorize?.Invoke("取消授权"); IsAuthorized = false; _httpClient.PostAsync(url, new StringContent(""), _cancellationToken).AsUniTask().Forget(); return UniTask.CompletedTask; } }