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
+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
}