Make crawlers generate page previews

This commit is contained in:
grandeljay 2022-11-19 20:46:50 +01:00
parent 274124c32f
commit fdda3af826
3 changed files with 94 additions and 0 deletions

44
src/api/save-preview.php Normal file
View file

@ -0,0 +1,44 @@
<?php
/**
* Save preview
*
* @category API
*/
namespace wishthis;
global $page;
if (!isset($page)) {
http_response_code(403);
die('Direct access to this location is not allowed.');
}
switch ($_SERVER['REQUEST_METHOD']) {
case 'POST':
if (isset($_POST['preview'], $_POST['page'])) {
$preview = substr($_POST['preview'], 22); // data:image/png;base64,
$preview = base64_decode($preview);
$preview_filepath = ROOT . '/src/assets/img/screenshots/' . $_POST['page'] . '.png';
$preview_create = false;
$page_filepath = ROOT . 'src/pages/' . $_POST['page'] . '.php';
$page = new Page($page_filepath);
if (file_exists($preview_filepath)) {
$preview_age = time() - filemtime($preview_filepath);
if ($preview_age > Duration::MONTH) {
$preview_create = true;
}
} else {
$preview_create = true;
}
if ($preview_create && $_SESSION['user']->power >= $page->power) {
file_put_contents($preview_filepath, $preview);
}
}
break;
}

View file

@ -0,0 +1,33 @@
"use strict";
window.addEventListener("load", (event) => {
/**
* Generate page preview
*/
html2canvas(
document.querySelector('body'),
{
'logging' : false,
'x' : window.scrollX,
'y' : window.scrollY,
'width' : window.innerWidth,
'height' : window.innerHeight,
}
)
.then(canvas => {
var data = new URLSearchParams();
data.append('preview', canvas.toDataURL());
data.append('api_token', api.token);
data.append('page', $_GET.page);
/** Save page preview */
fetch('/?page=api&module=save-preview', {
method : 'POST',
body : data
})
.then(handleFetchError)
.then(handleFetchResponse)
.then(function(response) {})
.finally(function() {});
});
});

View file

@ -440,6 +440,23 @@ class Page
<script defer src="/<?= $scriptFomantic ?>?m=<?= $scriptFomanticModified ?>"></script>
<?php
/** html2canvas */
$CrawlerDetect = new \Jaybizzle\CrawlerDetect\CrawlerDetect();
if ($CrawlerDetect->isCrawler()) {
$scripthtml2canvas1 = 'node_modules/html2canvas/dist/html2canvas.min.js';
$scripthtml2canvas1Modified = filemtime($scripthtml2canvas1);
?>
<script defer src="/<?= $scripthtml2canvas1 ?>?m=<?= $scripthtml2canvas1Modified ?>"></script>
<?php
$scripthtml2canvas2 = 'src/assets/js/html2canvas.js';
$scripthtml2canvas2Modified = filemtime($scripthtml2canvas2);
?>
<script defer src="/<?= $scripthtml2canvas2 ?>?m=<?= $scripthtml2canvas2Modified ?>"></script>
<?php
}
/** Default */
$scriptDefault = 'src/assets/js/default.js';
$scriptDefaultModified = filemtime($scriptDefault);