vendor/nexcrm/nexcrm-web-bundle/src/Controller/Front/FeedController.php line 49

Open in your IDE?
  1. <?php
  2. namespace NexCRM\WebBundle\Controller\Front;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use NexCRM\BaseBundle\Entity\Setting;
  5. use NexCRM\BaseBundle\Repository\SettingRepository;
  6. use League\OAuth2\Client\Provider\Instagram;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpClient\CurlHttpClient;
  9. use Symfony\Component\HttpFoundation\JsonResponse;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\HttpFoundation\Session\Session;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. class FeedController extends AbstractController
  15. {
  16.     private EntityManagerInterface $entityManager;
  17.     private string $baseUrl;
  18.     private string $dataUrl;
  19.     private Setting $clientId;
  20.     private Setting $clientSecret;
  21.     private Setting $clientToken;
  22.     private CurlHttpClient $curl;
  23.     public function __construct(
  24.         EntityManagerInterface $entityManager,
  25.         SettingRepository $settingRepository
  26.     ) {
  27.         $this->curl = new CurlHttpClient();
  28.         $this->entityManager $entityManager;
  29.         $this->baseUrl 'https://api.instagram.com';
  30.         $this->dataUrl 'https://graph.instagram.com';
  31.         $this->clientId $settingRepository->findOneBy(['alias' => 'instagram_client_id']);
  32.         $this->clientSecret $settingRepository->findOneBy(['alias' => 'instagram_client_secret']);
  33.         $this->clientToken $settingRepository->findOneBy(['alias' => 'instagram_token']);
  34.     }
  35.     /**
  36.      * @Route("/instagram/", name="instagram")
  37.      */
  38.     public function instagramAction(Request $request)
  39.     {
  40.         if (empty($this->clientToken)
  41.             || empty($this->clientToken->getValue())) {
  42.             exit('Missing token');
  43.         }
  44.         $instagramPhotos = [];
  45.         $cache './instagram.json';
  46.         if (file_exists($cache) && filemtime($cache) > time() - 60*60) {
  47.             $jsonData json_decode(file_get_contents($cache));
  48.         } else {
  49.             $data = ["query" => [
  50.                 'fields' => 'id, caption, media_url, permalink, media_type, thumbnail_url',
  51.                 'access_token' => $this->clientToken->getValue()
  52.             ]];
  53.             $response $this->curl->request(
  54.                 'GET',
  55.                 $this->dataUrl."/me/media",
  56.                 $data
  57.             );
  58.             $jsonData json_decode($response->getContent());
  59.             if (!empty(reset($jsonData->data)->media_url)) {
  60.                 file_put_contents($cachejson_encode($jsonData));
  61.             }
  62.         }
  63.         foreach ($jsonData->data as $key => $value) {
  64.             $instagramPhotos[$value->id]["link"] = $value->permalink;
  65.             $instagramPhotos[$value->id]["url"] = $value->media_url;
  66.             $instagramPhotos[$value->id]["type"] = $value->media_type;
  67.             $instagramPhotos[$value->id]["thumb"] = $value->thumbnail_url??'';
  68.             $instagramPhotos[$value->id]["text"] = $value->caption??'';
  69.         }
  70.         return new JsonResponse($instagramPhotos);
  71.     }
  72.     /** @Route("/instagram/init/", name="instagram_init") */
  73.     public function instagramInitAction(Request $request)
  74.     {
  75.         if (!empty($this->clientToken) && !empty($this->clientToken->getValue())) {
  76.             exit('Duplicate initialization');
  77.         }
  78.         if (empty($this->clientId)
  79.             || empty($this->clientSecret)
  80.             || empty($this->clientId->getValue())
  81.             || empty($this->clientSecret->getValue())
  82.         ) {
  83.             exit('Invalid client credentials');
  84.         }
  85.         $session = new Session();
  86.         $provider = new Instagram([
  87.             'clientId'          => $this->clientId->getValue(),
  88.             'clientSecret'      => $this->clientSecret->getValue(),
  89.             'redirectUri'       => explode('?'$request->getUri())[0],
  90.             'host'              => $this->baseUrl,
  91.             'graphHost'         => $this->dataUrl
  92.         ]);
  93.         if (!isset($_GET['code'])) {
  94.             $authUrl $provider->getAuthorizationUrl(['scope' => 'user_profile,user_media']);
  95.             $session->set('oauth2state'$provider->getState());
  96.             header('Location: '.$authUrl);
  97.             exit;
  98.         } elseif (empty($_GET['state']) || ($_GET['state'] !== $session->get('oauth2state'))) {
  99.             $session->remove('oauth2state');
  100.             exit('Invalid state');
  101.         } else {
  102.             $token $provider->getAccessToken('authorization_code', [
  103.                 'code' => $_GET['code']
  104.             ]);
  105.             try {
  106.                 //$user = $provider->getResourceOwner($token);
  107.                 $data = ["query" => [
  108.                     'grant_type' => 'ig_exchange_token',
  109.                     'access_token' => $token->getToken(),
  110.                     'client_secret' => $this->clientSecret->getValue()
  111.                 ]];
  112.                 $response $this->curl->request(
  113.                     'GET',
  114.                     $this->dataUrl."/access_token",
  115.                     $data
  116.                 );
  117.                 $responseData json_decode($response->getContent());
  118.                 if (empty($responseData->access_token)) {
  119.                     exit('Invalid response');
  120.                 }
  121.                 $this->clientToken->setValue($responseData->access_token);
  122.                 $this->entityManager->persist($this->clientToken);
  123.                 $this->entityManager->flush();
  124.             } catch (\Exception $e) {
  125.                 exit('Oh dear...');
  126.             }
  127.         }
  128.         return new Response('Ok');
  129.     }
  130.     /** @Route("/instagram/refresh/", name="instagram_refresh") */
  131.     public function instagramRefreshAction(Request $request)
  132.     {
  133.         if (empty($this->clientToken)
  134.            || empty($this->clientToken->getValue())) {
  135.             exit('Missing token');
  136.         }
  137.         try {
  138.             $data = ["query" => [
  139.                 'grant_type' => 'ig_refresh_token',
  140.                 'access_token' => $this->clientToken->getValue()
  141.             ]];
  142.             $response $this->curl->request(
  143.                 'GET',
  144.                 $this->dataUrl."/refresh_access_token",
  145.                 $data
  146.             );
  147.             $responseData json_decode($response->getContent());
  148.             if (empty($responseData->access_token)) {
  149.                 exit('Invalid response');
  150.             }
  151.             $this->clientToken->setValue($responseData->access_token);
  152.             $this->entityManager->persist($this->clientToken);
  153.             $this->entityManager->flush();
  154.         } catch (\Exception $e) {
  155.             exit('Oh dear...');
  156.         }
  157.         return new Response(!empty($responseData->expires_in)?'Ok - '.$responseData->expires_in:'Error');
  158.     }
  159. }