Newer
Older
namespace SGalinski\SgYoutube\Service;
/***************************************************************
* Copyright notice
*
* (c) sgalinski Internet Services (https://www.sgalinski.de)
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project 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 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script 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.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
use Exception;
use GuzzleHttp\Exception\ClientException;
Fabian Galinski
committed
use InvalidArgumentException;
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
Fabian Galinski
committed
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Context\Exception\AspectNotFoundException;
use TYPO3\CMS\Core\Context\LanguageAspect;
Fabian Galinski
committed
use TYPO3\CMS\Core\Http\ServerRequest;
Fabian Galinski
committed
use TYPO3\CMS\Core\Site\Entity\Site;
use TYPO3\CMS\Core\Utility\GeneralUtility;
Stefan Galinski
committed
* YouTube Helper Service
public const API_URL = 'https://www.googleapis.com/youtube/v3/';
public const API_CHANNEL = 'search';
public const API_PLAYLIST = 'playlistItems';
public const API_VIDEO = 'videos';
public const API_PART = 'snippet';
public const API_PART_LOCALIZATIONS = 'localizations';
public const API_ORDER_BY = 'date';
public const CACHE_LIFETIME_IN_SECONDS = 86400;
/**
* @var FrontendInterface
*/
protected $cache;
/**
* @param FrontendInterface $cache
*/
public function __construct(FrontendInterface $cache) {
$this->cache = $cache;
}
Stefan Galinski
committed
* Maps the json array from the YouTube call to return some unified value. The output from YouTube is pretty
* unsteady. Also we calculate the correct thumbnail sized and so on.
*
Johannes Kreiner
committed
* @param array $jsonArray
* @param string $youtubeId
Stefan Galinski
committed
* @param string $aspectRatio 16:9 (default) or 4:3 (ONLY used if byAspectRation is set as thumbnail type)
* @param string $thumbnailType maxres, standard, high, medium, default, byAspectRatio (default)
Fabian Galinski
committed
* @param string $apiKey
Johannes Kreiner
committed
* @return array
*/
Stefan Galinski
committed
public function mapArray(
$jsonArray = [],
$youtubeId = '',
$aspectRatio = '16:9',
$thumbnailType = 'byAspectRatio',
$apiKey = ''
Stefan Galinski
committed
): array {
Fabian Galinski
committed
if (count($jsonArray) <= 0) {
return $jsonArray;
}
// Normalize the data to video details.
if (strpos($youtubeId, 'UC') === 0 || strpos($youtubeId, 'PL') === 0) {
$result = $this->getDetailedVideoInformationForJsonArray($jsonArray, $apiKey, self::API_PART);
if (count($result) <= 0 || !isset($result['items'])) {
return $jsonArray;
}
$jsonArray = $result['items'];
}
Stefan Galinski
committed
if (!in_array($thumbnailType, ['maxres', 'standard', 'high', 'medium', 'default', 'byAspectRatio'])) {
$thumbnailType = 'byAspectRatio';
Stefan Galinski
committed
if (!in_array($aspectRatio, ['16:9', '4:3'])) {
$aspectRatio = '16:9';
Johannes Kreiner
committed
}
Kevin Ditscheid
committed
$context = GeneralUtility::makeInstance(Context::class);
try {
/** @var LanguageAspect $languageAspect */
$languageAspect = $context->getAspect('language');
$currentLanguageUid = $languageAspect->getId();
} catch (AspectNotFoundException $e) {
// Can't be possible to land here, otherwise the whole frontend would be weird as hell..
$currentLanguageUid = 0;
}
Fabian Galinski
committed
Kevin Ditscheid
committed
if ($currentLanguageUid > 0 && $youtubeId && $apiKey) {
$jsonArray = $this->addLocalizationData($jsonArray, $apiKey, $currentLanguageUid);
Fabian Galinski
committed
}
Stefan Galinski
committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
$result = [];
foreach ($jsonArray as $field) {
$previewImage = [];
$resolutionTypes = ['maxres', 'standard', 'high', 'medium', 'default'];
if ($thumbnailType !== 'byAspectRatio') {
array_unshift($resolutionTypes, $thumbnailType);
}
foreach ($resolutionTypes as $type) {
if (isset($field['snippet']['thumbnails'][$type])) {
$previewImage = $field['snippet']['thumbnails'][$type];
if ($thumbnailType === 'byAspectRatio' && isset($previewImage['height'])) {
$aspectRatioOfImage = $previewImage['width'] / $previewImage['height'];
if ($aspectRatio === '16:9' && $aspectRatioOfImage > 1.7 && $aspectRatioOfImage < 1.9) {
break;
}
if ($aspectRatio === '4:3' && $aspectRatioOfImage > 1.2 && $aspectRatioOfImage < 1.4) {
break;
}
} else {
break;
}
}
}
// Don't cache the preview URL. YouTube has a CDN and delivers much faster.
Stefan Galinski
committed
$result[] = [
'title' => $field['snippet']['title'],
'description' => strip_tags($field['snippet']['description']),
'thumbnail' => $previewImage['url'],
'url' => 'https://www.youtube.com/watch?v=' . $field['id'],
'publishedAt' => $field['snippet']['publishedAt'],
Stefan Galinski
committed
];
}
Stefan Galinski
committed
return $result;
}
Fabian Galinski
committed
/**
* Adds the localized title and description for each of the given entries in the jsonArray and returns it.
*
* @param array $jsonArray
* @param string $apiKey
* @param int $currentLanguageUid
*
* @return array
*/
protected function addLocalizationData(array $jsonArray, $apiKey, $currentLanguageUid): array {
if (!$apiKey || !$currentLanguageUid || count($jsonArray) <= 0) {
Fabian Galinski
committed
return $jsonArray;
}
$localizationData = $this->getDetailedVideoInformationForJsonArray(
$jsonArray,
$apiKey,
self::API_PART_LOCALIZATIONS
if (!isset($localizationData['items']) || (is_countable($localizationData['items']) ? count(
$localizationData['items']
) : 0) <= 0) {
Fabian Galinski
committed
return $jsonArray;
}
$site = $this->getSite();
if ($site === NULL) {
Fabian Galinski
committed
return $jsonArray;
}
$languages = $site->getLanguages();
$currentSiteLanguage = $languages[$currentLanguageUid];
if (!$currentSiteLanguage) {
return $jsonArray;
}
$languageIsoCodes = [
$currentSiteLanguage->getTwoLetterIsoCode()
];
foreach ($currentSiteLanguage->getFallbackLanguageIds() as $languageId) {
$siteLanguage = $languages[$languageId];
if (!$siteLanguage) {
continue;
}
$languageIsoCodes[] = $siteLanguage->getTwoLetterIsoCode();
}
foreach ($localizationData['items'] as $index => $localizationEntry) {
if (!isset($localizationEntry['localizations']) || (is_countable(
$localizationEntry['localizations']
) ? count($localizationEntry['localizations']) : 0) <= 0) {
Fabian Galinski
committed
continue;
}
$title = '';
$description = '';
$localizations = $localizationEntry['localizations'];
foreach ($languageIsoCodes as $languageIsoCode) {
if ($title && $description) {
break;
}
if (!$title && isset($localizations[$languageIsoCode]['title'])) {
Fabian Galinski
committed
$title = $localizations[$languageIsoCode]['title'];
}
if (!$description && isset($localizations[$languageIsoCode]['description'])) {
Fabian Galinski
committed
$description = $localizations[$languageIsoCode]['description'];
}
}
if ($title) {
$jsonArray[$index]['snippet']['title'] = $title;
}
if ($description) {
$jsonArray[$index]['snippet']['description'] = $description;
}
}
return $jsonArray;
}
/**
* Returns the detailed video information for the given json array and returns them as an array.
*
* @param array $jsonArray
* @param string $apiKey
* @param string $part
*
* @return array
*/
public function getDetailedVideoInformationForJsonArray(array $jsonArray, $apiKey, $part): array {
if (!$apiKey || count($jsonArray) <= 0) {
return $jsonArray;
}
$apiUrl = self::API_URL . self::API_VIDEO;
$parameters = [];
$parameters['part'] = $part;
$parameters['key'] = $apiKey;
$query = http_build_query($parameters);
foreach ($jsonArray as $videoData) {
$videoId = '';
if (isset($videoData['snippet']['resourceId']['videoId'])) {
$videoId = trim($videoData['snippet']['resourceId']['videoId']);
}
if (!$videoId && isset($videoData['id'])) {
$videoId = $videoData['id']['videoId'] ?? $videoData['id'];
// This is a check, because the $videoData['id'] can be a whole sub-channel-id.
if (is_array($videoId)) {
continue;
}
$videoId = trim($videoId);
}
if (!$videoId) {
continue;
}
$query .= '&id=' . $videoId;
}
$result = $this->getJsonAsArray('', '10', $apiKey, $apiUrl . '?' . $query);
if (!isset($result['items']) || (is_countable($result['items']) ? count($result['items']) : 0) <= 0) {
return $jsonArray;
}
return $result;
}
* Returns a JSON array with the video details (title, description, preview image, url)
*
* @param string $maxResults
* @param string $apiKey
Fabian Galinski
committed
* @param string $url
Fabian Galinski
committed
public function getJsonAsArray($youtubeId = '', $maxResults = '10', $apiKey = '', $url = '') {
if (!$url) {
$url = $this->getApiUrl($youtubeId, $maxResults, $apiKey);
}
$cacheKey = 'sg_youtube' . sha1($url);
$disableYoutubeCache = (bool) GeneralUtility::_GP('disableYoutubeCache');
if (!$disableYoutubeCache) {
$cachedResult = $this->cache->get($cacheKey);
$requestFactory = GeneralUtility::makeInstance(RequestFactory::class);
try {
$site = $this->getSite();
if ($site === NULL) {
throw new Exception('No site object found!');
}
$response = $requestFactory->request($url, 'GET', [
'headers' => [
'Referer' => $site->getBase()->getHost()
]
]);
$jsonString = (string) $response->getBody();
} catch (ClientException $exception) {
$jsonString = (string) $exception->getResponse()->getBody();
$jsonArray = ($jsonString !== '' ? json_decode($jsonString, TRUE) : []);
if ($jsonArray === NULL) {
'There is something wrong with loaded JSON or encoded data is deeper than the recursion limit.',
403
throw new InvalidArgumentException('JSON could\'t be parsed.', 403);
Stefan Galinski
committed
// By API documentation provided 'error' key is sent if, probably,
// URL can not return JSON data or Permission is denied.
throw new InvalidArgumentException('Message: ' . $jsonArray['error']['message'], 403);
if (!isset($jsonArray['items'])) {
throw new InvalidArgumentException('No items array.', 403);
}
if ((is_countable($jsonArray['items']) ? count($jsonArray['items']) : 0) < 1) {
throw new InvalidArgumentException('No items found.', 403);
}
$this->cache->set($cacheKey, $jsonArray, [], self::CACHE_LIFETIME_IN_SECONDS);
return $jsonArray;
Stefan Galinski
committed
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/**
* Returns the YouTube API URL
*
* @param string $youtubeId
* @param string $maxResults
* @param string $apiKey
* @return string
*/
public function getApiUrl($youtubeId = '', $maxResults = '10', $apiKey = ''): string {
$apiUrl = self::API_URL;
$parameters = [];
if (strpos($youtubeId, 'UC') === 0) {
$apiUrl .= self::API_CHANNEL;
$parameters['channelId'] = $youtubeId;
} elseif (strpos($youtubeId, 'PL') === 0) {
$apiUrl .= self::API_PLAYLIST;
$parameters['playlistId'] = $youtubeId;
} else {
$apiUrl .= self::API_VIDEO;
$parameters['id'] = $this->removeIdParameters($youtubeId);
}
$parameters['order'] = self::API_ORDER_BY;
$parameters['part'] = self::API_PART;
$parameters['key'] = $apiKey;
$parameters['maxResults'] = $maxResults;
$query = http_build_query($parameters);
return $apiUrl . '?' . $query;
}
/**
* Removes GET parameters following the ID
*
* @param string $youtubeId
* @return array|string
*/
protected function removeIdParameters($youtubeId = '') {
if (strpos($youtubeId, '&')) {
return explode('&', $youtubeId)[0];
}
return $youtubeId;
}
/**
* Get the current site of the request
*
* @return Site|null
*/
protected function getSite(): ?Site {
/** @var ServerRequest $request */
$request = $GLOBALS['TYPO3_REQUEST'];
$attributes = $request->getAttributes();
if (!isset($attributes['site'])) {
return NULL;
}
return $attributes['site'];
}