diff --git a/app/api/n8n/chat/route.ts b/app/api/n8n/chat/route.ts new file mode 100644 index 0000000..dc09850 --- /dev/null +++ b/app/api/n8n/chat/route.ts @@ -0,0 +1,86 @@ +import { NextResponse } from 'next/server'; + +export async function POST(request: Request) { + try { + const { message } = await request.json(); + + if (!message || typeof message !== 'string') { + return NextResponse.json( + { error: 'Message is required' }, + { status: 400 } + ); + } + + // Call your n8n chat webhook + const n8nWebhookUrl = process.env.N8N_WEBHOOK_URL; + + if (!n8nWebhookUrl) { + console.error('N8N_WEBHOOK_URL not configured'); + // Return fallback response + return NextResponse.json({ + reply: getFallbackResponse(message) + }); + } + + const response = await fetch(`${n8nWebhookUrl}/webhook/chat`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(process.env.N8N_API_KEY && { + 'Authorization': `Bearer ${process.env.N8N_API_KEY}` + }), + }, + body: JSON.stringify({ message }), + }); + + if (!response.ok) { + throw new Error(`n8n webhook failed: ${response.status}`); + } + + const data = await response.json(); + return NextResponse.json({ reply: data.reply || data.message || data.response }); + } catch (error) { + console.error('Chat API error:', error); + + // Fallback to mock responses if n8n is down + const { message } = await request.json(); + return NextResponse.json( + { reply: getFallbackResponse(message) } + ); + } +} + +function getFallbackResponse(message: string): string { + const lowerMessage = message.toLowerCase(); + + if (lowerMessage.includes('skill') || lowerMessage.includes('tech')) { + return "Dennis specializes in full-stack development with Next.js, Flutter for mobile, and DevOps with Docker Swarm. He's passionate about self-hosting and runs his own infrastructure!"; + } + + if (lowerMessage.includes('project')) { + return "Dennis has built Clarity (a Flutter app for people with dyslexia) and runs a complete self-hosted infrastructure with Docker Swarm, Traefik, and automated CI/CD pipelines. Check out the Projects section for more!"; + } + + if (lowerMessage.includes('contact') || lowerMessage.includes('email') || lowerMessage.includes('reach')) { + return "You can reach Dennis via the contact form on this site or email him at contact@dk0.dev. He's always open to discussing new opportunities and interesting projects!"; + } + + if (lowerMessage.includes('location') || lowerMessage.includes('where')) { + return "Dennis is based in Osnabrück, Germany. He's a student who's passionate about technology and self-hosting."; + } + + if (lowerMessage.includes('hobby') || lowerMessage.includes('free time')) { + return "When Dennis isn't coding or managing servers, he enjoys gaming, jogging, and experimenting with new technologies. He also uses pen and paper for notes despite automating everything else!"; + } + + if (lowerMessage.includes('devops') || lowerMessage.includes('docker') || lowerMessage.includes('infrastructure')) { + return "Dennis runs his own infrastructure on IONOS and OVHcloud using Docker Swarm, Traefik for reverse proxy, and custom CI/CD pipelines. He loves self-hosting and managing game servers!"; + } + + if (lowerMessage.includes('student') || lowerMessage.includes('study')) { + return "Yes, Dennis is currently a student in Osnabrück while also working on various tech projects and managing his own infrastructure. He's always learning and exploring new technologies!"; + } + + // Default response + return "That's a great question! Dennis is a full-stack developer and DevOps enthusiast who loves building things with Next.js, Flutter, and Docker. Feel free to ask me more specific questions about his skills, projects, or experience!"; +} diff --git a/app/api/n8n/generate-image/route.ts b/app/api/n8n/generate-image/route.ts new file mode 100644 index 0000000..ebe2528 --- /dev/null +++ b/app/api/n8n/generate-image/route.ts @@ -0,0 +1,176 @@ +import { NextRequest, NextResponse } from "next/server"; + +/** + * POST /api/n8n/generate-image + * + * Triggers AI image generation for a project via n8n workflow + * + * Body: + * { + * projectId: number; + * regenerate?: boolean; // Force regenerate even if image exists + * } + */ +export async function POST(req: NextRequest) { + try { + const body = await req.json(); + const { projectId, regenerate = false } = body; + + // Validate input + if (!projectId) { + return NextResponse.json( + { error: "projectId is required" }, + { status: 400 }, + ); + } + + // Check environment variables + const n8nWebhookUrl = process.env.N8N_WEBHOOK_URL; + const n8nSecretToken = process.env.N8N_SECRET_TOKEN; + + if (!n8nWebhookUrl) { + return NextResponse.json( + { + error: "N8N_WEBHOOK_URL not configured", + message: + "AI image generation is not set up. Please configure n8n webhooks.", + }, + { status: 503 }, + ); + } + + // Optional: Check if project already has an image + if (!regenerate) { + const checkResponse = await fetch( + `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000"}/api/projects/${projectId}`, + { + method: "GET", + cache: "no-store", + }, + ); + + if (checkResponse.ok) { + const project = await checkResponse.json(); + if (project.imageUrl && project.imageUrl !== "") { + return NextResponse.json( + { + success: true, + message: + "Project already has an image. Use regenerate=true to force regeneration.", + projectId: projectId, + existingImageUrl: project.imageUrl, + regenerated: false, + }, + { status: 200 }, + ); + } + } + } + + // Call n8n webhook to trigger AI image generation + const n8nResponse = await fetch(`${n8nWebhookUrl}/ai-image-generation`, { + method: "POST", + headers: { + "Content-Type": "application/json", + ...(n8nSecretToken && { + Authorization: `Bearer ${n8nSecretToken}`, + }), + }, + body: JSON.stringify({ + projectId: projectId, + regenerate: regenerate, + triggeredBy: "api", + timestamp: new Date().toISOString(), + }), + }); + + if (!n8nResponse.ok) { + const errorText = await n8nResponse.text(); + console.error("n8n webhook error:", errorText); + + return NextResponse.json( + { + error: "Failed to trigger image generation", + message: "n8n workflow failed to execute", + details: errorText, + }, + { status: 500 }, + ); + } + + const result = await n8nResponse.json(); + + return NextResponse.json( + { + success: true, + message: "AI image generation started successfully", + projectId: projectId, + imageUrl: result.imageUrl, + generatedAt: result.generatedAt, + fileSize: result.fileSize, + regenerated: regenerate, + }, + { status: 200 }, + ); + } catch (error) { + console.error("Error in generate-image API:", error); + return NextResponse.json( + { + error: "Internal server error", + message: error instanceof Error ? error.message : "Unknown error", + }, + { status: 500 }, + ); + } +} + +/** + * GET /api/n8n/generate-image?projectId=123 + * + * Check the status of image generation for a project + */ +export async function GET(req: NextRequest) { + try { + const searchParams = req.nextUrl.searchParams; + const projectId = searchParams.get("projectId"); + + if (!projectId) { + return NextResponse.json( + { error: "projectId query parameter is required" }, + { status: 400 }, + ); + } + + // Fetch project to check image status + const projectResponse = await fetch( + `${process.env.NEXT_PUBLIC_API_URL || "http://localhost:3000"}/api/projects/${projectId}`, + { + method: "GET", + cache: "no-store", + }, + ); + + if (!projectResponse.ok) { + return NextResponse.json({ error: "Project not found" }, { status: 404 }); + } + + const project = await projectResponse.json(); + + return NextResponse.json({ + projectId: parseInt(projectId), + title: project.title, + hasImage: !!project.imageUrl, + imageUrl: project.imageUrl || null, + updatedAt: project.updatedAt, + }); + } catch (error) { + console.error("Error checking image status:", error); + return NextResponse.json( + { + error: "Internal server error", + message: error instanceof Error ? error.message : "Unknown error", + }, + { status: 500 }, + ); + } +} diff --git a/app/api/n8n/status/route.ts b/app/api/n8n/status/route.ts index 06d0fe0..d358632 100644 --- a/app/api/n8n/status/route.ts +++ b/app/api/n8n/status/route.ts @@ -1,19 +1,115 @@ -import { NextResponse } from 'next/server'; +import { NextResponse } from "next/server"; +import { PrismaClient } from "@prisma/client"; + +const prisma = new PrismaClient(); + +export const dynamic = "force-dynamic"; +export const revalidate = 0; export async function GET() { - // Mock data - in real integration this would fetch from n8n webhook or database - return NextResponse.json({ - activity: { - type: 'coding', // coding, listening, watching - details: 'Portfolio Website', - timestamp: new Date().toISOString(), - }, - music: { - isPlaying: true, - track: 'Midnight City', - artist: 'M83', - platform: 'spotify' - }, - watching: null - }); + try { + // Fetch from activity_status table + const result = await prisma.$queryRawUnsafe( + `SELECT * FROM activity_status WHERE id = 1 LIMIT 1`, + ); + + if (!result || result.length === 0) { + return NextResponse.json({ + activity: null, + music: null, + watching: null, + gaming: null, + status: null, + }); + } + + const data = result[0]; + + // Check if activity is recent (within last 2 hours) + const lastUpdate = new Date(data.updated_at); + const now = new Date(); + const hoursSinceUpdate = + (now.getTime() - lastUpdate.getTime()) / (1000 * 60 * 60); + const isRecent = hoursSinceUpdate < 2; + + return NextResponse.json( + { + activity: + data.activity_type && isRecent + ? { + type: data.activity_type, + details: data.activity_details, + project: data.activity_project, + language: data.activity_language, + repo: data.activity_repo, + link: data.activity_repo, // Use repo URL as link + timestamp: data.updated_at, + } + : null, + + music: data.music_playing + ? { + isPlaying: data.music_playing, + track: data.music_track, + artist: data.music_artist, + album: data.music_album, + platform: data.music_platform || "spotify", + progress: data.music_progress, + albumArt: data.music_album_art, + spotifyUrl: data.music_track + ? `https://open.spotify.com/search/${encodeURIComponent(data.music_track + " " + data.music_artist)}` + : null, + } + : null, + + watching: data.watching_title + ? { + title: data.watching_title, + platform: data.watching_platform || "youtube", + type: data.watching_type || "video", + } + : null, + + gaming: data.gaming_game + ? { + game: data.gaming_game, + platform: data.gaming_platform || "steam", + status: data.gaming_status || "playing", + } + : null, + + status: data.status_mood + ? { + mood: data.status_mood, + customMessage: data.status_message, + } + : null, + }, + { + headers: { + "Cache-Control": "no-store, no-cache, must-revalidate, max-age=0", + Pragma: "no-cache", + }, + }, + ); + } catch (error) { + console.error("Error fetching activity status:", error); + + // Return empty state on error (graceful degradation) + return NextResponse.json( + { + activity: null, + music: null, + watching: null, + gaming: null, + status: null, + }, + { + status: 200, // Return 200 to prevent frontend errors + headers: { + "Cache-Control": "no-store, no-cache, must-revalidate, max-age=0", + }, + }, + ); + } } diff --git a/app/components/About.tsx b/app/components/About.tsx index 54a59aa..736853c 100644 --- a/app/components/About.tsx +++ b/app/components/About.tsx @@ -1,9 +1,34 @@ "use client"; -import { useState, useEffect } from 'react'; -import { motion } from 'framer-motion'; -import { Code, Terminal, Cpu, Globe } from 'lucide-react'; -import { LiquidHeading } from '@/components/LiquidHeading'; +import { useState, useEffect } from "react"; +import { motion } from "framer-motion"; +import { Globe, Server, Wrench, Shield, Gamepad2, Code } from "lucide-react"; + +// Smooth animation configuration +const smoothTransition = { + duration: 1, + ease: [0.25, 0.1, 0.25, 1], +}; + +const staggerContainer = { + hidden: { opacity: 0 }, + visible: { + opacity: 1, + transition: { + staggerChildren: 0.15, + delayChildren: 0.2, + }, + }, +}; + +const fadeInUp = { + hidden: { opacity: 0, y: 30 }, + visible: { + opacity: 1, + y: 0, + transition: smoothTransition, + }, +}; const About = () => { const [mounted, setMounted] = useState(false); @@ -14,81 +39,205 @@ const About = () => { const techStack = [ { - category: 'Frontend', + category: "Frontend & Mobile", icon: Globe, - items: ['React', 'TypeScript', 'Tailwind', 'Next.js'] + items: ["Next.js", "Tailwind CSS", "Flutter"], }, { - category: 'Backend', - icon: Terminal, - items: ['Node.js', 'PostgreSQL', 'Prisma', 'API Design'] + category: "Backend & DevOps", + icon: Server, + items: ["Docker Swarm", "Traefik", "Nginx Proxy Manager", "Redis"], }, { - category: 'Tools', - icon: Cpu, - items: ['Git', 'Docker', 'VS Code', 'Figma'] - } + category: "Tools & Automation", + icon: Wrench, + items: ["Git", "CI/CD", "n8n", "Self-hosted Services"], + }, + { + category: "Security & Admin", + icon: Shield, + items: ["CrowdSec", "Suricata", "Mailcow"], + }, + ]; + + const hobbies = [ + { icon: Code, text: "Self-Hosting & DevOps" }, + { icon: Gamepad2, text: "Gaming" }, + { icon: Server, text: "Setting up Game Servers" }, ]; if (!mounted) return null; return ( -
+
- -
+
{/* Text Content */} -
- -
+ + + About Me + +

- Hi, I'm Dennis. I'm a software engineer who likes building things that work well and look good. + Hi, I'm Dennis – a student and passionate self-hoster based + in Osnabrück, Germany.

- I'm currently based in Osnabrück, Germany. My journey in tech is driven by curiosity—I love figuring out how things work and how to make them better. + I love building full-stack web applications with{" "} + Next.js and mobile apps with{" "} + Flutter. But what really excites me is{" "} + DevOps: I run my own infrastructure on{" "} + IONOS and OVHcloud, managing + everything with Docker Swarm,{" "} + Traefik, and automated CI/CD pipelines with my + own runners.

- When I'm not in front of a screen, you can find me listening to music, exploring new ideas, or just relaxing. + When I'm not coding or tinkering with servers, you'll + find me gaming, jogging, or + experimenting with new tech like game servers or automation + workflows with n8n.

-
-
+

+ 💡 Fun fact: Even though I automate a lot, I still use pen and + paper for my calendar and notes – it helps me clear my head and + stay focused. +

+ + - {/* Simplified Skills / Tech Stack */} -
-

My Toolbox

- {techStack.map((stack, idx) => ( - +
+ -
-
- -
-

{stack.category}

-
-
- {stack.items.map(item => ( - - {item} + My Tech Stack + +
+ {techStack.map((stack, idx) => ( + +
+
+ +
+

+ {stack.category} +

+
+
+ {stack.items.map((item, itemIdx) => ( + + {item} + + ))} +
+
+ ))} +
+
+ + {/* Hobbies */} +
+ + When I'm Not Coding + +
+ {hobbies.map((hobby, idx) => ( + + + + {hobby.text} - ))} -
- - ))} -
+ + ))} + +

+ 🏃 Jogging to clear my mind and stay active +

+
+
+
+
); }; -export default About; \ No newline at end of file +export default About; diff --git a/app/components/ActivityFeed.tsx b/app/components/ActivityFeed.tsx index 9a2f3ec..8fde83a 100644 --- a/app/components/ActivityFeed.tsx +++ b/app/components/ActivityFeed.tsx @@ -1,48 +1,270 @@ -'use client'; +"use client"; -import { useState, useEffect } from 'react'; -import { motion, AnimatePresence } from 'framer-motion'; -import { Music, Code, Monitor, MessageSquare, Send, X } from 'lucide-react'; +import { useState, useEffect } from "react"; +import { motion, AnimatePresence } from "framer-motion"; +import { + Music, + Code, + Monitor, + MessageSquare, + Send, + X, + Loader2, + Github, + Tv, + Gamepad2, + Coffee, + Headphones, + Terminal, + Sparkles, + ExternalLink, + Activity, + Waves, + Zap, +} from "lucide-react"; interface ActivityData { activity: { - type: 'coding' | 'listening' | 'watching'; + type: + | "coding" + | "listening" + | "watching" + | "gaming" + | "reading" + | "running"; details: string; timestamp: string; + project?: string; + language?: string; + repo?: string; + link?: string; } | null; music: { isPlaying: boolean; track: string; artist: string; - platform: 'spotify' | 'apple'; + album?: string; + platform: "spotify" | "apple"; + progress?: number; + albumArt?: string; + spotifyUrl?: string; } | null; watching: { title: string; - platform: 'youtube' | 'netflix'; + platform: "youtube" | "netflix" | "twitch"; + type: "video" | "stream" | "movie" | "series"; + } | null; + gaming: { + game: string; + platform: "steam" | "playstation" | "xbox"; + status: "playing" | "idle"; + } | null; + status: { + mood: string; + customMessage?: string; } | null; } +// Matrix rain effect for coding +const MatrixRain = () => { + const chars = "01"; + return ( +
+ {[...Array(15)].map((_, i) => ( + + {[...Array(20)].map((_, j) => ( +
{chars[Math.floor(Math.random() * chars.length)]}
+ ))} +
+ ))} +
+ ); +}; + +// Sound waves for music +const SoundWaves = () => { + return ( +
+ {[...Array(5)].map((_, i) => ( + + ))} +
+ ); +}; + +// Running animation +const RunningAnimation = () => { + return ( +
+ + 🏃 + +
+
+ ); +}; + +// Gaming particles +const GamingParticles = () => { + return ( +
+ {[...Array(10)].map((_, i) => ( + + ))} +
+ ); +}; + +// TV scan lines +const TVScanLines = () => { + return ( +
+ +
+ ); +}; + +const activityIcons = { + coding: Terminal, + listening: Headphones, + watching: Tv, + gaming: Gamepad2, + reading: Coffee, + running: Activity, +}; + +const activityColors = { + coding: { + bg: "from-liquid-mint/20 to-liquid-sky/20", + border: "border-liquid-mint/40", + text: "text-liquid-mint", + pulse: "bg-green-500", + }, + listening: { + bg: "from-liquid-rose/20 to-liquid-coral/20", + border: "border-liquid-rose/40", + text: "text-liquid-rose", + pulse: "bg-red-500", + }, + watching: { + bg: "from-liquid-lavender/20 to-liquid-pink/20", + border: "border-liquid-lavender/40", + text: "text-liquid-lavender", + pulse: "bg-purple-500", + }, + gaming: { + bg: "from-liquid-peach/20 to-liquid-yellow/20", + border: "border-liquid-peach/40", + text: "text-liquid-peach", + pulse: "bg-orange-500", + }, + reading: { + bg: "from-liquid-teal/20 to-liquid-lime/20", + border: "border-liquid-teal/40", + text: "text-liquid-teal", + pulse: "bg-teal-500", + }, + running: { + bg: "from-liquid-lime/20 to-liquid-mint/20", + border: "border-liquid-lime/40", + text: "text-liquid-lime", + pulse: "bg-lime-500", + }, +}; + export const ActivityFeed = () => { const [data, setData] = useState(null); const [showChat, setShowChat] = useState(false); - const [chatMessage, setChatMessage] = useState(''); - const [chatHistory, setChatHistory] = useState<{ - role: 'user' | 'ai'; - text: string; - }[]>([ - { role: 'ai', text: 'Hi! I am Dennis\'s AI assistant. Ask me anything about him!' } + const [chatMessage, setChatMessage] = useState(""); + const [isLoading, setIsLoading] = useState(false); + const [chatHistory, setChatHistory] = useState< + { + role: "user" | "ai"; + text: string; + timestamp: number; + }[] + >([ + { + role: "ai", + text: "Hi! I'm Dennis's AI assistant. Ask me anything about his work, skills, or projects! 🚀", + timestamp: Date.now(), + }, ]); useEffect(() => { const fetchData = async () => { try { - const res = await fetch('/api/n8n/status'); + const res = await fetch("/api/n8n/status"); if (res.ok) { const json = await res.json(); setData(json); } } catch (e) { - console.error('Failed to fetch activity', e); + console.error("Failed to fetch activity", e); } }; fetchData(); @@ -50,67 +272,306 @@ export const ActivityFeed = () => { return () => clearInterval(interval); }, []); - const handleSendMessage = (e: React.FormEvent) => { + const handleSendMessage = async (e: React.FormEvent) => { e.preventDefault(); - if (!chatMessage.trim()) return; + if (!chatMessage.trim() || isLoading) return; const userMsg = chatMessage; - setChatHistory(prev => [...prev, { role: 'user', text: userMsg }]); - setChatMessage(''); + setChatHistory((prev) => [ + ...prev, + { role: "user", text: userMsg, timestamp: Date.now() }, + ]); + setChatMessage(""); + setIsLoading(true); - // Mock AI response - would connect to n8n webhook - setTimeout(() => { - setChatHistory(prev => [...prev, { role: 'ai', text: `That's a great question about "${userMsg}"! I'll ask Dennis to add more info about that.` }]); - }, 1000); + try { + const response = await fetch("/api/n8n/chat", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ message: userMsg }), + }); + + if (response.ok) { + const data = await response.json(); + setChatHistory((prev) => [ + ...prev, + { role: "ai", text: data.reply, timestamp: Date.now() }, + ]); + } else { + throw new Error("Chat API failed"); + } + } catch (error) { + console.error("Chat error:", error); + setChatHistory((prev) => [ + ...prev, + { + role: "ai", + text: "Sorry, I encountered an error. Please try again later.", + timestamp: Date.now(), + }, + ]); + } finally { + setIsLoading(false); + } }; - if (!data) return null; + const renderActivityBubble = () => { + if (!data?.activity) return null; + + const { type, details, project, language, link } = data.activity; + const Icon = activityIcons[type]; + const colors = activityColors[type]; + + return ( + + {/* Background Animation based on activity type */} + {type === "coding" && } + {type === "running" && } + {type === "gaming" && } + {type === "watching" && } + +
+ + + + +
+
+
+ + + + {type} +
+

{details}

+ {project && ( +

+ + {project} +

+ )} + {language && ( + + {language} + + )} + {link && ( + + View + + )} +
+
+ ); + }; + + const renderMusicBubble = () => { + if (!data?.music?.isPlaying) return null; + + const { track, artist, album, progress, albumArt, spotifyUrl } = data.music; + + return ( + + {/* Animated sound waves background */} + + + {albumArt && ( + + {album + + )} +
+
+ + + + Now Playing +
+

{track}

+

{artist}

+ {progress !== undefined && ( +
+ +
+ )} + {spotifyUrl && ( + + + Listen with me + + )} +
+
+ ); + }; + + const renderStatusBubble = () => { + if (!data?.status) return null; + + const { mood, customMessage } = data.status; + + return ( + + + {mood} + +
+ {customMessage && ( +

+ {customMessage} +

+ )} +
+
+ ); + }; return ( -
- +
{/* Chat Window */} {showChat && ( -
- - - Ask me anything +
+ + + AI Assistant -
-
+
{chatHistory.map((msg, i) => ( -
-
+ +
{msg.text}
-
+ ))} + {isLoading && ( + +
+ + Thinking... +
+
+ )}
-
- + setChatMessage(e.target.value)} - placeholder="Type a message..." - className="flex-1 bg-white/60 border border-white/60 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-stone-400" + placeholder="Ask me anything..." + disabled={isLoading} + className="flex-1 bg-white border-2 border-stone-200 rounded-xl px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-liquid-mint focus:border-transparent disabled:opacity-50 transition-all duration-300" /> - + + +
)} @@ -118,41 +579,40 @@ export const ActivityFeed = () => { {/* Activity Bubbles */}
- {data.activity?.type === 'coding' && ( - - - - - - - Working on {data.activity.details} - - )} + + {renderActivityBubble()} + {renderMusicBubble()} + {renderStatusBubble()} + - {data.music?.isPlaying && ( - - - Listening to {data.music.track} - - )} - - {/* Chat Toggle Button */} + {/* Chat Toggle Button with Notification Indicator */} setShowChat(!showChat)} - className="bg-stone-900 text-white rounded-full p-4 shadow-xl hover:bg-black transition-all" + className="relative bg-stone-900 text-white rounded-full p-4 shadow-xl hover:bg-stone-950 transition-all duration-500 ease-out" + title="Ask me anything about Dennis" > + {!showChat && ( + + + + )}
diff --git a/app/components/Contact.tsx b/app/components/Contact.tsx index 560b68a..9d8a6aa 100644 --- a/app/components/Contact.tsx +++ b/app/components/Contact.tsx @@ -1,10 +1,9 @@ "use client"; -import { useState, useEffect } from 'react'; -import { motion } from 'framer-motion'; -import { Mail, MapPin, Send } from 'lucide-react'; -import { useToast } from '@/components/Toast'; -import { LiquidHeading } from '@/components/LiquidHeading'; +import { useState, useEffect } from "react"; +import { motion } from "framer-motion"; +import { Mail, MapPin, Send } from "lucide-react"; +import { useToast } from "@/components/Toast"; const Contact = () => { const [mounted, setMounted] = useState(false); @@ -15,10 +14,10 @@ const Contact = () => { }, []); const [formData, setFormData] = useState({ - name: '', - email: '', - subject: '', - message: '' + name: "", + email: "", + subject: "", + message: "", }); const [errors, setErrors] = useState>({}); @@ -29,27 +28,27 @@ const Contact = () => { const newErrors: Record = {}; if (!formData.name.trim()) { - newErrors.name = 'Name is required'; + newErrors.name = "Name is required"; } else if (formData.name.trim().length < 2) { - newErrors.name = 'Name must be at least 2 characters'; + newErrors.name = "Name must be at least 2 characters"; } if (!formData.email.trim()) { - newErrors.email = 'Email is required'; + newErrors.email = "Email is required"; } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) { - newErrors.email = 'Please enter a valid email address'; + newErrors.email = "Please enter a valid email address"; } if (!formData.subject.trim()) { - newErrors.subject = 'Subject is required'; + newErrors.subject = "Subject is required"; } else if (formData.subject.trim().length < 3) { - newErrors.subject = 'Subject must be at least 3 characters'; + newErrors.subject = "Subject must be at least 3 characters"; } if (!formData.message.trim()) { - newErrors.message = 'Message is required'; + newErrors.message = "Message is required"; } else if (formData.message.trim().length < 10) { - newErrors.message = 'Message must be at least 10 characters'; + newErrors.message = "Message must be at least 10 characters"; } setErrors(newErrors); @@ -58,18 +57,18 @@ const Contact = () => { const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); - + if (!validateForm()) { return; } setIsSubmitting(true); - + try { - const response = await fetch('/api/email', { - method: 'POST', + const response = await fetch("/api/email", { + method: "POST", headers: { - 'Content-Type': 'application/json', + "Content-Type": "application/json", }, body: JSON.stringify({ name: formData.name, @@ -81,41 +80,49 @@ const Contact = () => { if (response.ok) { showEmailSent(formData.email); - setFormData({ name: '', email: '', subject: '', message: '' }); + setFormData({ name: "", email: "", subject: "", message: "" }); setTouched({}); setErrors({}); } else { const errorData = await response.json(); - showEmailError(errorData.error || 'Failed to send message. Please try again.'); + showEmailError( + errorData.error || "Failed to send message. Please try again.", + ); } } catch (error) { - console.error('Error sending email:', error); - showEmailError('Network error. Please check your connection and try again.'); + console.error("Error sending email:", error); + showEmailError( + "Network error. Please check your connection and try again.", + ); } finally { setIsSubmitting(false); } }; - const handleChange = (e: React.ChangeEvent) => { + const handleChange = ( + e: React.ChangeEvent, + ) => { const { name, value } = e.target; setFormData({ ...formData, - [name]: value + [name]: value, }); // Clear error when user starts typing if (errors[name]) { setErrors({ ...errors, - [name]: '' + [name]: "", }); } }; - const handleBlur = (e: React.FocusEvent) => { + const handleBlur = ( + e: React.FocusEvent, + ) => { setTouched({ ...touched, - [e.target.name]: true + [e.target.name]: true, }); validateForm(); }; @@ -123,53 +130,61 @@ const Contact = () => { const contactInfo = [ { icon: Mail, - title: 'Email', - value: 'contact@dk0.dev', - href: 'mailto:contact@dk0.dev' + title: "Email", + value: "contact@dk0.dev", + href: "mailto:contact@dk0.dev", }, { icon: MapPin, - title: 'Location', - value: 'Osnabrück, Germany', - } + title: "Location", + value: "Osnabrück, Germany", + }, ]; - if (!mounted) { return null; } return ( -
+
{/* Section Header */} -
- -

- Interested in working together or have questions about my projects? Feel free to reach out! + +

+ Contact Me +

+

+ Interested in working together or have questions about my projects? + Feel free to reach out!

-
+
{/* Contact Information */}
-

+

Get In Touch

-

- I'm always available to discuss new opportunities, interesting projects, - or simply chat about technology and innovation. +

+ I'm always available to discuss new opportunities, + interesting projects, or simply chat about technology and + innovation.

@@ -182,37 +197,50 @@ const Contact = () => { initial={{ opacity: 0, x: -20 }} whileInView={{ opacity: 1, x: 0 }} viewport={{ once: true }} - transition={{ duration: 0.6, delay: index * 0.1 }} - whileHover={{ x: 5 }} - className="flex items-center space-x-4 p-4 rounded-2xl glass-card hover:bg-white/60 transition-colors group border-transparent hover:border-white/60" + transition={{ + duration: 0.8, + delay: index * 0.15, + ease: [0.25, 0.1, 0.25, 1], + }} + whileHover={{ + x: 8, + transition: { duration: 0.4, ease: "easeOut" }, + }} + className="flex items-center space-x-4 p-4 rounded-2xl glass-card hover:bg-white/80 transition-all duration-500 ease-out group border-transparent hover:border-white/70" >
-

{info.title}

+

+ {info.title} +

{info.value}

))}
- {/* Contact Form */} -

Send Message

- +

+ Send Message +

+
-
- +
-
-
-
\n\n
\n

🏃 Manual Activities

\n \n \n \n \n
\n\n
\n

🧹 Quick Actions

\n \n \n \n
\n\n \n\n" + } + } + ] +} +``` + +**Zugriff:** +``` +https://your-n8n-instance.com/webhook/activity-dashboard +``` + +--- + +### Option 2: Discord Bot Commands + +Erstelle einen Discord Bot für schnelle Updates: + +**Commands:** +``` +!status 💻 Working on new features +!coding Portfolio Next.js +!music +!gaming Elden Ring +!clear +!afk +``` + +**n8n Workflow:** +```json +{ + "nodes": [ + { + "name": "Discord Webhook", + "type": "n8n-nodes-base.webhook", + "parameters": { + "path": "discord-bot" + } + }, + { + "name": "Parse Command", + "type": "n8n-nodes-base.function", + "parameters": { + "functionCode": "const message = items[0].json.content;\nconst [command, ...args] = message.split(' ');\n\nswitch(command) {\n case '!status':\n return [{\n json: {\n action: 'update_status',\n mood: args[0],\n message: args.slice(1).join(' ')\n }\n }];\n \n case '!coding':\n return [{\n json: {\n action: 'update_activity',\n type: 'coding',\n details: args.join(' ')\n }\n }];\n \n case '!clear':\n return [{\n json: { action: 'clear_all' }\n }];\n}\n\nreturn [{ json: {} }];" + } + }, + { + "name": "Update Database", + "type": "n8n-nodes-base.postgres" + } + ] +} +``` + +--- + +### Option 3: Mobile App / Shortcut + +**iOS Shortcuts:** +``` +1. "Start Coding" → POST to n8n webhook +2. "Finished Work" → Clear activity +3. "Set Mood" → Update status +``` + +**Android Tasker:** +- Similar webhooks +- Location-based triggers +- Time-based automation + +--- + +### Option 4: CLI Tool + +Erstelle ein simples CLI Tool: + +```bash +#!/bin/bash +# activity.sh + +N8N_URL="https://your-n8n-instance.com" + +case "$1" in + status) + curl -X POST "$N8N_URL/webhook/update-status" \ + -H "Content-Type: application/json" \ + -d "{\"mood\":\"$2\",\"message\":\"$3\"}" + ;; + coding) + curl -X POST "$N8N_URL/webhook/update-activity" \ + -H "Content-Type: application/json" \ + -d "{\"type\":\"coding\",\"project\":\"$2\",\"language\":\"$3\"}" + ;; + clear) + curl -X POST "$N8N_URL/webhook/clear-all" + ;; + *) + echo "Usage: activity.sh [status|coding|clear] [args]" + ;; +esac +``` + +**Usage:** +```bash +./activity.sh status 💻 "Deep work mode" +./activity.sh coding "Portfolio" "TypeScript" +./activity.sh clear +``` + +--- + +## 🔄 Automatische Sync-Workflows + +### Musik geht weg wenn nicht mehr läuft + +**n8n Workflow: "Spotify Auto-Clear"** +```json +{ + "nodes": [ + { + "name": "Check Every 30s", + "type": "n8n-nodes-base.cron", + "parameters": { + "cronExpression": "*/30 * * * * *" + } + }, + { + "name": "Get Spotify Status", + "type": "n8n-nodes-base.httpRequest", + "parameters": { + "url": "https://api.spotify.com/v1/me/player/currently-playing" + } + }, + { + "name": "Check If Playing", + "type": "n8n-nodes-base.if", + "parameters": { + "conditions": { + "boolean": [ + { + "value1": "={{$json.is_playing}}", + "value2": false + } + ] + } + } + }, + { + "name": "Clear Music from Database", + "type": "n8n-nodes-base.postgres", + "parameters": { + "operation": "executeQuery", + "query": "UPDATE activity_status SET music_playing = FALSE, music_track = NULL, music_artist = NULL, music_album = NULL, music_album_art = NULL, music_progress = NULL WHERE id = 1" + } + } + ] +} +``` + +### Auto-Clear nach Zeit + +**n8n Workflow: "Activity Timeout"** +```javascript +// Function Node: Check Activity Age +const lastUpdate = new Date(items[0].json.updated_at); +const now = new Date(); +const hoursSinceUpdate = (now - lastUpdate) / (1000 * 60 * 60); + +// Clear activity if older than 2 hours +if (hoursSinceUpdate > 2) { + return [{ + json: { + should_clear: true, + reason: `Activity too old (${hoursSinceUpdate.toFixed(1)} hours)` + } + }]; +} + +return [{ json: { should_clear: false } }]; +``` + +### Smart Activity Detection + +**Workflow: "Detect Coding from Git Commits"** +```javascript +// When you push to GitHub +const commit = items[0].json; +const repo = commit.repository.name; +const message = commit.head_commit.message; + +// Detect language from files +const files = commit.head_commit.modified; +const language = files[0]?.split('.').pop(); // Get extension + +return [{ + json: { + activity_type: 'coding', + activity_details: message, + activity_project: repo, + activity_language: language, + activity_repo: commit.repository.html_url, + link: commit.head_commit.url + } +}]; +``` + +--- + +## 📊 Activity Analytics Dashboard + +**Workflow: "Activity History & Stats"** + +Speichere Historie in separater Tabelle: + +```sql +CREATE TABLE activity_history ( + id SERIAL PRIMARY KEY, + activity_type VARCHAR(50), + details TEXT, + duration INTEGER, -- in minutes + started_at TIMESTAMP, + ended_at TIMESTAMP, + created_at TIMESTAMP DEFAULT NOW() +); + +-- View für Statistiken +CREATE VIEW activity_stats AS +SELECT + activity_type, + COUNT(*) as count, + SUM(duration) as total_minutes, + AVG(duration) as avg_duration, + DATE(created_at) as date +FROM activity_history +GROUP BY activity_type, DATE(created_at) +ORDER BY date DESC; +``` + +**Dashboard Queries:** +```sql +-- Heute +SELECT * FROM activity_stats WHERE date = CURRENT_DATE; + +-- Diese Woche +SELECT activity_type, SUM(total_minutes) as minutes +FROM activity_stats +WHERE date >= CURRENT_DATE - INTERVAL '7 days' +GROUP BY activity_type; + +-- Most Coded Languages +SELECT activity_language, COUNT(*) +FROM activity_history +WHERE activity_type = 'coding' +GROUP BY activity_language +ORDER BY COUNT(*) DESC; +``` + +--- + +## 🎨 Custom Activity Types + +Erweitere das System mit eigenen Activity-Types: + +```sql +-- Add custom columns +ALTER TABLE activity_status +ADD COLUMN custom_activity_type VARCHAR(100), +ADD COLUMN custom_activity_data JSONB; + +-- Example: Workout tracking +UPDATE activity_status SET + custom_activity_type = 'workout', + custom_activity_data = '{ + "exercise": "Push-ups", + "reps": 50, + "icon": "💪", + "color": "orange" + }'::jsonb +WHERE id = 1; +``` + +**Frontend Support:** +```typescript +// In ActivityFeed.tsx +interface CustomActivity { + type: string; + data: { + icon: string; + color: string; + [key: string]: any; + }; +} + +// Render custom activities dynamically +if (data.customActivity) { + return ( + + {data.customActivity.data.icon} + {data.customActivity.type} + {/* Render data fields dynamically */} + + ); +} +``` + +--- + +## 🔐 Security & Best Practices + +### 1. Webhook Authentication + +```javascript +// In n8n webhook +const secret = $credentials.webhookSecret; +const providedSecret = $node["Webhook"].json.headers["x-webhook-secret"]; + +if (secret !== providedSecret) { + return [{ + json: { error: "Unauthorized" }, + statusCode: 401 + }]; +} +``` + +### 2. Rate Limiting + +```sql +-- Track requests +CREATE TABLE webhook_requests ( + ip_address VARCHAR(45), + endpoint VARCHAR(100), + requested_at TIMESTAMP DEFAULT NOW() +); + +-- Check rate limit (max 10 requests per minute) +SELECT COUNT(*) FROM webhook_requests +WHERE ip_address = $1 +AND requested_at > NOW() - INTERVAL '1 minute'; +``` + +### 3. Input Validation + +```javascript +// In n8n Function node +const validateInput = (data) => { + if (!data.type || typeof data.type !== 'string') { + throw new Error('Invalid activity type'); + } + + if (data.type === 'coding' && !data.project) { + throw new Error('Project name required for coding activity'); + } + + return true; +}; +``` + +--- + +## 🚀 Quick Deploy Checklist + +- [ ] Datenbank Table erstellt (`setup_activity_status.sql`) +- [ ] n8n Workflows importiert +- [ ] Spotify OAuth konfiguriert +- [ ] GitHub Webhooks eingerichtet +- [ ] Dashboard-URL getestet +- [ ] API Routes deployed +- [ ] Environment Variables gesetzt +- [ ] Frontend ActivityFeed getestet +- [ ] Auto-Clear Workflows aktiviert + +--- + +## 💡 Pro-Tipps + +1. **Backup System**: Exportiere n8n Workflows regelmäßig +2. **Monitoring**: Setup alerts wenn Workflows fehlschlagen +3. **Testing**: Nutze n8n's Test-Modus vor Produktion +4. **Logging**: Speichere alle Aktivitäten für Analyse +5. **Fallbacks**: Zeige Placeholder wenn keine Daten vorhanden + +--- + +## 📞 Quick Support Commands + +```bash +# Check database status +psql -d portfolio_dev -c "SELECT * FROM activity_status WHERE id = 1;" + +# Clear all activities +psql -d portfolio_dev -c "UPDATE activity_status SET activity_type = NULL, music_playing = FALSE WHERE id = 1;" + +# View recent history +psql -d portfolio_dev -c "SELECT * FROM activity_history ORDER BY created_at DESC LIMIT 10;" + +# Test n8n webhook +curl -X POST https://your-n8n.com/webhook/update-activity \ + -H "Content-Type: application/json" \ + -d '{"type":"coding","details":"Testing","project":"Portfolio"}' +``` + +--- + +Happy automating! 🎉 \ No newline at end of file diff --git a/docs/N8N_INTEGRATION.md b/docs/N8N_INTEGRATION.md new file mode 100644 index 0000000..97581ff --- /dev/null +++ b/docs/N8N_INTEGRATION.md @@ -0,0 +1,590 @@ +# 🚀 n8n Integration Guide - Complete Setup + +## Übersicht + +Dieses Portfolio nutzt n8n für: +- ⚡ **Echtzeit-Aktivitätsanzeige** (Coding, Musik, Gaming, etc.) +- 💬 **AI-Chatbot** (mit OpenAI/Anthropic) +- 📊 **Aktivitäts-Tracking** (GitHub, Spotify, Netflix, etc.) +- 🎮 **Gaming-Status** (Steam, Discord) +- 📧 **Automatische Benachrichtigungen** + +--- + +## 🎨 Coole Ideen für Integrationen + +### 1. **GitHub Activity Feed** 🔨 +**Was es zeigt:** +- "Currently coding: Portfolio Website" +- "Last commit: 5 minutes ago" +- "Working on: feature/n8n-integration" +- Programming language (TypeScript, Python, etc.) + +**n8n Workflow:** +``` +GitHub Webhook → Extract Data → Update Database → Display on Site +``` + +### 2. **Spotify Now Playing** 🎵 +**Was es zeigt:** +- Aktueller Song + Artist +- Album Cover (rotierend animiert!) +- Fortschrittsbalken +- "Listening to X since Y minutes" + +**n8n Workflow:** +``` +Cron (every 30s) → Spotify API → Parse Track Data → Update Database +``` + +### 3. **Netflix/YouTube/Twitch Watching** 📺 +**Was es zeigt:** +- "Watching: Breaking Bad S05E14" +- "Streaming: Coding Tutorial" +- Platform badges (Netflix/YouTube/Twitch) + +**n8n Workflow:** +``` +Trakt.tv API → Get Current Watching → Update Database +Discord Rich Presence → Extract Activity → Update Database +``` + +### 4. **Gaming Activity** 🎮 +**Was es zeigt:** +- "Playing: Elden Ring" +- Platform: Steam/PlayStation/Xbox +- Play time +- Achievement notifications + +**n8n Workflow:** +``` +Steam API → Get Current Game → Update Database +Discord Presence → Parse Game → Update Database +``` + +### 5. **Mood & Custom Status** 😊 +**Was es zeigt:** +- Emoji mood (😊, 💻, 🏃, 🎮, 😴) +- Custom message: "Focused on DevOps" +- Auto-status based on time/activity + +**n8n Workflow:** +``` +Schedule → Determine Status (work hours/break/sleep) → Update Database +Manual Webhook → Set Custom Status → Update Database +``` + +### 6. **Smart Notifications** 📬 +**Was es zeigt:** +- "New email from X" +- "GitHub PR needs review" +- "Calendar event in 15 min" + +**n8n Workflow:** +``` +Email/Calendar/GitHub → Filter Important → Create Notification → Display +``` + +--- + +## 📦 Setup: Datenbank Schema + +### PostgreSQL Table: `activity_status` + +```sql +CREATE TABLE activity_status ( + id SERIAL PRIMARY KEY, + + -- Activity + activity_type VARCHAR(50), -- 'coding', 'listening', 'watching', 'gaming', 'reading' + activity_details TEXT, + activity_project VARCHAR(255), + activity_language VARCHAR(50), + activity_repo VARCHAR(255), + + -- Music + music_playing BOOLEAN DEFAULT FALSE, + music_track VARCHAR(255), + music_artist VARCHAR(255), + music_album VARCHAR(255), + music_platform VARCHAR(50), -- 'spotify', 'apple' + music_progress INTEGER, -- 0-100 + music_album_art TEXT, + + -- Watching + watching_title VARCHAR(255), + watching_platform VARCHAR(50), -- 'youtube', 'netflix', 'twitch' + watching_type VARCHAR(50), -- 'video', 'stream', 'movie', 'series' + + -- Gaming + gaming_game VARCHAR(255), + gaming_platform VARCHAR(50), -- 'steam', 'playstation', 'xbox' + gaming_status VARCHAR(50), -- 'playing', 'idle' + + -- Status + status_mood VARCHAR(10), -- emoji + status_message TEXT, + + updated_at TIMESTAMP DEFAULT NOW() +); +``` + +--- + +## 🔧 n8n Workflows + +### Workflow 1: GitHub Activity Tracker + +**Trigger:** Webhook bei Push/Commit +**Frequenz:** Echtzeit + +```json +{ + "nodes": [ + { + "name": "GitHub Webhook", + "type": "n8n-nodes-base.webhook", + "parameters": { + "path": "github-activity", + "method": "POST" + } + }, + { + "name": "Extract Commit Data", + "type": "n8n-nodes-base.function", + "parameters": { + "functionCode": "const commit = items[0].json;\nreturn [\n {\n json: {\n activity_type: 'coding',\n activity_details: commit.head_commit.message,\n activity_project: commit.repository.name,\n activity_language: 'TypeScript',\n activity_repo: commit.repository.html_url,\n updated_at: new Date().toISOString()\n }\n }\n];" + } + }, + { + "name": "Update Database", + "type": "n8n-nodes-base.postgres", + "parameters": { + "operation": "executeQuery", + "query": "INSERT INTO activity_status (activity_type, activity_details, activity_project, activity_language, activity_repo, updated_at) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (id) DO UPDATE SET activity_type = $1, activity_details = $2, activity_project = $3, activity_language = $4, activity_repo = $5, updated_at = $6 WHERE activity_status.id = 1" + } + } + ] +} +``` + +**Setup in GitHub:** +1. Gehe zu deinem Repository → Settings → Webhooks +2. Add webhook: `https://your-n8n-instance.com/webhook/github-activity` +3. Content type: `application/json` +4. Events: Push events + +--- + +### Workflow 2: Spotify Now Playing + +**Trigger:** Cron (alle 30 Sekunden) + +```json +{ + "nodes": [ + { + "name": "Schedule", + "type": "n8n-nodes-base.cron", + "parameters": { + "cronExpression": "*/30 * * * * *" + } + }, + { + "name": "Spotify API", + "type": "n8n-nodes-base.httpRequest", + "parameters": { + "url": "https://api.spotify.com/v1/me/player/currently-playing", + "method": "GET", + "authentication": "oAuth2", + "headers": { + "Authorization": "Bearer {{$credentials.spotify.accessToken}}" + } + } + }, + { + "name": "Parse Track Data", + "type": "n8n-nodes-base.function", + "parameters": { + "functionCode": "const track = items[0].json;\nif (!track || !track.is_playing) {\n return [{ json: { music_playing: false } }];\n}\n\nreturn [\n {\n json: {\n music_playing: true,\n music_track: track.item.name,\n music_artist: track.item.artists[0].name,\n music_album: track.item.album.name,\n music_platform: 'spotify',\n music_progress: Math.round((track.progress_ms / track.item.duration_ms) * 100),\n music_album_art: track.item.album.images[0].url,\n updated_at: new Date().toISOString()\n }\n }\n];" + } + }, + { + "name": "Update Database", + "type": "n8n-nodes-base.postgres", + "parameters": { + "operation": "executeQuery", + "query": "UPDATE activity_status SET music_playing = $1, music_track = $2, music_artist = $3, music_album = $4, music_platform = $5, music_progress = $6, music_album_art = $7, updated_at = $8 WHERE id = 1" + } + } + ] +} +``` + +**Spotify API Setup:** +1. Gehe zu https://developer.spotify.com/dashboard +2. Create App +3. Add Redirect URI: `https://your-n8n-instance.com/oauth/callback` +4. Kopiere Client ID & Secret in n8n Credentials +5. Scopes: `user-read-currently-playing`, `user-read-playback-state` + +--- + +### Workflow 3: AI Chatbot mit OpenAI + +**Trigger:** Webhook bei Chat-Message + +```json +{ + "nodes": [ + { + "name": "Chat Webhook", + "type": "n8n-nodes-base.webhook", + "parameters": { + "path": "chat", + "method": "POST" + } + }, + { + "name": "Build Context", + "type": "n8n-nodes-base.function", + "parameters": { + "functionCode": "const userMessage = items[0].json.message;\n\nconst context = `You are Dennis Konkol's AI assistant. Here's information about Dennis:\n\n- Student in Osnabrück, Germany\n- Passionate self-hoster and DevOps enthusiast\n- Skills: Next.js, Flutter, Docker Swarm, Traefik, CI/CD, n8n\n- Runs own infrastructure on IONOS and OVHcloud\n- Projects: Clarity (Flutter dyslexia app), Self-hosted portfolio with Docker Swarm\n- Hobbies: Gaming, Jogging, Experimenting with tech\n- Fun fact: Uses pen & paper for calendar despite automating everything\n\nAnswer questions about Dennis professionally and friendly. Keep answers concise (2-3 sentences).\n\nUser question: ${userMessage}`;\n\nreturn [{ json: { context, userMessage } }];" + } + }, + { + "name": "OpenAI Chat", + "type": "n8n-nodes-base.openAi", + "parameters": { + "resource": "chat", + "operation": "message", + "model": "gpt-4", + "messages": { + "values": [ + { + "role": "system", + "content": "={{$node[\"Build Context\"].json[\"context\"]}}" + }, + { + "role": "user", + "content": "={{$node[\"Build Context\"].json[\"userMessage\"]}}" + } + ] + } + } + }, + { + "name": "Return Response", + "type": "n8n-nodes-base.respondToWebhook", + "parameters": { + "responseBody": "={{ { reply: $json.message.content } }}" + } + } + ] +} +``` + +**OpenAI API Setup:** +1. Gehe zu https://platform.openai.com/api-keys +2. Create API Key +3. Add zu n8n Credentials +4. Wähle Model: gpt-4 oder gpt-3.5-turbo + +--- + +### Workflow 4: Discord/Steam Gaming Status + +**Trigger:** Cron (alle 60 Sekunden) + +```json +{ + "nodes": [ + { + "name": "Schedule", + "type": "n8n-nodes-base.cron", + "parameters": { + "cronExpression": "0 * * * * *" + } + }, + { + "name": "Discord API", + "type": "n8n-nodes-base.httpRequest", + "parameters": { + "url": "https://discord.com/api/v10/users/@me", + "method": "GET", + "authentication": "oAuth2", + "headers": { + "Authorization": "Bot {{$credentials.discord.token}}" + } + } + }, + { + "name": "Parse Gaming Status", + "type": "n8n-nodes-base.function", + "parameters": { + "functionCode": "const user = items[0].json;\nconst activity = user.activities?.find(a => a.type === 0); // 0 = Playing\n\nif (!activity) {\n return [{ json: { gaming_game: null, gaming_status: 'idle' } }];\n}\n\nreturn [\n {\n json: {\n gaming_game: activity.name,\n gaming_platform: 'discord',\n gaming_status: 'playing',\n updated_at: new Date().toISOString()\n }\n }\n];" + } + }, + { + "name": "Update Database", + "type": "n8n-nodes-base.postgres", + "parameters": { + "operation": "executeQuery", + "query": "UPDATE activity_status SET gaming_game = $1, gaming_platform = $2, gaming_status = $3, updated_at = $4 WHERE id = 1" + } + } + ] +} +``` + +--- + +### Workflow 5: Smart Status (Auto-Detect) + +**Trigger:** Cron (alle 5 Minuten) + +```json +{ + "nodes": [ + { + "name": "Schedule", + "type": "n8n-nodes-base.cron", + "parameters": { + "cronExpression": "*/5 * * * *" + } + }, + { + "name": "Determine Status", + "type": "n8n-nodes-base.function", + "parameters": { + "functionCode": "const hour = new Date().getHours();\nconst day = new Date().getDay(); // 0 = Sunday, 6 = Saturday\n\nlet mood = '💻';\nlet message = 'Working on projects';\n\n// Sleep time (0-7 Uhr)\nif (hour >= 0 && hour < 7) {\n mood = '😴';\n message = 'Sleeping (probably dreaming of code)';\n}\n// Morning (7-9 Uhr)\nelse if (hour >= 7 && hour < 9) {\n mood = '☕';\n message = 'Morning coffee & catching up';\n}\n// Work time (9-17 Uhr, Mo-Fr)\nelse if (hour >= 9 && hour < 17 && day >= 1 && day <= 5) {\n mood = '💻';\n message = 'Deep work mode - coding & learning';\n}\n// Evening (17-22 Uhr)\nelse if (hour >= 17 && hour < 22) {\n mood = '🎮';\n message = 'Relaxing - gaming or watching shows';\n}\n// Late night (22-24 Uhr)\nelse if (hour >= 22) {\n mood = '🌙';\n message = 'Late night coding session';\n}\n// Weekend\nif (day === 0 || day === 6) {\n mood = '🏃';\n message = 'Weekend vibes - exploring & experimenting';\n}\n\nreturn [\n {\n json: {\n status_mood: mood,\n status_message: message,\n updated_at: new Date().toISOString()\n }\n }\n];" + } + }, + { + "name": "Update Database", + "type": "n8n-nodes-base.postgres", + "parameters": { + "operation": "executeQuery", + "query": "UPDATE activity_status SET status_mood = $1, status_message = $2, updated_at = $3 WHERE id = 1" + } + } + ] +} +``` + +--- + +## 🔌 Frontend API Integration + +### Update `/app/api/n8n/status/route.ts` + +```typescript +import { NextResponse } from 'next/server'; +import { PrismaClient } from '@prisma/client'; + +const prisma = new PrismaClient(); + +export async function GET() { + try { + // Fetch from your activity_status table + const status = await prisma.$queryRaw` + SELECT * FROM activity_status WHERE id = 1 LIMIT 1 + `; + + if (!status || status.length === 0) { + return NextResponse.json({ + activity: null, + music: null, + watching: null, + gaming: null, + status: null, + }); + } + + const data = status[0]; + + return NextResponse.json({ + activity: data.activity_type ? { + type: data.activity_type, + details: data.activity_details, + project: data.activity_project, + language: data.activity_language, + repo: data.activity_repo, + timestamp: data.updated_at, + } : null, + music: data.music_playing ? { + isPlaying: data.music_playing, + track: data.music_track, + artist: data.music_artist, + album: data.music_album, + platform: data.music_platform, + progress: data.music_progress, + albumArt: data.music_album_art, + } : null, + watching: data.watching_title ? { + title: data.watching_title, + platform: data.watching_platform, + type: data.watching_type, + } : null, + gaming: data.gaming_game ? { + game: data.gaming_game, + platform: data.gaming_platform, + status: data.gaming_status, + } : null, + status: data.status_mood ? { + mood: data.status_mood, + customMessage: data.status_message, + } : null, + }); + } catch (error) { + console.error('Error fetching activity status:', error); + return NextResponse.json({ + activity: null, + music: null, + watching: null, + gaming: null, + status: null, + }, { status: 500 }); + } +} +``` + +### Create `/app/api/n8n/chat/route.ts` + +```typescript +import { NextResponse } from 'next/server'; + +export async function POST(request: Request) { + try { + const { message } = await request.json(); + + // Call your n8n chat webhook + const response = await fetch(`${process.env.N8N_WEBHOOK_URL}/webhook/chat`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ message }), + }); + + if (!response.ok) { + throw new Error('n8n webhook failed'); + } + + const data = await response.json(); + return NextResponse.json({ reply: data.reply }); + } catch (error) { + console.error('Chat API error:', error); + return NextResponse.json( + { reply: 'Sorry, I encountered an error. Please try again later.' }, + { status: 500 } + ); + } +} +``` + +--- + +## 🌟 Zusätzliche coole Ideen + +### 1. **Live Coding Stats** +- Lines of code today +- Most used language this week +- GitHub contribution graph +- Pull requests merged + +### 2. **Coffee Counter** ☕ +- Button in n8n Dashboard: "I had coffee" +- Displays: "3 coffees today" +- Funny messages bei > 5 cups + +### 3. **Mood Tracker** +- Manual mood updates via Discord Bot +- Shows emoji + custom message +- Persists über den Tag + +### 4. **Auto-DND Status** +- Wenn du in einem Meeting bist (Calendar API) +- Wenn du fokussiert arbeitest (Pomodoro Timer) +- Custom status: "🔴 In Deep Work - Back at 15:00" + +### 5. **Project Highlights** +- "Currently building: X" +- "Deployed Y minutes ago" +- "Last successful build: Z" + +### 6. **Social Activity** +- "New blog post: Title" +- "Trending on Twitter: X mentions" +- "LinkedIn: Y profile views this week" + +--- + +## 📝 Environment Variables + +Add to `.env.local`: + +```bash +# n8n +N8N_WEBHOOK_URL=https://your-n8n-instance.com +N8N_API_KEY=your_n8n_api_key + +# Spotify +SPOTIFY_CLIENT_ID=your_spotify_client_id +SPOTIFY_CLIENT_SECRET=your_spotify_client_secret + +# OpenAI +OPENAI_API_KEY=your_openai_api_key + +# Discord (optional) +DISCORD_BOT_TOKEN=your_discord_bot_token + +# GitHub (optional) +GITHUB_WEBHOOK_SECRET=your_github_webhook_secret +``` + +--- + +## 🚀 Quick Start + +1. **Setup Database:** + ```bash + psql -U postgres -d portfolio_dev -f setup_activity_status.sql + ``` + +2. **Create n8n Workflows:** + - Import workflows via n8n UI + - Configure credentials + - Activate workflows + +3. **Update API Routes:** + - Add `status/route.ts` and `chat/route.ts` + - Set environment variables + +4. **Test:** + ```bash + npm run dev + ``` + - Check bottom-right corner for activity bubbles + - Click chat button to test AI + +--- + +## 🎯 Best Practices + +1. **Caching:** Cache API responses für 30s (nicht bei jedem Request neu fetchen) +2. **Error Handling:** Graceful fallbacks wenn n8n down ist +3. **Rate Limiting:** Limitiere Chat-Requests (max 10/minute) +4. **Privacy:** Zeige nur das, was du teilen willst +5. **Performance:** Nutze Webhooks statt Polling wo möglich + +--- + +## 🤝 Community Ideas + +Teile deine coolen n8n-Integrationen! +- Discord: Zeig deinen Setup +- GitHub: Share deine Workflows +- Blog: Write-up über dein System + +Happy automating! 🎉 \ No newline at end of file diff --git a/docs/ai-image-generation/ENVIRONMENT.md b/docs/ai-image-generation/ENVIRONMENT.md new file mode 100644 index 0000000..87c34e8 --- /dev/null +++ b/docs/ai-image-generation/ENVIRONMENT.md @@ -0,0 +1,311 @@ +# Environment Variables for AI Image Generation + +This document lists all environment variables needed for the AI image generation system. + +## Required Variables + +Add these to your `.env.local` file: + +```bash +# ============================================================================= +# AI IMAGE GENERATION CONFIGURATION +# ============================================================================= + +# n8n Webhook Configuration +# The base URL where your n8n instance is running +N8N_WEBHOOK_URL=http://localhost:5678/webhook + +# Secret token for authenticating webhook requests +# Generate a secure random token: openssl rand -hex 32 +N8N_SECRET_TOKEN=your-secure-random-token-here + +# Stable Diffusion API Configuration +# The URL where your Stable Diffusion WebUI is running +SD_API_URL=http://localhost:7860 + +# Optional: API key if your SD instance requires authentication +# SD_API_KEY=your-sd-api-key-here + +# ============================================================================= +# IMAGE GENERATION SETTINGS +# ============================================================================= + +# Automatically generate images when new projects are created +# Set to 'true' to enable, 'false' to disable +AUTO_GENERATE_IMAGES=true + +# Directory where generated images will be saved +# Should be inside your public directory for web access +GENERATED_IMAGES_DIR=/app/public/generated-images + +# Maximum time to wait for image generation (in milliseconds) +# Default: 180000 (3 minutes) +IMAGE_GENERATION_TIMEOUT=180000 + +# ============================================================================= +# STABLE DIFFUSION SETTINGS (Optional - Overrides n8n workflow defaults) +# ============================================================================= + +# Default image dimensions +SD_DEFAULT_WIDTH=1024 +SD_DEFAULT_HEIGHT=768 + +# Generation quality settings +SD_DEFAULT_STEPS=30 +SD_DEFAULT_CFG_SCALE=7 + +# Sampler algorithm +# Options: "Euler a", "DPM++ 2M Karras", "DDIM", etc. +SD_DEFAULT_SAMPLER=DPM++ 2M Karras + +# Default model checkpoint +# SD_DEFAULT_MODEL=sd_xl_base_1.0.safetensors + +# ============================================================================= +# FEATURE FLAGS (Optional) +# ============================================================================= + +# Enable/disable specific features +ENABLE_IMAGE_REGENERATION=true +ENABLE_BATCH_GENERATION=false +ENABLE_IMAGE_OPTIMIZATION=true + +# ============================================================================= +# LOGGING & MONITORING (Optional) +# ============================================================================= + +# Log all image generation requests +LOG_IMAGE_GENERATION=true + +# Send notifications on generation success/failure +# DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/... +# SLACK_WEBHOOK_URL=https://hooks.slack.com/services/... + +# ============================================================================= +# ADVANCED SETTINGS (Optional) +# ============================================================================= + +# Custom prompt prefix for all generations +# SD_CUSTOM_PROMPT_PREFIX=professional tech illustration, modern design, + +# Custom negative prompt suffix for all generations +# SD_CUSTOM_NEGATIVE_SUFFIX=low quality, blurry, pixelated, text, watermark + +# Image file naming pattern +# Available variables: {projectId}, {timestamp}, {title} +IMAGE_FILENAME_PATTERN=project-{projectId}-{timestamp}.png + +# Maximum concurrent image generation requests +MAX_CONCURRENT_GENERATIONS=2 + +# Retry failed generations +AUTO_RETRY_ON_FAILURE=true +MAX_RETRY_ATTEMPTS=3 +``` + +## Production Environment + +For production deployments, adjust these settings: + +```bash +# Production n8n (if using cloud/dedicated instance) +N8N_WEBHOOK_URL=https://n8n.yourdomain.com/webhook + +# Production Stable Diffusion (if using dedicated GPU server) +SD_API_URL=https://sd-api.yourdomain.com + +# Production image storage (use absolute path) +GENERATED_IMAGES_DIR=/var/www/portfolio/public/generated-images + +# Disable auto-generation in production (manual only) +AUTO_GENERATE_IMAGES=false + +# Enable logging +LOG_IMAGE_GENERATION=true + +# Set timeouts appropriately +IMAGE_GENERATION_TIMEOUT=300000 + +# Limit concurrent generations +MAX_CONCURRENT_GENERATIONS=1 +``` + +## Docker Environment + +If running in Docker, use these paths: + +```bash +# Docker-specific paths +N8N_WEBHOOK_URL=http://n8n:5678/webhook +SD_API_URL=http://stable-diffusion:7860 +GENERATED_IMAGES_DIR=/app/public/generated-images +``` + +Add to `docker-compose.yml`: + +```yaml +services: + portfolio: + environment: + - N8N_WEBHOOK_URL=http://n8n:5678/webhook + - N8N_SECRET_TOKEN=${N8N_SECRET_TOKEN} + - SD_API_URL=http://stable-diffusion:7860 + - AUTO_GENERATE_IMAGES=true + - GENERATED_IMAGES_DIR=/app/public/generated-images + volumes: + - ./public/generated-images:/app/public/generated-images + + n8n: + image: n8nio/n8n + ports: + - "5678:5678" + environment: + - N8N_BASIC_AUTH_ACTIVE=true + - N8N_BASIC_AUTH_USER=admin + - N8N_BASIC_AUTH_PASSWORD=${N8N_PASSWORD} + + stable-diffusion: + image: your-sd-webui-image + ports: + - "7860:7860" + deploy: + resources: + reservations: + devices: + - driver: nvidia + count: 1 + capabilities: [gpu] +``` + +## Cloud GPU Configuration + +If using cloud GPU services (RunPod, vast.ai, etc.): + +```bash +# Remote GPU URL with authentication +SD_API_URL=https://your-runpod-instance.com:7860 +SD_API_KEY=your-api-key-here + +# Longer timeout for network latency +IMAGE_GENERATION_TIMEOUT=300000 +``` + +## Security Best Practices + +1. **Never commit `.env.local` to version control** + ```bash + # Add to .gitignore + echo ".env.local" >> .gitignore + ``` + +2. **Generate secure tokens** + ```bash + # Generate N8N_SECRET_TOKEN + openssl rand -hex 32 + + # Or using Node.js + node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" + ``` + +3. **Restrict API access** + - Use firewall rules to limit SD API access + - Enable authentication on n8n webhooks + - Use HTTPS in production + +4. **Environment-specific files** + - `.env.local` - local development + - `.env.production` - production (server-side only) + - `.env.test` - testing environment + +## Verifying Configuration + +Test your environment variables: + +```bash +# Check if variables are loaded +npm run dev + +# In another terminal +node -e " +const envFile = require('fs').readFileSync('.env.local', 'utf8'); +console.log('✓ .env.local exists'); +console.log('✓ Variables found:', envFile.split('\\n').filter(l => l && !l.startsWith('#')).length); +" + +# Test n8n connection +curl -f $N8N_WEBHOOK_URL/health || echo "n8n not reachable" + +# Test SD API connection +curl -f $SD_API_URL/sdapi/v1/sd-models || echo "SD API not reachable" +``` + +## Troubleshooting + +### Variables not loading + +```bash +# Ensure .env.local is in the project root +ls -la .env.local + +# Restart Next.js dev server +npm run dev +``` + +### Wrong paths in Docker + +```bash +# Check volume mounts +docker-compose exec portfolio ls -la /app/public/generated-images + +# Fix permissions +docker-compose exec portfolio chmod 755 /app/public/generated-images +``` + +### n8n webhook unreachable + +```bash +# Check n8n is running +docker ps | grep n8n + +# Check network connectivity +docker-compose exec portfolio ping n8n + +# Verify webhook URL in n8n UI +``` + +## Example Complete Configuration + +```bash +# .env.local - Complete working example + +# Database (required for project data) +DATABASE_URL=postgresql://user:password@localhost:5432/portfolio + +# NextAuth (if using authentication) +NEXTAUTH_URL=http://localhost:3000 +NEXTAUTH_SECRET=your-nextauth-secret + +# AI Image Generation +N8N_WEBHOOK_URL=http://localhost:5678/webhook +N8N_SECRET_TOKEN=a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6 +SD_API_URL=http://localhost:7860 +AUTO_GENERATE_IMAGES=true +GENERATED_IMAGES_DIR=/Users/dennis/code/gitea/portfolio/public/generated-images + +# Image settings +SD_DEFAULT_WIDTH=1024 +SD_DEFAULT_HEIGHT=768 +SD_DEFAULT_STEPS=30 +SD_DEFAULT_CFG_SCALE=7 +SD_DEFAULT_SAMPLER=DPM++ 2M Karras + +# Optional features +ENABLE_IMAGE_REGENERATION=true +LOG_IMAGE_GENERATION=true +IMAGE_GENERATION_TIMEOUT=180000 +MAX_CONCURRENT_GENERATIONS=2 +``` + +--- + +**Note**: Always keep your `.env.local` file secure and never share tokens publicly! \ No newline at end of file diff --git a/docs/ai-image-generation/PROMPT_TEMPLATES.md b/docs/ai-image-generation/PROMPT_TEMPLATES.md new file mode 100644 index 0000000..545ffa5 --- /dev/null +++ b/docs/ai-image-generation/PROMPT_TEMPLATES.md @@ -0,0 +1,612 @@ +# AI Image Generation Prompt Templates + +This document contains optimized prompt templates for different project categories to ensure consistent, high-quality AI-generated images. + +## Template Structure + +Each template follows this structure: +- **Base Prompt**: Core visual elements and style +- **Technical Keywords**: Category-specific terminology +- **Color Palette**: Recommended colors for the category +- **Negative Prompt**: Elements to avoid +- **Recommended Model**: Best SD model for this category + +--- + +## Web Application Projects + +### Base Prompt +``` +modern web application interface, clean dashboard UI, sleek web design, +gradient backgrounds, glass morphism effect, floating panels, +data visualization charts, modern typography, +soft shadows, depth layers, isometric perspective, +professional tech aesthetic, vibrant interface elements, +smooth gradients, minimalist composition, +4k resolution, high quality digital art +``` + +### Technical Keywords +- SaaS dashboard, web portal, admin panel +- Interactive UI elements, responsive design +- Navigation bars, sidebars, cards +- Progress indicators, status badges + +### Color Palette +- Primary: `#3B82F6` (Blue), `#8B5CF6` (Purple) +- Secondary: `#06B6D4` (Cyan), `#EC4899` (Pink) +- Accent: `#10B981` (Green), `#F59E0B` (Amber) + +### Negative Prompt +``` +mobile phone, smartphone, app mockup, tablet, +realistic photo, stock photo, people, faces, +cluttered, messy, dark, gloomy, text, watermark +``` + +### Recommended Model +- SDXL Base 1.0 +- DreamShaper 8 + +--- + +## Mobile Application Projects + +### Base Prompt +``` +modern mobile app interface mockup, sleek smartphone design, +iOS or Android app screen, mobile UI elements, +app icons grid, notification badges, bottom navigation, +touch gestures indicators, smooth animations preview, +gradient app background, modern mobile design trends, +floating action button, card-based layout, +professional mobile photography, studio lighting, +4k quality, trending on dribbble +``` + +### Technical Keywords +- Native app, cross-platform, Flutter, React Native +- Mobile-first design, touch interface +- Swipe gestures, pull-to-refresh +- Push notifications, app widgets + +### Color Palette +- Primary: `#6366F1` (Indigo), `#EC4899` (Pink) +- Secondary: `#8B5CF6` (Purple), `#06B6D4` (Cyan) +- Accent: `#F59E0B` (Amber), `#EF4444` (Red) + +### Negative Prompt +``` +desktop interface, web browser, laptop, monitor, +desktop computer, keyboard, mouse, +old phone, cracked screen, low resolution, +text, watermark, people holding phones +``` + +### Recommended Model +- Realistic Vision V5.1 +- Juggernaut XL + +--- + +## DevOps & Infrastructure Projects + +### Base Prompt +``` +cloud infrastructure visualization, modern server architecture diagram, +Docker containers network, Kubernetes cluster illustration, +CI/CD pipeline flowchart, automated deployment system, +interconnected server nodes, data flow arrows, +cloud services icons, microservices architecture, +network topology, distributed systems, +glowing connections, tech blueprint style, +isometric technical illustration, cyberpunk aesthetic, +blue and orange tech colors, professional diagram +``` + +### Technical Keywords +- Docker Swarm, Kubernetes, container orchestration +- CI/CD pipeline, Jenkins, GitHub Actions +- Cloud architecture, AWS, Azure, GCP +- Monitoring dashboard, Grafana, Prometheus + +### Color Palette +- Primary: `#0EA5E9` (Sky Blue), `#F97316` (Orange) +- Secondary: `#06B6D4` (Cyan), `#8B5CF6` (Purple) +- Accent: `#10B981` (Green), `#EF4444` (Red) + +### Negative Prompt +``` +realistic datacenter photo, physical servers, +people, technicians, hands, cables mess, +dark server room, blurry, low quality, +text labels, company logos, watermark +``` + +### Recommended Model +- SDXL Base 1.0 +- DreamShaper 8 + +--- + +## Backend & API Projects + +### Base Prompt +``` +API architecture visualization, RESTful endpoints diagram, +database schema illustration, data flow architecture, +server-side processing, microservices connections, +API gateway, request-response flow, +JSON data structures, GraphQL schema visualization, +modern backend architecture, technical blueprint, +glowing data streams, interconnected services, +professional tech diagram, isometric view, +clean composition, high quality illustration +``` + +### Technical Keywords +- REST API, GraphQL, WebSocket +- Microservices, serverless functions +- Database architecture, SQL, NoSQL +- Authentication, JWT, OAuth + +### Color Palette +- Primary: `#8B5CF6` (Purple), `#06B6D4` (Cyan) +- Secondary: `#3B82F6` (Blue), `#10B981` (Green) +- Accent: `#F59E0B` (Amber), `#EC4899` (Pink) + +### Negative Prompt +``` +frontend UI, user interface, buttons, forms, +people, faces, hands, realistic photo, +messy cables, physical hardware, +text, code snippets, watermark +``` + +### Recommended Model +- SDXL Base 1.0 +- DreamShaper 8 + +--- + +## AI & Machine Learning Projects + +### Base Prompt +``` +artificial intelligence concept art, neural network visualization, +glowing AI nodes and connections, machine learning algorithm, +data science visualization, deep learning architecture, +brain-inspired computing, futuristic AI interface, +holographic data displays, floating neural pathways, +AI chip design, quantum computing aesthetic, +particle systems, energy flows, digital consciousness, +sci-fi technology, purple and cyan neon lighting, +high-tech laboratory, 4k quality, cinematic lighting +``` + +### Technical Keywords +- Neural networks, deep learning, TensorFlow +- Computer vision, NLP, transformers +- Model training, GPU acceleration +- AI agents, reinforcement learning + +### Color Palette +- Primary: `#8B5CF6` (Purple), `#EC4899` (Pink) +- Secondary: `#06B6D4` (Cyan), `#3B82F6` (Blue) +- Accent: `#A855F7` (Fuchsia), `#14B8A6` (Teal) + +### Negative Prompt +``` +realistic lab photo, scientists, people, faces, +physical robots, mechanical parts, +cluttered, messy, text, formulas, equations, +low quality, dark, gloomy, stock photo +``` + +### Recommended Model +- SDXL Base 1.0 +- Juggernaut XL + +--- + +## Game Development Projects + +### Base Prompt +``` +game environment scene, 3D rendered game world, +video game interface, game UI overlay, HUD elements, +fantasy game landscape, sci-fi game setting, +character perspective view, gaming atmosphere, +dynamic lighting, particle effects, atmospheric fog, +game asset showcase, level design preview, +cinematic game screenshot, unreal engine quality, +vibrant game colors, epic composition, +4k game graphics, trending on artstation +``` + +### Technical Keywords +- Unity, Unreal Engine, game engine +- 3D modeling, texture mapping, shaders +- Game mechanics, physics engine +- Multiplayer, networking, matchmaking + +### Color Palette +- Primary: `#EF4444` (Red), `#F59E0B` (Amber) +- Secondary: `#8B5CF6` (Purple), `#06B6D4` (Cyan) +- Accent: `#10B981` (Green), `#EC4899` (Pink) + +### Negative Prompt +``` +real photo, realistic photography, real people, +mobile game screenshot, casual game, +low poly, pixelated, retro graphics, +text, game title, logos, watermark +``` + +### Recommended Model +- Juggernaut XL +- DreamShaper 8 + +--- + +## Blockchain & Crypto Projects + +### Base Prompt +``` +blockchain network visualization, cryptocurrency concept art, +distributed ledger technology, decentralized network nodes, +crypto mining visualization, digital currency symbols, +smart contracts interface, DeFi platform design, +glowing blockchain connections, cryptographic security, +web3 technology aesthetic, neon blockchain grid, +futuristic finance, holographic crypto data, +clean modern composition, professional tech illustration, +blue and gold color scheme, high quality render +``` + +### Technical Keywords +- Smart contracts, Solidity, Ethereum +- DeFi, NFT, token economics +- Consensus mechanisms, proof of stake +- Web3, dApp, wallet integration + +### Color Palette +- Primary: `#F59E0B` (Gold), `#3B82F6` (Blue) +- Secondary: `#8B5CF6` (Purple), `#10B981` (Green) +- Accent: `#06B6D4` (Cyan), `#EC4899` (Pink) + +### Negative Prompt +``` +real coins, physical money, paper currency, +people, traders, faces, hands, +stock market photo, trading floor, +text, ticker symbols, logos, watermark +``` + +### Recommended Model +- SDXL Base 1.0 +- Juggernaut XL + +--- + +## IoT & Hardware Projects + +### Base Prompt +``` +Internet of Things network, smart home devices connected, +IoT sensor network, embedded systems visualization, +smart device ecosystem, wireless communication, +connected hardware illustration, automation network, +sensor data visualization, edge computing nodes, +modern tech devices, clean product design, +isometric hardware illustration, minimalist tech aesthetic, +glowing connection lines, mesh network topology, +professional product photography, studio lighting +``` + +### Technical Keywords +- Raspberry Pi, Arduino, ESP32 +- Sensor networks, MQTT, edge computing +- Smart home, automation, wireless protocols +- Embedded systems, firmware, microcontrollers + +### Color Palette +- Primary: `#10B981` (Green), `#06B6D4` (Cyan) +- Secondary: `#3B82F6` (Blue), `#8B5CF6` (Purple) +- Accent: `#F59E0B` (Amber), `#EC4899` (Pink) + +### Negative Prompt +``` +messy wiring, cluttered breadboard, realistic lab photo, +people, hands holding devices, technicians, +old electronics, broken hardware, +text, labels, brand names, watermark +``` + +### Recommended Model +- Realistic Vision V5.1 +- Juggernaut XL + +--- + +## Security & Cybersecurity Projects + +### Base Prompt +``` +cybersecurity concept art, digital security shield, +encrypted data streams, firewall visualization, +network security diagram, threat detection system, +secure connection network, cryptography illustration, +cyber defense interface, security monitoring dashboard, +glowing security barriers, protected data vault, +ethical hacking interface, penetration testing tools, +dark mode tech aesthetic, green matrix-style code, +professional security illustration, high-tech composition +``` + +### Technical Keywords +- Penetration testing, vulnerability scanning +- Firewall, IDS/IPS, SIEM +- Encryption, SSL/TLS, zero trust +- Security monitoring, threat intelligence + +### Color Palette +- Primary: `#10B981` (Green), `#0EA5E9` (Sky Blue) +- Secondary: `#8B5CF6` (Purple), `#EF4444` (Red) +- Accent: `#F59E0B` (Amber), `#06B6D4` (Cyan) + +### Negative Prompt +``` +realistic office photo, security guards, people, +physical locks, keys, cameras, +dark, scary, threatening, ominous, +text, code snippets, terminal text, watermark +``` + +### Recommended Model +- SDXL Base 1.0 +- DreamShaper 8 + +--- + +## Data Science & Analytics Projects + +### Base Prompt +``` +data visualization dashboard, analytics interface, +big data processing, statistical charts and graphs, +machine learning insights, predictive analytics, +data pipeline illustration, ETL process visualization, +interactive data dashboard, business intelligence, +colorful data charts, infographic elements, +modern analytics design, clean data presentation, +professional data visualization, gradient backgrounds, +isometric data center, flowing information streams +``` + +### Technical Keywords +- Data pipeline, ETL, data warehouse +- BI dashboard, Tableau, Power BI +- Statistical analysis, data mining +- Pandas, NumPy, data processing + +### Color Palette +- Primary: `#3B82F6` (Blue), `#8B5CF6` (Purple) +- Secondary: `#06B6D4` (Cyan), `#10B981` (Green) +- Accent: `#EC4899` (Pink), `#F59E0B` (Amber) + +### Negative Prompt +``` +spreadsheet screenshot, Excel interface, +people analyzing data, hands, faces, +cluttered charts, messy graphs, confusing layout, +text labels, numbers, watermark, low quality +``` + +### Recommended Model +- SDXL Base 1.0 +- DreamShaper 8 + +--- + +## E-commerce & Marketplace Projects + +### Base Prompt +``` +modern e-commerce platform interface, online shopping design, +product showcase grid, shopping cart visualization, +payment system interface, marketplace dashboard, +product cards layout, checkout flow design, +clean storefront design, modern retail aesthetic, +shopping bag icons, product imagery, price tags design, +conversion-optimized layout, mobile commerce, +professional e-commerce photography, studio product shots, +vibrant shopping experience, user-friendly interface +``` + +### Technical Keywords +- Online store, payment gateway, Stripe +- Product catalog, inventory management +- Shopping cart, checkout flow, conversion +- Marketplace platform, vendor management + +### Color Palette +- Primary: `#EC4899` (Pink), `#F59E0B` (Amber) +- Secondary: `#8B5CF6` (Purple), `#10B981` (Green) +- Accent: `#3B82F6` (Blue), `#EF4444` (Red) + +### Negative Prompt +``` +realistic store photo, physical shop, retail store, +people shopping, customers, cashiers, hands, +cluttered shelves, messy products, +text prices, brand logos, watermark +``` + +### Recommended Model +- Realistic Vision V5.1 +- Juggernaut XL + +--- + +## Automation & Workflow Projects + +### Base Prompt +``` +workflow automation visualization, process flow diagram, +automated pipeline illustration, task orchestration, +business process automation, workflow nodes connected, +integration platform design, automation dashboard, +robotic process automation, efficiency visualization, +streamlined processes, gear mechanisms, conveyor systems, +modern workflow interface, productivity tools, +clean automation design, professional illustration, +isometric process view, smooth gradient backgrounds +``` + +### Technical Keywords +- n8n, Zapier, workflow automation +- Integration platform, API orchestration +- Task scheduling, cron jobs, triggers +- Business process automation, RPA + +### Color Palette +- Primary: `#8B5CF6` (Purple), `#06B6D4` (Cyan) +- Secondary: `#10B981` (Green), `#3B82F6` (Blue) +- Accent: `#F59E0B` (Amber), `#EC4899` (Pink) + +### Negative Prompt +``` +realistic factory photo, physical machinery, +people working, hands, faces, workers, +cluttered, messy, industrial setting, +text, labels, watermark, low quality +``` + +### Recommended Model +- SDXL Base 1.0 +- DreamShaper 8 + +--- + +## Universal Negative Prompt + +Use this as a base for all generations: + +``` +low quality, blurry, pixelated, grainy, jpeg artifacts, compression artifacts, +text, letters, words, numbers, watermark, signature, copyright, logo, brand name, +people, person, human, face, faces, hands, fingers, arms, body parts, +portrait, selfie, crowd, group of people, +cluttered, messy, chaotic, disorganized, busy, overwhelming, +dark, gloomy, depressing, scary, ominous, threatening, +ugly, distorted, deformed, mutation, extra limbs, bad anatomy, +realistic photo, stock photo, photograph, camera phone, +duplicate, duplication, repetitive, copied elements, +old, outdated, vintage, retro (unless specifically wanted), +screenshot, UI screenshot, browser window +``` + +--- + +## Prompt Engineering Best Practices + +### 1. Specificity Matters +- Be specific about visual elements you want +- Include style keywords: "isometric", "minimalist", "modern" +- Specify quality: "4k resolution", "high quality", "professional" + +### 2. Weight Distribution +- Most important elements should be early in the prompt +- Use emphasis syntax if your tool supports it: `(keyword:1.2)` or `((keyword))` + +### 3. Category Mixing +- Combine multiple category templates for hybrid projects +- Example: AI + Web App = neural network + modern dashboard UI + +### 4. Color Psychology +- **Blue**: Trust, technology, corporate +- **Purple**: Innovation, creativity, luxury +- **Green**: Growth, success, eco-friendly +- **Orange**: Energy, action, excitement +- **Pink**: Modern, playful, creative + +### 5. Consistency +- Use the same negative prompt across all generations +- Maintain consistent aspect ratios (4:3 for project cards) +- Stick to similar quality settings + +### 6. A/B Testing +- Generate 2-3 variants with slightly different prompts +- Test which style resonates better with your audience +- Refine prompts based on results + +--- + +## Advanced Techniques + +### ControlNet Integration +If using ControlNet, you can guide composition: +- Use Canny edge detection for layout control +- Use Depth maps for 3D perspective +- Use OpenPose for element positioning + +### Multi-Stage Generation +1. Generate base composition at lower resolution (512x512) +2. Upscale using img2img with same prompt +3. Apply post-processing (sharpening, color grading) + +### Style Consistency +To maintain consistent style across all project images: +``` +Add to every prompt: +"in the style of modern tech illustration, consistent design language, +professional portfolio aesthetic, cohesive visual identity" +``` + +--- + +## Troubleshooting Common Issues + +### Issue: Too Abstract / Not Related to Project +**Solution**: Add more specific technical keywords from project description + +### Issue: Text Appearing in Images +**Solution**: Add multiple text-related terms to negative prompt: +`text, letters, words, typography, font, writing, characters` + +### Issue: Dark or Poorly Lit +**Solution**: Add lighting keywords: +`studio lighting, bright, well-lit, soft lighting, professional lighting` + +### Issue: Cluttered Composition +**Solution**: Add composition keywords: +`clean composition, minimalist, negative space, centered, balanced, organized` + +### Issue: Wrong Aspect Ratio +**Solution**: Specify dimensions explicitly in generation settings: +- Cards: 1024x768 (4:3) +- Hero: 1920x1080 (16:9) +- Square: 1024x1024 (1:1) + +--- + +## Quick Reference Card + +| Category | Primary Colors | Key Style | Model | +|----------|---------------|-----------|-------| +| Web | Blue, Purple | Glass UI | SDXL | +| Mobile | Indigo, Pink | Mockup | Realistic Vision | +| DevOps | Cyan, Orange | Diagram | SDXL | +| AI/ML | Purple, Cyan | Futuristic | SDXL | +| Game | Red, Amber | Cinematic | Juggernaut | +| Blockchain | Gold, Blue | Neon | SDXL | +| IoT | Green, Cyan | Product | Realistic Vision | +| Security | Green, Blue | Dark Tech | SDXL | +| Data | Blue, Purple | Charts | SDXL | + +--- + +**Last Updated**: 2024 +**Version**: 1.0 +**Maintained by**: Portfolio AI Image Generation System \ No newline at end of file diff --git a/docs/ai-image-generation/QUICKSTART.md b/docs/ai-image-generation/QUICKSTART.md new file mode 100644 index 0000000..3399ca7 --- /dev/null +++ b/docs/ai-image-generation/QUICKSTART.md @@ -0,0 +1,366 @@ +# Quick Start Guide: AI Image Generation + +Get AI-powered project images up and running in 15 minutes. + +## Prerequisites + +- Docker installed +- 8GB+ RAM +- GPU recommended (NVIDIA with CUDA support) +- Node.js 18+ for portfolio app + +## Step 1: Install Stable Diffusion WebUI (5 min) + +```bash +# Clone the repository +git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git +cd stable-diffusion-webui + +# Run with API enabled +./webui.sh --api --listen + +# For low VRAM GPUs (< 8GB) +./webui.sh --api --listen --medvram + +# Wait for model download and startup +# Access WebUI at: http://localhost:7860 +``` + +## Step 2: Download a Model (3 min) + +Open WebUI at `http://localhost:7860` and download a model: + +**Option A: Via WebUI** +1. Go to **Checkpoint Merger** tab +2. Click **Model Download** +3. Enter: `stabilityai/stable-diffusion-xl-base-1.0` +4. Wait for download (6.94 GB) + +**Option B: Manual Download** +```bash +cd models/Stable-diffusion/ +wget https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0.safetensors +``` + +## Step 3: Test Stable Diffusion API (1 min) + +```bash +curl -X POST http://localhost:7860/sdapi/v1/txt2img \ + -H "Content-Type: application/json" \ + -d '{ + "prompt": "modern tech dashboard, blue gradient, minimalist design", + "steps": 20, + "width": 512, + "height": 512 + }' | jq '.images[0]' | base64 -d > test.png +``` + +Open `test.png` - if you see an image, API is working! ✅ + +## Step 4: Setup n8n (2 min) + +```bash +# Docker Compose method +docker run -d \ + --name n8n \ + -p 5678:5678 \ + -v ~/.n8n:/home/node/.n8n \ + n8nio/n8n + +# Wait 30 seconds for startup +# Access n8n at: http://localhost:5678 +``` + +## Step 5: Import Workflow (1 min) + +1. Open n8n at `http://localhost:5678` +2. Create account (first time only) +3. Click **+ New Workflow** +4. Click **⋮** (three dots) → **Import from File** +5. Select `docs/ai-image-generation/n8n-workflow-ai-image-generator.json` +6. Click **Save** + +## Step 6: Configure Workflow (2 min) + +### A. Add PostgreSQL Credentials +1. Click **Get Project Data** node +2. Click **Credential to connect with** +3. Enter your database credentials: + - Host: `localhost` (or your DB host) + - Database: `portfolio` + - User: `your_username` + - Password: `your_password` +4. Click **Save** + +### B. Configure Stable Diffusion URL +1. Click **Generate Image (Stable Diffusion)** node +2. Update URL to: `http://localhost:7860/sdapi/v1/txt2img` +3. If SD is on different machine: `http://YOUR_SD_IP:7860/sdapi/v1/txt2img` + +### C. Set Webhook Authentication +1. Click **Webhook Trigger** node +2. Click **Add Credential** +3. Set header: `Authorization` +4. Set value: `Bearer your-secret-token-here` +5. Save this token - you'll need it! + +### D. Update Image Save Path +1. Click **Save Image to File** node +2. Update `uploadDir` path to your portfolio's public folder: + ```javascript + const uploadDir = '/path/to/portfolio/public/generated-images'; + ``` + +## Step 7: Create Directory for Images (1 min) + +```bash +cd /path/to/portfolio +mkdir -p public/generated-images +chmod 755 public/generated-images +``` + +## Step 8: Add Environment Variables (1 min) + +Add to `portfolio/.env.local`: + +```bash +# n8n Webhook Configuration +N8N_WEBHOOK_URL=http://localhost:5678/webhook +N8N_SECRET_TOKEN=your-secret-token-here + +# Stable Diffusion API +SD_API_URL=http://localhost:7860 + +# Auto-generate images for new projects +AUTO_GENERATE_IMAGES=true + +# Image storage +GENERATED_IMAGES_DIR=/path/to/portfolio/public/generated-images +``` + +## Step 9: Test the Full Pipeline (2 min) + +```bash +# Start your portfolio app +cd portfolio +npm run dev + +# In another terminal, trigger image generation +curl -X POST http://localhost:5678/webhook/ai-image-generation \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer your-secret-token-here" \ + -d '{ + "projectId": 1 + }' + +# Check response (should take 15-30 seconds) +# Response example: +# { +# "success": true, +# "projectId": 1, +# "imageUrl": "/generated-images/project-1-1234567890.png", +# "generatedAt": "2024-01-15T10:30:00Z" +# } +``` + +## Step 10: Verify Image (1 min) + +```bash +# Check if image was created +ls -lh public/generated-images/ + +# Open in browser +open http://localhost:3000/generated-images/project-1-*.png +``` + +You should see a generated image! 🎉 + +--- + +## Using the Admin UI + +If you created the admin component: + +1. Navigate to your admin page (create one if needed) +2. Add the AI Image Generator component: + +```tsx +import AIImageGenerator from '@/app/components/admin/AIImageGenerator'; + + console.log('Generated:', url)} +/> +``` + +3. Click **Generate Image** button +4. Wait 15-30 seconds +5. Image appears automatically! + +--- + +## Automatic Generation on New Projects + +Add this to your project creation API: + +```typescript +// In portfolio/app/api/projects/route.ts (or similar) + +export async function POST(req: Request) { + // ... your project creation code ... + + const newProject = await createProject(data); + + // Trigger AI image generation + if (process.env.AUTO_GENERATE_IMAGES === 'true') { + fetch(`${process.env.N8N_WEBHOOK_URL}/ai-image-generation`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${process.env.N8N_SECRET_TOKEN}` + }, + body: JSON.stringify({ projectId: newProject.id }) + }).catch(err => console.error('AI generation failed:', err)); + } + + return NextResponse.json(newProject); +} +``` + +--- + +## Troubleshooting + +### "Connection refused to localhost:7860" +```bash +# Check if SD WebUI is running +ps aux | grep webui + +# Restart with API flag +cd stable-diffusion-webui +./webui.sh --api --listen +``` + +### "CUDA out of memory" +```bash +# Restart with lower VRAM usage +./webui.sh --api --listen --medvram + +# Or even lower +./webui.sh --api --listen --lowvram +``` + +### "n8n workflow fails at database step" +- Check PostgreSQL is running: `pg_isready` +- Verify credentials in n8n node +- Check database connection from terminal: + ```bash + psql -h localhost -U your_username -d portfolio + ``` + +### "Image saves but doesn't appear on website" +- Check directory permissions: `chmod 755 public/generated-images` +- Verify path in n8n workflow matches portfolio structure +- Check Next.js static files config in `next.config.js` + +### "Generated images are low quality" +Edit n8n workflow's SD node, increase: +- `steps`: 20 → 40 +- `cfg_scale`: 7 → 9 +- `width/height`: 512 → 1024 + +### "Images don't match project theme" +Edit **Build AI Prompt** node in n8n: +- Add more specific technical keywords +- Include project category in style description +- Adjust color palette keywords + +--- + +## Next Steps + +✅ **You're done!** Images now generate automatically. + +**Optional Enhancements:** + +1. **Batch Generate**: Generate images for all existing projects + ```bash + # Create a script: scripts/batch-generate-images.ts + for projectId in $(psql -t -c "SELECT id FROM projects WHERE image_url IS NULL"); do + curl -X POST http://localhost:5678/webhook/ai-image-generation \ + -H "Authorization: Bearer $N8N_SECRET_TOKEN" \ + -d "{\"projectId\": $projectId}" + sleep 30 # Wait for generation + done + ``` + +2. **Custom Models**: Download specialized models for better results + - `dreamshaper_8.safetensors` for web/UI projects + - `realisticVision_v51.safetensors` for product shots + - `juggernautXL_v8.safetensors` for modern tech aesthetics + +3. **Prompt Refinement**: Edit prompt templates in n8n workflow + - Check `docs/ai-image-generation/PROMPT_TEMPLATES.md` + - Test different styles for your brand + +4. **Monitoring**: Set up logging and alerts + - Add Discord/Slack notifications to n8n workflow + - Log generation stats to analytics + +5. **Optimization**: Compress images after generation + ```bash + npm install sharp + # Add post-processing step to n8n workflow + ``` + +--- + +## Performance Benchmarks + +| Hardware | Generation Time | Image Quality | +|----------|----------------|---------------| +| RTX 4090 | ~8 seconds | Excellent | +| RTX 3080 | ~15 seconds | Excellent | +| RTX 3060 | ~25 seconds | Good | +| GTX 1660 | ~45 seconds | Good | +| CPU only | ~5 minutes | Fair | + +**Recommended**: RTX 3060 or better for production use. + +--- + +## Cost Analysis + +**Local Setup (One-time):** +- GPU (RTX 3060): ~$300-400 +- OR Cloud GPU (RunPod, vast.ai): $0.20-0.50/hour + +**Per Image Cost:** +- Local: $0.00 (electricity ~$0.001) +- Cloud GPU: ~$0.01-0.02 per image + +**vs. Commercial APIs:** +- DALL-E 3: $0.04 per image +- Midjourney: ~$0.06 per image (with subscription) +- Stable Diffusion API: $0.02 per image + +💡 **Break-even**: After ~500 images, local setup pays for itself! + +--- + +## Support & Resources + +- **Documentation**: `docs/ai-image-generation/SETUP.md` +- **Prompt Templates**: `docs/ai-image-generation/PROMPT_TEMPLATES.md` +- **SD WebUI Wiki**: https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki +- **n8n Documentation**: https://docs.n8n.io +- **Community Discord**: [Your Discord link] + +**Need Help?** Open an issue or reach out! + +--- + +**Total Setup Time**: ~15 minutes +**Result**: Automatic AI-generated project images 🎨✨ \ No newline at end of file diff --git a/docs/ai-image-generation/README.md b/docs/ai-image-generation/README.md new file mode 100644 index 0000000..4d5a197 --- /dev/null +++ b/docs/ai-image-generation/README.md @@ -0,0 +1,423 @@ +# AI Image Generation System + +Automatically generate stunning project cover images using local AI models. + +![AI Generated](https://img.shields.io/badge/AI-Generated-purple?style=flat-square) +![Stable Diffusion](https://img.shields.io/badge/Stable%20Diffusion-SDXL-blue?style=flat-square) +![n8n](https://img.shields.io/badge/n8n-Workflow-orange?style=flat-square) + +## 🎨 What is this? + +This system automatically creates professional, tech-themed cover images for your portfolio projects using AI. No more stock photos, no design skills needed. + +### Features + +✨ **Fully Automatic** - Generate images when creating new projects +🎯 **Context-Aware** - Uses project title, description, category, and tech stack +🖼️ **High Quality** - 1024x768 optimized for web display +🔒 **Privacy-First** - Runs 100% locally, no data sent to external APIs +⚡ **Fast** - 15-30 seconds per image with GPU +💰 **Free** - No per-image costs after initial setup +🎨 **Customizable** - Full control over style, colors, and aesthetics + +## 🚀 Quick Start + +**Want to get started in 15 minutes?** → Check out [QUICKSTART.md](./QUICKSTART.md) + +**For detailed setup and configuration** → See [SETUP.md](./SETUP.md) + +## 📋 Table of Contents + +- [How It Works](#how-it-works) +- [System Architecture](#system-architecture) +- [Installation](#installation) +- [Usage](#usage) +- [Prompt Engineering](#prompt-engineering) +- [Examples](#examples) +- [Troubleshooting](#troubleshooting) +- [FAQ](#faq) + +## 🔧 How It Works + +```mermaid +graph LR + A[Create Project] --> B[Trigger n8n Webhook] + B --> C[Fetch Project Data] + C --> D[Build AI Prompt] + D --> E[Stable Diffusion] + E --> F[Save Image] + F --> G[Update Database] + G --> H[Display on Site] +``` + +1. **Project Creation**: You create or update a project +2. **Data Extraction**: System reads project metadata (title, description, tags, category) +3. **Prompt Generation**: AI-optimized prompt is created based on project type +4. **Image Generation**: Stable Diffusion generates a unique image +5. **Storage**: Image is saved and optimized +6. **Database Update**: Project's `imageUrl` is updated +7. **Display**: Image appears automatically on your portfolio + +## 🏗️ System Architecture + +``` +┌─────────────────┐ +│ Portfolio App │ +│ (Next.js) │ +└────────┬────────┘ + │ + ▼ +┌─────────────────┐ ┌─────────────────┐ +│ n8n Workflow │─────▶│ PostgreSQL DB │ +│ (Automation) │◀─────│ (Projects) │ +└────────┬────────┘ └─────────────────┘ + │ + ▼ +┌─────────────────┐ +│ Stable Diffusion│ +│ WebUI │ +│ (Image Gen) │ +└─────────────────┘ +``` + +### Components + +- **Next.js App**: Frontend and API endpoints +- **n8n**: Workflow automation and orchestration +- **Stable Diffusion**: Local AI image generation +- **PostgreSQL**: Project data storage +- **File System**: Generated image storage + +## 📦 Installation + +### Prerequisites + +- **Node.js** 18+ +- **Docker** (recommended) or Python 3.10+ +- **PostgreSQL** database +- **8GB+ RAM** minimum +- **GPU recommended** (NVIDIA with CUDA support) + - Minimum: GTX 1060 6GB + - Recommended: RTX 3060 12GB or better + - Also works on CPU (slower) + +### Step-by-Step Setup + +#### 1. Install Stable Diffusion WebUI + +```bash +git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git +cd stable-diffusion-webui +./webui.sh --api --listen +``` + +Wait for model download (~7GB). Access at: `http://localhost:7860` + +#### 2. Install n8n + +```bash +# Docker (recommended) +docker run -d --name n8n -p 5678:5678 -v ~/.n8n:/home/node/.n8n n8nio/n8n + +# Or npm +npm install -g n8n +n8n start +``` + +Access at: `http://localhost:5678` + +#### 3. Import Workflow + +1. Open n8n at `http://localhost:5678` +2. Import `n8n-workflow-ai-image-generator.json` +3. Configure database credentials +4. Update Stable Diffusion API URL +5. Set webhook authentication token + +#### 4. Configure Portfolio App + +Add to `.env.local`: + +```bash +N8N_WEBHOOK_URL=http://localhost:5678/webhook +N8N_SECRET_TOKEN=your-secure-token-here +SD_API_URL=http://localhost:7860 +AUTO_GENERATE_IMAGES=true +GENERATED_IMAGES_DIR=/path/to/portfolio/public/generated-images +``` + +#### 5. Create Image Directory + +```bash +mkdir -p public/generated-images +chmod 755 public/generated-images +``` + +**That's it!** 🎉 You're ready to generate images. + +## 💻 Usage + +### Automatic Generation + +When you create a new project, an image is automatically generated: + +```typescript +// In your project creation API +const newProject = await createProject(data); + +if (process.env.AUTO_GENERATE_IMAGES === 'true') { + await fetch(`${process.env.N8N_WEBHOOK_URL}/ai-image-generation`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${process.env.N8N_SECRET_TOKEN}` + }, + body: JSON.stringify({ projectId: newProject.id }) + }); +} +``` + +### Manual Generation via API + +```bash +curl -X POST http://localhost:3000/api/n8n/generate-image \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer YOUR_TOKEN" \ + -d '{"projectId": 123}' +``` + +### Admin UI Component + +```tsx +import AIImageGenerator from '@/app/components/admin/AIImageGenerator'; + + { + console.log('New image:', url); + }} +/> +``` + +### Batch Generation + +Generate images for all existing projects: + +```bash +# Get all projects without images +psql -d portfolio -t -c "SELECT id FROM projects WHERE image_url IS NULL" | while read id; do + curl -X POST http://localhost:3000/api/n8n/generate-image \ + -H "Content-Type: application/json" \ + -d "{\"projectId\": $id}" + sleep 30 # Wait for generation +done +``` + +## 🎯 Prompt Engineering + +The system automatically generates optimized prompts based on project category: + +### Web Application Example + +**Input Project:** +- Title: "Real-Time Analytics Dashboard" +- Category: "web" +- Tags: ["React", "Next.js", "TypeScript"] + +**Generated Prompt:** +``` +Professional tech project cover image, modern web interface, +clean dashboard UI, gradient backgrounds, glass morphism effect, +representing "Real-Time Analytics Dashboard", React, Next.js, TypeScript, +modern minimalist design, vibrant gradient colors, high quality digital art, +isometric perspective, color palette: cyan, purple, pink, blue accents, +4k resolution, no text, no watermarks, futuristic, professional +``` + +**Result:** Clean, modern dashboard visualization in your brand colors + +### Customize Prompts + +Edit the `Build AI Prompt` node in n8n workflow to customize: + +```javascript +// Add your brand colors +const brandColors = 'navy blue, gold accents, white backgrounds'; + +// Add style preferences +const stylePreference = 'minimalist, clean, corporate, professional'; + +// Modify prompt template +const prompt = ` +${categoryStyle}, +${projectTitle}, +${brandColors}, +${stylePreference}, +4k quality, trending on artstation +`; +``` + +See [PROMPT_TEMPLATES.md](./PROMPT_TEMPLATES.md) for category-specific templates. + +## 🖼️ Examples + +### Before & After + +| Category | Without AI Image | With AI Image | +|----------|------------------|---------------| +| Web App | Generic stock photo | Custom dashboard visualization | +| Mobile App | App store screenshot | Professional phone mockup | +| DevOps | Server rack photo | Cloud architecture diagram | +| AI/ML | Brain illustration | Neural network visualization | + +### Quality Comparison + +**Settings:** +- Resolution: 1024x768 +- Steps: 30 +- CFG Scale: 7 +- Sampler: DPM++ 2M Karras +- Model: SDXL Base 1.0 + +**Generation Time:** +- RTX 4090: ~8 seconds +- RTX 3080: ~15 seconds +- RTX 3060: ~25 seconds +- CPU: ~5 minutes + +## 🐛 Troubleshooting + +### Common Issues + +#### "Connection refused to SD API" +```bash +# Check if SD WebUI is running +ps aux | grep webui + +# Restart with API enabled +cd stable-diffusion-webui +./webui.sh --api --listen +``` + +#### "CUDA out of memory" +```bash +# Use lower VRAM mode +./webui.sh --api --listen --medvram +``` + +#### "Images are low quality" +In n8n workflow, increase: +- Steps: 30 → 40 +- CFG Scale: 7 → 9 +- Resolution: 512 → 1024 + +#### "Images don't match project" +- Add more specific keywords to prompt +- Use category-specific templates +- Refine negative prompts + +See [SETUP.md](./SETUP.md#troubleshooting) for more solutions. + +## ❓ FAQ + +### How much does it cost? + +**Initial Setup:** $300-400 for GPU (or $0 with cloud GPU rental) +**Per Image:** $0.00 (local electricity ~$0.001) +**Break-even:** ~500 images vs. commercial APIs + +### Can I use this without a GPU? + +Yes, but it's slower (~5 minutes per image on CPU). Consider cloud GPU services: +- RunPod: ~$0.20/hour +- vast.ai: ~$0.15/hour +- Google Colab: Free with limitations + +### Is the data sent anywhere? + +No! Everything runs locally. Your project data never leaves your server. + +### Can I customize the style? + +Absolutely! Edit prompts in the n8n workflow or use the template system. + +### What models should I use? + +- **SDXL Base 1.0**: Best all-around quality +- **DreamShaper 8**: Artistic, modern tech style +- **Realistic Vision V5**: Photorealistic results +- **Juggernaut XL**: Clean, professional aesthetics + +### Can I generate images on-demand? + +Yes! Use the admin UI component or API endpoint to regenerate anytime. + +### How do I change image dimensions? + +Edit the n8n workflow's SD node: +```json +{ + "width": 1920, // Change this + "height": 1080 // And this +} +``` + +### Can I use a different AI model? + +Yes! The system works with: +- Stable Diffusion WebUI (default) +- ComfyUI (more advanced) +- Any API that accepts txt2img requests + +## 📚 Additional Resources + +- **[SETUP.md](./SETUP.md)** - Detailed installation guide +- **[QUICKSTART.md](./QUICKSTART.md)** - 15-minute setup guide +- **[PROMPT_TEMPLATES.md](./PROMPT_TEMPLATES.md)** - Category-specific prompts +- **[n8n-workflow-ai-image-generator.json](./n8n-workflow-ai-image-generator.json)** - Workflow file + +### External Documentation + +- [Stable Diffusion WebUI Wiki](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki) +- [n8n Documentation](https://docs.n8n.io) +- [Stable Diffusion Prompt Guide](https://prompthero.com/stable-diffusion-prompt-guide) + +## 🤝 Contributing + +Have improvements or new prompt templates? Contributions welcome! + +1. Fork the repository +2. Create a feature branch +3. Test your changes +4. Submit a pull request + +## 📝 License + +This system is part of your portfolio project. AI-generated images are yours to use freely. + +**Model Licenses:** +- SDXL Base 1.0: CreativeML Open RAIL++-M License +- Other models: Check individual model licenses + +## 🙏 Credits + +- **Stable Diffusion**: Stability AI & AUTOMATIC1111 +- **n8n**: n8n GmbH +- **Prompt Engineering**: Community templates and best practices + +## 💬 Support + +Need help? Found a bug? + +- Open an issue on GitHub +- Check existing documentation +- Join the community Discord +- Email: contact@dk0.dev + +--- + +**Built with ❤️ for automatic, beautiful project images** + +*Last Updated: 2024* \ No newline at end of file diff --git a/docs/ai-image-generation/SETUP.md b/docs/ai-image-generation/SETUP.md new file mode 100644 index 0000000..3c8b008 --- /dev/null +++ b/docs/ai-image-generation/SETUP.md @@ -0,0 +1,486 @@ +# AI Image Generation Setup + +This guide explains how to set up automatic AI-powered image generation for your portfolio projects using local AI models. + +## Overview + +The system automatically generates project cover images by: +1. Reading project metadata (title, description, tags, tech stack) +2. Creating an optimized prompt for image generation +3. Sending the prompt to a local AI image generator +4. Saving the generated image +5. Updating the project's `imageUrl` in the database + +## Supported Local AI Tools + +### Option 1: Stable Diffusion WebUI (AUTOMATIC1111) - Recommended + +**Pros:** +- Most mature and widely used +- Excellent API support +- Large model ecosystem +- Easy to use + +**Installation:** +```bash +# Clone the repository +git clone https://github.com/AUTOMATIC1111/stable-diffusion-webui.git +cd stable-diffusion-webui + +# Install and run (will download models automatically) +./webui.sh --api --listen +``` + +**API Endpoint:** `http://localhost:7860` + +**Recommended Models:** +- **SDXL Base 1.0** - High quality, versatile +- **Realistic Vision V5.1** - Photorealistic images +- **DreamShaper 8** - Artistic, tech-focused imagery +- **Juggernaut XL** - Modern, clean aesthetics + +**Download Models:** +```bash +cd models/Stable-diffusion/ + +# SDXL Base (6.94 GB) +wget https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0.safetensors + +# Or use the WebUI's model downloader +``` + +### Option 2: ComfyUI + +**Pros:** +- Node-based workflow system +- More control over generation pipeline +- Better for complex compositions + +**Installation:** +```bash +git clone https://github.com/comfyanonymous/ComfyUI.git +cd ComfyUI +pip install -r requirements.txt +python main.py --listen 0.0.0.0 --port 8188 +``` + +**API Endpoint:** `http://localhost:8188` + +### Option 3: Ollama + Stable Diffusion + +**Pros:** +- Lightweight +- Easy model management +- Can combine with LLM for better prompts + +**Installation:** +```bash +# Install Ollama +curl -fsSL https://ollama.com/install.sh | sh + +# Install a vision-capable model +ollama pull llava + +# For image generation, you'll still need SD WebUI or ComfyUI +``` + +## n8n Workflow Setup + +### 1. Install n8n (if not already installed) + +```bash +# Docker Compose (recommended) +docker-compose up -d n8n + +# Or npm +npm install -g n8n +n8n start +``` + +### 2. Import Workflow + +1. Open n8n at `http://localhost:5678` +2. Go to **Workflows** → **Import from File** +3. Import `n8n-workflows/ai-image-generator.json` + +### 3. Configure Workflow Nodes + +#### Node 1: Webhook Trigger +- **Method:** POST +- **Path:** `ai-image-generation` +- **Authentication:** Header Auth (use secret token) + +#### Node 2: Postgres - Get Project Data +```sql +SELECT id, title, description, tags, category, content +FROM projects +WHERE id = $json.projectId +LIMIT 1; +``` + +#### Node 3: Code - Build AI Prompt +```javascript +// Extract project data +const project = $input.first().json; + +// Build sophisticated prompt +const styleKeywords = { + 'web': 'modern web interface, clean UI, gradient backgrounds, glass morphism', + 'mobile': 'mobile app mockup, sleek design, app icons, smartphone screen', + 'devops': 'server infrastructure, network diagram, cloud architecture, terminal windows', + 'game': 'game scene, 3D environment, gaming interface, player HUD', + 'ai': 'neural network visualization, AI chip, data flow, futuristic tech', + 'automation': 'workflow diagram, automated processes, gears and circuits' +}; + +const categoryStyle = styleKeywords[project.category?.toLowerCase()] || 'technology concept'; + +const prompt = ` +Professional tech project cover image, ${categoryStyle}, +representing "${project.title}", +modern design, vibrant colors, high quality, +isometric view, minimalist, clean composition, +4k resolution, trending on artstation, +color palette: blue, purple, teal accents, +no text, no people, no logos +`.trim().replace(/\s+/g, ' '); + +const negativePrompt = ` +low quality, blurry, pixelated, text, watermark, +signature, logo, people, faces, hands, +cluttered, messy, dark, gloomy +`.trim().replace(/\s+/g, ' '); + +return { + json: { + projectId: project.id, + prompt: prompt, + negativePrompt: negativePrompt, + title: project.title, + category: project.category + } +}; +``` + +#### Node 4: HTTP Request - Generate Image (Stable Diffusion) +- **Method:** POST +- **URL:** `http://your-sd-server:7860/sdapi/v1/txt2img` +- **Body:** +```json +{ + "prompt": "={{ $json.prompt }}", + "negative_prompt": "={{ $json.negativePrompt }}", + "steps": 30, + "cfg_scale": 7, + "width": 1024, + "height": 768, + "sampler_name": "DPM++ 2M Karras", + "seed": -1, + "batch_size": 1, + "n_iter": 1 +} +``` + +#### Node 5: Code - Save Image to File +```javascript +const fs = require('fs'); +const path = require('path'); + +const imageData = $input.first().json.images[0]; // Base64 image +const projectId = $json.projectId; +const timestamp = Date.now(); + +// Create directory if doesn't exist +const uploadDir = '/app/public/generated-images'; +if (!fs.existsSync(uploadDir)) { + fs.mkdirSync(uploadDir, { recursive: true }); +} + +// Save image +const filename = `project-${projectId}-${timestamp}.png`; +const filepath = path.join(uploadDir, filename); + +fs.writeFileSync(filepath, Buffer.from(imageData, 'base64')); + +return { + json: { + projectId: projectId, + imageUrl: `/generated-images/${filename}`, + filepath: filepath + } +}; +``` + +#### Node 6: Postgres - Update Project +```sql +UPDATE projects +SET image_url = $json.imageUrl, + updated_at = NOW() +WHERE id = $json.projectId; +``` + +#### Node 7: Webhook Response +```json +{ + "success": true, + "projectId": "={{ $json.projectId }}", + "imageUrl": "={{ $json.imageUrl }}", + "message": "Image generated successfully" +} +``` + +## API Integration + +### Generate Image for Project + +**Endpoint:** `POST /api/n8n/generate-image` + +**Request:** +```json +{ + "projectId": 123, + "regenerate": false +} +``` + +**Response:** +```json +{ + "success": true, + "projectId": 123, + "imageUrl": "/generated-images/project-123-1234567890.png", + "generatedAt": "2024-01-15T10:30:00Z" +} +``` + +### Automatic Generation on Project Creation + +Add this to your project creation API: + +```typescript +// After creating project in database +if (process.env.AUTO_GENERATE_IMAGES === 'true') { + await fetch(`${process.env.N8N_WEBHOOK_URL}/ai-image-generation`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${process.env.N8N_SECRET_TOKEN}` + }, + body: JSON.stringify({ + projectId: newProject.id + }) + }); +} +``` + +## Environment Variables + +Add to `.env.local`: + +```bash +# AI Image Generation +N8N_WEBHOOK_URL=http://localhost:5678/webhook +N8N_SECRET_TOKEN=your-secure-token-here +AUTO_GENERATE_IMAGES=true + +# Stable Diffusion API +SD_API_URL=http://localhost:7860 +SD_API_KEY=optional-if-protected + +# Image Storage +GENERATED_IMAGES_DIR=/app/public/generated-images +``` + +## Prompt Engineering Tips + +### Good Prompts for Tech Projects + +**Web Application:** +``` +modern web dashboard interface, clean UI design, gradient background, +glass morphism, floating panels, data visualization, charts and graphs, +vibrant blue and purple color scheme, isometric view, 4k quality +``` + +**Mobile App:** +``` +sleek mobile app interface mockup, smartphone screen, modern app design, +minimalist UI, smooth gradients, app icons, notification badges, +floating elements, teal and pink accents, professional photography +``` + +**DevOps/Infrastructure:** +``` +cloud infrastructure diagram, server network visualization, +interconnected nodes, data flow arrows, container icons, +modern tech illustration, isometric perspective, cyan and orange colors +``` + +**AI/ML Project:** +``` +artificial intelligence concept, neural network visualization, +glowing nodes and connections, data streams, futuristic interface, +holographic elements, purple and blue neon lighting, high tech +``` + +### Negative Prompts (What to Avoid) + +``` +text, watermark, signature, logo, brand name, letters, numbers, +people, faces, hands, fingers, human figures, +low quality, blurry, pixelated, jpeg artifacts, +dark, gloomy, depressing, messy, cluttered, +realistic photo, stock photo +``` + +## Image Specifications + +**Recommended Settings:** +- **Resolution:** 1024x768 (4:3 aspect ratio for cards) +- **Format:** PNG (with transparency support) +- **Size:** < 500KB (optimize after generation) +- **Color Profile:** sRGB +- **Sampling Steps:** 25-35 (balance quality vs speed) +- **CFG Scale:** 6-8 (how closely to follow prompt) + +## Optimization + +### Post-Processing Pipeline + +```bash +# Install image optimization tools +npm install sharp tinypng-cli + +# Optimize generated images +sharp input.png -o optimized.png --webp --quality 85 + +# Or use TinyPNG +tinypng input.png --key YOUR_API_KEY +``` + +### Caching Strategy + +```typescript +// Cache generated images in Redis +await redis.set( + `project:${projectId}:image`, + imageUrl, + 'EX', + 60 * 60 * 24 * 30 // 30 days +); +``` + +## Monitoring & Debugging + +### Check Stable Diffusion Status + +```bash +curl http://localhost:7860/sdapi/v1/sd-models +``` + +### View n8n Execution Logs + +1. Open n8n UI → Executions +2. Filter by workflow "AI Image Generator" +3. Check error logs and execution time + +### Test Image Generation + +```bash +curl -X POST http://localhost:7860/sdapi/v1/txt2img \ + -H "Content-Type: application/json" \ + -d '{ + "prompt": "modern tech interface, blue gradient", + "steps": 20, + "width": 512, + "height": 512 + }' +``` + +## Troubleshooting + +### "CUDA out of memory" +- Reduce image resolution (768x576 instead of 1024x768) +- Lower batch size to 1 +- Use `--lowvram` or `--medvram` flags when starting SD + +### "Connection refused to SD API" +- Check if SD WebUI is running: `ps aux | grep webui` +- Verify API is enabled: `--api` flag in startup +- Check firewall: `sudo ufw allow 7860` + +### "Poor image quality" +- Increase sampling steps (30-40) +- Try different samplers (Euler a, DPM++ 2M Karras) +- Adjust CFG scale (7-9) +- Use better checkpoint model (SDXL, Realistic Vision) + +### "Images don't match project theme" +- Refine prompts with more specific keywords +- Use category-specific style templates +- Add technical keywords from project tags +- Experiment with different negative prompts + +## Advanced: Multi-Model Strategy + +Use different models for different project types: + +```javascript +const modelMap = { + 'web': 'dreamshaper_8.safetensors', + 'mobile': 'realisticVision_v51.safetensors', + 'devops': 'juggernautXL_v8.safetensors', + 'ai': 'sdxl_base_1.0.safetensors' +}; + +// Switch model before generation +await fetch('http://localhost:7860/sdapi/v1/options', { + method: 'POST', + body: JSON.stringify({ + sd_model_checkpoint: modelMap[project.category] + }) +}); +``` + +## Security Considerations + +1. **Isolate SD WebUI:** Run in Docker container, not exposed to internet +2. **Authentication:** Protect n8n webhooks with tokens +3. **Rate Limiting:** Limit image generation requests +4. **Content Filtering:** Validate prompts to prevent abuse +5. **Resource Limits:** Set GPU memory limits in Docker + +## Cost & Performance + +**Hardware Requirements:** +- **Minimum:** 8GB RAM, GTX 1060 6GB +- **Recommended:** 16GB RAM, RTX 3060 12GB +- **Optimal:** 32GB RAM, RTX 4090 24GB + +**Generation Time:** +- **512x512:** ~5-10 seconds +- **1024x768:** ~15-30 seconds +- **1024x1024 (SDXL):** ~30-60 seconds + +**Storage:** +- ~500KB per optimized image +- ~50MB for 100 projects + +## Future Enhancements + +- [ ] Style transfer from existing brand assets +- [ ] A/B testing different image variants +- [ ] User feedback loop for prompt refinement +- [ ] Batch generation for multiple projects +- [ ] Integration with DALL-E 3 / Midjourney as fallback +- [ ] Automatic alt text generation for accessibility +- [ ] Version history for generated images + +--- + +**Next Steps:** +1. Set up Stable Diffusion WebUI locally +2. Import n8n workflow +3. Test with sample project +4. Refine prompts based on results +5. Enable auto-generation for new projects \ No newline at end of file diff --git a/docs/ai-image-generation/n8n-workflow-ai-image-generator.json b/docs/ai-image-generation/n8n-workflow-ai-image-generator.json new file mode 100644 index 0000000..29a9012 --- /dev/null +++ b/docs/ai-image-generation/n8n-workflow-ai-image-generator.json @@ -0,0 +1,340 @@ +{ + "name": "AI Project Image Generator", + "nodes": [ + { + "parameters": { + "httpMethod": "POST", + "path": "ai-image-generation", + "responseMode": "responseNode", + "options": { + "authType": "headerAuth" + } + }, + "id": "webhook-trigger", + "name": "Webhook Trigger", + "type": "n8n-nodes-base.webhook", + "typeVersion": 1, + "position": [250, 300], + "webhookId": "ai-image-gen-webhook", + "credentials": { + "httpHeaderAuth": { + "id": "1", + "name": "Header Auth" + } + } + }, + { + "parameters": { + "operation": "executeQuery", + "query": "SELECT id, title, description, tags, category, content, tech_stack FROM projects WHERE id = $1 LIMIT 1", + "additionalFields": { + "queryParameters": "={{ $json.body.projectId }}" + } + }, + "id": "get-project-data", + "name": "Get Project Data", + "type": "n8n-nodes-base.postgres", + "typeVersion": 2, + "position": [450, 300], + "credentials": { + "postgres": { + "id": "2", + "name": "PostgreSQL" + } + } + }, + { + "parameters": { + "jsCode": "// Extract project data\nconst project = $input.first().json;\n\n// Style keywords by category\nconst styleKeywords = {\n 'web': 'modern web interface, clean UI dashboard, gradient backgrounds, glass morphism effect, floating panels',\n 'mobile': 'mobile app mockup, sleek smartphone design, app icons, modern UI elements, notification badges',\n 'devops': 'server infrastructure, cloud network diagram, container orchestration, CI/CD pipeline visualization',\n 'backend': 'API architecture, database systems, microservices diagram, server endpoints, data flow',\n 'game': 'game environment scene, 3D rendered world, gaming interface, player HUD elements',\n 'ai': 'neural network visualization, AI chip design, machine learning data flow, futuristic technology',\n 'automation': 'workflow automation diagram, process flows, interconnected systems, automated pipeline',\n 'security': 'cybersecurity shields, encrypted data streams, security locks, firewall visualization',\n 'iot': 'Internet of Things devices, sensor networks, smart home technology, connected devices',\n 'blockchain': 'blockchain network, crypto technology, distributed ledger, decentralized nodes'\n};\n\nconst categoryStyle = styleKeywords[project.category?.toLowerCase()] || 'modern technology concept visualization';\n\n// Extract tech-specific keywords from tags and tech_stack\nconst techKeywords = [];\nif (project.tags) {\n const tags = Array.isArray(project.tags) ? project.tags : JSON.parse(project.tags || '[]');\n techKeywords.push(...tags.slice(0, 3));\n}\nif (project.tech_stack) {\n const stack = Array.isArray(project.tech_stack) ? project.tech_stack : JSON.parse(project.tech_stack || '[]');\n techKeywords.push(...stack.slice(0, 2));\n}\n\nconst techContext = techKeywords.length > 0 ? techKeywords.join(', ') + ' technology,' : '';\n\n// Build sophisticated prompt\nconst prompt = `\nProfessional tech project cover image, ${categoryStyle},\nrepresenting the concept of \"${project.title}\",\n${techContext}\nmodern minimalist design, vibrant gradient colors,\nhigh quality digital art, isometric perspective,\nclean composition, soft lighting,\ncolor palette: cyan, purple, pink, blue accents,\n4k resolution, trending on artstation,\nno text, no watermarks, no people, no logos,\nfuturistic, professional, tech-focused\n`.trim().replace(/\\s+/g, ' ');\n\n// Comprehensive negative prompt\nconst negativePrompt = `\nlow quality, blurry, pixelated, grainy, jpeg artifacts,\ntext, letters, words, watermark, signature, logo, brand name,\npeople, faces, hands, fingers, human figures, person,\ncluttered, messy, chaotic, disorganized,\ndark, gloomy, depressing, ugly, distorted,\nrealistic photo, stock photo, photograph,\nbad anatomy, deformed, mutation, extra limbs,\nduplication, duplicate elements, repetitive patterns\n`.trim().replace(/\\s+/g, ' ');\n\nreturn {\n json: {\n projectId: project.id,\n prompt: prompt,\n negativePrompt: negativePrompt,\n title: project.title,\n category: project.category,\n timestamp: Date.now()\n }\n};" + }, + "id": "build-ai-prompt", + "name": "Build AI Prompt", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [650, 300] + }, + { + "parameters": { + "method": "POST", + "url": "={{ $env.SD_API_URL || 'http://localhost:7860' }}/sdapi/v1/txt2img", + "authentication": "genericCredentialType", + "genericAuthType": "httpHeaderAuth", + "sendBody": true, + "bodyParameters": { + "parameters": [ + { + "name": "prompt", + "value": "={{ $json.prompt }}" + }, + { + "name": "negative_prompt", + "value": "={{ $json.negativePrompt }}" + }, + { + "name": "steps", + "value": "30" + }, + { + "name": "cfg_scale", + "value": "7" + }, + { + "name": "width", + "value": "1024" + }, + { + "name": "height", + "value": "768" + }, + { + "name": "sampler_name", + "value": "DPM++ 2M Karras" + }, + { + "name": "seed", + "value": "-1" + }, + { + "name": "batch_size", + "value": "1" + }, + { + "name": "n_iter", + "value": "1" + }, + { + "name": "save_images", + "value": "false" + } + ] + }, + "options": { + "timeout": 180000 + } + }, + "id": "generate-image-sd", + "name": "Generate Image (Stable Diffusion)", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4, + "position": [850, 300], + "credentials": { + "httpHeaderAuth": { + "id": "3", + "name": "SD API Auth" + } + } + }, + { + "parameters": { + "jsCode": "const fs = require('fs');\nconst path = require('path');\n\n// Get the base64 image data from Stable Diffusion response\nconst response = $input.first().json;\nconst imageData = response.images[0]; // Base64 encoded PNG\n\nconst projectId = $('Build AI Prompt').first().json.projectId;\nconst timestamp = Date.now();\n\n// Define upload directory (adjust path based on your setup)\nconst uploadDir = process.env.GENERATED_IMAGES_DIR || '/app/public/generated-images';\n\n// Create directory if it doesn't exist\nif (!fs.existsSync(uploadDir)) {\n fs.mkdirSync(uploadDir, { recursive: true });\n}\n\n// Generate filename\nconst filename = `project-${projectId}-${timestamp}.png`;\nconst filepath = path.join(uploadDir, filename);\n\n// Convert base64 to buffer and save\ntry {\n const imageBuffer = Buffer.from(imageData, 'base64');\n fs.writeFileSync(filepath, imageBuffer);\n \n // Get file size for logging\n const stats = fs.statSync(filepath);\n const fileSizeKB = (stats.size / 1024).toFixed(2);\n \n return {\n json: {\n projectId: projectId,\n imageUrl: `/generated-images/${filename}`,\n filepath: filepath,\n filename: filename,\n fileSize: fileSizeKB + ' KB',\n generatedAt: new Date().toISOString(),\n success: true\n }\n };\n} catch (error) {\n return {\n json: {\n projectId: projectId,\n error: error.message,\n success: false\n }\n };\n}" + }, + "id": "save-image-file", + "name": "Save Image to File", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [1050, 300] + }, + { + "parameters": { + "operation": "executeQuery", + "query": "UPDATE projects SET image_url = $1, updated_at = NOW() WHERE id = $2 RETURNING id, title, image_url", + "additionalFields": { + "queryParameters": "={{ $json.imageUrl }},={{ $json.projectId }}" + } + }, + "id": "update-project-image", + "name": "Update Project Image URL", + "type": "n8n-nodes-base.postgres", + "typeVersion": 2, + "position": [1250, 300], + "credentials": { + "postgres": { + "id": "2", + "name": "PostgreSQL" + } + } + }, + { + "parameters": { + "respondWith": "json", + "responseBody": "={\n \"success\": true,\n \"projectId\": {{ $json.id }},\n \"title\": \"{{ $json.title }}\",\n \"imageUrl\": \"{{ $json.image_url }}\",\n \"generatedAt\": \"{{ $('Save Image to File').first().json.generatedAt }}\",\n \"fileSize\": \"{{ $('Save Image to File').first().json.fileSize }}\",\n \"message\": \"Project image generated successfully\"\n}", + "options": {} + }, + "id": "webhook-response", + "name": "Webhook Response", + "type": "n8n-nodes-base.respondToWebhook", + "typeVersion": 1, + "position": [1450, 300] + }, + { + "parameters": { + "conditions": { + "boolean": [ + { + "value1": "={{ $json.success }}", + "value2": true + } + ] + } + }, + "id": "check-save-success", + "name": "Check Save Success", + "type": "n8n-nodes-base.if", + "typeVersion": 1, + "position": [1050, 450] + }, + { + "parameters": { + "respondWith": "json", + "responseBody": "={\n \"success\": false,\n \"error\": \"{{ $json.error || 'Failed to save image' }}\",\n \"projectId\": {{ $json.projectId }},\n \"message\": \"Image generation failed\"\n}", + "options": { + "responseCode": 500 + } + }, + "id": "error-response", + "name": "Error Response", + "type": "n8n-nodes-base.respondToWebhook", + "typeVersion": 1, + "position": [1250, 500] + }, + { + "parameters": { + "operation": "executeQuery", + "query": "INSERT INTO activity_logs (type, action, details, created_at) VALUES ('ai_generation', 'image_generated', $1, NOW())", + "additionalFields": { + "queryParameters": "={{ JSON.stringify({ projectId: $json.id, imageUrl: $json.image_url, timestamp: new Date().toISOString() }) }}" + } + }, + "id": "log-activity", + "name": "Log Generation Activity", + "type": "n8n-nodes-base.postgres", + "typeVersion": 2, + "position": [1250, 150], + "credentials": { + "postgres": { + "id": "2", + "name": "PostgreSQL" + } + } + } + ], + "connections": { + "Webhook Trigger": { + "main": [ + [ + { + "node": "Get Project Data", + "type": "main", + "index": 0 + } + ] + ] + }, + "Get Project Data": { + "main": [ + [ + { + "node": "Build AI Prompt", + "type": "main", + "index": 0 + } + ] + ] + }, + "Build AI Prompt": { + "main": [ + [ + { + "node": "Generate Image (Stable Diffusion)", + "type": "main", + "index": 0 + } + ] + ] + }, + "Generate Image (Stable Diffusion)": { + "main": [ + [ + { + "node": "Save Image to File", + "type": "main", + "index": 0 + } + ] + ] + }, + "Save Image to File": { + "main": [ + [ + { + "node": "Check Save Success", + "type": "main", + "index": 0 + } + ] + ] + }, + "Check Save Success": { + "main": [ + [ + { + "node": "Update Project Image URL", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "Error Response", + "type": "main", + "index": 0 + } + ] + ] + }, + "Update Project Image URL": { + "main": [ + [ + { + "node": "Log Generation Activity", + "type": "main", + "index": 0 + }, + { + "node": "Webhook Response", + "type": "main", + "index": 0 + } + ] + ] + } + }, + "settings": { + "executionOrder": "v1", + "saveManualExecutions": true, + "callerPolicy": "workflowsFromSameOwner", + "errorWorkflow": "" + }, + "staticData": null, + "tags": [ + { + "name": "AI", + "id": "ai-tag" + }, + { + "name": "Automation", + "id": "automation-tag" + }, + { + "name": "Image Generation", + "id": "image-gen-tag" + } + ], + "meta": { + "instanceId": "your-instance-id" + }, + "id": "ai-image-generator-workflow", + "versionId": "1", + "triggerCount": 1, + "active": true +} diff --git a/docs/setup_activity_status.sql b/docs/setup_activity_status.sql new file mode 100644 index 0000000..658a14e --- /dev/null +++ b/docs/setup_activity_status.sql @@ -0,0 +1,91 @@ +-- Activity Status Table Setup for n8n Integration +-- This table stores real-time activity data from various sources + +-- Drop existing table if it exists +DROP TABLE IF EXISTS activity_status CASCADE; + +-- Create the activity_status table +CREATE TABLE activity_status ( + id SERIAL PRIMARY KEY, + + -- Activity (Coding, Reading, etc.) + activity_type VARCHAR(50), -- 'coding', 'listening', 'watching', 'gaming', 'reading' + activity_details TEXT, + activity_project VARCHAR(255), + activity_language VARCHAR(50), + activity_repo VARCHAR(255), + + -- Music (Spotify, Apple Music) + music_playing BOOLEAN DEFAULT FALSE, + music_track VARCHAR(255), + music_artist VARCHAR(255), + music_album VARCHAR(255), + music_platform VARCHAR(50), -- 'spotify', 'apple' + music_progress INTEGER, -- 0-100 (percentage) + music_album_art TEXT, -- URL to album art + + -- Watching (YouTube, Netflix, Twitch) + watching_title VARCHAR(255), + watching_platform VARCHAR(50), -- 'youtube', 'netflix', 'twitch' + watching_type VARCHAR(50), -- 'video', 'stream', 'movie', 'series' + + -- Gaming (Steam, PlayStation, Xbox, Discord) + gaming_game VARCHAR(255), + gaming_platform VARCHAR(50), -- 'steam', 'playstation', 'xbox', 'discord' + gaming_status VARCHAR(50), -- 'playing', 'idle' + + -- Status (Mood & Custom Message) + status_mood VARCHAR(10), -- emoji like '😊', '💻', '🎮', '😴' + status_message TEXT, + + -- Timestamps + created_at TIMESTAMP DEFAULT NOW(), + updated_at TIMESTAMP DEFAULT NOW() +); + +-- Create index for faster queries +CREATE INDEX idx_activity_status_updated_at ON activity_status(updated_at DESC); + +-- Insert default row (will be updated by n8n workflows) +INSERT INTO activity_status ( + id, + activity_type, + activity_details, + music_playing, + status_mood, + status_message +) VALUES ( + 1, + NULL, + NULL, + FALSE, + '💻', + 'Getting started...' +); + +-- Create function to automatically update updated_at timestamp +CREATE OR REPLACE FUNCTION update_activity_status_timestamp() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = NOW(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- Create trigger to call the function on UPDATE +CREATE TRIGGER trigger_update_activity_status_timestamp +BEFORE UPDATE ON activity_status +FOR EACH ROW +EXECUTE FUNCTION update_activity_status_timestamp(); + +-- Grant permissions (adjust as needed) +-- GRANT SELECT, INSERT, UPDATE ON activity_status TO your_app_user; +-- GRANT USAGE, SELECT ON SEQUENCE activity_status_id_seq TO your_app_user; + +-- Display success message +DO $$ +BEGIN + RAISE NOTICE '✅ Activity Status table created successfully!'; + RAISE NOTICE '📝 You can now configure your n8n workflows to update this table.'; + RAISE NOTICE '🔗 See docs/N8N_INTEGRATION.md for setup instructions.'; +END $$; diff --git a/middleware.ts b/middleware.ts index 1d546b7..bbf7cd6 100644 --- a/middleware.ts +++ b/middleware.ts @@ -1,37 +1,31 @@ -import { NextResponse } from 'next/server'; -import type { NextRequest } from 'next/server'; -import { verifySessionAuth } from '@/lib/auth'; +import { NextResponse } from "next/server"; +import type { NextRequest } from "next/server"; +import { verifySessionAuth } from "@/lib/auth"; export function middleware(request: NextRequest) { - // For /manage and /editor routes, require authentication - if (request.nextUrl.pathname.startsWith('/manage') || - request.nextUrl.pathname.startsWith('/editor')) { - // Check for session authentication - if (!verifySessionAuth(request)) { - // Redirect to home page if not authenticated - const url = request.nextUrl.clone(); - url.pathname = '/'; - return NextResponse.redirect(url); - } - } + // For /manage and /editor routes, the pages handle their own authentication + // No middleware redirect needed - let the pages show login forms // Add security headers to all responses const response = NextResponse.next(); - + // Security headers (complementing next.config.ts headers) - response.headers.set('X-DNS-Prefetch-Control', 'on'); - response.headers.set('X-Frame-Options', 'DENY'); - response.headers.set('X-Content-Type-Options', 'nosniff'); - response.headers.set('X-XSS-Protection', '1; mode=block'); - response.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin'); - response.headers.set('Permissions-Policy', 'camera=(), microphone=(), geolocation=()'); - + response.headers.set("X-DNS-Prefetch-Control", "on"); + response.headers.set("X-Frame-Options", "DENY"); + response.headers.set("X-Content-Type-Options", "nosniff"); + response.headers.set("X-XSS-Protection", "1; mode=block"); + response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin"); + response.headers.set( + "Permissions-Policy", + "camera=(), microphone=(), geolocation=()", + ); + // Rate limiting headers for API routes - if (request.nextUrl.pathname.startsWith('/api/')) { - response.headers.set('X-RateLimit-Limit', '100'); - response.headers.set('X-RateLimit-Remaining', '99'); + if (request.nextUrl.pathname.startsWith("/api/")) { + response.headers.set("X-RateLimit-Limit", "100"); + response.headers.set("X-RateLimit-Remaining", "99"); } - + return response; } @@ -46,6 +40,6 @@ export const config = { * - favicon.ico (favicon file) * - api/auth (auth API routes - need to be processed) */ - '/((?!api/email|api/health|_next/static|_next/image|favicon.ico|api/auth).*)', + "/((?!api/email|api/health|_next/static|_next/image|favicon.ico|api/auth).*)", ], -}; \ No newline at end of file +}; diff --git a/package.json b/package.json index 8703959..07cc37a 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "dev:simple": "node scripts/dev-simple.js", "dev:next": "next dev", "db:setup": "node scripts/setup-database.js", - "db:seed": "tsx prisma/seed.ts", + "db:seed": "tsx -r dotenv/config prisma/seed.ts dotenv_config_path=.env.local", "build": "next build", "start": "next start", "lint": "eslint .", diff --git a/prisma/migrations/README.md b/prisma/migrations/README.md new file mode 100644 index 0000000..b43642a --- /dev/null +++ b/prisma/migrations/README.md @@ -0,0 +1,127 @@ +# Database Migrations + +This directory contains SQL migration scripts for manual database updates. + +## Running Migrations + +### Method 1: Using psql (Recommended) + +```bash +# Connect to your database +psql -d portfolio -f prisma/migrations/create_activity_status.sql + +# Or with connection string +psql "postgresql://user:password@localhost:5432/portfolio" -f prisma/migrations/create_activity_status.sql +``` + +### Method 2: Using Docker + +```bash +# If your database is in Docker +docker exec -i postgres_container psql -U username -d portfolio < prisma/migrations/create_activity_status.sql +``` + +### Method 3: Using pgAdmin or Database GUI + +1. Open pgAdmin or your database GUI +2. Connect to your `portfolio` database +3. Open Query Tool +4. Copy and paste the contents of `create_activity_status.sql` +5. Execute the query + +## Verifying Migration + +After running the migration, verify it was successful: + +```bash +# Check if table exists +psql -d portfolio -c "\dt activity_status" + +# View table structure +psql -d portfolio -c "\d activity_status" + +# Check if default row was inserted +psql -d portfolio -c "SELECT * FROM activity_status;" +``` + +Expected output: +``` + id | activity_type | ... | updated_at +----+---------------+-----+--------------------------- + 1 | | ... | 2024-01-15 10:30:00+00 +``` + +## Migration: create_activity_status.sql + +**Purpose**: Creates the `activity_status` table for n8n activity feed integration. + +**What it does**: +- Creates `activity_status` table with all necessary columns +- Inserts a default row with `id = 1` +- Sets up automatic `updated_at` timestamp trigger +- Adds table comment for documentation + +**Required by**: +- `/api/n8n/status` endpoint +- `ActivityFeed` component +- n8n workflows for status updates + +**Safe to run multiple times**: Yes (uses `IF NOT EXISTS` and `ON CONFLICT`) + +## Troubleshooting + +### "relation already exists" +Table already exists - migration is already applied. Safe to ignore. + +### "permission denied" +Your database user needs CREATE TABLE permissions: +```sql +GRANT CREATE ON DATABASE portfolio TO your_user; +``` + +### "database does not exist" +Create the database first: +```bash +createdb portfolio +# Or +psql -c "CREATE DATABASE portfolio;" +``` + +### "connection refused" +Ensure PostgreSQL is running: +```bash +# Check status +pg_isready + +# Start PostgreSQL (macOS) +brew services start postgresql + +# Start PostgreSQL (Linux) +sudo systemctl start postgresql +``` + +## Rolling Back + +To remove the activity_status table: + +```sql +DROP TRIGGER IF EXISTS activity_status_updated_at ON activity_status; +DROP FUNCTION IF EXISTS update_activity_status_updated_at(); +DROP TABLE IF EXISTS activity_status; +``` + +Save this as `rollback_activity_status.sql` and run if needed. + +## Future Migrations + +When adding new migrations: +1. Create a new `.sql` file with descriptive name +2. Use timestamps in filename: `YYYYMMDD_description.sql` +3. Document what it does in this README +4. Test on local database first +5. Mark as safe/unsafe for production + +--- + +**Last Updated**: 2024-01-15 +**Status**: Required for n8n integration \ No newline at end of file diff --git a/prisma/migrations/create_activity_status.sql b/prisma/migrations/create_activity_status.sql new file mode 100644 index 0000000..c435677 --- /dev/null +++ b/prisma/migrations/create_activity_status.sql @@ -0,0 +1,49 @@ +-- Create activity_status table for n8n integration +CREATE TABLE IF NOT EXISTS activity_status ( + id INTEGER PRIMARY KEY DEFAULT 1, + activity_type VARCHAR(50), + activity_details VARCHAR(255), + activity_project VARCHAR(255), + activity_language VARCHAR(50), + activity_repo VARCHAR(500), + music_playing BOOLEAN DEFAULT FALSE, + music_track VARCHAR(255), + music_artist VARCHAR(255), + music_album VARCHAR(255), + music_platform VARCHAR(50), + music_progress INTEGER, + music_album_art VARCHAR(500), + watching_title VARCHAR(255), + watching_platform VARCHAR(50), + watching_type VARCHAR(50), + gaming_game VARCHAR(255), + gaming_platform VARCHAR(50), + gaming_status VARCHAR(50), + status_mood VARCHAR(50), + status_message VARCHAR(500), + updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() +); + +-- Insert default row +INSERT INTO activity_status (id, updated_at) +VALUES (1, NOW()) +ON CONFLICT (id) DO NOTHING; + +-- Create function to automatically update updated_at +CREATE OR REPLACE FUNCTION update_activity_status_updated_at() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = NOW(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- Create trigger for automatic timestamp updates +DROP TRIGGER IF EXISTS activity_status_updated_at ON activity_status; +CREATE TRIGGER activity_status_updated_at + BEFORE UPDATE ON activity_status + FOR EACH ROW + EXECUTE FUNCTION update_activity_status_updated_at(); + +-- Add helpful comment +COMMENT ON TABLE activity_status IS 'Stores real-time activity status from n8n workflows (coding, music, gaming, etc.)'; diff --git a/prisma/migrations/quick-fix.sh b/prisma/migrations/quick-fix.sh new file mode 100755 index 0000000..70d5f09 --- /dev/null +++ b/prisma/migrations/quick-fix.sh @@ -0,0 +1,73 @@ +#!/bin/bash + +# Quick Fix Script for Portfolio Database +# This script creates the activity_status table needed for n8n integration + +set -e + +echo "🔧 Portfolio Database Quick Fix" +echo "================================" +echo "" + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Check if .env.local exists +if [ ! -f .env.local ]; then + echo -e "${RED}❌ Error: .env.local not found${NC}" + echo "Please create .env.local with DATABASE_URL" + exit 1 +fi + +# Load DATABASE_URL from .env.local +export $(grep -v '^#' .env.local | xargs) + +if [ -z "$DATABASE_URL" ]; then + echo -e "${RED}❌ Error: DATABASE_URL not found in .env.local${NC}" + exit 1 +fi + +echo -e "${GREEN}✓ Found DATABASE_URL${NC}" +echo "" + +# Extract database name from DATABASE_URL +DB_NAME=$(echo $DATABASE_URL | sed -n 's/.*\/\([^?]*\).*/\1/p') +echo "📦 Database: $DB_NAME" +echo "" + +# Run the migration +echo "🚀 Creating activity_status table..." +echo "" + +psql "$DATABASE_URL" -f prisma/migrations/create_activity_status.sql + +if [ $? -eq 0 ]; then + echo "" + echo -e "${GREEN}✅ SUCCESS! Migration completed${NC}" + echo "" + echo "Verifying table..." + psql "$DATABASE_URL" -c "\d activity_status" | head -20 + echo "" + echo "Checking default row..." + psql "$DATABASE_URL" -c "SELECT id, updated_at FROM activity_status LIMIT 1;" + echo "" + echo -e "${GREEN}🎉 All done! Your database is ready.${NC}" + echo "" + echo "Next steps:" + echo " 1. Restart your Next.js dev server: npm run dev" + echo " 2. Visit http://localhost:3000" + echo " 3. The activity feed should now work without errors" +else + echo "" + echo -e "${RED}❌ Migration failed${NC}" + echo "" + echo "Troubleshooting:" + echo " 1. Ensure PostgreSQL is running: pg_isready" + echo " 2. Check your DATABASE_URL in .env.local" + echo " 3. Verify database exists: psql -l | grep $DB_NAME" + echo " 4. Try manual migration: psql $DB_NAME -f prisma/migrations/create_activity_status.sql" + exit 1 +fi diff --git a/prisma/schema.prisma b/prisma/schema.prisma index f34bf02..a645fc5 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -103,3 +103,30 @@ enum InteractionType { BOOKMARK COMMENT } + +model ActivityStatus { + id Int @id @default(1) + activityType String? @map("activity_type") @db.VarChar(50) + activityDetails String? @map("activity_details") @db.VarChar(255) + activityProject String? @map("activity_project") @db.VarChar(255) + activityLanguage String? @map("activity_language") @db.VarChar(50) + activityRepo String? @map("activity_repo") @db.VarChar(500) + musicPlaying Boolean @default(false) @map("music_playing") + musicTrack String? @map("music_track") @db.VarChar(255) + musicArtist String? @map("music_artist") @db.VarChar(255) + musicAlbum String? @map("music_album") @db.VarChar(255) + musicPlatform String? @map("music_platform") @db.VarChar(50) + musicProgress Int? @map("music_progress") + musicAlbumArt String? @map("music_album_art") @db.VarChar(500) + watchingTitle String? @map("watching_title") @db.VarChar(255) + watchingPlatform String? @map("watching_platform") @db.VarChar(50) + watchingType String? @map("watching_type") @db.VarChar(50) + gamingGame String? @map("gaming_game") @db.VarChar(255) + gamingPlatform String? @map("gaming_platform") @db.VarChar(50) + gamingStatus String? @map("gaming_status") @db.VarChar(50) + statusMood String? @map("status_mood") @db.VarChar(50) + statusMessage String? @map("status_message") @db.VarChar(500) + updatedAt DateTime @default(now()) @updatedAt @map("updated_at") + + @@map("activity_status") +} diff --git a/prisma/seed.ts b/prisma/seed.ts index 9c919dd..af0e377 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -1,296 +1,236 @@ -import { PrismaClient } from '@prisma/client'; +import { PrismaClient } from "@prisma/client"; const prisma = new PrismaClient(); async function main() { - console.log('🌱 Seeding database...'); + console.log("🌱 Seeding database..."); // Clear existing data await prisma.userInteraction.deleteMany(); await prisma.pageView.deleteMany(); await prisma.project.deleteMany(); - // Create sample projects + // Create real projects const projects = [ { - title: "Portfolio Website 2.0", - description: "A cutting-edge portfolio website showcasing modern web development techniques with advanced features and stunning design.", - content: `# Portfolio Website 2.0 + title: "Clarity", + description: + "A Flutter mobile app supporting people with dyslexia by displaying text in OpenDyslexic font and simplifying content using AI.", + content: `# Clarity - Dyslexia Support App -This is my personal portfolio website built with cutting-edge web technologies. The site features a dark theme with glassmorphism effects, smooth animations, and advanced interactive elements. +Clarity is a mobile application built with Flutter to help people with dyslexia read and understand text more easily. + +## 🎯 Purpose + +The app was designed to make reading more accessible by using the OpenDyslexic font, which is specifically designed to make letters more distinguishable and reduce reading errors. ## 🚀 Features -- **Responsive Design**: Works perfectly on all devices -- **Dark Theme**: Modern dark mode with glassmorphism effects -- **Animations**: Smooth animations powered by Framer Motion -- **Markdown Support**: Projects are written in Markdown for easy editing -- **Performance**: Optimized for speed and SEO -- **Interactive Elements**: Advanced UI components and micro-interactions -- **Accessibility**: WCAG 2.1 AA compliant -- **Analytics**: Built-in performance and user analytics +- **OpenDyslexic Font**: All text is displayed in the OpenDyslexic typeface +- **AI Text Simplification**: Complex texts are simplified using AI integration +- **Clean Interface**: Simple, distraction-free reading experience +- **Mobile-First**: Optimized for smartphones and tablets +- **Accessibility**: Built with accessibility in mind from the ground up ## 🛠️ Technologies Used -- Next.js 15 -- TypeScript -- Tailwind CSS -- Framer Motion -- React Markdown -- Advanced CSS (Grid, Flexbox, Custom Properties) -- Performance optimization techniques +- Flutter +- Dart +- AI Integration for text simplification +- OpenDyslexic Font -## 📈 Development Process +## 📱 Platform Support -The website was designed with a focus on user experience, performance, and accessibility. I used modern CSS techniques and best practices to create a responsive, fast, and beautiful layout. +- iOS +- Android -## 🔮 Future Improvements +## 💡 What I Learned -- AI-powered content suggestions -- Advanced project filtering and search -- Interactive project demos -- Real-time collaboration features -- Advanced analytics dashboard +Building Clarity taught me a lot about accessibility, mobile UI/UX design, and how to integrate AI services into mobile applications. It was rewarding to create something that could genuinely help people in their daily lives. -## 🔗 Links +## 🔮 Future Plans -- [Live Demo](https://dki.one) -- [GitHub Repository](https://github.com/Denshooter/portfolio)`, - tags: ["Next.js", "TypeScript", "Tailwind CSS", "Framer Motion", "Advanced CSS", "Performance"], +- Add more font options +- Implement text-to-speech +- Support for more languages +- PDF and document scanning`, + tags: ["Flutter", "Mobile", "AI", "Accessibility", "Dart"], featured: true, - category: "Web Development", - date: "2024", - published: true, - difficulty: "ADVANCED", - timeToComplete: "3-4 weeks", - technologies: ["Next.js 15", "TypeScript", "Tailwind CSS", "Framer Motion", "React Markdown"], - challenges: ["Complex state management", "Performance optimization", "Responsive design across devices"], - lessonsLearned: ["Advanced CSS techniques", "Performance optimization", "User experience design"], - futureImprovements: ["AI integration", "Advanced analytics", "Real-time features"], - demoVideo: "", - screenshots: [], - colorScheme: "Dark with glassmorphism", - accessibility: true, - performance: { - lighthouse: 0, - bundleSize: "0KB", - loadTime: "0s" - }, - analytics: { - views: 1250, - likes: 89, - shares: 23 - } - }, - { - title: "E-Commerce Platform", - description: "A full-stack e-commerce solution with advanced features like real-time inventory, payment processing, and admin dashboard.", - content: `# E-Commerce Platform - -A comprehensive e-commerce solution built with modern web technologies, featuring a robust backend, secure payment processing, and an intuitive user interface. - -## 🚀 Features - -- **User Authentication**: Secure login and registration -- **Product Management**: Add, edit, and delete products -- **Shopping Cart**: Persistent cart with real-time updates -- **Payment Processing**: Stripe integration for secure payments -- **Order Management**: Complete order lifecycle tracking -- **Admin Dashboard**: Comprehensive admin interface -- **Inventory Management**: Real-time stock tracking -- **Responsive Design**: Mobile-first approach - -## 🛠️ Technologies Used - -- Frontend: React, TypeScript, Tailwind CSS -- Backend: Node.js, Express, Prisma -- Database: PostgreSQL -- Payment: Stripe API -- Authentication: JWT, bcrypt -- Deployment: Docker, AWS - -## 📈 Development Process - -Built with a focus on scalability and user experience. Implemented proper error handling, input validation, and security measures throughout the development process. - -## 🔮 Future Improvements - -- Multi-language support -- Advanced analytics dashboard -- AI-powered product recommendations -- Mobile app development -- Advanced search and filtering`, - tags: ["React", "Node.js", "PostgreSQL", "Stripe", "E-commerce", "Full-Stack"], - featured: true, - category: "Full-Stack", - date: "2024", - published: true, - difficulty: "EXPERT", - timeToComplete: "8-10 weeks", - technologies: ["React", "Node.js", "PostgreSQL", "Stripe", "Docker", "AWS"], - challenges: ["Payment integration", "Real-time updates", "Scalability", "Security"], - lessonsLearned: ["Payment processing", "Real-time systems", "Security best practices", "Scalable architecture"], - futureImprovements: ["AI recommendations", "Mobile app", "Multi-language", "Advanced analytics"], - demoVideo: "", - screenshots: [], - colorScheme: "Professional and clean", - accessibility: true, - performance: { - lighthouse: 0, - bundleSize: "0KB", - loadTime: "0s" - }, - analytics: { - views: 890, - likes: 67, - shares: 18 - } - }, - { - title: "Task Management App", - description: "A collaborative task management application with real-time updates, team collaboration, and progress tracking.", - content: `# Task Management App - -A collaborative task management application designed for teams to organize, track, and complete projects efficiently. - -## 🚀 Features - -- **Task Creation**: Easy task creation with descriptions and deadlines -- **Team Collaboration**: Assign tasks to team members -- **Real-time Updates**: Live updates across all connected clients -- **Progress Tracking**: Visual progress indicators and analytics -- **File Attachments**: Support for documents and images -- **Notifications**: Email and push notifications for updates -- **Mobile Responsive**: Works perfectly on all devices -- **Dark/Light Theme**: User preference support - -## 🛠️ Technologies Used - -- Frontend: React, TypeScript, Tailwind CSS -- Backend: Node.js, Express, Socket.io -- Database: MongoDB -- Real-time: WebSockets -- Authentication: JWT -- File Storage: AWS S3 -- Deployment: Heroku - -## 📈 Development Process - -Focused on creating an intuitive user interface and seamless real-time collaboration. Implemented proper error handling and user feedback throughout the development. - -## 🔮 Future Improvements - -- Advanced reporting and analytics -- Integration with external tools -- Mobile app development -- AI-powered task suggestions -- Advanced automation features`, - tags: ["React", "Node.js", "MongoDB", "WebSockets", "Collaboration", "Real-time"], - featured: false, - category: "Web Application", + category: "Mobile Development", date: "2024", published: true, difficulty: "INTERMEDIATE", - timeToComplete: "6-8 weeks", - technologies: ["React", "Node.js", "MongoDB", "Socket.io", "AWS S3", "Heroku"], - challenges: ["Real-time synchronization", "Team collaboration", "File management", "Mobile responsiveness"], - lessonsLearned: ["WebSocket implementation", "Real-time systems", "File upload handling", "Team collaboration features"], - futureImprovements: ["Advanced analytics", "Mobile app", "AI integration", "Automation"], + timeToComplete: "4-6 weeks", + technologies: ["Flutter", "Dart", "AI Integration", "OpenDyslexic Font"], + challenges: [ + "Implementing AI text simplification", + "Font rendering optimization", + "Mobile accessibility standards", + ], + lessonsLearned: [ + "Mobile development with Flutter", + "Accessibility best practices", + "AI API integration", + ], + futureImprovements: [ + "Text-to-speech", + "Multi-language support", + "Document scanning", + ], demoVideo: "", screenshots: [], - colorScheme: "Modern and clean", - accessibility: true, - performance: { - lighthouse: 88, - bundleSize: "65KB", - loadTime: "1.5s" - }, - analytics: { - views: 567, - likes: 34, - shares: 12 - } - }, - { - title: "Weather Dashboard", - description: "A beautiful weather application with real-time data, forecasts, and interactive maps.", - content: `# Weather Dashboard - -A beautiful and functional weather application that provides real-time weather data, forecasts, and interactive maps. - -## 🚀 Features - -- **Current Weather**: Real-time weather conditions -- **Forecast**: 7-day weather predictions -- **Interactive Maps**: Visual weather maps with overlays -- **Location Search**: Find weather for any location -- **Weather Alerts**: Severe weather notifications -- **Historical Data**: Past weather information -- **Responsive Design**: Works on all devices -- **Offline Support**: Basic functionality without internet - -## 🛠️ Technologies Used - -- Frontend: React, TypeScript, Tailwind CSS -- Maps: Mapbox GL JS -- Weather API: OpenWeatherMap -- State Management: Zustand -- Charts: Chart.js -- Icons: Weather Icons -- Deployment: Vercel - -## 📈 Development Process - -Built with a focus on user experience and visual appeal. Implemented proper error handling for API failures and created an intuitive interface for weather information. - -## 🔮 Future Improvements - -- Weather widgets for other websites -- Advanced forecasting algorithms -- Weather-based recommendations -- Social sharing features -- Weather photography integration`, - tags: ["React", "TypeScript", "Weather API", "Maps", "Real-time", "UI/UX"], - featured: false, - category: "Web Application", - date: "2024", - published: true, - difficulty: "BEGINNER", - timeToComplete: "3-4 weeks", - technologies: ["React", "TypeScript", "Tailwind CSS", "Mapbox", "OpenWeatherMap", "Chart.js"], - challenges: ["API integration", "Map implementation", "Responsive design", "Error handling"], - lessonsLearned: ["External API integration", "Map libraries", "Responsive design", "Error handling"], - futureImprovements: ["Advanced forecasting", "Weather widgets", "Social features", "Mobile app"], - demoVideo: "", - screenshots: [], - colorScheme: "Light and colorful", + colorScheme: "Clean and minimal with high contrast", accessibility: true, performance: { lighthouse: 0, bundleSize: "0KB", - loadTime: "0s" + loadTime: "0s", }, analytics: { - views: 423, - likes: 28, - shares: 8 - } - } + views: 850, + likes: 67, + shares: 34, + }, + }, + { + title: "Self-Hosted Infrastructure & Portfolio", + description: + "A complete DevOps setup running in Docker Swarm. My Next.js projects are deployed via automated CI/CD pipelines with custom runners.", + content: `# Self-Hosted Infrastructure & Portfolio + +Not just a website – this is a complete self-hosted infrastructure project showcasing my DevOps skills and passion for self-hosting. + +## 🏗️ Architecture + +All my projects run on a Docker Swarm cluster hosted on IONOS and OVHcloud servers. Everything is self-managed, from the networking layer to the application deployments. + +## 🚀 Features + +- **Docker Swarm Cluster**: Multi-node orchestration for high availability +- **Traefik Reverse Proxy**: Automatic SSL certificates and routing +- **Automated CI/CD**: Custom GitLab/Gitea runners for continuous deployment +- **Zero-Downtime Deployments**: Rolling updates without service interruption +- **Redis Caching**: Performance optimization with Redis +- **Nginx Proxy Manager**: Additional layer for complex routing scenarios + +## 🛠️ Tech Stack + +- **Frontend**: Next.js, Tailwind CSS +- **Infrastructure**: Docker Swarm, Traefik, Nginx Proxy Manager +- **CI/CD**: Custom Git runners with automated pipelines +- **Monitoring**: Self-hosted monitoring stack +- **Security**: CrowdSec, Suricata, Mailcow +- **Caching**: Redis + +## 🔐 Security + +Security is a top priority. I use CrowdSec for intrusion prevention, Suricata for network monitoring, and Mailcow for secure email communications. + +## 📈 DevOps Process + +1. Code push triggers CI/CD pipeline +2. Automated tests run on custom runners +3. Docker images are built and tagged +4. Rolling deployment to Swarm cluster +5. Traefik automatically routes traffic +6. Zero downtime for users + +## 💡 What I Learned + +This project taught me everything about production-grade DevOps, from container orchestration to security hardening. Managing my own infrastructure has given me deep insights into networking, load balancing, and system administration. + +## 🎯 Other Projects + +Besides this portfolio, I host: +- Interactive photo galleries +- Quiz applications +- Game servers +- n8n automation workflows +- Various experimental Next.js apps + +## 🔮 Future Improvements + +- Kubernetes migration for more advanced orchestration +- Automated backup and disaster recovery +- Advanced monitoring with Prometheus and Grafana +- Multi-region deployment`, + tags: [ + "Docker", + "Swarm", + "DevOps", + "CI/CD", + "Next.js", + "Traefik", + "Self-Hosting", + ], + featured: true, + category: "DevOps", + date: "2024", + published: true, + difficulty: "ADVANCED", + timeToComplete: "Ongoing project", + technologies: [ + "Docker Swarm", + "Traefik", + "Next.js", + "Redis", + "CI/CD", + "Nginx", + "CrowdSec", + "Suricata", + ], + challenges: [ + "Zero-downtime deployments", + "Network configuration", + "Security hardening", + "Performance optimization", + ], + lessonsLearned: [ + "Container orchestration", + "DevOps practices", + "Infrastructure as Code", + "Security best practices", + ], + futureImprovements: [ + "Kubernetes migration", + "Multi-region setup", + "Advanced monitoring", + "Automated backups", + ], + demoVideo: "", + screenshots: [], + colorScheme: "Modern and professional", + accessibility: true, + performance: { + lighthouse: 0, + bundleSize: "0KB", + loadTime: "0s", + }, + analytics: { + views: 1420, + likes: 112, + shares: 45, + }, + }, ]; for (const project of projects) { await prisma.project.create({ data: { ...project, - difficulty: project.difficulty as 'BEGINNER' | 'INTERMEDIATE' | 'ADVANCED' | 'EXPERT', - } + difficulty: project.difficulty as + | "BEGINNER" + | "INTERMEDIATE" + | "ADVANCED" + | "EXPERT", + }, }); } - console.log(`✅ Created ${projects.length} sample projects`); + console.log(`✅ Created ${projects.length} projects`); // Create some sample analytics data - for (let i = 1; i <= 4; i++) { + for (let i = 1; i <= projects.length; i++) { // Create page views for (let j = 0; j < Math.floor(Math.random() * 100) + 50; j++) { await prisma.pageView.create({ @@ -298,9 +238,10 @@ Built with a focus on user experience and visual appeal. Implemented proper erro projectId: i, page: `/projects/${i}`, ip: `192.168.1.${Math.floor(Math.random() * 255)}`, - userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', - referrer: 'https://google.com' - } + userAgent: + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", + referrer: "https://google.com", + }, }); } @@ -309,22 +250,23 @@ Built with a focus on user experience and visual appeal. Implemented proper erro await prisma.userInteraction.create({ data: { projectId: i, - type: Math.random() > 0.5 ? 'LIKE' : 'SHARE', + type: Math.random() > 0.5 ? "LIKE" : "SHARE", ip: `192.168.1.${Math.floor(Math.random() * 255)}`, - userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' - } + userAgent: + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", + }, }); } } - console.log('✅ Created sample analytics data'); + console.log("✅ Created sample analytics data"); - console.log('🎉 Database seeding completed!'); + console.log("🎉 Database seeding completed!"); } main() .catch((e) => { - console.error('❌ Error seeding database:', e); + console.error("❌ Error seeding database:", e); process.exit(1); }) .finally(async () => { diff --git a/tailwind.config.ts b/tailwind.config.ts index 98583c8..0fe91b6 100644 --- a/tailwind.config.ts +++ b/tailwind.config.ts @@ -65,11 +65,19 @@ export default { blue: "#BFDBFE", rose: "#FECACA", yellow: "#FDE68A", - } + peach: "#FED7AA", + pink: "#FBCFE8", + sky: "#BAE6FD", + lime: "#D9F99D", + coral: "#FCA5A5", + purple: "#E9D5FF", + teal: "#99F6E4", + amber: "#FDE047", + }, }, fontFamily: { - sans: ['var(--font-inter)', 'sans-serif'], - mono: ['var(--font-roboto-mono)', 'monospace'], + sans: ["var(--font-inter)", "sans-serif"], + mono: ["var(--font-roboto-mono)", "monospace"], }, }, },