Compare commits
20 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
a10a3a5c50 | ||
![]() |
ed33e5d76d | ||
![]() |
021528afd1 | ||
![]() |
05d8af4d0e | ||
![]() |
1536a96dcf | ||
![]() |
b532f19080 | ||
![]() |
8720bf9f88 | ||
![]() |
482a64ac54 | ||
![]() |
fbd8f3566d | ||
![]() |
64bbf0598e | ||
![]() |
370d018c92 | ||
![]() |
9eecccf0e0 | ||
![]() |
7604f7af88 | ||
![]() |
9c162ee934 | ||
![]() |
31ddb54e5a | ||
![]() |
22e2318843 | ||
![]() |
90514e8e62 | ||
![]() |
3bdb592671 | ||
![]() |
6e2f05c9b8 | ||
![]() |
f7f0c90570 |
@@ -4,7 +4,7 @@ branches:
|
||||
regex: ^master$|^main$
|
||||
mode: ContinuousDelivery
|
||||
tag: ''
|
||||
increment: None
|
||||
increment: Minor
|
||||
prevent-increment-of-merged-branch-version: true
|
||||
track-merge-target: false
|
||||
source-branches: [ 'develop', 'release' ]
|
||||
@@ -16,7 +16,7 @@ branches:
|
||||
regex: ^dev(elop)?(ment)?$
|
||||
mode: ContinuousDeployment
|
||||
tag: pre
|
||||
increment: None
|
||||
increment: Patch
|
||||
prevent-increment-of-merged-branch-version: false
|
||||
track-merge-target: true
|
||||
source-branches: []
|
||||
@@ -27,3 +27,7 @@ branches:
|
||||
ignore:
|
||||
sha: []
|
||||
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
|
||||
|
@@ -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();
|
||||
}
|
||||
}
|
||||
|
@@ -27,7 +27,7 @@ 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;
|
||||
}
|
||||
|
7
TomatenMusic/Models/ChannelDisconnectRequest.cs
Normal file
7
TomatenMusic/Models/ChannelDisconnectRequest.cs
Normal file
@@ -0,0 +1,7 @@
|
||||
namespace TomatenMusic_Api.Models.EventArgs
|
||||
{
|
||||
public class ChannelDisconnectRequest
|
||||
{
|
||||
public ulong GuildId { get; set; }
|
||||
}
|
||||
}
|
18
TomatenMusic/Models/EventArgs/ChannelConnectArgs.cs
Normal file
18
TomatenMusic/Models/EventArgs/ChannelConnectArgs.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
13
TomatenMusic/Models/EventArgs/ChannelDisconnectArgs.cs
Normal file
13
TomatenMusic/Models/EventArgs/ChannelDisconnectArgs.cs
Normal 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; }
|
||||
}
|
||||
|
||||
|
||||
}
|
22
TomatenMusic/Models/EventArgs/TrackPlayArgs.cs
Normal file
22
TomatenMusic/Models/EventArgs/TrackPlayArgs.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
10
TomatenMusic/Models/TrackPlayRequest.cs
Normal file
10
TomatenMusic/Models/TrackPlayRequest.cs
Normal 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; }
|
||||
}
|
||||
}
|
@@ -4,11 +4,9 @@ using TomatenMusic_Api.Auth.Services;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddCors();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
|
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -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)
|
||||
|
@@ -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.PlayTracksNowAsync(e.Response.Tracks);
|
||||
else
|
||||
await player.PlayTracksAsync(e.Response.Tracks);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.Response.IsPlaylist)
|
||||
{
|
||||
if (e.Now)
|
||||
await player.PlayPlaylistNowAsync(e.Response.Playlist);
|
||||
else
|
||||
await player.PlayPlaylistAsync(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);
|
||||
}
|
||||
|
||||
|
@@ -4,8 +4,8 @@
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Information"
|
||||
"Default": "Debug",
|
||||
"Microsoft.AspNetCore": "Debug"
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"TOKEN": "Bot_Token",
|
||||
"TOKEN": "TOKEN",
|
||||
"LavaLinkPassword": " ",
|
||||
"SpotifyClientId": " ",
|
||||
"SpotifyClientSecret": " ",
|
||||
|
@@ -5,6 +5,7 @@ using Lavalink4NET.Player;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using TomatenMusic.Commands.Checks;
|
||||
@@ -35,6 +36,8 @@ namespace TomatenMusic.Commands
|
||||
[OnlyGuildCheck]
|
||||
public async Task PlayQueryCommand(InteractionContext ctx, [Option("query", "The song search query.")] string query)
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
|
||||
await ctx.DeferAsync(true);
|
||||
|
||||
GuildPlayer player = (GuildPlayer)_audioService.GetPlayer(ctx.Guild.Id);
|
||||
@@ -50,7 +53,9 @@ namespace TomatenMusic.Commands
|
||||
await ctx.EditResponseAsync(new DiscordWebhookBuilder()
|
||||
.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
|
||||
@@ -66,15 +71,17 @@ namespace TomatenMusic.Commands
|
||||
await ctx.EditResponseAsync(new DiscordWebhookBuilder()
|
||||
.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
|
||||
{
|
||||
if (response.isPlaylist)
|
||||
if (response.IsPlaylist)
|
||||
{
|
||||
LavalinkPlaylist playlist = response.Playlist;
|
||||
ILavalinkPlaylist playlist = response.Playlist;
|
||||
await player.PlayPlaylistNowAsync(playlist);
|
||||
|
||||
_ = ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Now Playing:").AddEmbed(
|
||||
@@ -97,9 +104,13 @@ namespace TomatenMusic.Commands
|
||||
await ctx.EditResponseAsync(new DiscordWebhookBuilder()
|
||||
.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)")]
|
||||
[UserInVoiceChannelCheck]
|
||||
@@ -107,8 +118,9 @@ namespace TomatenMusic.Commands
|
||||
[OnlyGuildCheck]
|
||||
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);
|
||||
|
||||
@@ -123,7 +135,9 @@ namespace TomatenMusic.Commands
|
||||
await ctx.EditResponseAsync(new DiscordWebhookBuilder()
|
||||
.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
|
||||
@@ -138,7 +152,9 @@ namespace TomatenMusic.Commands
|
||||
await ctx.EditResponseAsync(new DiscordWebhookBuilder()
|
||||
.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)));
|
||||
|
||||
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")]
|
||||
@@ -172,7 +190,9 @@ namespace TomatenMusic.Commands
|
||||
[OnlyGuildCheck]
|
||||
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);
|
||||
|
||||
@@ -187,7 +207,9 @@ namespace TomatenMusic.Commands
|
||||
await ctx.EditResponseAsync(new DiscordWebhookBuilder()
|
||||
.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
|
||||
@@ -202,15 +224,17 @@ namespace TomatenMusic.Commands
|
||||
await ctx.EditResponseAsync(new DiscordWebhookBuilder()
|
||||
.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
|
||||
{
|
||||
if (response.isPlaylist)
|
||||
if (response.IsPlaylist)
|
||||
{
|
||||
LavalinkPlaylist playlist = response.Playlist;
|
||||
ILavalinkPlaylist playlist = response.Playlist;
|
||||
await player.PlayPlaylistAsync(playlist);
|
||||
|
||||
await ctx.EditResponseAsync(new DiscordWebhookBuilder().WithContent("Now Playing:").AddEmbed(
|
||||
@@ -233,9 +257,13 @@ namespace TomatenMusic.Commands
|
||||
await ctx.EditResponseAsync(new DiscordWebhookBuilder()
|
||||
.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)")]
|
||||
[UserInVoiceChannelCheck]
|
||||
@@ -243,8 +271,9 @@ namespace TomatenMusic.Commands
|
||||
[OnlyGuildCheck]
|
||||
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);
|
||||
|
||||
@@ -259,7 +288,9 @@ namespace TomatenMusic.Commands
|
||||
await ctx.EditResponseAsync(new DiscordWebhookBuilder()
|
||||
.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
|
||||
@@ -274,7 +305,9 @@ namespace TomatenMusic.Commands
|
||||
await ctx.EditResponseAsync(new DiscordWebhookBuilder()
|
||||
.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)));
|
||||
|
||||
await player.PlayAsync(response.Track);
|
||||
|
||||
sw.Stop();
|
||||
_logger.LogDebug($"Command {ctx.CommandName} took {sw.ElapsedMilliseconds}ms to execute.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -34,7 +34,7 @@ namespace TomatenMusic.Music.Entitites
|
||||
public int SpotifyPopularity { 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;
|
||||
|
||||
@@ -43,12 +43,15 @@ namespace TomatenMusic.Music.Entitites
|
||||
|
||||
var spotifyService = TomatenMusicBot.ServiceProvider.GetRequiredService<ISpotifyService>();
|
||||
var youtubeService = TomatenMusicBot.ServiceProvider.GetRequiredService<YoutubeService>();
|
||||
context.SpotifyIdentifier = spotifyIdentifier;
|
||||
context.YoutubeUri = new Uri($"https://youtu.be/{track.TrackIdentifier}");
|
||||
if (spotifyId != null)
|
||||
context.SpotifyIdentifier = spotifyId;
|
||||
else if (spotifyTrack != null)
|
||||
context.SpotifyIdentifier = spotifyTrack.Id;
|
||||
|
||||
context.YoutubeUri = new Uri(track.Source);
|
||||
track.Context = context;
|
||||
Console.WriteLine(context);
|
||||
await youtubeService.PopulateTrackInfoAsync(track);
|
||||
await spotifyService.PopulateTrackAsync(track);
|
||||
await spotifyService.PopulateTrackAsync(track, spotifyTrack);
|
||||
|
||||
return track;
|
||||
}
|
||||
|
@@ -8,7 +8,7 @@ using Lavalink4NET.Player;
|
||||
|
||||
namespace TomatenMusic.Music.Entitites
|
||||
{
|
||||
public interface LavalinkPlaylist
|
||||
public interface ILavalinkPlaylist
|
||||
{
|
||||
public string Name { get; }
|
||||
public IEnumerable<LavalinkTrack> Tracks { get; }
|
@@ -5,7 +5,7 @@ using System.Text;
|
||||
|
||||
namespace TomatenMusic.Music.Entitites
|
||||
{
|
||||
public class SpotifyPlaylist : LavalinkPlaylist
|
||||
public class SpotifyPlaylist : ILavalinkPlaylist
|
||||
{
|
||||
public string Name { get; }
|
||||
public IEnumerable<LavalinkTrack> Tracks { get; }
|
||||
|
@@ -4,10 +4,12 @@ using System.Text;
|
||||
using System.Linq;
|
||||
using Google.Apis.YouTube.v3.Data;
|
||||
using Lavalink4NET.Player;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using TomatenMusic.Services;
|
||||
|
||||
namespace TomatenMusic.Music.Entitites
|
||||
{
|
||||
public class YoutubePlaylist : LavalinkPlaylist
|
||||
public class YoutubePlaylist : ILavalinkPlaylist
|
||||
{
|
||||
public string Name { get; }
|
||||
|
||||
@@ -26,13 +28,14 @@ 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, IEnumerable<LavalinkTrack> tracks, string id)
|
||||
{
|
||||
Identifier = uri.ToString().Replace("https://www.youtube.com/playlist?list=", "");
|
||||
Identifier = id;
|
||||
Name = name;
|
||||
Tracks = tracks;
|
||||
Url = uri;
|
||||
Url = new Uri($"https://youtube.com/playlist?list={id}");
|
||||
TrackCount = tracks.Count();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -39,9 +39,6 @@ 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)
|
||||
{
|
||||
|
||||
@@ -76,7 +73,7 @@ namespace TomatenMusic.Music
|
||||
QueuePrompt.UpdateFor(GuildId);
|
||||
}
|
||||
|
||||
public async Task PlayTracksAsync(List<LavalinkTrack> tracks)
|
||||
public async Task PlayTracksAsync(IEnumerable<LavalinkTrack> tracks)
|
||||
{
|
||||
EnsureNotDestroyed();
|
||||
EnsureConnected();
|
||||
@@ -114,7 +111,7 @@ namespace TomatenMusic.Music
|
||||
QueuePrompt.UpdateFor(GuildId);
|
||||
}
|
||||
|
||||
public async Task PlayPlaylistAsync(LavalinkPlaylist playlist)
|
||||
public async Task PlayPlaylistAsync(ILavalinkPlaylist playlist)
|
||||
{
|
||||
EnsureNotDestroyed();
|
||||
EnsureConnected();
|
||||
@@ -132,9 +129,8 @@ namespace TomatenMusic.Music
|
||||
QueuePrompt.UpdateFor(GuildId);
|
||||
}
|
||||
|
||||
public async Task PlayPlaylistNowAsync(LavalinkPlaylist playlist)
|
||||
public async Task PlayPlaylistNowAsync(ILavalinkPlaylist playlist)
|
||||
{
|
||||
|
||||
EnsureConnected();
|
||||
EnsureNotDestroyed();
|
||||
if (!PlayerQueue.Queue.Any())
|
||||
@@ -159,8 +155,16 @@ namespace TomatenMusic.Music
|
||||
|
||||
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}");
|
||||
await base.PlayAsync(response.Track);
|
||||
QueuePrompt.UpdateFor(GuildId);
|
||||
@@ -168,6 +172,8 @@ namespace TomatenMusic.Music
|
||||
|
||||
public async Task SkipAsync()
|
||||
{
|
||||
EnsureNotDestroyed();
|
||||
EnsureConnected();
|
||||
MusicActionResponse response = PlayerQueue.NextTrack(true);
|
||||
|
||||
_logger.LogInformation($"Skipped Track {CurrentTrack.Title} for Track {response.Track.Title}");
|
||||
|
@@ -8,15 +8,15 @@ namespace TomatenMusic.Music
|
||||
{
|
||||
public class MusicActionResponse
|
||||
{
|
||||
public LavalinkPlaylist Playlist { get; }
|
||||
public ILavalinkPlaylist 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 bool IsPlaylist { get; }
|
||||
public MusicActionResponse(LavalinkTrack track = null, ILavalinkPlaylist playlist = null, IEnumerable<LavalinkTrack> tracks = null)
|
||||
{
|
||||
Playlist = playlist;
|
||||
Track = track;
|
||||
isPlaylist = playlist != null;
|
||||
IsPlaylist = playlist != null;
|
||||
Tracks = tracks;
|
||||
}
|
||||
}
|
||||
|
@@ -18,7 +18,7 @@ namespace TomatenMusic.Music
|
||||
public Queue<LavalinkTrack> Queue { get; set; } = new Queue<LavalinkTrack>();
|
||||
public Queue<LavalinkTrack> PlayedTracks { get; set; } = new Queue<LavalinkTrack>();
|
||||
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;
|
||||
|
||||
@@ -36,7 +36,7 @@ namespace TomatenMusic.Music
|
||||
QueueLoopList.Add(track);
|
||||
}
|
||||
|
||||
public Task QueuePlaylistAsync(LavalinkPlaylist playlist)
|
||||
public Task QueuePlaylistAsync(ILavalinkPlaylist playlist)
|
||||
{
|
||||
return Task.Run(() =>
|
||||
{
|
||||
@@ -59,7 +59,7 @@ namespace TomatenMusic.Music
|
||||
|
||||
}
|
||||
|
||||
public Task QueueTracksAsync(List<LavalinkTrack> tracks)
|
||||
public Task QueueTracksAsync(IEnumerable<LavalinkTrack> tracks)
|
||||
{
|
||||
return Task.Run(() =>
|
||||
{
|
||||
|
@@ -269,7 +269,10 @@ namespace TomatenMusic.Prompt.Implementation
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -32,7 +32,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()));
|
||||
}
|
||||
|
@@ -87,7 +87,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());
|
||||
|
||||
|
@@ -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()
|
||||
|
@@ -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; }
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
@@ -11,6 +11,7 @@ using TomatenMusic.Services;
|
||||
using TomatenMusic.Music;
|
||||
using Lavalink4NET;
|
||||
using Lavalink4NET.Player;
|
||||
using System.Runtime.Caching;
|
||||
|
||||
namespace TomatenMusic.Services
|
||||
{
|
||||
@@ -18,9 +19,9 @@ namespace TomatenMusic.Services
|
||||
public interface ISpotifyService
|
||||
{
|
||||
public Task<MusicActionResponse> ConvertURL(string url);
|
||||
public Task<SpotifyPlaylist> PopulateSpotifyPlaylistAsync(SpotifyPlaylist playlist);
|
||||
public Task<SpotifyPlaylist> PopulateSpotifyAlbumAsync(SpotifyPlaylist playlist);
|
||||
public Task<LavalinkTrack> PopulateTrackAsync(LavalinkTrack track);
|
||||
public Task<SpotifyPlaylist> PopulateSpotifyPlaylistAsync(SpotifyPlaylist playlist, FullPlaylist spotifyPlaylist = null);
|
||||
public Task<SpotifyPlaylist> PopulateSpotifyAlbumAsync(SpotifyPlaylist playlist, FullAlbum spotifyAlbum = null);
|
||||
public Task<LavalinkTrack> PopulateTrackAsync(LavalinkTrack track, FullTrack spotifyFullTrack = null);
|
||||
|
||||
}
|
||||
|
||||
@@ -29,10 +30,13 @@ namespace TomatenMusic.Services
|
||||
public ILogger _logger { get; set; }
|
||||
public IAudioService _audioService { get; set; }
|
||||
|
||||
public ObjectCache Cache { get; set; }
|
||||
|
||||
public SpotifyService(SpotifyClientConfig config, ILogger<SpotifyService> logger, IAudioService audioService) : base(config)
|
||||
{
|
||||
_logger = logger;
|
||||
_audioService = audioService;
|
||||
Cache = MemoryCache.Default;
|
||||
}
|
||||
|
||||
public async Task<MusicActionResponse> ConvertURL(string url)
|
||||
@@ -43,9 +47,11 @@ namespace TomatenMusic.Services
|
||||
.Replace("https://open.spotify.com/playlist/", "")
|
||||
.Substring(0, 22);
|
||||
|
||||
_logger.LogDebug($"Starting spotify conversion for: {url}");
|
||||
|
||||
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)}");
|
||||
|
||||
@@ -53,39 +59,43 @@ namespace TomatenMusic.Services
|
||||
|
||||
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"))
|
||||
{
|
||||
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))
|
||||
{
|
||||
_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);
|
||||
|
||||
if (track == null) throw new ArgumentException("This Spotify Track was not found on Youtube");
|
||||
|
||||
tracks.Add(await FullTrackContext.PopulateAsync(track, sTrack.Uri.Replace("spotify:track:", "")));
|
||||
|
||||
tracks.Add(await FullTrackContext.PopulateAsync(track, spotifyId: sTrack.Uri.Replace("spotify:track:", "")));
|
||||
}
|
||||
Uri uri;
|
||||
Uri.TryCreate(url, UriKind.Absolute, out 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);
|
||||
|
||||
}
|
||||
else if (url.StartsWith("https://open.spotify.com/playlist"))
|
||||
{
|
||||
|
||||
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))
|
||||
{
|
||||
@@ -98,23 +108,28 @@ namespace TomatenMusic.Services
|
||||
|
||||
if (track == null) throw new ArgumentException("This Spotify Track was not found on Youtube");
|
||||
|
||||
tracks.Add(await FullTrackContext.PopulateAsync(track, fullTrack.Uri.Replace("spotify:track:", "")));
|
||||
tracks.Add(await FullTrackContext.PopulateAsync(track, fullTrack));
|
||||
}
|
||||
|
||||
}
|
||||
Uri uri;
|
||||
Uri.TryCreate(url, UriKind.Absolute, out 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 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;
|
||||
if (list == null)
|
||||
list = await this.Playlists.Get(playlist.Identifier);
|
||||
|
||||
string desc = list.Description;
|
||||
|
||||
playlist.Description = desc.Substring(0, Math.Min(desc.Length, 1024)) + (desc.Length > 1020 ? "..." : " ");
|
||||
@@ -134,9 +149,12 @@ namespace TomatenMusic.Services
|
||||
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;
|
||||
if (list == null)
|
||||
list = await this.Albums.Get(playlist.Identifier);
|
||||
|
||||
string desc = list.Label;
|
||||
|
||||
playlist.Description = desc.Substring(0, Math.Min(desc.Length, 1024)) + (desc.Length > 1020 ? "..." : " ");
|
||||
@@ -148,13 +166,15 @@ namespace TomatenMusic.Services
|
||||
return playlist;
|
||||
}
|
||||
|
||||
public async Task<LavalinkTrack> PopulateTrackAsync(LavalinkTrack track)
|
||||
public async Task<LavalinkTrack> PopulateTrackAsync(LavalinkTrack track, FullTrack spotifyFullTrack)
|
||||
{
|
||||
FullTrackContext context = (FullTrackContext)track.Context;
|
||||
if (context.SpotifyIdentifier == null)
|
||||
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.SpotifyArtists = spotifyTrack.Artists;
|
||||
|
@@ -5,6 +5,7 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using TomatenMusic.Music.Entitites;
|
||||
using TomatenMusic.Services;
|
||||
|
||||
@@ -14,11 +15,13 @@ namespace TomatenMusic.Music
|
||||
{
|
||||
public ISpotifyService _spotifyService { 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;
|
||||
_spotifyService = spotify;
|
||||
_youtubeService = youtubeService;
|
||||
}
|
||||
|
||||
public async Task<MusicActionResponse> SearchAsync(string query, bool withSearchResults = false)
|
||||
@@ -55,7 +58,8 @@ namespace TomatenMusic.Music
|
||||
|
||||
if (loadResult.LoadType == TrackLoadType.PlaylistLoaded && !isSearch)
|
||||
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), ParseListId(query))));
|
||||
else
|
||||
return new MusicActionResponse(await FullTrackContext.PopulateAsync(loadResult.Tracks.First()));
|
||||
|
||||
@@ -77,5 +81,27 @@ namespace TomatenMusic.Music
|
||||
|
||||
}
|
||||
|
||||
public string ParseListId(string url)
|
||||
{
|
||||
var uri = new Uri(url, UriKind.Absolute);
|
||||
|
||||
// you can check host here => uri.Host <= "www.youtube.com"
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
@@ -37,7 +37,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 +45,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;
|
||||
@@ -53,7 +58,7 @@ namespace TomatenMusic.Services
|
||||
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>();
|
||||
foreach (var track in tracks)
|
||||
@@ -61,7 +66,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);
|
||||
@@ -69,14 +74,18 @@ namespace TomatenMusic.Services
|
||||
string desc = list.Snippet.Description;
|
||||
|
||||
playlist.Description = desc.Substring(0, Math.Min(desc.Length, 1024)) + (desc.Length > 1020 ? "..." : " ");
|
||||
if (playlist.Description == "")
|
||||
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.AuthorUri = new Uri($"https://www.youtube.com/playlist?list={playlist.Identifier}");
|
||||
playlist.AuthorThumbnail = new Uri(channel.Snippet.Thumbnails.Default__.Url);
|
||||
playlist.AuthorUri = new Uri($"https://www.youtube.com/channels/{channel.Id}");
|
||||
|
||||
return playlist;
|
||||
}
|
||||
|
@@ -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;
|
||||
|
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
@@ -11,17 +11,17 @@
|
||||
</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-01101" />
|
||||
<PackageReference Include="DSharpPlus.Interactivity" Version="4.2.0-nightly-01101" />
|
||||
<PackageReference Include="DSharpPlus.SlashCommands" Version="4.2.0-nightly-01101" />
|
||||
<PackageReference Include="Google.Apis.YouTube.v3" Version="1.56.0.2630" />
|
||||
<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>
|
||||
|
@@ -92,7 +92,7 @@ namespace TomatenMusic.Util
|
||||
return builder;
|
||||
}
|
||||
|
||||
public static DiscordEmbed AsEmbed(LavalinkPlaylist playlist)
|
||||
public static DiscordEmbed AsEmbed(ILavalinkPlaylist playlist)
|
||||
{
|
||||
|
||||
DiscordEmbedBuilder builder = new DiscordEmbedBuilder();
|
||||
@@ -100,28 +100,28 @@ namespace TomatenMusic.Util
|
||||
if (playlist is YoutubePlaylist)
|
||||
{
|
||||
YoutubePlaylist youtubePlaylist = (YoutubePlaylist)playlist;
|
||||
builder
|
||||
.WithAuthor(playlist.AuthorName, playlist.AuthorUri.ToString(), youtubePlaylist.AuthorThumbnail.ToString())
|
||||
.WithTitle(playlist.Name)
|
||||
.WithUrl(playlist.Url)
|
||||
.WithDescription(TrackListString(playlist.Tracks))
|
||||
.WithImageUrl(youtubePlaylist.Thumbnail)
|
||||
.AddField("Description", playlist.Description, false)
|
||||
.AddField("Track Count", $"{playlist.Tracks.Count()} Tracks", true)
|
||||
.AddField("Length", $"{Common.GetTimestamp(playlist.GetLength())}", true)
|
||||
.AddField("Create Date", $"{youtubePlaylist.CreationTime:dd. MMMM, yyyy}", true);
|
||||
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.WithUrl(playlist.Url);
|
||||
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);
|
||||
builder.AddField("Length", $"{Common.GetTimestamp(playlist.GetLength())}", true);
|
||||
builder.AddField("Create Date", $"{youtubePlaylist.CreationTime:dd. MMMM, yyyy}", true);
|
||||
|
||||
}else if (playlist is SpotifyPlaylist)
|
||||
{
|
||||
SpotifyPlaylist spotifyPlaylist = (SpotifyPlaylist)playlist;
|
||||
builder
|
||||
.WithTitle(playlist.Name)
|
||||
.WithUrl(playlist.Url)
|
||||
.WithDescription(TrackListString(playlist.Tracks))
|
||||
.AddField("Description", playlist.Description, false)
|
||||
.AddField("Track Count", $"{playlist.Tracks.Count()} Tracks", true)
|
||||
.AddField("Length", $"{Common.GetTimestamp(playlist.GetLength())}", true)
|
||||
.AddField("Spotify Followers", $"{spotifyPlaylist.Followers:N0}", true);
|
||||
|
||||
builder.WithTitle(playlist.Name);
|
||||
builder.WithUrl(playlist.Url);
|
||||
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);
|
||||
builder.AddField("Spotify Followers", $"{spotifyPlaylist.Followers:N0}", true);
|
||||
if (spotifyPlaylist.AuthorThumbnail != null)
|
||||
{
|
||||
builder.WithAuthor(playlist.AuthorName, playlist.AuthorUri.ToString(), spotifyPlaylist.AuthorThumbnail.ToString());
|
||||
@@ -136,7 +136,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");
|
||||
|
||||
@@ -150,27 +150,32 @@ namespace TomatenMusic.Util
|
||||
builder.AddField("Length", GetTimestamp(timeSpan), true);
|
||||
builder.AddField("Loop Type", player.PlayerQueue.LoopType.ToString(), 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)
|
||||
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, 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;
|
||||
}
|
||||
|
||||
FullTrackContext context = (FullTrackContext)track.Context;
|
||||
|
||||
lastString = builder.ToString();
|
||||
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");
|
||||
count++;
|
||||
|
Reference in New Issue
Block a user