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.

SocketGuild.cs 32 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. #pragma warning disable CS0618
  2. using Discord.Audio;
  3. using Discord.Rest;
  4. using System;
  5. using System.Collections.Concurrent;
  6. using System.Collections.Generic;
  7. using System.Collections.Immutable;
  8. using System.Diagnostics;
  9. using System.Linq;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using ChannelModel = Discord.API.Channel;
  13. using EmojiUpdateModel = Discord.API.Gateway.GuildEmojiUpdateEvent;
  14. using ExtendedModel = Discord.API.Gateway.ExtendedGuild;
  15. using GuildSyncModel = Discord.API.Gateway.GuildSyncEvent;
  16. using MemberModel = Discord.API.GuildMember;
  17. using Model = Discord.API.Guild;
  18. using PresenceModel = Discord.API.Presence;
  19. using RoleModel = Discord.API.Role;
  20. using UserModel = Discord.API.User;
  21. using VoiceStateModel = Discord.API.VoiceState;
  22. namespace Discord.WebSocket
  23. {
  24. public class SocketGuild : SocketEntity<ulong>, IGuild
  25. {
  26. private readonly SemaphoreSlim _audioLock;
  27. private TaskCompletionSource<bool> _syncPromise, _downloaderPromise;
  28. private TaskCompletionSource<AudioClient> _audioConnectPromise;
  29. private ConcurrentHashSet<ulong> _channels;
  30. private ConcurrentDictionary<ulong, SocketGuildUser> _members;
  31. private ConcurrentDictionary<ulong, SocketRole> _roles;
  32. private ConcurrentDictionary<ulong, SocketVoiceState> _voiceStates;
  33. private ImmutableArray<GuildEmote> _emotes;
  34. private ImmutableArray<string> _features;
  35. private AudioClient _audioClient;
  36. public string Name { get; private set; }
  37. public int AFKTimeout { get; private set; }
  38. public bool IsEmbeddable { get; private set; }
  39. public VerificationLevel VerificationLevel { get; private set; }
  40. public MfaLevel MfaLevel { get; private set; }
  41. public DefaultMessageNotifications DefaultMessageNotifications { get; private set; }
  42. public int MemberCount { get; internal set; }
  43. public int DownloadedMemberCount { get; private set; }
  44. internal bool IsAvailable { get; private set; }
  45. public bool IsConnected { get; internal set; }
  46. internal ulong? AFKChannelId { get; private set; }
  47. internal ulong? EmbedChannelId { get; private set; }
  48. internal ulong? SystemChannelId { get; private set; }
  49. public ulong OwnerId { get; private set; }
  50. public SocketGuildUser Owner => GetUser(OwnerId);
  51. public string VoiceRegionId { get; private set; }
  52. public string IconId { get; private set; }
  53. public string SplashId { get; private set; }
  54. public DateTimeOffset CreatedAt => SnowflakeUtils.FromSnowflake(Id);
  55. public string IconUrl => CDN.GetGuildIconUrl(Id, IconId);
  56. public string SplashUrl => CDN.GetGuildSplashUrl(Id, SplashId);
  57. public bool HasAllMembers => MemberCount == DownloadedMemberCount;// _downloaderPromise.Task.IsCompleted;
  58. public bool IsSynced => _syncPromise.Task.IsCompleted;
  59. public Task SyncPromise => _syncPromise.Task;
  60. public Task DownloaderPromise => _downloaderPromise.Task;
  61. public IAudioClient AudioClient => _audioClient;
  62. public SocketTextChannel DefaultChannel => TextChannels
  63. .Where(c => CurrentUser.GetPermissions(c).ReadMessages)
  64. .OrderBy(c => c.Position)
  65. .FirstOrDefault();
  66. public SocketVoiceChannel AFKChannel
  67. {
  68. get
  69. {
  70. var id = AFKChannelId;
  71. return id.HasValue ? GetVoiceChannel(id.Value) : null;
  72. }
  73. }
  74. public SocketGuildChannel EmbedChannel
  75. {
  76. get
  77. {
  78. var id = EmbedChannelId;
  79. return id.HasValue ? GetChannel(id.Value) : null;
  80. }
  81. }
  82. public SocketTextChannel SystemChannel
  83. {
  84. get
  85. {
  86. var id = SystemChannelId;
  87. return id.HasValue ? GetTextChannel(id.Value) : null;
  88. }
  89. }
  90. public IReadOnlyCollection<SocketTextChannel> TextChannels
  91. => Channels.Select(x => x as SocketTextChannel).Where(x => x != null).ToImmutableArray();
  92. public IReadOnlyCollection<SocketVoiceChannel> VoiceChannels
  93. => Channels.Select(x => x as SocketVoiceChannel).Where(x => x != null).ToImmutableArray();
  94. public SocketGuildUser CurrentUser => _members.TryGetValue(Discord.CurrentUser.Id, out SocketGuildUser member) ? member : null;
  95. public SocketRole EveryoneRole => GetRole(Id);
  96. public IReadOnlyCollection<SocketGuildChannel> Channels
  97. {
  98. get
  99. {
  100. var channels = _channels;
  101. var state = Discord.State;
  102. return channels.Select(x => state.GetChannel(x) as SocketGuildChannel).Where(x => x != null).ToReadOnlyCollection(channels);
  103. }
  104. }
  105. public IReadOnlyCollection<GuildEmote> Emotes => _emotes;
  106. public IReadOnlyCollection<string> Features => _features;
  107. public IReadOnlyCollection<SocketGuildUser> Users => _members.ToReadOnlyCollection();
  108. public IReadOnlyCollection<SocketRole> Roles => _roles.ToReadOnlyCollection();
  109. internal SocketGuild(DiscordSocketClient client, ulong id)
  110. : base(client, id)
  111. {
  112. _audioLock = new SemaphoreSlim(1, 1);
  113. _emotes = ImmutableArray.Create<GuildEmote>();
  114. _features = ImmutableArray.Create<string>();
  115. }
  116. internal static SocketGuild Create(DiscordSocketClient discord, ClientState state, ExtendedModel model)
  117. {
  118. var entity = new SocketGuild(discord, model.Id);
  119. entity.Update(state, model);
  120. return entity;
  121. }
  122. internal void Update(ClientState state, ExtendedModel model)
  123. {
  124. IsAvailable = !(model.Unavailable ?? false);
  125. if (!IsAvailable)
  126. {
  127. if (_channels == null)
  128. _channels = new ConcurrentHashSet<ulong>();
  129. if (_members == null)
  130. _members = new ConcurrentDictionary<ulong, SocketGuildUser>();
  131. if (_roles == null)
  132. _roles = new ConcurrentDictionary<ulong, SocketRole>();
  133. /*if (Emojis == null)
  134. _emojis = ImmutableArray.Create<Emoji>();
  135. if (Features == null)
  136. _features = ImmutableArray.Create<string>();*/
  137. _syncPromise = new TaskCompletionSource<bool>();
  138. _downloaderPromise = new TaskCompletionSource<bool>();
  139. return;
  140. }
  141. Update(state, model as Model);
  142. var channels = new ConcurrentHashSet<ulong>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.Channels.Length * 1.05));
  143. {
  144. for (int i = 0; i < model.Channels.Length; i++)
  145. {
  146. var channel = SocketGuildChannel.Create(this, state, model.Channels[i]);
  147. state.AddChannel(channel);
  148. channels.TryAdd(channel.Id);
  149. }
  150. }
  151. _channels = channels;
  152. var members = new ConcurrentDictionary<ulong, SocketGuildUser>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.Members.Length * 1.05));
  153. {
  154. for (int i = 0; i < model.Members.Length; i++)
  155. {
  156. var member = SocketGuildUser.Create(this, state, model.Members[i]);
  157. members.TryAdd(member.Id, member);
  158. }
  159. DownloadedMemberCount = members.Count;
  160. for (int i = 0; i < model.Presences.Length; i++)
  161. {
  162. if (members.TryGetValue(model.Presences[i].User.Id, out SocketGuildUser member))
  163. member.Update(state, model.Presences[i], true);
  164. }
  165. }
  166. _members = members;
  167. MemberCount = model.MemberCount;
  168. var voiceStates = new ConcurrentDictionary<ulong, SocketVoiceState>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.VoiceStates.Length * 1.05));
  169. {
  170. for (int i = 0; i < model.VoiceStates.Length; i++)
  171. {
  172. SocketVoiceChannel channel = null;
  173. if (model.VoiceStates[i].ChannelId.HasValue)
  174. channel = state.GetChannel(model.VoiceStates[i].ChannelId.Value) as SocketVoiceChannel;
  175. var voiceState = SocketVoiceState.Create(channel, model.VoiceStates[i]);
  176. voiceStates.TryAdd(model.VoiceStates[i].UserId, voiceState);
  177. }
  178. }
  179. _voiceStates = voiceStates;
  180. _syncPromise = new TaskCompletionSource<bool>();
  181. _downloaderPromise = new TaskCompletionSource<bool>();
  182. if (Discord.ApiClient.AuthTokenType != TokenType.User)
  183. {
  184. var _ = _syncPromise.TrySetResultAsync(true);
  185. /*if (!model.Large)
  186. _ = _downloaderPromise.TrySetResultAsync(true);*/
  187. }
  188. }
  189. internal void Update(ClientState state, Model model)
  190. {
  191. AFKChannelId = model.AFKChannelId;
  192. EmbedChannelId = model.EmbedChannelId;
  193. SystemChannelId = model.SystemChannelId;
  194. AFKTimeout = model.AFKTimeout;
  195. IsEmbeddable = model.EmbedEnabled;
  196. IconId = model.Icon;
  197. Name = model.Name;
  198. OwnerId = model.OwnerId;
  199. VoiceRegionId = model.Region;
  200. SplashId = model.Splash;
  201. VerificationLevel = model.VerificationLevel;
  202. MfaLevel = model.MfaLevel;
  203. DefaultMessageNotifications = model.DefaultMessageNotifications;
  204. if (model.Emojis != null)
  205. {
  206. var emojis = ImmutableArray.CreateBuilder<GuildEmote>(model.Emojis.Length);
  207. for (int i = 0; i < model.Emojis.Length; i++)
  208. emojis.Add(model.Emojis[i].ToEntity());
  209. _emotes = emojis.ToImmutable();
  210. }
  211. else
  212. _emotes = ImmutableArray.Create<GuildEmote>();
  213. if (model.Features != null)
  214. _features = model.Features.ToImmutableArray();
  215. else
  216. _features = ImmutableArray.Create<string>();
  217. var roles = new ConcurrentDictionary<ulong, SocketRole>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.Roles.Length * 1.05));
  218. if (model.Roles != null)
  219. {
  220. for (int i = 0; i < model.Roles.Length; i++)
  221. {
  222. var role = SocketRole.Create(this, state, model.Roles[i]);
  223. roles.TryAdd(role.Id, role);
  224. }
  225. }
  226. _roles = roles;
  227. }
  228. internal void Update(ClientState state, GuildSyncModel model)
  229. {
  230. var members = new ConcurrentDictionary<ulong, SocketGuildUser>(ConcurrentHashSet.DefaultConcurrencyLevel, (int)(model.Members.Length * 1.05));
  231. {
  232. for (int i = 0; i < model.Members.Length; i++)
  233. {
  234. var member = SocketGuildUser.Create(this, state, model.Members[i]);
  235. members.TryAdd(member.Id, member);
  236. }
  237. DownloadedMemberCount = members.Count;
  238. for (int i = 0; i < model.Presences.Length; i++)
  239. {
  240. if (members.TryGetValue(model.Presences[i].User.Id, out SocketGuildUser member))
  241. member.Update(state, model.Presences[i], true);
  242. }
  243. }
  244. _members = members;
  245. var _ = _syncPromise.TrySetResultAsync(true);
  246. /*if (!model.Large)
  247. _ = _downloaderPromise.TrySetResultAsync(true);*/
  248. }
  249. internal void Update(ClientState state, EmojiUpdateModel model)
  250. {
  251. var emotes = ImmutableArray.CreateBuilder<GuildEmote>(model.Emojis.Length);
  252. for (int i = 0; i < model.Emojis.Length; i++)
  253. emotes.Add(model.Emojis[i].ToEntity());
  254. _emotes = emotes.ToImmutable();
  255. }
  256. //General
  257. public Task DeleteAsync(RequestOptions options = null)
  258. => GuildHelper.DeleteAsync(this, Discord, options);
  259. public Task ModifyAsync(Action<GuildProperties> func, RequestOptions options = null)
  260. => GuildHelper.ModifyAsync(this, Discord, func, options);
  261. public Task ModifyEmbedAsync(Action<GuildEmbedProperties> func, RequestOptions options = null)
  262. => GuildHelper.ModifyEmbedAsync(this, Discord, func, options);
  263. public Task ReorderChannelsAsync(IEnumerable<ReorderChannelProperties> args, RequestOptions options = null)
  264. => GuildHelper.ReorderChannelsAsync(this, Discord, args, options);
  265. public Task ReorderRolesAsync(IEnumerable<ReorderRoleProperties> args, RequestOptions options = null)
  266. => GuildHelper.ReorderRolesAsync(this, Discord, args, options);
  267. public Task LeaveAsync(RequestOptions options = null)
  268. => GuildHelper.LeaveAsync(this, Discord, options);
  269. //Bans
  270. public Task<IReadOnlyCollection<RestBan>> GetBansAsync(RequestOptions options = null)
  271. => GuildHelper.GetBansAsync(this, Discord, options);
  272. public Task AddBanAsync(IUser user, int pruneDays = 0, string reason = null, RequestOptions options = null)
  273. => GuildHelper.AddBanAsync(this, Discord, user.Id, pruneDays, reason, options);
  274. public Task AddBanAsync(ulong userId, int pruneDays = 0, string reason = null, RequestOptions options = null)
  275. => GuildHelper.AddBanAsync(this, Discord, userId, pruneDays, reason, options);
  276. public Task RemoveBanAsync(IUser user, RequestOptions options = null)
  277. => GuildHelper.RemoveBanAsync(this, Discord, user.Id, options);
  278. public Task RemoveBanAsync(ulong userId, RequestOptions options = null)
  279. => GuildHelper.RemoveBanAsync(this, Discord, userId, options);
  280. //Channels
  281. public SocketGuildChannel GetChannel(ulong id)
  282. {
  283. var channel = Discord.State.GetChannel(id) as SocketGuildChannel;
  284. if (channel?.Guild.Id == Id)
  285. return channel;
  286. return null;
  287. }
  288. public SocketTextChannel GetTextChannel(ulong id)
  289. => GetChannel(id) as SocketTextChannel;
  290. public SocketVoiceChannel GetVoiceChannel(ulong id)
  291. => GetChannel(id) as SocketVoiceChannel;
  292. public Task<RestTextChannel> CreateTextChannelAsync(string name, RequestOptions options = null)
  293. => GuildHelper.CreateTextChannelAsync(this, Discord, name, options);
  294. public Task<RestVoiceChannel> CreateVoiceChannelAsync(string name, RequestOptions options = null)
  295. => GuildHelper.CreateVoiceChannelAsync(this, Discord, name, options);
  296. internal SocketGuildChannel AddChannel(ClientState state, ChannelModel model)
  297. {
  298. var channel = SocketGuildChannel.Create(this, state, model);
  299. _channels.TryAdd(model.Id);
  300. state.AddChannel(channel);
  301. return channel;
  302. }
  303. internal SocketGuildChannel RemoveChannel(ClientState state, ulong id)
  304. {
  305. if (_channels.TryRemove(id))
  306. return state.RemoveChannel(id) as SocketGuildChannel;
  307. return null;
  308. }
  309. //Integrations
  310. public Task<IReadOnlyCollection<RestGuildIntegration>> GetIntegrationsAsync(RequestOptions options = null)
  311. => GuildHelper.GetIntegrationsAsync(this, Discord, options);
  312. public Task<RestGuildIntegration> CreateIntegrationAsync(ulong id, string type, RequestOptions options = null)
  313. => GuildHelper.CreateIntegrationAsync(this, Discord, id, type, options);
  314. //Invites
  315. public Task<IReadOnlyCollection<RestInviteMetadata>> GetInvitesAsync(RequestOptions options = null)
  316. => GuildHelper.GetInvitesAsync(this, Discord, options);
  317. //Roles
  318. public SocketRole GetRole(ulong id)
  319. {
  320. if (_roles.TryGetValue(id, out SocketRole value))
  321. return value;
  322. return null;
  323. }
  324. public Task<RestRole> CreateRoleAsync(string name, GuildPermissions? permissions = default(GuildPermissions?), Color? color = default(Color?),
  325. bool isHoisted = false, RequestOptions options = null)
  326. => GuildHelper.CreateRoleAsync(this, Discord, name, permissions, color, isHoisted, options);
  327. internal SocketRole AddRole(RoleModel model)
  328. {
  329. var role = SocketRole.Create(this, Discord.State, model);
  330. _roles[model.Id] = role;
  331. return role;
  332. }
  333. internal SocketRole RemoveRole(ulong id)
  334. {
  335. if (_roles.TryRemove(id, out SocketRole role))
  336. return role;
  337. return null;
  338. }
  339. //Users
  340. public SocketGuildUser GetUser(ulong id)
  341. {
  342. if (_members.TryGetValue(id, out SocketGuildUser member))
  343. return member;
  344. return null;
  345. }
  346. public Task<int> PruneUsersAsync(int days = 30, bool simulate = false, RequestOptions options = null)
  347. => GuildHelper.PruneUsersAsync(this, Discord, days, simulate, options);
  348. internal SocketGuildUser AddOrUpdateUser(UserModel model)
  349. {
  350. if (_members.TryGetValue(model.Id, out SocketGuildUser member))
  351. member.GlobalUser?.Update(Discord.State, model);
  352. else
  353. {
  354. member = SocketGuildUser.Create(this, Discord.State, model);
  355. member.GlobalUser.AddRef();
  356. _members[member.Id] = member;
  357. DownloadedMemberCount++;
  358. }
  359. return member;
  360. }
  361. internal SocketGuildUser AddOrUpdateUser(MemberModel model)
  362. {
  363. if (_members.TryGetValue(model.User.Id, out SocketGuildUser member))
  364. member.Update(Discord.State, model);
  365. else
  366. {
  367. member = SocketGuildUser.Create(this, Discord.State, model);
  368. member.GlobalUser.AddRef();
  369. _members[member.Id] = member;
  370. DownloadedMemberCount++;
  371. }
  372. return member;
  373. }
  374. internal SocketGuildUser AddOrUpdateUser(PresenceModel model)
  375. {
  376. if (_members.TryGetValue(model.User.Id, out SocketGuildUser member))
  377. member.Update(Discord.State, model, false);
  378. else
  379. {
  380. member = SocketGuildUser.Create(this, Discord.State, model);
  381. member.GlobalUser.AddRef();
  382. _members[member.Id] = member;
  383. DownloadedMemberCount++;
  384. }
  385. return member;
  386. }
  387. internal SocketGuildUser RemoveUser(ulong id)
  388. {
  389. if (_members.TryRemove(id, out SocketGuildUser member))
  390. {
  391. DownloadedMemberCount--;
  392. member.GlobalUser.RemoveRef(Discord);
  393. return member;
  394. }
  395. return null;
  396. }
  397. public async Task DownloadUsersAsync()
  398. {
  399. await Discord.DownloadUsersAsync(new[] { this }).ConfigureAwait(false);
  400. }
  401. internal void CompleteDownloadUsers()
  402. {
  403. _downloaderPromise.TrySetResultAsync(true);
  404. }
  405. //Emotes
  406. public Task<IReadOnlyCollection<GuildEmote>> ListEmotesAsync(RequestOptions options = null)
  407. => GuildHelper.ListEmotesAsync(this, Discord, options);
  408. public Task<GuildEmote> GetEmoteAsync(ulong id, RequestOptions options = null)
  409. => GuildHelper.GetEmoteAsync(this, Discord, id, options);
  410. public Task<GuildEmote> CreateEmoteAsync(string name, Image image, Optional<IEnumerable<IRole>> roles = default(Optional<IEnumerable<IRole>>), RequestOptions options = null)
  411. => GuildHelper.CreateEmoteAsync(this, Discord, name, image, roles, options);
  412. public Task<GuildEmote> ModifyEmoteAsync(GuildEmote emote, Action<EmoteProperties> func, RequestOptions options = null)
  413. => GuildHelper.ModifyEmoteAsync(this, Discord, emote.Id, func, options);
  414. public Task DeleteEmoteAsync(GuildEmote emote, RequestOptions options = null)
  415. => GuildHelper.DeleteEmoteAsync(this, Discord, emote.Id, options);
  416. //Voice States
  417. internal async Task<SocketVoiceState> AddOrUpdateVoiceStateAsync(ClientState state, VoiceStateModel model)
  418. {
  419. var voiceChannel = state.GetChannel(model.ChannelId.Value) as SocketVoiceChannel;
  420. var before = GetVoiceState(model.UserId) ?? SocketVoiceState.Default;
  421. var after = SocketVoiceState.Create(voiceChannel, model);
  422. _voiceStates[model.UserId] = after;
  423. if (_audioClient != null && before.VoiceChannel?.Id != after.VoiceChannel?.Id)
  424. {
  425. if (model.UserId == CurrentUser.Id)
  426. {
  427. if (after.VoiceChannel != null && _audioClient.ChannelId != after.VoiceChannel?.Id)
  428. {
  429. _audioClient.ChannelId = after.VoiceChannel.Id;
  430. await RepopulateAudioStreamsAsync().ConfigureAwait(false);
  431. }
  432. }
  433. else
  434. {
  435. await _audioClient.RemoveInputStreamAsync(model.UserId).ConfigureAwait(false); //User changed channels, end their stream
  436. if (CurrentUser.VoiceChannel != null && after.VoiceChannel?.Id == CurrentUser.VoiceChannel?.Id)
  437. await _audioClient.CreateInputStreamAsync(model.UserId).ConfigureAwait(false);
  438. }
  439. }
  440. return after;
  441. }
  442. internal SocketVoiceState? GetVoiceState(ulong id)
  443. {
  444. if (_voiceStates.TryGetValue(id, out SocketVoiceState voiceState))
  445. return voiceState;
  446. return null;
  447. }
  448. internal async Task<SocketVoiceState?> RemoveVoiceStateAsync(ulong id)
  449. {
  450. if (_voiceStates.TryRemove(id, out SocketVoiceState voiceState))
  451. {
  452. if (_audioClient != null)
  453. await _audioClient.RemoveInputStreamAsync(id).ConfigureAwait(false); //User changed channels, end their stream
  454. return voiceState;
  455. }
  456. return null;
  457. }
  458. //Audio
  459. internal AudioInStream GetAudioStream(ulong userId)
  460. {
  461. return _audioClient?.GetInputStream(userId);
  462. }
  463. internal async Task<IAudioClient> ConnectAudioAsync(ulong channelId, bool selfDeaf, bool selfMute, Action<IAudioClient> configAction)
  464. {
  465. selfDeaf = false;
  466. selfMute = false;
  467. TaskCompletionSource<AudioClient> promise;
  468. await _audioLock.WaitAsync().ConfigureAwait(false);
  469. try
  470. {
  471. await DisconnectAudioInternalAsync().ConfigureAwait(false);
  472. promise = new TaskCompletionSource<AudioClient>();
  473. _audioConnectPromise = promise;
  474. if (_audioClient == null)
  475. {
  476. var audioClient = new AudioClient(this, Discord.GetAudioId(), channelId);
  477. audioClient.Disconnected += async ex =>
  478. {
  479. if (!promise.Task.IsCompleted)
  480. {
  481. try { audioClient.Dispose(); } catch { }
  482. _audioClient = null;
  483. if (ex != null)
  484. await promise.TrySetExceptionAsync(ex);
  485. else
  486. await promise.TrySetCanceledAsync();
  487. return;
  488. }
  489. };
  490. audioClient.Connected += () =>
  491. {
  492. var _ = promise.TrySetResultAsync(_audioClient);
  493. return Task.Delay(0);
  494. };
  495. configAction?.Invoke(audioClient);
  496. _audioClient = audioClient;
  497. }
  498. await Discord.ApiClient.SendVoiceStateUpdateAsync(Id, channelId, selfDeaf, selfMute).ConfigureAwait(false);
  499. }
  500. catch (Exception)
  501. {
  502. await DisconnectAudioInternalAsync().ConfigureAwait(false);
  503. throw;
  504. }
  505. finally
  506. {
  507. _audioLock.Release();
  508. }
  509. try
  510. {
  511. var timeoutTask = Task.Delay(15000);
  512. if (await Task.WhenAny(promise.Task, timeoutTask) == timeoutTask)
  513. throw new TimeoutException();
  514. return await promise.Task.ConfigureAwait(false);
  515. }
  516. catch (Exception)
  517. {
  518. await DisconnectAudioAsync().ConfigureAwait(false);
  519. throw;
  520. }
  521. }
  522. internal async Task DisconnectAudioAsync()
  523. {
  524. await _audioLock.WaitAsync().ConfigureAwait(false);
  525. try
  526. {
  527. await DisconnectAudioInternalAsync().ConfigureAwait(false);
  528. }
  529. finally
  530. {
  531. _audioLock.Release();
  532. }
  533. }
  534. private async Task DisconnectAudioInternalAsync()
  535. {
  536. _audioConnectPromise?.TrySetCanceledAsync(); //Cancel any previous audio connection
  537. _audioConnectPromise = null;
  538. if (_audioClient != null)
  539. await _audioClient.StopAsync().ConfigureAwait(false);
  540. await Discord.ApiClient.SendVoiceStateUpdateAsync(Id, null, false, false).ConfigureAwait(false);
  541. _audioClient = null;
  542. }
  543. internal async Task FinishConnectAudio(string url, string token)
  544. {
  545. //TODO: Mem Leak: Disconnected/Connected handlers arent cleaned up
  546. var voiceState = GetVoiceState(Discord.CurrentUser.Id).Value;
  547. await _audioLock.WaitAsync().ConfigureAwait(false);
  548. try
  549. {
  550. await RepopulateAudioStreamsAsync().ConfigureAwait(false);
  551. await _audioClient.StartAsync(url, Discord.CurrentUser.Id, voiceState.VoiceSessionId, token).ConfigureAwait(false);
  552. }
  553. catch (OperationCanceledException)
  554. {
  555. await DisconnectAudioInternalAsync().ConfigureAwait(false);
  556. }
  557. catch (Exception e)
  558. {
  559. await _audioConnectPromise.SetExceptionAsync(e).ConfigureAwait(false);
  560. await DisconnectAudioInternalAsync().ConfigureAwait(false);
  561. }
  562. finally
  563. {
  564. _audioLock.Release();
  565. }
  566. }
  567. internal async Task RepopulateAudioStreamsAsync()
  568. {
  569. await _audioClient.ClearInputStreamsAsync().ConfigureAwait(false); //We changed channels, end all current streams
  570. if (CurrentUser.VoiceChannel != null)
  571. {
  572. foreach (var pair in _voiceStates)
  573. {
  574. if (pair.Value.VoiceChannel?.Id == CurrentUser.VoiceChannel?.Id && pair.Key != CurrentUser.Id)
  575. await _audioClient.CreateInputStreamAsync(pair.Key).ConfigureAwait(false);
  576. }
  577. }
  578. }
  579. public override string ToString() => Name;
  580. private string DebuggerDisplay => $"{Name} ({Id})";
  581. internal SocketGuild Clone() => MemberwiseClone() as SocketGuild;
  582. //IGuild
  583. ulong? IGuild.AFKChannelId => AFKChannelId;
  584. IAudioClient IGuild.AudioClient => null;
  585. bool IGuild.Available => true;
  586. ulong IGuild.DefaultChannelId => DefaultChannel?.Id ?? 0;
  587. ulong? IGuild.EmbedChannelId => EmbedChannelId;
  588. ulong? IGuild.SystemChannelId => SystemChannelId;
  589. IRole IGuild.EveryoneRole => EveryoneRole;
  590. IReadOnlyCollection<IRole> IGuild.Roles => Roles;
  591. async Task<IReadOnlyCollection<IBan>> IGuild.GetBansAsync(RequestOptions options)
  592. => await GetBansAsync(options).ConfigureAwait(false);
  593. Task<IReadOnlyCollection<IGuildChannel>> IGuild.GetChannelsAsync(CacheMode mode, RequestOptions options)
  594. => Task.FromResult<IReadOnlyCollection<IGuildChannel>>(Channels);
  595. Task<IGuildChannel> IGuild.GetChannelAsync(ulong id, CacheMode mode, RequestOptions options)
  596. => Task.FromResult<IGuildChannel>(GetChannel(id));
  597. Task<IReadOnlyCollection<ITextChannel>> IGuild.GetTextChannelsAsync(CacheMode mode, RequestOptions options)
  598. => Task.FromResult<IReadOnlyCollection<ITextChannel>>(TextChannels);
  599. Task<ITextChannel> IGuild.GetTextChannelAsync(ulong id, CacheMode mode, RequestOptions options)
  600. => Task.FromResult<ITextChannel>(GetTextChannel(id));
  601. Task<IReadOnlyCollection<IVoiceChannel>> IGuild.GetVoiceChannelsAsync(CacheMode mode, RequestOptions options)
  602. => Task.FromResult<IReadOnlyCollection<IVoiceChannel>>(VoiceChannels);
  603. Task<IVoiceChannel> IGuild.GetVoiceChannelAsync(ulong id, CacheMode mode, RequestOptions options)
  604. => Task.FromResult<IVoiceChannel>(GetVoiceChannel(id));
  605. Task<IVoiceChannel> IGuild.GetAFKChannelAsync(CacheMode mode, RequestOptions options)
  606. => Task.FromResult<IVoiceChannel>(AFKChannel);
  607. Task<ITextChannel> IGuild.GetDefaultChannelAsync(CacheMode mode, RequestOptions options)
  608. => Task.FromResult<ITextChannel>(DefaultChannel);
  609. Task<IGuildChannel> IGuild.GetEmbedChannelAsync(CacheMode mode, RequestOptions options)
  610. => Task.FromResult<IGuildChannel>(EmbedChannel);
  611. Task<ITextChannel> IGuild.GetSystemChannelAsync(CacheMode mode, RequestOptions options)
  612. => Task.FromResult<ITextChannel>(SystemChannel);
  613. async Task<ITextChannel> IGuild.CreateTextChannelAsync(string name, RequestOptions options)
  614. => await CreateTextChannelAsync(name, options).ConfigureAwait(false);
  615. async Task<IVoiceChannel> IGuild.CreateVoiceChannelAsync(string name, RequestOptions options)
  616. => await CreateVoiceChannelAsync(name, options).ConfigureAwait(false);
  617. async Task<IReadOnlyCollection<IGuildIntegration>> IGuild.GetIntegrationsAsync(RequestOptions options)
  618. => await GetIntegrationsAsync(options).ConfigureAwait(false);
  619. async Task<IGuildIntegration> IGuild.CreateIntegrationAsync(ulong id, string type, RequestOptions options)
  620. => await CreateIntegrationAsync(id, type, options).ConfigureAwait(false);
  621. async Task<IReadOnlyCollection<IInviteMetadata>> IGuild.GetInvitesAsync(RequestOptions options)
  622. => await GetInvitesAsync(options).ConfigureAwait(false);
  623. IRole IGuild.GetRole(ulong id)
  624. => GetRole(id);
  625. async Task<IRole> IGuild.CreateRoleAsync(string name, GuildPermissions? permissions, Color? color, bool isHoisted, RequestOptions options)
  626. => await CreateRoleAsync(name, permissions, color, isHoisted, options).ConfigureAwait(false);
  627. Task<IReadOnlyCollection<IGuildUser>> IGuild.GetUsersAsync(CacheMode mode, RequestOptions options)
  628. => Task.FromResult<IReadOnlyCollection<IGuildUser>>(Users);
  629. Task<IGuildUser> IGuild.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
  630. => Task.FromResult<IGuildUser>(GetUser(id));
  631. Task<IGuildUser> IGuild.GetCurrentUserAsync(CacheMode mode, RequestOptions options)
  632. => Task.FromResult<IGuildUser>(CurrentUser);
  633. Task<IGuildUser> IGuild.GetOwnerAsync(CacheMode mode, RequestOptions options)
  634. => Task.FromResult<IGuildUser>(Owner);
  635. Task IGuild.DownloadUsersAsync() { throw new NotSupportedException(); }
  636. }
  637. }