Lazuli, now with openapi!
This commit is contained in:
12
src/routes/api/connections/+server.ts
Normal file
12
src/routes/api/connections/+server.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import type { RequestHandler } from '@sveltejs/kit'
|
||||
import { Connections } from '$lib/server/users'
|
||||
|
||||
export const GET: RequestHandler = async ({ url }) => {
|
||||
const ids = url.searchParams.get('ids')?.replace(/\s/g, '').split(',')
|
||||
if (!ids) return new Response('Missing ids query parameter', { status: 400 })
|
||||
|
||||
const connections: Connection[] = []
|
||||
for (const connectionId of ids) connections.push(Connections.getConnection(connectionId))
|
||||
|
||||
return Response.json({ connections })
|
||||
}
|
||||
53
src/routes/api/connections/[connectionId]/info/+server.ts
Normal file
53
src/routes/api/connections/[connectionId]/info/+server.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import type { RequestHandler } from '@sveltejs/kit'
|
||||
import { Connections } from '$lib/server/users'
|
||||
import { google } from 'googleapis'
|
||||
|
||||
const youtubeInfo = async (connection: Connection): Promise<ConnectionInfo> => {
|
||||
const youtube = google.youtube('v3')
|
||||
const userChannelResponse = await youtube.channels.list({ mine: true, part: ['snippet'], access_token: connection.accessToken })
|
||||
const userChannel = userChannelResponse.data.items![0]
|
||||
|
||||
return {
|
||||
connectionId: connection.id,
|
||||
serviceType: connection.service.type,
|
||||
username: userChannel.snippet?.title as string,
|
||||
profilePicture: userChannel.snippet?.thumbnails?.default?.url as string | undefined,
|
||||
}
|
||||
}
|
||||
|
||||
const jellyfinInfo = async (connection: Connection): Promise<ConnectionInfo> => {
|
||||
const reqHeaders = new Headers({ Authorization: `MediaBrowser Token="${connection.accessToken}"` })
|
||||
|
||||
const userUrl = new URL(`Users/${connection.service.userId}`, connection.service.urlOrigin).href
|
||||
const systemUrl = new URL('System/Info', connection.service.urlOrigin).href
|
||||
|
||||
const userResponse = await fetch(userUrl, { headers: reqHeaders })
|
||||
const systemResponse = await fetch(systemUrl, { headers: reqHeaders })
|
||||
|
||||
const userData: Jellyfin.User = await userResponse.json()
|
||||
const systemData: Jellyfin.System = await systemResponse.json()
|
||||
|
||||
return {
|
||||
connectionId: connection.id,
|
||||
serviceType: 'jellyfin',
|
||||
username: userData.Name,
|
||||
serverName: systemData.ServerName,
|
||||
}
|
||||
}
|
||||
|
||||
export const GET: RequestHandler = async ({ params }) => {
|
||||
const connectionId = params.connectionId!
|
||||
const connection = Connections.getConnection(connectionId)
|
||||
|
||||
let info: ConnectionInfo
|
||||
switch (connection.service.type) {
|
||||
case 'jellyfin':
|
||||
info = await jellyfinInfo(connection)
|
||||
break
|
||||
case 'youtube-music':
|
||||
info = await youtubeInfo(connection)
|
||||
break
|
||||
}
|
||||
|
||||
return Response.json({ info })
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
import type { RequestHandler } from '@sveltejs/kit'
|
||||
import { isValidURL } from '$lib/utils'
|
||||
import { z } from 'zod'
|
||||
|
||||
export const POST: RequestHandler = async ({ request, fetch }) => {
|
||||
const jellyfinAuthSchema = z.object({
|
||||
serverUrl: z.string().refine((val) => isValidURL(val)),
|
||||
username: z.string(),
|
||||
password: z.string(),
|
||||
deviceId: z.string(),
|
||||
})
|
||||
|
||||
const jellyfinAuthData = await request.json()
|
||||
const jellyfinAuthValidation = jellyfinAuthSchema.safeParse(jellyfinAuthData)
|
||||
if (!jellyfinAuthValidation.success) return new Response('Invalid data in request body', { status: 400 })
|
||||
|
||||
const { serverUrl, username, password, deviceId } = jellyfinAuthValidation.data
|
||||
const authUrl = new URL('/Users/AuthenticateByName', serverUrl).href
|
||||
try {
|
||||
const authResponse = await fetch(authUrl, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
Username: username,
|
||||
Pw: password,
|
||||
}),
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'X-Emby-Authorization': `MediaBrowser Client="Lazuli", Device="Chrome", DeviceId="${deviceId}", Version="1.0.0.0"`,
|
||||
},
|
||||
})
|
||||
if (!authResponse.ok) return new Response('Failed to authenticate', { status: 401 })
|
||||
|
||||
const authData: Jellyfin.AuthData = await authResponse.json()
|
||||
return Response.json(authData)
|
||||
} catch {
|
||||
return new Response('Fetch request failed', { status: 404 })
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { RequestHandler } from '@sveltejs/kit'
|
||||
import { YouTubeMusic } from '$lib/service-managers/youtubeMusic'
|
||||
import { Jellyfin } from '$lib/service-managers/jellyfin'
|
||||
import { Connections } from '$lib/server/users'
|
||||
|
||||
export const GET: RequestHandler = async ({ params, url }) => {
|
||||
const userId = params.userId as string
|
||||
const requestedConnectionIds = url.searchParams.get('connectionIds')?.split(',')
|
||||
|
||||
const connectionInfo: ConnectionInfo[] = []
|
||||
|
||||
const userConnections: Connection[] = requestedConnectionIds ? Array.from(requestedConnectionIds, (id) => Connections.getConnection(id)) : Connections.getUserConnections(userId)
|
||||
|
||||
for (const connection of userConnections) {
|
||||
let info: ConnectionInfo
|
||||
switch (connection.service.type) {
|
||||
case 'jellyfin':
|
||||
info = await Jellyfin.connectionInfo(connection as Jellyfin.JFConnection)
|
||||
break
|
||||
case 'youtube-music':
|
||||
info = await YouTubeMusic.connectionInfo(connection as YouTubeMusic.YTConnection)
|
||||
break
|
||||
}
|
||||
connectionInfo.push(info)
|
||||
}
|
||||
|
||||
return Response.json({ connectionInfo })
|
||||
}
|
||||
@@ -1,48 +1,9 @@
|
||||
import { Connections } from '$lib/server/users'
|
||||
import { isValidURL } from '$lib/utils'
|
||||
import type { RequestHandler } from '@sveltejs/kit'
|
||||
import { z } from 'zod'
|
||||
|
||||
export const GET: RequestHandler = async ({ params }) => {
|
||||
const userId = params.userId as string
|
||||
const userId = params.userId!
|
||||
|
||||
const connections = Connections.getUserConnections(userId)
|
||||
return Response.json(connections)
|
||||
}
|
||||
|
||||
// This schema should be identical to the Connection Data Type but without the id and userId
|
||||
const newConnectionSchema = z.object({
|
||||
service: z.object({
|
||||
type: z.enum(['jellyfin', 'youtube-music']),
|
||||
userId: z.string(),
|
||||
urlOrigin: z.string().refine((val) => isValidURL(val)),
|
||||
}),
|
||||
tokens: z.object({
|
||||
accessToken: z.string(),
|
||||
refreshToken: z.string().optional(),
|
||||
expiry: z.number().optional(),
|
||||
}),
|
||||
})
|
||||
|
||||
export const POST: RequestHandler = async ({ params, request }) => {
|
||||
const userId = params.userId as string
|
||||
|
||||
const connection: Connection = await request.json()
|
||||
|
||||
const connectionValidation = newConnectionSchema.safeParse(connection)
|
||||
if (!connectionValidation.success) return new Response(connectionValidation.error.message, { status: 400 })
|
||||
|
||||
const { service, tokens } = connection
|
||||
const newConnection = Connections.addConnection(userId, service, tokens)
|
||||
return Response.json(newConnection)
|
||||
}
|
||||
|
||||
export const DELETE: RequestHandler = async ({ request }) => {
|
||||
const requestData = await request.json()
|
||||
try {
|
||||
Connections.deleteConnection(requestData.connectionId)
|
||||
return new Response('Connection Deleted')
|
||||
} catch (error) {
|
||||
return new Response('Connection does not exist', { status: 400 })
|
||||
}
|
||||
return Response.json({ connections })
|
||||
}
|
||||
|
||||
@@ -5,15 +5,15 @@ import { Jellyfin } from '$lib/service-managers/jellyfin'
|
||||
// This is temporary functionally for the sake of developing the app.
|
||||
// In the future will implement more robust algorithm for offering recommendations
|
||||
export const GET: RequestHandler = async ({ params, fetch }) => {
|
||||
const userId = params.userId as string
|
||||
const userId = params.userId!
|
||||
|
||||
const connectionsResponse = await fetch(`/api/users/${userId}/connections`, { headers: { apikey: SECRET_INTERNAL_API_KEY } })
|
||||
const userConnections: Connection[] = await connectionsResponse.json()
|
||||
const userConnections = await connectionsResponse.json()
|
||||
|
||||
const recommendations: Song[] = []
|
||||
const recommendations: MediaItem[] = []
|
||||
|
||||
for (const connection of userConnections) {
|
||||
const { service, tokens } = connection
|
||||
for (const connection of userConnections.connections) {
|
||||
const { service, accessToken } = connection as Connection
|
||||
|
||||
switch (service.type) {
|
||||
case 'jellyfin':
|
||||
@@ -26,12 +26,12 @@ export const GET: RequestHandler = async ({ params, fetch }) => {
|
||||
})
|
||||
|
||||
const mostPlayedSongsURL = new URL(`/Users/${service.userId}/Items?${mostPlayedSongsSearchParams.toString()}`, service.urlOrigin).href
|
||||
const requestHeaders = new Headers({ Authorization: `MediaBrowser Token="${tokens.accessToken}"` })
|
||||
const requestHeaders = new Headers({ Authorization: `MediaBrowser Token="${accessToken}"` })
|
||||
|
||||
const mostPlayedResponse = await fetch(mostPlayedSongsURL, { headers: requestHeaders })
|
||||
const mostPlayedData = await mostPlayedResponse.json()
|
||||
|
||||
mostPlayedData.Items.forEach((song: Jellyfin.Song) => recommendations.push(Jellyfin.songFactory(song, connection as Jellyfin.JFConnection)))
|
||||
for (const song of mostPlayedData.Items) recommendations.push(Jellyfin.songFactory(song, connection))
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { fail } from '@sveltejs/kit'
|
||||
import { SECRET_INTERNAL_API_KEY, YOUTUBE_API_CLIENT_SECRET } from '$env/static/private'
|
||||
import { PUBLIC_YOUTUBE_API_CLIENT_ID } from '$env/static/public'
|
||||
import type { PageServerLoad, Actions } from './$types'
|
||||
import { Connections } from '$lib/server/users'
|
||||
import { google } from 'googleapis'
|
||||
|
||||
export const load: PageServerLoad = async ({ fetch, locals }) => {
|
||||
@@ -10,9 +11,8 @@ export const load: PageServerLoad = async ({ fetch, locals }) => {
|
||||
headers: { apikey: SECRET_INTERNAL_API_KEY },
|
||||
})
|
||||
|
||||
console.log(locals.user.id)
|
||||
const userConnections: Connection[] = await connectionsResponse.json()
|
||||
return { userConnections }
|
||||
const userConnections = await connectionsResponse.json()
|
||||
return { connections: userConnections.connections }
|
||||
}
|
||||
|
||||
export const actions: Actions = {
|
||||
@@ -20,92 +20,63 @@ export const actions: Actions = {
|
||||
const formData = await request.formData()
|
||||
const { serverUrl, username, password, deviceId } = Object.fromEntries(formData)
|
||||
|
||||
const jellyfinAuthResponse = await fetch('/api/jellyfin/auth', {
|
||||
method: 'POST',
|
||||
headers: { apikey: SECRET_INTERNAL_API_KEY },
|
||||
body: JSON.stringify({ serverUrl, username, password, deviceId }),
|
||||
})
|
||||
const authUrl = new URL('/Users/AuthenticateByName', serverUrl.toString()).href
|
||||
let authData: Jellyfin.AuthData
|
||||
try {
|
||||
const authResponse = await fetch(authUrl, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
Username: username,
|
||||
Pw: password,
|
||||
}),
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'X-Emby-Authorization': `MediaBrowser Client="Lazuli", Device="Chrome", DeviceId="${deviceId}", Version="1.0.0.0"`,
|
||||
},
|
||||
})
|
||||
|
||||
if (!jellyfinAuthResponse.ok) {
|
||||
if (jellyfinAuthResponse.status === 404) {
|
||||
return fail(404, { message: 'Request failed, check Server URL' })
|
||||
} else if (jellyfinAuthResponse.status === 401) {
|
||||
return fail(401, { message: 'Invalid Credentials' })
|
||||
}
|
||||
if (!authResponse.ok) return fail(401, { message: 'Failed to authenticate' })
|
||||
|
||||
return fail(500, { message: 'Internal Server Error' })
|
||||
authData = await authResponse.json()
|
||||
} catch {
|
||||
return fail(400, { message: 'Could not reach Jellyfin server' })
|
||||
}
|
||||
|
||||
const authData: Jellyfin.AuthData = await jellyfinAuthResponse.json()
|
||||
|
||||
const serviceData: Jellyfin.JFService = {
|
||||
const serviceData: Service = {
|
||||
type: 'jellyfin',
|
||||
userId: authData.User.Id,
|
||||
urlOrigin: serverUrl.toString(),
|
||||
}
|
||||
const tokenData: Jellyfin.JFTokens = {
|
||||
accessToken: authData.AccessToken,
|
||||
}
|
||||
|
||||
const newConnectionResponse = await fetch(`/api/users/${locals.user.id}/connections`, {
|
||||
method: 'POST',
|
||||
headers: { apikey: SECRET_INTERNAL_API_KEY },
|
||||
body: JSON.stringify({ service: serviceData, tokens: tokenData }),
|
||||
})
|
||||
const newConnection = Connections.addConnection(locals.user.id, serviceData, authData.AccessToken)
|
||||
|
||||
if (!newConnectionResponse.ok) return fail(500, { message: 'Internal Server Error' })
|
||||
|
||||
const newConnection: Jellyfin.JFConnection = await newConnectionResponse.json()
|
||||
return { newConnection }
|
||||
},
|
||||
youtubeMusicLogin: async ({ request, fetch, locals }) => {
|
||||
youtubeMusicLogin: async ({ request, locals }) => {
|
||||
const formData = await request.formData()
|
||||
const { code } = Object.fromEntries(formData)
|
||||
const client = new google.auth.OAuth2({ clientId: PUBLIC_YOUTUBE_API_CLIENT_ID, clientSecret: YOUTUBE_API_CLIENT_SECRET, redirectUri: 'http://localhost:5173' }) // DO NOT SHIP THIS. THE CLIENT SECRET SHOULD NOT BE MADE AVAILABLE TO USERS. MAKE A REQUEST TO THE LAZULI WEBSITE INSTEAD.
|
||||
const { tokens } = await client.getToken(code.toString())
|
||||
|
||||
const tokenData: YouTubeMusic.YTTokens = {
|
||||
accessToken: tokens.access_token as string,
|
||||
refreshToken: tokens.refresh_token as string,
|
||||
expiry: tokens.expiry_date as number,
|
||||
}
|
||||
|
||||
const youtube = google.youtube('v3')
|
||||
const userChannelResponse = await youtube.channels.list({ mine: true, part: ['id', 'snippet'], access_token: tokenData.accessToken })
|
||||
const userChannelResponse = await youtube.channels.list({ mine: true, part: ['id', 'snippet'], access_token: tokens.access_token! })
|
||||
const userChannel = userChannelResponse.data.items![0]
|
||||
|
||||
const serviceData: YouTubeMusic.YTService = {
|
||||
const serviceData: Service = {
|
||||
type: 'youtube-music',
|
||||
userId: userChannel.id as string,
|
||||
userId: userChannel.id!,
|
||||
urlOrigin: 'https://www.googleapis.com/youtube/v3',
|
||||
}
|
||||
|
||||
const newConnectionResponse = await fetch(`/api/users/${locals.user.id}/connections`, {
|
||||
method: 'POST',
|
||||
headers: { apikey: SECRET_INTERNAL_API_KEY },
|
||||
body: JSON.stringify({ service: serviceData, tokens: tokenData }),
|
||||
})
|
||||
const newConnection = Connections.addConnection(locals.user.id, serviceData, tokens.access_token!, tokens.refresh_token!, tokens.expiry_date!)
|
||||
|
||||
if (!newConnectionResponse.ok) return fail(500, { message: 'Internal Server Error' })
|
||||
|
||||
const newConnection: YouTubeMusic.YTConnection = await newConnectionResponse.json()
|
||||
return { newConnection }
|
||||
},
|
||||
refreshConnection: async ({ request }) => {
|
||||
deleteConnection: async ({ request }) => {
|
||||
const formData = await request.formData()
|
||||
const connectionId = formData.get('connectionId')?.toString() as string
|
||||
},
|
||||
deleteConnection: async ({ request, fetch, locals }) => {
|
||||
const formData = await request.formData()
|
||||
const connectionId = formData.get('connectionId')?.toString() as string
|
||||
const connectionId = formData.get('connectionId')!.toString()
|
||||
|
||||
const deleteConnectionResponse = await fetch(`/api/users/${locals.user.id}/connections`, {
|
||||
method: 'DELETE',
|
||||
headers: { apikey: SECRET_INTERNAL_API_KEY },
|
||||
body: JSON.stringify({ connectionId }),
|
||||
})
|
||||
|
||||
if (!deleteConnectionResponse.ok) return fail(500, { message: 'Internal Server Error' })
|
||||
Connections.deleteConnection(connectionId)
|
||||
|
||||
return { deletedConnectionId: connectionId }
|
||||
},
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
import { PUBLIC_YOUTUBE_API_CLIENT_ID } from '$env/static/public'
|
||||
|
||||
export let data: PageServerData
|
||||
let connections = data.userConnections
|
||||
let connections: Connection[] = data.connections
|
||||
|
||||
const authenticateJellyfin: SubmitFunction = ({ formData, cancel }) => {
|
||||
const { serverUrl, username, password } = Object.fromEntries(formData)
|
||||
|
||||
Reference in New Issue
Block a user