Advertisement
okardec

Youtube API v3

May 7th, 2015
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 9.64 KB | None | 0 0
  1. <?php
  2. /**
  3.  * API do Youtube v3
  4.  * por Allan Kardec (07/05/2015)
  5.  * como usar: http://pastebin.com/V4Xi47qG
  6.  */
  7. class YoutubeAPI3 {
  8.  
  9.  
  10.     /**
  11.      * A API KEY agora deve ser criada no console de desenvolvedor do Google
  12.      * https://console.developers.google.com/
  13.      * Primeiro cria-se o projeto, e confirma se a permissão do usuário da conta esta OK
  14.      * vá em "APIs e Autenticações > APIs" localize a do Youtube e ative
  15.      * apos va em "Credenciais" e crie uma "chave de acesso público"
  16.      * confirme que ela esteja com a opção "Qualquer IP permitido" ativo
  17.      * o valor retornado e a API_KEY     *
  18.      */
  19.     const API_KEY = "xxxxxxxxxxxxxsssssssxxx";
  20.    
  21.     //url para requisição montada >> https://www.googleapis.com/youtube/v3/[METHOD]?key=[API_KEY]&id=[ID_VIDEO]&part=[PARAMS]
  22.     const PATH = "https://www.googleapis.com/youtube/v3/[METHOD]?key=[API_KEY]";
  23.     /**
  24.      * Indica se a url foi carregada com sucesso
  25.      *
  26.      * @var bool
  27.      */
  28.     protected $lodaed;
  29.    
  30.     /**
  31.      * Objeto formado pelo JSON retornado pela API.
  32.      *
  33.      * @var JSON
  34.      */
  35.     protected $json;
  36.    
  37.     /**
  38.      * Metodo construtor
  39.      *
  40.      * @param string[optional] $method >> método que deve carregar, ex: videos
  41.      * @param string[optional] $idVideo >> id do vídeo a ser carregado
  42.      * @param array[optional] $param >> parametros necessarios para recuperar os dados do vídeo, ex: snippet,contentDetails,statistics,status
  43.      */
  44.     public function __construct($method=null,$idVideo=null,array $param=null){
  45.         $this->setLodead(false);
  46.         if (isset($method)){
  47.             $this->load($method,$idVideo,$param);                        
  48.         }
  49.     }
  50.    
  51.     private static function isValid($response){
  52.         return strpos($response,'"totalResults": 0,')==false;
  53.     }
  54.        
  55.     /**
  56.      * como o resultado vem por um json, com a requisição via url, poderia pegar via file_get_content
  57.      * mas prefiro usar o CURL por ser mais confiavel é maleavel se for necessario em algum momento passar dados via post/cookie
  58.      */
  59.     private static function getData($URL){             
  60.         $header = array();     
  61.         $header[0]= "Accept: text/xml,application/xml,application/xhtml+xml,";
  62.         $header[0].= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  63.         $header[] = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1';
  64.         $header[] = "Cache-Control: max-age=0";
  65.         $header[] = "Connection: keep-alive";
  66.         $header[] = "Keep-Alive: 300";
  67.         $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
  68.         $header[] = "Accept-Language: pt-br,pt;q=0.8,en-us;q=0.5,en;q=0.3";
  69.         $header[] = "Pragma: "; // browsers keep this blank.
  70.         $header[] = 'Content-type: text/html; charset=utf-8';
  71.                
  72.         $ch = curl_init();
  73.         curl_setopt($ch, CURLOPT_URL,$URL);
  74.         curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  75.         curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);    
  76.                
  77.         /*$cookie='';  
  78.         curl_setopt($ch, CURLOPT_COOKIE,$cookie);   */
  79.                
  80.         $result=curl_exec ($ch);
  81.         curl_close ($ch);
  82.                
  83.         return $result;
  84.     }
  85.    
  86.     /**
  87.      * Define se a url foi carregada
  88.      *
  89.      * @param bool $loaded
  90.      */
  91.     protected function setLodead($loaded){
  92.         $this->lodaed = $loaded;
  93.     }
  94.     /**
  95.      * Indica se a url foi carregada com sucesso.
  96.      *
  97.      * @return bool
  98.      */
  99.     protected function isLoaded(){
  100.         return $this->lodaed;
  101.     }
  102.     /**
  103.      * Indica se o Xml foi carregado com sucesso
  104.      *
  105.      * @return bool
  106.      */
  107.     public function isValidResponse(){
  108.         return $this->isLoaded();
  109.     }
  110.     /**
  111.      * Caso exista um erro no carregamento, retorna a descrição
  112.      *
  113.      * @return string
  114.      */
  115.     public function getErrorDescription(){
  116.         if (!$this->isLoaded()){
  117.             return "A requisição não foi realizada corretamente";
  118.         }else{
  119.             return "Nenhum erro encontrado";
  120.         }
  121.     }
  122.     /**
  123.      * Caso existe um erro no carregmaento, retorna um número indicando ou 0 se estiver certo.
  124.      *
  125.      * @return int
  126.      */
  127.     public function getErrorCode(){
  128.         if (!$this->isLoaded()){
  129.             return 666;
  130.         }
  131.         return 0;      
  132.     }
  133.    
  134.        
  135.     /**
  136.      * Define o objeto JSON
  137.      *
  138.      * @param obj JSON
  139.      */
  140.     protected function setJSON($json){
  141.         $this->json = $json;
  142.     }
  143.     /**
  144.      * Retorna o objeto JSON
  145.      *
  146.      * @return obj JSON
  147.      */
  148.     public function getJSON(){
  149.         return $this->json;
  150.     }
  151.    
  152.     /**
  153.      * Carrega a API do Youtube
  154.      *
  155.      * @param string $method
  156.      * @param array[optional] $param
  157.      * @return bool
  158.      */
  159.     public function load($method,$idVideo=null,array $param){
  160.         //monta a url da requisição
  161.         //exemplo: https://www.googleapis.com/youtube/v3/[METHOD]?key=[API_KEY]&id=[ID_VIDEO]&part=[PARAMS]
  162.        
  163.         $path = self::PATH;
  164.         $path = str_replace('[METHOD]',$method,$path);
  165.         $path = str_replace('[API_KEY]',self::API_KEY,$path);
  166.                        
  167.         $url_parts = array();        
  168.         if(isset($idVideo)){
  169.             $url_parts[] = 'id='.$idVideo;
  170.         }
  171.         if(isset($param)){
  172.             $url_parts[] = 'part='.implode(',',$param);
  173.         }
  174.         if(count($url_parts)>0){
  175.             $path.='&'.implode('&',$url_parts);
  176.         }
  177.        
  178.         $this->setLodead(false);
  179.         $json = $this->getData($path);
  180.         if(!$this->isValid($json)){
  181.             die($this->getErrorDescription());
  182.         }
  183.         $this->setLodead(true);
  184.        
  185.         try {
  186.             @$this->setJSON(json_decode($json));
  187.         }catch (Exception $e){
  188.             $this->setLodead(false);
  189.             $e->getCode();
  190.         }
  191.            
  192.         return $this->isLoaded();
  193.     }
  194.    
  195.     /**
  196.      * este metodo é responsavel por retornar os segundos corretamente
  197.      * passa uma string no formato 1:00:00 para segundos
  198.      * é meio "gato" mas funciona
  199.      *
  200.      * @param strin $time >>deve receber a string normalizada 1:00
  201.      * @return int $seconds;
  202.      */
  203.     private function adjustSeconds($time){
  204.         $seconds = 0;
  205.        
  206.         //1:16:51
  207.         $i = explode(':',trim($time));
  208.         //somente segundos
  209.         if(count($i)==1){
  210.             $seconds = (int)$i[0];
  211.         }
  212.         //minutos + segundos
  213.         if(count($i)==2){
  214.             $seconds+= (int)$i[0]*60;
  215.             $seconds+= (int)$i[1];
  216.         }
  217.         //hora + minutos + segundos
  218.         if(count($i)==3){
  219.             $seconds+= (int)$i[0]*60*60;
  220.             $seconds+= (int)$i[1]*60;
  221.             $seconds+= (int)$i[2];
  222.         }  
  223.        
  224.         return $seconds;
  225.     }
  226.     /**
  227.      * metodo para retornar os dados dos vídeos mais amigavelmente
  228.      * só irá funcionar se o retorno for a lista de vídeos  
  229.      *
  230.      * @return json >>retorna um array com os dados simplificados dos vídeos
  231.      */
  232.     public function fetchVideoData(){
  233.    
  234.         $json = $this->getJSON();
  235.        
  236.         $videos = array();
  237.        
  238.         $total = $json->pageInfo->resultsPerPage;
  239.         if($total<=0){
  240.             return $videos;
  241.         }      
  242.         for($n=0;$n!=$total;$n++){
  243.             //monto o array do video com os elementos vazios, para preencher logo a baixo
  244.             $videoObj = array('id'=>'','title'=>'','description'=>'','time'=>'','time_friendly'=>'','seconds'=>0,'dimension'=>'','definition'=>'','caption'=>'','thumbs'=>array());
  245.            
  246.             $videoObj['id'] = $json->items[0]->id;
  247.            
  248.             if(isset($json->items[0]->snippet)){           
  249.                 $videoObj['title'] = $json->items[0]->snippet->title;
  250.                 $videoObj['description'] = $json->items[0]->snippet->description;          
  251.             }
  252.             if(isset($json->items[0]->contentDetails)){
  253.                 $videoObj['time'] = $json->items[0]->contentDetails->duration;
  254.                 $videoObj['time_friendly'] = str_replace(array('PT','S'),'',str_replace(array('H','M'),':',$json->items[0]->contentDetails->duration));
  255.                
  256.                 $videoObj['seconds'] = $this->adjustSeconds($videoObj['time_friendly']);
  257.                
  258.                 $videoObj['dimension'] = $json->items[0]->contentDetails->dimension;
  259.                 $videoObj['definition'] = $json->items[0]->contentDetails->definition;
  260.                 $videoObj['caption'] = $json->items[0]->contentDetails->caption;
  261.             }
  262.            
  263.             if(isset($json->items[0]->snippet->thumbnails)){       
  264.                 $thumbs = array('default'=>array(),'medium'=>array(),'high'=>array(),'standard'=>array(),'maxres'=>array());   
  265.                
  266.                 if(isset($json->items[0]->snippet->thumbnails->default)){      
  267.                     $thumbItem = array();
  268.                     $thumbItem['url'] = $json->items[0]->snippet->thumbnails->default->url;
  269.                     $thumbItem['width'] = $json->items[0]->snippet->thumbnails->default->width;
  270.                     $thumbItem['height'] = $json->items[0]->snippet->thumbnails->default->height;
  271.                     $thumbs['default'] = $thumbItem;
  272.                 }
  273.                 if(isset($json->items[0]->snippet->thumbnails->medium)){       
  274.                     $thumbItem = array();
  275.                     $thumbItem['url'] = $json->items[0]->snippet->thumbnails->medium->url;
  276.                     $thumbItem['width'] = $json->items[0]->snippet->thumbnails->medium->width;
  277.                     $thumbItem['height'] = $json->items[0]->snippet->thumbnails->medium->height;
  278.                     $thumbs['medium'] = $thumbItem;
  279.                 }
  280.                 if(isset($json->items[0]->snippet->thumbnails->high)){     
  281.                     $thumbItem = array();
  282.                     $thumbItem['url'] = $json->items[0]->snippet->thumbnails->high->url;
  283.                     $thumbItem['width'] = $json->items[0]->snippet->thumbnails->high->width;
  284.                     $thumbItem['height'] = $json->items[0]->snippet->thumbnails->high->height;
  285.                     $thumbs['high'] = $thumbItem;
  286.                 }
  287.                 if(isset($json->items[0]->snippet->thumbnails->standard)){     
  288.                     $thumbItem = array();
  289.                     $thumbItem['url'] = $json->items[0]->snippet->thumbnails->standard->url;
  290.                     $thumbItem['width'] = $json->items[0]->snippet->thumbnails->standard->width;
  291.                     $thumbItem['height'] = $json->items[0]->snippet->thumbnails->standard->height;
  292.                     $thumbs['standard'] = $thumbItem;
  293.                 }
  294.                 if(isset($json->items[0]->snippet->thumbnails->maxres)){       
  295.                     $thumbItem = array();
  296.                     $thumbItem['url'] = $json->items[0]->snippet->thumbnails->maxres->url;
  297.                     $thumbItem['width'] = $json->items[0]->snippet->thumbnails->maxres->width;
  298.                     $thumbItem['height'] = $json->items[0]->snippet->thumbnails->maxres->height;
  299.                     $thumbs['maxres'] = $thumbItem;
  300.                 }
  301.                
  302.                 $videoObj['thumbs'] = $thumbs;         
  303.             }
  304.            
  305.            
  306.             $videos[] = $videoObj;
  307.        
  308.         }
  309.                  
  310.         ///normaliza o array, transformando o em json
  311.         ///parece bobagem, mas facilita a utilização dos nodos
  312.         return json_decode(json_encode(array('total'=>count($videos),'items'=>$videos)));  
  313.     }
  314.    
  315.    
  316. }
  317.  
  318. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement