-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathroutes.php
78 lines (64 loc) · 2.88 KB
/
routes.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
<?php
declare(strict_types=1);
use Backend\Facades\BackendAuth;
use Backend\Models\BrandSetting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;
use Winter\Redirect\Classes\Sparkline;
use Winter\Redirect\Classes\StatisticsHelper;
Route::group(['middleware' => ['web']], static function () {
Route::get('winter/redirect/sparkline/{redirectId}', static function ($redirectId) {
if (!BackendAuth::check()) {
return response('Forbidden', 403);
}
/** @var Request $request */
$request = resolve(Request::class);
$crawler = $request->has('crawler');
$preset = $request->get('preset', '30d-small');
$properties = [
'format' => '200x60',
'lineThickness' => 3,
'days' => 30,
];
if ($preset === '3m-large') {
$properties = [
'format' => '520x120',
'lineThickness' => 2,
'days' => 90,
];
}
$cacheKey = sprintf('winter_redirect_%s_%d_%d', $preset, (int) $redirectId, (int) $crawler);
$data = Cache::remember($cacheKey, 5 * 60, static function () use ($redirectId, $crawler, $properties) {
return (new StatisticsHelper())->getRedirectHitsSparkline((int) $redirectId, $crawler, $properties['days']);
});
// TODO: Generate fallback image data if generating image fails.
$imageData = Cache::remember($cacheKey . '_image', 5 * 60, static function () use ($crawler, $data, $properties) {
try {
$primaryColor = BrandSetting::get(
$crawler ? 'primary_color' : 'secondary_color',
$crawler ? BrandSetting::PRIMARY_COLOR : BrandSetting::SECONDARY_COLOR
);
$sparkline = new Sparkline();
$sparkline->setFormat($properties['format']);
$sparkline->setPadding('2 0 0 2');
$sparkline->setData($data);
$sparkline->setLineThickness($properties['lineThickness']);
$sparkline->setLineColorHex($primaryColor);
$sparkline->setFillColorHex($primaryColor);
$sparkline->deactivateBackgroundColor();
return $sparkline->toBase64();
} catch (\Throwable $e) {
// Generate a 1x1 transparent pixel as fallback.
return 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFDQJXep6X8QAAAABJRU5ErkJggg==';
}
});
return Response::make(base64_decode($imageData), 200, [
'Content-Type' => 'image/png',
'Content-Disposition' => 'inline; filename="' . $cacheKey . '.png"',
'Accept-Ranges' => 'none',
// Leverage browser caching
'Cache-Control' => 'public, max-age=300',
]);
});
});