Add reactions, reliable push & session checks

Implements message reactions and reaction packs (domain models, services, admin HTTP API, media processing via ImageSharp and limits) and adds reliable push delivery (ChatPushNotification, ChatPushDispatcher, ChatPushWorker, improved ChatNotificationService). Enhances message reading (ReadChat API, unread counts, concurrency-safe receipts) and tightens session security (access-token session validation in JWT, hub filter, SessionAuthorization). Improves SignalR behavior (session groups, reaction/channel events, hub/error mappings). Adds EF migrations, many controller fixes (Forbid handling, password API), tests (Govor.Server.Tests), docs, CI and tooling updates (Dockerfile → .NET 10, GH Actions matrix for sqlite/postgres, Govor.Server.slnx, global.json), and small infra changes (AutoMapper bump, NullPushProvider, storage/token handling).
This commit is contained in:
Artemy
2026-10-03 17:42:24 +07:00
parent 4603be9f71
commit 29cc51ee0c
127 changed files with 7290 additions and 2488 deletions
@@ -2,12 +2,13 @@ using Govor.Application.Infrastructure.AdminsStuff;
using Govor.Contracts.DTOs;
using Govor.Contracts.Requests;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
namespace Govor.API.Controllers.AdminStuff;
[Route("api/admin/[controller]")]
[ApiController]
//[Authorize(Roles = "Admin")]
[Authorize(Roles = "Admin")]
public class InviteUserController : Controller
{
private readonly IInvitationGetter _invitationGetter;
@@ -144,4 +145,4 @@ public class InviteUserController : Controller
return BadRequest($"An error occured: {e.Message}");
}
}
}
}
@@ -0,0 +1,66 @@
using System.ComponentModel.DataAnnotations;
using AutoMapper;
using Govor.API.Common.Extensions;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Reactions;
using Govor.Contracts.Requests;
using Govor.Contracts.Responses;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Govor.API.Controllers.AdminStuff;
[ApiController]
[Authorize(Roles = "Admin")]
[Route("api/admin/reaction-packs")]
public class ReactionPacksAdminController(IReactionPackService packs, ICurrentUserService currentUser, IMapper mapper) : ControllerBase
{
[HttpGet]
public async Task<IActionResult> List([FromQuery, Range(0, int.MaxValue)] int skip = 0,
[FromQuery, Range(1, 100)] int take = 50) =>
Ok(mapper.Map<List<ReactionPackResponse>>(await packs.ListAsync(currentUser.GetCurrentUserId(), includeDisabled: true, skip: skip, take: take)));
[HttpGet("{packId:guid}")]
public async Task<IActionResult> Get(Guid packId) => (await packs.GetAsync(packId, includeDisabled: true))
.Map(p => mapper.Map<ReactionPackResponse>(p)).ToActionResult();
[HttpPost]
public async Task<IActionResult> Create([FromBody] CreateReactionPackRequest request) =>
(await packs.CreateAsync(currentUser.GetCurrentUserId(), request.Name, request.Description))
.Map(p => mapper.Map<ReactionPackResponse>(p)).ToActionResult();
[HttpPut("{packId:guid}")]
public async Task<IActionResult> Update(Guid packId, [FromBody] UpdateReactionPackRequest request) =>
(await packs.UpdateAsync(currentUser.GetCurrentUserId(), packId, request.Name, request.Description, request.IsEnabled))
.Map(p => mapper.Map<ReactionPackResponse>(p)).ToActionResult();
[HttpDelete("{packId:guid}")]
public async Task<IActionResult> Disable(Guid packId) => (await packs.DisableAsync(currentUser.GetCurrentUserId(), packId)).ToActionResult();
[HttpPost("{packId:guid}/reactions/emoji")]
public async Task<IActionResult> Emoji(Guid packId, [FromBody] CreateEmojiReactionRequest request) =>
(await packs.AddEmojiAsync(currentUser.GetCurrentUserId(), packId, request.Name, request.Emoji))
.Map(r => mapper.Map<ReactionItemResponse>(r)).ToActionResult();
[HttpPost("{packId:guid}/reactions/media")]
[RequestSizeLimit(2_200_000)]
public async Task<IActionResult> Media(Guid packId, [FromForm] ReactionUploadRequest request)
{
if (request.File is null || request.File.Length == 0 || request.File.Length > ReactionMediaLimits.MaxUploadBytes)
return BadRequest("Upload must contain at most 2 MiB.");
using var buffer = new MemoryStream();
await request.File.CopyToAsync(buffer, HttpContext.RequestAborted);
return (await packs.AddMediaAsync(currentUser.GetCurrentUserId(), packId, request.Name,
buffer.ToArray(), HttpContext.RequestAborted)).Map(r => mapper.Map<ReactionItemResponse>(r)).ToActionResult();
}
[HttpDelete("{packId:guid}/reactions/{reactionId:guid}")]
public async Task<IActionResult> DisableReaction(Guid packId, Guid reactionId) =>
(await packs.DisableReactionAsync(currentUser.GetCurrentUserId(), packId, reactionId)).ToActionResult();
}
public class ReactionUploadRequest
{
[Required, MaxLength(100)] public string Name { get; set; } = string.Empty;
[Required] public IFormFile File { get; set; }
}
@@ -3,13 +3,14 @@ using Govor.Contracts.Responses.Admins;
using Govor.Domain.Models.Users;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Govor.Contracts.Requests;
namespace Govor.API.Controllers.AdminStuff;
[ApiController]
[Route("api/admin/[controller]")]
[Authorize]//(Roles = "Admin")
[Authorize(Roles = "Admin")]
public class UsersController : Controller
{
private readonly ILogger<UsersController> _logger;
@@ -48,6 +49,8 @@ public class UsersController : Controller
{
_logger.LogInformation($"Getting user {id} by administrator");
var read = await _users.GetUserById(id);
if (read is null)
return NotFound();
return Ok(BuildUserDtos([read]).First());
}
catch (Exception e)
@@ -57,13 +60,15 @@ public class UsersController : Controller
}
}
[HttpGet("user/{id:guid}/setpassword/{password}")]
public async Task<IActionResult> SetNewPassword(Guid id, string password)
[HttpPost("user/{id:guid}/password")]
public async Task<IActionResult> SetNewPassword(Guid id, [FromBody] SetPasswordRequest request)
{
try
{
await _users.SetPasswordAsync(id, password);
return Ok();
if (await _users.GetUserById(id) is null)
return NotFound();
await _users.SetPasswordAsync(id, request.Password);
return NoContent();
}
catch (Exception ex)
{
@@ -78,10 +83,9 @@ public class UsersController : Controller
Description = user.Description,
WasOnline = user.WasOnline,
IconId = user.IconId,
PasswordHash = user.PasswordHash,
InviteId = user.InviteId,
CreatedOn = user.CreatedOn,
IsAdmin = user.Invite?.IsAdmin ?? false,
}).ToList();
}
}
@@ -4,6 +4,7 @@ using Govor.Application.Users.UserSessions.Crypto;
using Govor.Contracts.Requests;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Govor.Contracts.DTOs;
namespace Govor.API.Controllers.Authentication;
@@ -27,7 +28,8 @@ public class SessionKeysController : Controller
ICurrentUserSessionService currentSession,
ISessionKeyAttacher sessionKeyAttacher,
ISessionKeysReader sessionKeysReader,
ICurrentUserService currentUser)
ICurrentUserService currentUser,
IOneTimePreKeysRotator oneTimePreKeysRotator)
{
_logger = logger;
_friendshipService = friendshipService;
@@ -35,6 +37,7 @@ public class SessionKeysController : Controller
_sessionKeyAttacher = sessionKeyAttacher;
_sessionKeysReader = sessionKeysReader;
_currentUser = currentUser;
_oneTimePreKeysRotator = oneTimePreKeysRotator;
}
[HttpPost("keys")]
@@ -63,11 +66,24 @@ public class SessionKeysController : Controller
var requesterId = _currentUser.GetCurrentUserId();
if (!(await _friendshipService.GetFriendsAsync(userId)).Select(u => u.Id).Contains(requesterId))
return Forbid("You can only access keys of your friends");
return Forbid();
var keys = await _sessionKeysReader.GetAllActiveKeysAsync(userId);
return Ok(keys);
return Ok(keys.Select(k => new PublicSessionKeysDto
{
IdentityKey = Convert.ToBase64String(k.PublicIdentityKey),
SignedPreKey = k.SignedPreKey is null ? null : new SignedPreKeyDto
{
Id = k.SignedPreKey.Id,
Key = Convert.ToBase64String(k.SignedPreKey.PublicSignedPreKey),
Signature = Convert.ToBase64String(k.SignedPreKey.SignedPreKeySignature)
},
OneTimePreKeys = k.OneTimePreKeys.Where(p => !p.IsUsed).Select(p => new OneTimePreKeyDto
{
Id = p.Id, Key = Convert.ToBase64String(p.PublicKey)
}).ToList()
}));
}
[HttpPost("keys/rotate")]
@@ -106,4 +122,4 @@ public class SessionKeysController : Controller
return Ok("Marked as used.");
}
}
}
@@ -0,0 +1,32 @@
using AutoMapper;
using Govor.API.Common.Extensions;
using Govor.API.Hubs.Infrastructure;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Reactions;
using Govor.Contracts.Requests;
using Govor.Contracts.Responses.SignalR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
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
{
[HttpGet]
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 response = mapper.Map<ChannelReactionPolicyResponse>(result.Value);
await notifier.NotifyChannelReactionPolicyChangedAsync(response);
return Ok(response);
}
}
+3 -3
View File
@@ -41,7 +41,7 @@ public class ChatLoadController : Controller
{
try
{
if (query.Before < 0 || query.After < 0 || query.After + query.Before > 100)
if (query.Before < 0 || query.After < 0 || query.Before > 100 || query.After > 100 || query.After + query.Before > 100)
return BadRequest("Values must be non-negative and total must not exceed 100.");
var result = (await _messagesLoader.LoadMessagesInChatGroup(
@@ -67,7 +67,7 @@ public class ChatLoadController : Controller
{
try
{
if (query.Before < 0 || query.After < 0 || query.After + query.Before > 100)
if (query.Before < 0 || query.After < 0 || query.Before > 100 || query.After > 100 || query.After + query.Before > 100)
return BadRequest("Values must be non-negative and total must not exceed 100.");
var result = (await _messagesLoader.LoadMessagesInUserChat(
@@ -86,4 +86,4 @@ public class ChatLoadController : Controller
return StatusCode(500, "Unexpected Error! Please try again later.");
}
}
}
}
+4 -1
View File
@@ -37,6 +37,9 @@ public class MediaController : Controller
if (!ModelState.IsValid)
return BadRequest(ModelState);
if (request.OwnerType != MediaOwnerType.Message && request.OwnerType != MediaOwnerType.Avatar)
return BadRequest("Only message and personal avatar uploads are supported.");
if (request?.FromFile is null || request.FromFile.Length == 0)
return BadRequest("No file uploaded");
@@ -85,7 +88,7 @@ public class MediaController : Controller
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message);
return Forbid();
}
catch (Exception ex)
{
@@ -0,0 +1,37 @@
using AutoMapper;
using Govor.API.Common.Extensions;
using Govor.API.Hubs.Infrastructure;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Reactions;
using Govor.Contracts.Requests;
using Govor.Contracts.Responses.SignalR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Govor.API.Controllers;
[ApiController]
[Authorize(Roles = "Admin,User")]
[Route("api/messages/{messageId:guid}/reactions")]
public class MessageReactionsController(IMessageReactionService reactions, ICurrentUserService currentUser,
IMapper mapper, IChatNotificationService notifier) : ControllerBase
{
[HttpGet]
public async Task<IActionResult> Get(Guid messageId) => (await reactions.GetAsync(currentUser.GetCurrentUserId(), messageId))
.Map(s => mapper.Map<MessageReactionsChangedResponse>(s)).ToActionResult();
[HttpPut("me")]
public Task<IActionResult> Set(Guid messageId, [FromBody] SetReactionRequest request) => ChangeAsync(messageId, request.ReactionId);
[HttpDelete("me")]
public Task<IActionResult> Remove(Guid messageId) => ChangeAsync(messageId, null);
private async Task<IActionResult> ChangeAsync(Guid messageId, Guid? reactionId)
{
var result = await reactions.SetAsync(currentUser.GetCurrentUserId(), messageId, reactionId);
if (result.IsFailure) return result.ToActionResult();
var response = mapper.Map<MessageReactionsChangedResponse>(result.Value);
if (result.Value.Changed) await notifier.NotifyMessageReactionsChangedAsync(response);
return Ok(response);
}
}
@@ -0,0 +1,52 @@
using AutoMapper;
using Govor.API.Common.Extensions;
using Govor.API.Hubs.Infrastructure;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Messages;
using Govor.Contracts.Requests;
using Govor.Contracts.Responses.SignalR;
using Govor.Domain.Models.Messages;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Govor.API.Controllers;
[ApiController]
[Authorize(Roles = "Admin,User")]
[Route("api/chats/{chatId:guid}")]
public class MessageReadController : ControllerBase
{
private readonly IMessageReadingService _reader;
private readonly ICurrentUserService _currentUser;
private readonly IChatNotificationService _notifier;
private readonly IMapper _mapper;
public MessageReadController(IMessageReadingService reader, ICurrentUserService currentUser,
IChatNotificationService notifier, IMapper mapper)
{
_reader = reader;
_currentUser = currentUser;
_notifier = notifier;
_mapper = mapper;
}
[HttpPost("read")]
public async Task<IActionResult> Read(Guid chatId, [FromBody] ReadChatRequest request)
{
var result = await _reader.ReadChatAsync(_currentUser.GetCurrentUserId(), chatId,
request.RecipientType, request.MessageIds, request.UpToMessageId);
if (result.IsFailure)
return result.ToActionResult();
var response = _mapper.Map<ChatReadResponse>(result.Value);
await _notifier.NotifyChatReadAsync(response);
return Ok(response);
}
[HttpGet("unread-count")]
public async Task<IActionResult> GetUnreadCount(Guid chatId, [FromQuery] RecipientType recipientType)
{
var result = await _reader.GetUnreadCountAsync(_currentUser.GetCurrentUserId(), chatId, recipientType);
return result.IsFailure ? result.ToActionResult() : Ok(new { unreadCount = result.Value });
}
}
@@ -19,11 +19,15 @@ public class OnlinePingingController : Controller
public OnlinePingingController(ILogger<OnlinePingingController> logger,
IPingHandlerService ping,
ICurrentUserService currentUserService)
ICurrentUserService currentUserService,
IUserPresenceReader presenceReader,
IOnlineUserStore userOnlineStore)
{
_logger = logger;
_ping = ping;
_currentUserService = currentUserService;
_presenceReader = presenceReader;
_userOnlineStore = userOnlineStore;
}
@@ -66,4 +70,4 @@ public class OnlinePingingController : Controller
return StatusCode(500, "Internal server error.");
}
}
}
}
@@ -49,7 +49,7 @@ public class PrivateChatController : Controller
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex.Message);
return Forbid(ex.Message);
return Forbid();
}
catch (ArgumentException ex)
{
@@ -59,7 +59,7 @@ public class PrivateChatController : Controller
catch (FriendshipException ex)
{
_logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message);
return Forbid();
}
catch (Exception ex)
{
@@ -87,7 +87,7 @@ public class PrivateChatController : Controller
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex.Message);
return Forbid(ex.Message);
return Forbid();
}
catch (Exception ex)
{
@@ -95,4 +95,4 @@ public class PrivateChatController : Controller
return StatusCode(500, "Unexpected Error! Please try again later.");
}
}
}
}
+3 -3
View File
@@ -1,4 +1,4 @@
using AutoMapper;
using AutoMapper;
using Govor.API.Common.Extensions;
using Govor.API.Hubs;
using Govor.Application.Infrastructure.Extensions;
@@ -102,7 +102,7 @@ public class ProfileController : ControllerBase
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex.Message);
return Forbid(ex.Message);
return Forbid();
}
catch (Exception ex)
{
@@ -124,7 +124,7 @@ public class ProfileController : ControllerBase
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex.Message);
return Forbid(ex.Message);
return Forbid();
}
catch (Exception ex)
{
@@ -0,0 +1,55 @@
using System.ComponentModel.DataAnnotations;
using AutoMapper;
using Govor.API.Common.Extensions;
using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Reactions;
using Govor.Contracts.Responses;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Govor.API.Controllers;
[ApiController]
[Authorize(Roles = "Admin,User")]
[Route("api/reaction-packs")]
public class ReactionPacksController(IReactionPackService packs, ICurrentUserService currentUser, IMapper mapper) : ControllerBase
{
[HttpGet]
public async Task<IActionResult> List([FromQuery, Range(0, int.MaxValue)] int skip = 0,
[FromQuery, Range(1, 100)] int take = 50) =>
Ok(mapper.Map<List<ReactionPackResponse>>(await packs.ListAsync(currentUser.GetCurrentUserId(), skip: skip, take: take)));
[HttpGet("mine")]
public async Task<IActionResult> Mine([FromQuery, Range(0, int.MaxValue)] int skip = 0,
[FromQuery, Range(1, 100)] int take = 50) =>
Ok(mapper.Map<List<ReactionPackResponse>>(await packs.ListAsync(currentUser.GetCurrentUserId(), installedOnly: true, skip: skip, take: take)));
[HttpGet("{packId:guid}")]
public async Task<IActionResult> Get(Guid packId) => (await packs.GetAsync(packId))
.Map(p => mapper.Map<ReactionPackResponse>(p)).ToActionResult();
[HttpGet("shared/{shareCode}")]
public async Task<IActionResult> Shared(string shareCode) => (await packs.GetSharedAsync(shareCode))
.Map(p => mapper.Map<ReactionPackResponse>(p)).ToActionResult();
[HttpGet("/api/reactions/{reactionId:guid}")]
public async Task<IActionResult> Reaction(Guid reactionId) => (await packs.GetReactionAsync(reactionId))
.Map(r => mapper.Map<ReactionItemResponse>(r)).ToActionResult();
[HttpPut("{packId:guid}/subscription")]
public async Task<IActionResult> Subscribe(Guid packId) =>
(await packs.SubscribeAsync(currentUser.GetCurrentUserId(), packId, true)).ToActionResult();
[HttpDelete("{packId:guid}/subscription")]
public async Task<IActionResult> Unsubscribe(Guid packId) =>
(await packs.SubscribeAsync(currentUser.GetCurrentUserId(), packId, false)).ToActionResult();
[HttpGet("limits")]
public IActionResult Limits() => Ok(new
{
maxDimension = ReactionMediaLimits.MaxDimension, maxUploadBytes = ReactionMediaLimits.MaxUploadBytes,
maxImageBytes = ReactionMediaLimits.MaxImageBytes, maxGifBytes = ReactionMediaLimits.MaxGifBytes,
maxFrames = ReactionMediaLimits.MaxFrames, maxDurationMilliseconds = ReactionMediaLimits.MaxDurationMilliseconds,
maxItemsPerPack = 100
});
}
+5 -5
View File
@@ -49,7 +49,7 @@ public class SessionController : Controller
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message);
return Forbid();
}
catch (Exception ex)
{
@@ -74,7 +74,7 @@ public class SessionController : Controller
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message);
return Forbid();
}
catch (Exception ex)
{
@@ -97,7 +97,7 @@ public class SessionController : Controller
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message);
return Forbid();
}
catch (Exception ex)
{
@@ -118,7 +118,7 @@ public class SessionController : Controller
catch (UnauthorizedAccessException ex)
{
_logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message);
return Forbid();
}
catch (Exception ex)
{
@@ -126,4 +126,4 @@ public class SessionController : Controller
return StatusCode(500, "Unexpected Error! Please try again later.");
}
}
}
}