koel/app/Services/YouTube.php

91 lines
2.2 KiB
PHP
Raw Normal View History

2016-07-14 08:47:50 +00:00
<?php
namespace App\Services;
2016-07-30 15:32:17 +00:00
use App\Models\Song;
2016-07-14 08:47:50 +00:00
use Cache;
use GuzzleHttp\Client;
class YouTube extends RESTfulService
{
/**
* Construct an instance of YouTube service.
*
* @param string $key The YouTube API key
* @param Client|null $client The Guzzle HTTP client
*/
public function __construct($key = null, Client $client = null)
{
parent::__construct(
2016-08-21 15:19:03 +00:00
$key ?: config('koel.youtube.key'),
2016-07-14 08:47:50 +00:00
null,
'https://www.googleapis.com/youtube/v3',
$client ?: new Client()
);
}
/**
* Determine if our application is using YouTube.
*
* @return bool
*/
public function enabled()
{
2016-08-21 15:19:03 +00:00
return (bool) config('koel.youtube.key');
2016-07-14 08:47:50 +00:00
}
/**
2016-07-30 15:32:17 +00:00
* Search for YouTube videos related to a song.
*
2016-07-30 15:34:34 +00:00
* @param Song $song
2016-07-30 15:32:17 +00:00
* @param string $pageToken
*
* @return object|false
*/
2016-08-03 10:42:11 +00:00
public function searchVideosRelatedToSong(Song $song, $pageToken = '')
2016-07-30 15:32:17 +00:00
{
$q = $song->title;
// If the artist is worth noticing, include them into the search.
if (!$song->artist->isUnknown() && !$song->artist->isVarious()) {
$q .= ' '.$song->artist->name;
}
return $this->search($q, $pageToken);
}
/**
* Search for YouTube videos by a query string.
2016-07-14 08:47:50 +00:00
*
* @param string $q The query string
* @param string $pageToken YouTube page token (e.g. for next/previous page)
* @param int $perPage Number of results per page
*
* @return object|false
*/
public function search($q, $pageToken = '', $perPage = 10)
{
if (!$this->enabled()) {
return false;
}
2016-07-30 15:32:17 +00:00
$uri = sprintf('search?part=snippet&type=video&maxResults=%s&pageToken=%s&q=%s',
2016-07-14 08:47:50 +00:00
$perPage,
urlencode($pageToken),
urlencode($q)
);
$cacheKey = md5("youtube_$uri");
if ($response = Cache::get($cacheKey)) {
return $response;
}
if ($response = $this->get($uri)) {
// Cache the result for 7 days
Cache::put($cacheKey, $response, 60 * 24 * 7);
}
return $response;
}
}