| Server IP : 159.69.118.108 / Your IP : 216.73.216.200 Web Server : Apache/2.4.58 (Ubuntu) System : Linux ubuntu-4gb-fsn1-1 6.8.0-90-generic #91-Ubuntu SMP PREEMPT_DYNAMIC Tue Nov 18 13:53:54 UTC 2025 aarch64 User : root ( 0) PHP Version : 8.2.32 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : OFF Directory : /var/www/lauthiamkok.net/contents.lauthiamkok.net/dist/ |
Upload File : |
import http from "http";
import fs, { readFileSync } from "fs";
import chokidar from "chokidar";
import crypto from "crypto";
import rehypeStringify from "rehype-stringify";
import remarkFrontmatter from "remark-frontmatter";
import remarkGfm from "remark-gfm";
import remarkParse from "remark-parse";
import remarkRehype from "remark-rehype";
import { unified } from "unified";
import { read } from "to-vfile";
import { matter } from "vfile-matter";
import rehypeAttrs from "rehype-attr";
import { ObjectId, Timestamp, MongoClient } from "mongodb";
const frontmatterToObject = () => {
return function(tree, file) {
matter(file);
};
};
const markdownToHtml = async (markdown) => {
const result = await unified().use(remarkParse).use(remarkRehype, { allowDangerousHtml: true }).use(rehypeStringify, { allowDangerousHtml: true }).use(rehypeAttrs, { properties: "attr" }).process(markdown);
return String(result);
};
const markdownToObject = async (source) => {
const isHtml = (string) => /<\/?[a-z][\s\S]*>/i.test(string);
const arraySource = source.split("/");
arraySource.pop();
if (source.includes(".txt")) {
source = `${arraySource.join("/")}/index.md`;
}
const result = await unified().use(remarkParse).use(remarkFrontmatter).use(remarkGfm).use(remarkRehype).use(rehypeStringify).use(frontmatterToObject).process(await read(`./${source}`));
const output = result.data.matter;
output.body = result.value;
const id = source.toLowerCase().replace(/\//g, "-");
output.id = id.replace(/ /g, "-");
const uniqueId = crypto.randomUUID();
output.uuid = uniqueId;
const tags = output.tags;
if (tags !== void 0) {
const string = tags.toString();
const toArray = string.split(",");
output.tags = toArray;
}
const last = [...arraySource].pop();
output.slug = last.toLowerCase().replace(/ /g, "-");
output.relativePath = `${arraySource.join("/")}/`;
if (!output.excerpt && output.body) {
const clean = output.body.replace(/\r?\n|\r/g, " ");
const matches = clean.match(/<(\w+)>(.*?)<\/\1>/);
output.excerpt = matches[0];
}
if (output.include !== void 0) {
const filePath = `./${output.relativePath}/${output.include}`;
const string = filePath ? readFileSync(filePath, "utf8") : "";
output.body = await markdownToHtml(string);
}
if (output.excerpt && !isHtml(output.excerpt)) {
output.excerpt = await markdownToHtml(output.excerpt);
}
if (!output.extract && output.body) {
const clean = output.body.replace(/\r?\n|\r/g, " ");
const matches = clean.match(/<(\w+)>(.*?)<\/\1>/);
output.extract = matches[0];
}
if (output.footnotes) {
const footnotes = output.footnotes;
Object.keys(footnotes).forEach(async (key) => {
const footnote = footnotes[key];
if (footnote.body) {
footnote.body = await markdownToHtml(footnote.body);
}
});
}
if (output.carousel) {
const carousel = output.carousel;
if (carousel.body) {
output.carousel.body = await markdownToHtml(carousel.body);
}
if (carousel.attachment && carousel.attachment.body) {
const attachment = carousel.attachment;
carousel.attachment.body = await markdownToHtml(attachment.body);
}
if (carousel.attachments) {
const attachments = carousel.attachments;
Object.keys(attachments).forEach(async (key) => {
const attachment = attachments[key];
if (attachment.body) {
attachment.body = await markdownToHtml(attachment.body);
}
});
}
}
if (output.carousels) {
const carousels = output.carousels;
Object.keys(carousels).forEach(async (key) => {
const carousel = carousels[key];
if (carousel.body) {
carousel.body = await markdownToHtml(carousel.body);
}
if (carousel.attachments) {
const attachments = carousel.attachments;
Object.keys(attachments).forEach(async (key2) => {
const attachment = attachments[key2];
if (attachment.body) {
attachment.body = await markdownToHtml(attachment.body);
}
});
}
});
}
return output;
};
const url = "mongodb://lau:kueHs6tuxhH6qcAUibxcL@localhost:27017/lauthiamkok-mongodb";
const dbName = "lauthiamkok-mongodb";
async function connect() {
const client = new MongoClient(url);
await client.connect();
const db = client.db(dbName);
return { client, db };
}
function close(client) {
client.close();
}
const useMongo = () => {
return {
ObjectId,
Timestamp,
connect,
close
};
};
const dropDatabase = async (slug, collectionName) => {
const { connect: connect2, close: close2 } = useMongo();
const { client, db } = await connect2();
return await db.dropDatabase();
};
const createDocument = async (data, collectionName) => {
const { connect: connect2, close: close2 } = useMongo();
const { client, db } = await connect2();
const collection = db.collection(collectionName);
const found = await collection.findOne({
slug: data.slug
});
if (found) {
console.log(`slug "${data.slug}" has been taken!`);
return;
}
const timestamp = Date.now();
data.createdAt = timestamp;
data.lastModified = timestamp;
const doc = await collection.insertOne(data);
close2(client);
return doc;
};
const updateDocument = async (data, collectionName) => {
const { connect: connect2, close: close2 } = useMongo();
const { client, db } = await connect2();
const collection = db.collection(collectionName);
const found = await collection.findOne({
slug: data.slug
});
if (!found) {
console.log(`slug "${data.slug}" is not found!`);
return;
}
const taken = await collection.findOne({
slug: data.slug,
// https://docs.mongodb.com/manual/reference/operator/query/ne/#op._S_ne
id: { $ne: data.id }
});
if (taken) {
console.log(`slug "${data.slug}" has been taken`);
return;
}
data.lastModified = Date.now();
const doc = await collection.replaceOne({
slug: data.slug
}, data);
close2(client);
return doc;
};
const deleteDocument = async (slug, collectionName) => {
const { connect: connect2, close: close2 } = useMongo();
const { client, db } = await connect2();
const collection = db.collection(collectionName);
const found = await collection.findOne({
slug
});
if (!found) {
console.log(`slug "${slug}" is not found!`);
return;
}
const doc = await collection.deleteOne({
slug
});
close2(client);
return doc;
};
const watch = async () => {
const log = console.log.bind(console);
await dropDatabase();
chokidar.watch(`./contents/`, {
// ignoreInitial: true,
ignored: (path) => [
"draft",
"archive",
".gitignore",
".jpg",
".jpeg",
".png",
".pdf",
".json",
".doc"
].some((x) => path.includes(x)),
// https://github.com/paulmillr/chokidar#performance
awaitWriteFinish: true
// https://github.com/paulmillr/chokidar#errors
// atomic: 5000,
}).on("add", async (path) => {
log(`File "${path}" has been added`);
if (path.includes(".txt")) {
return;
}
const collection = path.split("/")[1];
const data = await markdownToObject(path);
const result = await createDocument(data, collection);
if (result) {
log(`Data of "${path}" has been injected to MongoDB`);
}
}).on("change", async (path) => {
log(`File "${path}" has been changed`);
const collection = path.split("/")[1];
const data = await markdownToObject(path);
const result = await updateDocument(data, collection);
if (result) {
log(`Data of "${path}" has been updated to MongoDB`);
}
}).on("unlink", async (path) => {
log(`File "${path}" has been removed`);
if (path.includes(".txt")) {
return;
}
const arrayPath = path.split("/");
arrayPath.pop();
const collection = arrayPath[1];
const last = [...arrayPath].pop();
const slug = last.toLowerCase().replace(/ /g, "-");
const result = await deleteDocument(slug, collection);
if (result) {
log(`Data of "${path}" has been deleted from MongoDB`);
}
});
};
watch();
const requestListener = (req, res) => {
const url2 = req.url;
res.setHeader("Access-Control-Allow-Origin", "https://lauthiamkok.net");
res.setHeader("Access-Control-Allow-Methods", "GET");
if (url2 === "/") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ "message": "Content HTTP server is ready!" }));
return;
}
fs.readFile(`./${decodeURIComponent(url2)}`, (err, data) => {
if (err) {
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({
message: "File not found or you made an invalid request.",
data: err
}));
return;
}
const days = 365;
const maxAge = days * 24 * 60 * 60;
res.setHeader("Cache-Control", `public, max-age=${maxAge}`);
res.writeHead(200);
res.end(data);
});
};
{
const host = "localhost";
const port = "3000";
const server = http.createServer(requestListener);
server.listen(port, () => {
console.log(`🚀 Server ready at ${host}:${port}`);
});
}
const viteNodeApp = requestListener;
export {
viteNodeApp
};