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.

DiscordSocketClient.cs 102 kB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826
  1. using Discord.API;
  2. using Discord.API.Gateway;
  3. using Discord.Logging;
  4. using Discord.Net.Converters;
  5. using Discord.Net.Udp;
  6. using Discord.Net.WebSockets;
  7. using Discord.Rest;
  8. using Newtonsoft.Json;
  9. using Newtonsoft.Json.Linq;
  10. using System;
  11. using System.Collections.Concurrent;
  12. using System.Collections.Generic;
  13. using System.Collections.Immutable;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using GameModel = Discord.API.Game;
  19. namespace Discord.WebSocket
  20. {
  21. public partial class DiscordSocketClient : BaseSocketClient, IDiscordClient
  22. {
  23. private readonly ConcurrentQueue<ulong> _largeGuilds;
  24. private readonly JsonSerializer _serializer;
  25. private readonly SemaphoreSlim _connectionGroupLock;
  26. private readonly DiscordSocketClient _parentClient;
  27. private readonly ConcurrentQueue<long> _heartbeatTimes;
  28. private readonly ConnectionManager _connection;
  29. private readonly Logger _gatewayLogger;
  30. private readonly SemaphoreSlim _stateLock;
  31. private string _sessionId;
  32. private int _lastSeq;
  33. private ImmutableDictionary<string, RestVoiceRegion> _voiceRegions;
  34. private Task _heartbeatTask, _guildDownloadTask;
  35. private int _unavailableGuildCount;
  36. private long _lastGuildAvailableTime, _lastMessageTime;
  37. private int _nextAudioId;
  38. private DateTimeOffset? _statusSince;
  39. private RestApplication _applicationInfo;
  40. /// <summary> Gets the shard of of this client. </summary>
  41. public int ShardId { get; }
  42. /// <summary> Gets the current connection state of this client. </summary>
  43. public ConnectionState ConnectionState => _connection.State;
  44. /// <inheritdoc />
  45. public override int Latency { get; protected set; }
  46. public override UserStatus Status { get; protected set; } = UserStatus.Online;
  47. public override IActivity Activity { get; protected set; }
  48. //From DiscordSocketConfig
  49. internal int TotalShards { get; private set; }
  50. internal int MessageCacheSize { get; private set; }
  51. internal int LargeThreshold { get; private set; }
  52. internal ClientState State { get; private set; }
  53. internal UdpSocketProvider UdpSocketProvider { get; private set; }
  54. internal WebSocketProvider WebSocketProvider { get; private set; }
  55. internal bool AlwaysDownloadUsers { get; private set; }
  56. internal int? HandlerTimeout { get; private set; }
  57. internal new DiscordSocketApiClient ApiClient => base.ApiClient as DiscordSocketApiClient;
  58. public override IReadOnlyCollection<SocketGuild> Guilds => State.Guilds;
  59. public override IReadOnlyCollection<ISocketPrivateChannel> PrivateChannels => State.PrivateChannels;
  60. public IReadOnlyCollection<SocketDMChannel> DMChannels
  61. => State.PrivateChannels.Select(x => x as SocketDMChannel).Where(x => x != null).ToImmutableArray();
  62. public IReadOnlyCollection<SocketGroupChannel> GroupChannels
  63. => State.PrivateChannels.Select(x => x as SocketGroupChannel).Where(x => x != null).ToImmutableArray();
  64. public override IReadOnlyCollection<RestVoiceRegion> VoiceRegions => _voiceRegions.ToReadOnlyCollection();
  65. /// <summary> Creates a new REST/WebSocket discord client. </summary>
  66. public DiscordSocketClient() : this(new DiscordSocketConfig()) { }
  67. /// <summary> Creates a new REST/WebSocket discord client. </summary>
  68. public DiscordSocketClient(DiscordSocketConfig config) : this(config, CreateApiClient(config), null, null) { }
  69. internal DiscordSocketClient(DiscordSocketConfig config, SemaphoreSlim groupLock, DiscordSocketClient parentClient) : this(config, CreateApiClient(config), groupLock, parentClient) { }
  70. private DiscordSocketClient(DiscordSocketConfig config, API.DiscordSocketApiClient client, SemaphoreSlim groupLock, DiscordSocketClient parentClient)
  71. : base(config, client)
  72. {
  73. ShardId = config.ShardId ?? 0;
  74. TotalShards = config.TotalShards ?? 1;
  75. MessageCacheSize = config.MessageCacheSize;
  76. LargeThreshold = config.LargeThreshold;
  77. UdpSocketProvider = config.UdpSocketProvider;
  78. WebSocketProvider = config.WebSocketProvider;
  79. AlwaysDownloadUsers = config.AlwaysDownloadUsers;
  80. HandlerTimeout = config.HandlerTimeout;
  81. State = new ClientState(0, 0);
  82. _heartbeatTimes = new ConcurrentQueue<long>();
  83. _stateLock = new SemaphoreSlim(1, 1);
  84. _gatewayLogger = LogManager.CreateLogger(ShardId == 0 && TotalShards == 1 ? "Gateway" : $"Shard #{ShardId}");
  85. _connection = new ConnectionManager(_stateLock, _gatewayLogger, config.ConnectionTimeout,
  86. OnConnectingAsync, OnDisconnectingAsync, x => ApiClient.Disconnected += x);
  87. _connection.Connected += () => TimedInvokeAsync(_connectedEvent, nameof(Connected));
  88. _connection.Disconnected += (ex, recon) => TimedInvokeAsync(_disconnectedEvent, nameof(Disconnected), ex);
  89. _nextAudioId = 1;
  90. _connectionGroupLock = groupLock;
  91. _parentClient = parentClient;
  92. _serializer = new JsonSerializer { ContractResolver = new DiscordContractResolver() };
  93. _serializer.Error += (s, e) =>
  94. {
  95. _gatewayLogger.WarningAsync("Serializer Error", e.ErrorContext.Error).GetAwaiter().GetResult();
  96. e.ErrorContext.Handled = true;
  97. };
  98. ApiClient.SentGatewayMessage += async opCode => await _gatewayLogger.DebugAsync($"Sent {opCode}").ConfigureAwait(false);
  99. ApiClient.ReceivedGatewayEvent += ProcessMessageAsync;
  100. LeftGuild += async g => await _gatewayLogger.InfoAsync($"Left {g.Name}").ConfigureAwait(false);
  101. JoinedGuild += async g => await _gatewayLogger.InfoAsync($"Joined {g.Name}").ConfigureAwait(false);
  102. GuildAvailable += async g => await _gatewayLogger.VerboseAsync($"Connected to {g.Name}").ConfigureAwait(false);
  103. GuildUnavailable += async g => await _gatewayLogger.VerboseAsync($"Disconnected from {g.Name}").ConfigureAwait(false);
  104. LatencyUpdated += async (old, val) => await _gatewayLogger.DebugAsync($"Latency = {val} ms").ConfigureAwait(false);
  105. GuildAvailable += g =>
  106. {
  107. if (ConnectionState == ConnectionState.Connected && AlwaysDownloadUsers && !g.HasAllMembers)
  108. {
  109. var _ = g.DownloadUsersAsync();
  110. }
  111. return Task.Delay(0);
  112. };
  113. _voiceRegions = ImmutableDictionary.Create<string, RestVoiceRegion>();
  114. _largeGuilds = new ConcurrentQueue<ulong>();
  115. }
  116. private static API.DiscordSocketApiClient CreateApiClient(DiscordSocketConfig config)
  117. => new API.DiscordSocketApiClient(config.RestClientProvider, config.WebSocketProvider, DiscordRestConfig.UserAgent, config.GatewayHost);
  118. internal override void Dispose(bool disposing)
  119. {
  120. if (disposing)
  121. {
  122. StopAsync().GetAwaiter().GetResult();
  123. ApiClient.Dispose();
  124. }
  125. }
  126. internal override async Task OnLoginAsync(TokenType tokenType, string token)
  127. {
  128. if (_parentClient == null)
  129. {
  130. var voiceRegions = await ApiClient.GetVoiceRegionsAsync(new RequestOptions { IgnoreState = true, RetryMode = RetryMode.AlwaysRetry }).ConfigureAwait(false);
  131. _voiceRegions = voiceRegions.Select(x => RestVoiceRegion.Create(this, x)).ToImmutableDictionary(x => x.Id);
  132. }
  133. else
  134. _voiceRegions = _parentClient._voiceRegions;
  135. }
  136. internal override async Task OnLogoutAsync()
  137. {
  138. await StopAsync().ConfigureAwait(false);
  139. _applicationInfo = null;
  140. _voiceRegions = ImmutableDictionary.Create<string, RestVoiceRegion>();
  141. }
  142. public override async Task StartAsync()
  143. => await _connection.StartAsync().ConfigureAwait(false);
  144. public override async Task StopAsync()
  145. => await _connection.StopAsync().ConfigureAwait(false);
  146. private async Task OnConnectingAsync()
  147. {
  148. if (_connectionGroupLock != null)
  149. await _connectionGroupLock.WaitAsync(_connection.CancelToken).ConfigureAwait(false);
  150. try
  151. {
  152. await _gatewayLogger.DebugAsync("Connecting ApiClient").ConfigureAwait(false);
  153. await ApiClient.ConnectAsync().ConfigureAwait(false);
  154. if (_sessionId != null)
  155. {
  156. await _gatewayLogger.DebugAsync("Resuming").ConfigureAwait(false);
  157. await ApiClient.SendResumeAsync(_sessionId, _lastSeq).ConfigureAwait(false);
  158. }
  159. else
  160. {
  161. await _gatewayLogger.DebugAsync("Identifying").ConfigureAwait(false);
  162. await ApiClient.SendIdentifyAsync(shardID: ShardId, totalShards: TotalShards).ConfigureAwait(false);
  163. }
  164. //Wait for READY
  165. await _connection.WaitAsync().ConfigureAwait(false);
  166. await _gatewayLogger.DebugAsync("Sending Status").ConfigureAwait(false);
  167. await SendStatusAsync().ConfigureAwait(false);
  168. }
  169. finally
  170. {
  171. if (_connectionGroupLock != null)
  172. {
  173. await Task.Delay(5000).ConfigureAwait(false);
  174. _connectionGroupLock.Release();
  175. }
  176. }
  177. }
  178. private async Task OnDisconnectingAsync(Exception ex)
  179. {
  180. await _gatewayLogger.DebugAsync("Disconnecting ApiClient").ConfigureAwait(false);
  181. await ApiClient.DisconnectAsync().ConfigureAwait(false);
  182. //Wait for tasks to complete
  183. await _gatewayLogger.DebugAsync("Waiting for heartbeater").ConfigureAwait(false);
  184. var heartbeatTask = _heartbeatTask;
  185. if (heartbeatTask != null)
  186. await heartbeatTask.ConfigureAwait(false);
  187. _heartbeatTask = null;
  188. while (_heartbeatTimes.TryDequeue(out long time)) { }
  189. _lastMessageTime = 0;
  190. await _gatewayLogger.DebugAsync("Waiting for guild downloader").ConfigureAwait(false);
  191. var guildDownloadTask = _guildDownloadTask;
  192. if (guildDownloadTask != null)
  193. await guildDownloadTask.ConfigureAwait(false);
  194. _guildDownloadTask = null;
  195. //Clear large guild queue
  196. await _gatewayLogger.DebugAsync("Clearing large guild queue").ConfigureAwait(false);
  197. while (_largeGuilds.TryDequeue(out ulong guildId)) { }
  198. //Raise virtual GUILD_UNAVAILABLEs
  199. await _gatewayLogger.DebugAsync("Raising virtual GuildUnavailables").ConfigureAwait(false);
  200. foreach (var guild in State.Guilds)
  201. {
  202. if (guild.IsAvailable)
  203. await GuildUnavailableAsync(guild).ConfigureAwait(false);
  204. }
  205. }
  206. /// <inheritdoc />
  207. public override async Task<RestApplication> GetApplicationInfoAsync(RequestOptions options = null)
  208. => _applicationInfo ?? (_applicationInfo = await ClientHelper.GetApplicationInfoAsync(this, options ?? RequestOptions.Default).ConfigureAwait(false));
  209. /// <inheritdoc />
  210. public override SocketGuild GetGuild(ulong id)
  211. => State.GetGuild(id);
  212. /// <inheritdoc />
  213. public override SocketChannel GetChannel(ulong id)
  214. => State.GetChannel(id);
  215. /// <inheritdoc />
  216. public override SocketUser GetUser(ulong id)
  217. => State.GetUser(id);
  218. /// <inheritdoc />
  219. public override SocketUser GetUser(string username, string discriminator)
  220. => State.Users.FirstOrDefault(x => x.Discriminator == discriminator && x.Username == username);
  221. internal SocketGlobalUser GetOrCreateUser(ClientState state, Discord.API.User model)
  222. {
  223. return state.GetOrAddUser(model.Id, x =>
  224. {
  225. var user = SocketGlobalUser.Create(this, state, model);
  226. user.GlobalUser.AddRef();
  227. return user;
  228. });
  229. }
  230. internal SocketGlobalUser GetOrCreateSelfUser(ClientState state, Discord.API.User model)
  231. {
  232. return state.GetOrAddUser(model.Id, x =>
  233. {
  234. var user = SocketGlobalUser.Create(this, state, model);
  235. user.GlobalUser.AddRef();
  236. user.Presence = new SocketPresence(UserStatus.Online, null);
  237. return user;
  238. });
  239. }
  240. internal void RemoveUser(ulong id)
  241. => State.RemoveUser(id);
  242. /// <inheritdoc />
  243. public override RestVoiceRegion GetVoiceRegion(string id)
  244. {
  245. if (_voiceRegions.TryGetValue(id, out RestVoiceRegion region))
  246. return region;
  247. return null;
  248. }
  249. /// <summary> Downloads the users list for the provided guilds, if they don't have a complete list. </summary>
  250. public override async Task DownloadUsersAsync(IEnumerable<IGuild> guilds)
  251. {
  252. if (ConnectionState == ConnectionState.Connected)
  253. {
  254. //Race condition leads to guilds being requested twice, probably okay
  255. await ProcessUserDownloadsAsync(guilds.Select(x => GetGuild(x.Id)).Where(x => x != null)).ConfigureAwait(false);
  256. }
  257. }
  258. private async Task ProcessUserDownloadsAsync(IEnumerable<SocketGuild> guilds)
  259. {
  260. var cachedGuilds = guilds.ToImmutableArray();
  261. const short batchSize = 50;
  262. ulong[] batchIds = new ulong[Math.Min(batchSize, cachedGuilds.Length)];
  263. Task[] batchTasks = new Task[batchIds.Length];
  264. int batchCount = (cachedGuilds.Length + (batchSize - 1)) / batchSize;
  265. for (int i = 0, k = 0; i < batchCount; i++)
  266. {
  267. bool isLast = i == batchCount - 1;
  268. int count = isLast ? (batchIds.Length - (batchCount - 1) * batchSize) : batchSize;
  269. for (int j = 0; j < count; j++, k++)
  270. {
  271. var guild = cachedGuilds[k];
  272. batchIds[j] = guild.Id;
  273. batchTasks[j] = guild.DownloaderPromise;
  274. }
  275. await ApiClient.SendRequestMembersAsync(batchIds).ConfigureAwait(false);
  276. if (isLast && batchCount > 1)
  277. await Task.WhenAll(batchTasks.Take(count)).ConfigureAwait(false);
  278. else
  279. await Task.WhenAll(batchTasks).ConfigureAwait(false);
  280. }
  281. }
  282. public override async Task SetStatusAsync(UserStatus status)
  283. {
  284. Status = status;
  285. if (status == UserStatus.AFK)
  286. _statusSince = DateTimeOffset.UtcNow;
  287. else
  288. _statusSince = null;
  289. await SendStatusAsync().ConfigureAwait(false);
  290. }
  291. public override async Task SetGameAsync(string name, string streamUrl = null, ActivityType type = ActivityType.Playing)
  292. {
  293. if (!string.IsNullOrEmpty(streamUrl))
  294. Activity = new StreamingGame(name, streamUrl);
  295. else if (!string.IsNullOrEmpty(name))
  296. Activity = new Game(name, type);
  297. else
  298. Activity = null;
  299. await SendStatusAsync().ConfigureAwait(false);
  300. }
  301. public override async Task SetActivityAsync(IActivity activity)
  302. {
  303. Activity = activity;
  304. await SendStatusAsync().ConfigureAwait(false);
  305. }
  306. private async Task SendStatusAsync()
  307. {
  308. if (CurrentUser == null)
  309. return;
  310. var status = Status;
  311. var statusSince = _statusSince;
  312. CurrentUser.Presence = new SocketPresence(status, Activity);
  313. var gameModel = new GameModel();
  314. // Discord only accepts rich presence over RPC, don't even bother building a payload
  315. if (Activity is RichGame game)
  316. throw new NotSupportedException("Outgoing Rich Presences are not supported");
  317. if (Activity != null)
  318. {
  319. gameModel.Name = Activity.Name;
  320. gameModel.Type = Activity.Type;
  321. if (Activity is StreamingGame streamGame)
  322. gameModel.StreamUrl = streamGame.Url;
  323. }
  324. await ApiClient.SendStatusUpdateAsync(
  325. status,
  326. status == UserStatus.AFK,
  327. statusSince != null ? DateTimeUtils.ToUnixMilliseconds(_statusSince.Value) : (long?)null,
  328. gameModel).ConfigureAwait(false);
  329. }
  330. private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string type, object payload)
  331. {
  332. if (seq != null)
  333. _lastSeq = seq.Value;
  334. _lastMessageTime = Environment.TickCount;
  335. try
  336. {
  337. switch (opCode)
  338. {
  339. case GatewayOpCode.Hello:
  340. {
  341. await _gatewayLogger.DebugAsync("Received Hello").ConfigureAwait(false);
  342. var data = (payload as JToken).ToObject<HelloEvent>(_serializer);
  343. _heartbeatTask = RunHeartbeatAsync(data.HeartbeatInterval, _connection.CancelToken);
  344. }
  345. break;
  346. case GatewayOpCode.Heartbeat:
  347. {
  348. await _gatewayLogger.DebugAsync("Received Heartbeat").ConfigureAwait(false);
  349. await ApiClient.SendHeartbeatAsync(_lastSeq).ConfigureAwait(false);
  350. }
  351. break;
  352. case GatewayOpCode.HeartbeatAck:
  353. {
  354. await _gatewayLogger.DebugAsync("Received HeartbeatAck").ConfigureAwait(false);
  355. if (_heartbeatTimes.TryDequeue(out long time))
  356. {
  357. int latency = (int)(Environment.TickCount - time);
  358. int before = Latency;
  359. Latency = latency;
  360. await TimedInvokeAsync(_latencyUpdatedEvent, nameof(LatencyUpdated), before, latency).ConfigureAwait(false);
  361. }
  362. }
  363. break;
  364. case GatewayOpCode.InvalidSession:
  365. {
  366. await _gatewayLogger.DebugAsync("Received InvalidSession").ConfigureAwait(false);
  367. await _gatewayLogger.WarningAsync("Failed to resume previous session").ConfigureAwait(false);
  368. _sessionId = null;
  369. _lastSeq = 0;
  370. await ApiClient.SendIdentifyAsync(shardID: ShardId, totalShards: TotalShards).ConfigureAwait(false);
  371. }
  372. break;
  373. case GatewayOpCode.Reconnect:
  374. {
  375. await _gatewayLogger.DebugAsync("Received Reconnect").ConfigureAwait(false);
  376. _connection.Error(new Exception("Server requested a reconnect"));
  377. }
  378. break;
  379. case GatewayOpCode.Dispatch:
  380. switch (type)
  381. {
  382. //Connection
  383. case "READY":
  384. {
  385. try
  386. {
  387. await _gatewayLogger.DebugAsync("Received Dispatch (READY)").ConfigureAwait(false);
  388. var data = (payload as JToken).ToObject<ReadyEvent>(_serializer);
  389. var state = new ClientState(data.Guilds.Length, data.PrivateChannels.Length);
  390. var currentUser = SocketSelfUser.Create(this, state, data.User);
  391. ApiClient.CurrentUserId = currentUser.Id;
  392. int unavailableGuilds = 0;
  393. for (int i = 0; i < data.Guilds.Length; i++)
  394. {
  395. var model = data.Guilds[i];
  396. var guild = AddGuild(model, state);
  397. if (!guild.IsAvailable)
  398. unavailableGuilds++;
  399. else
  400. await GuildAvailableAsync(guild).ConfigureAwait(false);
  401. }
  402. for (int i = 0; i < data.PrivateChannels.Length; i++)
  403. AddPrivateChannel(data.PrivateChannels[i], state);
  404. _sessionId = data.SessionId;
  405. _unavailableGuildCount = unavailableGuilds;
  406. CurrentUser = currentUser;
  407. State = state;
  408. }
  409. catch (Exception ex)
  410. {
  411. _connection.CriticalError(new Exception("Processing READY failed", ex));
  412. return;
  413. }
  414. _lastGuildAvailableTime = Environment.TickCount;
  415. _guildDownloadTask = WaitForGuildsAsync(_connection.CancelToken, _gatewayLogger)
  416. .ContinueWith(async x =>
  417. {
  418. if (x.IsFaulted)
  419. {
  420. _connection.Error(x.Exception);
  421. return;
  422. }
  423. else if (_connection.CancelToken.IsCancellationRequested)
  424. return;
  425. await TimedInvokeAsync(_readyEvent, nameof(Ready)).ConfigureAwait(false);
  426. await _gatewayLogger.InfoAsync("Ready").ConfigureAwait(false);
  427. });
  428. _ = _connection.CompleteAsync();
  429. }
  430. break;
  431. case "RESUMED":
  432. {
  433. await _gatewayLogger.DebugAsync("Received Dispatch (RESUMED)").ConfigureAwait(false);
  434. _ = _connection.CompleteAsync();
  435. //Notify the client that these guilds are available again
  436. foreach (var guild in State.Guilds)
  437. {
  438. if (guild.IsAvailable)
  439. await GuildAvailableAsync(guild).ConfigureAwait(false);
  440. }
  441. await _gatewayLogger.InfoAsync("Resumed previous session").ConfigureAwait(false);
  442. }
  443. break;
  444. //Guilds
  445. case "GUILD_CREATE":
  446. {
  447. var data = (payload as JToken).ToObject<ExtendedGuild>(_serializer);
  448. if (data.Unavailable == false)
  449. {
  450. type = "GUILD_AVAILABLE";
  451. _lastGuildAvailableTime = Environment.TickCount;
  452. await _gatewayLogger.DebugAsync($"Received Dispatch (GUILD_AVAILABLE)").ConfigureAwait(false);
  453. var guild = State.GetGuild(data.Id);
  454. if (guild != null)
  455. {
  456. guild.Update(State, data);
  457. if (_unavailableGuildCount != 0)
  458. _unavailableGuildCount--;
  459. await GuildAvailableAsync(guild).ConfigureAwait(false);
  460. if (guild.DownloadedMemberCount >= guild.MemberCount && !guild.DownloaderPromise.IsCompleted)
  461. {
  462. guild.CompleteDownloadUsers();
  463. await TimedInvokeAsync(_guildMembersDownloadedEvent, nameof(GuildMembersDownloaded), guild).ConfigureAwait(false);
  464. }
  465. }
  466. else
  467. {
  468. await UnknownGuildAsync(type, data.Id).ConfigureAwait(false);
  469. return;
  470. }
  471. }
  472. else
  473. {
  474. await _gatewayLogger.DebugAsync($"Received Dispatch (GUILD_CREATE)").ConfigureAwait(false);
  475. var guild = AddGuild(data, State);
  476. if (guild != null)
  477. {
  478. await TimedInvokeAsync(_joinedGuildEvent, nameof(JoinedGuild), guild).ConfigureAwait(false);
  479. }
  480. else
  481. {
  482. await UnknownGuildAsync(type, data.Id).ConfigureAwait(false);
  483. return;
  484. }
  485. }
  486. }
  487. break;
  488. case "GUILD_UPDATE":
  489. {
  490. await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_UPDATE)").ConfigureAwait(false);
  491. var data = (payload as JToken).ToObject<API.Guild>(_serializer);
  492. var guild = State.GetGuild(data.Id);
  493. if (guild != null)
  494. {
  495. var before = guild.Clone();
  496. guild.Update(State, data);
  497. await TimedInvokeAsync(_guildUpdatedEvent, nameof(GuildUpdated), before, guild).ConfigureAwait(false);
  498. }
  499. else
  500. {
  501. await UnknownGuildAsync(type, data.Id).ConfigureAwait(false);
  502. return;
  503. }
  504. }
  505. break;
  506. case "GUILD_EMOJIS_UPDATE":
  507. {
  508. await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_EMOJIS_UPDATE)").ConfigureAwait(false);
  509. var data = (payload as JToken).ToObject<API.Gateway.GuildEmojiUpdateEvent>(_serializer);
  510. var guild = State.GetGuild(data.GuildId);
  511. if (guild != null)
  512. {
  513. var before = guild.Clone();
  514. guild.Update(State, data);
  515. await TimedInvokeAsync(_guildUpdatedEvent, nameof(GuildUpdated), before, guild).ConfigureAwait(false);
  516. }
  517. else
  518. {
  519. await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false);
  520. return;
  521. }
  522. }
  523. break;
  524. case "GUILD_SYNC":
  525. {
  526. await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_SYNC)").ConfigureAwait(false);
  527. var data = (payload as JToken).ToObject<GuildSyncEvent>(_serializer);
  528. var guild = State.GetGuild(data.Id);
  529. if (guild != null)
  530. {
  531. var before = guild.Clone();
  532. guild.Update(State, data);
  533. //This is treated as an extension of GUILD_AVAILABLE
  534. _unavailableGuildCount--;
  535. _lastGuildAvailableTime = Environment.TickCount;
  536. await GuildAvailableAsync(guild).ConfigureAwait(false);
  537. await TimedInvokeAsync(_guildUpdatedEvent, nameof(GuildUpdated), before, guild).ConfigureAwait(false);
  538. }
  539. else
  540. {
  541. await UnknownGuildAsync(type, data.Id).ConfigureAwait(false);
  542. return;
  543. }
  544. }
  545. break;
  546. case "GUILD_DELETE":
  547. {
  548. var data = (payload as JToken).ToObject<ExtendedGuild>(_serializer);
  549. if (data.Unavailable == true)
  550. {
  551. type = "GUILD_UNAVAILABLE";
  552. await _gatewayLogger.DebugAsync($"Received Dispatch (GUILD_UNAVAILABLE)").ConfigureAwait(false);
  553. var guild = State.GetGuild(data.Id);
  554. if (guild != null)
  555. {
  556. await GuildUnavailableAsync(guild).ConfigureAwait(false);
  557. _unavailableGuildCount++;
  558. }
  559. else
  560. {
  561. await UnknownGuildAsync(type, data.Id).ConfigureAwait(false);
  562. return;
  563. }
  564. }
  565. else
  566. {
  567. await _gatewayLogger.DebugAsync($"Received Dispatch (GUILD_DELETE)").ConfigureAwait(false);
  568. var guild = RemoveGuild(data.Id);
  569. if (guild != null)
  570. {
  571. await GuildUnavailableAsync(guild).ConfigureAwait(false);
  572. await TimedInvokeAsync(_leftGuildEvent, nameof(LeftGuild), guild).ConfigureAwait(false);
  573. }
  574. else
  575. {
  576. await UnknownGuildAsync(type, data.Id).ConfigureAwait(false);
  577. return;
  578. }
  579. }
  580. }
  581. break;
  582. //Channels
  583. case "CHANNEL_CREATE":
  584. {
  585. await _gatewayLogger.DebugAsync("Received Dispatch (CHANNEL_CREATE)").ConfigureAwait(false);
  586. var data = (payload as JToken).ToObject<API.Channel>(_serializer);
  587. SocketChannel channel = null;
  588. if (data.GuildId.IsSpecified)
  589. {
  590. var guild = State.GetGuild(data.GuildId.Value);
  591. if (guild != null)
  592. {
  593. channel = guild.AddChannel(State, data);
  594. if (!guild.IsSynced)
  595. {
  596. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  597. return;
  598. }
  599. }
  600. else
  601. {
  602. await UnknownGuildAsync(type, data.GuildId.Value).ConfigureAwait(false);
  603. return;
  604. }
  605. }
  606. else
  607. {
  608. channel = State.GetChannel(data.Id);
  609. if (channel != null)
  610. return; //Discord may send duplicate CHANNEL_CREATEs for DMs
  611. channel = AddPrivateChannel(data, State) as SocketChannel;
  612. }
  613. if (channel != null)
  614. await TimedInvokeAsync(_channelCreatedEvent, nameof(ChannelCreated), channel).ConfigureAwait(false);
  615. }
  616. break;
  617. case "CHANNEL_UPDATE":
  618. {
  619. await _gatewayLogger.DebugAsync("Received Dispatch (CHANNEL_UPDATE)").ConfigureAwait(false);
  620. var data = (payload as JToken).ToObject<API.Channel>(_serializer);
  621. var channel = State.GetChannel(data.Id);
  622. if (channel != null)
  623. {
  624. var before = channel.Clone();
  625. channel.Update(State, data);
  626. var guild = (channel as SocketGuildChannel)?.Guild;
  627. if (!(guild?.IsSynced ?? true))
  628. {
  629. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  630. return;
  631. }
  632. await TimedInvokeAsync(_channelUpdatedEvent, nameof(ChannelUpdated), before, channel).ConfigureAwait(false);
  633. }
  634. else
  635. {
  636. await UnknownChannelAsync(type, data.Id).ConfigureAwait(false);
  637. return;
  638. }
  639. }
  640. break;
  641. case "CHANNEL_DELETE":
  642. {
  643. await _gatewayLogger.DebugAsync("Received Dispatch (CHANNEL_DELETE)").ConfigureAwait(false);
  644. SocketChannel channel = null;
  645. var data = (payload as JToken).ToObject<API.Channel>(_serializer);
  646. if (data.GuildId.IsSpecified)
  647. {
  648. var guild = State.GetGuild(data.GuildId.Value);
  649. if (guild != null)
  650. {
  651. channel = guild.RemoveChannel(State, data.Id);
  652. if (!guild.IsSynced)
  653. {
  654. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  655. return;
  656. }
  657. }
  658. else
  659. {
  660. await UnknownGuildAsync(type, data.GuildId.Value).ConfigureAwait(false);
  661. return;
  662. }
  663. }
  664. else
  665. channel = RemovePrivateChannel(data.Id) as SocketChannel;
  666. if (channel != null)
  667. await TimedInvokeAsync(_channelDestroyedEvent, nameof(ChannelDestroyed), channel).ConfigureAwait(false);
  668. else
  669. {
  670. await UnknownChannelAsync(type, data.Id, data.GuildId.GetValueOrDefault(0)).ConfigureAwait(false);
  671. return;
  672. }
  673. }
  674. break;
  675. //Members
  676. case "GUILD_MEMBER_ADD":
  677. {
  678. await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_MEMBER_ADD)").ConfigureAwait(false);
  679. var data = (payload as JToken).ToObject<GuildMemberAddEvent>(_serializer);
  680. var guild = State.GetGuild(data.GuildId);
  681. if (guild != null)
  682. {
  683. var user = guild.AddOrUpdateUser(data);
  684. guild.MemberCount++;
  685. if (!guild.IsSynced)
  686. {
  687. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  688. return;
  689. }
  690. await TimedInvokeAsync(_userJoinedEvent, nameof(UserJoined), user).ConfigureAwait(false);
  691. }
  692. else
  693. {
  694. await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false);
  695. return;
  696. }
  697. }
  698. break;
  699. case "GUILD_MEMBER_UPDATE":
  700. {
  701. await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_MEMBER_UPDATE)").ConfigureAwait(false);
  702. var data = (payload as JToken).ToObject<GuildMemberUpdateEvent>(_serializer);
  703. var guild = State.GetGuild(data.GuildId);
  704. if (guild != null)
  705. {
  706. var user = guild.GetUser(data.User.Id);
  707. if (!guild.IsSynced)
  708. {
  709. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  710. return;
  711. }
  712. if (user != null)
  713. {
  714. var before = user.Clone();
  715. user.Update(State, data);
  716. await TimedInvokeAsync(_guildMemberUpdatedEvent, nameof(GuildMemberUpdated), before, user).ConfigureAwait(false);
  717. }
  718. else
  719. {
  720. if (!guild.HasAllMembers)
  721. await IncompleteGuildUserAsync(type, data.User.Id, data.GuildId).ConfigureAwait(false);
  722. else
  723. await UnknownGuildUserAsync(type, data.User.Id, data.GuildId).ConfigureAwait(false);
  724. return;
  725. }
  726. }
  727. else
  728. {
  729. await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false);
  730. return;
  731. }
  732. }
  733. break;
  734. case "GUILD_MEMBER_REMOVE":
  735. {
  736. await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_MEMBER_REMOVE)").ConfigureAwait(false);
  737. var data = (payload as JToken).ToObject<GuildMemberRemoveEvent>(_serializer);
  738. var guild = State.GetGuild(data.GuildId);
  739. if (guild != null)
  740. {
  741. var user = guild.RemoveUser(data.User.Id);
  742. guild.MemberCount--;
  743. if (!guild.IsSynced)
  744. {
  745. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  746. return;
  747. }
  748. if (user != null)
  749. await TimedInvokeAsync(_userLeftEvent, nameof(UserLeft), user).ConfigureAwait(false);
  750. else
  751. {
  752. if (!guild.HasAllMembers)
  753. await IncompleteGuildUserAsync(type, data.User.Id, data.GuildId).ConfigureAwait(false);
  754. else
  755. await UnknownGuildUserAsync(type, data.User.Id, data.GuildId).ConfigureAwait(false);
  756. return;
  757. }
  758. }
  759. else
  760. {
  761. await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false);
  762. return;
  763. }
  764. }
  765. break;
  766. case "GUILD_MEMBERS_CHUNK":
  767. {
  768. await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_MEMBERS_CHUNK)").ConfigureAwait(false);
  769. var data = (payload as JToken).ToObject<GuildMembersChunkEvent>(_serializer);
  770. var guild = State.GetGuild(data.GuildId);
  771. if (guild != null)
  772. {
  773. foreach (var memberModel in data.Members)
  774. guild.AddOrUpdateUser(memberModel);
  775. if (guild.DownloadedMemberCount >= guild.MemberCount && !guild.DownloaderPromise.IsCompleted)
  776. {
  777. guild.CompleteDownloadUsers();
  778. await TimedInvokeAsync(_guildMembersDownloadedEvent, nameof(GuildMembersDownloaded), guild).ConfigureAwait(false);
  779. }
  780. }
  781. else
  782. {
  783. await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false);
  784. return;
  785. }
  786. }
  787. break;
  788. case "CHANNEL_RECIPIENT_ADD":
  789. {
  790. await _gatewayLogger.DebugAsync("Received Dispatch (CHANNEL_RECIPIENT_ADD)").ConfigureAwait(false);
  791. var data = (payload as JToken).ToObject<RecipientEvent>(_serializer);
  792. if (State.GetChannel(data.ChannelId) is SocketGroupChannel channel)
  793. {
  794. var user = channel.GetOrAddUser(data.User);
  795. await TimedInvokeAsync(_recipientAddedEvent, nameof(RecipientAdded), user).ConfigureAwait(false);
  796. }
  797. else
  798. {
  799. await UnknownChannelAsync(type, data.ChannelId).ConfigureAwait(false);
  800. return;
  801. }
  802. }
  803. break;
  804. case "CHANNEL_RECIPIENT_REMOVE":
  805. {
  806. await _gatewayLogger.DebugAsync("Received Dispatch (CHANNEL_RECIPIENT_REMOVE)").ConfigureAwait(false);
  807. var data = (payload as JToken).ToObject<RecipientEvent>(_serializer);
  808. if (State.GetChannel(data.ChannelId) is SocketGroupChannel channel)
  809. {
  810. var user = channel.RemoveUser(data.User.Id);
  811. if (user != null)
  812. await TimedInvokeAsync(_recipientRemovedEvent, nameof(RecipientRemoved), user).ConfigureAwait(false);
  813. else
  814. {
  815. await UnknownChannelUserAsync(type, data.User.Id, data.ChannelId).ConfigureAwait(false);
  816. return;
  817. }
  818. }
  819. else
  820. {
  821. await UnknownChannelAsync(type, data.ChannelId).ConfigureAwait(false);
  822. return;
  823. }
  824. }
  825. break;
  826. //Roles
  827. case "GUILD_ROLE_CREATE":
  828. {
  829. await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_ROLE_CREATE)").ConfigureAwait(false);
  830. var data = (payload as JToken).ToObject<GuildRoleCreateEvent>(_serializer);
  831. var guild = State.GetGuild(data.GuildId);
  832. if (guild != null)
  833. {
  834. var role = guild.AddRole(data.Role);
  835. if (!guild.IsSynced)
  836. {
  837. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  838. return;
  839. }
  840. await TimedInvokeAsync(_roleCreatedEvent, nameof(RoleCreated), role).ConfigureAwait(false);
  841. }
  842. else
  843. {
  844. await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false);
  845. return;
  846. }
  847. }
  848. break;
  849. case "GUILD_ROLE_UPDATE":
  850. {
  851. await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_ROLE_UPDATE)").ConfigureAwait(false);
  852. var data = (payload as JToken).ToObject<GuildRoleUpdateEvent>(_serializer);
  853. var guild = State.GetGuild(data.GuildId);
  854. if (guild != null)
  855. {
  856. var role = guild.GetRole(data.Role.Id);
  857. if (role != null)
  858. {
  859. var before = role.Clone();
  860. role.Update(State, data.Role);
  861. if (!guild.IsSynced)
  862. {
  863. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  864. return;
  865. }
  866. await TimedInvokeAsync(_roleUpdatedEvent, nameof(RoleUpdated), before, role).ConfigureAwait(false);
  867. }
  868. else
  869. {
  870. await UnknownRoleAsync(type, data.Role.Id, guild.Id).ConfigureAwait(false);
  871. return;
  872. }
  873. }
  874. else
  875. {
  876. await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false);
  877. return;
  878. }
  879. }
  880. break;
  881. case "GUILD_ROLE_DELETE":
  882. {
  883. await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_ROLE_DELETE)").ConfigureAwait(false);
  884. var data = (payload as JToken).ToObject<GuildRoleDeleteEvent>(_serializer);
  885. var guild = State.GetGuild(data.GuildId);
  886. if (guild != null)
  887. {
  888. var role = guild.RemoveRole(data.RoleId);
  889. if (role != null)
  890. {
  891. if (!guild.IsSynced)
  892. {
  893. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  894. return;
  895. }
  896. await TimedInvokeAsync(_roleDeletedEvent, nameof(RoleDeleted), role).ConfigureAwait(false);
  897. }
  898. else
  899. {
  900. await UnknownRoleAsync(type, data.RoleId, guild.Id).ConfigureAwait(false);
  901. return;
  902. }
  903. }
  904. else
  905. {
  906. await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false);
  907. return;
  908. }
  909. }
  910. break;
  911. //Bans
  912. case "GUILD_BAN_ADD":
  913. {
  914. await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_BAN_ADD)").ConfigureAwait(false);
  915. var data = (payload as JToken).ToObject<GuildBanEvent>(_serializer);
  916. var guild = State.GetGuild(data.GuildId);
  917. if (guild != null)
  918. {
  919. if (!guild.IsSynced)
  920. {
  921. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  922. return;
  923. }
  924. SocketUser user = guild.GetUser(data.User.Id);
  925. if (user == null)
  926. user = SocketUnknownUser.Create(this, State, data.User);
  927. await TimedInvokeAsync(_userBannedEvent, nameof(UserBanned), user, guild).ConfigureAwait(false);
  928. }
  929. else
  930. {
  931. await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false);
  932. return;
  933. }
  934. }
  935. break;
  936. case "GUILD_BAN_REMOVE":
  937. {
  938. await _gatewayLogger.DebugAsync("Received Dispatch (GUILD_BAN_REMOVE)").ConfigureAwait(false);
  939. var data = (payload as JToken).ToObject<GuildBanEvent>(_serializer);
  940. var guild = State.GetGuild(data.GuildId);
  941. if (guild != null)
  942. {
  943. if (!guild.IsSynced)
  944. {
  945. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  946. return;
  947. }
  948. SocketUser user = State.GetUser(data.User.Id);
  949. if (user == null)
  950. user = SocketUnknownUser.Create(this, State, data.User);
  951. await TimedInvokeAsync(_userUnbannedEvent, nameof(UserUnbanned), user, guild).ConfigureAwait(false);
  952. }
  953. else
  954. {
  955. await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false);
  956. return;
  957. }
  958. }
  959. break;
  960. //Messages
  961. case "MESSAGE_CREATE":
  962. {
  963. await _gatewayLogger.DebugAsync("Received Dispatch (MESSAGE_CREATE)").ConfigureAwait(false);
  964. var data = (payload as JToken).ToObject<API.Message>(_serializer);
  965. if (State.GetChannel(data.ChannelId) is ISocketMessageChannel channel)
  966. {
  967. var guild = (channel as SocketGuildChannel)?.Guild;
  968. if (guild != null && !guild.IsSynced)
  969. {
  970. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  971. return;
  972. }
  973. SocketUser author;
  974. if (guild != null)
  975. {
  976. if (data.WebhookId.IsSpecified)
  977. author = SocketWebhookUser.Create(guild, State, data.Author.Value, data.WebhookId.Value);
  978. else
  979. author = guild.GetUser(data.Author.Value.Id);
  980. }
  981. else
  982. author = (channel as SocketChannel).GetUser(data.Author.Value.Id);
  983. if (author == null)
  984. {
  985. if (guild != null)
  986. author = guild.AddOrUpdateUser(data.Author.Value); //User has no guild-specific data
  987. else if (channel is SocketGroupChannel)
  988. author = (channel as SocketGroupChannel).GetOrAddUser(data.Author.Value);
  989. else
  990. {
  991. await UnknownChannelUserAsync(type, data.Author.Value.Id, channel.Id).ConfigureAwait(false);
  992. return;
  993. }
  994. }
  995. var msg = SocketMessage.Create(this, State, author, channel, data);
  996. SocketChannelHelper.AddMessage(channel, this, msg);
  997. await TimedInvokeAsync(_messageReceivedEvent, nameof(MessageReceived), msg).ConfigureAwait(false);
  998. }
  999. else
  1000. {
  1001. await UnknownChannelAsync(type, data.ChannelId).ConfigureAwait(false);
  1002. return;
  1003. }
  1004. }
  1005. break;
  1006. case "MESSAGE_UPDATE":
  1007. {
  1008. await _gatewayLogger.DebugAsync("Received Dispatch (MESSAGE_UPDATE)").ConfigureAwait(false);
  1009. var data = (payload as JToken).ToObject<API.Message>(_serializer);
  1010. if (State.GetChannel(data.ChannelId) is ISocketMessageChannel channel)
  1011. {
  1012. var guild = (channel as SocketGuildChannel)?.Guild;
  1013. if (guild != null && !guild.IsSynced)
  1014. {
  1015. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  1016. return;
  1017. }
  1018. SocketMessage before = null, after = null;
  1019. SocketMessage cachedMsg = channel.GetCachedMessage(data.Id);
  1020. bool isCached = cachedMsg != null;
  1021. if (isCached)
  1022. {
  1023. before = cachedMsg.Clone();
  1024. cachedMsg.Update(State, data);
  1025. after = cachedMsg;
  1026. }
  1027. else if (data.Author.IsSpecified)
  1028. {
  1029. //Edited message isnt in cache, create a detached one
  1030. SocketUser author;
  1031. if (guild != null)
  1032. author = guild.GetUser(data.Author.Value.Id);
  1033. else
  1034. author = (channel as SocketChannel).GetUser(data.Author.Value.Id);
  1035. if (author == null)
  1036. author = SocketUnknownUser.Create(this, State, data.Author.Value);
  1037. after = SocketMessage.Create(this, State, author, channel, data);
  1038. }
  1039. var cacheableBefore = new Cacheable<IMessage, ulong>(before, data.Id, isCached, async () => await channel.GetMessageAsync(data.Id));
  1040. await TimedInvokeAsync(_messageUpdatedEvent, nameof(MessageUpdated), cacheableBefore, after, channel).ConfigureAwait(false);
  1041. }
  1042. else
  1043. {
  1044. await UnknownChannelAsync(type, data.ChannelId).ConfigureAwait(false);
  1045. return;
  1046. }
  1047. }
  1048. break;
  1049. case "MESSAGE_DELETE":
  1050. {
  1051. await _gatewayLogger.DebugAsync("Received Dispatch (MESSAGE_DELETE)").ConfigureAwait(false);
  1052. var data = (payload as JToken).ToObject<API.Message>(_serializer);
  1053. if (State.GetChannel(data.ChannelId) is ISocketMessageChannel channel)
  1054. {
  1055. var guild = (channel as SocketGuildChannel)?.Guild;
  1056. if (!(guild?.IsSynced ?? true))
  1057. {
  1058. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  1059. return;
  1060. }
  1061. var msg = SocketChannelHelper.RemoveMessage(channel, this, data.Id);
  1062. bool isCached = msg != null;
  1063. var cacheable = new Cacheable<IMessage, ulong>(msg, data.Id, isCached, async () => await channel.GetMessageAsync(data.Id));
  1064. await TimedInvokeAsync(_messageDeletedEvent, nameof(MessageDeleted), cacheable, channel).ConfigureAwait(false);
  1065. }
  1066. else
  1067. {
  1068. await UnknownChannelAsync(type, data.ChannelId).ConfigureAwait(false);
  1069. return;
  1070. }
  1071. }
  1072. break;
  1073. case "MESSAGE_REACTION_ADD":
  1074. {
  1075. await _gatewayLogger.DebugAsync("Received Dispatch (MESSAGE_REACTION_ADD)").ConfigureAwait(false);
  1076. var data = (payload as JToken).ToObject<API.Gateway.Reaction>(_serializer);
  1077. if (State.GetChannel(data.ChannelId) is ISocketMessageChannel channel)
  1078. {
  1079. var cachedMsg = channel.GetCachedMessage(data.MessageId) as SocketUserMessage;
  1080. bool isCached = cachedMsg != null;
  1081. var user = await channel.GetUserAsync(data.UserId, CacheMode.CacheOnly);
  1082. var reaction = SocketReaction.Create(data, channel, cachedMsg, Optional.Create(user));
  1083. var cacheable = new Cacheable<IUserMessage, ulong>(cachedMsg, data.MessageId, isCached, async () => await channel.GetMessageAsync(data.MessageId) as IUserMessage);
  1084. cachedMsg?.AddReaction(reaction);
  1085. await TimedInvokeAsync(_reactionAddedEvent, nameof(ReactionAdded), cacheable, channel, reaction).ConfigureAwait(false);
  1086. }
  1087. else
  1088. {
  1089. await UnknownChannelAsync(type, data.ChannelId).ConfigureAwait(false);
  1090. return;
  1091. }
  1092. }
  1093. break;
  1094. case "MESSAGE_REACTION_REMOVE":
  1095. {
  1096. await _gatewayLogger.DebugAsync("Received Dispatch (MESSAGE_REACTION_REMOVE)").ConfigureAwait(false);
  1097. var data = (payload as JToken).ToObject<API.Gateway.Reaction>(_serializer);
  1098. if (State.GetChannel(data.ChannelId) is ISocketMessageChannel channel)
  1099. {
  1100. var cachedMsg = channel.GetCachedMessage(data.MessageId) as SocketUserMessage;
  1101. bool isCached = cachedMsg != null;
  1102. var user = await channel.GetUserAsync(data.UserId, CacheMode.CacheOnly);
  1103. var reaction = SocketReaction.Create(data, channel, cachedMsg, Optional.Create(user));
  1104. var cacheable = new Cacheable<IUserMessage, ulong>(cachedMsg, data.MessageId, isCached, async () => await channel.GetMessageAsync(data.MessageId) as IUserMessage);
  1105. cachedMsg?.RemoveReaction(reaction);
  1106. await TimedInvokeAsync(_reactionRemovedEvent, nameof(ReactionRemoved), cacheable, channel, reaction).ConfigureAwait(false);
  1107. }
  1108. else
  1109. {
  1110. await UnknownChannelAsync(type, data.ChannelId).ConfigureAwait(false);
  1111. return;
  1112. }
  1113. }
  1114. break;
  1115. case "MESSAGE_REACTION_REMOVE_ALL":
  1116. {
  1117. await _gatewayLogger.DebugAsync("Received Dispatch (MESSAGE_REACTION_REMOVE_ALL)").ConfigureAwait(false);
  1118. var data = (payload as JToken).ToObject<RemoveAllReactionsEvent>(_serializer);
  1119. if (State.GetChannel(data.ChannelId) is ISocketMessageChannel channel)
  1120. {
  1121. var cachedMsg = channel.GetCachedMessage(data.MessageId) as SocketUserMessage;
  1122. bool isCached = cachedMsg != null;
  1123. var cacheable = new Cacheable<IUserMessage, ulong>(cachedMsg, data.MessageId, isCached, async () => await channel.GetMessageAsync(data.MessageId) as IUserMessage);
  1124. cachedMsg?.ClearReactions();
  1125. await TimedInvokeAsync(_reactionsClearedEvent, nameof(ReactionsCleared), cacheable, channel).ConfigureAwait(false);
  1126. }
  1127. else
  1128. {
  1129. await UnknownChannelAsync(type, data.ChannelId).ConfigureAwait(false);
  1130. return;
  1131. }
  1132. }
  1133. break;
  1134. case "MESSAGE_DELETE_BULK":
  1135. {
  1136. await _gatewayLogger.DebugAsync("Received Dispatch (MESSAGE_DELETE_BULK)").ConfigureAwait(false);
  1137. var data = (payload as JToken).ToObject<MessageDeleteBulkEvent>(_serializer);
  1138. if (State.GetChannel(data.ChannelId) is ISocketMessageChannel channel)
  1139. {
  1140. var guild = (channel as SocketGuildChannel)?.Guild;
  1141. if (!(guild?.IsSynced ?? true))
  1142. {
  1143. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  1144. return;
  1145. }
  1146. foreach (ulong id in data.Ids)
  1147. {
  1148. var msg = SocketChannelHelper.RemoveMessage(channel, this, id);
  1149. bool isCached = msg != null;
  1150. var cacheable = new Cacheable<IMessage, ulong>(msg, id, isCached, async () => await channel.GetMessageAsync(id));
  1151. await TimedInvokeAsync(_messageDeletedEvent, nameof(MessageDeleted), cacheable, channel).ConfigureAwait(false);
  1152. }
  1153. }
  1154. else
  1155. {
  1156. await UnknownChannelAsync(type, data.ChannelId).ConfigureAwait(false);
  1157. return;
  1158. }
  1159. }
  1160. break;
  1161. //Statuses
  1162. case "PRESENCE_UPDATE":
  1163. {
  1164. await _gatewayLogger.DebugAsync("Received Dispatch (PRESENCE_UPDATE)").ConfigureAwait(false);
  1165. var data = (payload as JToken).ToObject<API.Presence>(_serializer);
  1166. if (data.GuildId.IsSpecified)
  1167. {
  1168. var guild = State.GetGuild(data.GuildId.Value);
  1169. if (guild == null)
  1170. {
  1171. await UnknownGuildAsync(type, data.GuildId.Value).ConfigureAwait(false);
  1172. return;
  1173. }
  1174. if (!guild.IsSynced)
  1175. {
  1176. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  1177. return;
  1178. }
  1179. var user = guild.GetUser(data.User.Id);
  1180. if (user == null)
  1181. {
  1182. if (data.Status == UserStatus.Offline)
  1183. {
  1184. return;
  1185. }
  1186. user = guild.AddOrUpdateUser(data);
  1187. }
  1188. else
  1189. {
  1190. var globalBefore = user.GlobalUser.Clone();
  1191. if (user.GlobalUser.Update(State, data.User))
  1192. {
  1193. //Global data was updated, trigger UserUpdated
  1194. await TimedInvokeAsync(_userUpdatedEvent, nameof(UserUpdated), globalBefore, user).ConfigureAwait(false);
  1195. }
  1196. }
  1197. var before = user.Clone();
  1198. user.Update(State, data, true);
  1199. await TimedInvokeAsync(_guildMemberUpdatedEvent, nameof(GuildMemberUpdated), before, user).ConfigureAwait(false);
  1200. }
  1201. else
  1202. {
  1203. var globalUser = State.GetUser(data.User.Id);
  1204. if (globalUser == null)
  1205. {
  1206. await UnknownGlobalUserAsync(type, data.User.Id).ConfigureAwait(false);
  1207. return;
  1208. }
  1209. var before = globalUser.Clone();
  1210. globalUser.Update(State, data.User);
  1211. globalUser.Update(State, data);
  1212. await TimedInvokeAsync(_userUpdatedEvent, nameof(UserUpdated), before, globalUser).ConfigureAwait(false);
  1213. }
  1214. }
  1215. break;
  1216. case "TYPING_START":
  1217. {
  1218. await _gatewayLogger.DebugAsync("Received Dispatch (TYPING_START)").ConfigureAwait(false);
  1219. var data = (payload as JToken).ToObject<TypingStartEvent>(_serializer);
  1220. if (State.GetChannel(data.ChannelId) is ISocketMessageChannel channel)
  1221. {
  1222. var guild = (channel as SocketGuildChannel)?.Guild;
  1223. if (!(guild?.IsSynced ?? true))
  1224. {
  1225. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  1226. return;
  1227. }
  1228. var user = (channel as SocketChannel).GetUser(data.UserId);
  1229. if (user != null)
  1230. await TimedInvokeAsync(_userIsTypingEvent, nameof(UserIsTyping), user, channel).ConfigureAwait(false);
  1231. }
  1232. }
  1233. break;
  1234. //Users
  1235. case "USER_UPDATE":
  1236. {
  1237. await _gatewayLogger.DebugAsync("Received Dispatch (USER_UPDATE)").ConfigureAwait(false);
  1238. var data = (payload as JToken).ToObject<API.User>(_serializer);
  1239. if (data.Id == CurrentUser.Id)
  1240. {
  1241. var before = CurrentUser.Clone();
  1242. CurrentUser.Update(State, data);
  1243. await TimedInvokeAsync(_selfUpdatedEvent, nameof(CurrentUserUpdated), before, CurrentUser).ConfigureAwait(false);
  1244. }
  1245. else
  1246. {
  1247. await _gatewayLogger.WarningAsync("Received USER_UPDATE for wrong user.").ConfigureAwait(false);
  1248. return;
  1249. }
  1250. }
  1251. break;
  1252. //Voice
  1253. case "VOICE_STATE_UPDATE":
  1254. {
  1255. await _gatewayLogger.DebugAsync("Received Dispatch (VOICE_STATE_UPDATE)").ConfigureAwait(false);
  1256. var data = (payload as JToken).ToObject<API.VoiceState>(_serializer);
  1257. SocketUser user;
  1258. SocketVoiceState before, after;
  1259. if (data.GuildId != null)
  1260. {
  1261. var guild = State.GetGuild(data.GuildId.Value);
  1262. if (guild == null)
  1263. {
  1264. await UnknownGuildAsync(type, data.GuildId.Value).ConfigureAwait(false);
  1265. return;
  1266. }
  1267. else if (!guild.IsSynced)
  1268. {
  1269. await UnsyncedGuildAsync(type, guild.Id).ConfigureAwait(false);
  1270. return;
  1271. }
  1272. if (data.ChannelId != null)
  1273. {
  1274. before = guild.GetVoiceState(data.UserId)?.Clone() ?? SocketVoiceState.Default;
  1275. after = await guild.AddOrUpdateVoiceStateAsync(State, data).ConfigureAwait(false);
  1276. /*if (data.UserId == CurrentUser.Id)
  1277. {
  1278. var _ = guild.FinishJoinAudioChannel().ConfigureAwait(false);
  1279. }*/
  1280. }
  1281. else
  1282. {
  1283. before = await guild.RemoveVoiceStateAsync(data.UserId).ConfigureAwait(false) ?? SocketVoiceState.Default;
  1284. after = SocketVoiceState.Create(null, data);
  1285. }
  1286. user = guild.GetUser(data.UserId);
  1287. if (user == null)
  1288. {
  1289. await UnknownGuildUserAsync(type, data.UserId, guild.Id).ConfigureAwait(false);
  1290. return;
  1291. }
  1292. }
  1293. else
  1294. {
  1295. var groupChannel = State.GetChannel(data.ChannelId.Value) as SocketGroupChannel;
  1296. if (groupChannel == null)
  1297. {
  1298. await UnknownChannelAsync(type, data.ChannelId.Value).ConfigureAwait(false);
  1299. return;
  1300. }
  1301. if (data.ChannelId != null)
  1302. {
  1303. before = groupChannel.GetVoiceState(data.UserId)?.Clone() ?? SocketVoiceState.Default;
  1304. after = groupChannel.AddOrUpdateVoiceState(State, data);
  1305. }
  1306. else
  1307. {
  1308. before = groupChannel.RemoveVoiceState(data.UserId) ?? SocketVoiceState.Default;
  1309. after = SocketVoiceState.Create(null, data);
  1310. }
  1311. user = groupChannel.GetUser(data.UserId);
  1312. if (user == null)
  1313. {
  1314. await UnknownChannelUserAsync(type, data.UserId, groupChannel.Id).ConfigureAwait(false);
  1315. return;
  1316. }
  1317. }
  1318. await TimedInvokeAsync(_userVoiceStateUpdatedEvent, nameof(UserVoiceStateUpdated), user, before, after).ConfigureAwait(false);
  1319. }
  1320. break;
  1321. case "VOICE_SERVER_UPDATE":
  1322. {
  1323. await _gatewayLogger.DebugAsync("Received Dispatch (VOICE_SERVER_UPDATE)").ConfigureAwait(false);
  1324. var data = (payload as JToken).ToObject<VoiceServerUpdateEvent>(_serializer);
  1325. var guild = State.GetGuild(data.GuildId);
  1326. if (guild != null)
  1327. {
  1328. string endpoint = data.Endpoint.Substring(0, data.Endpoint.LastIndexOf(':'));
  1329. var _ = guild.FinishConnectAudio(endpoint, data.Token).ConfigureAwait(false);
  1330. }
  1331. else
  1332. {
  1333. await UnknownGuildAsync(type, data.GuildId).ConfigureAwait(false);
  1334. return;
  1335. }
  1336. }
  1337. break;
  1338. //Ignored (User only)
  1339. case "CHANNEL_PINS_ACK":
  1340. await _gatewayLogger.DebugAsync("Ignored Dispatch (CHANNEL_PINS_ACK)").ConfigureAwait(false);
  1341. break;
  1342. case "CHANNEL_PINS_UPDATE":
  1343. await _gatewayLogger.DebugAsync("Ignored Dispatch (CHANNEL_PINS_UPDATE)").ConfigureAwait(false);
  1344. break;
  1345. case "GUILD_INTEGRATIONS_UPDATE":
  1346. await _gatewayLogger.DebugAsync("Ignored Dispatch (GUILD_INTEGRATIONS_UPDATE)").ConfigureAwait(false);
  1347. break;
  1348. case "MESSAGE_ACK":
  1349. await _gatewayLogger.DebugAsync("Ignored Dispatch (MESSAGE_ACK)").ConfigureAwait(false);
  1350. break;
  1351. case "USER_SETTINGS_UPDATE":
  1352. await _gatewayLogger.DebugAsync("Ignored Dispatch (USER_SETTINGS_UPDATE)").ConfigureAwait(false);
  1353. break;
  1354. case "WEBHOOKS_UPDATE":
  1355. await _gatewayLogger.DebugAsync("Ignored Dispatch (WEBHOOKS_UPDATE)").ConfigureAwait(false);
  1356. break;
  1357. //Others
  1358. default:
  1359. await _gatewayLogger.WarningAsync($"Unknown Dispatch ({type})").ConfigureAwait(false);
  1360. break;
  1361. }
  1362. break;
  1363. default:
  1364. await _gatewayLogger.WarningAsync($"Unknown OpCode ({opCode})").ConfigureAwait(false);
  1365. break;
  1366. }
  1367. }
  1368. catch (Exception ex)
  1369. {
  1370. await _gatewayLogger.ErrorAsync($"Error handling {opCode}{(type != null ? $" ({type})" : "")}", ex).ConfigureAwait(false);
  1371. }
  1372. }
  1373. private async Task RunHeartbeatAsync(int intervalMillis, CancellationToken cancelToken)
  1374. {
  1375. try
  1376. {
  1377. await _gatewayLogger.DebugAsync("Heartbeat Started").ConfigureAwait(false);
  1378. while (!cancelToken.IsCancellationRequested)
  1379. {
  1380. int now = Environment.TickCount;
  1381. //Did server respond to our last heartbeat, or are we still receiving messages (long load?)
  1382. if (_heartbeatTimes.Count != 0 && (now - _lastMessageTime) > intervalMillis)
  1383. {
  1384. if (ConnectionState == ConnectionState.Connected && (_guildDownloadTask?.IsCompleted ?? true))
  1385. {
  1386. _connection.Error(new Exception("Server missed last heartbeat"));
  1387. return;
  1388. }
  1389. }
  1390. _heartbeatTimes.Enqueue(now);
  1391. try
  1392. {
  1393. await ApiClient.SendHeartbeatAsync(_lastSeq).ConfigureAwait(false);
  1394. }
  1395. catch (Exception ex)
  1396. {
  1397. await _gatewayLogger.WarningAsync("Heartbeat Errored", ex).ConfigureAwait(false);
  1398. }
  1399. await Task.Delay(intervalMillis, cancelToken).ConfigureAwait(false);
  1400. }
  1401. await _gatewayLogger.DebugAsync("Heartbeat Stopped").ConfigureAwait(false);
  1402. }
  1403. catch (OperationCanceledException)
  1404. {
  1405. await _gatewayLogger.DebugAsync("Heartbeat Stopped").ConfigureAwait(false);
  1406. }
  1407. catch (Exception ex)
  1408. {
  1409. await _gatewayLogger.ErrorAsync("Heartbeat Errored", ex).ConfigureAwait(false);
  1410. }
  1411. }
  1412. /*public async Task WaitForGuildsAsync()
  1413. {
  1414. var downloadTask = _guildDownloadTask;
  1415. if (downloadTask != null)
  1416. await _guildDownloadTask.ConfigureAwait(false);
  1417. }*/
  1418. private async Task WaitForGuildsAsync(CancellationToken cancelToken, Logger logger)
  1419. {
  1420. //Wait for GUILD_AVAILABLEs
  1421. try
  1422. {
  1423. await logger.DebugAsync("GuildDownloader Started").ConfigureAwait(false);
  1424. while ((_unavailableGuildCount != 0) && (Environment.TickCount - _lastGuildAvailableTime < 2000))
  1425. await Task.Delay(500, cancelToken).ConfigureAwait(false);
  1426. await logger.DebugAsync("GuildDownloader Stopped").ConfigureAwait(false);
  1427. }
  1428. catch (OperationCanceledException)
  1429. {
  1430. await logger.DebugAsync("GuildDownloader Stopped").ConfigureAwait(false);
  1431. }
  1432. catch (Exception ex)
  1433. {
  1434. await logger.ErrorAsync("GuildDownloader Errored", ex).ConfigureAwait(false);
  1435. }
  1436. }
  1437. private async Task SyncGuildsAsync()
  1438. {
  1439. var guildIds = Guilds.Where(x => !x.IsSynced).Select(x => x.Id).ToImmutableArray();
  1440. if (guildIds.Length > 0)
  1441. await ApiClient.SendGuildSyncAsync(guildIds).ConfigureAwait(false);
  1442. }
  1443. internal SocketGuild AddGuild(ExtendedGuild model, ClientState state)
  1444. {
  1445. var guild = SocketGuild.Create(this, state, model);
  1446. state.AddGuild(guild);
  1447. if (model.Large)
  1448. _largeGuilds.Enqueue(model.Id);
  1449. return guild;
  1450. }
  1451. internal SocketGuild RemoveGuild(ulong id)
  1452. {
  1453. var guild = State.RemoveGuild(id);
  1454. if (guild != null)
  1455. {
  1456. foreach (var channel in guild.Channels)
  1457. State.RemoveChannel(id);
  1458. foreach (var user in guild.Users)
  1459. user.GlobalUser.RemoveRef(this);
  1460. }
  1461. return guild;
  1462. }
  1463. internal ISocketPrivateChannel AddPrivateChannel(API.Channel model, ClientState state)
  1464. {
  1465. var channel = SocketChannel.CreatePrivate(this, state, model);
  1466. state.AddChannel(channel as SocketChannel);
  1467. if (channel is SocketDMChannel dm)
  1468. dm.Recipient.GlobalUser.DMChannel = dm;
  1469. return channel;
  1470. }
  1471. internal ISocketPrivateChannel RemovePrivateChannel(ulong id)
  1472. {
  1473. var channel = State.RemoveChannel(id) as ISocketPrivateChannel;
  1474. if (channel != null)
  1475. {
  1476. if (channel is SocketDMChannel dmChannel)
  1477. dmChannel.Recipient.GlobalUser.DMChannel = null;
  1478. foreach (var recipient in channel.Recipients)
  1479. recipient.GlobalUser.RemoveRef(this);
  1480. }
  1481. return channel;
  1482. }
  1483. private async Task GuildAvailableAsync(SocketGuild guild)
  1484. {
  1485. if (!guild.IsConnected)
  1486. {
  1487. guild.IsConnected = true;
  1488. await TimedInvokeAsync(_guildAvailableEvent, nameof(GuildAvailable), guild).ConfigureAwait(false);
  1489. }
  1490. }
  1491. private async Task GuildUnavailableAsync(SocketGuild guild)
  1492. {
  1493. if (guild.IsConnected)
  1494. {
  1495. guild.IsConnected = false;
  1496. await TimedInvokeAsync(_guildUnavailableEvent, nameof(GuildUnavailable), guild).ConfigureAwait(false);
  1497. }
  1498. }
  1499. private async Task TimedInvokeAsync(AsyncEvent<Func<Task>> eventHandler, string name)
  1500. {
  1501. if (eventHandler.HasSubscribers)
  1502. {
  1503. if (HandlerTimeout.HasValue)
  1504. await TimeoutWrap(name, () => eventHandler.InvokeAsync()).ConfigureAwait(false);
  1505. else
  1506. await eventHandler.InvokeAsync().ConfigureAwait(false);
  1507. }
  1508. }
  1509. private async Task TimedInvokeAsync<T>(AsyncEvent<Func<T, Task>> eventHandler, string name, T arg)
  1510. {
  1511. if (eventHandler.HasSubscribers)
  1512. {
  1513. if (HandlerTimeout.HasValue)
  1514. await TimeoutWrap(name, () => eventHandler.InvokeAsync(arg)).ConfigureAwait(false);
  1515. else
  1516. await eventHandler.InvokeAsync(arg).ConfigureAwait(false);
  1517. }
  1518. }
  1519. private async Task TimedInvokeAsync<T1, T2>(AsyncEvent<Func<T1, T2, Task>> eventHandler, string name, T1 arg1, T2 arg2)
  1520. {
  1521. if (eventHandler.HasSubscribers)
  1522. {
  1523. if (HandlerTimeout.HasValue)
  1524. await TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2)).ConfigureAwait(false);
  1525. else
  1526. await eventHandler.InvokeAsync(arg1, arg2).ConfigureAwait(false);
  1527. }
  1528. }
  1529. private async Task TimedInvokeAsync<T1, T2, T3>(AsyncEvent<Func<T1, T2, T3, Task>> eventHandler, string name, T1 arg1, T2 arg2, T3 arg3)
  1530. {
  1531. if (eventHandler.HasSubscribers)
  1532. {
  1533. if (HandlerTimeout.HasValue)
  1534. await TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2, arg3)).ConfigureAwait(false);
  1535. else
  1536. await eventHandler.InvokeAsync(arg1, arg2, arg3).ConfigureAwait(false);
  1537. }
  1538. }
  1539. private async Task TimedInvokeAsync<T1, T2, T3, T4>(AsyncEvent<Func<T1, T2, T3, T4, Task>> eventHandler, string name, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
  1540. {
  1541. if (eventHandler.HasSubscribers)
  1542. {
  1543. if (HandlerTimeout.HasValue)
  1544. await TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2, arg3, arg4)).ConfigureAwait(false);
  1545. else
  1546. await eventHandler.InvokeAsync(arg1, arg2, arg3, arg4).ConfigureAwait(false);
  1547. }
  1548. }
  1549. private async Task TimedInvokeAsync<T1, T2, T3, T4, T5>(AsyncEvent<Func<T1, T2, T3, T4, T5, Task>> eventHandler, string name, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5)
  1550. {
  1551. if (eventHandler.HasSubscribers)
  1552. {
  1553. if (HandlerTimeout.HasValue)
  1554. await TimeoutWrap(name, () => eventHandler.InvokeAsync(arg1, arg2, arg3, arg4, arg5)).ConfigureAwait(false);
  1555. else
  1556. await eventHandler.InvokeAsync(arg1, arg2, arg3, arg4, arg5).ConfigureAwait(false);
  1557. }
  1558. }
  1559. private async Task TimeoutWrap(string name, Func<Task> action)
  1560. {
  1561. try
  1562. {
  1563. var timeoutTask = Task.Delay(HandlerTimeout.Value);
  1564. var handlersTask = action();
  1565. if (await Task.WhenAny(timeoutTask, handlersTask).ConfigureAwait(false) == timeoutTask)
  1566. {
  1567. await _gatewayLogger.WarningAsync($"A {name} handler is blocking the gateway task.").ConfigureAwait(false);
  1568. await handlersTask.ConfigureAwait(false); //Ensure the handler completes
  1569. }
  1570. }
  1571. catch (Exception ex)
  1572. {
  1573. await _gatewayLogger.WarningAsync($"A {name} handler has thrown an unhandled exception.", ex).ConfigureAwait(false);
  1574. }
  1575. }
  1576. private async Task UnknownGlobalUserAsync(string evnt, ulong userId)
  1577. {
  1578. string details = $"{evnt} User={userId}";
  1579. await _gatewayLogger.WarningAsync($"Unknown User ({details}).").ConfigureAwait(false);
  1580. }
  1581. private async Task UnknownChannelUserAsync(string evnt, ulong userId, ulong channelId)
  1582. {
  1583. string details = $"{evnt} User={userId} Channel={channelId}";
  1584. await _gatewayLogger.WarningAsync($"Unknown User ({details}).").ConfigureAwait(false);
  1585. }
  1586. private async Task UnknownGuildUserAsync(string evnt, ulong userId, ulong guildId)
  1587. {
  1588. string details = $"{evnt} User={userId} Guild={guildId}";
  1589. await _gatewayLogger.WarningAsync($"Unknown User ({details}).").ConfigureAwait(false);
  1590. }
  1591. private async Task IncompleteGuildUserAsync(string evnt, ulong userId, ulong guildId)
  1592. {
  1593. string details = $"{evnt} User={userId} Guild={guildId}";
  1594. await _gatewayLogger.DebugAsync($"User has not been downloaded ({details}).").ConfigureAwait(false);
  1595. }
  1596. private async Task UnknownChannelAsync(string evnt, ulong channelId)
  1597. {
  1598. string details = $"{evnt} Channel={channelId}";
  1599. await _gatewayLogger.WarningAsync($"Unknown Channel ({details}).").ConfigureAwait(false);
  1600. }
  1601. private async Task UnknownChannelAsync(string evnt, ulong channelId, ulong guildId)
  1602. {
  1603. if (guildId == 0)
  1604. {
  1605. await UnknownChannelAsync(evnt, channelId).ConfigureAwait(false);
  1606. return;
  1607. }
  1608. string details = $"{evnt} Channel={channelId} Guild={guildId}";
  1609. await _gatewayLogger.WarningAsync($"Unknown Channel ({details}).").ConfigureAwait(false);
  1610. }
  1611. private async Task UnknownRoleAsync(string evnt, ulong roleId, ulong guildId)
  1612. {
  1613. string details = $"{evnt} Role={roleId} Guild={guildId}";
  1614. await _gatewayLogger.WarningAsync($"Unknown Role ({details}).").ConfigureAwait(false);
  1615. }
  1616. private async Task UnknownGuildAsync(string evnt, ulong guildId)
  1617. {
  1618. string details = $"{evnt} Guild={guildId}";
  1619. await _gatewayLogger.WarningAsync($"Unknown Guild ({details}).").ConfigureAwait(false);
  1620. }
  1621. private async Task UnsyncedGuildAsync(string evnt, ulong guildId)
  1622. {
  1623. string details = $"{evnt} Guild={guildId}";
  1624. await _gatewayLogger.DebugAsync($"Unsynced Guild ({details}).").ConfigureAwait(false);
  1625. }
  1626. internal int GetAudioId() => _nextAudioId++;
  1627. //IDiscordClient
  1628. async Task<IApplication> IDiscordClient.GetApplicationInfoAsync(RequestOptions options)
  1629. => await GetApplicationInfoAsync().ConfigureAwait(false);
  1630. Task<IChannel> IDiscordClient.GetChannelAsync(ulong id, CacheMode mode, RequestOptions options)
  1631. => Task.FromResult<IChannel>(GetChannel(id));
  1632. Task<IReadOnlyCollection<IPrivateChannel>> IDiscordClient.GetPrivateChannelsAsync(CacheMode mode, RequestOptions options)
  1633. => Task.FromResult<IReadOnlyCollection<IPrivateChannel>>(PrivateChannels);
  1634. Task<IReadOnlyCollection<IDMChannel>> IDiscordClient.GetDMChannelsAsync(CacheMode mode, RequestOptions options)
  1635. => Task.FromResult<IReadOnlyCollection<IDMChannel>>(DMChannels);
  1636. Task<IReadOnlyCollection<IGroupChannel>> IDiscordClient.GetGroupChannelsAsync(CacheMode mode, RequestOptions options)
  1637. => Task.FromResult<IReadOnlyCollection<IGroupChannel>>(GroupChannels);
  1638. async Task<IReadOnlyCollection<IConnection>> IDiscordClient.GetConnectionsAsync(RequestOptions options)
  1639. => await GetConnectionsAsync().ConfigureAwait(false);
  1640. async Task<IInvite> IDiscordClient.GetInviteAsync(string inviteId, bool withCount, RequestOptions options)
  1641. => await GetInviteAsync(inviteId, withCount, options).ConfigureAwait(false);
  1642. Task<IGuild> IDiscordClient.GetGuildAsync(ulong id, CacheMode mode, RequestOptions options)
  1643. => Task.FromResult<IGuild>(GetGuild(id));
  1644. Task<IReadOnlyCollection<IGuild>> IDiscordClient.GetGuildsAsync(CacheMode mode, RequestOptions options)
  1645. => Task.FromResult<IReadOnlyCollection<IGuild>>(Guilds);
  1646. async Task<IGuild> IDiscordClient.CreateGuildAsync(string name, IVoiceRegion region, Stream jpegIcon, RequestOptions options)
  1647. => await CreateGuildAsync(name, region, jpegIcon).ConfigureAwait(false);
  1648. Task<IUser> IDiscordClient.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
  1649. => Task.FromResult<IUser>(GetUser(id));
  1650. Task<IUser> IDiscordClient.GetUserAsync(string username, string discriminator, RequestOptions options)
  1651. => Task.FromResult<IUser>(GetUser(username, discriminator));
  1652. Task<IReadOnlyCollection<IVoiceRegion>> IDiscordClient.GetVoiceRegionsAsync(RequestOptions options)
  1653. => Task.FromResult<IReadOnlyCollection<IVoiceRegion>>(VoiceRegions);
  1654. Task<IVoiceRegion> IDiscordClient.GetVoiceRegionAsync(string id, RequestOptions options)
  1655. => Task.FromResult<IVoiceRegion>(GetVoiceRegion(id));
  1656. async Task IDiscordClient.StartAsync()
  1657. => await StartAsync().ConfigureAwait(false);
  1658. async Task IDiscordClient.StopAsync()
  1659. => await StopAsync().ConfigureAwait(false);
  1660. }
  1661. }