-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathFB4D.Helpers.pas
1917 lines (1770 loc) · 57.5 KB
/
FB4D.Helpers.pas
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
{******************************************************************************}
{ }
{ Delphi FB4D Library }
{ Copyright (c) 2018-2023 Christoph Schneider }
{ Schneider Infosystems AG, Switzerland }
{ https://github.com/SchneiderInfosystems/FB4D }
{ }
{******************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{******************************************************************************}
unit FB4D.Helpers;
interface
uses
System.Classes, System.Types, System.SysUtils, System.StrUtils,
{$IFNDEF LINUX64}
System.Sensors,
{$ENDIF}
System.JSON, System.Generics.Collections,
REST.Types,
FB4D.Interfaces;
type
TOnSimpleDownloadError = procedure(const DownloadURL, ErrMsg: string) of
object;
TOnSimpleDownloadSuccess = procedure(const DownloadURL: string) of object;
TOnLog = procedure(const Text: string) of object;
TFirebaseHelpers = class
class var OnLog: TOnLog;
// Time conversion functions
class function CodeRFC3339DateTime(DateTimeStamp: TDateTime): string;
class function DecodeRFC3339DateTime(DateTimeStamp: string): TDateTime;
class function ConvertTimeStampToUTCDateTime(TimeStamp: Int64): TDateTime;
class function ConvertRFC5322ToUTCDateTime(DateTime: string): TDateTime;
class function ConvertRFC5322ToLocalDateTime(DateTime: string): TDateTime;
class function ConvertTimeStampToLocalDateTime(Timestamp: Int64): TDateTime;
class function ConvertToLocalDateTime(DateTimeStampUTC: TDateTime): TDateTime;
class function ConvertToUTCDateTime(DateTimeStampLocal: TDateTime): TDateTime;
// Query parameter helpers
class function EncodeQueryParams(QueryParams: TQueryParams): string;
class function EncodeQueryParamsWithToken(QueryParams: TQueryParams;
const EncodedToken: string): string;
// Request parameter helpers
class function EncodeResourceParams(Params: TRequestResourceParam): string;
class function AddParamToResParams(Params: TRequestResourceParam;
const Param: string): TRequestResourceParam;
// Encode token for URL based token transmission
class function EncodeToken(const Token: string): string;
// Array of string helpers
class function ArrStrToCommaStr(Arr: array of string): string;
class function ArrStrToQuotedCommaStr(Arr: array of string): string;
class function FirestorePath(const Path: string): TRequestResourceParam;
deprecated 'Use TFirestorePath.ConvertToDocPath instead';
// FBID is based on charset of cBase64: Helpers and converter to GUID
// PUSHID is based on charset of cPushID64: Supports chronological sorting
type TIDKind = (FBID {random 22 Chars},
PUSHID {timestamp and random: total 20 Chars},
FSID {random 20 Chars});
class function CreateAutoID(IDKind: TIDKind = FBID): string;
class function ConvertGUIDtoFBID(Guid: TGuid): string;
class function ConvertFBIDtoGUID(const FBID: string): TGuid;
class function ConvertTimeStampAndRandomPatternToPUSHID(timestamp: TDateTime;
Random: TBytes): string;
class function DecodeTimeStampFromPUSHID(const PUSHID: string;
ConvertToLocalTime: boolean = true): TDateTime;
// File helpers
class procedure SimpleDownload(const DownloadUrl: string; Stream: TStream;
OnSuccess: TOnSimpleDownloadSuccess;
OnError: TOnSimpleDownloadError = nil);
class procedure SimpleDownloadSynchronous(const DownloadUrl: string;
Stream: TStream);
{$IF Defined(FMX) OR Defined(FGX)}
class function ContentTypeToFileExt(const ContentType: string): string;
class function ImageStreamToContentType(Stream: TStream): TRESTContentType;
{$ENDIF}
// Miscellaneous functions
class function IsEMailAdress(const EMail: string): boolean;
// Application helpers
class procedure Log(msg: string);
class procedure LogFmt(msg: string; const Args: array of const);
class function AppIsTerminated: boolean;
class procedure SleepAndMessageLoop(SleepInMs: cardinal);
class function IsMainThread: boolean;
class function GetConfigAndPlatform: string;
class function GetPlatform: string;
// ML helpers
class function GetLanguageInEnglishFromCode(const Code: string): string;
private const
cBase64 =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-';
// The last two chars '_' and '-' are not real Base64 because '+' and '/'
// causes troubles in IDs
cPushID64 =
'-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';
// This notification is used in the Realtime DB for Post and Push operation
end;
TFirestorePath = class
class function TrimStartAndEndPathDelimiters(const Path: string): string;
class function ConvertToDocPath(const Path: string): TRequestResourceParam;
class function GetDocPath(Params: TRequestResourceParam): string;
class function ContainsPathDelim(const Path: string): boolean;
class function ExtractLastCollection(const Path: string): string;
class function DocPathWithoutLastCollection(
const Path: string): TRequestResourceParam;
end;
TFirestoreMap = array of TJSONPair;
TFirestoreArr = array of TJSONValue;
TJSONHelpers = class helper for TJSONObject
// String
function GetStringValue: string; overload;
function GetStringValue(const Name: string): string; overload;
function GetStringValueDef(const Name: string;
const Default: string = ''): string;
class function SetStringValue(const Val: string): TJSONObject;
class function SetString(const VarName, Val: string): TJSONPair;
// Integer
function GetIntegerValue: integer; overload;
function GetIntegerValue(const Name: string): integer; overload;
function GetIntegerValueDef(const Name: string;
Default: integer = 0): integer;
function GetInt64Value: Int64; overload;
function GetInt64Value(const Name: string): Int64; overload;
function GetInt64ValueDef(const Name: string;
Default: Int64 = 0): Int64;
class function SetIntegerValue(Val: integer): TJSONObject;
class function SetInteger(const VarName: string; Val: integer): TJSONPair;
class function SetInt64Value(Val: Int64): TJSONObject;
class function SetInt64(const VarName: string; Val: Int64): TJSONPair;
// Boolean
function GetBooleanValue: boolean; overload;
function GetBooleanValue(const Name: string): boolean; overload;
function GetBooleanValueDef(const Name: string;
Default: boolean = false): boolean;
class function SetBooleanValue(Val: boolean): TJSONObject;
class function SetBoolean(const VarName: string; Val: boolean): TJSONPair;
// Double
function GetDoubleValue: double; overload;
function GetDoubleValue(const Name: string): double; overload;
function GetDoubleValueDef(const Name: string; Default: double = 0): double;
class function SetDoubleValue(Val: double): TJSONObject;
class function SetDouble(const VarName: string; Val: double): TJSONPair;
// TimeStamp
function GetTimeStampValue(TimeZone: TTimeZone = tzUTC): TDateTime; overload;
function GetTimeStampValue(const Name: string;
TimeZone: TTimeZone = tzUTC): TDateTime; overload;
function GetTimeStampValueDef(const Name: string; Default: TDateTime = 0;
TimeZone: TTimeZone = tzUTC): TDateTime;
class function SetTimeStampValue(Val: TDateTime;
TimeZone: FB4D.Interfaces.TTimeZone = tzUTC): TJSONObject;
class function SetTimeStamp(const VarName: string;
Val: TDateTime; TimeZone: FB4D.Interfaces.TTimeZone = tzUTC): TJSONPair;
// Null
class function SetNullValue: TJSONObject;
class function SetNull(const VarName: string): TJSONPair;
function IsNull: boolean;
// Reference
function GetReference: string; overload;
function GetReference(const Name: string): string; overload;
function GetReferenceDef(const Name: string;
const Default: string = ''): string;
class function SetReferenceValue(const ProjectID, Ref: string;
const Database: string = cDefaultDatabaseID): TJSONObject;
class function SetReference(const Name, ProjectID, Ref: string): TJSONPair;
// GeoPoint
function GetGeoPoint: TLocationCoord2D; overload;
function GetGeoPoint(const Name: string): TLocationCoord2D; overload;
function GetGeoPointDef(const Name: string;
Default: TLocationCoord2D): TLocationCoord2D;
class function SetGeoPointValue(Val: TLocationCoord2D): TJSONObject;
class function SetGeoPoint(const VarName: string;
Val: TLocationCoord2D): TJSONPair;
// Bytes
function GetBytes: TBytes; overload;
function GetBytes(const Name: string): TBytes; overload;
class function SetBytesValue(Val: TBytes): TJSONObject;
class function SetBytes(const VarName: string; Val: TBytes): TJSONPair;
// Map
function GetMapSize: integer; overload;
function GetMapSize(const Name: string): integer; overload;
function GetMapItem(Ind: integer): TJSONPair; overload;
function GetMapItem(const Name: string): TJSONObject; overload;
function GetMapItem(const Name: string; Ind: integer): TJSONPair; overload;
function GetMapValue(const Name: string; Ind: integer): TJSONObject;
function GetMapValues: TJSONObject;
class function SetMapValue(MapVars: TFirestoreMap): TJSONObject;
class function SetMap(const VarName: string;
MapVars: TFirestoreMap): TJSONPair;
// Array
function GetArraySize: integer; overload;
function GetArraySize(const Name: string): integer; overload;
function GetArrayItem(Ind: integer): TJSONObject; overload;
function GetArrayItem(const Name: string; Ind: integer): TJSONObject;
overload;
function GetArrayValues: TJSONObjects;
function GetStringArray: TStringDynArray;
class function SetArray(const VarName: string;
FSArr: TFirestoreArr): TJSONPair;
class function SetArrayValue(FSArr: TFirestoreArr): TJSONObject;
class function SetStringArray(const VarName: string;
Strings: TStringDynArray): TJSONPair; overload;
class function SetStringArray(const VarName: string;
Strings: TStringList): TJSONPair; overload;
class function SetStringArray(const VarName: string;
Strings: TList<string>): TJSONPair; overload;
end;
TQueryParamsHelper = class helper for TQueryParams
class function CreateQueryParams(CheckThisInstanceFirst: TQueryParams =
nil): TQueryParams;
function AddOrderBy(const FieldName: string): TQueryParams;
function AddOrderByType(const TypeName: string): TQueryParams;
function AddLimitToFirst(LimitToFirst: integer): TQueryParams;
function AddLimitToLast(LimitToLast: integer): TQueryParams;
function AddTransaction(
Transaction: TFirestoreReadTransaction): TQueryParams;
function AddPageSize(PageSize: integer): TQueryParams;
function AddPageToken(const PageToken: string): TQueryParams;
end;
resourcestring
rsFBFailureIn = '%s Firebase failure in %s: %s';
implementation
uses
System.Character,
{$IFDEF MSWINDOWS}
WinAPI.Windows,
{$ENDIF}
{$IF Defined(CONSOLE)}
{$ELSEIF Defined(VCL)}
VCL.Forms,
{$ELSEIF Defined(FMX)}
FMX.Types, FMX.Forms, FMX.Graphics, FMX.Consts,
{$ELSEIF Defined(FGX)}
FGX.Forms, FGX.Logs,
{$ELSE}
FMX.Types, FMX.Forms,
{$ENDIF}
System.DateUtils, System.NetEncoding, System.JSONConsts, System.Math,
System.Net.HttpClient, System.Hash,
IdGlobalProtocols;
resourcestring
rsArrFieldNotJSONObj = 'Arrayfield[%d] does not contain a JSONObject';
rsArrFieldNotTypeValue = 'Arrayfield[%d] does not contain type-value pair';
rsArrayItemOutOfBounds = 'Array item %d out of bounds';
rsInvalidArrayItem = 'Invalid array item %d';
rsMapItemOutOfBounds = 'Map item %d out of bounds';
{ TFirestoreHelpers }
class function TFirebaseHelpers.CodeRFC3339DateTime(
DateTimeStamp: TDateTime): string;
var
UTC: TDateTime;
begin
// Convert to UTC
UTC := TTimeZone.Local.ToUniversalTime(DateTimeStamp);
// Format RFC3339
result := FormatDateTime('yyyy-mm-dd', UTC) + 'T' +
FormatDateTime('hh:mm:ss', UTC) + 'Z';
end;
class function TFirebaseHelpers.DecodeRFC3339DateTime(
DateTimeStamp: string): TDateTime;
begin
result := ISO8601ToDate(DateTimeStamp, false); // To local time
end;
class function TFirebaseHelpers.ConvertRFC5322ToLocalDateTime(
DateTime: string): TDateTime;
begin
result := ConvertToLocalDateTime(ConvertRFC5322ToUTCDateTime(DateTime));
end;
class function TFirebaseHelpers.ConvertRFC5322ToUTCDateTime(
DateTime: string): TDateTime;
begin
result := StrInternetToDateTime(DateTime);
end;
class function TFirebaseHelpers.ConvertTimeStampToLocalDateTime(
Timestamp: Int64): TDateTime;
begin
result := ConvertToLocalDateTime(ConvertTimeStampToUTCDateTime(Timestamp));
end;
class function TFirebaseHelpers.ConvertTimeStampToUTCDateTime(
TimeStamp: Int64): TDateTime;
begin
result := UnixToDateTime(TimeStamp div 1000);
end;
class function TFirebaseHelpers.ConvertToLocalDateTime(
DateTimeStampUTC: TDateTime): TDateTime;
begin
result := TTimeZone.Local.ToLocalTime(DateTimeStampUTC);
end;
class function TFirebaseHelpers.ConvertToUTCDateTime(
DateTimeStampLocal: TDateTime): TDateTime;
begin
result := TTimeZone.Local.ToUniversalTime(DateTimeStampLocal);
end;
class function TFirebaseHelpers.EncodeQueryParams(
QueryParams: TQueryParams): string;
var
Param: TPair<string, TStringDynArray>;
ParVal: string;
begin
if (not assigned(QueryParams)) or not(QueryParams.Count > 0) then
exit('');
result := '?';
for Param in QueryParams do
for ParVal in Param.Value do
begin
if result <> '?' then
result := result + '&';
result := result + TNetEncoding.URL.Encode(Param.Key) + '=' +
TNetEncoding.URL.Encode(ParVal);
end;
end;
class function TFirebaseHelpers.EncodeQueryParamsWithToken(
QueryParams: TQueryParams; const EncodedToken: string): string;
var
Param: TPair<string, TStringDynArray>;
ParVal: string;
begin
result := '?auth=' + EncodedToken;
if assigned(QueryParams) then
for Param in QueryParams do
for ParVal in Param.Value do
result := result + '&' + TNetEncoding.URL.Encode(Param.Key) + '=' +
TNetEncoding.URL.Encode(ParVal);
end;
class function TFirebaseHelpers.EncodeResourceParams(
Params: TRequestResourceParam): string;
const
PathUnsafeChars: TURLEncoding.TUnsafeChars =
[Ord('"'), Ord('<'), Ord('>'), Ord('^'), Ord('`'), Ord('{'), Ord('}'),
Ord('|'), Ord('/'), Ord('\'), Ord('?'), Ord('#'), Ord('+')];
Option: TURLEncoding.TEncodeOptions =
[TURLEncoding.TEncodeOption.SpacesAsPlus,
TURLEncoding.TEncodeOption.EncodePercent];
var
i: integer;
begin
result := '';
for i := low(Params) to high(Params) do
result := result + '/' + TNetEncoding.URL.Encode(Params[i], PathUnsafeChars,
Option);
end;
class function TFirebaseHelpers.EncodeToken(const Token: string): string;
begin
if Token.IsEmpty then
result := ''
else
result := '?auth=' + TNetEncoding.URL.Encode(Token);
end;
class function TFirebaseHelpers.FirestorePath(
const Path: string): TRequestResourceParam;
begin
if Path.StartsWith('/') or Path.StartsWith('\') then
result := Path.Substring(1).Split(['/', '\'])
else
result := Path.Split(['/', '\']);
end;
class function TFirebaseHelpers.ArrStrToCommaStr(Arr: array of string): string;
var
i: integer;
begin
result := '';
for i := low(Arr) to high(Arr) do
if i = low(Arr) then
result := Arr[i]
else
result := result + ',' + Arr[i];
end;
class function TFirebaseHelpers.ArrStrToQuotedCommaStr(
Arr: array of string): string;
function DoubleQuotedStr(const S: string): string;
var
i: integer;
begin
result := S;
for i := result.Length - 1 downto 0 do
if result.Chars[i] = '"' then
result := result.Insert(i, '"');
result := '"' + result + '"';
end;
var
i: integer;
begin
result := '';
for i := low(Arr) to high(Arr) do
if i = low(Arr) then
result := DoubleQuotedStr(Arr[i])
else
result := result + ',' + DoubleQuotedStr(Arr[i]);
end;
class procedure TFirebaseHelpers.Log(msg: string);
begin
if AppIsTerminated then
exit;
{$IF Defined(FMX)}
{$IFDEF LINUX}
writeln(msg); // Workaround for RSP-32303
{$ELSE}
FMX.Types.Log.d(msg, []);
// there is a bug in DE 10.2 when the wrong method is calling?
{$ENDIF}
{$ELSEIF Defined(FGX)}
TfgLog.Debug(msg);
{$ELSEIF Defined(VCL)}
OutputDebugString(PChar(msg));
{$ELSEIF Defined(MSWINDOWS)}
OutputDebugString(PChar(msg));
{$ELSEIF Defined(CONSOLE)}
writeln(msg);
{$ENDIF}
if Assigned(OnLog) then
OnLog(msg);
end;
class procedure TFirebaseHelpers.LogFmt(msg: string; const Args: array of const);
begin
Log(Format(msg, args));
end;
class function TFirebaseHelpers.AddParamToResParams(
Params: TRequestResourceParam; const Param: string): TRequestResourceParam;
var
c: integer;
begin
SetLength(result, length(Params) + 1);
for c := low(Params) to high(Params) do
result[c] := Params[c];
result[length(Params)] := Param;
end;
class function TFirebaseHelpers.AppIsTerminated: boolean;
begin
{$IF Defined(VCL) OR Defined(FMX)}
result := Application.Terminated;
{$ELSE}
result := false;
{$ENDIF}
end;
class procedure TFirebaseHelpers.SleepAndMessageLoop(SleepInMs: cardinal);
begin
{$IF Defined(VCL) OR Defined(FMX)}
Application.ProcessMessages;
{$ENDIF}
Sleep(SleepInMs);
end;
class procedure TFirebaseHelpers.SimpleDownload(const DownloadUrl: string;
Stream: TStream; OnSuccess: TOnSimpleDownloadSuccess;
OnError: TOnSimpleDownloadError);
var
ErrMsg: string;
begin
TThread.CreateAnonymousThread(
procedure
var
Client: THTTPClient;
Response: IHTTPResponse;
begin
Client := THTTPClient.Create;
try
try
Response := Client.Get(DownloadUrl, Stream);
if Response.StatusCode = 200 then
begin
if assigned(OnSuccess) then
TThread.Queue(nil,
procedure
begin
OnSuccess(DownloadUrl);
end);
end else begin
{$IFDEF DEBUG}
TFirebaseHelpers.Log(Response.ContentAsString);
{$ENDIF}
if assigned(OnError) then
TThread.Queue(nil,
procedure
begin
OnError(DownloadUrl, Response.StatusText);
end);
end;
except
on e: exception do
if assigned(OnError) then
begin
ErrMsg := e.Message;
TThread.Queue(nil,
procedure
begin
OnError(DownloadUrl, ErrMsg);
end)
end else
TFirebaseHelpers.LogFmt(rsFBFailureIn,
['FirebaseHelpers.SimpleDownload', DownloadUrl, e.Message]);
end;
finally
Client.Free;
end;
end).Start;
end;
class procedure TFirebaseHelpers.SimpleDownloadSynchronous(
const DownloadUrl: string; Stream: TStream);
var
Client: THTTPClient;
Response: IHTTPResponse;
begin
Client := THTTPClient.Create;
try
Response := Client.Get(DownloadUrl, Stream);
if Response.StatusCode <> 200 then
begin
{$IFDEF DEBUG}
TFirebaseHelpers.Log(Response.ContentAsString);
{$ENDIF}
raise EFirebaseResponse.Create(Response.StatusText);
end;
finally
Client.Free;
end;
end;
class function TFirebaseHelpers.CreateAutoID(IDKind: TIDKind = FBID): string;
function ShortenIDTo20Chars(const ID: string): string;
begin
result := ReplaceStr(ID, '_', '');
result := ReplaceStr(ID, '-', '');
if result.Length > 20 then
result := result.Substring(0, 20);
while result.Length < 20 do
result := result + cBase64[Random(62)];
end;
begin
// use OS to generate a random number
case IDKind of
FBID:
result := ConvertGUIDtoFBID(TGuid.NewGuid);
FSID:
result := ShortenIDTo20Chars(ConvertGUIDtoFBID(TGuid.NewGuid));
PUSHID:
result := ConvertTimeStampAndRandomPatternToPUSHID(now,
THashMD5.GetHashBytes(GuidToString(TGUID.NewGuid)));
end;
end;
class function TFirebaseHelpers.ConvertGUIDtoFBID(Guid: TGuid): string;
function GetBase64(b: Byte): char;
begin
result := cBase64[low(cBase64) + b and $3F];
end;
var
D1: cardinal;
D2, D3: Word;
begin
SetLength(result, 22);
D1 := Guid.D1;
result[1] := GetBase64(D1 and $FF);
D1 := D1 shr 6;
result[2] := GetBase64(D1 and $FF);
D1 := D1 shr 6;
result[3] := GetBase64(D1 and $FF);
D1 := D1 shr 6;
result[4] := GetBase64(D1 and $FF);
D1 := D1 shr 6;
result[5] := GetBase64(D1 and $FF);
D2 := Guid.D2;
result[6] := GetBase64(D2 and $FF);
D2 := D2 shr 6;
result[7] := GetBase64(D2 and $FF);
D2 := D2 shr 6;
result[8] := GetBase64(D2 and $F + (D1 and $C0) shr 2);
D3 := Guid.D3;
result[9] := GetBase64(D3 and $FF);
D3 := D3 shr 6;
result[10] := GetBase64(D3 and $FF);
D3 := D3 shr 6;
result[11] := GetBase64(D3 and $F + (Guid.D4[0] and $C0) shr 2);
result[12] := GetBase64(Guid.D4[0]);
result[13] := GetBase64(Guid.D4[1]);
result[14] := GetBase64(Guid.D4[2]);
result[15] := GetBase64(Guid.D4[3]);
result[16] := GetBase64(Guid.D4[4]);
result[17] := GetBase64(Guid.D4[5]);
result[18] := GetBase64(Guid.D4[6]);
result[19] := GetBase64(Guid.D4[7]);
result[20] := GetBase64((Guid.D4[1] and $C0) shr 6 +
(Guid.D4[2] and $C0) shr 4 + (Guid.D4[3] and $C0) shr 2);
result[21] := GetBase64((Guid.D4[4] and $C0) shr 6 +
(Guid.D4[5] and $C0) shr 4 + (Guid.D4[6] and $C0) shr 2);
result[22] := GetBase64((Guid.D4[7] and $C0) shr 6);
end;
class function TFirebaseHelpers.ConvertFBIDtoGUID(const FBID: string): TGuid;
var
c: integer;
Base64: array[1..22] of byte;
begin
for c := low(Base64) to high(Base64) do
Base64[c] := 0; // Zero for ID that are shorter than 22
for c := 1 to max(length(FBID), high(Base64)) do
Base64[c] := pos(FBID[c], cBase64) - 1;
result.D1 := Base64[1] + Base64[2] shl 6 + Base64[3] shl 12 +
Base64[4] shl 18 + Base64[5] shl 24 + (Base64[8] and $30) shl 26;
result.D2 := Base64[6] + Base64[7] shl 6 + (Base64[8] and $F) shl 12;
result.D3 := Base64[9] + Base64[10] shl 6 + (Base64[11] and $F) shl 12;
result.D4[0] := Base64[12] + (Base64[11] and $30) shl 2;
result.D4[1] := Base64[13] + (Base64[20] and $03) shl 6;
result.D4[2] := Base64[14] + (Base64[20] and $0C) shl 4;
result.D4[3] := Base64[15] + (Base64[20] and $30) shl 2;
result.D4[4] := Base64[16] + (Base64[21] and $03) shl 6;
result.D4[5] := Base64[17] + (Base64[21] and $0C) shl 4;
result.D4[6] := Base64[18] + (Base64[21] and $30) shl 2;
result.D4[7] := Base64[19] + (Base64[22] and $03) shl 6;
end;
class function TFirebaseHelpers.ConvertTimeStampAndRandomPatternToPUSHID(
timestamp: TDateTime; Random: TBytes): string;
var
tsi: int64;
c: integer;
begin
Assert(length(Random) >= 12, 'Too short random pattern');
tsi := System.DateUtils.DateTimeToUnix(timestamp, false) * 1000;
result := '';
for c := 1 to 8 do
begin
result := cPushID64[(tsi mod 64) + low(cPushID64)] + result;
tsi := tsi shr 6;
end;
for c := 0 to 11 do
result := result + cPushID64[Random[c] and $3F + low(cPushID64)];
end;
class function TFirebaseHelpers.DecodeTimeStampFromPUSHID(
const PUSHID: string; ConvertToLocalTime: boolean): TDateTime;
var
tsi: int64;
c: integer;
begin
Assert(length(PUSHID) = 20, 'Invalid PUSHID length');
tsi := 0;
for c := low(PUSHID) to low(PUSHID) + 7 do
tsi := tsi shl 6 + pos(PUSHID[c], cPushID64) - low(cPushID64);
result := UnixToDateTime(tsi div 1000);
if ConvertToLocalTime then
result := TTimeZone.Local.ToLocalTime(result);
end;
{$IF Defined(FMX) OR Defined(FGX)}
class function TFirebaseHelpers.ContentTypeToFileExt(
const ContentType: string): string;
{$IF CompilerVersion < 35} // Delphi 10.4 and before
function SameText(const ContentType: string;
AContentType: TRESTContentType): boolean;
begin
result := System.SysUtils.SameText(ContentType,
ContentTypeToString(AContentType));
end;
{$ENDIF}
begin
if SameText(ContentType, TRESTContentType.ctIMAGE_JPEG) then
result := SJPGImageExtension
else if SameText(ContentType, TRESTContentType.ctIMAGE_GIF) then
result := SGIFImageExtension
else if SameText(ContentType, TRESTContentType.ctIMAGE_PNG) then
result := SPNGImageExtension
else if SameText(ContentType, TRESTContentType.ctIMAGE_TIFF) then
result := STIFFImageExtension
else if SameText(ContentType, TRESTContentType.ctIMAGE_SVG_XML) or
SameText(ContentType, TRESTContentType.ctAPPLICATION_XML) or
SameText(ContentType, TRESTContentType.ctTEXT_XML) then
result := '.xml'
else if SameText(ContentType, TRESTContentType.ctAPPLICATION_JSON) then
result := '.json'
else if SameText(ContentType, TRESTContentType.ctAPPLICATION_PDF) then
result := '.pdf'
else if SameText(ContentType, TRESTContentType.ctAPPLICATION_ZIP) then
result := '.zip'
else if SameText(ContentType, TRESTContentType.ctTEXT_HTML) then
result := '.htm'
else if SameText(ContentType, TRESTContentType.ctTEXT_CSS) then
result := '.css'
else if SameText(ContentType, TRESTContentType.ctTEXT_JAVASCRIPT) or
SameText(ContentType, TRESTContentType.ctAPPLICATION_JAVASCRIPT)then
result := '.js'
else if SameText(ContentType, TRESTContentType.ctTEXT_PLAIN) then
result := '.txt'
else if SameText(ContentType, TRESTContentType.ctTEXT_CSV) then
result := '.csv'
else if SameText(ContentType, TRESTContentType.ctTEXT_X_MARKDOWN) then
result := '.md'
else
result := '';
end;
class function TFirebaseHelpers.ImageStreamToContentType(
Stream: TStream): TRESTContentType;
var
ImgType: string;
begin
ImgType := TImageTypeChecker.GetType(Stream);
if ImgType = SJPGImageExtension then
result := TRESTContentType.ctIMAGE_JPEG
else if ImgType = SGIFImageExtension then
result := TRESTContentType.ctIMAGE_GIF
else if ImgType = SPNGImageExtension then
result := TRESTContentType.ctIMAGE_PNG
else if ImgType = STIFFImageExtension then
result := TRESTContentType.ctIMAGE_TIFF
else // if ImgType = SBMPImageExtension then
// Unsupported image type!
{$IF CompilerVersion < 35} // Delphi 10.4 and before
result := ctNone;
{$ELSE}
result := '';
{$ENDIF}
end;
{$ENDIF}
class function TFirebaseHelpers.IsEMailAdress(const EMail: string): boolean;
// Returns True if the email address is valid
// Inspired by Ernesto D'Spirito
function IsAtomChars(c: Char): boolean;
begin
result := (c >= #33) and (c <= #255) and not c.IsInArray(
['(', ')', '<', '>', '@', ',', ';', ':', '\', '/', '"', '.',
'[', ']', #127]);
end;
function IsQuotedStringChars(c: Char): boolean;
begin
result := (c < #255) and not c.IsInArray(['"', #13, '\']);
end;
type
States = (stBegin, stAtom, stQText, st_QChar, stQuote, stLocalPeriod,
stExpectingSubDomain, stSubDomain, stHyphen);
var
State: States;
i, subdomains: integer;
c: char;
begin
State := stBegin;
subdomains := 1;
for i := low(email) to high(email) do
begin
c := email[i];
case State of
stBegin:
if IsAtomChars(c) then
State := stAtom
else if c = '"' then
State := stQText
else
exit(false);
stAtom:
if c = '@' then
State := stExpectingSubDomain
else if c = '.' then
State := stLocalPeriod
else if not IsAtomChars(c) then
exit(false);
stQText:
if c = '\' then
State := st_QChar
else if c = '"' then
State := stQuote
else if not IsQuotedStringChars(c) then
exit(false);
st_QChar:
State := stQText;
stQuote:
if c = '@' then
State := stExpectingSubDomain
else if c = '.' then
State := stLocalPeriod
else
exit(false);
stLocalPeriod:
if IsAtomChars(c) then
State := stAtom
else if c = '"' then
State := stQText
else
exit(false);
stExpectingSubDomain:
if c.IsLetter then
State := stSubDomain
else
exit(false);
stSubDomain:
if c = '.' then begin
inc(subdomains);
State := stExpectingSubDomain
end else if c = '-' then
State := stHyphen
else if not c.IsLetterOrDigit then
exit((i = high(email)) and (subdomains >= 2));
stHyphen:
if c.IsLetterOrDigit then
State := stSubDomain
else if c <> '-' then
exit(false);
end;
end;
result := (State = stSubDomain) and (subdomains >= 2);
end;
class function TFirebaseHelpers.IsMainThread: boolean;
begin
result := TThread.Current.ThreadID = System.MainThreadID;
end;
class function TFirebaseHelpers.GetPlatform: string;
begin
{$IF defined(WIN32)}
result := 'Win32';
{$ELSEIF defined(WIN64)}
result := 'Win64';
{$ELSEIF defined(MACOS32)}
result := 'Mac32';
{$ELSEIF defined(MACOS64)}
result := 'Mac64';
{$ELSEIF defined(IOS32)}
result := 'iOS32';
{$ELSEIF defined(IOS64)}
result := 'iOS64';
{$ELSEIF defined(ANDROID32)}
result := 'Android32';
{$ELSEIF defined(ANDROID64)}
result := 'Android64';
{$ELSEIF defined(LINUX32)}
result := 'Linux32';
{$ELSEIF defined(Linux64)}
result := 'Linux64';
{$ELSE}
result := 'Platform?';
{$ENDIF}
end;
class function TFirebaseHelpers.GetConfigAndPlatform: string;
begin
{$IF defined(RELEASE)}
result := 'Release Build/';
{$ELSEIF defined(DEBUG)}
result := 'Debug Build/';
{$ELSE}
result := 'Unknown Build/';
{$ENDIF}
result := result + GetPlatform;
end;
class function TFirebaseHelpers.GetLanguageInEnglishFromCode(
const Code: string): string;
begin
if SameText(Code, 'af') then
result := 'Afrikaans'
else if SameText(Code, 'am') then
result := 'Amharic'
else if SameText(Code, 'ar') then
result := 'Arabic'
else if SameText(Code, 'arn') then
result := 'Mapudungun'
else if SameText(Code, 'as') then
result := 'Assamese'
else if SameText(Code, 'az') then
result := 'Azeri'
else if SameText(Code, 'ba') then
result := 'Bashkir'
else if SameText(Code, 'be') then
result := 'Belarusian'
else if SameText(Code, 'bg') then
result := 'Bulgarian'
else if SameText(Code, 'bn') then
result := 'Bengali'
else if SameText(Code, 'bo') then
result := 'Tibetan'
else if SameText(Code, 'br') then
result := 'Breton'
else if SameText(Code, 'bs') then
result := 'Bosnian'
else if SameText(Code, 'ca') then
result := 'Catalan'
else if SameText(Code, 'co') then
result := 'Corsican'
else if SameText(Code, 'cs') then
result := 'Czech'
else if SameText(Code, 'cy') then
result := 'Welsh'
else if SameText(Code, 'da') then
result := 'Danish'
else if SameText(Code, 'de') then
result := 'German'
else if SameText(Code, 'dsb') then
result := 'Lower Sorbian'
else if SameText(Code, 'dv') then
result := 'Divehi'
else if SameText(Code, 'el') then
result := 'Greek'
else if SameText(Code, 'en') then
result := 'English'
else if SameText(Code, 'es') then
result := 'Spanish'
else if SameText(Code, 'et') then
result := 'Estonian'
else if SameText(Code, 'eu') then
result := 'Basque'
else if SameText(Code, 'fa') then
result := 'Persian'
else if SameText(Code, 'fi') then
result := 'Finnish'
else if SameText(Code, 'fil') then
result := 'Filipino'
else if SameText(Code, 'fo') then
result := 'Faroese'
else if SameText(Code, 'fr') then
result := 'French'
else if SameText(Code, 'fy') then
result := 'Frisian'
else if SameText(Code, 'ga') then
result := 'Irish'
else if SameText(Code, 'gd') then
result := 'Scottish Gaelic'
else if SameText(Code, 'gl') then
result := 'Galician'
else if SameText(Code, 'gsw') then
result := 'Alsatian'
else if SameText(Code, 'gu') then
result := 'Gujarati'
else if SameText(Code, 'ha') then
result := 'Hausa'
else if SameText(Code, 'he') then
result := 'Hebrew'
else if SameText(Code, 'hi') then
result := 'Hindi'
else if SameText(Code, 'hr') then
result := 'Croatian'
else if SameText(Code, 'hsb') then
result := 'Upper Sorbian'
else if SameText(Code, 'hu') then
result := 'Hungarian'
else if SameText(Code, 'hy') then
result := 'Armenian'
else if SameText(Code, 'id') then
result := 'Indonesian'
else if SameText(Code, 'ig') then
result := 'Igbo'
else if SameText(Code, 'ii') then
result := 'Yi'
else if SameText(Code, 'is') then
result := 'Icelandic'
else if SameText(Code, 'it') then