mirror of
https://github.com/Govor-team/Govor.git
synced 2026-07-21 19:54:55 +00:00
Refactor: migrate Core -> Domain and reorganize projects
Large refactor that renames/moves core types into a new Govor.Domain surface and reorganizes the Application layer. Models, configurations, migrations and many files moved from Govor.Core/Govor.Data to Govor.Domain; numerous Application services, interfaces and implementations were relocated or added (authentication, friends, messages, medias, push notifications, user sessions, storage, synching, private chats, etc.). Tests updated to use Govor.Domain namespaces and adjusted project references (removed Govor.Data reference from API tests). Also updated API, Hub and mapping code and project files to reflect the new structure and naming. This is primarily a codebase-wide namespace and module reorganization to establish a Domain project and restructure application services.
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
using Govor.Domain.Common;
|
||||
|
||||
namespace Govor.Application.PushNotifications;
|
||||
|
||||
public interface IPushNotificationService
|
||||
{
|
||||
Task<Result> SendToUserAsync(Guid userId, string title, string body, string channelId, string tag = "", Dictionary<string, string>? data = null);
|
||||
|
||||
Task<Result> SendToUsersAsync(IEnumerable<Guid> userIds, string title, string body, string channelId, string tag = "", Dictionary<string, string>? data = null);
|
||||
|
||||
Task<Result> SendToSessionAsync(Guid sessionId, string title, string body, string channelId, string tag = "", Dictionary<string, string>? data = null);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Govor.Domain.Common;
|
||||
|
||||
namespace Govor.Application.PushNotifications;
|
||||
|
||||
public interface IPushTokenService
|
||||
{
|
||||
Task<Result> DeactivateTokenBySessionAsync(Guid sessionId);
|
||||
Task<Result> DeactivateAllTokensByUserIdAsync(Guid userId);
|
||||
Task<Result<List<string>>> GetStringsActiveTokensAsync(Guid userId);
|
||||
Task<Result<List<string>>> GetUsersStringsActiveTokensAsync(IEnumerable<Guid> userIds);
|
||||
Task<Result<string?>> GetActiveTokenBySessionAsync(Guid sessionId);
|
||||
Task<Result> RemoveTokensAsync(IEnumerable<string> tokens);
|
||||
Task<Result> AddOrUpdateTokenAsync(Guid userId, Guid sessionId, string token, string platform);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Govor.Application.Interfaces.PushNotifications.Models;
|
||||
|
||||
public class PushMessage
|
||||
{
|
||||
public string Title { get; set; } = string.Empty;
|
||||
public string Body { get; set; } = string.Empty;
|
||||
public string Tag { get; set; } = string.Empty;
|
||||
public Dictionary<string, string> Data { get; set; } = new();
|
||||
public string? ChannelId { get; set; } = "chat_messages"; //for Android
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
namespace Govor.Application.Interfaces.PushNotifications.Models;
|
||||
|
||||
public record SendPushResult(int SuccessCount, int FailureCount, IEnumerable<string> FailedTokens);
|
||||
@@ -0,0 +1,131 @@
|
||||
using FirebaseAdmin.Messaging;
|
||||
using Govor.Application.Interfaces.PushNotifications;
|
||||
using Govor.Application.Interfaces.PushNotifications.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Govor.Application.PushNotifications.Providers;
|
||||
|
||||
public class FirebasePushProvider : IPushNotificationProvider
|
||||
{
|
||||
private readonly ILogger<FirebasePushProvider> _logger;
|
||||
public FirebasePushProvider(ILogger<FirebasePushProvider> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public string Name => "FCM";
|
||||
|
||||
public async Task<SendPushResult> SendToTokenAsync(string token, PushMessage message)
|
||||
{
|
||||
var msg = BuildFcmMessage(message, token: token);
|
||||
|
||||
try
|
||||
{
|
||||
string response = await FirebaseMessaging.DefaultInstance.SendAsync(msg);
|
||||
return new SendPushResult(1, 0, []);
|
||||
}
|
||||
catch (FirebaseMessagingException ex)
|
||||
{
|
||||
if (IsInvalidTokenError(ex))
|
||||
{
|
||||
_logger.LogError(ex, "FCM send failed");
|
||||
return new SendPushResult(0, 1, [token]);
|
||||
}
|
||||
|
||||
throw; // return failed
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<SendPushResult> SendMulticastAsync(IReadOnlyList<string> tokens, PushMessage message)
|
||||
{
|
||||
if (tokens.Count == 0)
|
||||
return new SendPushResult(0, 0, []);
|
||||
|
||||
var multicastMsg = new MulticastMessage
|
||||
{
|
||||
Tokens = tokens,
|
||||
Notification = new Notification
|
||||
{
|
||||
Title = message.Title,
|
||||
Body = message.Body,
|
||||
},
|
||||
Data = message.Data,
|
||||
Android = message.ChannelId != null ? new AndroidConfig
|
||||
{
|
||||
Priority = Priority.High,
|
||||
Notification = new AndroidNotification
|
||||
{
|
||||
ChannelId = message.ChannelId ?? "chat_messages",
|
||||
Tag = message.Tag,
|
||||
}
|
||||
} : null
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
var response = await FirebaseMessaging.DefaultInstance.SendEachForMulticastAsync(multicastMsg);
|
||||
|
||||
var failedTokens = new List<string>();
|
||||
|
||||
for (int i = 0; i < response.Responses.Count; i++)
|
||||
{
|
||||
if (!response.Responses[i].IsSuccess)
|
||||
{
|
||||
var ex = response.Responses[i].Exception;
|
||||
|
||||
if (ex != null && IsInvalidTokenError(ex))
|
||||
{
|
||||
failedTokens.Add(tokens[i]); // invalid
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return new SendPushResult(
|
||||
response.SuccessCount,
|
||||
response.FailureCount,
|
||||
failedTokens
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "FCM multicast failed");
|
||||
return new SendPushResult(0, tokens.Count, tokens.ToList());
|
||||
}
|
||||
}
|
||||
|
||||
private Message BuildFcmMessage(PushMessage pm, string? token = null)
|
||||
{
|
||||
var msg = new Message
|
||||
{
|
||||
Notification = new Notification
|
||||
{
|
||||
Title = pm.Title,
|
||||
Body = pm.Body
|
||||
},
|
||||
Data = pm.Data,
|
||||
Token = token
|
||||
};
|
||||
|
||||
if (pm.ChannelId is not null)
|
||||
{
|
||||
msg.Android = new AndroidConfig
|
||||
{
|
||||
Priority = Priority.High,
|
||||
Notification = new AndroidNotification
|
||||
{
|
||||
ChannelId = pm.ChannelId,
|
||||
Tag = pm.Tag,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return msg;
|
||||
}
|
||||
|
||||
private static bool IsInvalidTokenError(FirebaseMessagingException ex)
|
||||
{
|
||||
return ex.MessagingErrorCode is MessagingErrorCode.Unregistered
|
||||
or MessagingErrorCode.InvalidArgument
|
||||
or MessagingErrorCode.SenderIdMismatch;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using Govor.Application.Interfaces.PushNotifications.Models;
|
||||
|
||||
namespace Govor.Application.PushNotifications.Providers;
|
||||
|
||||
public interface IPushNotificationProvider
|
||||
{
|
||||
string Name { get; }
|
||||
|
||||
Task<SendPushResult> SendToTokenAsync(string token, PushMessage message);
|
||||
|
||||
Task<SendPushResult> SendMulticastAsync(
|
||||
IReadOnlyList<string> tokens,
|
||||
PushMessage message);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using Govor.Application.Interfaces.PushNotifications;
|
||||
using Govor.Application.Interfaces.PushNotifications.Models;
|
||||
|
||||
namespace Govor.Application.PushNotifications.Providers;
|
||||
|
||||
public class NullPushProvider : IPushNotificationProvider
|
||||
{
|
||||
public string Name => "NULL";
|
||||
|
||||
public Task<SendPushResult> SendToTokenAsync(string token, PushMessage message)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<SendPushResult> SendMulticastAsync(IReadOnlyList<string> tokens, PushMessage message)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
using Govor.Application.Interfaces.PushNotifications.Models;
|
||||
using Govor.Application.PushNotifications.Providers;
|
||||
using Govor.Domain.Common;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Govor.Application.PushNotifications;
|
||||
|
||||
public class PushNotificationService : IPushNotificationService
|
||||
{
|
||||
private readonly IPushNotificationProvider _provider;
|
||||
private readonly IPushTokenService _tokenService;
|
||||
private readonly ILogger<PushNotificationService> _logger;
|
||||
|
||||
public PushNotificationService(
|
||||
IPushNotificationProvider provider,
|
||||
IPushTokenService tokenService,
|
||||
ILogger<PushNotificationService> logger)
|
||||
{
|
||||
_provider = provider;
|
||||
_tokenService = tokenService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<Result> SendToUserAsync(Guid userId, string title, string body, string channelId, string tag = "", Dictionary<string, string>? data = null)
|
||||
{
|
||||
var resultTokens = await _tokenService.GetStringsActiveTokensAsync(userId);
|
||||
if (resultTokens.IsFailure)
|
||||
return Result.Failure(resultTokens.Error);
|
||||
|
||||
var tokens = resultTokens.Value;
|
||||
if (tokens.Count == 0)
|
||||
{
|
||||
_logger.LogInformation("No active push tokens for user {UserId}", userId);
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
return await SendMulticastInternalAsync(tokens, title, body, channelId, tag, data, userId.ToString());
|
||||
}
|
||||
|
||||
public async Task<Result> SendToUsersAsync(IEnumerable<Guid> userIds, string title, string body, string channelId, string tag = "", Dictionary<string, string>? data = null)
|
||||
{
|
||||
if (userIds == null || !userIds.Any())
|
||||
return Result.Failure(new Error("Push.InvalidArgs", "User IDs collection cannot be empty."));
|
||||
|
||||
var tokensResult = await _tokenService.GetUsersStringsActiveTokensAsync(userIds);
|
||||
if (tokensResult.IsFailure)
|
||||
return Result.Failure(tokensResult.Error);
|
||||
|
||||
var tokens = tokensResult.Value;
|
||||
if (tokens.Count == 0)
|
||||
return Result.Success();
|
||||
|
||||
return await SendMulticastInternalAsync(tokens, title, body, channelId, tag, data, "bulk_request");
|
||||
}
|
||||
|
||||
public async Task<Result> SendToSessionAsync(Guid sessionId, string title, string body, string channelId, string tag = "", Dictionary<string, string>? data = null)
|
||||
{
|
||||
var tokenResult = await _tokenService.GetActiveTokenBySessionAsync(sessionId);
|
||||
if (tokenResult.IsFailure)
|
||||
return Result.Failure(tokenResult.Error);
|
||||
|
||||
var token = tokenResult.Value;
|
||||
if (string.IsNullOrEmpty(token))
|
||||
return Result.Success();
|
||||
|
||||
try
|
||||
{
|
||||
var message = CreateMessage(title, body, channelId, tag, data);
|
||||
var result = await _provider.SendToTokenAsync(token, message);
|
||||
|
||||
if (result.FailureCount > 0)
|
||||
{
|
||||
await _tokenService.RemoveTokensAsync(result.FailedTokens);
|
||||
_logger.LogWarning("Removed {Count} invalid FCM tokens for session {SessionId}", result.FailureCount, sessionId);
|
||||
}
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to send single push notification to session {SessionId}", sessionId);
|
||||
return Result.Failure(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<Result> SendMulticastInternalAsync(List<string> tokens, string title, string body, string channelId, string tag, Dictionary<string, string>? data, string targetInfo)
|
||||
{
|
||||
try
|
||||
{
|
||||
var message = CreateMessage(title, body, channelId, tag, data);
|
||||
var result = await _provider.SendMulticastAsync(tokens, message);
|
||||
|
||||
if (result.FailureCount > 0)
|
||||
{
|
||||
await _tokenService.RemoveTokensAsync(result.FailedTokens);
|
||||
_logger.LogWarning("Removed {Count} invalid FCM tokens for target: {Target}", result.FailureCount, targetInfo);
|
||||
}
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error occurred during push notification multicast sending to {Target}", targetInfo);
|
||||
return Result.Failure(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static PushMessage CreateMessage(string title, string body, string channelId, string tag, Dictionary<string, string>? data)
|
||||
{
|
||||
return new PushMessage
|
||||
{
|
||||
Title = title,
|
||||
Body = body,
|
||||
Data = data ?? new(),
|
||||
Tag = tag,
|
||||
ChannelId = channelId
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Govor.Application.PushNotifications;
|
||||
|
||||
public class PushTokenService : IPushTokenService
|
||||
{
|
||||
private readonly GovorDbContext _context;
|
||||
private readonly ILogger<PushTokenService> _logger;
|
||||
|
||||
public PushTokenService(GovorDbContext context, ILogger<PushTokenService> logger)
|
||||
{
|
||||
_context = context;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<Result> DeactivateTokenBySessionAsync(Guid sessionId)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _context.UserPushTokens
|
||||
.Where(t => t.UserSessionId == sessionId && t.IsActive)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(t => t.IsActive, false));
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to deactivate push token for session {SessionId}", sessionId);
|
||||
return Result.Failure(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Result> DeactivateAllTokensByUserIdAsync(Guid userId)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _context.UserPushTokens
|
||||
.Where(t => t.UserId == userId && t.IsActive)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(t => t.IsActive, false));
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to deactivate all push tokens for user {UserId}", userId);
|
||||
return Result.Failure(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Result<List<string>>> GetStringsActiveTokensAsync(Guid userId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var tokens = await _context.UserPushTokens
|
||||
.AsNoTracking()
|
||||
.Where(t => t.UserId == userId && t.IsActive)
|
||||
.Select(t => t.Token)
|
||||
.ToListAsync();
|
||||
|
||||
return tokens;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to fetch active push tokens for user {UserId}", userId);
|
||||
return Result<List<string>>.Failure(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Result<List<string>>> GetUsersStringsActiveTokensAsync(IEnumerable<Guid> userIds)
|
||||
{
|
||||
try
|
||||
{
|
||||
var tokens = await _context.UserPushTokens
|
||||
.AsNoTracking()
|
||||
.Where(t => userIds.Contains(t.UserId) && t.IsActive)
|
||||
.Select(t => t.Token)
|
||||
.ToListAsync();
|
||||
|
||||
return tokens;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to fetch active push tokens for bulk users");
|
||||
return Result<List<string>>.Failure(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Result<string?>> GetActiveTokenBySessionAsync(Guid sessionId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var token = await _context.UserPushTokens
|
||||
.AsNoTracking()
|
||||
.Where(t => t.UserSessionId == sessionId && t.IsActive)
|
||||
.Select(t => t.Token)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
return token;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to fetch active push token for session {SessionId}", sessionId);
|
||||
return Result<string?>.Failure(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Result> RemoveTokensAsync(IEnumerable<string> tokens)
|
||||
{
|
||||
if (tokens is null || !tokens.Any())
|
||||
return Result.Success();
|
||||
|
||||
try
|
||||
{
|
||||
await _context.UserPushTokens
|
||||
.Where(t => tokens.Contains(t.Token))
|
||||
.ExecuteDeleteAsync();
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to bulk remove invalid push tokens");
|
||||
return Result.Failure(ex);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Result> AddOrUpdateTokenAsync(Guid userId, Guid sessionId, string token, string platform)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
{
|
||||
return new Error("PushToken.Empty", "Push token cannot be empty.");
|
||||
}
|
||||
|
||||
var existingToken = await _context.UserPushTokens
|
||||
.FirstOrDefaultAsync(t => t.Token == token);
|
||||
|
||||
if (existingToken is null)
|
||||
{
|
||||
var newToken = new UserPushToken
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
UserId = userId,
|
||||
UserSessionId = sessionId,
|
||||
Token = token,
|
||||
Platform = platform,
|
||||
CreatedAt = DateTime.UtcNow
|
||||
};
|
||||
|
||||
await _context.UserPushTokens.AddAsync(newToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
existingToken.UserId = userId;
|
||||
existingToken.UserSessionId = sessionId;
|
||||
existingToken.Platform = platform;
|
||||
existingToken.UpdatedAt = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user