Add chat message handling and WebSocket integration

Introduce new `ChatService` for managing chat messages, including marking messages as read and checking read status. Add `WebSocketPacket` class for handling WebSocket communication and integrate it with `WebSocketService` to process chat-related packets. Enhance `ChatRoom` and `ChatMember` models with additional fields and relationships. Update `AppDatabase` to include new chat-related entities and adjust permissions for chat creation.
This commit is contained in:
LittleSheep 2025-05-02 19:51:32 +08:00
parent da6a891b5f
commit 17de9a0f23
18 changed files with 483 additions and 1819 deletions

View File

@ -50,9 +50,11 @@ public class AppDatabase(
public DbSet<Realm.Realm> Realms { get; set; } public DbSet<Realm.Realm> Realms { get; set; }
public DbSet<Realm.RealmMember> RealmMembers { get; set; } public DbSet<Realm.RealmMember> RealmMembers { get; set; }
public DbSet<Chat.ChatRoom> ChatRooms { get; set; } public DbSet<Chat.ChatRoom> ChatRooms { get; set; }
public DbSet<Chat.ChatMember> ChatMembers { get; set; } public DbSet<Chat.ChatMember> ChatMembers { get; set; }
public DbSet<Chat.Message> ChatMessages { get; set; }
public DbSet<Chat.MessageStatus> ChatStatuses { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{ {
@ -80,7 +82,7 @@ public class AppDatabase(
PermissionService.NewPermissionNode("group:default", "global", "posts.create", true), PermissionService.NewPermissionNode("group:default", "global", "posts.create", true),
PermissionService.NewPermissionNode("group:default", "global", "publishers.create", true), PermissionService.NewPermissionNode("group:default", "global", "publishers.create", true),
PermissionService.NewPermissionNode("group:default", "global", "files.create", true), PermissionService.NewPermissionNode("group:default", "global", "files.create", true),
PermissionService.NewPermissionNode("group:default", "global", "chatrooms.create", true) PermissionService.NewPermissionNode("group:default", "global", "chat.create", true)
} }
}); });
await context.SaveChangesAsync(cancellationToken); await context.SaveChangesAsync(cancellationToken);
@ -161,7 +163,7 @@ public class AppDatabase(
.HasMany(p => p.Collections) .HasMany(p => p.Collections)
.WithMany(c => c.Posts) .WithMany(c => c.Posts)
.UsingEntity(j => j.ToTable("post_collection_links")); .UsingEntity(j => j.ToTable("post_collection_links"));
modelBuilder.Entity<Realm.RealmMember>() modelBuilder.Entity<Realm.RealmMember>()
.HasKey(pm => new { pm.RealmId, pm.AccountId }); .HasKey(pm => new { pm.RealmId, pm.AccountId });
modelBuilder.Entity<Realm.RealmMember>() modelBuilder.Entity<Realm.RealmMember>()
@ -174,9 +176,11 @@ public class AppDatabase(
.WithMany() .WithMany()
.HasForeignKey(pm => pm.AccountId) .HasForeignKey(pm => pm.AccountId)
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Chat.ChatMember>() modelBuilder.Entity<Chat.ChatMember>()
.HasKey(pm => new { pm.ChatRoomId, pm.AccountId }); .HasKey(pm => new { pm.Id });
modelBuilder.Entity<Chat.ChatMember>()
.HasAlternateKey(pm => new { pm.ChatRoomId, pm.AccountId });
modelBuilder.Entity<Chat.ChatMember>() modelBuilder.Entity<Chat.ChatMember>()
.HasOne(pm => pm.ChatRoom) .HasOne(pm => pm.ChatRoom)
.WithMany(p => p.Members) .WithMany(p => p.Members)
@ -187,6 +191,8 @@ public class AppDatabase(
.WithMany() .WithMany()
.HasForeignKey(pm => pm.AccountId) .HasForeignKey(pm => pm.AccountId)
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Chat.MessageStatus>()
.HasKey(e => new { e.MessageId, e.SenderId });
// Automatically apply soft-delete filter to all entities inheriting BaseModel // Automatically apply soft-delete filter to all entities inheriting BaseModel
foreach (var entityType in modelBuilder.Model.GetEntityTypes()) foreach (var entityType in modelBuilder.Model.GetEntityTypes())

View File

@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("/chat")]
public class ChatController : ControllerBase
{
public class MarkMessageReadRequest
{
public Guid MessageId { get; set; }
public long ChatRoomId { get; set; }
}
}

View File

@ -37,6 +37,7 @@ public enum ChatMemberRole
public class ChatMember : ModelBase public class ChatMember : ModelBase
{ {
public Guid Id { get; set; }
public long ChatRoomId { get; set; } public long ChatRoomId { get; set; }
[JsonIgnore] public ChatRoom ChatRoom { get; set; } = null!; [JsonIgnore] public ChatRoom ChatRoom { get; set; } = null!;
public long AccountId { get; set; } public long AccountId { get; set; }

View File

@ -1,8 +1,10 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using DysonNetwork.Sphere.Permission;
using DysonNetwork.Sphere.Realm; using DysonNetwork.Sphere.Realm;
using DysonNetwork.Sphere.Storage; using DysonNetwork.Sphere.Storage;
using Microsoft.AspNetCore.Authorization;
namespace DysonNetwork.Sphere.Chat; namespace DysonNetwork.Sphere.Chat;
@ -17,6 +19,7 @@ public class ChatRoomController(AppDatabase db, FileService fs) : ControllerBase
.Where(c => c.Id == id) .Where(c => c.Id == id)
.Include(e => e.Picture) .Include(e => e.Picture)
.Include(e => e.Background) .Include(e => e.Background)
.Include(e => e.Realm)
.FirstOrDefaultAsync(); .FirstOrDefaultAsync();
if (chatRoom is null) return NotFound(); if (chatRoom is null) return NotFound();
return Ok(chatRoom); return Ok(chatRoom);
@ -51,6 +54,8 @@ public class ChatRoomController(AppDatabase db, FileService fs) : ControllerBase
} }
[HttpPost] [HttpPost]
[Authorize]
[RequiredPermission("global", "chat.create")]
public async Task<ActionResult<ChatRoom>> CreateChatRoom(ChatRoomRequest request) public async Task<ActionResult<ChatRoom>> CreateChatRoom(ChatRoomRequest request)
{ {
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized(); if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized();
@ -65,7 +70,8 @@ public class ChatRoomController(AppDatabase db, FileService fs) : ControllerBase
new() new()
{ {
Role = ChatMemberRole.Owner, Role = ChatMemberRole.Owner,
AccountId = currentUser.Id AccountId = currentUser.Id,
JoinedAt = NodaTime.Instant.FromDateTimeUtc(DateTime.UtcNow)
} }
} }
}; };
@ -105,7 +111,7 @@ public class ChatRoomController(AppDatabase db, FileService fs) : ControllerBase
return Ok(chatRoom); return Ok(chatRoom);
} }
[HttpPut("{id:long}")] [HttpPatch("{id:long}")]
public async Task<ActionResult<ChatRoom>> UpdateChatRoom(long id, [FromBody] ChatRoomRequest request) public async Task<ActionResult<ChatRoom>> UpdateChatRoom(long id, [FromBody] ChatRoomRequest request)
{ {
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized(); if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized();

View File

@ -0,0 +1,48 @@
using DysonNetwork.Sphere;
using DysonNetwork.Sphere.Chat;
using Microsoft.EntityFrameworkCore;
public class ChatService(AppDatabase db)
{
public async Task MarkMessageAsReadAsync(Guid messageId, long roomId, long userId)
{
var existingStatus = await db.ChatStatuses
.FirstOrDefaultAsync(x => x.MessageId == messageId && x.Sender.AccountId == userId);
var sender = await db.ChatMembers
.Where(m => m.AccountId == userId && m.ChatRoomId == roomId)
.FirstOrDefaultAsync();
if (sender is null) throw new ArgumentException("User is not a member of the chat room.");
if (existingStatus == null)
{
existingStatus = new MessageStatus
{
MessageId = messageId,
SenderId = sender.Id,
};
db.ChatStatuses.Add(existingStatus);
}
await db.SaveChangesAsync();
}
public async Task<bool> GetMessageReadStatus(Guid messageId, long userId)
{
return await db.ChatStatuses
.AnyAsync(x => x.MessageId == messageId && x.Sender.AccountId == userId);
}
public async Task<int> CountUnreadMessage(long userId, long chatRoomId)
{
var messages = await db.ChatMessages
.Where(m => m.ChatRoomId == chatRoomId)
.Select(m => new MessageStatusResponse
{
MessageId = m.Id,
IsRead = m.Statuses.Any(rs => rs.Sender.AccountId == userId)
})
.ToListAsync();
return messages.Count(m => !m.IsRead);
}
}

View File

@ -0,0 +1,67 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Net.Mail;
using System.Text.Json.Serialization;
using NodaTime;
namespace DysonNetwork.Sphere.Chat;
public class Message : ModelBase
{
public Guid Id { get; set; } = Guid.NewGuid();
[MaxLength(1024)] public string Type { get; set; } = null!;
[MaxLength(4096)] public string Content { get; set; } = string.Empty;
[Column(TypeName = "jsonb")] public Dictionary<string, object>? Meta { get; set; }
[Column(TypeName = "jsonb")] public List<Guid>? MembersMetioned { get; set; }
public Instant? EditedAt { get; set; }
public ICollection<Attachment> Attachments { get; set; } = new List<Attachment>();
public ICollection<MessageReaction> Reactions { get; set; } = new List<MessageReaction>();
public ICollection<MessageStatus> Statuses { get; set; } = new List<MessageStatus>();
public Guid? RepliedMessageId { get; set; }
public Message? RepliedMessage { get; set; }
public Guid? ForwardedMessageId { get; set; }
public Message? ForwardedMessage { get; set; }
public Guid SenderId { get; set; }
public ChatMember Sender { get; set; } = null!;
public long ChatRoomId { get; set; }
[JsonIgnore] public ChatRoom ChatRoom { get; set; } = null!;
}
public enum MessageReactionAttitude
{
Positive,
Neutral,
Negative,
}
public class MessageReaction : ModelBase
{
public Guid MessageId { get; set; }
[JsonIgnore] public Message Message { get; set; } = null!;
public Guid SenderId { get; set; }
public ChatMember Sender { get; set; } = null!;
[MaxLength(256)] public string Symbol { get; set; } = null!;
public MessageReactionAttitude Attitude { get; set; }
}
/// If the status is exist, means the user has read the message.
public class MessageStatus : ModelBase
{
public Guid MessageId { get; set; }
public Message Message { get; set; } = null!;
public Guid SenderId { get; set; }
public ChatMember Sender { get; set; } = null!;
public Instant ReadAt { get; set; }
}
[NotMapped]
public class MessageStatusResponse
{
public Guid MessageId { get; set; }
public bool IsRead { get; set; }
}

View File

@ -2,6 +2,7 @@ using System.Collections.Concurrent;
using System.Net.WebSockets; using System.Net.WebSockets;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Swashbuckle.AspNetCore.Annotations; using Swashbuckle.AspNetCore.Annotations;
namespace DysonNetwork.Sphere.Connection; namespace DysonNetwork.Sphere.Connection;
@ -52,7 +53,7 @@ public class WebSocketController(WebSocketService ws, ILogger<WebSocketContext>
try try
{ {
await _ConnectionEventLoop(connectionKey, webSocket, cts.Token); await _ConnectionEventLoop(deviceId, currentUser, webSocket, cts.Token);
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -67,11 +68,14 @@ public class WebSocketController(WebSocketService ws, ILogger<WebSocketContext>
} }
private async Task _ConnectionEventLoop( private async Task _ConnectionEventLoop(
(long AccountId, string DeviceId) connectionKey, string deviceId,
Account.Account currentUser,
WebSocket webSocket, WebSocket webSocket,
CancellationToken cancellationToken CancellationToken cancellationToken
) )
{ {
var connectionKey = (AccountId: currentUser.Id, DeviceId: deviceId);
var buffer = new byte[1024 * 4]; var buffer = new byte[1024 * 4];
try try
{ {
@ -85,9 +89,11 @@ public class WebSocketController(WebSocketService ws, ILogger<WebSocketContext>
new ArraySegment<byte>(buffer), new ArraySegment<byte>(buffer),
cancellationToken cancellationToken
); );
}
// TODO handle values var packet = WebSocketPacket.FromBytes(buffer[..receiveResult.Count]);
if (packet is null) continue;
ws.HandlePacket(currentUser, connectionKey.DeviceId, packet, webSocket);
}
} }
catch (OperationCanceledException) catch (OperationCanceledException)
{ {

View File

@ -0,0 +1,62 @@
using System.Text.Json;
public class WebSocketPacketType
{
public const string Error = "error";
}
public class WebSocketPacket
{
public string Type { get; set; } = null!;
public object Data { get; set; }
public string? ErrorMessage { get; set; }
/// <summary>
/// Creates a WebSocketPacket from raw WebSocket message bytes
/// </summary>
/// <param name="bytes">Raw WebSocket message bytes</param>
/// <returns>Deserialized WebSocketPacket</returns>
public static WebSocketPacket FromBytes(byte[] bytes)
{
var json = System.Text.Encoding.UTF8.GetString(bytes);
var jsonOpts = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
DictionaryKeyPolicy = JsonNamingPolicy.SnakeCaseLower,
};
return JsonSerializer.Deserialize<WebSocketPacket>(json, jsonOpts) ??
throw new JsonException("Failed to deserialize WebSocketPacket");
}
/// <summary>
/// Deserializes the Data property to the specified type T
/// </summary>
/// <typeparam name="T">Target type to deserialize to</typeparam>
/// <returns>Deserialized data of type T</returns>
public T? GetData<T>()
{
if (Data == null)
return default;
if (Data is T typedData)
return typedData;
return JsonSerializer.Deserialize<T>(
JsonSerializer.Serialize(Data)
);
}
/// <summary>
/// Serializes this WebSocketPacket to a byte array for sending over WebSocket
/// </summary>
/// <returns>Byte array representation of the packet</returns>
public byte[] ToBytes()
{
var jsonOpts = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
DictionaryKeyPolicy = JsonNamingPolicy.SnakeCaseLower,
};
var json = JsonSerializer.Serialize(this, jsonOpts);
return System.Text.Encoding.UTF8.GetBytes(json);
}
}

View File

@ -3,7 +3,7 @@ using System.Net.WebSockets;
namespace DysonNetwork.Sphere.Connection; namespace DysonNetwork.Sphere.Connection;
public class WebSocketService public class WebSocketService(ChatService cs)
{ {
public static readonly ConcurrentDictionary< public static readonly ConcurrentDictionary<
(long AccountId, string DeviceId), (long AccountId, string DeviceId),
@ -32,4 +32,41 @@ public class WebSocketService
data.Cts.Cancel(); data.Cts.Cancel();
ActiveConnections.TryRemove(key, out _); ActiveConnections.TryRemove(key, out _);
} }
public void HandlePacket(Account.Account currentUser, string deviceId, WebSocketPacket packet, WebSocket socket)
{
switch (packet.Type)
{
case "message.read":
var request = packet.GetData<ChatController.MarkMessageReadRequest>();
if (request is null)
{
socket.SendAsync(
new ArraySegment<byte>(new WebSocketPacket
{
Type = WebSocketPacketType.Error,
ErrorMessage = "Mark message as read requires you provide the ChatRoomId and MessageId"
}.ToBytes()),
WebSocketMessageType.Binary,
true,
CancellationToken.None
);
break;
}
_ = cs.MarkMessageAsReadAsync(request.MessageId, currentUser.Id, currentUser.Id).ConfigureAwait(false);
break;
default:
socket.SendAsync(
new ArraySegment<byte>(new WebSocketPacket
{
Type = WebSocketPacketType.Error,
ErrorMessage = $"Unprocessable packet: {packet.Type}"
}.ToBytes()),
WebSocketMessageType.Binary,
true,
CancellationToken.None
);
break;
}
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,51 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
using NodaTime;
#nullable disable
namespace DysonNetwork.Sphere.Migrations
{
/// <inheritdoc />
public partial class RealmAndChat : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Instant>(
name: "created_at",
table: "publisher_members",
type: "timestamp with time zone",
nullable: false,
defaultValue: NodaTime.Instant.FromUnixTimeTicks(0L));
migrationBuilder.AddColumn<Instant>(
name: "deleted_at",
table: "publisher_members",
type: "timestamp with time zone",
nullable: true);
migrationBuilder.AddColumn<Instant>(
name: "updated_at",
table: "publisher_members",
type: "timestamp with time zone",
nullable: false,
defaultValue: NodaTime.Instant.FromUnixTimeTicks(0L));
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "created_at",
table: "publisher_members");
migrationBuilder.DropColumn(
name: "deleted_at",
table: "publisher_members");
migrationBuilder.DropColumn(
name: "updated_at",
table: "publisher_members");
}
}
}

View File

@ -16,8 +16,8 @@ using NpgsqlTypes;
namespace DysonNetwork.Sphere.Migrations namespace DysonNetwork.Sphere.Migrations
{ {
[DbContext(typeof(AppDatabase))] [DbContext(typeof(AppDatabase))]
[Migration("20250502040651_RealmAndChat")] [Migration("20250502041309_InitialMigration")]
partial class RealmAndChat partial class InitialMigration
{ {
/// <inheritdoc /> /// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder) protected override void BuildTargetModel(ModelBuilder modelBuilder)

View File

@ -405,6 +405,52 @@ namespace DysonNetwork.Sphere.Migrations
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
}); });
migrationBuilder.CreateTable(
name: "chat_members",
columns: table => new
{
chat_room_id = table.Column<long>(type: "bigint", nullable: false),
account_id = table.Column<long>(type: "bigint", nullable: false),
role = table.Column<int>(type: "integer", nullable: false),
joined_at = table.Column<Instant>(type: "timestamp with time zone", nullable: true),
is_bot = table.Column<bool>(type: "boolean", nullable: false),
created_at = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
updated_at = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
deleted_at = table.Column<Instant>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("pk_chat_members", x => new { x.chat_room_id, x.account_id });
table.ForeignKey(
name: "fk_chat_members_accounts_account_id",
column: x => x.account_id,
principalTable: "accounts",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "chat_rooms",
columns: table => new
{
id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
name = table.Column<string>(type: "character varying(1024)", maxLength: 1024, nullable: false),
description = table.Column<string>(type: "character varying(4096)", maxLength: 4096, nullable: false),
type = table.Column<int>(type: "integer", nullable: false),
is_public = table.Column<bool>(type: "boolean", nullable: false),
picture_id = table.Column<string>(type: "character varying(128)", nullable: true),
background_id = table.Column<string>(type: "character varying(128)", nullable: true),
realm_id = table.Column<long>(type: "bigint", nullable: true),
created_at = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
updated_at = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
deleted_at = table.Column<Instant>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("pk_chat_rooms", x => x.id);
});
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "files", name: "files",
columns: table => new columns: table => new
@ -476,6 +522,47 @@ namespace DysonNetwork.Sphere.Migrations
principalColumn: "id"); principalColumn: "id");
}); });
migrationBuilder.CreateTable(
name: "realms",
columns: table => new
{
id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
slug = table.Column<string>(type: "character varying(1024)", maxLength: 1024, nullable: false),
name = table.Column<string>(type: "character varying(1024)", maxLength: 1024, nullable: false),
description = table.Column<string>(type: "character varying(4096)", maxLength: 4096, nullable: false),
verified_as = table.Column<string>(type: "character varying(4096)", maxLength: 4096, nullable: true),
verified_at = table.Column<Instant>(type: "timestamp with time zone", nullable: true),
is_community = table.Column<bool>(type: "boolean", nullable: false),
is_public = table.Column<bool>(type: "boolean", nullable: false),
picture_id = table.Column<string>(type: "character varying(128)", nullable: true),
background_id = table.Column<string>(type: "character varying(128)", nullable: true),
account_id = table.Column<long>(type: "bigint", nullable: false),
created_at = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
updated_at = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
deleted_at = table.Column<Instant>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("pk_realms", x => x.id);
table.ForeignKey(
name: "fk_realms_accounts_account_id",
column: x => x.account_id,
principalTable: "accounts",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_realms_files_background_id",
column: x => x.background_id,
principalTable: "files",
principalColumn: "id");
table.ForeignKey(
name: "fk_realms_files_picture_id",
column: x => x.picture_id,
principalTable: "files",
principalColumn: "id");
});
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "post_collections", name: "post_collections",
columns: table => new columns: table => new
@ -588,6 +675,35 @@ namespace DysonNetwork.Sphere.Migrations
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
}); });
migrationBuilder.CreateTable(
name: "realm_members",
columns: table => new
{
realm_id = table.Column<long>(type: "bigint", nullable: false),
account_id = table.Column<long>(type: "bigint", nullable: false),
role = table.Column<int>(type: "integer", nullable: false),
joined_at = table.Column<Instant>(type: "timestamp with time zone", nullable: true),
created_at = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
updated_at = table.Column<Instant>(type: "timestamp with time zone", nullable: false),
deleted_at = table.Column<Instant>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("pk_realm_members", x => new { x.realm_id, x.account_id });
table.ForeignKey(
name: "fk_realm_members_accounts_account_id",
column: x => x.account_id,
principalTable: "accounts",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "fk_realm_members_realms_realm_id",
column: x => x.realm_id,
principalTable: "realms",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "post_category_links", name: "post_category_links",
columns: table => new columns: table => new
@ -742,6 +858,26 @@ namespace DysonNetwork.Sphere.Migrations
table: "auth_sessions", table: "auth_sessions",
column: "challenge_id"); column: "challenge_id");
migrationBuilder.CreateIndex(
name: "ix_chat_members_account_id",
table: "chat_members",
column: "account_id");
migrationBuilder.CreateIndex(
name: "ix_chat_rooms_background_id",
table: "chat_rooms",
column: "background_id");
migrationBuilder.CreateIndex(
name: "ix_chat_rooms_picture_id",
table: "chat_rooms",
column: "picture_id");
migrationBuilder.CreateIndex(
name: "ix_chat_rooms_realm_id",
table: "chat_rooms",
column: "realm_id");
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "ix_files_account_id", name: "ix_files_account_id",
table: "files", table: "files",
@ -878,6 +1014,32 @@ namespace DysonNetwork.Sphere.Migrations
table: "publishers", table: "publishers",
column: "picture_id"); column: "picture_id");
migrationBuilder.CreateIndex(
name: "ix_realm_members_account_id",
table: "realm_members",
column: "account_id");
migrationBuilder.CreateIndex(
name: "ix_realms_account_id",
table: "realms",
column: "account_id");
migrationBuilder.CreateIndex(
name: "ix_realms_background_id",
table: "realms",
column: "background_id");
migrationBuilder.CreateIndex(
name: "ix_realms_picture_id",
table: "realms",
column: "picture_id");
migrationBuilder.CreateIndex(
name: "ix_realms_slug",
table: "realms",
column: "slug",
unique: true);
migrationBuilder.AddForeignKey( migrationBuilder.AddForeignKey(
name: "fk_account_profiles_files_background_id", name: "fk_account_profiles_files_background_id",
table: "account_profiles", table: "account_profiles",
@ -892,6 +1054,35 @@ namespace DysonNetwork.Sphere.Migrations
principalTable: "files", principalTable: "files",
principalColumn: "id"); principalColumn: "id");
migrationBuilder.AddForeignKey(
name: "fk_chat_members_chat_rooms_chat_room_id",
table: "chat_members",
column: "chat_room_id",
principalTable: "chat_rooms",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "fk_chat_rooms_files_background_id",
table: "chat_rooms",
column: "background_id",
principalTable: "files",
principalColumn: "id");
migrationBuilder.AddForeignKey(
name: "fk_chat_rooms_files_picture_id",
table: "chat_rooms",
column: "picture_id",
principalTable: "files",
principalColumn: "id");
migrationBuilder.AddForeignKey(
name: "fk_chat_rooms_realms_realm_id",
table: "chat_rooms",
column: "realm_id",
principalTable: "realms",
principalColumn: "id");
migrationBuilder.AddForeignKey( migrationBuilder.AddForeignKey(
name: "fk_files_posts_post_id", name: "fk_files_posts_post_id",
table: "files", table: "files",
@ -937,6 +1128,9 @@ namespace DysonNetwork.Sphere.Migrations
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "auth_sessions"); name: "auth_sessions");
migrationBuilder.DropTable(
name: "chat_members");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "magic_spells"); name: "magic_spells");
@ -967,9 +1161,15 @@ namespace DysonNetwork.Sphere.Migrations
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "publisher_members"); name: "publisher_members");
migrationBuilder.DropTable(
name: "realm_members");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "auth_challenges"); name: "auth_challenges");
migrationBuilder.DropTable(
name: "chat_rooms");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "permission_groups"); name: "permission_groups");
@ -982,6 +1182,9 @@ namespace DysonNetwork.Sphere.Migrations
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "post_tags"); name: "post_tags");
migrationBuilder.DropTable(
name: "realms");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "accounts"); name: "accounts");

View File

@ -59,7 +59,7 @@ public class PostService(AppDatabase db, FileService fs, ActivityService act)
break; break;
} }
using var newDocument = JsonDocument.Parse(JsonSerializer.Serialize(truncatedArrayElements)); var newDocument = JsonDocument.Parse(JsonSerializer.Serialize(truncatedArrayElements));
item.Content = newDocument; item.Content = newDocument;
} }

View File

@ -9,9 +9,11 @@ using DysonNetwork.Sphere;
using DysonNetwork.Sphere.Account; using DysonNetwork.Sphere.Account;
using DysonNetwork.Sphere.Activity; using DysonNetwork.Sphere.Activity;
using DysonNetwork.Sphere.Auth; using DysonNetwork.Sphere.Auth;
using DysonNetwork.Sphere.Chat;
using DysonNetwork.Sphere.Connection; using DysonNetwork.Sphere.Connection;
using DysonNetwork.Sphere.Permission; using DysonNetwork.Sphere.Permission;
using DysonNetwork.Sphere.Post; using DysonNetwork.Sphere.Post;
using DysonNetwork.Sphere.Realm;
using DysonNetwork.Sphere.Storage; using DysonNetwork.Sphere.Storage;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.HttpOverrides;
@ -128,6 +130,8 @@ builder.Services.AddScoped<FileService>();
builder.Services.AddScoped<PublisherService>(); builder.Services.AddScoped<PublisherService>();
builder.Services.AddScoped<ActivityService>(); builder.Services.AddScoped<ActivityService>();
builder.Services.AddScoped<PostService>(); builder.Services.AddScoped<PostService>();
builder.Services.AddScoped<RealmService>();
builder.Services.AddScoped<ChatRoomService>();
// Timed task // Timed task

View File

@ -9,7 +9,7 @@ namespace DysonNetwork.Sphere.Realm;
[Route("/realm/{slug}")] [Route("/realm/{slug}")]
public class RealmChatController(AppDatabase db) : ControllerBase public class RealmChatController(AppDatabase db) : ControllerBase
{ {
[HttpGet("/chat")] [HttpGet("chat")]
[Authorize] [Authorize]
public async Task<ActionResult<List<ChatRoom>>> ListRealmChat(string slug) public async Task<ActionResult<List<ChatRoom>>> ListRealmChat(string slug)
{ {

View File

@ -167,8 +167,8 @@ public class RealmController(AppDatabase db, RealmService rs, FileService fs) :
public async Task<ActionResult<Realm>> CreateRealm(RealmRequest request) public async Task<ActionResult<Realm>> CreateRealm(RealmRequest request)
{ {
if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized(); if (HttpContext.Items["CurrentUser"] is not Account.Account currentUser) return Unauthorized();
if (request.Name is null) return BadRequest("You cannot create a realm without a name."); if (string.IsNullOrWhiteSpace(request.Name)) return BadRequest("You cannot create a realm without a name.");
if (request.Slug is null) return BadRequest("You cannot create a realm without a slug."); if (string.IsNullOrWhiteSpace(request.Slug)) return BadRequest("You cannot create a realm without a slug.");
var slugExists = await db.Realms.AnyAsync(r => r.Slug == request.Slug); var slugExists = await db.Realms.AnyAsync(r => r.Slug == request.Slug);
if (slugExists) return BadRequest("Realm with this slug already exists."); if (slugExists) return BadRequest("Realm with this slug already exists.");
@ -186,7 +186,8 @@ public class RealmController(AppDatabase db, RealmService rs, FileService fs) :
new() new()
{ {
Role = RealmMemberRole.Owner, Role = RealmMemberRole.Owner,
AccountId = currentUser.Id AccountId = currentUser.Id,
JoinedAt = NodaTime.Instant.FromDateTimeUtc(DateTime.UtcNow)
} }
} }
}; };
@ -212,7 +213,7 @@ public class RealmController(AppDatabase db, RealmService rs, FileService fs) :
return Ok(realm); return Ok(realm);
} }
[HttpPut("{slug}")] [HttpPatch("{slug}")]
[Authorize] [Authorize]
public async Task<ActionResult<Realm>> Update(string slug, [FromBody] RealmRequest request) public async Task<ActionResult<Realm>> Update(string slug, [FromBody] RealmRequest request)
{ {

View File

@ -15,7 +15,7 @@ public class FileController(
) : ControllerBase ) : ControllerBase
{ {
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<ActionResult> OpenFile(string id) public async Task<ActionResult> OpenFile(string id, [FromQuery] bool original = false)
{ {
var file = await db.Files.FindAsync(id); var file = await db.Files.FindAsync(id);
if (file is null) return NotFound(); if (file is null) return NotFound();
@ -29,12 +29,18 @@ public class FileController(
} }
var dest = fs.GetRemoteStorageConfig(file.UploadedTo); var dest = fs.GetRemoteStorageConfig(file.UploadedTo);
var fileName = file.Id;
if (!original && file.HasCompression)
{
fileName += ".compressed";
}
if (dest.ImageProxy is not null && (file.MimeType?.StartsWith("image/") ?? false)) if (dest.ImageProxy is not null && (file.MimeType?.StartsWith("image/") ?? false))
{ {
var proxyUrl = dest.ImageProxy; var proxyUrl = dest.ImageProxy;
var baseUri = new Uri(proxyUrl.EndsWith('/') ? proxyUrl : $"{proxyUrl}/"); var baseUri = new Uri(proxyUrl.EndsWith('/') ? proxyUrl : $"{proxyUrl}/");
var fullUri = new Uri(baseUri, file.Id); var fullUri = new Uri(baseUri, fileName);
return Redirect(fullUri.ToString()); return Redirect(fullUri.ToString());
} }
@ -42,7 +48,7 @@ public class FileController(
{ {
var proxyUrl = dest.AccessProxy; var proxyUrl = dest.AccessProxy;
var baseUri = new Uri(proxyUrl.EndsWith('/') ? proxyUrl : $"{proxyUrl}/"); var baseUri = new Uri(proxyUrl.EndsWith('/') ? proxyUrl : $"{proxyUrl}/");
var fullUri = new Uri(baseUri, file.Id); var fullUri = new Uri(baseUri, fileName);
return Redirect(fullUri.ToString()); return Redirect(fullUri.ToString());
} }
@ -67,7 +73,7 @@ public class FileController(
// Fallback redirect to the S3 endpoint (public read) // Fallback redirect to the S3 endpoint (public read)
var protocol = dest.EnableSsl ? "https" : "http"; var protocol = dest.EnableSsl ? "https" : "http";
// Use the path bucket lookup mode // Use the path bucket lookup mode
return Redirect($"{protocol}://{dest.Endpoint}/{dest.Bucket}/{file.Id}"); return Redirect($"{protocol}://{dest.Endpoint}/{dest.Bucket}/{fileName}");
} }
[HttpGet("{id}/info")] [HttpGet("{id}/info")]