weathers: rain, sleep and shines.

This commit is contained in:
Alastair Poole 2021-02-18 12:12:00 +00:00
parent 4aec8d62fd
commit 16b2bdc289
2 changed files with 91 additions and 0 deletions

91
public_html/weather.php Normal file
View File

@ -0,0 +1,91 @@
<?php
const CACHE_PATH = '/weather';
function response_code($code, $why)
{
header("HTTP/1.1 $code $why");
exit(0);
}
function weather_cache_path($lat, $lon)
{
$t = time();
$d = date('Y-m-d h', $t);
$m = date('i', $t);
// One per coord per 15 mins
$file = md5(sprintf("%s Q%d:%.4f:%.4f", $d, $m/15, $lat, $lon));
$path = $_SERVER["DOCUMENT_ROOT"] .'/'. CACHE_PATH . '/'. $file;
return $path;
}
function weather_cache_get($lat, $lon)
{
$path = weather_cache_path($lat, $lon);
if (file_exists($path)) {
$json = file_get_contents($path);
if ($json === false) {
response_code(500, "Internal Server Error");
}
return file_get_contents($path);
}
return null;
}
function weather_cache_save($lat, $lon, $json)
{
$path = weather_cache_path($lat, $lon);
if (file_put_contents($path, $json) === false) {
response_code(500, "Internal Server Error");
}
}
function weather_get($lat, $lon)
{
$json = weather_cache_get($lat, $lon);
if (isset($json)) return $json;
$url = "https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=$lat&lon=$lon";
$c = curl_init();
curl_setopt($c, CURLOPT_USERAGENT, "eWeatherProxy/1.0");
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$json = curl_exec($c);
$s = curl_getinfo($c, CURLINFO_RESPONSE_CODE);
curl_close($c);
if ($s != 200) {
response_code($s, "Meh Meh Meh");
}
weather_cache_save($lat, $lon, $json);
return $json;
}
function main()
{
if ($_SERVER['REQUEST_METHOD'] !== "GET") {
response_code(405, "Method Not Allowed");
}
if ((count($_GET) != 2) || (!isset($_GET['lon'])) || (!isset($_GET['lat']))) {
response_code(400, "Bad Request");
}
$lat = floatval($_GET['lat']);
$lon = floatval($_GET['lon']);
if ((($lat < -90) || ($lat > 90)) || (($lon < -180) || ($lon > 180))) {
response_code(400, "Bad Request");
}
$resp = weather_get($lat, $lon);
header('Content-Length: ' . strlen($resp));
header('Content-Type: application/json; charset=utf-8');
print $resp;
}
MAIN();
?>

0
public_html/weather/.gitignore vendored Normal file
View File