Code style updates.

This commit is contained in:
flash 2023-02-07 16:01:56 +01:00
parent c9cc5ff23a
commit 4104e40843
42 changed files with 292 additions and 317 deletions

View file

@ -26,7 +26,9 @@ namespace SharpChat {
Username = fb.Username;
}
public override string ToString() => Username;
public override string ToString() {
return Username;
}
}
public class BannedIPAddress : IBan {
@ -41,7 +43,9 @@ namespace SharpChat {
Expires = fb.Expires;
}
public override string ToString() => Address.ToString();
public override string ToString() {
return Address.ToString();
}
}
public class BanManager : IDisposable {
@ -168,8 +172,9 @@ namespace SharpChat {
return BanList.ToList();
}
~BanManager()
=> DoDispose();
~BanManager() {
DoDispose();
}
public void Dispose() {
DoDispose();

View file

@ -9,7 +9,7 @@ namespace SharpChat {
public class ChannelInvalidNameException : ChannelException { }
public class ChannelManager : IDisposable {
private readonly List<ChatChannel> Channels = new List<ChatChannel>();
private readonly List<ChatChannel> Channels = new();
public readonly ChatContext Context;
@ -140,21 +140,21 @@ namespace SharpChat {
return Channels.Where(c => c.Rank <= hierarchy).ToList();
}
~ChannelManager()
=> Dispose(false);
~ChannelManager() {
DoDispose();
}
public void Dispose()
=> Dispose(true);
public void Dispose() {
DoDispose();
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing) {
private void DoDispose() {
if(IsDisposed)
return;
IsDisposed = true;
Channels.Clear();
if (disposing)
GC.SuppressFinalize(this);
}
}
}

View file

@ -10,8 +10,7 @@ namespace SharpChat {
public int Rank { get; set; } = 0;
public ChatUser Owner { get; set; } = null;
private List<ChatUser> Users { get; } = new List<ChatUser>();
private List<ChatChannelTyping> Typing { get; } = new List<ChatChannelTyping>();
private List<ChatUser> Users { get; } = new();
public bool HasPassword
=> !string.IsNullOrWhiteSpace(Password);
@ -69,30 +68,8 @@ namespace SharpChat {
}
}
public bool IsTyping(ChatUser user) {
if(user == null)
return false;
lock(Typing)
return Typing.Any(x => x.User == user && !x.HasExpired);
}
public bool CanType(ChatUser user) {
if(user == null || !HasUser(user))
return false;
return !IsTyping(user);
}
public ChatChannelTyping RegisterTyping(ChatUser user) {
if(user == null || !HasUser(user))
return null;
ChatChannelTyping typing = new ChatChannelTyping(user);
lock(Typing) {
Typing.RemoveAll(x => x.HasExpired);
Typing.Add(typing);
}
return typing;
}
public string Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append(Name);
sb.Append('\t');

View file

@ -1,18 +0,0 @@
using System;
namespace SharpChat {
public class ChatChannelTyping {
public static TimeSpan Lifetime { get; } = TimeSpan.FromSeconds(5);
public ChatUser User { get; }
public DateTimeOffset Started { get; }
public bool HasExpired
=> DateTimeOffset.Now - Started > Lifetime;
public ChatChannelTyping(ChatUser user) {
User = user ?? throw new ArgumentNullException(nameof(user));
Started = DateTimeOffset.Now;
}
}
}

View file

@ -28,10 +28,10 @@ namespace SharpChat {
public ChatContext(HttpClient httpClient, SockChatServer server) {
HttpClient = httpClient;
Server = server;
Bans = new BanManager(httpClient, this);
Users = new UserManager(this);
Channels = new ChannelManager(this);
Events = new ChatEventManager(this);
Bans = new(httpClient, this);
Users = new(this);
Channels = new(this);
Events = new(this);
BumpTimer = new Timer(e => FlashiiBump.SubmitAsync(HttpClient, Users.WithActiveConnections()).Wait(), null, TimeSpan.Zero, TimeSpan.FromMinutes(1));
}

View file

@ -16,7 +16,7 @@ namespace SharpChat {
Context = context;
if(!Database.HasDatabase)
Events = new List<IChatEvent>();
Events = new();
}
public void Add(IChatEvent evt) {
@ -80,21 +80,21 @@ namespace SharpChat {
return Enumerable.Empty<IChatEvent>();
}
~ChatEventManager()
=> Dispose(false);
~ChatEventManager() {
DoDispose();
}
public void Dispose()
=> Dispose(true);
public void Dispose() {
DoDispose();
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing) {
private void DoDispose() {
if(IsDisposed)
return;
IsDisposed = true;
Events?.Clear();
if (disposing)
GC.SuppressFinalize(this);
}
}
}

View file

@ -13,7 +13,7 @@ namespace SharpChat {
private const int FLOOD_PROTECTION_AMOUNT = 30;
private const int FLOOD_PROTECTION_THRESHOLD = 10;
private readonly Queue<DateTimeOffset> TimePoints = new Queue<DateTimeOffset>();
private readonly Queue<DateTimeOffset> TimePoints = new();
public ChatRateLimitState State {
get {

View file

@ -23,15 +23,16 @@ namespace SharpChat {
public bool HasFloodProtection
=> Rank < RANK_NO_FLOOD;
public bool Equals([AllowNull] BasicUser other)
=> UserId == other.UserId;
public bool Equals([AllowNull] BasicUser other) {
return UserId == other.UserId;
}
public string DisplayName {
get {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
if(Status == ChatUserStatus.Away)
sb.AppendFormat(@"&lt;{0}&gt;_", StatusMessage.Substring(0, Math.Min(StatusMessage.Length, 5)).ToUpperInvariant());
sb.AppendFormat(@"&lt;{0}&gt;_", StatusMessage[..Math.Min(StatusMessage.Length, 5)].ToUpperInvariant());
if(string.IsNullOrWhiteSpace(Nickname))
sb.Append(Username);
@ -50,7 +51,7 @@ namespace SharpChat {
}
public string Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append(UserId);
sb.Append('\t');
@ -61,7 +62,7 @@ namespace SharpChat {
sb.Append(Rank);
sb.Append(' ');
sb.Append(Can(ChatUserPermissions.KickUser) ? '1' : '0');
sb.Append(@" 0 ");
sb.Append(@" 0 "); // view logs
sb.Append(Can(ChatUserPermissions.SetOwnNickname) ? '1' : '0');
sb.Append(' ');
sb.Append(Can(ChatUserPermissions.CreateChannel | ChatUserPermissions.SetChannelPermanent, true) ? 2 : (
@ -75,10 +76,10 @@ namespace SharpChat {
public class ChatUser : BasicUser, IPacketTarget {
public DateTimeOffset SilencedUntil { get; set; }
private readonly List<ChatUserSession> Sessions = new List<ChatUserSession>();
private readonly List<ChatChannel> Channels = new List<ChatChannel>();
private readonly List<ChatUserSession> Sessions = new();
private readonly List<ChatChannel> Channels = new();
public readonly ChatRateLimiter RateLimiter = new ChatRateLimiter();
public readonly ChatRateLimiter RateLimiter = new();
public string TargetName => @"@log";
@ -130,7 +131,7 @@ namespace SharpChat {
if(Status == ChatUserStatus.Offline)
Status = ChatUserStatus.Online;
Colour = new ChatColour(auth.ColourRaw);
Colour = new(auth.ColourRaw);
Rank = auth.Rank;
Permissions = auth.Permissions;
@ -152,8 +153,9 @@ namespace SharpChat {
}
}
public void ForceChannel(ChatChannel chan = null)
=> Send(new UserChannelForceJoinPacket(chan ?? CurrentChannel));
public void ForceChannel(ChatChannel chan = null) {
Send(new UserChannelForceJoinPacket(chan ?? CurrentChannel));
}
public void FocusChannel(ChatChannel chan) {
lock(Channels) {

View file

@ -20,7 +20,7 @@ namespace SharpChat {
public DateTimeOffset LastPing { get; set; } = DateTimeOffset.MinValue;
public ChatUser User { get; set; }
private static int CloseCode { get; set; } = 1000;
private int CloseCode { get; set; } = 1000;
public string TargetName => @"@log";
@ -65,30 +65,32 @@ namespace SharpChat {
Connection.Send(line);
}
public void BumpPing()
=> LastPing = DateTimeOffset.Now;
public void BumpPing() {
LastPing = DateTimeOffset.Now;
}
public bool HasTimedOut
=> DateTimeOffset.Now - LastPing > SessionTimeOut;
public void PrepareForRestart()
=> CloseCode = 1012;
public void PrepareForRestart() {
CloseCode = 1012;
}
public void Dispose()
=> Dispose(true);
~ChatUserSession() {
DoDispose();
}
~ChatUserSession()
=> Dispose(false);
public void Dispose() {
DoDispose();
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing) {
private void DoDispose() {
if(IsDisposed)
return;
IsDisposed = true;
Connection.Close(CloseCode);
if(disposing)
GC.SuppressFinalize(this);
}
}
}

View file

@ -18,7 +18,7 @@ namespace SharpChat.Commands {
else {
statusText = statusText.Trim();
if(statusText.Length > MAX_LENGTH)
statusText = statusText.Substring(0, MAX_LENGTH).Trim();
statusText = statusText[..MAX_LENGTH].Trim();
}
context.User.Status = ChatUserStatus.Away;

View file

@ -46,7 +46,7 @@ namespace SharpChat {
if(!HasDatabase)
return null;
MySqlConnection conn = new MySqlConnection(ConnectionString);
MySqlConnection conn = new(ConnectionString);
conn.Open();
return conn;
@ -175,7 +175,7 @@ namespace SharpChat {
}
public static IEnumerable<IChatEvent> GetEvents(IPacketTarget target, int amount, int offset) {
List<IChatEvent> events = new List<IChatEvent>();
List<IChatEvent> events = new();
try {
using MySqlDataReader reader = RunQuery(

View file

@ -1,20 +1,19 @@
using System;
using System.IO;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace SharpChat {
public static class Extensions {
public static string GetSignedHash(this string str, string key = null)
=> Encoding.UTF8.GetBytes(str).GetSignedHash(key);
public static string GetSignedHash(this string str, string key = null) {
return Encoding.UTF8.GetBytes(str).GetSignedHash(key);
}
public static string GetSignedHash(this byte[] bytes, string key = null) {
if (key == null)
key = File.Exists(@"login_key.txt") ? File.ReadAllText(@"login_key.txt") : @"woomy";
key ??= File.Exists(@"login_key.txt") ? File.ReadAllText(@"login_key.txt") : @"woomy";
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
using (HMACSHA256 algo = new HMACSHA256(Encoding.UTF8.GetBytes(key))) {
using(HMACSHA256 algo = new(Encoding.UTF8.GetBytes(key))) {
byte[] hash = algo.ComputeHash(bytes);
foreach(byte b in hash)
@ -26,7 +25,7 @@ namespace SharpChat {
public static string GetIdString(this byte[] buffer) {
const string id_chars = @"abcdefghijklmnopqrstuvwxyz0123456789-_ABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
foreach(byte b in buffer)
sb.Append(id_chars[b % id_chars.Length]);
return sb.ToString();

View file

@ -19,8 +19,9 @@ namespace SharpChat.Flashii {
public string Hash
=> string.Join(@"#", UserId, Token, IPAddress).GetSignedHash();
public byte[] GetJSON()
=> JsonSerializer.SerializeToUtf8Bytes(this);
public byte[] GetJSON() {
return JsonSerializer.SerializeToUtf8Bytes(this);
}
}
public class FlashiiAuth {

View file

@ -4,25 +4,31 @@ using System.Text;
namespace SharpChat {
public static class Logger {
public static void Write(string str)
=> Console.WriteLine(string.Format(@"[{1}] {0}", str, DateTime.Now));
public static void Write(string str) {
Console.WriteLine(string.Format(@"[{1}] {0}", str, DateTime.Now));
}
public static void Write(byte[] bytes)
=> Write(Encoding.UTF8.GetString(bytes));
public static void Write(byte[] bytes) {
Write(Encoding.UTF8.GetString(bytes));
}
public static void Write(object obj)
=> Write(obj?.ToString() ?? string.Empty);
public static void Write(object obj) {
Write(obj?.ToString() ?? string.Empty);
}
[Conditional(@"DEBUG")]
public static void Debug(string str)
=> Write(str);
public static void Debug(string str) {
Write(str);
}
[Conditional(@"DEBUG")]
public static void Debug(byte[] bytes)
=> Write(bytes);
public static void Debug(byte[] bytes) {
Write(bytes);
}
[Conditional(@"DEBUG")]
public static void Debug(object obj)
=> Write(obj);
public static void Debug(object obj) {
Write(obj);
}
}
}

View file

@ -24,7 +24,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('1');
sb.Append("\tn\t");

View file

@ -15,7 +15,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('1');
sb.Append("\ty\t");

View file

@ -12,7 +12,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('2');
sb.Append('\t');

View file

@ -10,7 +10,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('4');
sb.Append('\t');

View file

@ -11,7 +11,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('4');
sb.Append('\t');

View file

@ -12,7 +12,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('4');
sb.Append('\t');

View file

@ -15,7 +15,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('2');
sb.Append('\t');

View file

@ -10,7 +10,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('6');
sb.Append('\t');

View file

@ -12,7 +12,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('7');
sb.Append('\t');

View file

@ -23,7 +23,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('8');
sb.Append('\t');

View file

@ -16,7 +16,7 @@ namespace SharpChat.Packet {
private const string V1_CHATBOT = "-1\tChatBot\tinherit\t\t";
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('7');
sb.Append('\t');

View file

@ -12,7 +12,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('7');
sb.Append('\t');

View file

@ -5,7 +5,7 @@ using System.Text;
namespace SharpChat.Packet {
public class FloodWarningPacket : ServerPacket {
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('2');
sb.Append('\t');

View file

@ -23,7 +23,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('9');
sb.Append('\t');

View file

@ -20,7 +20,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
if(StringId == LCR.WELCOME) {
sb.Append('7');

View file

@ -11,7 +11,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('0');
sb.Append('\t');

View file

@ -11,7 +11,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('5');
sb.Append('\t');

View file

@ -11,7 +11,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('5');
sb.Append('\t');

View file

@ -11,7 +11,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('5');
sb.Append('\t');

View file

@ -13,7 +13,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('1');
sb.Append('\t');

View file

@ -22,7 +22,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
sb.Append('3');
sb.Append('\t');

View file

@ -13,7 +13,7 @@ namespace SharpChat.Packet {
}
public override IEnumerable<string> Pack() {
StringBuilder sb = new StringBuilder();
StringBuilder sb = new();
bool isSilent = string.IsNullOrEmpty(PreviousName);

View file

@ -3,8 +3,8 @@ using System.Security.Cryptography;
namespace SharpChat {
public static class RNG {
private static object Lock { get; } = new object();
private static Random NormalRandom { get; } = new Random();
private static object Lock { get; } = new();
private static Random NormalRandom { get; } = new();
private static RandomNumberGenerator SecureRandom { get; } = RandomNumberGenerator.Create();
public static int Next() {

View file

@ -21,7 +21,7 @@ namespace SharpChat {
private Action<IWebSocketConnection> _config;
public SharpChatWebSocketServer(string location, bool supportDualStack = true) {
Uri uri = new Uri(location);
Uri uri = new(location);
Port = uri.Port;
Location = location;
@ -29,7 +29,7 @@ namespace SharpChat {
_locationIP = ParseIPAddress(uri);
_scheme = uri.Scheme;
Socket socket = new Socket(_locationIP.AddressFamily, SocketType.Stream, ProtocolType.IP);
Socket socket = new(_locationIP.AddressFamily, SocketType.Stream, ProtocolType.IP);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
if(SupportDualStack && Type.GetType(@"Mono.Runtime") == null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
@ -37,7 +37,7 @@ namespace SharpChat {
}
ListenerSocket = new SocketWrapper(socket);
SupportedSubProtocols = new string[0];
SupportedSubProtocols = Array.Empty<string>();
}
public ISocket ListenerSocket { get; set; }
@ -55,9 +55,10 @@ namespace SharpChat {
public void Dispose() {
ListenerSocket.Dispose();
GC.SuppressFinalize(this);
}
private IPAddress ParseIPAddress(Uri uri) {
private static IPAddress ParseIPAddress(Uri uri) {
string ipStr = uri.Host;
if(ipStr == "0.0.0.0") {
@ -74,7 +75,7 @@ namespace SharpChat {
}
public void Start(Action<IWebSocketConnection> config) {
IPEndPoint ipLocal = new IPEndPoint(_locationIP, Port);
IPEndPoint ipLocal = new(_locationIP, Port);
ListenerSocket.Bind(ipLocal);
ListenerSocket.Listen(100);
Port = ((IPEndPoint)ListenerSocket.LocalEndPoint).Port;
@ -101,7 +102,7 @@ namespace SharpChat {
FleckLog.Info("Listener socket restarting");
try {
ListenerSocket.Dispose();
Socket socket = new Socket(_locationIP.AddressFamily, SocketType.Stream, ProtocolType.IP);
Socket socket = new(_locationIP.AddressFamily, SocketType.Stream, ProtocolType.IP);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
ListenerSocket = new SocketWrapper(socket);
Start(_config);

View file

@ -4,7 +4,7 @@ using System.Linq;
namespace SharpChat {
public class UserManager : IDisposable {
private readonly List<ChatUser> Users = new List<ChatUser>();
private readonly List<ChatUser> Users = new();
public readonly ChatContext Context;
@ -70,21 +70,21 @@ namespace SharpChat {
return Users.ToList();
}
~UserManager()
=> Dispose(false);
~UserManager() {
DoDispose();
}
public void Dispose()
=> Dispose(true);
public void Dispose() {
DoDispose();
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing) {
private void DoDispose() {
if(IsDisposed)
return;
IsDisposed = true;
Users.Clear();
if (disposing)
GC.SuppressFinalize(this);
}
}
}