sharp-chat/SharpChat/ChatChannel.cs

83 lines
2.2 KiB
C#
Raw Normal View History

2022-08-30 15:00:58 +00:00
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SharpChat {
public class ChatChannel : IPacketTarget {
public string Name { get; set; }
public string Password { get; set; } = string.Empty;
public bool IsTemporary { get; set; } = false;
public int Rank { get; set; } = 0;
public ChatUser Owner { get; set; } = null;
2023-02-07 15:01:56 +00:00
private List<ChatUser> Users { get; } = new();
2022-08-30 15:00:58 +00:00
public bool HasPassword
=> !string.IsNullOrWhiteSpace(Password);
public string TargetName => Name;
2023-02-08 03:32:12 +00:00
public ChatChannel() { }
2022-08-30 15:00:58 +00:00
public ChatChannel(string name) {
Name = name;
}
public bool HasUser(ChatUser user) {
2023-02-07 15:01:56 +00:00
lock(Users)
2022-08-30 15:00:58 +00:00
return Users.Contains(user);
}
public void UserJoin(ChatUser user) {
2023-02-07 15:01:56 +00:00
if(!user.InChannel(this)) {
2022-08-30 15:00:58 +00:00
// Remove this, a different means for this should be established for V1 compat.
user.Channel?.UserLeave(user);
user.JoinChannel(this);
}
2023-02-07 15:01:56 +00:00
lock(Users) {
if(!HasUser(user))
2022-08-30 15:00:58 +00:00
Users.Add(user);
}
}
public void UserLeave(ChatUser user) {
2023-02-07 15:01:56 +00:00
lock(Users)
2022-08-30 15:00:58 +00:00
Users.Remove(user);
2023-02-07 15:01:56 +00:00
if(user.InChannel(this))
2022-08-30 15:00:58 +00:00
user.LeaveChannel(this);
}
public void Send(IServerPacket packet) {
2023-02-07 15:01:56 +00:00
lock(Users) {
foreach(ChatUser user in Users)
2022-08-30 15:00:58 +00:00
user.Send(packet);
}
}
public IEnumerable<ChatUser> GetUsers(IEnumerable<ChatUser> exclude = null) {
2023-02-07 15:01:56 +00:00
lock(Users) {
2022-08-30 15:00:58 +00:00
IEnumerable<ChatUser> users = Users.OrderByDescending(x => x.Rank);
2023-02-07 15:01:56 +00:00
if(exclude != null)
2022-08-30 15:00:58 +00:00
users = users.Except(exclude);
return users.ToList();
}
}
public string Pack() {
2023-02-07 15:01:56 +00:00
StringBuilder sb = new();
2022-08-30 15:00:58 +00:00
sb.Append(Name);
sb.Append('\t');
sb.Append(string.IsNullOrEmpty(Password) ? '0' : '1');
sb.Append('\t');
sb.Append(IsTemporary ? '1' : '0');
return sb.ToString();
}
}
}