-
Notifications
You must be signed in to change notification settings - Fork 9.9k
feat(route): add Shanghai weather alert #22087
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
TinkoLiu
wants to merge
4
commits into
DIYgod:master
Choose a base branch
from
TinkoLiu:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+143
−0
Open
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| import type { Namespace } from '@/types'; | ||
|
|
||
| export const namespace: Namespace = { | ||
| name: 'SoWeather', | ||
| url: 'wx.soweather.com', | ||
| categories: ['forecast'], | ||
| lang: 'zh-CN', | ||
| zh: { | ||
| name: '上海天气预警', | ||
| }, | ||
| }; |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| import sanitizeHtml from 'sanitize-html'; | ||
|
|
||
| import type { DataItem, Route } from '@/types'; | ||
| import cache from '@/utils/cache'; | ||
| import ofetch from '@/utils/ofetch'; | ||
| import { parseDate } from '@/utils/parse-date'; | ||
| import timezone from '@/utils/timezone'; | ||
|
|
||
| import type { Data } from '../../types'; | ||
|
|
||
| const rootUrl = 'https://wx.soweather.com'; | ||
| const pageUrl = `${rootUrl}/wxapp/warn.jsp`; | ||
| const dataUrl = `${rootUrl}/wxapp/jsondata/warn.js`; | ||
| const cacheMaxAge = 5 * 60; | ||
| const specialIssuers = new Set(['上海市民防办', '中国铁路上海局集团有限公司上海站', '上海申通地铁集团有限公司', '市交通委指挥中心']); | ||
| const warningGroups = [ | ||
| ['市级预警', 'warns'], | ||
| ['市级历史预警', 'historywarns'], | ||
| ['分区预警', 'fqwarns'], | ||
| ['分区历史预警', 'fqhistorywarns'], | ||
| ] as const; | ||
|
|
||
| interface RawWarning { | ||
| isActive: boolean; | ||
| yjid: string; | ||
| htmlword: string; | ||
| yjfbdw: string; | ||
| yjfbtype: string; | ||
| name: string; | ||
| id: number; | ||
| district: string; | ||
| fbsj: string; | ||
| jcsj?: string | null; | ||
| lqImage1?: string | null; | ||
| icon?: string | null; | ||
| gtyjstatus?: string | null; | ||
| } | ||
|
|
||
| async function handler(): Promise<Data | null> { | ||
| const response = await cache.tryGet(`soweather:warn:${dataUrl}`, () => ofetch<string>(dataUrl, { parseResponse: (txt) => txt }), cacheMaxAge); | ||
| const warnings = warningGroups.flatMap(([groupName, variableName]) => | ||
| parseWarnings(response, variableName) | ||
| .filter((warning) => isRealWarning(warning)) | ||
| .map((warning) => buildItem(warning, groupName)) | ||
| ); | ||
|
|
||
| return { | ||
| title: '上海天气预警', | ||
| description: '上海天气预警', | ||
| link: pageUrl, | ||
| item: warnings, | ||
| language: 'zh-CN', | ||
| }; | ||
| } | ||
|
|
||
| export const route: Route = { | ||
| path: '/warn', | ||
| name: 'Shanghai Weather Alert', | ||
| url: 'wx.soweather.com/wxapp/warn.jsp', | ||
| maintainers: ['TinkoLiu'], | ||
| example: '/soweather/warn', | ||
| categories: ['forecast'], | ||
| handler, | ||
| zh: { | ||
| name: '上海天气预警', | ||
| example: '/soweather/warn', | ||
| path: '/warn', | ||
| maintainers: ['TinkoLiu'], | ||
| handler, | ||
| }, | ||
| }; | ||
|
|
||
| function parseWarnings(script: string, variableName: string): RawWarning[] { | ||
| const pattern = new RegExp(`var\\s+${variableName}\\s*=\\s*(\\[[\\s\\S]*?\\])\\s*(?=var\\s+\\w+\\s*=|$)`); | ||
| const json = pattern.exec(script)?.[1]; | ||
|
|
||
| return json ? (JSON.parse(json) as RawWarning[]) : []; | ||
| } | ||
|
|
||
| function isRealWarning(warning: RawWarning): boolean { | ||
| return !['Exercise', 'Test'].includes(warning.gtyjstatus ?? ''); | ||
| } | ||
|
|
||
| function buildItem(warning: RawWarning, groupName: string): DataItem { | ||
| const title = buildTitle(warning); | ||
| const content = buildContent(warning); | ||
| const guid = `${warning.district}-${warning.id}-${warning.yjid}`; | ||
| const image = warning.icon ? `${rootUrl}/wxapp/images/icon/${warning.icon.replaceAll('-', '_')}` : undefined; | ||
| const updated = !warning.isActive && warning.jcsj ? timezone(parseDate(warning.jcsj, 'YYYY-MM-DD HH:mm'), 8) : undefined; | ||
|
|
||
| return { | ||
| title, | ||
| link: `${pageUrl}#${encodeURIComponent(guid)}`, | ||
| guid, | ||
| description: content, | ||
| content: { | ||
| html: content, | ||
| text: content | ||
| .replaceAll(/<br\s*\/?>/gi, '\n') | ||
| .replaceAll(/<[^>]+>/g, '') | ||
Check failureCode scanning / CodeQL Incomplete multi-character sanitization High
This string may still contain
<script Error loading related location Loading |
||
|
Comment on lines
+95
to
+97
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| .trim(), | ||
| }, | ||
| pubDate: timezone(parseDate(warning.fbsj, 'YYYY-MM-DD HH:mm'), 8), | ||
| updated, | ||
| author: warning.yjfbdw, | ||
| category: [groupName, warning.district, warning.name, warning.isActive ? '生效中' : '已解除'], | ||
| image, | ||
| }; | ||
| } | ||
|
|
||
| function buildTitle(warning: RawWarning): string { | ||
| const suffix = specialIssuers.has(warning.yjfbdw) ? '' : '预警'; | ||
|
|
||
| return `${warning.isActive ? '' : '【已解除】'}${warning.yjfbdw}${warning.yjfbtype}${warning.name}${suffix}`; | ||
| } | ||
|
|
||
| function buildContent(warning: RawWarning): string { | ||
| const sections = [ | ||
| !warning.isActive && warning.jcsj ? `解除时间:${warning.jcsj}<br>` : '', | ||
| sanitizeHtml(getWarningInfo(warning.htmlword), { | ||
| allowedTags: [...sanitizeHtml.defaults.allowedTags, 'br'], | ||
| allowedAttributes: {}, | ||
| }), | ||
| warning.lqImage1 ? `<p><img src="${new URL(warning.lqImage1.replaceAll('\\', '/'), `${rootUrl}/wxapp/`).href}"></p>` : '', | ||
| ]; | ||
|
|
||
| return sections.join(''); | ||
| } | ||
|
|
||
| function getWarningInfo(htmlword: string): string { | ||
| return htmlword | ||
| .split('防御指引')[0] | ||
| .replaceAll(/(?:(?:\s| )*<br\s*\/?>)+\s*$/gi, '') | ||
| .trim(); | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do not hardcode the cache duration. Users are expected to adjust it to their liking thru envs.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
cuz the Shanghai Weather Station does not publish the alerts in fixed intervals, and the global duration setting might be too long for a weather alert, but should be fine for other feeds like news or daily weather forecast ( and also the env since you can't configure it for each route ) , so I hardcoded this as I tested it to be a sweet point for cache duration.
Or if it's should be left to the users to consider about this, I would remove the param later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's up to the users to decide where the sweet spot is for them. I know some have set the cache duration to 0 so they get fresh content every time their RSS reader updates.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ACK and done