mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-17 04:58:46 +00:00
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:
@@ -11,6 +11,7 @@ using Govor.Application.Infrastructure.Extensions;
|
||||
using Govor.Application.Infrastructure.Validators;
|
||||
using Govor.Application.Medias;
|
||||
using Govor.Application.Messages;
|
||||
using Govor.Application.Reactions;
|
||||
using Govor.Application.PingHandler;
|
||||
using Govor.Application.PrivateUserChats;
|
||||
using Govor.Application.Profiles;
|
||||
@@ -68,6 +69,9 @@ public static class ConfigurationProgramExtensions
|
||||
//services.AddScoped<IMessageCommandService, MessageCommandService>();
|
||||
services.AddScoped<IMessageSendingService, MessageSendingService>();
|
||||
services.AddScoped<IMessageReadingService, MessageReadingService>();
|
||||
services.AddScoped<IMessageReactionService, MessageReactionService>();
|
||||
services.AddScoped<IReactionPackService, ReactionPackService>();
|
||||
services.AddSingleton<IReactionMediaProcessor, ReactionMediaProcessor>();
|
||||
services.AddScoped<IMessageEditingService, MessageEditingService>();
|
||||
services.AddScoped<IMessageRemovingService, MessageRemovingService>();
|
||||
services.AddScoped<IVerifyFriendship, VerifyFriendship>();
|
||||
@@ -91,6 +95,8 @@ public static class ConfigurationProgramExtensions
|
||||
// Hubs Infrastructure
|
||||
services.AddScoped<IPrivateChatGroupManager, PrivateChatGroupManager>();
|
||||
services.AddScoped<IChatNotificationService, ChatNotificationService>();
|
||||
services.AddScoped<ChatPushDispatcher>();
|
||||
services.AddHostedService<ChatPushWorker>();
|
||||
services.AddScoped<IConnectionManager, ConnectionManager>();
|
||||
|
||||
services.AddSingleton<IConnectionStore, ConnectionStore>();
|
||||
@@ -98,7 +104,10 @@ public static class ConfigurationProgramExtensions
|
||||
// Pushs
|
||||
services.AddScoped<IPushTokenService, PushTokenService>();
|
||||
services.AddScoped<IPushNotificationService, PushNotificationService>();
|
||||
services.AddSingleton<IPushNotificationProvider, FirebasePushProvider>();
|
||||
services.AddSingleton<IPushNotificationProvider>(sp =>
|
||||
sp.GetRequiredService<IConfiguration>().GetValue("Firebase:Enabled", true)
|
||||
? ActivatorUtilities.CreateInstance<FirebasePushProvider>(sp)
|
||||
: new NullPushProvider());
|
||||
|
||||
|
||||
// Auto Mapper
|
||||
@@ -133,8 +142,8 @@ public static class ConfigurationProgramExtensions
|
||||
|
||||
//options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
|
||||
|
||||
options.EnableSensitiveDataLogging();
|
||||
options.EnableDetailedErrors();
|
||||
if (configuration.GetValue<bool>("Database:EnableDetailedErrors"))
|
||||
options.EnableDetailedErrors();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
using Govor.Contracts.Responses.SignalR;
|
||||
using Govor.Domain.Common;
|
||||
|
||||
namespace Govor.API.Common.Extensions;
|
||||
|
||||
public static class HubResultExtensions
|
||||
{
|
||||
public static HubResult<T> ToHubResult<T>(this Error error) => error.Type switch
|
||||
{
|
||||
ErrorType.NotFound => HubResult<T>.NotFound(error.Message),
|
||||
ErrorType.Forbidden => HubResult<T>.Forbidden(error.Message),
|
||||
ErrorType.Unauthorized => HubResult<T>.Unauthorized(error.Message),
|
||||
ErrorType.Conflict => HubResult<T>.Conflict(error.Message),
|
||||
ErrorType.ServerError => HubResult<T>.Error("Internal server error."),
|
||||
_ => HubResult<T>.BadRequest(error.Message)
|
||||
};
|
||||
}
|
||||
@@ -28,6 +28,7 @@ public static class ResultExtensions
|
||||
ErrorType.Conflict => StatusCodes.Status409Conflict,
|
||||
ErrorType.Unauthorized => StatusCodes.Status401Unauthorized,
|
||||
ErrorType.Forbidden => StatusCodes.Status403Forbidden,
|
||||
ErrorType.ServerError => StatusCodes.Status500InternalServerError,
|
||||
_ => StatusCodes.Status400BadRequest
|
||||
};
|
||||
|
||||
@@ -55,6 +56,7 @@ public static class ResultExtensions
|
||||
ErrorType.Conflict => "Conflict",
|
||||
ErrorType.Unauthorized => "Unauthorized",
|
||||
ErrorType.Forbidden => "Forbidden",
|
||||
ErrorType.ServerError => "Internal Server Error",
|
||||
_ => "Bad Request"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#nullable enable
|
||||
using System.Security.Claims;
|
||||
using Govor.Domain;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Govor.API.Common.Extensions;
|
||||
|
||||
public static class SessionAuthorization
|
||||
{
|
||||
public static Task<bool> HasActiveSessionAsync(this GovorDbContext context, ClaimsPrincipal? user)
|
||||
{
|
||||
if (user?.Identity?.IsAuthenticated != true || user.FindFirst("tokenType")?.Value == "refresh" ||
|
||||
!Guid.TryParse(user.FindFirst("userId")?.Value, out var userId) ||
|
||||
!Guid.TryParse(user.FindFirst("sid")?.Value, out var sessionId))
|
||||
return Task.FromResult(false);
|
||||
|
||||
var now = DateTime.UtcNow;
|
||||
return context.UserSessions.AsNoTracking().AnyAsync(s => s.Id == sessionId &&
|
||||
s.UserId == userId && !s.IsRevoked && s.ExpiresAt > now);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,10 @@ using Govor.Contracts.Responses;
|
||||
using Govor.Domain.Models;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Govor.Domain.Models.Users;
|
||||
using Govor.Application.Messages.Parameters;
|
||||
using Govor.Contracts.Responses.SignalR;
|
||||
using Govor.Application.Reactions;
|
||||
using Govor.Domain.Models.Reactions;
|
||||
|
||||
namespace Govor.API.Common.Mapping;
|
||||
|
||||
@@ -12,6 +16,12 @@ public class MappingProfile : Profile
|
||||
{
|
||||
public MappingProfile()
|
||||
{
|
||||
CreateMap<ChatReadResult, ChatReadResponse>();
|
||||
CreateMap<ReactionPack, ReactionPackResponse>();
|
||||
CreateMap<ReactionItem, ReactionItemResponse>();
|
||||
CreateMap<ReactionCount, ReactionCountResponse>();
|
||||
CreateMap<MessageReactionState, MessageReactionsChangedResponse>();
|
||||
CreateMap<ChannelReactionPolicy, ChannelReactionPolicyResponse>();
|
||||
CreateMap<Message, MessageResponse>();
|
||||
CreateMap<MediaAttachments, MediaAttachmentResponse>();
|
||||
CreateMap<MessageReaction, MessageReactionResponse>();
|
||||
@@ -27,6 +37,5 @@ public class MappingProfile : Profile
|
||||
|
||||
CreateMap<UserSession, SessionDto>();
|
||||
|
||||
CreateMap<UserProfile, UserProfileDto>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
});
|
||||
}
|
||||
@@ -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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
using Govor.Contracts.Responses.SignalR;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Govor.API.Common.Extensions;
|
||||
using Govor.Domain;
|
||||
|
||||
namespace Govor.API.Filters;
|
||||
|
||||
public class HubExceptionFilter : IHubFilter
|
||||
{
|
||||
private readonly ILogger<HubExceptionFilter> _logger;
|
||||
private readonly GovorDbContext _context;
|
||||
|
||||
public HubExceptionFilter(ILogger<HubExceptionFilter> logger)
|
||||
public HubExceptionFilter(ILogger<HubExceptionFilter> logger, GovorDbContext context)
|
||||
{
|
||||
_logger = logger;
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async ValueTask<object?> InvokeMethodAsync(
|
||||
@@ -18,6 +22,11 @@ public class HubExceptionFilter : IHubFilter
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!await _context.HasActiveSessionAsync(context.Context.User))
|
||||
{
|
||||
context.Context.Abort();
|
||||
return CreateHubErrorResult(context, HubResultStatus.Unauthorized, "Session revoked or expired.");
|
||||
}
|
||||
return await next(context);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
@@ -66,10 +75,10 @@ public class HubExceptionFilter : IHubFilter
|
||||
hubResultType.GetProperty(nameof(HubResult<object>.ErrorMessage))!
|
||||
.SetValue(errorResult, message);
|
||||
|
||||
return Task.FromResult(errorResult);
|
||||
return errorResult;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BCrypt.Net-Next" Version="4.2.0" />
|
||||
<PackageReference Include="FirebaseAdmin" Version="3.6.0" />
|
||||
<PackageReference Include="AutoMapper" Version="16.0.0" />
|
||||
<PackageReference Include="AutoMapper" Version="16.2.0" />
|
||||
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.10" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.10" />
|
||||
@@ -34,7 +34,8 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="uploads\2026.08\" />
|
||||
<Folder Include="logs\" />
|
||||
<Folder Include="uploads\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
+80
-13
@@ -1,8 +1,12 @@
|
||||
using Govor.API.Common.SignalR.Helpers;
|
||||
using Govor.API.Common.Extensions;
|
||||
using Govor.Contracts.Requests;
|
||||
using Govor.API.Hubs.Infrastructure;
|
||||
using Govor.Application.Exceptions.VerifyFriendship;
|
||||
using Govor.Application.Infrastructure.Common;
|
||||
using Govor.Application.Messages;
|
||||
using Govor.Application.Reactions;
|
||||
using AutoMapper;
|
||||
using Govor.Application.Messages.Parameters;
|
||||
using Govor.Contracts.Requests.SignalR;
|
||||
using Govor.Contracts.Responses.SignalR;
|
||||
@@ -24,6 +28,8 @@ public class ChatsHub : Hub
|
||||
private readonly IChatNotificationService _notifier;
|
||||
private readonly IConnectionManager _connectionManager;
|
||||
private readonly INowDateTimeProvider _nowDateTimeProvider;
|
||||
private readonly IMessageReactionService _reactions;
|
||||
private readonly IMapper _mapper;
|
||||
|
||||
public ChatsHub(ILogger<ChatsHub> logger,
|
||||
IMessageReadingService messageReadingService,
|
||||
@@ -33,7 +39,9 @@ public class ChatsHub : Hub
|
||||
IHubUserAccessor userAccessor,
|
||||
IChatNotificationService notifier,
|
||||
INowDateTimeProvider nowDateTimeProvider,
|
||||
IConnectionManager connectionManager)
|
||||
IConnectionManager connectionManager,
|
||||
IMessageReactionService reactions,
|
||||
IMapper mapper)
|
||||
{
|
||||
_logger = logger;
|
||||
_nowDateTimeProvider = nowDateTimeProvider;
|
||||
@@ -44,6 +52,8 @@ public class ChatsHub : Hub
|
||||
_userAccessor = userAccessor;
|
||||
_notifier = notifier;
|
||||
_connectionManager = connectionManager;
|
||||
_reactions = reactions;
|
||||
_mapper = mapper;
|
||||
}
|
||||
|
||||
public override async Task OnConnectedAsync()
|
||||
@@ -56,6 +66,12 @@ public class ChatsHub : Hub
|
||||
}
|
||||
|
||||
await _connectionManager.OnConnectedAsync(Context.ConnectionId, userId);
|
||||
if (!Guid.TryParse(Context.User?.FindFirst("sid")?.Value, out var sessionId))
|
||||
{
|
||||
Context.Abort();
|
||||
return;
|
||||
}
|
||||
await Groups.AddToGroupAsync(Context.ConnectionId, ChatHubConstants.GetSessionGroup(sessionId));
|
||||
_logger.LogInformation("User {UserId} connected", userId);
|
||||
await base.OnConnectedAsync();
|
||||
}
|
||||
@@ -84,23 +100,25 @@ public class ChatsHub : Hub
|
||||
var result = await _messageSendingService.SendMessageAsync(sendParams);
|
||||
|
||||
if (!result.IsSuccess)
|
||||
throw new InvalidOperationException(result.Exception.Message ?? "Failed to send message");
|
||||
throw result.Exception ?? new InvalidOperationException("Failed to send message");
|
||||
|
||||
var response = MapToResponse(result.Message, request.ReplyToMessageId);
|
||||
|
||||
await _notifier.NotifyMessageSentAsync(response);
|
||||
|
||||
return HubResult<UserMessageResponse>.Ok(response);
|
||||
}, request.RecipientId);
|
||||
}, request?.RecipientId ?? Guid.Empty);
|
||||
}
|
||||
|
||||
// --- Read ---
|
||||
public async Task<HubResult<MessageReadResponse>> Read(ReadMessageRequest request)
|
||||
{
|
||||
return await SafeExecute(async (userId) =>
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var result = await _messageReadingService.ReadMessageAsync(userId, request.MessageId);
|
||||
if(!result.IsSuccess)
|
||||
throw new InvalidOperationException(result.Error.ToString());
|
||||
return result.Error.ToHubResult<MessageReadResponse>();
|
||||
|
||||
var message = result.Value;
|
||||
|
||||
@@ -119,13 +137,36 @@ public class ChatsHub : Hub
|
||||
await _notifier.NotifyMessageWasReadAsync(response);
|
||||
|
||||
return HubResult<MessageReadResponse>.Ok(response);
|
||||
}, request.MessageId);
|
||||
}, request?.MessageId ?? Guid.Empty);
|
||||
}
|
||||
// --- REMOVE ---
|
||||
public async Task<HubResult<ChatReadResponse>> ReadChat(Guid chatId, ReadChatRequest request)
|
||||
{
|
||||
return await SafeExecute(async userId =>
|
||||
{
|
||||
if (request is null)
|
||||
return HubResult<ChatReadResponse>.BadRequest("Request is required.");
|
||||
var result = await _messageReadingService.ReadChatAsync(userId, chatId,
|
||||
request.RecipientType, request.MessageIds, request.UpToMessageId);
|
||||
if (result.IsFailure)
|
||||
return result.Error.ToHubResult<ChatReadResponse>();
|
||||
var read = result.Value;
|
||||
var response = new ChatReadResponse
|
||||
{
|
||||
ChatId = read.ChatId, RecipientType = read.RecipientType, ReaderId = read.ReaderId,
|
||||
ReadAt = read.ReadAt, UpToMessageId = read.UpToMessageId, UpToSentAt = read.UpToSentAt,
|
||||
MessageIds = read.MessageIds, ReadCount = read.ReadCount, UnreadCount = read.UnreadCount
|
||||
};
|
||||
await _notifier.NotifyChatReadAsync(response);
|
||||
return HubResult<ChatReadResponse>.Ok(response);
|
||||
}, chatId);
|
||||
}
|
||||
|
||||
public async Task<HubResult<MessageRemovedResponse>> Remove(RemoveMessageRequest request)
|
||||
{
|
||||
return await SafeExecute(async (userId) =>
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var deletemessage = new DeleteMessage(
|
||||
userId,
|
||||
request.MessageId,
|
||||
@@ -140,7 +181,7 @@ public class ChatsHub : Hub
|
||||
var result = await _messageRemovingService.DeleteMessageAsync(deletemessage);
|
||||
|
||||
if (!result.IsSuccess)
|
||||
throw new InvalidOperationException(result.Error.ToString());
|
||||
return result.Error.ToHubResult<MessageRemovedResponse>();
|
||||
|
||||
var notification = new MessageRemovedResponse
|
||||
{
|
||||
@@ -154,7 +195,26 @@ public class ChatsHub : Hub
|
||||
await _notifier.NotifyMessageRemovedAsync(notification);
|
||||
|
||||
return HubResult<MessageRemovedResponse>.Ok(notification);
|
||||
}, request.MessageId);
|
||||
}, request?.MessageId ?? Guid.Empty);
|
||||
}
|
||||
|
||||
public Task<HubResult<MessageReactionsChangedResponse>> React(Guid messageId, SetReactionRequest request) =>
|
||||
SafeExecute(async userId =>
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
return await ChangeReactionAsync(userId, messageId, request.ReactionId);
|
||||
}, messageId);
|
||||
|
||||
public Task<HubResult<MessageReactionsChangedResponse>> RemoveReaction(Guid messageId) =>
|
||||
SafeExecute(userId => ChangeReactionAsync(userId, messageId, null), messageId);
|
||||
|
||||
private async Task<HubResult<MessageReactionsChangedResponse>> ChangeReactionAsync(Guid userId, Guid messageId, Guid? reactionId)
|
||||
{
|
||||
var result = await _reactions.SetAsync(userId, messageId, reactionId);
|
||||
if (result.IsFailure) return result.Error.ToHubResult<MessageReactionsChangedResponse>();
|
||||
var response = _mapper.Map<MessageReactionsChangedResponse>(result.Value);
|
||||
if (result.Value.Changed) await _notifier.NotifyMessageReactionsChangedAsync(response);
|
||||
return HubResult<MessageReactionsChangedResponse>.Ok(response);
|
||||
}
|
||||
|
||||
// --- EDIT ---
|
||||
@@ -162,6 +222,7 @@ public class ChatsHub : Hub
|
||||
{
|
||||
return await SafeExecute(async (userId) =>
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var editParams = new EditMessage(
|
||||
userId,
|
||||
request.MessageId,
|
||||
@@ -171,7 +232,7 @@ public class ChatsHub : Hub
|
||||
var result = await _messageEditingService.EditMessageAsync(editParams);
|
||||
|
||||
if (!result.IsSuccess || result.OriginalMessage == null)
|
||||
throw new InvalidOperationException("Edit message error");
|
||||
throw result.Exception ?? new InvalidOperationException("Edit message error");
|
||||
|
||||
var response = new MessageEditResponse
|
||||
{
|
||||
@@ -186,20 +247,21 @@ public class ChatsHub : Hub
|
||||
await _notifier.NotifyMessageEditedAsync(response);
|
||||
|
||||
return HubResult<MessageEditResponse>.Ok(response);
|
||||
}, request.MessageId);
|
||||
}, request?.MessageId ?? Guid.Empty);
|
||||
}
|
||||
|
||||
private async Task<HubResult<T>> SafeExecute<T>(Func<Guid, Task<HubResult<T>>> action, Guid targetIdForLog)
|
||||
{
|
||||
var userId = _userAccessor.GetUserId(Context);
|
||||
var userId = Guid.Empty;
|
||||
try
|
||||
{
|
||||
userId = _userAccessor.GetUserId(Context);
|
||||
return await action(userId);
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Unauthorized: {UserId} -> {TargetId}", userId, targetIdForLog);
|
||||
return HubResult<T>.Unauthorized("You are not authorized.");
|
||||
return HubResult<T>.Forbidden("You do not have permission to perform this action.");
|
||||
}
|
||||
catch (FriendshipException)
|
||||
{
|
||||
@@ -213,6 +275,10 @@ public class ChatsHub : Hub
|
||||
{
|
||||
return HubResult<T>.NotFound("Resource not found.");
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
return HubResult<T>.BadRequest(ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error executing hub method for {UserId}", userId);
|
||||
@@ -222,12 +288,13 @@ public class ChatsHub : Hub
|
||||
|
||||
private void ValidateMessageRequest(MessageRequest request)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (string.IsNullOrWhiteSpace(request.EncryptedContent) &&
|
||||
(request.MediaAttachments == null || !request.MediaAttachments.Any()))
|
||||
{
|
||||
throw new ArgumentException("Message must contain content or media.");
|
||||
}
|
||||
if (request.EncryptedContent.Length > 50_000)
|
||||
if ((request.EncryptedContent?.Length ?? 0) > 50_000)
|
||||
{
|
||||
throw new ArgumentException("Message is too long.");
|
||||
}
|
||||
@@ -262,4 +329,4 @@ public class ChatsHub : Hub
|
||||
ReplyToMessageId = replyToId
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,11 @@ using Govor.Application.Friends;
|
||||
using Govor.Contracts.DTOs;
|
||||
using Govor.Contracts.Responses.SignalR;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace Govor.API.Hubs;
|
||||
|
||||
[Authorize(Roles = "Admin,User")]
|
||||
public class FriendsHub : Hub
|
||||
{
|
||||
private readonly ILogger<FriendsHub> _logger;
|
||||
@@ -194,4 +196,4 @@ public class FriendsHub : Hub
|
||||
return HubResult<object>.Error("Unexpected error! Please try later!");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,8 +7,12 @@ public static class ChatHubConstants
|
||||
public const string MessageRemoved = "MessageRemoved";
|
||||
public const string MessageEdited = "MessageEdited";
|
||||
public static string MessageRead = "MessageReaded";
|
||||
public const string ChatRead = "ChatRead";
|
||||
public const string MessageReactionsChanged = "MessageReactionsChanged";
|
||||
public const string ChannelReactionPolicyChanged = "ChannelReactionPolicyChanged";
|
||||
|
||||
public static string GetUserGroup(Guid userId) => userId.ToString();
|
||||
public static string GetSessionGroup(Guid sessionId) => $"session_{sessionId}";
|
||||
public static string GetChatGroup(Guid groupId) => $"group_{groupId}";
|
||||
public static string GetPrivateChat(Guid groupId) => $"private_{groupId}";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,130 +2,161 @@ using Govor.Application.PrivateUserChats;
|
||||
using Govor.Application.Profiles;
|
||||
using Govor.Application.PushNotifications;
|
||||
using Govor.Contracts.Responses.SignalR;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Govor.API.Hubs.Infrastructure;
|
||||
|
||||
public class ChatNotificationService : IChatNotificationService
|
||||
public class ChatNotificationService : IChatNotificationService
|
||||
{
|
||||
private readonly IHubContext<ChatsHub> _hubContext;
|
||||
private readonly IPushNotificationService _notificationService;
|
||||
private readonly IUserPrivateChatsGetterService _userPrivateChatsGetterService;
|
||||
private readonly IProfileService _profileService;
|
||||
private readonly IUserPrivateChatsGetterService _chats;
|
||||
private readonly IProfileService _profiles;
|
||||
private readonly GovorDbContext _context;
|
||||
private readonly ILogger<ChatNotificationService> _logger;
|
||||
|
||||
public ChatNotificationService(
|
||||
IHubContext<ChatsHub> hubContext,
|
||||
IPushNotificationService notificationService,
|
||||
IUserPrivateChatsGetterService userPrivateChatsGetterService,
|
||||
IProfileService profileService)
|
||||
public ChatNotificationService(IHubContext<ChatsHub> hubContext,
|
||||
IPushNotificationService notificationService, IUserPrivateChatsGetterService chats,
|
||||
IProfileService profiles, GovorDbContext context, ILogger<ChatNotificationService> logger)
|
||||
{
|
||||
_hubContext = hubContext;
|
||||
_notificationService = notificationService;
|
||||
_userPrivateChatsGetterService = userPrivateChatsGetterService;
|
||||
_profileService = profileService;
|
||||
_chats = chats;
|
||||
_profiles = profiles;
|
||||
_context = context;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task NotifyMessageSentAsync(UserMessageResponse message)
|
||||
{
|
||||
if (message.RecipientType == RecipientType.User)
|
||||
await TryNotifyAsync(() => NotifyParticipantsAsync(message.RecipientId,
|
||||
message.RecipientType, ChatHubConstants.ReceiveMessage, message));
|
||||
await TryNotifyAsync(() => NotifyUsersAsync(new[] { message.SenderId }, ChatHubConstants.MessageSent, message));
|
||||
|
||||
}
|
||||
|
||||
public async Task<bool> DeliverPushAsync(UserMessageResponse message)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _hubContext.Clients.Group(ChatHubConstants.GetPrivateChat(message.RecipientId))
|
||||
.SendAsync(ChatHubConstants.ReceiveMessage, message);
|
||||
|
||||
await NotifyMessageReceivedInPrivateChatAsync(message);
|
||||
List<Guid> recipients;
|
||||
if (message.RecipientType == RecipientType.User)
|
||||
{
|
||||
var result = await _chats.GetPrivateChatAsync(message.RecipientId);
|
||||
if (result.IsFailure)
|
||||
return result.Error.Type == ErrorType.NotFound;
|
||||
recipients = new[] { result.Value.UserAId, result.Value.UserBId }
|
||||
.Where(id => id != message.SenderId).Distinct().ToList();
|
||||
}
|
||||
else
|
||||
recipients = await _context.GroupMemberships.AsNoTracking()
|
||||
.Where(m => m.GroupId == message.RecipientId && m.UserId != message.SenderId && !m.IsBanned)
|
||||
.Select(m => m.UserId).Distinct().ToListAsync();
|
||||
|
||||
if (recipients.Count == 0)
|
||||
return true;
|
||||
var readers = await _context.MessageViews.AsNoTracking()
|
||||
.Where(v => v.MessageId == message.MessageId).Select(v => v.UserId).ToListAsync();
|
||||
recipients = recipients.Except(readers).ToList();
|
||||
if (recipients.Count == 0)
|
||||
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)];
|
||||
var data = new Dictionary<string, string>
|
||||
{
|
||||
["chatId"] = message.RecipientId.ToString(),
|
||||
["messageId"] = message.MessageId.ToString(),
|
||||
["isGroup"] = message.RecipientType == RecipientType.Group ? "true" : "false"
|
||||
};
|
||||
var push = await _notificationService.SendToUsersAsync(recipients, title, body,
|
||||
"chat_messages", $"chat_{message.RecipientId}", data);
|
||||
if (push.IsFailure)
|
||||
_logger.LogWarning("Push failed for message {MessageId}: {Error}",
|
||||
message.MessageId, push.Error);
|
||||
return push.IsSuccess;
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
await _hubContext.Clients.Group(ChatHubConstants.GetChatGroup(message.RecipientId))
|
||||
.SendAsync(ChatHubConstants.ReceiveMessage, message);
|
||||
_logger.LogError(ex, "Failed to deliver push for message {MessageId}", message.MessageId);
|
||||
return false;
|
||||
}
|
||||
|
||||
// await _hubContext.Clients.Group(ChatHubConstants.GetUserGroup(message.SenderId))
|
||||
// .SendAsync(ChatHubConstants.MessageSent, message);
|
||||
}
|
||||
|
||||
public async Task NotifyMessageWasReadAsync(MessageReadResponse response)
|
||||
{
|
||||
await NotifyParticipantsAsync(
|
||||
response.ReaderId,
|
||||
response.RecipientId,
|
||||
response.RecipientType,
|
||||
ChatHubConstants.MessageRead,
|
||||
response);
|
||||
// Keep the existing wire name for old clients; new clients can use MessageRead.
|
||||
await TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
|
||||
response.RecipientType, ChatHubConstants.MessageRead, response));
|
||||
await TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
|
||||
response.RecipientType, "MessageRead", response));
|
||||
}
|
||||
|
||||
private async Task NotifyMessageReceivedInPrivateChatAsync(UserMessageResponse message)
|
||||
{
|
||||
|
||||
var result = await _userPrivateChatsGetterService.GetPrivateChatAsync(message.RecipientId);
|
||||
|
||||
if(result.IsFailure)
|
||||
return;
|
||||
var privateChat = result.Value;
|
||||
|
||||
var text = message.EncryptedContent.Substring(0, Math.Min(40, message.EncryptedContent.Length));
|
||||
var userId = message.SenderId == privateChat.UserAId ? privateChat.UserBId : privateChat.UserAId;
|
||||
|
||||
var resultProf = await _profileService.GetUserProfileAsync(message.SenderId);
|
||||
|
||||
if(resultProf.IsFailure)
|
||||
return;
|
||||
var profile = resultProf.Value;
|
||||
|
||||
var title = profile.Username;
|
||||
Dictionary<string, string> data = new Dictionary<string, string>();
|
||||
|
||||
data["chatId"] = message.RecipientId.ToString();
|
||||
data["isGroup"] = message.RecipientType == RecipientType.Group ? "true" : "false";
|
||||
|
||||
await _notificationService.SendToUserAsync(
|
||||
userId,
|
||||
title,
|
||||
text,
|
||||
"chat_messages",
|
||||
$"private_chat_{message.RecipientId}",
|
||||
data);
|
||||
}
|
||||
|
||||
public async Task NotifyMessageRemovedAsync(MessageRemovedResponse response)
|
||||
{
|
||||
await NotifyParticipantsAsync(
|
||||
response.SenderId,
|
||||
response.RecipientId,
|
||||
response.RecipientType,
|
||||
ChatHubConstants.MessageRemoved,
|
||||
response);
|
||||
}
|
||||
public Task NotifyChatReadAsync(ChatReadResponse response) =>
|
||||
TryNotifyAsync(() => NotifyParticipantsAsync(response.ChatId,
|
||||
response.RecipientType, ChatHubConstants.ChatRead, response));
|
||||
|
||||
public async Task NotifyMessageEditedAsync(MessageEditResponse response)
|
||||
{
|
||||
await NotifyParticipantsAsync(
|
||||
response.EditorId,
|
||||
response.RecipientId,
|
||||
response.RecipientType,
|
||||
ChatHubConstants.MessageEdited,
|
||||
response);
|
||||
}
|
||||
|
||||
private async Task NotifyParticipantsAsync(Guid initiatorId, Guid targetId, RecipientType type, string method, object payload)
|
||||
public Task NotifyMessageReactionsChangedAsync(MessageReactionsChangedResponse response) =>
|
||||
TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
|
||||
response.RecipientType, ChatHubConstants.MessageReactionsChanged, response));
|
||||
|
||||
public Task NotifyChannelReactionPolicyChangedAsync(ChannelReactionPolicyResponse response) =>
|
||||
TryNotifyAsync(() => NotifyParticipantsAsync(response.GroupId,
|
||||
RecipientType.Group, ChatHubConstants.ChannelReactionPolicyChanged, response));
|
||||
|
||||
public Task NotifyMessageRemovedAsync(MessageRemovedResponse response) =>
|
||||
TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
|
||||
response.RecipientType, ChatHubConstants.MessageRemoved, response));
|
||||
|
||||
public Task NotifyMessageEditedAsync(MessageEditResponse response) =>
|
||||
TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
|
||||
response.RecipientType, ChatHubConstants.MessageEdited, response));
|
||||
|
||||
private async Task NotifyParticipantsAsync(Guid chatId, RecipientType type, string method, object payload)
|
||||
{
|
||||
// Resolve current participants instead of treating a chat ID as a user ID.
|
||||
// Deliver only to active sessions, including all of a participant's devices.
|
||||
List<Guid> participants;
|
||||
if (type == RecipientType.User)
|
||||
{
|
||||
await _hubContext.Clients.Group(ChatHubConstants.GetUserGroup(initiatorId))
|
||||
.SendAsync(method, payload);
|
||||
|
||||
if (initiatorId != targetId)
|
||||
{
|
||||
await _hubContext.Clients.Group(ChatHubConstants.GetUserGroup(targetId))
|
||||
.SendAsync(method, payload);
|
||||
}
|
||||
var result = await _chats.GetPrivateChatAsync(chatId);
|
||||
if (result.IsFailure)
|
||||
return;
|
||||
participants = new[] { result.Value.UserAId, result.Value.UserBId }.Distinct().ToList();
|
||||
}
|
||||
else
|
||||
{
|
||||
// to groups
|
||||
await _hubContext.Clients.Group(ChatHubConstants.GetChatGroup(targetId))
|
||||
participants = await _context.GroupMemberships.AsNoTracking()
|
||||
.Where(m => m.GroupId == chatId && !m.IsBanned).Select(m => m.UserId).Distinct().ToListAsync();
|
||||
|
||||
if (participants.Count > 0)
|
||||
await NotifyUsersAsync(participants, method, payload);
|
||||
}
|
||||
|
||||
private async Task NotifyUsersAsync(IEnumerable<Guid> users, string method, object payload)
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
var sessions = await _context.UserSessions.AsNoTracking()
|
||||
.Where(s => users.Contains(s.UserId) && !s.IsRevoked && s.ExpiresAt > now)
|
||||
.Select(s => s.Id).ToListAsync();
|
||||
if (sessions.Count > 0)
|
||||
await _hubContext.Clients.Groups(sessions.Select(ChatHubConstants.GetSessionGroup).ToList())
|
||||
.SendAsync(method, payload);
|
||||
}
|
||||
|
||||
private async Task TryNotifyAsync(Func<Task> notify)
|
||||
{
|
||||
try
|
||||
{
|
||||
await notify();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to deliver chat notification; clients can resync from history.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
using Govor.Application.Infrastructure.Common;
|
||||
using Govor.Contracts.Responses.SignalR;
|
||||
using Govor.Domain;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Govor.API.Hubs.Infrastructure;
|
||||
|
||||
public class ChatPushDispatcher(GovorDbContext context, IChatNotificationService notifier,
|
||||
INowDateTimeProvider dateTimeProvider)
|
||||
{
|
||||
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);
|
||||
|
||||
foreach (var id in pending)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
// 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)
|
||||
.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);
|
||||
if (delivered)
|
||||
await context.ChatPushNotifications.Where(n => n.MessageId == id)
|
||||
.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)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(n => n.NextAttemptAt, retryAt), cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace Govor.API.Hubs.Infrastructure;
|
||||
|
||||
public class ChatPushWorker(IServiceScopeFactory scopeFactory, ILogger<ChatPushWorker> logger) : BackgroundService
|
||||
{
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
await scope.ServiceProvider.GetRequiredService<ChatPushDispatcher>().DispatchAsync(stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Chat push dispatch failed; pending notifications will be retried.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,11 @@ namespace Govor.API.Hubs.Infrastructure;
|
||||
public interface IChatNotificationService
|
||||
{
|
||||
Task NotifyMessageSentAsync(UserMessageResponse message);
|
||||
Task<bool> DeliverPushAsync(UserMessageResponse message);
|
||||
Task NotifyMessageWasReadAsync(MessageReadResponse response);
|
||||
Task NotifyChatReadAsync(ChatReadResponse response);
|
||||
Task NotifyMessageReactionsChangedAsync(MessageReactionsChangedResponse response);
|
||||
Task NotifyChannelReactionPolicyChangedAsync(ChannelReactionPolicyResponse response);
|
||||
Task NotifyMessageRemovedAsync(MessageRemovedResponse response);
|
||||
Task NotifyMessageEditedAsync(MessageEditResponse response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Govor.API.Common.SignalR.Helpers;
|
||||
using Govor.Application.Friends;
|
||||
using Govor.API.Common.Extensions;
|
||||
using Govor.Application.Medias;
|
||||
using Govor.Application.Profiles;
|
||||
using Govor.Application.Synching;
|
||||
@@ -101,9 +102,11 @@ public sealed class ProfileHub : Hub
|
||||
|
||||
try
|
||||
{
|
||||
await _profileService.SetDescription(
|
||||
var result = await _profileService.SetDescription(
|
||||
description,
|
||||
userId);
|
||||
if (result.IsFailure)
|
||||
return result.Error.ToHubResult<bool>();
|
||||
|
||||
var payload = new DescriptionUpdatePayload
|
||||
{
|
||||
@@ -146,9 +149,11 @@ public sealed class ProfileHub : Hub
|
||||
return HubResult<bool>.BadRequest(
|
||||
"Invalid icon id.");
|
||||
|
||||
await _profileService.SetNewIcon(
|
||||
var result = await _profileService.SetNewIcon(
|
||||
userId,
|
||||
iconId);
|
||||
if (result.IsFailure)
|
||||
return result.Error.ToHubResult<bool>();
|
||||
|
||||
var payload = new AvatarUpdatePayload
|
||||
{
|
||||
@@ -265,4 +270,4 @@ public sealed class ProfileHub : Hub
|
||||
{
|
||||
return $"{UserGroupPrefix}{userId}";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+35
-27
@@ -1,4 +1,4 @@
|
||||
using System.Text;
|
||||
using System.Text;
|
||||
using FirebaseAdmin;
|
||||
using Google.Apis.Auth.OAuth2;
|
||||
using Govor.API.Common.Extensions;
|
||||
@@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using Microsoft.OpenApi;
|
||||
using Govor.Domain;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
@@ -18,23 +19,23 @@ builder.AddLogger();// Serilog
|
||||
|
||||
builder.Configuration.AddJsonFile("configs/ban_usernames.json", optional: false, reloadOnChange: true);
|
||||
|
||||
#if DEBUG
|
||||
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
|
||||
//builder.Configuration.AddJsonFile("appsettings.Development.json", optional: false, reloadOnChange: true);
|
||||
#else
|
||||
builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
|
||||
#endif
|
||||
|
||||
FirebaseApp.Create(new AppOptions()
|
||||
if (configuration.GetValue("Firebase:Enabled", true))
|
||||
{
|
||||
Credential = GoogleCredential.FromFile("secrets/firebase-adminsdk.json")
|
||||
});
|
||||
FirebaseApp.Create(new AppOptions()
|
||||
{
|
||||
Credential = GoogleCredential.FromFile("secrets/firebase-adminsdk.json")
|
||||
});
|
||||
}
|
||||
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("AllowFrontend", policy =>
|
||||
{
|
||||
policy.SetIsOriginAllowed(_ => true)
|
||||
var origins = configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];
|
||||
if (origins.Length > 0)
|
||||
policy.WithOrigins(origins);
|
||||
policy
|
||||
.AllowAnyHeader()
|
||||
.AllowAnyMethod()
|
||||
.AllowCredentials();
|
||||
@@ -60,6 +61,12 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
};
|
||||
options.Events = new JwtBearerEvents
|
||||
{
|
||||
OnTokenValidated = async context =>
|
||||
{
|
||||
var db = context.HttpContext.RequestServices.GetRequiredService<GovorDbContext>();
|
||||
if (!await db.HasActiveSessionAsync(context.Principal))
|
||||
context.Fail("The access session is invalid or revoked.");
|
||||
},
|
||||
OnMessageReceived = context =>
|
||||
{
|
||||
var accessToken = context.Request.Query["access_token"];
|
||||
@@ -110,25 +117,24 @@ services.AddSwaggerGen(options =>
|
||||
|
||||
//builder.Services.AddOpenApi();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
// Configure the HTTP request pipeline.
|
||||
if (!app.Environment.IsDevelopment())
|
||||
if (!builder.Environment.IsDevelopment() && string.IsNullOrWhiteSpace(configuration["urls"]) &&
|
||||
string.IsNullOrWhiteSpace(configuration["HTTP_PORTS"]))
|
||||
{
|
||||
//app.MapOpenApi();
|
||||
builder.WebHost.UseUrls("http://0.0.0.0:8080");
|
||||
//builder.WebHost.UseUrls("http://10.8.0.5:5000");
|
||||
//builder.WebHost.UseUrls("http://192.168.1.107:8080");
|
||||
}
|
||||
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseCors("AllowFrontend");
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
|
||||
//app.UseHttpsRedirection();
|
||||
|
||||
app.UseRouting();
|
||||
app.UseCors("AllowFrontend");
|
||||
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
@@ -136,16 +142,18 @@ app.UseAuthorization();
|
||||
app.MapControllers();
|
||||
|
||||
app.MapGet("/server/ping",
|
||||
() => new OkResult());
|
||||
() => Results.Ok());
|
||||
|
||||
app.MapHub<ChatsHub>("/hubs/chats");
|
||||
app.MapHub<FriendsHub>("/hubs/friends");
|
||||
app.MapHub<ProfileHub>("/hubs/profiles");
|
||||
app.MapHub<PresenceHub>("/hubs/presence");
|
||||
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.MapSwagger()
|
||||
.RequireAuthorization();
|
||||
|
||||
app.Map("/", () => "Not for browsers");
|
||||
|
||||
app.Run();
|
||||
app.Run();
|
||||
|
||||
public partial class Program { }
|
||||
|
||||
Reference in New Issue
Block a user