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