-
Notifications
You must be signed in to change notification settings - Fork 1
/
gpx2image.php
154 lines (131 loc) · 2.52 KB
/
gpx2image.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
<?php declare(strict_types=1);
use Nesk\Puphpeteer\Puppeteer;
require_once 'vendor/autoload.php';
function isValidGpx(string $gpx): bool
{
if (stripos($gpx, '<gpx') === false)
{
return false;
}
if (stripos($gpx, '</gpx>') === false)
{
return false;
}
return true;
}
try
{
if (isset($argv[1]))
{
$filePath = __DIR__ . '/' . $argv[1];
if (!is_readable($filePath))
{
throw new Exception(".gpx file $filePath is not readable.");
}
$gpxContent = file_get_contents($filePath);
$hash = md5_file($filePath);
$isCli = true;
} else
{
// Web request.
$gpxContent = file_get_contents('php://input');
$hash = md5($gpxContent);
$filePath = "/tmp/$hash.gpx";
file_put_contents($filePath, $gpxContent);
$isCli = false;
}
$imagePath = __DIR__ . "/storage/$hash.png";
if (!isValidGpx($gpxContent))
{
throw new InvalidArgumentException(".gpx file $filePath is not valid xml.");
}
if (!file_exists($imagePath))
{
if (!$isCli) {
header('X-Cache-Hit: false');
}
// Not found in cache => download.
$puppeteer = new Puppeteer();
$browser = $puppeteer->launch(
[
'defaultViewport' => [
'width' => 1920,
'height' => 1080,
],
'args' =>
[
// this is required for dockerized puppeteer
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
],
]
);
$page = $browser->newPage();
$page->goto(
'https://labs.strava.com/gpx-to-route',
[
'waitUntil' => 'networkidle0',
]
);
if ($isCli)
{
echo "Title is {$page->title()}.\n";
}
$gpxFileInput = $page->querySelector('#gpxFile');
$gpxFileInput->uploadFile($filePath);
$page->waitForNavigation(
[
'waitUntil' => 'networkidle0',
]
);
$page->waitFor(1000);
$page->screenshot(
[
'path' => "storage/$hash.png",
'fullPage' => false,
'clip' => [
'x' => 374,
'y' => 59,
'width' => 1546,
'height' => 1021,
],
]
);
$browser->close();
} else {
// Image found in cache.
if (!$isCli) {
header('X-Cache-Hit: true');
}
}
}
catch (Error $exception)
{
if ($isCli)
{
throw $exception;
} else
{
header('Content-Type: application/json');
echo json_encode(
[
'success' => false,
'error' => $exception->getMessage(),
]
);
}
}
if ($isCli)
{
echo "$hash.png\n";
} else
{
header('Content-Type: application/json');
echo json_encode(
[
'success' => true,
'image' => "https://cdn.gpsart.app/storage/$hash.png",
]
);
}