diff --git a/app/controllers/TracksController.php b/app/controllers/TracksController.php index e71a79e2..a9ccd910 100644 --- a/app/controllers/TracksController.php +++ b/app/controllers/TracksController.php @@ -72,18 +72,7 @@ if (!$track || !$track->canView(Auth::user())) App::abort(404); - $trackFile = null; - - foreach ($track->trackFiles as $file) { - if ($file->extension === $extension) { - $trackFile = $file; - break; - } - } - - if ($trackFile == null) - App::abort(404); - + $trackFile = TrackFile::findOrFailByExtension($track->id, $extension); ResourceLogItem::logItem('track', $id, ResourceLogItem::PLAY, $trackFile->getFormat()['index']); $response = Response::make('', 200); @@ -113,18 +102,7 @@ if (!$track || !$track->canView(Auth::user())) App::abort(404); - $trackFile = null; - - foreach ($track->trackFiles as $file) { - if ($file->extension === $extension) { - $trackFile = $file; - break; - } - } - - if ($trackFile == null) - App::abort(404); - + $trackFile = TrackFile::findOrFailByExtension($track->id, $extension); ResourceLogItem::logItem('track', $id, ResourceLogItem::DOWNLOAD, $trackFile->getFormat()['index']); $response = Response::make('', 200); diff --git a/app/models/Entities/TrackFile.php b/app/models/Entities/TrackFile.php index 8855d10c..9730f793 100644 --- a/app/models/Entities/TrackFile.php +++ b/app/models/Entities/TrackFile.php @@ -1,6 +1,8 @@ belongsTo('Entities\Track'); } + public static function findOrFailByExtension($trackId, $extension) { + // find the extension's format + $requestedFormatName = null; + foreach (Track::$Formats as $name => $format) { + if ($extension === $format[ 'extension' ]) { + $requestedFormatName = $name; + break; + } + } + if ($requestedFormatName === null) { + App::abort(404); + } + + return static:: + with('track') + ->where('track_id', $trackId) + ->where('format', $requestedFormatName) + ->first(); + } + public function getFormatAttribute($value) { return $value; }