-
Notifications
You must be signed in to change notification settings - Fork 3
/
PageController.php
1116 lines (1026 loc) · 36.2 KB
/
PageController.php
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Nextcloud - gpxpod
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Julien Veyssier <eneiluj@posteo.net>
* @copyright Julien Veyssier 2015
*/
namespace OCA\GpxPod\Controller;
use Exception;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use OC\User\NoUserException;
use OCP\Files\File;
use OCA\GpxPod\AppInfo\Application;
use OCA\GpxPod\Db\Directory;
use OCA\GpxPod\Db\DirectoryMapper;
use OCA\GpxPod\Db\TrackMapper;
use OCA\GpxPod\Service\ConversionService;
use OCA\GpxPod\Service\ElevationService;
use OCA\GpxPod\Service\ProcessService;
use OCA\GpxPod\Service\ToolsService;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\DataDisplayResponse;
use OCP\AppFramework\Http\Response;
use OCP\AppFramework\Http\Template\PublicTemplateResponse;
use OCP\AppFramework\Services\IInitialState;
use OCP\Files\Folder;
use OCP\Files\GenericFileException;
use OCP\Files\IRootFolder;
use OCP\Files\NotFoundException;
use OCP\Files\NotPermittedException;
use OCP\Http\Client\IClientService;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\Lock\LockedException;
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IManager;
use OCP\Share\IShare;
use phpGPX\Models\Point;
use phpGPX\Models\Segment;
use phpGPX\Models\Track;
use phpGPX\phpGPX;
use OCP\AppFramework\Http\ContentSecurityPolicy;
use OCP\IRequest;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Controller;
require_once __DIR__ . '/../../vendor/autoload.php';
class PageController extends Controller {
private IConfig $config;
private IInitialState $initialStateService;
private IRootFolder $root;
private IClientService $clientService;
private ProcessService $processService;
private ConversionService $conversionService;
private ToolsService $toolsService;
private ElevationService $elevationService;
private DirectoryMapper $directoryMapper;
private TrackMapper $trackMapper;
private IManager $shareManager;
private IL10N $l10n;
private IURLGenerator $urlGenerator;
private ?string $userId;
/**
* @var array|string[]
*/
private array $extensions;
private array $upperExtensions;
public function __construct($appName,
IRequest $request,
IConfig $config,
IInitialState $initialStateService,
IRootFolder $root,
IClientService $clientService,
ProcessService $processService,
ConversionService $conversionService,
ToolsService $toolsService,
ElevationService $elevationService,
DirectoryMapper $directoryMapper,
TrackMapper $trackMapper,
IManager $shareManager,
IL10N $l10n,
IURLGenerator $urlGenerator,
?string $userId) {
parent::__construct($appName, $request);
$this->extensions = [
'.kml' => 'kml',
'.gpx' => '',
'.tcx' => 'gtrnctr',
'.igc' => 'igc',
'.jpg' => '',
'.fit' => 'garmin_fit',
];
$this->upperExtensions = array_map('strtoupper', array_keys($this->extensions));
$this->config = $config;
$this->initialStateService = $initialStateService;
$this->root = $root;
$this->clientService = $clientService;
$this->processService = $processService;
$this->conversionService = $conversionService;
$this->toolsService = $toolsService;
$this->elevationService = $elevationService;
$this->directoryMapper = $directoryMapper;
$this->trackMapper = $trackMapper;
$this->shareManager = $shareManager;
$this->l10n = $l10n;
$this->urlGenerator = $urlGenerator;
$this->userId = $userId;
}
/**
* @NoAdminRequired
* @NoCSRFRequired
*
* @param string $service
* @param int $x
* @param int $y
* @param int $z
* @return DataDisplayResponse
* @throws Exception
*/
public function getRasterTile(string $service, int $x, int $y, int $z): DataDisplayResponse {
if ($service === 'osm') {
$s = 'abc'[mt_rand(0, 2)];
$url = 'https://' . $s . '.tile.openstreetmap.org/' . $z . '/' . $x . '/' . $y . '.png';
} elseif ($service === 'esri-topo') {
$url = 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/' . $z . '/' . $y . '/' . $x;
} elseif ($service === 'watercolor') {
$s = 'abc'[mt_rand(0, 2)];
$url = 'http://' . $s . '.tile.stamen.com/watercolor/' . $z . '/' . $x . '/' . $y . '.jpg';
} else {
$s = 'abc'[mt_rand(0, 2)];
$url = 'https://' . $s . '.tile.openstreetmap.org/' . $z . '/' . $x . '/' . $y . '.png';
}
try {
$client = $this->clientService->newClient();
$response = new DataDisplayResponse($client->get($url)->getBody());
$response->cacheFor(60 * 60 * 24);
return $response;
} catch (ClientException | ServerException $e) {
return new DataDisplayResponse('', Http::STATUS_NOT_FOUND);
}
}
/**
* @NoAdminRequired
* @NoCSRFRequired
*
* @return TemplateResponse
* @throws \OCP\DB\Exception
*/
public function index(): TemplateResponse {
$this->cleanDbFromAbsentFiles($this->userId, null);
$alldirs = $this->getDirectories($this->userId);
// personal settings
$settings = [];
$keys = $this->config->getUserKeys($this->userId, Application::APP_ID);
foreach ($keys as $key) {
$value = $this->config->getUserValue($this->userId, Application::APP_ID, $key);
$settings[$key] = $value;
}
$adminMaptilerApiKey = $this->config->getAppValue(Application::APP_ID, 'maptiler_api_key', Application::DEFAULT_MAPTILER_API_KEY) ?: Application::DEFAULT_MAPTILER_API_KEY;
$maptilerApiKey = $this->config->getUserValue($this->userId, Application::APP_ID, 'maptiler_api_key', $adminMaptilerApiKey) ?: $adminMaptilerApiKey;
$settings['maptiler_api_key'] = $maptilerApiKey;
$adminMapboxApiKey = $this->config->getAppValue(Application::APP_ID, 'mapbox_api_key', Application::DEFAULT_MAPBOX_API_KEY) ?: Application::DEFAULT_MAPBOX_API_KEY;
$mapboxApiKey = $this->config->getUserValue($this->userId, Application::APP_ID, 'mapbox_api_key', $adminMapboxApiKey) ?: $adminMapboxApiKey;
$settings['mapbox_api_key'] = $mapboxApiKey;
$settings = $this->getDefaultSettings($settings);
$dirObj = [];
foreach ($alldirs as $dir) {
$dirObj[$dir['id']] = [
'id' => $dir['id'],
'path' => $dir['path'],
'isOpen' => $dir['isOpen'],
'sortOrder' => $dir['sortOrder'],
'tracks' => [],
'pictures' => [],
'loading' => false,
];
}
$state = [
'directories' => $dirObj,
'settings' => $settings,
];
$this->initialStateService->provideInitialState(
'gpxpod-state',
$state
);
$response = new TemplateResponse(Application::APP_ID, 'newMain');
$csp = new ContentSecurityPolicy();
// tiles
$csp->addAllowedImageDomain('https://*.tile.openstreetmap.org');
$csp->addAllowedImageDomain('https://api.maptiler.com');
$csp->addAllowedConnectDomain('https://api.maptiler.com');
$csp->addAllowedConnectDomain('https://api.mapbox.com');
$csp->addAllowedConnectDomain('https://events.mapbox.com');
// TODO check why this is needed (maybe only for NC < 25)
// $csp->addAllowedChildSrcDomain('blob:');
$response->setContentSecurityPolicy($csp);
return $response;
}
/**
* @NoAdminRequired
* @NoCSRFRequired
* @PublicPage
*
* @param string $shareToken
* @param string $password
* @return Response
* @throws NotFoundException
*/
public function publicPasswordIndex(string $shareToken, string $password): Response {
return $this->publicIndex($shareToken, $password);
}
/**
* @NoAdminRequired
* @NoCSRFRequired
* @PublicPage
*
* @param string $shareToken
* @param string|null $password
* @return Response
* @throws NotFoundException
*/
public function publicIndex(string $shareToken, ?string $password = null): Response {
// check if share exists
try {
$share = $this->shareManager->getShareByToken($shareToken);
} catch (ShareNotFound $e) {
return new TemplateResponse('core', '404', [], 'guest');
}
// check if share is password protected
$sharePassword = $share->getPassword();
if ($sharePassword && !$this->shareManager->checkPassword($share, $password)) {
// if so: return password form template response
$params = [
'action' => $this->urlGenerator->linkToRouteAbsolute('gpxpod.page.publicIndex', ['shareToken' => $shareToken]),
];
// if a password was given, it is incorrect
if ($password !== null) {
$params['wrong'] = true;
}
// PARAMS to view
$response = new PublicTemplateResponse(Application::APP_ID, 'sharePassword', $params);
$response->setHeaderTitle($this->l10n->t('GpxPod public access'));
// $response->setHeaderDetails($this->l10n->t('Enter shared access password'));
$response->setFooterVisible(false);
return $response;
}
// if not: return real public index with initial state
return $this->getPublicTemplate($share, $password);
}
/**
* @param IShare $share
* @param string|null $password
* @return PublicTemplateResponse
* @throws NotFoundException
*/
private function getPublicTemplate(IShare $share, ?string $password): PublicTemplateResponse {
$adminMaptilerApiKey = $this->config->getAppValue(Application::APP_ID, 'maptiler_api_key', Application::DEFAULT_MAPTILER_API_KEY) ?: Application::DEFAULT_MAPTILER_API_KEY;
$adminMapboxApiKey = $this->config->getAppValue(Application::APP_ID, 'mapbox_api_key', Application::DEFAULT_MAPBOX_API_KEY) ?: Application::DEFAULT_MAPBOX_API_KEY;
$settings = [
'show_mouse_position_control' => '1',
'show_marker_cluster' => '0',
'maptiler_api_key' => $adminMaptilerApiKey,
'mapbox_api_key' => $adminMapboxApiKey,
];
$settings = $this->getDefaultSettings($settings);
$state = [
'shareToken' => $share->getToken(),
'directories' => [],
'settings' => $settings,
];
if ($password !== null) {
$state['sharePassword'] = $password;
}
$node = $share->getNode();
if ($node instanceof File) {
$state['shareTargetType'] = 'file';
$state['directories'] = [
$share->getToken() => [
'id' => $share->getToken(),
'path' => $this->l10n->t('Public link'),
'isOpen' => true,
'sortOrder' => 0,
'tracks' => [
'0' => $this->getPublicTrack($share),
],
'pictures' => [],
'loading' => false,
],
];
} elseif ($node instanceof Folder) {
$state['shareTargetType'] = 'folder';
$state['directories'] = [
$share->getToken() => [
'id' => $share->getToken(),
'path' => $share->getNode()->getName(),
'isOpen' => true,
'sortOrder' => 0,
'tracks' => $this->getPublicDirectoryTracks($share),
'pictures' => [],
'loading' => false,
],
];
}
$this->initialStateService->provideInitialState(
'gpxpod-state',
$state
);
$response = new PublicTemplateResponse(Application::APP_ID, 'newMain');
$response->setHeaderTitle($share->getNode()->getName());
$response->setHeaderDetails(
$node instanceof File
? $this->l10n->t('GpxPod public file share')
: $this->l10n->t('GpxPod public directory share')
);
$response->setFooterVisible(false);
$csp = new ContentSecurityPolicy();
// tiles
$csp->addAllowedImageDomain('https://*.tile.openstreetmap.org');
$csp->addAllowedImageDomain('https://api.maptiler.com');
$csp->addAllowedConnectDomain('https://api.maptiler.com');
$csp->addAllowedConnectDomain('https://api.mapbox.com');
$csp->addAllowedConnectDomain('https://events.mapbox.com');
// TODO check why this is needed (maybe only for NC < 25)
$csp->addAllowedChildSrcDomain('blob:');
$response->setContentSecurityPolicy($csp);
return $response;
}
private function getPublicDirectoryTracks(IShare $share): array {
$sharedBy = $share->getSharedBy();
$sharedDir = $share->getNode();
$directoryPath = preg_replace('/^files/', '', $sharedDir->getInternalPath());
// try {
$dbDir = $this->directoryMapper->getDirectoryOfUserByPath($directoryPath, $sharedBy);
// } catch (\OCP\DB\Exception | DoesNotExistException $e) {
// TODO handle this error
// }
$this->processService->processGpxFiles($sharedBy, $dbDir->getId(), true, true, false);
$dbTracks = $this->trackMapper->getDirectoryTracksOfUser($sharedBy, $dbDir->getId());
$jsonTracks = array_map(static function(\OCA\GpxPod\Db\Track $track) use ($share) {
$jsonTrack = $track->jsonSerialize();
$jsonTrack['geojson'] = null;
$jsonTrack['onTop'] = false;
$jsonTrack['loading'] = false;
$jsonTrack['directoryId'] = $share->getToken();
$jsonTrack['trackpath'] = basename($jsonTrack['trackpath']);
$jsonTrack['color'] = $jsonTrack['color'] ?? '#0693e3';
$decodedMarker = json_decode($jsonTrack['marker'], true);
foreach (Application::MARKER_FIELDS as $k => $v) {
$jsonTrack[$k] = $decodedMarker[$v];
}
unset($jsonTrack['marker']);
return $jsonTrack;
}, $dbTracks);
$tracksById = [];
foreach ($jsonTracks as $jsonTrack) {
$tracksById[$jsonTrack['id']] = $jsonTrack;
}
return $tracksById;
}
/**
* @NoAdminRequired
* @PublicPage
*
* @param string $shareToken
* @param int $trackId
* @param string|null $password
* @return DataResponse
* @throws LockedException
* @throws MultipleObjectsReturnedException
* @throws NoUserException
* @throws NotFoundException
* @throws NotPermittedException
* @throws \OCP\DB\Exception
*/
public function getPublicDirectoryTrackGeojson(string $shareToken, int $trackId, ?string $password = null): DataResponse {
// check if share exists
try {
$share = $this->shareManager->getShareByToken($shareToken);
} catch (ShareNotFound $e) {
return new DataResponse('', Http::STATUS_NOT_FOUND);
}
// check share password
$sharePassword = $share->getPassword();
if ($sharePassword && !$this->shareManager->checkPassword($share, $password)) {
return new DataResponse('p', Http::STATUS_NOT_FOUND);
}
$sharedBy = $share->getSharedBy();
try {
$dbTrack = $this->trackMapper->getTrackOfUser($trackId, $sharedBy);
} catch (DoesNotExistException $e) {
return new DataResponse('t', Http::STATUS_NOT_FOUND);
}
$dirId = $dbTrack->getDirectoryId();
try {
$dbDir = $this->directoryMapper->getDirectoryOfUser($dirId, $sharedBy);
} catch (DoesNotExistException $e) {
return new DataResponse('d', Http::STATUS_NOT_FOUND);
}
$sharedDirPath = preg_replace('/^files/', '', $share->getNode()->getInternalPath());
if ($dbDir->getPath() !== $sharedDirPath) {
return new DataResponse('s', Http::STATUS_NOT_FOUND);
}
$userFolder = $this->root->getUserFolder($sharedBy);
$cleanpath = str_replace(['../', '..\\'], '', $dbTrack->getTrackpath());
if ($userFolder->nodeExists($cleanpath)) {
$file = $userFolder->get($cleanpath);
if ($file instanceof File) {
if ($this->toolsService->endswith($file->getName(), '.GPX') || $this->toolsService->endswith($file->getName(), '.gpx')) {
$gpxContent = $this->toolsService->remove_utf8_bom($file->getContent());
$geojsonArray = $this->gpxToGeojson($gpxContent);
return new DataResponse($geojsonArray);
}
}
}
return new DataResponse('e', Http::STATUS_BAD_REQUEST);
}
/**
* @param IShare $share
* @return array
*/
private function getPublicTrack(IShare $share): array {
$sharedBy = $share->getSharedBy();
$trackFile = $share->getNode();
$trackPath = preg_replace('/^files/', '', $trackFile->getInternalPath());
// try {
$track = $this->trackMapper->getTrackOfUserByPath($sharedBy, $trackPath);
// } catch (DoesNotExistException $e) {
// TODO process the parent directory (problem, we now pass dirId to processService->processGpxFiles())
// }
$jsonTrack = $track->jsonSerialize();
$jsonTrack['id'] = 0;
$jsonTrack['isEnabled'] = true;
$gpxContent = $this->toolsService->remove_utf8_bom($trackFile->getContent());
$geojsonArray = $this->gpxToGeojson($gpxContent);
$jsonTrack['geojson'] = $geojsonArray;
$jsonTrack['onTop'] = false;
$jsonTrack['loading'] = false;
$jsonTrack['directoryId'] = $share->getToken();
$jsonTrack['trackpath'] = basename($jsonTrack['trackpath']);
$jsonTrack['color'] = $jsonTrack['color'] ?? '#0693e3';
$decodedMarker = json_decode($jsonTrack['marker'], true);
foreach (Application::MARKER_FIELDS as $k => $v) {
$jsonTrack[$k] = $decodedMarker[$v];
}
unset($jsonTrack['marker']);
return $jsonTrack;
}
/**
* @param array $settings
* @return array
*/
private function getDefaultSettings(array $settings): array {
$settings['app_version'] = $this->config->getAppValue(Application::APP_ID, 'installed_version');
// for vue reactive props, initialize missing ones that have an immediate effect on the map
if (!isset($settings['chart_hover_show_detailed_popup'])) {
$settings['chart_hover_show_detailed_popup'] = '0';
}
if (!isset($settings['follow_chart_hover'])) {
$settings['follow_chart_hover'] = '1';
}
if (!isset($settings['show_marker_cluster'])) {
$settings['show_marker_cluster'] = '1';
}
if (!isset($settings['show_picture_cluster'])) {
$settings['show_picture_cluster'] = '1';
}
if (!isset($settings['chart_x_axis'])) {
$settings['chart_x_axis'] = 'time';
}
if (!isset($settings['nav_tracks_filter_map_bounds'])) {
$settings['nav_tracks_filter_map_bounds'] = '';
}
if (!isset($settings['nav_show_hovered_dir_bounds'])) {
$settings['nav_show_hovered_dir_bounds'] = '';
}
if (!isset($settings['show_mouse_position_control'])) {
$settings['show_mouse_position_control'] = '';
}
if (!isset($settings['use_terrain'])) {
$settings['use_terrain'] = '';
}
return $settings;
}
/**
* @NoAdminRequired
*
* @param int $id
* @param bool $isOpen
* @param int|null $sortOrder
* @return DataResponse
* @throws \OCP\DB\Exception
*/
public function updateDirectory(int $id, ?bool $isOpen = null, ?int $sortOrder = null): DataResponse {
$this->directoryMapper->updateDirectory($id, $this->userId, null, $isOpen, $sortOrder);
return new DataResponse();
}
/**
* @NoAdminRequired
*
* @param int $id
* @param bool|null $isEnabled
* @param string|null $color
* @param int|null $colorCriteria
* @return DataResponse
* @throws \OCP\DB\Exception
*/
public function updateTrack(int $id, ?bool $isEnabled = null, ?string $color = null, ?int $colorCriteria = null): DataResponse {
$this->trackMapper->updateTrack($id, $this->userId, null, null, $isEnabled, $color, $colorCriteria);
return new DataResponse([]);
}
/**
* @NoAdminRequired
*
* @param string $path
* @param bool $recursive
* @return DataResponse
* @throws NoUserException
* @throws NotFoundException
* @throws NotPermittedException
*/
public function addDirectory(string $path, bool $recursive = false): DataResponse {
if ($recursive) {
return $this->addDirectoryRecursive($path);
}
$userFolder = $this->root->getUserFolder($this->userId);
$cleanpath = str_replace(['../', '..\\'], '', $path);
if ($userFolder->nodeExists($cleanpath)) {
try {
$dir = $this->directoryMapper->createDirectory($cleanpath, $this->userId, false);
$addedId = $dir->getId();
} catch (\OCP\DB\Exception $e) {
return new DataResponse('Impossible to insert. ' . $e->getMessage(), 400);
}
return new DataResponse($addedId);
} else {
return new DataResponse($cleanpath . ' does not exist', 400);
}
}
/**
* @NoAdminRequired
*
* @param string $path
* @return DataResponse
* @throws NoUserException
* @throws NotFoundException
* @throws NotPermittedException
*/
public function addDirectoryRecursive(string $path): DataResponse {
$userFolder = $this->root->getUserFolder($this->userId);
$userFolderPath = $userFolder->getPath();
$cleanpath = str_replace(['../', '..\\'], '', $path);
if ($userFolder->nodeExists($cleanpath)) {
$folder = $userFolder->get($cleanpath);
// DIRS array population
$optionValues = $this->processService->getSharedMountedOptionValue($this->userId);
$sharedAllowed = $optionValues['sharedAllowed'];
$mountedAllowed = $optionValues['mountedAllowed'];
$showpicsonlyfold = $this->config->getUserValue($this->userId, 'gpxpod', 'showpicsonlyfold', 'true');
$searchJpg = ($showpicsonlyfold === 'true');
$extensions = array_keys($this->extensions);
if ($searchJpg) {
$extensions = array_merge($extensions, ['.jpg']);
}
$files = $this->processService->searchFilesWithExt($folder, $sharedAllowed, $mountedAllowed, $extensions);
$alldirs = [];
foreach($files as $file) {
if ($file->getType() === \OCP\Files\FileInfo::TYPE_FILE and
// name extension is supported
(
in_array( '.'.pathinfo($file->getName(), PATHINFO_EXTENSION), array_keys($this->extensions)) or
in_array( '.'.pathinfo($file->getName(), PATHINFO_EXTENSION), $this->upperExtensions)
)
) {
$rel_dir = str_replace($userFolderPath, '', dirname($file->getPath()));
$rel_dir = str_replace('//', '/', $rel_dir);
if ($rel_dir === '') {
$rel_dir = '/';
}
if (!in_array($rel_dir, $alldirs)) {
$alldirs[] = $rel_dir;
}
}
}
// add each directory
$addedDirs = [];
foreach ($alldirs as $path) {
try {
$insertedDir = $this->directoryMapper->createDirectory($path, $this->userId, false);
$addedDirs[] = $insertedDir->jsonSerialize();
} catch (\OCP\DB\Exception $e) {
// ignore this dir
}
}
return new DataResponse($addedDirs);
} else {
return new DataResponse($cleanpath . ' does not exist', 400);
}
}
/**
* @NoAdminRequired
*
* @param int $id
* @return DataResponse
* @throws MultipleObjectsReturnedException
* @throws \OCP\DB\Exception
*/
public function deleteDirectory(int $id): DataResponse {
try {
$dir = $this->directoryMapper->getDirectoryOfUser($id, $this->userId);
} catch (DoesNotExistException $e) {
return new DataResponse('Directory not found', Http::STATUS_BAD_REQUEST);
}
$this->directoryMapper->delete($dir);
$this->trackMapper->deleteDirectoryTracksForUser($this->userId, $id);
return new DataResponse('');
}
/**
* @NoAdminRequired
*
* @param string $userId
* @return array
* @throws \OCP\DB\Exception
*/
public function getDirectories(string $userId): array {
return array_map(static function(Directory $directory) {
return $directory->jsonSerialize();
}, $this->directoryMapper->getDirectoriesOfUser($userId));
}
/**
* @NoAdminRequired
*
* @param int $id
* @return DataResponse
* @throws LockedException
* @throws MultipleObjectsReturnedException
* @throws NoUserException
* @throws NotFoundException
* @throws NotPermittedException
* @throws \OCP\DB\Exception
*/
public function getGeojson(int $id): DataResponse {
try {
$dbTrack = $this->trackMapper->getTrackOfUser($id, $this->userId);
} catch (DoesNotExistException $e) {
return new DataResponse('Track not found', Http::STATUS_BAD_REQUEST);
}
$path = $dbTrack->getTrackpath();
$userFolder = $this->root->getUserFolder($this->userId);
$cleanpath = str_replace(['../', '..\\'], '', $path);
if ($userFolder->nodeExists($cleanpath)) {
$file = $userFolder->get($cleanpath);
if ($file instanceof File) {
if ($this->toolsService->endswith($file->getName(), '.GPX') || $this->toolsService->endswith($file->getName(), '.gpx')) {
$gpxContent = $this->toolsService->remove_utf8_bom($file->getContent());
$geojsonArray = $this->gpxToGeojson($gpxContent);
return new DataResponse($geojsonArray);
}
}
}
return new DataResponse('', Http::STATUS_BAD_REQUEST);
}
/**
* @param string $gpxContent
* @return array
*/
private function gpxToGeojson(string $gpxContent): array {
$gpx = new phpGPX();
$gpxArray = $gpx->parse($gpxContent);
// one LineString per segment, ignoring the track separation
/*
$result = [
'type' => 'FeatureCollection',
'features' => [],
];
foreach ($gpxArray->tracks as $track) {
foreach ($track->segments as $segment) {
$result['features'][] = [
'type' => 'Feature',
'geometry' => [
'type' => 'LineString',
'coordinates' => array_map(static function(Point $point) {
return [
$point->longitude,
$point->latitude,
$point->elevation,
$point->time->getTimestamp(),
];
}, array_values(array_filter($segment->points, static function(Point $point) {
return $point->longitude !== null && $point->latitude !== null && $point->time !== null;
}))
),
],
];
}
}
return $result;
*/
// one multiline per gpx-track
// one series of coords per gpx-segment
return [
'type' => 'FeatureCollection',
'features' => array_map(static function(Track $track) {
return [
'type' => 'Feature',
'geometry' => [
'type' => 'MultiLineString',
'coordinates' => array_map(static function(Segment $segment) {
return array_map(static function(Point $point) {
return [
$point->longitude,
$point->latitude,
$point->elevation,
$point->time !== null ? $point->time->getTimestamp() : null,
];
}, array_values(array_filter($segment->points, static function(Point $point) {
// && $point->time !== null;
return $point->longitude !== null && $point->latitude !== null;
})));
}, $track->segments)
],
'properties' => [
'name' => $track->name,
],
];
}, $gpxArray->tracks),
];
}
/**
* @NoAdminRequired
*
* @param int $id
* @return DataResponse
* @throws GenericFileException
* @throws LockedException
* @throws MultipleObjectsReturnedException
* @throws NoUserException
* @throws NotFoundException
* @throws NotPermittedException
* @throws \OCP\DB\Exception
*/
public function processTrackElevations(int $id): DataResponse {
try {
$dbTrack = $this->trackMapper->getTrackOfUser($id, $this->userId);
} catch (DoesNotExistException $e) {
return new DataResponse('Track not found', Http::STATUS_BAD_REQUEST);
}
$path = $dbTrack->getTrackpath();
$userFolder = $this->root->getUserFolder($this->userId);
$cleanpath = str_replace(['../', '..\\'], '', $path);
if ($userFolder->nodeExists($cleanpath)) {
$file = $userFolder->get($cleanpath);
if ($file instanceof File) {
if ($this->toolsService->endswith($file->getName(), '.GPX') || $this->toolsService->endswith($file->getName(), '.gpx')) {
$gpxContent = $this->toolsService->remove_utf8_bom($file->getContent());
$gpx = new phpGPX();
$gpxFile = $gpx->parse($gpxContent);
try {
$correctedGpxFile = $this->elevationService->correctElevations($gpxFile);
} catch (Exception $e) {
return new DataResponse($e->getMessage(), Http::STATUS_BAD_REQUEST);
}
// save to dir
$dirId = $dbTrack->getDirectoryId();
try {
$dbDir = $this->directoryMapper->getDirectoryOfUser($dirId, $this->userId);
} catch (DoesNotExistException $e) {
return new DataResponse('Directory not found', Http::STATUS_BAD_REQUEST);
}
/** @var Folder $targetDirectory */
$targetDirectory = $userFolder->get($dbDir->getPath());
if ($this->toolsService->endswith($file->getName(), '.GPX')) {
$newName = preg_replace('/\.GPX$/', '_corrected.GPX', $file->getName());
} else {
$newName = preg_replace('/\.gpx$/', '_corrected.gpx', $file->getName());
}
if ($targetDirectory->nodeExists($newName)) {
/** @var File $targetFile */
$targetFile = $targetDirectory->get($newName);
$targetFile->putContent($correctedGpxFile->toXML()->saveXML());
} else {
$targetDirectory->newFile($newName, $correctedGpxFile->toXML()->saveXML());
}
return new DataResponse('');
}
}
}
return new DataResponse('Track not found', Http::STATUS_BAD_REQUEST);
}
/**
* @NoAdminRequired
*
* Ajax markers json retrieval from DB
*
* First convert kml, tcx... files if necessary.
* Then copy files to a temporary directory (decrypt them if necessary).
* Then correct elevations if it was asked.
* Then process the files to produce marker content.
* Then INSERT or UPDATE the database with processed data.
* Then get the markers for all gpx files in the target folder
* Then clean useless database entries (for files that no longer exist)
*/
public function getTrackMarkersJson(int $id, string $directoryPath, bool $processAll = false): DataResponse {
try {
$dbDir = $this->directoryMapper->getDirectoryOfUser($id ,$this->userId);
} catch (\OCP\DB\Exception | DoesNotExistException $e) {
return new DataResponse('No such directory', 400);
}
if ($dbDir->getPath() !== $directoryPath) {
return new DataResponse('No such directory', 400);
}
$userFolder = $this->root->getUserFolder($this->userId);
try {
$dbDir = $this->directoryMapper->getDirectoryOfUserByPath($directoryPath, $this->userId);
} catch (\OCP\DB\Exception | DoesNotExistException $e) {
return new DataResponse('No such directory', 400);
}
if ($directoryPath === null || !$userFolder->nodeExists($directoryPath)) {
return new DataResponse('No such directory', 400);
}
$folder = $userFolder->get($directoryPath);
if (!$folder instanceof Folder) {
return new DataResponse('Directory is not a directory', 400);
}
$optionValues = $this->processService->getSharedMountedOptionValue($this->userId);
$sharedAllowed = $optionValues['sharedAllowed'];
$mountedAllowed = $optionValues['mountedAllowed'];
// Convert KML to GPX
// only if we want to display a folder AND it exists AND we want
// to compute AND we find GPSBABEL AND file was not already converted
if ($directoryPath === '/') {
$directoryPath = '';
}
$filesByExtension = [];
foreach($this->extensions as $ext => $gpsbabel_fmt) {
$filesByExtension[$ext] = [];
}
foreach ($folder->getDirectoryListing() as $ff) {
if ($ff instanceof File) {
$ffext = '.' . strtolower(pathinfo($ff->getName(), PATHINFO_EXTENSION));
if (in_array($ffext, array_keys($this->extensions))) {
// if shared files are allowed or it is not shared
if ($sharedAllowed || !$ff->isShared()) {
$filesByExtension[$ffext][] = $ff;
}
}
}
}
$this->convertFiles($userFolder, $directoryPath, $this->userId, $filesByExtension);
// PROCESS gpx files and fill DB
$this->processService->processGpxFiles($this->userId, $dbDir->getId(), $sharedAllowed, $mountedAllowed, $processAll);
// build tracks array
$dbTracks = $this->trackMapper->getDirectoryTracksOfUser($this->userId, $dbDir->getId());
$that = $this;
$filteredTracks = array_filter($dbTracks, static function(\OCA\GpxPod\Db\Track $dbTrack) use ($userFolder, $sharedAllowed, $that) {
if ($userFolder->nodeExists($dbTrack->getTrackpath())) {
$file = $userFolder->get($dbTrack->getTrackpath());
return $file instanceof File && ($sharedAllowed || !$file->isShared());
}
// CLEANUP DB for non-existing files
$that->trackMapper->delete($dbTrack);
return false;
});
$jsonTracks = array_map(static function(\OCA\GpxPod\Db\Track $track) {
$jsonTrack = $track->jsonSerialize();
$jsonTrack['geojson'] = null;
$jsonTrack['onTop'] = false;
$jsonTrack['loading'] = false;
$jsonTrack['color'] = $jsonTrack['color'] ?? '#0693e3';
$decodedMarker = json_decode($jsonTrack['marker'], true);
foreach (Application::MARKER_FIELDS as $k => $v) {
$jsonTrack[$k] = $decodedMarker[$v];
}
unset($jsonTrack['marker']);
return $jsonTrack;
}, $filteredTracks);
$tracksById = [];
foreach ($jsonTracks as $jsonTrack) {
$tracksById[$jsonTrack['id']] = $jsonTrack;
}
$picturesArray = $this->processService->getGeoPicsFromFolder($this->userId, $directoryPath, $id, false);
return new DataResponse([
'tracks' => $tracksById,
'pictures' => $picturesArray,
]);
}
private function convertFiles($userFolder, $subfolder, $userId, $filesByExtension) {
// convert kml, tcx etc...
if ( $userFolder->nodeExists($subfolder)
&& $userFolder->get($subfolder)->getType() === \OCP\Files\FileInfo::TYPE_FOLDER) {
$gpsbabel_path = $this->toolsService->getProgramPath('gpsbabel');
$igctrack = $this->config->getUserValue($userId, 'gpxpod', 'igctrack');
if ($gpsbabel_path !== null) {
foreach ($this->extensions as $ext => $gpsbabel_fmt) {
if ($ext !== '.gpx' && $ext !== '.jpg') {
$igcfilter1 = '';
$igcfilter2 = '';
if ($ext === '.igc') {
if ($igctrack === 'pres') {
$igcfilter1 = '-x';
$igcfilter2 = 'track,name=PRESALTTRK';
} elseif ($igctrack === 'gnss') {
$igcfilter1 = '-x';
$igcfilter2 = 'track,name=GNSSALTTRK';
}
}
foreach ($filesByExtension[$ext] as $f) {
$name = $f->getName();
$gpx_targetname = str_replace($ext, '.gpx', $name);