同步插件源代码并补齐标准项目文件
This commit is contained in:
223
utils/api.ts
Normal file
223
utils/api.ts
Normal 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
21
utils/cache.ts
Normal 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
67
utils/datetime.ts
Normal 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
317
utils/extract.ts
Normal file
File diff suppressed because it is too large
Load Diff
21
utils/i18n.ts
Normal file
21
utils/i18n.ts
Normal 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
209
utils/read_state.ts
Normal 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();
|
||||
}
|
||||
Reference in New Issue
Block a user