252 lines
13 KiB
Markdown
252 lines
13 KiB
Markdown
# 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 │
|
|
└──────────────────────────┘
|
|
```
|