♻️ I have no idea what I have done
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.RegularExpressions;
|
||||
using DysonNetwork.Shared.Auth;
|
||||
using DysonNetwork.Shared.Content;
|
||||
using DysonNetwork.Shared.Data;
|
||||
using DysonNetwork.Shared.Proto;
|
||||
using DysonNetwork.Sphere.Permission;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
@@ -1,10 +1,13 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using DysonNetwork.Shared;
|
||||
using DysonNetwork.Shared.Data;
|
||||
using DysonNetwork.Shared.Proto;
|
||||
using DysonNetwork.Sphere.Localization;
|
||||
using DysonNetwork.Sphere.Permission;
|
||||
using DysonNetwork.Sphere.Realm;
|
||||
using Grpc.Core;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NodaTime;
|
||||
@@ -20,7 +23,9 @@ public class ChatRoomController(
|
||||
IStringLocalizer<NotificationResource> localizer,
|
||||
AccountService.AccountServiceClient accounts,
|
||||
FileService.FileServiceClient files,
|
||||
FileReferenceService.FileReferenceServiceClient fileRefs
|
||||
FileReferenceService.FileReferenceServiceClient fileRefs,
|
||||
ActionLogService.ActionLogServiceClient als,
|
||||
PusherService.PusherServiceClient pusher
|
||||
) : ControllerBase
|
||||
{
|
||||
[HttpGet("{id:guid}")]
|
||||
@@ -123,10 +128,14 @@ public class ChatRoomController(
|
||||
db.ChatRooms.Add(dmRoom);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
als.CreateActionLogFromRequest(
|
||||
ActionLogType.ChatroomCreate,
|
||||
new Dictionary<string, object> { { "chatroom_id", dmRoom.Id } }, Request
|
||||
);
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.create",
|
||||
Meta = { { "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(dmRoom.Id.ToString()) } },
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
var invitedMember = dmRoom.Members.First(m => m.AccountId == request.RelatedUserId);
|
||||
invitedMember.ChatRoom = dmRoom;
|
||||
@@ -200,23 +209,44 @@ public class ChatRoomController(
|
||||
|
||||
if (request.PictureId is not null)
|
||||
{
|
||||
chatRoom.Picture = (await db.Files.FindAsync(request.PictureId))?.ToReferenceObject();
|
||||
if (chatRoom.Picture is null) return BadRequest("Invalid picture id, unable to find the file on cloud.");
|
||||
await fileRefs.CreateReferenceAsync(
|
||||
new CreateReferenceRequest
|
||||
try
|
||||
{
|
||||
var fileResponse = await files.GetFileAsync(new GetFileRequest { Id = request.PictureId });
|
||||
if (fileResponse == null) return BadRequest("Invalid picture id, unable to find the file on cloud.");
|
||||
chatRoom.Picture = CloudFileReferenceObject.FromProtoValue(fileResponse);
|
||||
|
||||
await fileRefs.CreateReferenceAsync(new CreateReferenceRequest
|
||||
{
|
||||
FileId = publisher.Picture.Id,
|
||||
Usage = "publisher.picture",
|
||||
ResourceId = publisher.ResourceIdentifier,
|
||||
}
|
||||
);
|
||||
FileId = fileResponse.Id,
|
||||
Usage = "chatroom.picture",
|
||||
ResourceId = chatRoom.ResourceIdentifier,
|
||||
});
|
||||
}
|
||||
catch (RpcException ex) when (ex.StatusCode == Grpc.Core.StatusCode.NotFound)
|
||||
{
|
||||
return BadRequest("Invalid picture id, unable to find the file on cloud.");
|
||||
}
|
||||
}
|
||||
|
||||
if (request.BackgroundId is not null)
|
||||
{
|
||||
chatRoom.Background = (await db.Files.FindAsync(request.BackgroundId))?.ToReferenceObject();
|
||||
if (chatRoom.Background is null)
|
||||
try
|
||||
{
|
||||
var fileResponse = await files.GetFileAsync(new GetFileRequest { Id = request.BackgroundId });
|
||||
if (fileResponse == null) return BadRequest("Invalid background id, unable to find the file on cloud.");
|
||||
chatRoom.Background = CloudFileReferenceObject.FromProtoValue(fileResponse);
|
||||
|
||||
await fileRefs.CreateReferenceAsync(new CreateReferenceRequest
|
||||
{
|
||||
FileId = fileResponse.Id,
|
||||
Usage = "chatroom.background",
|
||||
ResourceId = chatRoom.ResourceIdentifier,
|
||||
});
|
||||
}
|
||||
catch (RpcException ex) when (ex.StatusCode == Grpc.Core.StatusCode.NotFound)
|
||||
{
|
||||
return BadRequest("Invalid background id, unable to find the file on cloud.");
|
||||
}
|
||||
}
|
||||
|
||||
db.ChatRooms.Add(chatRoom);
|
||||
@@ -225,23 +255,33 @@ public class ChatRoomController(
|
||||
var chatRoomResourceId = $"chatroom:{chatRoom.Id}";
|
||||
|
||||
if (chatRoom.Picture is not null)
|
||||
await fileRefService.CreateReferenceAsync(
|
||||
chatRoom.Picture.Id,
|
||||
"chat.room.picture",
|
||||
chatRoomResourceId
|
||||
);
|
||||
{
|
||||
await fileRefs.CreateReferenceAsync(new CreateReferenceRequest
|
||||
{
|
||||
FileId = chatRoom.Picture.Id,
|
||||
Usage = "chat.room.picture",
|
||||
ResourceId = chatRoomResourceId
|
||||
});
|
||||
}
|
||||
|
||||
if (chatRoom.Background is not null)
|
||||
await fileRefService.CreateReferenceAsync(
|
||||
chatRoom.Background.Id,
|
||||
"chat.room.background",
|
||||
chatRoomResourceId
|
||||
);
|
||||
{
|
||||
await fileRefs.CreateReferenceAsync(new CreateReferenceRequest
|
||||
{
|
||||
FileId = chatRoom.Background.Id,
|
||||
Usage = "chat.room.background",
|
||||
ResourceId = chatRoomResourceId
|
||||
});
|
||||
}
|
||||
|
||||
als.CreateActionLogFromRequest(
|
||||
ActionLogType.ChatroomCreate,
|
||||
new Dictionary<string, object> { { "chatroom_id", chatRoom.Id } }, Request
|
||||
);
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.create",
|
||||
Meta = { { "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(chatRoom.Id.ToString()) } },
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return Ok(chatRoom);
|
||||
}
|
||||
@@ -279,38 +319,62 @@ public class ChatRoomController(
|
||||
|
||||
if (request.PictureId is not null)
|
||||
{
|
||||
var picture = await db.Files.FindAsync(request.PictureId);
|
||||
if (picture is null) return BadRequest("Invalid picture id, unable to find the file on cloud.");
|
||||
try
|
||||
{
|
||||
var fileResponse = await files.GetFileAsync(new GetFileRequest { Id = request.PictureId });
|
||||
if (fileResponse == null) return BadRequest("Invalid picture id, unable to find the file on cloud.");
|
||||
|
||||
// Remove old references for pictures
|
||||
await fileRefService.DeleteResourceReferencesAsync(chatRoom.ResourceIdentifier, "chat.room.picture");
|
||||
// Remove old references for pictures
|
||||
await fileRefs.DeleteResourceReferencesAsync(new DeleteResourceReferencesRequest
|
||||
{
|
||||
ResourceId = chatRoom.ResourceIdentifier,
|
||||
Usage = "chat.room.picture"
|
||||
});
|
||||
|
||||
// Add a new reference
|
||||
await fileRefService.CreateReferenceAsync(
|
||||
picture.Id,
|
||||
"chat.room.picture",
|
||||
chatRoom.ResourceIdentifier
|
||||
);
|
||||
// Add a new reference
|
||||
await fileRefs.CreateReferenceAsync(new CreateReferenceRequest
|
||||
{
|
||||
FileId = fileResponse.Id,
|
||||
Usage = "chat.room.picture",
|
||||
ResourceId = chatRoom.ResourceIdentifier
|
||||
});
|
||||
|
||||
chatRoom.Picture = picture.ToReferenceObject();
|
||||
chatRoom.Picture = CloudFileReferenceObject.FromProtoValue(fileResponse);
|
||||
}
|
||||
catch (RpcException ex) when (ex.StatusCode == Grpc.Core.StatusCode.NotFound)
|
||||
{
|
||||
return BadRequest("Invalid picture id, unable to find the file on cloud.");
|
||||
}
|
||||
}
|
||||
|
||||
if (request.BackgroundId is not null)
|
||||
{
|
||||
var background = await db.Files.FindAsync(request.BackgroundId);
|
||||
if (background is null) return BadRequest("Invalid background id, unable to find the file on cloud.");
|
||||
try
|
||||
{
|
||||
var fileResponse = await files.GetFileAsync(new GetFileRequest { Id = request.BackgroundId });
|
||||
if (fileResponse == null) return BadRequest("Invalid background id, unable to find the file on cloud.");
|
||||
|
||||
// Remove old references for backgrounds
|
||||
await fileRefService.DeleteResourceReferencesAsync(chatRoom.ResourceIdentifier, "chat.room.background");
|
||||
// Remove old references for backgrounds
|
||||
await fileRefs.DeleteResourceReferencesAsync(new DeleteResourceReferencesRequest
|
||||
{
|
||||
ResourceId = chatRoom.ResourceIdentifier,
|
||||
Usage = "chat.room.background"
|
||||
});
|
||||
|
||||
// Add a new reference
|
||||
await fileRefService.CreateReferenceAsync(
|
||||
background.Id,
|
||||
"chat.room.background",
|
||||
chatRoom.ResourceIdentifier
|
||||
);
|
||||
// Add a new reference
|
||||
await fileRefs.CreateReferenceAsync(new CreateReferenceRequest
|
||||
{
|
||||
FileId = fileResponse.Id,
|
||||
Usage = "chat.room.background",
|
||||
ResourceId = chatRoom.ResourceIdentifier
|
||||
});
|
||||
|
||||
chatRoom.Background = background.ToReferenceObject();
|
||||
chatRoom.Background = CloudFileReferenceObject.FromProtoValue(fileResponse);
|
||||
}
|
||||
catch (RpcException ex) when (ex.StatusCode == Grpc.Core.StatusCode.NotFound)
|
||||
{
|
||||
return BadRequest("Invalid background id, unable to find the file on cloud.");
|
||||
}
|
||||
}
|
||||
|
||||
if (request.Name is not null)
|
||||
@@ -325,10 +389,14 @@ public class ChatRoomController(
|
||||
db.ChatRooms.Update(chatRoom);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
als.CreateActionLogFromRequest(
|
||||
ActionLogType.ChatroomUpdate,
|
||||
new Dictionary<string, object> { { "chatroom_id", chatRoom.Id } }, Request
|
||||
);
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.update",
|
||||
Meta = { { "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(chatRoom.Id.ToString()) } },
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return Ok(chatRoom);
|
||||
}
|
||||
@@ -355,15 +423,22 @@ public class ChatRoomController(
|
||||
var chatRoomResourceId = $"chatroom:{chatRoom.Id}";
|
||||
|
||||
// Delete all file references for this chat room
|
||||
await fileRefService.DeleteResourceReferencesAsync(chatRoomResourceId);
|
||||
await fileRefs.DeleteResourceReferencesAsync(new DeleteResourceReferencesRequest
|
||||
{
|
||||
ResourceId = chatRoomResourceId
|
||||
});
|
||||
|
||||
db.ChatRooms.Remove(chatRoom);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
als.CreateActionLogFromRequest(
|
||||
ActionLogType.ChatroomDelete,
|
||||
new Dictionary<string, object> { { "chatroom_id", chatRoom.Id } }, Request
|
||||
);
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.delete",
|
||||
Meta = { { "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(chatRoom.Id.ToString()) } },
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return NoContent();
|
||||
}
|
||||
@@ -411,44 +486,44 @@ public class ChatRoomController(
|
||||
.Include(m => m.Account)
|
||||
.Include(m => m.Account.Profile);
|
||||
|
||||
if (withStatus)
|
||||
{
|
||||
var members = await query
|
||||
.OrderBy(m => m.JoinedAt)
|
||||
.ToListAsync();
|
||||
// if (withStatus)
|
||||
// {
|
||||
// var members = await query
|
||||
// .OrderBy(m => m.JoinedAt)
|
||||
// .ToListAsync();
|
||||
//
|
||||
// var memberStatuses = await aes.GetStatuses(members.Select(m => m.AccountId).ToList());
|
||||
//
|
||||
// if (!string.IsNullOrEmpty(status))
|
||||
// {
|
||||
// members = members.Where(m =>
|
||||
// memberStatuses.TryGetValue(m.AccountId, out var s) && s.Label != null &&
|
||||
// s.Label.Equals(status, StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
// }
|
||||
//
|
||||
// members = members.OrderByDescending(m => memberStatuses.TryGetValue(m.AccountId, out var s) && s.IsOnline)
|
||||
// .ToList();
|
||||
//
|
||||
// var total = members.Count;
|
||||
// Response.Headers.Append("X-Total", total.ToString());
|
||||
//
|
||||
// var result = members.Skip(skip).Take(take).ToList();
|
||||
//
|
||||
// return Ok(result);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
var total = await query.CountAsync();
|
||||
Response.Headers.Append("X-Total", total.ToString());
|
||||
|
||||
var memberStatuses = await aes.GetStatuses(members.Select(m => m.AccountId).ToList());
|
||||
var members = await query
|
||||
.OrderBy(m => m.JoinedAt)
|
||||
.Skip(skip)
|
||||
.Take(take)
|
||||
.ToListAsync();
|
||||
|
||||
if (!string.IsNullOrEmpty(status))
|
||||
{
|
||||
members = members.Where(m =>
|
||||
memberStatuses.TryGetValue(m.AccountId, out var s) && s.Label != null &&
|
||||
s.Label.Equals(status, StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
}
|
||||
|
||||
members = members.OrderByDescending(m => memberStatuses.TryGetValue(m.AccountId, out var s) && s.IsOnline)
|
||||
.ToList();
|
||||
|
||||
var total = members.Count;
|
||||
Response.Headers.Append("X-Total", total.ToString());
|
||||
|
||||
var result = members.Skip(skip).Take(take).ToList();
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
else
|
||||
{
|
||||
var total = await query.CountAsync();
|
||||
Response.Headers.Append("X-Total", total.ToString());
|
||||
|
||||
var members = await query
|
||||
.OrderBy(m => m.JoinedAt)
|
||||
.Skip(skip)
|
||||
.Take(take)
|
||||
.ToListAsync();
|
||||
|
||||
return Ok(members);
|
||||
}
|
||||
return Ok(members);
|
||||
// }
|
||||
}
|
||||
|
||||
|
||||
@@ -463,14 +538,23 @@ public class ChatRoomController(
|
||||
public async Task<ActionResult<ChatMember>> InviteMember(Guid roomId,
|
||||
[FromBody] ChatMemberRequest request)
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Shared.Proto.Account currentUser) return Unauthorized();
|
||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||
var accountId = Guid.Parse(currentUser.Id);
|
||||
|
||||
var relatedUser = await db.Accounts.FindAsync(request.RelatedUserId);
|
||||
if (relatedUser is null) return BadRequest("Related user was not found");
|
||||
// Get related user account
|
||||
var relatedUser =
|
||||
await accounts.GetAccountAsync(new GetAccountRequest { Id = request.RelatedUserId.ToString() });
|
||||
if (relatedUser == null) return BadRequest("Related user was not found");
|
||||
|
||||
if (await rels.HasRelationshipWithStatus(Guid.Parse(currentUser.Id), relatedUser.Id,
|
||||
RelationshipStatus.Blocked))
|
||||
// Check if the user has blocked the current user
|
||||
var relationship = await accounts.GetRelationshipAsync(new GetRelationshipRequest
|
||||
{
|
||||
AccountId = currentUser.Id,
|
||||
RelatedId = relatedUser.Id,
|
||||
Status = -100
|
||||
});
|
||||
|
||||
if (relationship != null && relationship.Relationship.Status == -100)
|
||||
return StatusCode(403, "You cannot invite a user that blocked you.");
|
||||
|
||||
var chatRoom = await db.ChatRooms
|
||||
@@ -512,7 +596,7 @@ public class ChatRoomController(
|
||||
|
||||
var newMember = new ChatMember
|
||||
{
|
||||
AccountId = relatedUser.Id,
|
||||
AccountId = Guid.Parse(relatedUser.Id),
|
||||
ChatRoomId = roomId,
|
||||
Role = request.Role,
|
||||
};
|
||||
@@ -523,10 +607,18 @@ public class ChatRoomController(
|
||||
newMember.ChatRoom = chatRoom;
|
||||
await _SendInviteNotify(newMember, currentUser);
|
||||
|
||||
als.CreateActionLogFromRequest(
|
||||
ActionLogType.ChatroomInvite,
|
||||
new Dictionary<string, object> { { "chatroom_id", chatRoom.Id }, { "account_id", relatedUser.Id } }, Request
|
||||
);
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.invite",
|
||||
Meta =
|
||||
{
|
||||
{ "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(chatRoom.Id.ToString()) },
|
||||
{ "account_id", Google.Protobuf.WellKnownTypes.Value.ForString(relatedUser.Id.ToString()) }
|
||||
},
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return Ok(newMember);
|
||||
}
|
||||
@@ -575,10 +667,14 @@ public class ChatRoomController(
|
||||
await db.SaveChangesAsync();
|
||||
_ = crs.PurgeRoomMembersCache(roomId);
|
||||
|
||||
als.CreateActionLogFromRequest(
|
||||
ActionLogType.ChatroomJoin,
|
||||
new Dictionary<string, object> { { "chatroom_id", roomId } }, Request
|
||||
);
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = ActionLogType.ChatroomJoin,
|
||||
Meta = { { "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(roomId.ToString()) } },
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return Ok(member);
|
||||
}
|
||||
@@ -688,12 +784,19 @@ public class ChatRoomController(
|
||||
|
||||
await crs.PurgeRoomMembersCache(roomId);
|
||||
|
||||
als.CreateActionLogFromRequest(
|
||||
ActionLogType.RealmAdjustRole,
|
||||
new Dictionary<string, object>
|
||||
{ { "chatroom_id", roomId }, { "account_id", memberId }, { "new_role", newRole } },
|
||||
Request
|
||||
);
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.role.edit",
|
||||
Meta =
|
||||
{
|
||||
{ "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(roomId.ToString()) },
|
||||
{ "account_id", Google.Protobuf.WellKnownTypes.Value.ForString(memberId.ToString()) },
|
||||
{ "new_role", Google.Protobuf.WellKnownTypes.Value.ForNumber(newRole) }
|
||||
},
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return Ok(targetMember);
|
||||
}
|
||||
@@ -738,10 +841,18 @@ public class ChatRoomController(
|
||||
await db.SaveChangesAsync();
|
||||
_ = crs.PurgeRoomMembersCache(roomId);
|
||||
|
||||
als.CreateActionLogFromRequest(
|
||||
ActionLogType.ChatroomKick,
|
||||
new Dictionary<string, object> { { "chatroom_id", roomId }, { "account_id", memberId } }, Request
|
||||
);
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.kick",
|
||||
Meta =
|
||||
{
|
||||
{ "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(roomId.ToString()) },
|
||||
{ "account_id", Google.Protobuf.WellKnownTypes.Value.ForString(memberId.ToString()) }
|
||||
},
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return NoContent();
|
||||
}
|
||||
@@ -780,10 +891,14 @@ public class ChatRoomController(
|
||||
await db.SaveChangesAsync();
|
||||
_ = crs.PurgeRoomMembersCache(roomId);
|
||||
|
||||
als.CreateActionLogFromRequest(
|
||||
ActionLogType.ChatroomJoin,
|
||||
new Dictionary<string, object> { { "chatroom_id", roomId } }, Request
|
||||
);
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = ActionLogType.ChatroomJoin,
|
||||
Meta = { { "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(roomId.ToString()) } },
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return Ok(chatRoom);
|
||||
}
|
||||
@@ -817,10 +932,14 @@ public class ChatRoomController(
|
||||
await db.SaveChangesAsync();
|
||||
await crs.PurgeRoomMembersCache(roomId);
|
||||
|
||||
als.CreateActionLogFromRequest(
|
||||
ActionLogType.ChatroomLeave,
|
||||
new Dictionary<string, object> { { "chatroom_id", roomId } }, Request
|
||||
);
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = ActionLogType.ChatroomLeave,
|
||||
Meta = { { "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(roomId.ToString()) } },
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return NoContent();
|
||||
}
|
||||
@@ -833,7 +952,19 @@ public class ChatRoomController(
|
||||
? localizer["ChatInviteDirectBody", sender.Nick]
|
||||
: localizer["ChatInviteBody", member.ChatRoom.Name ?? "Unnamed"];
|
||||
|
||||
AccountService.SetCultureInfo(member.Account);
|
||||
await nty.SendNotification(member.Account, "invites.chats", title, null, body, actionUri: "/chat");
|
||||
CultureService.SetCultureInfo(member.Account);
|
||||
await pusher.SendPushNotificationToUserAsync(
|
||||
new SendPushNotificationToUserRequest
|
||||
{
|
||||
UserId = member.Account.Id.ToString(),
|
||||
Notification = new PushNotification
|
||||
{
|
||||
Topic = "invites.chats",
|
||||
Title = title,
|
||||
Body = body,
|
||||
IsSavable = false
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
947
DysonNetwork.Sphere/Chat/ChatRoomController.cs.bak
Normal file
947
DysonNetwork.Sphere/Chat/ChatRoomController.cs.bak
Normal file
@@ -0,0 +1,947 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using DysonNetwork.Shared.Data;
|
||||
using DysonNetwork.Shared.Proto;
|
||||
using DysonNetwork.Sphere.Localization;
|
||||
using DysonNetwork.Sphere.Permission;
|
||||
using DysonNetwork.Sphere.Realm;
|
||||
using Grpc.Core;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NodaTime;
|
||||
|
||||
namespace DysonNetwork.Sphere.Chat;
|
||||
|
||||
[ApiController]
|
||||
[Route("/api/chat")]
|
||||
public class ChatRoomController(
|
||||
AppDatabase db,
|
||||
ChatRoomService crs,
|
||||
RealmService rs,
|
||||
IStringLocalizer<NotificationResource> localizer,
|
||||
AccountService.AccountServiceClient accounts,
|
||||
FileService.FileServiceClient files,
|
||||
FileReferenceService.FileReferenceServiceClient fileRefs,
|
||||
ActionLogService.ActionLogServiceClient als
|
||||
) : ControllerBase
|
||||
{
|
||||
[HttpGet("{id:guid}")]
|
||||
public async Task<ActionResult<ChatRoom>> GetChatRoom(Guid id)
|
||||
{
|
||||
var chatRoom = await db.ChatRooms
|
||||
.Where(c => c.Id == id)
|
||||
.Include(e => e.Realm)
|
||||
.FirstOrDefaultAsync();
|
||||
if (chatRoom is null) return NotFound();
|
||||
if (chatRoom.Type != ChatRoomType.DirectMessage) return Ok(chatRoom);
|
||||
|
||||
if (HttpContext.Items["CurrentUser"] is Account currentUser)
|
||||
chatRoom = await crs.LoadDirectMessageMembers(chatRoom, Guid.Parse(currentUser.Id));
|
||||
|
||||
return Ok(chatRoom);
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
[Authorize]
|
||||
public async Task<ActionResult<List<ChatRoom>>> ListJoinedChatRooms()
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser)
|
||||
return Unauthorized();
|
||||
var accountId = Guid.Parse(currentUser.Id);
|
||||
|
||||
var chatRooms = await db.ChatMembers
|
||||
.Where(m => m.AccountId == accountId)
|
||||
.Where(m => m.JoinedAt != null)
|
||||
.Where(m => m.LeaveAt == null)
|
||||
.Include(m => m.ChatRoom)
|
||||
.Select(m => m.ChatRoom)
|
||||
.ToListAsync();
|
||||
chatRooms = await crs.LoadDirectMessageMembers(chatRooms, accountId);
|
||||
chatRooms = await crs.SortChatRoomByLastMessage(chatRooms);
|
||||
|
||||
return Ok(chatRooms);
|
||||
}
|
||||
|
||||
public class DirectMessageRequest
|
||||
{
|
||||
[Required] public Guid RelatedUserId { get; set; }
|
||||
}
|
||||
|
||||
[HttpPost("direct")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult<ChatRoom>> CreateDirectMessage([FromBody] DirectMessageRequest request)
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Shared.Proto.Account currentUser)
|
||||
return Unauthorized();
|
||||
|
||||
var relatedUser = await accounts.GetAccountAsync(
|
||||
new GetAccountRequest { Id = request.RelatedUserId.ToString() }
|
||||
);
|
||||
if (relatedUser is null)
|
||||
return BadRequest("Related user was not found");
|
||||
|
||||
var hasBlocked = await accounts.HasRelationshipAsync(new GetRelationshipRequest()
|
||||
{
|
||||
AccountId = currentUser.Id,
|
||||
RelatedId = request.RelatedUserId.ToString(),
|
||||
Status = -100
|
||||
});
|
||||
if (hasBlocked?.Value ?? false)
|
||||
return StatusCode(403, "You cannot create direct message with a user that blocked you.");
|
||||
|
||||
// Check if DM already exists between these users
|
||||
var existingDm = await db.ChatRooms
|
||||
.Include(c => c.Members)
|
||||
.Where(c => c.Type == ChatRoomType.DirectMessage && c.Members.Count == 2)
|
||||
.Where(c => c.Members.Any(m => m.AccountId == Guid.Parse(currentUser.Id)))
|
||||
.Where(c => c.Members.Any(m => m.AccountId == request.RelatedUserId))
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
if (existingDm != null)
|
||||
return BadRequest("You already have a DM with this user.");
|
||||
|
||||
// Create new DM chat room
|
||||
var dmRoom = new ChatRoom
|
||||
{
|
||||
Type = ChatRoomType.DirectMessage,
|
||||
IsPublic = false,
|
||||
Members = new List<ChatMember>
|
||||
{
|
||||
new()
|
||||
{
|
||||
AccountId = Guid.Parse(currentUser.Id),
|
||||
Role = ChatMemberRole.Owner,
|
||||
JoinedAt = Instant.FromDateTimeUtc(DateTime.UtcNow)
|
||||
},
|
||||
new()
|
||||
{
|
||||
AccountId = request.RelatedUserId,
|
||||
Role = ChatMemberRole.Member,
|
||||
JoinedAt = null, // Pending status
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
db.ChatRooms.Add(dmRoom);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.create",
|
||||
Meta = { { "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(dmRoom.Id.ToString()) } },
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
var invitedMember = dmRoom.Members.First(m => m.AccountId == request.RelatedUserId);
|
||||
invitedMember.ChatRoom = dmRoom;
|
||||
await _SendInviteNotify(invitedMember, currentUser);
|
||||
|
||||
return Ok(dmRoom);
|
||||
}
|
||||
|
||||
[HttpGet("direct/{accountId:guid}")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult<ChatRoom>> GetDirectChatRoom(Guid accountId)
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Shared.Proto.Account currentUser)
|
||||
return Unauthorized();
|
||||
|
||||
var room = await db.ChatRooms
|
||||
.Include(c => c.Members)
|
||||
.Where(c => c.Type == ChatRoomType.DirectMessage && c.Members.Count == 2)
|
||||
.Where(c => c.Members.Any(m => m.AccountId == Guid.Parse(currentUser.Id)))
|
||||
.Where(c => c.Members.Any(m => m.AccountId == accountId))
|
||||
.FirstOrDefaultAsync();
|
||||
if (room is null) return NotFound();
|
||||
|
||||
return Ok(room);
|
||||
}
|
||||
|
||||
public class ChatRoomRequest
|
||||
{
|
||||
[Required] [MaxLength(1024)] public string? Name { get; set; }
|
||||
[MaxLength(4096)] public string? Description { get; set; }
|
||||
[MaxLength(32)] public string? PictureId { get; set; }
|
||||
[MaxLength(32)] public string? BackgroundId { get; set; }
|
||||
public Guid? RealmId { get; set; }
|
||||
public bool? IsCommunity { get; set; }
|
||||
public bool? IsPublic { get; set; }
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize]
|
||||
[RequiredPermission("global", "chat.create")]
|
||||
public async Task<ActionResult<ChatRoom>> CreateChatRoom(ChatRoomRequest request)
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Shared.Proto.Account currentUser) return Unauthorized();
|
||||
if (request.Name is null) return BadRequest("You cannot create a chat room without a name.");
|
||||
|
||||
var chatRoom = new ChatRoom
|
||||
{
|
||||
Name = request.Name,
|
||||
Description = request.Description ?? string.Empty,
|
||||
IsCommunity = request.IsCommunity ?? false,
|
||||
IsPublic = request.IsPublic ?? false,
|
||||
Type = ChatRoomType.Group,
|
||||
Members = new List<ChatMember>
|
||||
{
|
||||
new()
|
||||
{
|
||||
Role = ChatMemberRole.Owner,
|
||||
AccountId = Guid.Parse(currentUser.Id),
|
||||
JoinedAt = NodaTime.Instant.FromDateTimeUtc(DateTime.UtcNow)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (request.RealmId is not null)
|
||||
{
|
||||
if (!await rs.IsMemberWithRole(request.RealmId.Value, Guid.Parse(currentUser.Id),
|
||||
RealmMemberRole.Moderator))
|
||||
return StatusCode(403, "You need at least be a moderator to create chat linked to the realm.");
|
||||
chatRoom.RealmId = request.RealmId;
|
||||
}
|
||||
|
||||
if (request.PictureId is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var fileResponse = await files.GetFileAsync(new GetFileRequest { Id = request.PictureId });
|
||||
if (fileResponse == null) return BadRequest("Invalid picture id, unable to find the file on cloud.");
|
||||
chatRoom.Picture = CloudFileReferenceObject.FromProtoValue(fileResponse);
|
||||
|
||||
await fileRefs.CreateReferenceAsync(new CreateReferenceRequest
|
||||
{
|
||||
FileId = fileResponse.Id,
|
||||
Usage = "chatroom.picture",
|
||||
ResourceId = chatRoom.ResourceIdentifier,
|
||||
});
|
||||
}
|
||||
catch (RpcException ex) when (ex.StatusCode == Grpc.Core.StatusCode.NotFound)
|
||||
{
|
||||
return BadRequest("Invalid picture id, unable to find the file on cloud.");
|
||||
}
|
||||
}
|
||||
|
||||
if (request.BackgroundId is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var fileResponse = await files.GetFileAsync(new GetFileRequest { Id = request.BackgroundId });
|
||||
if (fileResponse == null) return BadRequest("Invalid background id, unable to find the file on cloud.");
|
||||
chatRoom.Background = CloudFileReferenceObject.FromProtoValue(fileResponse);
|
||||
|
||||
await fileRefs.CreateReferenceAsync(new CreateReferenceRequest
|
||||
{
|
||||
FileId = fileResponse.Id,
|
||||
Usage = "chatroom.background",
|
||||
ResourceId = chatRoom.ResourceIdentifier,
|
||||
});
|
||||
}
|
||||
catch (RpcException ex) when (ex.StatusCode == Grpc.Core.StatusCode.NotFound)
|
||||
{
|
||||
return BadRequest("Invalid background id, unable to find the file on cloud.");
|
||||
}
|
||||
}
|
||||
|
||||
db.ChatRooms.Add(chatRoom);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
var chatRoomResourceId = $"chatroom:{chatRoom.Id}";
|
||||
|
||||
if (chatRoom.Picture is not null)
|
||||
{
|
||||
await fileRefs.CreateReferenceAsync(new CreateReferenceRequest
|
||||
{
|
||||
FileId = chatRoom.Picture.Id,
|
||||
Usage = "chat.room.picture",
|
||||
ResourceId = chatRoomResourceId
|
||||
});
|
||||
}
|
||||
|
||||
if (chatRoom.Background is not null)
|
||||
{
|
||||
await fileRefs.CreateReferenceAsync(new CreateReferenceRequest
|
||||
{
|
||||
FileId = chatRoom.Background.Id,
|
||||
Usage = "chat.room.background",
|
||||
ResourceId = chatRoomResourceId
|
||||
});
|
||||
}
|
||||
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.create",
|
||||
Meta = { { "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(chatRoom.Id.ToString()) } },
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return Ok(chatRoom);
|
||||
}
|
||||
|
||||
|
||||
[HttpPatch("{id:guid}")]
|
||||
public async Task<ActionResult<ChatRoom>> UpdateChatRoom(Guid id, [FromBody] ChatRoomRequest request)
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Shared.Proto.Account currentUser) return Unauthorized();
|
||||
|
||||
var chatRoom = await db.ChatRooms
|
||||
.Where(e => e.Id == id)
|
||||
.FirstOrDefaultAsync();
|
||||
if (chatRoom is null) return NotFound();
|
||||
|
||||
if (chatRoom.RealmId is not null)
|
||||
{
|
||||
if (!await rs.IsMemberWithRole(chatRoom.RealmId.Value, Guid.Parse(currentUser.Id),
|
||||
RealmMemberRole.Moderator))
|
||||
return StatusCode(403, "You need at least be a realm moderator to update the chat.");
|
||||
}
|
||||
else if (!await crs.IsMemberWithRole(chatRoom.Id, Guid.Parse(currentUser.Id), ChatMemberRole.Moderator))
|
||||
return StatusCode(403, "You need at least be a moderator to update the chat.");
|
||||
|
||||
if (request.RealmId is not null)
|
||||
{
|
||||
var member = await db.RealmMembers
|
||||
.Where(m => m.AccountId == Guid.Parse(currentUser.Id))
|
||||
.Where(m => m.RealmId == request.RealmId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (member is null || member.Role < RealmMemberRole.Moderator)
|
||||
return StatusCode(403, "You need at least be a moderator to transfer the chat linked to the realm.");
|
||||
chatRoom.RealmId = member.RealmId;
|
||||
}
|
||||
|
||||
if (request.PictureId is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var fileResponse = await files.GetFileAsync(new GetFileRequest { Id = request.PictureId });
|
||||
if (fileResponse == null) return BadRequest("Invalid picture id, unable to find the file on cloud.");
|
||||
|
||||
// Remove old references for pictures
|
||||
await fileRefs.DeleteResourceReferencesAsync(new DeleteResourceReferencesRequest
|
||||
{
|
||||
ResourceId = chatRoom.ResourceIdentifier,
|
||||
Usage = "chat.room.picture"
|
||||
});
|
||||
|
||||
// Add a new reference
|
||||
await fileRefs.CreateReferenceAsync(new CreateReferenceRequest
|
||||
{
|
||||
FileId = fileResponse.Id,
|
||||
Usage = "chat.room.picture",
|
||||
ResourceId = chatRoom.ResourceIdentifier
|
||||
});
|
||||
|
||||
chatRoom.Picture = CloudFileReferenceObject.FromProtoValue(fileResponse);
|
||||
}
|
||||
catch (RpcException ex) when (ex.StatusCode == Grpc.Core.StatusCode.NotFound)
|
||||
{
|
||||
return BadRequest("Invalid picture id, unable to find the file on cloud.");
|
||||
}
|
||||
}
|
||||
|
||||
if (request.BackgroundId is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var fileResponse = await files.GetFileAsync(new GetFileRequest { Id = request.BackgroundId });
|
||||
if (fileResponse == null) return BadRequest("Invalid background id, unable to find the file on cloud.");
|
||||
|
||||
// Remove old references for backgrounds
|
||||
await fileRefs.DeleteResourceReferencesAsync(new DeleteResourceReferencesRequest
|
||||
{
|
||||
ResourceId = chatRoom.ResourceIdentifier,
|
||||
Usage = "chat.room.background"
|
||||
});
|
||||
|
||||
// Add a new reference
|
||||
await fileRefs.CreateReferenceAsync(new CreateReferenceRequest
|
||||
{
|
||||
FileId = fileResponse.Id,
|
||||
Usage = "chat.room.background",
|
||||
ResourceId = chatRoom.ResourceIdentifier
|
||||
});
|
||||
|
||||
chatRoom.Background = CloudFileReferenceObject.FromProtoValue(fileResponse);
|
||||
}
|
||||
catch (RpcException ex) when (ex.StatusCode == Grpc.Core.StatusCode.NotFound)
|
||||
{
|
||||
return BadRequest("Invalid background id, unable to find the file on cloud.");
|
||||
}
|
||||
}
|
||||
|
||||
if (request.Name is not null)
|
||||
chatRoom.Name = request.Name;
|
||||
if (request.Description is not null)
|
||||
chatRoom.Description = request.Description;
|
||||
if (request.IsCommunity is not null)
|
||||
chatRoom.IsCommunity = request.IsCommunity.Value;
|
||||
if (request.IsPublic is not null)
|
||||
chatRoom.IsPublic = request.IsPublic.Value;
|
||||
|
||||
db.ChatRooms.Update(chatRoom);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.update",
|
||||
Meta = { { "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(chatRoom.Id.ToString()) } },
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return Ok(chatRoom);
|
||||
}
|
||||
|
||||
[HttpDelete("{id:guid}")]
|
||||
public async Task<ActionResult> DeleteChatRoom(Guid id)
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Shared.Proto.Account currentUser) return Unauthorized();
|
||||
|
||||
var chatRoom = await db.ChatRooms
|
||||
.Where(e => e.Id == id)
|
||||
.FirstOrDefaultAsync();
|
||||
if (chatRoom is null) return NotFound();
|
||||
|
||||
if (chatRoom.RealmId is not null)
|
||||
{
|
||||
if (!await rs.IsMemberWithRole(chatRoom.RealmId.Value, Guid.Parse(currentUser.Id),
|
||||
RealmMemberRole.Moderator))
|
||||
return StatusCode(403, "You need at least be a realm moderator to delete the chat.");
|
||||
}
|
||||
else if (!await crs.IsMemberWithRole(chatRoom.Id, Guid.Parse(currentUser.Id), ChatMemberRole.Owner))
|
||||
return StatusCode(403, "You need at least be the owner to delete the chat.");
|
||||
|
||||
var chatRoomResourceId = $"chatroom:{chatRoom.Id}";
|
||||
|
||||
// Delete all file references for this chat room
|
||||
await fileRefs.DeleteResourceReferencesAsync(new DeleteResourceReferencesRequest
|
||||
{
|
||||
ResourceId = chatRoomResourceId
|
||||
});
|
||||
|
||||
db.ChatRooms.Remove(chatRoom);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.delete",
|
||||
Meta = { { "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(chatRoom.Id.ToString()) } },
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
[HttpGet("{roomId:guid}/members/me")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult<ChatMember>> GetRoomIdentity(Guid roomId)
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Shared.Proto.Account currentUser)
|
||||
return Unauthorized();
|
||||
|
||||
var member = await db.ChatMembers
|
||||
.Where(m => m.AccountId == Guid.Parse(currentUser.Id) && m.ChatRoomId == roomId)
|
||||
.Include(m => m.Account)
|
||||
.Include(m => m.Account.Profile)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
if (member == null)
|
||||
return NotFound();
|
||||
|
||||
return Ok(member);
|
||||
}
|
||||
|
||||
[HttpGet("{roomId:guid}/members")]
|
||||
public async Task<ActionResult<List<ChatMember>>> ListMembers(Guid roomId, [FromQuery] int take = 20,
|
||||
[FromQuery] int skip = 0, [FromQuery] bool withStatus = false, [FromQuery] string? status = null)
|
||||
{
|
||||
var currentUser = HttpContext.Items["CurrentUser"] as Shared.Proto.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 members of private chat room.");
|
||||
}
|
||||
|
||||
IQueryable<ChatMember> query = db.ChatMembers
|
||||
.Where(m => m.ChatRoomId == roomId)
|
||||
.Where(m => m.LeaveAt == null) // Add this condition to exclude left members
|
||||
.Include(m => m.Account)
|
||||
.Include(m => m.Account.Profile);
|
||||
|
||||
// if (withStatus)
|
||||
// {
|
||||
// var members = await query
|
||||
// .OrderBy(m => m.JoinedAt)
|
||||
// .ToListAsync();
|
||||
//
|
||||
// var memberStatuses = await aes.GetStatuses(members.Select(m => m.AccountId).ToList());
|
||||
//
|
||||
// if (!string.IsNullOrEmpty(status))
|
||||
// {
|
||||
// members = members.Where(m =>
|
||||
// memberStatuses.TryGetValue(m.AccountId, out var s) && s.Label != null &&
|
||||
// s.Label.Equals(status, StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
// }
|
||||
//
|
||||
// members = members.OrderByDescending(m => memberStatuses.TryGetValue(m.AccountId, out var s) && s.IsOnline)
|
||||
// .ToList();
|
||||
//
|
||||
// var total = members.Count;
|
||||
// Response.Headers.Append("X-Total", total.ToString());
|
||||
//
|
||||
// var result = members.Skip(skip).Take(take).ToList();
|
||||
//
|
||||
// return Ok(result);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
var total = await query.CountAsync();
|
||||
Response.Headers.Append("X-Total", total.ToString());
|
||||
|
||||
var members = await query
|
||||
.OrderBy(m => m.JoinedAt)
|
||||
.Skip(skip)
|
||||
.Take(take)
|
||||
.ToListAsync();
|
||||
|
||||
return Ok(members);
|
||||
// }
|
||||
}
|
||||
|
||||
|
||||
public class ChatMemberRequest
|
||||
{
|
||||
[Required] public Guid RelatedUserId { get; set; }
|
||||
[Required] public int Role { get; set; }
|
||||
}
|
||||
|
||||
[HttpPost("invites/{roomId:guid}")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult<ChatMember>> InviteMember(Guid roomId,
|
||||
[FromBody] ChatMemberRequest request)
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||
var accountId = Guid.Parse(currentUser.Id);
|
||||
|
||||
// Get related user account
|
||||
var relatedUser = await accounts.GetAccountAsync(new GetAccountRequest { Id = request.RelatedUserId.ToString() });
|
||||
if (relatedUser == null) return BadRequest("Related user was not found");
|
||||
|
||||
// Check if the user has blocked the current user
|
||||
var relationship = await accounts.GetRelationshipAsync(new GetRelationshipRequest
|
||||
{
|
||||
AccountId = currentUser.Id,
|
||||
RelatedId = relatedUser.Id,
|
||||
Status = -100
|
||||
});
|
||||
|
||||
if (relationship != null && relationship.Relationship.Status == -100)
|
||||
return StatusCode(403, "You cannot invite a user that blocked you.");
|
||||
|
||||
var chatRoom = await db.ChatRooms
|
||||
.Where(p => p.Id == roomId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (chatRoom is null) return NotFound();
|
||||
|
||||
// Handle realm-owned chat rooms
|
||||
if (chatRoom.RealmId is not null)
|
||||
{
|
||||
var realmMember = await db.RealmMembers
|
||||
.Where(m => m.AccountId == accountId)
|
||||
.Where(m => m.RealmId == chatRoom.RealmId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (realmMember is null || realmMember.Role < RealmMemberRole.Moderator)
|
||||
return StatusCode(403, "You need at least be a realm moderator to invite members to this chat.");
|
||||
}
|
||||
else
|
||||
{
|
||||
var chatMember = await db.ChatMembers
|
||||
.Where(m => m.AccountId == accountId)
|
||||
.Where(m => m.ChatRoomId == roomId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (chatMember is null) return StatusCode(403, "You are not even a member of the targeted chat room.");
|
||||
if (chatMember.Role < ChatMemberRole.Moderator)
|
||||
return StatusCode(403,
|
||||
"You need at least be a moderator to invite other members to this chat room.");
|
||||
if (chatMember.Role < request.Role)
|
||||
return StatusCode(403, "You cannot invite member with higher permission than yours.");
|
||||
}
|
||||
|
||||
var hasExistingMember = await db.ChatMembers
|
||||
.Where(m => m.AccountId == request.RelatedUserId)
|
||||
.Where(m => m.ChatRoomId == roomId)
|
||||
.Where(m => m.LeaveAt == null)
|
||||
.AnyAsync();
|
||||
if (hasExistingMember)
|
||||
return BadRequest("This user has been joined the chat cannot be invited again.");
|
||||
|
||||
var newMember = new ChatMember
|
||||
{
|
||||
AccountId = Guid.Parse(relatedUser.Id),
|
||||
ChatRoomId = roomId,
|
||||
Role = request.Role,
|
||||
};
|
||||
|
||||
db.ChatMembers.Add(newMember);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
newMember.ChatRoom = chatRoom;
|
||||
await _SendInviteNotify(newMember, currentUser);
|
||||
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.invite",
|
||||
Meta =
|
||||
{
|
||||
{ "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(chatRoom.Id.ToString()) },
|
||||
{ "account_id", Google.Protobuf.WellKnownTypes.Value.ForString(relatedUser.Id.ToString()) }
|
||||
},
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return Ok(newMember);
|
||||
}
|
||||
|
||||
[HttpGet("invites")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult<List<ChatMember>>> ListChatInvites()
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Shared.Proto.Account currentUser) return Unauthorized();
|
||||
var accountId = Guid.Parse(currentUser.Id);
|
||||
|
||||
var members = await db.ChatMembers
|
||||
.Where(m => m.AccountId == accountId)
|
||||
.Where(m => m.JoinedAt == null)
|
||||
.Include(e => e.ChatRoom)
|
||||
.Include(e => e.Account)
|
||||
.Include(e => e.Account.Profile)
|
||||
.ToListAsync();
|
||||
|
||||
var chatRooms = members.Select(m => m.ChatRoom).ToList();
|
||||
var directMembers =
|
||||
(await crs.LoadDirectMessageMembers(chatRooms, accountId)).ToDictionary(c => c.Id, c => c.Members);
|
||||
|
||||
foreach (var member in members.Where(member => member.ChatRoom.Type == ChatRoomType.DirectMessage))
|
||||
member.ChatRoom.Members = directMembers[member.ChatRoom.Id];
|
||||
|
||||
return members.ToList();
|
||||
}
|
||||
|
||||
[HttpPost("invites/{roomId:guid}/accept")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult<ChatRoom>> AcceptChatInvite(Guid roomId)
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||
var accountId = Guid.Parse(currentUser.Id);
|
||||
|
||||
var member = await db.ChatMembers
|
||||
.Where(m => m.AccountId == accountId)
|
||||
.Where(m => m.ChatRoomId == roomId)
|
||||
.Where(m => m.JoinedAt == null)
|
||||
.FirstOrDefaultAsync();
|
||||
if (member is null) return NotFound();
|
||||
|
||||
member.JoinedAt = Instant.FromDateTimeUtc(DateTime.UtcNow);
|
||||
db.Update(member);
|
||||
await db.SaveChangesAsync();
|
||||
_ = crs.PurgeRoomMembersCache(roomId);
|
||||
|
||||
als.CreateActionLogFromRequest(
|
||||
ActionLogType.ChatroomJoin,
|
||||
new Dictionary<string, object> { { "chatroom_id", roomId } }, Request
|
||||
);
|
||||
|
||||
return Ok(member);
|
||||
}
|
||||
|
||||
[HttpPost("invites/{roomId:guid}/decline")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult> DeclineChatInvite(Guid roomId)
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||
var accountId = Guid.Parse(currentUser.Id);
|
||||
|
||||
var member = await db.ChatMembers
|
||||
.Where(m => m.AccountId == accountId)
|
||||
.Where(m => m.ChatRoomId == roomId)
|
||||
.Where(m => m.JoinedAt == null)
|
||||
.FirstOrDefaultAsync();
|
||||
if (member is null) return NotFound();
|
||||
|
||||
member.LeaveAt = SystemClock.Instance.GetCurrentInstant();
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
public class ChatMemberNotifyRequest
|
||||
{
|
||||
public ChatMemberNotify? NotifyLevel { get; set; }
|
||||
public Instant? BreakUntil { get; set; }
|
||||
}
|
||||
|
||||
[HttpPatch("{roomId:guid}/members/me/notify")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult<ChatMember>> UpdateChatMemberNotify(
|
||||
Guid roomId,
|
||||
[FromBody] ChatMemberNotifyRequest request
|
||||
)
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||
|
||||
var chatRoom = await db.ChatRooms
|
||||
.Where(r => r.Id == roomId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (chatRoom is null) return NotFound();
|
||||
|
||||
var accountId = Guid.Parse(currentUser.Id);
|
||||
var targetMember = await db.ChatMembers
|
||||
.Where(m => m.AccountId == accountId && m.ChatRoomId == roomId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (targetMember is null) return BadRequest("You have not joined this chat room.");
|
||||
if (request.NotifyLevel is not null)
|
||||
targetMember.Notify = request.NotifyLevel.Value;
|
||||
if (request.BreakUntil is not null)
|
||||
targetMember.BreakUntil = request.BreakUntil.Value;
|
||||
|
||||
db.ChatMembers.Update(targetMember);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
await crs.PurgeRoomMembersCache(roomId);
|
||||
|
||||
return Ok(targetMember);
|
||||
}
|
||||
|
||||
[HttpPatch("{roomId:guid}/members/{memberId:guid}/role")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult<ChatMember>> UpdateChatMemberRole(Guid roomId, Guid memberId, [FromBody] int newRole)
|
||||
{
|
||||
if (newRole >= ChatMemberRole.Owner) return BadRequest("Unable to set chat member to owner or greater role.");
|
||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||
|
||||
var chatRoom = await db.ChatRooms
|
||||
.Where(r => r.Id == roomId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (chatRoom is null) return NotFound();
|
||||
|
||||
// Check if the chat room is owned by a realm
|
||||
if (chatRoom.RealmId is not null)
|
||||
{
|
||||
var realmMember = await db.RealmMembers
|
||||
.Where(m => m.AccountId == Guid.Parse(currentUser.Id))
|
||||
.Where(m => m.RealmId == chatRoom.RealmId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (realmMember is null || realmMember.Role < RealmMemberRole.Moderator)
|
||||
return StatusCode(403, "You need at least be a realm moderator to change member roles.");
|
||||
}
|
||||
else
|
||||
{
|
||||
var targetMember = await db.ChatMembers
|
||||
.Where(m => m.AccountId == memberId && m.ChatRoomId == roomId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (targetMember is null) return NotFound();
|
||||
|
||||
// Check if the current user has permission to change roles
|
||||
if (
|
||||
!await crs.IsMemberWithRole(
|
||||
chatRoom.Id,
|
||||
Guid.Parse(currentUser.Id),
|
||||
ChatMemberRole.Moderator,
|
||||
targetMember.Role,
|
||||
newRole
|
||||
)
|
||||
)
|
||||
return StatusCode(403, "You don't have enough permission to edit the roles of members.");
|
||||
|
||||
targetMember.Role = newRole;
|
||||
db.ChatMembers.Update(targetMember);
|
||||
await db.SaveChangesAsync();
|
||||
|
||||
await crs.PurgeRoomMembersCache(roomId);
|
||||
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.role.edit",
|
||||
Meta =
|
||||
{
|
||||
{ "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(roomId.ToString()) },
|
||||
{ "account_id", Google.Protobuf.WellKnownTypes.Value.ForString(memberId.ToString()) },
|
||||
{ "new_role", Google.Protobuf.WellKnownTypes.Value.ForNumber(newRole) }
|
||||
},
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return Ok(targetMember);
|
||||
}
|
||||
|
||||
return BadRequest();
|
||||
}
|
||||
|
||||
[HttpDelete("{roomId:guid}/members/{memberId:guid}")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult> RemoveChatMember(Guid roomId, Guid memberId)
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||
|
||||
var chatRoom = await db.ChatRooms
|
||||
.Where(r => r.Id == roomId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (chatRoom is null) return NotFound();
|
||||
|
||||
// Check if the chat room is owned by a realm
|
||||
if (chatRoom.RealmId is not null)
|
||||
{
|
||||
if (!await rs.IsMemberWithRole(chatRoom.RealmId.Value, Guid.Parse(currentUser.Id),
|
||||
RealmMemberRole.Moderator))
|
||||
return StatusCode(403, "You need at least be a realm moderator to remove members.");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (!await crs.IsMemberWithRole(chatRoom.Id, Guid.Parse(currentUser.Id), ChatMemberRole.Moderator))
|
||||
return StatusCode(403, "You need at least be a moderator to remove members.");
|
||||
|
||||
// Find the target member
|
||||
var member = await db.ChatMembers
|
||||
.Where(m => m.AccountId == memberId && m.ChatRoomId == roomId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (member is null) return NotFound();
|
||||
|
||||
// Check if the current user has sufficient permissions
|
||||
if (!await crs.IsMemberWithRole(chatRoom.Id, memberId, member.Role))
|
||||
return StatusCode(403, "You cannot remove members with equal or higher roles.");
|
||||
|
||||
member.LeaveAt = SystemClock.Instance.GetCurrentInstant();
|
||||
await db.SaveChangesAsync();
|
||||
_ = crs.PurgeRoomMembersCache(roomId);
|
||||
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.kick",
|
||||
Meta =
|
||||
{
|
||||
{ "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(roomId.ToString()) },
|
||||
{ "account_id", Google.Protobuf.WellKnownTypes.Value.ForString(memberId.ToString()) }
|
||||
},
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
return BadRequest();
|
||||
}
|
||||
|
||||
|
||||
[HttpPost("{roomId:guid}/members/me")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult<ChatRoom>> JoinChatRoom(Guid roomId)
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||
|
||||
var chatRoom = await db.ChatRooms
|
||||
.Where(r => r.Id == roomId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (chatRoom is null) return NotFound();
|
||||
if (!chatRoom.IsCommunity)
|
||||
return StatusCode(403, "This chat room isn't a community. You need an invitation to join.");
|
||||
|
||||
var existingMember = await db.ChatMembers
|
||||
.FirstOrDefaultAsync(m => m.AccountId == Guid.Parse(currentUser.Id) && m.ChatRoomId == roomId);
|
||||
if (existingMember != null)
|
||||
return BadRequest("You are already a member of this chat room.");
|
||||
|
||||
var newMember = new ChatMember
|
||||
{
|
||||
AccountId = Guid.Parse(currentUser.Id),
|
||||
ChatRoomId = roomId,
|
||||
Role = ChatMemberRole.Member,
|
||||
JoinedAt = NodaTime.Instant.FromDateTimeUtc(DateTime.UtcNow)
|
||||
};
|
||||
|
||||
db.ChatMembers.Add(newMember);
|
||||
await db.SaveChangesAsync();
|
||||
_ = crs.PurgeRoomMembersCache(roomId);
|
||||
|
||||
als.CreateActionLogFromRequest(
|
||||
ActionLogType.ChatroomJoin,
|
||||
new Dictionary<string, object> { { "chatroom_id", roomId } }, Request
|
||||
);
|
||||
|
||||
return Ok(chatRoom);
|
||||
}
|
||||
|
||||
[HttpDelete("{roomId:guid}/members/me")]
|
||||
[Authorize]
|
||||
public async Task<ActionResult> LeaveChat(Guid roomId)
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||
|
||||
var member = await db.ChatMembers
|
||||
.Where(m => m.AccountId == Guid.Parse(currentUser.Id))
|
||||
.Where(m => m.ChatRoomId == roomId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (member is null) return NotFound();
|
||||
|
||||
if (member.Role == ChatMemberRole.Owner)
|
||||
{
|
||||
// Check if this is the only owner
|
||||
var otherOwners = await db.ChatMembers
|
||||
.Where(m => m.ChatRoomId == roomId)
|
||||
.Where(m => m.Role == ChatMemberRole.Owner)
|
||||
.Where(m => m.AccountId != Guid.Parse(currentUser.Id))
|
||||
.AnyAsync();
|
||||
|
||||
if (!otherOwners)
|
||||
return BadRequest("The last owner cannot leave the chat. Transfer ownership first or delete the chat.");
|
||||
}
|
||||
|
||||
member.LeaveAt = Instant.FromDateTimeUtc(DateTime.UtcNow);
|
||||
await db.SaveChangesAsync();
|
||||
await crs.PurgeRoomMembersCache(roomId);
|
||||
|
||||
_ = als.CreateActionLogAsync(new CreateActionLogRequest
|
||||
{
|
||||
Action = "chatrooms.leave",
|
||||
Meta = { { "chatroom_id", Google.Protobuf.WellKnownTypes.Value.ForString(roomId.ToString()) } },
|
||||
AccountId = currentUser.Id,
|
||||
UserAgent = Request.Headers.UserAgent,
|
||||
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
private async Task _SendInviteNotify(ChatMember member, Account sender)
|
||||
{
|
||||
string title = localizer["ChatInviteTitle"];
|
||||
|
||||
string body = member.ChatRoom.Type == ChatRoomType.DirectMessage
|
||||
? localizer["ChatInviteDirectBody", sender.Nick]
|
||||
: localizer["ChatInviteBody", member.ChatRoom.Name ?? "Unnamed"];
|
||||
|
||||
AccountService.SetCultureInfo(member.Account);
|
||||
await nty.SendNotification(member.Account, "invites.chats", title, null, body, actionUri: "/chat");
|
||||
}
|
||||
}
|
@@ -1,8 +1,7 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using DysonNetwork.Sphere.Account;
|
||||
using DysonNetwork.Shared.Data;
|
||||
using DysonNetwork.Shared.Proto;
|
||||
using DysonNetwork.Sphere.Chat.Realtime;
|
||||
using DysonNetwork.Sphere.Connection;
|
||||
using DysonNetwork.Sphere.Storage;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NodaTime;
|
||||
|
||||
@@ -10,7 +9,8 @@ namespace DysonNetwork.Sphere.Chat;
|
||||
|
||||
public partial class ChatService(
|
||||
AppDatabase db,
|
||||
FileReferenceService fileRefService,
|
||||
FileService.FileServiceClient filesClient,
|
||||
FileReferenceService.FileReferenceServiceClient fileRefs,
|
||||
IServiceScopeFactory scopeFactory,
|
||||
IRealtimeService realtime,
|
||||
ILogger<ChatService> logger
|
||||
@@ -33,7 +33,7 @@ public partial class ChatService(
|
||||
// Create a new scope for database operations
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
var dbContext = scope.ServiceProvider.GetRequiredService<AppDatabase>();
|
||||
var webReader = scope.ServiceProvider.GetRequiredService<Connection.WebReader.WebReaderService>();
|
||||
var webReader = scope.ServiceProvider.GetRequiredService<WebReader.WebReaderService>();
|
||||
var newChat = scope.ServiceProvider.GetRequiredService<ChatService>();
|
||||
|
||||
// Preview the links in the message
|
||||
@@ -86,7 +86,7 @@ public partial class ChatService(
|
||||
/// <param name="webReader">The web reader service</param>
|
||||
/// <returns>The message with link previews added to its meta data</returns>
|
||||
public async Task<Message> PreviewMessageLinkAsync(Message message,
|
||||
Connection.WebReader.WebReaderService? webReader = null)
|
||||
WebReader.WebReaderService? webReader = null)
|
||||
{
|
||||
if (string.IsNullOrEmpty(message.Content))
|
||||
return message;
|
||||
@@ -109,7 +109,7 @@ public partial class ChatService(
|
||||
|
||||
var embeds = (List<Dictionary<string, object>>)message.Meta["embeds"];
|
||||
webReader ??= scopeFactory.CreateScope().ServiceProvider
|
||||
.GetRequiredService<Connection.WebReader.WebReaderService>();
|
||||
.GetRequiredService<WebReader.WebReaderService>();
|
||||
|
||||
// Process up to 3 links to avoid excessive processing
|
||||
var processedLinks = 0;
|
||||
@@ -157,16 +157,13 @@ public partial class ChatService(
|
||||
var files = message.Attachments.Distinct().ToList();
|
||||
if (files.Count != 0)
|
||||
{
|
||||
var messageResourceId = $"message:{message.Id}";
|
||||
foreach (var file in files)
|
||||
var request = new CreateReferenceBatchRequest
|
||||
{
|
||||
await fileRefService.CreateReferenceAsync(
|
||||
file.Id,
|
||||
ChatFileUsageIdentifier,
|
||||
messageResourceId,
|
||||
duration: Duration.FromDays(30)
|
||||
);
|
||||
}
|
||||
Usage = ChatFileUsageIdentifier,
|
||||
ResourceId = message.ResourceIdentifier,
|
||||
};
|
||||
request.FilesId.AddRange(message.Attachments.Select(a => a.Id));
|
||||
await fileRefs.CreateReferenceBatchAsync(request);
|
||||
}
|
||||
|
||||
// Then start the delivery process
|
||||
@@ -203,8 +200,7 @@ public partial class ChatService(
|
||||
message.ChatRoom = room;
|
||||
|
||||
using var scope = scopeFactory.CreateScope();
|
||||
var scopedWs = scope.ServiceProvider.GetRequiredService<WebSocketService>();
|
||||
var scopedNty = scope.ServiceProvider.GetRequiredService<NotificationService>();
|
||||
var scopedNty = scope.ServiceProvider.GetRequiredService<PusherService.PusherServiceClient>();
|
||||
var scopedCrs = scope.ServiceProvider.GetRequiredService<ChatRoomService>();
|
||||
|
||||
var roomSubject = room is { Type: ChatRoomType.DirectMessage, Name: null } ? "DM" :
|
||||
@@ -230,30 +226,32 @@ public partial class ChatService(
|
||||
if (!string.IsNullOrEmpty(room.Name))
|
||||
metaDict["room_name"] = room.Name;
|
||||
|
||||
var notification = new Notification
|
||||
var notification = new PushNotification
|
||||
{
|
||||
Topic = "messages.new",
|
||||
Title = $"{sender.Nick ?? sender.Account.Nick} ({roomSubject})",
|
||||
Content = !string.IsNullOrEmpty(message.Content)
|
||||
Body = !string.IsNullOrEmpty(message.Content)
|
||||
? message.Content[..Math.Min(message.Content.Length, 100)]
|
||||
: "<no content>",
|
||||
Meta = metaDict,
|
||||
Priority = 10,
|
||||
};
|
||||
notification.Meta.Add(GrpcTypeHelper.ConvertToValueMap(metaDict));
|
||||
|
||||
List<Account> accountsToNotify = [];
|
||||
foreach (var member in members)
|
||||
{
|
||||
scopedWs.SendPacketToAccount(member.AccountId, new WebSocketPacket
|
||||
await scopedNty.PushWebSocketPacketToUsersAsync(new PushWebSocketPacketToUsersRequest
|
||||
{
|
||||
Type = type,
|
||||
Data = message
|
||||
Packet = new WebSocketPacket
|
||||
{
|
||||
Type = type,
|
||||
Data = GrpcTypeHelper.ConvertObjectToValue(metaDict),
|
||||
},
|
||||
});
|
||||
|
||||
if (member.Account.Id == sender.AccountId) continue;
|
||||
if (member.AccountId == sender.AccountId) continue;
|
||||
if (member.Notify == ChatMemberNotify.None) continue;
|
||||
// if (scopedWs.IsUserSubscribedToChatRoom(member.AccountId, room.Id.ToString())) continue;
|
||||
if (message.MembersMentioned is null || !message.MembersMentioned.Contains(member.Account.Id))
|
||||
if (message.MembersMentioned is null || !message.MembersMentioned.Contains(member.AccountId))
|
||||
{
|
||||
var now = SystemClock.Instance.GetCurrentInstant();
|
||||
if (member.BreakUntil is not null && member.BreakUntil > now) continue;
|
||||
@@ -265,8 +263,10 @@ public partial class ChatService(
|
||||
|
||||
logger.LogInformation($"Trying to deliver message to {accountsToNotify.Count} accounts...");
|
||||
// Only send notifications if there are accounts to notify
|
||||
var ntyRequest = new SendPushNotificationToUsersRequest { Notification = notification };
|
||||
ntyRequest.UserIds.AddRange(accountsToNotify.Select(a => a.Id.ToString()));
|
||||
if (accountsToNotify.Count > 0)
|
||||
await scopedNty.SendNotificationBatch(notification, accountsToNotify, save: false);
|
||||
await scopedNty.SendPushNotificationToUsersAsync(ntyRequest);
|
||||
|
||||
logger.LogInformation($"Delivered message to {accountsToNotify.Count} accounts.");
|
||||
}
|
||||
@@ -495,25 +495,24 @@ public partial class ChatService(
|
||||
var messageResourceId = $"message:{message.Id}";
|
||||
|
||||
// Delete existing references for this message
|
||||
await fileRefService.DeleteResourceReferencesAsync(messageResourceId);
|
||||
await fileRefs.DeleteResourceReferencesAsync(
|
||||
new DeleteResourceReferencesRequest { ResourceId = messageResourceId }
|
||||
);
|
||||
|
||||
// Create new references for each attachment
|
||||
foreach (var fileId in attachmentsId)
|
||||
var createRequest = new CreateReferenceBatchRequest
|
||||
{
|
||||
await fileRefService.CreateReferenceAsync(
|
||||
fileId,
|
||||
ChatFileUsageIdentifier,
|
||||
messageResourceId,
|
||||
duration: Duration.FromDays(30)
|
||||
);
|
||||
}
|
||||
Usage = ChatFileUsageIdentifier,
|
||||
ResourceId = messageResourceId,
|
||||
};
|
||||
createRequest.FilesId.AddRange(attachmentsId);
|
||||
await fileRefs.CreateReferenceBatchAsync(createRequest);
|
||||
|
||||
// Update message attachments by getting files from database
|
||||
var files = await db.Files
|
||||
.Where(f => attachmentsId.Contains(f.Id))
|
||||
.ToListAsync();
|
||||
|
||||
message.Attachments = files.Select(x => x.ToReferenceObject()).ToList();
|
||||
// Update message attachments by getting files from da
|
||||
var queryRequest = new GetFileBatchRequest();
|
||||
queryRequest.Ids.AddRange(attachmentsId);
|
||||
var queryResult = await filesClient.GetFileBatchAsync(queryRequest);
|
||||
message.Attachments = queryResult.Files.Select(CloudFileReferenceObject.FromProtoValue).ToList();
|
||||
}
|
||||
|
||||
message.EditedAt = SystemClock.Instance.GetCurrentInstant();
|
||||
@@ -542,7 +541,9 @@ public partial class ChatService(
|
||||
{
|
||||
// Remove all file references for this message
|
||||
var messageResourceId = $"message:{message.Id}";
|
||||
await fileRefService.DeleteResourceReferencesAsync(messageResourceId);
|
||||
await fileRefs.DeleteResourceReferencesAsync(
|
||||
new DeleteResourceReferencesRequest { ResourceId = messageResourceId }
|
||||
);
|
||||
|
||||
db.ChatMessages.Remove(message);
|
||||
await db.SaveChangesAsync();
|
||||
@@ -575,4 +576,4 @@ public class SyncResponse
|
||||
{
|
||||
public List<MessageChange> Changes { get; set; } = [];
|
||||
public Instant CurrentTimestamp { get; set; }
|
||||
}
|
||||
}
|
@@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using DysonNetwork.Shared.Proto;
|
||||
|
||||
namespace DysonNetwork.Sphere.Chat.Realtime;
|
||||
|
||||
|
@@ -1,32 +1,31 @@
|
||||
using DysonNetwork.Sphere.Connection;
|
||||
using DysonNetwork.Sphere.Storage;
|
||||
using Livekit.Server.Sdk.Dotnet;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NodaTime;
|
||||
using System.Text.Json;
|
||||
using DysonNetwork.Shared.Cache;
|
||||
using DysonNetwork.Shared.Data;
|
||||
using DysonNetwork.Shared.Proto;
|
||||
|
||||
namespace DysonNetwork.Sphere.Chat.Realtime;
|
||||
|
||||
/// <summary>
|
||||
/// LiveKit implementation of the real-time communication service
|
||||
/// </summary>
|
||||
public class LivekitRealtimeService : IRealtimeService
|
||||
public class LiveKitRealtimeService : IRealtimeService
|
||||
{
|
||||
private readonly AppDatabase _db;
|
||||
private readonly ICacheService _cache;
|
||||
private readonly WebSocketService _ws;
|
||||
|
||||
private readonly ILogger<LivekitRealtimeService> _logger;
|
||||
private readonly ILogger<LiveKitRealtimeService> _logger;
|
||||
private readonly RoomServiceClient _roomService;
|
||||
private readonly AccessToken _accessToken;
|
||||
private readonly WebhookReceiver _webhookReceiver;
|
||||
|
||||
public LivekitRealtimeService(
|
||||
public LiveKitRealtimeService(
|
||||
IConfiguration configuration,
|
||||
ILogger<LivekitRealtimeService> logger,
|
||||
ILogger<LiveKitRealtimeService> logger,
|
||||
AppDatabase db,
|
||||
ICacheService cache,
|
||||
WebSocketService ws
|
||||
ICacheService cache
|
||||
)
|
||||
{
|
||||
_logger = logger;
|
||||
@@ -45,7 +44,6 @@ public class LivekitRealtimeService : IRealtimeService
|
||||
|
||||
_db = db;
|
||||
_cache = cache;
|
||||
_ws = ws;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -159,7 +157,7 @@ public class LivekitRealtimeService : IRealtimeService
|
||||
evt.Room.Name, evt.Participant.Identity);
|
||||
|
||||
// Broadcast participant list update to all participants
|
||||
await _BroadcastParticipantUpdate(evt.Room.Name);
|
||||
// await _BroadcastParticipantUpdate(evt.Room.Name);
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -174,7 +172,7 @@ public class LivekitRealtimeService : IRealtimeService
|
||||
evt.Room.Name, evt.Participant.Identity);
|
||||
|
||||
// Broadcast participant list update to all participants
|
||||
await _BroadcastParticipantUpdate(evt.Room.Name);
|
||||
// await _BroadcastParticipantUpdate(evt.Room.Name);
|
||||
}
|
||||
|
||||
break;
|
||||
@@ -310,82 +308,4 @@ public class LivekitRealtimeService : IRealtimeService
|
||||
JoinedAt = DateTime.UtcNow
|
||||
};
|
||||
}
|
||||
|
||||
// Broadcast participant update to all participants in a room
|
||||
private async Task _BroadcastParticipantUpdate(string roomName)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Get the room ID from the session name
|
||||
var roomInfo = await _db.ChatRealtimeCall
|
||||
.Where(c => c.SessionId == roomName && c.EndedAt == null)
|
||||
.Select(c => new { c.RoomId, c.Id })
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
if (roomInfo == null)
|
||||
{
|
||||
_logger.LogWarning("Could not find room info for session: {SessionName}", roomName);
|
||||
return;
|
||||
}
|
||||
|
||||
// Get current participants
|
||||
var livekitParticipants = await GetRoomParticipantsAsync(roomName);
|
||||
|
||||
// Get all room members who should receive this update
|
||||
var roomMembers = await _db.ChatMembers
|
||||
.Where(m => m.ChatRoomId == roomInfo.RoomId && m.LeaveAt == null)
|
||||
.Select(m => m.AccountId)
|
||||
.ToListAsync();
|
||||
|
||||
// Get member profiles for participants who have account IDs
|
||||
var accountIds = livekitParticipants
|
||||
.Where(p => p.AccountId.HasValue)
|
||||
.Select(p => p.AccountId!.Value)
|
||||
.ToList();
|
||||
|
||||
var memberProfiles = new Dictionary<Guid, ChatMember>();
|
||||
if (accountIds.Count != 0)
|
||||
{
|
||||
memberProfiles = await _db.ChatMembers
|
||||
.Where(m => m.ChatRoomId == roomInfo.RoomId && accountIds.Contains(m.AccountId))
|
||||
.Include(m => m.Account)
|
||||
.ThenInclude(m => m.Profile)
|
||||
.ToDictionaryAsync(m => m.AccountId, m => m);
|
||||
}
|
||||
|
||||
// Convert to CallParticipant objects
|
||||
var participants = livekitParticipants.Select(p => new CallParticipant
|
||||
{
|
||||
Identity = p.Identity,
|
||||
Name = p.Name,
|
||||
AccountId = p.AccountId,
|
||||
JoinedAt = p.JoinedAt,
|
||||
Profile = p.AccountId.HasValue && memberProfiles.TryGetValue(p.AccountId.Value, out var profile)
|
||||
? profile
|
||||
: null
|
||||
}).ToList();
|
||||
|
||||
// Create the update packet with CallParticipant objects
|
||||
var updatePacket = new WebSocketPacket
|
||||
{
|
||||
Type = WebSocketPacketType.CallParticipantsUpdate,
|
||||
Data = new Dictionary<string, object>
|
||||
{
|
||||
{ "room_id", roomInfo.RoomId },
|
||||
{ "call_id", roomInfo.Id },
|
||||
{ "participants", participants }
|
||||
}
|
||||
};
|
||||
|
||||
// Send the update to all members
|
||||
foreach (var accountId in roomMembers)
|
||||
{
|
||||
_ws.SendPacketToAccount(accountId, updatePacket);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error broadcasting participant update for room {RoomName}", roomName);
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,3 +1,4 @@
|
||||
using DysonNetwork.Shared.Proto;
|
||||
using DysonNetwork.Sphere.Chat.Realtime;
|
||||
using Livekit.Server.Sdk.Dotnet;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
@@ -48,8 +49,9 @@ public class RealtimeCallController(
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||
|
||||
var accountId = Guid.Parse(currentUser.Id);
|
||||
var member = await db.ChatMembers
|
||||
.Where(m => m.AccountId == currentUser.Id && m.ChatRoomId == roomId)
|
||||
.Where(m => m.AccountId == accountId && m.ChatRoomId == roomId)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
if (member == null || member.Role < ChatMemberRole.Member)
|
||||
@@ -74,8 +76,9 @@ public class RealtimeCallController(
|
||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||
|
||||
// Check if the user is a member of the chat room
|
||||
var accountId = Guid.Parse(currentUser.Id);
|
||||
var member = await db.ChatMembers
|
||||
.Where(m => m.AccountId == currentUser.Id && m.ChatRoomId == roomId)
|
||||
.Where(m => m.AccountId == accountId && m.ChatRoomId == roomId)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
if (member == null || member.Role < ChatMemberRole.Member)
|
||||
@@ -102,7 +105,7 @@ public class RealtimeCallController(
|
||||
|
||||
// Get current participants from the LiveKit service
|
||||
var participants = new List<CallParticipant>();
|
||||
if (realtime is LivekitRealtimeService livekitService)
|
||||
if (realtime is LiveKitRealtimeService livekitService)
|
||||
{
|
||||
var roomParticipants = await livekitService.GetRoomParticipantsAsync(ongoingCall.SessionId);
|
||||
participants = [];
|
||||
@@ -146,8 +149,9 @@ public class RealtimeCallController(
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||
|
||||
var accountId = Guid.Parse(currentUser.Id);
|
||||
var member = await db.ChatMembers
|
||||
.Where(m => m.AccountId == currentUser.Id && m.ChatRoomId == roomId)
|
||||
.Where(m => m.AccountId == accountId && m.ChatRoomId == roomId)
|
||||
.Include(m => m.ChatRoom)
|
||||
.FirstOrDefaultAsync();
|
||||
if (member == null || member.Role < ChatMemberRole.Member)
|
||||
@@ -165,8 +169,9 @@ public class RealtimeCallController(
|
||||
{
|
||||
if (HttpContext.Items["CurrentUser"] is not Account currentUser) return Unauthorized();
|
||||
|
||||
var accountId = Guid.Parse(currentUser.Id);
|
||||
var member = await db.ChatMembers
|
||||
.Where(m => m.AccountId == currentUser.Id && m.ChatRoomId == roomId)
|
||||
.Where(m => m.AccountId == accountId && m.ChatRoomId == roomId)
|
||||
.FirstOrDefaultAsync();
|
||||
if (member == null || member.Role < ChatMemberRole.Member)
|
||||
return StatusCode(403, "You need to be a normal member to end a call.");
|
||||
|
Reference in New Issue
Block a user