-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathBroadcastAPI.pas
More file actions
2465 lines (2046 loc) · 63.2 KB
/
Copy pathBroadcastAPI.pas
File metadata and controls
2465 lines (2046 loc) · 63.2 KB
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
unit BroadcastAPI;
{$SCOPEDENUMS ON}
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
//{$DEFINE GENRES}
{$DEFINE LOG}
interface
uses
// Required Units
SysUtils, Classes, Graphics, Generics.Collections,
IdHTTP, IdGlobal, IdSSLOpenSSL, IdURI, DateUtils, Forms,
{$IFDEF FPC}fpjson, {$ELSE}Imaging.jpeg,{$ENDIF}
Cod.Types, Cod.Files, Cod.ArrayHelpers, Cod.JSON, Cod.JSON.Utils,
Cod.Version, UnitInfo
{$IFDEF FPC}, Cod.Platform.Lazarus{$ELSE}, IOUtils{$ENDIF};
type
// Cardinals
TArtSize = (Small, Medium, Large);
TWorkItem = (DownloadingImage);
TWorkItems = set of TWorkItem;
// Source
TDataSource = (None, Tracks, Albums, Artists, Playlists{$IFDEF GENRES}, Genres{$ENDIF});
TDataSources = set of TDataSource;
// Loading
TLoad = (Track, Album, Artist, PlayList);
TLoadSet = set of TLoad;
// Flags
TAPIOperationFlag = (ConnectionFailed, TokenRefreshed);
TAPIOperationFlags = set of TAPIOperationFlag;
const
LOAD_SET_ALL = [Low(TLoad)..High(TLoad)];
type
// Procs
TDataTypeUpdate = procedure(AUpdate: TDataSource) of object;
{ TCollageMaker }
TCollageMaker = class
private
TempResult: TJPEGImage;
procedure Build;
public
Image1,
Image2,
Image3,
Image4: TJPEGImage;
function Make: TJPEGImage;
end;
{ TSaveArtClass }
TSaveArtClass = class
private
procedure SaveFile;
public
Image: TJPEGImage;
FilePath: string;
procedure Save;
end;
// Records
TTrackHistoryItem = record
TrackID: string;
TimeStamp: TDateTime;
end;
TLibraryStatus = record
TotalTracks: integer;
TotalPlays: integer;
TokenExpireDate: TDateTime;
LastLibraryModified: TDateTime;
UpdateTimestamp: TDateTime;
(* Loading *)
procedure LoadFrom(AObj: IJObject);
end;
TAccount = record
Username: string;
OneQueue: boolean;
BitRate: string;
UserID: string;
CreationDate: TDateTime;
Verified: boolean;
BetaTester: boolean;
EmailAdress: string;
Premium: boolean;
VerificationDate: TDateTime;
(* Loading *)
procedure LoadFrom(AObj: IJObject);
end;
{ TTrackItem }
TTrackItem = record
(* Song properties in their JSON order, "?" is a unknown property *)
ID: string;
TrackNumber: cardinal;
Year: cardinal;
Title: string;
Genre: string;
LengthSeconds: cardinal;
AlbumID: string;
ArtworkID: string;
ArtistID: string;
// ??? Some ID integer
DayUploaded: TDate;
IsInTrash: boolean;
FileSize: integer;
UploadLocation: string;
// ??? empty string
Rating: cardinal;
Plays: cardinal;
StreamLocations: string;
AudioType: string;
ReplayGain: string;
UploadTime: TTime;
// ??? Tag Array
// Extra Data
CachedImage,
CachedImageLarge: TJpegImage;
Status: TWorkItems;
(* Utils *)
function GetStreamingURL: string;
(* Artwork *)
function ArtworkLoaded(Large: boolean = false): boolean;
function GetArtwork(Large: boolean = false): TJPEGImage;
(* Loading *)
procedure LoadFrom(Key: string; AArr: IJArray);
end;
TAlbumItem = record
(* Album properties in their JSON order, "?" is a unknown property *)
ID: string;
AlbumName: string;
TracksID: TArray<string>;
ArtistID: string;
IsInTrash: boolean;
Rating: cardinal;
Disk: cardinal;
Year: cardinal;
// ??? - Artist_aditional
// ??? - ICatID
CachedImage: TJpegImage;
Status: TWorkItems;
(* Artwork *)
function ArtworkLoaded: boolean;
function GetArtwork: TJPEGImage;
(* Loading *)
procedure LoadFrom(Key: string; AArr: IJArray);
end;
{ TArtistItem }
TArtistItem = record
(* Album properties in their JSON order, "?" is a unknown property *)
ID: string;
ArtistName: string;
TracksID: TArray<string>;
IsInTrash: boolean;
Rating: cardinal;
ArtworkID: string;
// ??? - ICatID
// Extra Data
CachedImage,
CachedImageLarge: TJpegImage;
Status: TWorkItems;
(* Artwork *)
function HasArtwork: boolean;
function ArtworkLoaded(Large: boolean = false): boolean;
function GetArtwork(Large: boolean = false): TJPEGImage;
(* Loading *)
procedure LoadFrom(Key: string; AArr: IJArray);
end;
{ TPlaylistItem }
TPlaylistItem = record
(* Album properties in their JSON order, "?" is a unknown property *)
ID: string;
Name: string;
TracksID: TArray<string>;
// ??? UID
// ??? system_created
// ??? public_id
PlaylistType: string;
Description: string;
ArtworkID: string;
// ??? SortType
// Extra Data
CachedImage,
CachedImageLarge: TJpegImage;
Status: TWorkItems;
(* Artwork *)
function HasArtwork: boolean;
function ArtworkLoaded(Large: boolean = false): boolean;
function GetArtwork(Large: boolean = false): TJPEGImage;
(* Loading *)
procedure LoadFrom(Key: string; AArr: IJArray);
end;
{ TGenreItem }
{$IFDEF GENRES}
TGenreItem = record
(* Album properties in their JSON order, "?" is a unknown property *)
ID: string;
TracksID: TStringArray;
CachedImage: TJpegImage;
Status: TWorkItems;
(* Artwork *)
function ArtworkLoaded: boolean;
function GetArtwork: TJPEGImage;
end;
{$ENDIF}
// Arrays
TArtists = TArray<TArtistItem>;
TAlbums = TArray<TAlbumItem>;
TTracks = TArray<TTrackItem>;
TPlaylists = TArray<TPlaylistItem>;
{$IFDEF GENRES}
TGenres = TArray<TGenreItem>;
{$ENDIF}
// Get Data
function GetTrack(ID: string): integer;
function GetAlbum(ID: string): integer;
function GetArtist(ID: string): integer;
function GetPlaylist(ID: string): integer;
{$IFDEF GENRES}
function GetGenre(ID: string): integer;
{$ENDIF}
function GetData(ID: string; Source: TDataSource): integer;
function GetItemID(Index: integer; Source: TDataSource): string;
function GetPlaylistOfType(AType: string): integer; (* thumbsup, recently-played, recently-uploaded *)
// Utils
function StringToDateTime(const ADateTimeStr: string; CovertUTC: boolean = true): TDateTime;
function StringToTime(const ADateTimeStr: string; CovertUTC: boolean = true): TTime;
function DateTimeToString(ADateTime: TDateTime; CovertUTC: boolean = true): string;
function DateToString(ADateTime: TDate; CovertUTC: boolean = true): string;
function Yearify(Year: cardinal): string;
// Memory
procedure APIFreeMemory;
// Artwork Store
procedure AddToArtworkStore(ID: string; Cache: TJpegImage; AType: TDataSource);
function ExistsInStore(ID: string; AType: TDataSource): boolean;
function GetArtStoreCachePath(ID: string; Extension: string; AType: TDataSource): string;
function GetArtStoreCache(ID: string; AType: TDataSource): TJpegImage;
function GetArtworkStore(AType: TDataSource = TDataSource.None): string;
procedure ClearArtworkStore;
procedure InitiateArtworkStore;
// Tracks
function UpdateTrackRating(const HTTP: TIdHTTP; ID: string; Rating: integer; ReloadLibrary: boolean): boolean;
function GetSongPlaylists(ID: string): TArray<string>;
function TrackRatingToLikedPlaylist(const HTTP: TIdHTTP; ID: string): boolean;
// Rating
function RatingToString(Rating: integer): string;
// Albums
function UpdateAlbumRating(const HTTP: TIdHTTP; ID: string; Rating: integer; ReloadLibrary: boolean): boolean;
// Artists
function UpdateArtistRating(const HTTP: TIdHTTP; ID: string; Rating: integer; ReloadLibrary: boolean): boolean;
// Playlist
function CreateNewPlayList(const HTTP: TIdHTTP; Name, Description: string; MakePublic: boolean; Tracks: TArray<string>): boolean; overload;
function AppentToPlaylist(const HTTP: TIdHTTP; ID: string; Tracks: TArray<string>): boolean;
function PrependToPlaylist(const HTTP: TIdHTTP; ID: string; Tracks: TArray<string>): boolean;
function ChangePlayList(const HTTP: TIdHTTP; ID: string; Tracks: TArray<string>): boolean;
function DeleteFromPlaylist(const HTTP: TIdHTTP; ID: string; Tracks: TArray<string>): boolean;
function TouchupPlaylist(const HTTP: TIdHTTP; ID: string): boolean;
function UpdatePlayList(const HTTP: TIdHTTP; ID: string; Name, Description: string; ReloadLibrary: boolean): boolean;
function DeletePlayList(const HTTP: TIdHTTP; ID: string): boolean;
{$IFDEF GENRES}
function DeleteGenre(const HTTP: TIdHTTP; ID: string): boolean;
{$ENDIF}
function DeleteTracks(const HTTP: TIdHTTP; Tracks: TArray<string>): boolean;
function DeleteAlbum(const HTTP: TIdHTTP; ID: string): boolean;
function DeleteArtist(const HTTP: TIdHTTP; ID: string): boolean;
function RestoreTracks(const HTTP: TIdHTTP; Tracks: TArray<string>): boolean;
function RestoreAlbum(const HTTP: TIdHTTP; ID: string): boolean;
function RestoreArtist(const HTTP: TIdHTTP; ID: string): boolean;
function EmptyTrash(const HTTP: TIdHTTP; Tracks: TArray<string>): boolean;
function CompleteEmptyTrash(const HTTP: TIdHTTP): boolean;
// History
function PushHistory(const HTTP: TIdHTTP; Items: TArray<TTrackHistoryItem>): boolean;
// Library
function LoadStatus(const HTTP: TIdHTTP): boolean;
function LoadLibrary(const HTTP: TIdHTTP; LoadSet: TLoadSet=LOAD_SET_ALL): boolean;
{$IFDEF GENRES}
procedure LoadLibraryGenres;
{$ENDIF}
procedure EmptyLibrary;
// Additional Data
function GetSongArtwork(ID: string; Size: TArtSize = TArtSize.Small): TJpegImage;
function SongArtCollage(ID1, ID2, ID3, ID4: string): TJpegImage;
// Status
procedure SetWorkStatus(Status: string);
procedure SetDataWorkStatus(Status: string);
procedure ResetWork;
// Utils
function CalculateLength(Seconds: cardinal): string;
/// V2
// Builders
function V2_CreateHTTP: TIdHTTP;
function V2_GetBody: IJObject;
// Requests
function V2_RequestPost(const HTTP: TIdHTTP; const Body: IJValue; const Endpoint: string; const Authorization: string=''): IJValue; overload;
function V2_RequestPost(const HTTP: TIdHTTP; const Body: TStringList; const Endpoint: string; const Authorization: string=''): IJValue; overload;
/// Actions
// Login
function V2_Login_AuthorizeURL(const State: string; const ACodeChallange: string): string;
function V2_Login_Token_GetFromCode(const HTTP: TIdHTTP; const ACode: string; const ACodeVerifier: string): boolean;
function V2_Login_Token_Refresh(const HTTP: TIdHTTP): boolean;
function V2_Login_Token_Revoke(const HTTP: TIdHTTP): boolean;
// Login - processer & modifier
function V2_Login_LoggedIn(const HTTP: TIdHTTP; out Flags: TAPIOperationFlags): boolean;
const
// Formattable Strings
DEVICE_NAME_CONST = '%S' + ' iBroadcast for Windows';
WELCOME_STRING = 'Welcome, %S';
WELCOME_STRING_SPECIAL = 'Happy holidays, %S';
// App
APP_NAME = 'Cod''s iBroadcast';
APP_VERSION: TVersion = (Major:APP_VERSION_MAJOR; Minor:APP_VERSION_MINOR; Maintenance: APP_VERSION_MAINTENANCE; Build: 0);
APP_USERMODELID = 'com.codrutsoft.ibroadcast';
APP_IDENTIFIER = APP_USERMODELID;
APP_DESCRIPTION = 'Codrut'#39's iBroadcast for Windows';
APP_USERAGENT = APP_NAME+'/%s';
// Endpoints
ENDPOINT_API = 'https://api.ibroadcast.com/';
ENDPOINT_API_LIBRARY = 'https://library.ibroadcast.com/';
ENDPOINT_ARTWORK = 'https://artwork.ibroadcast.com/artwork/%S-%U';
ENDPOINT_STREAMING = 'https://streaming.ibroadcast.com';
// OAuth2
OAUTH2_CLIENT_ID = '9ad81c4a98db11f1b50eb49691aa2236';
OAUTH2_CLIENT_SECRET = '6ef778c35907804c3babcd3f98e5f4c1d38301de50efbfc6fbd403c82bb99a06';
OAUTH2_REDIRECT_URI = 'http://127.0.0.1:49321/';
OAUTH2_SCOPE = 'user.account:read user.devices:read user.library:read user.library:write';
OAUTH2_LISTEN_PORT: word = 49321;
// Artwork Store
ART_EXT = '.jpeg';
var
// App Device token
LOGIN_TOKEN: string;
// Auth
OAuth2_RefreshToken: string;
OAuth2_AccessToken: string;
OAuth2_Expiry: TDateTime;
// Notify
OnWorkStatusChange: procedure(Status: string);
OnDataWorkStatusChange: procedure(Status: string);
// Cover Settings
DefaultArtSize: TArtSize = TArtSize.Medium;
// Login Information
DEVICE_NAME: string;
// Verbose Loggins
WORK_STATUS: string;
DATA_WORK_STATUS: string;
// Work
WorkCount: int64;
TotalWorkCount: int64;
// Setings
ValueRatingMode: boolean = false; // use rating stars
AllowArtCollage: boolean = true; { Bug fixed, error is no more }
// Notify Events
OnUpdateType: TDataTypeUpdate;
// Artwork Store
ArtworkStore: boolean = true;
MediaStoreLocation: string;
// Library
LibraryStatus: TLibraryStatus;
Account: TAccount;
Tracks: TTracks;
Albums: TAlbums;
Artists: TArtists;
Playlists: TPlaylists;
{$IFDEF GENRES}
Genres: TGenres;
{$ENDIF}
DefaultPicture: TJPEGImage;
// Debug & logs
EnableLogging: boolean = false;
DebugMode: boolean;
var
V2_HTTP: TIdHTTP;
implementation
uses
MainUI;
function V2_CreateHTTP: TIdHTTP;
var
V2_SSL: TIdSSLIOHandlerSocketOpenSSL;
begin
Result := TIdHTTP.Create(nil);
// Init SSL
V2_SSL := TIdSSLIOHandlerSocketOpenSSL.Create(Result);
V2_SSL.SSLOptions.SSLVersions := [sslvTLSv1_2];
Result.IOHandler := V2_SSL;
end;
function V2_GetBody: IJObject;
begin
Result := TJObject.CreateNew;
Result.Put('client', APP_IDENTIFIER);
Result.Put('version', APP_VERSION.ToString);
Result.Put('device_name', APP_NAME);
Result.Put('user_agent', Format(APP_USERAGENT, [APP_VERSION.ToString]));
end;
function V2_RequestPost(const HTTP: TIdHTTP; const Body: IJValue; const Endpoint: string; const Authorization: string): IJValue;
var
ResponseStream, RequestStream: TStringStream;
begin
Result := nil;
// Set options
HTTP.HTTPOptions := HTTP.HTTPOptions + [hoNoProtocolErrorException, hoWantProtocolErrorContent, hoWaitForUnexpectedData];
// Set headers
HTTP.Request.CustomHeaders.Clear;
if Body <> nil then
HTTP.Request.ContentType := 'application/json; charset=utf-8';
if Authorization <> '' then
HTTP.Request.CustomHeaders.AddValue('Authorization', 'Bearer ' + Authorization);
// Send request and receive response
RequestStream := TStringStream.Create('', TEncoding.UTF8);
ResponseStream := TStringStream.Create('', TEncoding.UTF8);
if Body <> nil then
RequestStream.WriteString(Body.ToJSON);
try
try
{$IFDEF LOG}if DebugMode then AddToLog('POST: '+Endpoint);{$ENDIF}
HTTP.Post(Endpoint, RequestStream, ResponseStream);
{$IFDEF LOG}if DebugMode then AddToLog('HEADERS:'+sLineBreak+string.Join(sLineBreak, HTTP.Request.RawHeaders.ToStringArray));{$ENDIF}
{$IFDEF LOG}if DebugMode then AddToLog('BODY:'+sLineBreak+RequestStream.DataString);{$ENDIF}
// Parse response and extract numbers
if (ResponseStream.Size > 0) and (ResponseStream.DataString <> 'OK') then
Result := TJValue.ParseJson(ResponseStream.DataString);
{$IFDEF LOG}if DebugMode then AddToLog('RESPONSE:'+ResponseStream.DataString+sLineBreak+sLineBreak);{$ENDIF}
except
on E: Exception do begin
{$IFDEF LOG}AddToLog(E.ClassName+': '+E.Message);{$ENDIF}
Exit;
end;
end;
finally
RequestStream.Free;
ResponseStream.Free;
end;
end;
function V2_RequestPost(const HTTP: TIdHTTP; const Body: TStringList; const Endpoint: string; const Authorization: string=''): IJValue; overload;
var
ResponseStream: TStringStream;
begin
Result := nil;
// Set options
HTTP.HTTPOptions := HTTP.HTTPOptions + [hoNoProtocolErrorException, hoWantProtocolErrorContent, hoWaitForUnexpectedData];
// Set headers
HTTP.Request.CustomHeaders.Clear;
if Body <> nil then
HTTP.Request.ContentType := 'application/x-www-form-urlencoded; charset=utf-8';
if Authorization <> '' then
HTTP.Request.CustomHeaders.AddValue('Authorization', 'Bearer ' + Authorization);
// Send request and receive response
ResponseStream := TStringStream.Create('', TEncoding.UTF8);
try
try
{$IFDEF LOG}if DebugMode then AddToLog('POST: '+Endpoint);{$ENDIF}
HTTP.Post(Endpoint, Body, ResponseStream);
{$IFDEF LOG}if DebugMode then AddToLog('HEADERS:'+sLineBreak+string.Join(sLineBreak, HTTP.Request.RawHeaders.ToStringArray)); {$ENDIF}
{$IFDEF LOG}if DebugMode then AddToLog('BODY:'+sLineBreak+Body.Text);{$ENDIF}
// Parse response and extract numbers
if (ResponseStream.Size > 0) then begin
if ResponseStream.DataString = 'OK' then
Exit( TJNull.CreateNew );
Result := TJValue.ParseJson(ResponseStream.DataString);
end;
{$IFDEF LOG}if DebugMode then AddToLog('RESPONSE:'+ResponseStream.DataString+sLineBreak+sLineBreak);{$ENDIF}
except
on E: Exception do begin
{$IFDEF LOG}AddToLog(E.ClassName+': '+E.Message);{$ENDIF}
Exit;
end;
end;
finally
ResponseStream.Free;
end;
end;
function V2_Login_AuthorizeURL(const State: string; const ACodeChallange: string): string;
begin
Result :=
'https://oauth.ibroadcast.com/authorize?' +
'client_id=' + TIdURI.ParamsEncode(OAUTH2_CLIENT_ID) +
'&state=' + TIdURI.ParamsEncode(State) +
'&response_type=' + TIdURI.ParamsEncode('code') +
'&code_challenge=' + TIdURI.ParamsEncode(ACodeChallange) +
'&code_challenge_method=S256' +
'&scope=' + TIdURI.ParamsEncode(OAUTH2_SCOPE);
end;
function V2_Login_Token_GetFromCode(const HTTP: TIdHTTP; const ACode: string; const ACodeVerifier: string): boolean;
var
Params: TStringList;
Response: IJValue;
Obj: IJObject;
begin
Result := false;
//
Params := TStringList.Create;
try
Params.Add('grant_type=authorization_code');
Params.Add('code=' + ACode);
Params.Add('client_id=' + OAUTH2_CLIENT_ID);
Params.Add('redirect_uri=' + OAUTH2_REDIRECT_URI);
Params.Add('code_verifier=' + ACodeVerifier);
// Send
Response := V2_RequestPost(HTTP, Params,'https://oauth.ibroadcast.com/token');
finally
Params.Free;
end;
//
if (Response = nil) or not Response.IsObject then
Exit;
Obj := Response.AsObject;
if not (Obj.KeyExists('access_token') and Obj.KeyExists('expires_in') and Obj.KeyExists('refresh_token')) then
Exit;
//
OAuth2_RefreshToken := Obj['refresh_token'].AsString;
OAuth2_AccessToken := Obj['access_token'].AsString;
OAuth2_Expiry := IncSecond(Now, Obj['expires_in'].AsInteger);
//
Result := true;
end;
function V2_Login_Token_Refresh(const HTTP: TIdHTTP): boolean;
var
Params: TStringList;
Response: IJValue;
Obj: IJObject;
begin
Result := false;
//
Params := TStringList.Create;
try
Params.Add('grant_type=refresh_token');
Params.Add('refresh_token=' + OAuth2_RefreshToken);
Params.Add('client_id=' + OAUTH2_CLIENT_ID);
Params.Add('redirect_uri=' + OAUTH2_REDIRECT_URI);
// Send
Response := V2_RequestPost(HTTP, Params,'https://oauth.ibroadcast.com/token');
finally
Params.Free;
end;
//
if (Response = nil) or not Response.IsObject then
Exit;
Obj := Response.AsObject;
if not (Obj.KeyExists('access_token') and Obj.KeyExists('expires_in') and Obj.KeyExists('refresh_token')) then
Exit;
//
OAuth2_RefreshToken := Obj['refresh_token'].AsString;
OAuth2_AccessToken := Obj['access_token'].AsString;
OAuth2_Expiry := IncSecond(Now, Obj['expires_in'].AsInteger);
//
Result := true;
end;
function V2_Login_Token_Revoke(const HTTP: TIdHTTP): boolean;
var
Params: TStringList;
Response: IJValue;
Obj: IJObject;
begin
Result := false;
//
Params := TStringList.Create;
try
Params.Add('refresh_token=' + OAuth2_RefreshToken);
Params.Add('client_id=' + OAUTH2_CLIENT_ID);
// Send
Response := V2_RequestPost(HTTP, Params,'https://oauth.ibroadcast.com/revoke');
finally
Params.Free;
end;
//
if Response = nil then
Exit;
if Response.IsObject then begin
Obj := Response.AsObject;
Result := not Obj.KeyExists('error');
if not Result then Exit;
end;
Result := true;
OAuth2_RefreshToken := '';
OAuth2_AccessToken := '';
OAuth2_Expiry := 0;
end;
function V2_Login_LoggedIn(const HTTP: TIdHTTP; out Flags: TAPIOperationFlags): boolean;
var
Response: IJValue;
Body: IJObject;
Obj: IJObject;
Succeeded: boolean;
begin
Result := false;
Flags := [];
Body := V2_GetBody;
Body.Put('mode', 'status');
Response := V2_RequestPost(HTTP, Body, ENDPOINT_API, OAuth2_AccessToken);
Succeeded := Response <> nil;
if not Succeeded then
Flags := Flags + [TAPIOperationFlag.ConnectionFailed];
if (Response = nil) or not Response.IsObject then
Exit;
Obj := Response.AsObject;
// Logged in
Result := Obj.KeyExists('authenticated') and Obj['authenticated'].AsBoolean;
// Migrate refresh token (if access token failed, or it expired/expires in the next 30 minutes)
if OAuth2_RefreshToken <> '' then
if (Succeeded and not Result)
or (IncMinute(Now, 30) >= OAuth2_Expiry) then begin
Result := V2_Login_Token_Refresh(HTTP);
Flags := Flags + [TAPIOperationFlag.TokenRefreshed];
end;
// Clear login on server confirmation
if Succeeded and not Result then begin
OAuth2_RefreshToken := '';
OAuth2_AccessToken := '';
OAuth2_Expiry := 0;
end;
end;
procedure APIFreeMemory;
var
I: Integer;
begin
for I := 0 to High(Tracks) do
begin
if Tracks[I].CachedImage <> nil then
Tracks[I].CachedImage.Free;
if Tracks[I].CachedImageLarge <> nil then
Tracks[I].CachedImageLarge.Free;
end;
end;
procedure AddToArtworkStore(ID: string; Cache: TJpegImage; AType: TDataSource);
var
LifeSaver: TSaveArtClass;
begin
// gud
LifeSaver := TSaveArtClass.Create;
try
LifeSaver.Image := Cache;
LifeSaver.FilePath:=GetArtStoreCachePath(ID, ART_EXT, AType);
LifeSaver.Save;
finally
LifeSaver.Free;
end;
end;
function ExistsInStore(ID: string; AType: TDataSource): boolean;
var
Path: string;
begin
if not ArtworkStore then
Exit(false);
Path := GetArtStoreCachePath(ID, ART_EXT, AType);
Result := fileexists( Path );
end;
function GetArtStoreCachePath(ID: string; Extension: string; AType: TDataSource
): string;
begin
{$IFDEF GENRES}
if AType in [TDataSource.Genres] then
ID := ValidateFileName(ID);
{$ENDIF}
Result := GetArtworkStore(AType) + ID + Extension;
end;
function GetArtStoreCache(ID: string; AType: TDataSource): TJpegImage;
var
Path: string;
begin
Path := GetArtStoreCachePath(ID, ART_EXT, AType);
Result := TJpegImage.Create;
Result.LoadFromFile(Path);
end;
function GetArtworkStore(AType: TDataSource): string;
begin
Result := IncludeTrailingPathDelimiter(MediaStoreLocation);
case AType of
TDataSource.Tracks: Result := Result + 'tracks';
TDataSource.Albums: Result := Result + 'albums';
TDataSource.Artists: Result := Result + 'artists';
TDataSource.Playlists: Result := Result + 'playlists';
{$IFDEF GENRES}TDataSource.Genres: Result := Result + 'genres';{$ENDIF}
end;
Result := IncludeTrailingPathDelimiter(Result);
end;
procedure ClearArtworkStore;
var
Path: string;
begin
Path := GetArtworkStore;
if TDirectory.Exists(Path) then
TDirectory.Delete(Path, true);
end;
procedure InitiateArtworkStore;
var
ArtRoot: string;
begin
if not ArtworkStore then
Exit;
ArtRoot := GetArtworkStore;
if not TDirectory.Exists(ArtRoot) then
TDirectory.CreateDirectory(ArtRoot);
TDirectory.CreateDirectory(GetArtworkStore(TDataSource.Tracks));
TDirectory.CreateDirectory(GetArtworkStore(TDataSource.Albums));
TDirectory.CreateDirectory(GetArtworkStore(TDataSource.Artists));
TDirectory.CreateDirectory(GetArtworkStore(TDataSource.Playlists));
{$IFDEF GENRES}
TDirectory.CreateDirectory(GetArtworkStore(TDataSource.Genres));
{$ENDIF}
end;
function UpdateTrackRating(const HTTP: TIdHTTP; ID: string; Rating: integer; ReloadLibrary: boolean): boolean;
var
Body: IJObject;
Response: IJValue;
Obj: IJObject;
begin
Result := false;
SetWorkStatus('Setting track rating');
//
Body := V2_GetBody;
Body.Put('mode', 'ratetrack');
Body.Put('track_id', ID);
Body.Put('rating', Rating);
Response := V2_RequestPost(HTTP, Body, ENDPOINT_API, OAuth2_AccessToken);
if (Response = nil) or not Response.IsObject then
Exit;
Obj := Response.AsObject;
Result := Obj.KeyExists('result') and Obj.Memory['result'].AsBoolean;
// Re-load
if ReloadLibrary then
LoadLibrary(HTTP, [TLoad.Track]);
end;
function GetSongPlaylists(ID: string): TArray<string>;
var
I: Integer;
begin
// Search
Result := [];
for I := 0 to High(Playlists) do
if TArrayUtils<string>.Contains(ID, Playlists[I].TracksID) then
Result := Result + [Playlists[I].ID];
end;
function TrackRatingToLikedPlaylist(const HTTP: TIdHTTP; ID: string): boolean;
var
Index, SongIndex: integer;
Fav: boolean;
IsFav: boolean;
begin
Result := false;
SongIndex := GetTrack(ID);
Index := GetPlaylistOfType('thumbsup');
if (Index <> -1) and (SongIndex <> -1) then
begin
Fav := TArrayUtils<string>.Contains(ID, Playlists[Index].TracksID);
if ValueRatingMode then
IsFav := Tracks[SongIndex].Rating = 10
else
IsFav := Tracks[SongIndex].Rating in [10, 5];
if IsFav <> Fav then
begin
if IsFav then
Result := PrependToPlaylist(HTTP, Playlists[Index].ID, [ID])
else
Result := DeleteFromPlaylist(HTTP, Playlists[Index].ID, [ID]);
end;
end;
end;
function RatingToString(Rating: integer): string;
begin
if ValueRatingMode then
begin
if Rating <> 0 then
Result := Format('%D/%D', [Rating, 10])
else
Result := 'Not rated';
end
else
case Rating of
10, 5: Result := 'Liked';
1: Result := 'Disliked';
else Result := 'Not rated';
end;
end;
function UpdateAlbumRating(const HTTP: TIdHTTP; ID: string; Rating: integer; ReloadLibrary: boolean): boolean;
var
Body: IJObject;
Response: IJValue;
Obj: IJObject;
begin
Result := false;
SetWorkStatus('Setting album rating');
//
Body := V2_GetBody;
Body.Put('mode', 'ratealbum');
Body.Put('album_id', ID);
Body.Put('rating', Rating);
Response := V2_RequestPost(HTTP, Body, ENDPOINT_API, OAuth2_AccessToken);
if (Response = nil) or not Response.IsObject then
Exit;
Obj := Response.AsObject;
Result := Obj.KeyExists('result') and Obj.Memory['result'].AsBoolean;
// Re-load
if ReloadLibrary then
LoadLibrary(HTTP, [TLoad.Album]);
end;
function UpdateArtistRating(const HTTP: TIdHTTP; ID: string; Rating: integer; ReloadLibrary: boolean): boolean;
var
Body: IJObject;
Response: IJValue;
Obj: IJObject;
begin
Result := false;
SetWorkStatus('Setting artist rating');
//
Body := V2_GetBody;
Body.Put('mode', 'rateartist');
Body.Put('name', ID);
Body.Put('description', Rating);
Response := V2_RequestPost(HTTP, Body, ENDPOINT_API, OAuth2_AccessToken);
if (Response = nil) or not Response.IsObject then
Exit;
Obj := Response.AsObject;
Result := Obj.KeyExists('result') and Obj.Memory['result'].AsBoolean;
// Re-load
if ReloadLibrary then
LoadLibrary(HTTP, [TLoad.Artist]);
end;