sharp-chat/SharpChat/SockChatUtility.cs

66 lines
2.1 KiB
C#
Raw Normal View History

2024-05-19 21:02:17 +00:00
using System;
using System.Text.RegularExpressions;
namespace SharpChat {
public static class SockChatUtility {
private static readonly Regex ChannelName = new(@"[^A-Za-z0-9\-_]", RegexOptions.CultureInvariant | RegexOptions.Compiled);
public static string SanitiseMessageBody(string? body) {
if(string.IsNullOrEmpty(body))
return string.Empty;
return body.Replace("<", "&lt;").Replace(">", "&gt;").Replace("\n", " <br/> ").Replace("\t", " ");
}
public static string SanitiseChannelName(string name) {
return ChannelName.Replace(name.Replace(" ", "_"), "-");
}
public static bool CheckChannelName(string name) {
return name.Length < 1 || ChannelName.IsMatch(name);
}
public static string GetUserName(UserInfo info) {
return string.IsNullOrWhiteSpace(info.NickName) ? info.UserName : $"~{info.NickName}";
}
public static string GetUserNameWithStatus(UserInfo info) {
string name = GetUserName(info);
if(info.Status == UserStatus.Away)
name = string.Format(
"&lt;{0}&gt;_{1}",
info.StatusText[..Math.Min(info.StatusText.Length, 5)].ToUpperInvariant(),
name
);
return name;
}
public static (string, UsersContext.NameTarget) ExplodeUserName(string name) {
UsersContext.NameTarget target = UsersContext.NameTarget.UserName;
if(name.StartsWith("<")) {
int gt = name.IndexOf(">_");
if(gt > 0) {
gt += 2;
name = name[gt..];
}
} else if(name.StartsWith("&lt;")) {
int gt = name.IndexOf("&gt;_");
if(gt > 0) {
gt += 5;
name = name[gt..];
}
}
if(name.StartsWith("~")) {
target = UsersContext.NameTarget.NickName;
name = name[1..];
}
return (name, target);
}
}
}