// // Copyright (c) alveus.dev. All rights reserved. Licensed under the MIT License. // using Astral.Core.Entities; using Astral.Core.Extensions; using Astral.Core.RepositoryInterfaces; using Astral.Services.Constants; using Astral.Services.Dtos; using Astral.Services.Exceptions; using Astral.Services.Interfaces; using Injectio.Attributes; namespace Astral.Services.Services; /// [RegisterScoped] public class UserPresenceService : IUserPresenceService { private readonly IIdentityProvider _identityProvider; private readonly ICryptographyService _cryptographyService; private readonly IUserPresenceRepository _userPresenceRepository; /// /// Initializes a new instance of the class. /// /// Instance of . /// Instance of . /// Instance of . public UserPresenceService( IIdentityProvider identityProvider, ICryptographyService cryptographyService, IUserPresenceRepository userPresenceRepository) { _identityProvider = identityProvider; _cryptographyService = cryptographyService; _userPresenceRepository = userPresenceRepository; } /// public async Task HandleHeartbeat() { var userId = _identityProvider.GetUserId(); if (userId == Guid.Empty) { throw new UnauthorizedException(); } var heartbeat = await _userPresenceRepository.FindByIdAsync(userId); if (heartbeat is null) { heartbeat = new UserPresence() { Id = userId, LastHeartbeat = DateTime.UtcNow }; await _userPresenceRepository.AddAsync(heartbeat); } else { heartbeat.LastHeartbeat = DateTime.UtcNow; await _userPresenceRepository.UpdateAsync(heartbeat); } } /// public async Task ConsumeLocationHeartbeat(UserLocationHeartbeatDto heartbeat) { throw new NotImplementedException(); } /// public async Task ConsumePublicKey(Stream publicKey) { var userId = _identityProvider.GetUserId(); if (userId == Guid.Empty) { throw new UnauthorizedException(); } var key = _cryptographyService.ConvertPublicKey(publicKey.ToByteArray(), PublicKeyType.Pkcs1PublicKey); var heartbeat = await _userPresenceRepository.FindByIdAsync(userId); if (heartbeat is null) { heartbeat = new UserPresence() { Id = userId, LastHeartbeat = DateTime.UtcNow, PublicKey = key }; await _userPresenceRepository.AddAsync(heartbeat); } else { heartbeat.LastHeartbeat = DateTime.UtcNow; heartbeat.PublicKey = key; await _userPresenceRepository.UpdateAsync(heartbeat); } } }