1
0
silverbullet/plugs/core/cloud.ts

84 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-09-12 12:50:37 +00:00
import type {
FileData,
FileEncoding,
} from "../../common/spaces/space_primitives.ts";
2022-10-14 13:11:33 +00:00
import { renderToText, replaceNodesMatching } from "$sb/lib/tree.ts";
import type { FileMeta } from "../../common/types.ts";
2022-10-14 13:11:33 +00:00
import { parseMarkdown } from "$sb/silverbullet-syscall/markdown.ts";
2022-10-21 14:56:46 +00:00
import { base64EncodedDataUrl } from "../../plugos/asset_bundle/base64.ts";
const pagePrefix = "💭 ";
2022-09-12 12:50:37 +00:00
export async function readFileCloud(
name: string,
2022-10-21 14:56:46 +00:00
encoding: FileEncoding,
2022-09-12 12:50:37 +00:00
): Promise<{ data: FileData; meta: FileMeta } | undefined> {
2022-10-15 17:02:56 +00:00
const originalUrl = name.substring(
2022-09-12 12:50:37 +00:00
pagePrefix.length,
name.length - ".md".length,
2022-09-12 12:50:37 +00:00
);
let url = originalUrl;
if (!url.includes("/")) {
url += "/index";
}
if (!url.startsWith("127.0.0.1")) {
url = `https://${url}`;
} else {
url = `http://${url}`;
}
let text = "";
try {
2022-10-15 17:02:56 +00:00
const r = await fetch(`${url}.md`);
text = await r.text();
if (r.status !== 200) {
text = `ERROR: ${text}`;
}
} catch (e: any) {
console.error("ERROR", e.message);
text = e.message;
}
2022-10-21 14:56:46 +00:00
text = await translateLinksWithPrefix(
text,
`${pagePrefix}${originalUrl.split("/")[0]}/`,
);
return {
2022-10-21 14:56:46 +00:00
data: encoding === "string" ? text : base64EncodedDataUrl(
"text/markdown",
new TextEncoder().encode(text),
),
meta: {
name,
2022-09-12 12:50:37 +00:00
contentType: "text/markdown",
lastModified: 0,
2022-09-12 12:50:37 +00:00
size: text.length,
perm: "ro",
},
};
}
async function translateLinksWithPrefix(
text: string,
prefix: string,
): Promise<string> {
2022-10-14 13:11:33 +00:00
const tree = await parseMarkdown(text);
replaceNodesMatching(tree, (tree) => {
if (tree.type === "WikiLinkPage") {
// Add the prefix in the link text
tree.children![0].text = prefix + tree.children![0].text;
}
return undefined;
});
text = renderToText(tree);
return text;
}
2022-10-14 13:11:33 +00:00
export function getFileMetaCloud(name: string): Promise<FileMeta> {
return Promise.resolve({
name,
2022-09-12 12:50:37 +00:00
size: 0,
contentType: "text/markdown",
lastModified: 0,
perm: "ro",
2022-10-14 13:11:33 +00:00
});
}