-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
LavalinkPlayer.cs
612 lines (536 loc) · 24.2 KB
/
LavalinkPlayer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
/*
* File: LavalinkPlayer.cs
* Author: Angelo Breuer
*
* The MIT License (MIT)
*
* Copyright (c) Angelo Breuer 2020
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace Lavalink4NET.Player
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Events;
using Lavalink4NET.Payloads.Events;
using Lavalink4NET.Payloads.Node;
using Lavalink4NET.Payloads.Player;
/// <summary>
/// Controls a remote Lavalink Audio Player.
/// </summary>
public class LavalinkPlayer : IDisposable
{
internal VoiceServer? _voiceServer;
internal VoiceState? _voiceState;
private DateTimeOffset _lastPositionUpdate;
private TimeSpan _position;
/// <summary>
/// Initializes a new instance of the <see cref="LavalinkPlayer"/> class.
/// </summary>
public LavalinkPlayer()
{
_lastPositionUpdate = DateTimeOffset.UtcNow;
_position = TimeSpan.Zero;
}
/// <summary>
/// Gets the default equalizer bands. (All 15 [0-14] equalizer bands set to zero gain)
/// </summary>
public static IReadOnlyCollection<EqualizerBand> DefaultEqualizer { get; }
= Enumerable.Range(0, 15).Select(s => new EqualizerBand(s, 0)).ToList().AsReadOnly();
/// <summary>
/// Gets the discord client wrapper.
/// </summary>
public IDiscordClientWrapper Client { get; private set; } = null!; // Lazy-initialized
/// <summary>
/// Gets the track that is currently playing.
/// </summary>
public LavalinkTrack? CurrentTrack { get; private set; }
/// <summary>
/// Gets the identifier snowflake value of the guild the player is for.
/// </summary>
public ulong GuildId { get; private set; }
/// <summary>
/// Gets the current player state.
/// </summary>
public PlayerState State { get; private set; }
= PlayerState.NotConnected;
/// <summary>
/// Gets the current track position.
/// </summary>
public TimeSpan TrackPosition => CurrentTrack is null ? TimeSpan.Zero :
DateTimeOffset.UtcNow - _lastPositionUpdate + _position;
/// <summary>
/// Gets the voice channel id the player is connected to.
/// </summary>
public ulong? VoiceChannelId { get; private set; }
/// <summary>
/// Gets the current player volume.
/// </summary>
public float Volume { get; private set; } = 1f;
/// <summary>
/// Gets or sets the reason why the player disconnected.
/// </summary>
internal PlayerDisconnectCause DisconnectCause { get; set; }
/// <summary>
/// Gets the communication lavalink socket.
/// </summary>
internal LavalinkSocket LavalinkSocket { get; set; } = null!; // Lazy-initialized
/// <summary>
/// Gets or sets a value indicating whether the player should stop after the track
/// finished playing.
/// </summary>
protected bool DisconnectOnStop { get; set; }
/// <summary>
/// Joins the voice channel specified by <paramref name="voiceChannelId"/> asynchronously.
/// </summary>
/// <param name="voiceChannelId">the voice channel identifier to join</param>
/// <param name="selfDeaf">a value indicating whether the bot user should be self deafened</param>
/// <param name="selfMute">a value indicating whether the bot user should be self muted</param>
/// <returns>a task that represents the asynchronous operation</returns>
public virtual async Task ConnectAsync(ulong voiceChannelId, bool selfDeaf = false, bool selfMute = false)
{
await Client.SendVoiceUpdateAsync(GuildId, voiceChannelId, selfDeaf, selfMute);
VoiceChannelId = voiceChannelId;
State = PlayerState.NotPlaying;
CurrentTrack = null;
}
/// <summary>
/// Destroys the player asynchronously.
/// </summary>
/// <returns>a task that represents the asynchronous operation</returns>
public async Task DestroyAsync()
{
EnsureNotDestroyed();
// destroy player
State = PlayerState.Destroyed;
// send destroy payload
await LavalinkSocket.SendPayloadAsync(new PlayerDestroyPayload(GuildId));
}
/// <summary>
/// Disconnects the player asynchronously.
/// </summary>
/// <returns>a task that represents the asynchronous operation</returns>
/// <exception cref="InvalidOperationException">
/// thrown if the player is not connected to a voice channel
/// </exception>
public virtual Task DisconnectAsync()
{
EnsureConnected();
return DisconnectAsync(PlayerDisconnectCause.Stop);
}
/// <summary>
/// Disposes the player.
/// </summary>
public virtual void Dispose()
{
if (State == PlayerState.Destroyed)
{
return;
}
// Disconnect from voice channel and send destroy player payload to the lavalink node
DisconnectAsync(PlayerDisconnectCause.Dispose).Wait();
DestroyAsync().Wait();
}
/// <summary>
/// Asynchronously triggered when the player has connected to a voice channel.
/// </summary>
/// <param name="voiceServer">the voice server connected to</param>
/// <param name="voiceState">the voice state</param>
/// <returns>a task that represents the asynchronous operation</returns>
public virtual Task OnConnectedAsync(VoiceServer voiceServer, VoiceState voiceState)
=> Task.CompletedTask;
/// <summary>
/// Asynchronously triggered when a track ends.
/// </summary>
/// <remarks>
/// When overriding this method without supering / base calling it, the disconnect on
/// stop function will be prevent.
/// </remarks>
/// <param name="eventArgs">the track event arguments</param>
/// <returns>a task that represents the asynchronous operation</returns>
public virtual Task OnTrackEndAsync(TrackEndEventArgs eventArgs)
{
if (DisconnectOnStop)
{
return DisconnectAsync();
}
else
{
// The track ended, set to not playing
State = PlayerState.NotPlaying;
CurrentTrack = null;
}
return Task.CompletedTask;
}
/// <summary>
/// Asynchronously triggered when an exception occurred while playing a track.
/// </summary>
/// <param name="eventArgs">the track event arguments</param>
/// <returns>a task that represents the asynchronous operation</returns>
public virtual Task OnTrackExceptionAsync(TrackExceptionEventArgs eventArgs)
=> Task.CompletedTask;
/// <summary>
/// Asynchronously triggered when a track started.
/// </summary>
/// <param name="eventArgs">the track event arguments</param>
/// <returns>a task that represents the asynchronous operation</returns>
public virtual Task OnTrackStartedAsync(TrackStartedEventArgs eventArgs)
=> Task.CompletedTask;
/// <summary>
/// Asynchronously triggered when a track got stuck.
/// </summary>
/// <param name="eventArgs">the track event arguments</param>
/// <returns>a task that represents the asynchronous operation</returns>
public virtual Task OnTrackStuckAsync(TrackStuckEventArgs eventArgs)
=> Task.CompletedTask;
/// <summary>
/// Pauses the current playing track asynchronously.
/// </summary>
/// <returns>a task that represents the asynchronous operation</returns>
/// <exception cref="InvalidOperationException">
/// thrown if the current playing track is already paused.
/// </exception>
/// <exception cref="InvalidOperationException">
/// thrown if the player is not connected to a voice channel
/// </exception>
/// <exception cref="InvalidOperationException">thrown if the player is destroyed</exception>
public virtual async Task PauseAsync()
{
EnsureNotDestroyed();
EnsureConnected();
if (State != PlayerState.Playing)
{
throw new InvalidOperationException("The current playing track is not playing.");
}
await LavalinkSocket.SendPayloadAsync(new PlayerPausePayload(GuildId, true));
State = PlayerState.Paused;
}
/// <summary>
/// Plays the specified <paramref name="track"/> asynchronously.
/// </summary>
/// <param name="track">the track to play</param>
/// <param name="startTime">the track start position</param>
/// <param name="endTime">the track end position</param>
/// <param name="noReplace">
/// a value indicating whether the track play should be ignored if the same track is
/// currently playing
/// </param>
/// <returns>a task that represents the asynchronous operation</returns>
/// <exception cref="InvalidOperationException">
/// thrown if the player is not connected to a voice channel
/// </exception>
/// <exception cref="InvalidOperationException">thrown if the player is destroyed</exception>
public virtual async Task PlayAsync(LavalinkTrack track, TimeSpan? startTime = null,
TimeSpan? endTime = null, bool noReplace = false)
{
EnsureNotDestroyed();
EnsureConnected();
CurrentTrack = track ?? throw new ArgumentNullException(nameof(track));
startTime ??= track.Position;
await LavalinkSocket.SendPayloadAsync(new PlayerPlayPayload(GuildId, track.Identifier,
startTime, endTime, noReplace));
State = PlayerState.Playing;
}
/// <summary>
/// Replays the current track asynchronously.
/// </summary>
/// <returns>a task that represents the asynchronous operation</returns>
/// <exception cref="InvalidOperationException">thrown if the player is destroyed</exception>
/// <exception cref="InvalidOperationException">
/// thrown if the player is not connected to a voice channel
/// </exception>
public virtual Task ReplayAsync()
{
EnsureNotDestroyed();
EnsureConnected();
if (CurrentTrack is null || State == PlayerState.NotPlaying)
{
throw new InvalidOperationException("No track is playing.");
}
return PlayAsync(CurrentTrack, startTime: TimeSpan.Zero);
}
/// <summary>
/// Resumes the current playing track asynchronously.
/// </summary>
/// <returns>a task that represents the asynchronous operation</returns>
/// <exception cref="InvalidOperationException">
/// thrown if the player is not connected to a voice channel
/// </exception>
/// <exception cref="InvalidOperationException">
/// thrown if the current playing track is not paused
/// </exception>
/// <exception cref="InvalidOperationException">thrown if the player is destroyed</exception>
public virtual async Task ResumeAsync()
{
EnsureNotDestroyed();
EnsureConnected();
if (State != PlayerState.Paused)
{
throw new InvalidOperationException("There is no track paused.");
}
await LavalinkSocket.SendPayloadAsync(new PlayerPausePayload(GuildId, false));
State = PlayerState.Playing;
}
/// <summary>
/// Seeks the current playing track asynchronously.
/// </summary>
/// <returns>a task that represents the asynchronous operation</returns>
/// <exception cref="InvalidOperationException">
/// thrown if the player is not connected to a voice channel
/// </exception>
/// <exception cref="NotSupportedException">
/// thrown if the current playing track does not support seeking.
/// </exception>
/// <exception cref="InvalidOperationException">thrown if the player is destroyed</exception>
public virtual Task SeekPositionAsync(TimeSpan position)
{
EnsureNotDestroyed();
EnsureConnected();
if (State != PlayerState.Paused && State != PlayerState.Playing)
{
throw new InvalidOperationException("There is no track paused or playing.");
}
return LavalinkSocket.SendPayloadAsync(new PlayerSeekPayload(GuildId, position));
}
/// <summary>
/// Updates the player volume asynchronously.
/// </summary>
/// <param name="volume">the player volume (0f - 10f)</param>
/// <param name="normalize">
/// a value indicating whether if the <paramref name="volume"/> is out of range (0f -
/// 10f) it should be normalized in its range. For example 11f will be mapped to 10f and
/// -20f to 0f.
/// </param>
/// <returns>a task that represents the asynchronous operation</returns>
/// <exception cref="InvalidOperationException">
/// thrown if the player is not connected to a voice channel
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// thrown if the specified <paramref name="volume"/> is out of range (0f - 10f)
/// </exception>
/// <exception cref="InvalidOperationException">thrown if the player is destroyed</exception>
public virtual async Task SetVolumeAsync(float volume = 1f, bool normalize = false)
{
EnsureNotDestroyed();
EnsureConnected();
if (volume > 10f || volume < 0f)
{
if (!normalize)
{
throw new ArgumentOutOfRangeException(nameof(volume), volume, "Volume is out of range (0f - 10f)");
}
// bring the values into range (0f - 10f)
volume = Math.Max(0f, volume);
volume = Math.Min(10f, volume);
}
// check if the volume is already the same as wanted
if (Volume == volume)
{
return;
}
var payload = new PlayerVolumePayload(GuildId, (int)(volume * 100));
await LavalinkSocket.SendPayloadAsync(payload);
Volume = volume;
}
/// <summary>
/// Stops playing the current track asynchronously.
/// </summary>
/// <param name="disconnect">
/// a value indicating whether the connection to the voice server should be closed
/// </param>
/// <returns>a task that represents the asynchronous operation</returns>
/// <exception cref="InvalidOperationException">
/// thrown if the player is not connected to a voice channel
/// </exception>
/// <exception cref="InvalidOperationException">thrown if the player is destroyed</exception>
public virtual async Task StopAsync(bool disconnect = false)
{
EnsureNotDestroyed();
EnsureConnected();
await LavalinkSocket.SendPayloadAsync(new PlayerStopPayload(GuildId));
if (disconnect)
{
await DisconnectAsync(PlayerDisconnectCause.Stop);
}
State = PlayerState.NotPlaying;
CurrentTrack = null;
}
/// <summary>
/// Updates the player equalizer asynchronously.
/// </summary>
/// <param name="bands">the bands</param>
/// <param name="reset">
/// a value indicating whether the equalizer bands should be overridden ( <see
/// langword="false"/>) or replaced ( <see langword="true"/>).
/// </param>
/// <returns>a task that represents the asynchronous operation</returns>
/// <exception cref="InvalidOperationException">thrown if the player is destroyed</exception>
public virtual Task UpdateEqualizerAsync(IEnumerable<EqualizerBand> bands, bool reset = true)
{
EnsureNotDestroyed();
if (reset)
{
bands = bands.Union(DefaultEqualizer, new EqualizerBandComparer());
}
return LavalinkSocket.SendPayloadAsync(new PlayerEqualizerPayload(GuildId, bands.ToArray()));
}
/// <summary>
/// Initializes a new instance of a player.
/// </summary>
/// <param name="playerFactory">the player factory</param>
/// <param name="socket">the lavalink socket</param>
/// <param name="client">the discord client</param>
/// <param name="guildId">the identifier of the guild that is controlled by the player</param>
/// <param name="disconnectOnStop">
/// a value indicating whether the player should stop after the track finished playing
/// </param>
/// <exception cref="ArgumentNullException">
/// thrown if the specified <paramref name="playerFactory"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// thrown if the specified <paramref name="socket"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// thrown if the specified <paramref name="client"/> is <see langword="null"/>.
/// </exception>
internal static T CreatePlayer<T>(
PlayerFactory<T> playerFactory, LavalinkSocket socket, IDiscordClientWrapper client,
ulong guildId, bool disconnectOnStop) where T : LavalinkPlayer
{
if (playerFactory is null)
{
throw new ArgumentNullException(nameof(playerFactory));
}
var player = playerFactory();
player.LavalinkSocket = socket ?? throw new ArgumentNullException(nameof(socket));
player.Client = client ?? throw new ArgumentNullException(nameof(client));
player.GuildId = guildId;
player.DisconnectOnStop = disconnectOnStop;
return player;
}
/// <summary>
/// Disconnects the player asynchronously.
/// </summary>
/// <returns>a task that represents the asynchronous operation</returns>
internal async Task DisconnectAsync(PlayerDisconnectCause disconnectCause)
{
if (State == PlayerState.NotConnected)
{
return;
}
// keep old channel in memory
var channel = VoiceChannelId;
// disconnect from channel
await Client.SendVoiceUpdateAsync(GuildId, null);
VoiceChannelId = null;
State = PlayerState.NotConnected;
// only trigger event if disconnected from a channel
if (channel.HasValue)
{
// notify disconnect
await LavalinkSocket.NotifyDisconnectAsync(
new PlayerDisconnectedEventArgs(this, channel.Value, disconnectCause));
}
}
/// <summary>
/// Updates the voice server and sends the data to the Lavalink Node if the voice state
/// is also provided.
/// </summary>
/// <param name="voiceServer">the voice server data</param>
/// <returns>a task that represents the asynchronous operation</returns>
/// <exception cref="InvalidOperationException">thrown if the player is destroyed</exception>
internal Task UpdateAsync(VoiceServer voiceServer)
{
EnsureNotDestroyed();
_voiceServer = voiceServer;
return UpdateAsync();
}
/// <summary>
/// Updates the voice state and sends the data to the Lavalink Node if the voice server
/// is also provided.
/// </summary>
/// <param name="voiceState">the voice state data</param>
/// <returns>a task that represents the asynchronous operation</returns>
/// <exception cref="InvalidOperationException">thrown if the player is destroyed</exception>
internal Task UpdateAsync(VoiceState voiceState)
{
EnsureNotDestroyed();
_voiceState = voiceState;
VoiceChannelId = voiceState.VoiceChannelId;
return UpdateAsync();
}
/// <summary>
/// Sends the voice state and server data to the Lavalink Node if both is provided.
/// </summary>
/// <returns>a task that represents the asynchronous operation</returns>
internal async Task UpdateAsync()
{
if (_voiceServer is null || _voiceState is null)
{
// voice state or server is missing
return;
}
// send voice update payload
await LavalinkSocket.SendPayloadAsync(new VoiceUpdatePayload(_voiceState.GuildId,
_voiceState.VoiceSessionId, new VoiceServerUpdateEvent(_voiceServer)));
if (State == PlayerState.NotConnected || State == PlayerState.Destroyed)
{
// set initial player state to connected, if player was not connected or destroyed,
// see: https://github.com/angelobreuer/Lavalink4NET/issues/28
State = PlayerState.NotPlaying;
CurrentTrack = null;
}
// trigger event
await OnConnectedAsync(_voiceServer, _voiceState);
}
internal void UpdateTrackPosition(DateTimeOffset positionUpdateTime, TimeSpan position)
{
_lastPositionUpdate = positionUpdateTime;
_position = position;
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> when the player is not connected
/// to a voice channel.
/// </summary>
/// <exception cref="InvalidOperationException">
/// thrown if the player is not connected to a voice channel
/// </exception>
protected void EnsureConnected()
{
if (State == PlayerState.NotConnected)
{
throw new InvalidOperationException("The player is not connected to a voice channel.");
}
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> when the player is destroyed.
/// </summary>
/// <exception cref="InvalidOperationException">thrown if the player is destroyed</exception>
protected void EnsureNotDestroyed()
{
if (State == PlayerState.Destroyed)
{
throw new InvalidOperationException("The player is destroyed.");
}
}
}
}