koel/app/Services/YouTubeService.php

57 lines
1.6 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;
2022-08-08 16:00:59 +00:00
use App\Services\ApiClients\YouTubeClient;
use Illuminate\Cache\Repository as Cache;
2016-07-14 08:47:50 +00:00
2022-08-08 16:00:59 +00:00
class YouTubeService
2016-07-14 08:47:50 +00:00
{
2022-08-08 16:00:59 +00:00
public function __construct(private YouTubeClient $client, private Cache $cache)
{
}
2016-07-14 08:47:50 +00:00
/**
* Determine if our application is using YouTube.
*/
2022-08-08 16:00:59 +00:00
public static function enabled(): bool
2016-07-14 08:47:50 +00:00
{
2022-08-08 16:00:59 +00:00
return (bool) config('koel.youtube.key');
2016-07-14 08:47:50 +00:00
}
2021-06-05 10:47:56 +00:00
public function searchVideosRelatedToSong(Song $song, string $pageToken = '') // @phpcs:ignore
2016-07-30 15:32:17 +00:00
{
$q = $song->title;
// If the artist is worth noticing, include them into the search.
2017-06-03 23:21:50 +00:00
if (!$song->artist->is_unknown && !$song->artist->is_various) {
$q .= " {$song->artist->name}";
2016-07-30 15:32:17 +00:00
}
return $this->search($q, $pageToken);
}
/**
* Search for YouTube videos by a query string.
2016-07-14 08:47:50 +00:00
*
2021-06-05 10:47:56 +00:00
* @param string $q The query string
2016-07-14 08:47:50 +00:00
* @param string $pageToken YouTube page token (e.g. for next/previous page)
2021-06-05 10:47:56 +00:00
* @param int $perPage Number of results per page
2016-07-14 08:47:50 +00:00
*
*/
2022-08-08 16:00:59 +00:00
private function search(string $q, string $pageToken = '', int $perPage = 10) // @phpcs:ignore
{
2022-08-08 16:00:59 +00:00
return attempt_if(static::enabled(), function () use ($q, $pageToken, $perPage) {
$uri = sprintf(
'search?part=snippet&type=video&maxResults=%s&pageToken=%s&q=%s',
$perPage,
urlencode($pageToken),
urlencode($q)
);
return $this->cache->remember(md5("youtube_$uri"), now()->addWeek(), fn () => $this->client->get($uri));
});
}
2016-07-14 08:47:50 +00:00
}