Files
toolshed-extensions/yr/init.lua
T

251 lines
11 KiB
Lua

-- Yr: "yr bergen" finds places as yr.no does; Enter shows the weather there now, hour by hour
-- and for the week, from MET Norway, with yr.no's own weather symbols. ⌘K opens the place on yr.no.
-- Its text is in locales/, and places are named in the language Toolshed speaks.
-- MET Norway asks automated clients to say what they are, and turns away those that don't.
local agent = "Toolshed-Yr-extension/1.0"
-- MET Norway's weather symbols, the ones yr.no shows (https://github.com/metno/weathericons).
local symbols = "https://cdn.jsdelivr.net/gh/metno/weathericons@main/weather/svg/"
local encode = toolshed.url_encode
local escape = toolshed.escape
local function get(url, max_seconds)
return toolshed.json.decode(toolshed.exec({ "curl", "-sSfL", "--max-time", tostring(max_seconds), "-A", agent, url }))
end
local function symbol(code, size)
if not code then return "" end
return '<img src="' .. symbols .. escape(code) .. '.svg" alt="" width="' .. size .. '" height="' .. size ..
'" style="vertical-align:middle">'
end
-- "lightrainshowers_day" says "Light rain showers"; by day or night reads the same.
local function describe(code)
return toolshed.t("symbol." .. (code or ""):gsub("_.*", ""))
end
-- yr.no speaks English, Bokmål and Nynorsk.
local function language()
local locale = toolshed.locale()
return (locale == "nb" or locale == "nn") and locale or "en"
end
-- Forecasts are given in UTC; they're shown in the place's own time, offset as it is now.
local function utc_offset(zone)
local ok, out = pcall(toolshed.exec, { "env", "TZ=" .. zone, "date", "+%z" })
local sign, hours, minutes = (ok and out or ""):match("([+-])(%d%d)(%d%d)")
if not sign then return 0 end
return (sign == "-" and -1 or 1) * (tonumber(hours) * 3600 + tonumber(minutes) * 60)
end
-- local_time turns "2026-11-18T06:00:00Z" into a time to format with os.date as the place's.
local function local_time(iso, offset)
local y, mo, d, h, mi = iso:match("^(%d+)-(%d+)-(%d+)T(%d+):(%d+)")
return os.time({ year = tonumber(y), month = tonumber(mo), day = tonumber(d), hour = tonumber(h), min = tonumber(mi) + math.floor(offset / 60) })
end
local compass = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" }
local function direction(degrees)
return toolshed.t("compass." .. compass[math.floor(((degrees or 0) + 22.5) / 45) % 8 + 1])
end
-- "Wednesday 25 Nov", as the language says it; os.date only knows English.
local function date(time)
local d = os.date("*t", time)
return toolshed.t("date", { weekday = toolshed.t("weekday." .. d.wday), day = d.day, month = toolshed.t("month." .. d.month) })
end
-- 2.5 in English, 2,5 in Norwegian.
local function number(n)
local text = string.format("%.1f", n):gsub("%.0$", ""):gsub("^%-0$", "0")
return (text:gsub("%.", toolshed.t("decimal")))
end
local function temperature(t)
return string.format("%d°", math.floor(t + 0.5))
end
local function tile(icon)
return '<span class="tile" data-icon="' .. icon .. '"></span>'
end
local function sparkline(values, from_zero)
local text = {}
for _, v in ipairs(values) do table.insert(text, string.format("%.4g", v)) end
return '<svg class="spark" data-values="' .. table.concat(text, " ") .. '"' .. (from_zero and " data-from-zero" or "") .. "></svg>"
end
local function figure(label, value, icon, tint, values, from_zero)
return '<div class="figure" data-tint="' .. tint .. '">' .. tile(icon) .. '<div class="value">' .. value ..
'</div><div class="label">' .. escape(label) .. "</div>" .. sparkline(values, from_zero) .. "</div>"
end
local function precipitation(entry, hours)
local next = entry.data["next_" .. hours .. "_hours"]
return next and next.details and next.details.precipitation_amount or 0
end
local function next_symbol(entry)
local d = entry.data
local next = d.next_1_hours or d.next_6_hours or d.next_12_hours
return next and next.summary.symbol_code
end
local function line(cells)
return '<div class="line">' .. table.concat(cells) .. "</div>"
end
local function forecast(place)
local f = get("https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=" ..
string.format("%.4f", place.lat) .. "&lon=" .. string.format("%.4f", place.lon), 10)
local series = f.properties.timeseries
local offset = utc_offset(place.zone)
local now = series[1]
local details = now.data.instant.details
-- The next 24 hours, for the figures' lines and the hourly forecast.
local temps, rain, wind, hours = {}, {}, {}, {}
local total_rain = 0
for i = 1, math.min(24, #series) do
local e = series[i]
local d = e.data.instant.details
local amount = precipitation(e, 1)
table.insert(temps, d.air_temperature)
table.insert(rain, amount)
table.insert(wind, d.wind_speed)
total_rain = total_rain + amount
if i <= 12 then
local none = '<div class="num"><span class="none">—</span></div>'
table.insert(hours, line({
'<div class="name">' .. symbol(next_symbol(e), 24) .. '<span class="text">' .. os.date("%H:%M", local_time(e.time, offset)) .. "</span></div>",
'<div class="num">' .. temperature(d.air_temperature) .. "</div>",
amount > 0 and ('<div class="num">' .. number(amount) .. " mm</div>") or none,
'<div class="num dim">' .. number(d.wind_speed) .. " m/s " .. escape(direction(d.wind_from_direction)) .. "</div>",
}))
end
end
-- The coming days, each from midnight to midnight in the place's time, with the symbol yr.no
-- shows for the day: the six hours from noon.
local days, order = {}, {}
for _, e in ipairs(series) do
local t = local_time(e.time, offset)
local key = os.date("%Y-%m-%d", t)
local day = days[key]
if not day then
day = { time = t, low = math.huge, high = -math.huge, rain = 0 }
days[key] = day
table.insert(order, key)
end
local temp = e.data.instant.details.air_temperature
day.low, day.high = math.min(day.low, temp), math.max(day.high, temp)
if e.data.next_1_hours then
day.rain = day.rain + precipitation(e, 1)
elseif e.data.next_6_hours and tonumber(e.time:sub(12, 13)) % 6 == 0 then
day.rain = day.rain + precipitation(e, 6)
end
local hour = tonumber(os.date("%H", t))
if e.data.next_6_hours and (not day.symbol or (hour >= 12 and not day.noon)) then
day.symbol, day.noon = e.data.next_6_hours.summary.symbol_code, hour >= 12
end
end
local week = {}
for i, key in ipairs(order) do
if i > 8 then break end
local day = days[key]
table.insert(week, line({
'<div class="name">' .. symbol(day.symbol, 24) .. '<span class="text">' ..
escape(i == 1 and toolshed.t("today") or date(day.time)) .. "</span></div>",
'<div class="num">' .. temperature(day.high) .. ' <span class="dim">' .. temperature(day.low) .. "</span></div>",
day.rain > 0 and ('<div class="num">' .. number(day.rain) .. " mm</div>") or '<div class="num"><span class="none">—</span></div>',
'<div class="num dim"></div>',
}))
end
local code = next_symbol(now)
local heading = '<div class="note">' .. symbol(code, 40) .. '<span>' ..
escape(toolshed.t("now", { weather = describe(code), place = place.name })) .. '<span class="dim"> · ' ..
escape(toolshed.t("updated", { time = os.date("%H:%M", local_time(f.properties.meta.updated_at, offset)) })) .. "</span></span></div>"
local top = '<div class="figures">' ..
figure(toolshed.t("temperature"), temperature(details.air_temperature), "thermometer", details.air_temperature < 0 and "blue" or "orange", temps) ..
figure(toolshed.t("rain-24h"), number(total_rain) .. "<small> mm</small>", "umbrella", "blue", rain, true) ..
figure(toolshed.t("wind-from", { direction = direction(details.wind_from_direction) }), number(details.wind_speed) .. "<small> m/s</small>", "wind", "teal", wind, true) ..
"</div>"
local columns = "minmax(0, 1fr) 80px 72px 110px"
local function table_of(title, last, lines)
return '<div style="--columns: ' .. columns .. '"><div class="head"><div>' .. escape(toolshed.t(title)) ..
'</div><div class="num">' .. escape(toolshed.t("temp")) .. '</div><div class="num">' .. escape(toolshed.t("rain")) ..
'</div><div class="num">' .. escape(last) .. "</div></div>" .. table.concat(lines) .. "</div>"
end
return '<div class="page">' .. heading .. top .. table_of("hour", toolshed.t("wind"), hours) .. table_of("day", "", week) .. "</div>"
end
-- yr.no finds the rest of a place's address, in the language of the link, from its ID.
local function yr_address(place)
return toolshed.t("link") .. place.id
end
return toolshed.toolbox {
key = "yr",
title = "Yr",
description = "i18n:toolbox.description",
icon = "cloud-sun",
tint = "blue",
tools = {
{
key = "search",
title = "i18n:tool.search.title",
words = { "yr" },
examples = { "yr oslo", "yr bergen", "yr tromsø" },
keywords = { "weather", "forecast", "vær", "temperature" },
items = true,
-- yr.no is asked once typing pauses, not for every letter on the way.
debounce = true,
search = function(rest, settings)
if rest == "" then return {} end
local ok, found = pcall(get, "https://www.yr.no/api/v0/locations/search?language=" .. language() .. "&q=" .. encode(rest), 1.5)
local jigs = {}
for i, l in ipairs(ok and found._embedded and found._embedded.location or {}) do
if i > 10 then break end
local where = {}
for _, key in ipairs({ "subregion", "region", "country" }) do
local part = l[key]
if part and part.name and part.name ~= l.name and part.name ~= where[#where] then table.insert(where, part.name) end
end
table.insert(jigs, {
title = l.name,
subtitle = table.concat(where, ", ") .. (l.category and (" · " .. l.category.name) or ""),
icon = "map-pin",
data = { id = l.id, name = l.name, lat = l.position.lat, lon = l.position.lon, zone = l.timeZone },
})
end
return jigs
end,
actions = {
{
key = "forecast", title = "i18n:action.search.forecast", icon = "cloud-sun",
run = function(ctx) return { html = forecast(ctx.data), refresh = 600 } end,
},
{
key = "open", title = "i18n:action.search.open", icon = "external-link", shortcut = "cmd+enter",
run = function(ctx) toolshed.open(yr_address(ctx.data)) end,
},
{
key = "copy-link", title = "i18n:action.search.copy-link", icon = "link", shortcut = "cmd+shift+c",
run = function(ctx)
toolshed.clipboard.copy(yr_address(ctx.data))
return toolshed.t("link-copied")
end,
},
},
},
},
}