From f344ed376cb35b25309db9cb58b01feb6b4592b0 Mon Sep 17 00:00:00 2001 From: Hugo Sales Date: Wed, 15 Sep 2021 16:49:29 +0100 Subject: [PATCH] [ATTACHMENTS][Embed][UI] Allow plugins to provide a title for an attachment, if a note has none, implement such a mechanism in Embed and cache the result, since it is potentially costly --- plugins/Embed/Embed.php | 11 +++++++++++ src/Entity/Attachment.php | 26 ++++++++++++++++++++------ 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/plugins/Embed/Embed.php b/plugins/Embed/Embed.php index 53da857889..42a42f78fa 100644 --- a/plugins/Embed/Embed.php +++ b/plugins/Embed/Embed.php @@ -485,6 +485,17 @@ class Embed extends Plugin return HTTPClient::get($url)->getContent(); } + public function onAttachmentGetBestTitle(Attachment $attachment, Note $note, ?string &$title) + { + try { + $embed = DB::findOneBy('attachment_embed', ['attachment_id' => $attachment->getId()]); + $title = $embed->getTitle(); + return Event::stop; + } catch (NotFoundException) { + } + return Event::next; + } + /** * Event raised when GNU social polls the plugin for information about it. * Adds this plugin's version information to $versions array diff --git a/src/Entity/Attachment.php b/src/Entity/Attachment.php index 1c00445d30..5e9aed84db 100644 --- a/src/Entity/Attachment.php +++ b/src/Entity/Attachment.php @@ -21,8 +21,10 @@ namespace App\Entity; +use App\Core\Cache; use App\Core\DB\DB; use App\Core\Entity; +use App\Core\Event; use App\Core\GSFile; use function App\Core\I18n\_m; use App\Core\Log; @@ -294,12 +296,24 @@ class Attachment extends Entity { // If we have a note, then the best title is the title itself if (!is_null(($note))) { - $attachment_to_note = DB::findOneBy('attachment_to_note', [ - 'attachment_id' => $this->getId(), - 'note_id' => $note->getId(), - ]); - if (!is_null($attachment_to_note->getTitle())) { - return $attachment_to_note->getTitle(); + $title = Cache::get('attachment-title-' . $this->getId() . '-' . $note->getId(), function () use ($note) { + try { + $attachment_to_note = DB::findOneBy('attachment_to_note', [ + 'attachment_id' => $this->getId(), + 'note_id' => $note->getId(), + ]); + if (!is_null($attachment_to_note->getTitle())) { + return $attachment_to_note->getTitle(); + } + } catch (NotFoundException) { + $title = null; + Event::handle('AttachmentGetBestTitle', [$this, $note, &$title]); + return $title; + } + return null; + }); + if ($title != null) { + return $title; } } // Else