aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFactiven <[email protected]>2023-04-17 16:17:45 +0700
committerFactiven <[email protected]>2023-04-17 16:17:45 +0700
commit9a9e892a1f43a61188cfd08ef1faaf5100d0a41a (patch)
tree005b6b4e5b786139b266847b6548770f9de6bca3
parentUpdate [user].js (diff)
downloadmoopa-9a9e892a1f43a61188cfd08ef1faaf5100d0a41a.tar.xz
moopa-9a9e892a1f43a61188cfd08ef1faaf5100d0a41a.zip
4th fixes
-rw-r--r--components/hero/content.js4
-rw-r--r--components/videoPlayer.js50
-rw-r--r--pages/anime/[...id].js129
-rw-r--r--pages/anime/watch/[...info].js70
-rw-r--r--pages/api/get-media.js76
-rw-r--r--pages/api/get-user.js31
-rw-r--r--pages/api/update-user.js31
-rw-r--r--pages/api/watched-episode.js43
-rw-r--r--pages/index.js18
-rw-r--r--pages/testing.js92
10 files changed, 147 insertions, 397 deletions
diff --git a/components/hero/content.js b/components/hero/content.js
index 348e1ab..1a45860 100644
--- a/components/hero/content.js
+++ b/components/hero/content.js
@@ -27,7 +27,7 @@ export default function Content({ ids, section, data }) {
// console.log({ left: scrollLeft, right: scrollRight });
const array = data;
- let filteredData = array.filter((item) => item.status !== "Unknown");
+ let filteredData = array?.filter((item) => item.status !== "Unknown");
return (
<div>
<h1 className="px-5 font-karla text-[20px] font-bold">{section}</h1>
@@ -44,7 +44,7 @@ export default function Content({ ids, section, data }) {
className="scroll flex h-full w-full items-center select-none overflow-x-scroll scroll-smooth whitespace-nowrap overflow-y-hidden scrollbar-hide lg:gap-8 gap-5 p-10 z-30 "
onScroll={handleScroll}
>
- {filteredData.map((anime) => {
+ {filteredData?.map((anime) => {
return (
<div
key={anime.id}
diff --git a/components/videoPlayer.js b/components/videoPlayer.js
index c0d551d..efd354a 100644
--- a/components/videoPlayer.js
+++ b/components/videoPlayer.js
@@ -69,7 +69,8 @@ export default function VideoPlayer({
style={{ width: "100%", height: "100%", margin: "0 auto 0" }}
getInstance={(art) => {
art.on("ready", () => {
- const seekTime = seek;
+ const seek = art.storage.get(id);
+ const seekTime = seek?.time || 0;
const duration = art.duration;
const percentage = seekTime / duration;
@@ -78,7 +79,7 @@ export default function VideoPlayer({
art.currentTime = 0;
console.log("Video restarted from the beginning");
} else {
- art.currentTime = seek;
+ art.currentTime = seek.time;
}
});
@@ -101,50 +102,7 @@ export default function VideoPlayer({
});
art.on("destroy", async () => {
- if (!session) return;
- const lastPlayed = {
- id: id,
- time: art.currentTime,
- };
- const res = await fetch("/api/watched-episode", {
- method: "POST",
- body: JSON.stringify({
- username: session?.user.name,
- id: aniId,
- newData: lastPlayed,
- }),
- headers: {
- "Content-Type": "application/json",
- },
- });
-
- // console.log(res.status);
-
- const title = titles;
- const prevDataStr = localStorage.getItem("lastPlayed") || "[]";
- const prevData = JSON.parse(prevDataStr);
- let titleExists = false;
-
- prevData.forEach((item) => {
- if (item.title === title) {
- const foundIndex = item.data.findIndex((e) => e.id === id);
- if (foundIndex !== -1) {
- item.data[foundIndex] = lastPlayed;
- } else {
- item.data.push(lastPlayed);
- }
- titleExists = true;
- }
- });
-
- if (!titleExists) {
- prevData.push({
- title: title,
- data: [lastPlayed],
- });
- }
-
- localStorage.setItem("lastPlayed", JSON.stringify(prevData));
+ art.storage.set(id, { time: art.currentTime });
});
}}
/>
diff --git a/pages/anime/[...id].js b/pages/anime/[...id].js
index 1df8ea4..8fba4fb 100644
--- a/pages/anime/[...id].js
+++ b/pages/anime/[...id].js
@@ -73,25 +73,6 @@ export default function Himitsu({
episodeIndo = episode;
}
- async function handleUpdate(data) {
- if (!sessions) return;
- const res = await fetch("/api/update-user", {
- method: "POST",
- body: JSON.stringify({
- name: sessions?.user.name,
- newData: {
- recentWatch: data,
- },
- }),
- headers: {
- "Content-Type": "application/json",
- },
- });
- console.log(res.status);
- }
-
- // console.log(lastPlayed);
-
return (
<>
<Head>
@@ -158,24 +139,7 @@ export default function Himitsu({
</div>
<div className="flex">
{epi1 && epi1[0] ? (
- <Link
- href={`/anime/watch/${epi1[0].id}/${info.id}`}
- onClick={() =>
- handleUpdate({
- title: {
- romaji:
- info.title.romaji ||
- info.title.english ||
- info.title.native,
- },
- description: info.description,
- coverImage: {
- extraLarge: info.image,
- },
- id: parseInt(info.id),
- })
- }
- >
+ <Link href={`/anime/watch/${epi1[0].id}/${info.id}`}>
<h1 className="flex cursor-pointer items-center gap-2 rounded-[20px] bg-[#ff9537] px-4 py-2 font-bold text-[#ffffff]">
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -415,21 +379,6 @@ export default function Himitsu({
return (
<div key={index} className="flex flex-col gap-3 px-2">
<Link
- onClick={() =>
- handleUpdate({
- title: {
- romaji:
- info.title.romaji ||
- info.title.english ||
- info.title.native,
- },
- description: info.description,
- coverImage: {
- extraLarge: info.image,
- },
- id: parseInt(info.id),
- })
- }
href={`/anime/watch/${episode.id}/${info.id}/${
item ? `${item.time}` : ""
}`}
@@ -615,18 +564,80 @@ export async function getServerSideProps(context) {
let lastPlayed = null;
if (session) {
- const res = await fetch(
- `https://moopa-anilist.vercel.app/api/get-media?username=${query.user}`
- );
+ const response = await fetch("https://graphql.anilist.co/", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ query: `
+ query ($username: String, $status: MediaListStatus) {
+ MediaListCollection(userName: $username, type: ANIME, status: $status, sort: SCORE_DESC) {
+ user {
+ id
+ name
+ about (asHtml: true)
+ createdAt
+ avatar {
+ large
+ }
+ statistics {
+ anime {
+ count
+ episodesWatched
+ meanScore
+ minutesWatched
+ }
+ }
+ bannerImage
+ mediaListOptions {
+ animeList {
+ sectionOrder
+ }
+ }
+ }
+ lists {
+ status
+ name
+ entries {
+ id
+ mediaId
+ status
+ progress
+ score
+ media {
+ id
+ status
+ title {
+ english
+ romaji
+ }
+ episodes
+ coverImage {
+ large
+ }
+ }
+ }
+ }
+ }
+ }
+ `,
+ variables: {
+ username: session?.user.name,
+ },
+ }),
+ });
+
+ const dat = await response.json();
- const resp = await fetch(`/api/get-user?userName=${session?.user.name}`);
- const data = await resp.json();
+ // const resp = await fetch(`/api/get-user?userName=${session?.user.name}`);
+ // const data = await resp.json();
- lastPlayed = data?.recentWatch.filter(
+ lastPlayed = session?.user?.recentWatch?.filter(
(item) => item.title.romaji === info.title.romaji
)[0]?.episode;
- const prog = await res.json();
+ const prog = dat.data.MediaListCollection;
const gat = prog.lists.map((item) => item.entries);
const git = gat.map((item) =>
diff --git a/pages/anime/watch/[...info].js b/pages/anime/watch/[...info].js
index e7195d6..ba3a078 100644
--- a/pages/anime/watch/[...info].js
+++ b/pages/anime/watch/[...info].js
@@ -423,11 +423,73 @@ export async function getServerSideProps(context) {
.filter((item) => item.id == id)
.map((item) => item.number);
- const resp = await fetch(
- `https://moopa-anilist.vercel.app/api/get-media?username=${query.user}`
- );
+ const response = await fetch("https://graphql.anilist.co/", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ query: `
+ query ($username: String, $status: MediaListStatus) {
+ MediaListCollection(userName: $username, type: ANIME, status: $status, sort: SCORE_DESC) {
+ user {
+ id
+ name
+ about (asHtml: true)
+ createdAt
+ avatar {
+ large
+ }
+ statistics {
+ anime {
+ count
+ episodesWatched
+ meanScore
+ minutesWatched
+ }
+ }
+ bannerImage
+ mediaListOptions {
+ animeList {
+ sectionOrder
+ }
+ }
+ }
+ lists {
+ status
+ name
+ entries {
+ id
+ mediaId
+ status
+ progress
+ score
+ media {
+ id
+ status
+ title {
+ english
+ romaji
+ }
+ episodes
+ coverImage {
+ large
+ }
+ }
+ }
+ }
+ }
+ }
+ `,
+ variables: {
+ username: session?.user.name,
+ },
+ }),
+ });
+
+ const dat = await response.json();
- const prog = await resp.json();
+ const prog = dat.data.MediaListCollection;
const gat = prog?.lists.map((item) => item.entries);
const git = gat?.map((item) =>
diff --git a/pages/api/get-media.js b/pages/api/get-media.js
deleted file mode 100644
index 8558f63..0000000
--- a/pages/api/get-media.js
+++ /dev/null
@@ -1,76 +0,0 @@
-export default async function handler(req, res) {
- const { username, status } = req.query;
-
- try {
- const response = await fetch("https://graphql.anilist.co/", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- query: `
- query ($username: String, $status: MediaListStatus) {
- MediaListCollection(userName: $username, type: ANIME, status: $status, sort: SCORE_DESC) {
- user {
- id
- name
- about (asHtml: true)
- createdAt
- avatar {
- large
- }
- statistics {
- anime {
- count
- episodesWatched
- meanScore
- minutesWatched
- }
- }
- bannerImage
- mediaListOptions {
- animeList {
- sectionOrder
- }
- }
- }
- lists {
- status
- name
- entries {
- id
- mediaId
- status
- progress
- score
- media {
- id
- status
- title {
- english
- romaji
- }
- episodes
- coverImage {
- large
- }
- }
- }
- }
- }
- }
- `,
- variables: {
- username,
- status,
- },
- }),
- });
-
- const data = await response.json();
- res.status(200).json(data.data.MediaListCollection);
- } catch (error) {
- console.error(error);
- res.status(500).json({ message: "Internal server error" });
- }
-}
diff --git a/pages/api/get-user.js b/pages/api/get-user.js
deleted file mode 100644
index 94ec845..0000000
--- a/pages/api/get-user.js
+++ /dev/null
@@ -1,31 +0,0 @@
-import clientPromise from "../../lib/mongodb";
-
-export async function getUser(userId) {
- const client = await clientPromise;
- const db = client.db("authbase");
-
- const collection = db.collection("users");
- const user = await collection.findOne({ id: userId });
-
- if (user && user._id) {
- user._id = String(user._id);
- }
-
- return user;
-}
-
-export default async function handler(req, res) {
- const { userId } = req.query;
-
- if (!userId) {
- return res.status(400).json({ message: "User ID is required" });
- }
-
- const user = await getUser(userId);
-
- if (!user) {
- return res.status(404).json({ message: "User not found" });
- }
-
- res.status(200).json(user);
-}
diff --git a/pages/api/update-user.js b/pages/api/update-user.js
deleted file mode 100644
index 67c80d0..0000000
--- a/pages/api/update-user.js
+++ /dev/null
@@ -1,31 +0,0 @@
-// pages/api/update-user.js
-import clientPromise from "../../lib/mongodb";
-
-export default async function handler(req, res) {
- const client = await clientPromise;
- const db = client.db("authbase");
- const collection = db.collection("users");
-
- const { name, newData } = req.body; // id is the user ID and newData is the new data you want to set
-
- try {
- const existingData = await collection.findOne({
- name: name,
- "recentWatch.id": newData.recentWatch.id,
- });
-
- if (existingData) {
- res.status(200).json({ message: "Data already exists" });
- return;
- }
-
- const result = await collection.updateOne(
- { name: name },
- { $addToSet: newData }
- );
-
- res.status(200).json(result);
- } catch (error) {
- res.status(500).json({ error: "Unable to update user data" });
- }
-}
diff --git a/pages/api/watched-episode.js b/pages/api/watched-episode.js
deleted file mode 100644
index 271348d..0000000
--- a/pages/api/watched-episode.js
+++ /dev/null
@@ -1,43 +0,0 @@
-// pages/api/update-user.js
-import clientPromise from "../../lib/mongodb";
-
-export default async function handler(req, res) {
- const client = await clientPromise;
- const db = client.db("authbase");
- const collection = db.collection("users");
-
- const { username, id, newData } = req.body; // id is the user ID and newData is the new data you want to set
-
- try {
- const result = await collection.updateOne(
- {
- name: username,
- "recentWatch.id": id,
- "recentWatch.episode.id": { $ne: newData.id },
- },
- { $addToSet: { "recentWatch.$.episode": newData } }
- );
-
- if (result.modifiedCount === 0) {
- const updateResult = await collection.updateOne(
- {
- name: username,
- "recentWatch.id": id,
- "recentWatch.episode.id": newData.id,
- "recentWatch.episode.time": { $ne: newData.time },
- },
- { $set: { "recentWatch.$.episode.$[elem].time": newData.time } },
- { arrayFilters: [{ "elem.id": newData.id }] }
- );
- if (updateResult.modifiedCount === 0) {
- console.log("The episode already exists with the same time.");
- }
- }
-
- console.log("Successfully updated the recentWatch collection.");
-
- res.status(200).json(result);
- } catch (error) {
- res.status(500).json({ error: "Unable to update user data", dat: newData });
- }
-}
diff --git a/pages/index.js b/pages/index.js
index 79e99ed..5fe7e37 100644
--- a/pages/index.js
+++ b/pages/index.js
@@ -102,9 +102,7 @@ export default function Home({ detail, populars, sessions }) {
const [isVisible, setIsVisible] = useState(false);
const [plan, setPlan] = useState(null);
- const [user, setUser] = useState(null);
- const [array, setArray] = useState([]);
- const [fade, setFade] = useState(false);
+ // const [array, setArray] = useState(null);
const popular = populars?.data;
const data = detail.data[0];
@@ -112,20 +110,15 @@ export default function Home({ detail, populars, sessions }) {
const handleShowClick = () => {
setIsVisible(true);
- setFade(true);
};
const handleHideClick = () => {
setIsVisible(false);
- setFade(false);
};
useEffect(() => {
async function userData() {
if (!sessions) return;
- const res = await fetch(`/api/get-user?id=${sessions?.user.id}`);
- const data = await res.json();
-
const getMedia =
media.filter((item) => item.status === "CURRENT")[0] || null;
const plan = getMedia?.entries
@@ -141,6 +134,8 @@ export default function Home({ detail, populars, sessions }) {
}
});
+ // setArray(sessions.user?.recentWatch?.reverse());
+
const getlog = newArray
.map(({ media }) => media)
.filter((media) => media);
@@ -148,9 +143,6 @@ export default function Home({ detail, populars, sessions }) {
if (plan) {
setPlan(plan.reverse());
}
-
- setArray(data?.recentWatch?.reverse());
- setUser(data);
}
userData();
}, [sessions, media]);
@@ -427,7 +419,7 @@ export default function Home({ detail, populars, sessions }) {
transition={{ duration: 0.5, staggerChildren: 0.2 }} // Add staggerChildren prop
>
{/* SECTION 1 */}
- {sessions && user?.recentWatch && (
+ {/* {sessions && sessions?.user?.recentWatch && (
<motion.div // Add motion.div to each child component
key="recentlyWatched"
initial={{ y: 20, opacity: 0 }}
@@ -441,7 +433,7 @@ export default function Home({ detail, populars, sessions }) {
data={array}
/>
</motion.div>
- )}
+ )} */}
{sessions && plan && (
<motion.div // Add motion.div to each child component
diff --git a/pages/testing.js b/pages/testing.js
deleted file mode 100644
index 63d5e96..0000000
--- a/pages/testing.js
+++ /dev/null
@@ -1,92 +0,0 @@
-import { signIn, signOut, useSession } from "next-auth/react";
-import { getServerSession } from "next-auth/next";
-import { authOptions } from "./api/auth/[...nextauth]";
-const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000";
-
-export default function Testing({ sesi, data, progress, statusWatch }) {
- const { data: session, status } = useSession();
- // console.log(session.user.id);
- async function handleUpdate() {
- // const data = ;
- const res = await fetch("/api/update-user", {
- method: "POST",
- body: JSON.stringify({
- name: session?.user.name,
- newData: {
- recentWatch: {
- id: parseInt(9280220),
- title: {
- romaji: "something title here",
- },
- description:
- "lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quod.",
- coverImage: {
- extraLarge: "this should be an image url",
- },
- episode: {
- id: "first-id-yeah",
- time: 12344,
- },
- },
- },
- }),
- headers: {
- "Content-Type": "application/json",
- },
- });
- // const data = await res.json(); // parse the response body as JSON
- // console.log(data.dat.id);
- console.log(res.status);
- }
-
- console.log(statusWatch);
- return (
- <div>
- <button onClick={() => handleUpdate()}>Click for update</button>
- {!session && (
- <button onClick={() => signIn("AniListProvider")}>LOGIN</button>
- )}
- {session && <button onClick={() => signOut()}>LOGOUT</button>}
- </div>
- );
-}
-
-export async function getServerSideProps(context) {
- const session = await getServerSession(context.req, context.res, authOptions);
-
- const res = await fetch(`${baseUrl}/api/get-media`, {
- method: "POST",
- body: JSON.stringify({
- username: session?.user.name,
- }),
- headers: {
- "Content-Type": "application/json",
- },
- });
-
- const prog = await res.json();
-
- const gat = prog.lists.map((item) => item.entries);
- const git = gat.map((item) => item.find((item) => item.media.id === 130003));
- const gut = git.find((item) => item?.media.id === 130003);
-
- let progress = null;
- let statusWatch = "CURRENT";
-
- if (gut?.status === "COMPLETED") {
- statusWatch = "REPEATING";
- }
-
- if (gut) {
- progress = gut?.progress;
- }
-
- return {
- props: {
- sesi: session,
- data: gut || null,
- progress: progress,
- statusWatch: statusWatch,
- },
- };
-}