sharp-chat/SharpChat/Packet/ChatMessageAddPacket.cs

82 lines
2.3 KiB
C#
Raw Normal View History

using SharpChat.EventStorage;
2022-08-30 15:00:58 +00:00
using System;
using System.Text;
namespace SharpChat.Packet {
2022-08-30 15:00:58 +00:00
public class ChatMessageAddPacket : ServerPacket {
public DateTimeOffset Created { get; }
public long UserId { get; }
public string Text { get; }
public bool IsAction { get; }
public bool IsPrivate { get; }
2022-08-30 15:00:58 +00:00
public ChatMessageAddPacket(
long msgId,
DateTimeOffset created,
long userId,
string text,
bool isAction,
bool isPrivate
) : base(msgId) {
Created = created;
UserId = userId < 0 ? -1 : userId;
Text = text;
IsAction = isAction;
IsPrivate = isPrivate;
}
public static ChatMessageAddPacket FromStoredEvent(StoredEventInfo sei) {
if(sei == null)
throw new ArgumentNullException(nameof(sei));
if(sei.Type is not "msg:add" and not "SharpChat.Events.ChatMessage")
throw new ArgumentException("Wrong event type.", nameof(sei));
2022-08-30 15:00:58 +00:00
return new ChatMessageAddPacket(
sei.Id,
sei.Created,
sei.Sender?.UserId ?? -1,
string.Empty, // todo: this
(sei.Flags & StoredEventFlags.Action) > 0,
(sei.Flags & StoredEventFlags.Private) > 0
);
2022-08-30 15:00:58 +00:00
}
2024-05-10 15:24:43 +00:00
public override string Pack() {
2023-02-07 15:01:56 +00:00
StringBuilder sb = new();
2022-08-30 15:00:58 +00:00
2023-02-07 14:34:31 +00:00
sb.Append('2');
2022-08-30 15:00:58 +00:00
sb.Append('\t');
sb.Append(Created.ToUnixTimeSeconds());
2022-08-30 15:00:58 +00:00
sb.Append('\t');
sb.Append(UserId);
2022-08-30 15:00:58 +00:00
sb.Append('\t');
if(IsAction)
sb.Append("<i>");
2022-08-30 15:00:58 +00:00
sb.Append(
Text.Replace("<", "&lt;")
.Replace(">", "&gt;")
.Replace("\n", " <br/> ")
.Replace("\t", " ")
2022-08-30 15:00:58 +00:00
);
if(IsAction)
sb.Append("</i>");
2022-08-30 15:00:58 +00:00
sb.Append('\t');
sb.Append(SequenceId);
sb.AppendFormat(
"\t1{0}0{1}{2}",
IsAction ? '1' : '0',
IsAction ? '0' : '1',
IsPrivate ? '1' : '0'
2022-08-30 15:00:58 +00:00
);
2024-05-10 15:24:43 +00:00
return sb.ToString();
2022-08-30 15:00:58 +00:00
}
}
}