-
Notifications
You must be signed in to change notification settings - Fork 7
/
GPMDPPlugin.cs
1722 lines (1571 loc) · 76.1 KB
/
GPMDPPlugin.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;
using System.Runtime.InteropServices;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WebSocketSharp;
using Rainmeter;
using System.IO;
using System.Net;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
namespace GPMDPPlugin
{
internal class Measure
{
//These Classes and enums are for use with every media player type, if you want to implement new info or a new player source then add it here
class musicInfo
{
public musicInfo()
{
State = 0;
Repeat = 0;
Shuffle = 0;
Volume = 100;
Status = -1;
DurationInms = 0;
PositionInms = 0;
Progress = 0;
Rating = 0;
Artist = "";
Album = "";
Title = "";
//Number = "";
//Year = "";
//Genre = "";
Cover = null;
CoverWebAddress = "";
//File = "";
//Position and duration now calculated at update time so it respects DisableLeadingZero
//Duration = "00:00";
//Position = "00:00";
Lyrics = "";
//ThemeType = 0;
//ThemeColor = "222, 79, 44";
Queue = new List<JToken>();
//This loop populates the websocket queue with null
JObject blankInfo = new JObject();
foreach (QueueInfoType type in Enum.GetValues(typeof(QueueInfoType)))
{
JProperty info = new JProperty(type.ToString(), "");
if (type == QueueInfoType.Duration || type == QueueInfoType.PlayCount || type == QueueInfoType.Index)
{
info = new JProperty(type.ToString(), "0");
}
blankInfo.Add(info);
}
Queue.Add(blankInfo);
}
public string Artist { get; set; }
public string Album { get; set; }
public string Title { get; set; }
//public string Number { get; set; }
//public string Year { get; set; }
//public string Genre { get; set; }
public string Cover { get; set; }
public string CoverWebAddress { get; set; }
//public string File { get; set; }
//public string Duration { get; set; }
//public string Position { get; set; }
public double Progress { get; set; }
public int DurationInms { get; set; }
public int PositionInms { get; set; }
public int Rating { get; set; }
public int Repeat { get; set; }
public int Shuffle { get; set; }
public int State { get; set; }
public int Status { get; set; }
public int Volume { get; set; }
public string Lyrics { get; set; }
//public int ThemeType { get; set; }
//public string ThemeColor { get; set; }
public List<JToken> Queue { get; set; }
}
//Possible info types the measure can be
enum MeasureInfoType
{
Artist,
Album,
Title,
//Number,
//Year,
//Genre,
Cover,
CoverWebAddress,
Duration,
Position,
Progress,
Rating,
Repeat,
Shuffle,
State,
Status,
Volume,
Lyrics,
ThemeType,
ThemeColor,
Queue
}
//Info type of the current measure
private MeasureInfoType InfoType;
//Possible infotypes queue info can be
enum QueueInfoType
{
Artist = 0,
Album = 1,
Title = 2,
AlbumArt = 3,
Duration = 4,
PlayCount = 5,
Index = 6,
ID = 7,
AlbumArtist = 8,
AlbumID = 9,
ArtistID = 10,
ArtistImage = 11,
}
//Queue info type and location to read it from for current measure
private int myQueueLocationToRead = 0;
private QueueInfoType myQueueInfoType = QueueInfoType.Title;
//These variables, enums, and functions are all related to support for GPMDP
public static WebSocket ws;
//Version the plugin was built around, should be no breaking issues until version 2.x.x
private const String supportedAPIVersion = "1.1.0";
//Latest info from the websocket
private static musicInfo websocketInfoGPMDP = new musicInfo();
//Not stored in websocket so each measure can have their own, if normal cover is null it is replaced with this later on
private string defaultCoverLocation = "";
//Fallback location to download coverart to
private static string coverOutputLocation = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/Rainmeter/GPMDPPlugin/cover.png";
//Default theme state and color for GPMDP
private static int lastKnownThemeType = 0;
private static string lastKnownThemeColor = "222, 79, 44";
//Flags related to Prgoress, Position, and Duration
private int asDecimal = 0;
private int disableLeadingZero = 0;
private int includeMS = 0;
//For setting queue locations relatively/finding current song faster
private static int lastKnownQueueLocation = 0;
//Threads related to updating queue
private static Thread queueUpdateThread;
private static Thread queueLocUpdateThread;
//For reading and setting authcode, flow is a little different now that it is read from GPMDP settings file but the old code is still in just in case
private static string authcode = "\0";
private static string rainmeterFileSettingsLocation = "";
private static bool sentInitialAuthcode = false;
//So networking never happens on UI thread the creation and reconnection of websockets are handled on a different thread
private static Thread GPMInitThread = new Thread(Measure.GPMDPWebsocketCreator);
private static Thread GPMReconnectThread;
//Store how long its been since last attempt
private static int GPMReconnectTimer;
//Time between reconnect attempts in ms
private const int timeBetweenReconnectAttempts = 1000;
//The channel names that are handled in the OnMessage for the GPMDP websocket, to add a new one add it here first
//Theme and results are not in this due to the way they are handled
enum GPMInfoSupported
{
//Note this list does not include 2 theme support channels
api_version,
track,
time,
playstate,
connect,
repeat,
shuffle,
rating,
lyrics,
volume,
queue
}
//Setup the websocket for GPMDP, you can find code relating to updating music info in the onMessage here
public static void GPMDPWebsocketCreator()
{
if (ws == null)
{
ws = new WebSocket("ws://localhost:5672");
bool acceptedVersion = false;
ws.OnMessage += (sender, d) =>
{
//Get the location of what type of info this is, which is formatted as :"%%%%%%",
String type = d.Data.Substring(d.Data.IndexOf(":") + 2, d.Data.IndexOf(",") - d.Data.IndexOf(":") - 3);
bool acceptedType = false;
//API.Log(API.LogType.Notice, "type:" + type);
foreach (GPMInfoSupported currType in Enum.GetValues(typeof(GPMInfoSupported)))
{
if (currType.ToString().CompareTo(type.ToLower()) == 0)
{
acceptedType = true;
}
}
if (acceptedType)
{
JObject data = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(d.Data);
JArray arrayData = new JArray(data);
foreach (JToken token in arrayData)
{
JToken currentProperty = token.First.Last;
JToken currentValue = token.Last.Last;
if (currentProperty.ToString().ToLower().CompareTo(GPMInfoSupported.api_version.ToString()) == 0)
{
String versionNumber = currentValue.ToString();
if (versionNumber.Substring(0, versionNumber.IndexOf(".")).CompareTo(supportedAPIVersion.Substring(0, versionNumber.IndexOf("."))) == 0)
{
acceptedVersion = true;
}
else
{
//TODO Have a rainmeter attribute flag to supress this error and attempt to continue working
API.Log(API.LogType.Error, "GPMDP Websocket API version is: " + versionNumber + " this plugin was built for version " + supportedAPIVersion);
}
}
else if (currentProperty.ToString().ToLower().CompareTo(GPMInfoSupported.time.ToString()) == 0 && acceptedVersion == true)
{
foreach (JProperty trackInfo in currentValue)
{
if (trackInfo.Name.ToString().ToLower().CompareTo("current") == 0)
{
try
{
websocketInfoGPMDP.PositionInms = Convert.ToInt32(trackInfo.First);
if (websocketInfoGPMDP.DurationInms != 0)
{
websocketInfoGPMDP.Progress = ((double)websocketInfoGPMDP.PositionInms / (double)websocketInfoGPMDP.DurationInms * 100);
}
}
catch (Exception e)
{
API.Log(API.LogType.Error, "Unable to convert the position from GPMDP, report this issue on the GPMDP plugin github page");
API.Log(API.LogType.Debug, e.ToString());
}
}
else if (trackInfo.Name.ToString().ToLower().CompareTo("total") == 0)
{
try
{
websocketInfoGPMDP.DurationInms = Convert.ToInt32(trackInfo.First);
if (websocketInfoGPMDP.DurationInms != 0)
{
websocketInfoGPMDP.Progress = ((double)websocketInfoGPMDP.PositionInms / (double)websocketInfoGPMDP.DurationInms * 100);
}
}
catch (Exception e)
{
API.Log(API.LogType.Error, "Unable to convert the duration from GPMDP, report this issue on the GPMDP plugin github page");
API.Log(API.LogType.Debug, e.ToString());
}
}
}
}
else if (currentProperty.ToString().ToLower().CompareTo(GPMInfoSupported.track.ToString()) == 0 && acceptedVersion == true)
{
foreach (JProperty trackInfo in currentValue)
{
if (trackInfo.Name.ToString().ToLower().CompareTo("title") == 0)
{
websocketInfoGPMDP.Title = trackInfo.First.ToString();
}
else if (trackInfo.Name.ToString().ToLower().CompareTo("artist") == 0)
{
if (trackInfo.First.ToString().ToLower().CompareTo("unknown artist") != 0)
{
websocketInfoGPMDP.Artist = trackInfo.First.ToString();
}
else
{
websocketInfoGPMDP.Artist = "";
}
}
else if (trackInfo.Name.ToString().ToLower().CompareTo("album") == 0)
{
if (trackInfo.First.ToString().ToLower().CompareTo("unknown album") != 0)
{
websocketInfoGPMDP.Album = trackInfo.First.ToString();
}
else
{
websocketInfoGPMDP.Album = "";
}
}
else if (trackInfo.First.ToString().Length != 0 && coverOutputLocation != null && trackInfo.Name.ToString().ToLower().CompareTo("albumart") == 0)
{
if (!trackInfo.First.ToString().Contains("default"))
{
websocketInfoGPMDP.Cover = null;
Thread t = new Thread(() => GetImageFromUrl(trackInfo.First.ToString(), coverOutputLocation));
t.Start();
}
else
{
websocketInfoGPMDP.Cover = null;
websocketInfoGPMDP.CoverWebAddress = trackInfo.First.ToString();
}
}
}
if (queueLocUpdateThread != null)
{
queueLocUpdateThread.Abort();
queueLocUpdateThread.Join();
}
queueLocUpdateThread = new Thread(() => updateQueueLoc());
queueLocUpdateThread.Start();
}
else if (currentProperty.ToString().ToLower().CompareTo(GPMInfoSupported.playstate.ToString()) == 0 && acceptedVersion == true)
{
try
{
websocketInfoGPMDP.State = Convert.ToBoolean(currentValue) ? 1 : 2;
}
catch (Exception e)
{
API.Log(API.LogType.Error, "Unable to convert the play state from GPMDP, report this issue on the GPMDP plugin github page");
API.Log(API.LogType.Debug, e.ToString());
}
}
else if (currentProperty.ToString().ToLower().CompareTo(GPMInfoSupported.connect.ToString()) == 0)
{
String connectionInfo = currentValue.ToString();
if (connectionInfo.ToUpper().CompareTo("CODE_REQUIRED") == 0)
{
API.Log(API.LogType.Warning, "Connection code bad, please send pin code using a bang as folows ''keycode ####''");
websocketInfoGPMDP.Status = 1;
}
else
{
API.Log(API.LogType.Warning, "New authorization code generated and saved:" + connectionInfo);
sendGPMDPAuthCode(connectionInfo);
WritePrivateProfileString("GPMDPPlugin", "AuthCode", connectionInfo, rainmeterFileSettingsLocation);
authcode = connectionInfo;
}
}
else if (currentProperty.ToString().ToLower().CompareTo(GPMInfoSupported.repeat.ToString()) == 0 && acceptedVersion == true)
{
String repeatState = currentValue.ToString();
if (repeatState.ToUpper().CompareTo("NO_REPEAT") == 0)
{
websocketInfoGPMDP.Repeat = 0;
}
else if (repeatState.ToUpper().CompareTo("SINGLE_REPEAT") == 0)
{
websocketInfoGPMDP.Repeat = 1;
}
else if (repeatState.ToUpper().CompareTo("LIST_REPEAT") == 0)
{
websocketInfoGPMDP.Repeat = 2;
}
}
else if (currentProperty.ToString().ToLower().CompareTo(GPMInfoSupported.shuffle.ToString()) == 0 && acceptedVersion == true)
{
String shuffleState = currentValue.ToString();
if (shuffleState.ToUpper().CompareTo("NO_SHUFFLE") == 0)
{
websocketInfoGPMDP.Shuffle = 0;
}
else if (shuffleState.ToUpper().CompareTo("ALL_SHUFFLE") == 0)
{
websocketInfoGPMDP.Shuffle = 1;
}
}
else if (currentProperty.ToString().ToLower().CompareTo(GPMInfoSupported.rating.ToString()) == 0 && acceptedVersion == true)
{
int internalRating = 0;
try
{
foreach (JProperty ratingInfo in currentValue)
{
if (ratingInfo.Name.ToString().ToLower().CompareTo("liked") == 0)
{
if (Convert.ToBoolean(ratingInfo.First))
{
internalRating = 1;
}
}
else if (ratingInfo.Name.ToString().ToLower().CompareTo("disliked") == 0)
{
if (Convert.ToBoolean(ratingInfo.First))
{
internalRating = -1;
}
}
}
}
catch (Exception e)
{
API.Log(API.LogType.Error, "Unable to convert the song rating from GPMDP, report this issue on the GPMDP plugin github page");
API.Log(API.LogType.Debug, e.ToString());
}
websocketInfoGPMDP.Rating = internalRating;
}
else if (currentProperty.ToString().ToLower().CompareTo(GPMInfoSupported.lyrics.ToString()) == 0 && acceptedVersion == true)
{
websocketInfoGPMDP.Lyrics = currentValue.ToString();
}
else if (currentProperty.ToString().ToLower().CompareTo(GPMInfoSupported.volume.ToString()) == 0 && acceptedVersion == true)
{
try
{
websocketInfoGPMDP.Volume = Convert.ToInt16(currentValue);
}
catch (Exception e)
{
API.Log(API.LogType.Error, "Unable to convert the volume from GPMDP, report this issue on the GPMDP plugin github page");
API.Log(API.LogType.Debug, e.ToString());
}
}
else if (currentProperty.ToString().ToLower().CompareTo(GPMInfoSupported.queue.ToString()) == 0 && acceptedVersion == true)
{
//TODO Better handle both this and album art downloader being run again before the last one has finished
if (queueUpdateThread != null)
{
queueUpdateThread.Abort();
queueUpdateThread.Join();
}
queueUpdateThread = new Thread(() => updateQueueInfo(currentValue));
queueUpdateThread.Start();
}
}
}
else if (type.CompareTo("result") == 0 && acceptedVersion == true)
{
//JObject data = JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(d.Data);
//JArray arrayData = new JArray(data);
//
//if (data.First.Next.ToString() == "\"requestID\": 1")
//{
// foreach (JToken innerData in arrayData)
// {
// foreach (JToken info in innerData)
// {
// if (info.ToString().Contains("return"))
// {
// foreach (JToken songInfo in info.Next.Children())
// {
// lastKnownQueueLocation = (int)(songInfo["index"]) - 1;
// }
// }
// }
// }
//}
}
else if (type.Contains("theme"))
{
JObject data = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(d.Data);
JArray arrayData = new JArray(data);
//API.Log(API.LogType.Notice, "data:" + data);
foreach (JToken token in arrayData)
{
JToken currentProperty = token.First.Last;
JToken currentValue = token.Last.Last;
if (currentProperty.ToString().ToLower().Contains("themetype") && acceptedVersion == true)
{
if (currentValue.ToString().ToUpper().CompareTo("FULL") == 0)
{
lastKnownThemeType = 1;
}
else
{
lastKnownThemeType = 0;
}
}
else if (currentProperty.ToString().ToLower().Contains("themecolor") && acceptedVersion == true)
{
String rgbString = currentValue.ToString();
try
{
if (rgbString.ToLower().Contains("rgb"))
{
lastKnownThemeColor = rgbString.Substring(rgbString.IndexOf("(") + 1, rgbString.IndexOf(")") - rgbString.IndexOf("(") - 1);
}
else
{
//Cutoff the # that is at the beginning
rgbString = rgbString.Substring(1);
string r = Convert.ToInt32(rgbString.Substring(0, 2), 16).ToString();
string g = Convert.ToInt32(rgbString.Substring(2, 2), 16).ToString();
string b = Convert.ToInt32(rgbString.Substring(4, 2), 16).ToString();
lastKnownThemeColor = r + ", " + g + ", " + b;
}
}
catch (Exception e)
{
API.Log(API.LogType.Error, "Unable to convert the theme color from GPMDP, report this issue on the GPMDP plugin github page");
API.Log(API.LogType.Debug, e.ToString());
}
}
}
}
};
ws.OnClose += (sender, d) =>
{
websocketInfoGPMDP = new musicInfo();
websocketInfoGPMDP.Status = 0;
};
ws.OnOpen += (sender, d) =>
{
websocketInfoGPMDP.Status = 1;
if (authcode.Length > 30 && !authcode.Contains("\0"))
{
sentInitialAuthcode = true;
sendGPMDPAuthCode(authcode);
}
};
//ws.ConnectAsync();
}
}
//For downloading the image, called in a thread in the onMessage for the websocket
public static void GetImageFromUrl(string url, string filePath)
{
try
{
// Create http request
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
using (HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
// Read as stream
using (Stream stream = httpWebReponse.GetResponseStream())
{
Byte[] buffer = ReadStream(stream);
if (coverOutputLocation == Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/Rainmeter/GPMDPPlugin/cover.png")
{
// Make sure the path folder exists if using it
System.IO.Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/Rainmeter/GPMDPPlugin");
}
// Write stream to file
File.WriteAllBytes(filePath, buffer);
}
}
// Change back to cover image
//coverDownloaded = true;
websocketInfoGPMDP.Cover = filePath;
websocketInfoGPMDP.CoverWebAddress = url;
}
catch (Exception e)
{
API.Log(API.LogType.Error, "Unable to download album art to: " + coverOutputLocation);
Console.WriteLine(e);
}
}
private static byte[] ReadStream(Stream input)
{
byte[] buffer = new byte[1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
//These functions are related to elevating the GPMDP websocket to have remote status
//Call sendGPMDPRemoteRequest to have GPMDP generate a 4 digit keycode, then getGPMDPAuthCode once you have recieved the code, and send authcode once GPMDP's websocket has sent you the perminate code
//Should be mostly unused now see next group of functions for new automatic method
private static void sendGPMDPRemoteRequest()
{
if (ws != null && ws.ReadyState == WebSocketState.Open)
{
String ConnectionString = "{\n";
ConnectionString += "\"namespace\": \"connect\",\n";
ConnectionString += "\"method\": \"connect\",\n";
ConnectionString += "\"arguments\": [\"Rainmeter GPMDP Plugin\"]\n";
ConnectionString += "}";
ws.SendAsync(ConnectionString, null);
}
}
private static void getGPMDPAuthCode(String keycode)
{
String keycodeConnectionString = "{\n";
keycodeConnectionString += "\"namespace\": \"connect\",\n";
keycodeConnectionString += "\"method\": \"connect\",\n";
keycodeConnectionString += "\"arguments\": [\"Rainmeter GPMDP Plugin\", \"" + keycode + "\"]\n";
keycodeConnectionString += "}";
ws.SendAsync(keycodeConnectionString, null);
}
private static void sendGPMDPAuthCode(String authcode)
{
if (ws != null && ws.ReadyState == WebSocketState.Open)
{
String ConnectionString = "{\n";
ConnectionString += "\"namespace\": \"connect\",\n";
ConnectionString += "\"method\": \"connect\",\n";
ConnectionString += "\"arguments\": [\"Rainmeter GPMDP Plugin\", \"" + authcode + "\"]\n";
ConnectionString += "}";
ws.SendAsync(ConnectionString, null);
websocketInfoGPMDP.Status = 2;
}
}
//This is to prevent multiple writes from happening to the settings file
private static bool fileIsAdjusted = false;
//These get and adjust if needed the GPMDP settings
private static void getGPMDPSettings()
{
try
{
string settingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Google Play Music Desktop Player\\json_store\\.settings.json");
using (StreamReader file = File.OpenText(settingsPath))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject settingsFile = (JObject)JToken.ReadFrom(reader);
reader.Close();
file.Close();
bool fileNeedsAdjusted = false;
bool fileContainsPlaybackAPISection = false;
bool fileContainsAuthcodeSection = false;
foreach (JToken setting in settingsFile.Children())
{
if (setting.Path.ToString().CompareTo("themeColor") == 0)
{
string settingsColor = setting.First.ToString();
try
{
if (settingsColor.ToLower().Contains("rgb"))
{
lastKnownThemeColor = settingsColor.Substring(settingsColor.IndexOf("(") + 1, settingsColor.IndexOf(")") - settingsColor.IndexOf("(") - 1);
}
else
{
//Cutoff the # that is at the beginning
settingsColor = settingsColor.Substring(1);
string r = Convert.ToInt32(settingsColor.Substring(0, 2), 16).ToString();
string g = Convert.ToInt32(settingsColor.Substring(2, 2), 16).ToString();
string b = Convert.ToInt32(settingsColor.Substring(4, 2), 16).ToString();
lastKnownThemeColor = r + ", " + g + ", " + b;
}
}
catch (Exception e)
{
API.Log(API.LogType.Error, "Unable to convert the theme color from GPMDP settings file, report this issue on the GPMDP plugin github page");
API.Log(API.LogType.Debug, e.ToString());
}
}
else if (setting.Path.ToString().CompareTo("themeType") == 0)
{
if (setting.First.ToString().ToUpper().CompareTo("FULL") == 0)
{
lastKnownThemeType = 1;
}
else
{
lastKnownThemeType = 0;
}
}
else if (setting.Path.ToString().CompareTo("enableJSON_API") == 0 && !fileIsAdjusted)
{
if (setting.First.ToString().ToLower().Contains("false"))
{
setting.First.Replace("true");
fileNeedsAdjusted = true;
}
}
else if (setting.Path.ToString().CompareTo("playbackAPI") == 0 && !fileIsAdjusted)
{
fileContainsPlaybackAPISection = true;
if (setting.First.ToString().ToLower().Contains("false"))
{
setting.First.Replace("true");
fileNeedsAdjusted = true;
}
}
else if (setting.Path.ToString().CompareTo("authorized_devices") == 0 && !fileIsAdjusted)
{
fileContainsAuthcodeSection = true;
bool foundMatch = false;
foreach (JToken currAuthcode in setting.Children().Children())
{
if (currAuthcode.ToString().CompareTo(authcode) == 0)
{
foundMatch = true;
}
}
if (!foundMatch)
{
//If no authcode found matching the one from the rainmeter settings kill GPMDP and make a new one
if (setting.First.Last != null)
{
String newAuthcode = System.Guid.NewGuid().ToString();
authcode = newAuthcode;
setting.First.Last.AddAfterSelf(authcode);
WritePrivateProfileString("GPMDPPlugin", "AuthCode", authcode, rainmeterFileSettingsLocation);
fileNeedsAdjusted = true;
}
else
{
fileContainsAuthcodeSection = false;
}
}
}
}
if (!fileContainsPlaybackAPISection && !fileIsAdjusted)
{
settingsFile.Add("playbackAPI", "true");
fileNeedsAdjusted = true;
}
if (!fileContainsAuthcodeSection && !fileIsAdjusted)
{
settingsFile.Remove("authorized_devices");
String newAuthcode = System.Guid.NewGuid().ToString();
authcode = newAuthcode;
JArray authcodes = new JArray(authcode);
settingsFile.Add("authorized_devices", authcodes);
WritePrivateProfileString("GPMDPPlugin", "AuthCode", authcode, rainmeterFileSettingsLocation);
fileNeedsAdjusted = true;
}
if (fileNeedsAdjusted && !fileIsAdjusted)
{
fileIsAdjusted = true;
adjustGPMDPSettings(settingsFile);
}
else
{
fileIsAdjusted = true;
}
}
}
catch
{
API.Log(API.LogType.Error, "Unable to locate GPMDP settings file, you will need to use an authenication skin to get playback controls and custom theme colors will be unsupported");
}
}
private static void adjustGPMDPSettings(JObject settingsFile)
{
try
{
foreach (var process in Process.GetProcessesByName("Google Play Music Desktop Player"))
{
process.Kill();
}
string settingsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Google Play Music Desktop Player\\json_store\\.settings.json");
//Replace is to make it so it uses 4 spaces instead of 2 spaces like the normal file does
File.WriteAllText(settingsPath, settingsFile.Root.ToString().Replace(" ", " "));
}
catch
{
API.Log(API.LogType.Error, "Unable to write to GPMDP settings file, this will cause issues with automatic verification. Try closing GPMDP and refreshing your skin");
}
try
{
Process.Start(Environment.GetEnvironmentVariable("LocalAppData") + "\\GPMDP_3\\update.exe", "-processStart \"Google Play Music Desktop Player.exe\"");
}
catch
{
API.Log(API.LogType.Warning, "Unable to relaunch GPMDP after first run settings change, you will need to relaunch it manually");
}
}
//These are functions that handle the sending of various GPMDP websocket commands
//In theory if these were called before the websocket has been setup the could error but that would be impossible in rainmeter so adding the overhead for checks is unneeded.
private static void GPMDPPlayPause()
{
String playPauseString = "{\n";
playPauseString += "\"namespace\": \"playback\",\n";
playPauseString += "\"method\": \"playPause\"\n";
playPauseString += "}";
ws.SendAsync(playPauseString, null);
}
private static void GPMDPForward()
{
String forwardString = "{\n";
forwardString += "\"namespace\": \"playback\",\n";
forwardString += "\"method\": \"forward\"\n";
forwardString += "}";
ws.SendAsync(forwardString, null);
}
private static void GPMDPPrevious()
{
String previousString = "{\n";
previousString += "\"namespace\": \"playback\",\n";
previousString += "\"method\": \"rewind\"\n";
previousString += "}";
ws.SendAsync(previousString, null);
}
private static void GPMDPToggleShuffle()
{
String shuffleString = "{\n";
shuffleString += "\"namespace\": \"playback\",\n";
shuffleString += "\"method\": \"toggleShuffle\"\n";
shuffleString += "}";
ws.SendAsync(shuffleString, null);
}
private static void GPMDPToggleRepeat()
{
String repeatString = "{\n";
repeatString += "\"namespace\": \"playback\",\n";
repeatString += "\"method\": \"toggleRepeat\"\n";
repeatString += "}";
ws.SendAsync(repeatString, null);
}
private static void GPMDPSetPosition(String percent)
{
int currentDuration = websocketInfoGPMDP.DurationInms;
int timeInms = websocketInfoGPMDP.PositionInms;
try
{
if (percent.Contains("-")) { timeInms = (int)Math.Round(timeInms - Convert.ToDouble(percent.Substring(percent.IndexOf("-") + 1)) * currentDuration / 100); ; }
else if (percent.Contains("+")) { timeInms = (int)Math.Round(timeInms + Convert.ToDouble(percent.Substring(percent.IndexOf("+") + 1)) * currentDuration / 100); ; }
else { timeInms = (int)Math.Round(Convert.ToDouble(percent) * currentDuration / 100); }
}
catch (Exception e)
{
API.Log(API.LogType.Error, "Unable to convert SetPosition bang value:" + percent + " to a valid position.");
API.Log(API.LogType.Debug, e.ToString());
}
String positionString = "{\n";
positionString += "\"namespace\": \"playback\",\n";
positionString += "\"method\": \"setCurrentTime\",\n";
positionString += "\"arguments\": [" + timeInms + "]\n";
positionString += "}";
ws.SendAsync(positionString, null);
}
private static void GPMDPToggleThumbsUp()
{
String ratingString = "{\n";
ratingString += "\"namespace\": \"rating\",\n";
ratingString += "\"method\": \"toggleThumbsUp\"\n";
ratingString += "}";
ws.SendAsync(ratingString, null);
}
private static void GPMDPToggleThumbsDown()
{
String ratingString = "{\n";
ratingString += "\"namespace\": \"rating\",\n";
ratingString += "\"method\": \"toggleThumbsDown\"\n";
ratingString += "}";
ws.SendAsync(ratingString, null);
}
private static void GPMDPSetRating(int rating)
{
if (rating == -1) { rating = 1; }
else if (rating == 0) { rating = 3; }
else if (rating == -1) { rating = 5; }
String ratingString = "{\n";
ratingString += "\"namespace\": \"rating\",\n";
ratingString += "\"method\": \"setRating\",\n";
ratingString += "\"arguments\": [" + rating + "]\n";
ratingString += "}";
ws.SendAsync(ratingString, null);
}
private static void GPMDPSetVolume(String volume)
{
int currentVolume = websocketInfoGPMDP.Volume;
int volumeToSet = 100;
try
{
if (volume.Contains("-")) { volumeToSet = currentVolume - Convert.ToInt16(volume.Substring(volume.IndexOf("-") + 1)); }
else if (volume.Contains("+")) { volumeToSet = currentVolume + Convert.ToInt16(volume.Substring(volume.IndexOf("+") + 1)); }
else { volumeToSet = Convert.ToInt16(volume); }
}
catch (Exception e)
{
API.Log(API.LogType.Error, "Unable to convert SetVolume bang value:" + volume + " to a valid volume.");
API.Log(API.LogType.Debug, e.ToString());
}
if (volumeToSet > 100) { volumeToSet = 100; }
else if (volumeToSet < 0) { volumeToSet = 0; }
String volumeString = "{\n";
volumeString += "\"namespace\": \"volume\",\n";
volumeString += "\"method\": \"setVolume\",\n";
volumeString += "\"arguments\": [" + volumeToSet + "]\n";
volumeString += "}";
ws.SendAsync(volumeString, null);
}
//UNUSED, turns out you can not do a manual request to get genre. Shelved until GPMDP supports it which they have no plans to. Also can not be used to get index or id
private static void GPMDPGetExtraSongInfo()
{
//TODO change the requestID from being a constant to using an internal ID system.
String playPauseString = "{\n";
playPauseString += "\"namespace\": \"playback\",\n";
playPauseString += "\"method\": \"getCurrentTrack\",\n";
playPauseString += "\"requestID\": " + 1 + "\n";
playPauseString += "}";
ws.SendAsync(playPauseString, null);
}
private static void GPMDPSetTrack(int trackLoc)
{
if (websocketInfoGPMDP.Queue.Count > trackLoc)
{
//GPMDPGetQueueTracks();
//TODO change the requestID from being a constant to using an internal ID system.
//TODO Use objects for command strings instead of this trash, it was okay before when it was just a few hacky lines now its borderline unreadable Edit: Better now but still should probably be rewritten
String queuePlaytrackString = "{\n";
queuePlaytrackString += "\"namespace\": \"queue\",\n";
queuePlaytrackString += "\"method\": \"playTrack\",\n";
queuePlaytrackString += "\"arguments\": [\n" + websocketInfoGPMDP.Queue[trackLoc] + "\n],\n";
queuePlaytrackString += "\"requestID\": " + 2 + "\n";
queuePlaytrackString += "}";
ws.SendAsync(queuePlaytrackString, null);
}
}
//For updating the queue displayed to the user with new info
private static void updateQueueInfo(JToken queueInfo)
{
websocketInfoGPMDP.Queue.Clear();
//lastKnownQueueLocation = -1;
//API.Log(API.LogType.Notice, "queue:" + currentValue);
foreach (JToken track in queueInfo)
{
//TODO Check this code in edge cases since at least AlbumArt is not passed if it is the default cover
if(track["title"].ToString() == websocketInfoGPMDP.Title && track["artist"].ToString() == websocketInfoGPMDP.Artist && track["album"].ToString() == websocketInfoGPMDP.Album)
{
lastKnownQueueLocation = (int)(track["index"]) - 1;
}
websocketInfoGPMDP.Queue.Add(track);
}
//if(lastKnownQueueLocation == -1)
//{
// API.Log(API.LogType.Error, "GPMDP was unable to locate current song in queue");
// lastKnownQueueLocation = 0;
//}
}
//For updating where we are at in the queue when the queue has not changed
//TODO Nag GPMDP devs to make it so I can identify current song in a less intensive way
private static void updateQueueLoc()
{
if (queueUpdateThread.IsAlive)
{
queueUpdateThread.Join();
}