jonnybarnes.uk/app/Console/Commands/ParseCachedWebMentions.php

68 lines
1.9 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace App\Console\Commands;
2017-12-19 16:00:42 +00:00
use App\Models\WebMention;
use Illuminate\Console\Command;
2023-02-18 09:34:57 +00:00
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\FileSystem\FileSystem;
/**
* @psalm-suppress UnusedClass
*/
class ParseCachedWebMentions extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'webmentions:parsecached';
/**
* The console command description.
*
* @var string
*/
2016-09-17 20:56:57 +01:00
protected $description = 'Re-parse the webmentions cached HTML';
/**
* Execute the console command.
*
2023-02-18 09:34:57 +00:00
* @throws FileNotFoundException
*/
2023-02-18 09:34:57 +00:00
public function handle(FileSystem $filesystem): void
{
$htmlFiles = $filesystem->allFiles(storage_path() . '/HTML');
foreach ($htmlFiles as $file) {
2025-04-01 21:08:17 +01:00
if ($file->getExtension() !== 'backup') { // we dont want to parse `.backup` files
2016-09-19 17:19:04 +01:00
$filepath = $file->getPathname();
2016-09-19 21:22:03 +01:00
$this->info('Loading HTML from: ' . $filepath);
2016-09-19 17:19:04 +01:00
$html = $filesystem->get($filepath);
$url = $this->urlFromFilename($filepath);
2016-09-19 17:19:04 +01:00
$webmention = WebMention::where('source', $url)->firstOrFail();
$microformats = \Mf2\parse($html, $url);
2016-09-19 17:19:04 +01:00
$webmention->mf2 = json_encode($microformats);
$webmention->save();
2016-09-19 21:22:03 +01:00
$this->info('Saved the microformats to the database.');
2016-09-19 17:19:04 +01:00
}
}
}
/**
* Determine the source URL from a filename.
*/
private function urlFromFilename(string $filepath): string
{
$dir = mb_substr($filepath, mb_strlen(storage_path() . '/HTML/'));
$url = str_replace(['http/', 'https/'], ['http://', 'https://'], $dir);
if (mb_substr($url, -10) === 'index.html') {
$url = mb_substr($url, 0, -10);
}
return $url;
}
}