Esempio n. 1
0
        public async Task StopCmd()
        {
            LavalinkPlayer player = _lavaManager.GetPlayer(Context.Guild.Id);
            await player.StopAsync();

            await _lavaManager.LeaveAsync(Context.Guild.Id);
        }
Esempio n. 2
0
        internal static ValueTask SendAsync(LavalinkPlayer player)
        {
            using var payloadWriter = new PayloadWriter(player);
            var writer = payloadWriter.Writer;

            payloadWriter.WriteStartPayload("equalizer");

            writer.WritePropertyName("bands");
            writer.WriteStartArray();
            var bands         = player.Bands.Bands;
            var previousBands = player.Bands.PreviousBands;

            for (int i = 0; i < 15; i++)
            {
                float gain = bands[i];
                if (previousBands[i] != gain)
                {
                    previousBands[i] = gain;

                    writer.WriteStartObject();
                    writer.WriteNumber("band", i);
                    writer.WriteNumber("gain", gain);
                    writer.WriteEndObject();
                }
            }
            writer.WriteEndArray();

            return(payloadWriter.SendAsync());
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="PlayerTrackingStatusUpdateEventArgs"/> class.
 /// </summary>
 /// <param name="audioService">the audio service</param>
 /// <param name="player">the affected player (may be <see langword="null"/>)</param>
 /// <param name="trackingStatus">the new tracking status of the player</param>
 /// <exception cref="ArgumentNullException">
 ///     thrown if the specified <paramref name="audioService"/> is <see langword="null"/>.
 /// </exception>
 public PlayerTrackingStatusUpdateEventArgs(IAudioService audioService,
                                            LavalinkPlayer player, InactivityTrackingStatus trackingStatus)
 {
     AudioService   = audioService ?? throw new ArgumentNullException(nameof(audioService));
     Player         = player;
     TrackingStatus = trackingStatus;
 }
 public static async Task LavalinkManager_TrackEnd(LavalinkPlayer arg1, LavalinkTrack arg2, string arg3)
 {
     if (arg3 == "FINISHED")
     {
         await RemoveAndPlay(arg1, arg2);
     }
     return;
 }
        /// <summary>
        ///     Removes the specified <paramref name="player"/> from the inactivity tracking list asynchronously.
        /// </summary>
        /// <param name="player">the player to remove</param>
        /// <returns>
        ///     a task that represents the asynchronous operation. The task result is a value
        ///     indicating whether the player was removed from the tracking list.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     thrown if the specified <paramref name="player"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ObjectDisposedException">thrown if the instance is disposed</exception>
        public Task <bool> UntrackPlayerAsync(LavalinkPlayer player)
        {
            if (player is null)
            {
                throw new ArgumentNullException(nameof(player));
            }

            return(UntrackPlayerAsync(player.GuildId));
        }
Esempio n. 6
0
        internal static ValueTask SendAsync(LavalinkPlayer player)
        {
            using var payloadWriter = new PayloadWriter(player);
            var writer = payloadWriter.Writer;

            payloadWriter.WriteStartPayload("destroy");

            return(payloadWriter.SendAsync());
        }
Esempio n. 7
0
        internal PayloadWriter(ClientWebSocket webSocket, int bufferSize = 1024)
        {
            _player    = null;
            _webSocket = webSocket;
            _buffer    = ArrayPool <byte> .Shared.Rent(bufferSize);

            _stream = new MemoryStream(_buffer, 0, bufferSize);
            Writer  = new Utf8JsonWriter(_stream);
        }
        public static async Task RemoveAndPlay(LavalinkPlayer player, LavalinkTrack track)
        {
            var audioQueue = AudioQueues.GetAudioQueue(player.VoiceChannel.Guild as SocketGuild);

            RemoveTrack(audioQueue, track);
            await player.StopAsync();

            await PlayNextAfterRemove(audioQueue, player);
        }
Esempio n. 9
0
        internal static ValueTask SendAsync(LavalinkPlayer player, ushort volume)
        {
            using var payloadWriter = new PayloadWriter(player);
            var writer = payloadWriter.Writer;

            payloadWriter.WriteStartPayload("volume");

            writer.WriteNumber("volume", volume);

            return(payloadWriter.SendAsync());
        }
Esempio n. 10
0
        public static async Task StopAsync(ulong guildId)
        {
            LavalinkPlayer player = lavalinkManager.GetPlayer(guildId);

            if (player.Playing == false)
            {
                return;
            }

            await player.PauseAsync();
        }
Esempio n. 11
0
        internal static ValueTask SendAsync(LavalinkPlayer player, uint positionMs)
        {
            using var payloadWriter = new PayloadWriter(player);
            var writer = payloadWriter.Writer;

            payloadWriter.WriteStartPayload("seek");

            writer.WriteNumber("position", positionMs);

            return(payloadWriter.SendAsync());
        }
Esempio n. 12
0
        internal static ValueTask SendAsync(LavalinkPlayer player, bool pause)
        {
            using var payloadWriter = new PayloadWriter(player);
            var writer = payloadWriter.Writer;

            payloadWriter.WriteStartPayload("pause");

            writer.WriteBoolean("pause", pause);

            return(payloadWriter.SendAsync());
        }
        private static async Task PlayNextAfterRemove(AudioQueue audioQueue, LavalinkPlayer player)
        {
            if (audioQueue.Queue.ElementAtOrDefault(0) != null)
            {
                audioQueue.PlayingTrackIndex = 0;
                AudioQueues.SaveQueues();
                LavalinkTrack track = audioQueue.Queue.ElementAtOrDefault(0);
                await player.PlayAsync(track);
            }

            await Task.CompletedTask;
        }
Esempio n. 14
0
        public async Task YouTubeCmd([Remainder] string query)
        {
            LavalinkPlayer player = _lavaManager.GetPlayer(Context.Guild.Id) ?? await _lavaManager.JoinAsync((Context.User as IVoiceState).VoiceChannel);

            LoadTracksResponse r = await _lavaManager.GetTracksAsync($"ytsearch:{query}");

            LavalinkTrack tr = r.Tracks.First();

            await player.PlayAsync(tr);

            await ReplyAsync("", embed : GetTrackInfoEmbed(tr, Context.User));
        }
Esempio n. 15
0
        public static async Task LeaveAsync(SocketGuild guild)
        {
            LavalinkPlayer player = lavalinkManager.GetPlayer(guild.Id);

            if (player == null)
            {
                return;
            }

            await lavalinkManager.LeaveAsync(guild.Id);

            await RemoveAllTracks(guild);
        }
Esempio n. 16
0
        public static async Task PlayAsync(SocketCommandContext context, string song, int choose, YoutubeVideo video = null)
        {
            // Create used objects
            SocketGuild           guild        = context.Guild;
            SocketUserMessage     message      = context.Message;
            IVoiceChannel         voiceChannel = (context.User as IVoiceState).VoiceChannel;
            ISocketMessageChannel channel      = context.Channel;
            Utilities             utilities    = new Utilities(guild);

            // Checking if voice channel is null (and sending an error message)
            // If not, creating or getting a lavalink player
            // Checking if a given string is empty (if true, and there is a song in queue that is stopped, resuming it
            if (await VoiceChannelIsNull(channel, voiceChannel, utilities) is true)
            {
                return;
            }
            LavalinkPlayer player = lavalinkManager.GetPlayer(guild.Id) ?? await lavalinkManager.JoinAsync(voiceChannel);

            var audioQueue = AudioQueues.GetAudioQueue(guild);

            if (await SongIsEmpty(channel, utilities, player, audioQueue, song) is true)
            {
                return;
            }

            LoadTracksResponse response = await lavalinkManager.GetTracksAsync(song);

            LavalinkTrack track = response.Tracks.First();

            // Maximum songs in queue is 50
            if (await QueueIsFull(channel, utilities, audioQueue.Queue.Count) is true)
            {
                return;
            }

            // Adding a track to queue
            audioQueue.Queue = AudioQueues.GetOrCreateGuildQueue(track, audioQueue);

            // A check if a song is first in the queue, or if it's been added
            string songAlert = "PLAY_ADDED_SONG";

            if (await SongIsFirst(player, audioQueue, track, video, context, songAlert, choose) is false)
            {
                return;
            }
            // If a user gives a link to a youtube video, we don't need to send song info
            if (choose != -1)
            {
                await SongInfo(channel, message, video, choose, songAlert);
            }
        }
        /// <summary>
        ///     Gets a value indicating whether the specified <paramref name="player"/> is inactive asynchronously.
        /// </summary>
        /// <param name="player">the player to check</param>
        /// <returns>
        ///     a task that represents the asynchronous operation. The task result is a value
        ///     indicating whether the specified <paramref name="player"/> is inactive.
        /// </returns>
        protected virtual async Task <bool> IsInactiveAsync(LavalinkPlayer player)
        {
            // iterate through the trackers
            foreach (var tracker in Trackers)
            {
                // check if the player is inactivity
                if (await tracker(player, _clientWrapper))
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 18
0
        private async Task TrackEnd(LavalinkPlayer player, LavalinkTrack track, string type)
        {
            if (type == "STOPPED")
            {
                return;
            }

            try
            {
                await player.PlayAsync(player.VoiceChannel.Guild.Id.PopTrack());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
        /// <summary>
        ///     Gets the tracking status of the specified <paramref name="player"/>.
        /// </summary>
        /// <param name="player">the player</param>
        /// <returns>the inactivity tracking status of the player</returns>
        public InactivityTrackingStatus GetStatus(LavalinkPlayer player)
        {
            if (!_players.TryGetValue(player.GuildId, out var dateTimeOffset))
            {
                // there are no tracking entries for the player
                return(InactivityTrackingStatus.Untracked);
            }

            // the player has exceeded the stop delay
            if (DateTimeOffset.UtcNow > dateTimeOffset)
            {
                return(InactivityTrackingStatus.Inactive);
            }

            //player is tracked for inactivity, but not removed
            return(InactivityTrackingStatus.Tracked);
        }
Esempio n. 20
0
        internal static ValueTask SendAsync(LavalinkPlayer player, VoiceServerUpdatedEventArgs e)
        {
            using var payloadWriter = new PayloadWriter(player);
            var writer = payloadWriter.Writer;

            payloadWriter.WriteStartPayload("voiceUpdate");

            writer.WriteString("sessionId", player.SessionId);

            writer.WriteStartObject("event");
            writer.WriteString("token", e.Token);
            writer.WriteString("guild_id", player.GuildIdStr);
            writer.WriteString("endpoint", e.Endpoint);
            writer.WriteEndObject();

            return(payloadWriter.SendAsync());
        }
        /// <summary>
        ///     Removes the specified <paramref name="player"/> from the inactivity tracking list asynchronously.
        /// </summary>
        /// <param name="player">the player to remove</param>
        /// <returns>
        ///     a task that represents the asynchronous operation. The task result is a value
        ///     indicating whether the player was removed from the tracking list.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     thrown if the specified <paramref name="player"/> is <see langword="null"/>.
        /// </exception>
        public async Task <bool> UntrackPlayerAsync(LavalinkPlayer player)
        {
            if (player is null)
            {
                throw new ArgumentNullException(nameof(player));
            }

            if (!_players.Remove(player.GuildId))
            {
                // player was not tracked
                return(false);
            }

            // trigger event
            await OnPlayerTrackingStatusUpdated(new PlayerTrackingStatusUpdateEventArgs(_audioService,
                                                                                        player, InactivityTrackingStatus.Untracked));

            return(true);
        }
Esempio n. 22
0
        internal static ValueTask SendAsync(LavalinkPlayer player, LavalinkTrack track, TimeSpan startTime = default, TimeSpan endTime = default, bool noReplace = false)
        {
            using var payloadWriter = new PayloadWriter(player);
            var writer = payloadWriter.Writer;

            payloadWriter.WriteStartPayload("play");

            writer.WriteString("track", track.Hash);
            if (startTime != default)
            {
                writer.WriteString("startTime", ((int)startTime.TotalMilliseconds).ToString());
            }
            if (endTime != default)
            {
                writer.WriteString("endTime", ((int)endTime.TotalMilliseconds).ToString());
            }
            writer.WriteBoolean("noReplace", noReplace);

            return(payloadWriter.SendAsync());
        }
Esempio n. 23
0
        /// <inheritdoc/>
        /// <exception cref="ObjectDisposedException">thrown if the instance is disposed</exception>
        public async Task <TPlayer> JoinAsync <TPlayer>(
            PlayerFactory <TPlayer> playerFactory, ulong guildId, ulong voiceChannelId, bool selfDeaf = false,
            bool selfMute = false) where TPlayer : LavalinkPlayer
        {
            EnsureNotDisposed();

            var player = GetPlayer <TPlayer>(guildId);

            if (player is null)
            {
                Players[guildId] = player = LavalinkPlayer.CreatePlayer(
                    playerFactory, this, _discordClient, guildId, _disconnectOnStop);
            }

            if (!player.VoiceChannelId.HasValue || player.VoiceChannelId != voiceChannelId)
            {
                await player.ConnectAsync(voiceChannelId, selfDeaf, selfMute);
            }

            return(player);
        }
Esempio n. 24
0
        /// <summary>
        ///     Moves the specified <paramref name="player"/> to the specified <paramref
        ///     name="node"/> asynchronously (while keeping its data and the same instance of the player).
        /// </summary>
        /// <param name="player">the player to move</param>
        /// <param name="node">the node to move the player to</param>
        /// <returns>a task that represents the asynchronous operation.</returns>
        /// <exception cref="ArgumentNullException">
        ///     thrown if the specified <paramref name="player"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     thrown if the specified <paramref name="node"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     thrown if the specified <paramref name="node"/> is the same as the player node.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     thrown if the specified <paramref name="player"/> is already served by the specified
        ///     <paramref name="node"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///     thrown if the specified <paramref name="node"/> does not serve the specified
        ///     <paramref name="player"/>.
        /// </exception>
        /// <exception cref="ObjectDisposedException">thrown if the instance is disposed</exception>
        public async Task MovePlayerAsync(LavalinkPlayer player, LavalinkNode node)
        {
            EnsureNotDisposed();

            if (player is null)
            {
                throw new ArgumentNullException(nameof(player), "The player to move is null.");
            }

            if (node is null)
            {
                throw new ArgumentNullException(nameof(node), "The specified target node is null.");
            }

            if (node == this)
            {
                throw new ArgumentException("Can not move the player to the same node.", nameof(node));
            }

            if (player.LavalinkSocket == node)
            {
                throw new ArgumentException("The specified player is already served by the targeted node.");
            }

            if (!Players.Contains(new KeyValuePair <ulong, LavalinkPlayer>(player.GuildId, player)))
            {
                throw new ArgumentException("The specified player is not a player from the current node.", nameof(player));
            }

            // remove the player from the current node
            Players.Remove(player.GuildId);

            // move player
            await MovePlayerInternalAsync(player, node);

            // log
            Logger?.Log(this, string.Format("Moved player for guild {0} to new node.", player.GuildId), LogLevel.Debug);
        }
Esempio n. 25
0
        private async Task MovePlayerInternalAsync(LavalinkPlayer player, LavalinkNode node)
        {
            var wasPlaying = player.State == PlayerState.Playing;

            // destroy (NOT DISCONNECT) the player
            await player.DestroyAsync();

            // update the communication node
            player.LavalinkSocket = node;

            // resend voice update to the new node
            await player.UpdateAsync();

            // play track if one is playing
            if (wasPlaying)
            {
                // restart track
                await player.PlayAsync(player.CurrentTrack);
            }

            // add player to the new node
            node.Players.TryAdd(player.GuildId, player);
        }
Esempio n. 26
0
        private async Task MovePlayerToNewNodeAsync(LavalinkNode sourceNode, LavalinkPlayer player)
        {
            if (player is null)
            {
                throw new ArgumentNullException(nameof(player));
            }

            if (!Nodes.Any(s => s.IsConnected))
            {
                _logger.Log(this, $"(Stay-Online) No node available for player {player.GuildId}, dropping player...");

                // invoke event
                await OnPlayerMovedAsync(new PlayerMovedEventArgs(sourceNode, null, player));

                return;
            }

            // move node
            var targetNode = GetPreferredNode();
            await sourceNode.MovePlayerAsync(player, targetNode);

            // invoke event
            await OnPlayerMovedAsync(new PlayerMovedEventArgs(sourceNode, targetNode, player));
        }
Esempio n. 27
0
        private static async Task <bool> SongIsFirst(LavalinkPlayer player, AudioQueue audioQueue, LavalinkTrack track, YoutubeVideo video, SocketCommandContext context, string songAlert, int choose)
        {
            ISocketMessageChannel channel     = context.Channel;
            SocketUserMessage     message     = context.Message;
            LavalinkTrack         secondTrack = audioQueue.Queue.ElementAtOrDefault(1);

            if (secondTrack == null)
            {
                audioQueue.PlayingTrackIndex = 0;
                AudioQueues.SaveQueues();

                await player.PlayAsync(track);

                if (video != null)
                {
                    songAlert = "PLAY_PLAYED_SONG";
                    await SongInfo(channel, message, video, choose, songAlert);
                }

                return(true);
            }

            return(false);
        }
Esempio n. 28
0
 public async Task ResumeCmd()
 {
     LavalinkPlayer player = _lavaManager.GetPlayer(Context.Guild.Id);
     await player.ResumeAsync();
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="PlayerDisconnectedEventArgs"/> class.
 /// </summary>
 /// <param name="player">the affected player</param>
 /// <param name="voiceChannelId">
 ///     the snowflake identifier of the voice channel disconnected from
 /// </param>
 /// <param name="disconnectCause">the reason why the player disconnected</param>
 /// <exception cref="ArgumentNullException">
 ///     thrown if the specified <paramref name="player"/> is <see langword="null"/>.
 /// </exception>
 public PlayerDisconnectedEventArgs(LavalinkPlayer player, ulong voiceChannelId, PlayerDisconnectCause disconnectCause) : base(player)
 {
     VoiceChannelId  = voiceChannelId;
     DisconnectCause = disconnectCause;
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="TrackStuckEventArgs"/> class.
 /// </summary>
 /// <param name="player">the affected player</param>
 /// <param name="trackIdentifier">the identifier of the affected track</param>
 /// <param name="threshold">the threshold in milliseconds</param>
 /// <exception cref="ArgumentNullException">
 ///     thrown if the specified <paramref name="player"/> is <see langword="null"/>.
 /// </exception>
 /// <exception cref="ArgumentNullException">
 ///     thrown if the specified <paramref name="trackIdentifier"/> is <see langword="null"/>.
 /// </exception>
 public TrackStuckEventArgs(LavalinkPlayer player, string trackIdentifier, long threshold)
     : base(player, trackIdentifier)
     => Threshold = threshold;