Backend: Added docs & AGENTS.md

This commit is contained in:
Mohammed Abad committed 2026-03-30 19:37:08 +01:00
1 parent b3f2097b8b
commit b3ab69cc22
8 files changed
+3082

No files matched your search

+150
View File
@@ -0,0 +1,150 @@
# Agents & Autonomous Logic
> **Last reviewed:** 2026-03-30
---
## Overview
The Showy backend does **not** incorporate any AI models, LLM integrations, or agentic frameworks (e.g., LangChain, OpenAI function-calling, autonomous planners). There are no prompt-driven decision loops, tool-use chains, or inference endpoints.
However, the system does implement several **autonomous orchestration services** — referred to internally as **"Managers"** — that coordinate multi-step workflows without user intervention after the initial trigger. These managers behave similarly to agents in that they:
- Make decisions based on data state (e.g., "is this person fully fetched?")
- Orchestrate side effects across multiple services (TMDB API, DB, filesystem)
- Perform lazy evaluation and deferred work on first access
---
## Manager Services (Agent-like Orchestrators)
### 1. `EntryManager`
**File:** `services/entryManager.js`
**Singleton:** Yes
| Capability | Description |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `fetchAndSaveNewEntry(tmdbId, isTvSeries)` | Fetches entry from TMDB → persists entry + IDs + ratings + genres → fetches seasons & episodes (if TV) → downloads & generates media previews → fetches & links collection |
| `refrechEntryById(id)` | Compares local data with TMDB → selectively updates title, dates, status, ratings, genres, networks → iterates seasons/episodes to upsert new ones → fetches credits & creates People/Credit records |
| `SyncSeriesData()` | Batch refresh of all TV series entries |
| `getUpdatedEntry(id)` | Lazy trigger: returns entry and refreshes if stale |
**Orchestration flow for `fetchAndSaveNewEntry`:**
```
Client POST /entries { tmdb_id, is_tvserie }
│
├─ 1. tmdbService.fetchEntryData() → TMDB API call
├─ 2. entryService.createEntry() → DB insert (entry + entryId + entryRating + genres)
├─ 3. collectionManager.fetchAndSaveCollection() → if movie belongs to a collection
├─ 4. mediaManager.getEntryMedia() → downloads posters/backdrops/logos
├─ 5. mediaOptimizerService.doGeneratePreview() → generates low-res previews
└─ 6. (for TV) loops seasons → episodes → downloads season/episode media
```
---
### 2. `CollectionManager`
**File:** `services/collectionManager.js`
**Singleton:** Yes
| Capability | Description |
| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `fetchAndSaveCollection(tmdbId)` | Fetches collection from TMDB → creates/updates collection record → links existing library entries as parts → downloads & generates media previews |
| `fetchCollectionByEntryId(entryId)` | Resolves an entry's parent collection from TMDB if not yet stored locally |
| `getCollectionParts(collectionId)` | Fetches missing parts (entries) that belong to the collection but are not in the local library → auto-imports them |
**Decision logic in `getCollectionParts`:**
```
For each TMDB collection part:
├─ Part already in library? → link to collection (skip fetch)
└─ Part NOT in library? → entryManager.fetchAndSaveNewEntry() → link
```
---
### 3. `PeopleManager`
**File:** `services/peopleManager.js`
**Singleton:** Yes
| Capability | Description |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `getUpdatedPerson(id)` | Lazy-fetch pattern: if `fully_fetched` is false, fetches detailed person data from TMDB → updates DB → downloads profile images → generates previews |
**Decision logic:**
```
GET /people/:id
│
├─ person.fully_fetched == true? → return cached data
└─ person.fully_fetched == false?
├─ tmdbService.fetchPersonDetails()
├─ peopleService.updatePerson()
├─ mediaDownloaderService.downloadPersonMedia()
├─ mediaOptimizerService.doGeneratePreview()
└─ return enriched person
```
---
### 4. `MediaManager`
**File:** `services/mediaManager.js`
**Singleton:** Yes
| Capability | Description |
| ----------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `saveMedia(entryId, files)` | Persists uploaded media → triggers async preview generation |
| `getEntryMedia(tmdbId, isTvSeries)` | Fetches available images from TMDB → selects preferred variants → downloads in parallel → stores on disk |
| `getSeasonMedia(season)` | Downloads season poster from TMDB → stores locally |
| `getEpisodenMedia(episode)` | Downloads episode still from TMDB → stores locally |
---
## Supporting Services
These are not autonomous but are invoked by the managers above:
| Service | File | Role |
| ------------------------ | ------------------------------------ | ----------------------------------------------------------------------------------------- |
| `tmdbService` | `services/tmdbService.js` | HTTP client wrapping TMDB API v3 (entries, seasons, credits, people, collections, images) |
| `mediaDownloaderService` | `services/mediaDownloaderService.js` | Downloads remote images to local filesystem |
| `mediaOptimizerService` | `services/mediaOptimizerService.js` | Generates low-resolution preview variants (JPEG/PNG) |
| `configService` | `services/configService.js` | Reads/writes `settings.json`; provides TMDB API credentials and data paths |
| `storageService` | `services/storageService.js` | Low-level file write abstraction |
| `networkService` | `services/networkService.js` | Creates or updates TV network records |
| `importerService` | `services/importerService.js` | Bulk-import orchestration with TMDB rate-limit handling (35 req / 10 s) |
| `maintenanceService` | `services/maintenanceService.js` | Detects and cleans orphan files and DB records |
---
## Importer Rate-Limit Strategy
The `importerService` implements a self-throttling loop to respect TMDB's rate limits:
```
for each item in batch:
fetch from TMDB
wait 500ms
if (fetchCount >= 35):
wait 10 seconds
reset counter
```
This is the closest pattern to an "autonomous agent loop" in the current codebase — it runs unsupervised for potentially long periods, makes sequential decisions, and self-regulates.
---
## Future Considerations
The manager pattern is well-suited for upgrading to a true agentic architecture if needed:
- **Tool registry** — Each service (`tmdbService`, `mediaDownloaderService`, etc.) could be registered as a callable tool.
- **Planner/Orchestrator** — An LLM-backed planner could replace the hardcoded orchestration in managers.
- **Observation loop** — The lazy-fetch pattern (`fully_fetched` checks) already implements observe → decide → act semantics.
No such integration exists today. All decision logic is deterministic and rule-based.
+198
View File
@@ -0,0 +1,198 @@
# Showy Backend — Documentation Hub
> **Version:** 1.0.0 · **Runtime:** Node.js 18+ · **Framework:** Express 4 · **Database:** MySQL 8
---
## What is Showy?
Showy is a self-hosted media library tracker for movies and TV series. The backend is a REST API server that:
- Manages a personal library of movies and TV series
- Fetches metadata, images, and credits from **TMDB API v3**
- Tracks watch history per movie and per episode
- Organises entries into collections (TMDB-sourced or user-created)
- Serves optimised media assets (posters, backdrops, stills) from local storage
- Provides statistics dashboards and calendar feeds
- Runs standalone, inside Docker, or embedded in an Electron desktop app
---
## Architecture at a Glance
```
┌───────────────────────────────────────────────────────────┐
│ Client (Angular / Electron) │
└──────────────────────────┬────────────────────────────────┘
│ HTTP (REST JSON)
▼
┌──────────────────────────────────────────────────────────┐
│ Express Server (:4000) │
│ │
│ ┌─────────┐ ┌────────────┐ ┌────────────────────┐ │
│ │ Routes │──▶│ Controllers│──▶│ Managers │ │
│ └─────────┘ └────────────┘ │ (EntryMgr, CollMgr, │ │
│ │ PeopleMgr, MediaMgr)│ │
│ └─────────┬────────────┘ │
│ │ │
│ ┌──────────────────────┼───────────┐ │
│ ▼ ▼ ▼ │
│ ┌────────────┐ ┌──────────────┐ ┌─────┐ │
│ │ Services │ │ TMDB Service │ │Sharp│ │
│ │ (Entry, │ │ (axios→TMDB) │ │ Opt │ │
│ │ Collection,│ └──────────────┘ └─────┘ │
│ │ People...) │ │
│ └──────┬──────┘ │
│ │ │
│ ▼ │
│ ┌────────────────────┐ │
│ │ Sequelize ORM │ │
│ │ (17 models) │ │
│ └─────────┬──────────┘ │
└───────────────────┼──────────────────────────────────────┘
│
▼
┌────────────────┐ ┌────────────────────┐
│ MySQL 8.0 │ │ Local Filesystem │
│ (Showzy DB) │ │ (images/previews) │
└────────────────┘ └────────────────────┘
```
---
## Quick Start
### Prerequisites
| Tool | Version |
| ------------- | --------------------------------------------------------- |
| Node.js | 18+ |
| MySQL | 8.0 |
| pnpm (or npm) | any |
| TMDB API key | [themoviedb.org](https://www.themoviedb.org/settings/api) |
### 1. Install dependencies
```bash
cd backend
pnpm install
```
### 2. Configure settings
```bash
cp settings.json.example settings.json
```
Edit `settings.json`:
```json
{
"userDataPath": "C:\\Users\\you\\Documents\\Showy Data",
"tmdbApiUrl": "https://api.themoviedb.org/3/",
"tmdbApiKey": "YOUR_KEY_HERE",
"backPort": 4000
}
```
### 3. Start MySQL
Make sure a MySQL 8 instance is running with a database called `Showzy` and user `root` / `password` (or update `config/database.js`).
### 4. Run the server
```bash
# Development (auto-restart on file changes)
pnpm run backend
# Production
node server.js
```
The server will:
1. Connect to MySQL
2. Auto-sync the schema (`ALTER TABLE` if needed)
3. Seed the genres table
4. Start listening on the configured port (default `4000`)
### 5. Verify
```bash
curl http://localhost:4000/api/v1/ping
# → { "message": "pong" }
```
---
## Documentation Index
| Document | Description |
| ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| **[Project Setup & Configuration](project_setup.md)** | Tech stack, directory structure, `settings.json` reference, NPM scripts, startup sequence, Docker config, CORS, logging, Electron integration |
| **[API Reference](api_reference.md)** | All 55+ REST endpoints grouped by resource — HTTP methods, parameter tables, sample responses |
| **[Database Architecture](db_architecture.md)** | Full schema reference (17 tables), ERD, relationship summary, polymorphic media pattern, hooks, seeding, indexing |
| **[Service Layer](service_layer.md)** | Controller → Manager → Service architecture, service catalogue, TMDB API mapping, media pipeline, dependency graph |
| **[Error Handling](error_handling.md)** | Custom error hierarchy, global middleware, response contract, logging integration |
| **[Agents & Orchestrators](../agents.md)** | Manager services (EntryMgr, CollectionMgr, PeopleMgr, MediaMgr), orchestration flows, importer rate-limit strategy |
| **[Deployment Guide](deployment.md)** | Docker, standalone, Electron, and production deployment instructions |
---
## Key Concepts
### Entry
The core entity — represents either a **movie** or **TV series** (discriminated by `is_tvseries`). Everything revolves around entries: ratings, watch history, seasons, credits, collections, and media assets.
### Managers vs. Services
- **Services** handle single-responsibility data access (CRUD, queries).
- **Managers** orchestrate multi-step workflows across services (fetch from TMDB → save → download media → generate previews). They are the primary business logic layer.
### Polymorphic Media
The `media` table stores images for entries, collections, seasons, episodes, and people using a `(mediaable, mediaable_id)` discriminator pattern — no physical FK constraints.
### Lazy Fetching
When a person or entry is accessed for the first time, the corresponding Manager checks whether the data is complete. If not, it transparently fetches missing data from TMDB, downloads media, and returns the enriched object.
### Preview Generation
All downloaded images get a low-resolution preview variant generated via `sharp`. Previews are served when the client requests `size=preview`, reducing bandwidth for grid/list views.
---
## API Quick Reference
| Verb | Endpoint | Description |
| -------- | -------------------------------------- | ------------------- |
| `GET` | `/api/v1/ping` | Health check |
| `GET` | `/api/v1/entries` | List all entries |
| `POST` | `/api/v1/entries` | Add entry from TMDB |
| `GET` | `/api/v1/entries/:id` | Get entry details |
| `PUT` | `/api/v1/entries/:id/refresh` | Refresh from TMDB |
| `DELETE` | `/api/v1/entries/:id` | Delete entry |
| `GET` | `/api/v1/collections` | List collections |
| `POST` | `/api/v1/collections` | Create collection |
| `GET` | `/api/v1/people` | List people |
| `GET` | `/api/v1/seasons/:id/episodes` | Get season episodes |
| `POST` | `/api/v1/entry-seen` | Log a watch |
| `GET` | `/api/v1/statistics/watch-time` | Total watch time |
| `GET` | `/api/v1/media/:cat/:type/:size/:file` | Serve image |
See the full **[API Reference](api_reference.md)** for all endpoints.
---
## Environment Variables
| Variable | Set By | Purpose |
| ---------------- | -------------------- | ------------------------------------------------------------------------------ |
| `PARENT_PROCESS` | Electron (`main.js`) | JSON object with `electron_path`; tells the backend it was spawned by Electron |
| `MYSQL_HOST` | Docker Compose | MySQL hostname (defaults to `localhost` in `config/database.js`) |
| `MYSQL_DB` | Docker Compose | Database name |
| `MYSQL_USER` | Docker Compose | Database user |
| `MYSQL_PASSWORD` | Docker Compose | Database password |
> **Note:** In non-Docker mode, the database connection is hardcoded in `config/database.js`. Environment variables only apply when running via Docker Compose.
File diff suppressed because it is too large. Load diff
+462
View File
@@ -0,0 +1,462 @@
# Database Architecture
> **RDBMS:** MySQL · **ORM:** Sequelize v6 · **Sync strategy:** `sequelize.sync({ alter })` at startup
---
## 1. High-Level Overview
Showy persists a personal media library (movies & TV series) sourced from TMDB.
The schema centres on the **Entry** entity — a movie _or_ TV series — and fans out into ratings, watch-history, seasons/episodes, collections, genres, networks, credits (cast/crew), and polymorphic media assets.
---
## 2. Tables & Column Reference
### 2.1 `entries`
| Column | Type | Constraints | Notes |
| ------------------ | ------------- | ------------------ | -------------------------------------- |
| `id` | INTEGER | PK, AUTO_INCREMENT | |
| `title` | VARCHAR(500) | | Display title |
| `original_title` | VARCHAR(100) | | |
| `release_date` | DATE | | Movie release or series first air date |
| `release_status` | VARCHAR(50) | | e.g. `Released`, `Returning Series` |
| `runtime` | INTEGER | | Minutes (movies only) |
| `tagline` | VARCHAR(200) | | |
| `storyline` | VARCHAR(3000) | | Synopsis / overview |
| `country` | VARCHAR(30) | | Primary production country |
| `certification` | INTEGER | | Age rating |
| `network_studio` | VARCHAR(40) | | Legacy field |
| `collection_id` | INTEGER | | Soft reference to collection |
| `max_cast` | INTEGER | DEFAULT 10 | Max cast members to display |
| `credit_fetched` | BOOLEAN | DEFAULT false | Whether credits have been fetched |
| `watchlist` | BOOLEAN | DEFAULT false | User flag |
| `favorit` | BOOLEAN | DEFAULT false | User flag |
| `hidden` | BOOLEAN | DEFAULT false | User flag |
| `show_in_calendar` | BOOLEAN | DEFAULT true | Calendar visibility |
| `auto_sync` | BOOLEAN | DEFAULT true | Auto-refresh from TMDB |
| `note` | VARCHAR(2000) | | User notes |
| `is_tvseries` | BOOLEAN | | Discriminator: movie vs. TV |
| `status` | VARCHAR(20) | | e.g. `Ended`, `Returning Series` |
| `poster_path` | VARCHAR(200) | | TMDB poster path |
| `banner_path` | VARCHAR(200) | | TMDB backdrop path |
| `date_first_seen` | DATEONLY | | First watch date (computed) |
| `date_last_seen` | DATEONLY | | Last watch date (computed) |
| `last_fetch` | DATEONLY | | Last TMDB sync timestamp |
| `createdAt` | DATETIME | Sequelize-managed | |
| `updatedAt` | DATETIME | Sequelize-managed | |
---
### 2.2 `entryIds`
One-to-one with `entries`. Stores external provider IDs.
| Column | Type | Constraints |
| ---------- | ----------- | ------------------ |
| `id` | INTEGER | PK, AUTO_INCREMENT |
| `entry_id` | INTEGER | FK → `entries.id` |
| `tmdb_id` | VARCHAR(30) | TMDB identifier |
| `imdb_id` | VARCHAR(30) | IMDb identifier |
| `tvdb_id` | VARCHAR(30) | TVDB identifier |
> `timestamps: false`
---
### 2.3 `entryRatings`
One-to-one with `entries`. Aggregated ratings from multiple sources.
| Column | Type | Constraints |
| ------------------------ | ------- | ------------------ |
| `id` | INTEGER | PK, AUTO_INCREMENT |
| `entry_id` | INTEGER | FK → `entries.id` |
| `user_rating` | FLOAT | |
| `tmdb_rating` | FLOAT | |
| `imdb_rating` | FLOAT | |
| `rotten_tomatoes_rating` | FLOAT | |
> `timestamps: false`
---
### 2.4 `entrySeens`
One-to-many from `entries`. Each row = one watch event for a movie/entry.
| Column | Type | Constraints |
| ----------- | ----------- | --------------------- |
| `id` | INTEGER | PK, AUTO_INCREMENT |
| `entry_id` | INTEGER | FK → `entries.id` |
| `date_seen` | DATE | When the user watched |
| `seen_with` | VARCHAR(50) | Companion name |
> `timestamps: false`
---
### 2.5 `seasons`
One-to-many from `entries` (TV series only).
| Column | Type | Constraints |
| --------------- | ------------- | ------------------ |
| `id` | INTEGER | PK, AUTO_INCREMENT |
| `tmdb_id` | VARCHAR(30) | |
| `imdb_id` | VARCHAR(30) | |
| `entry_id` | INTEGER | FK → `entries.id` |
| `name` | VARCHAR(500) | |
| `overview` | VARCHAR(3000) | |
| `season_number` | INTEGER | |
| `episode_count` | INTEGER | |
| `air_date` | DATE | |
| `user_rating` | FLOAT | |
| `tmdb_rating` | FLOAT | |
| `imdb_rating` | FLOAT | |
| `poster_path` | VARCHAR(200) | |
| `banner_path` | VARCHAR(200) | |
---
### 2.6 `episodes`
One-to-many from `seasons`.
| Column | Type | Constraints |
| ----------------- | ------------- | ------------------ |
| `id` | INTEGER | PK, AUTO_INCREMENT |
| `tmdb_id` | VARCHAR(30) | |
| `imdb_id` | VARCHAR(30) | |
| `tvdb_id` | VARCHAR(30) | |
| `season_id` | INTEGER | FK → `seasons.id` |
| `name` | VARCHAR(500) | |
| `overview` | VARCHAR(3000) | |
| `episode_number` | INTEGER | |
| `episode_type` | VARCHAR(60) | |
| `runtime` | INTEGER | Minutes |
| `air_date` | DATE | |
| `user_rating` | FLOAT | |
| `tmdb_rating` | FLOAT | |
| `still_path` | VARCHAR(200) | |
| `date_first_seen` | DATEONLY | |
| `date_last_seen` | DATEONLY | |
---
### 2.7 `episodeSeens`
One-to-many from both `episodes` and `entries`.
| Column | Type | Constraints |
| ------------ | ----------- | ------------------ |
| `id` | INTEGER | PK, AUTO_INCREMENT |
| `entry_id` | INTEGER | FK → `entries.id` |
| `episode_id` | INTEGER | FK → `episodes.id` |
| `date_seen` | DATE | |
| `seen_with` | VARCHAR(50) | |
| `createdAt` | DATETIME | Sequelize-managed |
| `updatedAt` | DATETIME | Sequelize-managed |
---
### 2.8 `userCollections`
| Column | Type | Constraints |
| -------------------- | ------------- | ------------------ |
| `id` | INTEGER | PK, AUTO_INCREMENT |
| `tmdb_id` | VARCHAR(30) | |
| `imdb_id` | VARCHAR(30) | |
| `tvdb_id` | VARCHAR(30) | |
| `name` | VARCHAR(150) | |
| `description` | VARCHAR(3000) | |
| `is_user_collection` | BOOLEAN | DEFAULT false |
| `user_rating` | FLOAT | |
| `poster_path` | VARCHAR(200) | |
| `backdrop_path` | VARCHAR(200) | |
| `is_local` | BOOLEAN | DEFAULT false |
---
### 2.9 `userCollectionEntries` (join table)
Many-to-many pivot between `userCollections` and `entries`.
| Column | Type | Constraints |
| -------------------- | ------- | ----------------------------------------- |
| `user_collection_id` | INTEGER | PK (composite), FK → `userCollections.id` |
| `entry_id` | INTEGER | PK (composite), FK → `entries.id` |
| `order` | INTEGER | Display position |
---
### 2.10 `genres`
| Column | Type | Constraints |
| ------ | ----------- | ---------------------------------------- |
| `id` | INTEGER | PK (TMDB genre ID, not auto-incremented) |
| `name` | VARCHAR(30) | |
> `timestamps: false` — Seeded at startup via `dataInitializer.js`.
---
### 2.11 `entryGenres` (join table)
Many-to-many pivot between `entries` and `genres`.
| Column | Type | Constraints |
| ---------- | ------- | --------------------------------- |
| `genre_id` | INTEGER | PK (composite), FK → `genres.id` |
| `entry_id` | INTEGER | PK (composite), FK → `entries.id` |
---
### 2.12 `networks`
| Column | Type | Constraints |
| ---------------- | ------------ | -------------------- |
| `id` | INTEGER | PK (TMDB network ID) |
| `name` | VARCHAR(30) | |
| `origin_country` | VARCHAR(100) | |
| `homepage` | VARCHAR(100) | |
| `logo_path` | VARCHAR(200) | |
| `poster_path` | VARCHAR(200) | |
| `backdrop_path` | VARCHAR(200) | |
---
### 2.13 `entryNetworks` (join table)
Many-to-many pivot between `entries` and `networks`.
| Column | Type | Constraints |
| ------------ | ------- | ---------------------------------- |
| `network_id` | INTEGER | PK (composite), FK → `networks.id` |
| `entry_id` | INTEGER | PK (composite), FK → `entries.id` |
| `order` | INTEGER | Display position |
---
### 2.14 `peoples`
| Column | Type | Constraints |
| ---------------------- | ------------ | -------------------------- |
| `id` | INTEGER | PK, AUTO_INCREMENT |
| `tmdb_id` | VARCHAR(100) | |
| `name` | VARCHAR(100) | |
| `birthday` | DATEONLY | |
| `deathday` | DATEONLY | NULLABLE |
| `gender` | INTEGER | TMDB gender enum |
| `biography` | TEXT | |
| `place_of_birth` | VARCHAR(100) | |
| `adult` | BOOLEAN | DEFAULT false |
| `popularity` | FLOAT | |
| `known_for_department` | VARCHAR(50) | e.g. `Acting`, `Directing` |
| `homepage` | VARCHAR(200) | NULLABLE |
| `imdb_id` | VARCHAR(20) | |
| `profile_path` | VARCHAR(200) | |
| `last_fetch` | DATEONLY | |
| `profile_update` | DATEONLY | |
| `fully_fetched` | BOOLEAN | DEFAULT false |
---
### 2.15 `credits`
One-to-many from both `entries` and `peoples`.
| Column | Type | Constraints |
| ---------------- | -------------------- | ------------------ |
| `id` | INTEGER | PK, AUTO_INCREMENT |
| `tmdb_credit_id` | VARCHAR(100) | |
| `adult` | BOOLEAN | DEFAULT false |
| `profile_path` | VARCHAR(200) | |
| `character` | VARCHAR(100) | Role name played |
| `order` | INTEGER | Billing order |
| `cast_type` | ENUM(`cast`, `crew`) | DEFAULT `cast` |
| `department` | VARCHAR(100) | Crew department |
| `job` | VARCHAR(100) | Crew job title |
| `entry_id` | INTEGER | FK → `entries.id` |
| `people_id` | INTEGER | FK → `peoples.id` |
---
### 2.16 `franchises`
| Column | Type | Constraints |
| ------------- | ------------ | ------------------ |
| `id` | INTEGER | PK, AUTO_INCREMENT |
| `title` | VARCHAR(50) | |
| `overview` | VARCHAR(300) | |
| `user_rating` | FLOAT | |
> `timestamps: false`
---
### 2.17 `media` (polymorphic)
Polymorphic asset table. The target entity is identified by the `(mediaable, mediaable_id)` tuple.
| Column | Type | Constraints |
| -------------- | ------------ | ------------------------------------------------------------------- |
| `id` | INTEGER | PK, AUTO_INCREMENT |
| `mediaable` | VARCHAR(255) | Discriminator: `entry`, `people`, `collection`, `season`, `episode` |
| `mediaable_id` | INTEGER | ID of the owning entity |
| `type` | VARCHAR(50) | `poster`, `backdrop`, `logo`, `still`, `profile` |
| `path` | VARCHAR(200) | Filename on disk |
| `is_local` | BOOLEAN | True if stored locally |
| `is_selected` | BOOLEAN | DEFAULT false — currently active asset |
| `is_custom` | BOOLEAN | DEFAULT false — user-uploaded |
| `is_favorit` | BOOLEAN | DEFAULT false |
---
## 3. Entity Relationship Diagram
```
┌──────────────────────────────────┐
│ franchises │
│──────────────────────────────────│
│ id (PK) │
│ title, overview, user_rating │
└────────────┬─────────────────────┘
│ 1
│
│ N
┌────────────▼─────────────────────────────────────────────────────┐
│ entries │
│──────────────────────────────────────────────────────────────────│
│ id (PK) │ title │ is_tvseries │ franchise_id (FK) │ ... │
└──┬───┬───┬──────┬────────┬────────┬──────────────────────────────┘
│ │ │ │ │ │
│ │ │ │ │ ├─── 1:1 ──► entryIds
│ │ │ │ │ ├─── 1:1 ──► entryRatings
│ │ │ │ │ │
│ │ │ │ │ ├─── 1:N ──► entrySeens
│ │ │ │ │ ├─── 1:N ──► credits ◄── N:1 ── peoples
│ │ │ │ │ ├─── 1:N ──► episodeSeens
│ │ │ │ │ │
│ │ │ │ │ ├─── M:N ──► genres (via entryGenres)
│ │ │ │ │ ├─── M:N ──► networks (via entryNetworks)
│ │ │ │ │ └─── M:N ──► userCollections (via userCollectionEntries)
│ │ │ │ │
│ │ │ │ │ 1:N
│ │ │ │ ┌─────▼──────────────┐
│ │ │ │ │ seasons │
│ │ │ │ │────────────────────│
│ │ │ │ │ id (PK) │
│ │ │ │ │ entry_id (FK) │
│ │ │ │ └─────┬──────────────┘
│ │ │ │ │ 1:N
│ │ │ │ ┌─────▼──────────────┐
│ │ │ │ │ episodes │
│ │ │ │ │────────────────────│
│ │ │ │ │ id (PK) │
│ │ │ │ │ season_id (FK) │
│ │ │ │ └─────┬──────────────┘
│ │ │ │ │ 1:N
│ │ │ │ ┌─────▼──────────────┐
│ │ │ │ │ episodeSeens │
│ │ │ │ │────────────────────│
│ │ │ │ │ episode_id (FK) │
│ │ │ │ │ entry_id (FK) │
│ │ │ │ └───────────────────-┘
│ │ │ │
│ │ │ │ ┌───────────────────┐
│ │ │ └──────────┤ media (polymorphic)│
│ │ │ │───────────────────│
│ │ │ │ mediaable │
│ │ │ │ mediaable_id │
│ │ │ └───────────────────┘
│ │ │ ▲ ▲ ▲ ▲ ▲
│ │ │ entry ─────┘ │ │ │ └───── episode
│ │ │ people ───────┘ │ └──────── season
│ │ │ collection ──────┘
```
---
## 4. Relationship Summary
| Relationship | Type | FK / Pivot | ON DELETE |
| ----------------------- | ----- | ---------------------------------------- | -------------------- |
| Franchise → Entry | 1 : N | `entries.franchise_id` | — |
| Entry → EntryId | 1 : 1 | `entryIds.entry_id` | CASCADE |
| Entry → EntryRating | 1 : 1 | `entryRatings.entry_id` | CASCADE |
| Entry → EntrySeen | 1 : N | `entrySeens.entry_id` | CASCADE |
| Entry → Season | 1 : N | `seasons.entry_id` | CASCADE |
| Season → Episode | 1 : N | `episodes.season_id` | CASCADE |
| Episode → EpisodeSeen | 1 : N | `episodeSeens.episode_id` | CASCADE |
| Entry → EpisodeSeen | 1 : N | `episodeSeens.entry_id` | CASCADE |
| Entry ↔ Genre | M : N | `entryGenres` | CASCADE |
| Entry ↔ Network | M : N | `entryNetworks` | CASCADE |
| Entry ↔ UserCollection | M : N | `userCollectionEntries` | CASCADE |
| Entry → Credit | 1 : N | `credits.entry_id` | CASCADE |
| People → Credit | 1 : N | `credits.people_id` | CASCADE |
| Media → * (polymorphic) | N : 1 | `media.mediaable` + `media.mediaable_id` | — (no FK constraint) |
---
## 5. Polymorphic Media Pattern
The `media` table uses a **polymorphic association** (no physical foreign key constraints).
Scoping is done via Sequelize's `scope` option:
```js
Entry.hasMany(Media, {
foreignKey: 'mediaableId',
constraints: false,
as: 'medias',
scope: { mediaable: 'entry' }
});
```
Supported owners: `entry`, `people`, `collection`, `season`, `episode`.
---
## 6. Sequelize Hooks
Defined in `config/sequelizeHooks.js`, the following lifecycle hooks enforce business rules:
| Hook | Model | Purpose |
| -------------- | --------------------- | ---------------------------------------------------------------- |
| `afterCreate` | `UserCollectionEntry` | Auto-assign `order` value; touch parent collection's `updatedAt` |
| `afterUpdate` | `UserCollectionEntry` | Re-order sibling entries; touch parent collection's `updatedAt` |
| `afterDestroy` | `UserCollectionEntry` | Touch parent collection's `updatedAt`; recalculate poster |
---
## 7. Data Seeding
On startup, `config/dataInitializer.js` inserts **27 TMDB genre records** into the `genres` table if they are missing. Genre IDs mirror TMDB's canonical IDs (e.g., `28 = Action`, `18 = Drama`).
---
## 8. Schema Sync Strategy
The server boots with:
```js
sequelize.sync({ alter: doUpdate })
```
- `alter: true` — Sequelize issues `ALTER TABLE` statements to reconcile model definitions with the live schema.
- `force: true` (commented out) — Would drop and recreate all tables. Reserved for development resets.
No explicit migration framework is in use; schema evolution is managed via Sequelize's auto-alter mechanism.
---
## 9. Indexing & Constraints
| Constraint Type | Table(s) | Details |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------- |
| Primary Key (auto-increment) | Most tables | Standard `id` column |
| Composite Primary Key | `entryGenres`, `entryNetworks`, `userCollectionEntries` | Prevents duplicate associations |
| Foreign Key | `seasons.entry_id`, `episodes.season_id`, `entrySeens.entry_id`, `episodeSeens.episode_id`, `episodeSeens.entry_id`, `credits.entry_id`, `credits.people_id` | Referential integrity |
| No FK constraint | `media.mediaable_id` | Polymorphic — `constraints: false` in Sequelize |
| ENUM | `credits.cast_type` | Restricted to `cast` / `crew` |
+440
View File
@@ -0,0 +1,440 @@
# Deployment Guide
> Showy backend supports three deployment modes: **Docker** (recommended), **standalone Node.js**, and **Electron-embedded**.
---
## Table of Contents
1. [Prerequisites](#1-prerequisites)
2. [Docker Deployment (Recommended)](#2-docker-deployment-recommended)
3. [Standalone Node.js](#3-standalone-nodejs)
4. [Electron Desktop App](#4-electron-desktop-app)
5. [Building a Portable Executable](#5-building-a-portable-executable)
6. [Environment Configuration](#6-environment-configuration)
7. [Database Setup](#7-database-setup)
8. [Reverse Proxy (nginx)](#8-reverse-proxy-nginx)
9. [Health Checks & Monitoring](#9-health-checks--monitoring)
10. [Backup & Restore](#10-backup--restore)
11. [Troubleshooting](#11-troubleshooting)
---
## 1. Prerequisites
| Requirement | Docker mode | Standalone mode | Electron mode |
| ----------------------- | ------------------- | --------------- | -------------- |
| Docker + Docker Compose | Yes | — | — |
| Node.js 18+ | — | Yes | Yes |
| MySQL 8.0 | Provided by compose | Manual install | Manual install |
| pnpm / npm | — | Yes | Yes |
| TMDB API key | Yes | Yes | Yes |
---
## 2. Docker Deployment (Recommended)
The quickest way to run the full stack (frontend + backend + MySQL).
### 2.1 Clone and configure
```bash
git clone https://github.com/X4Lo/showy.git
cd showy
```
### 2.2 Configure `settings.json`
```bash
cp backend/settings.json.example backend/settings.json
```
Edit `backend/settings.json`:
```json
{
"userDataPath": "/app/data",
"tmdbApiUrl": "https://api.themoviedb.org/3/",
"tmdbApiKey": "YOUR_TMDB_API_KEY",
"backPort": 4000
}
```
> In Docker, set `userDataPath` to `/app/data` so the container stores images inside a mountable volume.
### 2.3 Build and start
```bash
docker-compose up --build -d
```
This starts three containers:
| Service | Port | Description |
| ---------- | ------ | ---------------------------- |
| `frontend` | `3000` | Angular app served via nginx |
| `backend` | `4000` | Express API server |
| `mysql` | `3306` | MySQL 8.0 database |
### 2.4 Verify
```bash
curl http://localhost:4000/api/v1/ping
# → { "message": "pong" }
```
### 2.5 Persist data with volumes
Add a volume mount to the backend service in `docker-compose.yml` to persist images across container restarts:
```yaml
services:
backend:
volumes:
- ./showy-data:/app/data # persistent media storage
- ./backend/settings.json:/app/settings.json # config
```
### 2.6 Stop
```bash
docker-compose down # stop containers
docker-compose down -v # stop + remove volumes (deletes DB data!)
```
---
## 3. Standalone Node.js
Run the backend directly on the host machine.
### 3.1 Install MySQL
Install MySQL 8.0 and create the database:
```sql
CREATE DATABASE Showzy;
```
### 3.2 Install dependencies
```bash
cd backend
pnpm install
```
### 3.3 Configure
```bash
cp settings.json.example settings.json
```
Edit `settings.json` with your local paths and TMDB key.
If your MySQL credentials differ from the defaults (`root` / `password` / `localhost`), update `config/database.js`:
```js
const sequelize = new Sequelize('Showzy', 'YOUR_USER', 'YOUR_PASSWORD', {
host: 'YOUR_HOST',
dialect: 'mysql',
});
```
### 3.4 Start (development)
```bash
pnpm run backend
# Runs: nodemon server.js --trace-warnings
```
Nodemon watches for file changes and auto-restarts.
### 3.5 Start (production)
```bash
node server.js
```
For background execution on Linux:
```bash
# Using pm2
npm install -g pm2
pm2 start server.js --name showy-backend
pm2 save
pm2 startup
# Using systemd (see section below)
```
### 3.6 systemd service (Linux)
Create `/etc/systemd/system/showy-backend.service`:
```ini
[Unit]
Description=Showy Backend API
After=network.target mysql.service
[Service]
Type=simple
User=showy
WorkingDirectory=/opt/showy/backend
ExecStart=/usr/bin/node server.js
Restart=on-failure
RestartSec=5
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target
```
```bash
sudo systemctl daemon-reload
sudo systemctl enable showy-backend
sudo systemctl start showy-backend
sudo systemctl status showy-backend
```
---
## 4. Electron Desktop App
The backend can be embedded inside an Electron app for a fully self-contained desktop experience.
### 4.1 How it works
1. Electron's `main.js` spawns the backend as a child process:
```js
spawn('node', ['backend/server.js'], {
env: { PARENT_PROCESS: JSON.stringify({ electron_path: app.getPath('userData') }) }
});
```
2. The backend detects the `PARENT_PROCESS` env var and knows it's running inside Electron.
3. The frontend is loaded from local HTML files (`frontend_build/browser/index.html`).
4. When Electron quits, it kills the backend child process.
5. If the backend crashes, Electron **auto-restarts** it.
### 4.2 Build steps
```bash
# 1. Build the frontend
cd frontend
pnpm run build
# 2. Copy build output to electron folder
cp -r dist/showy/browser electron/frontend_build/browser
# 3. Install electron dependencies
cd ../electron
pnpm install
# 4. Run in dev mode
npx electron .
# 5. Package for distribution (using electron-builder or similar)
npx electron-builder
```
### 4.3 Backend lifecycle in Electron
| Event | Action |
| -------------------------------------------- | ----------------------------------------------------------------------- |
| `app.on('ready')` | Starts Express + creates browser window |
| Backend `stdout` contains `"Server started"` | Sends `backend-ready` event to renderer |
| Backend crashes (`exit` event) | Auto-restart via `startExpressServer()` |
| `app.on('before-quit')` | `backendExpressProcess.kill()` |
| `GET/POST /killer` | Intentionally crashes backend (triggers restart loop or clean shutdown) |
---
## 5. Building a Portable Executable
The backend can be packaged into a standalone `.exe` using `pkg`:
```bash
cd backend
pnpm run package
# Outputs: ../dist/backend/backend.exe (Windows x64, Node 18)
```
This produces a single binary that includes Node.js and all dependencies. No Node.js installation required on the target machine — only MySQL must be available.
### pkg configuration (from `package.json`)
```json
{
"pkg": {
"scripts": ["node_modules/**/*"],
"assets": ["node_modules/**/*"],
"targets": ["node18-win-x64"],
"outputPath": "../dist/backend/backend.exe"
}
}
```
---
## 6. Environment Configuration
### `settings.json` (primary)
All runtime configuration is stored in `settings.json` at the backend root. See [Project Setup](project_setup.md) for the full reference.
### Environment variables (Docker only)
| Variable | Default | Description |
| ---------------- | ----------- | ------------------------------------------ |
| `MYSQL_HOST` | `localhost` | MySQL hostname |
| `MYSQL_DB` | `Showzy` | Database name |
| `MYSQL_USER` | `root` | Database user |
| `MYSQL_PASSWORD` | `password` | Database password |
| `PARENT_PROCESS` | `{}` | Set by Electron; JSON with `electron_path` |
> **Important:** In the current codebase, `config/database.js` has hardcoded credentials. For Docker, these env vars are passed but must be read manually (or update `database.js` to use `process.env`).
---
## 7. Database Setup
### Schema management
Sequelize auto-manages the schema at startup:
```js
// In server.js
sequelize.sync({ alter: doUpdate }) // doUpdate = false by default
```
- **First run:** All tables are created automatically.
- **Schema changes:** Set `doUpdate = true` in `server.js` to apply `ALTER TABLE` statements.
- **Full reset:** Set `doForce = true` to drop and recreate all tables (destroys data).
### Data seeding
On startup, `dataInitializer.js` seeds **27 TMDB genre records** if they're missing. No other seeding is required.
### Recommended MySQL settings
```ini
[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci
max_connections = 100
innodb_buffer_pool_size = 256M
```
---
## 8. Reverse Proxy (nginx)
For production deployments behind a reverse proxy:
```nginx
server {
listen 80;
server_name showy.example.com;
# Frontend
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# Backend API
location /api/ {
proxy_pass http://localhost:4000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
client_max_body_size 20M; # for media uploads
}
}
```
For HTTPS, add a TLS certificate via Let's Encrypt / Certbot.
---
## 9. Health Checks & Monitoring
### Health endpoint
```bash
GET /api/v1/ping → { "message": "pong" }
```
### Docker health check
Add to `docker-compose.yml`:
```yaml
services:
backend:
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:4000/api/v1/ping"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
```
### Log file
- **Location:** `backend/showy.log`
- **Format:** `[YYYY-MM-DD HH:mm:ss] message`
- **Contains:** TMDB fetch logs, media download/preview events, error traces
Monitor in real time:
```bash
tail -f backend/showy.log
```
---
## 10. Backup & Restore
### What to back up
| Component | Location | Method |
| ------------- | ------------------------ | ----------------- |
| Database | MySQL `Showzy` | `mysqldump` |
| Media files | `{userDataPath}/images/` | File copy / rsync |
| Configuration | `backend/settings.json` | File copy |
### MySQL backup
```bash
# Backup
mysqldump -u root -p Showzy > showzy_backup_$(date +%F).sql
# Restore
mysql -u root -p Showzy < showzy_backup_2026-03-30.sql
```
### Media backup
```bash
# Backup (rsync)
rsync -av /path/to/showy-data/images/ /backup/showy-images/
# Or tar archive
tar czf showy-media-$(date +%F).tar.gz -C /path/to/showy-data images/
```
---
## 11. Troubleshooting
| Problem | Cause | Fix |
| ---------------------------- | -------------------------------------- | -------------------------------------------------------------------------------- |
| `ECONNREFUSED` on startup | MySQL not running or wrong credentials | Check MySQL is up; verify `config/database.js` |
| `ER_NOT_SUPPORTED_AUTH_MODE` | MySQL 8 auth plugin mismatch | Run `ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'password';` |
| Port 4000 already in use | Another process on that port | Change `backPort` in `settings.json` or kill the other process |
| Images not loading | `userDataPath` misconfigured | Verify the path exists and is writable; check `settings.json` |
| Previews not generating | `sharp` native bindings missing | Run `pnpm rebuild sharp` or reinstall with `pnpm install` |
| TMDB fetch returns `null` | Invalid API key or rate limited | Verify `tmdbApiKey` in `settings.json`; check TMDB account status |
| Schema out of sync | New model fields added | Set `doUpdate = true` in `server.js`, restart, then set back to `false` |
| Docker MySQL won't start | Volume permission issues | Run `docker-compose down -v` then `docker-compose up --build` |
| Sequelize sync error | Table conflicts on `alter` | Backup DB, set `doForce = true` temporarily (destroys data), restart |
+143
View File
@@ -0,0 +1,143 @@
# Error Handling
---
## 1. Architecture
The backend uses a **custom error class hierarchy** rooted in `CustomError` (extends `Error`) combined with an Express **global error-handling middleware** registered after all routes.
```
Error (native)
└── CustomError (base, 500)
├── BadRequestError (400)
├── ValidationError (400)
├── UnauthorizedError (401)
├── ForbiddenError (403)
├── NotFoundError (404)
├── ConflictError (409)
└── InternalServerError (500)
```
---
## 2. Error Classes
All classes live under `errors/` and extend `CustomError`.
| Class | File | HTTP Status | Use Case |
| --------------------- | ------------------------------- | ----------- | -------------------------------------------------------------- |
| `CustomError` | `errors/CustomError.js` | 500 | Abstract base class |
| `BadRequestError` | `errors/BadRequestError.js` | 400 | Missing or invalid request parameters |
| `ValidationError` | `errors/ValidationError.js` | 400 | Semantic validation failures (named 422-style but returns 400) |
| `UnauthorizedError` | `errors/UnauthorizedError.js` | 401 | Authentication required |
| `ForbiddenError` | `errors/ForbiddenError.js` | 403 | Insufficient permissions |
| `NotFoundError` | `errors/NotFoundError.js` | 404 | Resource not found |
| `ConflictError` | `errors/ConflictError.js` | 409 | State conflict (e.g., duplicate resource) |
| `InternalServerError` | `errors/InternalServerError.js` | 500 | Unexpected server-side failures |
### Base class implementation
```js
class CustomError extends Error {
constructor(message) {
super(message);
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
statusCode() {
return 500;
}
}
```
Each subclass overrides `statusCode()` to return its specific HTTP code.
---
## 3. Global Error-Handling Middleware
**File:** `middleware/errorHandler.js`
```js
module.exports = (err, req, res, next) => {
if (err instanceof CustomError) {
res.status(err.statusCode()).json({ message: err.message });
logToFile(`Error (${err.statusCode()}) ${err.message}`);
} else {
logToFile(`Error (500) ${err}`);
res.status(500).json({ message: 'Internal server error' });
}
};
```
**Behaviour:**
| Error type | Response status | Response body | Logged |
| ------------------------ | ------------------ | ---------------------------------------- | -------------------------- |
| `instanceof CustomError` | `err.statusCode()` | `{ "message": "<error message>" }` | Yes — error code + message |
| Any other error | `500` | `{ "message": "Internal server error" }` | Yes — full error string |
The middleware is registered in `server.js` after all route handlers:
```js
app.use('/api/v1', routes);
app.use(errorHandler); // ← catches all thrown/next(err) errors
```
---
## 4. Throwing Errors in Services
Services throw custom errors directly. Express catches them via the async flow (controllers use `async` handlers):
```js
// In a service
if (!id) {
throw new BadRequestError("Entry id not provided");
}
const entry = await Entry.findByPk(id);
if (!entry) {
throw new NotFoundError("Entry with the provided id was not found");
}
```
> **Note:** Most controller methods do not wrap calls in `try/catch`. They rely on the global error middleware. Some controllers (particularly `CollectionController`) still have inline `try/catch` blocks that return `500` directly — these predate the centralized error handling.
---
## 5. Logging Integration
All handled errors are written to `showy.log` via `LogService.logToFile()`:
```
[2026-03-30 14:22:01] Error (404) Entry with the provided id was not found
[2026-03-30 14:22:05] Error (500) ReferenceError: kill is not defined
```
Format: `[YYYY-MM-DD HH:mm:ss] Error ({code}) {message}`
---
## 6. Error Response Contract
All error responses follow a consistent JSON shape:
```json
{
"message": "Human-readable error description"
}
```
Some legacy controller handlers also use `{ "error": "..." }` — this inconsistency exists in older code paths that pre-date the `CustomError` system.
---
## 7. Unhandled Cases
| Scenario | Current behaviour |
| --------------------------------------- | ------------------------------------------------------------------------------------- |
| Sequelize `ValidationError` (ORM-level) | Falls through to the generic 500 handler since it is not an instance of `CustomError` |
| Unhandled promise rejection | Logged to stderr by Node.js; not caught by Express middleware |
| CORS preflight errors | Handled by inline CORS middleware before reaching the error handler |
| Multer file upload errors | Caught inline in route handlers |
+325
View File
@@ -0,0 +1,325 @@
# Project Setup & Configuration
---
## 1. Tech Stack
| Component | Technology | Version |
| ---------------- | ---------- | ------- |
| Runtime | Node.js | 18+ |
| Framework | Express | 4.21 |
| ORM | Sequelize | 6.37 |
| Database | MySQL | 8.0 |
| Image processing | sharp | 0.33 |
| HTTP client | Axios | 1.7 |
| File uploads | Multer | 1.4 |
| UUID generation | uuid | 11.0 |
| Dev server | Nodemon | 3.1 |
| Packaging | pkg | — |
---
## 2. Directory Structure
```
backend/
├── server.js # Express app entry point
├── package.json # Dependencies & scripts
├── nodemon.json # Dev watcher config
├── settings.json # Runtime configuration (git-ignored)
├── settings.json.example # Template for settings.json
├── Dockerfile # Container build
├── showy.log # Runtime log file (auto-created)
│
├── config/
│ ├── database.js # Sequelize instance (MySQL connection)
│ ├── relations.js # All model associations
│ ├── sequelizeHooks.js # Lifecycle hooks (afterCreate, afterUpdate, afterDestroy)
│ ├── dataInitializer.js # Genre seeding on startup
│ └── genres.sql # Reference SQL for genres
│
├── models/ # Sequelize model definitions (1 file per table)
│ ├── Entry.js
│ ├── EntryId.js
│ ├── EntryRating.js
│ ├── EntrySeen.js
│ ├── Season.js
│ ├── Episode.js
│ ├── EpisodeSeen.js
│ ├── Collection.js
│ ├── UserCollectionEntry.js
│ ├── Genre.js
│ ├── EntryGenre.js
│ ├── Network.js
│ ├── EntryNetwork.js
│ ├── People.js
│ ├── Credit.js
│ ├── Franchise.js
│ └── Media.js
│
├── controllers/ # HTTP request handlers (thin layer)
│ ├── entryController.js
│ ├── collectionController.js
│ ├── entrySeenController.js
│ ├── episodeController.js
│ ├── episodeSeenController.js
│ ├── seasonController.js
│ ├── mediaController.js
│ ├── peopleController.js
│ ├── importController.js
│ ├── settingsController.js
│ ├── statisticsController.js
│ ├── maintenanceController.js
│ ├── pingController.js
│ └── killerController.js
│
├── routes/ # Express router definitions
│ ├── routes.js # Root router (mounts all sub-routers)
│ ├── entry.routes.js
│ ├── collection.routes.js
│ ├── entry-seen.routes.js
│ ├── episode.routes.js
│ ├── episode-seen.routes.js
│ ├── season.routes.js
│ ├── media.routes.js
│ ├── people.routes.js
│ ├── import.routes.js
│ ├── settings.routes.js
│ ├── statistics.routes.js
│ ├── maintenance.routes.js
│ ├── ping.routes.js
│ └── killer.routes.js
│
├── services/ # Business logic & infrastructure
│ ├── entryManager.js
│ ├── entryService.js
│ ├── collectionManager.js
│ ├── collectionService.js
│ ├── episodeService.js
│ ├── peopleManager.js
│ ├── peopleService.js
│ ├── mediaManager.js
│ ├── mediaService.js
│ ├── mediaDownloaderService.js
│ ├── mediaOptimizerService.js
│ ├── storageService.js
│ ├── networkService.js
│ ├── tmdbService.js
│ ├── configService.js
│ ├── logService.js
│ ├── maintenanceService.js
│ ├── importerService.js
│ ├── mutlerStorageLocations.js
│ └── models-services/ # Legacy procedural service functions
│ ├── entryService.js
│ └── seasonService.js
│
├── middleware/
│ └── errorHandler.js # Global Express error middleware
│
├── errors/ # Custom error class hierarchy
│ ├── CustomError.js
│ ├── BadRequestError.js
│ ├── ValidationError.js
│ ├── UnauthorizedError.js
│ ├── ForbiddenError.js
│ ├── NotFoundError.js
│ ├── ConflictError.js
│ └── InternalServerError.js
│
├── mappers/
│ └── entryMapper.js # Empty — reserved for DTO mapping
│
├── utils/
│ └── moment.js # Bundled moment.js library
│
└── docs/ # This documentation
```
---
## 3. Configuration (`settings.json`)
Copy `settings.json.example` to `settings.json` and fill in your values:
```json
{
"userDataPath": "C:\\Users\\<username>\\Documents\\Showy Data",
"tmdbApiUrl": "https://api.themoviedb.org/3/",
"tmdbApiKey": "<your_tmdb_api_key>",
"frontPort": "8000",
"backPort": 4000,
"portableMode": "",
"libraryViewMode": "grid",
"favoritViewMode": "grid",
"watchlistViewMode": "grid",
"CollectionsViewMode": "grid",
"CollectionItemsViewMode": "grid",
"episodesViewMode": "grid"
}
```
| Key | Type | Description |
| -------------- | ------ | -------------------------------------------------------- |
| `userDataPath` | string | Absolute path to the local data directory (images, etc.) |
| `tmdbApiUrl` | string | TMDB API v3 base URL |
| `tmdbApiKey` | string | Your TMDB API key |
| `frontPort` | string | Frontend dev server port |
| `backPort` | number | Backend Express server port (default: `4000`) |
| `portableMode` | string | Reserved for Electron portable mode |
| `*ViewMode` | string | UI preferences (`grid` or other view modes) |
If `settings.json` is missing, `ConfigService` auto-creates one with defaults and `userDataPath` set to `backend/data/`.
---
## 4. NPM Scripts
| Script | Command | Purpose |
| --------- | ------------------------------------------------------------------------- | ------------------------------------------- |
| `backend` | `nodemon server.js --trace-warnings` | Start dev server with auto-restart |
| `package` | `pkg server.js --output ../dist/backend/backend --targets node18-win-x64` | Bundle into a standalone Windows executable |
---
## 5. Startup Sequence
```
1. Load settings.json via ConfigService
2. Configure Express middleware (body-parser, CORS)
3. Mount routes at /api/v1
4. Mount error handler middleware
5. Mount /killer route (outside /api/v1 prefix)
6. sequelize.sync({ alter }) → auto-migrate schema
7. initializeData() → seed genres table
8. app.listen(PORT) → server ready
```
### Sequelize sync modes (in `server.js`)
```js
const doUpdate = false; // Set to true to enable ALTER TABLE
const doForce = false; // Set to true to DROP + recreate ALL tables (data loss!)
sequelize.sync({ alter: doUpdate })
```
---
## 6. Docker Setup
### Backend Dockerfile
```dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm i
COPY backend/* .
EXPOSE 4000
CMD ["node", "server.js"]
```
### docker-compose.yml (root)
Three services: `frontend`, `backend`, `mysql`.
```yaml
services:
backend:
build:
context: ./
dockerfile: backend/Dockerfile
environment:
MYSQL_HOST: mysql
MYSQL_DB: Showzy
MYSQL_USER: root
MYSQL_PASSWORD: password
ports:
- "4000:4000"
depends_on:
- mysql
mysql:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: rootpassword
MYSQL_DATABASE: mydatabase
ports:
- "3306:3306"
volumes:
- db_data:/var/lib/mysql
```
---
## 7. CORS Configuration
CORS is set globally via inline middleware in `server.js` — all origins are allowed:
```js
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
```
No authentication or API key middleware is applied. The server is designed for single-user, local-network use.
---
## 8. Logging
- **File:** `showy.log` (in project root)
- **Format:** `[YYYY-MM-DD HH:mm:ss] {message}`
- **Append mode:** Each write reopens the file with `{ flag: 'a' }`
- **Dual output:** All log messages are also written to `stdout` via `console.log`
- **Library:** Uses the bundled `utils/moment.js` for timestamp formatting
---
## 9. Data Directory Structure
Created by `ConfigService.createMediaFolders()` on first media download:
```
{userDataPath}/
└── images/
├── entries/
│ ├── posters/
│ ├── backdrops/
│ └── logos/
├── collections/
│ ├── posters/
│ └── backdrops/
├── seasons/
│ └── posters/
├── episodes/
│ └── stills/
└── peoples/
└── profiles/
```
Each image is stored with a UUID v4 filename (e.g., `a1b2c3d4-e5f6-...jpg`).
Preview variants are stored alongside with a `_preview` suffix (e.g., `a1b2c3d4_preview.jpg`).
---
## 10. External Dependencies
| Dependency | Purpose |
| ----------------------- | ------------------------------------------------------------------------------------- |
| **TMDB API v3** | All movie/series/person/collection metadata and images |
| **MySQL 8.0** | Primary data store |
| **Electron** (optional) | Desktop app wrapper — communicates via `/killer` endpoint to manage backend lifecycle |
---
## 11. Electron Integration
The backend can be spawned as a child process by the Electron main process (`electron/main.js`). Key integration points:
| Feature | Mechanism |
| ------------------------ | ------------------------------------------------------------------------- |
| Start backend | Electron spawns `node server.js` or the `pkg`-built `.exe` |
| Stop backend | `GET /killer` or `POST /killer` — intentionally crashes the process |
| Parent process detection | `process.env.PARENT_PROCESS` is set by Electron and parsed in `server.js` |
| Port coordination | Both frontend and backend ports are configured in `settings.json` |
+251
View File
@@ -0,0 +1,251 @@
# Service Layer Architecture
> **Pattern:** Singleton services · **DI:** Manual constructor-guard (`if (!X.instance) { X.instance = this }`)
---
## 1. Overview
The backend follows a **Controller → Manager → Service** layered architecture:
```
HTTP Request
│
▼
Controller Thin adapter — validates params, delegates, returns HTTP response
│
▼
Manager Orchestrates multi-step workflows across services (optional layer)
│
▼
Service Single-responsibility data-access and business logic
│
▼
Model (Sequelize) ORM layer — maps to MySQL tables
```
All services and managers are instantiated as **singletons** via a constructor guard pattern and exported as pre-built instances (`module.exports = new XService()`).
---
## 2. Service Catalogue
### 2.1 Data Services
| Service | File | Responsibility |
| ------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `EntryService` | `services/entryService.js` | CRUD for entries; creates entry + IDs + ratings + genres + networks + seasons/episodes + credits + media in one transaction; queries with deep includes |
| `CollectionService` | `services/collectionService.js` | List/get/createOrUpdate collections; deep include of entries with pivot ordering |
| `EpisodeService` | `services/episodeService.js` | Query episodes between date ranges (calendar feed); joins through Season → Entry |
| `PeopleService` | `services/peopleService.js` | CRUD for people; lazy fetch from TMDB; search by name; credits retrieval |
| `NetworkService` | `services/networkService.js` | `findOrCreate` networks; list/get with associated entries |
| `MediaService` | `services/mediaService.js` | Thin wrapper around `Media.create()` |
### 2.2 Managers (Orchestrators)
| Manager | File | Responsibility |
| ------------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `EntryManager` | `services/entryManager.js` | Full entry lifecycle: TMDB fetch → persist → collection linking → media download → preview generation → credits |
| `CollectionManager` | `services/collectionManager.js` | Fetch collection from TMDB → createOrUpdate → link entries → download media → generate previews; fetch missing parts |
| `PeopleManager` | `services/peopleManager.js` | Lazy-fetch person on first access; download + optimize profile images |
| `MediaManager` | `services/mediaManager.js` | Download entry/season/episode media from TMDB; persist `Media` records; trigger preview generation |
### 2.3 Infrastructure Services
| Service | File | Responsibility |
| ------------------------ | ------------------------------------ | -------------------------------------------------------------------------------------------------- |
| `TmdbService` | `services/tmdbService.js` | HTTP client wrapping the TMDB v3 REST API (entries, seasons, collections, credits, people, images) |
| `MediaDownloaderService` | `services/mediaDownloaderService.js` | Downloads remote images to local disk via Axios streams; selects preferred language variant |
| `MediaOptimizerService` | `services/mediaOptimizerService.js` | Generates low-res preview images using `sharp` (resize + JPEG/PNG compression) |
| `StorageService` | `services/storageService.js` | Low-level file write abstraction (pipes Axios response stream to `fs.createWriteStream`) |
| `ConfigService` | `services/configService.js` | Reads/writes `settings.json`; creates media directory tree; exposes TMDB API credentials |
| `LogService` | `services/logService.js` | Appends timestamped messages to `showy.log` via `fs.writeFile` with `{ flag: 'a' }` |
| `MaintenanceService` | `services/maintenanceService.js` | Detects/removes orphan files (disk without DB record) and orphan records (DB without file) |
| `ImporterService` | `services/importerService.js` | Bulk-import movies/series/episode-history with self-throttling TMDB rate-limit loop |
| `MullerStorageLocations` | `services/mutlerStorageLocations.js` | Multer disk-storage configs for entry, collection, and people image uploads (UUID filenames) |
### 2.4 Legacy / Stub Services
| File | Notes |
| ------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `services/models-services/entryService.js` | Legacy `saveEntry()` / `updateEntry()` functions (procedural). Superseded by `EntryService` class but still used by `ImporterService`. |
| `services/models-services/seasonService.js` | Stub — all functions are empty placeholders. Not called anywhere. |
---
## 3. Key Service Details
### 3.1 `EntryService.createEntry(data)`
The most complex single-service method. Performs the following in sequence:
```
1. Build & save Entry record
2. Create EntryId record (tmdb_id, imdb_id)
3. Create EntryGenre join records
4. Create/link Network records (findOrCreate per network)
5. Create EntryRating record
6. IF is_tvseries:
6a. For each TMDB season:
- fetchSeasonData() from TMDB
- Create Season record
- Download season poster (async, fire-and-forget)
- For each episode:
- Create Episode record
- Download episode still (async, fire-and-forget)
7. fetchEntryCredits() from TMDB
8. Bulk-create People records (deduplicated by tmdb_id)
9. Bulk-create Credit records (cast + crew)
10. Download entry media (posters, backdrops, logos)
11. Create Media records + generate previews
12. Re-query entry with all includes and return
```
### 3.2 `EntryService.getEntryById(id)`
Returns a deeply nested object with all related data:
```
Entry
├── entryId (EntryId)
├── entryRating (EntryRating)
├── entrySeen[] (EntrySeen[])
├── seasons[] (Season[])
├── medias[] (Media[])
├── networks[] (Network[])
├── credits[] (Credit[] — cast only, limit 10, ordered by billing)
│ └── person (People)
├── collections[] (Collection[])
│ └── medias[] (Media[])
└── genres[] (string[] — names only)
```
### 3.3 `CollectionService.createOrUpdateCollection(data)`
Uses Sequelize's `findOrCreate` keyed on `tmdb_id`. Returns `[existingInstance, createdInstance]` — one will be `null`.
### 3.4 `PeopleService.fetchAndSavePersonByTmdbId(tmdbId)`
Implements an **upsert with lazy enrichment** pattern:
```
Person exists + fully_fetched? → return cached
Person exists + NOT fully_fetched? → fetch from TMDB → update → download media → return
Person NOT in DB? → fetch from TMDB → create → download media → return
```
### 3.5 `EpisodeService.getEpisodesBetweenDates(start, end)`
Calendar query that joins `Episode → Season → Entry → (EntryId, Media)` and flattens the result so `entry` appears at the top level of each episode object instead of nested under `season.entry`.
---
## 4. TMDB Service API Mapping
| Function | TMDB Endpoint | Returns |
| ----------------------------- | -------------------------------------------------- | -------------------------------- |
| `fetchEntryData(id, isTv)` | `GET /{movie\|tv}/{id}` | Full movie/series metadata |
| `fetchSeasonData(tvId, num)` | `GET /tv/{id}/season/{num}` | Season with embedded episodes |
| `fetchEntryMedia(id, isTv)` | `GET /{movie\|tv}/{id}/images` | Posters, backdrops, logos |
| `fetchCollectionData(id)` | `GET /collection/{id}` | Collection metadata + parts list |
| `fetchEntryCredits(id, isTv)` | `GET /{movie\|tv}/{id}/credits` | Cast and crew arrays |
| `fetchPersonDetails(id)` | `GET /person/{id}?append_to_response=external_ids` | Full person bio + external IDs |
All functions use `axios.get()` with the API key passed as a query parameter. Base URL and key are read from `ConfigService` at module load time.
---
## 5. Media Pipeline
```
TMDB API (remote URL)
│
▼
MediaDownloaderService.downloadImage() → Axios stream → fs.createWriteStream
│
▼
Local filesystem: {userDataPath}/images/{category}/{type}/{uuid}.{ext}
│
▼
MediaOptimizerService.doGeneratePreview() → sharp resize → {uuid}_preview.jpg
│
▼
Media table record (mediaable, type, path, isLocal, isSelected)
```
### Preview dimensions
| Media type | Preview width (px) | Format |
| ---------- | ------------------ | ----------------- |
| Posters | 342 | JPEG (quality 80) |
| Backdrops | 780 | JPEG (quality 80) |
| Logos | 300 | PNG |
### Upload pipeline (user-uploaded media)
```
Client multipart POST
│
▼
Multer diskStorage → UUID filename, routed to correct folder
│
▼
Controller inline handler → Media.create() record
│
▼
MediaOptimizerService → async preview generation (fire-and-forget)
```
Multer configs are in `services/mutlerStorageLocations.js`, one per entity type:
- `entryPicturesUpload` — accepts `poster`, `backdrop`, `logo` fields
- `collectionPicturesUpload` — accepts `poster`, `backdrop` fields
- `peoplePicturesUpload` — accepts `profile` field
---
## 6. Media Category → Folder Mapping
| `mediaable` | `type` | Disk folder |
| ------------ | ---------- | ------------------------------------------ |
| `entry` | `poster` | `{dataPath}/images/entries/posters/` |
| `entry` | `backdrop` | `{dataPath}/images/entries/backdrops/` |
| `entry` | `logo` | `{dataPath}/images/entries/logos/` |
| `collection` | `poster` | `{dataPath}/images/collections/posters/` |
| `collection` | `backdrop` | `{dataPath}/images/collections/backdrops/` |
| `season` | `poster` | `{dataPath}/images/seasons/posters/` |
| `episode` | `still` | `{dataPath}/images/episodes/stills/` |
| `people` | `profile` | `{dataPath}/images/peoples/profiles/` |
---
## 7. Dependency Graph
```
┌─────────────┐
│ Controllers │
└──────┬──────┘
│
┌────────────┼────────────┐
▼ ▼ ▼
EntryManager CollectionMgr PeopleMgr
│ │ │
┌─────┬──┴──┬────┐ │ ┌─────┘
▼ ▼ ▼ ▼ ▼ ▼
Entry Coll. Media Tmdb Coll. People
Svc Svc Mgr Svc Svc Svc
│ │ │ │ │ │
▼ ▼ ▼ ▼ ▼ ▼
┌──────────────────────────────────┐
│ Sequelize Models (ORM) │
└──────────────────────────────────┘
│
┌─────────┼──────────┐
▼ ▼ ▼
MediaDL MediaOpt Storage
Svc Svc Svc
│ │ │
▼ ▼ ▼
┌──────────────────────────┐
│ Filesystem / Axios / sharp │
└──────────────────────────┘
```