summaryrefslogtreecommitdiff
path: root/plugins/!Deprecated/MirandaNGHistoryToDB/IMDownloaderComponent/uIMDownloader.pas
blob: 168fc21a7f105065ada8f1b9256042b07331ba8a (plain)
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
{ ################################################################################### }
{ #                                                                                 # }
{ #  IMDownloader                                                                   # }
{ #                                                                                 # }
{ #  Base on Downloader www.webdelphi.ru                                            # }
{ #  http://www.webdelphi.ru/2009/10/mnogopotochnost-v-svoix-prilozheniyax-chast-2/ # }
{ #                                                                                 # }
{ #  License: GPLv3                                                                 # }
{ #                                                                                 # }
{ #  Author: Grigorev Michael (icq: 161867489, email: sleuthhound@gmail.com)        # }
{ #                                                                                 # }
{ #  Äîðàáîòêè ïî ñðàâíåíèþ ñ Downloader:                                           # }
{ #  + Äîáàâëåí ðàáîòà ÷åðåç ïðîêñè (ñâîéñòâà Proxy, ProxyBypass,                   # }
{ #    AuthUserName, AuthPassword, ProxyAuthUserName, ProxyAuthPassword)                                                  # }
{ #  + Äîáàâëåíî ñâîéñòâî DirPath - Ïóòü ãäå èäåò ïîèñê ôàéëà è ïðîâåðêà åãî MD5.   # }
{ #    (Èìÿ ôàéëà è åãî MD5 óçíàþòñÿ èç çàãîëîâêà îòâåòà ñåðâåðà). Åñëè MD5 ôàéëà   # }
{ #    íà äèñêå ðàâíî MD5 ôàéëà â çàãîëîâêå îòâåòà, òî ñêà÷èâàíèå íå íà÷èíàåòñÿ.    # }
{ #  + Ñîáûòèå OnHeaders - Ïîëó÷åíèå çàãîëîâêà îòâåòà ñåðâåðà.                      # }
{ #  + Ñîáûòèå OnMD5Checked - Ïîäñ÷åò MD5 ñóììû ñêà÷åííîãî ôàéëà.                   # }
{ #                                                                                 # }
{ ################################################################################### }

unit uIMDownloader;

interface

uses Classes, WinInet, SysUtils, Dialogs, Windows, Forms, uMD5;

const
 Accept = 'Accept: */*' + sLineBreak;
 ProxyConnection = 'Proxy-Connection: Keep-Alive' + sLineBreak;
 Lang = 'Accept-Language: ru' + sLineBreak;
 Agent =
   'User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; ' +
   'Windows NT 5.1; SV1; .NET CLR 2.0.50727)' + sLineBreak;

type
  PMemoryStream = ^TMemoryStream;
  TIMDownloadError = (deInternetOpen, deInternetOpenUrl, deDownloadingFile, deConnect, deRequest);
  TErrorEvent = procedure(Sender: TObject; E: TIMDownloadError) of object;
  TDownloadingEvent = procedure(Sender: TObject; AcceptedSize, MaxSize: Cardinal) of object;
  THeadersEvent = procedure(Sender: TObject; Headers: String) of object;
  TMD5Event = procedure(Sender: TObject; MD5Correct, SizeCorrect: Boolean; MD5Str: String) of object;

  TIMDownloadThread = class(TThread)
  private
    fURL: String;
    fProxy: String;
    fProxyBypass: String;
    fAuthUserName: String;
    fAuthPassword: String;
    fProxyAuthUserName: String;
    fProxyAuthPassword: String;
    fDirPath: String;
    MemoryStream: TMemoryStream;
    Err: TIMDownloadError;
    fError: TErrorEvent;
    fAccepted: TNotifyEvent;
    fBreak: TNotifyEvent;
    fDownloading: TDownloadingEvent;
    fHeaders: THeadersEvent;
    AcceptedSize: Cardinal;
    AllSize: Cardinal;
    Headers: String;
    MD5Str: String;
    MD5Correct: Boolean;
    SizeCorrect: Boolean;
    fMD5: TMD5Event;
    procedure toError;
    procedure toHeaders;
    procedure toDownloading;
    procedure toAccepted;
    procedure toBreak;
    procedure toMD5;
    procedure Complete;
    function ErrorResult(E: Boolean; eType: TIMDownloadError): Boolean;
    function GetQueryInfo(hRequest: Pointer; Flag: Integer): String;
  protected
    procedure Execute; override;
  public
    constructor Create(CreateSuspennded: Boolean; const URL, Proxy, ProxyBypass, AuthUserName, AuthPassword, ProxyAuthUserName, ProxyAuthPassword, DirPath: String; Stream: PMemoryStream);
    property URL: string read fURL;
    property Proxy: string read fProxy;			                          // Ñïèñîê ïðîêñè
    property ProxyBypass: string read fProxyBypass;                   // Äîïîëíèîòåëüíûé ñïèñîê ïðîêñè
    property AuthUserName: string read fAuthUserName;                 // Ëîãèí äëÿ Authorization: Basic
    property AuthPassword: string read fAuthPassword;                 // Ïàðîëü äëÿ Authorization: Basic
    property ProxyAuthUserName: string read fProxyAuthUserName;       // Ëîãèí äëÿ ïðîêñè
    property ProxyAuthPassword: string read fProxyAuthPassword;       // Ïàðîëü äëÿ ïðîêñè
    property DirPath: string read fDirPath write fDirPath;            // Äèðåêòîðèÿ â êîòîðîé áóäóò ïðîâåðÿòüñÿ MD5 ôàéëîâ
    property OnError: TErrorEvent read fError write fError;
    property OnAccepted: TNotifyEvent read fAccepted write fAccepted;
    property OnBreak: TNotifyEvent read fBreak write fBreak;
    property OnDownloading: TDownloadingEvent read fDownloading write fDownloading;
    property OnHeaders: THeadersEvent read fHeaders write fHeaders;
    property OnMD5Checked: TMD5Event read fMD5 write fMD5;
  end;

  TIMDownloader = class(TComponent)
  private
    fOutStream: TMemoryStream;
    fURL: String;
    fProxy: String;
    fProxyBypass: String;
    fAuthUserName: String;
    fAuthPassword: String;
    fProxyAuthUserName: String;
    fProxyAuthPassword: String;
    fDirPath: String;
    Downloader: TIMDownloadThread;
    fOnError: TErrorEvent;
    fOnAccepted: TNotifyEvent;
    fOnBreak: TNotifyEvent;
    fOnStartDownload: TNotifyEvent;
    fInDowloading: Boolean;
    fAcceptedSize: Cardinal;
    fMyHeaders: String;
    fMyMD5Str: String;
    fMyMD5Correct: Boolean;
    fMySizeCorrect: Boolean;
    fHeaders: THeadersEvent;
    fDownloading: TDownloadingEvent;
    fMD5: TMD5Event;
    procedure AcceptDownload(Sender: TObject);
    procedure Break_Download(Sender: TObject);
    procedure Downloading(Sender: TObject; AcceptedSize, MaxSize: Cardinal);
    procedure GetHeaders(Sender: TObject; Headers: String);
    procedure GetMD5(Sender: TObject; MD5Correct, SizeCorrect: Boolean; MD5Str: String);
    procedure ErrorDownload(Sender: TObject; Error: TIMDownloadError);
  public
    procedure Download;
    procedure BreakDownload;
    property OutStream: TMemoryStream read fOutStream;
    property InDowloading: Boolean read fInDowloading;
    property AcceptedSize: Cardinal read fAcceptedSize;
    property MyHeaders: String read fMyHeaders;
    property MyMD5Str: String read fMyMD5Str;
    property MyMD5Correct: Boolean read fMyMD5Correct;
    property MySizeCorrect: Boolean read fMySizeCorrect;
  published
    property URL: string read fURL write fURL;
    property Proxy: string read fProxy write fProxy;			                               // Ñïèñîê ïðîêñè
    property ProxyBypass: string read fProxyBypass write fProxyBypass;                   // Äîïîëíèîòåëüíûé ñïèñîê ïðîêñè
    property AuthUserName: string read fAuthUserName write fAuthUserName;                // Ëîãèí äëÿ Authorization: Basic
    property AuthPassword: string read fAuthPassword write fAuthPassword;                // Ïàðîëü äëÿ Authorization: Basic
    property ProxyAuthUserName: string read fProxyAuthUserName write fProxyAuthUserName; // Ëîãèí äëÿ ïðîêñè
    property ProxyAuthPassword: string read fProxyAuthPassword write fProxyAuthUserName; // Ïàðîëü äëÿ ïðîêñè
    property DirPath: string read fDirPath write fDirPath;  	                           // Äèðåêòîðèÿ â êîòîðîé áóäóò ïðîâåðÿòüñÿ MD5 ôàéëîâ
    property OnError: TErrorEvent read fOnError write fOnError;
    property OnAccepted: TNotifyEvent read fOnAccepted write fOnAccepted;
    property OnHeaders: THeadersEvent read fHeaders write fHeaders;
    property OnMD5Checked: TMD5Event read fMD5 write fMD5;
    property OnDownloading: TDownloadingEvent read fDownloading write fDownloading;
    property OnStartDownload: TNotifyEvent read fOnStartDownload write fOnStartDownload;
    property OnBreak: TNotifyEvent read fOnBreak write fOnBreak;
  end;

{$R IMDownloader.dcr}

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('IM-History', [TIMDownloader]);
end;

procedure TIMDownloadThread.toHeaders;
begin
  if Assigned(fHeaders) then
    fHeaders(Self, Headers);
end;

procedure TIMDownloadThread.toMD5;
begin
  if Assigned(fMD5) then
    fMD5(Self, MD5Correct, SizeCorrect, MD5Str);
end;

procedure TIMDownloadThread.toDownloading;
begin
  if Assigned(fDownloading) then
    fDownloading(Self, AcceptedSize, AllSize);
end;

procedure TIMDownloadThread.toAccepted;
begin
  if Assigned(fAccepted) then
    fAccepted(Self);
end;

procedure TIMDownloadThread.toBreak;
begin
  if Assigned(fBreak) then
    fBreak(Self);
end;

procedure TIMDownloadThread.Complete;
begin
  if Terminated then
    Synchronize(toBreak)
  else
    Synchronize(toAccepted);
end;

procedure TIMDownloadThread.toError;
begin
  if Assigned(fError) then
    OnError(Self, err);
end;

function TIMDownloadThread.ErrorResult(E: Boolean; eType: TIMDownloadError): Boolean;
begin
  Result := E;
  if E then
  begin
    err := eType;
    toError;
  end;
end;

function TIMDownloadThread.GetQueryInfo(hRequest: Pointer; Flag: Integer): String;
var
  Code: String;
  Size, Index: Cardinal;
begin
  SetLength(Code, 8); // Äîñòàòî÷íàÿ äëèíà äëÿ ÷òåíèÿ ñòàòóñ-êîäà
  Size := Length(Code);
  Index := 0;
  if HttpQueryInfo(hRequest, Flag ,PChar(Code), Size, Index) then
    Result := Code
  else
  if GetLastError = ERROR_INSUFFICIENT_BUFFER then // Óâåëè÷èâàåì áóôôåð
    begin
      SetLength(Code, Size);
      Size := Length(Code);
      if HttpQueryInfo(hRequest, Flag, PChar(Code), Size, Index) then
        Result := Code;
    end
  else
  begin
    //FErrorCode := GetLastError;
    Result := '';
  end;
end;

procedure TIMDownloadThread.Execute;
var
  Buffer: Array [0 .. 1024] of Byte;
  BytesRead: Cardinal;
  FSession, FConnect, FRequest: hInternet;
  dwBuffer: array [0 .. 1024] of Byte;
  dwBufferLen, dwIndex: DWORD;
  FHost, FScript, SRequest, ARequest: String;
  ProxyReqRes, ProxyReqLen: Cardinal;
  TempHeaders, TempMD5, DownloadsFileName, DownloadsFileMD5: String;

 function DelHttp(sURL: String): String;
 var
   HttpPos: Integer;
 begin
   HttpPos := Pos('http://', sURL);
   if HttpPos > 0 then Delete(sURL, HttpPos, 7);
   Result := Copy(sURL, 1, Pos('/', sURL) - 1);
   if Result = '' then Result := sURL;
 end;

 function ParseHeadersMD5andSize(HeaderStr: String): String;
 var
   HeadersStrList: TStringList;
   I: Integer;
   Size: String;
   Ch: Char;
   ResultFilename, ResultMD5Sum, ResultHeaders: String;
   ResultFileSize: Integer;
 begin
   ResultFilename := 'Test';
   ResultMD5Sum := '00000000000000000000000000000000';
   ResultFileSize := 0;
   // Ñîçäàåì TStringList
   HeadersStrList := TStringList.Create;
   HeadersStrList.Clear;
   HeadersStrList.Text := HeaderStr;
   HeadersStrList.Delete(HeadersStrList.Count-1); // Ïîñëåäíèé ýëåìåíò ñîäåðæèò âñåãäà CRLF
   if HeadersStrList.Count > 0 then
   begin
     for I := 0 to HeadersStrList.Count - 1 do
     begin
       // Ïàðñèì ñòðîêó âèäà
       // Content-Disposition: attachment; filename="ÈÌß-ÔÀÉËÀ"
       // Òàêóþ ñòðîêó âñòàâëÿåò â çàãîëîâîê HTTP-çàïðîñà
       // òîëüêî ìîé ñêðèïò get.php
       if pos('content-disposition', LowerCase(HeadersStrList[I])) > 0 then
       begin
         ResultFilename := HeadersStrList[I];
         Delete(ResultFilename, 1, Pos('"', HeadersStrList[I]));
         Delete(ResultFilename, Length(ResultFilename),1);
         //LogMemo.Lines.Add('Filename: '+ResultFilename);
       end;
       // Ïàðñèì ñòðîêó âèäà
       // Content-MD5Sum: MD5
       // Òàêóþ ñòðîêó âñòàâëÿåò â çàãîëîâîê HTTP-çàïðîñà
       // òîëüêî ìîé ñêðèïò get.php
       if pos('content-md5sum', LowerCase(HeadersStrList[I])) > 0 then
       begin
         ResultMD5Sum := HeadersStrList[I];
         Delete(ResultMD5Sum, 1, Pos(':', HeadersStrList[I]));
         Delete(ResultMD5Sum, 1,1);
       end;
       // Ïàðñèì ñòðîêó âèäà
       // Content-Length: ÐÀÇÌÅÐ
       if pos('content-length', LowerCase(HeadersStrList[i])) > 0 then
       begin
         Size := '';
         for Ch in HeadersStrList[I]do
           if Ch in ['0'..'9'] then
             Size := Size + Ch;
         ResultFileSize := StrToIntDef(Size,-1);
       end;
     end;
     Result := ResultFilename + '|' + LowerCase(ResultMD5Sum) + '|' + IntToStr(ResultFileSize) + '|';
   end;
   HeadersStrList.Free;
 end;

 { Ôóíêöèÿ ðàçáèâàåò ñòðîêó S íà ñëîâà, ðàçäåëåííûå ñèìâîëàìè-ðàçäåëèòåëÿìè,
 óêàçàííûìè â ñòðîêå Sep. Ôóíêöèÿ âîçâðàùàåò ïåðâîå íàéäåííîå ñëîâî, ïðè
 ýòîì èç ñòðîêè S óäàëÿåòñÿ íà÷àëüíàÿ ÷àñòü äî ñëåäóþùåãî ñëîâà }
 function Tok(Sep: String; var S: String): String;

   function isoneof(c, s: string): Boolean;
   var
     iTmp: integer;
   begin
     Result := False;
     for iTmp := 1 to Length(s) do
     begin
       if c = Copy(s, iTmp, 1) then
       begin
         Result := True;
         Exit;
       end;
     end;
   end;

 var
   c, t: String;
 begin
   if s = '' then
   begin
     Result := s;
     Exit;
   end;
   c := Copy(s, 1, 1);
   while isoneof(c, sep) do
   begin
     s := Copy(s, 2, Length(s) - 1);
     c := Copy(s, 1, 1);
   end;
   t := '';
   while (not isoneof(c, sep)) and (s <> '') do
   begin
     t := t + c;
     s := Copy(s, 2, length(s) - 1);
     c := Copy(s, 1, 1);
   end;
   Result := t;
 end;

begin
  // Èíèöèàëèçèðóåì WinInet
  if fProxy = '' then
    FSession := InternetOpen('IM-History Download Master', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0)
  else
  begin
    FSession := InternetOpen('IM-History Download Master', INTERNET_OPEN_TYPE_PROXY, PChar(fProxy), PChar(fProxyBypass), 0);
    if fProxyAuthUserName <> '' then
    begin
      InternetSetOption(FSession, INTERNET_OPTION_PROXY_USERNAME, @fProxyAuthUserName, Length(fProxyAuthUserName));
      InternetSetOption(FSession, INTERNET_OPTION_PROXY_PASSWORD, @fProxyAuthPassword, Length(fProxyAuthPassword));
    end;
  end;
  if ErrorResult(FSession = nil, deInternetOpen) then
    Exit;
  if Assigned(FSession) then
  begin
    // Íåáîëüøîé ïàðñèíã
    // Âûòàñêèâàåì èìÿ õîñòà è ïàðàìåòðû îáðàùåíèÿ ê ñêðèïòó
    ARequest := fURL;
    FHost := DelHttp(ARequest);
    FScript := ARequest;
    Delete(FScript, 1, Pos(FHost, FScript) + Length(FHost));
    // Ïîïûòêà ñîåäèíåíèÿ ñ ñåðâåðîì
    if fAuthUserName = '' then // Åñëè íåò Basic-àâòîðèçàöèè
      FConnect := InternetOpenURL(FSession, PChar(fURL), nil, 0, INTERNET_FLAG_RELOAD, 0)
    else
      FConnect := InternetConnect(FSession, PChar(FHost), INTERNET_DEFAULT_HTTP_PORT, PChar(fAuthUserName),
                  PChar(fAuthPassword), INTERNET_SERVICE_HTTP, 0, 0);
    if ErrorResult(FConnect = nil, deInternetOpenUrl) then
      Exit;
    dwIndex := 0;
    dwBufferLen := Length(dwBuffer);
    if fProxy <> '' then
    begin
      // Ïîäãîòàâëèâàåì çàïðîñ
      FRequest := HttpOpenRequest(FConnect, 'GET', PChar(FScript), nil, '', nil, 0, 0);
      // Äîáàâëÿåì íåîáõîäèìûå çàãîëîâêè ê çàïðîñó
      HttpAddRequestHeaders(FRequest, Accept, Length(Accept), HTTP_ADDREQ_FLAG_ADD);
      HttpAddRequestHeaders(FRequest, ProxyConnection, Length(ProxyConnection), HTTP_ADDREQ_FLAG_ADD);
      HttpAddRequestHeaders(FRequest, Lang, Length(Lang), HTTP_ADDREQ_FLAG_ADD);
      HttpAddRequestHeaders(FRequest, Agent, Length(Agent), HTTP_ADDREQ_FLAG_ADD);
      // Ïðîâåðÿåì çàïðîñ:
      ProxyReqLen := 0;
      ProxyReqRes := 0;
      SRequest := ' ';
      HttpQueryInfo(FRequest, HTTP_QUERY_RAW_HEADERS_CRLF or
        HTTP_QUERY_FLAG_REQUEST_HEADERS, @SRequest[1], ProxyReqLen, ProxyReqRes);
      if ProxyReqLen > 0 then
      begin
        SetLength(SRequest, ProxyReqLen);
        HttpQueryInfo(FRequest, HTTP_QUERY_RAW_HEADERS_CRLF or
          HTTP_QUERY_FLAG_REQUEST_HEADERS, @SRequest[1], ProxyReqLen, ProxyReqRes);
      end;
      // Îòïðàâëÿåì çàïðîñ
      if ErrorResult(not HttpSendRequest(FRequest, nil, 0, nil, 0), deRequest) then Exit;
    end;
    if fProxy = '' then
    begin
      // Ïîëó÷àåì çàãîëîâîê îòâåòà ñ ñåðâåðà
      Headers := GetQueryInfo(FConnect, HTTP_QUERY_RAW_HEADERS_CRLF);
      Synchronize(toHeaders);
      // Çàïðîñ ðàçìåðà
      if HttpQueryInfo(FConnect, HTTP_QUERY_CONTENT_LENGTH, @dwBuffer, dwBufferLen, dwIndex) then
        AllSize := StrToInt('0' + PChar(@dwBuffer));
    end
    else
    begin
      // Ïîëó÷àåì çàãîëîâîê îòâåòà ñ ñåðâåðà
      Headers := GetQueryInfo(FRequest, HTTP_QUERY_RAW_HEADERS_CRLF);
      Synchronize(toHeaders);
      // Çàïðîñ ðàçìåðà
      if HttpQueryInfo(FRequest, HTTP_QUERY_CONTENT_LENGTH, @dwBuffer, dwBufferLen, dwIndex) then
        AllSize := StrToInt('0' + PChar(@dwBuffer));
    end;
    // Ïðîâåðÿåì MD5 ñòàðîãî ôàéëà íà äèñêå
    TempHeaders := ParseHeadersMD5andSize(Headers);
    DownloadsFileName := Tok('|', TempHeaders);
    DownloadsFileMD5 := Tok('|', TempHeaders);
    if FileExists(fDirPath+DownloadsFileName) then
      TempMD5 := LowerCase(MD5DigestToStr(MD5File(fDirPath+DownloadsFileName)))
    else
      TempMD5 := '00000000000000000000000000000000';
    if LowerCase(DownloadsFileMD5) <> TempMD5 then
    begin
      repeat
        if Terminated then
          Break;
        FillChar(Buffer, SizeOf(Buffer), 0);
        if fProxy = '' then
        begin
          if ErrorResult(not InternetReadFile(FConnect, @Buffer, Length(Buffer), BytesRead), deDownloadingFile) then
            Exit
          else
            MemoryStream.Write(Buffer, BytesRead);
        end
        else
        begin
          if ErrorResult(not InternetReadFile(FRequest, @Buffer, Length(Buffer), BytesRead), deDownloadingFile) then
            Exit
          else
            MemoryStream.Write(Buffer, BytesRead);
        end;
        AcceptedSize := MemoryStream.Size;
        Synchronize(toDownloading);
      until (BytesRead = 0);
      MemoryStream.Position := 0;
      // Ïîäñ÷åò MD5 è ðàçìåðà ôàéëà
      MD5Str := LowerCase(MD5DigestToStr(MD5Stream(MemoryStream)));
      TempHeaders := ParseHeadersMD5andSize(Headers);
      DownloadsFileName := Tok('|', TempHeaders);
      if Tok('|', TempHeaders) = MD5Str then
        MD5Correct := True
      else
        MD5Correct := False;
      if Tok('|', TempHeaders) = IntToStr(MemoryStream.Size) then
        SizeCorrect := True
      else
        SizeCorrect := False;
      Synchronize(toMD5);
    end
    else
    begin
      AcceptedSize := 0;
      Synchronize(toDownloading);
      MD5Str := 'FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF';
      MD5Correct := True;
      SizeCorrect := True;
      Synchronize(toMD5);
    end;
    // Î÷èùàåì ðåñóðñû
    if Assigned(FRequest) then
      InternetCloseHandle(FRequest);
    if Assigned(FConnect) then
      InternetCloseHandle(FConnect);
    InternetCloseHandle(FSession);
    Pointer(MemoryStream) := nil;
    Complete;
  end;
end;

constructor TIMDownloadThread.Create(CreateSuspennded: Boolean; const URL, Proxy, ProxyBypass, AuthUserName, AuthPassword, ProxyAuthUserName, ProxyAuthPassword, DirPath: String; Stream: PMemoryStream);
begin
  inherited Create(CreateSuspennded);
  FreeOnTerminate := True;
  Pointer(MemoryStream) := Stream;
  AcceptedSize := 0;
  Headers := '';
  MD5Str := '';
  MD5Correct := False;
  SizeCorrect := False;
  fURL := URL;
  fProxy := Proxy;
  fProxyBypass := ProxyBypass;
  fAuthUserName := AuthUserName;
  fAuthPassword := AuthPassword;
  fProxyAuthUserName := ProxyAuthUserName;
  fProxyAuthPassword := ProxyAuthPassword;
  fDirPath := DirPath;
end;

procedure TIMDownloader.Download;
begin
  fInDowloading := True;
  if Assigned(Downloader) then
    Downloader.Terminate;
  if Assigned(fOutStream) then
    FreeAndNil(fOutStream);
  fAcceptedSize := 0;
  fMyHeaders := '';
  fMyMD5Str := '';
  fMyMD5Correct := False;
  fMySizeCorrect := False;
  fOutStream := TMemoryStream.Create;
  Downloader := TIMDownloadThread.Create(True, fURL, fProxy, fProxyBypass, fAuthUserName, fAuthPassword, fProxyAuthUserName, fProxyAuthPassword, fDirPath, Pointer(fOutStream));
  Downloader.OnAccepted := AcceptDownload;
  Downloader.OnError := ErrorDownload;
  Downloader.OnHeaders := GetHeaders;
  Downloader.OnDownloading := Downloading;
  Downloader.OnBreak := Break_Download;
  Downloader.OnMD5Checked := GetMD5;
  Downloader.Resume;
  if Assigned(fOnStartDownload) then
    fOnStartDownload(Self);
end;

procedure TIMDownloader.BreakDownload;
begin
  if not InDowloading then
    Exit;
  if Assigned(Downloader) then
    Downloader.Terminate;
end;

procedure TIMDownloader.Break_Download(Sender: TObject);
begin
  fInDowloading := False;
  Downloader := nil;
  if Assigned(fOnBreak) then
    fOnBreak(Self);
end;

procedure TIMDownloader.AcceptDownload(Sender: TObject);
begin
  fInDowloading := False;
  Downloader := nil;
  if Assigned(fOnAccepted) then
    fOnAccepted(Self);
end;

procedure TIMDownloader.GetHeaders(Sender: TObject; Headers: String);
begin
  fMyHeaders := Headers;
  if Assigned(fHeaders) then
    fHeaders(Self, Headers);
end;

procedure TIMDownloader.GetMD5(Sender: TObject; MD5Correct, SizeCorrect: Boolean; MD5Str: String);
begin
  fMyMD5Str := MD5Str;
  fMyMD5Correct := MD5Correct;
  fMySizeCorrect := SizeCorrect;
  if Assigned(fMD5) then
    fMD5(Self, MD5Correct, SizeCorrect, MD5Str);
end;

procedure TIMDownloader.Downloading(Sender: TObject; AcceptedSize, MaxSize: Cardinal);
begin
  fAcceptedSize := AcceptedSize;
  if Assigned(fDownloading) then
    fDownloading(Self, AcceptedSize, MaxSize);
end;

procedure TIMDownloader.ErrorDownload(Sender: TObject; Error: TIMDownloadError);
begin
  fInDowloading := False;
  Downloader := nil;
  fOutStream := nil;
  if Assigned(fOnError) then
    fOnError(Self, Error);
end;

end.