Added some error message handling and added basic info about functionality on ui

This commit is contained in:
Tom 2024-01-06 20:17:04 +00:00
parent 0f7fb11f4e
commit 68df045c54
13 changed files with 232 additions and 93 deletions

View File

@ -19,7 +19,7 @@ export async function GET(req: Request) {
const voice = voices.find(v => v.value == new String(u?.ttsDefaultVoice)) const voice = voices.find(v => v.value == new String(u?.ttsDefaultVoice))
return NextResponse.json(voice); return NextResponse.json(voice);
} catch (error) { } catch (error) {
console.log("[TTS/FILTER/USER]", error); console.log("[TTS/FILTER/DEFAULT]", error);
return new NextResponse("Internal Error", { status: 500 }); return new NextResponse("Internal Error", { status: 500 });
} }
} }
@ -32,11 +32,9 @@ export async function POST(req: Request) {
} }
const { voice } = await req.json(); const { voice } = await req.json();
console.log(voice) if (!voice || !voices.map(v => v.label.toLowerCase()).includes(voice.toLowerCase())) return new NextResponse("Bad Request", { status: 400 });
const v = voices.find(v => v.label.toLowerCase() == voice.toLowerCase()) const v = voices.find(v => v.label.toLowerCase() == voice.toLowerCase())
if (v == null)
return new NextResponse("Bad Request", { status: 400 });
await db.user.update({ await db.user.update({
where: { where: {
@ -49,7 +47,7 @@ export async function POST(req: Request) {
return new NextResponse("", { status: 200 }); return new NextResponse("", { status: 200 });
} catch (error) { } catch (error) {
console.log("[TTS/FILTER/USER]", error); console.log("[TTS/FILTER/DEFAULT]", error);
return new NextResponse("Internal Error", { status: 500 }); return new NextResponse("Internal Error", { status: 500 });
} }
} }

View File

@ -30,6 +30,8 @@ export async function POST(req: Request) {
} }
const { username, tag } = await req.json(); const { username, tag } = await req.json();
if (!username || username.length < 4 || username.length > 25) return new NextResponse("Bad Request", { status: 400 });
if (!tag || !["blacklisted", "priority"].includes(tag)) return new NextResponse("Bad Request", { status: 400 });
const filter = await db.ttsUsernameFilter.upsert({ const filter = await db.ttsUsernameFilter.upsert({
where: { where: {
@ -64,6 +66,7 @@ export async function DELETE(req: Request) {
const { searchParams } = new URL(req.url) const { searchParams } = new URL(req.url)
const username = searchParams.get('username') as string const username = searchParams.get('username') as string
if (!username || username.length < 4 || username.length > 25) return new NextResponse("Bad Request", { status: 400 });
const filter = await db.ttsUsernameFilter.delete({ const filter = await db.ttsUsernameFilter.delete({
where: { where: {

View File

@ -30,6 +30,8 @@ export async function POST(req: Request) {
} }
const { search, replace } = await req.json(); const { search, replace } = await req.json();
if (!search || search.length < 4 || search.length > 200) return new NextResponse("Bad Request", { status: 400 });
if (!replace) return new NextResponse("Bad Request", { status: 400 });
const filter = await db.ttsWordFilter.create({ const filter = await db.ttsWordFilter.create({
data: { data: {
@ -54,6 +56,9 @@ export async function PUT(req: Request) {
} }
const { id, search, replace } = await req.json(); const { id, search, replace } = await req.json();
if (!id || id.length < 1) return new NextResponse("Bad Request", { status: 400 });
if (!search || search.length < 4 || search.length > 200) return new NextResponse("Bad Request", { status: 400 });
if (!replace) return new NextResponse("Bad Request", { status: 400 });
const filter = await db.ttsWordFilter.update({ const filter = await db.ttsWordFilter.update({
where: { where: {
@ -83,8 +88,11 @@ export async function DELETE(req: Request) {
const { searchParams } = new URL(req.url) const { searchParams } = new URL(req.url)
const id = searchParams.get('id') as string const id = searchParams.get('id') as string
const search = searchParams.get('search') as string const search = searchParams.get('search') as string
if (!id && !search) return new NextResponse("Bad Request", { status: 400 });
if (search) { if (search) {
if (search.length < 4 || search.length > 200) return new NextResponse("Bad Request", { status: 400 });
const filter = await db.ttsWordFilter.delete({ const filter = await db.ttsWordFilter.delete({
where: { where: {
userId_search: { userId_search: {
@ -96,6 +104,8 @@ export async function DELETE(req: Request) {
return NextResponse.json(filter) return NextResponse.json(filter)
} else if (id) { } else if (id) {
if (id.length < 1) return new NextResponse("Bad Request", { status: 400 });
const filter = await db.ttsWordFilter.delete({ const filter = await db.ttsWordFilter.delete({
where: { where: {
id: id id: id

View File

@ -10,21 +10,14 @@ export async function GET(req: Request) {
return new NextResponse("Unauthorized", { status: 401 }); return new NextResponse("Unauthorized", { status: 401 });
} }
const u = await db.user.findFirst({
where: {
id: user.id
}
});
let list : { let list : {
value: string; value: string;
label: string; label: string;
gender: string; gender: string;
language: string; language: string;
}[] = [] }[] = []
const enabled = u?.ttsEnabledVoice ?? 0 const enabled = user.ttsEnabledVoice
for (let i = 0; i < voices.length; i++) { for (let v of voices) {
var v = voices[i]
var n = Number.parseInt(v.value) - 1 var n = Number.parseInt(v.value) - 1
if ((enabled & (1 << n)) > 0) { if ((enabled & (1 << n)) > 0) {
list.push(v) list.push(v)
@ -46,7 +39,6 @@ export async function POST(req: Request) {
} }
let { voice } = await req.json(); let { voice } = await req.json();
console.log(voice)
voice = voice & ((1 << voices.length) - 1) voice = voice & ((1 << voices.length) - 1)
await db.user.update({ await db.user.update({

View File

@ -10,11 +10,16 @@ import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, Command
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"; import { Form, FormControl, FormField, FormItem, FormMessage } from "@/components/ui/form";
import * as z from "zod"; import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { ToastAction } from "@/components/ui/toast"
import { useToast } from "@/components/ui/use-toast"
import InfoNotice from "@/components/elements/info-notice";
import { Toaster } from "@/components/ui/toaster";
import { stringifyError } from "next/dist/shared/lib/utils";
const TTSFiltersPage = () => { const TTSFiltersPage = () => {
@ -23,6 +28,8 @@ const TTSFiltersPage = () => {
const [tag, setTag] = useState("blacklisted") const [tag, setTag] = useState("blacklisted")
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const [userTags, setUserTag] = useState<{ username: string, tag: string }[]>([]) const [userTags, setUserTag] = useState<{ username: string, tag: string }[]>([])
const { toast } = useToast()
const [error, setError] = useState("")
const router = useRouter(); const router = useRouter();
const tags = [ const tags = [
@ -30,9 +37,24 @@ const TTSFiltersPage = () => {
"priority" "priority"
] ]
const toasting = (title: string, error: Error) => {
toast({
title: title,
description: error.message,
variant: "error"
})
}
const success = (title: string, description: string) => {
toast({
title: title,
description: description,
variant: "success"
})
}
// Username blacklist // Username blacklist
const usernameFilteredFormSchema = z.object({ const usernameFilteredFormSchema = z.object({
//userId: z.string().trim().min(1),
username: z.string().trim().min(4).max(25).regex(new RegExp("[a-zA-Z0-9][a-zA-Z0-9\_]{3,24}"), "Must be a valid twitch username."), username: z.string().trim().min(4).max(25).regex(new RegExp("[a-zA-Z0-9][a-zA-Z0-9\_]{3,24}"), "Must be a valid twitch username."),
tag: z.string().trim() tag: z.string().trim()
}); });
@ -40,7 +62,6 @@ const TTSFiltersPage = () => {
const usernameFilteredForm = useForm({ const usernameFilteredForm = useForm({
resolver: zodResolver(usernameFilteredFormSchema), resolver: zodResolver(usernameFilteredFormSchema),
defaultValues: { defaultValues: {
//userId: session?.user?.id ?? "",
username: "", username: "",
tag: "" tag: ""
} }
@ -52,18 +73,18 @@ const TTSFiltersPage = () => {
const userFiltersData = await axios.get("/api/settings/tts/filter/users") const userFiltersData = await axios.get("/api/settings/tts/filter/users")
setUserTag(userFiltersData.data ?? []) setUserTag(userFiltersData.data ?? [])
} catch (error) { } catch (error) {
console.log("ERROR", error) toasting("Failed to fetch all the username filters.", error as Error)
} }
try { try {
const replacementData = await axios.get("/api/settings/tts/filter/words") const replacementData = await axios.get("/api/settings/tts/filter/words")
setReplacements(replacementData.data ?? []) setReplacements(replacementData.data ?? [])
} catch (e) { } catch (error) {
console.log("ERROR", e) toasting("Failed to fetch all the word filters.", error as Error)
} }
}; };
fetchData().catch(console.error); fetchData().catch((error) => toasting("Failed to fetch all the username filters.", error as Error));
}, []); }, []);
const onDelete = () => { const onDelete = () => {
@ -71,13 +92,13 @@ const TTSFiltersPage = () => {
axios.delete("/api/settings/tts/filter/users?username=" + username) axios.delete("/api/settings/tts/filter/users?username=" + username)
.then(() => { .then(() => {
setUserTag(userTags.filter((u) => u.username != username)) setUserTag(userTags.filter((u) => u.username != username))
}).catch((e) => console.error(e)) success("Username filter deleted", `"${username.toLowerCase()}" is now back to normal.`)
}).catch((error) => toasting("Failed to delete the username filter.", error as Error))
} }
const isSubmitting = usernameFilteredForm.formState.isSubmitting; const isSubmitting = usernameFilteredForm.formState.isSubmitting;
const onAddExtended = (values: z.infer<typeof usernameFilteredFormSchema>, test: boolean = true) => { const onAddExtended = (values: z.infer<typeof usernameFilteredFormSchema>, test: boolean = true) => {
try {
const original = userTags.find(u => u.username.toLowerCase() == values.username.toLowerCase()) const original = userTags.find(u => u.username.toLowerCase() == values.username.toLowerCase())
if (test) if (test)
@ -94,10 +115,11 @@ const TTSFiltersPage = () => {
usernameFilteredForm.reset(); usernameFilteredForm.reset();
router.refresh(); router.refresh();
}) if (values.tag == "blacklisted")
} catch (error) { success("Username filter added", `"${values.username.toLowerCase()}" will be blocked.`)
console.log("[TTS/FILTERS/USER]", error); else if (values.tag == "priority")
} success("Username filter added", `"${values.username.toLowerCase()}" will be taking priority.`)
}).catch(error => toasting("Failed to add the username filter.", error as Error))
} }
const onAdd = (values: z.infer<typeof usernameFilteredFormSchema>) => { const onAdd = (values: z.infer<typeof usernameFilteredFormSchema>) => {
@ -108,27 +130,24 @@ const TTSFiltersPage = () => {
const [replacements, setReplacements] = useState<{ id: string, search: string, replace: string, userId: string }[]>([]) const [replacements, setReplacements] = useState<{ id: string, search: string, replace: string, userId: string }[]>([])
const onReplaceAdd = async () => { const onReplaceAdd = async () => {
if (search.length <= 0) {
toasting("Unable to add the word filter.", new Error("Search must not be empty."))
return
}
await axios.post("/api/settings/tts/filter/words", { search, replace }) await axios.post("/api/settings/tts/filter/words", { search, replace })
.then(d => { .then(d => {
replacements.push({ id: d.data.id, search: d.data.search, replace: d.data.replace, userId: d.data.userId }) replacements.push({ id: d.data.id, search: d.data.search, replace: d.data.replace, userId: d.data.userId })
setReplacements(replacements) setReplacements(replacements)
setSearch("") setSearch("")
}).catch(e => { success("Word filter added", `"${d.data.search}" will be replaced.`)
// TODO: handle already exist. }).catch(error => toasting("Failed to add the word filter.", error as Error))
console.log("LOGGED:", e)
return null
})
} }
const onReplaceUpdate = async (data: { id: string, search: string, replace: string, userId: string }) => { const onReplaceUpdate = async (data: { id: string, search: string, replace: string, userId: string }) => {
await axios.put("/api/settings/tts/filter/words", data) await axios.put("/api/settings/tts/filter/words", data)
.then(d => { .then(() => success("Word filter updated", ""))
//setReplacements(replacements.filter(r => r.id != id)) .catch(error => toasting("Failed to update the word filter.", error as Error))
}).catch(e => {
// TODO: handle does not exist.
console.log("LOGGED:", e)
return null
})
} }
const onReplaceDelete = async (id: string) => { const onReplaceDelete = async (id: string) => {
@ -136,29 +155,10 @@ const TTSFiltersPage = () => {
.then(d => { .then(d => {
const r = replacements.filter(r => r.id != d.data.id) const r = replacements.filter(r => r.id != d.data.id)
setReplacements(r) setReplacements(r)
console.log(r) success("Word filter deleted", `No more filter for "${d.data.search}"`)
}).catch(e => { }).catch(error => toasting("Failed to delete the word filter.", error as Error))
// TODO: handle does not exist.
console.log("LOGGED:", e)
return null
})
} }
// const replaceFormSchema = z.object({
// //userId: z.string().trim().min(1),
// search: z.string().trim().min(1),
// replace: z.string().trim().min(0),
// });
// const replaceForm = useForm({
// resolver: zodResolver(replaceFormSchema),
// defaultValues: {
// //userId: session?.user?.id ?? "",
// search: "",
// replace: ""
// }
// });
let [search, setSearch] = useState("") let [search, setSearch] = useState("")
let [replace, setReplace] = useState("") let [replace, setReplace] = useState("")
let [searchInfo, setSearchInfo] = useState("") let [searchInfo, setSearchInfo] = useState("")
@ -166,10 +166,11 @@ const TTSFiltersPage = () => {
return ( return (
<div> <div>
<div className="text-2xl text-center pt-[50px]">TTS Filters</div> <div className="text-2xl text-center pt-[50px]">TTS Filters</div>
<div className="px-10 py-5 w-full h-full flex-grow inset-y-1/2"> <div className="px-10 py-1 w-full h-full flex-grow inset-y-1/2">
<InfoNotice message="You can tag certain labels to twitch users, allowing changes applied specifically to these users when using the text to speech feature." hidden={false} />
<div> <div>
{userTags.map((user, index) => ( {userTags.map((user, index) => (
<div key={user.username + "-tags"} className="flex w-full items-start justify-between rounded-md border px-4 py-1"> <div key={user.username + "-tags"} className="flex w-full items-start justify-between rounded-md border px-4 py-2 mt-2">
<p className="text-base font-medium"> <p className="text-base font-medium">
<span className="mr-2 rounded-lg bg-primary px-2 py-1 text-xs text-primary-foreground"> <span className="mr-2 rounded-lg bg-primary px-2 py-1 text-xs text-primary-foreground">
{user.tag} {user.tag}
@ -228,7 +229,7 @@ const TTSFiltersPage = () => {
))} ))}
<Form {...usernameFilteredForm}> <Form {...usernameFilteredForm}>
<form onSubmit={usernameFilteredForm.handleSubmit(onAdd)}> <form onSubmit={usernameFilteredForm.handleSubmit(onAdd)}>
<div className="flex w-full items-center justify-between rounded-md border px-4 py-2 gap-3"> <div className="flex w-full items-center justify-between rounded-md border px-4 py-2 gap-3 mt-2">
<Label className="rounded-lg bg-primary px-2 py-1 text-xs text-primary-foreground "> <Label className="rounded-lg bg-primary px-2 py-1 text-xs text-primary-foreground ">
{tag} {tag}
</Label> </Label>
@ -336,6 +337,7 @@ const TTSFiltersPage = () => {
</div> </div>
</div> </div>
</div> </div>
<Toaster />
</div> </div>
); );
} }

View File

@ -13,6 +13,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox"; import { Checkbox } from "@/components/ui/checkbox";
import voices from "@/data/tts"; import voices from "@/data/tts";
import InfoNotice from "@/components/elements/info-notice";
const TTSVoiceFiltersPage = () => { const TTSVoiceFiltersPage = () => {
const { data: session, status } = useSession(); const { data: session, status } = useSession();
@ -94,8 +95,7 @@ const TTSVoiceFiltersPage = () => {
setValue(Number.parseInt(currentValue)) setValue(Number.parseInt(currentValue))
onDefaultChange(voice.label) onDefaultChange(voice.label)
setOpen(false) setOpen(false)
}} }}>
>
<Check <Check
className={cn( className={cn(
"mr-2 h-4 w-4", "mr-2 h-4 w-4",
@ -113,6 +113,7 @@ const TTSVoiceFiltersPage = () => {
<div className="w-full pt-[50px]"> <div className="w-full pt-[50px]">
<p className="text-xl text-center justify-center">Voices Enabled</p> <p className="text-xl text-center justify-center">Voices Enabled</p>
<InfoNotice message="Voices can be disabled from being used. Default voice will always work." hidden={false} />
<div className="grid grid-cols-4 grid-flow-row gap-4 pt-[20px]"> <div className="grid grid-cols-4 grid-flow-row gap-4 pt-[20px]">
{voices.map((v, i) => ( {voices.map((v, i) => (
<div key={v.label + "-enabled"} className="h-[30px] row-span-1 col-span-1 align-middle flex items-center justify-center"> <div key={v.label + "-enabled"} className="h-[30px] row-span-1 col-span-1 align-middle flex items-center justify-center">

View File

@ -0,0 +1,36 @@
import React, { useState } from "react";
import { FaExclamationTriangle } from "react-icons/fa";
import { Button } from "../ui/button";
import { X } from "lucide-react";
interface NoticeProps {
message: string
hidden?: boolean
}
const ErrorNotice = ({
message,
hidden = false
} : NoticeProps ) => {
const [open, setOpen] = useState(true)
return (
<div className={"flex flex-col bg-red-400 rounded-lg px-4 py-2 mx-6" + (hidden || !open ? " hidden" : "")}>
<div className="ml-[10px] items-center align-middle text-start w-full flex flex-row justify-between">
<div>
<FaExclamationTriangle className="w-3 h-3 inline-block" />
<div className="ml-2 inline-block text-md align-middle font-bold">Info</div>
</div>
<Button variant="ghost" onClick={() => setOpen(false)} className="hover:bg-red-800 rounded-lg">
<X className="align-top items-end" />
</Button>
</div>
<div>
<p className="text-sm flex flex-grow w-full">{message}</p>
</div>
</div>
);
}
export default ErrorNotice;

View File

@ -0,0 +1,35 @@
import { Info, X } from "lucide-react";
import React, { useState } from "react";
import { Button } from "../ui/button";
interface NoticeProps {
message: string
hidden?: boolean
}
const InfoNotice = ({
message,
hidden = false
} : NoticeProps ) => {
const [open, setOpen] = useState(true)
return (
<div className={"flex flex-col bg-blue-400 rounded-lg px-4 py-2 mx-6" + (hidden || !open ? " hidden" : "")}>
<div className="ml-[10px] items-center align-middle text-start w-full flex flex-row justify-between">
<div>
<Info className="w-3 h-3 inline-block" />
<div className="ml-2 inline-block text-md align-middle font-bold">Info</div>
</div>
<Button variant="ghost" onClick={() => setOpen(false)} className="hover:bg-red-800 rounded-lg">
<X className="align-top items-end" />
</Button>
</div>
<div>
<p className="text-sm flex flex-grow w-full">{message}</p>
</div>
</div>
);
}
export default InfoNotice;

View File

@ -0,0 +1,36 @@
import { X } from "lucide-react";
import React, { useState } from "react";
import { FaExclamationCircle } from "react-icons/fa";
import { Button } from "../ui/button";
interface NoticeProps {
message: string
hidden?: boolean
}
const WarningNotice = ({
message,
hidden = false
} : NoticeProps ) => {
const [open, setOpen] = useState(true)
return (
<div className={"flex flex-col bg-orange-400 rounded-lg px-4 py-2 mx-6" + (hidden || !open ? " hidden" : "")}>
<div className="ml-[10px] items-center align-middle text-start w-full flex flex-row justify-between">
<div>
<FaExclamationCircle className="w-3 h-3 inline-block" />
<div className="ml-2 inline-block text-md align-middle font-bold">Info</div>
</div>
<Button variant="ghost" onClick={() => setOpen(false)} className="hover:bg-red-800 rounded-lg">
<X className="align-top items-end" />
</Button>
</div>
<div>
<p className="text-sm flex flex-grow w-full">{message}</p>
</div>
</div>
);
}
export default WarningNotice;

31
components/ui/sonner.tsx Normal file
View File

@ -0,0 +1,31 @@
"use client"
import { useTheme } from "next-themes"
import { Toaster as Sonner } from "sonner"
type ToasterProps = React.ComponentProps<typeof Sonner>
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton:
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
)
}
export { Toaster }

View File

@ -28,8 +28,11 @@ const toastVariants = cva(
variants: { variants: {
variant: { variant: {
default: "border bg-background text-foreground", default: "border bg-background text-foreground",
destructive: destructive: "destructive group border-destructive bg-destructive text-destructive-foreground",
"destructive group border-destructive bg-destructive text-destructive-foreground", info: "bg-blue-500 opacity-90 text-white border-0",
success: "bg-green-500 opacity-90 text-white border-0",
warning: "bg-orange-500 opacity-90 text-white border-0",
error: "bg-red-500 opacity-90 text-white border-0",
}, },
}, },
defaultVariants: { defaultVariants: {

View File

@ -50,18 +50,10 @@ const fetch = async (userId: string) => {
}) })
if (copied) { if (copied) {
return { return copied
id: copied.id,
username: copied.name,
role: copied.role
}
} }
} }
} }
return { return user
id: user.id,
username: user.name,
role: user.role
}
} }

View File

@ -47,7 +47,7 @@ export default auth((req) => {
return response; return response;
}) })
// Optionally, don't invoke Middleware on some paths
export const config = { export const config = {
// Any subpath matching this causes this middleware to be invoked.
matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'], matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
} }