Fixes to music. Thanks to samvaio

This commit is contained in:
Kwoth 2017-02-16 18:13:24 +01:00
parent 8eb2b980d1
commit 108a9fb156
2 changed files with 52 additions and 44 deletions

View File

@ -7,6 +7,8 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using NLog;
namespace NadekoBot.Modules.Music.Classes namespace NadekoBot.Modules.Music.Classes
{ {
@ -46,17 +48,19 @@ namespace NadekoBot.Modules.Music.Classes
// this should be written better // this should be written better
public TimeSpan TotalPlaytime => public TimeSpan TotalPlaytime =>
playlist.Any(s => s.TotalTime == TimeSpan.MaxValue) ? _playlist.Any(s => s.TotalTime == TimeSpan.MaxValue) ?
TimeSpan.MaxValue : TimeSpan.MaxValue :
new TimeSpan(playlist.Sum(s => s.TotalTime.Ticks)); new TimeSpan(_playlist.Sum(s => s.TotalTime.Ticks));
/// <summary> /// <summary>
/// Users who recently got their music wish /// Users who recently got their music wish
/// </summary> /// </summary>
private ConcurrentHashSet<string> recentlyPlayedUsers { get; } = new ConcurrentHashSet<string>(); private ConcurrentHashSet<string> recentlyPlayedUsers { get; } = new ConcurrentHashSet<string>();
private readonly List<Song> playlist = new List<Song>(); private readonly List<Song> _playlist = new List<Song>();
public IReadOnlyCollection<Song> Playlist => playlist; private readonly Logger _log;
public IReadOnlyCollection<Song> Playlist => _playlist;
public Song CurrentSong { get; private set; } public Song CurrentSong { get; private set; }
public CancellationTokenSource SongCancelSource { get; private set; } public CancellationTokenSource SongCancelSource { get; private set; }
@ -73,7 +77,7 @@ namespace NadekoBot.Modules.Music.Classes
public IVoiceChannel PlaybackVoiceChannel { get; private set; } public IVoiceChannel PlaybackVoiceChannel { get; private set; }
public ITextChannel OutputTextChannel { get; set; } public ITextChannel OutputTextChannel { get; set; }
private bool Destroyed { get; set; } = false; private bool destroyed { get; set; } = false;
public bool RepeatSong { get; private set; } = false; public bool RepeatSong { get; private set; } = false;
public bool RepeatPlaylist { get; private set; } = false; public bool RepeatPlaylist { get; private set; } = false;
public bool Autoplay { get; set; } = false; public bool Autoplay { get; set; } = false;
@ -90,6 +94,8 @@ namespace NadekoBot.Modules.Music.Classes
if (startingVoiceChannel == null) if (startingVoiceChannel == null)
throw new ArgumentNullException(nameof(startingVoiceChannel)); throw new ArgumentNullException(nameof(startingVoiceChannel));
_log = LogManager.GetCurrentClassLogger();
OutputTextChannel = outputChannel; OutputTextChannel = outputChannel;
Volume = defaultVolume ?? 1.0f; Volume = defaultVolume ?? 1.0f;
@ -101,7 +107,7 @@ namespace NadekoBot.Modules.Music.Classes
{ {
try try
{ {
while (!Destroyed) while (!destroyed)
{ {
try try
{ {
@ -119,14 +125,14 @@ namespace NadekoBot.Modules.Music.Classes
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine("Action queue crashed"); _log.Warn("Action queue crashed");
Console.WriteLine(ex); _log.Warn(ex);
} }
}).ConfigureAwait(false); }).ConfigureAwait(false);
var t = new Thread(new ThreadStart(async () => var t = new Thread(async () =>
{ {
while (!Destroyed) while (!destroyed)
{ {
try try
{ {
@ -139,7 +145,7 @@ namespace NadekoBot.Modules.Music.Classes
try { await audioClient.DisconnectAsync().ConfigureAwait(false); } catch { } try { await audioClient.DisconnectAsync().ConfigureAwait(false); } catch { }
audioClient = await PlaybackVoiceChannel.ConnectAsync().ConfigureAwait(false); audioClient = await PlaybackVoiceChannel.ConnectAsync().ConfigureAwait(false);
var index = playlist.IndexOf(CurrentSong); var index = _playlist.IndexOf(CurrentSong);
if (index != -1) if (index != -1)
RemoveSongAt(index, true); RemoveSongAt(index, true);
@ -149,6 +155,9 @@ namespace NadekoBot.Modules.Music.Classes
await CurrentSong.Play(audioClient, cancelToken); await CurrentSong.Play(audioClient, cancelToken);
} }
catch (OperationCanceledException) catch (OperationCanceledException)
{
}
finally
{ {
OnCompleted(this, CurrentSong); OnCompleted(this, CurrentSong);
} }
@ -163,8 +172,8 @@ namespace NadekoBot.Modules.Music.Classes
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine("Music thread almost crashed."); _log.Warn("Music thread almost crashed.");
Console.WriteLine(ex); _log.Warn(ex);
await Task.Delay(3000).ConfigureAwait(false); await Task.Delay(3000).ConfigureAwait(false);
} }
finally finally
@ -179,7 +188,7 @@ namespace NadekoBot.Modules.Music.Classes
await Task.Delay(300).ConfigureAwait(false); await Task.Delay(300).ConfigureAwait(false);
} }
} }
})); });
t.Start(); t.Start();
} }
@ -199,7 +208,8 @@ namespace NadekoBot.Modules.Music.Classes
{ {
RepeatPlaylist = false; RepeatPlaylist = false;
RepeatSong = false; RepeatSong = false;
playlist.Clear(); Autoplay = false;
_playlist.Clear();
if (!SongCancelSource.IsCancellationRequested) if (!SongCancelSource.IsCancellationRequested)
SongCancelSource.Cancel(); SongCancelSource.Cancel();
}); });
@ -222,10 +232,10 @@ namespace NadekoBot.Modules.Music.Classes
{ {
if (!FairPlay) if (!FairPlay)
{ {
return playlist.FirstOrDefault(); return _playlist.FirstOrDefault();
} }
var song = playlist.FirstOrDefault(c => !recentlyPlayedUsers.Contains(c.QueuerName)) var song = _playlist.FirstOrDefault(c => !recentlyPlayedUsers.Contains(c.QueuerName))
?? playlist.FirstOrDefault(); ?? _playlist.FirstOrDefault();
if (song == null) if (song == null)
return null; return null;
@ -243,9 +253,9 @@ namespace NadekoBot.Modules.Music.Classes
{ {
actionQueue.Enqueue(() => actionQueue.Enqueue(() =>
{ {
var oldPlaylist = playlist.ToArray(); var oldPlaylist = _playlist.ToArray();
playlist.Clear(); _playlist.Clear();
playlist.AddRange(oldPlaylist.Shuffle()); _playlist.AddRange(oldPlaylist.Shuffle());
}); });
} }
@ -258,7 +268,7 @@ namespace NadekoBot.Modules.Music.Classes
{ {
s.MusicPlayer = this; s.MusicPlayer = this;
s.QueuerName = username.TrimTo(10); s.QueuerName = username.TrimTo(10);
playlist.Add(s); _playlist.Add(s);
}); });
} }
@ -268,7 +278,7 @@ namespace NadekoBot.Modules.Music.Classes
throw new ArgumentNullException(nameof(s)); throw new ArgumentNullException(nameof(s));
actionQueue.Enqueue(() => actionQueue.Enqueue(() =>
{ {
playlist.Insert(index, s); _playlist.Insert(index, s);
}); });
} }
@ -278,7 +288,7 @@ namespace NadekoBot.Modules.Music.Classes
throw new ArgumentNullException(nameof(s)); throw new ArgumentNullException(nameof(s));
actionQueue.Enqueue(() => actionQueue.Enqueue(() =>
{ {
playlist.Remove(s); _playlist.Remove(s);
}); });
} }
@ -286,10 +296,10 @@ namespace NadekoBot.Modules.Music.Classes
{ {
actionQueue.Enqueue(() => actionQueue.Enqueue(() =>
{ {
if (index < 0 || index >= playlist.Count) if (index < 0 || index >= _playlist.Count)
return; return;
var song = playlist.ElementAtOrDefault(index); var song = _playlist.ElementAtOrDefault(index);
if (playlist.Remove(song) && !silent) if (_playlist.Remove(song) && !silent)
{ {
SongRemoved(song, index); SongRemoved(song, index);
} }
@ -301,14 +311,14 @@ namespace NadekoBot.Modules.Music.Classes
{ {
actionQueue.Enqueue(() => actionQueue.Enqueue(() =>
{ {
playlist.Clear(); _playlist.Clear();
}); });
} }
public async Task UpdateSongDurationsAsync() public async Task UpdateSongDurationsAsync()
{ {
var curSong = CurrentSong; var curSong = CurrentSong;
var toUpdate = playlist.Where(s => s.SongInfo.ProviderType == MusicType.Normal && var toUpdate = _playlist.Where(s => s.SongInfo.ProviderType == MusicType.Normal &&
s.TotalTime == TimeSpan.Zero) s.TotalTime == TimeSpan.Zero)
.ToArray(); .ToArray();
if (curSong != null) if (curSong != null)
@ -341,8 +351,9 @@ namespace NadekoBot.Modules.Music.Classes
{ {
RepeatPlaylist = false; RepeatPlaylist = false;
RepeatSong = false; RepeatSong = false;
Destroyed = true; Autoplay = false;
playlist.Clear(); destroyed = true;
_playlist.Clear();
try { await audioClient.DisconnectAsync(); } catch { } try { await audioClient.DisconnectAsync(); } catch { }
if (!SongCancelSource.IsCancellationRequested) if (!SongCancelSource.IsCancellationRequested)
@ -358,17 +369,17 @@ namespace NadekoBot.Modules.Music.Classes
// audioClient = await voiceChannel.ConnectAsync().ConfigureAwait(false); // audioClient = await voiceChannel.ConnectAsync().ConfigureAwait(false);
//} //}
public bool ToggleRepeatSong() => this.RepeatSong = !this.RepeatSong; public bool ToggleRepeatSong() => RepeatSong = !RepeatSong;
public bool ToggleRepeatPlaylist() => this.RepeatPlaylist = !this.RepeatPlaylist; public bool ToggleRepeatPlaylist() => RepeatPlaylist = !RepeatPlaylist;
public bool ToggleAutoplay() => this.Autoplay = !this.Autoplay; public bool ToggleAutoplay() => Autoplay = !Autoplay;
public void ThrowIfQueueFull() public void ThrowIfQueueFull()
{ {
if (MaxQueueSize == 0) if (MaxQueueSize == 0)
return; return;
if (playlist.Count >= MaxQueueSize) if (_playlist.Count >= MaxQueueSize)
throw new PlaylistFullException(); throw new PlaylistFullException();
} }
} }

View File

@ -838,8 +838,7 @@ namespace NadekoBot.Modules.Music
{ {
try try
{ {
if (lastFinishedMessage != null) lastFinishedMessage?.DeleteAfter(0);
lastFinishedMessage.DeleteAfter(0);
lastFinishedMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor() lastFinishedMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithAuthor(eab => eab.WithName("Finished Song").WithMusicIcon()) .WithAuthor(eab => eab.WithName("Finished Song").WithMusicIcon())
@ -855,7 +854,7 @@ namespace NadekoBot.Modules.Music
textCh, textCh,
voiceCh, voiceCh,
relatedVideos[new NadekoRandom().Next(0, relatedVideos.Count)], relatedVideos[new NadekoRandom().Next(0, relatedVideos.Count)],
silent, true,
musicType).ConfigureAwait(false); musicType).ConfigureAwait(false);
} }
} }
@ -870,8 +869,7 @@ namespace NadekoBot.Modules.Music
return; return;
try try
{ {
if (playingMessage != null) playingMessage?.DeleteAfter(0);
playingMessage.DeleteAfter(0);
playingMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor() playingMessage = await mp.OutputTextChannel.EmbedAsync(new EmbedBuilder().WithOkColor()
.WithAuthor(eab => eab.WithName("Playing Song").WithMusicIcon()) .WithAuthor(eab => eab.WithName("Playing Song").WithMusicIcon())
@ -891,8 +889,7 @@ namespace NadekoBot.Modules.Music
else else
msg = await mp.OutputTextChannel.SendConfirmAsync("🎵 Music playback **resumed**.").ConfigureAwait(false); msg = await mp.OutputTextChannel.SendConfirmAsync("🎵 Music playback **resumed**.").ConfigureAwait(false);
if (msg != null) msg?.DeleteAfter(10);
msg.DeleteAfter(10);
} }
catch { } catch { }
}; };