File: opkman_downloader.pas

package info (click to toggle)
lazarus 2.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 214,460 kB
  • sloc: pascal: 1,862,622; xml: 265,709; cpp: 56,595; sh: 3,008; java: 609; makefile: 535; perl: 297; sql: 222; ansic: 137
file content (733 lines) | stat: -rw-r--r-- 25,515 bytes parent folder | download | duplicates (2)
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
 {
 ***************************************************************************
 *                                                                         *
 *   This source is free software; you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This code is distributed in the hope that it will be useful, but      *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   General Public License for more details.                              *
 *                                                                         *
 *   A copy of the GNU General Public License is available on the World    *
 *   Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also      *
 *   obtain it by writing to the Free Software Foundation,                 *
 *   Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA.   *
 *                                                                         *
 ***************************************************************************

 Author: Balázs Székely
 Abstract:
   Implementation of the package downloader class.
}
unit opkman_downloader;

{$mode objfpc}{$H+}

{$INCLUDE opkman_fpcdef.inc}

interface

uses
  Classes, SysUtils, fpjson, LazIDEIntf,
  // OpkMan
  opkman_timer, opkman_common, opkman_serializablepackages, opkman_const, opkman_options,
  {$IFDEF FPC311}fphttpclient{$ELSE}opkman_httpclient{$ENDIF};

type
  TDownloadType = (dtJSON, dtPackage, dtUpdate);
  TErrorType = (etNone, etConfig, etTimeOut, etHTTPClient);
  TOnTimer = TNotifyEvent;
  TOnJSONProgress = TNotifyEvent;
  TOnJSONDownloadCompleted = procedure(Sender: TObject; AJSON: TJSONStringType; AErrTyp: TErrorType; const AErrMsg: String = '') of object;
  TOnWriteStream = procedure(Sender: TObject; APos: Int64) of object;
  TOnPackageDownloadProgress = procedure(Sender: TObject; AFrom, ATo: String; ACnt, ATotCnt: Integer; ACurPos, ACurSize, ATotPos, ATotSize: Int64;
    AElapsed, ARemaining, ASpeed: LongInt) of object;
  TOnPackageDownloadError = procedure(Sender: TObject; APackageName: String; const AErrMsg: String = '') of object;
  TOnPackageDownloadCompleted = TNotifyEvent;
  TOnPackageUpdateProgress = procedure(Sender: TObject; AUPackageName, AUPackageURL: String; ACnt, ATotCnt: Integer; AUTyp: Integer; AUErrMsg: String) of object;
  TOnPackageUpdateCompleted = procedure(Sender: TObject; AUSuccess: Boolean) of object;

  { TDownloadStream }

  TDownloadStream = class(TStream)
  private
    FOnWriteStream: TOnWriteStream;
    FStream: TStream;
  public
    constructor Create(AStream: TStream);
    destructor Destroy; override;
    function Read(var Buffer; Count: LongInt): LongInt; override;
    function Write(const Buffer; Count: LongInt): LongInt; override;
    function Seek(Offset: LongInt; Origin: Word): LongInt; override;
    procedure DoProgress;
  published
    property OnWriteStream: TOnWriteStream read FOnWriteStream write FOnWriteStream;
  end;

  { TThreadDownload }

  TThreadDownload = class(TThread)
  private
    FHTTPClient: TFPHTTPClient;
    FOnJSONComplete: TOnJSONDownloadCompleted;
    FOnJSONProgress: TNotifyEvent;
    FRemoteJSONFile: String;
    FErrMsg: String;
    FDownloadType: TDownloadType;
    FErrTyp: TErrorType;
    FMS: TMemoryStream;
    FFrom: String;
    FTo: String;
    FCnt: Integer;
    FTotCnt: Integer;
    FCurPos: Int64;
    FCurSize: Int64;
    FTotPos: Int64;
    FTotPosTmp: Int64;
    FTotSize: Int64;
    FElapsed: Integer;
    FRemaining: Integer;
    FSpeed: Integer;
    FTimer: TThreadTimer;
    FNeedToBreak: Boolean;
    FDownloadTo: String;
    FUPackageName: String;
    FUPackageURL: String;
    FUTyp: Integer;
    FUErrMsg: String;
    FUSuccess: Boolean;
    FSilent: Boolean;
    FOnPackageDownloadProgress: TOnPackageDownloadProgress;
    FOnPackageDownloadError: TOnPackageDownloadError;
    FOnPackageDownloadCompleted: TOnPackageDownloadCompleted;
    FOnPackageUpdateProgress: TOnPackageUpdateProgress;
    FOnPackageUpdateCompleted: TOnPackageUpdateCompleted;
    function GetUpdateSize(const AURL: String; var AErrMsg: String): Int64;
    procedure DoReceivedUpdateSize(Sender: TObject; const ContentLength, {%H-}CurrentPos: int64);
    procedure DoOnTimer(Sender: TObject);
    procedure DoOnJSONProgress;
    procedure DoOnJSONDownloadCompleted;
    procedure DoOnWriteStream(Sender: TObject; APos: Int64);
    procedure DoOnPackageDownloadProgress;
    procedure DoOnPackageDownloadError;
    procedure DoOnPackageDownloadCompleted;
    procedure DoOnPackageUpdateProgress;
    procedure DoOnPackageUpdateCompleted;
  protected
    procedure Execute; override;
  public
    constructor Create;
    destructor Destroy; override;
    procedure DownloadJSON(const ATimeOut: Integer = -1; const ASilent: Boolean = False);
    procedure DownloadPackages(const ADownloadTo: String);
    procedure UpdatePackages(const ADownloadTo: String);
  published
    property OnJSONProgress: TNotifyEvent read FOnJSONProgress write FOnJSONProgress;
    property OnJSONDownloadCompleted: TOnJSONDownloadCompleted read FOnJSONComplete write FOnJSONComplete;
    property OnPackageDownloadCompleted: TOnPackageDownloadCompleted read FOnPackageDownloadCompleted write FOnPackageDownloadCompleted;
    property OnPackageDownloadError: TOnPackageDownloadError read FOnPackageDownloadError write FOnPackageDownloadError;
    property OnPackageDownloadProgress: TOnPackageDownloadProgress read FOnPackageDownloadProgress write FOnPackageDownloadProgress;
    property OnPackageUpdateProgress: TOnPackageUpdateProgress read FOnPackageUpdateProgress write FOnPackageUpdateProgress;
    property OnPackageUpdateCompleted: TOnPackageUpdateCompleted read FOnPackageUpdateCompleted write FOnPackageUpdateCompleted;
    property NeedToBreak: Boolean read FNeedToBreak write FNeedToBreak;
  end;

  { TPackageDownloader }

  TPackageDownloader = class
  private
    FJSON: TJSONStringType;
    FDownload: TThreadDownload;
    FRemoteRepository: String;
    FLastError: String;
    FDownloadingJSON: Boolean;
    FSilent: Boolean;
    FOnJSONProgress: TNotifyEvent;
    FOnJSONDownloadCompleted: TOnJSONDownloadCompleted;
    FOnPackageDownloadProgress: TOnPackageDownloadProgress;
    FOnPackageDownloadError: TOnPackageDownloadError;
    FOnPackageDownloadCompleted: TOnPackageDownloadCompleted;
    FOnPackageUpdateProgress: TOnPackageUpdateProgress;
    FOnPackageUpdateCompleted: TOnPackageUpdateCompleted;
    procedure DoOnJSONProgress(Sender: TObject);
    procedure DoOnJSONDownloadCompleted(Sender: TObject; AJSON: TJSONStringType; AErrTyp: TErrorType; const AErrMsg: String = '');
    procedure DoOnPackageDownloadProgress(Sender: TObject; AFrom, ATo: String; ACnt, ATotCnt: Integer;
      ACurPos, ACurSize, ATotPos, ATotSize: Int64; AElapsed, ARemaining, ASpeed: LongInt);
    procedure DoOnPackageDownloadError(Sender: TObject; APackageName: String; const AErrMsg: String = '');
    procedure DoOnPackageDownloadCompleted(Sender: TObject);
    procedure DoOnPackageUpdateProgress(Sender: TObject; AUPackageName, AUPackageURL: String; ACnt, ATotCnt: Integer; AUTyp: Integer; AUErrMsg: String);
    procedure DoOnPackageUpdateCompleted(Sender: TObject; AUSuccess: Boolean);
  public
    constructor Create(const ARemoteRepository: String);
    destructor Destroy; override;
    procedure DownloadJSON(const ATimeOut: Integer = -1; const ASilent: Boolean = False);
    procedure DownloadPackages(const ADownloadTo: String);
    procedure UpdatePackages(const ADownloadTo: String);
    procedure Cancel;
  published
    property RemoteRepository: String read FRemoteRepository write FRemoteRepository;
    property LastError: String read FLastError write FLastError;
    property DownloadingJSON: Boolean read FDownloadingJSON;
    property JSON: TJSONStringType read FJSON;
    property OnJSONProgress: TNotifyEvent read FOnJSONProgress write FOnJSONProgress;
    property OnJSONDownloadCompleted: TOnJSONDownloadCompleted read FOnJSONDownloadCompleted write FOnJSONDownloadCompleted;
    property OnPackageDownloadProgress: TOnPackageDownloadProgress read FOnPackageDownloadProgress write FOnPackageDownloadProgress;
    property OnPackageDownloadError: TOnPackageDownloadError read FOnPackageDownloadError write FOnPackageDownloadError;
    property OnPackageDownloadCompleted: TOnPackageDownloadCompleted read FOnPackageDownloadCompleted write FOnPackageDownloadCompleted;
    property OnPackageUpdateProgress: TOnPackageUpdateProgress read FOnPackageUpdateProgress write FOnPackageUpdateProgress;
    property OnPackageUpdateCompleted: TOnPackageUpdateCompleted read FOnPackageUpdateCompleted write FOnPackageUpdateCompleted;
  end;

var
  PackageDownloader: TPackageDownloader = nil;

implementation

{ TDownloadStream }
constructor TDownloadStream.Create(AStream: TStream);
begin
  inherited Create;
  FStream := AStream;
  FStream.Position := 0;
end;

destructor TDownloadStream.Destroy;
begin
  FStream.Free;
  inherited Destroy;
end;

function TDownloadStream.Read(var Buffer; Count: LongInt): LongInt;
begin
  Result := FStream.Read(Buffer, Count);
end;

function TDownloadStream.Write(const Buffer; Count: LongInt): LongInt;
begin
  Result := FStream.Write(Buffer, Count);
  DoProgress;
end;

function TDownloadStream.Seek(Offset: LongInt; Origin: Word): LongInt;
begin
  Result := FStream.Seek(Offset, Origin);
end;

procedure TDownloadStream.DoProgress;
begin
  if Assigned(FOnWriteStream) then
    FOnWriteStream(Self, Self.Position);
end;

{ TThreadDownload }

procedure TThreadDownload.DoOnPackageDownloadProgress;
begin
  if Assigned(FOnPackageDownloadProgress) then
    FOnPackageDownloadProgress(Self, FFrom, FTo, FCnt, FTotCnt, FCurPos, FCurSize, FTotPosTmp, FTotSize, FElapsed, FRemaining, FSpeed);
end;

procedure TThreadDownload.DoOnPackageDownloadError;
begin
  if Assigned(FOnPackageDownloadError) then
    FOnPackageDownloadError(Self, ExtractFileName(FTo), FErrMsg);
end;

procedure TThreadDownload.DoOnPackageDownloadCompleted;
begin
  if Assigned(FOnPackageDownloadCompleted) then
    FOnPackageDownloadCompleted(Self);
end;

procedure TThreadDownload.DoOnPackageUpdateProgress;
begin
  if Assigned(FOnPackageUpdateProgress) then
    FOnPackageUpdateProgress(Self, FUPackageName, FUPackageURL, FCnt, FTotcnt, FUTyp, FUErrMsg);
end;

procedure TThreadDownload.DoOnPackageUpdateCompleted;
begin
  if Assigned(FOnPackageUpdateCompleted) then
    FOnPackageUpdateCompleted(Self, FUSuccess);
end;

procedure TThreadDownload.DoOnJSONDownloadCompleted;
var
  JSON: TJSONStringType;
begin
  if Assigned(FOnJSONComplete) then
  begin
    if (FErrTyp = etNone) or (FMS.Size > 0) then
    begin
      SetLength(JSON, FMS.Size);
      FMS.Read(Pointer(JSON)^, Length(JSON));
      SerializablePackages.JSONToPackages(JSON);
      FOnJSONComplete(Self, JSON, FErrTyp, '');
    end
    else
      FOnJSONComplete(Self, '', FErrTyp, FErrMsg);
  end;
end;

procedure TThreadDownload.DoOnTimer(Sender: TObject);
begin
  if FDownloadType = dtJSON then
  begin
    FHTTPClient.Terminate;
    FErrMsg := rsMainFrm_rsMessageError2;
    FErrTyp := etTimeOut;
    if Assigned(FTimer) then
      FTimer.StopTimer;
    TThreadTimer(Sender).Synchronize(@DoOnJSONDownloadCompleted);
    //Synchronize(@DoOnJSONDownloadCompleted);
    FOnJSONComplete := nil;
  end
  else if (FDownloadType = dtPackage) or (FDownloadType = dtUpdate) then
  begin
    Inc(FElapsed);
    FSpeed := Round(FTotPosTmp/FElapsed);
    if FSpeed > 0 then
      FRemaining := Round((FTotSize - FTotPosTmp)/FSpeed);
  end;
end;

procedure TThreadDownload.DoOnJSONProgress;
begin
  if FSilent then
    Exit;
  if Assigned(FOnJSONProgress) then
    FOnJSONProgress(Self);
end;

procedure TThreadDownload.DoOnWriteStream(Sender: TObject; APos: Int64);
begin
  FCurPos := APos;
  FTotPosTmp := FTotPos + APos;
  Synchronize(@DoOnPackageDownloadProgress);
  Sleep(5);
end;

procedure TThreadDownload.Execute;
var
  I: Integer;
  DS: TDownloadStream;
  UpdateSize: Int64;
  UpdCnt: Integer;
begin
  FErrMsg := '';
  FErrTyp := etNone;
  if FDownloadType = dtJSON then //JSON
  begin
    Synchronize(@DoOnJSONProgress);
    if FRemoteJSONFile <> cRemoteJSONFile then
    begin
      try
        FHTTPClient.Get(FRemoteJSONFile, FMS);
        if FMS.Size > 0 then
          FMS.Position := 0;
      except
        on E: Exception do
        begin
          FErrMsg := E.Message;
          FErrTyp := etHTTPClient;
        end;
      end;
    end
    else
    begin
      FErrTyp := etConfig;
      FErrMsg := rsMainFrm_rsMessageNoRepository0;
    end;
    if Assigned(FTimer) and FTimer.Enabled then
      FTimer.StopTimer;
    Synchronize(@DoOnJSONDownloadCompleted);
  end
  else if FDownloadType = dtPackage then //download from repository
  begin
    FCnt := 0;
    for I := 0 to SerializablePackages.Count - 1 do
    begin
      if NeedToBreak then
        Break;
      if SerializablePackages.Items[I].IsDownloadable then
      begin
        Inc(FCnt);
        FFrom := Options.RemoteRepository[Options.ActiveRepositoryIndex] + SerializablePackages.Items[I].RepositoryFileName;
        FTo := FDownloadTo + SerializablePackages.Items[I].RepositoryFileName;
        FCurSize := SerializablePackages.Items[I].RepositoryFileSize;
        DS := TDownloadStream.Create(TFileStream.Create(FTo, fmCreate));
        try
          DS.FOnWriteStream := @DoOnWriteStream;
          try
            FHTTPClient.HTTPMethod('GET', FFrom, DS, [200]);
            SerializablePackages.Items[I].ChangePackageStates(ctAdd, psDownloaded);
          except
            on E: Exception do
            begin
              FErrMsg := E.Message;
              FErrTyp := etHTTPClient;
              SerializablePackages.Items[I].ChangePackageStates(ctRemove, psDownloaded);
              SerializablePackages.Items[I].ChangePackageStates(ctAdd, psError);
              Synchronize(@DoOnPackageDownloadError);
            end;
          end;
        finally
          DS.Free
        end;
        if psError in  SerializablePackages.Items[I].PackageStates then
          DeleteFile(FTo);
        FTotPos := FTotPos + FCurSize;
      end;
    end;
    if (FNeedToBreak) then
      DeleteFile(FTo)
    else
      Synchronize(@DoOnPackageDownloadCompleted);
  end
  else if FDownloadType = dtUpdate then //download from external link
  begin
    FCnt := 0;
    UpdCnt := 0;
    for I := 0 to SerializablePackages.Count - 1 do
    begin
      if FNeedToBreak then
        Break;
      if (SerializablePackages.Items[I].Checked) and (Trim(SerializablePackages.Items[I].DownloadZipURL) <> '') then
      begin
        Inc(FCnt);
        FUpackageName := SerializablePackages.Items[I].Name;
        FUPackageURL := SerializablePackages.Items[I].DownloadZipURL;
        FUTyp := 0;
        Synchronize(@DoOnPackageUpdateProgress);
        UpdateSize := GetUpdateSize(SerializablePackages.Items[I].DownloadZipURL, FUErrMsg);
        if UpdateSize > -1 then
        begin
          if UpdateSize = 0 then
            UpdateSize := SerializablePackages.Items[I].RepositoryFileSize;
          FUTyp := 1;
          Synchronize(@DoOnPackageUpdateProgress);
          Inc(UpdCnt);
          SerializablePackages.Items[I].UpdateSize := UpdateSize;
          FTotSize := FTotSize + UpdateSize;
        end
        else
        begin
          FUTyp := 2;
          Synchronize(@DoOnPackageUpdateProgress);
          SerializablePackages.Items[I].UpdateSize := -1;
          SerializablePackages.Items[I].ChangePackageStates(ctAdd, psError);
        end;
      end;
    end;
    if FNeedToBreak then
      Exit;
    if (UpdCnt = 0) then
    begin
      FUSuccess := False;
      Synchronize(@DoOnPackageUpdateCompleted);
    end
    else
    begin
      FUSuccess := True;
      Synchronize(@DoOnPackageUpdateCompleted);
      if Assigned(FTimer) then
        FTimer.Enabled := True;
      FCnt := 0;
      FTotCnt := UpdCnt;
      for I := 0 to SerializablePackages.Count - 1 do
      begin
        if NeedToBreak then
          Break;
        if (SerializablePackages.Items[I].Checked) and (Trim(SerializablePackages.Items[I].DownloadZipURL) <> '') and
           (SerializablePackages.Items[I].UpdateSize > -1) and (not (psError in  SerializablePackages.Items[I].PackageStates)) then
        begin
          Inc(FCnt);
          FFrom := FixProtocol(SerializablePackages.Items[I].DownloadZipURL);
          FTo := FDownloadTo + SerializablePackages.Items[I].RepositoryFileName;
          FCurSize := SerializablePackages.Items[I].UpdateSize;
          DS := TDownloadStream.Create(TFileStream.Create(FTo, fmCreate));
          try
            DS.FOnWriteStream := @DoOnWriteStream;
            try
              FHTTPClient.AllowRedirect := True;
              FHTTPClient.HTTPMethod('GET', FFrom, DS, []);
            except
            end;
            if FHTTPClient.ResponseStatusCode <> 200 then
            begin
              FErrMsg := IntToStr(FHTTPClient.ResponseStatusCode);
              FErrTyp := etHTTPClient;
              SerializablePackages.Items[I].ChangePackageStates(ctRemove, psDownloaded);
              SerializablePackages.Items[I].ChangePackageStates(ctAdd, psError);
              Synchronize(@DoOnPackageDownloadError);
            end
            else
              SerializablePackages.Items[I].ChangePackageStates(ctAdd, psDownloaded);
          finally
            DS.Free
          end;
          if psError in  SerializablePackages.Items[I].PackageStates then
            DeleteFile(FTo);
          FTotPos := FTotPos + FCurSize;
        end;
      end;
      if (FNeedToBreak) then
        DeleteFile(FTo)
      else
        Synchronize(@DoOnPackageDownloadCompleted);
    end;
  end;
end;

constructor TThreadDownload.Create;
begin
  inherited Create(True);
  FreeOnTerminate := True;
  FTimer := nil;
  FMS := TMemoryStream.Create;
  FHTTPClient := TFPHTTPClient.Create(nil);
  if Options.ProxyEnabled then
  begin
    FHTTPClient.Proxy.Host:= Options.ProxyServer;
    FHTTPClient.Proxy.Port:= Options.ProxyPort;
    FHTTPClient.Proxy.UserName:= Options.ProxyUser;
    FHTTPClient.Proxy.Password:= Options.ProxyPassword;
  end;
end;

destructor TThreadDownload.Destroy;
begin
  if Assigned(FTimer) then
  begin
    if FTimer.Enabled then
      FTimer.StopTimer;
    FTimer.Terminate;
  end;
  FHTTPClient.Free;
  FMS.Free;
  inherited Destroy;
end;

procedure TThreadDownload.DownloadJSON(const ATimeOut: Integer = -1;
  const ASilent: Boolean = False);
begin
  FRemoteJSONFile := Options.RemoteRepository[Options.ActiveRepositoryIndex] + cRemoteJSONFile;
  FDownloadType := dtJSON;
  FSilent := ASilent;
  if (Assigned(LazarusIDE) and LazarusIDE.IDEStarted and (not LazarusIDE.IDEIsClosing)) then
  begin
    FTimer := TThreadTimer.Create;
    FTimer.Interval := ATimeOut;
    FTimer.OnTimer := @DoOnTimer;
    FTimer.StartTimer;
    Start;
  end;
end;

procedure TThreadDownload.DownloadPackages(const ADownloadTo: String);
var
  I: Integer;
begin
  FDownloadType := dtPackage;
  FDownloadTo := ADownloadTo;
  FTotCnt := 0;
  FTotSize := 0;
  for I := 0 to SerializablePackages.Count - 1 do
  begin
    if SerializablePackages.Items[I].IsDownloadable then
    begin
      Inc(FTotCnt);
      FTotSize := FTotSize + SerializablePackages.Items[I].RepositoryFileSize;
    end;
  end;
  if (Assigned(LazarusIDE) and LazarusIDE.IDEStarted and (not LazarusIDE.IDEIsClosing)) then
  begin
    FTimer := TThreadTimer.Create;
    FTimer.OnTimer := @DoOnTimer;
    FTimer.StartTimer;
    Start;
  end;
end;

procedure TThreadDownload.DoReceivedUpdateSize(Sender: TObject;
  const ContentLength, CurrentPos: int64);
begin
  if ContentLength > 0 then
    Abort;
end;

function TThreadDownload.GetUpdateSize(const AURL: String; var AErrMsg: String): Int64;
var
  SS: TStringStream;
  HttpClient: TFPHTTPClient;
  URL: String;
begin
  Result := -1;
  AErrMsg := '';
  SS := TStringStream.Create('');
  try
    URL := FixProtocol(AURL);
    HttpClient := TFPHTTPClient.Create(nil);
    if Options.ProxyEnabled then
      begin
        HTTPClient.Proxy.Host:= Options.ProxyServer;
        HTTPClient.Proxy.Port:= Options.ProxyPort;
        HTTPClient.Proxy.UserName:= Options.ProxyUser;
        HTTPClient.Proxy.Password:= Options.ProxyPassword;
      end;

    try
      HttpClient.OnDataReceived := @DoReceivedUpdateSize;
      HttpClient.AllowRedirect := True;
      HttpClient.ResponseHeaders.NameValueSeparator := ':';
      try
        HttpClient.HTTPMethod('GET', URL, SS, []);
      except
      end;
      if HttpClient.ResponseStatusCode = 200 then
        Result := StrToIntDef(HttpClient.ResponseHeaders.Values['CONTENT-LENGTH'], 0)
      else
        AErrMsg := 'Error code: ' + IntToStr(HttpClient.ResponseStatusCode);
    finally
      HttpClient.Free;
    end;
  finally
    SS.Free
  end;
end;

procedure TThreadDownload.UpdatePackages(const ADownloadTo: String);
var
  I: Integer;
begin
  FDownloadTo := ADownloadTo;
  FDownloadType := dtUpdate;
  FTotCnt := 0;
  FTotSize := 0;
  for I := 0 to SerializablePackages.Count - 1 do
    if (SerializablePackages.Items[I].Checked) and (Trim(SerializablePackages.Items[I].DownloadZipURL) <> '') then
      Inc(FTotCnt);
  if (Assigned(LazarusIDE) and LazarusIDE.IDEStarted and (not LazarusIDE.IDEIsClosing)) then
  begin
    FTimer := TThreadTimer.Create;
    FTimer.OnTimer := @DoOnTimer;
    FTimer.StartTimer;
    FTimer.Enabled := False;
    Start;
  end;
end;

{ TPackageDownloader}

procedure TPackageDownloader.DoOnPackageDownloadProgress(Sender: TObject; AFrom, ATo: String;
  ACnt, ATotCnt: Integer; ACurPos, ACurSize, ATotPos, ATotSize: Int64;
  AElapsed, ARemaining, ASpeed: LongInt);
begin
  if Assigned(FOnPackageDownloadProgress) then
    FOnPackageDownloadProgress(Self, AFrom, ATo, ACnt, ATotCnt, ACurPos, ACurSize, ATotPos, ATotSize, AElapsed, ARemaining, ASpeed);
end;

procedure TPackageDownloader.DoOnPackageDownloadError(Sender: TObject;
  APackageName: String; const AErrMsg: String);
begin
  if Assigned(FOnPackageDownloadError) then
    FOnPackageDownloadError(Self, APackageName, AErrMsg);
end;

procedure TPackageDownloader.DoOnPackageDownloadCompleted(Sender: TObject);
begin
  if Assigned(FOnPackageDownloadCompleted) then
    FOnPackageDownloadCompleted(Sender);
end;

procedure TPackageDownloader.DoOnPackageUpdateProgress(Sender: TObject; AUPackageName,
  AUPackageURL: String; ACnt, ATotCnt: Integer; AUTyp: Integer; AUErrMsg: String);
begin
  if Assigned(FOnPackageUpdateProgress) then
    FOnPackageUpdateProgress(Self, AUPackageName, AUPackageURL, ACnt, ATotCnt, AUTyp, AUErrMsg);
end;

procedure TPackageDownloader.DoOnPackageUpdateCompleted(Sender: TObject;
  AUSuccess: Boolean);
begin
  if Assigned(FOnPackageUpdateCompleted) then
    FOnPackageUpdateCompleted(Self, AUSuccess);
end;

procedure TPackageDownloader.DoOnJSONProgress(Sender: TObject);
begin
  if Assigned(FOnJSONProgress) then
    FOnJSONProgress(Self);
end;

procedure TPackageDownloader.DoOnJSONDownloadCompleted(Sender: TObject;
  AJSON: TJSONStringType; AErrTyp: TErrorType; const AErrMsg: String);
begin
  if not FSilent then
  begin
    FJSON := AJSON;
    if Assigned(FOnJSONDownloadCompleted) then
      FOnJSONDownloadCompleted(Self, AJSON, AErrTyp, AErrMsg);
  end;
  FDownloadingJSON := False;
end;

constructor TPackageDownloader.Create(const ARemoteRepository: String);
begin
  FRemoteRepository := ARemoteRepository;
  if (Length(FRemoteRepository) > 0) and (not IsPathDelimiter(FRemoteRepository, Length(FRemoteRepository))) then
    FRemoteRepository := FRemoteRepository + '/';
end;

destructor TPackageDownloader.Destroy;
begin
  inherited Destroy;
end;

procedure TPackageDownloader.DownloadJSON(const ATimeOut: Integer = -1;
  const ASilent: Boolean = False);
begin
  FDownloadingJSON := True;
  FSilent := ASilent;
  FDownload := TThreadDownload.Create;
  FDownload.OnJSONProgress := @DoOnJSONProgress;
  FDownload.OnJSONDownloadCompleted := @DoOnJSONDownloadCompleted;
  FDownload.DownloadJSON(ATimeOut, ASilent);
end;

procedure TPackageDownloader.DownloadPackages(const ADownloadTo: String);
begin
  FDownload := TThreadDownload.Create;
  FDownload.OnPackageDownloadProgress := @DoOnPackageDownloadProgress;
  FDownload.OnPackageDownloadError := @DoOnPackageDownloadError;
  FDownload.OnPackageDownloadCompleted := @DoOnPackageDownloadCompleted;
  FDownload.DownloadPackages(ADownloadTo);
end;

procedure TPackageDownloader.UpdatePackages(const ADownloadTo: String);
begin
  FDownload := TThreadDownload.Create;
  FDownload.OnPackageDownloadProgress := @DoOnPackageDownloadProgress;
  FDownload.OnPackageDownloadError := @DoOnPackageDownloadError;
  FDownload.OnPackageDownloadCompleted := @DoOnPackageDownloadCompleted;
  FDownload.OnPackageUpdateProgress := @DoOnPackageUpdateProgress;
  FDownload.OnPackageUpdateCompleted := @DoOnPackageUpdateCompleted;
  FDownload.UpdatePackages(ADownloadTo);
end;

procedure TPackageDownloader.Cancel;
begin
  if Assigned(FDownload) then
  begin
    FDownload.FHTTPClient.Terminate;
    if Assigned(FDownload.FTimer) then
      FDownload.FTimer.StopTimer;
    FDownload.NeedToBreak := True;
  end;
end;

end.