diff --git a/src/app/api/try/[toolId]/route.ts b/src/app/api/try/[toolId]/route.ts index 879d822..8063f1e 100644 --- a/src/app/api/try/[toolId]/route.ts +++ b/src/app/api/try/[toolId]/route.ts @@ -147,6 +147,7 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str // Record rate-limit usage recordUsage(visitorId, ip); + const remainingAfterUsage = Math.max(0, rateCheck.remainingToday - 1); // Call backend or mock engine const { buffer: resultBuffer, contentType } = await executeBackendTryIt( @@ -164,7 +165,7 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str 'Content-Type': contentType, 'Content-Length': resultBuffer.length.toString(), 'Cache-Control': 'no-store, no-cache, must-revalidate', - 'X-Remaining-Tries': rateCheck.remainingToday.toString(), + 'X-Remaining-Tries': remainingAfterUsage.toString(), }, }); diff --git a/src/app/api/user-quota/route.ts b/src/app/api/user-quota/route.ts new file mode 100644 index 0000000..f301c7a --- /dev/null +++ b/src/app/api/user-quota/route.ts @@ -0,0 +1,38 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { checkRateLimits } from '@/lib/api/rateLimiter'; + +export const dynamic = 'force-dynamic'; +export const revalidate = 0; + +export async function GET(req: NextRequest) { + const ip = req.headers.get('x-forwarded-for')?.split(',')[0].trim() || '127.0.0.1'; + let visitorId = req.cookies.get('photoai_vid')?.value; + let isNewVisitor = false; + if (!visitorId) { + visitorId = 'v_' + Math.random().toString(36).substring(2, 15); + isNewVisitor = true; + } + + const rateCheck = checkRateLimits(visitorId, ip); + const response = NextResponse.json({ + allowed: rateCheck.allowed, + remainingToday: rateCheck.remainingToday, + limit: 5, + timestamp: Date.now(), + }, { + headers: { + 'Cache-Control': 'no-store, no-cache, must-revalidate', + }, + }); + + if (isNewVisitor) { + response.cookies.set('photoai_vid', visitorId, { + path: '/', + maxAge: 60 * 60 * 24 * 30, + httpOnly: true, + sameSite: 'lax', + }); + } + + return response; +} diff --git a/src/components/tools/DynamicToolWorkspace.tsx b/src/components/tools/DynamicToolWorkspace.tsx index f076740..458a3aa 100644 --- a/src/components/tools/DynamicToolWorkspace.tsx +++ b/src/components/tools/DynamicToolWorkspace.tsx @@ -1,6 +1,6 @@ 'use client'; -import React, { useState, useRef, useCallback } from 'react'; +import React, { useState, useRef, useCallback, useEffect } from 'react'; import Link from 'next/link'; import { UploadCloud, @@ -10,20 +10,11 @@ import { RotateCcw, Loader2, AlertCircle, - CheckCircle2, - Layers, - SlidersHorizontal, ArrowRight, - Maximize2, - Wand2, RefreshCw, - Image as ImageIcon, - Check, - ChevronRight, - Smartphone, FolderOpen, Zap, - ShieldCheck + Crop } from 'lucide-react'; import { ToolItem, @@ -38,7 +29,7 @@ import { MaskCanvasEditor } from './MaskCanvasEditor'; import { ThumbnailsSection } from './ThumbnailsSection'; import { AlternatingFeaturesSection } from './AlternatingFeaturesSection'; import { ProcessingOverlay } from './ProcessingOverlay'; -import { KineticText } from '@/components/magicui/kinetic-text'; +import { ImageCropper } from './ImageCropper'; import { AnimatedShinyText } from '@/components/magicui/animated-shiny-text'; import { BorderBeam } from '@/components/magicui/border-beam'; @@ -59,7 +50,7 @@ export function DynamicToolWorkspace({ const pageType: ToolPageType = tool.pageType || ( tool.id.includes('lama') || tool.id.includes('eraser') || tool.id.includes('inpaint') ? 'masking' - : tool.id.includes('cartoon') || tool.id.includes('polaroid') + : tool.thumbnails && tool.thumbnails.length > 0 ? 'image-thumbnail' : tool.id.includes('text') || tool.id.includes('prompt') ? 'text-to-image' @@ -91,6 +82,10 @@ export function DynamicToolWorkspace({ const [hasMaskDrawn, setHasMaskDrawn] = useState(false); const getMaskBlobRef = useRef<(() => Promise) | null>(null); + // Cropper State & Export Ref + const getCroppedBlobRef = useRef<(() => Promise) | null>(null); + const [isCropFull, setIsCropFull] = useState(true); + // Inference Execution State const [status, setStatus] = useState<'idle' | 'processing' | 'success' | 'error' | 'limit'>('idle'); const [resultUrl, setResultUrl] = useState(null); @@ -100,6 +95,25 @@ export function DynamicToolWorkspace({ const fileInputRef = useRef(null); const secondaryFileInputRef = useRef(null); + // Fetch verified user quota from server dynamically (immune to inspect tool manipulation) + const fetchUserQuota = useCallback(async () => { + try { + const res = await fetch('/api/user-quota', { cache: 'no-store' }); + if (res.ok) { + const data = await res.json(); + if (typeof data.remainingToday === 'number') { + setRemainingTries(data.remainingToday); + } + } + } catch { + // Keep existing state + } + }, []); + + useEffect(() => { + fetchUserQuota(); + }, [fetchUserQuota]); + // Examples from JSON const primaryExample = tool.content?.examples?.[0] || { before: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=800&auto=format&fit=crop&q=80', @@ -151,7 +165,7 @@ export function DynamicToolWorkspace({ setSecondaryPreview(URL.createObjectURL(file)); }; - const handleLoadSample = (sampleUrl: string, sampleResult?: string) => { + const handleLoadSample = (sampleUrl: string) => { setPrimaryPreview(sampleUrl); setPrimaryFile(null); setResultUrl(null); @@ -165,6 +179,12 @@ export function DynamicToolWorkspace({ // Execute Request dynamically according to pageType const handleExecute = async () => { + if (remainingTries <= 0) { + setStatus('limit'); + setErrorMessage('You have reached the free operations limit for today. Try again tomorrow or get the mobile app.'); + return; + } + setStatus('processing'); setErrorMessage(''); @@ -174,8 +194,23 @@ export function DynamicToolWorkspace({ // 1. Primary Image (for image-based archetypes) if (pageType !== 'text-to-image') { const imageParamName = tool.maskingConfig?.imageParamName || tool.twoImagesConfig?.firstImageParam || 'image'; - if (primaryFile) { - formData.append(imageParamName, primaryFile); + + let fileToSend: Blob | File | null = primaryFile; + + // If user cropped the image via ImageCropper + if (getCroppedBlobRef.current) { + try { + const croppedBlob = await getCroppedBlobRef.current(); + if (croppedBlob) { + fileToSend = croppedBlob; + } + } catch (e) { + console.error('Failed to export cropped blob, using original:', e); + } + } + + if (fileToSend) { + formData.append(imageParamName, fileToSend, 'photo.jpg'); } else if (primaryPreview) { const res = await fetch(primaryPreview); const blob = await res.blob(); @@ -226,7 +261,7 @@ export function DynamicToolWorkspace({ formData.append('aspect_ratio', aspectRatio); } - // 5. Selected Thumbnail / Style Preset (for image-thumbnail or any tool with thumbnails) + // 5. Selected Thumbnail / Style Preset if (selectedThumbnail) { formData.append('style', selectedThumbnail.value); formData.append('variant', selectedThumbnail.value); @@ -254,7 +289,14 @@ export function DynamicToolWorkspace({ const outputUrl = URL.createObjectURL(blob); setResultUrl(outputUrl); setStatus('success'); - setRemainingTries((prev) => Math.max(0, prev - 1)); + + // Update verified remaining count from server response headers or server quota + const remainingHeader = res.headers.get('X-Remaining-Tries'); + if (remainingHeader !== null && !isNaN(parseInt(remainingHeader, 10))) { + setRemainingTries(parseInt(remainingHeader, 10)); + } else { + fetchUserQuota(); + } } catch { setStatus('error'); setErrorMessage('Network error during model inference.'); @@ -283,83 +325,54 @@ export function DynamicToolWorkspace({ if (viewMode === 'studio') { return (
- {/* Studio Sticky Header */} + + {/* Studio Clean Top Bar (Old duplicate buttons & pills removed) */}
- {/* Left: Back to Overview & Tool Title */} + {/* Left: Clean Back to Overview */} + + + {/* Right: Direct Download when Result is Ready */}
- - -
- -
- - {toolName} - - - {pageType} studio - -
-
- - {/* Right: Actions, Tries, Process Button */} -
- - {remainingTries} free tries today - - - - - {status === 'success' && resultUrl ? ( + {status === 'success' && resultUrl && ( - + Download Result - ) : ( - )}
{/* Studio Workspace Canvas */} -
+
+ {/* Prominent, Visually Large Tool Heading & Subtitle */} +
+
+ Tools + / + {toolName} +
+

+ {toolName} +

+

+ {toolSummary} +

+
+ {/* Error Banner */} {errorMessage && (
@@ -369,7 +382,7 @@ export function DynamicToolWorkspace({ )} {/* Archetype Studio Layout */} -
+
{/* POST-EDIT RESULT COMPARISON VIEW (If inference succeeded) */} {status === 'success' && resultUrl ? ( @@ -405,8 +418,8 @@ export function DynamicToolWorkspace({ />
- {/* POST-EDIT ACTION BAR: DIRECTLY BELOW THE RESULT SLIDER */} -
+ {/* POST-EDIT ACTION BAR */} +
- )} -
- {/* Right: Massive High-Visibility Main Process Button */} + {/* Right: Massive High-Visibility Main Process Button with Dynamic Server-backed Quota Icon */}
-
-
- - - Volatile GPU memory execution · Zero server storage - - {remainingTries} free daily operations remaining
@@ -695,15 +685,6 @@ export function DynamicToolWorkspace({
- {/* Quick Info Row */} -
-
- - In-browser volatile GPU RAM execution · Zero server storage -
- Unlimited batch & 4K exports available in {homeApp ? resolveLocalised(homeApp.name, locale) : 'the mobile app'} -
-
); @@ -716,17 +697,17 @@ export function DynamicToolWorkspace({
{/* ================= HERO SECTION ================= */} -
+
{/* Ambient Radial Spotlight */}