Skip to content

Instantly share code, notes, and snippets.

@qianlifeng
Created September 1, 2026 15:34
Show Gist options
  • Select an option

  • Save qianlifeng/5505503cf2ab741e2073e8bc120fba77 to your computer and use it in GitHub Desktop.

Select an option

Save qianlifeng/5505503cf2ab741e2073e8bc120fba77 to your computer and use it in GitHub Desktop.
Wox.Plugin.Script.HackerNews
#!/usr/bin/env python3
# {
# "Id": "a7c3e9f2-4b81-4d6e-9f1a-2c8d5e0b7a13",
# "Name": "i18n:plugin_name",
# "Author": "qianlifeng",
# "Version": "1.0.0",
# "MinWoxVersion": "2.0.0",
# "Description": "i18n:plugin_description",
# "Website": "https://news.ycombinator.com",
# "Icon": "svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"18\" height=\"18\" viewBox=\"4 4 188 188\"><path d=\"m4 4h188v188h-188z\" fill=\"#f60\"/><path d=\"m73.2521756 45.01 22.7478244 47.39130083 22.7478244-47.39130083h19.56569631l-34.32352071 64.48661468v41.49338532h-15.98v-41.49338532l-34.32352071-64.48661468z\" fill=\"#fff\"/></svg>",
# "TriggerKeywords": ["hn"],
# "SupportedOS": ["windows", "linux", "darwin"],
# "Commands": [
# { "Command": "frontpage", "Description": "i18n:topic.frontpage" },
# { "Command": "newest", "Description": "i18n:topic.newest" },
# { "Command": "ask", "Description": "i18n:topic.ask" },
# { "Command": "show", "Description": "i18n:topic.show" },
# { "Command": "best", "Description": "i18n:topic.best" },
# { "Command": "active", "Description": "i18n:topic.active" },
# { "Command": "jobs", "Description": "i18n:topic.jobs" },
# { "Command": "launches", "Description": "i18n:topic.launches" },
# { "Command": "polls", "Description": "i18n:topic.polls" },
# { "Command": "classic", "Description": "i18n:topic.classic" },
# { "Command": "bestcomments", "Description": "i18n:topic.bestcomments" },
# { "Command": "newcomments", "Description": "i18n:topic.newcomments" },
# { "Command": "whoishiring", "Description": "i18n:topic.whoishiring" },
# { "Command": "topics", "Description": "i18n:cmd.topics" }
# ],
# "Features": [
# { "Name": "debounce", "Params": { "IntervalMs": 300 } },
# { "Name": "ignoreAutoScore" }
# ],
# "SettingDefinitions": [
# {
# "Type": "select",
# "Value": {
# "Key": "default_topic",
# "Label": "i18n:setting.default_topic",
# "DefaultValue": "frontpage",
# "Options": [
# { "Label": "i18n:topic.frontpage", "Value": "frontpage" },
# { "Label": "i18n:topic.newest", "Value": "newest" },
# { "Label": "i18n:topic.ask", "Value": "ask" },
# { "Label": "i18n:topic.show", "Value": "show" },
# { "Label": "i18n:topic.best", "Value": "best" },
# { "Label": "i18n:topic.active", "Value": "active" }
# ]
# }
# },
# {
# "Type": "textbox",
# "Value": {
# "Key": "story_count",
# "Label": "i18n:setting.story_count",
# "Tooltip": "i18n:setting.story_count_tip",
# "DefaultValue": "30",
# "Style": { "Width": 120 }
# }
# }
# ],
# "I18n": {
# "en_US": {
# "plugin_name": "Hacker News",
# "plugin_description": "Browse Hacker News stories and discussions",
# "cmd.topics": "Browse HN topics",
# "setting.default_topic": "Default topic",
# "setting.story_count": "Story count",
# "setting.story_count_tip": "How many stories to fetch (1-60)",
# "topic.frontpage": "Front page",
# "topic.newest": "Newest stories",
# "topic.ask": "Ask HN",
# "topic.show": "Show HN",
# "topic.best": "Best stories",
# "topic.active": "Active discussions",
# "topic.jobs": "Jobs",
# "topic.launches": "Launches",
# "topic.polls": "Polls",
# "topic.pool": "Pool",
# "topic.classic": "Classic",
# "topic.invited": "Invited",
# "topic.bestcomments": "Best comments",
# "topic.newcomments": "New comments",
# "topic.whoishiring": "Who is hiring",
# "action.open": "Open article",
# "action.comments": "Open comments",
# "action.copy_title": "Copy title",
# "action.copy_url": "Copy URL",
# "action.copy_comments": "Copy comments URL",
# "action.open_hn": "Open Hacker News",
# "action.switch": "Switch topic",
# "hint.switch": "Switch to another HN topic",
# "error.fetch": "Failed to load Hacker News",
# "error.empty": "No stories in this topic",
# "error.none": "No matching stories",
# "label.by": "by",
# "label.comments": "comments",
# "rel.just_now": "just now",
# "rel.minutes_ago": "m ago",
# "rel.hours_ago": "h ago",
# "rel.days_ago": "d ago",
# "rel.minutes_later": "m later",
# "rel.hours_later": "h later",
# "rel.days_later": "d later"
# },
# "zh_CN": {
# "plugin_name": "Hacker News",
# "plugin_description": "浏览 Hacker News 首页、话题和讨论",
# "cmd.topics": "浏览 HN 话题",
# "setting.default_topic": "默认话题",
# "setting.story_count": "条目数量",
# "setting.story_count_tip": "每次获取的条目数(1-60)",
# "topic.frontpage": "首页",
# "topic.newest": "最新",
# "topic.ask": "问 HN",
# "topic.show": "秀 HN",
# "topic.best": "最佳",
# "topic.active": "热议",
# "topic.jobs": "招聘",
# "topic.launches": "发布",
# "topic.polls": "投票",
# "topic.pool": "候选池",
# "topic.classic": "经典",
# "topic.invited": "特邀",
# "topic.bestcomments": "最佳评论",
# "topic.newcomments": "最新评论",
# "topic.whoishiring": "谁在招人",
# "action.open": "打开原文",
# "action.comments": "打开评论",
# "action.copy_title": "复制标题",
# "action.copy_url": "复制链接",
# "action.copy_comments": "复制评论链接",
# "action.open_hn": "打开 Hacker News",
# "action.switch": "切换话题",
# "hint.switch": "切换到其他 HN 话题",
# "error.fetch": "加载 Hacker News 失败",
# "error.empty": "这个话题没有条目",
# "error.none": "没有匹配的条目",
# "label.by": "作者",
# "label.comments": "评论",
# "rel.just_now": "刚刚",
# "rel.minutes_ago": "分钟前",
# "rel.hours_ago": "小时前",
# "rel.days_ago": "天前",
# "rel.minutes_later": "分钟后",
# "rel.hours_later": "小时后",
# "rel.days_later": "天后"
# }
# }
# }
"""
Wox Hacker News script plugin.
Usage:
hn front page (or the default topic in settings)
hn ask Ask HN
hn show rust filter Show HN by keyword
hn topics list all topics
"""
from __future__ import annotations
import datetime
import email.utils
import json
import os
import re
import sys
import tempfile
import xml.etree.ElementTree as ET
from typing import Any, List, Optional, TypedDict
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlencode
from urllib.request import Request, urlopen
HN_ICON = (
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"18\" height=\"18\" "
"viewBox=\"4 4 188 188\"><path d=\"m4 4h188v188h-188z\" fill=\"#f60\"/>"
"<path d=\"m73.2521756 45.01 22.7478244 47.39130083 22.7478244-47.39130083"
"h19.56569631l-34.32352071 64.48661468v41.49338532h-15.98v-41.49338532"
"l-34.32352071-64.48661468z\" fill=\"#fff\"/></svg>"
)
OPEN_ICON = "emoji:🔗"
COMMENT_ICON = "emoji:💬"
COPY_ICON = "emoji:📋"
TOPIC_ICON = "emoji:📂"
WARN_ICON = "emoji:⚠️"
HN_HOME = "https://news.ycombinator.com"
RSS_BASE = "https://hnrss.org"
CACHE_TTL_SECONDS = 90
CACHE_SCHEMA = 1
USER_AGENT = "Wox.Plugin.Script.HackerNews/1.0"
TOPICS = (
"frontpage",
"newest",
"ask",
"show",
"best",
"active",
"jobs",
"launches",
"polls",
"pool",
"classic",
"invited",
"bestcomments",
"newcomments",
"whoishiring",
)
TOPIC_SET = set(TOPICS)
POINTS_RE = re.compile(r"Points:\s*(\d+)", re.I)
COMMENTS_RE = re.compile(r"#?\s*Comments:\s*(\d+)", re.I)
class WoxPluginBase:
"""Wox plugin base class for script plugins. Do not modify this class."""
class Preview(TypedDict, total=False):
preview_type: str
preview_data: str
preview_properties: dict[str, str]
class ActionItem(TypedDict, total=False):
id: str
name: str
icon: str
text: str
url: str
path: str
message: str
query: str
preventHideAfterAction: bool
data: dict[str, str]
class TailItem(TypedDict, total=False):
id: str
type: str
text: str
image: str
contextData: dict[str, str]
class QueryResult(TypedDict, total=False):
title: str
subtitle: str
icon: str
preview: WoxPluginBase.Preview
tails: List[WoxPluginBase.TailItem]
score: int
actions: List[WoxPluginBase.ActionItem]
def __init__(self):
self.log_file_path = __file__ + ".log"
def log(self, message: str) -> None:
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
message = f"[{ts}] {message}"
if self.is_invoke_from_wox():
with open(self.log_file_path, "a", encoding="utf-8") as handle:
handle.write(f"{message}\n")
else:
print(f"LOG: {message}")
def is_invoke_from_wox(self) -> bool:
return "WOX_PLUGIN_ID" in os.environ
def _build_response(self, result: Any, request_id: Any) -> dict:
return {"jsonrpc": "2.0", "result": result, "id": request_id}
def _build_error_response(
self, code: int, message: str, data: Any = None, request_id: Any = None
) -> dict:
error = {"code": code, "message": message}
if data is not None:
error["data"] = data
return {"jsonrpc": "2.0", "error": error, "id": request_id}
def query(
self, raw_query: str, trigger_keyword: str, command: str, search: str
) -> List[WoxPluginBase.QueryResult]:
return []
def action(self, action_id: str, data: Any) -> None:
return None
def handle_query(self, params, request_id):
results = self.query(
params.get("raw_query", ""),
params.get("trigger_keyword", ""),
params.get("command", ""),
params.get("search", ""),
)
return self._build_response({"items": results}, request_id)
def handle_action(self, params, request_id):
self.action(params.get("id", ""), params.get("data", ""))
return self._build_response({}, request_id)
def run(self):
if hasattr(sys.stdout, "reconfigure"):
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
if self.is_invoke_from_wox():
try:
stdin_text = sys.stdin.read()
except Exception:
return 1
else:
print("Manual mode - please enter query:")
query_input = input()
stdin_text = (
'{"jsonrpc": "2.0", "method": "query", "params": {"search": "'
+ query_input.replace("\\", "\\\\").replace('"', '\\"')
+ '"}, "id": 1}'
)
try:
request = json.loads(stdin_text)
except json.JSONDecodeError as exc:
print(
json.dumps(
self._build_error_response(-32700, "Parse error", str(exc), None),
ensure_ascii=False,
)
)
return 1
if request.get("jsonrpc") != "2.0":
print(
json.dumps(
self._build_error_response(
-32600, "Invalid Request", None, request.get("id")
),
ensure_ascii=False,
)
)
return 1
method = request.get("method")
params = request.get("params", {})
request_id = request.get("id")
if method == "query":
response = self.handle_query(params, request_id)
elif method == "action":
response = self.handle_action(params, request_id)
else:
response = self._build_error_response(
-32601,
"Method not found",
f"Method '{method}' not supported",
request_id,
)
print(json.dumps(response, ensure_ascii=False))
return 0
def _setting(key: str, default: str = "") -> str:
return os.environ.get(f"WOX_SETTING_{key.upper()}", default).strip()
I18N = {
"en_US": {
"label.by": "by",
"label.comments": "comments",
"rel.just_now": "just now",
"rel.minutes_ago": "m ago",
"rel.hours_ago": "h ago",
"rel.days_ago": "d ago",
"rel.minutes_later": "m later",
"rel.hours_later": "h later",
"rel.days_later": "d later",
},
"zh_CN": {
"label.by": "作者",
"label.comments": "评论",
"rel.just_now": "刚刚",
"rel.minutes_ago": "分钟前",
"rel.hours_ago": "小时前",
"rel.days_ago": "天前",
"rel.minutes_later": "分钟后",
"rel.hours_later": "小时后",
"rel.days_later": "天后",
},
}
_LANG_CACHE = ""
def _wox_lang() -> str:
global _LANG_CACHE
if _LANG_CACHE:
return _LANG_CACHE
lang = os.environ.get("WOX_LANG", "").strip()
if lang in I18N:
_LANG_CACHE = lang
return lang
data_dir = os.environ.get("WOX_DIRECTORY_USER_DATA", "")
db_path = os.path.join(data_dir, "wox.db") if data_dir else ""
if db_path and os.path.isfile(db_path):
try:
import sqlite3
with sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=0.3) as conn:
row = conn.execute(
"SELECT value FROM wox_settings WHERE key = ?", ("LangCode",)
).fetchone()
if row and row[0]:
value = str(row[0]).strip().strip('"')
if value in I18N:
_LANG_CACHE = value
return value
except Exception:
pass
_LANG_CACHE = "en_US"
return _LANG_CACHE
def _t(key: str) -> str:
table = I18N.get(_wox_lang()) or I18N["en_US"]
return table.get(key) or I18N["en_US"].get(key, key)
def _local_tag(tag: str) -> str:
if tag.startswith("{"):
return tag.split("}", 1)[1]
return tag
def _child_text(parent: ET.Element, name: str) -> str:
for child in list(parent):
if _local_tag(child.tag) == name:
return (child.text or "").strip()
return ""
def _cache_dir() -> str:
path = os.path.join(tempfile.gettempdir(), "wox-plugin-hackernews")
os.makedirs(path, exist_ok=True)
return path
def _cache_path(topic: str, count: int) -> str:
return os.path.join(_cache_dir(), f"{topic}-{count}.json")
def _read_cache(topic: str, count: int) -> Optional[list[dict[str, Any]]]:
path = _cache_path(topic, count)
try:
with open(path, encoding="utf-8") as handle:
payload = json.load(handle)
except Exception:
return None
if not isinstance(payload, dict) or payload.get("schema") != CACHE_SCHEMA:
return None
fetched_at = payload.get("fetched_at")
items = payload.get("items")
if not isinstance(fetched_at, (int, float)) or not isinstance(items, list):
return None
if datetime.datetime.now().timestamp() - fetched_at > CACHE_TTL_SECONDS:
return None
return [item for item in items if isinstance(item, dict)]
def _write_cache(topic: str, count: int, items: list[dict[str, Any]]) -> None:
payload = {
"schema": CACHE_SCHEMA,
"fetched_at": datetime.datetime.now().timestamp(),
"items": items,
}
path = _cache_path(topic, count)
tmp = path + ".tmp"
try:
with open(tmp, "w", encoding="utf-8") as handle:
json.dump(payload, handle, ensure_ascii=False)
os.replace(tmp, path)
except Exception:
try:
os.remove(tmp)
except OSError:
pass
def _parse_count(item: dict[str, Any], key: str, text: str, pattern: re.Pattern[str]) -> int:
value = item.get(key)
if isinstance(value, int):
return value
match = pattern.search(text)
return int(match.group(1)) if match else 0
def _parse_pubdate(text: str) -> Optional[datetime.datetime]:
if not text:
return None
try:
moment = email.utils.parsedate_to_datetime(text)
if moment.tzinfo is None:
moment = moment.replace(tzinfo=datetime.timezone.utc)
return moment.astimezone()
except (TypeError, ValueError, OverflowError):
return None
def _parse_rss_item(node: ET.Element) -> Optional[dict[str, Any]]:
title = _child_text(node, "title")
if not title:
return None
description = _child_text(node, "description")
link = _child_text(node, "link")
comments = _child_text(node, "comments")
creator = _child_text(node, "creator")
pub_date = _child_text(node, "pubDate")
return {
"title": title,
"link": link or comments,
"comments": comments or link,
"creator": creator,
"pub_date": pub_date,
"points": _parse_count({}, "points", description, POINTS_RE),
"comment_count": _parse_count({}, "comment_count", description, COMMENTS_RE),
}
def _http_get(url: str, timeout: int = 8) -> bytes:
request = Request(url, headers={"User-Agent": USER_AGENT})
last_error: Exception | None = None
for _ in range(2):
try:
with urlopen(request, timeout=timeout) as response:
return response.read()
except HTTPError as exc:
last_error = exc
if exc.code < 500:
raise
except URLError as exc:
last_error = exc
if last_error:
raise last_error
raise URLError("empty response")
def _parse_rss(raw: bytes) -> list[dict[str, Any]]:
root = ET.fromstring(raw)
items: list[dict[str, Any]] = []
for node in root.iter():
if _local_tag(node.tag) != "item":
continue
parsed = _parse_rss_item(node)
if parsed:
items.append(parsed)
return items
def _algolia_endpoint(topic: str) -> Optional[tuple[str, dict[str, str]]]:
if topic == "frontpage":
return "search", {"tags": "front_page"}
if topic == "newest":
return "search_by_date", {"tags": "story"}
if topic == "ask":
return "search", {"tags": "ask_hn"}
if topic == "show":
return "search", {"tags": "show_hn"}
if topic == "best":
return "search", {"tags": "story"}
if topic == "jobs":
return "search", {"tags": "job"}
if topic == "polls":
return "search", {"tags": "poll"}
if topic == "bestcomments":
return "search", {"tags": "comment"}
if topic == "newcomments":
return "search_by_date", {"tags": "comment"}
if topic == "whoishiring":
return "search_by_date", {"tags": "story", "query": "who is hiring"}
return None
def _parse_algolia(payload: dict[str, Any]) -> list[dict[str, Any]]:
items: list[dict[str, Any]] = []
for hit in payload.get("hits") or []:
if not isinstance(hit, dict):
continue
object_id = str(hit.get("objectID") or "")
title = (
str(hit.get("title") or "")
or str(hit.get("story_title") or "")
or str(hit.get("comment_text") or "")[:120]
)
if not title:
continue
comments = f"{HN_HOME}/item?id={object_id}" if object_id else ""
created = hit.get("created_at")
pub_date = ""
if isinstance(created, str) and created:
try:
moment = datetime.datetime.fromisoformat(created.replace("Z", "+00:00"))
pub_date = moment.strftime("%a, %d %b %Y %H:%M:%S %z")
except ValueError:
pub_date = created
items.append(
{
"title": title,
"link": str(hit.get("url") or comments),
"comments": comments,
"creator": str(hit.get("author") or ""),
"pub_date": pub_date,
"points": int(hit.get("points") or 0),
"comment_count": int(hit.get("num_comments") or 0),
}
)
return items
def _fetch_rss(topic: str, count: int) -> list[dict[str, Any]]:
url = f"{RSS_BASE}/{quote(topic)}?count={count}"
return _parse_rss(_http_get(url))
def _fetch_algolia(topic: str, count: int) -> list[dict[str, Any]]:
spec = _algolia_endpoint(topic)
if spec is None:
return []
method, params = spec
query = {"hitsPerPage": str(count), **params}
url = f"https://hn.algolia.com/api/v1/{method}?{urlencode(query)}"
payload = json.loads(_http_get(url).decode("utf-8"))
if not isinstance(payload, dict):
return []
return _parse_algolia(payload)
def _error_text(exc: Exception) -> str:
if isinstance(exc, HTTPError):
return f"HTTP {exc.code} {exc.reason}"
if isinstance(exc, URLError):
return str(exc.reason or exc)
return str(exc)
def _fetch_feed(topic: str, count: int) -> tuple[list[dict[str, Any]], str]:
cached = _read_cache(topic, count)
if cached is not None:
return cached, ""
errors: list[str] = []
for loader in (_fetch_rss, _fetch_algolia):
try:
items = loader(topic, count)
except (ET.ParseError, HTTPError, URLError, TimeoutError, json.JSONDecodeError) as exc:
errors.append(_error_text(exc))
continue
except Exception as exc:
errors.append(str(exc))
continue
if items:
_write_cache(topic, count, items)
return items, ""
errors.append("empty feed")
return [], errors[0] if errors else "empty feed"
def _relative_text(moment: datetime.datetime) -> str:
now = datetime.datetime.now().astimezone()
if moment.tzinfo is None:
moment = moment.replace(tzinfo=now.tzinfo)
seconds = int((now - moment.astimezone(now.tzinfo)).total_seconds())
future = seconds < 0
seconds = abs(seconds)
if seconds < 45:
return _t("rel.just_now")
if seconds < 3600:
amount = max(1, seconds // 60)
key = "rel.minutes_later" if future else "rel.minutes_ago"
return f"{amount} {_t(key)}"
if seconds < 86400:
amount = seconds // 3600
key = "rel.hours_later" if future else "rel.hours_ago"
return f"{amount} {_t(key)}"
amount = seconds // 86400
key = "rel.days_later" if future else "rel.days_ago"
return f"{amount} {_t(key)}"
def _contains_token(haystack: str, token: str) -> bool:
return re.search(rf"(?<![a-z0-9]){re.escape(token)}(?![a-z0-9])", haystack) is not None
def _match_score(needle: str, title: str, extra: str = "") -> int:
if not needle:
return 0
haystack = f"{title} {extra}".lower()
if haystack == needle:
return 80
if haystack.startswith(needle):
return 50
if _contains_token(haystack, needle):
return 40
if len(needle) >= 3 and needle in haystack:
return 30
tokens = [token for token in needle.split() if token]
if tokens and all(_contains_token(haystack, token) for token in tokens):
return 20
return 0
class HackerNewsPlugin(WoxPluginBase):
def query(
self, raw_query: str, trigger_keyword: str, command: str, search: str
) -> List[WoxPluginBase.QueryResult]:
topic, keyword, show_topics = self._normalize_query(command, search)
trigger = trigger_keyword or "hn"
if show_topics:
return self._topic_results(trigger, keyword or topic)
return self._story_results(trigger, topic, keyword)
def _default_topic(self) -> str:
topic = _setting("default_topic", "frontpage").lower()
return topic if topic in TOPIC_SET else "frontpage"
def _story_count(self) -> int:
raw = _setting("story_count", "30")
try:
return min(60, max(1, int(raw)))
except ValueError:
return 30
def _normalize_query(
self, command: str, search: str
) -> tuple[str, str, bool]:
command = (command or "").strip().lower()
search = (search or "").strip()
if not command and search:
parts = search.split(None, 1)
command = parts[0].lower()
search = parts[1] if len(parts) > 1 else ""
if command in {"topics", "topic"}:
return "", search, True
if command in TOPIC_SET:
return command, search, False
if command:
return self._default_topic(), f"{command} {search}".strip(), False
return self._default_topic(), search, False
def _topic_results(
self, trigger: str, needle: str
) -> List[WoxPluginBase.QueryResult]:
query = needle.lower()
results: List[WoxPluginBase.QueryResult] = []
for index, topic in enumerate(TOPICS):
if query and query not in topic:
continue
results.append(
{
"title": topic,
"subtitle": f"i18n:topic.{topic}",
"icon": HN_ICON,
"score": 200 - index,
"actions": [
{
"name": "i18n:action.switch",
"id": "change-query",
"icon": TOPIC_ICON,
"query": f"{trigger} {topic} ",
"preventHideAfterAction": True,
},
{
"name": "i18n:action.open_hn",
"id": "open-url",
"icon": OPEN_ICON,
"url": self._topic_page(topic),
},
],
}
)
if results:
return results
return [
{
"title": "i18n:error.none",
"subtitle": needle,
"icon": WARN_ICON,
"score": 10,
}
]
def _story_results(
self, trigger: str, topic: str, keyword: str
) -> List[WoxPluginBase.QueryResult]:
items, error = _fetch_feed(topic, self._story_count())
if error:
return [
{
"title": "i18n:error.fetch",
"subtitle": error,
"icon": WARN_ICON,
"score": 100,
"actions": [
{
"name": "i18n:action.open_hn",
"id": "open-url",
"icon": OPEN_ICON,
"url": HN_HOME,
}
],
}
]
needle = keyword.lower()
results: List[WoxPluginBase.QueryResult] = []
if not needle:
results.append(self._topic_header(trigger, topic, len(items)))
matched = 0
for index, item in enumerate(items):
title = str(item.get("title") or "")
creator = str(item.get("creator") or "")
boost = _match_score(needle, title, creator)
if needle and boost <= 0:
continue
matched += 1
results.append(self._story_item(item, index, boost, bool(needle)))
if needle and matched == 0:
return [
{
"title": "i18n:error.none",
"subtitle": keyword,
"icon": WARN_ICON,
"score": 10,
"actions": [
{
"name": "i18n:action.switch",
"id": "change-query",
"icon": TOPIC_ICON,
"query": f"{trigger} {topic} ",
"preventHideAfterAction": True,
}
],
}
]
if not items:
results.append(
{
"title": "i18n:error.empty",
"subtitle": f"i18n:topic.{topic}",
"icon": WARN_ICON,
"score": 10,
}
)
return results
def _topic_header(
self, trigger: str, topic: str, total: int
) -> WoxPluginBase.QueryResult:
return {
"title": f"i18n:topic.{topic}",
"subtitle": "i18n:hint.switch",
"icon": HN_ICON,
"score": 400,
"tails": [{"type": "text", "text": f"{total}"}],
"actions": [
{
"name": "i18n:action.switch",
"id": "change-query",
"icon": TOPIC_ICON,
"query": f"{trigger} topics ",
"preventHideAfterAction": True,
},
{
"name": "i18n:action.open_hn",
"id": "open-url",
"icon": OPEN_ICON,
"url": self._topic_page(topic),
},
],
}
def _story_item(
self, item: dict[str, Any], rank: int, boost: int, searching: bool
) -> WoxPluginBase.QueryResult:
title = str(item.get("title") or "Untitled")
link = str(item.get("link") or "")
comments = str(item.get("comments") or "")
creator = str(item.get("creator") or "")
points = int(item.get("points") or 0)
comment_count = int(item.get("comment_count") or 0)
moment = _parse_pubdate(str(item.get("pub_date") or ""))
relative = _relative_text(moment) if moment else ""
subtitle_parts: list[str] = []
if creator:
subtitle_parts.append(f"{_t('label.by')} {creator}")
subtitle_parts.append(f"{comment_count} {_t('label.comments')}")
tails: List[WoxPluginBase.TailItem] = [
{"type": "text", "text": str(points)}
]
if relative:
tails.append({"type": "text", "text": relative})
article_url = link or comments
comments_url = comments or link
actions: List[WoxPluginBase.ActionItem] = []
if article_url:
actions.append(
{
"name": "i18n:action.open",
"id": "open-url",
"icon": OPEN_ICON,
"url": article_url,
}
)
if comments_url:
actions.append(
{
"name": "i18n:action.comments",
"id": "open-url",
"icon": COMMENT_ICON,
"url": comments_url,
}
)
actions.extend(
[
{
"name": "i18n:action.copy_title",
"id": "copy-to-clipboard",
"icon": COPY_ICON,
"text": title,
},
{
"name": "i18n:action.copy_url",
"id": "copy-to-clipboard",
"icon": COPY_ICON,
"text": article_url,
},
]
)
if comments_url:
actions.append(
{
"name": "i18n:action.copy_comments",
"id": "copy-to-clipboard",
"icon": COPY_ICON,
"text": comments_url,
}
)
return {
"title": title,
"subtitle": " · ".join(subtitle_parts),
"icon": HN_ICON,
"score": 200 + boost + points // 10 if searching else 300 - rank,
"tails": tails,
"actions": actions,
}
def _topic_page(self, topic: str) -> str:
if topic in {"frontpage", "classic", "invited", "pool"}:
return HN_HOME
if topic == "bestcomments":
return f"{HN_HOME}/bestcomments"
if topic == "newcomments":
return f"{HN_HOME}/newcomments"
if topic == "whoishiring":
return f"{HN_HOME}/submitted?id=whoishiring"
if topic == "launches":
return f"{HN_HOME}/launches"
return f"{HN_HOME}/{topic}"
if __name__ == "__main__":
sys.exit(HackerNewsPlugin().run())
@qianlifeng

Copy link
Copy Markdown
Author
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment