Skip to content

Instantly share code, notes, and snippets.

@selfire1
Last active October 7, 2023 06:15
Show Gist options
  • Save selfire1/3b73e1e981ae37b14977660f753e2263 to your computer and use it in GitHub Desktop.
Save selfire1/3b73e1e981ae37b14977660f753e2263 to your computer and use it in GitHub Desktop.
To be run in the Obsidian Templater Plugin to update query files and permalinks. To be saved as a `.md` file.
<%*
const dv = app.plugins.plugins["dataview"].api;
const openPublishPanel = app.commands.commands["publish:view-changes"].callback;
// ----------------------
// Update query files
// ----------------------
const updateQueryFiles = async () => {
const fileAndQuery = new Map([
[
"Books Read (Auto-Updating)",
[
'TABLE WITHOUT ID "![thumb|80](" + thumbnail + ")" AS Cover, file.link AS Title, file.tags[0] AS Type FROM #book WHERE publish and read SORT read desc',
"dn7aBKbWWW931tT8DQSvRu",
],
],
[
"Currently Reading (Auto-Updating)",
[
'TABLE WITHOUT ID "![thumb|60](" + thumbnail + ")" AS Cover, file.link AS Title FROM #currently-reading WHERE publish AND status = "currently-reading" SORT started desc',
"rEcyrvGqKjvf4D7dB3ketR",
],
],
[
"Recently read",
[
'TABLE WITHOUT ID "![thumb|50](" + thumbnail + ")" AS Cover, file.link AS Title, dateformat(read, "DD") AS Read, file.tags[0] AS Type FROM #book WHERE publish and read SORT read desc LIMIT 5',
"uktgERNWudD3eZ4fcwdUry",
],
],
[
"Recently edited",
[
'TABLE WITHOUT ID file.link AS Note, dateformat(file.mtime, "ff") AS Modified FROM "50 Slipbox" OR "30 External" WHERE publish SORT file.mtime desc LIMIT 7',
"oskqEgv91u4hJnQBUfx2u4",
],
],
[
"Recent new files",
[
'TABLE WITHOUT ID file.link AS Note, dateformat(file.ctime, "DD") AS Added FROM "50 Slipbox" OR "30 External" WHERE publish SORT file.ctime desc LIMIT 7',
"4domq73qZGB6ySfhcoZXhr",
],
],
]);
let filesUpdatedCounter = 0;
await fileAndQuery.forEach(async (content, filename) => {
const query = content[0];
const uuid = content[1];
if (!tp.file.find_tfile(filename)) {
await tp.file.create_new("", filename);
new Notice(`Created ${filename}.`);
}
const tFile = tp.file.find_tfile(filename);
const queryOutput = await dv.queryMarkdown(query);
const currentContent = await app.vault.read(tFile);
const newContent = `---\npublish: true\npermalink: ${uuid}\n---\n%% update via "Pre-Publish Hook" template %% \n\n${queryOutput.value}`;
if (currentContent === newContent) {
console.log("🔎 No new content for " + tFile.basename);
return;
}
try {
await app.vault.modify(tFile, newContent);
new Notice(`🔎 Updated query file "${tFile.basename}".`);
} catch (error) {
new Notice(
"⚠️ ERROR updating! Check console. Skipped file: " + filename,
0
);
}
filesUpdatedCounter++;
});
if (!filesUpdatedCounter) {
new Notice("No update to query files");
return;
}
};
// ----------------------
// Update permalinks
// ----------------------
const writePermalinks = async () => {
// Get all notes through dataview
const notes = dv.pages();
// Filter to get all pages that have `publish: true` in the frontmatter and no `permalink` frontmatter field
const publishedNotesWithoutPermalink = notes.values.filter(
(el) => el.file.frontmatter?.publish && !el.file.frontmatter?.permalink
);
if (!publishedNotesWithoutPermalink?.length) {
new Notice("No notes to permalink found");
return;
}
// Create an array of paths
const paths = publishedNotesWithoutPermalink.map((note) => note.file.path);
// Get the tFile object for each note
const tFiles = paths.map((el) => app.vault.getAbstractFileByPath(el));
// Get a short uuid for each note
const response = await (
await fetch(`https://uuid.rocks/json/bulk/?short&count=${tFiles.length}`)
).json();
const uuids = response.uuids;
// Loop through each note
await tFiles.forEach(async (tFile, index) => {
const find = "publish: true";
// instead of a the api call above, you could also use the built-in browser method:
// const uuid = crypto.randomUUID()
const uuid = uuids[index]; // Get the uuid from the uuids array
const insert = `\npermalink: ${uuid}`;
const content = await app.vault.read(tFile);
const contentInserted = content.replace(find, `${find}${insert}`);
await app.vault.modify(tFile, contentInserted);
console.log(`🔗 Added permalink ${uuid} in "${tFile.basename}"`);
});
new Notice(
`🔗 Added ${tFiles.length} permalink${tFiles.length > 1 ? "s" : ""}`
);
};
await writePermalinks();
await updateQueryFiles();
openPublishPanel();
%>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment