<?php
namespace App\Controller\Admin;
//require_once '../vendor/autoload.php';
use Google\Client;
use App\Entity\InstantIndexing;
use Symfony\Component\Mercure\Update;
use App\Repository\LanguageRepository;
use Doctrine\ORM\EntityManagerInterface;
use Google\Http\Batch as Google_Http_Batch;
use Symfony\Component\Mercure\HubInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Console\Output\BufferedOutput;
use Google\Service\Indexing as Google_Service_Indexing;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Google\Service\Webmasters as Google_Service_Webmasters;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Google\Service\SearchConsole as Google_Service_SearchConsole;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Google\Service\Indexing\UrlNotification as Google_Service_Indexing_UrlNotification;
use Google\Service\SearchConsole\InspectUrlIndexRequest as Google_Service_SearchConsole_InspectUrlIndexRequest;
use Google\Service\Webmasters\SearchAnalyticsQueryRequest as Google_Service_Webmasters_SearchAnalyticsQueryRequest;
class ApiIndexingController extends AbstractController
{
private $em;
private $languages;
public function __construct(EntityManagerInterface $em,LanguageRepository $languages){
$this->em = $em;
$this->languages = $languages->findActifLang();
}
/**
* @Security("not is_granted('ROLE_BLOG')")
* @Route("/console/instant-indexing", methods={"GET","POST"}, name="admin_instant_indexing")
*/
public function InstantIndexing(Request $request)
{
$action = 'edit_config';
$quotas = null;
$config_indexing = $this->getDoctrine()->getRepository(InstantIndexing::class)->find(1);
if(!$config_indexing){
$action = 'create_config';
$config_indexing = new InstantIndexing();
}elseif($config_indexing->getApiRequests() != null){
$quotas = $this->get_limits($config_indexing->getApiRequests());
}
if ($request->isMethod('POST')) {
$config = $request->request->get('config');
if(empty($config)){
$config_indexing->setConfig(null);
}else{
$config_indexing->setConfig($config);
}
if($action == "create_config"){
$this->em->persist($config_indexing);
}
$this->em->flush();
return $this->redirectToRoute('admin_instant_indexing');
}
return $this->render('admin/dashboards/instant_indexing/index.html.twig',[
'config_indexing'=> $config_indexing,
'quotas'=> $quotas,
]);
}
/**
* @Security("not is_granted('ROLE_BLOG')")
* @Route("/console/instant-indexing-api", methods={"POST"}, name="admin_instant_indexing_api", condition="request.isXmlHttpRequest()")
*/
public function send_to_api(Request $request)
{
$data = [];
$config_indexing = $this->getDoctrine()->getRepository(InstantIndexing::class)->find(1);
$urls = preg_split('/\r\n|\n\r|\r|\n/',$request->request->get('urls'));
$urls_count = count($urls);
$action = $request->request->get('action');
if($config_indexing){
$client = new Client();
$client->setAuthConfig(json_decode($config_indexing->getConfig(),true));
$client->setConfig( 'base_path', 'https://indexing.googleapis.com' );
$client->addScope( 'https://www.googleapis.com/auth/indexing' );
$client->setUseBatch( true );
$service = new Google_Service_Indexing($client);
$batch = new Google_Http_Batch($client, false, 'https://indexing.googleapis.com');
foreach ($urls as $key => $url) {
$post_body = new Google_Service_Indexing_UrlNotification();
if($action == 'status'){
$request_part = $service->urlNotifications->getMetadata( [ 'url' => $url ] );
}else{
$post_body->setType( $action === 'update' ? 'URL_UPDATED' : 'URL_DELETED' );
$post_body->setUrl($url);
$request_part = $service->urlNotifications->publish($post_body);
}
$batch->add( $request_part, 'url-' . $key );
}
$results = $batch->execute();
$res_count = count( $results );
foreach ( $results as $id => $response ) {
$local_id = substr($id,9);
if(is_a($response,'Google_Service_Exception')){
$data[ $local_id ] = json_decode( $response->getMessage() );
}else{
$data[ $local_id ] = (array) $response->toSimpleObject();
}
if($res_count === 1){
$data = $data[ $local_id ];
}
}
$this->log_request($action,$urls_count,$config_indexing);
}
return new JsonResponse($data);
}
public function log_request( $type, $number = 1,$config_indexing ) {
if($config_indexing->getApiRequests() != null){
$requests_log = unserialize($config_indexing->getApiRequests());
}else{
$requests_log = [
'update' => [],
'delete' => [],
'status' => [],
'bing_submit' => [],
];
}
if (!isset( $requests_log[$type] ) ) {
$requests_log[$type] = [];
}
$add = array_fill(0, $number, time() );
$requests_log[$type] = array_merge( $requests_log[$type], $add );
if(count($requests_log[$type]) > 600 ) {
$requests_log[$type] = array_slice( $requests_log[ $type ], -600, 600, true );
}
$config_indexing->setApiRequests(serialize($requests_log));
$this->em->flush();
}
public function get_limits($api_requests) {
$requests_log = unserialize($api_requests);
$current_limits = [
'publishperday' => 0,
'permin' => 0,
'metapermin' => 0,
'bing_submitperday' => 0,
];
$limit_publishperday = 200;
$limit_permin = 600;
$limit_metapermin = 180;
$limit_bingsubmitperday = 10;
// $requests_log = [
// 'update' => [],
// 'delete' => [],
// 'status' => [],
// 'bing_submit' => [],
// ];
$timestamp_1day_ago = strtotime( '-1 day' );
$timestamp_1min_ago = strtotime( '-1 minute' );
$publish_1day = 0;
$all_1min = 0;
$meta_1min = 0;
foreach ( $requests_log['update'] as $time ) {
if ( $time > $timestamp_1day_ago ) {
$publish_1day++;
}
if ( $time > $timestamp_1min_ago ) {
$all_1min++;
}
}
foreach ( $requests_log['delete'] as $time ) {
if ( $time > $timestamp_1min_ago ) {
$all_1min++;
}
}
foreach ( $requests_log['status'] as $time ) {
if ( $time > $timestamp_1min_ago ) {
$all_1min++;
$meta_1min++;
}
}
$bing_submit_1day = 0;
if ( ! isset( $requests_log['bing_submit'] ) ) {
$requests_log['bing_submit'] = [];
}
foreach ( $requests_log['bing_submit'] as $time ) {
if ( $time > $timestamp_1day_ago ) {
$bing_submit_1day++;
}
}
$current_limits['publishperday'] = $limit_publishperday - $publish_1day;
$current_limits['permin'] = $limit_permin - $all_1min;
$current_limits['metapermin'] = $limit_metapermin - $meta_1min;
$current_limits['bing_submitperday'] = $limit_bingsubmitperday - $bing_submit_1day;
$current_limits['publishperday_max'] = $limit_publishperday;
$current_limits['permin_max'] = $limit_permin;
$current_limits['metapermin_max'] = $limit_metapermin;
$current_limits['bing_submitperday_max'] = $limit_bingsubmitperday;
return $current_limits;
}
}