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

View File

@@ -4,7 +4,6 @@
IMAGE_NAME="markdown-blog"
CONTAINER_NAME="markdown-blog-container"
PORT=8080
# Automatically set MARKDOWN_DIR to the directory where this script lives
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
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'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Function to check if Docker is running
check_docker() {
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
fi
}
@@ -35,7 +35,7 @@ container_running() {
# Function to check container health
check_container_health() {
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
return 0
else
@@ -54,17 +54,11 @@ npm_spinner_right() {
"JavaScript: Where '1' + 1 = '11'!"
"NPM: Installing 1000 dependencies for 'hello world'..."
"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 joke_count=${#jokes[@]}
local colors=(31 33 32 36 34 35) # Red, Yellow, Green, Cyan, Blue, Magenta
local joke_index=0
tput civis
while kill -0 $pid 2>/dev/null; do
tput civis # Hide cursor
while kill -0 "$pid" 2>/dev/null; do
local temp="${spinstr#?}"
local cols=$(tput cols)
local msg="[%c] %s"
@@ -86,102 +80,84 @@ npm_spinner_right() {
printf "\r%*s%s" $pad "" "$rainbow"
spinstr=$temp${spinstr%$temp}
sleep $delay
joke_index=$(( (joke_index + 1) % joke_count ))
joke_index=$(( (joke_index + 1) % ${#jokes[@]} ))
done
printf "\r"
tput cnorm
tput cnorm # Restore cursor
}
# Function to build the Docker image (show spinner/jokes only during npm ci)
build_image() {
echo -e "${YELLOW}Building Docker image...${NC}"
# Use a named pipe to capture docker build output
local pipe=$(mktemp -u)
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=$!
# Watch the pipe for the npm ci step
while read -r line; do
echo "$line"
if [[ "$line" == *"RUN npm ci"* ]]; then
# Wait for the npm ci process to start in the background
sleep 1
npm_spinner_right $build_pid &
npm_spinner_right "$build_pid" &
spinner_pid=$!
wait $build_pid
kill $spinner_pid 2>/dev/null
wait "$build_pid"
kill "$spinner_pid" 2>/dev/null
break
fi
done < "$pipe"
wait $build_pid
wait "$build_pid"
rm -f "$pipe"
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
fi
echo -e "${GREEN}Docker image built successfully${NC}"
echo -e "${GREEN}Docker image built successfully!${NC}"
}
# Function to start the container
start_container() {
echo -e "${YELLOW}Starting container...${NC}"
# Check if container already exists
if container_exists; then
if container_running; then
echo -e "${YELLOW}Container is already running${NC}"
echo -e "${YELLOW}Container is already running.${NC}"
return
else
echo -e "${YELLOW}Container exists but is not running. Starting it...${NC}"
if ! docker start $CONTAINER_NAME; then
echo -e "${RED}Error: Failed to start existing container${NC}"
echo -e "${YELLOW}Restarting existing container...${NC}"
docker start "$CONTAINER_NAME" || {
echo -e "${RED}Error: Failed to start container.${NC}"
exit 1
fi
}
fi
else
# Create and start new container
if ! docker run -d \
--name $CONTAINER_NAME \
-p $PORT:8080 \
echo -e "${BLUE}Creating and starting new container...${NC}"
docker run -d \
--name "$CONTAINER_NAME" \
-p "$PORT:8080" \
-v "$MARKDOWN_DIR:/markdown" \
--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-timeout=30s \
--health-timeout=10s \
--health-retries=3 \
--health-start-period=5s \
$IMAGE_NAME; then
echo -e "${RED}Error: Failed to create and start container${NC}"
"$IMAGE_NAME" || {
echo -e "${RED}Error: Failed to create container.${NC}"
exit 1
fi
}
fi
# Wait for container to be ready
# Wait for container to be healthy
echo -e "${YELLOW}Waiting for container to be ready...${NC}"
local max_attempts=60
local max_attempts=30
local attempt=1
while [ $attempt -le $max_attempts ]; do
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
fi
# 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 "."
printf "."
sleep 1
attempt=$((attempt + 1))
done
echo -e "${RED}Error: Container did not become healthy in time${NC}"
docker logs $CONTAINER_NAME
echo -e "${RED}Error: Container did not become healthy. Check logs with './manage_container.sh logs'.${NC}"
exit 1
}
@@ -189,77 +165,71 @@ start_container() {
stop_container() {
echo -e "${YELLOW}Stopping container...${NC}"
if ! container_exists; then
echo -e "${YELLOW}Container does not exist${NC}"
echo -e "${YELLOW}Container does not exist.${NC}"
return
fi
if ! docker stop $CONTAINER_NAME; then
echo -e "${RED}Error: Failed to stop container${NC}"
docker stop "$CONTAINER_NAME" || {
echo -e "${RED}Error: Failed to stop container.${NC}"
exit 1
fi
echo -e "${GREEN}Container stopped successfully${NC}"
}
echo -e "${GREEN}Container stopped successfully.${NC}"
}
# Function to remove the container
remove_container() {
echo -e "${YELLOW}Removing container...${NC}"
if ! container_exists; then
echo -e "${YELLOW}Container does not exist${NC}"
echo -e "${YELLOW}Container does not exist.${NC}"
return
fi
if container_running; then
stop_container
fi
if ! docker rm $CONTAINER_NAME; then
echo -e "${RED}Error: Failed to remove container${NC}"
docker rm "$CONTAINER_NAME" || {
echo -e "${RED}Error: Failed to remove container.${NC}"
exit 1
fi
echo -e "${GREEN}Container removed successfully${NC}"
}
echo -e "${GREEN}Container removed successfully.${NC}"
}
# Function to restart the container
restart_container() {
echo -e "${YELLOW}Restarting container...${NC}"
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
return
fi
if ! docker restart $CONTAINER_NAME; then
echo -e "${RED}Error: Failed to restart container${NC}"
docker restart "$CONTAINER_NAME" || {
echo -e "${RED}Error: Failed to restart container.${NC}"
exit 1
fi
echo -e "${GREEN}Container restarted successfully${NC}"
}
echo -e "${GREEN}Container restarted successfully.${NC}"
}
# Function to view logs
view_logs() {
echo -e "${YELLOW}Viewing logs...${NC}"
if ! container_exists; then
echo -e "${RED}Error: Container does not exist${NC}"
echo -e "${RED}Error: Container does not exist.${NC}"
exit 1
fi
docker logs -f $CONTAINER_NAME
docker logs -f "$CONTAINER_NAME"
}
# Function to show container status
show_status() {
echo -e "${YELLOW}Container Status:${NC}"
if ! container_exists; then
echo -e "${RED}Container does not exist${NC}"
echo -e "${RED}Container does not exist.${NC}"
return
fi
if container_running; then
local health_status
health_status=$(docker inspect --format='{{.State.Health.Status}}' $CONTAINER_NAME 2>/dev/null)
echo -e "${GREEN}Container is running${NC}"
echo "Health status: $health_status"
echo "Access the application at: http://localhost:$PORT"
health_status=$(docker inspect --format='{{.State.Health.Status}}' "$CONTAINER_NAME" 2>/dev/null)
echo -e "${GREEN}Container is running.${NC}"
echo -e "Health: ${health_status}"
echo -e
else
echo -e "${YELLOW}Container exists but is not running${NC}"
fi

3573
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -12,21 +12,29 @@
},
"dependencies": {
"@tailwindcss/typography": "^0.5.16",
"@types/dompurify": "^3.0.5",
"@types/jsdom": "^21.1.7",
"@types/marked": "^5.0.2",
"autoprefixer": "^10.4.17",
"bcrypt": "^6.0.0",
"chokidar": "^4.0.3",
"date-fns": "^3.3.1",
"dompurify": "^3.2.6",
"gray-matter": "^4.0.3",
"jsdom": "^26.1.0",
"marked": "^15.0.12",
"next": "14.1.0",
"postcss": "^8.4.35",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"rehype-raw": "^6.1.1",
"rehype-sanitize": "^6.0.0",
"rehype-stringify": "^9.0.3",
"remark": "^15.0.1",
"remark": "^15.0.0",
"remark-gfm": "^3.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"
},
"devDependencies": {

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)
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 });
}
}