forked from s1lvax/route
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
s1lvax
committed
Oct 23, 2024
1 parent
a842d8c
commit a2c202f
Showing
16 changed files
with
390 additions
and
21 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
<script lang="ts"> | ||
import { AudioLines } from 'lucide-svelte'; // For the music icon | ||
import { onMount } from 'svelte'; | ||
import * as Card from '$lib/components/ui/card'; | ||
import type { Artist, CurrentlyPlaying } from '$lib/types/Spotify'; | ||
export let githubUsername; | ||
let currentlyPlaying: CurrentlyPlaying | null = null; | ||
let isListening = false; | ||
// Fetch the currently playing song on mount | ||
onMount(async () => { | ||
try { | ||
const response = await fetch(`/api/spotify/currently-listening/${githubUsername}`); | ||
if (response.ok) { | ||
const data = await response.json(); | ||
if (data?.item) { | ||
isListening = true; | ||
currentlyPlaying = { | ||
song: data.item.name, | ||
artist: data.item.artists.map((artist: Artist) => artist.name).join(', '), | ||
songUrl: data.item.external_urls.spotify, // Link to song on Spotify | ||
artistUrl: data.item.artists[0].external_urls.spotify, // Link to the first artist on Spotify | ||
albumImageUrl: data.item.album.images[0]?.url ?? '' // Album image URL | ||
}; | ||
} else { | ||
isListening = false; | ||
} | ||
} | ||
} catch (error) { | ||
console.error('Error fetching currently playing song:', error); | ||
} | ||
}); | ||
</script> | ||
|
||
<Card.Root> | ||
<Card.Header> | ||
<Card.Title> | ||
<div class="flex flex-row items-center"> | ||
<AudioLines class="mr-2 text-green-700" /> Music | ||
</div> | ||
</Card.Title> | ||
<Card.Description>The developer is currently listening to</Card.Description> | ||
</Card.Header> | ||
|
||
<Card.Content> | ||
{#if isListening} | ||
<div class="flex flex-row items-center"> | ||
<!-- Album Image --> | ||
{#if currentlyPlaying?.albumImageUrl} | ||
<img | ||
src={currentlyPlaying.albumImageUrl} | ||
alt="Album Art" | ||
class="mr-4 h-12 w-12 rounded-lg" | ||
/> | ||
{/if} | ||
|
||
<div class="flex flex-col"> | ||
<!-- Song and Artist links --> | ||
<a | ||
href={currentlyPlaying?.songUrl} | ||
target="_blank" | ||
class="font-semibold hover:cursor-pointer hover:underline" | ||
> | ||
{currentlyPlaying?.song} | ||
</a> | ||
<a | ||
href={currentlyPlaying?.artistUrl} | ||
target="_blank" | ||
class=" text-sm hover:cursor-pointer hover:underline" | ||
> | ||
by {currentlyPlaying?.artist} | ||
</a> | ||
</div> | ||
</div> | ||
{:else} | ||
<div class="flex items-center"> | ||
<p>Not listening to anything currently</p> | ||
</div> | ||
{/if} | ||
</Card.Content> | ||
</Card.Root> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
export interface CurrentlyPlaying { | ||
song: string; | ||
artist: string; | ||
songUrl: string; | ||
artistUrl: string; | ||
albumImageUrl: string; | ||
} | ||
|
||
export interface Artist { | ||
name: string; | ||
external_urls: { | ||
spotify: string; | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
// src/lib/utils/spotify/fetchSpotifyCurrentlyPlaying.ts | ||
export const SPOTIFY_API_URL = 'https://api.spotify.com/v1'; | ||
|
||
export const fetchSpotifyCurrentlyPlaying = async (accessToken: string) => { | ||
const response = await fetch(`${SPOTIFY_API_URL}/me/player/currently-playing`, { | ||
headers: { | ||
Authorization: `Bearer ${accessToken}`, | ||
'Content-Type': 'application/json' | ||
} | ||
}); | ||
|
||
if (response.status === 204 || !response.ok) { | ||
// Return null if no content (204) or if there's an error | ||
return null; | ||
} | ||
|
||
return await response.json(); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import { randomBytes } from 'crypto'; | ||
|
||
export const generateRandomString = (length: number): string => { | ||
return randomBytes(Math.ceil(length / 2)) | ||
.toString('hex') | ||
.slice(0, length); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
// src/lib/utils/spotify/refreshSpotifyToken.ts | ||
export const refreshSpotifyToken = async (refreshToken: string) => { | ||
const response = await fetch('https://accounts.spotify.com/api/token', { | ||
method: 'POST', | ||
headers: { | ||
'Content-Type': 'application/x-www-form-urlencoded', | ||
Authorization: `Basic ${Buffer.from( | ||
`${process.env.SPOTIFY_CLIENT_ID}:${process.env.SPOTIFY_CLIENT_SECRET}` | ||
).toString('base64')}` | ||
}, | ||
body: new URLSearchParams({ | ||
grant_type: 'refresh_token', | ||
refresh_token: refreshToken | ||
}) | ||
}); | ||
|
||
if (!response.ok) { | ||
console.error('Failed to refresh Spotify token:', response.statusText); | ||
return null; | ||
} | ||
|
||
return await response.json(); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import { prisma } from '$lib/server/prisma'; | ||
|
||
export const unlinkSpotify = async (githubId: number) => { | ||
try { | ||
// fetch current state | ||
const user = await prisma.user.findUnique({ | ||
where: { githubId: githubId } | ||
}); | ||
|
||
if (!user) { | ||
throw new Error('User not found'); | ||
} | ||
|
||
// delete token from db | ||
await prisma.spotifyToken.delete({ | ||
where: { userId: githubId } | ||
}); | ||
} catch (error) { | ||
console.error(error); | ||
throw new Error('Failed to delete Spotify'); | ||
} | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
// src/routes/auth/callback/+server.ts | ||
import type { RequestHandler } from './$types'; | ||
import { json, redirect } from '@sveltejs/kit'; | ||
import { prisma } from '$lib/server/prisma'; // Import Prisma client | ||
|
||
import { SPOTIFY_ID, SPOTIFY_REDIRECT, SPOTIFY_SECRET } from '$env/static/private'; | ||
import { getGitHubUserIdFromImageUrl } from '$lib/utils/getGithubIDFromImage'; | ||
|
||
//Token URL | ||
const TOKEN_URL = 'https://accounts.spotify.com/api/token'; | ||
|
||
export const GET: RequestHandler = async ({ url, locals }) => { | ||
const code = url.searchParams.get('code'); | ||
const state = url.searchParams.get('state'); | ||
|
||
// error if no code returns (spotify docs) | ||
if (!code) { | ||
return json({ error: 'Missing authorization code' }, { status: 400 }); | ||
} | ||
|
||
//make sure an user exists | ||
const session = await locals.auth(); | ||
if (!session?.user) throw redirect(303, '/'); | ||
|
||
//use our image strategy to get the user Id | ||
const userId = getGitHubUserIdFromImageUrl(session.user.image); | ||
|
||
// exchange the authorization code for an access token and refresh token | ||
const body = new URLSearchParams({ | ||
grant_type: 'authorization_code', | ||
code, | ||
redirect_uri: SPOTIFY_REDIRECT, | ||
client_id: SPOTIFY_ID, | ||
client_secret: SPOTIFY_SECRET | ||
}); | ||
|
||
const response = await fetch(TOKEN_URL, { | ||
method: 'POST', | ||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, | ||
body | ||
}); | ||
|
||
const tokenData = await response.json(); | ||
|
||
if (tokenData.access_token && tokenData.refresh_token) { | ||
const accessToken = tokenData.access_token; | ||
const refreshToken = tokenData.refresh_token; | ||
const expiresIn = tokenData.expires_in; | ||
|
||
const expiresAt = new Date(Date.now() + expiresIn * 1000); // Calculate token expiration time | ||
|
||
// Upsert tokens into the Prisma database (insert if not exists, otherwise update) | ||
await prisma.spotifyToken.upsert({ | ||
where: { userId: userId }, | ||
update: { | ||
accessToken, | ||
refreshToken, | ||
expiresAt | ||
}, | ||
create: { | ||
userId, | ||
accessToken, | ||
refreshToken, | ||
expiresAt | ||
} | ||
}); | ||
|
||
throw redirect(302, '/profile'); | ||
} else { | ||
return json({ error: 'Failed to get tokens from Spotify' }, { status: 400 }); | ||
} | ||
}; |
Oops, something went wrong.