repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/ProxyAuthService.php | app/Services/ProxyAuthService.php | <?php
namespace App\Services;
use App\Attributes\RequiresPlus;
use App\Models\User;
use App\Values\User\SsoUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\IpUtils;
use Throwable;
#[RequiresPlus]
class ProxyAuthService
{
public function __construct(private readonly UserService $userService)
{
}
public function tryGetProxyAuthenticatedUserFromRequest(Request $request): ?User
{
if (!self::validateProxyIp($request)) {
return null;
}
try {
return $this->userService->createOrUpdateUserFromSso(SsoUser::fromProxyAuthRequest($request));
} catch (Throwable $e) {
Log::error($e->getMessage(), ['exception' => $e]);
}
return null;
}
private static function validateProxyIp(Request $request): bool
{
return IpUtils::checkIp(
$request->server->get('REMOTE_ADDR'),
config('koel.proxy_auth.allow_list')
);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/FavoriteService.php | app/Services/FavoriteService.php | <?php
namespace App\Services;
use App\Events\MultipleSongsLiked;
use App\Events\MultipleSongsUnliked;
use App\Events\SongFavoriteToggled;
use App\Models\Contracts\Favoriteable;
use App\Models\Favorite;
use App\Models\Song;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
class FavoriteService
{
public function toggleFavorite(Favoriteable|Model $favoriteable, User $user): ?Favorite
{
$favorite = $favoriteable->favorites()->where('user_id', $user->id)->delete() === 0
? $favoriteable->favorites()->create(['user_id' => $user->id])
: null;
if ($favoriteable instanceof Song) {
event(new SongFavoriteToggled($favoriteable, (bool) $favorite, $user));
}
return $favorite;
}
/**
* Batch favorite multiple entities.
*
* @param Collection<int, Model> $entities
*/
public function batchFavorite(Collection $entities, User $user): void
{
$favorites = [];
foreach ($entities as $entity) {
if (!$entity instanceof Favoriteable) {
throw new InvalidArgumentException('Entity must implement Favoriteable interface.');
}
$favorites[] = [
'user_id' => $user->id,
'favoriteable_type' => $entity->getMorphClass(),
'favoriteable_id' => $entity->getKey(),
'created_at' => now(),
];
}
Favorite::query()->upsert($favorites, ['favoriteable_type', 'favoriteable_id', 'user_id']);
$songs = $entities->filter(static fn (Model $entity) => $entity instanceof Song);
if ($songs->isNotEmpty()) {
event(new MultipleSongsLiked($songs, $user));
}
}
/**
* Batch undo favorite for multiple entities.
*
* @param Collection<int, Model&Favoriteable> $entities
*/
public function batchUndoFavorite(Collection $entities, User $user): void
{
$grouped = $entities->groupBy(static fn (Model $entity) => $entity->getMorphClass());
DB::transaction(static function () use ($grouped, $user): void {
foreach ($grouped as $type => $items) {
Favorite::query()
->whereBelongsTo($user)
->where('favoriteable_type', $type)
->whereIn('favoriteable_id', $items->pluck('id'))
->delete();
}
});
$songs = $entities->filter(static fn (Model $entity) => $entity instanceof Song);
if ($songs->isNotEmpty()) {
event(new MultipleSongsUnliked($songs, $user));
}
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SmartPlaylistService.php | app/Services/SmartPlaylistService.php | <?php
namespace App\Services;
use App\Exceptions\NonSmartPlaylistException;
use App\Models\Playlist;
use App\Models\Song;
use App\Models\User;
use App\Repositories\SongRepository;
use Illuminate\Database\Eloquent\Collection;
class SmartPlaylistService
{
public function __construct(private readonly SongRepository $songRepository)
{
}
/** @return Collection|array<array-key, Song> */
public function getSongs(Playlist $playlist, User $user): Collection
{
throw_unless($playlist->is_smart, NonSmartPlaylistException::create($playlist));
return $this->songRepository->getByPlaylist($playlist, $user);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/ArtistService.php | app/Services/ArtistService.php | <?php
namespace App\Services;
use App\Exceptions\ArtistNameConflictException;
use App\Models\Artist;
use App\Repositories\ArtistRepository;
use App\Values\Artist\ArtistUpdateData;
use Illuminate\Support\Arr;
use Webmozart\Assert\Assert;
class ArtistService
{
public function __construct(
private readonly ArtistRepository $artistRepository,
private readonly ImageStorage $imageStorage,
) {
}
public function updateArtist(Artist $artist, ArtistUpdateData $dto): Artist
{
Assert::false($artist->is_various, '"Various" artists cannot be updated.');
// Ensure that the artist name is unique (per user)
$existingArtistWithTheSameName = $this->artistRepository->findOneBy([
'name' => $dto->name,
'user_id' => $artist->user_id,
]);
throw_if($existingArtistWithTheSameName?->isNot($artist), ArtistNameConflictException::class);
$data = $dto->toArray();
if (is_string($dto->image)) {
// A non-empty string means the user is uploading another image,
// when an empty string means the user is removing the image.
$data['image'] = rescue_if($dto->image, fn () => $this->imageStorage->storeImage($dto->image), '');
} else {
// If the image is null, the user's not changing or removing the image at all.
Arr::forget($data, 'image');
}
$artist->update($data);
return $artist->refresh();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/MusicBrainzService.php | app/Services/MusicBrainzService.php | <?php
namespace App\Services;
use App\Models\Album;
use App\Models\Artist;
use App\Pipelines\Encyclopedia\GetAlbumTracksUsingMbid;
use App\Pipelines\Encyclopedia\GetAlbumWikidataIdUsingReleaseGroupMbid;
use App\Pipelines\Encyclopedia\GetArtistWikidataIdUsingMbid;
use App\Pipelines\Encyclopedia\GetMbidForArtist;
use App\Pipelines\Encyclopedia\GetReleaseAndReleaseGroupMbidsForAlbum;
use App\Pipelines\Encyclopedia\GetWikipediaPageSummaryUsingPageTitle;
use App\Pipelines\Encyclopedia\GetWikipediaPageTitleUsingWikidataId;
use App\Services\Contracts\Encyclopedia;
use App\Values\Album\AlbumInformation;
use App\Values\Artist\ArtistInformation;
use Illuminate\Support\Facades\Pipeline;
class MusicBrainzService implements Encyclopedia
{
public static function enabled(): bool
{
return config('koel.services.musicbrainz.enabled');
}
public function getArtistInformation(Artist $artist): ?ArtistInformation
{
if ($artist->is_unknown || $artist->is_various) {
return null;
}
return rescue_if(static::enabled(), static function () use ($artist) {
$wikipediaSummary = Pipeline::send($artist->name)
->through([
GetMbidForArtist::class,
GetArtistWikidataIdUsingMbid::class,
GetWikipediaPageTitleUsingWikidataId::class,
GetWikipediaPageSummaryUsingPageTitle::class,
])
->thenReturn();
return $wikipediaSummary
? ArtistInformation::fromWikipediaSummary($wikipediaSummary)
: null;
});
}
public function getAlbumInformation(Album $album): ?AlbumInformation
{
if ($album->is_unknown || $album->artist->is_unknown) {
return null;
}
return rescue_if(static::enabled(), static function () use ($album): ?AlbumInformation {
// MusicBrainz has the concept of a "release" and a "release group".
// A release is a specific version of an album, which contains the actual tracks.
// A release group is a collection of releases (e.g. different formats or editions or markets
// of the same album), which contains metadata like the Wikidata relationship.
/**
* @var string|null $albumMbid
* @var string|null $releaseGroupMbid
*/
[$albumMbid, $releaseGroupMbid] = Pipeline::send([
'album' => $album->name,
'artist' => $album->artist->name,
])
->through([GetReleaseAndReleaseGroupMbidsForAlbum::class])
->thenReturn();
if (!$albumMbid || !$releaseGroupMbid) {
return null;
}
/** @var array<mixed> $tracks */
$tracks = Pipeline::send($albumMbid)
->through([GetAlbumTracksUsingMbid::class])
->thenReturn() ?: [];
$wikipediaSummary = Pipeline::send($releaseGroupMbid)
->through([
GetAlbumWikidataIdUsingReleaseGroupMbid::class,
GetWikipediaPageTitleUsingWikidataId::class,
GetWikipediaPageSummaryUsingPageTitle::class,
])
->thenReturn();
return $wikipediaSummary
? AlbumInformation::fromWikipediaSummary($wikipediaSummary)->withMusicBrainzTracks($tracks)
: AlbumInformation::make(url: "https://musicbrainz.org/release/$albumMbid")
->withMusicBrainzTracks($tracks);
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/PlaylistFolderService.php | app/Services/PlaylistFolderService.php | <?php
namespace App\Services;
use App\Models\PlaylistFolder;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
class PlaylistFolderService
{
public function createFolder(User $user, string $name): PlaylistFolder
{
return $user->playlistFolders()->create(['name' => $name]);
}
public function renameFolder(PlaylistFolder $folder, string $name): PlaylistFolder
{
$folder->update(['name' => $name]);
return $folder;
}
public function addPlaylistsToFolder(PlaylistFolder $folder, array $playlistIds): void
{
DB::transaction(
static function () use ($folder, $playlistIds): void {
// A playlist can only be in one folder by the user at a time
collect($playlistIds)->each(
static function (string $playlistId) use ($folder): void {
PlaylistFolder::query()
->where('user_id', $folder->user_id)
->whereHas('playlists', static fn (Builder $query) => $query->where('id', $playlistId))
->get()
->each(static fn (PlaylistFolder $folder) => $folder->playlists()->detach($playlistId));
}
);
$folder->playlists()->attach($playlistIds);
}
);
}
public function movePlaylistsToRootLevel(PlaylistFolder $folder, array $playlistIds): void
{
$folder->playlists()->detach($playlistIds);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SpotifyService.php | app/Services/SpotifyService.php | <?php
namespace App\Services;
use App\Http\Integrations\Spotify\SpotifyClient;
use App\Models\Album;
use App\Models\Artist;
use Illuminate\Support\Arr;
class SpotifyService
{
public function __construct(private readonly SpotifyClient $client)
{
}
public static function enabled(): bool
{
return config('koel.services.spotify.client_id') && config('koel.services.spotify.client_secret');
}
public function tryGetArtistImage(Artist $artist): ?string
{
if (!static::enabled()) {
return null;
}
if ($artist->is_various || $artist->is_unknown) {
return null;
}
return Arr::get(
$this->client->search($artist->name, 'artist', ['limit' => 1]),
'artists.items.0.images.0.url'
);
}
public function tryGetAlbumCover(Album $album): ?string
{
if (!static::enabled()) {
return null;
}
if ($album->is_unknown || $album->artist->is_unknown || $album->artist->is_various) {
return null;
}
return Arr::get(
$this->client->search("$album->name artist:{$album->artist->name}", 'album', ['limit' => 1]),
'albums.items.0.images.0.url'
);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/ThemeService.php | app/Services/ThemeService.php | <?php
namespace App\Services;
use App\Models\Theme;
use App\Models\User;
use App\Values\ImageWritingConfig;
use App\Values\Theme\ThemeCreateData;
use App\Values\Theme\ThemeProperties;
class ThemeService
{
public function __construct(private readonly ImageStorage $imageStorage)
{
}
public function createTheme(User $user, ThemeCreateData $data): Theme
{
$bgImage = '';
$thumbnail = null;
if ($data->bgImage) {
// store the bg image and create a thumbnail too
$bgImage = $this->imageStorage->storeImage(
source: $data->bgImage,
config: ImageWritingConfig::make(maxWidth: 2560),
);
$thumbnail = $this->imageStorage->storeImage(
source: $data->bgImage,
config: ImageWritingConfig::make(maxWidth: 640),
);
}
return $user->themes()->create([
'name' => $data->name,
'thumbnail' => $thumbnail,
'properties' => ThemeProperties::make(
fgColor: $data->fgColor,
bgColor: $data->bgColor,
bgImage: $bgImage,
highlightColor: $data->highlightColor,
fontFamily: $data->fontFamily,
fontSize: $data->fontSize,
),
]);
}
public function deleteTheme(Theme $theme): void
{
$theme->delete(); // will trigger cover/thumbnail cleanup in ThemeObserver
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/PlaylistService.php | app/Services/PlaylistService.php | <?php
namespace App\Services;
use App\Enums\Placement;
use App\Exceptions\OperationNotApplicableForSmartPlaylistException;
use App\Models\Playlist;
use App\Models\Song as Playable;
use App\Models\User;
use App\Repositories\SongRepository;
use App\Values\Playlist\PlaylistCreateData;
use App\Values\Playlist\PlaylistUpdateData;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class PlaylistService
{
public function __construct(
private readonly ImageStorage $imageStorage,
private readonly SongRepository $songRepository,
) {
}
public function createPlaylist(PlaylistCreateData $data, User $user): Playlist
{
// cover is optional and not critical, so no transaction is needed
$cover = rescue_if($data->cover, function () use ($data) {
return $this->imageStorage->storeImage($data->cover);
});
return DB::transaction(
static function () use ($data, $cover, $user): Playlist {
/** @var Playlist $playlist */
$playlist = Playlist::query()->create([
'name' => $data->name,
'description' => $data->description,
'rules' => $data->ruleGroups,
'cover' => $cover,
]);
$user->ownedPlaylists()->attach($playlist, [
'role' => 'owner',
]);
$playlist->folders()->attach($data->folderId);
if (!$playlist->is_smart && $data->playableIds) {
$playlist->addPlayables($data->playableIds, $user);
}
return $playlist;
}
);
}
public function updatePlaylist(Playlist $playlist, PlaylistUpdateData $dto): Playlist
{
$data = [
'name' => $dto->name,
'description' => $dto->description,
'rules' => $dto->ruleGroups,
];
if (is_string($dto->cover)) {
$data['cover'] = rescue_if($dto->cover, fn () => $this->imageStorage->storeImage($dto->cover), '');
}
$playlist->update($data);
if ($dto->folderId) {
$playlist->folders()->syncWithoutDetaching([$dto->folderId]);
}
return $playlist->refresh();
}
/** @return EloquentCollection<array-key, Playable> */
public function addPlayablesToPlaylist(
Playlist $playlist,
Collection|Playable|array $playables,
User $user
): EloquentCollection {
return DB::transaction(function () use ($playlist, $playables, $user) {
$playables = Collection::wrap($playables);
$playlist->addPlayables(
$playables->filter(static fn ($song): bool => !$playlist->playables->contains($song)),
$user
);
// if the playlist is collaborative, make the songs public
if ($playlist->is_collaborative) {
$this->makePlaylistContentPublic($playlist);
}
// we want a fresh copy of the songs with the possibly updated visibility
return $this->songRepository->getManyInCollaborativeContext(
ids: $playables->pluck('id')->all(),
scopedUser: $user
);
});
}
public function removePlayablesFromPlaylist(Playlist $playlist, Collection|Playable|array $playables): void
{
$playlist->removePlayables($playables);
}
public function makePlaylistContentPublic(Playlist $playlist): void
{
$playlist->playables()->where('is_public', false)->update(['is_public' => true]);
}
/** @param array<string> $movingIds */
public function movePlayablesInPlaylist(
Playlist $playlist,
array $movingIds,
string $target,
Placement $placement,
): void {
throw_if($playlist->is_smart, OperationNotApplicableForSmartPlaylistException::class);
DB::transaction(static function () use ($playlist, $movingIds, $target, $placement): void {
$targetPosition = $playlist->playables()->wherePivot('song_id', $target)->value('position');
$insertPosition = $placement === Placement::BEFORE ? $targetPosition : $targetPosition + 1;
// create a "gap" for the moving songs by incrementing the position of the songs after the target
$playlist->playables()
->newPivotQuery()
->where('position', $placement === Placement::BEFORE ? '>=' : '>', $targetPosition)
->whereNotIn('song_id', $movingIds)
->increment('position', count($movingIds));
$values = [];
foreach ($movingIds as $id) {
$values[$id] = ['position' => $insertPosition++];
}
$playlist->playables()->syncWithoutDetaching($values);
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/PlaylistCollaborationService.php | app/Services/PlaylistCollaborationService.php | <?php
namespace App\Services;
use App\Events\NewPlaylistCollaboratorJoined;
use App\Exceptions\CannotRemoveOwnerFromPlaylistException;
use App\Exceptions\NotAPlaylistCollaboratorException;
use App\Exceptions\OperationNotApplicableForSmartPlaylistException;
use App\Exceptions\PlaylistCollaborationTokenExpiredException;
use App\Models\Playlist;
use App\Models\PlaylistCollaborationToken;
use App\Models\User;
use App\Values\Playlist\PlaylistCollaborator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class PlaylistCollaborationService
{
public function createToken(Playlist $playlist): PlaylistCollaborationToken
{
throw_if($playlist->is_smart, OperationNotApplicableForSmartPlaylistException::class);
return $playlist->collaborationTokens()->create();
}
public function acceptUsingToken(string $token, User $user): Playlist
{
/** @var PlaylistCollaborationToken $collaborationToken */
$collaborationToken = PlaylistCollaborationToken::query()->where('token', $token)->firstOrFail();
throw_if($collaborationToken->expired, PlaylistCollaborationTokenExpiredException::class);
if ($collaborationToken->playlist->ownedBy($user)) {
return $collaborationToken->playlist;
}
$collaborationToken->playlist->addCollaborator($user);
// Now that we have at least one external collaborator, the songs in the playlist should be made public.
// Here we dispatch an event for that to happen.
event(new NewPlaylistCollaboratorJoined($user, $collaborationToken));
return $collaborationToken->playlist;
}
/** @return Collection<array-key, PlaylistCollaborator> */
public function getCollaborators(Playlist $playlist, bool $includingOwner = false): Collection
{
$collaborators = $includingOwner ? $playlist->users : $playlist->collaborators;
return $collaborators->map(static fn (User $user) => PlaylistCollaborator::fromUser($user));
}
public function removeCollaborator(Playlist $playlist, User $user): void
{
throw_if($playlist->ownedBy($user), CannotRemoveOwnerFromPlaylistException::class);
throw_if(!$playlist->hasCollaborator($user), NotAPlaylistCollaboratorException::class);
DB::transaction(static function () use ($playlist, $user): void {
$playlist->collaborators()->detach($user);
$playlist->playables()->wherePivot('user_id', $user->id)->detach();
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SongService.php | app/Services/SongService.php | <?php
namespace App\Services;
use App\Events\LibraryChanged;
use App\Facades\Dispatcher;
use App\Facades\License;
use App\Jobs\DeleteSongFilesJob;
use App\Jobs\DeleteTranscodeFilesJob;
use App\Jobs\ExtractSongFolderStructureJob;
use App\Models\Album;
use App\Models\Artist;
use App\Models\Song;
use App\Models\Transcode;
use App\Models\User;
use App\Repositories\SongRepository;
use App\Repositories\TranscodeRepository;
use App\Services\Scanners\Contracts\ScannerCacheStrategy as CacheStrategy;
use App\Values\Scanning\ScanConfiguration;
use App\Values\Scanning\ScanInformation;
use App\Values\Song\SongFileInfo;
use App\Values\Song\SongUpdateData;
use App\Values\Song\SongUpdateResult;
use App\Values\Transcoding\TranscodeFileInfo;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
class SongService
{
public function __construct(
private readonly SongRepository $songRepository,
private readonly TranscodeRepository $transcodeRepository,
private readonly AlbumService $albumService,
private readonly CacheStrategy $cache,
) {
}
public function updateSongs(array $ids, SongUpdateData $data): SongUpdateResult
{
if (count($ids) === 1) {
// If we're only updating one song, an empty non-required should be converted to the default values.
// This allows the user to clear those fields.
$data->disc = $data->disc ?: 1;
$data->track = $data->track ?: 0;
$data->lyrics = $data->lyrics ?: '';
$data->year = $data->year ?: null;
$data->genre = $data->genre ?: '';
$data->albumArtistName = $data->albumArtistName ?: $data->artistName;
}
return DB::transaction(function () use ($ids, $data): SongUpdateResult {
$result = SongUpdateResult::make();
$multiSong = count($ids) > 1;
$noTrackUpdate = $multiSong && !$data->track;
$affectedAlbums = collect();
$affectedArtists = collect();
Song::query()->with('artist.user', 'album.artist', 'album.artist.user')->findMany($ids)->each(
function (Song $song) use ($data, $result, $noTrackUpdate, $affectedAlbums, $affectedArtists): void {
if ($noTrackUpdate) {
$data->track = $song->track;
}
if ($affectedAlbums->pluck('id')->doesntContain($song->album_id)) {
$affectedAlbums->push($song->album);
}
if ($affectedArtists->pluck('id')->doesntContain($song->artist_id)) {
$affectedArtists->push($song->artist);
}
if ($affectedArtists->pluck('id')->doesntContain($song->album->artist_id)) {
$affectedArtists->push($song->album_artist);
}
$result->addSong($this->updateSong($song, clone $data)); // @phpstan-ignore-line
if ($noTrackUpdate) {
$data->track = null;
}
},
);
$affectedAlbums->each(static function (Album $album) use ($result): void {
if ($album->refresh()->songs()->count() === 0) {
$result->addRemovedAlbum($album);
$album->delete();
}
});
$affectedArtists->each(static function (Artist $artist) use ($result): void {
if ($artist->refresh()->songs()->count() === 0) {
$result->addRemovedArtist($artist);
$artist->delete();
}
});
return $result;
});
}
private function updateSong(Song $song, SongUpdateData $data): Song
{
// For non-nullable fields, if the provided data is empty, use the existing value
$data->albumName = $data->albumName ?: $song->album->name;
$data->artistName = $data->artistName ?: $song->artist->name;
$data->title = $data->title ?: $song->title;
// For nullable fields, use the existing value only if the provided data is explicitly null
// (i.e., when multiple songs are being updated and the user did not provide a value).
// This allows us to clear those fields (when user provides an empty string).
$data->albumArtistName ??= $song->album_artist->name;
$data->lyrics ??= $song->lyrics;
$data->track ??= $song->track;
$data->disc ??= $song->disc;
$data->genre ??= $song->genre;
$data->year ??= $song->year;
$albumArtist = Artist::getOrCreate($song->album_artist->user, $data->albumArtistName);
$artist = Artist::getOrCreate($song->artist->user, $data->artistName);
$album = Album::getOrCreate($albumArtist, $data->albumName);
$song->album_id = $album->id;
$song->album_name = $album->name;
$song->artist_id = $artist->id;
$song->artist_name = $artist->name;
$song->title = $data->title;
$song->lyrics = $data->lyrics;
$song->track = $data->track;
$song->disc = $data->disc;
$song->year = $data->year;
$song->push();
if (!$song->genreEqualsTo($data->genre)) {
$song->syncGenres($data->genre);
}
return $this->songRepository->getOne($song->id);
}
public function markSongsAsPublic(EloquentCollection $songs): void
{
$songs->toQuery()->update(['is_public' => true]);
}
/** @return array<string> IDs of songs that are marked as private */
public function markSongsAsPrivate(EloquentCollection $songs): array
{
License::requirePlus();
// Songs that are in collaborative playlists can't be marked as private.
/**
* @var Collection<array-key, Song> $collaborativeSongs
*/
$collaborativeSongs = $songs->toQuery()
->join('playlist_song', 'songs.id', '=', 'playlist_song.song_id')
->join('playlist_user', 'playlist_song.playlist_id', '=', 'playlist_user.playlist_id')
->select('songs.id')
->distinct()
->pluck('songs.id')
->all();
$applicableSongIds = $songs->whereNotIn('id', $collaborativeSongs)->modelKeys();
Song::query()->whereKey($applicableSongIds)->update(['is_public' => false]);
return $applicableSongIds;
}
/**
* @param array<string>|string $ids
*/
public function deleteSongs(array|string $ids): void
{
$ids = Arr::wrap($ids);
// Since song (and cascadingly, transcode) records will be deleted, we query them first and, if there are any,
// dispatch a job to delete their associated files.
$songFiles = Song::query()
->findMany($ids)
->map(static fn (Song $song) => SongFileInfo::fromSong($song)); // @phpstan-ignore-line
$transcodeFiles = $this->transcodeRepository->findBySongIds($ids)
->map(static fn (Transcode $transcode) => TranscodeFileInfo::fromTranscode($transcode)); // @phpstan-ignore-line
if (Song::destroy($ids) === 0) {
return;
}
Dispatcher::dispatch(new DeleteSongFilesJob($songFiles));
if ($transcodeFiles->isNotEmpty()) {
Dispatcher::dispatch(new DeleteTranscodeFilesJob($transcodeFiles));
}
// Instruct the system to prune the library, i.e., remove empty albums and artists.
event(new LibraryChanged());
}
public function createOrUpdateSongFromScan(
ScanInformation $info,
ScanConfiguration $config,
?Song $song = null,
): ?Song {
$song ??= $this->songRepository->findOneByPath($info->path);
$isFileNew = !$song;
$isFileModified = $song && $song->isFileModified($info->mTime);
$isFileNewOrModified = $isFileNew || $isFileModified;
if (!$isFileNewOrModified && !$config->force) {
return $song;
}
$data = $info->toArray();
$genre = Arr::pull($data, 'genre', '');
// If the file is new, we take all necessary metadata, totally discarding the "ignores" config.
// Otherwise, we only take the metadata not in the "ignores" config.
if (!$isFileNew) {
Arr::forget($data, $config->ignores);
}
$artist = $this->resolveArtist($config->owner, Arr::get($data, 'artist'));
$albumArtist = Arr::get($data, 'albumartist')
? $this->resolveArtist($config->owner, $data['albumartist'])
: $artist;
$album = $this->resolveAlbum($albumArtist, Arr::get($data, 'album'));
$hasCover = $album->cover && File::exists(image_storage_path($album->cover));
if (!$hasCover && !in_array('cover', $config->ignores, true)) {
$coverData = Arr::get($data, 'cover.data');
if ($coverData) {
$this->albumService->storeAlbumCover($album, $coverData);
} else {
$this->albumService->trySetAlbumCoverFromDirectory($album, dirname($data['path']));
}
}
Arr::forget($data, ['album', 'artist', 'albumartist', 'cover']);
$data['album_id'] = $album->id;
$data['artist_id'] = $artist->id;
$data['is_public'] = $config->makePublic;
$data['album_name'] = $album->name;
$data['artist_name'] = $artist->name;
if ($isFileNew) {
// Only set the owner if the song is new, i.e., don't override the owner if the song is being updated.
$data['owner_id'] = $config->owner->id;
/** @var Song $song */
$song = Song::query()->create($data);
} else {
$song->update($data);
}
if ($genre !== $song->genre) {
$song->syncGenres($genre);
}
if (!$album->year && $song->year) {
$album->update(['year' => $song->year]);
}
if ($config->extractFolderStructure) {
Dispatcher::dispatch(new ExtractSongFolderStructureJob($song));
}
return $song;
}
private function resolveArtist(User $user, ?string $name): Artist
{
$name = trim($name);
return $this->cache->remember(
key: cache_key(__METHOD__, $user->id, $name),
callback: static fn () => Artist::getOrCreate($user, $name)
);
}
private function resolveAlbum(Artist $artist, ?string $name): Album
{
$name = trim($name);
return $this->cache->remember(
key: cache_key(__METHOD__, $artist->id, $name),
callback: static fn () => Album::getOrCreate($artist, $name)
);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/LicenseService.php | app/Services/LicenseService.php | <?php
namespace App\Services;
use App\Exceptions\FailedToActivateLicenseException;
use App\Http\Integrations\LemonSqueezy\LemonSqueezyConnector;
use App\Http\Integrations\LemonSqueezy\Requests\ActivateLicenseRequest;
use App\Http\Integrations\LemonSqueezy\Requests\DeactivateLicenseRequest;
use App\Http\Integrations\LemonSqueezy\Requests\ValidateLicenseRequest;
use App\Models\License;
use App\Services\License\Contracts\LicenseServiceInterface;
use App\Values\License\LicenseInstance;
use App\Values\License\LicenseMeta;
use App\Values\License\LicenseStatus;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Saloon\Exceptions\Request\RequestException;
use Throwable;
class LicenseService implements LicenseServiceInterface
{
public function __construct(private readonly LemonSqueezyConnector $connector, private ?string $hashSalt = null)
{
$this->hashSalt ??= config('app.key');
}
public function activate(string $key): License
{
try {
$result = $this->connector->send(new ActivateLicenseRequest($key))->object();
if ($result->meta->store_id !== config('lemonsqueezy.store_id')) {
throw new FailedToActivateLicenseException('This license key is not from Koel’s official store.');
}
$license = $this->updateOrCreateLicenseFromApiResponseBody($result);
self::cacheStatus(LicenseStatus::valid($license));
return $license;
} catch (RequestException $e) {
throw FailedToActivateLicenseException::fromRequestException($e);
} catch (Throwable $e) {
Log::error($e);
throw FailedToActivateLicenseException::fromThrowable($e);
}
}
public function deactivate(License $license): void
{
try {
$result = $this->connector->send(new DeactivateLicenseRequest($license))->object();
if ($result->deactivated) {
self::deleteLicense($license);
}
} catch (RequestException $e) {
if ($e->getStatus() === Response::HTTP_NOT_FOUND) {
// The instance ID was not found. The license record must be a leftover from an erroneous attempt.
self::deleteLicense($license);
return;
}
throw FailedToActivateLicenseException::fromRequestException($e);
} catch (Throwable $e) {
Log::error($e);
throw $e;
}
}
public function getStatus(bool $checkCache = true): LicenseStatus
{
if ($checkCache && Cache::has('license_status')) {
return Cache::get('license_status');
}
/** @var ?License $license */
$license = License::query()->latest()->first();
if (!$license) {
return LicenseStatus::noLicense();
}
try {
$result = $this->connector->send(new ValidateLicenseRequest($license))->object();
$updatedLicense = $this->updateOrCreateLicenseFromApiResponseBody($result);
return self::cacheStatus(LicenseStatus::valid($updatedLicense));
} catch (RequestException $e) {
if ($e->getStatus() === Response::HTTP_BAD_REQUEST || $e->getStatus() === Response::HTTP_NOT_FOUND) {
return self::cacheStatus(LicenseStatus::invalid($license));
}
throw $e;
} catch (DecryptException) {
// the license key has been tampered with somehow
return self::cacheStatus(LicenseStatus::invalid($license));
} catch (Throwable $e) {
Log::error($e);
return LicenseStatus::unknown($license);
}
}
/** @noinspection PhpIncompatibleReturnTypeInspection */
private function updateOrCreateLicenseFromApiResponseBody(object $body): License
{
return License::query()->updateOrCreate([
'hash' => sha1($body->license_key->key . $this->hashSalt),
], [
'key' => $body->license_key->key,
'instance' => LicenseInstance::fromJsonObject($body->instance),
'meta' => LicenseMeta::fromJson($body->meta),
'created_at' => $body->license_key->created_at,
'expires_at' => $body->license_key->expires_at,
]);
}
private static function deleteLicense(License $license): void
{
$license->delete();
Cache::delete('license_status');
}
private static function cacheStatus(LicenseStatus $status): LicenseStatus
{
Cache::put('license_status', $status, now()->addWeek());
return $status;
}
public function isPlus(): bool
{
return $this->getStatus()->isValid();
}
public function isCommunity(): bool
{
return !$this->isPlus();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/AuthenticationService.php | app/Services/AuthenticationService.php | <?php
namespace App\Services;
use App\Exceptions\InvalidCredentialsException;
use App\Models\User;
use App\Repositories\UserRepository;
use App\Values\CompositeToken;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Auth\Passwords\PasswordBroker;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use InvalidArgumentException;
use Throwable;
class AuthenticationService
{
public function __construct(
private readonly UserRepository $userRepository,
private readonly TokenManager $tokenManager,
private readonly PasswordBroker $passwordBroker
) {
}
public function login(string $email, string $password): CompositeToken
{
$user = $this->userRepository->findFirstWhere('email', $email);
if (!$user || !Hash::check($password, $user->password)) {
throw new InvalidCredentialsException();
}
if (Hash::needsRehash($user->password)) {
$user->password = Hash::make($password);
$user->save();
}
return $this->logUserIn($user);
}
public function logUserIn(User $user): CompositeToken
{
return $this->tokenManager->createCompositeToken($user);
}
public function logoutViaBearerToken(string $token): void
{
$this->tokenManager->deleteCompositionToken($token);
}
public function trySendResetPasswordLink(string $email): bool
{
return $this->passwordBroker->sendResetLink(['email' => $email]) === Password::RESET_LINK_SENT;
}
public function tryResetPasswordUsingBroker(string $email, string $password, string $token): bool
{
$credentials = [
'email' => $email,
'password' => $password,
'password_confirmation' => $password,
'token' => $token,
];
$status = $this->passwordBroker->reset($credentials, static function (User $user, string $password): void {
$user->password = Hash::make($password);
$user->save();
event(new PasswordReset($user));
});
return $status === Password::PASSWORD_RESET;
}
public function generateOneTimeToken(User $user): string
{
$token = bin2hex(random_bytes(12));
Cache::set(cache_key('one-time token', $token), encrypt($user->id), 60 * 10);
return $token;
}
public function loginViaOneTimeToken(string $token): CompositeToken
{
$cacheKey = cache_key('one-time token', $token);
$encryptedUserId = Cache::pull($cacheKey);
if (!$encryptedUserId) {
throw new InvalidArgumentException(message: 'One-time token not found or expired.');
}
try {
$userId = decrypt($encryptedUserId);
} catch (Throwable $e) {
throw new InvalidArgumentException(message: 'Invalid one-time token.', previous: $e);
}
return $this->logUserIn($this->userRepository->getOne($userId));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/RadioService.php | app/Services/RadioService.php | <?php
namespace App\Services;
use App\Models\RadioStation;
use App\Models\User;
use App\Repositories\RadioStationRepository;
use App\Values\Radio\RadioStationCreateData;
use App\Values\Radio\RadioStationUpdateData;
class RadioService
{
public function __construct(
private readonly RadioStationRepository $repository,
private readonly ImageStorage $imageStorage,
) {
}
public function createRadioStation(RadioStationCreateData $dto, User $user): RadioStation
{
// logo is optional and not critical, so no transaction is needed
$logoFileName = rescue_if($dto->logo, function () use ($dto) {
return $this->imageStorage->storeImage($dto->logo);
});
/** @var RadioStation $station */
$station = $user->radioStations()->create([
'url' => $dto->url,
'name' => $dto->name,
'logo' => $logoFileName,
'description' => $dto->description,
'is_public' => $dto->isPublic,
]);
return $this->repository->findOneWithUserContext($station->id, $user);
}
public function updateRadioStation(RadioStation $radioStation, RadioStationUpdateData $dto): RadioStation
{
$data = [
'url' => $dto->url,
'name' => $dto->name,
'description' => $dto->description,
'is_public' => $dto->isPublic,
];
if (is_string($dto->logo)) {
$data['logo'] = rescue_if($dto->logo, fn () => $this->imageStorage->storeImage($dto->logo), '');
}
$radioStation->update($data);
return $this->repository->findOneWithUserContext($radioStation->id, $radioStation->user);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/LibraryManager.php | app/Services/LibraryManager.php | <?php
namespace App\Services;
use App\Models\Album;
use App\Models\Artist;
use Illuminate\Support\Facades\DB;
class LibraryManager
{
/**
* Delete albums and artists that have no songs.
*
* @return array<mixed>
*/
public function prune(bool $dryRun = false): array
{
return DB::transaction(static function () use ($dryRun): array {
$albumQuery = Album::query()
->leftJoin('songs', 'songs.album_id', '=', 'albums.id')
->whereNull('songs.album_id');
$artistQuery = Artist::query()
->leftJoin('songs', 'songs.artist_id', '=', 'artists.id')
->leftJoin('albums', 'albums.artist_id', '=', 'artists.id')
->whereNull('songs.artist_id')
->whereNull('albums.artist_id');
$results = [
'albums' => $albumQuery->get('albums.*'),
'artists' => $artistQuery->get('artists.*'),
];
if (!$dryRun) {
$albumQuery->delete();
$artistQuery->delete();
}
return $results;
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/InteractionService.php | app/Services/InteractionService.php | <?php
namespace App\Services;
use App\Models\Interaction;
use App\Models\Song as Playable;
use App\Models\User;
class InteractionService
{
public function increasePlayCount(Playable $playable, User $user): Interaction
{
return tap(Interaction::query()->firstOrCreate([
'song_id' => $playable->id,
'user_id' => $user->id,
]), static function (Interaction $interaction): void {
$interaction->last_played_at = now();
++$interaction->play_count;
$interaction->save();
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/ImageStorage.php | app/Services/ImageStorage.php | <?php
namespace App\Services;
use App\Helpers\Ulid;
use App\Values\ImageWritingConfig;
use Illuminate\Support\Facades\File;
use RuntimeException;
class ImageStorage
{
public function __construct(
private readonly ImageWriter $imageWriter,
private readonly SvgSanitizer $svgSanitizer,
) {
}
/**
* Store an image file and return the (randomly generated) file name.
*
* @param mixed $source Any kind of image data that Intervention can read.
* @param ?string $path The path to store the image file. Randomly generated if not provided.
*
* @return string The file name.
*/
public function storeImage(mixed $source, ?ImageWritingConfig $config = null, ?string $path = null): string
{
preg_match('/^data:(image\/[A-Za-z0-9+\-.]+);base64,/', $source, $matches);
$mime = $matches[1] ?? null;
if ($mime === 'image/svg+xml') {
$svgData = preg_replace('/^data:image\/svg\+xml;base64,/', '', $source);
$raw = base64_decode($svgData, true);
if ($raw === false) {
throw new RuntimeException('Failed to decode base64 SVG data.');
}
$sanitized = $this->svgSanitizer->sanitize($raw);
if (!$sanitized) {
throw new RuntimeException('Invalid SVG file.');
}
$path ??= self::generateRandomStoragePath('svg');
File::put($path, $sanitized);
return basename($path);
}
$path ??= self::generateRandomStoragePath();
$this->imageWriter->write($path, $source, $config);
return basename($path);
}
private static function generateRandomStoragePath(string $extension = 'webp'): string
{
return image_storage_path(sprintf("%s.%s", Ulid::generate(), $extension));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/LastfmService.php | app/Services/LastfmService.php | <?php
namespace App\Services;
use App\Http\Integrations\Lastfm\LastfmConnector;
use App\Http\Integrations\Lastfm\Requests\GetAlbumInfoRequest;
use App\Http\Integrations\Lastfm\Requests\GetArtistInfoRequest;
use App\Http\Integrations\Lastfm\Requests\GetSessionKeyRequest;
use App\Http\Integrations\Lastfm\Requests\ScrobbleRequest;
use App\Http\Integrations\Lastfm\Requests\ToggleLoveTrackRequest;
use App\Http\Integrations\Lastfm\Requests\UpdateNowPlayingRequest;
use App\Models\Album;
use App\Models\Artist;
use App\Models\Song;
use App\Models\User;
use App\Services\Contracts\Encyclopedia;
use App\Values\Album\AlbumInformation;
use App\Values\Artist\ArtistInformation;
use Generator;
use Illuminate\Support\Collection;
class LastfmService implements Encyclopedia
{
public function __construct(private readonly LastfmConnector $connector)
{
}
/**
* Determine if our application is using Last.fm.
*/
public static function used(): bool
{
return (bool) config('koel.services.lastfm.key');
}
/**
* Determine if Last.fm integration is enabled.
*/
public static function enabled(): bool
{
return config('koel.services.lastfm.key') && config('koel.services.lastfm.secret');
}
public function getArtistInformation(Artist $artist): ?ArtistInformation
{
if ($artist->is_unknown || $artist->is_various) {
return null;
}
return rescue_if(static::enabled(), function () use ($artist): ?ArtistInformation {
return $this->connector->send(new GetArtistInfoRequest($artist))->dto();
});
}
public function getAlbumInformation(Album $album): ?AlbumInformation
{
if ($album->is_unknown || $album->artist->is_unknown) {
return null;
}
return rescue_if(static::enabled(), function () use ($album): ?AlbumInformation {
return $this->connector->send(new GetAlbumInfoRequest($album))->dto();
});
}
public function scrobble(Song $song, User $user, int $timestamp): void
{
rescue(fn () => $this->connector->send(new ScrobbleRequest($song, $user, $timestamp)));
}
public function toggleLoveTrack(Song $song, User $user, bool $love): void
{
rescue(fn () => $this->connector->send(new ToggleLoveTrackRequest($song, $user, $love)));
}
/**
* @param Collection<array-key, Song> $songs
*/
public function batchToggleLoveTracks(Collection $songs, User $user, bool $love): void
{
$generatorCallback = static function () use ($songs, $user, $love): Generator {
foreach ($songs as $song) {
yield new ToggleLoveTrackRequest($song, $user, $love);
}
};
$this->connector
->pool($generatorCallback)
->send()
->wait();
}
public function updateNowPlaying(Song $song, User $user): void
{
rescue(fn () => $this->connector->send(new UpdateNowPlayingRequest($song, $user)));
}
public function getSessionKey(string $token): ?string
{
return object_get($this->connector->send(new GetSessionKeyRequest($token))->object(), 'session.key');
}
public function setUserSessionKey(User $user, ?string $sessionKey): void
{
$user->preferences->lastFmSessionKey = $sessionKey;
$user->save();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SvgSanitizer.php | app/Services/SvgSanitizer.php | <?php
namespace App\Services;
use enshrined\svgSanitize\Sanitizer;
class SvgSanitizer
{
public function __construct(private readonly Sanitizer $sanitizer)
{
}
public function sanitize(string $svg): false|string
{
return $this->sanitizer->sanitize($svg);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/ApplicationInformationService.php | app/Services/ApplicationInformationService.php | <?php
namespace App\Services;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;
class ApplicationInformationService
{
public function __construct(private readonly Client $client)
{
}
/**
* Get the latest version number of Koel from GitHub.
*/
public function getLatestVersionNumber(): string
{
return rescue(function () {
return Cache::remember(cache_key('latest version number'), now()->addDay(), function (): string {
return json_decode($this->client->get('https://api.github.com/repos/koel/koel/tags')->getBody())[0]
->name;
});
}) ?? koel_version();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SettingService.php | app/Services/SettingService.php | <?php
namespace App\Services;
use App\Facades\License;
use App\Models\Setting;
use App\Values\Branding;
use Illuminate\Support\Arr;
class SettingService
{
public function __construct(private readonly ImageStorage $imageStorage)
{
}
public function getBranding(): Branding
{
return License::isPlus()
? Branding::fromArray(Arr::wrap(Setting::get('branding')))
: Branding::make(name: config('app.name'));
}
public function updateMediaPath(string $path): string
{
$path = rtrim($path, DIRECTORY_SEPARATOR);
Setting::set('media_path', $path);
return $path;
}
public function updateBranding(string $name, ?string $logo, ?string $cover): void
{
$branding = $this->getBranding()->withName($name);
if ($logo && $logo !== $branding->logo) {
$branding = $branding->withLogo($this->imageStorage->storeImage($logo));
} elseif (!$logo) {
$branding = $branding->withoutLogo();
}
if ($cover && $cover !== $branding->cover) {
$branding = $branding->withCover($this->imageStorage->storeImage($cover));
} elseif (!$cover) {
$branding = $branding->withoutCover();
}
Setting::set('branding', $branding->toArray());
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/YouTubeService.php | app/Services/YouTubeService.php | <?php
namespace App\Services;
use App\Http\Integrations\YouTube\Requests\SearchVideosRequest;
use App\Http\Integrations\YouTube\YouTubeConnector;
use App\Models\Song;
use Illuminate\Support\Facades\Cache;
use Throwable;
class YouTubeService
{
public function __construct(private readonly YouTubeConnector $connector)
{
}
public static function enabled(): bool
{
return (bool) config('koel.services.youtube.key');
}
public function searchVideosRelatedToSong(Song $song, string $pageToken = ''): ?object
{
if (!self::enabled()) {
return null;
}
$request = new SearchVideosRequest($song, $pageToken);
try {
return Cache::remember(
cache_key('YouTube search query', serialize($request->query()->all())),
now()->addWeek(),
fn () => $this->connector->send($request)->object()
);
} catch (Throwable) {
return null;
}
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/UserInvitationService.php | app/Services/UserInvitationService.php | <?php
namespace App\Services;
use App\Enums\Acl\Role;
use App\Exceptions\InvitationNotFoundException;
use App\Helpers\Uuid;
use App\Mail\UserInvite;
use App\Models\User;
use App\Repositories\UserRepository;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
class UserInvitationService
{
public function __construct(private readonly UserRepository $userRepository)
{
}
/** @return Collection<array-key, User> */
public function invite(array $emails, Role $role, User $invitor): Collection
{
$role->assertAvailable();
return DB::transaction(function () use ($emails, $role, $invitor) {
return collect($emails)->map(fn ($email) => $this->inviteOne($email, $role, $invitor));
});
}
public function getUserProspectByToken(string $token): User
{
return User::query()->where('invitation_token', $token)->firstOr(static function (): never {
throw new InvitationNotFoundException();
});
}
public function revokeByEmail(string $email): void
{
$user = $this->userRepository->findOneByEmail($email);
throw_unless($user?->is_prospect, new InvitationNotFoundException());
$user->delete();
}
private function inviteOne(string $email, Role $role, User $invitor): User
{
$role->assertAvailable();
/** @var User $invitee */
$invitee = $invitor->organization->users()->create([
'name' => '',
'email' => $email,
'password' => '',
'invited_by_id' => $invitor->id,
'invitation_token' => Uuid::generate(),
'invited_at' => now(),
]);
$invitee->syncRoles($role);
Mail::to($email)->queue(new UserInvite($invitee));
return $invitee;
}
public function accept(string $token, string $name, string $password): User
{
$user = $this->getUserProspectByToken($token);
$user->update(attributes: [
'name' => $name,
'password' => Hash::make($password),
'invitation_token' => null,
'invitation_accepted_at' => now(),
]);
return $user;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/ImageWriter.php | app/Services/ImageWriter.php | <?php
namespace App\Services;
use App\Values\ImageWritingConfig;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Intervention\Image\FileExtension;
use Intervention\Image\Interfaces\ImageManagerInterface;
use Intervention\Image\Laravel\Facades\Image;
use RuntimeException;
class ImageWriter
{
private FileExtension $extension;
public function __construct()
{
$this->extension = self::getExtension();
}
private static function getExtension(): FileExtension
{
/** @var ImageManagerInterface $manager */
$manager = Image::getFacadeRoot();
// Prioritize AVIF over WEBP over JPEG.
foreach ([FileExtension::AVIF, FileExtension::WEBP, FileExtension::JPEG] as $extension) {
if ($manager->driver()->supports($extension)) {
return $extension;
}
}
throw new RuntimeException('No supported image extension found.');
}
public function write(string $destination, mixed $source, ?ImageWritingConfig $config = null): void
{
$config ??= ImageWritingConfig::default();
$img = Image::read(Str::isUrl($source) ? Http::get($source)->body() : $source)
->scale(width: $config->maxWidth);
if ($config->blur) {
$img->blur($config->blur);
}
$img->save($destination, $config->quality, $this->extension);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/EncyclopediaService.php | app/Services/EncyclopediaService.php | <?php
namespace App\Services;
use App\Models\Album;
use App\Models\Artist;
use App\Services\Contracts\Encyclopedia;
use App\Values\Album\AlbumInformation;
use App\Values\Artist\ArtistInformation;
use Illuminate\Support\Facades\Cache;
class EncyclopediaService
{
public function __construct(
private readonly Encyclopedia $encyclopedia,
private readonly ImageStorage $imageStorage,
private readonly SpotifyService $spotifyService,
) {
}
public function getAlbumInformation(Album $album): ?AlbumInformation
{
if ($album->is_unknown) {
return null;
}
return Cache::remember(
cache_key('album information', $album->name, $album->artist->name),
now()->addWeek(),
function () use ($album): AlbumInformation {
$info = $this->encyclopedia->getAlbumInformation($album) ?: AlbumInformation::make();
if ($album->cover || (!SpotifyService::enabled() && !$info->cover)) {
// If the album already has a cover, or there's no resource to download a cover from,
// just return the info.
return $info;
}
// If the album cover is not set, try to download it either from Spotify (prioritized, due to
// the high quality) or from the encyclopedia. We will also set the downloaded image right
// away into the info object so that the caller/client can use it immediately.
$info->cover = rescue(function () use ($album, $info): ?string {
return $this->fetchAndStoreAlbumCover($album, $info) ?? $info->cover;
});
return $info;
}
);
}
public function getArtistInformation(Artist $artist): ?ArtistInformation
{
if ($artist->is_unknown || $artist->is_various) {
return null;
}
return Cache::remember(
cache_key('artist information', $artist->name),
now()->addWeek(),
function () use ($artist): ArtistInformation {
$info = $this->encyclopedia->getArtistInformation($artist) ?: ArtistInformation::make();
if ($artist->image || (!SpotifyService::enabled() && !$info->image)) {
// If the artist already has an image, or there's no resource to download an image from,
// just return the info.
return $info;
}
// If the artist image is not set, try to download it either from Spotify (prioritized, due to
// the high quality) or from the encyclopedia. We will also set the downloaded image right
// away into the info object so that the caller/client can use it immediately.
$info->image = rescue(function () use ($artist, $info): ?string {
return $this->fetchAndStoreArtistImage($artist, $info) ?? $info->image;
});
return $info;
}
);
}
private function fetchAndStoreAlbumCover(Album $album, AlbumInformation $info): ?string
{
$coverUrl = SpotifyService::enabled()
? $this->spotifyService->tryGetAlbumCover($album)
: $info->cover;
if (!$coverUrl) {
return null;
}
$fileName = $this->imageStorage->storeImage($coverUrl);
$album->cover = $fileName;
$album->save();
return image_storage_url($fileName);
}
private function fetchAndStoreArtistImage(Artist $artist, ArtistInformation $info): ?string
{
$imgUrl = SpotifyService::enabled()
? $this->spotifyService->tryGetArtistImage($artist)
: $info->image;
if (!$imgUrl) {
return null;
}
$fileName = $this->imageStorage->storeImage($imgUrl);
$artist->image = $fileName;
$artist->save();
return image_storage_url($fileName);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/DownloadService.php | app/Services/DownloadService.php | <?php
namespace App\Services;
use App\Enums\SongStorageType;
use App\Models\Song;
use App\Models\SongZipArchive;
use App\Services\SongStorages\CloudStorageFactory;
use App\Services\SongStorages\SftpStorage;
use App\Values\Downloadable;
use App\Values\Podcast\EpisodePlayable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\File;
class DownloadService
{
/**
* @param Collection<Song>|array<array-key, Song> $songs
*/
public function getDownloadable(Collection $songs): ?Downloadable
{
if ($songs->count() === 1) {
return optional(
$this->getLocalPathOrDownloadableUrl($songs->first()), // @phpstan-ignore-line
static fn (string $url) => Downloadable::make($url)
);
}
return Downloadable::make(
(new SongZipArchive())
->addSongs($songs)
->finish()
->getPath()
);
}
public function getLocalPathOrDownloadableUrl(Song $song): ?string
{
if (!$song->storage->supported()) {
return null;
}
if ($song->isEpisode()) {
// If the song is an episode, get the episode's media URL ("path").
return $song->path;
}
if ($song->storage === SongStorageType::LOCAL) {
return $song->path;
}
if ($song->storage === SongStorageType::SFTP) {
return app(SftpStorage::class)->copyToLocal($song);
}
return CloudStorageFactory::make($song->storage)->getPresignedUrl($song->storage_metadata->getPath());
}
public function getLocalPath(Song $song): ?string
{
if (!$song->storage->supported()) {
return null;
}
if ($song->isEpisode()) {
return EpisodePlayable::getForEpisode($song)->path;
}
$location = $song->storage_metadata->getPath();
if ($song->storage === SongStorageType::LOCAL) {
return File::exists($location) ? $location : null;
}
if ($song->storage === SongStorageType::SFTP) {
/** @var SftpStorage $storage */
$storage = app(SftpStorage::class);
return $storage->copyToLocal($location);
}
return CloudStorageFactory::make($song->storage)->copyToLocal($location);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Dispatcher.php | app/Services/Dispatcher.php | <?php
namespace App\Services;
class Dispatcher
{
/**
* Whether the job should be queued or run synchronously.
*/
private bool $shouldQueue;
public function __construct()
{
$this->shouldQueue = config('queue.default') !== 'sync'
&& config('broadcasting.default') !== 'log'
&& config('broadcasting.default') !== 'null';
}
public function dispatch(object $job): mixed
{
// If the job should be queued, we simply dispatch it, assuming it already implements the `ShouldQueue`
// interface.
if ($this->shouldQueue) {
return dispatch($job);
}
// Otherwise, we call the job's `handle` method directly, providing the necessary dependencies
// and returning the result. This allows the caller (like a controller) to grab the result
// and e.g., return it as a response.
return app()->call([$job, 'handle']);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/UploadService.php | app/Services/UploadService.php | <?php
namespace App\Services;
use App\Exceptions\SongUploadFailedException;
use App\Models\Song;
use App\Models\User;
use App\Services\Scanners\FileScanner;
use App\Services\SongStorages\Contracts\MustDeleteTemporaryLocalFileAfterUpload;
use App\Services\SongStorages\SongStorage;
use App\Values\Scanning\ScanConfiguration;
use App\Values\UploadReference;
use Illuminate\Support\Facades\File;
use Throwable;
class UploadService
{
public function __construct(
private readonly SongService $songService,
private readonly SongStorage $storage,
private readonly FileScanner $scanner,
) {
}
public function handleUpload(string $filePath, User $uploader): Song
{
$uploadReference = $this->storage->storeUploadedFile($filePath, $uploader);
$config = ScanConfiguration::make(
owner: $uploader,
makePublic: $uploader->preferences->makeUploadsPublic,
extractFolderStructure: $this->storage->getStorageType()->supportsFolderStructureExtraction(),
);
try {
$song = $this->songService->createOrUpdateSongFromScan(
$this->scanner->scan($uploadReference->localPath),
$config,
);
} catch (Throwable $error) {
$this->handleUploadFailure($uploadReference, $error);
}
if ($this->storage instanceof MustDeleteTemporaryLocalFileAfterUpload) {
File::delete($uploadReference->localPath);
}
// Since we scanned a local file, the song's path was initially set to the local path.
// We need to update it to the actual storage (e.g. S3) and location (e.g., the S3 key) if applicable.
if ($song->path !== $uploadReference->location || $song->storage !== $this->storage->getStorageType()) {
$song->update([
'path' => $uploadReference->location,
'storage' => $this->storage->getStorageType(),
]);
}
return $song;
}
private function handleUploadFailure(UploadReference $reference, Throwable|string $error): never
{
$this->storage->undoUpload($reference);
throw SongUploadFailedException::make($error);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Acl.php | app/Services/Acl.php | <?php
namespace App\Services;
use App\Enums\Acl\Role;
use App\Enums\PermissionableResourceType;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Gate;
use Webmozart\Assert\Assert;
class Acl
{
private const VALID_ACTIONS = [
'edit',
'delete',
];
public function checkPermission(
PermissionableResourceType $type,
int|string $id,
string $action,
?User $user = null,
): bool {
Assert::inArray($action, self::VALID_ACTIONS);
return Gate::forUser($user ?? auth()->user())
->allows($action, self::resolveResource($type, $id));
}
private static function resolveResource(PermissionableResourceType $type, int|string $id): Model
{
$modelClass = $type->modelClass();
return $modelClass::query()->where($modelClass::getPermissionableIdentifier(), $id)->firstOrFail(); // @phpstan-ignore-line
}
/** @return Collection<Role> */
public function getAssignableRolesForUser(User $user): Collection
{
return Role::allAvailable()->filter(static fn (Role $role) => $user->role->canManage($role))
->sortBy(static fn (Role $role) => $role->level())
->values();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SearchService.php | app/Services/SearchService.php | <?php
namespace App\Services;
use App\Models\Song;
use App\Models\User;
use App\Repositories\AlbumRepository;
use App\Repositories\ArtistRepository;
use App\Repositories\PodcastRepository;
use App\Repositories\RadioStationRepository;
use App\Repositories\SongRepository;
use App\Values\ExcerptSearchResult;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Throwable;
class SearchService
{
public const DEFAULT_EXCERPT_RESULT_LIMIT = 6;
public const DEFAULT_SONG_RESULT_LIMIT = 500;
public function __construct(
private readonly SongRepository $songRepository,
private readonly ArtistRepository $artistRepository,
private readonly AlbumRepository $albumRepository,
private readonly PodcastRepository $podcastRepository,
private readonly RadioStationRepository $radioStationRepository,
) {
}
public function excerptSearch(
string $keywords,
int $limit = self::DEFAULT_EXCERPT_RESULT_LIMIT,
?User $scopedUser = null
): ExcerptSearchResult {
$scopedUser ??= auth()->user();
$results = [];
foreach (
[
$this->songRepository,
$this->artistRepository,
$this->albumRepository,
$this->podcastRepository,
$this->radioStationRepository,
] as $repository
) {
try {
$results[] = $repository->search($keywords, $limit, $scopedUser);
} catch (Throwable $e) {
Log::error('Scout search failed', ['exception' => $e]);
$results[] = new Collection();
}
}
return ExcerptSearchResult::make(...$results);
}
/** @return Collection|array<array-key, Song> */
public function searchSongs(
string $keywords,
?User $scopedUser = null,
int $limit = self::DEFAULT_SONG_RESULT_LIMIT
): Collection {
return $this->songRepository->search($keywords, $limit, $scopedUser);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/TokenManager.php | app/Services/TokenManager.php | <?php
namespace App\Services;
use App\Models\User;
use App\Values\CompositeToken;
use Illuminate\Support\Facades\Cache;
use Laravel\Sanctum\NewAccessToken;
use Laravel\Sanctum\PersonalAccessToken;
class TokenManager
{
public function createToken(User $user, array $abilities = ['*']): NewAccessToken
{
return $user->createToken(config('app.name'), $abilities);
}
public function createCompositeToken(User $user): CompositeToken
{
$token = CompositeToken::fromAccessTokens(
api: $this->createToken($user),
audio: $this->createToken($user, ['audio'])
);
Cache::forever("app.composite-tokens.$token->apiToken", $token->audioToken);
return $token;
}
public function deleteCompositionToken(string $plainTextApiToken): void
{
/** @var string $audioToken */
$audioToken = Cache::get("app.composite-tokens.$plainTextApiToken");
if ($audioToken) {
$this->deleteTokenByPlainTextToken($audioToken);
Cache::forget("app.composite-tokens.$plainTextApiToken");
}
$this->deleteTokenByPlainTextToken($plainTextApiToken);
}
public function destroyTokens(User $user): void
{
$user->tokens()->delete();
}
public function deleteTokenByPlainTextToken(string $plainTextToken): void
{
PersonalAccessToken::findToken($plainTextToken)?->delete();
}
public function getUserFromPlainTextToken(string $plainTextToken): ?User
{
return PersonalAccessToken::findToken($plainTextToken)?->tokenable;
}
public function refreshApiToken(string $currentPlainTextToken): NewAccessToken
{
$newToken = $this->createToken($this->getUserFromPlainTextToken($currentPlainTextToken));
$this->deleteTokenByPlainTextToken($currentPlainTextToken);
return $newToken;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/MediaBrowser.php | app/Services/MediaBrowser.php | <?php
namespace App\Services;
use App\Exceptions\MediaBrowserNotSupportedException;
use App\Exceptions\MediaPathNotSetException;
use App\Facades\License;
use App\Models\Folder;
use App\Models\Setting;
use App\Models\Song;
use Illuminate\Support\Str;
class MediaBrowser
{
/** @var array<string, Folder> */
private static array $folderCache = [];
private static ?string $mediaPath;
public static function used(): bool
{
return config('koel.media_browser.enabled') && License::isPlus();
}
/**
* Create a folder structure for the given song if it doesn't exist, and return the deepest folder.
* For example, if the song's path is `/root/media/path/foo/bar/baz.mp3`, it will create the folders with paths
* "foo" and "foo/bar" if they don't exist, and return the folder with path "foo/bar".
* For efficiency, we also cache the folders and the media path to avoid multiple database queries.
* This is particularly useful when processing multiple songs in a batch (e.g., during scanning).
*/
public function maybeCreateFolderStructureForSong(Song $song): void
{
throw_unless($song->storage->supportsFolderStructureExtraction(), MediaBrowserNotSupportedException::class);
// The song is already in a folder, so we don't need to create one.
if ($song->folder_id) {
return;
}
self::$mediaPath ??= Setting::get('media_path');
throw_unless(self::$mediaPath, MediaPathNotSetException::class);
$parentId = null;
$currentPath = '';
$folder = null;
$relativePath = Str::after($song->path, self::$mediaPath);
$folderPath = pathinfo($relativePath, PATHINFO_DIRNAME);
$segments = explode(DIRECTORY_SEPARATOR, trim($folderPath, DIRECTORY_SEPARATOR));
// For each segment in the folder path ('foo' and 'bar'), we will create a folder if it doesn't exist
// using the aggregated path (e.g., 'foo' and 'foo/bar').
foreach ($segments as $segment) {
if (!$segment) {
continue;
}
$currentPath = $currentPath ? sprintf('%s%s%s', $currentPath, DIRECTORY_SEPARATOR, $segment) : $segment;
if (isset(self::$folderCache[$currentPath])) {
$folder = self::$folderCache[$currentPath];
} else {
/** @var Folder $folder */
$folder = Folder::query()->firstOrCreate(
['hash' => simple_hash($currentPath)],
[
'parent_id' => $parentId,
'path' => $currentPath,
],
);
self::$folderCache[$currentPath] = $folder;
}
$parentId = $folder->id;
}
if ($folder) {
$song->folder()->associate($folder);
$song->save();
}
}
public static function clearCache(): void
{
self::$folderCache = [];
self::$mediaPath = null;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/ITunesService.php | app/Services/ITunesService.php | <?php
namespace App\Services;
use App\Http\Integrations\iTunes\ITunesConnector;
use App\Http\Integrations\iTunes\Requests\GetTrackRequest;
use App\Models\Album;
use Illuminate\Support\Facades\Cache;
class ITunesService
{
public function __construct(private readonly ITunesConnector $connector)
{
}
public static function used(): bool
{
return (bool) config('koel.services.itunes.enabled');
}
public function getTrackUrl(string $trackName, Album $album): ?string
{
return rescue(function () use ($trackName, $album): ?string {
$request = new GetTrackRequest($trackName, $album);
return Cache::remember(
cache_key('iTunes track URL', serialize($request->query())),
now()->addWeek(),
function () use ($request): ?string {
$response = $this->connector->send($request)->object();
if (!$response->resultCount) {
return null;
}
$trackUrl = $response->results[0]->trackViewUrl;
$connector = parse_url($trackUrl, PHP_URL_QUERY) ? '&' : '?';
return $trackUrl . "{$connector}at=" . config('koel.services.itunes.affiliate_id');
}
);
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/QueueService.php | app/Services/QueueService.php | <?php
namespace App\Services;
use App\Models\QueueState;
use App\Models\Song;
use App\Models\User;
use App\Repositories\SongRepository;
use App\Values\QueueState as QueueStateDTO;
class QueueService
{
public function __construct(private readonly SongRepository $songRepository)
{
}
public function getQueueState(User $user): QueueStateDTO
{
$state = QueueState::query()
->whereBelongsTo($user)
->firstOrCreate(
['user_id' => $user->id],
['song_ids' => []],
);
$currentSong = $state->current_song_id ? $this->songRepository->findOne($state->current_song_id, $user) : null;
return QueueStateDTO::make(
$this->songRepository->getMany(ids: $state->song_ids, preserveOrder: true, scopedUser: $user),
$currentSong,
$state->playback_position ?? 0
);
}
public function updateQueueState(User $user, array $songIds): void
{
QueueState::query()->updateOrCreate(['user_id' => $user->id], ['song_ids' => $songIds]);
}
public function updatePlaybackStatus(User $user, Song $song, int $position): void
{
QueueState::query()->updateOrCreate([
'user_id' => $user->id,
], [
'current_song_id' => $song->id,
'playback_position' => $position,
]);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/TicketmasterService.php | app/Services/TicketmasterService.php | <?php
namespace App\Services;
use App\Facades\License;
use App\Http\Integrations\Ticketmaster\Requests\AttractionSearchRequest;
use App\Http\Integrations\Ticketmaster\Requests\EventSearchRequest;
use App\Http\Integrations\Ticketmaster\TicketmasterConnector;
use App\Services\Geolocation\Contracts\GeolocationService;
use App\Values\Ticketmaster\TicketmasterAttraction;
use App\Values\Ticketmaster\TicketmasterEvent;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
class TicketmasterService
{
public function __construct(
private readonly TicketmasterConnector $connector,
private readonly GeolocationService $geolocator,
private readonly string $defaultCountryCode,
) {
}
public static function used(): bool
{
return License::isPlus() && config('koel.services.ticketmaster.key');
}
/** @return Collection<TicketmasterEvent>|array<array-key, TicketmasterEvent> */
public function searchEventForArtist(string $artistName, string $ip): Collection
{
$countryCode = $this->geolocator->getCountryCodeFromIp($ip) ?: $this->defaultCountryCode;
return rescue(function () use ($artistName, $countryCode) {
return Cache::remember(
cache_key('Ticketmaster events', $artistName, $countryCode),
now()->addDay(),
function () use ($artistName, $countryCode): Collection {
$attractionId = $this->getAttractionIdForArtist($artistName);
return $attractionId
? $this->connector->send(new EventSearchRequest($attractionId, $countryCode))->dto()
: collect();
}
);
}, collect());
}
private function getAttractionIdForArtist(string $artistName): ?string
{
return rescue(function () use ($artistName): ?string {
return Cache::remember(
cache_key('Ticketmaster attraction id', $artistName),
now()->addMonth(),
function () use ($artistName): ?string {
/** @var Collection<TicketmasterAttraction>|array<array-key, TicketmasterAttraction> $attractions */
$attractions = $this->connector->send(new AttractionSearchRequest($artistName))->dto();
return $attractions->firstWhere(
static function (TicketmasterAttraction $attraction) use ($artistName) {
return Str::lower($attraction->name) === Str::lower($artistName);
}
)?->id;
}
);
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/OrganizationService.php | app/Services/OrganizationService.php | <?php
namespace App\Services;
use App\Models\Organization;
use App\Repositories\OrganizationRepository;
class OrganizationService
{
public function __construct(private readonly OrganizationRepository $repository)
{
}
public function getCurrentOrganization(): Organization
{
// @phpstan-ignore-next-line
return auth()->user()?->organization ?? $this->repository->getDefault();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/UserService.php | app/Services/UserService.php | <?php
namespace App\Services;
use App\Exceptions\UserProspectUpdateDeniedException;
use App\Models\Organization;
use App\Models\User;
use App\Repositories\UserRepository;
use App\Values\ImageWritingConfig;
use App\Values\User\SsoUser;
use App\Values\User\UserCreateData;
use App\Values\User\UserUpdateData;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
class UserService
{
public function __construct(
private readonly UserRepository $repository,
private readonly ImageStorage $imageStorage,
private readonly OrganizationService $organizationService,
) {
}
public function createUser(UserCreateData $dto, ?Organization $organization = null): User
{
$dto->role->assertAvailable();
$organization ??= $this->organizationService->getCurrentOrganization();
$data = $dto->toArray();
$data['avatar'] = $dto->avatar ? $this->maybeStoreAvatar($dto->avatar) : null;
/** @var User $user */
$user = $organization->users()->create($data);
return $user->syncRoles($dto->role);
}
public function createOrUpdateUserFromSso(SsoUser $ssoUser): User
{
$existingUser = $this->repository->findOneBySso($ssoUser);
if ($existingUser) {
$existingUser->update([
'avatar' => $existingUser->has_custom_avatar ? $existingUser->avatar : $ssoUser->avatar,
'sso_id' => $ssoUser->id,
'sso_provider' => $ssoUser->provider,
]);
return $existingUser;
}
return $this->createUser(UserCreateData::fromSsoUser($ssoUser));
}
public function updateUser(User $user, UserUpdateData $dto): User
{
throw_if($user->is_prospect, new UserProspectUpdateDeniedException());
$dto->role?->assertAvailable();
$data = [
'name' => $dto->name,
'email' => $dto->email,
'password' => $dto->password ?: $user->password,
'avatar' => $dto->avatar ? $this->maybeStoreAvatar($dto->avatar) : null,
];
if ($user->sso_provider) {
// SSO users cannot change their password or email
Arr::forget($data, ['password', 'email']);
}
$user->update($data);
if ($dto->role && $user->role !== $dto->role) {
$user->syncRoles($dto->role);
}
return $user->refresh(); // make sure the roles and permissions are refreshed
}
/**
* @param string $avatar Either the URL of the avatar or image data
*/
private function maybeStoreAvatar(string $avatar): string
{
if (Str::startsWith($avatar, ['http://', 'https://'])) {
return $avatar;
}
return basename($this->imageStorage->storeImage($avatar, ImageWritingConfig::make(maxWidth: 480)));
}
public function deleteUser(User $user): void
{
$user->delete();
}
public function savePreference(User $user, string $key, mixed $value): void
{
$user->preferences = $user->preferences->set($key, $value);
$user->save();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/EmbedService.php | app/Services/EmbedService.php | <?php
namespace App\Services;
use App\Models\Album;
use App\Models\Artist;
use App\Models\Contracts\Embeddable;
use App\Models\Embed;
use App\Models\Playlist;
use App\Models\Song;
use App\Models\User;
class EmbedService
{
/** @param Album|Artist|Playlist|Song $embeddable */
public function resolveEmbedForEmbeddable(Embeddable $embeddable, User $user): Embed
{
return $embeddable->embeds()->firstOrCreate([
'embeddable_id' => $embeddable->getKey(),
'embeddable_type' => $embeddable->getMorphClass(),
'user_id' => $user->id,
]);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/AlbumService.php | app/Services/AlbumService.php | <?php
namespace App\Services;
use App\Exceptions\AlbumNameConflictException;
use App\Models\Album;
use App\Repositories\AlbumRepository;
use App\Values\Album\AlbumUpdateData;
use App\Values\ImageWritingConfig;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Symfony\Component\Finder\Finder;
class AlbumService
{
public function __construct(
private readonly AlbumRepository $albumRepository,
private readonly ImageStorage $imageStorage,
private readonly Finder $finder,
) {
}
public function updateAlbum(Album $album, AlbumUpdateData $dto): Album
{
// Ensure that the album name is unique within the artist
$existingAlbumWithTheSameName = $this->albumRepository->findOneBy([
'name' => $dto->name,
'artist_id' => $album->artist_id,
]);
throw_if($existingAlbumWithTheSameName?->isNot($album), AlbumNameConflictException::class);
$data = $dto->toArray();
if (is_string($dto->cover)) {
// A non-empty string means the user is uploading another cover,
// when an empty string means the user is removing the cover.
$data['cover'] = rescue_if($dto->cover, fn () => $this->imageStorage->storeImage($dto->cover), '');
} else {
// If the cover is null, the user's not changing or removing the cover at all.
Arr::forget($data, 'cover');
}
$album->update($data);
return $album->refresh();
}
public function storeAlbumCover(Album $album, mixed $source): ?string
{
$fileName = $this->imageStorage->storeImage($source);
$album->cover = $fileName;
$album->save();
return $fileName;
}
public function trySetAlbumCoverFromDirectory(Album $album, string $directory): void
{
// As directory scanning can be expensive, we cache and reuse the result.
Cache::remember(cache_key($directory, 'cover'), now()->addDay(), function () use ($album, $directory): ?string {
$matches = array_keys(
iterator_to_array(
$this->finder::create()
->depth(0)
->ignoreUnreadableDirs()
->files()
->followLinks()
->name('/(cov|fold)er\.(jpe?g|gif|png|webp|avif)$/i')
->in($directory)
)
);
$cover = $matches[0] ?? null;
if ($cover && is_image($cover)) {
$this->storeAlbumCover($album, $cover);
}
return $cover;
});
}
public function generateAlbumThumbnail(Album $album): string
{
$this->imageStorage->storeImage(
source: image_storage_path($album->cover),
config: ImageWritingConfig::make(
maxWidth: 48,
blur: 10,
),
path: image_storage_path($album->thumbnail),
);
return $album->thumbnail;
}
public function getOrCreateAlbumThumbnail(Album $album): ?string
{
$thumbnailPath = image_storage_path($album->thumbnail);
if ($thumbnailPath && !File::exists($thumbnailPath)) {
$this->generateAlbumThumbnail($album);
}
return $album->thumbnail;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/PodcastService.php | app/Services/PodcastService.php | <?php
namespace App\Services;
use App\Events\UserUnsubscribedFromPodcast;
use App\Exceptions\FailedToParsePodcastFeedException;
use App\Exceptions\UserAlreadySubscribedToPodcastException;
use App\Helpers\Uuid;
use App\Models\Podcast;
use App\Models\PodcastUserPivot;
use App\Models\Song as Episode;
use App\Models\User;
use App\Repositories\PodcastRepository;
use App\Repositories\SongRepository;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\RedirectMiddleware;
use GuzzleHttp\RequestOptions;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use PhanAn\Poddle\Poddle;
use PhanAn\Poddle\Values\Episode as EpisodeValue;
use PhanAn\Poddle\Values\EpisodeCollection;
use Psr\Http\Client\ClientInterface;
use Throwable;
use Webmozart\Assert\Assert;
class PodcastService
{
public function __construct(
private readonly PodcastRepository $podcastRepository,
private readonly SongRepository $songRepository,
private ?ClientInterface $client = null,
) {
}
public function addPodcast(string $url, User $user): Podcast
{
// Since downloading and parsing a feed can be time-consuming, try setting the execution time to 5 minutes
@ini_set('max_execution_time', 300);
$podcast = $this->podcastRepository->findOneByUrl($url);
if ($podcast) {
if ($this->isPodcastObsolete($podcast)) {
$this->refreshPodcast($podcast);
}
$this->subscribeUserToPodcast($user, $podcast);
return $podcast;
}
try {
$parser = $this->createParser($url);
$channel = $parser->getChannel();
return DB::transaction(function () use ($url, $podcast, $parser, $channel, $user) {
/** @var Podcast $podcast */
$podcast = Podcast::query()->create([
'url' => $url,
'title' => $channel->title,
'description' => $channel->description,
'author' => $channel->metadata->author,
'link' => $channel->link,
'language' => $channel->language,
'explicit' => $channel->explicit,
'image' => $channel->image,
'categories' => $channel->categories,
'metadata' => $channel->metadata,
'added_by' => $user->id,
'last_synced_at' => now(),
]);
$this->synchronizeEpisodes($podcast, $parser->getEpisodes(true));
$this->subscribeUserToPodcast($user, $podcast);
return $podcast;
});
} catch (UserAlreadySubscribedToPodcastException $exception) {
throw $exception;
} catch (Throwable $exception) {
Log::error($exception);
throw FailedToParsePodcastFeedException::create($url, $exception);
}
}
public function refreshPodcast(Podcast $podcast): Podcast
{
$parser = $this->createParser($podcast->url);
$channel = $parser->getChannel();
$pubDate = $parser->xmlReader->value('rss.channel.pubDate')->first()
?? $parser->xmlReader->value('rss.channel.lastBuildDate')->first();
if ($pubDate && Carbon::createFromFormat(Carbon::RFC1123, $pubDate)?->isBefore($podcast->last_synced_at)) {
// The pubDate/lastBuildDate value indicates that there's been no new content since the last check.
// We'll simply return the podcast.
return $podcast;
}
$this->synchronizeEpisodes($podcast, $parser->getEpisodes(true));
$podcast->update([
'title' => $channel->title,
'description' => $channel->description,
'author' => $channel->metadata->author,
'link' => $channel->link,
'language' => $channel->language,
'explicit' => $channel->explicit,
'image' => $channel->image,
'categories' => $channel->categories,
'metadata' => $channel->metadata,
'last_synced_at' => now(),
]);
return $podcast->refresh();
}
private function synchronizeEpisodes(Podcast $podcast, EpisodeCollection $episodeCollection): void
{
$existingEpisodeGuids = $this->songRepository->getEpisodeGuidsByPodcast($podcast);
$records = [];
$ids = [];
/** @var EpisodeValue $episodeValue */
foreach ($episodeCollection as $episodeValue) {
if (!in_array($episodeValue->guid->value, $existingEpisodeGuids, true)) {
$id = Uuid::generate();
$ids[] = $id;
$records[] = [
'id' => $id,
'podcast_id' => $podcast->id,
'title' => $episodeValue->title,
'lyrics' => '',
'path' => $episodeValue->enclosure->url,
'created_at' => $episodeValue->metadata->pubDate ?: now(),
'updated_at' => $episodeValue->metadata->pubDate ?: now(),
'episode_metadata' => $episodeValue->metadata->toJson(),
'episode_guid' => $episodeValue->guid,
'length' => $episodeValue->metadata->duration ?? 0,
'mtime' => time(),
'is_public' => true,
];
}
}
// We use insert() instead of $podcast->episodes()->createMany() for better performance,
// as the latter would trigger a separate query for each episode.
Episode::query()->insert($records);
// Since insert() doesn't trigger model events, Scout operations will not be called.
// We have to manually update the search index.
Episode::query()->whereIn('id', $ids)->searchable(); // @phpstan-ignore-line
}
private function subscribeUserToPodcast(User $user, Podcast $podcast): void
{
$user->subscribeToPodcast($podcast);
// Refreshing so that $podcast->subscribers are updated
$podcast->refresh();
}
public function updateEpisodeProgress(User $user, Episode $episode, int $position): void
{
Assert::true($user->subscribedToPodcast($episode->podcast));
/** @var PodcastUserPivot $subscription */
$subscription = $episode->podcast->subscribers->sole('id', $user->id)->pivot;
$state = $subscription->state->toArray();
$state['current_episode'] = $episode->id;
$state['progresses'][$episode->id] = $position;
$subscription->update(['state' => $state]);
}
public function unsubscribeUserFromPodcast(User $user, Podcast $podcast): void
{
$user->unsubscribeFromPodcast($podcast);
event(new UserUnsubscribedFromPodcast($user, $podcast));
}
public function isPodcastObsolete(Podcast $podcast): bool
{
if (abs($podcast->last_synced_at->diffInHours(now())) < 12) {
// If we have recently synchronized the podcast, consider it "fresh"
return false;
}
try {
$lastModified = Http::head($podcast->url)->header('Last-Modified');
return $lastModified
&& Carbon::createFromFormat(Carbon::RFC1123, $lastModified)->isAfter($podcast->last_synced_at);
} catch (Throwable) {
return true;
}
}
/**
* Get a directly streamable (CORS-friendly) URL by following redirects if necessary.
*/
public function getStreamableUrl(string|Episode $url, ?Client $client = null, string $method = 'OPTIONS'): ?string
{
$url = $url instanceof Episode ? $url->path : $url;
$client ??= new Client();
try {
$response = $client->request($method, $url, [
RequestOptions::HEADERS => [
'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4.1 Safari/605.1.15', // @phpcs-ignore-line
'Origin' => '*',
],
RequestOptions::HTTP_ERRORS => false,
RequestOptions::ALLOW_REDIRECTS => ['track_redirects' => true],
]);
$redirects = Arr::wrap($response->getHeader(RedirectMiddleware::HISTORY_HEADER));
// Sometimes the podcast server disallows OPTIONS requests. We'll try again with a HEAD request.
if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500 && $method !== 'HEAD') {
return $this->getStreamableUrl($url, $client, 'HEAD');
}
if (in_array('*', Arr::wrap($response->getHeader('Access-Control-Allow-Origin')), true)) {
// If there were redirects, the last one is the final URL.
return $redirects ? Arr::last($redirects) : $url;
}
return null;
} catch (Throwable) {
return null;
}
}
public function deletePodcast(Podcast $podcast): void
{
$podcast->delete();
}
private function createParser(string $url): Poddle
{
return Poddle::fromUrl($url, 5 * 60, $this->client);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SimpleLrcReader.php | app/Services/SimpleLrcReader.php | <?php
namespace App\Services;
use Illuminate\Support\Facades\File;
use Throwable;
class SimpleLrcReader
{
public function tryReadForMediaFile(string $mediaFilePath): string
{
$lrcFilePath = self::getLrcFilePath($mediaFilePath);
try {
return $lrcFilePath ? trim(File::get($lrcFilePath)) : '';
} catch (Throwable) {
return '';
}
}
private static function getLrcFilePath(string $mediaFilePath): ?string
{
foreach (['.lrc', '.LRC'] as $extension) {
$lrcFilePath = preg_replace('/\.[^.]+$/', $extension, $mediaFilePath);
if (File::isFile($lrcFilePath) && File::isReadable($lrcFilePath)) {
return $lrcFilePath;
}
}
return null;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Transcoding/TranscodeStrategyFactory.php | app/Services/Transcoding/TranscodeStrategyFactory.php | <?php
namespace App\Services\Transcoding;
use App\Enums\SongStorageType;
class TranscodeStrategyFactory
{
public static function make(SongStorageType $storageType): TranscodingStrategy
{
return match ($storageType) {
SongStorageType::LOCAL => app(LocalTranscodingStrategy::class),
SongStorageType::S3,
SongStorageType::S3_LAMBDA,
SongStorageType::DROPBOX => app(CloudTranscodingStrategy::class),
SongStorageType::SFTP => app(SftpTranscodingStrategy::class),
};
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Transcoding/TranscodingStrategy.php | app/Services/Transcoding/TranscodingStrategy.php | <?php
namespace App\Services\Transcoding;
use App\Enums\SongStorageType;
use App\Models\Song;
use App\Models\Transcode;
use App\Repositories\TranscodeRepository;
abstract class TranscodingStrategy
{
public function __construct(
protected TranscodeRepository $transcodeRepository,
protected Transcoder $transcoder,
) {
}
protected function findTranscodeBySongAndBitRate(Song $song, int $bitRate): ?Transcode
{
return $this->transcodeRepository->findFirstWhere([
'song_id' => $song->id,
'bit_rate' => $bitRate,
]);
}
protected function createOrUpdateTranscode(
Song $song,
string $locationOrCloudKey,
int $bitRate,
string $hash,
int $fileSize,
): Transcode {
Transcode::query()->upsert(
values: [
'song_id' => $song->id,
'location' => $locationOrCloudKey,
'bit_rate' => $bitRate,
'hash' => $hash,
'file_size' => $fileSize,
],
uniqueBy: ['song_id', 'bit_rate'],
update: ['location', 'hash', 'file_size'],
);
return $this->findTranscodeBySongAndBitRate($song, $bitRate); // @phpstan-ignore-line
}
abstract public function getTranscodeLocation(Song $song, int $bitRate): string;
abstract public function deleteTranscodeFile(string $location, SongStorageType $storageType): void;
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Transcoding/SftpTranscodingStrategy.php | app/Services/Transcoding/SftpTranscodingStrategy.php | <?php
namespace App\Services\Transcoding;
use App\Enums\SongStorageType;
use App\Helpers\Ulid;
use App\Models\Song;
use App\Services\SongStorages\SftpStorage;
use Illuminate\Support\Facades\File;
class SftpTranscodingStrategy extends TranscodingStrategy
{
public function getTranscodeLocation(Song $song, int $bitRate): string
{
$transcode = $this->findTranscodeBySongAndBitRate($song, $bitRate);
if ($transcode?->isValid()) {
return $transcode->location;
}
// If a transcode record exists, but is not valid (i.e., checksum failed), delete the associated file.
if ($transcode) {
File::delete($transcode->location);
}
/** @var SftpStorage $storage */
$storage = app(SftpStorage::class);
$tmpSource = $storage->copyToLocal($song->storage_metadata->getPath());
// (Re)Transcode the song to the specified bit rate and either create a new transcode record or
// update the existing one.
$destination = artifact_path(sprintf('transcodes/%d/%s.m4a', $bitRate, Ulid::generate()));
$this->transcoder->transcode($tmpSource, $destination, $bitRate);
$this->createOrUpdateTranscode(
$song,
$destination,
$bitRate,
File::hash($destination),
File::size($destination),
);
File::delete($tmpSource);
return $destination;
}
public function deleteTranscodeFile(string $location, SongStorageType $storageType): void
{
/** @var SftpStorage $storage */
$storage = app(SftpStorage::class);
$storage->deleteFileUnderPath(path: $location, backup: false);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Transcoding/LocalTranscodingStrategy.php | app/Services/Transcoding/LocalTranscodingStrategy.php | <?php
namespace App\Services\Transcoding;
use App\Enums\SongStorageType;
use App\Helpers\Ulid;
use App\Models\Song;
use Illuminate\Support\Facades\File;
class LocalTranscodingStrategy extends TranscodingStrategy
{
public function getTranscodeLocation(Song $song, int $bitRate): string
{
$transcode = $this->findTranscodeBySongAndBitRate($song, $bitRate);
if ($transcode?->isValid()) {
return $transcode->location;
}
// If a transcode record exists, but is not valid (i.e., checksum failed), delete the associated file.
if ($transcode) {
File::delete($transcode->location);
}
// (Re)Transcode the song to the specified bit rate and either create a new transcode record or
// update the existing one.
$destination = artifact_path(sprintf('transcodes/%d/%s.m4a', $bitRate, Ulid::generate()));
$this->transcoder->transcode($song->path, $destination, $bitRate);
$this->createOrUpdateTranscode(
$song,
$destination,
$bitRate,
File::hash($destination),
File::size($destination),
);
return $destination;
}
public function deleteTranscodeFile(string $location, SongStorageType $storageType): void
{
File::delete($location);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Transcoding/Transcoder.php | app/Services/Transcoding/Transcoder.php | <?php
namespace App\Services\Transcoding;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Process;
class Transcoder
{
public function transcode(string $source, string $destination, int $bitRate): void
{
setlocale(LC_CTYPE, 'en_US.UTF-8'); // #1481 special chars might be stripped otherwise
File::ensureDirectoryExists(dirname($destination));
Process::timeout(60)->run([
config('koel.streaming.ffmpeg_path'),
'-i', $source,
'-vn', // Strip video
'-c:a', 'aac', // Use native AAC encoder for its efficiency
'-b:a', "{$bitRate}k", // Set target bitrate (e.g., 128k, 192k)
'-y', // Overwrite if exists
$destination,
]);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Transcoding/CloudTranscodingStrategy.php | app/Services/Transcoding/CloudTranscodingStrategy.php | <?php
namespace App\Services\Transcoding;
use App\Enums\SongStorageType;
use App\Helpers\Ulid;
use App\Models\Song;
use App\Models\Transcode;
use App\Services\SongStorages\CloudStorage;
use App\Services\SongStorages\CloudStorageFactory;
use Illuminate\Support\Facades\File;
class CloudTranscodingStrategy extends TranscodingStrategy
{
public function getTranscodeLocation(Song $song, int $bitRate): string
{
$storage = CloudStorageFactory::make($song->storage);
$transcode = $this->findTranscodeBySongAndBitRate($song, $bitRate)
?? $this->createTranscode($storage, $song, $bitRate);
return $storage->getPresignedUrl($transcode->location);
}
/**
* Create a new transcode for the given song at the specified bit rate by performing the following steps:
* 1. Transcode the song to the specified bit rate and store it temporarily.
* 2. Upload the transcoded file back to the cloud storage.
* 3. Store the transcode record in the database.
* 4. Delete the temporary file.
*/
private function createTranscode(CloudStorage $storage, Song $song, int $bitRate): Transcode
{
$tmpDestination = artifact_path(sprintf('tmp/%s.m4a', Ulid::generate()));
$this->transcoder->transcode(
$storage->getPresignedUrl($song->storage_metadata->getPath()),
$tmpDestination,
$bitRate,
);
$key = sprintf('transcodes/%d/%s.m4a', $bitRate, Ulid::generate());
try {
$storage->uploadToStorage($key, $tmpDestination);
return $this->createOrUpdateTranscode(
$song,
$key,
$bitRate,
File::hash($tmpDestination),
File::size($tmpDestination),
);
} finally {
File::delete($tmpDestination);
}
}
public function deleteTranscodeFile(string $location, SongStorageType $storageType): void
{
CloudStorageFactory::make($storageType)->deleteFileWithKey(key: $location, backup: false);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SongStorages/SftpStorage.php | app/Services/SongStorages/SftpStorage.php | <?php
namespace App\Services\SongStorages;
use App\Enums\SongStorageType;
use App\Helpers\Ulid;
use App\Models\User;
use App\Services\SongStorages\Concerns\DeletesUsingFilesystem;
use App\Services\SongStorages\Concerns\MovesUploadedFile;
use App\Services\SongStorages\Contracts\MustDeleteTemporaryLocalFileAfterUpload;
use App\Values\UploadReference;
use Closure;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class SftpStorage extends SongStorage implements MustDeleteTemporaryLocalFileAfterUpload
{
use DeletesUsingFilesystem;
use MovesUploadedFile;
private Filesystem $disk;
public function __construct()
{
$this->disk = Storage::disk('sftp');
}
public function storeUploadedFile(string $uploadedFilePath, User $uploader): UploadReference
{
$path = $this->generateRemotePath(basename($uploadedFilePath), $uploader);
$this->disk->put($path, fopen($uploadedFilePath, 'r'));
return UploadReference::make(
location: "sftp://$path",
localPath: $uploadedFilePath,
);
}
public function undoUpload(UploadReference $reference): void
{
// Delete the tmp file
File::delete($reference->localPath);
// Delete the file from the SFTP server
$this->delete(location: Str::after($reference->location, 'sftp://'), backup: false);
}
public function delete(string $location, bool $backup = false): void
{
$this->deleteFileUnderPath(
$location,
$backup ? static fn (Filesystem $fs, string $path) => $fs->copy($path, "$path.bak") : false,
);
}
public function copyToLocal(string $path): string
{
$localPath = artifact_path(sprintf('tmp/%s_%s', Ulid::generate(), basename($path)));
file_put_contents($localPath, $this->disk->readStream($path));
return $localPath;
}
public function testSetup(): void
{
$this->disk->put('test.txt', 'Koel test file');
$this->disk->delete('test.txt');
}
private function generateRemotePath(string $filename, User $uploader): string
{
return sprintf('%s__%s__%s', $uploader->id, Ulid::generate(), $filename);
}
public function deleteFileUnderPath(string $path, bool|Closure $backup): void
{
$this->deleteUsingFilesystem($this->disk, $path, $backup);
}
public function getStorageType(): SongStorageType
{
return SongStorageType::SFTP;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SongStorages/DropboxStorage.php | app/Services/SongStorages/DropboxStorage.php | <?php
namespace App\Services\SongStorages;
use App\Enums\SongStorageType;
use App\Filesystems\DropboxFilesystem;
use App\Models\User;
use App\Services\SongStorages\Concerns\DeletesUsingFilesystem;
use App\Values\UploadReference;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
class DropboxStorage extends CloudStorage
{
use DeletesUsingFilesystem;
public function __construct(
private readonly DropboxFilesystem $filesystem,
private readonly array $config
) {
$this->filesystem->getAdapter()->getClient()->setAccessToken($this->maybeRefreshAccessToken());
}
public function storeUploadedFile(string $uploadedFilePath, User $uploader): UploadReference
{
$key = $this->generateStorageKey(basename($uploadedFilePath), $uploader);
$this->uploadToStorage($key, $uploadedFilePath);
return UploadReference::make(
location: "dropbox://$key",
localPath: $uploadedFilePath,
);
}
public function undoUpload(UploadReference $reference): void
{
// Delete the temporary file
File::delete($reference->localPath);
// Delete the file from Dropbox
$this->delete(Str::after($reference->location, 'dropbox://'));
}
private function maybeRefreshAccessToken(): string
{
$accessToken = Cache::get('dropbox_access_token');
if ($accessToken) {
return $accessToken;
}
$response = Http::asForm()
->withBasicAuth($this->config['app_key'], $this->config['app_secret'])
->post('https://api.dropboxapi.com/oauth2/token', [
'refresh_token' => $this->config['refresh_token'],
'grant_type' => 'refresh_token',
]);
Cache::put(
'dropbox_access_token',
$response->json('access_token'),
now()->addSeconds($response->json('expires_in') - 60) // 60 seconds buffer
);
return $response->json('access_token');
}
public function getPresignedUrl(string $key): string
{
return $this->filesystem->temporaryUrl($key);
}
public function delete(string $location, bool $backup = false): void
{
$this->deleteFileWithKey($location, $backup);
}
public function testSetup(): void
{
$this->filesystem->write('test.txt', 'Koel test file.');
$this->filesystem->delete('test.txt');
}
public function getStorageType(): SongStorageType
{
return SongStorageType::DROPBOX;
}
public function uploadToStorage(string $key, string $path): void
{
$this->filesystem->writeStream($key, fopen($path, 'r'));
}
public function deleteFileWithKey(string $key, bool $backup): void
{
$this->deleteUsingFilesystem($this->filesystem, $key, $backup);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SongStorages/CloudStorageFactory.php | app/Services/SongStorages/CloudStorageFactory.php | <?php
namespace App\Services\SongStorages;
use App\Enums\SongStorageType;
use App\Exceptions\NonCloudStorageException;
class CloudStorageFactory
{
public static function make(SongStorageType $storageType): CloudStorage
{
return match ($storageType) {
SongStorageType::S3_LAMBDA => app(S3LambdaStorage::class),
SongStorageType::S3 => app(S3CompatibleStorage::class),
SongStorageType::DROPBOX => app(DropboxStorage::class),
default => throw NonCloudStorageException::create($storageType),
};
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SongStorages/SongStorage.php | app/Services/SongStorages/SongStorage.php | <?php
namespace App\Services\SongStorages;
use App\Enums\SongStorageType;
use App\Exceptions\KoelPlusRequiredException;
use App\Models\User;
use App\Values\UploadReference;
abstract class SongStorage
{
abstract public function getStorageType(): SongStorageType;
abstract public function storeUploadedFile(string $uploadedFilePath, User $uploader): UploadReference;
abstract public function undoUpload(UploadReference $reference): void;
abstract public function delete(string $location, bool $backup = false): void;
abstract public function testSetup(): void;
public function assertSupported(): void
{
throw_unless(
$this->getStorageType()->supported(),
new KoelPlusRequiredException('The storage driver is only supported in Koel Plus.')
);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SongStorages/S3LambdaStorage.php | app/Services/SongStorages/S3LambdaStorage.php | <?php
namespace App\Services\SongStorages;
use App\Enums\SongStorageType;
use App\Exceptions\MethodNotImplementedException;
use App\Exceptions\SongPathNotFoundException;
use App\Models\Album;
use App\Models\Artist;
use App\Models\Song;
use App\Models\User;
use App\Repositories\SongRepository;
use App\Repositories\UserRepository;
use App\Services\AlbumService;
use App\Values\UploadReference;
/**
* The legacy storage implementation for Lambda and S3, to provide backward compatibility.
* In this implementation, the songs are supposed to be uploaded to S3 directly.
*/
class S3LambdaStorage extends S3CompatibleStorage
{
public function __construct(
private readonly AlbumService $albumService,
private readonly SongRepository $songRepository,
private readonly UserRepository $userRepository
) {
parent::__construct();
}
public function storeUploadedFile(string $uploadedFilePath, User $uploader): UploadReference
{
throw new MethodNotImplementedException('Lambda storage does not support uploading.');
}
public function undoUpload(UploadReference $reference): void
{
throw new MethodNotImplementedException('Lambda storage does not support uploading.');
}
public function createSongEntry(
string $bucket,
string $key,
string $artistName,
string $albumName,
string $albumArtistName,
?array $cover,
string $title,
float $duration,
int $track,
string $lyrics
): Song {
$user = $this->userRepository->getFirstAdminUser();
$path = Song::getPathFromS3BucketAndKey($bucket, $key);
$artist = Artist::getOrCreate($user, $artistName);
$albumArtist = $albumArtistName && $albumArtistName !== $artistName
? Artist::getOrCreate($user, $albumArtistName)
: $artist;
$album = Album::getOrCreate($albumArtist, $albumName);
if ($cover) {
$this->albumService->storeAlbumCover($album, base64_decode($cover['data'], true));
}
return Song::query()->updateOrCreate(['path' => $path], [
'album_id' => $album->id,
'artist_id' => $artist->id,
'title' => $title,
'length' => $duration,
'track' => $track,
'lyrics' => $lyrics,
'mtime' => time(),
'owner_id' => $user->id,
'is_public' => true,
'storage' => SongStorageType::S3_LAMBDA,
]);
}
public function deleteSongEntry(string $bucket, string $key): void
{
$path = Song::getPathFromS3BucketAndKey($bucket, $key);
$song = $this->songRepository->findOneByPath($path);
throw_unless((bool) $song, SongPathNotFoundException::create($path));
$song->delete();
}
public function delete(string $location, bool $backup = false): void
{
throw new MethodNotImplementedException('Lambda storage does not support deleting from filesystem.');
}
public function getStorageType(): SongStorageType
{
return SongStorageType::S3_LAMBDA;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SongStorages/CloudStorage.php | app/Services/SongStorages/CloudStorage.php | <?php
namespace App\Services\SongStorages;
use App\Helpers\Ulid;
use App\Models\User;
use App\Services\SongStorages\Concerns\MovesUploadedFile;
use App\Services\SongStorages\Contracts\MustDeleteTemporaryLocalFileAfterUpload;
use Illuminate\Support\Facades\File;
abstract class CloudStorage extends SongStorage implements MustDeleteTemporaryLocalFileAfterUpload
{
use MovesUploadedFile;
public function copyToLocal(string $key): string
{
$publicUrl = $this->getPresignedUrl($key);
$localPath = artifact_path(sprintf('tmp/%s_%s', Ulid::generate(), basename($key)));
File::copy($publicUrl, $localPath);
return $localPath;
}
protected function generateStorageKey(string $filename, User $uploader): string
{
return sprintf('%s__%s__%s', $uploader->id, Ulid::generate(), $filename);
}
abstract public function uploadToStorage(string $key, string $path): void;
abstract public function getPresignedUrl(string $key): string;
abstract public function deleteFileWithKey(string $key, bool $backup): void;
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SongStorages/S3CompatibleStorage.php | app/Services/SongStorages/S3CompatibleStorage.php | <?php
namespace App\Services\SongStorages;
use App\Enums\SongStorageType;
use App\Models\User;
use App\Services\SongStorages\Concerns\DeletesUsingFilesystem;
use App\Values\UploadReference;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
class S3CompatibleStorage extends CloudStorage
{
use DeletesUsingFilesystem;
public function __construct(private readonly ?string $bucket = null)
{
}
public function storeUploadedFile(string $uploadedFilePath, User $uploader): UploadReference
{
$key = $this->generateStorageKey(basename($uploadedFilePath), $uploader);
$this->uploadToStorage($key, $uploadedFilePath);
return UploadReference::make(
location: "s3://$this->bucket/$key",
localPath: $uploadedFilePath,
);
}
public function undoUpload(UploadReference $reference): void
{
// Delete the temporary file
File::delete($reference->localPath);
// Delete the file from S3
$this->deleteFileWithKey(Str::after($reference->location, "s3://$this->bucket/"));
}
public function getPresignedUrl(string $key): string
{
return Storage::disk('s3')->temporaryUrl($key, now()->addHour());
}
public function deleteFileWithKey(string $key, bool $backup = false): void
{
$this->deleteUsingFilesystem(Storage::disk('s3'), $key, $backup);
}
public function delete(string $location, bool $backup = false): void
{
$this->deleteFileWithKey($location, $backup);
}
public function uploadToStorage(string $key, string $path): void
{
Storage::disk('s3')->put($key, fopen($path, 'r'));
}
public function testSetup(): void
{
Storage::disk('s3')->put('test.txt', 'Koel test file');
Storage::disk('s3')->delete('test.txt');
}
public function getStorageType(): SongStorageType
{
return SongStorageType::S3;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SongStorages/LocalStorage.php | app/Services/SongStorages/LocalStorage.php | <?php
namespace App\Services\SongStorages;
use App\Enums\SongStorageType;
use App\Exceptions\MediaPathNotSetException;
use App\Helpers\Ulid;
use App\Models\Setting;
use App\Models\User;
use App\Values\UploadReference;
use Exception;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
class LocalStorage extends SongStorage
{
public function storeUploadedFile(string $uploadedFilePath, User $uploader): UploadReference
{
$destination = $this->getDestination($uploadedFilePath, $uploader);
File::move($uploadedFilePath, $destination);
// For local storage, the "location" and "localPath" are the same.
return UploadReference::make(
location: $destination,
localPath: $destination,
);
}
public function undoUpload(UploadReference $reference): void
{
// To undo an upload, we simply delete the file from the local disk.
File::delete($reference->localPath);
}
private function getUploadDirectory(User $uploader): string
{
$mediaPath = Setting::get('media_path');
throw_unless((bool) $mediaPath, MediaPathNotSetException::class);
$dir = "$mediaPath/__KOEL_UPLOADS_\${$uploader->id}__/";
File::ensureDirectoryExists($dir);
return $dir;
}
private function getDestination(string $sourcePath, User $uploader): string
{
$uploadDirectory = $this->getUploadDirectory($uploader);
$sourceName = basename($sourcePath);
// If there's no existing file with the same name in the upload directory, use the original name.
// Otherwise, prefix the original name with a hash.
// The whole point is to keep a readable file name when we can.
if (!File::exists($uploadDirectory . $sourceName)) {
return $uploadDirectory . $sourceName;
}
return $uploadDirectory . $this->getUniqueHash() . '_' . $sourceName;
}
private function getUniqueHash(): string
{
return Str::take(sha1(Ulid::generate()), 6);
}
public function delete(string $location, bool $backup = false): void
{
if ($backup) {
File::move($location, "$location.bak");
} else {
throw_unless(File::delete($location), new Exception("Failed to delete song file: $location"));
}
}
public function testSetup(): void
{
$mediaPath = Setting::get('media_path');
if (File::isReadable($mediaPath) && File::isWritable($mediaPath)) {
return;
}
throw new Exception("The media path $mediaPath is not readable or writable.");
}
public function getStorageType(): SongStorageType
{
return SongStorageType::LOCAL;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SongStorages/Contracts/MustDeleteTemporaryLocalFileAfterUpload.php | app/Services/SongStorages/Contracts/MustDeleteTemporaryLocalFileAfterUpload.php | <?php
namespace App\Services\SongStorages\Contracts;
interface MustDeleteTemporaryLocalFileAfterUpload
{
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SongStorages/Concerns/DeletesUsingFilesystem.php | app/Services/SongStorages/Concerns/DeletesUsingFilesystem.php | <?php
namespace App\Services\SongStorages\Concerns;
use Closure;
use Illuminate\Contracts\Filesystem\Filesystem as IlluminateFilesystem;
use Illuminate\Support\Facades\Log;
use League\Flysystem\Filesystem;
use Throwable;
trait DeletesUsingFilesystem
{
private function deleteUsingFilesystem(
Filesystem | IlluminateFilesystem $disk,
string $key,
bool|Closure $backup,
): void {
try {
if (is_callable($backup)) {
$backup($disk, $key);
} elseif ($backup) {
$disk->copy($key, "backup/$key.bak");
}
} catch (Throwable $e) {
Log::error('Failed to backup file.', [
'key' => $key,
'error' => $e,
]);
}
$disk->delete($key);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/SongStorages/Concerns/MovesUploadedFile.php | app/Services/SongStorages/Concerns/MovesUploadedFile.php | <?php
namespace App\Services\SongStorages\Concerns;
use App\Helpers\Ulid;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\File as FileFacade;
use Symfony\Component\HttpFoundation\File\File;
trait MovesUploadedFile
{
protected function moveUploadedFileToTemporaryLocation(UploadedFile $file): File
{
// Can't scan the uploaded file directly, as it apparently causes some misbehavior during idv3 tag reading.
// Instead, we copy the file to a tmp directory and later scan it from there.
$tmpDir = artifact_path('tmp/' . Ulid::generate());
FileFacade::ensureDirectoryExists($tmpDir);
return $file->move($tmpDir, $file->getClientOriginalName());
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Streamer/Streamer.php | app/Services/Streamer/Streamer.php | <?php
namespace App\Services\Streamer;
use App\Enums\SongStorageType;
use App\Exceptions\KoelPlusRequiredException;
use App\Models\Song;
use App\Services\Streamer\Adapters\DropboxStreamerAdapter;
use App\Services\Streamer\Adapters\LocalStreamerAdapter;
use App\Services\Streamer\Adapters\PodcastStreamerAdapter;
use App\Services\Streamer\Adapters\S3CompatibleStreamerAdapter;
use App\Services\Streamer\Adapters\SftpStreamerAdapter;
use App\Services\Streamer\Adapters\StreamerAdapter;
use App\Services\Streamer\Adapters\TranscodingStreamerAdapter;
use App\Values\RequestedStreamingConfig;
class Streamer
{
public function __construct(
private readonly Song $song,
private ?StreamerAdapter $adapter = null,
private readonly ?RequestedStreamingConfig $config = null
) {
$this->adapter ??= $this->resolveAdapter();
}
private function resolveAdapter(): StreamerAdapter
{
throw_unless($this->song->storage->supported(), KoelPlusRequiredException::class);
if ($this->song->isEpisode()) {
return app(PodcastStreamerAdapter::class);
}
if ($this->config?->transcode || self::shouldTranscode($this->song)) {
return app(TranscodingStreamerAdapter::class);
}
return match ($this->song->storage) {
SongStorageType::LOCAL => app(LocalStreamerAdapter::class),
SongStorageType::SFTP => app(SftpStreamerAdapter::class),
SongStorageType::S3, SongStorageType::S3_LAMBDA => app(S3CompatibleStreamerAdapter::class),
SongStorageType::DROPBOX => app(DropboxStreamerAdapter::class),
};
}
public function stream(): mixed
{
// Turn off error reporting to make sure our stream isn't interfered with.
@error_reporting(0);
return $this->adapter->stream($this->song, $this->config);
}
public function getAdapter(): StreamerAdapter
{
return $this->adapter;
}
/**
* Determine if the given song should be transcoded based on its format and the server's FFmpeg installation.
*/
private static function shouldTranscode(Song $song): bool
{
if ($song->isEpisode()) {
return false;
}
if (!self::hasValidFfmpegInstallation()) {
return false;
}
if (
in_array($song->mime_type, ['audio/flac', 'audio/x-flac'], true)
&& config('koel.streaming.transcode_flac')
) {
return true;
}
return in_array($song->mime_type, config('koel.streaming.transcode_required_mime_types', []), true);
}
private static function hasValidFfmpegInstallation(): bool
{
return app()->runningUnitTests() || is_executable(config('koel.streaming.ffmpeg_path'));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Streamer/Adapters/SftpStreamerAdapter.php | app/Services/Streamer/Adapters/SftpStreamerAdapter.php | <?php
namespace App\Services\Streamer\Adapters;
use App\Models\Song;
use App\Services\SongStorages\SftpStorage;
use App\Services\Streamer\Adapters\Concerns\StreamsLocalPath;
use App\Values\RequestedStreamingConfig;
class SftpStreamerAdapter implements StreamerAdapter
{
use StreamsLocalPath;
public function __construct(private readonly SftpStorage $storage)
{
}
public function stream(Song $song, ?RequestedStreamingConfig $config = null): void
{
$this->streamLocalPath($this->storage->copyToLocal($song->storage_metadata->getPath()));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Streamer/Adapters/S3CompatibleStreamerAdapter.php | app/Services/Streamer/Adapters/S3CompatibleStreamerAdapter.php | <?php
namespace App\Services\Streamer\Adapters;
use App\Models\Song;
use App\Services\SongStorages\S3CompatibleStorage;
use App\Values\RequestedStreamingConfig;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector;
class S3CompatibleStreamerAdapter implements StreamerAdapter
{
public function __construct(private readonly S3CompatibleStorage $storage)
{
}
public function stream(Song $song, ?RequestedStreamingConfig $config = null): Redirector|RedirectResponse
{
$this->storage->assertSupported();
return redirect($this->storage->getPresignedUrl($song->storage_metadata->getPath()));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Streamer/Adapters/XSendFileStreamerAdapter.php | app/Services/Streamer/Adapters/XSendFileStreamerAdapter.php | <?php
namespace App\Services\Streamer\Adapters;
use App\Models\Song;
use App\Values\RequestedStreamingConfig;
class XSendFileStreamerAdapter extends LocalStreamerAdapter
{
/**
* Stream the current song using Apache's x_sendfile module.
*/
public function stream(Song $song, ?RequestedStreamingConfig $config = null): never
{
$path = $song->storage_metadata->getPath();
$contentType = 'audio/' . pathinfo($path, PATHINFO_EXTENSION);
header("X-Sendfile: $path");
header("Content-Type: $contentType");
header('Content-Disposition: inline; filename="' . basename($path) . '"');
// prevent PHP from sending stray headers
exit;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Streamer/Adapters/LocalStreamerAdapter.php | app/Services/Streamer/Adapters/LocalStreamerAdapter.php | <?php
namespace App\Services\Streamer\Adapters;
abstract class LocalStreamerAdapter implements StreamerAdapter
{
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Streamer/Adapters/DropboxStreamerAdapter.php | app/Services/Streamer/Adapters/DropboxStreamerAdapter.php | <?php
namespace App\Services\Streamer\Adapters;
use App\Models\Song;
use App\Services\SongStorages\DropboxStorage;
use App\Values\RequestedStreamingConfig;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Redirector;
class DropboxStreamerAdapter implements StreamerAdapter
{
public function __construct(private readonly DropboxStorage $storage)
{
}
public function stream(Song $song, ?RequestedStreamingConfig $config = null): Redirector|RedirectResponse
{
$this->storage->assertSupported();
return redirect($this->storage->getPresignedUrl($song->storage_metadata->getPath()));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Streamer/Adapters/PhpStreamerAdapter.php | app/Services/Streamer/Adapters/PhpStreamerAdapter.php | <?php
namespace App\Services\Streamer\Adapters;
use App\Models\Song;
use App\Services\Streamer\Adapters\Concerns\StreamsLocalPath;
use App\Values\RequestedStreamingConfig;
class PhpStreamerAdapter extends LocalStreamerAdapter
{
use StreamsLocalPath;
public function stream(Song $song, ?RequestedStreamingConfig $config = null): void
{
$this->streamLocalPath($song->storage_metadata->getPath());
// For PHP streamer, we explicitly exit here to prevent the framework from sending additional headers
// and causing "headers already sent" errors (#2054).
exit;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Streamer/Adapters/TranscodingStreamerAdapter.php | app/Services/Streamer/Adapters/TranscodingStreamerAdapter.php | <?php
namespace App\Services\Streamer\Adapters;
use App\Models\Song;
use App\Services\Streamer\Adapters\Concerns\StreamsLocalPath;
use App\Services\Transcoding\TranscodeStrategyFactory;
use App\Values\RequestedStreamingConfig;
use Illuminate\Http\Response;
use Illuminate\Support\Str;
class TranscodingStreamerAdapter implements StreamerAdapter
{
use StreamsLocalPath;
public function stream(Song $song, ?RequestedStreamingConfig $config = null) // @phpcs:ignore
{
abort_unless(
is_executable(config('koel.streaming.ffmpeg_path')),
Response::HTTP_INTERNAL_SERVER_ERROR,
'ffmpeg not found or not executable.'
);
$bitRate = $config?->bitRate ?: config('koel.streaming.bitrate');
$transcodePath = TranscodeStrategyFactory::make($song->storage)->getTranscodeLocation($song, $bitRate);
if (Str::startsWith($transcodePath, ['http://', 'https://'])) {
return response()->redirectTo($transcodePath);
}
$this->streamLocalPath($transcodePath);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Streamer/Adapters/PodcastStreamerAdapter.php | app/Services/Streamer/Adapters/PodcastStreamerAdapter.php | <?php
namespace App\Services\Streamer\Adapters;
use App\Models\Song as Episode;
use App\Services\PodcastService;
use App\Services\Streamer\Adapters\Concerns\StreamsLocalPath;
use App\Values\Podcast\EpisodePlayable;
use App\Values\RequestedStreamingConfig;
use Webmozart\Assert\Assert;
class PodcastStreamerAdapter implements StreamerAdapter
{
use StreamsLocalPath;
public function __construct(private readonly PodcastService $podcastService)
{
}
/** @inheritDoc */
public function stream(Episode $song, ?RequestedStreamingConfig $config = null)
{
Assert::true($song->isEpisode());
$streamableUrl = $this->podcastService->getStreamableUrl($song);
if ($streamableUrl) {
return response()->redirectTo($streamableUrl);
}
$this->streamLocalPath(EpisodePlayable::getForEpisode($song)->path);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Streamer/Adapters/XAccelRedirectStreamerAdapter.php | app/Services/Streamer/Adapters/XAccelRedirectStreamerAdapter.php | <?php
namespace App\Services\Streamer\Adapters;
use App\Models\Setting;
use App\Models\Song;
use App\Values\RequestedStreamingConfig;
class XAccelRedirectStreamerAdapter extends LocalStreamerAdapter
{
/**
* Stream the current song using nginx's X-Accel-Redirect.
* @link https://www.nginx.com/resources/wiki/start/topics/examples/xsendfile/
*/
public function stream(Song $song, ?RequestedStreamingConfig $config = null): never
{
$path = $song->storage_metadata->getPath();
$contentType = 'audio/' . pathinfo($path, PATHINFO_EXTENSION);
$relativePath = str_replace(Setting::get('media_path'), '', $path);
// We send our media_path value as an 'X-Media-Root' header to downstream (nginx)
// It will then be used as `alias` in X-Accel config location block.
// See nginx.conf.example.
header('X-Media-Root: ' . Setting::get('media_path'));
header("X-Accel-Redirect: /media/$relativePath");
header("Content-Type: $contentType");
header('Content-Disposition: inline; filename="' . basename($path) . '"');
// prevent PHP from sending stray headers
exit;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Streamer/Adapters/StreamerAdapter.php | app/Services/Streamer/Adapters/StreamerAdapter.php | <?php
namespace App\Services\Streamer\Adapters;
use App\Models\Song;
use App\Values\RequestedStreamingConfig;
interface StreamerAdapter
{
public function stream(Song $song, ?RequestedStreamingConfig $config = null); // @phpcs:ignore
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Streamer/Adapters/Concerns/StreamsLocalPath.php | app/Services/Streamer/Adapters/Concerns/StreamsLocalPath.php | <?php
namespace App\Services\Streamer\Adapters\Concerns;
use DaveRandom\Resume\FileResource;
use DaveRandom\Resume\InvalidRangeHeaderException;
use DaveRandom\Resume\NonExistentFileException;
use DaveRandom\Resume\RangeSet;
use DaveRandom\Resume\ResourceServlet;
use DaveRandom\Resume\SendFileFailureException;
use DaveRandom\Resume\UnreadableFileException;
use DaveRandom\Resume\UnsatisfiableRangeException;
use Illuminate\Support\Facades\File;
use Symfony\Component\HttpFoundation\Response;
use function DaveRandom\Resume\get_request_header;
trait StreamsLocalPath
{
private function streamLocalPath(string $path): void
{
try {
$rangeHeader = get_request_header('Range');
// On Safari, the "Range" header value can be "bytes=0-1" which breaks streaming.
$rangeHeader = $rangeHeader === 'bytes=0-1' ? 'bytes=0-' : $rangeHeader;
$rangeSet = RangeSet::createFromHeader($rangeHeader);
$resource = new FileResource($path, File::mimeType($path));
(new ResourceServlet($resource))->sendResource($rangeSet);
} catch (InvalidRangeHeaderException) {
abort(Response::HTTP_BAD_REQUEST);
} catch (UnsatisfiableRangeException) {
abort(Response::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE);
} catch (NonExistentFileException) {
abort(Response::HTTP_NOT_FOUND);
} catch (UnreadableFileException) {
abort(Response::HTTP_INTERNAL_SERVER_ERROR);
} catch (SendFileFailureException $e) {
abort_unless(headers_sent(), Response::HTTP_INTERNAL_SERVER_ERROR);
echo "An error occurred while attempting to send the requested resource: {$e->getMessage()}";
}
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/License/CommunityLicenseService.php | app/Services/License/CommunityLicenseService.php | <?php
namespace App\Services\License;
use App\Exceptions\MethodNotImplementedException;
use App\Models\License;
use App\Services\License\Contracts\LicenseServiceInterface;
use App\Values\License\LicenseStatus;
class CommunityLicenseService implements LicenseServiceInterface
{
public function activate(string $key): License
{
throw MethodNotImplementedException::method(__METHOD__);
}
public function deactivate(License $license): void
{
throw MethodNotImplementedException::method(__METHOD__);
}
public function getStatus(bool $checkCache = true): LicenseStatus
{
throw MethodNotImplementedException::method(__METHOD__);
}
public function isPlus(): bool
{
return false;
}
public function isCommunity(): bool
{
return true;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/License/Contracts/LicenseServiceInterface.php | app/Services/License/Contracts/LicenseServiceInterface.php | <?php
namespace App\Services\License\Contracts;
use App\Models\License;
use App\Values\License\LicenseStatus;
interface LicenseServiceInterface
{
public function isPlus(): bool;
public function isCommunity(): bool;
public function activate(string $key): License;
public function deactivate(License $license): void;
public function getStatus(bool $checkCache = true): LicenseStatus;
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Contracts/ObjectStorageInterface.php | app/Services/Contracts/ObjectStorageInterface.php | <?php
namespace App\Services\Contracts;
use App\Models\Song;
interface ObjectStorageInterface
{
/**
* Get a song's Object Storage url for streaming or downloading.
*/
public function getSongPublicUrl(Song $song): string;
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Contracts/Encyclopedia.php | app/Services/Contracts/Encyclopedia.php | <?php
namespace App\Services\Contracts;
use App\Models\Album;
use App\Models\Artist;
use App\Values\Album\AlbumInformation;
use App\Values\Artist\ArtistInformation;
interface Encyclopedia
{
public function getArtistInformation(Artist $artist): ?ArtistInformation;
public function getAlbumInformation(Album $album): ?AlbumInformation;
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Geolocation/IPinfoService.php | app/Services/Geolocation/IPinfoService.php | <?php
namespace App\Services\Geolocation;
use App\Http\Integrations\IPinfo\IPinfoConnector;
use App\Http\Integrations\IPinfo\Requests\GetLiteDataRequest;
use App\Services\Geolocation\Contracts\GeolocationService;
use App\Values\IpInfoLiteData;
use Illuminate\Support\Facades\Cache;
class IPinfoService implements GeolocationService
{
public function __construct(private readonly IPinfoConnector $connector)
{
}
public static function used(): bool
{
return (bool) config('koel.services.ipinfo.token');
}
public function getCountryCodeFromIp(string $ip): ?string
{
if (!static::used()) {
return null;
}
return Cache::rememberForever(
cache_key('IP to country code', $ip),
function () use ($ip): string {
/** @var IpInfoLiteData $data */
$data = $this->connector->send(new GetLiteDataRequest($ip))->dto();
return $data->countryCode;
},
);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Geolocation/Contracts/GeolocationService.php | app/Services/Geolocation/Contracts/GeolocationService.php | <?php
namespace App\Services\Geolocation\Contracts;
interface GeolocationService
{
public function getCountryCodeFromIp(string $ip): ?string;
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Scanners/ScannerNoCacheStrategy.php | app/Services/Scanners/ScannerNoCacheStrategy.php | <?php
namespace App\Services\Scanners;
use App\Services\Scanners\Contracts\ScannerCacheStrategy;
use Closure;
class ScannerNoCacheStrategy implements ScannerCacheStrategy
{
public function remember(
string $key,
Closure $callback,
): mixed {
return $callback();
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Scanners/ScannerCacheStrategy.php | app/Services/Scanners/ScannerCacheStrategy.php | <?php
namespace App\Services\Scanners;
use App\Services\Scanners\Contracts\ScannerCacheStrategy as ScannerCacheStrategyContract;
use Closure;
use Illuminate\Support\Collection;
class ScannerCacheStrategy implements ScannerCacheStrategyContract
{
/** @var Collection<string, mixed> */
private Collection $cache;
public function __construct(private readonly int $maxCacheSize = 1000)
{
$this->cache = new Collection();
}
public function remember(string $key, Closure $callback): mixed
{
if ($this->cache->has($key)) {
return $this->cache->get($key);
}
if ($this->cache->count() >= $this->maxCacheSize) {
$this->cache->shift();
}
$result = $callback();
$this->cache->put($key, $result);
return $result;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Scanners/DirectoryScanner.php | app/Services/Scanners/DirectoryScanner.php | <?php
namespace App\Services\Scanners;
use App\Enums\ScanEvent;
use App\Events\MediaScanCompleted;
use App\Values\Scanning\ScanConfiguration;
use App\Values\Scanning\ScanResultCollection;
class DirectoryScanner extends Scanner
{
/** @var array<string, callable> */
private array $events = [];
public function scan(string $directory, ScanConfiguration $config): ScanResultCollection
{
self::setSystemRequirements();
$files = $this->gatherFiles($directory);
if (isset($this->events[ScanEvent::PATHS_GATHERED->name])) {
$this->events[ScanEvent::PATHS_GATHERED->name]($files);
}
$results = ScanResultCollection::create();
foreach ($files as $file) {
$result = $this->handleIndividualFile($file->getRealPath(), $config);
$results->add($result);
if (isset($this->events[ScanEvent::SCAN_PROGRESS->name])) {
$this->events[ScanEvent::SCAN_PROGRESS->name]($result);
}
}
event(new MediaScanCompleted($results));
return $results;
}
public function on(ScanEvent $event, callable $callback): void
{
$this->events[$event->name] = $callback;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Scanners/Scanner.php | app/Services/Scanners/Scanner.php | <?php
namespace App\Services\Scanners;
use App\Repositories\SongRepository;
use App\Services\SongService;
use App\Values\Scanning\ScanConfiguration;
use App\Values\Scanning\ScanResult;
use Illuminate\Support\Facades\File;
use Symfony\Component\Finder\Finder;
use Throwable;
abstract class Scanner
{
public function __construct(
protected SongService $songService,
protected SongRepository $songRepository,
protected FileScanner $fileScanner,
protected Finder $finder
) {
}
protected function handleIndividualFile(string $path, ScanConfiguration $config): ScanResult
{
try {
$song = $this->songRepository->findOneByPath($path);
// Use last modified time instead of hash to determine if the file is modified
// as calculating hash for every file is too time-consuming.
// See https://github.com/koel/koel/issues/2165.
if (!$config->force && $song && !$song->isFileModified(File::lastModified($path))) {
return ScanResult::skipped($path);
}
$info = $this->fileScanner->scan($path);
$this->songService->createOrUpdateSongFromScan($info, $config, $song);
return ScanResult::success($info->path);
} catch (Throwable $e) {
return ScanResult::error($path, $e->getMessage());
}
}
/**
* Gather all applicable files in a given directory.
*
* @param string $path The directory's full path
*/
protected function gatherFiles(string $path): Finder
{
$nameRegex = '/\.(' . implode('|', collect_accepted_audio_extensions()) . ')$/i';
return $this->finder::create()
->ignoreUnreadableDirs()
->ignoreDotFiles((bool) config('koel.ignore_dot_files')) // https://github.com/koel/koel/issues/450
->files()
->followLinks()
->name($nameRegex)
->in($path);
}
protected static function setSystemRequirements(): void
{
if (!app()->runningInConsole()) {
set_time_limit(config('koel.scan.timeout'));
}
if (config('koel.scan.memory_limit')) {
ini_set('memory_limit', config('koel.scan.memory_limit') . 'M');
}
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Scanners/FileScanner.php | app/Services/Scanners/FileScanner.php | <?php
namespace App\Services\Scanners;
use App\Services\SimpleLrcReader;
use App\Values\Scanning\ScanInformation;
use getID3;
use Illuminate\Support\Arr;
use RuntimeException;
use SplFileInfo;
class FileScanner
{
public function __construct(private readonly getID3 $getID3, private readonly SimpleLrcReader $lrcReader)
{
}
public function scan(string|SplFileInfo $path): ScanInformation
{
$file = $path instanceof SplFileInfo ? $path : new SplFileInfo($path);
$filePath = $file->getRealPath();
$raw = $this->getID3->analyze($filePath);
if (Arr::get($raw, 'playtime_seconds')) {
$syncError = Arr::get($raw, 'error.0') ?: (null);
} else {
$syncError = Arr::get($raw, 'error.0') ?: 'Empty file';
}
throw_if($syncError, new RuntimeException($syncError));
$this->getID3->CopyTagsToComments($raw);
return tap(
ScanInformation::fromGetId3Info($raw, $filePath),
function (ScanInformation $info) use ($filePath): void {
$info->lyrics = $info->lyrics ?: $this->lrcReader->tryReadForMediaFile($filePath);
}
);
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Scanners/WatchRecordScanner.php | app/Services/Scanners/WatchRecordScanner.php | <?php
namespace App\Services\Scanners;
use App\Models\Song;
use App\Values\Scanning\ScanConfiguration;
use App\Values\WatchRecord\Contracts\WatchRecordInterface;
use Illuminate\Support\Facades\Log;
use Throwable;
class WatchRecordScanner extends Scanner
{
public function scan(WatchRecordInterface $record, ScanConfiguration $config): void
{
self::setSystemRequirements();
Log::info("Scanning watch record: '{$record->getPath()}'");
if ($record->isFile()) {
$this->scanFileRecord($record, $config);
} else {
$this->scanDirectoryRecord($record, $config);
}
}
private function scanFileRecord(WatchRecordInterface $record, ScanConfiguration $config): void
{
$path = $record->getPath();
Log::info("'$path' is a file.");
if ($record->isDeleted()) {
$this->handleDeletedFileRecord($path);
} elseif ($record->isNewOrModified()) {
$this->handleNewOrModifiedFileRecord($path, $config);
}
}
private function scanDirectoryRecord(WatchRecordInterface $record, ScanConfiguration $config): void
{
$path = $record->getPath();
Log::info("'$path' is a directory.");
if ($record->isDeleted()) {
$this->handleDeletedDirectoryRecord($path);
} elseif ($record->isNewOrModified()) {
$this->handleNewOrModifiedDirectoryRecord($path, $config);
}
}
private function handleDeletedFileRecord(string $path): void
{
$result = $this->songRepository->findOneByPath($path)?->delete();
Log::info($result === null ? "$path deleted." : "$path doesn't exist in our database--skipping.");
}
private function handleNewOrModifiedFileRecord(string $path, ScanConfiguration $config): void
{
try {
$this->songService->createOrUpdateSongFromScan($this->fileScanner->scan($path), $config);
Log::info("Scanned $path");
} catch (Throwable $e) {
Log::warning("Failed to scan $path.", ['error' => $e]);
}
}
private function handleDeletedDirectoryRecord(string $path): void
{
$count = Song::query()->inDirectory($path)->delete();
if ($count) {
Log::info("Deleted $count song(s) under $path");
} else {
Log::info("$path is empty--no action needed.");
}
}
private function handleNewOrModifiedDirectoryRecord(string $path, ScanConfiguration $config): void
{
foreach ($this->gatherFiles($path) as $file) {
$this->handleIndividualFile($file->getPathname(), $config);
}
Log::info("Scanned all song(s) under $path");
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Services/Scanners/Contracts/ScannerCacheStrategy.php | app/Services/Scanners/Contracts/ScannerCacheStrategy.php | <?php
namespace App\Services\Scanners\Contracts;
use Closure;
interface ScannerCacheStrategy
{
public function remember(
string $key,
Closure $callback,
): mixed;
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Builders/ArtistBuilder.php | app/Builders/ArtistBuilder.php | <?php
namespace App\Builders;
use App\Builders\Concerns\CanScopeByUser;
use App\Facades\License;
use App\Models\Artist;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Facades\DB;
use LogicException;
use Webmozart\Assert\Assert;
class ArtistBuilder extends FavoriteableBuilder
{
use CanScopeByUser;
public const SORT_COLUMNS_NORMALIZE_MAP = [
'name' => 'artists.name',
'created_at' => 'artists.created_at',
];
private const VALID_SORT_COLUMNS = [
'artists.name',
'artists.created_at',
];
public function onlyStandard(): self
{
return $this->whereNotIn('artists.name', [Artist::UNKNOWN_NAME, Artist::VARIOUS_NAME]);
}
private function accessible(): self
{
if (License::isCommunity()) {
// With the Community license, all artists are accessible by all users.
return $this;
}
throw_unless($this->user, new LogicException('User must be set to query accessible artists.'));
if (!$this->user->preferences->includePublicMedia) {
// If the user does not want to include public media, we only return artists
// that belong to them.
return $this->whereBelongsTo($this->user);
}
// otherwise, we return artists that belong to the user or
// artists who have at least one public song owned by the user in the same organization.
return $this->where(function (Builder $query): void {
$query->whereBelongsTo($this->user)
->orWhereHas('songs', function (Builder $q): void {
$q->where('songs.is_public', true)
->whereHas('owner', function (Builder $owner): void {
$owner->where('organization_id', $this->user->organization_id)
->where('owner_id', '<>', $this->user->id);
});
});
});
}
private function withPlayCount(bool $includingFavoriteStatus = false): self
{
throw_unless($this->user, new LogicException('User must be set to query play counts.'));
$groupColumns = $includingFavoriteStatus
? ['artists.id', 'favorites.created_at']
: ['artists.id'];
// As we might have joined the `songs` table already, use an alias for the `songs` table
// in this join to avoid conflicts.
return $this->leftJoin('songs as songs_for_playcount', 'artists.id', 'songs_for_playcount.artist_id')
->join('interactions', function (JoinClause $join): void {
$join->on('interactions.song_id', 'songs_for_playcount.id')
->where('interactions.user_id', $this->user->id);
})
->groupBy($groupColumns)
->addSelect(DB::raw("SUM(interactions.play_count) as play_count"));
}
private static function normalizeSortColumn(string $column): string
{
return array_key_exists($column, self::SORT_COLUMNS_NORMALIZE_MAP)
? self::SORT_COLUMNS_NORMALIZE_MAP[$column]
: $column;
}
public function sort(string $column, string $direction): self
{
$column = self::normalizeSortColumn($column);
Assert::oneOf($column, self::VALID_SORT_COLUMNS);
Assert::oneOf(strtolower($direction), ['asc', 'desc']);
return $this->orderBy($column, $direction);
}
public function withUserContext(
User $user,
bool $includeFavoriteStatus = true,
bool $favoritesOnly = false,
bool $includePlayCount = false,
): self {
$this->user = $user;
return $this->accessible()
->when($includeFavoriteStatus, static fn (self $query) => $query->withFavoriteStatus($favoritesOnly))
->when($includePlayCount, static fn (self $query) => $query->withPlayCount($includeFavoriteStatus));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Builders/GenreBuilder.php | app/Builders/GenreBuilder.php | <?php
namespace App\Builders;
use App\Facades\License;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
class GenreBuilder extends Builder
{
public function accessibleBy(User $user): self
{
if (License::isCommunity()) {
// With the Community license, all genres are accessible by all users.
return $this;
}
return $this->whereHas('songs', static fn (SongBuilder $query) => $query->setScopedUser($user)->accessible()); //@phpstan-ignore-line
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Builders/FavoriteableBuilder.php | app/Builders/FavoriteableBuilder.php | <?php
namespace App\Builders;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Facades\DB;
/**
* @property ?User $user
*/
abstract class FavoriteableBuilder extends Builder
{
/**
* @param bool $favoritesOnly Whether to query the user's favorites only.
* If false (default), queries will return all records
* with a 'liked' column indicating whether the user has favorited each record.
*/
public function withFavoriteStatus(bool $favoritesOnly = false): static
{
$joinMethod = $favoritesOnly ? 'join' : 'leftJoin';
$this->$joinMethod('favorites', function (JoinClause $join): void {
$joinColumn = $this->model->getTable() . '.' . $this->model->getKeyName();
$join->on('favorites.favoriteable_id', $joinColumn)
->where('favorites.favoriteable_type', $this->getModel()->getMorphClass())
->where('favorites.user_id', $this->user->id);
});
$this->addSelect(DB::raw('CASE WHEN favorites.created_at IS NULL THEN false ELSE true END AS favorite'));
return $this;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Builders/AlbumBuilder.php | app/Builders/AlbumBuilder.php | <?php
namespace App\Builders;
use App\Builders\Concerns\CanScopeByUser;
use App\Facades\License;
use App\Models\Album;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Facades\DB;
use LogicException;
use Webmozart\Assert\Assert;
class AlbumBuilder extends FavoriteableBuilder
{
use CanScopeByUser;
public const SORT_COLUMNS_NORMALIZE_MAP = [
'name' => 'albums.name',
'year' => 'albums.year',
'created_at' => 'albums.created_at',
'artist_name' => 'albums.artist_name',
];
private const VALID_SORT_COLUMNS = [
'albums.name',
'albums.year',
'albums.created_at',
'albums.artist_name',
'favorite', // alias column for favorite status
];
public function onlyStandard(): self
{
return $this->whereNot('albums.name', Album::UNKNOWN_NAME);
}
private function accessible(): self
{
if (License::isCommunity()) {
// With the Community license, all albums are accessible by all users.
return $this;
}
throw_unless($this->user, new LogicException('User must be set to query accessible albums.'));
if (!$this->user->preferences->includePublicMedia) {
// If the user does not want to include public media, we only return albums
// that belong to them.
return $this->whereBelongsTo($this->user);
}
// otherwise, we return albums that belong to the user or
// albums that have at least one public song owned by the user in the same organization.
return $this->where(function (Builder $query): void {
$query->whereBelongsTo($this->user)
->orWhereHas('songs', function (Builder $q): void {
$q->where('songs.is_public', true)
->whereHas('owner', function (Builder $owner): void {
$owner->where('organization_id', $this->user->organization_id)
->where('owner_id', '<>', $this->user->id);
});
});
});
}
private function withPlayCount($includingFavoriteStatus = false): self
{
throw_unless($this->user, new LogicException('User must be set to query play counts.'));
$groupColumns = $includingFavoriteStatus
? ['albums.id', 'favorites.created_at']
: ['albums.id'];
// As we might have joined the `songs` table already, use an alias for the `songs` table
// in this join to avoid conflicts.
return $this->leftJoin('songs as songs_for_playcount', 'albums.id', 'songs_for_playcount.album_id')
->join('interactions', function (JoinClause $join): void {
$join->on('songs_for_playcount.id', 'interactions.song_id')
->where('interactions.user_id', $this->user->id);
})
->groupBy($groupColumns)
->addSelect(DB::raw("SUM(interactions.play_count) as play_count"));
}
public function withUserContext(
User $user,
bool $includeFavoriteStatus = true,
bool $favoritesOnly = false,
bool $includePlayCount = false,
): self {
$this->user = $user;
return $this->accessible()
->when($includeFavoriteStatus, static fn (self $query) => $query->withFavoriteStatus($favoritesOnly))
->when($includePlayCount, static fn (self $query) => $query->withPlayCount($includeFavoriteStatus));
}
private static function normalizeSortColumn(string $column): string
{
return array_key_exists($column, self::SORT_COLUMNS_NORMALIZE_MAP)
? self::SORT_COLUMNS_NORMALIZE_MAP[$column]
: $column;
}
public function sort(string $column, string $direction): self
{
$column = self::normalizeSortColumn($column);
Assert::oneOf($column, self::VALID_SORT_COLUMNS);
Assert::oneOf(strtolower($direction), ['asc', 'desc']);
return $this
->orderBy($column, $direction)
// Depending on the column, we might need to order by the album's name as well.
->when($column === 'albums.artist_name', static fn (self $query) => $query->orderBy('albums.name'))
->when($column === 'albums.year', static fn (self $query) => $query->orderBy('albums.name'))
->when($column === 'favorite', static fn (self $query) => $query->orderBy('albums.name'));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Builders/SongBuilder.php | app/Builders/SongBuilder.php | <?php
namespace App\Builders;
use App\Builders\Concerns\CanScopeByUser;
use App\Facades\License;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use LogicException;
use Webmozart\Assert\Assert;
class SongBuilder extends FavoriteableBuilder
{
use CanScopeByUser;
public const SORT_COLUMNS_NORMALIZE_MAP = [
'title' => 'songs.title',
'track' => 'songs.track',
'length' => 'songs.length',
'created_at' => 'songs.created_at',
'disc' => 'songs.disc',
'year' => 'songs.year',
'artist_name' => 'songs.artist_name',
'album_name' => 'songs.album_name',
'podcast_title' => 'podcasts.title',
'podcast_author' => 'podcasts.author',
'genre' => 'genres.name',
];
private const VALID_SORT_COLUMNS = [
'songs.title',
'songs.track',
'songs.length',
'songs.year',
'songs.created_at',
'songs.artist_name',
'songs.album_name',
'podcasts.title',
'podcasts.author',
'genres.name',
];
public function inDirectory(string $path): self
{
// Make sure the path ends with a directory separator.
$path = Str::finish(trim($path), DIRECTORY_SEPARATOR);
return $this->where('path', 'LIKE', "$path%");
}
private function withPlayCount(): self
{
throw_unless($this->user, new LogicException('User must be set to query play counts.'));
return $this
->leftJoin('interactions', function (JoinClause $join): void {
$join->on('interactions.song_id', 'songs.id')->where('interactions.user_id', $this->user->id);
})
->addSelect(DB::raw('COALESCE(interactions.play_count, 0) as play_count'));
}
public function accessible(): self
{
if (License::isCommunity()) {
// In the Community Edition, all songs are accessible by all users.
return $this;
}
throw_unless($this->user, new LogicException('User must be set to query accessible songs.'));
// We want to alias both podcasts and podcast_user tables to avoid possible conflicts with other joins.
$this->leftJoin('podcasts as podcasts_a11y', 'songs.podcast_id', 'podcasts_a11y.id')
->leftJoin('podcast_user as podcast_user_a11y', function (JoinClause $join): void {
$join->on('podcasts_a11y.id', 'podcast_user_a11y.podcast_id')
->where('podcast_user_a11y.user_id', $this->user->id);
})->whereNot(static function (self $query): void {
// Episodes must belong to a podcast that the user is subscribed to.
$query->whereNotNull('songs.podcast_id')->whereNull('podcast_user_a11y.podcast_id');
});
// If the song is a podcast episode, we need to ensure that the user has access to it.
return $this->where(function (self $query): void {
$query->whereNotNull('songs.podcast_id')
->orWhere(function (self $q2) {
// Depending on the user preferences, the song must be either:
// - owned by the user, or
// - shared (is_public=true) by the users in the same organization
if (!$this->user->preferences->includePublicMedia) {
return $q2->whereBelongsTo($this->user, 'owner');
}
return $q2->where(function (self $q3): void {
$q3->whereBelongsTo($this->user, 'owner')
->orWhere(function (self $q4): void {
$q4->where('songs.is_public', true)
->whereHas('owner', function (Builder $owner): void {
$owner->where('organization_id', $this->user->organization_id)
->where('owner_id', '<>', $this->user->id);
});
});
});
});
});
}
public function withUserContext(
bool $includeFavoriteStatus = true,
bool $favoritesOnly = false,
bool $includePlayCount = true,
): self {
return $this->accessible()
->when($includeFavoriteStatus, static fn (self $query) => $query->withFavoriteStatus($favoritesOnly))
->when($includePlayCount, static fn (self $query) => $query->withPlayCount());
}
private function sortByOneColumn(string $column, string $direction): self
{
$column = self::normalizeSortColumn($column);
Assert::oneOf($column, self::VALID_SORT_COLUMNS);
Assert::oneOf(strtolower($direction), ['asc', 'desc']);
return $this
->orderBy($column, $direction)
// Depending on the column, we might need to order by other columns as well.
->when($column === 'songs.artist_name', static fn (self $query) => $query->orderBy('songs.album_name')
->orderBy('songs.disc')
->orderBy('songs.track')
->orderBy('songs.title'))
->when($column === 'songs.album_name', static fn (self $query) => $query->orderBy('songs.artist_name')
->orderBy('songs.disc')
->orderBy('songs.track')
->orderBy('songs.title'))
->when($column === 'track', static fn (self $query) => $query->orderBy('songs.disc')
->orderBy('songs.track'));
}
public function sort(array $columns, string $direction): self
{
$this->when(
in_array('podcast_title', $columns, true) || in_array('podcast_author', $columns, true),
static fn (self $query) => $query->leftJoin('podcasts', 'songs.podcast_id', 'podcasts.id')
)->when(
in_array('genre', $columns, true),
static fn (self $query) => $query
->leftJoin('genre_song', 'songs.id', 'genre_song.song_id')
->leftJoin('genres', 'genre_song.genre_id', 'genres.id')
);
foreach ($columns as $column) {
$this->sortByOneColumn($column, $direction);
}
return $this;
}
private static function normalizeSortColumn(string $column): string
{
return array_key_exists($column, self::SORT_COLUMNS_NORMALIZE_MAP)
? self::SORT_COLUMNS_NORMALIZE_MAP[$column]
: $column;
}
public function storedOnCloud(): self
{
return $this->whereNotNull('storage')
->where('storage', '!=', '')
->whereNull('podcast_id');
}
public function storedLocally(): self
{
return $this->where(static function (self $query): void {
$query->whereNull('songs.storage')->orWhere('songs.storage', '')
->whereNull('songs.podcast_id');
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Builders/PodcastBuilder.php | app/Builders/PodcastBuilder.php | <?php
namespace App\Builders;
use App\Builders\Concerns\CanScopeByUser;
use Illuminate\Database\Query\JoinClause;
use LogicException;
class PodcastBuilder extends FavoriteableBuilder
{
use CanScopeByUser;
public function subscribed(): self
{
throw_if(!$this->user, new LogicException('User must be set to query subscribed podcasts.'));
return $this->join('podcast_user', function (JoinClause $join): void {
$join->on('podcasts.id', 'podcast_user.podcast_id')
->where('podcast_user.user_id', $this->user->id);
});
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Builders/UserBuilder.php | app/Builders/UserBuilder.php | <?php
namespace App\Builders;
use App\Enums\Acl\Role as RoleEnum;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection as BaseCollection;
/**
* @method Builder whereRole(RoleEnum|string|array|BaseCollection $roles) Scope the model query to certain roles only.
*/
class UserBuilder extends Builder
{
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Builders/RadioStationBuilder.php | app/Builders/RadioStationBuilder.php | <?php
namespace App\Builders;
use App\Builders\Concerns\CanScopeByUser;
use App\Models\User;
use LogicException;
class RadioStationBuilder extends FavoriteableBuilder
{
use CanScopeByUser;
private function accessible(): self
{
throw_unless($this->user, new LogicException('User must be set to query accessible radio stations.'));
if (!$this->user->preferences->includePublicMedia) {
// If the user does not want to include public media, we only return stations created by them.
return $this->whereBelongsTo($this->user);
}
// otherwise, we return stations that are created by the user in the same organization.
return $this->join('users', 'users.id', '=', 'radio_stations.user_id')
->join('organizations', 'organizations.id', '=', 'users.organization_id')
->where(function (self $builder): void {
$builder->where('radio_stations.user_id', $this->user->id)
->orWhere(function (self $query): void {
$query->where('radio_stations.is_public', true)
->where('organizations.id', $this->user->organization_id);
});
});
}
public function withUserContext(
User $user,
bool $includeFavoriteStatus = true,
bool $favoritesOnly = false,
): self {
$this->user = $user;
return $this->accessible()
->when($includeFavoriteStatus, static fn (self $query) => $query->withFavoriteStatus($favoritesOnly));
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Builders/Concerns/CanScopeByUser.php | app/Builders/Concerns/CanScopeByUser.php | <?php
namespace App\Builders\Concerns;
use App\Models\User;
trait CanScopeByUser
{
protected ?User $user = null;
public function setScopedUser(User $user): static
{
$this->user = $user;
return $this;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Facades/Util.php | app/Facades/Util.php | <?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @method static string detectUTFEncoding(string $name)
*/
class Util extends Facade
{
protected static function getFacadeAccessor(): string
{
return 'Util';
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Facades/YouTube.php | app/Facades/YouTube.php | <?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @method static bool enabled()
*/
class YouTube extends Facade
{
protected static function getFacadeAccessor(): string
{
return 'YouTube';
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Facades/Dispatcher.php | app/Facades/Dispatcher.php | <?php
namespace App\Facades;
use App\Jobs\QueuedJob;
use Illuminate\Support\Facades\Facade;
/**
* @method static mixed dispatch(QueuedJob $job)
* @see \App\Services\Dispatcher
*/
class Dispatcher extends Facade
{
protected static function getFacadeAccessor(): string
{
return 'Dispatcher';
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Facades/ITunes.php | app/Facades/ITunes.php | <?php
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @method static bool used()
*/
class ITunes extends Facade
{
protected static function getFacadeAccessor(): string
{
return 'iTunes';
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Facades/License.php | app/Facades/License.php | <?php
namespace App\Facades;
use App\Exceptions\KoelPlusRequiredException;
use Illuminate\Support\Facades\Facade;
/**
* @method static bool isPlus()
* @method static bool isCommunity()
* @see \App\Services\LicenseService
*/
class License extends Facade
{
public static function requirePlus(): void
{
throw_unless(static::isPlus(), KoelPlusRequiredException::class);
}
protected static function getFacadeAccessor(): string
{
return 'License';
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Facades/Download.php | app/Facades/Download.php | <?php
namespace App\Facades;
use App\Models\Song;
use Illuminate\Support\Facades\Facade;
/**
* @method static string getLocalPath(Song $song)
* @see \App\Services\DownloadService
*/
class Download extends Facade
{
protected static function getFacadeAccessor(): string
{
return 'Download';
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/DoctorCommand.php | app/Console/Commands/DoctorCommand.php | <?php
namespace App\Console\Commands;
use App\Enums\DoctorResult;
use App\Enums\SongStorageType;
use App\Facades\License;
use App\Helpers\Ulid;
use App\Http\Integrations\Lastfm\LastfmConnector;
use App\Http\Integrations\Lastfm\Requests\GetArtistInfoRequest;
use App\Http\Integrations\Spotify\SpotifyClient;
use App\Http\Integrations\YouTube\Requests\SearchVideosRequest;
use App\Http\Integrations\YouTube\YouTubeConnector;
use App\Models\Artist;
use App\Models\Setting;
use App\Models\Song;
use App\Models\User;
use App\Services\LastfmService;
use App\Services\SongStorages\SongStorage;
use App\Services\SpotifyService;
use App\Services\YouTubeService;
use Closure;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use InvalidArgumentException;
use Throwable;
use TiBeN\CrontabManager\CrontabAdapter;
use TiBeN\CrontabManager\CrontabRepository;
class DoctorCommand extends Command
{
protected $signature = 'koel:doctor';
protected $description = 'Check Koel setup';
private array $errors = [];
public function handle(): int
{
if (PHP_OS_FAMILY === 'Windows' || PHP_OS_FAMILY === 'Unknown') {
$this->components->error('This command is only available on Linux systems.');
return self::FAILURE;
}
$this->components->alert('Checking Koel setup...');
$this->line('');
if (exec('whoami') === 'root') {
$this->components->error('This command cannot be run as root.');
return self::FAILURE;
}
$this->checkDirectoryPermissions();
if ($this->checkDatabaseConnection() === DoctorResult::SUCCESS) {
$this->checkMediaStorage();
} else {
$this->reportWarning('Storage type.', 'UNKNOWN');
}
$this->checkFullTextSearch();
$this->checkApiHealth();
$this->checkFFMpeg();
$this->checkPhpExtensions();
$this->checkPhpConfiguration();
$this->checkStreamingMethod();
$this->checkServiceIntegrations();
$this->checkMailConfiguration();
$this->checkScheduler();
$this->checkPlusLicense();
if ($this->errors) {
$this->reportErroneousResult();
} else {
$this->output->success('Your Koel setup should be good to go!');
}
return self::SUCCESS;
}
private function reportErroneousResult(): void
{
$this->components->error('There are errors in your Koel setup. Koel will not work properly.');
if (File::isWritable(base_path('storage/logs/laravel.log'))) {
/** @var Throwable $error */
foreach ($this->errors as $error) {
Log::error('[KOEL.DOCTOR] ' . $error->getMessage(), ['error' => $error]);
}
$this->components->error('You can find more details in ' . base_path('storage/logs/laravel.log'));
} else {
$this->components->error('The list of errors is as follows:');
/** @var Throwable $error */
foreach ($this->errors as $i => $error) {
$this->line(" <error>[$i]</error> " . $error->getMessage());
}
}
}
private function checkPlusLicense(): void
{
try {
$status = License::getStatus(checkCache: false);
if ($status->hasNoLicense()) {
$this->reportInfo('Koel Plus license status', 'Not available');
return;
}
if ($status->isValid()) {
$this->reportSuccess('Koel Plus license status', 'Active');
} else {
$this->reportError('Koel Plus license status', 'Invalid');
}
} catch (Throwable $e) {
$this->collectError($e);
$this->reportWarning('Cannot check for Koel Plus license status');
}
}
private function checkScheduler(): void
{
$crontab = new CrontabRepository(new CrontabAdapter());
if (InstallSchedulerCommand::schedulerInstalled($crontab)) {
$this->reportSuccess('Koel scheduler status', 'Installed');
} else {
$this->reportWarning('Koel scheduler status', 'Not installed');
}
}
private function checkMailConfiguration(): void
{
if (!config('mail.default') || config('mail.default') === 'log') {
$this->reportWarning('Mailer configuration', 'Not available');
return;
}
$recipient = Ulid::generate() . '@mailinator.com';
try {
Mail::raw('This is a test email.', static fn (Message $message) => $message->to($recipient));
$this->reportSuccess('Mailer configuration');
} catch (Throwable $e) {
$this->collectError($e);
$this->reportError('Mailer configuration');
}
}
private function checkServiceIntegrations(): void
{
if (!LastfmService::enabled()) {
$this->reportWarning('Last.fm integration', 'Not available');
} else {
/** @var LastfmConnector $connector */
$connector = app(LastfmConnector::class);
/** @var Artist $artist */
$artist = Artist::factory()->make(['name' => 'Pink Floyd']);
try {
$dto = $connector->send(new GetArtistInfoRequest($artist))->dto();
if (!$dto) {
throw new Exception('No data returned.');
}
$this->reportSuccess('Last.fm integration');
} catch (Throwable $e) {
$this->collectError($e);
$this->reportError('Last.fm integration');
}
}
if (!YouTubeService::enabled()) {
$this->reportWarning('YouTube integration', 'Not available');
} else {
/** @var YouTubeConnector $connector */
$connector = app(YouTubeConnector::class);
/** @var Song $artist */
$song = Song::factory()->forArtist(['name' => 'Pink Floyd'])->make(['title' => 'Comfortably Numb']); // @phpstan-ignore-line
try {
$object = $connector->send(new SearchVideosRequest($song))->object();
if (object_get($object, 'error')) {
throw new Exception(object_get($object, 'error.message'));
}
$this->reportSuccess('YouTube integration');
} catch (Throwable $e) {
$this->collectError($e);
$this->reportError('YouTube integration');
}
}
if (!SpotifyService::enabled()) {
$this->reportWarning('Spotify integration', 'Not available');
} else {
/** @var SpotifyService $service */
$service = app(SpotifyService::class);
Cache::forget(SpotifyClient::ACCESS_TOKEN_CACHE_KEY);
try {
/** @var Artist $artist */
$artist = Artist::factory()->make([
'id' => 999,
'name' => 'Pink Floyd',
]);
$image = $service->tryGetArtistImage($artist);
if (!$image) {
throw new Exception('No result returned.');
}
$this->reportSuccess('Spotify integration');
} catch (Throwable $e) {
$this->collectError($e);
$this->reportError('Spotify integration');
}
}
}
private function checkStreamingMethod(): void
{
$this->reportInfo('Streaming method', config('koel.streaming.method'));
}
private function checkPhpConfiguration(): void
{
$this->reportInfo('Max upload size', ini_get('upload_max_filesize'));
$this->reportInfo('Max post size', ini_get('post_max_size'));
}
private function checkPhpExtensions(): void
{
$this->assert(
condition: extension_loaded('zip'),
success: 'PHP extension <info>zip</info> is loaded. Multi-file downloading is supported.',
warning: 'PHP extension <info>zip</info> is not loaded. Multi-file downloading will not be available.',
);
// as "gd" and "SimpleXML" are both required in the composer.json file, we don't need to check for them
}
private function checkFFMpeg(): void
{
$ffmpegPath = config('koel.streaming.ffmpeg_path');
if ($ffmpegPath) {
$this->assert(
condition: File::exists($ffmpegPath) && is_executable($ffmpegPath),
success: "FFmpeg binary <info>$ffmpegPath</info> is executable.",
warning: "FFmpeg binary <info>$ffmpegPath</info> does not exist or is not executable. "
. 'Transcoding will not be available.',
);
} else {
$this->reportWarning('FFmpeg path is not set. Transcoding will not be available.');
}
}
private function checkApiHealth(): void
{
try {
Http::get(config('app.url') . '/api/ping');
$this->reportSuccess('API is healthy');
} catch (Throwable $e) {
$this->collectError($e);
$this->reportError('API is healthy');
}
}
private function checkFullTextSearch(): void
{
if (config('scout.driver') === 'tntsearch') {
$this->assertDirectoryPermissions(base_path('storage/search-indexes'), 'TNT search index');
return;
}
if (config('scout.driver') === 'algolia') {
try {
Song::search('foo')->raw();
$this->reportSuccess('Full-text search (using Algolia)');
} catch (Throwable $e) {
$this->collectError($e);
$this->reportError('Full-text search (using Algolia)');
}
}
}
private function checkDatabaseConnection(): DoctorResult
{
try {
User::query()->count('id');
$this->reportSuccess('Checking database connection');
return DoctorResult::SUCCESS;
} catch (Throwable $e) {
$this->collectError($e);
$this->reportError('Checking database connection');
return DoctorResult::ERROR;
}
}
private function checkMediaStorage(): void
{
/** @var SongStorage $storage */
$storage = app(SongStorage::class);
$name = $storage->getStorageType()->value ?: 'local';
if (!$storage->getStorageType()->supported()) {
$this->reportError("Media storage driver <info>$name</info>", 'Not supported');
return;
}
if ($storage->getStorageType() === SongStorageType::LOCAL && !Setting::get('media_path')) {
$this->reportWarning('Media path', 'Not set');
return;
}
try {
$storage->testSetup();
$this->reportSuccess("Media storage setup (<info>$name</info>)");
} catch (Throwable $e) {
$this->collectError($e);
$this->reportError("Media storage setup (<info>$name</info>)");
}
}
private function checkDirectoryPermissions(): void
{
$this->assertDirectoryPermissions(artifact_path(), 'Artifacts');
$this->assertDirectoryPermissions(base_path('storage/framework/sessions'), 'Session');
$this->assertDirectoryPermissions(base_path('storage/framework/cache'), 'Cache');
$this->assertDirectoryPermissions(base_path('storage/logs'), 'Log');
}
private function reportError(string $message, ?string $value = 'ERROR'): void
{
$this->components->twoColumnDetail($message, "<error>$value</error>");
}
private function reportSuccess(string $message, ?string $value = 'OK'): void
{
$this->components->twoColumnDetail($message, "<info>$value</info>");
}
private function reportWarning(string $message, ?string $second = 'WARNING'): void
{
$this->components->twoColumnDetail($message, "<comment>$second</comment>");
}
private function reportInfo(string $message, ?string $value = null): void
{
$this->components->twoColumnDetail($message, $value);
}
private function assertDirectoryPermissions(string $path, string $name): void
{
$this->assert(
condition: File::isReadable($path) && File::isWritable($path),
success: "$name directory <info>$path</info> is readable/writable.",
error: "$name directory <info>$path</info> is not readable/writable.",
);
}
private function assert(
Closure|bool $condition,
Closure|string|null $success = null,
Closure|string|null $error = null,
Closure|string|null $warning = null,
): void {
$result = value($condition);
if ($result) {
$this->reportSuccess(value($success));
return;
}
if ($error && $warning) {
throw new InvalidArgumentException('Cannot have both error and warning.');
}
if ($error) {
$this->reportError(value($error));
} else {
$this->reportWarning(value($warning));
}
}
private function collectError(Throwable $e): void
{
$this->errors[] = $e;
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
koel/koel | https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/InstallSchedulerCommand.php | app/Console/Commands/InstallSchedulerCommand.php | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use TiBeN\CrontabManager\CrontabAdapter;
use TiBeN\CrontabManager\CrontabJob;
use TiBeN\CrontabManager\CrontabRepository;
class InstallSchedulerCommand extends Command
{
protected $signature = 'koel:scheduler:install';
protected $description = 'Install the scheduler for Koel';
public function handle(): int
{
if (PHP_OS_FAMILY === 'Windows' || PHP_OS_FAMILY === 'Unknown') {
$this->components->error('This command is only available on Linux systems.');
return self::FAILURE;
}
$crontab = new CrontabRepository(new CrontabAdapter());
$this->components->info('Trying to install Koel scheduler…');
if (self::schedulerInstalled($crontab)) {
$this->components->info('Koel scheduler is already installed. Skipping…');
return self::SUCCESS;
}
$job = CrontabJob::createFromCrontabLine(
'* * * * * cd ' . base_path() . ' && php artisan schedule:run >> /dev/null 2>&1'
);
$crontab->addJob($job);
$crontab->persist();
$this->components->info('Koel scheduler installed successfully.');
return self::SUCCESS;
}
public static function schedulerInstalled(CrontabRepository $crontab): bool
{
return (bool) $crontab->findJobByRegex('/artisan schedule:run/');
}
}
| php | MIT | add9401a4b9a904bb1b9f679bc674ad1570ff20e | 2026-01-04T15:02:34.446708Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.