sharp-chat/SharpChat/Packet/ChatMessageAddPacket.cs

81 lines
2.3 KiB
C#

using SharpChat.EventStorage;
using System;
using System.Text;
namespace SharpChat.Packet {
public class ChatMessageAddPacket : ServerPacket {
public DateTimeOffset Created { get; }
public long UserId { get; }
public string Text { get; }
public bool IsAction { get; }
public bool IsPrivate { get; }
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));
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
);
}
public override string Pack() {
StringBuilder sb = new();
sb.Append('2');
sb.Append('\t');
sb.Append(Created.ToUnixTimeSeconds());
sb.Append('\t');
sb.Append(UserId);
sb.Append('\t');
if(IsAction)
sb.Append("<i>");
sb.Append(
Text.Replace("<", "&lt;")
.Replace(">", "&gt;")
.Replace("\n", " <br/> ")
.Replace("\t", " ")
);
if(IsAction)
sb.Append("</i>");
sb.Append('\t');
sb.Append(SequenceId);
sb.AppendFormat(
"\t1{0}0{1}{2}",
IsAction ? '1' : '0',
IsAction ? '0' : '1',
IsPrivate ? '1' : '0'
);
return sb.ToString();
}
}
}