using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using JiDangJia.Contracts;
namespace JiDangJia.Services;
#if !COMMUNITY_APP
public sealed class ActivationRequiredException(string username) : InvalidOperationException("首次使用、授权已到期或此设备未激活,请填写管理员分发的卡密后登录。")
{
public string Username { get; } = username;
}
#endif
public sealed partial class AuthClient
{
public static AuthClient Current { get; } = new();
private readonly HttpClient http = new() { Timeout = TimeSpan.FromSeconds(120) };
private string token = "";
private int generation;
public string AccountId { get; private set; } = "";
public string Name { get; private set; } = "";
public string Username { get; private set; } = "";
public string Role { get; private set; } = "user";
public bool IsAdmin => Role == "admin";
public DateTime VerifiedAt { get; private set; }
#if !COMMUNITY_APP
public DateTime ExpiresAt { get; private set; }
public bool Licensed { get; private set; }
public bool Permanent {get;private set;}
#endif
public bool Locked {get;internal set;}
public string ServerUrl => ServerSettings.BaseUrl;
public string DeviceId
{
get
{
string id = Preferences.Default.Get("device_id", ""); if (id.Length > 0) return id;
#if ANDROID
var androidId = Android.Provider.Settings.Secure.GetString(Android.App.Application.Context.ContentResolver, Android.Provider.Settings.Secure.AndroidId);
#else
string? androidId=null;
#endif
id = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(androidId ?? Guid.NewGuid().ToString("N")))); Preferences.Default.Set("device_id", id); return id;
}
}
private async Task<JsonDocument> Request(string path, object? data = null, bool auth = true)
{
if(auth&&Locked&&path!="/user/password/verify")throw new InvalidOperationException("账户已锁定,请先解锁");var version = Volatile.Read(ref generation);
using var request = new HttpRequestMessage(data is null ? HttpMethod.Get : HttpMethod.Post, ServerUrl + "/api" + path);
if (auth && token.Length > 0) request.Headers.Authorization = new("Bearer", token);
if (path.StartsWith("/community/", StringComparison.Ordinal)||path.StartsWith("/safety/",StringComparison.Ordinal)) request.Headers.Add("X-Device-Id", DeviceId);
if (data is not null) request.Content = JsonContent.Create(data);
HttpResponseMessage response;
using var cancel = new CancellationTokenSource(TimeSpan.FromSeconds(20));
try { response = await http.SendAsync(request, cancel.Token); } catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) { throw new InvalidOperationException("无法连接登录服务器,请检查网络或联系管理员。", ex); }
using (response)
{
var text = await response.Content.ReadAsStringAsync(); if (version != Volatile.Read(ref generation)||Locked&&path!="/user/password/verify") throw new OperationCanceledException("账户已切换,请重新执行操作"); JsonDocument result;
try { result = JsonDocument.Parse(text); } catch (JsonException) { throw new InvalidOperationException(response.StatusCode == System.Net.HttpStatusCode.TooManyRequests ? "操作频繁,请稍后重试" : "服务器返回了无效响应"); }
if (!response.IsSuccessStatusCode) { var message = result.RootElement.TryGetProperty("error", out var error) ? error.GetString() : "请求失败"; result.Dispose(); if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) ClearSession(); throw new InvalidOperationException(message); }
return result;
}
}
#if COMMUNITY_APP
public async Task Login(string username,string password,LegalConsent? consent=null)
#else
public async Task Login(string username, string password, string? activationCode = null,LegalConsent? consent=null)
#endif
{
RequireLegalConsent(consent);
ClearSession(); var version = Volatile.Read(ref generation);
try
{
consent=consent! with{DeviceId=DeviceId};
using var d = await Request("/auth/login", new { username, password,consent }, false);
token = d.RootElement.GetProperty("token").GetString()!; SetAccount(d.RootElement.GetProperty("account"));
#if COMMUNITY_APP
VerifiedAt=DateTime.UtcNow;await SaveCache();
#else
var code = (activationCode ?? "").Trim().ToUpperInvariant();
if (code.Length > 0 && !IsAdmin) await Activate(code); else await RefreshLicense();
EnsureActivated();
#endif
await SecureStorage.Default.SetAsync("server_session", JsonSerializer.Serialize(new { token, server = ServerUrl, accountId = AccountId,legalConsent=consent }));
}
catch
{
if (version == Volatile.Read(ref generation)) await Logout();
throw;
}
}
public async Task RegisterAccount(string username, string password, string name,LegalConsent? consent=null)
{ RequireLegalConsent(consent);consent=consent! with{DeviceId=DeviceId};using var result = await Request("/auth/register", new { username, password, name,consent }, false); }
#if COMMUNITY_APP
public async Task Register(string username,string password,string name,LegalConsent? consent=null)
{await RegisterAccount(username,password,name,consent);await Login(username,password,consent);}
#else
public async Task Register(string username, string password, string name, string? activationCode = null,LegalConsent? consent=null)
{ await RegisterAccount(username, password, name,consent); await Login(username, password, activationCode,consent); }
#endif
public async Task<bool> Restore()
{
var version = Volatile.Read(ref generation); string expectedAccount = "";bool previouslyConsented=false;
try
{
var saved=await SecureStorage.Default.GetAsync("server_session");if(saved is null||version!=Volatile.Read(ref generation))return false;
using var d=JsonDocument.Parse(saved);if(d.RootElement.GetProperty("server").GetString()!=ServerUrl)return false;
expectedAccount=d.RootElement.TryGetProperty("accountId",out var id)?id.GetString()??"":"";
var consent=d.RootElement.TryGetProperty("legalConsent",out var legal)?legal.Deserialize<LegalConsent>(communityJson):null;
RequireLegalConsent(consent);previouslyConsented=true;token=d.RootElement.GetProperty("token").GetString()!;
if(!(await LegalPolicies()).Matches(consent))throw new LegalConsentRequiredException("用户协议或隐私政策已更新,请阅读并重新勾选后登录");
using var me=await Request("/user/me");SetAccount(me.RootElement.GetProperty("account"));
#if COMMUNITY_APP
VerifiedAt=DateTime.UtcNow;await SaveCache();
#else
await RefreshLicense();EnsureActivated();
#endif
return true;
}
catch(LegalConsentRequiredException){if(version==Volatile.Read(ref generation))ClearSession();throw;}
#if !COMMUNITY_APP
catch (ActivationRequiredException)
{ if (version == Volatile.Read(ref generation)) await Logout(); throw; }
#endif
catch (InvalidOperationException ex) when (ex.InnerException is HttpRequestException or TaskCanceledException)
{ var restored = previouslyConsented&&version == Volatile.Read(ref generation) && await RestoreCache(expectedAccount); if (!restored && version == Volatile.Read(ref generation)) ClearSession(); return restored; }
catch { if (version == Volatile.Read(ref generation)) ClearSession(); return false; }
}
private void SetAccount(JsonElement a) { AccountId = a.GetProperty("id").GetString()!; Name = a.GetProperty("name").GetString()!; Username = a.GetProperty("username").GetString()!; Role = a.GetProperty("role").GetString() ?? "user"; }
#if !COMMUNITY_APP
private void EnsureActivated()
{ if (!Licensed || DateTime.UtcNow >= ExpiresAt) throw new ActivationRequiredException(Username); }
#endif
public void RequireAccess()
{
#if COMMUNITY_APP
if(Locked)throw new InvalidOperationException("账户已锁定,请先解锁");
if(AccountId.Length==0||token.Length==0)throw new InvalidOperationException("请先登录社群账户");
#else
RequireLicense();
#endif
}
public Task<JsonDocument> AdminRequest(string path, object? data = null) { if (!IsAdmin) throw new InvalidOperationException("需要管理员权限"); return Request("/admin" + path, data); }
private static readonly JsonSerializerOptions communityJson = new(JsonSerializerDefaults.Web);
#if !ACCOUNTING_APP
public async Task<T> CommunityRequest<T>(string path, object? data = null)
{
RequireAccess(); using var result = await Request("/community" + path, data);
return result.RootElement.Deserialize<T>(communityJson) ?? throw new InvalidOperationException("服务器返回了无效社群数据");
}
private static void MediaOriginHeaders(HttpRequestMessage request,string kind,string source,DateTimeOffset? createdAt)
{
if(kind is not ("IMAGE" or "VIDEO"))return;request.Headers.Add("X-Media-Source",source);
if(createdAt is {} stamp)request.Headers.Add("X-Media-Created-At",stamp.ToUniversalTime().ToString("O"));
}
public async Task<JiDangJia.Contracts.CommunityMedia> UploadMedia(byte[] bytes,string kind,string uploadId,string source="LOCAL",DateTimeOffset? createdAt=null,bool forChat=false)
{
RequireAccess();var version=Volatile.Read(ref generation);
using var request=new HttpRequestMessage(HttpMethod.Post,ServerUrl+"/api/community/media");request.Headers.Authorization=new("Bearer",token);request.Headers.Add("X-Device-Id",DeviceId);request.Headers.Add("X-Media-Kind",kind);request.Headers.Add("X-Upload-Id",uploadId);request.Content=new ByteArrayContent(bytes);
MediaOriginHeaders(request,kind,source,createdAt);
if(forChat)request.Headers.Add("X-Media-Purpose","CHAT");
using var cancel=new CancellationTokenSource(TimeSpan.FromSeconds(120));using var response=await http.SendAsync(request,cancel.Token);if(version!=Volatile.Read(ref generation)||Locked)throw new OperationCanceledException("账户已切换");
var responseText=await response.Content.ReadAsStringAsync(cancel.Token);if(version!=Volatile.Read(ref generation)||Locked)throw new OperationCanceledException("账户已切换");
if(response.StatusCode==System.Net.HttpStatusCode.Unauthorized)ClearSession();using var data=JsonDocument.Parse(responseText);
if(!response.IsSuccessStatusCode)throw new InvalidOperationException(data.RootElement.TryGetProperty("error",out var error)?error.GetString():"媒体上传失败");
return data.RootElement.Deserialize<JiDangJia.Contracts.CommunityMedia>(communityJson)??throw new InvalidOperationException("媒体数据无效");
}
public async Task<byte[]> DownloadMedia(string id,CancellationToken ct=default)
{
RequireAccess();if(!System.Text.RegularExpressions.Regex.IsMatch(id,"^[a-f0-9]{32}$"))throw new ArgumentException("媒体编号无效");var version=Volatile.Read(ref generation);
#if COMMUNITY_APP
var local=await CommunityChatArchive.ReadMedia(id);if(version!=Volatile.Read(ref generation)||Locked)throw new OperationCanceledException("账户已切换");if(local is not null)return local;
#endif
using var request=new HttpRequestMessage(HttpMethod.Get,ServerUrl+"/api/community/media/"+id);request.Headers.Authorization=new("Bearer",token);request.Headers.Add("X-Device-Id",DeviceId);
using var response=await http.SendAsync(request,ct);if(version!=Volatile.Read(ref generation)||Locked)throw new OperationCanceledException("账户已切换");
if(response.StatusCode==System.Net.HttpStatusCode.Unauthorized)ClearSession();if(response.StatusCode==System.Net.HttpStatusCode.Gone)throw new InvalidOperationException("本机未保存此附件,服务器保留期已过");if(!response.IsSuccessStatusCode)throw new InvalidOperationException("此媒体已不可用或没有读取权限");var bytes=await response.Content.ReadAsByteArrayAsync(ct);if(version!=Volatile.Read(ref generation)||Locked)throw new OperationCanceledException("账户已切换");
#if COMMUNITY_APP
CommunityChatArchive.SaveMedia(id,bytes);
#endif
return bytes;
}
internal Dictionary<string,string> MediaHeaders()
{RequireAccess();return new(){["Authorization"]="Bearer "+token,["X-Device-Id"]=DeviceId};}
public async Task<JiDangJia.Contracts.CommunityMedia> UploadRecommendation(Stream stream,string kind,string uploadId,CancellationToken ct=default,string source="LOCAL",DateTimeOffset? createdAt=null)
{
RequireAccess();if(!IsAdmin)throw new InvalidOperationException("推荐内容由管理员发布");int version=Volatile.Read(ref generation);
using var request=new HttpRequestMessage(HttpMethod.Post,ServerUrl+"/api/admin/community/media");request.Headers.Authorization=new("Bearer",token);request.Headers.Add("X-Device-Id",DeviceId);request.Headers.Add("X-Media-Kind",kind);request.Headers.Add("X-Upload-Id",uploadId);request.Content=new StreamContent(stream);
MediaOriginHeaders(request,kind,source,createdAt);
using var streaming=new HttpClient{Timeout=Timeout.InfiniteTimeSpan};using var response=await streaming.SendAsync(request,ct);if(version!=Volatile.Read(ref generation)||Locked)throw new OperationCanceledException("账户已切换");
using var data=JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct));if(version!=Volatile.Read(ref generation)||Locked)throw new OperationCanceledException("账户已切换");if(response.StatusCode==System.Net.HttpStatusCode.Unauthorized)ClearSession();if(!response.IsSuccessStatusCode)throw new InvalidOperationException(data.RootElement.TryGetProperty("error",out var error)?error.GetString():"媒体上传失败");
return data.RootElement.Deserialize<JiDangJia.Contracts.CommunityMedia>(new JsonSerializerOptions(JsonSerializerDefaults.Web))??throw new InvalidOperationException("媒体数据无效");
}
#endif
public async Task<JiDangJia.Contracts.AppContent> GetContent()
{
RequireAccess();using var result=await Request("/content");
return result.RootElement.Deserialize<JiDangJia.Contracts.AppContent>(communityJson)??throw new InvalidOperationException("服务器内容数据无效");
}
public async Task<AppContent> GetPublicContent()
{
using var result=await Request("/public/content",auth:false);
return result.RootElement.Deserialize<AppContent>(communityJson)??throw new InvalidOperationException("服务器公开信息无效");
}
#if !COMMUNITY_APP
public async Task RefreshLicense()
{ using var d = await Request("/user/license?deviceId=" + DeviceId); UpdateLicense(d.RootElement); await SaveCache(); }
public async Task Activate(string code)
{ using var d = await Request("/user/activate", new { deviceId = DeviceId, code }); UpdateLicense(d.RootElement); await SaveCache(); }
private void UpdateLicense(JsonElement result)
{ Permanent=result.TryGetProperty("permanent",out var p)&&p.GetBoolean();Licensed = result.GetProperty("active").GetBoolean(); ExpiresAt = result.TryGetProperty("expiresAt", out var e) && e.ValueKind == JsonValueKind.String ? e.GetDateTime().ToUniversalTime() : DateTime.MinValue; VerifiedAt = DateTime.UtcNow; }
public void RequireLicense()
{
if(Locked)throw new InvalidOperationException("账户已锁定,请先解锁");if (!Licensed || DateTime.UtcNow >= ExpiresAt || DateTime.UtcNow - VerifiedAt > TimeSpan.FromHours(24)) throw new InvalidOperationException("授权未激活、已到期或需要联网校验,请在设置中的账户授权页更新。");
}
private Task SaveCache() => SecureStorage.Default.SetAsync("verified_license", JsonSerializer.Serialize(new { server = ServerUrl, device = DeviceId, account = new { id = AccountId, username = Username, name = Name, role = Role }, licensed = Licensed, expiresAt = ExpiresAt, verifiedAt = VerifiedAt }));
private async Task<bool> RestoreCache(string expectedAccount)
{
try
{
var saved = await SecureStorage.Default.GetAsync("verified_license"); if (saved is null) return false;
using var doc = JsonDocument.Parse(saved); var d = doc.RootElement;
var verified = d.GetProperty("verifiedAt").GetDateTime().ToUniversalTime(); var expires = d.GetProperty("expiresAt").GetDateTime().ToUniversalTime();
if (expectedAccount.Length == 0 || d.GetProperty("account").GetProperty("id").GetString() != expectedAccount || d.GetProperty("server").GetString() != ServerUrl || d.GetProperty("device").GetString() != DeviceId || !d.GetProperty("licensed").GetBoolean() || DateTime.UtcNow >= expires || verified > DateTime.UtcNow.AddMinutes(5) || DateTime.UtcNow - verified > TimeSpan.FromHours(24)) return false;
SetAccount(d.GetProperty("account")); VerifiedAt = verified; ExpiresAt = expires; Licensed = true;Permanent=expires.Year==9999; return true;
}
catch { return false; }
}
#else
public async Task RefreshAccount(){using var me=await Request("/user/me");SetAccount(me.RootElement.GetProperty("account"));VerifiedAt=DateTime.UtcNow;await SaveCache();}
private Task SaveCache()=>SecureStorage.Default.SetAsync("community_account_cache",JsonSerializer.Serialize(new{server=ServerUrl,device=DeviceId,account=new{id=AccountId,username=Username,name=Name,role=Role},verifiedAt=VerifiedAt}));
private async Task<bool> RestoreCache(string expectedAccount)
{
try{
var saved=await SecureStorage.Default.GetAsync("community_account_cache");if(saved is null)return false;
using var doc=JsonDocument.Parse(saved);var d=doc.RootElement;var verified=d.GetProperty("verifiedAt").GetDateTime().ToUniversalTime();
if(expectedAccount.Length==0||d.GetProperty("account").GetProperty("id").GetString()!=expectedAccount||d.GetProperty("server").GetString()!=ServerUrl||d.GetProperty("device").GetString()!=DeviceId||verified>DateTime.UtcNow.AddMinutes(5)||DateTime.UtcNow-verified>TimeSpan.FromHours(24))return false;
SetAccount(d.GetProperty("account"));VerifiedAt=verified;return true;
}catch{return false;}
}
#endif
private void ClearSession() { AppNotifications.Stop();
#if !ACCOUNTING_APP
Views.CommunityVideo.StopAll();
#endif
Interlocked.Increment(ref generation);token="";Locked=false;AccountId="";Role="user";Name="";Username="";VerifiedAt=default;
#if !COMMUNITY_APP
Permanent=false;Licensed=false;ExpiresAt=default;
#endif
SecureStorage.Default.Remove("server_session");SecureStorage.Default.Remove("verified_license");SecureStorage.Default.Remove("community_account_cache");}
public async Task ChangePassword(string oldPassword, string password) { using var d = await Request("/user/password", new { oldPassword, password }); await Logout(false); }
public async Task Logout(bool callServer = true)
{ try { if (callServer && token.Length > 0) { using var d = await Request("/user/logout", new { }); } } catch (InvalidOperationException) { } finally { ClearSession(); } }
}
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using JiDangJia.Contracts;
namespace JiDangJia.Services;
#if !COMMUNITY_APP
public sealed class ActivationRequiredException(string username) : InvalidOperationException("首次使用、授权已到期或此设备未激活,请填写管理员分发的卡密后登录。")
{
public string Username { get; } = username;
}
#endif
public sealed partial class AuthClient
{
public static AuthClient Current { get; } = new();
private readonly HttpClient http = new() { Timeout = TimeSpan.FromSeconds(120) };
private string token = "";
private int generation;
public string AccountId { get; private set; } = "";
public string Name { get; private set; } = "";
public string Username { get; private set; } = "";
public string Role { get; private set; } = "user";
public bool IsAdmin => Role == "admin";
public DateTime VerifiedAt { get; private set; }
#if !COMMUNITY_APP
public DateTime ExpiresAt { get; private set; }
public bool Licensed { get; private set; }
public bool Permanent {get;private set;}
#endif
public bool Locked {get;internal set;}
public string ServerUrl => ServerSettings.BaseUrl;
public string DeviceId
{
get
{
string id = Preferences.Default.Get("device_id", ""); if (id.Length > 0) return id;
#if ANDROID
var androidId = Android.Provider.Settings.Secure.GetString(Android.App.Application.Context.ContentResolver, Android.Provider.Settings.Secure.AndroidId);
#else
string? androidId=null;
#endif
id = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(androidId ?? Guid.NewGuid().ToString("N")))); Preferences.Default.Set("device_id", id); return id;
}
}
private async Task<JsonDocument> Request(string path, object? data = null, bool auth = true)
{
if(auth&&Locked&&path!="/user/password/verify")throw new InvalidOperationException("账户已锁定,请先解锁");var version = Volatile.Read(ref generation);
using var request = new HttpRequestMessage(data is null ? HttpMethod.Get : HttpMethod.Post, ServerUrl + "/api" + path);
if (auth && token.Length > 0) request.Headers.Authorization = new("Bearer", token);
if (path.StartsWith("/community/", StringComparison.Ordinal)||path.StartsWith("/safety/",StringComparison.Ordinal)) request.Headers.Add("X-Device-Id", DeviceId);
if (data is not null) request.Content = JsonContent.Create(data);
HttpResponseMessage response;
using var cancel = new CancellationTokenSource(TimeSpan.FromSeconds(20));
try { response = await http.SendAsync(request, cancel.Token); } catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException) { throw new InvalidOperationException("无法连接登录服务器,请检查网络或联系管理员。", ex); }
using (response)
{
var text = await response.Content.ReadAsStringAsync(); if (version != Volatile.Read(ref generation)||Locked&&path!="/user/password/verify") throw new OperationCanceledException("账户已切换,请重新执行操作"); JsonDocument result;
try { result = JsonDocument.Parse(text); } catch (JsonException) { throw new InvalidOperationException(response.StatusCode == System.Net.HttpStatusCode.TooManyRequests ? "操作频繁,请稍后重试" : "服务器返回了无效响应"); }
if (!response.IsSuccessStatusCode) { var message = result.RootElement.TryGetProperty("error", out var error) ? error.GetString() : "请求失败"; result.Dispose(); if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) ClearSession(); throw new InvalidOperationException(message); }
return result;
}
}
#if COMMUNITY_APP
public async Task Login(string username,string password,LegalConsent? consent=null)
#else
public async Task Login(string username, string password, string? activationCode = null,LegalConsent? consent=null)
#endif
{
RequireLegalConsent(consent);
ClearSession(); var version = Volatile.Read(ref generation);
try
{
consent=consent! with{DeviceId=DeviceId};
using var d = await Request("/auth/login", new { username, password,consent }, false);
token = d.RootElement.GetProperty("token").GetString()!; SetAccount(d.RootElement.GetProperty("account"));
#if COMMUNITY_APP
VerifiedAt=DateTime.UtcNow;await SaveCache();
#else
var code = (activationCode ?? "").Trim().ToUpperInvariant();
if (code.Length > 0 && !IsAdmin) await Activate(code); else await RefreshLicense();
EnsureActivated();
#endif
await SecureStorage.Default.SetAsync("server_session", JsonSerializer.Serialize(new { token, server = ServerUrl, accountId = AccountId,legalConsent=consent }));
}
catch
{
if (version == Volatile.Read(ref generation)) await Logout();
throw;
}
}
public async Task RegisterAccount(string username, string password, string name,LegalConsent? consent=null)
{ RequireLegalConsent(consent);consent=consent! with{DeviceId=DeviceId};using var result = await Request("/auth/register", new { username, password, name,consent }, false); }
#if COMMUNITY_APP
public async Task Register(string username,string password,string name,LegalConsent? consent=null)
{await RegisterAccount(username,password,name,consent);await Login(username,password,consent);}
#else
public async Task Register(string username, string password, string name, string? activationCode = null,LegalConsent? consent=null)
{ await RegisterAccount(username, password, name,consent); await Login(username, password, activationCode,consent); }
#endif
public async Task<bool> Restore()
{
var version = Volatile.Read(ref generation); string expectedAccount = "";bool previouslyConsented=false;
try
{
var saved=await SecureStorage.Default.GetAsync("server_session");if(saved is null||version!=Volatile.Read(ref generation))return false;
using var d=JsonDocument.Parse(saved);if(d.RootElement.GetProperty("server").GetString()!=ServerUrl)return false;
expectedAccount=d.RootElement.TryGetProperty("accountId",out var id)?id.GetString()??"":"";
var consent=d.RootElement.TryGetProperty("legalConsent",out var legal)?legal.Deserialize<LegalConsent>(communityJson):null;
RequireLegalConsent(consent);previouslyConsented=true;token=d.RootElement.GetProperty("token").GetString()!;
if(!(await LegalPolicies()).Matches(consent))throw new LegalConsentRequiredException("用户协议或隐私政策已更新,请阅读并重新勾选后登录");
using var me=await Request("/user/me");SetAccount(me.RootElement.GetProperty("account"));
#if COMMUNITY_APP
VerifiedAt=DateTime.UtcNow;await SaveCache();
#else
await RefreshLicense();EnsureActivated();
#endif
return true;
}
catch(LegalConsentRequiredException){if(version==Volatile.Read(ref generation))ClearSession();throw;}
#if !COMMUNITY_APP
catch (ActivationRequiredException)
{ if (version == Volatile.Read(ref generation)) await Logout(); throw; }
#endif
catch (InvalidOperationException ex) when (ex.InnerException is HttpRequestException or TaskCanceledException)
{ var restored = previouslyConsented&&version == Volatile.Read(ref generation) && await RestoreCache(expectedAccount); if (!restored && version == Volatile.Read(ref generation)) ClearSession(); return restored; }
catch { if (version == Volatile.Read(ref generation)) ClearSession(); return false; }
}
private void SetAccount(JsonElement a) { AccountId = a.GetProperty("id").GetString()!; Name = a.GetProperty("name").GetString()!; Username = a.GetProperty("username").GetString()!; Role = a.GetProperty("role").GetString() ?? "user"; }
#if !COMMUNITY_APP
private void EnsureActivated()
{ if (!Licensed || DateTime.UtcNow >= ExpiresAt) throw new ActivationRequiredException(Username); }
#endif
public void RequireAccess()
{
#if COMMUNITY_APP
if(Locked)throw new InvalidOperationException("账户已锁定,请先解锁");
if(AccountId.Length==0||token.Length==0)throw new InvalidOperationException("请先登录社群账户");
#else
RequireLicense();
#endif
}
public Task<JsonDocument> AdminRequest(string path, object? data = null) { if (!IsAdmin) throw new InvalidOperationException("需要管理员权限"); return Request("/admin" + path, data); }
private static readonly JsonSerializerOptions communityJson = new(JsonSerializerDefaults.Web);
#if !ACCOUNTING_APP
public async Task<T> CommunityRequest<T>(string path, object? data = null)
{
RequireAccess(); using var result = await Request("/community" + path, data);
return result.RootElement.Deserialize<T>(communityJson) ?? throw new InvalidOperationException("服务器返回了无效社群数据");
}
private static void MediaOriginHeaders(HttpRequestMessage request,string kind,string source,DateTimeOffset? createdAt)
{
if(kind is not ("IMAGE" or "VIDEO"))return;request.Headers.Add("X-Media-Source",source);
if(createdAt is {} stamp)request.Headers.Add("X-Media-Created-At",stamp.ToUniversalTime().ToString("O"));
}
public async Task<JiDangJia.Contracts.CommunityMedia> UploadMedia(byte[] bytes,string kind,string uploadId,string source="LOCAL",DateTimeOffset? createdAt=null,bool forChat=false)
{
RequireAccess();var version=Volatile.Read(ref generation);
using var request=new HttpRequestMessage(HttpMethod.Post,ServerUrl+"/api/community/media");request.Headers.Authorization=new("Bearer",token);request.Headers.Add("X-Device-Id",DeviceId);request.Headers.Add("X-Media-Kind",kind);request.Headers.Add("X-Upload-Id",uploadId);request.Content=new ByteArrayContent(bytes);
MediaOriginHeaders(request,kind,source,createdAt);
if(forChat)request.Headers.Add("X-Media-Purpose","CHAT");
using var cancel=new CancellationTokenSource(TimeSpan.FromSeconds(120));using var response=await http.SendAsync(request,cancel.Token);if(version!=Volatile.Read(ref generation)||Locked)throw new OperationCanceledException("账户已切换");
var responseText=await response.Content.ReadAsStringAsync(cancel.Token);if(version!=Volatile.Read(ref generation)||Locked)throw new OperationCanceledException("账户已切换");
if(response.StatusCode==System.Net.HttpStatusCode.Unauthorized)ClearSession();using var data=JsonDocument.Parse(responseText);
if(!response.IsSuccessStatusCode)throw new InvalidOperationException(data.RootElement.TryGetProperty("error",out var error)?error.GetString():"媒体上传失败");
return data.RootElement.Deserialize<JiDangJia.Contracts.CommunityMedia>(communityJson)??throw new InvalidOperationException("媒体数据无效");
}
public async Task<byte[]> DownloadMedia(string id,CancellationToken ct=default)
{
RequireAccess();if(!System.Text.RegularExpressions.Regex.IsMatch(id,"^[a-f0-9]{32}$"))throw new ArgumentException("媒体编号无效");var version=Volatile.Read(ref generation);
#if COMMUNITY_APP
var local=await CommunityChatArchive.ReadMedia(id);if(version!=Volatile.Read(ref generation)||Locked)throw new OperationCanceledException("账户已切换");if(local is not null)return local;
#endif
using var request=new HttpRequestMessage(HttpMethod.Get,ServerUrl+"/api/community/media/"+id);request.Headers.Authorization=new("Bearer",token);request.Headers.Add("X-Device-Id",DeviceId);
using var response=await http.SendAsync(request,ct);if(version!=Volatile.Read(ref generation)||Locked)throw new OperationCanceledException("账户已切换");
if(response.StatusCode==System.Net.HttpStatusCode.Unauthorized)ClearSession();if(response.StatusCode==System.Net.HttpStatusCode.Gone)throw new InvalidOperationException("本机未保存此附件,服务器保留期已过");if(!response.IsSuccessStatusCode)throw new InvalidOperationException("此媒体已不可用或没有读取权限");var bytes=await response.Content.ReadAsByteArrayAsync(ct);if(version!=Volatile.Read(ref generation)||Locked)throw new OperationCanceledException("账户已切换");
#if COMMUNITY_APP
CommunityChatArchive.SaveMedia(id,bytes);
#endif
return bytes;
}
internal Dictionary<string,string> MediaHeaders()
{RequireAccess();return new(){["Authorization"]="Bearer "+token,["X-Device-Id"]=DeviceId};}
public async Task<JiDangJia.Contracts.CommunityMedia> UploadRecommendation(Stream stream,string kind,string uploadId,CancellationToken ct=default,string source="LOCAL",DateTimeOffset? createdAt=null)
{
RequireAccess();if(!IsAdmin)throw new InvalidOperationException("推荐内容由管理员发布");int version=Volatile.Read(ref generation);
using var request=new HttpRequestMessage(HttpMethod.Post,ServerUrl+"/api/admin/community/media");request.Headers.Authorization=new("Bearer",token);request.Headers.Add("X-Device-Id",DeviceId);request.Headers.Add("X-Media-Kind",kind);request.Headers.Add("X-Upload-Id",uploadId);request.Content=new StreamContent(stream);
MediaOriginHeaders(request,kind,source,createdAt);
using var streaming=new HttpClient{Timeout=Timeout.InfiniteTimeSpan};using var response=await streaming.SendAsync(request,ct);if(version!=Volatile.Read(ref generation)||Locked)throw new OperationCanceledException("账户已切换");
using var data=JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct));if(version!=Volatile.Read(ref generation)||Locked)throw new OperationCanceledException("账户已切换");if(response.StatusCode==System.Net.HttpStatusCode.Unauthorized)ClearSession();if(!response.IsSuccessStatusCode)throw new InvalidOperationException(data.RootElement.TryGetProperty("error",out var error)?error.GetString():"媒体上传失败");
return data.RootElement.Deserialize<JiDangJia.Contracts.CommunityMedia>(new JsonSerializerOptions(JsonSerializerDefaults.Web))??throw new InvalidOperationException("媒体数据无效");
}
#endif
public async Task<JiDangJia.Contracts.AppContent> GetContent()
{
RequireAccess();using var result=await Request("/content");
return result.RootElement.Deserialize<JiDangJia.Contracts.AppContent>(communityJson)??throw new InvalidOperationException("服务器内容数据无效");
}
public async Task<AppContent> GetPublicContent()
{
using var result=await Request("/public/content",auth:false);
return result.RootElement.Deserialize<AppContent>(communityJson)??throw new InvalidOperationException("服务器公开信息无效");
}
#if !COMMUNITY_APP
public async Task RefreshLicense()
{ using var d = await Request("/user/license?deviceId=" + DeviceId); UpdateLicense(d.RootElement); await SaveCache(); }
public async Task Activate(string code)
{ using var d = await Request("/user/activate", new { deviceId = DeviceId, code }); UpdateLicense(d.RootElement); await SaveCache(); }
private void UpdateLicense(JsonElement result)
{ Permanent=result.TryGetProperty("permanent",out var p)&&p.GetBoolean();Licensed = result.GetProperty("active").GetBoolean(); ExpiresAt = result.TryGetProperty("expiresAt", out var e) && e.ValueKind == JsonValueKind.String ? e.GetDateTime().ToUniversalTime() : DateTime.MinValue; VerifiedAt = DateTime.UtcNow; }
public void RequireLicense()
{
if(Locked)throw new InvalidOperationException("账户已锁定,请先解锁");if (!Licensed || DateTime.UtcNow >= ExpiresAt || DateTime.UtcNow - VerifiedAt > TimeSpan.FromHours(24)) throw new InvalidOperationException("授权未激活、已到期或需要联网校验,请在设置中的账户授权页更新。");
}
private Task SaveCache() => SecureStorage.Default.SetAsync("verified_license", JsonSerializer.Serialize(new { server = ServerUrl, device = DeviceId, account = new { id = AccountId, username = Username, name = Name, role = Role }, licensed = Licensed, expiresAt = ExpiresAt, verifiedAt = VerifiedAt }));
private async Task<bool> RestoreCache(string expectedAccount)
{
try
{
var saved = await SecureStorage.Default.GetAsync("verified_license"); if (saved is null) return false;
using var doc = JsonDocument.Parse(saved); var d = doc.RootElement;
var verified = d.GetProperty("verifiedAt").GetDateTime().ToUniversalTime(); var expires = d.GetProperty("expiresAt").GetDateTime().ToUniversalTime();
if (expectedAccount.Length == 0 || d.GetProperty("account").GetProperty("id").GetString() != expectedAccount || d.GetProperty("server").GetString() != ServerUrl || d.GetProperty("device").GetString() != DeviceId || !d.GetProperty("licensed").GetBoolean() || DateTime.UtcNow >= expires || verified > DateTime.UtcNow.AddMinutes(5) || DateTime.UtcNow - verified > TimeSpan.FromHours(24)) return false;
SetAccount(d.GetProperty("account")); VerifiedAt = verified; ExpiresAt = expires; Licensed = true;Permanent=expires.Year==9999; return true;
}
catch { return false; }
}
#else
public async Task RefreshAccount(){using var me=await Request("/user/me");SetAccount(me.RootElement.GetProperty("account"));VerifiedAt=DateTime.UtcNow;await SaveCache();}
private Task SaveCache()=>SecureStorage.Default.SetAsync("community_account_cache",JsonSerializer.Serialize(new{server=ServerUrl,device=DeviceId,account=new{id=AccountId,username=Username,name=Name,role=Role},verifiedAt=VerifiedAt}));
private async Task<bool> RestoreCache(string expectedAccount)
{
try{
var saved=await SecureStorage.Default.GetAsync("community_account_cache");if(saved is null)return false;
using var doc=JsonDocument.Parse(saved);var d=doc.RootElement;var verified=d.GetProperty("verifiedAt").GetDateTime().ToUniversalTime();
if(expectedAccount.Length==0||d.GetProperty("account").GetProperty("id").GetString()!=expectedAccount||d.GetProperty("server").GetString()!=ServerUrl||d.GetProperty("device").GetString()!=DeviceId||verified>DateTime.UtcNow.AddMinutes(5)||DateTime.UtcNow-verified>TimeSpan.FromHours(24))return false;
SetAccount(d.GetProperty("account"));VerifiedAt=verified;return true;
}catch{return false;}
}
#endif
private void ClearSession() { AppNotifications.Stop();
#if !ACCOUNTING_APP
Views.CommunityVideo.StopAll();
#endif
Interlocked.Increment(ref generation);token="";Locked=false;AccountId="";Role="user";Name="";Username="";VerifiedAt=default;
#if !COMMUNITY_APP
Permanent=false;Licensed=false;ExpiresAt=default;
#endif
SecureStorage.Default.Remove("server_session");SecureStorage.Default.Remove("verified_license");SecureStorage.Default.Remove("community_account_cache");}
public async Task ChangePassword(string oldPassword, string password) { using var d = await Request("/user/password", new { oldPassword, password }); await Logout(false); }
public async Task Logout(bool callServer = true)
{ try { if (callServer && token.Length > 0) { using var d = await Request("/user/logout", new { }); } } catch (InvalidOperationException) { } finally { ClearSession(); } }
}