同步插件源代码并补齐标准项目文件

This commit is contained in:
XIGE
2026-11-26 15:05:38 +08:00
parent f813b839fa
commit 86b4e24004
21 changed files with 4694 additions and 1 deletions

29
.gitignore vendored Normal file
View File

@@ -0,0 +1,29 @@
# Dependencies and build output
node_modules/
vendor/
dist/
build/
out/
main.js
*.apk
# Build tools and IDE
.gradle/
.idea/
*.iml
gradle/
gradlew
gradlew.bat
# Environment and secrets
.env
.env.*
keystore.properties
*.jks
credentials*.json
# Runtime data and backups
data/
备份/
*.log
.DS_Store

7
CHANGELOG.md Normal file
View File

@@ -0,0 +1,7 @@
# 变更记录
## 2026-11-26 · 初始同步
- 同步插件源代码到新 Gitea 仓库。
- 补齐 README、LICENSE、.gitignore、CONTRIBUTING 等标准项目文件。
- 本仓库仅包含插件实现代码与必要资源,排除依赖、构建工具、编译产物、环境配置与备份数据。

19
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,19 @@
# 贡献指南
欢迎对本插件提出改进建议或提交代码。
## 提交前检查
- 仅提交插件实现代码、资源与必要文档,不提交依赖目录、编译产物、运行时数据或备份文件。
- 保持现有目录结构;如新增平台适配代码,请在 `README.md` 的目录结构中说明。
- 涉及对外服务或凭据的配置不要写入代码或文档。
## 提交流程
1. Fork 仓库并创建功能分支。
2. 完成修改后提交 Pull Request,说明改动目的与影响范围。
3. 重要功能变更请同步更新 `CHANGELOG.md`。
## 问题反馈
请通过仓库 Issue 反馈问题,并尽可能提供插件类型、版本与复现步骤。

21
LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 RssUnion
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,2 +1,35 @@
# obsidian-rss-union # RSS Union Reader
> 仓库:`obsidian-rss-union` · 类型:Obsidian 插件 · 版本:`1.4.1` · 作者:RssUnion
把 RssUnion 网站的「我的订阅」搬进 Obsidian:分类树、文章列表与阅读窗口全文阅读。
本仓库同步自本地插件源码,**仅包含插件实现代码与必要资源**;不包含依赖、构建工具、编译产物、环境配置或备份数据。
## 目录结构
- `locales/`
- `main.ts`
- `manifest.json`
- `setting/`
- `styles.css`
- `utils/`
- `view/`
## 安装与使用
1. 本仓库仅包含插件源代码,未包含依赖与构建工具;请先按 Obsidian 插件标准流程构建生成 `main.js`。
2. 将 `manifest.json`、构建后的 `main.js`、`styles.css` 及源码目录放入 `<Vault>/.obsidian/plugins/<插件 id>/`。
3. 在 Obsidian「设置 → 第三方插件」中启用该插件。
## 开发与贡献
详见 [CONTRIBUTING.md](CONTRIBUTING.md)。
## 授权
授权条款见 [LICENSE](LICENSE)(MIT License)。第三方组件版权归各自作者所有。
## 变更记录
详见 [CHANGELOG.md](CHANGELOG.md)。

110
locales/en.json Normal file
View File

@@ -0,0 +1,110 @@
{
"common": {
"refresh": "Refresh",
"loading": "Loading…",
"search": "Search title / site",
"previousPage": "Previous",
"nextPage": "Next",
"pageOf": "Page {page} / {total}",
"retry": "Retry",
"copy": "Copy",
"copied": "Copied",
"save": "Save",
"cancel": "Cancel",
"close": "Close",
"error": "Error",
"total": "{total} items"
},
"setting": {
"title": "RSS Union Reader",
"siteUrl": "Site URL",
"siteUrlDesc": "Root URL of your site, e.g. https://example.com (no /action/rssunion, no trailing slash)",
"authCode": "Auth code",
"authCodeDesc": "Site → Member center → My subscriptions → “Obsidian auth code”, then copy it here",
"verify": "Verify",
"verifying": "Verifying…",
"verified": "Connected: {name}, {sites} subscribed sites",
"verifyNeedInput": "Fill in site URL and auth code first",
"pageSize": "Items per page",
"pageSizeDesc": "How many articles per page (10–100)",
"openMode": "Reader window",
"openModeDesc": "Where to open the article after the full text is fetched",
"openModeSplit": "Split to the right",
"openModeTab": "New tab",
"saveFolder": "Save folder",
"saveFolderDesc": "Folder used by “Save as note” (created when missing)",
"autoRefresh": "Auto refresh",
"autoRefreshDesc": "While the panel is open, how often to pull new articles. Choose “Off” to refresh only when you click Refresh.",
"autoRefreshOff": "Off",
"minutes": "{n} min",
"clearRead": "Read history",
"clearReadDesc": "Read/unread marks are stored on this device only. Clearing them makes every article unread again.",
"clearReadBtn": "Clear read marks",
"clearReadDone": "Read marks cleared",
"howTo": "How to use",
"howToBody": "1. Generate an auth code in the member center and paste it above; 2. Run “Open RSS Union reader” from the command palette, or click the RSS ribbon icon; 3. Pick a category or site on the left, click an article on the right, and the full text opens in the reader."
},
"view": {
"title": "RSS Union",
"all": "All subscriptions",
"emptyTree": "No subscriptions yet",
"emptyTreeDesc": "Subscribe to some sites on the RSS page or site square first, then categories and articles show up here.",
"notConfigured": "Site not configured",
"notConfiguredDesc": "Fill in the site URL and auth code in the plugin settings, then refresh.",
"openSettings": "Open settings",
"emptyList": "No articles in this scope",
"refreshing": "Refreshing…",
"refreshed": "Refreshed",
"fetchedMark": "Fetched",
"loadingList": "Loading articles…",
"totalCount": "{n} articles",
"readChip": "Read",
"unreadChip": "Unread",
"filterTip": "Show only {label}",
"filterClear": "Click again to show all",
"selectMode": "Select",
"selectCancel": "Cancel",
"selectTip": "Enter multi-select to mark several articles as read at once",
"selectExitTip": "Leave multi-select",
"selectAll": "All",
"selectAllTip": "Select every article on this page",
"selectNoneTip": "Click again to deselect all",
"selectItem": "Select this article",
"markRead": "Mark read",
"markReadTip": "Mark the {n} selected articles as read",
"markReadEmpty": "Select some articles first",
"markReadDone": "{n} articles marked as read",
"markReadNone": "The selected articles are already read",
"filterOn": "Filtered: {label} ({n})",
"filterPartial": "Only the latest {n} articles were scanned",
"searching": "Search: {q}",
"clearSearch": "Click to clear the search",
"emptyRead": "Nothing read in this scope yet",
"emptyReadDesc": "Articles you open are remembered here (on this device only)",
"emptyUnread": "You have read everything in this scope",
"emptyUnreadDesc": "Click “Read” on the right to browse what you have read",
"serverBadge": "Server outdated",
"serverBadgeTip": "Category counts on the left still cover the whole site. Upload the new Obsidian.php to the plugin folder and restart Obsidian.",
"serverOld": "The server API is outdated (v{v}), so category counts on the left are still site-wide: replace Obsidian.php in the plugin folder (1.9.316)",
"serverUnknown": "The server did not report an API version, so counts cannot be verified: replace Obsidian.php in the plugin folder (1.9.316)",
"catTip": "{total} articles site-wide, {mine} in your subscriptions",
"autoRefreshHint": "Auto refresh every {n} min",
"loadFailed": "Failed to load: {message}",
"openReader": "Read",
"open": "Open RSS Union reader"
},
"reader": {
"title": "Reader",
"fetching": "Fetching full text…",
"fetchingHint": "Requesting the original page and extracting the article",
"failed": "Fetch failed",
"noContent": "No article body found — the page may use an unusual layout, try opening it in the browser",
"openSource": "Open in browser",
"saveNote": "Save as note",
"saved": "Saved: {path}",
"copyAll": "Copy all",
"words": "{n} chars",
"source": "Source",
"unknownTitle": "Untitled"
}
}

110
locales/zh.json Normal file
View File

@@ -0,0 +1,110 @@
{
"common": {
"refresh": "刷新",
"loading": "加载中…",
"search": "搜索标题 / 网站",
"previousPage": "上一页",
"nextPage": "下一页",
"pageOf": "第 {page} / {total} 页",
"retry": "重试",
"copy": "复制",
"copied": "已复制",
"save": "保存",
"cancel": "取消",
"close": "关闭",
"error": "出错了",
"total": "共 {total} 条"
},
"setting": {
"title": "RSS Union Reader",
"siteUrl": "站点地址",
"siteUrlDesc": "填网站根地址,例如 https://example.com(不要带 /action/rssunion,也不要带结尾斜杠)",
"authCode": "授权码",
"authCodeDesc": "网站 → 会员中心 → 我的订阅 → 「Obsidian 授权码」,复制过来即可",
"verify": "验证连接",
"verifying": "验证中…",
"verified": "连接正常:{name},已订阅 {sites} 个网站",
"verifyNeedInput": "先填站点地址和授权码",
"pageSize": "每页文章数",
"pageSizeDesc": "右侧列表一页显示几条(10–100)",
"openMode": "阅读窗口",
"openModeDesc": "点文章抓完全文后在哪里打开",
"openModeSplit": "右侧分栏",
"openModeTab": "新标签页",
"saveFolder": "保存目录",
"saveFolderDesc": "「保存为笔记」写进库里的哪个文件夹(不存在会自动创建)",
"autoRefresh": "自动刷新间隔",
"autoRefreshDesc": "面板开着的时候,每隔多久去网站取一次新文章。选「关闭」就只在你手动点刷新时才更新。",
"autoRefreshOff": "关闭",
"minutes": "{n} 分钟",
"clearRead": "已读记录",
"clearReadDesc": "已读 / 未读标记只记在本机,不会同步到其他设备。清空后所有文章重新算未读。",
"clearReadBtn": "清空已读",
"clearReadDone": "已读记录已清空",
"howTo": "怎么用",
"howToBody": "1. 在会员中心生成授权码,填到上面的「授权码」;2. 命令面板执行「打开 RSS Union 阅读器」,或点左侧功能区的 RSS 图标;3. 左树选分类或网站,右侧点文章,抓到全文后打开阅读窗口。"
},
"view": {
"title": "RSS Union",
"all": "全部订阅",
"emptyTree": "还没有订阅任何网站",
"emptyTreeDesc": "先去网站的 RSS 聚合页或网站广场订阅几个网站,这里就会出现分类和文章。",
"notConfigured": "还没配置站点",
"notConfiguredDesc": "先在插件设置里填站点地址和授权码,然后回来刷新。",
"openSettings": "打开设置",
"emptyList": "这个范围暂时没有文章",
"refreshing": "正在刷新…",
"refreshed": "已刷新",
"fetchedMark": "已抓取",
"loadingList": "正在取文章列表…",
"totalCount": "共 {n} 篇",
"readChip": "已读",
"unreadChip": "未读",
"filterTip": "只看{label}",
"filterClear": "再点一次回到全部",
"selectMode": "选择",
"selectCancel": "取消",
"selectTip": "进入多选,勾选后可以一次标为已读",
"selectExitTip": "退出多选",
"selectAll": "全选",
"selectAllTip": "选中当前这一页的全部文章",
"selectNoneTip": "再点一次取消全选",
"selectItem": "选择这篇文章",
"markRead": "设为已读",
"markReadTip": "把勾选的 {n} 篇标为已读",
"markReadEmpty": "先勾选文章",
"markReadDone": "已把 {n} 篇标为已读",
"markReadNone": "勾选的文章都已经是已读了",
"filterOn": "筛选中:{label}({n} 篇)",
"filterPartial": "只筛了最近 {n} 篇",
"searching": "搜索:{q}",
"clearSearch": "点一下清空搜索",
"emptyRead": "这个范围还没有已读文章",
"emptyReadDesc": "点开过的文章会记在这里(只记在本机,不与其他设备同步)",
"emptyUnread": "这个范围的文章都读完了",
"emptyUnreadDesc": "点右侧「已读」可以回看读过的文章",
"serverOld": "服务端接口是旧版(v{v}),左侧数字仍是整个分类的全站篇数:把 plugins/RssUnion/Obsidian.php 覆盖成新版(1.9.316)",
"serverUnknown": "服务端没返回接口版本,无法确认左侧数字的口径:把 plugins/RssUnion/Obsidian.php 覆盖成新版(1.9.316)",
"serverBadge": "服务端待更新",
"serverBadgeTip": "左侧分类数字现在还是「整个分类全站」的篇数。把新版 Obsidian.php 覆盖到服务器插件目录,再重启 Obsidian 即可。",
"catTip": "全站 {total} 篇,你订阅的网站里有 {mine} 篇",
"autoRefreshHint": "每 {n} 分钟自动刷新",
"loadFailed": "加载失败:{message}",
"openReader": "读全文",
"open": "打开 RSS Union 阅读器"
},
"reader": {
"title": "阅读",
"fetching": "正在抓取全文…",
"fetchingHint": "正在请求原文并抽取正文,稍等",
"failed": "抓取失败",
"noContent": "没抽到正文,可能原文结构特殊,用浏览器打开看看",
"openSource": "浏览器打开",
"saveNote": "保存为笔记",
"saved": "已保存:{path}",
"copyAll": "复制全文",
"words": "{n} 字",
"source": "原文",
"unknownTitle": "未命名文章"
}
}

84
main.ts Normal file
View File

@@ -0,0 +1,84 @@
import { Plugin, WorkspaceLeaf, addIcon } from "obsidian";
import { DEFAULT_SETTINGS, RssUnionSettings } from "./setting/plugin_settings";
import { setSettings } from "./setting/store";
import { RssUnionSettingTab } from "./setting/setting_tab";
import { RssUnionView, VIEW_TYPE_MAIN } from "./view/main_view";
import { ReaderView, VIEW_TYPE_READER } from "./view/reader_view";
import i18n from "./utils/i18n";
/** 左侧功能区的图标:几道 RSS 波纹,和插件用途对上 */
const ICON_RSS = `<path d="M4 11a9 9 0 0 1 9 9"/><path d="M4 4a16 16 0 0 1 16 16"/><circle cx="5" cy="19" r="1"/>`;
export default class RssUnionPlugin extends Plugin {
settings: RssUnionSettings = Object.assign({}, DEFAULT_SETTINGS);
async onload(): Promise<void> {
await this.loadSettings();
addIcon("ru-rss", ICON_RSS);
this.registerView(VIEW_TYPE_MAIN, (leaf: WorkspaceLeaf) => new RssUnionView(leaf));
this.registerView(VIEW_TYPE_READER, (leaf: WorkspaceLeaf) => new ReaderView(leaf));
this.addRibbonIcon("ru-rss", i18n.t("view.title"), () => {
void this.activateView();
});
this.addCommand({
id: "open-rss-union-reader",
name: i18n.t("view.open"),
callback: () => {
void this.activateView();
},
});
this.addSettingTab(new RssUnionSettingTab(this.app, this));
}
async loadSettings(): Promise<void> {
const loaded = await this.loadData();
this.settings = Object.assign({}, DEFAULT_SETTINGS, loaded || {});
setSettings(this.settings);
}
async saveSettings(): Promise<void> {
await this.saveData(this.settings);
setSettings(this.settings);
}
/** 打开(或聚焦)主面板 */
async activateView(): Promise<void> {
const { workspace } = this.app;
const existing = workspace.getLeavesOfType(VIEW_TYPE_MAIN);
if (existing.length > 0) {
workspace.revealLeaf(existing[0]);
return;
}
const leaf = workspace.getLeaf("tab");
if (!leaf) return;
await leaf.setViewState({ type: VIEW_TYPE_MAIN, active: true });
workspace.revealLeaf(leaf);
}
/**
* 让已经打开的面板重新取一遍数据
*
* @param reset true = 顺带把选中的分类、搜索词清空(改了站点 / 授权码时用)
* false = 保持当前浏览位置(只改刷新间隔时用)
*/
async refreshViews(reset = true): Promise<void> {
for (const leaf of this.app.workspace.getLeavesOfType(VIEW_TYPE_MAIN)) {
const view = leaf.view as unknown as {
reloadFromSettings?: (reset?: boolean) => Promise<void>;
};
await view.reloadFromSettings?.(reset);
}
}
}

9
manifest.json Normal file
View File

@@ -0,0 +1,9 @@
{
"id": "obsidian-rss-union",
"name": "RSS Union Reader",
"version": "1.4.1",
"minAppVersion": "0.15.0",
"description": "把 RssUnion 网站的「我的订阅」搬进 Obsidian:左侧分类树、右侧文章列表,点文章抓全文在阅读窗口看。",
"author": "RssUnion",
"isDesktopOnly": false
}

View File

@@ -0,0 +1,36 @@
export interface RssUnionSettings {
/** 网站根地址,例如 https://example.com(不带结尾斜杠) */
siteUrl: string;
/** 会员中心生成的授权码 */
authCode: string;
/** 文章列表每页条数 */
pageSize: number;
/** 阅读窗口打开位置:tab = 新标签页(稳),split = 当前面板右侧分栏 */
openMode: "split" | "tab";
/** 「保存为笔记」时的目录 */
saveFolder: string;
/** 自动刷新间隔(分钟),0 = 关闭 */
autoRefreshMin: number;
/** 上次验证得到的会员名,设置页展示用 */
verifyName: string;
/** 上次验证时间(ISO 字符串) */
verifyAt: string;
}
/**
* 默认用「新标签页」
*
* split 出来的新 leaf 在部分 Obsidian 版本里,setViewState 时 header 还没建好,
* Obsidian 内部会对 null 的 title 元素调 setText 抛错,整个 view 打不开。
* tab 走的路径稳定,默认给它;想要分栏的可以自己在设置里改。
*/
export const DEFAULT_SETTINGS: RssUnionSettings = {
siteUrl: "",
authCode: "",
pageSize: 30,
openMode: "tab",
saveFolder: "RssUnion",
autoRefreshMin: 5,
verifyName: "",
verifyAt: "",
};

182
setting/setting_tab.ts Normal file
View File

@@ -0,0 +1,182 @@
import {
App,
Notice,
PluginSettingTab,
Setting,
} from "obsidian";
import type RssUnionPlugin from "../main";
import { ping } from "../utils/api";
import { clearReadState } from "../utils/read_state";
import i18n from "../utils/i18n";
export class RssUnionSettingTab extends PluginSettingTab {
private plugin: RssUnionPlugin;
private verifyEl: HTMLElement | null = null;
constructor(app: App, plugin: RssUnionPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: i18n.t("setting.title") });
new Setting(containerEl)
.setName(i18n.t("setting.siteUrl"))
.setDesc(i18n.t("setting.siteUrlDesc"))
.addText((text) =>
text
.setPlaceholder("https://example.com")
.setValue(this.plugin.settings.siteUrl)
.onChange(async (value) => {
this.plugin.settings.siteUrl = value.trim();
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName(i18n.t("setting.authCode"))
.setDesc(i18n.t("setting.authCodeDesc"))
.addText((text) => {
text.inputEl.addClass("ru-setting-code");
text.setPlaceholder("ruo_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.setValue(this.plugin.settings.authCode)
.onChange(async (value) => {
this.plugin.settings.authCode = value.trim();
await this.plugin.saveSettings();
});
});
const verify = new Setting(containerEl).setName(i18n.t("setting.verify"));
this.verifyEl = verify.descEl.createDiv({ cls: "ru-setting-verify" });
this.paintVerify();
verify.addButton((button) =>
button.setButtonText(i18n.t("setting.verify")).setCta().onClick(async () => {
button.setDisabled(true);
button.setButtonText(i18n.t("setting.verifying"));
try {
const res = await ping();
this.plugin.settings.verifyName = res.user?.name || "";
this.plugin.settings.verifyAt = new Date().toISOString();
await this.plugin.saveSettings();
this.paintVerify();
new Notice(i18n.t("setting.verified", { name: res.user?.name || "-", sites: res.siteCount || 0 }));
await this.plugin.refreshViews();
} catch (error: any) {
this.plugin.settings.verifyName = "";
this.plugin.settings.verifyAt = "";
await this.plugin.saveSettings();
this.paintVerify(String(error?.message || error));
new Notice(`验证失败:${error?.message || error}`);
} finally {
button.setDisabled(false);
button.setButtonText(i18n.t("setting.verify"));
}
})
);
new Setting(containerEl)
.setName(i18n.t("setting.pageSize"))
.setDesc(i18n.t("setting.pageSizeDesc"))
.addSlider((slider) =>
slider
.setLimits(10, 100, 5)
.setValue(this.plugin.settings.pageSize)
.setDynamicTooltip()
.onChange(async (value) => {
this.plugin.settings.pageSize = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName(i18n.t("setting.autoRefresh"))
.setDesc(i18n.t("setting.autoRefreshDesc"))
.addDropdown((drop) => {
drop.addOption("0", i18n.t("setting.autoRefreshOff"));
for (const minutes of [1, 5, 10, 15, 30, 60]) {
drop.addOption(String(minutes), i18n.t("setting.minutes", { n: minutes }));
}
drop.setValue(String(this.plugin.settings.autoRefreshMin || 0)).onChange(async (value) => {
this.plugin.settings.autoRefreshMin = Number(value) || 0;
await this.plugin.saveSettings();
// 只重启定时器,不重置当前选中的分类和搜索词
await this.plugin.refreshViews(false);
});
});
new Setting(containerEl)
.setName(i18n.t("setting.openMode"))
.setDesc(i18n.t("setting.openModeDesc"))
.addDropdown((drop) =>
drop
.addOption("split", i18n.t("setting.openModeSplit"))
.addOption("tab", i18n.t("setting.openModeTab"))
.setValue(this.plugin.settings.openMode)
.onChange(async (value) => {
this.plugin.settings.openMode = value === "tab" ? "tab" : "split";
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName(i18n.t("setting.saveFolder"))
.setDesc(i18n.t("setting.saveFolderDesc"))
.addText((text) =>
text
.setPlaceholder("RssUnion")
.setValue(this.plugin.settings.saveFolder)
.onChange(async (value) => {
this.plugin.settings.saveFolder = value.trim();
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName(i18n.t("setting.clearRead"))
.setDesc(i18n.t("setting.clearReadDesc"))
.addButton((button) =>
button.setButtonText(i18n.t("setting.clearReadBtn")).onClick(async () => {
clearReadState();
await this.plugin.refreshViews(false);
new Notice(i18n.t("setting.clearReadDone"));
})
);
containerEl.createEl("h3", { text: i18n.t("setting.howTo") });
containerEl.createEl("p", { cls: "ru-setting-help", text: i18n.t("setting.howToBody") });
}
private paintVerify(errorMessage?: string): void {
if (!this.verifyEl) return;
this.verifyEl.empty();
this.verifyEl.removeClass("is-ok");
this.verifyEl.removeClass("is-error");
if (errorMessage) {
this.verifyEl.addClass("is-error");
this.verifyEl.setText(errorMessage);
return;
}
if (this.plugin.settings.verifyName) {
this.verifyEl.addClass("is-ok");
this.verifyEl.setText(`已连接:${this.plugin.settings.verifyName}`);
return;
}
this.verifyEl.setText(i18n.t("setting.verifyNeedInput"));
}
}

23
setting/store.ts Normal file
View File

@@ -0,0 +1,23 @@
import { DEFAULT_SETTINGS, RssUnionSettings } from "./plugin_settings";
/** 全局设置引用:main.ts 加载完写入,其余模块只读,避免各处 import main 造成循环依赖 */
let current: RssUnionSettings = Object.assign({}, DEFAULT_SETTINGS);
export function setSettings(next: RssUnionSettings) {
current = next;
}
export function getSettings(): RssUnionSettings {
return current;
}
/** 站点地址是否已经填了(授权码可以为空,验证时会单独提示) */
export function hasSite(): boolean {
return normalizeSiteUrl(current.siteUrl) !== "";
}
export function normalizeSiteUrl(raw: string): string {
return String(raw || "")
.trim()
.replace(/\/+$/, "");
}

1268
styles.css Normal file

File diff suppressed because it is too large Load Diff

223
utils/api.ts Normal file
View File

@@ -0,0 +1,223 @@
import { requestUrl } from "obsidian";
import { getSettings, normalizeSiteUrl } from "../setting/store";
/* ==================================================================
* 与服务端 /action/rssunion?do=obsidian* 的对接
*
* 参数全部走查询串:GET 请求在 Obsidian 里没有 CORS 问题
* (requestUrl 走的是主进程),也不会因为 Referer 被拦。
* ================================================================== */
export interface RuSite {
id: number;
title: string;
url: string;
feedCount: number;
star: number;
}
export interface RuCategory {
id: number;
name: string;
siteCount: number;
/** 我订阅范围内、该分类的文章数(与右侧列表 total 同口径) */
feedCount: number;
/** 该分类全站的文章数(不含订阅限制),只在悬浮提示里用 */
feedTotal?: number;
sites: RuSite[];
}
export interface RuItem {
id: number;
urlId: number;
title: string;
link: string;
excerpt: string;
siteTitle: string;
siteUrl: string;
categoryId: number;
categoryName: string;
pubDate: string;
srcPubDate: string;
cachedAt: string;
isPinned: boolean;
isFeatured: boolean;
isHot: boolean;
isDaily: boolean;
tags: string[];
}
export interface RuPing {
apiVersion: string;
user: { uid: number; name: string; mail: string };
siteCount: number;
serverTime: string;
}
export interface RuTree {
tree: RuCategory[];
stats: { categories: number; sites: number; feeds?: number };
/** 服务端接口版本(1.9.313 起才有);没有说明服务器上的 Obsidian.php 还是旧文件 */
apiVersion?: string;
/** subscribed = 分类 / 网站 / 合计三个数字都只算我订阅的网站 */
countMode?: string;
message?: string;
}
export interface RuItems {
apiVersion?: string;
page: number;
pages: number;
pageSize: number;
total: number;
items: RuItem[];
message?: string;
}
export interface ItemQuery {
urlId?: number;
catId?: number;
keyword?: string;
page?: number;
pageSize?: number;
}
/** 配置是否齐全 */
export function isConfigured(): boolean {
const s = getSettings();
return normalizeSiteUrl(s.siteUrl) !== "" && String(s.authCode || "").trim() !== "";
}
function endpoint(action: string, params: Record<string, string | number | undefined> = {}): string {
const s = getSettings();
const q = new URLSearchParams();
q.set("do", action);
q.set("code", String(s.authCode || "").trim());
Object.keys(params).forEach((key) => {
const value = params[key];
if (value === undefined || value === "" || value === 0) return;
q.set(key, String(value));
});
return `${normalizeSiteUrl(s.siteUrl)}/action/rssunion?${q.toString()}`;
}
async function getJson<T>(url: string): Promise<T> {
let res;
try {
res = await requestUrl({
url,
method: "GET",
headers: { Accept: "application/json" },
throw: false,
});
} catch (error: any) {
// requestUrl 的网络层错误(DNS / 证书 / 超时):消息太技术,换成一句能看懂的
const detail = String(error?.message || error || "");
throw new Error(`连不上站点(${detail})。检查站点地址是否写对、网络是否正常`);
}
const text = String(res.text || "").trim();
if (res.status >= 400) {
throw new Error(`站点返回 HTTP ${res.status}:${snippet(text)}`);
}
if (!text.startsWith("{")) {
throw new Error(
`站点返回的不是 JSON(${snippet(text)})。可能是插件未启用、站点地址填错,或服务器把 /action/rssunion 重写了`
);
}
let data: any;
try {
data = JSON.parse(text);
} catch (error) {
throw new Error("站点返回的 JSON 解析失败,可能被压缩或截断了");
}
if (!data || data.success !== true) {
const err: any = new Error((data && data.message) || "接口返回失败");
err.code = data && data.code;
throw err;
}
return data as T;
}
/** 服务器把 HTML 错误页丢回来时,压成一句话给用户看 */
function snippet(html: string): string {
const plain = String(html || "")
.replace(/<script[\s\S]*?<\/script>/gi, " ")
.replace(/<style[\s\S]*?<\/style>/gi, " ")
.replace(/<[^>]+>/g, " ")
.replace(/\s+/g, " ")
.trim();
return plain.slice(0, 120) || "空响应";
}
/** 验证连接 */
export async function ping(): Promise<RuPing> {
const data = await getJson<RuPing>(endpoint("obsidianPing"));
return data;
}
/** 分类树(只含我订阅的网站) */
export async function fetchTree(): Promise<RuTree> {
return getJson<RuTree>(endpoint("obsidianTree"));
}
/** 文章列表 */
export async function fetchItems(query: ItemQuery): Promise<RuItems> {
const pageSize = query.pageSize || getSettings().pageSize || 30;
return getJson<RuItems>(
endpoint("obsidianItems", {
url_id: query.urlId,
cat_id: query.catId,
keyword: query.keyword,
page: query.page || 1,
page_size: pageSize,
})
);
}
/**
* 把 tags 统一成字符串数组
*
* 服务端给的可能是 `["旅行","骑行"]`,也可能是 `[{id,name,slug}, ...]`
* (取决于 RssUnion 那边有没有升级)。两种都认,别让 #标签 变成 [object Object]。
*/
export function tagLabels(tags: unknown): string[] {
if (!Array.isArray(tags)) return [];
const names: string[] = [];
for (const tag of tags) {
let name = "";
if (typeof tag === "string") {
name = tag;
} else if (tag && typeof tag === "object") {
const value = (tag as Record<string, unknown>).name;
if (typeof value === "string") name = value;
}
name = name.trim();
if (name !== "") names.push(name);
}
return Array.from(new Set(names));
}

21
utils/cache.ts Normal file
View File

@@ -0,0 +1,21 @@
import { ExtractedArticle } from "./extract";
/**
* 本次会话已经抓过的全文。
*
* 只放内存:抓一次读多次够用,也避免把几十万字写进 data.json。
* 关掉 Obsidian 就没了,下次点同一篇会重新抓(想要长期留存用「保存为笔记」)。
*/
const cache = new Map<number, ExtractedArticle>();
export function getCached(feedId: number): ExtractedArticle | undefined {
return cache.get(feedId);
}
export function setCached(feedId: number, article: ExtractedArticle): void {
cache.set(feedId, article);
}
export function hasCached(feedId: number): boolean {
return cache.has(feedId);
}

67
utils/datetime.ts Normal file
View File

@@ -0,0 +1,67 @@
/**
* 服务端时间都是「YYYY-MM-DD HH:mm:ss」的本地时间字符串,
* 直接 new Date() 在部分环境会被当成 UTC,这里手动拆字段,避免差 8 小时。
*/
export function parseServerDate(raw: string): Date | null {
const text = String(raw || "").trim();
const m = text.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?/);
if (!m) return null;
return new Date(
Number(m[1]),
Number(m[2]) - 1,
Number(m[3]),
Number(m[4] || 0),
Number(m[5] || 0),
Number(m[6] || 0)
);
}
function pad(n: number): string {
return n < 10 ? `0${n}` : String(n);
}
/** 列表里显示的时间:今天 / 昨天 / N 天前,超过一周显示日期 */
export function formatListDate(raw: string): string {
const date = parseServerDate(raw);
if (!date) return String(raw || "").slice(0, 10);
const now = new Date();
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
const time = date.getTime();
const diffDays = Math.floor((startOfToday - new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()) / 86400000);
if (diffDays === 0) return `今天 ${pad(date.getHours())}:${pad(date.getMinutes())}`;
if (diffDays === 1) return `昨天 ${pad(date.getHours())}:${pad(date.getMinutes())}`;
if (diffDays > 1 && diffDays < 7) return `${diffDays} 天前`;
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}
/** 完整时间:阅读窗口头部用 */
export function formatFullDate(raw: string): string {
const date = parseServerDate(raw);
if (!date) return String(raw || "");
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
/** 文件名 / 笔记标题用的日期前缀 */
export function dayStamp(raw?: string): string {
const date = parseServerDate(raw || "") || new Date();
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}
/** 文件名里不能出现的字符统一换掉 */
export function safeFileName(name: string, maxLength = 80): string {
const cleaned = String(name || "")
.replace(/[\\/:*?"<>|#^[\]]/g, " ")
.replace(/\s+/g, " ")
.trim();
return cleaned.slice(0, maxLength) || "untitled";
}

317
utils/extract.ts Normal file

File diff suppressed because it is too large Load Diff

21
utils/i18n.ts Normal file
View File

@@ -0,0 +1,21 @@
import i18next from "i18next";
import { getLanguage } from "obsidian";
const resources = {
en: { translation: require("../locales/en.json") },
zh: { translation: require("../locales/zh.json") },
};
i18next.init({
lng: getLanguage(),
fallbackLng: "en",
resources,
interpolation: {
escapeValue: false,
prefix: "{",
suffix: "}",
},
keySeparator: ".",
});
export default i18next;

209
utils/read_state.ts Normal file
View File

@@ -0,0 +1,209 @@
/* ==================================================================
* 已读 / 未读
*
* 存在 localStorage,不写 data.json:
* - 阅读状态是高频写入的数据,塞进设置里会让每次点文章都重写整个配置文件;
* - 用户手改设置时也不会被几千个 id 淹没。
*
* 两个索引:
* read —— 全局已读表(id → 时间戳),决定某一行为「已读」样式
* scope —— 按范围(全部 / 分类 / 网站)存的 id 数组,用来算「已读 (x)」
*
* 标记一篇已读时,同时写进 all / cat:<分类> / site:<网站> 三个范围,
* 这样在哪一层看统计都对得上。范围数组只追加不重排,超出上限砍掉最早的。
* ================================================================== */
const STORAGE_KEY = "ruu-read-v1";
const MAX_SCOPE_ITEMS = 8000;
const MAX_GLOBAL_ITEMS = 20000;
interface ReadStore {
v: number;
read: Record<string, number>;
scope: Record<string, number[]>;
}
export interface ReadableItem {
id: number;
categoryId?: number;
urlId?: number;
}
let store: ReadStore | null = null;
let saveTimer: number | null = null;
function emptyStore(): ReadStore {
return { v: 1, read: {}, scope: {} };
}
function load(): ReadStore {
if (store) return store;
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
const parsed = raw ? JSON.parse(raw) : null;
if (parsed && typeof parsed === "object" && parsed.read && parsed.scope) {
store = {
v: 1,
read: parsed.read || {},
scope: parsed.scope || {},
};
return store;
}
} catch (error) {
/* 存的内容坏了就当空的,别让阅读列表因为一个坏 JSON 打不开 */
console.warn("RssUnion: 已读记录解析失败,已重置", error);
}
store = emptyStore();
return store;
}
/** 攒一下再写盘:连点几篇只落一次 */
function persistSoon(): void {
if (saveTimer !== null) return;
saveTimer = window.setTimeout(() => {
saveTimer = null;
try {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(load()));
} catch (error) {
console.warn("RssUnion: 已读记录写入失败", error);
}
}, 400);
}
/** 立刻落盘(面板关闭时用,别把最后的记录丢掉) */
export function flushReadState(): void {
if (saveTimer !== null) {
window.clearTimeout(saveTimer);
saveTimer = null;
}
try {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(load()));
} catch (error) {
// 存不进去也不影响当前会话
}
}
/** 当前选中范围对应的 scope 键 */
export function scopeKeyOf(type: string, id: number): string {
if (type === "cat") return `cat:${id}`;
if (type === "site") return `site:${id}`;
return "all";
}
/** 一篇已读文章要记进哪几个范围 */
function scopeKeysOfItem(item: ReadableItem): string[] {
const keys = ["all"];
if (item.categoryId) keys.push(`cat:${item.categoryId}`);
if (item.urlId) keys.push(`site:${item.urlId}`);
return keys;
}
export function isRead(id: number): boolean {
const data = load();
return Object.prototype.hasOwnProperty.call(data.read, String(id));
}
/** 把一篇写进数据(不落盘);返回 true 表示这是新标记(之前未读) */
function applyMark(data: ReadStore, item: ReadableItem): boolean {
if (!item || !item.id) return false;
const key = String(item.id);
const fresh = !data.read[key];
if (fresh) data.read[key] = Date.now();
/* 已读过的也补一次范围索引,防止早期版本只写了全局没写范围 */
for (const scope of scopeKeysOfItem(item)) {
if (!data.scope[scope]) data.scope[scope] = [];
const list = data.scope[scope];
if (list.indexOf(item.id) >= 0) continue;
list.push(item.id);
if (list.length > MAX_SCOPE_ITEMS) {
data.scope[scope] = list.slice(list.length - MAX_SCOPE_ITEMS);
}
}
return fresh;
}
/** 标记已读;返回 true 表示这是新标记(之前未读) */
export function markRead(item: ReadableItem): boolean {
const data = load();
const fresh = applyMark(data, item);
if (fresh) {
trimGlobal(data);
persistSoon();
}
return fresh;
}
/**
* 批量标记已读(多选「设为已读」用)
*
* @returns 真正从「未读」变成「已读」的篇数(原本就读过的不计入)
*/
export function markReadMany(items: ReadableItem[]): number {
if (!items || items.length === 0) return 0;
const data = load();
let changed = 0;
for (const item of items) {
if (applyMark(data, item)) changed++;
}
if (changed > 0) {
trimGlobal(data);
persistSoon();
}
return changed;
}
function trimGlobal(data: ReadStore): void {
const keys = Object.keys(data.read);
if (keys.length <= MAX_GLOBAL_ITEMS) return;
keys.sort((a, b) => (data.read[a] || 0) - (data.read[b] || 0));
for (const key of keys.slice(0, keys.length - MAX_GLOBAL_ITEMS)) {
delete data.read[key];
}
}
/** 某个范围里已读了多少篇 */
export function countRead(scope: string): number {
const list = load().scope[scope];
return list ? list.length : 0;
}
/** 清空已读记录(设置页里给个「重置」用) */
export function clearReadState(): void {
store = emptyStore();
flushReadState();
}
/** 把 localStorage 里的记录读出来(调试 / 测试用) */
export function debugSnapshot(): ReadStore {
return load();
}

1546
view/main_view.ts Normal file

File diff suppressed because it is too large Load Diff

358
view/reader_view.ts Normal file

File diff suppressed because it is too large Load Diff