jonnybarnes.uk/app/Jobs/DownloadWebMention.php

82 lines
2.4 KiB
PHP
Raw Permalink Normal View History

<?php
declare(strict_types=1);
namespace App\Jobs;
use Illuminate\Bus\Queueable;
2019-10-27 19:31:33 +00:00
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Contracts\Queue\ShouldQueue;
2019-10-27 16:29:15 +00:00
use Illuminate\FileSystem\FileSystem;
use Illuminate\Http\Client\RequestException;
2019-10-27 16:29:15 +00:00
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
class DownloadWebMention implements ShouldQueue
{
2019-10-27 19:31:33 +00:00
use InteractsWithQueue;
use Queueable;
use SerializesModels;
/**
* Create a new job instance.
*/
2023-02-18 09:34:57 +00:00
public function __construct(
protected string $source
) {}
/**
* Execute the job.
*
* @throws RequestException
2019-10-27 19:31:33 +00:00
* @throws FileNotFoundException
*/
public function handle(): void
{
// 4XX and 5XX responses should throw so Laravel can catch and
// retry these automatically.
$response = Http::throw()->get($this->source);
if ($response->status() === 200) {
$filesystem = new FileSystem;
2026-04-07 09:01:19 +01:00
$filename = storage_path('HTML').'/'.$this->createFilenameFromURL($this->source);
2025-03-01 15:00:41 +00:00
// backup file first
2026-04-07 09:01:19 +01:00
$filenameBackup = $filename.'.'.date('Y-m-d').'.backup';
if ($filesystem->exists($filename)) {
2016-09-19 17:25:01 +01:00
$filesystem->copy($filename, $filenameBackup);
}
2025-03-01 15:00:41 +00:00
// check if base directory exists
2016-09-21 14:25:12 +01:00
if (! $filesystem->exists($filesystem->dirname($filename))) {
$filesystem->makeDirectory(
$filesystem->dirname($filename),
2025-03-01 15:00:41 +00:00
0755, // mode
true // recursive
);
}
2025-03-01 15:00:41 +00:00
// save new HTML
$filesystem->put(
$filename,
$response->body()
2016-09-17 21:29:32 +01:00
);
2025-03-01 15:00:41 +00:00
// remove backup if the same
if ($filesystem->exists($filenameBackup)) {
2023-02-18 09:34:57 +00:00
if ($filesystem->get($filename) === $filesystem->get($filenameBackup)) {
$filesystem->delete($filenameBackup);
}
2016-09-19 17:25:01 +01:00
}
}
}
/**
2019-10-27 19:31:33 +00:00
* Create a file path from a URL. This is used when caching the HTML response.
*/
2023-02-18 09:34:57 +00:00
private function createFilenameFromURL(string $url): string
{
$filepath = str_replace(['https://', 'http://'], ['https/', 'http/'], $url);
2023-02-18 09:34:57 +00:00
if (str_ends_with($filepath, '/')) {
$filepath .= 'index.html';
}
return $filepath;
}
}