Compare commits

...

No commits in common. "v0.9.10" and "master" have entirely different histories.

42 changed files with 1434 additions and 317 deletions

View File

@ -1,9 +1,12 @@
using DSharpPlus.Entities;
using Microsoft.AspNetCore.Mvc;
using TomatenMusic;
using TomatenMusic.Music;
using TomatenMusic_Api;
using TomatenMusic_Api.Auth.Helpers;
using TomatenMusic_Api.Models;
using TomatenMusic_Api.Models.EventArgs;
using static TomatenMusic_Api.InProcessEventBus;
namespace TomatenMusic_Api.Controllers;
@ -54,8 +57,9 @@ public class PlayerController : ControllerBase
}
[HttpPost("connect")]
public async Task<IActionResult> PostConnection(ChannelConnectRequest request)
public async Task<IActionResult> PostConnect(ChannelConnectRequest request)
{
try
{
await _tomatenMusicDataService.GetGuildAsync(request.Guild_Id);
@ -85,8 +89,58 @@ public class PlayerController : ControllerBase
_eventBus.OnConnectRequestEvent(new InProcessEventBus.ChannelConnectEventArgs(request.Guild_Id, channel));
_eventBus.OnConnectRequestEvent(new ChannelConnectArgs(request.Guild_Id, channel));
return Ok();
}
[HttpPost("disconnect")]
public async Task<IActionResult> PostDisconnect(ChannelDisconnectRequest request)
{
try
{
await _tomatenMusicDataService.GetGuildAsync(request.GuildId);
}
catch (Exception ex)
{
return NotFound("That Guild was not found");
}
if (!await _tomatenMusicDataService.IsConnectedAsync(request.GuildId) == true)
return BadRequest("The Bot is not connected.");
_eventBus.OnDisconnectRequestEvent(new ChannelDisconnectArgs(request.GuildId));
return Ok();
}
[HttpPost("play")]
public async Task<IActionResult> PostPlay(TrackPlayRequest request)
{
try
{
await _tomatenMusicDataService.GetGuildAsync(request.GuildId);
}
catch (Exception ex)
{
return NotFound("That Guild was not found");
}
if (!await _tomatenMusicDataService.IsConnectedAsync(request.GuildId) == true)
return BadRequest("The Bot is not connected.");
MusicActionResponse response;
try
{
response = await _tomatenMusicDataService.TrackProvider.SearchAsync(request.TrackUri);
}catch (Exception ex)
{
return NotFound(ex.Message + "\n" + ex.StackTrace);
}
_eventBus.OnPlayRequestEvent(new TrackPlayArgs(response, request.GuildId, TimeSpan.FromSeconds(request.StartTimeSeconds), request.Now));
return Ok();
}
}

View File

@ -27,9 +27,9 @@ namespace TomatenMusic_Api.Models
Name = track.Title;
Platform = ctx.SpotifyIdentifier == null ? TrackPlatform.YOUTUBE : TrackPlatform.SPOTIFY;
YoutubeId = track.Identifier;
YoutubeId = track.TrackIdentifier;
SpotifyId = ctx.SpotifyIdentifier;
URL = ctx.YoutubeUri;
URL = new Uri(track.Source);
}
}

View File

@ -0,0 +1,7 @@
namespace TomatenMusic_Api.Models.EventArgs
{
public class ChannelDisconnectRequest
{
public ulong GuildId { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using DSharpPlus.Entities;
using Emzi0767.Utilities;
namespace TomatenMusic_Api.Models.EventArgs
{
public class ChannelConnectArgs : AsyncEventArgs
{
public ulong Guild_Id { get; set; }
public DiscordChannel Channel { get; set; }
public ChannelConnectArgs(ulong guild_Id, DiscordChannel channel)
{
Guild_Id = guild_Id;
Channel = channel;
}
}
}

View File

@ -0,0 +1,13 @@
using Emzi0767.Utilities;
namespace TomatenMusic_Api.Models.EventArgs
{
public class ChannelDisconnectArgs : AsyncEventArgs
{
public ulong GuildId { get; set; }
public ChannelDisconnectArgs(ulong guildId) { GuildId = guildId; }
}
}

View File

@ -0,0 +1,22 @@
using Emzi0767.Utilities;
using Lavalink4NET.Player;
using TomatenMusic.Music;
namespace TomatenMusic_Api.Models.EventArgs
{
public class TrackPlayArgs : AsyncEventArgs
{
public MusicActionResponse Response { get; set; }
public ulong GuildId { get; set; }
public TimeSpan StartTime { get; set; }
public bool Now { get; set; }
public TrackPlayArgs(MusicActionResponse response, ulong guildId, TimeSpan startTime, bool now)
{
Response = response;
GuildId = guildId;
StartTime = startTime;
Now = now;
}
}
}

View File

@ -0,0 +1,10 @@
namespace TomatenMusic_Api.Models
{
public class TrackPlayRequest
{
public ulong GuildId { get; set; }
public string TrackUri { get; set; }
public bool Now { get; set; }
public int StartTimeSeconds { get; set; }
}
}

View File

@ -2,29 +2,30 @@
using Emzi0767.Utilities;
using Microsoft.AspNetCore.Mvc;
using TomatenMusic_Api.Models;
using TomatenMusic_Api.Models.EventArgs;
namespace TomatenMusic_Api;
public class InProcessEventBus
{
public event AsyncEventHandler<InProcessEventBus, ChannelConnectEventArgs>? OnConnectRequest;
public event AsyncEventHandler<InProcessEventBus, ChannelConnectArgs>? OnConnectRequest;
public void OnConnectRequestEvent(ChannelConnectEventArgs e)
public event AsyncEventHandler<InProcessEventBus, ChannelDisconnectArgs>? OnDisconnectRequest;
public event AsyncEventHandler<InProcessEventBus, TrackPlayArgs> OnPlayRequest;
public void OnConnectRequestEvent(ChannelConnectArgs e)
{
_ = OnConnectRequest?.Invoke(this, e);
}
public class ChannelConnectEventArgs : AsyncEventArgs
{
public ulong Guild_Id { get; set; }
public void OnDisconnectRequestEvent(ChannelDisconnectArgs e)
{
_ = OnDisconnectRequest?.Invoke(this, e);
}
public DiscordChannel Channel { get; set; }
public ChannelConnectEventArgs(ulong guild_Id, DiscordChannel channel)
{
Guild_Id = guild_Id;
Channel = channel;
}
public void OnPlayRequestEvent(TrackPlayArgs e)
{
_ = OnPlayRequest?.Invoke(this, e);
}
}

View File

@ -11,12 +11,14 @@ namespace TomatenMusic_Api
public class TomatenMusicDataService : IHostedService
{
private ILogger<TomatenMusicDataService> _logger;
public IServiceProvider _serviceProvider { get; set; } = TomatenMusicBot.ServiceProvider;
private IServiceProvider _serviceProvider { get; set; } = TomatenMusicBot.ServiceProvider;
public IAudioService _audioService { get; set; }
public TrackProvider TrackProvider { get; set; }
public TomatenMusicDataService(ILogger<TomatenMusicDataService> logger)
{
_logger = logger;
_audioService = _serviceProvider.GetRequiredService<IAudioService>();
TrackProvider = _serviceProvider.GetRequiredService<TrackProvider>();
}
public async Task<PlayerConnectionInfo> GetConnectionInfoAsync(ulong guild_id)

View File

@ -2,6 +2,7 @@
using TomatenMusic;
using TomatenMusic.Music;
using TomatenMusic_Api.Models;
using TomatenMusic_Api.Models.EventArgs;
using static TomatenMusic_Api.InProcessEventBus;
namespace TomatenMusic_Api
@ -24,11 +25,48 @@ namespace TomatenMusic_Api
private void Initialize()
{
_inProcessEventBus.OnConnectRequest += _inProcessEventBus_OnConnectRequest;
_inProcessEventBus.OnDisconnectRequest += _inProcessEventBus_OnDisconnectRequest;
_inProcessEventBus.OnPlayRequest += _inProcessEventBus_OnPlayRequest;
}
private async Task _inProcessEventBus_OnConnectRequest(InProcessEventBus sender, ChannelConnectEventArgs e)
private async Task _inProcessEventBus_OnPlayRequest(InProcessEventBus sender, TrackPlayArgs e)
{
GuildPlayer player = _audioService.GetPlayer<GuildPlayer>(e.GuildId);
if (e.Response.Tracks != null && e.Response.Tracks.Any())
{
if (e.Now)
await player.PlayNowAsync(e.Response.Tracks);
else
await player.PlayItemAsync(e.Response.Tracks);
return;
}
if (e.Response.IsPlaylist)
{
if (e.Now)
await player.PlayNowAsync(e.Response.Playlist);
else
await player.PlayItemAsync(e.Response.Playlist);
}else
{
if (e.Now)
await player.PlayNowAsync(e.Response.Track, e.StartTime);
else
await player.PlayAsync(e.Response.Track, e.StartTime);
}
}
private async Task _inProcessEventBus_OnDisconnectRequest(InProcessEventBus sender, ChannelDisconnectArgs e)
{
GuildPlayer player = _audioService.GetPlayer<GuildPlayer>(e.GuildId);
player.DisconnectAsync();
}
private async Task _inProcessEventBus_OnConnectRequest(InProcessEventBus sender, ChannelConnectArgs e)
{
_logger.LogInformation("Channel Connected!");
GuildPlayer player = await _audioService.JoinAsync<GuildPlayer>(e.Guild_Id, e.Channel.Id, true);
}

View File

@ -5,10 +5,6 @@
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>TomatenMusic_Api</RootNamespace>
<RestoreAdditionalProjectSources>
https://api.nuget.org/v3/index.json;
https://nuget.emzi0767.com/api/v3/index.json
</RestoreAdditionalProjectSources>
</PropertyGroup>
<ItemGroup>

View File

@ -1,5 +1,5 @@
{
"TOKEN": "Bot_Token",
"TOKEN": "TOKEN",
"LavaLinkPassword": " ",
"SpotifyClientId": " ",
"SpotifyClientSecret": " ",

View File

@ -17,6 +17,7 @@ using TomatenMusic.Prompt.Option;
using System.Linq;
using Lavalink4NET;
using Lavalink4NET.Player;
using TomatenMusicCore.Prompt.Implementation;
namespace TomatenMusic.Commands
{
@ -104,18 +105,40 @@ namespace TomatenMusic.Commands
response = await _trackProvider.SearchAsync(query, true);
}catch (Exception e)
{
await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent($"❌ Search failed: ``{e.Message}``"));
await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent($"❌ Search failed: ``{e.Message}``, ```{e.StackTrace}```"));
return;
}
var prompt = new SongSelectorPrompt($"Search results for {query}", response.Tracks);
prompt.ConfirmCallback = async (tracks) =>
{
var selectPrompt = new SongListActionPrompt(tracks, ctx.Member, prompt);
await selectPrompt.UseAsync(prompt.Interaction, prompt.Message);
};
DiscordPromptBase prompt;
await prompt.UseAsync(ctx.Interaction, await ctx.GetOriginalResponseAsync());
if (!response.IsPlaylist && response.Tracks.Count() == 1)
{
var sPrompt = new SongActionPrompt(response.Tracks.First(), ctx.Member);
prompt = sPrompt;
}
else if (response.IsPlaylist)
{
var sPrompt = new PlaylistSongSelectorPrompt(response.Playlist);
sPrompt.ConfirmCallback = async (tracks) =>
{
var selectPrompt = new SongListActionPrompt(tracks, ctx.Member, sPrompt);
await selectPrompt.UseAsync(sPrompt.Interaction, sPrompt.Message);
};
prompt = sPrompt;
}
else
{
var sPrompt = new SongSelectorPrompt($"Search results for {query}", response.Tracks);
sPrompt.ConfirmCallback = async (tracks) =>
{
var selectPrompt = new SongListActionPrompt(tracks, ctx.Member, sPrompt);
await selectPrompt.UseAsync(sPrompt.Interaction, sPrompt.Message);
};
prompt = sPrompt;
}
await prompt.UseAsync(ctx.Interaction, await ctx.GetOriginalResponseAsync());
}
[SlashCommand("time", "Sets the playing position of the current Song.")]

View File

@ -12,6 +12,8 @@ using TomatenMusic.Commands.Checks;
using TomatenMusic.Music;
using TomatenMusic.Music.Entitites;
using TomatenMusic.Util;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
namespace TomatenMusic.Commands
{
@ -79,10 +81,10 @@ namespace TomatenMusic.Commands
try
{
if (response.isPlaylist)
if (response.IsPlaylist)
{
LavalinkPlaylist playlist = response.Playlist;
await player.PlayPlaylistNowAsync(playlist);
ILavalinkPlaylist playlist = response.Playlist;
await player.PlayNowAsync(playlist);
_ = ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Now Playing:").AddEmbed(
Common.AsEmbed(playlist)
@ -91,7 +93,7 @@ namespace TomatenMusic.Commands
}
else
{
LavalinkTrack track = response.Track;
TomatenMusicTrack track = response.Track;
_ = ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Playing Now")
.AddEmbed(Common.AsEmbed(track, player.PlayerQueue.LoopType, 0)));
@ -232,10 +234,10 @@ namespace TomatenMusic.Commands
try
{
if (response.isPlaylist)
if (response.IsPlaylist)
{
LavalinkPlaylist playlist = response.Playlist;
await player.PlayPlaylistAsync(playlist);
ILavalinkPlaylist playlist = response.Playlist;
await player.PlayItemAsync(playlist);
await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Now Playing:").AddEmbed(
Common.AsEmbed(playlist)
@ -249,7 +251,7 @@ namespace TomatenMusic.Commands
_ = ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent(player.State == PlayerState.NotPlaying ? "Now Playing:" : "Added to Queue")
.AddEmbed(Common.AsEmbed(track, player.PlayerQueue.LoopType, player.State == PlayerState.NotPlaying ? 0 : player.PlayerQueue.Queue.Count + 1)));
await player.PlayAsync(response.Track);
await player.PlayItemAsync(response.Track);
}
}
catch (Exception ex)
@ -316,7 +318,7 @@ namespace TomatenMusic.Commands
_ = ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent(player.State == PlayerState.NotPlaying ? "Now Playing:" : "Added to Queue")
.AddEmbed(Common.AsEmbed(track, player.PlayerQueue.LoopType, player.State == PlayerState.NotPlaying ? 0 : player.PlayerQueue.Queue.Count + 1)));
await player.PlayAsync(response.Track);
await player.PlayItemAsync(response.Track);
sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");

View File

@ -8,6 +8,8 @@ using SpotifyAPI.Web;
using Lavalink4NET.Player;
using Microsoft.Extensions.DependencyInjection;
using Lavalink4NET;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
namespace TomatenMusic.Music.Entitites
{
@ -15,11 +17,10 @@ namespace TomatenMusic.Music.Entitites
{
public bool IsFile { get; set; }
public string YoutubeDescription { get; set; }
public Uri YoutubeUri { get; set; }
public IEnumerable<string> YoutubeTags { get; set; }
public ulong YoutubeViews { get; set; }
public ulong YoutubeLikes { get; set; }
public Uri YoutubeThumbnail { get; set; }
public Uri? YoutubeThumbnail { get; set; } = null;
public DateTime YoutubeUploadDate { get; set; }
//
// Summary:
@ -34,7 +35,7 @@ namespace TomatenMusic.Music.Entitites
public int SpotifyPopularity { get; set; }
public Uri SpotifyUri { get; set; }
public static async Task<LavalinkTrack> PopulateAsync(LavalinkTrack track, FullTrack spotifyTrack = null, string spotifyId = null)
public static async Task<TomatenMusicTrack> PopulateAsync(TomatenMusicTrack track, FullTrack spotifyTrack = null, string spotifyId = null)
{
FullTrackContext context = (FullTrackContext)track.Context;
@ -48,7 +49,6 @@ namespace TomatenMusic.Music.Entitites
else if (spotifyTrack != null)
context.SpotifyIdentifier = spotifyTrack.Id;
context.YoutubeUri = new Uri(track.Source);
track.Context = context;
await youtubeService.PopulateTrackInfoAsync(track);
await spotifyService.PopulateTrackAsync(track, spotifyTrack);
@ -56,7 +56,7 @@ namespace TomatenMusic.Music.Entitites
return track;
}
public static async Task<IEnumerable<LavalinkTrack>> PopulateTracksAsync(IEnumerable<LavalinkTrack> tracks)
public static async Task<TrackList> PopulateTracksAsync(TrackList tracks)
{
foreach (var trackItem in tracks)
{

View File

@ -5,13 +5,15 @@ using System.Linq;
using TomatenMusic.Util;
using DSharpPlus.Entities;
using Lavalink4NET.Player;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
namespace TomatenMusic.Music.Entitites
{
public interface LavalinkPlaylist
public interface ILavalinkPlaylist : IPlayableItem
{
public string Name { get; }
public IEnumerable<LavalinkTrack> Tracks { get; }
public string Title { get; }
public TrackList Tracks { get; }
public Uri Url { get; }
public string AuthorName { get; set; }
public Uri AuthorUri { get; set; }

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TomatenMusic.Music;
namespace TomatenMusicCore.Music.Entities
{
public interface IPlayableItem
{
public string Title { get; }
Task Play(GuildPlayer player, TimeSpan? startTime = null, TimeSpan? endTime = null, bool noReplace = true);
Task PlayNow(GuildPlayer player, TimeSpan? startTime = null, TimeSpan? endTime = null, bool withoutQueuePrepend = false);
}
}

View File

@ -2,13 +2,15 @@
using System;
using System.Collections.Generic;
using System.Text;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
namespace TomatenMusic.Music.Entitites
{
public class SpotifyPlaylist : LavalinkPlaylist
public class SpotifyPlaylist : ILavalinkPlaylist
{
public string Name { get; }
public IEnumerable<LavalinkTrack> Tracks { get; }
public string Title { get; }
public TrackList Tracks { get; }
public Uri Url { get; set; }
public string AuthorName { get; set; }
public Uri AuthorUri { get; set; }
@ -17,13 +19,47 @@ namespace TomatenMusic.Music.Entitites
public string Identifier { get; }
public Uri AuthorThumbnail { get; set; }
public SpotifyPlaylist(string name, string id, IEnumerable<LavalinkTrack> tracks, Uri uri)
public SpotifyPlaylist(string name, string id, TrackList tracks, Uri uri)
{
Name = name;
Title = name;
Identifier = id;
Tracks = tracks;
Url = uri;
}
public async Task Play(GuildPlayer player, TimeSpan? startTime = null, TimeSpan? endTime = null, bool noReplace = true)
{
await player.PlayerQueue.QueuePlaylistAsync(this);
if (player.State == PlayerState.NotPlaying)
{
LavalinkTrack nextTrack = player.PlayerQueue.NextTrack().Track;
await player.PlayAsync(nextTrack);
}
}
public async Task PlayNow(GuildPlayer player, TimeSpan? startTime = null, TimeSpan? endTime = null, bool withoutQueuePrepend = false)
{
if (!player.PlayerQueue.Queue.Any())
player.PlayerQueue.CurrentPlaylist = this;
if (!withoutQueuePrepend && player.State == PlayerState.Playing)
player.PlayerQueue.Queue = new Queue<TomatenMusicTrack>(player.PlayerQueue.Queue.Prepend(new TomatenMusicTrack(player.PlayerQueue.LastTrack.WithPosition(player.TrackPosition))));
Queue<TomatenMusicTrack> reversedTracks = new Queue<TomatenMusicTrack>(Tracks);
TomatenMusicTrack track = reversedTracks.Dequeue();
player.PlayerQueue.LastTrack = track;
await player.PlayAsync(track);
reversedTracks.Reverse();
foreach (var item in reversedTracks)
{
player.PlayerQueue.Queue = new Queue<TomatenMusicTrack>(player.PlayerQueue.Queue.Prepend(item));
}
}
}
}

View File

@ -0,0 +1,50 @@
using Lavalink4NET.Player;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TomatenMusic.Music;
using TomatenMusic.Prompt.Implementation;
namespace TomatenMusicCore.Music.Entities
{
public class TomatenMusicTrack : LavalinkTrack, IPlayableItem
{
public override TimeSpan Position { get; }
public TomatenMusicTrack
(LavalinkTrack track)
: base(track.Identifier, track.Author, track.Duration, track.IsLiveStream, track.IsSeekable, track.Source, track.Title, track.TrackIdentifier, track.Provider)
{
Context = track.Context;
Position = track.Position;
}
public string Title => base.Title;
public async Task Play(GuildPlayer player, TimeSpan? startTime = null, TimeSpan? endTime = null, bool noReplace = true)
{
if (player.State == PlayerState.NotPlaying)
{
player.PlayerQueue.LastTrack = this;
await player.PlayAsync(this, startTime, endTime, noReplace);
}
else
player.PlayerQueue.QueueTrack(this);
}
public async Task PlayNow(GuildPlayer player, TimeSpan? startTime = null, TimeSpan? endTime = null, bool withoutQueuePrepend = false)
{
if (!withoutQueuePrepend && player.State == PlayerState.Playing)
player.PlayerQueue.Queue = new Queue<TomatenMusicTrack>(player.PlayerQueue.Queue.Prepend(new TomatenMusicTrack(player.PlayerQueue.LastTrack.WithPosition(player.TrackPosition))));
player.PlayerQueue.LastTrack = this;
await player.PlayAsync(this, startTime, endTime);
}
}
}

View File

@ -0,0 +1,567 @@

using Lavalink4NET.Player;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using TomatenMusic.Music;
namespace TomatenMusicCore.Music.Entities
{
//
// Summary:
// A thread-safe queue for Lavalink4NET.Player.LavalinkTrack.
public sealed class TrackList : IList<TomatenMusicTrack>, ICollection<TomatenMusicTrack>, IEnumerable<TomatenMusicTrack>, IEnumerable, IPlayableItem
{
private readonly List<TomatenMusicTrack> _list;
private readonly object _syncRoot;
//
// Summary:
// Gets the number of queued tracks.
//
// Remarks:
// This property is thread-safe, so it can be used from multiple threads at once
// safely.
public int Count
{
get
{
lock (_syncRoot)
{
return _list.Count;
}
}
}
//
// Summary:
// Gets a value indicating whether the queue is empty.
//
// Remarks:
// This property is thread-safe, so it can be used from multiple threads at once
// safely.
public bool IsEmpty => Count == 0;
//
// Summary:
// Gets a value indicating whether the queue is read-only.
//
// Remarks:
// This property is thread-safe, so it can be used from multiple threads at once
// safely.
public bool IsReadOnly => false;
//
// Summary:
// Gets or sets the enqueued tracks.
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public IReadOnlyList<TomatenMusicTrack> Tracks
{
get
{
lock (_syncRoot)
{
return _list.ToArray();
}
}
set
{
lock (_syncRoot)
{
_list.Clear();
_list.AddRange(value);
}
}
}
public string Title => $"Track List with {Count} Tracks";
//
// Summary:
// Gets or sets the track at the specified index.
//
// Parameters:
// index:
// the zero-based position
//
// Returns:
// the track at the specified index
//
// Remarks:
// This indexer property is thread-safe, so it can be used from multiple threads
// at once safely.
public TomatenMusicTrack this[int index]
{
get
{
lock (_syncRoot)
{
return _list[index];
}
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
lock (_syncRoot)
{
_list[index] = value;
}
}
}
public TrackList()
{
_list = new List<TomatenMusicTrack>();
_syncRoot = new object();
}
public TrackList(IEnumerable<LavalinkTrack> tracks)
{
_list = new List<TomatenMusicTrack>();
_syncRoot = new object();
foreach (var track in tracks)
Add(new TomatenMusicTrack(track));
}
//
// Summary:
// Adds a track at the end of the queue.
//
// Parameters:
// track:
// the track to add
//
// Exceptions:
// T:System.ArgumentNullException:
// thrown if the specified track is null.
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public void Add(TomatenMusicTrack track)
{
if (track == null)
{
throw new ArgumentNullException("track");
}
lock (_syncRoot)
{
_list.Add(track);
}
}
//
// Summary:
// Adds all specified tracks to the queue.
//
// Parameters:
// tracks:
// the tracks to enqueue
//
// Exceptions:
// T:System.ArgumentNullException:
// thrown if the specified tracks enumerable is null.
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public void AddRange(IEnumerable<TomatenMusicTrack> tracks)
{
if (tracks == null)
{
throw new ArgumentNullException("tracks");
}
lock (_syncRoot)
{
_list.AddRange(tracks);
}
}
//
// Summary:
// Clears all tracks from the queue.
//
// Returns:
// the number of tracks removed
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public int Clear()
{
lock (_syncRoot)
{
int count = _list.Count;
_list.Clear();
return count;
}
}
//
// Summary:
// Gets a value indicating whether the specified track is in the queue.
//
// Parameters:
// track:
// the track to find
//
// Returns:
// a value indicating whether the specified track is in the queue
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public bool Contains(TomatenMusicTrack track)
{
if (track == null)
{
throw new ArgumentNullException("track");
}
lock (_syncRoot)
{
return _list.Contains(track);
}
}
//
// Summary:
// Copies all tracks to the specified array at the specified index.
//
// Parameters:
// array:
// the array to the tracks to
//
// index:
// the zero-based writing start index
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public void CopyTo(TomatenMusicTrack[] array, int index)
{
lock (_syncRoot)
{
_list.CopyTo(array, index);
}
}
//
// Summary:
// Dequeues a track using the FIFO method.
//
// Returns:
// the dequeued track
//
// Exceptions:
// T:System.InvalidOperationException:
// thrown if no tracks were in the queue
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public TomatenMusicTrack Dequeue()
{
lock (_syncRoot)
{
if (_list.Count <= 0)
{
throw new InvalidOperationException("No tracks in to dequeue.");
}
TomatenMusicTrack result = _list[0];
_list.RemoveAt(0);
return result;
}
}
//
// Summary:
// Deletes all duplicate tracks from the queue.
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public void Distinct()
{
lock (_syncRoot)
{
if (_list.Count > 1)
{
TomatenMusicTrack[] collection = (from track in _list
group track by track.Identifier into s
select s.First()).ToArray();
_list.Clear();
_list.AddRange(collection);
}
}
}
//
// Summary:
// Gets the track enumerator.
//
// Returns:
// the track enumerator
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public IEnumerator<TomatenMusicTrack> GetEnumerator()
{
lock (_syncRoot)
{
return _list.ToList().GetEnumerator();
}
}
//
// Summary:
// Gets the zero-based index of the specified track.
//
// Parameters:
// track:
// the track to locate
//
// Returns:
// the zero-based index of the specified track
//
// Exceptions:
// T:System.ArgumentNullException:
// thrown if the specified track is null.
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public int IndexOf(TomatenMusicTrack track)
{
if (track == null)
{
throw new ArgumentNullException("track");
}
lock (_syncRoot)
{
return _list.IndexOf(track);
}
}
//
// Summary:
// Inserts the specified track at the specified index.
//
// Parameters:
// index:
// the zero-based index to insert (e.g. 0 = top)
//
// track:
// the track to insert
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public void Insert(int index, TomatenMusicTrack track)
{
lock (_syncRoot)
{
_list.Insert(index, track);
}
}
//
// Summary:
// Tries to remove the specified track from the queue.
//
// Parameters:
// track:
// the track to remove
//
// Returns:
// a value indicating whether the track was found and removed from the queue
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public bool Remove(TomatenMusicTrack track)
{
lock (_syncRoot)
{
return _list.Remove(track);
}
}
//
// Summary:
// Removes all tracks that matches the specified predicate.
//
// Parameters:
// predicate:
// the track predicate
//
// Returns:
// the number of tracks removed
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public int RemoveAll(Predicate<TomatenMusicTrack> predicate)
{
lock (_syncRoot)
{
return _list.RemoveAll(predicate);
}
}
//
// Summary:
// Removes a track at the specified index.
//
// Parameters:
// index:
// the index to remove the track
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public void RemoveAt(int index)
{
lock (_syncRoot)
{
_list.RemoveAt(index);
}
}
//
// Summary:
// Removes all count tracks from the specified index.
//
// Parameters:
// index:
// the start index (zero-based)
//
// count:
// the number of tracks to remove
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public void RemoveRange(int index, int count)
{
lock (_syncRoot)
{
_list.RemoveRange(index, count);
}
}
//
// Summary:
// Shuffles / mixes all tracks in the queue.
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public void Shuffle()
{
lock (_syncRoot)
{
if (_list.Count > 2)
{
TomatenMusicTrack[] collection = _list.OrderBy((TomatenMusicTrack s) => Guid.NewGuid()).ToArray();
_list.Clear();
_list.AddRange(collection);
}
}
}
//
// Summary:
// Tries to dequeue a track using the FIFO method.
//
// Parameters:
// track:
// the dequeued track; or default is the result is false.
//
// Returns:
// a value indicating whether a track was dequeued.
//
// Exceptions:
// T:System.InvalidOperationException:
// thrown if no tracks were in the queue
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
public bool TryDequeue(out TomatenMusicTrack? track)
{
lock (_syncRoot)
{
if (_list.Count <= 0)
{
track = null;
return false;
}
track = _list[0];
_list.RemoveAt(0);
return true;
}
}
//
// Summary:
// Clears the queue.
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
void ICollection<TomatenMusicTrack>.Clear()
{
lock (_syncRoot)
{
_list.Clear();
}
}
//
// Summary:
// Gets the track enumerator.
//
// Returns:
// the track enumerator
//
// Remarks:
// This method is thread-safe, so it can be used from multiple threads at once safely.
IEnumerator IEnumerable.GetEnumerator()
{
lock (_syncRoot)
{
return _list.ToArray().GetEnumerator();
}
}
public async Task Play(GuildPlayer player, TimeSpan? startTime = null, TimeSpan? endTime = null, bool noReplace = true)
{
await player.PlayerQueue.QueueTracksAsync(this);
if (player.State == PlayerState.NotPlaying)
{
LavalinkTrack nextTrack = player.PlayerQueue.NextTrack().Track;
await player.PlayAsync(nextTrack, startTime, endTime, noReplace);
}
}
public async Task PlayNow(GuildPlayer player, TimeSpan? startTime = null, TimeSpan? endTime = null, bool withoutQueuePrepend = false)
{
Queue<TomatenMusicTrack> reversedTracks = new Queue<TomatenMusicTrack>(this);
player.PlayerQueue.Queue = new Queue<TomatenMusicTrack>(player.PlayerQueue.Queue.Prepend(new TomatenMusicTrack(player.PlayerQueue.LastTrack.WithPosition(player.TrackPosition))));
TomatenMusicTrack track = reversedTracks.Dequeue();
player.PlayerQueue.LastTrack = track;
await player.PlayAsync(track, startTime, endTime);
reversedTracks.Reverse();
foreach (var item in reversedTracks)
{
player.PlayerQueue.Queue = new Queue<TomatenMusicTrack>(player.PlayerQueue.Queue.Prepend(item));
}
}
}
}

View File

@ -6,14 +6,16 @@ using Google.Apis.YouTube.v3.Data;
using Lavalink4NET.Player;
using Microsoft.Extensions.DependencyInjection;
using TomatenMusic.Services;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
namespace TomatenMusic.Music.Entitites
{
public class YoutubePlaylist : LavalinkPlaylist
public class YoutubePlaylist : ILavalinkPlaylist
{
public string Name { get; }
public string Title { get; }
public IEnumerable<LavalinkTrack> Tracks { get; }
public TrackList Tracks { get; }
public int TrackCount { get; }
@ -28,14 +30,50 @@ namespace TomatenMusic.Music.Entitites
public Playlist YoutubeItem { get; set; }
public Uri AuthorThumbnail { get; set; }
public YoutubePlaylist(string name, IEnumerable<LavalinkTrack> tracks, Uri uri)
public YoutubePlaylist(string name, TrackList tracks, string id)
{
Identifier = uri.ToString().Replace("https://www.youtube.com/playlist?list=", "").Replace("https://youtube.com/playlist?list=", "");
Name = name;
Identifier = id;
Title = name;
Tracks = tracks;
Url = uri;
Url = new Uri($"https://youtube.com/playlist?list={id}");
TrackCount = tracks.Count();
}
public async Task Play(GuildPlayer player, TimeSpan? startTime = null, TimeSpan? endTime = null, bool noReplace = true)
{
await player.PlayerQueue.QueuePlaylistAsync(this);
if (player.State == PlayerState.NotPlaying)
{
LavalinkTrack nextTrack = player.PlayerQueue.NextTrack().Track;
await player.PlayAsync(nextTrack);
}
}
public async Task PlayNow(GuildPlayer player, TimeSpan? startTime = null, TimeSpan? endTime = null, bool withoutQueuePrepend = false)
{
if (!player.PlayerQueue.Queue.Any())
player.PlayerQueue.CurrentPlaylist = this;
if (!withoutQueuePrepend && player.State == PlayerState.Playing)
player.PlayerQueue.Queue = new Queue<TomatenMusicTrack>(player.PlayerQueue.Queue.Prepend(new TomatenMusicTrack(player.PlayerQueue.LastTrack.WithPosition(player.TrackPosition))));
Queue<TomatenMusicTrack> reversedTracks = new Queue<TomatenMusicTrack>(Tracks);
TomatenMusicTrack track = reversedTracks.Dequeue();
player.PlayerQueue.LastTrack = track;
await player.PlayAsync(track);
reversedTracks.Reverse();
foreach (var item in reversedTracks)
{
player.PlayerQueue.Queue = new Queue<TomatenMusicTrack>(player.PlayerQueue.Queue.Prepend(item));
}
}
}
}

View File

@ -15,6 +15,8 @@ using Lavalink4NET;
using Lavalink4NET.Rest;
using Microsoft.Extensions.DependencyInjection;
using Lavalink4NET.Decoding;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
namespace TomatenMusic.Music
{
@ -39,119 +41,25 @@ namespace TomatenMusic.Music
_spotify = serviceProvider.GetRequiredService<ISpotifyService>();
_audioService = serviceProvider.GetRequiredService<IAudioService>();
}
public async override Task PlayAsync(LavalinkTrack track, TimeSpan? startTime = null, TimeSpan? endTime = null, bool noReplace = true)
public async Task PlayItemAsync(IPlayableItem item, TimeSpan? startTime = null, TimeSpan? endTime = null, bool noReplace = true)
{
EnsureConnected();
EnsureNotDestroyed();
if (State == PlayerState.NotPlaying)
{
PlayerQueue.LastTrack = track;
await base.PlayAsync(track, startTime, endTime, noReplace);
_logger.LogInformation("Started playing Track {0} on Guild {1}", track.Title, (await GetGuildAsync()).Name);
}else
PlayerQueue.QueueTrack(track);
_ = item.Play(this, startTime, endTime, noReplace);
_logger.LogInformation("Started playing Item {0} on Guild {1}", item.Title, (await GetGuildAsync()).Name);
QueuePrompt.UpdateFor(GuildId);
}
public async Task PlayNowAsync(LavalinkTrack track, TimeSpan? startTime = null, TimeSpan? endTime = null, bool withoutQueuePrepend = false)
{
EnsureConnected();
EnsureNotDestroyed();
if (!withoutQueuePrepend)
PlayerQueue.Queue = new Queue<LavalinkTrack>(PlayerQueue.Queue.Prepend(PlayerQueue.LastTrack));
PlayerQueue.LastTrack = track;
await base.PlayAsync(track, startTime, endTime);
_logger.LogInformation("Started playing Track {0} now on Guild {1}", track.Title, (await GetGuildAsync()).Name);
QueuePrompt.UpdateFor(GuildId);
}
public async Task PlayTracksAsync(List<LavalinkTrack> tracks)
{
EnsureNotDestroyed();
EnsureConnected();
_logger.LogInformation("Started playing TrackList {0} on Guild {1}", tracks.ToString(), (await GetGuildAsync()).Name);
await PlayerQueue.QueueTracksAsync(tracks);
if (State == PlayerState.NotPlaying)
{
LavalinkTrack nextTrack = PlayerQueue.NextTrack().Track;
await base.PlayAsync(nextTrack);
}
QueuePrompt.UpdateFor(GuildId);
}
public async Task PlayTracksNowAsync(IEnumerable<LavalinkTrack> tracks)
{
EnsureConnected();
EnsureNotDestroyed();
Queue<LavalinkTrack> reversedTracks = new Queue<LavalinkTrack>(tracks);
LavalinkTrack track = reversedTracks.Dequeue();
PlayerQueue.LastTrack = track;
await base.PlayAsync(track);
_logger.LogInformation("Started playing Track {0} on Guild {1}", track.Title, (await GetGuildAsync()).Name);
reversedTracks.Reverse();
foreach (var item in reversedTracks)
{
PlayerQueue.Queue = new Queue<LavalinkTrack>(PlayerQueue.Queue.Prepend(PlayerQueue.LastTrack));
}
QueuePrompt.UpdateFor(GuildId);
}
public async Task PlayPlaylistAsync(LavalinkPlaylist playlist)
{
EnsureNotDestroyed();
EnsureConnected();
_logger.LogInformation("Started playing Playlist {0} on Guild {1}", playlist.Name, (await GetGuildAsync()).Name);
await PlayerQueue.QueuePlaylistAsync(playlist);
if (State == PlayerState.NotPlaying)
{
LavalinkTrack nextTrack = PlayerQueue.NextTrack().Track;
await base.PlayAsync(nextTrack);
}
QueuePrompt.UpdateFor(GuildId);
}
public async Task PlayPlaylistNowAsync(LavalinkPlaylist playlist)
public async Task PlayNowAsync(IPlayableItem item, TimeSpan? startTime = null, TimeSpan? endTime = null, bool withoutQueuePrepend = false)
{
EnsureConnected();
EnsureNotDestroyed();
if (!PlayerQueue.Queue.Any())
PlayerQueue.CurrentPlaylist = playlist;
Queue<LavalinkTrack> reversedTracks = new Queue<LavalinkTrack>(playlist.Tracks);
LavalinkTrack track = reversedTracks.Dequeue();
PlayerQueue.LastTrack = track;
await base.PlayAsync(track);
_logger.LogInformation("Started playing Track {0} on Guild {1}", track.Title, (await GetGuildAsync()).Name);
reversedTracks.Reverse();
foreach (var item in reversedTracks)
{
PlayerQueue.Queue = new Queue<LavalinkTrack>(PlayerQueue.Queue.Prepend(PlayerQueue.LastTrack));
}
_ = item.PlayNow(this, startTime, endTime, withoutQueuePrepend);
_logger.LogInformation("Started playing Item {0} now on Guild {1}", item.Title, (await GetGuildAsync()).Name);
QueuePrompt.UpdateFor(GuildId);
}
@ -160,7 +68,7 @@ namespace TomatenMusic.Music
{
EnsureNotDestroyed();
EnsureConnected();
if (Position.Position.Seconds < 4)
if (Position.Position.Seconds > 5)
{
await ReplayAsync();
return;
@ -177,10 +85,23 @@ namespace TomatenMusic.Music
{
EnsureNotDestroyed();
EnsureConnected();
MusicActionResponse response = PlayerQueue.NextTrack(true);
MusicActionResponse response;
try
{
response = PlayerQueue.NextTrack(true, Autoplay);
}catch (Exception ex)
{
if (Autoplay)
{
_ = OnAutoPlay(CurrentTrack);
return;
}
throw ex;
}
_logger.LogInformation($"Skipped Track {CurrentTrack.Title} for Track {response.Track.Title}");
await base.PlayAsync(response.Track);
await PlayNowAsync(response.Track, withoutQueuePrepend: true);
QueuePrompt.UpdateFor(GuildId);
}
@ -238,10 +159,16 @@ namespace TomatenMusic.Music
if (channel.Type == ChannelType.Stage)
{
DiscordStageInstance stageInstance = await channel.GetStageInstanceAsync();
DiscordStageInstance stageInstance;
try
{
stageInstance = await channel.GetStageInstanceAsync();
if (stageInstance == null)
}catch (Exception ex)
{
stageInstance = await channel.CreateStageInstanceAsync("Music");
}
await stageInstance.Channel.UpdateCurrentUserVoiceStateAsync(false);
}
@ -277,7 +204,6 @@ namespace TomatenMusic.Music
public async override Task OnTrackEndAsync(TrackEndEventArgs eventArgs)
{
DisconnectOnStop = false;
YoutubeService youtube = TomatenMusicBot.ServiceProvider.GetRequiredService<YoutubeService>();
var oldTrack = CurrentTrack;
if (eventArgs.Reason != TrackEndReason.Finished)
@ -295,30 +221,35 @@ namespace TomatenMusic.Music
if (!Autoplay)
{
_logger.LogInformation("Track has ended and Queue was Empty... Idling");
QueuePrompt.UpdateFor(GuildId);
await base.OnTrackEndAsync(eventArgs);
return;
}
LavalinkTrack newTrack = await youtube.GetRelatedTrackAsync(oldTrack.TrackIdentifier);
_logger.LogInformation($"Autoplaying for track {oldTrack.TrackIdentifier} with Track {newTrack.TrackIdentifier}");
await PlayNowAsync(newTrack, withoutQueuePrepend: true);
await base.OnTrackEndAsync(eventArgs);
_ = OnAutoPlay(oldTrack);
/* try
{
LavalinkTrack track = await youtube.GetRelatedTrackAsync(eventArgs.TrackIdentifier);
_logger.LogInformation($"Autoplaying for track {eventArgs.TrackIdentifier} with Track {track.TrackIdentifier}");
await PlayAsync(track);
}
catch (Exception ex2)
{
await base.OnTrackEndAsync(eventArgs);
}*/
}
}
}
public async Task OnAutoPlay(LavalinkTrack oldTrack)
{
YoutubeService youtube = TomatenMusicBot.ServiceProvider.GetRequiredService<YoutubeService>();
TomatenMusicTrack newTrack;
if (oldTrack.Provider != StreamProvider.YouTube)
newTrack = await youtube.GetRelatedTrackAsync(PlayerQueue.PlayedTracks.First(x => x.Provider == StreamProvider.YouTube).TrackIdentifier, PlayerQueue.PlayedTracks.Take(5).ToList().ConvertAll(x => x.TrackIdentifier));
else
newTrack = await youtube.GetRelatedTrackAsync(oldTrack.TrackIdentifier, PlayerQueue.PlayedTracks.Take(5).ToList().ConvertAll(x => x.TrackIdentifier));
_logger.LogInformation($"Autoplaying for track {oldTrack.TrackIdentifier} with Track {newTrack.TrackIdentifier}");
PlayerQueue.LastTrack = newTrack;
await newTrack.PlayNow(this, withoutQueuePrepend: true);
QueuePrompt.UpdateFor(GuildId);
}
public async Task<DiscordChannel> GetChannelAsync()
{
EnsureConnected();

View File

@ -3,21 +3,29 @@ using System;
using System.Collections.Generic;
using System.Text;
using TomatenMusic.Music.Entitites;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
namespace TomatenMusic.Music
{
public class MusicActionResponse
{
public LavalinkPlaylist Playlist { get; }
public LavalinkTrack Track { get; }
public IEnumerable<LavalinkTrack> Tracks { get; }
public bool isPlaylist { get; }
public MusicActionResponse(LavalinkTrack track = null, LavalinkPlaylist playlist = null, IEnumerable<LavalinkTrack> tracks = null)
public ILavalinkPlaylist Playlist { get; }
public TomatenMusicTrack Track { get; }
public TrackList Tracks { get; }
public bool IsPlaylist { get; }
public MusicActionResponse(TomatenMusicTrack track = null, ILavalinkPlaylist playlist = null, TrackList tracks = null)
{
Playlist = playlist;
Track = track;
isPlaylist = playlist != null;
IsPlaylist = playlist != null;
Tracks = tracks;
if (track != null)
{
var list = new TrackList();
list.Add(track);
Tracks = list;
}
}
}
}

View File

@ -9,24 +9,26 @@ using TomatenMusic.Util;
using Microsoft.Extensions.Logging;
using Lavalink4NET.Player;
using Microsoft.Extensions.DependencyInjection;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
namespace TomatenMusic.Music
{
public class PlayerQueue
{
public Queue<LavalinkTrack> Queue { get; set; } = new Queue<LavalinkTrack>();
public Queue<LavalinkTrack> PlayedTracks { get; set; } = new Queue<LavalinkTrack>();
public Queue<TomatenMusicTrack> Queue { get; set; } = new Queue<TomatenMusicTrack>();
public Queue<TomatenMusicTrack> PlayedTracks { get; set; } = new Queue<TomatenMusicTrack>();
public ILogger<PlayerQueue> _logger { get; set; } = TomatenMusicBot.ServiceProvider.GetRequiredService<ILogger<PlayerQueue>>();
public LavalinkPlaylist CurrentPlaylist { get; set; }
public ILavalinkPlaylist CurrentPlaylist { get; set; }
public LoopType LoopType { get; private set; } = LoopType.NONE;
public LavalinkTrack LastTrack { get; set; }
public TomatenMusicTrack LastTrack { get; set; }
public List<LavalinkTrack> QueueLoopList { get; private set; }
public List<TomatenMusicTrack> QueueLoopList { get; private set; } = new List<TomatenMusicTrack>();
public void QueueTrack(LavalinkTrack track)
public void QueueTrack(TomatenMusicTrack track)
{
CurrentPlaylist = null;
Queue.Enqueue(track);
@ -36,7 +38,7 @@ namespace TomatenMusic.Music
QueueLoopList.Add(track);
}
public Task QueuePlaylistAsync(LavalinkPlaylist playlist)
public Task QueuePlaylistAsync(ILavalinkPlaylist playlist)
{
return Task.Run(() =>
{
@ -45,8 +47,8 @@ namespace TomatenMusic.Music
else
CurrentPlaylist = null;
_logger.LogInformation("Queued Playlist {0}", playlist.Name);
foreach (LavalinkTrack track in playlist.Tracks)
_logger.LogInformation("Queued Playlist {0}", playlist.Title);
foreach (var track in playlist.Tracks)
{
Queue.Enqueue(track);
}
@ -59,13 +61,13 @@ namespace TomatenMusic.Music
}
public Task QueueTracksAsync(List<LavalinkTrack> tracks)
public Task QueueTracksAsync(TrackList tracks)
{
return Task.Run(() =>
{
CurrentPlaylist = null;
_logger.LogInformation("Queued TrackList {0}", tracks.ToString());
foreach (LavalinkTrack track in tracks)
foreach (var track in tracks)
{
Queue.Enqueue(track);
}
@ -84,16 +86,17 @@ namespace TomatenMusic.Music
public void RemoveAt(int index)
{
if (Queue.Count == 0) throw new InvalidOperationException("Queue was Empty");
List<LavalinkTrack> tracks = Queue.ToList();
List<TomatenMusicTrack> tracks = Queue.ToList();
tracks.RemoveAt(index);
Queue = new Queue<LavalinkTrack>(tracks);
Queue = new Queue<TomatenMusicTrack>(tracks);
}
public MusicActionResponse NextTrack(bool ignoreLoop = false)
public MusicActionResponse NextTrack(bool ignoreLoop = false, bool autoplay = false)
{
if (LastTrack != null)
PlayedTracks = new Queue<LavalinkTrack>(PlayedTracks.Prepend(LastTrack));
if (LoopType != LoopType.TRACK || (ignoreLoop && (Queue.Any() || autoplay)))
PlayedTracks = new Queue<TomatenMusicTrack>(PlayedTracks.Prepend(new TomatenMusicTrack(LastTrack.WithPosition(TimeSpan.Zero))));
switch (LoopType)
{
@ -115,9 +118,9 @@ namespace TomatenMusic.Music
if (!Queue.Any())
{
if (CurrentPlaylist != null)
Queue = new Queue<LavalinkTrack>(CurrentPlaylist.Tracks);
Queue = new Queue<TomatenMusicTrack>(CurrentPlaylist.Tracks);
else
Queue = new Queue<LavalinkTrack>(QueueLoopList);
Queue = new Queue<TomatenMusicTrack>(QueueLoopList);
}
LastTrack = Queue.Dequeue();
@ -133,7 +136,7 @@ namespace TomatenMusic.Music
if (!PlayedTracks.Any()) throw new InvalidOperationException("There are no songs that could be rewinded to yet.");
Queue = new Queue<LavalinkTrack>(Queue.Prepend(LastTrack));
Queue = new Queue<TomatenMusicTrack>(Queue.Prepend(LastTrack));
LastTrack = PlayedTracks.Dequeue();
return new MusicActionResponse(LastTrack);
@ -143,9 +146,9 @@ namespace TomatenMusic.Music
{
if (Queue.Count == 0) throw new InvalidOperationException("Queue is Empty");
List<LavalinkTrack> tracks = new List<LavalinkTrack>(Queue);
List<TomatenMusicTrack> tracks = new List<TomatenMusicTrack>(Queue);
tracks.Shuffle();
Queue = new Queue<LavalinkTrack>(tracks);
Queue = new Queue<TomatenMusicTrack>(tracks);
return Task.CompletedTask;
}
@ -155,8 +158,7 @@ namespace TomatenMusic.Music
if (type == LoopType.QUEUE)
{
QueueLoopList = new List<LavalinkTrack>(Queue);
QueueLoopList.Add(LastTrack);
QueueLoopList = new List<TomatenMusicTrack>(Queue.Prepend(LastTrack));
}
}
}

View File

@ -9,19 +9,22 @@ using System.Threading.Tasks;
using TomatenMusic.Music;
using TomatenMusic.Music.Entitites;
using Microsoft.Extensions.DependencyInjection;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
using TomatenMusic.Prompt.Option;
namespace TomatenMusic.Prompt.Buttons
{
class AddToQueueButton : ButtonPromptOption
{
public List<LavalinkTrack> Tracks { get; set; }
public TrackList Tracks { get; set; }
public AddToQueueButton(List<LavalinkTrack> tracks, int row, DiscordMember requestMember)
public AddToQueueButton(TrackList tracks, int row, DiscordMember requestMember)
{
Tracks = tracks;
Emoji = new DiscordComponentEmoji("▶️");
Row = row;
Style = DSharpPlus.ButtonStyle.Primary;
Style = DSharpPlus.ButtonStyle.Secondary;
UpdateMethod = (prompt) =>
{
if (requestMember.VoiceState == null || requestMember.VoiceState.Channel == null)
@ -32,7 +35,7 @@ namespace TomatenMusic.Prompt.Buttons
Run = async (args, sender, option) =>
{
IAudioService audioService = TomatenMusicBot.ServiceProvider.GetRequiredService<IAudioService>();
GuildPlayer player;player = audioService.GetPlayer<GuildPlayer>(args.Guild.Id);
GuildPlayer player;
try
{
@ -44,7 +47,7 @@ namespace TomatenMusic.Prompt.Buttons
{
player = audioService.GetPlayer<GuildPlayer>(args.Guild.Id);
}
await player.PlayTracksAsync(Tracks);
await player.PlayItemAsync(Tracks);
}
catch (Exception ex)
{

View File

@ -0,0 +1,60 @@
using DSharpPlus.Entities;
using Lavalink4NET;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TomatenMusic;
using TomatenMusic.Music;
using TomatenMusic.Prompt;
using TomatenMusic.Prompt.Option;
using TomatenMusicCore.Music.Entities;
namespace TomatenMusicCore.Prompt.Buttons
{
class PlayNowButton : ButtonPromptOption
{
public TrackList Tracks { get; set; }
public PlayNowButton(TrackList tracks, int row, DiscordMember requestMember)
{
Tracks = tracks;
Emoji = new DiscordComponentEmoji("▶");
Content = "Now";
Row = row;
Style = DSharpPlus.ButtonStyle.Secondary;
UpdateMethod = (prompt) =>
{
if (requestMember.VoiceState == null || requestMember.VoiceState.Channel == null)
prompt.Disabled = true;
return Task.FromResult(prompt);
};
Run = async (args, sender, option) =>
{
IAudioService audioService = TomatenMusicBot.ServiceProvider.GetRequiredService<IAudioService>();
GuildPlayer player;
try
{
try
{
player = await audioService.JoinAsync<GuildPlayer>(args.Guild.Id, ((DiscordMember)args.User).VoiceState.Channel.Id, true);
}
catch (Exception ex)
{
player = audioService.GetPlayer<GuildPlayer>(args.Guild.Id);
}
await player.PlayNowAsync(Tracks);
}
catch (Exception ex)
{
}
};
}
}
}

View File

@ -0,0 +1,105 @@
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.EventArgs;
using Lavalink4NET.Player;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TomatenMusic.Music.Entitites;
using TomatenMusic.Prompt;
using TomatenMusic.Prompt.Model;
using TomatenMusic.Prompt.Option;
using TomatenMusic.Util;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
namespace TomatenMusicCore.Prompt.Implementation
{
class PlaylistSongSelectorPrompt : PaginatedSelectPrompt<TomatenMusicTrack>
{
public bool IsConfirmed { get; set; }
public Func<TrackList, Task> ConfirmCallback { get; set; } = (tracks) =>
{
return Task.CompletedTask;
};
public ILavalinkPlaylist Playlist { get; private set; }
public PlaylistSongSelectorPrompt(ILavalinkPlaylist playlist, DiscordPromptBase lastPrompt = null, List<DiscordEmbed> embeds = null) : base(playlist.Title, playlist.Tracks.ToList(), lastPrompt, embeds)
{
Playlist = playlist;
AddOption(new ButtonPromptOption
{
Emoji = new DiscordComponentEmoji("✔️"),
Row = 3,
Style = ButtonStyle.Success,
Run = async (args, client, option) =>
{
if (SelectedItems.Count == 0)
{
await args.Interaction.CreateFollowupMessageAsync(new DiscordFollowupMessageBuilder().WithContent("Please Select a Song!").AsEphemeral(true));
return;
}
IsConfirmed = true;
_ = ConfirmCallback.Invoke(new TrackList(SelectedItems));
}
});
}
public override Task<PaginatedSelectMenuOption<TomatenMusicTrack>> ConvertToOption(TomatenMusicTrack item)
{
return Task.FromResult<PaginatedSelectMenuOption<TomatenMusicTrack>>(new PaginatedSelectMenuOption<TomatenMusicTrack>
{
Label = item.Title,
Description = item.Author
});
}
public override Task OnSelect(TomatenMusicTrack item, ComponentInteractionCreateEventArgs args, DiscordClient sender)
{
_logger.LogDebug($"Added {item.Title}, {SelectedItems}");
return Task.CompletedTask;
}
public override Task OnUnselect(TomatenMusicTrack item, ComponentInteractionCreateEventArgs args, DiscordClient sender)
{
_logger.LogDebug($"Removed {item.Title}");
return Task.CompletedTask;
}
public async Task<TrackList> AwaitSelectionAsync()
{
return await Task.Run(() =>
{
while (!IsConfirmed)
{
if (State == PromptState.INVALID)
throw new InvalidOperationException("Prompt has been Invalidated");
}
IsConfirmed = false;
return new TrackList(SelectedItems);
});
}
protected override DiscordMessageBuilder PopulateMessage(DiscordEmbedBuilder builder)
{
builder.WithTitle(Title);
builder.WithDescription(Common.TrackListString(PageManager.GetPage(CurrentPage), 4000));
builder.WithUrl(Playlist.Url);
builder.WithAuthor(Playlist.AuthorName, Playlist.AuthorUri.ToString(), Playlist.AuthorThumbnail.ToString());
List<DiscordEmbed> embeds = new List<DiscordEmbed>();
embeds.Add(builder.Build());
if (Embeds != null)
embeds.AddRange(Embeds);
return new DiscordMessageBuilder().AddEmbeds(embeds);
}
}
}

View File

@ -32,7 +32,7 @@ namespace TomatenMusic.Prompt.Implementation
}
public static void UpdateFor(ulong guildId)
{
_ = Task.Delay(600).ContinueWith(async (task) =>
_ = Task.Delay(400).ContinueWith(async (task) =>
{
foreach (var prompt in ActivePrompts)
{
@ -93,11 +93,15 @@ namespace TomatenMusic.Prompt.Implementation
_ = args.Interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().WithContent("Please connect to the bots Channel to use this Interaction"));
return;
}
try
{
await Player.RewindAsync();
}catch (Exception ex)
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
@ -131,8 +135,18 @@ namespace TomatenMusic.Prompt.Implementation
_ = args.Interaction.EditOriginalResponseAsync(new DiscordWebhookBuilder().WithContent("Please connect to the bots Channel to use this Interaction"));
return;
}
try
{
await Player.SkipAsync();
await Player.SkipAsync();
}
catch (Exception ex)
{
_ = args.Interaction.CreateResponseAsync(
DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
new DiscordInteractionResponseBuilder()
.WithContent($"An Error occurred during this Interaction {ex.Message}"));
}
System.Timers.Timer timer = new System.Timers.Timer(800);
timer.Elapsed += (s, args) =>

View File

@ -7,23 +7,29 @@ using System.Threading.Tasks;
using TomatenMusic.Music.Entitites;
using TomatenMusic.Prompt.Buttons;
using TomatenMusic.Prompt.Model;
using TomatenMusic.Util;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
using TomatenMusicCore.Prompt.Buttons;
namespace TomatenMusic.Prompt.Implementation
{
class SongActionPrompt : ButtonPrompt
{
public LavalinkTrack Track { get; set; }
public SongActionPrompt(LavalinkTrack track, DiscordMember requestMember, List<DiscordEmbed> embeds = null)
public SongActionPrompt(TomatenMusicTrack track, DiscordMember requestMember, List<DiscordEmbed> embeds = null)
{
Embeds = embeds;
Embeds = embeds == null ? new List<DiscordEmbed>() : embeds;
Track = track;
AddOption(new AddToQueueButton(new List<LavalinkTrack>() { track }, 1, requestMember));
AddOption(new AddToQueueButton(new TrackList() { track }, 1, requestMember));
AddOption(new PlayNowButton(new TrackList() { track }, 1, requestMember));
}
protected async override Task<DiscordMessageBuilder> GetMessageAsync()
{
return new DiscordMessageBuilder().AddEmbeds(Embeds);
return new DiscordMessageBuilder().AddEmbed(Common.AsEmbed(Track)).AddEmbeds(Embeds);
}
}
}

View File

@ -11,19 +11,24 @@ using TomatenMusic.Music;
using Microsoft.Extensions.Logging;
using TomatenMusic.Prompt.Buttons;
using Lavalink4NET.Player;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
using TomatenMusicCore.Prompt.Buttons;
namespace TomatenMusic.Prompt.Implementation
{
class SongListActionPrompt : ButtonPrompt
{
//TODO
public List<LavalinkTrack> Tracks { get; private set; }
public TrackList Tracks { get; private set; }
public SongListActionPrompt(List<LavalinkTrack> tracks, DiscordMember requestMember, DiscordPromptBase lastPrompt = null) : base(lastPrompt)
public SongListActionPrompt(TrackList tracks, DiscordMember requestMember, DiscordPromptBase lastPrompt = null) : base(lastPrompt)
{
Tracks = tracks;
AddOption(new AddToQueueButton(tracks, 1, requestMember));
AddOption(new PlayNowButton(tracks, 1, requestMember));
}
protected override Task<DiscordMessageBuilder> GetMessageAsync()
@ -32,7 +37,7 @@ namespace TomatenMusic.Prompt.Implementation
DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
.WithTitle("What do you want to do with these Tracks?");
builder.WithDescription(Common.TrackListString(Tracks));
builder.WithDescription(Common.TrackListString(Tracks, 1000));
return Task.FromResult(new DiscordMessageBuilder().WithEmbed(builder.Build()));
}

View File

@ -12,13 +12,16 @@ using TomatenMusic.Music.Entitites;
using TomatenMusic.Music;
using System.Linq;
using Lavalink4NET.Player;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
using TomatenMusic.Prompt.Option;
namespace TomatenMusic.Prompt.Implementation
{
sealed class SongSelectorPrompt : PaginatedSelectPrompt<LavalinkTrack>
{
public bool IsConfirmed { get; set; }
public Func<List<LavalinkTrack>, Task> ConfirmCallback { get; set; } = (tracks) =>
public Func<TrackList, Task> ConfirmCallback { get; set; } = (tracks) =>
{
return Task.CompletedTask;
};
@ -42,7 +45,7 @@ namespace TomatenMusic.Prompt.Implementation
return;
}
IsConfirmed = true;
_ = ConfirmCallback.Invoke(SelectedItems);
_ = ConfirmCallback.Invoke(new TrackList(SelectedItems));
}
});
}
@ -87,7 +90,7 @@ namespace TomatenMusic.Prompt.Implementation
{
builder.WithTitle(Title);
builder.WithDescription(Common.TrackListString(PageManager.GetPage(CurrentPage)));
builder.WithDescription(Common.TrackListString(PageManager.GetPage(CurrentPage), 4000));
List<DiscordEmbed> embeds = new List<DiscordEmbed>();
embeds.Add(builder.Build());

View File

@ -23,6 +23,7 @@ namespace TomatenMusic.Prompt.Model
public List<IPromptOption> Options { get; protected set; } = new List<IPromptOption>();
public DiscordClient _client { get; set; }
public DiscordPromptBase LastPrompt { get; protected set; }
public System.Timers.Timer TimeoutTimer { get; set; }
protected ILogger<DiscordPromptBase> _logger { get; set; }
@ -132,6 +133,16 @@ namespace TomatenMusic.Prompt.Model
Interaction = interaction;
Message = await interaction.CreateFollowupMessageAsync(builder);
State = PromptState.OPEN;
long timeoutTime = (Interaction.CreationTimestamp.ToUnixTimeMilliseconds() + 900000) - DateTimeOffset.Now.ToUnixTimeMilliseconds();
if (TimeoutTimer != null)
TimeoutTimer.Close();
TimeoutTimer = new System.Timers.Timer(timeoutTime);
TimeoutTimer.Elapsed += OnTimeout;
TimeoutTimer.AutoReset = false;
TimeoutTimer.Start();
}
public async Task UseAsync(DiscordMessage message)
@ -164,6 +175,7 @@ namespace TomatenMusic.Prompt.Model
_client = client.GetShard((ulong)interaction.GuildId);
_client.ComponentInteractionCreated += Discord_ComponentInteractionCreated;
ActivePrompts.Add(this);
AddGuids();
DiscordWebhookBuilder builder = await GetWebhookMessageAsync();
@ -171,6 +183,22 @@ namespace TomatenMusic.Prompt.Model
Message = message;
await EditMessageAsync(builder);
State = PromptState.OPEN;
long timeoutTime = (Interaction.CreationTimestamp.ToUnixTimeMilliseconds() + 900000) - DateTimeOffset.Now.ToUnixTimeMilliseconds();
if (TimeoutTimer != null)
TimeoutTimer.Close();
TimeoutTimer = new System.Timers.Timer(timeoutTime);
TimeoutTimer.Elapsed += OnTimeout;
TimeoutTimer.AutoReset = false;
TimeoutTimer.Start();
}
private void OnTimeout(object? sender, System.Timers.ElapsedEventArgs e)
{
_ = InvalidateAsync();
}
private void AddGuids()

View File

@ -7,8 +7,7 @@ using TomatenMusic.Util;
using DSharpPlus;
using DSharpPlus.EventArgs;
using Microsoft.Extensions.Logging;
using TomatenMusic.Prompt.Option;
namespace TomatenMusic.Prompt.Model
{
@ -26,6 +25,7 @@ namespace TomatenMusic.Prompt.Model
for (int i = 0; i < 9; i++)
{
int currentNumber = i + 1;
ButtonPromptOption option = new ButtonPromptOption()
{
Style = DSharpPlus.ButtonStyle.Primary,

View File

@ -24,7 +24,7 @@ namespace TomatenMusic.Prompt.Model
public PaginatedSelectPrompt(string title, List<T> items, DiscordPromptBase lastPrompt = null, List<DiscordEmbed> embeds = null) : base(lastPrompt)
{
Embeds = embeds;
PageManager = new PageManager<T>(items, 25);
PageManager = new PageManager<T>(items, 10);
Title = title;
AddOption(new SelectMenuPromptOption
{

View File

@ -8,7 +8,7 @@ using TomatenMusic.Prompt.Option;
using TomatenMusic.Prompt.Model;
namespace TomatenMusic.Prompt
namespace TomatenMusic.Prompt.Option
{
class ButtonPromptOption : IPromptOption
{

View File

@ -19,8 +19,5 @@ namespace TomatenMusic.Prompt.Option
public Func<IPromptOption, Task<IPromptOption>> UpdateMethod { get; set; }
public Func<DSharpPlus.EventArgs.ComponentInteractionCreateEventArgs, DiscordClient, IPromptOption, Task> Run { get; set; }
}
}

View File

@ -12,6 +12,8 @@ using TomatenMusic.Music;
using Lavalink4NET;
using Lavalink4NET.Player;
using System.Runtime.Caching;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
namespace TomatenMusic.Services
{
@ -55,7 +57,9 @@ namespace TomatenMusic.Services
_logger.LogInformation($"Searching youtube from spotify with query: {sTrack.Name} {String.Join(" ", sTrack.Artists)}");
var track = await _audioService.GetTrackAsync($"{sTrack.Name} {String.Join(" ", sTrack.Artists.ConvertAll(artist => artist.Name))}", Lavalink4NET.Rest.SearchMode.YouTube);
var track = new TomatenMusicTrack(
await _audioService.GetTrackAsync($"{sTrack.Name} {String.Join(" ", sTrack.Artists.ConvertAll(artist => artist.Name))}"
, Lavalink4NET.Rest.SearchMode.YouTube));
if (track == null) throw new ArgumentException("This Spotify Track was not found on Youtube");
@ -66,14 +70,16 @@ namespace TomatenMusic.Services
}
else if (url.StartsWith("https://open.spotify.com/album"))
{
List<LavalinkTrack> tracks = new List<LavalinkTrack>();
TrackList tracks = new TrackList();
FullAlbum album = Cache.Contains(trackId) ? Cache.Get(trackId) as FullAlbum : await Albums.Get(trackId);
foreach (var sTrack in await PaginateAll(album.Tracks))
{
_logger.LogInformation($"Searching youtube from spotify with query: {sTrack.Name} {String.Join(" ", sTrack.Artists.ConvertAll(artist => artist.Name))}");
var track = await _audioService.GetTrackAsync($"{sTrack.Name} {String.Join(" ", sTrack.Artists.ConvertAll(artist => artist.Name))}", Lavalink4NET.Rest.SearchMode.YouTube);
var track = new TomatenMusicTrack(
await _audioService.GetTrackAsync($"{sTrack.Name} {String.Join(" ", sTrack.Artists.ConvertAll(artist => artist.Name))}"
, Lavalink4NET.Rest.SearchMode.YouTube));
if (track == null) throw new ArgumentException("This Spotify Track was not found on Youtube");
@ -93,7 +99,7 @@ namespace TomatenMusic.Services
else if (url.StartsWith("https://open.spotify.com/playlist"))
{
List<LavalinkTrack> tracks = new List<LavalinkTrack>();
TrackList tracks = new TrackList();
FullPlaylist spotifyPlaylist = Cache.Contains(trackId) ? Cache.Get(trackId) as FullPlaylist : await Playlists.Get(trackId);
@ -104,7 +110,9 @@ namespace TomatenMusic.Services
FullTrack fullTrack = (FullTrack)sTrack.Track;
_logger.LogInformation($"Searching youtube from spotify with query: {fullTrack.Name} {String.Join(" ", fullTrack.Artists.ConvertAll(artist => artist.Name))}");
var track = await _audioService.GetTrackAsync($"{fullTrack.Name} {String.Join(" ", fullTrack.Artists.ConvertAll(artist => artist.Name))}", Lavalink4NET.Rest.SearchMode.YouTube);
var track = new TomatenMusicTrack(
await _audioService.GetTrackAsync($"{fullTrack.Name} {String.Join(" ", fullTrack.Artists.ConvertAll(artist => artist.Name))}"
, Lavalink4NET.Rest.SearchMode.YouTube));
if (track == null) throw new ArgumentException("This Spotify Track was not found on Youtube");

View File

@ -5,8 +5,11 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using TomatenMusic.Music.Entitites;
using TomatenMusic.Services;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
namespace TomatenMusic.Music
{
@ -50,23 +53,27 @@ namespace TomatenMusic.Music
if (loadResult.LoadType == TrackLoadType.NoMatches) throw new FileNotFoundException("Query resulted in no Matches");
if (ParseTimestamp(query) != null)
loadResult.Tracks[0] = loadResult.Tracks[0].WithPosition((TimeSpan)ParseTimestamp(query));
if (withSearchResults && loadResult.LoadType == TrackLoadType.SearchResult)
{
return new MusicActionResponse(tracks: await FullTrackContext.PopulateTracksAsync(loadResult.Tracks));
return new MusicActionResponse(tracks: await FullTrackContext.PopulateTracksAsync(new TrackList(loadResult.Tracks)));
}
if (loadResult.LoadType == TrackLoadType.PlaylistLoaded && !isSearch)
return new MusicActionResponse(
playlist: await _youtubeService.PopulatePlaylistAsync(new YoutubePlaylist(loadResult.PlaylistInfo.Name, await FullTrackContext.PopulateTracksAsync(loadResult.Tracks), uri)));
playlist: await _youtubeService.PopulatePlaylistAsync(
new YoutubePlaylist(loadResult.PlaylistInfo.Name, await FullTrackContext.PopulateTracksAsync(new TrackList(loadResult.Tracks)), ParseListId(query))));
else
return new MusicActionResponse(await FullTrackContext.PopulateAsync(loadResult.Tracks.First()));
return new MusicActionResponse(await FullTrackContext.PopulateAsync(new TomatenMusicTrack(loadResult.Tracks.First())));
}
public async Task<MusicActionResponse> SearchAsync(Uri fileUri)
{
var loadResult = await _audioService.GetTrackAsync(fileUri.ToString());
var loadResult = new TomatenMusicTrack(await _audioService.GetTrackAsync(fileUri.ToString()));
loadResult.Context = new FullTrackContext
{
IsFile = true
@ -79,5 +86,50 @@ namespace TomatenMusic.Music
}
public string ParseListId(string url)
{
var uri = new Uri(url, UriKind.Absolute);
var query = HttpUtility.ParseQueryString(uri.Query);
var videoId = string.Empty;
if (query.AllKeys.Contains("list"))
{
videoId = query["list"];
}
else
{
videoId = uri.Segments.Last();
}
return videoId;
}
public TimeSpan? ParseTimestamp(string url)
{
Uri uri;
try
{
uri = new Uri(url, UriKind.Absolute);
}catch (UriFormatException)
{
return null;
}
var query = HttpUtility.ParseQueryString(uri.Query);
int seconds;
if (query.AllKeys.Contains("t"))
{
seconds = int.Parse(query["t"]);
}
else
return null;
return TimeSpan.FromSeconds(seconds);
}
}
}

View File

@ -12,6 +12,8 @@ using static TomatenMusic.TomatenMusicBot;
using Lavalink4NET.Player;
using Microsoft.Extensions.DependencyInjection;
using Lavalink4NET;
using TomatenMusicCore.Music;
using TomatenMusicCore.Music.Entities;
namespace TomatenMusic.Services
{
@ -37,7 +39,7 @@ namespace TomatenMusic.Services
if (channel.Statistics.SubscriberCount != null)
context.YoutubeAuthorSubs = (ulong) channel.Statistics.SubscriberCount;
context.YoutubeAuthorThumbnail = new Uri(channel.Snippet.Thumbnails.High.Url);
context.YoutubeAuthorThumbnail = new Uri(channel.Snippet.Thumbnails.Default__.Url);
context.YoutubeAuthorUri = new Uri($"https://www.youtube.com/channel/{channel.Id}");
string desc = video.Snippet.Description;
@ -45,7 +47,12 @@ namespace TomatenMusic.Services
if (video.Statistics.LikeCount != null)
context.YoutubeLikes = (ulong) video.Statistics.LikeCount;
context.YoutubeTags = video.Snippet.Tags;
context.YoutubeThumbnail = new Uri(video.Snippet.Thumbnails.High.Url);
try
{
context.YoutubeThumbnail = new Uri(video.Snippet.Thumbnails.High.Url);
}catch (Exception ex) { }
context.YoutubeUploadDate = (DateTime)video.Snippet.PublishedAt;
context.YoutubeViews = (ulong)video.Statistics.ViewCount;
context.YoutubeCommentCount = video.Statistics.CommentCount;
@ -61,7 +68,7 @@ namespace TomatenMusic.Services
return newTracks;
}
public async Task<LavalinkPlaylist> PopulatePlaylistAsync(YoutubePlaylist playlist)
public async Task<ILavalinkPlaylist> PopulatePlaylistAsync(YoutubePlaylist playlist)
{
var list = await GetPlaylistAsync(playlist.Identifier);
var channel = await GetChannelAsync(list.Snippet.ChannelId);
@ -72,10 +79,14 @@ namespace TomatenMusic.Services
if (playlist.Description.Length < 2)
playlist.Description = "None";
playlist.Thumbnail = new Uri(list.Snippet.Thumbnails.High.Url);
try
{
playlist.Thumbnail = new Uri(list.Snippet.Thumbnails.Maxres.Url);
}catch (Exception ex) { }
playlist.AuthorName = channel.Snippet.Title;
playlist.CreationTime = (DateTime)list.Snippet.PublishedAt;
playlist.YoutubeItem = list;
playlist.AuthorThumbnail = new Uri(channel.Snippet.Thumbnails.High.Url);
playlist.AuthorThumbnail = new Uri(channel.Snippet.Thumbnails.Default__.Url);
playlist.AuthorUri = new Uri($"https://www.youtube.com/channels/{channel.Id}");
return playlist;
@ -106,21 +117,28 @@ namespace TomatenMusic.Services
return response.Items.First();
}
public async Task<SearchResult> GetRelatedVideoAsync(string id)
public async Task<IEnumerable<SearchResult>> GetRelatedVideosAsync(string id)
{
var search = Service.Search.List("snippet");
search.RelatedToVideoId = id;
search.Type = "video";
var response = await search.ExecuteAsync();
return response.Items.First(s => s.Snippet != null);
return response.Items.Where(x => x.Snippet != null);
}
public async Task<LavalinkTrack> GetRelatedTrackAsync(string id)
public async Task<TomatenMusicTrack> GetRelatedTrackAsync(string id, List<string> excludeIds)
{
var audioService = TomatenMusicBot.ServiceProvider.GetRequiredService<IAudioService>();
var video = await GetRelatedVideoAsync(id);
var loadResult = await audioService.GetTrackAsync($"https://youtu.be/{video.Id.VideoId}");
var videos = await GetRelatedVideosAsync(id);
SearchResult video = null;
foreach (var vid in videos)
video = videos.First(x => !excludeIds.Contains(x.Id.VideoId));
if (video == null)
video = videos.FirstOrDefault();
var loadResult = new TomatenMusicTrack(await audioService.GetTrackAsync($"https://youtu.be/{video.Id.VideoId}"));
if (loadResult == null)
throw new Exception("An Error occurred while processing the Request");

View File

@ -87,9 +87,9 @@ namespace TomatenMusic
.AddSingleton(
new LavalinkNodeOptions
{
RestUri = "http://116.202.92.16:2333",
RestUri = "http://127.0.0.1:2333",
Password = config.LavaLinkPassword,
WebSocketUri = "ws://116.202.92.16:2333",
WebSocketUri = "ws://127.0.0.1:2333",
AllowResuming = true
})
@ -99,7 +99,8 @@ namespace TomatenMusic
.AddSingleton<YoutubeService>()
.AddSingleton<LyricsOptions>()
.AddSingleton<LyricsService>()
.AddSingleton(SpotifyClientConfig.CreateDefault().WithAuthenticator(new ClientCredentialsAuthenticator(config.SpotifyClientId, config.SpotifyClientSecret))))
.AddSingleton(
SpotifyClientConfig.CreateDefault().WithAuthenticator(new ClientCredentialsAuthenticator(config.SpotifyClientId, config.SpotifyClientSecret))))
.Build();
ServiceProvider = _host.Services;

View File

@ -1,27 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RestoreAdditionalProjectSources>
https://api.nuget.org/v3/index.json;
https://nuget.emzi0767.com/api/v3/index.json
</RestoreAdditionalProjectSources>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DSharpPlus" Version="4.2.0-nightly-01088" />
<PackageReference Include="DSharpPlus.Interactivity" Version="4.2.0-nightly-01084" />
<PackageReference Include="DSharpPlus.SlashCommands" Version="4.2.0-nightly-01088" />
<PackageReference Include="Google.Apis.YouTube.v3" Version="1.56.0.2617" />
<PackageReference Include="DSharpPlus" Version="4.2.0-nightly-01107" />
<PackageReference Include="DSharpPlus.Interactivity" Version="4.2.0-nightly-01107" />
<PackageReference Include="DSharpPlus.SlashCommands" Version="4.2.0-nightly-01107" />
<PackageReference Include="Google.Apis.YouTube.v3" Version="1.57.0.2637" />
<PackageReference Include="HtmlAgilityPack" Version="1.11.42" />
<PackageReference Include="Lavalink4NET" Version="2.1.1" />
<PackageReference Include="Lavalink4NET.DSharpPlus" Version="2.1.1" />
<PackageReference Include="Lavalink4NET.Logging.Microsoft" Version="2.1.1-preview.5" />
<PackageReference Include="Lavalink4NET.Logging.Microsoft" Version="2.1.1-preview.6" />
<PackageReference Include="Lavalink4NET.MemoryCache" Version="2.1.1" />
<PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.2.7" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0-preview.2.22152.2" />
<PackageReference Include="SpotifyAPI.Web" Version="6.2.2" />
<PackageReference Include="SpotifyAPI.Web.Auth" Version="6.2.2" />
</ItemGroup>

View File

@ -20,38 +20,8 @@ namespace TomatenMusic.Util
public static DiscordEmbed AsEmbed(LavalinkTrack track, LoopType loopType, int position = -1)
{
FullTrackContext context = (FullTrackContext)track.Context;
DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
.WithTitle(track.Title)
.AddField("Length", Common.GetTimestamp(track.Duration), true);
if (context.IsFile)
{
builder.WithAuthor(track.Author);
}
else
builder
.WithAuthor(track.Author, context.YoutubeAuthorUri.ToString(), context.YoutubeAuthorThumbnail.ToString())
.WithUrl(context.YoutubeUri)
.WithImageUrl(context.YoutubeThumbnail)
.WithDescription(context.YoutubeDescription);
if (position != -1)
{
builder.AddField("Position", (position == 0 ? "Now Playing" : position.ToString()), true);
}
DiscordEmbedBuilder builder = new DiscordEmbedBuilder(AsEmbed(track, position));
builder.AddField("Current Queue Loop", loopType.ToString(), true);
if (!context.IsFile)
{
builder.AddField("Views", $"{context.YoutubeViews:N0} Views", true);
builder.AddField("Rating", $"{context.YoutubeLikes:N0} 👍", true);
builder.AddField("Upload Date", $"{context.YoutubeUploadDate.ToString("dd. MMMM, yyyy")}", true);
builder.AddField("Comments", context.YoutubeCommentCount == null ? "Comments Disabled" : $"{context.YoutubeCommentCount:N0} Comments", true);
builder.AddField("Channel Subscriptions", $"{context.YoutubeAuthorSubs:N0} Subscribers", true);
}
return builder;
}
@ -61,27 +31,34 @@ namespace TomatenMusic.Util
DiscordEmbedBuilder builder = new DiscordEmbedBuilder()
.WithTitle(track.Title)
.WithUrl(context.YoutubeUri)
.WithImageUrl(context.YoutubeThumbnail)
.WithUrl(track.Source)
.WithDescription(context.YoutubeDescription)
.AddField("Length", Common.GetTimestamp(track.Duration), true);
if (context.YoutubeThumbnail != null)
builder.WithImageUrl(context.YoutubeThumbnail);
if (context.IsFile)
{
builder.WithAuthor(track.Author);
builder.WithUrl(track.Source);
}
else
builder
.WithAuthor(track.Author, context.YoutubeAuthorUri.ToString(), context.YoutubeAuthorThumbnail.ToString())
.WithUrl(context.YoutubeUri);
.WithUrl(track.Source);
if (position != -1)
{
builder.AddField("Position", (position == 0 ? "Now Playing" : position.ToString()), true);
builder.AddField("Queue Position", (position == 0 ? "Now Playing" : position.ToString()), true);
}
if (!context.IsFile)
{
if (track.Position.Seconds > 0)
builder.AddField("Starting Position", GetTimestamp(track.Position), true);
builder.AddField("Views", $"{context.YoutubeViews:N0} Views", true);
builder.AddField("Rating", $"{context.YoutubeLikes:N0} 👍", true);
builder.AddField("Upload Date", $"{context.YoutubeUploadDate.ToString("dd. MMMM, yyyy")}", true);
@ -92,7 +69,7 @@ namespace TomatenMusic.Util
return builder;
}
public static DiscordEmbed AsEmbed(LavalinkPlaylist playlist)
public static DiscordEmbed AsEmbed(ILavalinkPlaylist playlist)
{
DiscordEmbedBuilder builder = new DiscordEmbedBuilder();
@ -100,11 +77,11 @@ namespace TomatenMusic.Util
if (playlist is YoutubePlaylist)
{
YoutubePlaylist youtubePlaylist = (YoutubePlaylist)playlist;
Console.WriteLine($"{playlist.AuthorName}, {playlist.AuthorUri.ToString()}, {playlist.AuthorThumbnail.ToString()}");
builder.WithAuthor(playlist.AuthorName, playlist.AuthorUri.ToString(), youtubePlaylist.AuthorThumbnail.ToString());
builder.WithTitle(playlist.Name);
builder.WithTitle(playlist.Title);
builder.WithUrl(playlist.Url);
builder.WithDescription(TrackListString(playlist.Tracks));
builder.WithDescription(TrackListString(playlist.Tracks, 4000));
builder.WithImageUrl(youtubePlaylist.Thumbnail);
builder.AddField("Description", playlist.Description, false);
builder.AddField("Track Count", $"{playlist.Tracks.Count()} Tracks", true);
@ -115,9 +92,9 @@ namespace TomatenMusic.Util
{
SpotifyPlaylist spotifyPlaylist = (SpotifyPlaylist)playlist;
builder.WithTitle(playlist.Name);
builder.WithTitle(playlist.Title);
builder.WithUrl(playlist.Url);
builder.WithDescription(TrackListString(playlist.Tracks));
builder.WithDescription(TrackListString(playlist.Tracks, 4000));
builder.AddField("Description", playlist.Description, false);
builder.AddField("Track Count", $"{playlist.Tracks.Count()} Tracks", true);
builder.AddField("Length", $"{Common.GetTimestamp(playlist.GetLength())}", true);
@ -136,7 +113,7 @@ namespace TomatenMusic.Util
{
DiscordEmbedBuilder builder = new DiscordEmbedBuilder();
builder.WithDescription(TrackListString(player.PlayerQueue.Queue));
builder.WithDescription(TrackListString(player.PlayerQueue.Queue, 4000));
builder.WithTitle("Current Queue");
builder.WithAuthor($"{player.PlayerQueue.Queue.Count} Songs");
@ -151,29 +128,36 @@ namespace TomatenMusic.Util
builder.AddField("Loop Type", player.PlayerQueue.LoopType.ToString(), true);
builder.AddField("Autoplay", player.Autoplay ? "✅" : "❌", true);
if (player.PlayerQueue.CurrentPlaylist != null)
builder.AddField("Current Playlist", $"[{player.PlayerQueue.CurrentPlaylist.Name}]({player.PlayerQueue.CurrentPlaylist.Url})", true);
builder.AddField("Current Playlist", $"[{player.PlayerQueue.CurrentPlaylist.Title}]({player.PlayerQueue.CurrentPlaylist.Url})", true);
if (player.PlayerQueue.PlayedTracks.Any())
builder.AddField("History", TrackListString(player.PlayerQueue.PlayedTracks), true);
builder.AddField("History", TrackListString(player.PlayerQueue.PlayedTracks, 1000), true);
return builder;
}
public static string TrackListString(IEnumerable<LavalinkTrack> tracks)
public static string TrackListString(IEnumerable<LavalinkTrack> tracks, int maxCharacters)
{
StringBuilder builder = new StringBuilder();
string lastString = " ";
int count = 1;
foreach (LavalinkTrack track in tracks)
{
FullTrackContext context = (FullTrackContext)track.Context;
if (count > 10)
if (builder.ToString().Length > maxCharacters)
{
builder.Append(String.Format("***And {0} more...***", tracks.Count() - 10));
builder = new StringBuilder(lastString);
builder.Append(String.Format("***And {0} more...***", tracks.Count() - count));
break;
}
builder.Append(count).Append(": ").Append($"[{track.Title}]({context.YoutubeUri})").Append(" [").Append(Common.GetTimestamp(track.Duration)).Append("] | ");
builder.Append($"[{track.Author}]({context.YoutubeAuthorUri})").Append("\n\n");
FullTrackContext context = (FullTrackContext)track.Context;
lastString = builder.ToString();
builder.Append(count).Append(": ").Append($"[{track.Title}]({track.Source})").Append(" [").Append(Common.GetTimestamp(track.Duration)).Append("] | ");
builder.Append($"[{track.Author}]({context.YoutubeAuthorUri})");
if (track.Position.Seconds != 0)
builder.Append($" | 🕑");
builder.Append("\n\n");
count++;
}
builder.Append(" ");