Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

koel/koel

16858 stars
2 code files
View koel/koel on GitHub

app/Services/YouTubeService.php

Open in GitHub
use App\Models\Song;
use Throwable;
 
class YouTubeService extends AbstractApiClient implements ApiConsumerInterface
{
public function enabled(): bool
{
return (bool) $this->getKey();
}
 
public function searchVideosRelatedToSong(Song $song, string $pageToken = '') // @phpcs:ignore
{
$q = $song->title;
 
if (!$song->artist->is_unknown && !$song->artist->is_various) {
$q .= " {$song->artist->name}";
}
 
return $this->search($q, $pageToken);
}
 
public function search(string $q, string $pageToken = '', int $perPage = 10) // @phpcs:ignore
{
if (!$this->enabled()) {
return null;
}
 
$uri = sprintf(
'search?part=snippet&type=video&maxResults=%s&pageToken=%s&q=%s',
$perPage,
urlencode($pageToken),
urlencode($q)
);
 
try {
return $this->cache->remember(md5("youtube_$uri"), 60 * 24 * 7, fn () => $this->get($uri));
} catch (Throwable $e) {
$this->logger->error($e);
 
return null;
}
}
 
public function getEndpoint(): ?string
{
return config('koel.youtube.endpoint');
}
 
public function getKey(): ?string
{
return config('koel.youtube.key');
}
 
public function getSecret(): ?string
{
return null;
}
}

app/Http/Controllers/API/YouTubeController.php

Open in GitHub
use App\Http\Requests\API\YouTubeSearchRequest;
use App\Models\Song;
use App\Services\YouTubeService;
 
class YouTubeController extends Controller
{
private YouTubeService $youTubeService;
 
public function __construct(YouTubeService $youTubeService)
{
$this->youTubeService = $youTubeService;
}
 
public function searchVideosRelatedToSong(YouTubeSearchRequest $request, Song $song)
{
return response()->json($this->youTubeService->searchVideosRelatedToSong($song, $request->pageToken));
}
}

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.