-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMapService.php
More file actions
421 lines (399 loc) · 13 KB
/
MapService.php
File metadata and controls
421 lines (399 loc) · 13 KB
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
<?php
/**
* Nextcloud - gpxpod
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Julien Veyssier
* @copyright Julien Veyssier 2023
*/
namespace OCA\GpxPod\Service;
use Exception;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use OCA\GpxPod\AppInfo\Application;
use OCA\GpxPod\Db\TileServer;
use OCP\AppFramework\Http\ContentSecurityPolicy;
use OCP\Http\Client\IClient;
use OCP\Http\Client\IClientService;
use OCP\IAppConfig;
use OCP\IL10N;
use OCP\IURLGenerator;
use Psr\Log\LoggerInterface;
use Throwable;
class MapService {
private IClient $client;
public function __construct(
IClientService $clientService,
private LoggerInterface $logger,
private IURLGenerator $urlGenerator,
private IL10N $l10n,
private IAppConfig $appConfig,
) {
$this->client = $clientService->newClient();
}
/**
* @param ContentSecurityPolicy $csp
* @param TileServer[] $extraTileServers
* @return void
*/
public function addPageCsp(ContentSecurityPolicy $csp, array $extraTileServers): void {
$csp
// raster tiles
->addAllowedConnectDomain('https://*.openstreetmap.org')
->addAllowedConnectDomain('https://server.arcgisonline.com')
->addAllowedConnectDomain('https://*.tile.thunderforest.com')
->addAllowedConnectDomain('https://stamen-tiles.a.ssl.fastly.net')
->addAllowedConnectDomain('https://tiles.stadiamaps.com')
->addAllowedConnectDomain('https://tile.osmand.net')
// vector tiles
->addAllowedConnectDomain('https://api.maptiler.com')
// for https://api.maptiler.com/resources/logo.svg
->addAllowedImageDomain('https://api.maptiler.com')
// nominatim (not needed, we proxy requests through the server)
//->addAllowedConnectDomain('https://nominatim.openstreetmap.org')
// maplibre-gl
->addAllowedWorkerSrcDomain('blob:');
foreach ($extraTileServers as $ts) {
$type = $ts->getType();
$url = $ts->getUrl();
$domain = parse_url($url, PHP_URL_HOST);
$scheme = parse_url($url, PHP_URL_SCHEME);
// extra raster tile servers
if ($type === Application::TILE_SERVER_RASTER) {
$domain = str_replace('{s}', '*', $domain);
if ($scheme === 'http') {
$csp->addAllowedConnectDomain('http://' . $domain);
} else {
$csp->addAllowedConnectDomain('https://' . $domain);
}
} else {
// extra vector tile servers
if ($scheme === 'http') {
$csp->addAllowedConnectDomain('http://' . $domain);
} else {
$csp->addAllowedConnectDomain('https://' . $domain);
}
}
};
}
/**
* @param string $service
* @param int $x
* @param int $y
* @param int $z
* @param string|null $s
* @return array
* @throws Exception
*/
public function getRasterTile(string $service, int $x, int $y, int $z, ?string $s = null): array {
$options = [];
if ($service === 'osm') {
// $url = 'https://' . $s . '.tile.openstreetmap.org/' . $z . '/' . $x . '/' . $y . '.png';
// recommended tile server: https://operations.osmfoundation.org/policies/tiles/
$url = 'https://tile.openstreetmap.org/' . $z . '/' . $x . '/' . $y . '.png';
} elseif ($service === 'ocm') {
if ($s === null) {
$s = 'abc'[mt_rand(0, 2)];
}
// https://{s}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png
$url = 'https://' . $s . '.tile.thunderforest.com/cycle/' . $z . '/' . $x . '/' . $y . '.png';
} elseif ($service === 'osm-highres') {
$url = 'https://tile.osmand.net/hd/' . $z . '/' . $x . '/' . $y . '.png';
} elseif ($service === 'ocm-highres') {
if ($s === null) {
$s = 'abc'[mt_rand(0, 2)];
}
$url = 'https://' . $s . '.tile.thunderforest.com/cycle/' . $z . '/' . $x . '/' . $y . '@2x.png';
} elseif ($service === 'esri-topo') {
$url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/' . $z . '/' . $y . '/' . $x;
} elseif ($service === 'watercolor') {
$url = 'https://tiles.stadiamaps.com/styles/stamen_watercolor/' . $z . '/' . $x . '/' . $y . '.jpg';
// see https://docs.stadiamaps.com/authentication
$options['headers'] = ['Origin' => 'https://nextcloud.local'];
// old URLs that don't work
// $url = 'http://' . $s . '.tile.stamen.com/watercolor/' . $z . '/' . $x . '/' . $y . '.jpg';
// $url = 'https://stamen-tiles.' . $s . '.ssl.fastly.net/watercolor/' . $z . '/' . $x . '/' . $y . '.jpg';
} elseif ($service === 'stadia-sat') {
$url = 'https://tiles.stadiamaps.com/tiles/alidade_satellite/' . $z . '/' . $x . '/' . $y . '.jpg';
$options['headers'] = ['Origin' => 'https://nextcloud.local'];
} else {
$url = 'https://tile.openstreetmap.org/' . $z . '/' . $x . '/' . $y . '.png';
}
$response = $this->client->get($url, $options);
$body = $response->getBody();
if (is_resource($body)) {
$content = stream_get_contents($body);
$body = $content === false
? null
: $content;
}
return [
'body' => $body,
'content-type' => $response->getHeader('content-type'),
];
}
private function getVectorProxyRequestOptions() {
$instanceUrl = $this->urlGenerator->getBaseUrl();
return [
'headers' => [
'Origin' => $instanceUrl,
],
];
}
/**
* @param string $version
* @param string|null $key
* @return array
* @throws Exception
*/
public function getMapTilerStyle(string $version, ?string $key = null): array {
$url = 'https://api.maptiler.com/maps/' . $version . '/style.json';
if ($key !== null) {
$url .= '?key=' . $key;
}
$body = $this->client->get($url, $this->getVectorProxyRequestOptions())->getBody();
if (is_resource($body)) {
$content = stream_get_contents($body);
} else {
$content = $body;
}
$replacementUrl = $this->urlGenerator->linkToRouteAbsolute(Application::APP_ID . '.page.index') . 'maptiler';
$style = json_decode(preg_replace('/https:\/\/api\.maptiler\.com/', $replacementUrl, $content), true);
foreach ($style['layers'] as $i => $layer) {
if (isset($layer['layout']) && is_array($layer['layout']) && empty($layer['layout'])) {
$style['layers'][$i]['layout'] = (object)[];
}
}
return $style;
}
/**
* @param string $fontstack
* @param string $range
* @param string|null $key
* @return array
* @throws Exception
*/
public function getMapTilerFont(string $fontstack, string $range, ?string $key = null): array {
// https://api.maptiler.com/fonts/{fontstack}/{range}.pbf?key=' + apiKey
$url = 'https://api.maptiler.com/fonts/' . $fontstack . '/' . $range . '.pbf';
if ($key !== null) {
$url .= '?key=' . $key;
}
$response = $this->client->get($url, $this->getVectorProxyRequestOptions());
$body = $response->getBody();
if (is_resource($body)) {
$content = stream_get_contents($body);
$body = $content === false
? null
: $content;
}
return [
'body' => $body,
'content-type' => $response->getHeader('content-type'),
];
}
/**
* @param string $version
* @param string|null $key
* @return array
* @throws Exception
*/
public function getMapTilerTiles(string $version, ?string $key = null): array {
$url = 'https://api.maptiler.com/tiles/' . $version . '/tiles.json';
if ($key !== null) {
$url .= '?key=' . $key;
}
$body = $this->client->get($url, $this->getVectorProxyRequestOptions())->getBody();
if (is_resource($body)) {
$content = stream_get_contents($body);
if ($content === false) {
throw new Exception('No content');
}
} else {
$content = $body;
}
$replacementUrl = $this->urlGenerator->linkToRouteAbsolute(Application::APP_ID . '.page.index') . 'maptiler';
return json_decode(preg_replace('/https:\/\/api\.maptiler\.com/', $replacementUrl, $content), true);
}
/**
* @param string $version
* @param int $x
* @param int $y
* @param int $z
* @param string $ext
* @param string|null $key
* @return array
* @throws Exception
*/
public function getMapTilerTile(string $version, int $x, int $y, int $z, string $ext, ?string $key = null): array {
$url = 'https://api.maptiler.com/tiles/' . $version . '/' . $z . '/' . $x . '/' . $y . '.' . $ext;
if ($key !== null) {
$url .= '?key=' . $key;
}
$response = $this->client->get($url, $this->getVectorProxyRequestOptions());
$body = $response->getBody();
$headers = $response->getHeaders();
return [
'body' => $body,
'headers' => $headers,
];
}
/**
* @param string $version
* @param string $size
* @return array
* @throws Exception
*/
public function getMapTilerSpriteJson(string $version, string $size): array {
$url = 'https://api.maptiler.com/maps/' . $version . '/sprite' . $size . '.json';
$body = $this->client->get($url, $this->getVectorProxyRequestOptions())->getBody();
if (is_resource($body)) {
$content = stream_get_contents($body);
if ($content === false) {
throw new Exception('No content');
}
return json_decode($content, true);
}
return json_decode($body, true);
}
/**
* @param string $version
* @param string $size
* @param string $ext
* @return array
* @throws Exception
*/
public function getMapTilerSpriteImage(string $version, string $size, string $ext): array {
$url = 'https://api.maptiler.com/maps/' . $version . '/sprite' . $size . '.' . $ext;
$response = $this->client->get($url, $this->getVectorProxyRequestOptions());
$body = $response->getBody();
$headers = $response->getHeaders();
return [
'body' => $body,
'headers' => $headers,
];
}
/**
* @param string $name
* @return array
* @throws Exception
*/
public function getMapTilerResource(string $name): array {
$url = 'https://api.maptiler.com/resources/' . $name;
$response = $this->client->get($url, $this->getVectorProxyRequestOptions());
$body = $response->getBody();
$headers = $response->getHeaders();
return [
'body' => $body,
'headers' => $headers,
];
}
/**
* Search items
*
* @param string $query
* @param string $format
* @param array $extraParams
* @param int $offset
* @param int $limit
* @return array request result
*/
public function searchLocation(string $query, string $format = 'json', array $extraParams = [], int $offset = 0, int $limit = 5): array {
// no pagination...
$limitParam = $offset + $limit;
$params = [
'q' => $query,
'limit' => $limitParam,
];
$geocoderUrl = $this->appConfig->getValueString(Application::APP_ID, 'geocoder_url', lazy: true);
if ($geocoderUrl === '') {
// using nominatim
$params['format'] = $format;
foreach ($extraParams as $k => $v) {
if ($v !== null) {
$params[$k] = $v;
}
}
}
$url = $geocoderUrl === ''
? 'https://nominatim.openstreetmap.org/search'
: $geocoderUrl;
$result = $this->request($url, $params);
if (!isset($result['error'])) {
return array_slice($result, $offset, $limit);
}
return $result;
}
/**
* Make an HTTP request to the Osm API
*
* @param string $url The geocoder url
* @param array $params Query parameters (key/val pairs)
* @param string $method HTTP query method
* @param bool $rawResponse
* @return array decoded request result or error
*/
public function request(string $url, array $params = [], string $method = 'GET', bool $rawResponse = false): array {
try {
// $url = 'https://photon.komoot.io/api/';
$options = [
'headers' => [
'User-Agent' => 'Nextcloud OpenStreetMap integration',
// 'Authorization' => 'MediaBrowser Token="' . $token . '"',
'Content-Type' => 'application/json',
],
];
if (count($params) > 0) {
if ($method === 'GET') {
$paramsContent = http_build_query($params);
$url .= '?' . $paramsContent;
} else {
$options['body'] = json_encode($params);
}
}
if ($method === 'GET') {
$response = $this->client->get($url, $options);
} elseif ($method === 'POST') {
$response = $this->client->post($url, $options);
} elseif ($method === 'PUT') {
$response = $this->client->put($url, $options);
} elseif ($method === 'DELETE') {
$response = $this->client->delete($url, $options);
} else {
return ['error' => $this->l10n->t('Bad HTTP method')];
}
$body = $response->getBody();
$respCode = $response->getStatusCode();
if ($respCode >= 400) {
return ['error' => $this->l10n->t('Bad credentials')];
} else {
if ($rawResponse) {
return [
'body' => $body,
'headers' => $response->getHeaders(),
];
} else {
return json_decode($body, true) ?: [];
}
}
} catch (ClientException|ServerException $e) {
$responseBody = $e->getResponse()->getBody();
$parsedResponseBody = json_decode($responseBody, true);
if ($e->getResponse()->getStatusCode() === 404) {
// Only log inaccessible github links as debug
$this->logger->debug('Osm API error : ' . $e->getMessage(), ['response_body' => $parsedResponseBody, 'app' => Application::APP_ID]);
} else {
$this->logger->warning('Osm API error : ' . $e->getMessage(), ['response_body' => $parsedResponseBody, 'app' => Application::APP_ID]);
}
return [
'error' => $e->getMessage(),
'body' => $parsedResponseBody,
];
} catch (Exception|Throwable $e) {
$this->logger->warning('Osm API error : ' . $e->getMessage(), ['app' => Application::APP_ID]);
return ['error' => $e->getMessage()];
}
}
}