-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathKLib.Indy.pas
457 lines (401 loc) · 13.2 KB
/
KLib.Indy.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
{
KLib Version = 3.0
The Clear BSD License
Copyright (c) 2020 by Karol De Nery Ortiz LLave. All rights reserved.
zitrokarol@gmail.com
Redistribution and use in source and binary forms, with or without
modification, are permitted (subject to the limitations in the disclaimer
below) provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY
THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
unit KLib.Indy;
interface
uses
KLib.Types, KLib.Constants,
IdFTP, IdHTTP,
System.Classes;
procedure TCPPrintFilesInDir(hostPort: THostPort; dirName: string; fileType: string = EMPTY_STRING);
procedure TCPPrintFilesInDirWithStartingFileName(hostPort: THostPort;
dirName: string; startingFileName: string = EMPTY_STRING; fileType: string = EMPTY_STRING);
procedure TCPPrintFromFile(hostPort: THostPort; fileName: string);
procedure TCPPrintText(hostPort: THostPort; text: string);
function getValidIdFTP(FTPCredentials: TFTPCredentials): TIdFTP;
function checkFTPCredentials(FTPCredentials: TFTPCredentials): boolean;
function getIdFTP(FTPCredentials: TFTPCredentials): TIdFTP;
function getOAuth2Response(const url: string; const clientID: string; const clientSecret: string): TOAuth2Response;
function HTTP_get(url: string; paramList: TStringList; credentials: TCredentials): string; overload;
function HTTP_get(url: string; paramList: TStringList; idHTTPRequest: TIdHTTPRequest = nil): string; overload;
function HTTP_post(url: string; paramList: TStringList; credentials: TCredentials): string; overload;
function HTTP_post(url: string; paramList: TStringList; idHTTPRequest: TIdHTTPRequest = nil): string; overload;
//USING INDY WITH SSL (E.G downloadFileWithIndy) YOU NEED libeay32.dll, libssl32.dll, ssleay32.dll
//INCLUDE RESOURCES IN YOUR PROJECT
// RESOURCE_LIBEAY32: TResource = (name: 'LIBEAY32'; _type: DLL_TYPE);
// RESOURCE_LIBSSL32: TResource = (name: 'LIBSSL32'; _type: DLL_TYPE);
// RESOURCE_SSLEAY32: TResource = (name: 'SSLEAY32'; _type: DLL_TYPE);
procedure downloadZipFileAndExtract(info: TDownloadInfo; forceOverwrite: boolean;
destinationPath: string; forceDeleteZipFile: boolean = false);
procedure downloadFile(info: TDownloadInfo; forceOverwrite: boolean);
procedure getOpenSSLDLLsFromResource;
procedure tryToDeleteOpenSSLDLLsIfExists;
procedure deleteOpenSSLDLLsIfExists;
function getMD5ChecksumFile(fileName: string): string;
implementation
uses
KLib.Validate, KLib.Utils, KLib.MyIdHTTP, KLib.MyStringList, Klib.Windows, KLib.Generics.JSON,
IdGlobal, IdHash, IdHashMessageDigest, IdSSLOpenSSL, IdFTPCommon, IdTCPClient,
System.SysUtils, System.NetEncoding;
procedure TCPPrintFilesInDir(hostPort: THostPort; dirName: string; fileType: string = EMPTY_STRING);
begin
TCPPrintFilesInDirWithStartingFileName(hostPort, dirName, EMPTY_STRING, fileType);
end;
procedure TCPPrintFilesInDirWithStartingFileName(hostPort: THostPort;
dirName: string; startingFileName: string = EMPTY_STRING; fileType: string = EMPTY_STRING);
const
IGNORE_CASE = true;
var
_files: TStringList;
_file: string;
_fileName: string;
begin
_files := getFileNamesListInDir(dirName, fileType);
for _file in _files do
begin
_fileName := ExtractFileName(_file);
if (_fileName.StartsWith(startingFileName, IGNORE_CASE)) or (startingFileName = EMPTY_STRING) then
begin
TCPPrintFromFile(hostPort, _file)
end;
end;
FreeAndNil(_files);
end;
procedure TCPPrintFromFile(hostPort: THostPort; fileName: string);
var
_text: string;
begin
_text := getTextFromFile(fileName);
TCPPrintText(hostPort, _text);
end;
procedure TCPPrintText(hostPort: THostPort; text: string);
var
TCPClient: TIdTCPClient;
begin
TCPClient := TIdTCPClient.Create(nil);
with TCPClient do
begin
Host := hostPort.host;
Port := hostPort.port;
end;
try
TCPClient.Connect;
TCPClient.Socket.Write(text);
TCPClient.Disconnect;
finally
TCPClient.Free;
end;
end;
function getValidIdFTP(FTPCredentials: TFTPCredentials): TIdFTP;
var
connection: TIdFTP;
begin
validateFTPCredentials(FTPCredentials);
connection := getIdFTP(FTPCredentials);
Result := connection;
end;
function checkFTPCredentials(FTPCredentials: TFTPCredentials): boolean;
var
_connection: TIdFTP;
_result: boolean;
begin
_result := true;
_connection := getIdFTP(FTPCredentials);
try
_connection.Connect;
if FTPCredentials.pathFTPDir <> EMPTY_STRING then
begin
_connection.ChangeDir(FTPCredentials.pathFTPDir);
end;
except
on E: Exception do
begin
_result := false;
end;
end;
_connection.Disconnect;
_connection.Free;
Result := _result;
end;
function getIdFTP(FTPCredentials: TFTPCredentials): TIdFTP;
var
connection: TIdFTP;
begin
validateRequiredFTPProperties(FTPCredentials);
connection := TIdFTP.Create(nil);
with connection do
begin
Host := FTPCredentials.server;
Username := FTPCredentials.credentials.username;
Password := FTPCredentials.credentials.password;
Port := FTPCredentials.port;
TransferType := TIdFTPTransferType(FTPCredentials.transferType);
end;
if connection.Port = 0 then
begin
connection.Port := FTP_DEFAULT_PORT;
end;
//todo create function checkIFEnumIsInValidRange
if (connection.transferType < Low(TIdFTPTransferType)) or (connection.transferType > High(TIdFTPTransferType)) then
begin
connection.transferType := ftBinary;
end;
connection.Passive := true;
Result := connection;
end;
function getOAuth2Response(const url: string; const clientID: string; const clientSecret: string): TOAuth2Response;
var
OAuth2Response: TOAuth2Response;
_response: string;
_authHeader: string;
_idHTTPRequest: TIdHTTPRequest;
_params: TStringList;
begin
_idHTTPRequest := TIdHTTPRequest.Create(nil);
_authHeader := 'Basic ' + TNetEncoding.Base64.Encode(clientID + ':' + clientSecret).Replace(#13#10, '');
_idHTTPRequest.CustomHeaders.Add('Authorization: ' + _authHeader);
_idHTTPRequest.ContentType := 'application/x-www-form-urlencoded';
_params := TStringList.Create();
_params.Add('grant_type=client_credentials');
try
_response := HTTP_post(url, _params, _idHTTPRequest);
OAuth2Response := TJSONGenerics.getParsedJSON<TOAuth2Response>(_response);
finally
FreeAndNil(_idHTTPRequest);
FreeAndNil(_params);
end;
Result := OAuth2Response;
end;
function HTTP_get(url: string; paramList: TStringList; credentials: TCredentials): string;
var
HTTP_response: string;
_idHTTPRequest: TIdHTTPRequest;
begin
_idHTTPRequest := TIdHTTPRequest.Create(nil);
try
if (not credentials.isEmpty()) then
begin
with _idHTTPRequest do
begin
BasicAuthentication := true;
Username := credentials.username;
Password := credentials.password;
end;
end;
HTTP_response := HTTP_get(url, paramList, _idHTTPRequest);
finally
FreeAndNil(_idHTTPRequest);
end;
Result := HTTP_response;
end;
function HTTP_get(url: string; paramList: TStringList; idHTTPRequest: TIdHTTPRequest = nil): string;
var
HTTP_response: string;
_HTTP: TMyIdHTTP;
_url: string;
begin
_HTTP := TMyIdHTTP.Create(nil);
if Assigned(idHTTPRequest) then
begin
_HTTP.Request := idHTTPRequest;
end;
_url := getHTTPGetEncodedUrl(url, paramList);
try
HTTP_response := _HTTP.Get(_url);
finally
_HTTP.Free;
end;
Result := HTTP_response;
end;
function HTTP_post(url: string; paramList: TStringList; credentials: TCredentials): string;
var
HTTP_response: string;
_idHTTPRequest: TIdHTTPRequest;
begin
_idHTTPRequest := TIdHTTPRequest.Create(nil);
try
if (not credentials.isEmpty()) then
begin
with _idHTTPRequest do
begin
BasicAuthentication := true;
Username := credentials.username;
Password := credentials.password;
end;
end;
HTTP_response := HTTP_post(url, paramList, _idHTTPRequest);
finally
FreeAndNil(_idHTTPRequest);
end;
Result := HTTP_response;
end;
function HTTP_post(url: string; paramList: TStringList; idHTTPRequest: TIdHTTPRequest = nil): string;
var
HTTP_response: string;
_HTTP: TMyIdHTTP;
begin
_HTTP := TMyIdHTTP.Create(nil);
if Assigned(idHTTPRequest) then
begin
_HTTP.Request := idHTTPRequest;
end;
try
HTTP_response := _HTTP.Post(url, paramList);
finally
_HTTP.Free;
end;
Result := HTTP_response;
end;
//USING INDY YOU NEED libeay32.dll AND libssl32.dll
procedure downloadZipFileAndExtract(info: TDownloadInfo; forceOverwrite: boolean;
destinationPath: string; forceDeleteZipFile: boolean = false);
var
_ZipFileName: string;
begin
downloadFile(info, forceOverwrite);
_ZipFileName := getCombinedPath(destinationPath, info.fileName);
unzip(_ZipFileName, destinationPath, forceDeleteZipFile);
end;
procedure downloadFile(info: TDownloadInfo; forceOverwrite: boolean);
const
ERR_MSG = 'Error downloading file.';
var
_downloadSuccess: boolean;
_HTTP: TMyIdHTTP;
_memoryStream: TMemoryStream;
_links: TStringList;
i: integer;
begin
if forceOverwrite then
begin
deleteFileIfExists(info.fileName);
end;
_downloadSuccess := false;
i := 0;
_HTTP := TMyIdHTTP.Create(nil);
_memoryStream := TMemoryStream.Create;
_links := TStringList.Create;
_links.Add(info.link);
_links.AddStrings(info.alternative_links);
try
while (not _downloadSuccess) and (i < _links.Count) do
begin
try
_HTTP.Get(_links[i], _memoryStream);
_downloadSuccess := true;
except
on E: Exception do
begin
_memoryStream.Clear;
end;
end;
Inc(i);
end;
if not _downloadSuccess then
begin
raise Exception.Create(ERR_MSG);
end;
_memoryStream.SaveToFile(info.fileName);
finally
_HTTP.Free;
FreeAndNil(_memoryStream);
FreeAndNil(_links);
end;
if info.MD5 <> '' then
begin
validateMD5File(info.fileName, info.MD5, ERR_MSG);
end;
end;
const
RESOURCE_LIBEAY32: TResource = (name: 'LIBEAY32'; _type: DLL_TYPE);
RESOURCE_LIBSSL32: TResource = (name: 'LIBSSL32'; _type: DLL_TYPE);
RESOURCE_SSLEAY32: TResource = (name: 'SSLEAY32'; _type: DLL_TYPE);
FILENAME_LIBSSL32 = 'libssl32.dll';
FILENAME_LIBEAY32 = 'libeay32.dll';
FILENAME_SSLEAY32 = 'ssleay32.dll';
procedure getOpenSSLDLLsFromResource;
var
_path_libeay32: string;
_path_libssl32: string;
_path_ssleay32: string;
begin
_path_libeay32 := getCombinedPathWithCurrentDir(FILENAME_LIBEAY32);
if not checkIfFileExists(_path_libeay32) then
begin
getResourceAsFile(RESOURCE_LIBEAY32, _path_libeay32);
end;
_path_libssl32 := getCombinedPathWithCurrentDir(FILENAME_LIBSSL32);
if not checkIfFileExists(_path_libssl32) then
begin
getResourceAsFile(RESOURCE_LIBSSL32, _path_libssl32);
end;
_path_ssleay32 := getCombinedPathWithCurrentDir(FILENAME_SSLEAY32);
if not checkIfFileExists(_path_ssleay32) then
begin
getResourceAsFile(RESOURCE_SSLEAY32, _path_ssleay32);
end;
end;
procedure tryToDeleteOpenSSLDLLsIfExists;
begin
tryToExecuteProcedure(deleteOpenSSLDLLsIfExists);
end;
procedure deleteOpenSSLDLLsIfExists;
var
_path_libeay32: string;
_path_libssl32: string;
_path_ssleay32: string;
begin
UnLoadOpenSSLLibrary;
_path_libeay32 := getCombinedPathWithCurrentDir(FILENAME_LIBEAY32);
deleteFileIfExists(_path_libeay32);
_path_libssl32 := getCombinedPathWithCurrentDir(FILENAME_LIBSSL32);
deleteFileIfExists(_path_libssl32);
_path_ssleay32 := getCombinedPathWithCurrentDir(FILENAME_SSLEAY32);
deleteFileIfExists(_path_ssleay32);
end;
function getMD5ChecksumFile(fileName: string): string;
var
MD5: string;
_IdHashMessageDigest: TIdHashMessageDigest5;
_fileStream: TFileStream;
begin
validateThatFileExists(fileName);
_IdHashMessageDigest := TIdHashMessageDigest5.Create;
_fileStream := TFileStream.Create(fileName, fmOpenRead or fmShareDenyWrite);
try
MD5 := _IdHashMessageDigest.HashStreamAsHex(_fileStream);
finally
begin
_fileStream.Free;
_IdHashMessageDigest.Free;
end;
end;
Result := MD5;
end;
end.