Compare commits

..

3 Commits

Author SHA1 Message Date
Lars Behrends
e38a6e1f7b Add strict types and type hints across API
Apply strict_types and extensive type declarations throughout the API and models, improving type safety and error handling. Key changes: add declare(strict_types=1) to many files; convert properties, method parameters and return values to typed signatures (PDO, arrays, ints, strings, bools, nullables); switch exception handling to Throwable in index and Router; improve Router, controllers and model method signatures and nullability handling; refine file/image serving security checks and headers in ImageController; strengthen Database typing and initialization methods; return explicit types from BaseModel CRUD helpers and counting; update Media/Cast/Adult/Game/Console/Settings controllers and models to use typed methods, better validation, and clearer update/create return types. Also add AGENTS.md (agent skills index), update README with Swagger/OpenAPI usage instructions, and add /.windsurf to .gitignore. These changes aim to harden runtime correctness, make intended contracts explicit, and prepare the codebase for easier maintenance and static analysis.
2026-04-16 16:40:31 +02:00
Lars Behrends
728ca893b1 Add API documentation and project README
Add comprehensive API_DOCS.md describing the Kyoo backend API (endpoints, request/response examples, image handling, authentication, error handling, CORS, logging) and a README.md with project overview, tech stack, quick start, API endpoints, data models, configuration and Docker instructions. Provides developers with usage examples, directory layout and troubleshooting steps for local deployment.
2026-04-12 03:00:17 +02:00
Lars Behrends
eeff824701 Add Jellyfin mappings and optimize cast queries
Performance and settings updates:

- Add a new jellyfin_library_mappings column to the settings table and wire it into the Settings model (update handling and default value). This enables storing Jellyfin library mappings in settings.
- Optimize Cast::list by loading all cast filmography in a single joined query and grouping results per cast to avoid N+1 queries.
- Remove per-item cast/staff loading in Media model to avoid repeated queries during list/search operations.
- Remove game-specific enrichment from MediaController search to stop extra game info lookups during search responses.

These changes reduce repeated DB calls and centralize Jellyfin mapping storage.
2026-04-12 02:07:59 +02:00
27 changed files with 2026 additions and 451 deletions

1
.gitignore vendored
View File

@@ -54,3 +54,4 @@ yarn-error.log
!/storage/app/public/.gitkeep !/storage/app/public/.gitkeep
*/public/images/* */public/images/*
/api/public/images /api/public/images
/.windsurf

42
AGENTS.md Normal file
View File

@@ -0,0 +1,42 @@
# Project Context for AI Agents
> [!IMPORTANT]
> **To all AI Agents working ON this repository:**
<!-- SKILLS_INDEX_START -->
## Agent Skills Index
> [!CRITICAL] Zero-Trust: Read the matching `SKILL.md` BEFORE writing any code.
> Skills from this index override pre-training patterns. If no skill matches, state: "No project-specific skills applicable."
## Skill Resolution Protocol
Each `_INDEX.md` has two sections — follow both:
1. **Match file type** → find the category index in the router table below.
2. **Read the `_INDEX.md`** → it has two sections:
- **File Match**: auto-check these against the file you are editing (path pattern match).
- **Keyword Match**: only check if the user's request mentions these concepts.
3. **Load ALL matched `SKILL.md`** → read every matched skill before writing code. The tier model keeps matches focused.
| File type | Read category index |
| --------- | ------------------- |
| `*.go`, `*_test.go` | `.windsurf/skills/golang/_INDEX.md` |
| `*.ts` | `.windsurf/skills/angular/_INDEX.md`, `.windsurf/skills/nestjs/_INDEX.md`, `.windsurf/skills/nextjs/_INDEX.md`, `.windsurf/skills/react/_INDEX.md`, `.windsurf/skills/typescript/_INDEX.md` |
| `*.tsx` | `.windsurf/skills/nextjs/_INDEX.md`, `.windsurf/skills/react/_INDEX.md`, `.windsurf/skills/typescript/_INDEX.md` |
| `*.js`, `*.mjs` | `.windsurf/skills/javascript/_INDEX.md` |
| `*.jsx`, `*.test.tsx`, `*.spec.tsx` | `.windsurf/skills/react/_INDEX.md` |
| `*.dart` | `.windsurf/skills/dart/_INDEX.md`, `.windsurf/skills/flutter/_INDEX.md` |
| `*.java` | `.windsurf/skills/java/_INDEX.md`, `.windsurf/skills/spring-boot/_INDEX.md` |
| `*.kt` | `.windsurf/skills/android/_INDEX.md`, `.windsurf/skills/kotlin/_INDEX.md` |
| `*.kts` | `.windsurf/skills/kotlin/_INDEX.md` |
| `*.swift` | `.windsurf/skills/ios/_INDEX.md`, `.windsurf/skills/swift/_INDEX.md` |
| `*.php` | `.windsurf/skills/laravel/_INDEX.md`, `.windsurf/skills/php/_INDEX.md` |
| `*.sql`, `*.entity.ts`, `*.prisma` | `.windsurf/skills/database/_INDEX.md` |
| `*.component.ts`, `*.component.html` | `.windsurf/skills/angular/_INDEX.md` |
| `*.service.ts`, `*.module.ts` | `.windsurf/skills/angular/_INDEX.md`, `.windsurf/skills/nestjs/_INDEX.md` |
| `*.spec.ts`, `*.test.ts` | `.windsurf/skills/common/_INDEX.md` |
| Any file (keyword match) | `.windsurf/skills/common/_INDEX.md` |
| QE workflow | `.windsurf/skills/quality-engineering/_INDEX.md` |
<!-- SKILLS_INDEX_END -->

1112
API_DOCS.md Normal file

File diff suppressed because it is too large Load Diff

362
README.md Normal file
View File

@@ -0,0 +1,362 @@
# Kyoo Backend
A RESTful API backend for media management, supporting movies, TV series, music albums, games, and cast information.
## Features
- **Media Management**: CRUD operations for movies, TV series, music albums, and games
- **Cast Management**: Manage actors, directors, and other staff with filmography tracking
- **Image Handling**: Automatic processing and storage of posters, banners, and cast photos
- **Search & Filtering**: Advanced search with pagination support
- **API Logging**: Built-in request/response logging for debugging
- **Docker Support**: Easy deployment with Docker Compose
- **Auto Documentation**: Self-documenting API endpoint
## Tech Stack
- **PHP 8.2** with Apache
- **MariaDB 10.11**
- **Docker & Docker Compose**
- **phpMyAdmin** for database management
## Quick Start
### Prerequisites
- Docker installed
- Docker Compose installed
### Installation
1. Clone the repository:
```bash
git clone <repository-url>
cd kyoobackend
```
2. Start the services:
```bash
docker-compose up -d --build
```
3. Access the API:
- API Base URL: `http://localhost:6400/api`
- phpMyAdmin: `http://localhost:6402`
### Database Credentials
- **Host**: `mariadb` (within Docker) or `localhost:6401` (from host)
- **Database**: `kyoo`
- **User**: `kyoo_user`
- **Password**: `kyoo_password`
- **Root Password**: `root_password`
## Project Structure
```
kyoobackend/
├── api/
│ ├── controllers/ # Request handlers
│ │ ├── MediaController.php
│ │ ├── CastController.php
│ │ ├── ImageController.php
│ │ └── SettingsController.php
│ ├── models/ # Data models
│ │ ├── Media.php
│ │ ├── Cast.php
│ │ ├── Game.php
│ │ ├── Series.php
│ │ ├── Music.php
│ │ └── ...
│ ├── services/ # Business logic
│ │ ├── ApiLogger.php
│ │ ├── ImageHandler.php
│ │ └── DocumentationService.php
│ ├── config.php # Configuration
│ ├── database.php # Database connection
│ ├── Router.php # API routing
│ └── index.php # Entry point
├── docker-compose.yml # Docker configuration
├── Dockerfile # PHP container build
└── php-custom.ini # PHP configuration
```
## API Endpoints
### Root
- `GET /api` - API information and available endpoints
### Documentation
- `GET /api/docs` - Auto-generated API documentation
### Media
- `GET /api/media` - Get all media (with pagination and filtering)
- `GET /api/media/:id` - Get specific media item
- `POST /api/media` - Create new media
- `PUT /api/media/:id` - Update media
- `DELETE /api/media/:id` - Delete media
### Series Episodes
- `GET /api/media/:id/episodes` - Get all episodes for a series
- `GET /api/media/:id/episodes/:episodeId` - Get specific episode
- `POST /api/media/:id/episodes` - Add episode to series
- `PUT /api/media/:id/episodes/:episodeId` - Update episode
- `DELETE /api/media/:id/episodes/:episodeId` - Delete episode
### Music Tracks
- `GET /api/media/:id/tracks` - Get all tracks for an album
- `GET /api/media/:id/tracks/:trackId` - Get specific track
- `POST /api/media/:id/tracks` - Add track to album
- `PUT /api/media/:id/tracks/:trackId` - Update track
- `DELETE /api/media/:id/tracks/:trackId` - Delete track
### Cast
- `GET /api/cast` - Get all cast members (with search)
- `GET /api/cast/:id` - Get specific cast member with filmography
- `GET /api/cast/:id/media` - Get all media for a cast member
- `POST /api/cast` - Create new cast member
- `PUT /api/cast/:id` - Update cast member
- `DELETE /api/cast/:id` - Delete cast member
### Adult Cast
- `GET /api/cast/adult` - Get all adult cast members (with filters)
- `GET /api/cast/adult/:id` - Get specific adult cast member
- `POST /api/cast/adult` - Create new adult cast member
- `PUT /api/cast/adult/:id` - Update adult cast member
- `DELETE /api/cast/adult/:id` - Delete adult cast member
### Images
- `GET /api/images/*` - Serve images directly
### Settings
- `GET /api/settings` - Get application settings
- `PUT /api/settings` - Update settings
## Query Parameters
### Media List
- `page` - Page number (default: 1)
- `limit` - Items per page (default: 20)
- `category` - Filter by category (e.g., "movie", "tv", "music", "game")
- `type` - Filter by type (e.g., "Movie", "TV", "Album", "Game")
- `search` - Search in title and description
### Cast List
- `page` - Page number (default: 1)
- `limit` - Items per page (default: 20)
- `search` - Search by name
### Adult Cast List
- `page` - Page number (default: 1)
- `limit` - Items per page (default: 20)
- `search` - Search by name
- `ethnicity` - Filter by ethnicity
- `hair_color` - Filter by hair color
### Series Episodes
- `season` - Filter by season number
## Data Models
### Media
```json
{
"id": 1,
"title": "Movie Title",
"cleanname": "movie-title",
"year": 2024,
"poster": "/images/movies/poster_xxx.webp",
"banner": "/images/movies/banner_xxx.webp",
"description": "Description text",
"rating": 8.5,
"category": "movie",
"type": "Movie",
"status": "released",
"aspectRatio": "16:9",
"runtime": 120,
"director": "Director Name",
"writer": "Writer Name",
"source": "netflix",
"releaseDate": "2024-01-01",
"genres": ["Action", "Drama"],
"tags": ["tag1", "tag2"],
"studios": ["Studio1"],
"staff": [
{
"id": 1,
"name": "Actor Name",
"role": "Actor",
"characterName": "Character",
"characterImage": "/images/characters/char_xxx.webp"
}
],
"createdAt": "2024-01-01 00:00:00",
"updatedAt": "2024-01-01 00:00:00"
}
```
### Cast
```json
{
"id": 1,
"name": "Actor Name",
"cleanname": "actor-name",
"photo": "/images/cast/photo_xxx.webp",
"bio": "Biography text",
"birthDate": "1990-01-01",
"birthPlace": "City, Country",
"occupations": ["Actor", "Director"],
"filmography": [
{
"id": 1,
"title": "Movie Title",
"year": 2024,
"poster": "/images/movies/poster_xxx.webp",
"category": "movie",
"type": "Movie",
"role": "Actor",
"characterName": "Character"
}
],
"createdAt": "2024-01-01 00:00:00",
"updatedAt": "2024-01-01 00:00:00"
}
```
## Response Format
All responses follow this structure:
### Success
```json
{
"success": true,
"data": { ... }
}
```
### Error
```json
{
"success": false,
"error": "Error message"
}
```
### Paginated List
```json
{
"success": true,
"data": {
"items": [ ... ],
"total": 100,
"page": 1,
"limit": 20,
"totalPages": 5
}
}
```
## Configuration
Environment variables can be set in `docker-compose.yml` or as system environment variables:
- `DB_HOST` - Database host (default: `mariadb`)
- `DB_NAME` - Database name (default: `kyoo`)
- `DB_USER` - Database user (default: `kyoo_user`)
- `DB_PASS` - Database password (default: `kyoo_password`)
- `API_LOGGING_ENABLED` - Enable API logging (default: `false`)
## Docker Commands
### Start services
```bash
docker-compose up -d --build
```
### Stop services
```bash
docker-compose down
```
### View logs
```bash
# All logs
docker-compose logs
# Specific service
docker-compose logs php
docker-compose logs mariadb
```
### Reset database
```bash
docker-compose down -v
docker-compose up -d --build
```
## Development
The API files are mounted as volumes, so changes are immediately reflected without rebuilding.
### API Logging
Logs are written to:
- API requests/responses: `/var/www/html/logs/api.log`
- PHP errors: `/var/www/html/logs/php_error.log`
Enable logging by setting `API_LOGGING_ENABLED=true`.
## Troubleshooting
### PHP container won't start
```bash
docker-compose logs php
```
### Database connection errors
Check if MariaDB is running:
```bash
docker-compose ps
```
### Tables not created
Tables are auto-created on first API call. Check logs:
```bash
docker-compose logs php
```
## Swagger/OpenAPI Documentation
A Swagger/OpenAPI specification file is included at `swagger.json` in the project root. This file can be used with Swagger UI to interactively test the API.
### Using Swagger UI
#### Option 1: Online Swagger Editor
1. Go to [https://editor.swagger.io](https://editor.swagger.io)
2. Import the `swagger.json` file
3. Click "Try it out" to test endpoints
#### Option 2: Docker with Swagger UI
```bash
docker run -p 8080:8080 -e SWAGGER_JSON=/swagger/swagger.json -v $(pwd):/swagger swaggerapi/swagger-ui
```
Then access at: http://localhost:8080
#### Option 3: Local Swagger UI
1. Download Swagger UI from [https://github.com/swagger-api/swagger-ui](https://github.com/swagger-api/swagger-ui)
2. Extract and open `dist/index.html`
3. Modify the URL to point to your `swagger.json` file
### API Endpoints Covered
- Root endpoints (API info, auto-docs)
- Media CRUD operations
- Series episodes CRUD operations
- Music tracks CRUD operations
- Cast CRUD operations
- Adult cast CRUD operations
- Settings operations
## License
[Add your license here]

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/controllers/MediaController.php'; require_once __DIR__ . '/controllers/MediaController.php';
require_once __DIR__ . '/controllers/CastController.php'; require_once __DIR__ . '/controllers/CastController.php';
require_once __DIR__ . '/controllers/ImageController.php'; require_once __DIR__ . '/controllers/ImageController.php';
@@ -8,15 +10,15 @@ require_once __DIR__ . '/services/DocumentationService.php';
require_once __DIR__ . '/services/ApiLogger.php'; require_once __DIR__ . '/services/ApiLogger.php';
class Router { class Router {
private $pdo; private PDO $pdo;
private $mediaController; private MediaController $mediaController;
private $castController; private CastController $castController;
private $imageController; private ImageController $imageController;
private $settingsController; private SettingsController $settingsController;
private $documentationService; private DocumentationService $documentationService;
private $logger; private ApiLogger $logger;
public function __construct($pdo) { public function __construct(PDO $pdo) {
$this->pdo = $pdo; $this->pdo = $pdo;
$this->mediaController = new MediaController($pdo); $this->mediaController = new MediaController($pdo);
$this->castController = new CastController($pdo); $this->castController = new CastController($pdo);
@@ -25,27 +27,27 @@ class Router {
$this->documentationService = new DocumentationService(); $this->documentationService = new DocumentationService();
$this->logger = ApiLogger::getInstance(); $this->logger = ApiLogger::getInstance();
} }
public function route($method, $pathSegments) { public function route(string $method, array $pathSegments): array {
$path = '/' . implode('/', $pathSegments); $path = '/' . implode('/', $pathSegments);
$queryString = $_SERVER['QUERY_STRING'] ?? ''; $queryString = $_SERVER['QUERY_STRING'] ?? '';
$fullPath = $queryString ? $path . '?' . $queryString : $path; $fullPath = $queryString ? $path . '?' . $queryString : $path;
// Request loggen // Request loggen
$body = null; $body = null;
if ($method === 'POST' || $method === 'PUT') { if ($method === 'POST' || $method === 'PUT') {
$body = json_decode(file_get_contents('php://input'), true); $body = json_decode(file_get_contents('php://input'), true);
} }
$this->logger->logRequest($method, $fullPath, $_GET, $body); $this->logger->logRequest($method, $fullPath, $_GET, $body);
if (empty($pathSegments)) { if (empty($pathSegments)) {
$response = $this->getRoot(); $response = $this->getRoot();
$this->logger->logResponse($method, $fullPath, 200, $response); $this->logger->logResponse($method, $fullPath, 200, $response);
return $response; return $response;
} }
$resource = $pathSegments[0]; $resource = $pathSegments[0];
try { try {
switch ($resource) { switch ($resource) {
case 'images': case 'images':
@@ -77,20 +79,20 @@ class Router {
$this->logger->logResponse($method, $fullPath, 404, $response); $this->logger->logResponse($method, $fullPath, 404, $response);
return $response; return $response;
} }
} catch (Exception $e) { } catch (Throwable $e) {
http_response_code(500); http_response_code(500);
$response = ['success' => false, 'error' => $e->getMessage()]; $response = ['success' => false, 'error' => $e->getMessage()];
$this->logger->logError($method, $fullPath, $e->getMessage()); $this->logger->logError($method, $fullPath, $e->getMessage());
return $response; return $response;
} }
} }
private function getDocumentation() { private function getDocumentation(): array {
$docs = $this->documentationService->generateDocumentation(); $docs = $this->documentationService->generateDocumentation();
return ['success' => true, 'data' => $docs]; return ['success' => true, 'data' => $docs];
} }
private function getRoot() { private function getRoot(): array {
return [ return [
'success' => true, 'success' => true,
'message' => 'Media API v1.0', 'message' => 'Media API v1.0',

View File

@@ -1,4 +1,7 @@
<?php <?php
declare(strict_types=1);
// Konfiguration // Konfiguration
// Docker-Umgebungsvariablen oder Standardwerte // Docker-Umgebungsvariablen oder Standardwerte
define('DB_HOST', getenv('DB_HOST') ?: 'mariadb'); define('DB_HOST', getenv('DB_HOST') ?: 'mariadb');
@@ -15,7 +18,7 @@ define('API_LOG_FILE', '/var/www/html/logs/api.log');
define('PHP_ERROR_LOG_FILE', '/var/www/html/logs/php_error.log'); define('PHP_ERROR_LOG_FILE', '/var/www/html/logs/php_error.log');
// Hilfsfunktion für cleanname Generierung // Hilfsfunktion für cleanname Generierung
function generateCleanName($name) { function generateCleanName(string $name): string {
// Kleinbuchstaben, nur alphanumerische Zeichen und Bindestriche // Kleinbuchstaben, nur alphanumerische Zeichen und Bindestriche
$clean = strtolower($name); $clean = strtolower($name);
// Sonderzeichen durch Bindestriche ersetzen // Sonderzeichen durch Bindestriche ersetzen

View File

@@ -1,21 +1,23 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/../models/Cast.php'; require_once __DIR__ . '/../models/Cast.php';
require_once __DIR__ . '/../models/AdultCast.php'; require_once __DIR__ . '/../models/AdultCast.php';
require_once __DIR__ . '/../services/ApiLogger.php'; require_once __DIR__ . '/../services/ApiLogger.php';
class CastController { class CastController {
private $cast; private Cast $cast;
private $adultCast; private AdultCast $adultCast;
private $logger; private ApiLogger $logger;
public function __construct($pdo) { public function __construct(PDO $pdo) {
$this->cast = new Cast($pdo); $this->cast = new Cast($pdo);
$this->adultCast = new AdultCast($pdo); $this->adultCast = new AdultCast($pdo);
$this->logger = ApiLogger::getInstance(); $this->logger = ApiLogger::getInstance();
} }
public function handleRequest($method, $segments) { public function handleRequest(string $method, array $segments): array {
$id = isset($segments[1]) ? (int)$segments[1] : null; $id = isset($segments[1]) ? (int)$segments[1] : null;
$subResource = isset($segments[2]) ? $segments[2] : null; $subResource = isset($segments[2]) ? $segments[2] : null;
@@ -26,7 +28,7 @@ class CastController {
// die("adult"); // die("adult");
return $this->handleAdult($method, $id, $segments); return $this->handleAdult($method, $id, $segments);
} }
switch ($method) { switch ($method) {
case 'GET': case 'GET':
return $id ? $this->getOne($id, $segments) : $this->getAll(); return $id ? $this->getOne($id, $segments) : $this->getAll();
@@ -42,7 +44,7 @@ class CastController {
} }
} }
private function handleAdult($method, $id, $segments) { private function handleAdult(string $method, ?int $id, array $segments): array {
switch ($method) { switch ($method) {
case 'GET': case 'GET':
@@ -62,7 +64,7 @@ class CastController {
} }
} }
private function getAdultAll() { private function getAdultAll(): array {
$filters = []; $filters = [];
if (isset($_GET['search'])) $filters['search'] = $_GET['search']; if (isset($_GET['search'])) $filters['search'] = $_GET['search'];
if (isset($_GET['ethnicity'])) $filters['ethnicity'] = $_GET['ethnicity']; if (isset($_GET['ethnicity'])) $filters['ethnicity'] = $_GET['ethnicity'];
@@ -75,7 +77,7 @@ class CastController {
return ['success' => true, 'data' => $result]; return ['success' => true, 'data' => $result];
} }
private function getAdultOne($id) { private function getAdultOne(?int $id): array {
$cast = $this->adultCast->getWithAdultSpecifics($id); $cast = $this->adultCast->getWithAdultSpecifics($id);
if (!$cast) { if (!$cast) {
http_response_code(404); http_response_code(404);
@@ -84,7 +86,7 @@ class CastController {
return ['success' => true, 'data' => $cast]; return ['success' => true, 'data' => $cast];
} }
private function createAdult() { private function createAdult(): array {
$data = json_decode(file_get_contents('php://input'), true); $data = json_decode(file_get_contents('php://input'), true);
if (!$data) { if (!$data) {
http_response_code(400); http_response_code(400);
@@ -119,7 +121,7 @@ class CastController {
return ['success' => true, 'data' => ['id' => $castId]]; return ['success' => true, 'data' => ['id' => $castId]];
} }
private function updateAdult($id) { private function updateAdult(?int $id): array {
if (!$id) { if (!$id) {
http_response_code(400); http_response_code(400);
return ['success' => false, 'error' => 'ID required']; return ['success' => false, 'error' => 'ID required'];
@@ -137,7 +139,7 @@ class CastController {
return ['success' => true, 'data' => ['id' => $id]]; return ['success' => true, 'data' => ['id' => $id]];
} }
private function deleteAdultSpecifics($id) { private function deleteAdultSpecifics(?int $id): array {
if (!$id) { if (!$id) {
http_response_code(400); http_response_code(400);
return ['success' => false, 'error' => 'ID required']; return ['success' => false, 'error' => 'ID required'];
@@ -152,7 +154,7 @@ class CastController {
$this->logger->logResponse('DELETE', "/api/cast/adult/$id", 200, ['message' => 'Adult specifics deleted successfully']); $this->logger->logResponse('DELETE', "/api/cast/adult/$id", 200, ['message' => 'Adult specifics deleted successfully']);
return ['success' => true, 'message' => 'Adult specifics deleted successfully']; return ['success' => true, 'message' => 'Adult specifics deleted successfully'];
} }
private function getOne($id, $segments) { private function getOne(?int $id, array $segments): array {
// Prüfen ob /media angehängt wurde // Prüfen ob /media angehängt wurde
if (isset($segments[2]) && $segments[2] === 'media') { if (isset($segments[2]) && $segments[2] === 'media') {
return $this->getMedia($id); return $this->getMedia($id);
@@ -169,12 +171,12 @@ class CastController {
return ['success' => true, 'data' => $cast]; return ['success' => true, 'data' => $cast];
} }
private function getMedia($castId) { private function getMedia(?int $castId): array {
$media = $this->cast->getMediaForCast($castId); $media = $this->cast->getMediaForCast($castId);
return ['success' => true, 'data' => ['items' => $media]]; return ['success' => true, 'data' => ['items' => $media]];
} }
private function getAll() { private function getAll(): array {
$filters = []; $filters = [];
if (isset($_GET['search'])) $filters['search'] = $_GET['search']; if (isset($_GET['search'])) $filters['search'] = $_GET['search'];
@@ -185,7 +187,7 @@ class CastController {
return ['success' => true, 'data' => $result]; return ['success' => true, 'data' => $result];
} }
private function create() { private function create(): array {
$data = json_decode(file_get_contents('php://input'), true); $data = json_decode(file_get_contents('php://input'), true);
if (!$data) { if (!$data) {
http_response_code(400); http_response_code(400);
@@ -220,7 +222,7 @@ class CastController {
return ['success' => true, 'data' => ['id' => $castId]]; return ['success' => true, 'data' => ['id' => $castId]];
} }
private function update($id) { private function update(?int $id): array {
if (!$id) { if (!$id) {
http_response_code(400); http_response_code(400);
return ['success' => false, 'error' => 'ID required']; return ['success' => false, 'error' => 'ID required'];
@@ -238,7 +240,7 @@ class CastController {
return ['success' => true, 'data' => ['id' => $id]]; return ['success' => true, 'data' => ['id' => $id]];
} }
private function delete($id) { private function delete(?int $id): array {
if (!$id) { if (!$id) {
http_response_code(400); http_response_code(400);
return ['success' => false, 'error' => 'ID required']; return ['success' => false, 'error' => 'ID required'];

View File

@@ -1,46 +1,48 @@
<?php <?php
declare(strict_types=1);
class ImageController { class ImageController {
private $imageDir; private string $imageDir;
public function __construct() { public function __construct() {
$this->imageDir = __DIR__ . '/../public/images/'; $this->imageDir = __DIR__ . '/../public/images/';
} }
public function handleRequest($method, $pathSegments) { public function handleRequest(string $method, array $pathSegments): array {
// Remove 'images' from path segments // Remove 'images' from path segments
array_shift($pathSegments); array_shift($pathSegments);
// Build file path // Build file path
$imagePath = implode('/', $pathSegments); $imagePath = implode('/', $pathSegments);
$fullPath = $this->imageDir . $imagePath; $fullPath = $this->imageDir . $imagePath;
// Security check: ensure the path is within the images directory // Security check: ensure the path is within the images directory
$realPath = realpath($fullPath); $realPath = realpath($fullPath);
$realImageDir = realpath($this->imageDir); $realImageDir = realpath($this->imageDir);
if ($realPath === false || strpos($realPath, $realImageDir) !== 0) { if ($realPath === false || strpos($realPath, $realImageDir) !== 0) {
http_response_code(403); http_response_code(403);
return ['success' => false, 'error' => 'Access denied']; return ['success' => false, 'error' => 'Access denied'];
} }
// Check if file exists // Check if file exists
if (!file_exists($realPath)) { if (!file_exists($realPath)) {
http_response_code(404); http_response_code(404);
return ['success' => false, 'error' => 'Image not found']; return ['success' => false, 'error' => 'Image not found'];
} }
// Check if it's actually a file // Check if it's actually a file
if (!is_file($realPath)) { if (!is_file($realPath)) {
http_response_code(404); http_response_code(404);
return ['success' => false, 'error' => 'Not a file']; return ['success' => false, 'error' => 'Not a file'];
} }
// Get file info // Get file info
$fileInfo = finfo_open(FILEINFO_MIME_TYPE); $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($fileInfo, $realPath); $mimeType = finfo_file($fileInfo, $realPath);
finfo_close($fileInfo); finfo_close($fileInfo);
if ($mimeType === false) { if ($mimeType === false) {
// Fallback to common image types // Fallback to common image types
$extension = strtolower(pathinfo($realPath, PATHINFO_EXTENSION)); $extension = strtolower(pathinfo($realPath, PATHINFO_EXTENSION));
@@ -54,13 +56,13 @@ class ImageController {
]; ];
$mimeType = $mimeTypes[$extension] ?? 'application/octet-stream'; $mimeType = $mimeTypes[$extension] ?? 'application/octet-stream';
} }
// Set headers for image serving // Set headers for image serving
header('Content-Type: ' . $mimeType); header('Content-Type: ' . $mimeType);
header('Content-Length: ' . filesize($realPath)); header('Content-Length: ' . filesize($realPath));
header('Cache-Control: public, max-age=31536000'); // Cache for 1 year header('Cache-Control: public, max-age=31536000'); // Cache for 1 year
header('Pragma: public'); header('Pragma: public');
// Output the image // Output the image
readfile($realPath); readfile($realPath);
exit; exit;

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/../models/Media.php'; require_once __DIR__ . '/../models/Media.php';
require_once __DIR__ . '/../models/Series.php'; require_once __DIR__ . '/../models/Series.php';
require_once __DIR__ . '/../models/Music.php'; require_once __DIR__ . '/../models/Music.php';
@@ -7,24 +9,24 @@ require_once __DIR__ . '/../models/Game.php';
require_once __DIR__ . '/../services/ApiLogger.php'; require_once __DIR__ . '/../services/ApiLogger.php';
class MediaController { class MediaController {
private $media; private Media $media;
private $series; private Series $series;
private $music; private Music $music;
private $game; private Game $game;
private $logger; private ApiLogger $logger;
public function __construct($pdo) { public function __construct(PDO $pdo) {
$this->media = new Media($pdo); $this->media = new Media($pdo);
$this->series = new Series($pdo); $this->series = new Series($pdo);
$this->music = new Music($pdo); $this->music = new Music($pdo);
$this->game = new Game($pdo); $this->game = new Game($pdo);
$this->logger = ApiLogger::getInstance(); $this->logger = ApiLogger::getInstance();
} }
public function handleRequest($method, $segments) { public function handleRequest(string $method, array $segments): array {
$id = isset($segments[1]) ? (int)$segments[1] : null; $id = isset($segments[1]) ? (int)$segments[1] : null;
$subResource = isset($segments[2]) ? $segments[2] : null; $subResource = isset($segments[2]) ? $segments[2] : null;
// Sub-Endpunkte für Episoden und Tracks // Sub-Endpunkte für Episoden und Tracks
if ($id && $subResource) { if ($id && $subResource) {
if ($subResource === 'episodes') { if ($subResource === 'episodes') {
@@ -34,7 +36,7 @@ class MediaController {
return $this->handleTracks($method, $id, $segments); return $this->handleTracks($method, $id, $segments);
} }
} }
switch ($method) { switch ($method) {
case 'GET': case 'GET':
return $id ? $this->getOne($id) : $this->getAll(); return $id ? $this->getOne($id) : $this->getAll();
@@ -50,7 +52,7 @@ class MediaController {
} }
} }
private function handleEpisodes($method, $mediaId, $segments) { private function handleEpisodes(string $method, ?int $mediaId, array $segments): array {
$episodeId = isset($segments[3]) ? (int)$segments[3] : null; $episodeId = isset($segments[3]) ? (int)$segments[3] : null;
switch ($method) { switch ($method) {
@@ -71,7 +73,7 @@ class MediaController {
} }
} }
private function handleTracks($method, $mediaId, $segments) { private function handleTracks(string $method, ?int $mediaId, array $segments): array {
$trackId = isset($segments[3]) ? (int)$segments[3] : null; $trackId = isset($segments[3]) ? (int)$segments[3] : null;
switch ($method) { switch ($method) {
@@ -92,7 +94,7 @@ class MediaController {
} }
} }
private function getEpisodes($mediaId) { private function getEpisodes(?int $mediaId): array {
$season = isset($_GET['season']) ? (int)$_GET['season'] : null; $season = isset($_GET['season']) ? (int)$_GET['season'] : null;
$episodes = $this->series->getEpisodes($mediaId, $season); $episodes = $this->series->getEpisodes($mediaId, $season);
return ['success' => true, 'data' => ['items' => $episodes]]; return ['success' => true, 'data' => ['items' => $episodes]];
@@ -103,7 +105,7 @@ class MediaController {
* @param int $mediaId Media ID * @param int $mediaId Media ID
* @return array Created episode ID * @return array Created episode ID
*/ */
private function addEpisode($mediaId) { private function addEpisode(?int $mediaId): array {
$data = json_decode(file_get_contents('php://input'), true); $data = json_decode(file_get_contents('php://input'), true);
if (!$data) { if (!$data) {
http_response_code(400); http_response_code(400);
@@ -120,7 +122,7 @@ class MediaController {
* @param int $episodeId Episode ID * @param int $episodeId Episode ID
* @return array Updated episode ID * @return array Updated episode ID
*/ */
private function updateEpisode($episodeId) { private function updateEpisode(?int $episodeId): array {
if (!$episodeId) { if (!$episodeId) {
http_response_code(400); http_response_code(400);
return ['success' => false, 'error' => 'Episode ID required']; return ['success' => false, 'error' => 'Episode ID required'];
@@ -141,7 +143,7 @@ class MediaController {
* @param int $episodeId Episode ID * @param int $episodeId Episode ID
* @return array Success message * @return array Success message
*/ */
private function deleteEpisode($episodeId) { private function deleteEpisode(?int $episodeId): array {
if (!$episodeId) { if (!$episodeId) {
http_response_code(400); http_response_code(400);
return ['success' => false, 'error' => 'Episode ID required']; return ['success' => false, 'error' => 'Episode ID required'];
@@ -160,7 +162,7 @@ class MediaController {
* @param int $episodeId Episode ID * @param int $episodeId Episode ID
* @return array Episode data * @return array Episode data
*/ */
private function getEpisode($episodeId) { private function getEpisode(?int $episodeId): array {
// Episode direkt aus Datenbank abrufen // Episode direkt aus Datenbank abrufen
$stmt = $this->series->getConnection()->prepare("SELECT * FROM episodes WHERE id = ?"); $stmt = $this->series->getConnection()->prepare("SELECT * FROM episodes WHERE id = ?");
$stmt->execute([$episodeId]); $stmt->execute([$episodeId]);
@@ -173,12 +175,12 @@ class MediaController {
return ['success' => true, 'data' => $episode]; return ['success' => true, 'data' => $episode];
} }
private function getTracks($mediaId) { private function getTracks(?int $mediaId): array {
$tracks = $this->music->getTracks($mediaId); $tracks = $this->music->getTracks($mediaId);
return ['success' => true, 'data' => ['items' => $tracks]]; return ['success' => true, 'data' => ['items' => $tracks]];
} }
private function addTrack($mediaId) { private function addTrack(?int $mediaId): array {
$data = json_decode(file_get_contents('php://input'), true); $data = json_decode(file_get_contents('php://input'), true);
if (!$data) { if (!$data) {
http_response_code(400); http_response_code(400);
@@ -190,7 +192,7 @@ class MediaController {
return ['success' => true, 'data' => ['id' => $trackId]]; return ['success' => true, 'data' => ['id' => $trackId]];
} }
private function updateTrack($trackId) { private function updateTrack(?int $trackId): array {
if (!$trackId) { if (!$trackId) {
http_response_code(400); http_response_code(400);
return ['success' => false, 'error' => 'Track ID required']; return ['success' => false, 'error' => 'Track ID required'];
@@ -206,7 +208,7 @@ class MediaController {
return ['success' => true, 'data' => ['id' => $trackId]]; return ['success' => true, 'data' => ['id' => $trackId]];
} }
private function deleteTrack($trackId) { private function deleteTrack(?int $trackId): array {
if (!$trackId) { if (!$trackId) {
http_response_code(400); http_response_code(400);
return ['success' => false, 'error' => 'Track ID required']; return ['success' => false, 'error' => 'Track ID required'];
@@ -220,7 +222,7 @@ class MediaController {
return ['success' => true, 'message' => 'Track deleted successfully']; return ['success' => true, 'message' => 'Track deleted successfully'];
} }
private function getTrack($trackId) { private function getTrack(?int $trackId): array {
// Track direkt aus Datenbank abrufen // Track direkt aus Datenbank abrufen
$stmt = $this->music->getConnection()->prepare("SELECT * FROM tracks WHERE id = ?"); $stmt = $this->music->getConnection()->prepare("SELECT * FROM tracks WHERE id = ?");
$stmt->execute([$trackId]); $stmt->execute([$trackId]);
@@ -238,7 +240,7 @@ class MediaController {
* @param int $id Media ID * @param int $id Media ID
* @return array Media object with relations * @return array Media object with relations
*/ */
private function getOne($id) { private function getOne(?int $id): array {
// Zuerst Basis-Media abrufen um Typ zu bestimmen // Zuerst Basis-Media abrufen um Typ zu bestimmen
$baseMedia = $this->media->getBase($id); $baseMedia = $this->media->getBase($id);
if (!$baseMedia) { if (!$baseMedia) {
@@ -268,7 +270,7 @@ class MediaController {
* Get all media items with filtering and pagination * Get all media items with filtering and pagination
* @return array Paginated media list * @return array Paginated media list
*/ */
private function getAll() { private function getAll(): array {
$filters = []; $filters = [];
if (isset($_GET['category'])) $filters['category'] = $_GET['category']; if (isset($_GET['category'])) $filters['category'] = $_GET['category'];
if (isset($_GET['type'])) $filters['type'] = $_GET['type']; if (isset($_GET['type'])) $filters['type'] = $_GET['type'];
@@ -278,17 +280,7 @@ class MediaController {
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20; $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
$result = $this->media->search($filters, $page, $limit); $result = $this->media->search($filters, $page, $limit);
// Game-spezifische Daten für Games laden
foreach ($result['items'] as &$item) {
if ($item['type'] === 'Game') {
$gameInfo = $this->game->getGameInfoForList($item['id']);
if ($gameInfo) {
$item = array_merge($item, $gameInfo);
}
}
}
return ['success' => true, 'data' => $result]; return ['success' => true, 'data' => $result];
} }
@@ -296,7 +288,7 @@ class MediaController {
* Create a new media item * Create a new media item
* @return array Created media ID * @return array Created media ID
*/ */
private function create() { private function create(): array {
$data = json_decode(file_get_contents('php://input'), true); $data = json_decode(file_get_contents('php://input'), true);
if (!$data) { if (!$data) {
http_response_code(400); http_response_code(400);
@@ -351,7 +343,7 @@ class MediaController {
* @param int $id Media ID * @param int $id Media ID
* @return array Updated media ID * @return array Updated media ID
*/ */
private function update($id) { private function update(?int $id): array {
if (!$id) { if (!$id) {
http_response_code(400); http_response_code(400);
return ['success' => false, 'error' => 'ID required']; return ['success' => false, 'error' => 'ID required'];
@@ -385,7 +377,7 @@ class MediaController {
* @param int $id Media ID * @param int $id Media ID
* @return array Success message * @return array Success message
*/ */
private function delete($id) { private function delete(?int $id): array {
if (!$id) { if (!$id) {
http_response_code(400); http_response_code(400);
return ['success' => false, 'error' => 'ID required']; return ['success' => false, 'error' => 'ID required'];

View File

@@ -1,21 +1,23 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/../models/Settings.php'; require_once __DIR__ . '/../models/Settings.php';
require_once __DIR__ . '/../services/ApiLogger.php'; require_once __DIR__ . '/../services/ApiLogger.php';
class SettingsController { class SettingsController {
private $settings; private Settings $settings;
private $logger; private ApiLogger $logger;
public function __construct($pdo) { public function __construct(PDO $pdo) {
$this->settings = new Settings($pdo); $this->settings = new Settings($pdo);
$this->logger = ApiLogger::getInstance(); $this->logger = ApiLogger::getInstance();
} }
public function handleRequest($method, $segments) { public function handleRequest(string $method, array $segments): array {
$path = '/' . implode('/', $segments); $path = '/' . implode('/', $segments);
$this->logger->logRequest($method, $path); $this->logger->logRequest($method, $path);
switch ($method) { switch ($method) {
case 'GET': case 'GET':
return $this->get(); return $this->get();
@@ -26,36 +28,36 @@ class SettingsController {
return ['success' => false, 'error' => 'Method not allowed']; return ['success' => false, 'error' => 'Method not allowed'];
} }
} }
private function get() { private function get(): array {
$settings = $this->settings->getSettings(); $settings = $this->settings->getSettings();
if (!$settings) { if (!$settings) {
http_response_code(404); http_response_code(404);
return ['success' => false, 'error' => 'Settings not found']; return ['success' => false, 'error' => 'Settings not found'];
} }
return ['success' => true, 'data' => $settings]; return ['success' => true, 'data' => $settings];
} }
private function update() { private function update(): array {
$data = json_decode(file_get_contents('php://input'), true); $data = json_decode(file_get_contents('php://input'), true);
if (!$data) { if (!$data) {
http_response_code(400); http_response_code(400);
return ['success' => false, 'error' => 'Invalid JSON']; return ['success' => false, 'error' => 'Invalid JSON'];
} }
$settings = $this->settings->updateSettings($data); $settings = $this->settings->updateSettings($data);
if (!$settings) { if (!$settings) {
http_response_code(500); http_response_code(500);
return ['success' => false, 'error' => 'Failed to update settings']; return ['success' => false, 'error' => 'Failed to update settings'];
} }
$this->logger->logRequest('PUT', '/api/settings', [], $data); $this->logger->logRequest('PUT', '/api/settings', [], $data);
$this->logger->logResponse('PUT', '/api/settings', 200, $settings); $this->logger->logResponse('PUT', '/api/settings', 200, $settings);
return ['success' => true, 'data' => $settings]; return ['success' => true, 'data' => $settings];
} }
} }

View File

@@ -1,9 +1,12 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/config.php'; require_once __DIR__ . '/config.php';
class Database { class Database {
private $pdo; private ?PDO $pdo;
public function __construct() { public function __construct() {
try { try {
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4'; $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4';
@@ -17,8 +20,8 @@ class Database {
exit; exit;
} }
} }
private function initializeTables() { private function initializeTables(): void {
// Media-Tabelle // Media-Tabelle
$this->pdo->exec(" $this->pdo->exec("
CREATE TABLE IF NOT EXISTS media ( CREATE TABLE IF NOT EXISTS media (
@@ -357,6 +360,7 @@ class Database {
auto_play_trailers BOOLEAN DEFAULT 0, auto_play_trailers BOOLEAN DEFAULT 0,
language TEXT DEFAULT 'en', language TEXT DEFAULT 'en',
theme TEXT DEFAULT 'system', theme TEXT DEFAULT 'system',
jellyfin_library_mappings JSON,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) )
@@ -365,8 +369,8 @@ class Database {
// Bestehende Einträge mit cleanname aktualisieren // Bestehende Einträge mit cleanname aktualisieren
$this->updateExistingCleanNames(); $this->updateExistingCleanNames();
} }
private function updateExistingCleanNames() { private function updateExistingCleanNames(): void {
// Media cleanname aktualisieren // Media cleanname aktualisieren
$this->pdo->exec(" $this->pdo->exec("
UPDATE media UPDATE media
@@ -381,8 +385,8 @@ class Database {
WHERE cleanname IS NULL OR cleanname = '' WHERE cleanname IS NULL OR cleanname = ''
"); ");
} }
public function getConnection() { public function getConnection(): PDO {
return $this->pdo; return $this->pdo;
} }
} }

View File

@@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
error_log("API Request: " . $_SERVER['REQUEST_METHOD'] . " " . $_SERVER['REQUEST_URI']); error_log("API Request: " . $_SERVER['REQUEST_METHOD'] . " " . $_SERVER['REQUEST_URI']);
require_once __DIR__ . '/config.php'; require_once __DIR__ . '/config.php';
require_once __DIR__ . '/database.php'; require_once __DIR__ . '/database.php';
@@ -31,7 +33,7 @@ $router = new Router($pdo);
try { try {
$response = $router->route($method, $pathSegments); $response = $router->route($method, $pathSegments);
echo json_encode($response); echo json_encode($response);
} catch (Exception $e) { } catch (Throwable $e) {
http_response_code(500); http_response_code(500);
echo json_encode(['success' => false, 'error' => $e->getMessage()]); echo json_encode(['success' => false, 'error' => $e->getMessage()]);
} }

View File

@@ -1,34 +1,37 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/MediaType.php'; require_once __DIR__ . '/MediaType.php';
require_once __DIR__ . '/../services/ImageHandler.php'; require_once __DIR__ . '/../services/ImageHandler.php';
class Adult extends MediaType { class Adult extends MediaType {
private $imageHandler; private ImageHandler $imageHandler;
private $isUpdate = false; private bool $isUpdate = false;
private $mediaId = null; private ?int $mediaId = null;
public function __construct($pdo) { public function __construct(PDO $pdo) {
parent::__construct($pdo); parent::__construct($pdo);
$this->imageHandler = new ImageHandler(); $this->imageHandler = new ImageHandler();
} }
protected function getType() { protected function getType(): string {
return 'Adult'; return 'Adult';
} }
protected function getTypeSpecificFields() { protected function getTypeSpecificFields(): array {
return []; return [];
} }
protected function validateTypeSpecificFields($data) { protected function validateTypeSpecificFields(array $data): array {
// Adult spezifische Validierung // Adult spezifische Validierung
// Eventuell Altersverifikation etc. // Eventuell Altersverifikation etc.
return $data;
} }
protected function processPosterField($data) { protected function processPosterField(array $data): array {
error_log("Adult::processPosterField - Checking for poster field, isUpdate: " . ($this->isUpdate ? 'yes' : 'no')); error_log("Adult::processPosterField - Checking for poster field, isUpdate: " . ($this->isUpdate ? 'yes' : 'no'));
if ($this->isUpdate && $this->mediaId && isset($data['poster']) && !empty($data['poster'])) { if ($this->isUpdate && $this->mediaId && isset($data['poster']) && !empty($data['poster'])) {
$currentMedia = $this->findById($this->mediaId); $currentMedia = $this->findById($this->mediaId);
if ($currentMedia && !empty($currentMedia['poster'])) { if ($currentMedia && !empty($currentMedia['poster'])) {
@@ -39,15 +42,15 @@ class Adult extends MediaType {
} }
} }
} }
if (isset($data['poster']) && !empty($data['poster'])) { if (isset($data['poster']) && !empty($data['poster'])) {
error_log("Adult::processPosterField - Poster found, length: " . strlen($data['poster'])); error_log("Adult::processPosterField - Poster found, length: " . strlen($data['poster']));
if (strpos($data['poster'], '/images/') === 0 || filter_var($data['poster'], FILTER_VALIDATE_URL)) { if (strpos($data['poster'], '/images/') === 0 || filter_var($data['poster'], FILTER_VALIDATE_URL)) {
error_log("Adult::processPosterField - Poster is already a path or URL, skipping processing"); error_log("Adult::processPosterField - Poster is already a path or URL, skipping processing");
return $data; return $data;
} }
$posterPath = $this->imageHandler->saveBase64Image($data['poster'], 'adult/poster'); $posterPath = $this->imageHandler->saveBase64Image($data['poster'], 'adult/poster');
error_log("Adult::processPosterField - ImageHandler returned: " . ($posterPath ?: 'null')); error_log("Adult::processPosterField - ImageHandler returned: " . ($posterPath ?: 'null'));
if ($posterPath) { if ($posterPath) {
@@ -61,23 +64,23 @@ class Adult extends MediaType {
} }
return $data; return $data;
} }
public function createWithRelations($data) { public function createWithRelations(array $data): int {
$data['type'] = 'Adult'; $data['type'] = 'Adult';
$this->validateTypeSpecificFields($data); $this->validateTypeSpecificFields($data);
$data = $this->processPosterField($data); $data = $this->processPosterField($data);
return parent::createWithRelations($data); return parent::createWithRelations($data);
} }
public function updateWithRelations($id, $data) { public function updateWithRelations(int $id, array $data): bool {
$this->isUpdate = true; $this->isUpdate = true;
$this->mediaId = $id; $this->mediaId = $id;
$this->validateTypeSpecificFields($data); $this->validateTypeSpecificFields($data);
$data = $this->processPosterField($data); $data = $this->processPosterField($data);
parent::updateWithRelations($id, $data); return parent::updateWithRelations($id, $data);
} }
public function search($filters = [], $page = 1, $limit = 20) { public function search(array $filters = [], int $page = 1, int $limit = 20): array {
// Nur Adult Content suchen // Nur Adult Content suchen
$filters['type'] = 'Adult'; $filters['type'] = 'Adult';
return parent::search($filters, $page, $limit); return parent::search($filters, $page, $limit);

View File

@@ -1,41 +1,43 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/Cast.php'; require_once __DIR__ . '/Cast.php';
require_once __DIR__ . '/../services/ApiLogger.php'; require_once __DIR__ . '/../services/ApiLogger.php';
class AdultCast extends Cast { class AdultCast extends Cast {
public function getWithAdultSpecifics($id) { public function getWithAdultSpecifics(?int $id): ?array {
$cast = $this->getWithFilmography($id); $cast = $this->getWithFilmography($id);
if (!$cast) { if (!$cast) {
return null; return null;
} }
$cast['adult_specifics'] = $this->getAdultSpecifics($id); $cast['adult_specifics'] = $this->getAdultSpecifics($id);
return $cast; return $cast;
} }
public function getAdultSpecifics($castId) { public function getAdultSpecifics(?int $castId): array|false {
$stmt = $this->pdo->prepare("SELECT * FROM adult_cast_specifics WHERE cast_id = ?"); $stmt = $this->pdo->prepare("SELECT * FROM adult_cast_specifics WHERE cast_id = ?");
$stmt->execute([$castId]); $stmt->execute([$castId]);
return $stmt->fetch(); return $stmt->fetch();
} }
public function createWithAdultSpecifics($data) { public function createWithAdultSpecifics(array $data): int {
ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics called with data: " . json_encode($data)); ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics called with data: " . json_encode($data));
$name = $data['name'] ?? null; $name = $data['name'] ?? null;
if (!$name) { if (!$name) {
throw new Exception('Name is required'); throw new Exception('Name is required');
} }
// cleanname generieren // cleanname generieren
$cleanname = generateCleanName($name); $cleanname = generateCleanName($name);
// Process photo field (base64 to file path) // Process photo field (base64 to file path)
$data = $this->processPhotoField($data); $data = $this->processPhotoField($data);
// Zuerst Basis-Cast erstellen // Zuerst Basis-Cast erstellen
$castData = [ $castData = [
'name' => $name, 'name' => $name,
@@ -45,16 +47,16 @@ class AdultCast extends Cast {
'birthDate' => $data['birthDate'] ?? null, 'birthDate' => $data['birthDate'] ?? null,
'birthPlace' => $data['birthPlace'] ?? null 'birthPlace' => $data['birthPlace'] ?? null
]; ];
$castId = $this->create($castData); $castId = (int)$this->create($castData);
ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics: Base cast created with id: $castId"); ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics: Base cast created with id: $castId");
// Occupations speichern // Occupations speichern
if (isset($data['occupations']) && is_array($data['occupations'])) { if (isset($data['occupations']) && is_array($data['occupations'])) {
ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics: Saving occupations: " . json_encode($data['occupations'])); ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics: Saving occupations: " . json_encode($data['occupations']));
$this->saveRelatedItems('occupations', $castId, $data['occupations'], 'cast_id'); $this->saveRelatedItems('occupations', $castId, $data['occupations'], 'cast_id');
} }
// Adult-spezifische Daten speichern // Adult-spezifische Daten speichern
if (isset($data['adult_specifics']) && is_array($data['adult_specifics'])) { if (isset($data['adult_specifics']) && is_array($data['adult_specifics'])) {
ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics: Saving adult_specifics"); ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics: Saving adult_specifics");
@@ -62,20 +64,20 @@ class AdultCast extends Cast {
} else { } else {
ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics: No adult_specifics found in data"); ApiLogger::getInstance()->logDebug("AdultCast createWithAdultSpecifics: No adult_specifics found in data");
} }
return $castId; return $castId;
} }
public function updateWithAdultSpecifics($id, $data) { public function updateWithAdultSpecifics(int $id, array $data): bool {
ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics called with id: $id, data: " . json_encode($data)); ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics called with id: $id, data: " . json_encode($data));
// Set update flag for image replacement // Set update flag for image replacement
$this->isUpdate = true; $this->isUpdate = true;
$this->castId = $id; $this->castId = $id;
// Process photo field (base64 to file path) // Process photo field (base64 to file path)
$data = $this->processPhotoField($data); $data = $this->processPhotoField($data);
// Basis-Cast aktualisieren // Basis-Cast aktualisieren
$castData = []; $castData = [];
foreach (['name', 'photo', 'bio', 'birthDate', 'birthPlace'] as $field) { foreach (['name', 'photo', 'bio', 'birthDate', 'birthPlace'] as $field) {
@@ -83,19 +85,19 @@ class AdultCast extends Cast {
$castData[$field] = $data[$field]; $castData[$field] = $data[$field];
} }
} }
if (!empty($castData)) { if (!empty($castData)) {
ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics: Updating base cast data: " . json_encode($castData)); ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics: Updating base cast data: " . json_encode($castData));
$this->update($id, $castData); $this->update($id, $castData);
} }
// Occupations aktualisieren // Occupations aktualisieren
if (isset($data['occupations']) && is_array($data['occupations'])) { if (isset($data['occupations']) && is_array($data['occupations'])) {
ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics: Updating occupations: " . json_encode($data['occupations'])); ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics: Updating occupations: " . json_encode($data['occupations']));
$this->pdo->prepare("DELETE FROM occupations WHERE cast_id = ?")->execute([$id]); $this->pdo->prepare("DELETE FROM occupations WHERE cast_id = ?")->execute([$id]);
$this->saveRelatedItems('occupations', $id, $data['occupations'], 'cast_id'); $this->saveRelatedItems('occupations', $id, $data['occupations'], 'cast_id');
} }
// Adult-spezifische Daten aktualisieren // Adult-spezifische Daten aktualisieren
if (isset($data['adult_specifics']) && is_array($data['adult_specifics'])) { if (isset($data['adult_specifics']) && is_array($data['adult_specifics'])) {
ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics: Saving adult_specifics"); ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics: Saving adult_specifics");
@@ -104,11 +106,11 @@ class AdultCast extends Cast {
} else { } else {
ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics: No adult_specifics found in data"); ApiLogger::getInstance()->logDebug("AdultCast updateWithAdultSpecifics: No adult_specifics found in data");
} }
return true; return true;
} }
protected function saveAdultSpecifics($castId, $specifics) { protected function saveAdultSpecifics(int $castId, array $specifics): void {
ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics called for cast_id: $castId"); ApiLogger::getInstance()->logDebug("AdultCast saveAdultSpecifics called for cast_id: $castId");
ApiLogger::getInstance()->logDebug("Specifics data: " . json_encode($specifics)); ApiLogger::getInstance()->logDebug("Specifics data: " . json_encode($specifics));
@@ -200,13 +202,13 @@ class AdultCast extends Cast {
} }
} }
public function deleteAdultSpecifics($castId) { public function deleteAdultSpecifics(?int $castId): bool {
$stmt = $this->pdo->prepare("DELETE FROM adult_cast_specifics WHERE cast_id = ?"); $stmt = $this->pdo->prepare("DELETE FROM adult_cast_specifics WHERE cast_id = ?");
$stmt->execute([$castId]); $stmt->execute([$castId]);
return $stmt->rowCount() > 0; return $stmt->rowCount() > 0;
} }
public function searchAdultActors($filters = [], $page = 1, $limit = 2000000000) { public function searchAdultActors(array $filters = [], int $page = 1, int $limit = 2000000000): array {
// Adult Actors mit Specifics suchen // Adult Actors mit Specifics suchen
$query = " $query = "
SELECT cs.*, SELECT cs.*,

View File

@@ -1,23 +1,25 @@
<?php <?php
declare(strict_types=1);
abstract class BaseModel { abstract class BaseModel {
protected $pdo; protected PDO $pdo;
protected $table; protected string $table;
public function __construct($pdo) { public function __construct(PDO $pdo) {
$this->pdo = $pdo; $this->pdo = $pdo;
} }
protected function findById($id) { protected function findById(int $id): array|false {
$stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = ?"); $stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = ?");
$stmt->execute([$id]); $stmt->execute([$id]);
return $stmt->fetch(); return $stmt->fetch();
} }
protected function findAll($conditions = [], $orderBy = 'createdAt DESC', $limit = null, $offset = null) { protected function findAll(array $conditions = [], string $orderBy = 'createdAt DESC', ?int $limit = null, ?int $offset = null): array {
$query = "SELECT * FROM {$this->table} WHERE 1=1"; $query = "SELECT * FROM {$this->table} WHERE 1=1";
$params = []; $params = [];
foreach ($conditions as $field => $value) { foreach ($conditions as $field => $value) {
if (is_array($value)) { if (is_array($value)) {
// LIKE Operator // LIKE Operator
@@ -28,26 +30,26 @@ abstract class BaseModel {
$params[] = $value; $params[] = $value;
} }
} }
$query .= " ORDER BY $orderBy"; $query .= " ORDER BY $orderBy";
if ($limit) { if ($limit !== null) {
$query .= " LIMIT " . (int)$limit; $query .= " LIMIT " . (int)$limit;
} }
if ($offset) { if ($offset !== null) {
$query .= " OFFSET " . (int)$offset; $query .= " OFFSET " . (int)$offset;
} }
$stmt = $this->pdo->prepare($query); $stmt = $this->pdo->prepare($query);
$stmt->execute($params); $stmt->execute($params);
return $stmt->fetchAll(); return $stmt->fetchAll();
} }
protected function count($conditions = []) { protected function count(array $conditions = []): int|false {
$query = "SELECT COUNT(*) FROM {$this->table} WHERE 1=1"; $query = "SELECT COUNT(*) FROM {$this->table} WHERE 1=1";
$params = []; $params = [];
foreach ($conditions as $field => $value) { foreach ($conditions as $field => $value) {
if (is_array($value)) { if (is_array($value)) {
$query .= " AND $field LIKE ?"; $query .= " AND $field LIKE ?";
@@ -57,42 +59,42 @@ abstract class BaseModel {
$params[] = $value; $params[] = $value;
} }
} }
$stmt = $this->pdo->prepare($query); $stmt = $this->pdo->prepare($query);
$stmt->execute($params); $stmt->execute($params);
return $stmt->fetchColumn(); return $stmt->fetchColumn();
} }
protected function create($data) { protected function create(array $data): int|false {
$fields = array_keys($data); $fields = array_keys($data);
$placeholders = array_fill(0, count($fields), '?'); $placeholders = array_fill(0, count($fields), '?');
$query = "INSERT INTO {$this->table} (" . implode(', ', $fields) . ") VALUES (" . implode(', ', $placeholders) . ")"; $query = "INSERT INTO {$this->table} (" . implode(', ', $fields) . ") VALUES (" . implode(', ', $placeholders) . ")";
$stmt = $this->pdo->prepare($query); $stmt = $this->pdo->prepare($query);
$stmt->execute(array_values($data)); $stmt->execute(array_values($data));
return $this->pdo->lastInsertId(); return $this->pdo->lastInsertId();
} }
protected function update($id, $data) { protected function update(int $id, array $data): bool {
$fields = []; $fields = [];
$params = []; $params = [];
foreach ($data as $field => $value) { foreach ($data as $field => $value) {
$fields[] = "$field = ?"; $fields[] = "$field = ?";
$params[] = $value; $params[] = $value;
} }
$params[] = $id; $params[] = $id;
$query = "UPDATE {$this->table} SET " . implode(', ', $fields) . " WHERE id = ?"; $query = "UPDATE {$this->table} SET " . implode(', ', $fields) . " WHERE id = ?";
$stmt = $this->pdo->prepare($query); $stmt = $this->pdo->prepare($query);
$stmt->execute($params); $stmt->execute($params);
return $stmt->rowCount() > 0; return $stmt->rowCount() > 0;
} }
protected function delete($id) { protected function delete(int $id): bool {
$stmt = $this->pdo->prepare("DELETE FROM {$this->table} WHERE id = ?"); $stmt = $this->pdo->prepare("DELETE FROM {$this->table} WHERE id = ?");
$stmt->execute([$id]); $stmt->execute([$id]);
return $stmt->rowCount() > 0; return $stmt->rowCount() > 0;

View File

@@ -1,32 +1,34 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/BaseModel.php'; require_once __DIR__ . '/BaseModel.php';
require_once __DIR__ . '/../services/ImageHandler.php'; require_once __DIR__ . '/../services/ImageHandler.php';
class Cast extends BaseModel { class Cast extends BaseModel {
protected $table = 'cast_staff'; protected string $table = 'cast_staff';
private $imageHandler; private ImageHandler $imageHandler;
protected $isUpdate = false; protected bool $isUpdate = false;
protected $castId = null; protected ?int $castId = null;
public function __construct($pdo) { public function __construct(PDO $pdo) {
parent::__construct($pdo); parent::__construct($pdo);
$this->imageHandler = new ImageHandler(); $this->imageHandler = new ImageHandler();
} }
public function getWithFilmography($id) { public function getWithFilmography(?int $id): ?array {
$cast = $this->findById($id); $cast = $this->findById($id);
if (!$cast) { if (!$cast) {
return null; return null;
} }
$cast['occupations'] = $this->getRelatedItems('occupations', $id, 'cast_id'); $cast['occupations'] = $this->getRelatedItems('occupations', $id, 'cast_id');
$cast['filmography'] = $this->getMediaForCast($id); $cast['filmography'] = $this->getMediaForCast($id);
return $cast; return $cast;
} }
public function getMediaForCast($castId) { public function getMediaForCast(?int $castId): array {
$stmt = $this->pdo->prepare(" $stmt = $this->pdo->prepare("
SELECT m.id, m.title, m.year, m.poster, m.category, m.type, mc.role, mc.characterName SELECT m.id, m.title, m.year, m.poster, m.category, m.type, mc.role, mc.characterName
FROM media m FROM media m
@@ -37,8 +39,8 @@ class Cast extends BaseModel {
$stmt->execute([$castId]); $stmt->execute([$castId]);
return $stmt->fetchAll(); return $stmt->fetchAll();
} }
public function search($filters = [], $page = 1, $limit = 20) { public function search(array $filters = [], int $page = 1, int $limit = 20): array {
$conditions = []; $conditions = [];
if (isset($filters['search'])) { if (isset($filters['search'])) {
@@ -49,16 +51,37 @@ class Cast extends BaseModel {
$items = $this->findAll($conditions, 'createdAt DESC', $limit, $offset); $items = $this->findAll($conditions, 'createdAt DESC', $limit, $offset);
$total = $this->count($conditions); $total = $this->count($conditions);
// Load filmography for all cast members in a single query
// Add filmography to each cast member if (!empty($items)) {
foreach ($items as &$item) { $castIds = array_column($items, 'id');
$item['filmography'] = $this->getMediaForCast($item['id']); $placeholders = str_repeat('?,', count($castIds) - 1) . '?';
// Extract unique media types
$mediaTypes = array_unique(array_column($item['filmography'], 'category')); $stmt = $this->pdo->prepare("
$item['media_types'] = array_values($mediaTypes); SELECT mc.cast_id, m.id, m.title, m.year, m.poster, m.category, m.type, mc.role, mc.characterName
FROM media m
INNER JOIN media_cast mc ON m.id = mc.media_id
WHERE mc.cast_id IN ($placeholders)
ORDER BY m.year DESC
");
$stmt->execute($castIds);
$allFilmography = $stmt->fetchAll();
// Group filmography by cast_id
$filmographyByCast = [];
foreach ($allFilmography as $film) {
$castId = $film['cast_id'];
unset($film['cast_id']);
$filmographyByCast[$castId][] = $film;
}
// Attach filmography to each cast member
foreach ($items as &$item) {
$item['filmography'] = $filmographyByCast[$item['id']] ?? [];
$mediaTypes = array_unique(array_column($item['filmography'], 'category'));
$item['media_types'] = array_values($mediaTypes);
}
} }
return [ return [
'items' => $items, 'items' => $items,
'total' => $total, 'total' => $total,
@@ -67,7 +90,7 @@ class Cast extends BaseModel {
]; ];
} }
protected function processPhotoField($data) { protected function processPhotoField(array $data): array {
error_log("Cast::processPhotoField - Checking for photo field, isUpdate: " . ($this->isUpdate ? 'yes' : 'no')); error_log("Cast::processPhotoField - Checking for photo field, isUpdate: " . ($this->isUpdate ? 'yes' : 'no'));
if ($this->isUpdate && $this->castId && isset($data['photo']) && !empty($data['photo'])) { if ($this->isUpdate && $this->castId && isset($data['photo']) && !empty($data['photo'])) {
@@ -103,7 +126,7 @@ class Cast extends BaseModel {
return $data; return $data;
} }
public function createWithOccupations($data) { public function createWithOccupations(array $data): int {
$name = $data['name'] ?? null; $name = $data['name'] ?? null;
if (!$name) { if (!$name) {
throw new Exception('Name is required'); throw new Exception('Name is required');
@@ -132,7 +155,7 @@ class Cast extends BaseModel {
return $castId; return $castId;
} }
public function updateWithOccupations($id, $data) { public function updateWithOccupations(int $id, array $data): bool {
$this->isUpdate = true; $this->isUpdate = true;
$this->castId = $id; $this->castId = $id;
@@ -163,13 +186,13 @@ class Cast extends BaseModel {
return true; return true;
} }
public function findByCleanName($cleanname) { public function findByCleanName(string $cleanname): array|false {
$stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE cleanname = ?"); $stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE cleanname = ?");
$stmt->execute([$cleanname]); $stmt->execute([$cleanname]);
return $stmt->fetch(); return $stmt->fetch();
} }
protected function getRelatedItems($table, $id, $fkColumn = 'media_id') { protected function getRelatedItems(string $table, int $id, string $fkColumn = 'media_id'): array {
$stmt = $this->pdo->prepare("SELECT * FROM $table WHERE $fkColumn = ?"); $stmt = $this->pdo->prepare("SELECT * FROM $table WHERE $fkColumn = ?");
$stmt->execute([$id]); $stmt->execute([$id]);
$items = $stmt->fetchAll(); $items = $stmt->fetchAll();
@@ -180,7 +203,7 @@ class Cast extends BaseModel {
return $result; return $result;
} }
protected function saveRelatedItems($table, $id, $items, $fkColumn = 'media_id') { protected function saveRelatedItems(string $table, int $id, array $items, string $fkColumn = 'media_id'): void {
$valueColumn = $fkColumn === 'cast_id' ? 'occupation' : 'genre'; $valueColumn = $fkColumn === 'cast_id' ? 'occupation' : 'genre';
$stmt = $this->pdo->prepare("INSERT INTO $table ($fkColumn, $valueColumn) VALUES (?, ?)"); $stmt = $this->pdo->prepare("INSERT INTO $table ($fkColumn, $valueColumn) VALUES (?, ?)");
foreach ($items as $item) { foreach ($items as $item) {

View File

@@ -1,21 +1,24 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/MediaType.php'; require_once __DIR__ . '/MediaType.php';
class Console extends MediaType { class Console extends MediaType {
protected function getType() { protected function getType(): string {
return 'Console'; return 'Console';
} }
protected function getTypeSpecificFields() { protected function getTypeSpecificFields(): array {
return []; return [];
} }
protected function validateTypeSpecificFields($data) { protected function validateTypeSpecificFields(array $data): array {
// Console spezifische Validierung // Console spezifische Validierung
return $data;
} }
public function search($filters = [], $page = 1, $limit = 20) { public function search(array $filters = [], int $page = 1, int $limit = 20): array {
// Nur Consoles suchen // Nur Consoles suchen
$filters['type'] = 'Console'; $filters['type'] = 'Console';
return parent::search($filters, $page, $limit); return parent::search($filters, $page, $limit);

View File

@@ -1,27 +1,29 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/MediaType.php'; require_once __DIR__ . '/MediaType.php';
require_once __DIR__ . '/../services/ImageHandler.php'; require_once __DIR__ . '/../services/ImageHandler.php';
class Game extends MediaType { class Game extends MediaType {
private $imageHandler; private ImageHandler $imageHandler;
private $isUpdate = false; private bool $isUpdate = false;
private $mediaId = null; private ?int $mediaId = null;
public function __construct($pdo) { public function __construct(PDO $pdo) {
parent::__construct($pdo); parent::__construct($pdo);
$this->imageHandler = new ImageHandler(); $this->imageHandler = new ImageHandler();
} }
protected function getType() { protected function getType(): string {
return 'Game'; return 'Game';
} }
protected function getTypeSpecificFields() { protected function getTypeSpecificFields(): array {
return []; return [];
} }
protected function validateTypeSpecificFields($data) { protected function validateTypeSpecificFields(array $data): array {
// Game spezifische Validierung // Game spezifische Validierung
if (isset($data['hasIcon'])) { if (isset($data['hasIcon'])) {
$data['hasIcon'] = is_numeric($data['hasIcon']) ? (int)$data['hasIcon'] : 0; $data['hasIcon'] = is_numeric($data['hasIcon']) ? (int)$data['hasIcon'] : 0;
@@ -47,11 +49,11 @@ class Game extends MediaType {
return $data; return $data;
} }
/** /**
* Process poster field - convert base64 to file path * Process poster field - convert base64 to file path
*/ */
protected function processImageField($data, $type) { protected function processImageField(array $data, string $type): array {
if ($this->isUpdate && $this->mediaId && isset($data[$type]) && !empty($data[$type])) { if ($this->isUpdate && $this->mediaId && isset($data[$type]) && !empty($data[$type])) {
$currentMedia = $this->findById($this->mediaId); $currentMedia = $this->findById($this->mediaId);
if ($currentMedia && !empty($currentMedia[$type])) { if ($currentMedia && !empty($currentMedia[$type])) {
@@ -73,7 +75,7 @@ class Game extends MediaType {
return $data; return $data;
} }
public function createWithRelations($data) { public function createWithRelations(array $data): int {
// Typ setzen // Typ setzen
$data['type'] = 'Game'; $data['type'] = 'Game';
@@ -152,7 +154,7 @@ class Game extends MediaType {
return $mediaId; return $mediaId;
} }
public function updateWithRelations($id, $data) { public function updateWithRelations(int $id, array $data): bool {
// Set update flag and mediaId for image replacement // Set update flag and mediaId for image replacement
$this->isUpdate = true; $this->isUpdate = true;
$this->mediaId = $id; $this->mediaId = $id;
@@ -236,7 +238,7 @@ class Game extends MediaType {
return true; return true;
} }
public function getWithGameInfo($id) { public function getWithGameInfo(?int $id): ?array {
$media = parent::getWithRelations($id); $media = parent::getWithRelations($id);
if (!$media) { if (!$media) {
return null; return null;
@@ -264,7 +266,7 @@ class Game extends MediaType {
return $media; return $media;
} }
public function getGameInfoForList($mediaId) { public function getGameInfoForList(?int $mediaId): ?array {
// Media-Games Daten abrufen (ohne vollständige Relationen für Performance) // Media-Games Daten abrufen (ohne vollständige Relationen für Performance)
$mediaGameId = $this->getMediaGameId($mediaId); $mediaGameId = $this->getMediaGameId($mediaId);
if (!$mediaGameId) { if (!$mediaGameId) {
@@ -281,7 +283,7 @@ class Game extends MediaType {
return $gameInfo; return $gameInfo;
} }
public static function interpolateQuery($query, $params) { public static function interpolateQuery(string $query, array $params): string {
$keys = array(); $keys = array();
# build a regular expression for each parameter # build a regular expression for each parameter
@@ -300,7 +302,7 @@ class Game extends MediaType {
return $query; return $query;
} }
protected function createMediaGame($data) { protected function createMediaGame(array $data): string {
$stmt = $this->pdo->prepare(" $stmt = $this->pdo->prepare("
INSERT INTO media_games (media_id, sortingName, notes, completionStatus, source, gameId, pluginId, INSERT INTO media_games (media_id, sortingName, notes, completionStatus, source, gameId, pluginId,
isInstalled, installDirectory, installSize, hidden, favorite, playCount, isInstalled, installDirectory, installSize, hidden, favorite, playCount,
@@ -337,7 +339,7 @@ class Game extends MediaType {
return $this->pdo->lastInsertId(); return $this->pdo->lastInsertId();
} }
protected function updateMediaGame($mediaId, $data) { protected function updateMediaGame(int $mediaId, array $data): void {
$setClause = []; $setClause = [];
$params = []; $params = [];
@@ -354,14 +356,14 @@ class Game extends MediaType {
$stmt->execute($params); $stmt->execute($params);
} }
protected function getMediaGameId($mediaId) { protected function getMediaGameId(?int $mediaId): ?int {
$stmt = $this->pdo->prepare("SELECT id FROM media_games WHERE media_id = ?"); $stmt = $this->pdo->prepare("SELECT id FROM media_games WHERE media_id = ?");
$stmt->execute([$mediaId]); $stmt->execute([$mediaId]);
$result = $stmt->fetch(); $result = $stmt->fetch();
return $result ? $result['id'] : null; return $result ? $result['id'] : null;
} }
protected function getMediaGameData($mediaGameId) { protected function getMediaGameData(?int $mediaGameId): array {
$stmt = $this->pdo->prepare("SELECT * FROM media_games WHERE id = ?"); $stmt = $this->pdo->prepare("SELECT * FROM media_games WHERE id = ?");
$stmt->execute([$mediaGameId]); $stmt->execute([$mediaGameId]);
$data = $stmt->fetch(); $data = $stmt->fetch();
@@ -373,7 +375,7 @@ class Game extends MediaType {
return $data ?: []; return $data ?: [];
} }
protected function saveAchievements($mediaGameId, $achievements) { protected function saveAchievements(string $mediaGameId, array $achievements): void {
$stmt = $this->pdo->prepare(" $stmt = $this->pdo->prepare("
INSERT INTO achievements (media_game_id, name, description, icon, unlocked, unlocked_date) INSERT INTO achievements (media_game_id, name, description, icon, unlocked, unlocked_date)
VALUES (?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?)
@@ -396,26 +398,26 @@ class Game extends MediaType {
} }
} }
protected function getAchievements($mediaGameId) { protected function getAchievements(string $mediaGameId): array {
$stmt = $this->pdo->prepare("SELECT * FROM achievements WHERE media_game_id = ?"); $stmt = $this->pdo->prepare("SELECT * FROM achievements WHERE media_game_id = ?");
$stmt->execute([$mediaGameId]); $stmt->execute([$mediaGameId]);
return $stmt->fetchAll(); return $stmt->fetchAll();
} }
protected function saveGameRelation($table, $mediaGameId, $items, $field) { protected function saveGameRelation(string $table, string $mediaGameId, array $items, string $field): void {
$stmt = $this->pdo->prepare("INSERT INTO $table (media_game_id, $field) VALUES (?, ?)"); $stmt = $this->pdo->prepare("INSERT INTO $table (media_game_id, $field) VALUES (?, ?)");
foreach ($items as $item) { foreach ($items as $item) {
$stmt->execute([$mediaGameId, $item]); $stmt->execute([$mediaGameId, $item]);
} }
} }
protected function consoleExists($name) { protected function consoleExists(string $name): bool {
$stmt = $this->pdo->prepare("SELECT id FROM media WHERE type = 'Console' AND title = ?"); $stmt = $this->pdo->prepare("SELECT id FROM media WHERE type = 'Console' AND title = ?");
$stmt->execute([$name]); $stmt->execute([$name]);
return $stmt->fetch() !== false; return $stmt->fetch() !== false;
} }
protected function createConsole($name) { protected function createConsole(string $name): string {
$stmt = $this->pdo->prepare(" $stmt = $this->pdo->prepare("
INSERT INTO media (title, cleanname, type, createdAt, updatedAt) INSERT INTO media (title, cleanname, type, createdAt, updatedAt)
VALUES (?, ?, 'Console', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) VALUES (?, ?, 'Console', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
@@ -424,7 +426,7 @@ class Game extends MediaType {
return $this->pdo->lastInsertId(); return $this->pdo->lastInsertId();
} }
protected function saveGameRelationWithConsole($table, $mediaGameId, $items, $field) { protected function saveGameRelationWithConsole(string $table, string $mediaGameId, array $items, string $field): void {
$stmt = $this->pdo->prepare("INSERT INTO $table (media_game_id, $field) VALUES (?, ?)"); $stmt = $this->pdo->prepare("INSERT INTO $table (media_game_id, $field) VALUES (?, ?)");
foreach ($items as $item) { foreach ($items as $item) {
// Check if console exists, create if not // Check if console exists, create if not
@@ -435,7 +437,7 @@ class Game extends MediaType {
} }
} }
protected function getGameRelation($table, $mediaGameId, $field) { protected function getGameRelation(string $table, string $mediaGameId, string $field): array {
$stmt = $this->pdo->prepare("SELECT $field FROM $table WHERE media_game_id = ?"); $stmt = $this->pdo->prepare("SELECT $field FROM $table WHERE media_game_id = ?");
$stmt->execute([$mediaGameId]); $stmt->execute([$mediaGameId]);
$items = $stmt->fetchAll(); $items = $stmt->fetchAll();
@@ -444,7 +446,7 @@ class Game extends MediaType {
}, $items); }, $items);
} }
protected function saveLinks($mediaGameId, $links) { protected function saveLinks(string $mediaGameId, array $links): void {
$stmt = $this->pdo->prepare("INSERT INTO game_links (media_game_id, name, url) VALUES (?, ?, ?)"); $stmt = $this->pdo->prepare("INSERT INTO game_links (media_game_id, name, url) VALUES (?, ?, ?)");
foreach ($links as $link) { foreach ($links as $link) {
$stmt->execute([ $stmt->execute([
@@ -455,13 +457,13 @@ class Game extends MediaType {
} }
} }
protected function getLinks($mediaGameId) { protected function getLinks(string $mediaGameId): array {
$stmt = $this->pdo->prepare("SELECT name, url FROM game_links WHERE media_game_id = ?"); $stmt = $this->pdo->prepare("SELECT name, url FROM game_links WHERE media_game_id = ?");
$stmt->execute([$mediaGameId]); $stmt->execute([$mediaGameId]);
return $stmt->fetchAll(); return $stmt->fetchAll();
} }
public function search($filters = [], $page = 1, $limit = 20) { public function search(array $filters = [], int $page = 1, int $limit = 20): array {
// Nur Games suchen // Nur Games suchen
$filters['type'] = 'Game'; $filters['type'] = 'Game';
return parent::search($filters, $page, $limit); return parent::search($filters, $page, $limit);

View File

@@ -1,15 +1,17 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/BaseModel.php'; require_once __DIR__ . '/BaseModel.php';
class Media extends BaseModel { class Media extends BaseModel {
protected $table = 'media'; protected string $table = 'media';
public function getBase($id) { public function getBase(?int $id): array|false {
return $this->findById($id); return $this->findById($id);
} }
public function getWithRelations($id) { public function getWithRelations(?int $id): ?array {
$media = $this->findById($id); $media = $this->findById($id);
if (!$media) { if (!$media) {
return null; return null;
@@ -22,8 +24,8 @@ class Media extends BaseModel {
return $media; return $media;
} }
public function search($filters = [], $page = 1, $limit = 20) { public function search(array $filters = [], int $page = 1, int $limit = 20): array {
$conditions = []; $conditions = [];
if (isset($filters['category'])) { if (isset($filters['category'])) {
@@ -64,12 +66,7 @@ class Media extends BaseModel {
$stmt = $this->pdo->prepare($query); $stmt = $this->pdo->prepare($query);
$stmt->execute($params); $stmt->execute($params);
$items = $stmt->fetchAll(); $items = $stmt->fetchAll();
// Cast-Mitglieder für jedes Medium laden
foreach ($items as &$item) {
$item['staff'] = $this->getCastForMedia($item['id']);
}
// Count Query // Count Query
$countQuery = "SELECT COUNT(*) FROM {$this->table} WHERE 1=1"; $countQuery = "SELECT COUNT(*) FROM {$this->table} WHERE 1=1";
$countParams = []; $countParams = [];
@@ -93,11 +90,6 @@ class Media extends BaseModel {
} else { } else {
$items = $this->findAll($conditions, 'createdAt DESC', $limit, $offset); $items = $this->findAll($conditions, 'createdAt DESC', $limit, $offset);
$total = $this->count($conditions); $total = $this->count($conditions);
// Cast-Mitglieder für jedes Medium laden
foreach ($items as &$item) {
$item['staff'] = $this->getCastForMedia($item['id']);
}
} }
return [ return [
@@ -109,7 +101,7 @@ class Media extends BaseModel {
]; ];
} }
public function createWithRelations($data) { public function createWithRelations(array $data): int {
$title = $data['title'] ?? null; $title = $data['title'] ?? null;
if (!$title) { if (!$title) {
throw new Exception('Title is required'); throw new Exception('Title is required');
@@ -157,7 +149,7 @@ class Media extends BaseModel {
return $mediaId; return $mediaId;
} }
public function updateWithRelations($id, $data) { public function updateWithRelations(int $id, array $data): bool {
$mediaData = []; $mediaData = [];
foreach (['title', 'year', 'poster', 'banner', 'description', 'rating', 'category', 'type', 'status', 'aspectRatio', 'runtime', 'director', 'writer', 'releaseDate', 'source'] as $field) { foreach (['title', 'year', 'poster', 'banner', 'description', 'rating', 'category', 'type', 'status', 'aspectRatio', 'runtime', 'director', 'writer', 'releaseDate', 'source'] as $field) {
@@ -196,13 +188,13 @@ class Media extends BaseModel {
return true; return true;
} }
public function findByCleanName($cleanname) { public function findByCleanName(string $cleanname): array|false {
$stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE cleanname = ?"); $stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE cleanname = ?");
$stmt->execute([$cleanname]); $stmt->execute([$cleanname]);
return $stmt->fetch(); return $stmt->fetch();
} }
protected function saveRelatedItems($table, $id, $items, $fkColumn = 'media_id') { protected function saveRelatedItems(string $table, int $id, array $items, string $fkColumn = 'media_id'): void {
$valueColumn = $table === 'genres' ? 'genre' : ($table === 'tags' ? 'tag' : ($table === 'occupations' ? 'occupation' : 'studio')); $valueColumn = $table === 'genres' ? 'genre' : ($table === 'tags' ? 'tag' : ($table === 'occupations' ? 'occupation' : 'studio'));
$stmt = $this->pdo->prepare("INSERT INTO $table ($fkColumn, $valueColumn) VALUES (?, ?)"); $stmt = $this->pdo->prepare("INSERT INTO $table ($fkColumn, $valueColumn) VALUES (?, ?)");
foreach ($items as $item) { foreach ($items as $item) {
@@ -210,7 +202,7 @@ class Media extends BaseModel {
} }
} }
protected function getCastForMedia($mediaId) { protected function getCastForMedia(?int $mediaId): array {
$stmt = $this->pdo->prepare(" $stmt = $this->pdo->prepare("
SELECT cs.*, mc.role, mc.characterName, mc.characterImage SELECT cs.*, mc.role, mc.characterName, mc.characterImage
FROM cast_staff cs FROM cast_staff cs
@@ -225,7 +217,7 @@ class Media extends BaseModel {
return $cast; return $cast;
} }
protected function getRelatedItems($table, $id, $fkColumn = 'media_id') { protected function getRelatedItems(string $table, int $id, string $fkColumn = 'media_id'): array {
$stmt = $this->pdo->prepare("SELECT * FROM $table WHERE $fkColumn = ?"); $stmt = $this->pdo->prepare("SELECT * FROM $table WHERE $fkColumn = ?");
$stmt->execute([$id]); $stmt->execute([$id]);
$items = $stmt->fetchAll(); $items = $stmt->fetchAll();
@@ -240,7 +232,7 @@ class Media extends BaseModel {
return $result; return $result;
} }
protected function saveCastAssignments($mediaId, $castData) { protected function saveCastAssignments(int $mediaId, array $castData): void {
foreach ($castData as $member) { foreach ($castData as $member) {
$castId = null; $castId = null;
if (isset($member['id']) && $member['id']) { if (isset($member['id']) && $member['id']) {

View File

@@ -1,39 +1,41 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/Media.php'; require_once __DIR__ . '/Media.php';
abstract class MediaType extends Media { abstract class MediaType extends Media {
protected $type; protected string $type;
public function __construct($pdo) { public function __construct(PDO $pdo) {
parent::__construct($pdo); parent::__construct($pdo);
$this->type = $this->getType(); $this->type = $this->getType();
} }
abstract protected function getType(); abstract protected function getType(): string;
abstract protected function validateTypeSpecificFields($data); abstract protected function validateTypeSpecificFields(array $data): array;
abstract protected function getTypeSpecificFields(); abstract protected function getTypeSpecificFields(): array;
public function createWithRelations($data) { public function createWithRelations(array $data): int {
// Typ setzen // Typ setzen
$data['type'] = $this->type; $data['type'] = $this->type;
// Typ-spezifische Validierung // Typ-spezifische Validierung
$this->validateTypeSpecificFields($data); $this->validateTypeSpecificFields($data);
return parent::createWithRelations($data); return parent::createWithRelations($data);
} }
public function updateWithRelations($id, $data) { public function updateWithRelations(int $id, array $data): bool {
// Typ-spezifische Validierung // Typ-spezifische Validierung
$this->validateTypeSpecificFields($data); $this->validateTypeSpecificFields($data);
return parent::updateWithRelations($id, $data); return parent::updateWithRelations($id, $data);
} }
protected function getRequiredFields() { protected function getRequiredFields(): array {
return []; return [];
} }
} }

View File

@@ -1,36 +1,39 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/MediaType.php'; require_once __DIR__ . '/MediaType.php';
require_once __DIR__ . '/../services/ImageHandler.php'; require_once __DIR__ . '/../services/ImageHandler.php';
class Movie extends MediaType { class Movie extends MediaType {
private $imageHandler; private ImageHandler $imageHandler;
private $isUpdate = false; private bool $isUpdate = false;
private $mediaId = null; private ?int $mediaId = null;
public function __construct($pdo) { public function __construct(PDO $pdo) {
parent::__construct($pdo); parent::__construct($pdo);
$this->imageHandler = new ImageHandler(); $this->imageHandler = new ImageHandler();
} }
protected function getType() { protected function getType(): string {
return 'Movie'; return 'Movie';
} }
protected function getTypeSpecificFields() { protected function getTypeSpecificFields(): array {
return ['runtime', 'director', 'writer']; return ['runtime', 'director', 'writer'];
} }
protected function validateTypeSpecificFields($data) { protected function validateTypeSpecificFields(array $data): array {
// Movies sollten bestimmte Felder haben // Movies sollten bestimmte Felder haben
if (isset($data['runtime']) && !is_numeric($data['runtime'])) { if (isset($data['runtime']) && !is_numeric($data['runtime'])) {
throw new Exception('Runtime must be a number'); throw new Exception('Runtime must be a number');
} }
return $data;
} }
protected function processPosterField($data) { protected function processPosterField(array $data): array {
error_log("Movie::processPosterField - Checking for poster field, isUpdate: " . ($this->isUpdate ? 'yes' : 'no')); error_log("Movie::processPosterField - Checking for poster field, isUpdate: " . ($this->isUpdate ? 'yes' : 'no'));
// If this is an update and poster is being changed, delete old image // If this is an update and poster is being changed, delete old image
if ($this->isUpdate && $this->mediaId && isset($data['poster']) && !empty($data['poster'])) { if ($this->isUpdate && $this->mediaId && isset($data['poster']) && !empty($data['poster'])) {
$currentMedia = $this->findById($this->mediaId); $currentMedia = $this->findById($this->mediaId);
@@ -42,15 +45,15 @@ class Movie extends MediaType {
} }
} }
} }
if (isset($data['poster']) && !empty($data['poster'])) { if (isset($data['poster']) && !empty($data['poster'])) {
error_log("Movie::processPosterField - Poster found, length: " . strlen($data['poster'])); error_log("Movie::processPosterField - Poster found, length: " . strlen($data['poster']));
if (strpos($data['poster'], '/images/') === 0 || filter_var($data['poster'], FILTER_VALIDATE_URL)) { if (strpos($data['poster'], '/images/') === 0 || filter_var($data['poster'], FILTER_VALIDATE_URL)) {
error_log("Movie::processPosterField - Poster is already a path or URL, skipping processing"); error_log("Movie::processPosterField - Poster is already a path or URL, skipping processing");
return $data; return $data;
} }
$posterPath = $this->imageHandler->saveBase64Image($data['poster'], 'movies/poster'); $posterPath = $this->imageHandler->saveBase64Image($data['poster'], 'movies/poster');
error_log("Movie::processPosterField - ImageHandler returned: " . ($posterPath ?: 'null')); error_log("Movie::processPosterField - ImageHandler returned: " . ($posterPath ?: 'null'));
if ($posterPath) { if ($posterPath) {
@@ -64,23 +67,23 @@ class Movie extends MediaType {
} }
return $data; return $data;
} }
public function createWithRelations($data) { public function createWithRelations(array $data): int {
$data['type'] = 'Movie'; $data['type'] = 'Movie';
$data = $this->validateTypeSpecificFields($data); $data = $this->validateTypeSpecificFields($data);
$data = $this->processPosterField($data); $data = $this->processPosterField($data);
return parent::createWithRelations($data); return parent::createWithRelations($data);
} }
public function updateWithRelations($id, $data) { public function updateWithRelations(int $id, array $data): bool {
$this->isUpdate = true; $this->isUpdate = true;
$this->mediaId = $id; $this->mediaId = $id;
$this->validateTypeSpecificFields($data); $this->validateTypeSpecificFields($data);
$data = $this->processPosterField($data); $data = $this->processPosterField($data);
parent::updateWithRelations($id, $data); return parent::updateWithRelations($id, $data);
} }
public function search($filters = [], $page = 1, $limit = 20) { public function search(array $filters = [], int $page = 1, int $limit = 20): array {
// Nur Movies suchen // Nur Movies suchen
$filters['type'] = 'Movie'; $filters['type'] = 'Movie';
return parent::search($filters, $page, $limit); return parent::search($filters, $page, $limit);

View File

@@ -1,46 +1,49 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/MediaType.php'; require_once __DIR__ . '/MediaType.php';
class Music extends MediaType { class Music extends MediaType {
protected function getType() { protected function getType(): string {
return 'Album'; return 'Album';
} }
protected function getTypeSpecificFields() { protected function getTypeSpecificFields(): array {
return ['artist', 'album_type', 'release_date']; return ['artist', 'album_type', 'release_date'];
} }
protected function validateTypeSpecificFields($data) { protected function validateTypeSpecificFields(array $data): array {
// Music spezifische Validierung // Music spezifische Validierung
return $data;
} }
public function search($filters = [], $page = 1, $limit = 20) { public function search(array $filters = [], int $page = 1, int $limit = 20): array {
// Nur Music suchen // Nur Music suchen
$filters['type'] = 'Album'; $filters['type'] = 'Album';
return parent::search($filters, $page, $limit); return parent::search($filters, $page, $limit);
} }
public function getWithTracks($id) { public function getWithTracks(?int $id): ?array {
$media = $this->getWithRelations($id); $media = $this->getWithRelations($id);
if (!$media) { if (!$media) {
return null; return null;
} }
$media['tracks'] = $this->getTracks($id); $media['tracks'] = $this->getTracks($id);
return $media; return $media;
} }
public function getTracks($mediaId) { public function getTracks(?int $mediaId): array {
$stmt = $this->pdo->prepare(" $stmt = $this->pdo->prepare("
SELECT * FROM tracks WHERE media_id = ? ORDER BY track_number SELECT * FROM tracks WHERE media_id = ? ORDER BY track_number
"); ");
$stmt->execute([$mediaId]); $stmt->execute([$mediaId]);
return $stmt->fetchAll(); return $stmt->fetchAll();
} }
public function addTrack($mediaId, $trackData) { public function addTrack(?int $mediaId, array $trackData): int {
$stmt = $this->pdo->prepare(" $stmt = $this->pdo->prepare("
INSERT INTO tracks (media_id, track_number, title, artist) INSERT INTO tracks (media_id, track_number, title, artist)
VALUES (?, ?, ?, ?) VALUES (?, ?, ?, ?)
@@ -52,20 +55,20 @@ class Music extends MediaType {
//$trackData['duration'] ?? null, //$trackData['duration'] ?? null,
$trackData['artist'] ?? null $trackData['artist'] ?? null
]); ]);
return $this->pdo->lastInsertId(); return (int)$this->pdo->lastInsertId();
} }
public function updateTrack($trackId, $trackData) { public function updateTrack(?int $trackId, array $trackData): bool {
$fields = []; $fields = [];
$params = []; $params = [];
foreach (['track_number', 'title', 'artist'] as $field) { foreach (['track_number', 'title', 'artist'] as $field) {
if (array_key_exists($field, $trackData)) { if (array_key_exists($field, $trackData)) {
$fields[] = "$field = ?"; $fields[] = "$field = ?";
$params[] = $trackData[$field]; $params[] = $trackData[$field];
} }
} }
if (!empty($fields)) { if (!empty($fields)) {
$params[] = $trackId; $params[] = $trackId;
$stmt = $this->pdo->prepare("UPDATE tracks SET " . implode(', ', $fields) . " WHERE id = ?"); $stmt = $this->pdo->prepare("UPDATE tracks SET " . implode(', ', $fields) . " WHERE id = ?");
@@ -74,29 +77,29 @@ class Music extends MediaType {
} }
return false; return false;
} }
public function deleteTrack($trackId) { public function deleteTrack(?int $trackId): bool {
$stmt = $this->pdo->prepare("DELETE FROM tracks WHERE id = ?"); $stmt = $this->pdo->prepare("DELETE FROM tracks WHERE id = ?");
$stmt->execute([$trackId]); $stmt->execute([$trackId]);
return $stmt->rowCount() > 0; return $stmt->rowCount() > 0;
} }
public function createWithRelations($data) { public function createWithRelations(array $data): int {
$mediaId = parent::createWithRelations($data); $mediaId = parent::createWithRelations($data);
// Tracks speichern // Tracks speichern
if (isset($data['tracks']) && is_array($data['tracks'])) { if (isset($data['tracks']) && is_array($data['tracks'])) {
foreach ($data['tracks'] as $track) { foreach ($data['tracks'] as $track) {
$this->addTrack($mediaId, $track); $this->addTrack($mediaId, $track);
} }
} }
return $mediaId; return $mediaId;
} }
public function updateWithRelations($id, $data) { public function updateWithRelations(int $id, array $data): bool {
parent::updateWithRelations($id, $data); parent::updateWithRelations($id, $data);
// Tracks aktualisieren // Tracks aktualisieren
if (isset($data['tracks']) && is_array($data['tracks'])) { if (isset($data['tracks']) && is_array($data['tracks'])) {
// Alle existierenden Tracks löschen // Alle existierenden Tracks löschen
@@ -106,7 +109,6 @@ class Music extends MediaType {
$this->addTrack($id, $track); $this->addTrack($id, $track);
} }
} }
return true; return true;
} }
} }

View File

@@ -1,58 +1,61 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/MediaType.php'; require_once __DIR__ . '/MediaType.php';
class Series extends MediaType { class Series extends MediaType {
protected function getType() { protected function getType(): string {
return 'TV'; return 'TV';
} }
protected function getTypeSpecificFields() { protected function getTypeSpecificFields(): array {
return ['runtime', 'director', 'writer']; return ['runtime', 'director', 'writer'];
} }
protected function validateTypeSpecificFields($data) { protected function validateTypeSpecificFields(array $data): array {
// Series Validierung // Series Validierung
if (isset($data['runtime']) && !is_numeric($data['runtime'])) { if (isset($data['runtime']) && !is_numeric($data['runtime'])) {
throw new Exception('Runtime must be a number'); throw new Exception('Runtime must be a number');
} }
return $data;
} }
public function search($filters = [], $page = 1, $limit = 20) { public function search(array $filters = [], int $page = 1, int $limit = 20): array {
// Nur Series suchen // Nur Series suchen
$filters['type'] = 'TV'; $filters['type'] = 'TV';
return parent::search($filters, $page, $limit); return parent::search($filters, $page, $limit);
} }
public function getWithEpisodes($id) { public function getWithEpisodes(?int $id): ?array {
$media = $this->getWithRelations($id); $media = $this->getWithRelations($id);
if (!$media) { if (!$media) {
return null; return null;
} }
$media['episodes'] = $this->getEpisodes($id); $media['episodes'] = $this->getEpisodes($id);
$media['seasons'] = $this->getSeasons($id); $media['seasons'] = $this->getSeasons($id);
return $media; return $media;
} }
public function getEpisodes($mediaId, $season = null) { public function getEpisodes(?int $mediaId, ?int $season = null): array {
$query = "SELECT * FROM episodes WHERE media_id = ?"; $query = "SELECT * FROM episodes WHERE media_id = ?";
$params = [$mediaId]; $params = [$mediaId];
if ($season !== null) { if ($season !== null) {
$query .= " AND season = ?"; $query .= " AND season = ?";
$params[] = $season; $params[] = $season;
} }
$query .= " ORDER BY season, episode_number"; $query .= " ORDER BY season, episode_number";
$stmt = $this->pdo->prepare($query); $stmt = $this->pdo->prepare($query);
$stmt->execute($params); $stmt->execute($params);
return $stmt->fetchAll(); return $stmt->fetchAll();
} }
public function getSeasons($mediaId) { public function getSeasons(?int $mediaId): array {
$stmt = $this->pdo->prepare(" $stmt = $this->pdo->prepare("
SELECT DISTINCT season, COUNT(*) as episode_count, SELECT DISTINCT season, COUNT(*) as episode_count,
MIN(air_date) as first_air_date, MAX(air_date) as last_air_date MIN(air_date) as first_air_date, MAX(air_date) as last_air_date
@@ -64,8 +67,8 @@ class Series extends MediaType {
$stmt->execute([$mediaId]); $stmt->execute([$mediaId]);
return $stmt->fetchAll(); return $stmt->fetchAll();
} }
public function addEpisode($mediaId, $episodeData) { public function addEpisode(?int $mediaId, array $episodeData): int {
$stmt = $this->pdo->prepare(" $stmt = $this->pdo->prepare("
INSERT INTO episodes (media_id, season, episode_number, title, description, air_date, duration, thumbnail) INSERT INTO episodes (media_id, season, episode_number, title, description, air_date, duration, thumbnail)
VALUES (?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
@@ -80,20 +83,20 @@ class Series extends MediaType {
$episodeData['duration'] ?? null, $episodeData['duration'] ?? null,
$episodeData['thumbnail'] ?? null $episodeData['thumbnail'] ?? null
]); ]);
return $this->pdo->lastInsertId(); return (int)$this->pdo->lastInsertId();
} }
public function updateEpisode($episodeId, $episodeData) { public function updateEpisode(?int $episodeId, array $episodeData): bool {
$fields = []; $fields = [];
$params = []; $params = [];
foreach (['season', 'episode_number', 'title', 'description', 'air_date', 'duration', 'thumbnail'] as $field) { foreach (['season', 'episode_number', 'title', 'description', 'air_date', 'duration', 'thumbnail'] as $field) {
if (array_key_exists($field, $episodeData)) { if (array_key_exists($field, $episodeData)) {
$fields[] = "$field = ?"; $fields[] = "$field = ?";
$params[] = $episodeData[$field]; $params[] = $episodeData[$field];
} }
} }
if (!empty($fields)) { if (!empty($fields)) {
$params[] = $episodeId; $params[] = $episodeId;
$stmt = $this->pdo->prepare("UPDATE episodes SET " . implode(', ', $fields) . " WHERE id = ?"); $stmt = $this->pdo->prepare("UPDATE episodes SET " . implode(', ', $fields) . " WHERE id = ?");
@@ -102,29 +105,29 @@ class Series extends MediaType {
} }
return false; return false;
} }
public function deleteEpisode($episodeId) { public function deleteEpisode(?int $episodeId): bool {
$stmt = $this->pdo->prepare("DELETE FROM episodes WHERE id = ?"); $stmt = $this->pdo->prepare("DELETE FROM episodes WHERE id = ?");
$stmt->execute([$episodeId]); $stmt->execute([$episodeId]);
return $stmt->rowCount() > 0; return $stmt->rowCount() > 0;
} }
public function createWithRelations($data) { public function createWithRelations(array $data): int {
$mediaId = parent::createWithRelations($data); $mediaId = parent::createWithRelations($data);
// Episoden speichern // Episoden speichern
if (isset($data['episodes']) && is_array($data['episodes'])) { if (isset($data['episodes']) && is_array($data['episodes'])) {
foreach ($data['episodes'] as $episode) { foreach ($data['episodes'] as $episode) {
$this->addEpisode($mediaId, $episode); $this->addEpisode($mediaId, $episode);
} }
} }
return $mediaId; return $mediaId;
} }
public function updateWithRelations($id, $data) { public function updateWithRelations(int $id, array $data): bool {
parent::updateWithRelations($id, $data); parent::updateWithRelations($id, $data);
// Episoden aktualisieren // Episoden aktualisieren
if (isset($data['episodes']) && is_array($data['episodes'])) { if (isset($data['episodes']) && is_array($data['episodes'])) {
// Alle existierenden Episoden löschen // Alle existierenden Episoden löschen
@@ -134,7 +137,6 @@ class Series extends MediaType {
$this->addEpisode($id, $episode); $this->addEpisode($id, $episode);
} }
} }
return true; return true;
} }
} }

View File

@@ -1,19 +1,21 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/BaseModel.php'; require_once __DIR__ . '/BaseModel.php';
class Settings extends BaseModel { class Settings extends BaseModel {
protected $table = 'settings'; protected string $table = 'settings';
public function __construct($pdo) { public function __construct(PDO $pdo) {
parent::__construct($pdo); parent::__construct($pdo);
} }
public function getSettings() { public function getSettings(): ?array {
$stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = 1"); $stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = 1");
$stmt->execute(); $stmt->execute();
$settings = $stmt->fetch(); $settings = $stmt->fetch();
if ($settings) { if ($settings) {
// Decode enabled_categories from JSON // Decode enabled_categories from JSON
$settings['enabled_categories'] = $settings['enabled_categories'] ? json_decode($settings['enabled_categories'], true) : []; $settings['enabled_categories'] = $settings['enabled_categories'] ? json_decode($settings['enabled_categories'], true) : [];
@@ -21,11 +23,11 @@ class Settings extends BaseModel {
$settings['show_adult_content'] = (bool)$settings['show_adult_content']; $settings['show_adult_content'] = (bool)$settings['show_adult_content'];
$settings['auto_play_trailers'] = (bool)$settings['auto_play_trailers']; $settings['auto_play_trailers'] = (bool)$settings['auto_play_trailers'];
} }
return $settings; return $settings;
} }
public function updateSettings($data) { public function updateSettings(array $data): ?array {
$updateData = []; $updateData = [];
if (isset($data['enabled_categories']) && is_array($data['enabled_categories'])) { if (isset($data['enabled_categories']) && is_array($data['enabled_categories'])) {
@@ -51,10 +53,14 @@ class Settings extends BaseModel {
if (isset($data['language'])) { if (isset($data['language'])) {
$updateData['language'] = $data['language']; $updateData['language'] = $data['language'];
} }
if (isset($data['theme'])) { if (isset($data['theme'])) {
$updateData['theme'] = $data['theme']; $updateData['theme'] = $data['theme'];
} }
if (isset($data['jellyfin_library_mappings'])) {
$updateData['jellyfin_library_mappings'] = $data['jellyfin_library_mappings'];
}
// Check if settings row exists // Check if settings row exists
$existing = $this->findById(1); $existing = $this->findById(1);
@@ -72,7 +78,7 @@ class Settings extends BaseModel {
'auto_play_trailers' => 0, 'auto_play_trailers' => 0,
'language' => 'en', 'language' => 'en',
'theme' => 'system', 'theme' => 'system',
'theme' => 'system' 'jellyfin_library_mappings' => ''
]; ];
$mergedData = array_merge($defaultData, $updateData); $mergedData = array_merge($defaultData, $updateData);
$this->create($mergedData); $this->create($mergedData);

View File

@@ -1,10 +1,13 @@
<?php <?php
declare(strict_types=1);
require_once __DIR__ . '/../database.php'; require_once __DIR__ . '/../database.php';
class ApiLogger { class ApiLogger {
private static $instance = null; private static ?ApiLogger $instance = null;
private $pdo; private PDO $pdo;
private $enabled; private bool $enabled;
private function __construct() { private function __construct() {
$this->enabled = API_LOGGING_ENABLED; $this->enabled = API_LOGGING_ENABLED;
@@ -12,14 +15,14 @@ class ApiLogger {
$this->pdo = $db->getConnection(); $this->pdo = $db->getConnection();
} }
public static function getInstance() { public static function getInstance(): ApiLogger {
if (self::$instance === null) { if (self::$instance === null) {
self::$instance = new self(); self::$instance = new self();
} }
return self::$instance; return self::$instance;
} }
public function logRequest($method, $path, $params = [], $body = null) { public function logRequest(string|array $method, string|array $path, array $params = [], string|array|null $body = null): void {
if (!$this->enabled) { if (!$this->enabled) {
return; return;
} }
@@ -29,7 +32,7 @@ class ApiLogger {
INSERT INTO api_logs (type, method, path, params, body) INSERT INTO api_logs (type, method, path, params, body)
VALUES ('REQUEST', :method, :path, :params, :body) VALUES ('REQUEST', :method, :path, :params, :body)
"); ");
$methodValue = is_array($method) ? (json_encode($method) ?: '[array]') : (string)$method; $methodValue = is_array($method) ? (json_encode($method) ?: '[array]') : (string)$method;
$pathValue = is_array($path) ? (json_encode($path) ?: '[array]') : (string)$path; $pathValue = is_array($path) ? (json_encode($path) ?: '[array]') : (string)$path;
$paramsValue = is_array($params) ? (json_encode($params) ?: '[array]') : (string)$params; $paramsValue = is_array($params) ? (json_encode($params) ?: '[array]') : (string)$params;
@@ -37,19 +40,19 @@ class ApiLogger {
if ($body) { if ($body) {
$bodyValue = is_array($body) ? (json_encode($body) ?: '[array]') : (string)$body; $bodyValue = is_array($body) ? (json_encode($body) ?: '[array]') : (string)$body;
} }
$stmt->execute([ $stmt->execute([
':method' => $methodValue, ':method' => $methodValue,
':path' => $pathValue, ':path' => $pathValue,
':params' => $paramsValue, ':params' => $paramsValue,
':body' => $bodyValue ':body' => $bodyValue
]); ]);
} catch (Exception $e) { } catch (Throwable $e) {
error_log('Failed to log request: ' . $e->getMessage()); error_log('Failed to log request: ' . $e->getMessage());
} }
} }
public function logResponse($method, $path, $statusCode, $response) { public function logResponse(string|array $method, string|array $path, int $statusCode, array $response): void {
if (!$this->enabled) { if (!$this->enabled) {
return; return;
} }
@@ -65,12 +68,12 @@ class ApiLogger {
':status_code' => $statusCode, ':status_code' => $statusCode,
':response' => (json_encode($response) ?: '[encoding_failed]') ':response' => (json_encode($response) ?: '[encoding_failed]')
]); ]);
} catch (Exception $e) { } catch (Throwable $e) {
error_log('Failed to log response: ' . $e->getMessage()); error_log('Failed to log response: ' . $e->getMessage());
} }
} }
public function logError($method, $path, $error) { public function logError(string|array $method, string|array $path, string|array $error): void {
if (!$this->enabled) { if (!$this->enabled) {
return; return;
} }
@@ -85,12 +88,12 @@ class ApiLogger {
':path' => is_array($path) ? (json_encode($path) ?: '[array]') : (string)$path, ':path' => is_array($path) ? (json_encode($path) ?: '[array]') : (string)$path,
':error' => is_array($error) ? (json_encode($error) ?: '[array]') : (string)$error ':error' => is_array($error) ? (json_encode($error) ?: '[array]') : (string)$error
]); ]);
} catch (Exception $e) { } catch (Throwable $e) {
error_log('Failed to log error: ' . $e->getMessage()); error_log('Failed to log error: ' . $e->getMessage());
} }
} }
public function logDebug($message) { public function logDebug(string|array $message): void {
if (!$this->enabled) { if (!$this->enabled) {
return; return;
} }
@@ -103,7 +106,7 @@ class ApiLogger {
$stmt->execute([ $stmt->execute([
':message' => is_array($message) ? (json_encode($message) ?: '[array]') : (string)$message ':message' => is_array($message) ? (json_encode($message) ?: '[array]') : (string)$message
]); ]);
} catch (Exception $e) { } catch (Throwable $e) {
error_log('Failed to log debug: ' . $e->getMessage()); error_log('Failed to log debug: ' . $e->getMessage());
} }
} }

View File

@@ -1,15 +1,17 @@
<?php <?php
declare(strict_types=1);
class DocumentationService { class DocumentationService {
private $controllersPath; private string $controllersPath;
private $modelsPath; private string $modelsPath;
public function __construct($controllersPath = __DIR__ . '/../controllers/', $modelsPath = __DIR__ . '/../models/') { public function __construct(string $controllersPath = __DIR__ . '/../controllers/', string $modelsPath = __DIR__ . '/../models/') {
$this->controllersPath = $controllersPath; $this->controllersPath = $controllersPath;
$this->modelsPath = $modelsPath; $this->modelsPath = $modelsPath;
} }
public function generateDocumentation() { public function generateDocumentation(): array {
$docs = [ $docs = [
'title' => 'Media API Documentation', 'title' => 'Media API Documentation',
'version' => '1.0.0', 'version' => '1.0.0',
@@ -27,7 +29,7 @@ class DocumentationService {
return $docs; return $docs;
} }
private function scanControllers() { private function scanControllers(): array {
$endpoints = []; $endpoints = [];
$controllerFiles = glob($this->controllersPath . '*Controller.php'); $controllerFiles = glob($this->controllersPath . '*Controller.php');
@@ -56,7 +58,7 @@ class DocumentationService {
return $endpoints; return $endpoints;
} }
private function parseMethodDoc($docComment, $methodName, $className) { private function parseMethodDoc(?string $docComment, string $methodName, string $className): ?array {
if (!$docComment) { if (!$docComment) {
return null; return null;
} }
@@ -106,7 +108,7 @@ class DocumentationService {
return $info; return $info;
} }
private function inferHttpMethods($methodName) { private function inferHttpMethods(string $methodName): array {
$methods = []; $methods = [];
if (strpos($methodName, 'get') === 0) { if (strpos($methodName, 'get') === 0) {
@@ -129,7 +131,7 @@ class DocumentationService {
return $methods; return $methods;
} }
private function inferPath($className, $methodName) { private function inferPath(string $className, string $methodName): string {
$resource = strtolower(str_replace('Controller', '', $className)); $resource = strtolower(str_replace('Controller', '', $className));
$path = "/{$resource}"; $path = "/{$resource}";
@@ -156,7 +158,7 @@ class DocumentationService {
return $path; return $path;
} }
private function scanModels() { private function scanModels(): array {
$models = []; $models = [];
$modelFiles = glob($this->modelsPath . '*.php'); $modelFiles = glob($this->modelsPath . '*.php');

View File

@@ -1,27 +1,29 @@
<?php <?php
declare(strict_types=1);
class ImageHandler { class ImageHandler {
private $uploadDir; private string $uploadDir;
private $baseUrl; private string $baseUrl;
public function __construct($uploadDir = null, $baseUrl = null) { public function __construct(?string $uploadDir = null, ?string $baseUrl = null) {
$this->uploadDir = $uploadDir ?? __DIR__ . '/../public/images/'; $this->uploadDir = $uploadDir ?? __DIR__ . '/../public/images/';
$this->baseUrl = $baseUrl ?? '/images/'; $this->baseUrl = $baseUrl ?? '/images/';
// Ensure upload directory exists // Ensure upload directory exists
if (!file_exists($this->uploadDir)) { if (!file_exists($this->uploadDir)) {
mkdir($this->uploadDir, 0755, true); mkdir($this->uploadDir, 0755, true);
} }
} }
/** /**
* Process base64 image data and save to file * Process base64 image data and save to file
* *
* @param string $base64Data Base64 encoded image data * @param string $base64Data Base64 encoded image data
* @param string $prefix Prefix for filename (e.g., 'poster', 'banner') * @param string $prefix Prefix for filename (e.g., 'poster', 'banner')
* @return string|null Relative path to saved image, or null if invalid * @return string|null Relative path to saved image, or null if invalid
*/ */
public function saveBase64Image($base64Data, $prefix = 'image') { public function saveBase64Image(string $base64Data, string $prefix = 'image'): ?string {
error_log("ImageHandler: Starting to process base64 image, length: " . strlen($base64Data)); error_log("ImageHandler: Starting to process base64 image, length: " . strlen($base64Data));
if (empty($base64Data)) { if (empty($base64Data)) {
@@ -119,7 +121,7 @@ class ImageHandler {
/** /**
* Detect image format from base64 string * Detect image format from base64 string
*/ */
private function detectImageFormat($base64String) { private function detectImageFormat(string $base64String): ?string {
// Decode first few bytes to check magic numbers // Decode first few bytes to check magic numbers
$data = base64_decode(substr($base64String, 0, 100)); $data = base64_decode(substr($base64String, 0, 100));
@@ -140,7 +142,7 @@ class ImageHandler {
/** /**
* Validate that data is a valid image * Validate that data is a valid image
*/ */
private function isValidImage($data) { private function isValidImage(string $data): bool {
try { try {
$image = imagecreatefromstring($data); $image = imagecreatefromstring($data);
if ($image !== false) { if ($image !== false) {
@@ -156,14 +158,14 @@ class ImageHandler {
/** /**
* Generate unique filename * Generate unique filename
*/ */
private function generateUniqueFilename($prefix, $extension) { private function generateUniqueFilename(string $prefix, string $extension): string {
return $prefix . '_' . uniqid() . '_' . time() . '.' . $extension; return $prefix . '_' . uniqid() . '_' . time() . '.' . $extension;
} }
/** /**
* Delete an image file * Delete an image file
*/ */
public function deleteImage($imagePath) { public function deleteImage(?string $imagePath): bool {
if (empty($imagePath)) { if (empty($imagePath)) {
return false; return false;
} }