Skip to content

Commit

Permalink
refactore: improve auto select of User-Agent
Browse files Browse the repository at this point in the history
  • Loading branch information
kfilippenok committed Dec 16, 2024
1 parent 68665ba commit 4173526
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
24 changes: 21 additions & 3 deletions src/TilesManipulations/TilesManipulations.Core.pas
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ TProviderClient = class(TFPCustomHTTPClient)
strict private
FUserAgents: TStringList;
FUserAgent: String;
FUASelected: Boolean;
strict private
procedure SetupUserAgents; virtual;
procedure AutoSelectUserAgent(const AURL: String); virtual; final;
Expand Down Expand Up @@ -360,9 +361,12 @@ procedure TProviderClient.AutoSelectUserAgent(const AURL: String);
Complete: Boolean;
LException: Exception;
begin
Write('Setting up settings for connection... ');

Complete := False;
for i := 0 to FUserAgents.Count-1 do
try
Self.AddHeader('User-Agent', FUserAgents[i]);
Self.Get(AURL);
Complete := True;
except
Expand All @@ -372,8 +376,14 @@ procedure TProviderClient.AutoSelectUserAgent(const AURL: String);
Continue;
end;
end;
if not Complete then

if Complete then
WriteLn('Ok')
else
begin
WriteLn('Fail');
raise LException;
end;
end;

constructor TProviderClient.Create(AOwner: TComponent);
Expand All @@ -385,6 +395,7 @@ constructor TProviderClient.Create(AOwner: TComponent);
Self.ConnectTimeOut := 10000;
FUserAgents := TStringList.Create;
SetupUserAgents;
FUASelected := False;
end;

destructor TProviderClient.Destroy;
Expand All @@ -400,6 +411,14 @@ function TProviderClient.ReceiveTile(const AURL: String): TBGRABitmap;
begin
Result := nil;

if not FUASelected then
try
AutoSelectUserAgent(AURL);
except
on E: Exception do
raise;
end;

WriteLn(Format('TileLink: %s', [AURL]));
try
LMemoryStream := TMemoryStream.Create;
Expand All @@ -410,8 +429,6 @@ function TProviderClient.ReceiveTile(const AURL: String): TBGRABitmap;
except
on E: ESocketError do
continue;
on E: EHTTPClient do
AutoSelectUserAgent(AURL);
end;
LMemoryStream.Position := 0;
Result.LoadFromStream(LMemoryStream);
Expand Down Expand Up @@ -444,6 +461,7 @@ destructor TProvider.Destroy;

function TProvider.GiveTile(AZoom: Integer; AX, AY: Integer): TBGRABitmap;
begin
Write(Name + ': ');
Result := FClient.ReceiveTile(Format('%s/%d/%d/%d.png',[URL, AZoom, AX, AY]));
end;

Expand Down
2 changes: 1 addition & 1 deletion src/tilesdownloader.lpr
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ ATilesDownloader = class(TCustomApplication)
begin
TilesManipulator := TTilesManipulator.Create;
TilesManipulator.Layers.Add(Providers['osm-standard'], TFilterGrayscale.Create);
//TilesManipulator.Layers[0].Load(0, 0, 0);
TilesManipulator.Layers[0].Load(0, 0, 0);

TilesManipulator.Free;

Expand Down

0 comments on commit 4173526

Please sign in to comment.