1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
| /**
* NCDR 工作學校停課警報 (workschoolclose) 資料擷取與整理
*
* version: 2.4.2
* date: 2026-07-11
*
* ------------------------------------------------------------------------
* 功能說明
* ------------------------------------------------------------------------
* 此 Netlify Function 會:
*
* 1. 抓取 NCDR(國家災害防救科技中心)提供的工作/學校停課 Atom Feed:
* https://alerts.ncdr.nat.gov.tw/RssAtomFeed.ashx?AlertType=33
*
* 2. 解析 Atom XML,保留所有原始欄位,並整理為 JavaScript 物件。
*
* 3. 依設定決定是否只保留最近兩天(今天與昨天)的資料:
* - 預設依 CONFIG.ONLY_TWO_DAYS
* - 可由 URL 參數 onlyTwoDays 覆蓋
*
* 4. 清理 summary:
* - 移除前導 "[停班停課通知]"
* - 移除 "行政院人事行政總處。" 之後所有文字
*
* 例如:
*
* [停班停課通知]花蓮縣:7/10停止上班、停止上課。行政院人事行政總處。如有任何問題...
*
* ↓
*
* 花蓮縣:7/10停止上班、停止上課。
*
* 5. 解析行政區資訊:
* county:縣市名稱
* region:行政區名稱
*
* 範例:
*
* 花蓮縣
* county = 花蓮縣
* region = 花蓮縣
*
* 臺東縣綠島鄉
* county = 臺東縣
* region = 綠島鄉
*
* 嘉義縣竹崎鄉
* county = 嘉義縣
* region = 竹崎鄉
*
* 6. 去除重複公告:
* 使用
*
* ${county}|${cleanedSummary}
*
* 作為唯一鍵,
* 若有多筆相同公告,保留 updated 最新的一筆。
*
* 7. 將資料依縣市整理為 areas,
* 並依 updated 由新到舊排序。
*
* 若某縣市沒有任何公告,
* 自動加入預設公告:
*
* "暫無公告 (No announcements)"
*
* 若 Feed 無法取得,
* 則所有縣市皆回傳:
*
* "無法取得資訊 (Unable to fetch data)"
*
* 8. 快取(Cache)機制:
* - 首次請求時建立 JSON 快取。
* - 後續請求會先比對 feedUpdated。
* - feedUpdated 相同則直接回傳快取。
* - feedUpdated 不同才重新解析 XML 並更新快取。
* - 可利用 forceRefresh=true 強制略過快取重新抓取。
*
* ------------------------------------------------------------------------
* API
* ------------------------------------------------------------------------
*
* 基本:
*
* GET /.netlify/functions/workschoolclose
*
* 回傳:
*
* {
* cache,
* feedUpdated,
* generatedAt,
* count,
* areas
* }
*
* ------------------------------------------------------------------------
* 可用參數
* ------------------------------------------------------------------------
*
* county
* ----------
* 指定縣市。
*
* 範例:
*
* ?county=花蓮縣
* ?county=花蓮縣,臺東縣
*
*
* onlySummary
* ----------
* true
* 只回傳 summary。
*
* false (預設)
* 回傳完整 alerts。
*
* 範例:
*
* ?onlySummary=true
* ?county=花蓮縣&onlySummary=true
*
*
* onlyTwoDays
* ----------
* true
* 僅保留今天與昨天資料。
*
* false
* 不限制日期。
*
* 若未提供,
* 則使用 CONFIG.ONLY_TWO_DAYS。
*
* 範例:
*
* ?onlyTwoDays=true
* ?onlyTwoDays=false
*
*
* forceRefresh
* ----------
* true
* 強制重新抓取 Feed,
* 忽略目前快取。
*
* false (預設)
* 使用快取。
*
* 範例:
*
* ?forceRefresh=true
*
* ------------------------------------------------------------------------
* API 使用範例
* ------------------------------------------------------------------------
*
* 全部縣市
* GET /.netlify/functions/workschoolclose
*
* 花蓮縣
* GET /.netlify/functions/workschoolclose?county=花蓮縣
*
* 只回傳 Summary
* GET /.netlify/functions/workschoolclose?onlySummary=true
*
* 花蓮縣 Summary
* GET /.netlify/functions/workschoolclose?county=花蓮縣&onlySummary=true
*
* 查看全部 Feed(不限最近兩天)
* GET /.netlify/functions/workschoolclose?onlyTwoDays=false
*
* 強制更新快取
* GET /.netlify/functions/workschoolclose?forceRefresh=true
*
* 花蓮縣 + Summary + 強制更新
* GET /.netlify/functions/workschoolclose?county=花蓮縣&summary=true&forceRefresh=true
*
* ------------------------------------------------------------------------
* 相依套件
* ------------------------------------------------------------------------
*
* npm install fast-xml-parser
*
* ------------------------------------------------------------------------
* 注意事項
* ------------------------------------------------------------------------
*
* - 本程式使用 Asia/Taipei 時區進行日期判斷。
* - Feed 更新時間若超過兩天(且 onlyTwoDays=true),
* 將所有縣市視為「暫無公告 (No announcements)」。
* - API 回傳的 cache 欄位表示本次是否直接使用快取資料。
*/
import { XMLParser } from 'fast-xml-parser';
import fs from 'fs';
// --- 設定參數 (可依需求調整) ---
const CONFIG = {
FEED_URL: "https://alerts.ncdr.nat.gov.tw/RssAtomFeed.ashx?AlertType=33", // NCDR Atom Feed
ONLY_TWO_DAYS: true, // 是否只保留今天/昨天的資料 (只篩選最新兩日資料)
COUNTIES: [
"臺北市", "新北市", "桃園市", "臺中市", "臺南市", "高雄市", "基隆市", "新竹市", "嘉義市", "新竹縣", "苗栗縣", "彰化縣", "南投縣", "雲林縣", "嘉義縣", "屏東縣", "宜蘭縣", "花蓮縣", "臺東縣", "澎湖縣", "金門縣", "連江縣"
],
// 快取檔案 (執行時寫入 /tmp 目錄,注意該目錄非永久存儲)
CACHE_FILE: "/tmp/workschoolclose.json"
};
/**
* 下載並解析 Atom Feed,回傳物件 (含 feed 及 entry 陣列)
*/
async function fetchFeed() {
const res = await fetch(CONFIG.FEED_URL);
if (!res.ok) {
throw new Error(`無法下載 RSS 資料 (狀態 ${res.status})`);
}
const xmlText = await res.text();
// 解析 XML
const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: "" });
const feedObj = parser.parse(xmlText);
return feedObj;
}
/**
* 清理 summary 文字:
* - 移除前導的 [停班停課通知]
* - 移除「行政院人事行政總處。」之後的所有內容
*/
function cleanSummary(text) {
let s = text || "";
s = s.replace(/^\[[^\]]+\]/, "");
s = s.replace(/行政院人事行政總處。[\s\S]*$/, "");
return s.trim();
}
/**
* 從清理後 summary 擷取縣市 (county) 與行政區 (region)
* 例如 "臺東縣綠島鄉:xxx" -> county = "臺東縣", region = "綠島鄉"
* 如果沒有子區域,region = county
*/
function parseRegion(cleaned) {
const fullRegion = (cleaned.split(":")[0] || "").trim();
let county = fullRegion;
let region = fullRegion;
for (const c of CONFIG.COUNTIES) {
if (fullRegion.startsWith(c)) {
county = c;
// 如果子區域存在,取 substring;否則仍然是縣市名
region = fullRegion.substring(c.length) || c;
break;
}
}
return { county, region };
}
/**
* 去除重複公告 (相同縣市+清理後 summary),僅保留 updated 最新的那筆
*/
function deduplicateAlerts(alerts) {
const latestMap = new Map();
for (const alert of alerts) {
const key = `${alert.county}|${alert.cleanedSummary}`;
if (!latestMap.has(key) ||
new Date(alert.updated) > new Date(latestMap.get(key).updated)) {
latestMap.set(key, alert);
}
}
return Array.from(latestMap.values());
}
/**
* 依縣市分組,並加上 summary 清單
* 若某縣市無公告,插入預設值 "暫無公告 (No announcements)"
* 同時將每筆 alerts 依 updated 由近到遠排序,再產生對應的 summary list
*/
function groupByCounty(alerts) {
const areas = {};
// 初始化所有縣市
for (const c of CONFIG.COUNTIES) {
areas[c] = { summary: [], alerts: [] };
}
// 分組
for (const alert of alerts) {
if (!areas[alert.county]) {
// 忽略未列入清單的縣市
continue;
}
areas[alert.county].alerts.push({
region: alert.region,
summary: alert.cleanedSummary,
updated: alert.updated,
effective: alert.effective,
expires: alert.expires,
link: alert.link,
raw: alert.raw
});
}
// 處理各縣市的空置與排序
for (const c of CONFIG.COUNTIES) {
if (areas[c].alerts.length === 0) {
// 若無公告,加入一筆預設訊息
areas[c].alerts.push({
region: c,
summary: "暫無公告 (No announcements)",
updated: "",
effective: "",
expires: "",
link: "",
raw: {}
});
}
// 依 updated 時間從近到遠排序
areas[c].alerts.sort((a, b) => new Date(b.updated) - new Date(a.updated));
// 建立 summary 字串列表 (前綴 [月/日])
areas[c].summary = areas[c].alerts.map(a => {
if (!a.updated) {
// 沒有有效時間,直接回傳原始 summary
return a.summary;
}
const date = new Date(a.updated).toLocaleDateString("zh-TW", {
timeZone: "Asia/Taipei", month: "numeric", day: "numeric"
});
return `[${date}] ${a.summary}`;
});
}
return areas;
}
/**
* 根據縣市篩選區域資料
* 適用於 ?county= 花蓮縣,臺東縣 這種情況
*/
function filterAreasByCounty(areas, queryCounty) {
if (!queryCounty) {
return areas;
}
const counties = queryCounty
.split(",")
.map(c => c.trim());
const selectedAreas = {};
counties.forEach(county => {
if (areas[county]) {
selectedAreas[county] = areas[county];
}
});
return selectedAreas;
}
/**
* 根據縣市篩選區域資料,僅保留 summary 清單
*/
function extractSummaryAreas(areas) {
const summaryAreas = {};
Object.entries(areas).forEach(([county, data]) => {
summaryAreas[county] = {
summary: data.summary || []
};
});
return summaryAreas;
}
/**
* 載入快取 (若檔案存在),回傳 JSON 物件或 null
*/
function loadCache() {
try {
const raw = fs.readFileSync(CONFIG.CACHE_FILE, "utf8");
return JSON.parse(raw);
} catch (err) {
return null;
}
}
/**
* 儲存快取至檔案 (JSON),寫入 /tmp 資料夾
*/
function saveCache(data) {
try {
fs.writeFileSync(CONFIG.CACHE_FILE, JSON.stringify(data));
} catch (err) {
console.error("快取保存失敗:", err);
}
}
/**
* Netlify Function 主程式
*/
export default async function handler(request) {
// 嘗試讀取快取
const cacheData = loadCache();
// 解析查詢參數
const url = new URL(request.url);
/* 是否指定縣市 (county) */
const queryCounty = url.searchParams.get('county');
/* 是否只會傳回 summary 清單 (不含 alerts 陣列) */
const summaryOnly = url.searchParams.get('onlySummary') === 'true';
/* 是否只保留最近兩天的資料, url 參數優先於 CONFIG 設定 */
const onlyTwoDays =
url.searchParams.has("onlyTwoDays")
? url.searchParams.get("onlyTwoDays") === "true"
: CONFIG.ONLY_TWO_DAYS;
/* 是否強制重新抓取 Feed ,否則若快取存在且 Feed 未更新,直接回傳快取內容 */
const forceRefresh = url.searchParams.get("forceRefresh") === "true";
try {
// 1. 下載並解析 Atom Feed
const feedObj = await fetchFeed();
const feedUpdated = feedObj.feed?.updated || "";
// 若未要求強制更新,且 Feed 更新時間與快取一致,則直接回傳快取內容。
if (!forceRefresh && cacheData && cacheData.feedUpdated === feedUpdated) {
if (queryCounty || summaryOnly) {
const selectedAreas = queryCounty
? filterAreasByCounty(cacheData.areas, queryCounty) // 有指定縣市
: cacheData.areas; // 所有縣市 (未指定縣市,但可能只要求 summaryOnly)
if (Object.keys(selectedAreas).length === 0) {
return new Response(
JSON.stringify({
error: "Unknown county",
cache: true
}),
{
status:404,
headers:{
"Content-Type":"application/json; charset=utf-8",
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Methods":"GET, OPTIONS",
"Access-Control-Allow-Headers":"Content-Type"
}
}
);
}
const outputAreas = summaryOnly
? extractSummaryAreas(selectedAreas)
: selectedAreas;
const summaries = Object.values(outputAreas)
.flatMap(area => area.summary || []);
return new Response(
JSON.stringify({
feedUpdated: cacheData.feedUpdated,
generatedAt: cacheData.generatedAt,
count: summaryOnly ? summaries.length : undefined,
areas: outputAreas,
cache: true
}),
{
status: 200,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Methods":"GET, OPTIONS",
"Access-Control-Allow-Headers":"Content-Type"
}
}
);
}
// 預設回傳完整快取 (未指定任何參數)
return new Response(
JSON.stringify({
...cacheData,
cache: true
}),
{
status: 200,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Methods":"GET, OPTIONS",
"Access-Control-Allow-Headers":"Content-Type"
}
}
);
}
// 2. 提取所有 entry,轉為警報物件 (含清理後 summary)
const entries = feedObj.feed.entry || [];
const alerts = entries.map(e => {
const rawSummary = (typeof e.summary === "object") ? (e.summary["#text"] || "") : (e.summary || "");
const cleaned = cleanSummary(rawSummary);
const { county, region } = parseRegion(cleaned);
return {
raw: e,
updated: e.updated || "",
summary: rawSummary,
cleanedSummary: cleaned,
county: county,
region: region,
effective: e["cap:effective"] || "",
expires: e["cap:expires"] || "",
link: (e.link && (e.link.href || e.link)) || ""
};
});
// 3. 篩選「今天」與「昨天」的資料 (依照 ?onlyTwoDays 參數決定)
let filtered = alerts;
if (onlyTwoDays) {
const today = new Date().toLocaleDateString("sv-SE", { timeZone: "Asia/Taipei" });
const yesterdayDate = new Date();
yesterdayDate.setDate(yesterdayDate.getDate() - 1);
const yesterday = yesterdayDate.toLocaleDateString("sv-SE", { timeZone: "Asia/Taipei" });
filtered = alerts.filter(a => {
const aDate = new Date(a.updated).toLocaleDateString("sv-SE", { timeZone: "Asia/Taipei" });
return (aDate === today || aDate === yesterday);
});
}
// 4. 去除重複公告
const uniqueAlerts = deduplicateAlerts(filtered);
// 5. 依縣市分組
let areas = groupByCounty(uniqueAlerts);
// 6. 若 Feed 資料超過 2 天未更新,全部視為「暫無公告」
const now = new Date();
const feedTime = new Date(feedUpdated);
if (onlyTwoDays && feedUpdated && (now - feedTime > 2 * 24 * 60 * 60 * 1000)) {
const emptyAreas = {};
for (const c of CONFIG.COUNTIES) {
emptyAreas[c] = {
summary: ["暫無公告 (No announcements)"],
alerts: [{
region: c,
summary: "暫無公告 (No announcements)",
updated: "",
effective: "",
expires: "",
link: "",
raw: {}
}]
};
}
const resultEmpty = {
feedUpdated: feedUpdated,
generatedAt: new Date().toISOString(),
count: 0,
areas: emptyAreas
};
// 不更新快取,直接回傳結果
return new Response(
JSON.stringify({
...resultEmpty,
cache: false
}),
{
status: 200,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Methods":"GET, OPTIONS",
"Access-Control-Allow-Headers":"Content-Type"
}
}
);
}
// 計算總筆數
const totalCount = uniqueAlerts.length;
// 7. 建構回傳 JSON
let resultData = {
feedUpdated: feedUpdated,
generatedAt: new Date().toISOString(),
count: totalCount,
areas: areas
};
// 保存快取
saveCache(resultData);
// 8. 處理 ?county= 和 ?summary=true 參數
if (queryCounty || summaryOnly) {
const selectedAreas = queryCounty
? filterAreasByCounty(areas, queryCounty) // 有指定縣市
: areas; // 所有縣市 (未指定縣市,但可能只要求 summaryOnly)
if (Object.keys(selectedAreas).length === 0) {
return new Response(
JSON.stringify({
error: "Unknown county",
cache: false
}),
{
status: 404,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Methods":"GET, OPTIONS",
"Access-Control-Allow-Headers":"Content-Type"
}
}
);
}
if (summaryOnly) {
const summaryAreas = extractSummaryAreas(
selectedAreas
);
const summaries = Object.values(summaryAreas)
.flatMap(area => area.summary || []);
return new Response(
JSON.stringify({
feedUpdated: resultData.feedUpdated,
generatedAt: resultData.generatedAt,
count: summaries.length,
areas: summaryAreas,
cache: false
}),
{
status: 200,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Methods":"GET, OPTIONS",
"Access-Control-Allow-Headers":"Content-Type"
}
}
);
}
// 非 summary 模式,只保留指定縣市完整資料
resultData.areas = selectedAreas;
}
// 正常回傳
return new Response(
JSON.stringify({
...resultData,
cache: false
}),
{
status: 200,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Methods":"GET, OPTIONS",
"Access-Control-Allow-Headers":"Content-Type"
}
}
);
} catch (err) {
console.error("Error:", err);
// 若抓取失敗但有快取,則回傳快取內容
if (cacheData) {
return new Response(
JSON.stringify({
...cacheData,
cache: true,
error: "Fetch failed, returning cached data"
}),
{
status: 200,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Methods":"GET, OPTIONS",
"Access-Control-Allow-Headers":"Content-Type"
}
}
);
}
// 完全失敗時,回傳「無法取得資訊」預設訊息
const errorAreas = {};
for (const c of CONFIG.COUNTIES) {
errorAreas[c] = {
summary: ["無法取得資訊 (Unable to fetch data)"],
alerts: [{
region: c,
summary: "無法取得資訊 (Unable to fetch data)",
updated: "",
effective: "",
expires: "",
link: "",
raw: {}
}]
};
}
const errorBody = {
feedUpdated: "",
generatedAt: new Date().toISOString(),
count: 0,
areas: errorAreas
};
return new Response(
JSON.stringify({
...errorBody,
cache: false
}),
{
status: 200,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Access-Control-Allow-Origin":"*",
"Access-Control-Allow-Methods":"GET, OPTIONS",
"Access-Control-Allow-Headers":"Content-Type"
}
}
);
}
}
|