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

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