Files

224 lines
6.7 KiB
TypeScript
Raw Permalink Normal View History

import { requestUrl, RequestUrlResponse, Notice } from "obsidian";
import { getSettings, getActiveSite, getSites } from "../main";
import { ResponseType } from "./response_type";
export class HttpUtils {
// 动态配置(优先使用)
private static currentHost: string = "";
private static currentToken: string = "";
// 设置当前使用的网站(切换时调用)
public static setCurrentSite(host: string, token: string) {
this.currentHost = host;
this.currentToken = token;
}
// 获取当前有效的 Host(公开方法,供外部使用)
public static getCurrentHost(): string {
if (this.currentHost) return this.currentHost;
const activeSite = getActiveSite();
if (activeSite?.Host) return activeSite.Host;
// 降级:从第一个网站获取
const sites = getSites();
return sites[0]?.Host || "";
}
// 获取当前有效的 Token(公开方法,供外部使用)
public static getCurrentToken(): string {
if (this.currentToken) return this.currentToken;
const activeSite = getActiveSite();
if (activeSite?.Token) return activeSite.Token;
// 降级:从第一个网站获取
const sites = getSites();
return sites[0]?.Token || "";
}
// 获取当前激活网站的用户UID
public static getCurrentUserUid(): string {
const activeSite = getActiveSite();
if (activeSite?.User?.uid) return activeSite.User.uid;
// 降级:从第一个网站获取
const sites = getSites();
return sites[0]?.User?.uid || "";
}
private static getHeaders() {
return {
"Content-Type": "application/json",
token: this.getCurrentToken(),
Origin: this.getCurrentHost(),
};
}
private static getHost() {
return this.getCurrentHost();
}
/**
* 发起 GET 请求
*
* @param silent 为 true 时失败不弹提示,用于可有可无的辅助查询
*/
public static async get(
url: string,
headers?: Record<string, string>,
silent = false
): Promise<ResponseType> {
return this.request("GET", url, undefined, headers, silent);
}
/**
* 发起 POST 请求
*/
public static async post(
url: string,
body: any,
headers?: Record<string, string>
): Promise<ResponseType> {
return this.request("POST", url, body, headers);
}
/**
* 发起通用 HTTP 请求
*/
private static async request(
method: string,
url: string,
body?: any,
headers?: Record<string, string>,
silent = false
): Promise<ResponseType> {
headers = {
...this.getHeaders(),
...headers,
};
const shouldHaveBody = !["GET", "HEAD", "DELETE"].includes(
method.toUpperCase()
);
const requestOptions = {
method: method,
url: this.getHost() + url,
headers: headers || {},
};
// 只有需要时才添加 body
if (shouldHaveBody && body !== undefined && body !== null) {
(requestOptions as any).body =
typeof body === "string" ? body : JSON.stringify(body);
if (!headers?.["Content-Type"]) {
requestOptions.headers = {
...requestOptions.headers,
"Content-Type": "application/json",
};
}
}
try {
const response: RequestUrlResponse = await requestUrl(
requestOptions
);
// 正常接口一定回 JSON。返回 HTML 一般是 URL 落到了主题页或错误页
// (插件没启用、新接口没注册、Host 没填到 /index.php/api),
// 直接把 "<pre><code>" 丢给 JSON.parse 只会得到看不懂的语法错误
if (!this.looksLikeJson(response)) {
throw new Error(this.describeNonJson(response, url));
}
const res: ResponseType = response.json;
if (res.status === "success") {
return res;
} else {
if (!silent) new Notice(res.message);
// 标记「提示已经弹过」:本方法末尾的 catch 与调用方都不再重复弹,
// 否则一次失败会连出两三条提示,用户根本看不清哪句是真的原因
const apiError: any = new Error(
`HTTP Error: - ${response.json.message}`
);
apiError.__notified = !silent;
throw apiError;
}
} catch (error) {
console.error(`Request failed: ${url}`, error);
if (!silent && !(error as any)?.__notified) {
new Notice(this.messageOf(error, url));
if (error && typeof error === "object") {
(error as any).__notified = true;
}
}
throw error;
}
}
/**
* 统一错误提示
*
* request() 失败时已经弹过最具体的那条原因(HTTP 状态 + 服务器原文),
* 并在错误对象上打了 __notified 标记。调用方用它兜底,就不会出现
* 「真实原因」和「请求失败」两条提示互相覆盖的情况。
*
* @param fallback 拿不到有效信息时退而显示的文案(一般是「XX 失败」)
*/
public static notifyError(error: any, fallback = "") {
if (error && typeof error === "object" && (error as any).__notified) {
return;
}
const detail = this.messageOf(error);
const message = detail && detail !== "undefined" ? detail : fallback;
if (message) new Notice(message);
if (error && typeof error === "object") {
(error as any).__notified = true;
}
}
private static looksLikeJson(response: RequestUrlResponse): boolean {
const contentType = String(
response.headers?.["content-type"] || ""
).toLowerCase();
if (contentType.includes("json")) return true;
const body = String(response.text || "").trimStart();
return body.startsWith("{") || body.startsWith("[");
}
/** 把 HTML 错误页压成一句话,方便直接弹给用户看 */
private static describeNonJson(
response: { status?: number; text?: string },
path?: string
): string {
const raw = String(response.text || "");
const shortPath = path ? path.split("?")[0] : "";
// Typecho 路由没注册时会直接抛出这一行,是最常见的「接口不存在」
if (/Path\s+'[^']*'\s+not found/i.test(raw)) {
return `该网站没有这个接口${
shortPath ? `(${shortPath})` : ""
}:服务器上的 TypechoToObsidian 插件是旧版本。把最新的 Action.php、Plugin.php 上传到 usr/plugins/TypechoToObsidian/ 后,在后台停用再启用插件即可`;
}
const snippet = raw
.replace(/<script[\s\S]*?<\/script>/gi, " ")
.replace(/<style[\s\S]*?<\/style>/gi, " ")
.replace(/<[^>]+>/g, " ")
.replace(/\s+/g, " ")
.trim()
.slice(0, 100);
const status = response.status ? `HTTP ${response.status}` : "非 JSON";
return `服务器返回的不是 JSON(${status})${
snippet ? ":" + snippet : ""
}。请确认 Host 填到了 /index.php/api,且 Typecho 端插件已重新启用`;
}
private static messageOf(error: any, path?: string): string {
if (typeof error === "string") return error;
// requestUrl 遇到 4xx/5xx 会抛出带回包的对象,HTML 错误页也走这里
if (error?.status && error?.text) {
return this.describeNonJson(error, path);
}
return String(error?.message ?? error);
}
}