diff --git a/api/Http.ts b/api/Http.ts index 21dff40..852b033 100644 --- a/api/Http.ts +++ b/api/Http.ts @@ -1,28 +1,83 @@ +type Search = Record; + class Http { - private base = 'https://api.themoviedb.org/3'; + private readonly base = 'https://api.themoviedb.org/3'; + + private async request({ + method, + url, + base = this.base, + search, + body, + preventCache = true + }: { + method: 'GET' | 'POST'; + url: string; + base?: string; + search?: Search; + body?: B; + preventCache?: boolean; + }): Promise { + const serializedParams = new URLSearchParams( + Object.entries(search ?? {}).reduce((params, [key, value]) => { + if (value != null && value !== '') { + params.set(key, String(value)); + } + return params; + }, new URLSearchParams()) + ); + + try { + const response = await fetch(`${base}${url}?${serializedParams}`, { + method, + headers: { + Authorization: `Bearer ${process.env.MOVIE_DB_TOKEN}`, + 'Content-Type': 'application/json' + }, + body: body ? JSON.stringify(body) : undefined, + next: preventCache ? undefined : { revalidate: 3600 } + }); + + if (!response.ok) { + return Promise.reject({ + status: response.status, + statusText: response.statusText + }); + } + + return response.json(); + } catch (error) { + return Promise.reject({ message: 'Network or parsing error', error }); + } + } get( url: string, - { params, force }: { params?: Record; force?: boolean } = {}, + { params, preventCache }: { params?: Search; preventCache?: boolean } = {}, base?: string ): Promise { - const serializedParams = Object.entries(params || {}).reduce((params, [key, value]) => { - if (!['', undefined, null].includes(value as string)) { - params.set(key, value as string); - } + return this.request({ + url, + method: 'GET', + search: params, + preventCache, + base + }); + } - return params; - }, new URLSearchParams()); - - return fetch(`${base || this.base}${url}?${serializedParams}`, { - headers: { - Authorization: `Bearer ${process.env.MOVIE_DB_TOKEN}` - }, - next: force ? undefined : { revalidate: 3600 } - }).then((response) => { - if (!response.ok) return Promise.reject(response); - - return response.json(); + post( + url: string, + { params, preventCache }: { params?: Search; preventCache?: boolean } = {}, + body?: B, + base?: string + ): Promise { + return this.request({ + url, + method: 'POST', + search: params, + body, + base, + preventCache }); } } diff --git a/api/index.ts b/api/index.ts index 422589e..2f54618 100644 --- a/api/index.ts +++ b/api/index.ts @@ -7,11 +7,42 @@ import pirateBay from './parsers/pirate-bay'; import yts from './parsers/yts'; import http from './Http'; import { Sort } from './parsers'; +import { cookies } from 'next/headers'; export const createRequestToken = async () => { + return http.get('/authentication/token/new', { preventCache: true }).then(({ request_token }) => ({ + redirectUrl: `https://www.themoviedb.org/authenticate/${request_token}`, + requestToken: request_token + })); +}; + +export const createSession = async ({ requestToken }: { requestToken: string }) => { + return http.post('/authentication/session/new', { + params: { request_token: requestToken }, + preventCache: true + }); +}; + +export const account = async () => { + return http.get('/account/null', { + params: { session_id: cookies().get('session')?.value }, + preventCache: true + }); +}; + +export const usersShows = async ({ + showType, + listType +}: { + showType: Show['type']; + listType: 'favorites' | 'watchlist'; +}): Promise> => { return http - .get('/authentication/token/new', { force: true }) - .then(({ request_token }) => request_token); + .get>(`/account/null/${listType}/${showType === 'tv' ? 'tv' : 'movies'}`, { + params: { session_id: cookies().get('session')?.value }, + preventCache: true + }) + .then((response) => mapMoviesSeriesResponseToShows(response, showType)); }; export const search = async ({ diff --git a/app/api/approved/route.ts b/app/api/approved/route.ts deleted file mode 100644 index b09295e..0000000 --- a/app/api/approved/route.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { NextRequest, NextResponse } from 'next/server'; - -import broadcaster from '@/lib/broadcaster'; - -export async function GET({ nextUrl }: NextRequest) { - const requestToken = nextUrl.searchParams.get('request_token'); - - broadcaster.emit('approve', requestToken); - - return NextResponse.json({ requestToken }); -} diff --git a/app/api/auth/route.ts b/app/api/auth/route.ts deleted file mode 100644 index 0882187..0000000 --- a/app/api/auth/route.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { NextRequest } from 'next/server'; - -import broadcaster from '@/lib/broadcaster'; - -export async function GET(req: NextRequest) { - const headers = new Headers(); - - headers.set('Content-Type', 'text/event-stream'); - headers.set('Cache-Control', 'no-cache'); - headers.set('Connection', 'keep-alive'); - - const stream = new ReadableStream({ - start(controller) { - const emit = (token: string) => { - controller.enqueue(new TextEncoder().encode(`data: ${token}\n\n`)); - }; - - broadcaster.on('approve', emit); - - req.signal.addEventListener('abort', () => { - broadcaster.off('approve', emit); - controller.close(); - }); - } - }); - - return new Response(stream, { - headers - }); -} diff --git a/app/layout.tsx b/app/layout.tsx index 3ee78fe..9b8fef9 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -22,7 +22,7 @@ export const viewport: Viewport = { userScalable: false }; -const font = Poppins({ subsets: ['latin'], weight: '400' }); +const font = Poppins({ subsets: ['latin'], weight: ['400', '500', '600'] }); const RootLayout = ({ children }: { children: ReactNode }) => { const theme = cookies().get('theme')?.value as Theme; diff --git a/components/Header/components/User/index.tsx b/components/Header/components/User/index.tsx index 75d496d..712dab7 100644 --- a/components/Header/components/User/index.tsx +++ b/components/Header/components/User/index.tsx @@ -1,6 +1,6 @@ 'use client'; -import { UserRound } from 'lucide-react'; +import { LogIn,LogOut, User as UserIcon, UserRound } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { @@ -8,15 +8,19 @@ import { DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, - DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; +import useAccount from '@/hooks/useAccount'; import useAuth from './useAuth'; +import useLogOut from './useLogOut'; const User = () => { + const account = useAccount(); + const auth = useAuth(); + const logOut = useLogOut(); return ( @@ -27,12 +31,29 @@ const User = () => { - auth.mutate()}> - Log in - + {account ? ( + <> + + + {account.username} + + + + + Log out + + + ) : ( + auth.mutate()} + > + + Log in + + )} - {/* My Account - */} ); diff --git a/components/Header/components/User/useAuth.ts b/components/Header/components/User/useAuth.ts index 8ea69a4..1430eb9 100644 --- a/components/Header/components/User/useAuth.ts +++ b/components/Header/components/User/useAuth.ts @@ -1,35 +1,38 @@ -import { useEffect, useRef } from 'react'; +import { useRef } from 'react'; import { useMutation } from '@tanstack/react-query'; -import { createRequestToken } from '@/api'; +import { createRequestToken, createSession } from '@/api'; +import { useSetSession } from '@/hooks/useSession'; const useAuth = () => { + const setSession = useSetSession(); const tabRef = useRef(null); - useEffect(() => { - const approveSource = new EventSource('/api/auth'); - - approveSource.onmessage = (event) => { - console.log(event.data); + const session = useMutation({ + retry: 5, + mutationFn: createSession, + onSuccess({ session_id }) { + setSession(session_id); tabRef.current?.close(); - approveSource.close(); - }; - - return () => { - approveSource.close(); - }; - }, []); - - return useMutation({ - mutationFn: createRequestToken, - onSuccess(requestToken) { - const link = `https://www.themoviedb.org/authenticate/${requestToken}?redirect_to=${encodeURIComponent( - `${location.origin}/api/approved` - )}`; - - tabRef.current = window.open(link, '_blank'); } }); + + const requestToken = useMutation({ + mutationFn: createRequestToken, + onMutate() { + tabRef.current = window.open('', '_blank'); + tabRef.current?.focus(); + }, + onSuccess({ redirectUrl, requestToken }) { + if (!tabRef.current) return; + + tabRef.current.location = redirectUrl; + + session.mutate({ requestToken }); + } + }); + + return requestToken; }; export default useAuth; diff --git a/components/Header/components/User/useLogOut.ts b/components/Header/components/User/useLogOut.ts new file mode 100644 index 0000000..1c966f5 --- /dev/null +++ b/components/Header/components/User/useLogOut.ts @@ -0,0 +1,11 @@ +import { useCallback } from 'react'; + +import { useSetSession } from '@/hooks/useSession'; + +const useLogOut = () => { + const setSession = useSetSession(); + + return useCallback(() => setSession(null), [setSession]); +}; + +export default useLogOut; diff --git a/hooks/useAccount.ts b/hooks/useAccount.ts new file mode 100644 index 0000000..0a4e5f8 --- /dev/null +++ b/hooks/useAccount.ts @@ -0,0 +1,27 @@ +import { account } from '@/api'; +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { useSession } from './useSession'; + +const KEY = ['account']; + +const useAccount = () => { + const queryClient = useQueryClient(); + const session = useSession(); + + const query = useQuery({ + enabled: Boolean(session), + staleTime: Infinity, + notifyOnChangeProps: ['data'], + queryKey: KEY, + queryFn: () => account() + }); + + if (session === null) { + queryClient.removeQueries({ queryKey: KEY }); + queryClient.resetQueries({ queryKey: KEY }); + } + + return session ? query.data : undefined; +}; + +export default useAccount; diff --git a/hooks/useFavorites.ts b/hooks/useFavorites.ts new file mode 100644 index 0000000..13250e7 --- /dev/null +++ b/hooks/useFavorites.ts @@ -0,0 +1,21 @@ +import { usersShows } from '@/api'; +import useInfiniteList from './useInfiniteList'; +import { useSession } from './useSession'; + +const useFavorites = ({ + showType, + listType = 'favorites' +}: { + showType: Show['type']; + listType: 'favorites' | 'watchlist'; +}) => { + const session = useSession(); + + return useInfiniteList({ + queryKey: [`users-${listType}`, showType], + queryFn: () => usersShows({ showType, listType }), + enabled: Boolean(session) + }); +}; + +export default useFavorites; diff --git a/hooks/useSession.ts b/hooks/useSession.ts new file mode 100644 index 0000000..8ee37c8 --- /dev/null +++ b/hooks/useSession.ts @@ -0,0 +1,19 @@ +import { atom, useAtomValue, useSetAtom } from 'jotai'; +import Cookies from 'js-cookie'; +import { useCallback } from 'react'; + +const sessionAtom = atom(Cookies.get('session') as string); + +export const useSession = () => useAtomValue(sessionAtom); + +export const useSetSession = () => { + const setSession = useSetAtom(sessionAtom); + + return useCallback( + (session: string | null) => { + typeof session === 'string' ? Cookies.set('session', session) : Cookies.remove('session'); + setSession(session); + }, + [setSession] + ); +}; diff --git a/lib/broadcaster.ts b/lib/broadcaster.ts deleted file mode 100644 index cf0b5c3..0000000 --- a/lib/broadcaster.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { EventEmitter } from 'events'; - -class RequestTokenBroadcaster extends EventEmitter {} -const requestTokenBroadcaster = new RequestTokenBroadcaster(); - -export default requestTokenBroadcaster; diff --git a/lib/queryClient.ts b/lib/queryClient.ts index fe1e966..62eed7b 100644 --- a/lib/queryClient.ts +++ b/lib/queryClient.ts @@ -1,17 +1,29 @@ -import { cache } from 'react'; -import { QueryClient, QueryClientConfig } from '@tanstack/react-query'; +import { defaultShouldDehydrateQuery, isServer, QueryClient } from '@tanstack/react-query'; -export const queryClientOptions: QueryClientConfig = { - defaultOptions: { - queries: { - refetchOnWindowFocus: false, - staleTime: Infinity, - refetchOnReconnect: false, - refetchOnMount: false +const makeQueryClient = () => { + return new QueryClient({ + defaultOptions: { + queries: { + refetchOnWindowFocus: false, + staleTime: Infinity, + refetchOnReconnect: false, + refetchOnMount: false + }, + dehydrate: { + shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending' + } } - } + }); }; -const getQueryClient = cache(() => new QueryClient(queryClientOptions)); +let browserQueryClient: QueryClient | undefined = undefined; + +const getQueryClient = () => { + if (isServer) return makeQueryClient(); + + if (!browserQueryClient) browserQueryClient = makeQueryClient(); + + return browserQueryClient; +}; export default getQueryClient; diff --git a/package-lock.json b/package-lock.json index 8e08fba..17ddc2a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -16,7 +16,7 @@ "@radix-ui/react-tabs": "^1.0.4", "@radix-ui/react-toast": "^1.2.2", "@radix-ui/react-toggle": "^1.0.3", - "@tanstack/react-query": "^5.17.3", + "@tanstack/react-query": "^5.59.15", "@vidstack/react": "^1.12.11", "axios": "^1.4.0", "class-variance-authority": "^0.7.0", @@ -2539,27 +2539,29 @@ } }, "node_modules/@tanstack/query-core": { - "version": "5.28.4", - "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.28.4.tgz", - "integrity": "sha512-uQZqOFqLWUvXNIQZ63XdKzg22NtHzgCBUfDmjDHi3BoF+nUYeBNvMi/xFPtFrMhqRzG2Ir4mYaGsWZzmiEjXpA==", + "version": "5.59.13", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.59.13.tgz", + "integrity": "sha512-Oou0bBu/P8+oYjXsJQ11j+gcpLAMpqW42UlokQYEz4dE7+hOtVO9rVuolJKgEccqzvyFzqX4/zZWY+R/v1wVsQ==", + "license": "MIT", "funding": { "type": "github", "url": "https://github.com/sponsors/tannerlinsley" } }, "node_modules/@tanstack/react-query": { - "version": "5.28.4", - "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.28.4.tgz", - "integrity": "sha512-BErcoB/QQG6YwLSUKnaGxF+lSc270RH2w3kMBpG0i4YzDCsFs2pdxPX1WVknQvFk9bNgukMb158hc2Zb4SdwSA==", + "version": "5.59.15", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.59.15.tgz", + "integrity": "sha512-QbVlAkTI78wB4Mqgf2RDmgC0AOiJqer2c5k9STOOSXGv1S6ZkY37r/6UpE8DbQ2Du0ohsdoXgFNEyv+4eDoPEw==", + "license": "MIT", "dependencies": { - "@tanstack/query-core": "5.28.4" + "@tanstack/query-core": "5.59.13" }, "funding": { "type": "github", "url": "https://github.com/sponsors/tannerlinsley" }, "peerDependencies": { - "react": "^18.0.0" + "react": "^18 || ^19" } }, "node_modules/@types/js-cookie": { @@ -8946,16 +8948,16 @@ } }, "@tanstack/query-core": { - "version": "5.28.4", - "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.28.4.tgz", - "integrity": "sha512-uQZqOFqLWUvXNIQZ63XdKzg22NtHzgCBUfDmjDHi3BoF+nUYeBNvMi/xFPtFrMhqRzG2Ir4mYaGsWZzmiEjXpA==" + "version": "5.59.13", + "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.59.13.tgz", + "integrity": "sha512-Oou0bBu/P8+oYjXsJQ11j+gcpLAMpqW42UlokQYEz4dE7+hOtVO9rVuolJKgEccqzvyFzqX4/zZWY+R/v1wVsQ==" }, "@tanstack/react-query": { - "version": "5.28.4", - "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.28.4.tgz", - "integrity": "sha512-BErcoB/QQG6YwLSUKnaGxF+lSc270RH2w3kMBpG0i4YzDCsFs2pdxPX1WVknQvFk9bNgukMb158hc2Zb4SdwSA==", + "version": "5.59.15", + "resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.59.15.tgz", + "integrity": "sha512-QbVlAkTI78wB4Mqgf2RDmgC0AOiJqer2c5k9STOOSXGv1S6ZkY37r/6UpE8DbQ2Du0ohsdoXgFNEyv+4eDoPEw==", "requires": { - "@tanstack/query-core": "5.28.4" + "@tanstack/query-core": "5.59.13" } }, "@types/js-cookie": { diff --git a/package.json b/package.json index 253b778..e348edf 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "private": true, "scripts": { "dev": "next dev", - "build": "next build", + "build": "npm run lint && next build", "start": "next start", "lint": "next lint --fix .", "prepare": "husky" @@ -18,7 +18,7 @@ "@radix-ui/react-tabs": "^1.0.4", "@radix-ui/react-toast": "^1.2.2", "@radix-ui/react-toggle": "^1.0.3", - "@tanstack/react-query": "^5.17.3", + "@tanstack/react-query": "^5.59.15", "@vidstack/react": "^1.12.11", "axios": "^1.4.0", "class-variance-authority": "^0.7.0", diff --git a/providers/index.tsx b/providers/index.tsx index 65afae6..6ecb77a 100644 --- a/providers/index.tsx +++ b/providers/index.tsx @@ -1,11 +1,11 @@ 'use client'; -import { FC, ReactNode, useState } from 'react'; +import { FC, ReactNode } from 'react'; import ModalContainer from 'react-modal-promise'; -import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { QueryClientProvider } from '@tanstack/react-query'; import { Toaster } from '@/components/ui/toaster'; -import { queryClientOptions } from '@/lib/queryClient'; +import getQueryClient from '@/lib/queryClient'; import ThemeProvider from './Theme'; @@ -15,7 +15,7 @@ interface Props { } const Providers: FC = ({ children, theme }) => { - const [queryClient] = useState(() => new QueryClient(queryClientOptions)); + const queryClient = getQueryClient(); return ( diff --git a/types.d.ts b/types.d.ts index 5228597..3387196 100644 --- a/types.d.ts +++ b/types.d.ts @@ -171,3 +171,22 @@ interface RequestToken { expires_at: string; request_token: string; } + +interface Session { + session_id: string; +} + +interface Account { + id: number; + name: string; + username: string; + avatar: Avatar; +} + +interface Gravatar { + hash: string; +} + +interface Tmdb { + avatar_path: null; +}