fuck this shit

This commit is contained in:
rattatwinko
2025-06-17 17:36:13 +02:00
parent a1e4238435
commit 7a90128247
6 changed files with 2951 additions and 906 deletions

View File

@@ -2,19 +2,16 @@ import { NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import { remark } from 'remark';
import html from 'remark-html';
import gfm from 'remark-gfm';
import remarkRehype from 'remark-rehype';
import rehypeRaw from 'rehype-raw';
import rehypeStringify from 'rehype-stringify';
import { marked } from 'marked';
import DOMPurify from 'dompurify';
import { JSDOM } from 'jsdom';
const postsDirectory = path.join(process.cwd(), 'posts');
// Function to get file creation date
function getFileCreationDate(filePath: string): Date {
const stats = fs.statSync(filePath);
return stats.birthtime;
return stats.birthtime ?? stats.mtime;
}
async function getPostBySlug(slug: string) {
@@ -24,12 +21,48 @@ async function getPostBySlug(slug: string) {
const { data, content } = matter(fileContents);
const createdAt = getFileCreationDate(fullPath);
const processedContent = await remark()
.use(gfm)
.use(remarkRehype, { allowDangerousHtml: true })
.use(rehypeRaw)
.use(rehypeStringify)
.process(content);
let processedContent = '';
try {
// Configure marked options
marked.setOptions({
gfm: true,
breaks: true,
headerIds: true,
mangle: false
});
// Convert markdown to HTML
const rawHtml = marked(content);
// Create a DOM window for DOMPurify
const window = new JSDOM('').window;
const purify = DOMPurify(window);
// Sanitize the HTML
processedContent = purify.sanitize(rawHtml, {
ALLOWED_TAGS: [
'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'p', 'a', 'ul', 'ol', 'li', 'blockquote',
'pre', 'code', 'em', 'strong', 'del',
'hr', 'br', 'img', 'table', 'thead', 'tbody',
'tr', 'th', 'td', 'div', 'span', 'iframe'
],
ALLOWED_ATTR: [
'class', 'id', 'style',
'href', 'target', 'rel',
'src', 'alt', 'title', 'width', 'height',
'frameborder', 'allowfullscreen'
],
ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i
});
} catch (err) {
console.error(`Error processing markdown for slug "${realSlug}":`, err);
// Return a more informative error message in the content
processedContent = `<div class="error-message">
<p>Error processing markdown content. Please check the console for details.</p>
<pre>${err instanceof Error ? err.message : 'Unknown error'}</pre>
</div>`;
}
return {
slug: realSlug,
@@ -37,9 +70,9 @@ async function getPostBySlug(slug: string) {
date: data.date,
tags: data.tags || [],
summary: data.summary,
content: processedContent.toString(),
content: processedContent,
createdAt: createdAt.toISOString(),
author: process.env.NEXT_PUBLIC_BLOG_OWNER + "'s" || 'Anonymous',
author: (process.env.NEXT_PUBLIC_BLOG_OWNER || 'Anonymous') + "'s",
};
}
@@ -48,12 +81,19 @@ export async function GET(
{ params }: { params: { slug: string[] | string } }
) {
try {
// Support catch-all route: slug can be string or string[]
const slugArr = Array.isArray(params.slug) ? params.slug : [params.slug];
const slugPath = slugArr.join('/');
const post = await getPostBySlug(slugPath);
return NextResponse.json(post);
} catch (error) {
return NextResponse.json({ error: 'Fehler beim Laden des Beitrags' }, { status: 500 });
console.error('Error loading post:', error);
return NextResponse.json(
{
error: 'Error loading post',
details: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 500 }
);
}
}
}

View File

@@ -2,8 +2,10 @@ import { NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import { remark } from 'remark';
import gfm from 'remark-gfm';
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkGfm from 'remark-gfm';
import remarkRehype from 'remark-rehype';
import rehypeRaw from 'rehype-raw';
import rehypeStringify from 'rehype-stringify';
@@ -15,25 +17,37 @@ let pinnedSlugs: string[] = [];
if (fs.existsSync(pinnedPath)) {
try {
pinnedSlugs = JSON.parse(fs.readFileSync(pinnedPath, 'utf8'));
} catch {}
} catch {
pinnedSlugs = [];
}
}
// Function to get file creation date
function getFileCreationDate(filePath: string): Date {
const stats = fs.statSync(filePath);
return stats.birthtime;
return stats.birthtime ?? stats.mtime;
}
async function getPostByPath(filePath: string, relPath: string) {
const fileContents = fs.readFileSync(filePath, 'utf8');
const { data, content } = matter(fileContents);
const createdAt = getFileCreationDate(filePath);
const processedContent = await remark()
.use(gfm)
.use(remarkRehype, { allowDangerousHtml: true })
.use(rehypeRaw)
.use(rehypeStringify)
.process(content);
let processedContent = '';
try {
const file = await unified()
.use(remarkParse as any)
.use(remarkGfm)
.use(remarkRehype, { allowDangerousHtml: true })
.use(rehypeRaw)
.use(rehypeStringify)
.process(content);
processedContent = file.toString();
} catch (err) {
console.error(`Error processing markdown for ${relPath}:`, err);
}
return {
type: 'post',
slug: relPath.replace(/\.md$/, ''),
@@ -41,7 +55,7 @@ async function getPostByPath(filePath: string, relPath: string) {
date: data.date,
tags: data.tags || [],
summary: data.summary,
content: processedContent.toString(),
content: processedContent,
createdAt: createdAt.toISOString(),
pinned: pinnedSlugs.includes(relPath.replace(/\.md$/, '')),
};
@@ -51,9 +65,11 @@ async function readPostsDir(dir: string, relDir = ''): Promise<any[]> {
const entries = fs.readdirSync(dir, { withFileTypes: true });
const folders: any[] = [];
const posts: any[] = [];
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
const relPath = relDir ? path.join(relDir, entry.name) : entry.name;
if (entry.isDirectory()) {
const children = await readPostsDir(fullPath, relPath);
folders.push({ type: 'folder', name: entry.name, path: relPath, children });
@@ -61,8 +77,10 @@ async function readPostsDir(dir: string, relDir = ''): Promise<any[]> {
posts.push(await getPostByPath(fullPath, relPath));
}
}
// Sort posts by creation date (newest first)
posts.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
// Folders first, then posts
return [...folders, ...posts];
}
@@ -72,6 +90,8 @@ export async function GET() {
const tree = await readPostsDir(postsDirectory);
return NextResponse.json(tree);
} catch (error) {
console.error('Error loading posts:', error);
return NextResponse.json({ error: 'Fehler beim Laden der Beiträge' }, { status: 500 });
}
}
}