diff --git a/src/iTool.DiscordBot/Bot.cs b/src/iTool.DiscordBot/Bot.cs index 5641f61..c79f0c6 100644 --- a/src/iTool.DiscordBot/Bot.cs +++ b/src/iTool.DiscordBot/Bot.cs @@ -65,9 +65,7 @@ public async Task StartAsync() IServiceCollection serviceCollection = new ServiceCollection() .AddSingleton(_loggerFactory) .AddLogging() - .AddSingleton(_settings) - .AddSingleton(typeof(AudioService)) - .AddSingleton(typeof(AudioFileService)); + .AddSingleton(_settings); if (string.IsNullOrEmpty(_settings.SteamKey)) { diff --git a/src/iTool.DiscordBot/Databases/TagDatabase.cs b/src/iTool.DiscordBot/Databases/TagDatabase.cs index 8849b74..032de0f 100644 --- a/src/iTool.DiscordBot/Databases/TagDatabase.cs +++ b/src/iTool.DiscordBot/Databases/TagDatabase.cs @@ -23,15 +23,14 @@ protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) } public Task GetTagAsync(ulong guildID, string name) - => Tags.AsQueryable() - .FirstOrDefaultAsync(x => x.GuildID == guildID && string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)); + => Tags.FirstOrDefaultAsync(x => x.GuildID == guildID && string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)); public IQueryable GetTags(ulong guildID) - => Tags.AsQueryable().Where(x => x.GuildID == guildID); + => Tags.Where(x => x.GuildID == guildID); public async Task CreateTagAsync(SocketCommandContext context, string name, string content, string attachment = null) { - if (await Tags.AsQueryable().AnyAsync( + if (await Tags.AsNoTracking().AnyAsync( x => x.GuildID == context.Guild.Id && string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)).ConfigureAwait(false)) { throw new ArgumentException($"The tag `{name}` already exists."); @@ -50,16 +49,12 @@ public async Task CreateTagAsync(SocketCommandContext context, string name, stri public async Task DeleteTagAsync(SocketCommandContext context, string name) { - Tag tag = await Tags.AsQueryable() - .FirstOrDefaultAsync(x => x.GuildID == context.Guild.Id && string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)).ConfigureAwait(false); - - if (tag == null) - { - throw new ArgumentException($"The tag `{name}` does not exist."); - } + Tag tag = await Tags + .FirstOrDefaultAsync(x => x.GuildID == context.Guild.Id && string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)).ConfigureAwait(false) + ?? throw new ArgumentException($"The tag `{name}` does not exist."); var user = (SocketGuildUser)context.User; - if (tag.AuthorID != user.Id && !user.GuildPermissions.ManageMessages) + if (tag.AuthorID != user.Id && !user.GuildPermissions.ManageMessages) { throw new UnauthorizedAccessException($"You are not the owner of the tag `{name}`."); } diff --git a/src/iTool.DiscordBot/Helpers/AudioFile.cs b/src/iTool.DiscordBot/Helpers/AudioFile.cs deleted file mode 100644 index a7fdd82..0000000 --- a/src/iTool.DiscordBot/Helpers/AudioFile.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace iTool.DiscordBot -{ - public class AudioFile - { - public string FileName { get; set; } - public string[] Names { get; set; } - } -} diff --git a/src/iTool.DiscordBot/Modules/AudioModule.cs b/src/iTool.DiscordBot/Modules/AudioModule.cs deleted file mode 100644 index 617f546..0000000 --- a/src/iTool.DiscordBot/Modules/AudioModule.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Threading.Tasks; -using Discord; -using Discord.Commands; - -namespace iTool.DiscordBot.Modules -{ - [RequireContext(ContextType.Guild)] - public sealed class AudioModule : ModuleBase - { - private readonly AudioService _audioService; - private readonly AudioFileService _fileService; - - public AudioModule(AudioService audioService, AudioFileService fileService) - { - _audioService = audioService; - _fileService = fileService; - } - - [Command("join", RunMode = RunMode.Async)] - [Summary("Joins the voice channel")] - public Task Join() - => _audioService.JoinAudio(Context.Guild, (Context.User as IGuildUser).VoiceChannel); - - [Command("stop", RunMode = RunMode.Async)] - [Summary("Stops the audio playback and leaves the voice channel")] - public Task Stop() - => _audioService.LeaveAudio(Context.Guild); - - [Command("play", RunMode = RunMode.Async)] - [Summary("Plays an audio file")] - public async Task Play([Remainder] string song) - { - string path = _fileService.GetSong(song); - if (path == null) - { - return; - } - - await _audioService.JoinAudio(Context.Guild, (Context.User as IGuildUser).VoiceChannel).ConfigureAwait(false); - await _audioService.SendAudioAsync(Context.Guild, path).ConfigureAwait(false); - await _audioService.LeaveAudio(Context.Guild).ConfigureAwait(false); - } - } -} diff --git a/src/iTool.DiscordBot/Services/AudioFileService.cs b/src/iTool.DiscordBot/Services/AudioFileService.cs deleted file mode 100644 index 9881dd4..0000000 --- a/src/iTool.DiscordBot/Services/AudioFileService.cs +++ /dev/null @@ -1,71 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Nett; -using Microsoft.Extensions.Logging; - -namespace iTool.DiscordBot -{ - // TODO: Rework - public class AudioFileService - { - private IEnumerable _audioFiles; - private readonly ILogger _logger; - - public AudioFileService(ILogger logger) - { - _logger = logger; - LoadSongs(); - } - - public void LoadSongs() - { - if (!File.Exists(Common.AudioIndexFile)) - { - ResetAudioIndex(); - } - - try - { - _audioFiles = Toml.ReadFile>(Common.AudioIndexFile); // Temporary workaround - } - catch (Exception ex) - { - _logger.LogError(ex, "Error reading audio index file"); - } - } - - public string GetSong(string name) - { - string filename = _audioFiles.FirstOrDefault(x => x.Names.Contains(name))?.FileName; - if (string.IsNullOrEmpty(filename)) - { - return null; - } - - string path = Path.Combine(Common.AudioDir, filename); - if (!File.Exists(path)) - { - return null; - } - - return path; - } - - public static void ResetAudioIndex() - { - Directory.CreateDirectory(Common.AudioDir); - - Toml.WriteFile(new AudioFile[] - { - new AudioFile() - { - FileName = string.Empty, - Names = new string[] { string.Empty } - } - } - , Common.AudioIndexFile); - } - } -} diff --git a/src/iTool.DiscordBot/Services/AudioService.cs b/src/iTool.DiscordBot/Services/AudioService.cs deleted file mode 100644 index dc68e1d..0000000 --- a/src/iTool.DiscordBot/Services/AudioService.cs +++ /dev/null @@ -1,79 +0,0 @@ -using System.Collections.Concurrent; -using System.Diagnostics; -using System.IO; -using System.Runtime.InteropServices; -using System.Threading.Tasks; -using Discord; -using Discord.Audio; -using Microsoft.Extensions.Logging; - -namespace iTool.DiscordBot -{ - public class AudioService - { - private readonly ConcurrentDictionary _connectedChannels = new ConcurrentDictionary(); - private readonly ILogger _logger; - - public AudioService(ILogger logger) - { - _logger = logger; - } - - public async Task JoinAudio(IGuild guild, IVoiceChannel target) - { - if (_connectedChannels.ContainsKey(guild.Id) - || target.Guild.Id != guild.Id) - { - return; - } - - if (_connectedChannels.TryAdd(guild.Id, await target.ConnectAsync().ConfigureAwait(false))) - { - _logger.LogInformation("Connected to voice on {Guild}.", guild.Name); - } - } - - public async Task LeaveAudio(IGuild guild) - { - if (_connectedChannels.TryRemove(guild.Id, out IAudioClient client)) - { - await client.StopAsync().ConfigureAwait(false); - _logger.LogInformation("Disconnected from voice on {Guild}.", guild.Name); - } - } - - public async Task SendAudioAsync(IGuild guild, string path) - { - if (!File.Exists(path)) - { - _logger.LogInformation("File not found {Path}", path); - return; - } - - if (_connectedChannels.TryGetValue(guild.Id, out IAudioClient client)) - { - _logger.LogInformation($"Starting playback of {path} in {guild.Name}"); - using (Process process = CreateStream(path)) - using (AudioOutStream stream = client.CreatePCMStream(AudioApplication.Music)) - { - await process.StandardOutput.BaseStream.CopyToAsync(stream).ConfigureAwait(false); - await stream.FlushAsync().ConfigureAwait(false); - } - } - } - - private Process CreateStream(string path) - { - string filename = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) - ? "ffmpeg.exe" : "ffmpeg"; - - return Process.Start(new ProcessStartInfo() - { - FileName = filename, - Arguments = $"-hide_banner -loglevel panic -i \"{path}\" -ac 2 -f s16le -ar 48000 pipe:1", - UseShellExecute = false, - RedirectStandardOutput = true - }); - } - } -}