# 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\\\\Documents\\Showy Data", "tmdbApiUrl": "https://api.themoviedb.org/3/", "tmdbApiKey": "", "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` |