-
Notifications
You must be signed in to change notification settings - Fork 0
/
CloudMailRu.pas
2055 lines (1897 loc) · 78.4 KB
/
CloudMailRu.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
unit CloudMailRu;
interface
uses CMLJSON, CMLTypes, System.Hash, System.Classes, System.Generics.Collections, System.SysUtils, PLUGIN_Types, Winapi.Windows, IdStack, MRC_helper, Settings, IdCookieManager, IdIOHandler, IdIOHandlerSocket, IdIOHandlerStack, IdSSL, IdSSLOpenSSL, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdSocks, IdHTTP, IdAuthentication, IdIOHandlerStream, IdInterceptThrottler, FileSplitter, IdCookie, IdMultipartFormData, Cipher;
type
TCloudMailRu = class
private
{VARIABLES}
ExternalSourceName: PWideChar;
ExternalTargetName: PWideChar;
domain: WideString;
user: WideString;
password: WideString;
unlimited_filesize: Boolean;
split_large_files: Boolean;
split_file_size: integer;
public_account: Boolean;
PUBLIC_URL: WideString;
public_link: WideString; //public url without adress prefix
public_download_token: WideString;
public_shard: WideString;
shard_override: WideString;
token: WideString;
OAuthToken: TCloudMailRuOAuthInfo;
x_page_id: WideString;
build: WideString;
upload_url: WideString;
login_method: integer;
Cookie: TIdCookieManager;
Socks: TIdSocksInfo;
Throttle: TIdInterceptThrottler;
ExternalProgressProc: TProgressHandler;
ExternalLogProc: TLogHandler;
ExternalRequestProc: TRequestHandler;
Shard: WideString;
Proxy: TProxySettings;
ConnectTimeout: integer;
UploadBPS: integer;
DownloadBPS: integer;
PrecalculateHash: Boolean;
CheckCRC: Boolean;
FileCipher: TFileCipher;
united_params: WideString; //Объединённый набор авторизационных параметров для подстановки в URL
{BASE HTTP METHODS}
procedure HTTPInit(var HTTP: TIdHTTP; var SSL: TIdSSLIOHandlerSocketOpenSSL; var Socks: TIdSocksInfo; var Cookie: TIdCookieManager);
procedure HTTPDestroy(var HTTP: TIdHTTP; var SSL: TIdSSLIOHandlerSocketOpenSSL);
function HTTPGetPage(URL: WideString; var Answer: WideString; var ProgressEnabled: Boolean): Boolean; //если ProgressEnabled - включаем обработчик onWork, возвращаем ProgressEnabled=false при отмене
function HTTPGetFile(URL: WideString; FileStream: TStream; LogErrors: Boolean = true): integer;
function HTTPPostForm(URL: WideString; PostDataString: WideString; var Answer: WideString; ContentType: WideString = 'application/x-www-form-urlencoded'; LogErrors: Boolean = true; ProgressEnabled: Boolean = true): Boolean; //Постинг данных с возможным получением ответа.
function HTTPPostMultipart(URL: WideString; Params: TDictionary<WideString, WideString>; var Answer: WideString): Boolean;
function HTTPPostFile(URL: WideString; FileName: WideString; var Answer: WideString): integer; //Постинг файла и получение ответа
function HTTPPost(URL: WideString; PostData, ResultData: TStringStream; UnderstandResponseCode: Boolean = false; ContentType: WideString = ''; LogErrors: Boolean = true; ProgressEnabled: Boolean = true): integer; overload; //Постинг подготовленных данных, отлов ошибок
function HTTPPost(URL: WideString; var PostData: TIdMultiPartFormDataStream; ResultData: TStringStream): integer; overload; //TIdMultiPartFormDataStream should be passed via var
function HTTPExceptionHandler(E: Exception; URL: WideString; HTTPMethod: integer = HTTP_METHOD_POST; LogErrors: Boolean = true): integer;
procedure HTTPProgress(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: int64);
{RAW TEXT PARSING}
function extractNearValue(Text, Anchor: WideString; StartChar: WideChar = '"'; EndChar: WideChar = '"'): WideString;
function extractTokenFromText(Text: WideString; var token: WideString): Boolean;
function extractPublicTokenFromText(Text: WideString; var PublicToken: WideString): Boolean;
function extract_x_page_id_FromText(Text: WideString; var PageId: WideString): Boolean;
function extract_build_FromText(Text: WideString; var build: WideString): Boolean;
function extract_upload_url_FromText(Text: WideString; var UploadUrl: WideString): Boolean;
function extractPublicShard(Text: WideString; var Shard: WideString): Boolean;
function extractTwostepJson(Text: WideString; var JSON: WideString): Boolean;
{JSON MANIPULATION}
//Moved to CMLJSON
{HTTP REQUESTS WRAPPERS}
function getToken(): Boolean;
function getSharedToken(): Boolean;
function getOAuthToken(var OAuthToken: TCloudMailRuOAuthInfo): Boolean;
function getShard(var Shard: WideString): Boolean;
function getUserSpace(var SpaceInfo: TCloudMailRuSpaceInfo): Boolean;
function putFileToCloud(localPath: WideString; Return: TStringList): integer;
function addFileToCloud(Hash: WideString; size: int64; remotePath: WideString; var JSONAnswer: WideString; ConflictMode: WideString = CLOUD_CONFLICT_STRICT; LogErrors: Boolean = true): Boolean; //LogErrors=false => не логируем результат операции, нужно для поиска данных в облаке по хешу
{OTHER ROUTINES}
procedure Log(LogLevel, MsgType: integer; LogString: WideString);
function CloudResultToFsResult(CloudResult: integer; OperationStatus: integer; ErrorPrefix: WideString = ''): integer;
function cloudHash(Path: WideString): WideString; overload;
function cloudHash(Stream: TStream; SourceName: WideString = ''): WideString; overload;
protected
{REGULAR CLOUD}
function loginRegular(method: integer = CLOUD_AUTH_METHOD_WEB): Boolean;
function getFileRegular(remotePath, localPath: WideString; var resultHash: WideString; LogErrors: Boolean = true): integer; //LogErrors=false => не логируем результат копирования, нужно для запроса descript.ion (которого может не быть)
{SHARED WEBFOLDERS}
function loginShared(method: integer = CLOUD_AUTH_METHOD_WEB): Boolean;
function getFileShared(remotePath, localPath: WideString; var resultHash: WideString; LogErrors: Boolean = true): integer; //LogErrors=false => не логируем результат копирования, нужно для запроса descript.ion (которого может не быть)
public
crypt_files: Boolean;
crypt_filenames: Boolean;
Property isPublicShare: Boolean read public_account;
Property ProxySettings: TProxySettings read Proxy;
Property UploadLimit: integer read UploadBPS;
Property DownloadLimit: integer read DownloadBPS;
Property ConnectTimeoutValue: integer read ConnectTimeout;
function getSharedFileUrl(remotePath: WideString; DoUrlEncode: Boolean = true): WideString;
{CONSTRUCTOR/DESTRUCTOR}
constructor Create(AccountSettings: TAccountSettings; split_file_size: integer; Proxy: TProxySettings; ConnectTimeout: integer; UploadBPS: integer; DownloadBPS: integer; PrecalculateHash: Boolean = true; CheckCRC: Boolean = true; ExternalProgressProc: TProgressHandler = nil; ExternalLogProc: TLogHandler = nil; ExternalRequestProc: TRequestHandler = nil);
destructor Destroy; override;
{CLOUD INTERFACE METHODS}
function login(method: integer = CLOUD_AUTH_METHOD_WEB): Boolean;
function getDirListing(Path: WideString; var DirListing: TCloudMailRuDirListing; ShowProgress: Boolean = false): Boolean;
function getSharedLinksListing(var DirListing: TCloudMailRuDirListing; ShowProgress: Boolean = false): Boolean;
function getIncomingLinksListing(var IncomingListing: TCloudMailRuIncomingInviteInfoListing; ShowProgress: Boolean = false): Boolean; overload;
function getIncomingLinksListing(var IncomingListing: TCloudMailRuDirListing; var InvitesListing: TCloudMailRuIncomingInviteInfoListing; ShowProgress: Boolean = false): Boolean; overload;
function getTrashbinListing(var DirListing: TCloudMailRuDirListing; ShowProgress: Boolean = false): Boolean;
function createDir(Path: WideString): Boolean;
function removeDir(Path: WideString): Boolean;
function statusFile(Path: WideString; var FileInfo: TCloudMailRuDirListingItem): Boolean;
function getFile(remotePath, localPath: WideString; var resultHash: WideString; LogErrors: Boolean = true): integer; //LogErrors=false => не логируем результат копирования, нужно для запроса descript.ion (которого может не быть)
function putFile(localPath, remotePath: WideString; ConflictMode: WideString = CLOUD_CONFLICT_STRICT; ChunkOverwriteMode: integer = 0): integer;
function renameFile(OldName, NewName: WideString): integer; //смена имени без перемещения
function moveFile(OldName, ToPath: WideString): integer; //перемещение по дереву каталогов
function copyFile(OldName, ToPath: WideString): integer; //Копирование файла внутри одного каталога
function mvFile(OldName, NewName: WideString): integer; //объединяющая функция, определяет делать rename или move
function cpFile(OldName, NewName: WideString): integer; //Копирует файл, и переименует, если нужно
function deleteFile(Path: WideString): Boolean;
function publishFile(Path: WideString; var PublicLink: WideString; publish: Boolean = CLOUD_PUBLISH): Boolean;
function cloneWeblink(Path, link: WideString; ConflictMode: WideString = CLOUD_CONFLICT_RENAME): integer; //клонировать публичную ссылку в текущий каталог
function getShareInfo(Path: WideString; var InviteListing: TCloudMailRuInviteInfoListing): Boolean;
function shareFolder(Path, email: WideString; access: integer): Boolean;
function trashbinRestore(Path: WideString; RestoreRevision: integer; ConflictMode: WideString = CLOUD_CONFLICT_RENAME): Boolean;
function trashbinEmpty(): Boolean;
function mountFolder(home, invite_token: WideString; ConflictMode: WideString = CLOUD_CONFLICT_RENAME): Boolean;
function unmountFolder(home: WideString; clone_copy: Boolean): Boolean;
function rejectInvite(invite_token: WideString): Boolean;
{OTHER ROUTINES}
function getDescriptionFile(remotePath, localCopy: WideString): Boolean; //Если в каталоге remotePath есть descript.ion - скопировать его в файл localcopy
function putDesriptionFile(remotePath, localCopy: WideString): Boolean; //Скопировать descript.ion из временного файла на сервер
procedure logUserSpaceInfo();
function putFileSplit(localPath, remotePath: WideString; ConflictMode: WideString = CLOUD_CONFLICT_STRICT; ChunkOverwriteMode: integer = 0): integer;
{STATIC ROUTINES}
class function CloudAccessToString(access: WideString; Invert: Boolean = false): WideString; static;
class function StringToCloudAccess(accessString: WideString; Invert: Boolean = false): integer; static;
class function ErrorCodeText(ErrorCode: integer): WideString; static;
end;
implementation
{TCloudMailRu}
function TCloudMailRu.addFileToCloud(Hash: WideString; size: int64; remotePath: WideString; var JSONAnswer: WideString; ConflictMode: WideString = CLOUD_CONFLICT_STRICT; LogErrors: Boolean = true): Boolean;
var
FileName: WideString;
begin
{Экспериментально выяснено, что параметры api, build, email, x-email, x-page-id в запросе не обязательны}
if self.crypt_filenames then
begin
FileName := ExtractUniversalFileName(remotePath);
FileName := FileCipher.CryptFileName(FileName);
remotePath := ChangePathFileName(remotePath, FileName);
end;
Result := self.HTTPPostForm(API_FILE_ADD, 'conflict=' + ConflictMode + '&home=/' + PathToUrl(remotePath) + '&hash=' + Hash + '&size=' + size.ToString + self.united_params, JSONAnswer, 'application/x-www-form-urlencoded', LogErrors);
end;
function TCloudMailRu.cloneWeblink(Path, link, ConflictMode: WideString): integer;
var
JSON: WideString;
OperationStatus: integer;
Progress: Boolean;
begin
Result := FS_FILE_WRITEERROR;
if not(Assigned(self)) then
exit; //Проверка на вызов без инициализации
if self.public_account then
exit(FS_FILE_NOTSUPPORTED);
Progress := true;
if self.HTTPGetPage(API_CLONE + '?folder=' + PathToUrl(Path) + '&weblink=' + link + '&conflict=' + ConflictMode + self.united_params, JSON, Progress) then
begin //Парсим ответ
Result := fromJSON_OperationResult(JSON, OperationStatus);
if Result <> CLOUD_OPERATION_OK then
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'File publish error: ' + self.ErrorCodeText(Result) + ' Status: ' + OperationStatus.ToString());
end else begin
if not(Progress) then
begin //user cancelled
Result := FS_FILE_USERABORT;
end else begin //unknown error
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'Public link clone error: got ' + OperationStatus.ToString + ' status');
Result := FS_FILE_WRITEERROR;
end;
end;
end;
function TCloudMailRu.CloudResultToFsResult(CloudResult: integer; OperationStatus: integer; ErrorPrefix: WideString): integer;
begin
case CloudResult of
CLOUD_OPERATION_OK:
exit(CLOUD_OPERATION_OK);
CLOUD_ERROR_EXISTS:
exit(FS_FILE_EXISTS);
CLOUD_ERROR_REQUIRED, CLOUD_ERROR_INVALID, CLOUD_ERROR_READONLY, CLOUD_ERROR_NAME_LENGTH_EXCEEDED:
exit(FS_FILE_WRITEERROR);
CLOUD_ERROR_UNKNOWN:
exit(FS_FILE_NOTSUPPORTED);
CLOUD_ERROR_OVERQUOTA:
begin
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'Insufficient Storage');
exit(FS_FILE_WRITEERROR);
end;
CLOUD_ERROR_NAME_TOO_LONG:
begin
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'Name too long');
exit(FS_FILE_WRITEERROR);
end;
else
begin //что-то неизвестное
if (ErrorPrefix <> EmptyWideStr) then
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, ErrorPrefix + self.ErrorCodeText(CloudResult) + ' Status: ' + OperationStatus.ToString());
exit(FS_FILE_WRITEERROR);
end;
end;
end;
function TCloudMailRu.copyFile(OldName, ToPath: WideString): integer;
var
JSON: WideString;
OperationStatus, OperationResult: integer;
begin
Result := FS_FILE_WRITEERROR;
if not(Assigned(self)) then
exit; //Проверка на вызов без инициализации
if self.public_account then
exit(FS_FILE_NOTSUPPORTED);
if self.HTTPPostForm(API_FILE_COPY, 'home=' + PathToUrl(OldName) + '&folder=' + PathToUrl(ToPath) + self.united_params + '&conflict', JSON) then
begin //Парсим ответ
OperationResult := fromJSON_OperationResult(JSON, OperationStatus);
Result := CloudResultToFsResult(OperationResult, OperationStatus, 'File copy error: ');
end;
end;
function TCloudMailRu.cpFile(OldName, NewName: WideString): integer;
var
NewPath: WideString;
SameDir, SameName: Boolean;
begin //Облако умеет скопировать файл, но не сможет его переименовать, поэтому хитрим
NewPath := ExtractFilePath(NewName);
SameDir := ExtractFilePath(OldName) = ExtractFilePath(NewName);
SameName := ExtractFileName(OldName) = ExtractFileName(NewName);
if (SameDir) then //копирование в тот же каталог не поддерживается напрямую, а мудрить со временными каталогами я не хочу
begin
Log(LogLevelWarning, MSGTYPE_IMPORTANTERROR, 'Copying in same dir not supported by cloud');
exit(FS_FILE_NOTSUPPORTED);
end else begin
Result := self.copyFile(OldName, NewPath);
if Result <> CLOUD_OPERATION_OK then
exit;
end;
if not(SameName) then
begin //скопированный файл лежит в новом каталоге со старым именем
Result := self.renameFile(NewPath + ExtractFileName(OldName), ExtractFileName(NewName));
end;
end;
constructor TCloudMailRu.Create(AccountSettings: TAccountSettings; split_file_size: integer; Proxy: TProxySettings; ConnectTimeout: integer; UploadBPS: integer; DownloadBPS: integer; PrecalculateHash: Boolean = true; CheckCRC: Boolean = true; ExternalProgressProc: TProgressHandler = nil; ExternalLogProc: TLogHandler = nil; ExternalRequestProc: TRequestHandler = nil);
begin
try
self.ExternalProgressProc := ExternalProgressProc;
self.ExternalLogProc := ExternalLogProc;
self.ExternalRequestProc := ExternalRequestProc;
self.Cookie := TIdCookieManager.Create();
self.Throttle := TIdInterceptThrottler.Create();
self.Proxy := Proxy;
if Proxy.ProxyType in SocksProxyTypes then //SOCKS proxy initialization
begin
self.Socks := TIdSocksInfo.Create();
self.Socks.Host := Proxy.Server;
self.Socks.Port := Proxy.Port;
if Proxy.user <> EmptyWideStr then
begin
self.Socks.Authentication := saUsernamePassword;
self.Socks.Username := Proxy.user;
self.Socks.password := Proxy.password;
end
else
self.Socks.Authentication := saNoAuthentication;
case Proxy.ProxyType of
ProxySocks5:
Socks.Version := svSocks5;
ProxySocks4:
Socks.Version := svSocks4;
end;
self.Socks.Enabled := true;
end;
self.user := AccountSettings.user;
self.password := AccountSettings.password;
self.domain := AccountSettings.domain;
self.unlimited_filesize := AccountSettings.unlimited_filesize;
self.split_large_files := AccountSettings.split_large_files;
self.public_account := AccountSettings.public_account;
self.PUBLIC_URL := AccountSettings.PUBLIC_URL;
if AccountSettings.encrypt_files_mode <> EncryptModeNone then
begin
self.FileCipher := TFileCipher.Create(AccountSettings.crypt_files_password, AccountSettings.CryptedGUID_files, AccountSettings.encrypt_filenames);
if self.FileCipher.WrongPassword then
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'Wrong encryption password, encryption support disabled');
self.crypt_files := not(self.FileCipher.WrongPassword);
self.crypt_filenames := self.crypt_files and AccountSettings.encrypt_filenames and not(self.FileCipher.WrongPassword);
end;
self.shard_override := AccountSettings.shard_override;
if self.public_account and (self.PUBLIC_URL <> EmptyWideStr) then
begin
self.public_link := self.PUBLIC_URL;
self.PUBLIC_URL := IncludeSlash(self.PUBLIC_URL);
Delete(self.public_link, 1, length(PUBLIC_ACCESS_URL));
if self.public_link[length(self.public_link)] = '/' then
Delete(self.public_link, length(self.public_link), 1);
end;
self.split_file_size := split_file_size;
self.ConnectTimeout := ConnectTimeout;
self.UploadBPS := UploadBPS;
self.DownloadBPS := DownloadBPS;
self.PrecalculateHash := PrecalculateHash;
self.CheckCRC := CheckCRC;
self.ExternalSourceName := nil;
self.ExternalTargetName := nil;
except
on E: Exception do
begin
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'Cloud initialization error: ' + E.Message);
end;
end;
end;
function TCloudMailRu.createDir(Path: WideString): Boolean;
var
PostAnswer: WideString;
OperationStatus, OperationResult: integer;
begin
Result := false;
if not(Assigned(self)) then
exit; //Проверка на вызов без инициализации
if self.public_account then
exit;
if self.HTTPPostForm(API_FOLDER_ADD, 'home=/' + PathToUrl(Path) + self.united_params + '&conflict', PostAnswer) then
begin
OperationResult := fromJSON_OperationResult(PostAnswer, OperationStatus);
case OperationResult of
CLOUD_OPERATION_OK:
Result := true;
else
begin
//Log(MSGTYPE_IMPORTANTERROR, 'Directory creation error: ' + self.ErrorCodeText(OperationResult) + ' Status: ' + OperationStatus.ToString());
Result := false;
end;
end;
end;
end;
function TCloudMailRu.deleteFile(Path: WideString): Boolean;
var
JSON: WideString;
OperationResult, OperationStatus: integer;
begin
Result := false;
if not(Assigned(self)) then
exit; //Проверка на вызов без инициализации
if self.public_account then
exit;
Result := self.HTTPPostForm(API_FILE_REMOVE, 'home=/' + PathToUrl(Path) + self.united_params + '&conflict', JSON);
if Result then
begin
OperationResult := fromJSON_OperationResult(JSON, OperationStatus);
case OperationResult of
CLOUD_OPERATION_OK:
Result := true;
else
begin
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'Delete file error: ' + self.ErrorCodeText(OperationResult) + ' Status: ' + OperationStatus.ToString());
Result := false;
end;
end;
end;
end;
destructor TCloudMailRu.Destroy;
begin
if Assigned(self.Cookie) then
self.Cookie.free;
if Assigned(self.Throttle) then
self.Throttle.free;
if Assigned(self.Socks) then
self.Socks.free;
if Assigned(self.FileCipher) then
self.FileCipher.Destroy;
inherited;
end;
class function TCloudMailRu.ErrorCodeText(ErrorCode: integer): WideString;
begin
case ErrorCode of
CLOUD_ERROR_EXISTS:
exit('Объект с таким названием уже существует. Попробуйте другое название.');
CLOUD_ERROR_REQUIRED:
exit('Название папки не может быть пустым.');
CLOUD_ERROR_INVALID:
exit('Неправильное название папки. В названии папок нельзя использовать символы «" * / : < > ? \\ |».');
CLOUD_ERROR_READONLY:
exit('Невозможно создать. Доступ только для просмотра.');
CLOUD_ERROR_NAME_LENGTH_EXCEEDED:
exit('Превышена длина имени папки.');
CLOUD_ERROR_OVERQUOTA:
exit('Невозможно скопировать, в вашем Облаке недостаточно места.');
CLOUD_ERROR_NOT_EXISTS:
exit('Копируемая ссылка не существует.');
CLOUD_ERROR_OWN:
exit('Невозможно клонировать собственную ссылку.');
CLOUD_ERROR_NAME_TOO_LONG:
exit('Превышена длина имени файла.');
CLOUD_ERROR_VIRUS_SCAN_FAIL:
exit('Файл заражен вирусом');
CLOUD_ERROR_OWNER:
exit('Нельзя использовать собственный email');
CLOUD_ERROR_FAHRENHEIT:
exit('Невозможно создать ссылку. Публикация контента заблокирована по требованию правообладателя или уполномоченного государственного ведомства.');
CLOUD_ERROR_BAD_REQUEST:
exit('Ошибка запроса к серверу.');
CLOUD_ERROR_TREES_CONFLICT:
exit('Нельзя сделать папку общей, если она содержит другие общие папки или находится в общей папке');
CLOUD_ERROR_UNPROCESSABLE_ENTRY:
exit('Нельзя открыть доступ к файлу');
CLOUD_ERROR_USER_LIMIT_EXCEEDED:
exit('Невозможно добавить пользователя. Вы можете иметь не более 200 пользователей в одной общей папке ');
CLOUD_ERROR_EXPORT_LIMIT_EXCEEDED:
exit('Невозможно добавить пользователя. Вы можете создать не более 50 общих папок');
CLOUD_ERROR_NOT_ACCEPTABLE:
exit('Нельзя добавить этого пользователя');
else
exit('Неизвестная ошибка (' + ErrorCode.ToString + ')');
end;
end;
function TCloudMailRu.extractNearValue(Text, Anchor: WideString; StartChar: WideChar = '"'; EndChar: WideChar = '"'): WideString;
var
start, end_: integer;
begin
Result := EmptyWideStr;
Text := StringReplace(Text, #$A, EmptyWideStr, [rfReplaceAll]); //так нам проще ковыряться в тексте
Text := StringReplace(Text, #$D, EmptyWideStr, [rfReplaceAll]);
Text := StringReplace(Text, #9, EmptyWideStr, [rfReplaceAll]);
Text := StringReplace(Text, #$20, EmptyWideStr, [rfReplaceAll]);
start := Pos(WideString(Anchor), Text);
if start > 0 then
begin
start := Pos(StartChar, Text, start + length(Anchor)) + 1;
end_ := Pos(EndChar, Text, start);
Result := copy(Text, start, end_ - start);
end;
end;
function TCloudMailRu.extractTokenFromText(Text: WideString; var token: WideString): Boolean;
begin
token := self.extractNearValue(Text, '"csrf"');
Result := token <> EmptyWideStr;
end;
function TCloudMailRu.extractTwostepJson(Text: WideString; var JSON: WideString): Boolean;
var
start, finish: integer;
begin
Result := false;
start := Pos(WideString('<script type="text/html" id="json">'), Text);
finish := Pos(WideString('</script>'), Text);
if (start > 0) and (finish > 0) then
begin
JSON := copy(Text, start + 35, finish - start - 35);
Result := true;
end;
end;
function TCloudMailRu.extract_build_FromText(Text: WideString; var build: WideString): Boolean;
begin
build := self.extractNearValue(Text, '"BUILD"');
Result := build <> EmptyWideStr;
end;
function TCloudMailRu.extract_upload_url_FromText(Text: WideString; var UploadUrl: WideString): Boolean;
var
start, start1, start2, finish, length: Cardinal;
temp: WideString;
begin
Result := false;
start := Pos(WideString('mail.ru/upload/"'), Text);
if start > 0 then
begin
start1 := start - 50;
finish := start + 15;
length := finish - start1;
temp := copy(Text, start1, length);
start2 := Pos(WideString('https://'), temp);
UploadUrl := copy(temp, start2, Strlen(PWideChar(temp)) - start2);
Result := true;
end;
end;
function TCloudMailRu.extract_x_page_id_FromText(Text: WideString; var PageId: WideString): Boolean;
begin
PageId := self.extractNearValue(Text, '"x-page-id"');
Result := PageId <> EmptyWideStr;
end;
function TCloudMailRu.extractPublicShard(Text: WideString; var Shard: WideString): Boolean;
begin
Shard := extractNearValue(Text, '"weblink_get":', '[', ']');
Shard := extractNearValue(Shard, '"url":');
Result := EmptyWideStr <> Shard;
end;
function TCloudMailRu.extractPublicTokenFromText(Text: WideString; var PublicToken: WideString): Boolean;
begin
PublicToken := extractNearValue(Text, '"tokens":{"download":');
Result := EmptyWideStr <> PublicToken;
end;
function TCloudMailRu.getDescriptionFile(remotePath, localCopy: WideString): Boolean;
var
resultHash: WideString;
begin
Result := self.getFile(remotePath, localCopy, resultHash, false) = FS_FILE_OK;
end;
function TCloudMailRu.putDesriptionFile(remotePath, localCopy: WideString): Boolean;
begin
if FileExists(localCopy) then
Result := self.putFile(localCopy, remotePath) = FS_FILE_OK
else
Result := self.deleteFile(remotePath);
end;
function TCloudMailRu.getSharedLinksListing(var DirListing: TCloudMailRuDirListing; ShowProgress: Boolean = false): Boolean;
var
JSON: WideString;
OperationStatus, OperationResult: integer;
begin
Result := false;
if not(Assigned(self)) then
exit; //Проверка на вызов без инициализации
SetLength(DirListing, 0);
if self.public_account then
exit;
Result := self.HTTPGetPage(API_FOLDER_SHARED_LINKS + '?' + self.united_params, JSON, ShowProgress);
if Result then
begin
OperationResult := fromJSON_OperationResult(JSON, OperationStatus);
case OperationResult of
CLOUD_OPERATION_OK:
Result := fromJSON_DirListing(JSON, DirListing);
else
begin
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'Shared links listing error: ' + self.ErrorCodeText(OperationResult) + ' Status: ' + OperationStatus.ToString());
Result := false;
end;
end;
end;
end;
function TCloudMailRu.getIncomingLinksListing(var IncomingListing: TCloudMailRuIncomingInviteInfoListing; ShowProgress: Boolean): Boolean;
var
JSON: WideString;
OperationStatus, OperationResult: integer;
begin
Result := false;
if not(Assigned(self)) then
exit; //Проверка на вызов без инициализации
SetLength(IncomingListing, 0);
if self.public_account then
exit;
Result := self.HTTPGetPage(API_FOLDER_SHARED_INCOMING + '?' + self.united_params, JSON, ShowProgress);
if Result then
begin
OperationResult := fromJSON_OperationResult(JSON, OperationStatus);
case OperationResult of
CLOUD_OPERATION_OK:
Result := fromJSON_IncomingInviteListing(JSON, IncomingListing);
else
begin
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'Incoming requests listing error: ' + self.ErrorCodeText(OperationResult) + ' Status: ' + OperationStatus.ToString());
Result := false;
end;
end;
end;
end;
function TCloudMailRu.getIncomingLinksListing(var IncomingListing: TCloudMailRuDirListing; var InvitesListing: TCloudMailRuIncomingInviteInfoListing; ShowProgress: Boolean = false): Boolean;
var
i: integer;
begin
Result := false;
if not(Assigned(self)) then
exit; //Проверка на вызов без инициализации
SetLength(IncomingListing, 0);
Result := self.getIncomingLinksListing(InvitesListing, ShowProgress);
if Result then
begin
SetLength(IncomingListing, length(InvitesListing));
for i := 0 to length(InvitesListing) - 1 do
begin
IncomingListing[i].name := InvitesListing[i].name;
IncomingListing[i].size := InvitesListing[i].size;
IncomingListing[i].tree := InvitesListing[i].tree;
//IncomingListing[length(IncomingListing)].
end;
end;
end;
function TCloudMailRu.getTrashbinListing(var DirListing: TCloudMailRuDirListing; ShowProgress: Boolean): Boolean;
var
JSON: WideString;
OperationStatus, OperationResult: integer;
begin
Result := false;
if not(Assigned(self)) then
exit; //Проверка на вызов без инициализации
SetLength(DirListing, 0);
if self.public_account then
exit;
Result := self.HTTPGetPage(API_TRASHBIN + '?' + self.united_params, JSON, ShowProgress);
if Result then
begin
OperationResult := fromJSON_OperationResult(JSON, OperationStatus);
case OperationResult of
CLOUD_OPERATION_OK:
Result := fromJSON_DirListing(JSON, DirListing);
else
begin
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'Incoming requests listing error: ' + self.ErrorCodeText(OperationResult) + ' Status: ' + OperationStatus.ToString());
Result := false;
end;
end;
end;
end;
function TCloudMailRu.getDirListing(Path: WideString; var DirListing: TCloudMailRuDirListing; ShowProgress: Boolean = false): Boolean;
var
JSON: WideString;
OperationStatus, OperationResult: integer;
begin
Result := false;
if not(Assigned(self)) then
exit; //Проверка на вызов без инициализации
SetLength(DirListing, 0);
if self.public_account then
Result := self.HTTPGetPage(API_FOLDER + '&weblink=' + IncludeSlash(self.public_link) + PathToUrl(Path, false) + self.united_params, JSON, ShowProgress)
else
Result := self.HTTPGetPage(API_FOLDER + '&home=' + PathToUrl(Path) + self.united_params, JSON, ShowProgress);
if Result then
begin
OperationResult := fromJSON_OperationResult(JSON, OperationStatus);
case OperationResult of
CLOUD_OPERATION_OK:
begin
Result := fromJSON_DirListing(JSON, DirListing);
if Result and self.crypt_filenames then
self.FileCipher.DecryptDirListing(DirListing);
end;
CLOUD_ERROR_NOT_EXISTS:
begin
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'Path not exists: ' + Path);
Result := false;
end
else
begin
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'Directory listing error: ' + self.ErrorCodeText(OperationResult) + ' Status: ' + OperationStatus.ToString()); //?? WUT
Result := false;
end;
end;
end;
end;
function TCloudMailRu.getFile(remotePath, localPath: WideString; var resultHash: WideString; LogErrors: Boolean): integer;
begin
Result := FS_FILE_NOTSUPPORTED;
if not(Assigned(self)) then
exit; //Проверка на вызов без инициализации
if self.public_account then
Result := self.getFileShared(remotePath, localPath, resultHash, LogErrors)
else
Result := self.getFileRegular(remotePath, localPath, resultHash, LogErrors);
end;
function TCloudMailRu.getFileRegular(remotePath, localPath: WideString; var resultHash: WideString; LogErrors: Boolean): integer;
var
FileStream: TFileStream;
FileName: WideString;
MemoryStream: TMemoryStream;
begin
Result := FS_FILE_NOTSUPPORTED;
if self.Shard = EmptyWideStr then
begin
Log(LogLevelDetail, MSGTYPE_DETAILS, 'Current shard is undefined, trying to get one');
if not self.getShard(self.Shard) then
exit;
end;
if self.crypt_filenames then
begin
FileName := ExtractUniversalFileName(remotePath);
FileName := FileCipher.DecryptFileName(FileName);
localPath := ChangePathFileName(localPath, FileName);
end;
try
FileStream := TFileStream.Create(GetUNCFilePath(localPath), fmCreate);
except
on E: Exception do
begin
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, E.Message);
exit(FS_FILE_WRITEERROR);
end;
end;
self.ExternalSourceName := PWideChar(remotePath);
self.ExternalTargetName := PWideChar(localPath);
if self.crypt_files then //Загрузка файла в память, дешифрация в файл
begin
MemoryStream := TMemoryStream.Create;
Result := self.HTTPGetFile(self.Shard + PathToUrl(remotePath, false), MemoryStream, LogErrors);
if Result in [FS_FILE_OK] then
begin
resultHash := cloudHash(MemoryStream, ExtractFileName(localPath));
MemoryStream.Position := 0;
self.FileCipher.DecryptStream(MemoryStream, FileStream);
end;
MemoryStream.free;
end else begin
Result := self.HTTPGetFile(self.Shard + PathToUrl(remotePath, false), FileStream, LogErrors);
if (Result in [FS_FILE_OK]) then
resultHash := cloudHash(FileStream, ExtractFileName(localPath));
end;
FlushFileBuffers(FileStream.Handle);
FileStream.free;
self.ExternalSourceName := nil;
self.ExternalTargetName := nil;
if not(Result in [FS_FILE_OK]) then
System.SysUtils.deleteFile(GetUNCFilePath(localPath));
end;
function TCloudMailRu.getSharedFileUrl(remotePath: WideString; DoUrlEncode: Boolean = true): WideString;
begin
Result := IncludeSlash(self.public_shard) + IncludeSlash(self.public_link) + PathToUrl(remotePath, true, DoUrlEncode) + '?key=' + self.public_download_token
end;
function TCloudMailRu.getFileShared(remotePath, localPath: WideString; var resultHash: WideString; LogErrors: Boolean): integer;
var
FileStream: TFileStream;
begin
Result := FS_FILE_NOTFOUND;
if (self.public_shard = EmptyWideStr) or (self.public_download_token = EmptyWideStr) then
exit;
try
FileStream := TFileStream.Create(GetUNCFilePath(localPath), fmCreate);
except
on E: Exception do
begin
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, E.Message);
exit(FS_FILE_WRITEERROR);
end;
end;
if (Assigned(FileStream)) then
begin
Result := self.HTTPGetFile(getSharedFileUrl(remotePath), FileStream, LogErrors);
resultHash := cloudHash(FileStream);
FlushFileBuffers(FileStream.Handle);
FileStream.free;
end;
if Result <> FS_FILE_OK then
System.SysUtils.deleteFile(GetUNCFilePath(localPath));
end;
function TCloudMailRu.getOAuthToken(var OAuthToken: TCloudMailRuOAuthInfo): Boolean;
var
Answer: WideString;
begin
Result := false;
if self.HTTPPostForm(OAUTH_TOKEN_URL, 'client_id=cloud-win&grant_type=password&username=' + self.user + '%40' + self.domain + '&password=' + UrlEncode(self.password), Answer) then
begin
if not fromJSON_OAuthTokenInfo(Answer, OAuthToken) then
exit(false);
Result := OAuthToken.error_code = NOERROR;
end;
end;
function TCloudMailRu.getShard(var Shard: WideString): Boolean;
var
JSON: WideString;
OperationResult, OperationStatus: integer;
begin
Result := false;
if not(Assigned(self)) then
exit; //Проверка на вызов без инициализации
if self.shard_override <> EmptyWideStr then
begin
Log(LogLevelError, MSGTYPE_DETAILS, 'Shard overriden via config!');
Shard := self.shard_override;
exit(true);
end;
if self.HTTPPostForm(API_DISPATCHER, self.united_params, JSON) then //checkme
begin
OperationResult := fromJSON_OperationResult(JSON, OperationStatus);
case OperationResult of
CLOUD_OPERATION_OK:
begin
Result := fromJSON_Shard(JSON, Shard) and (Shard <> EmptyWideStr);
Log(LogLevelDetail, MSGTYPE_DETAILS, 'Shard received: ' + Shard);
end
else
begin
Result := false;
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'Shard receive error: ' + self.ErrorCodeText(OperationResult) + ' Status: ' + OperationStatus.ToString());
end;
end;
end;
end;
function TCloudMailRu.getToken: Boolean;
var
JSON: WideString;
Progress: Boolean;
begin
Result := false;
if not(Assigned(self)) then
exit; //Проверка на вызов без инициализации
Progress := false;
Result := self.HTTPGetPage(TOKEN_URL, JSON, Progress);
if Result then
begin
Result := self.extractTokenFromText(JSON, self.token) and self.extract_x_page_id_FromText(JSON, self.x_page_id) and self.extract_build_FromText(JSON, self.build) and self.extract_upload_url_FromText(JSON, self.upload_url);
self.united_params := '&api=2&build=' + self.build + '&x-page-id=' + self.x_page_id + '&email=' + self.user + '%40' + self.domain + '&x-email=' + self.user + '%40' + self.domain + '&token=' + self.token + '&_=' + DateTimeToUnix(now).ToString + '810';
end;
end;
function TCloudMailRu.getSharedToken(): Boolean;
var
PageContent: WideString;
Progress: Boolean;
begin
Result := false;
if not(Assigned(self)) then
exit; //Проверка на вызов без инициализации
Progress := false;
Result := self.HTTPGetPage(self.PUBLIC_URL, PageContent, Progress);
if Result then
begin
if not self.extractPublicTokenFromText(PageContent, self.public_download_token) then //refresh public download token
begin
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'Can''t get public share download token');
exit(false);
end;
if not self.extractPublicShard(PageContent, self.public_shard) then
begin
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'Can''t get public share download share');
exit(false);
end;
end;
end;
function TCloudMailRu.getUserSpace(var SpaceInfo: TCloudMailRuSpaceInfo): Boolean;
var
JSON: WideString;
Progress: Boolean;
OperationResult, OperationStatus: integer;
begin
Result := false;
if not(Assigned(self)) then
exit; //Проверка на вызов без инициализации
Progress := false;
Result := self.HTTPGetPage(API_USER_SPACE + '?home=/' + self.united_params, JSON, Progress);
if Result then
begin
OperationResult := fromJSON_OperationResult(JSON, OperationStatus);
case OperationResult of
CLOUD_OPERATION_OK:
Result := fromJSON_UserSpace(JSON, SpaceInfo);
else
begin
Result := false;
Log(LogLevelError, MSGTYPE_IMPORTANTERROR, 'User space receiving error: ' + self.ErrorCodeText(OperationResult) + ' Status: ' + OperationStatus.ToString());
end;
end;
end;
end;
procedure TCloudMailRu.HTTPInit(var HTTP: TIdHTTP; var SSL: TIdSSLIOHandlerSocketOpenSSL; var Socks: TIdSocksInfo; var Cookie: TIdCookieManager);
begin
SSL := TIdSSLIOHandlerSocketOpenSSL.Create();
SSL.SSLOptions.SSLVersions := [sslvSSLv23];
HTTP := TIdHTTP.Create();
if (self.Proxy.ProxyType in SocksProxyTypes) and (self.Socks.Enabled) then
SSL.TransparentProxy := self.Socks;
if self.Proxy.ProxyType = ProxyHTTP then
begin
HTTP.ProxyParams.ProxyServer := self.Proxy.Server;
HTTP.ProxyParams.ProxyPort := self.Proxy.Port;
if self.Proxy.user <> EmptyWideStr then
begin
HTTP.ProxyParams.BasicAuthentication := true;
HTTP.ProxyParams.ProxyUsername := self.Proxy.user;
HTTP.ProxyParams.ProxyPassword := self.Proxy.password;
end
end;
HTTP.CookieManager := Cookie;
HTTP.IOHandler := SSL;
HTTP.AllowCookies := true;
HTTP.HTTPOptions := [hoForceEncodeParams, hoNoParseMetaHTTPEquiv, hoKeepOrigProtocol, hoTreat302Like303];
HTTP.HandleRedirects := true;
if (self.ConnectTimeout < 0) then
begin
HTTP.ConnectTimeout := self.ConnectTimeout;
HTTP.ReadTimeout := self.ConnectTimeout;
end;
if (self.UploadBPS > 0) or (self.DownloadBPS > 0) then
begin
self.Throttle.RecvBitsPerSec := self.DownloadBPS;
self.Throttle.SendBitsPerSec := self.UploadBPS;
end;
HTTP.Request.UserAgent := 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17/TCWFX(' + PlatformX + ')';
HTTP.Request.Connection := EmptyWideStr;
end;
procedure TCloudMailRu.HTTPDestroy(var HTTP: TIdHTTP; var SSL: TIdSSLIOHandlerSocketOpenSSL);
begin
HTTP.free;
SSL.free;
end;
function TCloudMailRu.HTTPGetPage(URL: WideString; var Answer: WideString; var ProgressEnabled: Boolean): Boolean;
var
HTTP: TIdHTTP;
SSL: TIdSSLIOHandlerSocketOpenSSL;
Socks: TIdSocksInfo;
begin
Result := false;
try
self.HTTPInit(HTTP, SSL, Socks, self.Cookie);
if ProgressEnabled then
HTTP.OnWork := self.HTTPProgress; //Вызов прогресса ведёт к возможности отменить получение списка каталогов и других операций, поэтому он нужен не всегда
Answer := HTTP.Get(URL);
self.HTTPDestroy(HTTP, SSL);
Result := Answer <> EmptyWideStr;
Except
on E: Exception do
begin
case self.HTTPExceptionHandler(E, URL) of
CLOUD_OPERATION_CANCELLED:
begin
ProgressEnabled := false; //сообщаем об отмене
end;
CLOUD_OPERATION_FAILED:
begin
case HTTP.ResponseCode of
HTTP_ERROR_BAD_REQUEST, HTTP_ERROR_OVERQUOTA: //recoverable errors
begin
//Answer := (E as EIdHTTPProtocolException).ErrorMessage; //TODO: нужно протестировать, наверняка тут не json
end;
end;
end;
end;
if Assigned(HTTP) then
self.HTTPDestroy(HTTP, SSL);
end;
end;
end;
function TCloudMailRu.HTTPGetFile(URL: WideString; FileStream: TStream; LogErrors: Boolean): integer;
var