From 135d76719d03da04ced384c52af7ad53e583a10d Mon Sep 17 00:00:00 2001 From: Master Kwoth Date: Wed, 24 Feb 2016 06:32:01 +0100 Subject: [PATCH] added caching to lol commands --- NadekoBot/Classes/Music/StreamRequest.cs | 3 ++ NadekoBot/Commands/LoLCommands.cs | 41 +++++++++++++++++++++--- NadekoBot/Modules/Music.cs | 23 +++++++++++-- 3 files changed, 61 insertions(+), 6 deletions(-) diff --git a/NadekoBot/Classes/Music/StreamRequest.cs b/NadekoBot/Classes/Music/StreamRequest.cs index 4576d88d..4ae9ecfc 100644 --- a/NadekoBot/Classes/Music/StreamRequest.cs +++ b/NadekoBot/Classes/Music/StreamRequest.cs @@ -191,6 +191,7 @@ namespace NadekoBot.Classes.Music { if (State == StreamState.Completed) { Console.WriteLine("Buffering canceled, stream is completed."); + p.CancelOutputRead(); p.Close(); return; } @@ -215,6 +216,7 @@ namespace NadekoBot.Classes.Music { if (read == 0) { if (attempt == 5) { Console.WriteLine($"Didn't read anything from the stream for {attempt} attempts. {buffer.Length / 1.MB()}MB length"); + p.CancelOutputRead(); p.Close(); return; } @@ -235,6 +237,7 @@ namespace NadekoBot.Classes.Music { catch { } finally { if (p != null) { + p.CancelOutputRead(); p.Close(); p.Dispose(); p = null; diff --git a/NadekoBot/Commands/LoLCommands.cs b/NadekoBot/Commands/LoLCommands.cs index 255dbb93..1e5f7493 100644 --- a/NadekoBot/Commands/LoLCommands.cs +++ b/NadekoBot/Commands/LoLCommands.cs @@ -8,9 +8,31 @@ using NadekoBot; using System.Drawing; using NadekoBot.Extensions; using Newtonsoft.Json.Linq; +using System.Collections.Concurrent; + namespace NadekoBot.Commands { class LoLCommands : DiscordCommand { + private class CachedChampion { + public System.IO.Stream ImageStream { get; set; } + public DateTime AddedAt { get; set; } + public string Name { get; set; } + } + + private static List CachedChampionImages = new List(); + private readonly object cacheLock = new object(); + + public LoLCommands() : base() { + Task.Run(async () => { + while (true) { + lock (cacheLock) { + CachedChampionImages = CachedChampionImages.Where(cc => DateTime.Now - cc.AddedAt < new TimeSpan(1, 0, 0)).ToList(); + } + await Task.Delay(new TimeSpan(0, 10, 0)); + } + }); + } + string[] trashTalk = new[] { "Better ban your counters. You are going to carry the game anyway.", "Go with the flow. Don't think. Just ban one of these.", "DONT READ BELOW! Ban Urgot mid OP 100%. Im smurf Diamond 1.", @@ -32,7 +54,7 @@ namespace NadekoBot.Commands { public override void Init(CommandGroupBuilder cgb) { cgb.CreateCommand("~lolchamp") - .Description("Shows League Of Legends champion statistics. Optional second parameter is a role.\n**Usage:**~lolchamp Riven or ~lolchamp Annie sup") + .Description("Shows League Of Legends champion statistics. If there are spaces/apostrophes or in the name - omit them. Optional second parameter is a role.\n**Usage:**~lolchamp Riven or ~lolchamp Annie sup") .Parameter("champ", ParameterType.Required) .Parameter("position", ParameterType.Unparsed) .Do(async e => { @@ -40,7 +62,16 @@ namespace NadekoBot.Commands { //get role string role = ResolvePos(e.GetArg("position")); var name = e.GetArg("champ").Replace(" ", ""); - + CachedChampion champ; + lock (cacheLock) { + champ = CachedChampionImages.Where(cc => cc.Name == name.ToLower()).FirstOrDefault(); + } + if (champ != null) { + Console.WriteLine("Sending lol image from cache."); + champ.ImageStream.Position = 0; + await e.Channel.SendFile("champ.png", champ.ImageStream); + return; + } var allData = JArray.Parse(await Classes.SearchHelper.GetResponseAsync($"http://api.champion.gg/champion/{name}?api_key={NadekoBot.creds.LOLAPIKey}")); JToken data = null; if (role != null) { @@ -67,7 +98,7 @@ namespace NadekoBot.Commands { if (roles[i] == role) roles[i] = ">" + roles[i] + "<"; } - var general = JArray.Parse(await Classes.SearchHelper.GetResponseAsync($"http://api.champion.gg/champion/{name}?api_key={NadekoBot.creds.LOLAPIKey}")) + var general = JArray.Parse(await Classes.SearchHelper.GetResponseAsync($"http://api.champion.gg/stats/champs/{name}?api_key={NadekoBot.creds.LOLAPIKey}")) .Where(jt => jt["role"].ToString() == role) .FirstOrDefault()?["general"]; if (general == null) { @@ -182,7 +213,9 @@ Assists: {general["assists"]} Ban: {general["banRate"]}% smallImgSize)); } } - await e.Channel.SendFile(data["title"] + "_stats.png", img.ToStream(System.Drawing.Imaging.ImageFormat.Png)); + var cachedChamp = new CachedChampion { AddedAt = DateTime.Now, ImageStream = img.ToStream(System.Drawing.Imaging.ImageFormat.Png), Name = name.ToLower() }; + CachedChampionImages.Add(cachedChamp); + await e.Channel.SendFile(data["title"] + "_stats.png", cachedChamp.ImageStream); } catch (Exception ex) { await e.Channel.SendMessage("💢 Failed retreiving data for that champion."); diff --git a/NadekoBot/Modules/Music.cs b/NadekoBot/Modules/Music.cs index 3d676bca..1e4a5a34 100644 --- a/NadekoBot/Modules/Music.cs +++ b/NadekoBot/Modules/Music.cs @@ -274,7 +274,7 @@ namespace NadekoBot.Modules { if (IsRadioLink(query)) { radio = true; - query = await HandleStreamContainers(query); + query = await HandleStreamContainers(query) ?? query; } if (musicPlayers.ContainsKey(e.Server) == false) { @@ -343,7 +343,8 @@ namespace NadekoBot.Modules { && (query.Contains(".pls") || query.Contains(".m3u") || - query.Contains(".asx")); + query.Contains(".asx") || + query.Contains(".xspf")); private async Task HandleStreamContainers(string query) { string file = null; @@ -395,6 +396,24 @@ namespace NadekoBot.Modules { return null; } } + else if (query.Contains(".xspf")) { + /* + + + + file:///mp3s/song_1.mp3 + */ + try { + var m = Regex.Match(file, "(?.*?)"); + var res = m.Groups["url"]?.ToString(); + return res?.Trim(); + } + catch { + Console.WriteLine($"Failed reading .xspf:\n{file}"); + return null; + } + } + return query; } }