Add Google mailbox lifecycle controls and guarded sync recovery

This commit is contained in:
wolf-demon
2026-09-16 15:18:22 +01:00
parent 7fcf51c900
commit bc7cbc1492
20 changed files with 314 additions and 33 deletions
+2 -1
View File
@@ -68,7 +68,7 @@ public sealed class AutoReplyWork(IStore store,IConfiguration config)
else
{
var rule=(await store.Get<AutoReplyRule>(message.HotelId,result.RuleId))!;
message.Delivery=new Delivery{Automatic=true,AutoDay=DateTime.UtcNow.ToString("yyyy-MM-dd"),AutoRuleId=rule.Id,AutoRuleVersion=rule.Version,AutoKnowledgeId=rule.KnowledgeId,AutoKnowledgeVersion=rule.KnowledgeVersion,AutoEpoch=hotel.AutoReplyEpoch,Recipient=message.ReplyAddress,Body=result.Body+"\n\n"+hotel.Signature,ApprovedBy=rule.ApprovedBy};
message.Delivery=new Delivery{MailboxEpoch=box!.ConnectionEpoch,Automatic=true,AutoDay=DateTime.UtcNow.ToString("yyyy-MM-dd"),AutoRuleId=rule.Id,AutoRuleVersion=rule.Version,AutoKnowledgeId=rule.KnowledgeId,AutoKnowledgeVersion=rule.KnowledgeVersion,AutoEpoch=hotel.AutoReplyEpoch,Recipient=message.ReplyAddress,Body=result.Body+"\n\n"+hotel.Signature,ApprovedBy=rule.ApprovedBy};
bool valid=await CanDeliver(store,config,message);
try{_=ReplyMime.Build(message,box!);}catch{valid=false;}
if(valid&&await Claim(message)){message.Draft=message.Delivery.Body;message.DraftSources=[result.KnowledgeId];message.AutoReplyDetail="Queued the approved FAQ answer for automatic delivery.";}
@@ -102,3 +102,4 @@ public sealed class AutoReplyWork(IStore store,IConfiguration config)
+1
View File
@@ -6,6 +6,7 @@ public static class Demo
var hotel = new Hotel { Name = "The Willow House", Signature = "Warm regards,\nThe Willow House team" }; hotel.HotelId = hotel.Id;
var user = new StaffUser { HotelId = hotel.Id, Name = "Alex Morgan", Email = hotel.Id + "@example.invalid" };
await store.Insert(hotel); await store.Insert(user);
await store.Insert(new Mailbox{HotelId=hotel.Id,Email="reservations@example.invalid",Status="NeedsReconnect",SyncErrorCode="ReconnectRequired",SyncError="Sample recovery state: a hotel owner would reconnect Google here. No real mailbox is connected.",LastSyncAt=DateTime.UtcNow.AddHours(-2),LastAttemptAt=DateTime.UtcNow.AddMinutes(-5)});
var questions = new[] {
("Emma Wilson", "A little question before our weekend stay", "Hello! We're looking forward to staying with you on Friday. Is there somewhere to park our car, and do we need to book a space?\n\nMany thanks,\nEmma", "Parking", "Hello Emma,\n\nWe're looking forward to welcoming you on Friday. Complimentary parking is available in our courtyard, subject to availability. There is no need to reserve a space.\n\nWarm regards,\nThe Willow House team"),
("James & Sophie", "Arriving a little earlier on Saturday", "Hi there, our train gets in at 12:30. Would it be possible to leave our bags with you before check-in? Thank you!", "Arrival", ""),
+64 -12
View File
@@ -1,7 +1,15 @@
using System.Text;
using System.Text.Json;
using System.Net;
using System.Security.Cryptography;
using Microsoft.AspNetCore.DataProtection;
namespace GuestOps.Web;
public sealed class GoogleFailure(string kind,HttpStatusCode status,TimeSpan? retryAfter=null):Exception("Google request failed: "+kind)
{
public string Kind {get;}=kind;
public HttpStatusCode Status {get;}=status;
public TimeSpan? RetryAfter {get;}=retryAfter;
}
public sealed class GoogleMailbox(HttpClient http, IConfiguration config, IStore store, IDataProtectionProvider protection)
{
@@ -18,44 +26,66 @@ public sealed class GoogleMailbox(HttpClient http, IConfiguration config, IStore
{
data["client_id"] = ClientId; data["client_secret"] = ClientSecret;
using var response = await http.PostAsync("https://oauth2.googleapis.com/token", new FormUrlEncodedContent(data), ct);
response.EnsureSuccessStatusCode();
await Check(response,true,ct);
return JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct)).RootElement.Clone();
}
async Task<JsonElement> Read(string path, string token, CancellationToken ct = default)
{
using var request = new HttpRequestMessage(HttpMethod.Get, "https://gmail.googleapis.com/gmail/v1/users/me/" + path);
request.Headers.Authorization = new("Bearer", token);
using var response = await http.SendAsync(request, ct); response.EnsureSuccessStatusCode();
using var response = await http.SendAsync(request, ct); await Check(response,false,ct);
return JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct)).RootElement.Clone();
}
public async Task Connect(string hotel, string code)
static async Task Check(HttpResponseMessage response,bool token,CancellationToken ct)
{
if(response.IsSuccessStatusCode)return;
var reason="";try{using var json=JsonDocument.Parse(await response.Content.ReadAsStringAsync(ct));if(json.RootElement.TryGetProperty("error",out var error)){if(error.ValueKind==JsonValueKind.String)reason=error.GetString()??"";else if(error.TryGetProperty("errors",out var errors)&&errors.GetArrayLength()>0&&errors[0].TryGetProperty("reason",out var value))reason=value.GetString()??"";}}catch(JsonException){}
var kind=token?(reason=="invalid_grant"?"ReconnectRequired":reason=="invalid_client"||response.StatusCode==HttpStatusCode.Unauthorized?"Configuration":"Temporary"):
response.StatusCode==HttpStatusCode.Unauthorized?"ReconnectRequired":response.StatusCode==HttpStatusCode.NotFound?"NotFound":response.StatusCode==HttpStatusCode.BadRequest?"BadRequest":response.StatusCode==HttpStatusCode.Forbidden&&reason is not ("rateLimitExceeded" or "userRateLimitExceeded")?"AccessDenied":"Temporary";
var delay=response.Headers.RetryAfter?.Delta??(response.Headers.RetryAfter?.Date-DateTimeOffset.UtcNow);
throw new GoogleFailure(kind,response.StatusCode,delay);
}
public async Task Connect(string hotel, string code,DateTime? startedAt=null,string expectedEmail="")
{
if (string.IsNullOrWhiteSpace(code)) throw new InvalidOperationException("No authorization code.");
var tokens = await Token(new() { ["code"] = code, ["redirect_uri"] = Callback, ["grant_type"] = "authorization_code" });
var profile = await Read("profile", tokens.GetProperty("access_token").GetString()!);
var email = profile.GetProperty("emailAddress").GetString()!.ToLowerInvariant();
if(!Input.Email(email)||expectedEmail.Length>0&&email!=expectedEmail)throw new InvalidOperationException("Choose the expected Google mailbox.");
var prior = (await store.List<Mailbox>(hotel)).SingleOrDefault(x => x.Email == email);
if(prior?.ConnectionChangedAt>startedAt.GetValueOrDefault(DateTime.MinValue))throw new MailboxConflict();
var mailbox = prior ?? new Mailbox { HotelId = hotel, Email = email };
var version=mailbox.Version;
// No token reuse across hotels. Mongo's unique mailbox-email index prevents
// accidental connection of one shared mailbox to two hotel workspaces.
mailbox.ProtectedRefreshToken = protector.Protect(tokens.GetProperty("refresh_token").GetString()!);
mailbox.CanSend = tokens.TryGetProperty("scope", out var scopes) && scopes.GetString()!.Split(' ').Contains("https://www.googleapis.com/auth/gmail.send");
mailbox.Status = "Connected"; mailbox.SyncError = "";
await store.SaveMailbox(mailbox);
if(string.IsNullOrWhiteSpace(tokens.GetProperty("refresh_token").GetString()))throw new InvalidOperationException("Google did not return offline access.");
if(!tokens.TryGetProperty("scope",out var granted)||!granted.GetString()!.Split(' ').Contains("https://www.googleapis.com/auth/gmail.readonly"))throw new InvalidOperationException("Read permission is required.");
mailbox.Status = "Connected"; mailbox.SyncError = "";mailbox.SyncErrorCode="";mailbox.NextAttemptAt=null;mailbox.FailureCount=0;mailbox.PageToken="";
mailbox.ConnectionEpoch=Guid.NewGuid().ToString("N");mailbox.ConnectionChangedAt=DateTime.UtcNow;mailbox.Version++;
if(!(prior==null?await store.TryInsertMailbox(mailbox):await store.Replace(hotel,mailbox.Id,version,mailbox)))throw new MailboxConflict();
}
public async Task Sync(Mailbox mailbox, CancellationToken ct)
{
var tokens = await Token(new() { ["refresh_token"] = protector.Unprotect(mailbox.ProtectedRefreshToken), ["grant_type"] = "refresh_token" }, ct);
var token = tokens.GetProperty("access_token").GetString()!;
if(mailbox.NextAttemptAt>DateTime.UtcNow||!await MailboxManagement.Current(store,mailbox))return;
mailbox.LastAttemptAt=DateTime.UtcNow;await store.SaveSync(mailbox);
var token = await AccessToken(mailbox,ct);
var after = new DateTimeOffset(mailbox.WindowStart).ToUnixTimeSeconds();
var before = new DateTimeOffset(mailbox.WindowEnd).ToUnixTimeSeconds();
var query = Uri.EscapeDataString($"in:inbox after:{after} before:{before}");
var path = "messages?maxResults=25&q=" + query + (mailbox.PageToken.Length > 0 ? "&pageToken=" + Uri.EscapeDataString(mailbox.PageToken) : "");
var page = await Read(path, token, ct);
JsonElement page;
try{page=await Read(path, token, ct);}
catch(GoogleFailure ex) when(ex.Status==HttpStatusCode.BadRequest&&mailbox.PageToken.Length>0)
{
mailbox.PageToken="";mailbox.SyncErrorCode="CheckpointRestart";mailbox.SyncError="Google rejected the saved page. The worker will restart this import window without duplicating messages.";mailbox.NextAttemptAt=DateTime.UtcNow.AddMinutes(1);await store.SaveSync(mailbox);return;
}
if (page.TryGetProperty("messages", out var items)) foreach (var item in items.EnumerateArray())
{
if(!await MailboxManagement.Current(store,mailbox))return;
var id = item.GetProperty("id").GetString()!;
var message = await Read("messages/" + Uri.EscapeDataString(id) + "?format=full", token, ct);
JsonElement message;try{message=await Read("messages/" + Uri.EscapeDataString(id) + "?format=full", token, ct);}catch(GoogleFailure ex) when(ex.Status==HttpStatusCode.NotFound){continue;}
var payload = message.GetProperty("payload");
string Header(string name) => payload.GetProperty("headers").EnumerateArray().Where(x => string.Equals(x.GetProperty("name").GetString(), name, StringComparison.OrdinalIgnoreCase)).Select(x => x.GetProperty("value").GetString()).FirstOrDefault() ?? "";
var auto = Header("Auto-Submitted");
@@ -65,11 +95,12 @@ public sealed class GoogleMailbox(HttpClient http, IConfiguration config, IStore
row.ReplyAddress = ReplyMime.Address(Header("Reply-To").Length > 0 ? Header("Reply-To") : Header("From"));
row.RfcMessageId = Header("Message-ID");
row.AutoReplyHeadersEligible = FaqMatcher.HeadersEligible(payload,mailbox.Email);
if(!await MailboxManagement.Current(store,mailbox))return;
await store.Import(row); // deduplicated before advancing the page checkpoint
}
mailbox.PageToken = page.TryGetProperty("nextPageToken", out var next) ? next.GetString()! : "";
if (mailbox.PageToken.Length == 0) { mailbox.WindowStart = mailbox.WindowEnd.AddMinutes(-5); mailbox.WindowEnd = DateTime.UtcNow; }
mailbox.LastSyncAt = DateTime.UtcNow; mailbox.SyncError = "";
mailbox.LastSyncAt = DateTime.UtcNow; mailbox.SyncError = "";mailbox.SyncErrorCode="";mailbox.FailureCount=0;mailbox.NextAttemptAt=null;
await store.SaveSync(mailbox);
}
static string PlainText(JsonElement payload)
@@ -83,8 +114,29 @@ public sealed class GoogleMailbox(HttpClient http, IConfiguration config, IStore
}
public async Task<string> AccessToken(Mailbox mailbox, CancellationToken ct)
{
var token = await Token(new() { ["refresh_token"] = protector.Unprotect(mailbox.ProtectedRefreshToken), ["grant_type"] = "refresh_token" }, ct);
return token.GetProperty("access_token").GetString()!;
if(!await MailboxManagement.Current(store,mailbox))throw new MailboxConflict();
try
{
var token = await Token(new() { ["refresh_token"] = protector.Unprotect(mailbox.ProtectedRefreshToken), ["grant_type"] = "refresh_token" }, ct);
return token.GetProperty("access_token").GetString()!;
}
catch(Exception ex) when(ex is CryptographicException || ex is GoogleFailure {Kind:"ReconnectRequired"}) {await RecordFailure(mailbox,ex);throw;}
}
public async Task RecordFailure(Mailbox mailbox,Exception ex)
{
if(ex is MailboxConflict)return;
mailbox.LastAttemptAt=DateTime.UtcNow;mailbox.FailureCount=Math.Min(mailbox.FailureCount+1,20);
var kind=ex is GoogleFailure failure?failure.Kind:ex is CryptographicException?"ReconnectRequired":"Temporary";
mailbox.SyncErrorCode=kind;
if(kind=="ReconnectRequired") {mailbox.Status="NeedsReconnect";mailbox.NextAttemptAt=null;mailbox.SyncError="Google access is unavailable. Ask the hotel owner to reconnect this mailbox.";}
else
{
var seconds=kind is "Configuration" or "AccessDenied"?3600:Math.Min(3600,60*Math.Pow(2,mailbox.FailureCount-1));
if(ex is GoogleFailure g&&g.RetryAfter is {} delay)seconds=Math.Max(seconds,Math.Min(86400,delay.TotalSeconds));
mailbox.NextAttemptAt=DateTime.UtcNow.AddSeconds(seconds+Random.Shared.Next(0,31));
mailbox.SyncError=kind is "Configuration" or "AccessDenied"?"Google rejected the app configuration or permissions. Ask the administrator to review access. A later check is scheduled.":"Google synchronization is temporarily unavailable. The worker will retry automatically.";
}
await store.SaveSync(mailbox);
}
public async Task<bool> AutoReplyThreadUnchanged(Conversation message,string token,CancellationToken ct)
{
+47
View File
@@ -0,0 +1,47 @@
using System.Security.Claims;
namespace GuestOps.Web;
public sealed class MailboxConflict():Exception("The mailbox changed. Refresh its status and try again.");
public static class MailboxManagement
{
public static object View(Mailbox box)=>new {box.Id,box.Email,box.Status,box.Version,box.LastSyncAt,box.LastAttemptAt,box.NextAttemptAt,box.FailureCount,box.SyncError,box.SyncErrorCode,box.CanSend,catchingUp=box.PageToken.Length>0};
public static async Task<bool> Current(IStore store,Mailbox box)
{
var current=await store.Get<Mailbox>(box.HotelId,box.Id);return current?.Status=="Connected"&&current.Version==box.Version&&current.ProtectedRefreshToken==box.ProtectedRefreshToken;
}
public static async Task<bool> Change(IStore store,Mailbox box,long version,string action)
{
if(box.Version!=version)return false;
if(action=="disconnect")
{
if(box.Status=="Disconnected")return false;
box.Status="Disconnected";box.ProtectedRefreshToken="";box.CanSend=false;box.ConnectionEpoch=Guid.NewGuid().ToString("N");box.ConnectionChangedAt=DateTime.UtcNow;box.SyncError="Disconnected from GuestOps. Reconnect to resume.";box.SyncErrorCode="Disconnected";box.NextAttemptAt=null;
}
else if(action=="retry")
{
if(box.Status!="Connected"||box.NextAttemptAt>DateTime.UtcNow)return false;
// Retry the same window from its first page; duplicate imports remain idempotent.
box.PageToken="";box.NextAttemptAt=null;box.SyncError="A fresh import pass is queued for the worker.";box.SyncErrorCode="RestartQueued";
}
else return false;
box.Version++;return await store.Replace(box.HotelId,box.Id,version,box);
}
public static void Map(RouteGroupBuilder api,bool preview)
{
api.MapPost("/mailboxes/{id}/{action}",async(string id,string action,VersionInput input,HttpContext c,IStore store,GoogleMailbox google)=>
{
var box=await store.Get<Mailbox>(Session.Hotel(c),id);if(box==null)return Results.NotFound();
if(preview)return Results.BadRequest(new{error="Real mailbox changes are unavailable in preview."});
if(action=="reconnect")
{
if(!google.Configured)return Results.BadRequest(new{error="Ask the administrator to configure Google first."});
if(box.Version!=input.Version)return Input.Conflict();
var state=new OAuthRequest{Id=Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32)),HotelId=box.HotelId,UserId=c.User.FindFirstValue(ClaimTypes.NameIdentifier)!,ExpectedEmail=box.Email,ExpiresAt=DateTime.UtcNow.AddMinutes(10)};
await store.Insert(state);return Results.Ok(new{url=google.AuthorizationUrl(state.Id)});
}
if(action is not ("disconnect" or "retry"))return Results.NotFound();
if(!await Change(store,box,input.Version,action))return Results.Conflict(new{error="The mailbox changed, needs reconnection, or is waiting for its retry time. Refresh the status."});
await Session.Audit(store,c,action=="disconnect"?"Disconnected Google mailbox from GuestOps":"Requested a fresh mailbox import pass");return Results.Ok(View(box));
}).RequireAuthorization("Owner").RequireRateLimiting("accounts");
}
}
+10
View File
@@ -71,6 +71,13 @@ public class Conversation : TenantDocument
}
public class Mailbox : TenantDocument
{
public long Version {get;set;}
public string ConnectionEpoch {get;set;}="";
public DateTime? ConnectionChangedAt {get;set;}
public DateTime? LastAttemptAt {get;set;}
public DateTime? NextAttemptAt {get;set;}
public int FailureCount {get;set;}
public string SyncErrorCode {get;set;}="";
public bool CanSend { get; set; }
public string Email { get; set; } = "";
public string ProtectedRefreshToken { get; set; } = "";
@@ -83,6 +90,8 @@ public class Mailbox : TenantDocument
}
public class OAuthRequest : TenantDocument
{
public DateTime StartedAt {get;set;}=DateTime.UtcNow;
public string ExpectedEmail {get;set;}="";
public string UserId { get; set; } = "";
public DateTime ExpiresAt { get; set; }
}
@@ -108,6 +117,7 @@ public record SendInput(long Version, string Recipient);
public record ReplyControlsInput(long Version, bool AiDraftsEnabled, bool StaffSendingEnabled);
public class Delivery
{
public string MailboxEpoch {get;set;}="";
public bool Automatic {get;set;}
public string AutoRuleId {get;set;}="";
public long AutoRuleVersion {get;set;}
+12 -5
View File
@@ -101,6 +101,8 @@ app.Use(async (ctx, next) =>
ctx.Response.Headers["Content-Security-Policy"] = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'";
if (ctx.Request.Path.StartsWithSegments("/api") || ctx.Request.Path.StartsWithSegments("/account")) ctx.Response.Headers.CacheControl = "no-store";
try { await next(); }
catch (MailboxConflict ex) { ctx.Response.StatusCode = 409; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); }
catch (GoogleFailure) { ctx.Response.StatusCode = 503; await ctx.Response.WriteAsJsonAsync(new { error = "Google could not complete this check. Review the mailbox status in Settings. No resend has been queued." }); }
catch (AccountInvalid ex) { ctx.Response.StatusCode = 400; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); }
catch (AccountConflict ex) { ctx.Response.StatusCode = 409; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); }
catch (PaymentInvalid ex) { ctx.Response.StatusCode = 400; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); }
@@ -144,7 +146,8 @@ var api = app.MapGroup("/api").RequireAuthorization();
PmsEndpoints.Map(api,preview);
PaymentEndpoints.Map(api,preview);
AutoReplyEndpoints.Map(api,preview);
TeamEndpoints.Map(app,api,preview);
TeamEndpoints.Map(app,api,preview);
MailboxManagement.Map(api,preview);
api.MapGet("/hotel", async (HttpContext c, CancellationToken _) => Results.Ok(await store.Get<Hotel>(Session.Hotel(c), Session.Hotel(c))));
api.MapPut("/hotel", async (SettingsInput input, HttpContext c) =>
{
@@ -191,7 +194,7 @@ api.MapPut("/knowledge/{id}", async (string id, KnowledgeInput input, HttpContex
await Session.Audit(store, c, "Updated hotel knowledge"); return Results.Ok(item);
}).RequireAuthorization("Owner");
api.MapGet("/activity", async (HttpContext c, CancellationToken _) => Results.Ok((await store.List<Activity>(Session.Hotel(c))).OrderByDescending(x => x.At).Take(100)));
api.MapGet("/mailboxes", async (HttpContext c, GoogleMailbox google, AiDrafts ai) => Results.Ok(new { configured = !preview && google.Configured, sendingConfigured = !preview && google.SendingConfigured, aiConfigured = !preview && ai.Configured, items = (await store.List<Mailbox>(Session.Hotel(c))).Select(x => new { x.Id, x.Email, x.Status, x.LastSyncAt, x.SyncError, x.CanSend }) }));
api.MapGet("/mailboxes", async (HttpContext c, GoogleMailbox google, AiDrafts ai) => Results.Ok(new { configured = !preview && google.Configured, sendingConfigured = !preview && google.SendingConfigured, aiConfigured = !preview && ai.Configured, items = (await store.List<Mailbox>(Session.Hotel(c))).Select(MailboxManagement.View) }));
api.MapPut("/reply-controls", async (ReplyControlsInput input, HttpContext c, GoogleMailbox google, AiDrafts ai) =>
{
if ((input.AiDraftsEnabled && (preview || !ai.Configured)) || (input.StaffSendingEnabled && (preview || !google.SendingConfigured))) return Results.BadRequest(new { error = "The administrator must configure this capability first." });
@@ -225,10 +228,10 @@ api.MapPost("/conversations/{id}/send", async (string id, SendInput input, HttpC
var item = await store.Get<Conversation>(Session.Hotel(c), id); if (item == null) return Results.NotFound();
if (item.Delivery != null) return Results.Conflict(new { error = "This message already has a delivery request. Refresh to see its status." });
var hotel = await store.Get<Hotel>(item.HotelId, item.HotelId); var mailbox = await store.Get<Mailbox>(item.HotelId, item.MailboxId);
if (preview || hotel?.StaffSendingEnabled != true || !google.SendingConfigured || mailbox?.CanSend != true) return Results.BadRequest(new { error = "Enable staff sending and reconnect Google with send permission first." });
if (preview || hotel?.StaffSendingEnabled != true || !google.SendingConfigured || mailbox?.CanSend != true || mailbox.Status != "Connected") return Results.BadRequest(new { error = "Enable staff sending and reconnect Google with send permission first." });
if (item.Version != input.Version) return Input.Conflict();
if (input.Recipient != item.ReplyAddress || string.IsNullOrWhiteSpace(item.ReplyAddress)) return Results.BadRequest(new { error = "The recipient must match the message's reply address." });
item.Delivery = new Delivery { Recipient = item.ReplyAddress, Body = item.Draft, ApprovedBy = c.User.FindFirstValue(ClaimTypes.NameIdentifier)! };
item.Delivery = new Delivery { MailboxEpoch=mailbox.ConnectionEpoch, Recipient = item.ReplyAddress, Body = item.Draft, ApprovedBy = c.User.FindFirstValue(ClaimTypes.NameIdentifier)! };
try { _ = ReplyMime.Build(item, mailbox); } catch { return Results.BadRequest(new { error = "This message lacks valid reply metadata or a saved draft. Reply in Gmail instead." }); }
item.Version++;
if (!await store.Replace(item.HotelId, item.Id, input.Version, item)) return Input.Conflict();
@@ -244,6 +247,9 @@ api.MapPost("/conversations/{id}/delivery/retry", async (string id, VersionInput
{
var item = await store.Get<Conversation>(Session.Hotel(c), id); if (item == null) return Results.NotFound();
if (preview || item.Delivery?.State != "Rejected" || item.Version != input.Version) return Input.Conflict();
var retryMailbox=await store.Get<Mailbox>(item.HotelId,item.MailboxId);
if(retryMailbox?.Status!="Connected"||!retryMailbox.CanSend)return Results.BadRequest(new{error="Reconnect the mailbox with sending permission first."});
item.Delivery.MailboxEpoch=retryMailbox.ConnectionEpoch;
item.Delivery.State = "Pending"; item.Delivery.UpdatedAt = DateTime.UtcNow; item.Version++;
if (!await store.Replace(item.HotelId, item.Id, input.Version, item)) return Input.Conflict();
await Session.Audit(store, c, "Retried a reply that had not reached Gmail sending"); return Results.Ok(item);
@@ -271,7 +277,7 @@ api.MapGet("/integrations/google/callback", async (HttpContext c, GoogleMailbox
var state = await store.ConsumeOAuth(c.Request.Query["state"].ToString(), Session.Hotel(c), c.User.FindFirstValue(ClaimTypes.NameIdentifier)!);
if (state == null) return Results.BadRequest(new { error = "The connection request expired. Start again from Settings." });
if (c.Request.Query.ContainsKey("error")) return Results.Redirect("/settings?google=cancelled");
try { await google.Connect(Session.Hotel(c), c.Request.Query["code"].ToString()); await Session.Audit(store, c, "Connected Google mailbox"); }
try { await google.Connect(Session.Hotel(c), c.Request.Query["code"].ToString(),state.StartedAt,state.ExpectedEmail); await Session.Audit(store, c, "Connected Google mailbox"); }
catch { return Results.Redirect("/settings?google=failed"); }
return Results.Redirect("/settings?google=connected");
}).RequireAuthorization("Owner");
@@ -298,3 +304,4 @@ namespace GuestOps.Web
}
+2 -1
View File
@@ -48,11 +48,12 @@ public sealed class ReplyDelivery(IStore store, GoogleMailbox google, IConfigura
{
var hotel = await store.Get<Hotel>(message.HotelId, message.HotelId);
var mailbox = await store.Get<Mailbox>(message.HotelId, message.MailboxId);
if (hotel?.StaffSendingEnabled != true || mailbox?.CanSend != true || mailbox.Status != "Connected" || !google.SendingConfigured) throw new InvalidOperationException("Sending disabled.");
if (hotel?.StaffSendingEnabled != true || mailbox?.CanSend != true || mailbox.Status != "Connected" || mailbox.ConnectionEpoch!=message.Delivery.MailboxEpoch || !google.SendingConfigured) throw new InvalidOperationException("Sending disabled or mailbox connection changed.");
if(!await AutoReplyWork.CanDeliver(store,config,message))throw new InvalidOperationException("Automatic approval no longer valid.");
raw = ReplyMime.Build(message, mailbox);
token = await google.AccessToken(mailbox, ct);
if(message.Delivery.Automatic&&(!await google.AutoReplyThreadUnchanged(message,token,ct)||!await AutoReplyWork.CanDeliver(store,config,message)))throw new InvalidOperationException("Automatic reply no longer eligible.");
if(!await MailboxManagement.Current(store,mailbox))throw new MailboxConflict();
ct.ThrowIfCancellationRequested();
}
catch { await Save("Rejected", "Nothing was sent. Check reply metadata, hotel controls and Google connection, then retry the approved reply."); return; }
+7 -3
View File
@@ -19,6 +19,7 @@ public interface IStore
Task<OAuthRequest?> ConsumeOAuth(string id, string hotel, string user);
Task<List<Mailbox>> Mailboxes();
Task SaveMailbox(Mailbox mailbox);
Task<bool> TryInsertMailbox(Mailbox mailbox);
Task SaveSync(Mailbox mailbox);
Task<bool> TryLease(string id, string owner);
Task ReleaseLease(string id, string owner);
@@ -81,7 +82,7 @@ public sealed class MongoStore : IStore
{
if (document.HotelId != hotel || document.Id != id) throw new InvalidOperationException("Invalid document scope.");
var versionFilter=Builders<T>.Filter.Eq("Version",version);
if(typeof(T)==typeof(StaffUser)&&version==0)versionFilter|=Builders<T>.Filter.Exists("Version",false);
if((typeof(T)==typeof(StaffUser)||typeof(T)==typeof(Mailbox))&&version==0)versionFilter|=Builders<T>.Filter.Exists("Version",false);
var result = await Collection<T>().ReplaceOneAsync(Scope<T>(hotel) & Builders<T>.Filter.Eq(x => x.Id, id) & versionFilter, document);
return result.ModifiedCount == 1;
}
@@ -97,9 +98,11 @@ public sealed class MongoStore : IStore
public async Task<OAuthRequest?> ConsumeOAuth(string id, string hotel, string user) => await Collection<OAuthRequest>().FindOneAndDeleteAsync(x => x.Id == id && x.HotelId == hotel && x.UserId == user && x.ExpiresAt > DateTime.UtcNow);
public Task<List<Mailbox>> Mailboxes() => Collection<Mailbox>().Find(x => x.Status == "Connected").ToListAsync();
public async Task SaveMailbox(Mailbox mailbox) => await Collection<Mailbox>().ReplaceOneAsync(x => x.HotelId == mailbox.HotelId && x.Id == mailbox.Id, mailbox, new ReplaceOptions { IsUpsert = true });
public async Task<bool> TryInsertMailbox(Mailbox mailbox){try{await Insert(mailbox);return true;}catch(MongoWriteException ex) when(ex.WriteError.Category==ServerErrorCategory.DuplicateKey){return false;}}
public async Task SaveSync(Mailbox mailbox) => await Collection<Mailbox>().UpdateOneAsync(
x => x.HotelId == mailbox.HotelId && x.Id == mailbox.Id && x.ProtectedRefreshToken == mailbox.ProtectedRefreshToken,
Builders<Mailbox>.Filter.Eq(x=>x.HotelId,mailbox.HotelId)&Builders<Mailbox>.Filter.Eq(x=>x.Id,mailbox.Id)&Builders<Mailbox>.Filter.Eq(x=>x.ProtectedRefreshToken,mailbox.ProtectedRefreshToken)&Builders<Mailbox>.Filter.Eq(x=>x.Status,"Connected")&(mailbox.Version==0?(Builders<Mailbox>.Filter.Eq(x=>x.Version,0)|Builders<Mailbox>.Filter.Exists("Version",false)):Builders<Mailbox>.Filter.Eq(x=>x.Version,mailbox.Version)),
Builders<Mailbox>.Update.Set(x => x.LastSyncAt, mailbox.LastSyncAt).Set(x => x.SyncError, mailbox.SyncError)
.Set(x=>x.Status,mailbox.Status).Set(x=>x.LastAttemptAt,mailbox.LastAttemptAt).Set(x=>x.NextAttemptAt,mailbox.NextAttemptAt).Set(x=>x.FailureCount,mailbox.FailureCount).Set(x=>x.SyncErrorCode,mailbox.SyncErrorCode)
.Set(x => x.PageToken, mailbox.PageToken).Set(x => x.WindowStart, mailbox.WindowStart).Set(x => x.WindowEnd, mailbox.WindowEnd));
public async Task<bool> TryLease(string id, string owner)
{
@@ -190,7 +193,8 @@ public sealed class PreviewStore : IStore
public Task<OAuthRequest?> ConsumeOAuth(string id, string hotel, string user) { lock(gate) { var x = rows.TryGetValue(Key<OAuthRequest>(id), out var raw) ? Clone<OAuthRequest>(raw) : null; if(x?.HotelId != hotel || x.UserId != user || x.ExpiresAt <= DateTime.UtcNow) return Task.FromResult<OAuthRequest?>(null); rows.TryRemove(Key<OAuthRequest>(id),out _); return Task.FromResult<OAuthRequest?>(x); } }
public Task<List<Mailbox>> Mailboxes() => Task.FromResult(new List<Mailbox>());
public Task SaveMailbox(Mailbox mailbox) => throw new InvalidOperationException("Real mailbox connections are unavailable in preview mode.");
public Task SaveSync(Mailbox mailbox) => throw new InvalidOperationException("Real mailbox connections are unavailable in preview mode.");
public Task<bool> TryInsertMailbox(Mailbox mailbox){lock(gate){if(rows.Where(x=>x.Key.StartsWith("Mailbox:")).Select(x=>Clone<Mailbox>(x.Value)).Any(x=>x.Email==mailbox.Email))return Task.FromResult(false);return Task.FromResult(rows.TryAdd(Key<Mailbox>(mailbox.Id),Json(mailbox)));}}
public Task SaveSync(Mailbox mailbox){lock(gate){if(rows.TryGetValue(Key<Mailbox>(mailbox.Id),out var raw)){var old=Clone<Mailbox>(raw);if(old.HotelId==mailbox.HotelId&&old.Version==mailbox.Version&&old.Status=="Connected"&&old.ProtectedRefreshToken==mailbox.ProtectedRefreshToken)rows[Key<Mailbox>(mailbox.Id)]=Json(mailbox);}return Task.CompletedTask;}}
public Task<bool> TryLease(string id, string owner) => Task.FromResult(false);
public Task ReleaseLease(string id, string owner) => Task.CompletedTask;
public async Task Import(Conversation message) { if (!(await List<Conversation>(message.HotelId)).Any(x => x.MailboxId == message.MailboxId && x.ProviderMessageId == message.ProviderMessageId)) await Insert(message); }
+4 -3
View File
@@ -31,7 +31,7 @@ sealed class MailboxWorker(IStore store, IServiceScopeFactory factory, ILogger<M
{
foreach (var mailbox in await store.Mailboxes())
{
if (!await store.TryLease(mailbox.Id, owner)) continue;
if (mailbox.NextAttemptAt > DateTime.UtcNow || !await store.TryLease(mailbox.Id, owner)) continue;
// Per-page deadline is shorter than the lease. Import is idempotent.
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken); deadline.CancelAfter(TimeSpan.FromMinutes(2));
try { using var scope = factory.CreateScope(); await scope.ServiceProvider.GetRequiredService<GoogleMailbox>().Sync(mailbox, deadline.Token); }
@@ -39,8 +39,8 @@ sealed class MailboxWorker(IStore store, IServiceScopeFactory factory, ILogger<M
catch (Exception ex)
{
log.LogWarning("Mailbox synchronization paused for {Id} ({Type})", mailbox.Id, ex.GetType().Name);
mailbox.SyncError = "Synchronization failed. Retry later or reconnect your Google mailbox.";
await store.SaveSync(mailbox);
using var failureScope = factory.CreateScope();
await failureScope.ServiceProvider.GetRequiredService<GoogleMailbox>().RecordFailure(mailbox,ex);
}
finally { await store.ReleaseLease(mailbox.Id, owner); }
}
@@ -95,3 +95,4 @@ sealed class AutoReplyWorker(IStore store,IServiceScopeFactory factory,ILogger<A
}
}
}