| 1 |
{%MainUnit castledownload.pas} |
| 2 |
{ |
| 3 |
Copyright 2013-2022 Michalis Kamburelis. |
| 4 |
|
| 5 |
This file is part of "Castle Game Engine". |
| 6 |
|
| 7 |
"Castle Game Engine" is free software; see the file COPYING.txt, |
| 8 |
included in this distribution, for details about the copyright. |
| 9 |
|
| 10 |
"Castle Game Engine" is distributed in the hope that it will be useful, |
| 11 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 13 |
|
| 14 |
---------------------------------------------------------------------------- |
| 15 |
} |
| 16 |
|
| 17 |
{$ifdef read_interface} |
| 18 |
|
| 19 |
type |
| 20 |
TCastleDownload = class; |
| 21 |
|
| 22 |
TDownloadFinishedEvent = procedure (const Sender: TCastleDownload; var FreeSender: Boolean) of object; |
| 23 |
|
| 24 |
{ Download an URL (possibly making an HTTP(S) request) asynchronously, |
| 25 |
without blocking the application. |
| 26 |
You can register a callback @link(OnFinish) or watch |
| 27 |
when the @link(Status) property changes from dsDownloading to dsError or dsSuccess |
| 28 |
to detect when this finished downloading. |
| 29 |
|
| 30 |
@italic(Features:) |
| 31 |
|
| 32 |
@unorderedList( |
| 33 |
@item(The download can be observed (looking at @link(Status), @link(DownloadedBytes), @link(TotalBytes)).) |
| 34 |
|
| 35 |
@item(When the downlad is finished, look at @link(Contents) (if success) or @link(ErrorMessage) (if error, that is @link(Status) = @link(dsError)).) |
| 36 |
|
| 37 |
@item(We can read MIME type from server (can be used throughout our engine to designate file type).) |
| 38 |
|
| 39 |
@item(For downloading (making a request) using HTTP, this is a handful of additional features, to support downloading from modern web servers and using REST APIs: |
| 40 |
|
| 41 |
@unorderedList( |
| 42 |
@item(First of all, we support both HTTP and HTTPS on all platforms and compilers, through various backend (FpHttpClient, Indy, Delphi Net Client).) |
| 43 |
|
| 44 |
@item(You can provide arbitrary HTTP headers using @link(HttpHeader). For example, various REST APIs require you to provide some key to authenticate through a custom HTTP header.) |
| 45 |
|
| 46 |
@item(You can specify any @link(HttpMethod), like GET, POST, PUT and more. Default is naturally GET which is the standard method to just download the data.) |
| 47 |
|
| 48 |
@item(For HTTP POST method, you can provide form data as @link(HttpPostData).) |
| 49 |
|
| 50 |
@item(You can provide input data for any request using @link(HttpRequestBody). The most common use case is to provide a body for PUT requests, but it can be used for any request, e.g. to provide POST body overriding the @link(HttpPostData).) |
| 51 |
|
| 52 |
@item(Once the download finishes, you can read @link(HttpResponseCode) and @link(HttpResponseHeaders).) |
| 53 |
|
| 54 |
@item(By default, we follow HTTP/HTTPS redirects.) |
| 55 |
) |
| 56 |
) |
| 57 |
) |
| 58 |
|
| 59 |
@italic(See examples:) |
| 60 |
|
| 61 |
@unorderedList( |
| 62 |
@item(@url(https://github.com/castle-engine/castle-engine/blob/master/examples/network/asynchronous_download/ asynchronous_download) to download resources asynchronously, downloading a few URLs and at the same time displaying an animation and progress bar.) |
| 63 |
|
| 64 |
@item(@url(https://github.com/castle-engine/castle-engine/blob/master/examples/network/remote_logging/ remote_logging) to send logs to a remote server, using HTTP POST.) |
| 65 |
|
| 66 |
@item(@url(https://github.com/castle-engine/castle-engine/tree/master/examples/network/put_data/ put_data) to send HTTP PUT request.) |
| 67 |
|
| 68 |
@item(And other examples in @url(https://github.com/castle-engine/castle-engine/tree/master/examples/network examples/network) subdirectory.) |
| 69 |
) |
| 70 |
|
| 71 |
@italic(Usage:) |
| 72 |
|
| 73 |
The download starts when you call @link(Start). |
| 74 |
Be sure to configure the properties, including @link(OnFinish), |
| 75 |
before calling @link(Start), because in case of some protocols @link(Start) may immediately |
| 76 |
read everything and finish. |
| 77 |
When the download ends, the @link(OnFinish) is called and @link(Status) changes. |
| 78 |
|
| 79 |
You can always just free an instance of this class, this will |
| 80 |
break the download immediately, if it's still in-progress. |
| 81 |
|
| 82 |
The download continues while your application is running, |
| 83 |
because we use @link(TCastleApplicationProperties.OnUpdate ApplicationProperties.OnUpdate) |
| 84 |
mechanism. If your application uses TCastleWindow or TCastleControl, |
| 85 |
then this just works. |
| 86 |
Note that if you just want to wait for download to finish, |
| 87 |
you can use @link(WaitForFinish) method or just call simpler @link(Download) |
| 88 |
routine. |
| 89 |
|
| 90 |
Do not worry whether this uses threads (or not) internally. |
| 91 |
All the methods and properties of this class should be accessed |
| 92 |
from the main thread, the same thread you use for all Castle Game Engine |
| 93 |
functions. And the OnFinish is called in the main thread, |
| 94 |
so you can handle it without worrying about threading. |
| 95 |
} |
| 96 |
TCastleDownload = class(TComponent) |
| 97 |
strict private |
| 98 |
FUrl: String; |
| 99 |
FFinalUrl: String; |
| 100 |
FHttpMethod: THttpMethod; |
| 101 |
FOnFinish: TDownloadFinishedEvent; |
| 102 |
FStatus: TDownloadStatus; |
| 103 |
FErrorMessage: String; |
| 104 |
FContents: TStream; |
| 105 |
FOwnsContents: Boolean; |
| 106 |
FOptions: TStreamOptions; |
| 107 |
FTotalBytes, FDownloadedBytes: Int64; |
| 108 |
FMimeType: String; |
| 109 |
Reader: TUrlAsynchronousReader; //< non-nil when asynchronous reading is in-progress |
| 110 |
UpdateInitialized: Boolean; |
| 111 |
FHttpPostData: TStringList; |
| 112 |
FHttpHeadersKeys, FHttpHeadersValues: TStringList; |
| 113 |
FHttpRequestBody: TMemoryStream; |
| 114 |
FHttpResponseCode: Integer; |
| 115 |
FHttpResponseHeaders: TStrings; |
| 116 |
procedure SetUrl(const Value: String); |
| 117 |
procedure SetHttpMethod(const Value: THttpMethod); |
| 118 |
procedure SetOnFinish(const Value: TDownloadFinishedEvent); |
| 119 |
procedure SetOptions(const Value: TStreamOptions); |
| 120 |
procedure ReleaseContents; |
| 121 |
{ Set Contents from given UnderlyingStream. |
| 122 |
The passed UnderlyingStream becomes owned by something in this method |
| 123 |
(like TCastleDownload instance or FContents or it is freed). |
| 124 |
Consider the reference to UnderlyingStream invalid after this call. } |
| 125 |
procedure SetContentsApplyOptions(UnderlyingStream: TStream); |
| 126 |
procedure Update(Sender: TObject); |
| 127 |
private |
| 128 |
{ Set by Download(). } |
| 129 |
ForceSynchronous: Boolean; |
| 130 |
protected |
| 131 |
{ Note that this may destroy our own instance. |
| 132 |
So never access our own fields / virtual methods after calling this. } |
| 133 |
procedure DoFinish; virtual; |
| 134 |
public |
| 135 |
constructor Create(AOwner: TComponent); override; |
| 136 |
destructor Destroy; override; |
| 137 |
|
| 138 |
{ Get the data. This starts downloading. |
| 139 |
Be sure to set @link(Url) and other necessary properties before calling this. } |
| 140 |
procedure Start; |
| 141 |
|
| 142 |
{ URL to read or write. |
| 143 |
Supports all protocols, like @code(file), @code(http), @code(https), |
| 144 |
@code(castle-data) and other documented on |
| 145 |
https://castle-engine.io/manual_network.php . |
| 146 |
|
| 147 |
Can only change when there is no download in progress |
| 148 |
(@link(Status) is dsNotStarted or dsSuccess). } |
| 149 |
property Url: String read FUrl write SetUrl; |
| 150 |
|
| 151 |
{ When the download has finished (with success or error), |
| 152 |
this is updated to "final" URL, after resolving HTTP/HTTPS redirects and |
| 153 |
castle-data:/ protocol. } |
| 154 |
property FinalUrl: String read FFinalUrl; |
| 155 |
|
| 156 |
{ Options that configure the output stream. See TStreamOption for details. } |
| 157 |
property Options: TStreamOptions read FOptions write SetOptions; |
| 158 |
|
| 159 |
{ In case of HTTP and HTTPS protocols, choose the http request method (verb). |
| 160 |
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods |
| 161 |
and https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods |
| 162 |
for description. |
| 163 |
|
| 164 |
Can only change when there is no download in progress |
| 165 |
(@link(Status) is not dsDownloading). } |
| 166 |
property HttpMethod: THttpMethod read FHttpMethod write SetHttpMethod default hmGet; |
| 167 |
|
| 168 |
{ Event called when we finish downloading. |
| 169 |
|
| 170 |
Can only change when there is no download in progress |
| 171 |
(@link(Status) is not dsDownloading). } |
| 172 |
property OnFinish: TDownloadFinishedEvent read FOnFinish write SetOnFinish; |
| 173 |
|
| 174 |
{ Whether we finished the download (and if yes, was it an error or success). } |
| 175 |
property Status: TDownloadStatus read FStatus; |
| 176 |
|
| 177 |
{ Wait until status is no longer dsDownloading. } |
| 178 |
procedure WaitForFinish; |
| 179 |
|
| 180 |
{ If the @link(Status) is dsError, this contains a detailed error message. } |
| 181 |
property ErrorMessage: String read FErrorMessage; |
| 182 |
|
| 183 |
{ The downloaded contents. |
| 184 |
|
| 185 |
If the @link(Status) is dsSuccess, this is always set (never @nil). |
| 186 |
In case of some protocols and some failures, the contents may be available |
| 187 |
(not @nil) even when error occurred, that is when Status is dsError. |
| 188 |
E.g. when HTTP server returns an error, |
| 189 |
like 404, it also still sends the response contents. |
| 190 |
|
| 191 |
This stream is owned by default (if @link(OwnsContents)) by this TCastleDownload instance, |
| 192 |
so it will become invalid when the TCastleDownload instance is freed. } |
| 193 |
property Contents: TStream read FContents; |
| 194 |
|
| 195 |
{ Is the @link(Contents) owned by this @link(TCastleDownload) instance. |
| 196 |
Set this to @false to be able to free this TCastleDownload instance |
| 197 |
and still keep the stream reference. |
| 198 |
It is your responsibility then to keep and free the @link(Contents) |
| 199 |
stream whenever you want. } |
| 200 |
property OwnsContents: boolean read FOwnsContents write FOwnsContents default true; |
| 201 |
|
| 202 |
{ How many bytes were downloaded. |
| 203 |
Together with @link(TotalBytes), you can use it e.g. to show a progress bar |
| 204 |
when downloading. |
| 205 |
This is always >= 0. } |
| 206 |
property DownloadedBytes: Int64 read FDownloadedBytes; |
| 207 |
|
| 208 |
{ How many bytes are expected to be downloaded, in total. |
| 209 |
-1 if unknown. |
| 210 |
Depending on the server answer, this may be known fairly quickly after |
| 211 |
starting the download, or if may not be known at all (until we finish |
| 212 |
the download). |
| 213 |
It's guaranteed that this is known (not -1) when @link(Status) = dsSuccess, |
| 214 |
in all other cases always be prepared that this may be equal -1. } |
| 215 |
property TotalBytes: Int64 read FTotalBytes; |
| 216 |
|
| 217 |
{ As soon as the MIME type of the downloaded contents is known, this is set. |
| 218 |
It is guaranteed to be set when @link(Status) is dsSuccess, |
| 219 |
it *may* be determined earlier (when dsDownloading). } |
| 220 |
property MimeType: String read FMimeType; |
| 221 |
|
| 222 |
{ Form data to send when HttpMethod = hmPost. |
| 223 |
Initially empty. |
| 224 |
Use the TStrings name/value mechanism to set the form, like |
| 225 |
|
| 226 |
@longCode(# |
| 227 |
// Advised: |
| 228 |
Download.HttpPostData.Values['my-form-key'] := 'my-form-value'; |
| 229 |
// This also works, it is equivalent to above if key didn't already exist |
| 230 |
Download.HttpPostData.Append('my-form-key-2=my-form-value-2'); |
| 231 |
#) |
| 232 |
} |
| 233 |
function HttpPostData: TStrings; |
| 234 |
function PostData: TStrings; deprecated 'use HttpPostData'; |
| 235 |
|
| 236 |
{ Request body to send along with the request. |
| 237 |
Most useful with PUT (to send data to save on the server side). |
| 238 |
May also be useful with POST (only when the HttpPostData key-value is not |
| 239 |
flexible enough) or other requests. |
| 240 |
|
| 241 |
You can use various @code(TStream) methods to set the stream, |
| 242 |
like @code(TStream.CopyFrom). The CastleClassUtils also has various |
| 243 |
helpers for stream, e.g. to write a String (AnsiString, UTF-8 encoding) |
| 244 |
to a stream use @code(WriteStr(Download.HttpRequestBody, 'My content')). |
| 245 |
|
| 246 |
Example usage: |
| 247 |
|
| 248 |
@includeCode(../../examples/network/put_data/put_data.dpr) |
| 249 |
|
| 250 |
Note: For some requests you may want to add HTTP headers like Content-Type etc. |
| 251 |
Do this using @link(HttpHeader). |
| 252 |
|
| 253 |
In case of POST requests, when this stream has non-empty contents |
| 254 |
(stream size > 0), it overrules the HttpPostData. That is, |
| 255 |
HttpPostData is completely ignored in this case. |
| 256 |
Reason: Internally, HttpPostData is just an alternative way to set |
| 257 |
HttpRequestBody. |
| 258 |
|
| 259 |
TODO: We may change this behavior in the future, to make it such that |
| 260 |
using HttpPostData will automatically set also HttpRequestBody contents |
| 261 |
to represent the given POST data, immediately. |
| 262 |
This way the "overriding" will be "whatever is set last, wins". |
| 263 |
For now, @italic(never use both HttpPostData and HttpRequestBody |
| 264 |
at the same time.) |
| 265 |
|
| 266 |
TODO: For now this is supported only when using FPC (not Delphi), |
| 267 |
on desktop or Android platforms (not iOS yet). |
| 268 |
It should be trivial to |
| 269 |
make it work in other cases too, just let us know |
| 270 |
( https://castle-engine.io/talk.php ). |
| 271 |
} |
| 272 |
function HttpRequestBody: TMemoryStream; |
| 273 |
|
| 274 |
{ Add additional HTTP headers, e.g. User-Agent. } |
| 275 |
procedure HttpHeader(const AKey, AValue: String); |
| 276 |
procedure AddHeader(const AKey, AValue: String); deprecated 'use HttpHeader'; |
| 277 |
|
| 278 |
{ When Status is dsSuccess or dsError, and request was using HTTP or HTTPS, |
| 279 |
this contains the HTTP status code. |
| 280 |
It is always 200 on success. } |
| 281 |
property HttpResponseCode: Integer read FHttpResponseCode; |
| 282 |
|
| 283 |
{ When Status is dsSuccess or dsError, and request was using HTTP or HTTPS, |
| 284 |
this contains the HTTP response headers. |
| 285 |
The NameValueSeparator is set to ':' which means you can use TStrings |
| 286 |
name/value mechanism to read the data, like this: |
| 287 |
|
| 288 |
@longCode(# |
| 289 |
LastModified := Download.HttpResponseHeaders.Values['Last-Modified']; |
| 290 |
#) |
| 291 |
|
| 292 |
Note that it is @nil in case of non-HTTP/HTTPS requests. |
| 293 |
} |
| 294 |
property HttpResponseHeaders: TStrings read FHttpResponseHeaders; |
| 295 |
end; |
| 296 |
|
| 297 |
{$endif} |
| 298 |
|
| 299 |
{$ifdef read_implementation} |
| 300 |
|
| 301 |
constructor TCastleDownload.Create(AOwner: TComponent); |
| 302 |
begin |
| 303 |
inherited Create(AOwner); |
| 304 |
FOwnsContents := true; |
| 305 |
end; |
| 306 |
|
| 307 |
destructor TCastleDownload.Destroy; |
| 308 |
begin |
| 309 |
ReleaseContents; |
| 310 |
if Reader <> nil then |
| 311 |
begin |
| 312 |
FreeAndNil(Reader.Contents); // Reader doesn't own Contents, so we need to take care of it |
| 313 |
FreeAndNil(Reader); |
| 314 |
end; |
| 315 |
if UpdateInitialized then |
| 316 |
begin |
| 317 |
ApplicationProperties.OnUpdate.Remove({$ifdef FPC}@{$endif}Update); |
| 318 |
UpdateInitialized := false; |
| 319 |
end; |
| 320 |
FreeAndNil(FHttpPostData); |
| 321 |
FreeAndNil(FHttpResponseHeaders); |
| 322 |
FreeAndNil(FHttpHeadersKeys); |
| 323 |
FreeAndNil(FHttpHeadersValues); |
| 324 |
FreeAndNil(FHttpRequestBody); |
| 325 |
inherited; |
| 326 |
end; |
| 327 |
|
| 328 |
procedure TCastleDownload.SetUrl(const Value: String); |
| 329 |
begin |
| 330 |
if FUrl <> Value then |
| 331 |
begin |
| 332 |
if Status = dsDownloading then |
| 333 |
raise Exception.Create('Cannot change URL when downloading'); |
| 334 |
FUrl := Value; |
| 335 |
end; |
| 336 |
end; |
| 337 |
|
| 338 |
procedure TCastleDownload.SetHttpMethod(const Value: THttpMethod); |
| 339 |
begin |
| 340 |
if FHttpMethod <> Value then |
| 341 |
begin |
| 342 |
if Status = dsDownloading then |
| 343 |
raise Exception.Create('Cannot change HTTP method when downloading'); |
| 344 |
FHttpMethod := Value; |
| 345 |
end; |
| 346 |
end; |
| 347 |
|
| 348 |
procedure TCastleDownload.SetOnFinish(const Value: TDownloadFinishedEvent); |
| 349 |
begin |
| 350 |
if not SameMethods(TMethod(FOnFinish), TMethod(Value)) then |
| 351 |
begin |
| 352 |
if Status = dsDownloading then |
| 353 |
raise Exception.Create('Cannot change OnFinish when downloading, you have to set it before Start to be reliable'); |
| 354 |
FOnFinish := Value; |
| 355 |
end; |
| 356 |
end; |
| 357 |
|
| 358 |
procedure TCastleDownload.SetOptions(const Value: TStreamOptions); |
| 359 |
begin |
| 360 |
if FOptions <> Value then |
| 361 |
begin |
| 362 |
if Status = dsDownloading then |
| 363 |
raise Exception.Create('Cannot change Options when downloading'); |
| 364 |
FOptions := Value; |
| 365 |
end; |
| 366 |
end; |
| 367 |
|
| 368 |
procedure TCastleDownload.ReleaseContents; |
| 369 |
begin |
| 370 |
if OwnsContents then |
| 371 |
FreeAndNil(FContents) |
| 372 |
else |
| 373 |
FContents := nil; |
| 374 |
end; |
| 375 |
|
| 376 |
procedure TCastleDownload.DoFinish; |
| 377 |
var |
| 378 |
FreeSender: Boolean; |
| 379 |
begin |
| 380 |
if Assigned(OnFinish) then |
| 381 |
begin |
| 382 |
FreeSender := false; |
| 383 |
OnFinish(Self, FreeSender); |
| 384 |
if FreeSender then |
| 385 |
Self.Destroy; |
| 386 |
end; |
| 387 |
end; |
| 388 |
|
| 389 |
procedure TCastleDownload.Start; |
| 390 |
|
| 391 |
{ Reset properties that describe the downloaded result. } |
| 392 |
procedure ClearPreviousDownload; |
| 393 |
begin |
| 394 |
ReleaseContents; |
| 395 |
if Reader <> nil then |
| 396 |
begin |
| 397 |
FreeAndNil(Reader.Contents); // Reader doesn't own Contents, so we need to take care of it |
| 398 |
FreeAndNil(Reader); |
| 399 |
end; |
| 400 |
FErrorMessage := ''; |
| 401 |
FMimeType := ''; |
| 402 |
FTotalBytes := -1; |
| 403 |
FDownloadedBytes := 0; |
| 404 |
FStatus := dsDownloading; |
| 405 |
end; |
| 406 |
|
| 407 |
{ Read synchronously. |
| 408 |
This calls DoFinish at end, and may free us. } |
| 409 |
procedure SynchronousRead(const ReadEvent: TUrlReadEvent; const RealUrl: String); |
| 410 |
var |
| 411 |
Size: Int64; |
| 412 |
begin |
| 413 |
try |
| 414 |
SetContentsApplyOptions(ReadEvent(RealUrl, FMimeType)); |
| 415 |
FStatus := dsSuccess; |
| 416 |
|
| 417 |
// determine FTotalBytes, FDownloadedBytes from stream Size |
| 418 |
try |
| 419 |
Size := FContents.Size; |
| 420 |
FTotalBytes := Size; |
| 421 |
FDownloadedBytes := Size; |
| 422 |
except |
| 423 |
on E: TObject do |
| 424 |
begin |
| 425 |
{ Gracefully handle exceptions from Size. |
| 426 |
E.g. TGZFileStream raises EZlibError: Compression stream seek error, |
| 427 |
testcase: castle-model-viewer escape_universe/trunk/data/entities/meteorite_4/animations.x3dv } |
| 428 |
FTotalBytes := -1; |
| 429 |
FDownloadedBytes := 0; |
| 430 |
// WritelnLog('Cannot determine Size of %s (the DownloadedBytes/TotalBytes will be 0/-1): %s', [ |
| 431 |
// FContents.ClassName, |
| 432 |
// ExceptMessage(E) |
| 433 |
// ]); |
| 434 |
end; |
| 435 |
end; |
| 436 |
|
| 437 |
except |
| 438 |
on E: TObject do |
| 439 |
begin |
| 440 |
FStatus := dsError; |
| 441 |
FErrorMessage := Format('Error when downloading "%s": ', [UriDisplay(Url)]) + |
| 442 |
ExceptMessage(E); |
| 443 |
{$if defined(VER3_2) and defined(DARWIN) and not defined(CASTLE_IOS)} |
| 444 |
if (E is ESocketError) and (URIProtocol(RealUrl) = 'https') then |
| 445 |
begin |
| 446 |
FErrorMessage += NL + |
| 447 |
'Warning: Https downloading with FPC 3.2.0 on macOS is broken for many hosts.' + NL + |
| 448 |
'Upgrade to FPC 3.3.1.' + NL + |
| 449 |
'See https://bugs.freepascal.org/view.php?id=37747 , https://github.com/castle-engine/castle-engine/issues/184 .'; |
| 450 |
end; |
| 451 |
{$endif} |
| 452 |
end; |
| 453 |
end; |
| 454 |
DoFinish; |
| 455 |
end; |
| 456 |
|
| 457 |
var |
| 458 |
P: String; |
| 459 |
RegisteredProtocol: TRegisteredProtocol; |
| 460 |
begin |
| 461 |
ClearPreviousDownload; |
| 462 |
|
| 463 |
P := URIProtocol(Url); |
| 464 |
|
| 465 |
if not UpdateInitialized then |
| 466 |
begin |
| 467 |
ApplicationProperties.OnUpdate.Add({$ifdef FPC}@{$endif}Update); |
| 468 |
UpdateInitialized := true; |
| 469 |
end; |
| 470 |
|
| 471 |
{ Handle early castle-data:, protocol to access application data, |
| 472 |
https://castle-engine.io/data . } |
| 473 |
if P = 'castle-data' then |
| 474 |
begin |
| 475 |
FFinalUrl := ResolveCastleDataURL(Url); |
| 476 |
P := URIProtocol(FFinalUrl); |
| 477 |
end else |
| 478 |
FFinalUrl := Url; |
| 479 |
|
| 480 |
if LogAllLoading then |
| 481 |
WritelnLog('Loading', 'Loading "%s"', [UriDisplay(FFinalUrl)]); |
| 482 |
|
| 483 |
RegisteredProtocol := RegisteredProtocols.Find(P); |
| 484 |
if RegisteredProtocol <> nil then |
| 485 |
begin |
| 486 |
if RegisteredProtocol.AsynchronousReader <> nil then |
| 487 |
begin |
| 488 |
Reader := RegisteredProtocol.AsynchronousReader.Create; |
| 489 |
Reader.Url := FFinalUrl; |
| 490 |
Reader.ForceSynchronous := ForceSynchronous; |
| 491 |
Reader.HttpMethod := HttpMethod; |
| 492 |
{ Assign from field FHttpPostData, not HttpPostData function, |
| 493 |
this way it may remain nil and not waste memory |
| 494 |
in case user didn't touch HttpPostData. } |
| 495 |
Reader.HttpPostData := FHttpPostData; |
| 496 |
Reader.HttpRequestBody := FHttpRequestBody; |
| 497 |
Reader.HttpHeadersKeys := FHttpHeadersKeys; |
| 498 |
Reader.HttpHeadersValues := FHttpHeadersValues; |
| 499 |
Reader.Start; |
| 500 |
end else |
| 501 |
if Assigned(RegisteredProtocol.ReadEvent) then |
| 502 |
begin |
| 503 |
SynchronousRead(RegisteredProtocol.ReadEvent, FFinalUrl); |
| 504 |
end else |
| 505 |
begin |
| 506 |
FStatus := dsError; |
| 507 |
raise EDownloadError.CreateFmt('Cannot read URLs with protocol "%s"', [P]); |
| 508 |
end; |
| 509 |
end else |
| 510 |
begin |
| 511 |
FStatus := dsError; |
| 512 |
raise EDownloadError.CreateFmt('Downloading from protocol "%s" is not supported', [P]); |
| 513 |
end; |
| 514 |
end; |
| 515 |
|
| 516 |
procedure TCastleDownload.WaitForFinish; |
| 517 |
begin |
| 518 |
while Status = dsDownloading do |
| 519 |
begin |
| 520 |
Update(nil); |
| 521 |
Sleep(10); |
| 522 |
end; |
| 523 |
end; |
| 524 |
|
| 525 |
procedure TCastleDownload.Update(Sender: TObject); |
| 526 |
begin |
| 527 |
if Status = dsDownloading then |
| 528 |
begin |
| 529 |
Assert(Reader <> nil); |
| 530 |
|
| 531 |
Reader.Update; |
| 532 |
|
| 533 |
Assert(Reader.Status <> dsNotStarted); |
| 534 |
FStatus := Reader.Status; |
| 535 |
FDownloadedBytes := Reader.DownloadedBytes; |
| 536 |
FTotalBytes := Reader.TotalBytes; |
| 537 |
FMimeType := Reader.MimeType; |
| 538 |
|
| 539 |
if FStatus in [dsError, dsSuccess] then |
| 540 |
begin |
| 541 |
// copy stuff from Reader |
| 542 |
if FStatus = dsSuccess then |
| 543 |
Assert(Reader.Contents <> nil); // in this case, Reader.Contents is obligatory |
| 544 |
if Reader.Contents <> nil then // in this case, Reader.Contents is optional |
| 545 |
begin |
| 546 |
SetContentsApplyOptions(Reader.Contents); |
| 547 |
Reader.Contents := nil; // not valid anymore, SetContentsApplyOptions took ownership |
| 548 |
end; |
| 549 |
FHttpResponseCode := Reader.HttpResponseCode; |
| 550 |
FHttpResponseHeaders := Reader.HttpResponseHeaders; |
| 551 |
FFinalUrl := Reader.FinalUrl; |
| 552 |
Reader.HttpResponseHeaders := nil; // do not free HttpResponseHeaders in Reader destructor |
| 553 |
if FStatus = dsError then |
| 554 |
FErrorMessage := Reader.ErrorMessage; |
| 555 |
|
| 556 |
FreeAndNil(Reader); |
| 557 |
DoFinish; |
| 558 |
Exit; // DoFinish possibly freed us, so Exit and do not access any own fields |
| 559 |
end; |
| 560 |
|
| 561 |
// Reader continues to exist if and only if still dsDownloading |
| 562 |
Assert((Reader <> nil) = (FStatus = dsDownloading)); |
| 563 |
end; |
| 564 |
end; |
| 565 |
|
| 566 |
procedure CopyStreamWithoutRewinding(const Dest: TMemoryStream; const Source: TStream); |
| 567 |
begin |
| 568 |
{ Do not call Dest.LoadFromStream(Source), as it does "Source.Position := 0" |
| 569 |
(at least in FPC) which should not be required, and actually fails with |
| 570 |
some stream implementations. |
| 571 |
|
| 572 |
Testcase: open with castle-model-viewer demo-models/x3d/data_uri.x3dv . |
| 573 |
The TUrlData.Read returns TBase64DecodingStream which doesn't allow assigning Position. |
| 574 |
} |
| 575 |
if Source.Position <> 0 then |
| 576 |
Source.Position := 0; // set Source.Position, but only if it's not already 0 |
| 577 |
// raise EDownloadError.CreateFmt('Underlying stream %s position should be 0, but is %d', [ |
| 578 |
// Source.ClassName, |
| 579 |
// Source.Position |
| 580 |
// ]); |
| 581 |
Dest.SetSize(Source.Size); |
| 582 |
if Source.Size <> 0 then |
| 583 |
Source.ReadBuffer(Dest.Memory^, Source.Size); |
| 584 |
end; |
| 585 |
|
| 586 |
procedure TCastleDownload.SetContentsApplyOptions(UnderlyingStream: TStream); |
| 587 |
|
| 588 |
{ Load Stream to TMemoryStream. |
| 589 |
Sets given Stream to @nil (it is freed by this function). } |
| 590 |
function CreateMemoryStream(var Stream: TStream): TMemoryStream; overload; |
| 591 |
begin |
| 592 |
Result := TMemoryStream.Create; |
| 593 |
try |
| 594 |
CopyStreamWithoutRewinding(Result, Stream); |
| 595 |
FreeAndNil(Stream); |
| 596 |
Result.Position := 0; { rewind for easy reading } |
| 597 |
except |
| 598 |
FreeAndNil(Result); raise; |
| 599 |
end; |
| 600 |
end; |
| 601 |
|
| 602 |
{ Decompress gzipped FileName. |
| 603 |
When ForceMemoryStream, always returns TMemoryStream. |
| 604 |
Sets given Stream to @nil (it is owned by us now, possibly it is freed by this function). } |
| 605 |
function ReadGzipped(var Stream: TStream; const ForceMemoryStream: boolean): TStream; |
| 606 |
var |
| 607 |
NewResult: TMemoryStream; |
| 608 |
begin |
| 609 |
Result := TGZFileStream.Create(Stream, false); |
| 610 |
try |
| 611 |
Stream := nil; // Stream is owned by Result now |
| 612 |
|
| 613 |
if ForceMemoryStream then |
| 614 |
begin |
| 615 |
{ This case happens e.g. when reading .x3d.gz, that is gzipped |
| 616 |
(must pass through TGZFileStream) |
| 617 |
but also needs OnLoadForceMemoryStream. } |
| 618 |
NewResult := TMemoryStream.Create; |
| 619 |
ReadGrowingStream(Result, NewResult, true); |
| 620 |
FreeAndNil(Result); |
| 621 |
Result := NewResult; |
| 622 |
end; |
| 623 |
except |
| 624 |
FreeAndNil(Result); raise; |
| 625 |
end; |
| 626 |
end; |
| 627 |
|
| 628 |
begin |
| 629 |
// unpack gzip if requested |
| 630 |
if soGzip in Options then |
| 631 |
FContents := ReadGzipped(UnderlyingStream, soForceMemoryStream in Options) |
| 632 |
else |
| 633 |
if (soForceMemoryStream in Options) and |
| 634 |
// if UnderlyingStream is already TMemoryStream, like with data URI, then we're OK |
| 635 |
(not (UnderlyingStream is TMemoryStream)) then |
| 636 |
FContents := CreateMemoryStream(UnderlyingStream) |
| 637 |
else |
| 638 |
FContents := UnderlyingStream; |
| 639 |
end; |
| 640 |
|
| 641 |
function TCastleDownload.PostData: TStrings; |
| 642 |
begin |
| 643 |
Result := HttpPostData; |
| 644 |
end; |
| 645 |
|
| 646 |
procedure TCastleDownload.AddHeader(const AKey, AValue: String); |
| 647 |
begin |
| 648 |
HttpHeader(AKey, AValue); |
| 649 |
end; |
| 650 |
|
| 651 |
function TCastleDownload.HttpPostData: TStrings; |
| 652 |
begin |
| 653 |
// FHttpPostData is created on-demand, because it is often not needed |
| 654 |
if FHttpPostData = nil then |
| 655 |
FHttpPostData := TStringList.Create; |
| 656 |
Result := FHttpPostData; |
| 657 |
end; |
| 658 |
|
| 659 |
function TCastleDownload.HttpRequestBody: TMemoryStream; |
| 660 |
begin |
| 661 |
// FHttpRequestBody is created on-demand, because it is often not needed |
| 662 |
if FHttpRequestBody = nil then |
| 663 |
FHttpRequestBody := TMemoryStream.Create; |
| 664 |
Result := FHttpRequestBody; |
| 665 |
end; |
| 666 |
|
| 667 |
procedure TCastleDownload.HttpHeader(const AKey, AValue: String); |
| 668 |
begin |
| 669 |
// 2 string lists are created on-demand, because they are often not needed |
| 670 |
if FHttpHeadersKeys = nil then |
| 671 |
FHttpHeadersKeys := TStringList.Create; |
| 672 |
if FHttpHeadersValues = nil then |
| 673 |
FHttpHeadersValues := TStringList.Create; |
| 674 |
FHttpHeadersKeys.Append(AKey); |
| 675 |
FHttpHeadersValues.Append(AValue); |
| 676 |
Assert(FHttpHeadersKeys.Count = FHttpHeadersValues.Count); |
| 677 |
end; |
| 678 |
|
| 679 |
{$endif} |