78 lines
2.3 KiB
JavaScript
78 lines
2.3 KiB
JavaScript
module.exports = async (params) => {
|
|
const { app, obsidian, quickAddApi } = params;
|
|
|
|
// 获取当前选中的文件或让用户选择图片文件
|
|
const activeFile = app.workspace.getActiveFile();
|
|
if (
|
|
!activeFile ||
|
|
!activeFile.extension.match(/(png|jpg|jpeg|gif|webp|svg)/i)
|
|
) {
|
|
new obsidian.Notice("请先选择一个图片文件");
|
|
return;
|
|
}
|
|
|
|
// 生成UUID
|
|
const uuid = crypto.randomUUID();
|
|
const newFileName = `${uuid}.${activeFile.extension}`;
|
|
const newPath = activeFile.path.replace(activeFile.name, newFileName);
|
|
|
|
// 获取所有引用该文件的笔记
|
|
const backlinks = app.metadataCache.getBacklinksForFile(activeFile);
|
|
|
|
console.log("引用文件的列表:");
|
|
for (const [file, links] of backlinks.data) {
|
|
console.log(`- ${file}: ${links.length} 个引用`);
|
|
for (const link of links) {
|
|
console.log(` ${link.link}`);
|
|
}
|
|
}
|
|
|
|
// 确认操作
|
|
const confirm = await quickAddApi.yesNoPrompt(
|
|
"确认重命名",
|
|
`将 ${activeFile.name} 重命名为 ${newFileName}\n` +
|
|
`将更新 ${backlinks.data.size} 个文件中的引用`,
|
|
);
|
|
|
|
if (!confirm) return;
|
|
|
|
try {
|
|
// 重命名文件
|
|
await app.fileManager.renameFile(activeFile, newPath);
|
|
|
|
// 更新所有引用
|
|
let updatedCount = 0;
|
|
for (const [file, links] of backlinks.data) {
|
|
const fileObj = app.vault.getAbstractFileByPath(file);
|
|
if (fileObj instanceof obsidian.TFile) {
|
|
let content = await app.vault.read(fileObj);
|
|
|
|
// 更新所有链接引用
|
|
for (const link of links) {
|
|
const oldLink = `[[${activeFile.path}]]`;
|
|
const newLink = `[[${newPath}]]`;
|
|
const oldEmbed = `![[${activeFile.path}]]`;
|
|
const newEmbed = `![[${newPath}]]`;
|
|
|
|
content = content.replace(
|
|
new RegExp(oldLink.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"),
|
|
newLink,
|
|
);
|
|
content = content.replace(
|
|
new RegExp(oldEmbed.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"),
|
|
newEmbed,
|
|
);
|
|
}
|
|
|
|
await app.vault.modify(fileObj, content);
|
|
updatedCount++;
|
|
}
|
|
}
|
|
|
|
new obsidian.Notice(`成功重命名并更新了 ${updatedCount} 个文件`);
|
|
} catch (error) {
|
|
console.error("重命名失败:", error);
|
|
new obsidian.Notice("重命名失败: " + error.message);
|
|
}
|
|
};
|