Skip to content

Instantly share code, notes, and snippets.

@cprima
Last active June 22, 2024 06:54
Show Gist options
  • Save cprima/e12288200c5a6f8857d25a240f9001ca to your computer and use it in GitHub Desktop.
Save cprima/e12288200c5a6f8857d25a240f9001ca to your computer and use it in GitHub Desktop.
travel route weather display

Travel Route Weather Display

This application retrieves weather forecasts and current weather data for a list of cities based on their city IDs and visit dates. The data is fetched from the OpenWeatherMap API, cached, processed to find the forecast for noon on specific visit dates, and then displayed in a user-friendly HTML format.

Features

  • Fetches weather forecast and current weather data from the OpenWeatherMap API.
  • Caches the fetched data to reduce API calls and improve performance.
  • Retrieves and processes the forecast for noon on specific visit dates.
  • Includes cache metadata (hit/miss status and cache age) in the output.
  • Formats the visit date in German for display purposes.
  • Displays the weather data in an interactive HTML page.

Prerequisites

  • PHP 7.0 or higher
  • cURL for PHP
  • OpenWeatherMap API key
  • Internet connection to access the OpenWeatherMap API

Installation

  1. Clone the repository:

    git clone https://github.com/yourusername/weather-forecast-app.git
    cd weather-forecast-app
  2. Create a .env file in the root directory and add your OpenWeatherMap API key:

    OPENWEATHERMAP_APIKEY=your_api_key_here
  3. Ensure the cache directories exist and are writable:

    mkdir -p cache permanentcache
    chmod 777 cache permanentcache

Usage

Point to the backend

The PHP script retrieves weather data, processes it, and serves it as JSON.

  • Endpoint: backend.php
  • Change the frontend.html to point to you r location:
    const url = 'https://example.com/backend.php';

Viewing the HTML Page

The HTML page fetches the weather data from the PHP script and displays it in a user-friendly format.

  • Adopt the CSS for body background-image
  • Open the frontend.html file in a web browser:
    open frontend.html

Cron Job for Cache Warming

To ensure the cache is warmed up periodically, you can set up a cron job to call the backend PHP script.

  1. Make the script executable:

    chmod +x warmup_cache.sh
  2. Set up the cron job:

    crontab -e

    Add the following line to schedule the script to run every hour and redirect all output to /dev/null:

    0 * * * * /path/to/warmup_cache.sh > /dev/null 2>&1

File Descriptions

PHP Script (backend.php)

The PHP script fetches weather data from the OpenWeatherMap API, caches the results, and serves them as JSON. It includes the following key functions:

  • fetchFromAPI($url): Fetches data from the specified API URL using cURL.
  • getWeatherForecast($cityId, $dateVisited): Retrieves and caches the weather forecast data for a city on a specific date.
  • getCurrentWeather($cityId, $dateVisited): Retrieves and caches the current weather data for a city on a specific date.
  • getNoonForecast($weatherData, $dateVisited): Finds the forecast for noon or the closest time on the visit date.
  • processForecast($noonForecast): Processes the forecast data to extract relevant information.
  • getCityInfo($weatherData, $currentWeatherData): Retrieves city information from the weather data.
  • kelvinToCelsius($kelvin): Converts temperature from Kelvin to Celsius.
  • getRelativeDate($dateVisited, $currentDate): Formats the visit date in German.

HTML File (index.html)

The HTML file displays the weather data in a user-friendly format. It includes:

  • Styles for a clean and modern look.
  • JavaScript to fetch weather data from the PHP script and display it dynamically.
  • Translations for weather descriptions from English to German.

License

This project is licensed under the CC BY 4.0 License.

Author

Christian Prior-Mamulyan
cprior@gmail.com

<?php
/**
* Weather Forecast Script
*
* This script retrieves weather forecast and current weather data for a list of cities
* based on their city IDs and visit dates. It fetches data from the OpenWeatherMap API,
* caches the data, and processes it to find the forecast for noon on specific visit dates.
* The results are then formatted and output as JSON.
*
* Features:
* - Fetches weather forecast and current weather data from the OpenWeatherMap API.
* - Caches the fetched data to reduce API calls and improve performance.
* - Retrieves and processes the forecast for noon on specific visit dates.
* - Includes cache metadata (hit/miss status and cache age) in the output.
* - Formats the visit date in German for display purposes.
*
* Functions:
* - fetchFromAPI($url): Fetches data from the specified API URL using cURL.
* - getWeatherForecast($cityId, $apiKey): Retrieves and caches the weather forecast data for a city.
* - getCurrentWeather($cityId, $apiKey): Retrieves and caches the current weather data for a city.
* - getNoonForecast($weatherData, $dateVisited): Finds the forecast for noon or the closest time on the visit date.
* - processForecast($noonForecast): Processes the forecast data to extract relevant information.
* - getCityInfo($weatherData, $currentWeatherData): Retrieves city information from the weather data.
* - kelvinToCelsius($kelvin): Converts temperature from Kelvin to Celsius.
* - getRelativeDate($dateVisited, $currentDate): Formats the visit date in German.
*
*
* Weaknesses and Limitations:
* - Timezone Issues: The script assumes the server's timezone for date and time operations. It does not account for the timezone differences between the server and the locations being queried.
* - No Cache Expiry for Permanent Cache: The permanent cache never expires, which may lead to outdated data being used indefinitely.
* - Limited Error Handling: The script does not handle errors returned from the API calls gracefully.
* -
*
* Usage:
* 1. Create a .env file with your OpenWeatherMap API key.
* 2. List the city IDs and their corresponding visit dates.
* 3. Run the script to fetch, process, and output the weather data as JSON.
*
* Example .env file:
* ```ini
* OPENWEATHERMAP_APIKEY=your_api_key_here
* ```
*
* Example usage in PHP script:
* ```php
* <?php
* $cityVisits = [
* ['cityId' => 2832495, 'dateVisited' => '2024-06-21'],
* ['cityId' => 2832495, 'dateVisited' => '2024-06-22'],
* ];
* ?>
* ```
*
* Note:
* - Ensure the cache directories exist and are writable.
* - This script is designed to be run infrequently to minimize API calls.
*
* @version 1.0
* @license CC BY 4.0
*
* @author Christian Prior-Mamulyan <cprior@gmail.com>
*/
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
// Load API key from .env file
$envFilePath = '../weather/.env';
if (file_exists($envFilePath)) {
$dotenv = parse_ini_file($envFilePath);
if (isset($dotenv['OPENWEATHERMAP_APIKEY'])) {
define('OPENWEATHERMAP_APIKEY', $dotenv['OPENWEATHERMAP_APIKEY']);
} else {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(['error' => 'OPENWEATHERMAP_APIKEY not found in .env file.']);
exit;
}
} else {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(['error' => '.env file not found.']);
exit;
}
define('CACHE_LIFETIME', 7200); // Cache lifetime in seconds
// List of city IDs and their corresponding visit dates
$cityVisits = [
['cityId' => 2832495, 'dateVisited' => '2024-06-22'], // Siegen
['cityId' => 3033123, 'dateVisited' => '2024-06-23'], // Besançon
['cityId' => 3014728, 'dateVisited' => '2024-06-24'], // Grenoble
['cityId' => 3028382, 'dateVisited' => '2024-06-25'], // Castellane
['cityId' => 2995469, 'dateVisited' => '2024-06-26'], // Marseille
['cityId' => 3032833, 'dateVisited' => '2024-06-27'], // Béziers
['cityId' => 3128978, 'dateVisited' => '2024-06-28'], // Balaguer
['cityId' => 3126580, 'dateVisited' => '2024-06-29'], // Canfranc
['cityId' => 3031582, 'dateVisited' => '2024-06-30'], // Bordeaux
['cityId' => 3037025, 'dateVisited' => '2024-07-01'], // Argenton
['cityId' => 2971549, 'dateVisited' => '2024-07-02'], // Troyes
['cityId' => 6554291, 'dateVisited' => '2024-07-03'], // Trier
];
// Cache directory
$cacheDir = __DIR__ . '/cache/';
if (!file_exists($cacheDir)) {
mkdir($cacheDir, 0777, true);
}
$archiveCacheDir = __DIR__ . '/permanentcache/';
if (!file_exists($archiveCacheDir)) {
mkdir($archiveCacheDir, 0777, true);
}
/**
* Fetch data from the specified API URL using cURL
*
* @param string $url The API URL to fetch data from
* @return string|null The response data or null if an error occurred
*/
function fetchFromAPI($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);
if (curl_errno($ch) || curl_getinfo($ch, CURLINFO_HTTP_CODE) >= 400) {
curl_close($ch);
return null;
}
curl_close($ch);
return $response;
}
/**
* Retrieve and cache the weather forecast data for a city on a specific date
*
* @param int $cityId The ID of the city to retrieve the forecast for
* @param string $dateVisited The date for which to retrieve the forecast
* @return array|null The weather forecast data and cache metadata or null if an error occurred
*/
function getWeatherForecast($cityId, $dateVisited) {
global $cacheDir, $archiveCacheDir;
$cacheFile = "{$cacheDir}/forecast_{$cityId}_{$dateVisited}.json";
$archiveCacheFile = "{$archiveCacheDir}/latest_{$cityId}_{$dateVisited}.json";
$cacheMetadata = [
'cacheStatus' => 'miss',
'cacheFileTime' => null
];
// Check if the archive cache should be used
$currentDate = new DateTime();
$visitDate = new DateTime($dateVisited);
$visitDate->setTime(12, 0); // Set visit date time to 12:00 noon
if (file_exists($archiveCacheFile) && $currentDate >= $visitDate) {
$cacheMetadata['cacheStatus'] = 'hit';
$cacheMetadata['cacheFileTime'] = filemtime($archiveCacheFile);
return [
'data' => json_decode(file_get_contents($archiveCacheFile), true),
'cacheMetadata' => $cacheMetadata
];
}
// Check if regular cache is valid
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < CACHE_LIFETIME) {
$cacheMetadata['cacheStatus'] = 'hit';
$cacheMetadata['cacheFileTime'] = filemtime($cacheFile);
return [
'data' => json_decode(file_get_contents($cacheFile), true),
'cacheMetadata' => $cacheMetadata
];
}
// Fetch data from API
$url = "http://api.openweathermap.org/data/2.5/forecast?id={$cityId}&appid=" . OPENWEATHERMAP_APIKEY;
$forecastData = fetchFromAPI($url);
if ($forecastData === null) {
return null;
}
// Save data to cache
file_put_contents($cacheFile, $forecastData);
file_put_contents($archiveCacheFile, $forecastData);
return [
'data' => json_decode($forecastData, true),
'cacheMetadata' => $cacheMetadata
];
}
/**
* Retrieve and cache the current weather data for a city on a specific date
*
* @param int $cityId The ID of the city to retrieve the current weather for
* @param string $dateVisited The date for which to retrieve the current weather
* @return array|null The current weather data and cache metadata or null if an error occurred
*/
function getCurrentWeather($cityId, $dateVisited) {
global $cacheDir, $archiveCacheDir;
$cacheFile = "{$cacheDir}/current_{$cityId}_{$dateVisited}.json";
$archiveCacheFile = "{$archiveCacheDir}/latest_{$cityId}_{$dateVisited}.json";
$cacheMetadata = [
'cacheStatus' => 'miss',
'cacheFileTime' => null
];
// Check if the archive cache should be used
$currentDate = new DateTime();
$visitDate = new DateTime($dateVisited);
$visitDate->setTime(12, 0); // Set visit date time to 12:00 noon
if (file_exists($archiveCacheFile) && $currentDate >= $visitDate) {
$cacheMetadata['cacheStatus'] = 'hit';
$cacheMetadata['cacheFileTime'] = filemtime($archiveCacheFile);
return [
'data' => json_decode(file_get_contents($archiveCacheFile), true),
'cacheMetadata' => $cacheMetadata
];
}
// Check if regular cache is valid
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < CACHE_LIFETIME) {
$cacheMetadata['cacheStatus'] = 'hit';
$cacheMetadata['cacheFileTime'] = filemtime($cacheFile);
return [
'data' => json_decode(file_get_contents($cacheFile), true),
'cacheMetadata' => $cacheMetadata
];
}
// Fetch data from API
$url = "http://api.openweathermap.org/data/2.5/weather?id={$cityId}&appid=" . OPENWEATHERMAP_APIKEY;
$weatherData = fetchFromAPI($url);
if ($weatherData === null) {
return null;
}
// Save data to cache
file_put_contents($cacheFile, $weatherData);
file_put_contents($archiveCacheFile, $weatherData);
return [
'data' => json_decode($weatherData, true),
'cacheMetadata' => $cacheMetadata
];
}
/**
* Find the forecast for noon or the closest time on the visit date
*
* @param array $weatherData The weather data to search through
* @param string $dateVisited The date to find the noon forecast for
* @return array|null The noon forecast data or null if not found
*/
function getNoonForecast($weatherData, $dateVisited) {
foreach ($weatherData['list'] as $forecast) {
$forecastDateTime = strtotime($forecast['dt_txt']);
$forecastDate = date('Y-m-d', $forecastDateTime);
$forecastHour = date('H', $forecastDateTime);
if ($forecastDate == $dateVisited && $forecastHour == '12') {
return $forecast;
}
}
// If no exact noon forecast found, get the closest time
foreach ($weatherData['list'] as $forecast) {
$forecastDateTime = strtotime($forecast['dt_txt']);
$forecastDate = date('Y-m-d', $forecastDateTime);
if ($forecastDate == $dateVisited) {
return $forecast;
}
}
return null;
}
/**
* Process the forecast data to extract relevant information
*
* @param array|null $noonForecast The noon forecast data to process
* @return array The processed forecast information
*/
function processForecast($noonForecast) {
if ($noonForecast) {
$temperature = kelvinToCelsius($noonForecast['main']['temp']);
$feelsLike = kelvinToCelsius($noonForecast['main']['feels_like']);
$tempMin = kelvinToCelsius($noonForecast['main']['temp_min']);
$tempMax = kelvinToCelsius($noonForecast['main']['temp_max']);
$icon = isset($noonForecast['weather'][0]['icon']) ? $noonForecast['weather'][0]['icon'] : '';
$forecastDescription = $noonForecast['weather'][0]['description'];
} else {
$temperature = $feelsLike = $tempMin = $tempMax = null;
$icon = $forecastDescription = '';
}
return [
'temperature' => $temperature,
'feelsLike' => $feelsLike,
'tempMin' => $tempMin,
'tempMax' => $tempMax,
'icon' => $icon,
'forecastDescription' => $forecastDescription
];
}
/**
* Retrieve city information from the weather data
*
* @param array|null $weatherData The weather forecast data
* @param array|null $currentWeatherData The current weather data
* @return array The city information
*/
function getCityInfo($weatherData, $currentWeatherData) {
if (isset($weatherData['data']['city'])) {
return $weatherData['data']['city'];
}
if ($currentWeatherData) {
return [
'name' => $currentWeatherData['data']['name'],
'country' => $currentWeatherData['data']['sys']['country'],
'coord' => [
'lat' => $currentWeatherData['data']['coord']['lat'],
'lon' => $currentWeatherData['data']['coord']['lon']
],
'sunrise' => $currentWeatherData['data']['sys']['sunrise'],
'sunset' => $currentWeatherData['data']['sys']['sunset']
];
}
return [
'name' => '',
'country' => '',
'coord' => ['lat' => null, 'lon' => null],
'sunrise' => null,
'sunset' => null
];
}
/**
* Iterate over each city visit, fetch the weather data, process the noon forecast,
* retrieve city information, and prepare the data for JSON output.
*
* For each visit:
* 1. Retrieve the weather forecast data.
* 2. Retrieve the current weather data as a fallback.
* 3. Find and process the forecast for noon on the visit date.
* 4. Retrieve city information from the forecast or current weather data.
* 5. Format the data, including cache metadata, for JSON output.
*/
$forecasts = [];
$currentDate = date('Y-m-d');
foreach ($cityVisits as $visit) {
$cityId = $visit['cityId'];
$dateVisited = $visit['dateVisited'];
$formattedDate = getRelativeDate($dateVisited, $currentDate);
// Get the weather forecast for the city
$weatherData = getWeatherForecast($cityId, $dateVisited);
$currentWeatherData = getCurrentWeather($cityId, $dateVisited);
// Get the noon forecast
$noonForecast = getNoonForecast($weatherData['data'], $dateVisited);
$forecast = processForecast($noonForecast);
// Get the city information
$cityInfo = getCityInfo($weatherData, $currentWeatherData);
$latitude = $cityInfo['coord']['lat'];
$longitude = $cityInfo['coord']['lon'];
$sunrise = date('H:i', $cityInfo['sunrise']);
$sunset = date('H:i', $cityInfo['sunset']);
$forecasts[] = [
'cityId' => $cityId,
'dateVisited' => $dateVisited,
'formattedDate' => $formattedDate,
'cityName' => $cityInfo['name'],
'country' => $cityInfo['country'],
'latitude' => $latitude,
'longitude' => $longitude,
'sunrise' => $sunrise,
'sunset' => $sunset,
'weather' => [
'temperature' => $forecast['temperature'] !== null ? round($forecast['temperature'], 2) : 'N/A',
'feelsLike' => $forecast['feelsLike'] !== null ? round($forecast['feelsLike'], 2) : 'N/A',
'tempMin' => $forecast['tempMin'] !== null ? round($forecast['tempMin'], 2) : 'N/A',
'tempMax' => $forecast['tempMax'] !== null ? round($forecast['tempMax'], 2) : 'N/A',
'description' => $forecast['forecastDescription']
],
'icon' => $forecast['icon'] ? "http://openweathermap.org/img/wn/{$forecast['icon']}.png" : '',
'forecastCache' => $weatherData['cacheMetadata']
];
}
// Control output to ensure only JSON is returned
ob_start();
header('Content-Type: application/json');
echo json_encode($forecasts);
// Flush output buffer
ob_end_flush();
// Helper functions
/**
* Convert temperature from Kelvin to Celsius
*
* @param float $kelvin The temperature in Kelvin
* @return float The temperature in Celsius
*/
function kelvinToCelsius($kelvin) {
return $kelvin - 273.15;
}
/**
* Format the visit date in German
*
* @param string $dateVisited The visit date to format
* @param string $currentDate The current date
* @return string The formatted visit date in German
*/
function getRelativeDate($dateVisited, $currentDate) {
$dateVisitedTimestamp = strtotime($dateVisited);
$currentDateTimestamp = strtotime($currentDate);
$diffDays = ceil(($dateVisitedTimestamp - $currentDateTimestamp) / (60 * 60 * 24));
if ($diffDays > 0) {
return $diffDays == 1 ? "in 1 Tag" : "in $diffDays Tagen";
} else if ($diffDays < 0) {
return abs($diffDays) == 1 ? "vor 1 Tag" : "vor " . abs($diffDays) . " Tagen";
} else {
return "heute";
}
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Wettervorhersage</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #fdf6e3;
color: #586e75;
background-image: url('/RnD/jeollerjedoller.png');
background-position: bottom right;
background-repeat: no-repeat;
background-size: cover;
background-attachment: fixed;
}
.container {
display: flex;
flex-wrap: wrap;
justify-content: center;
padding: 20px;
}
.card {
background: rgba(238, 232, 213, 0.9); /* 90% transparent */
border-radius: 10px;
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
margin: 20px;
padding: 20px;
width: 320px;
box-sizing: border-box;
text-align: center;
transition: transform 0.2s;
}
.card:hover {
transform: scale(1.05);
}
.card img {
width: 50px;
height: 50px;
}
.card h2 {
margin: 10px 0;
color: #073642;
}
.card p {
margin: 5px 0;
color: #586e75;
}
.card .cache-info {
color: rgba(147, 161, 161, 0.7);
}
.highlight {
border: 2px solid #cb4b16; /* Solarized Orange */
}
h1 {
text-align: center;
margin-top: 20px;
color: #073642;
}
@media (max-width: 600px) {
.card {
width: 90%;
}
}
</style>
</head>
<body>
<h1>Je oller, je doller</h1>
<div class="container" id="weather-container">
<!-- Wetterkarten werden hier eingefügt -->
</div>
<script>
const translations = {
"clear sky": "klarer Himmel",
"few clouds": "wenige Wolken",
"scattered clouds": "vereinzelte Wolken",
"broken clouds": "aufgelockerte Bewölkung",
"overcast clouds": "bedeckt",
"shower rain": "Regenschauer",
"rain": "Regen",
"light rain": "leichter Regen",
"moderate rain": "mäßiger Regen",
"heavy intensity rain": "starker Regen",
"very heavy rain": "sehr starker Regen",
"extreme rain": "extremer Regen",
"freezing rain": "Eisregen",
"light intensity shower rain": "leichte Regenschauer",
"heavy intensity shower rain": "starke Regenschauer",
"ragged shower rain": "unregelmäßige Regenschauer",
"thunderstorm": "Gewitter",
"thunderstorm with light rain": "Gewitter mit leichtem Regen",
"thunderstorm with rain": "Gewitter mit Regen",
"thunderstorm with heavy rain": "Gewitter mit starkem Regen",
"light thunderstorm": "leichtes Gewitter",
"heavy thunderstorm": "starkes Gewitter",
"ragged thunderstorm": "unregelmäßiges Gewitter",
"thunderstorm with light drizzle": "Gewitter mit leichtem Nieselregen",
"thunderstorm with drizzle": "Gewitter mit Nieselregen",
"thunderstorm with heavy drizzle": "Gewitter mit starkem Nieselregen",
"snow": "Schnee",
"light snow": "leichter Schnee",
"heavy snow": "starker Schnee",
"sleet": "Schneeregen",
"light shower sleet": "leichter Schneeregen",
"shower sleet": "Schneeregen",
"light rain and snow": "leichter Regen und Schnee",
"rain and snow": "Regen und Schnee",
"light shower snow": "leichte Schneeschauer",
"shower snow": "Schneeschauer",
"heavy shower snow": "starke Schneeschauer",
"mist": "Nebel",
"smoke": "Rauch",
"haze": "Dunst",
"sand/ dust whirls": "Sand-/Staubwirbel",
"fog": "Nebel",
"sand": "Sand",
"dust": "Staub",
"volcanic ash": "Vulkanausbruch",
"squalls": "Böen",
"tornado": "Tornado",
"tropical storm": "tropischer Sturm",
"hurricane": "Hurrikan",
"cold": "kalt",
"hot": "heiß",
"windy": "windig",
"hail": "Hagel"
};
function translateWeather(description) {
return translations[description.toLowerCase()] || description;
}
function getCacheInfo(item) {
if (item.forecastCache.cacheStatus === 'miss') {
return 'Cache miss';
} else {
const cacheAgeHours = Math.round((Date.now() / 1000 - item.forecastCache.cacheFileTime) / 3600);
return `Cache age: ${cacheAgeHours} hours`;
}
}
async function fetchWeatherData() {
const url = 'https://cpr.in-berlin.de/jeollerjedoller/backend.php';
try {
const response = await fetch(url);
const data = await response.json();
displayWeatherData(data);
} catch (error) {
console.error('Fehler beim Abrufen der Wetterdaten:', error);
document.getElementById('weather-container').innerHTML = '<p>Wetterdaten konnten nicht geladen werden. Bitte versuchen Sie es später noch einmal.</p>';
}
}
function displayWeatherData(data) {
const container = document.getElementById('weather-container');
container.innerHTML = '';
if (data.length === 0) {
container.innerHTML = '<p>Keine Wetterdaten verfügbar.</p>';
return;
}
data.forEach(item => {
const currentDate = new Date().toISOString().split('T')[0];
const isToday = item.formattedDate === 'heute';
const cardClass = isToday ? 'card highlight' : 'card';
const card = document.createElement('div');
card.className = cardClass;
card.innerHTML = `
<h2>${item.cityName}</h2>
<p>${item.country}</p>
<p><strong>Wann:</strong> ${item.formattedDate}</p>
<p><strong>Sonnenaufgang:</strong> ${item.sunrise}</p>
<p><strong>Sonnenuntergang:</strong> ${item.sunset}</p>
${item.icon ? `<img src="${item.icon}" alt="Wettericon">` : ''}
<p><strong>Vorhersage:</strong> ${translateWeather(item.weather.description) || 'Nicht verfügbar'}</p> <p><strong>Temperatur:</strong> ${item.weather.temperature !== 'N/A' ? Math.round(item.weather.temperature) + ' °C' : 'Nicht verfügbar'}</p>
<p class="cache-info">${getCacheInfo(item)}</p>
`;
container.appendChild(card);
});
}
fetchWeatherData();
</script>
</body>
</html>
#!/bin/bash
# URL to warm up the cache
URL="https://cpr.in-berlin.de/jeollerjedoller/backend.php"
# Determine the script's directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Log file path relative to the script's location
LOG_FILE="$SCRIPT_DIR/warmup_cache.log"
# Send a request to the URL
response=$(curl --write-out "%{http_code}" --silent --output /dev/null $URL)
# Check if the response code is 200 (OK)
if [ "$response" -eq 200 ]; then
echo "$(date): Cache warmed up successfully." >> "$LOG_FILE"
else
echo "$(date): Failed to warm up cache. HTTP status code: $response" >> "$LOG_FILE"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment