forked from musicbeeremote/mbrc-plugin
/
Plugin.cs
1257 lines (1130 loc) · 51.2 KB
/
Plugin.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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Windows.Forms;
namespace MusicBeePlugin
{
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using AndroidRemote;
using AndroidRemote.Events;
using AndroidRemote.Networking;
using ServiceStack.Text;
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Timers;
using AndroidRemote.Controller;
using AndroidRemote.Entities;
using AndroidRemote.Error;
using AndroidRemote.Settings;
using AndroidRemote.Utilities;
using AndroidRemote.Enumerations;
using Timer = System.Timers.Timer;
/// <summary>
/// The MusicBee Plugin class. Used to communicate with the MusicBee API.
/// </summary>
public partial class Plugin
{
/// <summary>
/// The mb api interface.
/// </summary>
private MusicBeeApiInterface mbApiInterface;
/// <summary>
/// The _about.
/// </summary>
private readonly PluginInfo about = new PluginInfo();
/// <summary>
/// The timer.
/// </summary>
private Timer timer;
private Timer positionUpdateTimer;
/// <summary>
/// The shuffle.
/// </summary>
private bool shuffle;
/// <summary>
/// Represents the current repeat mode.
/// </summary>
private RepeatMode repeat;
/// <summary>
/// The scrobble.
/// </summary>
private bool scrobble;
/// <summary>
/// Returns the plugin instance (Singleton);
/// </summary>
public static Plugin Instance
{
get { return selfInstance; }
}
private static Plugin selfInstance;
private InfoWindow mWindow;
/// <summary>
/// This function initialized the Plugin.
/// </summary>
/// <param name="apiInterfacePtr"></param>
/// <returns></returns>
public PluginInfo Initialise(IntPtr apiInterfacePtr)
{
selfInstance = this;
JsConfig.ExcludeTypeInfo = true;
Configuration.Register(Controller.Instance);
mbApiInterface = new MusicBeeApiInterface();
mbApiInterface.Initialise(apiInterfacePtr);
UserSettings.Instance.SetStoragePath(mbApiInterface.Setting_GetPersistentStoragePath());
UserSettings.Instance.LoadSettings();
about.PluginInfoVersion = PluginInfoVersion;
about.Name = "MusicBee Remote: Plugin";
about.Description = "Remote Control for server to be used with android application.";
about.Author = "Konstantinos Paparas (aka Kelsos)";
about.TargetApplication = "MusicBee Remote";
Version v = Assembly.GetExecutingAssembly().GetName().Version;
UserSettings.Instance.CurrentVersion = v.ToString();
// 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 = Convert.ToInt16(v.Major);
about.VersionMinor = Convert.ToInt16(v.Minor);
about.Revision = Convert.ToInt16(v.Revision);
about.MinInterfaceVersion = MinInterfaceVersion;
about.MinApiRevision = MinApiRevision;
about.ReceiveNotifications = ReceiveNotificationFlags.PlayerEvents;
if (mbApiInterface.ApiRevision < MinApiRevision)
{
return about;
}
ErrorHandler.SetLogFilePath(mbApiInterface.Setting_GetPersistentStoragePath());
StartPlayerStatusMonitoring();
mbApiInterface.MB_AddMenuItem("mnuTools/MusicBee Remote", "Information Panel of the MusicBee Remote",
MenuItemClicked);
EventBus.FireEvent(new MessageEvent(EventType.ActionSocketStart));
EventBus.FireEvent(new MessageEvent(EventType.InitializeModel));
EventBus.FireEvent(new MessageEvent(EventType.StartServiceBroadcast));
EventBus.FireEvent(new MessageEvent(EventType.ShowFirstRunDialog));
positionUpdateTimer = new Timer(20000);
positionUpdateTimer.Elapsed += PositionUpdateTimerOnElapsed;
positionUpdateTimer.Enabled = true;
return about;
}
private void PositionUpdateTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
{
if (mbApiInterface.Player_GetPlayState() == PlayState.Playing)
{
RequestPlayPosition("status");
}
}
/// <summary>
/// Menu Item click handler. It handles the Tools -> MusicBee Remote entry click and opens the respective info panel.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="args">
/// The args.
/// </param>
private void MenuItemClicked(object sender, EventArgs args)
{
DisplayInfoWindow();
}
public void UpdateWindowStatus(bool status)
{
if (mWindow != null && mWindow.Visible)
{
mWindow.UpdateSocketStatus(status);
}
}
/// <summary>
/// The function populates the local player status variables and then
/// starts the Monitoring of the player status every 1000 ms to retrieve
/// any changes.
/// </summary>
private void StartPlayerStatusMonitoring()
{
scrobble = mbApiInterface.Player_GetScrobbleEnabled();
repeat = mbApiInterface.Player_GetRepeat();
shuffle = mbApiInterface.Player_GetShuffle();
timer = new Timer {Interval = 1000};
timer.Elapsed += HandleTimerElapsed;
timer.Enabled = true;
}
/// <summary>
/// This function runs periodically every 1000 ms as the timer ticks and
/// checks for changes on the player status. If a change is detected on
/// one of the monitored variables the function will fire an event with
/// the new status.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="args">
/// The event arguments.
/// </param>
private void HandleTimerElapsed(object sender, ElapsedEventArgs args)
{
if (mbApiInterface.Player_GetShuffle() != shuffle)
{
shuffle = mbApiInterface.Player_GetShuffle();
EventBus.FireEvent(new MessageEvent(EventType.ReplyAvailable, new SocketMessage(
Constants.PlayerShuffle,
Constants.Message, shuffle)
.toJsonString()));
}
if (mbApiInterface.Player_GetScrobbleEnabled() != scrobble)
{
scrobble = mbApiInterface.Player_GetScrobbleEnabled();
EventBus.FireEvent(new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerScrobble, Constants.Message, scrobble)
.toJsonString()));
}
if (mbApiInterface.Player_GetRepeat() != repeat)
{
repeat = mbApiInterface.Player_GetRepeat();
EventBus.FireEvent(new MessageEvent(
EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerRepeat,
Constants.Message, repeat).toJsonString()));
}
}
public void OpenInfoWindow()
{
IntPtr hwnd = mbApiInterface.MB_GetWindowHandle();
Form MB = (Form)Form.FromHandle(hwnd);
MB.Invoke(new MethodInvoker(DisplayInfoWindow));
}
private void DisplayInfoWindow()
{
if (mWindow == null || !mWindow.Visible)
{
mWindow = new InfoWindow();
}
mWindow.Show();
}
/// <summary>
/// Creates the MusicBee plugin Configuration panel.
/// </summary>
/// <param name="panelHandle">
/// The panel handle.
/// </param>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
public bool Configure(IntPtr panelHandle)
{
DisplayInfoWindow();
return true;
}
/// <summary>
/// The close.
/// </summary>
/// <param name="reason">
/// The reason.
/// </param>
public void Close(PluginCloseReason reason)
{
/** When the plugin closes for whatever reason the SocketServer must stop **/
EventBus.FireEvent(new MessageEvent(EventType.ActionSocketStop));
}
/// <summary>
/// Cleans up any persisted files during the plugin uninstall.
/// </summary>
public void Uninstall()
{
string settingsFolder = mbApiInterface.Setting_GetPersistentStoragePath + "\\mb_remote";
if (Directory.Exists(settingsFolder))
{
Directory.Delete(settingsFolder);
}
}
/// <summary>
/// Called by MusicBee when the user clicks Apply or Save in the MusicBee Preferences screen.
/// Used to save the temporary Plugin SettingsModel if the have changed.
/// </summary>
public void SaveSettings()
{
//UserSettings.SettingsModel = SettingsController.SettingsModel;
//UserSettings.SaveSettings("mbremote");
}
/// <summary>
/// Receives event Notifications from MusicBee. It is only required if the about.ReceiveNotificationFlags = PlayerEvents.
/// </summary>
/// <param name="sourceFileUrl"></param>
/// <param name="type"></param>
public void ReceiveNotification(string sourceFileUrl, NotificationType type)
{
/** Perfom an action depending on the notification type **/
switch (type)
{
case NotificationType.TrackChanged:
RequestNowPlayingTrackCover();
RequestTrackRating(String.Empty, String.Empty);
RequestLoveStatus("status");
RequestNowPlayingTrackLyrics();
RequestPlayPosition("status");
EventBus.FireEvent(new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.NowPlayingTrack,
Constants.Message, GetTrackInfo())
.toJsonString()));
break;
case NotificationType.VolumeLevelChanged:
EventBus.FireEvent(new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerVolume, Constants.Message,
((int)
Math.Round(
mbApiInterface.Player_GetVolume()*100,
1))).toJsonString()));
break;
case NotificationType.VolumeMuteChanged:
EventBus.FireEvent(new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerMute, Constants.Message,
mbApiInterface.Player_GetMute()).toJsonString()
));
break;
case NotificationType.PlayStateChanged:
EventBus.FireEvent(new MessageEvent(EventType.ReplyAvailable, new SocketMessage(Constants.PlayerState,
Constants.Message,
mbApiInterface
.Player_GetPlayState
()).toJsonString
()));
break;
case NotificationType.NowPlayingLyricsReady:
if (mbApiInterface.ApiRevision >= 17)
{
EventBus.FireEvent(new MessageEvent(EventType.NowPlayingLyricsChange,
!String.IsNullOrEmpty(mbApiInterface.NowPlaying_GetDownloadedLyrics())
? mbApiInterface.NowPlaying_GetDownloadedLyrics() : "Lyrics Not Found" ));
}
break;
case NotificationType.NowPlayingArtworkReady:
if (mbApiInterface.ApiRevision >= 17)
{
EventBus.FireEvent(new MessageEvent(EventType.NowPlayingCoverChange,
mbApiInterface.NowPlaying_GetDownloadedArtwork(), "",
mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album)));
}
break;
case NotificationType.NowPlayingListChanged:
EventBus.FireEvent(new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.NowPlayingListChanged,
Constants.Message, true).toJsonString()));
break;
}
}
private NowPlayingTrack GetTrackInfo()
{
NowPlayingTrack nowPlayingTrack = new NowPlayingTrack
{
Artist = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Artist),
Album = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album),
Year = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Year)
};
nowPlayingTrack.SetTitle(mbApiInterface.NowPlaying_GetFileTag(MetaDataType.TrackTitle),
mbApiInterface.NowPlaying_GetFileUrl());
return nowPlayingTrack;
}
/// <summary>
/// When called plays the next track.
/// </summary>
/// <returns></returns>
public void RequestNextTrack(string clientId)
{
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerNext, Constants.Reply,
mbApiInterface.Player_PlayNextTrack()).toJsonString()));
}
/// <summary>
/// When called stops the playback.
/// </summary>
/// <returns></returns>
public void RequestStopPlayback(string clientId)
{
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerStop, Constants.Reply,
mbApiInterface.Player_Stop()).toJsonString()));
}
/// <summary>
/// When called changes the play/pause state or starts playing a track if the status is stopped.
/// </summary>
/// <returns></returns>
public void RequestPlayPauseTrack(string clientId)
{
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerPlayPause, Constants.Reply,
mbApiInterface.Player_PlayPause()).toJsonString()));
}
/// <summary>
/// When called plays the previous track.
/// </summary>
/// <returns></returns>
public void RequestPreviousTrack(string clientId)
{
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerPrevious, Constants.Reply,
mbApiInterface.Player_PlayPreviousTrack()).toJsonString()));
}
/// <summary>
/// When called if the volume string is an integer in the range [0,100] it
/// changes the volume to the specific value and returns the new value.
/// In any other case it just returns the current value for the volume.
/// </summary>
/// <param name="volume"> </param>
public void RequestVolumeChange(int volume)
{
if (volume >= 0)
{
mbApiInterface.Player_SetVolume((float) volume/100);
}
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerVolume, Constants.Reply,
((int)Math.Round(mbApiInterface.Player_GetVolume() * 100, 1))).toJsonString()));
if (mbApiInterface.Player_GetMute())
{
mbApiInterface.Player_SetMute(false);
}
}
/// <summary>
/// Changes the player shuffle state. If the StateAction is Toggle then the current state is switched with it's opposite,
/// if it is State the current state is dispatched with an Event.
/// </summary>
/// <param name="action"></param>
public void RequestShuffleState(StateAction action)
{
if (action == StateAction.Toggle)
{
mbApiInterface.Player_SetShuffle(!mbApiInterface.Player_GetShuffle());
}
EventBus.FireEvent(
new MessageEvent(
EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerShuffle, Constants.Reply,
mbApiInterface.Player_GetShuffle()).toJsonString()));
}
/// <summary>
/// Changes the player mute state. If the StateAction is Toggle then the current state is switched with it's opposite,
/// if it is State the current state is dispatched with an Event.
/// </summary>
/// <param name="action"></param>
public void RequestMuteState(StateAction action)
{
if (action == StateAction.Toggle)
{
mbApiInterface.Player_SetMute(!mbApiInterface.Player_GetMute());
}
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerMute, Constants.Reply,
mbApiInterface.Player_GetMute()).toJsonString()));
}
/// <summary>
///
/// </summary>
/// <param name="action"></param>
public void RequestScrobblerState(StateAction action)
{
if (action == StateAction.Toggle)
{
mbApiInterface.Player_SetScrobbleEnabled(!mbApiInterface.Player_GetScrobbleEnabled());
}
EventBus.FireEvent(
new MessageEvent(
EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerScrobble, Constants.Reply,
mbApiInterface.Player_GetScrobbleEnabled()).toJsonString()));
}
/// <summary>
/// If the action equals toggle then it changes the repeat state, in any other case
/// it just returns the current value of the repeat.
/// </summary>
/// <param name="action">toggle or state</param>
/// <returns>Repeat state: None, All, One</returns>
public void RequestRepeatState(StateAction action)
{
if (action == StateAction.Toggle)
{
switch (mbApiInterface.Player_GetRepeat())
{
case RepeatMode.None:
mbApiInterface.Player_SetRepeat(RepeatMode.All);
break;
case RepeatMode.All:
mbApiInterface.Player_SetRepeat(RepeatMode.None);
break;
case RepeatMode.One:
mbApiInterface.Player_SetRepeat(RepeatMode.None);
break;
}
}
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerRepeat, Constants.Reply,
mbApiInterface.Player_GetRepeat()).toJsonString()));
}
/// <summary>
/// It gets the 100 first tracks of the playlist and returns them in an XML formated String without a root element.
/// </summary>
/// <param name="clientProtocolVersion"> </param>
/// <param name="clientId"> </param>
/// <returns>XML formated string without root element</returns>
public void RequestNowPlayingList(double clientProtocolVersion, string clientId)
{
mbApiInterface.NowPlayingList_QueryFiles(null);
List<NowPlayingListTrack> trackList = new List<NowPlayingListTrack>();
int position = 1;
while (position <= UserSettings.Instance.NowPlayingListLimit)
{
string playListTrack = mbApiInterface.NowPlayingList_QueryGetNextFile();
if (String.IsNullOrEmpty(playListTrack))
break;
string artist = mbApiInterface.Library_GetFileTag(playListTrack, MetaDataType.Artist);
string title = mbApiInterface.Library_GetFileTag(playListTrack, MetaDataType.TrackTitle);
if (String.IsNullOrEmpty(artist))
{
artist = "Unknown Artist";
}
if (String.IsNullOrEmpty(title))
{
int index = playListTrack.LastIndexOf('\\');
title = playListTrack.Substring(index + 1);
}
trackList.Add(
new NowPlayingListTrack(artist, title, position));
position++;
}
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.NowPlayingList, Constants.Reply,
trackList).toJsonString(),clientId));
}
/// <summary>
/// If the given rating string is not null or empty and the value of the string is a float number in the [0,5]
/// the function will set the new rating as the current track's new track rating. In any other case it will
/// just return the rating for the current track.
/// </summary>
/// <param name="rating">New Track Rating</param>
/// <param name="clientId"> </param>
/// <returns>Track Rating</returns>
public void RequestTrackRating(string rating, string clientId)
{
try
{
char a = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
rating = rating.Replace('.', a);
float fRating;
if (!float.TryParse(rating, out fRating))
{
fRating = -1;
}
if (fRating >= 0 && fRating <= 5)
{
mbApiInterface.Library_SetFileTag(mbApiInterface.NowPlaying_GetFileUrl(), MetaDataType.Rating, fRating.ToString());
mbApiInterface.Library_CommitTagsToFile(mbApiInterface.NowPlaying_GetFileUrl());
mbApiInterface.Player_GetShowRatingTrack();
mbApiInterface.MB_RefreshPanels();
}
rating = mbApiInterface.Library_GetFileTag(
mbApiInterface.NowPlaying_GetFileUrl(), MetaDataType.Rating).Replace(a, '.');
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.NowPlayingRating, Constants.Reply,
rating).toJsonString()));
}
catch (Exception e)
{
#if DEBUG
ErrorHandler.LogError(e);
#endif
}
}
/// <summary>
/// Requests the Now Playing track lyrics. If the lyrics are available then they are dispatched along with
/// and event. If not, and the ApiRevision is equal or greater than r17 a request for the downloaded lyrics
/// is initiated. The lyrics are dispatched along with and event when ready.
/// </summary>
public void RequestNowPlayingTrackLyrics()
{
if (!String.IsNullOrEmpty(mbApiInterface.NowPlaying_GetLyrics()))
{
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.NowPlayingLyrics, Constants.Reply,
mbApiInterface.NowPlaying_GetLyrics()).toJsonString()));
}
else if (mbApiInterface.ApiRevision >= 17)
{
string lyrics = mbApiInterface.NowPlaying_GetDownloadedLyrics();
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.NowPlayingLyrics, Constants.Reply,
!String.IsNullOrEmpty(lyrics) ? lyrics : "Retrieving Lyrics").toJsonString()));
}
else
{
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.NowPlayingLyrics, Constants.Reply,
"Lyrics Not Found").toJsonString()));
}
}
/// <summary>
/// Requests the Now Playing Track Cover. If the cover is available it is dispatched along with an event.
/// If not, and the ApiRevision is equal or greater than r17 a request for the downloaded artwork is
/// initiated. The cover is dispatched along with an event when ready.
/// </summary>
public void RequestNowPlayingTrackCover()
{
if (!String.IsNullOrEmpty(mbApiInterface.NowPlaying_GetArtwork()))
{
EventBus.FireEvent(new MessageEvent(EventType.NowPlayingCoverChange,
mbApiInterface.NowPlaying_GetArtwork(), "",
mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album)));
}
else if (mbApiInterface.ApiRevision >= 17)
{
string cover = mbApiInterface.NowPlaying_GetDownloadedArtwork();
if (!String.IsNullOrEmpty(cover))
{
EventBus.FireEvent(new MessageEvent(EventType.NowPlayingCoverChange, cover, "",
mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album)));
}
}
else
{
EventBus.FireEvent(new MessageEvent(EventType.NowPlayingCoverChange, String.Empty, "",
mbApiInterface.NowPlaying_GetFileTag(MetaDataType.Album)));
}
}
/// <summary>
///
/// </summary>
/// <param name="request"></param>
public void RequestPlayPosition(string request)
{
if (!request.Contains("status"))
{
int newPosition;
if (int.TryParse(request, out newPosition))
{
mbApiInterface.Player_SetPosition(newPosition);
}
}
int currentPosition = mbApiInterface.Player_GetPosition();
int totalDuration = mbApiInterface.NowPlaying_GetDuration();
var position = new
{
current = currentPosition,
total = totalDuration
};
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.NowPlayingPosition, Constants.Reply, position).toJsonString()));
}
/// <summary>
/// Searches in the Now playing list for the track specified and plays it.
/// </summary>
/// <param name="index">The track to play</param>
/// <returns></returns>
public void NowPlayingPlay(string index)
{
bool result = false;
int trackIndex;
if (int.TryParse(index, out trackIndex))
{
mbApiInterface.NowPlayingList_QueryFiles(null);
string trackToPlay = String.Empty;
int lTrackIndex = 0;
while (trackIndex != lTrackIndex)
{
trackToPlay = mbApiInterface.NowPlayingList_QueryGetNextFile();
lTrackIndex++;
}
if (!String.IsNullOrEmpty(trackToPlay))
result = mbApiInterface.NowPlayingList_PlayNow(trackToPlay);
}
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.NowPlayingListPlay, Constants.Reply,
result).toJsonString()));
}
/// <summary>
///
/// </summary>
/// <param name="index"></param>
/// <param name="clientId"></param>
public void NowPlayingListRemoveTrack(int index, string clientId)
{
var reply = new
{
success = mbApiInterface.NowPlayingList_RemoveAt(index),
index
};
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.NowPlayingListRemove, Constants.Reply,
reply).toJsonString(), clientId));
}
/// <summary>
/// This function requests or changes the AutoDJ functionality's state.
/// </summary>
/// <param name="action">
/// The action can be either toggle or state.
/// </param>
public void RequestAutoDjState(StateAction action)
{
if (action == StateAction.Toggle)
{
if (!mbApiInterface.Player_GetAutoDjEnabled())
{
mbApiInterface.Player_StartAutoDj();
}
else
{
mbApiInterface.Player_EndAutoDj();
}
}
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerAutoDj, Constants.Reply,
mbApiInterface.Player_GetAutoDjEnabled()).toJsonString()));
}
/// <summary>
/// This function is used to change the playing track's last.fm love rating.
/// </summary>
/// <param name="action">
/// The action can be either love, or ban.
/// </param>
public void RequestLoveStatus(string action)
{
IntPtr hwnd = mbApiInterface.MB_GetWindowHandle();
Form MB = (Form) Form.FromHandle(hwnd);
if (action.Equals("toggle", StringComparison.OrdinalIgnoreCase))
{
if (GetLfmStatus() == LastfmStatus.Love || GetLfmStatus() == LastfmStatus.Ban)
{
MB.Invoke(new MethodInvoker(SetLfmNormalStatus));
}
else
{
MB.Invoke(new MethodInvoker(SetLfmLoveStatus));
}
}
else if (action.Equals("love", StringComparison.OrdinalIgnoreCase))
{
MB.Invoke(new MethodInvoker(SetLfmLoveStatus));
}
else if (action.Equals("ban", StringComparison.OrdinalIgnoreCase))
{
MB.Invoke(new MethodInvoker(SetLfmLoveBan));
}
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.NowPlayingLfmRating, Constants.Reply, GetLfmStatus()).toJsonString()));
}
private void SetLfmNormalStatus()
{
mbApiInterface.Library_SetFileTag(
mbApiInterface.NowPlaying_GetFileUrl(), MetaDataType.RatingLove, "lfm");
}
private void SetLfmLoveStatus()
{
mbApiInterface.Library_SetFileTag(
mbApiInterface.NowPlaying_GetFileUrl(), MetaDataType.RatingLove, "Llfm");
}
private void SetLfmLoveBan()
{
mbApiInterface.Library_SetFileTag(
mbApiInterface.NowPlaying_GetFileUrl(), MetaDataType.RatingLove, "Blfm");
}
private LastfmStatus GetLfmStatus()
{
LastfmStatus lastfmStatus;
string apiReply = mbApiInterface.NowPlaying_GetFileTag(MetaDataType.RatingLove);
if (apiReply.Equals("L") || apiReply.Equals("lfm") || apiReply.Equals("Llfm"))
{
lastfmStatus = LastfmStatus.Love;
}
else if (apiReply.Equals("B") || apiReply.Equals("Blfm"))
{
lastfmStatus = LastfmStatus.Ban;
}
else
{
lastfmStatus = LastfmStatus.Normal;
}
return lastfmStatus;
}
/// <summary>
/// The function checks the MusicBee api and gets all the available playlist urls.
/// </summary>
public void GetAvailablePlaylistUrls()
{
mbApiInterface.Playlist_QueryPlaylists();
string playlistUrl;
while (true)
{
playlistUrl = mbApiInterface.Playlist_QueryGetNextPlaylist();
if (string.IsNullOrEmpty(playlistUrl)) break;
}
}
/// <summary>
///
/// </summary>
/// <param name="clientId"></param>
public void RequestPlayerStatus(string clientId)
{
var status = new
{
playerrepeat = mbApiInterface.Player_GetRepeat().ToString(),
playermute = mbApiInterface.Player_GetMute(),
playershuffle = mbApiInterface.Player_GetShuffle(),
scrobbler = mbApiInterface.Player_GetScrobbleEnabled(),
playerstate = mbApiInterface.Player_GetPlayState().ToString(),
playervolume =
((int) Math.Round(mbApiInterface.Player_GetVolume()*100, 1)).ToString(
CultureInfo.InvariantCulture)
};
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.PlayerStatus, Constants.Reply, status).toJsonString(), clientId));
}
/// <summary>
///
/// </summary>
/// <param name="clientId"></param>
public void RequestTrackInfo(string clientId)
{
EventBus.FireEvent(new MessageEvent(
EventType.ReplyAvailable,
new SocketMessage(Constants.NowPlayingTrack, Constants.Reply, GetTrackInfo()).toJsonString(), clientId));
}
/// <summary>
/// Moves a track of the now playing list to a new position.
/// </summary>
/// <param name="clientId">The Id of the client that initiated the request</param>
/// <param name="from">The initial position</param>
/// <param name="to">The final position</param>
public void RequestNowPlayingMove(string clientId, int from, int to)
{
bool result = false;
int[] aFrom = {from};
int dIn;
if (from > to)
{
dIn = to - 1;
}
else
{
dIn = to;
}
result = mbApiInterface.NowPlayingList_MoveFiles(aFrom, dIn);
var reply = new
{
success = result, from, to
};
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.NowPlayingListMove, Constants.Reply,reply).toJsonString(), clientId));
}
private string XmlFilter(string[] tags, string query, bool isStrict)
{
XElement filter = new XElement("Source",
new XAttribute("Type", 1));
XElement conditions = new XElement("Conditions",
new XAttribute("CombineMethod", "Any"));
foreach (string tag in tags)
{
XElement condition = new XElement("Condition",
new XAttribute("Field", tag),
new XAttribute("Comparison", isStrict ? "Is" : "Contains"),
new XAttribute("Value", query));
conditions.Add(condition);
}
filter.Add(conditions);
return filter.ToString();
}
/// <summary>
/// Calls the API to get albums matching the specified parameter. Fires an event with the message in JSON format.
/// </summary>
/// <param name="albumName">Is used to filter through the data.</param>
/// <param name="clientId">The client that initiated the call. (Should also be the only one to receive the data.</param>
public void LibrarySearchAlbums(string albumName, string clientId)
{
List<Album> albumList = new List<Album>();
if (mbApiInterface.Library_QueryLookupTable("album", "albumartist" + '\0' + "album", XmlFilter(new[] {"Album"}, albumName, false)))
{
try
{
foreach (string entry in new List<string>(mbApiInterface.Library_QueryGetLookupTableValue(null).Split(new[] {"\0\0"}, StringSplitOptions.None)))
{
if (String.IsNullOrEmpty(entry)) continue;
string[] albumInfo = entry.Split('\0');
if (albumInfo.Length < 2) continue;
Album current = albumInfo.Length == 3
? new Album(albumInfo[1], albumInfo[2])
: new Album(albumInfo[0], albumInfo[1]);
if (current.album.IndexOf(albumName, StringComparison.OrdinalIgnoreCase) < 0) continue;
if (!albumList.Contains(current))
{
albumList.Add(current);
}
else
{
albumList.ElementAt(albumList.IndexOf(current)).IncreaseCount();
}
}
}
catch (IndexOutOfRangeException)
{
}
}
mbApiInterface.Library_QueryLookupTable(null, null, null);
EventBus.FireEvent(
new MessageEvent(EventType.ReplyAvailable,
new SocketMessage(Constants.LibrarySearchAlbum, Constants.Reply,
albumList).toJsonString(), clientId));
albumList = null;
}
/// <summary>
/// Used to get all the albums by the specified artist.
/// </summary>
/// <param name="artist"></param>
/// <param name="clientId"></param>
public void LibraryGetArtistAlbums(string artist, string clientId)
{
List<Album> albumList = new List<Album>();
if (mbApiInterface.Library_QueryFiles(XmlFilter(new[] {"ArtistPeople"}, artist, true)))
{
while (true)
{
string currentFile = mbApiInterface.Library_QueryGetNextFile();