Skip to content

Commit

Permalink
check in YouTube api validation(#8)
Browse files Browse the repository at this point in the history
* begin work on validating videos utilizing yt api.

* check in youtube form validation.
  • Loading branch information
tydolla00 authored Nov 10, 2024
1 parent 68af353 commit 50f90a0
Show file tree
Hide file tree
Showing 4 changed files with 134 additions and 7 deletions.
6 changes: 5 additions & 1 deletion next.config.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};
const nextConfig = {
images: {
remotePatterns: [{ protocol: "https", hostname: "i.ytimg.com" }],
},
};

export default nextConfig;
42 changes: 36 additions & 6 deletions src/app/(routes)/submission/_components/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { submitUpdates } from "@/app/_actions/action";
import { getYTVid, submitUpdates } from "@/app/_actions/action";
import { Input } from "@/components/ui/input";
import {
Select,
Expand All @@ -35,6 +35,8 @@ import {
} from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { toast } from "sonner";
import { useState } from "react";
import Image from "next/image";

const formSchema = z.object({
video: z
Expand All @@ -43,7 +45,9 @@ const formSchema = z.object({
.startsWith(
"https://www.youtube.com",
"Please paste in a valid youtube url.",
),
)
.max(100)
.includes("v="),
stat: z
.object({
member: z
Expand All @@ -60,6 +64,9 @@ const formSchema = z.object({
});

export const SubmissionForm = () => {
const [session, setSession] = useState<
Awaited<ReturnType<typeof getYTVid>> | undefined
>(undefined);
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: { video: "", stat: [{ member: [{ name: "" }] }] },
Expand All @@ -76,9 +83,24 @@ export const SubmissionForm = () => {
console.log("Got here");
submitUpdates(data);
};
const nextButtonClicked = () => {
if (!isTouched) toast("Please submit a valid url.");
if (isTouched && !invalid) toast("Changes saved");
const saveBtnClicked = async () => {
if (!isTouched || invalid) {
toast("Please submit a valid url.");
return;
}

let id = form.getValues().video.split("=")[1];
const trimEnd = id.indexOf("&");

if (trimEnd !== -1) id = id.slice(0, trimEnd);
const video = await getYTVid(id);
if (!video) {
form.reset(undefined, { keepIsValid: true });
toast("Please upload a video by RDC Live");
} else {
if (isTouched && !invalid) toast("Changes saved");
setSession(video);
}
};
return (
<Form {...form}>
Expand All @@ -101,6 +123,14 @@ export const SubmissionForm = () => {
</CardDescription>
<Separator />
<CardContent>
{session && (
<Image
alt="Youtube Video"
src={session.thumbnail.url}
height={session.thumbnail.height}
width={session.thumbnail.width}
/>
)}
<FormField
control={form.control}
name="video"
Expand All @@ -124,7 +154,7 @@ export const SubmissionForm = () => {
<Separator />
</CardContent>
<CardFooter>
<Button onClick={nextButtonClicked} type="button">
<Button onClick={saveBtnClicked} type="button">
Save
</Button>
</CardFooter>
Expand Down
89 changes: 89 additions & 0 deletions src/app/_actions/action.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,93 @@
"use server";

import { PrismaClient } from "@prisma/client";
import config from "@/lib/config";

export const submitUpdates = async (props: any) => {
console.log(props);
};

export const getYTVid = async (videoId: string) => {
const prisma = new PrismaClient();
const sessions = await prisma.session.findMany();
const sessionURL = sessions.find(
(session) => session.sessionUrl.split("=")[1] === videoId,
);
console.log(sessionURL);
if (!sessionURL) {
const YTvideo = await fetch(
`https://youtube.googleapis.com/youtube/v3/videos?part=snippet&part=player&id=${videoId}&key=${config.YOUTUBE_LOCAL_API_KEY}`,
);
console.log(
`https://youtube.googleapis.com/youtube/v3/videos?part=snippet&part=player&id=${videoId}&key=${config.YOUTUBE_LOCAL_API_KEY}`,
);
console.log(YTvideo, videoId);
!config.YOUTUBE_LOCAL_API_KEY &&
console.log("YOUTUBE API KEY NOT CONFIGURED");

if (!YTvideo.ok) return undefined;

const json = (await YTvideo.json()) as YouTubeVideoListResponse;
console.log(json);
const video = json.items[0];

if (video.snippet.channelTitle !== "RDC Live") return undefined;

const session = {
sessionUrl: `https://youtube.com/watch?v=${video.id}`,
date: video.snippet.publishedAt,
sessionName: video.snippet.title,
thumbnail:
video.snippet.thumbnails.maxres || video.snippet.thumbnails.high,
};
return session;
}
await prisma.$disconnect();

return undefined;
};

type YouTubeVideoListResponse = {
kind: "youtube#videoListResponse";
etag: string;
items: {
kind: "youtube#video";
etag: string;
id: string;
snippet: {
publishedAt: string;
channelId: string;
title: string;
description: string;
thumbnails: {
default: Thumbnail;
medium: Thumbnail;
high: Thumbnail;
standard?: Thumbnail;
maxres?: Thumbnail;
};
channelTitle: string;
tags?: string[];
categoryId: string;
liveBroadcastContent: string;
localized: {
title: string;
description: string;
};
defaultAudioLanguage?: string;
};
player: {
embedHtml: string;
};
}[];
pageInfo: {
totalResults: number;
resultsPerPage: number;
};
};

type Thumbnail = {
url: string;
width: number;
height: number;
};
4 changes: 4 additions & 0 deletions src/lib/config.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
interface Config {
YOUTUBE_API_KEY: string | undefined;
YOUTUBE_LOCAL_API_KEY: string | undefined;
NEXT_PUBLIC_POSTHOG_KEY: string | undefined;
NEXT_PUBLIC_POSTHOG_HOST: string | undefined;
}

const getConfig = (): Config => {
return {
YOUTUBE_API_KEY: process.env.YOUTUBE_API_KEY,
YOUTUBE_LOCAL_API_KEY: process.env.YOUTUBE_LOCAL_API_KEY,
NEXT_PUBLIC_POSTHOG_KEY: process.env.NEXT_PUBLIC_POSTHOG_KEY,
NEXT_PUBLIC_POSTHOG_HOST: process.env.NEXT_PUBLIC_POSTHOG_HOST,
};
Expand Down

0 comments on commit 50f90a0

Please sign in to comment.