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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 the group user from the WebSocket cache.
  127. /// </summary>
  128. /// <remarks>
  129. /// This method does NOT attempt to fetch the user if they don't exist in the cache. To guarantee a return
  130. /// from an existing user that doesn't exist in cache, use <see cref="DiscordRestClient.GetUserAsync" />.
  131. /// </remarks>
  132. /// <param name="id">The ID of the user.</param>
  133. /// <returns>
  134. /// The user in the group.
  135. /// </returns>
  136. public new SocketGroupUser GetUser(ulong id)
  137. {
  138. if (_users.TryGetValue(id, out SocketGroupUser user))
  139. return user;
  140. return null;
  141. }
  142. internal SocketGroupUser GetOrAddUser(UserModel model)
  143. {
  144. if (_users.TryGetValue(model.Id, out SocketGroupUser user))
  145. return user as SocketGroupUser;
  146. else
  147. {
  148. var privateUser = SocketGroupUser.Create(this, Discord.State, model);
  149. privateUser.GlobalUser.AddRef();
  150. _users[privateUser.Id] = privateUser;
  151. return privateUser;
  152. }
  153. }
  154. internal SocketGroupUser RemoveUser(ulong id)
  155. {
  156. if (_users.TryRemove(id, out SocketGroupUser user))
  157. {
  158. user.GlobalUser.RemoveRef(Discord);
  159. return user as SocketGroupUser;
  160. }
  161. return null;
  162. }
  163. //Voice States
  164. internal SocketVoiceState AddOrUpdateVoiceState(ClientState state, VoiceStateModel model)
  165. {
  166. var voiceChannel = state.GetChannel(model.ChannelId.Value) as SocketVoiceChannel;
  167. var voiceState = SocketVoiceState.Create(voiceChannel, model);
  168. _voiceStates[model.UserId] = voiceState;
  169. return voiceState;
  170. }
  171. internal SocketVoiceState? GetVoiceState(ulong id)
  172. {
  173. if (_voiceStates.TryGetValue(id, out SocketVoiceState voiceState))
  174. return voiceState;
  175. return null;
  176. }
  177. internal SocketVoiceState? RemoveVoiceState(ulong id)
  178. {
  179. if (_voiceStates.TryRemove(id, out SocketVoiceState voiceState))
  180. return voiceState;
  181. return null;
  182. }
  183. /// <summary>
  184. /// Returns the name of the group.
  185. /// </summary>
  186. public override string ToString() => Name;
  187. private string DebuggerDisplay => $"{Name} ({Id}, Group)";
  188. internal new SocketGroupChannel Clone() => MemberwiseClone() as SocketGroupChannel;
  189. //SocketChannel
  190. /// <inheritdoc />
  191. internal override IReadOnlyCollection<SocketUser> GetUsersInternal() => Users;
  192. /// <inheritdoc />
  193. internal override SocketUser GetUserInternal(ulong id) => GetUser(id);
  194. //ISocketPrivateChannel
  195. /// <inheritdoc />
  196. IReadOnlyCollection<SocketUser> ISocketPrivateChannel.Recipients => Recipients;
  197. //IPrivateChannel
  198. /// <inheritdoc />
  199. IReadOnlyCollection<IUser> IPrivateChannel.Recipients => Recipients;
  200. //IMessageChannel
  201. /// <inheritdoc />
  202. async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
  203. {
  204. if (mode == CacheMode.AllowDownload)
  205. return await GetMessageAsync(id, options).ConfigureAwait(false);
  206. else
  207. return GetCachedMessage(id);
  208. }
  209. /// <inheritdoc />
  210. IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)
  211. => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, mode, options);
  212. /// <inheritdoc />
  213. IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options)
  214. => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, mode, options);
  215. /// <inheritdoc />
  216. IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options)
  217. => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, mode, options);
  218. /// <inheritdoc />
  219. async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options)
  220. => await GetPinnedMessagesAsync(options).ConfigureAwait(false);
  221. /// <inheritdoc />
  222. async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options)
  223. => await SendFileAsync(filePath, text, isTTS, embed, options).ConfigureAwait(false);
  224. /// <inheritdoc />
  225. async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options)
  226. => await SendFileAsync(stream, filename, text, isTTS, embed, options).ConfigureAwait(false);
  227. /// <inheritdoc />
  228. async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options)
  229. => await SendMessageAsync(text, isTTS, embed, options).ConfigureAwait(false);
  230. /// <inheritdoc />
  231. IDisposable IMessageChannel.EnterTypingState(RequestOptions options)
  232. => EnterTypingState(options);
  233. //IAudioChannel
  234. /// <inheritdoc />
  235. /// <exception cref="NotSupportedException">Connecting to a group channel is not supported.</exception>
  236. Task<IAudioClient> IAudioChannel.ConnectAsync(Action<IAudioClient> configAction) =>
  237. throw new NotSupportedException();
  238. //IChannel
  239. /// <inheritdoc />
  240. Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
  241. => Task.FromResult<IUser>(GetUser(id));
  242. /// <inheritdoc />
  243. IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
  244. => ImmutableArray.Create<IReadOnlyCollection<IUser>>(Users).ToAsyncEnumerable();
  245. }
  246. }