external_media/Classes/Soundcloud/OnlineMediaHelper.php

107 lines
3.2 KiB
PHP

<?php
namespace Codappix\ExternalTypo3Multimedia\Soundcloud;
/*
* Copyright (C) 2020 Daniel Siepmann <coding@daniel-siepmann.de>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use TYPO3\CMS\Core\Http\Uri;
use TYPO3\CMS\Core\Resource\File;
use TYPO3\CMS\Core\Resource\Folder;
use TYPO3\CMS\Core\Resource\OnlineMedia\Helpers\AbstractOEmbedHelper;
use TYPO3\CMS\Core\Utility\GeneralUtility;
class OnlineMediaHelper extends AbstractOEmbedHelper
{
public function transformUrlToFile($url, Folder $targetFolder)
{
$id = null;
$uri = new Uri($url);
if ($uri->getHost() === Registration::DOMAIN) {
$id = trim($uri->getPath(), '/');
}
if ($id === null) {
return null;
}
return $this->transformMediaIdToFile($id, $targetFolder, $this->extension);
}
public function getPublicUrl(File $file, $relativeToCurrentScript = false)
{
return sprintf(
'https://' . Registration::DOMAIN . '/%s',
$this->getOnlineMediaId($file)
);
}
public function getPreviewImage(File $file)
{
$data = $this->getOEmbedData($this->getOnlineMediaId($file));
if ($data === false || isset($data['thumbnail_url']) === false) {
return '';
}
$imageContent = GeneralUtility::getUrl($data['thumbnail_url']);
if ($imageContent === false) {
return '';
}
$tempName = GeneralUtility::tempnam($file->getNameWithoutExtension(), $file->getExtension());
GeneralUtility::writeFile($tempName, $imageContent);
return $tempName;
}
// Wrap original to add caching.
// Otherwise foreign API might be called multiple times.
protected function getOEmbedData($mediaId)
{
static $data = [];
if (isset($data[$mediaId]) === false) {
$data[$mediaId] = parent::getOEmbedData($mediaId);
}
return $data[$mediaId];
}
public function getMetaData(File $file)
{
$oEmbed = $this->getOEmbedData($this->getOnlineMediaId($file));
$metadata = parent::getMetaData($file);
if (empty($file->getProperty('description'))) {
$metadata['description'] = strip_tags($oEmbed['description']);
}
return $metadata;
}
protected function getOEmbedUrl($mediaId, $format = 'json')
{
return sprintf(
'https://' . Registration::DOMAIN . '/oembed?format=%s&url=%s',
rawurlencode($format),
sprintf('https://' . Registration::DOMAIN . '/%s', $mediaId)
);
}
}