diff --git a/config/routes.php b/config/routes.php index 8a47199..e34d2c1 100644 --- a/config/routes.php +++ b/config/routes.php @@ -64,7 +64,7 @@ Router::scope('/', function (RouteBuilder $routes) { $routes->connect('/api/v1/status', ['controller' => 'Main', 'action' => 'apistatus']); //$routes->connect('/api/v1/recenttxs', ['controller' => 'Main', 'action' => 'apirecenttxs']); - $routes->connect('/api/v1/claims/recent', ['controller' => 'Claims', 'action' => 'apirecent']); + $routes->connect('/api/v1/claims/browse', ['controller' => 'Claims', 'action' => 'apibrowse']); //$routes->fallbacks(DashedRoute::class); }); diff --git a/src/Controller/ClaimsController.php b/src/Controller/ClaimsController.php index e252a3b..5fb6850 100644 --- a/src/Controller/ClaimsController.php +++ b/src/Controller/ClaimsController.php @@ -6,33 +6,50 @@ use Cake\Datasource\ConnectionManager; use Cake\Log\Log; class ClaimsController extends AppController { - public function apirecent() { + public function apibrowse() { $this->autoRender = false; $this->loadModel('Claims'); - $offset = 0; $pageLimit = 48; - $page = intval($this->request->query('page')); + $beforeId = intval($this->request->query('before')); + $afterId = intval($this->request->query('after')); + $sort = trim($this->request->query('sort')); + switch ($sort) { + case 'popular': + // TODO: sort by upvote/downvote score + break; + case 'random': + $order = ['RAND()' => 'ASC']; + break; + case 'oldest': + $order = ['Claims.Created' => 'ASC']; + break; + case 'newest': + default: + $order = ['Claims.Created' => 'DESC']; + break; + } $conn = ConnectionManager::get('default'); $stmt = $conn->execute('SELECT COUNT(Id) AS Total FROM Claims WHERE ThumbnailUrl IS NOT NULL AND LENGTH(TRIM(ThumbnailUrl)) > 0'); $count = $stmt->fetch(\PDO::FETCH_OBJ); $numClaims = $count->Total; - $numPages = ceil($numClaims / $pageLimit); - if ($page < 1) { - $page = 1; - } - if ($page > $numPages) { - $page = $numPages; + if ($beforeId < 0) { + $beforeId = 0; } - $offset = ($page - 1) * $pageLimit; - $claims = $this->Claims->find()->contain(['Stream', 'Publisher' => ['fields' => ['Name']]])->where( - ['Claims.ThumbnailUrl IS NOT' => null, 'LENGTH(TRIM(Claims.ThumbnailUrl)) >' => 0])-> - order(['Claims.Created' => 'DESC'])->offset($offset)->limit($pageLimit)->toArray(); + $conditions = ['Claims.ThumbnailUrl IS NOT' => null, 'LENGTH(TRIM(Claims.ThumbnailUrl)) >' => 0]; + if ($afterId > 0) { + $conditions['Claims.Id >'] = $afterId; + } else if ($beforeId) { + $conditions['Claims.Id <'] = $beforeId; + } - return $this->_jsonResponse(['success' => true, 'claims' => $claims, 'num_pages' => $numPages, 'total' => (int) $numClaims]); + $claims = $this->Claims->find()->contain(['Stream', 'Publisher' => ['fields' => ['Name']]])->where($conditions)-> + limit($pageLimit)->order($order)->toArray(); + + return $this->_jsonResponse(['success' => true, 'claims' => $claims, 'total' => (int) $numClaims]); } }