Compare commits
10
Commits
main
..
118f8b8971
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
118f8b8971 | ||
|
|
8165b74e43 | ||
|
|
8ce4bc714f | ||
|
|
2d0bc0d75c | ||
|
|
d7e75797ef | ||
|
|
58bbdae26c | ||
|
|
3310a3c4a4 | ||
|
|
d8b0d86534 | ||
|
|
dc051fa9ae | ||
|
|
1fb1be47dd |
@@ -4,7 +4,6 @@ public interface IJwtTokenProvider
|
|||||||
{
|
{
|
||||||
string GenerateAccessToken(Guid userId, string username);
|
string GenerateAccessToken(Guid userId, string username);
|
||||||
string GenerateRefreshToken();
|
string GenerateRefreshToken();
|
||||||
DateTime GetRefreshTokenExpiry();
|
|
||||||
string Generate(Guid userId, string username, string displayName, string? avatar);
|
string Generate(Guid userId, string username, string displayName, string? avatar);
|
||||||
string Generate(Domain.UserContract user);
|
string Generate(Domain.UserContract user);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,5 @@ public static class AuthErrors
|
|||||||
public static Error IdentityInvalidCredentials => new("Auth.InvalidCredentials", "Invalid credentials");
|
public static Error IdentityInvalidCredentials => new("Auth.InvalidCredentials", "Invalid credentials");
|
||||||
public static Error IdentityRegistrationDisabled => new("Auth.RegistrationDisabled", "Registration is disabled");
|
public static Error IdentityRegistrationDisabled => new("Auth.RegistrationDisabled", "Registration is disabled");
|
||||||
public static Error IdentityUsernameNotUnique => new("Auth.UsernameNotUnique", "Username is already taken");
|
public static Error IdentityUsernameNotUnique => new("Auth.UsernameNotUnique", "Username is already taken");
|
||||||
public static Error IdentityRegistrationFailed => new("Auth.RegistrationFailed", "Failed to register user");
|
|
||||||
public static Error RefreshTokenExpired => new("Auth.RefreshTokenExpired", "Refresh token has expired. Please login again.");
|
|
||||||
public static Error UserNotFound => new("Auth.UserNotFound", "User not found");
|
public static Error UserNotFound => new("Auth.UserNotFound", "User not found");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,12 +19,4 @@ public class UserContract
|
|||||||
public bool IsExternal { get; set; }
|
public bool IsExternal { get; set; }
|
||||||
public string? Domain { get; set; }
|
public string? Domain { get; set; }
|
||||||
public DateTime? LastSeen { get; set; }
|
public DateTime? LastSeen { get; set; }
|
||||||
public string? RefreshToken { get; set; }
|
|
||||||
public DateTime? RefreshTokenExpiry { get; set; }
|
|
||||||
|
|
||||||
public void SetRefreshToken(string? refreshToken, DateTime? expiry = null)
|
|
||||||
{
|
|
||||||
RefreshToken = refreshToken;
|
|
||||||
RefreshTokenExpiry = expiry;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ public interface IMessageRepository
|
|||||||
|
|
||||||
Task<List<Message>> GetChatMessagesCursorAsync(Guid chatId, DateTime? cursor, long? sequenceId, int limit, CancellationToken cancellationToken);
|
Task<List<Message>> GetChatMessagesCursorAsync(Guid chatId, DateTime? cursor, long? sequenceId, int limit, CancellationToken cancellationToken);
|
||||||
Task<List<Message>> GetChatMessagesAroundAsync(Guid chatId, long sequenceId, int limit, CancellationToken cancellationToken);
|
Task<List<Message>> GetChatMessagesAroundAsync(Guid chatId, long sequenceId, int limit, CancellationToken cancellationToken);
|
||||||
Task<List<Message>> GetChatMessagesAfterAsync(Guid chatId, long sequenceId, int limit, CancellationToken cancellationToken);
|
|
||||||
Task<Message?> GetLastStoryMessageAsync(Guid chatId, Guid storyId, CancellationToken cancellationToken);
|
Task<Message?> GetLastStoryMessageAsync(Guid chatId, Guid storyId, CancellationToken cancellationToken);
|
||||||
|
|
||||||
Task UpdateAsync(Message message, CancellationToken cancellationToken);
|
Task UpdateAsync(Message message, CancellationToken cancellationToken);
|
||||||
|
|||||||
@@ -23,9 +23,6 @@ public abstract class Message : AggregateRoot<Guid>
|
|||||||
protected List<DeletedMessage> _deletedFor = new();
|
protected List<DeletedMessage> _deletedFor = new();
|
||||||
public IReadOnlyCollection<DeletedMessage> DeletedFor => _deletedFor.AsReadOnly();
|
public IReadOnlyCollection<DeletedMessage> DeletedFor => _deletedFor.AsReadOnly();
|
||||||
|
|
||||||
protected List<Guid> _readByUsers = new();
|
|
||||||
public IReadOnlyCollection<Guid> ReadByUsers => _readByUsers.AsReadOnly();
|
|
||||||
|
|
||||||
protected Message() : base(Guid.Empty) { }
|
protected Message() : base(Guid.Empty) { }
|
||||||
|
|
||||||
protected Message(Guid id, Guid chatId, Guid senderId, Guid? replyToId, Guid? forwardedFromId, DateTime createdAt, bool isImported)
|
protected Message(Guid id, Guid chatId, Guid senderId, Guid? replyToId, Guid? forwardedFromId, DateTime createdAt, bool isImported)
|
||||||
@@ -56,14 +53,4 @@ public abstract class Message : AggregateRoot<Guid>
|
|||||||
if (!_deletedFor.Exists(x => x.UserId == userId))
|
if (!_deletedFor.Exists(x => x.UserId == userId))
|
||||||
_deletedFor.Add(new DeletedMessage(Id, userId));
|
_deletedFor.Add(new DeletedMessage(Id, userId));
|
||||||
}
|
}
|
||||||
|
|
||||||
public void MarkAsRead(Guid userId)
|
|
||||||
{
|
|
||||||
if (!_readByUsers.Contains(userId))
|
|
||||||
{
|
|
||||||
_readByUsers.Add(userId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool IsReadBy(Guid userId) => _readByUsers.Contains(userId);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,8 +13,7 @@
|
|||||||
"Secret": "knot_super_secret_key_1234567890_knot",
|
"Secret": "knot_super_secret_key_1234567890_knot",
|
||||||
"Issuer": "Knot",
|
"Issuer": "Knot",
|
||||||
"Audience": "KnotUsers",
|
"Audience": "KnotUsers",
|
||||||
"ExpiryInMinutes": 1440,
|
"ExpiryInMinutes": 1440
|
||||||
"RefreshExpiryInDays": 30
|
|
||||||
},
|
},
|
||||||
"KNOT_MASTER_ENCRYPTION_KEY": "knot_super_secret_key_1234567890_knot"
|
"KNOT_MASTER_ENCRYPTION_KEY": "knot_super_secret_key_1234567890_knot"
|
||||||
}
|
}
|
||||||
@@ -5,8 +5,5 @@ namespace Knot.Modules.Auth.Application.Abstractions;
|
|||||||
public interface IJwtTokenProvider
|
public interface IJwtTokenProvider
|
||||||
{
|
{
|
||||||
string Generate(User user);
|
string Generate(User user);
|
||||||
string Generate(Guid userId, string username, string displayName, string? avatar);
|
|
||||||
string GenerateRefreshToken();
|
|
||||||
DateTime GetRefreshTokenExpiry();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
using System.IdentityModel.Tokens.Jwt;
|
using Knot.Contracts.Auth.Application.Auth.DTOs;
|
||||||
using System.Security.Claims;
|
|
||||||
using Knot.Contracts.Auth.Application.Abstractions;
|
|
||||||
using Knot.Contracts.Auth.Application.Auth.DTOs;
|
using Knot.Contracts.Auth.Application.Auth.DTOs;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
|
|
||||||
@@ -11,12 +9,10 @@ public sealed record GetMeQuery(Guid UserId) : IQuery<AuthResponseDto>;
|
|||||||
internal sealed class GetMeQueryHandler : IQueryHandler<GetMeQuery, AuthResponseDto>
|
internal sealed class GetMeQueryHandler : IQueryHandler<GetMeQuery, AuthResponseDto>
|
||||||
{
|
{
|
||||||
private readonly IUserRepository _userRepository;
|
private readonly IUserRepository _userRepository;
|
||||||
private readonly IJwtTokenProvider _tokenProvider;
|
|
||||||
|
|
||||||
public GetMeQueryHandler(IUserRepository userRepository, IJwtTokenProvider tokenProvider)
|
public GetMeQueryHandler(IUserRepository userRepository)
|
||||||
{
|
{
|
||||||
_userRepository = userRepository;
|
_userRepository = userRepository;
|
||||||
_tokenProvider = tokenProvider;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Result<AuthResponseDto>> Handle(GetMeQuery request, CancellationToken cancellationToken)
|
public async Task<Result<AuthResponseDto>> Handle(GetMeQuery request, CancellationToken cancellationToken)
|
||||||
@@ -27,18 +23,9 @@ internal sealed class GetMeQueryHandler : IQueryHandler<GetMeQuery, AuthResponse
|
|||||||
return Result.Failure<AuthResponseDto>(AuthErrors.UserNotFound);
|
return Result.Failure<AuthResponseDto>(AuthErrors.UserNotFound);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if access token needs to be refreshed (less than 1 hour remaining)
|
|
||||||
string? newAccessToken = null;
|
|
||||||
|
|
||||||
// We can't directly check the current token's expiry here, but we can
|
|
||||||
// always issue a new token if the user is authenticated
|
|
||||||
// For now, let's issue a new token on every request (simplified approach)
|
|
||||||
// A better approach would be to parse the incoming token and check expiry
|
|
||||||
newAccessToken = _tokenProvider.Generate(user);
|
|
||||||
|
|
||||||
var response = new AuthResponseDto
|
var response = new AuthResponseDto
|
||||||
{
|
{
|
||||||
AccessToken = newAccessToken,
|
AccessToken = string.Empty,
|
||||||
RefreshToken = string.Empty,
|
RefreshToken = string.Empty,
|
||||||
UserId = user.Id,
|
UserId = user.Id,
|
||||||
Username = user.Username,
|
Username = user.Username,
|
||||||
|
|||||||
@@ -5,6 +5,9 @@ using Knot.Shared.Kernel;
|
|||||||
|
|
||||||
namespace Knot.Modules.Auth.Application.Users.Login;
|
namespace Knot.Modules.Auth.Application.Users.Login;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ������� ��� ����� ������������. ���������� AuthResponseDto.
|
||||||
|
/// </summary>
|
||||||
public sealed record LoginUserCommand(string Username, string Password) : ICommand<AuthResponseDto>;
|
public sealed record LoginUserCommand(string Username, string Password) : ICommand<AuthResponseDto>;
|
||||||
|
|
||||||
public sealed class LoginUserCommandHandler : ICommandHandler<LoginUserCommand, AuthResponseDto>
|
public sealed class LoginUserCommandHandler : ICommandHandler<LoginUserCommand, AuthResponseDto>
|
||||||
@@ -28,21 +31,14 @@ public sealed class LoginUserCommandHandler : ICommandHandler<LoginUserCommand,
|
|||||||
}
|
}
|
||||||
|
|
||||||
string token = _tokenProvider.Generate(user.Id, user.Username, user.DisplayName, user.Avatar);
|
string token = _tokenProvider.Generate(user.Id, user.Username, user.DisplayName, user.Avatar);
|
||||||
string refreshToken = _tokenProvider.GenerateRefreshToken();
|
|
||||||
DateTime refreshExpiry = _tokenProvider.GetRefreshTokenExpiry();
|
|
||||||
|
|
||||||
// Save refresh token to database
|
|
||||||
user.SetRefreshToken(refreshToken, refreshExpiry);
|
|
||||||
await _userRepository.UpdateAsync(user, cancellationToken);
|
|
||||||
|
|
||||||
return Result.Success(new AuthResponseDto
|
return Result.Success(new AuthResponseDto
|
||||||
{
|
{
|
||||||
AccessToken = token,
|
AccessToken = token,
|
||||||
RefreshToken = refreshToken,
|
RefreshToken = string.Empty,
|
||||||
UserId = user.Id,
|
UserId = user.Id,
|
||||||
Username = user.Username,
|
Username = user.Username,
|
||||||
DisplayName = user.DisplayName
|
DisplayName = user.DisplayName
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
using Knot.Contracts.Auth.Application.Auth.DTOs;
|
|
||||||
using Knot.Shared.Kernel;
|
|
||||||
using MediatR;
|
|
||||||
|
|
||||||
namespace Knot.Modules.Auth.Application.Users.RefreshToken;
|
|
||||||
|
|
||||||
public record RefreshTokenCommand(string RefreshToken) : ICommand<AuthResponseDto>;
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
using Knot.Contracts.Auth.Application.Abstractions;
|
|
||||||
using Knot.Contracts.Auth.Application.Auth.DTOs;
|
|
||||||
using Knot.Contracts.Auth.Domain;
|
|
||||||
using Knot.Shared.Kernel;
|
|
||||||
using MediatR;
|
|
||||||
|
|
||||||
namespace Knot.Modules.Auth.Application.Users.RefreshToken;
|
|
||||||
|
|
||||||
internal sealed class RefreshTokenCommandHandler : ICommandHandler<RefreshTokenCommand, AuthResponseDto>
|
|
||||||
{
|
|
||||||
private readonly IUserRepository _userRepository;
|
|
||||||
private readonly IJwtTokenProvider _tokenProvider;
|
|
||||||
|
|
||||||
public RefreshTokenCommandHandler(
|
|
||||||
IUserRepository userRepository,
|
|
||||||
IJwtTokenProvider tokenProvider)
|
|
||||||
{
|
|
||||||
_userRepository = userRepository;
|
|
||||||
_tokenProvider = tokenProvider;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<Result<AuthResponseDto>> Handle(RefreshTokenCommand request, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
if (string.IsNullOrWhiteSpace(request.RefreshToken))
|
|
||||||
{
|
|
||||||
return Result.Failure<AuthResponseDto>(
|
|
||||||
new Error("Auth.InvalidRefreshToken", "Refresh token is required"));
|
|
||||||
}
|
|
||||||
|
|
||||||
var user = await _userRepository.GetByRefreshTokenAsync(request.RefreshToken, cancellationToken);
|
|
||||||
if (user == null)
|
|
||||||
{
|
|
||||||
return Result.Failure<AuthResponseDto>(
|
|
||||||
new Error("Auth.InvalidRefreshToken", "Invalid or expired refresh token"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if refresh token has expired
|
|
||||||
if (user.RefreshTokenExpiry.HasValue && user.RefreshTokenExpiry.Value < DateTime.UtcNow)
|
|
||||||
{
|
|
||||||
// Clear expired refresh token
|
|
||||||
user.SetRefreshToken(null, null);
|
|
||||||
await _userRepository.UpdateAsync(user, cancellationToken);
|
|
||||||
|
|
||||||
return Result.Failure<AuthResponseDto>(
|
|
||||||
new Error("Auth.RefreshTokenExpired", "Refresh token has expired. Please login again."));
|
|
||||||
}
|
|
||||||
|
|
||||||
var newAccessToken = _tokenProvider.Generate(user.Id, user.Username, user.DisplayName, user.Avatar);
|
|
||||||
|
|
||||||
var newRefreshToken = _tokenProvider.GenerateRefreshToken();
|
|
||||||
var newRefreshExpiry = _tokenProvider.GetRefreshTokenExpiry();
|
|
||||||
user.SetRefreshToken(newRefreshToken, newRefreshExpiry);
|
|
||||||
await _userRepository.UpdateAsync(user, cancellationToken);
|
|
||||||
|
|
||||||
return Result.Success(new AuthResponseDto
|
|
||||||
{
|
|
||||||
AccessToken = newAccessToken,
|
|
||||||
RefreshToken = newRefreshToken,
|
|
||||||
UserId = user.Id,
|
|
||||||
Username = user.Username,
|
|
||||||
DisplayName = user.DisplayName,
|
|
||||||
Avatar = user.Avatar
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using BCrypt.Net;
|
using BCrypt.Net;
|
||||||
|
using BCrypt.Net;
|
||||||
using Knot.Contracts.Auth.Application.Abstractions;
|
using Knot.Contracts.Auth.Application.Abstractions;
|
||||||
using Knot.Contracts.Auth.Application.Auth.DTOs;
|
using Knot.Contracts.Auth.Application.Auth.DTOs;
|
||||||
using Knot.Contracts.Settings.Application.Abstractions;
|
using Knot.Contracts.Settings.Application.Abstractions;
|
||||||
@@ -8,6 +9,9 @@ using Knot.Shared.Kernel;
|
|||||||
|
|
||||||
namespace Knot.Modules.Auth.Application.Users.Register;
|
namespace Knot.Modules.Auth.Application.Users.Register;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ������� ��� ����������� ������ ������������.
|
||||||
|
/// </summary>
|
||||||
public sealed record RegisterUserCommand(
|
public sealed record RegisterUserCommand(
|
||||||
string Username,
|
string Username,
|
||||||
string Password,
|
string Password,
|
||||||
@@ -15,6 +19,9 @@ public sealed record RegisterUserCommand(
|
|||||||
string? Email,
|
string? Email,
|
||||||
string? Bio) : ICommand<AuthResponseDto>;
|
string? Bio) : ICommand<AuthResponseDto>;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// ���������� ������� �����������.
|
||||||
|
/// </summary>
|
||||||
internal sealed class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, AuthResponseDto>
|
internal sealed class RegisterUserCommandHandler : ICommandHandler<RegisterUserCommand, AuthResponseDto>
|
||||||
{
|
{
|
||||||
private readonly IUserRepository _userRepository;
|
private readonly IUserRepository _userRepository;
|
||||||
@@ -41,13 +48,16 @@ internal sealed class RegisterUserCommandHandler : ICommandHandler<RegisterUserC
|
|||||||
return Result.Failure<AuthResponseDto>(AuthErrors.IdentityRegistrationDisabled);
|
return Result.Failure<AuthResponseDto>(AuthErrors.IdentityRegistrationDisabled);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 1. �������� ������������ username
|
||||||
if (!await _userRepository.IsUsernameUniqueAsync(request.Username, cancellationToken))
|
if (!await _userRepository.IsUsernameUniqueAsync(request.Username, cancellationToken))
|
||||||
{
|
{
|
||||||
return Result.Failure<AuthResponseDto>(AuthErrors.IdentityUsernameNotUnique);
|
return Result.Failure<AuthResponseDto>(AuthErrors.IdentityUsernameNotUnique);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 2. ����������� ������
|
||||||
string passwordHash = BCrypt.Net.BCrypt.HashPassword(request.Password);
|
string passwordHash = BCrypt.Net.BCrypt.HashPassword(request.Password);
|
||||||
|
|
||||||
|
// 3. �������� ��������
|
||||||
var user = User.Create(
|
var user = User.Create(
|
||||||
request.Username,
|
request.Username,
|
||||||
passwordHash,
|
passwordHash,
|
||||||
@@ -55,33 +65,21 @@ internal sealed class RegisterUserCommandHandler : ICommandHandler<RegisterUserC
|
|||||||
request.Email,
|
request.Email,
|
||||||
request.Bio);
|
request.Bio);
|
||||||
|
|
||||||
var repoImpl = _userRepository as Infrastructure.Persistence.UserRepository;
|
// 4. ���������� - ���������� ����� � Domain User
|
||||||
repoImpl?.Add(user);
|
var repoWithDomainUserAdd = _userRepository as Infrastructure.Persistence.UserRepository;
|
||||||
|
repoWithDomainUserAdd?.Add(user);
|
||||||
|
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
// Get the saved user as contract
|
string token = _tokenProvider.Generate(user.Id, user.Username, user.DisplayName, user.Avatar);
|
||||||
var userContract = await _userRepository.GetByUsernameAsync(request.Username, cancellationToken);
|
|
||||||
if (userContract == null)
|
|
||||||
{
|
|
||||||
return Result.Failure<AuthResponseDto>(AuthErrors.IdentityRegistrationFailed);
|
|
||||||
}
|
|
||||||
|
|
||||||
string token = _tokenProvider.Generate(userContract.Id, userContract.Username, userContract.DisplayName, userContract.Avatar);
|
|
||||||
string refreshToken = _tokenProvider.GenerateRefreshToken();
|
|
||||||
DateTime refreshExpiry = _tokenProvider.GetRefreshTokenExpiry();
|
|
||||||
|
|
||||||
userContract.SetRefreshToken(refreshToken, refreshExpiry);
|
|
||||||
await _userRepository.UpdateAsync(userContract, cancellationToken);
|
|
||||||
|
|
||||||
return Result.Success(new AuthResponseDto
|
return Result.Success(new AuthResponseDto
|
||||||
{
|
{
|
||||||
AccessToken = token,
|
AccessToken = token,
|
||||||
RefreshToken = refreshToken,
|
RefreshToken = string.Empty,
|
||||||
UserId = userContract.Id,
|
UserId = user.Id,
|
||||||
Username = userContract.Username,
|
Username = user.Username,
|
||||||
DisplayName = userContract.DisplayName
|
DisplayName = user.DisplayName
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ public sealed class User : AggregateRoot<Guid>
|
|||||||
public bool IsBanned { get; private set; }
|
public bool IsBanned { get; private set; }
|
||||||
public string? PhoneNumber { get; private set; }
|
public string? PhoneNumber { get; private set; }
|
||||||
public string? RefreshToken { get; private set; }
|
public string? RefreshToken { get; private set; }
|
||||||
public DateTime? RefreshTokenExpiry { get; private set; }
|
|
||||||
public DateTime? BannedUntil { get; private set; }
|
public DateTime? BannedUntil { get; private set; }
|
||||||
|
|
||||||
public void Ban() {
|
public void Ban() {
|
||||||
@@ -49,10 +48,9 @@ public sealed class User : AggregateRoot<Guid>
|
|||||||
PhoneNumber = phoneNumber;
|
PhoneNumber = phoneNumber;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void SetRefreshToken(string? refreshToken, DateTime? expiry = null)
|
public void SetRefreshToken(string? refreshToken)
|
||||||
{
|
{
|
||||||
RefreshToken = refreshToken;
|
RefreshToken = refreshToken;
|
||||||
RefreshTokenExpiry = expiry;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void SetBannedUntil(DateTime? bannedUntil)
|
public void SetBannedUntil(DateTime? bannedUntil)
|
||||||
@@ -81,8 +79,6 @@ public sealed class User : AggregateRoot<Guid>
|
|||||||
BannedUntil = contract.BannedUntil;
|
BannedUntil = contract.BannedUntil;
|
||||||
SetOnline(contract.IsOnline, contract.LastSeen);
|
SetOnline(contract.IsOnline, contract.LastSeen);
|
||||||
UserDomain = contract.Domain;
|
UserDomain = contract.Domain;
|
||||||
RefreshToken = contract.RefreshToken;
|
|
||||||
RefreshTokenExpiry = contract.RefreshTokenExpiry;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private User(Guid id, string username, string passwordHash, string displayName, string? email, string? bio = null)
|
private User(Guid id, string username, string passwordHash, string displayName, string? email, string? bio = null)
|
||||||
@@ -185,9 +181,7 @@ public sealed class User : AggregateRoot<Guid>
|
|||||||
IsOnline = IsOnline,
|
IsOnline = IsOnline,
|
||||||
IsExternal = IsExternal,
|
IsExternal = IsExternal,
|
||||||
Domain = _domain,
|
Domain = _domain,
|
||||||
LastSeen = LastSeen,
|
LastSeen = LastSeen
|
||||||
RefreshToken = RefreshToken,
|
|
||||||
RefreshTokenExpiry = RefreshTokenExpiry
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -50,12 +50,6 @@ internal sealed class JwtTokenProvider : IJwtTokenProvider
|
|||||||
return Convert.ToBase64String(randomBytes);
|
return Convert.ToBase64String(randomBytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
public DateTime GetRefreshTokenExpiry()
|
|
||||||
{
|
|
||||||
var expiryInDays = int.Parse(_configuration["Jwt:RefreshExpiryInDays"] ?? "30");
|
|
||||||
return DateTime.UtcNow.AddDays(expiryInDays);
|
|
||||||
}
|
|
||||||
|
|
||||||
public string Generate(Guid userId, string username, string displayName, string? avatar)
|
public string Generate(Guid userId, string username, string displayName, string? avatar)
|
||||||
{
|
{
|
||||||
var claims = new Claim[]
|
var claims = new Claim[]
|
||||||
|
|||||||
-100
@@ -1,100 +0,0 @@
|
|||||||
using System;
|
|
||||||
using Knot.Modules.Auth.Infrastructure.Persistence;
|
|
||||||
using Microsoft.EntityFrameworkCore;
|
|
||||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
|
||||||
using Microsoft.EntityFrameworkCore.Metadata;
|
|
||||||
using Microsoft.EntityFrameworkCore.Migrations;
|
|
||||||
using Microsoft.EntityFrameworkCore.Storage;
|
|
||||||
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
|
|
||||||
|
|
||||||
#nullable disable
|
|
||||||
|
|
||||||
namespace Knot.Modules.Auth.Migrations
|
|
||||||
{
|
|
||||||
/// <inheritdoc />
|
|
||||||
[DbContext(typeof(AuthDbContext))]
|
|
||||||
[Migration("20270419220000_AddRefreshTokenExpiry")]
|
|
||||||
partial class AddRefreshTokenExpiry
|
|
||||||
{
|
|
||||||
/// <inheritdoc />
|
|
||||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
|
||||||
{
|
|
||||||
#pragma warning disable 612, 618
|
|
||||||
modelBuilder
|
|
||||||
.HasAnnotation("ProductVersion", "10.0.0-rc.1.25451.105")
|
|
||||||
.HasAnnotation("Relational:DefaultSchema", "identity");
|
|
||||||
|
|
||||||
modelBuilder.Entity("Knot.Modules.Auth.Domain.User", b =>
|
|
||||||
{
|
|
||||||
b.Property<Guid>("Id")
|
|
||||||
.ValueGeneratedOnAdd()
|
|
||||||
.HasColumnType("uuid");
|
|
||||||
|
|
||||||
b.Property<string>("Avatar")
|
|
||||||
.HasColumnType("text");
|
|
||||||
|
|
||||||
b.Property<DateTime?>("BannedUntil")
|
|
||||||
.HasColumnType("timestamp with time zone");
|
|
||||||
|
|
||||||
b.Property<string>("Bio")
|
|
||||||
.HasColumnType("text");
|
|
||||||
|
|
||||||
b.Property<DateTime?>("Birthday")
|
|
||||||
.HasColumnType("timestamp with time zone");
|
|
||||||
|
|
||||||
b.Property<DateTime>("CreatedAt")
|
|
||||||
.HasColumnType("timestamp with time zone");
|
|
||||||
|
|
||||||
b.Property<string>("DisplayName")
|
|
||||||
.HasColumnType("text");
|
|
||||||
|
|
||||||
b.Property<string>("Domain")
|
|
||||||
.HasColumnType("text");
|
|
||||||
|
|
||||||
b.Property<string>("Email")
|
|
||||||
.HasColumnType("text");
|
|
||||||
|
|
||||||
b.Property<bool>("HideStatus")
|
|
||||||
.HasColumnType("boolean");
|
|
||||||
|
|
||||||
b.Property<bool>("HideStoryViews")
|
|
||||||
.HasColumnType("boolean");
|
|
||||||
|
|
||||||
b.Property<bool>("IsBanned")
|
|
||||||
.HasColumnType("boolean");
|
|
||||||
|
|
||||||
b.Property<bool>("IsExternal")
|
|
||||||
.HasColumnType("boolean");
|
|
||||||
|
|
||||||
b.Property<bool>("IsOnline")
|
|
||||||
.HasColumnType("boolean");
|
|
||||||
|
|
||||||
b.Property<DateTime?>("LastSeen")
|
|
||||||
.HasColumnType("timestamp with time zone");
|
|
||||||
|
|
||||||
b.Property<string>("PasswordHash")
|
|
||||||
.HasColumnType("text");
|
|
||||||
|
|
||||||
b.Property<string>("PhoneNumber")
|
|
||||||
.HasColumnType("text");
|
|
||||||
|
|
||||||
b.Property<string>("RefreshToken")
|
|
||||||
.HasColumnType("text");
|
|
||||||
|
|
||||||
b.Property<DateTime?>("RefreshTokenExpiry")
|
|
||||||
.HasColumnType("timestamp with time zone");
|
|
||||||
|
|
||||||
b.Property<string>("Username")
|
|
||||||
.HasColumnType("text");
|
|
||||||
|
|
||||||
b.HasKey("Id");
|
|
||||||
|
|
||||||
b.HasIndex("Username")
|
|
||||||
.IsUnique();
|
|
||||||
|
|
||||||
b.ToTable("Users", "identity");
|
|
||||||
});
|
|
||||||
#pragma warning restore 612, 618
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
using Microsoft.EntityFrameworkCore.Migrations;
|
|
||||||
|
|
||||||
#nullable disable
|
|
||||||
|
|
||||||
namespace Knot.Modules.Auth.Migrations
|
|
||||||
{
|
|
||||||
/// <inheritdoc />
|
|
||||||
public partial class AddRefreshTokenExpiry : Migration
|
|
||||||
{
|
|
||||||
protected override void Up(MigrationBuilder migrationBuilder)
|
|
||||||
{
|
|
||||||
migrationBuilder.AddColumn<DateTime>(
|
|
||||||
name: "RefreshTokenExpiry",
|
|
||||||
schema: "identity",
|
|
||||||
table: "Users",
|
|
||||||
type: "timestamp with time zone",
|
|
||||||
nullable: true);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected override void Down(MigrationBuilder migrationBuilder)
|
|
||||||
{
|
|
||||||
migrationBuilder.DropColumn(
|
|
||||||
name: "RefreshTokenExpiry",
|
|
||||||
schema: "identity",
|
|
||||||
table: "Users");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +1,12 @@
|
|||||||
using Knot.Modules.Auth.Application.Users.GetMe;
|
|
||||||
using Knot.Modules.Auth.Application.Users.Login;
|
|
||||||
using Knot.Modules.Auth.Application.Users.RefreshToken;
|
|
||||||
using Knot.Modules.Auth.Application.Users.Register;
|
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
|
using Knot.Modules.Auth.Application.Users.Login;
|
||||||
|
using Knot.Modules.Auth.Application.Users.Register;
|
||||||
|
using Knot.Modules.Auth.Application.Users.GetMe;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
using Microsoft.AspNetCore.Builder;
|
using Microsoft.AspNetCore.Builder;
|
||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Microsoft.AspNetCore.Routing;
|
using Microsoft.AspNetCore.Routing;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
namespace Knot.Modules.Auth.Presentation.Endpoints;
|
namespace Knot.Modules.Auth.Presentation.Endpoints;
|
||||||
|
|
||||||
@@ -29,12 +28,6 @@ public static class AuthEndpoints
|
|||||||
return result.IsSuccess ? Results.Ok(result.Value) : Results.Unauthorized();
|
return result.IsSuccess ? Results.Ok(result.Value) : Results.Unauthorized();
|
||||||
});
|
});
|
||||||
|
|
||||||
group.MapPost("refresh", async ([FromBody] RefreshTokenCommand command, ISender sender, CancellationToken ct) =>
|
|
||||||
{
|
|
||||||
var result = await sender.Send(command, ct);
|
|
||||||
return result.IsSuccess ? Results.Ok(result.Value) : Results.Unauthorized();
|
|
||||||
});
|
|
||||||
|
|
||||||
group.MapGet("me", async (ISender sender, IUserContext userContext, CancellationToken ct) =>
|
group.MapGet("me", async (ISender sender, IUserContext userContext, CancellationToken ct) =>
|
||||||
{
|
{
|
||||||
var result = await sender.Send(new GetMeQuery(userContext.UserId), ct);
|
var result = await sender.Send(new GetMeQuery(userContext.UserId), ct);
|
||||||
|
|||||||
+6
-21
@@ -1,15 +1,13 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Linq;
|
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Contracts.Conversations.Application.Abstractions;
|
|
||||||
using Knot.Contracts.Conversations.Domain;
|
|
||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
|
||||||
using Knot.Modules.Conversations.Infrastructure.SignalR;
|
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using Knot.Shared.Kernel.Storage;
|
using Knot.Contracts.Conversations.Domain;
|
||||||
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
using Microsoft.AspNetCore.SignalR;
|
using System.Linq;
|
||||||
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
|
using Knot.Shared.Kernel.Storage;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.Chats.LeaveOrDelete;
|
namespace Knot.Modules.Conversations.Application.Chats.LeaveOrDelete;
|
||||||
|
|
||||||
@@ -21,21 +19,17 @@ internal sealed class LeaveOrDeleteChatCommandHandler : ICommandHandler<LeaveOrD
|
|||||||
private readonly IMessageRepository _messageRepository;
|
private readonly IMessageRepository _messageRepository;
|
||||||
private readonly IFileStorageService _fileStorage;
|
private readonly IFileStorageService _fileStorage;
|
||||||
private readonly IChatsUnitOfWork _uow;
|
private readonly IChatsUnitOfWork _uow;
|
||||||
private readonly IHubContext<ChatHub> _hubContext;
|
|
||||||
|
|
||||||
public LeaveOrDeleteChatCommandHandler(
|
public LeaveOrDeleteChatCommandHandler(
|
||||||
IChatRepository chatRepository,
|
IChatRepository chatRepository,
|
||||||
|
|
||||||
IMessageRepository messageRepository,
|
IMessageRepository messageRepository,
|
||||||
IFileStorageService fileStorage,
|
IFileStorageService fileStorage,
|
||||||
IChatsUnitOfWork uow,
|
IChatsUnitOfWork uow)
|
||||||
IHubContext<ChatHub> hubContext)
|
|
||||||
{
|
{
|
||||||
_chatRepository = chatRepository;
|
_chatRepository = chatRepository;
|
||||||
_messageRepository = messageRepository;
|
_messageRepository = messageRepository;
|
||||||
_fileStorage = fileStorage;
|
_fileStorage = fileStorage;
|
||||||
_uow = uow;
|
_uow = uow;
|
||||||
_hubContext = hubContext;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Result<SuccessResponse>> Handle(LeaveOrDeleteChatCommand request, CancellationToken cancellationToken)
|
public async Task<Result<SuccessResponse>> Handle(LeaveOrDeleteChatCommand request, CancellationToken cancellationToken)
|
||||||
@@ -64,14 +58,6 @@ internal sealed class LeaveOrDeleteChatCommandHandler : ICommandHandler<LeaveOrD
|
|||||||
// DELETE ALL MESSAGES AND FILES FIRST
|
// DELETE ALL MESSAGES AND FILES FIRST
|
||||||
await DeleteChatMediaAndMessagesAsync(chat.Id, cancellationToken);
|
await DeleteChatMediaAndMessagesAsync(chat.Id, cancellationToken);
|
||||||
_chatRepository.Remove(chat);
|
_chatRepository.Remove(chat);
|
||||||
|
|
||||||
// Notify all remaining members that the chat was deleted
|
|
||||||
|
|
||||||
foreach (var member in chat.Members)
|
|
||||||
{
|
|
||||||
await _hubContext.Clients.User(member.UserId.ToString())
|
|
||||||
.SendAsync("chat_deleted", chat.Id.ToString(), cancellationToken);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await _uow.SaveChangesAsync(cancellationToken);
|
await _uow.SaveChangesAsync(cancellationToken);
|
||||||
@@ -82,7 +68,6 @@ internal sealed class LeaveOrDeleteChatCommandHandler : ICommandHandler<LeaveOrD
|
|||||||
private async Task DeleteChatMediaAndMessagesAsync(Guid chatId, CancellationToken ct)
|
private async Task DeleteChatMediaAndMessagesAsync(Guid chatId, CancellationToken ct)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
|
||||||
{
|
{
|
||||||
// Get all messages directly from Mongo (not paged)
|
// Get all messages directly from Mongo (not paged)
|
||||||
var messages = await _messageRepository.GetChatMessagesAsync(chatId, int.MaxValue, 0, ct);
|
var messages = await _messageRepository.GetChatMessagesAsync(chatId, int.MaxValue, 0, ct);
|
||||||
|
|||||||
@@ -32,8 +32,7 @@ public record MessageDetailDto(
|
|||||||
bool? PollIsMultipleChoice = null,
|
bool? PollIsMultipleChoice = null,
|
||||||
bool? PollIsAnonymous = null,
|
bool? PollIsAnonymous = null,
|
||||||
bool? PollIsClosed = null,
|
bool? PollIsClosed = null,
|
||||||
List<Guid>? UserVotedOptionIds = null,
|
List<Guid>? UserVotedOptionIds = null
|
||||||
bool IsDeletedForUser = false
|
|
||||||
);
|
);
|
||||||
|
|
||||||
public record ReplyToMessageDto(
|
public record ReplyToMessageDto(
|
||||||
|
|||||||
+13
-8
@@ -42,16 +42,10 @@ public sealed class DeleteMessagesCommandHandler : ICommandHandler<DeleteMessage
|
|||||||
|
|
||||||
if (request.DeleteForAll)
|
if (request.DeleteForAll)
|
||||||
{
|
{
|
||||||
// Only message sender can delete for everyone
|
|
||||||
if (message.SenderId == request.UserId)
|
if (message.SenderId == request.UserId)
|
||||||
{
|
{
|
||||||
message.Delete();
|
message.Delete();
|
||||||
}
|
}
|
||||||
else
|
|
||||||
{
|
|
||||||
// If not the sender, just delete for current user
|
|
||||||
message.DeleteForUser(request.UserId);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@@ -61,13 +55,24 @@ public sealed class DeleteMessagesCommandHandler : ICommandHandler<DeleteMessage
|
|||||||
await _messageRepository.UpdateAsync(message, cancellationToken);
|
await _messageRepository.UpdateAsync(message, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Notify all clients in the chat about the deletion
|
if (request.DeleteForAll)
|
||||||
|
{
|
||||||
await _hubContext.Clients.Group(request.ChatId.ToString()).SendAsync("messages_deleted", new
|
await _hubContext.Clients.Group(request.ChatId.ToString()).SendAsync("messages_deleted", new
|
||||||
{
|
{
|
||||||
chatId = request.ChatId,
|
chatId = request.ChatId,
|
||||||
messageIds = request.MessageIds,
|
messageIds = request.MessageIds,
|
||||||
deleteForAll = request.DeleteForAll
|
deleteForAll = true
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await _hubContext.Clients.User(request.UserId.ToString()).SendAsync("messages_deleted", new
|
||||||
|
{
|
||||||
|
chatId = request.ChatId,
|
||||||
|
messageIds = request.MessageIds,
|
||||||
|
deleteForAll = false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return global::Knot.Shared.Kernel.Result.Success();
|
return global::Knot.Shared.Kernel.Result.Success();
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-20
@@ -3,17 +3,17 @@ using System.Collections.Generic;
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Contracts.Conversations.Application.Abstractions;
|
|
||||||
using Knot.Contracts.Conversations.Domain;
|
|
||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
using Knot.Contracts.Messaging.Domain;
|
using Knot.Contracts.Messaging.Domain;
|
||||||
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
using Knot.Modules.Conversations.Application.DTOs;
|
using Knot.Modules.Conversations.Application.DTOs;
|
||||||
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.Messages.GetMessages;
|
namespace Knot.Modules.Conversations.Application.Messages.GetMessages;
|
||||||
|
|
||||||
public record GetMessagesQuery(Guid UserId, Guid ChatId, string? Cursor, long? Pivot = null, long? AfterSequenceId = null, int? Limit = null) : IQuery<List<MessageDetailDto>>;
|
public record GetMessagesQuery(Guid UserId, Guid ChatId, string? Cursor, long? Pivot = null, int? Limit = null) : IQuery<List<MessageDetailDto>>;
|
||||||
|
|
||||||
internal sealed class GetMessagesQueryHandler : IQueryHandler<GetMessagesQuery, List<MessageDetailDto>>
|
internal sealed class GetMessagesQueryHandler : IQueryHandler<GetMessagesQuery, List<MessageDetailDto>>
|
||||||
{
|
{
|
||||||
@@ -41,12 +41,7 @@ internal sealed class GetMessagesQueryHandler : IQueryHandler<GetMessagesQuery,
|
|||||||
List<Message> messages;
|
List<Message> messages;
|
||||||
int queryLimit = request.Limit ?? ChatConstants.DefaultMessageQueryLimit;
|
int queryLimit = request.Limit ?? ChatConstants.DefaultMessageQueryLimit;
|
||||||
|
|
||||||
if (request.AfterSequenceId.HasValue)
|
if (request.Pivot.HasValue)
|
||||||
{
|
|
||||||
// Получаем только сообщения ПОСЛЕ указанного sequenceId (для синхронизации)
|
|
||||||
messages = await _messageRepository.GetChatMessagesAfterAsync(request.ChatId, request.AfterSequenceId.Value, queryLimit, cancellationToken);
|
|
||||||
}
|
|
||||||
else if (request.Pivot.HasValue)
|
|
||||||
{
|
{
|
||||||
messages = await _messageRepository.GetChatMessagesAroundAsync(request.ChatId, request.Pivot.Value, queryLimit, cancellationToken);
|
messages = await _messageRepository.GetChatMessagesAroundAsync(request.ChatId, request.Pivot.Value, queryLimit, cancellationToken);
|
||||||
}
|
}
|
||||||
@@ -120,7 +115,6 @@ internal sealed class GetMessagesQueryHandler : IQueryHandler<GetMessagesQuery,
|
|||||||
senders.TryGetValue(message.SenderId, out var sender);
|
senders.TryGetValue(message.SenderId, out var sender);
|
||||||
reactionsByMessage.TryGetValue(message.Id, out var reactions);
|
reactionsByMessage.TryGetValue(message.Id, out var reactions);
|
||||||
|
|
||||||
|
|
||||||
Message? replyMsg = null;
|
Message? replyMsg = null;
|
||||||
if (message.ReplyToId.HasValue)
|
if (message.ReplyToId.HasValue)
|
||||||
{
|
{
|
||||||
@@ -147,7 +141,7 @@ internal sealed class GetMessagesQueryHandler : IQueryHandler<GetMessagesQuery,
|
|||||||
replyMsg is MediaMessage mm ? mm.Media.Select(m => new MediaDto(m.Id, m.Type, m.Url, m.Filename, m.Size, m.Duration)).ToList() : new List<MediaDto>(),
|
replyMsg is MediaMessage mm ? mm.Media.Select(m => new MediaDto(m.Id, m.Type, m.Url, m.Filename, m.Size, m.Duration)).ToList() : new List<MediaDto>(),
|
||||||
replySender != null ? new MessageSenderDto(replySender.Id, replySender.Username, replySender.DisplayName, replySender.Avatar) : null
|
replySender != null ? new MessageSenderDto(replySender.Id, replySender.Username, replySender.DisplayName, replySender.Avatar) : null
|
||||||
) : null,
|
) : null,
|
||||||
(message as TextMessage)?.Quote,
|
message is TextMessage tm ? tm.Quote : null,
|
||||||
message.IsEdited,
|
message.IsEdited,
|
||||||
message.IsDeleted,
|
message.IsDeleted,
|
||||||
message.CreatedAt,
|
message.CreatedAt,
|
||||||
@@ -159,23 +153,20 @@ internal sealed class GetMessagesQueryHandler : IQueryHandler<GetMessagesQuery,
|
|||||||
(message as StoryMessage)?.StoryMediaType,
|
(message as StoryMessage)?.StoryMediaType,
|
||||||
(message as MediaMessage)?.Media.Select(m => new MediaDto(m.Id, m.Type, m.Url, m.Filename, m.Size, m.Duration)).ToList() ?? new List<MediaDto>(),
|
(message as MediaMessage)?.Media.Select(m => new MediaDto(m.Id, m.Type, m.Url, m.Filename, m.Size, m.Duration)).ToList() ?? new List<MediaDto>(),
|
||||||
sender != null ? new MessageSenderDto(sender.Id, sender.Username, sender.DisplayName, sender.Avatar) : new MessageSenderDto(message.SenderId, "unknown", "Unknown", null),
|
sender != null ? new MessageSenderDto(sender.Id, sender.Username, sender.DisplayName, sender.Avatar) : new MessageSenderDto(message.SenderId, "unknown", "Unknown", null),
|
||||||
message.ReadByUsers.Select(id => new ReadByDto(id)).ToList(),
|
new List<ReadByDto>(), // ReadBy not implemented in this detailed view yet
|
||||||
reactions?.Select(r =>
|
reactions?.Select(r => {
|
||||||
{
|
|
||||||
senders.TryGetValue(r.UserId, out var ru);
|
senders.TryGetValue(r.UserId, out var ru);
|
||||||
return new MessageReactionDto(r.Id, r.Emoji, r.UserId, ru != null ? new MessageSenderDto(ru.Id, ru.Username, ru.DisplayName, ru.Avatar) : null);
|
return new MessageReactionDto(r.Id, r.Emoji, r.UserId, ru != null ? new MessageSenderDto(ru.Id, ru.Username, ru.DisplayName, ru.Avatar) : null);
|
||||||
}).ToList() ?? new List<MessageReactionDto>(),
|
}).ToList() ?? new List<MessageReactionDto>(),
|
||||||
(message as CallMessage)?.CallType,
|
(message as CallMessage)?.CallType,
|
||||||
(message as CallMessage)?.CallStatus,
|
(message as CallMessage)?.CallStatus,
|
||||||
(message as CallMessage)?.Duration,
|
(message as CallMessage)?.Duration,
|
||||||
(message as PollMessage)?.Options.Select(o =>
|
(message as PollMessage)?.Options.Select(o => {
|
||||||
{
|
|
||||||
var pm = (PollMessage)message;
|
var pm = (PollMessage)message;
|
||||||
var voters = pm.IsAnonymous == false
|
var voters = pm.IsAnonymous == false
|
||||||
? pm.Votes
|
? pm.Votes
|
||||||
.Where(v => v.OptionId == o.Id)
|
.Where(v => v.OptionId == o.Id)
|
||||||
.Select(v =>
|
.Select(v => {
|
||||||
{
|
|
||||||
senders.TryGetValue(v.UserId, out var vu);
|
senders.TryGetValue(v.UserId, out var vu);
|
||||||
return vu != null
|
return vu != null
|
||||||
? new MessageSenderDto(vu.Id, vu.Username, vu.DisplayName, vu.Avatar)
|
? new MessageSenderDto(vu.Id, vu.Username, vu.DisplayName, vu.Avatar)
|
||||||
@@ -188,8 +179,7 @@ internal sealed class GetMessagesQueryHandler : IQueryHandler<GetMessagesQuery,
|
|||||||
(message as PollMessage)?.IsMultipleChoice,
|
(message as PollMessage)?.IsMultipleChoice,
|
||||||
(message as PollMessage)?.IsAnonymous,
|
(message as PollMessage)?.IsAnonymous,
|
||||||
(message as PollMessage)?.IsClosed,
|
(message as PollMessage)?.IsClosed,
|
||||||
(message as PollMessage)?.Votes.Where(v => v.UserId == request.UserId).Select(v => v.OptionId).ToList(),
|
(message as PollMessage)?.Votes.Where(v => v.UserId == request.UserId).Select(v => v.OptionId).ToList()
|
||||||
message.IsDeletedForUser(request.UserId)
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+4
-24
@@ -1,8 +1,7 @@
|
|||||||
using Knot.Contracts.Conversations.Application.Abstractions;
|
|
||||||
using Knot.Contracts.Conversations.Domain;
|
|
||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
|
||||||
using Knot.Shared.Kernel;
|
|
||||||
using MediatR;
|
using MediatR;
|
||||||
|
using Knot.Contracts.Conversations.Domain;
|
||||||
|
using Knot.Shared.Kernel;
|
||||||
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.Messages.Read;
|
namespace Knot.Modules.Conversations.Application.Messages.Read;
|
||||||
|
|
||||||
@@ -12,13 +11,11 @@ public sealed class ReadMessagesCommandHandler : ICommandHandler<ReadMessagesCom
|
|||||||
{
|
{
|
||||||
private readonly IChatRepository _chatRepository;
|
private readonly IChatRepository _chatRepository;
|
||||||
private readonly IChatsUnitOfWork _unitOfWork;
|
private readonly IChatsUnitOfWork _unitOfWork;
|
||||||
private readonly IMessageRepository _messageRepository;
|
|
||||||
|
|
||||||
public ReadMessagesCommandHandler(IChatRepository chatRepository, IChatsUnitOfWork unitOfWork, IMessageRepository messageRepository)
|
public ReadMessagesCommandHandler(IChatRepository chatRepository, IChatsUnitOfWork unitOfWork)
|
||||||
{
|
{
|
||||||
_chatRepository = chatRepository;
|
_chatRepository = chatRepository;
|
||||||
_unitOfWork = unitOfWork;
|
_unitOfWork = unitOfWork;
|
||||||
_messageRepository = messageRepository;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Result> Handle(ReadMessagesCommand request, CancellationToken cancellationToken)
|
public async Task<Result> Handle(ReadMessagesCommand request, CancellationToken cancellationToken)
|
||||||
@@ -31,23 +28,6 @@ public sealed class ReadMessagesCommandHandler : ICommandHandler<ReadMessagesCom
|
|||||||
|
|
||||||
member.UpdateReadCursor(request.LastReadMessageId, request.LastReadSequenceId);
|
member.UpdateReadCursor(request.LastReadMessageId, request.LastReadSequenceId);
|
||||||
|
|
||||||
// Обновляем ReadByUsers для всех сообщений до LastReadSequenceId
|
|
||||||
var messages = await _messageRepository.GetChatMessagesAfterAsync(
|
|
||||||
request.ChatId,
|
|
||||||
0,
|
|
||||||
1000,
|
|
||||||
cancellationToken);
|
|
||||||
|
|
||||||
foreach (var message in messages)
|
|
||||||
{
|
|
||||||
if (message.SequenceId <= request.LastReadSequenceId &&
|
|
||||||
message.SenderId != request.UserId &&
|
|
||||||
!message.IsReadBy(request.UserId))
|
|
||||||
{
|
|
||||||
message.MarkAsRead(request.UserId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
await _unitOfWork.SaveChangesAsync(cancellationToken);
|
||||||
|
|
||||||
return Result.Success();
|
return Result.Success();
|
||||||
|
|||||||
+3
-4
@@ -3,10 +3,10 @@ using System.Collections.Generic;
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Knot.Contracts.Conversations.Domain;
|
|
||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
using Knot.Contracts.Messaging.Domain;
|
using Knot.Contracts.Messaging.Domain;
|
||||||
using Knot.Modules.Conversations.Application.DTOs;
|
using Knot.Modules.Conversations.Application.DTOs;
|
||||||
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
using MediatR;
|
using MediatR;
|
||||||
|
|
||||||
@@ -41,8 +41,7 @@ internal sealed class SearchMessagesQueryHandler : IQueryHandler<SearchMessagesQ
|
|||||||
var allReactions = await _reactionRepository.GetReactionsForMessagesAsync(messageIds, cancellationToken);
|
var allReactions = await _reactionRepository.GetReactionsForMessagesAsync(messageIds, cancellationToken);
|
||||||
var reactionsByMessage = allReactions.GroupBy(r => r.MessageId).ToDictionary(g => g.Key, g => g.ToList());
|
var reactionsByMessage = allReactions.GroupBy(r => r.MessageId).ToDictionary(g => g.Key, g => g.ToList());
|
||||||
|
|
||||||
var result = messages.Select(message =>
|
var result = messages.Select(message => {
|
||||||
{
|
|
||||||
var textMessage = message as TextMessage;
|
var textMessage = message as TextMessage;
|
||||||
var mediaMessage = message as MediaMessage;
|
var mediaMessage = message as MediaMessage;
|
||||||
var storyMessage = message as StoryMessage;
|
var storyMessage = message as StoryMessage;
|
||||||
@@ -67,7 +66,7 @@ internal sealed class SearchMessagesQueryHandler : IQueryHandler<SearchMessagesQ
|
|||||||
mediaMessage?.Media.Select(media => new MediaDto(media.Id, media.Type, media.Url, media.Filename, media.Size)).ToList() ?? new List<MediaDto>(),
|
mediaMessage?.Media.Select(media => new MediaDto(media.Id, media.Type, media.Url, media.Filename, media.Size)).ToList() ?? new List<MediaDto>(),
|
||||||
senders.TryGetValue(message.SenderId, out var senderUser) ? new MessageSenderDto(senderUser.Id, senderUser.Username, senderUser.DisplayName, senderUser.Avatar) : new MessageSenderDto(message.SenderId, "unknown", "Unknown", null),
|
senders.TryGetValue(message.SenderId, out var senderUser) ? new MessageSenderDto(senderUser.Id, senderUser.Username, senderUser.DisplayName, senderUser.Avatar) : new MessageSenderDto(message.SenderId, "unknown", "Unknown", null),
|
||||||
reactionsByMessage.TryGetValue(message.Id, out var mr) ? mr.Select(reaction => new SimpleReactionDto(reaction.UserId, reaction.Emoji)).ToList() : new List<SimpleReactionDto>(),
|
reactionsByMessage.TryGetValue(message.Id, out var mr) ? mr.Select(reaction => new SimpleReactionDto(reaction.UserId, reaction.Emoji)).ToList() : new List<SimpleReactionDto>(),
|
||||||
message.ReadByUsers.Select(id => new ReadByDto(id)).ToList()
|
new List<ReadByDto>()
|
||||||
);
|
);
|
||||||
}).ToList();
|
}).ToList();
|
||||||
|
|
||||||
|
|||||||
+2
-3
@@ -1,8 +1,8 @@
|
|||||||
using Knot.Contracts.Conversations.Application.Abstractions;
|
|
||||||
using Knot.Contracts.Conversations.Domain;
|
|
||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
using Knot.Contracts.Messaging.Domain;
|
using Knot.Contracts.Messaging.Domain;
|
||||||
using Knot.Contracts.Settings.Application.Abstractions;
|
using Knot.Contracts.Settings.Application.Abstractions;
|
||||||
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
|
using Knot.Contracts.Conversations.Domain;
|
||||||
using Knot.Shared.Kernel;
|
using Knot.Shared.Kernel;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Application.Messages.Send;
|
namespace Knot.Modules.Conversations.Application.Messages.Send;
|
||||||
@@ -192,7 +192,6 @@ public sealed class SendMessageCommandHandler : ICommandHandler<SendMessageComma
|
|||||||
var senderMember = chat.Members.First(m => m.UserId == request.SenderId);
|
var senderMember = chat.Members.First(m => m.UserId == request.SenderId);
|
||||||
senderMember.UpdateReadCursor(message.Id, message.SequenceId);
|
senderMember.UpdateReadCursor(message.Id, message.SequenceId);
|
||||||
senderMember.UpdateDeliveredCursor(message.Id);
|
senderMember.UpdateDeliveredCursor(message.Id);
|
||||||
message.MarkAsRead(request.SenderId); // Отправитель всегда "прочитал" своё сообщение
|
|
||||||
|
|
||||||
// 5. ���������
|
// 5. ���������
|
||||||
_messageRepository.Add(message);
|
_messageRepository.Add(message);
|
||||||
|
|||||||
@@ -1,26 +1,26 @@
|
|||||||
using System.Collections.Concurrent;
|
using System.Collections.Concurrent;
|
||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using Knot.Contracts.Auth.Application.Abstractions;
|
|
||||||
using Knot.Contracts.Auth.Domain;
|
|
||||||
using Knot.Contracts.Conversations.Application.Abstractions;
|
|
||||||
using Knot.Contracts.Conversations.Domain;
|
|
||||||
using Knot.Contracts.Messaging.Application.Abstractions;
|
|
||||||
using Knot.Contracts.Messaging.Domain;
|
|
||||||
using Knot.Modules.Conversations.Application.DTOs;
|
|
||||||
using Knot.Modules.Conversations.Application.Messages.Delete;
|
|
||||||
using Knot.Modules.Conversations.Application.Messages.Edit;
|
|
||||||
using Knot.Modules.Conversations.Application.Messages.Pin;
|
|
||||||
using Knot.Modules.Conversations.Application.Messages.React;
|
|
||||||
using Knot.Modules.Conversations.Application.Messages.Read;
|
|
||||||
using Knot.Modules.Conversations.Application.Messages.Send;
|
|
||||||
using Knot.Modules.Conversations.Application.Messages.Unpin;
|
|
||||||
using Knot.Modules.Conversations.Application.Messages.Vote;
|
|
||||||
using Knot.Shared.Kernel;
|
|
||||||
using MediatR;
|
using MediatR;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.SignalR;
|
using Microsoft.AspNetCore.SignalR;
|
||||||
using Microsoft.Extensions.Caching.Memory;
|
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Knot.Modules.Conversations.Application.Messages.Send;
|
||||||
|
using Knot.Modules.Conversations.Application.Messages.Read;
|
||||||
|
using Knot.Modules.Conversations.Application.Messages.Delete;
|
||||||
|
using Knot.Modules.Conversations.Application.Messages.React;
|
||||||
|
using Knot.Contracts.Conversations.Domain;
|
||||||
|
using Knot.Shared.Kernel;
|
||||||
|
using Microsoft.Extensions.Caching.Memory;
|
||||||
|
using Knot.Contracts.Auth.Domain;
|
||||||
|
using Knot.Contracts.Auth.Application.Abstractions;
|
||||||
|
using Knot.Modules.Conversations.Application.Messages.Pin;
|
||||||
|
using Knot.Modules.Conversations.Application.Messages.Unpin;
|
||||||
|
using Knot.Modules.Conversations.Application.Messages.Vote;
|
||||||
|
using Knot.Modules.Conversations.Application.Messages.Edit;
|
||||||
|
using Knot.Modules.Conversations.Application.DTOs;
|
||||||
|
using Knot.Contracts.Messaging.Application.Abstractions;
|
||||||
|
using Knot.Contracts.Messaging.Domain;
|
||||||
|
using Knot.Contracts.Conversations.Application.Abstractions;
|
||||||
|
|
||||||
namespace Knot.Modules.Conversations.Infrastructure.SignalR;
|
namespace Knot.Modules.Conversations.Infrastructure.SignalR;
|
||||||
|
|
||||||
@@ -158,7 +158,6 @@ public sealed class ChatHub : Hub
|
|||||||
await _sender.Send(command);
|
await _sender.Send(command);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Отправляем событие всем в чате о том, что пользователь прочитал сообщения
|
|
||||||
await Clients.Group(request.ChatId.ToString()).SendAsync("messages_read", new
|
await Clients.Group(request.ChatId.ToString()).SendAsync("messages_read", new
|
||||||
{
|
{
|
||||||
ChatId = request.ChatId.ToString(),
|
ChatId = request.ChatId.ToString(),
|
||||||
|
|||||||
@@ -19,17 +19,9 @@ public static class MessagesEndpoints
|
|||||||
{
|
{
|
||||||
var group = app.MapGroup("api/messages").RequireAuthorization();
|
var group = app.MapGroup("api/messages").RequireAuthorization();
|
||||||
|
|
||||||
group.MapGet("chat/{chatId:guid}", async (
|
group.MapGet("chat/{chatId:guid}", async ([FromRoute] Guid chatId, [FromQuery] string? cursor, ISender sender, IUserContext userContext, CancellationToken ct) =>
|
||||||
[FromRoute] Guid chatId,
|
|
||||||
[FromQuery] string? cursor,
|
|
||||||
[FromQuery] long? afterSequenceId,
|
|
||||||
[FromQuery] long? pivot,
|
|
||||||
[FromQuery] int? limit,
|
|
||||||
ISender sender,
|
|
||||||
IUserContext userContext,
|
|
||||||
CancellationToken ct) =>
|
|
||||||
{
|
{
|
||||||
var result = await sender.Send(new GetMessagesQuery(userContext.UserId, chatId, cursor, pivot, afterSequenceId, limit), ct);
|
var result = await sender.Send(new GetMessagesQuery(userContext.UserId, chatId, cursor), ct);
|
||||||
return result.IsSuccess ? Results.Ok(result.Value) : Results.BadRequest(result.Error.Description);
|
return result.IsSuccess ? Results.Ok(result.Value) : Results.BadRequest(result.Error.Description);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -42,10 +42,6 @@ public abstract class Message : AggregateRoot<Guid>
|
|||||||
protected List<DeletedMessage> _deletedFor = new();
|
protected List<DeletedMessage> _deletedFor = new();
|
||||||
public IReadOnlyCollection<DeletedMessage> DeletedFor => _deletedFor.AsReadOnly();
|
public IReadOnlyCollection<DeletedMessage> DeletedFor => _deletedFor.AsReadOnly();
|
||||||
|
|
||||||
// ================== Прочитано ==================
|
|
||||||
protected List<Guid> _readByUsers = new();
|
|
||||||
public IReadOnlyCollection<Guid> ReadByUsers => _readByUsers.AsReadOnly();
|
|
||||||
|
|
||||||
// ================== Инфраструктурный конструктор EF ==================
|
// ================== Инфраструктурный конструктор EF ==================
|
||||||
protected Message() : base(Guid.Empty) { }
|
protected Message() : base(Guid.Empty) { }
|
||||||
|
|
||||||
@@ -93,16 +89,6 @@ public abstract class Message : AggregateRoot<Guid>
|
|||||||
_deletedFor.Add(new DeletedMessage(Id, userId));
|
_deletedFor.Add(new DeletedMessage(Id, userId));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void MarkAsRead(Guid userId)
|
|
||||||
{
|
|
||||||
if (!_readByUsers.Contains(userId))
|
|
||||||
{
|
|
||||||
_readByUsers.Add(userId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public bool IsReadBy(Guid userId) => _readByUsers.Contains(userId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -84,7 +84,7 @@ public sealed class MessageSentDomainEventHandler : INotificationHandler<Message
|
|||||||
size = m.Size
|
size = m.Size
|
||||||
}).ToList() ?? (object)Array.Empty<object>(),
|
}).ToList() ?? (object)Array.Empty<object>(),
|
||||||
sender = senderObj,
|
sender = senderObj,
|
||||||
readBy = message.ReadByUsers.Select(id => new { id }).ToList(),
|
readBy = new List<object>(),
|
||||||
storyId = (message as StoryMessage)?.StoryId,
|
storyId = (message as StoryMessage)?.StoryId,
|
||||||
storyMediaUrl = (message as StoryMessage)?.StoryMediaUrl,
|
storyMediaUrl = (message as StoryMessage)?.StoryMediaUrl,
|
||||||
storyMediaType = (message as StoryMessage)?.StoryMediaType,
|
storyMediaType = (message as StoryMessage)?.StoryMediaType,
|
||||||
|
|||||||
@@ -95,20 +95,6 @@ public sealed class MessageRepository : IMessageRepository
|
|||||||
.ToListAsync(cancellationToken);
|
.ToListAsync(cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<List<Message>> GetChatMessagesAfterAsync(Guid chatId, long sequenceId, int limit, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var builder = Builders<Message>.Filter;
|
|
||||||
var filter = builder.And(
|
|
||||||
builder.Eq(m => m.ChatId, chatId),
|
|
||||||
builder.Gt(m => m.SequenceId, sequenceId)
|
|
||||||
);
|
|
||||||
|
|
||||||
return await _messages.Find(filter)
|
|
||||||
.SortBy(m => m.SequenceId)
|
|
||||||
.Limit(limit)
|
|
||||||
.ToListAsync(cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<List<Message>> GetChatMessagesAroundAsync(Guid chatId, long sequenceId, int limit, CancellationToken cancellationToken)
|
public async Task<List<Message>> GetChatMessagesAroundAsync(Guid chatId, long sequenceId, int limit, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var builder = Builders<Message>.Filter;
|
var builder = Builders<Message>.Filter;
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,2 @@
|
|||||||
|
#Tue Apr 14 00:27:15 MSK 2026
|
||||||
|
gradle.version=8.5
|
||||||
Binary file not shown.
@@ -0,0 +1,2 @@
|
|||||||
|
#Tue Apr 14 00:13:58 MSK 2026
|
||||||
|
java.home=C\:\\Program Files\\Android\\Android Studio\\jbr
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
plugins {
|
||||||
|
id("com.android.application")
|
||||||
|
id("org.jetbrains.kotlin.android")
|
||||||
|
id("com.google.dagger.hilt.android")
|
||||||
|
id("com.google.gms.google-services")
|
||||||
|
kotlin("kapt")
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "ru.knot.messager"
|
||||||
|
compileSdk = 34
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
applicationId = "ru.knot.messager"
|
||||||
|
minSdk = 26
|
||||||
|
targetSdk = 34
|
||||||
|
versionCode = 1
|
||||||
|
versionName = "1.0.0"
|
||||||
|
|
||||||
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
|
vectorDrawables {
|
||||||
|
useSupportLibrary = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buildTypes {
|
||||||
|
release {
|
||||||
|
isMinifyEnabled = false
|
||||||
|
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Подключаем все наши папки с кодом как sourceSets
|
||||||
|
sourceSets {
|
||||||
|
getByName("main") {
|
||||||
|
java.srcDirs(
|
||||||
|
"src/main/kotlin",
|
||||||
|
"../auth",
|
||||||
|
"../chats",
|
||||||
|
"../core",
|
||||||
|
"../calls",
|
||||||
|
"../stories",
|
||||||
|
"../contacts",
|
||||||
|
"../profiles",
|
||||||
|
"../settings",
|
||||||
|
"../navigation"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
kotlinOptions {
|
||||||
|
jvmTarget = "17"
|
||||||
|
}
|
||||||
|
buildFeatures {
|
||||||
|
compose = true
|
||||||
|
}
|
||||||
|
composeOptions {
|
||||||
|
kotlinCompilerExtensionVersion = "1.5.8"
|
||||||
|
}
|
||||||
|
packaging {
|
||||||
|
resources {
|
||||||
|
excludes += "/META-INF/{AL2.0,LGPL2.1}"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
// AndroidX & UI
|
||||||
|
implementation("androidx.core:core-ktx:1.12.0")
|
||||||
|
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.2")
|
||||||
|
implementation("androidx.activity:activity-compose:1.8.1")
|
||||||
|
implementation(platform("androidx.compose:compose-bom:2023.10.01"))
|
||||||
|
implementation("androidx.compose.ui:ui")
|
||||||
|
implementation("androidx.compose.ui:ui-graphics")
|
||||||
|
implementation("androidx.compose.ui:ui-tooling-preview")
|
||||||
|
implementation("androidx.compose.material3:material3")
|
||||||
|
implementation("com.google.android.material:material:1.11.0")
|
||||||
|
implementation("androidx.navigation:navigation-compose:2.7.5")
|
||||||
|
implementation("androidx.compose.material:material-icons-extended")
|
||||||
|
|
||||||
|
// Hilt
|
||||||
|
implementation("com.google.dagger:hilt-android:2.48")
|
||||||
|
kapt("com.google.dagger:hilt-android-compiler:2.48")
|
||||||
|
implementation("androidx.hilt:hilt-navigation-compose:1.1.0")
|
||||||
|
|
||||||
|
// Network & SignalR
|
||||||
|
implementation("com.squareup.retrofit2:retrofit:2.9.0")
|
||||||
|
implementation("com.squareup.retrofit2:converter-gson:2.9.0")
|
||||||
|
implementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
|
||||||
|
implementation("com.microsoft.signalr:signalr:7.0.0")
|
||||||
|
|
||||||
|
// WebRTC
|
||||||
|
implementation("com.github.webrtc-sdk:android:104.5112.01")
|
||||||
|
|
||||||
|
// Media3 (ExoPlayer)
|
||||||
|
implementation("androidx.media3:media3-exoplayer:1.2.0")
|
||||||
|
implementation("androidx.media3:media3-ui:1.2.0")
|
||||||
|
implementation("androidx.media3:media3-common:1.2.0")
|
||||||
|
|
||||||
|
// Images & GIF
|
||||||
|
implementation("io.coil-kt:coil-compose:2.5.0")
|
||||||
|
implementation("io.coil-kt:coil-gif:2.5.0")
|
||||||
|
implementation("io.coil-kt:coil-svg:2.5.0")
|
||||||
|
|
||||||
|
// Security
|
||||||
|
implementation("androidx.security:security-crypto:1.1.0-alpha06")
|
||||||
|
|
||||||
|
// UCrop (Image Cropping)
|
||||||
|
implementation("com.github.yalantis:ucrop:2.2.8")
|
||||||
|
|
||||||
|
// Firebase (Push Notifications)
|
||||||
|
implementation(platform("com.google.firebase:firebase-bom:32.7.0"))
|
||||||
|
implementation("com.google.firebase:firebase-messaging-ktx")
|
||||||
|
implementation("com.google.firebase:firebase-analytics-ktx")
|
||||||
|
|
||||||
|
// Room
|
||||||
|
val room_version = "2.6.1"
|
||||||
|
implementation("androidx.room:room-runtime:$room_version")
|
||||||
|
implementation("androidx.room:room-ktx:$room_version")
|
||||||
|
kapt("androidx.room:room-compiler:$room_version")
|
||||||
|
|
||||||
|
// Testing
|
||||||
|
testImplementation("junit:junit:4.13.2")
|
||||||
|
androidTestImplementation("androidx.test.ext:junit:1.1.5")
|
||||||
|
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"project_info": {
|
||||||
|
"project_number": "483917912506",
|
||||||
|
"project_id": "knot-bad1a",
|
||||||
|
"storage_bucket": "knot-bad1a.firebasestorage.app"
|
||||||
|
},
|
||||||
|
"client": [
|
||||||
|
{
|
||||||
|
"client_info": {
|
||||||
|
"mobilesdk_app_id": "1:483917912506:android:cd39213364869ef9e82583",
|
||||||
|
"android_client_info": {
|
||||||
|
"package_name": "ru.knot.messager"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"oauth_client": [],
|
||||||
|
"api_key": [
|
||||||
|
{
|
||||||
|
"current_key": "AIzaSyBAL_bZJYaa7rGERLX63LeFXz-__JXRWQY"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"services": {
|
||||||
|
"appinvite_service": {
|
||||||
|
"other_platform_oauth_client": []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"configuration_version": "1"
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||||
|
package="ru.knot.messager">
|
||||||
|
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.CAMERA" />
|
||||||
|
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||||
|
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
|
||||||
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
|
|
||||||
|
<application
|
||||||
|
android:name="com.knot.messenger.MainApplication"
|
||||||
|
android:allowBackup="true"
|
||||||
|
android:label="@string/app_name"
|
||||||
|
android:supportsRtl="true"
|
||||||
|
android:theme="@style/Theme.KnotMessenger">
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name="com.knot.messenger.MainActivity"
|
||||||
|
android:exported="true"
|
||||||
|
android:theme="@style/Theme.KnotMessenger">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
|
||||||
|
<service
|
||||||
|
android:name="core.notifications.data.ForkFirebaseMessagingService"
|
||||||
|
android:exported="false">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="com.google.firebase.MESSAGING_EVENT" />
|
||||||
|
</intent-filter>
|
||||||
|
</service>
|
||||||
|
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package com.knot.messenger
|
||||||
|
|
||||||
|
import android.os.Bundle
|
||||||
|
import androidx.activity.ComponentActivity
|
||||||
|
import androidx.activity.compose.setContent
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Surface
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
import navigation.AppNavigation
|
||||||
|
import core.presentation.theme.ForkMessengerTheme
|
||||||
|
|
||||||
|
@AndroidEntryPoint
|
||||||
|
class MainActivity : ComponentActivity() {
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
|
||||||
|
// Request notifications permission for Android 13+
|
||||||
|
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU) {
|
||||||
|
androidx.core.app.ActivityCompat.requestPermissions(
|
||||||
|
this,
|
||||||
|
arrayOf(android.Manifest.permission.POST_NOTIFICATIONS),
|
||||||
|
101
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
setContent {
|
||||||
|
ForkMessengerTheme {
|
||||||
|
Surface(
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
color = MaterialTheme.colorScheme.background
|
||||||
|
) {
|
||||||
|
AppNavigation()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.knot.messenger
|
||||||
|
|
||||||
|
import android.app.Application
|
||||||
|
import dagger.hilt.android.HiltAndroidApp
|
||||||
|
|
||||||
|
@HiltAndroidApp
|
||||||
|
class MainApplication : Application()
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
<resources>
|
||||||
|
<string name="app_name">ForkMessenger</string>
|
||||||
|
<string name="login">Login</string>
|
||||||
|
<string name="register">Register</string>
|
||||||
|
<string name="username">Username</string>
|
||||||
|
<string name="password">Password</string>
|
||||||
|
<string name="display_name">Display Name</string>
|
||||||
|
<string name="settings">Settings</string>
|
||||||
|
<string name="save">Save</string>
|
||||||
|
<string name="back">Back</string>
|
||||||
|
<string name="server_connection">Server Connection</string>
|
||||||
|
<string name="api_base_url">API Base URL</string>
|
||||||
|
<string name="server_features">Server Features</string>
|
||||||
|
<string name="stories">Stories</string>
|
||||||
|
<string name="polls">Polls</string>
|
||||||
|
<string name="calls">Calls</string>
|
||||||
|
<string name="groups">Groups</string>
|
||||||
|
<string name="enabled">Enabled</string>
|
||||||
|
<string name="disabled">Disabled</string>
|
||||||
|
<string name="limits">Limits</string>
|
||||||
|
<string name="max_file_size">Max File Size</string>
|
||||||
|
<string name="max_group_members">Max Group Members</string>
|
||||||
|
<string name="message">Message</string>
|
||||||
|
<string name="call">Call</string>
|
||||||
|
<string name="block">Block</string>
|
||||||
|
<string name="profile">Profile</string>
|
||||||
|
<string name="confirm_password">Confirm Password</string>
|
||||||
|
<string name="passwords_not_match">Passwords do not match</string>
|
||||||
|
<string name="no_account_register">Don\'t have an account? Register</string>
|
||||||
|
<string name="already_have_account">Already have an account? Login</string>
|
||||||
|
<string name="error_occurred">An error occurred</string>
|
||||||
|
<string name="loading">Loading...</string>
|
||||||
|
<string name="chats_title">Chats</string>
|
||||||
|
<string name="contacts_title">Contacts</string>
|
||||||
|
<string name="stories_title">Stories</string>
|
||||||
|
<string name="create_story">Create Story</string>
|
||||||
|
<string name="send_message_hint">Type a message...</string>
|
||||||
|
<string name="reply_to_user">Reply to %1$s...</string>
|
||||||
|
<string name="story_editor">STORY EDITOR</string>
|
||||||
|
<string name="publish">PUBLISH</string>
|
||||||
|
<string name="start_creation">START CREATION</string>
|
||||||
|
<string name="text_tool">TEXT</string>
|
||||||
|
<string name="crop_tool">CROP</string>
|
||||||
|
<string name="stickers_tool">STICKERS</string>
|
||||||
|
<string name="brush_tool">BRUSH</string>
|
||||||
|
<string name="filters_tool">FILTERS</string>
|
||||||
|
<string name="remove">Remove</string>
|
||||||
|
<string name="no_chats_found">No chats found</string>
|
||||||
|
<string name="typing">typing...</string>
|
||||||
|
<string name="video_call">Video Call</string>
|
||||||
|
<string name="emoji">Emoji</string>
|
||||||
|
<string name="attach">Attach</string>
|
||||||
|
<string name="message_placeholder">Message...</string>
|
||||||
|
<string name="voice_message">Voice Message</string>
|
||||||
|
<string name="send">Send</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
<resources>
|
||||||
|
<string name="app_name">ForkMessenger</string>
|
||||||
|
<string name="login">Войти</string>
|
||||||
|
<string name="register">Регистрация</string>
|
||||||
|
<string name="username">Имя пользователя</string>
|
||||||
|
<string name="password">Пароль</string>
|
||||||
|
<string name="display_name">Отображаемое имя</string>
|
||||||
|
<string name="settings">Настройки</string>
|
||||||
|
<string name="save">Сохранить</string>
|
||||||
|
<string name="back">Назад</string>
|
||||||
|
<string name="server_connection">Подключение к серверу</string>
|
||||||
|
<string name="api_base_url">API Base URL</string>
|
||||||
|
<string name="server_features">Функции сервера</string>
|
||||||
|
<string name="stories">Истории</string>
|
||||||
|
<string name="polls">Опросы</string>
|
||||||
|
<string name="calls">Звонки</string>
|
||||||
|
<string name="groups">Группы</string>
|
||||||
|
<string name="enabled">Включено</string>
|
||||||
|
<string name="disabled">Отключено</string>
|
||||||
|
<string name="limits">Лимиты</string>
|
||||||
|
<string name="max_file_size">Макс. размер файла</string>
|
||||||
|
<string name="max_group_members">Макс. участников в группе</string>
|
||||||
|
<string name="message">Сообщение</string>
|
||||||
|
<string name="call">Позвонить</string>
|
||||||
|
<string name="block">Заблокировать</string>
|
||||||
|
<string name="profile">Профиль</string>
|
||||||
|
<string name="confirm_password">Подтвердите пароль</string>
|
||||||
|
<string name="passwords_not_match">Пароли не совпадают</string>
|
||||||
|
<string name="no_account_register">Нет аккаунта? Зарегистрироваться</string>
|
||||||
|
<string name="already_have_account">Уже есть аккаунт? Войти</string>
|
||||||
|
<string name="error_occurred">Произошла ошибка</string>
|
||||||
|
<string name="loading">Загрузка...</string>
|
||||||
|
<string name="chats_title">Чаты</string>
|
||||||
|
<string name="contacts_title">Контакты</string>
|
||||||
|
<string name="stories_title">Истории</string>
|
||||||
|
<string name="create_story">Создать историю</string>
|
||||||
|
<string name="send_message_hint">Напишите сообщение...</string>
|
||||||
|
<string name="reply_to_user">Ответить %1$s...</string>
|
||||||
|
<string name="story_editor">РЕДАКТОР ИСТОРИЙ</string>
|
||||||
|
<string name="publish">ОПУБЛИКОВАТЬ</string>
|
||||||
|
<string name="start_creation">НАЧАТЬ СОЗДАНИЕ</string>
|
||||||
|
<string name="text_tool">ТЕКСТ</string>
|
||||||
|
<string name="crop_tool">ОБРЕЗКА</string>
|
||||||
|
<string name="stickers_tool">СТИКЕРЫ</string>
|
||||||
|
<string name="brush_tool">КИСТЬ</string>
|
||||||
|
<string name="filters_tool">ФИЛЬТРЫ</string>
|
||||||
|
<string name="remove">Удалить</string>
|
||||||
|
<string name="no_chats_found">Чаты не найдены</string>
|
||||||
|
<string name="typing">печатает...</string>
|
||||||
|
<string name="video_call">Видеозвонок</string>
|
||||||
|
<string name="emoji">Эмодзи</string>
|
||||||
|
<string name="attach">Прикрепить</string>
|
||||||
|
<string name="message_placeholder">Сообщение...</string>
|
||||||
|
<string name="voice_message">Голосовое сообщение</string>
|
||||||
|
<string name="send">Отправить</string>
|
||||||
|
<string name="search_hint">Поиск...</string>
|
||||||
|
<string name="online">В сети</string>
|
||||||
|
<string name="last_seen">Был(а): %1$s</string>
|
||||||
|
<string name="last_seen_recently">недавно</string>
|
||||||
|
<string name="all">Все</string>
|
||||||
|
<string name="online_tab">Онлайн</string>
|
||||||
|
<string name="blocked">Заблокированные</string>
|
||||||
|
<string name="media">Медиа</string>
|
||||||
|
<string name="notifications">Уведомления</string>
|
||||||
|
<string name="mute">Без звука</string>
|
||||||
|
<string name="unmute">Включить звук</string>
|
||||||
|
<string name="log_out">Выйти из аккаунта</string>
|
||||||
|
<string name="bio">О себе</string>
|
||||||
|
<string name="edit_profile">Редактировать профиль</string>
|
||||||
|
<string name="username_label">Имя пользователя</string>
|
||||||
|
<string name="change_photo">Изменить фото</string>
|
||||||
|
<string name="cancel">Отмена</string>
|
||||||
|
<string name="crop">Обрезать</string>
|
||||||
|
<string name="chats">Чаты</string>
|
||||||
|
<string name="contacts_tab">Контакты</string>
|
||||||
|
<string name="profile_tab">Профиль</string>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<style name="Theme.KnotMessenger" parent="Theme.Material3.DayNight.NoActionBar">
|
||||||
|
<item name="android:statusBarColor">#0F0F10</item>
|
||||||
|
<item name="android:windowBackground">#0F0F10</item>
|
||||||
|
</style>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package auth.data.remote.api
|
||||||
|
|
||||||
|
import auth.data.remote.dto.AuthRequest
|
||||||
|
import auth.data.remote.dto.AuthResponse
|
||||||
|
import core.domain.model.ServerConfigModel
|
||||||
|
import retrofit2.http.Body
|
||||||
|
import retrofit2.http.GET
|
||||||
|
import retrofit2.http.Headers
|
||||||
|
import retrofit2.http.POST
|
||||||
|
|
||||||
|
interface AuthApi {
|
||||||
|
@POST("auth/login")
|
||||||
|
@Headers("Cache-Control: no-cache")
|
||||||
|
suspend fun login(@Body request: AuthRequest): AuthResponse
|
||||||
|
|
||||||
|
@POST("auth/register")
|
||||||
|
@Headers("Cache-Control: no-cache")
|
||||||
|
suspend fun register(@Body request: AuthRequest): AuthResponse
|
||||||
|
|
||||||
|
@GET("config")
|
||||||
|
@Headers("Cache-Control: no-cache")
|
||||||
|
suspend fun getConfig(): ServerConfigModel
|
||||||
|
|
||||||
|
@POST("auth/push-token")
|
||||||
|
@Headers("Cache-Control: no-cache")
|
||||||
|
suspend fun updatePushToken(@Body token: String): Unit
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package auth.data.remote.dto
|
||||||
|
|
||||||
|
import com.google.gson.annotations.SerializedName
|
||||||
|
|
||||||
|
data class AuthRequest(
|
||||||
|
@SerializedName("userName") val userName: String,
|
||||||
|
@SerializedName("password") val password: String
|
||||||
|
)
|
||||||
|
|
||||||
|
data class AuthResponse(
|
||||||
|
@SerializedName("accessToken") val accessToken: String?,
|
||||||
|
@SerializedName("user") val user: UserDto?,
|
||||||
|
@SerializedName("userId") val userId: String?,
|
||||||
|
@SerializedName("username") val username: String?,
|
||||||
|
@SerializedName("displayName") val displayName: String?
|
||||||
|
)
|
||||||
|
|
||||||
|
data class UserDto(
|
||||||
|
@SerializedName("id") val id: String,
|
||||||
|
@SerializedName("userName") val userName: String,
|
||||||
|
@SerializedName("displayName") val displayName: String?,
|
||||||
|
@SerializedName("avatarUrl") val avatarUrl: String?
|
||||||
|
)
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package auth.data.repository
|
||||||
|
|
||||||
|
import auth.data.remote.api.AuthApi
|
||||||
|
import auth.data.remote.dto.AuthRequest
|
||||||
|
import auth.domain.model.AuthResult
|
||||||
|
import auth.domain.repository.AuthRepository
|
||||||
|
import core.network.ServerConfig
|
||||||
|
import core.security.TokenManager
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
class AuthRepositoryImpl @Inject constructor(
|
||||||
|
private val api: AuthApi,
|
||||||
|
private val tokenManager: TokenManager,
|
||||||
|
private val serverConfig: ServerConfig
|
||||||
|
) : AuthRepository {
|
||||||
|
|
||||||
|
override suspend fun login(userName: String, password: String): Result<AuthResult> {
|
||||||
|
return try {
|
||||||
|
val response = api.login(AuthRequest(userName, password))
|
||||||
|
val token = response.accessToken ?: return Result.failure(Exception("Token is null"))
|
||||||
|
val userId = response.userId ?: ""
|
||||||
|
|
||||||
|
tokenManager.saveToken(token, userId)
|
||||||
|
fetchConfig()
|
||||||
|
Result.success(
|
||||||
|
AuthResult(
|
||||||
|
token = token,
|
||||||
|
userId = userId,
|
||||||
|
userName = response.username ?: userName,
|
||||||
|
displayName = response.displayName ?: response.username ?: userName,
|
||||||
|
avatarUrl = null
|
||||||
|
)
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Result.failure(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun register(userName: String, password: String): Result<AuthResult> {
|
||||||
|
return try {
|
||||||
|
val response = api.register(AuthRequest(userName, password))
|
||||||
|
val token = response.accessToken ?: return Result.failure(Exception("Token is null"))
|
||||||
|
val userId = response.userId ?: ""
|
||||||
|
|
||||||
|
tokenManager.saveToken(token, userId)
|
||||||
|
fetchConfig()
|
||||||
|
Result.success(
|
||||||
|
AuthResult(
|
||||||
|
token = token,
|
||||||
|
userId = userId,
|
||||||
|
userName = response.username ?: userName,
|
||||||
|
displayName = response.displayName ?: response.username ?: userName,
|
||||||
|
avatarUrl = null
|
||||||
|
)
|
||||||
|
)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Result.failure(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun logout() {
|
||||||
|
tokenManager.deleteToken()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun isAuthenticated(): Boolean {
|
||||||
|
return tokenManager.getToken() != null
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun fetchConfig(): Result<Unit> {
|
||||||
|
return try {
|
||||||
|
val config = api.getConfig()
|
||||||
|
serverConfig.saveServerConfig(config)
|
||||||
|
Result.success(Unit)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Result.failure(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun updatePushToken(token: String) {
|
||||||
|
try {
|
||||||
|
api.updatePushToken(token)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// Silent fail
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package auth.di
|
||||||
|
|
||||||
|
import auth.data.remote.api.AuthApi
|
||||||
|
import auth.data.repository.AuthRepositoryImpl
|
||||||
|
import auth.domain.repository.AuthRepository
|
||||||
|
import core.network.ServerConfig
|
||||||
|
import core.security.TokenManager
|
||||||
|
import dagger.Module
|
||||||
|
import dagger.Provides
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import retrofit2.Retrofit
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
@Module
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
object AuthModule {
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun provideAuthApi(retrofit: Retrofit): AuthApi {
|
||||||
|
return retrofit.create(AuthApi::class.java)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun provideAuthRepository(
|
||||||
|
api: AuthApi,
|
||||||
|
tokenManager: TokenManager,
|
||||||
|
serverConfig: ServerConfig
|
||||||
|
): AuthRepository {
|
||||||
|
return AuthRepositoryImpl(api, tokenManager, serverConfig)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package auth.domain.model
|
||||||
|
|
||||||
|
data class AuthResult(
|
||||||
|
val token: String,
|
||||||
|
val userId: String,
|
||||||
|
val userName: String,
|
||||||
|
val displayName: String,
|
||||||
|
val avatarUrl: String?
|
||||||
|
)
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package auth.domain.repository
|
||||||
|
|
||||||
|
import auth.domain.model.AuthResult
|
||||||
|
|
||||||
|
interface AuthRepository {
|
||||||
|
suspend fun login(userName: String, password: String): Result<AuthResult>
|
||||||
|
suspend fun register(userName: String, password: String): Result<AuthResult>
|
||||||
|
suspend fun logout()
|
||||||
|
suspend fun fetchConfig(): Result<Unit>
|
||||||
|
fun isAuthenticated(): Boolean
|
||||||
|
suspend fun updatePushToken(token: String)
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package auth.presentation
|
||||||
|
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import auth.domain.repository.AuthRepository
|
||||||
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.asStateFlow
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import com.google.firebase.messaging.FirebaseMessaging
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
data class AuthState(
|
||||||
|
val isLoading: Boolean = false,
|
||||||
|
val error: String? = null,
|
||||||
|
val isAuthenticated: Boolean = false
|
||||||
|
)
|
||||||
|
|
||||||
|
@HiltViewModel
|
||||||
|
class AuthViewModel @Inject constructor(
|
||||||
|
private val repository: AuthRepository
|
||||||
|
) : ViewModel() {
|
||||||
|
|
||||||
|
init {
|
||||||
|
if (repository.isAuthenticated()) {
|
||||||
|
updatePushToken()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private val _state = MutableStateFlow(AuthState(isAuthenticated = repository.isAuthenticated()))
|
||||||
|
val state: StateFlow<AuthState> = _state.asStateFlow()
|
||||||
|
|
||||||
|
fun checkAuth() {
|
||||||
|
_state.update { it.copy(isAuthenticated = repository.isAuthenticated()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun login(userName: String, password: String) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_state.update { it.copy(isLoading = true, error = null) }
|
||||||
|
repository.login(userName, password)
|
||||||
|
.onSuccess {
|
||||||
|
_state.update { it.copy(isLoading = false, isAuthenticated = true) }
|
||||||
|
updatePushToken()
|
||||||
|
}
|
||||||
|
.onFailure { e ->
|
||||||
|
_state.update { it.copy(isLoading = false, error = e.message) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun register(userName: String, password: String) {
|
||||||
|
viewModelScope.launch {
|
||||||
|
_state.update { it.copy(isLoading = true, error = null) }
|
||||||
|
repository.register(userName, password)
|
||||||
|
.onSuccess {
|
||||||
|
_state.update { it.copy(isLoading = false, isAuthenticated = true) }
|
||||||
|
updatePushToken()
|
||||||
|
}
|
||||||
|
.onFailure { e ->
|
||||||
|
_state.update { it.copy(isLoading = false, error = e.message) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updatePushToken() {
|
||||||
|
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
|
||||||
|
if (task.isSuccessful) {
|
||||||
|
val token = task.result
|
||||||
|
viewModelScope.launch {
|
||||||
|
repository.updatePushToken(token)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package auth.presentation
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.Settings
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import ru.knot.messager.R
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun LoginScreen(
|
||||||
|
viewModel: AuthViewModel,
|
||||||
|
onNavigateToRegister: () -> Unit,
|
||||||
|
onNavigateToSettings: () -> Unit,
|
||||||
|
onLoginSuccess: () -> Unit
|
||||||
|
) {
|
||||||
|
val state by viewModel.state.collectAsState()
|
||||||
|
var userName by remember { mutableStateOf("") }
|
||||||
|
var password by remember { mutableStateOf("") }
|
||||||
|
|
||||||
|
LaunchedEffect(state.isAuthenticated) {
|
||||||
|
if (state.isAuthenticated) {
|
||||||
|
onLoginSuccess()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(
|
||||||
|
title = { Text(stringResource(R.string.login)) },
|
||||||
|
actions = {
|
||||||
|
IconButton(onClick = onNavigateToSettings) {
|
||||||
|
Icon(Icons.Default.Settings, contentDescription = stringResource(R.string.settings))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
) { paddingValues ->
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(paddingValues)
|
||||||
|
.padding(16.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.Center
|
||||||
|
) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = userName,
|
||||||
|
onValueChange = { userName = it },
|
||||||
|
label = { Text(stringResource(R.string.username)) },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
OutlinedTextField(
|
||||||
|
value = password,
|
||||||
|
onValueChange = { password = it },
|
||||||
|
label = { Text(stringResource(R.string.password)) },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
visualTransformation = PasswordVisualTransformation(),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
|
if (state.isLoading) {
|
||||||
|
CircularProgressIndicator()
|
||||||
|
} else {
|
||||||
|
Button(
|
||||||
|
onClick = { viewModel.login(userName, password) },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
enabled = userName.isNotBlank() && password.isNotBlank()
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.login))
|
||||||
|
}
|
||||||
|
TextButton(onClick = onNavigateToRegister) {
|
||||||
|
Text(stringResource(R.string.no_account_register))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.error != null) {
|
||||||
|
Text(
|
||||||
|
text = state.error!!,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
modifier = Modifier.padding(top = 8.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package auth.presentation
|
||||||
|
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import ru.knot.messager.R
|
||||||
|
|
||||||
|
@OptIn(ExperimentalMaterial3Api::class)
|
||||||
|
@Composable
|
||||||
|
fun RegisterScreen(
|
||||||
|
viewModel: AuthViewModel,
|
||||||
|
onNavigateToLogin: () -> Unit,
|
||||||
|
onRegisterSuccess: () -> Unit
|
||||||
|
) {
|
||||||
|
val state by viewModel.state.collectAsState()
|
||||||
|
var userName by remember { mutableStateOf("") }
|
||||||
|
var password by remember { mutableStateOf("") }
|
||||||
|
var confirmPassword by remember { mutableStateOf("") }
|
||||||
|
var errorMessage by remember { mutableStateOf<String?>(null) }
|
||||||
|
|
||||||
|
val passwordsNotMatchMsg = stringResource(R.string.passwords_not_match)
|
||||||
|
|
||||||
|
LaunchedEffect(state.isAuthenticated) {
|
||||||
|
if (state.isAuthenticated) {
|
||||||
|
onRegisterSuccess()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Scaffold(
|
||||||
|
topBar = {
|
||||||
|
TopAppBar(title = { Text(stringResource(R.string.register)) })
|
||||||
|
}
|
||||||
|
) { paddingValues ->
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(paddingValues)
|
||||||
|
.padding(16.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally,
|
||||||
|
verticalArrangement = Arrangement.Center
|
||||||
|
) {
|
||||||
|
OutlinedTextField(
|
||||||
|
value = userName,
|
||||||
|
onValueChange = { userName = it },
|
||||||
|
label = { Text(stringResource(R.string.username)) },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
OutlinedTextField(
|
||||||
|
value = password,
|
||||||
|
onValueChange = { password = it },
|
||||||
|
label = { Text(stringResource(R.string.password)) },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
visualTransformation = PasswordVisualTransformation(),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.height(8.dp))
|
||||||
|
OutlinedTextField(
|
||||||
|
value = confirmPassword,
|
||||||
|
onValueChange = { confirmPassword = it },
|
||||||
|
label = { Text(stringResource(R.string.confirm_password)) },
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
visualTransformation = PasswordVisualTransformation(),
|
||||||
|
singleLine = true
|
||||||
|
)
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
|
if (state.isLoading) {
|
||||||
|
CircularProgressIndicator()
|
||||||
|
} else {
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
if (password == confirmPassword) {
|
||||||
|
errorMessage = null
|
||||||
|
viewModel.register(userName, password)
|
||||||
|
} else {
|
||||||
|
errorMessage = passwordsNotMatchMsg
|
||||||
|
}
|
||||||
|
},
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
|
enabled = userName.isNotBlank() && password.isNotBlank() && confirmPassword.isNotBlank()
|
||||||
|
) {
|
||||||
|
Text(stringResource(R.string.register))
|
||||||
|
}
|
||||||
|
TextButton(onClick = onNavigateToLogin) {
|
||||||
|
Text(stringResource(R.string.already_have_account))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val displayError = state.error ?: errorMessage
|
||||||
|
if (displayError != null) {
|
||||||
|
Text(
|
||||||
|
text = displayError,
|
||||||
|
color = MaterialTheme.colorScheme.error,
|
||||||
|
modifier = Modifier.padding(top = 8.dp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
// Top-level build file
|
||||||
|
plugins {
|
||||||
|
id("com.android.application") version "8.2.0" apply false
|
||||||
|
id("com.android.library") version "8.2.0" apply false
|
||||||
|
id("org.jetbrains.kotlin.android") version "1.9.22" apply false
|
||||||
|
id("com.google.dagger.hilt.android") version "2.48" apply false
|
||||||
|
id("com.google.gms.google-services") version "4.4.0" apply false
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package calls.data.remote
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.media.AudioAttributes
|
||||||
|
import android.media.AudioFocusRequest
|
||||||
|
import android.media.AudioManager
|
||||||
|
import android.os.Build
|
||||||
|
|
||||||
|
class CallAudioManager(private val context: Context) {
|
||||||
|
private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
|
||||||
|
private var originalMode: Int = AudioManager.MODE_NORMAL
|
||||||
|
private var originalIsSpeakerphoneOn: Boolean = false
|
||||||
|
|
||||||
|
fun startCallMode(isVideoCall: Boolean) {
|
||||||
|
originalMode = audioManager.mode
|
||||||
|
originalIsSpeakerphoneOn = audioManager.isSpeakerphoneOn
|
||||||
|
|
||||||
|
audioManager.mode = AudioManager.MODE_IN_COMMUNICATION
|
||||||
|
setSpeakerphoneOn(isVideoCall)
|
||||||
|
|
||||||
|
// Запрашиваем фокус аудио
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||||
|
val playbackAttributes = AudioAttributes.Builder()
|
||||||
|
.setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
|
||||||
|
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
|
||||||
|
.build()
|
||||||
|
val focusRequest = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
|
||||||
|
.setAudioAttributes(playbackAttributes)
|
||||||
|
.build()
|
||||||
|
audioManager.requestAudioFocus(focusRequest)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setSpeakerphoneOn(on: Boolean) {
|
||||||
|
audioManager.isSpeakerphoneOn = on
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stopCallMode() {
|
||||||
|
audioManager.mode = originalMode
|
||||||
|
audioManager.isSpeakerphoneOn = originalIsSpeakerphoneOn
|
||||||
|
audioManager.abandonAudioFocus(null)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package calls.data.remote
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import org.webrtc.*
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
class GroupWebRtcManager @Inject constructor(private val context: Context) {
|
||||||
|
private val peerConnections = ConcurrentHashMap<String, PeerConnection>()
|
||||||
|
private val factory: PeerConnectionFactory by lazy { createFactory() }
|
||||||
|
|
||||||
|
private fun createFactory(): PeerConnectionFactory {
|
||||||
|
PeerConnectionFactory.initialize(
|
||||||
|
PeerConnectionFactory.InitializationOptions.builder(context).createInitializationOptions()
|
||||||
|
)
|
||||||
|
return PeerConnectionFactory.builder()
|
||||||
|
.setVideoEncoderFactory(DefaultVideoEncoderFactory(EglBase.create().eglBaseContext, true, true))
|
||||||
|
.setVideoDecoderFactory(DefaultVideoDecoderFactory(EglBase.create().eglBaseContext))
|
||||||
|
.createPeerConnectionFactory()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addParticipant(userId: String, observer: PeerConnection.Observer): PeerConnection? {
|
||||||
|
val iceServers = listOf(
|
||||||
|
PeerConnection.IceServer.builder("stun:stun.l.google.com:19302").createIceServer()
|
||||||
|
)
|
||||||
|
val pc = factory.createPeerConnection(iceServers, observer)
|
||||||
|
if (pc != null) {
|
||||||
|
peerConnections[userId] = pc
|
||||||
|
}
|
||||||
|
return pc
|
||||||
|
}
|
||||||
|
|
||||||
|
fun removeParticipant(userId: String) {
|
||||||
|
peerConnections[userId]?.dispose()
|
||||||
|
peerConnections.remove(userId)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getPeerConnection(userId: String): PeerConnection? = peerConnections[userId]
|
||||||
|
|
||||||
|
fun closeAll() {
|
||||||
|
peerConnections.values.forEach { it.dispose() }
|
||||||
|
peerConnections.clear()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package calls.data.remote
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import org.webrtc.*
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
class WebRtcManager @Inject constructor(private val context: Context) {
|
||||||
|
private var peerConnection: PeerConnection? = null
|
||||||
|
private val factory: PeerConnectionFactory by lazy { createFactory() }
|
||||||
|
|
||||||
|
// Аудио и видео источники
|
||||||
|
private val videoSource by lazy { factory.createVideoSource(false) }
|
||||||
|
private val audioSource by lazy { factory.createAudioSource(MediaConstraints()) }
|
||||||
|
|
||||||
|
private fun createFactory(): PeerConnectionFactory {
|
||||||
|
PeerConnectionFactory.initialize(
|
||||||
|
PeerConnectionFactory.InitializationOptions.builder(context).createInitializationOptions()
|
||||||
|
)
|
||||||
|
return PeerConnectionFactory.builder()
|
||||||
|
.setVideoEncoderFactory(DefaultVideoEncoderFactory(EglBase.create().eglBaseContext, true, true))
|
||||||
|
.setVideoDecoderFactory(DefaultVideoDecoderFactory(EglBase.create().eglBaseContext))
|
||||||
|
.createPeerConnectionFactory()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun initializePeerConnection(observer: PeerConnection.Observer) {
|
||||||
|
val iceServers = listOf(
|
||||||
|
PeerConnection.IceServer.builder("stun:stun.l.google.com:19302").createIceServer()
|
||||||
|
)
|
||||||
|
peerConnection = factory.createPeerConnection(iceServers, observer)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun createOffer(observer: SdpObserver) {
|
||||||
|
peerConnection?.createOffer(observer, MediaConstraints())
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setRemoteDescription(sdp: String, type: SessionDescription.Type, observer: SdpObserver) {
|
||||||
|
peerConnection?.setRemoteDescription(observer, SessionDescription(type, sdp))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addIceCandidate(candidate: IceCandidate) {
|
||||||
|
peerConnection?.addIceCandidate(candidate)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun close() {
|
||||||
|
peerConnection?.dispose()
|
||||||
|
peerConnection = null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
package calls.presentation
|
||||||
|
|
||||||
|
import androidx.compose.animation.*
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.material.icons.Icons
|
||||||
|
import androidx.compose.material.icons.filled.*
|
||||||
|
import androidx.compose.material3.*
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.graphics.Brush
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.layout.ContentScale
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import coil.compose.AsyncImage
|
||||||
|
import core.presentation.components.AppAvatar
|
||||||
|
import ru.knot.messager.R
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun CallScreen(
|
||||||
|
viewModel: CallViewModel,
|
||||||
|
onBack: () -> Unit
|
||||||
|
) {
|
||||||
|
val state by viewModel.state.collectAsState()
|
||||||
|
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.background(
|
||||||
|
Brush.verticalGradient(
|
||||||
|
colors = listOf(
|
||||||
|
Color(0xFF0F0F10),
|
||||||
|
Color(0xFF161618),
|
||||||
|
Color(0xFF6366F1).copy(alpha = 0.2f)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
// Контент звонка (Аватар или Видео)
|
||||||
|
Column(
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxSize()
|
||||||
|
.padding(top = 100.dp),
|
||||||
|
horizontalAlignment = Alignment.CenterHorizontally
|
||||||
|
) {
|
||||||
|
AppAvatar(
|
||||||
|
url = state.callerAvatar,
|
||||||
|
name = state.callerName,
|
||||||
|
size = 140.dp
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(24.dp))
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = state.callerName,
|
||||||
|
style = MaterialTheme.typography.headlineMedium,
|
||||||
|
color = Color.White,
|
||||||
|
fontWeight = FontWeight.Bold
|
||||||
|
)
|
||||||
|
|
||||||
|
Text(
|
||||||
|
text = when (state.status) {
|
||||||
|
CallStatus.INCOMING -> "Входящий звонок..."
|
||||||
|
CallStatus.OUTGOING -> "Вызов..."
|
||||||
|
CallStatus.CONNECTED -> "00:00" // TODO: Timer
|
||||||
|
CallStatus.ENDED -> "Звонок завершен"
|
||||||
|
else -> ""
|
||||||
|
},
|
||||||
|
style = MaterialTheme.typography.bodyLarge,
|
||||||
|
color = Color.White.copy(alpha = 0.7f)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Кнопки управления (Внизу)
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.align(Alignment.BottomCenter)
|
||||||
|
.padding(bottom = 60.dp)
|
||||||
|
.fillMaxWidth(),
|
||||||
|
contentAlignment = Alignment.Center
|
||||||
|
) {
|
||||||
|
Row(
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(32.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
if (state.status == CallStatus.INCOMING) {
|
||||||
|
// Кнопка отклонить
|
||||||
|
CallActionButton(
|
||||||
|
icon = Icons.Default.CallEnd,
|
||||||
|
backgroundColor = Color.Red,
|
||||||
|
onClick = { viewModel.endCall(); onBack() }
|
||||||
|
)
|
||||||
|
// Кнопка принять
|
||||||
|
CallActionButton(
|
||||||
|
icon = Icons.Default.Call,
|
||||||
|
backgroundColor = Color(0xFF10B981), // Green
|
||||||
|
onClick = { viewModel.acceptCall() }
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// Стандартные кнопки во время разговора
|
||||||
|
IconButton(
|
||||||
|
onClick = { /* viewModel.toggleMic() */ },
|
||||||
|
modifier = Modifier.size(56.dp).clip(CircleShape).background(Color.White.copy(alpha = 0.1f))
|
||||||
|
) {
|
||||||
|
Icon(Icons.Default.Mic, contentDescription = null, tint = Color.White)
|
||||||
|
}
|
||||||
|
|
||||||
|
CallActionButton(
|
||||||
|
icon = Icons.Default.CallEnd,
|
||||||
|
backgroundColor = Color.Red,
|
||||||
|
onClick = { viewModel.endCall(); onBack() }
|
||||||
|
)
|
||||||
|
|
||||||
|
IconButton(
|
||||||
|
onClick = { /* viewModel.toggleSpeaker() */ },
|
||||||
|
modifier = Modifier.size(56.dp).clip(CircleShape).background(Color.White.copy(alpha = 0.1f))
|
||||||
|
) {
|
||||||
|
Icon(Icons.Default.VolumeUp, contentDescription = null, tint = Color.White)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun CallActionButton(
|
||||||
|
icon: androidx.compose.ui.graphics.vector.ImageVector,
|
||||||
|
backgroundColor: Color,
|
||||||
|
onClick: () -> Unit
|
||||||
|
) {
|
||||||
|
FloatingActionButton(
|
||||||
|
onClick = onClick,
|
||||||
|
containerColor = backgroundColor,
|
||||||
|
contentColor = Color.White,
|
||||||
|
shape = CircleShape,
|
||||||
|
modifier = Modifier.size(64.dp)
|
||||||
|
) {
|
||||||
|
Icon(icon, contentDescription = null, modifier = Modifier.size(32.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package calls.presentation
|
||||||
|
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import calls.data.remote.WebRtcManager
|
||||||
|
import chats.data.remote.signalr.ChatEvent
|
||||||
|
import chats.data.remote.signalr.ChatHubClient
|
||||||
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
|
import kotlinx.coroutines.flow.*
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import org.webrtc.*
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
enum class CallStatus { IDLE, INCOMING, OUTGOING, CONNECTED, ENDED }
|
||||||
|
|
||||||
|
data class CallState(
|
||||||
|
val status: CallStatus = CallStatus.IDLE,
|
||||||
|
val chatId: String? = null,
|
||||||
|
val callerName: String = "",
|
||||||
|
val callerAvatar: String? = null,
|
||||||
|
val isMuted: Boolean = false,
|
||||||
|
val isSpeakerOn: Boolean = false,
|
||||||
|
val localVideoTrack: VideoTrack? = null,
|
||||||
|
val remoteVideoTrack: VideoTrack? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
@HiltViewModel
|
||||||
|
class CallViewModel @Inject constructor(
|
||||||
|
private val webRtcManager: WebRtcManager,
|
||||||
|
private val signalrClient: ChatHubClient
|
||||||
|
) : ViewModel() {
|
||||||
|
|
||||||
|
private val _state = MutableStateFlow(CallState())
|
||||||
|
val state: StateFlow<CallState> = _state.asStateFlow()
|
||||||
|
|
||||||
|
init {
|
||||||
|
observeSignaling()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun observeSignaling() {
|
||||||
|
signalrClient.events
|
||||||
|
.onEach { event ->
|
||||||
|
when (event) {
|
||||||
|
is ChatEvent.CallIncoming -> onIncomingCall(event)
|
||||||
|
is ChatEvent.CallAnswered -> onCallAnswered(event)
|
||||||
|
is ChatEvent.IceCandidateReceived -> onIceCandidate(event)
|
||||||
|
is ChatEvent.CallEnded -> onCallEnded()
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.launchIn(viewModelScope)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onIncomingCall(event: ChatEvent.CallIncoming) {
|
||||||
|
_state.update { it.copy(
|
||||||
|
status = CallStatus.INCOMING,
|
||||||
|
chatId = event.chatId,
|
||||||
|
callerName = "User ${event.from}" // TODO: Load actual user info
|
||||||
|
) }
|
||||||
|
// Set remote description from offer
|
||||||
|
webRtcManager.setRemoteDescription(event.offer, SessionDescription.Type.OFFER, object : SdpObserver {
|
||||||
|
override fun onCreateSuccess(p0: SessionDescription?) {}
|
||||||
|
override fun onSetSuccess() {}
|
||||||
|
override fun onCreateFailure(p0: String?) {}
|
||||||
|
override fun onSetFailure(p0: String?) {}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onCallAnswered(event: ChatEvent.CallAnswered) {
|
||||||
|
_state.update { it.copy(status = CallStatus.CONNECTED) }
|
||||||
|
webRtcManager.setRemoteDescription(event.answer, SessionDescription.Type.ANSWER, object : SdpObserver {
|
||||||
|
override fun onCreateSuccess(p0: SessionDescription?) {}
|
||||||
|
override fun onSetSuccess() {}
|
||||||
|
override fun onCreateFailure(p0: String?) {}
|
||||||
|
override fun onSetFailure(p0: String?) {}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onIceCandidate(event: ChatEvent.IceCandidateReceived) {
|
||||||
|
// Parse candidate JSON and add to peer connection
|
||||||
|
// webRtcManager.addIceCandidate(...)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun onCallEnded() {
|
||||||
|
_state.update { it.copy(status = CallStatus.ENDED) }
|
||||||
|
webRtcManager.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun acceptCall() {
|
||||||
|
val chatId = _state.value.chatId ?: return
|
||||||
|
// Create answer and send via SignalR
|
||||||
|
}
|
||||||
|
|
||||||
|
fun endCall() {
|
||||||
|
val chatId = _state.value.chatId ?: return
|
||||||
|
// Send call_end via SignalR
|
||||||
|
onCallEnded()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package calls.presentation
|
||||||
|
|
||||||
|
import androidx.lifecycle.ViewModel
|
||||||
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import chats.data.remote.signalr.ChatHubClient
|
||||||
|
import chats.data.remote.signalr.ChatEvent
|
||||||
|
import calls.data.remote.GroupWebRtcManager
|
||||||
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
|
import kotlinx.coroutines.flow.*
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import org.webrtc.*
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
data class ParticipantState(
|
||||||
|
val userId: String,
|
||||||
|
val videoTrack: VideoTrack? = null,
|
||||||
|
val isAudioMuted: Boolean = false,
|
||||||
|
val isVideoDisabled: Boolean = false
|
||||||
|
)
|
||||||
|
|
||||||
|
data class GroupCallState(
|
||||||
|
val chatId: String? = null,
|
||||||
|
val participants: Map<String, ParticipantState> = emptyMap(),
|
||||||
|
val isMicEnabled: Boolean = true,
|
||||||
|
val isCameraEnabled: Boolean = true
|
||||||
|
)
|
||||||
|
|
||||||
|
@HiltViewModel
|
||||||
|
class GroupCallViewModel @Inject constructor(
|
||||||
|
private val webRtcManager: GroupWebRtcManager,
|
||||||
|
private val signalrClient: ChatHubClient
|
||||||
|
) : ViewModel() {
|
||||||
|
|
||||||
|
private val _state = MutableStateFlow(GroupCallState())
|
||||||
|
val state: StateFlow<GroupCallState> = _state.asStateFlow()
|
||||||
|
|
||||||
|
init {
|
||||||
|
observeSignalREvents()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun observeSignalREvents() {
|
||||||
|
signalrClient.events.onEach { event ->
|
||||||
|
when (event) {
|
||||||
|
is ChatEvent.GroupCallUserJoined -> handleUserJoined(event.userId)
|
||||||
|
is ChatEvent.GroupCallUserLeft -> handleUserLeft(event.userId)
|
||||||
|
is ChatEvent.GroupCallOffer -> handleOffer(event.from, event.offer)
|
||||||
|
is ChatEvent.GroupCallAnswer -> handleAnswer(event.from, event.answer)
|
||||||
|
// Дополнительные обработчики ICE кандидатов и т.д.
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}.launchIn(viewModelScope)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleUserJoined(userId: String) {
|
||||||
|
// Создаем PeerConnection для нового участника
|
||||||
|
// Логика идентична портированному CallModal.tsx
|
||||||
|
_state.update { it.copy(participants = it.participants + (userId to ParticipantState(userId))) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleUserLeft(userId: String) {
|
||||||
|
webRtcManager.removeParticipant(userId)
|
||||||
|
_state.update { it.copy(participants = it.participants - userId) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleOffer(from: String, sdp: String) {
|
||||||
|
// Установка RemoteDescription и создание Answer
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleAnswer(from: String, sdp: String) {
|
||||||
|
// Установка RemoteDescription
|
||||||
|
}
|
||||||
|
|
||||||
|
fun toggleMic() {
|
||||||
|
_state.update { it.copy(isMicEnabled = !it.isMicEnabled) }
|
||||||
|
// Логика управления AudioTrack
|
||||||
|
}
|
||||||
|
|
||||||
|
fun toggleCamera() {
|
||||||
|
_state.update { it.copy(isCameraEnabled = !it.isCameraEnabled) }
|
||||||
|
// Логика управления VideoTrack
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onCleared() {
|
||||||
|
super.onCleared()
|
||||||
|
webRtcManager.closeAll()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package calls.presentation.components
|
||||||
|
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import androidx.compose.foundation.layout.*
|
||||||
|
import androidx.compose.foundation.lazy.grid.GridCells
|
||||||
|
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||||
|
import androidx.compose.foundation.lazy.grid.items
|
||||||
|
import androidx.compose.runtime.*
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import androidx.compose.ui.viewinterop.AndroidView
|
||||||
|
import org.webrtc.EglBase
|
||||||
|
import org.webrtc.SurfaceViewRenderer
|
||||||
|
import org.webrtc.VideoTrack
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun VideoGrid(
|
||||||
|
participants: Map<String, VideoTrack?>,
|
||||||
|
localVideoTrack: VideoTrack?
|
||||||
|
) {
|
||||||
|
val eglBaseContext = remember { EglBase.create().eglBaseContext }
|
||||||
|
val allVideoTracks = remember(participants, localVideoTrack) {
|
||||||
|
listOfNotNull(localVideoTrack) + participants.values.filterNotNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
LazyVerticalGrid(
|
||||||
|
columns = GridCells.Fixed(if (allVideoTracks.size <= 2) 1 else 2),
|
||||||
|
modifier = Modifier.fillMaxSize(),
|
||||||
|
contentPadding = PaddingValues(8.dp)
|
||||||
|
) {
|
||||||
|
items(allVideoTracks) { track ->
|
||||||
|
Box(
|
||||||
|
modifier = Modifier
|
||||||
|
.padding(4.dp)
|
||||||
|
.fillMaxWidth()
|
||||||
|
.aspectRatio(if (allVideoTracks.size == 1) 0.6f else 1f)
|
||||||
|
) {
|
||||||
|
VideoRenderer(videoTrack = track, eglBaseContext = eglBaseContext)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
fun VideoRenderer(
|
||||||
|
videoTrack: VideoTrack,
|
||||||
|
eglBaseContext: EglBase.Context
|
||||||
|
) {
|
||||||
|
AndroidView(
|
||||||
|
factory = { context ->
|
||||||
|
SurfaceViewRenderer(context).apply {
|
||||||
|
init(eglBaseContext, null)
|
||||||
|
layoutParams = ViewGroup.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT
|
||||||
|
)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
update = { view ->
|
||||||
|
videoTrack.addSink(view)
|
||||||
|
},
|
||||||
|
onRelease = { view ->
|
||||||
|
videoTrack.removeSink(view)
|
||||||
|
view.release()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
package chats.data.remote.api
|
||||||
|
|
||||||
|
import chats.data.remote.dto.ChatDto
|
||||||
|
import chats.data.remote.dto.MessageDto
|
||||||
|
import retrofit2.http.*
|
||||||
|
|
||||||
|
data class SendMessageRequest(
|
||||||
|
val content: String?,
|
||||||
|
val type: String = "text",
|
||||||
|
val attachments: List<AttachmentRequest>? = null,
|
||||||
|
val replyToId: String? = null,
|
||||||
|
val quote: String? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
data class AttachmentRequest(
|
||||||
|
val type: String,
|
||||||
|
val url: String,
|
||||||
|
val fileName: String,
|
||||||
|
val fileSize: Long
|
||||||
|
)
|
||||||
|
|
||||||
|
interface ChatApi {
|
||||||
|
@GET("chats")
|
||||||
|
suspend fun getChats(): List<ChatDto>
|
||||||
|
|
||||||
|
@GET("messages/chat/{chatId}")
|
||||||
|
suspend fun getMessages(
|
||||||
|
@Path("chatId") chatId: String,
|
||||||
|
@Query("cursor") cursor: String? = null,
|
||||||
|
@Query("limit") limit: Int? = 50
|
||||||
|
): List<MessageDto>
|
||||||
|
|
||||||
|
@POST("messages/chat/{chatId}")
|
||||||
|
suspend fun sendMessage(@Path("chatId") chatId: String, @Body request: SendMessageRequest): MessageDto
|
||||||
|
|
||||||
|
@Multipart
|
||||||
|
@POST("messages/upload")
|
||||||
|
suspend fun uploadFile(@Part file: okhttp3.MultipartBody.Part): FileUploadResponse
|
||||||
|
|
||||||
|
// Klipy GIF API
|
||||||
|
@GET("klipy/trending")
|
||||||
|
suspend fun getTrendingGifs(@Query("page") page: Int): KlipyResponse
|
||||||
|
|
||||||
|
@GET("klipy/search")
|
||||||
|
suspend fun searchGifs(@Query("q") query: String, @Query("page") page: Int): KlipyResponse
|
||||||
|
|
||||||
|
@GET("klipy/categories")
|
||||||
|
suspend fun getGifCategories(): GifCategoriesResponse
|
||||||
|
|
||||||
|
@POST("klipy/shared/{id}")
|
||||||
|
suspend fun markGifShared(@Path("id") id: String, @Body query: String)
|
||||||
|
|
||||||
|
@POST("messages/{messageId}/reactions")
|
||||||
|
suspend fun addReaction(@Path("messageId") messageId: String, @Query("emoji") emoji: String)
|
||||||
|
|
||||||
|
@POST("chats/{chatId}/typing")
|
||||||
|
suspend fun sendTypingStatus(@Path("chatId") chatId: String)
|
||||||
|
|
||||||
|
@POST("chats/{chatId}/read")
|
||||||
|
suspend fun markMessagesAsRead(@Path("chatId") chatId: String, @Body lastMessageId: String)
|
||||||
|
}
|
||||||
|
|
||||||
|
data class KlipyResponse(
|
||||||
|
val data: KlipyDataWrapper
|
||||||
|
)
|
||||||
|
|
||||||
|
data class KlipyDataWrapper(
|
||||||
|
val data: List<KlipyGifDto>
|
||||||
|
)
|
||||||
|
|
||||||
|
data class KlipyGifDto(
|
||||||
|
val id: String,
|
||||||
|
val images: GifImagesDto? = null,
|
||||||
|
val files: Map<String, Map<String, GifImageSourceDto>>? = null,
|
||||||
|
val file: Map<String, Map<String, GifImageSourceDto>>? = null,
|
||||||
|
val media_formats: Map<String, GifImageSourceDto>? = null,
|
||||||
|
val title: String? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
data class GifImagesDto(
|
||||||
|
val fixed_height: GifImageSourceDto? = null,
|
||||||
|
val original: GifImageSourceDto? = null,
|
||||||
|
val fixed_height_small: GifImageSourceDto? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
data class GifImageSourceDto(
|
||||||
|
val url: String
|
||||||
|
)
|
||||||
|
|
||||||
|
data class GifCategoryDto(
|
||||||
|
val category: String,
|
||||||
|
val preview_url: String,
|
||||||
|
val query: String
|
||||||
|
)
|
||||||
|
|
||||||
|
data class FileUploadResponse(
|
||||||
|
val url: String,
|
||||||
|
val filename: String,
|
||||||
|
val size: Long
|
||||||
|
)
|
||||||
|
|
||||||
|
data class GifCategoriesResponse(
|
||||||
|
val data: GifCategoriesData
|
||||||
|
)
|
||||||
|
|
||||||
|
data class GifCategoriesData(
|
||||||
|
val categories: List<GifCategoryDto>
|
||||||
|
)
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package chats.data.remote.dto
|
||||||
|
|
||||||
|
import com.google.gson.annotations.SerializedName
|
||||||
|
|
||||||
|
data class UserBasicDto(
|
||||||
|
@SerializedName("id") val id: String,
|
||||||
|
@SerializedName("username") val username: String? = null,
|
||||||
|
@SerializedName("displayName") val displayName: String? = null,
|
||||||
|
@SerializedName("avatarUrl") val avatarUrl: String? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
data class MessageDto(
|
||||||
|
@SerializedName("id") val id: String,
|
||||||
|
@SerializedName("chatId") val chatId: String? = null,
|
||||||
|
@SerializedName("senderId") val senderId: String? = null,
|
||||||
|
@SerializedName("content") val content: String? = null,
|
||||||
|
@SerializedName("type") val type: String? = null,
|
||||||
|
@SerializedName("sequenceId") val sequenceId: Int? = null,
|
||||||
|
@SerializedName("createdAt") val createdAt: String? = null,
|
||||||
|
@SerializedName("sender") val sender: UserBasicDto? = null,
|
||||||
|
@SerializedName("media") val media: List<MediaItemDto> = emptyList(),
|
||||||
|
@SerializedName("reactions") val reactions: List<ReactionDto>? = emptyList(),
|
||||||
|
@SerializedName("replyTo") val replyTo: MessageDto? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ReactionDto(
|
||||||
|
@SerializedName("emoji") val emoji: String,
|
||||||
|
@SerializedName("count") val count: Int,
|
||||||
|
@SerializedName("isSetByMe") val isSetByMe: Boolean
|
||||||
|
)
|
||||||
|
|
||||||
|
data class MediaItemDto(
|
||||||
|
@SerializedName("id") val id: String,
|
||||||
|
@SerializedName("type") val type: String,
|
||||||
|
@SerializedName("url") val url: String,
|
||||||
|
@SerializedName("filename") val filename: String? = null,
|
||||||
|
@SerializedName("size") val size: Long? = null,
|
||||||
|
@SerializedName("duration") val duration: Double? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ChatDto(
|
||||||
|
@SerializedName("id") val id: String,
|
||||||
|
@SerializedName("type") val type: String,
|
||||||
|
@SerializedName("name") val name: String? = null,
|
||||||
|
@SerializedName("avatar") val avatar: String? = null,
|
||||||
|
@SerializedName("unreadCount") val unreadCount: Int = 0,
|
||||||
|
@SerializedName("messages") val messages: List<MessageDto> = emptyList(),
|
||||||
|
@SerializedName("members") val members: List<ChatMemberDto> = emptyList()
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ChatMemberDto(
|
||||||
|
@SerializedName("userId") val userId: String,
|
||||||
|
@SerializedName("user") val user: UserBasicDto? = null
|
||||||
|
)
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package chats.data.remote.signalr
|
||||||
|
|
||||||
|
import chats.data.remote.dto.ChatDto
|
||||||
|
import chats.data.remote.dto.MessageDto
|
||||||
|
|
||||||
|
sealed class ChatEvent {
|
||||||
|
data class NewMessage(val message: MessageDto) : ChatEvent()
|
||||||
|
data class MessageEdited(val messageId: String, val chatId: String, val content: String) : ChatEvent()
|
||||||
|
data class MessageDeleted(val messageId: String, val chatId: String) : ChatEvent()
|
||||||
|
data class MessagesRead(val chatId: String, val userId: String, val lastReadSequenceId: Int) : ChatEvent()
|
||||||
|
data class UserTyping(val chatId: String, val userId: String) : ChatEvent()
|
||||||
|
data class UserStoppedTyping(val chatId: String, val userId: String) : ChatEvent()
|
||||||
|
data class UserOnline(val userId: String) : ChatEvent()
|
||||||
|
data class UserOffline(val userId: String, val lastSeen: String?) : ChatEvent()
|
||||||
|
data class NewChat(val chat: ChatDto) : ChatEvent()
|
||||||
|
data class ReactionUpdated(val messageId: String, val chatId: String, val userId: String, val emoji: String) : ChatEvent()
|
||||||
|
|
||||||
|
// Call Events (WebRTC Signaling)
|
||||||
|
data class CallIncoming(val chatId: String, val from: String, val offer: String, val callType: String) : ChatEvent()
|
||||||
|
data class CallAnswered(val chatId: String, val answer: String) : ChatEvent()
|
||||||
|
data class IceCandidateReceived(val chatId: String, val candidate: String) : ChatEvent()
|
||||||
|
data class CallEnded(val chatId: String) : ChatEvent()
|
||||||
|
|
||||||
|
// Group Call Events
|
||||||
|
data class GroupCallIncoming(val chatId: String, val from: String, val callerInfo: Any) : ChatEvent()
|
||||||
|
data class GroupCallParticipants(val chatId: String, val participants: List<String>) : ChatEvent()
|
||||||
|
data class GroupCallUserJoined(val chatId: String, val userId: String) : ChatEvent()
|
||||||
|
data class GroupCallUserLeft(val chatId: String, val userId: String) : ChatEvent()
|
||||||
|
data class GroupCallOffer(val chatId: String, val from: String, val offer: String) : ChatEvent()
|
||||||
|
data class GroupCallAnswer(val chatId: String, val from: String, val answer: String) : ChatEvent()
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package chats.data.remote.signalr
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import io.reactivex.rxjava3.core.Single
|
||||||
|
import com.microsoft.signalr.HubConnection
|
||||||
|
import com.microsoft.signalr.HubConnectionBuilder
|
||||||
|
import com.microsoft.signalr.HubConnectionState
|
||||||
|
import chats.data.remote.dto.ChatDto
|
||||||
|
import chats.data.remote.dto.MessageDto
|
||||||
|
import kotlinx.coroutines.flow.*
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import javax.inject.Inject
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
|
data class ReadMessagesRequest(
|
||||||
|
val chatId: String,
|
||||||
|
val lastReadMessageId: String,
|
||||||
|
val lastReadSequenceId: Int
|
||||||
|
)
|
||||||
|
|
||||||
|
enum class ConnectionStatus { CONNECTED, CONNECTING, DISCONNECTED }
|
||||||
|
|
||||||
|
@Singleton
|
||||||
|
class ChatHubClient @Inject constructor() {
|
||||||
|
private var hubConnection: HubConnection? = null
|
||||||
|
private val _events = MutableSharedFlow<ChatEvent>(extraBufferCapacity = 64)
|
||||||
|
val events: SharedFlow<ChatEvent> = _events.asSharedFlow()
|
||||||
|
|
||||||
|
private val _status = MutableStateFlow(ConnectionStatus.DISCONNECTED)
|
||||||
|
val status: StateFlow<ConnectionStatus> = _status.asStateFlow()
|
||||||
|
|
||||||
|
private val scope = CoroutineScope(Dispatchers.IO)
|
||||||
|
private var lastBaseUrl: String? = null
|
||||||
|
private var lastToken: String? = null
|
||||||
|
|
||||||
|
fun connect(baseUrl: String, accessToken: String) {
|
||||||
|
if (hubConnection?.connectionState == HubConnectionState.CONNECTED) return
|
||||||
|
|
||||||
|
lastBaseUrl = baseUrl
|
||||||
|
lastToken = accessToken
|
||||||
|
_status.value = ConnectionStatus.CONNECTING
|
||||||
|
|
||||||
|
hubConnection = HubConnectionBuilder.create("${baseUrl}/hubs/chat")
|
||||||
|
.withAccessTokenProvider(Single.just(accessToken))
|
||||||
|
.build()
|
||||||
|
|
||||||
|
setupHandlers()
|
||||||
|
|
||||||
|
hubConnection?.onClosed { exception ->
|
||||||
|
Log.e("ChatHubClient", "Connection closed. Reconnecting...", exception)
|
||||||
|
_status.value = ConnectionStatus.DISCONNECTED
|
||||||
|
scope.launch {
|
||||||
|
delay(5000)
|
||||||
|
connect(baseUrl, accessToken)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
hubConnection?.start()?.blockingAwait()
|
||||||
|
_status.value = ConnectionStatus.CONNECTED
|
||||||
|
Log.d("ChatHubClient", "SignalR Connected")
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.e("ChatHubClient", "SignalR Connection Error", e)
|
||||||
|
_status.value = ConnectionStatus.DISCONNECTED
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun setupHandlers() {
|
||||||
|
hubConnection?.let { conn ->
|
||||||
|
conn.on("new_message", { message: MessageDto ->
|
||||||
|
_events.tryEmit(ChatEvent.NewMessage(message))
|
||||||
|
}, MessageDto::class.java)
|
||||||
|
|
||||||
|
conn.on("messages_read", { chatId: String, userId: String, lastReadSequenceId: Int ->
|
||||||
|
_events.tryEmit(ChatEvent.MessagesRead(chatId, userId, lastReadSequenceId))
|
||||||
|
}, String::class.java, String::class.java, Int::class.java)
|
||||||
|
|
||||||
|
conn.on("user_typing", { chatId: String, userId: String ->
|
||||||
|
_events.tryEmit(ChatEvent.UserTyping(chatId, userId))
|
||||||
|
}, String::class.java, String::class.java)
|
||||||
|
|
||||||
|
conn.on("user_online", { userId: String ->
|
||||||
|
_events.tryEmit(ChatEvent.UserOnline(userId))
|
||||||
|
}, String::class.java)
|
||||||
|
|
||||||
|
conn.on("new_chat", { chat: ChatDto ->
|
||||||
|
_events.tryEmit(ChatEvent.NewChat(chat))
|
||||||
|
}, ChatDto::class.java)
|
||||||
|
|
||||||
|
conn.on("reaction_added", { messageId: String, chatId: String, userId: String, username: String, emoji: String ->
|
||||||
|
_events.tryEmit(ChatEvent.ReactionUpdated(messageId, chatId, userId, emoji))
|
||||||
|
}, String::class.java, String::class.java, String::class.java, String::class.java, String::class.java)
|
||||||
|
|
||||||
|
conn.on("reaction_removed", { messageId: String, chatId: String, userId: String, emoji: String ->
|
||||||
|
// Using ReactionUpdated with empty emoji to signal removal or just a specific removal event
|
||||||
|
_events.tryEmit(ChatEvent.ReactionUpdated(messageId, chatId, userId, ""))
|
||||||
|
}, String::class.java, String::class.java, String::class.java, String::class.java)
|
||||||
|
|
||||||
|
// WebRTC Signaling Handlers
|
||||||
|
conn.on("call_incoming", { chatId: String, from: String, offer: String, callType: String ->
|
||||||
|
_events.tryEmit(ChatEvent.CallIncoming(chatId, from, offer, callType))
|
||||||
|
}, String::class.java, String::class.java, String::class.java, String::class.java)
|
||||||
|
|
||||||
|
conn.on("call_answered", { chatId: String, answer: String ->
|
||||||
|
_events.tryEmit(ChatEvent.CallAnswered(chatId, answer))
|
||||||
|
}, String::class.java, String::class.java)
|
||||||
|
|
||||||
|
conn.on("ice_candidate", { chatId: String, candidate: String ->
|
||||||
|
_events.tryEmit(ChatEvent.IceCandidateReceived(chatId, candidate))
|
||||||
|
}, String::class.java, String::class.java)
|
||||||
|
|
||||||
|
conn.on("call_ended", { chatId: String ->
|
||||||
|
_events.tryEmit(ChatEvent.CallEnded(chatId))
|
||||||
|
}, String::class.java)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun disconnect() {
|
||||||
|
hubConnection?.stop()
|
||||||
|
_status.value = ConnectionStatus.DISCONNECTED
|
||||||
|
}
|
||||||
|
|
||||||
|
fun readMessages(request: ReadMessagesRequest) {
|
||||||
|
if (hubConnection?.connectionState == HubConnectionState.CONNECTED) {
|
||||||
|
hubConnection?.invoke("read_messages", request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
package chats.data.repository
|
||||||
|
|
||||||
|
import chats.data.remote.api.ChatApi
|
||||||
|
import chats.data.remote.api.SendMessageRequest
|
||||||
|
import chats.data.remote.dto.ChatDto
|
||||||
|
import chats.data.remote.dto.MessageDto
|
||||||
|
import chats.data.remote.dto.MediaItemDto
|
||||||
|
import chats.data.remote.dto.ReactionDto
|
||||||
|
import chats.domain.model.Chat
|
||||||
|
import chats.domain.model.Message
|
||||||
|
import chats.domain.model.MediaType
|
||||||
|
import chats.domain.repository.ChatRepository
|
||||||
|
import core.network.ServerConfig
|
||||||
|
import core.security.TokenManager
|
||||||
|
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||||
|
import okhttp3.MultipartBody
|
||||||
|
import okhttp3.RequestBody.Companion.asRequestBody
|
||||||
|
import javax.inject.Inject
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
|
||||||
|
class ChatRepositoryImpl @Inject constructor(
|
||||||
|
private val api: ChatApi,
|
||||||
|
private val tokenManager: TokenManager,
|
||||||
|
private val serverConfig: ServerConfig,
|
||||||
|
private val messageDao: core.database.data.MessageDao,
|
||||||
|
private val hubClient: chats.data.remote.signalr.ChatHubClient
|
||||||
|
) : ChatRepository {
|
||||||
|
private val gson = com.google.gson.Gson()
|
||||||
|
|
||||||
|
override suspend fun getChats(): List<Chat> {
|
||||||
|
val currentUserId = tokenManager.getUserId() ?: ""
|
||||||
|
val baseUrl = serverConfig.getBaseUrl().removeSuffix("/api/")
|
||||||
|
return api.getChats().map { it.toDomain(currentUserId, baseUrl) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getMessagesFlow(chatId: String): kotlinx.coroutines.flow.Flow<List<Message>> {
|
||||||
|
val baseUrl = serverConfig.getBaseUrl().removeSuffix("/api/")
|
||||||
|
return messageDao.getMessages(chatId).map { entities: List<core.database.data.MessageEntity> ->
|
||||||
|
entities.map { it.toDomain(baseUrl, gson) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getMessages(chatId: String): List<Message> {
|
||||||
|
val baseUrl = serverConfig.getBaseUrl().removeSuffix("/api/")
|
||||||
|
return try {
|
||||||
|
val messages = api.getMessages(chatId)
|
||||||
|
// Save to DB
|
||||||
|
messageDao.insertMessages(messages.map { msg: MessageDto -> msg.toEntity(baseUrl, gson) })
|
||||||
|
messages.map { it.toDomain(baseUrl) }
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// If network fails, caller should ideally use the Flow from DB
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun sendMessage(
|
||||||
|
chatId: String,
|
||||||
|
content: String?,
|
||||||
|
type: String,
|
||||||
|
attachments: List<chats.data.remote.api.AttachmentRequest>?
|
||||||
|
): Message {
|
||||||
|
val request = SendMessageRequest(
|
||||||
|
content = content,
|
||||||
|
type = type,
|
||||||
|
attachments = attachments
|
||||||
|
)
|
||||||
|
val baseUrl = serverConfig.getBaseUrl().removeSuffix("/api/")
|
||||||
|
return api.sendMessage(chatId, request).toDomain(baseUrl)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun addReaction(messageId: String, emoji: String) {
|
||||||
|
api.addReaction(messageId, emoji)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun sendTypingStatus(chatId: String) {
|
||||||
|
api.sendTypingStatus(chatId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun markMessagesAsRead(chatId: String, lastMessageId: String, lastReadSequenceId: Int) {
|
||||||
|
val request = chats.data.remote.signalr.ReadMessagesRequest(
|
||||||
|
chatId = chatId,
|
||||||
|
lastReadMessageId = lastMessageId,
|
||||||
|
lastReadSequenceId = lastReadSequenceId
|
||||||
|
)
|
||||||
|
hubClient.readMessages(request)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun saveMessage(message: Message) {
|
||||||
|
messageDao.insertMessages(listOf(message.toEntity(gson)))
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun deleteLocalMessage(messageId: String) {
|
||||||
|
messageDao.deleteMessage(messageId)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun uploadMedia(file: java.io.File): String {
|
||||||
|
val requestFile = file.asRequestBody("image/*".toMediaTypeOrNull())
|
||||||
|
val body = MultipartBody.Part.createFormData("file", file.name, requestFile)
|
||||||
|
return api.uploadFile(body).url
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getTrendingGifs(page: Int): List<chats.data.remote.api.KlipyGifDto> {
|
||||||
|
return api.getTrendingGifs(page).data.data
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun searchGifs(query: String, page: Int): List<chats.data.remote.api.KlipyGifDto> {
|
||||||
|
return api.searchGifs(query, page).data.data
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getGifCategories(): List<chats.data.remote.api.GifCategoryDto> {
|
||||||
|
return api.getGifCategories().data.categories
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mappers
|
||||||
|
fun ChatDto.toDomain(currentUserId: String, baseUrl: String): Chat {
|
||||||
|
val chatName = name ?: if (type == "personal") {
|
||||||
|
members.firstOrNull { it.userId != currentUserId }?.user?.displayName ?: "Unknown Chat"
|
||||||
|
} else "Group Chat"
|
||||||
|
|
||||||
|
val chatAvatar = (avatar ?: if (type == "personal") {
|
||||||
|
members.firstOrNull { it.userId != currentUserId }?.user?.avatarUrl
|
||||||
|
} else null)?.ensureAbsoluteUrl(baseUrl)
|
||||||
|
|
||||||
|
return Chat(
|
||||||
|
id = id,
|
||||||
|
type = type,
|
||||||
|
name = chatName,
|
||||||
|
avatar = chatAvatar,
|
||||||
|
unreadCount = unreadCount,
|
||||||
|
lastMessage = messages.firstOrNull()?.toDomain(baseUrl)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun Message.toEntity(gson: com.google.gson.Gson): core.database.data.MessageEntity {
|
||||||
|
return core.database.data.MessageEntity(
|
||||||
|
id = id,
|
||||||
|
chatId = chatId,
|
||||||
|
senderId = senderId,
|
||||||
|
senderName = senderName,
|
||||||
|
senderAvatar = senderAvatar,
|
||||||
|
content = content,
|
||||||
|
sequenceId = sequenceId,
|
||||||
|
createdAt = createdAt,
|
||||||
|
mediaType = mediaType.name.lowercase(),
|
||||||
|
mediaJson = gson.toJson(media),
|
||||||
|
reactionsJson = gson.toJson(reactions),
|
||||||
|
isRead = isRead,
|
||||||
|
replyToId = replyTo?.id
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun MessageDto.toDomain(baseUrl: String): Message {
|
||||||
|
val domainMediaType = when (type) {
|
||||||
|
"gif" -> MediaType.GIF
|
||||||
|
"image", "photo" -> MediaType.IMAGE
|
||||||
|
"video" -> MediaType.VIDEO
|
||||||
|
"audio", "voice" -> MediaType.AUDIO
|
||||||
|
"file" -> MediaType.FILE
|
||||||
|
else -> when (media.firstOrNull()?.type) {
|
||||||
|
"image", "photo" -> MediaType.IMAGE
|
||||||
|
"video" -> MediaType.VIDEO
|
||||||
|
"audio", "voice" -> MediaType.AUDIO
|
||||||
|
"file" -> MediaType.FILE
|
||||||
|
else -> MediaType.TEXT
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return Message(
|
||||||
|
id = id,
|
||||||
|
chatId = chatId ?: "",
|
||||||
|
senderId = senderId ?: "",
|
||||||
|
senderName = sender?.displayName ?: "Unknown",
|
||||||
|
senderAvatar = sender?.avatarUrl?.ensureAbsoluteUrl(baseUrl),
|
||||||
|
content = content,
|
||||||
|
sequenceId = sequenceId ?: 0,
|
||||||
|
createdAt = createdAt ?: "",
|
||||||
|
media = media.map {
|
||||||
|
chats.domain.model.Media(
|
||||||
|
id = it.id,
|
||||||
|
type = it.type,
|
||||||
|
url = it.url.ensureAbsoluteUrl(baseUrl),
|
||||||
|
filename = it.filename,
|
||||||
|
size = it.size,
|
||||||
|
duration = it.duration
|
||||||
|
)
|
||||||
|
},
|
||||||
|
mediaType = domainMediaType,
|
||||||
|
reactions = reactions?.associate { it.emoji to it.count } ?: emptyMap(),
|
||||||
|
isRead = true, // Network messages are usually considered read when fetched or handled by server
|
||||||
|
replyTo = replyTo?.toDomain(baseUrl)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun MessageDto.toEntity(baseUrl: String, gson: com.google.gson.Gson): core.database.data.MessageEntity {
|
||||||
|
return core.database.data.MessageEntity(
|
||||||
|
id = id,
|
||||||
|
chatId = chatId ?: "",
|
||||||
|
senderId = senderId ?: "",
|
||||||
|
senderName = sender?.displayName ?: "Unknown",
|
||||||
|
senderAvatar = sender?.avatarUrl?.ensureAbsoluteUrl(baseUrl),
|
||||||
|
content = content,
|
||||||
|
sequenceId = sequenceId ?: 0,
|
||||||
|
createdAt = createdAt ?: "",
|
||||||
|
mediaType = type ?: "text",
|
||||||
|
mediaJson = gson.toJson(media),
|
||||||
|
reactionsJson = gson.toJson(reactions),
|
||||||
|
isRead = true,
|
||||||
|
replyToId = replyTo?.id
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun core.database.data.MessageEntity.toDomain(baseUrl: String, gson: com.google.gson.Gson): Message {
|
||||||
|
val mediaTypeEnum = when (mediaType) {
|
||||||
|
"gif" -> MediaType.GIF
|
||||||
|
"image", "photo" -> MediaType.IMAGE
|
||||||
|
"video" -> MediaType.VIDEO
|
||||||
|
"audio", "voice" -> MediaType.AUDIO
|
||||||
|
"file" -> MediaType.FILE
|
||||||
|
else -> MediaType.TEXT
|
||||||
|
}
|
||||||
|
|
||||||
|
val mediaTypeToken = object : com.google.gson.reflect.TypeToken<List<chats.data.remote.dto.MediaItemDto>>() {}.type
|
||||||
|
val mediaDtos: List<chats.data.remote.dto.MediaItemDto> = gson.fromJson(mediaJson, mediaTypeToken) ?: emptyList()
|
||||||
|
|
||||||
|
val reactionsTypeToken = object : com.google.gson.reflect.TypeToken<List<chats.data.remote.dto.ReactionDto>>() {}.type
|
||||||
|
val reactionDtos: List<chats.data.remote.dto.ReactionDto> = gson.fromJson(reactionsJson, reactionsTypeToken) ?: emptyList()
|
||||||
|
|
||||||
|
return Message(
|
||||||
|
id = id,
|
||||||
|
chatId = chatId,
|
||||||
|
senderId = senderId,
|
||||||
|
senderName = senderName,
|
||||||
|
senderAvatar = senderAvatar,
|
||||||
|
content = content,
|
||||||
|
sequenceId = sequenceId,
|
||||||
|
createdAt = createdAt,
|
||||||
|
media = mediaDtos.map {
|
||||||
|
chats.domain.model.Media(
|
||||||
|
id = it.id,
|
||||||
|
type = it.type,
|
||||||
|
url = it.url.ensureAbsoluteUrl(baseUrl),
|
||||||
|
filename = it.filename,
|
||||||
|
size = it.size,
|
||||||
|
duration = it.duration
|
||||||
|
)
|
||||||
|
},
|
||||||
|
mediaType = mediaTypeEnum,
|
||||||
|
reactions = reactionDtos.associate { it.emoji to it.count },
|
||||||
|
isRead = isRead
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun String.ensureAbsoluteUrl(baseUrl: String): String {
|
||||||
|
return if (this.startsWith("http")) {
|
||||||
|
this
|
||||||
|
} else {
|
||||||
|
val base = baseUrl.removeSuffix("/")
|
||||||
|
val path = if (this.startsWith("/")) this else "/$this"
|
||||||
|
"$base$path"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package chats.di
|
||||||
|
|
||||||
|
import chats.data.remote.api.ChatApi
|
||||||
|
import chats.data.remote.signalr.ChatHubClient
|
||||||
|
import chats.data.repository.ChatRepositoryImpl
|
||||||
|
import chats.domain.repository.ChatRepository
|
||||||
|
import core.database.data.MessageDao
|
||||||
|
import core.network.ServerConfig
|
||||||
|
import core.security.TokenManager
|
||||||
|
import dagger.Module
|
||||||
|
import dagger.Provides
|
||||||
|
import dagger.hilt.InstallIn
|
||||||
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import retrofit2.Retrofit
|
||||||
|
import javax.inject.Singleton
|
||||||
|
|
||||||
|
@Module
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
object ChatModule {
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun provideChatApi(retrofit: Retrofit): ChatApi {
|
||||||
|
return retrofit.create(ChatApi::class.java)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun provideChatRepository(
|
||||||
|
api: ChatApi,
|
||||||
|
tokenManager: TokenManager,
|
||||||
|
serverConfig: ServerConfig,
|
||||||
|
messageDao: MessageDao,
|
||||||
|
hubClient: chats.data.remote.signalr.ChatHubClient
|
||||||
|
): ChatRepository {
|
||||||
|
return ChatRepositoryImpl(api, tokenManager, serverConfig, messageDao, hubClient)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun provideChatHubClient(): ChatHubClient {
|
||||||
|
return ChatHubClient()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package chats.domain.model
|
||||||
|
|
||||||
|
data class Chat(
|
||||||
|
val id: String,
|
||||||
|
val type: String,
|
||||||
|
val name: String,
|
||||||
|
val avatar: String?,
|
||||||
|
val unreadCount: Int,
|
||||||
|
val lastMessage: Message?
|
||||||
|
)
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package chats.domain.model
|
||||||
|
|
||||||
|
data class Message(
|
||||||
|
val id: String,
|
||||||
|
val chatId: String,
|
||||||
|
val senderId: String,
|
||||||
|
val senderName: String,
|
||||||
|
val senderAvatar: String? = null,
|
||||||
|
val content: String?,
|
||||||
|
val sequenceId: Int,
|
||||||
|
val createdAt: String,
|
||||||
|
val media: List<Media> = emptyList(),
|
||||||
|
val mediaType: MediaType = MediaType.TEXT,
|
||||||
|
val reactions: Map<String, Int> = emptyMap(),
|
||||||
|
val isRead: Boolean = false,
|
||||||
|
val replyTo: Message? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
data class Media(
|
||||||
|
val id: String,
|
||||||
|
val type: String,
|
||||||
|
val url: String,
|
||||||
|
val filename: String? = null,
|
||||||
|
val size: Long? = null,
|
||||||
|
val duration: Double? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
enum class MediaType {
|
||||||
|
TEXT, IMAGE, VIDEO, AUDIO, FILE, STORY_REPLY, GIF
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package chats.domain.repository
|
||||||
|
|
||||||
|
import chats.domain.model.Chat
|
||||||
|
import chats.domain.model.Message
|
||||||
|
|
||||||
|
interface ChatRepository {
|
||||||
|
suspend fun getChats(): List<Chat>
|
||||||
|
fun getMessagesFlow(chatId: String): kotlinx.coroutines.flow.Flow<List<Message>>
|
||||||
|
suspend fun getMessages(chatId: String): List<Message>
|
||||||
|
suspend fun sendMessage(
|
||||||
|
chatId: String,
|
||||||
|
content: String?,
|
||||||
|
type: String = "text",
|
||||||
|
attachments: List<chats.data.remote.api.AttachmentRequest>? = null
|
||||||
|
): Message
|
||||||
|
suspend fun addReaction(messageId: String, emoji: String)
|
||||||
|
suspend fun sendTypingStatus(chatId: String)
|
||||||
|
suspend fun markMessagesAsRead(chatId: String, lastMessageId: String, lastReadSequenceId: Int)
|
||||||
|
suspend fun saveMessage(message: Message)
|
||||||
|
suspend fun deleteLocalMessage(messageId: String)
|
||||||
|
suspend fun uploadMedia(file: java.io.File): String
|
||||||
|
suspend fun getTrendingGifs(page: Int = 0): List<chats.data.remote.api.KlipyGifDto>
|
||||||
|
suspend fun searchGifs(query: String, page: Int = 0): List<chats.data.remote.api.KlipyGifDto>
|
||||||
|
suspend fun getGifCategories(): List<chats.data.remote.api.GifCategoryDto>
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package chats.domain.usecase
|
||||||
|
|
||||||
|
import chats.data.remote.api.ChatApi
|
||||||
|
import chats.data.remote.api.FileUploadResponse
|
||||||
|
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||||
|
import okhttp3.MultipartBody
|
||||||
|
import okhttp3.RequestBody.Companion.asRequestBody
|
||||||
|
import java.io.File
|
||||||
|
import javax.inject.Inject
|
||||||
|
|
||||||
|
class UploadMediaUseCase @Inject constructor(
|
||||||
|
private val api: ChatApi
|
||||||
|
) {
|
||||||
|
suspend operator fun invoke(file: File): Result<FileUploadResponse> {
|
||||||
|
return try {
|
||||||
|
val requestFile = file.asRequestBody("image/*".toMediaTypeOrNull())
|
||||||
|
val body = MultipartBody.Part.createFormData("file", file.name, requestFile)
|
||||||
|
val response = api.uploadFile(body)
|
||||||
|
Result.success(response)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Result.failure(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user