Merge pull request #89 from Poniverse/scrutinizer-patch-1

Scrutinizer Auto-Fixes
This commit is contained in:
Peter Deltchev 2016-06-05 23:30:26 -07:00
commit b334e51928
43 changed files with 165 additions and 164 deletions

View file

@ -59,7 +59,7 @@ class AddTrackToPlaylistCommand extends CommandBase
// check if this track is already in the playlist // check if this track is already in the playlist
$validator = Validator::make( $validator = Validator::make(
['track_id' => $this->_track->id], ['track_id' => $this->_track->id],
['track_id' => "unique:playlist_track,track_id,null,id,playlist_id,{$this->_playlist->id}",] ['track_id' => "unique:playlist_track,track_id,null,id,playlist_id,{$this->_playlist->id}", ]
); );
if ($validator->fails()) { if ($validator->fails()) {
@ -72,7 +72,7 @@ class AddTrackToPlaylistCommand extends CommandBase
$this->_playlist->touch(); $this->_playlist->touch();
Playlist::where('id', $this->_playlist->id)->update([ Playlist::where('id', $this->_playlist->id)->update([
'track_count' => DB::raw('(SELECT COUNT(id) FROM playlist_track WHERE playlist_id = ' . $this->_playlist->id . ')') 'track_count' => DB::raw('(SELECT COUNT(id) FROM playlist_track WHERE playlist_id = '.$this->_playlist->id.')')
]); ]);
return CommandResponse::succeed(['message' => 'Track added!']); return CommandResponse::succeed(['message' => 'Track added!']);

View file

@ -90,11 +90,11 @@ class EditAlbumCommand extends CommandBase
} }
if (isset($this->_input['username'])) { if (isset($this->_input['username'])) {
$newid = User::where('username', $this->_input['username'])->first()->id; $newid = User::where('username', $this->_input['username'])->first()->id;
if ($this->_album->user_id != $newid) { if ($this->_album->user_id != $newid) {
$this->_album->user_id = $newid; $this->_album->user_id = $newid;
} }
} }
$trackIds = explode(',', $this->_input['track_ids']); $trackIds = explode(',', $this->_input['track_ids']);

View file

@ -27,7 +27,6 @@ use Poniverse\Ponyfm\Models\Image;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\TrackType; use Poniverse\Ponyfm\Models\TrackType;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use Auth;
use DB; use DB;
class EditTrackCommand extends CommandBase class EditTrackCommand extends CommandBase
@ -66,8 +65,8 @@ class EditTrackCommand extends CommandBase
$rules = [ $rules = [
'title' => 'required|min:3|max:80', 'title' => 'required|min:3|max:80',
'released_at' => 'before:' . 'released_at' => 'before:' .
(date('Y-m-d', time() + (86400 * 2))) . ( (date('Y-m-d', time() + (86400 * 2))) . (
isset($this->_input['released_at']) && $this->_input['released_at'] != "" isset($this->_input['released_at']) && $this->_input['released_at'] != ""
? '|date' ? '|date'
: ''), : ''),
'license_id' => 'required|exists:licenses,id', 'license_id' => 'required|exists:licenses,id',
@ -157,12 +156,12 @@ class EditTrackCommand extends CommandBase
$oldid = null; $oldid = null;
if (isset($this->_input['username'])) { if (isset($this->_input['username'])) {
$newid = User::where('username', $this->_input['username'])->first()->id; $newid = User::where('username', $this->_input['username'])->first()->id;
if ($track->user_id != $newid) { if ($track->user_id != $newid) {
$oldid = $track->user_id; $oldid = $track->user_id;
$track->user_id = $newid; $track->user_id = $newid;
} }
} }
$track->updateTags(); $track->updateTags();
@ -173,9 +172,9 @@ class EditTrackCommand extends CommandBase
]); ]);
if ($oldid != null) { if ($oldid != null) {
User::whereId($oldid)->update([ User::whereId($oldid)->update([
'track_count' => DB::raw('(SELECT COUNT(id) FROM tracks WHERE deleted_at IS NULL AND published_at IS NOT NULL AND user_id = ' . $oldid . ')') 'track_count' => DB::raw('(SELECT COUNT(id) FROM tracks WHERE deleted_at IS NULL AND published_at IS NOT NULL AND user_id = ' . $oldid . ')')
]); ]);
} }
return CommandResponse::succeed(['real_cover_url' => $track->getCoverUrl(Image::NORMAL)]); return CommandResponse::succeed(['real_cover_url' => $track->getCoverUrl(Image::NORMAL)]);

View file

@ -30,7 +30,6 @@ use AudioCache;
use File; use File;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use SplFileInfo; use SplFileInfo;
use Validator;
/** /**
* This command is the "second phase" of the upload process - once metadata has * This command is the "second phase" of the upload process - once metadata has

View file

@ -119,7 +119,7 @@ class ParseTrackTagsCommand extends CommandBase
* *
* @param int $artistId * @param int $artistId
* @param string|null $albumName * @param string|null $albumName
* @param null $coverId * @param integer|null $coverId
* @return int|null * @return int|null
*/ */
protected function getAlbumId(int $artistId, $albumName, $coverId = null) { protected function getAlbumId(int $artistId, $albumName, $coverId = null) {
@ -236,9 +236,9 @@ class ParseTrackTagsCommand extends CommandBase
} }
// write temporary image file // write temporary image file
$tmpPath = Config::get('ponyfm.files_directory') . '/tmp'; $tmpPath = Config::get('ponyfm.files_directory').'/tmp';
$filename = $file->getFilename() . ".cover.${extension}"; $filename = $file->getFilename().".cover.${extension}";
$imageFilePath = "${tmpPath}/${filename}"; $imageFilePath = "${tmpPath}/${filename}";
File::put($imageFilePath, $image['data']); File::put($imageFilePath, $image['data']);

View file

@ -54,7 +54,7 @@ class RemoveTrackFromPlaylistCommand extends CommandBase
{ {
$this->_playlist->tracks()->detach($this->_track); $this->_playlist->tracks()->detach($this->_track);
Playlist::whereId($this->_playlist->id)->update([ Playlist::whereId($this->_playlist->id)->update([
'track_count' => DB::raw('(SELECT COUNT(id) FROM playlist_track WHERE playlist_id = ' . $this->_playlist->id . ')') 'track_count' => DB::raw('(SELECT COUNT(id) FROM playlist_track WHERE playlist_id = '.$this->_playlist->id.')')
]); ]);
return CommandResponse::succeed(['message' => 'Track removed!']); return CommandResponse::succeed(['message' => 'Track removed!']);

View file

@ -70,7 +70,7 @@ class ToggleFavouriteCommand extends CommandBase
*/ */
public function execute() public function execute()
{ {
$typeId = $this->_resourceType . '_id'; $typeId = $this->_resourceType.'_id';
$existing = Favourite::where($typeId, '=', $this->_resourceId)->whereUserId(Auth::user()->id)->first(); $existing = Favourite::where($typeId, '=', $this->_resourceId)->whereUserId(Auth::user()->id)->first();
$isFavourited = false; $isFavourited = false;
@ -91,7 +91,7 @@ class ToggleFavouriteCommand extends CommandBase
$resourceUser->is_favourited = $isFavourited; $resourceUser->is_favourited = $isFavourited;
$resourceUser->save(); $resourceUser->save();
$resourceTable = $this->_resourceType . 's'; $resourceTable = $this->_resourceType.'s';
// We do this to prevent a race condition. Sure I could simply increment the count columns and re-save back to the db // We do this to prevent a race condition. Sure I could simply increment the count columns and re-save back to the db
// but that would require an additional SELECT and the operation would be non-atomic. If two log items are created // but that would require an additional SELECT and the operation would be non-atomic. If two log items are created
@ -105,7 +105,7 @@ class ToggleFavouriteCommand extends CommandBase
FROM FROM
favourites favourites
WHERE ' . WHERE ' .
$typeId . ' = ' . $this->_resourceId . ')') $typeId.' = '.$this->_resourceId.')')
]); ]);
return CommandResponse::succeed(['is_favourited' => $isFavourited]); return CommandResponse::succeed(['is_favourited' => $isFavourited]);

View file

@ -86,12 +86,12 @@ class UploadTrackCommand extends CommandBase
$track->save(); $track->save();
$track->ensureDirectoryExists(); $track->ensureDirectoryExists();
if (!is_dir(Config::get('ponyfm.files_directory') . '/tmp')) { if (!is_dir(Config::get('ponyfm.files_directory').'/tmp')) {
mkdir(Config::get('ponyfm.files_directory') . '/tmp', 0755, true); mkdir(Config::get('ponyfm.files_directory').'/tmp', 0755, true);
} }
if (!is_dir(Config::get('ponyfm.files_directory') . '/queued-tracks')) { if (!is_dir(Config::get('ponyfm.files_directory').'/queued-tracks')) {
mkdir(Config::get('ponyfm.files_directory') . '/queued-tracks', 0755, true); mkdir(Config::get('ponyfm.files_directory').'/queued-tracks', 0755, true);
} }
$trackFile = $trackFile->move(Config::get('ponyfm.files_directory').'/queued-tracks', $track->id); $trackFile = $trackFile->move(Config::get('ponyfm.files_directory').'/queued-tracks', $track->id);

View file

@ -76,15 +76,15 @@ class ClassifyMLPMA extends Command
$totalTracks = sizeof($tracks); $totalTracks = sizeof($tracks);
$fileToStartAt = (int)$this->option('startAt') - 1; $fileToStartAt = (int) $this->option('startAt') - 1;
$this->comment("Skipping $fileToStartAt files..." . PHP_EOL); $this->comment("Skipping $fileToStartAt files...".PHP_EOL);
$tracks = array_slice($tracks, $fileToStartAt); $tracks = array_slice($tracks, $fileToStartAt);
$this->currentTrack = $fileToStartAt; $this->currentTrack = $fileToStartAt;
foreach ($tracks as $track) { foreach ($tracks as $track) {
$this->currentTrack++; $this->currentTrack++;
$this->comment('[' . $this->currentTrack . '/' . $totalTracks . '] Classifying track [' . $track->filename . ']...'); $this->comment('['.$this->currentTrack.'/'.$totalTracks.'] Classifying track ['.$track->filename.']...');
$parsedTags = json_decode($track->parsed_tags, true); $parsedTags = json_decode($track->parsed_tags, true);
@ -163,7 +163,7 @@ class ClassifyMLPMA extends Command
foreach ($officialSongs as $song) { foreach ($officialSongs as $song) {
$this->comment('=> Matched official song: [' . $song->id . '] ' . $song->title); $this->comment('=> Matched official song: ['.$song->id.'] '.$song->title);
} }
@ -186,11 +186,11 @@ class ClassifyMLPMA extends Command
} }
$this->question('If this is a medley, multiple song ID\'s can be separated by commas. '); $this->question('If this is a medley, multiple song ID\'s can be separated by commas. ');
$this->question(' '); $this->question(' ');
$this->question(' ' . $filename . ' '); $this->question(' '.$filename.' ');
$this->question(' '); $this->question(' ');
$this->question(' Title: ' . $tags['title'] . ' '); $this->question(' Title: '.$tags['title'].' ');
$this->question(' Album: ' . $tags['album'] . ' '); $this->question(' Album: '.$tags['album'].' ');
$this->question(' Artist: ' . $tags['artist'] . ' '); $this->question(' Artist: '.$tags['artist'].' ');
$this->question(' '); $this->question(' ');
$this->question(' r = official song remix (accept all "guessed" matches) '); $this->question(' r = official song remix (accept all "guessed" matches) ');
$this->question(' # = official song remix (enter the ID(s) of the show song(s)) '); $this->question(' # = official song remix (enter the ID(s) of the show song(s)) ');
@ -205,7 +205,7 @@ class ClassifyMLPMA extends Command
case 'r': case 'r':
$trackTypeId = TrackType::OFFICIAL_TRACK_REMIX; $trackTypeId = TrackType::OFFICIAL_TRACK_REMIX;
foreach ($officialSongs as $officialSong) { foreach ($officialSongs as $officialSong) {
$linkedSongIds[] = (int)$officialSong->id; $linkedSongIds[] = (int) $officialSong->id;
} }
break; break;
@ -228,8 +228,8 @@ class ClassifyMLPMA extends Command
default: default:
$trackTypeId = TrackType::OFFICIAL_TRACK_REMIX; $trackTypeId = TrackType::OFFICIAL_TRACK_REMIX;
$linkedSongIds = explode(',', $input); $linkedSongIds = explode(',', $input);
$linkedSongIds = array_map(function ($item) { $linkedSongIds = array_map(function($item) {
return (int)$item; return (int) $item;
}, $linkedSongIds); }, $linkedSongIds);
} }
} }

View file

@ -79,35 +79,35 @@ class FixMLPMAImages extends Command
*/ */
public function handle() public function handle()
{ {
$mlpmaPath = Config::get('ponyfm.files_directory') . '/mlpma'; $mlpmaPath = Config::get('ponyfm.files_directory').'/mlpma';
$tmpPath = Config::get('ponyfm.files_directory') . '/tmp'; $tmpPath = Config::get('ponyfm.files_directory').'/tmp';
$this->comment('Enumerating MLP Music Archive source files...'); $this->comment('Enumerating MLP Music Archive source files...');
$files = File::allFiles($mlpmaPath); $files = File::allFiles($mlpmaPath);
$this->info(sizeof($files) . ' files found!'); $this->info(sizeof($files).' files found!');
$this->comment('Importing tracks...'); $this->comment('Importing tracks...');
$totalFiles = sizeof($files); $totalFiles = sizeof($files);
$fileToStartAt = (int) $this->option('startAt') - 1; $fileToStartAt = (int) $this->option('startAt') - 1;
$this->comment("Skipping $fileToStartAt files..." . PHP_EOL); $this->comment("Skipping $fileToStartAt files...".PHP_EOL);
$files = array_slice($files, $fileToStartAt); $files = array_slice($files, $fileToStartAt);
$this->currentFile = $fileToStartAt; $this->currentFile = $fileToStartAt;
foreach ($files as $file) { foreach ($files as $file) {
$this->currentFile ++; $this->currentFile++;
$this->info('[' . $this->currentFile . '/' . $totalFiles . '] Importing track [' . $file->getFilename() . ']...'); $this->info('['.$this->currentFile.'/'.$totalFiles.'] Importing track ['.$file->getFilename().']...');
if (in_array($file->getExtension(), $this->ignoredExtensions)) { if (in_array($file->getExtension(), $this->ignoredExtensions)) {
$this->comment('This is not an audio file! Skipping...' . PHP_EOL); $this->comment('This is not an audio file! Skipping...'.PHP_EOL);
continue; continue;
} }
// Get this track's MLPMA record // Get this track's MLPMA record
$importedTrack = DB::table('mlpma_tracks') $importedTrack = DB::table('mlpma_tracks')
->where('filename', '=', $file->getFilename()) ->where('filename', '=', $file->getFilename())
->join('tracks', 'mlpma_tracks.track_id', '=', 'tracks.id') ->join('tracks', 'mlpma_tracks.track_id', '=', 'tracks.id')
->first(); ->first();
$artistId = $importedTrack->user_id; $artistId = $importedTrack->user_id;
@ -138,8 +138,8 @@ class FixMLPMAImages extends Command
$this->error('Unknown cover art format!'); $this->error('Unknown cover art format!');
} }
// write temporary image file // write temporary image file
$imageFilename = $file->getFilename() . ".cover.$extension"; $imageFilename = $file->getFilename().".cover.$extension";
$imageFilePath = "$tmpPath/" . $imageFilename; $imageFilePath = "$tmpPath/".$imageFilename;
File::put($imageFilePath, $image['data']); File::put($imageFilePath, $image['data']);
$imageFile = new UploadedFile($imageFilePath, $imageFilename, $image['image_mime']); $imageFile = new UploadedFile($imageFilePath, $imageFilename, $image['image_mime']);
$cover = Image::upload($imageFile, $artistId, true); $cover = Image::upload($imageFile, $artistId, true);

View file

@ -100,12 +100,12 @@ class MigrateOldData extends Command
$coverId = null; $coverId = null;
if (!$user->uses_gravatar) { if (!$user->uses_gravatar) {
try { try {
$coverFile = $this->getIdDirectory('users', $user->id) . '/' . $user->id . '_.png'; $coverFile = $this->getIdDirectory('users', $user->id).'/'.$user->id.'_.png';
$coverId = Image::upload(new UploadedFile($coverFile, $coverId = Image::upload(new UploadedFile($coverFile,
$user->id . '_.png'), $user->id)->id; $user->id.'_.png'), $user->id)->id;
DB::table('users')->where('id', $user->id)->update(['avatar_id' => $coverId]); DB::table('users')->where('id', $user->id)->update(['avatar_id' => $coverId]);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Could copy user avatar ' . $user->id . ' because ' . $e->getMessage()); $this->error('Could copy user avatar '.$user->id.' because '.$e->getMessage());
DB::table('users')->where('id', $user->id)->update(['uses_gravatar' => true]); DB::table('users')->where('id', $user->id)->update(['uses_gravatar' => true]);
} }
} }
@ -150,7 +150,7 @@ class MigrateOldData extends Command
'ip_address' => $logItem->ip_address, 'ip_address' => $logItem->ip_address,
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Could insert log item for album ' . $playlist->id . ' because ' . $e->getMessage()); $this->error('Could insert log item for album '.$playlist->id.' because '.$e->getMessage());
} }
} }
@ -165,7 +165,7 @@ class MigrateOldData extends Command
'track_format_id' => $logItem->track_file_format_id - 1 'track_format_id' => $logItem->track_file_format_id - 1
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Could insert log item for album ' . $playlist->id . ' because ' . $e->getMessage()); $this->error('Could insert log item for album '.$playlist->id.' because '.$e->getMessage());
} }
} }
} }
@ -177,11 +177,11 @@ class MigrateOldData extends Command
if ($track->cover) { if ($track->cover) {
try { try {
$coverFile = $this->getIdDirectory('tracks', $coverFile = $this->getIdDirectory('tracks',
$track->id) . '/' . $track->id . '_' . $track->cover . '.png'; $track->id).'/'.$track->id.'_'.$track->cover.'.png';
$coverId = Image::upload(new UploadedFile($coverFile, $coverId = Image::upload(new UploadedFile($coverFile,
$track->id . '_' . $track->cover . '.png'), $track->user_id)->id; $track->id.'_'.$track->cover.'.png'), $track->user_id)->id;
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Could copy track cover ' . $track->id . ' because ' . $e->getMessage()); $this->error('Could copy track cover '.$track->id.' because '.$e->getMessage());
} }
} }
@ -226,7 +226,7 @@ class MigrateOldData extends Command
'ip_address' => $logItem->ip_address 'ip_address' => $logItem->ip_address
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Could insert log item for track ' . $track->id . ' because ' . $e->getMessage()); $this->error('Could insert log item for track '.$track->id.' because '.$e->getMessage());
} }
} }
@ -240,7 +240,7 @@ class MigrateOldData extends Command
'ip_address' => $logItem->ip_address 'ip_address' => $logItem->ip_address
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Could insert log item for track ' . $track->id . ' because ' . $e->getMessage()); $this->error('Could insert log item for track '.$track->id.' because '.$e->getMessage());
} }
} }
@ -255,7 +255,7 @@ class MigrateOldData extends Command
'track_format_id' => $logItem->track_file_format_id - 1 'track_format_id' => $logItem->track_file_format_id - 1
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Could insert log item for track ' . $track->id . ' because ' . $e->getMessage()); $this->error('Could insert log item for track '.$track->id.' because '.$e->getMessage());
} }
} }
} }
@ -269,7 +269,7 @@ class MigrateOldData extends Command
'track_id' => $song->track_id 'track_id' => $song->track_id
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Could insert show track item for ' . $song->track_id . ' because ' . $e->getMessage()); $this->error('Could insert show track item for '.$song->track_id.' because '.$e->getMessage());
} }
} }
@ -303,7 +303,7 @@ class MigrateOldData extends Command
'ip_address' => $logItem->ip_address, 'ip_address' => $logItem->ip_address,
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Could insert log item for playlist ' . $playlist->id . ' because ' . $e->getMessage()); $this->error('Could insert log item for playlist '.$playlist->id.' because '.$e->getMessage());
} }
} }
@ -318,7 +318,7 @@ class MigrateOldData extends Command
'track_format_id' => $logItem->track_file_format_id - 1 'track_format_id' => $logItem->track_file_format_id - 1
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Could insert log item for playlist ' . $playlist->id . ' because ' . $e->getMessage()); $this->error('Could insert log item for playlist '.$playlist->id.' because '.$e->getMessage());
} }
} }
} }
@ -353,7 +353,7 @@ class MigrateOldData extends Command
'profile_id' => $comment->profile_id 'profile_id' => $comment->profile_id
]); ]);
} catch (Exception $e) { } catch (Exception $e) {
$this->error('Could not sync comment ' . $comment->id . ' because ' . $e->getMessage()); $this->error('Could not sync comment '.$comment->id.' because '.$e->getMessage());
} }
} }
@ -370,7 +370,7 @@ class MigrateOldData extends Command
'playlist_id' => $fav->playlist_id, 'playlist_id' => $fav->playlist_id,
]); ]);
} catch (Exception $e) { } catch (Exception $e) {
$this->error('Could not sync favourite ' . $fav->id . ' because ' . $e->getMessage()); $this->error('Could not sync favourite '.$fav->id.' because '.$e->getMessage());
} }
} }
@ -385,16 +385,16 @@ class MigrateOldData extends Command
'created_at' => $follower->created_at, 'created_at' => $follower->created_at,
]); ]);
} catch (Exception $e) { } catch (Exception $e) {
$this->error('Could not sync follower ' . $follower->id . ' because ' . $e->getMessage()); $this->error('Could not sync follower '.$follower->id.' because '.$e->getMessage());
} }
} }
} }
private function getIdDirectory($type, $id) private function getIdDirectory($type, $id)
{ {
$dir = (string)(floor($id / 100) * 100); $dir = (string) (floor($id / 100) * 100);
return \Config::get('ponyfm.files_directory') . '/' . $type . '/' . $dir; return \Config::get('ponyfm.files_directory').'/'.$type.'/'.$dir;
} }
} }

View file

@ -109,7 +109,7 @@ class PoniverseApiSetup extends Command
if (file_exists($path)) { if (file_exists($path)) {
file_put_contents($path, str_replace( file_put_contents($path, str_replace(
"$key=" . $oldValue, "$key=" . $newValue, file_get_contents($path) "$key=".$oldValue, "$key=".$newValue, file_get_contents($path)
)); ));
} else { } else {
$this->error('Please run `vagrant up`!'); $this->error('Please run `vagrant up`!');

View file

@ -63,7 +63,7 @@ class RebuildFilesizes extends Command
false) false)
) { ) {
TrackFile::chunk(200, function ($trackFiles) { TrackFile::chunk(200, function($trackFiles) {
$this->info('========== Start Chunk =========='); $this->info('========== Start Chunk ==========');
@ -72,9 +72,9 @@ class RebuildFilesizes extends Command
if (File::exists($trackFile->getFile())) { if (File::exists($trackFile->getFile())) {
$size = $trackFile->updateFilesize(); $size = $trackFile->updateFilesize();
$this->info('ID ' . $trackFile->id . ' processed - ' . $size . ' bytes'); $this->info('ID '.$trackFile->id.' processed - '.$size.' bytes');
} else { } else {
$this->info('ID ' . $trackFile->id . ' skipped'); $this->info('ID '.$trackFile->id.' skipped');
} }
} }

View file

@ -26,7 +26,6 @@ use Poniverse\Ponyfm\Models\Album;
use Poniverse\Ponyfm\Models\Playlist; use Poniverse\Ponyfm\Models\Playlist;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use Symfony\Component\Console\Helper\ProgressBar;
class RebuildSearchIndex extends Command class RebuildSearchIndex extends Command
{ {
@ -68,7 +67,7 @@ class RebuildSearchIndex extends Command
$trackProgress = $this->output->createProgressBar($totalTracks); $trackProgress = $this->output->createProgressBar($totalTracks);
$this->info("Processing tracks..."); $this->info("Processing tracks...");
Track::withTrashed()->chunk(200, function(Collection $tracks) use ($trackProgress) { Track::withTrashed()->chunk(200, function(Collection $tracks) use ($trackProgress) {
foreach($tracks as $track) { foreach ($tracks as $track) {
/** @var Track $track */ /** @var Track $track */
$trackProgress->advance(); $trackProgress->advance();
$track->updateElasticsearchEntry(); $track->updateElasticsearchEntry();
@ -81,7 +80,7 @@ class RebuildSearchIndex extends Command
$albumProgress = $this->output->createProgressBar($totalAlbums); $albumProgress = $this->output->createProgressBar($totalAlbums);
$this->info("Processing albums..."); $this->info("Processing albums...");
Album::withTrashed()->chunk(200, function(Collection $albums) use ($albumProgress) { Album::withTrashed()->chunk(200, function(Collection $albums) use ($albumProgress) {
foreach($albums as $album) { foreach ($albums as $album) {
/** @var Album $album */ /** @var Album $album */
$albumProgress->advance(); $albumProgress->advance();
$album->updateElasticsearchEntry(); $album->updateElasticsearchEntry();
@ -94,7 +93,7 @@ class RebuildSearchIndex extends Command
$playlistProgress = $this->output->createProgressBar($totalPlaylists); $playlistProgress = $this->output->createProgressBar($totalPlaylists);
$this->info("Processing playlists..."); $this->info("Processing playlists...");
Playlist::withTrashed()->chunk(200, function(Collection $playlists) use ($playlistProgress) { Playlist::withTrashed()->chunk(200, function(Collection $playlists) use ($playlistProgress) {
foreach($playlists as $playlist) { foreach ($playlists as $playlist) {
/** @var Playlist $playlist */ /** @var Playlist $playlist */
$playlistProgress->advance(); $playlistProgress->advance();
$playlist->updateElasticsearchEntry(); $playlist->updateElasticsearchEntry();
@ -107,7 +106,7 @@ class RebuildSearchIndex extends Command
$userProgress = $this->output->createProgressBar($totalUsers); $userProgress = $this->output->createProgressBar($totalUsers);
$this->info("Processing users..."); $this->info("Processing users...");
User::chunk(200, function(Collection $users) use ($userProgress) { User::chunk(200, function(Collection $users) use ($userProgress) {
foreach($users as $user) { foreach ($users as $user) {
/** @var User $user */ /** @var User $user */
$userProgress->advance(); $userProgress->advance();
$user->updateElasticsearchEntry(); $user->updateElasticsearchEntry();

View file

@ -83,7 +83,7 @@ class RebuildTrackCache extends Command
// Chunk track files which are cacheable and NOT master // Chunk track files which are cacheable and NOT master
TrackFile::where('is_cacheable', true) TrackFile::where('is_cacheable', true)
->where('is_master', false) ->where('is_master', false)
->chunk(200, function ($trackFiles) use (&$count) { ->chunk(200, function($trackFiles) use (&$count) {
// Delete chunked track files // Delete chunked track files
foreach ($trackFiles as $trackFile) { foreach ($trackFiles as $trackFile) {
// Clear expiration so will be re-cached on next request // Clear expiration so will be re-cached on next request
@ -94,11 +94,11 @@ class RebuildTrackCache extends Command
if (File::exists($trackFile->getFile())) { if (File::exists($trackFile->getFile())) {
$count++; $count++;
File::delete($trackFile->getFile()); File::delete($trackFile->getFile());
$this->info('Deleted ' . $trackFile->getFile()); $this->info('Deleted '.$trackFile->getFile());
} }
} }
$this->info($count . ' track files deleted. Deletion complete. Continuing.'); $this->info($count.' track files deleted. Deletion complete. Continuing.');
}); });
//========================================================================================================== //==========================================================================================================
@ -115,7 +115,7 @@ class RebuildTrackCache extends Command
TrackFile::where('is_cacheable', false) TrackFile::where('is_cacheable', false)
->whereIn('format', Track::$CacheableFormats) ->whereIn('format', Track::$CacheableFormats)
->where('is_master', false) ->where('is_master', false)
->chunk(200, function ($trackFiles) use (&$trackFileCount, &$formats) { ->chunk(200, function($trackFiles) use (&$trackFileCount, &$formats) {
$this->output->newLine(1); $this->output->newLine(1);
$this->info('---------- Start Chunk ----------'); $this->info('---------- Start Chunk ----------');
@ -135,8 +135,8 @@ class RebuildTrackCache extends Command
$this->output->newLine(1); $this->output->newLine(1);
}); });
$this->info('Format(s) set from non-cacheable to cacheable: ' . implode(' ', array_unique($formats))); $this->info('Format(s) set from non-cacheable to cacheable: '.implode(' ', array_unique($formats)));
$this->info($trackFileCount . ' non-cacheable track files set to cacheable.'); $this->info($trackFileCount.' non-cacheable track files set to cacheable.');
$this->output->newLine(2); $this->output->newLine(2);
@ -150,7 +150,7 @@ class RebuildTrackCache extends Command
// Chunk track files which are NOT meant to be cacheable, but currently cacheable // Chunk track files which are NOT meant to be cacheable, but currently cacheable
TrackFile::where('is_cacheable', true) TrackFile::where('is_cacheable', true)
->whereNotIn('format', Track::$CacheableFormats) ->whereNotIn('format', Track::$CacheableFormats)
->chunk(200, function ($trackFiles) use (&$trackFileCount, &$formats) { ->chunk(200, function($trackFiles) use (&$trackFileCount, &$formats) {
$this->output->newLine(1); $this->output->newLine(1);
$this->info('---------- Start Chunk ----------'); $this->info('---------- Start Chunk ----------');
@ -172,8 +172,8 @@ class RebuildTrackCache extends Command
}); });
$this->info('Format(s) set from cacheable to non-cacheable: ' . implode(' ', array_unique($formats))); $this->info('Format(s) set from cacheable to non-cacheable: '.implode(' ', array_unique($formats)));
$this->info($trackFileCount . ' cacheable track files set to non-cacheable.'); $this->info($trackFileCount.' cacheable track files set to non-cacheable.');
//========================================================================================================== //==========================================================================================================
// Delete track files which have now been marked as cacheable // Delete track files which have now been marked as cacheable
@ -188,7 +188,7 @@ class RebuildTrackCache extends Command
// Find track files which are cacheable and NOT master // Find track files which are cacheable and NOT master
TrackFile::whereIn('format', Track::$CacheableFormats) TrackFile::whereIn('format', Track::$CacheableFormats)
->where('is_master', false) ->where('is_master', false)
->chunk(200, function ($trackFiles) use (&$count, &$trackFileCount) { ->chunk(200, function($trackFiles) use (&$count, &$trackFileCount) {
$this->output->newLine(1); $this->output->newLine(1);
$this->info('---------- Start Chunk ----------'); $this->info('---------- Start Chunk ----------');
@ -200,7 +200,7 @@ class RebuildTrackCache extends Command
$count++; $count++;
File::delete($trackFile->getFile()); File::delete($trackFile->getFile());
$this->info('Deleted ' . $trackFile->getFile()); $this->info('Deleted '.$trackFile->getFile());
} }
} }
@ -223,7 +223,7 @@ class RebuildTrackCache extends Command
// Chunk non-cacheable track files // Chunk non-cacheable track files
TrackFile::where('is_cacheable', false) TrackFile::where('is_cacheable', false)
->where('is_master', false) ->where('is_master', false)
->chunk(200, function ($trackFiles) use (&$count) { ->chunk(200, function($trackFiles) use (&$count) {
$this->output->newLine(1); $this->output->newLine(1);
$this->info('---------- Start Chunk ----------'); $this->info('---------- Start Chunk ----------');
@ -248,7 +248,7 @@ class RebuildTrackCache extends Command
}); });
$this->info($count . ' track files encoded.'); $this->info($count.' track files encoded.');
$this->output->newLine(1); $this->output->newLine(1);
$this->info('Rebuild complete. Exiting.'); $this->info('Rebuild complete. Exiting.');

View file

@ -190,7 +190,7 @@ class RefreshCache extends Command
foreach ($resources as $name => $resourceArray) { foreach ($resources as $name => $resourceArray) {
foreach ($resourceArray as $id => $resource) { foreach ($resourceArray as $id => $resource) {
DB::table($name . 's')->whereId($id)->update($resource); DB::table($name.'s')->whereId($id)->update($resource);
} }
} }
@ -238,7 +238,7 @@ class RefreshCache extends Command
'user_id' => $userId 'user_id' => $userId
]; ];
$item[$type . '_id'] = $id; $item[$type.'_id'] = $id;
$items[$userId][$type][$id] = $item; $items[$userId][$type][$id] = $item;

View file

@ -55,7 +55,7 @@ class AlbumsController extends ApiControllerBase
public function getShow($id) public function getShow($id)
{ {
$album = Album::with([ $album = Album::with([
'tracks' => function ($query) { 'tracks' => function($query) {
$query->userDetails(); $query->userDetails();
}, },
'tracks.cover', 'tracks.cover',
@ -176,7 +176,7 @@ class AlbumsController extends ApiControllerBase
{ {
$album = Album::with('tracks')->find($id); $album = Album::with('tracks')->find($id);
if (!$album) { if (!$album) {
return $this->notFound('Album ' . $id . ' not found!'); return $this->notFound('Album '.$id.' not found!');
} }
if (Gate::denies('edit', Auth::user())) { if (Gate::denies('edit', Auth::user())) {

View file

@ -166,7 +166,7 @@ class ArtistsController extends ApiControllerBase
if ($user->users->count()) { if ($user->users->count()) {
$userRow = $user->users[0]; $userRow = $user->users[0];
$userData = [ $userData = [
'is_following' => (bool)$userRow->is_followed 'is_following' => (bool) $userRow->is_followed
]; ];
} }
@ -178,7 +178,7 @@ class ArtistsController extends ApiControllerBase
'id' => $user->id, 'id' => $user->id,
'name' => $user->display_name, 'name' => $user->display_name,
'slug' => $user->slug, 'slug' => $user->slug,
'is_archived' => (bool)$user->is_archived, 'is_archived' => (bool) $user->is_archived,
'avatars' => [ 'avatars' => [
'small' => $user->getAvatarUrl(Image::SMALL), 'small' => $user->getAvatarUrl(Image::SMALL),
'normal' => $user->getAvatarUrl(Image::NORMAL) 'normal' => $user->getAvatarUrl(Image::NORMAL)

View file

@ -43,7 +43,7 @@ class FavouritesController extends ApiControllerBase
::whereUserId(Auth::user()->id) ::whereUserId(Auth::user()->id)
->whereNotNull('track_id') ->whereNotNull('track_id')
->with([ ->with([
'track' => function ($query) { 'track' => function($query) {
$query $query
->userDetails() ->userDetails()
->published(); ->published();
@ -75,7 +75,7 @@ class FavouritesController extends ApiControllerBase
::whereUserId(Auth::user()->id) ::whereUserId(Auth::user()->id)
->whereNotNull('album_id') ->whereNotNull('album_id')
->with([ ->with([
'album' => function ($query) { 'album' => function($query) {
$query->userDetails(); $query->userDetails();
}, },
'album.user', 'album.user',
@ -103,7 +103,7 @@ class FavouritesController extends ApiControllerBase
::whereUserId(Auth::user()->id) ::whereUserId(Auth::user()->id)
->whereNotNull('playlist_id') ->whereNotNull('playlist_id')
->with([ ->with([
'playlist' => function ($query) { 'playlist' => function($query) {
$query->userDetails(); $query->userDetails();
}, },
'playlist.user', 'playlist.user',

View file

@ -106,7 +106,7 @@ class PlaylistsController extends ApiControllerBase
'tracks.genre', 'tracks.genre',
'tracks.cover', 'tracks.cover',
'tracks.album', 'tracks.album',
'tracks' => function ($query) { 'tracks' => function($query) {
$query->userDetails(); $query->userDetails();
}, },
'tracks.trackFiles', 'tracks.trackFiles',
@ -161,7 +161,7 @@ class PlaylistsController extends ApiControllerBase
$query = Playlist $query = Playlist
::userDetails() ::userDetails()
->with('tracks', 'tracks.cover', 'tracks.user', 'user') ->with('tracks', 'tracks.cover', 'tracks.user', 'user')
->join('pinned_playlists', function ($join) { ->join('pinned_playlists', function($join) {
$join->on('playlist_id', '=', 'playlists.id'); $join->on('playlist_id', '=', 'playlists.id');
}) })
->where('pinned_playlists.user_id', '=', Auth::user()->id) ->where('pinned_playlists.user_id', '=', Auth::user()->id)

View file

@ -43,7 +43,7 @@ class StatsController extends ApiControllerBase
->selectRaw('created_at, COUNT(1) AS `plays`') ->selectRaw('created_at, COUNT(1) AS `plays`')
->where('track_id', '=', $id) ->where('track_id', '=', $id)
->where('log_type', '=', ResourceLogItem::PLAY) ->where('log_type', '=', ResourceLogItem::PLAY)
->whereRaw('`created_at` > now() - INTERVAL ' . $playRange) ->whereRaw('`created_at` > now() - INTERVAL '.$playRange)
->groupBy('created_at') ->groupBy('created_at')
->orderBy('created_at') ->orderBy('created_at')
->get(); ->get();
@ -62,7 +62,7 @@ class StatsController extends ApiControllerBase
$playsArray = array_fill(0, 30, 0); $playsArray = array_fill(0, 30, 0);
} }
foreach($query as $item) { foreach ($query as $item) {
$playDate = new Carbon($item->created_at); $playDate = new Carbon($item->created_at);
$key = 0; $key = 0;
@ -82,15 +82,15 @@ class StatsController extends ApiControllerBase
krsort($playsArray); krsort($playsArray);
// Covert playsArray into output we can understand // Covert playsArray into output we can understand
foreach($playsArray as $timeOffet => $plays) { foreach ($playsArray as $timeOffet => $plays) {
if ($hourly) { if ($hourly) {
$set = [ $set = [
'hours' => $timeOffet . ' ' . str_plural('hour', $timeOffet), 'hours' => $timeOffet.' '.str_plural('hour', $timeOffet),
'plays' => $plays 'plays' => $plays
]; ];
} else { } else {
$set = [ $set = [
'days' => $timeOffet . ' ' . str_plural('day', $timeOffet), 'days' => $timeOffet.' '.str_plural('day', $timeOffet),
'plays' => $plays 'plays' => $plays
]; ];
} }

View file

@ -48,7 +48,7 @@ class TracksController extends ApiControllerBase
$track = Track::findOrFail($trackId); $track = Track::findOrFail($trackId);
$this->authorize('edit', $track); $this->authorize('edit', $track);
if ($track->status === Track::STATUS_PROCESSING){ if ($track->status === Track::STATUS_PROCESSING) {
return Response::json(['message' => 'Processing...'], 202); return Response::json(['message' => 'Processing...'], 202);
} elseif ($track->status === Track::STATUS_COMPLETE) { } elseif ($track->status === Track::STATUS_COMPLETE) {
@ -99,11 +99,13 @@ class TracksController extends ApiControllerBase
return $this->notFound('Track not found!'); return $this->notFound('Track not found!');
} }
if (!$track->canView(Auth::user())) if (!$track->canView(Auth::user())) {
return $this->notFound('Track not found!'); return $this->notFound('Track not found!');
}
if ($track->is_downloadable == false) if ($track->is_downloadable == false) {
return $this->notFound('Track not found!'); return $this->notFound('Track not found!');
}
if (!in_array($format, Track::$CacheableFormats)) { if (!in_array($format, Track::$CacheableFormats)) {
return $this->notFound('Format not found!'); return $this->notFound('Format not found!');
@ -194,7 +196,7 @@ class TracksController extends ApiControllerBase
{ {
$track = Track::with('showSongs')->find($id); $track = Track::with('showSongs')->find($id);
if (!$track) { if (!$track) {
return $this->notFound('Track ' . $id . ' not found!'); return $this->notFound('Track '.$id.' not found!');
} }
$this->authorize('edit', $track); $this->authorize('edit', $track);

View file

@ -45,7 +45,7 @@ class ImagesController extends Controller
$filename = $image->getFile($coverType['id']); $filename = $image->getFile($coverType['id']);
if (!is_file($filename)) { if (!is_file($filename)) {
$redirect = url('/images/icons/profile_' . Image::$ImageTypes[$coverType['id']]['name'] . '.png'); $redirect = url('/images/icons/profile_'.Image::$ImageTypes[$coverType['id']]['name'].'.png');
return Redirect::to($redirect); return Redirect::to($redirect);
} }
@ -62,7 +62,7 @@ class ImagesController extends Controller
$lastModified = filemtime($filename); $lastModified = filemtime($filename);
$response->header('Last-Modified', $lastModified); $response->header('Last-Modified', $lastModified);
$response->header('Cache-Control', 'max-age=' . (60 * 60 * 24 * 7)); $response->header('Cache-Control', 'max-age='.(60 * 60 * 24 * 7));
return $response; return $response;
} }

View file

@ -154,11 +154,11 @@ class TracksController extends Controller
if (Config::get('app.sendfile')) { if (Config::get('app.sendfile')) {
$response->header('X-Sendfile', $filename); $response->header('X-Sendfile', $filename);
$response->header('Content-Disposition', $response->header('Content-Disposition',
'attachment; filename="' . $trackFile->getDownloadFilename() . '"'); 'attachment; filename="'.$trackFile->getDownloadFilename().'"');
} else { } else {
$response->header('X-Accel-Redirect', $filename); $response->header('X-Accel-Redirect', $filename);
$response->header('Content-Disposition', $response->header('Content-Disposition',
'attachment; filename="' . $trackFile->getDownloadFilename() . '"'); 'attachment; filename="'.$trackFile->getDownloadFilename().'"');
} }
$time = gmdate(filemtime($filename)); $time = gmdate(filemtime($filename));

View file

@ -63,7 +63,7 @@ Route::get('i{id}/{type}.{extension}', 'ImagesController@getImage')->where('id',
Route::get('playlist/{id}-{slug}', 'PlaylistsController@getPlaylist'); Route::get('playlist/{id}-{slug}', 'PlaylistsController@getPlaylist');
Route::get('p{id}', 'PlaylistsController@getShortlink')->where('id', '\d+'); Route::get('p{id}', 'PlaylistsController@getShortlink')->where('id', '\d+');
Route::get('p{id}/dl.{extension}', 'PlaylistsController@getDownload' ); Route::get('p{id}/dl.{extension}', 'PlaylistsController@getDownload');
Route::get('notifications', 'AccountController@getNotifications'); Route::get('notifications', 'AccountController@getNotifications');

View file

@ -68,7 +68,7 @@ class DeleteGenre extends Job implements SelfHandling, ShouldQueue
// This is done instead of a single UPDATE query in order to // This is done instead of a single UPDATE query in order to
// generate revision logs for the change. // generate revision logs for the change.
$this->genreToDelete->tracks()->chunk(200, function ($tracks) { $this->genreToDelete->tracks()->chunk(200, function($tracks) {
foreach ($tracks as $track) { foreach ($tracks as $track) {
/** @var Track $track */ /** @var Track $track */

View file

@ -64,7 +64,7 @@ class DeleteShowSong extends Job implements SelfHandling, ShouldQueue
// This is done instead of a single UPDATE query in order to // This is done instead of a single UPDATE query in order to
// generate revision logs for the change. // generate revision logs for the change.
$this->songToDelete->tracks()->chunk(200, function ($tracks) { $this->songToDelete->tracks()->chunk(200, function($tracks) {
foreach ($tracks as $track) { foreach ($tracks as $track) {
/** @var Track $track */ /** @var Track $track */
$oldSongs = $track->showSongs; $oldSongs = $track->showSongs;

View file

@ -65,7 +65,7 @@ class EncodeTrackFile extends Job implements SelfHandling, ShouldQueue
*/ */
public function __construct(TrackFile $trackFile, $isExpirable, $isForUpload = false, $autoPublish = false) public function __construct(TrackFile $trackFile, $isExpirable, $isForUpload = false, $autoPublish = false)
{ {
if( if (
(!$isForUpload && $trackFile->is_master) || (!$isForUpload && $trackFile->is_master) ||
($isForUpload && $trackFile->is_master && !$trackFile->getFormat()['is_lossless']) ($isForUpload && $trackFile->is_master && !$trackFile->getFormat()['is_lossless'])
) { ) {

View file

@ -83,7 +83,7 @@ class UpdateTagsForRenamedGenre extends Job implements SelfHandling, ShouldQueue
} }
$this->genreThatWasRenamed->tracks()->chunk(200, function ($tracks) { $this->genreThatWasRenamed->tracks()->chunk(200, function($tracks) {
foreach ($tracks as $track) { foreach ($tracks as $track) {
/** @var Track $track */ /** @var Track $track */
$track->updateTags(); $track->updateTags();

View file

@ -82,7 +82,7 @@ class UpdateTagsForRenamedShowSong extends Job implements SelfHandling, ShouldQu
} }
$this->songThatWasRenamed->tracks()->chunk(200, function ($tracks) { $this->songThatWasRenamed->tracks()->chunk(200, function($tracks) {
foreach ($tracks as $track) { foreach ($tracks as $track) {
/** @var Track $track */ /** @var Track $track */
$track->updateTags(); $track->updateTags();

View file

@ -398,6 +398,9 @@ class Album extends Model implements Searchable, Commentable, Favouritable
} }
} }
/**
* @param string $key
*/
public function getCacheKey($key) public function getCacheKey($key)
{ {
return 'album-'.$this->id.'-'.$key; return 'album-'.$this->id.'-'.$key;

View file

@ -24,7 +24,6 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany; use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\SoftDeletes;
use Poniverse\Ponyfm\Contracts\Commentable; use Poniverse\Ponyfm\Contracts\Commentable;
use Poniverse\Ponyfm\Contracts\GeneratesNotifications;
/** /**
* Poniverse\Ponyfm\Models\Comment * Poniverse\Ponyfm\Models\Comment

View file

@ -53,7 +53,7 @@ class Genre extends Model
use SlugTrait, SoftDeletes, RevisionableTrait; use SlugTrait, SoftDeletes, RevisionableTrait;
public function tracks(){ public function tracks() {
return $this->hasMany(Track::class, 'genre_id'); return $this->hasMany(Track::class, 'genre_id');
} }

View file

@ -93,7 +93,7 @@ class Image extends Model
return Str::startsWith($filename, $imagePrefix); return Str::startsWith($filename, $imagePrefix);
}); });
foreach($filenames as $filename) { foreach ($filenames as $filename) {
unlink($image->getDirectory().'/'.$filename); unlink($image->getDirectory().'/'.$filename);
} }
} else { } else {
@ -119,7 +119,7 @@ class Image extends Model
} else { } else {
// ImageMagick options reference: http://www.imagemagick.org/script/command-line-options.php // ImageMagick options reference: http://www.imagemagick.org/script/command-line-options.php
$command = 'convert 2>&1 "' . $file->getPathname() . '" -background white -alpha remove -alpha off -strip'; $command = 'convert 2>&1 "'.$file->getPathname().'" -background white -alpha remove -alpha off -strip';
if ($image->mime === 'image/jpeg') { if ($image->mime === 'image/jpeg') {
$command .= ' -quality 100 -format jpeg'; $command .= ' -quality 100 -format jpeg';
@ -132,7 +132,7 @@ class Image extends Model
$command .= " -thumbnail ${coverType['width']}x${coverType['height']}^ -gravity center -extent ${coverType['width']}x${coverType['height']}"; $command .= " -thumbnail ${coverType['width']}x${coverType['height']}^ -gravity center -extent ${coverType['width']}x${coverType['height']}";
} }
$command .= ' "' . $image->getFile($coverType['id']) . '"'; $command .= ' "'.$image->getFile($coverType['id']).'"';
} }
External::execute($command); External::execute($command);
@ -157,21 +157,21 @@ class Image extends Model
public function getFile($type = self::NORMAL) public function getFile($type = self::NORMAL)
{ {
return $this->getDirectory() . '/' . $this->getFilename($type); return $this->getDirectory().'/'.$this->getFilename($type);
} }
public function getFilename($type = self::NORMAL) public function getFilename($type = self::NORMAL)
{ {
$typeInfo = self::$ImageTypes[$type]; $typeInfo = self::$ImageTypes[$type];
return $this->id . '_' . $typeInfo['name'] . '.'.$this->extension; return $this->id.'_'.$typeInfo['name'].'.'.$this->extension;
} }
public function getDirectory() public function getDirectory()
{ {
$dir = (string)(floor($this->id / 100) * 100); $dir = (string) (floor($this->id / 100) * 100);
return Config::get('ponyfm.files_directory') . '/images/' . $dir; return Config::get('ponyfm.files_directory').'/images/'.$dir;
} }
public function ensureDirectoryExists() public function ensureDirectoryExists()

View file

@ -98,7 +98,7 @@ class Playlist extends Model implements Searchable, Commentable, Favouritable
{ {
if (Auth::check()) { if (Auth::check()) {
$query->with([ $query->with([
'users' => function ($query) { 'users' => function($query) {
$query->whereUserId(Auth::user()->id); $query->whereUserId(Auth::user()->id);
} }
]); ]);
@ -138,8 +138,8 @@ class Playlist extends Model implements Searchable, Commentable, Favouritable
$data['formats'] = $formats; $data['formats'] = $formats;
$data['share'] = [ $data['share'] = [
'url' => action('PlaylistsController@getShortlink', ['id' => $playlist->id]), 'url' => action('PlaylistsController@getShortlink', ['id' => $playlist->id]),
'tumblrUrl' => 'http://www.tumblr.com/share/link?url=' . urlencode($playlist->url) . '&name=' . urlencode($playlist->title) . '&description=' . urlencode($playlist->description), 'tumblrUrl' => 'http://www.tumblr.com/share/link?url='.urlencode($playlist->url).'&name='.urlencode($playlist->title).'&description='.urlencode($playlist->description),
'twitterUrl' => 'https://platform.twitter.com/widgets/tweet_button.html?text=' . $playlist->title . ' by ' . $playlist->user->display_name . ' on Pony.fm' 'twitterUrl' => 'https://platform.twitter.com/widgets/tweet_button.html?text='.$playlist->title.' by '.$playlist->user->display_name.' on Pony.fm'
]; ];
return $data; return $data;
@ -159,25 +159,25 @@ class Playlist extends Model implements Searchable, Commentable, Favouritable
$userRow = $playlist->users[0]; $userRow = $playlist->users[0];
$userData = [ $userData = [
'stats' => [ 'stats' => [
'views' => (int)$userRow->view_count, 'views' => (int) $userRow->view_count,
'downloads' => (int)$userRow->download_count, 'downloads' => (int) $userRow->download_count,
], ],
'is_favourited' => (bool)$userRow->is_favourited 'is_favourited' => (bool) $userRow->is_favourited
]; ];
} }
return [ return [
'id' => (int)$playlist->id, 'id' => (int) $playlist->id,
'track_count' => $playlist->track_count, 'track_count' => $playlist->track_count,
'title' => $playlist->title, 'title' => $playlist->title,
'slug' => $playlist->slug, 'slug' => $playlist->slug,
'created_at' => $playlist->created_at->format('c'), 'created_at' => $playlist->created_at->format('c'),
'is_public' => (bool)$playlist->is_public, 'is_public' => (bool) $playlist->is_public,
'stats' => [ 'stats' => [
'views' => (int)$playlist->view_count, 'views' => (int) $playlist->view_count,
'downloads' => (int)$playlist->download_count, 'downloads' => (int) $playlist->download_count,
'comments' => (int)$playlist->comment_count, 'comments' => (int) $playlist->comment_count,
'favourites' => (int)$playlist->favourite_count 'favourites' => (int) $playlist->favourite_count
], ],
'covers' => [ 'covers' => [
'small' => $playlist->getCoverUrl(Image::SMALL), 'small' => $playlist->getCoverUrl(Image::SMALL),
@ -186,7 +186,7 @@ class Playlist extends Model implements Searchable, Commentable, Favouritable
], ],
'url' => $playlist->url, 'url' => $playlist->url,
'user' => [ 'user' => [
'id' => (int)$playlist->user->id, 'id' => (int) $playlist->user->id,
'name' => $playlist->user->display_name, 'name' => $playlist->user->display_name,
'url' => $playlist->user->url, 'url' => $playlist->user->url,
], ],
@ -274,7 +274,7 @@ class Playlist extends Model implements Searchable, Commentable, Favouritable
return 0; return 0;
} }
return Cache::remember($this->getCacheKey('filesize-' . $format), 1440, function () use ($tracks, $format) { return Cache::remember($this->getCacheKey('filesize-'.$format), 1440, function() use ($tracks, $format) {
$size = 0; $size = 0;
foreach ($tracks as $track) { foreach ($tracks as $track) {
/** @var $track Track */ /** @var $track Track */
@ -313,7 +313,7 @@ class Playlist extends Model implements Searchable, Commentable, Favouritable
private function getCacheKey($key) private function getCacheKey($key)
{ {
return 'playlist-' . $this->id . '-' . $key; return 'playlist-'.$this->id.'-'.$key;
} }
/** /**

View file

@ -51,7 +51,7 @@ class ResourceLogItem extends Model
public static function logItem($resourceType, $resourceId, $logType, $formatId = null) public static function logItem($resourceType, $resourceId, $logType, $formatId = null)
{ {
$resourceIdColumn = $resourceType . '_id'; $resourceIdColumn = $resourceType.'_id';
$logItem = new ResourceLogItem(); $logItem = new ResourceLogItem();
$logItem->{$resourceIdColumn} = $resourceId; $logItem->{$resourceIdColumn} = $resourceId;
@ -66,7 +66,7 @@ class ResourceLogItem extends Model
$logItem->save(); $logItem->save();
$resourceTable = $resourceType . 's'; $resourceTable = $resourceType.'s';
$countColumn = ''; $countColumn = '';
if ($logType == self::VIEW) { if ($logType == self::VIEW) {
@ -92,9 +92,9 @@ class ResourceLogItem extends Model
FROM FROM
resource_log_items resource_log_items
WHERE ' . WHERE ' .
$resourceIdColumn . ' = ' . $resourceId . ' $resourceIdColumn.' = '.$resourceId.'
AND AND
log_type = ' . $logType . ')') log_type = ' . $logType.')')
]); ]);
if (Auth::check()) { if (Auth::check()) {
@ -106,11 +106,11 @@ class ResourceLogItem extends Model
FROM FROM
resource_log_items resource_log_items
WHERE WHERE
user_id = ' . Auth::user()->id . ' user_id = ' . Auth::user()->id.'
AND ' . AND ' .
$resourceIdColumn . ' = ' . $resourceId . ' $resourceIdColumn.' = '.$resourceId.'
AND AND
log_type = ' . $logType . ')') log_type = ' . $logType.')')
]); ]);
} }
} }

View file

@ -45,7 +45,7 @@ class ResourceUser extends Model
public static function get($userId, $resourceType, $resourceId) public static function get($userId, $resourceType, $resourceId)
{ {
$resourceIdColumn = $resourceType . '_id'; $resourceIdColumn = $resourceType.'_id';
$existing = self::where($resourceIdColumn, '=', $resourceId)->where('user_id', '=', $userId)->first(); $existing = self::where($resourceIdColumn, '=', $resourceId)->where('user_id', '=', $userId)->first();
if ($existing) { if ($existing) {
return $existing; return $existing;

View file

@ -142,9 +142,9 @@ class TrackFile extends Model
public function getDirectory() public function getDirectory()
{ {
$dir = (string)(floor($this->track_id / 100) * 100); $dir = (string) (floor($this->track_id / 100) * 100);
return \Config::get('ponyfm.files_directory') . '/tracks/' . $dir; return \Config::get('ponyfm.files_directory').'/tracks/'.$dir;
} }
public function getFile() public function getFile()
@ -164,7 +164,7 @@ class TrackFile extends Model
private function getCacheKey($key) private function getCacheKey($key)
{ {
return 'track_file-' . $this->id . '-' . $key; return 'track_file-'.$this->id.'-'.$key;
} }
/** /**

View file

@ -117,7 +117,7 @@ class User extends Model implements AuthenticatableContract, CanResetPasswordCon
$slugBeingTried = $baseSlug; $slugBeingTried = $baseSlug;
$counter = 2; $counter = 2;
while(true) { while (true) {
$existingEntity = static::where('slug', $slugBeingTried)->first(); $existingEntity = static::where('slug', $slugBeingTried)->first();
$validator = Validator::make(['slug' => $slugBeingTried], ['isNotReservedSlug']); $validator = Validator::make(['slug' => $slugBeingTried], ['isNotReservedSlug']);

View file

@ -43,7 +43,7 @@ class NotificationServiceProvider extends ServiceProvider
*/ */
public function register() public function register()
{ {
$this->app->singleton('notification', function(Application $app){ $this->app->singleton('notification', function(Application $app) {
return new NotificationManager(); return new NotificationManager();
}); });
} }

View file

@ -56,7 +56,7 @@ class RouteServiceProvider extends ServiceProvider
*/ */
public function map(Router $router) public function map(Router $router)
{ {
$router->group(['namespace' => $this->namespace], function ($router) { $router->group(['namespace' => $this->namespace], function($router) {
require app_path('Http/routes.php'); require app_path('Http/routes.php');
}); });
} }

View file

@ -47,11 +47,11 @@ trait IndexedInElasticsearchTrait
// Laravel automatically runs this method based on the trait's name. #magic // Laravel automatically runs this method based on the trait's name. #magic
public static function bootIndexedInElasticsearchTrait() { public static function bootIndexedInElasticsearchTrait() {
static::saved(function (Searchable $entity) { static::saved(function(Searchable $entity) {
$entity->updateElasticsearchEntry(); $entity->updateElasticsearchEntry();
}); });
static::deleted(function (Searchable $entity) { static::deleted(function(Searchable $entity) {
$entity->updateElasticsearchEntry(); $entity->updateElasticsearchEntry();
}); });
} }

View file

@ -83,7 +83,7 @@ trait TrackCollection
$trackFile->is_master || $trackFile->is_master ||
($trackFile->expires_at != null && File::exists($trackFile->getFile())) ($trackFile->expires_at != null && File::exists($trackFile->getFile()))
) { ) {
$availableCount ++; $availableCount++;
} }
} }
@ -118,7 +118,7 @@ trait TrackCollection
*/ */
protected function downloadableTrackFiles($format) { protected function downloadableTrackFiles($format) {
return $this->trackFiles()->with([ return $this->trackFiles()->with([
'track' => function ($query) { 'track' => function($query) {
$query->where('is_downloadable', true); $query->where('is_downloadable', true);
} }
])->where('format', $format)->get(); ])->where('format', $format)->get();