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

@@ -7,8 +7,8 @@ WORKDIR /app
# Copy package files # Copy package files
COPY package*.json ./ COPY package*.json ./
# Install dependencies # First install only production dependencies
RUN npm ci RUN npm install --omit=dev
# Copy source code and config files # Copy source code and config files
COPY . . COPY . .
@@ -23,10 +23,10 @@ FROM node:18-alpine AS runner
WORKDIR /app WORKDIR /app
# Copy package files # Copy package files
COPY package*.json ./ COPY --from=builder /app/package*.json ./
# Install production dependencies only # Install production dependencies only
RUN npm ci --only=production RUN npm install --omit=dev
# Copy necessary files from builder # Copy necessary files from builder
COPY --from=builder /app/.next ./.next/ COPY --from=builder /app/.next ./.next/

View File

@@ -4,7 +4,6 @@
IMAGE_NAME="markdown-blog" IMAGE_NAME="markdown-blog"
CONTAINER_NAME="markdown-blog-container" CONTAINER_NAME="markdown-blog-container"
PORT=8080 PORT=8080
# Automatically set MARKDOWN_DIR to the directory where this script lives
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MARKDOWN_DIR="$SCRIPT_DIR" # Use the script's directory as the default markdown directory MARKDOWN_DIR="$SCRIPT_DIR" # Use the script's directory as the default markdown directory
@@ -12,12 +11,13 @@ MARKDOWN_DIR="$SCRIPT_DIR" # Use the script's directory as the default markdown
RED='\033[0;31m' RED='\033[0;31m'
GREEN='\033[0;32m' GREEN='\033[0;32m'
YELLOW='\033[1;33m' YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color NC='\033[0m' # No Color
# Function to check if Docker is running # Function to check if Docker is running
check_docker() { check_docker() {
if ! docker info > /dev/null 2>&1; then if ! docker info > /dev/null 2>&1; then
echo -e "${RED}Error: Docker is not running${NC}" echo -e "${RED}Error: Docker is not running. Please start Docker and try again.${NC}"
exit 1 exit 1
fi fi
} }
@@ -35,7 +35,7 @@ container_running() {
# Function to check container health # Function to check container health
check_container_health() { check_container_health() {
local health_status local health_status
health_status=$(docker inspect --format='{{.State.Health.Status}}' $CONTAINER_NAME 2>/dev/null) health_status=$(docker inspect --format='{{.State.Health.Status}}' "$CONTAINER_NAME" 2>/dev/null)
if [ "$health_status" = "healthy" ]; then if [ "$health_status" = "healthy" ]; then
return 0 return 0
else else
@@ -54,17 +54,11 @@ npm_spinner_right() {
"JavaScript: Where '1' + 1 = '11'!" "JavaScript: Where '1' + 1 = '11'!"
"NPM: Installing 1000 dependencies for 'hello world'..." "NPM: Installing 1000 dependencies for 'hello world'..."
"TypeScript: Making JavaScript developers feel safe (sometimes)." "TypeScript: Making JavaScript developers feel safe (sometimes)."
"NPM: 5 minutes left... just kidding!"
"JavaScript: Because who needs types anyway?"
"NPM: One does not simply 'npm install' without warnings."
"TypeScript: The language that makes you write more code to do less."
"NPM: 0 vulnerabilities (in your dreams)."
) )
local colors=(31 33 32 36 34 35 91 92 93 94 95 96) local colors=(31 33 32 36 34 35) # Red, Yellow, Green, Cyan, Blue, Magenta
local joke_count=${#jokes[@]}
local joke_index=0 local joke_index=0
tput civis tput civis # Hide cursor
while kill -0 $pid 2>/dev/null; do while kill -0 "$pid" 2>/dev/null; do
local temp="${spinstr#?}" local temp="${spinstr#?}"
local cols=$(tput cols) local cols=$(tput cols)
local msg="[%c] %s" local msg="[%c] %s"
@@ -86,102 +80,84 @@ npm_spinner_right() {
printf "\r%*s%s" $pad "" "$rainbow" printf "\r%*s%s" $pad "" "$rainbow"
spinstr=$temp${spinstr%$temp} spinstr=$temp${spinstr%$temp}
sleep $delay sleep $delay
joke_index=$(( (joke_index + 1) % joke_count )) joke_index=$(( (joke_index + 1) % ${#jokes[@]} ))
done done
printf "\r" printf "\r"
tput cnorm tput cnorm # Restore cursor
} }
# Function to build the Docker image (show spinner/jokes only during npm ci) # Function to build the Docker image (show spinner/jokes only during npm ci)
build_image() { build_image() {
echo -e "${YELLOW}Building Docker image...${NC}" echo -e "${YELLOW}Building Docker image...${NC}"
# Use a named pipe to capture docker build output
local pipe=$(mktemp -u) local pipe=$(mktemp -u)
mkfifo "$pipe" mkfifo "$pipe"
# Start docker build, redirect output to pipe (docker build -t "$IMAGE_NAME" . | tee "$pipe") &
(docker build -t $IMAGE_NAME . | tee "$pipe") &
build_pid=$! build_pid=$!
# Watch the pipe for the npm ci step
while read -r line; do while read -r line; do
echo "$line" echo "$line"
if [[ "$line" == *"RUN npm ci"* ]]; then if [[ "$line" == *"RUN npm ci"* ]]; then
# Wait for the npm ci process to start in the background
sleep 1 sleep 1
npm_spinner_right $build_pid & npm_spinner_right "$build_pid" &
spinner_pid=$! spinner_pid=$!
wait $build_pid wait "$build_pid"
kill $spinner_pid 2>/dev/null kill "$spinner_pid" 2>/dev/null
break break
fi fi
done < "$pipe" done < "$pipe"
wait $build_pid wait "$build_pid"
rm -f "$pipe" rm -f "$pipe"
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
echo -e "${RED}Error: Failed to build Docker image${NC}" echo -e "${RED}Error: Failed to build Docker image. Check logs above.${NC}"
exit 1 exit 1
fi fi
echo -e "${GREEN}Docker image built successfully${NC}" echo -e "${GREEN}Docker image built successfully!${NC}"
} }
# Function to start the container # Function to start the container
start_container() { start_container() {
echo -e "${YELLOW}Starting container...${NC}" echo -e "${YELLOW}Starting container...${NC}"
# Check if container already exists
if container_exists; then if container_exists; then
if container_running; then if container_running; then
echo -e "${YELLOW}Container is already running${NC}" echo -e "${YELLOW}Container is already running.${NC}"
return return
else else
echo -e "${YELLOW}Container exists but is not running. Starting it...${NC}" echo -e "${YELLOW}Restarting existing container...${NC}"
if ! docker start $CONTAINER_NAME; then docker start "$CONTAINER_NAME" || {
echo -e "${RED}Error: Failed to start existing container${NC}" echo -e "${RED}Error: Failed to start container.${NC}"
exit 1 exit 1
fi }
fi fi
else else
# Create and start new container echo -e "${BLUE}Creating and starting new container...${NC}"
if ! docker run -d \ docker run -d \
--name $CONTAINER_NAME \ --name "$CONTAINER_NAME" \
-p $PORT:8080 \ -p "$PORT:8080" \
-v "$MARKDOWN_DIR:/markdown" \ -v "$MARKDOWN_DIR:/markdown" \
--restart unless-stopped \ --restart unless-stopped \
--health-cmd="wget --no-verbose --tries=1 --spider http://localhost:8080/ || exit 1" \ --health-cmd="curl -f http://localhost:8080/ || exit 1" \
--health-interval=30s \ --health-interval=30s \
--health-timeout=30s \ --health-timeout=10s \
--health-retries=3 \ --health-retries=3 \
--health-start-period=5s \ "$IMAGE_NAME" || {
$IMAGE_NAME; then echo -e "${RED}Error: Failed to create container.${NC}"
echo -e "${RED}Error: Failed to create and start container${NC}"
exit 1 exit 1
fi }
fi fi
# Wait for container to be ready # Wait for container to be healthy
echo -e "${YELLOW}Waiting for container to be ready...${NC}" echo -e "${YELLOW}Waiting for container to be ready...${NC}"
local max_attempts=60 local max_attempts=30
local attempt=1 local attempt=1
while [ $attempt -le $max_attempts ]; do while [ $attempt -le $max_attempts ]; do
if check_container_health; then if check_container_health; then
echo -e "${GREEN}Container is healthy and accessible at http://localhost:$PORT${NC}" echo -e "${GREEN}Container is healthy! Access it at: http://localhost:$PORT${NC}"
return return
fi fi
printf "."
# Check if container is still running
if ! container_running; then
echo -e "${RED}Error: Container stopped unexpectedly${NC}"
docker logs $CONTAINER_NAME
exit 1
fi
echo -n "."
sleep 1 sleep 1
attempt=$((attempt + 1)) attempt=$((attempt + 1))
done done
echo -e "${RED}Error: Container did not become healthy. Check logs with './manage_container.sh logs'.${NC}"
echo -e "${RED}Error: Container did not become healthy in time${NC}"
docker logs $CONTAINER_NAME
exit 1 exit 1
} }
@@ -189,77 +165,71 @@ start_container() {
stop_container() { stop_container() {
echo -e "${YELLOW}Stopping container...${NC}" echo -e "${YELLOW}Stopping container...${NC}"
if ! container_exists; then if ! container_exists; then
echo -e "${YELLOW}Container does not exist${NC}" echo -e "${YELLOW}Container does not exist.${NC}"
return return
fi fi
docker stop "$CONTAINER_NAME" || {
if ! docker stop $CONTAINER_NAME; then echo -e "${RED}Error: Failed to stop container.${NC}"
echo -e "${RED}Error: Failed to stop container${NC}"
exit 1 exit 1
fi }
echo -e "${GREEN}Container stopped successfully${NC}" echo -e "${GREEN}Container stopped successfully.${NC}"
} }
# Function to remove the container # Function to remove the container
remove_container() { remove_container() {
echo -e "${YELLOW}Removing container...${NC}" echo -e "${YELLOW}Removing container...${NC}"
if ! container_exists; then if ! container_exists; then
echo -e "${YELLOW}Container does not exist${NC}" echo -e "${YELLOW}Container does not exist.${NC}"
return return
fi fi
if container_running; then if container_running; then
stop_container stop_container
fi fi
docker rm "$CONTAINER_NAME" || {
if ! docker rm $CONTAINER_NAME; then echo -e "${RED}Error: Failed to remove container.${NC}"
echo -e "${RED}Error: Failed to remove container${NC}"
exit 1 exit 1
fi }
echo -e "${GREEN}Container removed successfully${NC}" echo -e "${GREEN}Container removed successfully.${NC}"
} }
# Function to restart the container # Function to restart the container
restart_container() { restart_container() {
echo -e "${YELLOW}Restarting container...${NC}" echo -e "${YELLOW}Restarting container...${NC}"
if ! container_exists; then if ! container_exists; then
echo -e "${YELLOW}Container does not exist. Starting new container...${NC}" echo -e "${YELLOW}Container does not exist. Starting new one...${NC}"
start_container start_container
return return
fi fi
docker restart "$CONTAINER_NAME" || {
if ! docker restart $CONTAINER_NAME; then echo -e "${RED}Error: Failed to restart container.${NC}"
echo -e "${RED}Error: Failed to restart container${NC}"
exit 1 exit 1
fi }
echo -e "${GREEN}Container restarted successfully${NC}" echo -e "${GREEN}Container restarted successfully.${NC}"
} }
# Function to view logs # Function to view logs
view_logs() { view_logs() {
echo -e "${YELLOW}Viewing logs...${NC}" echo -e "${YELLOW}Viewing logs...${NC}"
if ! container_exists; then if ! container_exists; then
echo -e "${RED}Error: Container does not exist${NC}" echo -e "${RED}Error: Container does not exist.${NC}"
exit 1 exit 1
fi fi
docker logs -f "$CONTAINER_NAME"
docker logs -f $CONTAINER_NAME
} }
# Function to show container status # Function to show container status
show_status() { show_status() {
echo -e "${YELLOW}Container Status:${NC}" echo -e "${YELLOW}Container Status:${NC}"
if ! container_exists; then if ! container_exists; then
echo -e "${RED}Container does not exist${NC}" echo -e "${RED}Container does not exist.${NC}"
return return
fi fi
if container_running; then if container_running; then
local health_status local health_status
health_status=$(docker inspect --format='{{.State.Health.Status}}' $CONTAINER_NAME 2>/dev/null) health_status=$(docker inspect --format='{{.State.Health.Status}}' "$CONTAINER_NAME" 2>/dev/null)
echo -e "${GREEN}Container is running${NC}" echo -e "${GREEN}Container is running.${NC}"
echo "Health status: $health_status" echo -e "Health: ${health_status}"
echo "Access the application at: http://localhost:$PORT" echo -e
else else
echo -e "${YELLOW}Container exists but is not running${NC}" echo -e "${YELLOW}Container exists but is not running${NC}"
fi fi

3573
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -12,21 +12,29 @@
}, },
"dependencies": { "dependencies": {
"@tailwindcss/typography": "^0.5.16", "@tailwindcss/typography": "^0.5.16",
"@types/dompurify": "^3.0.5",
"@types/jsdom": "^21.1.7",
"@types/marked": "^5.0.2",
"autoprefixer": "^10.4.17", "autoprefixer": "^10.4.17",
"bcrypt": "^6.0.0", "bcrypt": "^6.0.0",
"chokidar": "^4.0.3", "chokidar": "^4.0.3",
"date-fns": "^3.3.1", "date-fns": "^3.3.1",
"dompurify": "^3.2.6",
"gray-matter": "^4.0.3", "gray-matter": "^4.0.3",
"jsdom": "^26.1.0",
"marked": "^15.0.12",
"next": "14.1.0", "next": "14.1.0",
"postcss": "^8.4.35", "postcss": "^8.4.35",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"rehype-raw": "^6.1.1", "rehype-raw": "^6.1.1",
"rehype-sanitize": "^6.0.0",
"rehype-stringify": "^9.0.3", "rehype-stringify": "^9.0.3",
"remark": "^15.0.1", "remark": "^15.0.0",
"remark-gfm": "^3.0.1", "remark-gfm": "^3.0.1",
"remark-html": "^16.0.1", "remark-html": "^16.0.1",
"remark-rehype": "^11.1.0", "remark-parse": "^11.0.0",
"remark-rehype": "^11.0.0",
"tailwindcss": "^3.4.1" "tailwindcss": "^3.4.1"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -2,19 +2,16 @@ import { NextResponse } from 'next/server';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import matter from 'gray-matter'; import matter from 'gray-matter';
import { remark } from 'remark'; import { marked } from 'marked';
import html from 'remark-html'; import DOMPurify from 'dompurify';
import gfm from 'remark-gfm'; import { JSDOM } from 'jsdom';
import remarkRehype from 'remark-rehype';
import rehypeRaw from 'rehype-raw';
import rehypeStringify from 'rehype-stringify';
const postsDirectory = path.join(process.cwd(), 'posts'); const postsDirectory = path.join(process.cwd(), 'posts');
// Function to get file creation date // Function to get file creation date
function getFileCreationDate(filePath: string): Date { function getFileCreationDate(filePath: string): Date {
const stats = fs.statSync(filePath); const stats = fs.statSync(filePath);
return stats.birthtime; return stats.birthtime ?? stats.mtime;
} }
async function getPostBySlug(slug: string) { async function getPostBySlug(slug: string) {
@@ -24,12 +21,48 @@ async function getPostBySlug(slug: string) {
const { data, content } = matter(fileContents); const { data, content } = matter(fileContents);
const createdAt = getFileCreationDate(fullPath); const createdAt = getFileCreationDate(fullPath);
const processedContent = await remark() let processedContent = '';
.use(gfm) try {
.use(remarkRehype, { allowDangerousHtml: true }) // Configure marked options
.use(rehypeRaw) marked.setOptions({
.use(rehypeStringify) gfm: true,
.process(content); 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 { return {
slug: realSlug, slug: realSlug,
@@ -37,9 +70,9 @@ async function getPostBySlug(slug: string) {
date: data.date, date: data.date,
tags: data.tags || [], tags: data.tags || [],
summary: data.summary, summary: data.summary,
content: processedContent.toString(), content: processedContent,
createdAt: createdAt.toISOString(), 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 } } { params }: { params: { slug: string[] | string } }
) { ) {
try { try {
// Support catch-all route: slug can be string or string[]
const slugArr = Array.isArray(params.slug) ? params.slug : [params.slug]; const slugArr = Array.isArray(params.slug) ? params.slug : [params.slug];
const slugPath = slugArr.join('/'); const slugPath = slugArr.join('/');
const post = await getPostBySlug(slugPath); const post = await getPostBySlug(slugPath);
return NextResponse.json(post); return NextResponse.json(post);
} catch (error) { } 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 fs from 'fs';
import path from 'path'; import path from 'path';
import matter from 'gray-matter'; 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 remarkRehype from 'remark-rehype';
import rehypeRaw from 'rehype-raw'; import rehypeRaw from 'rehype-raw';
import rehypeStringify from 'rehype-stringify'; import rehypeStringify from 'rehype-stringify';
@@ -15,25 +17,37 @@ let pinnedSlugs: string[] = [];
if (fs.existsSync(pinnedPath)) { if (fs.existsSync(pinnedPath)) {
try { try {
pinnedSlugs = JSON.parse(fs.readFileSync(pinnedPath, 'utf8')); pinnedSlugs = JSON.parse(fs.readFileSync(pinnedPath, 'utf8'));
} catch {} } catch {
pinnedSlugs = [];
}
} }
// Function to get file creation date // Function to get file creation date
function getFileCreationDate(filePath: string): Date { function getFileCreationDate(filePath: string): Date {
const stats = fs.statSync(filePath); const stats = fs.statSync(filePath);
return stats.birthtime; return stats.birthtime ?? stats.mtime;
} }
async function getPostByPath(filePath: string, relPath: string) { async function getPostByPath(filePath: string, relPath: string) {
const fileContents = fs.readFileSync(filePath, 'utf8'); const fileContents = fs.readFileSync(filePath, 'utf8');
const { data, content } = matter(fileContents); const { data, content } = matter(fileContents);
const createdAt = getFileCreationDate(filePath); const createdAt = getFileCreationDate(filePath);
const processedContent = await remark()
.use(gfm) let processedContent = '';
.use(remarkRehype, { allowDangerousHtml: true }) try {
.use(rehypeRaw) const file = await unified()
.use(rehypeStringify) .use(remarkParse as any)
.process(content); .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 { return {
type: 'post', type: 'post',
slug: relPath.replace(/\.md$/, ''), slug: relPath.replace(/\.md$/, ''),
@@ -41,7 +55,7 @@ async function getPostByPath(filePath: string, relPath: string) {
date: data.date, date: data.date,
tags: data.tags || [], tags: data.tags || [],
summary: data.summary, summary: data.summary,
content: processedContent.toString(), content: processedContent,
createdAt: createdAt.toISOString(), createdAt: createdAt.toISOString(),
pinned: pinnedSlugs.includes(relPath.replace(/\.md$/, '')), 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 entries = fs.readdirSync(dir, { withFileTypes: true });
const folders: any[] = []; const folders: any[] = [];
const posts: any[] = []; const posts: any[] = [];
for (const entry of entries) { for (const entry of entries) {
const fullPath = path.join(dir, entry.name); const fullPath = path.join(dir, entry.name);
const relPath = relDir ? path.join(relDir, entry.name) : entry.name; const relPath = relDir ? path.join(relDir, entry.name) : entry.name;
if (entry.isDirectory()) { if (entry.isDirectory()) {
const children = await readPostsDir(fullPath, relPath); const children = await readPostsDir(fullPath, relPath);
folders.push({ type: 'folder', name: entry.name, path: relPath, children }); 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)); posts.push(await getPostByPath(fullPath, relPath));
} }
} }
// Sort posts by creation date (newest first) // Sort posts by creation date (newest first)
posts.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()); posts.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
// Folders first, then posts // Folders first, then posts
return [...folders, ...posts]; return [...folders, ...posts];
} }
@@ -72,6 +90,8 @@ export async function GET() {
const tree = await readPostsDir(postsDirectory); const tree = await readPostsDir(postsDirectory);
return NextResponse.json(tree); return NextResponse.json(tree);
} catch (error) { } catch (error) {
console.error('Error loading posts:', error);
return NextResponse.json({ error: 'Fehler beim Laden der Beiträge' }, { status: 500 }); return NextResponse.json({ error: 'Fehler beim Laden der Beiträge' }, { status: 500 });
} }
} }