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
|
unit Unit3;
interface
uses Windows, Classes, SysUtils, SyncObjs, Math, IdHttp , IdSSLOpenSSL;
// Téléchargement multiconnexions (multi-threads)
procedure FastURLDownload(aWnd :hWnd; aMessage :Cardinal; aURL :string; aFileName :TFileName; aThreadCount :integer = 0);
//-------------------------------------------------------------------------------------------------
// Status du téléchargement
const
FILE_READ_DATA = $0001;
FILE_WRITE_DATA = $0002;
procedure GetNativeSystemInfo(var aSystemInformation: TSystemInfo); stdcall; external kernel32;
function SetFilePointerEx(aFile: THandle; aDistance :int64; const aPointer :PInt64; aMethod :dword): bool; stdcall; external kernel32;
//-------------------------------------------------------------------------------------------------
// Structure permettant l'écriture en Int64 et la lecture en LoInt/HiInt par
// MapViewOfFile
type
TViewInfo = record
Size :int64;
case byte of
0 : (Offset :int64);
1 : (LoOffset, HiOffset :integer);
end;
type
TFastURLDownloadState = (dsStart, dsIncrement, dsError, dsSuccess);
//-------------------------------------------------------------------------------------------------
// Tâche de téléchargement d'un bloc
type
TViewDownloadThread = class(TThread)
private
URL :string;
MapFile :THandle;
View :TViewInfo;
fs :TFileStream;
SSL : TIdSSLIOHandlerSocketOpenSSL;
HTTP :TIDHttp;
RunEvent :THandle;
ReadyEvent :THandle;
function IdIOHandlerVerifyPeer(Certificate: TIdX509; AOk: Boolean; ADepth: Integer): Boolean;
protected
procedure Execute; override;
public
procedure Start(aOffset, aSize :int64);
procedure Stop;
constructor Create(aURL :string; aMapFile, aReadyEvent :THandle; aOnTerminate :TNotifyEvent);
destructor Destroy; override;
end;
//-------------------------------------------------------------------------------------------------
// Tâche principale. Se charge de répartir le travail
type
TDownloadThread = class(TThread)
private
Wnd :hWnd;
Message :Cardinal;
URL :string;
FileName :TFileName;
FileSize :int64;
AllocSize :int64;
AcceptRanges :boolean;
ThreadCount :integer;
Error :boolean;
fileLength :int64;
function IdIOHandlerVerifyPeer(Certificate: TIdX509; AOk: Boolean; ADepth: Integer): Boolean;
protected
procedure GetFileInfo;
procedure SingleDownload;
procedure MultiDownload;
procedure Notify(aState :TFastURLDownloadState; aLParam :LParam = 0);
procedure OnThreadTerminate(Sender :TObject);
procedure Execute; override;
public
constructor Create(aWnd :hWnd; aMessage :Cardinal; aURL :string; aFileName :TFileName; aThreadCount :integer);
end;
//------------------------------------Fin déclaration----------------------------------------------
implementation
constructor TViewDownloadThread.Create(aURL :string; aMapFile, aReadyEvent :THandle; aOnTerminate :TNotifyEvent);
begin
inherited Create(true);
URL := aURL;
MapFile := aMapFile;
ReadyEvent := aReadyEvent;
OnTerminate := aOnTerminate;
RunEvent := CreateEvent(nil, TRUE, FALSE, nil);
Http := TIdHTTP.Create(nil);
HTTP.Request.BasicAuthentication := True;
HTTP.Request.Username := 'safa';
HTTP.Request.Password := 'pass';
SSL :=TIdSSLIOHandlerSocketOpenSSL.Create(nil);
SSL.OnVerifyPeer:=IdIOHandlerVerifyPeer;
Http.IOHandler:=SSL;
//Libération automatique
FreeOnTerminate := TRUE;
end;
destructor TViewDownloadThread.Destroy;
begin
CloseHandle(RunEvent);
fs.Free;
inherited;
end;
//-------------------------------------------------------------------------------------------------
procedure TViewDownloadThread.Execute;
var
Data :pointer;
begin
while not Terminated do
begin
//Attente infinie de l'ordre de démarrage
WaitForSingleObject(RunEvent, INFINITE);
if not Terminated then
try
ReturnValue := ERROR_FILE_NOT_FOUND;
//Télécharge un bloc avec possibilité de reprise :
HTTP.Request.Range := Format('%d-%d',[View.Offset+fs.position , View.Offset +View.Size -1]);
HTTP.Get(url,fs);
//Ouvre en écriture la vue correspondante du fichier local
Data := MapViewOfFile(MapFile, FILE_MAP_WRITE, View.HiOffset, View.LoOffset, View.Size);
if not Assigned(Data) then
begin
ReturnValue := GetLastError;
Exit;
end;
//Copie les données et libère la vue
CopyMemory(Data, fs, View.Size);
UnmapViewOfFile(Data);
ReturnValue := ERROR_SUCCESS;
finally
//Arrêté et prêt
ResetEvent(RunEvent);
SetEvent(ReadyEvent);
end;
end;
end;
//-------------------------------------------------------------------------------------------------
procedure TViewDownloadThread.Start(aOffset, aSize: int64);
begin
View.Offset := aOffset;
View.Size := aSize;
//Occupé et démarré
ResetEvent(ReadyEvent);
SetEvent(RunEvent);
end;
//-------------------------------------------------------------------------------------------------
procedure TViewDownloadThread.Stop;
begin
Terminate;
SetEvent(RunEvent);
end;
function TViewDownloadThread.IdIOHandlerVerifyPeer(Certificate: TIdX509; AOk: Boolean;
ADepth: Integer): Boolean;
begin
Result := True;
end;
//=================================================================================================
{ TFileDownload }
//-------------------------------------------------------------------------------------------------
constructor TDownloadThread.Create(aWnd :hWnd; aMessage :Cardinal; aURL :string; aFileName :TFileName; aThreadCount :integer);
var
SystemInfo :TSystemInfo;
begin
inherited Create(true);
Wnd := aWnd;
URL := aURL;
Message := aMessage;
URL := aURL;
FileName := aFileName;
Error := FALSE;
//Fixe le nombre de threads à utiliser
if aThreadCount > 0
then ThreadCount := aThreadCount
else ThreadCount := CPUCount *2;
//Fixe la taille d'allocation minimale définie par le système
GetNativeSystemInfo(SystemInfo);
AllocSize := SystemInfo.dwAllocationGranularity *15;
execute;
//Libération automatique
FreeOnTerminate := TRUE;
end;
//-------------------------------------------------------------------------------------------------
procedure TDownloadThread.Notify(aState: TFastURLDownloadState; aLParam: LParam);
begin
PostMessage(Wnd, Message, WParam(aState), aLParam);
end;
//-------------------------------------------------------------------------------------------------
procedure TDownloadThread.OnThreadTerminate(Sender: TObject);
begin
with TThread(Sender) do
if ReturnValue <> ERROR_SUCCESS then
begin
Error := TRUE;
Notify(dsError, ReturnValue);
end;
end;
//-------------------------------------------------------------------------------------------------
procedure TDownloadThread.GetFileInfo;
var HTTP:TIDHttp;
SSL: TIdSSLIOHandlerSocketOpenSSL;
begin
SSL:= TIdSSLIOHandlerSocketOpenSSL.Create(nil);
HTTP:= TIDHttp.Create(nil);
SSL.OnVerifyPeer:=IdIOHandlerVerifyPeer;
HTTP.IOHandler:=SSL;
HTTP.Request.BasicAuthentication := True;
HTTP.Request.Username := 'safa';
HTTP.Request.Password := 'pass';
//Récupère la taille du fichier et la capacité du serveur
//en ne téléchargeant que l'entête
try
with HTTP do
try
Head(Self.URL);
FileSize := Response.ContentLength;
fileLength :=Filesize;
AcceptRanges := Response.AcceptRanges = 'bytes';
finally
Free;
end;
except
Notify(dsError, ERROR_FILE_NOT_FOUND);
Raise;
end;
end;
function TDownloadThread.IdIOHandlerVerifyPeer(Certificate: TIdX509; AOk: Boolean;
ADepth: Integer): Boolean;
begin
Result := True;
end;
//-------------------------------------------------------------------------------------------------
procedure TDownloadThread.SingleDownload;
var
Stream :TFileStream;
HTTP:TIDHTTP;
SSL :TIdSSLIOHandlerSocketOpenSSL;
begin
//Création du fichier local. "Accès refusé" si impossible
try
Stream := TFileStream.Create(FileName, fmCreate);
except
Notify(dsError, ERROR_ACCESS_DENIED);
Raise;
end;
Http := TIdHTTP.Create(nil);
SSL :=TIdSSLIOHandlerSocketOpenSSL.Create(nil);
SSL.OnVerifyPeer:=IdIOHandlerVerifyPeer;
Http.IOHandler:=SSL;
HTTP.Request.BasicAuthentication := True;
HTTP.Request.Username := 'safa';
HTTP.Request.Password := 'pass';
//Téléchargement
try
with HTTP do
try
Get('https:\\192.168.1.100\vb.exe', Stream);
finally
Stream.Free;
Free;
end;
except
Notify(dsError, ERROR_FILE_NOT_FOUND);
Raise;
end;
end;
//-------------------------------------------------------------------------------------------------
procedure TDownloadThread.MultiDownload;
var
FHandle :hFile;
hMap :THandle;
Offset :int64;
Size :int64;
Position :int64;
WaitState :dword;
i :integer;
lastOffset :int64;
FileInfoName :string;
ThreadList :array of TViewDownloadThread;
ReadyList :array of THandle;
//-----------------------------------
procedure CheckError(aCheck :boolean);
begin
if not aCheck then
begin
Abort;
end;
end;
//-----------------------------------
begin
// si ce fichier existe => une partie du fichier est téléchargé=> reprise
// en démarrant le thread avec la valeur de offset quand le téléchargement est
//interrompu.
FileInfoName := FileName +'.info';
if Fileexists('downloads\'+FileInfoName) then
try
with TFileStream.Create('downloads\'+FileInfoName, fmOpenRead) do
try
Read(Offset, SizeOf(Offset));
finally
Free;
end
except
Offset := 0;
end
else Offset := 0;
LastOffset := High(Int64);
Position := 0;
//Création du fichier local
FHandle := CreateFile(PChar(FileName), FILE_READ_DATA or FILE_WRITE_DATA, 0, nil, CREATE_ALWAYS, 0, 0);
CheckError(FHandle <> INVALID_HANDLE_VALUE);
try
//Fixe sa taille à la taille finale
CheckError(SetFilePointerEx(FHandle, FileSize, nil, FILE_BEGIN));
CheckError(SetEndOfFile(FHandle));
//Création du fichier mappé
hMap := CreateFileMapping(FHandle, nil, PAGE_READWRITE, 0, 0, nil);
CheckError(hMap <> 0);
try
//Création des Threads et Events de téléchargement
SetLength(ReadyList, ThreadCount);
SetLength(ThreadList, ThreadCount);
for i := 0 to ThreadCount -1 do
begin
ReadyList[i] := CreateEvent(nil, TRUE, TRUE, nil);
ThreadList[i] := TViewDownloadThread.Create('https:\\192.168.1.100\vb.exe', hMap, ReadyList[i], OnThreadTerminate);
end;
try
//Téléchargement
while not (Terminated or Error) do
begin
//Attend qu'au moins un Thread soit à l'état prêt
WaitState := WaitForMultipleObjects(ThreadCount, @ReadyList[0], FALSE, 1000);
if WaitState <> WAIT_TIMEOUT then
begin
i := WaitState -WAIT_OBJECT_0;
Size := Min(FileSize -Offset, AllocSize);
ThreadList[i].View.Offset := High(Int64);
//Le redémarre avec le prochain bloc
if Size > 0 then
begin
ThreadList[i].Start(Offset, Size);
inc(Position, Size);
end;
//Si la taille est plus petite que la taille d'allocation
//=> fin du téléchargement
if Size < AllocSize
then Break
else inc(Offset, AllocSize);
end;
end;
//Attend que tout les Threads aient terminé
if not Error then
WaitForMultipleObjects(ThreadCount, @ReadyList[0], TRUE, INFINITE);
finally
//Libération des Threads et Events et LastOffset si erreur
for i := 0 to ThreadCount -1 do
begin
if Error and (ThreadList[i].View.Offset < LastOffset) then
LastOffset := ThreadList[i].View.Offset;
ThreadList[i].Stop;
CloseHandle(ReadyList[i]);
end;
end;
finally
//Libération du fichier mappé
CloseHandle(hMap);
end;
finally
//Libération du fichier local
CloseHandle(FHandle);
//sauvegarder lastoffset dans un fichier pour faire la reprise:
if Error then
with TFileStream.Create('downloads\'+FileInfoName, fmCreate) do
try
Write(LastOffset, SizeOf(LastOffset));
finally
Free;
end
else DeleteFile('downloads\'+FileInfoName);
end;
end;
//-------------------------------------------------------------------------------------------------
procedure TDownloadThread.Execute;
var
StartTime :Cardinal;
begin
//Informations sur le fichier et la capacité du serveur
GetFileInfo;
//Contrôle le nombre de Threads à utiliser
if ThreadCount > 1 then
begin
if AcceptRanges and (FileSize > AllocSize)
then ThreadCount := Min(ThreadCount, FileSize div AllocSize)
else ThreadCount := 1;
end;
Notify(dsStart, FileSize);
StartTime := GetTickCount;
//Téléchargement
if ThreadCount > 1
then MultiDownload
else SingleDownload;
Notify(dsSuccess, GetTickCount -StartTime);
end;
//=================================================================================================
procedure FastURLDownload(aWnd :hWnd; aMessage :Cardinal; aURL :string; aFileName :TFileName; aThreadCount :integer);
begin
TDownloadThread.Create(aWnd, aMessage, aURL, aFileName, aThreadCount);
end;
end. |
Partager