-
Notifications
You must be signed in to change notification settings - Fork 2
/
proc.pb
1578 lines (1448 loc) · 56.2 KB
/
proc.pb
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
Procedure lastfmScrobble()
Shared nowPlaying
Shared lastfmSession
Protected api_sig.s
Protected requestPayload.s
Protected unixtimeUTC.s
Protected url.s
Protected request.HTTPRequestManager::request
unixtimeUTC = Str(unixtimeUTC())
api_sig = StringFingerprint("api_key" +
#lastfmAPIKey +
"artist" +
nowPlaying\artist +
"duration" +
Str(nowPlaying\durationSec) +
"methodtrack.scrobblesk" +
lastfmSession +
"timestamp" +
unixtimeUTC +
"track" +
nowPlaying\title +
#lastfmSecret,#PB_Cipher_MD5)
url = #lastfmEndpoint + "/2.0/?format=json"
requestPayload = "method=track.scrobble&api_key=" +
#lastfmAPIKey +
"&artist=" +
URLEncode(nowPlaying\artist) +
"&track=" +
URLEncode(nowPlaying\title) +
"&duration=" +
Str(nowPlaying\durationSec) +
"×tamp=" +
unixtimeUTC +
"&sk=" +
lastfmSession +
"&api_sig=" + api_sig
request\type = #PB_HTTP_Post
request\url = url
request\textData = requestPayload
request\finishEvent = #evScrobbleRequestFinished
request\comment = Str(nowPlaying\ID) + " scrobble"
HTTPRequestManager::request(@request)
EndProcedure
Procedure lastfmUpdateNowPlaying()
Shared nowPlaying
Shared lastfmSession
Protected api_sig.s
Protected requestPayload.s
Protected url.s
Protected request.HTTPRequestManager::request
api_sig = StringFingerprint("api_key" +
#lastfmAPIKey +
"artist" +
nowPlaying\artist +
"duration" +
Str(nowPlaying\durationSec) +
"methodtrack.updateNowPlayingsk" +
lastfmSession +
"track" +
nowPlaying\title +
#lastfmSecret,#PB_Cipher_MD5)
url = #lastfmEndpoint + "/2.0/?format=json"
requestPayload = "method=track.updateNowPlaying&api_key=" +
#lastfmAPIKey +
"&artist=" +
URLEncode(nowPlaying\artist) +
"&track=" +
URLEncode(nowPlaying\title) +
"&duration=" +
Str(nowPlaying\durationSec) +
"&sk=" +
lastfmSession +
"&api_sig=" + api_sig
request\type = #PB_HTTP_Post
request\url = url
request\textData = requestPayload
request\finishEvent = #evNowPlayingRequestFinished
request\comment = Str(nowPlaying\ID) + " nowplaying update"
HTTPRequestManager::request(@request)
EndProcedure
Procedure lastfmAuth(lastfmAuthStep.b)
Shared lastfmToken.s,lastfmSession.s,lastfmUser.s
Shared lastfmTokenResponse.s,lastfmSessionResponse.s
Protected api_sig.s,request.i,response.s,json.i,status.s
Select lastfmAuthStep
Case #getToken
lastfmToken = ""
api_sig = StringFingerprint("api_key" + #lastfmAPIKey + "methodauth.getToken" + #lastfmSecret,#PB_Cipher_MD5)
request = HTTPRequest(#PB_HTTP_Get,#lastfmEndpoint + "/2.0/?method=auth.getToken&api_key=" + #lastfmAPIKey + "&format=json&api_sig=" + api_sig)
If request
response = HTTPInfo(request,#PB_HTTP_Response)
status = HTTPInfo(request,#PB_HTTP_StatusCode)
FinishHTTP(request)
json = ParseJSON(#PB_Any,response)
If json And status = "200"
lastfmToken = GetJSONString(GetJSONMember(JSONValue(json),"token"))
FreeJSON(json)
EndIf
If lastfmToken
ProcedureReturn #True
Else
lastfmTokenResponse = "HTTP " + status + ~"\n" + response
EndIf
EndIf
Case #openAuthLink
RunProgram("open","http://www.last.fm/api/auth/?api_key=" + #lastfmAPIKey + "&token=" + lastfmToken,"")
ProcedureReturn #True
Case #getSession
lastfmSession = ""
api_sig = StringFingerprint("api_key" + #lastfmAPIKey + "methodauth.getSessiontoken" + lastfmToken + #lastfmSecret,#PB_Cipher_MD5)
;Debug "api_key" + #lastfmAPIKey + "methodauth.getSessiontoken" + lastfmToken + #lastfmSecret
;Debug api_sig
request = HTTPRequest(#PB_HTTP_Post,#lastfmEndpoint + "/2.0/?format=json","method=auth.getSession&api_key=" + #lastfmAPIKey + "&token=" + lastfmToken + "&api_sig=" + api_sig)
If request
response = HTTPInfo(request,#PB_HTTP_Response)
status = HTTPInfo(request,#PB_HTTP_StatusCode)
FinishHTTP(request)
json = ParseJSON(#PB_Any,response)
If json And status = "200"
;{"session":{"subscriber":0,"name":"...","key":"..."}}
lastfmSession = GetJSONString(GetJSONMember(GetJSONMember(JSONValue(json),"session"),"key"))
lastfmUser = GetJSONString(GetJSONMember(GetJSONMember(JSONValue(json),"session"),"name"))
FreeJSON(json)
EndIf
If lastfmSession
ProcedureReturn #True
Else
lastfmSessionResponse = "HTTP " + status + ~"\n" + response
EndIf
EndIf
EndSelect
EndProcedure
Procedure getTags(start.i)
Shared tagsToGet.track_info()
Shared numThreads.b
Shared tagsToGetLock.i
Shared ffprobe.s
Protected metadata.ffprobe_answer
Protected json.s
Protected NewMap tags_lcase.s()
Protected i.i
Protected task.task::task
Delay(start * 100) ; to spread execution times
For i = start To ListSize(tagsToGet()) - 1
If EXIT
ProcedureReturn
EndIf
LockMutex(tagsToGetLock)
SelectElement(tagsToGet(),i)
Protected path.s = tagsToGet()\path
UnlockMutex(tagsToGetLock)
ClearStructure(@task,task::task)
InitializeStructure(@task,task::task)
With task
\path = ffprobe
\wait_program = #True
\read_output = #True
AddElement(\args()) : \args() = "-v"
AddElement(\args()) : \args() = "quiet"
AddElement(\args()) : \args() = "-print_format"
AddElement(\args()) : \args() = "json"
AddElement(\args()) : \args() = "-show_format"
AddElement(\args()) : \args() = "-show_streams"
AddElement(\args()) : \args() = path
EndWith
If task::run(@task) And task\exit_code = 0
LockMutex(tagsToGetLock)
SelectElement(tagsToGet(),i)
If ParseJSON(0,task\stdout)
ExtractJSONStructure(JSONValue(0),@metadata.ffprobe_answer,ffprobe_answer)
ClearMap(tags_lcase())
ForEach metadata\format\tags()
tags_lcase(LCase(MapKey(metadata\format\tags()))) = metadata\format\tags()
Next
tagsToGet()\format = metadata\format\format_name
tagsToGet()\duration = FormatDate("%hh:%ii:%ss",ValF(metadata\format\duration))
tagsToGet()\bitrate = Val(metadata\format\bit_rate)
If Left(tagsToGet()\duration,2) = "00"
tagsToGet()\duration = Mid(tagsToGet()\duration,4)
EndIf
With tagsToGet()\tags
\album = tags_lcase("album")
\artist = tags_lcase("artist")
\title = tags_lcase("title")
\track = tags_lcase("track")
If Not Len(\artist)
If tags_lcase("composer") : \artist = tags_lcase("composer") : EndIf
If tags_lcase("discogs_artist_list") : \artist = tags_lcase("discogs_artist_list") : EndIf
If tags_lcase("band") : \artist = tags_lcase("band") : EndIf
If tags_lcase("performer") : \artist = tags_lcase("performer") : EndIf
If tags_lcase("album_artist") : \artist = tags_lcase("album_artist") : EndIf
EndIf
;Debug tagsToGet()\id
;Debug tagsToGet()\tags\title
If tags_lcase("date")
\album + " (" + tags_lcase("date") + ")"
ElseIf tags_lcase("year")
\album + " (" + tags_lcase("year") + ")"
EndIf
EndWith
; last resort - look into streams
If tagsToGet()\tags\artist = "" Or tagsToGet()\tags\title = ""
ForEach metadata\streams()
ClearMap(tags_lcase())
ForEach metadata\streams()\tags()
tags_lcase(LCase(MapKey(metadata\streams()\tags()))) = metadata\streams()\tags()
Next
With tagsToGet()\tags
If tags_lcase("album") : \album = tags_lcase("album") : EndIf
If tags_lcase("artist") : \artist = tags_lcase("artist") : EndIf
If tags_lcase("title") : \title = tags_lcase("title") : EndIf
If tags_lcase("track") : \track = tags_lcase("track") : EndIf
If tags_lcase("date")
\album + " (" + tags_lcase("date") + ")"
ElseIf tags_lcase("year")
\album + " (" + tags_lcase("year") + ")"
EndIf
EndWith
Next
EndIf
FreeJSON(0)
PostEvent(#evTagGetSuccess,#PB_Ignore,#PB_Ignore,#PB_Ignore,@tagsToGet())
Else
PostEvent(#evTagGetFail,#PB_Ignore,#PB_Ignore,#PB_Ignore,@tagsToGet())
EndIf
UnlockMutex(tagsToGetLock)
Else
Debug task\stderr
PostEvent(#evTagGetFail,#PB_Ignore,#PB_Ignore,#PB_Ignore,@tagsToGet())
EndIf
i + numThreads - 1
Next
PostEvent(#evTagGetFinish)
EndProcedure
Procedure lyrics(forceGenius)
Shared nowPlaying,dataDir
Protected lyricsHash.s = StringFingerprint(nowPlaying\artist + " - " + nowPlaying\title,#PB_Cipher_MD5)
Protected task.task::task
Protected json.s
If forceGenius = #False And FileSize(dataDir + "/lyrics/" + lyricsHash + ".txt") > 0
nowPlaying\lyrics = ReadFileFast(dataDir + "/lyrics/" + lyricsHash + ".txt")
PostEvent(#evLyricsSuccessFile)
ProcedureReturn
EndIf
With task
If FileSize("/usr/local/bin/python3") > 0
\path = "/usr/local/bin/python3"
Else
\path = "/opt/homebrew/bin/python3"
EndIf
\workdir = dataDir + "/tmp"
\read_output = #True
AddElement(\args()) : \args() = "-u"
AddElement(\args()) : \args() = "-m"
AddElement(\args()) : \args() = "lyricsgenius"
AddElement(\args()) : \args() = "song"
AddElement(\args()) : \args() = nowPlaying\title
AddElement(\args()) : \args() = nowPlaying\artist
AddElement(\args()) : \args() = "--save"
AddElement(\args()) : \args() = "-q"
SetEnvironmentVariable("GENIUS_ACCESS_TOKEN",#geniusToken)
EndWith
If task::run(@task) And Left(task\stdout,6) = "Wrote "
Protected geniusPath.s = RTrim(RTrim(RTrim(Mid(task\stdout,7),#LF$)),".")
If FileSize(dataDir + "/tmp/" + geniusPath) > 0
json = ReadFileFast(dataDir + "/tmp/" + geniusPath)
If ParseJSON(2,json)
Protected isInstrumental.b = GetJSONBoolean(GetJSONMember(JSONValue(2),"instrumental"))
nowPlaying\lyrics = GetJSONString(GetJSONMember(JSONValue(2),"lyrics"))
If Len(nowPlaying\lyrics) = 0 And isInstrumental
nowPlaying\lyrics = "[Instrumental]"
EndIf
FreeJSON(2)
WriteFileFast(dataDir + "/lyrics/" + lyricsHash + ".txt",nowPlaying\lyrics)
PostEvent(#evLyricsSuccessGenius)
DeleteFile(dataDir + "/tmp/" + geniusPath,#PB_FileSystem_Force)
ProcedureReturn
EndIf
EndIf
EndIf
PostEvent(#evLyricsFail)
EndProcedure
Procedure canLoadLyrics()
Protected task.task::task
With task
If FileSize("/usr/local/bin/python3") > 0
\path = "/usr/local/bin/python3"
Else
\path = "/opt/homebrew/bin/python3"
EndIf
\read_output = #True
AddElement(\args()) : \args() = "-u"
AddElement(\args()) : \args() = "-m"
AddElement(\args()) : \args() = "lyricsgenius"
AddElement(\args()) : \args() = "-h"
EndWith
If task::run(@task) And FindString(task\stdout,"Download song lyrics from Genius.com")
ProcedureReturn #True
EndIf
EndProcedure
Procedure registerShortcuts()
Shared settings
globalHK::remove("",0,#True)
If settings\shortcuts\toggle_shortcut And globalHK::add(settings\shortcuts\toggle_shortcut,#PB_Event_Menu,#wnd,#dockPlayPause)
If IsWindow(#wndPrefs)
CocoaMessage(0,GadgetID(#prefsShortcutToggle),"setTextColor:",NSColor($00FF00))
EndIf
Else
If IsWindow(#wndPrefs)
CocoaMessage(0,GadgetID(#prefsShortcutToggle),"setTextColor:",NSColor($0000FF))
EndIf
EndIf
If settings\shortcuts\next_shortcut And globalHK::add(settings\shortcuts\next_shortcut,#PB_Event_Menu,#wnd,#dockNext)
If IsWindow(#wndPrefs)
CocoaMessage(0,GadgetID(#prefsShortcutNext),"setTextColor:",NSColor($00FF00))
EndIf
Else
If IsWindow(#wndPrefs)
CocoaMessage(0,GadgetID(#prefsShortcutNext),"setTextColor:",NSColor($0000FF))
EndIf
EndIf
If settings\shortcuts\previous_shortcut And globalHK::add(settings\shortcuts\previous_shortcut,#PB_Event_Menu,#wnd,#dockPrevious)
If IsWindow(#wndPrefs)
CocoaMessage(0,GadgetID(#prefsShortcutPrevious),"setTextColor:",NSColor($00FF00))
EndIf
Else
If IsWindow(#wndPrefs)
CocoaMessage(0,GadgetID(#prefsShortcutPrevious),"setTextColor:",NSColor($0000FF))
EndIf
EndIf
If settings\shortcuts\find_shortcut And globalHK::add(settings\shortcuts\find_shortcut,#PB_Event_Menu,#wnd,#playlistFind)
If IsWindow(#wndPrefs)
CocoaMessage(0,GadgetID(#prefsShortcutFind),"setTextColor:",NSColor($00FF00))
EndIf
Else
If IsWindow(#wndPrefs)
CocoaMessage(0,GadgetID(#prefsShortcutFind),"setTextColor:",NSColor($0000FF))
EndIf
EndIf
EndProcedure
Procedure saveSettings()
Shared dataDir.s
Shared lastfmSession.s,lastfmUser.s
Shared lastPlayedID
Shared cursorFollowsPlayback.b,playbackFollowsCursor.b,playbackOrder.b,stopAtQueueEnd.b
Shared settings.settings
Protected json.i = CreateJSON(#PB_Any)
If IsWindow(#wndPrefs)
settings\web\api_key = GetGadgetText(#prefsWebApiKey)
settings\web\web_server_port = Val(GetGadgetText(#prefsWebPort))
If GetGadgetState(#prefsWebEnable) = #PB_Checkbox_Checked
settings\web\use_web_server = #True
Else
settings\web\use_web_server = #False
EndIf
If GetGadgetState(#prefsUseTerminalNotifier) = #PB_Checkbox_Checked
settings\use_terminal_notifier = #True
Else
settings\use_terminal_notifier = #False
EndIf
If GetGadgetState(#prefsUseGenius) = #PB_Checkbox_Checked
settings\use_genius = #True
Else
settings\use_genius = #False
EndIf
EndIf
Protected object.i = SetJSONObject(JSONValue(json))
SetJSONInteger(AddJSONMember(object,"last_played_track_id"),lastPlayedID)
SetJSONBoolean(AddJSONMember(object,"use_terminal_notifier"),settings\use_terminal_notifier)
SetJSONBoolean(AddJSONMember(object,"use_genius"),settings\use_genius)
Protected objectShortcuts = SetJSONObject(AddJSONMember(object,"shortcuts"))
SetJSONString(AddJSONMember(objectShortcuts,"toggle_shortcut"),settings\shortcuts\toggle_shortcut)
SetJSONString(AddJSONMember(objectShortcuts,"next_shortcut"),settings\shortcuts\next_shortcut)
SetJSONString(AddJSONMember(objectShortcuts,"previous_shortcut"),settings\shortcuts\previous_shortcut)
SetJSONString(AddJSONMember(objectShortcuts,"find_shortcut"),settings\shortcuts\find_shortcut)
Protected objectWeb = SetJSONObject(AddJSONMember(object,"web"))
SetJSONBoolean(AddJSONMember(objectWeb,"use_web_server"),settings\web\use_web_server)
SetJSONInteger(AddJSONMember(objectWeb,"web_server_port"),settings\web\web_server_port)
SetJSONString(AddJSONMember(objectWeb,"api_key"),settings\web\api_key)
Protected objectLastfm = SetJSONObject(AddJSONMember(object,"lastfm"))
SetJSONString(AddJSONMember(objectLastfm,"session"),lastfmSession)
SetJSONString(AddJSONMember(objectLastfm,"user"),lastfmUser)
Protected objectWindow = SetJSONObject(AddJSONMember(object,"window"))
SetJSONInteger(AddJSONMember(objectWindow,"x"),WindowX(#wnd))
SetJSONInteger(AddJSONMember(objectWindow,"y"),WindowY(#wnd))
SetJSONInteger(AddJSONMember(objectWindow,"width"),WindowWidth(#wnd))
SetJSONInteger(AddJSONMember(objectWindow,"height"),WindowHeight(#wnd))
If IsWindowFullscreen(#wnd)
SetJSONBoolean(AddJSONMember(objectWindow,"fullscreen"),#True)
Else
SetJSONBoolean(AddJSONMember(objectWindow,"fullscreen"),#False)
EndIf
Protected objectPlaylist = SetJSONObject(AddJSONMember(object,"playlist"))
SetJSONInteger(AddJSONMember(objectPlaylist,"status_width"),GetGadgetItemAttribute(#playlist,-1,#PB_ListIcon_ColumnWidth,#status))
SetJSONInteger(AddJSONMember(objectPlaylist,"track_width"),GetGadgetItemAttribute(#playlist,-1,#PB_ListIcon_ColumnWidth,#track))
SetJSONInteger(AddJSONMember(objectPlaylist,"artist_width"),GetGadgetItemAttribute(#playlist,-1,#PB_ListIcon_ColumnWidth,#artist))
SetJSONInteger(AddJSONMember(objectPlaylist,"title_width"),GetGadgetItemAttribute(#playlist,-1,#PB_ListIcon_ColumnWidth,#title))
SetJSONInteger(AddJSONMember(objectPlaylist,"duration_width"),GetGadgetItemAttribute(#playlist,-1,#PB_ListIcon_ColumnWidth,#duration))
SetJSONInteger(AddJSONMember(objectPlaylist,"album_width"),GetGadgetItemAttribute(#playlist,-1,#PB_ListIcon_ColumnWidth,#album))
SetJSONInteger(AddJSONMember(objectPlaylist,"details_width"),GetGadgetItemAttribute(#playlist,-1,#PB_ListIcon_ColumnWidth,#details))
If settings\playlist\dont_group_by_albums
SetJSONBoolean(AddJSONMember(objectPlaylist,"dont_group_by_albums"),#True)
Else
SetJSONBoolean(AddJSONMember(objectPlaylist,"dont_group_by_albums"),#False)
EndIf
Protected objectPlayback = SetJSONObject(AddJSONMember(object,"playback"))
If cursorFollowsPlayback
SetJSONBoolean(AddJSONMember(objectPlayback,"cursor_follows_playback"),#True)
Else
SetJSONBoolean(AddJSONMember(objectPlayback,"cursor_follows_playback"),#False)
EndIf
If playbackFollowsCursor
SetJSONBoolean(AddJSONMember(objectPlayback,"playback_follows_cursor"),#True)
Else
SetJSONBoolean(AddJSONMember(objectPlayback,"playback_follows_cursor"),#False)
EndIf
If stopAtQueueEnd
SetJSONBoolean(AddJSONMember(objectPlayback,"stop_at_queue_end"),#True)
Else
SetJSONBoolean(AddJSONMember(objectPlayback,"stop_at_queue_end"),#False)
EndIf
Select playbackOrder
Case #orderShuffleTracks
SetJSONString(AddJSONMember(objectPlayback,"playback_order"),"shuffle_tracks")
Case #orderShuffleAlbums
SetJSONString(AddJSONMember(objectPlayback,"playback_order"),"shuffle_albums")
Default
SetJSONString(AddJSONMember(objectPlayback,"playback_order"),"default")
EndSelect
WriteFileFast(dataDir + "/settings.json",ComposeJSON(json,#PB_JSON_PrettyPrint))
;Debug ComposeJSON(json,#PB_JSON_PrettyPrint)
FreeJSON(json)
debugLog("main","settings saved")
EndProcedure
Procedure loadSettings()
Shared dataDir.s
Shared lastfmSession.s,lastfmUser.s
Shared lastPlayedID
Shared cursorFollowsPlayback.b,playbackFollowsCursor.b,playbackOrder.b,stopAtQueueEnd.b
Protected settingsData.s = ReadFileFast(dataDir + "/settings.json")
Protected json.i = ParseJSON(#PB_Any,settingsData)
Shared settings.settings
; defaults
settings\playback\cursor_follows_playback = #True
settings\playback\playback_follows_cursor = #False
settings\playback\stop_at_queue_end = #False
settings\playback\playback_order = "default"
settings\web\use_web_server = #False
settings\web\web_server_port = 8008
settings\use_terminal_notifier = #True
settings\use_genius = #True
settings\playlist\dont_group_by_albums = #False
If json
ExtractJSONStructure(JSONValue(json),@settings,settings,#PB_JSON_NoClear)
FreeJSON(json)
registerShortcuts()
If Len(Trim(settings\web\api_key)) = 0 ; in case it exists but empty
settings\web\api_key = StringFingerprint(Str(Date()),#PB_Cipher_MD5)
EndIf
If settings\web\web_server_port < 1025 Or settings\web\web_server_port > 65534
settings\web\web_server_port = 8008
EndIf
If IsWindow(#wndPrefs)
SetGadgetText(#prefsWebPort,Str(settings\web\web_server_port))
SetGadgetState(#prefsWebPort,settings\web\web_server_port)
SetGadgetText(#prefsWebApiKey,settings\web\api_key)
If settings\web\use_web_server
SetGadgetState(#prefsWebEnable,#PB_Checkbox_Checked)
DisableGadget(#prefsWebPort,#True)
Else
SetGadgetState(#prefsWebEnable,#PB_Checkbox_Unchecked)
DisableGadget(#prefsWebPort,#False)
EndIf
If settings\use_terminal_notifier
SetGadgetState(#prefsUseTerminalNotifier,#PB_Checkbox_Checked)
EndIf
If settings\use_genius
SetGadgetState(#prefsUseGenius,#PB_Checkbox_Checked)
EndIf
EndIf
lastfmSession = settings\lastfm\session
lastfmUser = settings\lastfm\user
lastPlayedID = settings\last_played_track_id
If settings\window\x Or settings\window\y Or settings\window\width Or settings\window\height
ResizeWindow(#wnd,settings\window\x,settings\window\y,settings\window\width,settings\window\height)
EndIf
If settings\window\fullscreen
EnterWindowFullscreen(#wnd)
EndIf
If settings\playlist\album_width
SetGadgetItemAttribute(#playlist,-1,#PB_ListIcon_ColumnWidth,settings\playlist\album_width,#album)
EndIf
If settings\playlist\artist_width
SetGadgetItemAttribute(#playlist,-1,#PB_ListIcon_ColumnWidth,settings\playlist\artist_width,#artist)
EndIf
If settings\playlist\details_width
SetGadgetItemAttribute(#playlist,-1,#PB_ListIcon_ColumnWidth,settings\playlist\details_width,#details)
EndIf
If settings\playlist\duration_width
SetGadgetItemAttribute(#playlist,-1,#PB_ListIcon_ColumnWidth,settings\playlist\duration_width,#duration)
EndIf
If settings\playlist\status_width
SetGadgetItemAttribute(#playlist,-1,#PB_ListIcon_ColumnWidth,settings\playlist\status_width,#status)
EndIf
If settings\playlist\title_width
SetGadgetItemAttribute(#playlist,-1,#PB_ListIcon_ColumnWidth,settings\playlist\title_width,#title)
EndIf
If settings\playlist\track_width
SetGadgetItemAttribute(#playlist,-1,#PB_ListIcon_ColumnWidth,settings\playlist\track_width,#track)
EndIf
If settings\playlist\dont_group_by_albums
SetMenuItemState(#menu,#playlistDontGroupByAlbums,#True)
Else
SetMenuItemState(#menu,#playlistDontGroupByAlbums,#False)
EndIf
If settings\playback\cursor_follows_playback
cursorFollowsPlayback = #True
SetMenuItemState(#menu,#playbackCursorFollowsPlayback,#True)
EndIf
If settings\playback\playback_follows_cursor
playbackFollowsCursor = #True
SetMenuItemState(#menu,#playbackPlaybackFollowsCursor,#True)
EndIf
If settings\playback\stop_at_queue_end
stopAtQueueEnd = #True
SetMenuItemState(#menu,#playbackStopAtQueueEnd,#True)
EndIf
Select settings\playback\playback_order
Case "shuffle_tracks"
playbackOrder = #orderShuffleTracks
SetMenuItemState(#menu,#playbackOrderShuffleTracks,#True)
Case "shuffle_albums"
playbackOrder = #orderShuffleAlbums
SetMenuItemState(#menu,#playbackOrderShuffleAlbums,#True)
Default
playbackOrder = #orderDefault
SetMenuItemState(#menu,#playbackOrderDefault,#True)
EndSelect
EndIf
debugLog("main","settings loaded")
EndProcedure
Procedure saveState()
Protected playlistSize = CountGadgetItems(#playlist)
Protected i.i
Shared dataDir.s
CreateJSON(1)
Protected arr = SetJSONArray(JSONValue(1))
For i = 0 To playlistSize - 1
If Not GetGadgetItemData(#playlist,i)
Protected elem = SetJSONObject(AddJSONElement(arr))
SetJSONString(AddJSONMember(elem,"details"),GetGadgetItemText(#playlist,i,#details))
SetJSONString(AddJSONMember(elem,"album"),GetGadgetItemText(#playlist,i,#album))
SetJSONString(AddJSONMember(elem,"duration"),GetGadgetItemText(#playlist,i,#duration))
SetJSONString(AddJSONMember(elem,"title"),GetGadgetItemText(#playlist,i,#title))
SetJSONString(AddJSONMember(elem,"artist"),GetGadgetItemText(#playlist,i,#artist))
SetJSONString(AddJSONMember(elem,"track"),GetGadgetItemText(#playlist,i,#track))
SetJSONString(AddJSONMember(elem,"file"),GetGadgetItemText(#playlist,i,#file))
EndIf
Next
Protected state.s = ComposeJSON(1,#PB_JSON_PrettyPrint)
FreeJSON(1)
If FileSize(dataDir + "/current_state.json") > 0
If FileSize(dataDir + "/current_state.json.backup") > 0 : DeleteFile(dataDir + "/current_state.json.backup") : EndIf
RenameFile(dataDir + "/current_state.json",dataDir + "/current_state.json.backup")
EndIf
If CreateFile(1,dataDir + "/current_state.json")
WriteString(1,state)
CloseFile(1)
debugLog("main","state saved")
Else
MessageRequester(#myName,"Can't save current state to " + dataDir + "/current_state.json",#PB_MessageRequester_Error)
EndIf
EndProcedure
Procedure loadState()
Shared dataDir.s
Protected json.s
Protected i.i
Protected NewMap values.s()
If FileSize(dataDir + "/current_state.json") > 0
json = ReadFileFast(dataDir + "/current_state.json")
If ParseJSON(1,json)
CocoaMessage(0,GadgetID(#playlist),"beginUpdates")
For i = 0 To JSONArraySize(JSONValue(1)) - 1
ExtractJSONMap(GetJSONElement(JSONValue(1),i),values())
If values("isAlbum") = ""
AddGadgetItem(#playlist,-1,#sep +
values("file") + #sep +
values("track") + #sep +
values("artist") + #sep +
values("title") + #sep +
values("duration") + #sep +
values("album") + #sep +
values("details"))
EndIf
Next
CocoaMessage(0,GadgetID(#playlist),"endUpdates")
FreeJSON(1)
debugLog("main","state loaded")
EndIf
EndIf
EndProcedure
Procedure loadAlbumArt()
Shared nowPlaying
Shared dataDir
Shared myDir
Protected fileDir.s = GetPathPart(nowPlaying\path)
Protected tmpDir.s = dataDir + "/tmp"
Protected ffmpeg.s = myDir + "/Tools/ffmpeg-ichm"
Protected albumArt.s
Protected internalArt.s = tmpDir + "/" + StringFingerprint(fileDir,#PB_Cipher_MD5) + ".jpg"
If nowPlaying\ID = -1
nowPlaying\albumArt= ""
If IsImage(#currentAlbumArt)
SetGadgetState(#albumArt,ImageID(#defaultAlbumArt))
FreeImage(#currentAlbumArt)
EndIf
SetGadgetState(#albumArt,ImageID(#defaultAlbumArt))
ProcedureReturn
EndIf
If FileSize(fileDir + "folder.jpg") > 0
albumArt = fileDir + "folder.jpg"
EndIf
If FileSize(fileDir + "cover.jpg") > 0
albumArt = fileDir + "cover.jpg"
EndIf
If FileSize(fileDir + "folder.jpeg") > 0
albumArt = fileDir + "folder.jpeg"
EndIf
If FileSize(fileDir + "cover.jpeg") > 0
albumArt = fileDir + "cover.jpeg"
EndIf
If FileSize(fileDir + "folder.png") > 0
albumArt = fileDir + "folder.png"
EndIf
If FileSize(fileDir + "cover.png") > 0
albumArt = fileDir + "cover.png"
EndIf
If Not Len(albumArt)
If ExamineDirectory(0,fileDir,"*.jpg")
While NextDirectoryEntry(0)
If DirectoryEntryType(0) = #PB_DirectoryEntry_File
albumArt = fileDir + DirectoryEntryName(0)
Break
EndIf
Wend
FinishDirectory(0)
EndIf
If ExamineDirectory(0,fileDir,"*.jpeg")
While NextDirectoryEntry(0)
If DirectoryEntryType(0) = #PB_DirectoryEntry_File
albumArt = fileDir + DirectoryEntryName(0)
Break
EndIf
Wend
FinishDirectory(0)
EndIf
If ExamineDirectory(0,fileDir,"*.png")
While NextDirectoryEntry(0)
If DirectoryEntryType(0) = #PB_DirectoryEntry_File
albumArt = fileDir + DirectoryEntryName(0)
Break
EndIf
Wend
FinishDirectory(0)
EndIf
EndIf
If FileSize(internalArt) > 0
albumArt = internalArt
EndIf
If Not Len(albumArt)
Protected task.task::task
With task
\path = ffmpeg
\workdir = tmpDir
\wait_program = #True
AddElement(\args()) : \args() = "-i"
AddElement(\args()) : \args() = nowPlaying\path
AddElement(\args()) : \args() = "-an"
AddElement(\args()) : \args() = "-vcodec"
AddElement(\args()) : \args() = "copy"
AddElement(\args()) : \args() = "-y"
AddElement(\args()) : \args() = internalArt
EndWith
If task::run(@task) And task\exit_code = 0 And FileSize(internalArt) > 0
albumArt = internalArt
EndIf
EndIf
If nowPlaying\albumArt <> albumArt
If IsImage(#currentAlbumArt)
SetGadgetState(#albumArt,ImageID(#defaultAlbumArt))
FreeImage(#currentAlbumArt)
EndIf
If albumArt
debugLog ("albumart","loading " + albumArt)
If LoadImage(#currentAlbumArt,albumArt)
CopyImage(#currentAlbumArt,#tmpImage)
ResizeImage(#currentAlbumArt,500,500,#PB_Image_Smooth)
SetGadgetState(#albumArt,ImageID(#currentAlbumArt))
Else
CopyImage(#defaultAlbumArt,#tmpImage)
debugLog ("albumart","failed to load")
SetGadgetState(#albumArt,ImageID(#defaultAlbumArt))
EndIf
Else
CopyImage(#defaultAlbumArt,#tmpImage)
debugLog ("albumart","not found")
SetGadgetState(#albumArt,ImageID(#defaultAlbumArt))
EndIf
ResizeImage(#tmpImage,300,300,#PB_Image_Smooth)
SaveImage(#tmpImage,tmpDir + "/album-art.jpg",#PB_ImagePlugin_JPEG,7)
FreeImage(#tmpImage)
nowPlaying\albumArt = albumArt
EndIf
EndProcedure
ProcedureC dockMenuHandler(object.i,selector.i,sender.i)
Shared nowPlaying
If IsMenu(#dockMenu) : FreeMenu(#dockMenu) : EndIf
CreateMenu(#dockMenu,0)
MenuTitle("")
If nowPlaying\ID <> -1
MenuItem(#dockArtist,nowPlaying\artist)
MenuItem(#dockTitle,nowPlaying\title)
DisableMenuItem(#dockMenu,#dockArtist,#True)
DisableMenuItem(#dockMenu,#dockTitle,#True)
MenuBar()
EndIf
If nowPlaying\isPaused Or nowPlaying\ID = -1
MenuItem(#dockPlayPause,"Play")
Else
MenuItem(#dockPlayPause,"Pause")
EndIf
If nowPlaying\ID <> -1
MenuItem(#dockNext,"Next Track")
MenuItem(#dockPrevious,"Previous Track")
MenuItem(#dockNextAlbum,"Next Album")
MenuItem(#dockPreviousAlbum,"Previous Album")
MenuItem(#dockStop,"Stop")
EndIf
ProcedureReturn CocoaMessage(0,MenuID(#dockMenu),"objectAtIndex:",0)
EndProcedure
Procedure isParsingCompleted(checkTags.b = #True)
Shared tagsParserThreads()
Shared tagsToGet()
ForEach tagsParserThreads()
If IsThread(tagsParserThreads())
ProcedureReturn #False
EndIf
Next
If checkTags And ListSize(tagsToGet())
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
Procedure updateNowPlaying(currentTime.i,duration.i)
Protected currentTimeFormatted.s
Protected durationFormatted.s
If duration >= 3600
currentTimeFormatted = FormatDate("%hh:%ii:%ss",currentTime)
durationFormatted = FormatDate("%hh:%ii:%ss",duration)
Else
currentTimeFormatted = FormatDate("%ii:%ss",currentTime)
durationFormatted = FormatDate("%ii:%ss",duration)
EndIf
SetGadgetText(#nowPlayingDuration,currentTimeFormatted + " / " + durationFormatted)
Protected part.f = duration / 100
If part > 0
SetGadgetState(#nowPlayingProgress,currentTime / part)
EndIf
EndProcedure
Procedure queueClear()
Shared playQueue()
Shared nowPlaying
ForEach playQueue()
If playQueue() <> nowPlaying\ID
SetGadgetItemText(#playlist,playQueue(),"",#status)
EndIf
Next
ClearList(playQueue())
EndProcedure
Procedure isQueued(id.i)
Shared playQueue()
If GetGadgetItemData(#playlist,id)
Protected album.s = GetGadgetItemText(#playlist,id,#album)
Protected i.i
For i = id + 1 To CountGadgetItems(#playlist) - 1
If GetGadgetItemText(#playlist,i,#album) = album
If isQueued(i)
ProcedureReturn #True
EndIf
Else
Break
EndIf
Next
Else
ForEach playQueue()
If playQueue() = id
ProcedureReturn #True
EndIf
Next
EndIf
EndProcedure
Procedure queueAdd(id.i)
Shared playQueue()
Shared nowPlaying
If Not isQueued(id)
If GetGadgetItemData(#playlist,id)
Protected album.s = GetGadgetItemText(#playlist,id,#album)
Protected i.i
For i = id + 1 To CountGadgetItems(#playlist) - 1
If GetGadgetItemText(#playlist,i,#album) = album
queueAdd(i)
Else
Break
EndIf
Next
Else
If id <> nowPlaying\ID
AddElement(playQueue())
playQueue() = id
SetGadgetItemText(#playlist,playQueue(),"[" + Str(ListSize(playQueue())) + "]",#status)
EndIf
EndIf
EndIf
EndProcedure
Procedure queueRemove(id.i)
Shared playQueue()
Shared nowPlaying
If GetGadgetItemData(#playlist,id)
Protected i.i
Protected NewList idsToRemove.i()
For i = id + 1 To CountGadgetItems(#playlist) - 1
If Not GetGadgetItemData(#playlist,i)
AddElement(idsToRemove())
idsToRemove() = i
Else
Break
EndIf
Next
ForEach idsToRemove()
queueRemove(idsToRemove())
Next
Else
ForEach playQueue()
If playQueue() = id
If id <> nowPlaying\ID
SetGadgetItemText(#playlist,playQueue(),"",#status)
EndIf
DeleteElement(playQueue())
Break
EndIf
Next
ForEach playQueue()
SetGadgetItemText(#playlist,playQueue(),"[" + Str(ListIndex(playQueue()) + 1) + "]",#status)
Next
EndIf
EndProcedure
Procedure queueNext(peek.b = #False)
Shared playQueue()
Shared queueEnded.b
Protected id.i
If ListSize(playQueue())
SelectElement(playQueue(),0)
id = playQueue()
If ListSize(playQueue()) = 1
queueEnded = #True
EndIf
If Not peek
queueRemove(id)
EndIf
Else
id = -1
EndIf
ProcedureReturn id
EndProcedure
Procedure setAlbums()
Protected currentAlbum.s
Protected newAlbum.s
Protected color.i
Protected i.i,j.i
Shared settings
CocoaMessage(0,GadgetID(#playlist),"beginUpdates")
j = CountGadgetItems(#playlist) - 1
For i = 0 To j
newAlbum = GetGadgetItemText(#playlist,i,#album)
If newAlbum <> currentAlbum
currentAlbum = newAlbum
If settings\playlist\dont_group_by_albums
If GetGadgetItemData(#playlist,i)
RemoveGadgetItem(#playlist,i)
j - 1
EndIf
Else
If Not GetGadgetItemData(#playlist,i)
AddGadgetItem(#playlist,i,#albumSymbol + #sep + #sep + #sep + GetGadgetItemText(#playlist,i,#artist) + #sep + #sep + #sep + GetGadgetItemText(#playlist,i,#album))
j + 1
SetGadgetItemData(#playlist,i,#True)
EndIf
EndIf
EndIf
Next
CocoaMessage(0,GadgetID(#playlist),"endUpdates")
EndProcedure
Procedure getNextAlbum()
Protected nextID.i = -1
Protected randomAlbum,album,i
Shared playbackOrder
Shared currentAlbum,numAlbums
Shared nowPlaying
Select playbackOrder
Case #orderShuffleAlbums
numAlbums = 0
For i = 0 To CountGadgetItems(#playlist) - 1
If GetGadgetItemData(#playlist,i)
numAlbums + 1
EndIf