Unit CastleDownload

Description

Read and write stream contents from URLs.

Source: files/castledownload.pas (line 17).

Uses

Overview

Classes, Interfaces, Objects and Records

Name Description
Class TUrlAsynchronousReader Implement this class, and pass to RegisterUrlProtocol, to read protocols asynchronously (such that TCastleDownload can read them asynchronously).
Class EProtocolAlreadyRegistered  
Class TRegisteredProtocol Details of the registered URL protocol.
Class EDownloadError  
Class ESaveError  
Class TCastleDownload Download an URL (possibly making an HTTP(S) request) asynchronously, without blocking the application.
Class TCastleTextReaderWriter Common class for reading or writing a stream like a text file.
Class TCastleTextReader Read any stream like a text file.
Class TCastleTextWriter Write to a stream like to a text file.
Class TStringsHelper Copyright 2013-2020 Michalis Kamburelis.

Functions and Procedures

function RegisterUrlProtocol(const Protocol: String; const ReadEvent: TUrlReadEvent = nil; const WriteEvent: TUrlWriteEvent = nil; const AsynchronousReader: TUrlAsynchronousReaderClass = nil; const DetectMimeTypeFromExtension: Boolean = true): TRegisteredProtocol;
function RegisteredUrlProtocol(const Protocol: String): Boolean;
function FindRegisteredUrlProtocol(const Protocol: String): TRegisteredProtocol;
procedure UnregisterUrlProtocol(const Protocol: String);
function Download(const Url: String; const Options: TStreamOptions = []): TStream; overload;
function Download(const Url: String; const Options: TStreamOptions; out MimeType: string): TStream; overload;
function GetEnableNetwork: Boolean; deprecated 'use EnableBlockingDownloads';
procedure SetEnableNetwork(const Value: Boolean); deprecated 'use EnableBlockingDownloads';
function UrlSaveStream(const Url: String; const Options: TSaveStreamOptions = []): TStream;
function CreateReadFileStream(const Url: String): TStream; deprecated 'use Download(Url, [soForceMemoryStream])';
procedure StreamSaveToFile(Stream: TStream; const Url: String);

Types

TDownloadStatus = (...);
THttpMethod = (...);
TUrlAsynchronousReaderClass = class of TUrlAsynchronousReader;
TUrlReadEvent = function ( const Url: String; out MimeType: string): TStream of object;
TUrlWriteEvent = function(const Url: String): TStream of object;
TUrlExistsEvent = function(const Url: String): TUriExists of object;
TUrlFindFilesEvent = procedure(const UrlPath, Mask: String; const FileEvent: TFoundFileMethod; var StopSearch: Boolean) of object;
TStreamOption = (...);
TStreamOptions = set of TStreamOption;
TDownloadFinishedEvent = procedure (const Sender: TCastleDownload; var FreeSender: Boolean) of object;
TSaveStreamOption = (...);
TSaveStreamOptions = set of TSaveStreamOption;
TTextReaderWriter = TCastleTextReaderWriter deprecated 'use TCastleTextReaderWriter instead';
TTextReader = TCastleTextReader deprecated 'use TCastleTextReader instead';
TTextWriter = TCastleTextWriter deprecated 'use TCastleTextWriter instead';

Variables

LogAllLoading: boolean = false;
EnableBlockingDownloads: boolean = false;
property EnableNetwork: Boolean read GetEnableNetwork write SetEnableNetwork;

Description

Functions and Procedures

function RegisterUrlProtocol(const Protocol: String; const ReadEvent: TUrlReadEvent = nil; const WriteEvent: TUrlWriteEvent = nil; const AsynchronousReader: TUrlAsynchronousReaderClass = nil; const DetectMimeTypeFromExtension: Boolean = true): TRegisteredProtocol;

Register how we can load and/or save the URLs with given protocol.

All the parameters except the first, Protocol, are optional. You can leave these parameters at default values, and in effect the corresponding fields of TRegisteredProtocol will be set to Nil. You can later configure protocol events by assigning properties of the returned TRegisteredProtocol.

Parameters
ReadEvent
See TRegisteredProtocol.ReadEvent.
WriteEvent
See TRegisteredProtocol.WriteEvent.
AsynchronousReader
See TRegisteredProtocol.AsynchronousReader.
Returns

Instance of TRegisteredProtocol. You can configure handling of given protocol further by assigning properties of this instance. Do not free this instance yourself. It will be automatically freed when you call UnregisterUrlProtocol.

Exceptions raised
EProtocolAlreadyRegistered
If the protocol handlers are already registered.

Source: files/castledownload_register.inc (line 250).

function RegisteredUrlProtocol(const Protocol: String): Boolean;

Is given protocol name registered with RegisterUrlProtocol. The Protocol searching is case-insensitive. This is a shortcut for FindRegisteredUrlProtocol(Protocol) <> nil.

Source: files/castledownload_register.inc (line 259).

function FindRegisteredUrlProtocol(const Protocol: String): TRegisteredProtocol;

If the given protocol is registered with RegisterUrlProtocol, returns the TRegisteredProtocol instance that describes how to handle this protocol. The Protocol searching is case-insensitive. Returns Nil if not found.

Source: files/castledownload_register.inc (line 265).

procedure UnregisterUrlProtocol(const Protocol: String);

Unregister protocol, reverting the RegisterUrlProtocol.

Source: files/castledownload_register.inc (line 268).

function Download(const Url: String; const Options: TStreamOptions = []): TStream; overload;

Return a stream to read given URL. Returned stream is suitable only for reading, and the initial position is always at the beginning. Overloaded version also returns a MIME type (or '' if unknown).

Any errors are reported by raising exceptions.

All the supported URL protocols are documented in our manual: https://castle-engine.io/url . They include:

This routine makes a synchronous (blocking) downloading. Which means that if you use a network URL (like http://...) then your application will wait until the data arrives from the Internet. There may be a timeout of the request (so your application will not hang indefinitely), but still your code (or user) have no way to cancel or watch the progress of this operation. This is why http/https support is disabled by default (see EnableBlockingDownloads). This is sometimes acceptable (e.g. if you're waiting during the "loading" process, and the data just has to be downloaded in order to continue), and it's really easy to use (you just download data exactly the same way like you open a local file).

You can use asynchronous downloading through the TCastleDownload class instead.

Exceptions raised
EDownloadError
In case of problems loading from this URL.

Any exceptions inside internal loading routines, like EFOpenError or EStreamError, are internally caught and changed to EDownloadError.

Source: files/castledownload_synchronous.inc (line 118).

function Download(const Url: String; const Options: TStreamOptions; out MimeType: string): TStream; overload;

This item has no description.

Source: files/castledownload_synchronous.inc (line 119).

function GetEnableNetwork: Boolean; deprecated 'use EnableBlockingDownloads';

Warning: this symbol is deprecated: use EnableBlockingDownloads

This item has no description.

Source: files/castledownload_synchronous.inc (line 123).

procedure SetEnableNetwork(const Value: Boolean); deprecated 'use EnableBlockingDownloads';

Warning: this symbol is deprecated: use EnableBlockingDownloads

This item has no description.

Source: files/castledownload_synchronous.inc (line 124).

function UrlSaveStream(const Url: String; const Options: TSaveStreamOptions = []): TStream;

Create a stream to save (write to) a given URL.

For example, to save a file. When you use URLSaveStream with URL with a file protocol, or just with a regular filename, it will return a TFileStream instance to write this file.

This function supports any CGE custom protocol registered by RegisterUrlProtocol, if only you provided WriteEvent: TUrlWriteEvent when registering that protocol.

Note: When saving to castle-data URL, remember that on some platforms (like Android) or installation methods (like system-wide installation on Linux or Windows) the game data is read-only. To be portable, you should never use URLSaveStream with the castle-data protocol. It is only useful in limited cases when you know that you distribute your game in such way (and users install it in such way) and on such platforms, that the "data" directory is writable.

On Android, you should use the "write_external_storage" service to be able to write storage files (e.g. to SD card). This means files accessed by the 'file' protocol. See https://castle-engine.io/android-Services .

Example usage:

var
  Stream: TStream;
  I: Uint32;
begin
  Stream := URLSaveStream('file:///tmp/foo.txt', []);
  try
    // write some strings
    WritelnStr(Stream, 'Some string');
    WritelnStr(Stream, 'Another string');
    // write some binary data
    I := 666;
    Stream.WriteBuffer(I, SizeOf(I));
  finally FreeAndNil(Stream) end;
end;

Exceptions raised
ESaveError
In case of problems saving this URL.
Exception
Various TStream instances (used internally by this function) may raise exceptions in case the stream cannot be created for saving. Right now, we simply let these exceptions to "pass through" from this function (instead of catching and re-raising). So be ready that this function may raise any Exception class.

Source: files/castledownload_save.inc (line 79).

function CreateReadFileStream(const Url: String): TStream; deprecated 'use Download(Url, [soForceMemoryStream])';

Warning: this symbol is deprecated: use Download(Url, [soForceMemoryStream])

Open a proper stream to read a file, fast (with buffering) and with seeking. This gives you a stream most comfortable for reading (buffering means that you can read small, comfortable pieces of it; seeking means you can jump freely to various file positions, back and forward).

On different OSes or even compilers this may require a little different stream, so it's safest to just use this function. For example, traditional Classes.TFileStream doesn't do buffering. Although under Linux, the buffering of file handles is done at kernel level (so everything works fast), on Windows the slowdown is noticeable. This function will always create proper stream descendant, eventually wrapping some standard stream in a buffered stream with full seeking capability.

Instead of this, use Download with [soForceMemoryStream].

Source: files/castledownload_utils.inc (line 34).

procedure StreamSaveToFile(Stream: TStream; const Url: String);

Save the contents of given Stream to an Url.

Source: files/castledownload_utils.inc (line 37).

Types

TDownloadStatus = (...);

See TCastleDownload.Status.

Values
  • dsNotStarted
  • dsDownloading
  • dsError
  • dsSuccess

Source: files/castledownload_register.inc (line 21).

THttpMethod = (...);

See TCastleDownload.HttpMethod.

Values
  • hmGet
  • hmPost
  • hmPut
  • hmDelete
  • hmOptions
  • hmHead

Source: files/castledownload_register.inc (line 24).

TUrlAsynchronousReaderClass = class of TUrlAsynchronousReader;

This item has no description.

Source: files/castledownload_register.inc (line 107).

TUrlReadEvent = function ( const Url: String; out MimeType: string): TStream of object;

Event called when Download function wants to download URL with this protocol. Use with RegisterUrlProtocol and TRegisteredProtocol.ReadEvent.

TUrlWriteEvent = function(const Url: String): TStream of object;

Event called when URLSaveStream function wants to save URL with this protocol. Use with RegisterUrlProtocol and TRegisteredProtocol.WriteEvent.

TUrlExistsEvent = function(const Url: String): TUriExists of object;

Event called when UriExists function wants to know whether given URL exists, and if it is a directory or file.

When this is not assigned, UriExists answers ueUnknown for all URLs, which just means "we don't know, you can try to load the URL and see if it fails with an exception".

Use with RegisterUrlProtocol and TRegisteredProtocol.ExistsEvent.

TUrlFindFilesEvent = procedure(const UrlPath, Mask: String; const FileEvent: TFoundFileMethod; var StopSearch: Boolean) of object;

Event called with FindFiles is used to search within a directory with the registered URL protocol.

Should call FileEvent for all files and directories whose name matches Mask within directory UrlPath. To every call, pass regular TFoundFileMethod parameters:

  • FileInfo: TFileInfo, with all fields filled.

  • StopSearch: Boolean. Pass our parameter StopSearch to this. Initially False when this is executed. Stop enumerating if caller answers True.

Parameters
UrlPath
Absolute URL path where to search. E.g. this is a directory like 'file:///home/user/dir/'.
Mask
The mask to search for, with wildcards ? and *. E.g. '*.png' or '*.jpg'.
TStreamOption = (...);

Options for the Download function.

Values
  • soForceMemoryStream: Force result to be a TCustomMemoryStream, with contents fully loaded to the memory, and freely seekable (you can move back and forth within). Without this option, Download may return other streams, for example TFileStream (that may not have good buffering, depending on OS) or TBase64DecodingStream (that may not allow seeking).

    Using TCustomMemoryStream means that reading is fast and comfortable, but eats memory and doesn't allow to simultaneously read and process the contents (the file must be fully loaded, e.g. downloaded from the Internet, and ungzipped, before this function returns). So use this option only for files that aren't too big.

    For larger files, you usually don't want to use this option, instead wrap result in TBufferedReadStream.

  • soGzip: Filter the contents through gzip decompression.

Source: files/castledownload_synchronous.inc (line 38).

TStreamOptions = set of TStreamOption;

This item has no description.

Source: files/castledownload_synchronous.inc (line 59).

TDownloadFinishedEvent = procedure (const Sender: TCastleDownload; var FreeSender: Boolean) of object;

This item has no description.

TSaveStreamOption = (...);

Options for the UrlSaveStream function.

Values
  • ssoGzip: Filter the contents through gzip compression.

Source: files/castledownload_save.inc (line 21).

TSaveStreamOptions = set of TSaveStreamOption;

This item has no description.

Source: files/castledownload_save.inc (line 25).

TTextReaderWriter = TCastleTextReaderWriter deprecated 'use TCastleTextReaderWriter instead';

Warning: this symbol is deprecated: use TCastleTextReaderWriter instead

This item has no description.

Source: files/castledownload_text.inc (line 117).

TTextReader = TCastleTextReader deprecated 'use TCastleTextReader instead';

Warning: this symbol is deprecated: use TCastleTextReader instead

This item has no description.

Source: files/castledownload_text.inc (line 118).

TTextWriter = TCastleTextWriter deprecated 'use TCastleTextWriter instead';

Warning: this symbol is deprecated: use TCastleTextWriter instead

This item has no description.

Source: files/castledownload_text.inc (line 119).

Variables

LogAllLoading: boolean = false;

Log (through CastleLog) all loading, that is: all calls to Download. This allows to easily check e.g. whether the engine is not loading something during the game (which usually badly affects the performance).

Source: files/castledownload_synchronous.inc (line 23).

EnableBlockingDownloads: boolean = false;

Does Download (synchronous downloading routine) support http and https protocol. This is by default disabled, as it means that a call to Download may block your application, for arbitrarily long time, and you have no way to interrupt it. It is recommended to use asynchronous downloading, using TCastleDownload, to download resources over the network.

Source: files/castledownload_synchronous.inc (line 31).

property EnableNetwork: Boolean read GetEnableNetwork write SetEnableNetwork;

This item has no description.

Source: files/castledownload_synchronous.inc (line 126).


Generated by PasDoc 0.17.0.snapshot.