using System.Text.Json;
using JiDangJia.Contracts;
using JiDangJia.Messaging;
namespace JiDangJia.Services;
public static class CommunityChatArchive
{
private static readonly object gate=new();
private static readonly SemaphoreSlim syncing=new(1,1);
private static readonly HttpClient http=new(){Timeout=TimeSpan.FromSeconds(25)};
private static LocalChatStore? store;
private static CancellationTokenSource lifetime=new();
private static int generation;
public static string LastError{get;private set;}="";
public static bool MoreMessages{get;private set;}
private static LocalChatStore Store(string account,string server,int stamp)
{
lock(gate)
{
if(stamp!=generation)throw new OperationCanceledException("聊天账户已切换");
if(store is null||store.AccountId!=account||store.Server!=server.TrimEnd('/'))
{
// Keep the existing per-account files after the production IP move.
// Old IP is an on-device archive key only, never an HTTP destination.
string? archiveServer=server=="http://115.159.155.99:5189"?"http://175.178.121.98:5189":null;
store?.Deactivate();store=new LocalChatStore(FileSystem.AppDataDirectory,account,server,archiveServer:archiveServer);
}
return store;
}
}
public static LocalChatStore Current
{
get{int stamp=Volatile.Read(ref generation);var auth=AuthClient.Current;auth.RequireAccess();return Store(auth.AccountId,auth.ServerUrl,stamp);}
}
public static void Stop()
{
lock(gate){generation++;lifetime.Cancel();lifetime.Dispose();lifetime=new();store?.Deactivate();store=null;LastError="";MoreMessages=false;}
}
public static async Task Sync(CancellationToken ct=default)
{
if(AccountDataClear.InProgress||!await syncing.WaitAsync(0,ct))return;
try
{
int stamp;CancellationToken ownerToken;lock(gate){stamp=generation;ownerToken=lifetime.Token;}
string? saved=await SecureStorage.Default.GetAsync("server_session");if(saved is null)return;
using var document=JsonDocument.Parse(saved);var session=document.RootElement;
string account=session.GetProperty("accountId").GetString()??"",server=session.GetProperty("server").GetString()??"",token=session.GetProperty("token").GetString()??"";
if(server!=ServerSettings.BaseUrl||token.Length!=64||!System.Text.RegularExpressions.Regex.IsMatch(account,"^[a-f0-9]{32}$")||stamp!=Volatile.Read(ref generation))return;
var local=Store(account,server,stamp);string device=Preferences.Default.Get("device_id","");if(device.Length==0)return;
using var cancel=CancellationTokenSource.CreateLinkedTokenSource(ct,ownerToken);cancel.CancelAfter(TimeSpan.FromSeconds(45));
var client=new ChatSyncClient(local,http,token,device,()=>stamp==Volatile.Read(ref generation)&&!AccountDataClear.InProgress);
var result=await Task.Run(()=>client.Synchronize(cancel.Token),cancel.Token);if(stamp==Volatile.Read(ref generation)){MoreMessages=result.MoreMessages;LastError=result.Legacy?"正在兼容旧版后台同步。待消息和附件保存完成后,再升级后台启用到期清理。":"";}
}
catch(OperationCanceledException){ }
catch(Exception ex)when(ex is HttpRequestException or IOException or UnauthorizedAccessException or InvalidOperationException or JsonException or KeyNotFoundException or System.Security.Cryptography.CryptographicException or Microsoft.Data.Sqlite.SqliteException)
{LastError="暂时无法同步,本机已保存的消息可以继续查看。";}
finally{syncing.Release();}
}
public static void SaveSent(ChatMessage message,CommunityAccount peer)=>Current.SaveSent(message,peer);
public static Task<byte[]?> ReadMedia(string id)
{
var local=Current;return Task.Run(()=>local.ReadMedia(id));
}
public static void SaveMedia(string id,byte[] bytes)
{
var local=Current;if(local.KnowsMedia(id))local.SaveMedia(id,bytes);
}
}
using System.Text.Json;
using JiDangJia.Contracts;
using JiDangJia.Messaging;
namespace JiDangJia.Services;
public static class CommunityChatArchive
{
private static readonly object gate=new();
private static readonly SemaphoreSlim syncing=new(1,1);
private static readonly HttpClient http=new(){Timeout=TimeSpan.FromSeconds(25)};
private static LocalChatStore? store;
private static CancellationTokenSource lifetime=new();
private static int generation;
public static string LastError{get;private set;}="";
public static bool MoreMessages{get;private set;}
private static LocalChatStore Store(string account,string server,int stamp)
{
lock(gate)
{
if(stamp!=generation)throw new OperationCanceledException("聊天账户已切换");
if(store is null||store.AccountId!=account||store.Server!=server.TrimEnd('/'))
{
// Keep the existing per-account files after the production IP move.
// Old IP is an on-device archive key only, never an HTTP destination.
string? archiveServer=server=="http://115.159.155.99:5189"?"http://175.178.121.98:5189":null;
store?.Deactivate();store=new LocalChatStore(FileSystem.AppDataDirectory,account,server,archiveServer:archiveServer);
}
return store;
}
}
public static LocalChatStore Current
{
get{int stamp=Volatile.Read(ref generation);var auth=AuthClient.Current;auth.RequireAccess();return Store(auth.AccountId,auth.ServerUrl,stamp);}
}
public static void Stop()
{
lock(gate){generation++;lifetime.Cancel();lifetime.Dispose();lifetime=new();store?.Deactivate();store=null;LastError="";MoreMessages=false;}
}
public static async Task Sync(CancellationToken ct=default)
{
if(AccountDataClear.InProgress||!await syncing.WaitAsync(0,ct))return;
try
{
int stamp;CancellationToken ownerToken;lock(gate){stamp=generation;ownerToken=lifetime.Token;}
string? saved=await SecureStorage.Default.GetAsync("server_session");if(saved is null)return;
using var document=JsonDocument.Parse(saved);var session=document.RootElement;
string account=session.GetProperty("accountId").GetString()??"",server=session.GetProperty("server").GetString()??"",token=session.GetProperty("token").GetString()??"";
if(server!=ServerSettings.BaseUrl||token.Length!=64||!System.Text.RegularExpressions.Regex.IsMatch(account,"^[a-f0-9]{32}$")||stamp!=Volatile.Read(ref generation))return;
var local=Store(account,server,stamp);string device=Preferences.Default.Get("device_id","");if(device.Length==0)return;
using var cancel=CancellationTokenSource.CreateLinkedTokenSource(ct,ownerToken);cancel.CancelAfter(TimeSpan.FromSeconds(45));
var client=new ChatSyncClient(local,http,token,device,()=>stamp==Volatile.Read(ref generation)&&!AccountDataClear.InProgress);
var result=await Task.Run(()=>client.Synchronize(cancel.Token),cancel.Token);if(stamp==Volatile.Read(ref generation)){MoreMessages=result.MoreMessages;LastError=result.Legacy?"正在兼容旧版后台同步。待消息和附件保存完成后,再升级后台启用到期清理。":"";}
}
catch(OperationCanceledException){ }
catch(Exception ex)when(ex is HttpRequestException or IOException or UnauthorizedAccessException or InvalidOperationException or JsonException or KeyNotFoundException or System.Security.Cryptography.CryptographicException or Microsoft.Data.Sqlite.SqliteException)
{LastError="暂时无法同步,本机已保存的消息可以继续查看。";}
finally{syncing.Release();}
}
public static void SaveSent(ChatMessage message,CommunityAccount peer)=>Current.SaveSent(message,peer);
public static Task<byte[]?> ReadMedia(string id)
{
var local=Current;return Task.Run(()=>local.ReadMedia(id));
}
public static void SaveMedia(string id,byte[] bytes)
{
var local=Current;if(local.KnowsMedia(id))local.SaveMedia(id,bytes);
}
}