Skip to content

SeveToo/audiobook-face

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

82 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🎧 AudiobookFace

AudiobookFace is a modern platform for managing and listening to your personal audiobook library. The application is designed with high code quality, performance, and support for software engineering best practices in mind.


πŸ“½οΈ Application Preview

Tip

Below you will find screenshots showcasing the key features of the application.

🏠 User Library

Library - Screenshot Manage your collection, browse recently added items, and track your progress.

πŸ”Š Premium Player

Player - Screenshot A fully responsive player with keyboard shortcut support and progress saving.


✨ Key Features

  • πŸ” Full Authentication: Login and registration system powered by Auth.js (NextAuth v5 beta).
  • πŸ“š Library Management: Dynamic data fetching from PostgreSQL database using Drizzle ORM with optimized status filtering.
  • ⚑ Audio Player: Advanced player with volume control, seeking, and accessibility support.
  • ⌨️ Keyboard Shortcuts: Intuitive control (Space - Play/Pause, Arrows - Seeking).
  • ☁️ Cloud Synchronization: Your progress is saved in real-time. Start listening on your computer, finish on your phone.
  • πŸ” SEO & Metadata: Dynamic meta-tag generation for each book for search engine optimization.
  • 🚦 Usage Limits: Smart constraints to prevent abuse (Max 3 accounts per IP, Max 3 uploads per day).

πŸ› οΈ Architecture and Best Practices

The application was written with a focus on "Production-Ready" quality. Here are the patterns used to make the code stable and easy to maintain:

1. Reference Stabilization (React Optimization)

All key functions of the useAudioPlayer hook are wrapped in useCallback. This avoids unnecessary re-renders and effect triggers (e.g., key listeners), which is a common mistake in less advanced applications.

2. Component Composition (Clean Code)

Pages (e.g., app/library/page.tsx) play a declarative role. All UI logic has been moved to small, specialized components (Navbar, BookCard, EmptyLibrary, HeroSection), which dramatically simplifies testing and expansion.

3. Type and Environment Safety (Zod Validation)

We introduced lib/env.ts, which validates environment variables (DATABASE_URL, NEXT_PUBLIC_AUDIO_HOST) using Zod. The application will fail the build process if the configuration is incomplete, preventing production errors.

4. Accessibility (a11y)

Every interactive element, including native input[type="range"] sliders and icon buttons, has correct aria-label attributes. The application is screen-reader friendly.

5. Type-Safe Database (Drizzle ORM)

Instead of raw SQL queries, we use Drizzle ORM with full relationship support. This ensures type safety at both the database and application levels.

6. Synchronization and Debouncing (Performance)

Playback progress is synchronized with the database using Debouncing (use-debounce library). Database updates occur every 5-15 seconds and when the component unmounts, minimizing server load. Additionally, the system uses localStorage as an immediate buffer, ensuring zero delay upon page refresh.

7. Brute Force Protection (Rate Limiting)

Authentication processes (login/registration) are protected by a Rate Limiter based on Upstash Redis. The system blocks suspicious attempts (e.g., more than 5 failed logins in 15 minutes) at the IP and account level, protecting users from attacks.

8. Server-First Logic (Server Actions)

In this application, we swapped traditional API Routes (REST/JSON) for Next.js Server Actions. This moves all data mutation logic (authentication, progress updates) directly to the server with full TypeScript type support, reducing client-side code and increasing security.

9. Modern Styling Stack (Tailwind CSS 4.0)

The project uses the latest Tailwind CSS 4.0, which introduces an engine optimized for build performance and native CSS variable support. Styling is based on a consistent color palette and modern "glassmorphism," giving the application a "Premium" feel.

10. Memory-Efficient Streaming & Security

The system is optimized for handling large files (up to 1GB+) without RAM exhaustion. Instead of loading the entire file into memory, we use Node.js Streams (pipeline). Magic Bytes validation is performed on a small 16-byte slice of the file before streaming the rest to disk. This ensures high stability even under heavy concurrent load (OOM protection), while maintaining Magic Bytes security validation.

11. Multi-Level CRUD & Admin Visibility

The application implements an advanced permission system:

  • Creator: Can manage (edit/delete) their own uploaded audiobooks. Deletion by a creator acts as a "Soft Delete" from the public view.
  • Admin: Has full visibility of all system resources and the ability to physically delete files from the server.
  • Improved Visibility: The "In Progress" view correctly handles restarted books (from 0:00). Progress bars act as the primary visual indicator, appearing even if a book was previously marked as "Completed" but was later replayed.
  • Minimalist Library: The "My Library" view has been optimized for clarity, focusing exclusively on the user's progress.

12. Genre Management

Implemented a robust many-to-many relationship using a join table. Audiobooks can be categorized into multiple genres (Fantasy, Thriller, Personal Development, etc.) via a user-friendly, Facebook-style tag selection interface with autocomplete and chip management.

13. Advanced Search

The library features a dynamic search system powered by efficient SQL EXISTS queries. Users can search by:

  • Book Title
  • Author Name
  • Narrator Name
  • Category/Genre

14. Security & Robustness Patched

The application includes several security and reliability patches:

  • IDOR Protection: Direct Object Reference protection in app/audiobooki/[id]/page.tsx ensures that private audiobooks are only accessible by their owners or administrators.
  • Rate Limit Hardening: Enhanced protection against IP Spoofing (via x-real-ip and x-forwarded-for parsing) and standardized registration rate-limiting (IP-based instead of email-based) to prevent brute-force attacks and registration spam.
  • Atomic Operations (Transactional Integrity): When adding audiobooks, the system follows an atomic pattern: save the file first, then the database record. If the database transaction fails, a rollback mechanism automatically removes the orphaned file from storage.
  • Anti-Abuse Constraints:
    • Registration Limit: Max 3 user accounts per unique IP address to prevent mass registration.
    • Upload Quota: Standard users are limited to 3 audiobook uploads per 24-hour period (does not apply to administrators).
  • Large File Config: Added support for 1GB+ uploads via next.config.ts and middlewareClientMaxBodySize to circumvent default Next.js and server-level body size restrictions.
  • Safe JSON Handling: genreIds are safely parsed and transformed via Zod schemas, preventing Server Action crashes from malformed JSON payloads.
  • Secure File Storage: Local storage paths (for Windows/Development) have been moved out of the public/ directory to prevent unauthorized direct access via URL, routing all audio traffic through protected endpoints.
  • Schema Consistency: Unified Drizzle schema exports and fixed role-based synchronization to ensure a robust foundation for permissions.

15. Global Persistent Player (State Management)

The application implements a persistent audio player that continues playing smoothly across page navigations:

  • Zustand Global Store: A central player-store.ts manages the active audiobook, playback status, and a shared audioRef.
  • Persistent Media Element: The <audio> tag is rendered once in the RootLayout within the MiniPlayer component. This prevents the audio context from being destroyed during Next.js route transitions.
  • Ref Sharing Pattern: The physical DOM element's reference is shared via setAudioRef. This allow multiple independent UI components (the bottom MiniPlayer and the full-page AudioPlayer) to control the same audio instance without conflicts.
  • Event Proxying: Crucial event listeners (play, pause, timeupdate) are attached once in the RootLayout level. This ensures the global store remains the "Source of Truth" even when specific page-level control hooks are unmounted.
  • Auto-Sync: The system automatically restores the last played book and position from localStorage upon initialization, providing a seamless "Continue Listening" experience.

16. Administrative Management & Audit Logging

The application features a comprehensive, role-restricted administrative dashboard:

  • Unified DataTable: All management tables (Audiobooks, Users, Audit Logs) are built on a standardized @tanstack/react-table foundation for high performance.
  • Advanced Sorting & Filtering: Every data column is sortable and filterable. Administrators can instantly organize 10, 20, or 50 records per page.
  • Audit Logging & Delta Tracking: A persistent audit_logs system tracks all metadata modifications. It stores "old" and "new" states, allowing for detailed accountability.
  • Instant "Undo": Authorized moderators can revert metadata changes (titles, authors, genres) directly from the log dashboard with a single click.
  • Role Switching: Admins can dynamically update user permissions (Listener, VIP, Moderator, Admin) via a theme-consistent, type-safe select interface.
  • High-Contrast Admin UI: Dedicated management views feature enhanced contrast (zinc-300/200) and role-based color-coded iconography for optimal administrative efficiency.

πŸš€ Technology

  • Framework: Next.js 16 (App Router)
  • State Management: Zustand
  • Styling: Tailwind CSS 4.0
  • Database: PostgreSQL + Drizzle ORM
  • Auth: Auth.js (NextAuth v5 beta)
  • Validation: Zod
  • Rate Limiting: Upstash Redis
  • UI Components: Radix UI / Shadcn

πŸ—οΈ Local Setup

  1. Clone the repository.
  2. Install dependencies: npm install.
  3. Configure the .env file (refer to .env.example).
  4. Start the development server: npm run dev.

About

Fullstack audiobook platform with streaming, RBAC, rate limiting (Upstash Redis), audit logs & persistent global player. Next.js 15, PostgreSQL, Drizzle ORM.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors