Update: Text Channel Stuff
Bugs: Files don't work Bugs: Video In-Line don't work Added: idk, everything?
This commit is contained in:
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
@@ -12,13 +12,18 @@ public sealed class RelaySocketClient
|
|||||||
|
|
||||||
public string? ServerPublicKey { get; private set; }
|
public string? ServerPublicKey { get; private set; }
|
||||||
|
|
||||||
|
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://192.168.1.85:5001/")
|
public RelaySocketClient(string username, string url = "ws://127.0.0.1:5001/")
|
||||||
{
|
{
|
||||||
_username = username;
|
_username = username;
|
||||||
_socket = new WebSocket(url);
|
_socket = new WebSocket(url);
|
||||||
@@ -31,151 +36,169 @@ public sealed class RelaySocketClient
|
|||||||
|
|
||||||
var publicKey = KeyStorage.LoadPublicKey(_username);
|
var publicKey = KeyStorage.LoadPublicKey(_username);
|
||||||
|
|
||||||
SendControlMessage(new WsControlMessage
|
SendControlMessage(new WsControlMessage { Action = WsAction.Authenticate, Username = _username, Token = MainPage._userToken });
|
||||||
{
|
SendControlMessage(new WsControlMessage { Action = WsAction.RegisterKey, Username = _username, PublicKey = publicKey });
|
||||||
Action = WsAction.Authenticate,
|
|
||||||
Username = _username,
|
|
||||||
Token = MainPage._userToken
|
|
||||||
});
|
|
||||||
|
|
||||||
SendControlMessage(new WsControlMessage
|
|
||||||
{
|
|
||||||
Action = WsAction.RegisterKey,
|
|
||||||
Username = _username,
|
|
||||||
PublicKey = publicKey
|
|
||||||
});
|
|
||||||
|
|
||||||
SendControlMessage(new WsControlMessage { Action = WsAction.GetServerKey });
|
SendControlMessage(new WsControlMessage { Action = WsAction.GetServerKey });
|
||||||
SendControlMessage(new WsControlMessage { Action = WsAction.GetChannels });
|
SendControlMessage(new WsControlMessage { Action = WsAction.GetChannels });
|
||||||
}
|
}
|
||||||
|
|
||||||
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
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private void SendControlMessage(WsControlMessage msg)
|
|
||||||
{
|
|
||||||
SendJson(msg);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void SendJson<T>(T payload)
|
|
||||||
{
|
|
||||||
var json = JsonSerializer.Serialize(payload);
|
|
||||||
|
|
||||||
if (_socket.ReadyState == WebSocketState.Open)
|
|
||||||
_socket.Send(json);
|
|
||||||
}
|
|
||||||
|
|
||||||
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();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void SendControlMessage(WsControlMessage message) =>
|
||||||
|
SendRaw(JsonSerializer.Serialize(message));
|
||||||
|
|
||||||
|
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
|
||||||
|
{
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
private void OnMessage(object? sender, MessageEventArgs e)
|
||||||
{
|
{
|
||||||
Log?.Invoke($"[{_username}] RAW WS DATA: {e.Data}");
|
RawMessageReceived?.Invoke(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("Event", out var eventProp))
|
if (root.TryGetProperty("Event", out var evEl))
|
||||||
{
|
{
|
||||||
var wsEvent = (WsEvent)eventProp.GetInt32();
|
var wsEvent = (WsEvent)evEl.GetInt32();
|
||||||
|
|
||||||
switch (wsEvent)
|
switch (wsEvent)
|
||||||
{
|
{
|
||||||
case WsEvent.Authenticated:
|
case WsEvent.KeyRegistered: Log?.Invoke($"[{_username}] Key registered."); return;
|
||||||
Log?.Invoke($"[{_username}] Authenticated.");
|
case WsEvent.Authenticated: Log?.Invoke($"[{_username}] Authenticated."); return;
|
||||||
return;
|
|
||||||
case WsEvent.KeyRegistered:
|
|
||||||
Log?.Invoke($"[{_username}] Key registered.");
|
|
||||||
return;
|
|
||||||
case WsEvent.Error:
|
case WsEvent.Error:
|
||||||
var detail = root.TryGetProperty("Detail", out var d) ? d.GetString() : null;
|
var det = root.TryGetProperty("Detail", out var d) ? d.GetString() : null;
|
||||||
Log?.Invoke($"[{_username}] Server error: {detail}");
|
Log?.Invoke($"[{_username}] Server error: {det}");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!root.TryGetProperty("Type", out var typeElement))
|
if (!root.TryGetProperty("Type", out var typeEl)) return;
|
||||||
return;
|
var type = (SignalType)typeEl.GetInt32();
|
||||||
|
|
||||||
var type = (SignalType)typeElement.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}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
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;
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -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}";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
namespace RelayShared.Services;
|
namespace RelayShared.Services;
|
||||||
|
|
||||||
public enum WsAction
|
public enum WsAction
|
||||||
{
|
{
|
||||||
@@ -8,7 +8,11 @@ public enum WsAction
|
|||||||
GetChannels,
|
GetChannels,
|
||||||
GetHistory,
|
GetHistory,
|
||||||
RtcJoin,
|
RtcJoin,
|
||||||
RtcLeave
|
RtcLeave,
|
||||||
|
SendTyping,
|
||||||
|
GetEditHistory,
|
||||||
|
CreateChannel,
|
||||||
|
DeleteChannel
|
||||||
}
|
}
|
||||||
|
|
||||||
public enum WsEvent
|
public enum WsEvent
|
||||||
@@ -23,8 +27,12 @@ public sealed class WsControlMessage
|
|||||||
public WsAction Action { get; set; }
|
public WsAction Action { get; set; }
|
||||||
public string? Username { get; set; }
|
public string? Username { get; set; }
|
||||||
public string? Token { get; set; }
|
public string? Token { get; set; }
|
||||||
public string? ChannelId { get; set; }
|
|
||||||
public string? PublicKey { 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 sealed class WsEventMessage
|
||||||
|
|||||||
Reference in New Issue
Block a user