<?php
namespace NexCRM\WebBundle\Controller\Front;
use Doctrine\ORM\EntityManagerInterface;
use NexCRM\BaseBundle\Entity\Setting;
use NexCRM\BaseBundle\Repository\SettingRepository;
use League\OAuth2\Client\Provider\Instagram;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpClient\CurlHttpClient;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Annotation\Route;
class FeedController extends AbstractController
{
private EntityManagerInterface $entityManager;
private string $baseUrl;
private string $dataUrl;
private Setting $clientId;
private Setting $clientSecret;
private Setting $clientToken;
private CurlHttpClient $curl;
public function __construct(
EntityManagerInterface $entityManager,
SettingRepository $settingRepository
) {
$this->curl = new CurlHttpClient();
$this->entityManager = $entityManager;
$this->baseUrl = 'https://api.instagram.com';
$this->dataUrl = 'https://graph.instagram.com';
$this->clientId = $settingRepository->findOneBy(['alias' => 'instagram_client_id']);
$this->clientSecret = $settingRepository->findOneBy(['alias' => 'instagram_client_secret']);
$this->clientToken = $settingRepository->findOneBy(['alias' => 'instagram_token']);
}
/**
* @Route("/instagram/", name="instagram")
*/
public function instagramAction(Request $request)
{
if (empty($this->clientToken)
|| empty($this->clientToken->getValue())) {
exit('Missing token');
}
$instagramPhotos = [];
$cache = './instagram.json';
if (file_exists($cache) && filemtime($cache) > time() - 60*60) {
$jsonData = json_decode(file_get_contents($cache));
} else {
$data = ["query" => [
'fields' => 'id, caption, media_url, permalink, media_type, thumbnail_url',
'access_token' => $this->clientToken->getValue()
]];
$response = $this->curl->request(
'GET',
$this->dataUrl."/me/media",
$data
);
$jsonData = json_decode($response->getContent());
if (!empty(reset($jsonData->data)->media_url)) {
file_put_contents($cache, json_encode($jsonData));
}
}
foreach ($jsonData->data as $key => $value) {
$instagramPhotos[$value->id]["link"] = $value->permalink;
$instagramPhotos[$value->id]["url"] = $value->media_url;
$instagramPhotos[$value->id]["type"] = $value->media_type;
$instagramPhotos[$value->id]["thumb"] = $value->thumbnail_url??'';
$instagramPhotos[$value->id]["text"] = $value->caption??'';
}
return new JsonResponse($instagramPhotos);
}
/** @Route("/instagram/init/", name="instagram_init") */
public function instagramInitAction(Request $request)
{
if (!empty($this->clientToken) && !empty($this->clientToken->getValue())) {
exit('Duplicate initialization');
}
if (empty($this->clientId)
|| empty($this->clientSecret)
|| empty($this->clientId->getValue())
|| empty($this->clientSecret->getValue())
) {
exit('Invalid client credentials');
}
$session = new Session();
$provider = new Instagram([
'clientId' => $this->clientId->getValue(),
'clientSecret' => $this->clientSecret->getValue(),
'redirectUri' => explode('?', $request->getUri())[0],
'host' => $this->baseUrl,
'graphHost' => $this->dataUrl
]);
if (!isset($_GET['code'])) {
$authUrl = $provider->getAuthorizationUrl(['scope' => 'user_profile,user_media']);
$session->set('oauth2state', $provider->getState());
header('Location: '.$authUrl);
exit;
} elseif (empty($_GET['state']) || ($_GET['state'] !== $session->get('oauth2state'))) {
$session->remove('oauth2state');
exit('Invalid state');
} else {
$token = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
try {
//$user = $provider->getResourceOwner($token);
$data = ["query" => [
'grant_type' => 'ig_exchange_token',
'access_token' => $token->getToken(),
'client_secret' => $this->clientSecret->getValue()
]];
$response = $this->curl->request(
'GET',
$this->dataUrl."/access_token",
$data
);
$responseData = json_decode($response->getContent());
if (empty($responseData->access_token)) {
exit('Invalid response');
}
$this->clientToken->setValue($responseData->access_token);
$this->entityManager->persist($this->clientToken);
$this->entityManager->flush();
} catch (\Exception $e) {
exit('Oh dear...');
}
}
return new Response('Ok');
}
/** @Route("/instagram/refresh/", name="instagram_refresh") */
public function instagramRefreshAction(Request $request)
{
if (empty($this->clientToken)
|| empty($this->clientToken->getValue())) {
exit('Missing token');
}
try {
$data = ["query" => [
'grant_type' => 'ig_refresh_token',
'access_token' => $this->clientToken->getValue()
]];
$response = $this->curl->request(
'GET',
$this->dataUrl."/refresh_access_token",
$data
);
$responseData = json_decode($response->getContent());
if (empty($responseData->access_token)) {
exit('Invalid response');
}
$this->clientToken->setValue($responseData->access_token);
$this->entityManager->persist($this->clientToken);
$this->entityManager->flush();
} catch (\Exception $e) {
exit('Oh dear...');
}
return new Response(!empty($responseData->expires_in)?'Ok - '.$responseData->expires_in:'Error');
}
}