Removed a bunch of @ prefixes that aren't needed.

This commit is contained in:
flash 2023-02-08 04:17:07 +01:00
parent 27c28aafcd
commit 40c7ba4ded
21 changed files with 254 additions and 254 deletions

View file

@ -88,7 +88,7 @@ namespace SharpChat {
if(channel == null) if(channel == null)
throw new ArgumentNullException(nameof(channel)); throw new ArgumentNullException(nameof(channel));
if(!Channels.Contains(channel)) if(!Channels.Contains(channel))
throw new ArgumentException(@"Provided channel is not registered with this manager.", nameof(channel)); throw new ArgumentException("Provided channel is not registered with this manager.", nameof(channel));
string prevName = channel.Name; string prevName = channel.Name;
int prevHierarchy = channel.Rank; int prevHierarchy = channel.Rank;

View file

@ -11,7 +11,7 @@ namespace SharpChat {
public UserManager Users { get; } public UserManager Users { get; }
public ChatEventManager Events { get; } public ChatEventManager Events { get; }
public string TargetName => @"@broadcast"; public string TargetName => "@broadcast";
public ChatContext() { public ChatContext() {
Users = new(this); Users = new(this);
@ -76,7 +76,7 @@ namespace SharpChat {
public void SwitchChannel(ChatUser user, ChatChannel chan, string password) { public void SwitchChannel(ChatUser user, ChatChannel chan, string password) {
if(user.CurrentChannel == chan) { if(user.CurrentChannel == chan) {
//user.Send(true, @"samechan", chan.Name); //user.Send(true, "samechan", chan.Name);
user.ForceChannel(); user.ForceChannel();
return; return;
} }
@ -133,7 +133,7 @@ namespace SharpChat {
foreach(ChatUserSession sess in timedOut) { foreach(ChatUserSession sess in timedOut) {
user.RemoveSession(sess); user.RemoveSession(sess);
sess.Dispose(); sess.Dispose();
Logger.Write($@"Nuked session {sess.Id} from {user.Username} (timeout)"); Logger.Write($"Nuked session {sess.Id} from {user.Username} (timeout)");
} }
if(!user.HasSessions) if(!user.HasSessions)

View file

@ -32,7 +32,7 @@ namespace SharpChat {
StringBuilder sb = new(); StringBuilder sb = new();
if(Status == ChatUserStatus.Away) if(Status == ChatUserStatus.Away)
sb.AppendFormat(@"<{0}>_", StatusMessage[..Math.Min(StatusMessage.Length, 5)].ToUpperInvariant()); sb.AppendFormat("<{0}>_", StatusMessage[..Math.Min(StatusMessage.Length, 5)].ToUpperInvariant());
if(string.IsNullOrWhiteSpace(Nickname)) if(string.IsNullOrWhiteSpace(Nickname))
sb.Append(Username); sb.Append(Username);
@ -62,7 +62,7 @@ namespace SharpChat {
sb.Append(Rank); sb.Append(Rank);
sb.Append(' '); sb.Append(' ');
sb.Append(Can(ChatUserPermissions.KickUser) ? '1' : '0'); sb.Append(Can(ChatUserPermissions.KickUser) ? '1' : '0');
sb.Append(@" 0 "); // view logs sb.Append(" 0 "); // view logs
sb.Append(Can(ChatUserPermissions.SetOwnNickname) ? '1' : '0'); sb.Append(Can(ChatUserPermissions.SetOwnNickname) ? '1' : '0');
sb.Append(' '); sb.Append(' ');
sb.Append(Can(ChatUserPermissions.CreateChannel | ChatUserPermissions.SetChannelPermanent, true) ? 2 : ( sb.Append(Can(ChatUserPermissions.CreateChannel | ChatUserPermissions.SetChannelPermanent, true) ? 2 : (
@ -81,7 +81,7 @@ namespace SharpChat {
public readonly ChatRateLimiter RateLimiter = new(); public readonly ChatRateLimiter RateLimiter = new();
public string TargetName => @"@log"; public string TargetName => "@log";
public ChatChannel Channel { public ChatChannel Channel {
get { get {

View file

@ -22,7 +22,7 @@ namespace SharpChat {
private int CloseCode { get; set; } = 1000; private int CloseCode { get; set; } = 1000;
public string TargetName => @"@log"; public string TargetName => "@log";
private IPAddress _RemoteAddress = null; private IPAddress _RemoteAddress = null;
@ -30,9 +30,9 @@ namespace SharpChat {
public IPAddress RemoteAddress { public IPAddress RemoteAddress {
get { get {
if(_RemoteAddress == null) { if(_RemoteAddress == null) {
if((Connection.ConnectionInfo.ClientIpAddress == @"127.0.0.1" || Connection.ConnectionInfo.ClientIpAddress == @"::1") if((Connection.ConnectionInfo.ClientIpAddress == "127.0.0.1" || Connection.ConnectionInfo.ClientIpAddress == "::1")
&& Connection.ConnectionInfo.Headers.ContainsKey(@"X-Real-IP")) && Connection.ConnectionInfo.Headers.ContainsKey("X-Real-IP"))
_RemoteAddress = IPAddress.Parse(Connection.ConnectionInfo.Headers[@"X-Real-IP"]); _RemoteAddress = IPAddress.Parse(Connection.ConnectionInfo.Headers["X-Real-IP"]);
else else
_RemoteAddress = IPAddress.Parse(Connection.ConnectionInfo.ClientIpAddress); _RemoteAddress = IPAddress.Parse(Connection.ConnectionInfo.ClientIpAddress);
} }

View file

@ -4,11 +4,11 @@ using System.Linq;
namespace SharpChat.Commands { namespace SharpChat.Commands {
public class AFKCommand : IChatCommand { public class AFKCommand : IChatCommand {
private const string DEFAULT = @"AFK"; private const string DEFAULT = "AFK";
private const int MAX_LENGTH = 5; private const int MAX_LENGTH = 5;
public bool IsMatch(string name) { public bool IsMatch(string name) {
return name == @"afk"; return name == "afk";
} }
public IChatMessage Dispatch(IChatCommandContext context) { public IChatMessage Dispatch(IChatCommandContext context) {

View file

@ -14,9 +14,9 @@ namespace SharpChat {
=> !string.IsNullOrWhiteSpace(ConnectionString); => !string.IsNullOrWhiteSpace(ConnectionString);
public static void ReadConfig() { public static void ReadConfig() {
if(!File.Exists(@"mariadb.txt")) if(!File.Exists("mariadb.txt"))
return; return;
string[] config = File.ReadAllLines(@"mariadb.txt"); string[] config = File.ReadAllLines("mariadb.txt");
if(config.Length < 4) if(config.Length < 4)
return; return;
Init(config[0], config[1], config[2], config[3]); Init(config[0], config[1], config[2], config[3]);
@ -30,7 +30,7 @@ namespace SharpChat {
Database = database, Database = database,
OldGuids = false, OldGuids = false,
TreatTinyAsBoolean = false, TreatTinyAsBoolean = false,
CharacterSet = @"utf8mb4", CharacterSet = "utf8mb4",
SslMode = MySqlSslMode.None, SslMode = MySqlSslMode.None,
ForceSynchronous = true, ForceSynchronous = true,
ConnectionTimeout = 5, ConnectionTimeout = 5,
@ -125,49 +125,49 @@ namespace SharpChat {
evt.SequenceId = GenerateId(); evt.SequenceId = GenerateId();
RunCommand( RunCommand(
@"INSERT INTO `sqc_events` (`event_id`, `event_created`, `event_type`, `event_target`, `event_flags`, `event_data`" "INSERT INTO `sqc_events` (`event_id`, `event_created`, `event_type`, `event_target`, `event_flags`, `event_data`"
+ @", `event_sender`, `event_sender_name`, `event_sender_colour`, `event_sender_rank`, `event_sender_nick`, `event_sender_perms`)" + ", `event_sender`, `event_sender_name`, `event_sender_colour`, `event_sender_rank`, `event_sender_nick`, `event_sender_perms`)"
+ @" VALUES (@id, FROM_UNIXTIME(@created), @type, @target, @flags, @data" + " VALUES (@id, FROM_UNIXTIME(@created), @type, @target, @flags, @data"
+ @", @sender, @sender_name, @sender_colour, @sender_rank, @sender_nick, @sender_perms)", + ", @sender, @sender_name, @sender_colour, @sender_rank, @sender_nick, @sender_perms)",
new MySqlParameter(@"id", evt.SequenceId), new MySqlParameter("id", evt.SequenceId),
new MySqlParameter(@"created", evt.DateTime.ToUnixTimeSeconds()), new MySqlParameter("created", evt.DateTime.ToUnixTimeSeconds()),
new MySqlParameter(@"type", evt.GetType().FullName), new MySqlParameter("type", evt.GetType().FullName),
new MySqlParameter(@"target", evt.Target.TargetName), new MySqlParameter("target", evt.Target.TargetName),
new MySqlParameter(@"flags", (byte)evt.Flags), new MySqlParameter("flags", (byte)evt.Flags),
new MySqlParameter(@"data", JsonSerializer.SerializeToUtf8Bytes(evt, evt.GetType())), new MySqlParameter("data", JsonSerializer.SerializeToUtf8Bytes(evt, evt.GetType())),
new MySqlParameter(@"sender", evt.Sender?.UserId < 1 ? null : (long?)evt.Sender.UserId), new MySqlParameter("sender", evt.Sender?.UserId < 1 ? null : (long?)evt.Sender.UserId),
new MySqlParameter(@"sender_name", evt.Sender?.Username), new MySqlParameter("sender_name", evt.Sender?.Username),
new MySqlParameter(@"sender_colour", evt.Sender?.Colour.ToMisuzu()), new MySqlParameter("sender_colour", evt.Sender?.Colour.ToMisuzu()),
new MySqlParameter(@"sender_rank", evt.Sender?.Rank), new MySqlParameter("sender_rank", evt.Sender?.Rank),
new MySqlParameter(@"sender_nick", evt.Sender?.Nickname), new MySqlParameter("sender_nick", evt.Sender?.Nickname),
new MySqlParameter(@"sender_perms", evt.Sender?.Permissions) new MySqlParameter("sender_perms", evt.Sender?.Permissions)
); );
} }
public static void DeleteEvent(IChatEvent evt) { public static void DeleteEvent(IChatEvent evt) {
RunCommand( RunCommand(
@"UPDATE IGNORE `sqc_events` SET `event_deleted` = NOW() WHERE `event_id` = @id AND `event_deleted` IS NULL", "UPDATE IGNORE `sqc_events` SET `event_deleted` = NOW() WHERE `event_id` = @id AND `event_deleted` IS NULL",
new MySqlParameter(@"id", evt.SequenceId) new MySqlParameter("id", evt.SequenceId)
); );
} }
private static IChatEvent ReadEvent(MySqlDataReader reader, IPacketTarget target = null) { private static IChatEvent ReadEvent(MySqlDataReader reader, IPacketTarget target = null) {
Type evtType = Type.GetType(Encoding.ASCII.GetString((byte[])reader[@"event_type"])); Type evtType = Type.GetType(Encoding.ASCII.GetString((byte[])reader["event_type"]));
IChatEvent evt = JsonSerializer.Deserialize(Encoding.ASCII.GetString((byte[])reader[@"event_data"]), evtType) as IChatEvent; IChatEvent evt = JsonSerializer.Deserialize(Encoding.ASCII.GetString((byte[])reader["event_data"]), evtType) as IChatEvent;
evt.SequenceId = reader.GetInt64(@"event_id"); evt.SequenceId = reader.GetInt64("event_id");
evt.Target = target; evt.Target = target;
evt.TargetName = target?.TargetName ?? Encoding.ASCII.GetString((byte[])reader[@"event_target"]); evt.TargetName = target?.TargetName ?? Encoding.ASCII.GetString((byte[])reader["event_target"]);
evt.Flags = (ChatMessageFlags)reader.GetByte(@"event_flags"); evt.Flags = (ChatMessageFlags)reader.GetByte("event_flags");
evt.DateTime = DateTimeOffset.FromUnixTimeSeconds(reader.GetInt32(@"event_created")); evt.DateTime = DateTimeOffset.FromUnixTimeSeconds(reader.GetInt32("event_created"));
if(!reader.IsDBNull(reader.GetOrdinal(@"event_sender"))) { if(!reader.IsDBNull(reader.GetOrdinal("event_sender"))) {
evt.Sender = new BasicUser { evt.Sender = new BasicUser {
UserId = reader.GetInt64(@"event_sender"), UserId = reader.GetInt64("event_sender"),
Username = reader.GetString(@"event_sender_name"), Username = reader.GetString("event_sender_name"),
Colour = ChatColour.FromMisuzu(reader.GetInt32(@"event_sender_colour")), Colour = ChatColour.FromMisuzu(reader.GetInt32("event_sender_colour")),
Rank = reader.GetInt32(@"event_sender_rank"), Rank = reader.GetInt32("event_sender_rank"),
Nickname = reader.IsDBNull(reader.GetOrdinal(@"event_sender_nick")) ? null : reader.GetString(@"event_sender_nick"), Nickname = reader.IsDBNull(reader.GetOrdinal("event_sender_nick")) ? null : reader.GetString("event_sender_nick"),
Permissions = (ChatUserPermissions)reader.GetInt32(@"event_sender_perms") Permissions = (ChatUserPermissions)reader.GetInt32("event_sender_perms")
}; };
} }
@ -179,17 +179,17 @@ namespace SharpChat {
try { try {
using MySqlDataReader reader = RunQuery( using MySqlDataReader reader = RunQuery(
@"SELECT `event_id`, `event_type`, `event_flags`, `event_data`" "SELECT `event_id`, `event_type`, `event_flags`, `event_data`"
+ @", `event_sender`, `event_sender_name`, `event_sender_colour`, `event_sender_rank`, `event_sender_nick`, `event_sender_perms`" + ", `event_sender`, `event_sender_name`, `event_sender_colour`, `event_sender_rank`, `event_sender_nick`, `event_sender_perms`"
+ @", UNIX_TIMESTAMP(`event_created`) AS `event_created`" + ", UNIX_TIMESTAMP(`event_created`) AS `event_created`"
+ @" FROM `sqc_events`" + " FROM `sqc_events`"
+ @" WHERE `event_deleted` IS NULL AND `event_target` = @target" + " WHERE `event_deleted` IS NULL AND `event_target` = @target"
+ @" AND `event_id` > @offset" + " AND `event_id` > @offset"
+ @" ORDER BY `event_id` DESC" + " ORDER BY `event_id` DESC"
+ @" LIMIT @amount", + " LIMIT @amount",
new MySqlParameter(@"target", target.TargetName), new MySqlParameter("target", target.TargetName),
new MySqlParameter(@"amount", amount), new MySqlParameter("amount", amount),
new MySqlParameter(@"offset", offset) new MySqlParameter("offset", offset)
); );
while(reader.Read()) { while(reader.Read()) {
@ -207,12 +207,12 @@ namespace SharpChat {
public static IChatEvent GetEvent(long seqId) { public static IChatEvent GetEvent(long seqId) {
try { try {
using MySqlDataReader reader = RunQuery( using MySqlDataReader reader = RunQuery(
@"SELECT `event_id`, `event_type`, `event_flags`, `event_data`, `event_target`" "SELECT `event_id`, `event_type`, `event_flags`, `event_data`, `event_target`"
+ @", `event_sender`, `event_sender_name`, `event_sender_colour`, `event_sender_rank`, `event_sender_nick`, `event_sender_perms`" + ", `event_sender`, `event_sender_name`, `event_sender_colour`, `event_sender_rank`, `event_sender_nick`, `event_sender_perms`"
+ @", UNIX_TIMESTAMP(`event_created`) AS `event_created`" + ", UNIX_TIMESTAMP(`event_created`) AS `event_created`"
+ @" FROM `sqc_events`" + " FROM `sqc_events`"
+ @" WHERE `event_id` = @id", + " WHERE `event_id` = @id",
new MySqlParameter(@"id", seqId) new MySqlParameter("id", seqId)
); );
while(reader.Read()) { while(reader.Read()) {

View file

@ -5,55 +5,55 @@ namespace SharpChat {
public static partial class Database { public static partial class Database {
private static void DoMigration(string name, Action action) { private static void DoMigration(string name, Action action) {
bool done = (long)RunQueryValue( bool done = (long)RunQueryValue(
@"SELECT COUNT(*) FROM `sqc_migrations` WHERE `migration_name` = @name", "SELECT COUNT(*) FROM `sqc_migrations` WHERE `migration_name` = @name",
new MySqlParameter(@"name", name) new MySqlParameter("name", name)
) > 0; ) > 0;
if(!done) { if(!done) {
Logger.Write($@"Running migration '{name}'..."); Logger.Write($"Running migration '{name}'...");
action(); action();
RunCommand( RunCommand(
@"INSERT INTO `sqc_migrations` (`migration_name`) VALUES (@name)", "INSERT INTO `sqc_migrations` (`migration_name`) VALUES (@name)",
new MySqlParameter(@"name", name) new MySqlParameter("name", name)
); );
} }
} }
private static void RunMigrations() { private static void RunMigrations() {
RunCommand( RunCommand(
@"CREATE TABLE IF NOT EXISTS `sqc_migrations` (" "CREATE TABLE IF NOT EXISTS `sqc_migrations` ("
+ @"`migration_name` VARCHAR(255) NOT NULL," + "`migration_name` VARCHAR(255) NOT NULL,"
+ @"`migration_completed` TIMESTAMP NOT NULL DEFAULT current_timestamp()," + "`migration_completed` TIMESTAMP NOT NULL DEFAULT current_timestamp(),"
+ @"UNIQUE INDEX `migration_name` (`migration_name`)," + "UNIQUE INDEX `migration_name` (`migration_name`),"
+ @"INDEX `migration_completed` (`migration_completed`)" + "INDEX `migration_completed` (`migration_completed`)"
+ @") COLLATE='utf8mb4_unicode_ci' ENGINE=InnoDB;" + ") COLLATE='utf8mb4_unicode_ci' ENGINE=InnoDB;"
); );
DoMigration(@"create_events_table", CreateEventsTable); DoMigration("create_events_table", CreateEventsTable);
} }
private static void CreateEventsTable() { private static void CreateEventsTable() {
RunCommand( RunCommand(
@"CREATE TABLE `sqc_events` (" "CREATE TABLE `sqc_events` ("
+ @"`event_id` BIGINT(20) NOT NULL," + "`event_id` BIGINT(20) NOT NULL,"
+ @"`event_sender` BIGINT(20) UNSIGNED NULL DEFAULT NULL," + "`event_sender` BIGINT(20) UNSIGNED NULL DEFAULT NULL,"
+ @"`event_sender_name` VARCHAR(255) NULL DEFAULT NULL," + "`event_sender_name` VARCHAR(255) NULL DEFAULT NULL,"
+ @"`event_sender_colour` INT(11) NULL DEFAULT NULL," + "`event_sender_colour` INT(11) NULL DEFAULT NULL,"
+ @"`event_sender_rank` INT(11) NULL DEFAULT NULL," + "`event_sender_rank` INT(11) NULL DEFAULT NULL,"
+ @"`event_sender_nick` VARCHAR(255) NULL DEFAULT NULL," + "`event_sender_nick` VARCHAR(255) NULL DEFAULT NULL,"
+ @"`event_sender_perms` INT(11) NULL DEFAULT NULL," + "`event_sender_perms` INT(11) NULL DEFAULT NULL,"
+ @"`event_created` TIMESTAMP NOT NULL DEFAULT current_timestamp()," + "`event_created` TIMESTAMP NOT NULL DEFAULT current_timestamp(),"
+ @"`event_deleted` TIMESTAMP NULL DEFAULT NULL," + "`event_deleted` TIMESTAMP NULL DEFAULT NULL,"
+ @"`event_type` VARBINARY(255) NOT NULL," + "`event_type` VARBINARY(255) NOT NULL,"
+ @"`event_target` VARBINARY(255) NOT NULL," + "`event_target` VARBINARY(255) NOT NULL,"
+ @"`event_flags` TINYINT(3) UNSIGNED NOT NULL," + "`event_flags` TINYINT(3) UNSIGNED NOT NULL,"
+ @"`event_data` BLOB NULL DEFAULT NULL," + "`event_data` BLOB NULL DEFAULT NULL,"
+ @"PRIMARY KEY (`event_id`)," + "PRIMARY KEY (`event_id`),"
+ @"INDEX `event_target` (`event_target`)," + "INDEX `event_target` (`event_target`),"
+ @"INDEX `event_type` (`event_type`)," + "INDEX `event_type` (`event_type`),"
+ @"INDEX `event_sender` (`event_sender`)," + "INDEX `event_sender` (`event_sender`),"
+ @"INDEX `event_datetime` (`event_created`)," + "INDEX `event_datetime` (`event_created`),"
+ @"INDEX `event_deleted` (`event_deleted`)" + "INDEX `event_deleted` (`event_deleted`)"
+ @") COLLATE='utf8mb4_unicode_ci' ENGINE=InnoDB;" + ") COLLATE='utf8mb4_unicode_ci' ENGINE=InnoDB;"
); );
} }
} }

View file

@ -21,7 +21,7 @@ namespace SharpChat.Events {
[JsonIgnore] [JsonIgnore]
public long SequenceId { get; set; } public long SequenceId { get; set; }
[JsonPropertyName(@"text")] [JsonPropertyName("text")]
public string Text { get; set; } public string Text { get; set; }
public static string PackBotMessage(int type, string id, params string[] parts) { public static string PackBotMessage(int type, string id, params string[] parts) {

View file

@ -23,7 +23,7 @@ namespace SharpChat.Events {
[JsonIgnore] [JsonIgnore]
public long SequenceId { get; set; } public long SequenceId { get; set; }
[JsonPropertyName(@"reason")] [JsonPropertyName("reason")]
public UserDisconnectReason Reason { get; set; } public UserDisconnectReason Reason { get; set; }
public UserDisconnectEvent() { } public UserDisconnectEvent() { }

View file

@ -9,7 +9,7 @@ namespace SharpChat {
} }
public static string GetSignedHash(this byte[] bytes, string key = null) { public static string GetSignedHash(this byte[] bytes, string 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 sb = new();
@ -17,14 +17,14 @@ namespace SharpChat {
byte[] hash = algo.ComputeHash(bytes); byte[] hash = algo.ComputeHash(bytes);
foreach(byte b in hash) foreach(byte b in hash)
sb.AppendFormat(@"{0:x2}", b); sb.AppendFormat("{0:x2}", b);
} }
return sb.ToString(); return sb.ToString();
} }
public static string GetIdString(this byte[] buffer) { public static string GetIdString(this byte[] buffer) {
const string id_chars = @"abcdefghijklmnopqrstuvwxyz0123456789-_ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const string id_chars = "abcdefghijklmnopqrstuvwxyz0123456789-_ABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuilder sb = new(); StringBuilder sb = new();
foreach(byte b in buffer) foreach(byte b in buffer)
sb.Append(id_chars[b % id_chars.Length]); sb.Append(id_chars[b % id_chars.Length]);

View file

@ -7,28 +7,28 @@ using System.Threading.Tasks;
namespace SharpChat.Flashii { namespace SharpChat.Flashii {
public class FlashiiAuthInfo { public class FlashiiAuthInfo {
[JsonPropertyName(@"success")] [JsonPropertyName("success")]
public bool Success { get; set; } public bool Success { get; set; }
[JsonPropertyName(@"reason")] [JsonPropertyName("reason")]
public string Reason { get; set; } = @"none"; public string Reason { get; set; } = "none";
[JsonPropertyName(@"user_id")] [JsonPropertyName("user_id")]
public long UserId { get; set; } public long UserId { get; set; }
[JsonPropertyName(@"username")] [JsonPropertyName("username")]
public string Username { get; set; } public string Username { get; set; }
[JsonPropertyName(@"colour_raw")] [JsonPropertyName("colour_raw")]
public int ColourRaw { get; set; } public int ColourRaw { get; set; }
[JsonPropertyName(@"hierarchy")] [JsonPropertyName("hierarchy")]
public int Rank { get; set; } public int Rank { get; set; }
[JsonPropertyName(@"is_silenced")] [JsonPropertyName("is_silenced")]
public DateTimeOffset SilencedUntil { get; set; } public DateTimeOffset SilencedUntil { get; set; }
[JsonPropertyName(@"perms")] [JsonPropertyName("perms")]
public ChatUserPermissions Permissions { get; set; } public ChatUserPermissions Permissions { get; set; }
private const string SIG_FMT = "verify#{0}#{1}#{2}"; private const string SIG_FMT = "verify#{0}#{1}#{2}";
@ -50,7 +50,7 @@ namespace SharpChat.Flashii {
{ "ipaddr", ipAddr }, { "ipaddr", ipAddr },
}), }),
Headers = { Headers = {
{ @"X-SharpChat-Signature", sig.GetSignedHash() }, { "X-SharpChat-Signature", sig.GetSignedHash() },
}, },
}; };

View file

@ -27,7 +27,7 @@ namespace SharpChat.Flashii {
[JsonPropertyName("user_name")] [JsonPropertyName("user_name")]
public string UserName { get; set; } public string UserName { get; set; }
[JsonPropertyName(@"user_colour")] [JsonPropertyName("user_colour")]
public int UserColourRaw { get; set; } public int UserColourRaw { get; set; }
public bool HasExpired => !IsPermanent && DateTimeOffset.UtcNow >= ExpiresAt; public bool HasExpired => !IsPermanent && DateTimeOffset.UtcNow >= ExpiresAt;

View file

@ -5,7 +5,7 @@ using System.Text;
namespace SharpChat { namespace SharpChat {
public static class Logger { public static class Logger {
public static void Write(string str) { public static void Write(string str) {
Console.WriteLine(string.Format(@"[{1}] {0}", str, DateTime.Now)); Console.WriteLine(string.Format("[{1}] {0}", str, DateTime.Now));
} }
public static void Write(byte[] bytes) { public static void Write(byte[] bytes) {
@ -16,17 +16,17 @@ namespace SharpChat {
Write(obj?.ToString() ?? string.Empty); Write(obj?.ToString() ?? string.Empty);
} }
[Conditional(@"DEBUG")] [Conditional("DEBUG")]
public static void Debug(string str) { public static void Debug(string str) {
Write(str); Write(str);
} }
[Conditional(@"DEBUG")] [Conditional("DEBUG")]
public static void Debug(byte[] bytes) { public static void Debug(byte[] bytes) {
Write(bytes); Write(bytes);
} }
[Conditional(@"DEBUG")] [Conditional("DEBUG")]
public static void Debug(object obj) { public static void Debug(object obj) {
Write(obj); Write(obj);
} }

View file

@ -30,13 +30,13 @@ namespace SharpChat.Packet {
switch(Reason) { switch(Reason) {
case AuthFailReason.AuthInvalid: case AuthFailReason.AuthInvalid:
default: default:
sb.Append(@"authfail"); sb.Append("authfail");
break; break;
case AuthFailReason.MaxSessions: case AuthFailReason.MaxSessions:
sb.Append(@"sockfail"); sb.Append("sockfail");
break; break;
case AuthFailReason.Banned: case AuthFailReason.Banned:
sb.Append(@"joinfail"); sb.Append("joinfail");
break; break;
} }

View file

@ -27,18 +27,18 @@ namespace SharpChat.Packet {
sb.Append('\t'); sb.Append('\t');
if(Message.Flags.HasFlag(ChatMessageFlags.Action)) if(Message.Flags.HasFlag(ChatMessageFlags.Action))
sb.Append(@"<i>"); sb.Append("<i>");
sb.Append( sb.Append(
Message.Text Message.Text
.Replace(@"<", @"&lt;") .Replace("<", "&lt;")
.Replace(@">", @"&gt;") .Replace(">", "&gt;")
.Replace("\n", @" <br/> ") .Replace("\n", " <br/> ")
.Replace("\t", @" ") .Replace("\t", " ")
); );
if(Message.Flags.HasFlag(ChatMessageFlags.Action)) if(Message.Flags.HasFlag(ChatMessageFlags.Action))
sb.Append(@"</i>"); sb.Append("</i>");
sb.Append('\t'); sb.Append('\t');
sb.Append(SequenceId); sb.Append(SequenceId);

View file

@ -31,10 +31,10 @@ namespace SharpChat.Packet {
sb.Append('\t'); sb.Append('\t');
sb.Append( sb.Append(
msg.Text msg.Text
.Replace(@"<", @"&lt;") .Replace("<", "&lt;")
.Replace(@">", @"&gt;") .Replace(">", "&gt;")
.Replace("\n", @" <br/> ") .Replace("\n", " <br/> ")
.Replace("\t", @" ") .Replace("\t", " ")
); );
break; break;
@ -62,17 +62,17 @@ namespace SharpChat.Packet {
switch(ude.Reason) { switch(ude.Reason) {
case UserDisconnectReason.Flood: case UserDisconnectReason.Flood:
sb.Append(@"flood"); sb.Append("flood");
break; break;
case UserDisconnectReason.Kicked: case UserDisconnectReason.Kicked:
sb.Append(@"kick"); sb.Append("kick");
break; break;
case UserDisconnectReason.TimeOut: case UserDisconnectReason.TimeOut:
sb.Append(@"timeout"); sb.Append("timeout");
break; break;
case UserDisconnectReason.Leave: case UserDisconnectReason.Leave:
default: default:
sb.Append(@"leave"); sb.Append("leave");
break; break;
} }

View file

@ -68,41 +68,41 @@ namespace SharpChat.Packet {
// Abbreviated class name because otherwise shit gets wide // Abbreviated class name because otherwise shit gets wide
public static class LCR { public static class LCR {
public const string GENERIC_ERROR = @"generr"; public const string GENERIC_ERROR = "generr";
public const string COMMAND_NOT_FOUND = @"nocmd"; public const string COMMAND_NOT_FOUND = "nocmd";
public const string COMMAND_NOT_ALLOWED = @"cmdna"; public const string COMMAND_NOT_ALLOWED = "cmdna";
public const string COMMAND_FORMAT_ERROR = @"cmderr"; public const string COMMAND_FORMAT_ERROR = "cmderr";
public const string WELCOME = @"welcome"; public const string WELCOME = "welcome";
public const string BROADCAST = @"say"; public const string BROADCAST = "say";
public const string IP_ADDRESS = @"ipaddr"; public const string IP_ADDRESS = "ipaddr";
public const string USER_NOT_FOUND = @"usernf"; public const string USER_NOT_FOUND = "usernf";
public const string SILENCE_SELF = @"silself"; public const string SILENCE_SELF = "silself";
public const string SILENCE_HIERARCHY = @"silperr"; public const string SILENCE_HIERARCHY = "silperr";
public const string SILENCE_ALREADY = @"silerr"; public const string SILENCE_ALREADY = "silerr";
public const string TARGET_SILENCED = @"silok"; public const string TARGET_SILENCED = "silok";
public const string SILENCED = @"silence"; public const string SILENCED = "silence";
public const string UNSILENCED = @"unsil"; public const string UNSILENCED = "unsil";
public const string TARGET_UNSILENCED = @"usilok"; public const string TARGET_UNSILENCED = "usilok";
public const string NOT_SILENCED = @"usilerr"; public const string NOT_SILENCED = "usilerr";
public const string UNSILENCE_HIERARCHY = @"usilperr"; public const string UNSILENCE_HIERARCHY = "usilperr";
public const string NAME_IN_USE = @"nameinuse"; public const string NAME_IN_USE = "nameinuse";
public const string CHANNEL_INSUFFICIENT_HIERARCHY = @"ipchan"; public const string CHANNEL_INSUFFICIENT_HIERARCHY = "ipchan";
public const string CHANNEL_INVALID_PASSWORD = @"ipwchan"; public const string CHANNEL_INVALID_PASSWORD = "ipwchan";
public const string CHANNEL_NOT_FOUND = @"nochan"; public const string CHANNEL_NOT_FOUND = "nochan";
public const string CHANNEL_ALREADY_EXISTS = @"nischan"; public const string CHANNEL_ALREADY_EXISTS = "nischan";
public const string CHANNEL_NAME_INVALID = "inchan"; public const string CHANNEL_NAME_INVALID = "inchan";
public const string CHANNEL_CREATED = @"crchan"; public const string CHANNEL_CREATED = "crchan";
public const string CHANNEL_DELETE_FAILED = @"ndchan"; public const string CHANNEL_DELETE_FAILED = "ndchan";
public const string CHANNEL_DELETED = @"delchan"; public const string CHANNEL_DELETED = "delchan";
public const string CHANNEL_PASSWORD_CHANGED = @"cpwdchan"; public const string CHANNEL_PASSWORD_CHANGED = "cpwdchan";
public const string CHANNEL_HIERARCHY_CHANGED = @"cprivchan"; public const string CHANNEL_HIERARCHY_CHANGED = "cprivchan";
public const string USERS_LISTING_ERROR = @"whoerr"; public const string USERS_LISTING_ERROR = "whoerr";
public const string USERS_LISTING_CHANNEL = @"whochan"; public const string USERS_LISTING_CHANNEL = "whochan";
public const string USERS_LISTING_SERVER = @"who"; public const string USERS_LISTING_SERVER = "who";
public const string INSUFFICIENT_HIERARCHY = @"rankerr"; public const string INSUFFICIENT_HIERARCHY = "rankerr";
public const string MESSAGE_DELETE_ERROR = @"delerr"; public const string MESSAGE_DELETE_ERROR = "delerr";
public const string KICK_NOT_ALLOWED = @"kickna"; public const string KICK_NOT_ALLOWED = "kickna";
public const string USER_NOT_BANNED = @"notban"; public const string USER_NOT_BANNED = "notban";
public const string USER_UNBANNED = @"unban"; public const string USER_UNBANNED = "unban";
} }
} }

View file

@ -34,16 +34,16 @@ namespace SharpChat.Packet {
switch(Reason) { switch(Reason) {
case UserDisconnectReason.Leave: case UserDisconnectReason.Leave:
default: default:
sb.Append(@"leave"); sb.Append("leave");
break; break;
case UserDisconnectReason.TimeOut: case UserDisconnectReason.TimeOut:
sb.Append(@"timeout"); sb.Append("timeout");
break; break;
case UserDisconnectReason.Kicked: case UserDisconnectReason.Kicked:
sb.Append(@"kick"); sb.Append("kick");
break; break;
case UserDisconnectReason.Flood: case UserDisconnectReason.Flood:
sb.Append(@"flood"); sb.Append("flood");
break; break;
} }

View file

@ -35,7 +35,7 @@ namespace SharpChat {
using HttpClient httpClient = new(new HttpClientHandler() { using HttpClient httpClient = new(new HttpClientHandler() {
UseProxy = false, // we will never and the initial resolving takes forever on linux UseProxy = false, // we will never and the initial resolving takes forever on linux
}); });
httpClient.DefaultRequestHeaders.Add(@"User-Agent", @"SharpChat/20230206"); httpClient.DefaultRequestHeaders.Add("User-Agent", "SharpChat/20230206");
if(hasCancelled) return; if(hasCancelled) return;

View file

@ -32,7 +32,7 @@ namespace SharpChat {
Socket socket = new(_locationIP.AddressFamily, SocketType.Stream, ProtocolType.IP); Socket socket = new(_locationIP.AddressFamily, SocketType.Stream, ProtocolType.IP);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
if(SupportDualStack && Type.GetType(@"Mono.Runtime") == null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { if(SupportDualStack && Type.GetType("Mono.Runtime") == null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);
} }
@ -141,10 +141,10 @@ namespace SharpChat {
+ "Connection: close\r\n" + "Connection: close\r\n"
+ "\r\n" + "\r\n"
+ "{2}"; + "{2}";
string responseBody = File.Exists(@"http-motd.txt") ? File.ReadAllText(@"http-motd.txt") : @"SharpChat"; string responseBody = File.Exists("http-motd.txt") ? File.ReadAllText("http-motd.txt") : "SharpChat";
clientSocket.Stream.Write(Encoding.UTF8.GetBytes(string.Format( clientSocket.Stream.Write(Encoding.UTF8.GetBytes(string.Format(
responseMsg, DateTimeOffset.Now.ToString(@"r"), Encoding.UTF8.GetByteCount(responseBody), responseBody responseMsg, DateTimeOffset.Now.ToString("r"), Encoding.UTF8.GetByteCount(responseBody), responseBody
))); )));
clientSocket.Close(); clientSocket.Close();
return null; return null;

View file

@ -29,7 +29,7 @@ namespace SharpChat {
public static ChatUser Bot { get; } = new ChatUser { public static ChatUser Bot { get; } = new ChatUser {
UserId = -1, UserId = -1,
Username = @"ChatBot", Username = "ChatBot",
Rank = 0, Rank = 0,
Colour = new ChatColour(), Colour = new ChatColour(),
}; };
@ -61,16 +61,16 @@ namespace SharpChat {
Context = new ChatContext(); Context = new ChatContext();
Context.Channels.Add(new ChatChannel(@"Lounge")); Context.Channels.Add(new ChatChannel("Lounge"));
#if DEBUG #if DEBUG
Context.Channels.Add(new ChatChannel(@"Programming")); Context.Channels.Add(new ChatChannel("Programming"));
Context.Channels.Add(new ChatChannel(@"Games")); Context.Channels.Add(new ChatChannel("Games"));
Context.Channels.Add(new ChatChannel(@"Splatoon")); Context.Channels.Add(new ChatChannel("Splatoon"));
Context.Channels.Add(new ChatChannel(@"Password") { Password = @"meow", }); Context.Channels.Add(new ChatChannel("Password") { Password = "meow", });
#endif #endif
Context.Channels.Add(new ChatChannel(@"Staff") { Rank = 5 }); Context.Channels.Add(new ChatChannel("Staff") { Rank = 5 });
Server = new SharpChatWebSocketServer($@"ws://0.0.0.0:{port}"); Server = new SharpChatWebSocketServer($"ws://0.0.0.0:{port}");
} }
public void Listen(ManualResetEvent mre) { public void Listen(ManualResetEvent mre) {
@ -125,7 +125,7 @@ namespace SharpChat {
private void OnError(IWebSocketConnection conn, Exception ex) { private void OnError(IWebSocketConnection conn, Exception ex) {
ChatUserSession sess = GetSession(conn); ChatUserSession sess = GetSession(conn);
string sessId = sess?.Id ?? new string('0', ChatUserSession.ID_LENGTH); string sessId = sess?.Id ?? new string('0', ChatUserSession.ID_LENGTH);
Logger.Write($@"[{sessId} {conn.ConnectionInfo.ClientIpAddress}] {ex}"); Logger.Write($"[{sessId} {conn.ConnectionInfo.ClientIpAddress}] {ex}");
Context.Update(); Context.Update();
} }
@ -225,7 +225,7 @@ namespace SharpChat {
try { try {
fai = await FlashiiAuthInfo.VerifyAsync(HttpClient, authMethod, authToken, ipAddr); fai = await FlashiiAuthInfo.VerifyAsync(HttpClient, authMethod, authToken, ipAddr);
} catch(Exception ex) { } catch(Exception ex) {
Logger.Write($@"<{sess.Id}> Failed to authenticate: {ex}"); Logger.Write($"<{sess.Id}> Failed to authenticate: {ex}");
sess.Send(new AuthFailPacket(AuthFailReason.AuthInvalid)); sess.Send(new AuthFailPacket(AuthFailReason.AuthInvalid));
sess.Dispose(); sess.Dispose();
#if DEBUG #if DEBUG
@ -236,7 +236,7 @@ namespace SharpChat {
} }
if(!fai.Success) { if(!fai.Success) {
Logger.Debug($@"<{sess.Id}> Auth fail: {fai.Reason}"); Logger.Debug($"<{sess.Id}> Auth fail: {fai.Reason}");
sess.Send(new AuthFailPacket(AuthFailReason.AuthInvalid)); sess.Send(new AuthFailPacket(AuthFailReason.AuthInvalid));
sess.Dispose(); sess.Dispose();
return; return;
@ -246,7 +246,7 @@ namespace SharpChat {
try { try {
fbi = await FlashiiBanInfo.CheckAsync(HttpClient, fai.UserId.ToString(), ipAddr); fbi = await FlashiiBanInfo.CheckAsync(HttpClient, fai.UserId.ToString(), ipAddr);
} catch(Exception ex) { } catch(Exception ex) {
Logger.Write($@"<{sess.Id}> Failed auth ban check: {ex}"); Logger.Write($"<{sess.Id}> Failed auth ban check: {ex}");
sess.Send(new AuthFailPacket(AuthFailReason.AuthInvalid)); sess.Send(new AuthFailPacket(AuthFailReason.AuthInvalid));
sess.Dispose(); sess.Dispose();
#if DEBUG #if DEBUG
@ -257,7 +257,7 @@ namespace SharpChat {
} }
if(fbi.IsBanned && !fbi.HasExpired) { if(fbi.IsBanned && !fbi.HasExpired) {
Logger.Write($@"<{sess.Id}> User is banned."); Logger.Write($"<{sess.Id}> User is banned.");
sess.Send(new AuthFailPacket(AuthFailReason.Banned, fbi)); sess.Send(new AuthFailPacket(AuthFailReason.Banned, fbi));
sess.Dispose(); sess.Dispose();
return; return;
@ -284,10 +284,10 @@ namespace SharpChat {
aUser.AddSession(sess); aUser.AddSession(sess);
sess.Send(new LegacyCommandResponse(LCR.WELCOME, false, $@"Welcome to Flashii Chat, {aUser.Username}!")); sess.Send(new LegacyCommandResponse(LCR.WELCOME, false, $"Welcome to Flashii Chat, {aUser.Username}!"));
if(File.Exists(@"welcome.txt")) { if(File.Exists("welcome.txt")) {
IEnumerable<string> lines = File.ReadAllLines(@"welcome.txt").Where(x => !string.IsNullOrWhiteSpace(x)); IEnumerable<string> lines = File.ReadAllLines("welcome.txt").Where(x => !string.IsNullOrWhiteSpace(x));
string line = lines.ElementAtOrDefault(RNG.Next(lines.Count())); string line = lines.ElementAtOrDefault(RNG.Next(lines.Count()));
if(!string.IsNullOrWhiteSpace(line)) if(!string.IsNullOrWhiteSpace(line))
@ -333,7 +333,7 @@ namespace SharpChat {
messageText = messageText.Trim(); messageText = messageText.Trim();
#if DEBUG #if DEBUG
Logger.Write($@"<{sess.Id} {mUser.Username}> {messageText}"); Logger.Write($"<{sess.Id} {mUser.Username}> {messageText}");
#endif #endif
IChatMessage message = null; IChatMessage message = null;
@ -361,12 +361,12 @@ namespace SharpChat {
public IChatMessage HandleV1Command(string message, ChatUser user, ChatChannel channel, ChatUserSession sess) { public IChatMessage HandleV1Command(string message, ChatUser user, ChatChannel channel, ChatUserSession sess) {
string[] parts = message[1..].Split(' '); string[] parts = message[1..].Split(' ');
string commandName = parts[0].Replace(@".", string.Empty).ToLowerInvariant(); string commandName = parts[0].Replace(".", string.Empty).ToLowerInvariant();
for(int i = 1; i < parts.Length; i++) for(int i = 1; i < parts.Length; i++)
parts[i] = parts[i].Replace(@"<", @"&lt;") parts[i] = parts[i].Replace("<", "&lt;")
.Replace(@">", @"&gt;") .Replace(">", "&gt;")
.Replace("\n", @" <br/> "); .Replace("\n", " <br/> ");
IChatCommand command = null; IChatCommand command = null;
foreach(IChatCommand cmd in Commands) foreach(IChatCommand cmd in Commands)
@ -379,11 +379,11 @@ namespace SharpChat {
return command.Dispatch(new ChatCommandContext(parts, user, channel)); return command.Dispatch(new ChatCommandContext(parts, user, channel));
switch(commandName) { switch(commandName) {
case @"nick": // sets a temporary nickname case "nick": // sets a temporary nickname
bool setOthersNick = user.Can(ChatUserPermissions.SetOthersNickname); bool setOthersNick = user.Can(ChatUserPermissions.SetOthersNickname);
if(!setOthersNick && !user.Can(ChatUserPermissions.SetOwnNickname)) { if(!setOthersNick && !user.Can(ChatUserPermissions.SetOwnNickname)) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $@"/{commandName}")); user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{commandName}"));
break; break;
} }
@ -426,8 +426,8 @@ namespace SharpChat {
targetUser.Nickname = nickStr; targetUser.Nickname = nickStr;
channel.Send(new UserUpdatePacket(targetUser, previousName)); channel.Send(new UserUpdatePacket(targetUser, previousName));
break; break;
case @"whisper": // sends a pm to another user case "whisper": // sends a pm to another user
case @"msg": case "msg":
if(parts.Length < 3) { if(parts.Length < 3) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_FORMAT_ERROR)); user.Send(new LegacyCommandResponse(LCR.COMMAND_FORMAT_ERROR));
break; break;
@ -458,12 +458,12 @@ namespace SharpChat {
Target = whisperUser, Target = whisperUser,
TargetName = whisperUser.TargetName, TargetName = whisperUser.TargetName,
Sender = user, Sender = user,
Text = $@"{whisperUser.DisplayName} {whisperStr}", Text = $"{whisperUser.DisplayName} {whisperStr}",
Flags = ChatMessageFlags.Private, Flags = ChatMessageFlags.Private,
})); }));
break; break;
case @"action": // describe an action case "action": // describe an action
case @"me": case "me":
if(parts.Length < 2) if(parts.Length < 2)
break; break;
@ -477,7 +477,7 @@ namespace SharpChat {
Text = actionMsg, Text = actionMsg,
Flags = ChatMessageFlags.Action, Flags = ChatMessageFlags.Action,
}; };
case @"who": // gets all online users/online users in a channel if arg case "who": // gets all online users/online users in a channel if arg
StringBuilder whoChanSB = new(); StringBuilder whoChanSB = new();
string whoChanStr = parts.Length > 1 && !string.IsNullOrEmpty(parts[1]) ? parts[1] : string.Empty; string whoChanStr = parts.Length > 1 && !string.IsNullOrEmpty(parts[1]) ? parts[1] : string.Empty;
@ -502,7 +502,7 @@ namespace SharpChat {
whoChanSB.Append('>'); whoChanSB.Append('>');
whoChanSB.Append(whoUser.DisplayName); whoChanSB.Append(whoUser.DisplayName);
whoChanSB.Append(@"</a>, "); whoChanSB.Append("</a>, ");
} }
if(whoChanSB.Length > 2) if(whoChanSB.Length > 2)
@ -518,7 +518,7 @@ namespace SharpChat {
whoChanSB.Append('>'); whoChanSB.Append('>');
whoChanSB.Append(whoUser.DisplayName); whoChanSB.Append(whoUser.DisplayName);
whoChanSB.Append(@"</a>, "); whoChanSB.Append("</a>, ");
} }
if(whoChanSB.Length > 2) if(whoChanSB.Length > 2)
@ -531,18 +531,18 @@ namespace SharpChat {
// double alias for delchan and delmsg // double alias for delchan and delmsg
// if the argument is a number we're deleting a message // if the argument is a number we're deleting a message
// if the argument is a string we're deleting a channel // if the argument is a string we're deleting a channel
case @"delete": case "delete":
if(parts.Length < 2) { if(parts.Length < 2) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_FORMAT_ERROR)); user.Send(new LegacyCommandResponse(LCR.COMMAND_FORMAT_ERROR));
break; break;
} }
if(parts[1].All(char.IsDigit)) if(parts[1].All(char.IsDigit))
goto case @"delmsg"; goto case "delmsg";
goto case @"delchan"; goto case "delchan";
// anyone can use these // anyone can use these
case @"join": // join a channel case "join": // join a channel
if(parts.Length < 2) if(parts.Length < 2)
break; break;
@ -556,9 +556,9 @@ namespace SharpChat {
Context.SwitchChannel(user, joinChan, string.Join(' ', parts.Skip(2))); Context.SwitchChannel(user, joinChan, string.Join(' ', parts.Skip(2)));
break; break;
case @"create": // create a new channel case "create": // create a new channel
if(user.Can(ChatUserPermissions.CreateChannel)) { if(user.Can(ChatUserPermissions.CreateChannel)) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $@"/{commandName}")); user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{commandName}"));
break; break;
} }
@ -599,7 +599,7 @@ namespace SharpChat {
Context.SwitchChannel(user, createChan, createChan.Password); Context.SwitchChannel(user, createChan, createChan.Password);
user.Send(new LegacyCommandResponse(LCR.CHANNEL_CREATED, false, createChan.Name)); user.Send(new LegacyCommandResponse(LCR.CHANNEL_CREATED, false, createChan.Name));
break; break;
case @"delchan": // delete a channel case "delchan": // delete a channel
if(parts.Length < 2 || string.IsNullOrWhiteSpace(parts[1])) { if(parts.Length < 2 || string.IsNullOrWhiteSpace(parts[1])) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_FORMAT_ERROR)); user.Send(new LegacyCommandResponse(LCR.COMMAND_FORMAT_ERROR));
break; break;
@ -621,10 +621,10 @@ namespace SharpChat {
Context.Channels.Remove(delChan); Context.Channels.Remove(delChan);
user.Send(new LegacyCommandResponse(LCR.CHANNEL_DELETED, false, delChan.Name)); user.Send(new LegacyCommandResponse(LCR.CHANNEL_DELETED, false, delChan.Name));
break; break;
case @"password": // set a password on the channel case "password": // set a password on the channel
case @"pwd": case "pwd":
if(!user.Can(ChatUserPermissions.SetChannelPassword) || channel.Owner != user) { if(!user.Can(ChatUserPermissions.SetChannelPassword) || channel.Owner != user) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $@"/{commandName}")); user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{commandName}"));
break; break;
} }
@ -636,11 +636,11 @@ namespace SharpChat {
Context.Channels.Update(channel, password: chanPass); Context.Channels.Update(channel, password: chanPass);
user.Send(new LegacyCommandResponse(LCR.CHANNEL_PASSWORD_CHANGED, false)); user.Send(new LegacyCommandResponse(LCR.CHANNEL_PASSWORD_CHANGED, false));
break; break;
case @"privilege": // sets a minimum hierarchy requirement on the channel case "privilege": // sets a minimum hierarchy requirement on the channel
case @"rank": case "rank":
case @"priv": case "priv":
if(!user.Can(ChatUserPermissions.SetChannelHierarchy) || channel.Owner != user) { if(!user.Can(ChatUserPermissions.SetChannelHierarchy) || channel.Owner != user) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $@"/{commandName}")); user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{commandName}"));
break; break;
} }
@ -653,19 +653,19 @@ namespace SharpChat {
user.Send(new LegacyCommandResponse(LCR.CHANNEL_HIERARCHY_CHANGED, false)); user.Send(new LegacyCommandResponse(LCR.CHANNEL_HIERARCHY_CHANGED, false));
break; break;
case @"say": // pretend to be the bot case "say": // pretend to be the bot
if(!user.Can(ChatUserPermissions.Broadcast)) { if(!user.Can(ChatUserPermissions.Broadcast)) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $@"/{commandName}")); user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{commandName}"));
break; break;
} }
Context.Send(new LegacyCommandResponse(LCR.BROADCAST, false, string.Join(' ', parts.Skip(1)))); Context.Send(new LegacyCommandResponse(LCR.BROADCAST, false, string.Join(' ', parts.Skip(1))));
break; break;
case @"delmsg": // deletes a message case "delmsg": // deletes a message
bool deleteAnyMessage = user.Can(ChatUserPermissions.DeleteAnyMessage); bool deleteAnyMessage = user.Can(ChatUserPermissions.DeleteAnyMessage);
if(!deleteAnyMessage && !user.Can(ChatUserPermissions.DeleteOwnMessage)) { if(!deleteAnyMessage && !user.Can(ChatUserPermissions.DeleteOwnMessage)) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $@"/{commandName}")); user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{commandName}"));
break; break;
} }
@ -683,12 +683,12 @@ namespace SharpChat {
Context.Events.Remove(delMsg); Context.Events.Remove(delMsg);
break; break;
case @"kick": // kick a user from the server case "kick": // kick a user from the server
case @"ban": // ban a user from the server, this differs from /kick in that it adds all remote address to the ip banlist case "ban": // ban a user from the server, this differs from /kick in that it adds all remote address to the ip banlist
bool isBanning = commandName == @"ban"; bool isBanning = commandName == "ban";
if(!user.Can(isBanning ? ChatUserPermissions.BanUser : ChatUserPermissions.KickUser)) { if(!user.Can(isBanning ? ChatUserPermissions.BanUser : ChatUserPermissions.KickUser)) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $@"/{commandName}")); user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{commandName}"));
break; break;
} }
@ -698,7 +698,7 @@ namespace SharpChat {
ChatUser banUser = null; ChatUser banUser = null;
if(banUserTarget == null || (banUser = Context.Users.Get(banUserTarget)) == null) { if(banUserTarget == null || (banUser = Context.Users.Get(banUserTarget)) == null) {
user.Send(new LegacyCommandResponse(LCR.USER_NOT_FOUND, true, banUser == null ? @"User" : banUserTarget)); user.Send(new LegacyCommandResponse(LCR.USER_NOT_FOUND, true, banUser == null ? "User" : banUserTarget));
break; break;
} }
@ -746,10 +746,10 @@ namespace SharpChat {
Context.BanUser(banUser, duration); Context.BanUser(banUser, duration);
}).Wait(); }).Wait();
break; break;
case @"pardon": case "pardon":
case @"unban": case "unban":
if(!user.Can(ChatUserPermissions.BanUser | ChatUserPermissions.KickUser)) { if(!user.Can(ChatUserPermissions.BanUser | ChatUserPermissions.KickUser)) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $@"/{commandName}")); user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{commandName}"));
break; break;
} }
@ -784,10 +784,10 @@ namespace SharpChat {
user.Send(new LegacyCommandResponse(LCR.USER_NOT_BANNED, true, unbanUserTarget)); user.Send(new LegacyCommandResponse(LCR.USER_NOT_BANNED, true, unbanUserTarget));
}).Wait(); }).Wait();
break; break;
case @"pardonip": case "pardonip":
case @"unbanip": case "unbanip":
if(!user.Can(ChatUserPermissions.BanUser | ChatUserPermissions.KickUser)) { if(!user.Can(ChatUserPermissions.BanUser | ChatUserPermissions.KickUser)) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $@"/{commandName}")); user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{commandName}"));
break; break;
} }
@ -814,10 +814,10 @@ namespace SharpChat {
user.Send(new LegacyCommandResponse(LCR.USER_NOT_BANNED, true, unbanAddrTarget)); user.Send(new LegacyCommandResponse(LCR.USER_NOT_BANNED, true, unbanAddrTarget));
}).Wait(); }).Wait();
break; break;
case @"bans": // gets a list of bans case "bans": // gets a list of bans
case @"banned": case "banned":
if(!user.Can(ChatUserPermissions.BanUser | ChatUserPermissions.KickUser)) { if(!user.Can(ChatUserPermissions.BanUser | ChatUserPermissions.KickUser)) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $@"/{commandName}")); user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{commandName}"));
break; break;
} }
@ -827,16 +827,16 @@ namespace SharpChat {
)); ));
}).Wait(); }).Wait();
break; break;
case @"silence": // silence a user case "silence": // silence a user
if(!user.Can(ChatUserPermissions.SilenceUser)) { if(!user.Can(ChatUserPermissions.SilenceUser)) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $@"/{commandName}")); user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{commandName}"));
break; break;
} }
ChatUser silUser; ChatUser silUser;
if(parts.Length < 2 || (silUser = Context.Users.Get(parts[1])) == null) { if(parts.Length < 2 || (silUser = Context.Users.Get(parts[1])) == null) {
user.Send(new LegacyCommandResponse(LCR.USER_NOT_FOUND, true, parts.Length < 2 ? @"User" : parts[1])); user.Send(new LegacyCommandResponse(LCR.USER_NOT_FOUND, true, parts.Length < 2 ? "User" : parts[1]));
break; break;
} }
@ -870,16 +870,16 @@ namespace SharpChat {
silUser.Send(new LegacyCommandResponse(LCR.SILENCED, false)); silUser.Send(new LegacyCommandResponse(LCR.SILENCED, false));
user.Send(new LegacyCommandResponse(LCR.TARGET_SILENCED, false, silUser.DisplayName)); user.Send(new LegacyCommandResponse(LCR.TARGET_SILENCED, false, silUser.DisplayName));
break; break;
case @"unsilence": // unsilence a user case "unsilence": // unsilence a user
if(!user.Can(ChatUserPermissions.SilenceUser)) { if(!user.Can(ChatUserPermissions.SilenceUser)) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $@"/{commandName}")); user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{commandName}"));
break; break;
} }
ChatUser unsilUser; ChatUser unsilUser;
if(parts.Length < 2 || (unsilUser = Context.Users.Get(parts[1])) == null) { if(parts.Length < 2 || (unsilUser = Context.Users.Get(parts[1])) == null) {
user.Send(new LegacyCommandResponse(LCR.USER_NOT_FOUND, true, parts.Length < 2 ? @"User" : parts[1])); user.Send(new LegacyCommandResponse(LCR.USER_NOT_FOUND, true, parts.Length < 2 ? "User" : parts[1]));
break; break;
} }
@ -897,16 +897,16 @@ namespace SharpChat {
unsilUser.Send(new LegacyCommandResponse(LCR.UNSILENCED, false)); unsilUser.Send(new LegacyCommandResponse(LCR.UNSILENCED, false));
user.Send(new LegacyCommandResponse(LCR.TARGET_UNSILENCED, false, unsilUser.DisplayName)); user.Send(new LegacyCommandResponse(LCR.TARGET_UNSILENCED, false, unsilUser.DisplayName));
break; break;
case @"ip": // gets a user's ip (from all connections in this case) case "ip": // gets a user's ip (from all connections in this case)
case @"whois": case "whois":
if(!user.Can(ChatUserPermissions.SeeIPAddress)) { if(!user.Can(ChatUserPermissions.SeeIPAddress)) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, @"/ip")); user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, "/ip"));
break; break;
} }
ChatUser ipUser; ChatUser ipUser;
if(parts.Length < 2 || (ipUser = Context.Users.Get(parts[1])) == null) { if(parts.Length < 2 || (ipUser = Context.Users.Get(parts[1])) == null) {
user.Send(new LegacyCommandResponse(LCR.USER_NOT_FOUND, true, parts.Length < 2 ? @"User" : parts[1])); user.Send(new LegacyCommandResponse(LCR.USER_NOT_FOUND, true, parts.Length < 2 ? "User" : parts[1]));
break; break;
} }
@ -914,10 +914,10 @@ namespace SharpChat {
user.Send(new LegacyCommandResponse(LCR.IP_ADDRESS, false, ipUser.Username, ip)); user.Send(new LegacyCommandResponse(LCR.IP_ADDRESS, false, ipUser.Username, ip));
break; break;
case @"shutdown": case "shutdown":
case @"restart": case "restart":
if(user.UserId != 1) { if(user.UserId != 1) {
user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $@"/{commandName}")); user.Send(new LegacyCommandResponse(LCR.COMMAND_NOT_ALLOWED, true, $"/{commandName}"));
break; break;
} }
@ -925,7 +925,7 @@ namespace SharpChat {
break; break;
IsShuttingDown = true; IsShuttingDown = true;
if(commandName == @"restart") if(commandName == "restart")
lock(SessionsLock) lock(SessionsLock)
Sessions.ForEach(s => s.PrepareForRestart()); Sessions.ForEach(s => s.PrepareForRestart());