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/Console/Commands/TidyLibraryCommand.php
app/Console/Commands/TidyLibraryCommand.php
<?php namespace App\Console\Commands; use Illuminate\Console\Command; class TidyLibraryCommand extends Command { protected $signature = 'koel:tidy'; protected $hidden = true; public function handle(): int { $this->warn('koel:tidy has been renamed. Use koel:prune instead.'); return self::SUCCESS; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/DeactivateLicenseCommand.php
app/Console/Commands/DeactivateLicenseCommand.php
<?php namespace App\Console\Commands; use App\Services\License\Contracts\LicenseServiceInterface; use Illuminate\Console\Command; use Throwable; class DeactivateLicenseCommand extends Command { protected $signature = 'koel:license:deactivate'; protected $description = 'Deactivate the currently active Koel Plus license'; public function __construct(private readonly LicenseServiceInterface $licenseService) { parent::__construct(); } public function handle(): int { $status = $this->licenseService->getStatus(); if ($status->hasNoLicense()) { $this->components->warn('No active Plus license found.'); return self::SUCCESS; } if (!$this->confirm('Are you sure you want to deactivate your Koel Plus license?')) { $this->output->warning('License deactivation aborted.'); return self::SUCCESS; } $this->components->info('Deactivating your license…'); try { $this->licenseService->deactivate($status->license); $this->components->info('Koel Plus has been deactivated. Plus features are now disabled.'); return self::SUCCESS; } catch (Throwable $e) { $this->components->error('Failed to deactivate Koel Plus: ' . $e->getMessage()); return self::FAILURE; } } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/CollectTagsCommand.php
app/Console/Commands/CollectTagsCommand.php
<?php namespace App\Console\Commands; use App\Models\Song; use Illuminate\Console\Command; class CollectTagsCommand extends Command { protected $signature = 'koel:tags:collect {tag*}'; protected $description = 'Collect additional tags from existing songs'; private const ALL_TAGS = [ 'title', 'album', 'artist', 'albumartist', 'track', 'disc', 'year', 'genre', 'lyrics', 'cover', ]; private const COLLECTABLE_TAGS = ['year', 'genre']; public function handle(): int { if (config('koel.storage_driver') !== 'local') { $this->components->error('This command only works with the local storage driver.'); return self::INVALID; } $tags = collect($this->argument('tag'))->unique(); if ($tags->diff(self::COLLECTABLE_TAGS)->isNotEmpty()) { $this->error( sprintf( 'Invalid tag(s): %s. Allowed tags are: %s.', $tags->diff(self::COLLECTABLE_TAGS)->join(', '), implode(', ', self::COLLECTABLE_TAGS) ) ); return self::FAILURE; } Song::withoutSyncingToSearch(function () use ($tags): void { $this->call('koel:sync', [ '--force' => true, '--ignore' => collect(self::ALL_TAGS)->diff($tags)->all(), ]); }); return self::SUCCESS; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/ActivateLicenseCommand.php
app/Console/Commands/ActivateLicenseCommand.php
<?php namespace App\Console\Commands; use App\Services\License\Contracts\LicenseServiceInterface; use Illuminate\Console\Command; use Throwable; class ActivateLicenseCommand extends Command { protected $signature = 'koel:license:activate {key : The license key to activate.}'; protected $description = 'Activate a Koel Plus license'; public function __construct(private readonly LicenseServiceInterface $licenseService) { parent::__construct(); } public function handle(): int { $this->components->info('Activating license…'); try { $license = $this->licenseService->activate($this->argument('key')); } catch (Throwable $e) { $this->components->error($e->getMessage()); return self::FAILURE; } $this->output->success('Koel Plus activated! All Plus features are now available.'); $this->components->twoColumnDetail('License Key', $license->short_key); $this->components->twoColumnDetail( 'Registered To', "{$license->meta->customerName} <{$license->meta->customerEmail}>" ); $this->components->twoColumnDetail('Expires On', 'Never ever'); $this->newLine(); return self::SUCCESS; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/ScanCommand.php
app/Console/Commands/ScanCommand.php
<?php namespace App\Console\Commands; use App\Enums\ScanEvent; use App\Models\Setting; use App\Models\User; use App\Services\Scanners\DirectoryScanner; use App\Services\Scanners\WatchRecordScanner; use App\Values\Scanning\ScanConfiguration; use App\Values\Scanning\ScanResult; use App\Values\WatchRecord\InotifyWatchRecord; use Illuminate\Console\Command; use Illuminate\Support\Facades\File; use Illuminate\Support\Str; use RuntimeException; use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Finder\Finder; class ScanCommand extends Command { protected $signature = 'koel:scan {record? : A single watch record. Consult Wiki for more info.} {--O|owner= : The ID of the user who should own the newly scanned songs. Defaults to the first admin user.} {--P|private : Whether to make the newly scanned songs private to the user.} {--V|verbose : Show more details about the scanning process {--I|ignore=* : The comma-separated tags to ignore (exclude) from scanning} {--F|force : Force re-scanning even unchanged files}'; protected $description = 'Scan for songs in the configured directory.'; private string $mediaPath; private ProgressBar $progressBar; public function __construct( private readonly DirectoryScanner $directoryScanner, private readonly WatchRecordScanner $watchRecordScanner, ) { parent::__construct(); } protected function configure(): void { parent::configure(); $this->setAliases(['koel:sync']); } public function handle(): int { if (config('koel.storage_driver') !== 'local') { $this->components->error('This command only works with the local storage driver.'); return self::INVALID; } $this->mediaPath = $this->getMediaPath(); $config = ScanConfiguration::make( owner: $this->getOwner(), // When scanning via CLI, the songs should be public by default, unless explicitly specified otherwise. makePublic: !$this->option('private'), ignores: collect($this->option('ignore'))->sort()->values()->all(), force: $this->option('force') ); $record = $this->argument('record'); if ($record) { $this->scanSingleRecord($record, $config); } else { $this->scanMediaPath($config); } return self::SUCCESS; } /** * Scan all files in the configured media path. */ private function scanMediaPath(ScanConfiguration $config): void { $this->directoryScanner->on(ScanEvent::PATHS_GATHERED, function (Finder $files): void { $this->progressBar = new ProgressBar($this->output, $files->count()); }); $this->directoryScanner->on(ScanEvent::SCAN_PROGRESS, [$this, 'onScanProgress']); $this->components->info('Scanning ' . $this->mediaPath); if ($config->ignores) { $this->components->info('Ignoring tag(s): ' . implode(', ', $config->ignores)); } $results = $this->directoryScanner->scan((string) Setting::get('media_path'), $config); $this->newLine(2); $this->components->info('Scanning completed!'); $this->components->bulletList([ "<fg=green>{$results->success()->count()}</> new or updated song(s)", "<fg=yellow>{$results->skipped()->count()}</> unchanged song(s)", "<fg=red>{$results->error()->count()}</> invalid file(s)", ]); } /** * @param string $record The watch record. * As of current, we only support inotifywait. * Some examples: * - "DELETE /var/www/media/gone.mp3" * - "CLOSE_WRITE,CLOSE /var/www/media/new.mp3" * - "MOVED_TO /var/www/media/new_dir" * * @see http://man7.org/linux/man-pages/man1/inotifywait.1.html */ private function scanSingleRecord(string $record, ScanConfiguration $config): void { $this->watchRecordScanner->scan(new InotifyWatchRecord($record), $config); } public function onScanProgress(ScanResult $result): void { if (!$this->option('verbose')) { $this->progressBar->advance(); return; } $path = trim(Str::replaceFirst($this->mediaPath, '', $result->path), DIRECTORY_SEPARATOR); $this->components->twoColumnDetail($path, match (true) { $result->isSuccess() => "<fg=green>OK</>", $result->isSkipped() => "<fg=yellow>SKIPPED</>", $result->isError() => "<fg=red>ERROR</>", default => throw new RuntimeException("Unknown scan result type: {$result->type->value}") }); if ($result->isError()) { $this->output->writeln("<fg=red>$result->error</>"); } } private function getMediaPath(): string { $path = Setting::get('media_path'); if ($path) { return $path; } $this->warn("Media path hasn't been configured. Let's set it up."); while (true) { $path = $this->ask('Absolute path to your media directory'); if (File::isDirectory($path) && File::isReadable($path)) { Setting::set('media_path', $path); break; } $this->error('The path does not exist or is not readable. Try again.'); } return $path; } private function getOwner(): User { $specifiedOwner = $this->option('owner'); if ($specifiedOwner) { $user = User::query()->findOr($specifiedOwner, function () use ($specifiedOwner): never { $this->components->error("User with ID $specifiedOwner does not exist."); exit(self::INVALID); }); $this->components->info("Setting owner to $user->name (ID {$user->id})."); return $user; } $user = User::firstAdmin(); $this->components->warn( "No song owner specified. Setting the first admin ($user->name, ID {$user->id}) as owner." ); return $user; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/FetchArtworkCommand.php
app/Console/Commands/FetchArtworkCommand.php
<?php namespace App\Console\Commands; use App\Builders\AlbumBuilder; use App\Builders\ArtistBuilder; use App\Models\Album; use App\Models\Artist; use App\Services\EncyclopediaService; use App\Services\MusicBrainzService; use App\Services\SpotifyService; use Illuminate\Console\Command; use Illuminate\Support\Facades\Cache; class FetchArtworkCommand extends Command { /** * Time to sleep between requests in second to avoid hitting the possible rate limit. */ private const INTERVAL = 1; protected $signature = 'koel:fetch-artwork'; protected $description = 'Attempt to fetch artist and album artworks from available sources.'; public function __construct(private readonly EncyclopediaService $encyclopedia) { parent::__construct(); } public function handle(): int { if (!SpotifyService::enabled() && !MusicBrainzService::enabled()) { $this->components->error('Please configure Spotify and/or MusicBrainz integration first.'); return self::FAILURE; } $this->components->info('Fetching artist images...'); Artist::query() ->whereNotIn('name', [Artist::UNKNOWN_NAME, Artist::VARIOUS_NAME]) ->where(static fn (ArtistBuilder $query) => $query->whereNull('image')->orWhere('image', '')) ->orderBy('name') ->lazy() ->each(function (Artist $artist): void { Cache::forget(cache_key('artist information', $artist->name)); $this->encyclopedia->getArtistInformation($artist); $status = $artist->image ? '<info>OK</info>' : '<error>Failed</error>'; $this->components->twoColumnDetail($artist->name, $status); sleep(self::INTERVAL); }); $this->components->info('Fetching album covers...'); Album::query() ->whereNot('name', Album::UNKNOWN_NAME) ->whereNotIn('artist_name', [Artist::UNKNOWN_NAME, Artist::VARIOUS_NAME]) ->where(static fn (AlbumBuilder $query) => $query->whereNull('cover')->orWhere('cover', '')) ->orderBy('name') ->lazy() ->each(function (Album $album): void { Cache::forget(cache_key('album information', $album->name)); $this->encyclopedia->getAlbumInformation($album); $status = $album->cover ? '<info>OK</info>' : '<error>Failed</error>'; $this->components->twoColumnDetail($album->name . ' - ' . $album->artist_name, $status); sleep(self::INTERVAL); }); $this->components->success('All done!'); return self::SUCCESS; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/SyncPodcastsCommand.php
app/Console/Commands/SyncPodcastsCommand.php
<?php namespace App\Console\Commands; use App\Models\Podcast; use App\Services\PodcastService; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; use Throwable; class SyncPodcastsCommand extends Command { protected $signature = 'koel:podcasts:sync'; protected $description = 'Synchronize podcasts.'; public function __construct(private readonly PodcastService $podcastService) { parent::__construct(); } public function handle(): int { Podcast::query()->get()->each(function (Podcast $podcast): void { try { $this->info("Checking \"$podcast->title\" for new content…"); if (!$this->podcastService->isPodcastObsolete($podcast)) { $this->warn('└── The podcast feed has not been updated recently, skipping.'); return; } $this->info('└── Synchronizing episodes…'); $this->podcastService->refreshPodcast($podcast); } catch (Throwable $e) { Log::error($e); } }); return self::SUCCESS; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/ImportSearchableEntitiesCommand.php
app/Console/Commands/ImportSearchableEntitiesCommand.php
<?php namespace App\Console\Commands; use App\Models\Album; use App\Models\Artist; use App\Models\Playlist; use App\Models\Podcast; use App\Models\Song; use Illuminate\Console\Command; class ImportSearchableEntitiesCommand extends Command { private const SEARCHABLE_ENTITIES = [ Song::class, Album::class, Artist::class, Playlist::class, Podcast::class, ]; protected $signature = 'koel:search:import'; protected $description = 'Import all searchable entities with Scout'; public function handle(): int { foreach (self::SEARCHABLE_ENTITIES as $entity) { $this->call('scout:import', ['model' => $entity]); } return self::SUCCESS; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/CheckLicenseStatusCommand.php
app/Console/Commands/CheckLicenseStatusCommand.php
<?php namespace App\Console\Commands; use App\Enums\LicenseStatus; use App\Models\License; use App\Services\License\Contracts\LicenseServiceInterface; use Illuminate\Console\Command; use Throwable; class CheckLicenseStatusCommand extends Command { protected $signature = 'koel:license:status'; protected $description = 'Check the current Koel Plus license status'; public function __construct(private readonly LicenseServiceInterface $licenseService) { parent::__construct(); } public function handle(): int { $this->components->info('Checking your Koel Plus license status…'); if (License::count() > 1) { $this->components->warn('Multiple licenses found. This can cause unexpected behaviors.'); } try { $status = $this->licenseService->getStatus(checkCache: false); switch ($status->status) { case LicenseStatus::VALID: $this->output->success('You have a valid Koel Plus license. All Plus features are enabled.'); $this->components->twoColumnDetail('License Key', $status->license->short_key); $this->components->twoColumnDetail( 'Registered To', "{$status->license->meta->customerName} <{$status->license->meta->customerEmail}>" ); $this->components->twoColumnDetail('Expires On', 'Never ever'); $this->newLine(); break; case LicenseStatus::NO_LICENSE: $this->components->info( 'No license found. You can purchase one at https://store.koel.dev' . config('lemonsqueezy.plus_product_id') ); break; case LicenseStatus::INVALID: $this->components->error('Your license is invalid. Plus features will not be available.'); break; default: $this->components->warn('Your license status is unknown. Please try again later.'); } } catch (Throwable $e) { $this->output->error($e->getMessage()); } return self::SUCCESS; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/PruneLibraryCommand.php
app/Console/Commands/PruneLibraryCommand.php
<?php namespace App\Console\Commands; use App\Services\LibraryManager; use Illuminate\Console\Command; class PruneLibraryCommand extends Command { protected $signature = 'koel:prune {--dry-run}'; protected $description = 'Remove empty artists and albums'; public function __construct(private readonly LibraryManager $libraryManager) { parent::__construct(); } public function handle(): int { $dryRun = $this->option('dry-run'); $results = $this->libraryManager->prune($dryRun); if ($dryRun) { $this->info('Dry run: no changes made.'); $this->info( "Found {$results['artists']->count()} empty artist(s) and {$results['albums']->count()} empty album(s)." ); foreach ($results['artists'] as $result) { $this->line("Artist: {$result->name} (ID: {$result->id})"); } foreach ($results['albums'] as $result) { $this->line("Album: {$result->name} (ID: {$result->id}})"); } return self::SUCCESS; } $this->info("{$results['artists']->count()} empty artist(s) and {$results['albums']->count()} albums removed."); return self::SUCCESS; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/ReleaseCommand.php
app/Console/Commands/ReleaseCommand.php
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Process; use PHLAK\SemVer\Version; use Throwable; use function Laravel\Prompts\error; use function Laravel\Prompts\info; use function Laravel\Prompts\note; use function Laravel\Prompts\select; use function Laravel\Prompts\text; use function Laravel\Prompts\warning; class ReleaseCommand extends Command { protected $signature = 'koel:release {version? : The version to release, or "patch", "minor", "major" for auto-increment}'; protected $description = 'Tag and release a new version of Koel'; private Version $currentVersion; private string $mainBranch = 'master'; private string $releaseBranch = 'release'; public function handle(): int { $this->ensureMainBranch(); self::ensureCleanWorkingDirectory(); self::runOkOrThrow('git fetch'); $this->getCurrentVersion(); $releaseVersion = match ($this->argument('version')) { 'patch' => (clone $this->currentVersion)->incrementPatch()->prefix(), 'minor' => (clone $this->currentVersion)->incrementMinor()->prefix(), 'major' => (clone $this->currentVersion)->incrementMajor()->prefix(), null => $this->acquireReleaseVersionInteractively(), default => self::tryParseVersion($this->argument('version')) ?? $this->acquireReleaseVersionInteractively(), }; try { $this->release($releaseVersion); } catch (Throwable $e) { error($e->getMessage()); warning('Something went wrong. Double-check the working directory and maybe try again.'); return self::FAILURE; } return self::SUCCESS; } private function release(string $version): void { // Ensure the version is prefixed. $version = Version::parse($version)->prefix(); info("Releasing version $version..."); File::put(base_path('.version'), $version); $gitCommands = [ 'add .', "commit -m 'chore(release): bump version to $version'", 'push', "tag $version", 'tag latest -f', 'push origin --tags -f', "checkout $this->releaseBranch", 'pull', "merge $this->releaseBranch $this->mainBranch", 'push', "checkout $this->mainBranch", ]; foreach ($gitCommands as $command) { $this->components->task("Executing `git $command`", static fn () => self::runOkOrThrow("git $command")); } info("Success! The new version $version has been tagged."); info('Now go to https://github.com/koel/koel/releases and finish the draft release notes.'); } private function acquireReleaseVersionInteractively(): string { $patchVersion = (clone $this->currentVersion)->incrementPatch()->prefix(); $suggestedVersions = [ $patchVersion => 'Patch', (clone $this->currentVersion)->incrementMinor()->prefix() => 'Minor', (clone $this->currentVersion)->incrementMajor()->prefix() => 'Major', ]; $options = []; foreach ($suggestedVersions as $version => $name) { $options[$version] = "$name -> $version"; } $options['custom'] = 'Custom'; $selected = select( label: 'What are we releasing?', options: $options, default: $patchVersion, ); if ($selected === 'custom') { $selected = text( label: 'Enter the version you want to release', placeholder: $patchVersion, required: true, validate: static fn (string $value) => self::tryParseVersion($value) ? null : 'Invalid version format', ); } return Version::parse($selected)->prefix(); } private static function tryParseVersion(string $version): ?string { try { return Version::parse($version)->prefix(); } catch (Throwable) { return null; } } public function getCurrentVersion(): void { $this->currentVersion = new Version(File::get(base_path('.version'))); note('Current version: ' . $this->currentVersion->prefix()); } private function ensureMainBranch(): void { $branch = trim(Process::run('git branch --show-current')->output()); if ($branch !== $this->mainBranch) { error("You must be on the $this->mainBranch branch to release a new version (Current branch: '$branch.')"); exit(self::FAILURE); } } private static function ensureCleanWorkingDirectory(): void { if (Process::run('git status --porcelain')->output()) { error('Your working directly is not clean. Please commit or stash your changes before proceeding.'); exit(self::FAILURE); } } private static function runOkOrThrow(string $command): void { throw_unless(Process::forever()->run($command)->successful()); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/ExtractFoldersCommand.php
app/Console/Commands/ExtractFoldersCommand.php
<?php namespace App\Console\Commands; use App\Models\Setting; use App\Models\Song; use App\Services\MediaBrowser; use Illuminate\Console\Command; use Symfony\Component\Console\Helper\ProgressBar; class ExtractFoldersCommand extends Command { protected $signature = 'koel:extract-folders'; protected $description = 'Extract the folder structure from the existing song paths and store it in the database'; private ProgressBar $progressBar; public function __construct(private readonly MediaBrowser $browser) { parent::__construct(); } public function handle(): int { if (config('koel.storage_driver') !== 'local') { $this->components->error('This command only works with the local storage driver.'); return self::INVALID; } $root = Setting::get('media_path'); if (!$root) { $this->components->error('The media path is not set. Please set it up first.'); return self::INVALID; } $songs = Song::query() ->orderBy('path') ->whereNull('podcast_id') ->whereNull('folder_id') ->storedLocally() ->get(); $this->progressBar = new ProgressBar($this->output, count($songs)); $this->components->info('Extracting folders from the song paths...'); $songs->each(function (Song $song): void { $this->browser->maybeCreateFolderStructureForSong($song); $this->progressBar->advance(); }); $this->progressBar->finish(); $this->output->success('Done!'); return self::SUCCESS; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/CleanUpTempFilesCommand.php
app/Console/Commands/CleanUpTempFilesCommand.php
<?php namespace App\Console\Commands; use Carbon\Carbon; use Illuminate\Console\Command; use Illuminate\Support\Facades\File; class CleanUpTempFilesCommand extends Command { protected $signature = 'koel:clean-up-temp-files {--age=1440 : The age of temporary files to remove in minutes}'; protected $description = 'Remove temporary files older than a certain age'; public function handle(): int { $maxAgeMinutes = (int) $this->option('age'); $dir = artifact_path('tmp'); $files = File::allFiles($dir); $count = 0; foreach ($files as $file) { if (abs(now()->diffInMinutes(Carbon::createFromTimestamp($file->getMTime()))) > $maxAgeMinutes) { File::delete($file->getPathname()); $this->components->info("Deleted {$file->getPathname()}"); $count++; } } if ($count === 0) { $this->components->info("No temporary files older than $maxAgeMinutes minutes to delete."); } else { $this->components->info("Deleted {$count} temporary files older than {$maxAgeMinutes} minutes."); } return self::SUCCESS; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/InitCommand.php
app/Console/Commands/InitCommand.php
<?php namespace App\Console\Commands; use App\Console\Commands\Concerns\AskForPassword; use App\Exceptions\InstallationFailedException; use App\Models\Setting; use App\Models\User; use Illuminate\Console\Command; use Illuminate\Encryption\Encrypter; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Process; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Str; use Jackiedo\DotenvEditor\DotenvEditor; use Throwable; class InitCommand extends Command { use AskForPassword; private const NON_INTERACTION_MAX_DATABASE_ATTEMPT_COUNT = 10; protected $signature = 'koel:init {--no-assets : Do not compile front-end assets} {--no-scheduler : Do not install scheduler}'; protected $description = 'Install or upgrade Koel'; private bool $adminSeeded = false; public function __construct(private readonly DotenvEditor $dotenvEditor) { parent::__construct(); } public function handle(): int { $this->components->alert('KOEL INSTALLATION WIZARD'); $this->components->info( 'Remember, you can always install/upgrade manually using the guide at ' . config('koel.misc.docs_url') ); if ($this->inNoInteractionMode()) { $this->components->info('Running in no-interaction mode'); } try { $this->clearCaches(); $this->loadEnvFile(); $this->maybeGenerateAppKey(); $this->maybeSetUpDatabase(); $this->migrateDatabase(); $this->maybeSeedDatabase(); $this->maybeSetMediaPath(); $this->maybeCompileFrontEndAssets(); $this->maybeCopyManifests(); $this->dotenvEditor->save(); $this->tryInstallingScheduler(); } catch (Throwable $e) { Log::error($e); $this->components->error("Oops! Koel installation or upgrade didn't finish successfully."); $this->components->error('Please check the error log at storage/logs/laravel.log and try again.'); $this->components->error('For further troubleshooting, visit https://docs.koel.dev/troubleshooting.'); $this->components->error('😥 Sorry for this. You deserve better.'); return self::FAILURE; } $this->newLine(); $this->components->success('All done!'); if (app()->environment('local')) { $this->components->info('🏗️ Koel can now be run from localhost with `php artisan serve`'); } else { $this->components->info('🌟 A shiny Koel is now available at ' . config('app.url')); } if ($this->adminSeeded) { $this->components->info( sprintf('🧑‍💻 Log in with email %s and password %s', User::FIRST_ADMIN_EMAIL, User::FIRST_ADMIN_PASSWORD) ); } if (!Setting::get('media_path')) { $this->components->info('📀 You can set up the storage with `php artisan koel:storage`'); } $this->components->info('🛟 Documentation can be found at ' . config('koel.misc.docs_url')); $this->components->info('🤗 Consider supporting Koel’s development: ' . config('koel.misc.sponsor_github_url')); $this->components->info('🤘 Finally, thanks for using Koel. You rock!'); return self::SUCCESS; } private function clearCaches(): void { $this->components->task('Clearing caches', static function (): void { Artisan::call('config:clear', ['--quiet' => true]); Artisan::call('cache:clear', ['--quiet' => true]); }); } private function loadEnvFile(): void { if (!File::exists(base_path('.env'))) { $this->components->task('Copying .env file', static function (): void { File::copy(base_path('.env.example'), base_path('.env')); }); } else { $this->components->task('.env file exists -- skipping'); } $this->dotenvEditor->load(base_path('.env')); } private function maybeGenerateAppKey(): void { $key = $this->laravel['config']['app.key']; $this->components->task($key ? 'Retrieving app key' : 'Generating app key', function () use (&$key): void { if (!$key) { // Generate the key manually to prevent some clashes with `php artisan key:generate` $key = $this->generateRandomKey(); $this->dotenvEditor->setKey('APP_KEY', $key); $this->laravel['config']['app.key'] = $key; } }); $this->components->task('Using app key: ' . Str::limit($key, 16)); } /** * Prompt user for valid database credentials and set up the database. */ private function setUpDatabase(): void { $config = [ 'DB_HOST' => '', 'DB_PORT' => '', 'DB_USERNAME' => '', 'DB_PASSWORD' => '', ]; $config['DB_CONNECTION'] = $this->choice( 'Your DB driver of choice', [ 'mysql' => 'MySQL/MariaDB', 'pgsql' => 'PostgreSQL', 'sqlsrv' => 'SQL Server', 'sqlite-e2e' => 'SQLite', ], 'mysql' ); if ($config['DB_CONNECTION'] === 'sqlite-e2e') { $config['DB_DATABASE'] = $this->ask('Absolute path to the DB file'); } else { $config['DB_HOST'] = $this->anticipate('DB host', ['127.0.0.1', 'localhost']); $config['DB_PORT'] = (string) $this->ask('DB port (leave empty for default)'); $config['DB_DATABASE'] = $this->anticipate('DB name', ['koel']); $config['DB_USERNAME'] = $this->anticipate('DB user', ['koel']); $config['DB_PASSWORD'] = (string) $this->ask('DB password'); } $this->dotenvEditor->setKeys($config); $this->dotenvEditor->save(); // Set the config so that the next DB attempt uses refreshed credentials config([ 'database.default' => $config['DB_CONNECTION'], "database.connections.{$config['DB_CONNECTION']}.host" => $config['DB_HOST'], "database.connections.{$config['DB_CONNECTION']}.port" => $config['DB_PORT'], "database.connections.{$config['DB_CONNECTION']}.database" => $config['DB_DATABASE'], "database.connections.{$config['DB_CONNECTION']}.username" => $config['DB_USERNAME'], "database.connections.{$config['DB_CONNECTION']}.password" => $config['DB_PASSWORD'], ]); } private function inNoInteractionMode(): bool { return (bool) $this->option('no-interaction'); } private function inNoAssetsMode(): bool { return (bool) $this->option('no-assets'); } private function setUpAdminAccount(): void { $this->components->task('Creating default admin account', function (): void { User::firstAdmin(); $this->adminSeeded = true; }); } private function maybeSeedDatabase(): void { if (!User::query()->count()) { $this->setUpAdminAccount(); $this->components->task('Seeding data', static function (): void { Artisan::call('db:seed', ['--force' => true, '--quiet' => true]); }); } else { $this->components->task('Data already seeded -- skipping'); } } private function maybeSetUpDatabase(): void { $attempt = 0; while (true) { // In non-interactive mode, we must not endlessly attempt to connect. // Doing so will just end up with a huge amount of "failed to connect" logs. // We do retry a little, though, just in case there's some kind of temporary failure. if ($attempt >= self::NON_INTERACTION_MAX_DATABASE_ATTEMPT_COUNT && $this->inNoInteractionMode()) { $this->components->error('Maximum database connection attempts reached. Giving up.'); break; } $attempt++; try { // Make sure the config cache is cleared before another attempt. Artisan::call('config:clear', ['--quiet' => true]); DB::reconnect(); Schema::getTables(); break; } catch (Throwable $e) { Log::error($e); // We only try to update credentials if running in interactive mode. // Otherwise, we require admin intervention to fix them. // This avoids inadvertently wiping credentials if there's a connection failure. if ($this->inNoInteractionMode()) { $warning = sprintf( "Cannot connect to the database. Attempt: %d/%d", $attempt, self::NON_INTERACTION_MAX_DATABASE_ATTEMPT_COUNT ); $this->components->warn($warning); } else { $this->components->warn("Cannot connect to the database. Let's set it up."); $this->setUpDatabase(); } } } } private function migrateDatabase(): void { $this->components->task('Migrating database', static function (): void { Artisan::call('migrate', ['--force' => true, '--quiet' => true]); }); } private function maybeSetMediaPath(): void { if (Setting::get('media_path')) { return; } if ($this->inNoInteractionMode()) { $this->setMediaPathFromEnvFile(); return; } $this->newLine(); $this->info('The absolute path to your media directory. You can leave it blank and set it later via the web interface.'); // @phpcs-ignore-line $this->info('If you plan to use Koel with a cloud provider (S3 or Dropbox), you can also skip this.'); while (true) { $path = $this->ask('Media path', config('koel.media_path')); if (!$path) { return; } if (self::isValidMediaPath($path)) { Setting::set('media_path', $path); return; } $this->components->error('The path does not exist or not readable. Try again?'); } } private function maybeCompileFrontEndAssets(): void { if ($this->inNoAssetsMode()) { return; } $this->components->task('Installing npm dependencies', function (): void { $this->runOkOrThrow('pnpm install --color'); }); $this->components->task('Compiling frontend assets', function (): void { $this->runOkOrThrow('pnpm run --color build'); }); } private function runOkOrThrow(string $command): void { $printer = $this->option('verbose') ? static fn (string $type, string $output) => print $output : null; throw_unless(Process::forever()->run($command, $printer)->successful(), InstallationFailedException::class); } private function setMediaPathFromEnvFile(): void { $path = config('koel.media_path'); if (!$path) { return; } if (self::isValidMediaPath($path)) { Setting::set('media_path', $path); } else { $this->components->warn(sprintf('The path %s does not exist or not readable. Skipping.', $path)); } } private static function isValidMediaPath(string $path): bool { return File::isDirectory($path) && File::isReadable($path); } private function generateRandomKey(): string { return 'base64:' . base64_encode(Encrypter::generateKey($this->laravel['config']['app.cipher'])); } private function tryInstallingScheduler(): void { if (PHP_OS_FAMILY === 'Windows' || PHP_OS_FAMILY === 'Unknown') { return; } if ((bool) $this->option('no-scheduler')) { return; } $result = 0; $this->components->task('Installing Koel scheduler', static function () use (&$result): void { $result = Artisan::call('koel:scheduler:install', ['--quiet' => true]); }); if ($result !== self::SUCCESS) { $this->components->warn( 'Failed to install scheduler. ' . 'Please install manually: https://docs.koel.dev/cli-commands#command-scheduling' ); } } private function maybeCopyManifests(): void { foreach (['manifest.json', 'manifest-remote.json'] as $file) { $destination = public_path($file); $source = public_path("$file.example"); if (File::exists($destination)) { $this->components->task("$file already exists -- skipping"); continue; } $this->components->task("Copying $file", static function () use ($source, $destination): void { File::copy($source, $destination); }); } } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/Admin/SetUserRoleCommand.php
app/Console/Commands/Admin/SetUserRoleCommand.php
<?php namespace App\Console\Commands\Admin; use App\Enums\Acl\Role; use App\Repositories\UserRepository; use Illuminate\Console\Command; use function Laravel\Prompts\select; class SetUserRoleCommand extends Command { protected $signature = "koel:admin:set-user-role {email : The user's email}"; protected $description = 'Set a user\'s role'; public function __construct(private readonly UserRepository $userRepository) { parent::__construct(); } public function handle(): int { $user = $this->userRepository->findOneByEmail($this->argument('email')); if (!$user) { $this->components->error('The user account cannot be found.'); return self::FAILURE; } $roles = []; Role::allAvailable()->each(static function (Role $role) use (&$roles): void { $roles[$role->value] = $role->label(); }); $role = select( label: 'What role should the user have?', options: $roles, default: $user->role->value, ); $user->syncRoles($role); $this->info("The user's role has been set to <info>'$role'</info>."); return self::SUCCESS; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/Admin/ChangePasswordCommand.php
app/Console/Commands/Admin/ChangePasswordCommand.php
<?php namespace App\Console\Commands\Admin; use App\Console\Commands\Concerns\AskForPassword; use App\Repositories\UserRepository; use Illuminate\Console\Command; use Illuminate\Contracts\Hashing\Hasher as Hash; class ChangePasswordCommand extends Command { use AskForPassword; protected $signature = "koel:admin:change-password {email? : The user's email. If empty, will get the default admin user.}"; protected $description = "Change a user's password"; public function __construct(private readonly Hash $hash, private readonly UserRepository $userRepository) { parent::__construct(); } public function handle(): int { $email = $this->argument('email'); $user = $email ? $this->userRepository->findOneByEmail($email) : $this->userRepository->getFirstAdminUser(); if (!$user) { $this->error('The user account cannot be found.'); return self::FAILURE; } $this->comment("Changing the user's password (ID: {$user->id}, email: $user->email)"); $user->password = $this->hash->make($this->askForPassword()); $user->save(); $this->comment('Alrighty, the new password has been saved. Enjoy! 👌'); return self::SUCCESS; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/Storage/StorageCommand.php
app/Console/Commands/Storage/StorageCommand.php
<?php namespace App\Console\Commands\Storage; use App\Facades\License; use App\Models\Setting; use Illuminate\Console\Command; class StorageCommand extends Command { protected $signature = 'koel:storage'; protected $description = 'Set up and configure Koel’s storage'; public function handle(): int { $this->info('This command will set up and configure Koel’s storage.'); $this->info('Current storage configuration:'); $this->components->twoColumnDetail('Driver', config('koel.storage_driver')); if (config('koel.storage_driver') === 'local') { $this->components->twoColumnDetail('Media path', Setting::get('media_path') ?: '<not set>'); } if (License::isPlus()) { $choices = [ 'local' => 'This server', 's3' => 'Amazon S3 or compatible services (DO Spaces, Cloudflare R2, etc.)', 'dropbox' => 'Dropbox', ]; $driver = $this->choice( 'Where do you want to store your media files?', $choices, config('koel.storage_driver') ); } else { $driver = 'local'; } if ($this->call("koel:storage:$driver") === self::SUCCESS) { $this->output->success('Storage has been set up.'); return self::SUCCESS; } return self::FAILURE; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/Storage/SetupDropboxStorageCommand.php
app/Console/Commands/Storage/SetupDropboxStorageCommand.php
<?php namespace App\Console\Commands\Storage; use App\Facades\License; use App\Services\SongStorages\DropboxStorage; use Illuminate\Console\Command; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Http; use Jackiedo\DotenvEditor\DotenvEditor; use Throwable; class SetupDropboxStorageCommand extends Command { protected $signature = 'koel:storage:dropbox'; protected $description = 'Set up Dropbox as the storage driver for Koel'; public function __construct(private readonly DotenvEditor $dotenvEditor) { parent::__construct(); } public function handle(bool $firstTry = true): int { if (!License::isPlus()) { $this->components->error('Dropbox as a storage driver is only available in Koel Plus.'); return self::FAILURE; } if ($firstTry) { $this->components->info('Setting up Dropbox as the storage driver for Koel.'); $this->components->warn('Changing the storage configuration can cause irreversible data loss.'); $this->components->warn('Consider backing up your data before proceeding.'); } $config = ['STORAGE_DRIVER' => 'dropbox']; $config['DROPBOX_APP_KEY'] = $this->ask('Enter your Dropbox app key', env('DROPBOX_APP_KEY')); $config['DROPBOX_APP_SECRET'] = $this->ask('Enter your Dropbox app secret', env('DROPBOX_APP_SECRET')); $this->comment('Visit the following link to authorize Koel to access your Dropbox account.'); $this->comment('After you have authorized Koel, enter the access code below.'); $this->info(route('dropbox.authorize', ['key' => $config['DROPBOX_APP_KEY']])); $accessCode = $this->ask('Access code'); $response = Http::asForm() ->withBasicAuth($config['DROPBOX_APP_KEY'], $config['DROPBOX_APP_SECRET']) ->post('https://api.dropboxapi.com/oauth2/token', [ 'code' => $accessCode, 'grant_type' => 'authorization_code', ]); if ($response->failed()) { $this->error( 'Failed to authorize with Dropbox. The server said: ' . $response->json('error_description') . '.' ); $this->info('Please try again.'); return $this->handle(firstTry: false); } $config['DROPBOX_REFRESH_TOKEN'] = $response->json('refresh_token'); $this->dotenvEditor->setKeys($config); $this->dotenvEditor->save(); config()->set('filesystems.disks.dropbox', [ 'app_key' => $config['DROPBOX_APP_KEY'], 'app_secret' => $config['DROPBOX_APP_SECRET'], 'refresh_token' => $config['DROPBOX_REFRESH_TOKEN'], ]); $this->comment('Uploading a test file to make sure everything is working...'); try { /** @var DropboxStorage $storage */ $storage = app()->build(DropboxStorage::class); // build instead of make to avoid singleton issues $storage->testSetup(); } catch (Throwable $e) { $this->error('Failed to upload test file: ' . $e->getMessage() . '.'); $this->comment('Please make sure the app has the correct permissions and try again.'); $this->dotenvEditor->restore(); Artisan::call('config:clear', ['--quiet' => true]); return $this->handle(firstTry: false); } $this->components->info('All done!'); return self::SUCCESS; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/Storage/SetupS3StorageCommand.php
app/Console/Commands/Storage/SetupS3StorageCommand.php
<?php namespace App\Console\Commands\Storage; use App\Facades\License; use App\Services\SongStorages\S3CompatibleStorage; use Illuminate\Console\Command; use Illuminate\Support\Facades\Artisan; use Jackiedo\DotenvEditor\DotenvEditor; use Throwable; class SetupS3StorageCommand extends Command { protected $signature = 'koel:storage:s3'; protected $description = 'Set up Amazon S3 or a compatible service as the storage driver for Koel'; public function __construct(private readonly DotenvEditor $dotenvEditor) { parent::__construct(); } public function handle(): int { if (!License::isPlus()) { $this->components->error('S3 as a storage driver is only available in Koel Plus.'); return self::FAILURE; } $this->components->info('Setting up S3 or an S3-compatible service as the storage driver for Koel.'); $this->components->warn('Changing the storage configuration can cause irreversible data loss.'); $this->components->warn('Consider backing up your data before proceeding.'); $config = ['STORAGE_DRIVER' => 's3']; $config['AWS_ACCESS_KEY_ID'] = $this->ask('Enter the access key ID (AWS_ACCESS_KEY_ID)'); $config['AWS_SECRET_ACCESS_KEY'] = $this->ask('Enter the secret access key (AWS_SECRET_ACCESS_KEY)'); $config['AWS_REGION'] = $this->ask('Enter the region (AWS_REGION). For Cloudflare R2, use "auto".'); $config['AWS_ENDPOINT'] = $this->ask('Enter the endpoint (AWS_ENDPOINT)'); $config['AWS_BUCKET'] = $this->ask('Enter the bucket name (AWS_BUCKET)'); $this->dotenvEditor->setKeys($config); $this->dotenvEditor->save(); $this->comment('Uploading a test file to make sure everything is working...'); config('filesystems.disks.s3.bucket', $config['AWS_BUCKET']); try { /** @var S3CompatibleStorage $storage */ $storage = app()->build(S3CompatibleStorage::class); $storage->testSetup(); } catch (Throwable $e) { $this->error('Failed to upload test file: ' . $e->getMessage() . '.'); $this->comment('Please check your configuration and try again.'); $this->dotenvEditor->restore(); Artisan::call('config:clear', ['--quiet' => true]); return self::FAILURE; } $this->components->info('All done!'); return self::SUCCESS; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/Storage/SetupLocalStorageCommand.php
app/Console/Commands/Storage/SetupLocalStorageCommand.php
<?php namespace App\Console\Commands\Storage; use App\Models\Setting; use Illuminate\Console\Command; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\File; use Jackiedo\DotenvEditor\DotenvEditor; class SetupLocalStorageCommand extends Command { protected $signature = 'koel:storage:local'; protected $description = 'Set up the local storage for Koel'; public function __construct(private readonly DotenvEditor $dotenvEditor) { parent::__construct(); } public function handle(): int { $this->components->info('Setting up local storage for Koel.'); $this->components->warn('Changing the storage configuration can cause irreversible data loss.'); $this->components->warn('Consider backing up your data before proceeding.'); Setting::set('media_path', $this->askForMediaPath()); $this->dotenvEditor->setKey('STORAGE_DRIVER', 'local'); $this->dotenvEditor->save(); Artisan::call('config:clear', ['--quiet' => true]); $this->components->info('Local storage has been set up.'); if ($this->components->confirm('Would you want to initialize a scan now?', true)) { $this->call('koel:scan'); } return self::SUCCESS; } private function askForMediaPath(): string { $mediaPath = $this->components->ask('Enter the absolute path to your media files', Setting::get('media_path')); if (File::isReadable($mediaPath) && File::isWritable($mediaPath)) { return $mediaPath; } $this->components->error('The path you entered is not read- and/or writeable. Please check and try again.'); return $this->askForMediaPath(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Console/Commands/Concerns/AskForPassword.php
app/Console/Commands/Concerns/AskForPassword.php
<?php namespace App\Console\Commands\Concerns; /** * @method void error($message, $verbosity = null) * @method mixed secret($message, $fallback = true) */ trait AskForPassword { private function askForPassword(): string { do { $password = $this->secret('Your desired password'); if (!$password) { $this->error('Passwords cannot be empty. You know that.'); continue; } $confirmedPassword = $this->secret('Again, just to be sure'); } while (!$this->comparePasswords($password, $confirmedPassword ?? null)); return $password; } private function comparePasswords(?string $password, ?string $confirmedPassword): bool { if (!$password || !$confirmedPassword) { return false; } if (strcmp($password, $confirmedPassword) !== 0) { $this->error('The passwords do not match. Try again maybe?'); return false; } return true; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Enums/PlayableType.php
app/Enums/PlayableType.php
<?php namespace App\Enums; enum PlayableType: string { case SONG = 'song'; case PODCAST_EPISODE = 'episode'; }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Enums/PermissionableResourceType.php
app/Enums/PermissionableResourceType.php
<?php namespace App\Enums; use App\Models\Album; use App\Models\Artist; use App\Models\RadioStation; use App\Models\User; enum PermissionableResourceType: string { case ALBUM = 'album'; case ARTIST = 'artist'; case RADIO_STATION = 'radio-station'; case USER = 'user'; /** @return class-string<Album|Artist|RadioStation|User> */ public function modelClass(): string { return match ($this) { self::ALBUM => Album::class, self::ARTIST => Artist::class, self::RADIO_STATION => RadioStation::class, self::USER => User::class, }; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Enums/EmbeddableType.php
app/Enums/EmbeddableType.php
<?php namespace App\Enums; use App\Http\Resources\AlbumResource; use App\Http\Resources\ArtistResource; use App\Http\Resources\PlaylistResource; use App\Http\Resources\SongResource; use App\Models\Album; use App\Models\Artist; use App\Models\Playlist; use App\Models\Song; use Illuminate\Http\Resources\Json\JsonResource; enum EmbeddableType: string { case PLAYABLE = 'playable'; case PLAYLIST = 'playlist'; case ALBUM = 'album'; case ARTIST = 'artist'; /** @return class-string<Song|Playlist|Album|Artist> */ public function modelClass(): string { return match ($this) { self::PLAYABLE => Song::class, self::PLAYLIST => Playlist::class, self::ALBUM => Album::class, self::ARTIST => Artist::class, }; } /** @return class-string<JsonResource> */ public function resourceClass(): string { return match ($this) { self::PLAYABLE => SongResource::class, self::PLAYLIST => PlaylistResource::class, self::ALBUM => AlbumResource::class, self::ARTIST => ArtistResource::class, }; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Enums/SmartPlaylistModel.php
app/Enums/SmartPlaylistModel.php
<?php namespace App\Enums; enum SmartPlaylistModel: string { case ALBUM_NAME = 'album.name'; case ARTIST_NAME = 'artist.name'; case DATE_ADDED = 'created_at'; case DATE_MODIFIED = 'updated_at'; case GENRE = 'genre'; case LAST_PLAYED = 'interactions.last_played_at'; case LENGTH = 'length'; case PLAY_COUNT = 'interactions.play_count'; case TITLE = 'title'; case USER_ID = 'interactions.user_id'; case YEAR = 'year'; public function toColumnName(): string { return match ($this) { self::ALBUM_NAME => 'songs.album_name', self::ARTIST_NAME => 'songs.artist_name', self::DATE_ADDED => 'songs.created_at', self::DATE_MODIFIED => 'songs.updated_at', self::GENRE => 'genres.name', self::LENGTH => 'songs.length', self::PLAY_COUNT => 'COALESCE(interactions.play_count, 0)', self::TITLE => 'songs.title', self::YEAR => 'songs.year', default => $this->value, }; } public function isDate(): bool { return in_array($this, [self::LAST_PLAYED, self::DATE_ADDED, self::DATE_MODIFIED], true); } /** * Indicates whether this model would require a raw SQL query to be used in a smart playlist rule. * For example, the play count is a virtual column that needs to be queried with raw SQL. */ public function requiresRawQuery(): bool { return $this === self::PLAY_COUNT; } public function getManyToManyRelation(): ?string { return match ($this) { self::GENRE => 'genres', default => null, }; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Enums/SongStorageType.php
app/Enums/SongStorageType.php
<?php namespace App\Enums; use App\Facades\License; enum SongStorageType: string { case S3 = 's3'; case S3_LAMBDA = 's3-lambda'; case DROPBOX = 'dropbox'; case SFTP = 'sftp'; case LOCAL = ''; public function supported(): bool { return ($this === self::LOCAL || $this === self::S3_LAMBDA) || License::isPlus(); } public function supportsFolderStructureExtraction(): bool { return $this === self::LOCAL; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Enums/DoctorResult.php
app/Enums/DoctorResult.php
<?php namespace App\Enums; enum DoctorResult { case SUCCESS; case ERROR; }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Enums/ScanResultType.php
app/Enums/ScanResultType.php
<?php namespace App\Enums; enum ScanResultType: string { case SUCCESS = 'Success'; case ERROR = 'Error'; case SKIPPED = 'Skipped'; }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Enums/Placement.php
app/Enums/Placement.php
<?php namespace App\Enums; enum Placement: string { case BEFORE = 'before'; case AFTER = 'after'; }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Enums/ScanEvent.php
app/Enums/ScanEvent.php
<?php namespace App\Enums; enum ScanEvent { case PATHS_GATHERED; case SCAN_PROGRESS; case SCAN_COMPLETED; }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Enums/SmartPlaylistOperator.php
app/Enums/SmartPlaylistOperator.php
<?php namespace App\Enums; enum SmartPlaylistOperator: string { case IS = 'is'; case IS_NOT = 'isNot'; case CONTAINS = 'contains'; case NOT_CONTAIN = 'notContain'; case IS_BETWEEN = 'isBetween'; case IS_GREATER_THAN = 'isGreaterThan'; case IS_LESS_THAN = 'isLessThan'; case BEGINS_WITH = 'beginsWith'; case ENDS_WITH = 'endsWith'; case IN_LAST = 'inLast'; case NOT_IN_LAST = 'notInLast'; case IS_NOT_BETWEEN = 'isNotBetween'; public function toWhereMethod(): string { return match ($this) { self::IS_BETWEEN => 'whereBetween', self::IS_NOT_BETWEEN => 'whereNotBetween', default => 'where', }; } public function isNegative(): bool { return in_array($this, [self::IS_NOT, self::NOT_CONTAIN, self::IS_NOT_BETWEEN], true); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Enums/FavoriteableType.php
app/Enums/FavoriteableType.php
<?php namespace App\Enums; use App\Models\Album; use App\Models\Artist; use App\Models\Contracts\Favoriteable; use App\Models\Podcast; use App\Models\RadioStation; use App\Models\Song; use Illuminate\Database\Eloquent\Model; enum FavoriteableType: string { case PLAYABLE = 'playable'; case ALBUM = 'album'; case ARTIST = 'artist'; case PODCAST = 'podcast'; case RADIO_STATION = 'radio-station'; /** @return class-string<Favoriteable|Model> */ public function modelClass(): string { return match ($this) { self::PLAYABLE => Song::class, self::ALBUM => Album::class, self::ARTIST => Artist::class, self::PODCAST => Podcast::class, self::RADIO_STATION => RadioStation::class, }; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Enums/LicenseStatus.php
app/Enums/LicenseStatus.php
<?php namespace App\Enums; enum LicenseStatus { case VALID; case INVALID; case NO_LICENSE; case UNKNOWN; }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Enums/Acl/Role.php
app/Enums/Acl/Role.php
<?php namespace App\Enums\Acl; use App\Exceptions\KoelPlusRequiredException; use App\Facades\License; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Support\Collection; enum Role: string implements Arrayable { case ADMIN = 'admin'; case MANAGER = 'manager'; case USER = 'user'; public function label(): string { return match ($this) { self::ADMIN => 'Admin', self::MANAGER => 'Manager', self::USER => 'User', }; } public static function default(): self { return self::USER; } public function level(): int { return match ($this) { self::ADMIN => 3, self::MANAGER => 2, self::USER => 1, }; } public function greaterThan(self $other): bool { return $this->level() > $other->level(); } public function lessThan(self $other): bool { return $this->level() < $other->level(); } public function canManage(self $other): bool { return $this->level() >= $other->level(); } public function available(): bool { return match ($this) { self::ADMIN, self::USER => true, self::MANAGER => once(static fn () => License::isPlus()), }; } public function assertAvailable(): void { throw_unless($this->available(), KoelPlusRequiredException::class); } /** @return Collection<self> */ public static function allAvailable(): Collection { return collect(self::cases())->filter(static fn (Role $role) => $role->available()); } public function description(): string { $isCommunity = once(static fn () => License::isCommunity()); return match ($this) { self::ADMIN => 'Admins can manage everything.', self::MANAGER => $isCommunity ? 'Managers can manage users, upload musics, and perform other management tasks.' : 'Managers can manage users and perform other management tasks.', self::USER => $isCommunity ? 'Users can play music and manage their own playlists.' : 'Users can upload and manage their own music.', }; } /** @return array<mixed> */ public function toArray(): array { return [ 'id' => $this->value, 'label' => $this->label(), 'level' => $this->level(), 'is_default' => $this === self::default(), 'description' => $this->description(), ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Enums/Acl/Permission.php
app/Enums/Acl/Permission.php
<?php namespace App\Enums\Acl; enum Permission: string { case MANAGE_SETTINGS = 'manage settings'; // media path, plus edition, SSO, etc. case MANAGE_USERS = 'manage users'; // create, edit, delete users case MANAGE_SONGS = 'manage songs'; // upload, edit, delete case MANAGE_RADIO_STATIONS = 'manage radio stations'; // create, edit, delete case MANAGE_PODCASTS = 'manage podcasts'; // create, edit, delete podcasts }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/SongZipArchive.php
app/Models/SongZipArchive.php
<?php namespace App\Models; use App\Facades\Download; use App\Helpers\Ulid; use Illuminate\Support\Collection; use Illuminate\Support\Str; use RuntimeException; use ZipArchive; class SongZipArchive { private ZipArchive $archive; private string $path; /** * Names of the files in the archive * Format: ['file-name.mp3' => currentFileIndex]. */ private array $fileNames = []; public function __construct(?string $path = null) { $this->path = $path ?: self::generateRandomArchivePath(); $this->archive = new ZipArchive(); if ($this->archive->open($this->path, ZipArchive::CREATE) !== true) { throw new RuntimeException('Cannot create zip file.'); } } public function addSongs(Collection $songs): static { $songs->each(fn (Song $song) => $this->addSong($song)); return $this; } public function addSong(Song $song): static { rescue(function () use ($song): void { $path = Download::getLocalPath($song); $this->archive->addFile($path, $this->generateZipContentFileNameFromPath($path)); }); return $this; } public function finish(): static { $this->archive->close(); return $this; } public function getPath(): string { return $this->path; } /** * We add all files into the zip archive as a flat structure. * As a result, there can be duplicate file names. * This method makes sure each file name is unique in the zip archive. */ private function generateZipContentFileNameFromPath(string $path): string { $name = basename($path); if (array_key_exists($name, $this->fileNames)) { ++$this->fileNames[$name]; $extension = Str::afterLast($name, '.'); $name = Str::beforeLast($name, '.') . $this->fileNames[$name] . ".$extension"; } else { $this->fileNames[$name] = 1; } return $name; } private static function generateRandomArchivePath(): string { return artifact_path(sprintf('tmp/%s.zip', Ulid::generate())); } public function getArchive(): ZipArchive { return $this->archive; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Transcode.php
app/Models/Transcode.php
<?php namespace App\Models; use App\Enums\SongStorageType; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Concerns\HasUuids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Support\Facades\File; /** * @property string $id * @property string $song_id * @property Song $song * @property-read SongStorageType $storage The storage type of the associated song. * @property int $bit_rate * @property ?int $file_size * @property string $hash * @property string $location */ class Transcode extends Model { use HasFactory; use HasUuids; protected $guarded = []; protected $casts = [ 'bit_rate' => 'int', 'file_size' => 'int', ]; protected $with = ['song']; public function song(): BelongsTo { return $this->belongsTo(Song::class); } public function isValid(): bool { // For cloud storage songs, since the transcoded file is stored in the cloud too, // we assume the transcoded file is valid. if ($this->song->isStoredOnCloud()) { return true; } return File::isReadable($this->location) && File::hash($this->location) === $this->hash; } protected function storage(): Attribute { return Attribute::get(fn () => $this->song->storage)->shouldCache(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Interaction.php
app/Models/Interaction.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Support\Carbon; /** * @property int $play_count * @property Song $song * @property User $user * @property int $id * @property string $song_id * @property Carbon|string $last_played_at */ class Interaction extends Model { use HasFactory; protected $casts = [ 'play_count' => 'integer', ]; protected $guarded = ['id']; protected $hidden = ['id', 'user_id', 'created_at', 'updated_at', 'last_played_at']; public function user(): BelongsTo { return $this->belongsTo(User::class); } public function song(): BelongsTo { return $this->belongsTo(Song::class); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/PlaylistCollaborationToken.php
app/Models/PlaylistCollaborationToken.php
<?php namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * @property string $token * @property Carbon $created_at * @property-read bool $expired * @property string $playlist_id * @property Playlist $playlist */ class PlaylistCollaborationToken extends Model { use HasFactory; public function playlist(): BelongsTo { return $this->belongsTo(Playlist::class); } protected function expired(): Attribute { return Attribute::get(fn (): bool => $this->created_at->addDays(7)->isPast())->shouldCache(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/RadioStation.php
app/Models/RadioStation.php
<?php namespace App\Models; use App\Builders\RadioStationBuilder; use App\Models\Concerns\MorphsToFavorites; use App\Models\Contracts\Favoriteable; use App\Models\Contracts\Permissionable; use Carbon\Carbon; use Illuminate\Database\Eloquent\Concerns\HasUlids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Laravel\Scout\Searchable; use OwenIt\Auditing\Auditable; use OwenIt\Auditing\Contracts\Auditable as AuditableContract; /** * @property string $id * @property int $user_id * @property User $user * @property string $url * @property ?string $logo The station's logo file name * @property ?string $description * @property boolean $is_public * @property Carbon|string $created_at * @property string $name * @property-read ?boolean $favorite Whether the (scoped) user has favorited this radio station */ class RadioStation extends Model implements AuditableContract, Favoriteable, Permissionable { use Auditable; use HasFactory; use HasUlids; use MorphsToFavorites; use Searchable; protected $guarded = []; public $incrementing = false; protected $with = ['user']; protected $casts = [ 'created_at' => 'datetime', 'updated_at' => 'datetime', 'favorite' => 'boolean', 'is_public' => 'boolean', 'description' => 'string', ]; public function user(): BelongsTo { return $this->belongsTo(User::class); } public static function query(): RadioStationBuilder { /** @var RadioStationBuilder */ return parent::query()->addSelect('radio_stations.*'); } public function newEloquentBuilder($query): RadioStationBuilder { return new RadioStationBuilder($query); } /** @inheritdoc */ public function toSearchableArray(): array { return [ 'id' => $this->id, 'name' => $this->name, 'description' => $this->description, 'user_id' => $this->user_id, ]; } public static function getPermissionableIdentifier(): string { return 'id'; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Artist.php
app/Models/Artist.php
<?php namespace App\Models; use App\Builders\ArtistBuilder; use App\Facades\License; use App\Facades\Util; use App\Models\Concerns\MorphsToEmbeds; use App\Models\Concerns\MorphsToFavorites; use App\Models\Concerns\SupportsDeleteWhereValueNotIn; use App\Models\Contracts\Embeddable; use App\Models\Contracts\Favoriteable; use App\Models\Contracts\Permissionable; use Carbon\Carbon; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Concerns\HasUlids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Laravel\Scout\Searchable; use OwenIt\Auditing\Auditable; use OwenIt\Auditing\Contracts\Auditable as AuditableContract; /** * @property ?string $image The artist's image file name * @property Carbon $created_at * @property Collection<array-key, Album> $albums * @property Collection<array-key, Song> $songs * @property User $user * @property bool $is_unknown If the artist is Unknown Artist * @property bool $is_various If the artist is Various Artist * @property int $user_id The ID of the user that owns this artist * @property string $id * @property string $name */ class Artist extends Model implements AuditableContract, Embeddable, Favoriteable, Permissionable { use Auditable; use HasFactory; use HasUlids; use MorphsToEmbeds; use MorphsToFavorites; use Searchable; use SupportsDeleteWhereValueNotIn; public const UNKNOWN_NAME = 'Unknown Artist'; public const VARIOUS_NAME = 'Various Artists'; protected $guarded = ['id']; protected $hidden = ['created_at', 'updated_at']; public static function query(): ArtistBuilder { /** @var ArtistBuilder */ return parent::query()->addSelect('artists.*'); } public function newEloquentBuilder($query): ArtistBuilder { return new ArtistBuilder($query); } public function albums(): HasMany { return $this->hasMany(Album::class); } public function songs(): HasMany { return $this->hasMany(Song::class); } public function user(): BelongsTo { return $this->belongsTo(User::class); } public function belongsToUser(User $user): bool { return $this->user_id === $user->id; } protected function isUnknown(): Attribute { return Attribute::get(fn (): bool => $this->name === self::UNKNOWN_NAME); } protected function isVarious(): Attribute { return Attribute::get(fn (): bool => $this->name === self::VARIOUS_NAME); } /** * Get an Artist object from their name (and if Koel Plus, belonging to a specific user). * If such is not found, a new artist will be created. */ public static function getOrCreate(User $user, ?string $name = null): self { // Remove the BOM from UTF-8/16/32, as it will mess up the database constraints. $encoding = Util::detectUTFEncoding($name); if ($encoding) { $name = mb_convert_encoding($name, 'UTF-8', $encoding); } $name = trim($name) ?: self::UNKNOWN_NAME; // In the Community license, all artists are shared, so we determine the first artist by the name only. // In the Plus license, artists are user-specific, so we create or return the artist for the given user. $where = ['name' => $name]; if (License::isPlus()) { $where['user_id'] = $user->id; } return static::query()->where($where)->firstOr(static function () use ($user, $name): Artist { return static::query()->create([ 'user_id' => $user->id, 'name' => $name, ]); }); } /** * Sometimes the tags extracted from getID3 are HTML entity encoded. * This makes sure they are always sane. */ protected function name(): Attribute { return Attribute::get(static fn (string $value): string => html_entity_decode($value) ?: self::UNKNOWN_NAME); } /** @return array<mixed> */ public function toSearchableArray(): array { return [ 'id' => $this->id, 'user_id' => $this->user_id, 'name' => $this->name, ]; } public static function getPermissionableIdentifier(): string { return 'id'; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Theme.php
app/Models/Theme.php
<?php namespace App\Models; use App\Casts\ThemePropertiesCast; use App\Values\Theme\ThemeProperties; use Illuminate\Database\Eloquent\Concerns\HasUlids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * @property string $id * @property string $name * @property string|null $thumbnail * @property int $user_id * @property ThemeProperties $properties * @property User $user */ class Theme extends Model { use HasFactory; use HasUlids; protected $guarded = []; protected $casts = [ 'properties' => ThemePropertiesCast::class, ]; public function user(): BelongsTo { return $this->belongsTo(User::class); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Organization.php
app/Models/Organization.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Concerns\HasUlids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Carbon; /** * @property string $id * @property string $name * @property string $slug * @property Carbon $created_at * @property Carbon $updated_at * * @property-read Collection<User>|array<array-key, User> $users */ class Organization extends Model { use HasUlids; use HasFactory; public const DEFAULT_SLUG = 'koel'; protected $guarded = ['id']; public static function default(): Organization { return once(static fn () => self::query()->firstOrCreate(['slug' => self::DEFAULT_SLUG], ['name' => 'Koel'])); } public function users(): HasMany { return $this->hasMany(User::class); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/User.php
app/Models/User.php
<?php namespace App\Models; use App\Builders\UserBuilder; use App\Casts\UserPreferencesCast; use App\Enums\Acl\Role as RoleEnum; use App\Exceptions\UserAlreadySubscribedToPodcastException; use App\Facades\License; use App\Models\Contracts\Permissionable; use App\Values\User\UserPreferences; use Carbon\Carbon; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Prunable; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Support\Arr; use Illuminate\Support\Facades\Hash; use Laravel\Sanctum\HasApiTokens; use Laravel\Sanctum\PersonalAccessToken; use OwenIt\Auditing\Auditable; use OwenIt\Auditing\Contracts\Auditable as AuditableContract; use Spatie\Permission\Traits\HasRoles; /** * @property ?Carbon $invitation_accepted_at * @property ?Carbon $invited_at * @property ?User $invitedBy * @property ?string $invitation_token * @property Collection<array-key, Playlist> $collaboratedPlaylists * @property Collection<array-key, Playlist> $playlists * @property Collection<array-key, PlaylistFolder> $playlistFolders * @property Collection<array-key, Podcast> $podcasts * @property Collection<array-key, Theme> $themes * @property Organization $organization * @property PersonalAccessToken $currentAccessToken * @property UserPreferences $preferences * @property int $id * @property string $email * @property string $name * @property string $organization_id * @property string $password * @property string $public_id * @property-read ?string $sso_id * @property-read ?string $sso_provider * @property-read bool $connected_to_lastfm Whether the user is connected to Last.fm * @property-read bool $has_custom_avatar * @property-read bool $is_prospect * @property-read bool $is_sso * @property-read string $avatar * @property-read RoleEnum $role */ class User extends Authenticatable implements AuditableContract, Permissionable { use Auditable; use HasApiTokens; use HasFactory; use HasRoles { scopeRole as scopeWhereRole; } use Notifiable; use Prunable; private const FIRST_ADMIN_NAME = 'Koel'; public const FIRST_ADMIN_EMAIL = 'admin@koel.dev'; public const FIRST_ADMIN_PASSWORD = 'KoelIsCool'; public const DEMO_PASSWORD = 'demo'; public const DEMO_USER_DOMAIN = 'demo.koel.dev'; protected $guarded = ['id', 'public_id']; protected $hidden = ['password', 'remember_token', 'created_at', 'updated_at', 'invitation_accepted_at']; protected $appends = ['avatar']; protected array $auditExclude = ['password', 'remember_token', 'invitation_token']; protected $with = ['roles', 'permissions']; protected $casts = [ 'preferences' => UserPreferencesCast::class, ]; public static function query(): UserBuilder { /** @var UserBuilder */ return parent::query(); } public function newEloquentBuilder($query): UserBuilder { return new UserBuilder($query); } /** * The first admin user in the system. * This user is created automatically if it does not exist (e.g., during installation or unit tests). */ public static function firstAdmin(): static { $defaultOrganization = Organization::default(); return static::query() // @phpstan-ignore-line ->whereRole(RoleEnum::ADMIN) ->where('organization_id', $defaultOrganization->id) ->oldest() ->firstOr(static function () use ($defaultOrganization): User { /** @var User $user */ $user = static::query()->create([ 'email' => self::FIRST_ADMIN_EMAIL, 'name' => self::FIRST_ADMIN_NAME, 'password' => Hash::make(self::FIRST_ADMIN_PASSWORD), 'organization_id' => $defaultOrganization->id, ]); return $user->syncRoles(RoleEnum::ADMIN); }); } public function organization(): BelongsTo { return $this->belongsTo(Organization::class); } public function invitedBy(): BelongsTo { return $this->belongsTo(__CLASS__, 'invited_by_id'); } public function playlists(): BelongsToMany { return $this->belongsToMany(Playlist::class) ->withPivot('role', 'position') ->withTimestamps(); } public function ownedPlaylists(): BelongsToMany { return $this->playlists()->wherePivot('role', 'owner'); } public function collaboratedPlaylists(): BelongsToMany { return $this->playlists()->wherePivot('role', 'collaborator'); } public function playlistFolders(): HasMany { return $this->hasMany(PlaylistFolder::class); } public function interactions(): HasMany { return $this->hasMany(Interaction::class); } public function podcasts(): BelongsToMany { return $this->belongsToMany(Podcast::class) ->using(PodcastUserPivot::class) ->withTimestamps(); } public function radioStations(): HasMany { return $this->hasMany(RadioStation::class); } public function themes(): HasMany { return $this->hasMany(Theme::class); } public function subscribedToPodcast(Podcast $podcast): bool { return $this->podcasts()->whereKey($podcast)->exists(); } public function subscribeToPodcast(Podcast $podcast): void { throw_if( $this->subscribedToPodcast($podcast), UserAlreadySubscribedToPodcastException::create($this, $podcast) ); $this->podcasts()->attach($podcast); } public function unsubscribeFromPodcast(Podcast $podcast): void { $this->podcasts()->detach($podcast); } protected function avatar(): Attribute { return Attribute::get(fn (): string => avatar_or_gravatar(Arr::get($this->attributes, 'avatar'), $this->email)) ->shouldCache(); } protected function hasCustomAvatar(): Attribute { return Attribute::get(fn () => (bool)$this->getRawOriginal('avatar'))->shouldCache(); } protected function isProspect(): Attribute { return Attribute::get(fn (): bool => (bool)$this->invitation_token); } protected function isSso(): Attribute { return Attribute::get(fn (): bool => License::isPlus() && $this->sso_provider)->shouldCache(); } protected function connectedToLastfm(): Attribute { return Attribute::get(fn (): bool => (bool)$this->preferences->lastFmSessionKey)->shouldCache(); } public function getRouteKeyName(): string { return 'public_id'; } /** Delete all old and inactive demo users */ public function prunable(): Builder { if (!config('koel.misc.demo')) { return static::query()->whereRaw('false'); } return static::query() ->where('created_at', '<=', now()->subWeek()) ->where('email', 'like', '%@' . self::DEMO_USER_DOMAIN) ->whereDoesntHave('interactions', static function (Builder $query): void { $query->where('last_played_at', '>=', now()->subDays(7)); }); } protected function role(): Attribute { // Enforce a single-role permission model return Attribute::make( get: function () { $role = $this->getRoleNames(); if ($role->isEmpty()) { return RoleEnum::default(); } return RoleEnum::tryFrom($role->sole()) ?? RoleEnum::default(); }, ); } public function canManage(User $other): bool { return $this->role->canManage($other->role); } public static function getPermissionableIdentifier(): string { return 'public_id'; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Playlist.php
app/Models/Playlist.php
<?php namespace App\Models; use App\Casts\SmartPlaylistRulesCast; use App\Facades\License as LicenseFacade; use App\Models\Concerns\MorphsToEmbeds; use App\Models\Contracts\Embeddable; use App\Models\Song as Playable; use App\Values\SmartPlaylist\SmartPlaylistRuleGroupCollection; use Carbon\Carbon; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Collection as EloquentCollection; use Illuminate\Database\Eloquent\Concerns\HasUuids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Collection; use Laravel\Scout\Searchable; use OwenIt\Auditing\Auditable; use OwenIt\Auditing\Contracts\Auditable as AuditableContract; /** * @property string $id * @property string $name * @property string $description * @property bool $is_smart * @property User $owner * @property ?SmartPlaylistRuleGroupCollection $rule_groups * @property ?SmartPlaylistRuleGroupCollection $rules * @property Carbon $created_at * @property EloquentCollection<array-key, Playable> $playables * @property EloquentCollection<array-key, User> $users * @property EloquentCollection<array-key, User> $collaborators * @property ?string $cover The playlist cover's file name * @property-read EloquentCollection<array-key, PlaylistFolder> $folders * @property-read bool $is_collaborative * @property int $owner_id */ class Playlist extends Model implements AuditableContract, Embeddable { use Auditable; use HasFactory; use HasUuids; use MorphsToEmbeds; use Searchable; protected $hidden = ['created_at', 'updated_at']; protected $guarded = []; protected $casts = [ 'rules' => SmartPlaylistRulesCast::class, ]; protected $appends = ['is_smart']; protected $with = ['users', 'collaborators', 'folders']; public function playables(): BelongsToMany { return $this->belongsToMany(Playable::class) ->withTimestamps() ->withPivot('position') ->orderByPivot('position'); } public function users(): BelongsToMany { return $this->belongsToMany(User::class) ->withPivot('role', 'position') ->withTimestamps(); } protected function owner(): Attribute { return Attribute::get(fn () => $this->users()->wherePivot('role', 'owner')->sole())->shouldCache(); } public function collaborators(): BelongsToMany { return $this->users()->wherePivot('role', 'collaborator'); } public function folders(): BelongsToMany { return $this->belongsToMany(PlaylistFolder::class, null, null, 'folder_id'); } public function collaborationTokens(): HasMany { return $this->hasMany(PlaylistCollaborationToken::class); } protected function isSmart(): Attribute { return Attribute::get(fn (): bool => (bool) $this->rule_groups?->isNotEmpty())->shouldCache(); } protected function ruleGroups(): Attribute { // aliasing the attribute to avoid confusion return Attribute::get(fn () => $this->rules); } public function ownedBy(User $user): bool { return $this->owner->is($user); } public function inFolder(PlaylistFolder $folder): bool { return $this->folders->contains($folder); } public function getFolder(?User $contextUser = null): ?PlaylistFolder { return $this->folders->firstWhere( fn (PlaylistFolder $folder) => $folder->user->is($contextUser ?? $this->owner) ); } public function getFolderId(?User $user = null): ?string { return $this->getFolder($user)?->id; } public function addCollaborator(User $user): void { if (!$this->hasCollaborator($user)) { $this->users()->attach($user, ['role' => 'collaborator']); } } public function hasCollaborator(User $collaborator): bool { return $this->collaborators->contains(static fn (User $user): bool => $collaborator->is($user)); } /** * @param Collection|array<array-key, Playable>|Playable|array<string> $playables */ public function addPlayables(Collection|Playable|array $playables, ?User $collaborator = null): void { $collaborator ??= $this->owner; $maxPosition = $this->playables()->getQuery()->max('position') ?? 0; if (!is_array($playables)) { $playables = Collection::wrap($playables)->pluck('id')->all(); } $data = []; foreach ($playables as $playable) { $data[$playable] = [ 'position' => ++$maxPosition, 'user_id' => $collaborator->id, ]; } $this->playables()->attach($data); } /** * @param Collection<array-key, Playable>|Playable|array<string> $playables */ public function removePlayables(Collection|Playable|array $playables): void { if (!is_array($playables)) { $playables = Collection::wrap($playables)->pluck('id')->all(); } $this->playables()->detach($playables); } protected function isCollaborative(): Attribute { return Attribute::get( fn (): bool => !$this->is_smart && LicenseFacade::isPlus() && $this->collaborators->isNotEmpty() )->shouldCache(); } /** @inheritdoc */ public function toSearchableArray(): array { return [ 'id' => $this->id, 'owner_id' => $this->owner_id, 'name' => $this->name, 'description' => $this->description, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Embed.php
app/Models/Embed.php
<?php namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Concerns\HasUlids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\MorphTo; /** * @property Carbon $created_at * @property Song|Album|Artist|Playlist $embeddable * @property User $user * @property string $id * @property string $embeddable_id * @property string $embeddable_type */ class Embed extends Model { use HasFactory; use HasUlids; protected $guarded = []; protected $with = ['user', 'embeddable']; public function embeddable(): MorphTo { return $this->morphTo(); } public function user(): BelongsTo { return $this->belongsTo(User::class); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Song.php
app/Models/Song.php
<?php namespace App\Models; use App\Builders\SongBuilder; use App\Casts\Podcast\EpisodeMetadataCast; use App\Casts\SongLyricsCast; use App\Casts\SongStorageCast; use App\Casts\SongTitleCast; use App\Enums\PlayableType; use App\Enums\SongStorageType; use App\Models\Concerns\MorphsToEmbeds; use App\Models\Concerns\MorphsToFavorites; use App\Models\Concerns\SupportsDeleteWhereValueNotIn; use App\Models\Contracts\Embeddable; use App\Models\Contracts\Favoriteable; use App\Values\SongStorageMetadata\DropboxMetadata; use App\Values\SongStorageMetadata\LocalMetadata; use App\Values\SongStorageMetadata\S3CompatibleMetadata; use App\Values\SongStorageMetadata\S3LambdaMetadata; use App\Values\SongStorageMetadata\SftpMetadata; use App\Values\SongStorageMetadata\SongStorageMetadata; use Carbon\Carbon; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Concerns\HasUuids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Facades\File; use Laravel\Scout\Searchable; use LogicException; use OwenIt\Auditing\Auditable; use OwenIt\Auditing\Contracts\Auditable as AuditableContract; use PhanAn\Poddle\Values\EpisodeMetadata; use Throwable; use Webmozart\Assert\Assert; /** * @property ?Album $album * @property ?Artist $album_artist * @property ?Artist $artist * @property ?Folder $folder * @property ?bool $favorite Whether the song is liked by the current user (dynamically calculated) * @property ?int $play_count The number of times the song has been played by the current user (dynamically calculated) * @property ?string $album_name * @property ?string $artist_name * @property ?string $basename * @property ?string $folder_id * @property ?string $mime_type The MIME type of the song file, if available * @property Carbon $created_at * @property Collection<Genre>|array<array-key, Genre> $genres * @property SongStorageType $storage * @property User $owner * @property bool $is_public * @property float $length * @property string $album_id * @property string $artist_id * @property int $disc * @property int $mtime * @property ?string $hash The hash of the song file. Null for legacy songs. * @property int $owner_id * @property int $track * @property ?int $year * @property ?int $file_size The size in bytes of the song file, if available. * @property string $id * @property string $lyrics * @property string $path * @property string $title * @property-read SongStorageMetadata $storage_metadata * @property-read ?string $genre The string representation of the genres associated with the song. Readonly. * To set the genres, use the `syncGenres` method. * * // The following are only available for collaborative playlists * @property-read ?string $collaborator_email The email of the user who added the song to the playlist * @property-read ?string $collaborator_name The name of the user who added the song to the playlist * @property-read ?string $collaborator_avatar The avatar of the user who added the song to the playlist * @property-read ?string $collaborator_public_id The public ID of the user who added the song to the playlist * @property-read ?string $added_at The date the song was added to the playlist * @property-read PlayableType $type * * // Podcast episode properties * @property ?EpisodeMetadata $episode_metadata * @property ?string $episode_guid * @property ?string $podcast_id * @property ?Podcast $podcast */ class Song extends Model implements AuditableContract, Favoriteable, Embeddable { use Auditable; use HasFactory; use HasUuids; use MorphsToEmbeds; use MorphsToFavorites; use Searchable; use SupportsDeleteWhereValueNotIn; protected $guarded = []; protected $hidden = ['updated_at', 'path', 'mtime']; protected $casts = [ 'title' => SongTitleCast::class, 'lyrics' => SongLyricsCast::class, 'length' => 'float', 'file_size' => 'int', 'mtime' => 'int', 'track' => 'int', 'disc' => 'int', 'year' => 'int', 'is_public' => 'bool', 'storage' => SongStorageCast::class, 'episode_metadata' => EpisodeMetadataCast::class, 'favorite' => 'bool', ]; protected $with = ['album', 'artist', 'album.artist', 'podcast', 'genres', 'owner']; public static function query(?PlayableType $type = null, ?User $user = null): SongBuilder { return parent::query() ->when($user, static fn (SongBuilder $query) => $query->setScopedUser($user)) // @phpstan-ignore-line ->when($type, static fn (SongBuilder $query) => match ($type) { // @phpstan-ignore-line phpcs:ignore PlayableType::SONG => $query->whereNull('songs.podcast_id'), PlayableType::PODCAST_EPISODE => $query->whereNotNull('songs.podcast_id'), default => $query, }) ->addSelect('songs.*'); } public function owner(): BelongsTo { return $this->belongsTo(User::class); } public function newEloquentBuilder($query): SongBuilder { return new SongBuilder($query); } public function artist(): BelongsTo { return $this->belongsTo(Artist::class); } public function album(): BelongsTo { return $this->belongsTo(Album::class); } public function podcast(): BelongsTo { return $this->belongsTo(Podcast::class); } public function folder(): BelongsTo { return $this->belongsTo(Folder::class); } public function playlists(): BelongsToMany { return $this->belongsToMany(Playlist::class); } public function interactions(): HasMany { return $this->hasMany(Interaction::class); } public function genres(): BelongsToMany { return $this->belongsToMany(Genre::class); } protected function albumArtist(): Attribute { return Attribute::get(fn () => $this->album?->artist)->shouldCache(); } protected function type(): Attribute { return Attribute::get(fn () => $this->podcast_id ? PlayableType::PODCAST_EPISODE : PlayableType::SONG); } public function accessibleBy(User $user): bool { if ($this->isEpisode()) { return $user->subscribedToPodcast($this->podcast); } return $this->is_public || $this->ownedBy($user); } public function ownedBy(User $user): bool { return $this->owner->id === $user->id; } protected function storageMetadata(): Attribute { return (new Attribute( get: function (): SongStorageMetadata { try { switch ($this->storage) { case SongStorageType::SFTP: preg_match('/^sftp:\\/\\/(.*)/', $this->path, $matches); return SftpMetadata::make($matches[1]); case SongStorageType::S3: preg_match('/^s3:\\/\\/(.*)\\/(.*)/', $this->path, $matches); return S3CompatibleMetadata::make($matches[1], $matches[2]); case SongStorageType::S3_LAMBDA: preg_match('/^s3:\\/\\/(.*)\\/(.*)/', $this->path, $matches); return S3LambdaMetadata::make($matches[1], $matches[2]); case SongStorageType::DROPBOX: preg_match('/^dropbox:\\/\\/(.*)/', $this->path, $matches); return DropboxMetadata::make($matches[1]); default: return LocalMetadata::make($this->path); } } catch (Throwable) { return LocalMetadata::make($this->path); } } ))->shouldCache(); } protected function basename(): Attribute { return Attribute::get(function () { Assert::eq($this->type, PlayableType::SONG); return File::basename($this->path); }); } protected function genre(): Attribute { return Attribute::get(fn () => $this->genres->pluck('name')->implode(', '))->shouldCache(); } public function syncGenres(string|array $genres): void { $genreNames = is_array($genres) ? $genres : explode(',', $genres); $genreIds = collect($genreNames) ->map(static fn (string $name) => trim($name)) ->filter() ->unique() ->map(static fn (string $name) => Genre::get($name)->id); $this->genres()->sync($genreIds); } public static function getPathFromS3BucketAndKey(string $bucket, string $key): string { return "s3://$bucket/$key"; } /** @inheritdoc */ public function toSearchableArray(): array { $array = [ 'id' => $this->id, 'owner_id' => $this->owner_id, 'title' => $this->title, 'type' => $this->type->value, ]; if ($this->episode_metadata?->description) { $array['episode_description'] = $this->episode_metadata->description; } if ( $this->artist_name && $this->artist_name !== Artist::UNKNOWN_NAME && $this->artist_name !== Artist::VARIOUS_NAME ) { $array['artist'] = $this->artist_name; } return $array; } public function isEpisode(): bool { return $this->type === PlayableType::PODCAST_EPISODE; } public function genreEqualsTo(string|array $genres): bool { $genreNames = collect(is_string($genres) ? explode(',', $genres) : $genres) ->map(static fn (string $name) => trim($name)) ->filter() ->unique() ->sort() ->join(', '); if (!$this->genre && !$genreNames) { return true; } return $this->genre === $genreNames; } public function isStoredOnCloud(): bool { return in_array($this->storage, [ SongStorageType::S3, SongStorageType::S3_LAMBDA, SongStorageType::DROPBOX, ], true); } /** * Determine if the song's associated file has been modified since the last scan. * This is done by comparing the stored hash or mtime with the corresponding * value from the scan information. */ public function isFileModified(int $lastModified): bool { throw_if($this->isEpisode(), new LogicException('Podcast episodes do not have associated files.')); return $this->mtime !== $lastModified; } public function __toString(): string { return $this->id; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Genre.php
app/Models/Genre.php
<?php namespace App\Models; use App\Builders\GenreBuilder; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Laravel\Scout\Searchable; /** * @property int $id * @property string $public_id * @property string $name */ class Genre extends Model { use HasFactory; use Searchable; public const NO_GENRE_PUBLIC_ID = 'no-genre'; public const NO_GENRE_NAME = ''; public $timestamps = false; protected $fillable = [ 'public_id', 'name', ]; public static function query(): GenreBuilder { /** @var GenreBuilder */ return parent::query(); } public function newEloquentBuilder($query): GenreBuilder { return new GenreBuilder($query); } public function songs(): BelongsToMany { return $this->belongsToMany(Song::class); } public function getRouteKeyName(): string { return 'public_id'; } public static function get(string $name): static { $name = trim($name); /** @var static */ return static::query()->firstOrCreate( ['name' => $name], ); } /** @inheritdoc */ public function toSearchableArray(): array { return [ 'id' => $this->id, 'name' => $this->name, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Podcast.php
app/Models/Podcast.php
<?php namespace App\Models; use App\Builders\PodcastBuilder; use App\Casts\Podcast\CategoriesCast; use App\Casts\Podcast\PodcastMetadataCast; use App\Models\Concerns\MorphsToFavorites; use App\Models\Contracts\Favoriteable; use App\Models\Song as Episode; use Carbon\Carbon; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Concerns\HasUuids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\HasMany; use Laravel\Scout\Searchable; use PhanAn\Poddle\Values\CategoryCollection; use PhanAn\Poddle\Values\ChannelMetadata; /** * @property string $id * @property string $url * @property string $title * @property string $description * @property CategoryCollection $categories * @property ChannelMetadata $metadata * @property string $image * @property string $link * @property Collection<User> $subscribers * @property Collection<Episode> $episodes * @property int $added_by * @property Carbon $last_synced_at * @property ?string $author */ class Podcast extends Model implements Favoriteable { use HasFactory; use HasUuids; use MorphsToFavorites; use Searchable; protected $hidden = ['created_at', 'updated_at']; protected $guarded = []; protected $casts = [ 'categories' => CategoriesCast::class, 'metadata' => PodcastMetadataCast::class, 'last_synced_at' => 'datetime', 'explicit' => 'boolean', ]; public static function query(): PodcastBuilder { /** @var PodcastBuilder */ return parent::query()->addSelect('podcasts.*'); } public function newEloquentBuilder($query): PodcastBuilder { return new PodcastBuilder($query); } public function episodes(): HasMany { return $this->hasMany(Episode::class)->orderByDesc('created_at'); } public function subscribers(): BelongsToMany { return $this->belongsToMany(User::class) ->using(PodcastUserPivot::class) ->withPivot('state') ->withTimestamps(); } /** @return array<mixed> */ public function toSearchableArray(): array { return [ 'id' => $this->id, 'url' => $this->url, 'title' => $this->title, 'description' => $this->description, 'author' => $this->metadata->author, ]; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/License.php
app/Models/License.php
<?php namespace App\Models; use App\Casts\EncryptedValueCast; use App\Casts\LicenseInstanceCast; use App\Casts\LicenseMetaCast; use App\Values\License\LicenseInstance; use App\Values\License\LicenseMeta; use Carbon\Carbon; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; /** * @property-read string $short_key * @property string $key * @property LicenseInstance $instance An activation of the license. * @see https://docs.lemonsqueezy.com/api/license-key-instances * @property LicenseMeta $meta * @property-read Carbon $activated_at */ class License extends Model { use HasFactory; protected $guarded = ['id']; protected $casts = [ 'key' => EncryptedValueCast::class, 'instance' => LicenseInstanceCast::class, 'meta' => LicenseMetaCast::class, 'expires_at' => 'datetime', ]; protected function shortKey(): Attribute { return Attribute::get(fn (): string => '****-' . Str::afterLast($this->key, '-'))->shouldCache(); } protected function activatedAt(): Attribute { return Attribute::get(fn () => $this->instance->createdAt)->shouldCache(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Favorite.php
app/Models/Favorite.php
<?php namespace App\Models; use App\Models\Contracts\Favoriteable; use Carbon\Carbon; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\MorphTo; /** * @property Carbon $created_at * @property Favoriteable $favoriteable * @property User $user * @property int $id * @property string $favoriteable_id * @property string $favoriteable_type */ class Favorite extends Model { use HasFactory; protected $guarded = []; public $timestamps = false; protected $with = ['user', 'favoriteable']; protected $casts = [ 'created_at' => 'datetime', ]; public static function booted(): void { static::creating(static function (self $favorite): void { $favorite->created_at ??= now(); }); } public function favoriteable(): MorphTo { return $this->morphTo(); } public function user(): BelongsTo { return $this->belongsTo(User::class); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Folder.php
app/Models/Folder.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Concerns\HasUuids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Arr; /** * @property string $id * @property string $path * @property Collection<array-key, Song> $songs * @property ?Folder $parent * @property Collection<array-key, Folder> $subfolders * @property-read string $name * @property-read bool $is_uploads_folder Where the folder is the uploads folder by any user * @property-read ?int $uploader_id * @property ?string $parent_id * @property string $hash */ class Folder extends Model { use HasFactory; use HasUuids; protected $guarded = []; public $timestamps = false; protected $appends = ['name']; public function songs(): HasMany { return $this->hasMany(Song::class)->orderBy('path'); } public function parent(): BelongsTo { return $this->belongsTo(__CLASS__); } public function subfolders(): HasMany { return $this->hasMany(__CLASS__, 'parent_id')->orderBy('path'); } public function browsableBy(User $user): bool { return !$this->is_uploads_folder || $this->uploader_id === $user->id; } protected function name(): Attribute { return Attribute::get(fn () => Arr::last(explode(DIRECTORY_SEPARATOR, $this->path))); } protected function isUploadsFolder(): Attribute { // An uploads folder has a format of __KOEL_UPLOADS_$<id>__ and is a child of the root folder // (i.e., it has no parent). return Attribute::get( fn () => !$this->parent_id && preg_match('/^__KOEL_UPLOADS_\$\d+__$/', $this->name) === 1 ); } protected function uploaderId(): Attribute { return Attribute::get(function () { if (!$this->is_uploads_folder) { return null; } $matches = []; preg_match('/^__KOEL_UPLOADS_\$(\d+)__$/', $this->name, $matches); return (int) Arr::get($matches, 1); })->shouldCache(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/QueueState.php
app/Models/QueueState.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * @property array<string> $song_ids * @property ?string $current_song_id * @property int $playback_position * @property User $user */ class QueueState extends Model { use HasFactory; protected $guarded = ['id']; protected $casts = [ 'song_ids' => 'array', 'playback_position' => 'int', ]; public function user(): BelongsTo { return $this->belongsTo(User::class); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/PlaylistFolder.php
app/Models/PlaylistFolder.php
<?php namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Concerns\HasUuids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use OwenIt\Auditing\Auditable; use OwenIt\Auditing\Contracts\Auditable as AuditableContract; /** * @property string $name * @property User $user * @property Collection<array-key, Playlist> $playlists * @property int $user_id * @property Carbon $created_at * @property ?string $id */ class PlaylistFolder extends Model implements AuditableContract { use Auditable; use HasFactory; use HasUuids; protected $guarded = ['id']; protected $with = ['user']; public function playlists(): BelongsToMany { return $this->belongsToMany(Playlist::class, null, 'folder_id'); } public function user(): BelongsTo { return $this->belongsTo(User::class); } public function ownedBy(User $user): bool { return $this->user->is($user); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Setting.php
app/Models/Setting.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use OwenIt\Auditing\Auditable; use OwenIt\Auditing\Contracts\Auditable as AuditableContract; /** * @property string $key * @property mixed $value * * @method static self find(string $key) */ class Setting extends Model implements AuditableContract { use Auditable; use HasFactory; protected $primaryKey = 'key'; protected $keyType = 'string'; public $timestamps = false; protected $guarded = []; protected $casts = ['value' => 'json']; public static function get(string $key): mixed { return self::find($key)?->value; } /** * Set a setting (no pun) value. * * @param array|string $key the key of the setting, or an associative array of settings, * in which case $value will be discarded */ public static function set(array|string $key, $value = ''): void { if (is_array($key)) { foreach ($key as $k => $v) { self::set($k, $v); } return; } self::query()->updateOrCreate(compact('key'), compact('value')); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/PodcastUserPivot.php
app/Models/PodcastUserPivot.php
<?php namespace App\Models; use App\Casts\Podcast\PodcastStateCast; use App\Values\Podcast\PodcastState; use Carbon\Carbon; use Illuminate\Database\Eloquent\Relations\Pivot; /** * @property Carbon $created_at * @property Carbon $updated_at * @property PodcastState $state */ class PodcastUserPivot extends Pivot { protected $table = 'podcast_user'; protected $guarded = []; protected $casts = [ 'state' => PodcastStateCast::class, ]; }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Album.php
app/Models/Album.php
<?php namespace App\Models; use App\Builders\AlbumBuilder; use App\Models\Concerns\MorphsToEmbeds; use App\Models\Concerns\MorphsToFavorites; use App\Models\Concerns\SupportsDeleteWhereValueNotIn; use App\Models\Contracts\Embeddable; use App\Models\Contracts\Favoriteable; use App\Models\Contracts\Permissionable; use Carbon\Carbon; use Database\Factories\UserFactory; use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Concerns\HasUlids; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Support\Str; use Laravel\Scout\Searchable; use OwenIt\Auditing\Auditable; use OwenIt\Auditing\Contracts\Auditable as AuditableContract; /** * @property ?boolean $favorite Whether the album is liked by the scoped user * @property ?int $year * @property ?string $thumbnail The album's thumbnail file name * @property Artist $artist The album's artist * @property Carbon $created_at * @property Collection<array-key, Song> $songs * @property User $user * @property bool $is_unknown If the album is the Unknown Album * @property int $user_id * @property string $artist_id * @property string $artist_name * @property string $cover The album cover's file name * @property string $id * @property string $name Name of the album */ class Album extends Model implements AuditableContract, Embeddable, Favoriteable, Permissionable { use Auditable; /** @use HasFactory<UserFactory> */ use HasFactory; use HasUlids; use MorphsToEmbeds; use MorphsToFavorites; use Searchable; use SupportsDeleteWhereValueNotIn; public const UNKNOWN_NAME = 'Unknown Album'; protected $guarded = ['id']; protected $hidden = ['updated_at']; protected $with = ['artist']; /** @deprecated */ protected $appends = ['is_compilation']; public static function query(): AlbumBuilder { /** @var AlbumBuilder */ return parent::query()->addSelect('albums.*'); } public function newEloquentBuilder($query): AlbumBuilder { return new AlbumBuilder($query); } /** * Get an album using some provided information. * If such is not found, a new album will be created using the information. */ public static function getOrCreate(Artist $artist, ?string $name = null): static { return static::query()->firstOrCreate([ // @phpstan-ignore-line 'artist_id' => $artist->id, 'artist_name' => $artist->name, 'user_id' => $artist->user_id, 'name' => trim($name) ?: self::UNKNOWN_NAME, ]); } public function artist(): BelongsTo { return $this->belongsTo(Artist::class); } public function songs(): HasMany { return $this->hasMany(Song::class); } public function user(): BelongsTo { return $this->belongsTo(User::class); } public function belongsToUser(User $user): bool { return $this->user_id === $user->id; } protected function isUnknown(): Attribute { return Attribute::get(fn (): bool => $this->name === self::UNKNOWN_NAME); } /** * Sometimes the tags extracted from getID3 are HTML entity encoded. * This makes sure they are always sane. */ protected function name(): Attribute { return Attribute::get(static fn (?string $value) => html_entity_decode($value))->shouldCache(); } protected function thumbnail(): Attribute { return Attribute::get(function (): ?string { if (!$this->cover) { return null; } return sprintf('%s_thumb.%s', Str::beforeLast($this->cover, '.'), Str::afterLast($this->cover, '.')); })->shouldCache(); } /** @deprecated Only here for backward compat with mobile apps */ protected function isCompilation(): Attribute { return Attribute::get(fn () => $this->artist->is_various); } /** @inheritdoc */ public function toSearchableArray(): array { $array = [ 'id' => $this->id, 'user_id' => $this->user_id, 'name' => $this->name, ]; if ( $this->artist_name && $this->artist_name !== Artist::UNKNOWN_NAME && $this->artist_name !== Artist::VARIOUS_NAME ) { $array['artist'] = $this->artist_name; } return $array; } public static function getPermissionableIdentifier(): string { return 'id'; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Contracts/Embeddable.php
app/Models/Contracts/Embeddable.php
<?php namespace App\Models\Contracts; use Illuminate\Database\Eloquent\Relations\MorphMany; /** * @property-read string $id */ interface Embeddable { public function embeds(): MorphMany; }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Contracts/Favoriteable.php
app/Models/Contracts/Favoriteable.php
<?php namespace App\Models\Contracts; use Illuminate\Database\Eloquent\Relations\MorphMany; /** * @property string $id * @property bool $favorite */ interface Favoriteable { public function favorites(): MorphMany; }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Contracts/Permissionable.php
app/Models/Contracts/Permissionable.php
<?php namespace App\Models\Contracts; interface Permissionable { public static function getPermissionableIdentifier(): string; }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Concerns/MorphsToFavorites.php
app/Models/Concerns/MorphsToFavorites.php
<?php namespace App\Models\Concerns; use App\Models\Favorite; use Illuminate\Database\Eloquent\Relations\MorphMany; trait MorphsToFavorites { public function favorites(): MorphMany { return $this->morphMany(Favorite::class, 'favoriteable'); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Concerns/SupportsDeleteWhereValueNotIn.php
app/Models/Concerns/SupportsDeleteWhereValueNotIn.php
<?php namespace App\Models\Concerns; use Closure; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Facades\DB; /** * With reference to GitHub issue #463. * MySQL and PostgresSQL seem to have a limit of 2^16-1 (65535) elements in an IN statement. * This trait provides a method as a workaround to this limitation. * * @method static Builder query() */ trait SupportsDeleteWhereValueNotIn { /** * Deletes all records whose certain value is not in an array. */ public static function deleteWhereValueNotIn( array $values, ?string $field = null, ?Closure $queryModifier = null ): void { $field ??= (new static())->getKeyName(); $queryModifier ??= static fn (Builder $builder) => $builder; $maxChunkSize = DB::getDriverName() === 'sqlite' ? 999 : 65_535; if (count($values) <= $maxChunkSize) { $queryModifier(static::query())->whereNotIn($field, $values)->delete(); return; } $allIds = static::query()->select($field)->get()->pluck($field)->all(); $deletableIds = array_diff($allIds, $values); if (count($deletableIds) < $maxChunkSize) { $queryModifier(static::query())->whereIn($field, $deletableIds)->delete(); return; } static::deleteByChunk($deletableIds, $maxChunkSize, $field); } public static function deleteByChunk(array $values, int $chunkSize = 65_535, ?string $field = null): void { $field ??= (new static())->getKeyName(); DB::transaction(static function () use ($values, $field, $chunkSize): void { foreach (array_chunk($values, $chunkSize) as $chunk) { static::query()->whereIn($field, $chunk)->delete(); } }); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Models/Concerns/MorphsToEmbeds.php
app/Models/Concerns/MorphsToEmbeds.php
<?php namespace App\Models\Concerns; use App\Models\Embed; use Illuminate\Database\Eloquent\Relations\MorphMany; trait MorphsToEmbeds { public function embeds(): MorphMany { return $this->morphMany(Embed::class, 'embeddable'); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/SettingRepository.php
app/Repositories/SettingRepository.php
<?php namespace App\Repositories; use App\Models\Setting; /** @extends Repository<Setting> */ class SettingRepository extends Repository { /** @return array<mixed> */ public function getAllAsKeyValueArray(): array { return $this->modelClass::query()->pluck('value', 'key')->toArray(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/ArtistRepository.php
app/Repositories/ArtistRepository.php
<?php namespace App\Repositories; use App\Models\Artist; use App\Models\User; use App\Repositories\Contracts\ScoutableRepository; use Illuminate\Contracts\Pagination\Paginator; use Illuminate\Database\Eloquent\Collection; /** * @extends Repository<Artist> * @implements ScoutableRepository<Artist> */ class ArtistRepository extends Repository implements ScoutableRepository { /** * @param string $id */ public function getOne($id, ?User $user = null): Artist { return Artist::query() ->withUserContext(user: $user ?? $this->auth->user()) ->findOrFail($id); } /** @return Collection|array<array-key, Artist> */ public function getMostPlayed(int $count = 6, ?User $user = null): Collection { return Artist::query() ->withUserContext(user: $user ?? $this->auth->user(), includePlayCount: true) ->onlyStandard() ->orderByDesc('play_count') ->limit($count) ->get(); } /** @return Collection|array<array-key, Artist> */ public function getMany(array $ids, bool $preserveOrder = false, ?User $user = null): Collection { $artists = Artist::query() ->onlyStandard() ->withUserContext(user: $user ?? $this->auth->user()) ->whereIn('artists.id', $ids) ->get(); return $preserveOrder ? $artists->orderByArray($ids) : $artists; } public function getForListing( string $sortColumn, string $sortDirection, bool $favoritesOnly = false, ?User $user = null, ): Paginator { return Artist::query() ->withUserContext(user: $user ?? $this->auth->user(), favoritesOnly: $favoritesOnly) ->onlyStandard() ->sort($sortColumn, $sortDirection) ->simplePaginate(21); } /** @return Collection<Artist>|array<array-key, Artist> */ public function search(string $keywords, int $limit, ?User $user = null): Collection { return $this->getMany( ids: Artist::search($keywords)->get()->take($limit)->modelKeys(), preserveOrder: true, user: $user, ); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/ThemeRepository.php
app/Repositories/ThemeRepository.php
<?php namespace App\Repositories; use App\Models\Theme; use App\Models\User; use Illuminate\Database\Eloquent\Collection; /** * @extends Repository<Theme> */ class ThemeRepository extends Repository { /** @return Collection<Theme>|array<array-key, Theme> */ public function getAllByUser(User $user): Collection { return $user->themes->sortByDesc('created_at'); } public function findUserThemeById(string $id, User $user): ?Theme { return Theme::query()->whereBelongsTo($user)->find($id); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/RadioStationRepository.php
app/Repositories/RadioStationRepository.php
<?php namespace App\Repositories; use App\Models\Podcast; use App\Models\RadioStation; use App\Models\User; use App\Repositories\Contracts\ScoutableRepository; use Illuminate\Database\Eloquent\Collection; /** @extends Repository<RadioStation> */ class RadioStationRepository extends Repository implements ScoutableRepository { /** @return Collection<Podcast>|array<array-key, Podcast> */ public function getMany(array $ids, bool $preserveOrder = false, ?User $user = null): Collection { $stations = RadioStation::query() ->withUserContext(user: $user ?? $this->auth->user()) ->whereIn('radio_stations.id', $ids) ->get(); return $preserveOrder ? $stations->orderByArray($ids) : $stations; } /** @return Collection<RadioStation>|array<array-key, RadioStation> */ public function search(string $keywords, int $limit, ?User $user = null): Collection { return $this->getMany( ids: RadioStation::search($keywords)->get()->take($limit)->modelKeys(), preserveOrder: true, user: $user, ); } /** @return Collection<RadioStation>|array<array-key, RadioStation> */ public function getAllForUser(User $user): Collection { return RadioStation::query() ->withUserContext(user: $user) ->get(); } public function findOneWithUserContext(string $id, User $user, bool $withFavoriteStatus = true): RadioStation { return RadioStation::query() ->withUserContext( user: $user, includeFavoriteStatus: $withFavoriteStatus, )->findOrFail($id); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/GenreRepository.php
app/Repositories/GenreRepository.php
<?php namespace App\Repositories; use App\Enums\PlayableType; use App\Models\Genre; use App\Models\Song; use App\Models\User; use App\Values\GenreSummary; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; /** @extends Repository<Genre> */ class GenreRepository extends Repository { /** @return Collection<GenreSummary>|array<array-key, GenreSummary> */ public function getAllSummaries(?User $scopedUser = null): Collection { $genres = Genre::query() ->join('genre_song', 'genre_song.genre_id', '=', 'genres.id') ->join('songs', 'songs.id', '=', 'genre_song.song_id') ->accessibleBy($scopedUser ?? auth()->user()) ->groupBy('genres.id', 'genres.name', 'genres.public_id') ->orderBy('genres.name') ->select( 'genres.public_id', 'genres.name', DB::raw('COUNT(songs.id) AS song_count'), DB::raw('SUM(songs.length) AS length') ) ->get() ->map( static fn (object $genre) => GenreSummary::make( publicId: $genre->public_id, name: $genre->name, songCount: $genre->song_count, length: $genre->length ) ); $summaryForNoGenre = $this->getSummaryForNoGenre($scopedUser); // Only add the "No Genre" stats if there are indeed songs without a genre if ($summaryForNoGenre->songCount > 0) { $genres->unshift($summaryForNoGenre); } return $genres; } public function getSummaryForGenre(Genre $genre, ?User $scopedUser = null): GenreSummary { /** @var object $result */ $result = Song::query(type: PlayableType::SONG, user: $scopedUser ?? auth()->user()) ->accessible() ->join('genre_song', 'songs.id', '=', 'genre_song.song_id') ->join('genres', 'genre_song.genre_id', '=', 'genres.id') ->where('genres.id', $genre->id) ->groupBy('genres.public_id', 'genres.name') ->select( 'genres.public_id', 'genres.name', DB::raw('COUNT(songs.id) AS song_count'), DB::raw('SUM(songs.length) AS length') ) ->firstOrFail(); return GenreSummary::make( publicId: $result->public_id, name: $result->name, songCount: $result->song_count, length: $result->length ); } public function getSummaryForNoGenre(?User $scopedUser = null): GenreSummary { /** @var object $result */ $result = Song::query(type: PlayableType::SONG, user: $scopedUser ?? auth()->user()) ->accessible() ->leftJoin('genre_song', 'songs.id', '=', 'genre_song.song_id') ->whereNull('genre_song.genre_id') ->select( DB::raw('COUNT(songs.id) AS song_count'), DB::raw('SUM(songs.length) AS length') ) ->firstOrFail(); return GenreSummary::make( publicId: Genre::NO_GENRE_PUBLIC_ID, name: Genre::NO_GENRE_NAME, songCount: (int) $result->song_count, length: (float) $result->length ); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/TranscodeRepository.php
app/Repositories/TranscodeRepository.php
<?php namespace App\Repositories; use App\Models\Transcode; use Illuminate\Database\Eloquent\Collection; /** * @extends Repository<Transcode> */ class TranscodeRepository extends Repository { /** * @param array<string> $songIds * * @return Collection<Transcode>|array<array-key, Transcode> */ public function findBySongIds(array $songIds): Collection { return Transcode::query()->whereIn('song_id', $songIds)->get(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/AlbumRepository.php
app/Repositories/AlbumRepository.php
<?php namespace App\Repositories; use App\Models\Album; use App\Models\Artist; use App\Models\User; use App\Repositories\Contracts\ScoutableRepository; use Illuminate\Contracts\Pagination\Paginator; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; /** * @extends Repository<Album> * @implements ScoutableRepository<Album> */ class AlbumRepository extends Repository implements ScoutableRepository { /** * @param string $id */ public function getOne($id, ?User $user = null): Album { return Album::query() ->withUserContext(user: $user ?? $this->auth->user()) ->findOrFail($id); } /** @return Collection|array<array-key, Album> */ public function getRecentlyAdded(int $count = 6, ?User $user = null): Collection { return Album::query() ->onlyStandard() ->withUserContext(user: $user ?? $this->auth->user()) ->latest() ->limit($count) ->get(); } /** @return Collection|array<array-key, Album> */ public function getMostPlayed(int $count = 6, ?User $user = null): Collection { return Album::query() ->onlyStandard() ->withUserContext(user: $user ?? $this->auth->user(), includePlayCount: true) ->orderByDesc('play_count') ->limit($count) ->get(); } /** @return Collection|array<array-key, Album> */ public function getMany(array $ids, bool $preserveOrder = false, ?User $user = null): Collection { $albums = Album::query() ->onlyStandard() ->withUserContext(user: $user ?? $this->auth->user()) ->whereIn('albums.id', $ids) ->get(); return $preserveOrder ? $albums->orderByArray($ids) : $albums; } /** @return Collection|array<array-key, Album> */ public function getByArtist(Artist $artist, ?User $user = null): Collection { return Album::query() ->withUserContext(user: $user ?? $this->auth->user()) ->where(static function (Builder $query) use ($artist): void { $query->whereBelongsTo($artist) ->orWhereHas('songs', static function (Builder $songQuery) use ($artist): void { $songQuery->whereBelongsTo($artist); }); }) ->orderBy('albums.name') ->get(); } public function getForListing( string $sortColumn, string $sortDirection, bool $favoritesOnly = false, ?User $user = null, ): Paginator { return Album::query() ->onlyStandard() ->withUserContext(user: $user ?? $this->auth->user(), favoritesOnly: $favoritesOnly) ->sort($sortColumn, $sortDirection) ->simplePaginate(21); } /** @return Collection<Album>|array<array-key, Album> */ public function search(string $keywords, int $limit, ?User $user = null): Collection { return $this->getMany( ids: Album::search($keywords)->get()->take($limit)->modelKeys(), preserveOrder: true, user: $user, ); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/OrganizationRepository.php
app/Repositories/OrganizationRepository.php
<?php namespace App\Repositories; use App\Models\Organization; /** * @extends Repository<Organization> */ class OrganizationRepository extends Repository { public function getDefault(): Organization { return Organization::default(); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/Repository.php
app/Repositories/Repository.php
<?php namespace App\Repositories; use App\Repositories\Contracts\Repository as RepositoryContract; use Illuminate\Contracts\Auth\Guard; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; /** * @template T of Model * @implements RepositoryContract<T> */ abstract class Repository implements RepositoryContract { /** @var class-string<T> $modelClass */ public string $modelClass; protected Guard $auth; /** @param class-string<T> $modelClass */ public function __construct(?string $modelClass = null) { $this->modelClass = $modelClass ?: self::guessModelClass(); // This instantiation may fail during a console command if e.g. APP_KEY is empty, // rendering the whole installation failing. rescue(fn () => $this->auth = app(Guard::class)); } /** @return class-string<T> */ private static function guessModelClass(): string { return preg_replace('/(.+)\\\\Repositories\\\\(.+)Repository$/m', '$1\Models\\\$2', static::class); } /** @inheritDoc */ public function getOne($id): Model { return $this->modelClass::query()->findOrFail($id); } /** @inheritDoc */ public function findOne($id): ?Model { return $this->modelClass::query()->find($id); } /** @inheritDoc */ public function getOneBy(array $params): Model { return $this->modelClass::query()->where($params)->firstOrFail(); } /** @inheritDoc */ public function findOneBy(array $params): ?Model { return $this->modelClass::query()->where($params)->first(); } /** @inheritDoc */ public function getMany(array $ids, bool $preserveOrder = false): Collection { $models = $this->modelClass::query()->find($ids); return $preserveOrder ? $models->orderByArray($ids) : $models; } /** @inheritDoc */ // @phpcs:ignore public function getAll(): Collection { return $this->modelClass::all(); // @phpstan-ignore-line } /** @inheritDoc */ public function findFirstWhere(...$params): ?Model { return $this->modelClass::query()->firstWhere(...$params); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/PodcastRepository.php
app/Repositories/PodcastRepository.php
<?php namespace App\Repositories; use App\Models\Podcast; use App\Models\User; use App\Repositories\Contracts\ScoutableRepository; use Illuminate\Database\Eloquent\Collection; /** @extends Repository<Podcast> */ class PodcastRepository extends Repository implements ScoutableRepository { public function findOneByUrl(string $url): ?Podcast { return $this->findOneBy(['url' => $url]); } /** @return Collection<Podcast>|array<array-key, Podcast> */ public function getAllSubscribedByUser(bool $favoritesOnly, ?User $user = null): Collection { return Podcast::query() ->with('subscribers') ->setScopedUser($user ?? $this->auth->user()) ->withFavoriteStatus(favoritesOnly: $favoritesOnly) ->subscribed() ->get(); } /** @return Collection<Podcast>|array<array-key, Podcast> */ public function getMany(array $ids, bool $preserveOrder = false, ?User $user = null): Collection { $podcasts = Podcast::query() ->with('subscribers') ->setScopedUser($user ?? $this->auth->user()) ->subscribed() ->whereIn('podcasts.id', $ids) ->distinct() ->get(); return $preserveOrder ? $podcasts->orderByArray($ids) : $podcasts; } /** @return Collection<Podcast>|array<array-key, Podcast> */ public function search(string $keywords, int $limit, ?User $user = null): Collection { return $this->getMany( ids: Podcast::search($keywords)->get()->take($limit)->modelKeys(), preserveOrder: true, user: $user, ); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/SongRepository.php
app/Repositories/SongRepository.php
<?php namespace App\Repositories; use App\Builders\SongBuilder; use App\Enums\EmbeddableType; use App\Enums\PlayableType; use App\Exceptions\EmbeddableNotFoundException; use App\Exceptions\NonSmartPlaylistException; use App\Facades\License; use App\Models\Album; use App\Models\Artist; use App\Models\Embed; use App\Models\Folder; use App\Models\Genre; use App\Models\Playlist; use App\Models\Podcast; use App\Models\Song; use App\Models\User; use App\Repositories\Contracts\ScoutableRepository; use App\Values\SmartPlaylist\SmartPlaylistQueryModifier as QueryModifier; use App\Values\SmartPlaylist\SmartPlaylistRule as Rule; use App\Values\SmartPlaylist\SmartPlaylistRuleGroup as RuleGroup; use Illuminate\Contracts\Pagination\Paginator; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Collection; use LogicException; /** * @extends Repository<Song> * @implements ScoutableRepository<Song> */ class SongRepository extends Repository implements ScoutableRepository { private const LIST_SIZE_LIMIT = 500; public function __construct(private readonly FolderRepository $folderRepository) { parent::__construct(); } public function findOneByPath(string $path): ?Song { return Song::query()->where('path', $path)->first(); } /** @return Collection|array<array-key, Song> */ public function getAllStoredOnCloud(): Collection { return Song::query()->storedOnCloud()->get(); } /** @return Collection|array<array-key, Song> */ public function getRecentlyAdded(int $count = 8, ?User $scopedUser = null): Collection { return Song::query(type: PlayableType::SONG, user: $scopedUser ?? $this->auth->user()) ->withUserContext() ->latest() ->limit($count) ->get(); } /** @return Collection|array<array-key, Song> */ public function getMostPlayed(int $count = 8, ?User $scopedUser = null): Collection { return Song::query(user: $scopedUser ?? $this->auth->user()) ->withUserContext() ->where('interactions.play_count', '>', 0) ->orderByDesc('interactions.play_count') ->limit($count) ->get(); } /** @return Collection|array<array-key, Song> */ public function getRecentlyPlayed(int $count = 8, ?User $scopedUser = null): Collection { return Song::query(user: $scopedUser ?? $this->auth->user()) ->withUserContext() ->where('interactions.play_count', '>', 0) ->addSelect('interactions.last_played_at') ->orderByDesc('interactions.last_played_at') ->limit($count) ->get(); } public function paginate( array $sortColumns, string $sortDirection, ?User $scopedUser = null, int $perPage = 50 ): Paginator { $scopedUser ??= $this->auth->user(); return Song::query(type: PlayableType::SONG, user: $scopedUser) ->withUserContext() ->sort($sortColumns, $sortDirection) ->simplePaginate($perPage); } /** * @param Genre|null $genre If null, paginate songs that have no genre */ public function paginateByGenre( ?Genre $genre, array $sortColumns, string $sortDirection, ?User $scopedUser = null, int $perPage = 50 ): Paginator { return Song::query(type: PlayableType::SONG, user: $scopedUser ?? $this->auth->user()) ->withUserContext() ->when($genre, static fn (Builder $builder) => $builder->whereRelation('genres', 'genres.id', $genre->id)) ->when(!$genre, static fn (Builder $builder) => $builder->whereDoesntHave('genres')) ->sort($sortColumns, $sortDirection) ->simplePaginate($perPage); } /** @return Collection|array<array-key, Song> */ public function getForQueue( array $sortColumns, string $sortDirection, int $limit = self::LIST_SIZE_LIMIT, ?User $scopedUser = null, ): Collection { return Song::query(type: PlayableType::SONG, user: $scopedUser ?? $this->auth->user()) ->withUserContext() ->sort($sortColumns, $sortDirection) ->limit($limit) ->get(); } /** @return Collection|array<array-key, Song> */ public function getFavorites(?User $scopedUser = null): Collection { return Song::query(user: $scopedUser ?? $this->auth->user()) ->withUserContext(favoritesOnly: true) ->get(); } /** @return Collection|array<array-key, Song> */ public function getByAlbum(Album $album, ?User $scopedUser = null): Collection { return Song::query(user: $scopedUser ?? $this->auth->user()) ->withUserContext() ->whereBelongsTo($album) ->orderBy('songs.disc') ->orderBy('songs.track') ->orderBy('songs.title') ->get(); } public function paginateInFolder(?Folder $folder = null, ?User $scopedUser = null): Paginator { return Song::query(type: PlayableType::SONG, user: $scopedUser ?? $this->auth->user()) ->withUserContext() ->storedLocally() ->when($folder, static fn (SongBuilder $query) => $query->where('folder_id', $folder->id)) // @phpstan-ignore-line ->when(!$folder, static fn (SongBuilder $query) => $query->whereNull('folder_id')) ->orderBy('songs.path') ->simplePaginate(50); } /** @return Collection|array<array-key, Song> */ public function getByArtist(Artist $artist, ?User $scopedUser = null): Collection { return Song::query(type: PlayableType::SONG, user: $scopedUser ?? $this->auth->user()) ->withUserContext() ->where(static function (SongBuilder $query) use ($artist): void { $query->whereBelongsTo($artist) ->orWhereHas('album', static function (Builder $albumQuery) use ($artist): void { $albumQuery->whereBelongsTo($artist); }); }) ->orderBy('songs.album_name') ->orderBy('songs.disc') ->orderBy('songs.track') ->orderBy('songs.title') ->get(); } /** @return Collection|array<array-key, Song> */ public function getByPlaylist(Playlist $playlist, ?User $scopedUser = null): Collection { if ($playlist->is_smart) { return $this->getBySmartPlaylist($playlist, $scopedUser); } else { return $this->getByStandardPlaylist($playlist, $scopedUser); } } /** @return Collection|array<array-key, Song> */ private function getByStandardPlaylist(Playlist $playlist, ?User $scopedUser = null): Collection { throw_if($playlist->is_smart, new LogicException('Not a standard playlist.')); return Song::query(user: $scopedUser ?? $this->auth->user()) ->withUserContext() ->leftJoin('playlist_song', 'songs.id', '=', 'playlist_song.song_id') ->leftJoin('playlists', 'playlists.id', '=', 'playlist_song.playlist_id') ->when(License::isPlus(), static function (SongBuilder $query): SongBuilder { return $query->join('users as collaborators', 'playlist_song.user_id', '=', 'collaborators.id') ->addSelect( 'collaborators.public_id as collaborator_public_id', 'collaborators.name as collaborator_name', 'collaborators.email as collaborator_email', 'collaborators.avatar as collaborator_avatar', 'playlist_song.created_at as added_at' ); }) ->where('playlists.id', $playlist->id) ->orderBy('playlist_song.position') ->get(); } /** @return Collection|array<array-key, Song> */ private function getBySmartPlaylist(Playlist $playlist, ?User $scopedUser = null): Collection { throw_unless($playlist->is_smart, NonSmartPlaylistException::create($playlist)); $query = Song::query(type: PlayableType::SONG, user: $scopedUser)->withUserContext(); $playlist->rule_groups->each(static function (RuleGroup $group, int $index) use ($query): void { $whereClosure = static function (SongBuilder $subQuery) use ($group): void { $group->rules->each(static function (Rule $rule) use ($subQuery): void { QueryModifier::applyRule($rule, $subQuery); }); }; $query->when( $index === 0, static fn (SongBuilder $query) => $query->where($whereClosure), static fn (SongBuilder $query) => $query->orWhere($whereClosure) ); }); return $query->orderBy('songs.title') ->limit(self::LIST_SIZE_LIMIT) ->get(); } /** @return Collection|array<array-key, Song> */ public function getRandom(int $limit, ?User $scopedUser = null): Collection { return Song::query(type: PlayableType::SONG, user: $scopedUser ?? $this->auth->user()) ->withUserContext() ->inRandomOrder() ->limit($limit) ->get(); } /** @return Collection|array<array-key, Song> */ public function getMany(array $ids, bool $preserveOrder = false, ?User $scopedUser = null): Collection { $songs = Song::query(user: $scopedUser ?? $this->auth->user()) ->withUserContext() ->whereIn('songs.id', $ids) ->get(); return $preserveOrder ? $songs->orderByArray($ids) : $songs; // @phpstan-ignore-line } /** @param array<string> $ids */ public function countAccessibleByIds(array $ids, ?User $scopedUser = null): int { return Song::query(user: $scopedUser ?? $this->auth->user()) ->accessible() ->whereIn('songs.id', $ids) ->count(); } /** * Gets several songs, but also includes collaborative information. * * @return Collection|array<array-key, Song> */ public function getManyInCollaborativeContext(array $ids, ?User $scopedUser = null): Collection { return Song::query(user: $scopedUser ?? $this->auth->user()) ->withUserContext() ->when(License::isPlus(), static function (SongBuilder $query): SongBuilder { return $query->leftJoin('playlist_song', 'songs.id', '=', 'playlist_song.song_id') ->leftJoin('playlists', 'playlists.id', '=', 'playlist_song.playlist_id') ->join('users as collaborators', 'playlist_song.user_id', '=', 'collaborators.id') ->addSelect( 'collaborators.public_id as collaborator_public_id', 'collaborators.name as collaborator_name', 'collaborators.email as collaborator_email', 'playlist_song.created_at as added_at' ); }) ->whereIn('songs.id', $ids) ->get(); } /** @param string $id */ public function getOne($id, ?User $user = null): Song { return Song::query(user: $user ?? $this->auth->user()) ->withUserContext() ->findOrFail($id); } /** @param string $id */ public function findOne($id, ?User $user = null): ?Song { return Song::query(user: $user ?? $this->auth->user()) ->withUserContext() ->find($id); } public function countSongs(?User $scopedUser = null): int { return Song::query(type: PlayableType::SONG, user: $scopedUser ?? $this->auth->user()) ->accessible() ->count(); } public function getTotalSongLength(?User $scopedUser = null): float { return Song::query(type: PlayableType::SONG, user: $scopedUser ?? $this->auth->user()) ->accessible() ->sum('length'); } /** * @param Genre|null $genre If null, query songs that have no genre. * * @return Collection|array<array-key, Song> */ public function getByGenre(?Genre $genre, int $limit, $random = false, ?User $scopedUser = null): Collection { return Song::query(type: PlayableType::SONG, user: $scopedUser ?? $this->auth->user()) ->withUserContext() ->when($genre, static fn (Builder $builder) => $builder->whereRelation('genres', 'genres.id', $genre->id)) ->when(!$genre, static fn (Builder $builder) => $builder->whereDoesntHave('genres')) ->when($random, static fn (Builder $builder) => $builder->inRandomOrder()) ->when(!$random, static fn (Builder $builder) => $builder->orderBy('songs.title')) ->limit($limit) ->get(); } /** @return array<string> */ public function getEpisodeGuidsByPodcast(Podcast $podcast): array { return $podcast->episodes()->pluck('episode_guid')->toArray(); } /** @return Collection<Song>|array<array-key, Song> */ public function getEpisodesByPodcast(Podcast $podcast, ?User $user = null): Collection { return Song::query(user: $user ?? $this->auth->user()) ->withUserContext() ->whereBelongsTo($podcast) ->orderByDesc('songs.created_at') ->get(); } /** @return Collection<Song>|array<array-key, Song> */ public function getUnderPaths( array $paths, int $limit = 500, bool $random = false, ?User $scopedUser = null ): Collection { $paths = array_map(static fn (?string $path) => $path ? trim($path, DIRECTORY_SEPARATOR) : '', $paths); if (!$paths) { return Collection::empty(); } $hasRootPath = in_array('', $paths, true); $scopedUser ??= $this->auth->user(); return Song::query(type: PlayableType::SONG, user: $scopedUser) ->withUserContext() // if the root path is included, we don't need to filter by folder ->when(!$hasRootPath, function (SongBuilder $query) use ($paths, $scopedUser): void { $folders = $this->folderRepository->getByPaths($paths, $scopedUser); $query->whereIn('songs.folder_id', $folders->pluck('id')); }) ->when(!$random, static fn (SongBuilder $query): SongBuilder => $query->orderBy('songs.path')) ->when($random, static fn (SongBuilder $query): SongBuilder => $query->inRandomOrder()) ->limit($limit) ->get(); } /** * Fetch songs **directly** in a specific folder (or the media root if null). * This does not include songs in subfolders. * * @return Collection<Song>|array<array-key, Song> */ public function getInFolder(?Folder $folder = null, int $limit = 500, ?User $scopedUser = null): Collection { return Song::query(type: PlayableType::SONG, user: $scopedUser ?? $this->auth->user()) ->withUserContext() ->limit($limit) ->when($folder, static fn (SongBuilder $query) => $query->where('songs.folder_id', $folder->id)) // @phpstan-ignore-line ->when(!$folder, static fn (SongBuilder $query) => $query->whereNull('songs.folder_id')) ->orderBy('songs.path') ->get(); } /** @return Collection<Song>|array<array-key, Song> */ public function search(string $keywords, int $limit, ?User $user = null): Collection { return $this->getMany( ids: Song::search($keywords)->get()->take($limit)->modelKeys(), preserveOrder: true, scopedUser: $user, ); } /** @return Collection<Song>|array<array-key, Song> */ public function getForEmbed(Embed $embed): Collection { throw_unless((bool) $embed->embeddable, new EmbeddableNotFoundException()); return match (EmbeddableType::from($embed->embeddable_type)) { EmbeddableType::ALBUM => $this->getByAlbum($embed->embeddable, $embed->user), EmbeddableType::ARTIST => $this->getByArtist($embed->embeddable, $embed->user), EmbeddableType::PLAYLIST => $this->getByPlaylist($embed->embeddable, $embed->user), EmbeddableType::PLAYABLE => $this->getMany(ids: [$embed->embeddable->getKey()], scopedUser: $embed->user), }; } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/UserRepository.php
app/Repositories/UserRepository.php
<?php /** @noinspection PhpIncompatibleReturnTypeInspection */ namespace App\Repositories; use App\Models\User; use App\Values\User\SsoUser; /** * @extends Repository<User> */ class UserRepository extends Repository { public function getFirstAdminUser(): User { return User::firstAdmin(); } public function findOneByEmail(string $email): ?User { return User::query()->firstWhere('email', $email); } public function findOneBySso(SsoUser $ssoUser): ?User { // we prioritize the SSO ID over the email address, but still resort to the latter return User::query()->firstWhere([ 'sso_id' => $ssoUser->id, 'sso_provider' => $ssoUser->provider, ]) ?? $this->findOneByEmail($ssoUser->email); } public function getOneByPublicId(string $publicId): User { return $this->getOneBy(['public_id' => $publicId]); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/PlaylistFolderRepository.php
app/Repositories/PlaylistFolderRepository.php
<?php namespace App\Repositories; use App\Models\PlaylistFolder; /** * @extends Repository<PlaylistFolder> */ class PlaylistFolderRepository extends Repository { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/FolderRepository.php
app/Repositories/FolderRepository.php
<?php namespace App\Repositories; use App\Models\Folder; use App\Models\User; use Illuminate\Database\Eloquent\Collection; /** @extends Repository<Folder> */ class FolderRepository extends Repository { /** @return Collection<Folder>|array<array-key, Folder> */ private static function getOnlyBrowsable(Collection|Folder $folders, ?User $user = null): Collection { return Collection::wrap($folders) ->filter(static fn (Folder $folder) => $folder->browsableBy($user ?? auth()->user())); // @phpstan-ignore-line } private static function pathToHash(?string $path = null): string { return simple_hash($path ? trim($path, DIRECTORY_SEPARATOR) : $path); } /** @return Collection|array<array-key, Folder> */ public function getSubfolders(?Folder $folder = null, ?User $scopedUser = null): Collection { if ($folder) { return $folder->subfolders; } return self::getOnlyBrowsable( Folder::query()->whereNull('parent_id')->get(), $scopedUser ); } public function findByPath(?string $path = null): ?Folder { return $this->findOneBy(['hash' => self::pathToHash($path)]); } /** @return Collection|array<array-key, Folder> */ public function getByPaths(array $paths, ?User $scopedUser = null): Collection { $hashes = array_map(self::pathToHash(...), $paths); return self::getOnlyBrowsable( Folder::query()->whereIn('hash', $hashes)->get(), $scopedUser ); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/PlaylistRepository.php
app/Repositories/PlaylistRepository.php
<?php namespace App\Repositories; use App\Facades\License; use App\Models\Playlist; use App\Models\User; use Illuminate\Support\Collection; /** @extends Repository<Playlist> */ class PlaylistRepository extends Repository { /** @return Collection<Playlist>|array<array-key, Playlist> */ public function getAllAccessibleByUser(User $user): Collection { $relation = License::isCommunity() ? $user->ownedPlaylists() : $user->playlists(); return $relation ->leftJoin('playlist_playlist_folder', 'playlists.id', '=', 'playlist_playlist_folder.playlist_id') ->distinct() ->get(['playlists.*', 'playlist_playlist_folder.folder_id']); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/Contracts/Repository.php
app/Repositories/Contracts/Repository.php
<?php namespace App\Repositories\Contracts; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; /** @template T of Model */ interface Repository { /** @return T */ public function getOne($id): Model; /** @return T */ public function getOneBy(array $params): Model; /** @return T|null */ public function findOne($id): ?Model; /** @return T|null */ public function findOneBy(array $params): ?Model; /** @return Collection<array-key, T> */ public function getMany(array $ids, bool $preserveOrder = false): Collection; /** @return Collection<array-key, T> */ public function getAll(): Collection; /** @return T|null */ public function findFirstWhere(...$params): ?Model; }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Repositories/Contracts/ScoutableRepository.php
app/Repositories/Contracts/ScoutableRepository.php
<?php namespace App\Repositories\Contracts; use App\Models\User; use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Model; /** * @template T of Model */ interface ScoutableRepository { /** * Search for models based on keywords using Laravel Scout. * * @param string $keywords The search keywords. * @param int $limit The maximum number of results to return. * @param ?User $user Optional user to scope the search. * * @return Collection<T>|array<array-key, T> A collection of models matching the search criteria. */ public function search(string $keywords, int $limit, ?User $user = null): Collection; }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Providers/StreamerServiceProvider.php
app/Providers/StreamerServiceProvider.php
<?php namespace App\Providers; use App\Services\Streamer\Adapters\LocalStreamerAdapter; use App\Services\Streamer\Adapters\PhpStreamerAdapter; use App\Services\Streamer\Adapters\XAccelRedirectStreamerAdapter; use App\Services\Streamer\Adapters\XSendFileStreamerAdapter; use Illuminate\Support\ServiceProvider; class StreamerServiceProvider extends ServiceProvider { public function register(): void { $this->app->bind(LocalStreamerAdapter::class, function (): LocalStreamerAdapter { return match (config('koel.streaming.method')) { 'x-sendfile' => $this->app->make(XSendFileStreamerAdapter::class), 'x-accel-redirect' => $this->app->make(XAccelRedirectStreamerAdapter::class), default => $this->app->make(PhpStreamerAdapter::class), }; }); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Providers/ITunesServiceProvider.php
app/Providers/ITunesServiceProvider.php
<?php namespace App\Providers; use App\Services\ITunesService; use Illuminate\Support\ServiceProvider; class ITunesServiceProvider extends ServiceProvider { public function register(): void { app()->singleton('iTunes', static fn (): ITunesService => app(ITunesService::class)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Providers/MacroProvider.php
app/Providers/MacroProvider.php
<?php namespace App\Providers; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Schema\Blueprint; use Illuminate\Http\UploadedFile; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Schema; use Illuminate\Support\ServiceProvider; use Illuminate\Testing\TestResponse; class MacroProvider extends ServiceProvider { public function boot(): void { Collection::macro('orderByArray', function (array $orderBy, string $key = 'id') { /** @var Collection $this */ return $this->sortBy(static fn ($item) => array_search($item->$key, $orderBy, true))->values(); }); Builder::macro('logSql', function (): Builder { /** @var Builder $this */ Log::info($this->toSql()); return $this; }); DB::macro('dropForeignKeyIfExists', function (string $table, string $column): void { // @phpcs:ignore $driver = DB::getDriverName(); if (!in_array($driver, ['mysql', 'mariadb', 'pgsql'], true)) { if (!app()->runningUnitTests()) { Log::warning("No drop FK logic for driver $driver"); } return; } if (in_array($driver, ['mysql', 'mariadb'], true)) { $constraint = DB::table('information_schema.KEY_COLUMN_USAGE') ->select('CONSTRAINT_NAME') ->where('TABLE_SCHEMA', DB::getDatabaseName()) ->where('TABLE_NAME', $table) ->where('COLUMN_NAME', $column) ->whereNotNull('REFERENCED_TABLE_NAME') ->first(); } else { $constraint = DB::table('information_schema.table_constraints as tc') ->join('information_schema.key_column_usage as kcu', static function ($join): void { $join->on('tc.constraint_name', '=', 'kcu.constraint_name') ->on('tc.constraint_schema', '=', 'kcu.constraint_schema'); }) ->select('tc.constraint_name') ->where('tc.constraint_type', 'FOREIGN KEY') ->where('tc.table_name', $table) ->where('kcu.column_name', $column) ->first(); } if ($constraint) { Schema::table($table, static fn (Blueprint $table) => $table->dropForeign([$column])); } }); if (app()->runningUnitTests()) { UploadedFile::macro( 'fromFile', function (string $path, ?string $name = null): UploadedFile { // @phpcs:ignore return UploadedFile::fake()->createWithContent($name ?? basename($path), File::get($path)); } ); TestResponse::macro('log', function (string $file = 'test-response.json'): TestResponse { /** @var TestResponse $this */ File::put(storage_path('logs/' . $file), $this->getContent()); return $this; }); } } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Providers/UtilServiceProvider.php
app/Providers/UtilServiceProvider.php
<?php namespace App\Providers; use App\Services\Util; use Illuminate\Support\ServiceProvider; class UtilServiceProvider extends ServiceProvider { public function register(): void { app()->singleton('Util', static fn (): Util => app(Util::class)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Providers/SongStorageServiceProvider.php
app/Providers/SongStorageServiceProvider.php
<?php namespace App\Providers; use App\Services\SongStorages\DropboxStorage; use App\Services\SongStorages\LocalStorage; use App\Services\SongStorages\S3CompatibleStorage; use App\Services\SongStorages\SftpStorage; use App\Services\SongStorages\SongStorage; use Illuminate\Support\ServiceProvider; class SongStorageServiceProvider extends ServiceProvider { public function register(): void { $this->app->bind(SongStorage::class, function () { $concrete = match (config('koel.storage_driver')) { 's3' => S3CompatibleStorage::class, 'dropbox' => DropboxStorage::class, 'sftp' => SftpStorage::class, default => LocalStorage::class, }; return $this->app->make($concrete); }); $this->app->when(S3CompatibleStorage::class) ->needs('$bucket') ->giveConfig('filesystems.disks.s3.bucket'); $this->app->when(DropboxStorage::class) ->needs('$config') ->giveConfig('filesystems.disks.dropbox'); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Providers/BroadcastServiceProvider.php
app/Providers/BroadcastServiceProvider.php
<?php namespace App\Providers; use Illuminate\Support\Facades\Broadcast; use Illuminate\Support\ServiceProvider; class BroadcastServiceProvider extends ServiceProvider { public function boot(): void { Broadcast::routes(); require base_path('routes/channels.php'); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Providers/DownloadServiceProvider.php
app/Providers/DownloadServiceProvider.php
<?php namespace App\Providers; use App\Services\DownloadService; use Illuminate\Support\ServiceProvider; class DownloadServiceProvider extends ServiceProvider { public function register(): void { app()->singleton('Download', static fn (): DownloadService => app(DownloadService::class)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Providers/ObjectStorageServiceProvider.php
app/Providers/ObjectStorageServiceProvider.php
<?php namespace App\Providers; use Aws\AwsClientInterface; use Aws\S3\S3ClientInterface; use Illuminate\Support\ServiceProvider; class ObjectStorageServiceProvider extends ServiceProvider { public function register(): void { $this->app->bind(S3ClientInterface::class, static function (): ?AwsClientInterface { // If these two values are not configured in .env, AWS will attempt initializing // the client with null values and throw an error. if (!config('aws.credentials.key') || !config('aws.credentials.secret')) { return null; } return app('aws')->createClient('s3'); }); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Providers/RouteServiceProvider.php
app/Providers/RouteServiceProvider.php
<?php namespace App\Providers; use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\Route; use Webmozart\Assert\Assert; class RouteServiceProvider extends ServiceProvider { public static function loadVersionAwareRoutes(string $type): void { Assert::oneOf($type, ['web', 'api']); Route::group([], base_path(sprintf('routes/%s.base.php', $type))); $apiVersion = self::getApiVersion(); $routeFile = $apiVersion ? base_path(sprintf('routes/%s.%s.php', $type, $apiVersion)) : null; if ($routeFile && File::exists($routeFile)) { Route::group([], $routeFile); } } private static function getApiVersion(): ?string { // In the test environment, the route service provider is loaded _before_ the request is made, // so we can't rely on the header. // Instead, we manually set the API version as an env variable in applicable test cases. return app()->runningUnitTests() ? env('X_API_VERSION') : request()->header('X-Api-Version'); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Providers/EventServiceProvider.php
app/Providers/EventServiceProvider.php
<?php namespace App\Providers; use App\Events\LibraryChanged; use App\Events\MediaScanCompleted; use App\Events\MultipleSongsLiked; use App\Events\MultipleSongsUnliked; use App\Events\NewPlaylistCollaboratorJoined; use App\Events\PlaybackStarted; use App\Events\SongFavoriteToggled; use App\Events\UserUnsubscribedFromPodcast; use App\Listeners\DeleteNonExistingRecordsPostScan; use App\Listeners\DeletePodcastIfNoSubscribers; use App\Listeners\LoveMultipleTracksOnLastfm; use App\Listeners\LoveTrackOnLastfm; use App\Listeners\MakePlaylistSongsPublic; use App\Listeners\PruneLibrary; use App\Listeners\UnloveMultipleTracksOnLastfm; use App\Listeners\UpdateLastfmNowPlaying; use App\Listeners\WriteScanLog; use App\Models\Album; use App\Models\Artist; use App\Models\Folder; use App\Models\Genre; use App\Models\Playlist; use App\Models\PlaylistCollaborationToken; use App\Models\RadioStation; use App\Models\Theme; use App\Models\User; use App\Observers\AlbumObserver; use App\Observers\ArtistObserver; use App\Observers\FolderObserver; use App\Observers\GenreObserver; use App\Observers\PlaylistCollaborationTokenObserver; use App\Observers\PlaylistObserver; use App\Observers\RadioStationObserver; use App\Observers\ThemeObserver; use App\Observers\UserObserver; use Illuminate\Foundation\Support\Providers\EventServiceProvider as BaseServiceProvider; class EventServiceProvider extends BaseServiceProvider { protected $listen = [ SongFavoriteToggled::class => [ LoveTrackOnLastfm::class, ], MultipleSongsLiked::class => [ LoveMultipleTracksOnLastfm::class, ], MultipleSongsUnliked::class => [ UnloveMultipleTracksOnLastfm::class, ], PlaybackStarted::class => [ UpdateLastfmNowPlaying::class, ], LibraryChanged::class => [ PruneLibrary::class, ], MediaScanCompleted::class => [ DeleteNonExistingRecordsPostScan::class, PruneLibrary::class, WriteScanLog::class, ], NewPlaylistCollaboratorJoined::class => [ MakePlaylistSongsPublic::class, ], UserUnsubscribedFromPodcast::class => [ DeletePodcastIfNoSubscribers::class, ], ]; public function boot(): void { parent::boot(); Album::observe(AlbumObserver::class); Artist::observe(ArtistObserver::class); Folder::observe(FolderObserver::class); Playlist::observe(PlaylistObserver::class); PlaylistCollaborationToken::observe(PlaylistCollaborationTokenObserver::class); Genre::observe(GenreObserver::class); User::observe(UserObserver::class); RadioStation::observe(RadioStationObserver::class); Theme::observe(ThemeObserver::class); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Providers/YouTubeServiceProvider.php
app/Providers/YouTubeServiceProvider.php
<?php namespace App\Providers; use App\Services\YouTubeService; use Illuminate\Support\ServiceProvider; class YouTubeServiceProvider extends ServiceProvider { public function register(): void { app()->singleton('YouTube', static fn (): YouTubeService => app(YouTubeService::class)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Providers/AppServiceProvider.php
app/Providers/AppServiceProvider.php
<?php namespace App\Providers; use App\Enums\Acl\Role; use App\Models\Album; use App\Models\Artist; use App\Models\Genre; use App\Models\Playlist; use App\Models\Podcast; use App\Models\RadioStation; use App\Models\Song; use App\Models\User; use App\Rules\ValidRadioStationUrl; use App\Services\Contracts\Encyclopedia; use App\Services\Geolocation\Contracts\GeolocationService; use App\Services\Geolocation\IPinfoService; use App\Services\LastfmService; use App\Services\License\Contracts\LicenseServiceInterface; use App\Services\LicenseService; use App\Services\MusicBrainzService; use App\Services\NullEncyclopedia; use App\Services\Scanners\Contracts\ScannerCacheStrategy as ScannerCacheStrategyContract; use App\Services\Scanners\ScannerCacheStrategy; use App\Services\Scanners\ScannerNoCacheStrategy; use App\Services\SpotifyService; use App\Services\TicketmasterService; use Illuminate\Database\DatabaseManager; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\Relation; use Illuminate\Database\Schema\Builder; use Illuminate\Database\SQLiteConnection; use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Route; use Illuminate\Support\ServiceProvider; use SpotifyWebAPI\Session as SpotifySession; class AppServiceProvider extends ServiceProvider { public function boot(Builder $schema, DatabaseManager $db): void { // Fix utf8mb4-related error starting from Laravel 5.4 $schema->defaultStringLength(191); Model::preventLazyLoading(!app()->isProduction()); self::enableOnDeleteCascadeForSqliteConnections($db); // disable wrapping JSON resource in a `data` key JsonResource::withoutWrapping(); self::grantAllPermissionsToSuperAdminRole(); $this->app->bind(SpotifySession::class, static function () { return SpotifyService::enabled() ? new SpotifySession( config('koel.services.spotify.client_id'), config('koel.services.spotify.client_secret'), ) : null; }); $this->app->bind(Encyclopedia::class, static function () { // Prefer Last.fm over MusicBrainz, and fall back to a null encyclopedia. if (LastfmService::enabled()) { return app(LastfmService::class); } if (MusicBrainzService::enabled()) { return app(MusicBrainzService::class); } return app(NullEncyclopedia::class); }); $this->app->bind(LicenseServiceInterface::class, LicenseService::class); $this->app->when(LicenseService::class) ->needs('$hashSalt') ->give(config('app.key')); $this->app->bind(ScannerCacheStrategyContract::class, static function () { // Use a no-cache strategy for unit tests to ensure consistent results return app()->runningUnitTests() ? app(ScannerNoCacheStrategy::class) : app(ScannerCacheStrategy::class); }); $this->app->singleton(ValidRadioStationUrl::class, static fn () => new ValidRadioStationUrl()); Route::bind('genre', static function (string $value): ?Genre { if ($value === Genre::NO_GENRE_PUBLIC_ID) { return null; } return Genre::query()->where('public_id', $value)->firstOrFail(); }); Relation::morphMap([ 'playable' => Song::class, 'album' => Album::class, 'artist' => Artist::class, 'podcast' => Podcast::class, 'radio-station' => RadioStation::class, 'playlist' => Playlist::class, ]); $this->app->when(TicketmasterService::class) ->needs('$defaultCountryCode') ->give(config('koel.services.ticketmaster.default_country_code')); $this->app->bind(GeolocationService::class, static function (): GeolocationService { return app(IPinfoService::class); }); } public function register(): void { if (class_exists('Laravel\Tinker\TinkerServiceProvider')) { $this->app->register('Laravel\Tinker\TinkerServiceProvider'); } } private static function enableOnDeleteCascadeForSqliteConnections(DatabaseManager $db): void { if ($db->connection() instanceof SQLiteConnection) { $db->statement($db->raw('PRAGMA foreign_keys = ON')->getValue($db->getQueryGrammar())); } } private static function grantAllPermissionsToSuperAdminRole(): void { Gate::after(static fn (User $user) => $user->hasRole(Role::ADMIN)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Providers/AuthServiceProvider.php
app/Providers/AuthServiceProvider.php
<?php namespace App\Providers; use App\Models\User; use App\Services\TokenManager; use Illuminate\Auth\Notifications\ResetPassword; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Validation\Rules\Password; class AuthServiceProvider extends ServiceProvider { public function boot(): void { $this->registerPolicies(); Auth::viaRequest('token-via-query-parameter', static function (Request $request): ?User { $token = $request->get('api_token') ?: $request->get('t'); return app(TokenManager::class)->getUserFromPlainTextToken($token ?: ''); }); $this->setPasswordDefaultRules(); ResetPassword::createUrlUsing(static function (User $user, string $token): string { $payload = base64_encode($user->getEmailForPasswordReset() . "|$token"); return url("/#/reset-password/$payload"); }); } private function setPasswordDefaultRules(): void { Password::defaults(fn (): Password => $this->app->isProduction() ? Password::min(10)->letters()->numbers()->symbols()->uncompromised() : Password::min(6)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Providers/LicenseServiceProvider.php
app/Providers/LicenseServiceProvider.php
<?php namespace App\Providers; use App\Services\License\Contracts\LicenseServiceInterface; use Illuminate\Support\ServiceProvider; class LicenseServiceProvider extends ServiceProvider { public function register(): void { app()->singleton('License', static fn (): LicenseServiceInterface => app(LicenseServiceInterface::class)); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Attributes/DemoConstraint.php
app/Attributes/DemoConstraint.php
<?php namespace App\Attributes; use Illuminate\Http\Response; abstract class DemoConstraint { public function __construct( public int $code = Response::HTTP_FORBIDDEN, public bool $allowAdminOverride = true, ) { } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Attributes/RequiresPlus.php
app/Attributes/RequiresPlus.php
<?php namespace App\Attributes; use Attribute; use Illuminate\Http\Response; #[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_CLASS)] class RequiresPlus { public function __construct(public int $code = Response::HTTP_NOT_FOUND) { } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Attributes/RequiresDemo.php
app/Attributes/RequiresDemo.php
<?php namespace App\Attributes; use Attribute; #[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_CLASS)] class RequiresDemo extends DemoConstraint { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Attributes/DisabledInDemo.php
app/Attributes/DisabledInDemo.php
<?php namespace App\Attributes; use Attribute; #[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_CLASS)] class DisabledInDemo extends DemoConstraint { }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Pipelines/Encyclopedia/GetArtistWikidataIdUsingMbid.php
app/Pipelines/Encyclopedia/GetArtistWikidataIdUsingMbid.php
<?php namespace App\Pipelines\Encyclopedia; use App\Http\Integrations\MusicBrainz\MusicBrainzConnector; use App\Http\Integrations\MusicBrainz\Requests\GetArtistUrlRelationshipsRequest; use Closure; use Illuminate\Support\Arr; use Illuminate\Support\Str; class GetArtistWikidataIdUsingMbid { use TriesRemember; public function __construct(private readonly MusicBrainzConnector $connector) { } public function __invoke(?string $mbid, Closure $next): mixed { if (!$mbid) { return $next(null); } $wikidataId = $this->tryRememberForever( key: cache_key('artist wikidata id from mbid', $mbid), callback: function () use ($mbid): ?string { $wikidata = collect(Arr::where( $this->connector->send(new GetArtistUrlRelationshipsRequest($mbid))->json('relations'), static fn ($relation) => $relation['type'] === 'wikidata', ))->first(); return $wikidata ? Str::afterLast(Arr::get($wikidata, 'url.resource'), '/') // 'https://www.wikidata.org/wiki/Q461269' : null; } ); return $next($wikidataId); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false
koel/koel
https://github.com/koel/koel/blob/add9401a4b9a904bb1b9f679bc674ad1570ff20e/app/Pipelines/Encyclopedia/GetAlbumWikidataIdUsingReleaseGroupMbid.php
app/Pipelines/Encyclopedia/GetAlbumWikidataIdUsingReleaseGroupMbid.php
<?php namespace App\Pipelines\Encyclopedia; use App\Http\Integrations\MusicBrainz\MusicBrainzConnector; use App\Http\Integrations\MusicBrainz\Requests\GetReleaseGroupUrlRelationshipsRequest; use Closure; use Illuminate\Support\Arr; use Illuminate\Support\Str; class GetAlbumWikidataIdUsingReleaseGroupMbid { use TriesRemember; public function __construct(private readonly MusicBrainzConnector $connector) { } public function __invoke(?string $mbid, Closure $next): mixed { if (!$mbid) { return $next(null); } $wikidataId = $this->tryRememberForever( key: cache_key('album wikidata id from release group mbid', $mbid), callback: function () use ($mbid): ?string { $wikidata = collect(Arr::where( $this->connector->send(new GetReleaseGroupUrlRelationshipsRequest($mbid))->json('relations'), static fn ($relation) => $relation['type'] === 'wikidata', ))->first(); return $wikidata ? Str::afterLast(Arr::get($wikidata, 'url.resource'), '/') : null; } ); return $next($wikidataId); } }
php
MIT
add9401a4b9a904bb1b9f679bc674ad1570ff20e
2026-01-04T15:02:34.446708Z
false