forked from fmd-project-team/FMD
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuDownloadsManager.pas
1807 lines (1655 loc) · 51.7 KB
/
uDownloadsManager.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
{
File: uDownloadsManager.pas
License: GPLv2
This unit is a part of Free Manga Downloader
}
unit uDownloadsManager;
{$mode objfpc}{$H+}
{$IF FPC_FULLVERSION >= 20701}
{$DEFINE FPC271}
{$ENDIF}
interface
uses
LazFileUtils, RegExpr, IniFiles, Classes, SysUtils, ExtCtrls, typinfo, fgl,
blcksock, MultiLog, uBaseUnit, uPacker, uMisc, DownloadedChaptersDB, FMDOptions,
httpsendthread, DownloadsDB, BaseThread, dateutils, strutils;
type
TDownloadStatusType = (
STATUS_STOP,
STATUS_WAIT,
STATUS_PREPARE,
STATUS_DOWNLOAD,
STATUS_FINISH,
STATUS_COMPRESS,
STATUS_PROBLEM,
STATUS_FAILED,
STATUS_NONE // devault value oncreate, don't use
);
TDownloadStatusTypes = set of TDownloadStatusType;
TDownloadManager = class;
TTaskContainer = class;
TTaskThread = class;
{ TDownloadThread }
TDownloadThread = class(TBaseThread)
private
FTask: TTaskThread;
procedure SetTask(AValue: TTaskThread);
public
// Get download link from URL
function GetLinkPageFromURL(const URL: String): Boolean;
// Get number of download link from URL
function GetPageNumberFromURL(const URL: String): Boolean;
// Download image
function DownloadImage: Boolean;
procedure SockOnStatus(Sender: TObject; Reason: THookSocketReason;
const Value: String);
function GetPage(var output: TObject; URL: String;
const Reconnect: Integer = 0): Boolean; inline;
procedure Execute; override;
public
FHTTP: THTTPSendThread;
WorkId: Integer;
constructor Create;
destructor Destroy; override;
property Task: TTaskThread read FTask write SetTask;
end;
TDownloadThreads = specialize TFPGList<TDownloadThread>;
{ TTaskThread }
TTaskThread = class(TBaseThread)
private
FCS_THREADS: TRTLCriticalSection;
FCheckAndActiveTaskFlag: Boolean;
FCurrentWorkingDir: String;
{$IFDEF Windows}
FCurrentMaxFileNameLength: Integer;
{$ENDIF}
FCurrentCustomFileName: String;
FIsForDelete: Boolean;
procedure SetCurrentWorkingDir(AValue: String);
procedure SetIsForDelete(AValue: Boolean);
procedure SyncShowBallonHint;
protected
procedure CheckOut;
procedure Execute; override;
function Compress: Boolean;
procedure SyncStop;
procedure StatusFailedToCreateDir;
function FirstFailedChapters: Integer;
function FailedChaptersExist: Boolean;
// show notification when download completed
procedure ShowBalloonHint;
// general exception info
function GetExceptionInfo: String;
public
//additional parameter
httpCookies: String;
Flag: TFlagType;
// container (for storing information)
Container: TTaskContainer;
// download threads
Threads: TDownloadThreads;
constructor Create;
destructor Destroy; override;
function GetFileName(const AWorkId: Integer): String;
property CurrentWorkingDir: String read FCurrentWorkingDir write SetCurrentWorkingDir;
property CurrentMaxFileNameLength: Integer read FCurrentMaxFileNameLength;
// current custom filename with only %FILENAME% left intact
property CurrentCustomFileName: String read FCurrentCustomFileName write FCurrentCustomFileName;
property IsForDelete: Boolean read FIsForDelete write SetIsForDelete;
end;
{ TTaskContainer }
TTaskContainer = class
private
FWebsite: String;
FStatus: TDownloadStatusType;
FEnabled: Boolean;
procedure SetEnabled(AValue: Boolean);
procedure SetStatus(AValue: TDownloadStatusType);
procedure SetWebsite(AValue: String);
public
DlId: Integer;
// critical section
CS_Container: TRTLCriticalSection;
// read count for transfer rate
ReadCount: Integer;
// task thread of this container
Task: TTaskThread;
// download manager
Manager: TDownloadManager;
DownloadInfo: TDownloadInfo;
// current link index
CurrentPageNumber,
// current chapter index
CurrentDownloadChapterPtr,
WorkCounter,
DownCounter,
PageNumber: Integer;
ModuleId: Integer;
//Status: TDownloadStatusType;
ThreadState: Boolean;
ChapterName,
ChapterLinks,
ChaptersStatus,
PageContainerLinks,
PageLinks: TStringList;
FileNames: TStringList;
// custom filename
CustomFileName: String;
constructor Create;
destructor Destroy; override;
procedure IncReadCount(const ACount: Integer);
procedure SaveToDB(const AOrder: Integer = -1);
public
Visible: Boolean;
property Website: String read FWebsite write SetWebsite;
property Status: TDownloadStatusType read FStatus write SetStatus;
property Enabled: Boolean read FEnabled write SetEnabled;
end;
TTaskContainers = specialize TFPGList<TTaskContainer>;
{ TDownloadManager }
TDownloadManager = class
private
FSortDirection: Boolean;
FSortColumn: Integer;
FDownloadsDB: TDownloadsDB;
procedure AddItemsActiveTask(const Item: TTaskContainer);
procedure RemoveItemsActiveTask(const Item: TTaskContainer);
function GetTask(const TaskId: Integer): TTaskContainer;
function ConvertToDB: Boolean;
protected
function GetTaskCount: Integer; inline;
function GetTransferRate: Integer;
procedure ChangeStatusCount(const OldStatus, NewStatus: TDownloadStatusType);
procedure DecStatusCount(const Status: TDownloadStatusType);
procedure IncStatusCount(const Status: TDownloadStatusType);
public
CS_Task,
CS_ItemsActiveTask: TRTLCriticalSection;
Items,
ItemsActiveTask: TTaskContainers;
isRunningBackup, isFinishTaskAccessed, isRunningBackupDownloadedChaptersList,
isReadyForExit: Boolean;
// status count
CS_StatusCount: TRTLCriticalSection;
StatusCount: array [TDownloadStatusType] of Integer;
// disabled count
DisabledCount,
CompressType,
RetryConnect: Integer;
//downloaded chapter list database
DownloadedChapters: TDownloadedChaptersDB;
//exit counter
ExitWaitOK: Boolean;
constructor Create;
destructor Destroy; override;
property Count: Integer read GetTaskCount;
procedure Restore;
procedure Backup;
// These methods relate to highlight downloaded chapters.
procedure GetDownloadedChaptersState(const Alink: String;
var Chapters: array of TChapterStateItem);
// Add new task to the list.
function AddTask: Integer;
// Check and active previous work-in-progress tasks.
procedure CheckAndActiveTaskAtStartup;
// Check and active waiting tasks.
procedure CheckAndActiveTask(const isCheckForFMDDo: Boolean = False);
// Active a stopped task.
procedure SetTaskActive(const taskID: Integer);
procedure ActiveTask(const taskID: Integer);
// Stop a download/wait task.
procedure StopTask(const taskID: Integer; const isCheckForActive: Boolean =
True; isWaitFor: Boolean = False);
// Start all task
procedure StartAllTasks;
// Stop all download/wait tasks.
procedure StopAllTasks;
// Stop all download task inside a task before terminate the program.
procedure StopAllDownloadTasksForExit;
// Free then delete task without any check, use with caution
procedure FreeAndDelete(const TaskId: Integer);
// Remove a task from list.
procedure RemoveTask(const TaskID: Integer);
// Remove all finished tasks.
procedure RemoveAllFinishedTasks;
// check status of task
function TaskStatusPresent(Stats: TDownloadStatusTypes): Boolean;
// enable task
procedure EnableTask(const TaskId: Integer);
procedure DisableTask(const TaskId: Integer);
// Sort
procedure Sort(const AColumn: Integer);
property SortDirection: Boolean read FSortDirection write FSortDirection;
property SortColumn: Integer read FSortColumn write FSortColumn;
property TransferRate: Integer read GetTransferRate;
property Task[const TaskId: Integer]: TTaskContainer read GetTask; default;
end;
resourcestring
RS_FailedToCreateDir = 'Failed to create directory!';
RS_FailedTryResumeTask = 'Failed, try resuming this task!';
RS_Preparing = 'Preparing';
RS_Downloading = 'Downloading';
RS_Stopped = 'Stopped';
RS_Finish = 'Completed';
RS_Waiting = 'Waiting...';
RS_Compressing = 'Compressing...';
RS_Failed = 'Failed';
RS_Disabled = 'Disabled';
implementation
uses
frmMain, WebsiteModules, FMDVars, SimpleException;
function IntToStr(Value: Cardinal): String;
begin
Result := SysUtils.IntToStr(QWord(Value));
end;
{ TDownloadThread }
procedure TDownloadThread.SetTask(AValue: TTaskThread);
begin
if FTask = AValue then Exit;
FTask := AValue;
with FTask.Container do
if ModuleId<>-1 then
WebsiteModules.Modules[ModuleId].PrepareHTTP(FHTTP);
end;
procedure TDownloadThread.SockOnStatus(Sender: TObject;
Reason: THookSocketReason; const Value: String);
begin
if Reason = HR_ReadCount then
Task.Container.IncReadCount(StrToIntDef(Value, 0));
end;
constructor TDownloadThread.Create;
begin
inherited Create(True);
FHTTP := THTTPSendThread.Create(Self);
FHTTP.Headers.NameValueSeparator := ':';
FHTTP.Sock.OnStatus := @SockOnStatus;
end;
destructor TDownloadThread.Destroy;
begin
EnterCriticalsection(Task.FCS_THREADS);
try
Modules.DecActiveConnectionCount(Task.Container.ModuleId);
Task.Threads.Remove(Self);
finally
LeaveCriticalsection(Task.FCS_THREADS);
end;
FHTTP.Free;
inherited Destroy;
end;
function TDownloadThread.GetPage(var output: TObject; URL: String;
const Reconnect: Integer): Boolean;
begin
if FHTTP.Sock.Tag <> 100 then
FHTTP.Clear;
Result := uBaseUnit.GetPage(FHTTP, output, URL, Reconnect);
end;
procedure TDownloadThread.Execute;
var
Reslt: Boolean = False;
begin
try
case Task.Flag of
// Get number of images.
CS_GETPAGENUMBER:
begin
Reslt := GetPageNumberFromURL(
Task.Container.ChapterLinks.Strings[
Task.Container.CurrentDownloadChapterPtr]);
// Prepare 'space' for storing image url.
if (not Terminated) and
(Task.Container.PageNumber > 0) then
begin
while Task.Container.PageLinks.Count < Task.Container.PageNumber do
Task.Container.PageLinks.Add('W');
end
else
Reslt := False;
end;
// Get image urls.
CS_GETPAGELINK:
begin
Reslt := GetLinkPageFromURL(
Task.Container.ChapterLinks.Strings[
Task.Container.CurrentDownloadChapterPtr]);
end;
// Download images.
CS_DOWNLOAD:
begin
Reslt := DownloadImage;
end;
end;
if not Terminated and Reslt then
begin
EnterCriticalSection(Task.Container.CS_Container);
try
Task.Container.DownCounter := InterLockedIncrement(Task.Container.DownCounter);
Task.Container.DownloadInfo.Progress :=
Format('%d/%d', [Task.Container.DownCounter, Task.Container.PageNumber]);
finally
LeaveCriticalSection(Task.Container.CS_Container);
end;
end;
except
on E: Exception do
begin
E.Message := E.Message + LineEnding + ' In TDownloadThread.Execute' + LineEnding + Task.GetExceptionInfo;
MainForm.ExceptionHandler(Self, E);
end;
end;
end;
function TDownloadThread.GetPageNumberFromURL(const URL: String): Boolean;
begin
Result := False;
Task.Container.PageNumber := 0;
if Modules.ModuleAvailable(Task.Container.ModuleId, MMGetPageNumber) then
Result := Modules.GetPageNumber(Self, URL, Task.Container.ModuleId);
if Task.Container.PageLinks.Count > 0 then
TrimStrings(Task.Container.PageLinks);
end;
function TDownloadThread.GetLinkPageFromURL(const URL: String): Boolean;
begin
Result := False;
if Task.Container.PageLinks[WorkId] <> 'W' then Exit;
if Modules.ModuleAvailable(Task.Container.ModuleId, MMGetImageURL) then
Result := Modules.GetImageURL(Self, URL, Task.Container.ModuleId);
end;
// ----- TTaskThread -----
constructor TTaskThread.Create;
begin
inherited Create(True);
InitCriticalSection(FCS_THREADS);
Threads := TDownloadThreads.Create;
FCheckAndActiveTaskFlag := True;
FIsForDelete := False;
httpCookies := '';
FCurrentWorkingDir := '';
FCurrentCustomFileName := '';
{$IFDEF WINDOWS}
FCurrentMaxFileNameLength := 0;
{$ENDIF}
end;
destructor TTaskThread.Destroy;
var
i: Integer;
begin
EnterCriticalsection(FCS_THREADS);
try
if Threads.Count > 0 then
for i := 0 to Threads.Count - 1 do
Threads[i].Terminate;
finally
LeaveCriticalsection(FCS_THREADS);
end;
while Threads.Count > 0 do
Sleep(32);
Modules.DecActiveTaskCount(Container.ModuleId);
with Container do
begin
ThreadState := False;
Manager.RemoveItemsActiveTask(Container);
Task := nil;
if not (IsForDelete or Manager.isReadyForExit) then
begin
Container.ReadCount := 0;
DownloadInfo.TransferRate := '';
if Status <> STATUS_STOP then
begin
if (WorkCounter >= PageLinks.Count) and
(CurrentDownloadChapterPtr >= ChapterLinks.Count) and
(not FailedChaptersExist) then
begin
Status := STATUS_FINISH;
DownloadInfo.Status := Format('[%d/%d] %s',[Container.ChapterLinks.Count,Container.ChapterLinks.Count,RS_Finish]);
DownloadInfo.Progress := '';
end
else
if not (Status in [STATUS_FAILED, STATUS_PROBLEM]) then
begin
Status := STATUS_STOP;
DownloadInfo.Status :=
Format('[%d/%d] %s', [CurrentDownloadChapterPtr + 1,
ChapterLinks.Count, RS_Stopped]);
FCheckAndActiveTaskFlag := False;
end;
if not isExiting then
Synchronize(@SyncStop);
end;
end;
end;
Threads.Free;
DoneCriticalsection(FCS_THREADS);
inherited Destroy;
end;
function TTaskThread.GetFileName(const AWorkId: Integer): String;
{$IFDEF WINDOWS}
var
s: UnicodeString;
{$ENDIF}
begin
Result := '';
if (Container.FileNames.Count = Container.PageLinks.Count) and
(AWorkId < Container.FileNames.Count) then
Result := Container.FileNames[AWorkId];
if Result = '' then
Result := Format('%.3d', [AWorkId + 1]);
Result := StringReplace(CurrentCustomFileName, CR_FILENAME, Result, [rfReplaceAll]);
{$IFDEF WINDOWS}
s := UTF8Decode(Result);
if Length(s) > FCurrentMaxFileNameLength then
begin
Delete(s, 1, Length(s) - FCurrentMaxFileNameLength);
Result := UTF8Encode(s);
end;
{$ENDIF}
end;
function TTaskThread.Compress: Boolean;
var
uPacker: TPacker;
i: Integer;
s: String;
begin
Result := True;
if (Container.Manager.CompressType >= 1) then
begin
Container.DownloadInfo.Status :=
Format('[%d/%d] %s', [Container.CurrentDownloadChapterPtr + 1,
Container.ChapterLinks.Count, RS_Compressing]);
uPacker := TPacker.Create;
try
case Container.Manager.CompressType of
1: uPacker.Format := pfZIP;
2: uPacker.Format := pfCBZ;
3: uPacker.Format := pfPDF;
4: uPacker.Format := pfEPUB;
end;
uPacker.CompressionQuality := OptionPDFQuality;
uPacker.Path := CurrentWorkingDir;
uPacker.FileName := RemovePathDelim(CorrectPathSys(CorrectPathSys(Container.DownloadInfo.SaveTo) +
Container.ChapterName[Container.CurrentDownloadChapterPtr]));
for i := 0 to Container.PageLinks.Count - 1 do
begin
s := FindImageFile(uPacker.Path + GetFileName(i));
if s <> '' then
uPacker.FileList.Add(s);
end;
Result := uPacker.Execute;
if not Result then
Logger.SendWarning(Self.ClassName+', failed to compress. '+uPacker.SavedFileName);
except
on E: Exception do
begin
E.Message := E.Message + LineEnding + ' In TTaskThread.Compress' + LineEnding + GetExceptionInfo;
MainForm.ExceptionHandler(Self, E);
end;
end;
uPacker.Free;
end;
end;
procedure TTaskThread.SyncStop;
begin
Container.Manager.CheckAndActiveTask(FCheckAndActiveTaskFlag);
end;
procedure TTaskThread.StatusFailedToCreateDir;
begin
Logger.SendError(Format('Failed to create dir(%d) = %s', [Length(CurrentWorkingDir), CurrentWorkingDir]));
Container.Status := STATUS_FAILED;
Container.DownloadInfo.Status := Format('[%d/%d] %s (%d) %s', [
Container.CurrentDownloadChapterPtr,
Container.ChapterLinks.Count,
RS_FailedToCreateDir, Length(CurrentWorkingDir), LineEnding + CurrentWorkingDir]);
end;
function TTaskThread.FirstFailedChapters: Integer;
var
i: Integer;
begin
for i := 0 to Container.ChaptersStatus.Count - 1 do
if Container.ChaptersStatus[i] = 'F' then Exit(i);
Result := -1;
end;
function TTaskThread.FailedChaptersExist: Boolean;
begin
Result := FirstFailedChapters <> -1;
end;
procedure TTaskThread.ShowBalloonHint;
begin
if OptionShowBalloonHint then
Synchronize(@SyncShowBallonHint);
end;
function TTaskThread.GetExceptionInfo: String;
begin
Result :=
' Flag : ' + GetEnumName(TypeInfo(TFlagType), Integer(Flag)) + LineEnding +
' Website : ' + Container.DownloadInfo.Website + LineEnding +
' Title : ' + Container.DownloadInfo.title + LineEnding +
' Chapterlink : ' + Container.ChapterLinks[Container.CurrentDownloadChapterPtr] + LineEnding +
' Chaptername : ' + Container.ChapterName[Container.CurrentDownloadChapterPtr] + LineEnding;
end;
function TDownloadThread.DownloadImage: Boolean;
var
workFilename,
workURL,
savedFilename: String;
begin
Result := True;
// check download path
if not ForceDirectoriesUTF8(Task.CurrentWorkingDir) then
begin
Task.StatusFailedToCreateDir;
Result := False;
Exit;
end;
// check pagelinks url
workURL := Task.Container.PageLinks[WorkId];
if (workURL = '') or
(workURL = 'W') or
(workURL = 'D') then
Exit;
FHTTP.Clear;
// prepare filename
workFilename := Task.GetFileName(WorkId);
// download image
savedFilename := '';
if Modules.ModuleAvailable(Task.Container.ModuleId, MMDownloadImage) and
(Task.Container.PageNumber = Task.Container.PageContainerLinks.Count) and
(WorkId < Task.Container.PageContainerLinks.Count) then
workURL := Task.Container.PageContainerLinks[WorkId];
// OnBeforeDownloadImage
if Modules.ModuleAvailable(Task.Container.ModuleId, MMBeforeDownloadImage) then
Result := Modules.BeforeDownloadImage(Self, workURL, Task.Container.ModuleId);
if Result then
begin
// OnDownloadImage
if Modules.ModuleAvailable(Task.Container.ModuleId, MMDownloadImage) then
Result := Modules.DownloadImage(Self, workURL, Task.Container.ModuleId)
else
Result := FHTTP.GET(workURL);
end;
if Result then
begin
savedFilename := FindImageFile(Task.CurrentWorkingDir + workFilename);
Result := savedFilename <> '';
if not Result then
begin
if Modules.ModuleAvailable(Task.Container.ModuleId, MMSaveImage) then
savedFilename := Modules.SaveImage(FHTTP, Task.CurrentWorkingDir, workFilename, Task.Container.ModuleId)
else
savedFilename := SaveImageStreamToFile(FHTTP, Task.CurrentWorkingDir, workFilename);
Result := savedFilename <> '';
end;
end;
if Result then
Result := FileExistsUTF8(savedFilename);
if Terminated then Exit(False);
if Result then
begin
Task.Container.PageLinks[WorkId] := 'D';
// OnAfterImageSaved
if Modules.ModuleAvailable(Task.Container.ModuleId, MMAfterImageSaved) then
Modules.AfterImageSaved(savedFilename, Task.Container.ModuleId);
end;
end;
procedure TTaskThread.SetCurrentWorkingDir(AValue: String);
{$IFDEF WINDOWS}
var
s: UnicodeString;
{$ENDIF}
begin
if FCurrentWorkingDir = AValue then Exit;
FCurrentWorkingDir := CorrectPathSys(AValue);
{$IFDEF Windows}
s := UTF8Decode(FCurrentWorkingDir);
FCurrentMaxFileNameLength := FMDMaxImageFilePath - Length(s);
{$ENDIF}
end;
procedure TTaskThread.SetIsForDelete(AValue: Boolean);
begin
if FIsForDelete = AValue then Exit;
FIsForDelete := AValue;
end;
procedure TTaskThread.SyncShowBallonHint;
begin
with MainForm.TrayIcon, Container.DownloadInfo do
begin
if Container.Status = STATUS_FAILED then
begin
BalloonFlags := bfError;
BalloonHint := QuotedStrd(Title);
if Status = '' then
BalloonHint := BalloonHint + ' - ' + RS_Failed
else
BalloonHint := BalloonHint + LineEnding + Status;
end
else
if Container.Status = STATUS_FINISH then
begin
BalloonFlags := bfInfo;
BalloonHint :=
'"' + Container.DownloadInfo.title + '" - ' + RS_Finish;
end;
ShowBalloonHint;
end;
end;
procedure TTaskThread.CheckOut;
var
currentMaxThread, currentMaxConnections: Integer;
s: String;
begin
if Terminated then Exit;
try
if Modules.MaxThreadPerTaskLimit[Container.ModuleId] > 0 then
currentMaxThread := Modules.MaxThreadPerTaskLimit[Container.ModuleId]
else
currentMaxThread := OptionMaxThreads;
if currentMaxThread > OptionMaxThreads then
currentMaxThread := OptionMaxThreads;
if Container.PageLinks.Count > 0 then
begin
s := Trim(Container.PageLinks[Container.WorkCounter]);
if ((Flag = CS_GETPAGELINK) and (s <> 'W')) or
((Flag = CS_DOWNLOAD) and (s = 'D')) then
begin
Container.WorkCounter := InterLockedIncrement(Container.WorkCounter);
Container.DownCounter := InterLockedIncrement(Container.DownCounter);
Container.DownloadInfo.Progress :=
Format('%d/%d', [Container.DownCounter, Container.PageNumber]);
if Flag = CS_GETPAGELINK then
Container.CurrentPageNumber := InterLockedIncrement(Container.CurrentPageNumber);
Exit;
end;
end;
if Modules.MaxConnectionLimit[Container.ModuleId] > 0 then
while (not Terminated) and (not Modules.CanCreateConnection(Container.ModuleId)) do
Sleep(SOCKHEARTBEATRATE)
else
while (not Terminated) and (Threads.Count >= currentMaxThread) do
Sleep(SOCKHEARTBEATRATE);
currentMaxConnections := Modules.MaxConnectionLimit[Container.ModuleId];
if currentMaxConnections <= 0 then
currentMaxConnections := currentMaxThread;
if (not Terminated) and (Threads.Count < currentMaxThread) then
try
EnterCriticalsection(FCS_THREADS);
if Modules.ActiveConnectionCount[Container.ModuleId] >= currentMaxConnections then Exit;
Modules.IncActiveConnectionCount(Container.ModuleId);
Threads.Add(TDownloadThread.Create);
with TDownloadThread(Threads.Last) do begin
Task := Self;
WorkId := Container.WorkCounter;
Start;
Container.WorkCounter := InterLockedIncrement(Container.WorkCounter);
end;
if Flag = CS_GETPAGELINK then
Container.CurrentPageNumber := InterLockedIncrement(Container.CurrentPageNumber);
finally
LeaveCriticalsection(FCS_THREADS);
end;
except
on E: Exception do
begin
E.Message := E.Message + LineEnding + ' In TTaskThread.Checkout' + LineEnding + GetExceptionInfo;
MainForm.ExceptionHandler(Self, E);
end;
end;
end;
procedure TTaskThread.Execute;
function CheckForPrepare: Boolean;
var
i: Integer;
begin
if Container.PageLinks.Count = 0 then
Exit(True);
Result := False;
if Container.PageLinks.Count > 0 then
for i := 0 to Container.PageLinks.Count - 1 do
if (Trim(Container.PageLinks[i]) = 'W') or
(Trim(Container.PageLinks[i]) = '') then
Exit(True);
end;
function CheckForFinish: Boolean;
var
i, c: Integer;
sf: String;
begin
if Container.PageLinks.Count > 0 then
Result := True
else
begin
Result := False;
Exit;
end;
c := 0;
sf := '';
for i := 0 to Container.PageLinks.Count - 1 do
if Trim(Container.PageLinks[i]) <> 'D' then
begin
Inc(c);
sf += Container.PageLinks[i] + LineEnding;
end;
if c > 0 then begin
Logger.SendWarning(Format('%s, checkforfinish failed=%d/%d [%s]"%s" > "%s"',
[Self.ClassName,
c,
Container.PageLinks.Count,
Container.Website,
Container.DownloadInfo.Title,
Container.ChapterLinks[Container.CurrentDownloadChapterPtr]]) + LineEnding + Trim(sf));
Result := False;
end;
end;
procedure WaitForThreads;
begin
while (not Terminated) and (Threads.Count > 0) do
Sleep(SOCKHEARTBEATRATE);
end;
var
j: Integer;
DynamicPageLink: Boolean;
FailedRetryCount: Integer = 0;
begin
Container.ThreadState := True;
Container.DownloadInfo.TransferRate := FormatByteSize(Container.ReadCount, true);
try
if (Container.Website = '') and (Container.DownloadInfo.Website <> '') then
Container.Website := Container.DownloadInfo.Website;
if Container.ModuleId > -1 then
DynamicPageLink := Modules.Module[Container.ModuleId].DynamicPageLink
else
DynamicPageLink := False;
if Trim(Container.CustomFileName) = '' then
Container.CustomFileName := OptionFilenameCustomRename;
if Trim(Container.CustomFileName) = '' then
Container.CustomFileName := DEFAULT_FILENAME_CUSTOMRENAME;
while container.ChaptersStatus.Count < Container.CurrentDownloadChapterPtr - 1 do
Container.ChaptersStatus.Add('D');
while Container.ChaptersStatus.Count < Container.ChapterLinks.Count do
Container.ChaptersStatus.Add('P');
if OptionAlwaysStartTaskFromFailedChapters and (Container.CurrentDownloadChapterPtr <> 0) then
Container.CurrentDownloadChapterPtr := 0;
while Container.CurrentDownloadChapterPtr < Container.ChapterLinks.Count do
begin
while Container.ChaptersStatus[Container.CurrentDownloadChapterPtr] = 'D' do
Inc(Container.CurrentDownloadChapterPtr);
WaitForThreads;
if Terminated then Exit;
//check path
if OptionGenerateChapterFolder then
CurrentWorkingDir := CorrectPathSys(Container.DownloadInfo.SaveTo) +
Container.ChapterName[Container.CurrentDownloadChapterPtr]
else
CurrentWorkingDir := Container.DownloadInfo.SaveTo;
if not ForceDirectoriesUTF8(CurrentWorkingDir) then
begin
StatusFailedToCreateDir;
ShowBalloonHint;
Exit;
end;
if Container.ModuleId > -1 then
Modules.TaskStart(Container, Container.ModuleId);
// set current working custom filename
CurrentCustomFileName := CustomRename(Container.CustomFileName,
Container.DownloadInfo.Website,
Container.DownloadInfo.Title,
'',
'',
Container.ChapterName[Container.CurrentDownloadChapterPtr],
'',
OptionChangeUnicodeCharacter,
OptionChangeUnicodeCharacterStr,
CR_FILENAME);
// Get page number.
if Container.PageLinks.Count = 0 then
begin
Container.PageNumber := 0;
Flag := CS_GETPAGENUMBER;
Container.WorkCounter := 0;
Container.DownCounter := 0;
Container.DownloadInfo.iProgress := 0;
Container.DownloadInfo.Progress := '0/0';
Container.DownloadInfo.Status :=
Format('[%d/%d] %s (%s)',
[Container.CurrentDownloadChapterPtr + 1,
Container.ChapterLinks.Count,
RS_Preparing,
Container.ChapterName[Container.CurrentDownloadChapterPtr]]);
Container.Status := STATUS_PREPARE;
CheckOut;
WaitForThreads;
if Terminated then begin
Container.PageLinks.Clear;
Container.PageNumber := 0;
Exit;
end;
end;
//Check file, if exist set mark 'D', otherwise 'W' or 'G' for dynamic image url
if Container.PageLinks.Count > 0 then
begin
for j := 0 to Container.PageLinks.Count - 1 do
begin
if ImageFileExist(CurrentWorkingDir + GetFileName(j)) then
Container.PageLinks[j] := 'D'
else
if Container.PageLinks[j] = 'D' then
begin
if DynamicPageLink then
Container.PageLinks[j] := 'G'
else
Container.PageLinks[j] := 'W';
end;
end;
end;
//Get page links
if Container.PageLinks.Count = 0 then
Container.PageLinks.Add('W');
Container.PageNumber := Container.PageLinks.Count;
if (not DynamicPageLink) and CheckForPrepare then
begin
Flag := CS_GETPAGELINK;
Container.WorkCounter := 0;
Container.DownCounter := 0;
Container.DownloadInfo.iProgress := 0;
Container.DownloadInfo.Progress :=
Format('%d/%d', [Container.DownCounter, Container.PageNumber]);
Container.DownloadInfo.Status :=
Format('[%d/%d] %s (%s)',
[Container.CurrentDownloadChapterPtr + 1,
Container.ChapterLinks.Count,
RS_Preparing,
Container.ChapterName[Container.CurrentDownloadChapterPtr]]);
Container.Status := STATUS_PREPARE;
while Container.WorkCounter < Container.PageNumber do
begin
if Terminated then Exit;
Checkout;
Container.DownloadInfo.iProgress :=
InterLockedIncrement(Container.DownloadInfo.iProgress);
end;
WaitForThreads;
if Terminated then Exit;
//check if pagelink is found. Else set again to 'W'(some script return '')
if Container.PageLinks.Count > 0 then
begin
for j := 0 to Container.PageLinks.Count - 1 do
begin
if Trim(Container.PageLinks[j]) = '' then
Container.PageLinks[j] := 'W';
end;
end;
end;
if Terminated then Exit;
// download pages
// If Container doesn't have any image, we will skip the loop. Otherwise
// download them
Container.PageNumber := Container.PageLinks.Count;
if Container.PageLinks.Count > 0 then
begin
Flag := CS_DOWNLOAD;
Container.WorkCounter := 0;
Container.DownCounter := 0;
Container.DownloadInfo.iProgress := 0;
Container.DownloadInfo.Progress :=
Format('%d/%d', [Container.DownCounter, Container.PageNumber]);
Container.Status := STATUS_DOWNLOAD;
Container.DownloadInfo.Status :=
Format('[%d/%d] %s (%s)',
[Container.CurrentDownloadChapterPtr + 1,
Container.ChapterLinks.Count,
RS_Downloading,
Container.ChapterName[Container.CurrentDownloadChapterPtr]]);
while Container.WorkCounter < Container.PageLinks.Count do
begin
if Terminated then Exit;
Checkout;
Container.DownloadInfo.iProgress :=
InterLockedIncrement(Container.DownloadInfo.iProgress);