13 Commits

Author SHA1 Message Date
EkiciLP
fbd8f3566d Merge branch 'dev' 2022-03-21 22:45:43 +01:00
Tim Müller
64bbf0598e Add Spotify request Caching and more debugging 2022-03-21 22:29:59 +01:00
Tim Müller
370d018c92 Merge branch 'hotfix' into dev 2022-03-21 21:37:02 +01:00
Tim Müller
9eecccf0e0 Merge branch 'master' of https://github.com/EkiciLP/TomatenMusic-V2 2022-03-21 21:31:09 +01:00
Tim Müller
7604f7af88 set to Debug loglevel for error resolving 2022-03-21 21:28:01 +01:00
Tim Müller
9c162ee934 Merge branch 'hotfix' into dev 2022-03-21 21:17:03 +01:00
root
31ddb54e5a Merge branch 'hotfix'
+semver: fix
2022-03-20 19:25:53 +00:00
Tim Müller
22e2318843 fix bot not showing embed on youtube playlist 2022-03-20 20:21:30 +01:00
Tim Müller
90514e8e62 Implemented Card
https://cloud.tomatentum.net/apps/deck/#/board/19/card/229
2022-03-20 18:45:12 +01:00
Tim Müller
3bdb592671 change GitVersion.yml 2022-03-20 18:33:49 +01:00
root
6e2f05c9b8 Merge branch 'dev' 2022-03-20 14:09:03 +00:00
Tim Müller
c9c5a4f892 - fix spotify playlist playback
- fix spotify playlist embed failing due to too long description
- fix not removing current playlist after adding another
- exchanged Description and Tracks field in playlist embed
2022-03-20 15:06:38 +01:00
Tim Müller
f7f0c90570 +semver: patch 2022-03-19 22:38:07 +01:00
14 changed files with 195 additions and 93 deletions

View File

@@ -4,7 +4,7 @@ branches:
regex: ^master$|^main$ regex: ^master$|^main$
mode: ContinuousDelivery mode: ContinuousDelivery
tag: '' tag: ''
increment: None increment: Minor
prevent-increment-of-merged-branch-version: true prevent-increment-of-merged-branch-version: true
track-merge-target: false track-merge-target: false
source-branches: [ 'develop', 'release' ] source-branches: [ 'develop', 'release' ]
@@ -16,7 +16,7 @@ branches:
regex: ^dev(elop)?(ment)?$ regex: ^dev(elop)?(ment)?$
mode: ContinuousDeployment mode: ContinuousDeployment
tag: pre tag: pre
increment: None increment: Patch
prevent-increment-of-merged-branch-version: false prevent-increment-of-merged-branch-version: false
track-merge-target: true track-merge-target: true
source-branches: [] source-branches: []
@@ -27,3 +27,7 @@ branches:
ignore: ignore:
sha: [] sha: []
merge-message-formats: {} merge-message-formats: {}
major-version-bump-message: '\+semver:\s?(breaking|major)'
minor-version-bump-message: '\+semver:\s?(feature|minor)'
patch-version-bump-message: '\+semver:\s?(fix|patch)'
commit-message-incrementing: Enabled

View File

@@ -4,11 +4,9 @@ using TomatenMusic_Api.Auth.Services;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers(); builder.Services.AddControllers();
builder.Services.AddCors(); builder.Services.AddCors();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();

View File

@@ -4,8 +4,8 @@
}, },
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Debug",
"Microsoft.AspNetCore": "Information" "Microsoft.AspNetCore": "Debug"
} }
} }
} }

View File

@@ -5,6 +5,7 @@ using Lavalink4NET.Player;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using TomatenMusic.Commands.Checks; using TomatenMusic.Commands.Checks;
@@ -35,6 +36,8 @@ namespace TomatenMusic.Commands
[OnlyGuildCheck] [OnlyGuildCheck]
public async Task PlayQueryCommand(InteractionContext ctx, [Option("query", "The song search query.")] string query) public async Task PlayQueryCommand(InteractionContext ctx, [Option("query", "The song search query.")] string query)
{ {
var sw = Stopwatch.StartNew();
await ctx.DeferAsync(true); await ctx.DeferAsync(true);
GuildPlayer player = (GuildPlayer)_audioService.GetPlayer(ctx.Guild.Id); GuildPlayer player = (GuildPlayer)_audioService.GetPlayer(ctx.Guild.Id);
@@ -50,7 +53,9 @@ namespace TomatenMusic.Commands
await ctx.EditResponseAsync(new DiscordWebhookBuilder() await ctx.EditResponseAsync(new DiscordWebhookBuilder()
.WithContent($"❌ An error occured while resolving your query: ``{ex.Message}``, ```{ex.StackTrace}```") .WithContent($"❌ An error occured while resolving your query: ``{ex.Message}``, ```{ex.StackTrace}```")
); );
return; sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
return;
} }
try try
@@ -66,7 +71,9 @@ namespace TomatenMusic.Commands
await ctx.EditResponseAsync(new DiscordWebhookBuilder() await ctx.EditResponseAsync(new DiscordWebhookBuilder()
.WithContent($"❌ An error occured while connecting to your Channel: ``{ex.Message}``") .WithContent($"❌ An error occured while connecting to your Channel: ``{ex.Message}``")
); );
return; sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
return;
} }
} }
@@ -97,9 +104,13 @@ namespace TomatenMusic.Commands
await ctx.EditResponseAsync(new DiscordWebhookBuilder() await ctx.EditResponseAsync(new DiscordWebhookBuilder()
.WithContent($"❌ An error occured while playing your Query: ``{ex.Message}``") .WithContent($"❌ An error occured while playing your Query: ``{ex.Message}``")
); );
return; sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
return;
} }
} sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
}
[SlashCommand("file", "Play a song file. (mp3/mp4)")] [SlashCommand("file", "Play a song file. (mp3/mp4)")]
[UserInVoiceChannelCheck] [UserInVoiceChannelCheck]
@@ -107,8 +118,9 @@ namespace TomatenMusic.Commands
[OnlyGuildCheck] [OnlyGuildCheck]
public async Task PlayFileCommand(InteractionContext ctx, [Option("File", "The File that should be played.")] DiscordAttachment file) public async Task PlayFileCommand(InteractionContext ctx, [Option("File", "The File that should be played.")] DiscordAttachment file)
{ {
var sw = Stopwatch.StartNew();
await ctx.DeferAsync(true); await ctx.DeferAsync(true);
GuildPlayer player = (GuildPlayer)_audioService.GetPlayer(ctx.Guild.Id); GuildPlayer player = (GuildPlayer)_audioService.GetPlayer(ctx.Guild.Id);
@@ -123,7 +135,9 @@ namespace TomatenMusic.Commands
await ctx.EditResponseAsync(new DiscordWebhookBuilder() await ctx.EditResponseAsync(new DiscordWebhookBuilder()
.WithContent($"❌ An error occured while resolving your file: ``{ex.Message}``") .WithContent($"❌ An error occured while resolving your file: ``{ex.Message}``")
); );
return; sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
return;
} }
try try
@@ -138,7 +152,9 @@ namespace TomatenMusic.Commands
await ctx.EditResponseAsync(new DiscordWebhookBuilder() await ctx.EditResponseAsync(new DiscordWebhookBuilder()
.WithContent($"❌ An error occured while connecting to your Channel: ``{ex.Message}``") .WithContent($"❌ An error occured while connecting to your Channel: ``{ex.Message}``")
); );
return; sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
return;
} }
} }
@@ -148,7 +164,9 @@ namespace TomatenMusic.Commands
.AddEmbed(Common.AsEmbed(track, player.PlayerQueue.LoopType, 0))); .AddEmbed(Common.AsEmbed(track, player.PlayerQueue.LoopType, 0)));
await player.PlayNowAsync(response.Track); await player.PlayNowAsync(response.Track);
} sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
}
} }
[SlashCommandGroup("play", "Queues or plays the Song")] [SlashCommandGroup("play", "Queues or plays the Song")]
@@ -172,7 +190,9 @@ namespace TomatenMusic.Commands
[OnlyGuildCheck] [OnlyGuildCheck]
public async Task PlayQueryCommand(InteractionContext ctx, [Option("query", "The song search query.")] string query) public async Task PlayQueryCommand(InteractionContext ctx, [Option("query", "The song search query.")] string query)
{ {
await ctx.DeferAsync(true); var sw = Stopwatch.StartNew();
await ctx.DeferAsync(true);
GuildPlayer player = (GuildPlayer)_audioService.GetPlayer(ctx.Guild.Id); GuildPlayer player = (GuildPlayer)_audioService.GetPlayer(ctx.Guild.Id);
@@ -187,7 +207,9 @@ namespace TomatenMusic.Commands
await ctx.EditResponseAsync(new DiscordWebhookBuilder() await ctx.EditResponseAsync(new DiscordWebhookBuilder()
.WithContent($"❌ An error occured while resolving your query: ``{ex.Message}``, ```{ex.StackTrace}```") .WithContent($"❌ An error occured while resolving your query: ``{ex.Message}``, ```{ex.StackTrace}```")
); );
return; sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
return;
} }
try try
@@ -202,18 +224,20 @@ namespace TomatenMusic.Commands
await ctx.EditResponseAsync(new DiscordWebhookBuilder() await ctx.EditResponseAsync(new DiscordWebhookBuilder()
.WithContent($"❌ An error occured while connecting to your Channel: ``{ex.Message}``") .WithContent($"❌ An error occured while connecting to your Channel: ``{ex.Message}``")
); );
return; sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
return;
} }
} }
try try
{ {
if (response.isPlaylist) if (response.isPlaylist)
{ {
LavalinkPlaylist playlist = response.Playlist; LavalinkPlaylist playlist = response.Playlist;
await player.PlayPlaylistAsync(playlist); await player.PlayPlaylistAsync(playlist);
_ = ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Now Playing:").AddEmbed( await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Now Playing:").AddEmbed(
Common.AsEmbed(playlist) Common.AsEmbed(playlist)
)); ));
@@ -231,11 +255,15 @@ namespace TomatenMusic.Commands
catch (Exception ex) catch (Exception ex)
{ {
await ctx.EditResponseAsync(new DiscordWebhookBuilder() await ctx.EditResponseAsync(new DiscordWebhookBuilder()
.WithContent($"❌ An error occured while playing your Track: ``{ex.Message}``") .WithContent($"❌ An error occured while playing your Track: ``{ex.Message}``, ```{ex.StackTrace}```")
); );
return; sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
return;
} }
} sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
}
[SlashCommand("file", "Play a song file. (mp3/mp4)")] [SlashCommand("file", "Play a song file. (mp3/mp4)")]
[UserInVoiceChannelCheck] [UserInVoiceChannelCheck]
@@ -243,8 +271,9 @@ namespace TomatenMusic.Commands
[OnlyGuildCheck] [OnlyGuildCheck]
public async Task PlayFileCommand(InteractionContext ctx, [Option("File", "The File that should be played.")] DiscordAttachment file) public async Task PlayFileCommand(InteractionContext ctx, [Option("File", "The File that should be played.")] DiscordAttachment file)
{ {
var sw = Stopwatch.StartNew();
await ctx.DeferAsync(true); await ctx.DeferAsync(true);
GuildPlayer player = (GuildPlayer)_audioService.GetPlayer(ctx.Guild.Id); GuildPlayer player = (GuildPlayer)_audioService.GetPlayer(ctx.Guild.Id);
@@ -259,7 +288,9 @@ namespace TomatenMusic.Commands
await ctx.EditResponseAsync(new DiscordWebhookBuilder() await ctx.EditResponseAsync(new DiscordWebhookBuilder()
.WithContent($"❌ An error occured while resolving your file: ``{ex.Message}``") .WithContent($"❌ An error occured while resolving your file: ``{ex.Message}``")
); );
return; sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
return;
} }
try try
@@ -274,7 +305,9 @@ namespace TomatenMusic.Commands
await ctx.EditResponseAsync(new DiscordWebhookBuilder() await ctx.EditResponseAsync(new DiscordWebhookBuilder()
.WithContent($"❌ An error occured while connecting to your Channel: ``{ex.Message}``") .WithContent($"❌ An error occured while connecting to your Channel: ``{ex.Message}``")
); );
return; sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
return;
} }
} }
@@ -284,6 +317,9 @@ namespace TomatenMusic.Commands
.AddEmbed(Common.AsEmbed(track, player.PlayerQueue.LoopType, player.State == PlayerState.NotPlaying ? 0 : player.PlayerQueue.Queue.Count + 1))); .AddEmbed(Common.AsEmbed(track, player.PlayerQueue.LoopType, player.State == PlayerState.NotPlaying ? 0 : player.PlayerQueue.Queue.Count + 1)));
await player.PlayAsync(response.Track); await player.PlayAsync(response.Track);
sw.Stop();
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
} }
} }
} }

View File

@@ -34,7 +34,7 @@ namespace TomatenMusic.Music.Entitites
public int SpotifyPopularity { get; set; } public int SpotifyPopularity { get; set; }
public Uri SpotifyUri { get; set; } public Uri SpotifyUri { get; set; }
public static async Task<LavalinkTrack> PopulateAsync(LavalinkTrack track, string spotifyIdentifier = null) public static async Task<LavalinkTrack> PopulateAsync(LavalinkTrack track, FullTrack spotifyTrack = null, string spotifyId = null)
{ {
FullTrackContext context = (FullTrackContext)track.Context; FullTrackContext context = (FullTrackContext)track.Context;
@@ -43,12 +43,15 @@ namespace TomatenMusic.Music.Entitites
var spotifyService = TomatenMusicBot.ServiceProvider.GetRequiredService<ISpotifyService>(); var spotifyService = TomatenMusicBot.ServiceProvider.GetRequiredService<ISpotifyService>();
var youtubeService = TomatenMusicBot.ServiceProvider.GetRequiredService<YoutubeService>(); var youtubeService = TomatenMusicBot.ServiceProvider.GetRequiredService<YoutubeService>();
context.SpotifyIdentifier = spotifyIdentifier; if (spotifyId != null)
context.YoutubeUri = new Uri($"https://youtu.be/{track.TrackIdentifier}"); context.SpotifyIdentifier = spotifyId;
else if (spotifyTrack != null)
context.SpotifyIdentifier = spotifyTrack.Id;
context.YoutubeUri = new Uri(track.Source);
track.Context = context; track.Context = context;
Console.WriteLine(context);
await youtubeService.PopulateTrackInfoAsync(track); await youtubeService.PopulateTrackInfoAsync(track);
await spotifyService.PopulateTrackAsync(track); await spotifyService.PopulateTrackAsync(track, spotifyTrack);
return track; return track;
} }

View File

@@ -4,6 +4,8 @@ using System.Text;
using System.Linq; using System.Linq;
using Google.Apis.YouTube.v3.Data; using Google.Apis.YouTube.v3.Data;
using Lavalink4NET.Player; using Lavalink4NET.Player;
using Microsoft.Extensions.DependencyInjection;
using TomatenMusic.Services;
namespace TomatenMusic.Music.Entitites namespace TomatenMusic.Music.Entitites
{ {
@@ -28,11 +30,12 @@ namespace TomatenMusic.Music.Entitites
public YoutubePlaylist(string name, IEnumerable<LavalinkTrack> tracks, Uri uri) public YoutubePlaylist(string name, IEnumerable<LavalinkTrack> tracks, Uri uri)
{ {
Identifier = uri.ToString().Replace("https://www.youtube.com/playlist?list=", ""); Identifier = uri.ToString().Replace("https://www.youtube.com/playlist?list=", "").Replace("https://youtube.com/playlist?list=", "");
Name = name; Name = name;
Tracks = tracks; Tracks = tracks;
Url = uri; Url = uri;
TrackCount = tracks.Count(); TrackCount = tracks.Count();
} }
} }
} }

View File

@@ -134,7 +134,6 @@ namespace TomatenMusic.Music
public async Task PlayPlaylistNowAsync(LavalinkPlaylist playlist) public async Task PlayPlaylistNowAsync(LavalinkPlaylist playlist)
{ {
EnsureConnected(); EnsureConnected();
EnsureNotDestroyed(); EnsureNotDestroyed();
if (!PlayerQueue.Queue.Any()) if (!PlayerQueue.Queue.Any())
@@ -159,8 +158,16 @@ namespace TomatenMusic.Music
public async Task RewindAsync() public async Task RewindAsync()
{ {
MusicActionResponse response = PlayerQueue.Rewind(); EnsureNotDestroyed();
EnsureConnected();
if (Position.Position.Seconds < 4)
{
await ReplayAsync();
return;
}
MusicActionResponse response = PlayerQueue.Rewind();
_logger.LogInformation($"Rewinded Track {CurrentTrack.Title} for Track {response.Track.Title}"); _logger.LogInformation($"Rewinded Track {CurrentTrack.Title} for Track {response.Track.Title}");
await base.PlayAsync(response.Track); await base.PlayAsync(response.Track);
QueuePrompt.UpdateFor(GuildId); QueuePrompt.UpdateFor(GuildId);
@@ -168,6 +175,8 @@ namespace TomatenMusic.Music
public async Task SkipAsync() public async Task SkipAsync()
{ {
EnsureNotDestroyed();
EnsureConnected();
MusicActionResponse response = PlayerQueue.NextTrack(true); MusicActionResponse response = PlayerQueue.NextTrack(true);
_logger.LogInformation($"Skipped Track {CurrentTrack.Title} for Track {response.Track.Title}"); _logger.LogInformation($"Skipped Track {CurrentTrack.Title} for Track {response.Track.Title}");

View File

@@ -40,8 +40,10 @@ namespace TomatenMusic.Music
{ {
return Task.Run(() => return Task.Run(() =>
{ {
if (CurrentPlaylist == null) if (CurrentPlaylist == null && Queue.Count == 0)
CurrentPlaylist = playlist; CurrentPlaylist = playlist;
else
CurrentPlaylist = null;
_logger.LogInformation("Queued Playlist {0}", playlist.Name); _logger.LogInformation("Queued Playlist {0}", playlist.Name);
foreach (LavalinkTrack track in playlist.Tracks) foreach (LavalinkTrack track in playlist.Tracks)

View File

@@ -269,7 +269,10 @@ namespace TomatenMusic.Prompt.Implementation
protected async override Task<DiscordMessageBuilder> GetMessageAsync() protected async override Task<DiscordMessageBuilder> GetMessageAsync()
{ {
return new DiscordMessageBuilder().AddEmbed(Common.GetQueueEmbed(Player)).AddEmbed(await Common.CurrentSongEmbedAsync(Player)).AddEmbeds(Embeds); return new DiscordMessageBuilder()
.AddEmbed(Common.GetQueueEmbed(Player))
.AddEmbed(await Common.CurrentSongEmbedAsync(Player))
.AddEmbeds(Embeds);
} }
} }
} }

View File

@@ -11,6 +11,7 @@ using TomatenMusic.Services;
using TomatenMusic.Music; using TomatenMusic.Music;
using Lavalink4NET; using Lavalink4NET;
using Lavalink4NET.Player; using Lavalink4NET.Player;
using System.Runtime.Caching;
namespace TomatenMusic.Services namespace TomatenMusic.Services
{ {
@@ -18,9 +19,9 @@ namespace TomatenMusic.Services
public interface ISpotifyService public interface ISpotifyService
{ {
public Task<MusicActionResponse> ConvertURL(string url); public Task<MusicActionResponse> ConvertURL(string url);
public Task<SpotifyPlaylist> PopulateSpotifyPlaylistAsync(SpotifyPlaylist playlist); public Task<SpotifyPlaylist> PopulateSpotifyPlaylistAsync(SpotifyPlaylist playlist, FullPlaylist spotifyPlaylist = null);
public Task<SpotifyPlaylist> PopulateSpotifyAlbumAsync(SpotifyPlaylist playlist); public Task<SpotifyPlaylist> PopulateSpotifyAlbumAsync(SpotifyPlaylist playlist, FullAlbum spotifyAlbum = null);
public Task<LavalinkTrack> PopulateTrackAsync(LavalinkTrack track); public Task<LavalinkTrack> PopulateTrackAsync(LavalinkTrack track, FullTrack spotifyFullTrack = null);
} }
@@ -29,10 +30,13 @@ namespace TomatenMusic.Services
public ILogger _logger { get; set; } public ILogger _logger { get; set; }
public IAudioService _audioService { get; set; } public IAudioService _audioService { get; set; }
public ObjectCache Cache { get; set; }
public SpotifyService(SpotifyClientConfig config, ILogger<SpotifyService> logger, IAudioService audioService) : base(config) public SpotifyService(SpotifyClientConfig config, ILogger<SpotifyService> logger, IAudioService audioService) : base(config)
{ {
_logger = logger; _logger = logger;
_audioService = audioService; _audioService = audioService;
Cache = MemoryCache.Default;
} }
public async Task<MusicActionResponse> ConvertURL(string url) public async Task<MusicActionResponse> ConvertURL(string url)
@@ -43,9 +47,11 @@ namespace TomatenMusic.Services
.Replace("https://open.spotify.com/playlist/", "") .Replace("https://open.spotify.com/playlist/", "")
.Substring(0, 22); .Substring(0, 22);
_logger.LogDebug($"Starting spotify conversion for: {url}");
if (url.StartsWith("https://open.spotify.com/track")) if (url.StartsWith("https://open.spotify.com/track"))
{ {
FullTrack sTrack = await Tracks.Get(trackId); FullTrack sTrack = Cache.Contains(trackId) ? Cache.Get(trackId) as FullTrack : await Tracks.Get(trackId);
_logger.LogInformation($"Searching youtube from spotify with query: {sTrack.Name} {String.Join(" ", sTrack.Artists)}"); _logger.LogInformation($"Searching youtube from spotify with query: {sTrack.Name} {String.Join(" ", sTrack.Artists)}");
@@ -53,39 +59,43 @@ namespace TomatenMusic.Services
if (track == null) throw new ArgumentException("This Spotify Track was not found on Youtube"); if (track == null) throw new ArgumentException("This Spotify Track was not found on Youtube");
return new MusicActionResponse(await FullTrackContext.PopulateAsync(track, trackId)); Cache.Add(trackId, sTrack, DateTimeOffset.MaxValue);
return new MusicActionResponse(await FullTrackContext.PopulateAsync(track, sTrack));
} }
else if (url.StartsWith("https://open.spotify.com/album")) else if (url.StartsWith("https://open.spotify.com/album"))
{ {
List<LavalinkTrack> tracks = new List<LavalinkTrack>(); List<LavalinkTrack> tracks = new List<LavalinkTrack>();
FullAlbum album = await Albums.Get(trackId); FullAlbum album = Cache.Contains(trackId) ? Cache.Get(trackId) as FullAlbum : await Albums.Get(trackId);
foreach (var sTrack in await PaginateAll(album.Tracks)) 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))}"); _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 = 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"); if (track == null) throw new ArgumentException("This Spotify Track was not found on Youtube");
tracks.Add(await FullTrackContext.PopulateAsync(track, sTrack.Uri)); tracks.Add(await FullTrackContext.PopulateAsync(track, spotifyId: sTrack.Uri.Replace("spotify:track:", "")));
} }
Uri uri; Uri uri;
Uri.TryCreate(url, UriKind.Absolute, out uri); Uri.TryCreate(url, UriKind.Absolute, out uri);
SpotifyPlaylist playlist = new SpotifyPlaylist(album.Name, album.Id, tracks, uri); SpotifyPlaylist playlist = new SpotifyPlaylist(album.Name, album.Id, tracks, uri);
await PopulateSpotifyAlbumAsync(playlist); await PopulateSpotifyAlbumAsync(playlist, album);
Cache.Add(trackId, album, DateTimeOffset.MaxValue);
return new MusicActionResponse(playlist: playlist); return new MusicActionResponse(playlist: playlist);
} }
else if (url.StartsWith("https://open.spotify.com/playlist")) else if (url.StartsWith("https://open.spotify.com/playlist"))
{ {
List<LavalinkTrack> tracks = new List<LavalinkTrack>(); List<LavalinkTrack> tracks = new List<LavalinkTrack>();
FullPlaylist spotifyPlaylist = await Playlists.Get(trackId); FullPlaylist spotifyPlaylist = Cache.Contains(trackId) ? Cache.Get(trackId) as FullPlaylist : await Playlists.Get(trackId);
foreach (var sTrack in await PaginateAll(spotifyPlaylist.Tracks)) foreach (var sTrack in await PaginateAll(spotifyPlaylist.Tracks))
{ {
@@ -98,56 +108,78 @@ namespace TomatenMusic.Services
if (track == null) throw new ArgumentException("This Spotify Track was not found on Youtube"); if (track == null) throw new ArgumentException("This Spotify Track was not found on Youtube");
tracks.Add(await FullTrackContext.PopulateAsync(track, fullTrack.Uri)); tracks.Add(await FullTrackContext.PopulateAsync(track, fullTrack));
} }
} }
Uri uri; Uri uri;
Uri.TryCreate(url, UriKind.Absolute, out uri); Uri.TryCreate(url, UriKind.Absolute, out uri);
SpotifyPlaylist playlist = new SpotifyPlaylist(spotifyPlaylist.Name, spotifyPlaylist.Id, tracks, uri); SpotifyPlaylist playlist = new SpotifyPlaylist(spotifyPlaylist.Name, spotifyPlaylist.Id, tracks, uri);
await PopulateSpotifyPlaylistAsync(playlist); await PopulateSpotifyPlaylistAsync(playlist, spotifyPlaylist);
Cache.Add(trackId, spotifyPlaylist, DateTimeOffset.MaxValue);
return new MusicActionResponse(playlist: playlist); return new MusicActionResponse(playlist: playlist);
} }
return null; return null;
} }
public async Task<SpotifyPlaylist> PopulateSpotifyPlaylistAsync(SpotifyPlaylist playlist) public async Task<SpotifyPlaylist> PopulateSpotifyPlaylistAsync(SpotifyPlaylist playlist, FullPlaylist spotifyPlaylist = null)
{ {
var list = await this.Playlists.Get(playlist.Identifier); FullPlaylist list = spotifyPlaylist;
playlist.Description = list.Description; if (list == null)
playlist.AuthorUri = new Uri(list.Owner.Uri); list = await this.Playlists.Get(playlist.Identifier);
string desc = list.Description;
playlist.Description = desc.Substring(0, Math.Min(desc.Length, 1024)) + (desc.Length > 1020 ? "..." : " ");
if (playlist.Description.Length < 2)
playlist.Description = "None";
playlist.AuthorUri = new Uri($"https://open.spotify.com/user/{list.Owner.Id}");
playlist.AuthorName = list.Owner.DisplayName; playlist.AuthorName = list.Owner.DisplayName;
playlist.Followers = list.Followers.Total; playlist.Followers = list.Followers.Total;
playlist.Url = new Uri(list.Uri); playlist.Url = new Uri($"https://open.spotify.com/playlist/{playlist.Identifier}");
playlist.AuthorThumbnail = new Uri(list.Owner.Images.First().Url); try
{
playlist.AuthorThumbnail = new Uri(list.Owner.Images.First().Url);
}
catch (Exception ex) { }
return playlist; return playlist;
} }
public async Task<SpotifyPlaylist> PopulateSpotifyAlbumAsync(SpotifyPlaylist playlist) public async Task<SpotifyPlaylist> PopulateSpotifyAlbumAsync(SpotifyPlaylist playlist, FullAlbum spotifyAlbum = null)
{ {
var list = await this.Albums.Get(playlist.Identifier); FullAlbum list = spotifyAlbum;
playlist.Description = list.Label; if (list == null)
playlist.AuthorUri = new Uri(list.Artists.First().Uri); list = await this.Albums.Get(playlist.Identifier);
string desc = list.Label;
playlist.Description = desc.Substring(0, Math.Min(desc.Length, 1024)) + (desc.Length > 1020 ? "..." : " ");
playlist.AuthorUri = new Uri($"https://open.spotify.com/user/{list.Artists.First().Uri}");
playlist.AuthorName = list.Artists.First().Name; playlist.AuthorName = list.Artists.First().Name;
playlist.Followers = list.Popularity; playlist.Followers = list.Popularity;
playlist.Url = new Uri(list.Uri); playlist.Url = new Uri($"https://open.spotify.com/album/{playlist.Identifier}");
return playlist; return playlist;
} }
public async Task<LavalinkTrack> PopulateTrackAsync(LavalinkTrack track) public async Task<LavalinkTrack> PopulateTrackAsync(LavalinkTrack track, FullTrack spotifyFullTrack)
{ {
FullTrackContext context = (FullTrackContext)track.Context; FullTrackContext context = (FullTrackContext)track.Context;
if (context.SpotifyIdentifier == null) if (context.SpotifyIdentifier == null)
return track; return track;
var spotifyTrack = await this.Tracks.Get(context.SpotifyIdentifier); FullTrack spotifyTrack = spotifyFullTrack;
if (spotifyTrack == null)
spotifyTrack = await Tracks.Get(context.SpotifyIdentifier);
context.SpotifyAlbum = spotifyTrack.Album; context.SpotifyAlbum = spotifyTrack.Album;
context.SpotifyArtists = spotifyTrack.Artists; context.SpotifyArtists = spotifyTrack.Artists;
context.SpotifyPopularity = spotifyTrack.Popularity; context.SpotifyPopularity = spotifyTrack.Popularity;
context.SpotifyUri = new Uri(spotifyTrack.Uri); context.SpotifyUri = new Uri($"https://open.spotify.com/track/{context.SpotifyIdentifier}");
track.Context = context; track.Context = context;
return track; return track;

View File

@@ -14,11 +14,13 @@ namespace TomatenMusic.Music
{ {
public ISpotifyService _spotifyService { get; set; } public ISpotifyService _spotifyService { get; set; }
public IAudioService _audioService { get; set; } public IAudioService _audioService { get; set; }
public YoutubeService _youtubeService { get; set; }
public TrackProvider(ISpotifyService spotify, IAudioService audioService) public TrackProvider(ISpotifyService spotify, IAudioService audioService, YoutubeService youtubeService)
{ {
_audioService = audioService; _audioService = audioService;
_spotifyService = spotify; _spotifyService = spotify;
_youtubeService = youtubeService;
} }
public async Task<MusicActionResponse> SearchAsync(string query, bool withSearchResults = false) public async Task<MusicActionResponse> SearchAsync(string query, bool withSearchResults = false)
@@ -55,7 +57,7 @@ namespace TomatenMusic.Music
if (loadResult.LoadType == TrackLoadType.PlaylistLoaded && !isSearch) if (loadResult.LoadType == TrackLoadType.PlaylistLoaded && !isSearch)
return new MusicActionResponse( return new MusicActionResponse(
playlist: new YoutubePlaylist(loadResult.PlaylistInfo.Name, await FullTrackContext.PopulateTracksAsync(loadResult.Tracks), uri)); playlist: await _youtubeService.PopulatePlaylistAsync(new YoutubePlaylist(loadResult.PlaylistInfo.Name, await FullTrackContext.PopulateTracksAsync(loadResult.Tracks), uri)));
else else
return new MusicActionResponse(await FullTrackContext.PopulateAsync(loadResult.Tracks.First())); return new MusicActionResponse(await FullTrackContext.PopulateAsync(loadResult.Tracks.First()));

View File

@@ -39,7 +39,9 @@ namespace TomatenMusic.Services
context.YoutubeAuthorSubs = (ulong) channel.Statistics.SubscriberCount; context.YoutubeAuthorSubs = (ulong) channel.Statistics.SubscriberCount;
context.YoutubeAuthorThumbnail = new Uri(channel.Snippet.Thumbnails.High.Url); context.YoutubeAuthorThumbnail = new Uri(channel.Snippet.Thumbnails.High.Url);
context.YoutubeAuthorUri = new Uri($"https://www.youtube.com/channel/{channel.Id}"); context.YoutubeAuthorUri = new Uri($"https://www.youtube.com/channel/{channel.Id}");
context.YoutubeDescription = video.Snippet.Description; string desc = video.Snippet.Description;
context.YoutubeDescription = desc.Substring(0, Math.Min(desc.Length, 1024)) + (desc.Length > 1020 ? "..." : " ");
if (video.Statistics.LikeCount != null) if (video.Statistics.LikeCount != null)
context.YoutubeLikes = (ulong) video.Statistics.LikeCount; context.YoutubeLikes = (ulong) video.Statistics.LikeCount;
context.YoutubeTags = video.Snippet.Tags; context.YoutubeTags = video.Snippet.Tags;
@@ -51,7 +53,7 @@ namespace TomatenMusic.Services
return track; return track;
} }
public async Task<List<LavalinkTrack>> PopulateMultiTrackListAsync(IEnumerable<LavalinkTrack> tracks) public async Task<List<LavalinkTrack>> PopulateTrackListAsync(IEnumerable<LavalinkTrack> tracks)
{ {
List<LavalinkTrack> newTracks = new List<LavalinkTrack>(); List<LavalinkTrack> newTracks = new List<LavalinkTrack>();
foreach (var track in tracks) foreach (var track in tracks)
@@ -66,12 +68,15 @@ namespace TomatenMusic.Services
string desc = list.Snippet.Description; string desc = list.Snippet.Description;
playlist.Description = desc.Substring(0, Math.Min(desc.Length, 4092)) + (desc.Length > 4092 ? "..." : " "); playlist.Description = desc.Substring(0, Math.Min(desc.Length, 1024)) + (desc.Length > 1020 ? "..." : " ");
if (playlist.Description.Length < 2)
playlist.Description = "None";
playlist.Thumbnail = new Uri(list.Snippet.Thumbnails.High.Url); playlist.Thumbnail = new Uri(list.Snippet.Thumbnails.High.Url);
playlist.CreationTime = (DateTime)list.Snippet.PublishedAt; playlist.CreationTime = (DateTime)list.Snippet.PublishedAt;
playlist.YoutubeItem = list; playlist.YoutubeItem = list;
playlist.AuthorThumbnail = new Uri(channel.Snippet.Thumbnails.High.Url); playlist.AuthorThumbnail = new Uri(channel.Snippet.Thumbnails.High.Url);
playlist.AuthorUri = new Uri($"https://www.youtube.com/playlist?list={playlist.Identifier}"); playlist.AuthorUri = new Uri($"https://www.youtube.com/channels/{channel.Id}");
return playlist; return playlist;
} }

View File

@@ -186,7 +186,7 @@ namespace TomatenMusic
if (e.Exception is NotFoundException) if (e.Exception is NotFoundException)
logger.LogDebug($"{ ((NotFoundException)e.Exception).JsonMessage }"); logger.LogDebug($"{ ((NotFoundException)e.Exception).JsonMessage }");
if (e.Exception is BadRequestException) if (e.Exception is BadRequestException)
logger.LogDebug($"{ ((BadRequestException)e.Exception).JsonMessage }"); logger.LogInformation($"{ ((BadRequestException)e.Exception).Errors }");
return Task.CompletedTask; return Task.CompletedTask;
} }

View File

@@ -100,32 +100,36 @@ namespace TomatenMusic.Util
if (playlist is YoutubePlaylist) if (playlist is YoutubePlaylist)
{ {
YoutubePlaylist youtubePlaylist = (YoutubePlaylist)playlist; YoutubePlaylist youtubePlaylist = (YoutubePlaylist)playlist;
builder
.WithAuthor(playlist.AuthorName, playlist.AuthorUri.ToString(), youtubePlaylist.AuthorThumbnail.ToString()) builder.WithAuthor(playlist.AuthorName, playlist.AuthorUri.ToString(), youtubePlaylist.AuthorThumbnail.ToString());
.WithTitle(playlist.Name) builder.WithTitle(playlist.Name);
.WithUrl(playlist.Url) builder.WithUrl(playlist.Url);
.WithDescription(playlist.Description) builder.WithDescription(TrackListString(playlist.Tracks));
.WithImageUrl(youtubePlaylist.Thumbnail) builder.WithImageUrl(youtubePlaylist.Thumbnail);
.AddField("Tracks", TrackListString(playlist.Tracks), false) builder.AddField("Description", playlist.Description, false);
.AddField("Track Count", $"{playlist.Tracks.Count()} Tracks", true) builder.AddField("Track Count", $"{playlist.Tracks.Count()} Tracks", true);
.AddField("Length", $"{Common.GetTimestamp(playlist.GetLength())}", true) builder.AddField("Length", $"{Common.GetTimestamp(playlist.GetLength())}", true);
.AddField("Create Date", $"{youtubePlaylist.CreationTime:dd. MMMM, yyyy}", true); builder.AddField("Create Date", $"{youtubePlaylist.CreationTime:dd. MMMM, yyyy}", true);
}else if (playlist is SpotifyPlaylist) }else if (playlist is SpotifyPlaylist)
{ {
SpotifyPlaylist spotifyPlaylist = (SpotifyPlaylist)playlist; SpotifyPlaylist spotifyPlaylist = (SpotifyPlaylist)playlist;
builder
.WithAuthor(playlist.AuthorName, playlist.AuthorUri.ToString(), spotifyPlaylist.AuthorThumbnail.ToString()) builder.WithTitle(playlist.Name);
.WithTitle(playlist.Name) builder.WithUrl(playlist.Url);
.WithUrl(playlist.Url) builder.WithDescription(TrackListString(playlist.Tracks));
.WithDescription(playlist.Description) builder.AddField("Description", playlist.Description, false);
.AddField("Tracks", TrackListString(playlist.Tracks), false) builder.AddField("Track Count", $"{playlist.Tracks.Count()} Tracks", true);
.AddField("Track Count", $"{playlist.Tracks.Count()} Tracks", true) builder.AddField("Length", $"{Common.GetTimestamp(playlist.GetLength())}", true);
.AddField("Length", $"{Common.GetTimestamp(playlist.GetLength())}", true) builder.AddField("Spotify Followers", $"{spotifyPlaylist.Followers:N0}", true);
.AddField("Spotify Followers", $"{spotifyPlaylist.Followers:N0}", true); if (spotifyPlaylist.AuthorThumbnail != null)
{
builder.WithAuthor(playlist.AuthorName, playlist.AuthorUri.ToString(), spotifyPlaylist.AuthorThumbnail.ToString());
}else
builder.WithAuthor(playlist.AuthorName, playlist.AuthorUri.ToString());
} }
return builder; return builder.Build();
} }
public static DiscordEmbed GetQueueEmbed(GuildPlayer player) public static DiscordEmbed GetQueueEmbed(GuildPlayer player)
@@ -146,11 +150,12 @@ namespace TomatenMusic.Util
builder.AddField("Length", GetTimestamp(timeSpan), true); builder.AddField("Length", GetTimestamp(timeSpan), true);
builder.AddField("Loop Type", player.PlayerQueue.LoopType.ToString(), true); builder.AddField("Loop Type", player.PlayerQueue.LoopType.ToString(), true);
builder.AddField("Autoplay", player.Autoplay ? "✅" : "❌", true); builder.AddField("Autoplay", player.Autoplay ? "✅" : "❌", true);
if (player.PlayerQueue.PlayedTracks.Any())
builder.AddField("History", TrackListString(player.PlayerQueue.PlayedTracks), true);
if (player.PlayerQueue.CurrentPlaylist != null) 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.Name}]({player.PlayerQueue.CurrentPlaylist.Url})", true);
if (player.PlayerQueue.PlayedTracks.Any())
builder.AddField("History", TrackListString(player.PlayerQueue.PlayedTracks), true);
return builder; return builder;
} }
@@ -161,9 +166,9 @@ namespace TomatenMusic.Util
foreach (LavalinkTrack track in tracks) foreach (LavalinkTrack track in tracks)
{ {
FullTrackContext context = (FullTrackContext)track.Context; FullTrackContext context = (FullTrackContext)track.Context;
if (count > 15) if (count > 10)
{ {
builder.Append(String.Format("***And {0} more...***", tracks.Count() - 15)); builder.Append(String.Format("***And {0} more...***", tracks.Count() - 10));
break; break;
} }