-
Notifications
You must be signed in to change notification settings - Fork 2
/
mb_DiscordRichPresence.cs
446 lines (367 loc) · 18.6 KB
/
mb_DiscordRichPresence.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Threading.Tasks;
using DiscordRPC;
using Newtonsoft.Json.Linq;
using System.Linq;
using System.Runtime.Serialization;
using System.IO;
using EpikLastFMApi;
using DiscordRPC.Logging;
using System.Runtime.InteropServices;
namespace MusicBeePlugin
{
public class CurrentSongInfo
{
public string Artist { get; set; }
public string Track { get; set; }
public string Album { get; set; }
public bool Playing { get; set; }
public int Index { get; set; }
public int TotalTracks { get; set; }
public string ImageUrl { get; set; }
public string YearStr { get; set; }
public string Url { get; set; }
}
public partial class Plugin
{
private MusicBeeApiInterface mbApiInterface;
private PluginInfo about = new PluginInfo();
private DiscordRpcClient rpcClient = new DiscordRpcClient("519949979176140821");
private string imageSize = "medium"; // small, medium, large, extralarge, mega
private static Dictionary<string, string> albumArtCache = new Dictionary<string, string>();
public Plugin.Configuration config = new Plugin.Configuration();
public Plugin.Configuration newConfig = new Plugin.Configuration();
private LastFM_API FmApi = new LastFM_API("cba04ed41dff8bfb9c10835ee747ba94"); // LastFM Api key taken from MusicBee
public PluginInfo Initialise(IntPtr apiInterfacePtr)
{
mbApiInterface = new MusicBeeApiInterface();
mbApiInterface.Initialise(apiInterfacePtr);
about.PluginInfoVersion = PluginInfoVersion;
about.Name = "Discord Rich Presence";
about.Description = "Sets currently playing song as Discord Rich Presence";
about.Author = "Harmon758 + Kuunikal + BriannaFoxwell";
about.TargetApplication = ""; // current only applies to artwork, lyrics or instant messenger name that appears in the provider drop down selector or target Instant Messenger
about.Type = PluginType.General;
about.VersionMajor = 2; // your plugin version
about.VersionMinor = 0;
about.Revision = 05; // this how you do it?
about.MinInterfaceVersion = MinInterfaceVersion;
about.MinApiRevision = MinApiRevision;
about.ReceiveNotifications = (ReceiveNotificationFlags.PlayerEvents | ReceiveNotificationFlags.TagEvents);
about.ConfigurationPanelHeight = 48; // height in pixels that musicbee should reserve in a panel for config settings. When set, a handle to an empty panel will be passed to the Configure function
if (!rpcClient.IsInitialized)
{
rpcClient.Logger = new ConsoleLogger() { Level = LogLevel.Warning };
rpcClient.Initialize();
}
return about;
}
private async Task FetchArt(string track, string artist, string albumArtist, string album)
{
string key = $"{albumArtist}_{album}";
if (!albumArtCache.ContainsKey(key))
{
string mainArtist = albumArtist.Split(new [] { ", ", "; " }, StringSplitOptions.None)[0];
string url = await FmApi.AlbumGetInfo(AlbumGetInfo_FindAlbumImg, album, mainArtist);
if (string.IsNullOrEmpty(url))
url = await FmApi.AlbumGetInfo(AlbumGetInfo_FindAlbumImg, album, albumArtist);
if (string.IsNullOrEmpty(url))
url = await FmApi.AlbumGetInfo(AlbumGetInfo_FindAlbumImg, album, artist, track);
if (string.IsNullOrEmpty(url))
url = await FmApi.AlbumSearch(AlbumSearch_FindAlbumImg, album, mainArtist);
if (string.IsNullOrEmpty(url))
url = await FmApi.AlbumSearch(AlbumSearch_FindAlbumImg, album);
if (string.IsNullOrEmpty(url))
albumArtCache.Add(key, "unknown");
else
albumArtCache.Add(key, url);
}
}
private string AlbumSearch_FindAlbumImg(JObject Json, string ArtistRequest, string AlbumRequest)
{
Dictionary<string, string> ImageList = new Dictionary<string, string>();
dynamic DJson = Json;
JArray Albums = DJson.results.albummatches.album;
foreach (dynamic Album in Albums)
{
string Artist = Album.artist;
bool ArtistUnknown = string.IsNullOrWhiteSpace(ArtistRequest) | string.IsNullOrWhiteSpace(Artist);
bool IsVarious = (ArtistRequest.ToLower() == "va" | ArtistRequest.ToLower() == "various artists");
if (Artist.ToLower() == ArtistRequest.ToLower() | ArtistUnknown | IsVarious)
{
string name = Album.name;
JArray Images = Album.image;
bool FoundAlbum = (name == AlbumRequest | name.ToLower() == AlbumRequest.ToLower() | name.ToLower().Replace(" ", "") == AlbumRequest.ToLower().Replace(" ", ""));
bool FoundArtist = (Artist.ToLower() == ArtistRequest.ToLower());
if (FoundAlbum | FoundArtist | (IsVarious & FoundAlbum))
{
foreach (dynamic Image in Images)
{
string url = Image["#text"];
string size = Image["size"];
if (!string.IsNullOrEmpty(url) & !string.IsNullOrEmpty(size))
ImageList.Add(size, url);
}
if (ImageList.Count > 0)
break;
}
}
}
if (ImageList.Count == 0)
return "";
return ImageList.ContainsKey(imageSize) ? ImageList[imageSize] : ImageList.Values.Last();
}
private string AlbumGetInfo_FindAlbumImg(JObject Json)
{
Dictionary<string, string> ImageList = new Dictionary<string, string>();
dynamic DJson = Json;
JArray Images = DJson.album.image;
foreach (dynamic Image in Images)
{
string url = Image["#text"];
string size = Image["size"];
if (!string.IsNullOrEmpty(url) & !string.IsNullOrEmpty(size))
ImageList.Add(size, url);
}
if (ImageList.Count == 0)
return "";
return ImageList.ContainsKey(imageSize) ? ImageList[imageSize] : ImageList.Values.Last();
}
private void UpdatePresence(CurrentSongInfo SongInfo)
{
RichPresence presence = new RichPresence();
presence.Assets = new Assets();
presence.Party = new Party();
presence.Timestamps = new Timestamps();
presence.Assets.LargeImageKey = "albumart";
string yearStr = SongInfo.YearStr;
string album = SongInfo.Album;
string imageUrl = SongInfo.ImageUrl;
string track = SongInfo.Track;
string artist = SongInfo.Artist;
string url = SongInfo.Url;
bool playing = SongInfo.Playing;
int index = SongInfo.Index;
int totalTracks = SongInfo.TotalTracks;
string year = null;
if (yearStr.Length > 0 && config.showYear)
{
DateTime result;
if (DateTime.TryParse(yearStr, out result))
year = result.Year.ToString();
else
if (yearStr.Length == 4)
if (DateTime.TryParseExact(yearStr, "yyyy", null, System.Globalization.DateTimeStyles.None, out result))
year = result.Year.ToString();
}
presence.Assets.LargeImageText = $"{album}" + ( (year != null && config.showYear) ? $" ({year})" : "" );
if (imageUrl != "" && imageUrl != "unknown")
presence.Assets.LargeImageKey = imageUrl;
string bitrate = mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.Bitrate);
string codec = mbApiInterface.NowPlaying_GetFileProperty(Plugin.FilePropertyType.Kind);
presence.State = $"by {artist}";
presence.Details = $"{track} [{mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.Duration)}]";
// Set the small image to the playback status.
if (playing)
{
presence.Assets.SmallImageKey = "playing";
presence.Assets.SmallImageText = $"{bitrate.Replace("k", "kbps")} [{codec}]";
}
else
{
presence.Assets.SmallImageKey = "paused";
presence.Assets.SmallImageText = "Paused";
}
presence.Party.Size = index;
presence.Party.Max = totalTracks;
long now = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
long duration = this.mbApiInterface.NowPlaying_GetDuration() / 1000;
long end = now + duration;
if (playing)
{
long pos = (this.mbApiInterface.Player_GetPosition() / 1000);
presence.Timestamps.Start = new DateTime(1970, 1, 1).AddSeconds(now - pos);
if (duration != -1)
presence.Timestamps.End = new DateTime(1970, 1, 1).AddSeconds(end - pos);
if (url.StartsWith("http"))
{
presence.Buttons = new DiscordRPC.Button[]
{
new DiscordRPC.Button()
{
Label = "Listen to stream",
Url = url,
}
};
}
}
rpcClient.SetPresence(presence);
}
public bool Configure(IntPtr panelHandle)
{
// save any persistent settings in a sub-folder of this path
string dataPath = mbApiInterface.Setting_GetPersistentStoragePath();
// panelHandle will only be set if you set about.ConfigurationPanelHeight to a non-zero value
// keep in mind the panel width is scaled according to the font the user has selected
// if about.ConfigurationPanelHeight is set to 0, you can display your own popup window
if (panelHandle != IntPtr.Zero)
{
newConfig = (Configuration) config.Clone();
Panel configPanel = (Panel) Panel.FromHandle(panelHandle);
CheckBox showYear = new CheckBox();
showYear.Text = "Show year next to album";
showYear.Height = 16;
showYear.ForeColor = Color.FromArgb(mbApiInterface.Setting_GetSkinElementColour(SkinElement.SkinInputPanelLabel, ElementState.ElementStateDefault, ElementComponent.ComponentForeground));
showYear.Checked = newConfig.showYear;
showYear.CheckedChanged += ShowYearValueChanged;
Label customArtworkUrlLabel = new Label();
customArtworkUrlLabel.Height = 16;
customArtworkUrlLabel.Width = 128;
customArtworkUrlLabel.ForeColor = Color.FromArgb(mbApiInterface.Setting_GetSkinElementColour(SkinElement.SkinInputPanelLabel, ElementState.ElementStateDefault, ElementComponent.ComponentForeground));
customArtworkUrlLabel.Text = "Custom Artwork URL";
customArtworkUrlLabel.Top = 24;
customArtworkUrlLabel.TextAlign = ContentAlignment.MiddleLeft;
TextBox customArtworkUrl = (TextBox) mbApiInterface.MB_AddPanel(configPanel, PluginPanelDock.TextBox);
customArtworkUrl.Height = 16;
customArtworkUrl.Width = 192;
customArtworkUrl.ForeColor = Color.FromArgb(mbApiInterface.Setting_GetSkinElementColour(SkinElement.SkinInputPanelLabel, ElementState.ElementStateDefault, ElementComponent.ComponentForeground));
customArtworkUrl.Text = newConfig.customArtworkUrl;
customArtworkUrl.TextChanged += CustomArtworkUrlValueChanged;
customArtworkUrl.Top = 24;
customArtworkUrl.Left = customArtworkUrlLabel.Width;
configPanel.Controls.AddRange(new Control[] { showYear, customArtworkUrlLabel, customArtworkUrl });
}
return false;
}
private void ShowYearValueChanged(object sender, EventArgs args) {
newConfig.showYear = (sender as CheckBox).Checked;
}
private void CustomArtworkUrlValueChanged(object sender, EventArgs args)
{
newConfig.customArtworkUrl = (sender as TextBox).Text;
}
// called by MusicBee when the user clicks Apply or Save in the MusicBee Preferences screen.
// its up to you to figure out whether anything has changed and needs updating
public void SaveSettings()
{
// save any persistent settings in a sub-folder of this path
string dataPath = mbApiInterface.Setting_GetPersistentStoragePath();
config = newConfig;
SaveConfig(dataPath);
}
private void SaveConfig(string dataPath)
{
DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(Plugin.Configuration));
FileStream fileStream = new FileStream(Path.Combine(dataPath, "mb_DiscordRichPresence.xml"), FileMode.Create);
dataContractSerializer.WriteObject(fileStream, config);
fileStream.Close();
}
private void LoadConfig(string dataPath)
{
DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(Plugin.Configuration));
FileStream fileStream = new FileStream(Path.Combine(dataPath, "mb_DiscordRichPresence.xml"), FileMode.Open);
config = (Plugin.Configuration) dataContractSerializer.ReadObject(fileStream);
fileStream.Close();
}
// MusicBee is closing the plugin (plugin is being disabled by user or MusicBee is shutting down)
public void Close(PluginCloseReason reason)
{
rpcClient.ClearPresence();
rpcClient.Dispose();
}
// uninstall this plugin - clean up any persisted files
public void Uninstall()
{
}
// receive event notifications from MusicBee
// you need to set about.ReceiveNotificationFlags = PlayerEvents to receive all notifications, and not just the startup event
public void ReceiveNotification(string sourceFileUrl, NotificationType type)
{
string bitrate = mbApiInterface.NowPlaying_GetFileProperty(FilePropertyType.Bitrate);
string artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist);
string albumArtist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.AlbumArtist);
string trackTitle = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle);
string album = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album);
string year = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Year);
string url = mbApiInterface.NowPlaying_GetFileUrl();
int position = mbApiInterface.Player_GetPosition();
string originalArtist = artist;
string[] tracks = null;
mbApiInterface.NowPlayingList_QueryFilesEx(null, ref tracks);
int index = Array.IndexOf(tracks, url);
// Check if there isn't an artist for the current song. If so, replace it with "(unknown artist)".
if (string.IsNullOrEmpty(artist))
{
if (!string.IsNullOrEmpty(albumArtist))
artist = albumArtist;
else
artist = "(unknown artist)";
}
if (artist.Length > 128)
{
if (!string.IsNullOrEmpty(albumArtist) && albumArtist.Length <= 128)
artist = albumArtist;
else
artist = artist.Substring(0, 122) + "...";
}
if (type == NotificationType.PluginStartup)
LoadConfig(mbApiInterface.Setting_GetPersistentStoragePath());
// perform some action depending on the notification type
switch (type)
{
case NotificationType.PluginStartup:
case NotificationType.PlayStateChanged:
case NotificationType.TrackChanged:
bool isPlaying = mbApiInterface.Player_GetPlayState() == PlayState.Playing;
Task.Run(async () =>
{
try
{
string imageUrl = "";
if (config.customArtworkUrl != "")
imageUrl = config.customArtworkUrl + "?" + (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
else
{
await FetchArt(trackTitle, originalArtist, albumArtist, album);
imageUrl = albumArtCache[$"{albumArtist}_{album}"];
}
UpdatePresence(new CurrentSongInfo
{
Artist = artist,
Track = trackTitle,
Album = album,
Playing = isPlaying,
Index = index + 1,
TotalTracks = tracks.Length,
ImageUrl = imageUrl,
YearStr = year,
Url = url,
});
}
catch (Exception err)
{
Console.WriteLine(err);
}
});
break;
}
}
public class Configuration : ICloneable
{
public Configuration()
{
this.showYear = true;
this.customArtworkUrl = "";
}
public bool showYear { get; set; }
public string customArtworkUrl { get; set; }
public object Clone()
{
return base.MemberwiseClone();
}
}
}
}