initial version

This commit is contained in:
2026-03-25 16:18:23 -04:00
parent aeec7cae36
commit 88595bee90
27 changed files with 7959 additions and 1 deletions

2
.gitignore vendored
View File

@@ -2,4 +2,4 @@
data/
.next/
node_modules/
out/
out/

14
eslint.config.mjs Normal file
View File

@@ -0,0 +1,14 @@
import { dirname } from 'path'
import { fileURLToPath } from 'url'
import { FlatCompat } from '@eslint/eslintrc'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const compat = new FlatCompat({ baseDirectory: __dirname })
const eslintConfig = [
...compat.extends('next/core-web-vitals'),
]
export default eslintConfig

14
libraries.json Normal file
View File

@@ -0,0 +1,14 @@
[
{
"id": "games",
"name": "Games",
"path": "./data/Games",
"type": "games"
},
{
"id": "various",
"name": "Various Media",
"path": "./data/Various Media",
"type": "mixed"
}
]

6
next-env.d.ts vendored Normal file
View File

@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference path="./.next/types/routes.d.ts" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

5
next.config.ts Normal file
View File

@@ -0,0 +1,5 @@
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {}
export default nextConfig

6717
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

30
package.json Normal file
View File

@@ -0,0 +1,30 @@
{
"name": "medialoreweb",
"version": "1.0.0",
"description": "MediaLore NAS media library web UI",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"next": "^15.5.14",
"react": "^19.2.4",
"react-dom": "^19.2.4"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.2.2",
"@types/node": "^25.5.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"eslint": "^9.39.4",
"eslint-config-next": "^16.2.1",
"postcss": "^8.5.8",
"tailwindcss": "^4.2.2",
"typescript": "^5.9.3"
}
}

7
postcss.config.mjs Normal file
View File

@@ -0,0 +1,7 @@
const config = {
plugins: {
'@tailwindcss/postcss': {},
},
}
export default config

View File

@@ -0,0 +1,25 @@
import { NextRequest, NextResponse } from 'next/server'
import { getLibrary, resolveLibraryRoot } from '@/lib/libraries'
import { scanDirectory } from '@/lib/files'
export function GET(request: NextRequest) {
const { searchParams } = request.nextUrl
const libraryId = searchParams.get('libraryId')
const subpath = searchParams.get('path') ?? ''
if (!libraryId) {
return NextResponse.json({ error: 'Missing libraryId' }, { status: 400 })
}
const library = getLibrary(libraryId)
if (!library) {
return NextResponse.json({ error: 'Library not found' }, { status: 404 })
}
if (library.type !== 'mixed') {
return NextResponse.json({ error: 'Library is not a mixed library' }, { status: 400 })
}
const root = resolveLibraryRoot(library)
const listing = scanDirectory(root, libraryId, subpath)
return NextResponse.json(listing)
}

118
src/app/api/file/route.ts Normal file
View File

@@ -0,0 +1,118 @@
import { NextRequest, NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
import { getLibrary, resolveLibraryRoot, resolveAndJail } from '@/lib/libraries'
const MIME_TYPES: Record<string, string> = {
'.mp4': 'video/mp4',
'.mov': 'video/quicktime',
'.mkv': 'video/x-matroska',
'.avi': 'video/x-msvideo',
'.webm': 'video/webm',
'.m4v': 'video/x-m4v',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.png': 'image/png',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.bmp': 'image/bmp',
'.tiff': 'image/tiff',
'.tif': 'image/tiff',
'.zip': 'application/zip',
}
function getMimeType(filePath: string): string {
const ext = path.extname(filePath).toLowerCase()
return MIME_TYPES[ext] ?? 'application/octet-stream'
}
export async function GET(request: NextRequest) {
const { searchParams } = request.nextUrl
const libraryId = searchParams.get('libraryId')
const subpath = searchParams.get('path')
if (!libraryId || !subpath) {
return NextResponse.json({ error: 'Missing libraryId or path' }, { status: 400 })
}
const library = getLibrary(libraryId)
if (!library) {
return NextResponse.json({ error: 'Library not found' }, { status: 404 })
}
const root = resolveLibraryRoot(library)
let filePath: string
try {
filePath = resolveAndJail(root, subpath)
} catch {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
}
let stat: fs.Stats
try {
stat = fs.statSync(filePath)
} catch {
return NextResponse.json({ error: 'File not found' }, { status: 404 })
}
if (!stat.isFile()) {
return NextResponse.json({ error: 'Not a file' }, { status: 400 })
}
const mimeType = getMimeType(filePath)
const fileSize = stat.size
const rangeHeader = request.headers.get('range')
// Handle ZIP as a download
const isZip = path.extname(filePath).toLowerCase() === '.zip'
const contentDisposition = isZip
? `attachment; filename="${encodeURIComponent(path.basename(filePath))}"`
: `inline; filename="${encodeURIComponent(path.basename(filePath))}"`
if (rangeHeader) {
// Parse "bytes=start-end"
const match = rangeHeader.match(/bytes=(\d*)-(\d*)/)
if (!match) {
return new NextResponse('Invalid Range', { status: 416 })
}
const start = match[1] ? parseInt(match[1], 10) : 0
const end = match[2] ? parseInt(match[2], 10) : fileSize - 1
if (start > end || end >= fileSize) {
return new NextResponse('Range Not Satisfiable', {
status: 416,
headers: { 'Content-Range': `bytes */${fileSize}` },
})
}
const chunkSize = end - start + 1
const stream = fs.createReadStream(filePath, { start, end })
return new NextResponse(stream as unknown as ReadableStream, {
status: 206,
headers: {
'Content-Type': mimeType,
'Content-Range': `bytes ${start}-${end}/${fileSize}`,
'Content-Length': String(chunkSize),
'Accept-Ranges': 'bytes',
'Content-Disposition': contentDisposition,
'Cache-Control': 'public, max-age=3600',
},
})
}
// Full file response
const stream = fs.createReadStream(filePath)
return new NextResponse(stream as unknown as ReadableStream, {
status: 200,
headers: {
'Content-Type': mimeType,
'Content-Length': String(fileSize),
'Accept-Ranges': 'bytes',
'Content-Disposition': contentDisposition,
'Cache-Control': 'public, max-age=3600',
},
})
}

View File

@@ -0,0 +1,24 @@
import { NextRequest, NextResponse } from 'next/server'
import { getLibrary, resolveLibraryRoot } from '@/lib/libraries'
import { scanGamesLibrary } from '@/lib/games'
export function GET(request: NextRequest) {
const { searchParams } = request.nextUrl
const libraryId = searchParams.get('libraryId')
if (!libraryId) {
return NextResponse.json({ error: 'Missing libraryId' }, { status: 400 })
}
const library = getLibrary(libraryId)
if (!library) {
return NextResponse.json({ error: 'Library not found' }, { status: 404 })
}
if (library.type !== 'games') {
return NextResponse.json({ error: 'Library is not a games library' }, { status: 400 })
}
const root = resolveLibraryRoot(library)
const games = scanGamesLibrary(root, libraryId)
return NextResponse.json(games)
}

View File

@@ -0,0 +1,12 @@
import { NextResponse } from 'next/server'
import { getLibraries } from '@/lib/libraries'
export function GET() {
try {
const libraries = getLibraries()
return NextResponse.json(libraries)
} catch (err) {
console.error('Failed to read libraries.json', err)
return NextResponse.json({ error: 'Failed to load libraries' }, { status: 500 })
}
}

39
src/app/globals.css Normal file
View File

@@ -0,0 +1,39 @@
@import "tailwindcss";
:root {
--background: #0f0f11;
--surface: #1a1a1f;
--surface-hover: #24242b;
--border: #2e2e38;
--text-primary: #f0f0f5;
--text-secondary: #9090a8;
--accent: #7c6aff;
--accent-hover: #9583ff;
}
body {
background-color: var(--background);
color: var(--text-primary);
font-family: system-ui, -apple-system, sans-serif;
-webkit-font-smoothing: antialiased;
}
* {
box-sizing: border-box;
}
/* Scrollbar */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: var(--background);
}
::-webkit-scrollbar-thumb {
background: var(--border);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--text-secondary);
}

31
src/app/layout.tsx Normal file
View File

@@ -0,0 +1,31 @@
import type { Metadata } from 'next'
import './globals.css'
export const metadata: Metadata = {
title: 'MediaLore',
description: 'Your personal media library',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body className="min-h-screen">
<header className="border-b sticky top-0 z-40" style={{ borderColor: 'var(--border)', backgroundColor: 'var(--background)' }}>
<div className="max-w-7xl mx-auto px-6 h-14 flex items-center gap-3">
<a href="/" className="flex items-center gap-2 font-semibold text-lg tracking-tight" style={{ color: 'var(--text-primary)' }}>
<span style={{ color: 'var(--accent)' }}></span>
MediaLore
</a>
</div>
</header>
<main className="max-w-7xl mx-auto px-6 py-8">
{children}
</main>
</body>
</html>
)
}

View File

@@ -0,0 +1,34 @@
import { getLibrary } from '@/lib/libraries'
import { notFound } from 'next/navigation'
import GamesView from '@/components/games/GamesView'
import MixedView from '@/components/mixed/MixedView'
interface Props {
params: Promise<{ id: string }>
searchParams: Promise<{ path?: string }>
}
export default async function LibraryPage({ params, searchParams }: Props) {
const { id } = await params
const { path: subpath } = await searchParams
const library = getLibrary(id)
if (!library) notFound()
return (
<div>
<div className="flex items-center gap-2 mb-6">
<a href="/" className="text-sm transition-colors" style={{ color: 'var(--text-secondary)' }}>
Libraries
</a>
<span style={{ color: 'var(--text-secondary)' }}>/</span>
<span className="text-sm font-medium" style={{ color: 'var(--text-primary)' }}>
{library.name}
</span>
</div>
{library.type === 'games' && <GamesView libraryId={id} />}
{library.type === 'mixed' && <MixedView libraryId={id} initialPath={subpath ?? ''} />}
</div>
)
}

29
src/app/page.tsx Normal file
View File

@@ -0,0 +1,29 @@
import { getLibraries } from '@/lib/libraries'
import LibraryCard from '@/components/LibraryCard'
export default function HomePage() {
const libraries = getLibraries()
return (
<div>
<h1 className="text-2xl font-semibold mb-1" style={{ color: 'var(--text-primary)' }}>
Libraries
</h1>
<p className="text-sm mb-8" style={{ color: 'var(--text-secondary)' }}>
{libraries.length} {libraries.length === 1 ? 'library' : 'libraries'} configured
</p>
{libraries.length === 0 ? (
<div className="rounded-lg border p-12 text-center" style={{ borderColor: 'var(--border)', color: 'var(--text-secondary)' }}>
<p className="text-lg mb-2">No libraries configured</p>
<p className="text-sm">Add entries to <code className="font-mono text-xs px-1 py-0.5 rounded" style={{ background: 'var(--surface)' }}>libraries.json</code> to get started.</p>
</div>
) : (
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{libraries.map((lib) => (
<LibraryCard key={lib.id} library={lib} />
))}
</div>
)}
</div>
)
}

View File

@@ -0,0 +1,46 @@
'use client'
import Link from 'next/link'
import type { Library } from '@/types'
const TYPE_LABELS: Record<string, string> = {
games: 'Games',
mixed: 'Mixed Media',
}
const TYPE_ICONS: Record<string, string> = {
games: '🎮',
mixed: '🗂️',
}
export default function LibraryCard({ library }: { library: Library }) {
return (
<Link
href={`/library/${library.id}`}
className="group block rounded-xl border p-5 transition-colors"
style={{
borderColor: 'var(--border)',
backgroundColor: 'var(--surface)',
}}
onMouseEnter={(e) => {
(e.currentTarget as HTMLElement).style.backgroundColor = 'var(--surface-hover)'
;(e.currentTarget as HTMLElement).style.borderColor = 'var(--accent)'
}}
onMouseLeave={(e) => {
(e.currentTarget as HTMLElement).style.backgroundColor = 'var(--surface)'
;(e.currentTarget as HTMLElement).style.borderColor = 'var(--border)'
}}
>
<div className="text-3xl mb-3">{TYPE_ICONS[library.type] ?? '📁'}</div>
<div className="font-semibold text-base mb-1" style={{ color: 'var(--text-primary)' }}>
{library.name}
</div>
<div
className="text-xs font-medium px-2 py-0.5 rounded-full inline-block"
style={{ backgroundColor: 'var(--border)', color: 'var(--text-secondary)' }}
>
{TYPE_LABELS[library.type] ?? library.type}
</div>
</Link>
)
}

View File

@@ -0,0 +1,97 @@
'use client'
import { useEffect, useRef } from 'react'
import type { Game } from '@/types'
interface Props {
game: Game
libraryId: string
onClose: () => void
}
export default function GameDetailModal({ game, libraryId, onClose }: Props) {
const overlayRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const handleKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
}
document.addEventListener('keydown', handleKey)
document.body.style.overflow = 'hidden'
return () => {
document.removeEventListener('keydown', handleKey)
document.body.style.overflow = ''
}
}, [onClose])
const handleOverlayClick = (e: React.MouseEvent) => {
if (e.target === overlayRef.current) onClose()
}
const downloadHref = `/api/file?libraryId=${encodeURIComponent(libraryId)}&path=${encodeURIComponent(game.zipPath)}`
return (
<div
ref={overlayRef}
className="fixed inset-0 z-50 flex items-center justify-center p-4"
style={{ backgroundColor: 'rgba(0,0,0,0.75)' }}
onClick={handleOverlayClick}
>
<div
className="relative w-full max-w-lg rounded-2xl overflow-hidden shadow-2xl"
style={{ backgroundColor: 'var(--surface)', border: '1px solid var(--border)' }}
>
{/* Close button */}
<button
onClick={onClose}
className="absolute top-3 right-3 z-10 w-8 h-8 rounded-full flex items-center justify-center text-sm transition-colors"
style={{ backgroundColor: 'rgba(0,0,0,0.5)', color: 'var(--text-primary)' }}
onMouseEnter={(e) => ((e.currentTarget as HTMLElement).style.backgroundColor = 'rgba(0,0,0,0.8)')}
onMouseLeave={(e) => ((e.currentTarget as HTMLElement).style.backgroundColor = 'rgba(0,0,0,0.5)')}
aria-label="Close"
>
</button>
{/* Wide cover / cover hero */}
<div className="w-full" style={{ backgroundColor: 'var(--border)' }}>
{game.wideCoverUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={game.wideCoverUrl}
alt={`${game.title} wide cover`}
className="w-full object-cover max-h-64"
/>
) : game.coverUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={game.coverUrl}
alt={`${game.title} cover`}
className="w-full object-contain max-h-64"
/>
) : (
<div className="h-40 flex items-center justify-center text-5xl">🎮</div>
)}
</div>
{/* Info */}
<div className="p-5">
<h2 className="text-lg font-semibold mb-4" style={{ color: 'var(--text-primary)' }}>
{game.title}
</h2>
<a
href={downloadHref}
download
className="flex items-center justify-center gap-2 w-full px-4 py-2.5 rounded-lg font-medium text-sm transition-colors"
style={{ backgroundColor: 'var(--accent)', color: '#fff' }}
onMouseEnter={(e) => ((e.currentTarget as HTMLElement).style.backgroundColor = 'var(--accent-hover)')}
onMouseLeave={(e) => ((e.currentTarget as HTMLElement).style.backgroundColor = 'var(--accent)')}
>
<span></span>
Download .zip
</a>
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,119 @@
'use client'
import { useEffect, useState } from 'react'
import type { Game } from '@/types'
import GameDetailModal from './GameDetailModal'
interface Props {
libraryId: string
}
export default function GamesView({ libraryId }: Props) {
const [games, setGames] = useState<Game[]>([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [selected, setSelected] = useState<Game | null>(null)
useEffect(() => {
fetch(`/api/games?libraryId=${encodeURIComponent(libraryId)}`)
.then((r) => r.json())
.then((data) => {
setGames(data)
setLoading(false)
})
.catch(() => {
setError('Failed to load games')
setLoading(false)
})
}, [libraryId])
if (loading) return <LoadingGrid />
if (error) return <ErrorMessage message={error} />
if (games.length === 0) return <EmptyState />
return (
<>
<div className="grid gap-4 grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
{games.map((game) => (
<button
key={game.id}
onClick={() => setSelected(game)}
className="group text-left rounded-xl overflow-hidden border transition-all focus:outline-none focus-visible:ring-2"
style={{
borderColor: 'var(--border)',
backgroundColor: 'var(--surface)',
}}
onMouseEnter={(e) => {
;(e.currentTarget as HTMLElement).style.borderColor = 'var(--accent)'
;(e.currentTarget as HTMLElement).style.transform = 'translateY(-2px)'
}}
onMouseLeave={(e) => {
;(e.currentTarget as HTMLElement).style.borderColor = 'var(--border)'
;(e.currentTarget as HTMLElement).style.transform = 'translateY(0)'
}}
>
<div className="aspect-[3/4] w-full relative overflow-hidden" style={{ backgroundColor: 'var(--border)' }}>
{game.coverUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={game.coverUrl}
alt={game.title}
className="absolute inset-0 w-full h-full object-cover"
/>
) : (
<div className="absolute inset-0 flex items-center justify-center text-4xl">
🎮
</div>
)}
</div>
<div className="p-2">
<p
className="text-xs font-medium truncate leading-tight"
style={{ color: 'var(--text-primary)' }}
title={game.title}
>
{game.title}
</p>
</div>
</button>
))}
</div>
{selected && (
<GameDetailModal game={selected} libraryId={libraryId} onClose={() => setSelected(null)} />
)}
</>
)
}
function LoadingGrid() {
return (
<div className="grid gap-4 grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
{Array.from({ length: 12 }).map((_, i) => (
<div key={i} className="rounded-xl overflow-hidden" style={{ backgroundColor: 'var(--surface)' }}>
<div className="aspect-[3/4] w-full animate-pulse" style={{ backgroundColor: 'var(--border)' }} />
<div className="p-2">
<div className="h-3 rounded animate-pulse" style={{ backgroundColor: 'var(--border)', width: '70%' }} />
</div>
</div>
))}
</div>
)
}
function ErrorMessage({ message }: { message: string }) {
return (
<div className="rounded-lg border p-8 text-center" style={{ borderColor: 'var(--border)', color: 'var(--text-secondary)' }}>
{message}
</div>
)
}
function EmptyState() {
return (
<div className="rounded-lg border p-12 text-center" style={{ borderColor: 'var(--border)', color: 'var(--text-secondary)' }}>
<p className="text-lg mb-1">No games found</p>
<p className="text-sm">Each game should be a folder containing a .zip file.</p>
</div>
)
}

View File

@@ -0,0 +1,64 @@
'use client'
import { useEffect, useRef } from 'react'
interface Props {
url: string
name: string
onClose: () => void
}
export default function ImageLightbox({ url, name, onClose }: Props) {
const overlayRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const handleKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
}
document.addEventListener('keydown', handleKey)
document.body.style.overflow = 'hidden'
return () => {
document.removeEventListener('keydown', handleKey)
document.body.style.overflow = ''
}
}, [onClose])
const handleOverlayClick = (e: React.MouseEvent) => {
if (e.target === overlayRef.current) onClose()
}
return (
<div
ref={overlayRef}
className="fixed inset-0 z-50 flex flex-col items-center justify-center p-4 gap-3"
style={{ backgroundColor: 'rgba(0,0,0,0.9)' }}
onClick={handleOverlayClick}
>
{/* Toolbar */}
<div className="flex items-center justify-between w-full max-w-4xl">
<span className="text-sm truncate max-w-[80%]" style={{ color: 'var(--text-secondary)' }}>
{name}
</span>
<button
onClick={onClose}
className="w-8 h-8 rounded-full flex items-center justify-center text-sm flex-shrink-0 transition-colors"
style={{ backgroundColor: 'var(--surface)', color: 'var(--text-primary)' }}
onMouseEnter={(e) => ((e.currentTarget as HTMLElement).style.backgroundColor = 'var(--surface-hover)')}
onMouseLeave={(e) => ((e.currentTarget as HTMLElement).style.backgroundColor = 'var(--surface)')}
aria-label="Close"
>
</button>
</div>
{/* Image */}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={url}
alt={name}
className="max-w-full max-h-[80vh] object-contain rounded-lg"
onClick={(e) => e.stopPropagation()}
/>
</div>
)
}

View File

@@ -0,0 +1,210 @@
'use client'
import { useEffect, useState, useCallback } from 'react'
import type { DirectoryListing, FileEntry } from '@/types'
import VideoPlayerModal from './VideoPlayerModal'
import ImageLightbox from './ImageLightbox'
interface Props {
libraryId: string
initialPath: string
}
type ModalState =
| { type: 'video'; url: string; name: string }
| { type: 'image'; url: string; name: string }
| null
export default function MixedView({ libraryId, initialPath }: Props) {
const [currentPath, setCurrentPath] = useState(initialPath)
const [listing, setListing] = useState<DirectoryListing | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [modal, setModal] = useState<ModalState>(null)
const loadPath = useCallback(
(path: string) => {
setLoading(true)
setError(null)
fetch(
`/api/browse?libraryId=${encodeURIComponent(libraryId)}&path=${encodeURIComponent(path)}`
)
.then((r) => r.json())
.then((data: DirectoryListing) => {
setListing(data)
setCurrentPath(path)
setLoading(false)
})
.catch(() => {
setError('Failed to load directory')
setLoading(false)
})
},
[libraryId]
)
useEffect(() => {
loadPath(initialPath)
}, [loadPath, initialPath])
const handleEntry = (entry: FileEntry) => {
if (entry.type === 'directory') {
const newPath = currentPath ? `${currentPath}/${entry.name}` : entry.name
loadPath(newPath)
return
}
if (!entry.url) return
if (entry.mediaType === 'video') {
setModal({ type: 'video', url: entry.url, name: entry.name })
} else if (entry.mediaType === 'image') {
setModal({ type: 'image', url: entry.url, name: entry.name })
} else {
// Download other file types
window.open(entry.url, '_blank')
}
}
const navigateUp = () => {
const parts = currentPath.split('/').filter(Boolean)
parts.pop()
loadPath(parts.join('/'))
}
// Build breadcrumb segments
const breadcrumbs = currentPath
? currentPath.split('/').filter(Boolean)
: []
return (
<>
{/* Breadcrumb */}
<nav className="flex items-center gap-1 mb-6 flex-wrap text-sm">
<button
onClick={() => loadPath('')}
className="transition-colors"
style={{ color: breadcrumbs.length === 0 ? 'var(--text-primary)' : 'var(--text-secondary)' }}
>
Root
</button>
{breadcrumbs.map((segment, i) => {
const isLast = i === breadcrumbs.length - 1
const pathTo = breadcrumbs.slice(0, i + 1).join('/')
return (
<span key={i} className="flex items-center gap-1">
<span style={{ color: 'var(--border)' }}>/</span>
<button
onClick={() => !isLast && loadPath(pathTo)}
className="transition-colors"
style={{
color: isLast ? 'var(--text-primary)' : 'var(--text-secondary)',
cursor: isLast ? 'default' : 'pointer',
}}
>
{segment}
</button>
</span>
)
})}
</nav>
{loading && <LoadingSkeleton />}
{error && (
<div className="rounded-lg border p-8 text-center" style={{ borderColor: 'var(--border)', color: 'var(--text-secondary)' }}>
{error}
</div>
)}
{!loading && !error && listing && (
<>
{listing.entries.length === 0 ? (
<div className="rounded-lg border p-12 text-center" style={{ borderColor: 'var(--border)', color: 'var(--text-secondary)' }}>
This folder is empty.
</div>
) : (
<div className="grid gap-2 grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
{/* Up button */}
{breadcrumbs.length > 0 && (
<button
onClick={navigateUp}
className="flex flex-col items-center justify-center gap-2 rounded-xl border p-4 text-xs transition-colors aspect-square"
style={{ borderColor: 'var(--border)', backgroundColor: 'var(--surface)', color: 'var(--text-secondary)' }}
onMouseEnter={(e) => ((e.currentTarget as HTMLElement).style.backgroundColor = 'var(--surface-hover)')}
onMouseLeave={(e) => ((e.currentTarget as HTMLElement).style.backgroundColor = 'var(--surface)')}
>
<span className="text-2xl"></span>
<span>Up</span>
</button>
)}
{listing.entries.map((entry) => (
<EntryTile key={entry.name} entry={entry} onOpen={handleEntry} />
))}
</div>
)}
</>
)}
{modal?.type === 'video' && (
<VideoPlayerModal url={modal.url} name={modal.name} onClose={() => setModal(null)} />
)}
{modal?.type === 'image' && (
<ImageLightbox url={modal.url} name={modal.name} onClose={() => setModal(null)} />
)}
</>
)
}
function EntryTile({ entry, onOpen }: { entry: FileEntry; onOpen: (e: FileEntry) => void }) {
const icon = entry.type === 'directory'
? '📁'
: entry.mediaType === 'video'
? '▶'
: entry.mediaType === 'image'
? '🖼'
: '📄'
const isVideo = entry.type === 'file' && entry.mediaType === 'video'
return (
<button
onClick={() => onOpen(entry)}
className="group flex flex-col items-center gap-2 rounded-xl border p-3 text-xs transition-all text-center overflow-hidden"
style={{ borderColor: 'var(--border)', backgroundColor: 'var(--surface)' }}
onMouseEnter={(e) => {
;(e.currentTarget as HTMLElement).style.backgroundColor = 'var(--surface-hover)'
;(e.currentTarget as HTMLElement).style.borderColor = 'var(--accent)'
}}
onMouseLeave={(e) => {
;(e.currentTarget as HTMLElement).style.backgroundColor = 'var(--surface)'
;(e.currentTarget as HTMLElement).style.borderColor = 'var(--border)'
}}
>
<span
className="text-3xl"
style={isVideo ? { color: 'var(--accent)' } : undefined}
>
{icon}
</span>
<span
className="w-full truncate text-center"
style={{ color: 'var(--text-primary)' }}
title={entry.name}
>
{entry.name}
</span>
</button>
)
}
function LoadingSkeleton() {
return (
<div className="grid gap-2 grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
{Array.from({ length: 12 }).map((_, i) => (
<div
key={i}
className="rounded-xl aspect-square animate-pulse"
style={{ backgroundColor: 'var(--surface)' }}
/>
))}
</div>
)
}

View File

@@ -0,0 +1,65 @@
'use client'
import { useEffect, useRef } from 'react'
interface Props {
url: string
name: string
onClose: () => void
}
export default function VideoPlayerModal({ url, name, onClose }: Props) {
const overlayRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const handleKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
}
document.addEventListener('keydown', handleKey)
document.body.style.overflow = 'hidden'
return () => {
document.removeEventListener('keydown', handleKey)
document.body.style.overflow = ''
}
}, [onClose])
const handleOverlayClick = (e: React.MouseEvent) => {
if (e.target === overlayRef.current) onClose()
}
return (
<div
ref={overlayRef}
className="fixed inset-0 z-50 flex flex-col items-center justify-center p-4 gap-3"
style={{ backgroundColor: 'rgba(0,0,0,0.9)' }}
onClick={handleOverlayClick}
>
{/* Toolbar */}
<div className="flex items-center justify-between w-full max-w-4xl">
<span className="text-sm truncate max-w-[80%]" style={{ color: 'var(--text-secondary)' }}>
{name}
</span>
<button
onClick={onClose}
className="w-8 h-8 rounded-full flex items-center justify-center text-sm flex-shrink-0 transition-colors"
style={{ backgroundColor: 'var(--surface)', color: 'var(--text-primary)' }}
onMouseEnter={(e) => ((e.currentTarget as HTMLElement).style.backgroundColor = 'var(--surface-hover)')}
onMouseLeave={(e) => ((e.currentTarget as HTMLElement).style.backgroundColor = 'var(--surface)')}
aria-label="Close"
>
</button>
</div>
{/* Video */}
<video
src={url}
controls
autoPlay
className="w-full max-w-4xl max-h-[80vh] rounded-lg"
style={{ backgroundColor: '#000' }}
onClick={(e) => e.stopPropagation()}
/>
</div>
)
}

67
src/lib/files.ts Normal file
View File

@@ -0,0 +1,67 @@
import fs from 'fs'
import path from 'path'
import type { DirectoryListing, FileEntry, MediaType } from '@/types'
const HIDDEN_FILES = /^\./
const VIDEO_EXTENSIONS = new Set(['.mp4', '.mov', '.mkv', '.avi', '.webm', '.m4v'])
const IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.tiff', '.tif'])
function getMediaType(filename: string): MediaType {
const ext = path.extname(filename).toLowerCase()
if (VIDEO_EXTENSIONS.has(ext)) return 'video'
if (IMAGE_EXTENSIONS.has(ext)) return 'image'
return 'other'
}
function fileApiUrl(libraryId: string, relativePath: string): string {
return `/api/file?libraryId=${encodeURIComponent(libraryId)}&path=${encodeURIComponent(relativePath)}`
}
export function scanDirectory(
libraryRoot: string,
libraryId: string,
subpath: string
): DirectoryListing {
const absPath = subpath
? path.resolve(libraryRoot, subpath)
: libraryRoot
let dirents: fs.Dirent[]
try {
dirents = fs.readdirSync(absPath, { withFileTypes: true })
} catch {
return { path: subpath, entries: [] }
}
const entries: FileEntry[] = dirents
.filter((d) => !HIDDEN_FILES.test(d.name))
.map((d): FileEntry => {
if (d.isDirectory()) {
return {
name: d.name,
type: 'directory',
mediaType: null,
url: null,
}
}
const relPath = subpath ? path.join(subpath, d.name) : d.name
const mediaType = getMediaType(d.name)
return {
name: d.name,
type: 'file',
mediaType,
url: fileApiUrl(libraryId, relPath),
}
})
// Sort: directories first, then files; each group sorted alphabetically
entries.sort((a, b) => {
if (a.type !== b.type) return a.type === 'directory' ? -1 : 1
return a.name.localeCompare(b.name)
})
return { path: subpath, entries }
}

77
src/lib/games.ts Normal file
View File

@@ -0,0 +1,77 @@
import fs from 'fs'
import path from 'path'
import type { Game } from '@/types'
const HIDDEN_FILES = /^\./
/**
* Finds the first file in a directory whose basename (without extension)
* matches the given pattern (case-insensitive).
*/
function findFile(dir: string, pattern: RegExp): string | null {
let entries: string[]
try {
entries = fs.readdirSync(dir)
} catch {
return null
}
const match = entries.find(
(entry) => !HIDDEN_FILES.test(entry) && pattern.test(path.basename(entry, path.extname(entry)))
)
return match ?? null
}
function fileApiUrl(libraryId: string, relativePath: string): string {
return `/api/file?libraryId=${encodeURIComponent(libraryId)}&path=${encodeURIComponent(relativePath)}`
}
export function scanGamesLibrary(libraryRoot: string, libraryId: string): Game[] {
let gameDirs: string[]
try {
gameDirs = fs
.readdirSync(libraryRoot, { withFileTypes: true })
.filter((d) => d.isDirectory() && !HIDDEN_FILES.test(d.name))
.map((d) => d.name)
} catch {
return []
}
const games: Game[] = []
for (const dirName of gameDirs) {
const gamePath = path.join(libraryRoot, dirName)
// Find the .zip file (first match)
let zipFile: string | null = null
try {
const allFiles = fs.readdirSync(gamePath)
zipFile = allFiles.find((f) => f.toLowerCase().endsWith('.zip')) ?? null
} catch {
// skip unreadable dirs
continue
}
if (!zipFile) continue
// Case-insensitive cover matching
const coverFile = findFile(gamePath, /^cover$/i)
const wideCoverFile = findFile(gamePath, /^widecover$/i)
const id = encodeURIComponent(dirName)
const zipRelPath = path.join(dirName, zipFile)
games.push({
id,
title: dirName,
coverUrl: coverFile
? fileApiUrl(libraryId, path.join(dirName, coverFile))
: null,
wideCoverUrl: wideCoverFile
? fileApiUrl(libraryId, path.join(dirName, wideCoverFile))
: null,
zipPath: zipRelPath,
})
}
return games.sort((a, b) => a.title.localeCompare(b.title))
}

38
src/lib/libraries.ts Normal file
View File

@@ -0,0 +1,38 @@
import path from 'path'
import fs from 'fs'
import type { Library } from '@/types'
const CONFIG_PATH = path.resolve(process.cwd(), 'libraries.json')
export function getLibraries(): Library[] {
const raw = fs.readFileSync(CONFIG_PATH, 'utf-8')
return JSON.parse(raw) as Library[]
}
export function getLibrary(id: string): Library | undefined {
return getLibraries().find((lib) => lib.id === id)
}
/**
* Resolves a library's configured path to an absolute filesystem path.
* Paths in libraries.json may be relative (to project root) or absolute.
*/
export function resolveLibraryRoot(library: Library): string {
if (path.isAbsolute(library.path)) {
return library.path
}
return path.resolve(process.cwd(), library.path)
}
/**
* Resolves a relative subpath within a library root and verifies it doesn't
* escape the root (prevents path traversal attacks).
* Returns the absolute path, or throws if the path escapes the root.
*/
export function resolveAndJail(libraryRoot: string, subpath: string): string {
const resolved = path.resolve(libraryRoot, subpath)
if (!resolved.startsWith(libraryRoot + path.sep) && resolved !== libraryRoot) {
throw new Error(`Path traversal attempt detected: ${subpath}`)
}
return resolved
}

30
src/types/index.ts Normal file
View File

@@ -0,0 +1,30 @@
export type LibraryType = 'games' | 'mixed'
export interface Library {
id: string
name: string
path: string
type: LibraryType
}
export interface Game {
id: string
title: string
coverUrl: string | null
wideCoverUrl: string | null
zipPath: string
}
export type MediaType = 'video' | 'image' | 'other'
export interface FileEntry {
name: string
type: 'file' | 'directory'
mediaType: MediaType | null
url: string | null
}
export interface DirectoryListing {
path: string
entries: FileEntry[]
}

40
tsconfig.json Normal file
View File

@@ -0,0 +1,40 @@
{
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./src/*"
]
},
"target": "ES2017"
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}