Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
jan-dh committed Dec 9, 2024
1 parent 631fe3a commit ec40418
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 59 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Release Notes for Dynamic meta images

## 4.0.2 - 2024-12-09
- Fixed whitespace in title / file naming

## 4.0.1 - 2024-09-22
- Fixed a missing html tag in the 1.twig example
- Update the documentation
Expand Down
9 changes: 5 additions & 4 deletions src/jobs/GenerateImage.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ class GenerateImage extends BaseJob
public function execute($queue): void
{
if (!$this->entryId || !$this->templateString) {
Craft::error("Missing required parameters for image generation.", __METHOD__);
return;
}

Expand All @@ -24,13 +25,13 @@ public function execute($queue): void
$imageUrl = $imageService->generateImage($this->entryId, $this->templateString, $this->siteHandle);

if (!$imageUrl) {
Craft::error("Image URL is empty. Image generation might have failed.", __METHOD__);
return;
Craft::warning("No image URL returned. This might be expected if asset creation failed.", __METHOD__);
} else {
Craft::info("Image generated successfully: $imageUrl", __METHOD__);
}

Craft::info("Image generated successfully: $imageUrl", __METHOD__);
} catch (Throwable $e) {
Craft::error("Failed to generate image: {$e->getMessage()}", __METHOD__);
throw $e;
}
}

Expand Down
117 changes: 62 additions & 55 deletions src/services/ImageService.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,73 +18,80 @@ class ImageService extends Component
{
public function generateImage(string $entryId, string $templateString, string $siteHandle)
{
$html = $this->renderTemplateFromEntryId($entryId, $templateString, $siteHandle);
$html = $this->renderTemplateFromEntryId($entryId, $templateString, $siteHandle);

$settings = DynamicMetaImages::$plugin->getSettings();
$settings = DynamicMetaImages::$plugin->getSettings();
$siteSettings = $settings->getSiteSettings($siteHandle);
$volumeHandle = $siteSettings['volumeHandle'];
$filename = $entryId . '.png';
$title = $entryId;

$filename = $entryId . '.png';
$title = $entryId;

$volume = Craft::$app->volumes->getVolumeByHandle($volumeHandle);
if (!$volume) {
throw new \Exception('No volume selected for saving images.');
}
$folder = Craft::$app->getAssets()->getRootFolderByVolumeId($volume->id);
if (!$folder) {
throw new Exception('Failed to get root folder for volume: ' . $volume->name);
}
if (!$folder) {
throw new Exception('Failed to get root folder for volume: ' . $volume->name);
}

preg_match('/<title>(.*?)<\/title>/s', $html, $matches);
if (!empty($matches[1])) {
$title = $matches[1];
$filename = $title . '.png';
$title = $title;
}
preg_match('/<title>(.*?)<\/title>/s', $html, $matches);
if (!empty($matches[1])) {
$cleanTitle = trim(preg_replace('/\s+/', ' ', $matches[1]));
$filename = $cleanTitle . '.png';
$title = $cleanTitle;
}

$tempPath = Craft::$app->getPath()->getTempPath() . '/' . $filename;
$existingAsset = Asset::find()->filename($filename)->folderId($folder->id)->one();

try {
Browsershot::html($html)
->setNodeBinary(App::env('NODE_BINARY'))
->setNpmBinary(App::env('NPM_BINARY'))
->windowSize(1200, 675)
->deviceScaleFactor(3)
->setOption('args', ['--disable-web-security'])
->waitUntilNetworkIdle()
->save($tempPath);

if ($existingAsset) {
$existingAsset->tempFilePath = $tempPath;
$existingAsset->avoidFilenameConflicts = true;
$existingAsset->setScenario(Asset::SCENARIO_REPLACE);

$existingAsset->validate();
Craft::$app->getElements()->saveElement($existingAsset, false);

// Save the asset with its new file
if (!Craft::$app->getElements()->saveElement($existingAsset, false)) {
throw new Exception('Failed to replace file for existing asset: ' . implode(", ", $existingAsset->getErrorSummary(true)));
}
} else {
$asset = new Asset();
$asset->tempFilePath = $tempPath;
$asset->filename = $filename;
$asset->folderId = $folder->id;
$asset->kind = "image";
$asset->title = $title;
$asset->setVolumeId($volume->id);
$asset->setScenario(Asset::SCENARIO_CREATE);

$asset->validate();
Craft::$app->getElements()->saveElement($asset, false);

// Save the new asset
if (!Craft::$app->getElements()->saveElement($asset, false)) {
throw new Exception('Failed to save new asset: ' . implode(", ", $asset->getErrorSummary(true)));
}
};

$existingAsset = Asset::find()
->filename($filename)
->folderId($folder->id)
->one();

try {
Browsershot::html($html)
->setNodeBinary(App::env('NODE_BINARY'))
->setNpmBinary(App::env('NPM_BINARY'))
->windowSize(1200, 675)
->deviceScaleFactor(3)
->setOption('args', ['--disable-web-security'])
->waitUntilNetworkIdle()
->save($tempPath);

$assetToReturn = null;

if ($existingAsset) {
$existingAsset->tempFilePath = $tempPath;
$existingAsset->avoidFilenameConflicts = true;
$existingAsset->setScenario(Asset::SCENARIO_REPLACE);

if (!Craft::$app->getElements()->saveElement($existingAsset)) {
throw new Exception('Failed to update existing asset: ' . implode(", ", $existingAsset->getErrorSummary(true)));
}

$assetToReturn = $existingAsset;
} else {
$newAsset = new Asset();
$newAsset->tempFilePath = $tempPath;
$newAsset->filename = $filename;
$newAsset->title = $title;
$newAsset->folderId = $folder->id;
$newAsset->volumeId = $volume->id;
$newAsset->kind = "image";
$newAsset->avoidFilenameConflicts = true;
$newAsset->setScenario(Asset::SCENARIO_CREATE);

// Save the new asset
if (!Craft::$app->getElements()->saveElement($newAsset)) {
throw new Exception('Failed to save new asset: ' . implode(", ", $newAsset->getErrorSummary(true)));
}

$assetToReturn = $newAsset;
};

return $assetToReturn->getUrl();

} catch (\Exception $e) {
Craft::error('Failed to generate image: ' . $e->getMessage(), __METHOD__);
Expand Down

0 comments on commit ec40418

Please sign in to comment.