[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

This commit is contained in:
Hugo Sales 2021-09-15 16:49:29 +01:00 committed by Diogo Peralta Cordeiro
parent 15a2a69274
commit f344ed376c
Signed by: diogo
GPG Key ID: 18D2D35001FBFAB0
2 changed files with 31 additions and 6 deletions

View File

@ -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

View File

@ -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