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 31 kB

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