From 92a18c524c289a0ada5fac02c5f44d9a73fdbdb0 Mon Sep 17 00:00:00 2001 From: maybeclean <49769124+maybeclean@users.noreply.github.com> Date: Wed, 4 Aug 2021 02:28:32 -0400 Subject: [PATCH] App ID Configuration in Settings --- INIReader.cs | 76 ----------------------------------- IniParser.cs | 55 +++++++++++++++++++++++++ Models.cs | 21 ---------- Util.cs | 33 ++++++++------- app.config | 2 +- mb_DiscordRichPresence.cs | 76 +++++++++++++++++++++++++++-------- mb_DiscordRichPresence.csproj | 17 ++++---- packages.config | 2 +- 8 files changed, 144 insertions(+), 138 deletions(-) delete mode 100644 INIReader.cs create mode 100644 IniParser.cs delete mode 100644 Models.cs diff --git a/INIReader.cs b/INIReader.cs deleted file mode 100644 index 1c78287..0000000 --- a/INIReader.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -namespace MusicBeePlugin -{ - class IniReader - { - Dictionary> ini = new Dictionary>(StringComparer.InvariantCultureIgnoreCase); - - public IniReader(string file) - { - var txt = File.ReadAllText(file); - - Dictionary currentSection = new Dictionary(StringComparer.InvariantCultureIgnoreCase); - - ini[""] = currentSection; - - foreach(var line in txt.Split(new[]{"\n"}, StringSplitOptions.RemoveEmptyEntries) - .Where(t => !string.IsNullOrWhiteSpace(t)) - .Select(t => t.Trim())) - { - if (line.StartsWith(";")) - continue; - - if (line.StartsWith("[") && line.EndsWith("]")) - { - currentSection = new Dictionary(StringComparer.InvariantCultureIgnoreCase); - ini[line.Substring(1, line.LastIndexOf("]") - 1)] = currentSection; - continue; - } - - var idx = line.IndexOf("="); - if (idx == -1) - currentSection[line] = ""; - else - currentSection[line.Substring(0, idx)] = line.Substring(idx + 1); - } - } - - public string GetValue(string key) - { - return GetValue(key, "", ""); - } - - public string GetValue(string key, string section) - { - return GetValue(key, section, ""); - } - - public string GetValue(string key, string section, string @default) - { - if (!ini.ContainsKey(section)) - return @default; - - if (!ini[section].ContainsKey(key)) - return @default; - - return ini[section][key]; - } - - public string[] GetKeys(string section) - { - if (!ini.ContainsKey(section)) - return new string[0]; - - return ini[section].Keys.ToArray(); - } - - public string[] GetSections() - { - return ini.Keys.Where(t => t != "").ToArray(); - } - } -} diff --git a/IniParser.cs b/IniParser.cs new file mode 100644 index 0000000..87aa2ed --- /dev/null +++ b/IniParser.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading.Tasks; + +namespace MusicBeePlugin +{ + public class IniParser // revision 11 + { + string Path; + string EXE = Assembly.GetExecutingAssembly().GetName().Name; + + [DllImport("kernel32", CharSet = CharSet.Unicode)] + static extern long WritePrivateProfileString(string Section, string Key, string Value, string FilePath); + + [DllImport("kernel32", CharSet = CharSet.Unicode)] + static extern int GetPrivateProfileString(string Section, string Key, string Default, StringBuilder RetVal, int Size, string FilePath); + + public IniParser(string IniPath = null) + { + Path = new FileInfo(IniPath ?? EXE + ".ini").FullName; + } + + public string Read(string Key, string Section = null) + { + var RetVal = new StringBuilder(255); + GetPrivateProfileString(Section ?? EXE, Key, "", RetVal, 255, Path); + return RetVal.ToString(); + } + + public void Write(string Key, string Value, string Section = null) + { + WritePrivateProfileString(Section ?? EXE, Key, Value, Path); + } + + public void DeleteKey(string Key, string Section = null) + { + Write(Key, null, Section ?? EXE); + } + + public void DeleteSection(string Section = null) + { + Write(null, null, Section ?? EXE); + } + + public bool KeyExists(string Key, string Section = null) + { + return Read(Key, Section).Length > 0; + } + } +} diff --git a/Models.cs b/Models.cs deleted file mode 100644 index b09099f..0000000 --- a/Models.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace MusicBeePlugin -{ - public class MusicInfo - { - public string Artist { get; set; } - public string TrackArtist { get; set; } - public string TrackTitle { get; set; } - public string Album { get; set; } - public string Duration { get; set; } - - public int Volume { get; set; } - public int Position { get; set; } - - } -} diff --git a/Util.cs b/Util.cs index a059ae3..7673a45 100644 --- a/Util.cs +++ b/Util.cs @@ -4,12 +4,12 @@ using System.Net.Http; using MusicBeePlugin; using System.Net.Http.Headers; -using Newtonsoft.Json; using System.IO; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.Windows.Forms; using System.Collections.Generic; +using Newtonsoft.Json; namespace Utils { @@ -35,7 +35,6 @@ public static string Utf16ToUtf8(string utf16String) } } - public static string AssureByteSize(string input, int maxLength) { for (var i = input.Length - 1; i >= 0; i--) @@ -49,15 +48,6 @@ public static string AssureByteSize(string input, int maxLength) return string.Empty; } - public static string HashAlbum(string text) - { - if (string.IsNullOrEmpty(text)) - return text; - - var hashed = BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty); - return AssureByteSize(hashed, 10); - } - public static string SanitizeAlbumName(string albumName) { var albumArray = albumName.ToCharArray(); @@ -71,6 +61,19 @@ public static string SanitizeAlbumName(string albumName) return newAlbum; } + + public static string DiscordAPPID() + { + string app_id = Plugin.iniParser.Read("AppID", "Discord"); + + if (string.IsNullOrEmpty(app_id)) + { + MessageBox.Show("Add your Discord Application ID for the Plugin in [Preferences -> Plugins]", "Failed to read Application ID"); + return string.Empty; + } + + return app_id; + } } public static class Discord @@ -100,9 +103,9 @@ public static async Task UploadAsset(string albumName, string imageData) var responseContent = await response.Content.ReadAsStringAsync(); if (responseContent.Contains(albumName)) - Plugin.MbApiInterface.MB_SetBackgroundTaskMessage("Successfully uploaded artwork."); + Plugin.MbApiInterface.MB_SetBackgroundTaskMessage($"Successfully Uploaded Artwork for {albumName}"); else - Plugin.MbApiInterface.MB_SetBackgroundTaskMessage("Artwork upload failed, check log."); + Plugin.MbApiInterface.MB_SetBackgroundTaskMessage($"Failed Artwork Upload for {albumName}"); Plugin.Logging.LogWrite(responseContent); } @@ -132,7 +135,7 @@ private static string grabToken(string file) } } - return authToken; + return authToken != "" ? authToken : "FAIL"; } private static bool findLdb(ref string levelDB) { @@ -171,7 +174,7 @@ public static string GetAuthToken() string pathStr = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\discord\\Local Storage\\leveldb\\"; if (!findLdb(ref pathStr)) - return ""; + return "FAIL"; string tokenStr = grabToken(pathStr); diff --git a/app.config b/app.config index ad01e48..7765316 100644 --- a/app.config +++ b/app.config @@ -1,3 +1,3 @@ - + diff --git a/mb_DiscordRichPresence.cs b/mb_DiscordRichPresence.cs index 3b6271b..e9a71b6 100644 --- a/mb_DiscordRichPresence.cs +++ b/mb_DiscordRichPresence.cs @@ -6,31 +6,32 @@ using Utils; using System.Net.Http.Headers; using System.Text.RegularExpressions; -using IniParser; -using IniParser.Model; +using System.IO; namespace MusicBeePlugin { public partial class Plugin { - private static FileIniDataParser iniParser = new FileIniDataParser(); - private readonly PluginInfo _about = new PluginInfo(); private static DiscordRPC.RichPresence _rpcPresence = new DiscordRPC.RichPresence(); public static MusicBeeApiInterface MbApiInterface; + public static IniParser iniParser = new IniParser("C:\\MusicBee-RichPresence\\configuration.ini"); + public static readonly Logger Logging = new Logger(); public static readonly HttpClient httpClient = new HttpClient(); public static string DiscordId = ""; + public TextBox DiscordIDTextBox; + public PluginInfo Initialise(IntPtr apiInterfacePtr) { - IniData data = iniParser.ReadFile(@"C:\\MusicBee-RichPresence\\Configuration.ini"); - DiscordId = data["Discord"]["AppID"].ToString(); + string token = DiscordToken.GetAuthToken(); + DiscordId = Utility.DiscordAPPID(); MbApiInterface = new MusicBeeApiInterface(); MbApiInterface.Initialise(apiInterfacePtr); @@ -38,22 +39,57 @@ public PluginInfo Initialise(IntPtr apiInterfacePtr) _about.Name = "Discord Rich Presence"; _about.Description = "A Richer Rich Presence for Musicbee."; _about.Author = "@maybeclean"; - _about.TargetApplication = ""; _about.Type = PluginType.General; _about.VersionMajor = 1; - _about.VersionMinor = 0; - _about.Revision = 01; + _about.VersionMinor = 2; + _about.Revision = 09; _about.ReceiveNotifications = (ReceiveNotificationFlags.PlayerEvents | ReceiveNotificationFlags.TagEvents); - _about.ConfigurationPanelHeight = 0; + _about.ConfigurationPanelHeight = 30; + + if (token == "FAIL") + MessageBox.Show("Failed to grab auth token"); - if (!httpClient.DefaultRequestHeaders.Contains("Authorization")) - httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", DiscordToken.GetAuthToken()); + httpClient.DefaultRequestHeaders.Clear(); + httpClient.DefaultRequestHeaders.Add("Authorization", token); - InitialiseDiscord(); + if (!string.IsNullOrEmpty(DiscordId)) + InitialiseDiscord(); return _about; } + public bool Configure(IntPtr panelHandle) + { + if (panelHandle != IntPtr.Zero) + { + Panel configPanel = (Panel)Panel.FromHandle(panelHandle); + Label prompt = new Label(); + prompt.AutoSize = true; + prompt.Location = new Point(0, 0); + prompt.Text = "Developer App Id"; + DiscordIDTextBox = new TextBox(); + DiscordIDTextBox.Bounds = new Rectangle(135, 0, 100, DiscordIDTextBox.Height); + DiscordIDTextBox.Text = DiscordId; + configPanel.Controls.AddRange(new Control[] { prompt, DiscordIDTextBox }); + } + return false; + } + public void SaveSettings() + { + try + { + iniParser.Write("AppID", DiscordIDTextBox.Text, "Discord"); + DiscordId = DiscordIDTextBox.Text; + MessageBox.Show("Musicbee will now restart to apply your Application ID", "Restart Required"); + Application.Restart(); + Environment.Exit(0); + } + catch (Exception e) + { + MessageBox.Show(e.Message, "Exception Occured"); + } + } + private void InitialiseDiscord() { var handlers = new DiscordRPC.DiscordEventHandlers @@ -63,6 +99,7 @@ private void InitialiseDiscord() disconnectedCallback = HandleDisconnectedCallback }; + MessageBox.Show(DiscordId); DiscordRPC.Initialize(DiscordId, ref handlers, true, null); } @@ -111,7 +148,12 @@ private void UpdatePresence(string artist, string trackArtist, string track, str else largeText = album + " " + artist; - _rpcPresence.largeImageText = Utility.AssureByteSize(largeText.Substring(0, largeText.Length - 1), 128); + string genre = MbApiInterface.NowPlaying_GetFileTag(MetaDataType.Genre); + + _rpcPresence.largeImageText = largeText.Substring(0, largeText.Length - 1); + + if (!string.IsNullOrEmpty(genre)) + _rpcPresence.largeImageText += " (" + genre + ")"; string cleanedAlbum = Utility.SanitizeAlbumName(album); @@ -155,7 +197,7 @@ public void ReceiveNotification(string sourceFileUrl, NotificationType type) string album = MbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album); string duration = MbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.Duration); int volume = Convert.ToInt32(MbApiInterface.Player_GetVolume() * 100.0f); - int position = MbApiInterface.Player_GetPosition(); + int position = MbApiInterface.Player_GetPosition() / 1000; if (string.IsNullOrEmpty(artist)) artist = "[artist empty]"; @@ -166,7 +208,7 @@ public void ReceiveNotification(string sourceFileUrl, NotificationType type) switch (MbApiInterface.Player_GetPlayState()) { case PlayState.Playing: - UpdatePresence(artist, trackArtist, trackTitle, album, duration, true, position / 1000, volume); + UpdatePresence(artist, trackArtist, trackTitle, album, duration, true, position, volume); break; case PlayState.Paused: UpdatePresence(artist, trackArtist, trackTitle, album, duration, false, 0, volume); @@ -180,7 +222,7 @@ public void ReceiveNotification(string sourceFileUrl, NotificationType type) case NotificationType.VolumeLevelChanged: if (MbApiInterface.Player_GetPlayState() == PlayState.Playing) - UpdatePresence(artist, trackArtist, trackTitle, album, duration, true, position / 1000, volume); + UpdatePresence(artist, trackArtist, trackTitle, album, duration, true, position, volume); break; } } diff --git a/mb_DiscordRichPresence.csproj b/mb_DiscordRichPresence.csproj index 10c5be6..30711c1 100644 --- a/mb_DiscordRichPresence.csproj +++ b/mb_DiscordRichPresence.csproj @@ -32,6 +32,8 @@ false true + + true @@ -75,11 +77,8 @@ false - - packages\ini-parser.2.5.2\lib\net20\INIFileParser.dll - - - packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + + packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll @@ -91,8 +90,7 @@ - - + @@ -129,6 +127,11 @@ copy /Y "$(TargetDir)\*.*" "$(AppData)\MusicBee\Plugins\" copy /Y "$(ProjectDir)\lib\*.*" "$(AppData)\MusicBee\Plugins\" + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + +