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

@ -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