diff --git a/src/GsDChat.Client/Network/ChatClientConnection.cs b/src/GsDChat.Client/Network/ChatClientConnection.cs index 50ce710..8dee4eb 100644 --- a/src/GsDChat.Client/Network/ChatClientConnection.cs +++ b/src/GsDChat.Client/Network/ChatClientConnection.cs @@ -788,6 +788,7 @@ public class ChatClientConnection : IDisposable public Task JoinChannelAsync(string channelId) { + _state.MarkChannelInboxItemsReadLocally(channelId); var envelope = NetworkEnvelope.Create(MessageTypes.JoinChannel, new JoinChannelPacket { ChannelId = channelId }); return SendEnvelopeAsync(envelope); } @@ -1094,6 +1095,42 @@ public class ChatClientConnection : IDisposable } } + public async Task 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() { VoiceManager.Dispose(); diff --git a/src/GsDChat.Client/Rendering/ConsoleUi.cs b/src/GsDChat.Client/Rendering/ConsoleUi.cs index db676d8..1c21a7e 100644 --- a/src/GsDChat.Client/Rendering/ConsoleUi.cs +++ b/src/GsDChat.Client/Rendering/ConsoleUi.cs @@ -100,7 +100,19 @@ public class ConsoleUi // Check Screen Swapping Function Keys if (key.Key == ConsoleKey.F1) { - if (_state.ActiveScreenId != "F1_Chat") { _state.ActiveScreenId = "F1_Chat"; Console.Clear(); } + if (_state.ActiveScreenId != "F1_Chat") + { + _state.ActiveScreenId = "F1_Chat"; + Console.Clear(); + if (!string.IsNullOrEmpty(_state.ActiveChannelId)) + { + int changed = _state.MarkChannelInboxItemsReadLocally(_state.ActiveChannelId); + if (changed > 0) + { + _ = _connection.SendInboxActionAsync("mark_read", channelId: _state.ActiveChannelId); + } + } + } _state.NeedsRedraw = true; } else if (key.Key == ConsoleKey.F2) diff --git a/src/GsDChat.Client/Screens/FilesScreen.cs b/src/GsDChat.Client/Screens/FilesScreen.cs index 821f1c5..bb5f63d 100644 --- a/src/GsDChat.Client/Screens/FilesScreen.cs +++ b/src/GsDChat.Client/Screens/FilesScreen.cs @@ -27,7 +27,7 @@ public class FilesScreen : IScreen 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))); if (_state.Files.Count == 0) @@ -48,7 +48,13 @@ public class FilesScreen : IScreen string sizeStr = FormatBytes(f.FileSizeBytes); 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) { @@ -69,7 +75,7 @@ public class FilesScreen : IScreen } 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; } } + 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) { _isUploading = true; diff --git a/src/GsDChat.Client/State/ClientState.cs b/src/GsDChat.Client/State/ClientState.cs index 40c14d0..a521474 100644 --- a/src/GsDChat.Client/State/ClientState.cs +++ b/src/GsDChat.Client/State/ClientState.cs @@ -483,6 +483,15 @@ public class ClientState } } + public void RemoveFile(string fileId) + { + lock (_lock) + { + Files.RemoveAll(f => f.Id == fileId); + NeedsRedraw = true; + } + } + public void SetInboxSync(List items, int unreadCount, InboxPreferences? preferences = null) { lock (_lock) @@ -516,6 +525,29 @@ public class ClientState } } + public int MarkChannelInboxItemsReadLocally(string channelId) + { + if (string.IsNullOrEmpty(channelId)) return 0; + lock (_lock) + { + int changed = 0; + foreach (var item in InboxItems) + { + if (string.Equals(item.ChannelId, channelId, StringComparison.OrdinalIgnoreCase) && !item.IsRead) + { + item.IsRead = true; + changed++; + } + } + if (changed > 0) + { + UnreadInboxCount = Math.Max(0, UnreadInboxCount - changed); + NeedsRedraw = true; + } + return changed; + } + } + public List GetInboxItems() { lock (_lock) diff --git a/src/GsDChat.Core/Protocol/HttpModels.cs b/src/GsDChat.Core/Protocol/HttpModels.cs index 5c9b392..fb4162a 100644 --- a/src/GsDChat.Core/Protocol/HttpModels.cs +++ b/src/GsDChat.Core/Protocol/HttpModels.cs @@ -74,3 +74,10 @@ public class UploadFileResponse public string? ChannelId { 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; } +} diff --git a/src/GsDChat.Core/Protocol/NetworkMessages.cs b/src/GsDChat.Core/Protocol/NetworkMessages.cs index 13c39b5..14b2757 100644 --- a/src/GsDChat.Core/Protocol/NetworkMessages.cs +++ b/src/GsDChat.Core/Protocol/NetworkMessages.cs @@ -26,6 +26,7 @@ public static class MessageTypes public const string FetchHistory = "FETCH_HISTORY"; public const string UserListSync = "USER_LIST_SYNC"; public const string FileListSync = "FILE_LIST_SYNC"; + public const string DeleteFile = "DELETE_FILE"; public const string SystemNotice = "SYSTEM_NOTICE"; public const string Error = "ERROR"; public const string ExecuteCommand = "EXECUTE_COMMAND"; @@ -212,9 +213,15 @@ public class FileSummary public string ContentType { get; set; } = string.Empty; public long FileSizeBytes { get; set; } public string UploaderUsername { get; set; } = string.Empty; + public string UploaderId { get; set; } = string.Empty; public System.DateTime CreatedAt { get; set; } } +public class DeleteFilePacket +{ + public string FileId { get; set; } = string.Empty; +} + public class FileListSyncPacket { public List Files { get; set; } = new(); diff --git a/src/GsDChat.Modding/IModEventBus.cs b/src/GsDChat.Modding/IModEventBus.cs index d20af10..532985c 100644 --- a/src/GsDChat.Modding/IModEventBus.cs +++ b/src/GsDChat.Modding/IModEventBus.cs @@ -10,9 +10,11 @@ public interface IModEventBus void SubscribeUserDisconnected(Func handler); void SubscribeChannelCreated(Func handler); void SubscribeFileUploaded(Func handler); + void SubscribeFileDeleted(Func handler); Task PublishUserConnectedAsync(User user); Task PublishUserDisconnectedAsync(User user); Task PublishChannelCreatedAsync(Channel channel); Task PublishFileUploadedAsync(FileRecord file); + Task PublishFileDeletedAsync(FileRecord file); } diff --git a/src/GsDChat.Modding/ModEventBus.cs b/src/GsDChat.Modding/ModEventBus.cs index 90eea4e..545e133 100644 --- a/src/GsDChat.Modding/ModEventBus.cs +++ b/src/GsDChat.Modding/ModEventBus.cs @@ -11,11 +11,13 @@ public class ModEventBus : IModEventBus private readonly List> _userDisconnectedHandlers = new(); private readonly List> _channelCreatedHandlers = new(); private readonly List> _fileUploadedHandlers = new(); + private readonly List> _fileDeletedHandlers = new(); public void SubscribeUserConnected(Func handler) => _userConnectedHandlers.Add(handler); public void SubscribeUserDisconnected(Func handler) => _userDisconnectedHandlers.Add(handler); public void SubscribeChannelCreated(Func handler) => _channelCreatedHandlers.Add(handler); public void SubscribeFileUploaded(Func handler) => _fileUploadedHandlers.Add(handler); + public void SubscribeFileDeleted(Func handler) => _fileDeletedHandlers.Add(handler); public async Task PublishUserConnectedAsync(User user) { @@ -48,4 +50,12 @@ public class ModEventBus : IModEventBus try { await h(file); } catch { } } } + + public async Task PublishFileDeletedAsync(FileRecord file) + { + foreach (var h in _fileDeletedHandlers) + { + try { await h(file); } catch { } + } + } } diff --git a/src/GsDChat.Server/Data/ChatDatabase.cs b/src/GsDChat.Server/Data/ChatDatabase.cs index 0a61a3d..d0e1284 100644 --- a/src/GsDChat.Server/Data/ChatDatabase.cs +++ b/src/GsDChat.Server/Data/ChatDatabase.cs @@ -1307,7 +1307,7 @@ public class ChatDatabase : IDisposable using var conn = CreateConnection(); using var cmd = conn.CreateCommand(); 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 ORDER BY created_at DESC LIMIT @limit; @@ -1325,12 +1325,26 @@ public class ChatDatabase : IDisposable ContentType = reader.GetString(3), FileSizeBytes = reader.GetInt64(4), 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; } + public async Task 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 #region Inbox, Preferences & Push Subscription Operations diff --git a/src/GsDChat.Server/Program.cs b/src/GsDChat.Server/Program.cs index f625092..3be0ecb 100644 --- a/src/GsDChat.Server/Program.cs +++ b/src/GsDChat.Server/Program.cs @@ -462,6 +462,51 @@ app.MapGet("/api/files/{id}", async (string id, HttpRequest req, IAuthService au 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 app.MapGet("/ws", async (HttpContext context, IAuthService auth, ChatWebSocketManager wsManager, ConnectionLimiterService connectionLimiter, ServerOptions options) => { diff --git a/src/GsDChat.Server/Services/FileStorageService.cs b/src/GsDChat.Server/Services/FileStorageService.cs index 0b37505..f7d1c40 100644 --- a/src/GsDChat.Server/Services/FileStorageService.cs +++ b/src/GsDChat.Server/Services/FileStorageService.cs @@ -171,6 +171,29 @@ public class FileStorageService return await _db.GetFileRecordAsync(fileId); } + public async Task 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) { if (File.Exists(record.StoragePath)) diff --git a/src/GsDChat.Server/Services/WebPushService.cs b/src/GsDChat.Server/Services/WebPushService.cs index 8731e2c..c7d00a3 100644 --- a/src/GsDChat.Server/Services/WebPushService.cs +++ b/src/GsDChat.Server/Services/WebPushService.cs @@ -182,6 +182,7 @@ public class WebPushService : IDisposable using var request = new HttpRequestMessage(HttpMethod.Post, sub.Endpoint); request.Headers.TryAddWithoutValidation("Authorization", vapidHeader); + request.Headers.TryAddWithoutValidation("Crypto-Key", $"p256ecdsa={_options.VapidPublicKey}"); request.Headers.TryAddWithoutValidation("TTL", "86400"); request.Headers.TryAddWithoutValidation("Urgency", "high"); diff --git a/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs b/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs index 914170e..005594c 100644 --- a/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs +++ b/src/GsDChat.Server/WebSockets/ChatWebSocketManager.cs @@ -27,6 +27,7 @@ public class ChatWebSocketManager private readonly ServerOptions _options; private readonly ILogger _logger; private readonly WebPushService? _webPush; + private readonly FileStorageService _fileService; // Extensibility hooks for mod system public Func>? MessagePipelineInterceptor { get; set; } @@ -37,12 +38,14 @@ public class ChatWebSocketManager ChatDatabase db, ServerOptions options, ILogger 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; @@ -253,6 +256,14 @@ public class ChatWebSocketManager } break; + case MessageTypes.DeleteFile: + var delFilePkg = envelope.Unpack(); + if (delFilePkg != null && !string.IsNullOrWhiteSpace(delFilePkg.FileId)) + { + await HandleDeleteFileAsync(client, delFilePkg.FileId, ct); + } + break; + case MessageTypes.StartDm: var dmPkg = envelope.Unpack(); if (dmPkg != null) @@ -979,6 +990,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(); @@ -1023,6 +1057,7 @@ public class ChatWebSocketManager " /accept | /decline - Accept or decline an incoming DM voice call\n" + " /hangup - Leave or end the active voice call\n" + " /announce - Broadcast an official announcement (Admin/Owner)\n" + + " /deletefile - 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); @@ -1060,6 +1095,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 ", + 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": @@ -1439,6 +1523,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(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) diff --git a/src/GsDChat.Server/wwwroot/app.css b/src/GsDChat.Server/wwwroot/app.css index feaf729..b3997a7 100644 --- a/src/GsDChat.Server/wwwroot/app.css +++ b/src/GsDChat.Server/wwwroot/app.css @@ -228,6 +228,72 @@ html, body { text-transform: uppercase; } +/* ========================================================================== + WhatsApp Web Style Desktop Notification Banner + ========================================================================== */ + +.notif-banner { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 8px 16px; + background-color: var(--ctp-mantle); + border-bottom: 1px solid var(--ctp-mauve); + color: var(--ctp-text); + font-family: var(--font-mono); + font-size: 0.84rem; + flex-shrink: 0; +} + +.notif-banner-icon { + font-size: 1.2rem; + color: var(--ctp-mauve); + line-height: 1; +} + +.notif-banner-body { + display: flex; + flex-direction: column; + flex: 1; + min-width: 0; + gap: 2px; +} + +.notif-banner-title { + font-weight: 700; + color: var(--ctp-mauve); + font-size: 0.86rem; +} + +.notif-banner-desc { + font-size: 0.76rem; + color: var(--ctp-subtext0); +} + +.notif-banner-actions { + display: flex; + align-items: center; + gap: 8px; + flex-shrink: 0; +} + +.notif-banner-dismiss { + background: transparent; + border: 1px solid transparent; + color: var(--ctp-overlay0); + font-family: var(--font-mono); + font-size: 1rem; + cursor: pointer; + padding: 2px 6px; + transition: color 0.1s, border-color 0.1s; +} + +.notif-banner-dismiss:hover { + color: var(--ctp-red); + border-color: var(--ctp-red); +} + /* ========================================================================== Main Content Views ========================================================================== */ diff --git a/src/GsDChat.Server/wwwroot/app.js b/src/GsDChat.Server/wwwroot/app.js index 130446d..daec1ca 100644 --- a/src/GsDChat.Server/wwwroot/app.js +++ b/src/GsDChat.Server/wwwroot/app.js @@ -87,6 +87,10 @@ tabViews: document.querySelectorAll('.tab-view'), currentUsername: document.getElementById('currentUsername'), currentUserRole: document.getElementById('currentUserRole'), + headerPushBtn: document.getElementById('headerPushBtn'), + desktopNotifBanner: document.getElementById('desktopNotifBanner'), + bannerEnablePushBtn: document.getElementById('bannerEnablePushBtn'), + bannerDismissBtn: document.getElementById('bannerDismissBtn'), e2eeVaultBtn: document.getElementById('e2eeVaultBtn'), logoutBtn: document.getElementById('logoutBtn'), userBadge: document.getElementById('userBadge'), @@ -824,7 +828,10 @@ } async function initServiceWorkerAndPush() { - if (!('serviceWorker' in navigator)) return; + if (!('serviceWorker' in navigator)) { + updateDesktopNotifBanner(); + return; + } try { const reg = await navigator.serviceWorker.register('/sw.js'); state.swRegistration = reg; @@ -847,13 +854,64 @@ if (reg.pushManager) { const existingSub = await reg.pushManager.getSubscription(); state.pushSubscribed = !!existingSub; - updateInboxPreferencesUI(); if (existingSub && state.token) { await syncSubscriptionToServer(existingSub); + } else if (!existingSub && 'Notification' in window && Notification.permission === 'granted' && state.token) { + // If browser has already granted permission, auto-subscribe seamlessly like WhatsApp Web + await subscribeWebPush(false); } } } catch (err) { console.warn('Service Worker registration skipped or failed:', err); + } finally { + updateDesktopNotifBanner(); + updateInboxPreferencesUI(); + } + } + + function updateDesktopNotifBanner() { + initElements(); + const hasPushApi = ('Notification' in window) && ('serviceWorker' in navigator); + + if (el.headerPushBtn) { + if (!hasPushApi) { + el.headerPushBtn.style.display = 'none'; + } else { + el.headerPushBtn.style.display = ''; + if (Notification.permission === 'granted') { + if (state.pushSubscribed) { + el.headerPushBtn.textContent = '[🔔 Push: ON]'; + el.headerPushBtn.className = 'btn btn-sm btn-primary'; + el.headerPushBtn.title = 'Background Web Push is active (click to disable)'; + } else { + el.headerPushBtn.textContent = '[🔔 Enable Push]'; + el.headerPushBtn.className = 'btn btn-sm btn-outline-primary'; + el.headerPushBtn.title = 'Click to activate background Web Push'; + } + } else if (Notification.permission === 'denied') { + el.headerPushBtn.textContent = '[🔕 Push: Blocked]'; + el.headerPushBtn.className = 'btn btn-sm btn-secondary'; + el.headerPushBtn.title = 'Notifications are blocked in browser site permissions'; + } else { + el.headerPushBtn.textContent = '[🔔 Enable Push]'; + el.headerPushBtn.className = 'btn btn-sm btn-outline-primary'; + el.headerPushBtn.title = 'Enable background Web Push notifications'; + } + } + } + + if (!el.desktopNotifBanner) return; + + if (!hasPushApi || !state.token || Notification.permission === 'granted' || Notification.permission === 'denied') { + el.desktopNotifBanner.style.display = 'none'; + return; + } + + const dismissed = localStorage.getItem('gsdchat_dismiss_push_banner') === 'true'; + if (dismissed) { + el.desktopNotifBanner.style.display = 'none'; + } else { + el.desktopNotifBanner.style.display = 'flex'; } } @@ -913,16 +971,17 @@ if (state.pushSubscribed) { await unsubscribeWebPush(); } else { - await subscribeWebPush(); + await subscribeWebPush(true); } } - async function subscribeWebPush() { + async function subscribeWebPush(interactive = true) { try { if ('Notification' in window) { const perm = await Notification.requestPermission(); if (perm !== 'granted') { - showToast('Notification permission denied by browser.'); + if (interactive) showToast('Notification permission denied by browser.'); + updateDesktopNotifBanner(); return; } } @@ -934,33 +993,40 @@ const vapidKey = await fetchVapidPublicKey(); if (!vapidKey) { - showToast('Server VAPID public key is unavailable.'); + if (interactive) showToast('Server VAPID public key is unavailable.'); return; } - const sub = await state.swRegistration.pushManager.subscribe({ - userVisibleOnly: true, - applicationServerKey: urlBase64ToUint8Array(vapidKey) - }); + let sub = await state.swRegistration.pushManager.getSubscription(); + if (!sub) { + sub = await state.swRegistration.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: urlBase64ToUint8Array(vapidKey) + }); + } const ok = await syncSubscriptionToServer(sub); if (ok) { state.pushSubscribed = true; state.inboxPreferences.pushNotificationsEnabled = true; - sendEnvelope('UPDATE_INBOX_PREFERENCES', { - mentionsEnabled: state.inboxPreferences.mentionsEnabled, - announcementsEnabled: state.inboxPreferences.announcementsEnabled, - directMessagesEnabled: state.inboxPreferences.directMessagesEnabled, - followedChannelsEnabled: state.inboxPreferences.followedChannelsEnabled, - pushNotificationsEnabled: true - }); + if (state.socket && state.socket.readyState === WebSocket.OPEN) { + sendEnvelope('UPDATE_INBOX_PREFERENCES', { + mentionsEnabled: state.inboxPreferences.mentionsEnabled, + announcementsEnabled: state.inboxPreferences.announcementsEnabled, + directMessagesEnabled: state.inboxPreferences.directMessagesEnabled, + followedChannelsEnabled: state.inboxPreferences.followedChannelsEnabled, + pushNotificationsEnabled: true + }); + } updateInboxPreferencesUI(); + updateDesktopNotifBanner(); showToast('🔔 Background Web Push notifications enabled on this browser!'); } else { - showToast('Failed to register Web Push subscription with server.'); + if (interactive) showToast('Failed to register Web Push subscription with server.'); } } catch (err) { - showToast(`Web Push setup failed: ${err.message || err}`); + if (interactive) showToast(`Web Push setup failed: ${err.message || err}`); + updateDesktopNotifBanner(); } } @@ -987,6 +1053,7 @@ } state.pushSubscribed = false; updateInboxPreferencesUI(); + updateDesktopNotifBanner(); showToast('🔕 Web Push notifications disabled on this browser.'); } catch (err) { showToast(`Unsubscribe error: ${err.message || err}`); @@ -1197,6 +1264,8 @@ updateSettingsBadges(); hideAuthModal(); connectWebSocket(); + initServiceWorkerAndPush(); + updateDesktopNotifBanner(); } catch (err) { el.authError.textContent = 'Connection error. Please try again.'; } finally { @@ -1301,6 +1370,14 @@ } else if (!state.privateKey) { 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(); updateActiveChannelHeader(); updateE2eeModalUI(); @@ -1352,8 +1429,14 @@ sendInboxAction('mark_read', deepInboxItem); } if (deepChannel && getConversationById(deepChannel)) { - state.activeChannelId = deepChannel; + joinChannel(deepChannel); + switchTab('chat'); window.history.replaceState({}, document.title, window.location.pathname); + } else { + const isChatTabActive = el.tabViews && Array.from(el.tabViews).some(v => v.id === 'view-chat' && v.classList.contains('active')); + if (isChatTabActive && !document.hidden) { + markActiveChannelInboxRead(); + } } } catch { // Ignore URL parse issues @@ -1388,6 +1471,10 @@ if (state.activeChannelId === histChId) { renderMessages(!isPrepend); + const isChatTabActive = el.tabViews && Array.from(el.tabViews).some(v => v.id === 'view-chat' && v.classList.contains('active')); + if (isChatTabActive && !document.hidden) { + markActiveChannelInboxRead(); + } } } break; @@ -1401,6 +1488,10 @@ state.messages[chId].push(msg); if (state.activeChannelId === chId) { appendMessage(msg); + const isChatTabActive = el.tabViews && Array.from(el.tabViews).some(v => v.id === 'view-chat' && v.classList.contains('active')); + if (isChatTabActive && !document.hidden) { + markActiveChannelInboxRead(); + } } } break; @@ -1462,16 +1553,24 @@ if (rawItem) { const item = await decryptInboxItemIfNeeded(rawItem); const itemId = item.id || item.Id; + const itemChId = item.channelId || item.ChannelId; + const isChatTabActive = el.tabViews && Array.from(el.tabViews).some(v => v.id === 'view-chat' && v.classList.contains('active')); + const isViewingSameChannel = state.activeChannelId === itemChId && isChatTabActive && !document.hidden; + + if (isViewingSameChannel) { + item.isRead = true; + item.IsRead = true; + sendInboxAction('mark_read', itemId, itemChId); + } + state.inboxItems = [item, ...state.inboxItems.filter(x => (x.id || x.Id) !== itemId)]; - state.unreadInboxCount = payload.unreadCount ?? payload.UnreadCount ?? state.inboxItems.filter(i => !(i.isRead ?? i.IsRead)).length; + state.unreadInboxCount = state.inboxItems.filter(i => !(i.isRead ?? i.IsRead)).length; updateInboxBadge(); renderInbox(); - const itemChId = item.channelId || item.ChannelId; const itemCategory = (item.category || item.Category || 'mention').toLowerCase(); const itemSender = item.senderUsername || item.SenderUsername || 'System'; const itemChName = item.channelName || item.ChannelName || 'chat'; - const isViewingSameChannel = state.activeChannelId === itemChId && !document.hidden; if (!isViewingSameChannel) { showToast(`🔔 [${itemCategory.toUpperCase()}] @${itemSender} in ${itemChName}`); @@ -1592,6 +1691,28 @@ }); } + function markActiveChannelInboxRead() { + if (!state.activeChannelId) return; + + let markedAny = false; + for (const item of state.inboxItems) { + const chId = item.channelId || item.ChannelId; + const isRead = item.isRead ?? item.IsRead ?? false; + if (chId === state.activeChannelId && !isRead) { + item.isRead = true; + item.IsRead = true; + markedAny = true; + } + } + + if (markedAny) { + state.unreadInboxCount = state.inboxItems.filter(i => !(i.isRead ?? i.IsRead)).length; + updateInboxBadge(); + renderInbox(); + sendInboxAction('mark_read', null, state.activeChannelId); + } + } + function toggleInboxPreference(prefKey) { const prefs = state.inboxPreferences; if (prefKey in prefs) { @@ -1644,6 +1765,7 @@ el.toggleWebPushBtn.textContent = activePush ? '[🔔 Web Push: ON]' : '[🔕 Enable Web Push]'; el.toggleWebPushBtn.className = activePush ? 'btn btn-sm btn-primary' : 'btn btn-sm btn-secondary'; } + updateDesktopNotifBanner(); } function renderInbox() { @@ -1867,6 +1989,8 @@ renderInbox(); } else if (tabName === 'chat') { renderMessages(); + if (el.messageInput) el.messageInput.focus(); + markActiveChannelInboxRead(); } } @@ -2177,6 +2301,7 @@ if (!channelId) return; state.activeChannelId = channelId; sendEnvelope('JOIN_CHANNEL', { channelId }); + markActiveChannelInboxRead(); renderChannels(); updateActiveChannelHeader(); renderMessages(); @@ -2276,6 +2401,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) { const welcome = el.chatMessages.querySelector('.welcome-message'); if (welcome) welcome.remove(); @@ -2299,11 +2454,22 @@ const sizeStr = formatBytes(attBytes); const safeId = escapeHtml(attId); 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 += ` -
+
+ ${canDelete ? `` : ''}
`; } @@ -2327,6 +2493,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); if (autoScroll) { el.chatMessages.scrollTop = el.chatMessages.scrollHeight; @@ -2475,16 +2650,28 @@ const fileName = f.originalFileName || f.OriginalFileName || 'file'; const fileBytes = f.fileSizeBytes ?? f.FileSizeBytes ?? 0; const uploader = f.uploaderUsername || f.UploaderUsername || 'User'; + const uploaderId = f.uploaderId || f.UploaderId; const createdAt = f.createdAt || f.CreatedAt; const sizeStr = formatBytes(fileBytes); 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 = `
[^] ${escapeHtml(fileName)}
${sizeStr} | shared by @${escapeHtml(uploader)} on ${dateStr}
- +
+ + ${canDelete ? `` : ''} +
`; const dlBtn = item.querySelector('.btn-download'); if (dlBtn) { @@ -2493,6 +2680,17 @@ 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); }); } @@ -2510,6 +2708,7 @@ if (el.e2eeVaultBtn) el.e2eeVaultBtn.style.display = 'none'; el.logoutBtn.style.display = 'none'; } + renderFiles(); } function showAuthModal() { @@ -3981,6 +4180,7 @@ hideE2eeModal(); updateUserUI(); updateVoiceCallUI(); + updateDesktopNotifBanner(); showAuthModal(); } @@ -4140,9 +4340,43 @@ if (el.toggleWebPushBtn) { el.toggleWebPushBtn.addEventListener('click', toggleWebPushSubscription); } + if (el.headerPushBtn) { + el.headerPushBtn.addEventListener('click', toggleWebPushSubscription); + } + if (el.bannerEnablePushBtn) { + el.bannerEnablePushBtn.addEventListener('click', () => subscribeWebPush(false)); + } + if (el.bannerDismissBtn) { + el.bannerDismissBtn.addEventListener('click', () => { + localStorage.setItem('gsdchat_dismiss_push_banner', 'true'); + if (el.desktopNotifBanner) el.desktopNotifBanner.style.display = 'none'; + }); + } if (el.testWebPushBtn) { el.testWebPushBtn.addEventListener('click', sendTestWebPush); } + + // Mark active conversation inbox items read when focusing or interacting + window.addEventListener('focus', () => { + const isChatTabActive = el.tabViews && Array.from(el.tabViews).some(v => v.id === 'view-chat' && v.classList.contains('active')); + if (isChatTabActive && !document.hidden) { + markActiveChannelInboxRead(); + } + }); + document.addEventListener('visibilitychange', () => { + if (!document.hidden) { + const isChatTabActive = el.tabViews && Array.from(el.tabViews).some(v => v.id === 'view-chat' && v.classList.contains('active')); + if (isChatTabActive) { + markActiveChannelInboxRead(); + } + } + }); + if (el.messageInput) { + el.messageInput.addEventListener('focus', markActiveChannelInboxRead); + } + if (el.chatMessages) { + el.chatMessages.addEventListener('click', markActiveChannelInboxRead); + } if (el.e2eePinForm) { el.e2eePinForm.addEventListener('submit', async (e) => { e.preventDefault(); diff --git a/src/GsDChat.Server/wwwroot/icon.svg b/src/GsDChat.Server/wwwroot/icon.svg new file mode 100644 index 0000000..e6606e7 --- /dev/null +++ b/src/GsDChat.Server/wwwroot/icon.svg @@ -0,0 +1,8 @@ + + GsDChat + + + + + + diff --git a/src/GsDChat.Server/wwwroot/index.html b/src/GsDChat.Server/wwwroot/index.html index 36a18e8..61b119f 100644 --- a/src/GsDChat.Server/wwwroot/index.html +++ b/src/GsDChat.Server/wwwroot/index.html @@ -6,6 +6,7 @@ GsDChat - Web Client + @@ -58,11 +59,25 @@
+ + + +
diff --git a/src/GsDChat.Server/wwwroot/manifest.json b/src/GsDChat.Server/wwwroot/manifest.json index 8f2fb3b..4bebc65 100644 --- a/src/GsDChat.Server/wwwroot/manifest.json +++ b/src/GsDChat.Server/wwwroot/manifest.json @@ -4,7 +4,14 @@ "description": "High-performance terminal-inspired hybrid chat with End-to-End Encryption, Inbox, and Web Push Notifications.", "start_url": "/", "display": "standalone", - "background_color": "#0d1117", - "theme_color": "#00d4ff", - "icons": [] + "background_color": "#11111b", + "theme_color": "#cba6f7", + "icons": [ + { + "src": "/icon.svg", + "sizes": "192x192 512x512", + "type": "image/svg+xml", + "purpose": "any maskable" + } + ] } diff --git a/src/GsDChat.Server/wwwroot/sw.js b/src/GsDChat.Server/wwwroot/sw.js index decab58..90859dd 100644 --- a/src/GsDChat.Server/wwwroot/sw.js +++ b/src/GsDChat.Server/wwwroot/sw.js @@ -1,5 +1,6 @@ // ============================================================================ // GsDChat Service Worker (Web Push Notifications & Background Deep-Linking) +// Functions like WhatsApp Web: delivers notifications even when app is closed. // ============================================================================ self.addEventListener('install', (event) => { @@ -43,15 +44,15 @@ self.addEventListener('push', (event) => { // Check if any open client window is currently focused in the foreground let focusedClient = null; for (const client of windowClients) { - if (client.focused || client.visibilityState === 'visible') { + if (client.focused) { focusedClient = client; break; } } - if (focusedClient && focusedClient.focused) { - // Suppress duplicate OS popup if the user is actively focused on the app; - // notify the foreground window so it can play an indicator if desired. + if (focusedClient) { + // Suppress duplicate OS popup if user is actively focused on the chat window; + // notify the foreground window so it can update badges/chime if desired. focusedClient.postMessage({ type: 'PUSH_RECEIVED_FOREGROUND', payload: payload @@ -63,12 +64,20 @@ self.addEventListener('push', (event) => { ? `gsdchat-${payload.category || 'notif'}-${payload.channelId}` : `gsdchat-item-${payload.itemId || Date.now()}`; - await self.registration.showNotification(payload.title || 'GsDChat', { - body: payload.body || 'New activity in GsDChat', + const notificationOptions = { + body: payload.body || 'New message in GsDChat', + icon: '/icon.svg', + badge: '/icon.svg', tag: tag, renotify: true, - data: payload - }); + vibrate: [200, 100, 200], + data: payload, + actions: [ + { action: 'open', title: 'Open Chat' } + ] + }; + + await self.registration.showNotification(payload.title || 'GsDChat', notificationOptions); })()); }); @@ -76,6 +85,10 @@ self.addEventListener('notificationclick', (event) => { event.notification.close(); const data = event.notification.data || {}; + const targetUrl = data.channelId + ? `/?channel=${encodeURIComponent(data.channelId)}&inboxItem=${encodeURIComponent(data.itemId || '')}` + : '/'; + event.waitUntil((async () => { const windowClients = await self.clients.matchAll({ type: 'window', @@ -95,9 +108,6 @@ self.addEventListener('notificationclick', (event) => { } if (self.clients.openWindow) { - const targetUrl = data.channelId - ? `/?channel=${encodeURIComponent(data.channelId)}&inboxItem=${encodeURIComponent(data.itemId || '')}` - : '/'; await self.clients.openWindow(targetUrl); } })()); diff --git a/tests/GsDChat.Tests/DatabaseTests.cs b/tests/GsDChat.Tests/DatabaseTests.cs index cdebd4c..d4744d5 100644 --- a/tests/GsDChat.Tests/DatabaseTests.cs +++ b/tests/GsDChat.Tests/DatabaseTests.cs @@ -321,4 +321,62 @@ public class DatabaseTests : IDisposable await _db.RemovePushSubscriptionByEndpointAsync("https://push.example.org/send/sub_1"); 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); + } } diff --git a/tests/GsDChat.Tests/EndToEndChatTests.cs b/tests/GsDChat.Tests/EndToEndChatTests.cs index 508e821..061b1ef 100644 --- a/tests/GsDChat.Tests/EndToEndChatTests.cs +++ b/tests/GsDChat.Tests/EndToEndChatTests.cs @@ -234,6 +234,44 @@ public class EndToEndChatTests : IAsyncLifetime 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) => { if (!context.WebSockets.IsWebSocketRequest) @@ -390,6 +428,28 @@ public class EndToEndChatTests : IAsyncLifetime Assert.True(File.Exists(downloadedFilePath)); string downloadedText = await File.ReadAllTextAsync(downloadedFilePath); 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] @@ -1002,6 +1062,42 @@ public class EndToEndChatTests : IAsyncLifetime bobItems = stateBob.GetInboxItems(); Assert.Contains(bobItems, x => x.Category == InboxCategories.FollowedChannel && x.ContentPreview.Contains("Regular update")); + // 4b. Bob looks at / joins #general -> all inbox items for #general are auto-marked read! + await connBob.JoinChannelAsync(generalId); + for (int i = 0; i < 20; i++) + { + if (stateBob.UnreadInboxCount == 0) break; + await Task.Delay(100); + } + Assert.Equal(0, stateBob.UnreadInboxCount); + bobItems = stateBob.GetInboxItems(); + Assert.All(bobItems, item => Assert.True(item.IsRead)); + + // 4c. Alice sends DM to Bob while Bob is in #general -> Bob receives unread DM inbox item + await connAlice.StartDmAsync(stateBob.CurrentUsername, stateBob.CurrentUserId); + for (int i = 0; i < 20; i++) + { + if (stateAlice.DirectMessages.Count > 0 && stateBob.DirectMessages.Count > 0) break; + await Task.Delay(100); + } + string dmId = stateBob.DirectMessages[0].Id; + await connAlice.SendChatMessageAsync(dmId, "Hey Bob, private message here!"); + for (int i = 0; i < 20; i++) + { + if (stateBob.UnreadInboxCount >= 1) break; + await Task.Delay(100); + } + Assert.Equal(1, stateBob.UnreadInboxCount); + + // When Bob opens/looks at the DM -> DM inbox item is marked read! + await connBob.JoinChannelAsync(dmId); + for (int i = 0; i < 20; i++) + { + if (stateBob.UnreadInboxCount == 0) break; + await Task.Delay(100); + } + Assert.Equal(0, stateBob.UnreadInboxCount); + // 5. Bob marks all read and clears read items await connBob.SendInboxActionAsync("mark_all_read"); for (int i = 0; i < 20; i++) diff --git a/tests/GsDChat.Tests/FileStorageServiceTests.cs b/tests/GsDChat.Tests/FileStorageServiceTests.cs index 595cb3c..f331ab9 100644 --- a/tests/GsDChat.Tests/FileStorageServiceTests.cs +++ b/tests/GsDChat.Tests/FileStorageServiceTests.cs @@ -78,4 +78,83 @@ public class FileStorageServiceTests : IDisposable string readBack = await reader.ReadToEndAsync(); 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)); + } } diff --git a/tests/GsDChat.Tests/WebClientStaticTests.cs b/tests/GsDChat.Tests/WebClientStaticTests.cs index 48f6942..fcd2077 100644 --- a/tests/GsDChat.Tests/WebClientStaticTests.cs +++ b/tests/GsDChat.Tests/WebClientStaticTests.cs @@ -109,6 +109,13 @@ public class WebClientStaticTests : IAsyncLifetime Assert.Contains("id=\"navTabInbox\"", html); Assert.Contains("id=\"inboxUnreadBadge\"", html); Assert.Contains("id=\"toggleWebPushBtn\"", html); + Assert.Contains("id=\"navTabInbox\"", html); + Assert.Contains("id=\"inboxUnreadBadge\"", html); + Assert.Contains("id=\"toggleWebPushBtn\"", html); + Assert.Contains("id=\"desktopNotifBanner\"", html); + Assert.Contains("id=\"bannerEnablePushBtn\"", html); + Assert.Contains("id=\"headerPushBtn\"", html); + Assert.Contains("rel=\"icon\"", html); Assert.Contains("id=\"voiceCallBtn\"", html); Assert.Contains("id=\"voiceCallBar\"", html); Assert.Contains("id=\"incomingCallModal\"", html); @@ -128,6 +135,7 @@ public class WebClientStaticTests : IAsyncLifetime Assert.Contains(".conv-security-badge", css); Assert.Contains(".inbox-item", css); Assert.Contains(".inbox-badge", css); + Assert.Contains(".notif-banner", css); Assert.Contains(".voice-call-bar", css); Assert.Contains(".voice-participant-chip", css); Assert.Contains(".incoming-call-card", css); @@ -152,6 +160,10 @@ public class WebClientStaticTests : IAsyncLifetime Assert.Contains("INBOX_SYNC", js); Assert.Contains("INBOX_NEW_ITEM", js); Assert.Contains("subscribeWebPush", js); + Assert.Contains("updateDesktopNotifBanner", js); + Assert.Contains("initServiceWorkerAndPush", js); + Assert.Contains("markActiveChannelInboxRead", js); + Assert.Contains("deleteFile", js); Assert.Contains("VOICE_CALL_START", js); Assert.Contains("VOICE_CALL_STATE", js); Assert.Contains("VOICE_SIGNAL", js); @@ -170,10 +182,26 @@ public class WebClientStaticTests : IAsyncLifetime string swJs = await swRes.Content.ReadAsStringAsync(); Assert.Contains("showNotification", swJs); Assert.Contains("notificationclick", swJs); + Assert.Contains("/icon.svg", swJs); + Assert.Contains("renotify: true", swJs); var manifestRes = await _httpClient.GetAsync("/manifest.json"); Assert.True(manifestRes.IsSuccessStatusCode); string manifestJson = await manifestRes.Content.ReadAsStringAsync(); Assert.Contains("GsDChat", manifestJson); + Assert.Contains("icons", manifestJson); + Assert.Contains("/icon.svg", manifestJson); + } + + [Fact] + public async Task GetIconSvg_ShouldServeValidSvg() + { + Assert.NotNull(_httpClient); + + var iconRes = await _httpClient.GetAsync("/icon.svg"); + Assert.True(iconRes.IsSuccessStatusCode); + string svg = await iconRes.Content.ReadAsStringAsync(); + Assert.Contains("