-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgoogle_drive.pas
More file actions
1529 lines (1287 loc) · 41.2 KB
/
google_drive.pas
File metadata and controls
1529 lines (1287 loc) · 41.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 google_drive;
{$IFDEF FPC}
{$mode objfpc}{$H+}
{$ENDIF}
interface
uses
Classes, SysUtils, DB, Forms, google_oauth2, fpjson, jsonparser, memds,
httpsend, blcksock, typinfo, ComCtrls, synautil, StdCtrls, md5;
type TGDExport = record
Description : string;
MimeType : string;
FileExtension : string;
end;
type TGDExportArray = array of TGDExport;
const GoogleDocumentsExport : TGDExportArray =
(
(Description:'HTML';MimeType:'text/html';FileExtension:'.html'),
(Description:'Plain Text';MimeType:'text/plain';FileExtension:'.txt'),
(Description:'Rich text';MimeType:'application/rtf';FileExtension:'.rtf'),
(Description:'Open Office';MimeType:'application/vnd.oasis.opendocument.text';FileExtension:'.odt'),
(Description:'PDF';MimeType:'application/pdf';FileExtension:'.pdf'),
(Description:'MS Word document';MimeType:'application/vnd.openxmlformats-officedocument.wordprocessingml.document';FileExtension:'.docx')
) ;
const GoogleSpreadsheetsExport : TGDExportArray =
(
(Description:'MS Excel';MimeType:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';FileExtension:'.xlsx'),
(Description:'Open Office sheet';MimeType:'application/x-vnd.oasis.opendocument.spreadsheet';FileExtension:'.ods'),
(Description:'PDF';MimeType:'application/pdf';FileExtension:'.pdf'),
(Description:'CSV (first sheet only)';MimeType:'text/csv';FileExtension:'.csv')
) ;
const GoogleDrawingsExport : TGDExportArray =
(
(Description:'JPEG';MimeType:'image/jpeg';FileExtension:'.jpg'),
(Description:'PNG';MimeType:'image/png';FileExtension:'.png'),
(Description:'SVG';MimeType:'image/svg+xml';FileExtension:'.svg'),
(Description:'PDF';MimeType:'application/pdf';FileExtension:'.pdf')
) ;
const GooglePresentationsExport : TGDExportArray =
(
(Description:'MS PowerPoint';MimeType:'application/vnd.openxmlformats-officedocument.presentationml.presentation';FileExtension:'.pptx'),
(Description:'Plain text';MimeType:'text/plain';FileExtension:'.txt'),
(Description:'PDF';MimeType:'application/pdf';FileExtension:'.pdf')
) ;
type apiver = (v2, v3);
const UploadURL = 'https://www.googleapis.com/upload/drive/v3/files';
const MetaDataURL = 'https://www.googleapis.com/drive/v3/files';
type TUploadSetting = (RenameFile, KeepForever);
type TUploadSettings = set of TUploadSetting;
type Tlistsetting = (listrevisions, listparents, showpreviousfolder);
type Tlistsettings = set of Tlistsetting;
type TGFileParent = packed record
id: string;
end;
type TGFileParents = array of TGFileParent;
type TCustomPropertyAs = (asstring, asboolean, aslist, asinteger, aselse);
type TCustomProperty = packed record
name : string;
value : string;
end;
type TCustomProperties = array of TCustomProperty;
type TGFileRevision = packed record
id: string;
revisionid: string;
size: string;
modifiedTime: string;
mimetype: string;
originalFileName: string;
end;
type TGFileRevisions = array of TGfileRevision;
type TGFile = packed record
name: string;
fileid: string;
description: string;
createdTime: string;
modifiedTime: string;
downloadUrl: string;
originalFilename: string;
md5Checksum: string;
size: string;
mimeType: string;
iconLink: string;
isFolder: boolean;
headRevisionId: string;
trashed: boolean;
revisions: TGFilerevisions;
parents: TGFileParents;
end;
type TGFiles = array of TGfile;
type TGoogleDriveInformation= packed record
rootFolderId:string;
limit:int64;
usage:int64;
usageInDrive:int64;
usageInDriveTrash:int64;
end;
type
TGoogleDrive = class(TMemDataSet)
private
{ private declarations }
const MaxResults: integer = 500;
var
CancelCur: boolean;
CurFolder:string;
FgOAuth2: TGoogleOAuth2;
LastErrorCode: string;
LastErrorMessage: string;
Bytes: integer;
MaxBytes: integer;
downHTTP: THTTPSend;
FLogMemo: TMemo;
FDebugMemo: TMemo;
FProgress: TProgressBar;
procedure DownStatus(Sender: TObject; Reason: THookSocketReason;
const Value: string);
function GetSizeFromHeader(Header: string): integer;
procedure UpStatus(Sender: TObject; Reason: THookSocketReason; const Value: string);
function ParseMetadata(A:TJSONData;settings:TlistSettings):TGFile;
Function ExtractQueryProperties:string;
Function ExtractBodyProperties:string;
protected
{ protected declarations }
public
{ public declarations }
var Files: TGFiles;
var CustomBodyProperties : TCustomProperties;
var CustomQueryProperties : TCustomProperties;
constructor Create(AOwner: TComponent; client_id, client_secret: string); overload;
destructor Destroy; override;
procedure Populate(aFilter: string = '');
function DownloadFile(id, TargetFile: string; revisionid: string = ''; exportmimetype : string = ''): boolean;
function DownloadResumableFile(JFile: TGFile; TargetFile: string; revisionid: string = ''; exportmimetype : string = ''): boolean;
function GetUploadURI(const URL, auth, FileN, Description: string;const Data: TStream; parameters: string = ''; fileid: string = ''; settings : TuploadSettings = [] ): string;
property gOAuth2: TGoogleOAuth2 read FgOAuth2 write FgOAuth2;
property CurrentFolder:string read CurFolder write CurFolder;
property Progress: TProgressBar read Fprogress write Fprogress;
property GFiles: TGFiles read Files write Files;
property LogMemo: TMemo read FLogMemo write FLogMemo;
property DebugMemo: TMemo read FDebugMemo write FDebugMemo;
property CancelCurrent: boolean read CancelCur write CancelCur;
function UploadResumableFile(const URL: string; const Data: TStream): string;
procedure CreateFolder(foldername: string; parentid: string = '');
Procedure ClearAllCustomProperties;
Procedure AddCustomProperty(var customproperty:TCustomproperties;cname,cvalue:string; PropAs : TCustomPropertyAs = aselse);
Function SetFileProperties(id : string):string;
Function SetGFileProperties(Gfile:TGfile):string;
Function SetGFileRevisionProperties(Gfilerev:TGfileRevision):string;
function GetRevisions(fileid: string): TGFileRevisions;
procedure GetGFileRevisions(var A: TGFile);
function DeleteGFile(fileid:string; revisionid: string=''): boolean;
function DeleteGFileRevision(var A: TGFileRevision): boolean;
function DeleteAllGFileRevisions(var A: TGFileRevisions): boolean;
function GetGFileMetadata(id:string;settings:TListSettings;customfields:string='*'):TGFile;
procedure ListFiles(var A: TGFiles;settings:Tlistsettings;parentid:string='root';customfields:string='*');
procedure FillGFileMetadata(var A:TGFile;settings:Tlistsettings);
//function GetRootFolderId:string;
function AboutGdrive(version:apiver):TGoogleDriveInformation;
published
end;
implementation
Procedure TGoogleDrive.ClearAllCustomProperties;
begin
setlength(CustomBodyProperties,0);
setlength(CustomQueryProperties,0);
end;
Procedure TGoogleDrive.AddCustomProperty(var customproperty:TCustomproperties;cname,cvalue:string; PropAs : TCustomPropertyAs = aselse);
var i : integer;
begin
i:=length(CustomProperty);
Setlength(CustomProperty, i + 1);
with CustomProperty[i] do
begin
name:=cname;
value:=cvalue;
if (PropAs = asstring) then value := '"' + value + '"';
end
end;
procedure TGoogleDrive.UpStatus(Sender: TObject; Reason: THookSocketReason;
const Value: string);
begin
if Reason = HR_WriteCount then
begin
Progress.StepBy(StrToIntDef(Value, 0));
Application.ProcessMessages;
end;
end;
function TGoogleDrive.UploadResumableFile(const URL: string;
const Data: TStream): string;
const
MaxChunk = 40 * 256 * 1024; // ALWAYS chunks of 256KB
var
HTTP: THTTPSend;
s: string;
i: integer;
From, Size: integer;
Tries, PrevFrom: integer;
begin
Result := '';
HTTP := THTTPSend.Create;
try
// Always check if there already was aborted upload (is easiest)
HTTP.Headers.Add('Content-Length: 0');
HTTP.Headers.Add('Content-Range: bytes */*');
if not HTTP.HTTPMethod('PUT', URL) then exit;
Result := 'pre - ' + #13 + HTTP.Headers.Text + #13 + #13 + HTTP.ResultString;
From := 0;
if HTTP.ResultCode in [200, 201] then
begin
Result := '200 already uploaded completely';
exit;
end;
if HTTP.ResultCode = 308 then // Resume Incomplete
begin
for i := 0 to HTTP.Headers.Count - 1 do
begin
if Pos('Range: bytes=0-', HTTP.Headers.Strings[i]) > 0 then
begin
s := StringReplace(HTTP.Headers.Strings[i], 'Range: bytes=0-', '', []);
From := StrToIntDef(s, -1) + 1; // from 0 or max_range + 1
break;
end;
end;
end;
if not HTTP.ResultCode in [200, 201, 308] then
exit;
Tries := 0;
PrevFrom := From;
Progress.Min := 0;
Progress.Max := Data.Size - 1;
HTTP.Sock.OnStatus := @UpStatus;
repeat
Progress.Position := From;
HTTP.Document.Clear;
HTTP.Headers.Clear;
// We need to resune upload from position "from"
Data.Position := From;
Size := Data.Size - From;
if Size > MaxChunk then
Size := MaxChunk;
HTTP.Document.CopyFrom(Data, Size);
HTTP.Headers.Add(Format('Content-Range: bytes %d-%d/%d',
[From, From + Size - 1, Data.Size]));
HTTP.MimeType := '';
LogMemo.Lines.Add(HTTP.Headers.Text);
if not HTTP.HTTPMethod('PUT', URL) then exit;
Result := HTTP.Headers.Text + #13 + #13 + HTTP.ResultString;
// Mainform.Memo2.Lines.Add(Result);
if HTTP.ResultCode in [200, 201] then
Result := '200 Upload complete';
if HTTP.ResultCode = 308 then // Resume Incomplete
begin
for i := 0 to HTTP.Headers.Count - 1 do
begin
if Pos('Range: bytes=0-', HTTP.Headers.Strings[i]) > 0 then
begin
s := StringReplace(HTTP.Headers.Strings[i], 'Range: bytes=0-', '', []);
PrevFrom := From;
From := StrToIntDef(s, -1) + 1; // from 0 or max_range + 1
break;
end;
end;
end;
// no 308 with actual transfer is received, increase tries
if PrevFrom = From then
Inc(Tries);
until (HTTP.ResultCode in [200, 201]) or (Tries > 1);
finally
HTTP.Free;
end;
end;
Function TGoogleDrive.ExtractBodyProperties:string;
var i : integer;
begin
result:= '{' + CRLF + '}';
if length(CustomBodyProperties)>0 then
begin
result := '{' + CRLF;
for i:=0 to length(CustomBodyProperties)-1 do
begin;
result := result + '"' + CustomBodyProperties[i].name + '": ';
result := result + CustomBodyProperties[i].value;
if i<length(CustomBodyProperties)-1 then result := result + ',';
result := result + CRLF;
end;
result := result + '}';
end;
end;
Function TGoogleDrive.ExtractQueryProperties:string;
var i : integer;
begin
result:='';
if length(CustomQueryProperties)>0 then
begin
result := '?';
for i:=0 to length(CustomQueryProperties)-1 do
begin
result := result + CustomQueryProperties[i].name + '=' + CustomQueryProperties[i].value;
if i<length(CustomQueryProperties)-1 then result := result + '&';
end;
end;
end;
Function TGoogleDrive.SetFileProperties(id : string):string;
var
HTTP: THTTPSend;
s, p: string;
URL : string;
i: integer;
begin
Result := '';
if (length(CustomBodyProperties)=0) and (length(CustomQueryProperties)=0) then
begin
result:='No properties to set, can''t continue';
exit;
end;
URL := MetadataURL + '/' + id;
// Query Parameters
URL := URL + ExtractQueryProperties;
// Body parameters
s:= ExtractBodyProperties;
HTTP := THTTPSend.Create;
try
HTTP.MimeType := 'application/json; charset=UTF-8';
WriteStrToStream(HTTP.Document, ansistring(s));
HTTP.Headers.Add('Authorization: Bearer ' + gOAuth2.Access_token);
LogMemo.Lines.Add(s + #13 + URL);
if not HTTP.HTTPMethod('PATCH', URL) then
begin
LogMemo.Lines.Add('Error setting parameters');
exit;
end;
Result := HTTP.ResultString;
LogMemo.Lines.Add( Result);
finally
HTTP.Free;
end;
end;
Function TGoogleDrive.SetGFileProperties(Gfile:TGfile):string;
begin
result:=SetFileProperties(Gfile.fileid);
end;
Function TGoogleDrive.SetGFileRevisionProperties(Gfilerev:TGfileRevision):string;
begin
result:=SetFileProperties(Gfilerev.id+'revisions/'+Gfilerev.revisionid);
end;
function TGoogleDrive.GetUploadURI(const URL, auth, FileN, Description: string;
const Data: TStream; parameters: string = ''; fileid: string = ''; settings : TuploadSettings = [] ): string;
var
HTTP: THTTPSend;
Method, URLM: string;
s, rev: string;
i: integer;
begin
Result := '';
if fileid <> '' then
begin
Method := 'PATCH';
URLM := URL + '/' + fileid;
rev:='originalFilename';
end
else
begin
Method := 'POST';
URLM := URL;
rev:='name';
end;
ClearAllCustomProperties;
AddCustomProperty(CustomBodyProperties,rev,ExtractFileName(FileN),asstring);
if (Renamefile in settings) and (fileid <> '') then
AddCustomProperty(CustomBodyProperties,'name',ExtractFileName(FileN),asstring);
AddCustomProperty(CustomBodyProperties,'description',Description,asstring);
s := ExtractBodyProperties;
HTTP := THTTPSend.Create;
try
HTTP.MimeType := 'application/json; charset=UTF-8';
WriteStrToStream(HTTP.Document, ansistring(s));
HTTP.Headers.Add(Format('X-Upload-Content-Length: %d', [Data.Size]));
HTTP.Headers.Add('Authorization: Bearer ' + auth);
AddCustomProperty(CustomQueryProperties,'uploadType','resumable');
if (KeepForever in settings) then
AddCustomProperty(CustomQueryProperties,'keepRevisionForever','true');
parameters := ExtractQueryProperties;
LogMemo.Lines.Add(s + chr(13) + URLM + '[' + parameters + ']');
if not HTTP.HTTPMethod(Method, URLM + parameters) then
begin
LogMemo.Lines.Add('Error retrieving URI');
exit;
end;
Result := HTTP.ResultString; // for any errors
for i := 0 to HTTP.Headers.Count - 1 do
begin
if Pos('Location: ', HTTP.Headers.Strings[i]) > 0 then
begin
Result := StringReplace(HTTP.Headers.Strings[i], 'Location: ', '', []);
break;
end;
end;
finally
HTTP.Free;
end;
end;
function TGoogleDrive.DownloadResumableFile(JFile: TGFile; TargetFile: string; revisionid: string = ''; exportmimetype : string = ''): boolean;
const
MaxChunk = 1024 * 1024;// 40 * 256 * 1024;
var
HTTPGetResult: boolean;
URL, URLM: string;
from,size: integer;
Stream: TFileStream;
resume: boolean;
begin
CancelCurrent:= False;
Result := False;
resume:= false;
if FileExists(TargetFile) then
begin
Stream:=TFileStream.Create(TargetFile, fmOpenReadWrite);
from:= Stream.size;
resume:= true;
end
else
begin
Stream:=TFileStream.Create(TargetFile, fmCreate);
from := 0;
end;
size := strtoint64(JFile.size);
if gOAuth2.EMail = '' then exit;
DownHTTP := THTTPSend.Create;
Progress.Min := 0;
Progress.Max := size;
Progress.Position:= from;
Bytes := 0;
MaxBytes := -1;
if not resume then
LogMemo.Lines.Add('Downloading file...')
else
LogMemo.Lines.Add('Resuming file...');
try
repeat
DownHTTP.Sock.OnStatus := @DownStatus;
Stream.Seek(0,soEnd);
URL := MetadataURL + '/' + JFile.fileid;
ClearAllCustomProperties;
if revisionid <> '' then URL := URL + '/revisions/' + revisionid;
if exportmimetype <> '' then
begin
URL := URL + '/export';
AddCustomProperty(CustomQueryProperties, 'mimeType',exportmimetype);
end
else AddCustomProperty(CustomQueryProperties, 'alt','media');
DownHTTP.Clear;
DownHTTP.Headers.Add('Authorization: Bearer ' + gOAuth2.Access_token);
DownHTTP.Headers.Add(format('Range: bytes=%d-%d',[from,from+maxchunk]));
Result := DownHTTP.HTTPMethod('GET', URL + ExtractQueryproperties);
if (DownHTTP.ResultCode >= 100) and (DownHTTP.ResultCode <= 299) then
begin
Stream.CopyFrom(DownHTTP.Document, DownHTTP.Document.Size);
LogMemo.Lines.Add('Download OK [' + IntToStr(DownHTTP.ResultCode) + ' - Range ' + inttostr(from) + ' to ' + inttostr(from+DownHTTP.Document.Size) +']');
// LogMemo.Lines.Add(DownHTTP.Headers.Text);
inc(from,DownHTTP.Document.Size);
end
else
begin
CancelCurrent:=true;
LogMemo.Lines.Add('Error downloading file [' + IntToStr(DownHTTP.ResultCode) + ']');
end;
Application.processmessages;
until (from >= size) or (CancelCurrent);
Result := True;
finally
DownHTTP.Free;
Stream.Free;
if (JFile.md5Checksum<> '') and (JFile.md5Checksum=md5print(md5file(TargetFile))) then
LogMemo.Lines.Add('Download OK - checkSum OK') else
LogMemo.Lines.Add('Download OK - checkSum is not correct !!!');
end;
end;
function TGoogleDrive.DownloadFile(id, TargetFile: string; revisionid: string = ''; exportmimetype : string = ''): boolean;
var
HTTPGetResult: boolean;
URL, URLM: string;
begin
Result := False;
if gOAuth2.EMail = '' then exit;
Bytes := 0;
MaxBytes := -1;
DownHTTP := THTTPSend.Create;
try
Progress.Min := 0;
Progress.Max := 100;
// DownHTTP.Sock.OnStatus := @DownStatus;
LogMemo.Lines.Add('Downloading file...');
URL := MetadataURL + '/' + id;
ClearAllCustomProperties;
if revisionid <> '' then URL := URL + '/revisions/' + revisionid;
if exportmimetype <> '' then
begin
URL := URL + '/export';
AddCustomProperty(CustomQueryProperties, 'mimeType',exportmimetype);
end
else AddCustomProperty(CustomQueryProperties, 'alt','media');
DownHTTP.Headers.Add('Authorization: Bearer ' + gOAuth2.Access_token);
Result := DownHTTP.HTTPMethod('GET', URL + ExtractQueryproperties);
if (DownHTTP.ResultCode >= 100) and (DownHTTP.ResultCode <= 299) then
begin
DownHTTP.Document.SaveToFile(TargetFile);
LogMemo.Lines.Add('Download OK [' + IntToStr(DownHTTP.ResultCode) + ']');
Result := True;
end
else
begin
LogMemo.Lines.Add('Error downloading file [' + IntToStr(DownHTTP.ResultCode) + ']');
end;
finally
DownHTTP.Free;
end;
end;
procedure TGoogleDrive.DownStatus(Sender: TObject; Reason: THookSocketReason; const Value: string);
var
V, currentHeader: string;
i: integer;
pct: integer;
begin
if (MaxBytes = -1) then
begin
for i := 0 to DownHTTP.Headers.Count - 1 do
begin
currentHeader := DownHTTP.Headers[i];
MaxBytes := GetSizeFromHeader(currentHeader);
if MaxBytes <> -1 then break;
end;
end;
V := GetEnumName(TypeInfo(THookSocketReason), integer(Reason)) + ' ' + Value;
if Reason = THookSocketReason.HR_ReadCount then
begin
Bytes := Bytes + StrToInt(Value);
pct := round(Bytes / maxbytes * 100);
Progress.Position := progress.position + StrToInt(Value);//pct;
Application.ProcessMessages;
end;
end;
function TGoogleDrive.GetSizeFromHeader(Header: string): integer;
var
item: TStringList;
begin
Result := -1;
if Pos('Content-Length:', Header) <> 0 then
begin
item := TStringList.Create();
try
item.Delimiter := ':';
item.StrictDelimiter := True;
item.DelimitedText := Header;
if item.Count = 2 then
begin
Result := StrToInt(Trim(item[1]));
end;
finally
item.Free;
end;
end;
end;
constructor TGoogleDrive.Create(AOwner: TComponent; client_id, client_secret: string);
begin
inherited Create(AOwner);
FieldDefs.Clear;
//FieldDefs.Add('Boolean', ftBoolean, 0, False);
//FieldDefs.Add('Integer', ftInteger, 0, False);
//FieldDefs.Add('SmallInt', ftSmallInt, 0, False);
//FieldDefs.Add('Float', ftFloat, 0, False);
//FieldDefs.Add('String', ftString, 30, False);
//FieldDefs.Add('Time', ftTime, 0, False);
//FieldDefs.Add('Date', ftDate, 0, False);
//FieldDefs.Add('DateTime', ftDateTime, 0, False);
FieldDefs.Add('title', ftString, 255, False);
FieldDefs.Add('fileId', ftString, 255, False);
FieldDefs.Add('description', ftString, 255, False);
FieldDefs.Add('created', ftString, 255, False);
FieldDefs.Add('modified', ftString, 255, False);
FieldDefs.Add('downloadurl', ftString, 255, False);
FieldDefs.Add('filename', ftString, 255, False);
FieldDefs.Add('md5', ftString, 255, False);
FieldDefs.Add('filesize', ftString, 20, False);
FieldDefs.Add('IsFolder', ftBoolean, 0, False);
FieldDefs.Add('mimeType', ftString, 255, False);
FieldDefs.Add('iconLink', ftString, 255, False);
CreateTable;
gOAuth2 := TGoogleOAuth2.Create(client_id, client_secret);
end;
destructor TGoogleDrive.Destroy;
begin
gOAuth2.Free;
inherited Destroy;
end;
function RetrieveJSONValueInt64(JSON: TJSONData; Value: string): int64;
var
D: TJSONData;
begin
Result := 0;
if Assigned(JSON) then
begin
D := JSON.FindPath(Value);
if assigned(D) then
Result := D.AsInt64;
end;
end;
function RetrieveJSONValue(JSON: TJSONData; Value: string): string;
var
D: TJSONData;
begin
Result := '';
if Assigned(JSON) then
begin
D := JSON.FindPath(Value);
if assigned(D) then
Result := D.AsString;
end;
end;
procedure TGoogleDrive.Populate(aFilter: string = '');
var
Response: TStringList;
URL: string;
Params: string;
P: TJSONParser;
I: integer;
J, D, E: TJSONData;
begin
(*
{
"kind": "drive#fileList",
"etag": etag,
"selfLink": string,
"nextPageToken": string,
"nextLink": string,
"items": [ files Resource ]
}
{
"kind": "drive#file",
"id": string,
"etag": etag,
"selfLink": string,
"webContentLink": string,
"webViewLink": string,
"alternateLink": string,
"embedLink": string,
"openWithLinks": {
(key): string
},
"defaultOpenWithLink": string,
"iconLink": string,
"thumbnailLink": string,
"thumbnail": {
"image": bytes,
"mimeType": string
},
"title": string,
"mimeType": string,
"description": string,
"labels": {
"starred": boolean,
"hidden": boolean,
"trashed": boolean,
"restricted": boolean,
"viewed": boolean
},
"createdDate": datetime,
"modifiedDate": datetime,
"modifiedByMeDate": datetime,
"lastViewedByMeDate": datetime,
"markedViewedByMeDate": datetime,
"sharedWithMeDate": datetime,
"version": long,
"sharingUser": {
"kind": "drive#user",
"displayName": string,
"picture": {
"url": string
},
"isAuthenticatedUser": boolean,
"permissionId": string,
"emailAddress": string
},
"parents": [
parents Resource
],
"downloadUrl": string,
"downloadUrl": string,
"exportLinks": {
(key): string
},
"indexableText": {
"text": string
},
"userPermission": permissions Resource,
"permissions": [
permissions Resource
],
"originalFilename": string,
"fileExtension": string,
"fullFileExtension": string,
"md5Checksum": string,
"fileSize": long,
"quotaBytesUsed": long,
"ownerNames": [
string
],
"owners": [
{
"kind": "drive#user",
"displayName": string,
"picture": {
"url": string
},
"isAuthenticatedUser": boolean,
"permissionId": string,
"emailAddress": string
}
],
"lastModifyingUserName": string,
"lastModifyingUser": {
"kind": "drive#user",
"displayName": string,
"picture": {
"url": string
},
"isAuthenticatedUser": boolean,
"permissionId": string,
"emailAddress": string
},
"ownedByMe": boolean,
"editable": boolean,
"canComment": boolean,
"canReadRevisions": boolean,
"shareable": boolean,
"copyable": boolean,
"writersCanShare": boolean,
"shared": boolean,
"explicitlyTrashed": boolean,
"appDataContents": boolean,
"headRevisionId": string,
"properties": [
properties Resource
],
"folderColorRgb": string,
"imageMediaMetadata": {
"width": integer,
"height": integer,
"rotation": integer,
"location": {
"latitude": double,
"longitude": double,
"altitude": double
},
"date": string,
"cameraMake": string,
"cameraModel": string,
"exposureTime": float,
"aperture": float,
"flashUsed": boolean,
"focalLength": float,
"isoSpeed": integer,
"meteringMode": string,
"sensor": string,
"exposureMode": string,
"colorSpace": string,
"whiteBalance": string,
"exposureBias": float,
"maxApertureValue": float,
"subjectDistance": integer,
"lens": string
},
"videoMediaMetadata": {
"width": integer,
"height": integer,
"durationMillis": long
},
"spaces": [
string
],
"isAppAuthorized": boolean
}
*)
Response := TStringList.Create;
Self.DisableControls;
try
if gOAuth2.EMail = '' then
exit;
// https://developers.google.com/drive/v2/reference/files/list
gOAuth2.LogLine('Retrieving filelist ' + gOAuth2.EMail);
URL := 'https://www.googleapis.com/drive/v2/files';
Params := 'access_token=' + gOAuth2.Access_token;
Params := Params + '&maxResults=1000';
Params := Params + '&orderBy=folder,modifiedDate%20desc,title';
if HttpGetText(URL + '?' + Params, Response) then
begin
gOAuth2.DebugLine(Response.Text);
Self.Clear(False); // remove all records
P := TJSONParser.Create(Response.Text);
try
J := P.Parse;
if Assigned(J) then
begin
D := J.FindPath('error');
if assigned(D) then
begin
LastErrorCode := RetrieveJSONValue(D, 'code');
LastErrorMessage := RetrieveJSONValue(D, 'message');
gOAuth2.LogLine(format('Error %s: %s',
[LastErrorCode, LastErrorMessage]));
exit;
end;
gOAuth2.LogLine('Busy filling dataset');
D := J.FindPath('items');
gOAuth2.DebugLine(format('%d items received', [D.Count]));
for I := 0 to D.Count - 1 do
begin
Append;
// 2015-02-10T10:42:49.297Z
// 2012-05-18T15:45:00+02:00
FieldByName('title').AsString := RetrieveJSONValue(D.Items[I], 'title');
FieldByName('fileId').AsString := RetrieveJSONValue(D.Items[I], 'id');
FieldByName('description').AsString := RetrieveJSONValue(D.Items[I], 'description');
FieldByName('created').AsString := RetrieveJSONValue(D.Items[I], 'createdDate');
FieldByName('modified').AsString := RetrieveJSONValue(D.Items[I], 'modifiedDate');
FieldByName('downloadurl').AsString := RetrieveJSONValue(D.Items[I], 'downloadUrl');
FieldByName('filename').AsString := RetrieveJSONValue(D.Items[I], 'originalFilename');
FieldByName('md5').AsString := RetrieveJSONValue(D.Items[I], 'md5Checksum');
FieldByName('filesize').AsString := RetrieveJSONValue(D.Items[I], 'fileSize');
FieldByName('mimeType').AsString := RetrieveJSONValue(D.Items[I], 'mimeType');
FieldByName('iconLink').AsString := RetrieveJSONValue(D.Items[I], 'iconLink');
FieldByName('IsFolder').AsBoolean := FieldByName('mimeType').AsString = 'application/vnd.google-apps.folder';
Self.Post;
Application.ProcessMessages;
end;
gOAuth2.LogLine(format('%d items stored', [Self.RecordCount]));
gOAuth2.LogLine('Done filling dataset');
end;
finally
if assigned(J) then
J.Free;
P.Free;
end;
end;
finally
Response.Free;
Self.EnableControls;
end;