Add feature to delete uploaded files with uploader and admin permissions
This commit is contained in:
parent
7cc9ba7f4d
commit
45629b122e
16 changed files with 587 additions and 8 deletions
|
|
@ -928,6 +928,42 @@ public class ChatClientConnection : IDisposable
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<bool> DeleteFileAsync(string fileId)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var req = new HttpRequestMessage(HttpMethod.Delete, $"/api/files/{fileId}");
|
||||||
|
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _state.Token);
|
||||||
|
|
||||||
|
var res = await _httpClient.SendAsync(req);
|
||||||
|
if (res.IsSuccessStatusCode)
|
||||||
|
{
|
||||||
|
_state.SetStatus("File deleted successfully!", 4);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
string errText = await res.Content.ReadAsStringAsync();
|
||||||
|
_state.SetStatus($"Delete failed: {res.StatusCode} - {errText}", 5);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_state.SetStatus($"Delete error: {ex.Message}", 5);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task SendDeleteFilePacketAsync(string fileId)
|
||||||
|
{
|
||||||
|
var envelope = NetworkEnvelope.Create(MessageTypes.DeleteFile, new DeleteFilePacket
|
||||||
|
{
|
||||||
|
FileId = fileId
|
||||||
|
});
|
||||||
|
return SendEnvelopeAsync(envelope);
|
||||||
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
_cts?.Cancel();
|
_cts?.Cancel();
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,7 @@ public class FilesScreen : IScreen
|
||||||
|
|
||||||
public void Render(int width, int height, StringBuilder sb)
|
public void Render(int width, int height, StringBuilder sb)
|
||||||
{
|
{
|
||||||
sb.AppendLine($" {Ansi.Bold}{Ansi.Cyan}Shared Files Browser{Ansi.Reset} {Ansi.Gray}(Press 'D' to download, 'U' to upload){Ansi.Reset}");
|
sb.AppendLine($" {Ansi.Bold}{Ansi.Cyan}Shared Files Browser{Ansi.Reset} {Ansi.Gray}(Press 'D' to download, 'U' to upload, 'X'/'Del' to delete){Ansi.Reset}");
|
||||||
sb.AppendLine(new string('─', Math.Max(0, width - 1)));
|
sb.AppendLine(new string('─', Math.Max(0, width - 1)));
|
||||||
|
|
||||||
if (_state.Files.Count == 0)
|
if (_state.Files.Count == 0)
|
||||||
|
|
@ -48,7 +48,13 @@ public class FilesScreen : IScreen
|
||||||
string sizeStr = FormatBytes(f.FileSizeBytes);
|
string sizeStr = FormatBytes(f.FileSizeBytes);
|
||||||
string dateStr = f.CreatedAt.ToLocalTime().ToString("yyyy-MM-dd HH:mm");
|
string dateStr = f.CreatedAt.ToLocalTime().ToString("yyyy-MM-dd HH:mm");
|
||||||
|
|
||||||
string fileText = $"{f.OriginalFileName} ({sizeStr}) by @{f.UploaderUsername} [{dateStr}]";
|
bool canDelete = _state.CurrentUserRole == GsDChat.Core.Models.UserRoles.Admin ||
|
||||||
|
_state.CurrentUserRole == GsDChat.Core.Models.UserRoles.Owner ||
|
||||||
|
(!string.IsNullOrEmpty(f.UploaderId) && string.Equals(f.UploaderId, _state.CurrentUserId, StringComparison.OrdinalIgnoreCase)) ||
|
||||||
|
string.Equals(f.UploaderUsername, _state.CurrentUsername, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
string deleteBadge = canDelete ? $" {Ansi.BrightRed}[Del]{Ansi.Reset}" : "";
|
||||||
|
string fileText = $"{f.OriginalFileName} ({sizeStr}) by @{f.UploaderUsername} [{dateStr}]{deleteBadge}";
|
||||||
|
|
||||||
if (isSelected)
|
if (isSelected)
|
||||||
{
|
{
|
||||||
|
|
@ -69,7 +75,7 @@ public class FilesScreen : IScreen
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
sb.AppendLine($" {Ansi.Gray}[↑/↓] Navigate [D] Download Selected [U] Upload Local File{Ansi.Reset}");
|
sb.AppendLine($" {Ansi.Gray}[↑/↓] Navigate [D] Download Selected [U] Upload Local File [X/Del] Delete Selected{Ansi.Reset}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -139,6 +145,32 @@ public class FilesScreen : IScreen
|
||||||
_state.NeedsRedraw = true;
|
_state.NeedsRedraw = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
else if (key.Key == ConsoleKey.X || key.Key == ConsoleKey.Delete)
|
||||||
|
{
|
||||||
|
if (_selectedIndex >= 0 && _selectedIndex < _state.Files.Count)
|
||||||
|
{
|
||||||
|
var selected = _state.Files[_selectedIndex];
|
||||||
|
bool canDelete = _state.CurrentUserRole == GsDChat.Core.Models.UserRoles.Admin ||
|
||||||
|
_state.CurrentUserRole == GsDChat.Core.Models.UserRoles.Owner ||
|
||||||
|
(!string.IsNullOrEmpty(selected.UploaderId) && string.Equals(selected.UploaderId, _state.CurrentUserId, StringComparison.OrdinalIgnoreCase)) ||
|
||||||
|
string.Equals(selected.UploaderUsername, _state.CurrentUsername, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
if (!canDelete)
|
||||||
|
{
|
||||||
|
_state.SetStatus("Permission denied: You can only delete files you uploaded or if you are an admin.", 4);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_state.SetStatus($"Deleting {selected.OriginalFileName}...");
|
||||||
|
bool success = await _connection.DeleteFileAsync(selected.Id);
|
||||||
|
if (success)
|
||||||
|
{
|
||||||
|
_state.RemoveFile(selected.Id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_state.NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
else if (key.Key == ConsoleKey.U)
|
else if (key.Key == ConsoleKey.U)
|
||||||
{
|
{
|
||||||
_isUploading = true;
|
_isUploading = true;
|
||||||
|
|
|
||||||
|
|
@ -444,6 +444,15 @@ public class ClientState
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void RemoveFile(string fileId)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
Files.RemoveAll(f => f.Id == fileId);
|
||||||
|
NeedsRedraw = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public void SetInboxSync(List<InboxItem> items, int unreadCount, InboxPreferences? preferences = null)
|
public void SetInboxSync(List<InboxItem> items, int unreadCount, InboxPreferences? preferences = null)
|
||||||
{
|
{
|
||||||
lock (_lock)
|
lock (_lock)
|
||||||
|
|
|
||||||
|
|
@ -70,3 +70,10 @@ public class UploadFileResponse
|
||||||
public string? ChannelId { get; set; }
|
public string? ChannelId { get; set; }
|
||||||
public string? ErrorMessage { get; set; }
|
public string? ErrorMessage { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class DeleteFileResponse
|
||||||
|
{
|
||||||
|
public bool Success { get; set; }
|
||||||
|
public string? FileId { get; set; }
|
||||||
|
public string? ErrorMessage { get; set; }
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -26,6 +26,7 @@ public static class MessageTypes
|
||||||
public const string FetchHistory = "FETCH_HISTORY";
|
public const string FetchHistory = "FETCH_HISTORY";
|
||||||
public const string UserListSync = "USER_LIST_SYNC";
|
public const string UserListSync = "USER_LIST_SYNC";
|
||||||
public const string FileListSync = "FILE_LIST_SYNC";
|
public const string FileListSync = "FILE_LIST_SYNC";
|
||||||
|
public const string DeleteFile = "DELETE_FILE";
|
||||||
public const string SystemNotice = "SYSTEM_NOTICE";
|
public const string SystemNotice = "SYSTEM_NOTICE";
|
||||||
public const string Error = "ERROR";
|
public const string Error = "ERROR";
|
||||||
public const string ExecuteCommand = "EXECUTE_COMMAND";
|
public const string ExecuteCommand = "EXECUTE_COMMAND";
|
||||||
|
|
@ -204,9 +205,15 @@ public class FileSummary
|
||||||
public string ContentType { get; set; } = string.Empty;
|
public string ContentType { get; set; } = string.Empty;
|
||||||
public long FileSizeBytes { get; set; }
|
public long FileSizeBytes { get; set; }
|
||||||
public string UploaderUsername { get; set; } = string.Empty;
|
public string UploaderUsername { get; set; } = string.Empty;
|
||||||
|
public string UploaderId { get; set; } = string.Empty;
|
||||||
public System.DateTime CreatedAt { get; set; }
|
public System.DateTime CreatedAt { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class DeleteFilePacket
|
||||||
|
{
|
||||||
|
public string FileId { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
public class FileListSyncPacket
|
public class FileListSyncPacket
|
||||||
{
|
{
|
||||||
public List<FileSummary> Files { get; set; } = new();
|
public List<FileSummary> Files { get; set; } = new();
|
||||||
|
|
|
||||||
|
|
@ -10,9 +10,11 @@ public interface IModEventBus
|
||||||
void SubscribeUserDisconnected(Func<User, Task> handler);
|
void SubscribeUserDisconnected(Func<User, Task> handler);
|
||||||
void SubscribeChannelCreated(Func<Channel, Task> handler);
|
void SubscribeChannelCreated(Func<Channel, Task> handler);
|
||||||
void SubscribeFileUploaded(Func<FileRecord, Task> handler);
|
void SubscribeFileUploaded(Func<FileRecord, Task> handler);
|
||||||
|
void SubscribeFileDeleted(Func<FileRecord, Task> handler);
|
||||||
|
|
||||||
Task PublishUserConnectedAsync(User user);
|
Task PublishUserConnectedAsync(User user);
|
||||||
Task PublishUserDisconnectedAsync(User user);
|
Task PublishUserDisconnectedAsync(User user);
|
||||||
Task PublishChannelCreatedAsync(Channel channel);
|
Task PublishChannelCreatedAsync(Channel channel);
|
||||||
Task PublishFileUploadedAsync(FileRecord file);
|
Task PublishFileUploadedAsync(FileRecord file);
|
||||||
|
Task PublishFileDeletedAsync(FileRecord file);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,11 +11,13 @@ public class ModEventBus : IModEventBus
|
||||||
private readonly List<Func<User, Task>> _userDisconnectedHandlers = new();
|
private readonly List<Func<User, Task>> _userDisconnectedHandlers = new();
|
||||||
private readonly List<Func<Channel, Task>> _channelCreatedHandlers = new();
|
private readonly List<Func<Channel, Task>> _channelCreatedHandlers = new();
|
||||||
private readonly List<Func<FileRecord, Task>> _fileUploadedHandlers = new();
|
private readonly List<Func<FileRecord, Task>> _fileUploadedHandlers = new();
|
||||||
|
private readonly List<Func<FileRecord, Task>> _fileDeletedHandlers = new();
|
||||||
|
|
||||||
public void SubscribeUserConnected(Func<User, Task> handler) => _userConnectedHandlers.Add(handler);
|
public void SubscribeUserConnected(Func<User, Task> handler) => _userConnectedHandlers.Add(handler);
|
||||||
public void SubscribeUserDisconnected(Func<User, Task> handler) => _userDisconnectedHandlers.Add(handler);
|
public void SubscribeUserDisconnected(Func<User, Task> handler) => _userDisconnectedHandlers.Add(handler);
|
||||||
public void SubscribeChannelCreated(Func<Channel, Task> handler) => _channelCreatedHandlers.Add(handler);
|
public void SubscribeChannelCreated(Func<Channel, Task> handler) => _channelCreatedHandlers.Add(handler);
|
||||||
public void SubscribeFileUploaded(Func<FileRecord, Task> handler) => _fileUploadedHandlers.Add(handler);
|
public void SubscribeFileUploaded(Func<FileRecord, Task> handler) => _fileUploadedHandlers.Add(handler);
|
||||||
|
public void SubscribeFileDeleted(Func<FileRecord, Task> handler) => _fileDeletedHandlers.Add(handler);
|
||||||
|
|
||||||
public async Task PublishUserConnectedAsync(User user)
|
public async Task PublishUserConnectedAsync(User user)
|
||||||
{
|
{
|
||||||
|
|
@ -48,4 +50,12 @@ public class ModEventBus : IModEventBus
|
||||||
try { await h(file); } catch { }
|
try { await h(file); } catch { }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task PublishFileDeletedAsync(FileRecord file)
|
||||||
|
{
|
||||||
|
foreach (var h in _fileDeletedHandlers)
|
||||||
|
{
|
||||||
|
try { await h(file); } catch { }
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1307,7 +1307,7 @@ public class ChatDatabase : IDisposable
|
||||||
using var conn = CreateConnection();
|
using var conn = CreateConnection();
|
||||||
using var cmd = conn.CreateCommand();
|
using var cmd = conn.CreateCommand();
|
||||||
cmd.CommandText = """
|
cmd.CommandText = """
|
||||||
SELECT id, channel_id, original_name, content_type, size_bytes, uploader_username, created_at
|
SELECT id, channel_id, original_name, content_type, size_bytes, uploader_username, created_at, uploader_id
|
||||||
FROM files
|
FROM files
|
||||||
ORDER BY created_at DESC
|
ORDER BY created_at DESC
|
||||||
LIMIT @limit;
|
LIMIT @limit;
|
||||||
|
|
@ -1325,12 +1325,26 @@ public class ChatDatabase : IDisposable
|
||||||
ContentType = reader.GetString(3),
|
ContentType = reader.GetString(3),
|
||||||
FileSizeBytes = reader.GetInt64(4),
|
FileSizeBytes = reader.GetInt64(4),
|
||||||
UploaderUsername = reader.GetString(5),
|
UploaderUsername = reader.GetString(5),
|
||||||
CreatedAt = DateTime.Parse(reader.GetString(6))
|
CreatedAt = DateTime.Parse(reader.GetString(6)),
|
||||||
|
UploaderId = reader.IsDBNull(7) ? string.Empty : reader.GetString(7)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return files;
|
return files;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<bool> DeleteFileRecordAsync(string fileId)
|
||||||
|
{
|
||||||
|
using var conn = CreateConnection();
|
||||||
|
using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = """
|
||||||
|
DELETE FROM files WHERE id = @id;
|
||||||
|
DELETE FROM messages WHERE attachment_id = @id;
|
||||||
|
""";
|
||||||
|
cmd.Parameters.AddWithValue("@id", fileId);
|
||||||
|
int rows = await cmd.ExecuteNonQueryAsync();
|
||||||
|
return rows > 0;
|
||||||
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Inbox, Preferences & Push Subscription Operations
|
#region Inbox, Preferences & Push Subscription Operations
|
||||||
|
|
|
||||||
|
|
@ -421,6 +421,51 @@ app.MapGet("/api/files/{id}", async (string id, HttpRequest req, IAuthService au
|
||||||
return Results.File(stream, record.ContentType, record.OriginalFileName, enableRangeProcessing: true);
|
return Results.File(stream, record.ContentType, record.OriginalFileName, enableRangeProcessing: true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// File Delete
|
||||||
|
app.MapDelete("/api/files/{id}", async (string id, HttpRequest req, IAuthService auth, ChatDatabase chatDb, FileStorageService fileService, ChatWebSocketManager wsManager) =>
|
||||||
|
{
|
||||||
|
string? token = ExtractBearerToken(req);
|
||||||
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
return Results.Unauthorized();
|
||||||
|
}
|
||||||
|
|
||||||
|
var record = await fileService.GetFileRecordAsync(id);
|
||||||
|
if (record == null)
|
||||||
|
{
|
||||||
|
return Results.NotFound(new DeleteFileResponse { Success = false, ErrorMessage = "File not found." });
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isUploader = string.Equals(user.Id, record.UploaderId, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
string.Equals(user.Username, record.UploaderUsername, StringComparison.OrdinalIgnoreCase);
|
||||||
|
bool isAdmin = string.Equals(user.Role, UserRoles.Admin, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
string.Equals(user.Role, UserRoles.Owner, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
if (!isUploader && !isAdmin)
|
||||||
|
{
|
||||||
|
return Results.Json(new DeleteFileResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
ErrorMessage = "You do not have permission to delete this file. Only the uploader or an admin can delete it."
|
||||||
|
}, statusCode: StatusCodes.Status403Forbidden);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool deleted = await fileService.DeleteFileAsync(record.Id);
|
||||||
|
if (!deleted)
|
||||||
|
{
|
||||||
|
return Results.BadRequest(new DeleteFileResponse { Success = false, ErrorMessage = "Failed to delete file." });
|
||||||
|
}
|
||||||
|
|
||||||
|
await wsManager.BroadcastFileDeletedAsync(record, user.Username);
|
||||||
|
|
||||||
|
return Results.Ok(new DeleteFileResponse
|
||||||
|
{
|
||||||
|
Success = true,
|
||||||
|
FileId = record.Id
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// WebSocket Chat Endpoint
|
// WebSocket Chat Endpoint
|
||||||
app.MapGet("/ws", async (HttpContext context, IAuthService auth, ChatWebSocketManager wsManager, ConnectionLimiterService connectionLimiter, ServerOptions options) =>
|
app.MapGet("/ws", async (HttpContext context, IAuthService auth, ChatWebSocketManager wsManager, ConnectionLimiterService connectionLimiter, ServerOptions options) =>
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -171,6 +171,29 @@ public class FileStorageService
|
||||||
return await _db.GetFileRecordAsync(fileId);
|
return await _db.GetFileRecordAsync(fileId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<bool> DeleteFileAsync(string fileId)
|
||||||
|
{
|
||||||
|
var record = await _db.GetFileRecordAsync(fileId);
|
||||||
|
if (record == null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(record.StoragePath) && File.Exists(record.StoragePath))
|
||||||
|
{
|
||||||
|
File.Delete(record.StoragePath);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Best effort disk cleanup
|
||||||
|
}
|
||||||
|
|
||||||
|
return await _db.DeleteFileRecordAsync(fileId);
|
||||||
|
}
|
||||||
|
|
||||||
public Stream? OpenFileStream(FileRecord record)
|
public Stream? OpenFileStream(FileRecord record)
|
||||||
{
|
{
|
||||||
if (File.Exists(record.StoragePath))
|
if (File.Exists(record.StoragePath))
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,7 @@ public class ChatWebSocketManager
|
||||||
private readonly ServerOptions _options;
|
private readonly ServerOptions _options;
|
||||||
private readonly ILogger<ChatWebSocketManager> _logger;
|
private readonly ILogger<ChatWebSocketManager> _logger;
|
||||||
private readonly WebPushService? _webPush;
|
private readonly WebPushService? _webPush;
|
||||||
|
private readonly FileStorageService _fileService;
|
||||||
|
|
||||||
// Extensibility hooks for mod system
|
// Extensibility hooks for mod system
|
||||||
public Func<ChatMessage, Task<ChatMessage?>>? MessagePipelineInterceptor { get; set; }
|
public Func<ChatMessage, Task<ChatMessage?>>? MessagePipelineInterceptor { get; set; }
|
||||||
|
|
@ -35,12 +36,14 @@ public class ChatWebSocketManager
|
||||||
ChatDatabase db,
|
ChatDatabase db,
|
||||||
ServerOptions options,
|
ServerOptions options,
|
||||||
ILogger<ChatWebSocketManager> logger,
|
ILogger<ChatWebSocketManager> logger,
|
||||||
WebPushService? webPush = null)
|
WebPushService? webPush = null,
|
||||||
|
FileStorageService? fileStorage = null)
|
||||||
{
|
{
|
||||||
_db = db;
|
_db = db;
|
||||||
_options = options;
|
_options = options;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_webPush = webPush;
|
_webPush = webPush;
|
||||||
|
_fileService = fileStorage ?? new FileStorageService(db, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
public int ConnectedCount => _clients.Count;
|
public int ConnectedCount => _clients.Count;
|
||||||
|
|
@ -234,6 +237,14 @@ public class ChatWebSocketManager
|
||||||
}
|
}
|
||||||
break;
|
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:
|
case MessageTypes.StartDm:
|
||||||
var dmPkg = envelope.Unpack<StartDmPacket>();
|
var dmPkg = envelope.Unpack<StartDmPacket>();
|
||||||
if (dmPkg != null)
|
if (dmPkg != null)
|
||||||
|
|
@ -904,6 +915,29 @@ public class ChatWebSocketManager
|
||||||
await BroadcastSystemNoticeAsync($"Channel #{InputSanitizer.SanitizeChannelName(channel.Name)} was deleted.", "Warning");
|
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)
|
private async Task HandleCommandAsync(ConnectedClient client, ExecuteCommandPacket packet, CancellationToken ct)
|
||||||
{
|
{
|
||||||
string cmd = (packet.Command ?? string.Empty).TrimStart('/').ToLowerInvariant();
|
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" +
|
" /follow [channel] - Follow/unfollow a conversation for Inbox notifications\n" +
|
||||||
" /inbox [readall|clear] - Manage Inbox notifications & preferences\n" +
|
" /inbox [readall|clear] - Manage Inbox notifications & preferences\n" +
|
||||||
" /announce <message> - Broadcast an official announcement (Admin/Owner)\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" +
|
" /users - List all registered users\n" +
|
||||||
" /motd - Display message of the day";
|
" /motd - Display message of the day";
|
||||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = helpText, ChannelId = packet.ChannelId }, ct);
|
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = helpText, ChannelId = packet.ChannelId }, ct);
|
||||||
|
|
@ -982,6 +1017,55 @@ public class ChatWebSocketManager
|
||||||
}, ct);
|
}, ct);
|
||||||
break;
|
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 "follow":
|
||||||
case "unfollow":
|
case "unfollow":
|
||||||
case "mute":
|
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
|
#region Inbox & Notification Processing
|
||||||
|
|
||||||
public async Task SendInboxSyncToClientAsync(ConnectedClient client, CancellationToken ct = default)
|
public async Task SendInboxSyncToClientAsync(ConnectedClient client, CancellationToken ct = default)
|
||||||
|
|
|
||||||
|
|
@ -1108,6 +1108,14 @@
|
||||||
} else if (!state.privateKey) {
|
} else if (!state.privateKey) {
|
||||||
loadCachedKeysForCurrentUser();
|
loadCachedKeysForCurrentUser();
|
||||||
}
|
}
|
||||||
|
if (state.user) {
|
||||||
|
const role = payload.role ?? payload.Role;
|
||||||
|
if (role) state.user.role = role;
|
||||||
|
const uid = payload.userId ?? payload.UserId;
|
||||||
|
if (uid) state.user.id = uid;
|
||||||
|
localStorage.setItem('gsdchat_user', JSON.stringify(state.user));
|
||||||
|
}
|
||||||
|
updateUserUI();
|
||||||
updateSettingsBadges();
|
updateSettingsBadges();
|
||||||
updateActiveChannelHeader();
|
updateActiveChannelHeader();
|
||||||
updateE2eeModalUI();
|
updateE2eeModalUI();
|
||||||
|
|
@ -2056,6 +2064,36 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function deleteFile(fileId, fileName) {
|
||||||
|
if (!state.token) {
|
||||||
|
showToast('Please login to delete files');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
showToast(`Deleting ${fileName}...`);
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/files/${encodeURIComponent(fileId)}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${state.token}`
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
let errText = `HTTP ${res.status}`;
|
||||||
|
try {
|
||||||
|
const data = await res.json();
|
||||||
|
if (data && data.errorMessage) errText = data.errorMessage;
|
||||||
|
} catch { }
|
||||||
|
showToast(`Failed to delete ${fileName}: ${errText}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
showToast(`Deleted ${fileName} successfully!`);
|
||||||
|
state.files = state.files.filter(f => (f.id || f.Id) !== fileId);
|
||||||
|
renderFiles();
|
||||||
|
} catch (err) {
|
||||||
|
showToast(`Delete error: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function appendMessage(msg, autoScroll = true) {
|
function appendMessage(msg, autoScroll = true) {
|
||||||
const welcome = el.chatMessages.querySelector('.welcome-message');
|
const welcome = el.chatMessages.querySelector('.welcome-message');
|
||||||
if (welcome) welcome.remove();
|
if (welcome) welcome.remove();
|
||||||
|
|
@ -2079,11 +2117,22 @@
|
||||||
const sizeStr = formatBytes(attBytes);
|
const sizeStr = formatBytes(attBytes);
|
||||||
const safeId = escapeHtml(attId);
|
const safeId = escapeHtml(attId);
|
||||||
const safeName = escapeHtml(attName || 'file');
|
const safeName = escapeHtml(attName || 'file');
|
||||||
|
|
||||||
|
const msgSenderId = msg.senderId || msg.SenderId;
|
||||||
|
const isUploader = (state.user && state.user.id && msgSenderId && state.user.id.toLowerCase() === msgSenderId.toLowerCase()) ||
|
||||||
|
(state.user && state.user.username && sender && state.user.username.toLowerCase() === sender.toLowerCase());
|
||||||
|
const isAdmin = state.user && (
|
||||||
|
(state.user.role && state.user.role.toLowerCase() === 'admin') ||
|
||||||
|
(state.user.role && state.user.role.toLowerCase() === 'owner')
|
||||||
|
);
|
||||||
|
const canDelete = isUploader || isAdmin;
|
||||||
|
|
||||||
contentHtml += `
|
contentHtml += `
|
||||||
<div>
|
<div style="display:flex; align-items:center; gap:6px; margin-top:4px;">
|
||||||
<button type="button" class="attachment-card" data-file-id="${safeId}" data-file-name="${safeName}">
|
<button type="button" class="attachment-card" data-file-id="${safeId}" data-file-name="${safeName}">
|
||||||
[^] ${safeName} (${sizeStr})
|
[^] ${safeName} (${sizeStr})
|
||||||
</button>
|
</button>
|
||||||
|
${canDelete ? `<button type="button" class="btn btn-outline-danger btn-sm btn-delete-attachment" data-file-id="${safeId}" data-file-name="${safeName}" title="Delete file" style="padding:2px 8px; font-size:0.75rem;">[Delete]</button>` : ''}
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
@ -2107,6 +2156,15 @@
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
div.querySelectorAll('.btn-delete-attachment').forEach(btn => {
|
||||||
|
btn.addEventListener('click', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (confirm(`Are you sure you want to delete "${btn.dataset.fileName}"?`)) {
|
||||||
|
deleteFile(btn.dataset.fileId, btn.dataset.fileName);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
el.chatMessages.appendChild(div);
|
el.chatMessages.appendChild(div);
|
||||||
if (autoScroll) {
|
if (autoScroll) {
|
||||||
el.chatMessages.scrollTop = el.chatMessages.scrollHeight;
|
el.chatMessages.scrollTop = el.chatMessages.scrollHeight;
|
||||||
|
|
@ -2255,16 +2313,28 @@
|
||||||
const fileName = f.originalFileName || f.OriginalFileName || 'file';
|
const fileName = f.originalFileName || f.OriginalFileName || 'file';
|
||||||
const fileBytes = f.fileSizeBytes ?? f.FileSizeBytes ?? 0;
|
const fileBytes = f.fileSizeBytes ?? f.FileSizeBytes ?? 0;
|
||||||
const uploader = f.uploaderUsername || f.UploaderUsername || 'User';
|
const uploader = f.uploaderUsername || f.UploaderUsername || 'User';
|
||||||
|
const uploaderId = f.uploaderId || f.UploaderId;
|
||||||
const createdAt = f.createdAt || f.CreatedAt;
|
const createdAt = f.createdAt || f.CreatedAt;
|
||||||
const sizeStr = formatBytes(fileBytes);
|
const sizeStr = formatBytes(fileBytes);
|
||||||
const dateStr = createdAt ? new Date(createdAt).toLocaleDateString() : '';
|
const dateStr = createdAt ? new Date(createdAt).toLocaleDateString() : '';
|
||||||
|
|
||||||
|
const isUploader = (state.user && state.user.id && uploaderId && state.user.id.toLowerCase() === uploaderId.toLowerCase()) ||
|
||||||
|
(state.user && state.user.username && uploader && state.user.username.toLowerCase() === uploader.toLowerCase());
|
||||||
|
const isAdmin = state.user && (
|
||||||
|
(state.user.role && state.user.role.toLowerCase() === 'admin') ||
|
||||||
|
(state.user.role && state.user.role.toLowerCase() === 'owner')
|
||||||
|
);
|
||||||
|
const canDelete = isUploader || isAdmin;
|
||||||
|
|
||||||
item.innerHTML = `
|
item.innerHTML = `
|
||||||
<div class="file-meta">
|
<div class="file-meta">
|
||||||
<div style="font-weight:600;">[^] ${escapeHtml(fileName)}</div>
|
<div style="font-weight:600;">[^] ${escapeHtml(fileName)}</div>
|
||||||
<div style="font-size:0.8rem; color:var(--text-muted);">${sizeStr} | shared by @${escapeHtml(uploader)} on ${dateStr}</div>
|
<div style="font-size:0.8rem; color:var(--text-muted);">${sizeStr} | shared by @${escapeHtml(uploader)} on ${dateStr}</div>
|
||||||
</div>
|
</div>
|
||||||
<button type="button" class="btn btn-primary btn-sm btn-download" data-file-id="${escapeHtml(fileId)}" data-file-name="${escapeHtml(fileName)}">[Download]</button>
|
<div class="file-actions" style="display:flex; gap:8px;">
|
||||||
|
<button type="button" class="btn btn-primary btn-sm btn-download" data-file-id="${escapeHtml(fileId)}" data-file-name="${escapeHtml(fileName)}">[Download]</button>
|
||||||
|
${canDelete ? `<button type="button" class="btn btn-outline-danger btn-sm btn-delete-file" data-file-id="${escapeHtml(fileId)}" data-file-name="${escapeHtml(fileName)}">[Delete]</button>` : ''}
|
||||||
|
</div>
|
||||||
`;
|
`;
|
||||||
const dlBtn = item.querySelector('.btn-download');
|
const dlBtn = item.querySelector('.btn-download');
|
||||||
if (dlBtn) {
|
if (dlBtn) {
|
||||||
|
|
@ -2273,6 +2343,17 @@
|
||||||
downloadFile(dlBtn.dataset.fileId, dlBtn.dataset.fileName);
|
downloadFile(dlBtn.dataset.fileId, dlBtn.dataset.fileName);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
if (canDelete) {
|
||||||
|
const delBtn = item.querySelector('.btn-delete-file');
|
||||||
|
if (delBtn) {
|
||||||
|
delBtn.addEventListener('click', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (confirm(`Are you sure you want to delete "${fileName}"?`)) {
|
||||||
|
deleteFile(delBtn.dataset.fileId, delBtn.dataset.fileName);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
el.filesList.appendChild(item);
|
el.filesList.appendChild(item);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
@ -2290,6 +2371,7 @@
|
||||||
if (el.e2eeVaultBtn) el.e2eeVaultBtn.style.display = 'none';
|
if (el.e2eeVaultBtn) el.e2eeVaultBtn.style.display = 'none';
|
||||||
el.logoutBtn.style.display = 'none';
|
el.logoutBtn.style.display = 'none';
|
||||||
}
|
}
|
||||||
|
renderFiles();
|
||||||
}
|
}
|
||||||
|
|
||||||
function showAuthModal() {
|
function showAuthModal() {
|
||||||
|
|
|
||||||
|
|
@ -321,4 +321,62 @@ public class DatabaseTests : IDisposable
|
||||||
await _db.RemovePushSubscriptionByEndpointAsync("https://push.example.org/send/sub_1");
|
await _db.RemovePushSubscriptionByEndpointAsync("https://push.example.org/send/sub_1");
|
||||||
Assert.Empty(await _db.GetPushSubscriptionsForUserAsync(bob.Id));
|
Assert.Empty(await _db.GetPushSubscriptionsForUserAsync(bob.Id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task DeleteFileRecord_ShouldDeleteRecordAndAssociatedAttachmentMessages()
|
||||||
|
{
|
||||||
|
var channels = await _db.GetChannelsAsync();
|
||||||
|
var general = channels[0];
|
||||||
|
|
||||||
|
var file = new FileRecord
|
||||||
|
{
|
||||||
|
Id = "file_delete_test_1",
|
||||||
|
ChannelId = general.Id,
|
||||||
|
UploaderId = "user_uploader_1",
|
||||||
|
UploaderUsername = "uploader_user",
|
||||||
|
OriginalFileName = "document_to_delete.pdf",
|
||||||
|
ContentType = "application/pdf",
|
||||||
|
FileSizeBytes = 1234,
|
||||||
|
StoragePath = "/tmp/dummy.pdf",
|
||||||
|
Sha256Checksum = "dummy_sha256",
|
||||||
|
CreatedAt = DateTime.UtcNow
|
||||||
|
};
|
||||||
|
await _db.SaveFileRecordAsync(file);
|
||||||
|
|
||||||
|
var msg = new ChatMessage
|
||||||
|
{
|
||||||
|
ChannelId = general.Id,
|
||||||
|
SenderId = "user_uploader_1",
|
||||||
|
SenderUsername = "uploader_user",
|
||||||
|
Content = "Shared file: document_to_delete.pdf",
|
||||||
|
AttachmentId = file.Id,
|
||||||
|
AttachmentName = file.OriginalFileName,
|
||||||
|
AttachmentSizeBytes = file.FileSizeBytes
|
||||||
|
};
|
||||||
|
await _db.SaveMessageAsync(msg);
|
||||||
|
|
||||||
|
// Verify file is returned in recent files and includes UploaderId
|
||||||
|
var recent = await _db.GetRecentFilesAsync();
|
||||||
|
var summary = recent.Find(f => f.Id == file.Id);
|
||||||
|
Assert.NotNull(summary);
|
||||||
|
Assert.Equal("user_uploader_1", summary.UploaderId);
|
||||||
|
Assert.Equal("uploader_user", summary.UploaderUsername);
|
||||||
|
|
||||||
|
// Verify message exists
|
||||||
|
var msgs = await _db.GetRecentMessagesAsync(general.Id);
|
||||||
|
Assert.Contains(msgs, m => m.AttachmentId == file.Id);
|
||||||
|
|
||||||
|
// Delete file record
|
||||||
|
bool deleted = await _db.DeleteFileRecordAsync(file.Id);
|
||||||
|
Assert.True(deleted);
|
||||||
|
|
||||||
|
// Verify file record is gone
|
||||||
|
Assert.Null(await _db.GetFileRecordAsync(file.Id));
|
||||||
|
recent = await _db.GetRecentFilesAsync();
|
||||||
|
Assert.DoesNotContain(recent, f => f.Id == file.Id);
|
||||||
|
|
||||||
|
// Verify message with attachment_id is gone
|
||||||
|
msgs = await _db.GetRecentMessagesAsync(general.Id);
|
||||||
|
Assert.DoesNotContain(msgs, m => m.AttachmentId == file.Id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -234,6 +234,44 @@ public class EndToEndChatTests : IAsyncLifetime
|
||||||
return Results.File(stream, record.ContentType, record.OriginalFileName);
|
return Results.File(stream, record.ContentType, record.OriginalFileName);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
_app.MapDelete("/api/files/{id}", async (string id, HttpRequest req, IAuthService auth, ChatDatabase chatDb, FileStorageService fileSvc, ChatWebSocketManager ws) =>
|
||||||
|
{
|
||||||
|
string? token = ExtractToken(req);
|
||||||
|
var user = await auth.ValidateSessionTokenAsync(token ?? "");
|
||||||
|
if (user == null) return Results.Unauthorized();
|
||||||
|
|
||||||
|
var record = await fileSvc.GetFileRecordAsync(id);
|
||||||
|
if (record == null) return Results.NotFound(new DeleteFileResponse { Success = false, ErrorMessage = "File not found." });
|
||||||
|
|
||||||
|
bool isUploader = string.Equals(user.Id, record.UploaderId, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
string.Equals(user.Username, record.UploaderUsername, StringComparison.OrdinalIgnoreCase);
|
||||||
|
bool isAdmin = string.Equals(user.Role, UserRoles.Admin, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
string.Equals(user.Role, UserRoles.Owner, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
if (!isUploader && !isAdmin)
|
||||||
|
{
|
||||||
|
return Results.Json(new DeleteFileResponse
|
||||||
|
{
|
||||||
|
Success = false,
|
||||||
|
ErrorMessage = "You do not have permission to delete this file. Only the uploader or an admin can delete it."
|
||||||
|
}, statusCode: StatusCodes.Status403Forbidden);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool deleted = await fileSvc.DeleteFileAsync(record.Id);
|
||||||
|
if (!deleted)
|
||||||
|
{
|
||||||
|
return Results.BadRequest(new DeleteFileResponse { Success = false, ErrorMessage = "Failed to delete file." });
|
||||||
|
}
|
||||||
|
|
||||||
|
await ws.BroadcastFileDeletedAsync(record, user.Username);
|
||||||
|
|
||||||
|
return Results.Ok(new DeleteFileResponse
|
||||||
|
{
|
||||||
|
Success = true,
|
||||||
|
FileId = record.Id
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
_app.MapGet("/ws", async (HttpContext context, IAuthService auth, ChatWebSocketManager ws, ConnectionLimiterService connLimiter, ServerOptions options) =>
|
_app.MapGet("/ws", async (HttpContext context, IAuthService auth, ChatWebSocketManager ws, ConnectionLimiterService connLimiter, ServerOptions options) =>
|
||||||
{
|
{
|
||||||
if (!context.WebSockets.IsWebSocketRequest)
|
if (!context.WebSockets.IsWebSocketRequest)
|
||||||
|
|
@ -390,6 +428,28 @@ public class EndToEndChatTests : IAsyncLifetime
|
||||||
Assert.True(File.Exists(downloadedFilePath));
|
Assert.True(File.Exists(downloadedFilePath));
|
||||||
string downloadedText = await File.ReadAllTextAsync(downloadedFilePath);
|
string downloadedText = await File.ReadAllTextAsync(downloadedFilePath);
|
||||||
Assert.Equal(fileContent, downloadedText);
|
Assert.Equal(fileContent, downloadedText);
|
||||||
|
|
||||||
|
// 7. Bob (non-uploader, member) tries to delete Alice's file -> should fail with permission error
|
||||||
|
bool bobDeleteSuccess = await connBob.DeleteFileAsync(sharedFile.Id);
|
||||||
|
Assert.False(bobDeleteSuccess);
|
||||||
|
Assert.Contains("403", stateBob.StatusMessage);
|
||||||
|
|
||||||
|
// 8. Alice (uploader) deletes the file -> succeeds
|
||||||
|
bool aliceDeleteSuccess = await connAlice.DeleteFileAsync(sharedFile.Id);
|
||||||
|
Assert.True(aliceDeleteSuccess);
|
||||||
|
|
||||||
|
// Wait for file list sync to reflect deletion for both Bob and Alice
|
||||||
|
for (int i = 0; i < 20; i++)
|
||||||
|
{
|
||||||
|
if (!stateBob.Files.Exists(f => f.Id == sharedFile.Id) && !stateAlice.Files.Exists(f => f.Id == sharedFile.Id))
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
await Task.Delay(100);
|
||||||
|
}
|
||||||
|
|
||||||
|
Assert.DoesNotContain(stateBob.Files, f => f.Id == sharedFile.Id);
|
||||||
|
Assert.DoesNotContain(stateAlice.Files, f => f.Id == sharedFile.Id);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|
|
||||||
|
|
@ -78,4 +78,83 @@ public class FileStorageServiceTests : IDisposable
|
||||||
string readBack = await reader.ReadToEndAsync();
|
string readBack = await reader.ReadToEndAsync();
|
||||||
Assert.Equal(fileContent, readBack);
|
Assert.Equal(fileContent, readBack);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task DeleteFile_ShouldDeleteFileFromDiskAndDatabase()
|
||||||
|
{
|
||||||
|
var channels = await _db.GetChannelsAsync();
|
||||||
|
var general = channels[0];
|
||||||
|
|
||||||
|
string fileContent = "File to be deleted.";
|
||||||
|
byte[] fileBytes = Encoding.UTF8.GetBytes(fileContent);
|
||||||
|
|
||||||
|
using var memoryStream = new MemoryStream(fileBytes);
|
||||||
|
var (record, message) = await _fileService.StoreFileWithMessageAsync(
|
||||||
|
general.Id,
|
||||||
|
"uploader-1",
|
||||||
|
"Tester",
|
||||||
|
"delete_me.txt",
|
||||||
|
"text/plain",
|
||||||
|
memoryStream,
|
||||||
|
fileBytes.Length
|
||||||
|
);
|
||||||
|
|
||||||
|
Assert.NotNull(record);
|
||||||
|
Assert.True(File.Exists(record.StoragePath));
|
||||||
|
Assert.NotNull(await _fileService.GetFileRecordAsync(record.Id));
|
||||||
|
|
||||||
|
var msgsBefore = await _db.GetRecentMessagesAsync(general.Id);
|
||||||
|
Assert.Contains(msgsBefore, m => m.AttachmentId == record.Id);
|
||||||
|
|
||||||
|
// Delete the file
|
||||||
|
bool deleted = await _fileService.DeleteFileAsync(record.Id);
|
||||||
|
Assert.True(deleted);
|
||||||
|
|
||||||
|
// Verify disk file is gone
|
||||||
|
Assert.False(File.Exists(record.StoragePath));
|
||||||
|
|
||||||
|
// Verify database record is gone
|
||||||
|
Assert.Null(await _fileService.GetFileRecordAsync(record.Id));
|
||||||
|
|
||||||
|
// Verify associated attachment message is deleted
|
||||||
|
var msgsAfter = await _db.GetRecentMessagesAsync(general.Id);
|
||||||
|
Assert.DoesNotContain(msgsAfter, m => m.AttachmentId == record.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task DeleteFile_NonExistentId_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
bool deleted = await _fileService.DeleteFileAsync("non_existent_file_id");
|
||||||
|
Assert.False(deleted);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void FileDeletePermissions_ShouldAllowUploaderAndAdminAndOwnerOnly()
|
||||||
|
{
|
||||||
|
var file = new GsDChat.Core.Models.FileRecord
|
||||||
|
{
|
||||||
|
Id = "f1",
|
||||||
|
UploaderId = "user-alice",
|
||||||
|
UploaderUsername = "alice"
|
||||||
|
};
|
||||||
|
|
||||||
|
static bool CanDelete(GsDChat.Core.Models.User user, GsDChat.Core.Models.FileRecord record)
|
||||||
|
{
|
||||||
|
bool isUploader = string.Equals(user.Id, record.UploaderId, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
string.Equals(user.Username, record.UploaderUsername, StringComparison.OrdinalIgnoreCase);
|
||||||
|
bool isAdmin = string.Equals(user.Role, GsDChat.Core.Models.UserRoles.Admin, StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
string.Equals(user.Role, GsDChat.Core.Models.UserRoles.Owner, StringComparison.OrdinalIgnoreCase);
|
||||||
|
return isUploader || isAdmin;
|
||||||
|
}
|
||||||
|
|
||||||
|
var uploaderMember = new GsDChat.Core.Models.User { Id = "user-alice", Username = "alice", Role = GsDChat.Core.Models.UserRoles.Member };
|
||||||
|
var otherMember = new GsDChat.Core.Models.User { Id = "user-bob", Username = "bob", Role = GsDChat.Core.Models.UserRoles.Member };
|
||||||
|
var admin = new GsDChat.Core.Models.User { Id = "user-charlie", Username = "charlie", Role = GsDChat.Core.Models.UserRoles.Admin };
|
||||||
|
var owner = new GsDChat.Core.Models.User { Id = "user-dan", Username = "dan", Role = GsDChat.Core.Models.UserRoles.Owner };
|
||||||
|
|
||||||
|
Assert.True(CanDelete(uploaderMember, file));
|
||||||
|
Assert.False(CanDelete(otherMember, file));
|
||||||
|
Assert.True(CanDelete(admin, file));
|
||||||
|
Assert.True(CanDelete(owner, file));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -146,6 +146,7 @@ public class WebClientStaticTests : IAsyncLifetime
|
||||||
Assert.Contains("INBOX_SYNC", js);
|
Assert.Contains("INBOX_SYNC", js);
|
||||||
Assert.Contains("INBOX_NEW_ITEM", js);
|
Assert.Contains("INBOX_NEW_ITEM", js);
|
||||||
Assert.Contains("subscribeWebPush", js);
|
Assert.Contains("subscribeWebPush", js);
|
||||||
|
Assert.Contains("deleteFile", js);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue