Proxy weather requests and fix stats headers and offline page fallback
自动部署 / deploy (push) Failing after 2m20s
自动部署 / deploy (push) Failing after 2m20s
This commit is contained in:
1 parent
7809bf12c7
commit
1bd2a73039
5 files changed
+122
-239
No files matched your search
+16
-200
@@ -1,204 +1,20 @@
|
||||
// weather.js
|
||||
(() => {
|
||||
async function initWeather() {
|
||||
const el = document.getElementById('aside-weather');
|
||||
if (!el) return;
|
||||
|
||||
(function () {
|
||||
|
||||
const WEATHER_ID = "aside-weather";
|
||||
const LOCATION_WAIT_MS = 3000;
|
||||
const LOCATION_POLL_INTERVAL_MS = 100;
|
||||
const WEATHER_KEY = "70201debab4245379e376d116b05f8a2";
|
||||
const WEATHER_HOST = "https://ny5vxmbbkd.re.qweatherapi.com";
|
||||
const WEATHER_LANG = "zh";
|
||||
|
||||
function debugLog(label, payload) {
|
||||
console.log(`[weather.js] ${label}`, payload);
|
||||
try {
|
||||
const response = await fetch(el.dataset.endpoint);
|
||||
const now = await response.json();
|
||||
if (!response.ok || typeof now.text !== 'string') {
|
||||
throw new Error(now.error || '天气服务暂时不可用');
|
||||
}
|
||||
el.textContent = `当前天气${now.text},气温${now.temp}℃,体感${now.feelsLike}℃,${now.windDir}${now.windScale}级,湿度${now.humidity}%,能见度${now.vis}km。`;
|
||||
} catch (error) {
|
||||
el.textContent = `🌧️ 天气加载失败:${error.message}`;
|
||||
}
|
||||
}
|
||||
|
||||
function maskSecret(secret) {
|
||||
if (!secret || secret.length < 10) return secret;
|
||||
return `${secret.slice(0, 4)}***${secret.slice(-4)}`;
|
||||
}
|
||||
|
||||
function readExistingLocation() {
|
||||
return window.ipLocation?.result?.location || null;
|
||||
}
|
||||
|
||||
function waitForExistingLocation(timeout = LOCATION_WAIT_MS) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const existingLocation = readExistingLocation();
|
||||
if (existingLocation) {
|
||||
resolve(existingLocation);
|
||||
return;
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
const timer = window.setInterval(() => {
|
||||
const location = readExistingLocation();
|
||||
if (location) {
|
||||
window.clearInterval(timer);
|
||||
resolve(location);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Date.now() - startTime >= timeout) {
|
||||
window.clearInterval(timer);
|
||||
reject(new Error("等待 ipLocation 超时"));
|
||||
}
|
||||
}, LOCATION_POLL_INTERVAL_MS);
|
||||
});
|
||||
}
|
||||
|
||||
function requestLocationFallback() {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!window.$?.ajax) {
|
||||
reject(new Error("jQuery 未加载,无法执行定位兜底请求"));
|
||||
return;
|
||||
}
|
||||
|
||||
$.ajax({
|
||||
type: 'get',
|
||||
url: 'https://apis.map.qq.com/ws/location/v1/ip',
|
||||
data: {
|
||||
key: '你的key',
|
||||
output: 'jsonp',
|
||||
callback: '?',
|
||||
},
|
||||
dataType: 'jsonp',
|
||||
success: function (res) {
|
||||
debugLog("定位兜底返回", res);
|
||||
if (res && res.status === 0 && res.result?.location) {
|
||||
window.ipLocation = res;
|
||||
resolve(res.result.location);
|
||||
} else {
|
||||
reject(new Error("定位失败"));
|
||||
}
|
||||
},
|
||||
error: function () {
|
||||
reject(new Error("定位请求失败"));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function getLocation() {
|
||||
return waitForExistingLocation()
|
||||
.then(location => {
|
||||
debugLog("使用 txmap.js 定位", location);
|
||||
return location;
|
||||
})
|
||||
.catch(error => {
|
||||
debugLog("等待 txmap.js 定位失败,转兜底请求", error);
|
||||
return requestLocationFallback();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function getWeather(lng, lat) {
|
||||
const location = `${lng.toFixed(2)},${lat.toFixed(2)}`;
|
||||
const params = new URLSearchParams({
|
||||
location,
|
||||
lang: WEATHER_LANG,
|
||||
key: WEATHER_KEY
|
||||
});
|
||||
const requestUrl = `${WEATHER_HOST}/v7/weather/now?${params.toString()}`;
|
||||
|
||||
debugLog("天气请求参数", {
|
||||
host: WEATHER_HOST,
|
||||
location,
|
||||
lang: WEATHER_LANG,
|
||||
key: maskSecret(WEATHER_KEY)
|
||||
});
|
||||
|
||||
return fetch(requestUrl, {
|
||||
headers: {
|
||||
Accept: "application/json"
|
||||
}
|
||||
}).then(async res => {
|
||||
const responseText = await res.text();
|
||||
let data;
|
||||
|
||||
try {
|
||||
data = JSON.parse(responseText);
|
||||
} catch (parseError) {
|
||||
debugLog("天气接口返回非 JSON", {
|
||||
status: res.status,
|
||||
statusText: res.statusText,
|
||||
body: responseText
|
||||
});
|
||||
throw new Error(`天气接口返回非 JSON,HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
debugLog("天气接口响应", {
|
||||
status: res.status,
|
||||
statusText: res.statusText,
|
||||
body: data
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const detail = data?.error?.detail || data?.msg || `HTTP ${res.status}`;
|
||||
throw new Error(`天气接口请求失败:${detail}`);
|
||||
}
|
||||
|
||||
return data;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
function renderWeather(data) {
|
||||
const el = document.getElementById(WEATHER_ID);
|
||||
if (!el) return;
|
||||
|
||||
if (data.code !== "200") {
|
||||
debugLog("天气接口业务错误", data);
|
||||
el.innerHTML = `天气获取失败:${data.code || "未知错误"}`;
|
||||
return;
|
||||
}
|
||||
|
||||
const now = data.now;
|
||||
|
||||
const emojiMap = {
|
||||
"晴": "☀️",
|
||||
"多云": "⛅",
|
||||
"阴": "☁️",
|
||||
"雨": "🌧️",
|
||||
"雪": "❄️",
|
||||
"雷": "⛈️"
|
||||
};
|
||||
|
||||
const emoji = emojiMap[now.text] || "🌡️";
|
||||
const weatherSentence = `当前天气${now.text},气温${now.temp}℃,体感${now.feelsLike}℃,${now.windDir}${now.windScale}级,湿度${now.humidity}%,能见度${now.vis}km。`;
|
||||
|
||||
el.innerHTML = `
|
||||
<div class="aside-weather-card">
|
||||
<div class="weather-top">
|
||||
</div>
|
||||
<div class="weather-info">
|
||||
${weatherSentence}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
function initWeather() {
|
||||
const el = document.getElementById(WEATHER_ID);
|
||||
if (!el) return;
|
||||
|
||||
el.innerHTML = "🌥️ 获取天气中...";
|
||||
|
||||
getLocation()
|
||||
.then(loc => getWeather(loc.lng, loc.lat))
|
||||
.then(renderWeather)
|
||||
.catch(err => {
|
||||
console.error("[weather.js] 天气加载失败", err);
|
||||
el.innerHTML = `🌧️ 天气加载失败:${err.message || "未知错误"}`;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// 🚀 初次加载
|
||||
window.addEventListener("load", initWeather);
|
||||
|
||||
// 🔄 pjax
|
||||
document.addEventListener("pjax:complete", initWeather);
|
||||
|
||||
initWeather();
|
||||
document.addEventListener('pjax:complete', initWeather);
|
||||
})();
|
||||
+24
-16
@@ -17,24 +17,27 @@ const CORE_ASSETS = [
|
||||
];
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(
|
||||
caches.open(CORE_CACHE)
|
||||
.then((cache) => cache.addAll(CORE_ASSETS))
|
||||
);
|
||||
event.waitUntil(caches.open(CORE_CACHE).then((cache) => cache.addAll(CORE_ASSETS)));
|
||||
});
|
||||
|
||||
self.addEventListener('activate', (event) => {
|
||||
event.waitUntil((async () => {
|
||||
const cacheNames = await caches.keys();
|
||||
await Promise.all(
|
||||
cacheNames
|
||||
.filter((name) => name.startsWith(CACHE_PREFIX) && ![CORE_CACHE, PAGE_CACHE, ASSET_CACHE, IMAGE_CACHE].includes(name))
|
||||
.map((name) => caches.delete(name))
|
||||
);
|
||||
await self.clients.claim();
|
||||
const clients = await self.clients.matchAll({ type: 'window' });
|
||||
clients.forEach((client) => client.postMessage({ type: 'OFFLINE_READY' }));
|
||||
})());
|
||||
event.waitUntil(
|
||||
(async () => {
|
||||
const cacheNames = await caches.keys();
|
||||
await Promise.all(
|
||||
cacheNames
|
||||
.filter(
|
||||
(name) =>
|
||||
name.startsWith(CACHE_PREFIX) &&
|
||||
![CORE_CACHE, PAGE_CACHE, ASSET_CACHE, IMAGE_CACHE].includes(name),
|
||||
)
|
||||
.map((name) => caches.delete(name)),
|
||||
);
|
||||
await self.clients.claim();
|
||||
const clients = await self.clients.matchAll({ type: 'window' });
|
||||
clients.forEach((client) => client.postMessage({ type: 'OFFLINE_READY' }));
|
||||
})(),
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('message', (event) => {
|
||||
@@ -63,7 +66,12 @@ async function networkFirst(request) {
|
||||
}
|
||||
return response;
|
||||
} catch {
|
||||
return (await caches.match(request)) || (await caches.match('/offline.html'));
|
||||
return (
|
||||
(await caches.match(request, { cacheName: PAGE_CACHE })) ||
|
||||
(await caches.match(request, { cacheName: CORE_CACHE })) ||
|
||||
(await caches.match('/offline.html', { cacheName: CORE_CACHE })) ||
|
||||
Response.error()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -42,7 +42,9 @@ const avatar = siteConfig.author.avatar;
|
||||
<span aria-hidden="true">↗</span>
|
||||
</a>
|
||||
<div class="profile-links" aria-label="联系方式">
|
||||
<a href={siteConfig.author.github} target="_blank" rel="noreferrer" aria-label="GitHub">GitHub</a>
|
||||
<a href={siteConfig.author.github} target="_blank" rel="noreferrer" aria-label="GitHub"
|
||||
>GitHub</a
|
||||
>
|
||||
<a href={`mailto:${siteConfig.author.email}`} aria-label="Email">Email</a>
|
||||
</div>
|
||||
</section>
|
||||
@@ -55,7 +57,12 @@ const avatar = siteConfig.author.avatar;
|
||||
烧烤三件套,灵魂蘸料。<br />
|
||||
当前位置距离博主约 <strong>473</strong> 公里!
|
||||
</div>
|
||||
<p id="aside-weather">当前天气加载中...</p>
|
||||
<p
|
||||
id="aside-weather"
|
||||
data-endpoint={new URL('/weather', siteConfig.analytics.umami.statsEndpoint).href}
|
||||
>
|
||||
当前天气加载中...
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section class="sidebar-card calendar-card">
|
||||
@@ -153,16 +160,21 @@ const avatar = siteConfig.author.avatar;
|
||||
const el = document.getElementById(id);
|
||||
if (el) el.textContent = value;
|
||||
};
|
||||
const toDateKey = (date) => `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
||||
const toDateKey = (date) =>
|
||||
`${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
||||
const toMonthDayKey = (date) => `${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
|
||||
const escapeHtml = (value) =>
|
||||
String(value).replace(/[&<>"']/g, (char) => ({
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
})[char]);
|
||||
String(value).replace(
|
||||
/[&<>"']/g,
|
||||
(char) =>
|
||||
({
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": ''',
|
||||
})[char],
|
||||
);
|
||||
|
||||
function dayOfYear(date) {
|
||||
const start = new Date(date.getFullYear(), 0, 1);
|
||||
@@ -213,12 +225,15 @@ const avatar = siteConfig.author.avatar;
|
||||
const todayFestival = getFestival(now);
|
||||
setText('calendar-week', `第${weekOfYear(now)}周 ${dayNames[now.getDay()]}`);
|
||||
setText('calendar-date', pad(now.getDate()));
|
||||
setText('calendar-solar', `${now.getFullYear()}年${now.getMonth() + 1}月 第${dayOfYear(now)}天`);
|
||||
setText(
|
||||
'calendar-solar',
|
||||
`${now.getFullYear()}年${now.getMonth() + 1}月 第${dayOfYear(now)}天`,
|
||||
);
|
||||
setText(
|
||||
'calendar-lunar',
|
||||
todayFestival
|
||||
? `${todayLunar.yearName}年 ${todayFestival}`
|
||||
: `${todayLunar.yearName}年 农历${todayLunar.month}${todayLunar.day}日`
|
||||
: `${todayLunar.yearName}年 农历${todayLunar.month}${todayLunar.day}日`,
|
||||
);
|
||||
|
||||
const grid = document.getElementById('calendar-grid');
|
||||
@@ -266,10 +281,17 @@ const avatar = siteConfig.author.avatar;
|
||||
const monthStart = new Date(year, now.getMonth(), 1);
|
||||
const monthEnd = new Date(year, now.getMonth() + 1, 1);
|
||||
const weekStart = new Date(year, now.getMonth(), now.getDate() - ((now.getDay() + 6) % 7));
|
||||
const weekEnd = new Date(weekStart.getFullYear(), weekStart.getMonth(), weekStart.getDate() + 7);
|
||||
const weekEnd = new Date(
|
||||
weekStart.getFullYear(),
|
||||
weekStart.getMonth(),
|
||||
weekStart.getDate() + 7,
|
||||
);
|
||||
|
||||
setText('new-year-days', String(daysToEve));
|
||||
setText('new-year-date', `${nextEve.getFullYear()}-${pad(nextEve.getMonth() + 1)}-${pad(nextEve.getDate())}`);
|
||||
setText(
|
||||
'new-year-date',
|
||||
`${nextEve.getFullYear()}-${pad(nextEve.getMonth() + 1)}-${pad(nextEve.getDate())}`,
|
||||
);
|
||||
|
||||
const rows = [
|
||||
['year', yearStart, yearEnd],
|
||||
|
||||
Loaded 3 of 5 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user