From 3e874da86854677cf9086e4b9b70182c37ef3b77 Mon Sep 17 00:00:00 2001 From: Josef Citrine Date: Mon, 2 May 2016 13:23:22 +0100 Subject: [PATCH] Start of a stats API --- .../Controllers/Api/Web/StatsController.php | 59 +++++++++++++++++++ app/Http/routes.php | 1 + 2 files changed, 60 insertions(+) create mode 100644 app/Http/Controllers/Api/Web/StatsController.php diff --git a/app/Http/Controllers/Api/Web/StatsController.php b/app/Http/Controllers/Api/Web/StatsController.php new file mode 100644 index 00000000..4e4d235d --- /dev/null +++ b/app/Http/Controllers/Api/Web/StatsController.php @@ -0,0 +1,59 @@ +. + */ + +namespace Poniverse\Ponyfm\Http\Controllers\Api\Web; + +use Illuminate\Database\Eloquent\ModelNotFoundException; +use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; +use Poniverse\Ponyfm\Models\Track; +use Auth; +use DB; +use Response; + +class StatsController extends ApiControllerBase +{ + public function getTrackStatsHourly($id) + { + // Get track to check if it exists + // and if we are allowed to view it. + // In the future we could do something + // with this data, not sure. + try { + $track = Track::findOrFail($id); + } catch (ModelNotFoundException $e) { + return $this->notFound('Track not found!'); + } + + // Do we have permission to view this track? + if (!$track->canView(Auth::user())) + return $this->notFound('Track not found!'); + + // I know, raw SQL ugh. I'm not used to laravel's query system + $query = DB::select(DB::raw(" + SELECT HOUR(created_at) AS `hour`, COUNT(1) AS `plays` + FROM `resource_log_items` + WHERE `track_id` = :id AND `log_type` = 3 AND `created_at` > now() - INTERVAL 7 DAY + GROUP BY HOUR(created_at);"), array( + 'id' => $id, + )); + + return Response::json(['stats' => $query], 200); + } +} diff --git a/app/Http/routes.php b/app/Http/routes.php index fb907ea2..f26fec5f 100644 --- a/app/Http/routes.php +++ b/app/Http/routes.php @@ -84,6 +84,7 @@ Route::group(['prefix' => 'api/web'], function() { Route::get('/tracks', 'Api\Web\TracksController@getIndex'); Route::get('/tracks/{id}', 'Api\Web\TracksController@getShow')->where('id', '\d+'); Route::get('/tracks/cached/{id}/{format}', 'Api\Web\TracksController@getCachedTrack')->where(['id' => '\d+', 'format' => '.+']); + Route::get('/tracks/{id}/stats', 'Api\Web\StatsController@getTrackStatsHourly')->where('id', '\d+'); Route::get('/albums', 'Api\Web\AlbumsController@getIndex'); Route::get('/albums/{id}', 'Api\Web\AlbumsController@getShow')->where('id', '\d+');