同步插件源代码并补齐标准项目文件
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));
|
||||
}
|
||||
Reference in New Issue
Block a user