NadekoBot/NadekoBot.Modules.Music/Services/MusicService.cs

240 lines
8.7 KiB
C#
Raw Normal View History

using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using Discord;
using NadekoBot.Extensions;
2017-05-24 04:43:00 +00:00
using NadekoBot.Services.Database.Models;
using NLog;
using System.IO;
using System.Collections.Generic;
using Discord.Commands;
using Discord.WebSocket;
2017-07-17 19:42:36 +00:00
using NadekoBot.Common;
2017-07-06 17:20:00 +00:00
using NadekoBot.Services.Impl;
2017-07-17 02:37:51 +00:00
using NadekoBot.Services;
using NadekoBot.Modules.Music.Common;
using NadekoBot.Modules.Music.Common.Exceptions;
using NadekoBot.Modules.Music.Common.SongResolver;
2017-07-17 02:37:51 +00:00
namespace NadekoBot.Modules.Music.Services
{
public class MusicService : INService, IUnloadableService
{
2017-05-24 04:43:00 +00:00
public const string MusicDataPath = "data/musicdata";
private readonly IGoogleApiService _google;
2017-05-22 23:59:31 +00:00
private readonly NadekoStrings _strings;
private readonly ILocalization _localization;
private readonly DbService _db;
2017-05-24 04:43:00 +00:00
private readonly Logger _log;
private readonly SoundCloudApiService _sc;
private readonly IBotCredentials _creds;
private readonly ConcurrentDictionary<ulong, float> _defaultVolumes;
private readonly DiscordSocketClient _client;
2017-05-22 23:59:31 +00:00
public ConcurrentDictionary<ulong, MusicPlayer> MusicPlayers { get; } = new ConcurrentDictionary<ulong, MusicPlayer>();
public MusicService(DiscordSocketClient client, IGoogleApiService google,
NadekoStrings strings, ILocalization localization, DbService db,
SoundCloudApiService sc, IBotCredentials creds, NadekoBot bot)
{
_client = client;
_google = google;
2017-05-22 23:59:31 +00:00
_strings = strings;
_localization = localization;
2017-05-24 04:43:00 +00:00
_db = db;
_sc = sc;
_creds = creds;
_log = LogManager.GetCurrentClassLogger();
_client.LeftGuild += _client_LeftGuild;
2017-05-24 04:43:00 +00:00
try { Directory.Delete(MusicDataPath, true); } catch { }
_defaultVolumes = new ConcurrentDictionary<ulong, float>(
bot.AllGuildConfigs
.ToDictionary(x => x.GuildId, x => x.DefaultMusicVolume));
2017-05-24 04:43:00 +00:00
Directory.CreateDirectory(MusicDataPath);
}
public Task Unload()
{
_client.LeftGuild -= _client_LeftGuild;
return Task.CompletedTask;
}
2017-07-07 08:30:19 +00:00
private Task _client_LeftGuild(SocketGuild arg)
{
var t = DestroyPlayer(arg.Id);
return Task.CompletedTask;
}
public float GetDefaultVolume(ulong guildId)
{
return _defaultVolumes.GetOrAdd(guildId, (id) =>
{
using (var uow = _db.UnitOfWork)
{
return uow.GuildConfigs.For(guildId, set => set).DefaultMusicVolume;
}
});
}
public Task<MusicPlayer> GetOrCreatePlayer(ICommandContext context)
{
var gUsr = (IGuildUser)context.User;
var txtCh = (ITextChannel)context.Channel;
var vCh = gUsr.VoiceChannel;
return GetOrCreatePlayer(context.Guild.Id, vCh, txtCh);
}
public async Task<MusicPlayer> GetOrCreatePlayer(ulong guildId, IVoiceChannel voiceCh, ITextChannel textCh)
{
string GetText(string text, params object[] replacements) =>
2017-05-22 23:59:31 +00:00
_strings.GetText(text, _localization.GetCultureInfo(textCh.Guild), "Music".ToLowerInvariant(), replacements);
2017-07-05 16:39:54 +00:00
_log.Info("Checks");
if (voiceCh == null || voiceCh.Guild != textCh.Guild)
{
if (textCh != null)
{
await textCh.SendErrorAsync(GetText("must_be_in_voice")).ConfigureAwait(false);
}
throw new NotInVoiceChannelException();
}
2017-07-05 16:39:54 +00:00
_log.Info("Get or add");
return MusicPlayers.GetOrAdd(guildId, _ =>
{
2017-07-05 16:39:54 +00:00
_log.Info("Getting default volume");
var vol = GetDefaultVolume(guildId);
2017-07-05 16:39:54 +00:00
_log.Info("Creating musicplayer instance");
var mp = new MusicPlayer(this, _google, voiceCh, textCh, vol);
IUserMessage playingMessage = null;
IUserMessage lastFinishedMessage = null;
2017-07-05 16:39:54 +00:00
_log.Info("Subscribing");
mp.OnCompleted += async (s, song) =>
{
try
{
lastFinishedMessage?.DeleteAfter(0);
try
{
lastFinishedMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithAuthor(eab => eab.WithName(GetText("finished_song")).WithMusicIcon())
.WithDescription(song.PrettyName)
.WithFooter(ef => ef.WithText(song.PrettyInfo)))
.ConfigureAwait(false);
}
catch
{
// ignored
}
}
catch
{
// ignored
}
};
mp.OnStarted += async (player, song) =>
{
//try { await mp.UpdateSongDurationsAsync().ConfigureAwait(false); }
//catch
//{
// // ignored
//}
var sender = player;
if (sender == null)
return;
try
{
playingMessage?.DeleteAfter(0);
playingMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithAuthor(eab => eab.WithName(GetText("playing_song", song.Index + 1)).WithMusicIcon())
.WithDescription(song.Song.PrettyName)
.WithFooter(ef => ef.WithText(mp.PrettyVolume + " | " + song.Song.PrettyInfo)))
.ConfigureAwait(false);
}
catch
{
// ignored
}
};
mp.OnPauseChanged += async (player, paused) =>
{
try
{
IUserMessage msg;
if (paused)
msg = await mp.OutputTextChannel.SendConfirmAsync(GetText("paused")).ConfigureAwait(false);
else
msg = await mp.OutputTextChannel.SendConfirmAsync(GetText("resumed")).ConfigureAwait(false);
msg?.DeleteAfter(10);
}
catch
{
// ignored
}
};
2017-07-05 16:39:54 +00:00
_log.Info("Done creating");
return mp;
});
}
public MusicPlayer GetPlayerOrDefault(ulong guildId)
{
if (MusicPlayers.TryGetValue(guildId, out var mp))
return mp;
else
return null;
}
2017-07-08 23:37:17 +00:00
public async Task TryQueueRelatedSongAsync(SongInfo song, ITextChannel txtCh, IVoiceChannel vch)
{
2017-07-08 23:37:17 +00:00
var related = (await _google.GetRelatedVideosAsync(song.VideoId, 4)).ToArray();
if (!related.Any())
return;
var si = await ResolveSong(related[new NadekoRandom().Next(related.Length)], _client.CurrentUser.ToString(), MusicType.YouTube);
if (si == null)
throw new SongNotFoundException();
var mp = await GetOrCreatePlayer(txtCh.GuildId, vch, txtCh);
mp.Enqueue(si);
}
public async Task<SongInfo> ResolveSong(string query, string queuerName, MusicType? musicType = null)
{
query.ThrowIfNull(nameof(query));
2017-07-11 01:16:56 +00:00
ISongResolverFactory resolverFactory = new SongResolverFactory(_sc);
var strategy = await resolverFactory.GetResolveStrategy(query, musicType);
var sinfo = await strategy.ResolveSong(query);
2017-07-11 01:16:56 +00:00
if (sinfo == null)
return null;
2017-07-11 01:16:56 +00:00
sinfo.QueuerName = queuerName;
2017-07-11 01:16:56 +00:00
return sinfo;
}
public async Task DestroyAllPlayers()
{
foreach (var key in MusicPlayers.Keys)
{
await DestroyPlayer(key);
}
}
2017-07-01 06:16:06 +00:00
public async Task DestroyPlayer(ulong id)
2017-05-24 04:43:00 +00:00
{
if (MusicPlayers.TryRemove(id, out var mp))
2017-07-01 06:16:06 +00:00
await mp.Destroy();
2017-05-24 04:43:00 +00:00
}
}
}