-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathActorInfoServiceImplementation.pas
More file actions
7670 lines (6402 loc) · 330 KB
/
ActorInfoServiceImplementation.pas
File metadata and controls
7670 lines (6402 loc) · 330 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 ActorInfoServiceImplementation;
interface
uses
System.Classes,
System.SysUtils,
System.DateUtils,
System.StrUtils,
System.IOUtils,
System.JSON,
System.Math,
System.NetEncoding,
System.Generics.Collections,
REST.JSON,
XData.Server.Module,
XData.Service.Common,
XData.Sys.Exceptions,
IdHTTP, IdSSLOpenSSL, idURI,
System.Net.URLClient,
System.Net.HttpClientComponent,
System.Net.HttpClient,
brotli,
IdGlobalProtocols,
HashObj,
MiscObj,
ActorInfoService;
type
[ServiceImplementation]
TActorInfoService = class(TInterfacedObject, IActorInfoService)
// Used to help ensure client is using latest version, hopefully avoiding any server caching issues
function GetClientVersion(Day: String): TStream;
// Lookup data directly rather than through a query of some kind
function Lookup(Secret: String; Lookup: String; Progress: String):TStream;
// These get data from Wikipedia which is then used as the source for locating TMDb data
function BirthDay(Secret: String; aMonth: Integer; aDay: Integer; Progress: String):TStream;
function DeathDay(Secret: String; aMonth: Integer; aDay: Integer; Progress: String):TStream;
function ReleaseDay(Secret: String; aMonth: Integer; aDay: Integer; Progress: String):TStream;
function Relatives(Secret: String; RelatedTo: Integer; RelatedName: String; Progress: String):TStream;
// Get Actor information based on dates
function ActorBirthDay(Secret: String; aMonth: Integer; aDay: Integer; Progress: String):TStream;
function ActorDeathDay(Secret: String; aMonth: Integer; aDay: Integer; Progress: String):TStream;
function ActorBirthDay50(Secret: String; aMonth: Integer; aDay: Integer; Progress: String):TStream;
function ActorDeathDay50(Secret: String; aMonth: Integer; aDay: Integer; Progress: String):TStream;
// Get Movie information based on dates
function MovieReleaseDay(Secret: String; aMonth: Integer; aDay: Integer; Progress: String):TStream;
// Get Actor information based on TMDb top 10,000 list
function TopOneThousand(Secret: String; Progress: String):TStream;
function TopFiveThousand(Secret: String; Progress: String):TStream;
// Get the top actors for today (or another day) - used by ActoriousToday, for example
function TopToday(Secret: String; aMonth: Integer; aDay: Integer):TStream;
// Get information from a TMDb search
function SearchPeople(Secret: String; SearchTerm: String; Progress: String):TStream;
function SearchPeopleExtended(Secret: String; SearchTerm: String; Progress: String):TStream;
// Do our own search, thanks very much
function SearchLocal(Secret: String; SearchTerm: String; Progress: String):TStream;
// Return current progress of a request
function Progress(Secret: String; Progress: String):String;
// Other Support Functions
function HashThis(InputText: String):String;
end;
implementation
uses Unit2;
{ TActorInfoService }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// HashThis //
// //
// Returns a SHA2 hash of the supplied string. This is used to create a lookup for the Lookup endpoint, which is in //
// turn used to populate a dictionary to cache the Lookup requests. The main rationale is to help speed up generating //
// the data for the Top1000 requests, and to reduce the server overhead in responding to them. //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function TActorInfoService.HashThis(InputText: String):String;
var
SHA2: TSHA2Hash;
begin
SHA2 := TSHA2Hash.Create;
SHA2.HashSizeBits:= 256;
SHA2.OutputFormat:= hexa;
SHA2.Unicode:= noUni;
Result := LowerCase(SHA2.Hash(InputText));
SHA2.Free;
end;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// LoadJSON //
// //
// This is intended as an alternative to TStringList.LoadFromFile. Why? Well, that seems to do //
// a lot of file locking that blocks other processes reading the same files. //
// https://stackoverflow.com/questions/4845380/how-can-i-efficiently-read-the-first-few-lines-of-many-files-in-delphi //
// Will see if this helps. //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
procedure SLLoadJSON(var StrList: TStringList; Filename: String);
var
FS: TFileStream;
TR: TTextReader;
Attempt: Integer;
begin
Attempt := 0;
while (Attempt <= 3) do
begin
try
StrList.Clear;
FS := TFileStream.Create(FileName, fmOpenRead);
TR := TStreamReader.Create(FS);
try
while not((TR as TStreamReader).EndOfStream) do
StrList.Add( TR.ReadLine );
finally
TR.Free;
FS.Free;
end;
Attempt := 10;
except on E: Exception do
begin
Attempt := Attempt + 1;
if (Pos('The system cannot find the file specified', E.Message) > 0) or
(Pos('The system cannot find the path specified', E.Message) > 0) then
begin
// Not doing anything about this
Attempt := 10;
end
else if (Attempt <= 3) then
begin
MainForm.LogEvent('SLLoadJSON Error: Retrying '+IntToStr(Attempt)+'/3: ['+E.ClassName+'] '+Copy(E.Message,1,30)+'...'+RightStr(E.Message,30)+' ('+Filename+')');
Sleep(5000*Attempt);
end
else
begin
MainForm.LogException('SLLoadJSON Error', E.ClassName, E.Message, Filename);
end;
end;
end;
end;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////
// FilterResponse //
// //
// Sometimes we get back JSON that has illegal characters in it. Much of the data from TMDb, for //
// example, is user-supplied and it seemingly doesn't filter these out. As these trip up the //
// various JSON processing functions downstream (in the client even) we need to get rid of them //
// as soon as possible. //
///////////////////////////////////////////////////////////////////////////////////////////////////
function FilterResponse(Response: String):String;
begin
if Copy(Response,1,1) <> '{' then
begin
Result := '{}';
exit;
end;
Result := Response;
Result := StringReplace(Result, chr( 9), '', [rfReplaceAll]); // Tab
Result := StringReplace(Result, chr(10), '', [rfReplaceAll]); // NL
Result := StringReplace(Result, chr(13), '', [rfReplaceAll]); // CR
Result := StringReplace(Result, '\u0013', '', [rfReplaceAll]); // CR
Result := StringReplace(Result, '\u00A0', ' ', [rfReplaceAll]); // Non-breaking space
Result := StringReplace(Result, '\S', '/S', [rfReplaceAll]);
Result := StringReplace(Result, '\\', ' ', [rfReplaceAll]);
Result := StringReplace(Result, ' \ ', ' / ', [rfReplaceAll]);
end;
function FilterArrayResponse(Response: String):String;
begin
if Copy(Response,1,1) <> '[' then
begin
Result := '[]';
exit;
end;
Result := Response;
Result := StringReplace(Result, chr( 9), '', [rfReplaceAll]); // Tab
Result := StringReplace(Result, chr(10), '', [rfReplaceAll]); // NL
Result := StringReplace(Result, chr(13), '', [rfReplaceAll]); // CR
Result := StringReplace(Result, '\u0013', '', [rfReplaceAll]); // CR
Result := StringReplace(Result, '\u00A0', ' ', [rfReplaceAll]); // Non-breaking space
Result := StringReplace(Result, '\S', '/S', [rfReplaceAll]);
Result := StringReplace(Result, '\\', ' ', [rfReplaceAll]);
Result := StringReplace(Result, ' \ ', ' / ', [rfReplaceAll]);
end;
///////////////////////////////////////////////////////////////////////////////////////////////////
// SetBrotliHeaders //
// //
// When returning data, we're going to be sending back Brotli-compressed files, so we need the //
// headers to reflect this, and also that the data is JSON. //
///////////////////////////////////////////////////////////////////////////////////////////////////
procedure SetBrotliHeaders;
begin
TXDataOperationContext.Current.Response.Headers.SetValue('content-type', 'application/json');
TXDataOperationContext.Current.Response.Headers.SetValue('content-encoding', 'br');
TXDataOperationContext.Current.Response.Headers.SetValue('Access-Control-Expose-Headers','x-uncompressed-content-length');
end;
///////////////////////////////////////////////////////////////////////////////////////////////////
// GetImageURI //
// //
// Given an image URL (expecting a TMDb image reference here) the actual image is retrieved and //
// then converted to a Data URI. This is all to pass to the first launch of the Actorious app, //
// so we can display as much of the first page as possible (mostly the initial top section) //
// without having to do another fetch. //
// //
// This is complicated slightly by wanting to encode Base64 without using any line breaks, which //
// are generally not allowed in JSON. //
///////////////////////////////////////////////////////////////////////////////////////////////////
function GetImageURI(URL: String): String;
var
Query: String; // The full image URL we want to retrieve
Client: TNetHTTPClient; // The client connection
Photo: TMemoryStream; // The image coming back from TMDb
Encoding: TBase64Encoding;
begin
Query := 'https://image.tmdb.org/t/p/w185'+URL;
Client := TNetHTTPClient.Create(nil);
Client.ConnectionTimeout := 60000;
Client.ResponseTimeout := 60000;
Client.UserAgent := 'Actorious';
Client.SecureProtocols := [THTTPSecureProtocol.SSL3, THTTPSecureProtocol.TLS12];
Photo := TMemoryStream.Create;
try
Client.Get(Query, Photo);
Photo.Seek(0, soFromBeginning);
Encoding := TBase64Encoding.Create(0); // CharsPerLine -> 0 -> No line breaks
if Pos('.jpg', LowerCase(Query)) > 0
then Result := 'data:image/jpg;base64,'+Encoding.EncodeBytesToString(Photo.Memory, Photo.Size)
else Result := 'data:image/png;base64,'+Encoding.EncodeBytesToString(Photo.Memory, Photo.Size);
Encoding.Free;
except on E: Exception do
begin
MainForm.LogException('GetImageURI', E.ClassName, E.Message, Query);
Result := '';
end;
end;
Photo.Free;
Client.Free;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////
// GetDataFromWikidata //
// //
// The process is largely the same for retrieving data from Wikidata. So lets use a function to //
// make this a little simpler in the other functions
///////////////////////////////////////////////////////////////////////////////////////////////////
function GetDataFromWikidata(Query: String; CacheFile: String):String;
var
Client: TNetHTTPClient; // The client connection
Response: TStringList; // The response from TMDB
CacheAge: TDateTime; // The age of an existing cache file
Update: Boolean; // To Update or Not
begin
Response := TStringList.Create;
Response.Text := '';
// Determine whether we're updating;
Update := False;
if FileExists(CacheFile) then
begin
FileAge(CacheFile, CacheAge);
if HoursBetween(Now, CacheAge) > 24 then
begin
Update := True;
end
end
else
begin
Update := True;
end;
// Update only if necessary
if Update then
begin
// Standard commection, more or less.
Client := TNetHTTPClient.Create(nil);
Client.ConnectionTimeout := 60000;
Client.ResponseTimeout := 60000;
Client.UserAgent := 'Actorious';
Client.Accept := 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8';
Client.SecureProtocols := [THTTPSecureProtocol.SSL3, THTTPSecureProtocol.TLS12];
// Try and get the data
try
Response.Text := Client.Get(Query).ContentAsString(TEncoding.UTF8);
Response.Text := FilterResponse(Response.Text);
if (Pos('SPARQL-QUERY', Response.Text) = 0) and (Response.Text <> '{}')
then Response.SaveToFile(CacheFile, TEncoding.UTF8)
else Response.Text := '';
Client.Free;
except on E: Exception do
begin
MainForm.LogException('GetDataFromWikidata', E.ClassName, E.Message, CacheFile);
end;
end;
end;
// If We didn't get a response (or didn't ask for one) try and load the data
// from the cache instead.
if (Response.Text = '') then
begin
if FileExists(CacheFile)
then SLLoadJSON(Response, CacheFile);
end;
// If we still don't have data, well, I guess we don't have data
if (Response.Text = '') then Response.Text := '{}';
// Return the Response, Fresh or Cached or Otherwise
Result := FilterResponse(Response.Text);
Response.Free;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////
// GetPersonFromTMDb //
// //
// This simply contacts TMDb and gets as much information about a person as we can get in one //
// query (their API counts requests in this way so we try to make as few as we possibly can). //
// This contains a great deal of information about the person, but not as much detail about the //
// roles so we'll have to augment that data later on. //
///////////////////////////////////////////////////////////////////////////////////////////////////
function GetPersonfromTMDb(TMDb_ID: Integer; ForceUpdate: Boolean; ProgCount, TotCount:Integer):String;
var
Client: TNetHTTPClient; // The client connection
Query: String; // The query we're building
Response: TStringList; // The response from TMDB
CacheFile: String; // The location where we're going to put it
Update: Boolean; // To Update or Not
Reason: String; // Why are we doing what we're doing
Attempt: Integer;
begin
// Figure out where to put this
TDirectory.CreateDirectory(MainForm.AppCacheDir+'cache/people/tmdb/'+RightStr('00000000'+IntToStr(TMDB_ID),3));
CacheFile := MainForm.AppCacheDir+'cache/people/tmdb/'+RightStr('00000000'+IntToStr(TMDB_Id),3)+'/person-'+RightStr('00000000'+IntToStr(TMDb_ID),8)+'.json';
Response := TStringList.Create;
Response.Text := '';
// Determine whether we're updating;
Update := ForceUpdate;
if not(Update) then
begin
if FileExists(CacheFile) then
begin
if TFile.GetLastWriteTime(CacheFile) < (Now - 5) then
begin
Update := True;
Reason := 'Age';
end
end
else
begin
Update := True;
Reason := 'Miss';
// MainForm.LogEvent('- GetPersonFromTMDb Cache Miss [ '+RightStr('00000'+IntToStr(ProgCount),5)+' of '+RightStr('00000'+IntToStr(TotCount),5)+' ]: '+IntToStr(TMDb_ID));
end;
end
else
begin
Reason := 'Force';
end;
// Update only if necessary
if Update then
begin
// Standard commection, more or less.
Client := TNetHTTPClient.Create(nil);
Client.ConnectionTimeout := 60000;
Client.ResponseTimeout := 60000;
Client.UserAgent := 'Actorious';
Client.Accept := 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8';
Client.SecureProtocols := [THTTPSecureProtocol.SSL3, THTTPSecureProtocol.TLS12];
// Get basically everything that we possibly can. Note that the order is kinda important
Query := 'https://api.themoviedb.org/3/person/'+IntToSTr(TMDb_ID);
Query := Query+'?api_key='+MainForm.edTMDbAPI.Text;
Query := Query+'&language=en-US';
Query := Query+'&include_image_language=en,null';
Query := Query+'&append_to_response=images,videos,external_ids,tagged_images,combined_credits';
// Try and get the data
try
Response.Text := Client.Get(Query).ContentAsString(TEncoding.UTF8);
Client.Free;
Response.Text := FilterResponse(Response.Text);
Attempt := 0;
while Attempt < 3 do
begin
try
if (Response.Text <> '{}') and (Response.Text <> '')
then Response.SaveToFile(CacheFile, TEncoding.UTF8)
else Response.Text := '';
Attempt := 3;
except on E: Exception do
begin
if Attempt < 3 then
begin
Attempt := Attempt + 1;
MainForm.LogEvent('GetPersomFromTMDb/Error Writing File ('+IntToStr(Attempt)+'/3: '+CacheFile);
end
else
begin
MainForm.LogException('GetPersonFromTMDb/Error Writing File:', E.ClassName, E.Message, CacheFile);
end;
end;
end;
end;
except on E: Exception do
begin
MainForm.LogException('GetPersonFromTMDb', E.ClassName, E.Message, CacheFile);
end;
end;
end
else
begin
Reason := 'Cache';
end;
// If We didn't get a response (or didn't ask for one) try and load the data
// from the cache instead.
if (Response.Text = '') then
begin
if FileExists(CacheFile)
then SLLoadJSON(Response, CacheFile);
end;
// If we still don't have data, well, I guess we don't have data
if (Response.Text = '') then Response.Text := '{}';
// Return the Response, Fresh or Cached or Otherwise
Response.Text := FilterResponse(Response.Text);
Result := Response.Text;
Response.Free;
// Update Cache Information
inc(MainForm.PersonCacheRequests);
if Reason = 'Cache' then inc(MainForm.PersonCacheHit)
else if Reason = 'Force' then inc(MainForm.PersonCacheForce)
else if Reason = 'Age' then inc(MainForm.PersonCacheAge)
else if Reason = 'Miss' then inc(MainForm.PersonCacheMiss);
end;
///////////////////////////////////////////////////////////////////////////////////////////////////
// GetMovieFromTMDb //
// //
// This contacts TMDb and gets as much information about a movie as we can get in one single //
// query (their API counts requests in this way so we try to make as few as we possibly can). //
// This contains a great deal of information about the movie, enough to fill in the rest of the //
// pieces for the RoleTabulator as well as the list of actors when the row is selected. //
///////////////////////////////////////////////////////////////////////////////////////////////////
function GetMoviefromTMDb(TMDb_ID: Integer; ForceUpdate: Boolean):String;
var
Client: TNetHTTPClient; // The client connection
Query: String; // The query we're building
Response: TStringList; // The response from TMDB
CacheFile: String; // The location where we're going to put it
CacheAge: TDateTime; // The age of an existing cache file
Update: Boolean; // To Update or Not
Reason: String; // Why are we doing what we're doing
Success: Boolean;
Attempt: Integer;
begin
// Figure out where to put this
TDirectory.CreateDirectory(MainForm.AppCacheDir+'cache/movies/tmdb/'+RightStr('00000000'+IntToStr(TMDB_ID),3));
CacheFile := MainForm.AppCacheDir+'cache/movies/tmdb/'+RightStr('00000000'+IntToStr(TMDB_Id),3)+'/movie-'+RightStr('00000000'+IntToStr(TMDb_ID),8)+'.json';
Response := TStringList.Create;
Response.Text := '';
// Determine whether we're updating;
Update := ForceUpdate;
if not(Update) then
begin
if FileExists(CacheFile) then
begin
FileAge(CacheFile, CacheAge);
if HoursBetween(Now, CacheAge) > 168 then
begin
Update := True;
Reason := 'Age';
end
end
else
begin
Update := True;
Reason := 'Miss';
end;
end
else
begin
Reason := 'Force';
end;
// Update only if necessary
if Update then
begin
// Standard commection, more or less.
Client := TNetHTTPClient.Create(nil);
Client.ConnectionTimeout := 90000; // 90 seconds
Client.ResponseTimeout := 90000; // 90 seconds
Client.UserAgent := 'Actorious';
Client.Accept := 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8';
Client.SecureProtocols := [THTTPSecureProtocol.SSL3, THTTPSecureProtocol.TLS12];
// Get basically everything that we possibly can
Query := 'https://api.themoviedb.org/3/movie/'+IntToSTr(TMDb_ID);
Query := Query+'?api_key='+MainForm.edTMDbAPI.Text;
Query := Query+'&language=en-US';
Query := Query+'&include_image_language=en,null';
Query := Query+'&append_to_response=images,videos,external_ids,tagged_images,credits';
// Try and get the data
try
Response.Text := Client.Get(Query).ContentAsString(TEncoding.UTF8);
Client.Free;
except on E: Exception do
begin
MainForm.LogException('GetMovieFromTMDb', E.ClassName, E.Message, CacheFile);
end;
end;
Success := False;
Attempt := 1;
while ((Success = False) and (Attempt <= 3)) do
begin
try
Response.Text := FilterResponse(Response.Text);
if (Response.Text <> '') and (Response.Text <> '{}')
then Response.SaveToFile(CacheFile, TEncoding.UTF8)
else Response.Text := '';
Success := True;
except on E: Exception do
begin
Attempt := Attempt + 1;
if (Attempt <=3) then
begin
MainForm.LogEvent('GetMovieFromTMDb: Attempt '+IntToStr(Attempt)+'/3: '+CacheFile);
Sleep(5000*Attempt);
end
else
begin
MainForm.LogException('GetMovieFromTMDb', E.ClassName, E.Message, CacheFile);
end;
end;
end;
end;
end
else
begin
Reason := 'Cache';
end;
// If We didn't get a response (or didn't ask for one) try and load the data
// from the cache instead.
if (Response.Text = '') then
begin
if FileExists(CacheFile)
then SLLoadJSON(Response, CacheFile);
end;
// If we still don't have data, well, I guess we don't have data
if (Response.Text = '') then Response.Text := '{}';
// Return the Response, Fresh or Cached or Otherwise
Result := FilterResponse(Response.Text);
Response.Free;
// Update Cache Information
inc(MainForm.MovieCacheRequests);
if Reason = 'Cache' then inc(MainForm.MovieCacheHit)
else if Reason = 'Force' then inc(MainForm.MovieCacheForce)
else if Reason = 'Age' then inc(MainForm.MovieCacheAge)
else if Reason = 'Miss' then inc(MainForm.MovieCacheMiss);
end;
///////////////////////////////////////////////////////////////////////////////////////////////////
// GetTVShowFromTMDb //
// //
// This contacts TMDb and gets as much information about a TVShow as we can get in one single //
// query (their API counts requests in this way so we try to make as few as we possibly can). //
// This contains a great deal of information about the TVShow, enough to fill in the rest of the //
// pieces for the RoleTabulator as well as the list of actors when the row is selected. //
///////////////////////////////////////////////////////////////////////////////////////////////////
function GetTVShowfromTMDb(TMDb_ID: Integer; ForceUpdate: Boolean):String;
var
Client: TNetHTTPClient; // The client connection
Query: String; // The query we're building
Response: TStringList; // The response from TMDB
CacheFile: String; // The location where we're going to put it
CacheAge: TDateTime; // The age of an existing cache file
Update: Boolean; // To Update or Not
Reason: String; // Why are we doing what we're doing
Success: Boolean;
Attempt: Integer;
begin
// Figure out where to put this
TDirectory.CreateDirectory(MainForm.AppCacheDir+'cache/tvshows/tmdb/'+RightStr('00000000'+IntToStr(TMDB_ID),3));
CacheFile := MainForm.AppCacheDir+'cache/tvshows/tmdb/'+RightStr('00000000'+IntToStr(TMDB_Id),3)+'/tvshow-'+RightStr('00000000'+IntToStr(TMDb_ID),8)+'.json';
Response := TStringList.Create;
// Determine whether we're updating;
Update := ForceUpdate;
if not(Update) then
begin
if FileExists(CacheFile) then
begin
FileAge(CacheFile, CacheAge);
if HoursBetween(Now, CacheAge) > 168 then
begin
Update := True;
Reason := 'Age';
end
end
else
begin
Update := True;
Reason := 'Miss';
end;
end
else
begin
Reason := 'Force';
end;
// Update only if necessary
if Update then
begin
// Standard commection, more or less.
Client := TNetHTTPClient.Create(nil);
Client.ConnectionTimeout := 90000; // 90 seconds
Client.ResponseTimeout := 90000; // 90 seconds
Client.UserAgent := 'Actorious';
Client.Accept := 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8';
Client.SecureProtocols := [THTTPSecureProtocol.SSL3, THTTPSecureProtocol.TLS12];
// Get basically everything that we possibly can
Query := 'https://api.themoviedb.org/3/tv/'+IntToSTr(TMDb_ID);
Query := Query+'?api_key='+MainForm.edTMDbAPI.Text;
Query := Query+'&language=en-US';
Query := Query+'&include_image_language=en,null';
Query := Query+'&append_to_response=images,videos,external_ids,tagged_images,aggregate_credits';
// Try and get the data
try
Response.Text := Client.Get(Query).ContentAsString(TEncoding.UTF8);
Client.Free;
except on E: Exception do
begin
MainForm.LogException('GetTVShowFromTMDb', E.ClassName, E.Message, CacheFile);
end;
end;
Success := False;
Attempt := 1;
while ((Success = False) and (Attempt <= 3)) do
begin
try
Response.Text := FilterResponse(Response.Text);
if (Response.Text <> '') and (Response.Text <> '{}')
then Response.SaveToFile(CacheFile, TEncoding.UTF8)
else Response.Text := '';
Success := True;
except on E: Exception do
begin
Attempt := Attempt + 1;
if (Attempt <=3) then
begin
MainForm.LogEvent('GetTVShowFromTMDb: Attempt '+IntToStr(Attempt)+'/3: '+CacheFile);
Sleep(5000*Attempt);
end
else
begin
MainForm.LogException('GetTVShowFromTMDb', E.ClassName, E.Message, CacheFile);
end;
end;
end;
end;
end
else
begin
Reason := 'Cache';
end;
// If We didn't get a response (or didn't ask for one) try and load the data
// from the cache instead.
if (Response.Text = '') then
begin
if FIleExists(CacheFile)
then SLLoadJSON(Response, CacheFile);
end;
// If we still don't have data, well, I guess we don't have data
if (Response.Text = '') then Response.Text := '{}';
// Return the Response, Fresh or Cached or Otherwise
Response.Text := FilterResponse(Response.Text);
Result := Response.Text;
Response.Free;
// Update Cache Information
inc(MainForm.TVShowCacheRequests);
if Reason = 'Cache' then inc(MainForm.TVShowCacheHit)
else if Reason = 'Force' then inc(MainForm.TVShowCacheForce)
else if Reason = 'Age' then inc(MainForm.TVShowCacheAge)
else if Reason = 'Miss' then inc(MainForm.TVShowCacheMiss);
end;
///////////////////////////////////////////////////////////////////////////////////////////////////
// SaveActoriousPersonData //
// //
// Saves the Actorious version of the data to disk along with the Brotli-compressed version. //
// These are then used subsequently when building responses to search queries or other requests. //
///////////////////////////////////////////////////////////////////////////////////////////////////
procedure SaveActoriousPersonData(Person: String; PersonID: Integer; AdultActor:Boolean);
var
CacheFile: String;
PersonData: TStringList;
ResponseFile: TMemoryStream;
Brotli: TMemoryStream;
AdultList: TJSONObject;
AdultListFound: Boolean;
Success: Boolean;
Attempt: Integer;
I: Integer;
Attempts: Integer;
begin
// Figure out where to put this
TDirectory.CreateDirectory(MainForm.AppCacheDir+'cache/people/actorious/'+RightStr('00000000'+IntToStr(PersonID),3));
CacheFile := MainForm.AppCacheDir+'cache/people/actorious/'+RightStr('00000000'+IntToStr(PersonID),3)+'/person-'+RightStr('00000000'+IntToStr(PersonID),8);
Success := False;
Attempt := 1;
while ((Success = False) and (Attempt <= 3)) do
begin
// Try and Save the data
try
// Save the response to disk as-is
PersonData := TStringList.Create;
PersonData.Text := Person;
Attempts := 0;
while Attempts < 3 do
begin
try
PersonData.SaveToFile(CacheFile+'.json', TEncoding.UTF8);
Attempts := 3;
except on E: Exception do
begin
Attempts := Attempts + 1;
MainForm.LogEvent('SaveActoriousPersonData: Cache File In Use: Retrying '+IntToStr(Attempts)+'/3: '+CacheFile+'.json');
Sleep(30000);
end;
end;
end;
// Load binary file from disk into stream
ResponseFile := TMemoryStream.Create;
ResponseFile.LoadFromFile(CacheFile+'.json');
ResponseFile.Seek(0, soFromBeginning);
// Compress the stream with Brotli
Brotli := TMemoryStream.Create;
BrotliCompressStream(ResponseFile, Brotli, bcMax);
Brotli.Seek(0, soFromBeginning);
// Save the Brotli-compressed response to disk
Attempts := 0;
while Attempts < 3 do
begin
try
Brotli.SaveToFile(CacheFile+'.json.br');
Attempts := 3;
except on E: Exception do
begin
Attempts := Attempts + 1;
MainForm.LogEvent('SaveActoriousPersonData: Cache File In Use: Retrying '+IntToStr(Attempts)+'/3: '+CacheFile+'.json.br');
Sleep(30000);
end;
end;
end;
// We were never here
Brotli.Free;
ResponseFile.Free;
PersonData.Free;
Success := True;
except on E: Exception do
begin
MainForm.LogException('SaveActoriousPersonData', E.ClassName, E.Message, 'Attempt #'+IntToStr(Attempt)+'/3: '+CacheFile);
Attempt := Attempt + 1;
sleep(5000);
end;
end;
end;
// Here we're just creating a list of Adult Actors as we have no other way
// of generating such a list for use with things like the Top1000 queries.
// This list should be regenerated from time to time.
if AdultActor then
begin
try
// Get the existing list
PersonData := TStringList.Create;
AdultList := TJSONObject.Create;
try
if FileExists(MainForm.AppCacheDir+'cache/people/top1000/top1000-0.json')
then SLLoadJSON(PersonData, MainForm.AppCacheDir+'cache/people/top1000/top1000-0.json');
// Create an empty list if one doesn't exist already
if (PersonData.Text = '')
then PersonData.Text := '{"page":0,"results":[]}';
AdultList := TJSONObject.ParseJSONValue(PersonData.Text) as TJSONObject;
except on E: Exception do
begin
MainForm.LogException('SaveActoriousPersonData/LoadAdult', E.ClassName, E.Message, CacheFile);
end;
end;
// Don't add an entry if it is there already
i := 0;
AdultListFound := False;
while (i < ((AdultList as TJSONObject).getValue('results') as TJSONArray).Count) and (AdultListFound = False) do
begin
if ((((AdultList as TJSONObject).getValue('results') as TJSONArray).Items[i] as TJSONObject).getValue('id') as TJSONNumber).AsInt = PersonID
then AdultListFound := True;
i := i + 1;
end;
// Add the current person to the JSON Array
if AdultListFound = False then
begin
((AdultList as TJSONObject).getValue('results') as TJSONArray).AddElement(TJSONObject.Create(TJSONPair.Create('id',TJSONNumber.create(PersonID))));
// Save the updated list
PersonData.Text := AdultList.ToString;
PersonData.SaveToFile(MainForm.AppCacheDir+'cache/people/top1000/top1000-0.json', TEncoding.UTF8);
PersonData.SaveToFile(MainForm.AppCacheDir+'cache/people/top5000/top5000-0.json', TEncoding.UTF8);
end;
PersonData.Free;
AdultList.Free;
except on E: Exception do
begin
MainForm.LogException('SaveActoriousPersonData/SaveAdult', E.ClassName, E.Message, CacheFile);
end;
end;
end;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////
// SaveActoriousMovieData //
// //
// Saves the Actorious version of the data to disk along with the Brotli-compressed version. //
// These are then used subsequently when building responses to search queries or other requests. //
///////////////////////////////////////////////////////////////////////////////////////////////////
procedure SaveActoriousMovieData(Movie: String; MovieID: Integer; AdultMovie: Boolean);
var
CacheFile: String;
MovieData: TStringList;
ResponseFile: TMemoryStream;
Brotli: TMemoryStream;
AdultList: TJSONObject;
Success: Boolean;
Attempt: Integer;
begin
// Figure out where to put this
TDirectory.CreateDirectory(MainForm.AppCacheDir+'cache/movies/actorious/'+RightStr('00000000'+IntToStr(MovieID),3));
CacheFile := MainForm.AppCacheDir+'cache/movies/actorious/'+RightStr('00000000'+IntToStr(MovieID),3)+'/movie-'+RightStr('00000000'+IntToStr(MovieID),8);
Success := False;
Attempt := 1;
while ((Success = False) and (Attempt <= 3)) do
begin
// Try and Save the data
try
MovieData := TStringList.Create;
MovieData.Text := Movie;
MovieData.SaveToFile(CacheFile+'.json', TEncoding.UTF8);
// Save the response to disk as-is
ResponseFile := TMemoryStream.Create;
ResponseFile.LoadFromFile(CacheFile+'.json');
ResponseFile.Seek(0, soFromBeginning);
// Compress the stream with Brotli
Brotli := TMemoryStream.Create;
BrotliCompressStream(ResponseFile, Brotli, bcMax);
Brotli.Seek(0, soFromBeginning);
// Save the Brotli-compressed response to disk
Brotli.SaveToFile(CacheFile+'.json.br');
// We were never here
Brotli.Free;
ResponseFile.Free;
MovieData.Free;
Success := True;
except on E: Exception do
begin
MainForm.LogException('SaveActoriousPersonData', E.ClassName, E.Message, 'Attempt #'+IntToStr(Attempt)+'/3: '+CacheFile);
Attempt := Attempt + 1;
sleep(5000);
end;
end;
end;
// Here we're just creating a list of Adult Movies as we have no other way
// of generating such a list for use with things like the Top1000 queries.
// This list should be regenerated from time to time.
if AdultMovie then
begin
try
// Get the existing list
MovieData := TStringList.Create;
AdultList := TJSONObject.Create;
try
MovieData := TStringList.Create;
MovieData.Text := '';
if FileExists(MainForm.AppCacheDir+'cache/movies/top1000/top1000-0.json')
then SLLoadJSON(MovieData, MainForm.AppCacheDir+'cache/movies/top1000/top1000-0.json');
// Create an empty list if one doesn't exist already
if (MovieData.Text = '')
then MovieData.Text := '{"page":0,"results":[]}';