FacebookFetcher.php in Media entity facebook 3.x
File
src/FacebookFetcher.php
View source
<?php
namespace Drupal\media_entity_facebook;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
class FacebookFetcher {
protected $loggerChannel;
protected $httpClient;
protected $languageManager;
protected $apiErrorEncountered = FALSE;
protected $config;
protected $cache;
public function __construct(LoggerChannelFactoryInterface $logger_channel_factory, ClientInterface $client, LanguageManagerInterface $language_manager, ConfigFactoryInterface $configFactory, CacheBackendInterface $cache) {
$this->loggerChannel = $logger_channel_factory
->get('media_entity_facebook');
$this->httpClient = $client;
$this->languageManager = $language_manager;
$this->config = $configFactory
->get('media_entity_facebook.settings');
$this->cache = $cache;
}
public function getOembedData($resource_url) {
if ($this->apiErrorEncountered) {
$this->loggerChannel
->error('Aborting Facebook oembed API request due to a previously encountered error on the same request.');
return FALSE;
}
$appId = $this->config
->get('facebook_app_id') ?: '';
$appSecret = $this->config
->get('facebook_app_secret') ?: '';
if (empty($appId) || empty($appSecret)) {
$this->loggerChannel
->error('Cannot retrieve Facebook embed as the Facebook app ID and/or app secret are missing from configuration. Visit /admin/config/media/facebook-settings to provide these values.');
return FALSE;
}
$endpoint = $this
->getApiEndpointUrl($resource_url) . '?url=' . $resource_url . '&access_token=' . $appId . '|' . $appSecret;
$cid = 'media_entity_facebook:' . Crypt::hashBase64(serialize($endpoint));
$cacheItem = $this->cache
->get($cid);
if ($cacheItem) {
$oembedResponse = $cacheItem->data;
}
else {
$options = [
'timeout' => 5,
'headers' => [
'Accept-Language' => $this->languageManager
->getCurrentLanguage()
->getId(),
],
];
try {
$response = $this->httpClient
->request('GET', $endpoint, $options);
} catch (GuzzleException $e) {
$this->loggerChannel
->error('Error retrieving oEmbed data for a Facebook media entity: @error', [
'@error' => $e
->getMessage(),
]);
$this->apiErrorEncountered = TRUE;
return FALSE;
}
$oembedResponse = json_decode((string) $response
->getBody(), TRUE);
$cacheTime = \Drupal::time()
->getRequestTime() + 600;
$this->cache
->set($cid, $oembedResponse, $cacheTime);
}
return $oembedResponse;
}
protected function getApiEndpointUrl($content_url) {
if (preg_match('/\\/videos\\//', $content_url) || preg_match('/\\/video.php\\//', $content_url)) {
return 'https://graph.facebook.com/v10.0/oembed_video';
}
else {
return 'https://graph.facebook.com/v10.0/oembed_post';
}
}
}