You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

SocketGroupChannel.cs 14 kB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. using Discord.Audio;
  2. using Discord.Rest;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Collections.Immutable;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Threading.Tasks;
  11. using Model = Discord.API.Channel;
  12. using UserModel = Discord.API.User;
  13. using VoiceStateModel = Discord.API.VoiceState;
  14. namespace Discord.WebSocket
  15. {
  16. /// <summary>
  17. /// Represents a WebSocket-based private group channel.
  18. /// </summary>
  19. [DebuggerDisplay(@"{DebuggerDisplay,nq}")]
  20. public class SocketGroupChannel : SocketChannel, IGroupChannel, ISocketPrivateChannel, ISocketMessageChannel, ISocketAudioChannel
  21. {
  22. private readonly MessageCache _messages;
  23. private readonly ConcurrentDictionary<ulong, SocketVoiceState> _voiceStates;
  24. private string _iconId;
  25. private ConcurrentDictionary<ulong, SocketGroupUser> _users;
  26. /// <inheritdoc />
  27. public string Name { get; private set; }
  28. /// <inheritdoc />
  29. public IReadOnlyCollection<SocketMessage> CachedMessages => _messages?.Messages ?? ImmutableArray.Create<SocketMessage>();
  30. public new IReadOnlyCollection<SocketGroupUser> Users => _users.ToReadOnlyCollection();
  31. public IReadOnlyCollection<SocketGroupUser> Recipients
  32. => _users.Select(x => x.Value).Where(x => x.Id != Discord.CurrentUser.Id).ToReadOnlyCollection(() => _users.Count - 1);
  33. internal SocketGroupChannel(DiscordSocketClient discord, ulong id)
  34. : base(discord, id)
  35. {
  36. if (Discord.MessageCacheSize > 0)
  37. _messages = new MessageCache(Discord);
  38. _voiceStates = new ConcurrentDictionary<ulong, SocketVoiceState>(ConcurrentHashSet.DefaultConcurrencyLevel, 5);
  39. _users = new ConcurrentDictionary<ulong, SocketGroupUser>(ConcurrentHashSet.DefaultConcurrencyLevel, 5);
  40. }
  41. internal static SocketGroupChannel Create(DiscordSocketClient discord, ClientState state, Model model)
  42. {
  43. var entity = new SocketGroupChannel(discord, model.Id);
  44. entity.Update(state, model);
  45. return entity;
  46. }
  47. internal override void Update(ClientState state, Model model)
  48. {
  49. if (model.Name.IsSpecified)
  50. Name = model.Name.Value;
  51. if (model.Icon.IsSpecified)
  52. _iconId = model.Icon.Value;
  53. if (model.Recipients.IsSpecified)
  54. UpdateUsers(state, model.Recipients.Value);
  55. }
  56. private void UpdateUsers(ClientState state, UserModel[] models)
  57. {
  58. var users = new ConcurrentDictionary<ulong, SocketGroupUser>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(models.Length * 1.05));
  59. for (int i = 0; i < models.Length; i++)
  60. users[models[i].Id] = SocketGroupUser.Create(this, state, models[i]);
  61. _users = users;
  62. }
  63. /// <inheritdoc />
  64. public Task LeaveAsync(RequestOptions options = null)
  65. => ChannelHelper.DeleteAsync(this, Discord, options);
  66. /// <exception cref="NotSupportedException">Voice is not yet supported for group channels.</exception>
  67. public Task<IAudioClient> ConnectAsync()
  68. {
  69. throw new NotSupportedException("Voice is not yet supported for group channels.");
  70. }
  71. //Messages
  72. /// <inheritdoc />
  73. public SocketMessage GetCachedMessage(ulong id)
  74. => _messages?.Get(id);
  75. public async Task<IMessage> GetMessageAsync(ulong id, RequestOptions options = null)
  76. {
  77. IMessage msg = _messages?.Get(id);
  78. if (msg == null)
  79. msg = await ChannelHelper.GetMessageAsync(this, Discord, id, options).ConfigureAwait(false);
  80. return msg;
  81. }
  82. public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
  83. => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, CacheMode.AllowDownload, options);
  84. public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
  85. => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, CacheMode.AllowDownload, options);
  86. public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
  87. => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, CacheMode.AllowDownload, options);
  88. /// <inheritdoc />
  89. public IReadOnlyCollection<SocketMessage> GetCachedMessages(int limit = DiscordConfig.MaxMessagesPerBatch)
  90. => SocketChannelHelper.GetCachedMessages(this, Discord, _messages, null, Direction.Before, limit);
  91. /// <inheritdoc />
  92. public IReadOnlyCollection<SocketMessage> GetCachedMessages(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch)
  93. => SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessageId, dir, limit);
  94. /// <inheritdoc />
  95. public IReadOnlyCollection<SocketMessage> GetCachedMessages(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch)
  96. => SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessage.Id, dir, limit);
  97. /// <inheritdoc />
  98. public Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(RequestOptions options = null)
  99. => ChannelHelper.GetPinnedMessagesAsync(this, Discord, options);
  100. /// <inheritdoc />
  101. /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
  102. public Task<RestUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null)
  103. => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, options);
  104. /// <inheritdoc />
  105. public Task<RestUserMessage> SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null)
  106. => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, options);
  107. /// <inheritdoc />
  108. public Task<RestUserMessage> SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null)
  109. => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, options);
  110. /// <inheritdoc />
  111. public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null)
  112. => ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options);
  113. /// <inheritdoc />
  114. public Task DeleteMessageAsync(IMessage message, RequestOptions options = null)
  115. => ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options);
  116. /// <inheritdoc />
  117. public Task TriggerTypingAsync(RequestOptions options = null)
  118. => ChannelHelper.TriggerTypingAsync(this, Discord, options);
  119. /// <inheritdoc />
  120. public IDisposable EnterTypingState(RequestOptions options = null)
  121. => ChannelHelper.EnterTypingState(this, Discord, options);
  122. internal void AddMessage(SocketMessage msg)
  123. => _messages?.Add(msg);
  124. internal SocketMessage RemoveMessage(ulong id)
  125. => _messages?.Remove(id);
  126. //Users
  127. /// <summary>
  128. /// Gets a user from this group.
  129. /// </summary>
  130. /// <param name="id">The snowflake identifier of the user.</param>
  131. /// <returns>
  132. /// A WebSocket-based group user associated with the snowflake identifier.
  133. /// </returns>
  134. public new SocketGroupUser GetUser(ulong id)
  135. {
  136. if (_users.TryGetValue(id, out SocketGroupUser user))
  137. return user;
  138. return null;
  139. }
  140. internal SocketGroupUser GetOrAddUser(UserModel model)
  141. {
  142. if (_users.TryGetValue(model.Id, out SocketGroupUser user))
  143. return user;
  144. else
  145. {
  146. var privateUser = SocketGroupUser.Create(this, Discord.State, model);
  147. privateUser.GlobalUser.AddRef();
  148. _users[privateUser.Id] = privateUser;
  149. return privateUser;
  150. }
  151. }
  152. internal SocketGroupUser RemoveUser(ulong id)
  153. {
  154. if (_users.TryRemove(id, out SocketGroupUser user))
  155. {
  156. user.GlobalUser.RemoveRef(Discord);
  157. return user;
  158. }
  159. return null;
  160. }
  161. //Voice States
  162. internal SocketVoiceState AddOrUpdateVoiceState(ClientState state, VoiceStateModel model)
  163. {
  164. var voiceChannel = state.GetChannel(model.ChannelId.Value) as SocketVoiceChannel;
  165. var voiceState = SocketVoiceState.Create(voiceChannel, model);
  166. _voiceStates[model.UserId] = voiceState;
  167. return voiceState;
  168. }
  169. internal SocketVoiceState? GetVoiceState(ulong id)
  170. {
  171. if (_voiceStates.TryGetValue(id, out SocketVoiceState voiceState))
  172. return voiceState;
  173. return null;
  174. }
  175. internal SocketVoiceState? RemoveVoiceState(ulong id)
  176. {
  177. if (_voiceStates.TryRemove(id, out SocketVoiceState voiceState))
  178. return voiceState;
  179. return null;
  180. }
  181. /// <summary>
  182. /// Returns the name of the group.
  183. /// </summary>
  184. public override string ToString() => Name;
  185. private string DebuggerDisplay => $"{Name} ({Id}, Group)";
  186. internal new SocketGroupChannel Clone() => MemberwiseClone() as SocketGroupChannel;
  187. //SocketChannel
  188. /// <inheritdoc />
  189. internal override IReadOnlyCollection<SocketUser> GetUsersInternal() => Users;
  190. /// <inheritdoc />
  191. internal override SocketUser GetUserInternal(ulong id) => GetUser(id);
  192. //ISocketPrivateChannel
  193. /// <inheritdoc />
  194. IReadOnlyCollection<SocketUser> ISocketPrivateChannel.Recipients => Recipients;
  195. //IPrivateChannel
  196. /// <inheritdoc />
  197. IReadOnlyCollection<IUser> IPrivateChannel.Recipients => Recipients;
  198. //IMessageChannel
  199. /// <inheritdoc />
  200. async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
  201. {
  202. if (mode == CacheMode.AllowDownload)
  203. return await GetMessageAsync(id, options).ConfigureAwait(false);
  204. else
  205. return GetCachedMessage(id);
  206. }
  207. /// <inheritdoc />
  208. IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)
  209. => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, mode, options);
  210. /// <inheritdoc />
  211. IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options)
  212. => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, mode, options);
  213. /// <inheritdoc />
  214. IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options)
  215. => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, mode, options);
  216. /// <inheritdoc />
  217. async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options)
  218. => await GetPinnedMessagesAsync(options).ConfigureAwait(false);
  219. /// <inheritdoc />
  220. async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options)
  221. => await SendFileAsync(filePath, text, isTTS, embed, options).ConfigureAwait(false);
  222. /// <inheritdoc />
  223. async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options)
  224. => await SendFileAsync(stream, filename, text, isTTS, embed, options).ConfigureAwait(false);
  225. /// <inheritdoc />
  226. async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options)
  227. => await SendMessageAsync(text, isTTS, embed, options).ConfigureAwait(false);
  228. //IAudioChannel
  229. /// <inheritdoc />
  230. /// <exception cref="NotSupportedException">Connecting to a group channel is not supported.</exception>
  231. Task<IAudioClient> IAudioChannel.ConnectAsync(bool selfDeaf, bool selfMute, bool external) { throw new NotSupportedException(); }
  232. Task IAudioChannel.DisconnectAsync() { throw new NotSupportedException(); }
  233. //IChannel
  234. /// <inheritdoc />
  235. Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
  236. => Task.FromResult<IUser>(GetUser(id));
  237. /// <inheritdoc />
  238. IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
  239. => ImmutableArray.Create<IReadOnlyCollection<IUser>>(Users).ToAsyncEnumerable();
  240. }
  241. }