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

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