Merge branch 'master' into p2p_voice_call_turn
This commit is contained in:
commit
fe879781ab
23 changed files with 983 additions and 46 deletions
|
|
@ -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<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()
|
||||
{
|
||||
VoiceManager.Dispose();
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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<InboxItem> 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<InboxItem> GetInboxItems()
|
||||
{
|
||||
lock (_lock)
|
||||
|
|
|
|||
|
|
@ -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; }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<FileSummary> Files { get; set; } = new();
|
||||
|
|
|
|||
|
|
@ -10,9 +10,11 @@ public interface IModEventBus
|
|||
void SubscribeUserDisconnected(Func<User, Task> handler);
|
||||
void SubscribeChannelCreated(Func<Channel, Task> handler);
|
||||
void SubscribeFileUploaded(Func<FileRecord, Task> handler);
|
||||
void SubscribeFileDeleted(Func<FileRecord, Task> handler);
|
||||
|
||||
Task PublishUserConnectedAsync(User user);
|
||||
Task PublishUserDisconnectedAsync(User user);
|
||||
Task PublishChannelCreatedAsync(Channel channel);
|
||||
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<Channel, Task>> _channelCreatedHandlers = 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 SubscribeUserDisconnected(Func<User, Task> handler) => _userDisconnectedHandlers.Add(handler);
|
||||
public void SubscribeChannelCreated(Func<Channel, Task> handler) => _channelCreatedHandlers.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)
|
||||
{
|
||||
|
|
@ -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 { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<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
|
||||
|
||||
#region Inbox, Preferences & Push Subscription Operations
|
||||
|
|
|
|||
|
|
@ -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) =>
|
||||
{
|
||||
|
|
|
|||
|
|
@ -171,6 +171,29 @@ public class FileStorageService
|
|||
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)
|
||||
{
|
||||
if (File.Exists(record.StoragePath))
|
||||
|
|
|
|||
|
|
@ -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");
|
||||
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ public class ChatWebSocketManager
|
|||
private readonly ServerOptions _options;
|
||||
private readonly ILogger<ChatWebSocketManager> _logger;
|
||||
private readonly WebPushService? _webPush;
|
||||
private readonly FileStorageService _fileService;
|
||||
|
||||
// Extensibility hooks for mod system
|
||||
public Func<ChatMessage, Task<ChatMessage?>>? MessagePipelineInterceptor { get; set; }
|
||||
|
|
@ -37,12 +38,14 @@ public class ChatWebSocketManager
|
|||
ChatDatabase db,
|
||||
ServerOptions options,
|
||||
ILogger<ChatWebSocketManager> logger,
|
||||
WebPushService? webPush = null)
|
||||
WebPushService? webPush = null,
|
||||
FileStorageService? fileStorage = null)
|
||||
{
|
||||
_db = db;
|
||||
_options = options;
|
||||
_logger = logger;
|
||||
_webPush = webPush;
|
||||
_fileService = fileStorage ?? new FileStorageService(db, options);
|
||||
}
|
||||
|
||||
public int ConnectedCount => _clients.Count;
|
||||
|
|
@ -253,6 +256,14 @@ public class ChatWebSocketManager
|
|||
}
|
||||
break;
|
||||
|
||||
case MessageTypes.DeleteFile:
|
||||
var delFilePkg = envelope.Unpack<DeleteFilePacket>();
|
||||
if (delFilePkg != null && !string.IsNullOrWhiteSpace(delFilePkg.FileId))
|
||||
{
|
||||
await HandleDeleteFileAsync(client, delFilePkg.FileId, ct);
|
||||
}
|
||||
break;
|
||||
|
||||
case MessageTypes.StartDm:
|
||||
var dmPkg = envelope.Unpack<StartDmPacket>();
|
||||
if (dmPkg != null)
|
||||
|
|
@ -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 <message> - Broadcast an official announcement (Admin/Owner)\n" +
|
||||
" /deletefile <file_id> - Delete an uploaded file (Uploader or Admin)\n" +
|
||||
" /users - List all registered users\n" +
|
||||
" /motd - Display message of the day";
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = helpText, ChannelId = packet.ChannelId }, ct);
|
||||
|
|
@ -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 <file_id>",
|
||||
ChannelId = packet.ChannelId
|
||||
}, ct);
|
||||
break;
|
||||
}
|
||||
string targetFileId = packet.Args.Trim();
|
||||
var fileRec = await _fileService.GetFileRecordAsync(targetFileId);
|
||||
if (fileRec == null)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
||||
{
|
||||
Success = false,
|
||||
Output = $"File '{targetFileId}' not found.",
|
||||
ChannelId = packet.ChannelId
|
||||
}, ct);
|
||||
break;
|
||||
}
|
||||
|
||||
bool canDel = string.Equals(client.User.Id, fileRec.UploaderId, StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(client.User.Username, fileRec.UploaderUsername, StringComparison.OrdinalIgnoreCase) ||
|
||||
client.User.Role == UserRoles.Owner || client.User.Role == UserRoles.Admin;
|
||||
|
||||
if (!canDel)
|
||||
{
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
||||
{
|
||||
Success = false,
|
||||
Output = "You do not have permission to delete this file. Only the uploader or an Admin/Owner can delete it.",
|
||||
ChannelId = packet.ChannelId
|
||||
}, ct);
|
||||
break;
|
||||
}
|
||||
|
||||
await _fileService.DeleteFileAsync(fileRec.Id);
|
||||
await BroadcastFileDeletedAsync(fileRec, client.User.Username);
|
||||
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
|
||||
{
|
||||
Success = true,
|
||||
Output = $"File '{fileRec.OriginalFileName}' was deleted successfully.",
|
||||
ChannelId = packet.ChannelId
|
||||
}, ct);
|
||||
break;
|
||||
|
||||
case "follow":
|
||||
case "unfollow":
|
||||
case "mute":
|
||||
|
|
@ -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<string>(channel!.MemberIds, StringComparer.OrdinalIgnoreCase);
|
||||
await Task.WhenAll(_clients.Values
|
||||
.Where(c => memberSet.Contains(c.User.Id))
|
||||
.Select(c => SendFileListToClientAsync(c)));
|
||||
}
|
||||
else
|
||||
{
|
||||
await Task.WhenAll(_clients.Values.Select(c => SendFileListToClientAsync(c)));
|
||||
}
|
||||
|
||||
string deleterInfo = !string.IsNullOrWhiteSpace(deletedByUsername) ? $" by @{InputSanitizer.SanitizeUsername(deletedByUsername)}" : "";
|
||||
string noticeText = $"File '{file.OriginalFileName}' was deleted{deleterInfo}.";
|
||||
|
||||
if (isPrivateConv)
|
||||
{
|
||||
await BroadcastToMembersAsync(channel!.MemberIds, MessageTypes.SystemNotice, new SystemNoticePacket { Text = noticeText, Level = "Warning" });
|
||||
}
|
||||
else
|
||||
{
|
||||
await BroadcastToChannelAsync(file.ChannelId, MessageTypes.SystemNotice, new SystemNoticePacket { Text = noticeText, Level = "Warning" });
|
||||
}
|
||||
}
|
||||
|
||||
#region Inbox & Notification Processing
|
||||
|
||||
public async Task SendInboxSyncToClientAsync(ConnectedClient client, CancellationToken ct = default)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
========================================================================== */
|
||||
|
|
|
|||
|
|
@ -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,19 +993,23 @@
|
|||
|
||||
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({
|
||||
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;
|
||||
if (state.socket && state.socket.readyState === WebSocket.OPEN) {
|
||||
sendEnvelope('UPDATE_INBOX_PREFERENCES', {
|
||||
mentionsEnabled: state.inboxPreferences.mentionsEnabled,
|
||||
announcementsEnabled: state.inboxPreferences.announcementsEnabled,
|
||||
|
|
@ -954,13 +1017,16 @@
|
|||
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 += `
|
||||
<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}">
|
||||
[^] ${safeName} (${sizeStr})
|
||||
</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>
|
||||
`;
|
||||
}
|
||||
|
|
@ -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 = `
|
||||
<div class="file-meta">
|
||||
<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>
|
||||
<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');
|
||||
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();
|
||||
|
|
|
|||
8
src/GsDChat.Server/wwwroot/icon.svg
Normal file
8
src/GsDChat.Server/wwwroot/icon.svg
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 192" width="192" height="192">
|
||||
<title>GsDChat</title>
|
||||
<rect width="192" height="192" fill="#11111b" rx="28"/>
|
||||
<rect x="8" y="8" width="176" height="176" fill="#181825" stroke="#cba6f7" stroke-width="4" rx="20"/>
|
||||
<!-- Terminal Prompt >_ -->
|
||||
<path d="M48 64 L84 96 L48 128" fill="none" stroke="#a6e3a1" stroke-width="14" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<line x1="102" y1="128" x2="148" y2="128" stroke="#89b4fa" stroke-width="14" stroke-linecap="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 546 B |
|
|
@ -6,6 +6,7 @@
|
|||
<meta name="theme-color" content="#11111b">
|
||||
<meta name="color-scheme" content="dark">
|
||||
<title>GsDChat - Web Client</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/icon.svg">
|
||||
<link rel="manifest" href="/manifest.json">
|
||||
<!-- Preload stylesheet to prevent flash of unstyled content and forced layout reflow -->
|
||||
<link rel="preload" href="/app.css" as="style">
|
||||
|
|
@ -58,11 +59,25 @@
|
|||
<span class="user-name" id="currentUsername"></span>
|
||||
<span class="user-role" id="currentUserRole"></span>
|
||||
</div>
|
||||
<button class="btn btn-secondary btn-sm" id="headerPushBtn" title="Toggle background Web Push notifications" style="display:none;">[🔔 Push: OFF]</button>
|
||||
<button class="btn btn-secondary btn-sm" id="e2eeVaultBtn" title="Manage E2EE PIN Vault & Encryption Settings" style="display:none;">[🔒 E2EE Vault]</button>
|
||||
<button class="btn btn-outline-danger btn-sm" id="logoutBtn" title="Logout">[Disconnect]</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<!-- WhatsApp Web Style Desktop Notifications Opt-in Banner -->
|
||||
<div id="desktopNotifBanner" class="notif-banner" style="display:none;">
|
||||
<div class="notif-banner-icon">🔔</div>
|
||||
<div class="notif-banner-body">
|
||||
<span class="notif-banner-title">Get notified of new messages</span>
|
||||
<span class="notif-banner-desc">Turn on desktop notifications to receive alerts even when GsDChat is closed.</span>
|
||||
</div>
|
||||
<div class="notif-banner-actions">
|
||||
<button type="button" class="btn btn-sm btn-primary" id="bannerEnablePushBtn">[ Turn on desktop notifications > ]</button>
|
||||
<button type="button" class="notif-banner-dismiss" id="bannerDismissBtn" title="Dismiss">✕</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Main Views Container -->
|
||||
<main class="app-main">
|
||||
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
})());
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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++)
|
||||
|
|
|
|||
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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("<svg", svg);
|
||||
Assert.Contains("GsDChat", svg);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue