同步插件源代码并补齐标准项目文件
This commit is contained in:
41
utils/datetime.ts
Normal file
41
utils/datetime.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* 时间格式化
|
||||
*
|
||||
* 以前属性里写的是 `new Date().toISOString()`,也就是
|
||||
* `2026-11-11T06:09:43.465Z` 这种 UTC 串:中国香港 / 北京都在东八区,
|
||||
* 本地时间其实是 14:09,看属性面板会以为时间差了 8 小时。
|
||||
*
|
||||
* 这里固定按 UTC+8 换算,不依赖本机时区——换一台时区不同的电脑、
|
||||
* 或者在服务器上跑,输出都还是北京时间。
|
||||
*/
|
||||
const BEIJING_OFFSET_MS = 8 * 60 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* 把时间转成北京时间的 `YYYY-MM-DD HH:mm:ss`
|
||||
*
|
||||
* @param input Date / 时间戳 / 可解析的时间字符串,默认当前时刻
|
||||
*/
|
||||
export function formatBeijingTime(
|
||||
input: Date | number | string = new Date()
|
||||
): string {
|
||||
const date = input instanceof Date ? input : new Date(input);
|
||||
if (Number.isNaN(date.getTime())) return "";
|
||||
|
||||
// 先整体加 8 小时,再用 getUTC* 取值,得到的偏移量只由常量决定
|
||||
const shifted = new Date(date.getTime() + BEIJING_OFFSET_MS);
|
||||
const pad = (value: number) => String(value).padStart(2, "0");
|
||||
|
||||
const ymd = [
|
||||
shifted.getUTCFullYear(),
|
||||
pad(shifted.getUTCMonth() + 1),
|
||||
pad(shifted.getUTCDate()),
|
||||
].join("-");
|
||||
|
||||
const hms = [
|
||||
pad(shifted.getUTCHours()),
|
||||
pad(shifted.getUTCMinutes()),
|
||||
pad(shifted.getUTCSeconds()),
|
||||
].join(":");
|
||||
|
||||
return `${ymd} ${hms}`;
|
||||
}
|
||||
366
utils/frontmatter.ts
Normal file
366
utils/frontmatter.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;
|
||||
247
utils/post_import.ts
Normal file
247
utils/post_import.ts
Normal file
@@ -0,0 +1,247 @@
|
||||
import { App, Notice, TFile, normalizePath } from "obsidian";
|
||||
import { HttpUtils } from "./request";
|
||||
import { getActiveSite, getSettings } from "../main";
|
||||
import i18n from "./i18n";
|
||||
import { FM_KEYS } from "./frontmatter";
|
||||
import { formatBeijingTime } from "./datetime";
|
||||
|
||||
/** 文件名里不允许出现的字符 */
|
||||
const INVALID_FILE_CHARS = /[\\/:*?"<>|#^[\]]/g;
|
||||
|
||||
/**
|
||||
* 把标题转成合法的文件名
|
||||
*/
|
||||
export function sanitizeFileName(name: string): string {
|
||||
const cleaned = (name || "")
|
||||
.replace(INVALID_FILE_CHARS, "-")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.slice(0, 100);
|
||||
return cleaned || "untitled";
|
||||
}
|
||||
|
||||
/**
|
||||
* 目录名净化:和文件名同一套规则,另外去掉首尾的点和空格
|
||||
*/
|
||||
function sanitizeFolderName(name: string): string {
|
||||
return (name || "")
|
||||
.replace(INVALID_FILE_CHARS, "-")
|
||||
.replace(/\s+/g, " ")
|
||||
.replace(/^[.\s]+|[.\s]+$/g, "")
|
||||
.trim()
|
||||
.slice(0, 60);
|
||||
}
|
||||
|
||||
/**
|
||||
* 本次下载 / 新建使用的基础目录:站点自己配置的导入目录
|
||||
*
|
||||
* 站点没单独配置时回退到旧版全局目录,再回退到 Typecho。
|
||||
*/
|
||||
export function resolveImportFolder(
|
||||
site: { importFolder?: string } | undefined = getActiveSite(),
|
||||
categorySegment?: string
|
||||
): string {
|
||||
const base = (site?.importFolder || getSettings()?.importFolder || "Typecho")
|
||||
.replace(/\\/g, "/")
|
||||
.replace(/^\/+|\/+$/g, "");
|
||||
|
||||
const sub = sanitizeFolderName(categorySegment || "");
|
||||
return [base, sub].filter(Boolean).join("/");
|
||||
}
|
||||
|
||||
/**
|
||||
* 文章在本地所属的分类目录名
|
||||
*
|
||||
* 取文章的分类 slug;一篇文章挂多个分类时固定取 mid 最小的那个,
|
||||
* 保证同一个分类的文章每次都落在同一个目录,不会因为接口返回顺序变化而漂移。
|
||||
* 没有分类(或分类没有 slug)时退回分类名,两者都没有就落在站点目录根下。
|
||||
*/
|
||||
export function categoryFolderOf(post: any): string {
|
||||
const categories: any[] = Array.isArray(post?.categories)
|
||||
? [...post.categories]
|
||||
: Array.isArray(post?.categorySlugs)
|
||||
? post.categorySlugs.map((slug: string) => ({ slug }))
|
||||
: [];
|
||||
|
||||
categories.sort(
|
||||
(a, b) => Number(a?.mid ?? 0) - Number(b?.mid ?? 0)
|
||||
);
|
||||
|
||||
const first = categories[0];
|
||||
const raw = first?.slug
|
||||
? String(first.slug)
|
||||
: first?.name
|
||||
? String(first.name)
|
||||
: String(post?.categoryNames?.[0] ?? "");
|
||||
|
||||
return sanitizeFolderName(raw);
|
||||
}
|
||||
|
||||
/**
|
||||
* YAML 标量:遇到容易歧义的字符就加双引号
|
||||
*/
|
||||
function yamlScalar(value: string): string {
|
||||
if (value === "") return '""';
|
||||
if (
|
||||
/[:#\[\]{}&*!|>'"%@`,]/.test(value) ||
|
||||
/^\s|\s$/.test(value) ||
|
||||
/^(true|false|null|~)$/i.test(value) ||
|
||||
/^-?\d+(\.\d+)?$/.test(value)
|
||||
) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 行内数组,和插件发布时写回的风格保持一致
|
||||
*/
|
||||
function yamlList(values: string[]): string {
|
||||
if (!values || values.length === 0) return "[]";
|
||||
return `[${values.map((v) => yamlScalar(String(v))).join(", ")}]`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐级创建目录
|
||||
*/
|
||||
async function ensureFolder(app: App, folder: string): Promise<void> {
|
||||
if (!folder) return;
|
||||
const parts = folder.split("/");
|
||||
let current = "";
|
||||
for (const part of parts) {
|
||||
current = current ? `${current}/${part}` : part;
|
||||
if (!app.vault.getAbstractFileByPath(current)) {
|
||||
try {
|
||||
await app.vault.createFolder(current);
|
||||
} catch (error) {
|
||||
// 并发创建时可能已存在,忽略
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 组装本地笔记内容:属性 + 正文
|
||||
*/
|
||||
function buildContent(post: any, title: string): string {
|
||||
const lines: string[] = ["---"];
|
||||
lines.push(`title: ${yamlScalar(title)}`);
|
||||
lines.push(`${FM_KEYS.cid}: ${Number(post.cid)}`);
|
||||
if (post.slug) {
|
||||
lines.push(`${FM_KEYS.slug}: ${yamlScalar(String(post.slug))}`);
|
||||
}
|
||||
lines.push(`${FM_KEYS.title}: ${yamlScalar(title)}`);
|
||||
lines.push(`${FM_KEYS.categories}: ${yamlList(post.categoryNames || [])}`);
|
||||
lines.push(`${FM_KEYS.tags}: ${yamlList(post.tagNames || [])}`);
|
||||
if (post.permalink) {
|
||||
lines.push(`${FM_KEYS.url}: ${yamlScalar(String(post.permalink))}`);
|
||||
}
|
||||
|
||||
// 发布时间取接口给的 created(Unix 秒),排在更新时间上面;
|
||||
// 老文章没有这个字段时就只写更新时间
|
||||
const created = Number(post.created);
|
||||
if (Number.isFinite(created) && created > 0) {
|
||||
lines.push(
|
||||
`${FM_KEYS.created}: ${formatBeijingTime(created * 1000)}`
|
||||
);
|
||||
}
|
||||
|
||||
lines.push(`${FM_KEYS.updated}: ${formatBeijingTime()}`);
|
||||
lines.push("---");
|
||||
lines.push("");
|
||||
|
||||
const body = post.markdown ?? post.text ?? "";
|
||||
lines.push(String(body));
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* 新建一篇空笔记并打开,用于在本地起草新文章
|
||||
*
|
||||
* 草稿还没有分类,先落在站点导入目录的根下;
|
||||
* 发布时选了分类,正文和属性写回线上即可。
|
||||
* 同名文件已存在时自动追加序号,不会覆盖。
|
||||
*/
|
||||
export async function createPostDraft(app: App): Promise<TFile | null> {
|
||||
const rawFolder = resolveImportFolder();
|
||||
|
||||
try {
|
||||
await ensureFolder(app, rawFolder);
|
||||
|
||||
const baseName = i18n.t("manager.draftName");
|
||||
let path = "";
|
||||
let index = 0;
|
||||
|
||||
do {
|
||||
const fileName =
|
||||
index === 0 ? `${baseName}.md` : `${baseName} ${index}.md`;
|
||||
path = normalizePath(
|
||||
rawFolder ? `${rawFolder}/${fileName}` : fileName
|
||||
);
|
||||
index++;
|
||||
} while (app.vault.getAbstractFileByPath(path) && index < 1000);
|
||||
|
||||
const file = await app.vault.create(path, "");
|
||||
await app.workspace.getLeaf(true).openFile(file);
|
||||
new Notice(i18n.t("manager.draftCreated", { name: file.path }));
|
||||
|
||||
return file;
|
||||
} catch (error) {
|
||||
console.error("新建笔记失败", error);
|
||||
// 失败原因多半是目录无写权限或路径非法,把真实原因带出来才查得动
|
||||
const detail = (error as any)?.message;
|
||||
new Notice(
|
||||
detail
|
||||
? `${i18n.t("common.errorOccurred")}:${detail}`
|
||||
: i18n.t("common.errorOccurred")
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把线上文章下载成本地 Markdown 并打开编辑
|
||||
*
|
||||
* 存放位置:<站点导入目录>/<分类 slug>/<文章标题>.md
|
||||
* 没有分类的文章直接放在 <站点导入目录> 下。
|
||||
* 同目录下已有同名笔记时不会覆盖,直接打开已有文件。
|
||||
*/
|
||||
export async function importPostAsMarkdown(
|
||||
app: App,
|
||||
cid: number
|
||||
): Promise<TFile | null> {
|
||||
if (!cid || Number.isNaN(cid)) {
|
||||
new Notice(i18n.t("error.failedToFetchPostDetails"));
|
||||
return null;
|
||||
}
|
||||
|
||||
const response = await HttpUtils.get(`/postDetail?cid=${cid}`);
|
||||
const post = response?.data;
|
||||
if (!post) {
|
||||
new Notice(i18n.t("error.failedToFetchPostDetails"));
|
||||
return null;
|
||||
}
|
||||
|
||||
const title = String(post.title || i18n.t("manager.untitled"));
|
||||
// 分类 slug 作为二级目录,和线上分类结构对齐
|
||||
const rawFolder = resolveImportFolder(undefined, categoryFolderOf(post));
|
||||
|
||||
await ensureFolder(app, rawFolder);
|
||||
|
||||
const fileName = `${sanitizeFileName(title)}.md`;
|
||||
const path = normalizePath(rawFolder ? `${rawFolder}/${fileName}` : fileName);
|
||||
|
||||
const existing = app.vault.getAbstractFileByPath(path);
|
||||
if (existing instanceof TFile) {
|
||||
new Notice(i18n.t("manager.alreadyExists", { name: existing.path }));
|
||||
await app.workspace.getLeaf(true).openFile(existing);
|
||||
return existing;
|
||||
}
|
||||
|
||||
const file = await app.vault.create(path, buildContent(post, title));
|
||||
await app.workspace.getLeaf(true).openFile(file);
|
||||
new Notice(i18n.t("manager.imported", { name: file.path }));
|
||||
|
||||
return file;
|
||||
}
|
||||
223
utils/request.ts
Normal file
223
utils/request.ts
Normal file
@@ -0,0 +1,223 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
5
utils/response_type.ts
Normal file
5
utils/response_type.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export interface ResponseType {
|
||||
status: string;
|
||||
message: string;
|
||||
data: any;
|
||||
}
|
||||
276
utils/util.ts
Normal file
276
utils/util.ts
Normal file
@@ -0,0 +1,276 @@
|
||||
import { getSettings } from "main";
|
||||
import { Notice, Editor, TFolder, App } from "obsidian";
|
||||
import { HttpUtils } from "./request";
|
||||
import i18n from "./i18n";
|
||||
|
||||
// 定义树节点接口
|
||||
export interface TreeNode {
|
||||
id?: number;
|
||||
[key: string]: any;
|
||||
children: TreeNode[];
|
||||
parent?: TreeNode;
|
||||
}
|
||||
|
||||
export const Util = {
|
||||
// tree
|
||||
treeUtil: {
|
||||
generateTreeData: function <T extends Record<string, any>>(
|
||||
data: T[],
|
||||
nodeId: keyof T,
|
||||
parentNodeKey: keyof T
|
||||
): TreeNode[] {
|
||||
// 将数据存储为以 nodeId 为 KEY 的 map 索引数据列
|
||||
const map: Record<string | number, TreeNode> = {};
|
||||
data.forEach((item) => {
|
||||
(item as unknown as TreeNode).children = [];
|
||||
map[item[nodeId] as string | number] =
|
||||
item as unknown as TreeNode;
|
||||
});
|
||||
|
||||
// 遍历数据,构建树形结构
|
||||
const rootNodes: TreeNode[] = [];
|
||||
data.forEach((item) => {
|
||||
const parent = map[item[parentNodeKey] as string | number];
|
||||
if (parent) {
|
||||
parent.children.push(item as unknown as TreeNode);
|
||||
(item as unknown as TreeNode).parent = parent;
|
||||
} else {
|
||||
rootNodes.push(item as unknown as TreeNode);
|
||||
}
|
||||
});
|
||||
|
||||
return rootNodes;
|
||||
},
|
||||
// 在树形结构中查找指定id节点
|
||||
findNodeInTree: function (
|
||||
tree: TreeNode[],
|
||||
id: number
|
||||
): TreeNode | undefined {
|
||||
for (let i = 0; i < tree.length; i++) {
|
||||
if (tree[i].id === id) {
|
||||
return tree[i];
|
||||
} else {
|
||||
if (tree[i].children) {
|
||||
const node = this.findNodeInTree(tree[i].children, id);
|
||||
if (node) {
|
||||
return node;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
// 在树形结构中查找指定id节点的上一个父节点
|
||||
findParentNodeInTree: function (
|
||||
tree: TreeNode[],
|
||||
id: number
|
||||
): TreeNode | null {
|
||||
// Id等于0的节点为根节点,没有父节点
|
||||
// id找到了的话,往上找一层父节点返回
|
||||
if (id === 0) {
|
||||
return null;
|
||||
}
|
||||
for (let i = 0; i < tree.length; i++) {
|
||||
if (tree[i].id === id) {
|
||||
return tree[i].parent || null;
|
||||
} else {
|
||||
if (tree[i].children) {
|
||||
const node = this.findParentNodeInTree(
|
||||
tree[i].children,
|
||||
id
|
||||
);
|
||||
if (node) {
|
||||
return node;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
},
|
||||
hash: {
|
||||
simpleHash(str: string) {
|
||||
let hash = 0;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const char = str.charCodeAt(i);
|
||||
hash = (hash << 5) - hash + char;
|
||||
hash |= 0; // Convert to 32bit integer
|
||||
}
|
||||
// 转成16进制并取最后6位
|
||||
return (hash >>> 0).toString(16).padStart(8, "0").slice(-6);
|
||||
},
|
||||
},
|
||||
file: {
|
||||
// 将file转换成Uint8Array
|
||||
async fileToUint8Array(file: File | Blob) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const arrayBuffer = reader.result as ArrayBuffer;
|
||||
resolve(new Uint8Array(arrayBuffer));
|
||||
};
|
||||
reader.onerror = reject;
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
},
|
||||
},
|
||||
url: {
|
||||
extractDomain(url: string) {
|
||||
const domain = url.match(/https?:\/\/(www\.)?([^\s/]+)/);
|
||||
if (domain) {
|
||||
return domain[0];
|
||||
}
|
||||
return "";
|
||||
},
|
||||
},
|
||||
upload: {
|
||||
async handleImagePaste(
|
||||
app: App,
|
||||
editor: Editor,
|
||||
clipboardData: DataTransfer
|
||||
): Promise<boolean> {
|
||||
if (!getSettings().enablePasteUpload) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const items = Array.from(clipboardData.items || []);
|
||||
const imageItem = items.find((item) =>
|
||||
item.type.startsWith("image/")
|
||||
);
|
||||
if (!imageItem) return false;
|
||||
|
||||
console.log("📥 Detected image paste, handling...", imageItem.type);
|
||||
|
||||
try {
|
||||
const blob = imageItem.getAsFile();
|
||||
if (!blob) return false;
|
||||
|
||||
const ext =
|
||||
blob.type.split("/")[1]?.replace(/;.*/, "") || "png";
|
||||
const fileName = `paste-${Date.now()}.${ext}`; // 👈 记住这个 fileName
|
||||
|
||||
const notice = new Notice(
|
||||
i18n.t("notice.imageUploading", { fileName }),
|
||||
0
|
||||
);
|
||||
|
||||
const buffer = await Util.file.fileToUint8Array(blob);
|
||||
|
||||
const response = await HttpUtils.post(
|
||||
"/upload?authorId=" + HttpUtils.getCurrentUserUid(),
|
||||
{
|
||||
file: buffer,
|
||||
fileName: fileName,
|
||||
}
|
||||
);
|
||||
|
||||
notice.hide();
|
||||
|
||||
if (!response?.data?.url) {
|
||||
new Notice(i18n.t("notice.imageUploadFailed"), 3000);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ✅ 新增:删除 Obsidian 原生粘贴产生的 ![[fileName]] 或 
|
||||
try {
|
||||
const cursor = editor.getCursor();
|
||||
const line = editor.getLine(cursor.line);
|
||||
// 构造可能的原生粘贴内容(Obsidian 偏好双括号)
|
||||
const nativeEmbed1 = `![[${blob.name}]]`;
|
||||
const nativeEmbed2 = ``;
|
||||
const nativeEmbed3 = ``; // 少数情况
|
||||
|
||||
// 从光标位置往前找(原生粘贴通常在当前光标处插入)
|
||||
const startPos = Math.max(
|
||||
0,
|
||||
cursor.ch - nativeEmbed1.length - 20
|
||||
);
|
||||
const segment = line.substring(startPos, cursor.ch + 20);
|
||||
|
||||
let toDelete = null;
|
||||
if (segment.includes(nativeEmbed1)) {
|
||||
toDelete = nativeEmbed1;
|
||||
} else if (segment.includes(nativeEmbed2)) {
|
||||
toDelete = nativeEmbed2;
|
||||
} else if (segment.includes(nativeEmbed3)) {
|
||||
toDelete = nativeEmbed3;
|
||||
}
|
||||
|
||||
if (toDelete) {
|
||||
// 找到匹配项,计算其在行内的位置
|
||||
const idx = line.indexOf(toDelete, startPos);
|
||||
if (idx !== -1) {
|
||||
editor.replaceRange(
|
||||
"",
|
||||
{ line: cursor.line, ch: idx },
|
||||
{ line: cursor.line, ch: idx + toDelete.length }
|
||||
);
|
||||
// 修正光标位置(恢复到删除后的位置)
|
||||
editor.setCursor({ line: cursor.line, ch: idx });
|
||||
console.log(`🧹 已删除原生粘贴占位符: ${toDelete}`);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn(
|
||||
"Failed to remove native paste placeholder:",
|
||||
e
|
||||
);
|
||||
// 不中断主流程
|
||||
}
|
||||
|
||||
const domain = Util.url.extractDomain(HttpUtils.getCurrentHost());
|
||||
const imageUrl =
|
||||
(domain.endsWith("/") ? domain : domain + "/") +
|
||||
response.data.url;
|
||||
|
||||
const markdownImage = ``;
|
||||
editor.replaceSelection(markdownImage);
|
||||
|
||||
// 上传成功后,检查并删除当前目录下的同名本地文件
|
||||
try {
|
||||
const activeFile = app.workspace.getActiveFile();
|
||||
if (activeFile) {
|
||||
const parentDir = app.vault.getAbstractFileByPath(
|
||||
activeFile.parent?.path || "/"
|
||||
);
|
||||
|
||||
if (parentDir && parentDir instanceof TFolder) {
|
||||
const attachmentPath =
|
||||
(app.vault as any).config
|
||||
?.attachmentFolderPath || "";
|
||||
let delFilepath = blob.name;
|
||||
if (attachmentPath) {
|
||||
delFilepath = attachmentPath + "/" + blob.name;
|
||||
delFilepath = delFilepath.substring(1);
|
||||
}
|
||||
console.log(delFilepath);
|
||||
let existingFile =
|
||||
app.vault.getAbstractFileByPath(delFilepath);
|
||||
console.log(existingFile);
|
||||
if (existingFile) {
|
||||
await app.vault.delete(existingFile);
|
||||
console.log(
|
||||
`🗑️ 已删除本地重复文件: ${delFilepath}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (delErr) {
|
||||
console.warn(
|
||||
"Cleanup local duplicate file failed:",
|
||||
delErr
|
||||
);
|
||||
// 不中断主流程,静默失败
|
||||
}
|
||||
|
||||
new Notice(i18n.t("notice.imageUploaded"), 2000);
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.error("Paste image upload failed:", err);
|
||||
// 上传失败的具体原因 HttpUtils 已经弹过,别再盖一条笼统的
|
||||
HttpUtils.notifyError(err, i18n.t("notice.pasteUploadFailed"));
|
||||
return true;
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user