Refactor APIs to use routing

This commit is contained in:
Dale Davies
2022-07-18 14:29:49 +01:00
parent 4b5d51ee52
commit 42568ff66c
16 changed files with 227 additions and 209 deletions

View File

@@ -0,0 +1,39 @@
<?php
namespace Jump\API;
abstract class AbstractAPI {
public function __construct(
protected \Jump\Config $config,
protected \Jump\Cache $cache,
protected \Nette\Http\Session $session,
protected ?array $routeparams
){}
protected function send_json_header(): void {
header('Content-Type: application/json; charset=utf-8');
}
protected function validate_token(): void {
$this->send_json_header();
// Get a Nette session section for CSRF data.
$csrfsection = $this->session->getSection('csrf');
// Has a CSRF token been set up for the session yet?
if (!$csrfsection->offsetExists('token')){
http_response_code(401);
die(json_encode(['error' => 'Session not fully set up']));
}
// Check CSRF token saved in session against token provided via request.
if (!isset($this->routeparams['token']) || !hash_equals($csrfsection->get('token'), $this->routeparams['token'])) {
http_response_code(401);
die(json_encode(['error' => 'API token is incorrect or missing']));
}
}
abstract protected function get_output(): string;
}

View File

@@ -0,0 +1,24 @@
<?php
namespace Jump\API;
class Icon extends AbstractAPI {
public function get_output(): string {
if (!isset($this->routeparams['siteurl']) || empty($this->routeparams['siteurl'])) {
throw new \Exception('The siteurl query parameter is not provided or empty');
}
$sites = new \Jump\Sites($this->config, $this->cache);
$siteurl = filter_var($this->routeparams['siteurl'], FILTER_SANITIZE_URL);
$site = $sites->get_site_by_url($siteurl);
$imagedata = $site->get_favicon_image_data();
// We made it here so output the API response as json.
header('Content-Type: '.$imagedata->mimetype);
return $imagedata->data;
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Jump\API;
class Unsplash extends AbstractAPI {
public function get_output(): string {
$this->validate_token();
$unsplashdata = $this->cache->load(cachename: 'unsplash');
if ($unsplashdata == null) {
$unsplashdata = \Jump\Unsplash::load_cache_unsplash_data($this->config);
$this->cache->save(cachename: 'unsplash', data: $unsplashdata);
}
$toexec = '/usr/bin/nohup /usr/bin/php -f ' . $this->config->get('wwwroot') . '/cli/cacheunsplash.php >/dev/null 2>&1 &';
shell_exec($toexec);
return json_encode($unsplashdata);
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace Jump\API;
class Weather extends AbstractAPI {
public function get_output(): string {
$this->validate_token();
// Start of variables we want to use.
$owmapiurlbase = 'https://api.openweathermap.org/data/2.5/weather';
$units = $this->config->parse_bool($this->config->get('metrictemp')) ? 'metric' : 'imperial';
// If we have either lat or lon query params then cast them to a float, if not then
// set the values to zero.
$lat = isset($this->routeparams['lat']) ? (float) $this->routeparams['lat'] : 0;
$lon = isset($this->routeparams['lat']) ? (float) $this->routeparams['lat'] : 0;
// Use the lat and lon values provided unless they are zero, this might mean that
// either they werent provided as query params or they couldn't be cast to a float.
// If they are zero then use the default latlong from config.
$latlong = [$lat, $lon];
if ($lat === 0 || $lon === 0) {
$latlong = explode(',', $this->config->get('latlong', false));
}
// This is the API endpoint and params we are using for the query,
$url = $owmapiurlbase
.'?units=' . $units
.'&lat=' . $latlong[0]
.'&lon=' . $latlong[1]
.'&appid=' . $this->config->get('owmapikey', false);
// Use the cache to store/retrieve data, make an md5 hash of latlong so it is not possible
// to track location history form the stored cache.
$weatherdata = $this->cache->load(cachename: 'weatherdata', key: md5(json_encode($latlong)), callback: function() use ($url) {
// Ask the API for some data.
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$response = curl_exec($ch);
// Just in case something went wrong with the request we'll capture the error.
if (curl_errno($ch)) {
$curlerror = curl_error($ch);
}
curl_close($ch);
// If we had an error then return the error message and exit, otherwise return the API response.
if (isset($curlerror)) {
http_response_code(400);
die(json_encode(['error' => $curlerror]));
}
return $response;
});
// We made it here so return the API response as a json string.
return $weatherdata;
}
}