netstar pushed a commit to branch master. http://git.enlightenment.org/website/www.git/commit/?id=16b2bdc289455796898ad5c1bbcf7c0e8d5901c4
commit 16b2bdc289455796898ad5c1bbcf7c0e8d5901c4 Author: Alastair Poole <nets...@gmail.com> Date: Thu Feb 18 12:12:00 2021 +0000 weathers: rain, sleep and shines. --- public_html/weather.php | 91 ++++++++++++++++++++++++++++++++++++++++++ public_html/weather/.gitignore | 0 2 files changed, 91 insertions(+) diff --git a/public_html/weather.php b/public_html/weather.php new file mode 100644 index 00000000..f3e340e6 --- /dev/null +++ b/public_html/weather.php @@ -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(); +?> diff --git a/public_html/weather/.gitignore b/public_html/weather/.gitignore new file mode 100644 index 00000000..e69de29b --