Add feature to delete uploaded files with uploader and admin permissions

This commit is contained in:
tyuXX 2026-10-31 16:45:58 +03:00
parent 7cc9ba7f4d
commit 45629b122e
16 changed files with 587 additions and 8 deletions

View file

@ -25,6 +25,7 @@ public class ChatWebSocketManager
private readonly ServerOptions _options;
private readonly ILogger<ChatWebSocketManager> _logger;
private readonly WebPushService? _webPush;
private readonly FileStorageService _fileService;
// Extensibility hooks for mod system
public Func<ChatMessage, Task<ChatMessage?>>? MessagePipelineInterceptor { get; set; }
@ -35,12 +36,14 @@ public class ChatWebSocketManager
ChatDatabase db,
ServerOptions options,
ILogger<ChatWebSocketManager> logger,
WebPushService? webPush = null)
WebPushService? webPush = null,
FileStorageService? fileStorage = null)
{
_db = db;
_options = options;
_logger = logger;
_webPush = webPush;
_fileService = fileStorage ?? new FileStorageService(db, options);
}
public int ConnectedCount => _clients.Count;
@ -234,6 +237,14 @@ public class ChatWebSocketManager
}
break;
case MessageTypes.DeleteFile:
var delFilePkg = envelope.Unpack<DeleteFilePacket>();
if (delFilePkg != null && !string.IsNullOrWhiteSpace(delFilePkg.FileId))
{
await HandleDeleteFileAsync(client, delFilePkg.FileId, ct);
}
break;
case MessageTypes.StartDm:
var dmPkg = envelope.Unpack<StartDmPacket>();
if (dmPkg != null)
@ -904,6 +915,29 @@ public class ChatWebSocketManager
await BroadcastSystemNoticeAsync($"Channel #{InputSanitizer.SanitizeChannelName(channel.Name)} was deleted.", "Warning");
}
private async Task HandleDeleteFileAsync(ConnectedClient client, string fileId, CancellationToken ct)
{
var record = await _fileService.GetFileRecordAsync(fileId);
if (record == null)
{
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "File not found." }, ct);
return;
}
bool isUploader = string.Equals(client.User.Id, record.UploaderId, StringComparison.OrdinalIgnoreCase) ||
string.Equals(client.User.Username, record.UploaderUsername, StringComparison.OrdinalIgnoreCase);
bool isAdmin = client.User.Role == UserRoles.Owner || client.User.Role == UserRoles.Admin;
if (!isUploader && !isAdmin)
{
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You do not have permission to delete this file. Only the uploader or an Admin can delete it." }, ct);
return;
}
await _fileService.DeleteFileAsync(fileId);
await BroadcastFileDeletedAsync(record, client.User.Username);
}
private async Task HandleCommandAsync(ConnectedClient client, ExecuteCommandPacket packet, CancellationToken ct)
{
string cmd = (packet.Command ?? string.Empty).TrimStart('/').ToLowerInvariant();
@ -945,6 +979,7 @@ public class ChatWebSocketManager
" /follow [channel] - Follow/unfollow a conversation for Inbox notifications\n" +
" /inbox [readall|clear] - Manage Inbox notifications & preferences\n" +
" /announce <message> - Broadcast an official announcement (Admin/Owner)\n" +
" /deletefile <file_id> - Delete an uploaded file (Uploader or Admin)\n" +
" /users - List all registered users\n" +
" /motd - Display message of the day";
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = helpText, ChannelId = packet.ChannelId }, ct);
@ -982,6 +1017,55 @@ public class ChatWebSocketManager
}, ct);
break;
case "deletefile":
if (string.IsNullOrWhiteSpace(packet.Args))
{
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
{
Success = false,
Output = "Usage: /deletefile <file_id>",
ChannelId = packet.ChannelId
}, ct);
break;
}
string targetFileId = packet.Args.Trim();
var fileRec = await _fileService.GetFileRecordAsync(targetFileId);
if (fileRec == null)
{
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
{
Success = false,
Output = $"File '{targetFileId}' not found.",
ChannelId = packet.ChannelId
}, ct);
break;
}
bool canDel = string.Equals(client.User.Id, fileRec.UploaderId, StringComparison.OrdinalIgnoreCase) ||
string.Equals(client.User.Username, fileRec.UploaderUsername, StringComparison.OrdinalIgnoreCase) ||
client.User.Role == UserRoles.Owner || client.User.Role == UserRoles.Admin;
if (!canDel)
{
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
{
Success = false,
Output = "You do not have permission to delete this file. Only the uploader or an Admin/Owner can delete it.",
ChannelId = packet.ChannelId
}, ct);
break;
}
await _fileService.DeleteFileAsync(fileRec.Id);
await BroadcastFileDeletedAsync(fileRec, client.User.Username);
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
{
Success = true,
Output = $"File '{fileRec.OriginalFileName}' was deleted successfully.",
ChannelId = packet.ChannelId
}, ct);
break;
case "follow":
case "unfollow":
case "mute":
@ -1327,6 +1411,36 @@ public class ChatWebSocketManager
}
}
public async Task BroadcastFileDeletedAsync(FileRecord file, string? deletedByUsername = null)
{
var channel = await _db.GetChannelByIdAsync(file.ChannelId);
bool isPrivateConv = channel != null && (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group);
if (isPrivateConv)
{
var memberSet = new HashSet<string>(channel!.MemberIds, StringComparer.OrdinalIgnoreCase);
await Task.WhenAll(_clients.Values
.Where(c => memberSet.Contains(c.User.Id))
.Select(c => SendFileListToClientAsync(c)));
}
else
{
await Task.WhenAll(_clients.Values.Select(c => SendFileListToClientAsync(c)));
}
string deleterInfo = !string.IsNullOrWhiteSpace(deletedByUsername) ? $" by @{InputSanitizer.SanitizeUsername(deletedByUsername)}" : "";
string noticeText = $"File '{file.OriginalFileName}' was deleted{deleterInfo}.";
if (isPrivateConv)
{
await BroadcastToMembersAsync(channel!.MemberIds, MessageTypes.SystemNotice, new SystemNoticePacket { Text = noticeText, Level = "Warning" });
}
else
{
await BroadcastToChannelAsync(file.ChannelId, MessageTypes.SystemNotice, new SystemNoticePacket { Text = noticeText, Level = "Warning" });
}
}
#region Inbox & Notification Processing
public async Task SendInboxSyncToClientAsync(ConnectedClient client, CancellationToken ct = default)