mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-17 04:58:46 +00:00
Harden push notification delivery
Keep encrypted message content out of push payloads and improve cross-platform notification data. Add token registration validation and per-session unregister support, batch and deduplicate sends, remove only confirmed unregistered tokens, and protect queued retries with leases. Add delivery tests and document the push API and Firebase setup.
This commit is contained in:
@@ -13,20 +13,34 @@ namespace Govor.API.Controllers;
|
||||
[ApiController]
|
||||
[Authorize(Roles = "Admin,User")]
|
||||
[Route("api/groups/{groupId:guid}/reactions")]
|
||||
public class ChannelReactionsController(IMessageReactionService reactions, ICurrentUserService currentUser,
|
||||
IMapper mapper, IChatNotificationService notifier) : ControllerBase
|
||||
public class ChannelReactionsController(
|
||||
IMessageReactionService reactions,
|
||||
ICurrentUserService currentUser,
|
||||
IMapper mapper,
|
||||
IChatNotificationService notifier) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Get(Guid groupId) => (await reactions.GetPolicyAsync(currentUser.GetCurrentUserId(), groupId))
|
||||
.Map(p => mapper.Map<ChannelReactionPolicyResponse>(p)).ToActionResult();
|
||||
public async Task<IActionResult> Get(Guid groupId) =>
|
||||
(await reactions.GetPolicyAsync(currentUser.GetCurrentUserId(), groupId))
|
||||
.Map(p => mapper.Map<ChannelReactionPolicyResponse>(p))
|
||||
.ToActionResult();
|
||||
|
||||
[HttpPut]
|
||||
public async Task<IActionResult> Set(Guid groupId, [FromBody] ChannelReactionPolicyRequest request)
|
||||
{
|
||||
var result = await reactions.SetPolicyAsync(currentUser.GetCurrentUserId(), groupId, request.Mode, request.ReactionIds);
|
||||
if (result.IsFailure) return result.ToActionResult();
|
||||
var result = await reactions.SetPolicyAsync(
|
||||
currentUser.GetCurrentUserId(),
|
||||
groupId,
|
||||
request.Mode,
|
||||
request.ReactionIds);
|
||||
|
||||
if (result.IsFailure)
|
||||
return result.ToActionResult();
|
||||
|
||||
var response = mapper.Map<ChannelReactionPolicyResponse>(result.Value);
|
||||
|
||||
await notifier.NotifyChannelReactionPolicyChangedAsync(response);
|
||||
|
||||
return Ok(response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ public class ProfileController : ControllerBase
|
||||
}
|
||||
|
||||
[HttpGet("download/{id}")]
|
||||
public async Task<IActionResult> DowloadProfileByUserId(Guid id)
|
||||
public async Task<IActionResult> DownloadProfileByUserId(Guid id)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
@@ -15,15 +15,18 @@ public class PushTokensController : Controller
|
||||
private readonly ICurrentUserService _currentUser;
|
||||
private readonly ICurrentUserSessionService _currentSession;
|
||||
private readonly IPushTokenService _pushTokenService;
|
||||
private readonly ILogger<PushTokensController> _logger;
|
||||
|
||||
public PushTokensController(
|
||||
IPushTokenService pushTokenService,
|
||||
ICurrentUserService currentUser,
|
||||
ICurrentUserSessionService currentSession)
|
||||
ICurrentUserSessionService currentSession,
|
||||
ILogger<PushTokensController> logger)
|
||||
{
|
||||
_pushTokenService = pushTokenService;
|
||||
_currentUser = currentUser;
|
||||
_currentSession = currentSession;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpPost("pushes/token/register")]
|
||||
@@ -31,30 +34,22 @@ public class PushTokensController : Controller
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(ModelState);
|
||||
|
||||
if (string.IsNullOrEmpty(req.Token) || string.IsNullOrWhiteSpace(req.Platform))
|
||||
return BadRequest(ModelState);
|
||||
|
||||
var currentId = _currentUser.GetCurrentUserId();
|
||||
var currentSessionId = _currentSession.GetUserSessionId();
|
||||
|
||||
var result = await _pushTokenService.AddOrUpdateTokenAsync(
|
||||
userId: currentId,
|
||||
sessionId: currentSessionId,
|
||||
token: req.Token,
|
||||
platform: req.Platform);
|
||||
|
||||
return result.ToActionResult();
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
return BadRequest(ex.Message);
|
||||
var result = await _pushTokenService.AddOrUpdateTokenAsync(
|
||||
_currentUser.GetCurrentUserId(), _currentSession.GetUserSessionId(), req.Token, req.Platform);
|
||||
return result.ToActionResult();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return StatusCode(500, "Unexpected Error! Please try again later.");
|
||||
_logger.LogError(ex, "Failed to register push token for the current session");
|
||||
return Problem(statusCode: StatusCodes.Status500InternalServerError,
|
||||
detail: "Push token registration failed. Please try again later.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("pushes/token")]
|
||||
public async Task<IActionResult> UnregisterToken()
|
||||
{
|
||||
var result = await _pushTokenService.DeactivateTokenBySessionAsync(_currentSession.GetUserSessionId());
|
||||
return result.ToActionResult();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,12 +67,14 @@ public class ChatNotificationService : IChatNotificationService
|
||||
return true;
|
||||
var profile = await _profiles.GetUserProfileAsync(message.SenderId);
|
||||
var title = profile.IsSuccess ? profile.Value.Username : "Govor";
|
||||
var content = message.EncryptedContent ?? string.Empty;
|
||||
var body = content.Length == 0 ? "Attachment" : content[..Math.Min(40, content.Length)];
|
||||
// Message content is encrypted; never send ciphertext or a guessed preview to FCM.
|
||||
var body = "New message";
|
||||
var data = new Dictionary<string, string>
|
||||
{
|
||||
["chatId"] = message.RecipientId.ToString(),
|
||||
["messageId"] = message.MessageId.ToString(),
|
||||
["senderId"] = message.SenderId.ToString(),
|
||||
["type"] = "chat_message",
|
||||
["isGroup"] = message.RecipientType == RecipientType.Group ? "true" : "false"
|
||||
};
|
||||
var push = await _notificationService.SendToUsersAsync(recipients, title, body,
|
||||
|
||||
@@ -6,44 +6,58 @@ using Microsoft.EntityFrameworkCore;
|
||||
namespace Govor.API.Hubs.Infrastructure;
|
||||
|
||||
public class ChatPushDispatcher(GovorDbContext context, IChatNotificationService notifier,
|
||||
INowDateTimeProvider dateTimeProvider)
|
||||
INowDateTimeProvider dateTimeProvider, ILogger<ChatPushDispatcher> logger = null)
|
||||
{
|
||||
public async Task DispatchAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var now = dateTimeProvider.Now;
|
||||
var pending = await context.ChatPushNotifications.AsNoTracking()
|
||||
.Where(n => n.NextAttemptAt <= now).OrderBy(n => n.NextAttemptAt)
|
||||
.Take(20).Select(n => n.MessageId).ToListAsync(cancellationToken);
|
||||
.Take(20).Select(n => new { n.MessageId, n.Attempts }).ToListAsync(cancellationToken);
|
||||
|
||||
foreach (var id in pending)
|
||||
foreach (var item in pending)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var id = item.MessageId;
|
||||
now = dateTimeProvider.Now;
|
||||
// Conditional update claims a two-minute lease, including across server instances.
|
||||
// An interrupted worker leaves a retryable row rather than losing the notification.
|
||||
var claimed = await context.ChatPushNotifications
|
||||
.Where(n => n.MessageId == id && n.NextAttemptAt <= now)
|
||||
.Where(n => n.MessageId == id && n.NextAttemptAt <= now && n.Attempts == item.Attempts)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(n => n.NextAttemptAt, now.AddMinutes(2))
|
||||
.SetProperty(n => n.Attempts, n => n.Attempts + 1), cancellationToken);
|
||||
if (claimed == 0)
|
||||
continue;
|
||||
|
||||
var message = await context.Messages.AsNoTracking()
|
||||
.Where(m => m.Id == id).Select(m => new UserMessageResponse
|
||||
{
|
||||
MessageId = m.Id, SenderId = m.SenderId, RecipientId = m.RecipientId,
|
||||
RecipientType = m.RecipientType, EncryptedContent = m.EncryptedContent,
|
||||
SentAt = m.SentAt, ReplyToMessageId = m.ReplyToMessageId
|
||||
}).FirstOrDefaultAsync(cancellationToken);
|
||||
var delivered = message is null || await notifier.DeliverPushAsync(message);
|
||||
var attempt = item.Attempts + 1;
|
||||
// An old worker must not complete or reschedule a newer worker's lease.
|
||||
var owned = context.ChatPushNotifications.Where(n => n.MessageId == id && n.Attempts == attempt);
|
||||
var delivered = false;
|
||||
try
|
||||
{
|
||||
var message = await context.Messages.AsNoTracking()
|
||||
.Where(m => m.Id == id).Select(m => new UserMessageResponse
|
||||
{
|
||||
MessageId = m.Id, SenderId = m.SenderId, RecipientId = m.RecipientId,
|
||||
RecipientType = m.RecipientType, EncryptedContent = m.EncryptedContent,
|
||||
SentAt = m.SentAt, ReplyToMessageId = m.ReplyToMessageId
|
||||
}).FirstOrDefaultAsync(cancellationToken);
|
||||
delivered = message is null || await notifier.DeliverPushAsync(message);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger?.LogError(ex, "Push attempt failed for message {MessageId}; delivery will be retried.", id);
|
||||
}
|
||||
if (delivered)
|
||||
await context.ChatPushNotifications.Where(n => n.MessageId == id)
|
||||
.ExecuteDeleteAsync(cancellationToken);
|
||||
await owned.ExecuteDeleteAsync(cancellationToken);
|
||||
else
|
||||
{
|
||||
var attempts = await context.ChatPushNotifications.Where(n => n.MessageId == id)
|
||||
.Select(n => n.Attempts).FirstOrDefaultAsync(cancellationToken);
|
||||
var retryAt = dateTimeProvider.Now.AddSeconds(Math.Min(300, Math.Pow(2, Math.Min(attempts, 9))));
|
||||
await context.ChatPushNotifications.Where(n => n.MessageId == id)
|
||||
var retryAt = dateTimeProvider.Now.AddSeconds(Math.Min(300, Math.Pow(2, Math.Min(attempt, 9))));
|
||||
await owned
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(n => n.NextAttemptAt, retryAt), cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ using Govor.API.Common.Extensions;
|
||||
using Govor.API.Hubs;
|
||||
using Govor.Application.Authentication.JWT;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi;
|
||||
using Govor.Domain;
|
||||
@@ -201,10 +200,10 @@ app.MapGet("/server/ready", async (GovorDbContext db, CancellationToken cancella
|
||||
}
|
||||
});
|
||||
|
||||
app.MapHub<ChatsHub>("/hubs/chats", options => options.CloseOnAuthenticationExpiration = true);
|
||||
app.MapHub<FriendsHub>("/hubs/friends", options => options.CloseOnAuthenticationExpiration = true);
|
||||
app.MapHub<ProfileHub>("/hubs/profiles", options => options.CloseOnAuthenticationExpiration = true);
|
||||
app.MapHub<PresenceHub>("/hubs/presence", options => options.CloseOnAuthenticationExpiration = true);
|
||||
app.MapHub<ChatsHub>("/hubs/chats");
|
||||
app.MapHub<FriendsHub>("/hubs/friends");
|
||||
app.MapHub<ProfileHub>("/hubs/profiles");
|
||||
app.MapHub<PresenceHub>("/hubs/presence");
|
||||
|
||||
app.MapSwagger()
|
||||
.RequireAuthorization();
|
||||
|
||||
Reference in New Issue
Block a user