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.

AudioClient.cs 12 kB

10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. using Discord.API.Client.GatewaySocket;
  2. using Discord.API.Client.Rest;
  3. using Discord.Logging;
  4. using Discord.Net.Rest;
  5. using Discord.Net.WebSockets;
  6. using Newtonsoft.Json;
  7. using Nito.AsyncEx;
  8. using System;
  9. using System.Diagnostics;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace Discord.Audio
  13. {
  14. internal class AudioClient : IAudioClient
  15. {
  16. private readonly DiscordConfig _config;
  17. private readonly AsyncLock _connectionLock;
  18. private readonly TaskManager _taskManager;
  19. private ConnectionState _gatewayState;
  20. internal Logger Logger { get; }
  21. public int Id { get; }
  22. public AudioService Service { get; }
  23. public AudioServiceConfig Config { get; }
  24. public RestClient ClientAPI { get; }
  25. public GatewaySocket GatewaySocket { get; }
  26. public VoiceSocket VoiceSocket { get; }
  27. public JsonSerializer Serializer { get; }
  28. public CancellationToken CancelToken { get; private set; }
  29. public string SessionId => GatewaySocket.SessionId;
  30. public ConnectionState State => VoiceSocket.State;
  31. public Server Server => VoiceSocket.Server;
  32. public VoiceChannel Channel => VoiceSocket.Channel;
  33. public AudioClient(DiscordClient client, Server server, int id)
  34. {
  35. Id = id;
  36. Service = client.GetService<AudioService>();
  37. Config = Service.Config;
  38. Serializer = client.Serializer;
  39. _gatewayState = (int)ConnectionState.Disconnected;
  40. //Logging
  41. Logger = client.Log.CreateLogger($"AudioClient #{id}");
  42. //Async
  43. _taskManager = new TaskManager(Cleanup, false);
  44. _connectionLock = new AsyncLock();
  45. CancelToken = new CancellationToken(true);
  46. //Networking
  47. if (Config.EnableMultiserver)
  48. {
  49. //TODO: We can remove this hack when official API launches
  50. var baseConfig = client.Config;
  51. var builder = new DiscordConfigBuilder
  52. {
  53. AppName = baseConfig.AppName,
  54. AppUrl = baseConfig.AppUrl,
  55. AppVersion = baseConfig.AppVersion,
  56. CacheToken = baseConfig.CacheDir != null,
  57. ConnectionTimeout = baseConfig.ConnectionTimeout,
  58. EnablePreUpdateEvents = false,
  59. FailedReconnectDelay = baseConfig.FailedReconnectDelay,
  60. LargeThreshold = 1,
  61. LogLevel = baseConfig.LogLevel,
  62. MessageCacheSize = 0,
  63. ReconnectDelay = baseConfig.ReconnectDelay,
  64. UsePermissionsCache = false
  65. };
  66. _config = builder.Build();
  67. ClientAPI = new JsonRestClient(_config, DiscordConfig.ClientAPIUrl, client.Log.CreateLogger($"ClientAPI #{id}"));
  68. GatewaySocket = new GatewaySocket(_config, client.Serializer, client.Log.CreateLogger($"Gateway #{id}"));
  69. GatewaySocket.Connected += (s, e) =>
  70. {
  71. if (_gatewayState == ConnectionState.Connecting)
  72. EndGatewayConnect();
  73. };
  74. }
  75. else
  76. {
  77. _config = client.Config;
  78. GatewaySocket = client.GatewaySocket;
  79. }
  80. GatewaySocket.ReceivedDispatch += (s, e) => OnReceivedEvent(e);
  81. VoiceSocket = new VoiceSocket(_config, Config, client.Serializer, client.Log.CreateLogger($"Voice #{id}"));
  82. VoiceSocket.Server = server;
  83. }
  84. public async Task Connect()
  85. {
  86. if (Config.EnableMultiserver)
  87. await BeginGatewayConnect().ConfigureAwait(false);
  88. else
  89. {
  90. var cancelSource = new CancellationTokenSource();
  91. CancelToken = cancelSource.Token;
  92. await _taskManager.Start(new Task[0], cancelSource).ConfigureAwait(false);
  93. }
  94. }
  95. private async Task BeginGatewayConnect()
  96. {
  97. try
  98. {
  99. using (await _connectionLock.LockAsync().ConfigureAwait(false))
  100. {
  101. await Disconnect().ConfigureAwait(false);
  102. _taskManager.ClearException();
  103. ClientAPI.Token = Service.Client.ClientAPI.Token;
  104. Stopwatch stopwatch = null;
  105. if (_config.LogLevel >= LogSeverity.Verbose)
  106. stopwatch = Stopwatch.StartNew();
  107. _gatewayState = ConnectionState.Connecting;
  108. var cancelSource = new CancellationTokenSource();
  109. CancelToken = cancelSource.Token;
  110. ClientAPI.CancelToken = CancelToken;
  111. await GatewaySocket.Connect(ClientAPI, CancelToken).ConfigureAwait(false);
  112. await _taskManager.Start(new Task[0], cancelSource).ConfigureAwait(false);
  113. GatewaySocket.WaitForConnection(CancelToken);
  114. if (_config.LogLevel >= LogSeverity.Verbose)
  115. {
  116. stopwatch.Stop();
  117. double seconds = Math.Round(stopwatch.ElapsedTicks / (double)TimeSpan.TicksPerSecond, 2);
  118. Logger.Verbose($"Connection took {seconds} sec");
  119. }
  120. }
  121. }
  122. catch (Exception ex)
  123. {
  124. await _taskManager.SignalError(ex).ConfigureAwait(false);
  125. throw;
  126. }
  127. }
  128. private void EndGatewayConnect()
  129. {
  130. _gatewayState = ConnectionState.Connected;
  131. }
  132. public async Task Disconnect()
  133. {
  134. await _taskManager.Stop(true).ConfigureAwait(false);
  135. if (Config.EnableMultiserver)
  136. ClientAPI.Token = null;
  137. }
  138. private async Task Cleanup()
  139. {
  140. var oldState = _gatewayState;
  141. _gatewayState = ConnectionState.Disconnecting;
  142. if (Config.EnableMultiserver)
  143. {
  144. if (oldState == ConnectionState.Connected)
  145. {
  146. try { await ClientAPI.Send(new LogoutRequest()).ConfigureAwait(false); }
  147. catch (OperationCanceledException) { }
  148. }
  149. await GatewaySocket.Disconnect().ConfigureAwait(false);
  150. ClientAPI.Token = null;
  151. }
  152. var server = VoiceSocket.Server;
  153. VoiceSocket.Server = null;
  154. VoiceSocket.Channel = null;
  155. if (Config.EnableMultiserver)
  156. await Service.RemoveClient(server, this).ConfigureAwait(false);
  157. SendVoiceUpdate(server.Id, null);
  158. await VoiceSocket.Disconnect().ConfigureAwait(false);
  159. if (Config.EnableMultiserver)
  160. await GatewaySocket.Disconnect().ConfigureAwait(false);
  161. _gatewayState = (int)ConnectionState.Disconnected;
  162. }
  163. public async Task Join(VoiceChannel channel)
  164. {
  165. if (channel == null) throw new ArgumentNullException(nameof(channel));
  166. if (channel.Type != ChannelType.Voice)
  167. throw new ArgumentException("Channel must be a voice channel.", nameof(channel));
  168. if (channel == VoiceSocket.Channel) return;
  169. var server = channel.Server;
  170. if (server != VoiceSocket.Server)
  171. throw new ArgumentException("This is channel is not part of the current server.", nameof(channel));
  172. if (VoiceSocket.Server == null)
  173. throw new InvalidOperationException("This client has been closed.");
  174. SendVoiceUpdate(channel.Server.Id, channel.Id);
  175. using (await _connectionLock.LockAsync().ConfigureAwait(false))
  176. await Task.Run(() => VoiceSocket.WaitForConnection(CancelToken)).ConfigureAwait(false);
  177. }
  178. private async void OnReceivedEvent(WebSocketEventEventArgs e)
  179. {
  180. try
  181. {
  182. switch (e.Type)
  183. {
  184. case "VOICE_STATE_UPDATE":
  185. {
  186. var data = e.Payload.ToObject<VoiceStateUpdateEvent>(Serializer);
  187. if (data.GuildId == VoiceSocket.Server?.Id && data.UserId == Service.Client.CurrentUser?.Id)
  188. {
  189. if (data.ChannelId == null)
  190. await Disconnect().ConfigureAwait(false);
  191. else
  192. {
  193. var channel = Service.Client.GetChannel(data.ChannelId.Value) as VoiceChannel;
  194. if (channel != null)
  195. VoiceSocket.Channel = channel;
  196. else
  197. {
  198. Logger.Warning("VOICE_STATE_UPDATE referenced an unknown channel, disconnecting.");
  199. await Disconnect().ConfigureAwait(false);
  200. }
  201. }
  202. }
  203. }
  204. break;
  205. case "VOICE_SERVER_UPDATE":
  206. {
  207. var data = e.Payload.ToObject<VoiceServerUpdateEvent>(Serializer);
  208. if (data.GuildId == VoiceSocket.Server?.Id)
  209. {
  210. var client = Service.Client;
  211. var id = client.CurrentUser?.Id;
  212. if (id != null)
  213. {
  214. var host = "wss://" + e.Payload.Value<string>("endpoint").Split(':')[0];
  215. await VoiceSocket.Connect(host, data.Token, id.Value, GatewaySocket.SessionId, CancelToken).ConfigureAwait(false);
  216. }
  217. }
  218. }
  219. break;
  220. }
  221. }
  222. catch (Exception ex)
  223. {
  224. Logger.Error($"Error handling {e.Type} event", ex);
  225. }
  226. }
  227. public void Send(byte[] data, int offset, int count)
  228. {
  229. if (data == null) throw new ArgumentException(nameof(data));
  230. if (count < 0) throw new ArgumentOutOfRangeException(nameof(count));
  231. if (offset < 0) throw new ArgumentOutOfRangeException(nameof(count));
  232. if (VoiceSocket.Server == null) return; //Has been closed
  233. if (count == 0) return;
  234. VoiceSocket.SendPCMFrames(data, offset, count);
  235. }
  236. public void Clear()
  237. {
  238. if (VoiceSocket.Server == null) return; //Has been closed
  239. VoiceSocket.ClearPCMFrames();
  240. }
  241. public void Wait()
  242. {
  243. if (VoiceSocket.Server == null) return; //Has been closed
  244. VoiceSocket.WaitForQueue();
  245. }
  246. public void SendVoiceUpdate(ulong? serverId, ulong? channelId)
  247. {
  248. GatewaySocket.SendUpdateVoice(serverId, channelId,
  249. (Service.Config.Mode | AudioMode.Outgoing) == 0,
  250. (Service.Config.Mode | AudioMode.Incoming) == 0);
  251. }
  252. }
  253. }