Chat subscribe fixes and status update

This commit is contained in:
2025-09-27 19:25:10 +08:00
parent 1075177511
commit 58a44e8af4
8 changed files with 292 additions and 15 deletions

View File

@@ -483,6 +483,36 @@ public class ChatRoomController(
return Ok(await crs.LoadMemberAccount(member));
}
[HttpGet("{roomId:guid}/members/online")]
public async Task<ActionResult<int>> GetOnlineUsersCount(Guid roomId)
{
var currentUser = HttpContext.Items["CurrentUser"] as Account;
var room = await db.ChatRooms
.FirstOrDefaultAsync(r => r.Id == roomId);
if (room is null) return NotFound();
if (!room.IsPublic)
{
if (currentUser is null) return Unauthorized();
var member = await db.ChatMembers
.FirstOrDefaultAsync(m => m.ChatRoomId == roomId && m.AccountId == Guid.Parse(currentUser.Id));
if (member is null) return StatusCode(403, "You need to be a member to see online count of private chat room.");
}
var members = await db.ChatMembers
.Where(m => m.ChatRoomId == roomId)
.Where(m => m.LeaveAt == null)
.Select(m => m.AccountId)
.ToListAsync();
var memberStatuses = await accountsHelper.GetAccountStatusBatch(members);
var onlineCount = memberStatuses.Count(s => s.Value.IsOnline);
return Ok(onlineCount);
}
[HttpGet("{roomId:guid}/members")]
public async Task<ActionResult<List<SnChatMember>>> ListMembers(Guid roomId,
[FromQuery] int take = 20,

View File

@@ -167,20 +167,28 @@ public class ChatRoomService(
public async Task SubscribeChatRoom(SnChatMember member)
{
var cacheKey = ChatRoomSubscribeKeyPrefix + member.Id;
var cacheKey = $"{ChatRoomSubscribeKeyPrefix}{member.ChatRoomId}:{member.Id}";
await cache.SetAsync(cacheKey, true, TimeSpan.FromHours(1));
await cache.AddToGroupAsync(cacheKey, $"chatroom:subscribers:{member.ChatRoomId}");
}
public async Task UnsubscribeChatRoom(SnChatMember member)
{
var cacheKey = ChatRoomSubscribeKeyPrefix + member.Id;
var cacheKey = $"{ChatRoomSubscribeKeyPrefix}{member.ChatRoomId}:{member.Id}";
await cache.RemoveAsync(cacheKey);
}
public async Task<bool> IsSubscribedChatRoom(Guid memberId)
public async Task<bool> IsSubscribedChatRoom(Guid roomId, Guid memberId)
{
var cacheKey = ChatRoomSubscribeKeyPrefix + memberId;
var cacheKey = $"{ChatRoomSubscribeKeyPrefix}{roomId}:{memberId}";
var result = await cache.GetAsync<bool?>(cacheKey);
return result ?? false;
}
public async Task<List<Guid>> GetSubscribedMembers(Guid roomId)
{
var group = $"chatroom:subscribers:{roomId}";
var keys = await cache.GetGroupKeysAsync(group);
return keys.Select(k => Guid.Parse(k.Split(':').Last())).ToList();
}
}