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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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 string _iconId;
  24. private ConcurrentDictionary<ulong, SocketGroupUser> _users;
  25. private readonly ConcurrentDictionary<ulong, SocketVoiceState> _voiceStates;
  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. public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null)
  111. => ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options);
  112. public Task DeleteMessageAsync(IMessage message, RequestOptions options = null)
  113. => ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options);
  114. /// <inheritdoc />
  115. public Task TriggerTypingAsync(RequestOptions options = null)
  116. => ChannelHelper.TriggerTypingAsync(this, Discord, options);
  117. /// <inheritdoc />
  118. public IDisposable EnterTypingState(RequestOptions options = null)
  119. => ChannelHelper.EnterTypingState(this, Discord, options);
  120. internal void AddMessage(SocketMessage msg)
  121. => _messages?.Add(msg);
  122. internal SocketMessage RemoveMessage(ulong id)
  123. => _messages?.Remove(id);
  124. //Users
  125. /// <summary>
  126. /// Gets a user from this group.
  127. /// </summary>
  128. /// <param name="id">The snowflake identifier of the user.</param>
  129. /// <returns>
  130. /// A WebSocket-based group user associated with the snowflake identifier.
  131. /// </returns>
  132. public new SocketGroupUser GetUser(ulong id)
  133. {
  134. if (_users.TryGetValue(id, out SocketGroupUser user))
  135. return user;
  136. return null;
  137. }
  138. internal SocketGroupUser GetOrAddUser(UserModel model)
  139. {
  140. if (_users.TryGetValue(model.Id, out SocketGroupUser user))
  141. return user as SocketGroupUser;
  142. else
  143. {
  144. var privateUser = SocketGroupUser.Create(this, Discord.State, model);
  145. privateUser.GlobalUser.AddRef();
  146. _users[privateUser.Id] = privateUser;
  147. return privateUser;
  148. }
  149. }
  150. internal SocketGroupUser RemoveUser(ulong id)
  151. {
  152. if (_users.TryRemove(id, out SocketGroupUser user))
  153. {
  154. user.GlobalUser.RemoveRef(Discord);
  155. return user as SocketGroupUser;
  156. }
  157. return null;
  158. }
  159. //Voice States
  160. internal SocketVoiceState AddOrUpdateVoiceState(ClientState state, VoiceStateModel model)
  161. {
  162. var voiceChannel = state.GetChannel(model.ChannelId.Value) as SocketVoiceChannel;
  163. var voiceState = SocketVoiceState.Create(voiceChannel, model);
  164. _voiceStates[model.UserId] = voiceState;
  165. return voiceState;
  166. }
  167. internal SocketVoiceState? GetVoiceState(ulong id)
  168. {
  169. if (_voiceStates.TryGetValue(id, out SocketVoiceState voiceState))
  170. return voiceState;
  171. return null;
  172. }
  173. internal SocketVoiceState? RemoveVoiceState(ulong id)
  174. {
  175. if (_voiceStates.TryRemove(id, out SocketVoiceState voiceState))
  176. return voiceState;
  177. return null;
  178. }
  179. /// <summary>
  180. /// Returns the name of the group.
  181. /// </summary>
  182. public override string ToString() => Name;
  183. private string DebuggerDisplay => $"{Name} ({Id}, Group)";
  184. internal new SocketGroupChannel Clone() => MemberwiseClone() as SocketGroupChannel;
  185. //SocketChannel
  186. /// <inheritdoc />
  187. internal override IReadOnlyCollection<SocketUser> GetUsersInternal() => Users;
  188. /// <inheritdoc />
  189. internal override SocketUser GetUserInternal(ulong id) => GetUser(id);
  190. //ISocketPrivateChannel
  191. /// <inheritdoc />
  192. IReadOnlyCollection<SocketUser> ISocketPrivateChannel.Recipients => Recipients;
  193. //IPrivateChannel
  194. /// <inheritdoc />
  195. IReadOnlyCollection<IUser> IPrivateChannel.Recipients => Recipients;
  196. //IMessageChannel
  197. /// <inheritdoc />
  198. async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
  199. {
  200. if (mode == CacheMode.AllowDownload)
  201. return await GetMessageAsync(id, options).ConfigureAwait(false);
  202. else
  203. return GetCachedMessage(id);
  204. }
  205. /// <inheritdoc />
  206. IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)
  207. => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, mode, options);
  208. /// <inheritdoc />
  209. IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options)
  210. => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, mode, options);
  211. /// <inheritdoc />
  212. IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options)
  213. => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, mode, options);
  214. /// <inheritdoc />
  215. async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options)
  216. => await GetPinnedMessagesAsync(options).ConfigureAwait(false);
  217. /// <inheritdoc />
  218. async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options)
  219. => await SendFileAsync(filePath, text, isTTS, embed, options).ConfigureAwait(false);
  220. /// <inheritdoc />
  221. async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options)
  222. => await SendFileAsync(stream, filename, text, isTTS, embed, options).ConfigureAwait(false);
  223. /// <inheritdoc />
  224. async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options)
  225. => await SendMessageAsync(text, isTTS, embed, options).ConfigureAwait(false);
  226. //IAudioChannel
  227. /// <inheritdoc />
  228. /// <exception cref="NotSupportedException">Connecting to a group channel is not supported.</exception>
  229. Task<IAudioClient> IAudioChannel.ConnectAsync(bool selfDeaf, bool selfMute, bool external) { throw new NotSupportedException(); }
  230. Task IAudioChannel.DisconnectAsync() { throw new NotSupportedException(); }
  231. //IChannel
  232. /// <inheritdoc />
  233. Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
  234. => Task.FromResult<IUser>(GetUser(id));
  235. /// <inheritdoc />
  236. IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
  237. => ImmutableArray.Create<IReadOnlyCollection<IUser>>(Users).ToAsyncEnumerable();
  238. }
  239. }