feat: 首页每日资讯5列
- 首页「📰 每日资讯」5列并排, 每列5条(标题+时间), 点击标题新标签打开
- 五列: GITHUB(一周热门新仓库)/国际新闻(BBC)/AI资讯(TechCrunch)/IT技术(HN)/最热股票(东方财富涨幅榜)
- relay后台线程每天北京时间08:00自动抓取缓存data/news.json, 首访即抓, 单源失败降级
- 响应式5/3/2/1列
CHANGELOG记录
This commit is contained in:
1 parent
dd06abe59d
commit
24fd48ec53
3 files changed
+342
No files matched your search
@@ -1504,6 +1504,18 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
if parsed.path == "/news":
|
||||
data = _load_news_file()
|
||||
if not data.get("columns"):
|
||||
# 缓存为空(首次):同步抓一次
|
||||
try:
|
||||
_maybe_refresh_news()
|
||||
data = _load_news_file()
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[news] on-demand failed: {e}", flush=True)
|
||||
body = {"code": 200, "message": "ok", "data": data}
|
||||
self._reply(200, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if parsed.path == "/sites":
|
||||
status, body = sites_api("GET", "", {})
|
||||
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
@@ -2385,6 +2397,185 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self._reply(404, b"not found")
|
||||
|
||||
|
||||
|
||||
# ---- 首页 5 列资讯:每天北京时间 08:00 抓取,缓存到 data/news.json ----
|
||||
import xml.etree.ElementTree as _ET
|
||||
from datetime import datetime as _dt, timedelta as _td, timezone as _tz
|
||||
from email.utils import parsedate_to_datetime as _pdt
|
||||
|
||||
NEWS_FILE = os.environ.get("NEWS_FILE", "/app/data/news.json")
|
||||
_CST = _tz(_td(hours=8))
|
||||
_BBC_RSS = "https://feeds.bbci.co.uk/news/world/rss.xml"
|
||||
_TC_AI_RSS = "https://techcrunch.com/category/artificial-intelligence/feed/"
|
||||
_HN_RSS = "https://hnrss.org/frontpage"
|
||||
_STOCK_URL = ("https://push2.eastmoney.com/api/qt/clist/get?pn=1&pz=5&po=1&np=1"
|
||||
"&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23&fields=f12,f14,f3")
|
||||
|
||||
|
||||
def _cst_now():
|
||||
return _dt.now(_CST)
|
||||
|
||||
|
||||
def _norm_time(s):
|
||||
"""任意时间字符串 -> 北京时间 MM-DD HH:MM"""
|
||||
if not s:
|
||||
return ""
|
||||
s = str(s).strip()
|
||||
dt = None
|
||||
try:
|
||||
dt = _pdt(s)
|
||||
except Exception:
|
||||
try:
|
||||
dt = _dt.fromisoformat(s.replace("Z", "+00:00"))
|
||||
except Exception:
|
||||
return ""
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=_tz.utc)
|
||||
return dt.astimezone(_CST).strftime("%m-%d %H:%M")
|
||||
|
||||
|
||||
def _http_get(opener, url, timeout=20):
|
||||
req = request.Request(url, headers={"User-Agent": "Mozilla/5.0 (IT-Tools-News)", "Accept": "*/*"})
|
||||
with opener.open(req, timeout=timeout) as resp:
|
||||
return resp.read()
|
||||
|
||||
|
||||
def _parse_rss(data, limit=5):
|
||||
"""RSS 2.0 / Atom -> [{title,url,time}]"""
|
||||
items = []
|
||||
try:
|
||||
root = _ET.fromstring(data)
|
||||
except Exception:
|
||||
return items
|
||||
for it in root.iter("item"):
|
||||
t = (it.findtext("title") or "").strip()
|
||||
link = (it.findtext("link") or "").strip()
|
||||
pub = (it.findtext("pubDate") or "").strip()
|
||||
if t:
|
||||
items.append({"title": t, "url": link, "time": _norm_time(pub)})
|
||||
if len(items) >= limit:
|
||||
break
|
||||
if items:
|
||||
return items
|
||||
ns = "{http://www.w3.org/2005/Atom}"
|
||||
for it in root.iter(f"{ns}entry"):
|
||||
t = (it.findtext(f"{ns}title") or "").strip()
|
||||
link = ""
|
||||
l = it.find(f"{ns}link")
|
||||
if l is not None:
|
||||
link = l.get("href", "")
|
||||
pub = (it.findtext(f"{ns}published") or it.findtext(f"{ns}updated") or "").strip()
|
||||
if t:
|
||||
items.append({"title": t, "url": link, "time": _norm_time(pub)})
|
||||
if len(items) >= limit:
|
||||
break
|
||||
return items
|
||||
|
||||
|
||||
def _fetch_github():
|
||||
q = (_cst_now() - _td(days=7)).strftime("%Y-%m-%d")
|
||||
url = f"https://api.github.com/search/repositories?q=created:%3E{q}&sort=stars&order=desc&per_page=5"
|
||||
j = json.loads(_http_get(OPENER_PROXY, url))
|
||||
out = []
|
||||
for r in j.get("items", [])[:5]:
|
||||
out.append({
|
||||
"title": f"{r.get('full_name','')} \u2b50{r.get('stargazers_count',0)}",
|
||||
"url": r.get("html_url", ""),
|
||||
"time": _norm_time(r.get("created_at") or r.get("pushed_at")),
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _fetch_stock():
|
||||
j = json.loads(_http_get(OPENER_DIRECT, _STOCK_URL))
|
||||
diff = ((j.get("data") or {}).get("diff")) or []
|
||||
if isinstance(diff, dict):
|
||||
diff = list(diff.values())
|
||||
today = _cst_now().strftime("%m-%d")
|
||||
out = []
|
||||
for r in diff[:5]:
|
||||
name, code, pct = r.get("f14", ""), r.get("f12", ""), r.get("f3", 0)
|
||||
if not name:
|
||||
continue
|
||||
out.append({
|
||||
"title": f"{name} {code} {pct:+.2f}%",
|
||||
"url": f"https://quote.eastmoney.com/{code}.html",
|
||||
"time": today,
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _fetch_news():
|
||||
cols = []
|
||||
|
||||
def _col(key, title, icon, fn):
|
||||
try:
|
||||
items = (fn() or [])[:5]
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[news] {key} failed: {e}", flush=True)
|
||||
items = []
|
||||
cols.append({"key": key, "title": title, "icon": icon, "items": items})
|
||||
|
||||
_col("github", "GITHUB", "\U0001f419", _fetch_github)
|
||||
_col("world", "\u56fd\u9645\u65b0\u95fb", "\U0001f30d",
|
||||
lambda: _parse_rss(_http_get(OPENER_PROXY, _BBC_RSS)))
|
||||
_col("ai", "AI\u8d44\u8baf", "\U0001f916",
|
||||
lambda: _parse_rss(_http_get(OPENER_PROXY, _TC_AI_RSS)))
|
||||
_col("it", "IT\u6700\u65b0\u6280\u672f", "\U0001f4bb",
|
||||
lambda: _parse_rss(_http_get(OPENER_PROXY, _HN_RSS)))
|
||||
_col("stock", "\u5f53\u5929\u6700\u70ed\u80a1\u7968", "\U0001f4c8", _fetch_stock)
|
||||
return cols
|
||||
|
||||
|
||||
def _load_news_file():
|
||||
try:
|
||||
with open(NEWS_FILE, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _save_news_file(data):
|
||||
try:
|
||||
os.makedirs(os.path.dirname(NEWS_FILE), exist_ok=True)
|
||||
tmp = NEWS_FILE + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False)
|
||||
os.replace(tmp, NEWS_FILE)
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[news] save failed: {e}", flush=True)
|
||||
|
||||
|
||||
def _maybe_refresh_news():
|
||||
data = _load_news_file() or {}
|
||||
now = _cst_now()
|
||||
today, hour = now.strftime("%Y-%m-%d"), now.hour
|
||||
last = data.get("date", "")
|
||||
after8 = bool(data.get("after8"))
|
||||
need = False
|
||||
if not data.get("columns"):
|
||||
need = True # first boot / empty
|
||||
elif last != today and hour >= 8:
|
||||
need = True # new day, past 08:00 CST
|
||||
elif last == today and not after8 and hour >= 8:
|
||||
need = True # booted before 08:00, now past it
|
||||
if not need:
|
||||
return
|
||||
cols = _fetch_news()
|
||||
_save_news_file({"date": today, "after8": hour >= 8, "updated": int(time.time()), "columns": cols})
|
||||
print(f"[news] refreshed {today} {hour}h counts={[len(c['items']) for c in cols]}", flush=True)
|
||||
|
||||
|
||||
def _news_loop():
|
||||
while True:
|
||||
try:
|
||||
_maybe_refresh_news()
|
||||
except Exception as e: # noqa: BLE001
|
||||
print(f"[news] loop error: {e}", flush=True)
|
||||
time.sleep(600)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
_ensure_admin()
|
||||
threading.Thread(target=_news_loop, daemon=True).start()
|
||||
ThreadingHTTPServer(("0.0.0.0", 8091), Handler).serve_forever()
|
||||
Reference in new issue
Block a user