Add persistent Inbox and RFC 8291/8292 Web Push notification system

This commit is contained in:
tyuXX 2026-10-31 15:41:51 +03:00
parent 4714d25724
commit 7cc9ba7f4d
27 changed files with 3573 additions and 17 deletions

View file

@ -17,6 +17,11 @@ public class ServerOptions
public bool AllowDmE2ee { get; set; } = true;
public int MaxGroupChatUsers { get; set; } = 10;
// Web Push (VAPID RFC 8292)
public string? VapidPublicKey { get; set; }
public string? VapidPrivateKey { get; set; }
public string VapidSubject { get; set; } = "mailto:admin@gsdchat.local";
// Security Settings
public int RateLimitRequestsPerMinute { get; set; } = 60;
public int MaxConnectionsPerIp { get; set; } = 10;

View file

@ -1,6 +1,7 @@
using System;
using System.IO;
using System.Text.Json;
using GsDChat.Core.Security;
namespace GsDChat.Server.Configuration;
@ -87,6 +88,13 @@ public class ServerSettingsManager
options.MaxGroupChatUsers = 2;
}
if (string.IsNullOrWhiteSpace(options.VapidPublicKey) || string.IsNullOrWhiteSpace(options.VapidPrivateKey))
{
var (pub, priv) = WebPushCrypto.GenerateVapidKeys();
options.VapidPublicKey = pub;
options.VapidPrivateKey = priv;
}
Save(options);
return options;
}

View file

@ -155,6 +155,72 @@ public class ChatDatabase : IDisposable
);
""");
// Create inbox, preferences, channel follows, and push subscriptions tables
await TryExecuteTableMigrationAsync(conn, """
CREATE TABLE IF NOT EXISTS inbox_items (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
channel_id TEXT NOT NULL,
channel_name TEXT NOT NULL,
channel_type TEXT NOT NULL DEFAULT 'Channel',
message_id TEXT,
sender_id TEXT NOT NULL,
sender_username TEXT NOT NULL,
category TEXT NOT NULL,
content_preview TEXT NOT NULL,
is_encrypted INTEGER NOT NULL DEFAULT 0,
sender_public_key TEXT,
recipient_public_key TEXT,
is_read INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
FOREIGN KEY (channel_id) REFERENCES channels (id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_inbox_user_created
ON inbox_items(user_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_inbox_user_unread
ON inbox_items(user_id, is_read);
CREATE TABLE IF NOT EXISTS inbox_preferences (
user_id TEXT PRIMARY KEY,
mentions_enabled INTEGER NOT NULL DEFAULT 1,
announcements_enabled INTEGER NOT NULL DEFAULT 1,
direct_messages_enabled INTEGER NOT NULL DEFAULT 1,
followed_channels_enabled INTEGER NOT NULL DEFAULT 1,
push_notifications_enabled INTEGER NOT NULL DEFAULT 1,
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS channel_follows (
user_id TEXT NOT NULL,
channel_id TEXT NOT NULL,
mode TEXT NOT NULL DEFAULT 'Followed',
updated_at TEXT NOT NULL,
PRIMARY KEY (user_id, channel_id),
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE,
FOREIGN KEY (channel_id) REFERENCES channels (id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_channel_follows_user
ON channel_follows(user_id);
CREATE TABLE IF NOT EXISTS push_subscriptions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
endpoint TEXT NOT NULL UNIQUE,
p256dh TEXT NOT NULL,
auth TEXT NOT NULL,
user_agent TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_push_subscriptions_user
ON push_subscriptions(user_id);
""");
// Seed default channels if none exist
var channelsCountCmd = conn.CreateCommand();
channelsCountCmd.CommandText = "SELECT COUNT(*) FROM channels WHERE type = 'Channel';";
@ -642,6 +708,8 @@ public class ChatDatabase : IDisposable
using var cleanupCmd = conn.CreateCommand();
cleanupCmd.CommandText = """
DELETE FROM inbox_items WHERE channel_id = @id;
DELETE FROM channel_follows WHERE channel_id = @id;
DELETE FROM files WHERE channel_id = @id;
DELETE FROM messages WHERE channel_id = @id;
DELETE FROM channel_members WHERE channel_id = @id;
@ -1265,6 +1333,365 @@ public class ChatDatabase : IDisposable
#endregion
#region Inbox, Preferences & Push Subscription Operations
public async Task CreateInboxItemAsync(InboxItem item)
{
using var conn = CreateConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = """
INSERT INTO inbox_items (
id, user_id, channel_id, channel_name, channel_type, message_id,
sender_id, sender_username, category, content_preview,
is_encrypted, sender_public_key, recipient_public_key, is_read, created_at
)
VALUES (
@id, @user_id, @channel_id, @channel_name, @channel_type, @message_id,
@sender_id, @sender_username, @category, @content_preview,
@is_encrypted, @sender_public_key, @recipient_public_key, @is_read, @created_at
);
""";
cmd.Parameters.AddWithValue("@id", item.Id);
cmd.Parameters.AddWithValue("@user_id", item.UserId);
cmd.Parameters.AddWithValue("@channel_id", item.ChannelId);
cmd.Parameters.AddWithValue("@channel_name", item.ChannelName ?? string.Empty);
cmd.Parameters.AddWithValue("@channel_type", string.IsNullOrWhiteSpace(item.ChannelType) ? ChannelTypes.Channel : item.ChannelType);
cmd.Parameters.AddWithValue("@message_id", (object?)item.MessageId ?? DBNull.Value);
cmd.Parameters.AddWithValue("@sender_id", item.SenderId ?? string.Empty);
cmd.Parameters.AddWithValue("@sender_username", item.SenderUsername ?? string.Empty);
cmd.Parameters.AddWithValue("@category", item.Category ?? InboxCategories.Mention);
cmd.Parameters.AddWithValue("@content_preview", item.ContentPreview ?? string.Empty);
cmd.Parameters.AddWithValue("@is_encrypted", item.IsEncrypted ? 1 : 0);
cmd.Parameters.AddWithValue("@sender_public_key", (object?)item.SenderPublicKey ?? DBNull.Value);
cmd.Parameters.AddWithValue("@recipient_public_key", (object?)item.RecipientPublicKey ?? DBNull.Value);
cmd.Parameters.AddWithValue("@is_read", item.IsRead ? 1 : 0);
cmd.Parameters.AddWithValue("@created_at", item.CreatedAt.ToString("O"));
await cmd.ExecuteNonQueryAsync();
}
public async Task<List<InboxItem>> GetInboxItemsForUserAsync(string userId, int limit = 100)
{
var items = new List<InboxItem>();
using var conn = CreateConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = """
SELECT id, user_id, channel_id, channel_name, channel_type, message_id,
sender_id, sender_username, category, content_preview,
is_encrypted, sender_public_key, recipient_public_key, is_read, created_at
FROM inbox_items
WHERE user_id = @uid
ORDER BY created_at DESC
LIMIT @limit;
""";
cmd.Parameters.AddWithValue("@uid", userId);
cmd.Parameters.AddWithValue("@limit", Math.Clamp(limit, 1, 500));
using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
items.Add(new InboxItem
{
Id = reader.GetString(0),
UserId = reader.GetString(1),
ChannelId = reader.GetString(2),
ChannelName = reader.GetString(3),
ChannelType = reader.GetString(4),
MessageId = reader.IsDBNull(5) ? null : reader.GetString(5),
SenderId = reader.GetString(6),
SenderUsername = reader.GetString(7),
Category = reader.GetString(8),
ContentPreview = reader.GetString(9),
IsEncrypted = !reader.IsDBNull(10) && reader.GetInt32(10) == 1,
SenderPublicKey = reader.IsDBNull(11) ? null : reader.GetString(11),
RecipientPublicKey = reader.IsDBNull(12) ? null : reader.GetString(12),
IsRead = !reader.IsDBNull(13) && reader.GetInt32(13) == 1,
CreatedAt = DateTime.Parse(reader.GetString(14))
});
}
return items;
}
public async Task<int> GetUnreadInboxCountAsync(string userId)
{
using var conn = CreateConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT COUNT(*) FROM inbox_items WHERE user_id = @uid AND is_read = 0;";
cmd.Parameters.AddWithValue("@uid", userId);
var res = await cmd.ExecuteScalarAsync();
return Convert.ToInt32(res);
}
public async Task<bool> MarkInboxItemReadAsync(string userId, string itemId)
{
using var conn = CreateConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = "UPDATE inbox_items SET is_read = 1 WHERE user_id = @uid AND id = @id;";
cmd.Parameters.AddWithValue("@uid", userId);
cmd.Parameters.AddWithValue("@id", itemId);
return (await cmd.ExecuteNonQueryAsync()) > 0;
}
public async Task<int> MarkChannelInboxItemsReadAsync(string userId, string channelId)
{
using var conn = CreateConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = "UPDATE inbox_items SET is_read = 1 WHERE user_id = @uid AND channel_id = @cid AND is_read = 0;";
cmd.Parameters.AddWithValue("@uid", userId);
cmd.Parameters.AddWithValue("@cid", channelId);
return await cmd.ExecuteNonQueryAsync();
}
public async Task<int> MarkAllInboxItemsReadAsync(string userId)
{
using var conn = CreateConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = "UPDATE inbox_items SET is_read = 1 WHERE user_id = @uid AND is_read = 0;";
cmd.Parameters.AddWithValue("@uid", userId);
return await cmd.ExecuteNonQueryAsync();
}
public async Task<bool> DeleteInboxItemAsync(string userId, string itemId)
{
using var conn = CreateConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = "DELETE FROM inbox_items WHERE user_id = @uid AND id = @id;";
cmd.Parameters.AddWithValue("@uid", userId);
cmd.Parameters.AddWithValue("@id", itemId);
return (await cmd.ExecuteNonQueryAsync()) > 0;
}
public async Task<int> ClearInboxItemsAsync(string userId, bool onlyRead)
{
using var conn = CreateConnection();
using var cmd = conn.CreateCommand();
if (onlyRead)
{
cmd.CommandText = "DELETE FROM inbox_items WHERE user_id = @uid AND is_read = 1;";
}
else
{
cmd.CommandText = "DELETE FROM inbox_items WHERE user_id = @uid;";
}
cmd.Parameters.AddWithValue("@uid", userId);
return await cmd.ExecuteNonQueryAsync();
}
public async Task<InboxPreferences> GetInboxPreferencesAsync(string userId)
{
var prefs = new InboxPreferences
{
UserId = userId,
MentionsEnabled = true,
AnnouncementsEnabled = true,
DirectMessagesEnabled = true,
FollowedChannelsEnabled = true,
PushNotificationsEnabled = true
};
using var conn = CreateConnection();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = """
SELECT mentions_enabled, announcements_enabled, direct_messages_enabled, followed_channels_enabled, push_notifications_enabled
FROM inbox_preferences
WHERE user_id = @uid
LIMIT 1;
""";
cmd.Parameters.AddWithValue("@uid", userId);
using var reader = await cmd.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
prefs.MentionsEnabled = reader.GetInt32(0) == 1;
prefs.AnnouncementsEnabled = reader.GetInt32(1) == 1;
prefs.DirectMessagesEnabled = reader.GetInt32(2) == 1;
prefs.FollowedChannelsEnabled = reader.GetInt32(3) == 1;
prefs.PushNotificationsEnabled = reader.GetInt32(4) == 1;
}
}
using (var fCmd = conn.CreateCommand())
{
fCmd.CommandText = "SELECT channel_id, mode FROM channel_follows WHERE user_id = @uid;";
fCmd.Parameters.AddWithValue("@uid", userId);
using var fReader = await fCmd.ExecuteReaderAsync();
while (await fReader.ReadAsync())
{
string cid = fReader.GetString(0);
string mode = fReader.GetString(1);
if (string.Equals(mode, ConversationFollowModes.Followed, StringComparison.OrdinalIgnoreCase))
{
prefs.FollowedChannelIds.Add(cid);
}
else if (string.Equals(mode, ConversationFollowModes.Muted, StringComparison.OrdinalIgnoreCase))
{
prefs.MutedChannelIds.Add(cid);
}
}
}
return prefs;
}
public async Task SaveInboxPreferencesAsync(InboxPreferences prefs)
{
using var conn = CreateConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = """
INSERT INTO inbox_preferences (
user_id, mentions_enabled, announcements_enabled, direct_messages_enabled, followed_channels_enabled, push_notifications_enabled
)
VALUES (
@uid, @mentions, @announcements, @dms, @followed, @push
)
ON CONFLICT(user_id) DO UPDATE SET
mentions_enabled = @mentions,
announcements_enabled = @announcements,
direct_messages_enabled = @dms,
followed_channels_enabled = @followed,
push_notifications_enabled = @push;
""";
cmd.Parameters.AddWithValue("@uid", prefs.UserId);
cmd.Parameters.AddWithValue("@mentions", prefs.MentionsEnabled ? 1 : 0);
cmd.Parameters.AddWithValue("@announcements", prefs.AnnouncementsEnabled ? 1 : 0);
cmd.Parameters.AddWithValue("@dms", prefs.DirectMessagesEnabled ? 1 : 0);
cmd.Parameters.AddWithValue("@followed", prefs.FollowedChannelsEnabled ? 1 : 0);
cmd.Parameters.AddWithValue("@push", prefs.PushNotificationsEnabled ? 1 : 0);
await cmd.ExecuteNonQueryAsync();
}
public async Task SetChannelFollowModeAsync(string userId, string channelId, string mode)
{
using var conn = CreateConnection();
using var cmd = conn.CreateCommand();
if (string.Equals(mode, ConversationFollowModes.Default, StringComparison.OrdinalIgnoreCase))
{
cmd.CommandText = "DELETE FROM channel_follows WHERE user_id = @uid AND channel_id = @cid;";
cmd.Parameters.AddWithValue("@uid", userId);
cmd.Parameters.AddWithValue("@cid", channelId);
}
else
{
cmd.CommandText = """
INSERT INTO channel_follows (user_id, channel_id, mode, updated_at)
VALUES (@uid, @cid, @mode, @now)
ON CONFLICT(user_id, channel_id) DO UPDATE SET mode = @mode, updated_at = @now;
""";
cmd.Parameters.AddWithValue("@uid", userId);
cmd.Parameters.AddWithValue("@cid", channelId);
cmd.Parameters.AddWithValue("@mode", mode);
cmd.Parameters.AddWithValue("@now", DateTime.UtcNow.ToString("O"));
}
await cmd.ExecuteNonQueryAsync();
}
public async Task<bool> ToggleChannelFollowAsync(string userId, Channel channel, bool? explicitFollow = null)
{
var prefs = await GetInboxPreferencesAsync(userId);
bool isPublicChannel = channel.Type == ChannelTypes.Channel;
if (isPublicChannel)
{
bool currentlyFollowed = prefs.FollowedChannelIds.Contains(channel.Id, StringComparer.OrdinalIgnoreCase);
bool nextFollow = explicitFollow ?? !currentlyFollowed;
await SetChannelFollowModeAsync(
userId,
channel.Id,
nextFollow ? ConversationFollowModes.Followed : ConversationFollowModes.Default);
return nextFollow;
}
else
{
// DMs & Group Chats are followed by default unless Muted
bool currentlyMuted = prefs.MutedChannelIds.Contains(channel.Id, StringComparer.OrdinalIgnoreCase);
bool currentlyFollowed = !currentlyMuted;
bool nextFollow = explicitFollow ?? !currentlyFollowed;
await SetChannelFollowModeAsync(
userId,
channel.Id,
nextFollow ? ConversationFollowModes.Default : ConversationFollowModes.Muted);
return nextFollow;
}
}
public async Task SavePushSubscriptionAsync(PushSubscriptionRecord sub)
{
using var conn = CreateConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = """
INSERT INTO push_subscriptions (id, user_id, endpoint, p256dh, auth, user_agent, created_at)
VALUES (@id, @uid, @endpoint, @p256dh, @auth, @ua, @created_at)
ON CONFLICT(endpoint) DO UPDATE SET
user_id = @uid,
p256dh = @p256dh,
auth = @auth,
user_agent = @ua,
created_at = @created_at;
""";
cmd.Parameters.AddWithValue("@id", sub.Id);
cmd.Parameters.AddWithValue("@uid", sub.UserId);
cmd.Parameters.AddWithValue("@endpoint", sub.Endpoint);
cmd.Parameters.AddWithValue("@p256dh", sub.P256dh);
cmd.Parameters.AddWithValue("@auth", sub.Auth);
cmd.Parameters.AddWithValue("@ua", sub.UserAgent ?? string.Empty);
cmd.Parameters.AddWithValue("@created_at", sub.CreatedAt.ToString("O"));
await cmd.ExecuteNonQueryAsync();
}
public async Task<bool> RemovePushSubscriptionAsync(string userId, string endpoint)
{
using var conn = CreateConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = "DELETE FROM push_subscriptions WHERE user_id = @uid AND endpoint = @endpoint;";
cmd.Parameters.AddWithValue("@uid", userId);
cmd.Parameters.AddWithValue("@endpoint", endpoint);
return (await cmd.ExecuteNonQueryAsync()) > 0;
}
public async Task<bool> RemovePushSubscriptionByEndpointAsync(string endpoint)
{
using var conn = CreateConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = "DELETE FROM push_subscriptions WHERE endpoint = @endpoint;";
cmd.Parameters.AddWithValue("@endpoint", endpoint);
return (await cmd.ExecuteNonQueryAsync()) > 0;
}
public async Task<List<PushSubscriptionRecord>> GetPushSubscriptionsForUserAsync(string userId)
{
var subs = new List<PushSubscriptionRecord>();
using var conn = CreateConnection();
using var cmd = conn.CreateCommand();
cmd.CommandText = """
SELECT id, user_id, endpoint, p256dh, auth, user_agent, created_at
FROM push_subscriptions
WHERE user_id = @uid
ORDER BY created_at DESC;
""";
cmd.Parameters.AddWithValue("@uid", userId);
using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
subs.Add(new PushSubscriptionRecord
{
Id = reader.GetString(0),
UserId = reader.GetString(1),
Endpoint = reader.GetString(2),
P256dh = reader.GetString(3),
Auth = reader.GetString(4),
UserAgent = reader.GetString(5),
CreatedAt = DateTime.Parse(reader.GetString(6))
});
}
return subs;
}
#endregion
public void Dispose()
{
// SQLite in-process connections are pooled and closed as needed

View file

@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using GsDChat.Core.Models;
using GsDChat.Core.Protocol;
using GsDChat.Server.Configuration;
using GsDChat.Server.Data;
@ -112,6 +113,7 @@ builder.WebHost.ConfigureKestrel(kestrel =>
builder.Services.AddSingleton(sp => new ChatDatabase(serverOptions.DataDirectory));
builder.Services.AddSingleton<IAuthService, AuthService>();
builder.Services.AddSingleton<FileStorageService>();
builder.Services.AddSingleton<WebPushService>();
builder.Services.AddSingleton<ChatWebSocketManager>();
builder.Services.AddSingleton<ModLoaderService>();
builder.Services.AddSingleton<RateLimitService>();
@ -148,6 +150,8 @@ app.Use(async (context, next) =>
context.Response.Headers.Append("Content-Security-Policy",
"default-src 'self'; " +
"script-src 'self' 'unsafe-inline'; " +
"worker-src 'self'; " +
"manifest-src 'self'; " +
"style-src 'self' 'unsafe-inline'; " +
"img-src 'self' data:; " +
"font-src 'self'; " +
@ -213,10 +217,74 @@ app.MapGet("/api/info", (ServerOptions opt, IAuthService auth, HttpRequest req)
MaxFileSizeMb = opt.MaxFileSizeMb,
AllowMemberChannelCreation = opt.AllowMemberChannelCreation,
AllowDmE2ee = opt.AllowDmE2ee,
MaxGroupChatUsers = opt.MaxGroupChatUsers
MaxGroupChatUsers = opt.MaxGroupChatUsers,
VapidPublicKey = opt.VapidPublicKey
});
});
// Web Push Endpoints
app.MapGet("/api/push/vapid-public-key", (ServerOptions opt) =>
{
return Results.Ok(new { publicKey = opt.VapidPublicKey ?? string.Empty });
});
app.MapPost("/api/push/subscribe", async (PushSubscribeRequest req, HttpRequest httpReq, IAuthService auth, ChatDatabase chatDb) =>
{
string? token = ExtractBearerToken(httpReq);
var user = await auth.ValidateSessionTokenAsync(token ?? "");
if (user == null)
{
return Results.Unauthorized();
}
if (string.IsNullOrWhiteSpace(req.Endpoint) || string.IsNullOrWhiteSpace(req.P256dh) || string.IsNullOrWhiteSpace(req.Auth))
{
return Results.BadRequest(new { success = false, error = "Invalid push subscription parameters." });
}
await chatDb.SavePushSubscriptionAsync(new PushSubscriptionRecord
{
UserId = user.Id,
Endpoint = req.Endpoint.Trim(),
P256dh = req.P256dh.Trim(),
Auth = req.Auth.Trim(),
UserAgent = req.UserAgent ?? httpReq.Headers.UserAgent.ToString()
});
return Results.Ok(new { success = true });
});
app.MapPost("/api/push/unsubscribe", async (PushUnsubscribeRequest req, HttpRequest httpReq, IAuthService auth, ChatDatabase chatDb) =>
{
string? token = ExtractBearerToken(httpReq);
var user = await auth.ValidateSessionTokenAsync(token ?? "");
if (user == null)
{
return Results.Unauthorized();
}
if (string.IsNullOrWhiteSpace(req.Endpoint))
{
return Results.BadRequest(new { success = false, error = "Endpoint required." });
}
await chatDb.RemovePushSubscriptionAsync(user.Id, req.Endpoint.Trim());
return Results.Ok(new { success = true });
});
app.MapPost("/api/push/test", async (HttpRequest httpReq, IAuthService auth, WebPushService webPush) =>
{
string? token = ExtractBearerToken(httpReq);
var user = await auth.ValidateSessionTokenAsync(token ?? "");
if (user == null)
{
return Results.Unauthorized();
}
bool sent = await webPush.SendTestPushAsync(user.Id, user.Username);
return Results.Ok(new { success = sent });
});
app.MapPost("/api/auth/register", async (RegisterRequest req, IAuthService auth, RateLimitService rateLimiter, CsrfProtectionService csrf, HttpContext context) =>
{
string clientIp = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";

View file

@ -0,0 +1,209 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using GsDChat.Core.Models;
using GsDChat.Core.Security;
using GsDChat.Server.Configuration;
using GsDChat.Server.Data;
namespace GsDChat.Server.Services;
public class WebPushNotificationPayload
{
public string Title { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public string ChannelId { get; set; } = string.Empty;
public string ChannelName { get; set; } = string.Empty;
public string Category { get; set; } = string.Empty;
public string ItemId { get; set; } = string.Empty;
public string SenderUsername { get; set; } = string.Empty;
public string Timestamp { get; set; } = string.Empty;
}
public class WebPushService : IDisposable
{
private static readonly JsonSerializerOptions s_jsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
private readonly ChatDatabase _db;
private readonly ServerOptions _options;
private readonly ILogger<WebPushService> _logger;
private readonly HttpClient _httpClient;
public WebPushService(
ChatDatabase db,
ServerOptions options,
ILogger<WebPushService> logger,
HttpMessageHandler? customHandler = null)
{
_db = db;
_options = options;
_logger = logger;
if (string.IsNullOrWhiteSpace(_options.VapidPublicKey) || string.IsNullOrWhiteSpace(_options.VapidPrivateKey))
{
var (pub, priv) = WebPushCrypto.GenerateVapidKeys();
_options.VapidPublicKey = pub;
_options.VapidPrivateKey = priv;
}
_httpClient = customHandler != null
? new HttpClient(customHandler) { Timeout = TimeSpan.FromSeconds(10) }
: new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
}
public string VapidPublicKey => _options.VapidPublicKey ?? string.Empty;
public static WebPushNotificationPayload BuildNotificationPayload(InboxItem item, string serverName)
{
string sender = string.IsNullOrWhiteSpace(item.SenderUsername) ? "System" : item.SenderUsername;
string chName = string.IsNullOrWhiteSpace(item.ChannelName) ? "chat" : item.ChannelName;
string title = item.Category switch
{
InboxCategories.Mention => $"@{sender} mentioned you in {(item.ChannelType == ChannelTypes.Channel ? "#" + chName : chName)}",
InboxCategories.Announcement => $"📢 Announcement from @{sender}",
InboxCategories.DirectMessage => $"Direct Message from @{sender}",
InboxCategories.GroupMessage => $"@{sender} in [Group] {chName}",
InboxCategories.GroupInvite => $"Group Chat Invitation: {chName}",
_ => $"@{sender} in #{chName}"
};
bool isEncrypted = item.IsEncrypted || E2eeCrypto.IsEncryptedPayload(item.ContentPreview);
string body;
if (isEncrypted)
{
body = $"🔒 New encrypted message from @{sender}";
}
else
{
string raw = item.ContentPreview ?? string.Empty;
body = raw.Length > 180 ? raw[..177] + "..." : raw;
}
return new WebPushNotificationPayload
{
Title = title,
Body = body,
ChannelId = item.ChannelId,
ChannelName = chName,
Category = item.Category,
ItemId = item.Id,
SenderUsername = sender,
Timestamp = item.CreatedAt.ToString("O")
};
}
public async Task SendPushForInboxItemAsync(InboxItem item, InboxPreferences? prefs = null, CancellationToken ct = default)
{
try
{
var effectivePrefs = prefs ?? await _db.GetInboxPreferencesAsync(item.UserId);
if (!effectivePrefs.PushNotificationsEnabled)
{
return;
}
var subscriptions = await _db.GetPushSubscriptionsForUserAsync(item.UserId);
if (subscriptions.Count == 0)
{
return;
}
var payload = BuildNotificationPayload(item, _options.ServerName);
byte[] jsonBytes = JsonSerializer.SerializeToUtf8Bytes(payload, s_jsonOptions);
var sendTasks = new List<Task>(subscriptions.Count);
foreach (var sub in subscriptions)
{
sendTasks.Add(DeliverToSubscriptionAsync(sub, jsonBytes, ct));
}
await Task.WhenAll(sendTasks);
}
catch (Exception ex)
{
SafeLogger.LogWarning(_logger, "Error sending Web Push notifications for user {UserId}: {Msg}", item.UserId, ex.Message);
}
}
public async Task<bool> SendTestPushAsync(string userId, string username, CancellationToken ct = default)
{
var subscriptions = await _db.GetPushSubscriptionsForUserAsync(userId);
if (subscriptions.Count == 0)
{
return false;
}
var payload = new WebPushNotificationPayload
{
Title = $"{_options.ServerName} Push Active",
Body = $"Push notifications are configured for @{username}!",
ChannelId = string.Empty,
ChannelName = "inbox",
Category = InboxCategories.Announcement,
ItemId = Guid.NewGuid().ToString("N"),
SenderUsername = "System",
Timestamp = DateTime.UtcNow.ToString("O")
};
byte[] jsonBytes = JsonSerializer.SerializeToUtf8Bytes(payload, s_jsonOptions);
foreach (var sub in subscriptions)
{
await DeliverToSubscriptionAsync(sub, jsonBytes, ct);
}
return true;
}
private async Task DeliverToSubscriptionAsync(PushSubscriptionRecord sub, byte[] plaintextBytes, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(_options.VapidPublicKey) || string.IsNullOrWhiteSpace(_options.VapidPrivateKey))
{
return;
}
try
{
byte[] encrypted = WebPushCrypto.EncryptPayload(plaintextBytes, sub.P256dh, sub.Auth);
string vapidHeader = WebPushCrypto.CreateVapidAuthorizationHeader(
sub.Endpoint,
_options.VapidSubject,
_options.VapidPublicKey,
_options.VapidPrivateKey);
using var request = new HttpRequestMessage(HttpMethod.Post, sub.Endpoint);
request.Headers.TryAddWithoutValidation("Authorization", vapidHeader);
request.Headers.TryAddWithoutValidation("TTL", "86400");
request.Headers.TryAddWithoutValidation("Urgency", "high");
var content = new ByteArrayContent(encrypted);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
content.Headers.ContentEncoding.Add("aes128gcm");
request.Content = content;
using var response = await _httpClient.SendAsync(request, ct);
if (response.StatusCode == HttpStatusCode.Gone || response.StatusCode == HttpStatusCode.NotFound)
{
await _db.RemovePushSubscriptionByEndpointAsync(sub.Endpoint);
}
}
catch (Exception ex)
{
SafeLogger.LogDebug(_logger, "Web Push delivery failed for endpoint: {Msg}", ex.Message);
}
}
public void Dispose()
{
_httpClient.Dispose();
}
}

View file

@ -5,6 +5,7 @@ using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
@ -23,17 +24,23 @@ public class ChatWebSocketManager
private readonly ChatDatabase _db;
private readonly ServerOptions _options;
private readonly ILogger<ChatWebSocketManager> _logger;
private readonly WebPushService? _webPush;
// Extensibility hooks for mod system
public Func<ChatMessage, Task<ChatMessage?>>? MessagePipelineInterceptor { get; set; }
public Func<string, string, ConnectedClient, Task<CommandResultPacket?>>? CommandInterceptor { get; set; }
public Func<ServerUiSync>? UiSyncProvider { get; set; }
public ChatWebSocketManager(ChatDatabase db, ServerOptions options, ILogger<ChatWebSocketManager> logger)
public ChatWebSocketManager(
ChatDatabase db,
ServerOptions options,
ILogger<ChatWebSocketManager> logger,
WebPushService? webPush = null)
{
_db = db;
_options = options;
_logger = logger;
_webPush = webPush;
}
public int ConnectedCount => _clients.Count;
@ -92,6 +99,9 @@ public class ChatWebSocketManager
// Send Files List (filtered for user access)
await SendFileListToClientAsync(client, cancellationToken);
// Send Initial Inbox & Preferences Sync
await SendInboxSyncToClientAsync(client, cancellationToken);
// Send Initial User List
var initialUsers = await _db.GetAllUsersAsync();
var onlineIds = new HashSet<string>(_clients.Values.Select(c => c.User.Id), StringComparer.OrdinalIgnoreCase);
@ -280,6 +290,34 @@ public class ChatWebSocketManager
}
break;
case MessageTypes.InboxSync:
await SendInboxSyncToClientAsync(client, ct);
break;
case MessageTypes.InboxAction:
var inboxAct = envelope.Unpack<InboxActionPacket>();
if (inboxAct != null)
{
await HandleInboxActionAsync(client, inboxAct, ct);
}
break;
case MessageTypes.UpdateInboxPreferences:
var prefsPkg = envelope.Unpack<UpdateInboxPreferencesPacket>();
if (prefsPkg != null)
{
await HandleUpdateInboxPreferencesAsync(client, prefsPkg, ct);
}
break;
case MessageTypes.ToggleFollowChannel:
var followPkg = envelope.Unpack<ToggleFollowChannelPacket>();
if (followPkg != null)
{
await HandleToggleFollowChannelAsync(client, followPkg, ct);
}
break;
case MessageTypes.UserListSync:
case "GET_USERS":
await BroadcastUserListAsync();
@ -515,6 +553,13 @@ public class ChatWebSocketManager
await _db.SaveMessageAsync(message);
// If sender had unread inbox items in this conversation, mark them read
int senderMarked = await _db.MarkChannelInboxItemsReadAsync(client.User.Id, channelId);
if (senderMarked > 0)
{
await SyncInboxForUserAsync(client.User.Id, ct);
}
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
{
await BroadcastToMembersAsync(channel.MemberIds, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = message });
@ -523,6 +568,8 @@ public class ChatWebSocketManager
{
await BroadcastToChannelAsync(channelId, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = message });
}
await ProcessMessageInboxNotificationsAsync(channel, message, ct);
}
private async Task HandleJoinChannelAsync(ConnectedClient client, string channelId, CancellationToken ct)
@ -546,6 +593,12 @@ public class ChatWebSocketManager
client.ActiveChannelId = channelId;
int markedRead = await _db.MarkChannelInboxItemsReadAsync(client.User.Id, channelId);
if (markedRead > 0)
{
await SyncInboxForUserAsync(client.User.Id, ct);
}
await SendChannelListToClientAsync(client, ct);
await SendHistoryPageAsync(client, channelId, offset: 0, limit: 50, prepend: false, ct);
}
@ -662,6 +715,12 @@ public class ChatWebSocketManager
Text = $"Group chat '{InputSanitizer.SanitizeChannelName(group.Name)}' created by @{InputSanitizer.SanitizeUsername(client.User.Username)} ({group.MemberIds.Count}/{group.MaxUsers} members).",
Level = "Success"
});
// Notify initial invited members via Inbox & Web Push
foreach (var invitedUserId in group.MemberIds.Where(id => !string.Equals(id, client.User.Id, StringComparison.OrdinalIgnoreCase)))
{
await CreateGroupInviteInboxItemAsync(group, client.User, invitedUserId, ct);
}
}
private async Task HandleInviteToGroupAsync(ConnectedClient client, InviteToGroupPacket packet, CancellationToken ct)
@ -723,6 +782,8 @@ public class ChatWebSocketManager
Text = $"@{InputSanitizer.SanitizeUsername(targetUser.Username)} was added to group '{InputSanitizer.SanitizeChannelName(group.Name)}' by @{InputSanitizer.SanitizeUsername(client.User.Username)}.",
Level = "Info"
});
await CreateGroupInviteInboxItemAsync(updatedGroup ?? group, client.User, targetUser.Id, ct);
}
private async Task HandleLeaveGroupAsync(ConnectedClient client, LeaveGroupPacket packet, CancellationToken ct)
@ -854,6 +915,10 @@ public class ChatWebSocketManager
if (modResult != null)
{
await client.SendMessageAsync(MessageTypes.CommandResult, modResult, ct);
if (cmd == "announce" && modResult.Success && !string.IsNullOrWhiteSpace(packet.Args))
{
await CreateAnnouncementInboxItemsAsync(client.User, packet.Args.Trim(), packet.ChannelId, ct);
}
return;
}
}
@ -877,11 +942,140 @@ public class ChatWebSocketManager
$" /group create <name> [users] - Create a group chat (max {_options.MaxGroupChatUsers} users)\n" +
" /group invite <username> - Invite a user to the active group chat\n" +
" /group leave - Leave the active group chat\n" +
" /follow [channel] - Follow/unfollow a conversation for Inbox notifications\n" +
" /inbox [readall|clear] - Manage Inbox notifications & preferences\n" +
" /announce <message> - Broadcast an official announcement (Admin/Owner)\n" +
" /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);
break;
case "announce":
if (client.User.Role != UserRoles.Owner && client.User.Role != UserRoles.Admin)
{
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
{
Success = false,
Output = "Only Admins and Owners can use /announce.",
ChannelId = packet.ChannelId
}, ct);
break;
}
if (string.IsNullOrWhiteSpace(packet.Args))
{
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
{
Success = false,
Output = "Usage: /announce <announcement_message>",
ChannelId = packet.ChannelId
}, ct);
break;
}
string announceText = packet.Args.Trim();
await BroadcastSystemNoticeAsync($"📢 OFFICIAL ANNOUNCEMENT by @{InputSanitizer.SanitizeUsername(client.User.Username)}: {announceText}", "Warning");
await CreateAnnouncementInboxItemsAsync(client.User, announceText, packet.ChannelId, ct);
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
{
Success = true,
Output = $"📢 Announcement broadcast: {announceText}",
ChannelId = packet.ChannelId
}, ct);
break;
case "follow":
case "unfollow":
case "mute":
string targetChArg = (packet.Args ?? string.Empty).Trim().TrimStart('#', '@');
string resolvedChId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
if (!string.IsNullOrWhiteSpace(targetChArg))
{
var byName = await _db.GetChannelByNameAsync(targetChArg);
if (byName != null)
{
resolvedChId = byName.Id;
}
else
{
var userGroups = await _db.GetGroupChatsForUserAsync(client.User.Id);
var userDms = await _db.GetDirectMessagesForUserAsync(client.User.Id, _options.AllowDmE2ee);
var matched = userGroups.FirstOrDefault(g => g.Name.Equals(targetChArg, StringComparison.OrdinalIgnoreCase))
?? userDms.FirstOrDefault(d => d.Name.TrimStart('@').Equals(targetChArg, StringComparison.OrdinalIgnoreCase));
if (matched != null)
{
resolvedChId = matched.Id;
}
}
}
bool? explicitFollow = cmd == "unfollow" || cmd == "mute" ? false : (cmd == "follow" && !string.IsNullOrWhiteSpace(targetChArg) ? true : null);
await HandleToggleFollowChannelAsync(client, new ToggleFollowChannelPacket
{
ChannelId = resolvedChId,
Follow = explicitFollow
}, ct);
break;
case "inbox":
var inboxArgs = (packet.Args ?? string.Empty).Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (inboxArgs.Length == 0)
{
await SendInboxSyncToClientAsync(client, ct);
int unread = await _db.GetUnreadInboxCountAsync(client.User.Id);
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
{
Success = true,
Output = $"Inbox synced ({unread} unread). Usage: /inbox readall | /inbox clear [all] | /inbox <mentions|announcements|dms|channels|push> <on|off>",
ChannelId = packet.ChannelId
}, ct);
break;
}
string inboxSub = inboxArgs[0].ToLowerInvariant();
if (inboxSub == "readall" || inboxSub == "read")
{
await HandleInboxActionAsync(client, new InboxActionPacket { Action = "mark_all_read" }, ct);
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
{
Success = true,
Output = "All Inbox items marked as read.",
ChannelId = packet.ChannelId
}, ct);
}
else if (inboxSub == "clear")
{
bool clearAll = inboxArgs.Length > 1 && inboxArgs[1].Equals("all", StringComparison.OrdinalIgnoreCase);
await HandleInboxActionAsync(client, new InboxActionPacket { Action = clearAll ? "clear_all" : "clear_read" }, ct);
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
{
Success = true,
Output = clearAll ? "Cleared all Inbox items." : "Cleared read Inbox items.",
ChannelId = packet.ChannelId
}, ct);
}
else if (inboxArgs.Length >= 2)
{
bool enablePref = inboxArgs[1].Equals("on", StringComparison.OrdinalIgnoreCase) ||
inboxArgs[1].Equals("true", StringComparison.OrdinalIgnoreCase) ||
inboxArgs[1].Equals("1", StringComparison.OrdinalIgnoreCase);
var prefUpdate = new UpdateInboxPreferencesPacket();
switch (inboxSub)
{
case "mentions": prefUpdate.MentionsEnabled = enablePref; break;
case "announcements": prefUpdate.AnnouncementsEnabled = enablePref; break;
case "dms":
case "dm": prefUpdate.DirectMessagesEnabled = enablePref; break;
case "channels":
case "followed": prefUpdate.FollowedChannelsEnabled = enablePref; break;
case "push": prefUpdate.PushNotificationsEnabled = enablePref; break;
}
await HandleUpdateInboxPreferencesAsync(client, prefUpdate, ct);
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket
{
Success = true,
Output = $"Updated Inbox setting '{inboxSub}' to {(enablePref ? "ON" : "OFF")}.",
ChannelId = packet.ChannelId
}, ct);
}
break;
case "motd":
await client.SendMessageAsync(MessageTypes.CommandResult, new CommandResultPacket { Success = true, Output = $"MOTD: {_options.Motd}", ChannelId = packet.ChannelId }, ct);
break;
@ -1126,5 +1320,349 @@ public class ChatWebSocketManager
{
await BroadcastToChannelAsync(file.ChannelId, MessageTypes.MessageBroadcast, new MessageBroadcastPacket { Message = msg });
}
if (channel != null)
{
await ProcessMessageInboxNotificationsAsync(channel, msg);
}
}
#region Inbox & Notification Processing
public async Task SendInboxSyncToClientAsync(ConnectedClient client, CancellationToken ct = default)
{
var items = await _db.GetInboxItemsForUserAsync(client.User.Id, 100);
int unreadCount = await _db.GetUnreadInboxCountAsync(client.User.Id);
var prefs = await _db.GetInboxPreferencesAsync(client.User.Id);
await client.SendMessageAsync(MessageTypes.InboxSync, new InboxSyncPacket
{
Items = items,
UnreadCount = unreadCount,
Preferences = prefs
}, ct);
}
public async Task SyncInboxForUserAsync(string userId, CancellationToken ct = default)
{
var userClients = _clients.Values
.Where(c => string.Equals(c.User.Id, userId, StringComparison.OrdinalIgnoreCase))
.ToList();
if (userClients.Count == 0) return;
var items = await _db.GetInboxItemsForUserAsync(userId, 100);
int unreadCount = await _db.GetUnreadInboxCountAsync(userId);
var prefs = await _db.GetInboxPreferencesAsync(userId);
var packet = new InboxSyncPacket
{
Items = items,
UnreadCount = unreadCount,
Preferences = prefs
};
var envelope = NetworkEnvelope.Create(MessageTypes.InboxSync, packet);
await Task.WhenAll(userClients.Select(c => c.SendEnvelopeAsync(envelope, ct)));
}
private async Task HandleInboxActionAsync(ConnectedClient client, InboxActionPacket packet, CancellationToken ct)
{
string action = (packet.Action ?? string.Empty).Trim().ToLowerInvariant();
switch (action)
{
case "mark_read":
if (!string.IsNullOrWhiteSpace(packet.ItemId))
{
await _db.MarkInboxItemReadAsync(client.User.Id, packet.ItemId);
}
if (!string.IsNullOrWhiteSpace(packet.ChannelId))
{
await _db.MarkChannelInboxItemsReadAsync(client.User.Id, packet.ChannelId);
}
break;
case "mark_all_read":
await _db.MarkAllInboxItemsReadAsync(client.User.Id);
break;
case "dismiss":
case "delete":
if (!string.IsNullOrWhiteSpace(packet.ItemId))
{
await _db.DeleteInboxItemAsync(client.User.Id, packet.ItemId);
}
break;
case "clear_read":
await _db.ClearInboxItemsAsync(client.User.Id, onlyRead: true);
break;
case "clear_all":
await _db.ClearInboxItemsAsync(client.User.Id, onlyRead: false);
break;
}
await SyncInboxForUserAsync(client.User.Id, ct);
}
private async Task HandleUpdateInboxPreferencesAsync(ConnectedClient client, UpdateInboxPreferencesPacket packet, CancellationToken ct)
{
var prefs = await _db.GetInboxPreferencesAsync(client.User.Id);
if (packet.MentionsEnabled.HasValue) prefs.MentionsEnabled = packet.MentionsEnabled.Value;
if (packet.AnnouncementsEnabled.HasValue) prefs.AnnouncementsEnabled = packet.AnnouncementsEnabled.Value;
if (packet.DirectMessagesEnabled.HasValue) prefs.DirectMessagesEnabled = packet.DirectMessagesEnabled.Value;
if (packet.FollowedChannelsEnabled.HasValue) prefs.FollowedChannelsEnabled = packet.FollowedChannelsEnabled.Value;
if (packet.PushNotificationsEnabled.HasValue) prefs.PushNotificationsEnabled = packet.PushNotificationsEnabled.Value;
await _db.SaveInboxPreferencesAsync(prefs);
await SyncInboxForUserAsync(client.User.Id, ct);
}
private async Task HandleToggleFollowChannelAsync(ConnectedClient client, ToggleFollowChannelPacket packet, CancellationToken ct)
{
string channelId = string.IsNullOrWhiteSpace(packet.ChannelId) ? client.ActiveChannelId : packet.ChannelId;
if (string.IsNullOrWhiteSpace(channelId))
{
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "No conversation selected to follow/unfollow." }, ct);
return;
}
var channel = await _db.GetChannelByIdAsync(channelId, _options.AllowDmE2ee);
if (channel == null)
{
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "Conversation not found." }, ct);
return;
}
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
{
bool isMember = await _db.IsUserInChannelAsync(channel.Id, client.User.Id);
if (!isMember)
{
await client.SendMessageAsync(MessageTypes.Error, new ErrorPacket { Message = "You do not have access to this conversation." }, ct);
return;
}
}
bool isNowFollowed = await _db.ToggleChannelFollowAsync(client.User.Id, channel, packet.Follow);
await SyncInboxForUserAsync(client.User.Id, ct);
string displayConv = channel.Type == ChannelTypes.Channel
? $"#{channel.Name}"
: channel.Name;
string statusText = isNowFollowed
? $"🔔 Following {displayConv} for Inbox & Push notifications."
: $"🔕 Muted / unfollowed {displayConv} notifications.";
await client.SendMessageAsync(MessageTypes.SystemNotice, new SystemNoticePacket
{
Text = statusText,
Level = isNowFollowed ? "Success" : "Info"
}, ct);
}
public static bool IsUserMentioned(string content, string username)
{
if (string.IsNullOrWhiteSpace(content) || string.IsNullOrWhiteSpace(username))
{
return false;
}
if (E2eeCrypto.IsEncryptedPayload(content))
{
return false;
}
if (Regex.IsMatch(content, @"(^|[^\w])@(everyone|here)(?=$|[^\w])", RegexOptions.IgnoreCase))
{
return true;
}
string pattern = $@"(^|[^\w])@{Regex.Escape(username.Trim().TrimStart('@'))}(?=$|[^\w])";
return Regex.IsMatch(content, pattern, RegexOptions.IgnoreCase);
}
private async Task ProcessMessageInboxNotificationsAsync(Channel channel, ChatMessage message, CancellationToken ct = default)
{
var allUsers = await _db.GetAllUsersAsync();
var userById = allUsers.ToDictionary(u => u.Id, StringComparer.OrdinalIgnoreCase);
IEnumerable<UserSummary> candidateUsers;
if (channel.Type == ChannelTypes.DirectMessage || channel.Type == ChannelTypes.Group)
{
candidateUsers = channel.MemberIds
.Where(id => !string.Equals(id, message.SenderId, StringComparison.OrdinalIgnoreCase))
.Select(id => userById.GetValueOrDefault(id))
.Where(u => u != null)!;
}
else
{
candidateUsers = allUsers
.Where(u => !string.Equals(u.Id, message.SenderId, StringComparison.OrdinalIgnoreCase));
}
bool isAnnouncementChannel = channel.Type == ChannelTypes.Channel &&
string.Equals(channel.Name, "announcements", StringComparison.OrdinalIgnoreCase);
foreach (var recipient in candidateUsers)
{
var prefs = await _db.GetInboxPreferencesAsync(recipient.Id);
string? matchedCategory = null;
bool isMention = !message.IsEncrypted && IsUserMentioned(message.Content, recipient.Username);
if (isMention && prefs.MentionsEnabled)
{
matchedCategory = InboxCategories.Mention;
}
else if (isAnnouncementChannel && prefs.AnnouncementsEnabled)
{
matchedCategory = InboxCategories.Announcement;
}
else if (channel.Type == ChannelTypes.DirectMessage)
{
bool isMuted = prefs.MutedChannelIds.Contains(channel.Id, StringComparer.OrdinalIgnoreCase);
if (prefs.DirectMessagesEnabled && !isMuted)
{
matchedCategory = InboxCategories.DirectMessage;
}
}
else if (channel.Type == ChannelTypes.Group)
{
bool isMuted = prefs.MutedChannelIds.Contains(channel.Id, StringComparer.OrdinalIgnoreCase);
if (prefs.DirectMessagesEnabled && !isMuted)
{
matchedCategory = InboxCategories.GroupMessage;
}
}
else if (channel.Type == ChannelTypes.Channel)
{
bool isFollowed = prefs.FollowedChannelIds.Contains(channel.Id, StringComparer.OrdinalIgnoreCase);
if (prefs.FollowedChannelsEnabled && isFollowed)
{
matchedCategory = InboxCategories.FollowedChannel;
}
}
if (matchedCategory == null)
{
continue;
}
string channelDisplayName = channel.Type == ChannelTypes.DirectMessage
? message.SenderUsername
: channel.Name;
var inboxItem = new InboxItem
{
UserId = recipient.Id,
ChannelId = channel.Id,
ChannelName = channelDisplayName,
ChannelType = channel.Type,
MessageId = message.Id,
SenderId = message.SenderId,
SenderUsername = message.SenderUsername,
Category = matchedCategory,
ContentPreview = message.Content,
IsEncrypted = message.IsEncrypted,
SenderPublicKey = message.SenderPublicKey,
RecipientPublicKey = message.RecipientPublicKey,
IsRead = false,
CreatedAt = message.CreatedAt
};
await DeliverInboxItemAsync(inboxItem, prefs, ct);
}
}
private async Task CreateGroupInviteInboxItemAsync(Channel group, User inviter, string targetUserId, CancellationToken ct)
{
if (string.Equals(inviter.Id, targetUserId, StringComparison.OrdinalIgnoreCase))
{
return;
}
var prefs = await _db.GetInboxPreferencesAsync(targetUserId);
if (!prefs.DirectMessagesEnabled)
{
return;
}
var item = new InboxItem
{
UserId = targetUserId,
ChannelId = group.Id,
ChannelName = group.Name,
ChannelType = ChannelTypes.Group,
SenderId = inviter.Id,
SenderUsername = inviter.Username,
Category = InboxCategories.GroupInvite,
ContentPreview = $"@{inviter.Username} added you to group chat '{group.Name}'.",
IsEncrypted = false,
IsRead = false,
CreatedAt = DateTime.UtcNow
};
await DeliverInboxItemAsync(item, prefs, ct);
}
private async Task CreateAnnouncementInboxItemsAsync(User sender, string announcementText, string fallbackChannelId, CancellationToken ct)
{
var announcementsCh = await _db.GetChannelByNameAsync("announcements");
string channelId = announcementsCh?.Id ?? fallbackChannelId;
string channelName = announcementsCh?.Name ?? "announcements";
var allUsers = await _db.GetAllUsersAsync();
foreach (var recipient in allUsers.Where(u => !string.Equals(u.Id, sender.Id, StringComparison.OrdinalIgnoreCase)))
{
var prefs = await _db.GetInboxPreferencesAsync(recipient.Id);
if (!prefs.AnnouncementsEnabled) continue;
var item = new InboxItem
{
UserId = recipient.Id,
ChannelId = channelId,
ChannelName = channelName,
ChannelType = ChannelTypes.Channel,
SenderId = sender.Id,
SenderUsername = sender.Username,
Category = InboxCategories.Announcement,
ContentPreview = announcementText,
IsEncrypted = false,
IsRead = false,
CreatedAt = DateTime.UtcNow
};
await DeliverInboxItemAsync(item, prefs, ct);
}
}
private async Task DeliverInboxItemAsync(InboxItem item, InboxPreferences prefs, CancellationToken ct)
{
await _db.CreateInboxItemAsync(item);
int unreadCount = await _db.GetUnreadInboxCountAsync(item.UserId);
var newPacket = new InboxNewItemPacket
{
Item = item,
UnreadCount = unreadCount
};
var envelope = NetworkEnvelope.Create(MessageTypes.InboxNewItem, newPacket);
var targetClients = _clients.Values
.Where(c => string.Equals(c.User.Id, item.UserId, StringComparison.OrdinalIgnoreCase))
.ToList();
if (targetClients.Count > 0)
{
await Task.WhenAll(targetClients.Select(c => c.SendEnvelopeAsync(envelope, ct)));
}
if (_webPush != null && prefs.PushNotificationsEnabled)
{
await _webPush.SendPushForInboxItemAsync(item, prefs, ct);
}
}
#endregion
}

View file

@ -704,7 +704,8 @@ html, body {
.channel-list,
.user-list,
.files-list {
.files-list,
.inbox-list {
overflow-y: auto;
padding: 10px;
display: flex;
@ -714,10 +715,139 @@ html, body {
}
.user-list,
.files-list {
.files-list,
.inbox-list {
flex: 1;
}
.inbox-badge {
display: inline-block;
padding: 0 5px;
margin-left: 3px;
font-size: 0.72rem;
font-weight: 700;
background-color: var(--ctp-red);
color: var(--ctp-crust);
}
.inbox-settings-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 8px 14px;
background-color: var(--ctp-crust);
border-bottom: 1px solid var(--ctp-surface1);
flex-shrink: 0;
}
.inbox-prefs-group,
.inbox-push-group {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.inbox-prefs-label {
font-size: 0.74rem;
font-weight: 700;
color: var(--ctp-subtext0);
letter-spacing: 0.04em;
}
.inbox-item {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
padding: 8px 12px;
background-color: var(--ctp-mantle);
border: 1px solid var(--ctp-surface1);
border-left: 3px solid var(--ctp-surface1);
cursor: pointer;
transition: border-color 0.1s, background-color 0.1s;
}
.inbox-item:hover {
background-color: var(--ctp-surface0);
border-color: var(--ctp-mauve);
}
.inbox-item.unread {
border-left-color: var(--ctp-mauve);
background-color: #1c1c2e;
}
.inbox-item-main {
display: flex;
flex-direction: column;
gap: 4px;
flex: 1;
min-width: 0;
}
.inbox-item-top {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
font-size: 0.82rem;
}
.inbox-category-badge {
font-size: 0.68rem;
font-weight: 700;
padding: 1px 5px;
border: 1px solid var(--ctp-surface2);
text-transform: uppercase;
}
.inbox-category-badge.cat-mention {
color: var(--ctp-yellow);
border-color: var(--ctp-yellow);
background-color: rgba(249, 226, 175, 0.12);
}
.inbox-category-badge.cat-announcement {
color: var(--ctp-red);
border-color: var(--ctp-red);
background-color: rgba(243, 139, 168, 0.12);
}
.inbox-category-badge.cat-dm {
color: var(--ctp-green);
border-color: var(--ctp-green);
background-color: rgba(166, 227, 161, 0.12);
}
.inbox-category-badge.cat-followed,
.inbox-category-badge.cat-group_invite {
color: var(--ctp-sapphire);
border-color: var(--ctp-sapphire);
background-color: rgba(116, 199, 236, 0.12);
}
.inbox-unread-dot {
color: var(--ctp-mauve);
font-weight: 700;
}
.inbox-item-preview {
font-size: 0.86rem;
color: var(--ctp-text);
word-break: break-word;
white-space: pre-wrap;
}
.inbox-item-actions {
display: flex;
align-items: center;
gap: 4px;
flex-shrink: 0;
}
.channel-item,
.user-item,
.file-item {

View file

@ -21,6 +21,20 @@
e2eePromptedDms: {}, // dmChannelId -> bool (prevent repeated intrusive prompts after dismiss)
users: [],
files: [],
inboxItems: [],
unreadInboxCount: 0,
inboxPreferences: {
mentionsEnabled: true,
announcementsEnabled: true,
directMessagesEnabled: true,
followedChannelsEnabled: true,
pushNotificationsEnabled: true,
followedChannelIds: [],
mutedChannelIds: []
},
vapidPublicKey: null,
swRegistration: null,
pushSubscribed: false,
socket: null,
isRegister: false,
reconnectTimer: null
@ -31,6 +45,8 @@
serverTitle: document.getElementById('serverTitle'),
connIndicator: document.getElementById('connIndicator'),
navTabs: document.querySelectorAll('.nav-tab'),
navTabInbox: document.getElementById('navTabInbox'),
inboxUnreadBadge: document.getElementById('inboxUnreadBadge'),
tabViews: document.querySelectorAll('.tab-view'),
currentUsername: document.getElementById('currentUsername'),
currentUserRole: document.getElementById('currentUserRole'),
@ -43,6 +59,7 @@
channelSelectDropdown: document.getElementById('channelSelectDropdown'),
chatSecurityBadge: document.getElementById('chatSecurityBadge'),
activeChannelTopic: document.getElementById('activeChannelTopic'),
toggleFollowBtn: document.getElementById('toggleFollowBtn'),
toggleDmE2eeBtn: document.getElementById('toggleDmE2eeBtn'),
inviteGroupBtn: document.getElementById('inviteGroupBtn'),
leaveGroupBtn: document.getElementById('leaveGroupBtn'),
@ -93,6 +110,19 @@
filesList: document.getElementById('filesList'),
filesViewUploadInput: document.getElementById('filesViewUploadInput'),
// Inbox View
inboxHeaderCount: document.getElementById('inboxHeaderCount'),
markAllReadInboxBtn: document.getElementById('markAllReadInboxBtn'),
clearReadInboxBtn: document.getElementById('clearReadInboxBtn'),
clearAllInboxBtn: document.getElementById('clearAllInboxBtn'),
prefMentionsBtn: document.getElementById('prefMentionsBtn'),
prefAnnouncementsBtn: document.getElementById('prefAnnouncementsBtn'),
prefDmsBtn: document.getElementById('prefDmsBtn'),
prefFollowedBtn: document.getElementById('prefFollowedBtn'),
toggleWebPushBtn: document.getElementById('toggleWebPushBtn'),
testWebPushBtn: document.getElementById('testWebPushBtn'),
inboxList: document.getElementById('inboxList'),
// E2EE Vault Modal
e2eeModal: document.getElementById('e2eeModal'),
e2eeModalTitle: document.getElementById('e2eeModalTitle'),
@ -466,6 +496,53 @@
return msg;
}
async function decryptInboxItemIfNeeded(item) {
if (!item) return item;
const rawPreview = item._rawCiphertext || item.contentPreview || item.ContentPreview || '';
const isEnc = item.isEncrypted || item.IsEncrypted || rawPreview.startsWith(E2EE_PREFIX);
if (!isEnc) return item;
item.isEncrypted = true;
if (rawPreview.startsWith(E2EE_PREFIX)) {
item._rawCiphertext = rawPreview;
} else {
return item;
}
if (!state.privateKey) {
const lockedPlaceholder = '[🔒 Encrypted DM - Click [🔒 E2EE Vault] and enter PIN to unlock]';
item.contentPreview = lockedPlaceholder;
item.ContentPreview = lockedPlaceholder;
return item;
}
const senderId = item.senderId || item.SenderId || '';
const senderPubKey = item.senderPublicKey || item.SenderPublicKey || '';
const recipientPubKey = item.recipientPublicKey || item.RecipientPublicKey || '';
const chId = item.channelId || item.ChannelId || '';
const isSentByMe = state.user && senderId.toLowerCase() === (state.user.id || '').toLowerCase();
let peerKey = isSentByMe ? recipientPubKey : senderPubKey;
if (!peerKey) {
const conv = getConversationById(chId);
if (conv) peerKey = getPeerPublicKeyForDm(conv);
}
if (!peerKey && senderId) {
const u = state.users.find(user => (user.id || user.Id || '').toLowerCase() === senderId.toLowerCase());
if (u && (u.publicKey || u.PublicKey)) peerKey = u.publicKey || u.PublicKey;
}
if (!peerKey) {
peerKey = senderPubKey || recipientPubKey || null;
}
if (peerKey && state.privateKey) {
const decrypted = await decryptDmMessage(rawPreview, state.privateKey, peerKey);
item.contentPreview = decrypted;
item.ContentPreview = decrypted;
}
return item;
}
async function reDecryptAllLoadedMessages() {
for (const chId of Object.keys(state.messages)) {
const list = state.messages[chId] || [];
@ -475,9 +552,15 @@
}
}
}
for (const item of state.inboxItems) {
if (item._rawCiphertext || ((item.contentPreview || item.ContentPreview || '').startsWith(E2EE_PREFIX))) {
await decryptInboxItemIfNeeded(item);
}
}
if (state.activeChannelId) {
renderMessages();
}
renderInbox();
}
async function unlockOrInitE2eeWithPin(pin, resetKeys = false) {
@ -546,6 +629,216 @@
};
}
// ==========================================
// Service Worker & Web Push Notifications
// ==========================================
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
async function initServiceWorkerAndPush() {
if (!('serviceWorker' in navigator)) return;
try {
const reg = await navigator.serviceWorker.register('/sw.js');
state.swRegistration = reg;
navigator.serviceWorker.addEventListener('message', (event) => {
const data = event.data || {};
if (data.type === 'OPEN_CONVERSATION') {
if (data.itemId) {
sendInboxAction('mark_read', data.itemId);
}
if (data.channelId) {
joinChannel(data.channelId);
switchTab('chat');
} else {
switchTab('inbox');
}
}
});
if (reg.pushManager) {
const existingSub = await reg.pushManager.getSubscription();
state.pushSubscribed = !!existingSub;
updateInboxPreferencesUI();
if (existingSub && state.token) {
await syncSubscriptionToServer(existingSub);
}
}
} catch (err) {
console.warn('Service Worker registration skipped or failed:', err);
}
}
async function syncSubscriptionToServer(subscription) {
if (!subscription || !state.token) return false;
try {
const subJson = subscription.toJSON();
const endpoint = subJson.endpoint;
const p256dh = subJson.keys ? subJson.keys.p256dh : '';
const auth = subJson.keys ? subJson.keys.auth : '';
if (!endpoint || !p256dh || !auth) return false;
const csrfRes = await fetch('/api/csrf-token');
const csrfData = await csrfRes.json();
const csrfToken = csrfData.token || '';
const res = await fetch('/api/push/subscribe', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${state.token}`,
'X-CSRF-Token': csrfToken
},
body: JSON.stringify({
endpoint,
p256dh,
auth,
userAgent: navigator.userAgent || ''
})
});
return res.ok;
} catch {
return false;
}
}
async function fetchVapidPublicKey() {
if (state.vapidPublicKey) return state.vapidPublicKey;
try {
const res = await fetch('/api/push/vapid-public-key');
if (res.ok) {
const data = await res.json();
state.vapidPublicKey = data.publicKey || data.PublicKey || '';
}
} catch {
// ignore
}
return state.vapidPublicKey;
}
async function toggleWebPushSubscription() {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
showToast('Web Push is not supported in this browser.');
return;
}
if (state.pushSubscribed) {
await unsubscribeWebPush();
} else {
await subscribeWebPush();
}
}
async function subscribeWebPush() {
try {
if ('Notification' in window) {
const perm = await Notification.requestPermission();
if (perm !== 'granted') {
showToast('Notification permission denied by browser.');
return;
}
}
if (!state.swRegistration) {
state.swRegistration = await navigator.serviceWorker.register('/sw.js');
}
await navigator.serviceWorker.ready;
const vapidKey = await fetchVapidPublicKey();
if (!vapidKey) {
showToast('Server VAPID public key is unavailable.');
return;
}
const 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
});
updateInboxPreferencesUI();
showToast('🔔 Background Web Push notifications enabled on this browser!');
} else {
showToast('Failed to register Web Push subscription with server.');
}
} catch (err) {
showToast(`Web Push setup failed: ${err.message || err}`);
}
}
async function unsubscribeWebPush() {
try {
if (state.swRegistration && state.swRegistration.pushManager) {
const sub = await state.swRegistration.pushManager.getSubscription();
if (sub) {
if (state.token) {
const csrfRes = await fetch('/api/csrf-token');
const csrfData = await csrfRes.json();
await fetch('/api/push/unsubscribe', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${state.token}`,
'X-CSRF-Token': csrfData.token || ''
},
body: JSON.stringify({ endpoint: sub.endpoint })
});
}
await sub.unsubscribe();
}
}
state.pushSubscribed = false;
updateInboxPreferencesUI();
showToast('🔕 Web Push notifications disabled on this browser.');
} catch (err) {
showToast(`Unsubscribe error: ${err.message || err}`);
}
}
async function sendTestWebPush() {
if (!state.token) {
showToast('Login required');
return;
}
try {
const csrfRes = await fetch('/api/csrf-token');
const csrfData = await csrfRes.json();
const res = await fetch('/api/push/test', {
method: 'POST',
headers: {
'Authorization': `Bearer ${state.token}`,
'X-CSRF-Token': csrfData.token || ''
}
});
const data = await res.json();
if (res.ok && data.success) {
showToast('🔔 Test Web Push sent! Check your OS notification tray.');
} else {
showToast(data.message || 'Enable Web Push first before testing.');
}
} catch (err) {
showToast(`Test push failed: ${err.message || err}`);
}
}
// ==========================================
// Initialization
// ==========================================
@ -553,6 +846,7 @@
initElements();
setupEventListeners();
await fetchServerInfo();
await initServiceWorkerAndPush();
if (state.token && state.user) {
loadCachedKeysForCurrentUser();
@ -581,6 +875,9 @@
? state.serverInfo.allowDmE2ee
: (state.serverInfo.AllowDmE2ee !== undefined ? state.serverInfo.AllowDmE2ee : true);
state.maxGroupChatUsers = state.serverInfo.maxGroupChatUsers || state.serverInfo.MaxGroupChatUsers || 10;
if (state.serverInfo.vapidPublicKey || state.serverInfo.VapidPublicKey) {
state.vapidPublicKey = state.serverInfo.vapidPublicKey || state.serverInfo.VapidPublicKey;
}
el.serverTitle.textContent = state.serverInfo.serverName || 'GsDChat';
el.modalServerName.textContent = state.serverInfo.serverName || 'GsDChat';
@ -839,6 +1136,23 @@
const first = state.channels[0];
state.activeChannelId = first.id || first.Id;
}
// Check if opened from an OS push notification deep link (?channel=...)
try {
const params = new URLSearchParams(window.location.search);
const deepChannel = params.get('channel');
const deepInboxItem = params.get('inboxItem');
if (deepInboxItem) {
sendInboxAction('mark_read', deepInboxItem);
}
if (deepChannel && getConversationById(deepChannel)) {
state.activeChannelId = deepChannel;
window.history.replaceState({}, document.title, window.location.pathname);
}
} catch {
// Ignore URL parse issues
}
renderChannels();
updateActiveChannelHeader();
checkLazyDmE2eePrompt();
@ -909,6 +1223,82 @@
renderFiles();
break;
case 'INBOX_SYNC': {
const rawItems = payload.items || payload.Items || [];
const decryptedItems = [];
for (const item of rawItems) {
decryptedItems.push(await decryptInboxItemIfNeeded(item));
}
state.inboxItems = decryptedItems;
state.unreadInboxCount = payload.unreadCount ?? payload.UnreadCount ?? decryptedItems.filter(i => !(i.isRead ?? i.IsRead)).length;
const prefs = payload.preferences || payload.Preferences;
if (prefs) {
state.inboxPreferences = {
mentionsEnabled: prefs.mentionsEnabled ?? prefs.MentionsEnabled ?? true,
announcementsEnabled: prefs.announcementsEnabled ?? prefs.AnnouncementsEnabled ?? true,
directMessagesEnabled: prefs.directMessagesEnabled ?? prefs.DirectMessagesEnabled ?? true,
followedChannelsEnabled: prefs.followedChannelsEnabled ?? prefs.FollowedChannelsEnabled ?? true,
pushNotificationsEnabled: prefs.pushNotificationsEnabled ?? prefs.PushNotificationsEnabled ?? true,
followedChannelIds: prefs.followedChannelIds || prefs.FollowedChannelIds || [],
mutedChannelIds: prefs.mutedChannelIds || prefs.MutedChannelIds || []
};
}
updateInboxBadge();
updateInboxPreferencesUI();
renderInbox();
updateActiveChannelHeader();
renderChannels();
break;
}
case 'INBOX_NEW_ITEM': {
const rawItem = payload.item || payload.Item;
if (rawItem) {
const item = await decryptInboxItemIfNeeded(rawItem);
const itemId = item.id || item.Id;
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;
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}`);
}
// Fallback desktop Notification when tab is in background and Service Worker Push isn't active
if (document.hidden && !state.pushSubscribed && 'Notification' in window && Notification.permission === 'granted') {
try {
const isEnc = item.isEncrypted || item.IsEncrypted;
const notifBody = isEnc && !state.privateKey
? `🔒 New encrypted message from @${itemSender}`
: `@${itemSender}: ${item.contentPreview || item.ContentPreview || ''}`;
const n = new Notification(`GsDChat (${itemChName})`, {
body: notifBody,
tag: `gsdchat-ws-${itemChId || itemId}`
});
n.onclick = () => {
window.focus();
sendInboxAction('mark_read', itemId);
if (itemChId) {
joinChannel(itemChId);
switchTab('chat');
}
n.close();
};
} catch {
// Ignore Notification constructor errors on restricted environments
}
}
}
break;
}
case 'SYSTEM_NOTICE':
const noticeText = payload.text || payload.Text;
if (noticeText) {
@ -953,6 +1343,200 @@
return conv.type || conv.Type || 'Channel';
}
function isConversationFollowed(conv) {
if (!conv) return false;
const chId = (conv.id || conv.Id || '').toLowerCase();
const followedIds = (state.inboxPreferences && state.inboxPreferences.followedChannelIds) || [];
const mutedIds = (state.inboxPreferences && state.inboxPreferences.mutedChannelIds) || [];
if (followedIds.some(id => (id || '').toLowerCase() === chId)) return true;
if (mutedIds.some(id => (id || '').toLowerCase() === chId)) return false;
const cType = getConversationType(conv);
return cType === 'DM' || cType === 'Group';
}
function toggleFollowConversation(channelId, explicitFollow) {
const conv = getConversationById(channelId || state.activeChannelId);
if (!conv) return;
const chId = conv.id || conv.Id;
const currentlyFollowed = isConversationFollowed(conv);
const nextFollow = explicitFollow !== undefined ? explicitFollow : !currentlyFollowed;
sendEnvelope('TOGGLE_FOLLOW_CHANNEL', {
channelId: chId,
follow: nextFollow
});
}
function sendInboxAction(action, itemId = null, channelId = null) {
sendEnvelope('INBOX_ACTION', {
action: action,
itemId: itemId,
channelId: channelId
});
}
function toggleInboxPreference(prefKey) {
const prefs = state.inboxPreferences;
if (prefKey in prefs) {
prefs[prefKey] = !prefs[prefKey];
sendEnvelope('UPDATE_INBOX_PREFERENCES', {
mentionsEnabled: prefs.mentionsEnabled,
announcementsEnabled: prefs.announcementsEnabled,
directMessagesEnabled: prefs.directMessagesEnabled,
followedChannelsEnabled: prefs.followedChannelsEnabled,
pushNotificationsEnabled: prefs.pushNotificationsEnabled
});
updateInboxPreferencesUI();
}
}
function updateInboxBadge() {
initElements();
const count = state.unreadInboxCount || 0;
if (el.inboxUnreadBadge) {
if (count > 0) {
el.inboxUnreadBadge.style.display = 'inline-block';
el.inboxUnreadBadge.textContent = count > 99 ? '99+' : String(count);
} else {
el.inboxUnreadBadge.style.display = 'none';
el.inboxUnreadBadge.textContent = '0';
}
}
if (el.inboxHeaderCount) {
el.inboxHeaderCount.textContent = `(${count} Unread / ${state.inboxItems.length} Total)`;
}
}
function updateInboxPreferencesUI() {
initElements();
const p = state.inboxPreferences;
if (el.prefMentionsBtn) {
el.prefMentionsBtn.textContent = `[Mentions: ${p.mentionsEnabled ? 'ON' : 'OFF'}]`;
}
if (el.prefAnnouncementsBtn) {
el.prefAnnouncementsBtn.textContent = `[Announcements: ${p.announcementsEnabled ? 'ON' : 'OFF'}]`;
}
if (el.prefDmsBtn) {
el.prefDmsBtn.textContent = `[DMs & Groups: ${p.directMessagesEnabled ? 'ON' : 'OFF'}]`;
}
if (el.prefFollowedBtn) {
el.prefFollowedBtn.textContent = `[Followed Channels: ${p.followedChannelsEnabled ? 'ON' : 'OFF'}]`;
}
if (el.toggleWebPushBtn) {
const activePush = state.pushSubscribed && p.pushNotificationsEnabled;
el.toggleWebPushBtn.textContent = activePush ? '[🔔 Web Push: ON]' : '[🔕 Enable Web Push]';
el.toggleWebPushBtn.className = activePush ? 'btn btn-sm btn-primary' : 'btn btn-sm btn-secondary';
}
}
function renderInbox() {
initElements();
updateInboxBadge();
updateInboxPreferencesUI();
if (!el.inboxList) return;
el.inboxList.innerHTML = '';
if (state.inboxItems.length === 0) {
el.inboxList.innerHTML = '<div style="color:var(--text-muted); text-align:center; padding:24px;">Inbox is empty! Mentions (@username, @everyone, @here), #announcements, DMs, and followed channel messages will appear here.</div>';
return;
}
state.inboxItems.forEach(item => {
const itemId = item.id || item.Id;
const chId = item.channelId || item.ChannelId;
const chName = item.channelName || item.ChannelName || 'general';
const chType = item.channelType || item.ChannelType || 'Channel';
const sender = item.senderUsername || item.SenderUsername || 'User';
const category = (item.category || item.Category || 'mention').toLowerCase();
const preview = item.contentPreview || item.ContentPreview || '';
const isRead = !!(item.isRead ?? item.IsRead);
const isEnc = !!(item.isEncrypted ?? item.IsEncrypted);
const createdAt = item.createdAt || item.CreatedAt;
const timeStr = createdAt ? new Date(createdAt).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : '';
let catLabel = 'MENTION';
let catCss = 'mention';
if (category === 'announcement') {
catLabel = 'ANNOUNCEMENT';
catCss = 'announcement';
} else if (category === 'dm' || category === 'directmessage') {
catLabel = 'DIRECT MSG';
catCss = 'dm';
} else if (category === 'groupmessage') {
catLabel = 'GROUP MSG';
catCss = 'followed';
} else if (category === 'followed' || category === 'followedchannel') {
catLabel = 'FOLLOWED';
catCss = 'followed';
} else if (category === 'group_invite' || category === 'groupinvite') {
catLabel = 'GROUP INVITE';
catCss = 'group_invite';
}
let convDisplay = `#${chName}`;
if (chType === 'DM') convDisplay = `DM @${chName.replace(/^@/, '')}`;
else if (chType === 'Group') convDisplay = `[Group] ${chName}`;
const div = document.createElement('div');
div.className = 'inbox-item' + (isRead ? '' : ' unread');
div.innerHTML = `
<div class="inbox-item-main">
<div class="inbox-item-top">
${isRead ? '' : '<span class="inbox-unread-dot" title="Unread">●</span>'}
<span class="inbox-category-badge cat-${escapeHtml(catCss)}">[${catLabel}]</span>
<span style="font-weight:700; color:var(--ctp-sapphire);">${escapeHtml(convDisplay)}</span>
<span style="color:var(--ctp-subtext0);">from @${escapeHtml(sender)}</span>
${isEnc ? '<span class="msg-e2ee-tag">🔒 E2EE</span>' : ''}
<span class="message-time">${escapeHtml(timeStr)}</span>
</div>
<div class="inbox-item-preview">${escapeHtml(preview)}</div>
</div>
<div class="inbox-item-actions">
<button type="button" class="btn btn-secondary btn-sm btn-inbox-open" title="Jump to Conversation">[Open]</button>
<button type="button" class="btn btn-secondary btn-sm btn-inbox-toggle-read" title="Toggle Read/Unread">[${isRead ? 'Mark Unread' : '✓ Read'}]</button>
<button type="button" class="btn btn-outline-danger btn-sm btn-inbox-dismiss" title="Delete from Inbox">[✕]</button>
</div>
`;
const openAction = () => {
if (!isRead) {
sendInboxAction('mark_read', itemId);
}
if (chId) {
joinChannel(chId);
switchTab('chat');
}
};
div.addEventListener('click', openAction);
const openBtn = div.querySelector('.btn-inbox-open');
if (openBtn) {
openBtn.addEventListener('click', (e) => {
e.stopPropagation();
openAction();
});
}
const readBtn = div.querySelector('.btn-inbox-toggle-read');
if (readBtn) {
readBtn.addEventListener('click', (e) => {
e.stopPropagation();
sendInboxAction(isRead ? 'mark_unread' : 'mark_read', itemId);
});
}
const dismissBtn = div.querySelector('.btn-inbox-dismiss');
if (dismissBtn) {
dismissBtn.addEventListener('click', (e) => {
e.stopPropagation();
sendInboxAction('dismiss', itemId);
});
}
el.inboxList.appendChild(div);
});
}
function checkLazyDmE2eePrompt() {
const active = getConversationById(state.activeChannelId);
if (!active || getConversationType(active) !== 'DM') return;
@ -1061,6 +1645,8 @@
renderChannels();
} else if (tabName === 'files') {
renderFiles();
} else if (tabName === 'inbox') {
renderInbox();
} else if (tabName === 'chat') {
renderMessages();
}
@ -1079,6 +1665,21 @@
el.channelSelectDropdown.value = chId;
}
if (el.toggleFollowBtn) {
const isFollowed = isConversationFollowed(active);
if (chType === 'Channel') {
el.toggleFollowBtn.textContent = isFollowed ? '[🔔 Following]' : '[🔔 Follow]';
el.toggleFollowBtn.title = isFollowed
? 'Receiving Inbox & Push notifications for this channel (click to unfollow)'
: 'Follow this channel to receive Inbox & Push notifications for all messages';
} else {
el.toggleFollowBtn.textContent = isFollowed ? '[🔔 Following]' : '[🔕 Muted]';
el.toggleFollowBtn.title = isFollowed
? 'Receiving Inbox & Push notifications for this conversation (click to mute)'
: 'Notifications muted for this conversation (click to unmute)';
}
}
if (chType === 'DM') {
if (el.activeConvPrefix) el.activeConvPrefix.textContent = '@';
const dmIsE2ee = (active.isE2ee ?? active.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled;
@ -1147,6 +1748,7 @@
const chName = ch.name || ch.Name;
const chTopic = ch.topic || ch.Topic || '';
const isActive = chId === state.activeChannelId;
const isFollowed = isConversationFollowed(ch);
const item = document.createElement('div');
item.className = 'channel-item' + (isActive ? ' active' : '');
@ -1155,8 +1757,18 @@
<span class="channel-title">#${escapeHtml(chName)}</span>
<span class="channel-desc">${escapeHtml(chTopic)}</span>
</div>
${isActive ? '<span class="channel-badge">[ACTIVE]</span>' : ''}
<div style="display:flex; gap:6px; align-items:center;">
<button type="button" class="btn btn-secondary btn-sm btn-follow-conv" title="Toggle Inbox &amp; Push Notifications">[${isFollowed ? '🔔 Following' : '🔕 Follow'}]</button>
${isActive ? '<span class="channel-badge">[ACTIVE]</span>' : ''}
</div>
`;
const followBtn = item.querySelector('.btn-follow-conv');
if (followBtn) {
followBtn.addEventListener('click', (e) => {
e.stopPropagation();
toggleFollowConversation(chId, !isFollowed);
});
}
item.addEventListener('click', () => {
joinChannel(chId);
switchTab('chat');
@ -1178,6 +1790,7 @@
const members = grp.memberUsernames || grp.MemberUsernames || [];
const maxU = grp.maxUsers || grp.MaxUsers || state.maxGroupChatUsers;
const isActive = gId === state.activeChannelId;
const isFollowed = isConversationFollowed(grp);
const item = document.createElement('div');
item.className = 'channel-item' + (isActive ? ' active' : '');
@ -1187,8 +1800,18 @@
<span class="channel-title">[Group] ${escapeHtml(gName)} <span style="font-size:0.75rem; color:var(--ctp-mauve);">(${members.length}/${maxU})</span></span>
<span class="channel-desc">${escapeHtml(gTopic || membersText)}</span>
</div>
${isActive ? '<span class="channel-badge">[ACTIVE]</span>' : ''}
<div style="display:flex; gap:6px; align-items:center;">
<button type="button" class="btn btn-secondary btn-sm btn-follow-conv" title="Toggle Group Notifications">[${isFollowed ? '🔔 On' : '🔕 Muted'}]</button>
${isActive ? '<span class="channel-badge">[ACTIVE]</span>' : ''}
</div>
`;
const followBtn = item.querySelector('.btn-follow-conv');
if (followBtn) {
followBtn.addEventListener('click', (e) => {
e.stopPropagation();
toggleFollowConversation(gId, !isFollowed);
});
}
item.addEventListener('click', () => {
joinChannel(gId);
switchTab('chat');
@ -1210,6 +1833,7 @@
const isE2ee = (dm.isE2ee ?? dm.IsE2ee ?? true) && state.allowDmE2ee && state.accountE2eeEnabled;
const peerReady = isDmPeerE2eeReady(dm);
const isActive = dmId === state.activeChannelId;
const isFollowed = isConversationFollowed(dm);
let descText = 'Plaintext (Server-Visible)';
let badgeLabel = 'Plain';
@ -1236,10 +1860,18 @@
<span class="channel-desc">${descText}</span>
</div>
<div style="display:flex; gap:6px; align-items:center;">
<button type="button" class="btn btn-secondary btn-sm btn-follow-conv" title="Toggle DM Notifications">[${isFollowed ? '🔔 On' : '🔕 Muted'}]</button>
<button type="button" class="btn btn-secondary btn-sm btn-toggle-dm-e2ee" title="Toggle E2EE for this DM">[${isE2ee ? 'E2EE: ON' : 'E2EE: OFF'}]</button>
${isActive ? '<span class="channel-badge">[ACTIVE]</span>' : `<span class="conv-security-badge ${badgeClass}">${badgeLabel}</span>`}
</div>
`;
const followBtn = item.querySelector('.btn-follow-conv');
if (followBtn) {
followBtn.addEventListener('click', (e) => {
e.stopPropagation();
toggleFollowConversation(dmId, !isFollowed);
});
}
const toggleBtn = item.querySelector('.btn-toggle-dm-e2ee');
if (toggleBtn) {
toggleBtn.addEventListener('click', (e) => {
@ -1863,6 +2495,20 @@
return;
}
if (cmd === 'inbox') {
if (!args) {
switchTab('inbox');
return;
}
sendEnvelope('EXECUTE_COMMAND', {
command: cmd,
args: args,
channelId: state.activeChannelId || ''
});
switchTab('inbox');
return;
}
sendEnvelope('EXECUTE_COMMAND', {
command: cmd,
args: args,
@ -2015,6 +2661,38 @@
if (el.toggleDmE2eeBtn) {
el.toggleDmE2eeBtn.addEventListener('click', () => toggleDmE2ee(state.activeChannelId));
}
if (el.toggleFollowBtn) {
el.toggleFollowBtn.addEventListener('click', () => toggleFollowConversation(state.activeChannelId));
}
// Inbox & Web Push Controls
if (el.markAllReadInboxBtn) {
el.markAllReadInboxBtn.addEventListener('click', () => sendInboxAction('mark_all_read'));
}
if (el.clearReadInboxBtn) {
el.clearReadInboxBtn.addEventListener('click', () => sendInboxAction('clear_read'));
}
if (el.clearAllInboxBtn) {
el.clearAllInboxBtn.addEventListener('click', () => sendInboxAction('clear_all'));
}
if (el.prefMentionsBtn) {
el.prefMentionsBtn.addEventListener('click', () => toggleInboxPreference('mentionsEnabled'));
}
if (el.prefAnnouncementsBtn) {
el.prefAnnouncementsBtn.addEventListener('click', () => toggleInboxPreference('announcementsEnabled'));
}
if (el.prefDmsBtn) {
el.prefDmsBtn.addEventListener('click', () => toggleInboxPreference('directMessagesEnabled'));
}
if (el.prefFollowedBtn) {
el.prefFollowedBtn.addEventListener('click', () => toggleInboxPreference('followedChannelsEnabled'));
}
if (el.toggleWebPushBtn) {
el.toggleWebPushBtn.addEventListener('click', toggleWebPushSubscription);
}
if (el.testWebPushBtn) {
el.testWebPushBtn.addEventListener('click', sendTestWebPush);
}
if (el.e2eePinForm) {
el.e2eePinForm.addEventListener('submit', async (e) => {
e.preventDefault();

View file

@ -6,6 +6,7 @@
<meta name="theme-color" content="#11111b">
<meta name="color-scheme" content="dark">
<title>GsDChat - Web Client</title>
<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">
<link rel="stylesheet" href="/app.css">
@ -49,6 +50,7 @@
<button class="nav-tab" data-tab="channels">[2:channels/dms]</button>
<button class="nav-tab" data-tab="users">[3:users]</button>
<button class="nav-tab" data-tab="files">[4:files]</button>
<button class="nav-tab" data-tab="inbox" id="navTabInbox">[5:inbox] <span id="inboxUnreadBadge" class="inbox-badge" style="display:none;">0</span></button>
</nav>
<div class="header-right">
@ -76,6 +78,7 @@
<span class="channel-topic" id="activeChannelTopic"></span>
</div>
<div class="chat-header-actions">
<button type="button" class="btn btn-sm btn-secondary" id="toggleFollowBtn" title="Follow or Mute notifications for this conversation">[🔔 Follow]</button>
<button type="button" class="btn btn-sm btn-secondary" id="toggleDmE2eeBtn" style="display:none;" title="Toggle E2EE for this Direct Message">[DM E2EE: ON]</button>
<button type="button" class="btn btn-sm btn-secondary" id="inviteGroupBtn" style="display:none;" title="Invite User to Group">[+ Invite]</button>
<button type="button" class="btn btn-sm btn-outline-danger" id="leaveGroupBtn" style="display:none;" title="Leave Group">[Leave]</button>
@ -228,6 +231,37 @@
</div>
</section>
<!-- View 5: Inbox & Notifications View -->
<section id="view-inbox" class="tab-view">
<div class="view-header">
<h2>== INBOX &amp; NOTIFICATIONS <span id="inboxHeaderCount" class="section-sub-hint">(0 Unread)</span> ==</h2>
<div style="display:flex; gap:6px; flex-wrap:wrap;">
<button type="button" class="btn btn-secondary btn-sm" id="markAllReadInboxBtn">[✓ Mark All Read]</button>
<button type="button" class="btn btn-secondary btn-sm" id="clearReadInboxBtn">[Clear Read]</button>
<button type="button" class="btn btn-outline-danger btn-sm" id="clearAllInboxBtn">[Clear All]</button>
</div>
</div>
<div class="inbox-settings-bar">
<div class="inbox-prefs-group">
<span class="inbox-prefs-label">TRIGGERS:</span>
<button type="button" class="btn btn-sm btn-secondary" id="prefMentionsBtn" title="Toggle @mention notifications">[Mentions: ON]</button>
<button type="button" class="btn btn-sm btn-secondary" id="prefAnnouncementsBtn" title="Toggle #announcements &amp; /announce notifications">[Announcements: ON]</button>
<button type="button" class="btn btn-sm btn-secondary" id="prefDmsBtn" title="Toggle Direct Message &amp; Group notifications">[DMs &amp; Groups: ON]</button>
<button type="button" class="btn btn-sm btn-secondary" id="prefFollowedBtn" title="Toggle Followed Channel notifications">[Followed Channels: ON]</button>
</div>
<div class="inbox-push-group">
<span class="inbox-prefs-label">WEB PUSH:</span>
<button type="button" class="btn btn-sm btn-primary" id="toggleWebPushBtn" title="Enable or disable background Web Push notifications on this browser">[🔔 Enable Web Push]</button>
<button type="button" class="btn btn-sm btn-secondary" id="testWebPushBtn" title="Send a test Web Push notification to this device">[Test Push]</button>
</div>
</div>
<div class="inbox-list" id="inboxList">
<!-- Populated by JS -->
</div>
</section>
</main>
<!-- Toast Notification Overlay -->

View file

@ -0,0 +1,10 @@
{
"name": "GsDChat - Terminal Hybrid Chat",
"short_name": "GsDChat",
"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": []
}

View file

@ -0,0 +1,104 @@
// ============================================================================
// GsDChat Service Worker (Web Push Notifications & Background Deep-Linking)
// ============================================================================
self.addEventListener('install', (event) => {
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', (event) => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('push', (event) => {
let payload = {
title: 'GsDChat Notification',
body: 'You have a new notification in your Inbox.',
channelId: '',
channelName: '',
category: 'mention',
itemId: '',
timestamp: new Date().toISOString()
};
if (event.data) {
try {
const parsed = event.data.json();
payload = Object.assign(payload, parsed);
} catch (err) {
try {
payload.body = event.data.text();
} catch (_) {
// Keep default body
}
}
}
event.waitUntil((async () => {
const windowClients = await self.clients.matchAll({
type: 'window',
includeUncontrolled: true
});
// 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') {
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.
focusedClient.postMessage({
type: 'PUSH_RECEIVED_FOREGROUND',
payload: payload
});
return;
}
const tag = payload.channelId
? `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',
tag: tag,
renotify: true,
data: payload
});
})());
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
const data = event.notification.data || {};
event.waitUntil((async () => {
const windowClients = await self.clients.matchAll({
type: 'window',
includeUncontrolled: true
});
for (const client of windowClients) {
if ('focus' in client) {
await client.focus();
client.postMessage({
type: 'OPEN_CONVERSATION',
channelId: data.channelId || '',
itemId: data.itemId || ''
});
return;
}
}
if (self.clients.openWindow) {
const targetUrl = data.channelId
? `/?channel=${encodeURIComponent(data.channelId)}&inboxItem=${encodeURIComponent(data.itemId || '')}`
: '/';
await self.clients.openWindow(targetUrl);
}
})());
});