Skip to content

A self-hosted media server and file management system

feat: update preview generator service to use image service pipeline

aminnausin3797c8d496e8
diff --git a/app/Jobs/GeneratePreviewImage.php b/app/Jobs/GeneratePreviewImage.php
index 68f48fff..aaabb56e 100644
--- a/app/Jobs/GeneratePreviewImage.php
+++ b/app/Jobs/GeneratePreviewImage.php
@@ -7,9 +7,10 @@ use App\Models\SubTask;
use App\Services\GenerateImageException;
use App\Services\PreviewGeneratorService;
use App\Services\TaskService;
+use Illuminate\Database\Eloquent\Model;
class GeneratePreviewImage extends ManagedSubTask {
- protected $itemTitle;
+ protected string $itemTitle;
public $timeout = 3600;
@@ -20,10 +21,10 @@ class GeneratePreviewImage extends ManagedSubTask {
*/
public function __construct(
public array $data,
- public string $path,
+ public Model $owner,
int $taskId,
) {
- $this->itemTitle = $data['title'] ?? $path;
+ $this->itemTitle = $data['title'] ?? $owner->name ?? 'Unknown';
$subTask = SubTask::create(['task_id' => $taskId, 'status' => TaskStatus::PENDING, 'name' => "Regenerate Preview Image for '{$this->itemTitle}'"]);
@@ -37,11 +38,11 @@ class GeneratePreviewImage extends ManagedSubTask {
}
try {
- $result = $previewGenerator->generateImage($this->data, $this->path, true);
- if (! $result) {
+ $image = $previewGenerator->generateAndPersist($this->owner, $this->data);
+ if (! $image) {
throw new GenerateImageException('Preview image generation failed. View logs for error.');
}
- $this->completeSubTask($taskService, 'Generated preview image.');
+ $this->completeSubTask($taskService, "Generated preview image at {$image->path}.");
} catch (\Throwable $th) {
$this->failSubTask($taskService, $th);
throw $th;
diff --git a/app/Services/FileJobService.php b/app/Services/FileJobService.php
index af76892f..bdf87630 100644
--- a/app/Services/FileJobService.php
+++ b/app/Services/FileJobService.php
@@ -231,10 +231,10 @@ class FileJobService {
$chain = [];
foreach ($rows as $row) {
- if (! isset($row['data']) || ! isset($row['path'])) {
+ if (! isset($row['data']) || ! isset($row['owner'])) {
continue;
}
- $chain[] = new GeneratePreviewImage($row['data'], $row['path'], $task->id);
+ $chain[] = new GeneratePreviewImage($row['data'], $row['owner'], $task->id);
}
return $chain;
diff --git a/app/Services/PreviewGeneratorService.php b/app/Services/PreviewGeneratorService.php
index d0c5ae10..c4f49f79 100644
--- a/app/Services/PreviewGeneratorService.php
+++ b/app/Services/PreviewGeneratorService.php
@@ -2,47 +2,60 @@
namespace App\Services;
-use App\Http\Resources\FolderResource;
-use App\Http\Resources\VideoResource;
-use App\Jobs\VerifyFiles;
+use App\Data\Images\ImageData;
+use App\Enums\ImageSource;
+use App\Enums\ImageType;
+use App\Enums\MediaType;
+use App\Enums\TaskStatus;
use App\Models\Category;
use App\Models\Folder;
+use App\Models\Image;
+use App\Models\Metadata;
+use App\Models\Series;
+use App\Models\SubTask;
+use App\Services\Images\ImageService;
use Carbon\Carbon;
use Carbon\CarbonInterval;
use Exception;
+use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Spatie\Browsershot\Browsershot;
use Symfony\Component\HttpFoundation\Response;
class PreviewGeneratorService {
- protected string $defaultThumbnail;
+ protected string $defaultPoster;
+
+ private const LEGACY_PREVIEW_PREFIX = 'previews/';
public function __construct(
protected PathResolverService $pathResolver,
+ protected ImageService $imageService,
) {
- $this->defaultThumbnail = asset('storage/thumbnails/default.webp');
+ $this->defaultPoster = asset('storage/thumbnails/default.webp'); // I should use this more often???
}
public function handle(Request $request, bool $generateRawPreview): Response {
$outputTemplate = $generateRawPreview ? 'og-media-preview' : 'og-preview';
$defaultData = $this->defaultData($request);
+
try {
$categorySlug = $request->route('dir');
$folderSlug = $request->route('folderName') ?? '';
$videoId = $request->query('video');
- $category = $this->pathResolver->resolveCategory($categorySlug, $request->user()?->id !== 1);
- $folder = $this->pathResolver->resolveFolder(identifier: $folderSlug, category: $category)->load('series');
-
if ($videoId) {
- $data = $this->buildVideoPreviewData($category, $folder, $videoId, $request, $generateRawPreview);
+ $metadata = Metadata::where('video_id', $videoId)->firstOrFail()->load('video.folder.series.primaryPoster', 'video.folder.category', 'videoTags', 'primaryPoster');
+ $viewData = $this->preparePreviewData($this->buildMediaPreviewData($metadata, $request), $metadata, $generateRawPreview);
} else {
- $data = $this->buildFolderPreviewData($category, $folder, $request, $generateRawPreview);
+ $category = $this->pathResolver->resolveCategory($categorySlug, ! Gate::allows('admin'));
+ $folder = $this->pathResolver->resolveFolder(identifier: $folderSlug, category: $category, onlyPublic: ! Gate::allows('admin'))->load('series.primaryPoster', 'series.folderTags');
+ $viewData = $this->preparePreviewData($this->buildFolderPreviewData($category, $folder, $request), $folder->series, $generateRawPreview);
}
- return response()->view($outputTemplate, $data);
+ return response()->view($outputTemplate, $viewData);
} catch (\Throwable $e) {
Log::warning('Error generating link preview', [
'error' => $e->getMessage(),
@@ -53,103 +66,176 @@ class PreviewGeneratorService {
}
}
- public function handleGenerateImage(array $data, string $relativePath, ?int $dataLastUpdated = 0, bool $queued = true): ?string {
+ /**
+ * Returns the path to the generated preview image
+ *
+ * Directly generates on first request and returns exisiting file on subsquent requests
+ *
+ * If the owner has been edited since the last image was generated, a new one is queued to generate.
+ */
+ protected function handleGenerateImage(Model $owner, array $data, ?int $dataLastUpdated = 0): ?string {
+ $override = config('services.preview_generator.override'); // Forces generation in local environment
+
+ $existingRow = Image::where([
+ 'imageable_id' => $owner->uuid,
+ 'imageable_type' => $owner::class,
+ 'image_type' => ImageType::OGP,
+ 'replaced_at' => null,
+ ])->first();
+
+ $legacyPath = $this->resolveLegacyPath($owner);
$disk = Storage::disk('public');
- $override = config('services.preview_generator.override');
- $relativePath = trim('previews/' . $relativePath, '/') . '.png';
- $fullPath = $disk->path($relativePath);
+ $absoluteLegacyPath = $disk->path($legacyPath);
+
+ $isDbStale = $existingRow && $existingRow->updated_at->timestamp < $dataLastUpdated;
+ $isFileStale = ! $existingRow && $dataLastUpdated && file_exists($absoluteLegacyPath) && filemtime($absoluteLegacyPath) < $dataLastUpdated; // Will be false if file does not exist
+
+ // If not override and either db exists and is stale or file exists and is stale -> queue regenerate
+ if (! $override && ($isDbStale || $isFileStale)) {
+ $this->queueRegeneration($owner, $data);
+ }
+
+ $this->queueRegeneration($owner, $data);
+ if (! $override && $existingRow) {
+ return ImageService::getImageUrl($existingRow->path);
+ }
+
+ if (! $override && $disk->exists($legacyPath)) {
+ return asset('storage/' . $legacyPath);
+ }
+
+ $image = $this->generateAndPersist($owner, $data);
+
+ return $image ? ImageService::getImageUrl($image->path) : null;
+ }
+
+ /**
+ * Generates and persists a preview image for a given owner model
+ *
+ * !! Writes file to disk !!
+ *
+ * @param Model $owner Owner model
+ * @param array $data Preview data to fill html with
+ * @return ?Image persistent image data from database
+ */
+ public function generateAndPersist(Model $owner, array $data): ?Image {
try {
- if (! $disk->exists($relativePath)) {
- $queued = false;
- } elseif (! $override && $dataLastUpdated && filemtime($fullPath) > $dataLastUpdated) {
- return VerifyFiles::getPathUrl($relativePath);
- }
+ [$relativeOutputPath, $absoluteOutputPath] = $this->imageService->resolvePath($owner, ImageType::OGP, 'png');
- if (! $override && $queued) {
- $fileJobService = app(FileJobService::class);
- $fileJobService->regeneratePreviewImages([['data' => $data, 'path' => $relativePath]]);
+ $imageContents = $this->renderImage($data); // raw png data
- return VerifyFiles::getPathUrl($relativePath);
+ if (! $imageContents) {
+ throw new GenerateImageException('Browsershot returned no content');
}
- $generatedImage = $this->generateImage($data, $relativePath);
- if (! $generatedImage) {
- throw new GenerateImageException('Failed to generate Image');
+ file_put_contents($absoluteOutputPath, $imageContents);
+
+ if (! file_exists($absoluteOutputPath) || filesize($absoluteOutputPath) === 0) {
+ throw new GenerateImageException('Preview image file has no content');
}
- $disk->put($relativePath, $generatedImage);
- } catch (\Throwable $th) { // Cannot catch the specific spatie/image exception since it throws a generic one
- Log::warning('Error during OG image generation', ['error' => $th->getMessage()]);
+ return $this->imageService->persistImage(
+ $owner,
+ new ImageData(
+ absolutePath: $absoluteOutputPath,
+ relativePath: $relativeOutputPath,
+ type: ImageType::OGP,
+ source: ImageSource::GENERATED,
+ format: 'png',
+ ),
+ true
+ );
+ } catch (\Throwable $th) {
+ Log::error('Preview image generation failed', [
+ 'owner' => $owner::class,
+ 'id' => $owner->getKey(),
+ 'error' => $th->getMessage(),
+ ]);
+
+ return null;
}
+ }
- return file_exists($fullPath)
- ? VerifyFiles::getPathUrl($relativePath)
- : null;
+ /**
+ * Builds a legacy preview path for an owner, mirroring the previously used pathKeys in handleGenerateImage.
+ *
+ * Folder (Series): previews/folders/{folder_id}.png
+ * Video (Metadata): previews/{folder->path}/{video_id}.png
+ *
+ * @param Model $owner Database Model to buld a preview path for (Metadata|Series)
+ * @return ?string path to preview image for model $owner, null if $owner model is not matched
+ */
+ protected function resolveLegacyPath(Model $owner): ?string {
+ return match (true) {
+ $owner instanceof Series => $owner->folder_id ? self::LEGACY_PREVIEW_PREFIX . "folders/{$owner->folder_id}.png" : null,
+ $owner instanceof Metadata => ($owner->video?->folder?->path && $owner->video_id) ? self::LEGACY_PREVIEW_PREFIX . "{$owner->video?->folder?->path}/{$owner->video_id}.png" : null,
+ default => tap(null, fn () => Log::warning('PreviewGeneratorService: resolveLegacyPath called with unsupported owner', ['owner' => $owner::class, 'id' => $owner->id])),
+ };
}
- protected function buildFolderPreviewData(Category $category, ?Folder $folder, Request $request, bool $generateRawPreview): array {
- $folderResource = $this->getDecodedResource(new FolderResource($folder));
- $thumbnail = $folder->series->thumbnail_url ?: $this->defaultThumbnail;
+ protected function buildFolderPreviewData(Category $category, ?Folder $folder, Request $request): array {
+ $series = $folder->series;
+
+ $seriesPoster = $series->primaryPoster?->path ? "storage/{$series->primaryPoster->path}" : $series->thumbnail_url;
+ $poster = $seriesPoster ?: $this->defaultPoster;
- $isAudio = $folderResource->is_majority_audio;
- $fileCount = $folderResource->file_count ?? 0;
+ $isAudio = $folder->isMajorityAudio();
+ $fileCount = $series->file_count ?? 0;
$fileType = ($isAudio ? 'Track' : 'Episode') . ($fileCount === 1 ? '' : 's');
- $contentString = ($folderResource->series->started_at ? $this->getMediaReleaseSeason($folderResource->series->started_at) . ' • ' : '') . "$fileCount $fileType";
- $studio = ucfirst($folderResource?->series?->studio);
+ $contentString = ($series->started_at ? $this->getMediaReleaseSeason($series->started_at) . ' • ' : '') . "$fileCount $fileType";
+ $studio = ucfirst($series?->studio);
- $data = [
- 'title' => "{$folderResource->series->title}",
- 'description' => $folderResource->series->description ?: 'No description is available.',
+ return [
+ 'title' => "{$series->title}",
+ 'description' => $series->description ?: 'No description is available.',
'studio' => ($studio ? $studio . ' · ' : '') . ucfirst($category->name),
'is_audio' => $isAudio,
- 'file_count' => $folderResource->file_count,
- 'thumbnail_url' => $this->encodeImageURL($thumbnail),
- 'upload_date' => $this->formatDate($folderResource->series->created_at),
+ 'file_count' => $fileCount,
+ 'thumbnail_url' => $this->encodeImageURL($poster),
+ 'upload_date' => $this->formatDate($series->created_at),
'content_string' => $contentString,
- 'rating' => $folderResource->series->rating,
- 'tags' => $folderResource->series->folder_tags ? array_map(fn ($tag) => $tag->name, $folderResource->series->folder_tags) : null,
+ 'rating' => $series->rating,
+ 'tags' => $series->folder_tags ? array_map(fn ($tag) => $tag->name, $series->folder_tags) : null,
'url' => $request->fullUrl(),
+ 'last_updated' => strtotime($series->updated_at ?? ''),
];
-
- return $this->preparePreviewData($data, "folders/{$folder->id}", strtotime($folderResource->series?->updated_at ?? ''), $generateRawPreview);
}
- protected function buildVideoPreviewData(Category $category, ?Folder $folder, string $videoId, Request $request, bool $generateRawPreview): array {
- $folderResource = $this->getDecodedResource(new FolderResource($folder->load('series.primaryPoster')));
- $video = $folder->videos()->findOrFail($videoId);
- $videoResource = $this->getDecodedResource(new VideoResource($video->load('metadata.videoTags', 'metadata.primaryPoster')));
+ protected function buildMediaPreviewData(Metadata $metadata, Request $request) {
+ $series = $metadata->video->folder->series;
+ $isAudio = $metadata->media_type === MediaType::AUDIO;
- $isAudio = str_starts_with($videoResource->metadata?->mime_type, 'audio');
- $thumbnail = $videoResource->metadata->poster_url ?: $folder->series->thumbnail_url ?: $this->defaultThumbnail;
+ // Poster for music does not auto migrate?
+ $metadataPoster = $metadata->primaryPoster?->path ? "storage/{$metadata->primaryPoster->path}" : $metadata->poster_url; // Backwards Compatible
+ $seriesPoster = $series->primaryPoster?->path ? "storage/{$series->primaryPoster->path}" : $series->thumbnail_url;
+ $poster = $seriesPoster ?: $this->defaultPoster;
+ $banner = $metadataPoster ?: $seriesPoster ?: $this->defaultPoster;
- $releaseDate = $this->formatDate($video->metadata->released_at ?: $video->metadata->file_modified_at);
- $contentString = $releaseDate . ' • ' . $this->formatDuration($videoResource?->metadata?->duration ?? null);
+ $releaseDate = $this->formatDate($metadata->released_at ?: $metadata->file_modified_at);
- $folderDateUpdated = strtotime($folderResource->series->updated_at);
- $videoDateUpdated = strtotime($videoResource->updated_at ?? '') ?: 0;
- $latestTimestamp = max($folderDateUpdated, $videoDateUpdated);
- $data = [
- 'title' => ucfirst($folderResource->series->title) . " · {$video->metadata->title}",
- 'description' => $video->metadata->description ?: $folderResource->series->description ?: 'No description is available.',
- 'thumbnail_url' => $this->encodeImageURL($thumbnail),
+ return [
+ 'title' => ucfirst($series->title) . " · {$metadata->title}",
+ 'description' => $metadata->description ?: $series->description ?: 'No description is available.',
+ 'thumbnail_url' => $this->encodeImageURL($poster),
+ 'banner_url' => $this->encodeImageURL($banner),
'is_audio' => $isAudio,
- 'content_string' => $contentString,
+ 'content_string' => $releaseDate . ' • ' . $this->formatDuration($metadata?->duration ?? null),
'release_date' => $releaseDate,
- 'upload_date' => $this->formatDate($video->metadata->file_modified_at),
- 'mime_type' => $video->mime_type,
- 'tags' => $videoResource->video_tags ? array_map(fn ($tag) => $tag->name, $videoResource->video_tags) : null,
- 'studio' => ucfirst($folderResource?->series?->studio ?? $category->name),
+ 'upload_date' => $this->formatDate($metadata->file_modified_at),
+ 'mime_type' => $metadata->mime_type,
+ 'tags' => $metadata->video_tags ? array_map(fn ($tag) => $tag->name, $metadata->video_tags) : [$this->formatFileSize($metadata->file_size), "{$metadata->resolution_height}P", strtoupper($metadata->codec)],
+ 'studio' => ucfirst($series?->studio ?? $metadata->video->folder->category->name),
'url' => $request->fullUrl(),
+ 'last_updated' => max(strtotime($series->updated_at), strtotime($metadata->updated_at ?? '') ?: 0),
];
-
- return $this->preparePreviewData($data, "{$folder->path}/{$video->id}", $latestTimestamp, $generateRawPreview);
}
- protected function preparePreviewData(array $baseData, string $pathKey, ?int $dataLastUpdated, bool $generateRawPreview): array {
+ protected function preparePreviewData(array $baseData, Model $owner, bool $generateRawPreview): array {
+ $dataLastUpdated = $baseData['last_updated'] ?? 0;
$baseData['raw'] = $baseData['thumbnail_url'];
- if (! $generateRawPreview && $generatedImage = $this->handleGenerateImage($baseData, $pathKey, $dataLastUpdated)) {
+ if (! $generateRawPreview && $generatedImage = $this->handleGenerateImage($owner, $baseData, $dataLastUpdated)) {
$baseData['thumbnail_url'] = $generatedImage;
$baseData['is_generated'] = true;
}
@@ -157,81 +243,87 @@ class PreviewGeneratorService {
return $baseData;
}
- public function generateImage(array $data, string $relativePath, bool $selfStore = false) {
- try {
- $tempRelativePath = 'previews/' . uniqid('og-', true) . '.png';
- $tempPath = Storage::disk('public')->path($tempRelativePath);
-
- Storage::disk('public')->makeDirectory(dirname($relativePath));
+ // region Rendering / Browsershot
- $chromeUserDataDir = storage_path('app/chrome');
- $chromeConfigHome = storage_path('app/chrome/.config');
+ /**
+ * Renders preview image and returns raw png data
+ */
+ protected function renderImage(array $data): string|false {
+ $tempRelativePath = 'cache/render-artifacts/previews/' . uniqid('og-', true) . '.png'; // TODO: use configured cache path
+ $tempAbsolutePath = Storage::path($tempRelativePath);
+ Storage::makeDirectory(dirname($tempRelativePath));
+ try {
$html = $this->generatePreviewPage($data);
- $browsershot = Browsershot::html($html)->windowSize(1200, 630)
+
+ $browsershot = Browsershot::html($html)
+ ->windowSize(1200, 630)
->deviceScaleFactor(2)
- ->waitUntilNetworkIdle()->setOption('args', [
+ ->waitUntilNetworkIdle()
+ ->setOption('args', [
'--disable-gpu',
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
- "--user-data-dir=$chromeUserDataDir",
+ '--user-data-dir=' . storage_path('app/chrome'),
'--disable-web-security',
'--font-render-hinting=none',
'--enable-features=NetworkService,NetworkServiceInProcess',
'--blink-settings=imagesEnabled=true',
])
- ->ignoreConsoleErrors()->setEnvironmentOptions([
- 'CHROME_CONFIG_HOME' => $chromeConfigHome,
- ]);
+ ->ignoreConsoleErrors()
+ ->setEnvironmentOptions(['CHROME_CONFIG_HOME' => storage_path('app/chrome/.config')]);
- $browsershot = $this->setChromiumBinary($browsershot);
- $browsershot->timeout(120)->save($tempPath);
+ $this->setChromiumBinary($browsershot);
+ $browsershot->timeout(120)->save($tempAbsolutePath);
- $imageContents = file_get_contents($tempPath);
- Storage::disk('public')->delete($tempRelativePath);
-
- $result = $imageContents;
-
- if ($selfStore) {
- Storage::disk('public')->put($relativePath, $imageContents);
- $result = VerifyFiles::getPathUrl($relativePath);
- }
-
- return $result;
- } catch (\Throwable $th) { // Cannot catch the specific spatie/image exception since it throws a generic one
+ return file_get_contents($tempAbsolutePath);
+ } catch (\Throwable $th) {
$message = $th->getMessage();
if ($message !== 'The spatie/image package is required to perform image manipulations. Please install it by running `composer require spatie/image`') {
- Log::error('Error during OG image generation', ['error' => $th->getMessage(), 'trace' => $th->getTraceAsString()]);
+ Log::error('Browsershot render failed', ['error' => $message, 'trace' => $th->getTraceAsString()]);
}
- if (file_exists($tempPath)) {
- $imageContents = file_get_contents($tempPath);
- Storage::disk('public')->delete($tempRelativePath);
- }
+ return file_exists($tempAbsolutePath) ? file_get_contents($tempAbsolutePath) : false;
+ } finally {
+ Storage::delete($tempRelativePath);
+ }
+ }
- if (! $selfStore || ! isset($imageContents)) {
- return $imageContents ?? false;
- }
+ protected function generatePreviewPage(array $data): string {
+ $appURL = config('app.host', 'app.test');
+
+ $appScheme = config('app.scheme');
+ $appSchemeURL = "$appScheme://$appURL";
+ $nonAppSchemeURL = ($appScheme === 'https' ? 'http' : 'https') . '://' . $appURL;
+ $internalURL = $appURL . ':' . config('app.port', $appScheme === 'https' ? 443 : 80);
- Storage::disk('public')->put($relativePath, $imageContents);
+ $html = view('og-media-preview', $data)->render();
- return VerifyFiles::getPathUrl($relativePath);
- }
+ // Have to manage what the local url is and effectively replace the public url. Chrome on the server system may not see the public url if any proxy is done on another system
+
+ $html = str_replace($nonAppSchemeURL, $appSchemeURL, $html); // replacing external scheme with internal scheme (http for docker, https for standard)
+ $html = str_replace($appURL . '/', $internalURL . '/', $html); // replacing external port (80 or 443) with internal port (8080 on docker or 443 on standard)
+
+ return $html;
}
+ // endregion
+
+ // region Puppeteer Utility
+
protected function canUseDocker(): bool {
try {
$dockerInfo = shell_exec('docker info --format "{{.ServerVersion}}" 2>&1');
return ! empty($dockerInfo) && ! str_contains(strtolower($dockerInfo), 'error');
- } catch (\Throwable $e) {
+ } catch (\Throwable) {
return false;
}
}
- protected function getPuppeteerChromiumPath(): string {
+ protected function getPuppeteerChromiumPath(): ?string {
try {
// Determine user home directory
$homeDir = getenv('HOME') ?: getenv('USERPROFILE');
@@ -249,71 +341,57 @@ class PreviewGeneratorService {
} catch (\Throwable $th) {
Log::warning('Puppeteer Chromium path not found', ['Error' => $th->getMessage()]);
- return '';
+ return null;
}
}
protected function resolveChromiumBinary(string $baseDir): ?string {
try {
- $platform = PHP_OS_FAMILY;
-
if (! is_dir($baseDir) || ! ($versions = glob($baseDir . '/*', GLOB_ONLYDIR)) || empty($versions[0])) {
throw new ChromiumException('Invalid chromium binary query');
}
foreach ($versions as $versionDir) {
- $binary = match ($platform) {
+ $binary = match (PHP_OS_FAMILY) {
'Windows' => $versionDir . '/chrome-win64/chrome.exe',
'Darwin' => $versionDir . '/chrome-mac/Chromium.app/Contents/MacOS/Chromium',
default => $versionDir . '/chrome-linux64/chrome',
};
- if (! file_exists($binary)) {
- throw new ChromiumException("Chromium binary not found at: {$binary}");
+ if (file_exists($binary)) {
+ return $binary;
}
-
- return $binary;
}
throw new ChromiumException('No chromium binary found');
- } catch (\Throwable $th) {
+ } catch (\Throwable) {
return null;
}
}
- public function setChromiumBinary(Browsershot $browsershot) {
+ protected function setChromiumBinary(Browsershot $browsershot): Browsershot {
if (file_exists('/run/current-system/sw/bin/chromium')) {
- $browsershot->setChromePath('/run/current-system/sw/bin/chromium');
- } elseif (file_exists('/usr/bin/chromium') || file_exists('/usr/bin/chromium-browser')) {
- $browsershot->setChromePath('/usr/bin/chromium');
- } elseif ($this->canUseDocker()) {
- $browsershot->useDocker();
- } elseif ($this->getPuppeteerChromiumPath()) {
- return $browsershot;
- } else {
- throw new ChromiumException('No Chromium or Docker available for Browsershot.');
+ return $browsershot->setChromePath('/run/current-system/sw/bin/chromium');
}
- return $browsershot;
- }
-
- protected function generatePreviewPage(array $data): string {
- $appURL = config('app.host', 'app.test');
+ if (file_exists('/usr/bin/chromium') || file_exists('/usr/bin/chromium-browser')) {
+ return $browsershot->setChromePath('/usr/bin/chromium');
+ }
- $appScheme = config('app.scheme');
- $appSchemeURL = "$appScheme://$appURL";
- $nonAppSchemeURL = ($appScheme === 'https' ? 'http' : 'https') . '://' . $appURL;
- $internalURL = $appURL . ':' . config('app.port', $appScheme === 'https' ? 443 : 80);
+ if ($this->canUseDocker()) {
+ return $browsershot->useDocker();
+ }
- $html = view('og-media-preview', $data)->render();
+ if ($this->getPuppeteerChromiumPath()) {
+ return $browsershot;
+ }
- // Have to manage what the local url is and effectively replace the public url. Chrome on the server system may not see the public url if any proxy is done on another system
+ throw new ChromiumException('No Chromium or Docker available for Browsershot.');
+ }
- $html = str_replace($nonAppSchemeURL, $appSchemeURL, $html); // replacing external scheme with internal scheme (http for docker, https for standard)
- $html = str_replace($appURL . '/', $internalURL . '/', $html); // replacing external port (80 or 443) with internal port (8080 on docker or 443 on standard)
+ // endregion
- return $html;
- }
+ // region Utility
protected function getMediaReleaseSeason(?string $dateString): ?string {
if (! $dateString) {
@@ -322,14 +400,15 @@ class PreviewGeneratorService {
try {
$date = Carbon::parse($dateString);
+
$season = match (true) {
- $date->month >= 1 && $date->month <= 3 => 'Winter ',
- $date->month >= 4 && $date->month <= 6 => 'Spring ',
- $date->month >= 7 && $date->month <= 9 => 'Summer ',
- default => 'Fall ',
+ $date->month <= 3 => 'Winter',
+ $date->month <= 6 => 'Spring',
+ $date->month <= 9 => 'Summer',
+ default => 'Fall',
};
- return $season . $date->year;
+ return "$season {$date->year}";
} catch (\Throwable) {
return null;
}
@@ -339,42 +418,79 @@ class PreviewGeneratorService {
return [
'title' => 'Media Server',
'description' => 'An auto-generated preview for bots.',
- 'thumbnail_url' => $this->defaultThumbnail,
+ 'thumbnail_url' => $this->defaultPoster,
'url' => $request->fullUrl(),
'is_audio' => false,
'mediaUrl' => null,
];
}
- protected function getDecodedResource($resource) {
- return json_decode(json_encode($resource));
+ protected function formatDate(?string $date, ?string $errorMessage = 'Unknown Date') {
+ return $date ? Carbon::createFromDate($date)->format('F Y') : $errorMessage;
+ }
+
+ protected function formatDuration(?int $seconds): string {
+ return $seconds ? CarbonInterval::seconds($seconds)->cascade()->forHumans(['short' => true]) : 'Unknown Duration';
}
- protected function formatDate(?string $date, ?string $errorMessage = 'Unknown Date') {
- if (! $date) {
- return $errorMessage;
+ /**
+ * Mimics /js/service/util.ts/formatFileSize()
+ */
+ protected function formatFileSize(int $size = 0, bool $space = true, int $divisor = 1024): string {
+ if ($size < 0) {
+ return 'Unknown size';
}
- return Carbon::createFromDate($date)->format('F Y');
- }
+ $unitIndex = 0;
+ $units = ['B', 'KB', 'MB', 'GB', 'TB'];
- protected function formatDuration(?int $seconds) {
- if (! $seconds) {
- return 'Unknown Duration';
+ while ($size >= $divisor && $unitIndex < count($units) - 1) {
+ $size /= $divisor;
+ $unitIndex++;
}
- return CarbonInterval::seconds($seconds)->cascade()->forHumans([
- 'short' => true,
- ]);
+ // 2 decimal places
+ $formattedSize = round(($size * 100) / 100);
+
+ return "$formattedSize" . ($space ? ' ' : '') . $units[$unitIndex];
}
+ /**
+ * Returns an encoded url for a given image
+ *
+ * Converts to an asset url if the given url is relative in app storage
+ *
+ * @param string $url Image URL
+ * @return string Encoded Image URL
+ */
protected function encodeImageURL(string $url): string {
- if (! filter_var($url, FILTER_VALIDATE_URL) && str_starts_with($url, '/storage')) {
- $url = config('app.url') . $url;
+ if (! filter_var($url, FILTER_VALIDATE_URL) && str_starts_with($url, 'storage/')) {
+ $url = asset($url);
}
return str_replace([chr(39), chr(34), ' '], ['%27', '%22', '%20'], $url);
}
+
+ // endregion
+
+ // region Side Effects
+
+ protected function queueRegeneration(Model $owner, array $data): void {
+ $alreadyRunning = SubTask::where('reference_uuid', $owner->uuid)
+ ->where('reference_type', ImageType::OGP)
+ ->whereIn('status', [TaskStatus::PENDING, TaskStatus::PROCESSING])
+ ->latest()
+ ->first();
+
+ if ($alreadyRunning) {
+ return;
+ } // Don't duplicate regeneration jobs (maybe use date to determine stale jobs in progress?)
+
+ $fileJobService = app(FileJobService::class);
+ $fileJobService->regeneratePreviewImages([['owner' => $owner, 'data' => $data]]);
+ }
+
+ // endregion
}
class ChromiumException extends Exception {}