Merge branch 'dev'

This commit is contained in:
Tim Müller 2022-03-26 11:24:29 +01:00
commit a10a3a5c50
19 changed files with 253 additions and 39 deletions

@ -1,9 +1,12 @@
using DSharpPlus.Entities; using DSharpPlus.Entities;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using TomatenMusic; using TomatenMusic;
using TomatenMusic.Music;
using TomatenMusic_Api; using TomatenMusic_Api;
using TomatenMusic_Api.Auth.Helpers; using TomatenMusic_Api.Auth.Helpers;
using TomatenMusic_Api.Models; using TomatenMusic_Api.Models;
using TomatenMusic_Api.Models.EventArgs;
using static TomatenMusic_Api.InProcessEventBus;
namespace TomatenMusic_Api.Controllers; namespace TomatenMusic_Api.Controllers;
@ -54,8 +57,9 @@ public class PlayerController : ControllerBase
} }
[HttpPost("connect")] [HttpPost("connect")]
public async Task<IActionResult> PostConnection(ChannelConnectRequest request) public async Task<IActionResult> PostConnect(ChannelConnectRequest request)
{ {
try try
{ {
await _tomatenMusicDataService.GetGuildAsync(request.Guild_Id); await _tomatenMusicDataService.GetGuildAsync(request.Guild_Id);
@ -85,7 +89,57 @@ 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(); return Ok();
} }

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

@ -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;
}
}
}

@ -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; }
}
}

@ -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;
}
}
}

@ -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; }
}
}

@ -2,29 +2,30 @@
using Emzi0767.Utilities; using Emzi0767.Utilities;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using TomatenMusic_Api.Models; using TomatenMusic_Api.Models;
using TomatenMusic_Api.Models.EventArgs;
namespace TomatenMusic_Api; namespace TomatenMusic_Api;
public class InProcessEventBus 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); _ = OnConnectRequest?.Invoke(this, e);
} }
public class ChannelConnectEventArgs : AsyncEventArgs public void OnDisconnectRequestEvent(ChannelDisconnectArgs e)
{ {
public ulong Guild_Id { get; set; } _ = 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 public class TomatenMusicDataService : IHostedService
{ {
private ILogger<TomatenMusicDataService> _logger; private ILogger<TomatenMusicDataService> _logger;
public IServiceProvider _serviceProvider { get; set; } = TomatenMusicBot.ServiceProvider; private IServiceProvider _serviceProvider { get; set; } = TomatenMusicBot.ServiceProvider;
public IAudioService _audioService { get; set; } public IAudioService _audioService { get; set; }
public TrackProvider TrackProvider { get; set; }
public TomatenMusicDataService(ILogger<TomatenMusicDataService> logger) public TomatenMusicDataService(ILogger<TomatenMusicDataService> logger)
{ {
_logger = logger; _logger = logger;
_audioService = _serviceProvider.GetRequiredService<IAudioService>(); _audioService = _serviceProvider.GetRequiredService<IAudioService>();
TrackProvider = _serviceProvider.GetRequiredService<TrackProvider>();
} }
public async Task<PlayerConnectionInfo> GetConnectionInfoAsync(ulong guild_id) public async Task<PlayerConnectionInfo> GetConnectionInfoAsync(ulong guild_id)

@ -2,6 +2,7 @@
using TomatenMusic; using TomatenMusic;
using TomatenMusic.Music; using TomatenMusic.Music;
using TomatenMusic_Api.Models; using TomatenMusic_Api.Models;
using TomatenMusic_Api.Models.EventArgs;
using static TomatenMusic_Api.InProcessEventBus; using static TomatenMusic_Api.InProcessEventBus;
namespace TomatenMusic_Api namespace TomatenMusic_Api
@ -24,11 +25,48 @@ namespace TomatenMusic_Api
private void Initialize() private void Initialize()
{ {
_inProcessEventBus.OnConnectRequest += _inProcessEventBus_OnConnectRequest; _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); GuildPlayer player = await _audioService.JoinAsync<GuildPlayer>(e.Guild_Id, e.Channel.Id, true);
} }

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

@ -79,7 +79,7 @@ namespace TomatenMusic.Commands
try try
{ {
if (response.isPlaylist) if (response.IsPlaylist)
{ {
ILavalinkPlaylist playlist = response.Playlist; ILavalinkPlaylist playlist = response.Playlist;
await player.PlayPlaylistNowAsync(playlist); await player.PlayPlaylistNowAsync(playlist);
@ -232,7 +232,7 @@ namespace TomatenMusic.Commands
try try
{ {
if (response.isPlaylist) if (response.IsPlaylist)
{ {
ILavalinkPlaylist playlist = response.Playlist; ILavalinkPlaylist playlist = response.Playlist;
await player.PlayPlaylistAsync(playlist); await player.PlayPlaylistAsync(playlist);

@ -28,12 +28,12 @@ namespace TomatenMusic.Music.Entitites
public Playlist YoutubeItem { get; set; } public Playlist YoutubeItem { get; set; }
public Uri AuthorThumbnail { 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=", "").Replace("https://youtube.com/playlist?list=", ""); Identifier = id;
Name = name; Name = name;
Tracks = tracks; Tracks = tracks;
Url = uri; Url = new Uri($"https://youtube.com/playlist?list={id}");
TrackCount = tracks.Count(); TrackCount = tracks.Count();
} }

@ -39,9 +39,6 @@ namespace TomatenMusic.Music
_spotify = serviceProvider.GetRequiredService<ISpotifyService>(); _spotify = serviceProvider.GetRequiredService<ISpotifyService>();
_audioService = serviceProvider.GetRequiredService<IAudioService>(); _audioService = serviceProvider.GetRequiredService<IAudioService>();
} }
public async override Task PlayAsync(LavalinkTrack track, TimeSpan? startTime = null, TimeSpan? endTime = null, bool noReplace = true) 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); QueuePrompt.UpdateFor(GuildId);
} }
public async Task PlayTracksAsync(List<LavalinkTrack> tracks) public async Task PlayTracksAsync(IEnumerable<LavalinkTrack> tracks)
{ {
EnsureNotDestroyed(); EnsureNotDestroyed();
EnsureConnected(); EnsureConnected();

@ -11,12 +11,12 @@ namespace TomatenMusic.Music
public ILavalinkPlaylist Playlist { get; } public ILavalinkPlaylist Playlist { get; }
public LavalinkTrack Track { get; } public LavalinkTrack Track { get; }
public IEnumerable<LavalinkTrack> Tracks { get; } public IEnumerable<LavalinkTrack> Tracks { get; }
public bool isPlaylist { get; } public bool IsPlaylist { get; }
public MusicActionResponse(LavalinkTrack track = null, ILavalinkPlaylist playlist = null, IEnumerable<LavalinkTrack> tracks = null) public MusicActionResponse(LavalinkTrack track = null, ILavalinkPlaylist playlist = null, IEnumerable<LavalinkTrack> tracks = null)
{ {
Playlist = playlist; Playlist = playlist;
Track = track; Track = track;
isPlaylist = playlist != null; IsPlaylist = playlist != null;
Tracks = tracks; Tracks = tracks;
} }
} }

@ -59,7 +59,7 @@ namespace TomatenMusic.Music
} }
public Task QueueTracksAsync(List<LavalinkTrack> tracks) public Task QueueTracksAsync(IEnumerable<LavalinkTrack> tracks)
{ {
return Task.Run(() => return Task.Run(() =>
{ {

@ -23,6 +23,7 @@ namespace TomatenMusic.Prompt.Model
public List<IPromptOption> Options { get; protected set; } = new List<IPromptOption>(); public List<IPromptOption> Options { get; protected set; } = new List<IPromptOption>();
public DiscordClient _client { get; set; } public DiscordClient _client { get; set; }
public DiscordPromptBase LastPrompt { get; protected set; } public DiscordPromptBase LastPrompt { get; protected set; }
public System.Timers.Timer TimeoutTimer { get; set; }
protected ILogger<DiscordPromptBase> _logger { get; set; } protected ILogger<DiscordPromptBase> _logger { get; set; }
@ -132,6 +133,16 @@ namespace TomatenMusic.Prompt.Model
Interaction = interaction; Interaction = interaction;
Message = await interaction.CreateFollowupMessageAsync(builder); Message = await interaction.CreateFollowupMessageAsync(builder);
State = PromptState.OPEN; 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) public async Task UseAsync(DiscordMessage message)
@ -172,6 +183,22 @@ namespace TomatenMusic.Prompt.Model
Message = message; Message = message;
await EditMessageAsync(builder); await EditMessageAsync(builder);
State = PromptState.OPEN; 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() private void AddGuids()

@ -5,6 +5,7 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Web;
using TomatenMusic.Music.Entitites; using TomatenMusic.Music.Entitites;
using TomatenMusic.Services; using TomatenMusic.Services;
@ -57,7 +58,8 @@ namespace TomatenMusic.Music
if (loadResult.LoadType == TrackLoadType.PlaylistLoaded && !isSearch) if (loadResult.LoadType == TrackLoadType.PlaylistLoaded && !isSearch)
return new MusicActionResponse( 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(loadResult.Tracks), ParseListId(query))));
else else
return new MusicActionResponse(await FullTrackContext.PopulateAsync(loadResult.Tracks.First())); return new MusicActionResponse(await FullTrackContext.PopulateAsync(loadResult.Tracks.First()));
@ -79,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;
}
} }
} }

@ -99,7 +99,8 @@ namespace TomatenMusic
.AddSingleton<YoutubeService>() .AddSingleton<YoutubeService>()
.AddSingleton<LyricsOptions>() .AddSingleton<LyricsOptions>()
.AddSingleton<LyricsService>() .AddSingleton<LyricsService>()
.AddSingleton(SpotifyClientConfig.CreateDefault().WithAuthenticator(new ClientCredentialsAuthenticator(config.SpotifyClientId, config.SpotifyClientSecret)))) .AddSingleton(
SpotifyClientConfig.CreateDefault().WithAuthenticator(new ClientCredentialsAuthenticator(config.SpotifyClientId, config.SpotifyClientSecret))))
.Build(); .Build();
ServiceProvider = _host.Services; ServiceProvider = _host.Services;

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
@ -11,17 +11,17 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="DSharpPlus" Version="4.2.0-nightly-01088" /> <PackageReference Include="DSharpPlus" Version="4.2.0-nightly-01101" />
<PackageReference Include="DSharpPlus.Interactivity" Version="4.2.0-nightly-01084" /> <PackageReference Include="DSharpPlus.Interactivity" Version="4.2.0-nightly-01101" />
<PackageReference Include="DSharpPlus.SlashCommands" Version="4.2.0-nightly-01088" /> <PackageReference Include="DSharpPlus.SlashCommands" Version="4.2.0-nightly-01101" />
<PackageReference Include="Google.Apis.YouTube.v3" Version="1.56.0.2617" /> <PackageReference Include="Google.Apis.YouTube.v3" Version="1.56.0.2630" />
<PackageReference Include="HtmlAgilityPack" Version="1.11.42" /> <PackageReference Include="HtmlAgilityPack" Version="1.11.42" />
<PackageReference Include="Lavalink4NET" Version="2.1.1" /> <PackageReference Include="Lavalink4NET" Version="2.1.1" />
<PackageReference Include="Lavalink4NET.DSharpPlus" 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="Lavalink4NET.MemoryCache" Version="2.1.1" />
<PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.2.7" /> <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" Version="6.2.2" />
<PackageReference Include="SpotifyAPI.Web.Auth" Version="6.2.2" /> <PackageReference Include="SpotifyAPI.Web.Auth" Version="6.2.2" />
</ItemGroup> </ItemGroup>