Newer
Older
/***************************************************************
* 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;
use TYPO3\CMS\Core\Site\Entity\Site;
use TYPO3\CMS\Core\Utility\GeneralUtility;
Stefan Galinski
committed
* YouTube Helper Service
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
class YoutubeService {
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;
}
/**
* 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.
*
* @param array $jsonArray
* @param string $youtubeId
* @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)
* @param string $apiKey
* @return array
*/
public function mapArray(
$jsonArray = [],
$youtubeId = '',
$aspectRatio = '16:9',
$thumbnailType = 'byAspectRatio',
$apiKey = ''
): array {
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'];
}
if (!in_array($thumbnailType, ['maxres', 'standard', 'high', 'medium', 'default', 'byAspectRatio'])) {
$thumbnailType = 'byAspectRatio';
}
if (!in_array($aspectRatio, ['16:9', '4:3'])) {
$aspectRatio = '16:9';
}
$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;
}
if ($currentLanguageUid > 0 && $youtubeId && $apiKey) {
$jsonArray = $this->addLocalizationData($jsonArray, $apiKey, $currentLanguageUid);
}
$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.
$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'],
];
}
return $result;
}
/**
* 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) {
return $jsonArray;
}
$localizationData = $this->getDetailedVideoInformationForJsonArray(
$jsonArray,
$apiKey,
self::API_PART_LOCALIZATIONS
);
if (!isset($localizationData['items']) || (is_countable($localizationData['items']) ? count(
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
return $jsonArray;
}
$site = $this->getSite();
if ($site === NULL) {
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) {
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
continue;
}
$title = '';
$description = '';
$localizations = $localizationEntry['localizations'];
foreach ($languageIsoCodes as $languageIsoCode) {
if ($title && $description) {
break;
}
if (!$title && isset($localizations[$languageIsoCode]['title'])) {
$title = $localizations[$languageIsoCode]['title'];
}
if (!$description && isset($localizations[$languageIsoCode]['description'])) {
$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 $youtubeId
* @param string $maxResults
* @param string $apiKey
* @param string $url
* @return array|mixed
*/
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);
if ($cachedResult) {
return $cachedResult;
}
}
$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) $exception->getResponse()->getBody();
}
$jsonArray = ($jsonString !== '' ? json_decode($jsonString, TRUE) : []);
if ($jsonArray === NULL) {
throw new InvalidArgumentException(
'There is something wrong with loaded JSON or encoded data is deeper than the recursion limit.',
403
);
}
if (!$jsonArray) {
throw new InvalidArgumentException('JSON could\'t be parsed.', 403);
}
// By API documentation provided 'error' key is sent if, probably,
// URL cannot return JSON data or Permission is denied.
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
if (isset($jsonArray['error'])) {
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);
}
if (!$disableYoutubeCache) {
$this->cache->set($cacheKey, $jsonArray, [], self::CACHE_LIFETIME_IN_SECONDS);
}
return $jsonArray;
}
/**
* 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'];
}