Compare commits
18 Commits
RTC-Rewrit
...
dd75ca4b06
| Author | SHA1 | Date | |
|---|---|---|---|
| dd75ca4b06 | |||
| f819d7284e | |||
| b62ceb1949 | |||
| cd2d809322 | |||
| 1ed3efcc68 | |||
| 9fbe795660 | |||
| 63d3806936 | |||
| a9d2fd64de | |||
| f8b595f609 | |||
| 885db41ba9 | |||
| 3460ce6b04 | |||
| 4974663128 | |||
| ec6a8c446a | |||
| 3901542141 | |||
| 33eee17c43 | |||
| dd1aa45f6e | |||
| 38662f6655 | |||
| 777328caed |
@@ -15,7 +15,8 @@ public partial class App : Application
|
|||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(username))
|
if (string.IsNullOrWhiteSpace(username))
|
||||||
{
|
{
|
||||||
throw new Exception("Missing required --user argument. Example: --user Keeper317");
|
username = "Test";
|
||||||
|
// throw new Exception("Missing required --user argument. Example: --user Keeper317");
|
||||||
}
|
}
|
||||||
|
|
||||||
ClientSession.Username = username;
|
ClientSession.Username = 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"
|
||||||
|
|||||||
453
RelayClient/Helpers/EmbedHelper.cs
Normal file
453
RelayClient/Helpers/EmbedHelper.cs
Normal file
@@ -0,0 +1,453 @@
|
|||||||
|
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"];
|
||||||
|
|
||||||
|
public static List<string> DetectUrls(string text)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(text)) return [];
|
||||||
|
return UrlPattern.Matches(text).Select(m => m.Value).Distinct().ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static readonly BindableProperty JumpUrlProperty =
|
||||||
|
BindableProperty.CreateAttached("JumpUrl", typeof(string), typeof(EmbedHelper), null);
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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");
|
||||||
|
|
||||||
|
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");
|
||||||
|
|
||||||
|
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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static View BuildEmbeddedPlayer(string embedUrl)
|
||||||
|
{
|
||||||
|
return new WebView
|
||||||
|
{
|
||||||
|
Source = embedUrl,
|
||||||
|
WidthRequest = 480,
|
||||||
|
HeightRequest = 270,
|
||||||
|
HorizontalOptions = LayoutOptions.Start
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
377
RelayClient/Helpers/MarkdownHelper.cs
Normal file
377
RelayClient/Helpers/MarkdownHelper.cs
Normal file
@@ -0,0 +1,377 @@
|
|||||||
|
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");
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static char Peek(string text, int index) => index < text.Length ? text[index] : '\0';
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
310
RelayClient/Helpers/SyntaxHighlighter.cs
Normal file
310
RelayClient/Helpers/SyntaxHighlighter.cs
Normal file
@@ -0,0 +1,310 @@
|
|||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace RelayClient.Helpers;
|
||||||
|
|
||||||
|
public static class SyntaxHighlighter
|
||||||
|
{
|
||||||
|
private static readonly Color DefaultColor = Color.FromArgb("#D4D4D4");
|
||||||
|
private static readonly Color KeywordColor = Color.FromArgb("#569CD6");
|
||||||
|
private static readonly Color StringColor = Color.FromArgb("#CE9178");
|
||||||
|
private static readonly Color NumberColor = Color.FromArgb("#B5CEA8");
|
||||||
|
private static readonly Color CommentColor = Color.FromArgb("#6A9955");
|
||||||
|
private static readonly Color TypeColor = Color.FromArgb("#4EC9B0");
|
||||||
|
private static readonly Color FunctionColor = Color.FromArgb("#DCDCAA");
|
||||||
|
private static readonly Color OperatorColor = Color.FromArgb("#D4D4D4");
|
||||||
|
private static readonly Color TagColor = Color.FromArgb("#569CD6");
|
||||||
|
private static readonly Color AttrColor = Color.FromArgb("#9CDCFE");
|
||||||
|
|
||||||
|
private const string FontFamily = "AnonymousProRegular";
|
||||||
|
|
||||||
|
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"
|
||||||
|
};
|
||||||
|
|
||||||
|
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"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? Resolve(string? language)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(language)) return null;
|
||||||
|
var lower = language.Trim().ToLowerInvariant();
|
||||||
|
return Aliases.GetValueOrDefault(lower, lower);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
<?xml version="1.0" encoding="utf-8" ?>
|
<?xml version="1.0" encoding="utf-8" ?>
|
||||||
<ContentPage
|
<ContentPage
|
||||||
x:Class="RelayClient.MainPage"
|
x:Class="RelayClient.MainPage"
|
||||||
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
|
xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
|
||||||
@@ -12,82 +12,88 @@
|
|||||||
ColumnSpacing="10">
|
ColumnSpacing="10">
|
||||||
|
|
||||||
<!-- Header -->
|
<!-- Header -->
|
||||||
<Border Grid.Row="0"
|
<Border Grid.Row="0" Grid.ColumnSpan="2" StrokeThickness="1" Padding="10">
|
||||||
Grid.ColumnSpan="2"
|
<VerticalStackLayout Spacing="2">
|
||||||
StrokeThickness="1"
|
<Label x:Name="UserLabel" Text="Logged in as: Unknown"
|
||||||
Padding="10">
|
FontAttributes="Bold" FontSize="18" />
|
||||||
<VerticalStackLayout Spacing="4">
|
<Label x:Name="ChannelLabel" Text="No channel selected" FontSize="14" />
|
||||||
<Label x:Name="UserLabel"
|
<Label x:Name="TypingLabel" Text="" FontSize="11"
|
||||||
Text="Logged in as: Unknown"
|
FontAttributes="Italic" TextColor="Gray" IsVisible="False" />
|
||||||
FontAttributes="Bold"
|
|
||||||
FontSize="18" />
|
|
||||||
<Label x:Name="ChannelLabel"
|
|
||||||
Text="No channel selected"
|
|
||||||
FontSize="14" />
|
|
||||||
</VerticalStackLayout>
|
</VerticalStackLayout>
|
||||||
</Border>
|
</Border>
|
||||||
|
|
||||||
<!-- Sidebar -->
|
<!-- Sidebar: channel list -->
|
||||||
<Border Grid.Row="1"
|
<Border Grid.Row="1" Grid.Column="0" StrokeThickness="1" Padding="10">
|
||||||
Grid.Column="0"
|
|
||||||
StrokeThickness="1"
|
|
||||||
Padding="10">
|
|
||||||
<ScrollView>
|
<ScrollView>
|
||||||
<VerticalStackLayout Spacing="8">
|
<VerticalStackLayout Spacing="8">
|
||||||
<Label Text="Channels"
|
<Grid ColumnDefinitions="*,Auto">
|
||||||
FontAttributes="Bold"
|
<Label Grid.Column="0" Text="Channels"
|
||||||
FontSize="16" />
|
FontAttributes="Bold" FontSize="16"
|
||||||
<VerticalStackLayout x:Name="SidebarList"
|
VerticalOptions="Center" />
|
||||||
Spacing="6" />
|
<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>
|
</VerticalStackLayout>
|
||||||
</ScrollView>
|
</ScrollView>
|
||||||
</Border>
|
</Border>
|
||||||
|
|
||||||
<!-- Messages -->
|
<!-- Messages view (text channels) -->
|
||||||
<Border Grid.Row="1"
|
<Border x:Name="MessagesView" Grid.Row="1" Grid.Column="1" StrokeThickness="1" Padding="10">
|
||||||
Grid.Column="1"
|
|
||||||
StrokeThickness="1"
|
|
||||||
Padding="10">
|
|
||||||
<ScrollView x:Name="MessagesScrollView">
|
<ScrollView x:Name="MessagesScrollView">
|
||||||
<VerticalStackLayout x:Name="MessagesLayout"
|
<VerticalStackLayout x:Name="MessagesLayout" Spacing="8" />
|
||||||
Spacing="8" />
|
|
||||||
</ScrollView>
|
</ScrollView>
|
||||||
</Border>
|
</Border>
|
||||||
<Border x:Name="RtcView"
|
|
||||||
Grid.Row="1"
|
<!-- RTC view (voice channels) -->
|
||||||
Grid.Column="1"
|
<Border x:Name="RtcView" Grid.Row="1" Grid.Column="1"
|
||||||
StrokeThickness="1"
|
StrokeThickness="1" Padding="10" IsVisible="False">
|
||||||
Padding="10"
|
<Grid RowDefinitions="Auto,*">
|
||||||
IsVisible="False">
|
|
||||||
<!-- <WebView Source="test.html"/> -->
|
|
||||||
<Grid RowDefinitions="Auto,*"
|
|
||||||
ColumnDefinitions="*">
|
|
||||||
<HybridWebView x:Name="hybridWebView"
|
<HybridWebView x:Name="hybridWebView"
|
||||||
RawMessageReceived="OnHybridWebViewRawMessageReceived"
|
RawMessageReceived="OnHybridWebViewRawMessageReceived"
|
||||||
Grid.Row="1" />
|
Grid.Row="1" />
|
||||||
</Grid>
|
</Grid>
|
||||||
</Border>
|
</Border>
|
||||||
|
|
||||||
<!-- Input -->
|
<!-- Input area -->
|
||||||
<Grid Grid.Row="2"
|
<VerticalStackLayout x:Name="InputArea" Grid.Row="2" Grid.Column="1" Spacing="4">
|
||||||
Grid.Column="1"
|
|
||||||
ColumnDefinitions="*,Auto"
|
|
||||||
ColumnSpacing="10">
|
|
||||||
<Entry x:Name="MessageEntry"
|
|
||||||
Grid.Column="0"
|
|
||||||
Placeholder="Type a message..."
|
|
||||||
ReturnType="Send"
|
|
||||||
Completed="MessageEntry_OnCompleted" />
|
|
||||||
|
|
||||||
<Button Grid.Column="1"
|
<!-- Context bar (reply / edit mode) -->
|
||||||
Text="Send"
|
<Border x:Name="ContextBar" IsVisible="False" StrokeThickness="1" Padding="8,4">
|
||||||
Clicked="SendButton_OnClicked" />
|
<Grid ColumnDefinitions="*,Auto" ColumnSpacing="8">
|
||||||
</Grid>
|
<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>
|
||||||
|
|
||||||
<!-- Swap View -->
|
<!-- Entry row: attach button + editor + send -->
|
||||||
<Button x:Name="ViewSwapped" Grid.Row="2" Grid.Column="0"
|
<Grid ColumnDefinitions="Auto,*,Auto" ColumnSpacing="6">
|
||||||
Text="Swap to WebView"
|
<Button Grid.Column="0" Text="📎"
|
||||||
Clicked="SwapView_OnClicked" />
|
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>
|
||||||
|
|
||||||
|
</VerticalStackLayout>
|
||||||
|
|
||||||
|
<!-- Bottom-left: kept empty (swap button removed) -->
|
||||||
|
<ContentView Grid.Row="2" Grid.Column="0" />
|
||||||
|
|
||||||
</Grid>
|
</Grid>
|
||||||
</ContentPage>
|
</ContentPage>
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -50,3 +50,24 @@ window.addEventListener("load", async () => {
|
|||||||
await Media.loadDevices();
|
await Media.loadDevices();
|
||||||
await Media.ensureLocalMedia();
|
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!!");
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
const peerConnections = {};
|
const peerConnections = {};
|
||||||
|
|
||||||
async function joinChannelCall() {
|
async function joinChannelCall() {
|
||||||
LogMessage("Current username: " + currentUsername);
|
LogMessage("Current username: " + currentUsername);
|
||||||
@@ -24,7 +24,7 @@ async function joinChannelCall() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (const username of existingUsers) {
|
for (const username of existingUsers) {
|
||||||
await sendOffer(username);
|
await sendOffer(username); //Creates an offer to each person in call for MESH RTC
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,6 +34,7 @@ async function sendOffer(username) {
|
|||||||
await Media.applyLocalStreamToPeerConnection(pc, username);
|
await Media.applyLocalStreamToPeerConnection(pc, username);
|
||||||
|
|
||||||
const offer = await pc.createOffer();
|
const offer = await pc.createOffer();
|
||||||
|
// LogMessage(`Offer created: ${JSON.stringify(offer)}`);
|
||||||
await pc.setLocalDescription(offer);
|
await pc.setLocalDescription(offer);
|
||||||
|
|
||||||
await RelaySocket.sendRtcSignal({
|
await RelaySocket.sendRtcSignal({
|
||||||
@@ -88,11 +89,12 @@ async function handleRtcSignal(rawJson) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function handleOffer(msg) {
|
async function handleOffer(msg) {
|
||||||
|
LogMessage(`Offer handler: ${msg}`);
|
||||||
const pc = await ensurePeerConnectionForUser(msg.from);
|
const pc = await ensurePeerConnectionForUser(msg.from);
|
||||||
|
|
||||||
await Media.ensureLocalMedia();
|
await Media.ensureLocalMedia();
|
||||||
await Media.applyLocalStreamToPeerConnection(pc, msg.from);
|
await Media.applyLocalStreamToPeerConnection(pc, msg.from);
|
||||||
|
// const offer = JSON.parse(msg.offer);
|
||||||
await pc.setRemoteDescription({
|
await pc.setRemoteDescription({
|
||||||
type: "offer",
|
type: "offer",
|
||||||
sdp: msg.sdp
|
sdp: msg.sdp
|
||||||
@@ -138,7 +140,13 @@ async function handleIce(msg) {
|
|||||||
|
|
||||||
if (!msg.candidate) return;
|
if (!msg.candidate) return;
|
||||||
|
|
||||||
await pc.addIceCandidate(msg.candidate);
|
const candidateInit = {
|
||||||
|
candidate: msg.candidate,
|
||||||
|
sdpMid: msg.sdpMid,
|
||||||
|
sdpMLineIndex: msg.sdpMLineIndex
|
||||||
|
};
|
||||||
|
|
||||||
|
await pc.addIceCandidate(candidateInit);
|
||||||
|
|
||||||
LogMessage(`Applied ICE from ${msg.from}`);
|
LogMessage(`Applied ICE from ${msg.from}`);
|
||||||
}
|
}
|
||||||
@@ -159,7 +167,9 @@ async function ensurePeerConnectionForUser(username) {
|
|||||||
channelId: currentChannelId,
|
channelId: currentChannelId,
|
||||||
from: currentUsername,
|
from: currentUsername,
|
||||||
to: username,
|
to: username,
|
||||||
candidate: JSON.stringify(event.candidate)
|
candidate: event.candidate.candidate,
|
||||||
|
sdpMid: event.candidate.sdpMid,
|
||||||
|
sdpMLineIndex: event.candidate.sdpMLineIndex
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,18 +1,51 @@
|
|||||||
using System.Net.Http.Headers;
|
using System.Net.Http.Headers;
|
||||||
using System.Net.Http.Json;
|
using System.Net.Http.Json;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using RelayShared.Services;
|
||||||
|
|
||||||
namespace RelayClient;
|
namespace RelayClient;
|
||||||
|
|
||||||
public class ServerAPI
|
public class ServerAPI
|
||||||
{
|
{
|
||||||
static HttpClient client = new HttpClient { BaseAddress = new Uri("http://localhost:5000/") };
|
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 void setupClient()
|
public static async Task setupClient()
|
||||||
{
|
{
|
||||||
client.DefaultRequestHeaders.Accept.Clear();
|
client.DefaultRequestHeaders.Accept.Clear();
|
||||||
client.DefaultRequestHeaders.Accept.Add(
|
client.DefaultRequestHeaders.Accept.Add(
|
||||||
new MediaTypeWithQualityHeaderValue("application/json"));
|
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)
|
public static async Task<Uri> PostOfferAsync(DBOffer offer)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using RelayClient.Crypto;
|
using RelayClient.Crypto;
|
||||||
using RelayShared.Services;
|
using RelayShared.Services;
|
||||||
using WebSocketSharp;
|
using WebSocketSharp;
|
||||||
@@ -15,11 +15,15 @@ public sealed class RelaySocketClient
|
|||||||
public event Action<string>? RawMessageReceived;
|
public event Action<string>? RawMessageReceived;
|
||||||
public event Action<SocketChannelList>? ChannelListReceived;
|
public event Action<SocketChannelList>? ChannelListReceived;
|
||||||
public event Action<SocketEncryptedMessage>? EncryptedChatReceived;
|
public event Action<SocketEncryptedMessage>? EncryptedChatReceived;
|
||||||
|
public event Action<SocketEncryptedMessage>? MessageEdited;
|
||||||
|
public event Action<SocketMessageDeletedEvent>? MessageDeleted;
|
||||||
|
public event Action<SocketTypingEvent>? TypingReceived;
|
||||||
|
public event Action<SocketEditHistoryResponse>? EditHistoryReceived;
|
||||||
public event Action<SocketRtcSignalMessage>? EncryptedRtcSignalReceived;
|
public event Action<SocketRtcSignalMessage>? EncryptedRtcSignalReceived;
|
||||||
public event Action<string>? ServerPublicKeyReceived;
|
public event Action<string>? ServerPublicKeyReceived;
|
||||||
public event Action<string>? Log;
|
public event Action<string>? Log;
|
||||||
|
|
||||||
public RelaySocketClient(string username, string url = "ws://localhost:1337/")
|
public RelaySocketClient(string username, string url = "ws://127.0.0.1:5001/")
|
||||||
{
|
{
|
||||||
_username = username;
|
_username = username;
|
||||||
_socket = new WebSocket(url);
|
_socket = new WebSocket(url);
|
||||||
@@ -32,96 +36,169 @@ public sealed class RelaySocketClient
|
|||||||
|
|
||||||
var publicKey = KeyStorage.LoadPublicKey(_username);
|
var publicKey = KeyStorage.LoadPublicKey(_username);
|
||||||
|
|
||||||
SendRaw($"REGISTER_KEY|{_username}|{publicKey}");
|
SendControlMessage(new WsControlMessage { Action = WsAction.Authenticate, Username = _username, Token = MainPage._userToken });
|
||||||
SendRaw("GET_SERVER_KEY");
|
SendControlMessage(new WsControlMessage { Action = WsAction.RegisterKey, Username = _username, PublicKey = publicKey });
|
||||||
SendRaw("GET_CHANNELS");
|
SendControlMessage(new WsControlMessage { Action = WsAction.GetServerKey });
|
||||||
}
|
SendControlMessage(new WsControlMessage { Action = WsAction.GetChannels });
|
||||||
|
|
||||||
public void SendRaw(string message)
|
|
||||||
{
|
|
||||||
if (_socket.ReadyState == WebSocketState.Open)
|
|
||||||
_socket.Send(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void SendJson<T>(T payload)
|
|
||||||
{
|
|
||||||
SendRaw(JsonSerializer.Serialize(payload));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Disconnect()
|
public void Disconnect()
|
||||||
{
|
{
|
||||||
_socket.OnMessage -= OnMessage;
|
_socket.OnMessage -= OnMessage;
|
||||||
|
|
||||||
if (_socket.ReadyState == WebSocketState.Open)
|
if (_socket.ReadyState == WebSocketState.Open)
|
||||||
_socket.Close();
|
_socket.Close();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnMessage(object? sender, MessageEventArgs e)
|
public void SendControlMessage(WsControlMessage message) =>
|
||||||
{
|
SendRaw(JsonSerializer.Serialize(message));
|
||||||
if (e.Data.StartsWith("SERVER:REGISTERED_KEY:"))
|
|
||||||
|
public void SendGetHistory(string channelId) =>
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.GetHistory, Username = _username, ChannelId = channelId });
|
||||||
|
|
||||||
|
public void SendRtcJoinChannel(string channelId) =>
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.RtcJoin, Username = _username, ChannelId = channelId });
|
||||||
|
|
||||||
|
public void SendRtcLeaveChannel(string channelId) =>
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.RtcLeave, Username = _username, ChannelId = channelId });
|
||||||
|
|
||||||
|
public void SendTyping(string channelId) =>
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.SendTyping, Username = _username, ChannelId = channelId });
|
||||||
|
|
||||||
|
public void SendGetEditHistory(string messageId, string channelId) =>
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.GetEditHistory, Username = _username, MessageId = messageId, ChannelId = channelId });
|
||||||
|
|
||||||
|
public void SendCreateChannel(string name, ChannelType type, string group = "") =>
|
||||||
|
SendControlMessage(new WsControlMessage
|
||||||
{
|
{
|
||||||
Log?.Invoke(e.Data);
|
Action = WsAction.CreateChannel,
|
||||||
|
ChannelName = name,
|
||||||
|
ChannelType = (int)type,
|
||||||
|
ChannelGroup = group
|
||||||
|
});
|
||||||
|
|
||||||
|
public void SendDeleteChannel(string channelId) =>
|
||||||
|
SendControlMessage(new WsControlMessage { Action = WsAction.DeleteChannel, ChannelId = channelId });
|
||||||
|
|
||||||
|
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
|
||||||
|
});
|
||||||
|
|
||||||
|
public void SendDeleteMessage(string messageId, string channelId) =>
|
||||||
|
SendJson(new SocketEncryptedMessage
|
||||||
|
{
|
||||||
|
Type = SignalType.ClientDeleteMessage, MessageId = messageId,
|
||||||
|
SenderUsername = _username, ChannelId = channelId
|
||||||
|
});
|
||||||
|
|
||||||
|
public void SendRaw(string message)
|
||||||
|
{
|
||||||
|
if (_socket.ReadyState != WebSocketState.Open)
|
||||||
|
{
|
||||||
|
Log?.Invoke($"[{_username}] Drop: socket not open ({_socket.ReadyState}), {message.Length} bytes.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_socket.Send(message);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Log?.Invoke($"[{_username}] Send failed ({message.Length} bytes): {ex.Message}");
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SendJson<T>(T payload) => SendRaw(JsonSerializer.Serialize(payload));
|
||||||
|
|
||||||
|
private void OnMessage(object? sender, MessageEventArgs e)
|
||||||
|
{
|
||||||
RawMessageReceived?.Invoke(e.Data);
|
RawMessageReceived?.Invoke(e.Data);
|
||||||
Log?.Invoke($"[{_username}] RAW WS DATA: {e.Data}");
|
Log?.Invoke($"[{_username}] RAW: {e.Data[..Math.Min(200, e.Data.Length)]}");
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
using var doc = JsonDocument.Parse(e.Data);
|
using var doc = JsonDocument.Parse(e.Data);
|
||||||
var root = doc.RootElement;
|
var root = doc.RootElement;
|
||||||
|
|
||||||
if (!root.TryGetProperty("Type", out var typeElement))
|
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;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
var type = (SignalType)typeElement.GetInt32();
|
if (!root.TryGetProperty("Type", out var typeEl)) return;
|
||||||
|
var type = (SignalType)typeEl.GetInt32();
|
||||||
|
|
||||||
switch (type)
|
switch (type)
|
||||||
{
|
{
|
||||||
case SignalType.ChannelList:
|
case SignalType.ChannelList:
|
||||||
{
|
{
|
||||||
var channelList = JsonSerializer.Deserialize<SocketChannelList>(e.Data);
|
var p = JsonSerializer.Deserialize<SocketChannelList>(e.Data);
|
||||||
if (channelList is not null)
|
if (p is not null) ChannelListReceived?.Invoke(p);
|
||||||
ChannelListReceived?.Invoke(channelList);
|
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
case SignalType.ServerPublicKey:
|
case SignalType.ServerPublicKey:
|
||||||
{
|
{
|
||||||
var serverKeyMessage = JsonSerializer.Deserialize<ServerPublicKeyMessage>(e.Data);
|
var p = JsonSerializer.Deserialize<ServerPublicKeyMessage>(e.Data);
|
||||||
if (serverKeyMessage is not null)
|
if (p is not null) { ServerPublicKey = p.PublicKey; ServerPublicKeyReceived?.Invoke(p.PublicKey); }
|
||||||
{
|
|
||||||
ServerPublicKey = serverKeyMessage.PublicKey;
|
|
||||||
ServerPublicKeyReceived?.Invoke(serverKeyMessage.PublicKey);
|
|
||||||
}
|
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
case SignalType.EncryptedSignal:
|
case SignalType.EncryptedSignal:
|
||||||
{
|
{
|
||||||
var payload = JsonSerializer.Deserialize<SocketRtcSignalMessage>(e.Data);
|
var p = JsonSerializer.Deserialize<SocketRtcSignalMessage>(e.Data);
|
||||||
if (payload is not null)
|
if (p is not null) EncryptedRtcSignalReceived?.Invoke(p);
|
||||||
EncryptedRtcSignalReceived?.Invoke(payload);
|
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
case SignalType.EncryptedChat:
|
case SignalType.EncryptedChat:
|
||||||
{
|
{
|
||||||
var payload = JsonSerializer.Deserialize<SocketEncryptedMessage>(e.Data);
|
var p = JsonSerializer.Deserialize<SocketEncryptedMessage>(e.Data);
|
||||||
if (payload is not null)
|
if (p is not null) EncryptedChatReceived?.Invoke(p);
|
||||||
EncryptedChatReceived?.Invoke(payload);
|
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;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Log?.Invoke($"[{_username}] failed to process websocket message: {ex.Message}");
|
Log?.Invoke($"[{_username}] WS parse error: {ex.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
using RelayClient.Crypto;
|
using RelayClient.Crypto;
|
||||||
using RelayShared.Rtc;
|
using RelayShared.Rtc;
|
||||||
using RelayShared.Services;
|
using RelayShared.Services;
|
||||||
@@ -30,7 +31,7 @@ public sealed class RtcBridgeService
|
|||||||
if (string.IsNullOrWhiteSpace(channelId))
|
if (string.IsNullOrWhiteSpace(channelId))
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
|
|
||||||
_socket.SendRaw($"RTC_JOIN_CHANNEL|{_username}|{channelId}");
|
_socket.SendRtcJoinChannel(channelId);
|
||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,7 +42,7 @@ public sealed class RtcBridgeService
|
|||||||
if (string.IsNullOrWhiteSpace(channelId))
|
if (string.IsNullOrWhiteSpace(channelId))
|
||||||
return;
|
return;
|
||||||
|
|
||||||
_socket.SendRaw($"RTC_LEAVE_CHANNEL|{_username}|{channelId}");
|
_socket.SendRtcLeaveChannel(channelId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void SendRtcSignal(string json)
|
public void SendRtcSignal(string json)
|
||||||
@@ -70,6 +71,7 @@ public sealed class RtcBridgeService
|
|||||||
rtcSignal.ChannelId ??= _getCurrentChannelId();
|
rtcSignal.ChannelId ??= _getCurrentChannelId();
|
||||||
rtcSignal.From ??= _username;
|
rtcSignal.From ??= _username;
|
||||||
|
|
||||||
|
// _sendRawToWebView($"RTC_SIGNAL file: {JsonSerializer.Serialize(rtcSignal)}");
|
||||||
if (string.IsNullOrWhiteSpace(rtcSignal.ChannelId))
|
if (string.IsNullOrWhiteSpace(rtcSignal.ChannelId))
|
||||||
{
|
{
|
||||||
_sendRawToWebView("SendRtcSignal failed: missing channel id.");
|
_sendRawToWebView("SendRtcSignal failed: missing channel id.");
|
||||||
@@ -116,13 +118,20 @@ public sealed class RtcBridgeService
|
|||||||
|
|
||||||
public async Task HandleIncomingRtcSignalAsync(SocketRtcSignalMessage payload)
|
public async Task HandleIncomingRtcSignalAsync(SocketRtcSignalMessage payload)
|
||||||
{
|
{
|
||||||
|
// _sendRawToWebView("HandleIncomingRtcSignal called");
|
||||||
var currentChannelId = _getCurrentChannelId();
|
var currentChannelId = _getCurrentChannelId();
|
||||||
|
|
||||||
if (payload.ChannelId != currentChannelId)
|
if (payload.ChannelId != currentChannelId)
|
||||||
|
{
|
||||||
|
_sendRawToWebView("Channel id does not match");
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (payload.SenderUsername == _username)
|
if (payload.SenderUsername == _username)
|
||||||
|
{
|
||||||
|
_sendRawToWebView("Received own message");
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
string decryptedJson;
|
string decryptedJson;
|
||||||
|
|
||||||
@@ -152,6 +161,7 @@ public sealed class RtcBridgeService
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
rtcSignal = JsonSerializer.Deserialize<RtcSignalMessage>(decryptedJson);
|
rtcSignal = JsonSerializer.Deserialize<RtcSignalMessage>(decryptedJson);
|
||||||
|
// _sendRawToWebView($"Received Encrypted Signal: [{rtcSignal.From}]: {rtcSignal.Offer}");
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -160,7 +170,10 @@ public sealed class RtcBridgeService
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (rtcSignal is null)
|
if (rtcSignal is null)
|
||||||
|
{
|
||||||
|
_sendRawToWebView("rtcSignal is null");
|
||||||
return;
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(rtcSignal.To) &&
|
if (!string.IsNullOrWhiteSpace(rtcSignal.To) &&
|
||||||
!string.Equals(rtcSignal.To, _username, StringComparison.OrdinalIgnoreCase))
|
!string.Equals(rtcSignal.To, _username, StringComparison.OrdinalIgnoreCase))
|
||||||
@@ -169,9 +182,9 @@ public sealed class RtcBridgeService
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_sendRawToWebView("Received encrypted RTC signal: " + decryptedJson);
|
// _sendRawToWebView("Received encrypted RTC signal: " + decryptedJson);
|
||||||
|
|
||||||
await SendRtcSignalToJsAsync(decryptedJson);
|
await SendRtcSignalToJsAsync(rtcSignal);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task PushRtcContextToJsAsync()
|
public Task PushRtcContextToJsAsync()
|
||||||
@@ -188,37 +201,55 @@ public sealed class RtcBridgeService
|
|||||||
return Task.CompletedTask;
|
return Task.CompletedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Task SendRtcSignalToJsAsync(string rawJson)
|
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 () =>
|
MainThread.BeginInvokeOnMainThread(async () =>
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var jsArg = JsonSerializer.Serialize(rawJson);
|
// await _hybridWebView.InvokeJavaScriptAsync("testIndex", [JsonSerializer.Serialize(data)], [RtcJsType.Default.String]);
|
||||||
|
await _hybridWebView.InvokeJavaScriptAsync("testIndex", [data], [RtcJsType.Default.RtcSignalMessage]);
|
||||||
await _hybridWebView.EvaluateJavaScriptAsync($@"
|
#region OldDebugger
|
||||||
try {{
|
// var jsArg = JsonSerializer.Serialize(data);
|
||||||
window.HybridWebView.SendRawMessage('C# eval entered');
|
//
|
||||||
|
// await _hybridWebView.EvaluateJavaScriptAsync($@"
|
||||||
if (!window.RelaySocket) {{
|
// try {{
|
||||||
window.HybridWebView.SendRawMessage('window.RelaySocket missing');
|
// window.HybridWebView.SendRawMessage('C# eval entered');
|
||||||
}} else if (typeof window.RelaySocket.receiveRtcSignal !== 'function') {{
|
//
|
||||||
window.HybridWebView.SendRawMessage('RelaySocket.receiveRtcSignal missing');
|
// if (!window.RelaySocket) {{
|
||||||
}} else {{
|
// window.HybridWebView.SendRawMessage('window.RelaySocket missing');
|
||||||
window.HybridWebView.SendRawMessage('Calling RelaySocket.receiveRtcSignal');
|
// }} else if (typeof window.RelaySocket.receiveRtcSignal !== 'function') {{
|
||||||
window.RelaySocket.receiveRtcSignal({jsArg});
|
// window.HybridWebView.SendRawMessage('RelaySocket.receiveRtcSignal missing');
|
||||||
}}
|
// }} else {{
|
||||||
}} catch (err) {{
|
// window.HybridWebView.SendRawMessage('Calling RelaySocket.receiveRtcSignal');
|
||||||
window.HybridWebView.SendRawMessage('RTC JS dispatch failed: ' + err);
|
// window.RelaySocket.receiveRtcSignal({jsArg});
|
||||||
}}
|
// }}
|
||||||
");
|
// }} catch (err) {{
|
||||||
|
// window.HybridWebView.SendRawMessage('RTC JS dispatch failed: ' + err);
|
||||||
|
// }}
|
||||||
|
// ");
|
||||||
|
#endregion
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_sendRawToWebView("SendRtcSignalToJsAsync failed: " + ex.Message);
|
_sendRawToWebView("SendRtcSignalToJsAsync failed: " + ex.Message);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return Task.CompletedTask;
|
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
|
||||||
|
{
|
||||||
|
}
|
||||||
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);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,7 +22,7 @@ namespace RelayCore.Models
|
|||||||
/// <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
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ namespace RelayCore.Models;
|
|||||||
|
|
||||||
public class Sessions : Record
|
public class Sessions : Record
|
||||||
{
|
{
|
||||||
public required string UserId { get; set; }
|
public required RecordId UserId { get; set; }
|
||||||
public required string TokenHash { get; set; }
|
public required string TokenHash { get; set; }
|
||||||
public required DateTime IssuedAt { get; set; }
|
public required DateTime IssuedAt { get; set; }
|
||||||
public required DateTime ExpiresAt { get; set; }
|
public required DateTime ExpiresAt { get; set; }
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.Text.Json.Serialization;
|
||||||
using SurrealDb.Net.Models;
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
namespace RelayCore.Models;
|
namespace RelayCore.Models;
|
||||||
|
|||||||
@@ -1,14 +1,13 @@
|
|||||||
using SurrealDb.Net;
|
using SurrealDb.Net;
|
||||||
using SurrealDb.Net.Models.Auth;
|
using SurrealDb.Net.Models.Auth;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using System;
|
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using System.Threading.Tasks;
|
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Json;
|
|
||||||
|
|
||||||
using RelayCore.Enums;
|
using RelayCore.Enums;
|
||||||
using RelayCore.Models;
|
using RelayCore.Models;
|
||||||
|
using RelayCore.Endpoints;
|
||||||
|
using RelayCore.Services;
|
||||||
|
|
||||||
|
|
||||||
await using var db = new SurrealDbClient("ws://127.0.0.1:8000/rpc");
|
await using var db = new SurrealDbClient("ws://127.0.0.1:8000/rpc");
|
||||||
@@ -25,8 +24,26 @@ Console.WriteLine($"Keeper created: {ToJsonString(keeper)}");
|
|||||||
Console.WriteLine($"Kira created: {ToJsonString(kira)}");
|
Console.WriteLine($"Kira created: {ToJsonString(kira)}");
|
||||||
Console.WriteLine($"Test created: {ToJsonString(test)}");
|
Console.WriteLine($"Test created: {ToJsonString(test)}");
|
||||||
|
|
||||||
await server.Main(db);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
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>();
|
||||||
|
|
||||||
|
var app = builder.Build();
|
||||||
|
app.MapGet("/", () => "Auth Server Running!");
|
||||||
|
app.MapAuthEndpoints();
|
||||||
|
|
||||||
|
// await server.Main(db);
|
||||||
|
|
||||||
|
await app.StartAsync();
|
||||||
|
Console.WriteLine("API Started");
|
||||||
|
Console.WriteLine("\n\n\n");
|
||||||
|
|
||||||
|
Console.Write("Press any key to stop.");
|
||||||
Console.ReadKey(true);
|
Console.ReadKey(true);
|
||||||
|
|
||||||
|
await app.StopAsync();
|
||||||
return;
|
return;
|
||||||
|
|
||||||
static string ToJsonString(object? o)
|
static string ToJsonString(object? o)
|
||||||
@@ -51,7 +68,7 @@ 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();
|
var hasher = new PasswordHasher();
|
||||||
var passwordHash = hasher.HashPassword(created.Id.ToString() + rawPassword);
|
var passwordHash = hasher.HashPassword(created.Id.ToString() + rawPassword);
|
||||||
@@ -65,16 +82,15 @@ static async Task<Users> CreateUserAsync(SurrealDbClient db, string username, st
|
|||||||
return updated;
|
return updated;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
partial class Program
|
partial class Program
|
||||||
{
|
{
|
||||||
public async Task Main(SurrealDbClient db)
|
public async Task Main(SurrealDbClient db)
|
||||||
{
|
{
|
||||||
// Set up listener
|
// Set up listener
|
||||||
using var listener = new HttpListener();
|
using var listener = new HttpListener();
|
||||||
listener.Prefixes.Add("http://localhost:8080/");
|
listener.Prefixes.Add("http://127.0.0.1:8080/");
|
||||||
listener.Start();
|
listener.Start();
|
||||||
Console.WriteLine("API Started: http://localhost:8080/");
|
Console.WriteLine("API Started: http://127.0.0.1:8080/");
|
||||||
|
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<OutputType>Exe</OutputType>
|
<OutputType>Exe</OutputType>
|
||||||
@@ -10,11 +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>
|
<ItemGroup>
|
||||||
<Folder Include="Services\" />
|
<ProjectReference Include="..\RelayShared\RelayShared.csproj" />
|
||||||
</ItemGroup>
|
</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;
|
||||||
|
}
|
||||||
|
}
|
||||||
12
RelayServer/Models/Chat/ChannelMessageEdits.cs
Normal file
12
RelayServer/Models/Chat/ChannelMessageEdits.cs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
public class ChannelMessageEdits : Record
|
||||||
|
{
|
||||||
|
public required string MessageId { get; set; }
|
||||||
|
public required string CipherText { get; set; }
|
||||||
|
public required string Nonce { get; set; }
|
||||||
|
public required string Tag { get; set; }
|
||||||
|
public required DateTime EditedAt { get; set; }
|
||||||
|
}
|
||||||
@@ -10,4 +10,6 @@ public class ChannelMessages : Record
|
|||||||
public required string Nonce { get; set; }
|
public required string Nonce { get; set; }
|
||||||
public required string Tag { get; set; }
|
public required string Tag { get; set; }
|
||||||
public required DateTime CreatedAt { get; set; }
|
public required DateTime CreatedAt { get; set; }
|
||||||
|
public DateTime? EditedAt { get; set; }
|
||||||
|
public bool IsDeleted { get; set; }
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
using SurrealDb.Net.Models;
|
using SurrealDb.Net.Models;
|
||||||
|
using RelayShared.Services;
|
||||||
|
|
||||||
namespace RelayServer.Models;
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
@@ -6,4 +7,9 @@ public class Channels : Record
|
|||||||
{
|
{
|
||||||
public required string Name { get; set; }
|
public required string Name { get; set; }
|
||||||
public required DateTime CreatedAt { get; set; }
|
public required DateTime CreatedAt { get; set; }
|
||||||
|
public ChannelType Type { get; set; } = ChannelType.Text;
|
||||||
|
public string Group { get; set; } = string.Empty;
|
||||||
|
public bool IsReadOnly { get; set; }
|
||||||
|
public bool IsDeleted { get; set; }
|
||||||
|
public string? LinkedFileChannelId { get; set; }
|
||||||
}
|
}
|
||||||
11
RelayServer/Models/Server/ChannelPermissions.cs
Normal file
11
RelayServer/Models/Server/ChannelPermissions.cs
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
public class ChannelPermissions : Record
|
||||||
|
{
|
||||||
|
public required string ChannelId { get; set; }
|
||||||
|
public required string RoleId { get; set; }
|
||||||
|
public PermissionFlags Allow { get; set; }
|
||||||
|
public PermissionFlags Deny { get; set; }
|
||||||
|
}
|
||||||
28
RelayServer/Models/Server/Roles.cs
Normal file
28
RelayServer/Models/Server/Roles.cs
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
[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
|
||||||
|
}
|
||||||
|
|
||||||
|
public class Roles : Record
|
||||||
|
{
|
||||||
|
public required string Name { get; set; }
|
||||||
|
public required PermissionFlags Permissions { get; set; }
|
||||||
|
public required DateTime CreatedAt { get; set; }
|
||||||
|
|
||||||
|
public int Priority { get; set; }
|
||||||
|
}
|
||||||
10
RelayServer/Models/Server/UserRoles.cs
Normal file
10
RelayServer/Models/Server/UserRoles.cs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
using SurrealDb.Net.Models;
|
||||||
|
|
||||||
|
namespace RelayServer.Models;
|
||||||
|
|
||||||
|
public class UserRoles : Record
|
||||||
|
{
|
||||||
|
public required string UserId { get; set; }
|
||||||
|
public required string RoleId { get; set; }
|
||||||
|
public required DateTime AssignedAt { get; set; }
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ var cryptoService = new ChannelCryptoService();
|
|||||||
await using var db = await surrealService.ConnectAsync();
|
await using var db = await surrealService.ConnectAsync();
|
||||||
|
|
||||||
ChatSocketBehavior.ClientKeyService = new ClientKeyService(db);
|
ChatSocketBehavior.ClientKeyService = new ClientKeyService(db);
|
||||||
|
ChatSocketBehavior.PermissionService = new PermissionService(db);
|
||||||
ChatSocketBehavior.Db = db;
|
ChatSocketBehavior.Db = db;
|
||||||
ChatSocketBehavior.ChannelCryptoService = cryptoService;
|
ChatSocketBehavior.ChannelCryptoService = cryptoService;
|
||||||
|
|
||||||
@@ -21,6 +22,8 @@ var bootstrapService = new ServerBootstrapService(db, coreClient, cryptoService)
|
|||||||
await bootstrapService.InitializeAsync();
|
await bootstrapService.InitializeAsync();
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
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.AddSingleton(db);
|
||||||
builder.Services.AddScoped<RtcCallService>();
|
builder.Services.AddScoped<RtcCallService>();
|
||||||
@@ -30,7 +33,8 @@ var app = builder.Build();
|
|||||||
app.MapGet("/", () => "Server Running!");
|
app.MapGet("/", () => "Server Running!");
|
||||||
app.MapRtcEndpoints();
|
app.MapRtcEndpoints();
|
||||||
|
|
||||||
var wssv = new WebSocketServer("ws://localhost:1337");
|
var wssv = new WebSocketServer("ws://127.0.0.1:5001");
|
||||||
|
// var wssv = new WebSocketServer("ws://192.168.1.92:5001");
|
||||||
wssv.AddWebSocketService<ChatSocketBehavior>("/");
|
wssv.AddWebSocketService<ChatSocketBehavior>("/");
|
||||||
RtcNotificationService.Server = wssv;
|
RtcNotificationService.Server = wssv;
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
63
RelayServer/Services/Chat/ConnectedClientService.cs
Normal file
63
RelayServer/Services/Chat/ConnectedClientService.cs
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
|
||||||
|
namespace RelayServer.Services.Chat;
|
||||||
|
|
||||||
|
public static class ConnectedClientService
|
||||||
|
{
|
||||||
|
private static readonly ConcurrentDictionary<string, string> SessionToUsername = new();
|
||||||
|
private static readonly ConcurrentDictionary<string, HashSet<string>> UsernameToSessions =
|
||||||
|
new(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Unregister(string sessionId)
|
||||||
|
{
|
||||||
|
if (SessionToUsername.TryRemove(sessionId, out var username))
|
||||||
|
RemoveSessionFromUsername(sessionId, username);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IReadOnlyCollection<string> GetSessionsForUser(string username)
|
||||||
|
{
|
||||||
|
if (UsernameToSessions.TryGetValue(username, out var sessions))
|
||||||
|
{
|
||||||
|
lock (sessions)
|
||||||
|
return sessions.ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
return Array.Empty<string>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string? GetUsernameForSession(string sessionId)
|
||||||
|
{
|
||||||
|
return SessionToUsername.TryGetValue(sessionId, out var u) ? u : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,16 +2,13 @@ using System.Text.Json;
|
|||||||
using RelayServer.Models;
|
using RelayServer.Models;
|
||||||
using RelayServer.Services.Chat;
|
using RelayServer.Services.Chat;
|
||||||
using RelayServer.Services.Crypto;
|
using RelayServer.Services.Crypto;
|
||||||
|
using RelayShared.Services;
|
||||||
using SurrealDb.Net;
|
using SurrealDb.Net;
|
||||||
|
|
||||||
namespace RelayServer.Services.Core;
|
namespace RelayServer.Services.Core;
|
||||||
|
|
||||||
public sealed class ServerBootstrapService
|
public sealed class ServerBootstrapService
|
||||||
{
|
{
|
||||||
// TODO: Make channels dynamically addable
|
|
||||||
// TODO: Add logic for channel types (ENUM)
|
|
||||||
// TODO: Add logic for channel groups for future UI use
|
|
||||||
|
|
||||||
private readonly SurrealDbClient _db;
|
private readonly SurrealDbClient _db;
|
||||||
private readonly CoreClientService _coreClient;
|
private readonly CoreClientService _coreClient;
|
||||||
private readonly ChannelCryptoService _cryptoService;
|
private readonly ChannelCryptoService _cryptoService;
|
||||||
@@ -29,8 +26,8 @@ public sealed class ServerBootstrapService
|
|||||||
public async Task InitializeAsync()
|
public async Task InitializeAsync()
|
||||||
{
|
{
|
||||||
var keeper = await _coreClient.GetUserByUsernameAsync("Keeper317");
|
var keeper = await _coreClient.GetUserByUsernameAsync("Keeper317");
|
||||||
var kira = await _coreClient.GetUserByUsernameAsync("Ru_Kira");
|
var kira = await _coreClient.GetUserByUsernameAsync("Ru_Kira");
|
||||||
var test = await _coreClient.GetUserByUsernameAsync("Test");
|
var test = await _coreClient.GetUserByUsernameAsync("Test");
|
||||||
|
|
||||||
if (keeper is null || kira is null || test is null)
|
if (keeper is null || kira is null || test is null)
|
||||||
throw new InvalidOperationException("One or more required users do not exist in RelayCore.");
|
throw new InvalidOperationException("One or more required users do not exist in RelayCore.");
|
||||||
@@ -38,9 +35,7 @@ public sealed class ServerBootstrapService
|
|||||||
if (!keeper.Licensed || !kira.Licensed || !test.Licensed)
|
if (!keeper.Licensed || !kira.Licensed || !test.Licensed)
|
||||||
throw new InvalidOperationException("One or more required users are not licensed.");
|
throw new InvalidOperationException("One or more required users are not licensed.");
|
||||||
|
|
||||||
Console.WriteLine($"Core verified user: {keeper.Username}");
|
Console.WriteLine($"Core verified: {keeper.Username}, {kira.Username}, {test.Username}");
|
||||||
Console.WriteLine($"Core verified user: {kira.Username}");
|
|
||||||
Console.WriteLine($"Core verified user: {test.Username}");
|
|
||||||
|
|
||||||
var server = await GetServerByNameAsync("Test Server");
|
var server = await GetServerByNameAsync("Test Server");
|
||||||
|
|
||||||
@@ -52,44 +47,61 @@ public sealed class ServerBootstrapService
|
|||||||
OwnerUserId = keeper.Id,
|
OwnerUserId = keeper.Id,
|
||||||
CreatedAt = DateTime.UtcNow
|
CreatedAt = DateTime.UtcNow
|
||||||
});
|
});
|
||||||
|
Console.WriteLine($"Server created: {ToJson(server)}");
|
||||||
Console.WriteLine($"Server created: {ToJsonString(server)}");
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Console.WriteLine($"Server already exists: {ToJsonString(server)}");
|
Console.WriteLine($"Server already exists: {server.Name}");
|
||||||
}
|
}
|
||||||
|
|
||||||
await EnsureServerMemberAsync(keeper.Id, true);
|
await EnsureServerMemberAsync(keeper.Id, isOwner: true);
|
||||||
await EnsureServerMemberAsync(kira.Id, false);
|
await EnsureServerMemberAsync(kira.Id, isOwner: false);
|
||||||
await EnsureServerMemberAsync(test.Id, false);
|
await EnsureServerMemberAsync(test.Id, isOwner: false);
|
||||||
|
|
||||||
Console.WriteLine("Server members ensured.");
|
Console.WriteLine("Server members ensured.");
|
||||||
|
|
||||||
var channel = await EnsureChannelAsync("general", DateTime.UtcNow);
|
var tBase = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc);
|
||||||
var channel2 = await EnsureChannelAsync("files", DateTime.UtcNow.Subtract(new TimeSpan(0, 4, 0, 0)));
|
|
||||||
var channel3 = await EnsureChannelAsync("welcome", DateTime.UtcNow.Subtract(new TimeSpan(1, 4, 4, 4)));
|
|
||||||
var channel4 = await EnsureChannelAsync("voice-general", DateTime.UtcNow.Subtract(new TimeSpan(0, 2, 0, 0)));
|
|
||||||
|
|
||||||
Console.WriteLine($"Resolved channelId: {GetRecordId(channel.Id)}");
|
var chWelcome = await EnsureChannelAsync("welcome", ChannelType.Text, group: "General", isReadOnly: true, createdAt: tBase);
|
||||||
Console.WriteLine($"Resolved channelId: {GetRecordId(channel2.Id)}");
|
var chGeneral = await EnsureChannelAsync("general", ChannelType.Text, group: "General", isReadOnly: false, createdAt: tBase.AddHours(1));
|
||||||
Console.WriteLine($"Resolved channelId: {GetRecordId(channel3.Id)}");
|
var chFiles = await EnsureChannelAsync("files", ChannelType.File, group: "General", isReadOnly: true, createdAt: tBase.AddHours(2));
|
||||||
Console.WriteLine($"Resolved channelId: {GetRecordId(channel4.Id)}");
|
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();
|
var existingKey = await GetLatestServerEncryptionKeyAsync();
|
||||||
|
|
||||||
if (existingKey is null)
|
if (existingKey is null)
|
||||||
{
|
{
|
||||||
var keyBase64 = _cryptoService.GenerateKey();
|
var keyBase64 = _cryptoService.GenerateKey();
|
||||||
var serverKeys = E2EeHelper.GenerateRsaKeyPair();
|
var serverKeys = E2EeHelper.GenerateRsaKeyPair();
|
||||||
|
|
||||||
existingKey = await _db.Create("server_encryption_keys", new ServerEncryptionKeys
|
existingKey = await _db.Create("server_encryption_keys", new ServerEncryptionKeys
|
||||||
{
|
{
|
||||||
KeyBase64 = keyBase64,
|
KeyBase64 = keyBase64,
|
||||||
PublicKey = serverKeys.publicKey,
|
PublicKey = serverKeys.publicKey,
|
||||||
PrivateKey = serverKeys.privateKey,
|
PrivateKey = serverKeys.privateKey,
|
||||||
CreatedAt = DateTime.UtcNow,
|
CreatedAt = DateTime.UtcNow,
|
||||||
UpdatedAt = DateTime.UtcNow
|
UpdatedAt = DateTime.UtcNow
|
||||||
});
|
});
|
||||||
|
|
||||||
Console.WriteLine("Server encryption key created.");
|
Console.WriteLine("Server encryption key created.");
|
||||||
@@ -104,29 +116,154 @@ public sealed class ServerBootstrapService
|
|||||||
ChatSocketBehavior.ChannelDbKey = existingKey.KeyBase64;
|
ChatSocketBehavior.ChannelDbKey = existingKey.KeyBase64;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string ToJsonString(object? obj)
|
private async Task EnsureServerMemberAsync(string userId, bool isOwner)
|
||||||
{
|
{
|
||||||
return JsonSerializer.Serialize(obj, new JsonSerializerOptions
|
var members = await _db.Select<ServerMembers>("server_members");
|
||||||
|
var existing = members.FirstOrDefault(m => m.UserId == userId);
|
||||||
|
|
||||||
|
if (existing is not null)
|
||||||
{
|
{
|
||||||
WriteIndented = true,
|
if (existing.IsOwner != isOwner)
|
||||||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
{
|
||||||
|
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 static string GetRecordId(object? id)
|
private async Task<Channels> EnsureChannelAsync(
|
||||||
|
string name, ChannelType type, string group, bool isReadOnly, DateTime createdAt)
|
||||||
{
|
{
|
||||||
if (id is null)
|
var channels = await _db.Select<Channels>("channels");
|
||||||
return string.Empty;
|
var existing = channels.FirstOrDefault(c => c.Name == name);
|
||||||
|
|
||||||
var json = JsonSerializer.Serialize(id);
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
using var doc = JsonDocument.Parse(json);
|
var channel = await _db.Create("channels", new Channels
|
||||||
var root = doc.RootElement;
|
{
|
||||||
|
Name = name,
|
||||||
|
Type = type,
|
||||||
|
Group = group,
|
||||||
|
IsReadOnly = isReadOnly,
|
||||||
|
CreatedAt = createdAt
|
||||||
|
});
|
||||||
|
|
||||||
var recordId = root.GetProperty("Id").GetString() ?? string.Empty;
|
Console.WriteLine($"Channel created: {name} ({type})");
|
||||||
var table = root.GetProperty("Table").GetString() ?? string.Empty;
|
return channel;
|
||||||
|
}
|
||||||
|
|
||||||
return $"{table}:{recordId}";
|
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)
|
private async Task<Servers?> GetServerByNameAsync(string name)
|
||||||
@@ -135,61 +272,25 @@ public sealed class ServerBootstrapService
|
|||||||
return servers.FirstOrDefault(x => x.Name == name);
|
return servers.FirstOrDefault(x => x.Name == name);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<ServerMembers?> GetServerMemberByUserIdAsync(string userId)
|
|
||||||
{
|
|
||||||
var members = await _db.Select<ServerMembers>("server_members");
|
|
||||||
return members.FirstOrDefault(x => x.UserId == userId);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<Channels?> GetChannelByNameAsync(string name)
|
|
||||||
{
|
|
||||||
var channels = await _db.Select<Channels>("channels");
|
|
||||||
return channels.FirstOrDefault(x => x.Name == name);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<ServerEncryptionKeys?> GetLatestServerEncryptionKeyAsync()
|
private async Task<ServerEncryptionKeys?> GetLatestServerEncryptionKeyAsync()
|
||||||
{
|
{
|
||||||
var keys = await _db.Select<ServerEncryptionKeys>("server_encryption_keys");
|
var keys = await _db.Select<ServerEncryptionKeys>("server_encryption_keys");
|
||||||
return keys
|
return keys.OrderByDescending(x => x.CreatedAt).FirstOrDefault();
|
||||||
.OrderByDescending(x => x.CreatedAt)
|
|
||||||
.FirstOrDefault();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task EnsureServerMemberAsync(string userId, bool isOwner)
|
private static string GetRecordId(object? id)
|
||||||
{
|
{
|
||||||
var existing = await GetServerMemberByUserIdAsync(userId);
|
if (id is null) return string.Empty;
|
||||||
if (existing is not null)
|
var json = JsonSerializer.Serialize(id);
|
||||||
{
|
using var doc = JsonDocument.Parse(json);
|
||||||
Console.WriteLine($"Server member already exists for {userId}");
|
var root = doc.RootElement;
|
||||||
return;
|
return $"{root.GetProperty("Table").GetString()}:{root.GetProperty("Id").GetString()}";
|
||||||
}
|
|
||||||
|
|
||||||
await _db.Create("server_members", new ServerMembers
|
|
||||||
{
|
|
||||||
UserId = userId,
|
|
||||||
JoinedAt = DateTime.UtcNow,
|
|
||||||
IsOwner = isOwner
|
|
||||||
});
|
|
||||||
|
|
||||||
Console.WriteLine($"Server member created for {userId}");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<Channels> EnsureChannelAsync(string name, DateTime createdAt)
|
private static string ToJson(object? obj) =>
|
||||||
{
|
JsonSerializer.Serialize(obj, new JsonSerializerOptions
|
||||||
var existing = await GetChannelByNameAsync(name);
|
|
||||||
if (existing is not null)
|
|
||||||
{
|
{
|
||||||
Console.WriteLine($"Channel already exists: {name}");
|
WriteIndented = true,
|
||||||
return existing;
|
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||||
}
|
|
||||||
|
|
||||||
var channel = await _db.Create("channels", new Channels
|
|
||||||
{
|
|
||||||
Name = name,
|
|
||||||
CreatedAt = createdAt
|
|
||||||
});
|
});
|
||||||
|
|
||||||
Console.WriteLine($"Channel created: {ToJsonString(channel)}");
|
|
||||||
return channel;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
160
RelayServer/Services/Data/PermissionService.cs
Normal file
160
RelayServer/Services/Data/PermissionService.cs
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
using RelayServer.Models;
|
||||||
|
using SurrealDb.Net;
|
||||||
|
|
||||||
|
namespace RelayServer.Services.Data;
|
||||||
|
|
||||||
|
public sealed class PermissionService
|
||||||
|
{
|
||||||
|
private readonly SurrealDbClient _db;
|
||||||
|
|
||||||
|
public PermissionService(SurrealDbClient db)
|
||||||
|
{
|
||||||
|
_db = db;
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> CanManageChannelsAsync(string username) =>
|
||||||
|
await IsOwnerOrAdminAsync(username) ||
|
||||||
|
await HasGlobalPermissionAsync(username, PermissionFlags.ManageChannels);
|
||||||
|
|
||||||
|
public async Task<bool> CanManageMessagesAsync(string username, string channelId) =>
|
||||||
|
await IsOwnerOrAdminAsync(username) ||
|
||||||
|
await HasPermissionAsync(username, channelId, PermissionFlags.ManageMessages);
|
||||||
|
|
||||||
|
public async Task<bool> IsAdministratorAsync(string username) =>
|
||||||
|
await IsOwnerOrAdminAsync(username);
|
||||||
|
|
||||||
|
public async Task<bool> CanViewChannelAsync(string username, string channelId)
|
||||||
|
{
|
||||||
|
if (await IsOwnerOrAdminAsync(username)) return true;
|
||||||
|
return !await IsDeniedByChannelAsync(username, channelId, PermissionFlags.ViewChannel);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> CanSpeakAsync(string username, string channelId)
|
||||||
|
{
|
||||||
|
if (await IsOwnerOrAdminAsync(username)) return true;
|
||||||
|
return !await IsDeniedByChannelAsync(username, channelId, PermissionFlags.Speak);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<bool> CanDeleteChannelAsync(string username) =>
|
||||||
|
await IsOwnerOrAdminAsync(username) ||
|
||||||
|
await HasGlobalPermissionAsync(username, PermissionFlags.ManageChannels) ||
|
||||||
|
await HasGlobalPermissionAsync(username, PermissionFlags.DeleteChannel);
|
||||||
|
|
||||||
|
public async Task<bool> CanEditChannelAsync(string username) =>
|
||||||
|
await IsOwnerOrAdminAsync(username) ||
|
||||||
|
await HasGlobalPermissionAsync(username, PermissionFlags.ManageChannels) ||
|
||||||
|
await HasGlobalPermissionAsync(username, PermissionFlags.EditChannel);
|
||||||
|
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<List<ChannelPermissions>> GetChannelPermissionsAsync(string channelId)
|
||||||
|
{
|
||||||
|
var all = await _db.Select<ChannelPermissions>("channel_permissions");
|
||||||
|
return all.Where(cp => cp.ChannelId == channelId).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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}";
|
||||||
|
}
|
||||||
|
}
|
||||||
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;}
|
||||||
|
}
|
||||||
@@ -1,14 +1,15 @@
|
|||||||
namespace RelayShared.Services;
|
namespace RelayShared.Services;
|
||||||
|
|
||||||
public sealed class ChannelItem
|
public sealed class ChannelItem
|
||||||
{
|
{
|
||||||
public string ChannelId { get; set; } = string.Empty;
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
public string Name { get; set; } = string.Empty;
|
public string Name { get; set; } = string.Empty;
|
||||||
|
|
||||||
public ChannelType Type { get; set; }
|
public ChannelType Type { get; set; }
|
||||||
|
|
||||||
public string Group { get; set; } = string.Empty;
|
public string Group { get; set; } = string.Empty;
|
||||||
public DateTime CreatedAt { get; set; }
|
public DateTime CreatedAt { get; set; }
|
||||||
|
public bool IsReadOnly { get; set; }
|
||||||
|
public bool CanPost { get; set; }
|
||||||
|
public bool CanManage { get; set; }
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class SocketChannelList
|
public sealed class SocketChannelList
|
||||||
|
|||||||
14
RelayShared/Services/ChatMessageContent.cs
Normal file
14
RelayShared/Services/ChatMessageContent.cs
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
namespace RelayShared.Services;
|
||||||
|
|
||||||
|
public sealed class ChatMessageContent
|
||||||
|
{
|
||||||
|
public string Text { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public string? ReplyToId { get; set; }
|
||||||
|
public string? ReplyToSenderUsername { get; set; }
|
||||||
|
public string? ReplyPreview { get; set; }
|
||||||
|
public List<string>? Mentions { get; set; }
|
||||||
|
public string? AttachmentBase64 { get; set; }
|
||||||
|
public string? AttachmentMimeType { get; set; }
|
||||||
|
public string? AttachmentFileName { get; set; }
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
namespace RelayShared.Services;
|
namespace RelayShared.Services;
|
||||||
|
|
||||||
//TODO: review name of file, potentially rename for Encryption services rather than sockets
|
//TODO: review name of file, potentially rename for Encryption services rather than sockets
|
||||||
|
|
||||||
@@ -16,6 +16,8 @@ public sealed class SocketRtcSignalMessage
|
|||||||
public sealed class SocketEncryptedMessage
|
public sealed class SocketEncryptedMessage
|
||||||
{
|
{
|
||||||
public SignalType Type { get; set; } = SignalType.EncryptedChat;
|
public SignalType Type { get; set; } = SignalType.EncryptedChat;
|
||||||
|
public string MessageId { get; set; } = string.Empty;
|
||||||
|
|
||||||
public string SenderUsername { get; set; } = string.Empty;
|
public string SenderUsername { get; set; } = string.Empty;
|
||||||
public string RecipientUsername { get; set; } = string.Empty;
|
public string RecipientUsername { get; set; } = string.Empty;
|
||||||
public string ChannelId { get; set; } = string.Empty;
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
@@ -23,6 +25,38 @@ public sealed class SocketEncryptedMessage
|
|||||||
public string Nonce { get; set; } = string.Empty;
|
public string Nonce { get; set; } = string.Empty;
|
||||||
public string Tag { get; set; } = string.Empty;
|
public string Tag { get; set; } = string.Empty;
|
||||||
public string EncryptedKey { get; set; } = string.Empty;
|
public string EncryptedKey { get; set; } = string.Empty;
|
||||||
|
public bool IsEdited { get; set; }
|
||||||
|
public bool IsDeleted { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class SocketMessageDeletedEvent
|
||||||
|
{
|
||||||
|
public SignalType Type { get; set; } = SignalType.MessageDeleted;
|
||||||
|
public string MessageId { get; set; } = string.Empty;
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class SocketTypingEvent
|
||||||
|
{
|
||||||
|
public SignalType Type { get; set; } = SignalType.TypingIndicator;
|
||||||
|
public string Username { get; set; } = string.Empty;
|
||||||
|
public string ChannelId { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class SocketEditHistoryEntry
|
||||||
|
{
|
||||||
|
public string CipherText { get; set; } = string.Empty;
|
||||||
|
public string Nonce { get; set; } = string.Empty;
|
||||||
|
public string Tag { get; set; } = string.Empty;
|
||||||
|
public string EncryptedKey { get; set; } = string.Empty;
|
||||||
|
public DateTime EditedAt { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class SocketEditHistoryResponse
|
||||||
|
{
|
||||||
|
public SignalType Type { get; set; } = SignalType.EditHistory;
|
||||||
|
public string MessageId { get; set; } = string.Empty;
|
||||||
|
public List<SocketEditHistoryEntry> Entries { get; set; } = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class ServerPublicKeyMessage
|
public sealed class ServerPublicKeyMessage
|
||||||
@@ -44,5 +78,11 @@ public enum SignalType
|
|||||||
ServerPublicKey,
|
ServerPublicKey,
|
||||||
EncryptedSignal,
|
EncryptedSignal,
|
||||||
EncryptedChat,
|
EncryptedChat,
|
||||||
ClientEncryptedChat
|
ClientEncryptedChat,
|
||||||
|
ClientEditMessage,
|
||||||
|
ClientDeleteMessage,
|
||||||
|
MessageEdited,
|
||||||
|
MessageDeleted,
|
||||||
|
TypingIndicator,
|
||||||
|
EditHistory
|
||||||
}
|
}
|
||||||
42
RelayShared/Services/WsControlMessage.cs
Normal file
42
RelayShared/Services/WsControlMessage.cs
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
namespace RelayShared.Services;
|
||||||
|
|
||||||
|
public enum WsAction
|
||||||
|
{
|
||||||
|
Authenticate,
|
||||||
|
RegisterKey,
|
||||||
|
GetServerKey,
|
||||||
|
GetChannels,
|
||||||
|
GetHistory,
|
||||||
|
RtcJoin,
|
||||||
|
RtcLeave,
|
||||||
|
SendTyping,
|
||||||
|
GetEditHistory,
|
||||||
|
CreateChannel,
|
||||||
|
DeleteChannel
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum WsEvent
|
||||||
|
{
|
||||||
|
Authenticated,
|
||||||
|
KeyRegistered,
|
||||||
|
Error
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class WsControlMessage
|
||||||
|
{
|
||||||
|
public WsAction Action { get; set; }
|
||||||
|
public string? Username { get; set; }
|
||||||
|
public string? Token { get; set; }
|
||||||
|
public string? PublicKey { get; set; }
|
||||||
|
public string? ChannelId { get; set; }
|
||||||
|
public string? MessageId { get; set; }
|
||||||
|
public string? ChannelName { get; set; }
|
||||||
|
public int ChannelType { get; set; } // cast to ChannelType enum
|
||||||
|
public string? ChannelGroup { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class WsEventMessage
|
||||||
|
{
|
||||||
|
public WsEvent Event { get; set; }
|
||||||
|
public string? Detail { get; set; }
|
||||||
|
}
|
||||||
@@ -66,7 +66,7 @@ Start-Sleep -Seconds 5
|
|||||||
|
|
||||||
$testScript = New-TabScript -Name "Test" -Content @"
|
$testScript = New-TabScript -Name "Test" -Content @"
|
||||||
Set-Location '$root'
|
Set-Location '$root'
|
||||||
Start-Sleep -Seconds 25
|
Start-Sleep -Seconds 5
|
||||||
& '$clientExe' --user Test
|
& '$clientExe' --user Test
|
||||||
"@
|
"@
|
||||||
|
|
||||||
|
|||||||
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