mirror of
https://github.com/trafficlunar/tomodachi-share.git
synced 2026-05-13 21:27:46 +00:00
Compare commits
No commits in common. "0e2df242d02818679f635f44627040902f96cde4" and "ca2117c4a382821e0034e0483eca32d01746f149" have entirely different histories.
0e2df242d0
...
ca2117c4a3
9 changed files with 133 additions and 157 deletions
|
|
@ -80,8 +80,6 @@ For Discord, create an application in the developer portal, go to 'OAuth2', copy
|
|||
|
||||
For GitHub, navigate to your profile settings, then 'Developer Settings', and create a new application. Set the homepage URL to `http://localhost:3000` and copy the Client ID and generate a new client secret. Finally, add in a callback URL with the value `http://localhost:3000/api/auth/callback/github`.
|
||||
|
||||
Google is annoying so I'm not explaining it.
|
||||
|
||||
After configuring the environment variables, you can run a development server.
|
||||
|
||||
```bash
|
||||
|
|
|
|||
|
|
@ -93,7 +93,7 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
|
|||
makeup: formData.get("makeup") ?? undefined,
|
||||
miiPortraitImage: formData.get("miiPortraitImage"),
|
||||
miiFeaturesImage: formData.get("miiFeaturesImage"),
|
||||
youtubeId: formData.get("youtubeId") ?? undefined,
|
||||
youtubeId: formData.get("youtubeId"),
|
||||
instructions: minifiedInstructions,
|
||||
image1: formData.get("image1"),
|
||||
image2: formData.get("image2"),
|
||||
|
|
@ -110,28 +110,26 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
|
|||
parsed.data;
|
||||
|
||||
// Validate image files
|
||||
const customImages: File[] = [];
|
||||
let wasImagesModerated = false;
|
||||
const images: File[] = [];
|
||||
|
||||
for (const img of [image1, image2, image3]) {
|
||||
if (!img) continue;
|
||||
|
||||
const validation = await validateImage(img);
|
||||
if (validation.valid) {
|
||||
customImages.push(img);
|
||||
} else {
|
||||
return rateLimit.sendResponse({ error: `Failed to verify custom image: ${validation.error}` }, validation.status ?? 400);
|
||||
}
|
||||
if (!validation.valid) wasImagesModerated = true;
|
||||
images.push(img);
|
||||
}
|
||||
|
||||
// Check Mii portrait & features image (Switch)
|
||||
if (mii.platform === "SWITCH") {
|
||||
if (miiPortraitImage) {
|
||||
const validation = await validateImage(miiPortraitImage);
|
||||
if (!validation.valid) return rateLimit.sendResponse({ error: `Failed to verify portrait: ${validation.error}` }, validation.status ?? 400);
|
||||
if (!validation.valid) wasImagesModerated = true;
|
||||
}
|
||||
if (miiFeaturesImage) {
|
||||
const validation = await validateImage(miiFeaturesImage);
|
||||
if (!validation.valid) return rateLimit.sendResponse({ error: `Failed to verify features: ${validation.error}` }, validation.status ?? 400);
|
||||
if (!validation.valid) wasImagesModerated = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -149,10 +147,10 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
|
|||
if (makeup !== undefined) updateData.makeup = makeup;
|
||||
if (youtubeId !== undefined) updateData.youtubeId = youtubeId;
|
||||
if (instructions !== undefined) updateData.instructions = instructions;
|
||||
if (customImages.length > 0) updateData.imageCount = customImages.length;
|
||||
if (images.length > 0) updateData.imageCount = images.length;
|
||||
|
||||
const imagesChanged = customImages.length > 0 || miiPortraitImage || miiFeaturesImage;
|
||||
if (settings.queueEnabled && imagesChanged) updateData.in_queue = true;
|
||||
const imagesChanged = images.length > 0 || miiPortraitImage || miiFeaturesImage;
|
||||
if ((settings.queueEnabled && imagesChanged) || wasImagesModerated) updateData.in_queue = true;
|
||||
|
||||
if (Object.keys(updateData).length === 0) return rateLimit.sendResponse({ error: "Nothing was changed" }, 400);
|
||||
const updatedMii = await prisma.mii.update({
|
||||
|
|
@ -174,7 +172,7 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
|
|||
await fs.mkdir(miiUploadsDirectory, { recursive: true });
|
||||
|
||||
// Only touch files if new images were uploaded
|
||||
if (customImages.length > 0) {
|
||||
if (images.length > 0) {
|
||||
// Delete all custom images
|
||||
const files = await fs.readdir(miiUploadsDirectory);
|
||||
await Promise.all(files.filter((file) => file.startsWith("image")).map((file) => fs.unlink(path.join(miiUploadsDirectory, file))));
|
||||
|
|
@ -182,7 +180,7 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
|
|||
// Compress and upload new images
|
||||
try {
|
||||
await Promise.all(
|
||||
customImages.map(async (image, index) => {
|
||||
images.map(async (image, index) => {
|
||||
const buffer = Buffer.from(await image.arrayBuffer());
|
||||
const pngBuffer = await sharp(buffer).resize({ height: 800, fit: "inside", withoutEnlargement: true }).png({ quality: 85 }).toBuffer();
|
||||
const fileLocation = path.join(miiUploadsDirectory, `image${index}.png`);
|
||||
|
|
@ -200,6 +198,17 @@ export async function PATCH(request: NextRequest, { params }: { params: Promise<
|
|||
// Only save portrait & features for Switch Miis when they are provided
|
||||
if (mii.platform === "SWITCH" && (miiPortraitImage || miiFeaturesImage)) {
|
||||
try {
|
||||
// Delete existing portrait/features if they're being replaced
|
||||
await Promise.all(
|
||||
["mii.png", "features.png"]
|
||||
.filter((file) => {
|
||||
if (file === "mii.png") return miiPortraitImage;
|
||||
if (file === "features.png") return miiFeaturesImage;
|
||||
return false;
|
||||
})
|
||||
.map((file) => fs.unlink(path.join(miiUploadsDirectory, file))),
|
||||
);
|
||||
|
||||
await Promise.all(
|
||||
[
|
||||
miiPortraitImage &&
|
||||
|
|
|
|||
|
|
@ -39,9 +39,8 @@ const submitSchema = z
|
|||
miiFeaturesImage: z.union([z.instanceof(File), z.any()]).optional(),
|
||||
youtubeId: z
|
||||
.string()
|
||||
.trim()
|
||||
.transform((val) => (val === "" ? null : val))
|
||||
.refine((val) => val === null || /^[a-zA-Z0-9_-]{11}$/.test(val), "Invalid YouTube video ID")
|
||||
.regex(/^[a-zA-Z0-9_-]{11}$/, "Invalid YouTube video ID")
|
||||
.or(z.literal(""))
|
||||
.optional(),
|
||||
instructions: switchMiiInstructionsSchema,
|
||||
|
||||
|
|
@ -63,13 +62,13 @@ const submitSchema = z
|
|||
(data) => {
|
||||
// If platform is Switch, gender, miiPortraitImage, and miiFeaturesImage must be present
|
||||
if (data.platform === "SWITCH") {
|
||||
return data.gender !== undefined && data.miiPortraitImage !== undefined && data.miiFeaturesImage !== undefined;
|
||||
return data.gender !== undefined && data.miiPortraitImage !== undefined;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
message: "Gender, Mii portrait & features image are required for Switch platform",
|
||||
path: ["gender", "miiPortraitImage", "miiFeaturesImage"],
|
||||
message: "Gender, Mii portrait & features image, and instructions are required for Switch platform",
|
||||
path: ["gender", "miiPortraitImage", "miiFeaturesImage", "instructions"],
|
||||
},
|
||||
);
|
||||
|
||||
|
|
@ -161,27 +160,23 @@ export async function POST(request: NextRequest) {
|
|||
const description = uncensoredDescription && profanity.censor(uncensoredDescription);
|
||||
|
||||
// Validate image files
|
||||
let wasImagesModerated = false;
|
||||
const customImages: File[] = [];
|
||||
|
||||
for (const img of [image1, image2, image3]) {
|
||||
if (!img) continue;
|
||||
|
||||
const validation = await validateImage(img);
|
||||
if (validation.valid) {
|
||||
customImages.push(img);
|
||||
} else {
|
||||
return rateLimit.sendResponse({ error: `Failed to verify custom image: ${validation.error}` }, validation.status ?? 400);
|
||||
}
|
||||
if (!validation.valid) wasImagesModerated = true;
|
||||
customImages.push(img);
|
||||
}
|
||||
|
||||
// Check Mii portrait & features image (Switch)
|
||||
if (platform === "SWITCH") {
|
||||
const portraitValidation = await validateImage(miiPortraitImage);
|
||||
const featuresValidation = await validateImage(miiFeaturesImage);
|
||||
if (!portraitValidation.valid)
|
||||
return rateLimit.sendResponse({ error: `Failed to verify portrait: ${portraitValidation.error}` }, portraitValidation.status ?? 400);
|
||||
if (!featuresValidation.valid)
|
||||
return rateLimit.sendResponse({ error: `Failed to verify features: ${featuresValidation.error}` }, featuresValidation.status ?? 400);
|
||||
if (!portraitValidation.valid) wasImagesModerated = true;
|
||||
if (!featuresValidation.valid) wasImagesModerated = true;
|
||||
}
|
||||
|
||||
const qrBytes = new Uint8Array(qrBytesRaw ?? []);
|
||||
|
|
@ -206,7 +201,7 @@ export async function POST(request: NextRequest) {
|
|||
tags,
|
||||
description,
|
||||
gender: gender ?? "MALE",
|
||||
in_queue: settings.queueEnabled,
|
||||
in_queue: wasImagesModerated || settings.queueEnabled,
|
||||
|
||||
// Automatically detect certain information if on 3DS
|
||||
...(platform === "THREE_DS"
|
||||
|
|
@ -344,5 +339,5 @@ export async function POST(request: NextRequest) {
|
|||
return rateLimit.sendResponse({ error: "Failed to store user images" }, 500);
|
||||
}
|
||||
|
||||
return rateLimit.sendResponse({ success: true, id: miiRecord.id });
|
||||
return rateLimit.sendResponse({ success: true, id: miiRecord.id, inQueue: wasImagesModerated });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,72 +0,0 @@
|
|||
import { Metadata } from "next";
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { Icon } from "@iconify/react";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Leaving TomodachiShare",
|
||||
description: "Warning: You are leaving TomodachiShare, proceed with caution",
|
||||
};
|
||||
|
||||
interface Props {
|
||||
searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
|
||||
}
|
||||
|
||||
export default async function LinkOutPage({ searchParams }: Props) {
|
||||
const url = (await searchParams).url;
|
||||
if (!url || Array.isArray(url)) redirect("/");
|
||||
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
redirect("/"); // redirect if URL is invalid
|
||||
}
|
||||
|
||||
// Next.js doesn't allow attacks like these but you can never be too safe
|
||||
if (!["http:", "https:"].includes(parsed.protocol)) redirect("/");
|
||||
|
||||
const isSafe = Array.from(SAFE_LINKS).some((domain) => parsed.hostname === domain || parsed.hostname.endsWith(`.${domain}`));
|
||||
if (isSafe) redirect(url);
|
||||
|
||||
return (
|
||||
<div className="grow flex items-center justify-center">
|
||||
<div className="bg-amber-50 border-2 border-amber-500 rounded-2xl shadow-lg py-8 px-6 max-w-md w-full text-center flex flex-col items-center">
|
||||
<h2 className="text-3xl font-black flex items-center gap-2 mb-1">
|
||||
<Icon icon="mingcute:alert-fill" className="text-5xl" />
|
||||
Warning
|
||||
</h2>
|
||||
<p>You're attempting to leave TomodachiShare island! The destination website is potentially dangerous.</p>
|
||||
|
||||
<div className="bg-zinc-100 border border-zinc-300 rounded-md p-2 break-all w-full mt-4">
|
||||
<code className="font-mono text-sm">{url}</code>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center gap-2">
|
||||
<Link href="/" className="pill button gap-2 mt-8 w-fit self-center bg-zinc-100! border-zinc-300! hover:bg-zinc-300!">
|
||||
<Icon icon="ic:round-home" fontSize={24} />
|
||||
Travel Back
|
||||
</Link>
|
||||
<Link href={url} target="_blank" rel="noopener noreferrer" className="pill button gap-2 mt-8 w-fit self-center">
|
||||
<Icon icon="ic:round-open-in-new" fontSize={21} />
|
||||
Continue
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const SAFE_LINKS = new Set([
|
||||
"tomodachishare.com",
|
||||
"trafficlunar.net",
|
||||
"youtube.com",
|
||||
"youtu.be",
|
||||
"twitter.com",
|
||||
"x.com",
|
||||
"reddit.com",
|
||||
"tiktok.com",
|
||||
"tumblr.com",
|
||||
"instagram.com",
|
||||
"wikipedia.org",
|
||||
]);
|
||||
|
|
@ -1,43 +1,78 @@
|
|||
import { Icon } from "@iconify/react";
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
import ProfilePicture from "./profile-picture";
|
||||
|
||||
interface Props {
|
||||
text: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
// Adds fancy formatting to links
|
||||
export default function Description({ text, className }: Props) {
|
||||
const urlRegex = /(https?:\/\/[^\s]+)/g;
|
||||
const parts = text.split(urlRegex);
|
||||
|
||||
return (
|
||||
<p className={`text-sm mt-2 bg-white/50 p-3 rounded-lg border border-orange-200 whitespace-break-spaces max-h-54 overflow-y-auto ${className}`}>
|
||||
{parts.map(async (part, index) => {
|
||||
try {
|
||||
// Check if it's a URL
|
||||
if (!urlRegex.test(part)) throw new Error("Not a URL");
|
||||
const url = new URL(part);
|
||||
{/* Adds fancy formatting when linking to other pages on the site */}
|
||||
{(() => {
|
||||
const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || "https://tomodachishare.com";
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={index}
|
||||
href={`/out?url=${encodeURIComponent(part)}`}
|
||||
target="_blank"
|
||||
className="text-blue-700 underline break-all ml-1 inline-flex items-center group"
|
||||
title={`Go to ${url.hostname}`}
|
||||
>
|
||||
{url.hostname}
|
||||
{url.pathname !== "/" ? url.pathname : ""}
|
||||
{url.search}
|
||||
<Icon icon="mi:arrow-right-up" fontSize={16} className="transition group-hover:translate-x-0.5 group-hover:-translate-y-0.5" />
|
||||
</Link>
|
||||
);
|
||||
} catch {
|
||||
// Normal text/Invalid URL fallback
|
||||
// Match both mii and profile links
|
||||
const regex = new RegExp(`(${baseUrl.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&")}/(?:mii|profile)/\\d+)`, "g");
|
||||
const parts = text.split(regex);
|
||||
|
||||
return parts.map(async (part, index) => {
|
||||
const miiMatch = part.match(new RegExp(`^${baseUrl}/mii/(\\d+)$`));
|
||||
const profileMatch = part.match(new RegExp(`^${baseUrl}/profile/(\\d+)$`));
|
||||
|
||||
if (miiMatch) {
|
||||
const id = Number(miiMatch[1]);
|
||||
const linkedMii = await prisma.mii.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
|
||||
if (!linkedMii) return;
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={index}
|
||||
href={`/mii/${id}`}
|
||||
className="inline-flex items-center align-bottom gap-1.5 pr-2 bg-amber-100 border border-amber-400 rounded-lg mx-1 text-amber-800 text-xs"
|
||||
>
|
||||
<Image src={`/mii/${id}/image?type=mii`} alt="mii" width={24} height={24} className="bg-white rounded-lg border-r border-amber-400" />
|
||||
{linkedMii.name}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
if (profileMatch) {
|
||||
const id = Number(profileMatch[1]);
|
||||
const linkedProfile = await prisma.user.findUnique({
|
||||
where: {
|
||||
id,
|
||||
},
|
||||
});
|
||||
|
||||
if (!linkedProfile) return;
|
||||
|
||||
return (
|
||||
<Link
|
||||
key={index}
|
||||
href={`/profile/${id}`}
|
||||
className="inline-flex items-center align-bottom gap-1.5 pr-2 bg-orange-100 border border-orange-400 rounded-lg mx-1 text-orange-800 text-xs"
|
||||
>
|
||||
<ProfilePicture src={linkedProfile.image || "/guest.png"} width={24} height={24} className="bg-white rounded-lg border-r border-orange-400" />
|
||||
{linkedProfile.name}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
// Regular text
|
||||
return <span key={index}>{part}</span>;
|
||||
}
|
||||
})}
|
||||
});
|
||||
})()}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,10 +30,6 @@ function not(value: any) {
|
|||
return value !== undefined && value !== null;
|
||||
}
|
||||
|
||||
function numberValue(value: number, cutoff: number = 25) {
|
||||
return value === cutoff ? "0" : value > cutoff ? `+${value - cutoff}` : `${value - cutoff}`;
|
||||
}
|
||||
|
||||
function GridPosition({ index, cols = 5 }: { index: number; cols?: number }) {
|
||||
const row = Math.floor(index / cols) + 1;
|
||||
const col = (index % cols) + 1;
|
||||
|
|
@ -105,11 +101,11 @@ function Section({ name, instructions, children, isSubSection }: SectionProps) {
|
|||
<ColorPosition color={color} />
|
||||
</TableCell>
|
||||
)}
|
||||
{not(height) && <TableCell label="Height">{numberValue(height!, 0)}</TableCell>}
|
||||
{not(distance) && <TableCell label="Distance">{numberValue(distance!, 0)}</TableCell>}
|
||||
{not(rotation) && <TableCell label="Rotation">{numberValue(rotation!, 0)}</TableCell>}
|
||||
{not(size) && <TableCell label="Size">{numberValue(size!, 0)}</TableCell>}
|
||||
{not(stretch) && <TableCell label="Stretch">{numberValue(stretch!, 0)}</TableCell>}
|
||||
{not(height) && <TableCell label="Height">{height}</TableCell>}
|
||||
{not(distance) && <TableCell label="Distance">{distance}</TableCell>}
|
||||
{not(rotation) && <TableCell label="Rotation">{rotation}</TableCell>}
|
||||
{not(size) && <TableCell label="Size">{size}</TableCell>}
|
||||
{not(stretch) && <TableCell label="Stretch">{stretch}</TableCell>}
|
||||
|
||||
{children}
|
||||
</tbody>
|
||||
|
|
@ -198,13 +194,13 @@ export default function MiiInstructions({ instructions }: Props) {
|
|||
)}
|
||||
|
||||
{(height || weight || datingPreferences || voice || personality) && (
|
||||
<div className="p-3 border-l-4 border-amber-400 bg-amber-100/50 rounded-r-lg py-2.5 text-amber-950 w-max">
|
||||
<div className="p-3 text-sm border-l-4 border-amber-400 bg-amber-100/50 rounded-r-lg py-2.5 text-amber-950 w-max">
|
||||
<h3 className="font-semibold text-xl text-amber-800 mb-1">Misc</h3>
|
||||
|
||||
<table className="w-full">
|
||||
<tbody>
|
||||
{not(height) && <TableCell label="Height">{numberValue(height!, 64)}</TableCell>}
|
||||
{not(weight) && <TableCell label="Weight">{numberValue(weight!, 64)}</TableCell>}
|
||||
{not(height) && <TableCell label="Height">{height === 64 ? "0" : height! > 64 ? `+${height! - 64}` : `${height! - 64}`}</TableCell>}
|
||||
{not(weight) && <TableCell label="Weight">{weight === 64 ? "0" : weight! > 64 ? `+${weight! - 64}` : `${weight! - 64}`}</TableCell>}
|
||||
</tbody>
|
||||
</table>
|
||||
{birthday && (
|
||||
|
|
@ -225,10 +221,10 @@ export default function MiiInstructions({ instructions }: Props) {
|
|||
<h4 className="font-semibold text-xl text-amber-800 mb-1">Voice</h4>
|
||||
<table className="w-full">
|
||||
<tbody>
|
||||
{not(voice.speed) && <TableCell label="Speed">{numberValue(voice.speed!, 25)}</TableCell>}
|
||||
{not(voice.pitch) && <TableCell label="Pitch">{numberValue(voice.pitch!, 25)}</TableCell>}
|
||||
{not(voice.depth) && <TableCell label="Depth">{numberValue(voice.depth!, 25)}</TableCell>}
|
||||
{not(voice.delivery) && <TableCell label="Delivery">{numberValue(voice.delivery!, 25)}</TableCell>}
|
||||
{not(voice.speed) && <TableCell label="Speed">{voice.speed}</TableCell>}
|
||||
{not(voice.pitch) && <TableCell label="Pitch">{voice.pitch}</TableCell>}
|
||||
{not(voice.depth) && <TableCell label="Depth">{voice.depth}</TableCell>}
|
||||
{not(voice.delivery) && <TableCell label="Delivery">{voice.delivery}</TableCell>}
|
||||
{not(voice.tone) && <TableCell label="Tone">{voice.tone}</TableCell>}
|
||||
</tbody>
|
||||
</table>
|
||||
|
|
|
|||
|
|
@ -28,9 +28,9 @@ export default function VoiceViewer({ data, onChange, onClickTone }: Props) {
|
|||
type="button"
|
||||
key={i}
|
||||
onClick={() => {
|
||||
if (onClickTone) onClickTone(i + 1);
|
||||
if (onClickTone) onClickTone(i);
|
||||
}}
|
||||
className={`transition-colors duration-100 rounded-xl hover:bg-orange-300 cursor-pointer ${data.tone === i + 1 ? "bg-orange-400!" : ""}`}
|
||||
className={`transition-colors duration-100 rounded-xl hover:bg-orange-300 cursor-pointer ${data.tone === i ? "bg-orange-400!" : ""}`}
|
||||
>
|
||||
{i + 1}
|
||||
</button>
|
||||
|
|
|
|||
|
|
@ -50,11 +50,6 @@ export default function EditForm({ mii, likes }: Props) {
|
|||
const session = useSession();
|
||||
const [files, setFiles] = useState<FileWithPath[]>([]);
|
||||
|
||||
const handleFilesChange: React.Dispatch<React.SetStateAction<FileWithPath[]>> = (updater) => {
|
||||
hasCustomImagesChanged.current = true;
|
||||
setFiles(updater);
|
||||
};
|
||||
|
||||
const handleDrop = useCallback(
|
||||
(acceptedFiles: FileWithPath[]) => {
|
||||
if (files.length >= 3) return;
|
||||
|
|
@ -444,7 +439,7 @@ export default function EditForm({ mii, likes }: Props) {
|
|||
</Dropzone>
|
||||
</div>
|
||||
|
||||
<ImageList files={files} setFiles={handleFilesChange} />
|
||||
<ImageList files={files} setFiles={setFiles} />
|
||||
|
||||
<hr className="border-zinc-300 my-2" />
|
||||
<div className="flex justify-between items-center">
|
||||
|
|
|
|||
|
|
@ -52,6 +52,26 @@ export async function validateImage(file: File): Promise<{ valid: boolean; error
|
|||
return { valid: false, error: "Image dimensions are invalid. Resolution must be between 128x128 and 8000x8000" };
|
||||
}
|
||||
|
||||
// Check for inappropriate content
|
||||
// https://github.com/trafficlunar/api-moderation
|
||||
try {
|
||||
const blob = new Blob([buffer]);
|
||||
const formData = new FormData();
|
||||
formData.append("image", blob);
|
||||
|
||||
const headers = new Headers();
|
||||
headers.append("token", process.env.TOKEN ?? "");
|
||||
const moderationResponse = await fetch("https://api.trafficlunar.net/moderate/image", { method: "POST", body: formData, headers });
|
||||
const result = await moderationResponse.json();
|
||||
if (result.error) {
|
||||
return { valid: false, error: result.error };
|
||||
}
|
||||
} catch (moderationError) {
|
||||
console.error("Error fetching moderation API:", moderationError);
|
||||
Sentry.captureException(moderationError, { extra: { stage: "moderation-api-fetch" } });
|
||||
return { valid: false, error: "Moderation API is down", status: 503 };
|
||||
}
|
||||
|
||||
return { valid: true };
|
||||
} catch (error) {
|
||||
console.error("Error validating image:", error);
|
||||
|
|
|
|||
Loading…
Reference in a new issue