Skip to content

Commit

Permalink
styling: random spotify playlist
Browse files Browse the repository at this point in the history
  • Loading branch information
guidefari committed May 25, 2024
1 parent 7c403f9 commit 344adbc
Show file tree
Hide file tree
Showing 3 changed files with 158 additions and 30 deletions.
23 changes: 23 additions & 0 deletions src/components/common/icons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,26 @@ export const GB = () => (
/>
</svg>
)

export const SpinningCircleLoaderThingy = () => (
<svg
className="w-5 h-5 mx-auto text-inherit animate-spin"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
></circle>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
)
52 changes: 52 additions & 0 deletions src/pages/api/v2/random-playlist.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { getSession } from 'next-auth/react';
import { PlaylistInput, PlaylistResponse } from '@/src/types';
import { getUsersPlaylists } from '@/lib/spotify';
import { logMessage } from '@/lib/logger';
const fs = require('fs');

export type ResponseType = PlaylistResponse["items"]


let playlists: ResponseType
let looping = true

const handler = async (req: NextApiRequest,
res: NextApiResponse<ResponseType>) => {
const {
token: { accessToken, sub },
} = await getSession({ req });

playlists = []

await getBatch({ refresh_token: accessToken, user_id: sub })

if (!looping) {
// const random = stringsss[Math.floor(Math.random() * stringsss.length)]
return res.status(200).send(playlists)
};
};

export default handler;


const getBatch = async ({ offset, refresh_token, user_id, next_url }: PlaylistInput): Promise<PlaylistResponse> => {
const response = await getUsersPlaylists({ refresh_token, user_id, offset, next_url })
const thing: PlaylistResponse = await response.json()
// const stuffToClean: = await response.json()
// const clean = await cleanShitUp(stuffToClean)
playlists.push(...thing.items)
if (thing.next) {
await getBatch({ refresh_token, user_id, next_url: thing.next })
return
}

looping = false
return
}

// const cleanShitUp = async (stuff: PlaylistResponse) => {
// console.log('stuff:', stuff)
// return stuff.items.map((item) => item.external_urls.spotify)
// }

113 changes: 83 additions & 30 deletions src/pages/rsp.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import fetcher from '@/lib/fetcher'
import { useSession, signIn, signOut } from 'next-auth/react'
import Image from 'next/image'
import Link from 'next/link'
import { useState } from 'react'
import useSWR from 'swr'
import { type ResponseType as RandomPlaylistApiResponse } from './api/v2/random-playlist'
import { useRouter } from 'next/router'
import { SpinningCircleLoaderThingy } from '@/components/common/icons'
import clsx from 'clsx'

declare module 'next-auth' {
/**
Expand All @@ -24,39 +28,88 @@ declare module 'next-auth' {

export default function RSP() {
const { data: session } = useSession()
console.log('session:', session)
const [list, setList] = useState([])
const shouldFetch = !!session
const {
data: playlists,
error: playlistError,
isLoading: playlistLoading,
} = useSWR<RandomPlaylistApiResponse>(shouldFetch ? '/api/v2/random-playlist' : null, fetcher)
const router = useRouter()

const getMyPlaylists = async () => {
const res = await fetch('/api/playlists')
const { items } = await res.json()
setList(items)
const goToRandomPlaylist = () => {
let randomIndex = Math.floor(Math.random() * playlists?.length || 0)
router.push(`${playlists?.[randomIndex]?.external_urls.spotify}`)
}

if (!session) {
return (
<div className="flex flex-col items-center justify-center my-auto">
<div className="bg-[#191414] rounded-lg shadow-lg p-8 w-full max-w-md">
<div className="flex flex-col justify-center space-y-3">
<button
onClick={() => signIn()}
className="w-full p-3 rounded-md text-gb-highlight hover:ring-2 hover:ring-gb-highlight"
>
Sign in via Spotify
</button>
</div>
</div>
</div>
)
}

if (session) {
return (
<>
Signed in as {session?.session?.user?.name} <br />
<Image
width={50}
height={50}
alt={session?.session?.user?.name}
src={session?.session?.user?.image}
/>
<hr />
<button>
<Link target="_blank" href={'/api/random-playlist'}>
Random
</Link>
</button>
<button onClick={() => signOut()}>Sign out</button>
</>
<div className="flex flex-col items-center justify-center my-auto">
<div className="bg-[#191414] rounded-lg shadow-lg p-8 w-full max-w-md">
<div className="flex items-center justify-between mb-6">
<div className="flex items-center">
<Image
className="mr-4 rounded-full"
alt={session?.session?.user?.name}
src={session?.session?.user?.image}
height={48}
style={{
aspectRatio: '48/48',
objectFit: 'cover',
}}
width={48}
/>
<div>
<h2 className="text-2xl font-bold">{session?.session?.user?.name}</h2>
</div>
</div>
</div>
<div className="space-y-10 text-center">
{playlistLoading && (
<p className="mb-4 text-left text-gray-400">
Fetching your playlists. Wait time may be a little longer if you have many
playlists.
</p>
)}
<div className="flex flex-col justify-center space-y-3">
<button
onClick={() => goToRandomPlaylist()}
disabled={!playlists?.length && playlistLoading}
className={clsx(
'w-full p-3 rounded-md h-14 bg-gb-pastel-green-2 text-gb-highlight',
playlists?.length && !playlistLoading
? 'hover:ring-2 hover:ring-gb-highlight'
: ''
)}
>
{playlistLoading ? <SpinningCircleLoaderThingy /> : 'Take me to random playlist'}
</button>
<button
className="w-full p-3 rounded-md h-14 hover:ring-2 hover:ring-gb-highlight"
onClick={() => signOut()}
>
Logout
</button>
</div>
</div>
</div>
</div>
)
}
return (
<>
Not signed in <br />
<button onClick={() => signIn()}>Sign in</button>
</>
)
}

0 comments on commit 344adbc

Please sign in to comment.