Release v2.17.2: normalize weather providers and fix unit placeholders
This commit is contained in:
1 parent
6ce70ad7cb
commit
5e23d16483
12 files changed
+296
-13
No files matched your search
+106
-3
@@ -1,5 +1,99 @@
|
||||
// Convert cached weather snapshots for display without refetching.
|
||||
|
||||
function normalizeOpenMeteoSnapshot(snapshot) {
|
||||
const result = JSON.parse(JSON.stringify(snapshot || {}));
|
||||
for (const block of ['current', 'hourly', 'daily']) {
|
||||
if (!result[block] || typeof result[block] !== 'object') result[block] = {};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function normalizePirateWeatherSnapshot(snapshot, options) {
|
||||
const source = snapshot || {};
|
||||
const units = source.flags && source.flags.units || options && options.units || 'us';
|
||||
const timezone = source.timezone || options && options.timezone || 'UTC';
|
||||
const temperatureUnit = units === 'us' ? '\u00b0F' : '\u00b0C';
|
||||
const windUnit = units === 'us' || units === 'uk' || units === 'uk2' ? 'mph' : units === 'ca' ? 'km/h' : 'm/s';
|
||||
const precipitationUnit = units === 'us' ? 'in' : 'mm';
|
||||
const number = value => value === null || value === undefined || value === '' || !Number.isFinite(Number(value)) || Number(value) === -999 ? null : Number(value);
|
||||
const percent = value => number(value) === null ? null : Math.round(Number(value) * 100);
|
||||
const timestamp = value => {
|
||||
const seconds = number(value);
|
||||
const date = seconds === null ? null : new Date(seconds * 1000);
|
||||
return date && Number.isFinite(date.getTime()) ? date.toISOString() : null;
|
||||
};
|
||||
const dateFormatter = new Intl.DateTimeFormat('en-CA', { timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit' });
|
||||
const dateOnly = value => {
|
||||
const iso = timestamp(value);
|
||||
if (!iso) return null;
|
||||
const parts = Object.fromEntries(dateFormatter.formatToParts(new Date(iso)).map(part => [part.type, part.value]));
|
||||
return parts.year + '-' + parts.month + '-' + parts.day;
|
||||
};
|
||||
const codes = { clear: 0, 'clear-day': 0, 'clear-night': 0, 'partly-cloudy-day': 2, 'partly-cloudy-night': 2, cloudy: 3, fog: 45, rain: 61, sleet: 67, snow: 71, thunderstorm: 95, hail: 96 };
|
||||
const code = entry => {
|
||||
if (codes[entry.icon] !== undefined) return codes[entry.icon];
|
||||
const clouds = number(entry.cloudCover);
|
||||
return entry.icon === 'wind' && clouds !== null ? (clouds > 0.875 ? 3 : clouds > 0.375 ? 2 : 0) : null;
|
||||
};
|
||||
const current = source.currently || {};
|
||||
const allDailyRows = (Array.isArray(source.daily && source.daily.data) ? source.daily.data : []).filter(entry => entry && typeof entry === 'object');
|
||||
const dailyRows = allDailyRows.slice(0, 7);
|
||||
const currentHour = number(current.time) === null ? null : Math.floor(Number(current.time) / 3600) * 3600;
|
||||
const allHourlyRows = (Array.isArray(source.hourly && source.hourly.data) ? source.hourly.data : []).filter(entry => entry && typeof entry === 'object');
|
||||
const hourlyRows = allHourlyRows.filter(entry => currentHour === null || number(entry.time) !== null && Number(entry.time) >= currentHour).slice(0, 24);
|
||||
const day = dailyRows.find(entry => dateOnly(entry.time) === dateOnly(current.time));
|
||||
const sunrise = day && number(day.sunriseTime);
|
||||
const sunset = day && number(day.sunsetTime);
|
||||
const isDay = /-night$/.test(current.icon || '') ? 0 : /-day$/.test(current.icon || '') ? 1
|
||||
: sunrise !== null && sunrise !== undefined && sunset !== null && sunset !== undefined && number(current.time) !== null
|
||||
? Number(Number(current.time) >= sunrise && Number(current.time) < sunset) : null;
|
||||
const columns = (rows, fields) => Object.fromEntries(Object.entries(fields).map(([field, read]) => [field, rows.map(read)]));
|
||||
const sharedUnits = { time: 'iso8601', weather_code: 'wmo code', temperature_2m: temperatureUnit, wind_speed_10m: windUnit, precipitation: precipitationUnit, uv_index: '', cloud_cover: '%' };
|
||||
return {
|
||||
latitude: source.latitude,
|
||||
longitude: source.longitude,
|
||||
timezone,
|
||||
current_units: { ...sharedUnits, apparent_temperature: temperatureUnit, relative_humidity_2m: '%', wind_direction_10m: '\u00b0', is_day: '' },
|
||||
current: {
|
||||
time: timestamp(current.time), temperature_2m: number(current.temperature), apparent_temperature: number(current.apparentTemperature),
|
||||
relative_humidity_2m: percent(current.humidity), wind_speed_10m: number(current.windSpeed), wind_direction_10m: number(current.windBearing),
|
||||
precipitation: number(current.precipIntensity), weather_code: code(current), uv_index: number(current.uvIndex), cloud_cover: percent(current.cloudCover), is_day: isDay
|
||||
},
|
||||
hourly_units: { ...sharedUnits, precipitation_probability: '%' },
|
||||
hourly: columns(hourlyRows, {
|
||||
time: entry => timestamp(entry.time), temperature_2m: entry => number(entry.temperature), precipitation: entry => number(entry.precipIntensity),
|
||||
precipitation_probability: entry => percent(entry.precipProbability), weather_code: code, wind_speed_10m: entry => number(entry.windSpeed),
|
||||
uv_index: entry => number(entry.uvIndex), cloud_cover: entry => percent(entry.cloudCover)
|
||||
}),
|
||||
daily_units: { time: 'iso8601', weather_code: 'wmo code', temperature_2m_max: temperatureUnit, temperature_2m_min: temperatureUnit, sunrise: 'iso8601', sunset: 'iso8601', precipitation_sum: precipitationUnit, precipitation_probability_max: '%', wind_speed_10m_max: windUnit, uv_index_max: '', cloud_cover_mean: '%' },
|
||||
daily: columns(dailyRows, {
|
||||
time: entry => dateOnly(entry.time), weather_code: code,
|
||||
temperature_2m_max: entry => number(entry.temperatureMax ?? entry.temperatureHigh), temperature_2m_min: entry => number(entry.temperatureMin ?? entry.temperatureLow),
|
||||
sunrise: entry => timestamp(entry.sunriseTime), sunset: entry => timestamp(entry.sunsetTime),
|
||||
precipitation_sum: (entry, index) => {
|
||||
const intensity = number(entry.precipIntensity);
|
||||
const next = allDailyRows[index + 1];
|
||||
const hours = next && number(next.time) !== null && number(entry.time) !== null ? (Number(next.time) - Number(entry.time)) / 3600 : 24;
|
||||
return intensity === null ? null : Math.round(intensity * hours * 10000) / 10000;
|
||||
},
|
||||
precipitation_probability_max: entry => percent(entry.precipProbability),
|
||||
wind_speed_10m_max: entry => {
|
||||
const winds = allHourlyRows.filter(hour => dateOnly(hour.time) === dateOnly(entry.time)).map(hour => number(hour.windSpeed)).filter(value => value !== null);
|
||||
return winds.length ? Math.max(...winds) : null;
|
||||
},
|
||||
uv_index_max: entry => number(entry.uvIndex), cloud_cover_mean: entry => percent(entry.cloudCover)
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeWeatherSnapshot(snapshot, provider, options) {
|
||||
const source = snapshot && typeof snapshot === 'object' ? snapshot : {};
|
||||
const pirateShape = source.currently || Array.isArray(source.hourly && source.hourly.data) || Array.isArray(source.daily && source.daily.data);
|
||||
return pirateShape || provider === 'pirate-weather' && !source.current
|
||||
? normalizePirateWeatherSnapshot(source, options)
|
||||
: normalizeOpenMeteoSnapshot(source);
|
||||
}
|
||||
|
||||
function convertTemperature(value, fromUnit, toUnit) {
|
||||
const number = Number(value);
|
||||
if (!Number.isFinite(number) || fromUnit === toUnit) return value;
|
||||
@@ -39,13 +133,13 @@ function convertField(data, fields, converter, fromUnit, toUnit) {
|
||||
fields.forEach(function (field) {
|
||||
if (data[field] === undefined || data[field] === null) return;
|
||||
data[field] = Array.isArray(data[field])
|
||||
? data[field].map(function (value) { return converter(value, fromUnit, toUnit); })
|
||||
? data[field].map(function (value) { return value === null || value === undefined ? value : converter(value, fromUnit, toUnit); })
|
||||
: converter(data[field], fromUnit, toUnit);
|
||||
});
|
||||
}
|
||||
|
||||
function convertWeatherSnapshot(snapshot, targetUnits) {
|
||||
const source = snapshot && typeof snapshot === 'object' ? snapshot : {};
|
||||
const source = normalizeWeatherSnapshot(snapshot);
|
||||
const target = Object.assign({ temperature: 'celsius', wind: 'kmh', precipitation: 'mm' }, targetUnits || {});
|
||||
const result = JSON.parse(JSON.stringify(source));
|
||||
const currentUnits = source.current_units || {};
|
||||
@@ -61,7 +155,16 @@ function convertWeatherSnapshot(snapshot, targetUnits) {
|
||||
convertField(result.daily || {}, ['temperature_2m_max', 'temperature_2m_min'], convertTemperature, temperatureUnitFromLabel(dailyUnits.temperature_2m_max), target.temperature);
|
||||
convertField(result.daily || {}, ['wind_speed_10m_max'], convertWind, windUnitFromLabel(dailyUnits.wind_speed_10m_max), target.wind);
|
||||
convertField(result.daily || {}, ['precipitation_sum'], convertPrecipitation, precipitationUnitFromLabel(dailyUnits.precipitation_sum), target.precipitation);
|
||||
for (const block of ['current', 'hourly', 'daily']) {
|
||||
const metadata = result[block + '_units'] || {};
|
||||
for (const field of Object.keys(result[block])) {
|
||||
if (['temperature_2m', 'apparent_temperature', 'temperature_2m_max', 'temperature_2m_min'].includes(field)) metadata[field] = target.temperature === 'fahrenheit' ? '\u00b0F' : '\u00b0C';
|
||||
if (['wind_speed_10m', 'wind_speed_10m_max'].includes(field)) metadata[field] = target.wind === 'mph' ? 'mph' : target.wind === 'ms' ? 'm/s' : 'km/h';
|
||||
if (['precipitation', 'rain', 'precipitation_sum'].includes(field)) metadata[field] = target.precipitation === 'inch' ? 'in' : 'mm';
|
||||
}
|
||||
result[block + '_units'] = metadata;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
module.exports = { convertWeatherSnapshot };
|
||||
module.exports = { convertWeatherSnapshot, normalizeWeatherSnapshot, normalizeOpenMeteoSnapshot, normalizePirateWeatherSnapshot };
|
||||
+5
-1
@@ -2,6 +2,7 @@
|
||||
|
||||
const { fetchPagedRows, validateMaxLength } = require('#src/data/utils');
|
||||
const { fetchAppSettings } = require('#src/data/app-settings');
|
||||
const { normalizeWeatherSnapshot } = require('#src/data/weather-units');
|
||||
|
||||
const NAME_MAX_LENGTH = 255;
|
||||
const LOCATION_MAX_LENGTH = 255;
|
||||
@@ -97,7 +98,10 @@ async function fetchWeatherLocationForecast(pool, location) {
|
||||
|
||||
const response = await fetch(url, { headers: headers });
|
||||
if (!response.ok) throw new Error('Weather provider returned HTTP ' + response.status + '.');
|
||||
const snapshot = await response.json();
|
||||
const snapshot = normalizeWeatherSnapshot(await response.json(), source.provider, {
|
||||
units: temperatureUnit === 'fahrenheit' ? 'us' : 'si',
|
||||
timezone: source.timezone
|
||||
});
|
||||
return { snapshot: snapshot, responseJson: JSON.stringify(snapshot), fetchedAt: new Date() };
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ function getWeatherLocation(locationId) {
|
||||
function normalizeWeatherExpression(expression) {
|
||||
var value = String(expression || '').trim();
|
||||
var currentAliases = { temp: 'current.temperature_2m', temp_unit: 'current.temperature_unit', feels_like: 'current.apparent_temperature', humidity: 'current.relative_humidity_2m', code: 'current.weather_code', wind: 'current.wind_speed_10m', wind_unit: 'current.wind_speed_unit', precip: 'current.precipitation', precip_unit: 'current.precipitation_unit', uv_index: 'current.uv_index', cloud_cover: 'current.cloud_cover', icon: 'current.weather_code.icon' };
|
||||
var globalAliases = { temp_unit: 'temperature_unit', wind_unit: 'wind_speed_unit', precip_unit: 'precipitation_unit' };
|
||||
var globalAliases = { temp_unit: 'current.temperature_unit', wind_unit: 'current.wind_speed_unit', precip_unit: 'current.precipitation_unit' };
|
||||
if (globalAliases[value]) return globalAliases[value];
|
||||
var currentField = value.replace(/^current\./, '');
|
||||
var currentMatch = currentField.match(/^([^.()]+)((?:\(.*\))|(?:\..*))?$/);
|
||||
|
||||
@@ -169,7 +169,7 @@ function getImagePlaceholderConfig(expression) {
|
||||
function normalizeWeatherExpression(expression) {
|
||||
const value = String(expression || '').trim();
|
||||
const currentAliases = { temp: 'current.temperature_2m', feels_like: 'current.apparent_temperature', humidity: 'current.relative_humidity_2m', wind: 'current.wind_speed_10m', precip: 'current.precipitation', uv_index: 'current.uv_index', cloud_cover: 'current.cloud_cover', icon: 'current.weather_code.icon' };
|
||||
const globalAliases = { temp_unit: 'temperature_unit', wind_unit: 'wind_speed_unit', precip_unit: 'precipitation_unit' };
|
||||
const globalAliases = { temp_unit: 'current.temperature_unit', wind_unit: 'current.wind_speed_unit', precip_unit: 'current.precipitation_unit' };
|
||||
if (globalAliases[value]) return globalAliases[value];
|
||||
const currentField = value.replace(/^current\./, '').match(/^([^.()]+)((?:\(.*\))|(?:\..*))?$/);
|
||||
if (currentField && currentAliases[currentField[1]]) return currentAliases[currentField[1]] + (currentField[2] || '');
|
||||
|
||||
@@ -83,7 +83,7 @@
|
||||
var currentAliases = {
|
||||
temp: 'current.temperature_2m', temp_unit: 'current.temperature_unit', feels_like: 'current.apparent_temperature', humidity: 'current.relative_humidity_2m', code: 'current.weather_code', wind: 'current.wind_speed_10m', wind_unit: 'current.wind_speed_unit', precip: 'current.precipitation', precip_unit: 'current.precipitation_unit', uv_index: 'current.uv_index', cloud_cover: 'current.cloud_cover', icon: 'current.weather_code.icon'
|
||||
};
|
||||
var globalAliases = { temp_unit: 'temperature_unit', wind_unit: 'wind_speed_unit', precip_unit: 'precipitation_unit' };
|
||||
var globalAliases = { temp_unit: 'current.temperature_unit', wind_unit: 'current.wind_speed_unit', precip_unit: 'current.precipitation_unit' };
|
||||
if (globalAliases[value]) return globalAliases[value];
|
||||
var currentField = value.replace(/^current\./, '').match(/^([^.()]+)((?:\(.*\))|(?:\..*))?$/);
|
||||
if (currentField && currentAliases[currentField[1]]) return currentAliases[currentField[1]] + (currentField[2] || '');
|
||||
|
||||
Reference in new issue
Block a user