Created
September 24, 2026 01:55
-
-
Save qianlifeng/25d66a91de168cb7e210f2cf756960c2 to your computer and use it in GitHub Desktop.
Wox.Plugin.Weather
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // { | |
| // "Id": "7c1a0e4e-6b2d-4f5a-9c31-2a8e5d0b7f14", | |
| // "Name": "i18n:plugin_name", | |
| // "Author": "qianlifeng", | |
| // "Version": "1.0.0", | |
| // "MinWoxVersion": "2.4.2", | |
| // "Runtime": "NODEJS", | |
| // "Description": "i18n:plugin_description", | |
| // "Icon": "svg:<svg xmlns='http://www.w3.org/2000/svg' width='48' height='48' viewBox='0 0 48 48'><rect width='48' height='48' rx='14' fill='#0369a1'/><circle cx='24' cy='24' r='8' fill='#fbbf24'/><g stroke='#fde68a' stroke-width='3' stroke-linecap='round'><path d='M24 8v5M24 35v5M8 24h5M35 24h5M12.5 12.5l3.5 3.5M32 32l3.5 3.5M35.5 12.5L32 16M16 32l-3.5 3.5'/></g></svg>", | |
| // "TriggerKeywords": ["weather", "wt"], | |
| // "SupportedOS": ["Windows", "Linux", "Darwin"], | |
| // "Features": [ | |
| // { "Name": "debounce", "Params": { "IntervalMs": 350 } }, | |
| // { "Name": "mru", "Params": { "HashBy": "scoreKey" } } | |
| // ], | |
| // "SettingDefinitions": [ | |
| // { | |
| // "Type": "select", | |
| // "Value": { | |
| // "Key": "unit", | |
| // "Label": "i18n:setting_unit", | |
| // "Tooltip": "i18n:setting_unit_tip", | |
| // "DefaultValue": "celsius", | |
| // "Options": [ | |
| // { "Label": "i18n:unit_celsius", "Value": "celsius" }, | |
| // { "Label": "i18n:unit_fahrenheit", "Value": "fahrenheit" } | |
| // ] | |
| // }, | |
| // "IsPlatformSpecific": false | |
| // } | |
| // ], | |
| // "I18n": { | |
| // "en_US": { | |
| // "plugin_name": "Weather", | |
| // "plugin_description": "Current weather and the next few days from wttr.in. An empty query uses your network location.", | |
| // "setting_unit": "Temperature unit", | |
| // "setting_unit_tip": "Choose Celsius or Fahrenheit. Wind uses km/h with Celsius and mph with Fahrenheit.\n\n1. Type weather to use your current network location\n2. Type weather Beijing or weather London to choose a place\n3. The first row is the current weather. The following rows are the next few days", | |
| // "unit_celsius": "Celsius (°C)", | |
| // "unit_fahrenheit": "Fahrenheit (°F)", | |
| // "action_copy": "Copy", | |
| // "action_open": "Open wttr.in", | |
| // "group_now": "Now", | |
| // "group_forecast": "Forecast", | |
| // "not_found_title": "Location not found", | |
| // "not_found_subtitle": "Try a city, region, or airport code", | |
| // "error_title": "Weather is unavailable", | |
| // "error_subtitle": "Check the network, or type a city name", | |
| // "notify_copied": "Copied", | |
| // "notify_copy_failed": "Could not copy", | |
| // "notify_open_failed": "Could not open wttr.in", | |
| // "today": "Today", | |
| // "feels": "Feels {temp}", | |
| // "rain": "Rain {n}%", | |
| // "snow": "Snow {n}%", | |
| // "humidity_name": "Humidity", | |
| // "date_locale": "en", | |
| // "weekday_0": "Sun", | |
| // "weekday_1": "Mon", | |
| // "weekday_2": "Tue", | |
| // "weekday_3": "Wed", | |
| // "weekday_4": "Thu", | |
| // "weekday_5": "Fri", | |
| // "weekday_6": "Sat", | |
| // "wind_N": "N", | |
| // "wind_NNE": "NNE", | |
| // "wind_NE": "NE", | |
| // "wind_ENE": "ENE", | |
| // "wind_E": "E", | |
| // "wind_ESE": "ESE", | |
| // "wind_SE": "SE", | |
| // "wind_SSE": "SSE", | |
| // "wind_S": "S", | |
| // "wind_SSW": "SSW", | |
| // "wind_SW": "SW", | |
| // "wind_WSW": "WSW", | |
| // "wind_W": "W", | |
| // "wind_WNW": "WNW", | |
| // "wind_NW": "NW", | |
| // "wind_NNW": "NNW", | |
| // "tool_get_weather": "Get the current weather and the next few days. Omit location to use the network location." | |
| // }, | |
| // "zh_CN": { | |
| // "plugin_name": "天气", | |
| // "plugin_description": "用 wttr.in 查看当前天气和未来几天。不写地点时按网络位置查询。", | |
| // "setting_unit": "温度单位", | |
| // "setting_unit_tip": "选择摄氏度或华氏度。摄氏度搭配 km/h,华氏度搭配 mph。\n\n1. 输入 weather,按当前网络位置查询\n2. 输入 weather 北京 或 weather London 查询指定地点\n3. 第一行是当前天气,后面几行是未来几天", | |
| // "unit_celsius": "摄氏度(°C)", | |
| // "unit_fahrenheit": "华氏度(°F)", | |
| // "action_copy": "复制", | |
| // "action_open": "打开 wttr.in", | |
| // "group_now": "现在", | |
| // "group_forecast": "预报", | |
| // "not_found_title": "没有找到这个地点", | |
| // "not_found_subtitle": "试试城市、地区或机场代码", | |
| // "error_title": "暂时查不到天气", | |
| // "error_subtitle": "检查网络,或直接输入城市名", | |
| // "notify_copied": "已复制", | |
| // "notify_copy_failed": "复制失败", | |
| // "notify_open_failed": "无法打开 wttr.in", | |
| // "today": "今天", | |
| // "feels": "体感 {temp}", | |
| // "rain": "降水 {n}%", | |
| // "snow": "降雪 {n}%", | |
| // "humidity_name": "湿度", | |
| // "date_locale": "zh-CN", | |
| // "weekday_0": "周日", | |
| // "weekday_1": "周一", | |
| // "weekday_2": "周二", | |
| // "weekday_3": "周三", | |
| // "weekday_4": "周四", | |
| // "weekday_5": "周五", | |
| // "weekday_6": "周六", | |
| // "wind_N": "北", | |
| // "wind_NNE": "东北偏北", | |
| // "wind_NE": "东北", | |
| // "wind_ENE": "东北偏东", | |
| // "wind_E": "东", | |
| // "wind_ESE": "东南偏东", | |
| // "wind_SE": "东南", | |
| // "wind_SSE": "东南偏南", | |
| // "wind_S": "南", | |
| // "wind_SSW": "西南偏南", | |
| // "wind_SW": "西南", | |
| // "wind_WSW": "西南偏西", | |
| // "wind_W": "西", | |
| // "wind_WNW": "西北偏西", | |
| // "wind_NW": "西北", | |
| // "wind_NNW": "西北偏北", | |
| // "tool_get_weather": "查询某地的当前天气和未来几天。不填地点时使用网络位置。" | |
| // } | |
| // } | |
| // } | |
| const crypto = require("crypto") | |
| const fs = require("fs") | |
| const https = require("https") | |
| const path = require("path") | |
| const { spawn } = require("child_process") | |
| const CACHE_TTL_MS = 10 * 60 * 1000 | |
| const SETTING_UNIT = "unit" | |
| const MONTHS_EN = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] | |
| const ACTION_COPY = { ImageType: "svg", ImageData: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"var(--wox-theme-icon-color)\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><rect x=\"8\" y=\"8\" width=\"12\" height=\"12\" rx=\"2\"/><path d=\"M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2\"/></svg>" } | |
| const ACTION_OPEN = { ImageType: "svg", ImageData: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"var(--wox-theme-icon-color)\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M14 5h5v5M19 5l-9 9\"/><path d=\"M13 7H6a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h9a2 2 0 0 0 2-2v-7\"/></svg>" } | |
| const ICONS = { | |
| sun: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"8\" fill=\"#f59e0b\"/><g stroke=\"#f59e0b\" stroke-width=\"3\" stroke-linecap=\"round\"><path d=\"M24 6v6M24 36v6M6 24h6M36 24h6M12 12l4 4M32 32l4 4M36 12l-4 4M16 32l-4 4\"/></g></svg>", | |
| partly: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 48 48\"><circle cx=\"18\" cy=\"16\" r=\"6\" fill=\"#f59e0b\"/><g stroke=\"#f59e0b\" stroke-width=\"2.4\" stroke-linecap=\"round\"><path d=\"M18 6v3M8 16h3M12 10l2 2M24 10l-2 2\"/></g><path d=\"M14 36h20a6 6 0 0 0-.8-11.8A8 8 0 0 0 16 28a5 5 0 0 0-2 8z\" fill=\"#e2e8f0\"/></svg>", | |
| cloud: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 48 48\"><path d=\"M14 34h20a7 7 0 0 0-1-13.9A9 9 0 0 0 15 26a6 6 0 0 0-1 8z\" fill=\"#94a3b8\"/></svg>", | |
| fog: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 48 48\"><g stroke=\"#64748b\" stroke-width=\"3\" stroke-linecap=\"round\"><path d=\"M10 18h28M8 24h32M12 30h24\"/></g></svg>", | |
| rain: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 48 48\"><path d=\"M14 26h20a6 6 0 0 0-.8-11.8A8 8 0 0 0 16 18a5 5 0 0 0-2 8z\" fill=\"#94a3b8\"/><g stroke=\"#38bdf8\" stroke-width=\"3\" stroke-linecap=\"round\"><path d=\"M18 32l-2 6M24 32l-2 6M30 32l-2 6\"/></g></svg>", | |
| snow: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 48 48\"><path d=\"M14 24h20a6 6 0 0 0-.8-11.8A8 8 0 0 0 16 16a5 5 0 0 0-2 8z\" fill=\"#94a3b8\"/><g fill=\"#e2e8f0\"><circle cx=\"18\" cy=\"32\" r=\"2\"/><circle cx=\"24\" cy=\"36\" r=\"2\"/><circle cx=\"30\" cy=\"32\" r=\"2\"/></g></svg>", | |
| storm: "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" viewBox=\"0 0 48 48\"><path d=\"M13 24h21a6 6 0 0 0-.9-11.8A8 8 0 0 0 15 16a5 5 0 0 0-2 8z\" fill=\"#475569\"/><path d=\"M22 24l-4 8h6l-3 8 10-12h-6l3-4z\" fill=\"#fbbf24\"/></svg>" | |
| } | |
| const CONDITIONS = { | |
| en: { | |
| 113: "Sunny", 116: "Partly cloudy", 119: "Cloudy", 122: "Overcast", 143: "Mist", 149: "Haze", | |
| 176: "Patchy rain nearby", 179: "Patchy snow nearby", 182: "Patchy sleet nearby", 185: "Patchy freezing drizzle", | |
| 200: "Thundery outbreaks nearby", 227: "Blowing snow", 230: "Blizzard", 248: "Fog", 260: "Freezing fog", | |
| 263: "Patchy light drizzle", 266: "Light drizzle", 281: "Freezing drizzle", 284: "Heavy freezing drizzle", | |
| 293: "Patchy light rain", 296: "Light rain", 299: "Moderate rain at times", 302: "Moderate rain", | |
| 305: "Heavy rain at times", 308: "Heavy rain", 311: "Light freezing rain", 314: "Moderate or heavy freezing rain", | |
| 317: "Light sleet", 320: "Moderate or heavy sleet", 323: "Patchy light snow", 326: "Light snow", | |
| 329: "Patchy moderate snow", 332: "Moderate snow", 335: "Patchy heavy snow", 338: "Heavy snow", | |
| 350: "Ice pellets", 353: "Light rain shower", 356: "Moderate or heavy rain shower", 359: "Torrential rain shower", | |
| 362: "Light sleet showers", 365: "Moderate or heavy sleet showers", 368: "Light snow showers", | |
| 371: "Moderate or heavy snow showers", 374: "Light showers of ice pellets", 377: "Moderate or heavy showers of ice pellets", | |
| 386: "Patchy light rain with thunder", 389: "Moderate or heavy rain with thunder", | |
| 392: "Patchy light snow with thunder", 395: "Moderate or heavy snow with thunder" | |
| }, | |
| zh: { | |
| 113: "晴", 116: "局部多云", 119: "多云", 122: "阴", 143: "薄雾", 149: "霾", | |
| 176: "附近有小雨", 179: "附近有小雪", 182: "附近有雨夹雪", 185: "附近有冻毛毛雨", | |
| 200: "附近有雷暴", 227: "吹雪", 230: "暴风雪", 248: "雾", 260: "冻雾", | |
| 263: "局部小毛毛雨", 266: "小毛毛雨", 281: "冻毛毛雨", 284: "强冻毛毛雨", | |
| 293: "局部小雨", 296: "小雨", 299: "间歇中雨", 302: "中雨", | |
| 305: "间歇大雨", 308: "大雨", 311: "小冻雨", 314: "中到大冻雨", | |
| 317: "小雨夹雪", 320: "中到大雨夹雪", 323: "局部小雪", 326: "小雪", | |
| 329: "局部中雪", 332: "中雪", 335: "局部大雪", 338: "大雪", | |
| 350: "冰丸", 353: "小阵雨", 356: "中到大阵雨", 359: "暴雨", | |
| 362: "小阵性雨夹雪", 365: "中到大阵性雨夹雪", 368: "小阵雪", | |
| 371: "中到大阵雪", 374: "小阵性冰丸", 377: "中到大阵性冰丸", | |
| 386: "局部小雨伴雷", 389: "中到大雨伴雷", 392: "局部小雪伴雷", 395: "中到大雪伴雷" | |
| } | |
| } | |
| const I18N = { | |
| en_US: { | |
| date_locale: "en", today: "Today", feels: "Feels {temp}", rain: "Rain {n}%", snow: "Snow {n}%", | |
| humidity_name: "Humidity", | |
| weekday_0: "Sun", weekday_1: "Mon", weekday_2: "Tue", weekday_3: "Wed", weekday_4: "Thu", weekday_5: "Fri", weekday_6: "Sat", | |
| wind_N: "N", wind_NNE: "NNE", wind_NE: "NE", wind_ENE: "ENE", wind_E: "E", wind_ESE: "ESE", wind_SE: "SE", wind_SSE: "SSE", | |
| wind_S: "S", wind_SSW: "SSW", wind_SW: "SW", wind_WSW: "WSW", wind_W: "W", wind_WNW: "WNW", wind_NW: "NW", wind_NNW: "NNW", | |
| notify_copied: "Copied", notify_copy_failed: "Could not copy", notify_open_failed: "Could not open wttr.in" | |
| }, | |
| zh_CN: { | |
| date_locale: "zh-CN", today: "今天", feels: "体感 {temp}", rain: "降水 {n}%", snow: "降雪 {n}%", | |
| humidity_name: "湿度", | |
| weekday_0: "周日", weekday_1: "周一", weekday_2: "周二", weekday_3: "周三", weekday_4: "周四", weekday_5: "周五", weekday_6: "周六", | |
| wind_N: "北", wind_NNE: "东北偏北", wind_NE: "东北", wind_ENE: "东北偏东", wind_E: "东", wind_ESE: "东南偏东", wind_SE: "东南", wind_SSE: "东南偏南", | |
| wind_S: "南", wind_SSW: "西南偏南", wind_SW: "西南", wind_WSW: "西南偏西", wind_W: "西", wind_WNW: "西北偏西", wind_NW: "西北", wind_NNW: "西北偏北", | |
| notify_copied: "已复制", notify_copy_failed: "复制失败", notify_open_failed: "无法打开 wttr.in" | |
| } | |
| } | |
| const LABEL_KEYS = Object.keys(I18N.en_US) | |
| // buildWttrUrl requests JSON from wttr.in. An empty place uses the caller's network location. | |
| function buildWttrUrl(location, lang) { | |
| const place = String(location || "").trim() | |
| const route = place ? `/${encodeURIComponent(place)}` : "/" | |
| const query = new URLSearchParams({ format: "j1", lang: lang || "en" }) | |
| return `https://wttr.in${route}?${query.toString()}` | |
| } | |
| function wttrLang(locale) { | |
| return String(locale || "").toLowerCase().startsWith("zh") ? "zh-cn" : "en" | |
| } | |
| function normalizeLocale(value) { | |
| const text = String(value || "").trim() | |
| if (!text || text === "date_locale" || text.startsWith("i18n:")) return "en" | |
| return text.replaceAll("_", "-") | |
| } | |
| function normalizeUnit(value) { | |
| const text = String(value || "").trim().replace(/^"|"$/g, "").toLowerCase() | |
| return text === "fahrenheit" || text === "f" ? "fahrenheit" : "celsius" | |
| } | |
| function finiteNumber(value) { | |
| const number = Number(value) | |
| return Number.isFinite(number) ? number : null | |
| } | |
| function textValue(value) { | |
| if (typeof value === "string") return value.trim() | |
| if (Array.isArray(value) && value[0]) { | |
| if (typeof value[0] === "string") return value[0].trim() | |
| if (value[0] && typeof value[0].value === "string") return value[0].value.trim() | |
| } | |
| return "" | |
| } | |
| function langMap(row) { | |
| const langs = {} | |
| if (!row || typeof row !== "object") return langs | |
| for (const key of Object.keys(row)) { | |
| if (key.startsWith("lang_")) langs[key.slice(5).toLowerCase()] = textValue(row[key]) | |
| } | |
| return langs | |
| } | |
| function weatherError(code, message) { | |
| const error = new Error(message || code) | |
| error.code = code | |
| return error | |
| } | |
| function weatherFamily(code) { | |
| const number = Number(code) | |
| if (number === 113) return "sun" | |
| if (number === 116) return "partly" | |
| if (number === 119 || number === 122) return "cloud" | |
| if ([143, 149, 248, 260].includes(number)) return "fog" | |
| if ([179, 227, 230, 323, 326, 329, 332, 335, 338, 350, 368, 371, 374, 377, 392, 395].includes(number)) return "snow" | |
| if ([200, 386, 389].includes(number)) return "storm" | |
| if ([176, 182, 185, 263, 266, 281, 284, 293, 296, 299, 302, 305, 308, 311, 314, 317, 320, 353, 356, 359, 362, 365].includes(number)) return "rain" | |
| return "cloud" | |
| } | |
| function resultIcon(code) { | |
| const family = weatherFamily(code) | |
| return { ImageType: "svg", ImageData: ICONS[family] || ICONS.cloud } | |
| } | |
| function conditionLabel(point, locale) { | |
| const table = String(locale || "").toLowerCase().startsWith("zh") ? CONDITIONS.zh : CONDITIONS.en | |
| if (point && table[point.code]) return table[point.code] | |
| if (point && String(locale || "").toLowerCase().startsWith("zh")) { | |
| const translated = point.langs["zh-cn"] || point.langs.zh | |
| if (translated && translated !== point.english) return translated | |
| } | |
| return (point && point.english) || "" | |
| } | |
| function fill(template, values) { | |
| return String(template || "").replace(/\{(\w+)\}/g, (_, key) => (values[key] == null ? "" : String(values[key]))) | |
| } | |
| function formatTemp(celsius, fahrenheit, unit) { | |
| const value = unit === "fahrenheit" ? fahrenheit : celsius | |
| if (value == null) return "" | |
| return `${Math.round(value)}${unit === "fahrenheit" ? "°F" : "°C"}` | |
| } | |
| function formatRange(day, unit) { | |
| const low = formatTemp(day.minC, day.minF, unit) | |
| const high = formatTemp(day.maxC, day.maxF, unit) | |
| if (!low || !high) return low || high | |
| return `${low.replace("°C", "").replace("°F", "")}–${high}` | |
| } | |
| function formatWind(current, unit, labels) { | |
| const speed = unit === "fahrenheit" ? current.windMiles : current.windKmph | |
| const direction = (labels && labels[`wind_${current.windDir}`]) || current.windDir || "" | |
| if (speed == null) return direction | |
| const unitLabel = unit === "fahrenheit" ? "mph" : "km/h" | |
| return [direction, `${Math.round(speed)} ${unitLabel}`].filter(Boolean).join(" ") | |
| } | |
| function placeKey(report) { | |
| if (report && report.latitude != null && report.longitude != null) { | |
| return `${report.latitude.toFixed(2)},${report.longitude.toFixed(2)}` | |
| } | |
| return String((report && report.name) || "unknown").trim().toLowerCase() || "unknown" | |
| } | |
| function displayTitle(report) { | |
| const requested = String((report && report.requested) || "").trim() | |
| if (requested) return requested | |
| return (report && report.name) || (report && report.country) || "Weather" | |
| } | |
| function placeDetail(report) { | |
| const requested = String((report && report.requested) || "").trim() | |
| const name = String((report && report.name) || "").trim() | |
| const region = String((report && report.region) || "").trim() | |
| const country = String((report && report.country) || "").trim() | |
| const extraRegion = region && region.toLowerCase() !== name.toLowerCase() ? region : "" | |
| if (requested && name && requested.toLowerCase() !== name.toLowerCase()) { | |
| return [name, extraRegion, country].filter(Boolean).join(", ") | |
| } | |
| if (!requested && extraRegion) return [extraRegion, country].filter(Boolean).join(", ") | |
| return "" | |
| } | |
| function dayTitle(date, labels, index) { | |
| const parts = String(date || "").split("-").map((item) => Number(item)) | |
| if (parts.length < 3 || parts.some((item) => !item)) return date || "" | |
| const weekday = new Date(Date.UTC(parts[0], parts[1] - 1, parts[2])).getUTCDay() | |
| const week = (labels && labels[`weekday_${weekday}`]) || "" | |
| const main = labels && labels.date_locale === "zh-CN" | |
| ? `${parts[1]}月${parts[2]}日${week ? ` ${week}` : ""}` | |
| : `${week ? `${week}, ` : ""}${MONTHS_EN[parts[1] - 1]} ${parts[2]}` | |
| if (index === 0 && labels && labels.today) return `${labels.today} · ${main}` | |
| return main | |
| } | |
| function representativeHour(day) { | |
| const hours = Array.isArray(day && day.hourly) ? day.hourly : [] | |
| for (const time of ["1200", "1500", "900", "1800", "600"]) { | |
| const found = hours.find((hour) => String(hour.time) === time) | |
| if (found) return found | |
| } | |
| return hours[0] || null | |
| } | |
| function maxChance(day, key) { | |
| const hours = Array.isArray(day && day.hourly) ? day.hourly : [] | |
| let max = 0 | |
| for (const hour of hours) { | |
| const value = finiteNumber(hour[key]) | |
| if (value != null && value > max) max = value | |
| } | |
| return Math.round(max) | |
| } | |
| function pointFrom(row) { | |
| return { | |
| code: String((row && row.weatherCode) || "").trim(), | |
| english: textValue(row && row.weatherDesc), | |
| langs: langMap(row) | |
| } | |
| } | |
| // parseWttrResponse reads wttr.in format=j1. Unknown places come back as plain text, not JSON. | |
| function parseWttrResponse(status, body) { | |
| const text = String(body || "").trim() | |
| const lower = text.toLowerCase() | |
| if (!text.startsWith("{")) { | |
| if (status === 404 || lower.includes("unknown location") || lower.includes("location not found")) { | |
| return { error: "not_found" } | |
| } | |
| return { error: "unavailable", detail: text.slice(0, 180) || `HTTP ${status || 0}` } | |
| } | |
| let payload | |
| try { | |
| payload = JSON.parse(text) | |
| } catch { | |
| return { error: "unavailable", detail: "invalid JSON" } | |
| } | |
| const currentRow = payload.current_condition && payload.current_condition[0] | |
| if (!currentRow) return { error: "unavailable", detail: "missing current condition" } | |
| const area = (payload.nearest_area && payload.nearest_area[0]) || {} | |
| const currentPoint = pointFrom(currentRow) | |
| const current = { | |
| ...currentPoint, | |
| tempC: finiteNumber(currentRow.temp_C), | |
| tempF: finiteNumber(currentRow.temp_F), | |
| feelsC: finiteNumber(currentRow.FeelsLikeC), | |
| feelsF: finiteNumber(currentRow.FeelsLikeF), | |
| humidity: finiteNumber(currentRow.humidity), | |
| windKmph: finiteNumber(currentRow.windspeedKmph), | |
| windMiles: finiteNumber(currentRow.windspeedMiles), | |
| windDir: textValue(currentRow.winddir16Point) | |
| } | |
| if (current.tempC == null && current.tempF == null) return { error: "unavailable", detail: "missing temperature" } | |
| const days = (Array.isArray(payload.weather) ? payload.weather : []).slice(0, 7).map((day) => { | |
| const hour = representativeHour(day) | |
| return { | |
| ...pointFrom(hour || {}), | |
| date: textValue(day.date), | |
| maxC: finiteNumber(day.maxtempC), | |
| minC: finiteNumber(day.mintempC), | |
| maxF: finiteNumber(day.maxtempF), | |
| minF: finiteNumber(day.mintempF), | |
| rain: maxChance(day, "chanceofrain"), | |
| snow: maxChance(day, "chanceofsnow") | |
| } | |
| }).filter((day) => day.date) | |
| return { | |
| report: { | |
| name: textValue(area.areaName), | |
| region: textValue(area.region), | |
| country: textValue(area.country), | |
| latitude: finiteNumber(area.latitude), | |
| longitude: finiteNumber(area.longitude), | |
| current, | |
| days | |
| } | |
| } | |
| } | |
| function precipTail(day, labels) { | |
| if (day.snow >= 10 && day.snow >= day.rain) { | |
| return { Type: "text", Text: fill(labels.snow, { n: day.snow }), TextCategory: day.snow >= 50 ? "warning" : "default" } | |
| } | |
| if (day.rain >= 10) { | |
| return { Type: "text", Text: fill(labels.rain, { n: day.rain }), TextCategory: day.rain >= 50 ? "warning" : "default" } | |
| } | |
| return null | |
| } | |
| function joinParts(parts) { | |
| return parts.filter(Boolean).join(" · ") | |
| } | |
| function pageUrl(report, lang) { | |
| if (report.latitude != null && report.longitude != null) { | |
| return `https://wttr.in/${report.latitude},${report.longitude}?lang=${encodeURIComponent(lang || "en")}` | |
| } | |
| return `https://wttr.in/${encodeURIComponent(report.name || "")}?lang=${encodeURIComponent(lang || "en")}` | |
| } | |
| // buildWeatherResults keeps the current condition and each day on their own rows. | |
| function buildWeatherResults(report, options) { | |
| const labels = options.labels || I18N.en_US | |
| const unit = normalizeUnit(options.unit) | |
| const locale = labels.date_locale || "en" | |
| const lang = options.lang || wttrLang(locale) | |
| const key = placeKey(report) | |
| const title = displayTitle(report) | |
| const condition = conditionLabel(report.current, locale) | |
| const detail = placeDetail(report) | |
| const temp = formatTemp(report.current.tempC, report.current.tempF, unit) | |
| const feels = formatTemp(report.current.feelsC, report.current.feelsF, unit) | |
| const wind = formatWind(report.current, unit, labels) | |
| const humidity = report.current.humidity == null ? "" : `${Math.round(report.current.humidity)}%` | |
| const currentText = joinParts([title, condition, detail, temp, feels ? fill(labels.feels, { temp: feels }) : "", humidity, wind]) | |
| const open = pageUrl(report, lang) | |
| const context = { placeKey: key, kind: "now", date: "", name: report.name || "" } | |
| // A result row shows at most three tails. Humidity stays in the copied summary. | |
| const tails = [] | |
| if (temp) tails.push({ Type: "text", Text: temp }) | |
| if (feels) tails.push({ Type: "text", Text: fill(labels.feels, { temp: feels }) }) | |
| if (wind) tails.push({ Type: "text", Text: wind }) | |
| if (tails.length < 3 && humidity) tails.push({ Type: "text", Text: humidity, Tooltip: "i18n:humidity_name" }) | |
| const results = [{ | |
| Id: `weather-${key}-now`, | |
| Title: title, | |
| SubTitle: joinParts([condition, detail]), | |
| Icon: resultIcon(report.current.code), | |
| Score: 100, | |
| ScoreKey: `weather:${key}:now`, | |
| Group: "i18n:group_now", | |
| GroupScore: 100, | |
| Tails: tails, | |
| Actions: [ | |
| copyAction("copy-now", currentText, context, options), | |
| openAction("open-now", open, context, options) | |
| ] | |
| }] | |
| report.days.forEach((day, index) => { | |
| const dayCondition = conditionLabel(day, locale) | |
| const title = dayTitle(day.date, labels, index) | |
| const range = formatRange(day, unit) | |
| const precip = precipTail(day, labels) | |
| const dayContext = { placeKey: key, kind: "day", date: day.date, name: report.name || "" } | |
| const dayTails = [] | |
| if (range) dayTails.push({ Type: "text", Text: range }) | |
| if (precip) dayTails.push(precip) | |
| const copyText = joinParts([title, dayCondition, range, precip && precip.Text]) | |
| results.push({ | |
| Id: `weather-${key}-${day.date}`, | |
| Title: title, | |
| SubTitle: dayCondition, | |
| Icon: resultIcon(day.code), | |
| Score: 90 - index, | |
| ScoreKey: `weather:${key}:${day.date}`, | |
| Group: "i18n:group_forecast", | |
| GroupScore: 50, | |
| Tails: dayTails, | |
| Actions: [ | |
| copyAction(`copy-${day.date}`, copyText, dayContext, options), | |
| openAction(`open-${day.date}`, open, dayContext, options) | |
| ] | |
| }) | |
| }) | |
| return results | |
| } | |
| function copyAction(id, text, context, options) { | |
| return { | |
| Id: id, | |
| Name: "i18n:action_copy", | |
| Icon: ACTION_COPY, | |
| IsDefault: true, | |
| ContextData: context, | |
| Action: async (ctx) => { | |
| if (options && typeof options.onCopy === "function") await options.onCopy(ctx, text) | |
| } | |
| } | |
| } | |
| function openAction(id, url, context, options) { | |
| return { | |
| Id: id, | |
| Name: "i18n:action_open", | |
| Icon: ACTION_OPEN, | |
| ContextData: context, | |
| Action: async (ctx) => { | |
| if (options && typeof options.onOpen === "function") await options.onOpen(ctx, url) | |
| } | |
| } | |
| } | |
| function toolOutput(report, locale) { | |
| return { | |
| name: report.name || "", | |
| region: report.region || "", | |
| country: report.country || "", | |
| latitude: report.latitude, | |
| longitude: report.longitude, | |
| current: { | |
| tempC: report.current.tempC, | |
| tempF: report.current.tempF, | |
| feelsC: report.current.feelsC, | |
| feelsF: report.current.feelsF, | |
| humidity: report.current.humidity, | |
| windKmph: report.current.windKmph, | |
| windMiles: report.current.windMiles, | |
| windDir: report.current.windDir || "", | |
| code: report.current.code || "", | |
| description: conditionLabel(report.current, locale) | |
| }, | |
| days: report.days.map((day) => ({ | |
| date: day.date, | |
| maxC: day.maxC, | |
| minC: day.minC, | |
| maxF: day.maxF, | |
| minF: day.minF, | |
| rainChance: day.rain, | |
| snowChance: day.snow, | |
| code: day.code || "", | |
| description: conditionLabel(day, locale) | |
| })) | |
| } | |
| } | |
| function cacheFileName(key) { | |
| return `wttr-${crypto.createHash("sha256").update(key).digest("hex").slice(0, 16)}.json` | |
| } | |
| // httpGet follows a few HTTPS redirects. wttr.in expects a non-browser user agent for JSON. | |
| function httpGet(url, redirects = 0) { | |
| return new Promise((resolve, reject) => { | |
| const request = https.get(url, { | |
| headers: { "User-Agent": "curl/8.7.1", Accept: "application/json" }, | |
| timeout: 10000 | |
| }, (response) => { | |
| const status = response.statusCode || 0 | |
| if (status >= 300 && status < 400 && response.headers.location && redirects < 3) { | |
| response.resume() | |
| const next = new URL(response.headers.location, url).toString() | |
| if (!next.startsWith("https://")) { | |
| reject(new Error("redirect was not https")) | |
| return | |
| } | |
| resolve(httpGet(next, redirects + 1)) | |
| return | |
| } | |
| const chunks = [] | |
| response.on("data", (chunk) => chunks.push(chunk)) | |
| response.on("end", () => resolve({ status, body: Buffer.concat(chunks).toString("utf8") })) | |
| }) | |
| request.on("error", reject) | |
| request.on("timeout", () => request.destroy(new Error("timeout"))) | |
| }) | |
| } | |
| // openExternal opens a wttr.in page in the default browser. | |
| function openExternal(target) { | |
| if (process.platform === "win32") { | |
| spawn("cmd", ["/c", "start", "", target], { detached: true, stdio: "ignore", windowsHide: true }).unref() | |
| return | |
| } | |
| const command = process.platform === "darwin" ? "open" : "xdg-open" | |
| spawn(command, [target], { detached: true, stdio: "ignore" }).unref() | |
| } | |
| class WeatherPlugin { | |
| constructor(options = {}) { | |
| this.api = null | |
| this.unit = "celsius" | |
| this.cacheDir = "" | |
| this.ttlMs = options.ttlMs || CACHE_TTL_MS | |
| this.fetchImpl = options.fetchImpl || httpGet | |
| this.openExternal = options.openExternal || openExternal | |
| this.now = options.now || (() => Date.now()) | |
| this.memory = new Map() | |
| this.reports = new Map() | |
| this.labelsCache = null | |
| this.init = this.init.bind(this) | |
| this.query = this.query.bind(this) | |
| } | |
| async init(ctx, params) { | |
| this.api = params && params.API | |
| if (this.api && typeof this.api.GetCacheFolder === "function") { | |
| try { | |
| const folder = await this.api.GetCacheFolder(ctx) | |
| if (folder) this.cacheDir = String(folder) | |
| } catch (err) { | |
| await this.log(ctx, "Debug", `cache folder unavailable: ${err && err.message ? err.message : err}`) | |
| } | |
| } | |
| await this.loadSettings(ctx) | |
| if (this.api && typeof this.api.OnSettingChanged === "function") { | |
| await this.api.OnSettingChanged(ctx, async (_ctx, key, value) => { | |
| if (key === SETTING_UNIT) this.unit = normalizeUnit(value) | |
| }) | |
| } | |
| if (this.api && typeof this.api.OnMRURestore === "function") { | |
| await this.api.OnMRURestore(ctx, async (_ctx, mruData) => this.restoreResult(mruData)) | |
| } | |
| await this.labels(ctx) | |
| await this.registerTools(ctx) | |
| } | |
| async loadSettings(ctx) { | |
| this.unit = "celsius" | |
| if (!this.api || typeof this.api.GetSetting !== "function") return | |
| try { | |
| this.unit = normalizeUnit(await this.api.GetSetting(ctx, SETTING_UNIT)) | |
| } catch { | |
| this.unit = "celsius" | |
| } | |
| } | |
| async translate(ctx, key) { | |
| if (this.api && typeof this.api.GetTranslation === "function") { | |
| try { | |
| const value = await this.api.GetTranslation(ctx, key) | |
| if (value && value !== key && !String(value).startsWith("i18n:")) return value | |
| } catch { | |
| // Unit tests and older hosts use the bundled dictionary. | |
| } | |
| } | |
| return (I18N.en_US && I18N.en_US[key]) || key | |
| } | |
| async labels(ctx) { | |
| const entries = await Promise.all(LABEL_KEYS.map(async (key) => [key, await this.translate(ctx, key)])) | |
| const labels = Object.fromEntries(entries) | |
| labels.date_locale = normalizeLocale(labels.date_locale) | |
| this.labelsCache = labels | |
| return labels | |
| } | |
| async notify(ctx, key) { | |
| if (!this.api || typeof this.api.Notify !== "function") return | |
| await this.api.Notify(ctx, await this.translate(ctx, key)) | |
| } | |
| async log(ctx, level, message) { | |
| if (this.api && typeof this.api.Log === "function") await this.api.Log(ctx, level, message) | |
| } | |
| resultOptions(labels) { | |
| const active = labels || this.labelsCache || I18N.en_US | |
| return { | |
| labels: active, | |
| unit: this.unit, | |
| lang: wttrLang(active.date_locale), | |
| onCopy: async (ctx, text) => { | |
| try { | |
| if (!this.api || typeof this.api.Copy !== "function") return | |
| await this.api.Copy(ctx, { type: "text", text }) | |
| await this.notify(ctx, "notify_copied") | |
| } catch (err) { | |
| await this.log(ctx, "Error", `copy failed: ${err && err.message ? err.message : err}`) | |
| await this.notify(ctx, "notify_copy_failed") | |
| } | |
| }, | |
| onOpen: async (ctx, url) => { | |
| try { | |
| this.openExternal(url) | |
| } catch (err) { | |
| await this.log(ctx, "Error", `open failed: ${err && err.message ? err.message : err}`) | |
| await this.notify(ctx, "notify_open_failed") | |
| } | |
| } | |
| } | |
| } | |
| rememberReport(report) { | |
| if (report) this.reports.set(placeKey(report), report) | |
| } | |
| async readDisk(key) { | |
| if (!this.cacheDir) return null | |
| try { | |
| const saved = JSON.parse(await fs.promises.readFile(path.join(this.cacheDir, cacheFileName(key)), "utf8")) | |
| if (!saved || !saved.report || this.now() - saved.at > this.ttlMs) return null | |
| return saved.report | |
| } catch { | |
| return null | |
| } | |
| } | |
| async writeDisk(key, report) { | |
| if (!this.cacheDir) return | |
| try { | |
| await fs.promises.mkdir(this.cacheDir, { recursive: true }) | |
| await fs.promises.writeFile(path.join(this.cacheDir, cacheFileName(key)), JSON.stringify({ at: this.now(), report })) | |
| } catch (err) { | |
| await this.log(null, "Debug", `weather cache write failed: ${err && err.message ? err.message : err}`) | |
| } | |
| } | |
| // loadReport serves a recent wttr.in response from memory or the plugin cache folder before fetching. | |
| async loadReport(location, lang) { | |
| const key = `${lang}\n${String(location || "").trim().toLowerCase()}` | |
| const cached = this.memory.get(key) | |
| if (cached && this.now() - cached.at <= this.ttlMs) { | |
| cached.report.requested = String(location || "").trim() | |
| this.rememberReport(cached.report) | |
| return cached.report | |
| } | |
| const stored = await this.readDisk(key) | |
| if (stored) { | |
| stored.requested = String(location || "").trim() | |
| this.memory.set(key, { at: this.now(), report: stored }) | |
| this.rememberReport(stored) | |
| return stored | |
| } | |
| const url = buildWttrUrl(location, lang) | |
| let response | |
| try { | |
| response = await this.fetchImpl(url) | |
| } catch (err) { | |
| throw weatherError("unavailable", err && err.message ? err.message : "network") | |
| } | |
| const parsed = parseWttrResponse(response && response.status, response && response.body) | |
| if (parsed.error) throw weatherError(parsed.error, parsed.detail || parsed.error) | |
| const report = parsed.report | |
| report.requested = String(location || "").trim() | |
| this.memory.set(key, { at: this.now(), report }) | |
| this.rememberReport(report) | |
| await this.writeDisk(key, report) | |
| return report | |
| } | |
| // restoreResult rebuilds one row from the in-memory report. It must not fetch or call host APIs. | |
| restoreResult(mruData) { | |
| const data = (mruData && mruData.ContextData) || {} | |
| const report = this.reports.get(data.placeKey) | |
| if (!report) return null | |
| const identity = data.kind === "day" ? data.date : "now" | |
| const results = buildWeatherResults(report, this.resultOptions()) | |
| return results.find((result) => result.ScoreKey === `weather:${data.placeKey}:${identity}`) || null | |
| } | |
| async query(ctx, query) { | |
| const search = String((query && (query.Search || query.search)) || "").trim() | |
| const labels = await this.labels(ctx) | |
| try { | |
| const report = await this.loadReport(search, wttrLang(labels.date_locale)) | |
| await this.log(ctx, "Info", `weather ${search || "@ip"} -> ${report.name} ${report.current.tempC}C`) | |
| return { Results: buildWeatherResults(report, this.resultOptions(labels)) } | |
| } catch (err) { | |
| const code = err && err.code | |
| await this.log(ctx, "Error", `weather ${search || "@ip"} failed: ${err && err.message ? err.message : err}`) | |
| if (code === "not_found") { | |
| return { Results: [this.messageResult("i18n:not_found_title", "i18n:not_found_subtitle")] } | |
| } | |
| return { Results: [this.messageResult("i18n:error_title", "i18n:error_subtitle")] } | |
| } | |
| } | |
| messageResult(title, subtitle) { | |
| return { | |
| Title: title, | |
| SubTitle: subtitle, | |
| Icon: resultIcon(""), | |
| Score: 1, | |
| Actions: [] | |
| } | |
| } | |
| async registerTools(ctx) { | |
| if (!this.api || typeof this.api.RegisterPluginTool !== "function") return | |
| try { | |
| const registered = await this.api.RegisterPluginTool(ctx, { | |
| Tool: { | |
| Name: "get_weather", | |
| Description: "i18n:tool_get_weather", | |
| InputSchema: { | |
| type: "object", | |
| properties: { | |
| location: { type: "string", description: "City, region, or airport code. Omit to use the network location." } | |
| }, | |
| additionalProperties: false | |
| }, | |
| OutputSchema: { | |
| type: "object", | |
| properties: { | |
| name: { type: "string" }, | |
| region: { type: "string" }, | |
| country: { type: "string" }, | |
| latitude: { type: "number" }, | |
| longitude: { type: "number" }, | |
| current: { type: "object" }, | |
| days: { type: "array" } | |
| }, | |
| required: ["name", "current", "days"] | |
| }, | |
| Annotations: { ReadOnly: true, Destructive: false, Idempotent: true, RequiresUI: false } | |
| }, | |
| Handler: async (toolCtx, option) => this.handleGetWeather(toolCtx, option && option.Arguments) | |
| }) | |
| if (registered && registered.Error) { | |
| await this.log(ctx, "Warning", `get_weather was not registered: ${registered.Error.Message || registered.Error.Code}`) | |
| } | |
| } catch (err) { | |
| await this.log(ctx, "Warning", `get_weather unavailable: ${err && err.message ? err.message : err}`) | |
| } | |
| } | |
| async handleGetWeather(ctx, args) { | |
| const location = String((args && args.location) || "").trim() | |
| const labels = await this.labels(ctx) | |
| try { | |
| const report = await this.loadReport(location, wttrLang(labels.date_locale)) | |
| return { Output: toolOutput(report, labels.date_locale) } | |
| } catch (err) { | |
| const code = err && err.code === "not_found" ? "LOCATION_NOT_FOUND" : "WEATHER_UNAVAILABLE" | |
| return { Error: { Code: code, Message: (err && err.message) || code } } | |
| } | |
| } | |
| } | |
| const plugin = new WeatherPlugin() | |
| module.exports = { | |
| plugin, | |
| WeatherPlugin, | |
| buildWttrUrl, | |
| parseWttrResponse, | |
| buildWeatherResults, | |
| placeKey, | |
| I18N, | |
| ICONS | |
| } | |
| module.exports.plugin = plugin |
qianlifeng
commented
Sep 24, 2026
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment