Auto-migrate old drawing blocks on startup

This commit is contained in:
MassiveBox 2025-04-05 21:58:19 +02:00
parent 4555ec275f
commit d8cc4f8caf
Signed by: massivebox
GPG key ID: 9B74D3A59181947D
3 changed files with 54 additions and 0 deletions

View file

@ -11,8 +11,10 @@ function toFile(title: string, content: string, mimeType: string){
export async function uploadAsset(fileID: string, mimeType: string, content: string) {
const file = toFile(fileID + ".svg", content, mimeType);
console.log(1, file)
let r = await upload('/' + ASSETS_PATH, [file]);
console.log(2, r)
if(r.errFiles) {
throw new Error("Failed to upload file");
}

View file

@ -7,6 +7,7 @@ import {
imgSrcToIDs, generateTimeString, generateRandomString
} from "@/helper";
import {editorTabInit, openEditorTab} from "@/editorTab";
import {migrate} from "@/migration";
export default class DrawJSPlugin extends Plugin {
@ -17,6 +18,7 @@ export default class DrawJSPlugin extends Plugin {
'type': "whiteboard",
init() { editorTabInit(this) }
});
migrate()
this.protyleSlash = [{
id: "insert-drawing",

50
src/migration.ts Normal file
View file

@ -0,0 +1,50 @@
import {sql} from "@/api";
import {getFile, uploadAsset} from "@/file";
import {ASSETS_PATH, DATA_PATH, SVG_MIME} from "@/const";
import {replaceBlockContent} from "@/protyle";
import {generateRandomString, getMarkdownBlock} from "@/helper";
export async function migrate() {
let blocks = await findEmbedBlocks();
console.log(blocks);
const found = blocks.length > 0;
for(const block of blocks) {
const oldFileID = extractID(block.markdown);
if(oldFileID) {
const newFileID = generateRandomString() + "-" + oldFileID;
const file = await getFile(DATA_PATH + ASSETS_PATH + oldFileID + ".svg");
console.log("file", file)
const r = await uploadAsset(newFileID, SVG_MIME, file);
console.log("r", r);
const newMarkdown = getMarkdownBlock(r.fileID, r.syncID);
await replaceBlockContent(block.id, block.markdown, newMarkdown);
}
}
}
function extractID(html: string): string | null {
// Match the pattern: id= followed by characters until & or quote
const regex = /id=([^&"']+)/;
const match = html.match(regex);
return match ? match[1] : null;
}
async function findEmbedBlocks() {
const sqlQuery = `
SELECT id, markdown
FROM blocks
WHERE markdown like '%src="/plugins/siyuan-jsdraw-plugin/webapp/%'
`;
try {
return await sql(sqlQuery);
} catch (error) {
console.error('Error searching for embed blocks:', error);
return [];
}
}