[ATTACHMENTS] Follow URL redirects and don't duplicate attachments

This commit is contained in:
Diogo Peralta Cordeiro 2021-05-01 22:55:33 +01:00 committed by Hugo Sales
parent adb6680a01
commit 1e7d8cac9a
Signed by: someonewithpc
GPG Key ID: 7D0C7EAFC9D835A0
1 changed files with 19 additions and 11 deletions

View File

@ -22,6 +22,7 @@
namespace App\Core; namespace App\Core;
use App\Core\DB\DB; use App\Core\DB\DB;
use App\Util\Exception\NotFoundException;
use function App\Core\I18n\_m; use function App\Core\I18n\_m;
use App\Entity\Attachment; use App\Entity\Attachment;
use App\Util\Common; use App\Util\Common;
@ -75,17 +76,24 @@ class GSFile
{ {
if (Common::isValidHttpUrl($url)) { if (Common::isValidHttpUrl($url)) {
$head = HTTPClient::head($url); $head = HTTPClient::head($url);
$headers = $head->getHeaders(); // This must come before getInfo given that Symfony HTTPClient is lazy (thus forcing curl exec)
$headers = array_change_key_case($headers, CASE_LOWER); $headers = $head->getHeaders();
$attachment = Attachment::create([ $url = $head->getInfo('url'); // The last effective url (after getHeaders so it follows redirects)
'remote_url' => $url, $url_hash = hash(Attachment::URLHASH_ALGO, $url);
'remote_url_hash' => hash(Attachment::URLHASH_ALGO, $url), try {
'mimetype' => $headers['content-type'][0], return DB::findOneBy('attachment', ['remote_url_hash' => $url_hash]);
'is_local' => false, } catch (NotFoundException) {
]); $headers = array_change_key_case($headers, CASE_LOWER);
DB::persist($attachment); $attachment = Attachment::create([
Event::handle('AttachmentStoreNew', [&$attachment]); 'remote_url' => $url,
return $attachment; 'remote_url_hash' => $url_hash,
'mimetype' => $headers['content-type'][0],
'is_local' => false,
]);
DB::persist($attachment);
Event::handle('AttachmentStoreNew', [&$attachment]);
return $attachment;
}
} else { } else {
throw new \InvalidArgumentException(); throw new \InvalidArgumentException();
} }