Compare commits
122 Commits
a1ddf380dd
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 2916d17868 | |||
| dd75ca4b06 | |||
| f819d7284e | |||
| b62ceb1949 | |||
| cd2d809322 | |||
| 1ed3efcc68 | |||
| 9fbe795660 | |||
| 63d3806936 | |||
| a9d2fd64de | |||
| f8b595f609 | |||
| 885db41ba9 | |||
| 3460ce6b04 | |||
| 4974663128 | |||
| ec6a8c446a | |||
| 3901542141 | |||
| 33eee17c43 | |||
| dd1aa45f6e | |||
| 38662f6655 | |||
| 777328caed | |||
| 87ade75f1d | |||
| 798652cb4d | |||
| 6a650a282b | |||
| 5b10afcec2 | |||
| 1220654656 | |||
| be797c55c2 | |||
| 20e99fefec | |||
| f77a5eb823 | |||
| d6ecb63b5f | |||
| 687387b105 | |||
| 5486795f4d | |||
| b90144d335 | |||
| 9a3e435dd4 | |||
| c4dfb07627 | |||
| 92c432cd49 | |||
| a52ae2f4a4 | |||
| 0c9ff3b5d9 | |||
| 3b75c2b785 | |||
| 4f6bbcf6e2 | |||
| a2608ffab9 | |||
| b70189c619 | |||
| 88c5d597d3 | |||
| 4a8170c448 | |||
| a56e246095 | |||
| fba86881ec | |||
| 28be2ae6c3 | |||
| 627d67be39 | |||
| 085507519a | |||
| a67f94b08e | |||
| c3b8dc5061 | |||
| e855948ca9 | |||
| 63a12b8d17 | |||
| dc37933fb8 | |||
| 9ad1d898ff | |||
| dad5de3d7f | |||
| c03e5102fb | |||
| 9e587ad7b5 | |||
| 8fb9126072 | |||
| e18e61710e | |||
| cec2d7593f | |||
| dff05dd596 | |||
| 31646a315a | |||
| 7af9cd0df8 | |||
| 68a905a292 | |||
| df438e265b | |||
| 98a837cc8b | |||
| 9b666ee109 | |||
| 3c1a4c7a2d | |||
| 7d8755ca71 | |||
| aa7f6597c4 | |||
| 9f4d4eaa15 | |||
| e5a1166bec | |||
| e7994f00b1 | |||
| 7af1295754 | |||
| 3aec6e23b2 | |||
| 3f27c94032 | |||
| c89a0cf88b | |||
| 63e427a4a1 | |||
| b7af055845 | |||
| 941dcc16d9 | |||
| ebda006010 | |||
| cf70b82024 | |||
| f24a255d12 | |||
| 776889932e | |||
| 701e30c31b | |||
| 9a6fcfb6de | |||
| 5a69ea627e | |||
| fe2473be21 | |||
| e4e7a70b2c | |||
| bdaf793094 | |||
| 65eb163482 | |||
| 6d9c3c9a40 | |||
| 92db27edc4 | |||
| cb59cc4409 | |||
| c193061fe3 | |||
| a4f0175ca4 | |||
| 6287f4d19b | |||
| bb34b7b0fa | |||
| dc3d954757 | |||
| 2269866539 | |||
| e9f96b7389 | |||
| 6fedad92b1 | |||
| 8c6724038a | |||
| 0bb3aa28b1 | |||
| a5772d7579 | |||
| 3d5c35fb15 | |||
| 619f1add51 | |||
| caf020c393 | |||
| 69a4951579 | |||
| d0839308ef | |||
| 8a771220e4 | |||
| cc31c4024a | |||
| 2b2b16271b | |||
| 4961ced384 | |||
| 187c8de6d3 | |||
| 2dfc898e8a | |||
| 44fa9a8bb2 | |||
| aac69ea770 | |||
| 46ba326150 | |||
| 9bc41d9a6d | |||
| cc921f4b70 | |||
| 916801e524 | |||
| d3d52c3553 |
14
Relay.sln
14
Relay.sln
@@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RelayClient", "RelayClient\
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RelayServer", "RelayServer\RelayServer.csproj", "{38995780-E9AA-44D6-B62D-07CCA45E4E4C}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RelayServer", "RelayServer\RelayServer.csproj", "{38995780-E9AA-44D6-B62D-07CCA45E4E4C}"
|
||||||
EndProject
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RelayShared", "RelayShared\RelayShared.csproj", "{60B17B0B-9910-426A-9B48-AD9377AC89F7}"
|
||||||
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@@ -55,6 +57,18 @@ Global
|
|||||||
{38995780-E9AA-44D6-B62D-07CCA45E4E4C}.Release|x64.Build.0 = Release|Any CPU
|
{38995780-E9AA-44D6-B62D-07CCA45E4E4C}.Release|x64.Build.0 = Release|Any CPU
|
||||||
{38995780-E9AA-44D6-B62D-07CCA45E4E4C}.Release|x86.ActiveCfg = Release|Any CPU
|
{38995780-E9AA-44D6-B62D-07CCA45E4E4C}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
{38995780-E9AA-44D6-B62D-07CCA45E4E4C}.Release|x86.Build.0 = Release|Any CPU
|
{38995780-E9AA-44D6-B62D-07CCA45E4E4C}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{60B17B0B-9910-426A-9B48-AD9377AC89F7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{60B17B0B-9910-426A-9B48-AD9377AC89F7}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{60B17B0B-9910-426A-9B48-AD9377AC89F7}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{60B17B0B-9910-426A-9B48-AD9377AC89F7}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{60B17B0B-9910-426A-9B48-AD9377AC89F7}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{60B17B0B-9910-426A-9B48-AD9377AC89F7}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{60B17B0B-9910-426A-9B48-AD9377AC89F7}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{60B17B0B-9910-426A-9B48-AD9377AC89F7}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{60B17B0B-9910-426A-9B48-AD9377AC89F7}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{60B17B0B-9910-426A-9B48-AD9377AC89F7}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{60B17B0B-9910-426A-9B48-AD9377AC89F7}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{60B17B0B-9910-426A-9B48-AD9377AC89F7}.Release|x86.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
|||||||
@@ -1,16 +1,32 @@
|
|||||||
using Microsoft.Extensions.DependencyInjection;
|
namespace RelayClient;
|
||||||
|
|
||||||
namespace RelayClient;
|
|
||||||
|
|
||||||
public partial class App : Application
|
public partial class App : Application
|
||||||
{
|
{
|
||||||
public App()
|
public App()
|
||||||
{
|
{
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
|
|
||||||
|
var username = Environment.GetCommandLineArgs()
|
||||||
|
.Skip(1)
|
||||||
|
.Chunk(2)
|
||||||
|
.Where(x => x.Length == 2 && x[0] == "--user")
|
||||||
|
.Select(x => x[1])
|
||||||
|
.FirstOrDefault();
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(username))
|
||||||
|
{
|
||||||
|
username = "Test";
|
||||||
|
// throw new Exception("Missing required --user argument. Example: --user Keeper317");
|
||||||
|
}
|
||||||
|
|
||||||
|
ClientSession.Username = username;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected override Window CreateWindow(IActivationState? activationState)
|
protected override Window CreateWindow(IActivationState? activationState)
|
||||||
{
|
{
|
||||||
return new Window(new AppShell());
|
return new Window(new MainPage(ClientSession.Username))
|
||||||
|
{
|
||||||
|
Title = $"Relay Client - {ClientSession.Username}"
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,8 @@
|
|||||||
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
|
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
|
||||||
xmlns:local="clr-namespace:RelayClient"
|
xmlns:local="clr-namespace:RelayClient"
|
||||||
Title="RelayClient">
|
Title="RelayClient"
|
||||||
|
FlyoutBehavior="Flyout">
|
||||||
|
|
||||||
<ShellContent
|
<ShellContent
|
||||||
Title="Home"
|
Title="Home"
|
||||||
|
|||||||
8
RelayClient/ChatSimulator.cs
Normal file
8
RelayClient/ChatSimulator.cs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
namespace RelayClient;
|
||||||
|
|
||||||
|
public sealed class ChatMessage
|
||||||
|
{
|
||||||
|
public required string SenderUsername { get; set; }
|
||||||
|
public required string Text { get; set; }
|
||||||
|
public required DateTime Timestamp { get; set; }
|
||||||
|
}
|
||||||
6
RelayClient/ClientSession.cs
Normal file
6
RelayClient/ClientSession.cs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
namespace RelayClient;
|
||||||
|
|
||||||
|
public static class ClientSession
|
||||||
|
{
|
||||||
|
public static string Username { get; set; } = "Unknown";
|
||||||
|
}
|
||||||
95
RelayClient/Crypto/E2EeHelper.cs
Normal file
95
RelayClient/Crypto/E2EeHelper.cs
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace RelayClient.Crypto;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Client-side mirror of RelayServer.Services.Crypto.E2EeHelper. Identical algorithms +
|
||||||
|
/// key formats so blobs round-trip cleanly between server and client.
|
||||||
|
/// See the server class for full algorithm details.
|
||||||
|
/// </summary>
|
||||||
|
public static class E2EeHelper
|
||||||
|
{
|
||||||
|
/// <summary>Generates a fresh RSA-2048 keypair. Called once per user on first launch and persisted via KeyStorage.</summary>
|
||||||
|
public static (string publicKey, string privateKey) GenerateRsaKeyPair()
|
||||||
|
{
|
||||||
|
using var rsa = RSA.Create(2048);
|
||||||
|
|
||||||
|
return (
|
||||||
|
Convert.ToBase64String(rsa.ExportSubjectPublicKeyInfo()),
|
||||||
|
Convert.ToBase64String(rsa.ExportPkcs8PrivateKey())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Hybrid encrypts a plaintext string for a specific recipient: fresh AES-256 key encrypts
|
||||||
|
/// the payload (AES-GCM), then RSA-OAEP-SHA256 wraps the AES key with the recipient's
|
||||||
|
/// public key. Returns base64-encoded fields ready to ship in a SocketEncryptedMessage.
|
||||||
|
/// </summary>
|
||||||
|
public static EncryptedPayload EncryptForRecipient(string plainText, string recipientPublicKeyBase64)
|
||||||
|
{
|
||||||
|
byte[] aesKey = RandomNumberGenerator.GetBytes(32);
|
||||||
|
byte[] nonce = RandomNumberGenerator.GetBytes(12);
|
||||||
|
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
|
||||||
|
byte[] cipherBytes = new byte[plainBytes.Length];
|
||||||
|
byte[] tag = new byte[16];
|
||||||
|
|
||||||
|
using (var aes = new AesGcm(aesKey, 16))
|
||||||
|
{
|
||||||
|
aes.Encrypt(nonce, plainBytes, cipherBytes, tag);
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] encryptedKey;
|
||||||
|
using (var rsa = RSA.Create())
|
||||||
|
{
|
||||||
|
rsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(recipientPublicKeyBase64), out _);
|
||||||
|
encryptedKey = rsa.Encrypt(aesKey, RSAEncryptionPadding.OaepSHA256);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new EncryptedPayload
|
||||||
|
{
|
||||||
|
CipherText = Convert.ToBase64String(cipherBytes),
|
||||||
|
Nonce = Convert.ToBase64String(nonce),
|
||||||
|
Tag = Convert.ToBase64String(tag),
|
||||||
|
EncryptedKey = Convert.ToBase64String(encryptedKey)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reverse of EncryptForRecipient: RSA-decrypt the AES key with the recipient's private
|
||||||
|
/// key, then AES-GCM-decrypt the ciphertext. Throws on tampered/corrupt payloads
|
||||||
|
/// (auth tag mismatch). Returns the original UTF-8 plaintext string.
|
||||||
|
/// </summary>
|
||||||
|
public static string DecryptForRecipient(EncryptedPayload payload, string recipientPrivateKeyBase64)
|
||||||
|
{
|
||||||
|
byte[] aesKey;
|
||||||
|
using (var rsa = RSA.Create())
|
||||||
|
{
|
||||||
|
rsa.ImportPkcs8PrivateKey(Convert.FromBase64String(recipientPrivateKeyBase64), out _);
|
||||||
|
aesKey = rsa.Decrypt(Convert.FromBase64String(payload.EncryptedKey), RSAEncryptionPadding.OaepSHA256);
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] plainBytes = new byte[Convert.FromBase64String(payload.CipherText).Length];
|
||||||
|
|
||||||
|
using (var aes = new AesGcm(aesKey, 16))
|
||||||
|
{
|
||||||
|
aes.Decrypt(
|
||||||
|
Convert.FromBase64String(payload.Nonce),
|
||||||
|
Convert.FromBase64String(payload.CipherText),
|
||||||
|
Convert.FromBase64String(payload.Tag),
|
||||||
|
plainBytes
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Encoding.UTF8.GetString(plainBytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The 4-tuple ciphertext bundle. Same shape on both client and server; matches SocketEncryptedMessage's encrypted fields.</summary>
|
||||||
|
public class EncryptedPayload
|
||||||
|
{
|
||||||
|
public required string CipherText { get; set; }
|
||||||
|
public required string Nonce { get; set; }
|
||||||
|
public required string Tag { get; set; }
|
||||||
|
public required string EncryptedKey { get; set; }
|
||||||
|
}
|
||||||
52
RelayClient/Crypto/KeyStorage.cs
Normal file
52
RelayClient/Crypto/KeyStorage.cs
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
namespace RelayClient.Crypto;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Per-user RSA keypair persistence. Keys live as base64-encoded files in
|
||||||
|
/// {AppData}/keys/{username}.{public|private}.key
|
||||||
|
///
|
||||||
|
/// Plaintext on disk. For now this is fine because the only attack model is "someone else
|
||||||
|
/// has access to your filesystem" — at which point everything is compromised. A future
|
||||||
|
/// enhancement could encrypt the private key with a passphrase derived from the user's
|
||||||
|
/// password, similar to how SSH/PGP do it.
|
||||||
|
/// </summary>
|
||||||
|
public static class KeyStorage
|
||||||
|
{
|
||||||
|
/// <summary>Returns (and creates if needed) the per-app keys directory.</summary>
|
||||||
|
private static string GetKeyFolder()
|
||||||
|
{
|
||||||
|
var folder = Path.Combine(FileSystem.AppDataDirectory, "keys");
|
||||||
|
Directory.CreateDirectory(folder);
|
||||||
|
return folder;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes the base64 RSA private key to disk. Used at first-launch after GenerateRsaKeyPair.</summary>
|
||||||
|
public static void SavePrivateKey(string username, string privateKey)
|
||||||
|
{
|
||||||
|
File.WriteAllText(Path.Combine(GetKeyFolder(), $"{username}.private.key"), privateKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Writes the base64 RSA public key to disk. Sent to the server via WsAction.RegisterKey.</summary>
|
||||||
|
public static void SavePublicKey(string username, string publicKey)
|
||||||
|
{
|
||||||
|
File.WriteAllText(Path.Combine(GetKeyFolder(), $"{username}.public.key"), publicKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Reads the user's RSA private key. Used by TryDecryptAndParseContent on every inbound message.</summary>
|
||||||
|
public static string LoadPrivateKey(string username)
|
||||||
|
{
|
||||||
|
return File.ReadAllText(Path.Combine(GetKeyFolder(), $"{username}.private.key"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Reads the user's RSA public key. Used during the boot handshake to send to the server.</summary>
|
||||||
|
public static string LoadPublicKey(string username)
|
||||||
|
{
|
||||||
|
return File.ReadAllText(Path.Combine(GetKeyFolder(), $"{username}.public.key"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>True if BOTH halves of the user's keypair already exist on disk. False means we need to generate.</summary>
|
||||||
|
public static bool HasKeys(string username)
|
||||||
|
{
|
||||||
|
return File.Exists(Path.Combine(GetKeyFolder(), $"{username}.private.key")) &&
|
||||||
|
File.Exists(Path.Combine(GetKeyFolder(), $"{username}.public.key"));
|
||||||
|
}
|
||||||
|
}
|
||||||
498
RelayClient/Helpers/EmbedHelper.cs
Normal file
498
RelayClient/Helpers/EmbedHelper.cs
Normal file
@@ -0,0 +1,498 @@
|
|||||||
|
using System.Net.Http;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace RelayClient.Helpers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Detects URLs in message text and builds embed views:
|
||||||
|
/// • Direct image URLs → inline Image (loaded lazily from URI or base64).
|
||||||
|
/// • relay:// jump links → tappable "Jump to message" card.
|
||||||
|
/// • Everything else → a link card with an async OG-tag preview loaded in the background.
|
||||||
|
/// </summary>
|
||||||
|
public static class EmbedHelper
|
||||||
|
{
|
||||||
|
private static readonly Regex UrlPattern = new(
|
||||||
|
@"https?://[^\s<>""]+",
|
||||||
|
RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||||
|
|
||||||
|
private static readonly Regex RelayJumpPattern = new(
|
||||||
|
@"relay://jump/([^/]+)/(.+)",
|
||||||
|
RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||||
|
|
||||||
|
private static readonly HashSet<string> ImageExtensions =
|
||||||
|
[".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".avif"];
|
||||||
|
|
||||||
|
/// <summary>Extracts every distinct http/https URL from message text. De-duped so multiple occurrences don't double-embed.</summary>
|
||||||
|
public static List<string> DetectUrls(string text)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(text)) return [];
|
||||||
|
return UrlPattern.Matches(text).Select(m => m.Value).Distinct().ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Dispatcher: classifies each URL and delegates to the appropriate Build* method.
|
||||||
|
/// Order matters — jump links and YouTube/Vimeo IDs are checked before the generic
|
||||||
|
/// image-extension and link-card paths so the more specific embed wins.
|
||||||
|
/// </summary>
|
||||||
|
public static List<View> BuildEmbeds(string text)
|
||||||
|
{
|
||||||
|
var views = new List<View>();
|
||||||
|
foreach (var url in DetectUrls(text))
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (RelayJumpPattern.IsMatch(url))
|
||||||
|
views.Add(BuildJumpCard(url));
|
||||||
|
else if (TryGetYouTubeId(url, out var ytId))
|
||||||
|
views.Add(BuildYouTubeCard(url, ytId));
|
||||||
|
else if (TryGetVimeoId(url, out var vimeoId))
|
||||||
|
views.Add(BuildVimeoCard(url, vimeoId));
|
||||||
|
else if (IsImageUrl(url))
|
||||||
|
views.Add(BuildImageEmbed(url));
|
||||||
|
else
|
||||||
|
views.Add(BuildLinkCard(url));
|
||||||
|
}
|
||||||
|
catch { /* never crash the UI */ }
|
||||||
|
}
|
||||||
|
return views;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Decodes a base64 attachment to bytes and renders it as an inline Image. Used by
|
||||||
|
/// MainPage.BuildBubbleContent when a message has an image attachment.
|
||||||
|
/// </summary>
|
||||||
|
public static View BuildBase64ImageEmbed(string base64, string fileName)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var bytes = Convert.FromBase64String(base64);
|
||||||
|
var source = ImageSource.FromStream(() => new MemoryStream(bytes));
|
||||||
|
|
||||||
|
var image = new Image
|
||||||
|
{
|
||||||
|
Source = source,
|
||||||
|
Aspect = Aspect.AspectFit,
|
||||||
|
WidthRequest = 400,
|
||||||
|
MaximumHeightRequest = 300,
|
||||||
|
HorizontalOptions = LayoutOptions.Start
|
||||||
|
};
|
||||||
|
|
||||||
|
return new Border
|
||||||
|
{
|
||||||
|
StrokeThickness = 1,
|
||||||
|
Padding = new Thickness(4),
|
||||||
|
Margin = new Thickness(0, 4, 0, 0),
|
||||||
|
Content = image
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return new Label
|
||||||
|
{
|
||||||
|
Text = $"⚠ Could not render image: {fileName}",
|
||||||
|
FontSize = 12,
|
||||||
|
TextColor = Colors.Gray
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Renders a non-image attachment as a tappable card. Tap → writes the bytes to a temp
|
||||||
|
/// file and hands off to the system handler via Launcher.OpenAsync.
|
||||||
|
/// </summary>
|
||||||
|
public static View BuildFileCard(string base64, string fileName, string mimeType)
|
||||||
|
{
|
||||||
|
var label = new Label
|
||||||
|
{
|
||||||
|
Text = $"📎 {fileName}",
|
||||||
|
FontSize = 13,
|
||||||
|
TextColor = Color.FromArgb("#5DA8FF"),
|
||||||
|
TextDecorations = TextDecorations.Underline
|
||||||
|
};
|
||||||
|
|
||||||
|
var tap = new TapGestureRecognizer();
|
||||||
|
tap.Tapped += async (_, _) =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var bytes = Convert.FromBase64String(base64);
|
||||||
|
var tempPath = Path.Combine(Path.GetTempPath(), fileName);
|
||||||
|
await File.WriteAllBytesAsync(tempPath, bytes);
|
||||||
|
await Launcher.OpenAsync(new OpenFileRequest
|
||||||
|
{
|
||||||
|
File = new ReadOnlyFile(tempPath)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch { /* ignore launch errors */ }
|
||||||
|
};
|
||||||
|
label.GestureRecognizers.Add(tap);
|
||||||
|
|
||||||
|
return new Border
|
||||||
|
{
|
||||||
|
StrokeThickness = 1,
|
||||||
|
Padding = new Thickness(8, 6),
|
||||||
|
Margin = new Thickness(0, 4, 0, 0),
|
||||||
|
Content = label
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Direct image URL → inline Image (loaded async by MAUI from the URI). Tap opens in browser.</summary>
|
||||||
|
private static View BuildImageEmbed(string url)
|
||||||
|
{
|
||||||
|
var image = new Image
|
||||||
|
{
|
||||||
|
Source = ImageSource.FromUri(new Uri(url)),
|
||||||
|
Aspect = Aspect.AspectFit,
|
||||||
|
WidthRequest = 400,
|
||||||
|
MaximumHeightRequest = 300,
|
||||||
|
HorizontalOptions = LayoutOptions.Start
|
||||||
|
};
|
||||||
|
|
||||||
|
var tap = new TapGestureRecognizer();
|
||||||
|
tap.Tapped += (_, _) => _ = Launcher.OpenAsync(new Uri(url));
|
||||||
|
image.GestureRecognizers.Add(tap);
|
||||||
|
|
||||||
|
return new Border
|
||||||
|
{
|
||||||
|
StrokeThickness = 1,
|
||||||
|
Padding = new Thickness(4),
|
||||||
|
Margin = new Thickness(0, 4, 0, 0),
|
||||||
|
Content = image
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds the "💬 Jump to linked message" card for relay://jump URLs. The actual tap
|
||||||
|
/// handler is wired by MainPage.WireJumpLinks because it needs access to the message
|
||||||
|
/// bubble dictionary that EmbedHelper doesn't know about.
|
||||||
|
/// </summary>
|
||||||
|
private static View BuildJumpCard(string relayUrl)
|
||||||
|
{
|
||||||
|
var label = new Label
|
||||||
|
{
|
||||||
|
Text = "💬 Jump to linked message",
|
||||||
|
FontSize = 12,
|
||||||
|
TextColor = Color.FromArgb("#9ECEFF"),
|
||||||
|
TextDecorations = TextDecorations.Underline
|
||||||
|
};
|
||||||
|
|
||||||
|
label.SetValue(JumpUrlProperty, relayUrl);
|
||||||
|
|
||||||
|
return new Border
|
||||||
|
{
|
||||||
|
StrokeThickness = 1,
|
||||||
|
Padding = new Thickness(8, 4),
|
||||||
|
Margin = new Thickness(0, 4, 0, 0),
|
||||||
|
Content = label
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Attached property that stores the relay:// URL on the jump label so MainPage.WireJumpLinks can find it.</summary>
|
||||||
|
public static readonly BindableProperty JumpUrlProperty =
|
||||||
|
BindableProperty.CreateAttached("JumpUrl", typeof(string), typeof(EmbedHelper), null);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Generic URL card. Starts with just the URL itself; spawns a background task to fetch
|
||||||
|
/// OG meta tags from the page and append a title/description/preview-image when the
|
||||||
|
/// response arrives. The whole card is tappable to open the URL in the browser.
|
||||||
|
/// </summary>
|
||||||
|
private static View BuildLinkCard(string url)
|
||||||
|
{
|
||||||
|
var displayUrl = url.Length > 55 ? url[..52] + "…" : url;
|
||||||
|
|
||||||
|
var card = new VerticalStackLayout { Spacing = 4 };
|
||||||
|
|
||||||
|
var urlLabel = new Label
|
||||||
|
{
|
||||||
|
Text = "🔗 " + displayUrl,
|
||||||
|
FontSize = 12,
|
||||||
|
TextColor = Color.FromArgb("#5DA8FF"),
|
||||||
|
TextDecorations = TextDecorations.Underline,
|
||||||
|
LineBreakMode = LineBreakMode.TailTruncation
|
||||||
|
};
|
||||||
|
|
||||||
|
var tapUrl = new TapGestureRecognizer();
|
||||||
|
tapUrl.Tapped += (_, _) => _ = Launcher.OpenAsync(new Uri(url));
|
||||||
|
urlLabel.GestureRecognizers.Add(tapUrl);
|
||||||
|
card.Children.Add(urlLabel);
|
||||||
|
|
||||||
|
_ = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
var og = await FetchOgTagsAsync(url);
|
||||||
|
if (og is null) return;
|
||||||
|
|
||||||
|
MainThread.BeginInvokeOnMainThread(() =>
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(og.Title))
|
||||||
|
{
|
||||||
|
card.Children.Add(new Label
|
||||||
|
{
|
||||||
|
Text = og.Title,
|
||||||
|
FontSize = 13,
|
||||||
|
FontAttributes = FontAttributes.Bold,
|
||||||
|
MaxLines = 2,
|
||||||
|
LineBreakMode = LineBreakMode.TailTruncation
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(og.Description))
|
||||||
|
{
|
||||||
|
card.Children.Add(new Label
|
||||||
|
{
|
||||||
|
Text = og.Description,
|
||||||
|
FontSize = 11,
|
||||||
|
TextColor = Colors.LightGray,
|
||||||
|
MaxLines = 3,
|
||||||
|
LineBreakMode = LineBreakMode.TailTruncation
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(og.ImageUrl) && IsImageUrl(og.ImageUrl))
|
||||||
|
{
|
||||||
|
card.Children.Add(new Image
|
||||||
|
{
|
||||||
|
Source = ImageSource.FromUri(new Uri(og.ImageUrl)),
|
||||||
|
Aspect = Aspect.AspectFit,
|
||||||
|
WidthRequest = 360,
|
||||||
|
MaximumHeightRequest = 200,
|
||||||
|
HorizontalOptions = LayoutOptions.Start
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return new Border
|
||||||
|
{
|
||||||
|
StrokeThickness = 1,
|
||||||
|
Padding = new Thickness(8, 6),
|
||||||
|
Margin = new Thickness(0, 4, 0, 0),
|
||||||
|
Content = card
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed record OgData(string? Title, string? Description, string? ImageUrl);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 4-second-budget HTTP GET + regex extract of og:title, og:description, og:image meta
|
||||||
|
/// tags from a page's HTML. Returns null on any failure (so the link card just stays bare).
|
||||||
|
/// </summary>
|
||||||
|
private static async Task<OgData?> FetchOgTagsAsync(string url)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(4) };
|
||||||
|
client.DefaultRequestHeaders.Add("User-Agent", "Relay/1.0 (link preview)");
|
||||||
|
|
||||||
|
var html = await client.GetStringAsync(url);
|
||||||
|
|
||||||
|
var title = GetMetaContent(html, "og:title")
|
||||||
|
?? GetTitleTag(html);
|
||||||
|
var description = GetMetaContent(html, "og:description");
|
||||||
|
var image = GetMetaContent(html, "og:image");
|
||||||
|
|
||||||
|
if (title is null && description is null && image is null) return null;
|
||||||
|
return new OgData(title, description, image);
|
||||||
|
}
|
||||||
|
catch { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? GetMetaContent(string html, string property)
|
||||||
|
{
|
||||||
|
var pattern = $"""<meta[^>]+property=["']{Regex.Escape(property)}["'][^>]+content=["']([^"']+)["']""";
|
||||||
|
var m = Regex.Match(html, pattern, RegexOptions.IgnoreCase);
|
||||||
|
if (m.Success) return System.Net.WebUtility.HtmlDecode(m.Groups[1].Value.Trim());
|
||||||
|
|
||||||
|
var pattern2 = $"""<meta[^>]+content=["']([^"']+)["'][^>]+property=["']{Regex.Escape(property)}["']""";
|
||||||
|
m = Regex.Match(html, pattern2, RegexOptions.IgnoreCase);
|
||||||
|
return m.Success ? System.Net.WebUtility.HtmlDecode(m.Groups[1].Value.Trim()) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? GetTitleTag(string html)
|
||||||
|
{
|
||||||
|
var m = Regex.Match(html, @"<title[^>]*>([^<]+)</title>", RegexOptions.IgnoreCase);
|
||||||
|
return m.Success ? System.Net.WebUtility.HtmlDecode(m.Groups[1].Value.Trim()) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>True if the URL's path ends with a known image extension. Used to choose between BuildImageEmbed and BuildLinkCard.</summary>
|
||||||
|
private static bool IsImageUrl(string url)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var path = new Uri(url).AbsolutePath;
|
||||||
|
var ext = Path.GetExtension(path).ToLowerInvariant();
|
||||||
|
return ImageExtensions.Contains(ext);
|
||||||
|
}
|
||||||
|
catch { return false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly Regex YouTubePattern = new(
|
||||||
|
@"(?:youtube\.com/(?:watch\?(?:.*&)?v=|embed/|shorts/|v/)|youtu\.be/)([A-Za-z0-9_-]{6,})",
|
||||||
|
RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||||
|
|
||||||
|
/// <summary>Extracts the 11-char video ID from any YouTube URL form (watch, youtu.be, embed, shorts, /v/).</summary>
|
||||||
|
private static bool TryGetYouTubeId(string url, out string id)
|
||||||
|
{
|
||||||
|
var match = YouTubePattern.Match(url);
|
||||||
|
if (match.Success)
|
||||||
|
{
|
||||||
|
id = match.Groups[1].Value;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
id = string.Empty;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly Regex VimeoPattern = new(
|
||||||
|
@"vimeo\.com/(?:video/|channels/[^/]+/|groups/[^/]+/videos/)?(\d{6,})",
|
||||||
|
RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||||
|
|
||||||
|
/// <summary>Extracts the numeric video ID from Vimeo URLs. Handles vimeo.com/{id}, /video/{id}, channels/x/{id}, groups/x/videos/{id}.</summary>
|
||||||
|
private static bool TryGetVimeoId(string url, out string id)
|
||||||
|
{
|
||||||
|
var match = VimeoPattern.Match(url);
|
||||||
|
if (match.Success)
|
||||||
|
{
|
||||||
|
id = match.Groups[1].Value;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
id = string.Empty;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>YouTube embed card. Thumbnail comes from img.youtube.com; player swaps to the youtube.com/embed/ URL on tap.</summary>
|
||||||
|
private static View BuildYouTubeCard(string url, string videoId) =>
|
||||||
|
BuildVideoCardWithEmbed(
|
||||||
|
providerLabel: "🎬 YouTube",
|
||||||
|
providerColor: Color.FromArgb("#FF4444"),
|
||||||
|
externalUrl: url,
|
||||||
|
thumbnailUrl: $"https://img.youtube.com/vi/{videoId}/hqdefault.jpg",
|
||||||
|
embedUrl: $"https://www.youtube.com/embed/{videoId}?autoplay=1&rel=0");
|
||||||
|
|
||||||
|
/// <summary>Vimeo embed card. No thumbnail (Vimeo's API requires OAuth); placeholder stays black with a play badge until tap.</summary>
|
||||||
|
private static View BuildVimeoCard(string url, string videoId) =>
|
||||||
|
BuildVideoCardWithEmbed(
|
||||||
|
providerLabel: "🎬 Vimeo",
|
||||||
|
providerColor: Color.FromArgb("#1AB7EA"),
|
||||||
|
externalUrl: url,
|
||||||
|
thumbnailUrl: null, // Vimeo thumbs require an API call; skip and show a black placeholder
|
||||||
|
embedUrl: $"https://player.vimeo.com/video/{videoId}?autoplay=1");
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The lazy-swap player. Default content is BuildThumbnailPlaceholder (cheap — no WebView
|
||||||
|
/// spawned). On tap, the ContentView's content swaps to a WebView pointing at embedUrl.
|
||||||
|
/// Means 50 videos in scrollback = 50 thumbnails, not 50 WebViews.
|
||||||
|
/// </summary>
|
||||||
|
private static View BuildVideoCardWithEmbed(
|
||||||
|
string providerLabel,
|
||||||
|
Color providerColor,
|
||||||
|
string externalUrl,
|
||||||
|
string? thumbnailUrl,
|
||||||
|
string embedUrl)
|
||||||
|
{
|
||||||
|
var card = new VerticalStackLayout { Spacing = 4 };
|
||||||
|
|
||||||
|
var headerRow = new HorizontalStackLayout { Spacing = 10 };
|
||||||
|
headerRow.Children.Add(new Label
|
||||||
|
{
|
||||||
|
Text = providerLabel,
|
||||||
|
FontSize = 11,
|
||||||
|
FontAttributes = FontAttributes.Bold,
|
||||||
|
TextColor = providerColor
|
||||||
|
});
|
||||||
|
|
||||||
|
var openExternal = new Label
|
||||||
|
{
|
||||||
|
Text = "↗ Open in browser",
|
||||||
|
FontSize = 10,
|
||||||
|
TextColor = Color.FromArgb("#8E8E93"),
|
||||||
|
TextDecorations = TextDecorations.Underline
|
||||||
|
};
|
||||||
|
var openTap = new TapGestureRecognizer();
|
||||||
|
openTap.Tapped += (_, _) => _ = Launcher.OpenAsync(new Uri(externalUrl));
|
||||||
|
openExternal.GestureRecognizers.Add(openTap);
|
||||||
|
headerRow.Children.Add(openExternal);
|
||||||
|
|
||||||
|
card.Children.Add(headerRow);
|
||||||
|
|
||||||
|
var playerHost = new ContentView
|
||||||
|
{
|
||||||
|
HorizontalOptions = LayoutOptions.Start,
|
||||||
|
Content = BuildThumbnailPlaceholder(thumbnailUrl, () =>
|
||||||
|
{
|
||||||
|
// On tap → swap the placeholder for a real player.
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
playerHost.Content = BuildThumbnailPlaceholder(thumbnailUrl, () =>
|
||||||
|
{
|
||||||
|
playerHost.Content = BuildEmbeddedPlayer(embedUrl);
|
||||||
|
});
|
||||||
|
|
||||||
|
card.Children.Add(playerHost);
|
||||||
|
|
||||||
|
return new Border
|
||||||
|
{
|
||||||
|
StrokeThickness = 1,
|
||||||
|
Padding = new Thickness(8, 6),
|
||||||
|
Margin = new Thickness(0, 4, 0, 0),
|
||||||
|
Content = card
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 16:9 thumbnail (or solid black if no thumb URL) with a translucent black play-badge
|
||||||
|
/// overlay. Calling onPlay swaps the parent ContentView's content to the real WebView.
|
||||||
|
/// </summary>
|
||||||
|
private static View BuildThumbnailPlaceholder(string? thumbnailUrl, Action onPlay)
|
||||||
|
{
|
||||||
|
var grid = new Grid
|
||||||
|
{
|
||||||
|
WidthRequest = 400,
|
||||||
|
HeightRequest = 225,
|
||||||
|
BackgroundColor = Colors.Black,
|
||||||
|
HorizontalOptions = LayoutOptions.Start
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(thumbnailUrl))
|
||||||
|
{
|
||||||
|
grid.Children.Add(new Image
|
||||||
|
{
|
||||||
|
Source = ImageSource.FromUri(new Uri(thumbnailUrl)),
|
||||||
|
Aspect = Aspect.AspectFill
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
var playBadge = new Label
|
||||||
|
{
|
||||||
|
Text = "▶",
|
||||||
|
FontSize = 36,
|
||||||
|
TextColor = Colors.White,
|
||||||
|
BackgroundColor = Color.FromArgb("#CC000000"),
|
||||||
|
HorizontalTextAlignment = TextAlignment.Center,
|
||||||
|
VerticalTextAlignment = TextAlignment.Center,
|
||||||
|
WidthRequest = 64,
|
||||||
|
HeightRequest = 64,
|
||||||
|
HorizontalOptions = LayoutOptions.Center,
|
||||||
|
VerticalOptions = LayoutOptions.Center
|
||||||
|
};
|
||||||
|
grid.Children.Add(playBadge);
|
||||||
|
|
||||||
|
var tap = new TapGestureRecognizer();
|
||||||
|
tap.Tapped += (_, _) => onPlay();
|
||||||
|
grid.GestureRecognizers.Add(tap);
|
||||||
|
|
||||||
|
return grid;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The actual in-client video player. WebView2 (Windows) and WebKit (mobile) both handle YouTube/Vimeo embed pages.</summary>
|
||||||
|
private static View BuildEmbeddedPlayer(string embedUrl)
|
||||||
|
{
|
||||||
|
return new WebView
|
||||||
|
{
|
||||||
|
Source = embedUrl,
|
||||||
|
WidthRequest = 480,
|
||||||
|
HeightRequest = 270,
|
||||||
|
HorizontalOptions = LayoutOptions.Start
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
411
RelayClient/Helpers/MarkdownHelper.cs
Normal file
411
RelayClient/Helpers/MarkdownHelper.cs
Normal file
@@ -0,0 +1,411 @@
|
|||||||
|
using System.Text;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace RelayClient.Helpers;
|
||||||
|
|
||||||
|
public static class MarkdownHelper
|
||||||
|
{
|
||||||
|
private static readonly Regex FencedCode =
|
||||||
|
new(@"```([A-Za-z0-9_+#-]*)\r?\n?(.*?)```", RegexOptions.Singleline | RegexOptions.Compiled);
|
||||||
|
|
||||||
|
private static readonly Color MentionText = Color.FromArgb("#9EA8FF");
|
||||||
|
private static readonly Color MentionBg = Color.FromArgb("#2D2F5C");
|
||||||
|
private static readonly Color SpoilerBg = Color.FromArgb("#1F1F23");
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The entry point. Returns either a single Label (simple inline text) or a
|
||||||
|
/// VerticalStackLayout (anything with paragraphs, code blocks, or headers).
|
||||||
|
/// First pass extracts fenced code blocks (verbatim, can span multiple lines), then
|
||||||
|
/// AppendTextSegment handles per-line headers and the inline parser.
|
||||||
|
/// </summary>
|
||||||
|
public static View Render(string markdown, double fontSize = 14)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(markdown))
|
||||||
|
return new Label { Text = string.Empty, FontSize = fontSize };
|
||||||
|
|
||||||
|
var stack = new VerticalStackLayout { Spacing = 2 };
|
||||||
|
|
||||||
|
var matches = FencedCode.Matches(markdown);
|
||||||
|
int cursor = 0;
|
||||||
|
|
||||||
|
foreach (Match m in matches)
|
||||||
|
{
|
||||||
|
if (m.Index > cursor)
|
||||||
|
AppendTextSegment(stack, markdown[cursor..m.Index], fontSize);
|
||||||
|
|
||||||
|
stack.Children.Add(CreateCodeBlock(m.Groups[1].Value.Trim(), m.Groups[2].Value.TrimEnd()));
|
||||||
|
cursor = m.Index + m.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cursor < markdown.Length)
|
||||||
|
AppendTextSegment(stack, markdown[cursor..], fontSize);
|
||||||
|
|
||||||
|
return stack.Children.Count == 1 ? (View)stack.Children[0] : stack;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Splits a non-code segment by newline and emits the right view per line. Headers/subtext
|
||||||
|
/// get their own labels; consecutive normal lines accumulate into a paragraph buffer so
|
||||||
|
/// they wrap naturally as one paragraph.
|
||||||
|
/// </summary>
|
||||||
|
private static void AppendTextSegment(VerticalStackLayout stack, string segment, double fontSize)
|
||||||
|
{
|
||||||
|
var paragraphBuffer = new StringBuilder();
|
||||||
|
|
||||||
|
void FlushParagraph()
|
||||||
|
{
|
||||||
|
if (paragraphBuffer.Length == 0) return;
|
||||||
|
stack.Children.Add(CreateInlineLabel(paragraphBuffer.ToString(), fontSize));
|
||||||
|
paragraphBuffer.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var rawLine in segment.Split('\n'))
|
||||||
|
{
|
||||||
|
var line = rawLine.TrimEnd('\r');
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(line))
|
||||||
|
{
|
||||||
|
FlushParagraph();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line.StartsWith("### "))
|
||||||
|
{
|
||||||
|
FlushParagraph();
|
||||||
|
stack.Children.Add(CreateHeaderLabel(line[4..], fontSize + 3));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line.StartsWith("## "))
|
||||||
|
{
|
||||||
|
FlushParagraph();
|
||||||
|
stack.Children.Add(CreateHeaderLabel(line[3..], fontSize + 6));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line.StartsWith("# "))
|
||||||
|
{
|
||||||
|
FlushParagraph();
|
||||||
|
stack.Children.Add(CreateHeaderLabel(line[2..], fontSize + 10));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line.StartsWith("-# "))
|
||||||
|
{
|
||||||
|
FlushParagraph();
|
||||||
|
stack.Children.Add(CreateSubtextLabel(line[3..], fontSize - 3));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (paragraphBuffer.Length > 0)
|
||||||
|
paragraphBuffer.Append('\n');
|
||||||
|
paragraphBuffer.Append(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
FlushParagraph();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds the dark-pane code block. If a language is specified, delegates token coloring
|
||||||
|
/// to SyntaxHighlighter and prepends a small green language label (Discord-style).
|
||||||
|
/// </summary>
|
||||||
|
private static View CreateCodeBlock(string language, string code)
|
||||||
|
{
|
||||||
|
var label = new Label
|
||||||
|
{
|
||||||
|
FontFamily = "AnonymousProRegular",
|
||||||
|
FontSize = 12,
|
||||||
|
TextColor = Color.FromArgb("#D4D4D4"),
|
||||||
|
LineBreakMode = LineBreakMode.WordWrap
|
||||||
|
};
|
||||||
|
|
||||||
|
var spans = SyntaxHighlighter.Highlight(code, language, 12);
|
||||||
|
if (spans.Count > 0)
|
||||||
|
{
|
||||||
|
var fs = new FormattedString();
|
||||||
|
foreach (var s in spans) fs.Spans.Add(s);
|
||||||
|
label.FormattedText = fs;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
label.Text = code;
|
||||||
|
}
|
||||||
|
|
||||||
|
var stack = new VerticalStackLayout { Spacing = 4 };
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(language))
|
||||||
|
{
|
||||||
|
stack.Children.Add(new Label
|
||||||
|
{
|
||||||
|
Text = language.ToLowerInvariant(),
|
||||||
|
FontFamily = "AnonymousProRegular",
|
||||||
|
FontSize = 10,
|
||||||
|
TextColor = Color.FromArgb("#6A9955"),
|
||||||
|
FontAttributes = FontAttributes.Bold
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
stack.Children.Add(label);
|
||||||
|
|
||||||
|
return new Border
|
||||||
|
{
|
||||||
|
BackgroundColor = Color.FromArgb("#1E1E1E"),
|
||||||
|
StrokeThickness = 0,
|
||||||
|
Padding = new Thickness(10, 6),
|
||||||
|
Content = stack
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Bold, larger Label for # / ## / ### lines. Inline markdown still works inside (e.g. `# Hello **world**`).</summary>
|
||||||
|
private static Label CreateHeaderLabel(string text, double size)
|
||||||
|
{
|
||||||
|
var label = new Label
|
||||||
|
{
|
||||||
|
FontSize = size,
|
||||||
|
FontAttributes = FontAttributes.Bold,
|
||||||
|
LineBreakMode = LineBreakMode.WordWrap,
|
||||||
|
Margin = new Thickness(0, 4, 0, 2)
|
||||||
|
};
|
||||||
|
|
||||||
|
var fs = new FormattedString();
|
||||||
|
var spoilerSpans = new List<Span>();
|
||||||
|
ParseInline(text, fs.Spans, size, spoilerSpans);
|
||||||
|
|
||||||
|
if (fs.Spans.Count > 0) label.FormattedText = fs;
|
||||||
|
else label.Text = text;
|
||||||
|
|
||||||
|
WireSpoilerTap(label, spoilerSpans);
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Smaller, grey Label for "-#" lines (Discord calls it subtext). Inherits inline markdown.</summary>
|
||||||
|
private static Label CreateSubtextLabel(string text, double size)
|
||||||
|
{
|
||||||
|
var label = new Label
|
||||||
|
{
|
||||||
|
FontSize = size,
|
||||||
|
TextColor = Color.FromArgb("#8E8E93"),
|
||||||
|
LineBreakMode = LineBreakMode.WordWrap
|
||||||
|
};
|
||||||
|
|
||||||
|
var fs = new FormattedString();
|
||||||
|
var spoilerSpans = new List<Span>();
|
||||||
|
ParseInline(text, fs.Spans, size, spoilerSpans);
|
||||||
|
|
||||||
|
if (fs.Spans.Count > 0)
|
||||||
|
{
|
||||||
|
foreach (var s in fs.Spans)
|
||||||
|
s.TextColor ??= Color.FromArgb("#8E8E93");
|
||||||
|
label.FormattedText = fs;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
label.Text = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
WireSpoilerTap(label, spoilerSpans);
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Standard paragraph Label. Runs the inline parser to build a FormattedString of spans.</summary>
|
||||||
|
private static Label CreateInlineLabel(string text, double fontSize)
|
||||||
|
{
|
||||||
|
var label = new Label { FontSize = fontSize, LineBreakMode = LineBreakMode.WordWrap };
|
||||||
|
var fs = new FormattedString();
|
||||||
|
var spoilerSpans = new List<Span>();
|
||||||
|
ParseInline(text, fs.Spans, fontSize, spoilerSpans);
|
||||||
|
|
||||||
|
if (fs.Spans.Count > 0) label.FormattedText = fs;
|
||||||
|
else label.Text = text;
|
||||||
|
|
||||||
|
WireSpoilerTap(label, spoilerSpans);
|
||||||
|
return label;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Attaches a TapGestureRecognizer that reveals every spoiler span in the label when
|
||||||
|
/// tapped once. MAUI Spans can't fire their own gesture events, so per-spoiler reveal
|
||||||
|
/// would require splitting the line into separate labels — this is the pragmatic compromise.
|
||||||
|
/// </summary>
|
||||||
|
private static void WireSpoilerTap(Label label, List<Span> spoilerSpans)
|
||||||
|
{
|
||||||
|
if (spoilerSpans.Count == 0) return;
|
||||||
|
|
||||||
|
var tap = new TapGestureRecognizer();
|
||||||
|
tap.Tapped += (_, _) =>
|
||||||
|
{
|
||||||
|
foreach (var s in spoilerSpans)
|
||||||
|
{
|
||||||
|
s.BackgroundColor = Colors.Transparent;
|
||||||
|
s.TextColor = null; // fall back to default label color
|
||||||
|
}
|
||||||
|
};
|
||||||
|
label.GestureRecognizers.Add(tap);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Single-pass character walk. For each markdown sigil (||, @, ~~, __, **, *, `), tries
|
||||||
|
/// to find a matching closer; if found, emits a styled Span and skips past. Otherwise the
|
||||||
|
/// char accumulates into a "plain" buffer that's flushed as a plain Span when the next
|
||||||
|
/// sigil hits or the string ends. Spoiler spans are registered in spoilerSpans for reveal.
|
||||||
|
/// </summary>
|
||||||
|
private static void ParseInline(string text, IList<Span> spans, double fontSize, List<Span> spoilerSpans)
|
||||||
|
{
|
||||||
|
var plain = new StringBuilder();
|
||||||
|
int i = 0;
|
||||||
|
|
||||||
|
void Flush()
|
||||||
|
{
|
||||||
|
if (plain.Length == 0) return;
|
||||||
|
spans.Add(new Span { Text = plain.ToString(), FontSize = fontSize });
|
||||||
|
plain.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
while (i < text.Length)
|
||||||
|
{
|
||||||
|
char c = text[i];
|
||||||
|
|
||||||
|
if (c == '|' && Peek(text, i + 1) == '|')
|
||||||
|
{
|
||||||
|
int end = text.IndexOf("||", i + 2, StringComparison.Ordinal);
|
||||||
|
if (end > i + 2)
|
||||||
|
{
|
||||||
|
Flush();
|
||||||
|
var span = new Span
|
||||||
|
{
|
||||||
|
Text = text[(i + 2)..end],
|
||||||
|
FontSize = fontSize,
|
||||||
|
BackgroundColor = SpoilerBg,
|
||||||
|
TextColor = SpoilerBg // text invisible until revealed
|
||||||
|
};
|
||||||
|
spans.Add(span);
|
||||||
|
spoilerSpans.Add(span);
|
||||||
|
i = end + 2;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '@' && i + 1 < text.Length &&
|
||||||
|
(char.IsLetter(text[i + 1]) || text[i + 1] == '_'))
|
||||||
|
{
|
||||||
|
int end = i + 1;
|
||||||
|
while (end < text.Length && (char.IsLetterOrDigit(text[end]) || text[end] == '_'))
|
||||||
|
end++;
|
||||||
|
|
||||||
|
Flush();
|
||||||
|
spans.Add(new Span
|
||||||
|
{
|
||||||
|
Text = text[i..end],
|
||||||
|
TextColor = MentionText,
|
||||||
|
BackgroundColor = MentionBg,
|
||||||
|
FontAttributes = FontAttributes.Bold,
|
||||||
|
FontSize = fontSize
|
||||||
|
});
|
||||||
|
i = end;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '~' && Peek(text, i + 1) == '~')
|
||||||
|
{
|
||||||
|
int end = text.IndexOf("~~", i + 2, StringComparison.Ordinal);
|
||||||
|
if (end > i + 2)
|
||||||
|
{
|
||||||
|
Flush();
|
||||||
|
spans.Add(new Span
|
||||||
|
{
|
||||||
|
Text = text[(i + 2)..end],
|
||||||
|
FontSize = fontSize,
|
||||||
|
TextDecorations = TextDecorations.Strikethrough
|
||||||
|
});
|
||||||
|
i = end + 2; continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '_' && Peek(text, i + 1) == '_')
|
||||||
|
{
|
||||||
|
int end = text.IndexOf("__", i + 2, StringComparison.Ordinal);
|
||||||
|
if (end > i + 2)
|
||||||
|
{
|
||||||
|
Flush();
|
||||||
|
spans.Add(new Span
|
||||||
|
{
|
||||||
|
Text = text[(i + 2)..end],
|
||||||
|
FontSize = fontSize,
|
||||||
|
TextDecorations = TextDecorations.Underline
|
||||||
|
});
|
||||||
|
i = end + 2; continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '*' && Peek(text, i + 1) == '*')
|
||||||
|
{
|
||||||
|
int end = text.IndexOf("**", i + 2, StringComparison.Ordinal);
|
||||||
|
if (end > i + 2)
|
||||||
|
{
|
||||||
|
Flush();
|
||||||
|
spans.Add(new Span
|
||||||
|
{
|
||||||
|
Text = text[(i + 2)..end],
|
||||||
|
FontSize = fontSize,
|
||||||
|
FontAttributes = FontAttributes.Bold
|
||||||
|
});
|
||||||
|
i = end + 2; continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '*' && Peek(text, i + 1) != '*')
|
||||||
|
{
|
||||||
|
int end = FindClosingSingle(text, '*', i + 1);
|
||||||
|
if (end > i + 1)
|
||||||
|
{
|
||||||
|
Flush();
|
||||||
|
spans.Add(new Span
|
||||||
|
{
|
||||||
|
Text = text[(i + 1)..end],
|
||||||
|
FontSize = fontSize,
|
||||||
|
FontAttributes = FontAttributes.Italic
|
||||||
|
});
|
||||||
|
i = end + 1; continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '`')
|
||||||
|
{
|
||||||
|
int end = text.IndexOf('`', i + 1);
|
||||||
|
if (end > i + 1)
|
||||||
|
{
|
||||||
|
Flush();
|
||||||
|
spans.Add(new Span
|
||||||
|
{
|
||||||
|
Text = text[(i + 1)..end],
|
||||||
|
FontFamily = "AnonymousProRegular",
|
||||||
|
FontSize = fontSize - 1,
|
||||||
|
BackgroundColor = Color.FromArgb("#2D2D2D"),
|
||||||
|
TextColor = Color.FromArgb("#CE9178")
|
||||||
|
});
|
||||||
|
i = end + 1; continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
plain.Append(c);
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
Flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Safe one-character lookahead. Returns '\0' past end-of-string.</summary>
|
||||||
|
private static char Peek(string text, int index) => index < text.Length ? text[index] : '\0';
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Finds the next single occurrence of marker that is NOT immediately followed by
|
||||||
|
/// another marker. Used to disambiguate "*italic*" from "**bold**".
|
||||||
|
/// </summary>
|
||||||
|
private static int FindClosingSingle(string text, char marker, int start)
|
||||||
|
{
|
||||||
|
for (int i = start; i < text.Length; i++)
|
||||||
|
if (text[i] == marker && Peek(text, i + 1) != marker)
|
||||||
|
return i;
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
361
RelayClient/Helpers/SyntaxHighlighter.cs
Normal file
361
RelayClient/Helpers/SyntaxHighlighter.cs
Normal file
@@ -0,0 +1,361 @@
|
|||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace RelayClient.Helpers;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Discord-style syntax highlighting for ```lang...``` fenced code blocks. Builds a list of
|
||||||
|
/// MAUI Spans (with colors from the VS Code Dark+ palette) that the caller drops into a
|
||||||
|
/// FormattedString.
|
||||||
|
///
|
||||||
|
/// How it works:
|
||||||
|
/// - The opening fence captures an optional language tag (e.g. ```cs, ```python).
|
||||||
|
/// - Aliases resolves "cs" → "csharp", "js" → "javascript", etc.
|
||||||
|
/// - Tokenizers[lang] is a compiled regex with named groups (comment/string/number/word/…).
|
||||||
|
/// - For each match, SpanForMatch picks a colour based on which group matched + whether
|
||||||
|
/// a "word" hit a language keyword set.
|
||||||
|
///
|
||||||
|
/// Adding a new language: register an alias (if needed), a Keywords set, and a tokenizer regex.
|
||||||
|
/// </summary>
|
||||||
|
public static class SyntaxHighlighter
|
||||||
|
{
|
||||||
|
/// <summary>Fallback identifier color (light grey). Used for any token we don't recognise.</summary>
|
||||||
|
private static readonly Color DefaultColor = Color.FromArgb("#D4D4D4");
|
||||||
|
/// <summary>Language keywords (if, for, return, etc.) — VS Code's "control flow" blue.</summary>
|
||||||
|
private static readonly Color KeywordColor = Color.FromArgb("#569CD6");
|
||||||
|
/// <summary>String literals — orange/salmon.</summary>
|
||||||
|
private static readonly Color StringColor = Color.FromArgb("#CE9178");
|
||||||
|
/// <summary>Numeric literals — soft green.</summary>
|
||||||
|
private static readonly Color NumberColor = Color.FromArgb("#B5CEA8");
|
||||||
|
/// <summary>Comments — green, rendered italic.</summary>
|
||||||
|
private static readonly Color CommentColor = Color.FromArgb("#6A9955");
|
||||||
|
/// <summary>Type names (heuristic: uppercase-start words in C#/JS/TS) — teal.</summary>
|
||||||
|
private static readonly Color TypeColor = Color.FromArgb("#4EC9B0");
|
||||||
|
/// <summary>Function names — yellow. Currently unused (we don't disambiguate function calls).</summary>
|
||||||
|
private static readonly Color FunctionColor = Color.FromArgb("#DCDCAA");
|
||||||
|
/// <summary>Operators — same as default. Reserved for future use.</summary>
|
||||||
|
private static readonly Color OperatorColor = Color.FromArgb("#D4D4D4");
|
||||||
|
/// <summary>HTML tag names (<div>, </p>) — blue.</summary>
|
||||||
|
private static readonly Color TagColor = Color.FromArgb("#569CD6");
|
||||||
|
/// <summary>HTML/CSS attribute names, YAML keys, bash variables — light blue.</summary>
|
||||||
|
private static readonly Color AttrColor = Color.FromArgb("#9CDCFE");
|
||||||
|
|
||||||
|
/// <summary>Monospace font registered in MauiProgram. Used for all code-block spans.</summary>
|
||||||
|
private const string FontFamily = "AnonymousProRegular";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Short language tags → canonical names. So users can write ```cs (instead of ```csharp),
|
||||||
|
/// ```py instead of ```python, etc. Case-insensitive.
|
||||||
|
/// </summary>
|
||||||
|
private static readonly Dictionary<string, string> Aliases = new(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{
|
||||||
|
["cs"] = "csharp",
|
||||||
|
["c#"] = "csharp",
|
||||||
|
["js"] = "javascript",
|
||||||
|
["jsx"] = "javascript",
|
||||||
|
["ts"] = "typescript",
|
||||||
|
["tsx"] = "typescript",
|
||||||
|
["py"] = "python",
|
||||||
|
["sh"] = "bash",
|
||||||
|
["shell"] = "bash",
|
||||||
|
["zsh"] = "bash",
|
||||||
|
["htm"] = "html",
|
||||||
|
["xml"] = "html",
|
||||||
|
["yml"] = "yaml"
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Per-language keyword sets. A token in a "word" match-group that hits one of these
|
||||||
|
/// gets rendered with KeywordColor. Case-sensitivity matches the language — Ordinal
|
||||||
|
/// for most languages, OrdinalIgnoreCase for SQL and CSS.
|
||||||
|
/// </summary>
|
||||||
|
private static readonly Dictionary<string, HashSet<string>> Keywords = new(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{
|
||||||
|
["csharp"] = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
"abstract","as","async","await","base","bool","break","byte","case","catch","char","checked",
|
||||||
|
"class","const","continue","decimal","default","delegate","do","double","else","enum","event",
|
||||||
|
"explicit","extern","false","finally","fixed","float","for","foreach","get","goto","if",
|
||||||
|
"implicit","in","int","interface","internal","is","lock","long","namespace","new","null",
|
||||||
|
"object","operator","out","override","params","partial","private","protected","public",
|
||||||
|
"readonly","record","ref","return","sbyte","sealed","set","short","sizeof","stackalloc",
|
||||||
|
"static","string","struct","switch","this","throw","true","try","typeof","uint","ulong",
|
||||||
|
"unchecked","unsafe","ushort","using","var","virtual","void","volatile","while","yield",
|
||||||
|
"nameof","when","where","global","init","required","file","scoped","with"
|
||||||
|
},
|
||||||
|
["javascript"] = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
"async","await","break","case","catch","class","const","continue","debugger","default",
|
||||||
|
"delete","do","else","enum","export","extends","false","finally","for","from","function",
|
||||||
|
"get","if","implements","import","in","instanceof","let","new","null","of","package",
|
||||||
|
"private","protected","public","return","set","static","super","switch","this","throw",
|
||||||
|
"true","try","typeof","undefined","var","void","while","with","yield"
|
||||||
|
},
|
||||||
|
["typescript"] = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
"any","as","async","await","boolean","break","case","catch","class","const","continue",
|
||||||
|
"debugger","declare","default","delete","do","else","enum","export","extends","false",
|
||||||
|
"finally","for","from","function","get","if","implements","import","in","instanceof",
|
||||||
|
"interface","is","keyof","let","namespace","never","new","null","number","of","package",
|
||||||
|
"private","protected","public","readonly","return","set","static","string","super",
|
||||||
|
"switch","this","throw","true","try","type","typeof","undefined","unknown","var","void",
|
||||||
|
"while","with","yield"
|
||||||
|
},
|
||||||
|
["python"] = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
"and","as","assert","async","await","break","class","continue","def","del","elif","else",
|
||||||
|
"except","False","finally","for","from","global","if","import","in","is","lambda","None",
|
||||||
|
"nonlocal","not","or","pass","raise","return","True","try","while","with","yield","self",
|
||||||
|
"cls","match","case"
|
||||||
|
},
|
||||||
|
["sql"] = new(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{
|
||||||
|
"select","from","where","insert","update","delete","create","alter","drop","table","index",
|
||||||
|
"view","join","inner","outer","left","right","full","cross","on","as","group","by","order",
|
||||||
|
"having","distinct","union","all","into","values","set","null","not","and","or","in","like",
|
||||||
|
"between","is","true","false","primary","key","foreign","references","default","limit",
|
||||||
|
"offset","with","case","when","then","else","end","exists","cast","begin","commit","rollback"
|
||||||
|
},
|
||||||
|
["bash"] = new(StringComparer.Ordinal)
|
||||||
|
{
|
||||||
|
"if","then","else","elif","fi","for","in","do","done","while","until","case","esac",
|
||||||
|
"function","return","break","continue","exit","echo","printf","export","local","readonly",
|
||||||
|
"source","alias","unset","trap","set","eval","exec","shift","let","declare","typeset"
|
||||||
|
},
|
||||||
|
["json"] = new(StringComparer.Ordinal) { "true","false","null" },
|
||||||
|
["yaml"] = new(StringComparer.Ordinal) { "true","false","null","yes","no","on","off" },
|
||||||
|
["css"] = new(StringComparer.OrdinalIgnoreCase)
|
||||||
|
{
|
||||||
|
"important","inherit","initial","unset","auto","none","normal","bold","italic","center",
|
||||||
|
"left","right","top","bottom","flex","grid","block","inline","absolute","relative","fixed",
|
||||||
|
"sticky","static"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Per-language compiled token regex. Each pattern uses named groups (comment/string/
|
||||||
|
/// number/word/tag/attr/…) which SpanForMatch dispatches on. Initialised lazily in the
|
||||||
|
/// static constructor so the heavy regex compilation is paid once at startup.
|
||||||
|
/// </summary>
|
||||||
|
private static readonly Dictionary<string, Regex> Tokenizers = new(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
static SyntaxHighlighter()
|
||||||
|
{
|
||||||
|
const RegexOptions opts = RegexOptions.Compiled | RegexOptions.Singleline;
|
||||||
|
|
||||||
|
Tokenizers["csharp"] = new Regex(
|
||||||
|
@"(?<comment>//[^\n]*|/\*.*?\*/)" +
|
||||||
|
@"|(?<string>@""(?:""""|[^""])*""|\$""(?:\\.|[^""\\])*""|""(?:\\.|[^""\\])*""|'(?:\\.|[^'\\])*')" +
|
||||||
|
@"|(?<number>\b\d+(?:\.\d+)?[fFdDmMuUlL]*\b)" +
|
||||||
|
@"|(?<word>[A-Za-z_]\w*)",
|
||||||
|
opts);
|
||||||
|
|
||||||
|
Tokenizers["javascript"] = new Regex(
|
||||||
|
@"(?<comment>//[^\n]*|/\*.*?\*/)" +
|
||||||
|
@"|(?<string>""(?:\\.|[^""\\])*""|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)" +
|
||||||
|
@"|(?<number>\b\d+(?:\.\d+)?\b)" +
|
||||||
|
@"|(?<word>[A-Za-z_$][\w$]*)",
|
||||||
|
opts);
|
||||||
|
|
||||||
|
Tokenizers["typescript"] = Tokenizers["javascript"];
|
||||||
|
|
||||||
|
Tokenizers["python"] = new Regex(
|
||||||
|
@"(?<comment>\#[^\n]*)" +
|
||||||
|
@"|(?<string>""""""[\s\S]*?""""""|'''[\s\S]*?'''|""(?:\\.|[^""\\])*""|'(?:\\.|[^'\\])*')" +
|
||||||
|
@"|(?<number>\b\d+(?:\.\d+)?\b)" +
|
||||||
|
@"|(?<word>[A-Za-z_]\w*)",
|
||||||
|
opts);
|
||||||
|
|
||||||
|
Tokenizers["sql"] = new Regex(
|
||||||
|
@"(?<comment>--[^\n]*|/\*.*?\*/)" +
|
||||||
|
@"|(?<string>'(?:''|[^'])*')" +
|
||||||
|
@"|(?<number>\b\d+(?:\.\d+)?\b)" +
|
||||||
|
@"|(?<word>[A-Za-z_]\w*)",
|
||||||
|
opts);
|
||||||
|
|
||||||
|
Tokenizers["bash"] = new Regex(
|
||||||
|
@"(?<comment>\#[^\n]*)" +
|
||||||
|
@"|(?<string>""(?:\\.|[^""\\])*""|'[^']*')" +
|
||||||
|
@"|(?<number>\b\d+\b)" +
|
||||||
|
@"|(?<variable>\$\{?[A-Za-z_]\w*\}?)" +
|
||||||
|
@"|(?<word>[A-Za-z_][\w-]*)",
|
||||||
|
opts);
|
||||||
|
|
||||||
|
Tokenizers["json"] = new Regex(
|
||||||
|
@"(?<string>""(?:\\.|[^""\\])*"")" +
|
||||||
|
@"|(?<number>-?\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b)" +
|
||||||
|
@"|(?<word>true|false|null)",
|
||||||
|
opts);
|
||||||
|
|
||||||
|
Tokenizers["yaml"] = new Regex(
|
||||||
|
@"(?<comment>\#[^\n]*)" +
|
||||||
|
@"|(?<string>""(?:\\.|[^""\\])*""|'[^']*')" +
|
||||||
|
@"|(?<key>^[ \t]*[A-Za-z_][\w-]*(?=\s*:))" +
|
||||||
|
@"|(?<number>\b\d+(?:\.\d+)?\b)" +
|
||||||
|
@"|(?<word>[A-Za-z_][\w-]*)",
|
||||||
|
opts | RegexOptions.Multiline);
|
||||||
|
|
||||||
|
Tokenizers["html"] = new Regex(
|
||||||
|
@"(?<comment><!--.*?-->)" +
|
||||||
|
@"|(?<string>""[^""]*""|'[^']*')" +
|
||||||
|
@"|(?<tag></?[A-Za-z][A-Za-z0-9-]*)" +
|
||||||
|
@"|(?<attr>\b[A-Za-z_][\w-]*(?==))",
|
||||||
|
opts);
|
||||||
|
|
||||||
|
Tokenizers["css"] = new Regex(
|
||||||
|
@"(?<comment>/\*.*?\*/)" +
|
||||||
|
@"|(?<string>""[^""]*""|'[^']*')" +
|
||||||
|
@"|(?<number>-?\b\d+(?:\.\d+)?(?:px|em|rem|%|vh|vw|s|ms|deg)?\b)" +
|
||||||
|
@"|(?<selector>[.#]?[A-Za-z_][\w-]*(?=\s*[{,]))" +
|
||||||
|
@"|(?<prop>[A-Za-z-]+(?=\s*:))" +
|
||||||
|
@"|(?<word>[A-Za-z_][\w-]*)",
|
||||||
|
opts);
|
||||||
|
|
||||||
|
Tokenizers["diff"] = new Regex(
|
||||||
|
@"(?<add>^\+[^\n]*)" +
|
||||||
|
@"|(?<del>^-[^\n]*)" +
|
||||||
|
@"|(?<hunk>^@@[^\n]*)",
|
||||||
|
opts | RegexOptions.Multiline);
|
||||||
|
|
||||||
|
Tokenizers["markdown"] = new Regex(
|
||||||
|
@"(?<header>^#{1,6}[^\n]*)" +
|
||||||
|
@"|(?<bold>\*\*[^*\n]+\*\*|__[^_\n]+__)" +
|
||||||
|
@"|(?<italic>\*[^*\n]+\*|_[^_\n]+_)" +
|
||||||
|
@"|(?<code>`[^`\n]+`)" +
|
||||||
|
@"|(?<link>\[[^\]]+\]\([^)]+\))",
|
||||||
|
opts | RegexOptions.Multiline);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Entry point. Walks every regex match in the code, emits plain spans for the gaps and
|
||||||
|
/// styled spans for the matches. If the language is unknown (or not specified), returns a
|
||||||
|
/// single default-colored span — code still renders in the monospace font, just no colors.
|
||||||
|
/// </summary>
|
||||||
|
public static List<Span> Highlight(string code, string? language, double fontSize)
|
||||||
|
{
|
||||||
|
var lang = Resolve(language);
|
||||||
|
var spans = new List<Span>();
|
||||||
|
|
||||||
|
if (lang is null || !Tokenizers.TryGetValue(lang, out var tokenizer))
|
||||||
|
{
|
||||||
|
spans.Add(MakeSpan(code, DefaultColor, fontSize));
|
||||||
|
return spans;
|
||||||
|
}
|
||||||
|
|
||||||
|
var keywords = Keywords.GetValueOrDefault(lang);
|
||||||
|
int cursor = 0;
|
||||||
|
|
||||||
|
foreach (Match m in tokenizer.Matches(code))
|
||||||
|
{
|
||||||
|
if (m.Index > cursor)
|
||||||
|
spans.Add(MakeSpan(code[cursor..m.Index], DefaultColor, fontSize));
|
||||||
|
|
||||||
|
spans.Add(SpanForMatch(m, lang, keywords, fontSize));
|
||||||
|
cursor = m.Index + m.Length;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cursor < code.Length)
|
||||||
|
spans.Add(MakeSpan(code[cursor..], DefaultColor, fontSize));
|
||||||
|
|
||||||
|
return spans;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Maps a regex Match to a colored Span by inspecting which named group succeeded. Words
|
||||||
|
/// fall through to a keyword-set lookup; in C#/JS/TS, uppercase-start words that aren't
|
||||||
|
/// keywords are treated as type names (a cheap heuristic that works surprisingly well).
|
||||||
|
/// </summary>
|
||||||
|
private static Span SpanForMatch(Match m, string lang, HashSet<string>? keywords, double fontSize)
|
||||||
|
{
|
||||||
|
if (m.Groups["comment"].Success)
|
||||||
|
return MakeSpan(m.Value, CommentColor, fontSize, italic: true);
|
||||||
|
|
||||||
|
if (m.Groups["string"].Success)
|
||||||
|
return MakeSpan(m.Value, StringColor, fontSize);
|
||||||
|
|
||||||
|
if (m.Groups["number"].Success)
|
||||||
|
return MakeSpan(m.Value, NumberColor, fontSize);
|
||||||
|
|
||||||
|
if (m.Groups["variable"].Success)
|
||||||
|
return MakeSpan(m.Value, AttrColor, fontSize);
|
||||||
|
|
||||||
|
if (m.Groups["tag"].Success)
|
||||||
|
return MakeSpan(m.Value, TagColor, fontSize);
|
||||||
|
|
||||||
|
if (m.Groups["attr"].Success)
|
||||||
|
return MakeSpan(m.Value, AttrColor, fontSize);
|
||||||
|
|
||||||
|
if (m.Groups["selector"].Success)
|
||||||
|
return MakeSpan(m.Value, TypeColor, fontSize);
|
||||||
|
|
||||||
|
if (m.Groups["prop"].Success)
|
||||||
|
return MakeSpan(m.Value, AttrColor, fontSize);
|
||||||
|
|
||||||
|
if (m.Groups["key"].Success)
|
||||||
|
return MakeSpan(m.Value, AttrColor, fontSize);
|
||||||
|
|
||||||
|
if (m.Groups["add"].Success)
|
||||||
|
return MakeSpan(m.Value, Color.FromArgb("#6A9955"), fontSize);
|
||||||
|
|
||||||
|
if (m.Groups["del"].Success)
|
||||||
|
return MakeSpan(m.Value, Color.FromArgb("#F48771"), fontSize);
|
||||||
|
|
||||||
|
if (m.Groups["hunk"].Success)
|
||||||
|
return MakeSpan(m.Value, KeywordColor, fontSize);
|
||||||
|
|
||||||
|
if (m.Groups["header"].Success)
|
||||||
|
return MakeSpan(m.Value, KeywordColor, fontSize, bold: true);
|
||||||
|
|
||||||
|
if (m.Groups["bold"].Success)
|
||||||
|
return MakeSpan(m.Value, DefaultColor, fontSize, bold: true);
|
||||||
|
|
||||||
|
if (m.Groups["italic"].Success)
|
||||||
|
return MakeSpan(m.Value, DefaultColor, fontSize, italic: true);
|
||||||
|
|
||||||
|
if (m.Groups["code"].Success)
|
||||||
|
return MakeSpan(m.Value, StringColor, fontSize);
|
||||||
|
|
||||||
|
if (m.Groups["link"].Success)
|
||||||
|
return MakeSpan(m.Value, AttrColor, fontSize);
|
||||||
|
|
||||||
|
if (m.Groups["word"].Success)
|
||||||
|
{
|
||||||
|
var word = m.Value;
|
||||||
|
var compareSet = keywords;
|
||||||
|
|
||||||
|
if (compareSet is not null && compareSet.Contains(word))
|
||||||
|
return MakeSpan(word, KeywordColor, fontSize);
|
||||||
|
|
||||||
|
if (lang is "csharp" or "javascript" or "typescript" && word.Length > 0 && char.IsUpper(word[0]))
|
||||||
|
return MakeSpan(word, TypeColor, fontSize);
|
||||||
|
|
||||||
|
return MakeSpan(word, DefaultColor, fontSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
return MakeSpan(m.Value, DefaultColor, fontSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Helper: build a Span with the monospace code font and the given colour + bold/italic flags.</summary>
|
||||||
|
private static Span MakeSpan(string text, Color color, double fontSize, bool bold = false, bool italic = false)
|
||||||
|
{
|
||||||
|
var attrs = FontAttributes.None;
|
||||||
|
if (bold) attrs |= FontAttributes.Bold;
|
||||||
|
if (italic) attrs |= FontAttributes.Italic;
|
||||||
|
|
||||||
|
return new Span
|
||||||
|
{
|
||||||
|
Text = text,
|
||||||
|
TextColor = color,
|
||||||
|
FontSize = fontSize,
|
||||||
|
FontFamily = FontFamily,
|
||||||
|
FontAttributes = attrs
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Normalises a user-supplied language tag through the Aliases table. Returns null for empty/whitespace input.</summary>
|
||||||
|
private static string? Resolve(string? language)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(language)) return null;
|
||||||
|
var lower = language.Trim().ToLowerInvariant();
|
||||||
|
return Aliases.GetValueOrDefault(lower, lower);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,36 +1,99 @@
|
|||||||
<?xml version="1.0" encoding="utf-8" ?>
|
<?xml version="1.0" encoding="utf-8" ?>
|
||||||
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
|
<ContentPage
|
||||||
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
|
x:Class="RelayClient.MainPage"
|
||||||
x:Class="RelayClient.MainPage">
|
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
|
||||||
|
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
|
||||||
|
Title="Relay Client">
|
||||||
|
|
||||||
<ScrollView>
|
<Grid RowDefinitions="Auto,*,Auto"
|
||||||
<VerticalStackLayout
|
ColumnDefinitions="220,*"
|
||||||
Padding="30,0"
|
Padding="12"
|
||||||
Spacing="25">
|
RowSpacing="10"
|
||||||
<Image
|
ColumnSpacing="10">
|
||||||
Source="dotnet_bot.png"
|
|
||||||
HeightRequest="185"
|
|
||||||
Aspect="AspectFit"
|
|
||||||
SemanticProperties.Description="dot net bot in a submarine number ten" />
|
|
||||||
|
|
||||||
<Label
|
<!-- Header -->
|
||||||
Text="Hello, World!"
|
<Border Grid.Row="0" Grid.ColumnSpan="2" StrokeThickness="1" Padding="10">
|
||||||
Style="{StaticResource Headline}"
|
<VerticalStackLayout Spacing="2">
|
||||||
SemanticProperties.HeadingLevel="Level1" />
|
<Label x:Name="UserLabel" Text="Logged in as: Unknown"
|
||||||
|
FontAttributes="Bold" FontSize="18" />
|
||||||
|
<Label x:Name="ChannelLabel" Text="No channel selected" FontSize="14" />
|
||||||
|
<Label x:Name="TypingLabel" Text="" FontSize="11"
|
||||||
|
FontAttributes="Italic" TextColor="Gray" IsVisible="False" />
|
||||||
|
</VerticalStackLayout>
|
||||||
|
</Border>
|
||||||
|
|
||||||
<Label
|
<!-- Sidebar: channel list -->
|
||||||
Text="Welcome to .NET Multi-platform App UI"
|
<Border Grid.Row="1" Grid.Column="0" StrokeThickness="1" Padding="10">
|
||||||
Style="{StaticResource SubHeadline}"
|
<ScrollView>
|
||||||
SemanticProperties.HeadingLevel="Level2"
|
<VerticalStackLayout Spacing="8">
|
||||||
SemanticProperties.Description="Welcome to dot net Multi platform App U I" />
|
<Grid ColumnDefinitions="*,Auto">
|
||||||
|
<Label Grid.Column="0" Text="Channels"
|
||||||
|
FontAttributes="Bold" FontSize="16"
|
||||||
|
VerticalOptions="Center" />
|
||||||
|
<Button Grid.Column="1" Text="+"
|
||||||
|
FontSize="16" Padding="6,2"
|
||||||
|
HeightRequest="30" WidthRequest="30"
|
||||||
|
Clicked="AddChannel_OnClicked" />
|
||||||
|
</Grid>
|
||||||
|
<VerticalStackLayout x:Name="SidebarList" Spacing="4" />
|
||||||
|
</VerticalStackLayout>
|
||||||
|
</ScrollView>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<!-- Messages view (text channels) -->
|
||||||
|
<Border x:Name="MessagesView" Grid.Row="1" Grid.Column="1" StrokeThickness="1" Padding="10">
|
||||||
|
<ScrollView x:Name="MessagesScrollView">
|
||||||
|
<VerticalStackLayout x:Name="MessagesLayout" Spacing="8" />
|
||||||
|
</ScrollView>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<!-- RTC view (voice channels) -->
|
||||||
|
<Border x:Name="RtcView" Grid.Row="1" Grid.Column="1"
|
||||||
|
StrokeThickness="1" Padding="10" IsVisible="False">
|
||||||
|
<Grid RowDefinitions="Auto,*">
|
||||||
|
<HybridWebView x:Name="hybridWebView"
|
||||||
|
RawMessageReceived="OnHybridWebViewRawMessageReceived"
|
||||||
|
Grid.Row="1" />
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<!-- Input area -->
|
||||||
|
<VerticalStackLayout x:Name="InputArea" Grid.Row="2" Grid.Column="1" Spacing="4">
|
||||||
|
|
||||||
|
<!-- Context bar (reply / edit mode) -->
|
||||||
|
<Border x:Name="ContextBar" IsVisible="False" StrokeThickness="1" Padding="8,4">
|
||||||
|
<Grid ColumnDefinitions="*,Auto" ColumnSpacing="8">
|
||||||
|
<Label x:Name="ContextBarLabel" Grid.Column="0"
|
||||||
|
VerticalOptions="Center" FontSize="12"
|
||||||
|
LineBreakMode="TailTruncation" />
|
||||||
|
<Button Grid.Column="1" Text="✕" FontSize="11"
|
||||||
|
Padding="6,2" HeightRequest="30"
|
||||||
|
Clicked="CancelContext_OnClicked" />
|
||||||
|
</Grid>
|
||||||
|
</Border>
|
||||||
|
|
||||||
|
<!-- Entry row: attach button + editor + send -->
|
||||||
|
<Grid ColumnDefinitions="Auto,*,Auto" ColumnSpacing="6">
|
||||||
|
<Button Grid.Column="0" Text="📎"
|
||||||
|
FontSize="16" Padding="6,2"
|
||||||
|
HeightRequest="40" WidthRequest="40"
|
||||||
|
Clicked="AttachFile_OnClicked"
|
||||||
|
ToolTipProperties.Text="Attach a file or image" />
|
||||||
|
<Editor x:Name="MessageEntry"
|
||||||
|
Grid.Column="1"
|
||||||
|
Placeholder="Type a message… (Shift+Enter for newline)"
|
||||||
|
AutoSize="TextChanges"
|
||||||
|
MaximumHeightRequest="120"
|
||||||
|
TextChanged="MessageEntry_OnTextChanged" />
|
||||||
|
<Button x:Name="SendButton" Grid.Column="2"
|
||||||
|
Text="Send" VerticalOptions="End"
|
||||||
|
Clicked="SendButton_OnClicked" />
|
||||||
|
</Grid>
|
||||||
|
|
||||||
<Button
|
|
||||||
x:Name="CounterBtn"
|
|
||||||
Text="Click me"
|
|
||||||
SemanticProperties.Hint="Counts the number of times you click"
|
|
||||||
Clicked="OnCounterClicked"
|
|
||||||
HorizontalOptions="Fill" />
|
|
||||||
</VerticalStackLayout>
|
</VerticalStackLayout>
|
||||||
</ScrollView>
|
|
||||||
|
|
||||||
|
<!-- Bottom-left: kept empty (swap button removed) -->
|
||||||
|
<ContentView Grid.Row="2" Grid.Column="0" />
|
||||||
|
|
||||||
|
</Grid>
|
||||||
</ContentPage>
|
</ContentPage>
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
|||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Maui.Hosting;
|
using WebSocketSharp;
|
||||||
|
|
||||||
namespace RelayClient;
|
namespace RelayClient;
|
||||||
|
|
||||||
@@ -8,16 +8,17 @@ public static class MauiProgram
|
|||||||
public static MauiApp CreateMauiApp()
|
public static MauiApp CreateMauiApp()
|
||||||
{
|
{
|
||||||
var builder = MauiApp.CreateBuilder();
|
var builder = MauiApp.CreateBuilder();
|
||||||
builder
|
builder.UseMauiApp<App>().ConfigureFonts(fonts =>
|
||||||
.UseMauiApp<App>()
|
|
||||||
.ConfigureFonts(fonts =>
|
|
||||||
{
|
{
|
||||||
fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
|
fonts.AddFont("AnonymousPro-Bold.ttf", "AnonymousProBold");
|
||||||
fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
|
fonts.AddFont("AnonymousPro-BoldItalic.ttf", "AnonymousProBoldItalic");
|
||||||
|
fonts.AddFont("AnonymousPro-Italic.ttf", "AnonymousProItalic");
|
||||||
|
fonts.AddFont("AnonymousPro-Regular.ttf", "AnonymousProRegular");
|
||||||
});
|
});
|
||||||
|
|
||||||
#if DEBUG
|
#if DEBUG
|
||||||
builder.Logging.AddDebug();
|
builder.Services.AddHybridWebViewDeveloperTools();
|
||||||
|
builder.Logging.AddDebug();
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
return builder.Build();
|
return builder.Build();
|
||||||
|
|||||||
@@ -36,11 +36,26 @@
|
|||||||
<MauiImage Update="Resources\Images\dotnet_bot.png" Resize="True" BaseSize="300,185" />
|
<MauiImage Update="Resources\Images\dotnet_bot.png" Resize="True" BaseSize="300,185" />
|
||||||
<MauiFont Include="Resources\Fonts\*" />
|
<MauiFont Include="Resources\Fonts\*" />
|
||||||
<MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
|
<MauiAsset Include="Resources\Raw\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)" />
|
||||||
|
<None Remove="Resources\Raw\test.html" />
|
||||||
|
<MauiAsset Include="Resources\Raw\test.html">
|
||||||
|
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||||
|
</MauiAsset>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="11.0.0-preview.2.26159.112" />
|
||||||
<PackageReference Include="Microsoft.Maui.Controls" Version="$(MauiVersion)" />
|
<PackageReference Include="Microsoft.Maui.Controls" Version="$(MauiVersion)" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="10.0.0" />
|
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="10.0.0" />
|
||||||
|
<PackageReference Include="SurrealDb.Net" Version="0.9.0" />
|
||||||
|
<PackageReference Include="WebSocketSharp" Version="1.0.3-rc11" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\RelayShared\RelayShared.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Folder Include="Models\" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,4 +1 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
<svg id="New_Version" data-name="New Version" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 759.23 759.23"><defs><style>.cls-1{fill:#2e3338;}</style></defs><path id="Background" class="cls-1" d="M177.77,0H581.46A177.77,177.77,0,0,1,759.23,177.77V581.46A177.77,177.77,0,0,1,581.46,759.23H177.77A177.77,177.77,0,0,1,0,581.46V177.77A177.77,177.77,0,0,1,177.77,0Z"/></svg>
|
||||||
<svg width="456" height="456" viewBox="0 0 456 456" version="1.1" xmlns="http://www.w3.org/2000/svg">
|
|
||||||
<rect x="0" y="0" width="456" height="456" fill="#512BD4" />
|
|
||||||
</svg>
|
|
||||||
|
Before Width: | Height: | Size: 228 B After Width: | Height: | Size: 370 B |
File diff suppressed because one or more lines are too long
|
Before Width: | Height: | Size: 1.8 KiB After Width: | Height: | Size: 5.7 KiB |
4
RelayClient/Resources/AppIcon/old_appicon.svg
Normal file
4
RelayClient/Resources/AppIcon/old_appicon.svg
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
|
<svg width="456" height="456" viewBox="0 0 456 456" version="1.1" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<rect x="0" y="0" width="456" height="456" fill="#512BD4" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 228 B |
8
RelayClient/Resources/AppIcon/old_appiconfg.svg
Normal file
8
RelayClient/Resources/AppIcon/old_appiconfg.svg
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
|
||||||
|
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||||
|
<svg width="456" height="456" viewBox="0 0 456 456" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
|
||||||
|
<path d="m 105.50037,281.60863 c -2.70293,0 -5.00091,-0.90042 -6.893127,-2.70209 -1.892214,-1.84778 -2.837901,-4.04181 -2.837901,-6.58209 0,-2.58722 0.945687,-4.80389 2.837901,-6.65167 1.892217,-1.84778 4.190197,-2.77167 6.893127,-2.77167 2.74819,0 5.06798,0.92389 6.96019,2.77167 1.93749,1.84778 2.90581,4.06445 2.90581,6.65167 0,2.54028 -0.96832,4.73431 -2.90581,6.58209 -1.89221,1.80167 -4.212,2.70209 -6.96019,2.70209 z" style="fill:#ffffff;fill-rule:nonzero;stroke-width:0.838376" />
|
||||||
|
<path d="M 213.56111,280.08446 H 195.99044 L 149.69953,207.0544 c -1.17121,-1.84778 -2.14037,-3.76515 -2.90581,-5.75126 h -0.40578 c 0.36051,2.12528 0.54076,6.67515 0.54076,13.6496 v 65.13172 h -15.54349 v -99.36009 h 18.71925 l 44.7374,71.29798 c 1.89222,2.95695 3.1087,4.98917 3.64945,6.09751 h 0.26996 c -0.45021,-2.6325 -0.67573,-7.09015 -0.67573,-13.37293 v -64.02256 h 15.47557 z" style="fill:#ffffff;fill-rule:nonzero;stroke-width:0.838376" />
|
||||||
|
<path d="m 289.25134,280.08446 h -54.40052 v -99.36009 h 52.23835 v 13.99669 h -36.15411 v 28.13085 h 33.31621 v 13.9271 h -33.31621 v 29.37835 h 38.31628 z" style="fill:#ffffff;fill-rule:nonzero;stroke-width:0.838376" />
|
||||||
|
<path d="M 366.56466,194.72106 H 338.7222 v 85.3634 h -16.08423 v -85.3634 h -27.77455 v -13.99669 h 71.70124 z" style="fill:#ffffff;fill-rule:nonzero;stroke-width:0.838376" />
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.8 KiB |
BIN
RelayClient/Resources/Fonts/AnonymousPro-Bold.ttf
Normal file
BIN
RelayClient/Resources/Fonts/AnonymousPro-Bold.ttf
Normal file
Binary file not shown.
BIN
RelayClient/Resources/Fonts/AnonymousPro-BoldItalic.ttf
Normal file
BIN
RelayClient/Resources/Fonts/AnonymousPro-BoldItalic.ttf
Normal file
Binary file not shown.
BIN
RelayClient/Resources/Fonts/AnonymousPro-Italic.ttf
Normal file
BIN
RelayClient/Resources/Fonts/AnonymousPro-Italic.ttf
Normal file
Binary file not shown.
BIN
RelayClient/Resources/Fonts/AnonymousPro-Regular.ttf
Normal file
BIN
RelayClient/Resources/Fonts/AnonymousPro-Regular.ttf
Normal file
Binary file not shown.
24
RelayClient/Resources/Raw/test.css
Normal file
24
RelayClient/Resources/Raw/test.css
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
@import url('https://fonts.googleapis.com/css2?family=Anonymous+Pro');
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: 'Anonymous Pro', monospace;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
text-align: center;
|
||||||
|
color: #2c3e50;
|
||||||
|
margin: 80px 10px;
|
||||||
|
background-color: #666666;
|
||||||
|
}
|
||||||
|
|
||||||
|
video {
|
||||||
|
width: 40vw;
|
||||||
|
height: 30vw;
|
||||||
|
margin: 2rem;
|
||||||
|
background: #2c3e50;
|
||||||
|
}
|
||||||
|
|
||||||
|
.videos {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
41
RelayClient/Resources/Raw/test.html
Normal file
41
RelayClient/Resources/Raw/test.html
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="favicon.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>WebRTC Demo</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h2>1. Start your Webcam</h2>
|
||||||
|
<div class="videos">
|
||||||
|
<span>
|
||||||
|
<h3>Local Stream</h3>
|
||||||
|
<video id="webcamVideo" autoplay playsinline></video>
|
||||||
|
</span>
|
||||||
|
<span>
|
||||||
|
<h3>Remote Stream</h3>
|
||||||
|
<video id="remoteVideo" autoplay playsinline></video>
|
||||||
|
</span>
|
||||||
|
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button id="webcamButton">Start webcam</button>
|
||||||
|
<h2>2. Create a new Call</h2>
|
||||||
|
<button id="callButton" disabled>Create Call (offer)</button>
|
||||||
|
|
||||||
|
<h2>3. Join a Call</h2>
|
||||||
|
<p>Answer the call from a different browser window or device</p>
|
||||||
|
|
||||||
|
<input id="callInput" />
|
||||||
|
<button id="answerButton" disabled>Answer</button>
|
||||||
|
|
||||||
|
<h2>4. Hangup</h2>
|
||||||
|
|
||||||
|
<button id="hangupButton" disabled>Hangup</button>
|
||||||
|
|
||||||
|
<script type="module" src="test.js"></script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
146
RelayClient/Resources/Raw/test.js
Normal file
146
RelayClient/Resources/Raw/test.js
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
import './test.css';
|
||||||
|
|
||||||
|
import firebase from 'firebase/app';
|
||||||
|
import 'firebase/firestore';
|
||||||
|
|
||||||
|
const firebaseConfig = {
|
||||||
|
// your config
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!firebase.apps.length) {
|
||||||
|
firebase.initializeApp(firebaseConfig);
|
||||||
|
}
|
||||||
|
const firestore = firebase.firestore();
|
||||||
|
|
||||||
|
const servers = {
|
||||||
|
iceServers: [
|
||||||
|
{
|
||||||
|
urls: ['stun:stun1.l.google.com:19302', 'stun:stun2.l.google.com:19302'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
iceCandidatePoolSize: 10,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Global State
|
||||||
|
const pc = new RTCPeerConnection(servers);
|
||||||
|
let localStream = null;
|
||||||
|
let remoteStream = null;
|
||||||
|
|
||||||
|
// HTML elements
|
||||||
|
const webcamButton = document.getElementById('webcamButton');
|
||||||
|
const webcamVideo = document.getElementById('webcamVideo');
|
||||||
|
const callButton = document.getElementById('callButton');
|
||||||
|
const callInput = document.getElementById('callInput');
|
||||||
|
const answerButton = document.getElementById('answerButton');
|
||||||
|
const remoteVideo = document.getElementById('remoteVideo');
|
||||||
|
const hangupButton = document.getElementById('hangupButton');
|
||||||
|
|
||||||
|
// 1. Setup media sources
|
||||||
|
|
||||||
|
webcamButton.onclick = async () => {
|
||||||
|
localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
|
||||||
|
remoteStream = new MediaStream();
|
||||||
|
|
||||||
|
// Push tracks from local stream to peer connection
|
||||||
|
localStream.getTracks().forEach((track) => {
|
||||||
|
pc.addTrack(track, localStream);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Pull tracks from remote stream, add to video stream
|
||||||
|
pc.ontrack = (event) => {
|
||||||
|
event.streams[0].getTracks().forEach((track) => {
|
||||||
|
remoteStream.addTrack(track);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
webcamVideo.srcObject = localStream;
|
||||||
|
remoteVideo.srcObject = remoteStream;
|
||||||
|
|
||||||
|
callButton.disabled = false;
|
||||||
|
answerButton.disabled = false;
|
||||||
|
webcamButton.disabled = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 2. Create an offer
|
||||||
|
callButton.onclick = async () => {
|
||||||
|
// Reference Firestore collections for signaling
|
||||||
|
const callDoc = firestore.collection('calls').doc();
|
||||||
|
const offerCandidates = callDoc.collection('offerCandidates');
|
||||||
|
const answerCandidates = callDoc.collection('answerCandidates');
|
||||||
|
|
||||||
|
callInput.value = callDoc.id;
|
||||||
|
|
||||||
|
// Get candidates for caller, save to db
|
||||||
|
pc.onicecandidate = (event) => {
|
||||||
|
event.candidate && offerCandidates.add(event.candidate.toJSON());
|
||||||
|
};
|
||||||
|
|
||||||
|
// Create offer
|
||||||
|
const offerDescription = await pc.createOffer();
|
||||||
|
await pc.setLocalDescription(offerDescription);
|
||||||
|
|
||||||
|
const offer = {
|
||||||
|
sdp: offerDescription.sdp,
|
||||||
|
type: offerDescription.type,
|
||||||
|
};
|
||||||
|
|
||||||
|
await callDoc.set({ offer });
|
||||||
|
|
||||||
|
// Listen for remote answer
|
||||||
|
callDoc.onSnapshot((snapshot) => {
|
||||||
|
const data = snapshot.data();
|
||||||
|
if (!pc.currentRemoteDescription && data?.answer) {
|
||||||
|
const answerDescription = new RTCSessionDescription(data.answer);
|
||||||
|
pc.setRemoteDescription(answerDescription);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// When answered, add candidate to peer connection
|
||||||
|
answerCandidates.onSnapshot((snapshot) => {
|
||||||
|
snapshot.docChanges().forEach((change) => {
|
||||||
|
if (change.type === 'added') {
|
||||||
|
const candidate = new RTCIceCandidate(change.doc.data());
|
||||||
|
pc.addIceCandidate(candidate);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
hangupButton.disabled = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 3. Answer the call with the unique ID
|
||||||
|
answerButton.onclick = async () => {
|
||||||
|
const callId = callInput.value;
|
||||||
|
const callDoc = firestore.collection('calls').doc(callId);
|
||||||
|
const answerCandidates = callDoc.collection('answerCandidates');
|
||||||
|
const offerCandidates = callDoc.collection('offerCandidates');
|
||||||
|
|
||||||
|
pc.onicecandidate = (event) => {
|
||||||
|
event.candidate && answerCandidates.add(event.candidate.toJSON());
|
||||||
|
};
|
||||||
|
|
||||||
|
const callData = (await callDoc.get()).data();
|
||||||
|
|
||||||
|
const offerDescription = callData.offer;
|
||||||
|
await pc.setRemoteDescription(new RTCSessionDescription(offerDescription));
|
||||||
|
|
||||||
|
const answerDescription = await pc.createAnswer();
|
||||||
|
await pc.setLocalDescription(answerDescription);
|
||||||
|
|
||||||
|
const answer = {
|
||||||
|
type: answerDescription.type,
|
||||||
|
sdp: answerDescription.sdp,
|
||||||
|
};
|
||||||
|
|
||||||
|
await callDoc.update({ answer });
|
||||||
|
|
||||||
|
offerCandidates.onSnapshot((snapshot) => {
|
||||||
|
snapshot.docChanges().forEach((change) => {
|
||||||
|
console.log(change);
|
||||||
|
if (change.type === 'added') {
|
||||||
|
let data = change.doc.data();
|
||||||
|
pc.addIceCandidate(new RTCIceCandidate(data));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
114
RelayClient/Resources/Raw/wwwroot/index.css
Normal file
114
RelayClient/Resources/Raw/wwwroot/index.css
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 16px;
|
||||||
|
background-color: #121212;
|
||||||
|
color: #FFFFFF;
|
||||||
|
font-family: "Segoe UI", Arial, sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
h3 {
|
||||||
|
margin: 0 0 10px 0;
|
||||||
|
color: #FFA9D1F4;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
background-color: #332940;
|
||||||
|
color: #FFFFFF;
|
||||||
|
border: none;
|
||||||
|
padding: 8px 12px;
|
||||||
|
margin-right: 6px;
|
||||||
|
border-radius: 6px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.2s ease, transform 0.05s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover {
|
||||||
|
background-color: #40324f;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:active {
|
||||||
|
transform: scale(0.97);
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
background-color: #332940;
|
||||||
|
color: #FFFFFF;
|
||||||
|
border: none;
|
||||||
|
padding: 6px;
|
||||||
|
border-radius: 6px;
|
||||||
|
margin-left: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
video {
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid #332940;
|
||||||
|
background-color: #1F1A24;
|
||||||
|
}
|
||||||
|
|
||||||
|
#localVideoStatus,
|
||||||
|
#remoteVideoStatus,
|
||||||
|
#localMediaStatus,
|
||||||
|
#remoteMediaStatus {
|
||||||
|
font-size: 12px;
|
||||||
|
margin-top: 4px;
|
||||||
|
color: #FFA9D1F4;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea {
|
||||||
|
background-color: #1F1A24;
|
||||||
|
color: #FFFFFF;
|
||||||
|
border: 1px solid #332940;
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 8px;
|
||||||
|
font-family: monospace;
|
||||||
|
resize: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
div {
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea::-webkit-scrollbar {
|
||||||
|
width: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea::-webkit-scrollbar-thumb {
|
||||||
|
background: #332940;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel {
|
||||||
|
background: #1F1A24;
|
||||||
|
border: 1px solid #332940;
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote-media-container {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
|
gap: 16px;
|
||||||
|
align-items: flex-start;
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
overflow-x: auto;
|
||||||
|
padding: 8px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote-media-tile,
|
||||||
|
.remote-tile {
|
||||||
|
flex: 0 0 auto;
|
||||||
|
width: 320px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote-media-tile video,
|
||||||
|
.remote-tile video {
|
||||||
|
width: 320px;
|
||||||
|
height: 240px;
|
||||||
|
background: #111;
|
||||||
|
border-radius: 8px;
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
48
RelayClient/Resources/Raw/wwwroot/index.html
Normal file
48
RelayClient/Resources/Raw/wwwroot/index.html
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
|
||||||
|
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<title></title>
|
||||||
|
<link rel="icon" href="data:,">
|
||||||
|
<link rel="stylesheet" href="styles/app.css">
|
||||||
|
<link rel="stylesheet" href="index.css">
|
||||||
|
<script src="_framework/hybridwebview.js"></script>
|
||||||
|
<script src="media.js"></script>
|
||||||
|
<script src="relaySocket.js"></script>
|
||||||
|
<script src="rtc.js"></script>
|
||||||
|
<script src="index.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div>
|
||||||
|
<h3>Relay RTC Test</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<button onclick="Media.refreshDevicesAndPreview()">Refresh Devices</button>
|
||||||
|
<button onclick="RelayRtc.joinChannelCall()">Join Call</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top: 8px;">
|
||||||
|
<label for="cameraSelect">Camera:</label>
|
||||||
|
<select id="cameraSelect"></select>
|
||||||
|
|
||||||
|
<label for="micSelect" style="margin-left: 12px;">Microphone:</label>
|
||||||
|
<select id="micSelect"></select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top: 10px;">
|
||||||
|
<div style="display: inline-block; margin-right: 20px; vertical-align: top;">
|
||||||
|
<video id="localVideo" autoplay playsinline muted style="width: 320px; height: 240px; background: #111;"></video>
|
||||||
|
<div id="localVideoStatus">Local video: waiting...</div>
|
||||||
|
<div id="localMediaStatus">Waiting for local media...</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="remoteMediaContainer" class="remote-media-container"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top: 10px;">
|
||||||
|
<textarea readonly id="messageLog" style="width: 90%; height: 12em;"></textarea>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
73
RelayClient/Resources/Raw/wwwroot/index.js
Normal file
73
RelayClient/Resources/Raw/wwwroot/index.js
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
let currentUsername = null;
|
||||||
|
let currentChannelId = null;
|
||||||
|
|
||||||
|
const configuration = {
|
||||||
|
iceServers: [
|
||||||
|
{
|
||||||
|
urls: [
|
||||||
|
"stun:stun1.l.google.com:19302",
|
||||||
|
"stun:stun2.l.google.com:19302"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
iceCandidatePoolSize: 10
|
||||||
|
};
|
||||||
|
|
||||||
|
window.setUsername = function (name) {
|
||||||
|
currentUsername = name;
|
||||||
|
LogMessage("Username set to: " + currentUsername);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.setChannelId = function (channelId) {
|
||||||
|
currentChannelId = channelId;
|
||||||
|
LogMessage("Channel set to: " + currentChannelId);
|
||||||
|
};
|
||||||
|
|
||||||
|
function LogMessage(msg) {
|
||||||
|
const messageLog = document.getElementById("messageLog");
|
||||||
|
|
||||||
|
if (!messageLog) {
|
||||||
|
console.log(msg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
messageLog.value += "\r\n" + msg;
|
||||||
|
messageLog.scrollTop = messageLog.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.LogMessage = LogMessage;
|
||||||
|
|
||||||
|
window.addEventListener("HybridWebViewMessageReceived", function (e) {
|
||||||
|
LogMessage("Raw message: " + e.detail.message);
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener("load", async () => {
|
||||||
|
LogMessage("RTC page loaded");
|
||||||
|
|
||||||
|
window.HybridWebView.SendRawMessage("rtc_page_ready");
|
||||||
|
|
||||||
|
Media.wireDeviceSelectors();
|
||||||
|
await Media.loadDevices();
|
||||||
|
await Media.ensureLocalMedia();
|
||||||
|
});
|
||||||
|
|
||||||
|
function testIndex(rawJson)
|
||||||
|
{
|
||||||
|
const data = typeof rawJson === "string" ? JSON.parse(rawJson) : rawJson;
|
||||||
|
if (data.sdp) {
|
||||||
|
data.sdp = data.sdp.replaceAll("(rn)", "\r\n");
|
||||||
|
}
|
||||||
|
handleRtcSignal(JSON.stringify(data));
|
||||||
|
// if (data.type === "rtc_offer") {
|
||||||
|
// handleOffer(data)
|
||||||
|
// }
|
||||||
|
// if (data.type === "rtc_answer") {
|
||||||
|
// data.sdp = data.sdp.replaceAll("(rn)", "\r\n");
|
||||||
|
// handleAnswer(data)
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
|
||||||
|
function noDataTest()
|
||||||
|
{
|
||||||
|
LogMessage("No Data Called!!");
|
||||||
|
}
|
||||||
261
RelayClient/Resources/Raw/wwwroot/media.js
Normal file
261
RelayClient/Resources/Raw/wwwroot/media.js
Normal file
@@ -0,0 +1,261 @@
|
|||||||
|
let localStream = null;
|
||||||
|
const remoteStreams = {};
|
||||||
|
|
||||||
|
const Media = {
|
||||||
|
async loadDevices() {
|
||||||
|
const devices = await navigator.mediaDevices.enumerateDevices();
|
||||||
|
|
||||||
|
const cameras = devices.filter(d => d.kind === "videoinput");
|
||||||
|
const mics = devices.filter(d => d.kind === "audioinput");
|
||||||
|
|
||||||
|
const cameraSelect = document.getElementById("cameraSelect");
|
||||||
|
const micSelect = document.getElementById("micSelect");
|
||||||
|
|
||||||
|
if (!cameraSelect || !micSelect) return;
|
||||||
|
|
||||||
|
const selectedCamera = cameraSelect.value;
|
||||||
|
const selectedMic = micSelect.value;
|
||||||
|
|
||||||
|
cameraSelect.innerHTML = "";
|
||||||
|
micSelect.innerHTML = "";
|
||||||
|
|
||||||
|
const noCamera = document.createElement("option");
|
||||||
|
noCamera.value = "";
|
||||||
|
noCamera.textContent = "No camera / audio only";
|
||||||
|
cameraSelect.appendChild(noCamera);
|
||||||
|
|
||||||
|
const defaultMic = document.createElement("option");
|
||||||
|
defaultMic.value = "";
|
||||||
|
defaultMic.textContent = "Default microphone";
|
||||||
|
micSelect.appendChild(defaultMic);
|
||||||
|
|
||||||
|
for (const camera of cameras) {
|
||||||
|
const option = document.createElement("option");
|
||||||
|
option.value = camera.deviceId;
|
||||||
|
option.textContent = camera.label || `Camera ${cameraSelect.length}`;
|
||||||
|
cameraSelect.appendChild(option);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const mic of mics) {
|
||||||
|
const option = document.createElement("option");
|
||||||
|
option.value = mic.deviceId;
|
||||||
|
option.textContent = mic.label || `Microphone ${micSelect.length}`;
|
||||||
|
micSelect.appendChild(option);
|
||||||
|
}
|
||||||
|
|
||||||
|
cameraSelect.value = [...cameraSelect.options].some(o => o.value === selectedCamera)
|
||||||
|
? selectedCamera
|
||||||
|
: "";
|
||||||
|
|
||||||
|
micSelect.value = [...micSelect.options].some(o => o.value === selectedMic)
|
||||||
|
? selectedMic
|
||||||
|
: "";
|
||||||
|
|
||||||
|
LogMessage(`Loaded devices: ${cameras.length} cameras, ${mics.length} mics`);
|
||||||
|
},
|
||||||
|
|
||||||
|
async ensureLocalMedia() {
|
||||||
|
const cameraSelect = document.getElementById("cameraSelect");
|
||||||
|
const micSelect = document.getElementById("micSelect");
|
||||||
|
|
||||||
|
if (localStream) {
|
||||||
|
return localStream;
|
||||||
|
}
|
||||||
|
|
||||||
|
const audioDeviceId = micSelect?.value || "";
|
||||||
|
const videoDeviceId = cameraSelect?.value || "";
|
||||||
|
|
||||||
|
const constraints = {
|
||||||
|
audio: audioDeviceId
|
||||||
|
? { deviceId: { exact: audioDeviceId } }
|
||||||
|
: true,
|
||||||
|
video: videoDeviceId
|
||||||
|
? { deviceId: { exact: videoDeviceId } }
|
||||||
|
: false
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
localStream = await navigator.mediaDevices.getUserMedia(constraints);
|
||||||
|
} catch (err) {
|
||||||
|
LogMessage("Selected media failed: " + err);
|
||||||
|
|
||||||
|
localStream = await navigator.mediaDevices.getUserMedia({
|
||||||
|
audio: audioDeviceId
|
||||||
|
? { deviceId: { exact: audioDeviceId } }
|
||||||
|
: true,
|
||||||
|
video: false
|
||||||
|
});
|
||||||
|
|
||||||
|
LogMessage("No camera available, continuing without video");
|
||||||
|
}
|
||||||
|
|
||||||
|
this.attachLocalStream(localStream);
|
||||||
|
LogMessage("Local media initialized");
|
||||||
|
|
||||||
|
return localStream;
|
||||||
|
},
|
||||||
|
|
||||||
|
attachLocalStream(stream) {
|
||||||
|
const localVideo = document.getElementById("localVideo");
|
||||||
|
const localMediaStatus = document.getElementById("localMediaStatus");
|
||||||
|
const localVideoStatus = document.getElementById("localVideoStatus");
|
||||||
|
|
||||||
|
const audioTracks = stream.getAudioTracks();
|
||||||
|
const videoTracks = stream.getVideoTracks();
|
||||||
|
|
||||||
|
if (localVideo) {
|
||||||
|
localVideo.srcObject = videoTracks.length > 0 ? stream : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (localMediaStatus) {
|
||||||
|
localMediaStatus.textContent =
|
||||||
|
audioTracks.length > 0
|
||||||
|
? "Microphone active"
|
||||||
|
: "No microphone";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (localVideoStatus) {
|
||||||
|
localVideoStatus.textContent =
|
||||||
|
videoTracks.length > 0
|
||||||
|
? "Local video active"
|
||||||
|
: "Local video unavailable";
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async restartLocalMedia() {
|
||||||
|
if (localStream) {
|
||||||
|
localStream.getTracks().forEach(track => track.stop());
|
||||||
|
localStream = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.ensureLocalMedia();
|
||||||
|
|
||||||
|
if (window.RelayRtc?.applyLocalStreamToAllPeerConnections) {
|
||||||
|
await window.RelayRtc.applyLocalStreamToAllPeerConnections();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async refreshDevicesAndPreview() {
|
||||||
|
if (localStream) {
|
||||||
|
localStream.getTracks().forEach(track => track.stop());
|
||||||
|
localStream = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.loadDevices();
|
||||||
|
await this.ensureLocalMedia();
|
||||||
|
|
||||||
|
if (window.RelayRtc?.applyLocalStreamToAllPeerConnections) {
|
||||||
|
await window.RelayRtc.applyLocalStreamToAllPeerConnections();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async applyLocalStreamToPeerConnection(pc, username) {
|
||||||
|
const stream = await this.ensureLocalMedia();
|
||||||
|
const existingSenders = pc.getSenders();
|
||||||
|
|
||||||
|
for (const track of stream.getTracks()) {
|
||||||
|
const existingSender = existingSenders.find(sender =>
|
||||||
|
sender.track && sender.track.kind === track.kind
|
||||||
|
);
|
||||||
|
|
||||||
|
if (existingSender) {
|
||||||
|
await existingSender.replaceTrack(track);
|
||||||
|
LogMessage(`Replaced local ${track.kind} track for ${username}`);
|
||||||
|
} else {
|
||||||
|
pc.addTrack(track, stream);
|
||||||
|
LogMessage(`Added local ${track.kind} track for ${username}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async applyLocalStreamToAllPeerConnections() {
|
||||||
|
if (!window.RelayRtc?.peerConnections) return;
|
||||||
|
|
||||||
|
for (const [username, pc] of Object.entries(window.RelayRtc.peerConnections)) {
|
||||||
|
await this.applyLocalStreamToPeerConnection(pc, username);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
attachRemoteStream(username, stream) {
|
||||||
|
remoteStreams[username] = stream;
|
||||||
|
|
||||||
|
const tile = this.ensureRemoteTile(username);
|
||||||
|
const video = tile.querySelector("video");
|
||||||
|
const status = tile.querySelector(".remote-media-status");
|
||||||
|
|
||||||
|
if (video) {
|
||||||
|
video.srcObject = stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
const audioTracks = stream.getAudioTracks();
|
||||||
|
const videoTracks = stream.getVideoTracks();
|
||||||
|
|
||||||
|
if (status) {
|
||||||
|
status.textContent =
|
||||||
|
`${audioTracks.length > 0 ? "Audio" : "No audio"} / ` +
|
||||||
|
`${videoTracks.length > 0 ? "Video" : "No video"}`;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
ensureRemoteTile(username) {
|
||||||
|
const container = document.getElementById("remoteMediaContainer");
|
||||||
|
if (!container) return null;
|
||||||
|
|
||||||
|
let tile = document.getElementById(`remote-tile-${username}`);
|
||||||
|
if (tile) return tile;
|
||||||
|
|
||||||
|
tile = document.createElement("div");
|
||||||
|
tile.id = `remote-tile-${username}`;
|
||||||
|
tile.className = "remote-media-tile";
|
||||||
|
|
||||||
|
const title = document.createElement("div");
|
||||||
|
title.className = "remote-media-title";
|
||||||
|
title.textContent = username;
|
||||||
|
|
||||||
|
const video = document.createElement("video");
|
||||||
|
video.autoplay = true;
|
||||||
|
video.playsInline = true;
|
||||||
|
|
||||||
|
const status = document.createElement("div");
|
||||||
|
status.className = "remote-media-status";
|
||||||
|
status.textContent = "Remote media: waiting...";
|
||||||
|
|
||||||
|
tile.appendChild(title);
|
||||||
|
tile.appendChild(video);
|
||||||
|
tile.appendChild(status);
|
||||||
|
|
||||||
|
container.appendChild(tile);
|
||||||
|
|
||||||
|
return tile;
|
||||||
|
},
|
||||||
|
|
||||||
|
removeRemoteStream(username) {
|
||||||
|
delete remoteStreams[username];
|
||||||
|
|
||||||
|
const tile = document.getElementById(`remote-tile-${username}`);
|
||||||
|
if (tile) {
|
||||||
|
tile.remove();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
wireDeviceSelectors() {
|
||||||
|
const cameraSelect = document.getElementById("cameraSelect");
|
||||||
|
const micSelect = document.getElementById("micSelect");
|
||||||
|
|
||||||
|
if (cameraSelect) {
|
||||||
|
cameraSelect.addEventListener("change", async () => {
|
||||||
|
LogMessage("Camera changed");
|
||||||
|
await this.restartLocalMedia();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (micSelect) {
|
||||||
|
micSelect.addEventListener("change", async () => {
|
||||||
|
LogMessage("Microphone changed");
|
||||||
|
await this.restartLocalMedia();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
window.Media = Media;
|
||||||
46
RelayClient/Resources/Raw/wwwroot/relaySocket.js
Normal file
46
RelayClient/Resources/Raw/wwwroot/relaySocket.js
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
const RelaySocket = {
|
||||||
|
async joinRtcChannel() {
|
||||||
|
await window.HybridWebView.InvokeDotNet("JoinRtcChannel");
|
||||||
|
},
|
||||||
|
|
||||||
|
async leaveRtcChannel() {
|
||||||
|
await window.HybridWebView.InvokeDotNet("LeaveRtcChannel");
|
||||||
|
},
|
||||||
|
|
||||||
|
async getRtcParticipants() {
|
||||||
|
const raw = await window.HybridWebView.InvokeDotNet("GetRtcParticipants");
|
||||||
|
|
||||||
|
if (!raw) return [];
|
||||||
|
|
||||||
|
return typeof raw === "string"
|
||||||
|
? JSON.parse(raw)
|
||||||
|
: raw;
|
||||||
|
},
|
||||||
|
|
||||||
|
async sendRtcSignal(signal) {
|
||||||
|
if (!signal.channelId) signal.channelId = currentChannelId;
|
||||||
|
if (!signal.from) signal.from = currentUsername;
|
||||||
|
|
||||||
|
await window.HybridWebView.InvokeDotNet("SendRtcSignal", [
|
||||||
|
JSON.stringify(signal)
|
||||||
|
]);
|
||||||
|
},
|
||||||
|
|
||||||
|
receiveRtcSignal(rawJson) {
|
||||||
|
LogMessage("RelaySocket.receiveRtcSignal hit");
|
||||||
|
|
||||||
|
if (window.RelayRtc?.handleRtcSignal) {
|
||||||
|
LogMessage("Forwarding RTC signal to RelayRtc.handleRtcSignal");
|
||||||
|
return window.RelayRtc.handleRtcSignal(rawJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof window.handleRtcSignal === "function") {
|
||||||
|
LogMessage("Forwarding RTC signal to window.handleRtcSignal");
|
||||||
|
return window.handleRtcSignal(rawJson);
|
||||||
|
}
|
||||||
|
|
||||||
|
LogMessage("No RTC signal handler registered.");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
window.RelaySocket = RelaySocket;
|
||||||
235
RelayClient/Resources/Raw/wwwroot/rtc.js
Normal file
235
RelayClient/Resources/Raw/wwwroot/rtc.js
Normal file
@@ -0,0 +1,235 @@
|
|||||||
|
const peerConnections = {};
|
||||||
|
|
||||||
|
async function joinChannelCall() {
|
||||||
|
LogMessage("Current username: " + currentUsername);
|
||||||
|
LogMessage("Current channel: " + currentChannelId);
|
||||||
|
|
||||||
|
if (!currentUsername || !currentChannelId) {
|
||||||
|
LogMessage("Cannot join RTC: missing username or channel.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await RelaySocket.joinRtcChannel();
|
||||||
|
await Media.ensureLocalMedia();
|
||||||
|
|
||||||
|
const participants = await RelaySocket.getRtcParticipants();
|
||||||
|
|
||||||
|
LogMessage("Participants: " + JSON.stringify(participants));
|
||||||
|
|
||||||
|
const existingUsers = participants.filter(x => x !== currentUsername);
|
||||||
|
|
||||||
|
if (existingUsers.length === 0) {
|
||||||
|
LogMessage("Joined call as first participant. Waiting for others...");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const username of existingUsers) {
|
||||||
|
await sendOffer(username); //Creates an offer to each person in call for MESH RTC
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendOffer(username) {
|
||||||
|
const pc = await ensurePeerConnectionForUser(username);
|
||||||
|
|
||||||
|
await Media.applyLocalStreamToPeerConnection(pc, username);
|
||||||
|
|
||||||
|
const offer = await pc.createOffer();
|
||||||
|
// LogMessage(`Offer created: ${JSON.stringify(offer)}`);
|
||||||
|
await pc.setLocalDescription(offer);
|
||||||
|
|
||||||
|
await RelaySocket.sendRtcSignal({
|
||||||
|
type: "rtc_offer",
|
||||||
|
channelId: currentChannelId,
|
||||||
|
from: currentUsername,
|
||||||
|
to: username,
|
||||||
|
sdp: offer.sdp
|
||||||
|
});
|
||||||
|
|
||||||
|
LogMessage(`Sent offer to ${username}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRtcSignal(rawJson) {
|
||||||
|
try {
|
||||||
|
const msg = typeof rawJson === "string" ? JSON.parse(rawJson) : rawJson;
|
||||||
|
|
||||||
|
if (!msg || !msg.type) return;
|
||||||
|
if (msg.from === currentUsername) return;
|
||||||
|
|
||||||
|
if (msg.to && msg.to !== currentUsername) {
|
||||||
|
LogMessage(`Ignoring RTC signal meant for ${msg.to}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
LogMessage(`Received signal: ${msg.type} from ${msg.from}`);
|
||||||
|
|
||||||
|
if (msg.type === "rtc_offer") {
|
||||||
|
await handleOffer(msg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg.type === "rtc_answer") {
|
||||||
|
await handleAnswer(msg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg.type === "rtc_ice") {
|
||||||
|
await handleIce(msg);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (msg.type === "rtc_leave") {
|
||||||
|
closePeerConnection(msg.from);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
LogMessage("Unhandled RTC signal type: " + msg.type);
|
||||||
|
} catch (err) {
|
||||||
|
LogMessage("handleRtcSignal failed: " + err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleOffer(msg) {
|
||||||
|
LogMessage(`Offer handler: ${msg}`);
|
||||||
|
const pc = await ensurePeerConnectionForUser(msg.from);
|
||||||
|
|
||||||
|
await Media.ensureLocalMedia();
|
||||||
|
await Media.applyLocalStreamToPeerConnection(pc, msg.from);
|
||||||
|
// const offer = JSON.parse(msg.offer);
|
||||||
|
await pc.setRemoteDescription({
|
||||||
|
type: "offer",
|
||||||
|
sdp: msg.sdp
|
||||||
|
});
|
||||||
|
|
||||||
|
const answer = await pc.createAnswer();
|
||||||
|
await pc.setLocalDescription(answer);
|
||||||
|
|
||||||
|
await RelaySocket.sendRtcSignal({
|
||||||
|
type: "rtc_answer",
|
||||||
|
channelId: currentChannelId,
|
||||||
|
from: currentUsername,
|
||||||
|
to: msg.from,
|
||||||
|
sdp: answer.sdp
|
||||||
|
});
|
||||||
|
|
||||||
|
LogMessage(`Sent answer to ${msg.from}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleAnswer(msg) {
|
||||||
|
const pc = peerConnections[msg.from];
|
||||||
|
|
||||||
|
if (!pc) {
|
||||||
|
LogMessage(`No peer connection found for answer from ${msg.from}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await pc.setRemoteDescription({
|
||||||
|
type: "answer",
|
||||||
|
sdp: msg.sdp
|
||||||
|
});
|
||||||
|
|
||||||
|
LogMessage(`Applied answer from ${msg.from}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleIce(msg) {
|
||||||
|
const pc = peerConnections[msg.from];
|
||||||
|
|
||||||
|
if (!pc) {
|
||||||
|
LogMessage(`No peer connection found for ICE from ${msg.from}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!msg.candidate) return;
|
||||||
|
|
||||||
|
const candidateInit = {
|
||||||
|
candidate: msg.candidate,
|
||||||
|
sdpMid: msg.sdpMid,
|
||||||
|
sdpMLineIndex: msg.sdpMLineIndex
|
||||||
|
};
|
||||||
|
|
||||||
|
await pc.addIceCandidate(candidateInit);
|
||||||
|
|
||||||
|
LogMessage(`Applied ICE from ${msg.from}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensurePeerConnectionForUser(username) {
|
||||||
|
if (peerConnections[username]) {
|
||||||
|
return peerConnections[username];
|
||||||
|
}
|
||||||
|
|
||||||
|
const pc = new RTCPeerConnection(configuration);
|
||||||
|
peerConnections[username] = pc;
|
||||||
|
|
||||||
|
pc.onicecandidate = async event => {
|
||||||
|
if (!event.candidate) return;
|
||||||
|
|
||||||
|
await RelaySocket.sendRtcSignal({
|
||||||
|
type: "rtc_ice",
|
||||||
|
channelId: currentChannelId,
|
||||||
|
from: currentUsername,
|
||||||
|
to: username,
|
||||||
|
candidate: event.candidate.candidate,
|
||||||
|
sdpMid: event.candidate.sdpMid,
|
||||||
|
sdpMLineIndex: event.candidate.sdpMLineIndex
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
pc.ontrack = event => {
|
||||||
|
LogMessage(`Remote track received from ${username}`);
|
||||||
|
|
||||||
|
const stream = event.streams[0];
|
||||||
|
if (!stream) return;
|
||||||
|
|
||||||
|
Media.attachRemoteStream(username, stream);
|
||||||
|
};
|
||||||
|
|
||||||
|
pc.onconnectionstatechange = () => {
|
||||||
|
LogMessage(`Connection ${username}: ${pc.connectionState}`);
|
||||||
|
|
||||||
|
if (
|
||||||
|
pc.connectionState === "failed" ||
|
||||||
|
pc.connectionState === "closed" ||
|
||||||
|
pc.connectionState === "disconnected"
|
||||||
|
) {
|
||||||
|
closePeerConnection(username);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return pc;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function leaveChannelCall() {
|
||||||
|
await RelaySocket.sendRtcSignal({
|
||||||
|
type: "rtc_leave",
|
||||||
|
channelId: currentChannelId,
|
||||||
|
from: currentUsername
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const username of Object.keys(peerConnections)) {
|
||||||
|
closePeerConnection(username);
|
||||||
|
}
|
||||||
|
|
||||||
|
await RelaySocket.leaveRtcChannel();
|
||||||
|
|
||||||
|
LogMessage("Left RTC channel");
|
||||||
|
}
|
||||||
|
|
||||||
|
function closePeerConnection(username) {
|
||||||
|
const pc = peerConnections[username];
|
||||||
|
if (!pc) return;
|
||||||
|
|
||||||
|
pc.close();
|
||||||
|
delete peerConnections[username];
|
||||||
|
|
||||||
|
Media.removeRemoteStream(username);
|
||||||
|
|
||||||
|
LogMessage(`Closed RTC connection with ${username}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
window.RelayRtc = {
|
||||||
|
joinChannelCall,
|
||||||
|
leaveChannelCall,
|
||||||
|
handleRtcSignal,
|
||||||
|
peerConnections
|
||||||
|
};
|
||||||
|
|
||||||
|
window.handleRtcSignal = handleRtcSignal;
|
||||||
@@ -25,7 +25,7 @@
|
|||||||
<Style TargetType="Button">
|
<Style TargetType="Button">
|
||||||
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource White}, Dark={StaticResource PrimaryDarkText}}" />
|
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource White}, Dark={StaticResource PrimaryDarkText}}" />
|
||||||
<Setter Property="BackgroundColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource PrimaryDark}}" />
|
<Setter Property="BackgroundColor" Value="{AppThemeBinding Light={StaticResource Primary}, Dark={StaticResource PrimaryDark}}" />
|
||||||
<Setter Property="FontFamily" Value="OpenSansRegular"/>
|
<Setter Property="FontFamily" Value="AnonymousProRegular"/>
|
||||||
<Setter Property="FontSize" Value="14"/>
|
<Setter Property="FontSize" Value="14"/>
|
||||||
<Setter Property="BorderWidth" Value="0"/>
|
<Setter Property="BorderWidth" Value="0"/>
|
||||||
<Setter Property="CornerRadius" Value="8"/>
|
<Setter Property="CornerRadius" Value="8"/>
|
||||||
@@ -69,7 +69,7 @@
|
|||||||
<Style TargetType="DatePicker">
|
<Style TargetType="DatePicker">
|
||||||
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
|
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
|
||||||
<Setter Property="BackgroundColor" Value="Transparent" />
|
<Setter Property="BackgroundColor" Value="Transparent" />
|
||||||
<Setter Property="FontFamily" Value="OpenSansRegular"/>
|
<Setter Property="FontFamily" Value="AnonymousProRegular"/>
|
||||||
<Setter Property="FontSize" Value="14"/>
|
<Setter Property="FontSize" Value="14"/>
|
||||||
<Setter Property="MinimumHeightRequest" Value="44"/>
|
<Setter Property="MinimumHeightRequest" Value="44"/>
|
||||||
<Setter Property="MinimumWidthRequest" Value="44"/>
|
<Setter Property="MinimumWidthRequest" Value="44"/>
|
||||||
@@ -90,7 +90,7 @@
|
|||||||
<Style TargetType="Editor">
|
<Style TargetType="Editor">
|
||||||
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource White}}" />
|
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource White}}" />
|
||||||
<Setter Property="BackgroundColor" Value="Transparent" />
|
<Setter Property="BackgroundColor" Value="Transparent" />
|
||||||
<Setter Property="FontFamily" Value="OpenSansRegular"/>
|
<Setter Property="FontFamily" Value="AnonymousProRegular"/>
|
||||||
<Setter Property="FontSize" Value="14" />
|
<Setter Property="FontSize" Value="14" />
|
||||||
<Setter Property="PlaceholderColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray500}}" />
|
<Setter Property="PlaceholderColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray500}}" />
|
||||||
<Setter Property="MinimumHeightRequest" Value="44"/>
|
<Setter Property="MinimumHeightRequest" Value="44"/>
|
||||||
@@ -112,7 +112,7 @@
|
|||||||
<Style TargetType="Entry">
|
<Style TargetType="Entry">
|
||||||
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource White}}" />
|
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource White}}" />
|
||||||
<Setter Property="BackgroundColor" Value="Transparent" />
|
<Setter Property="BackgroundColor" Value="Transparent" />
|
||||||
<Setter Property="FontFamily" Value="OpenSansRegular"/>
|
<Setter Property="FontFamily" Value="AnonymousProRegular"/>
|
||||||
<Setter Property="FontSize" Value="14" />
|
<Setter Property="FontSize" Value="14" />
|
||||||
<Setter Property="PlaceholderColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray500}}" />
|
<Setter Property="PlaceholderColor" Value="{AppThemeBinding Light={StaticResource Gray200}, Dark={StaticResource Gray500}}" />
|
||||||
<Setter Property="MinimumHeightRequest" Value="44"/>
|
<Setter Property="MinimumHeightRequest" Value="44"/>
|
||||||
@@ -156,7 +156,7 @@
|
|||||||
<Style TargetType="Label">
|
<Style TargetType="Label">
|
||||||
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource White}}" />
|
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource White}}" />
|
||||||
<Setter Property="BackgroundColor" Value="Transparent" />
|
<Setter Property="BackgroundColor" Value="Transparent" />
|
||||||
<Setter Property="FontFamily" Value="OpenSansRegular" />
|
<Setter Property="FontFamily" Value="AnonymousProRegular" />
|
||||||
<Setter Property="FontSize" Value="14" />
|
<Setter Property="FontSize" Value="14" />
|
||||||
<Setter Property="VisualStateManager.VisualStateGroups">
|
<Setter Property="VisualStateManager.VisualStateGroups">
|
||||||
<VisualStateGroupList>
|
<VisualStateGroupList>
|
||||||
@@ -190,7 +190,7 @@
|
|||||||
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
|
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
|
||||||
<Setter Property="TitleColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource Gray200}}" />
|
<Setter Property="TitleColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource Gray200}}" />
|
||||||
<Setter Property="BackgroundColor" Value="Transparent" />
|
<Setter Property="BackgroundColor" Value="Transparent" />
|
||||||
<Setter Property="FontFamily" Value="OpenSansRegular"/>
|
<Setter Property="FontFamily" Value="AnonymousProRegular"/>
|
||||||
<Setter Property="FontSize" Value="14" />
|
<Setter Property="FontSize" Value="14" />
|
||||||
<Setter Property="MinimumHeightRequest" Value="44"/>
|
<Setter Property="MinimumHeightRequest" Value="44"/>
|
||||||
<Setter Property="MinimumWidthRequest" Value="44"/>
|
<Setter Property="MinimumWidthRequest" Value="44"/>
|
||||||
@@ -228,7 +228,7 @@
|
|||||||
<Style TargetType="RadioButton">
|
<Style TargetType="RadioButton">
|
||||||
<Setter Property="BackgroundColor" Value="Transparent"/>
|
<Setter Property="BackgroundColor" Value="Transparent"/>
|
||||||
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource White}}" />
|
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Black}, Dark={StaticResource White}}" />
|
||||||
<Setter Property="FontFamily" Value="OpenSansRegular"/>
|
<Setter Property="FontFamily" Value="AnonymousProRegular"/>
|
||||||
<Setter Property="FontSize" Value="14"/>
|
<Setter Property="FontSize" Value="14"/>
|
||||||
<Setter Property="MinimumHeightRequest" Value="44"/>
|
<Setter Property="MinimumHeightRequest" Value="44"/>
|
||||||
<Setter Property="MinimumWidthRequest" Value="44"/>
|
<Setter Property="MinimumWidthRequest" Value="44"/>
|
||||||
@@ -255,7 +255,7 @@
|
|||||||
<Setter Property="PlaceholderColor" Value="{StaticResource Gray500}" />
|
<Setter Property="PlaceholderColor" Value="{StaticResource Gray500}" />
|
||||||
<Setter Property="CancelButtonColor" Value="{StaticResource Gray500}" />
|
<Setter Property="CancelButtonColor" Value="{StaticResource Gray500}" />
|
||||||
<Setter Property="BackgroundColor" Value="Transparent" />
|
<Setter Property="BackgroundColor" Value="Transparent" />
|
||||||
<Setter Property="FontFamily" Value="OpenSansRegular" />
|
<Setter Property="FontFamily" Value="AnonymousProRegular" />
|
||||||
<Setter Property="FontSize" Value="14" />
|
<Setter Property="FontSize" Value="14" />
|
||||||
<Setter Property="MinimumHeightRequest" Value="44"/>
|
<Setter Property="MinimumHeightRequest" Value="44"/>
|
||||||
<Setter Property="MinimumWidthRequest" Value="44"/>
|
<Setter Property="MinimumWidthRequest" Value="44"/>
|
||||||
@@ -278,7 +278,7 @@
|
|||||||
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
|
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
|
||||||
<Setter Property="PlaceholderColor" Value="{StaticResource Gray500}" />
|
<Setter Property="PlaceholderColor" Value="{StaticResource Gray500}" />
|
||||||
<Setter Property="BackgroundColor" Value="Transparent" />
|
<Setter Property="BackgroundColor" Value="Transparent" />
|
||||||
<Setter Property="FontFamily" Value="OpenSansRegular" />
|
<Setter Property="FontFamily" Value="AnonymousProRegular" />
|
||||||
<Setter Property="FontSize" Value="14" />
|
<Setter Property="FontSize" Value="14" />
|
||||||
<Setter Property="VisualStateManager.VisualStateGroups">
|
<Setter Property="VisualStateManager.VisualStateGroups">
|
||||||
<VisualStateGroupList>
|
<VisualStateGroupList>
|
||||||
@@ -358,7 +358,7 @@
|
|||||||
<Style TargetType="TimePicker">
|
<Style TargetType="TimePicker">
|
||||||
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
|
<Setter Property="TextColor" Value="{AppThemeBinding Light={StaticResource Gray900}, Dark={StaticResource White}}" />
|
||||||
<Setter Property="BackgroundColor" Value="Transparent"/>
|
<Setter Property="BackgroundColor" Value="Transparent"/>
|
||||||
<Setter Property="FontFamily" Value="OpenSansRegular"/>
|
<Setter Property="FontFamily" Value="AnonymousProRegular"/>
|
||||||
<Setter Property="FontSize" Value="14"/>
|
<Setter Property="FontSize" Value="14"/>
|
||||||
<Setter Property="MinimumHeightRequest" Value="44"/>
|
<Setter Property="MinimumHeightRequest" Value="44"/>
|
||||||
<Setter Property="MinimumWidthRequest" Value="44"/>
|
<Setter Property="MinimumWidthRequest" Value="44"/>
|
||||||
|
|||||||
194
RelayClient/ServerAPI.cs
Normal file
194
RelayClient/ServerAPI.cs
Normal file
@@ -0,0 +1,194 @@
|
|||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Text.Json;
|
||||||
|
using RelayShared.Services;
|
||||||
|
|
||||||
|
namespace RelayClient;
|
||||||
|
|
||||||
|
public class ServerAPI
|
||||||
|
{
|
||||||
|
static HttpClient client = new HttpClient { BaseAddress = new Uri("http://127.0.0.1:5000/") };
|
||||||
|
static HttpClient core = new HttpClient { BaseAddress = new Uri("http://127.0.0.1:1337/") };
|
||||||
|
// static HttpClient client = new HttpClient { BaseAddress = new Uri("http://192.168.1.92:5000/") };
|
||||||
|
// static HttpClient core = new HttpClient { BaseAddress = new Uri("http://192.168.1.92:1337/") };
|
||||||
|
|
||||||
|
public static async Task setupClient()
|
||||||
|
{
|
||||||
|
client.DefaultRequestHeaders.Accept.Clear();
|
||||||
|
client.DefaultRequestHeaders.Accept.Add(
|
||||||
|
new MediaTypeWithQualityHeaderValue("application/json"));
|
||||||
|
core.DefaultRequestHeaders.Accept.Clear();
|
||||||
|
core.DefaultRequestHeaders.Accept.Add(
|
||||||
|
new MediaTypeWithQualityHeaderValue("application/json"));
|
||||||
|
core.DefaultRequestHeaders.Add("User-Agent", "RelayClient");
|
||||||
|
MainPage._userToken = await CoreUserSignin(new AuthSignin
|
||||||
|
{
|
||||||
|
UserName = MainPage._username,
|
||||||
|
Password = "password"
|
||||||
|
});
|
||||||
|
|
||||||
|
await CoreUserAlive(new AuthSignin
|
||||||
|
{
|
||||||
|
UserName = MainPage._username,
|
||||||
|
Password = MainPage._userToken
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<Uri> CoreUserAlive(AuthSignin data)
|
||||||
|
{
|
||||||
|
HttpResponseMessage response = await core.PostAsJsonAsync("user/isAlive", data);
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return response.Headers.Location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<string> CoreUserSignin(AuthSignin data)
|
||||||
|
{
|
||||||
|
HttpResponseMessage response = await core.PostAsJsonAsync("user/signin", data);
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return await response.Content.ReadAsStringAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<Uri> PostOfferAsync(DBOffer offer)
|
||||||
|
{
|
||||||
|
HttpResponseMessage response = await client.PostAsJsonAsync(
|
||||||
|
"api/rtc/offer", offer);
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return response.Headers.Location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<Uri> GetAllOffersAsync()
|
||||||
|
{
|
||||||
|
HttpResponseMessage response = await client.GetAsync("api/rtc/offers");
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return response.Headers.Location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<bool> GetIsChannelActiveAsync(string channelId)
|
||||||
|
{
|
||||||
|
HttpResponseMessage response = await client.GetAsync($"api/rtc/active/{channelId}");
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return bool.Parse(response.Content.ReadAsStringAsync().Result);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<RtcDescription> GetOffersForChannelAsync(string channelId)
|
||||||
|
{
|
||||||
|
HttpResponseMessage response = await client.GetAsync($"api/rtc/offers/{channelId}");
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
RtcDescription? offer = JsonSerializer.Deserialize<RtcDescription>(await response.Content.ReadAsStringAsync());
|
||||||
|
return offer;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<Uri?> PostAnswerAsync(DBOffer answer)
|
||||||
|
{
|
||||||
|
HttpResponseMessage response = await client.PostAsJsonAsync("api/rtc/answer", answer);
|
||||||
|
var body = await response.Content.ReadAsStringAsync();
|
||||||
|
|
||||||
|
Console.WriteLine("PostAnswerAsync status: " + response.StatusCode);
|
||||||
|
Console.WriteLine("PostAnswerAsync body: " + body);
|
||||||
|
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return response.Headers.Location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<Uri> GetAnswersForChannelAsync(string channelId)
|
||||||
|
{
|
||||||
|
HttpResponseMessage response = await client.GetAsync($"api/rtc/answers/{channelId}");
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return response.Headers.Location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<Uri> GetLatestAnswerForChannelAsync(string channelId)
|
||||||
|
{
|
||||||
|
HttpResponseMessage response = await client.GetAsync($"api/rtc/latest/{channelId}");
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return response.Headers.Location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<Uri> PostIceCandidateAsync(DBIceCandidate candidate)
|
||||||
|
{
|
||||||
|
HttpResponseMessage response = await client.PostAsJsonAsync("api/rtc/candidate", candidate);
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return response.Headers.Location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<Uri> GetIceCandidatesForChannelAsync(string channelId)
|
||||||
|
{
|
||||||
|
HttpResponseMessage response = await client.GetAsync($"api/rtc/candidates/{channelId}");
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return response.Headers.Location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<Uri> GetIceCandidatesForChannelByUserAsync(string channelId, string userId, string directions)
|
||||||
|
{
|
||||||
|
HttpResponseMessage response = await client.GetAsync($"api/rtc/candidates/{channelId}/{userId}/{directions}");
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return response.Headers.Location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<Uri> PostLeave(RtcLeave leave)
|
||||||
|
{
|
||||||
|
HttpResponseMessage response = await client.PostAsJsonAsync("api/rtc/leave", leave);
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
return response.Headers.Location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<RtcDescription?> GetAnswerForChannelAsync(string? channelId)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(channelId))
|
||||||
|
return null;
|
||||||
|
|
||||||
|
HttpResponseMessage response = await client.GetAsync($"api/rtc/answer/{channelId}");
|
||||||
|
if (!response.IsSuccessStatusCode)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var json = await response.Content.ReadAsStringAsync();
|
||||||
|
return JsonSerializer.Deserialize<RtcDescription>(json);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static async Task<List<string>> GetRtcParticipantsAsync(string? channelId)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(channelId))
|
||||||
|
return new List<string>();
|
||||||
|
|
||||||
|
HttpResponseMessage response = await client.GetAsync($"api/rtc/participants/{channelId}");
|
||||||
|
response.EnsureSuccessStatusCode();
|
||||||
|
|
||||||
|
var json = await response.Content.ReadAsStringAsync();
|
||||||
|
|
||||||
|
return JsonSerializer.Deserialize<List<string>>(json) ?? new List<string>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class RtcDescription
|
||||||
|
{
|
||||||
|
public string type { get; set; }
|
||||||
|
public string sdp { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class DBOffer
|
||||||
|
{
|
||||||
|
public required string ChannelId { get; set; }
|
||||||
|
public required string Username { get; set; }
|
||||||
|
public required RtcDescription SessionDescription { get; set; }
|
||||||
|
}
|
||||||
|
public class IceCandidate
|
||||||
|
{
|
||||||
|
public required string candidate { get; set; }
|
||||||
|
public required string sdpMid { get; set; }
|
||||||
|
public required int sdpMLineIndex { get; set; }
|
||||||
|
public required string usernameFragment { get; set; }
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public class DBIceCandidate
|
||||||
|
{
|
||||||
|
public required string ChannelId { get; set; }
|
||||||
|
public required string Username { get; set; }
|
||||||
|
public required IceCandidate Candidate { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class RtcLeave
|
||||||
|
{
|
||||||
|
public string ChannelId { get; set; }
|
||||||
|
public string Username { get; set; }
|
||||||
|
}
|
||||||
281
RelayClient/Services/RelaySocketClient.cs
Normal file
281
RelayClient/Services/RelaySocketClient.cs
Normal file
@@ -0,0 +1,281 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using RelayClient.Crypto;
|
||||||
|
using RelayShared.Services;
|
||||||
|
using WebSocketSharp;
|
||||||
|
|
||||||
|
namespace RelayClient.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The client-side WebSocket transport. Mirrors ChatSocketBehavior on the server.
|
||||||
|
///
|
||||||
|
/// Sending: typed helpers (SendGetHistory, SendRtcJoinChannel, SendEditMessage, …) build the
|
||||||
|
/// appropriate WsControlMessage or SocketEncryptedMessage and route through SendRaw. SendRaw
|
||||||
|
/// always uses synchronous _socket.Send because WebSocketSharp's SendAsync calls
|
||||||
|
/// Action.BeginInvoke internally, which throws PlatformNotSupportedException on .NET 5+.
|
||||||
|
/// Callers that need non-blocking sends (e.g. MainPage.SendMessage for image attachments)
|
||||||
|
/// wrap the call in Task.Run.
|
||||||
|
///
|
||||||
|
/// Receiving: OnMessage peeks the JSON. If it has an "Event" property → WsEventMessage (acks).
|
||||||
|
/// If it has a "Type" property → SignalType discriminator, deserialise into the right Socket*
|
||||||
|
/// type, fire the matching C# event. MainPage subscribes to these events.
|
||||||
|
///
|
||||||
|
/// Connect order matters: the first frame after the handshake is Authenticate (so the server
|
||||||
|
/// can verify the Core-issued token), then RegisterKey (so the server has our public key
|
||||||
|
/// before any encrypted message arrives), then GetServerKey + GetChannels.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class RelaySocketClient
|
||||||
|
{
|
||||||
|
/// <summary>Username this socket is authenticated as. Captured at construction.</summary>
|
||||||
|
private readonly string _username;
|
||||||
|
|
||||||
|
/// <summary>The underlying WebSocketSharp client. Owned (constructed) by this class.</summary>
|
||||||
|
private readonly WebSocket _socket;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The server's RSA public key, cached after the first GetServerKey response.
|
||||||
|
/// MainPage reads this to encrypt outbound chat payloads.
|
||||||
|
/// </summary>
|
||||||
|
public string? ServerPublicKey { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>Fires for every raw incoming text frame. Mostly used for debug logging.</summary>
|
||||||
|
public event Action<string>? RawMessageReceived;
|
||||||
|
|
||||||
|
/// <summary>Fires when the server pushes a fresh channel list (initial connect or after CRUD).</summary>
|
||||||
|
public event Action<SocketChannelList>? ChannelListReceived;
|
||||||
|
|
||||||
|
/// <summary>Fires for newly-arrived chat messages (SignalType.EncryptedChat).</summary>
|
||||||
|
public event Action<SocketEncryptedMessage>? EncryptedChatReceived;
|
||||||
|
|
||||||
|
/// <summary>Fires when an existing message is edited by its author (SignalType.MessageEdited).</summary>
|
||||||
|
public event Action<SocketEncryptedMessage>? MessageEdited;
|
||||||
|
|
||||||
|
/// <summary>Fires when a message is deleted (SignalType.MessageDeleted).</summary>
|
||||||
|
public event Action<SocketMessageDeletedEvent>? MessageDeleted;
|
||||||
|
|
||||||
|
/// <summary>Fires when another user is typing in a channel.</summary>
|
||||||
|
public event Action<SocketTypingEvent>? TypingReceived;
|
||||||
|
|
||||||
|
/// <summary>Fires in response to a SendGetEditHistory request.</summary>
|
||||||
|
public event Action<SocketEditHistoryResponse>? EditHistoryReceived;
|
||||||
|
|
||||||
|
/// <summary>Fires for encrypted RTC SDP/ICE signals — RtcBridgeService forwards into the JS engine.</summary>
|
||||||
|
public event Action<SocketRtcSignalMessage>? EncryptedRtcSignalReceived;
|
||||||
|
|
||||||
|
/// <summary>Fires once when the server's public key arrives. Mainly used by tests; production reads ServerPublicKey directly.</summary>
|
||||||
|
public event Action<string>? ServerPublicKeyReceived;
|
||||||
|
|
||||||
|
/// <summary>Diagnostic logger. MainPage subscribes Console.WriteLine here.</summary>
|
||||||
|
public event Action<string>? Log;
|
||||||
|
|
||||||
|
/// <summary>Default URL points at localhost dev server. Production passes a remote URL.</summary>
|
||||||
|
public RelaySocketClient(string username, string url = "ws://127.0.0.1:5001/")
|
||||||
|
{
|
||||||
|
_username = username;
|
||||||
|
_socket = new WebSocket(url);
|
||||||
|
_socket.OnMessage += OnMessage;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Opens the WebSocket and fires the four-step boot handshake IN ORDER:
|
||||||
|
/// Authenticate → RegisterKey → GetServerKey → GetChannels. Order matters because the
|
||||||
|
/// server uses RegisterKey to populate its session→username map (needed for permission
|
||||||
|
/// checks on subsequent messages).
|
||||||
|
/// </summary>
|
||||||
|
public void Connect()
|
||||||
|
{
|
||||||
|
_socket.Connect();
|
||||||
|
|
||||||
|
var publicKey = KeyStorage.LoadPublicKey(_username);
|
||||||
|
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.Authenticate, Username = _username, Token = MainPage._userToken });
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.RegisterKey, Username = _username, PublicKey = publicKey });
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.GetServerKey });
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.GetChannels });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Detaches the message handler and closes the socket. Called from MainPage.OnDisappearing.</summary>
|
||||||
|
public void Disconnect()
|
||||||
|
{
|
||||||
|
_socket.OnMessage -= OnMessage;
|
||||||
|
if (_socket.ReadyState == WebSocketState.Open)
|
||||||
|
_socket.Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Generic control-plane send. Serialises the WsControlMessage to JSON and ships it.</summary>
|
||||||
|
public void SendControlMessage(WsControlMessage message) =>
|
||||||
|
SendRaw(JsonSerializer.Serialize(message));
|
||||||
|
|
||||||
|
/// <summary>Request the message history for a channel. Server streams it back as individual EncryptedChat frames.</summary>
|
||||||
|
public void SendGetHistory(string channelId) =>
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.GetHistory, Username = _username, ChannelId = channelId });
|
||||||
|
|
||||||
|
/// <summary>Tell the server we've joined a voice channel. Fires Speak permission check server-side.</summary>
|
||||||
|
public void SendRtcJoinChannel(string channelId) =>
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.RtcJoin, Username = _username, ChannelId = channelId });
|
||||||
|
|
||||||
|
/// <summary>Tell the server we've left the voice channel. Idempotent server-side.</summary>
|
||||||
|
public void SendRtcLeaveChannel(string channelId) =>
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.RtcLeave, Username = _username, ChannelId = channelId });
|
||||||
|
|
||||||
|
/// <summary>Notify channel peers that we're typing. Server broadcasts a SocketTypingEvent to everyone but us.</summary>
|
||||||
|
public void SendTyping(string channelId) =>
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.SendTyping, Username = _username, ChannelId = channelId });
|
||||||
|
|
||||||
|
/// <summary>Request all historical versions of a message. Server replies with SocketEditHistoryResponse.</summary>
|
||||||
|
public void SendGetEditHistory(string messageId, string channelId) =>
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.GetEditHistory, Username = _username, MessageId = messageId, ChannelId = channelId });
|
||||||
|
|
||||||
|
/// <summary>Create a new channel. Permission-gated server-side; on success the server broadcasts a fresh channel list.</summary>
|
||||||
|
public void SendCreateChannel(string name, ChannelType type, string group = "") =>
|
||||||
|
SendControlMessage(new WsControlMessage
|
||||||
|
{
|
||||||
|
Action = WsAction.CreateChannel,
|
||||||
|
ChannelName = name,
|
||||||
|
ChannelType = (int)type,
|
||||||
|
ChannelGroup = group
|
||||||
|
});
|
||||||
|
|
||||||
|
/// <summary>Soft-delete a channel. Permission-gated server-side.</summary>
|
||||||
|
public void SendDeleteChannel(string channelId) =>
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.DeleteChannel, ChannelId = channelId });
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Send an edit for an existing message. Caller is responsible for encrypting the new
|
||||||
|
/// content (with the server's public key) before calling — same encryption shape as a new send.
|
||||||
|
/// </summary>
|
||||||
|
public void SendEditMessage(string messageId, string channelId, EncryptedPayload encrypted) =>
|
||||||
|
SendJson(new SocketEncryptedMessage
|
||||||
|
{
|
||||||
|
Type = SignalType.ClientEditMessage, MessageId = messageId,
|
||||||
|
SenderUsername = _username, ChannelId = channelId,
|
||||||
|
CipherText = encrypted.CipherText, Nonce = encrypted.Nonce,
|
||||||
|
Tag = encrypted.Tag, EncryptedKey = encrypted.EncryptedKey
|
||||||
|
});
|
||||||
|
|
||||||
|
/// <summary>Request soft-delete of one of our own messages. Server checks ownership before honoring.</summary>
|
||||||
|
public void SendDeleteMessage(string messageId, string channelId) =>
|
||||||
|
SendJson(new SocketEncryptedMessage
|
||||||
|
{
|
||||||
|
Type = SignalType.ClientDeleteMessage, MessageId = messageId,
|
||||||
|
SenderUsername = _username, ChannelId = channelId
|
||||||
|
});
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The single send pinch point. Synchronous (WebSocketSharp's SendAsync is broken on .NET 5+
|
||||||
|
/// due to Action.BeginInvoke). All exceptions are logged AND rethrown so the calling
|
||||||
|
/// Task.Run can surface them to the user via DisplayAlert.
|
||||||
|
/// </summary>
|
||||||
|
public void SendRaw(string message)
|
||||||
|
{
|
||||||
|
if (_socket.ReadyState != WebSocketState.Open)
|
||||||
|
{
|
||||||
|
Log?.Invoke($"[{_username}] Drop: socket not open ({_socket.ReadyState}), {message.Length} bytes.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_socket.Send(message);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log?.Invoke($"[{_username}] Send failed ({message.Length} bytes): {ex.Message}");
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Convenience: JSON-serialise any payload and ship it. Used for all SocketEncryptedMessage and WsControlMessage sends.</summary>
|
||||||
|
public void SendJson<T>(T payload) => SendRaw(JsonSerializer.Serialize(payload));
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// WebSocketSharp callback for every incoming text frame. Peeks the JSON to decide whether
|
||||||
|
/// it's a control-plane ack (Event property) or data-plane message (Type property), then
|
||||||
|
/// fires the matching public C# event. Exceptions are caught locally so a malformed frame
|
||||||
|
/// can't drop the connection.
|
||||||
|
/// </summary>
|
||||||
|
private void OnMessage(object? sender, MessageEventArgs e)
|
||||||
|
{
|
||||||
|
RawMessageReceived?.Invoke(e.Data);
|
||||||
|
Log?.Invoke($"[{_username}] RAW: {e.Data[..Math.Min(200, e.Data.Length)]}");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var doc = JsonDocument.Parse(e.Data);
|
||||||
|
var root = doc.RootElement;
|
||||||
|
|
||||||
|
if (root.TryGetProperty("Event", out var evEl))
|
||||||
|
{
|
||||||
|
var wsEvent = (WsEvent)evEl.GetInt32();
|
||||||
|
switch (wsEvent)
|
||||||
|
{
|
||||||
|
case WsEvent.KeyRegistered: Log?.Invoke($"[{_username}] Key registered."); return;
|
||||||
|
case WsEvent.Authenticated: Log?.Invoke($"[{_username}] Authenticated."); return;
|
||||||
|
case WsEvent.Error:
|
||||||
|
var det = root.TryGetProperty("Detail", out var d) ? d.GetString() : null;
|
||||||
|
Log?.Invoke($"[{_username}] Server error: {det}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!root.TryGetProperty("Type", out var typeEl)) return;
|
||||||
|
var type = (SignalType)typeEl.GetInt32();
|
||||||
|
|
||||||
|
switch (type)
|
||||||
|
{
|
||||||
|
case SignalType.ChannelList:
|
||||||
|
{
|
||||||
|
var p = JsonSerializer.Deserialize<SocketChannelList>(e.Data);
|
||||||
|
if (p is not null) ChannelListReceived?.Invoke(p);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case SignalType.ServerPublicKey:
|
||||||
|
{
|
||||||
|
var p = JsonSerializer.Deserialize<ServerPublicKeyMessage>(e.Data);
|
||||||
|
if (p is not null) { ServerPublicKey = p.PublicKey; ServerPublicKeyReceived?.Invoke(p.PublicKey); }
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case SignalType.EncryptedSignal:
|
||||||
|
{
|
||||||
|
var p = JsonSerializer.Deserialize<SocketRtcSignalMessage>(e.Data);
|
||||||
|
if (p is not null) EncryptedRtcSignalReceived?.Invoke(p);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case SignalType.EncryptedChat:
|
||||||
|
{
|
||||||
|
var p = JsonSerializer.Deserialize<SocketEncryptedMessage>(e.Data);
|
||||||
|
if (p is not null) EncryptedChatReceived?.Invoke(p);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case SignalType.MessageEdited:
|
||||||
|
{
|
||||||
|
var p = JsonSerializer.Deserialize<SocketEncryptedMessage>(e.Data);
|
||||||
|
if (p is not null) MessageEdited?.Invoke(p);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case SignalType.MessageDeleted:
|
||||||
|
{
|
||||||
|
var p = JsonSerializer.Deserialize<SocketMessageDeletedEvent>(e.Data);
|
||||||
|
if (p is not null) MessageDeleted?.Invoke(p);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case SignalType.TypingIndicator:
|
||||||
|
{
|
||||||
|
var p = JsonSerializer.Deserialize<SocketTypingEvent>(e.Data);
|
||||||
|
if (p is not null) TypingReceived?.Invoke(p);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
case SignalType.EditHistory:
|
||||||
|
{
|
||||||
|
var p = JsonSerializer.Deserialize<SocketEditHistoryResponse>(e.Data);
|
||||||
|
if (p is not null) EditHistoryReceived?.Invoke(p);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log?.Invoke($"[{_username}] WS parse error: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
304
RelayClient/Services/RtcBridgeService.cs
Normal file
304
RelayClient/Services/RtcBridgeService.cs
Normal file
@@ -0,0 +1,304 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
using RelayClient.Crypto;
|
||||||
|
using RelayShared.Rtc;
|
||||||
|
using RelayShared.Services;
|
||||||
|
|
||||||
|
namespace RelayClient.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The bridge between the C# WebSocket pipe and the JavaScript WebRTC engine
|
||||||
|
/// running inside the HybridWebView (which is shown when a Voice channel is open).
|
||||||
|
///
|
||||||
|
/// Outbound (JS → C# → server): the WebView JS calls into C# via SendRtcSignal(json).
|
||||||
|
/// We deserialise to RtcSignalMessage, encrypt with the server's public key, wrap in
|
||||||
|
/// SocketRtcSignalMessage, and send through the WebSocket.
|
||||||
|
///
|
||||||
|
/// Inbound (server → C# → JS): the WebSocket fires EncryptedRtcSignalReceived. MainPage
|
||||||
|
/// hands it to HandleIncomingRtcSignalAsync, which decrypts with the user's private key
|
||||||
|
/// and calls back into JS via hybridWebView.InvokeJavaScriptAsync("testIndex", …).
|
||||||
|
///
|
||||||
|
/// JoinRtcChannel / LeaveRtcChannel just send WsAction control messages; presence tracking
|
||||||
|
/// happens server-side in RtcChannelPresenceService.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class RtcBridgeService
|
||||||
|
{
|
||||||
|
/// <summary>The currently-signed-in username. Stamped onto outgoing RTC signals.</summary>
|
||||||
|
private readonly string _username;
|
||||||
|
|
||||||
|
/// <summary>The shared WebSocket to RelayServer. Outbound RTC signals ride on this.</summary>
|
||||||
|
private readonly RelaySocketClient _socket;
|
||||||
|
|
||||||
|
/// <summary>The MAUI HybridWebView that hosts the JS WebRTC engine. We push JS calls into it.</summary>
|
||||||
|
private readonly HybridWebView _hybridWebView;
|
||||||
|
|
||||||
|
/// <summary>Lazy view into MainPage._currentChannelId so we always have the current voice channel.</summary>
|
||||||
|
private readonly Func<string?> _getCurrentChannelId;
|
||||||
|
|
||||||
|
/// <summary>Diagnostic logger that surfaces messages back to the WebView UI. Used for status/error reporting.</summary>
|
||||||
|
private readonly Action<string> _sendRawToWebView;
|
||||||
|
|
||||||
|
/// <summary>Captures collaborators. MainPage constructs this once and never replaces it.</summary>
|
||||||
|
public RtcBridgeService(string username, RelaySocketClient socket, HybridWebView hybridWebView,
|
||||||
|
Func<string?> getCurrentChannelId, Action<string> sendRawToWebView)
|
||||||
|
{
|
||||||
|
_username = username;
|
||||||
|
_socket = socket;
|
||||||
|
_hybridWebView = hybridWebView;
|
||||||
|
_getCurrentChannelId = getCurrentChannelId;
|
||||||
|
_sendRawToWebView = sendRawToWebView;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sends RtcJoin for the currently-selected channel. Server-side, this triggers the Speak permission check and presence registration.</summary>
|
||||||
|
public Task JoinRtcChannel()
|
||||||
|
{
|
||||||
|
var channelId = _getCurrentChannelId();
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(channelId))
|
||||||
|
return Task.CompletedTask;
|
||||||
|
|
||||||
|
_socket.SendRtcJoinChannel(channelId);
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sends RtcLeave for the currently-selected channel. Clears server-side voice presence so peers stop seeing us.</summary>
|
||||||
|
public void LeaveRtcChannel()
|
||||||
|
{
|
||||||
|
var channelId = _getCurrentChannelId();
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(channelId))
|
||||||
|
return;
|
||||||
|
|
||||||
|
_socket.SendRtcLeaveChannel(channelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Called from JavaScript (via the HybridWebView bridge) when the WebRTC engine wants to
|
||||||
|
/// send an SDP offer/answer or ICE candidate to other peers. Parses the JSON, fills in
|
||||||
|
/// missing ChannelId/From, encrypts with the server's public key, ships as
|
||||||
|
/// SocketRtcSignalMessage. The server then forwards it (re-encrypted per-recipient) to
|
||||||
|
/// every other session in the same voice channel.
|
||||||
|
/// </summary>
|
||||||
|
public void SendRtcSignal(string json)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(_socket.ServerPublicKey))
|
||||||
|
{
|
||||||
|
_sendRawToWebView("SendRtcSignal failed: server public key not loaded.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
RtcSignalMessage? rtcSignal;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
rtcSignal = JsonSerializer.Deserialize<RtcSignalMessage>(json);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_sendRawToWebView("SendRtcSignal failed to parse RTC signal: " + ex.Message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rtcSignal is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
rtcSignal.ChannelId ??= _getCurrentChannelId();
|
||||||
|
rtcSignal.From ??= _username;
|
||||||
|
|
||||||
|
// _sendRawToWebView($"RTC_SIGNAL file: {JsonSerializer.Serialize(rtcSignal)}");
|
||||||
|
if (string.IsNullOrWhiteSpace(rtcSignal.ChannelId))
|
||||||
|
{
|
||||||
|
_sendRawToWebView("SendRtcSignal failed: missing channel id.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var outgoingJson = JsonSerializer.Serialize(rtcSignal);
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var encrypted = E2EeHelper.EncryptForRecipient(outgoingJson, _socket.ServerPublicKey);
|
||||||
|
|
||||||
|
var payload = new SocketRtcSignalMessage
|
||||||
|
{
|
||||||
|
Type = SignalType.EncryptedSignal,
|
||||||
|
SenderUsername = _username,
|
||||||
|
ChannelId = rtcSignal.ChannelId,
|
||||||
|
CipherText = encrypted.CipherText,
|
||||||
|
Nonce = encrypted.Nonce,
|
||||||
|
Tag = encrypted.Tag,
|
||||||
|
EncryptedKey = encrypted.EncryptedKey
|
||||||
|
};
|
||||||
|
|
||||||
|
_socket.SendJson(payload);
|
||||||
|
|
||||||
|
_sendRawToWebView($"SendRtcSignal sent: {rtcSignal.Type} -> {rtcSignal.To}");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_sendRawToWebView("SendRtcSignal failed: " + ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>JS bridge: returns the current voice-channel roster as JSON. Hits ServerAPI's REST endpoint, not the WebSocket.</summary>
|
||||||
|
public async Task<string> GetRtcParticipants()
|
||||||
|
{
|
||||||
|
var channelId = _getCurrentChannelId();
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(channelId))
|
||||||
|
return "[]";
|
||||||
|
|
||||||
|
var participants = await ServerAPI.GetRtcParticipantsAsync(channelId);
|
||||||
|
return JsonSerializer.Serialize(participants ?? []);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// MainPage hands incoming SocketRtcSignalMessage frames here. Filters out our own
|
||||||
|
/// frames, validates the channel scope, decrypts with the user's private key, parses to
|
||||||
|
/// RtcSignalMessage, then pushes into the JS RTC engine via SendRtcSignalToJsAsync.
|
||||||
|
/// </summary>
|
||||||
|
public async Task HandleIncomingRtcSignalAsync(SocketRtcSignalMessage payload)
|
||||||
|
{
|
||||||
|
// _sendRawToWebView("HandleIncomingRtcSignal called");
|
||||||
|
var currentChannelId = _getCurrentChannelId();
|
||||||
|
|
||||||
|
if (payload.ChannelId != currentChannelId)
|
||||||
|
{
|
||||||
|
_sendRawToWebView("Channel id does not match");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (payload.SenderUsername == _username)
|
||||||
|
{
|
||||||
|
_sendRawToWebView("Received own message");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string decryptedJson;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var privateKey = KeyStorage.LoadPrivateKey(_username);
|
||||||
|
|
||||||
|
decryptedJson = E2EeHelper.DecryptForRecipient(
|
||||||
|
new EncryptedPayload
|
||||||
|
{
|
||||||
|
CipherText = payload.CipherText,
|
||||||
|
Nonce = payload.Nonce,
|
||||||
|
Tag = payload.Tag,
|
||||||
|
EncryptedKey = payload.EncryptedKey
|
||||||
|
},
|
||||||
|
privateKey
|
||||||
|
);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_sendRawToWebView("RTC decrypt failed: " + ex.Message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
RtcSignalMessage? rtcSignal;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
rtcSignal = JsonSerializer.Deserialize<RtcSignalMessage>(decryptedJson);
|
||||||
|
// _sendRawToWebView($"Received Encrypted Signal: [{rtcSignal.From}]: {rtcSignal.Offer}");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_sendRawToWebView("RTC signal parse failed: " + ex.Message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rtcSignal is null)
|
||||||
|
{
|
||||||
|
_sendRawToWebView("rtcSignal is null");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(rtcSignal.To) &&
|
||||||
|
!string.Equals(rtcSignal.To, _username, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
_sendRawToWebView($"Ignoring RTC signal meant for {rtcSignal.To}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// _sendRawToWebView("Received encrypted RTC signal: " + decryptedJson);
|
||||||
|
|
||||||
|
await SendRtcSignalToJsAsync(rtcSignal);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Pushes the current username and channelId into JS globals (window.setUsername, window.setChannelId).
|
||||||
|
/// Called whenever the user switches voice channels OR the JS engine reports rtc_page_ready.
|
||||||
|
/// </summary>
|
||||||
|
public Task PushRtcContextToJsAsync()
|
||||||
|
{
|
||||||
|
MainThread.BeginInvokeOnMainThread(async () =>
|
||||||
|
{
|
||||||
|
var usernameJson = JsonSerializer.Serialize(_username);
|
||||||
|
var channelIdJson = JsonSerializer.Serialize(_getCurrentChannelId());
|
||||||
|
|
||||||
|
await _hybridWebView.EvaluateJavaScriptAsync($"window.setUsername({usernameJson})");
|
||||||
|
await _hybridWebView.EvaluateJavaScriptAsync($"window.setChannelId({channelIdJson})");
|
||||||
|
});
|
||||||
|
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Final hop: hands a decrypted RtcSignalMessage off to the JS engine via
|
||||||
|
/// hybridWebView.InvokeJavaScriptAsync("testIndex", …). SDP strings have their newlines
|
||||||
|
/// escaped as "(rn)" because the JSON marshalling otherwise breaks them.
|
||||||
|
/// </summary>
|
||||||
|
private Task SendRtcSignalToJsAsync(RtcSignalMessage data)
|
||||||
|
{
|
||||||
|
if (data.Type == "rtc_offer" || data.Type == "rtc_answer")
|
||||||
|
{
|
||||||
|
data.Sdp = data.Sdp.Replace("\r\n", "(rn)");
|
||||||
|
}
|
||||||
|
MainThread.BeginInvokeOnMainThread(async () =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// await _hybridWebView.InvokeJavaScriptAsync("testIndex", [JsonSerializer.Serialize(data)], [RtcJsType.Default.String]);
|
||||||
|
await _hybridWebView.InvokeJavaScriptAsync("testIndex", [data], [RtcJsType.Default.RtcSignalMessage]);
|
||||||
|
#region OldDebugger
|
||||||
|
// var jsArg = JsonSerializer.Serialize(data);
|
||||||
|
//
|
||||||
|
// await _hybridWebView.EvaluateJavaScriptAsync($@"
|
||||||
|
// try {{
|
||||||
|
// window.HybridWebView.SendRawMessage('C# eval entered');
|
||||||
|
//
|
||||||
|
// if (!window.RelaySocket) {{
|
||||||
|
// window.HybridWebView.SendRawMessage('window.RelaySocket missing');
|
||||||
|
// }} else if (typeof window.RelaySocket.receiveRtcSignal !== 'function') {{
|
||||||
|
// window.HybridWebView.SendRawMessage('RelaySocket.receiveRtcSignal missing');
|
||||||
|
// }} else {{
|
||||||
|
// window.HybridWebView.SendRawMessage('Calling RelaySocket.receiveRtcSignal');
|
||||||
|
// window.RelaySocket.receiveRtcSignal({jsArg});
|
||||||
|
// }}
|
||||||
|
// }} catch (err) {{
|
||||||
|
// window.HybridWebView.SendRawMessage('RTC JS dispatch failed: ' + err);
|
||||||
|
// }}
|
||||||
|
// ");
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_sendRawToWebView("SendRtcSignalToJsAsync failed: " + ex.Message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonSourceGenerationOptions(WriteIndented = false)]
|
||||||
|
[JsonSerializable(typeof(RtcDescription))]
|
||||||
|
[JsonSerializable(typeof(List<RtcSignalMessage>))]
|
||||||
|
[JsonSerializable(typeof(RtcSignalMessage))]
|
||||||
|
[JsonSerializable(typeof(IceCandidate))]
|
||||||
|
[JsonSerializable(typeof(List<IceCandidate>))]
|
||||||
|
[JsonSerializable(typeof(string))]
|
||||||
|
internal partial class RtcJsType : JsonSerializerContext
|
||||||
|
{
|
||||||
|
}
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
using System.Security.Cryptography;
|
|
||||||
using System.Text;
|
|
||||||
|
|
||||||
namespace RelayCore;
|
|
||||||
|
|
||||||
public static class E2EeHelper
|
|
||||||
{
|
|
||||||
public static (string publicKey, string privateKey) GenerateRsaKeyPair()
|
|
||||||
{
|
|
||||||
using var rsa = RSA.Create(2048);
|
|
||||||
|
|
||||||
var publicKey = Convert.ToBase64String(rsa.ExportSubjectPublicKeyInfo());
|
|
||||||
var privateKey = Convert.ToBase64String(rsa.ExportPkcs8PrivateKey());
|
|
||||||
|
|
||||||
return (publicKey, privateKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static EncryptedMessagePayload EncryptForRecipient(string plainText, string recipientPublicKeyBase64)
|
|
||||||
{
|
|
||||||
var aesKey = RandomNumberGenerator.GetBytes(32);
|
|
||||||
var nonce = RandomNumberGenerator.GetBytes(12);
|
|
||||||
var plainBytes = Encoding.UTF8.GetBytes(plainText);
|
|
||||||
var cipherBytes = new byte[plainBytes.Length];
|
|
||||||
var tag = new byte[16];
|
|
||||||
|
|
||||||
using (var aes = new AesGcm(aesKey, 16))
|
|
||||||
{
|
|
||||||
aes.Encrypt(nonce, plainBytes, cipherBytes, tag);
|
|
||||||
}
|
|
||||||
|
|
||||||
var recipientPublicKey = Convert.FromBase64String(recipientPublicKeyBase64);
|
|
||||||
byte[] encryptedKey;
|
|
||||||
|
|
||||||
using (var rsa = RSA.Create())
|
|
||||||
{
|
|
||||||
rsa.ImportSubjectPublicKeyInfo(recipientPublicKey, out _);
|
|
||||||
encryptedKey = rsa.Encrypt(aesKey, RSAEncryptionPadding.OaepSHA256);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new EncryptedMessagePayload
|
|
||||||
{
|
|
||||||
CipherText = Convert.ToBase64String(cipherBytes),
|
|
||||||
Nonce = Convert.ToBase64String(nonce),
|
|
||||||
Tag = Convert.ToBase64String(tag),
|
|
||||||
EncryptedKey = Convert.ToBase64String(encryptedKey)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public static string DecryptForRecipient(EncryptedMessagePayload payload, string recipientPrivateKeyBase64)
|
|
||||||
{
|
|
||||||
var encryptedKey = Convert.FromBase64String(payload.EncryptedKey);
|
|
||||||
var privateKey = Convert.FromBase64String(recipientPrivateKeyBase64);
|
|
||||||
|
|
||||||
byte[] aesKey;
|
|
||||||
|
|
||||||
using (var rsa = RSA.Create())
|
|
||||||
{
|
|
||||||
rsa.ImportPkcs8PrivateKey(privateKey, out _);
|
|
||||||
aesKey = rsa.Decrypt(encryptedKey, RSAEncryptionPadding.OaepSHA256);
|
|
||||||
}
|
|
||||||
|
|
||||||
var nonce = Convert.FromBase64String(payload.Nonce);
|
|
||||||
var tag = Convert.FromBase64String(payload.Tag);
|
|
||||||
var cipherBytes = Convert.FromBase64String(payload.CipherText);
|
|
||||||
var plainBytes = new byte[cipherBytes.Length];
|
|
||||||
|
|
||||||
using (var aes = new AesGcm(aesKey, 16))
|
|
||||||
{
|
|
||||||
aes.Decrypt(nonce, cipherBytes, tag, plainBytes);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Encoding.UTF8.GetString(plainBytes);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public class EncryptedMessagePayload
|
|
||||||
{
|
|
||||||
public required string CipherText { get; set; }
|
|
||||||
public required string Nonce { get; set; }
|
|
||||||
public required string Tag { get; set; }
|
|
||||||
public required string EncryptedKey { get; set; }
|
|
||||||
}
|
|
||||||
63
RelayCore/Endpoints/AuthEndpoints.cs
Normal file
63
RelayCore/Endpoints/AuthEndpoints.cs
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
using Microsoft.Extensions.Primitives;
|
||||||
|
using RelayCore.Services;
|
||||||
|
using RelayShared.Services;
|
||||||
|
|
||||||
|
namespace RelayCore.Endpoints;
|
||||||
|
|
||||||
|
public static class AuthEndpoints
|
||||||
|
{
|
||||||
|
public static void MapAuthEndpoints(this WebApplication app)
|
||||||
|
{
|
||||||
|
app.MapPost("/user/signin", async (AuthSignin request, APIAuthService service, HttpContext context) =>
|
||||||
|
{
|
||||||
|
string ip = "";
|
||||||
|
StringValues userAgent = "";
|
||||||
|
if (context != null)
|
||||||
|
{
|
||||||
|
ip = context.Connection.RemoteIpAddress?.MapToIPv4().ToString();
|
||||||
|
context.Request.Headers.TryGetValue("User-Agent", out userAgent);
|
||||||
|
}
|
||||||
|
|
||||||
|
var token = await service.UserSigninAsync(request, ip, userAgent.ToString());
|
||||||
|
|
||||||
|
return token != null ? Results.Ok(token) : Results.Unauthorized();
|
||||||
|
});
|
||||||
|
app.MapGet("/users", async (APIAuthService service) =>
|
||||||
|
{
|
||||||
|
return Results.Ok(await service.GetUsersAsync());
|
||||||
|
});
|
||||||
|
app.MapPost("/user/register", async (AuthRegister request, APIAuthService service, HttpContext context) =>
|
||||||
|
{
|
||||||
|
var ip = context.Connection.RemoteIpAddress?.MapToIPv4().ToString();
|
||||||
|
context.Request.Headers.TryGetValue("User-Agent", out var userAgent);
|
||||||
|
|
||||||
|
var token = await service.UserRegisterAsync(request, ip, userAgent);
|
||||||
|
return token != null ? Results.Ok(token) : Results.Ok("Username or Email already exists!");
|
||||||
|
});
|
||||||
|
app.MapPost("/user/isAlive", async (AuthSignin request, HttpContext context) =>
|
||||||
|
{
|
||||||
|
var ip = context.Connection.RemoteIpAddress?.MapToIPv4().ToString();
|
||||||
|
context.Request.Headers.TryGetValue("User-Agent", out var userAgent);
|
||||||
|
|
||||||
|
Console.WriteLine($"UN: {request.UserName}\nToken: {request.Password}\nIP: {ip}\nUserAgent: {userAgent}");
|
||||||
|
return Results.Ok();
|
||||||
|
});
|
||||||
|
app.MapPost("/server/verify/user", async (AuthUserVerify request, APIAuthService service) =>
|
||||||
|
{
|
||||||
|
bool valid = await service.ServerVerifyUser(request);
|
||||||
|
Console.WriteLine($"UN: {request.Username}\nToken: {request.Token}");
|
||||||
|
return Results.Ok(valid);
|
||||||
|
});
|
||||||
|
app.MapPost("/server/license/generate", async (AuthServerLicenseGenerate request, APIAuthService service) =>
|
||||||
|
{
|
||||||
|
var license = await service.ServerLicenseGenerate(request);
|
||||||
|
|
||||||
|
return license != null ? Results.Ok(license) : Results.BadRequest();
|
||||||
|
});
|
||||||
|
app.MapPost("/server/license/verify", async (AuthServerLicenseVerify request, APIAuthService service) =>
|
||||||
|
{
|
||||||
|
bool valid = await service.ServerVerifyLicense(request);
|
||||||
|
return Results.Ok(valid);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
9
RelayCore/Enums/AccountStatuses.cs
Normal file
9
RelayCore/Enums/AccountStatuses.cs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
namespace RelayCore.Enums;
|
||||||
|
|
||||||
|
public enum AccountStatuses
|
||||||
|
{
|
||||||
|
Active,
|
||||||
|
Suspended,
|
||||||
|
Banned,
|
||||||
|
Deleted
|
||||||
|
}
|
||||||
9
RelayCore/Enums/LicenseStatuses.cs
Normal file
9
RelayCore/Enums/LicenseStatuses.cs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
namespace RelayCore.Enums;
|
||||||
|
|
||||||
|
public enum LicenseStatuses
|
||||||
|
{
|
||||||
|
Active,
|
||||||
|
Expired,
|
||||||
|
Renewable,
|
||||||
|
Revoked
|
||||||
|
}
|
||||||
10
RelayCore/Enums/LicenseType.cs
Normal file
10
RelayCore/Enums/LicenseType.cs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
namespace RelayCore.Enums;
|
||||||
|
|
||||||
|
public enum LicenseType
|
||||||
|
{
|
||||||
|
Free,
|
||||||
|
Basic,
|
||||||
|
Advanced,
|
||||||
|
Pro,
|
||||||
|
Enterprise
|
||||||
|
}
|
||||||
11
RelayCore/Enums/LogEvents.cs
Normal file
11
RelayCore/Enums/LogEvents.cs
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
namespace RelayCore.Enums;
|
||||||
|
|
||||||
|
public enum LogEvents
|
||||||
|
{
|
||||||
|
LoginSuccess,
|
||||||
|
LoginFailure,
|
||||||
|
LogoutSuccess,
|
||||||
|
LogoutFailure,
|
||||||
|
PasswordResetSuccess,
|
||||||
|
PasswordResetFailure,
|
||||||
|
}
|
||||||
10
RelayCore/Enums/OnlineStatuses.cs
Normal file
10
RelayCore/Enums/OnlineStatuses.cs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
namespace RelayCore.Enums;
|
||||||
|
|
||||||
|
public enum OnlineStatuses
|
||||||
|
{
|
||||||
|
Online,
|
||||||
|
Busy,
|
||||||
|
DND,
|
||||||
|
Invisible,
|
||||||
|
Offline
|
||||||
|
}
|
||||||
14
RelayCore/Models/AuthAudits.cs
Normal file
14
RelayCore/Models/AuthAudits.cs
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayCore.Models;
|
||||||
|
|
||||||
|
public class AuthAudits : Record
|
||||||
|
{
|
||||||
|
public required string UserId { get; set; }
|
||||||
|
public required int EventType { get; set; }
|
||||||
|
public bool Success { get; set; }
|
||||||
|
public required string IpAddress { get; set; }
|
||||||
|
public required string UserAgent { get; set; }
|
||||||
|
public required string Details { get; set; }
|
||||||
|
public required DateTime CreatedAt { get; set; }
|
||||||
|
}
|
||||||
15
RelayCore/Models/Licenses.cs
Normal file
15
RelayCore/Models/Licenses.cs
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayCore.Models;
|
||||||
|
|
||||||
|
public class Licenses : Record
|
||||||
|
{
|
||||||
|
public required string UserId { get; set; }
|
||||||
|
public required int LicenseType { get; set; }
|
||||||
|
public required int Status { get; set; }
|
||||||
|
public required DateTime CreatedAt { get; set; }
|
||||||
|
public required DateTime StartsAt { get; set; }
|
||||||
|
public required DateTime UpdatedAt { get; set; }
|
||||||
|
public required DateTime ExpiresAt { get; set; }
|
||||||
|
|
||||||
|
}
|
||||||
8
RelayCore/Models/PasswordHash.cs
Normal file
8
RelayCore/Models/PasswordHash.cs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayCore.Models;
|
||||||
|
|
||||||
|
public class PasswordHash : Record
|
||||||
|
{
|
||||||
|
public string? Password { get; set; }
|
||||||
|
}
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
using System;
|
|
||||||
using System.Security.Cryptography;
|
using System.Security.Cryptography;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using Konscious.Security.Cryptography;
|
using Konscious.Security.Cryptography;
|
||||||
|
|
||||||
namespace PasswordHasher
|
namespace RelayCore.Models
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Provides secure password hashing functionality using Argon2id algorithm
|
/// Provides secure password hashing functionality using Argon2id algorithm
|
||||||
@@ -23,7 +22,7 @@ namespace PasswordHasher
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Number of threads to use for parallel computation
|
/// Number of threads to use for parallel computation
|
||||||
/// </summary>
|
/// </summary>
|
||||||
private const int DegreeOfParallelism = 1;
|
private const int DegreeOfParallelism = 2;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Number of iterations for the Argon2id algorithm
|
/// Number of iterations for the Argon2id algorithm
|
||||||
12
RelayCore/Models/PasswordReset.cs
Normal file
12
RelayCore/Models/PasswordReset.cs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayCore.Models;
|
||||||
|
|
||||||
|
public class PasswordReset : Record
|
||||||
|
{
|
||||||
|
public required string UserId { get; set; }
|
||||||
|
public required string TokenHash { get; set; }
|
||||||
|
public required DateTime CreatedAt { get; set; }
|
||||||
|
public required DateTime ExpiresAt { get; set; }
|
||||||
|
public bool Revoked { get; set; }
|
||||||
|
}
|
||||||
16
RelayCore/Models/Sessions.cs
Normal file
16
RelayCore/Models/Sessions.cs
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayCore.Models;
|
||||||
|
|
||||||
|
public class Sessions : Record
|
||||||
|
{
|
||||||
|
public required RecordId UserId { get; set; }
|
||||||
|
public required string TokenHash { get; set; }
|
||||||
|
public required DateTime IssuedAt { get; set; }
|
||||||
|
public required DateTime ExpiresAt { get; set; }
|
||||||
|
public DateTime? LastUsedAt { get; set; }
|
||||||
|
public bool Revoked { get; set; }
|
||||||
|
public required string DeviceName { get; set; }
|
||||||
|
public required string IpAddress { get; set; }
|
||||||
|
public required string UserAgent { get; set; }
|
||||||
|
}
|
||||||
18
RelayCore/Models/Users.cs
Normal file
18
RelayCore/Models/Users.cs
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
using System.Text.Json.Serialization;
|
||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayCore.Models;
|
||||||
|
|
||||||
|
public class Users : Record
|
||||||
|
{
|
||||||
|
public required string Username { get; set; }
|
||||||
|
public string? Password { get; set; }
|
||||||
|
public required string Email { get; set; }
|
||||||
|
public required DateTime CreatedAt { get; set; }
|
||||||
|
public required DateTime UpdatedAt { get; set; }
|
||||||
|
public required DateTime LastLogin { get; set; }
|
||||||
|
public bool TwoFactorEnabled { get; set; }
|
||||||
|
public bool EmailVerified { get; set; }
|
||||||
|
public required int AccountStatus { get; set; }
|
||||||
|
public required int OnlineStatus { get; set; }
|
||||||
|
}
|
||||||
@@ -1,91 +1,49 @@
|
|||||||
using SurrealDb.Net;
|
using SurrealDb.Net;
|
||||||
using SurrealDb.Net.Models;
|
|
||||||
using SurrealDb.Net.Models.Auth;
|
using SurrealDb.Net.Models.Auth;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using PasswordHasher;
|
using System.Net;
|
||||||
using RelayCore;
|
using System.Text;
|
||||||
|
|
||||||
using var db = new SurrealDbClient("ws://127.0.0.1:8000/rpc");
|
using RelayCore.Enums;
|
||||||
|
using RelayCore.Models;
|
||||||
|
using RelayCore.Endpoints;
|
||||||
|
using RelayCore.Services;
|
||||||
|
|
||||||
|
|
||||||
|
await using var db = new SurrealDbClient("ws://127.0.0.1:8000/rpc");
|
||||||
await db.SignIn(new RootAuth { Username = "root", Password = "secret" });
|
await db.SignIn(new RootAuth { Username = "root", Password = "secret" });
|
||||||
await db.Use("test", "test");
|
await db.Use("test", "test");
|
||||||
|
|
||||||
var keeper = await CreateUserAsync(db, "Keeper317", "Keeper317@gmail.com", "password");
|
var keeper = await CreateUserAsync(db, "Keeper317", "Keeper317@gmail.com", "password");
|
||||||
var kira = await CreateUserAsync(db, "Ru_Kira", "jduesling13@gmail.com", "password");
|
var kira = await CreateUserAsync(db, "Ru_Kira", "jduesling13@gmail.com", "password");
|
||||||
|
var test = await CreateUserAsync(db, "Test", "test@gmail.com", "password");
|
||||||
|
|
||||||
|
var server = new Program();
|
||||||
|
|
||||||
Console.WriteLine($"Keeper created: {ToJsonString(keeper)}");
|
Console.WriteLine($"Keeper created: {ToJsonString(keeper)}");
|
||||||
Console.WriteLine($"Kira created: {ToJsonString(kira)}");
|
Console.WriteLine($"Kira created: {ToJsonString(kira)}");
|
||||||
|
Console.WriteLine($"Test created: {ToJsonString(test)}");
|
||||||
|
|
||||||
var keeperKeys = E2EeHelper.GenerateRsaKeyPair();
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
var kiraKeys = E2EeHelper.GenerateRsaKeyPair();
|
builder.WebHost.UseUrls("http://127.0.0.1:1337/");
|
||||||
|
// builder.WebHost.UseUrls("http://192.168.1.92:1337");
|
||||||
|
builder.Services.AddSingleton(db);
|
||||||
|
builder.Services.AddScoped<APIAuthService>();
|
||||||
|
|
||||||
KeyStorage.SavePrivateKey("Keeper317", keeperKeys.privateKey);
|
var app = builder.Build();
|
||||||
KeyStorage.SavePrivateKey("Ru_Kira", kiraKeys.privateKey);
|
app.MapGet("/", () => "Auth Server Running!");
|
||||||
|
app.MapAuthEndpoints();
|
||||||
|
|
||||||
await db.Create("user_keys", new UserKeys
|
// await server.Main(db);
|
||||||
{
|
|
||||||
UserId = keeper.Id.ToString(),
|
|
||||||
PublicKey = keeperKeys.publicKey,
|
|
||||||
CreatedAt = DateTime.UtcNow,
|
|
||||||
UpdatedAt = DateTime.UtcNow
|
|
||||||
});
|
|
||||||
|
|
||||||
await db.Create("user_keys", new UserKeys
|
await app.StartAsync();
|
||||||
{
|
Console.WriteLine("API Started");
|
||||||
UserId = kira.Id.ToString(),
|
Console.WriteLine("\n\n\n");
|
||||||
PublicKey = kiraKeys.publicKey,
|
|
||||||
CreatedAt = DateTime.UtcNow,
|
|
||||||
UpdatedAt = DateTime.UtcNow
|
|
||||||
});
|
|
||||||
|
|
||||||
Console.WriteLine("Public keys stored for both users.");
|
Console.Write("Press any key to stop.");
|
||||||
|
Console.ReadKey(true);
|
||||||
var conversation = await db.Create("conversations", new Conversations
|
|
||||||
{
|
|
||||||
CreatedByUserId = keeper.Id.ToString(),
|
|
||||||
CreatedAt = DateTime.UtcNow,
|
|
||||||
UpdatedAt = DateTime.UtcNow,
|
|
||||||
Title = "Keeper317 + Ru_Kira",
|
|
||||||
IsDirectMessage = true
|
|
||||||
});
|
|
||||||
|
|
||||||
Console.WriteLine($"Conversation created: {ToJsonString(conversation)}");
|
|
||||||
|
|
||||||
await db.Create("conversation_members", new ConversationMembers
|
|
||||||
{
|
|
||||||
ConversationId = conversation.Id.ToString(),
|
|
||||||
UserId = keeper.Id.ToString(),
|
|
||||||
JoinedAt = DateTime.UtcNow
|
|
||||||
});
|
|
||||||
|
|
||||||
await db.Create("conversation_members", new ConversationMembers
|
|
||||||
{
|
|
||||||
ConversationId = conversation.Id.ToString(),
|
|
||||||
UserId = kira.Id.ToString(),
|
|
||||||
JoinedAt = DateTime.UtcNow
|
|
||||||
});
|
|
||||||
|
|
||||||
Console.WriteLine("Conversation members added.");
|
|
||||||
|
|
||||||
var encrypted = E2EeHelper.EncryptForRecipient("hello from Keeper317", kiraKeys.publicKey);
|
|
||||||
|
|
||||||
var savedMessage = await db.Create("messages", new Messages
|
|
||||||
{
|
|
||||||
ConversationId = conversation.Id.ToString(),
|
|
||||||
SenderUserId = keeper.Id.ToString(),
|
|
||||||
RecipientUserId = kira.Id.ToString(),
|
|
||||||
CipherText = encrypted.CipherText,
|
|
||||||
Nonce = encrypted.Nonce,
|
|
||||||
Tag = encrypted.Tag,
|
|
||||||
EncryptedKey = encrypted.EncryptedKey,
|
|
||||||
CreatedAt = DateTime.UtcNow
|
|
||||||
});
|
|
||||||
|
|
||||||
Console.WriteLine($"Encrypted message saved: {ToJsonString(savedMessage)}");
|
|
||||||
|
|
||||||
var decrypted = E2EeHelper.DecryptForRecipient(encrypted, kiraKeys.privateKey);
|
|
||||||
Console.WriteLine($"Decrypted for Ru_Kira: {decrypted}");
|
|
||||||
|
|
||||||
|
await app.StopAsync();
|
||||||
return;
|
return;
|
||||||
|
|
||||||
static string ToJsonString(object? o)
|
static string ToJsonString(object? o)
|
||||||
@@ -110,9 +68,9 @@ static async Task<Users> CreateUserAsync(SurrealDbClient db, string username, st
|
|||||||
OnlineStatus = (int)OnlineStatuses.Online,
|
OnlineStatus = (int)OnlineStatuses.Online,
|
||||||
};
|
};
|
||||||
|
|
||||||
var created = await db.Create("users", user);
|
var created = await db.Create("auth_users", user);
|
||||||
|
|
||||||
var hasher = new PasswordHasher.PasswordHasher();
|
var hasher = new PasswordHasher();
|
||||||
var passwordHash = hasher.HashPassword(created.Id.ToString() + rawPassword);
|
var passwordHash = hasher.HashPassword(created.Id.ToString() + rawPassword);
|
||||||
|
|
||||||
var updated = await db.Merge<PasswordHash, Users>(new PasswordHash
|
var updated = await db.Merge<PasswordHash, Users>(new PasswordHash
|
||||||
@@ -124,175 +82,49 @@ static async Task<Users> CreateUserAsync(SurrealDbClient db, string username, st
|
|||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static class KeyStorage
|
partial class Program
|
||||||
{
|
{
|
||||||
public static void SavePrivateKey(string username, string privateKey)
|
public async Task Main(SurrealDbClient db)
|
||||||
{
|
{
|
||||||
Directory.CreateDirectory("keys");
|
// Set up listener
|
||||||
File.WriteAllText(Path.Combine("keys", $"{username}.private.key"), privateKey);
|
using var listener = new HttpListener();
|
||||||
}
|
listener.Prefixes.Add("http://127.0.0.1:8080/");
|
||||||
|
listener.Start();
|
||||||
|
Console.WriteLine("API Started: http://127.0.0.1:8080/");
|
||||||
|
|
||||||
public static string LoadPrivateKey(string username)
|
while (true)
|
||||||
|
{
|
||||||
|
// Process requests
|
||||||
|
var context = await listener.GetContextAsync();
|
||||||
|
var req = context.Request;
|
||||||
|
var res = context.Response;
|
||||||
|
|
||||||
|
if (req.Url.AbsolutePath == "/api/hello" && req.HttpMethod == "GET")
|
||||||
|
{
|
||||||
|
var data = new { Message = "Hello, world!", Time = DateTime.Now };
|
||||||
|
byte[] buf = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(data));
|
||||||
|
res.ContentType = "application/json";
|
||||||
|
await res.OutputStream.WriteAsync(buf, 0, buf.Length);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.Url.AbsolutePath == "/api/users" && req.HttpMethod == "GET")
|
||||||
|
{
|
||||||
|
var data = new { Message = GetDBUsers(db).Result, Time = DateTime.Now };
|
||||||
|
byte[] buf = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(data));
|
||||||
|
res.ContentType = "application/json";
|
||||||
|
await res.OutputStream.WriteAsync(buf, 0, buf.Length);
|
||||||
|
}
|
||||||
|
res.Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
static async Task<Users[]> GetDBUsers(SurrealDbClient db)
|
||||||
|
{
|
||||||
|
var users = await db.Select<Users>("users");
|
||||||
|
Console.WriteLine(ToJsonString(users));
|
||||||
|
return users.ToArray();
|
||||||
|
}
|
||||||
|
static string ToJsonString(object? o)
|
||||||
{
|
{
|
||||||
return File.ReadAllText(Path.Combine("keys", $"{username}.private.key"));
|
return JsonSerializer.Serialize(o, new JsonSerializerOptions { WriteIndented = true, });
|
||||||
}
|
}
|
||||||
|
|
||||||
public static bool PrivateKeyExists(string username)
|
|
||||||
{
|
|
||||||
return File.Exists(Path.Combine("keys", $"{username}.private.key"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public class ResponsibilityMerge : Record
|
|
||||||
{
|
|
||||||
public bool Marketing { get; set; }
|
|
||||||
}
|
|
||||||
public class Group
|
|
||||||
{
|
|
||||||
public bool Marketing { get; set; }
|
|
||||||
public int Count { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class Users : Record
|
|
||||||
{
|
|
||||||
public required string Username { get; set; }
|
|
||||||
public string? Password { get; set; }
|
|
||||||
public required string Email { get; set; }
|
|
||||||
public required DateTime CreatedAt { get; set; }
|
|
||||||
public required DateTime UpdatedAt { get; set; }
|
|
||||||
public required DateTime LastLogin { get; set; }
|
|
||||||
public bool TwoFactorEnabled { get; set; }
|
|
||||||
public bool EmailVerified { get; set; }
|
|
||||||
public required int AccountStatus { get; set; }
|
|
||||||
public required int OnlineStatus { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class PasswordHash : Record
|
|
||||||
{
|
|
||||||
public string? Password { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class Sessions : Record
|
|
||||||
{
|
|
||||||
public required string UserId { get; set; }
|
|
||||||
public required string TokenHash { get; set; }
|
|
||||||
public required DateTime IssuedAt { get; set; }
|
|
||||||
public required DateTime ExpiresAt { get; set; }
|
|
||||||
public DateTime? LastUsedAt { get; set; }
|
|
||||||
public bool Revoked { get; set; }
|
|
||||||
public required string DeviceName { get; set; }
|
|
||||||
public required string IpAddress { get; set; }
|
|
||||||
public required string UserAgent { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class PasswordReset : Record
|
|
||||||
{
|
|
||||||
public required string UserId { get; set; }
|
|
||||||
public required string TokenHash { get; set; }
|
|
||||||
public required DateTime CreatedAt { get; set; }
|
|
||||||
public required DateTime ExpiresAt { get; set; }
|
|
||||||
public bool Revoked { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class Licenses : Record
|
|
||||||
{
|
|
||||||
public required string UserId { get; set; }
|
|
||||||
public required int LicenseType { get; set; }
|
|
||||||
public required int Status { get; set; }
|
|
||||||
public required DateTime CreatedAt { get; set; }
|
|
||||||
public required DateTime StartsAt { get; set; }
|
|
||||||
public required DateTime UpdatedAt { get; set; }
|
|
||||||
public required DateTime ExpiresAt { get; set; }
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public class AuthAudits : Record
|
|
||||||
{
|
|
||||||
public required string UserId { get; set; }
|
|
||||||
public required int EventType { get; set; }
|
|
||||||
public bool Success { get; set; }
|
|
||||||
public required string IpAddress { get; set; }
|
|
||||||
public required string UserAgent { get; set; }
|
|
||||||
public required string Details { get; set; }
|
|
||||||
public required DateTime CreatedAt { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class UserKeys : Record
|
|
||||||
{
|
|
||||||
public required string UserId { get; set; }
|
|
||||||
public required string PublicKey { get; set; }
|
|
||||||
public required DateTime CreatedAt { get; set; }
|
|
||||||
public required DateTime UpdatedAt { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class Conversations : Record
|
|
||||||
{
|
|
||||||
public required string CreatedByUserId { get; set; }
|
|
||||||
public required DateTime CreatedAt { get; set; }
|
|
||||||
public required DateTime UpdatedAt { get; set; }
|
|
||||||
public string? Title { get; set; }
|
|
||||||
public bool IsDirectMessage { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class ConversationMembers : Record
|
|
||||||
{
|
|
||||||
public required string ConversationId { get; set; }
|
|
||||||
public required string UserId { get; set; }
|
|
||||||
public required DateTime JoinedAt { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public class Messages : Record
|
|
||||||
{
|
|
||||||
public required string ConversationId { get; set; }
|
|
||||||
public required string SenderUserId { get; set; }
|
|
||||||
public required string RecipientUserId { get; set; }
|
|
||||||
public required string CipherText { get; set; }
|
|
||||||
public required string Nonce { get; set; }
|
|
||||||
public required string Tag { get; set; }
|
|
||||||
public required string EncryptedKey { get; set; }
|
|
||||||
public required DateTime CreatedAt { get; set; }
|
|
||||||
}
|
|
||||||
|
|
||||||
enum AccountStatuses
|
|
||||||
{
|
|
||||||
Active,
|
|
||||||
Suspended,
|
|
||||||
Banned,
|
|
||||||
Deleted
|
|
||||||
}
|
|
||||||
|
|
||||||
enum OnlineStatuses
|
|
||||||
{
|
|
||||||
Online,
|
|
||||||
Busy,
|
|
||||||
DND,
|
|
||||||
Invisible,
|
|
||||||
Offline
|
|
||||||
}
|
|
||||||
|
|
||||||
enum LicenseStatuses
|
|
||||||
{
|
|
||||||
Active,
|
|
||||||
Expired,
|
|
||||||
Renewable,
|
|
||||||
Revoked
|
|
||||||
}
|
|
||||||
|
|
||||||
enum LicenseType
|
|
||||||
{
|
|
||||||
Free,
|
|
||||||
Basic,
|
|
||||||
Advanced,
|
|
||||||
Pro,
|
|
||||||
Enterprise
|
|
||||||
}
|
|
||||||
|
|
||||||
enum LogEvents
|
|
||||||
{
|
|
||||||
LoginSuccess,
|
|
||||||
LoginFailure,
|
|
||||||
LogoutSuccess,
|
|
||||||
LogoutFailure,
|
|
||||||
PasswordResetSuccess,
|
|
||||||
PasswordResetFailure,
|
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>Exe</OutputType>
|
||||||
@@ -10,7 +10,12 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Konscious.Security.Cryptography.Argon2" Version="1.3.1" />
|
<PackageReference Include="Konscious.Security.Cryptography.Argon2" Version="1.3.1" />
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.2.9" />
|
||||||
<PackageReference Include="SurrealDb.Net" Version="0.9.0" />
|
<PackageReference Include="SurrealDb.Net" Version="0.9.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\RelayShared\RelayShared.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
126
RelayCore/Services/APIAuthService.cs
Normal file
126
RelayCore/Services/APIAuthService.cs
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
using Microsoft.AspNetCore.WebUtilities;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using RelayCore.Endpoints;
|
||||||
|
using RelayCore.Enums;
|
||||||
|
using RelayCore.Models;
|
||||||
|
using RelayShared.Services;
|
||||||
|
using SurrealDb.Net;
|
||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayCore.Services;
|
||||||
|
|
||||||
|
public class APIAuthService(SurrealDbClient _db)
|
||||||
|
{
|
||||||
|
public async Task<List<Users>> GetUsersAsync()
|
||||||
|
{
|
||||||
|
var users = await _db.Select<Users>("auth_users");
|
||||||
|
return users.Where(x => x.Username is not null).OrderByDescending(x=>x.CreatedAt).ToList();
|
||||||
|
}
|
||||||
|
public async Task<string?> UserSigninAsync(AuthSignin request, string ip, string userAgent)
|
||||||
|
{
|
||||||
|
var hasher = new PasswordHasher();
|
||||||
|
var users = await _db.Select<Users>("auth_users");
|
||||||
|
var user = users.FirstOrDefault(x => (x.Username.ToLower() == request.UserName.ToLower() ||
|
||||||
|
x.Email.ToLower() == request.UserName.ToLower()) &&
|
||||||
|
hasher.VerifyPassword(x.Id + request.Password, x.Password));
|
||||||
|
if (user == null)
|
||||||
|
return null;
|
||||||
|
var tokens = await _db.Select<Sessions>("auth_sessions");
|
||||||
|
var token = tokens.Where(x => x.UserId == user.Id && x.IpAddress == ip && x.UserAgent == userAgent && !x.Revoked)
|
||||||
|
.OrderByDescending(x => x.ExpiresAt).FirstOrDefault();
|
||||||
|
if (token != null)
|
||||||
|
if (token.ExpiresAt > DateTime.UtcNow)
|
||||||
|
return token.TokenHash;
|
||||||
|
|
||||||
|
//TODO: Generate TOKEN
|
||||||
|
var newToken = hasher.HashPassword($"{request.UserName}{userAgent}");
|
||||||
|
//TODO: Store TOKEN and Username for verification
|
||||||
|
var sessionId = await _db.Create("auth_sessions", new Sessions
|
||||||
|
{
|
||||||
|
UserId = user.Id,
|
||||||
|
TokenHash = newToken,
|
||||||
|
IssuedAt = DateTime.UtcNow,
|
||||||
|
ExpiresAt = DateTime.UtcNow.AddDays(30),
|
||||||
|
DeviceName = "",
|
||||||
|
Revoked = false,
|
||||||
|
IpAddress = ip,
|
||||||
|
UserAgent = userAgent
|
||||||
|
});
|
||||||
|
//TODO: Add invalidation to TOKENs
|
||||||
|
return newToken;
|
||||||
|
}
|
||||||
|
public async Task<string?> UserRegisterAsync(AuthRegister request, string ip, string userAgent)
|
||||||
|
{
|
||||||
|
var hasher = new PasswordHasher();
|
||||||
|
var users = await _db.Select<Users>("auth_users");
|
||||||
|
var user = users.FirstOrDefault(x => x.Username.ToLower() == request.Username.ToLower() || x.Email.ToLower() == request.Email.ToLower());
|
||||||
|
if (user == null)
|
||||||
|
{
|
||||||
|
var now = DateTime.Now;
|
||||||
|
var created = await _db.Create("auth_users", new Users
|
||||||
|
{
|
||||||
|
Username = request.Username,
|
||||||
|
Email = request.Email,
|
||||||
|
CreatedAt = now,
|
||||||
|
UpdatedAt = now,
|
||||||
|
LastLogin = now,
|
||||||
|
TwoFactorEnabled = false,
|
||||||
|
EmailVerified = false,
|
||||||
|
AccountStatus = (int)AccountStatuses.Active,
|
||||||
|
OnlineStatus = (int)OnlineStatuses.Online,
|
||||||
|
|
||||||
|
});
|
||||||
|
var passwordHash = hasher.HashPassword(created.Id + request.Password);
|
||||||
|
await _db.Merge<PasswordHash, Users>(new PasswordHash
|
||||||
|
{
|
||||||
|
Id = created.Id,
|
||||||
|
Password = passwordHash
|
||||||
|
});
|
||||||
|
|
||||||
|
return await UserSigninAsync(new AuthSignin{UserName=request.Username, Password = request.Password}, ip, userAgent);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> ServerVerifyUser(AuthUserVerify request)
|
||||||
|
{
|
||||||
|
var users = await _db.Select<Users>("auth_users");
|
||||||
|
var user = users.FirstOrDefault(x => x.Username == request.Username);
|
||||||
|
|
||||||
|
if (user == null)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
var sessions = await _db.Select<Sessions>("auth_sessions");
|
||||||
|
var session = sessions.FirstOrDefault(x => x.TokenHash == request.Token && x.UserId == user.Id);
|
||||||
|
if (session == null)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<string?> ServerLicenseGenerate(AuthServerLicenseGenerate request)
|
||||||
|
{
|
||||||
|
var hasher = new PasswordHasher();
|
||||||
|
string token = null;
|
||||||
|
token = hasher.HashPassword(DateTime.Now.ToString("yyyyMMddHHmmss"));
|
||||||
|
var created = await _db.Create("auth_licenses", new DBLicense
|
||||||
|
{
|
||||||
|
Token = token,
|
||||||
|
IsClient = false,
|
||||||
|
CreatedAt = DateTime.UtcNow,
|
||||||
|
ExpiresAt = DateTime.UtcNow.AddDays(365),
|
||||||
|
IsExpired = false,
|
||||||
|
});
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> ServerVerifyLicense(AuthServerLicenseVerify request)
|
||||||
|
{
|
||||||
|
var tokens = await _db.Select<DBLicense>("auth_licenses");
|
||||||
|
var token = tokens.FirstOrDefault(x => x.Token == request.License);
|
||||||
|
if (token != null)
|
||||||
|
return true;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
1
RelayServer/.gitignore
vendored
1
RelayServer/.gitignore
vendored
@@ -79,6 +79,7 @@ keys/*
|
|||||||
############################################
|
############################################
|
||||||
|
|
||||||
data/
|
data/
|
||||||
|
!Services/Data/
|
||||||
*.db
|
*.db
|
||||||
*.sqlite
|
*.sqlite
|
||||||
*.sqlite3
|
*.sqlite3
|
||||||
|
|||||||
141
RelayServer/Endpoints/RtcEndpoints.cs
Normal file
141
RelayServer/Endpoints/RtcEndpoints.cs
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using RelayShared.Rtc;
|
||||||
|
using RelayServer.Services.Rtc;
|
||||||
|
using RelayShared.Services;
|
||||||
|
|
||||||
|
namespace RelayServer.Endpoints;
|
||||||
|
|
||||||
|
public static class RtcEndpoints
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Maps all RTC-related HTTP endpoints used for storing offers and answers,
|
||||||
|
/// writing ICE candidates, checking active calls, and leaving active calls.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="app">The web application to map endpoints onto.</param>
|
||||||
|
public static void MapRtcEndpoints(this WebApplication app)
|
||||||
|
{
|
||||||
|
// Store or update the current SDP offer for a channel call.
|
||||||
|
app.MapPost("/api/rtc/offer", async (RtcOffer request, RtcCallService rtcCallService) =>
|
||||||
|
{
|
||||||
|
await rtcCallService.WriteOfferAsync(request.ChannelId, request.Username, request.SessionDescription);
|
||||||
|
|
||||||
|
RtcNotificationService.BroadcastToChannel(new RtcNotificationMessage
|
||||||
|
{
|
||||||
|
Type = SignalType.OfferUpdated,
|
||||||
|
ChannelId = request.ChannelId,
|
||||||
|
Username = request.Username
|
||||||
|
});
|
||||||
|
|
||||||
|
return Results.Ok();
|
||||||
|
});
|
||||||
|
|
||||||
|
// List all offers.
|
||||||
|
app.MapGet("/api/rtc/offers", async (RtcCallService rtcCallService) =>
|
||||||
|
{
|
||||||
|
return Results.Ok(await rtcCallService.GetOffersAsync());
|
||||||
|
});
|
||||||
|
|
||||||
|
// Return whether the specified channel currently has an active call.
|
||||||
|
app.MapGet("/api/rtc/active/{channelId}", async (string channelId, RtcCallService rtcCallService) =>
|
||||||
|
{
|
||||||
|
return Results.Ok(await rtcCallService.HasActiveCallAsync(channelId));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Return the latest stored SDP offer for the specified channel.
|
||||||
|
app.MapGet("/api/rtc/offers/{channelId}", async (string channelId, RtcCallService rtcCallService) =>
|
||||||
|
{
|
||||||
|
var offer = await rtcCallService.GetOfferAsync(channelId);
|
||||||
|
return offer is null ? Results.NotFound() : Results.Ok(offer);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Store a new SDP answer for the specified channel call.
|
||||||
|
app.MapPost("/api/rtc/answer", async (RtcOffer request, RtcCallService rtcCallService) =>
|
||||||
|
{
|
||||||
|
Console.WriteLine($"RTC answer received for channel {request.ChannelId} from {request.Username}");
|
||||||
|
|
||||||
|
await rtcCallService.WriteAnswerAsync(request.ChannelId, request.SessionDescription);
|
||||||
|
|
||||||
|
Console.WriteLine($"Broadcasting rtc_answer_updated for {request.ChannelId}");
|
||||||
|
|
||||||
|
RtcNotificationService.BroadcastToChannel(new RtcNotificationMessage
|
||||||
|
{
|
||||||
|
Type = SignalType.AnswerUpdated,
|
||||||
|
ChannelId = request.ChannelId
|
||||||
|
});
|
||||||
|
|
||||||
|
return Results.Ok();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Return all answers stored for the specified channel.
|
||||||
|
app.MapGet("/api/rtc/answers/{channelId}", async (string channelId, RtcCallService rtcCallService) =>
|
||||||
|
{
|
||||||
|
return Results.Ok(await rtcCallService.GetAnswersAsync(channelId));
|
||||||
|
});
|
||||||
|
|
||||||
|
app.MapGet("/api/rtc/participants/{channelId}", (string channelId) =>
|
||||||
|
{
|
||||||
|
return Results.Ok(RtcChannelPresenceService.GetUsersInChannel(channelId));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Return the latest answer stored for the specified channel.
|
||||||
|
app.MapGet("/api/rtc/answer/{channelId}", async (string channelId, RtcCallService rtcCallService) =>
|
||||||
|
{
|
||||||
|
var answer = await rtcCallService.GetLatestAnswerAsync(channelId);
|
||||||
|
return answer is null ? Results.NotFound() : Results.Ok(answer);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Store a new ICE candidate for the specified channel call.
|
||||||
|
app.MapPost("/api/rtc/candidate", async (RtcIceCandidate request, RtcCallService rtcCallService) =>
|
||||||
|
{
|
||||||
|
await rtcCallService.WriteIceCandidateAsync(
|
||||||
|
request.ChannelId,
|
||||||
|
request.Username,
|
||||||
|
request.Candidate.candidate,
|
||||||
|
request.Candidate.sdpMid,
|
||||||
|
request.Candidate.sdpMLineIndex
|
||||||
|
);
|
||||||
|
|
||||||
|
RtcNotificationService.BroadcastToChannel(new RtcNotificationMessage
|
||||||
|
{
|
||||||
|
Type = SignalType.CandidateAdded,
|
||||||
|
ChannelId = request.ChannelId,
|
||||||
|
Username = request.Username,
|
||||||
|
Direction = JsonSerializer.Serialize(request.Candidate)
|
||||||
|
});
|
||||||
|
|
||||||
|
return Results.Ok();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Return all ICE candidates stored for the specified channel.
|
||||||
|
app.MapGet("/api/rtc/candidates/{channelId}", async (string channelId, RtcCallService rtcCallService) =>
|
||||||
|
{
|
||||||
|
return Results.Ok(await rtcCallService.GetIceCandidatesAsync(channelId));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Return ICE candidates for the specified channel that belong to other users
|
||||||
|
// and match the requested direction.
|
||||||
|
app.MapGet("/api/rtc/candidates/{channelId}/{username}/{direction}", async (
|
||||||
|
string channelId,
|
||||||
|
string username,
|
||||||
|
string direction,
|
||||||
|
RtcCallService rtcCallService) =>
|
||||||
|
{
|
||||||
|
return Results.Ok(await rtcCallService.GetIceCandidatesForOthersAsync(channelId, username, direction));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Leave the active call for the specified channel.
|
||||||
|
app.MapPost("/api/rtc/leave", async (RtcLeaveRequest request, RtcCallService rtcCallService) =>
|
||||||
|
{
|
||||||
|
await rtcCallService.LeaveCallAsync(request.ChannelId, request.Username);
|
||||||
|
|
||||||
|
RtcNotificationService.BroadcastToChannel(new RtcNotificationMessage
|
||||||
|
{
|
||||||
|
Type = SignalType.CallLeft,
|
||||||
|
ChannelId = request.ChannelId,
|
||||||
|
Username = request.Username
|
||||||
|
});
|
||||||
|
|
||||||
|
return Results.Ok();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
25
RelayServer/Models/Chat/ChannelMessageEdits.cs
Normal file
25
RelayServer/Models/Chat/ChannelMessageEdits.cs
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Surreal record for the `channel_message_edits` table. One row per historical version of
|
||||||
|
/// an edited message — written by HandleEditMessage BEFORE overwriting the live row.
|
||||||
|
///
|
||||||
|
/// Encrypted with the channel AES key (same as ChannelMessages), so HandleGetEditHistory
|
||||||
|
/// can decrypt + re-encrypt per requester.
|
||||||
|
/// </summary>
|
||||||
|
public class ChannelMessageEdits : Record
|
||||||
|
{
|
||||||
|
/// <summary>"channel_messages:abc" — which live message this version belonged to.</summary>
|
||||||
|
public required string MessageId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Base64 AES-GCM ciphertext of the JSON-serialised previous ChatMessageContent.</summary>
|
||||||
|
public required string CipherText { get; set; }
|
||||||
|
|
||||||
|
public required string Nonce { get; set; }
|
||||||
|
public required string Tag { get; set; }
|
||||||
|
|
||||||
|
/// <summary>When this version was the current text (i.e. when it was replaced).</summary>
|
||||||
|
public required DateTime EditedAt { get; set; }
|
||||||
|
}
|
||||||
37
RelayServer/Models/Chat/ChannelMessages.cs
Normal file
37
RelayServer/Models/Chat/ChannelMessages.cs
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Surreal record for the `channel_messages` table. One row per message.
|
||||||
|
///
|
||||||
|
/// Encryption: CipherText/Nonce/Tag use the channel AES key (ChannelDbKey), NOT any user's
|
||||||
|
/// RSA keypair. This means the server can decrypt for history queries; the per-recipient
|
||||||
|
/// RSA wrapping happens at delivery time in DeliverToServerMembers.
|
||||||
|
/// </summary>
|
||||||
|
public class ChannelMessages : Record
|
||||||
|
{
|
||||||
|
/// <summary>"channels:xyz" — which channel this belongs to.</summary>
|
||||||
|
public required string ChannelId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>"users:keeper317" — who wrote it. Lowercased to match CoreClientService's id format.</summary>
|
||||||
|
public required string SenderUserId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Base64 AES-GCM ciphertext of the JSON-serialised ChatMessageContent.</summary>
|
||||||
|
public required string CipherText { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Base64 AES-GCM 96-bit nonce. Different every message.</summary>
|
||||||
|
public required string Nonce { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Base64 AES-GCM 128-bit authentication tag.</summary>
|
||||||
|
public required string Tag { get; set; }
|
||||||
|
|
||||||
|
/// <summary>UTC timestamp of original send. Drives history ordering.</summary>
|
||||||
|
public required DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>UTC timestamp of last edit. Null = never edited. Drives the (edited) bubble footer.</summary>
|
||||||
|
public DateTime? EditedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Soft-delete flag. Tombstones in history responses; bubbles show "deleted" placeholder.</summary>
|
||||||
|
public bool IsDeleted { get; set; }
|
||||||
|
}
|
||||||
40
RelayServer/Models/Chat/Channels.cs
Normal file
40
RelayServer/Models/Chat/Channels.cs
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
using RelayShared.Services;
|
||||||
|
|
||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Surreal record for the `channels` table. One row per channel.
|
||||||
|
///
|
||||||
|
/// Lifecycle: created by HandleCreateChannel (or seeded by ServerBootstrapService at boot).
|
||||||
|
/// Soft-deleted by HandleDeleteChannel (IsDeleted flipped, row stays for audit).
|
||||||
|
/// </summary>
|
||||||
|
public class Channels : Record
|
||||||
|
{
|
||||||
|
/// <summary>Sidebar display name. Lowercased and dash-separated for new channels.</summary>
|
||||||
|
public required string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Creation timestamp. Drives sidebar sort order.</summary>
|
||||||
|
public required DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Drives client rendering and server routing — Text/Voice/File/Forum/Stage.</summary>
|
||||||
|
public ChannelType Type { get; set; } = ChannelType.Text;
|
||||||
|
|
||||||
|
/// <summary>Sidebar category header (e.g. "General"). Empty means default group.</summary>
|
||||||
|
public string Group { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// True for announcement-style channels (#welcome, #files). Non-admins are blocked from
|
||||||
|
/// posting via PermissionService.CanSendMessagesAsync.
|
||||||
|
/// </summary>
|
||||||
|
public bool IsReadOnly { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Soft-delete flag. Filtered out of channel-list builds in BuildChannelListForUser.</summary>
|
||||||
|
public bool IsDeleted { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Surreal record id of a File channel ("channels:xyz"). When set, ChatSocketBehavior's
|
||||||
|
/// MirrorAttachmentIfNeeded auto-copies non-gif attachments into the linked channel.
|
||||||
|
/// </summary>
|
||||||
|
public string? LinkedFileChannelId { get; set; }
|
||||||
|
}
|
||||||
8
RelayServer/Models/Chat/SocketChannelInfo.cs
Normal file
8
RelayServer/Models/Chat/SocketChannelInfo.cs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
public class SocketChannelInfo
|
||||||
|
{
|
||||||
|
public required string ChannelId { get; set; }
|
||||||
|
public required string Name { get; set; }
|
||||||
|
public required DateTime CreatedAt { get; set; }
|
||||||
|
}
|
||||||
26
RelayServer/Models/Crypto/ClientPublicKeys.cs
Normal file
26
RelayServer/Models/Crypto/ClientPublicKeys.cs
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Surreal record for the `client_public_keys` table. Stores the RSA public key each user
|
||||||
|
/// has registered. Written by HandleRegisterKey, read by DeliverToServerMembers and history
|
||||||
|
/// fetches to encrypt outbound messages per recipient.
|
||||||
|
///
|
||||||
|
/// When a client reinstalls and regenerates a keypair, the existing row is updated rather
|
||||||
|
/// than duplicated (ClientKeyService.RegisterOrUpdateKeyAsync).
|
||||||
|
/// </summary>
|
||||||
|
public class ClientPublicKeys : Record
|
||||||
|
{
|
||||||
|
/// <summary>Mixed-case username as the user registered it. Used as the lookup key.</summary>
|
||||||
|
public required string Username { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Base64 SubjectPublicKeyInfo (DER) of the user's RSA public key.</summary>
|
||||||
|
public required string PublicKey { get; set; }
|
||||||
|
|
||||||
|
/// <summary>When the user first registered.</summary>
|
||||||
|
public required DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>When the key was last updated (key rotation, reinstall).</summary>
|
||||||
|
public required DateTime UpdatedAt { get; set; }
|
||||||
|
}
|
||||||
29
RelayServer/Models/Crypto/ServerEncryptionKeys.cs
Normal file
29
RelayServer/Models/Crypto/ServerEncryptionKeys.cs
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Surreal record for the `server_encryption_keys` table. Stores both:
|
||||||
|
/// - The server's RSA keypair (for receiving encrypted client→server payloads).
|
||||||
|
/// - The single AES-256 key used to encrypt channel_messages at rest.
|
||||||
|
///
|
||||||
|
/// Generated once on first boot by ServerBootstrapService. Loaded into static fields on
|
||||||
|
/// ChatSocketBehavior at boot so handlers can use them without a DB round-trip.
|
||||||
|
/// </summary>
|
||||||
|
public class ServerEncryptionKeys : Record
|
||||||
|
{
|
||||||
|
/// <summary>Base64 AES-256 key used by ChannelCryptoService for at-rest message encryption.</summary>
|
||||||
|
public required string KeyBase64 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Base64 SubjectPublicKeyInfo of the server's RSA public key. Sent to clients on GetServerKey.</summary>
|
||||||
|
public required string PublicKey { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Base64 PKCS8 of the server's RSA private key. Never leaves the server.</summary>
|
||||||
|
public required string PrivateKey { get; set; }
|
||||||
|
|
||||||
|
/// <summary>When the keys were generated.</summary>
|
||||||
|
public required DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>When the keys were last rotated. Currently same as CreatedAt — rotation isn't implemented.</summary>
|
||||||
|
public required DateTime UpdatedAt { get; set; }
|
||||||
|
}
|
||||||
25
RelayServer/Models/Server/ChannelPermissions.cs
Normal file
25
RelayServer/Models/Server/ChannelPermissions.cs
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Surreal record for the `channel_permissions` table. Per-(channel, role) override of a
|
||||||
|
/// role's base permissions.
|
||||||
|
///
|
||||||
|
/// Allow and Deny are independent masks (NOT a tri-state). Deny wins over Allow when both
|
||||||
|
/// have the same flag set. Bits not set in either fall through to the role's base permissions.
|
||||||
|
/// </summary>
|
||||||
|
public class ChannelPermissions : Record
|
||||||
|
{
|
||||||
|
/// <summary>"channels:xyz" — which channel this override applies in.</summary>
|
||||||
|
public required string ChannelId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>"roles:abc" — which role this override applies to.</summary>
|
||||||
|
public required string RoleId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Permissions explicitly granted here (overrides "role doesn't have it" for this channel).</summary>
|
||||||
|
public PermissionFlags Allow { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Permissions explicitly denied here. Wins over Allow.</summary>
|
||||||
|
public PermissionFlags Deny { get; set; }
|
||||||
|
}
|
||||||
50
RelayServer/Models/Server/Roles.cs
Normal file
50
RelayServer/Models/Server/Roles.cs
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The permission bitfield. The whole permission model is just:
|
||||||
|
///
|
||||||
|
/// ServerMembers.IsOwner = true → unconditional Administrator
|
||||||
|
/// roles.Permissions has Administrator flag → unconditional everything
|
||||||
|
/// channel_permissions.Deny has a specific flag → that permission denied here
|
||||||
|
/// channel_permissions.Allow has a specific flag → that permission allowed here
|
||||||
|
/// roles.Permissions has the flag → fallback (channel-independent)
|
||||||
|
///
|
||||||
|
/// PermissionService.HasPermissionAsync walks that ladder in order. See that class for the
|
||||||
|
/// authoritative implementation.
|
||||||
|
/// </summary>
|
||||||
|
[Flags]
|
||||||
|
public enum PermissionFlags
|
||||||
|
{
|
||||||
|
None = 0,
|
||||||
|
ReadMessages = 1 << 0,
|
||||||
|
SendMessages = 1 << 1,
|
||||||
|
ManageMessages = 1 << 2, // Edit / delete others' messages
|
||||||
|
ManageChannels = 1 << 3, // Create channels (umbrella manage permission)
|
||||||
|
ManageMembers = 1 << 4, // Kick / ban members
|
||||||
|
Administrator = 1 << 5, // All permissions, bypasses channel overrides
|
||||||
|
ViewChannel = 1 << 6, // "Visibility" — can see the channel at all
|
||||||
|
Speak = 1 << 7, // Can transmit in a voice channel
|
||||||
|
EditChannel = 1 << 8, // Rename / reconfigure a channel
|
||||||
|
DeleteChannel = 1 << 9 // Delete a channel
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Surreal record for the `roles` table. Defines a named permission bundle that can be
|
||||||
|
/// assigned to users via UserRoles.
|
||||||
|
/// </summary>
|
||||||
|
public class Roles : Record
|
||||||
|
{
|
||||||
|
/// <summary>Display name ("Admin", "Moderator", "Member").</summary>
|
||||||
|
public required string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Base permission bitfield. Channel-level overrides in ChannelPermissions can add or remove.</summary>
|
||||||
|
public required PermissionFlags Permissions { get; set; }
|
||||||
|
|
||||||
|
/// <summary>When the role was seeded.</summary>
|
||||||
|
public required DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Tie-breaker for future multi-role-per-user scenarios. Lower = higher priority. Not used by the current ladder.</summary>
|
||||||
|
public int Priority { get; set; }
|
||||||
|
}
|
||||||
23
RelayServer/Models/Server/ServerMembers.cs
Normal file
23
RelayServer/Models/Server/ServerMembers.cs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Surreal record for the `server_members` table. Membership list.
|
||||||
|
/// Drives DeliverToServerMembers (the fan-out target list for every chat message) and the
|
||||||
|
/// authoritative ownership flag for PermissionService.
|
||||||
|
/// </summary>
|
||||||
|
public class ServerMembers : Record
|
||||||
|
{
|
||||||
|
/// <summary>"users:keeper317" — references the Core users table by name convention.</summary>
|
||||||
|
public required string UserId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>When the user was added to this server.</summary>
|
||||||
|
public required DateTime JoinedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Authoritative owner flag. Owner gets unconditional Administrator via
|
||||||
|
/// PermissionService.IsServerOwnerAsync, independent of role assignments.
|
||||||
|
/// </summary>
|
||||||
|
public bool IsOwner { get; set; }
|
||||||
|
}
|
||||||
19
RelayServer/Models/Server/Servers.cs
Normal file
19
RelayServer/Models/Server/Servers.cs
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Surreal record for the `servers` table. Currently single-row (one server per deployment),
|
||||||
|
/// but the schema supports multi-server in the future.
|
||||||
|
/// </summary>
|
||||||
|
public class Servers : Record
|
||||||
|
{
|
||||||
|
/// <summary>Display name (currently "Test Server" from bootstrap).</summary>
|
||||||
|
public required string Name { get; set; }
|
||||||
|
|
||||||
|
/// <summary>"users:keeper317" — the owner. Mirrored as IsOwner=true on the matching ServerMembers row.</summary>
|
||||||
|
public required string OwnerUserId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Server creation timestamp.</summary>
|
||||||
|
public required DateTime CreatedAt { get; set; }
|
||||||
|
}
|
||||||
22
RelayServer/Models/Server/UserRoles.cs
Normal file
22
RelayServer/Models/Server/UserRoles.cs
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Surreal record for the `user_roles` table. Join table linking users to roles.
|
||||||
|
///
|
||||||
|
/// Invariant: ServerBootstrapService.SetUserRoleAsync guarantees exactly one row per user.
|
||||||
|
/// Multi-role-per-user isn't currently supported by the permission ladder — adding it would
|
||||||
|
/// just be a matter of removing the bootstrap's "delete stale rows" step.
|
||||||
|
/// </summary>
|
||||||
|
public class UserRoles : Record
|
||||||
|
{
|
||||||
|
/// <summary>"users:keeper317" — the assignee.</summary>
|
||||||
|
public required string UserId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>"roles:abc" — the role being granted.</summary>
|
||||||
|
public required string RoleId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>When the assignment was made.</summary>
|
||||||
|
public required DateTime AssignedAt { get; set; }
|
||||||
|
}
|
||||||
@@ -1 +1,72 @@
|
|||||||
Console.WriteLine("Hello, World!");
|
// =============================================================================
|
||||||
|
// RelayServer entrypoint.
|
||||||
|
//
|
||||||
|
// Boot sequence:
|
||||||
|
// 1. Connect to SurrealDB (port 8000) via SurrealService.
|
||||||
|
// 2. Wire static singletons onto ChatSocketBehavior (it's a WebSocketSharp
|
||||||
|
// WebSocketBehavior, so DI is impossible — fields are static).
|
||||||
|
// 3. Run ServerBootstrapService.InitializeAsync — seeds users, server, members,
|
||||||
|
// channels (welcome, general, files, voice-general), roles, role assignments,
|
||||||
|
// channel permission overrides, and encryption keys. Idempotent across reboots.
|
||||||
|
// 4. Start two listeners in parallel:
|
||||||
|
// - HTTP API on 127.0.0.1:5000 (RtcEndpoints — REST for RTC call orchestration)
|
||||||
|
// - WebSocket server on 127.0.0.1:5001 (ChatSocketBehavior — the chat/RTC-signal pipe)
|
||||||
|
// 5. Block on ConsoleCommandService.ShutdownTokenSource for graceful shutdown.
|
||||||
|
//
|
||||||
|
// Why two listeners? The HTTP API is used for one-shot RPC-style calls (e.g. "fetch
|
||||||
|
// the participant list for this voice channel"). The WebSocket is the persistent
|
||||||
|
// duplex pipe used for chat, typing, presence, encrypted RTC signalling.
|
||||||
|
// =============================================================================
|
||||||
|
|
||||||
|
using RelayServer.Endpoints;
|
||||||
|
using RelayServer.Services.Chat;
|
||||||
|
using RelayServer.Services.Core;
|
||||||
|
using RelayServer.Services.Data;
|
||||||
|
using RelayServer.Services.Rtc;
|
||||||
|
using RelayShared.Rtc;
|
||||||
|
using RelayShared.Services;
|
||||||
|
using WebSocketSharp.Server;
|
||||||
|
|
||||||
|
var surrealService = new SurrealService();
|
||||||
|
var coreClient = new CoreClientService();
|
||||||
|
var cryptoService = new ChannelCryptoService();
|
||||||
|
|
||||||
|
await using var db = await surrealService.ConnectAsync();
|
||||||
|
|
||||||
|
ChatSocketBehavior.ClientKeyService = new ClientKeyService(db);
|
||||||
|
ChatSocketBehavior.PermissionService = new PermissionService(db);
|
||||||
|
ChatSocketBehavior.Db = db;
|
||||||
|
ChatSocketBehavior.ChannelCryptoService = cryptoService;
|
||||||
|
|
||||||
|
var bootstrapService = new ServerBootstrapService(db, coreClient, cryptoService);
|
||||||
|
await bootstrapService.InitializeAsync();
|
||||||
|
|
||||||
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.WebHost.UseUrls("http://127.0.0.1:5000/");
|
||||||
|
// builder.WebHost.UseUrls("http://192.168.1.92:5000/");
|
||||||
|
|
||||||
|
builder.Services.AddSingleton(db);
|
||||||
|
builder.Services.AddScoped<RtcCallService>();
|
||||||
|
|
||||||
|
var app = builder.Build();
|
||||||
|
|
||||||
|
app.MapGet("/", () => "Server Running!");
|
||||||
|
app.MapRtcEndpoints();
|
||||||
|
|
||||||
|
var wssv = new WebSocketServer("ws://127.0.0.1:5001");
|
||||||
|
// var wssv = new WebSocketServer("ws://192.168.1.92:5001");
|
||||||
|
wssv.AddWebSocketService<ChatSocketBehavior>("/");
|
||||||
|
RtcNotificationService.Server = wssv;
|
||||||
|
|
||||||
|
wssv.Start();
|
||||||
|
Console.WriteLine("WebSocket server started");
|
||||||
|
|
||||||
|
await app.StartAsync();
|
||||||
|
Console.WriteLine("HTTP API started");
|
||||||
|
|
||||||
|
ConsoleCommandService.Start();
|
||||||
|
await Task.Delay(Timeout.Infinite, ConsoleCommandService.ShutdownTokenSource.Token);
|
||||||
|
|
||||||
|
wssv.Stop();
|
||||||
|
await app.StopAsync();
|
||||||
|
return;
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>Exe</OutputType>
|
||||||
@@ -7,4 +7,14 @@
|
|||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.2.9" />
|
||||||
|
<PackageReference Include="SurrealDb.Net" Version="0.9.0" />
|
||||||
|
<PackageReference Include="WebSocketSharp" Version="1.0.3-rc11" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\RelayShared\RelayShared.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
63
RelayServer/Services/Chat/ChannelCryptoService.cs
Normal file
63
RelayServer/Services/Chat/ChannelCryptoService.cs
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace RelayServer.Services.Chat;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// AES-GCM-256 only (no RSA). Used exclusively for "at-rest" encryption of channel messages
|
||||||
|
/// in the SurrealDB channel_messages table.
|
||||||
|
///
|
||||||
|
/// Why a separate service from E2EeHelper:
|
||||||
|
/// - E2EeHelper is for *transit* between a specific sender and a specific recipient — it
|
||||||
|
/// wraps an ephemeral AES key with the recipient's RSA public key.
|
||||||
|
/// - ChannelCryptoService is for *storage* — the server is both the encryptor and the
|
||||||
|
/// decryptor, and it stores the symmetric channel key in server_encryption_keys.KeyBase64.
|
||||||
|
/// There's no recipient to wrap for.
|
||||||
|
///
|
||||||
|
/// Server flow for a chat message:
|
||||||
|
/// incoming SocketEncryptedMessage (encrypted with server's RSA public key, by client)
|
||||||
|
/// → E2EeHelper.DecryptForRecipient(serverPrivateKey) → plaintext
|
||||||
|
/// → ChannelCryptoService.Encrypt(channelDbKey) → stored ciphertext
|
||||||
|
/// → … later, on history fetch …
|
||||||
|
/// → ChannelCryptoService.Decrypt(channelDbKey) → plaintext
|
||||||
|
/// → E2EeHelper.EncryptForRecipient(clientPublicKey) → delivered ciphertext
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ChannelCryptoService
|
||||||
|
{
|
||||||
|
public string GenerateKey()
|
||||||
|
{
|
||||||
|
return Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
|
||||||
|
}
|
||||||
|
|
||||||
|
public (string cipherText, string nonce, string tag) Encrypt(string plainText, string keyBase64)
|
||||||
|
{
|
||||||
|
var key = Convert.FromBase64String(keyBase64);
|
||||||
|
var nonce = RandomNumberGenerator.GetBytes(12);
|
||||||
|
var plainBytes = Encoding.UTF8.GetBytes(plainText);
|
||||||
|
var cipherBytes = new byte[plainBytes.Length];
|
||||||
|
var tag = new byte[16];
|
||||||
|
|
||||||
|
using var aes = new AesGcm(key, 16);
|
||||||
|
aes.Encrypt(nonce, plainBytes, cipherBytes, tag);
|
||||||
|
|
||||||
|
return (
|
||||||
|
Convert.ToBase64String(cipherBytes),
|
||||||
|
Convert.ToBase64String(nonce),
|
||||||
|
Convert.ToBase64String(tag)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Decrypt(string cipherTextBase64, string nonceBase64, string tagBase64, string keyBase64)
|
||||||
|
{
|
||||||
|
var key = Convert.FromBase64String(keyBase64);
|
||||||
|
var nonce = Convert.FromBase64String(nonceBase64);
|
||||||
|
var tag = Convert.FromBase64String(tagBase64);
|
||||||
|
var cipherBytes = Convert.FromBase64String(cipherTextBase64);
|
||||||
|
var plainBytes = new byte[cipherBytes.Length];
|
||||||
|
|
||||||
|
using var aes = new AesGcm(key, 16);
|
||||||
|
aes.Decrypt(nonce, cipherBytes, tag, plainBytes);
|
||||||
|
|
||||||
|
return Encoding.UTF8.GetString(plainBytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
915
RelayServer/Services/Chat/ChatSocketBehavior.cs
Normal file
915
RelayServer/Services/Chat/ChatSocketBehavior.cs
Normal file
@@ -0,0 +1,915 @@
|
|||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Text.Json;
|
||||||
|
using RelayServer.Models;
|
||||||
|
using RelayServer.Services.Crypto;
|
||||||
|
using RelayServer.Services.Data;
|
||||||
|
using RelayServer.Services.Rtc;
|
||||||
|
using WebSocketSharp;
|
||||||
|
using WebSocketSharp.Server;
|
||||||
|
using ErrorEventArgs = WebSocketSharp.ErrorEventArgs;
|
||||||
|
using RelayShared.Services;
|
||||||
|
|
||||||
|
namespace RelayServer.Services.Chat;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The server-side WebSocket endpoint. Every client connection creates one instance of this
|
||||||
|
/// class. WebSocketSharp owns the lifecycle: it constructs the behavior, calls OnMessage for
|
||||||
|
/// each incoming frame, and calls OnClose when the connection drops.
|
||||||
|
///
|
||||||
|
/// MESSAGE FLOW (data plane — chat message):
|
||||||
|
/// 1. Client sends a SocketEncryptedMessage with SignalType.ClientEncryptedChat.
|
||||||
|
/// Payload is JSON-serialised ChatMessageContent, encrypted with the server's public key.
|
||||||
|
/// 2. OnMessage parses the JSON, identifies Type, routes to HandleEncryptedChatMessage.
|
||||||
|
/// 3. Permission check via PermissionService.CanSendMessagesAsync.
|
||||||
|
/// 4. Decrypt with ServerPrivateKey → get plaintext JSON.
|
||||||
|
/// 5. Re-encrypt with ChannelDbKey (AES-GCM only, no RSA) → store in channel_messages table.
|
||||||
|
/// 6. For each connected server member: re-encrypt with their client public key, deliver
|
||||||
|
/// via Sessions.SendTo to every one of their active sessions (multi-device).
|
||||||
|
/// 7. If the origin channel has LinkedFileChannelId set, MirrorAttachmentIfNeeded also
|
||||||
|
/// stores+delivers a trimmed copy into the linked File channel.
|
||||||
|
///
|
||||||
|
/// MESSAGE FLOW (control plane — e.g. CreateChannel):
|
||||||
|
/// 1. Client sends a WsControlMessage with Action=CreateChannel.
|
||||||
|
/// 2. OnMessage sees the "Action" JSON property, routes via DispatchControl.
|
||||||
|
/// 3. Permission check, DB write, then BroadcastChannelList rebuilds the channel list per
|
||||||
|
/// user (because CanPost/CanManage are computed per-user) and pushes it to everyone.
|
||||||
|
///
|
||||||
|
/// STATE STORES used here:
|
||||||
|
/// - ConnectedClientService: session ↔ username mapping (in-memory, multi-device aware).
|
||||||
|
/// Populated by HandleRegisterKey, cleared by OnClose.
|
||||||
|
/// - RtcChannelPresenceService: session ↔ voice channel mapping. Populated by RtcJoin,
|
||||||
|
/// cleared by RtcLeave / OnClose.
|
||||||
|
/// - SurrealDB tables: channel_messages, channels, server_members, roles, user_roles,
|
||||||
|
/// channel_permissions, client_public_keys, server_encryption_keys, channel_message_edits.
|
||||||
|
///
|
||||||
|
/// CRITICAL invariant: this class is constructed by WebSocketSharp and has no constructor
|
||||||
|
/// hook for DI, so ALL services are static (set once by Program.cs at boot).
|
||||||
|
/// </summary>
|
||||||
|
public class ChatSocketBehavior : WebSocketBehavior
|
||||||
|
{
|
||||||
|
/// <summary>Reads/writes the client_public_keys table. Wired by Program.cs at boot.</summary>
|
||||||
|
public static ClientKeyService? ClientKeyService { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The permission ladder evaluator. Wired by Program.cs at boot.</summary>
|
||||||
|
public static PermissionService? PermissionService { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Base64 RSA public key — clients use this to encrypt outbound payloads to the server.</summary>
|
||||||
|
public static string? ServerPublicKey { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Base64 RSA private key — used to decrypt inbound payloads. Never leaves the server.</summary>
|
||||||
|
public static string? ServerPrivateKey { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Base64 AES-256 key for at-rest encryption of channel_messages.CipherText rows.</summary>
|
||||||
|
public static string? ChannelDbKey { get; set; }
|
||||||
|
|
||||||
|
/// <summary>AES-GCM-only encryption for stored messages. Wired by Program.cs at boot.</summary>
|
||||||
|
public static ChannelCryptoService? ChannelCryptoService { get; set; }
|
||||||
|
|
||||||
|
/// <summary>The SurrealDB connection. Wired by Program.cs at boot.</summary>
|
||||||
|
public static SurrealDb.Net.SurrealDbClient? Db { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// WebSocketSharp callback fired for every incoming text frame. Peeks the JSON to identify
|
||||||
|
/// "Action" (control-plane) vs "Type" (data-plane), then routes to the right handler.
|
||||||
|
/// All exceptions are caught and logged — they MUST NOT propagate or WebSocketSharp will
|
||||||
|
/// drop the connection.
|
||||||
|
/// </summary>
|
||||||
|
protected override void OnMessage(MessageEventArgs e)
|
||||||
|
{
|
||||||
|
var msg = e.Data;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var doc = JsonDocument.Parse(msg);
|
||||||
|
var root = doc.RootElement;
|
||||||
|
|
||||||
|
if (root.TryGetProperty("Action", out var actionProp))
|
||||||
|
{
|
||||||
|
var action = (WsAction)actionProp.GetInt32();
|
||||||
|
var control = JsonSerializer.Deserialize<WsControlMessage>(msg)!;
|
||||||
|
DispatchControl(action, control);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (root.TryGetProperty("Type", out var typeProp))
|
||||||
|
{
|
||||||
|
var type = (SignalType)typeProp.GetInt32();
|
||||||
|
switch (type)
|
||||||
|
{
|
||||||
|
case SignalType.EncryptedSignal: HandleEncryptedRtcSignal(msg); return;
|
||||||
|
case SignalType.ClientEncryptedChat: HandleEncryptedChatMessage(msg); return;
|
||||||
|
case SignalType.ClientEditMessage: HandleEditMessage(msg); return;
|
||||||
|
case SignalType.ClientDeleteMessage: HandleDeleteMessage(msg); return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Console.WriteLine($"Unrecognised WS message session={ID}: {msg[..Math.Min(120, msg.Length)]}");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"WS message error session={ID}: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Switches on WsAction to the matching Handle* method. Pure routing — no I/O.</summary>
|
||||||
|
private void DispatchControl(WsAction action, WsControlMessage c)
|
||||||
|
{
|
||||||
|
switch (action)
|
||||||
|
{
|
||||||
|
case WsAction.Authenticate: HandleAuthenticate(c); break;
|
||||||
|
case WsAction.RegisterKey: HandleRegisterKey(c); break;
|
||||||
|
case WsAction.GetServerKey: HandleGetServerKey(); break;
|
||||||
|
case WsAction.GetChannels: HandleGetChannels(); break;
|
||||||
|
case WsAction.GetHistory: HandleGetHistory(c); break;
|
||||||
|
case WsAction.RtcJoin: HandleRtcJoinChannel(c); break;
|
||||||
|
case WsAction.RtcLeave: HandleRtcLeaveChannel(c); break;
|
||||||
|
case WsAction.SendTyping: HandleTyping(c); break;
|
||||||
|
case WsAction.GetEditHistory: HandleGetEditHistory(c); break;
|
||||||
|
case WsAction.CreateChannel: HandleCreateChannel(c); break;
|
||||||
|
case WsAction.DeleteChannel: HandleDeleteChannel(c); break;
|
||||||
|
default: Console.WriteLine($"Unknown WsAction {action} session={ID}"); break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Verifies a Core-issued user token against the Core service. The HTTP call is wrapped in
|
||||||
|
/// try/catch so that a Core outage doesn't drop the chat session — we still ack with
|
||||||
|
/// WsEvent.Authenticated so the rest of the boot handshake can proceed.
|
||||||
|
///
|
||||||
|
/// NOTE async void here is unavoidable (it's an event handler) but every exception path
|
||||||
|
/// must be caught locally or WebSocketSharp will tear down the session.
|
||||||
|
/// </summary>
|
||||||
|
private async void HandleAuthenticate(WsControlMessage c)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(c.Username) || string.IsNullOrWhiteSpace(c.Token))
|
||||||
|
{
|
||||||
|
Console.WriteLine("Invalid Authenticate payload.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var core = new HttpClient { BaseAddress = new Uri("http://127.0.0.1:1337") };
|
||||||
|
core.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||||
|
core.DefaultRequestHeaders.Add("User-Agent", "RelayServer");
|
||||||
|
|
||||||
|
var resp = await core.PostAsJsonAsync("/server/verify/user",
|
||||||
|
new AuthUserVerify { Username = c.Username, Token = c.Token });
|
||||||
|
|
||||||
|
Console.WriteLine($"Auth [{c.Username}]: {await resp.Content.ReadAsStringAsync()}");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"Auth failed for {c.Username}: {ex.Message}");
|
||||||
|
}
|
||||||
|
|
||||||
|
Send(JsonSerializer.Serialize(new WsEventMessage { Event = WsEvent.Authenticated, Detail = c.Username }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Stores or updates the client's RSA public key in client_public_keys, then registers the
|
||||||
|
/// (sessionId, username) mapping in ConnectedClientService. After this fires the server can
|
||||||
|
/// route encrypted chat messages to this user's connected devices.
|
||||||
|
/// </summary>
|
||||||
|
private void HandleRegisterKey(WsControlMessage c)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(c.Username) || string.IsNullOrWhiteSpace(c.PublicKey))
|
||||||
|
{
|
||||||
|
Console.WriteLine("Invalid RegisterKey payload.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ClientKeyService is null) { Console.WriteLine("ClientKeyService null."); return; }
|
||||||
|
|
||||||
|
RegisterOrUpdateClientKeySync(c.Username, c.PublicKey);
|
||||||
|
ConnectedClientService.Register(ID, c.Username);
|
||||||
|
|
||||||
|
Console.WriteLine($"Key registered: {c.Username} (session={ID})");
|
||||||
|
Send(JsonSerializer.Serialize(new WsEventMessage { Event = WsEvent.KeyRegistered, Detail = c.Username }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sends the server's public RSA key. Called once per session right after RegisterKey.</summary>
|
||||||
|
private void HandleGetServerKey()
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(ServerPublicKey)) { Console.WriteLine("Server public key not initialised."); return; }
|
||||||
|
Send(JsonSerializer.Serialize(new ServerPublicKeyMessage { Type = SignalType.ServerPublicKey, PublicKey = ServerPublicKey }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sends a channel list with CanPost/CanManage/visibility resolved for this specific user.
|
||||||
|
/// The username is looked up by session ID so the client never has to spoof it.
|
||||||
|
/// </summary>
|
||||||
|
private void HandleGetChannels()
|
||||||
|
{
|
||||||
|
if (Db is null) { Console.WriteLine("Db null."); return; }
|
||||||
|
|
||||||
|
// Resolve the requesting user so we can compute per-user CanPost for each channel.
|
||||||
|
var username = ConnectedClientService.GetUsernameForSession(ID) ?? string.Empty;
|
||||||
|
|
||||||
|
var channels = BuildChannelListForUser(username);
|
||||||
|
Send(JsonSerializer.Serialize(new SocketChannelList { Type = SignalType.ChannelList, Channels = channels }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Streams the channel's full message history back to the requester. Each message is:
|
||||||
|
/// 1. Decrypted from the channel DB key (ChannelCryptoService.Decrypt).
|
||||||
|
/// 2. Re-encrypted with the requester's public key (E2EeHelper.EncryptForRecipient).
|
||||||
|
/// 3. Sent as an individual SocketEncryptedMessage frame.
|
||||||
|
/// Deleted messages are sent as tombstones (IsDeleted=true, no ciphertext) so the client
|
||||||
|
/// can render a placeholder without trying to decrypt.
|
||||||
|
/// </summary>
|
||||||
|
private void HandleGetHistory(WsControlMessage c)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(c.Username) || string.IsNullOrWhiteSpace(c.ChannelId))
|
||||||
|
{
|
||||||
|
Console.WriteLine("Invalid GetHistory payload.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!EnsureCoreReady() || ChannelCryptoService is null || string.IsNullOrWhiteSpace(ChannelDbKey)) return;
|
||||||
|
|
||||||
|
var targetClient = GetClientPublicKeyByUsernameSync(c.Username);
|
||||||
|
if (targetClient is null) { Console.WriteLine($"No public key for history user {c.Username}"); return; }
|
||||||
|
|
||||||
|
var messages = GetChannelMessagesSync()
|
||||||
|
.Where(m => m.ChannelId == c.ChannelId)
|
||||||
|
.OrderBy(m => m.CreatedAt)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
Console.WriteLine($"Sending {messages.Count} history messages to {c.Username}");
|
||||||
|
|
||||||
|
foreach (var dbMsg in messages)
|
||||||
|
{
|
||||||
|
var msgId = GetRecordId(dbMsg.Id);
|
||||||
|
|
||||||
|
if (dbMsg.IsDeleted)
|
||||||
|
{
|
||||||
|
Send(JsonSerializer.Serialize(new SocketEncryptedMessage
|
||||||
|
{
|
||||||
|
Type = SignalType.EncryptedChat, MessageId = msgId,
|
||||||
|
SenderUsername = ExtractUsernameFromUserId(dbMsg.SenderUserId),
|
||||||
|
RecipientUsername = c.Username, ChannelId = c.ChannelId, IsDeleted = true
|
||||||
|
}));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
string plainText;
|
||||||
|
try { plainText = ChannelCryptoService.Decrypt(dbMsg.CipherText, dbMsg.Nonce, dbMsg.Tag, ChannelDbKey); }
|
||||||
|
catch (Exception ex) { Console.WriteLine($"History decrypt failed {dbMsg.Id}: {ex.Message}"); continue; }
|
||||||
|
|
||||||
|
var encrypted = E2EeHelper.EncryptForRecipient(plainText, targetClient.PublicKey);
|
||||||
|
Send(JsonSerializer.Serialize(new SocketEncryptedMessage
|
||||||
|
{
|
||||||
|
Type = SignalType.EncryptedChat, MessageId = msgId,
|
||||||
|
SenderUsername = ExtractUsernameFromUserId(dbMsg.SenderUserId),
|
||||||
|
RecipientUsername = c.Username, ChannelId = c.ChannelId,
|
||||||
|
CipherText = encrypted.CipherText, Nonce = encrypted.Nonce,
|
||||||
|
Tag = encrypted.Tag, EncryptedKey = encrypted.EncryptedKey,
|
||||||
|
IsEdited = dbMsg.EditedAt.HasValue
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Marks the session as present in a voice channel. Gated by CanSpeakAsync — if the user's
|
||||||
|
/// role is denied Speak here we reject with WsEvent.Error and refuse to register presence.
|
||||||
|
/// </summary>
|
||||||
|
private void HandleRtcJoinChannel(WsControlMessage c)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(c.Username) || string.IsNullOrWhiteSpace(c.ChannelId))
|
||||||
|
{
|
||||||
|
Console.WriteLine("Invalid RtcJoin payload.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (PermissionService is not null &&
|
||||||
|
!PermissionService.CanSpeakAsync(c.Username, c.ChannelId).GetAwaiter().GetResult())
|
||||||
|
{
|
||||||
|
Console.WriteLine($"RTC join denied (no Speak): user={c.Username}, channel={c.ChannelId}");
|
||||||
|
Send(JsonSerializer.Serialize(new WsEventMessage { Event = WsEvent.Error, Detail = "You don't have permission to speak in this channel." }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
RtcChannelPresenceService.SetUser(ID, c.Username);
|
||||||
|
RtcChannelPresenceService.JoinChannel(ID, c.ChannelId);
|
||||||
|
Console.WriteLine($"RTC join: session={ID}, user={c.Username}, channel={c.ChannelId}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Clears the session's voice-channel presence. Idempotent — safe to call when not in a channel.</summary>
|
||||||
|
private void HandleRtcLeaveChannel(WsControlMessage c)
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(c.ChannelId) && RtcChannelPresenceService.IsInChannel(ID, c.ChannelId))
|
||||||
|
RtcChannelPresenceService.LeaveChannel(ID);
|
||||||
|
Console.WriteLine($"RTC leave: session={ID}, user={c.Username}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Broadcasts "{Username} is typing…" to every connected server member EXCEPT the sender.
|
||||||
|
/// Sender's username comes from ConnectedClientService (not the message payload) so a
|
||||||
|
/// malicious client can't impersonate someone else's typing.
|
||||||
|
/// </summary>
|
||||||
|
private void HandleTyping(WsControlMessage c)
|
||||||
|
{
|
||||||
|
var senderUsername = ConnectedClientService.GetUsernameForSession(ID);
|
||||||
|
if (string.IsNullOrWhiteSpace(senderUsername) || string.IsNullOrWhiteSpace(c.ChannelId)) return;
|
||||||
|
|
||||||
|
var json = JsonSerializer.Serialize(new SocketTypingEvent
|
||||||
|
{
|
||||||
|
Type = SignalType.TypingIndicator,
|
||||||
|
Username = senderUsername,
|
||||||
|
ChannelId = c.ChannelId
|
||||||
|
});
|
||||||
|
|
||||||
|
foreach (var member in GetServerMembersSync())
|
||||||
|
{
|
||||||
|
var rawUsername = ExtractUsernameFromUserId(member.UserId);
|
||||||
|
if (string.Equals(rawUsername, senderUsername, StringComparison.OrdinalIgnoreCase)) continue;
|
||||||
|
|
||||||
|
foreach (var sid in ConnectedClientService.GetSessionsForUser(rawUsername))
|
||||||
|
Sessions.SendTo(json, sid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Streams every prior version of a message back to the requester. Each entry is decrypted
|
||||||
|
/// from the channel key then re-encrypted for the requester's public key. Drives the
|
||||||
|
/// "(edited)" tap-popup on the client.
|
||||||
|
/// </summary>
|
||||||
|
private void HandleGetEditHistory(WsControlMessage c)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(c.MessageId) || string.IsNullOrWhiteSpace(c.Username)) return;
|
||||||
|
if (!EnsureCoreReady() || ChannelCryptoService is null || string.IsNullOrWhiteSpace(ChannelDbKey)) return;
|
||||||
|
|
||||||
|
var targetClient = GetClientPublicKeyByUsernameSync(c.Username);
|
||||||
|
if (targetClient is null) return;
|
||||||
|
|
||||||
|
var edits = GetChannelMessageEditsSync(c.MessageId)
|
||||||
|
.OrderBy(e => e.EditedAt)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
var entries = new List<SocketEditHistoryEntry>();
|
||||||
|
|
||||||
|
foreach (var edit in edits)
|
||||||
|
{
|
||||||
|
string plainText;
|
||||||
|
try { plainText = ChannelCryptoService.Decrypt(edit.CipherText, edit.Nonce, edit.Tag, ChannelDbKey); }
|
||||||
|
catch (Exception ex) { Console.WriteLine($"Edit history decrypt failed: {ex.Message}"); continue; }
|
||||||
|
|
||||||
|
var encrypted = E2EeHelper.EncryptForRecipient(plainText, targetClient.PublicKey);
|
||||||
|
entries.Add(new SocketEditHistoryEntry
|
||||||
|
{
|
||||||
|
CipherText = encrypted.CipherText,
|
||||||
|
Nonce = encrypted.Nonce,
|
||||||
|
Tag = encrypted.Tag,
|
||||||
|
EncryptedKey = encrypted.EncryptedKey,
|
||||||
|
EditedAt = edit.EditedAt
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Send(JsonSerializer.Serialize(new SocketEditHistoryResponse
|
||||||
|
{
|
||||||
|
Type = SignalType.EditHistory,
|
||||||
|
MessageId = c.MessageId,
|
||||||
|
Entries = entries
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Permission-gated channel creation. On success, broadcasts the new channel list to every
|
||||||
|
/// connected member (computed per-user since CanPost/CanManage depend on the recipient).
|
||||||
|
/// </summary>
|
||||||
|
private void HandleCreateChannel(WsControlMessage c)
|
||||||
|
{
|
||||||
|
var username = ConnectedClientService.GetUsernameForSession(ID);
|
||||||
|
if (string.IsNullOrWhiteSpace(username)) return;
|
||||||
|
|
||||||
|
if (PermissionService is null || !PermissionService.CanManageChannelsAsync(username).GetAwaiter().GetResult())
|
||||||
|
{
|
||||||
|
Console.WriteLine($"CreateChannel denied for {username}: insufficient permissions.");
|
||||||
|
Send(JsonSerializer.Serialize(new WsEventMessage { Event = WsEvent.Error, Detail = "Permission denied." }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(c.ChannelName))
|
||||||
|
{
|
||||||
|
Send(JsonSerializer.Serialize(new WsEventMessage { Event = WsEvent.Error, Detail = "Channel name is required." }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var type = (ChannelType)c.ChannelType;
|
||||||
|
|
||||||
|
Task.Run(async () => await Db!.Create("channels", new Channels
|
||||||
|
{
|
||||||
|
Name = c.ChannelName,
|
||||||
|
Type = type,
|
||||||
|
Group = c.ChannelGroup ?? string.Empty,
|
||||||
|
CreatedAt = DateTime.UtcNow
|
||||||
|
})).GetAwaiter().GetResult();
|
||||||
|
|
||||||
|
Console.WriteLine($"Channel created: {c.ChannelName} ({type}) by {username}");
|
||||||
|
BroadcastChannelList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Permission-gated soft-delete (sets IsDeleted on the row, doesn't actually remove it).
|
||||||
|
/// Broadcasts a fresh channel list after — clients drop the channel from their sidebar.
|
||||||
|
/// </summary>
|
||||||
|
private void HandleDeleteChannel(WsControlMessage c)
|
||||||
|
{
|
||||||
|
var username = ConnectedClientService.GetUsernameForSession(ID);
|
||||||
|
if (string.IsNullOrWhiteSpace(username)) return;
|
||||||
|
|
||||||
|
if (PermissionService is null || !PermissionService.CanDeleteChannelAsync(username).GetAwaiter().GetResult())
|
||||||
|
{
|
||||||
|
Send(JsonSerializer.Serialize(new WsEventMessage { Event = WsEvent.Error, Detail = "Permission denied." }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(c.ChannelId)) return;
|
||||||
|
|
||||||
|
var all = GetChannelsSync();
|
||||||
|
var target = all.FirstOrDefault(ch => GetRecordId(ch.Id) == c.ChannelId);
|
||||||
|
if (target is null) return;
|
||||||
|
|
||||||
|
target.IsDeleted = true;
|
||||||
|
Task.Run(async () => await Db!.Merge<Channels, Channels>(target))
|
||||||
|
.GetAwaiter().GetResult();
|
||||||
|
|
||||||
|
Console.WriteLine($"Channel deleted: {target.Name} by {username}");
|
||||||
|
BroadcastChannelList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Relays an encrypted WebRTC SDP/ICE signal to every other session in the same voice
|
||||||
|
/// channel. Decrypts with the server's private key, re-encrypts per-recipient. The server
|
||||||
|
/// never stores RTC signals — pure forwarding.
|
||||||
|
/// </summary>
|
||||||
|
private void HandleEncryptedRtcSignal(string msg)
|
||||||
|
{
|
||||||
|
SocketRtcSignalMessage? payload;
|
||||||
|
try { payload = JsonSerializer.Deserialize<SocketRtcSignalMessage>(msg); }
|
||||||
|
catch { Console.WriteLine("Failed to parse RTC signal."); return; }
|
||||||
|
|
||||||
|
if (payload is null || string.IsNullOrWhiteSpace(payload.ChannelId)) return;
|
||||||
|
|
||||||
|
string plainText;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
plainText = E2EeHelper.DecryptForRecipient(
|
||||||
|
new EncryptedPayload { CipherText = payload.CipherText, Nonce = payload.Nonce, Tag = payload.Tag, EncryptedKey = payload.EncryptedKey },
|
||||||
|
ServerPrivateKey);
|
||||||
|
}
|
||||||
|
catch (Exception ex) { Console.WriteLine($"RTC decrypt failed: {ex.Message}"); return; }
|
||||||
|
|
||||||
|
foreach (var sid in RtcChannelPresenceService.GetSessionsInChannel(payload.ChannelId))
|
||||||
|
{
|
||||||
|
if (sid == ID) continue;
|
||||||
|
var uname = RtcChannelPresenceService.GetUsernameForSession(sid);
|
||||||
|
if (string.IsNullOrWhiteSpace(uname)) continue;
|
||||||
|
var key = GetClientPublicKeyByUsernameSync(uname);
|
||||||
|
if (key is null) continue;
|
||||||
|
var enc = E2EeHelper.EncryptForRecipient(plainText, key.PublicKey);
|
||||||
|
Sessions.SendTo(JsonSerializer.Serialize(new SocketRtcSignalMessage
|
||||||
|
{
|
||||||
|
Type = SignalType.EncryptedSignal, SenderUsername = payload.SenderUsername,
|
||||||
|
ChannelId = payload.ChannelId, CipherText = enc.CipherText,
|
||||||
|
Nonce = enc.Nonce, Tag = enc.Tag, EncryptedKey = enc.EncryptedKey
|
||||||
|
}), sid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The main chat-message path. Permission gate → server-side decrypt → store with channel
|
||||||
|
/// key → DeliverToServerMembers (per-user re-encrypt + send) → MirrorAttachmentIfNeeded.
|
||||||
|
/// </summary>
|
||||||
|
private void HandleEncryptedChatMessage(string msg)
|
||||||
|
{
|
||||||
|
SocketEncryptedMessage? payload;
|
||||||
|
try { payload = JsonSerializer.Deserialize<SocketEncryptedMessage>(msg); }
|
||||||
|
catch { Console.WriteLine("Failed to parse chat payload."); return; }
|
||||||
|
|
||||||
|
if (payload is null || payload.Type != SignalType.ClientEncryptedChat) return;
|
||||||
|
if (!EnsureCoreReady() || !EnsureCryptoReady()) return;
|
||||||
|
|
||||||
|
// Permission check.
|
||||||
|
var senderUsername = ConnectedClientService.GetUsernameForSession(ID);
|
||||||
|
if (string.IsNullOrWhiteSpace(senderUsername)) return;
|
||||||
|
|
||||||
|
if (PermissionService is not null &&
|
||||||
|
!PermissionService.CanSendMessagesAsync(senderUsername, payload.ChannelId).GetAwaiter().GetResult())
|
||||||
|
{
|
||||||
|
Send(JsonSerializer.Serialize(new WsEventMessage { Event = WsEvent.Error, Detail = "You cannot send messages in this channel." }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string plainText;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
plainText = E2EeHelper.DecryptForRecipient(
|
||||||
|
new EncryptedPayload { CipherText = payload.CipherText, Nonce = payload.Nonce, Tag = payload.Tag, EncryptedKey = payload.EncryptedKey },
|
||||||
|
ServerPrivateKey);
|
||||||
|
}
|
||||||
|
catch (Exception ex) { Console.WriteLine($"Chat decrypt failed: {ex.Message}"); return; }
|
||||||
|
|
||||||
|
Console.WriteLine($"Decrypted chat from {payload.SenderUsername}");
|
||||||
|
|
||||||
|
string messageId;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var dbEnc = ChannelCryptoService!.Encrypt(plainText, ChannelDbKey);
|
||||||
|
var saved = CreateChannelMessageSync(new ChannelMessages
|
||||||
|
{
|
||||||
|
ChannelId = payload.ChannelId,
|
||||||
|
SenderUserId = $"users:{payload.SenderUsername.ToLower()}",
|
||||||
|
CipherText = dbEnc.cipherText,
|
||||||
|
Nonce = dbEnc.nonce,
|
||||||
|
Tag = dbEnc.tag,
|
||||||
|
CreatedAt = DateTime.UtcNow
|
||||||
|
});
|
||||||
|
messageId = GetRecordId(saved.Id);
|
||||||
|
Console.WriteLine($"Message saved: {messageId}");
|
||||||
|
}
|
||||||
|
catch (Exception ex) { Console.WriteLine($"Save failed: {ex.Message}"); return; }
|
||||||
|
|
||||||
|
DeliverToServerMembers(plainText, payload.SenderUsername, payload.ChannelId,
|
||||||
|
messageId, SignalType.EncryptedChat, isEdited: false);
|
||||||
|
|
||||||
|
MirrorAttachmentIfNeeded(plainText, payload.SenderUsername, payload.ChannelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// If the origin channel has LinkedFileChannelId set and the message has a non-gif
|
||||||
|
/// attachment, stores+delivers a trimmed copy ("📎 Shared from #X by Y" + attachment)
|
||||||
|
/// into the linked File channel. No-op for plain text messages.
|
||||||
|
/// </summary>
|
||||||
|
private void MirrorAttachmentIfNeeded(string plainText, string senderUsername, string originChannelId)
|
||||||
|
{
|
||||||
|
ChatMessageContent? content;
|
||||||
|
try { content = JsonSerializer.Deserialize<ChatMessageContent>(plainText); }
|
||||||
|
catch { return; }
|
||||||
|
|
||||||
|
if (content is null || string.IsNullOrWhiteSpace(content.AttachmentBase64))
|
||||||
|
return;
|
||||||
|
|
||||||
|
// The user wants images, zips, docs — but not gifs (and links/text aren't attachments anyway).
|
||||||
|
var mime = content.AttachmentMimeType ?? string.Empty;
|
||||||
|
if (mime.Equals("image/gif", StringComparison.OrdinalIgnoreCase))
|
||||||
|
return;
|
||||||
|
|
||||||
|
var origin = GetChannelsSync().FirstOrDefault(ch => GetRecordId(ch.Id) == originChannelId);
|
||||||
|
if (origin?.LinkedFileChannelId is null) return;
|
||||||
|
|
||||||
|
var fileChannelId = origin.LinkedFileChannelId;
|
||||||
|
|
||||||
|
if (originChannelId == fileChannelId) return;
|
||||||
|
|
||||||
|
var mirror = new ChatMessageContent
|
||||||
|
{
|
||||||
|
Text = $"📎 Shared from #{origin.Name} by {senderUsername}",
|
||||||
|
AttachmentBase64 = content.AttachmentBase64,
|
||||||
|
AttachmentMimeType = content.AttachmentMimeType,
|
||||||
|
AttachmentFileName = content.AttachmentFileName
|
||||||
|
};
|
||||||
|
|
||||||
|
var mirrorPlain = JsonSerializer.Serialize(mirror);
|
||||||
|
|
||||||
|
string mirrorId;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var dbEnc = ChannelCryptoService!.Encrypt(mirrorPlain, ChannelDbKey);
|
||||||
|
var saved = CreateChannelMessageSync(new ChannelMessages
|
||||||
|
{
|
||||||
|
ChannelId = fileChannelId,
|
||||||
|
SenderUserId = $"users:{senderUsername.ToLower()}",
|
||||||
|
CipherText = dbEnc.cipherText,
|
||||||
|
Nonce = dbEnc.nonce,
|
||||||
|
Tag = dbEnc.tag,
|
||||||
|
CreatedAt = DateTime.UtcNow
|
||||||
|
});
|
||||||
|
mirrorId = GetRecordId(saved.Id);
|
||||||
|
}
|
||||||
|
catch (Exception ex) { Console.WriteLine($"File mirror save failed: {ex.Message}"); return; }
|
||||||
|
|
||||||
|
DeliverToServerMembers(mirrorPlain, senderUsername, fileChannelId,
|
||||||
|
mirrorId, SignalType.EncryptedChat, isEdited: false);
|
||||||
|
|
||||||
|
Console.WriteLine($"Mirrored attachment from {originChannelId} to file channel {fileChannelId}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Ownership-gated edit. Saves the OLD ciphertext as a ChannelMessageEdits row before
|
||||||
|
/// overwriting the current row, so the edit chain is preserved. Broadcasts MessageEdited
|
||||||
|
/// with the new ciphertext so every recipient updates their bubble in place.
|
||||||
|
/// </summary>
|
||||||
|
private void HandleEditMessage(string msg)
|
||||||
|
{
|
||||||
|
SocketEncryptedMessage? request;
|
||||||
|
try { request = JsonSerializer.Deserialize<SocketEncryptedMessage>(msg); }
|
||||||
|
catch { Console.WriteLine("Failed to parse edit request."); return; }
|
||||||
|
|
||||||
|
if (request is null || string.IsNullOrWhiteSpace(request.MessageId)) return;
|
||||||
|
if (!EnsureCoreReady() || !EnsureCryptoReady()) return;
|
||||||
|
|
||||||
|
var senderUsername = ConnectedClientService.GetUsernameForSession(ID);
|
||||||
|
if (string.IsNullOrWhiteSpace(senderUsername)) return;
|
||||||
|
|
||||||
|
var existing = GetChannelMessageByIdSync(request.MessageId);
|
||||||
|
if (existing is null) { Console.WriteLine($"Edit: message {request.MessageId} not found."); return; }
|
||||||
|
|
||||||
|
if (!string.Equals(ExtractUsernameFromUserId(existing.SenderUserId), senderUsername, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
Console.WriteLine($"Edit denied: {senderUsername} does not own {request.MessageId}.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
string newPlainText;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
newPlainText = E2EeHelper.DecryptForRecipient(
|
||||||
|
new EncryptedPayload { CipherText = request.CipherText, Nonce = request.Nonce, Tag = request.Tag, EncryptedKey = request.EncryptedKey },
|
||||||
|
ServerPrivateKey);
|
||||||
|
}
|
||||||
|
catch (Exception ex) { Console.WriteLine($"Edit decrypt failed: {ex.Message}"); return; }
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
CreateChannelMessageEditSync(new ChannelMessageEdits
|
||||||
|
{
|
||||||
|
MessageId = request.MessageId,
|
||||||
|
CipherText = existing.CipherText,
|
||||||
|
Nonce = existing.Nonce,
|
||||||
|
Tag = existing.Tag,
|
||||||
|
EditedAt = existing.EditedAt ?? existing.CreatedAt
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex) { Console.WriteLine($"Edit history save failed: {ex.Message}"); }
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var dbEnc = ChannelCryptoService!.Encrypt(newPlainText, ChannelDbKey);
|
||||||
|
existing.CipherText = dbEnc.cipherText;
|
||||||
|
existing.Nonce = dbEnc.nonce;
|
||||||
|
existing.Tag = dbEnc.tag;
|
||||||
|
existing.EditedAt = DateTime.UtcNow;
|
||||||
|
UpdateChannelMessageSync(existing);
|
||||||
|
Console.WriteLine($"Message {request.MessageId} edited by {senderUsername}.");
|
||||||
|
}
|
||||||
|
catch (Exception ex) { Console.WriteLine($"Edit DB update failed: {ex.Message}"); return; }
|
||||||
|
|
||||||
|
DeliverToServerMembers(newPlainText, senderUsername, request.ChannelId,
|
||||||
|
request.MessageId, SignalType.MessageEdited, isEdited: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Soft-delete (sets IsDeleted on the row). Allowed for the message author OR anyone with
|
||||||
|
/// ManageMessages permission in the channel. Broadcasts a tombstone event to every
|
||||||
|
/// connected member; their client swaps the bubble to a "deleted" placeholder.
|
||||||
|
/// </summary>
|
||||||
|
private void HandleDeleteMessage(string msg)
|
||||||
|
{
|
||||||
|
SocketEncryptedMessage? request;
|
||||||
|
try { request = JsonSerializer.Deserialize<SocketEncryptedMessage>(msg); }
|
||||||
|
catch { Console.WriteLine("Failed to parse delete request."); return; }
|
||||||
|
|
||||||
|
if (request is null || string.IsNullOrWhiteSpace(request.MessageId)) return;
|
||||||
|
if (!EnsureCoreReady()) return;
|
||||||
|
|
||||||
|
var senderUsername = ConnectedClientService.GetUsernameForSession(ID);
|
||||||
|
if (string.IsNullOrWhiteSpace(senderUsername)) return;
|
||||||
|
|
||||||
|
var existing = GetChannelMessageByIdSync(request.MessageId);
|
||||||
|
if (existing is null) return;
|
||||||
|
|
||||||
|
bool isOwner = string.Equals(ExtractUsernameFromUserId(existing.SenderUserId), senderUsername, StringComparison.OrdinalIgnoreCase);
|
||||||
|
bool canManage = PermissionService?.CanManageMessagesAsync(senderUsername, request.ChannelId).GetAwaiter().GetResult() ?? false;
|
||||||
|
|
||||||
|
if (!isOwner && !canManage)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"Delete denied: {senderUsername} does not own {request.MessageId}.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
existing.IsDeleted = true;
|
||||||
|
UpdateChannelMessageSync(existing);
|
||||||
|
Console.WriteLine($"Message {request.MessageId} deleted by {senderUsername}.");
|
||||||
|
}
|
||||||
|
catch (Exception ex) { Console.WriteLine($"Delete DB update failed: {ex.Message}"); return; }
|
||||||
|
|
||||||
|
var deletedEvent = JsonSerializer.Serialize(new SocketMessageDeletedEvent
|
||||||
|
{
|
||||||
|
Type = SignalType.MessageDeleted, MessageId = request.MessageId, ChannelId = request.ChannelId
|
||||||
|
});
|
||||||
|
|
||||||
|
foreach (var member in GetServerMembersSync())
|
||||||
|
{
|
||||||
|
var rawUsername = ExtractUsernameFromUserId(member.UserId);
|
||||||
|
foreach (var sid in ConnectedClientService.GetSessionsForUser(rawUsername))
|
||||||
|
Sessions.SendTo(deletedEvent, sid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The fan-out for any chat-message delivery (new send, edit broadcast). For each
|
||||||
|
/// server_members row, looks up active sessions, fetches that user's public key, encrypts
|
||||||
|
/// the plaintext for them, and sends to every one of their sessions (multi-device).
|
||||||
|
///
|
||||||
|
/// "ProperUsername" is the mixed-case version captured at RegisterKey time, used so the
|
||||||
|
/// client's case-insensitive compare picks up the message instead of dropping it silently.
|
||||||
|
/// </summary>
|
||||||
|
private void DeliverToServerMembers(
|
||||||
|
string plainText, string senderUsername, string channelId,
|
||||||
|
string messageId, SignalType signalType, bool isEdited)
|
||||||
|
{
|
||||||
|
foreach (var member in GetServerMembersSync())
|
||||||
|
{
|
||||||
|
var rawUsername = ExtractUsernameFromUserId(member.UserId);
|
||||||
|
var sessionIds = ConnectedClientService.GetSessionsForUser(rawUsername);
|
||||||
|
if (sessionIds.Count == 0) continue;
|
||||||
|
|
||||||
|
var properUsername = sessionIds
|
||||||
|
.Select(ConnectedClientService.GetUsernameForSession)
|
||||||
|
.FirstOrDefault(u => u is not null) ?? rawUsername;
|
||||||
|
|
||||||
|
var clientKey = GetClientPublicKeyByUsernameSync(properUsername);
|
||||||
|
if (clientKey is null) { Console.WriteLine($"No public key for {properUsername}, skipping."); continue; }
|
||||||
|
|
||||||
|
var encrypted = E2EeHelper.EncryptForRecipient(plainText, clientKey.PublicKey);
|
||||||
|
var json = JsonSerializer.Serialize(new SocketEncryptedMessage
|
||||||
|
{
|
||||||
|
Type = signalType, MessageId = messageId,
|
||||||
|
SenderUsername = senderUsername, RecipientUsername = properUsername, ChannelId = channelId,
|
||||||
|
CipherText = encrypted.CipherText, Nonce = encrypted.Nonce,
|
||||||
|
Tag = encrypted.Tag, EncryptedKey = encrypted.EncryptedKey,
|
||||||
|
IsEdited = isEdited
|
||||||
|
});
|
||||||
|
|
||||||
|
foreach (var sid in sessionIds)
|
||||||
|
Sessions.SendTo(json, sid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Pushes a freshly-built channel list to every connected member. Has to compute the list
|
||||||
|
/// PER user because CanPost/CanManage/visibility are user-specific. Called after Create/Delete.
|
||||||
|
/// </summary>
|
||||||
|
private void BroadcastChannelList()
|
||||||
|
{
|
||||||
|
foreach (var member in GetServerMembersSync())
|
||||||
|
{
|
||||||
|
var rawUsername = ExtractUsernameFromUserId(member.UserId);
|
||||||
|
var sessionIds = ConnectedClientService.GetSessionsForUser(rawUsername);
|
||||||
|
if (sessionIds.Count == 0) continue;
|
||||||
|
|
||||||
|
var properUsername = sessionIds
|
||||||
|
.Select(ConnectedClientService.GetUsernameForSession)
|
||||||
|
.FirstOrDefault(u => u is not null) ?? rawUsername;
|
||||||
|
|
||||||
|
var channels = BuildChannelListForUser(properUsername);
|
||||||
|
var json = JsonSerializer.Serialize(new SocketChannelList { Type = SignalType.ChannelList, Channels = channels });
|
||||||
|
|
||||||
|
foreach (var sid in sessionIds)
|
||||||
|
Sessions.SendTo(json, sid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Resolves the channel list a specific user can see, with CanPost/CanManage flags filled
|
||||||
|
/// in. Visibility (ViewChannel) determines inclusion — denied channels are filtered out.
|
||||||
|
/// </summary>
|
||||||
|
private List<ChannelItem> BuildChannelListForUser(string username)
|
||||||
|
{
|
||||||
|
var rawChannels = GetChannelsSync()
|
||||||
|
.Where(c => !c.IsDeleted)
|
||||||
|
.OrderBy(c => c.CreatedAt)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
var items = new List<ChannelItem>();
|
||||||
|
|
||||||
|
foreach (var c in rawChannels)
|
||||||
|
{
|
||||||
|
var channelId = GetRecordId(c.Id);
|
||||||
|
|
||||||
|
// "Visibility" — drop channels this user is not allowed to see.
|
||||||
|
if (PermissionService is not null &&
|
||||||
|
!PermissionService.CanViewChannelAsync(username, channelId).GetAwaiter().GetResult())
|
||||||
|
continue;
|
||||||
|
|
||||||
|
bool canPost = PermissionService is null
|
||||||
|
|| PermissionService.CanSendMessagesAsync(username, channelId).GetAwaiter().GetResult();
|
||||||
|
bool canManage = PermissionService is not null &&
|
||||||
|
(PermissionService.CanDeleteChannelAsync(username).GetAwaiter().GetResult() ||
|
||||||
|
PermissionService.CanEditChannelAsync(username).GetAwaiter().GetResult());
|
||||||
|
|
||||||
|
items.Add(new ChannelItem
|
||||||
|
{
|
||||||
|
ChannelId = channelId,
|
||||||
|
Name = c.Name,
|
||||||
|
Type = c.Type,
|
||||||
|
Group = c.Group,
|
||||||
|
IsReadOnly = c.IsReadOnly,
|
||||||
|
CanPost = canPost,
|
||||||
|
CanManage = canManage,
|
||||||
|
CreatedAt = c.CreatedAt
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// WebSocketSharp callback when the connection drops (clean close OR network drop). Clears
|
||||||
|
/// both presence registries so other clients aren't trying to send to a dead session.
|
||||||
|
/// </summary>
|
||||||
|
protected override void OnClose(CloseEventArgs e)
|
||||||
|
{
|
||||||
|
ConnectedClientService.Unregister(ID);
|
||||||
|
RtcChannelPresenceService.RemoveSession(ID);
|
||||||
|
Console.WriteLine($"WS closed: session={ID}, code={e.Code}");
|
||||||
|
base.OnClose(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>WebSocketSharp callback for socket-level errors. Logged but non-fatal.</summary>
|
||||||
|
protected override void OnError(ErrorEventArgs e)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"WS error: session={ID}, message={e.Message}");
|
||||||
|
base.OnError(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// Sync DB shims. WebSocketSharp's handler methods are synchronous, so async DB calls
|
||||||
|
// are wrapped in Task.Run(...).GetAwaiter().GetResult(). Not ideal but pragmatic — the
|
||||||
|
// alternative is refactoring WebSocketSharp's behavior model.
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private void RegisterOrUpdateClientKeySync(string username, string publicKey) =>
|
||||||
|
Task.Run(async () => await ClientKeyService!.RegisterOrUpdateKeyAsync(username, publicKey)).GetAwaiter().GetResult();
|
||||||
|
|
||||||
|
private List<Channels> GetChannelsSync() =>
|
||||||
|
Task.Run(async () => await Db!.Select<Channels>("channels")).GetAwaiter().GetResult().ToList();
|
||||||
|
|
||||||
|
private ClientPublicKeys? GetClientPublicKeyByUsernameSync(string username) =>
|
||||||
|
Task.Run(async () => await ClientKeyService!.GetByUsernameAsync(username)).GetAwaiter().GetResult();
|
||||||
|
|
||||||
|
private List<ChannelMessages> GetChannelMessagesSync() =>
|
||||||
|
Task.Run(async () => await Db!.Select<ChannelMessages>("channel_messages")).GetAwaiter().GetResult().ToList();
|
||||||
|
|
||||||
|
private ChannelMessages? GetChannelMessageByIdSync(string messageId) =>
|
||||||
|
GetChannelMessagesSync().FirstOrDefault(m => GetRecordId(m.Id) == messageId);
|
||||||
|
|
||||||
|
private ChannelMessages CreateChannelMessageSync(ChannelMessages message) =>
|
||||||
|
Task.Run(async () => await Db!.Create("channel_messages", message)).GetAwaiter().GetResult();
|
||||||
|
|
||||||
|
private void UpdateChannelMessageSync(ChannelMessages message) =>
|
||||||
|
Task.Run(async () => await Db!.Merge<ChannelMessages, ChannelMessages>(message)).GetAwaiter().GetResult();
|
||||||
|
|
||||||
|
private void CreateChannelMessageEditSync(ChannelMessageEdits edit) =>
|
||||||
|
Task.Run(async () => await Db!.Create("channel_message_edits", edit)).GetAwaiter().GetResult();
|
||||||
|
|
||||||
|
private List<ChannelMessageEdits> GetChannelMessageEditsSync(string messageId)
|
||||||
|
{
|
||||||
|
var all = Task.Run(async () => await Db!.Select<ChannelMessageEdits>("channel_message_edits"))
|
||||||
|
.GetAwaiter().GetResult().ToList();
|
||||||
|
return all.Where(e => e.MessageId == messageId).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<ServerMembers> GetServerMembersSync() =>
|
||||||
|
Task.Run(async () => await Db!.Select<ServerMembers>("server_members")).GetAwaiter().GetResult().ToList();
|
||||||
|
|
||||||
|
/// <summary>"users:keeper317" → "keeper317". Stored as Surreal record id, displayed as plain name.</summary>
|
||||||
|
private static string ExtractUsernameFromUserId(string senderUserId)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(senderUserId)) return "Unknown";
|
||||||
|
var parts = senderUserId.Split(':', 2);
|
||||||
|
return parts.Length == 2 ? parts[1] : senderUserId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SurrealDB's Id object → "table:recordId" string. Used for storing parent refs as strings in child rows.</summary>
|
||||||
|
private static string GetRecordId(object? id)
|
||||||
|
{
|
||||||
|
if (id is null) return string.Empty;
|
||||||
|
var json = JsonSerializer.Serialize(id);
|
||||||
|
using var doc = JsonDocument.Parse(json);
|
||||||
|
var root = doc.RootElement;
|
||||||
|
return $"{root.GetProperty("Table").GetString()}:{root.GetProperty("Id").GetString()}";
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Guard: returns true if the DB and key service are both initialised. Logs and returns false otherwise.</summary>
|
||||||
|
private bool EnsureCoreReady()
|
||||||
|
{
|
||||||
|
if (ClientKeyService is null || Db is null) { Console.WriteLine("Core services null."); return false; }
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Guard: returns true if encryption keys + channel crypto service are all set. Logs and returns false otherwise.</summary>
|
||||||
|
private bool EnsureCryptoReady()
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(ServerPrivateKey) || string.IsNullOrWhiteSpace(ChannelDbKey) || ChannelCryptoService is null)
|
||||||
|
{
|
||||||
|
Console.WriteLine("Crypto keys null.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
100
RelayServer/Services/Chat/ConnectedClientService.cs
Normal file
100
RelayServer/Services/Chat/ConnectedClientService.cs
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
|
||||||
|
namespace RelayServer.Services.Chat;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Two-way in-memory mapping between WebSocket session IDs and usernames.
|
||||||
|
///
|
||||||
|
/// Why both directions: when a chat message arrives, we need to look up "which sessions does
|
||||||
|
/// this server member have open right now?" (username → sessions) so we can deliver to each
|
||||||
|
/// of their devices. When a connection closes, we need to know "which user owned this session?"
|
||||||
|
/// (session → username) to clean up correctly.
|
||||||
|
///
|
||||||
|
/// Multi-device support: one username can have multiple sessions (phone + desktop + web all
|
||||||
|
/// connected simultaneously). UsernameToSessions stores a HashSet per username; each lock
|
||||||
|
/// is scoped to that specific HashSet so different users never block each other.
|
||||||
|
///
|
||||||
|
/// Username comparisons are case-insensitive (OrdinalIgnoreCase on the outer dictionary)
|
||||||
|
/// because the DB stores usernames lowercase but clients may register with mixed case.
|
||||||
|
/// </summary>
|
||||||
|
public static class ConnectedClientService
|
||||||
|
{
|
||||||
|
private static readonly ConcurrentDictionary<string, string> SessionToUsername = new();
|
||||||
|
private static readonly ConcurrentDictionary<string, HashSet<string>> UsernameToSessions =
|
||||||
|
new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Associates a session ID with a username. Called from HandleRegisterKey. If the same
|
||||||
|
/// session re-registers under a different username (rare — basically only if the client
|
||||||
|
/// reauthenticates), the old mapping is cleaned up first to avoid double-bookkeeping.
|
||||||
|
/// </summary>
|
||||||
|
public static void Register(string sessionId, string username)
|
||||||
|
{
|
||||||
|
if (SessionToUsername.TryGetValue(sessionId, out var oldUsername) &&
|
||||||
|
!string.Equals(oldUsername, username, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
RemoveSessionFromUsername(sessionId, oldUsername);
|
||||||
|
}
|
||||||
|
|
||||||
|
SessionToUsername[sessionId] = username;
|
||||||
|
|
||||||
|
var sessions = UsernameToSessions.GetOrAdd(
|
||||||
|
username,
|
||||||
|
_ => new HashSet<string>(StringComparer.Ordinal));
|
||||||
|
|
||||||
|
lock (sessions)
|
||||||
|
sessions.Add(sessionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Removes a session from both mappings. Called from OnClose. Idempotent — calling for
|
||||||
|
/// a session that's already gone is a no-op.
|
||||||
|
/// </summary>
|
||||||
|
public static void Unregister(string sessionId)
|
||||||
|
{
|
||||||
|
if (SessionToUsername.TryRemove(sessionId, out var username))
|
||||||
|
RemoveSessionFromUsername(sessionId, username);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Returns every active session ID for a given username (case-insensitive lookup).
|
||||||
|
/// Empty collection if the user is offline. Snapshot-safe: the returned list is a copy,
|
||||||
|
/// not a live view of the underlying HashSet.
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyCollection<string> GetSessionsForUser(string username)
|
||||||
|
{
|
||||||
|
if (UsernameToSessions.TryGetValue(username, out var sessions))
|
||||||
|
{
|
||||||
|
lock (sessions)
|
||||||
|
return sessions.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
return Array.Empty<string>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reverse lookup: which user owns this session? Returns the mixed-case username the
|
||||||
|
/// client registered with (preserves casing for display). Null if the session is unknown.
|
||||||
|
/// </summary>
|
||||||
|
public static string? GetUsernameForSession(string sessionId)
|
||||||
|
{
|
||||||
|
return SessionToUsername.TryGetValue(sessionId, out var u) ? u : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Internal cleanup: pulls a session out of the username→sessions HashSet, and removes
|
||||||
|
/// the username entry entirely if no sessions remain (keeps the dictionary lean).
|
||||||
|
/// </summary>
|
||||||
|
private static void RemoveSessionFromUsername(string sessionId, string username)
|
||||||
|
{
|
||||||
|
if (!UsernameToSessions.TryGetValue(username, out var sessions))
|
||||||
|
return;
|
||||||
|
|
||||||
|
lock (sessions)
|
||||||
|
{
|
||||||
|
sessions.Remove(sessionId);
|
||||||
|
if (sessions.Count == 0)
|
||||||
|
UsernameToSessions.TryRemove(username, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
17
RelayServer/Services/Core/CoreClientService.cs
Normal file
17
RelayServer/Services/Core/CoreClientService.cs
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
namespace RelayServer.Services.Core;
|
||||||
|
|
||||||
|
public sealed class CoreClientService
|
||||||
|
{
|
||||||
|
public Task<CoreUser?> GetUserByUsernameAsync(string username)
|
||||||
|
{
|
||||||
|
return Task.FromResult<CoreUser?>(username switch
|
||||||
|
{
|
||||||
|
"Keeper317" => new CoreUser("users:keeper317", "Keeper317", true),
|
||||||
|
"Ru_Kira" => new CoreUser("users:ru_kira", "Ru_Kira", true),
|
||||||
|
"Test" => new CoreUser("users:test", "Test", true),
|
||||||
|
_ => null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record CoreUser(string Id, string Username, bool Licensed);
|
||||||
318
RelayServer/Services/Core/ServerBootstrapService.cs
Normal file
318
RelayServer/Services/Core/ServerBootstrapService.cs
Normal file
@@ -0,0 +1,318 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using RelayServer.Models;
|
||||||
|
using RelayServer.Services.Chat;
|
||||||
|
using RelayServer.Services.Crypto;
|
||||||
|
using RelayShared.Services;
|
||||||
|
using SurrealDb.Net;
|
||||||
|
|
||||||
|
namespace RelayServer.Services.Core;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Idempotent server setup. Runs once at boot from Program.cs.
|
||||||
|
///
|
||||||
|
/// Each "Ensure*" helper either inserts a missing row or patches an existing one so the
|
||||||
|
/// declared state matches the code. Running this twice in a row is a no-op.
|
||||||
|
///
|
||||||
|
/// What it provisions:
|
||||||
|
/// - Verifies the three test users exist via CoreClientService (currently a hardcoded stub).
|
||||||
|
/// - Creates the "Test Server" row in the servers table if missing.
|
||||||
|
/// - Adds those users to server_members, with Keeper317 as IsOwner=true.
|
||||||
|
/// - Creates the four premade channels with correct ChannelType and IsReadOnly flags:
|
||||||
|
/// welcome (Text, read-only) general (Text)
|
||||||
|
/// files (File, read-only) voice-general (Voice)
|
||||||
|
/// - Links #general → #files so attachments posted in #general auto-mirror to #files.
|
||||||
|
/// - Creates the three roles: Admin (all perms), Moderator (manage messages), Member (read+send).
|
||||||
|
/// - Assigns exactly one role per user (Keeper→Admin, Kira→Moderator, Test→Member).
|
||||||
|
/// SetUserRoleAsync DELETES stale assignments to guarantee single-role-per-user.
|
||||||
|
/// - Writes channel_permissions overrides explicitly denying Members SendMessages in
|
||||||
|
/// #welcome and #files.
|
||||||
|
/// - Generates the server's RSA keypair + the channel AES key on first boot, stores both
|
||||||
|
/// in server_encryption_keys, and copies them into ChatSocketBehavior's static fields.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ServerBootstrapService
|
||||||
|
{
|
||||||
|
private readonly SurrealDbClient _db;
|
||||||
|
private readonly CoreClientService _coreClient;
|
||||||
|
private readonly ChannelCryptoService _cryptoService;
|
||||||
|
|
||||||
|
public ServerBootstrapService(
|
||||||
|
SurrealDbClient db,
|
||||||
|
CoreClientService coreClient,
|
||||||
|
ChannelCryptoService cryptoService)
|
||||||
|
{
|
||||||
|
_db = db;
|
||||||
|
_coreClient = coreClient;
|
||||||
|
_cryptoService = cryptoService;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task InitializeAsync()
|
||||||
|
{
|
||||||
|
var keeper = await _coreClient.GetUserByUsernameAsync("Keeper317");
|
||||||
|
var kira = await _coreClient.GetUserByUsernameAsync("Ru_Kira");
|
||||||
|
var test = await _coreClient.GetUserByUsernameAsync("Test");
|
||||||
|
|
||||||
|
if (keeper is null || kira is null || test is null)
|
||||||
|
throw new InvalidOperationException("One or more required users do not exist in RelayCore.");
|
||||||
|
|
||||||
|
if (!keeper.Licensed || !kira.Licensed || !test.Licensed)
|
||||||
|
throw new InvalidOperationException("One or more required users are not licensed.");
|
||||||
|
|
||||||
|
Console.WriteLine($"Core verified: {keeper.Username}, {kira.Username}, {test.Username}");
|
||||||
|
|
||||||
|
var server = await GetServerByNameAsync("Test Server");
|
||||||
|
|
||||||
|
if (server is null)
|
||||||
|
{
|
||||||
|
server = await _db.Create("servers", new Servers
|
||||||
|
{
|
||||||
|
Name = "Test Server",
|
||||||
|
OwnerUserId = keeper.Id,
|
||||||
|
CreatedAt = DateTime.UtcNow
|
||||||
|
});
|
||||||
|
Console.WriteLine($"Server created: {ToJson(server)}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Console.WriteLine($"Server already exists: {server.Name}");
|
||||||
|
}
|
||||||
|
|
||||||
|
await EnsureServerMemberAsync(keeper.Id, isOwner: true);
|
||||||
|
await EnsureServerMemberAsync(kira.Id, isOwner: false);
|
||||||
|
await EnsureServerMemberAsync(test.Id, isOwner: false);
|
||||||
|
Console.WriteLine("Server members ensured.");
|
||||||
|
|
||||||
|
var tBase = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||||
|
|
||||||
|
var chWelcome = await EnsureChannelAsync("welcome", ChannelType.Text, group: "General", isReadOnly: true, createdAt: tBase);
|
||||||
|
var chGeneral = await EnsureChannelAsync("general", ChannelType.Text, group: "General", isReadOnly: false, createdAt: tBase.AddHours(1));
|
||||||
|
var chFiles = await EnsureChannelAsync("files", ChannelType.File, group: "General", isReadOnly: true, createdAt: tBase.AddHours(2));
|
||||||
|
var chVoice = await EnsureChannelAsync("voice-general", ChannelType.Voice, group: "General", isReadOnly: false, createdAt: tBase.AddHours(3));
|
||||||
|
|
||||||
|
Console.WriteLine($"Channels: {GetRecordId(chWelcome.Id)} | {GetRecordId(chGeneral.Id)} | {GetRecordId(chFiles.Id)} | {GetRecordId(chVoice.Id)}");
|
||||||
|
|
||||||
|
await EnsureFileChannelLinkAsync(chGeneral, GetRecordId(chFiles.Id));
|
||||||
|
|
||||||
|
var adminRole = await EnsureRoleAsync("Admin", PermissionFlags.Administrator, priority: 0);
|
||||||
|
var modRole = await EnsureRoleAsync("Moderator", PermissionFlags.ReadMessages | PermissionFlags.SendMessages | PermissionFlags.ManageMessages, priority: 1);
|
||||||
|
var memberRole = await EnsureRoleAsync("Member", PermissionFlags.ReadMessages | PermissionFlags.SendMessages, priority: 2);
|
||||||
|
|
||||||
|
Console.WriteLine($"Roles ensured: Admin={GetRecordId(adminRole.Id)}, Mod={GetRecordId(modRole.Id)}, Member={GetRecordId(memberRole.Id)}");
|
||||||
|
|
||||||
|
await SetUserRoleAsync(keeper.Id, GetRecordId(adminRole.Id));
|
||||||
|
await SetUserRoleAsync(kira.Id, GetRecordId(modRole.Id));
|
||||||
|
await SetUserRoleAsync(test.Id, GetRecordId(memberRole.Id));
|
||||||
|
Console.WriteLine("User roles set.");
|
||||||
|
|
||||||
|
await EnsureChannelPermissionAsync(GetRecordId(chWelcome.Id), GetRecordId(memberRole.Id),
|
||||||
|
allow: PermissionFlags.ReadMessages, deny: PermissionFlags.SendMessages);
|
||||||
|
await EnsureChannelPermissionAsync(GetRecordId(chFiles.Id), GetRecordId(memberRole.Id),
|
||||||
|
allow: PermissionFlags.ReadMessages, deny: PermissionFlags.SendMessages);
|
||||||
|
|
||||||
|
Console.WriteLine("Channel permissions ensured.");
|
||||||
|
|
||||||
|
var existingKey = await GetLatestServerEncryptionKeyAsync();
|
||||||
|
|
||||||
|
if (existingKey is null)
|
||||||
|
{
|
||||||
|
var keyBase64 = _cryptoService.GenerateKey();
|
||||||
|
var serverKeys = E2EeHelper.GenerateRsaKeyPair();
|
||||||
|
|
||||||
|
existingKey = await _db.Create("server_encryption_keys", new ServerEncryptionKeys
|
||||||
|
{
|
||||||
|
KeyBase64 = keyBase64,
|
||||||
|
PublicKey = serverKeys.publicKey,
|
||||||
|
PrivateKey = serverKeys.privateKey,
|
||||||
|
CreatedAt = DateTime.UtcNow,
|
||||||
|
UpdatedAt = DateTime.UtcNow
|
||||||
|
});
|
||||||
|
|
||||||
|
Console.WriteLine("Server encryption key created.");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Console.WriteLine("Server encryption key already exists.");
|
||||||
|
}
|
||||||
|
|
||||||
|
ChatSocketBehavior.ServerPublicKey = existingKey.PublicKey;
|
||||||
|
ChatSocketBehavior.ServerPrivateKey = existingKey.PrivateKey;
|
||||||
|
ChatSocketBehavior.ChannelDbKey = existingKey.KeyBase64;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task EnsureServerMemberAsync(string userId, bool isOwner)
|
||||||
|
{
|
||||||
|
var members = await _db.Select<ServerMembers>("server_members");
|
||||||
|
var existing = members.FirstOrDefault(m => m.UserId == userId);
|
||||||
|
|
||||||
|
if (existing is not null)
|
||||||
|
{
|
||||||
|
if (existing.IsOwner != isOwner)
|
||||||
|
{
|
||||||
|
existing.IsOwner = isOwner;
|
||||||
|
await _db.Merge<ServerMembers, ServerMembers>(existing);
|
||||||
|
Console.WriteLine($"Member IsOwner updated: {userId} → {isOwner}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Console.WriteLine($"Member already correct: {userId}");
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _db.Create("server_members", new ServerMembers
|
||||||
|
{
|
||||||
|
UserId = userId,
|
||||||
|
JoinedAt = DateTime.UtcNow,
|
||||||
|
IsOwner = isOwner
|
||||||
|
});
|
||||||
|
Console.WriteLine($"Member created: {userId} (IsOwner={isOwner})");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<Channels> EnsureChannelAsync(
|
||||||
|
string name, ChannelType type, string group, bool isReadOnly, DateTime createdAt)
|
||||||
|
{
|
||||||
|
var channels = await _db.Select<Channels>("channels");
|
||||||
|
var existing = channels.FirstOrDefault(c => c.Name == name);
|
||||||
|
|
||||||
|
if (existing is not null)
|
||||||
|
{
|
||||||
|
bool dirty = existing.Type != type || existing.Group != group || existing.IsReadOnly != isReadOnly;
|
||||||
|
if (dirty)
|
||||||
|
{
|
||||||
|
existing.Type = type;
|
||||||
|
existing.Group = group;
|
||||||
|
existing.IsReadOnly = isReadOnly;
|
||||||
|
await _db.Merge<Channels, Channels>(existing);
|
||||||
|
Console.WriteLine($"Channel updated: {name}");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Console.WriteLine($"Channel already correct: {name}");
|
||||||
|
}
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
|
||||||
|
var channel = await _db.Create("channels", new Channels
|
||||||
|
{
|
||||||
|
Name = name,
|
||||||
|
Type = type,
|
||||||
|
Group = group,
|
||||||
|
IsReadOnly = isReadOnly,
|
||||||
|
CreatedAt = createdAt
|
||||||
|
});
|
||||||
|
|
||||||
|
Console.WriteLine($"Channel created: {name} ({type})");
|
||||||
|
return channel;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task EnsureFileChannelLinkAsync(Channels channel, string fileChannelId)
|
||||||
|
{
|
||||||
|
if (channel.LinkedFileChannelId == fileChannelId)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"File link already correct: {channel.Name} → {fileChannelId}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
channel.LinkedFileChannelId = fileChannelId;
|
||||||
|
await _db.Merge<Channels, Channels>(channel);
|
||||||
|
Console.WriteLine($"File link set: {channel.Name} → {fileChannelId}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<Roles> EnsureRoleAsync(string name, PermissionFlags permissions, int priority)
|
||||||
|
{
|
||||||
|
var roles = await _db.Select<Roles>("roles");
|
||||||
|
var existing = roles.FirstOrDefault(r => r.Name == name);
|
||||||
|
|
||||||
|
if (existing is not null)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"Role already exists: {name}");
|
||||||
|
return existing;
|
||||||
|
}
|
||||||
|
|
||||||
|
var role = await _db.Create("roles", new Roles
|
||||||
|
{
|
||||||
|
Name = name,
|
||||||
|
Permissions = permissions,
|
||||||
|
Priority = priority,
|
||||||
|
CreatedAt = DateTime.UtcNow
|
||||||
|
});
|
||||||
|
Console.WriteLine($"Role created: {name}");
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SetUserRoleAsync(string userId, string roleId)
|
||||||
|
{
|
||||||
|
var userRoles = await _db.Select<UserRoles>("user_roles");
|
||||||
|
var existing = userRoles
|
||||||
|
.Where(ur => string.Equals(ur.UserId, userId, StringComparison.OrdinalIgnoreCase))
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
bool alreadyCorrect = existing.Count == 1 && existing[0].RoleId == roleId;
|
||||||
|
if (alreadyCorrect)
|
||||||
|
{
|
||||||
|
Console.WriteLine($"UserRole already correct: {userId} → {roleId}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var stale in existing)
|
||||||
|
{
|
||||||
|
if (stale.Id is not null)
|
||||||
|
await _db.Delete(stale.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
await _db.Create("user_roles", new UserRoles
|
||||||
|
{
|
||||||
|
UserId = userId,
|
||||||
|
RoleId = roleId,
|
||||||
|
AssignedAt = DateTime.UtcNow
|
||||||
|
});
|
||||||
|
Console.WriteLine($"UserRole set: {userId} → {roleId}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task EnsureChannelPermissionAsync(
|
||||||
|
string channelId, string roleId, PermissionFlags allow, PermissionFlags deny)
|
||||||
|
{
|
||||||
|
var perms = await _db.Select<ChannelPermissions>("channel_permissions");
|
||||||
|
if (perms.Any(cp => cp.ChannelId == channelId && cp.RoleId == roleId))
|
||||||
|
{
|
||||||
|
Console.WriteLine($"ChannelPermission already exists: {channelId} → {roleId}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _db.Create("channel_permissions", new ChannelPermissions
|
||||||
|
{
|
||||||
|
ChannelId = channelId,
|
||||||
|
RoleId = roleId,
|
||||||
|
Allow = allow,
|
||||||
|
Deny = deny
|
||||||
|
});
|
||||||
|
Console.WriteLine($"ChannelPermission created: {channelId} → {roleId} | allow={allow}, deny={deny}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<Servers?> GetServerByNameAsync(string name)
|
||||||
|
{
|
||||||
|
var servers = await _db.Select<Servers>("servers");
|
||||||
|
return servers.FirstOrDefault(x => x.Name == name);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<ServerEncryptionKeys?> GetLatestServerEncryptionKeyAsync()
|
||||||
|
{
|
||||||
|
var keys = await _db.Select<ServerEncryptionKeys>("server_encryption_keys");
|
||||||
|
return keys.OrderByDescending(x => x.CreatedAt).FirstOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string GetRecordId(object? id)
|
||||||
|
{
|
||||||
|
if (id is null) return string.Empty;
|
||||||
|
var json = JsonSerializer.Serialize(id);
|
||||||
|
using var doc = JsonDocument.Parse(json);
|
||||||
|
var root = doc.RootElement;
|
||||||
|
return $"{root.GetProperty("Table").GetString()}:{root.GetProperty("Id").GetString()}";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ToJson(object? obj) =>
|
||||||
|
JsonSerializer.Serialize(obj, new JsonSerializerOptions
|
||||||
|
{
|
||||||
|
WriteIndented = true,
|
||||||
|
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||||
|
});
|
||||||
|
}
|
||||||
98
RelayServer/Services/Crypto/E2EeHelper.cs
Normal file
98
RelayServer/Services/Crypto/E2EeHelper.cs
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace RelayServer.Services.Crypto;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Hybrid RSA-2048 + AES-GCM-256 encryption. Used for any payload that needs to be
|
||||||
|
/// readable by exactly one party (the holder of a specific RSA private key).
|
||||||
|
///
|
||||||
|
/// Encrypt:
|
||||||
|
/// 1. Generate a fresh 256-bit AES key and 96-bit nonce.
|
||||||
|
/// 2. Encrypt the plaintext with AES-GCM → CipherText + Tag (auth tag, 128-bit).
|
||||||
|
/// 3. Encrypt the AES key with the recipient's RSA public key (OAEP-SHA256).
|
||||||
|
/// 4. Return all four as base64 strings in an EncryptedPayload.
|
||||||
|
///
|
||||||
|
/// Decrypt: reverse — RSA-decrypt the AES key, then AES-GCM-decrypt the ciphertext.
|
||||||
|
///
|
||||||
|
/// Why hybrid: RSA can only encrypt small inputs (~190 bytes for 2048-bit OAEP-SHA256).
|
||||||
|
/// Wrapping a symmetric key with RSA lets us encrypt arbitrarily large payloads while
|
||||||
|
/// still using the recipient's RSA keypair as the access mechanism. This is the same
|
||||||
|
/// design as PGP, TLS handshakes, etc.
|
||||||
|
///
|
||||||
|
/// The identical implementation exists in RelayClient.Crypto.E2EeHelper — they're
|
||||||
|
/// mirrored on both ends so any payload encrypted on one side decrypts on the other.
|
||||||
|
/// </summary>
|
||||||
|
public static class E2EeHelper
|
||||||
|
{
|
||||||
|
public static (string publicKey, string privateKey) GenerateRsaKeyPair()
|
||||||
|
{
|
||||||
|
using var rsa = RSA.Create(2048);
|
||||||
|
|
||||||
|
return (
|
||||||
|
Convert.ToBase64String(rsa.ExportSubjectPublicKeyInfo()),
|
||||||
|
Convert.ToBase64String(rsa.ExportPkcs8PrivateKey())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static EncryptedPayload EncryptForRecipient(string plainText, string recipientPublicKeyBase64)
|
||||||
|
{
|
||||||
|
byte[] aesKey = RandomNumberGenerator.GetBytes(32);
|
||||||
|
byte[] nonce = RandomNumberGenerator.GetBytes(12);
|
||||||
|
byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
|
||||||
|
byte[] cipherBytes = new byte[plainBytes.Length];
|
||||||
|
byte[] tag = new byte[16];
|
||||||
|
|
||||||
|
using (var aes = new AesGcm(aesKey, 16))
|
||||||
|
{
|
||||||
|
aes.Encrypt(nonce, plainBytes, cipherBytes, tag);
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] encryptedKey;
|
||||||
|
using (var rsa = RSA.Create())
|
||||||
|
{
|
||||||
|
rsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(recipientPublicKeyBase64), out _);
|
||||||
|
encryptedKey = rsa.Encrypt(aesKey, RSAEncryptionPadding.OaepSHA256);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new EncryptedPayload
|
||||||
|
{
|
||||||
|
CipherText = Convert.ToBase64String(cipherBytes),
|
||||||
|
Nonce = Convert.ToBase64String(nonce),
|
||||||
|
Tag = Convert.ToBase64String(tag),
|
||||||
|
EncryptedKey = Convert.ToBase64String(encryptedKey)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string DecryptForRecipient(EncryptedPayload payload, string recipientPrivateKeyBase64)
|
||||||
|
{
|
||||||
|
byte[] aesKey;
|
||||||
|
using (var rsa = RSA.Create())
|
||||||
|
{
|
||||||
|
rsa.ImportPkcs8PrivateKey(Convert.FromBase64String(recipientPrivateKeyBase64), out _);
|
||||||
|
aesKey = rsa.Decrypt(Convert.FromBase64String(payload.EncryptedKey), RSAEncryptionPadding.OaepSHA256);
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] plainBytes = new byte[Convert.FromBase64String(payload.CipherText).Length];
|
||||||
|
|
||||||
|
using (var aes = new AesGcm(aesKey, 16))
|
||||||
|
{
|
||||||
|
aes.Decrypt(
|
||||||
|
Convert.FromBase64String(payload.Nonce),
|
||||||
|
Convert.FromBase64String(payload.CipherText),
|
||||||
|
Convert.FromBase64String(payload.Tag),
|
||||||
|
plainBytes
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Encoding.UTF8.GetString(plainBytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class EncryptedPayload
|
||||||
|
{
|
||||||
|
public required string CipherText { get; set; }
|
||||||
|
public required string Nonce { get; set; }
|
||||||
|
public required string Tag { get; set; }
|
||||||
|
public required string EncryptedKey { get; set; }
|
||||||
|
}
|
||||||
61
RelayServer/Services/Data/ClientKeyService.cs
Normal file
61
RelayServer/Services/Data/ClientKeyService.cs
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
using RelayServer.Models;
|
||||||
|
using SurrealDb.Net;
|
||||||
|
|
||||||
|
namespace RelayServer.Services.Data;
|
||||||
|
|
||||||
|
public sealed class ClientKeyService
|
||||||
|
{
|
||||||
|
private readonly SurrealDbClient _db;
|
||||||
|
|
||||||
|
public ClientKeyService(SurrealDbClient db)
|
||||||
|
{
|
||||||
|
_db = db;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task RegisterOrUpdateKeyAsync(string username, string publicKey)
|
||||||
|
{
|
||||||
|
var allKeys = await _db.Select<ClientPublicKeys>("client_public_keys");
|
||||||
|
|
||||||
|
var existing = allKeys.FirstOrDefault(x => x.Username == username);
|
||||||
|
|
||||||
|
if (existing is null)
|
||||||
|
{
|
||||||
|
await _db.Create("client_public_keys", new ClientPublicKeys
|
||||||
|
{
|
||||||
|
Username = username,
|
||||||
|
PublicKey = publicKey,
|
||||||
|
CreatedAt = DateTime.UtcNow,
|
||||||
|
UpdatedAt = DateTime.UtcNow
|
||||||
|
});
|
||||||
|
|
||||||
|
Console.WriteLine($"Stored public key for {username}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
existing.PublicKey = publicKey;
|
||||||
|
existing.UpdatedAt = DateTime.UtcNow;
|
||||||
|
|
||||||
|
await _db.Merge<ClientPublicKeys, ClientPublicKeys>(new ClientPublicKeys
|
||||||
|
{
|
||||||
|
Id = existing.Id,
|
||||||
|
Username = existing.Username,
|
||||||
|
PublicKey = existing.PublicKey,
|
||||||
|
CreatedAt = existing.CreatedAt,
|
||||||
|
UpdatedAt = existing.UpdatedAt
|
||||||
|
});
|
||||||
|
|
||||||
|
Console.WriteLine($"Updated public key for {username}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<ClientPublicKeys?> GetByUsernameAsync(string username)
|
||||||
|
{
|
||||||
|
var allKeys = await _db.Select<ClientPublicKeys>("client_public_keys");
|
||||||
|
return allKeys.FirstOrDefault(x => x.Username == username);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<List<ClientPublicKeys>> GetAllAsync()
|
||||||
|
{
|
||||||
|
var allKeys = await _db.Select<ClientPublicKeys>("client_public_keys");
|
||||||
|
return allKeys.ToList();
|
||||||
|
}
|
||||||
|
}
|
||||||
209
RelayServer/Services/Data/PermissionService.cs
Normal file
209
RelayServer/Services/Data/PermissionService.cs
Normal file
@@ -0,0 +1,209 @@
|
|||||||
|
using RelayServer.Models;
|
||||||
|
using SurrealDb.Net;
|
||||||
|
|
||||||
|
namespace RelayServer.Services.Data;
|
||||||
|
|
||||||
|
public sealed class PermissionService
|
||||||
|
{
|
||||||
|
private readonly SurrealDbClient _db;
|
||||||
|
|
||||||
|
public PermissionService(SurrealDbClient db)
|
||||||
|
{
|
||||||
|
_db = db;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Owners/admins always allowed. Non-admins blocked from read-only channels (#welcome,
|
||||||
|
/// #files). Everyone else passes through the normal channel-level Deny → Allow → role ladder.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<bool> CanSendMessagesAsync(string username, string channelId)
|
||||||
|
{
|
||||||
|
if (await IsOwnerOrAdminAsync(username))
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if (await IsChannelReadOnlyAsync(channelId))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
return await HasPermissionAsync(username, channelId, PermissionFlags.SendMessages);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Server-wide ability to create channels. Gates the "+" button on the sidebar.</summary>
|
||||||
|
public async Task<bool> CanManageChannelsAsync(string username) =>
|
||||||
|
await IsOwnerOrAdminAsync(username) ||
|
||||||
|
await HasGlobalPermissionAsync(username, PermissionFlags.ManageChannels);
|
||||||
|
|
||||||
|
/// <summary>Per-channel ability to delete/edit OTHER people's messages. Authors can always delete their own.</summary>
|
||||||
|
public async Task<bool> CanManageMessagesAsync(string username, string channelId) =>
|
||||||
|
await IsOwnerOrAdminAsync(username) ||
|
||||||
|
await HasPermissionAsync(username, channelId, PermissionFlags.ManageMessages);
|
||||||
|
|
||||||
|
/// <summary>Convenience query — exposes the owner-or-admin shortcut as a public method.</summary>
|
||||||
|
public async Task<bool> IsAdministratorAsync(string username) =>
|
||||||
|
await IsOwnerOrAdminAsync(username);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// "Visibility" — default-allow. Only blocks if a channel-level Deny mask explicitly
|
||||||
|
/// removes ViewChannel for the user's role. Owners/admins bypass.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<bool> CanViewChannelAsync(string username, string channelId)
|
||||||
|
{
|
||||||
|
if (await IsOwnerOrAdminAsync(username)) return true;
|
||||||
|
return !await IsDeniedByChannelAsync(username, channelId, PermissionFlags.ViewChannel);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Voice-channel Speak. Default-allow. Blocked by channel-level Deny. Used at RtcJoin
|
||||||
|
/// time so denied users can't even register voice presence.
|
||||||
|
/// </summary>
|
||||||
|
public async Task<bool> CanSpeakAsync(string username, string channelId)
|
||||||
|
{
|
||||||
|
if (await IsOwnerOrAdminAsync(username)) return true;
|
||||||
|
return !await IsDeniedByChannelAsync(username, channelId, PermissionFlags.Speak);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Server-wide ability to delete channels. ManageChannels OR explicit DeleteChannel.</summary>
|
||||||
|
public async Task<bool> CanDeleteChannelAsync(string username) =>
|
||||||
|
await IsOwnerOrAdminAsync(username) ||
|
||||||
|
await HasGlobalPermissionAsync(username, PermissionFlags.ManageChannels) ||
|
||||||
|
await HasGlobalPermissionAsync(username, PermissionFlags.DeleteChannel);
|
||||||
|
|
||||||
|
/// <summary>Server-wide ability to edit channels. ManageChannels OR explicit EditChannel.</summary>
|
||||||
|
public async Task<bool> CanEditChannelAsync(string username) =>
|
||||||
|
await IsOwnerOrAdminAsync(username) ||
|
||||||
|
await HasGlobalPermissionAsync(username, PermissionFlags.ManageChannels) ||
|
||||||
|
await HasGlobalPermissionAsync(username, PermissionFlags.EditChannel);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Step 1 of the ladder: owner flag OR Administrator permission on any assigned role.
|
||||||
|
/// Owner check goes first because it doesn't require roles to be seeded — server owner
|
||||||
|
/// is authoritative regardless of role-table state.
|
||||||
|
/// </summary>
|
||||||
|
private async Task<bool> IsOwnerOrAdminAsync(string username)
|
||||||
|
{
|
||||||
|
if (await IsServerOwnerAsync(username))
|
||||||
|
return true;
|
||||||
|
|
||||||
|
var roles = await GetUserRolesAsync(username);
|
||||||
|
return roles.Any(r => r.Permissions.HasFlag(PermissionFlags.Administrator));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The canonical permission ladder for per-channel checks:
|
||||||
|
/// 1. Owner/admin → true.
|
||||||
|
/// 2. Channel-level Deny mask for any of the user's roles → false (Deny wins).
|
||||||
|
/// 3. Channel-level Allow mask for any of the user's roles → true.
|
||||||
|
/// 4. Base role permissions → fallback.
|
||||||
|
/// </summary>
|
||||||
|
private async Task<bool> HasPermissionAsync(
|
||||||
|
string username, string channelId, PermissionFlags flag)
|
||||||
|
{
|
||||||
|
if (await IsOwnerOrAdminAsync(username))
|
||||||
|
return true;
|
||||||
|
|
||||||
|
var userRoles = await GetUserRolesAsync(username);
|
||||||
|
if (userRoles.Count == 0) return false;
|
||||||
|
|
||||||
|
var channelOverrides = await GetChannelPermissionsAsync(channelId);
|
||||||
|
var userRoleIds = new HashSet<string>(userRoles.Select(r => GetRecordIdString(r.Id)));
|
||||||
|
|
||||||
|
foreach (var co in channelOverrides.Where(co => userRoleIds.Contains(co.RoleId)))
|
||||||
|
if (co.Deny.HasFlag(flag)) return false;
|
||||||
|
|
||||||
|
foreach (var co in channelOverrides.Where(co => userRoleIds.Contains(co.RoleId)))
|
||||||
|
if (co.Allow.HasFlag(flag)) return true;
|
||||||
|
|
||||||
|
return userRoles.Any(r => r.Permissions.HasFlag(flag));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Server-wide (not channel-scoped) permission check. Used for things like ManageChannels
|
||||||
|
/// where there's no specific channel context. Admin flag short-circuits.
|
||||||
|
/// </summary>
|
||||||
|
private async Task<bool> HasGlobalPermissionAsync(string username, PermissionFlags flag)
|
||||||
|
{
|
||||||
|
var roles = await GetUserRolesAsync(username);
|
||||||
|
return roles.Any(r =>
|
||||||
|
r.Permissions.HasFlag(PermissionFlags.Administrator) ||
|
||||||
|
r.Permissions.HasFlag(flag));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// "Was this permission explicitly denied here?" — used by default-allow permissions
|
||||||
|
/// (ViewChannel, Speak) which only become restrictive when there's a Deny override.
|
||||||
|
/// </summary>
|
||||||
|
private async Task<bool> IsDeniedByChannelAsync(string username, string channelId, PermissionFlags flag)
|
||||||
|
{
|
||||||
|
var userRoles = await GetUserRolesAsync(username);
|
||||||
|
if (userRoles.Count == 0) return false;
|
||||||
|
|
||||||
|
var channelOverrides = await GetChannelPermissionsAsync(channelId);
|
||||||
|
var userRoleIds = new HashSet<string>(userRoles.Select(r => GetRecordIdString(r.Id)));
|
||||||
|
|
||||||
|
return channelOverrides
|
||||||
|
.Where(co => userRoleIds.Contains(co.RoleId))
|
||||||
|
.Any(co => co.Deny.HasFlag(flag));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Checks ServerMembers.IsOwner directly. This is the authoritative ownership test —
|
||||||
|
/// independent of the role table, so ownership keeps working even if roles aren't seeded.
|
||||||
|
/// </summary>
|
||||||
|
private async Task<bool> IsServerOwnerAsync(string username)
|
||||||
|
{
|
||||||
|
var userId = $"users:{username.ToLower()}";
|
||||||
|
var members = await _db.Select<ServerMembers>("server_members");
|
||||||
|
return members.Any(m =>
|
||||||
|
string.Equals(m.UserId, userId, StringComparison.OrdinalIgnoreCase) &&
|
||||||
|
m.IsOwner);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Loads every Role row currently assigned to the user via UserRoles. Empty list if the
|
||||||
|
/// user has no role assignments (which means they implicitly fail every permission check
|
||||||
|
/// unless they happen to be the server owner).
|
||||||
|
/// </summary>
|
||||||
|
private async Task<List<Roles>> GetUserRolesAsync(string username)
|
||||||
|
{
|
||||||
|
var userId = $"users:{username.ToLower()}";
|
||||||
|
|
||||||
|
var userRoleLinks = await _db.Select<UserRoles>("user_roles");
|
||||||
|
var userRoleIds = userRoleLinks
|
||||||
|
.Where(ur => string.Equals(ur.UserId, userId, StringComparison.OrdinalIgnoreCase))
|
||||||
|
.Select(ur => ur.RoleId)
|
||||||
|
.ToHashSet();
|
||||||
|
|
||||||
|
if (userRoleIds.Count == 0) return [];
|
||||||
|
|
||||||
|
var allRoles = await _db.Select<Roles>("roles");
|
||||||
|
return allRoles
|
||||||
|
.Where(r => userRoleIds.Contains(GetRecordIdString(r.Id)))
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Loads every channel_permissions override row for a channel (all roles, all flags).</summary>
|
||||||
|
private async Task<List<ChannelPermissions>> GetChannelPermissionsAsync(string channelId)
|
||||||
|
{
|
||||||
|
var all = await _db.Select<ChannelPermissions>("channel_permissions");
|
||||||
|
return all.Where(cp => cp.ChannelId == channelId).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>True if the channel's IsReadOnly flag is set on its row in the channels table.</summary>
|
||||||
|
private async Task<bool> IsChannelReadOnlyAsync(string channelId)
|
||||||
|
{
|
||||||
|
var channels = await _db.Select<Channels>("channels");
|
||||||
|
var channel = channels.FirstOrDefault(c => GetRecordIdString(c.Id) == channelId);
|
||||||
|
return channel?.IsReadOnly ?? false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>SurrealDB's Id object → "table:id" string. Local copy because PermissionService isn't a friend of ChatSocketBehavior.</summary>
|
||||||
|
private static string GetRecordIdString(object? id)
|
||||||
|
{
|
||||||
|
if (id is null) return string.Empty;
|
||||||
|
var json = System.Text.Json.JsonSerializer.Serialize(id);
|
||||||
|
using var doc = System.Text.Json.JsonDocument.Parse(json);
|
||||||
|
var root = doc.RootElement;
|
||||||
|
var recordId = root.GetProperty("Id").GetString() ?? string.Empty;
|
||||||
|
var table = root.GetProperty("Table").GetString() ?? string.Empty;
|
||||||
|
return $"{table}:{recordId}";
|
||||||
|
}
|
||||||
|
}
|
||||||
21
RelayServer/Services/Data/SurrealService.cs
Normal file
21
RelayServer/Services/Data/SurrealService.cs
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
using SurrealDb.Net;
|
||||||
|
using SurrealDb.Net.Models.Auth;
|
||||||
|
|
||||||
|
namespace RelayServer.Services.Data;
|
||||||
|
|
||||||
|
public sealed class SurrealService
|
||||||
|
{
|
||||||
|
public async Task<SurrealDbClient> ConnectAsync()
|
||||||
|
{
|
||||||
|
var db = new SurrealDbClient("ws://127.0.0.1:8000/rpc");
|
||||||
|
|
||||||
|
await db.SignIn(new RootAuth
|
||||||
|
{
|
||||||
|
Username = "root",
|
||||||
|
Password = "secret"
|
||||||
|
});
|
||||||
|
|
||||||
|
await db.Use("test", "test");
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
}
|
||||||
253
RelayServer/Services/Rtc/RtcCallService.cs
Normal file
253
RelayServer/Services/Rtc/RtcCallService.cs
Normal file
@@ -0,0 +1,253 @@
|
|||||||
|
using RelayShared.Rtc;
|
||||||
|
using SurrealDb.Net;
|
||||||
|
using RelayShared.Rtc;
|
||||||
|
|
||||||
|
namespace RelayServer.Services.Rtc;
|
||||||
|
|
||||||
|
public sealed class RtcCallService
|
||||||
|
{
|
||||||
|
private readonly SurrealDbClient _db;
|
||||||
|
|
||||||
|
public RtcCallService(SurrealDbClient db)
|
||||||
|
{
|
||||||
|
_db = db;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Checks whether the specified channel currently has an active RTC call.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="channelId">The channel to inspect.</param>
|
||||||
|
/// <returns>
|
||||||
|
/// True if the channel has an active call; otherwise, false.
|
||||||
|
/// </returns>
|
||||||
|
public async Task<bool> HasActiveCallAsync(string channelId)
|
||||||
|
{
|
||||||
|
var activeCalls = await _db.Select<DBActiveCall>("rtc_active_calls");
|
||||||
|
return activeCalls.Any(x => x.ChannelId == channelId && x.IsActive);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<DBActiveCall?> GetActiveCallAsync(string channelId)
|
||||||
|
{
|
||||||
|
var activeCalls = await _db.Select<DBActiveCall>("rtc_active_calls");
|
||||||
|
return activeCalls
|
||||||
|
.Where(x => x.ChannelId == channelId && x.IsActive)
|
||||||
|
.OrderByDescending(x => x.UpdatedAt)
|
||||||
|
.FirstOrDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Creates or updates the current SDP offer for a user in the specified channel.
|
||||||
|
/// If no active call exists for the channel, a new active call is created.
|
||||||
|
/// Otherwise, the existing active call timestamp is refreshed.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="channelId">The channel the offer belongs to.</param>
|
||||||
|
/// <param name="username">The user creating the offer.</param>
|
||||||
|
/// <param name="type">The RtcSession Type. </param>
|
||||||
|
/// <param name="sdp">The SDP offer payload.</param>
|
||||||
|
public async Task WriteOfferAsync(string channelId, string username, RtcSessionDescription sessionDescription)
|
||||||
|
{
|
||||||
|
var activeCalls = await _db.Select<DBActiveCall>("rtc_active_calls");
|
||||||
|
var activeCall = activeCalls.FirstOrDefault(x => x.ChannelId == channelId && x.IsActive);
|
||||||
|
|
||||||
|
if (activeCall is null)
|
||||||
|
{
|
||||||
|
await _db.Create("rtc_active_calls", new DBActiveCall
|
||||||
|
{
|
||||||
|
ChannelId = channelId,
|
||||||
|
OfferUser = username,
|
||||||
|
Offer = new RtcSessionDescription
|
||||||
|
{
|
||||||
|
Type = sessionDescription.Type,
|
||||||
|
Sdp = sessionDescription.Sdp
|
||||||
|
},
|
||||||
|
Answer = null,
|
||||||
|
CreatedAt = DateTime.UtcNow,
|
||||||
|
UpdatedAt = DateTime.UtcNow,
|
||||||
|
IsActive = true
|
||||||
|
});
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
activeCall.OfferUser = username;
|
||||||
|
activeCall.Offer = new RtcSessionDescription
|
||||||
|
{
|
||||||
|
Type = sessionDescription.Type,
|
||||||
|
Sdp = sessionDescription.Sdp
|
||||||
|
};
|
||||||
|
activeCall.UpdatedAt = DateTime.UtcNow;
|
||||||
|
|
||||||
|
await _db.Merge<DBActiveCall, DBActiveCall>(activeCall);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the current offer stored on the active call for the specified channel.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="channelId">The channel whose offer should be retrieved.</param>
|
||||||
|
/// <returns>
|
||||||
|
/// The current offer for the active call, or null if no active call or offer exists.
|
||||||
|
/// </returns>
|
||||||
|
public async Task<RtcSessionDescription?> GetOfferAsync(string channelId)
|
||||||
|
{
|
||||||
|
var activeCall = await GetActiveCallAsync(channelId);
|
||||||
|
return activeCall?.Offer;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes a new SDP answer for the specified channel and refreshes the active call timestamp
|
||||||
|
/// when a matching active call exists.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="channelId">The channel the answer belongs to.</param>
|
||||||
|
/// <param name="offerUser">The original offer owner.</param>
|
||||||
|
/// <param name="sessionDescription">The SDP and type answer payload.</param>
|
||||||
|
public async Task WriteAnswerAsync(string channelId, RtcSessionDescription sessionDescription)
|
||||||
|
{
|
||||||
|
var activeCalls = await _db.Select<DBActiveCall>("rtc_active_calls");
|
||||||
|
var activeCall = activeCalls.FirstOrDefault(x => x.ChannelId == channelId && x.IsActive);
|
||||||
|
|
||||||
|
if (activeCall is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
activeCall.Answer = new RtcSessionDescription
|
||||||
|
{
|
||||||
|
Type = sessionDescription.Type,
|
||||||
|
Sdp = sessionDescription.Sdp
|
||||||
|
};
|
||||||
|
activeCall.UpdatedAt = DateTime.UtcNow;
|
||||||
|
|
||||||
|
await _db.Merge<DBActiveCall, DBActiveCall>(activeCall);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets all answers stored for the specified channel in creation order.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="channelId">The channel whose answers should be retrieved.</param>
|
||||||
|
/// <returns>
|
||||||
|
/// A list of answers for the channel ordered from oldest to newest.
|
||||||
|
/// </returns>
|
||||||
|
public async Task<List<RtcSessionDescription>> GetAnswersAsync(string channelId)
|
||||||
|
{
|
||||||
|
var activeCall = await GetActiveCallAsync(channelId);
|
||||||
|
|
||||||
|
if (activeCall?.Answer is null)
|
||||||
|
return [];
|
||||||
|
|
||||||
|
return [activeCall.Answer];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the most recent answer stored for the specified channel.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="channelId">The channel whose latest answer should be retrieved.</param>
|
||||||
|
/// <returns>
|
||||||
|
/// The newest answer for the channel, or null if no answer exists.
|
||||||
|
/// </returns>
|
||||||
|
public async Task<RtcSessionDescription?> GetLatestAnswerAsync(string channelId)
|
||||||
|
{
|
||||||
|
var activeCall = await GetActiveCallAsync(channelId);
|
||||||
|
return activeCall?.Answer;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes a new ICE candidate entry for the specified channel and user.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="channelId">The channel the ICE candidate belongs to.</param>
|
||||||
|
/// <param name="username">The user who produced the ICE candidate.</param>
|
||||||
|
/// <param name="candidate">The ICE candidate string.</param>
|
||||||
|
/// <param name="sdpMid">The SDP media identifier for the candidate, if any.</param>
|
||||||
|
/// <param name="sdpMLineIndex">The SDP media line index for the candidate, if any.</param>
|
||||||
|
/// <param name="direction">
|
||||||
|
/// The signaling direction the candidate belongs to, such as offer or answer.
|
||||||
|
/// </param>
|
||||||
|
public async Task WriteIceCandidateAsync(
|
||||||
|
string channelId,
|
||||||
|
string username,
|
||||||
|
string candidate,
|
||||||
|
string? sdpMid,
|
||||||
|
int? sdpMLineIndex/*,
|
||||||
|
string direction*/)
|
||||||
|
{
|
||||||
|
await _db.Create("rtc_ice_candidates", new DBIceCandidate
|
||||||
|
{
|
||||||
|
ChannelId = channelId,
|
||||||
|
Username = username,
|
||||||
|
Candidate = candidate,
|
||||||
|
SdpMid = sdpMid,
|
||||||
|
SdpMLineIndex = sdpMLineIndex,
|
||||||
|
// Direction = direction,
|
||||||
|
CreatedAt = DateTime.UtcNow
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets all ICE candidates stored for the specified channel in creation order.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="channelId">The channel whose ICE candidates should be retrieved.</param>
|
||||||
|
/// <returns>
|
||||||
|
/// A list of ICE candidates for the channel ordered from oldest to newest.
|
||||||
|
/// </returns>
|
||||||
|
public async Task<List<DBIceCandidate>> GetIceCandidatesAsync(string channelId)
|
||||||
|
{
|
||||||
|
var candidates = await _db.Select<DBIceCandidate>("rtc_ice_candidates");
|
||||||
|
return candidates
|
||||||
|
.Where(x => x.ChannelId == channelId)
|
||||||
|
.OrderBy(x => x.CreatedAt)
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets ICE candidates for the specified channel that were created by other users
|
||||||
|
/// and match the requested signaling direction.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="channelId">The channel whose ICE candidates should be retrieved.</param>
|
||||||
|
/// <param name="username">The user to exclude from the results.</param>
|
||||||
|
/// <param name="direction">The signaling direction to match.</param>
|
||||||
|
/// <returns>
|
||||||
|
/// A list of matching ICE candidates ordered from oldest to newest.
|
||||||
|
/// </returns>
|
||||||
|
public async Task<List<DBIceCandidate>> GetIceCandidatesForOthersAsync(string channelId, string username, string direction)
|
||||||
|
{
|
||||||
|
var candidates = await _db.Select<DBIceCandidate>("rtc_ice_candidates");
|
||||||
|
return candidates
|
||||||
|
.Where(x => x.ChannelId == channelId && x.Username != username /*&& x.Direction == direction*/)
|
||||||
|
.OrderBy(x => x.CreatedAt)
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Leaves the active call for the specified channel. In the current implementation,
|
||||||
|
/// the call is only marked inactive when the offer user leaves.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="channelId">The channel whose call should be left.</param>
|
||||||
|
/// <param name="username">The user leaving the call.</param>
|
||||||
|
public async Task LeaveCallAsync(string channelId, string username)
|
||||||
|
{
|
||||||
|
var activeCalls = await _db.Select<DBActiveCall>("rtc_active_calls");
|
||||||
|
var activeCall = activeCalls.FirstOrDefault(x => x.ChannelId == channelId && x.IsActive);
|
||||||
|
|
||||||
|
if (activeCall is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (activeCall.OfferUser == username)
|
||||||
|
{
|
||||||
|
activeCall.IsActive = false;
|
||||||
|
activeCall.UpdatedAt = DateTime.UtcNow;
|
||||||
|
await _db.Merge<DBActiveCall, DBActiveCall>(activeCall);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Gets all active call records that currently contain an offer.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>
|
||||||
|
/// A list of active calls with offers, ordered from newest to oldest.
|
||||||
|
/// </returns>
|
||||||
|
public async Task<List<DBActiveCall>> GetOffersAsync()
|
||||||
|
{
|
||||||
|
var activeCalls = await _db.Select<DBActiveCall>("rtc_active_calls");
|
||||||
|
return activeCalls
|
||||||
|
.Where(x => x.Offer is not null)
|
||||||
|
.OrderByDescending(x => x.UpdatedAt)
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
}
|
||||||
67
RelayServer/Services/Rtc/RtcChannelPresenceService.cs
Normal file
67
RelayServer/Services/Rtc/RtcChannelPresenceService.cs
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
|
||||||
|
namespace RelayServer.Services.Rtc;
|
||||||
|
|
||||||
|
public static class RtcChannelPresenceService
|
||||||
|
{
|
||||||
|
private static readonly ConcurrentDictionary<string, string> SessionToChannel = new();
|
||||||
|
private static readonly ConcurrentDictionary<string, string> SessionToUsername = new();
|
||||||
|
|
||||||
|
public static void SetUser(string sessionId, string username)
|
||||||
|
{
|
||||||
|
SessionToUsername[sessionId] = username;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void JoinChannel(string sessionId, string channelId)
|
||||||
|
{
|
||||||
|
SessionToChannel[sessionId] = channelId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void LeaveChannel(string sessionId)
|
||||||
|
{
|
||||||
|
SessionToChannel.TryRemove(sessionId, out _);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void RemoveSession(string sessionId)
|
||||||
|
{
|
||||||
|
SessionToChannel.TryRemove(sessionId, out _);
|
||||||
|
SessionToUsername.TryRemove(sessionId, out _);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IReadOnlyList<string> GetSessionsInChannel(string channelId)
|
||||||
|
{
|
||||||
|
return SessionToChannel
|
||||||
|
.Where(x => x.Value == channelId)
|
||||||
|
.Select(x => x.Key)
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<string> GetUsernamesInChannel(string channelId)
|
||||||
|
{
|
||||||
|
return GetUsersInChannel(channelId).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IReadOnlyList<string> GetUsersInChannel(string channelId)
|
||||||
|
{
|
||||||
|
var sessionIds = GetSessionsInChannel(channelId);
|
||||||
|
|
||||||
|
return sessionIds
|
||||||
|
.Where(id => SessionToUsername.ContainsKey(id))
|
||||||
|
.Select(id => SessionToUsername[id])
|
||||||
|
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||||
|
.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool IsInChannel(string sessionId, string channelId)
|
||||||
|
{
|
||||||
|
return SessionToChannel.TryGetValue(sessionId, out var currentChannel) &&
|
||||||
|
string.Equals(currentChannel, channelId, StringComparison.Ordinal);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string? GetUsernameForSession(string sessionId)
|
||||||
|
{
|
||||||
|
return SessionToUsername.TryGetValue(sessionId, out var username)
|
||||||
|
? username
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
}
|
||||||
28
RelayServer/Services/Rtc/RtcNotificationService.cs
Normal file
28
RelayServer/Services/Rtc/RtcNotificationService.cs
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using RelayShared.Rtc;
|
||||||
|
using WebSocketSharp.Server;
|
||||||
|
|
||||||
|
namespace RelayServer.Services.Rtc;
|
||||||
|
|
||||||
|
public static class RtcNotificationService
|
||||||
|
{
|
||||||
|
public static WebSocketServer? Server { get; set; }
|
||||||
|
|
||||||
|
public static void BroadcastToChannel(RtcNotificationMessage message)
|
||||||
|
{
|
||||||
|
if (Server is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var host = Server.WebSocketServices["/"];
|
||||||
|
if (host is null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var json = JsonSerializer.Serialize(message);
|
||||||
|
var sessionIds = RtcChannelPresenceService.GetSessionsInChannel(message.ChannelId);
|
||||||
|
|
||||||
|
foreach (var sessionId in sessionIds)
|
||||||
|
{
|
||||||
|
host.Sessions.SendTo(json, sessionId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
93
RelayShared/.gitignore
vendored
Normal file
93
RelayShared/.gitignore
vendored
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
############################################
|
||||||
|
# .NET Build
|
||||||
|
############################################
|
||||||
|
|
||||||
|
bin/
|
||||||
|
obj/
|
||||||
|
out/
|
||||||
|
publish/
|
||||||
|
|
||||||
|
############################################
|
||||||
|
# Visual Studio
|
||||||
|
############################################
|
||||||
|
|
||||||
|
.vs/
|
||||||
|
*.user
|
||||||
|
*.suo
|
||||||
|
*.userprefs
|
||||||
|
*.csproj.user
|
||||||
|
*.dbmdl
|
||||||
|
*.cache
|
||||||
|
*.pdb
|
||||||
|
*.opendb
|
||||||
|
|
||||||
|
############################################
|
||||||
|
# Rider / JetBrains
|
||||||
|
############################################
|
||||||
|
|
||||||
|
.idea/
|
||||||
|
*.sln.iml
|
||||||
|
|
||||||
|
############################################
|
||||||
|
# VSCode
|
||||||
|
############################################
|
||||||
|
|
||||||
|
.vscode/
|
||||||
|
|
||||||
|
############################################
|
||||||
|
# NuGet
|
||||||
|
############################################
|
||||||
|
|
||||||
|
*.nupkg
|
||||||
|
*.snupkg
|
||||||
|
packages/
|
||||||
|
.nuget/
|
||||||
|
.nuget/packages/
|
||||||
|
|
||||||
|
############################################
|
||||||
|
# Logs
|
||||||
|
############################################
|
||||||
|
|
||||||
|
*.log
|
||||||
|
logs/
|
||||||
|
|
||||||
|
############################################
|
||||||
|
# OS files
|
||||||
|
############################################
|
||||||
|
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
############################################
|
||||||
|
# Local secrets / environment
|
||||||
|
############################################
|
||||||
|
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
secrets.json
|
||||||
|
appsettings.Development.json
|
||||||
|
|
||||||
|
############################################
|
||||||
|
# E2EE private keys
|
||||||
|
############################################
|
||||||
|
|
||||||
|
keys/*
|
||||||
|
!keys/.gitkeep
|
||||||
|
|
||||||
|
############################################
|
||||||
|
# Local test databases / data folders
|
||||||
|
############################################
|
||||||
|
|
||||||
|
data/
|
||||||
|
*.db
|
||||||
|
*.sqlite
|
||||||
|
*.sqlite3
|
||||||
|
|
||||||
|
############################################
|
||||||
|
# Temporary files
|
||||||
|
############################################
|
||||||
|
|
||||||
|
*.tmp
|
||||||
|
*.temp
|
||||||
|
*.bak
|
||||||
|
*.swp
|
||||||
9
RelayShared/Class1.cs
Normal file
9
RelayShared/Class1.cs
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
namespace RelayShared;
|
||||||
|
|
||||||
|
public class Class1
|
||||||
|
{
|
||||||
|
public Class1()
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
13
RelayShared/RelayShared.csproj
Normal file
13
RelayShared/RelayShared.csproj
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net9.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="SurrealDb.Net" Version="0.9.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
40
RelayShared/Rtc/RTCDatabase.cs
Normal file
40
RelayShared/Rtc/RTCDatabase.cs
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayShared.Rtc;
|
||||||
|
|
||||||
|
public sealed class DBActiveCall : Record
|
||||||
|
{
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
public string? OfferUser { get; set; }
|
||||||
|
public RtcSessionDescription? Offer { get; set; }
|
||||||
|
public RtcSessionDescription? Answer { get; set; }
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
public DateTime UpdatedAt { get; set; }
|
||||||
|
public bool IsActive { get; set; }
|
||||||
|
public string[] IceCandidates { get; set; } = []; //TODO: Should be array of DBIceCandidates IDs
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class DBOffer : Record
|
||||||
|
{
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
public string Type { get; set; } = string.Empty;
|
||||||
|
public string Sdp { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
public sealed class DBAnswer : Record
|
||||||
|
{
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
public string Type { get; set; } = string.Empty;
|
||||||
|
public string Sdp { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public class DBIceCandidate : Record
|
||||||
|
{
|
||||||
|
public required string ChannelId { get; set; }
|
||||||
|
public required string Username { get; set; }
|
||||||
|
public required string Candidate { get; set; }
|
||||||
|
public string? SdpMid { get; set; }
|
||||||
|
public int? SdpMLineIndex { get; set; }
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
}
|
||||||
93
RelayShared/Rtc/RTCTransmissions.cs
Normal file
93
RelayShared/Rtc/RTCTransmissions.cs
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
using System.Text.Json.Serialization;
|
||||||
|
using RelayShared.Services;
|
||||||
|
|
||||||
|
namespace RelayShared.Rtc;
|
||||||
|
|
||||||
|
public sealed class RtcSessionDescription
|
||||||
|
{
|
||||||
|
public string Type { get; set; } = string.Empty;
|
||||||
|
public string Sdp { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class RtcOffer
|
||||||
|
{
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
public RtcSessionDescription SessionDescription { get; set; } = new();
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class RtcAnswer
|
||||||
|
{
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
public RtcSessionDescription SessionDescription { get; set; } = new();
|
||||||
|
}
|
||||||
|
public class RtcIceCandidate
|
||||||
|
{
|
||||||
|
public required string ChannelId { get; set; }
|
||||||
|
public required string Username { get; set; }
|
||||||
|
public required IceCandidate Candidate { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class IceCandidate
|
||||||
|
{
|
||||||
|
public required string candidate { get; set; }
|
||||||
|
public required string sdpMid { get; set; }
|
||||||
|
public required int sdpMLineIndex { get; set; }
|
||||||
|
public required string usernameFragment { get; set; }
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class RtcJoinRequest
|
||||||
|
{
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class RtcJoinResponse
|
||||||
|
{
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
public string[] Participants { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class RtcLeaveRequest
|
||||||
|
{
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
public sealed class RtcNotificationMessage //TODO: Review for removal
|
||||||
|
{
|
||||||
|
public SignalType? Type { get; set; }
|
||||||
|
public string? ChannelId { get; set; }
|
||||||
|
public string? Username { get; set; }
|
||||||
|
public string? Direction { get; set; }
|
||||||
|
}
|
||||||
|
public sealed class RtcSignalMessage //TODO: Review for removal.
|
||||||
|
{
|
||||||
|
[JsonPropertyName("type")]
|
||||||
|
public string Type { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonPropertyName("from")]
|
||||||
|
public string From { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonPropertyName("to")]
|
||||||
|
public string To { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonPropertyName("channelId")]
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
[JsonPropertyName("sdp")]
|
||||||
|
public string? Sdp { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("candidate")]
|
||||||
|
public string? Candidate { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("sdpMid")]
|
||||||
|
public string? SdpMid { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("sdpMLineIndex")]
|
||||||
|
public int? SdpMLineIndex { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("isInitiator")]
|
||||||
|
public bool IsInitiator { get; set; }
|
||||||
|
}
|
||||||
6
RelayShared/Rtc/RtcServices.cs
Normal file
6
RelayShared/Rtc/RtcServices.cs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
namespace RelayShared.Rtc;
|
||||||
|
|
||||||
|
public class RtcServices
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
40
RelayShared/Services/Authentication.cs
Normal file
40
RelayShared/Services/Authentication.cs
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
namespace RelayShared.Services;
|
||||||
|
|
||||||
|
public class AuthSignin
|
||||||
|
{
|
||||||
|
public string UserName { get; set; }
|
||||||
|
public string Password { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AuthRegister
|
||||||
|
{
|
||||||
|
public string Username { get; set; }
|
||||||
|
public string Password { get; set; }
|
||||||
|
public string Email { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AuthUserVerify
|
||||||
|
{
|
||||||
|
public string Username { get; set; }
|
||||||
|
public string Token { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AuthServerLicenseVerify
|
||||||
|
{
|
||||||
|
public string License { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class AuthServerLicenseGenerate
|
||||||
|
{
|
||||||
|
public string Server { get; set; }
|
||||||
|
public string Length {get; set;} //TODO: Convert to Enum
|
||||||
|
}
|
||||||
|
|
||||||
|
public class DBLicense
|
||||||
|
{
|
||||||
|
public string Token {get; set;}
|
||||||
|
public bool IsClient {get; set;}
|
||||||
|
public DateTime CreatedAt {get; set;}
|
||||||
|
public DateTime ExpiresAt {get; set;}
|
||||||
|
public bool IsExpired {get; set;}
|
||||||
|
}
|
||||||
23
RelayShared/Services/ChannelEnums.cs
Normal file
23
RelayShared/Services/ChannelEnums.cs
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
namespace RelayShared.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Drives both rendering (sidebar icon, message view vs RTC view) and server-side routing
|
||||||
|
/// (file mirror destination must be ChannelType.File, RTC join only on Voice/Stage).
|
||||||
|
/// </summary>
|
||||||
|
public enum ChannelType
|
||||||
|
{
|
||||||
|
/// <summary>Default. Linear chat: text, markdown, embeds, attachments. Sidebar prefix "#".</summary>
|
||||||
|
Text,
|
||||||
|
|
||||||
|
/// <summary>WebRTC voice/video. Sidebar prefix 🔊. Selecting auto-swaps to the RTC view.</summary>
|
||||||
|
Voice,
|
||||||
|
|
||||||
|
/// <summary>File browser. Receives auto-mirrored attachments from any Text channel that points here via LinkedFileChannelId. Sidebar prefix 📁.</summary>
|
||||||
|
File,
|
||||||
|
|
||||||
|
/// <summary>Forum-style threaded posts. Sidebar prefix 📋. Currently a placeholder type.</summary>
|
||||||
|
Forum,
|
||||||
|
|
||||||
|
/// <summary>Announcement-style voice. Modified WebRTC where most participants are listeners. Sidebar prefix 🎤. Placeholder.</summary>
|
||||||
|
Stage
|
||||||
|
}
|
||||||
44
RelayShared/Services/ChannelTransmissions.cs
Normal file
44
RelayShared/Services/ChannelTransmissions.cs
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
namespace RelayShared.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One row in the sidebar channel list. The server computes the permission-derived fields
|
||||||
|
/// (CanPost, CanManage) per-user so the client never has to evaluate permissions itself.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ChannelItem
|
||||||
|
{
|
||||||
|
/// <summary>Surreal record id (e.g. "channels:abc").</summary>
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Sidebar display name ("general", "welcome", etc.).</summary>
|
||||||
|
public string Name { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Drives icon and behavior: Text/Voice/File/Forum/Stage.</summary>
|
||||||
|
public ChannelType Type { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Sidebar category label (e.g. "General"). Empty groups fall under a default "Channels" header.</summary>
|
||||||
|
public string Group { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Creation timestamp. Drives sidebar sort order (oldest → newest).</summary>
|
||||||
|
public DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
|
/// <summary>True if the channel is announcement-style (welcome, files). Drives the 🔒 suffix in the sidebar.</summary>
|
||||||
|
public bool IsReadOnly { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Permission-resolved: can the receiving user send messages here. Drives input enable/disable.</summary>
|
||||||
|
public bool CanPost { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Permission-resolved: can the receiving user edit/delete this channel. Drives context-menu visibility.</summary>
|
||||||
|
public bool CanManage { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Server-to-client channel list. Sent in response to WsAction.GetChannels and broadcast
|
||||||
|
/// to all sessions after every channel create / delete.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class SocketChannelList
|
||||||
|
{
|
||||||
|
public SignalType Type { get; set; } = SignalType.ChannelList;
|
||||||
|
|
||||||
|
/// <summary>Channels the receiving user is allowed to view. Permission filtering happens server-side.</summary>
|
||||||
|
public List<ChannelItem> Channels { get; set; } = [];
|
||||||
|
}
|
||||||
43
RelayShared/Services/ChatMessageContent.cs
Normal file
43
RelayShared/Services/ChatMessageContent.cs
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
namespace RelayShared.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The plaintext payload of a chat message before E2E encryption is applied.
|
||||||
|
///
|
||||||
|
/// Lifecycle of a message:
|
||||||
|
/// 1. Client builds a ChatMessageContent (text + optional reply/attachment/mentions).
|
||||||
|
/// 2. Client JSON-serialises it, encrypts with the server's public key (RSA wrapping an
|
||||||
|
/// AES-GCM key), and sends the encrypted blob wrapped in a SocketEncryptedMessage.
|
||||||
|
/// 3. Server decrypts with its private key, re-encrypts with the channel DB key, stores it.
|
||||||
|
/// 4. For each recipient, server decrypts from DB key and re-encrypts with that recipient's
|
||||||
|
/// public key, then delivers via SocketEncryptedMessage.
|
||||||
|
/// 5. Recipient decrypts with their private key and JSON-deserialises back to ChatMessageContent.
|
||||||
|
///
|
||||||
|
/// This type is intentionally shared by RelayClient and RelayServer so both ends agree on the
|
||||||
|
/// JSON shape. Adding a field here lights up the whole pipeline automatically.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ChatMessageContent
|
||||||
|
{
|
||||||
|
/// <summary>The raw message body, including Markdown syntax and @mentions.</summary>
|
||||||
|
public string Text { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>When set, this message is a reply. Carries the Surreal record id of the message being replied to.</summary>
|
||||||
|
public string? ReplyToId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Display name of the user being replied to. Lets the client render the quote bar without a lookup.</summary>
|
||||||
|
public string? ReplyToSenderUsername { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Trimmed preview of the replied-to text (≤100 chars). Captured at send time so the server never has to look it up.</summary>
|
||||||
|
public string? ReplyPreview { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Extracted usernames + special tokens ("everyone", "here"). Drives the ping-badge in the sidebar.</summary>
|
||||||
|
public List<string>? Mentions { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Base64-encoded attachment bytes. Null when there's no attachment.</summary>
|
||||||
|
public string? AttachmentBase64 { get; set; }
|
||||||
|
|
||||||
|
/// <summary>MIME type of the attachment (e.g. "image/png"). Used to choose between BuildBase64ImageEmbed and BuildFileCard.</summary>
|
||||||
|
public string? AttachmentMimeType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Original filename as chosen by the sender. Shown as the file card label and used for the download path.</summary>
|
||||||
|
public string? AttachmentFileName { get; set; }
|
||||||
|
}
|
||||||
38
RelayShared/Services/ConsoleCommandService.cs
Normal file
38
RelayShared/Services/ConsoleCommandService.cs
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
namespace RelayShared.Services;
|
||||||
|
|
||||||
|
public static class ConsoleCommandService
|
||||||
|
{
|
||||||
|
public static CancellationTokenSource ShutdownTokenSource { get; } = new();
|
||||||
|
|
||||||
|
public static void Start()
|
||||||
|
{
|
||||||
|
Task.Run(() =>
|
||||||
|
{
|
||||||
|
while (!ShutdownTokenSource.IsCancellationRequested)
|
||||||
|
{
|
||||||
|
var input = Console.ReadLine();
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(input))
|
||||||
|
continue;
|
||||||
|
|
||||||
|
HandleCommand(input.Trim().ToLower());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void HandleCommand(string command)
|
||||||
|
{
|
||||||
|
switch (command)
|
||||||
|
{
|
||||||
|
case "exit":
|
||||||
|
case "stop":
|
||||||
|
Console.WriteLine("Shutting down...");
|
||||||
|
ShutdownTokenSource.Cancel();
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
Console.WriteLine($"Unknown command: {command}");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
198
RelayShared/Services/SocketTransmissions.cs
Normal file
198
RelayShared/Services/SocketTransmissions.cs
Normal file
@@ -0,0 +1,198 @@
|
|||||||
|
namespace RelayShared.Services;
|
||||||
|
|
||||||
|
//TODO: review name of file, potentially rename for Encryption services rather than sockets
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The "data plane" wire types for the WebSocket protocol.
|
||||||
|
///
|
||||||
|
/// Every type here carries a SignalType discriminator so a generic JsonDocument peek
|
||||||
|
/// can identify the variant. The server dispatches on SignalType in ChatSocketBehavior.OnMessage;
|
||||||
|
/// the client dispatches on it in RelaySocketClient.OnMessage.
|
||||||
|
///
|
||||||
|
/// Encrypted payloads share a uniform 4-tuple shape: (CipherText, Nonce, Tag, EncryptedKey).
|
||||||
|
/// That tuple is hybrid RSA+AES-GCM: EncryptedKey is the per-message AES key wrapped with the
|
||||||
|
/// recipient's RSA public key; CipherText/Nonce/Tag are the AES-GCM ciphertext, nonce, and
|
||||||
|
/// authentication tag for the actual JSON-serialised ChatMessageContent.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class SocketRtcSignalMessage
|
||||||
|
{
|
||||||
|
/// <summary>Always SignalType.EncryptedSignal in flight.</summary>
|
||||||
|
public SignalType Type { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Username of the user generating the SDP/ICE signal.</summary>
|
||||||
|
public string SenderUsername { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>The voice channel this signal belongs to.</summary>
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Base64 AES-GCM ciphertext of the JSON-serialised RtcSignalMessage.</summary>
|
||||||
|
public string CipherText { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Base64 AES-GCM 96-bit nonce.</summary>
|
||||||
|
public string Nonce { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Base64 AES-GCM 128-bit authentication tag.</summary>
|
||||||
|
public string Tag { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Base64 RSA-OAEP-encrypted AES key (encrypted with recipient's public key).</summary>
|
||||||
|
public string EncryptedKey { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The workhorse envelope for chat messages and message lifecycle events.
|
||||||
|
/// Used for both directions and for new sends / edits / delete tombstones.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class SocketEncryptedMessage
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// EncryptedChat (server→client), ClientEncryptedChat (client→server new message),
|
||||||
|
/// ClientEditMessage / ClientDeleteMessage (client→server lifecycle), MessageEdited (server→client).
|
||||||
|
/// </summary>
|
||||||
|
public SignalType Type { get; set; } = SignalType.EncryptedChat;
|
||||||
|
|
||||||
|
/// <summary>Surreal record id (e.g. "channel_messages:abc"). Populated by the server on outbound delivery.</summary>
|
||||||
|
public string MessageId { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Who wrote the message.</summary>
|
||||||
|
public string SenderUsername { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Who this specific delivery is encrypted for. Different per recipient on the same logical message.</summary>
|
||||||
|
public string RecipientUsername { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>The channel the message belongs to.</summary>
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Base64 AES-GCM ciphertext of the JSON-serialised ChatMessageContent. Empty on tombstone deliveries.</summary>
|
||||||
|
public string CipherText { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Base64 AES-GCM 96-bit nonce.</summary>
|
||||||
|
public string Nonce { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Base64 AES-GCM 128-bit authentication tag.</summary>
|
||||||
|
public string Tag { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Base64 RSA-OAEP-encrypted AES key (encrypted with recipient's public key on outbound, server's on inbound).</summary>
|
||||||
|
public string EncryptedKey { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>True when this message has been edited at least once. Drives the (edited) footer in the bubble.</summary>
|
||||||
|
public bool IsEdited { get; set; }
|
||||||
|
|
||||||
|
/// <summary>True for tombstone deliveries (history only). Client renders a placeholder; no decryption is attempted.</summary>
|
||||||
|
public bool IsDeleted { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Server-broadcast tombstone fired the moment a message is deleted. Carries no content —
|
||||||
|
/// recipients use MessageId to find the existing bubble and swap it to a "deleted" placeholder.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class SocketMessageDeletedEvent
|
||||||
|
{
|
||||||
|
public SignalType Type { get; set; } = SignalType.MessageDeleted;
|
||||||
|
|
||||||
|
/// <summary>The message being tombstoned.</summary>
|
||||||
|
public string MessageId { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Channel scope — clients that aren't viewing this channel can defer the bubble update.</summary>
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// "{Username} is typing…" hint. Server forwards to every connected member except the sender.
|
||||||
|
/// Client auto-clears the indicator 3 seconds after the last such event.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class SocketTypingEvent
|
||||||
|
{
|
||||||
|
public SignalType Type { get; set; } = SignalType.TypingIndicator;
|
||||||
|
|
||||||
|
/// <summary>Who is typing.</summary>
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Which channel they're typing in. Clients ignore events for channels they're not viewing.</summary>
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One historical version of an edited message, re-encrypted for the requester.</summary>
|
||||||
|
public sealed class SocketEditHistoryEntry
|
||||||
|
{
|
||||||
|
/// <summary>Base64 AES-GCM ciphertext of the JSON-serialised previous ChatMessageContent.</summary>
|
||||||
|
public string CipherText { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public string Nonce { get; set; } = string.Empty;
|
||||||
|
public string Tag { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Base64 RSA-OAEP-encrypted AES key (encrypted with requester's public key).</summary>
|
||||||
|
public string EncryptedKey { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>When this version was the current text (i.e. when it was replaced).</summary>
|
||||||
|
public DateTime EditedAt { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Server reply to a GetEditHistory request. Entries are ordered oldest→newest.</summary>
|
||||||
|
public sealed class SocketEditHistoryResponse
|
||||||
|
{
|
||||||
|
public SignalType Type { get; set; } = SignalType.EditHistory;
|
||||||
|
|
||||||
|
/// <summary>Which message this history is for.</summary>
|
||||||
|
public string MessageId { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>Every previous version of the message. Empty if the message has never been edited.</summary>
|
||||||
|
public List<SocketEditHistoryEntry> Entries { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Server-to-client delivery of the server's public RSA key. Sent once per session in
|
||||||
|
/// response to WsAction.GetServerKey. Clients cache this for all outbound encryption.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ServerPublicKeyMessage
|
||||||
|
{
|
||||||
|
public SignalType Type { get; set; } = SignalType.ServerPublicKey;
|
||||||
|
|
||||||
|
/// <summary>Base64 SubjectPublicKeyInfo (DER) of the server's RSA public key.</summary>
|
||||||
|
public string PublicKey { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The wire discriminator for every data-plane Socket*Message.</summary>
|
||||||
|
public enum SignalType
|
||||||
|
{
|
||||||
|
// RTC SDP/ICE wire types (used by the WebView RTC engine, not handled directly here)
|
||||||
|
Offer,
|
||||||
|
Answer,
|
||||||
|
Candidate,
|
||||||
|
OfferUpdated,
|
||||||
|
AnswerUpdated,
|
||||||
|
CandidateAdded,
|
||||||
|
CallLeft,
|
||||||
|
|
||||||
|
/// <summary>Server→client: paginated channel list (SocketChannelList).</summary>
|
||||||
|
ChannelList,
|
||||||
|
|
||||||
|
/// <summary>Server→client: ServerPublicKeyMessage delivery.</summary>
|
||||||
|
ServerPublicKey,
|
||||||
|
|
||||||
|
/// <summary>Bidirectional: encrypted RTC SDP/ICE signal (SocketRtcSignalMessage).</summary>
|
||||||
|
EncryptedSignal,
|
||||||
|
|
||||||
|
/// <summary>Server→client: delivered chat message (SocketEncryptedMessage).</summary>
|
||||||
|
EncryptedChat,
|
||||||
|
|
||||||
|
/// <summary>Client→server: new chat message send (SocketEncryptedMessage).</summary>
|
||||||
|
ClientEncryptedChat,
|
||||||
|
|
||||||
|
/// <summary>Client→server: request to edit own message (SocketEncryptedMessage with new content).</summary>
|
||||||
|
ClientEditMessage,
|
||||||
|
|
||||||
|
/// <summary>Client→server: request to delete own message (SocketEncryptedMessage with only MessageId).</summary>
|
||||||
|
ClientDeleteMessage,
|
||||||
|
|
||||||
|
/// <summary>Server→clients: edit broadcast carrying re-encrypted new content (SocketEncryptedMessage).</summary>
|
||||||
|
MessageEdited,
|
||||||
|
|
||||||
|
/// <summary>Server→clients: deletion tombstone (SocketMessageDeletedEvent).</summary>
|
||||||
|
MessageDeleted,
|
||||||
|
|
||||||
|
/// <summary>Server→peers: typing indicator (SocketTypingEvent).</summary>
|
||||||
|
TypingIndicator,
|
||||||
|
|
||||||
|
/// <summary>Server→requester: edit-history response (SocketEditHistoryResponse).</summary>
|
||||||
|
EditHistory
|
||||||
|
}
|
||||||
111
RelayShared/Services/WsControlMessage.cs
Normal file
111
RelayShared/Services/WsControlMessage.cs
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
namespace RelayShared.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// JSON-dispatch contract for the WebSocket "control plane" (non-encrypted,
|
||||||
|
/// non-realtime requests like auth, key registration, channel CRUD, history fetches).
|
||||||
|
///
|
||||||
|
/// The server's ChatSocketBehavior.OnMessage looks at the first JSON property of every
|
||||||
|
/// incoming text frame:
|
||||||
|
/// - "Action" present → deserialise into WsControlMessage and dispatch on WsAction.
|
||||||
|
/// - "Type" present → deserialise into SocketEncryptedMessage/SocketRtcSignalMessage
|
||||||
|
/// and dispatch on SignalType (the "data plane" — chat messages,
|
||||||
|
/// RTC signals, edit/delete requests).
|
||||||
|
///
|
||||||
|
/// Responses come back as either WsEventMessage (for acks/errors) or one of the
|
||||||
|
/// Socket*Message types (for streaming data).
|
||||||
|
/// </summary>
|
||||||
|
public enum WsAction
|
||||||
|
{
|
||||||
|
/// <summary>Verify a Core-issued user token. Fields used: Username, Token.</summary>
|
||||||
|
Authenticate,
|
||||||
|
|
||||||
|
/// <summary>Register/update the client's RSA public key. Fields used: Username, PublicKey.</summary>
|
||||||
|
RegisterKey,
|
||||||
|
|
||||||
|
/// <summary>Request the server's public RSA key for outbound encryption. No fields.</summary>
|
||||||
|
GetServerKey,
|
||||||
|
|
||||||
|
/// <summary>Request the full channel list for this user. No fields.</summary>
|
||||||
|
GetChannels,
|
||||||
|
|
||||||
|
/// <summary>Request decrypted message history for a channel. Fields used: Username, ChannelId.</summary>
|
||||||
|
GetHistory,
|
||||||
|
|
||||||
|
/// <summary>Join a voice channel (presence tracking). Fields used: Username, ChannelId.</summary>
|
||||||
|
RtcJoin,
|
||||||
|
|
||||||
|
/// <summary>Leave a voice channel. Fields used: Username, ChannelId.</summary>
|
||||||
|
RtcLeave,
|
||||||
|
|
||||||
|
/// <summary>Broadcast "user is typing" to channel peers. Fields used: ChannelId.</summary>
|
||||||
|
SendTyping,
|
||||||
|
|
||||||
|
/// <summary>Request the edit-history chain for a specific message. Fields used: Username, MessageId, ChannelId.</summary>
|
||||||
|
GetEditHistory,
|
||||||
|
|
||||||
|
/// <summary>Create a new channel (permission-gated). Fields used: ChannelName, ChannelType, ChannelGroup.</summary>
|
||||||
|
CreateChannel,
|
||||||
|
|
||||||
|
/// <summary>Soft-delete a channel (permission-gated). Fields used: ChannelId.</summary>
|
||||||
|
DeleteChannel
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Server-to-client event types for acks and errors.</summary>
|
||||||
|
public enum WsEvent
|
||||||
|
{
|
||||||
|
/// <summary>Reply to Authenticate. Detail = username.</summary>
|
||||||
|
Authenticated,
|
||||||
|
|
||||||
|
/// <summary>Reply to RegisterKey. Detail = username.</summary>
|
||||||
|
KeyRegistered,
|
||||||
|
|
||||||
|
/// <summary>Generic error. Detail = human-readable reason shown to the user.</summary>
|
||||||
|
Error
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Control-plane envelope. All fields are nullable because each action only uses a subset
|
||||||
|
/// of them. Serialised as JSON; identified by the presence of the "Action" property.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class WsControlMessage
|
||||||
|
{
|
||||||
|
/// <summary>The action to perform. Server dispatches on this.</summary>
|
||||||
|
public WsAction Action { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Mixed-case username as the user typed it on sign-in. Server preserves casing for display.</summary>
|
||||||
|
public string? Username { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Core-issued auth token. Only set on Authenticate.</summary>
|
||||||
|
public string? Token { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Base64-encoded RSA public key. Only set on RegisterKey.</summary>
|
||||||
|
public string? PublicKey { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Surreal record id of a channel (e.g. "channels:xyz"). Used by most channel-scoped actions.</summary>
|
||||||
|
public string? ChannelId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Surreal record id of a message. Used by GetEditHistory.</summary>
|
||||||
|
public string? MessageId { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Channel name on create (e.g. "memes"). Server normalises to lowercase-dashes.</summary>
|
||||||
|
public string? ChannelName { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Integer cast of ChannelType enum (Text=0, Voice=1, …). Used on CreateChannel.</summary>
|
||||||
|
public int ChannelType { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Group/category label shown in the sidebar (e.g. "General"). Optional on CreateChannel.</summary>
|
||||||
|
public string? ChannelGroup { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Server-to-client ack envelope. Identified by the "Event" JSON property
|
||||||
|
/// (vs WsControlMessage's "Action" or Socket*Message's "Type").
|
||||||
|
/// </summary>
|
||||||
|
public sealed class WsEventMessage
|
||||||
|
{
|
||||||
|
/// <summary>Which event this is acknowledging.</summary>
|
||||||
|
public WsEvent Event { get; set; }
|
||||||
|
|
||||||
|
/// <summary>Human-readable context (username on success, error message on Error).</summary>
|
||||||
|
public string? Detail { get; set; }
|
||||||
|
}
|
||||||
47
UI Design Doc outline.md
Normal file
47
UI Design Doc outline.md
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
Server Profile:
|
||||||
|
- Server Name
|
||||||
|
- Server Image
|
||||||
|
- Selection Arrow
|
||||||
|
- Server specific settings (notifications, DMs, Admin settings link)
|
||||||
|
|
||||||
|
Member Server Settings: [shown only when selecting a member from member list]
|
||||||
|
- Settings for selected Member
|
||||||
|
- Mute and Deafen for voice channels
|
||||||
|
- Nickname editing
|
||||||
|
- Global Username
|
||||||
|
- View profile
|
||||||
|
- Member statuses (full length)
|
||||||
|
- Permissions editing (for admins)
|
||||||
|
|
||||||
|
User Profile and Channel Controls:
|
||||||
|
- User settings button
|
||||||
|
- Profile
|
||||||
|
- Mute and deafen for voice channels
|
||||||
|
- Connection details for voice call
|
||||||
|
- Disconnect for voice calls
|
||||||
|
- Share screens in voice channels
|
||||||
|
- Camera controls in voice channels
|
||||||
|
|
||||||
|
Members List:
|
||||||
|
- Member tile with Username/Nickname
|
||||||
|
- Status
|
||||||
|
- Profile
|
||||||
|
- Colored based on Assigned roles
|
||||||
|
|
||||||
|
Channels List:
|
||||||
|
- Channel Name
|
||||||
|
- Icon for channel type [Forum, Stage, Text, Voice/Video, File]
|
||||||
|
- Colored based on assigned roles
|
||||||
|
- Hidden based on assigned roles
|
||||||
|
|
||||||
|
Channel Specific Info:
|
||||||
|
- Channel Type
|
||||||
|
- Notification settings (specific to channel)
|
||||||
|
- Permission editing (for admins)
|
||||||
|
- Invite Link
|
||||||
|
- Channel Settings
|
||||||
|
|
||||||
|
General UI Needs:
|
||||||
|
- Icons for individual controls
|
||||||
|
- Design docs
|
||||||
|
- General design for all lists [text, file, forum, members, channels]
|
||||||
123
dev-run.ps1
Normal file
123
dev-run.ps1
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
|
Set-Location $root
|
||||||
|
|
||||||
|
$startedProcesses = @()
|
||||||
|
|
||||||
|
function Start-TrackedProcess {
|
||||||
|
param(
|
||||||
|
[string]$FilePath,
|
||||||
|
[string[]]$ArgumentList = @(),
|
||||||
|
[string]$WorkingDirectory = $root
|
||||||
|
)
|
||||||
|
|
||||||
|
$proc = Start-Process -FilePath $FilePath `
|
||||||
|
-ArgumentList $ArgumentList `
|
||||||
|
-WorkingDirectory $WorkingDirectory `
|
||||||
|
-PassThru
|
||||||
|
|
||||||
|
$script:startedProcesses += $proc
|
||||||
|
return $proc
|
||||||
|
}
|
||||||
|
|
||||||
|
function Stop-AllTrackedProcesses {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "Stopping launched processes..."
|
||||||
|
|
||||||
|
foreach ($proc in $script:startedProcesses) {
|
||||||
|
try {
|
||||||
|
if ($proc -and -not $proc.HasExited) {
|
||||||
|
Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue
|
||||||
|
Write-Host "Stopped PID $($proc.Id)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
$containerIds = docker ps --filter "ancestor=surrealdb/surrealdb:v2.2.1" --format "{{.ID}}"
|
||||||
|
foreach ($id in $containerIds) {
|
||||||
|
docker stop $id | Out-Null
|
||||||
|
Write-Host "Stopped Docker container $id"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Register-EngineEvent PowerShell.Exiting -Action {
|
||||||
|
Stop-AllTrackedProcesses
|
||||||
|
} | Out-Null
|
||||||
|
|
||||||
|
Write-Host "Building RelayCore..."
|
||||||
|
dotnet build .\RelayCore\RelayCore.csproj
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "RelayCore build failed." }
|
||||||
|
|
||||||
|
Write-Host "Building RelayServer..."
|
||||||
|
dotnet build .\RelayServer\RelayServer.csproj
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "RelayServer build failed." }
|
||||||
|
|
||||||
|
Write-Host "Building RelayClient (Windows only)..."
|
||||||
|
dotnet build .\RelayClient\RelayClient.csproj -f net10.0-windows10.0.19041.0
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "RelayClient build failed." }
|
||||||
|
|
||||||
|
$coreDll = Join-Path $root "RelayCore\bin\Debug\net9.0\RelayCore.dll"
|
||||||
|
$serverDll = Join-Path $root "RelayServer\bin\Debug\net10.0\RelayServer.dll"
|
||||||
|
$clientExe = Join-Path $root "RelayClient\bin\Debug\net10.0-windows10.0.19041.0\win-x64\RelayClient.exe"
|
||||||
|
|
||||||
|
Write-Host "Starting SurrealDB..."
|
||||||
|
Start-TrackedProcess `
|
||||||
|
-FilePath "docker" `
|
||||||
|
-ArgumentList @(
|
||||||
|
"run",
|
||||||
|
"--rm",
|
||||||
|
"-p", "8000:8000",
|
||||||
|
"-v", "/mydata:/mydata",
|
||||||
|
"surrealdb/surrealdb:v2.2.1",
|
||||||
|
"start",
|
||||||
|
"--user", "root",
|
||||||
|
"--pass", "secret"
|
||||||
|
)
|
||||||
|
|
||||||
|
Start-Sleep -Seconds 5
|
||||||
|
|
||||||
|
Write-Host "Starting RelayCore..."
|
||||||
|
Start-TrackedProcess `
|
||||||
|
-FilePath "dotnet" `
|
||||||
|
-ArgumentList @($coreDll)
|
||||||
|
|
||||||
|
Start-Sleep -Seconds 3
|
||||||
|
|
||||||
|
Write-Host "Starting RelayServer..."
|
||||||
|
Start-TrackedProcess `
|
||||||
|
-FilePath "dotnet" `
|
||||||
|
-ArgumentList @($serverDll)
|
||||||
|
|
||||||
|
Start-Sleep -Seconds 3
|
||||||
|
|
||||||
|
Write-Host "Starting RelayClient (Keeper317)..."
|
||||||
|
Start-TrackedProcess `
|
||||||
|
-FilePath $clientExe `
|
||||||
|
-ArgumentList @("--user", "Keeper317")
|
||||||
|
|
||||||
|
Start-Sleep -Seconds 1
|
||||||
|
|
||||||
|
Write-Host "Starting RelayClient (Ru_Kira)..."
|
||||||
|
Start-TrackedProcess `
|
||||||
|
-FilePath $clientExe `
|
||||||
|
-ArgumentList @("--user", "Ru_Kira")
|
||||||
|
|
||||||
|
Start-Sleep -Seconds 20
|
||||||
|
|
||||||
|
Write-Host "Starting RelayClient (Test)..."
|
||||||
|
Start-TrackedProcess `
|
||||||
|
-FilePath $clientExe `
|
||||||
|
-ArgumentList @("--user", "Test")
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "Everything started."
|
||||||
|
Write-Host "Press Ctrl+C in this PowerShell to stop everything."
|
||||||
|
|
||||||
|
while ($true) {
|
||||||
|
Start-Sleep -Seconds 1
|
||||||
|
}
|
||||||
BIN
mrwebrtc.dll
Normal file
BIN
mrwebrtc.dll
Normal file
Binary file not shown.
85
start-all.ps1
Normal file
85
start-all.ps1
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
|
Set-Location $root
|
||||||
|
|
||||||
|
$dockerExe = (Get-Command docker.exe).Source
|
||||||
|
$dotnetExe = (Get-Command dotnet.exe).Source
|
||||||
|
$ps = (Get-Command powershell.exe).Source
|
||||||
|
|
||||||
|
Write-Host "Building RelayCore..."
|
||||||
|
& $dotnetExe build .\RelayCore\RelayCore.csproj
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "RelayCore build failed." }
|
||||||
|
|
||||||
|
Write-Host "Building RelayServer..."
|
||||||
|
& $dotnetExe build .\RelayServer\RelayServer.csproj
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "RelayServer build failed." }
|
||||||
|
|
||||||
|
Write-Host "Building RelayClient (Windows only)..."
|
||||||
|
& $dotnetExe build .\RelayClient\RelayClient.csproj -f net10.0-windows10.0.19041.0
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "RelayClient build failed." }
|
||||||
|
|
||||||
|
$coreDll = Join-Path $root "RelayCore\bin\Debug\net9.0\RelayCore.dll"
|
||||||
|
$serverDll = Join-Path $root "RelayServer\bin\Debug\net10.0\RelayServer.dll"
|
||||||
|
$clientExe = Join-Path $root "RelayClient\bin\Debug\net10.0-windows10.0.19041.0\win-x64\RelayClient.exe"
|
||||||
|
|
||||||
|
$tempDir = Join-Path $env:TEMP "RelayTabs"
|
||||||
|
New-Item -ItemType Directory -Force -Path $tempDir | Out-Null
|
||||||
|
|
||||||
|
function New-TabScript {
|
||||||
|
param(
|
||||||
|
[string]$Name,
|
||||||
|
[string]$Content
|
||||||
|
)
|
||||||
|
|
||||||
|
$path = Join-Path $tempDir "$Name.ps1"
|
||||||
|
Set-Content -Path $path -Value $Content -Encoding UTF8
|
||||||
|
return $path
|
||||||
|
}
|
||||||
|
|
||||||
|
$dockerScript = New-TabScript -Name "SurrealDB" -Content @"
|
||||||
|
Set-Location '$root'
|
||||||
|
& '$dockerExe' run --rm -p 8000:8000 -v /mydata:/mydata surrealdb/surrealdb:v2.2.1 start --user root --pass secret
|
||||||
|
"@
|
||||||
|
|
||||||
|
$coreScript = New-TabScript -Name "RelayCore" -Content @"
|
||||||
|
Set-Location '$root'
|
||||||
|
Start-Sleep -Seconds 1
|
||||||
|
& '$dotnetExe' '$coreDll'
|
||||||
|
"@
|
||||||
|
|
||||||
|
$serverScript = New-TabScript -Name "RelayServer" -Content @"
|
||||||
|
Set-Location '$root'
|
||||||
|
Start-Sleep -Seconds 1
|
||||||
|
& '$dotnetExe' '$serverDll'
|
||||||
|
"@
|
||||||
|
|
||||||
|
$keeperScript = New-TabScript -Name "Keeper317" -Content @"
|
||||||
|
Set-Location '$root'
|
||||||
|
Start-Sleep -Seconds 5
|
||||||
|
& '$clientExe' --user Keeper317
|
||||||
|
"@
|
||||||
|
|
||||||
|
$kiraScript = New-TabScript -Name "Ru_Kira" -Content @"
|
||||||
|
Set-Location '$root'
|
||||||
|
Start-Sleep -Seconds 5
|
||||||
|
& '$clientExe' --user Ru_Kira
|
||||||
|
"@
|
||||||
|
|
||||||
|
$testScript = New-TabScript -Name "Test" -Content @"
|
||||||
|
Set-Location '$root'
|
||||||
|
Start-Sleep -Seconds 5
|
||||||
|
& '$clientExe' --user Test
|
||||||
|
"@
|
||||||
|
|
||||||
|
$wtArgs = @(
|
||||||
|
"new-tab --title `"SurrealDB`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$dockerScript`"",
|
||||||
|
"new-tab --title `"RelayCore`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$coreScript`"",
|
||||||
|
"new-tab --title `"RelayServer`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$serverScript`"",
|
||||||
|
"new-tab --title `"Keeper317`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$keeperScript`"",
|
||||||
|
"new-tab --title `"Test`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$testScript`"",
|
||||||
|
"new-tab --title `"Ru_Kira`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$kiraScript`""
|
||||||
|
) -join " ; "
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "Everything started."
|
||||||
|
Write-Host "Close out terminal to end all applications."
|
||||||
|
Start-Process wt.exe -ArgumentList $wtArgs
|
||||||
63
start-servers.ps1
Normal file
63
start-servers.ps1
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||||
|
Set-Location $root
|
||||||
|
|
||||||
|
$dockerExe = (Get-Command docker.exe).Source
|
||||||
|
$dotnetExe = (Get-Command dotnet.exe).Source
|
||||||
|
$ps = (Get-Command powershell.exe).Source
|
||||||
|
|
||||||
|
Write-Host "Building RelayCore..."
|
||||||
|
& $dotnetExe build .\RelayCore\RelayCore.csproj
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "RelayCore build failed." }
|
||||||
|
|
||||||
|
Write-Host "Building RelayServer..."
|
||||||
|
& $dotnetExe build .\RelayServer\RelayServer.csproj
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "RelayServer build failed." }
|
||||||
|
|
||||||
|
Write-Host "Building RelayClient (Windows only)..."
|
||||||
|
& $dotnetExe build .\RelayClient\RelayClient.csproj -f net10.0-windows10.0.19041.0
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "RelayClient build failed." }
|
||||||
|
|
||||||
|
$coreDll = Join-Path $root "RelayCore\bin\Debug\net9.0\RelayCore.dll"
|
||||||
|
$serverDll = Join-Path $root "RelayServer\bin\Debug\net10.0\RelayServer.dll"
|
||||||
|
|
||||||
|
$tempDir = Join-Path $env:TEMP "RelayTabs"
|
||||||
|
New-Item -ItemType Directory -Force -Path $tempDir | Out-Null
|
||||||
|
|
||||||
|
function New-TabScript {
|
||||||
|
param(
|
||||||
|
[string]$Name,
|
||||||
|
[string]$Content
|
||||||
|
)
|
||||||
|
|
||||||
|
$path = Join-Path $tempDir "$Name.ps1"
|
||||||
|
Set-Content -Path $path -Value $Content -Encoding UTF8
|
||||||
|
return $path
|
||||||
|
}
|
||||||
|
|
||||||
|
$dockerScript = New-TabScript -Name "SurrealDB" -Content @"
|
||||||
|
Set-Location '$root'
|
||||||
|
& '$dockerExe' run --rm -p 8000:8000 -v /mydata:/mydata surrealdb/surrealdb:v2.2.1 start --user root --pass secret
|
||||||
|
"@
|
||||||
|
|
||||||
|
$coreScript = New-TabScript -Name "RelayCore" -Content @"
|
||||||
|
Set-Location '$root'
|
||||||
|
Start-Sleep -Seconds 1
|
||||||
|
& '$dotnetExe' '$coreDll'
|
||||||
|
"@
|
||||||
|
|
||||||
|
$serverScript = New-TabScript -Name "RelayServer" -Content @"
|
||||||
|
Set-Location '$root'
|
||||||
|
Start-Sleep -Seconds 1
|
||||||
|
& '$dotnetExe' '$serverDll'
|
||||||
|
"@
|
||||||
|
|
||||||
|
$wtArgs = @(
|
||||||
|
"new-tab --title `"SurrealDB`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$dockerScript`"",
|
||||||
|
"new-tab --title `"RelayCore`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$coreScript`"",
|
||||||
|
"new-tab --title `"RelayServer`" `"$ps`" -NoExit -ExecutionPolicy Bypass -File `"$serverScript`""
|
||||||
|
) -join " ; "
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "Everything started."
|
||||||
|
Write-Host "Close out terminal to end all applications."
|
||||||
|
Start-Process wt.exe -ArgumentList $wtArgs
|
||||||
Reference in New Issue
Block a user