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

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