Stuff i guess ?

This commit is contained in:
Lars Behrends
2025-10-31 00:24:17 +01:00
parent db0fd4e728
commit 04140786a7
40 changed files with 5411 additions and 525 deletions

View File

@@ -40,6 +40,424 @@ class AdminController extends AdminBaseController
]);
}
/**
* Media Management
*/
// Movies Management
public function movies(Request $request, Response $response, $args)
{
$movieModel = new \App\Models\Movie($this->pdo);
// Get query parameters with defaults
$page = max(1, (int)($request->getQueryParams()['page'] ?? 1));
$search = trim($request->getQueryParams()['search'] ?? '');
$genre = trim($request->getQueryParams()['genre'] ?? '');
$director = trim($request->getQueryParams()['director'] ?? '');
$sort = trim($request->getQueryParams()['sort'] ?? 'title_asc');
$perPage = 20;
// Prepare filters for the view
$filters = [
'search' => $search,
'genre' => $genre,
'director' => $director,
'sort' => $sort
];
// Get paginated and filtered movies
$movies = $movieModel->getPaginated(
$this->pdo,
$page,
$perPage,
$search,
$genre ? [$genre] : [],
$sort
);
// Get available genres and directors for filters
$genres = $movieModel->getGenres($this->pdo);
$directors = $movieModel->getDirectors($this->pdo);
// Calculate pagination data
$totalMovies = $movieModel->getTotalCount(
$this->pdo,
$search,
$genre ? [$genre] : []
);
$totalPages = max(1, ceil($totalMovies / $perPage));
$currentPage = min($page, $totalPages);
// Get flash messages if any
// $successMessages = $this->container->get('flash')->getMessage('success');
return $this->render($response, 'admin/movies/index.twig', [
'title' => 'Manage Movies',
'movies' => $movies,
'genres' => $genres,
'directors' => $directors,
'filters' => $filters,
'pagination' => [
'current' => $currentPage,
'total' => $totalPages,
'per_page' => $perPage,
'total_items' => $totalMovies,
'from' => (($currentPage - 1) * $perPage) + 1,
'to' => min($currentPage * $perPage, $totalMovies)
]
]);
}
public function editMovie(Request $request, Response $response, $args)
{
$id = $args['id'] ?? null;
$movieModel = new \App\Models\Movie($this->pdo);
if ($request->getMethod() === 'POST') {
$data = $request->getParsedBody();
if ($id) {
// Update existing movie
$movieModel->update($id, $data);
//$this->flash->addMessage('success', 'Movie updated successfully');
} else {
// Create new movie
$id = $movieModel->create($data);
// $this->flash->addMessage('success', 'Movie created successfully');
}
return $response->withHeader('Location', '/admin/movies/' . $id . '/edit')
->withStatus(302);
}
$movie = $id ? $movieModel->find($id) : null;
return $this->render($response, 'admin/movies/edit.twig', [
'title' => $id ? 'Edit Movie' : 'Add New Movie',
'movie' => $movie
]);
}
public function deleteMovie(Request $request, Response $response, $args)
{
$id = $args['id'];
$movieModel = new \App\Models\Movie($this->pdo);
$movieModel->delete($id);
$this->flash->addMessage('success', 'Movie deleted successfully');
return $response->withHeader('Location', '/admin/movies')
->withStatus(302);
}
// Games Management
public function games(Request $request, Response $response, $args)
{
$gameModel = new \App\Models\Game($this->pdo);
// Get query parameters
$page = (int)($request->getQueryParams()['page'] ?? 1);
$search = $request->getQueryParams()['search'] ?? '';
$platform = $request->getQueryParams()['platform'] ?? '';
$genre = $request->getQueryParams()['genre'] ?? '';
$isInstalled = $request->getQueryParams()['installed'] ?? '';
$isFavorite = $request->getQueryParams()['favorite'] ?? '';
$sort = $request->getQueryParams()['sort'] ?? 'title_asc';
$perPage = 20; // Items per page
// Prepare filters
$filters = [
'search' => $search,
'platform' => $platform,
'genre' => $genre,
'is_installed' => $isInstalled,
'is_favorite' => $isFavorite,
'sort' => $sort
];
// Get paginated and filtered games
$result = $gameModel->getGroupedGamesWithPagination(
$this->pdo,
$page,
$perPage,
$search,
$genre ? [$genre] : [],
$platform ? [$platform] : []
);
// Get available platforms and genres for filters
$platforms = $gameModel->getPlatforms();
$genres = $gameModel->getGenres();
// Calculate pagination data
$totalGames = $gameModel->getTotalCount(
$this->pdo,
$search,
$genre ? [$genre] : [],
$platform ? [$platform] : []
);
$totalPages = ceil($totalGames / $perPage);
return $this->render($response, 'admin/games/index.twig', [
'title' => 'Manage Games',
'games' => $result,
'platforms' => $platforms,
'genres' => $genres,
'filters' => $filters,
'pagination' => [
'current' => $page,
'total' => $totalPages,
'per_page' => $perPage,
'total_items' => $totalGames
]
]);
}
public function editGame(Request $request, Response $response, $args)
{
$id = $args['id'] ?? null;
$gameModel = new \App\Models\Game($this->pdo);
if ($request->getMethod() === 'POST') {
$data = $request->getParsedBody();
if ($id) {
$gameModel->update($id, $data);
} else {
$id = $gameModel->create($data);
}
return $response->withHeader('Location', '/admin/games/' . $id . '/edit')
->withStatus(302);
}
$game = $id ? $gameModel->find($id) : null;
return $this->render($response, 'admin/games/edit.twig', [
'title' => $id ? 'Edit Game' : 'Add New Game',
'game' => $game
]);
}
public function deleteGame(Request $request, Response $response, $args)
{
$id = $args['id'];
$gameModel = new \App\Models\Game($this->pdo);
$gameModel->delete($id);
return $response->withHeader('Location', '/admin/games')
->withStatus(302);
}
// TV Shows Management
public function shows(Request $request, Response $response, $args)
{
$showModel = new \App\Models\TvShow($this->pdo);
// Get query parameters with defaults
$page = max(1, (int)($request->getQueryParams()['page'] ?? 1));
$search = trim($request->getQueryParams()['search'] ?? '');
$genre = trim($request->getQueryParams()['genre'] ?? '');
$network = trim($request->getQueryParams()['network'] ?? '');
$status = trim($request->getQueryParams()['status'] ?? '');
$sort = trim($request->getQueryParams()['sort'] ?? 'name_asc');
$perPage = 20;
// Prepare filters for the view
$filters = [
'search' => $search,
'genre' => $genre,
'network' => $network,
'status' => $status,
'sort' => $sort
];
// Get paginated and filtered shows
$shows = $showModel->getPaginated(
$this->pdo,
$page,
$perPage,
$search,
$genre ? [$genre] : [],
$network ? [$network] : [],
$status ? [$status] : [],
$sort
);
// Get available filters
$genres = $showModel->getGenres($this->pdo);
//$networks = $showModel->getNetworks($this->pdo);
$statuses = ['Returning Series', 'Ended', 'Canceled', 'In Production'];
// Calculate pagination data
$totalShows = $showModel->getTotalCount(
$this->pdo,
$search,
$genre ? [$genre] : [],
$network ? [$network] : [],
$status ? [$status] : []
);
$totalPages = max(1, ceil($totalShows / $perPage));
$currentPage = min($page, $totalPages);
return $this->render($response, 'admin/shows/index.twig', [
'title' => 'Manage TV Shows',
'shows' => $shows,
'genres' => $genres,
//'networks' => $networks,
'statuses' => $statuses,
'filters' => $filters,
'pagination' => [
'current' => $currentPage,
'total' => $totalPages,
'per_page' => $perPage,
'total_items' => $totalShows,
'from' => (($currentPage - 1) * $perPage) + 1,
'to' => min($currentPage * $perPage, $totalShows)
]
]);
}
public function editShow(Request $request, Response $response, $args)
{
$id = $args['id'] ?? null;
$showModel = new \App\Models\TvShow($this->pdo);
if ($request->getMethod() === 'POST') {
$data = $request->getParsedBody();
if ($id) {
$showModel->update($id, $data);
} else {
$id = $showModel->create($data);
}
return $response->withHeader('Location', '/admin/shows/' . $id . '/edit')
->withStatus(302);
}
$show = $id ? $showModel->find($id) : null;
return $this->render($response, 'admin/shows/edit.twig', [
'title' => $id ? 'Edit TV Show' : 'Add New TV Show',
'show' => $show
]);
}
public function deleteShow(Request $request, Response $response, $args)
{
$id = $args['id'];
$showModel = new \App\Models\TvShow($this->pdo);
$showModel->delete($id);
return $response->withHeader('Location', '/admin/shows')
->withStatus(302);
}
/**
* Display a listing of adult videos with pagination and filters
*/
public function adultVideos(Request $request, Response $response, $args)
{
$adultVideoModel = new \App\Models\AdultVideo($this->pdo);
// Get query parameters with defaults
$page = max(1, (int)($request->getQueryParams()['page'] ?? 1));
$search = trim($request->getQueryParams()['search'] ?? '');
$genre = trim($request->getQueryParams()['genre'] ?? '');
$director = trim($request->getQueryParams()['director'] ?? '');
$sort = trim($request->getQueryParams()['sort'] ?? 'newest');
$perPage = 20;
// Prepare filters for the view
$filters = [
'search' => $search,
'genre' => $genre,
'director' => $director,
'sort' => $sort
];
// Get available filters
$genres = $adultVideoModel::getAvailableGenres($this->pdo);
$directors = $adultVideoModel::getAvailableDirectors($this->pdo);
// Get paginated and filtered adult videos
$videos = $adultVideoModel::getAllWithPagination(
$this->pdo,
$page,
$perPage,
$search,
$genre ? [$genre] : [],
$director ? [$director] : []
);
// Get total count for pagination
$totalVideos = $adultVideoModel::getTotalCount(
$this->pdo,
$search,
$genre ? [$genre] : [],
$director ? [$director] : []
);
$totalPages = max(1, ceil($totalVideos / $perPage));
$currentPage = min($page, $totalPages);
return $this->render($response, 'admin/adult/index.twig', [
'title' => 'Manage Adult Videos',
'videos' => $videos,
'genres' => $genres,
'directors' => $directors,
'filters' => $filters,
'pagination' => [
'current' => $currentPage,
'total' => $totalPages,
'per_page' => $perPage,
'total_items' => $totalVideos,
'from' => (($currentPage - 1) * $perPage) + 1,
'to' => min($currentPage * $perPage, $totalVideos)
]
]);
}
public function editAdultVideo(Request $request, Response $response, $args)
{
$id = $args['id'] ?? null;
$adultModel = new \App\Models\AdultVideo($this->pdo);
if ($request->getMethod() === 'POST') {
$data = $request->getParsedBody();
if ($id) {
$adultModel->update($id, $data);
} else {
$id = $adultModel->create($data);
}
return $response->withHeader('Location', '/admin/adult/' . $id . '/edit')
->withStatus(302);
}
$video = $id ? $adultModel->find($id) : null;
return $this->render($response, 'admin/adult/edit.twig', [
'title' => $id ? 'Edit Adult Video' : 'Add New Adult Video',
'video' => $video
]);
}
public function deleteAdultVideo(Request $request, Response $response, $args)
{
$id = $args['id'];
$adultModel = new \App\Models\AdultVideo($this->pdo);
$adultModel->delete($id);
return $response->withHeader('Location', '/admin/adult')
->withStatus(302);
}
public function syncSource(Request $request, Response $response, $args)
{
$sourceId = $args['id'];
@@ -202,4 +620,119 @@ class AdminController extends AdminBaseController
'message' => 'Sync process starting in background'
]);
}
/**
* Get actors for a specific adult video
*/
public function getAdultVideoActors(Request $request, Response $response, $args)
{
$adultVideo = new \App\Models\AdultVideo($this->pdo);
$video = $adultVideo->find($args['id']);
if (!$video) {
$response->getBody()->write(json_encode(['error' => 'Video not found']));
return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
}
$actors = $adultVideo->actors($args['id']);
$response->getBody()->write(json_encode(['data' => $actors]));
return $response->withHeader('Content-Type', 'application/json');
}
/**
* Add an actor to an adult video
*/
public function addActorToAdultVideo(Request $request, Response $response, $args)
{
$contentType = $request->getHeaderLine('Content-Type');
if (strstr($contentType, 'application/json')) {
$data = json_decode((string)$request->getBody(), true);
} else {
$data = $request->getParsedBody();
}
$actorId = $data['actor_id'] ?? null;
if (!$actorId) {
$response->getBody()->write(json_encode(['error' => 'Actor ID is required']));
return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
}
$adultVideo = new \App\Models\AdultVideo($this->pdo);
$video = $adultVideo->find($args['id']);
if (!$video) {
$response->getBody()->write(json_encode(['error' => 'Video not found']));
return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
}
$success = $adultVideo->addActor($actorId);
if ($success) {
$adultVideo->updateCastField();
$response->getBody()->write(json_encode([
'success' => true,
'message' => 'Actor added successfully'
]));
return $response->withHeader('Content-Type', 'application/json');
}
$response->getBody()->write(json_encode(['error' => 'Failed to add actor']));
return $response->withStatus(500)->withHeader('Content-Type', 'application/json');
}
/**
* Remove an actor from an adult video
*/
public function removeActorFromAdultVideo(Request $request, Response $response, $args)
{
$actorId = $args['actorId'] ?? null;
if (!$actorId) {
$response->getBody()->write(json_encode(['error' => 'Actor ID is required']));
return $response->withStatus(400)->withHeader('Content-Type', 'application/json');
}
$adultVideo = new \App\Models\AdultVideo($this->pdo);
$video = $adultVideo->find($args['id']);
if (!$video) {
$response->getBody()->write(json_encode(['error' => 'Video not found']));
return $response->withStatus(404)->withHeader('Content-Type', 'application/json');
}
$success = $adultVideo->removeActor($actorId);
if ($success) {
$adultVideo->updateCastField();
$response->getBody()->write(json_encode([
'success' => true,
'message' => 'Actor removed successfully'
]));
return $response->withHeader('Content-Type', 'application/json');
}
$response->getBody()->write(json_encode(['error' => 'Failed to remove actor']));
return $response->withStatus(500)->withHeader('Content-Type', 'application/json');
}
/**
* Search actors by name
*/
public function searchActors(Request $request, Response $response, $args)
{
$query = $request->getQueryParams()['q'] ?? '';
if (empty($query)) {
$response->getBody()->write(json_encode(['data' => []]));
return $response->withHeader('Content-Type', 'application/json');
}
$adultVideo = new \App\Models\AdultVideo($this->pdo);
$actors = $adultVideo->searchActors($this->pdo, $query);
$response->getBody()->write(json_encode(['data' => $actors]));
return $response->withHeader('Content-Type', 'application/json');
}
}

View File

@@ -41,11 +41,12 @@ class AdultController extends Controller
}
$directors = array_filter($directors);
// Get view mode
// Get view mode and sort
$viewMode = $queryParams['view'] ?? 'grid'; // grid, list, covers
$sort = $queryParams['sort'] ?? 'recent';
// Get adult videos with pagination and filters
$adultVideos = AdultVideo::getAllWithPagination($this->pdo, $page, $perPage, $search, $genres, $directors);
// Get adult videos with pagination, filters, and sorting
$adultVideos = AdultVideo::getAllWithPagination($this->pdo, $page, $perPage, $search, $genres, $directors, $sort);
// Process metadata to extract local image paths for template compatibility
foreach ($adultVideos as &$video) {
@@ -94,6 +95,21 @@ class AdultController extends Controller
'search' => $search,
'view_mode' => $viewMode,
'view_modes' => ['grid', 'list', 'covers'],
'sort' => $sort,
'sort_options' => [
'recent' => 'Most Recent',
'oldest' => 'Oldest First',
'title_asc' => 'Title (A-Z)',
'title_desc' => 'Title (Z-A)',
'year_asc' => 'Release Year (Oldest First)',
'year_desc' => 'Release Year (Newest First)',
'rating_desc' => 'Highest Rated',
'rating_asc' => 'Lowest Rated',
'views_desc' => 'Most Viewed',
'views_asc' => 'Least Viewed',
'runtime_desc' => 'Longest Runtime',
'runtime_asc' => 'Shortest Runtime',
],
'filters' => [
'genres' => $genres,
'directors' => $directors

View File

@@ -0,0 +1,51 @@
<?php
namespace App\Controllers\Api;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use App\Controllers\Controller;
use App\Services\AuthService;
class AuthController extends Controller
{
private AuthService $authService;
public function __construct(AuthService $authService)
{
$this->authService = $authService;
}
/**
* Check if user is authenticated (API endpoint)
*/
public function checkAuth(Request $request, Response $response, $args)
{
try {
if (!$this->authService->isLoggedIn()) {
return $this->jsonResponse($response->withStatus(401), [
'error' => '401 Forbidden'
]);
}
$user = $this->authService->getCurrentUser();
if (!$user) {
return $this->jsonResponse($response->withStatus(401), [
'error' => '401 Forbidden'
]);
}
return $this->jsonResponse($response, [
'id' => $user['id'],
'username' => $user['username'],
'email' => $user['email'],
'is_admin' => $this->authService->isAdmin()
]);
} catch (\Exception $e) {
return $this->jsonResponse($response->withStatus(500), [
'error' => 'Authentication check failed'
]);
}
}
}

View File

@@ -0,0 +1,569 @@
<?php
namespace App\Controllers\Api;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use App\Controllers\Controller;
use App\Models\Game;
use App\Services\PlayniteImportService;
class PlayniteController extends Controller
{
private \PDO $pdo;
private PlayniteImportService $importService;
public function __construct(\PDO $pdo)
{
$this->pdo = $pdo;
$this->importService = new PlayniteImportService($pdo);
}
/**
* @OA\Post(
* path="/playnite/insert",
* summary="Insert or update games from Playnite",
* tags={"Playnite"},
* operationId="insertGames",
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"games"},
* @OA\Property(
* property="games",
* type="array",
* @OA\Items(type="object")
* ),
* @OA\Property(
* property="update_existing",
* type="boolean",
* default=true,
* description="Whether to update existing games"
* )
* )
* ),
* @OA\Response(
* response=200,
* description="Games successfully imported/updated",
* @OA\JsonContent(
* @OA\Property(property="success", type="boolean"),
* @OA\Property(property="result", type="object")
* )
* ),
* @OA\Response(
* response=400,
* description="Invalid input"
* ),
* @OA\Response(
* response=500,
* description="Server error"
* )
* )
*
* @param Request $request
* @param Response $response
* @param array $args
* @return Response
*/
public function insertGames(Request $request, Response $response, $args)
{
$data = $request->getParsedBody();
if (!isset($data['games']) || !is_array($data['games'])) {
return $this->jsonResponse($response->withStatus(400), [
'error' => 'Games data is required'
]);
}
try {
$importResult = $this->importService->importGames($data['games'], true);
return $this->jsonResponse($response, [
'success' => true,
'result' => $importResult
]);
} catch (\Exception $e) {
return $this->jsonResponse($response->withStatus(500), [
'error' => $e->getMessage()
]);
}
}
/**
* @OA\Put(
* path="/playnite/update",
* summary="Update existing games from Playnite",
* tags={"Playnite"},
* operationId="updateGames",
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"games"},
* @OA\Property(
* property="games",
* type="array",
* @OA\Items(type="object")
* )
* )
* ),
* @OA\Response(
* response=200,
* description="Games successfully updated",
* @OA\JsonContent(
* @OA\Property(property="success", type="boolean"),
* @OA\Property(property="result", type="object")
* )
* ),
* @OA\Response(
* response=400,
* description="Invalid input"
* ),
* @OA\Response(
* response=500,
* description="Server error"
* )
* )
*
* @param Request $request
* @param Response $response
* @param array $args
* @return Response
*/
public function updateGames(Request $request, Response $response, $args)
{
$data = $request->getParsedBody();
if (!isset($data['games']) || !is_array($data['games'])) {
return $this->jsonResponse($response->withStatus(400), [
'error' => 'Games data is required'
]);
}
try {
$importResult = $this->importService->importGames($data['games'], true);
return $this->jsonResponse($response, [
'success' => true,
'result' => $importResult
]);
} catch (\Exception $e) {
return $this->jsonResponse($response->withStatus(500), [
'error' => $e->getMessage()
]);
}
}
/**
* @OA\Delete(
* path="/playnite/delete",
* summary="Delete games from Playnite",
* tags={"Playnite"},
* operationId="deleteGames",
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* required={"games"},
* @OA\Property(
* property="games",
* type="array",
* @OA\Items(type="object")
* )
* )
* ),
* @OA\Response(
* response=200,
* description="Games successfully deleted",
* @OA\JsonContent(
* @OA\Property(property="success", type="boolean"),
* @OA\Property(property="result", type="object",
* @OA\Property(property="deleted", type="integer"),
* @OA\Property(property="errors", type="array", @OA\Items(type="string"))
* )
* )
* ),
* @OA\Response(
* response=400,
* description="Invalid input"
* ),
* @OA\Response(
* response=500,
* description="Server error"
* )
* )
*
* @param Request $request
* @param Response $response
* @param array $args
* @return Response
*/
public function deleteGames(Request $request, Response $response, $args)
{
$data = $request->getParsedBody();
if (!isset($data['games']) || !is_array($data['games'])) {
return $this->jsonResponse($response->withStatus(400), [
'error' => 'Games data is required'
]);
}
try {
$results = [
'deleted' => 0,
'errors' => []
];
foreach ($data['games'] as $gameData) {
try {
// Find the game by platform_game_id and source_id
$existingGame = $this->findExistingGame($gameData);
if ($existingGame) {
$this->deleteGame($existingGame['id']);
$results['deleted']++;
}
} catch (\Exception $e) {
$results['errors'][] = "Failed to delete {$gameData['title']}: " . $e->getMessage();
}
}
return $this->jsonResponse($response, [
'success' => true,
'result' => $results
]);
} catch (\Exception $e) {
return $this->jsonResponse($response->withStatus(500), [
'error' => $e->getMessage()
]);
}
}
/**
* @OA\Post(
* path="/playnite/upload-images",
* summary="Upload game images from Playnite",
* tags={"Playnite"},
* operationId="uploadImages",
* @OA\RequestBody(
* required=true,
* @OA\JsonContent(
* oneOf={
* @OA\Schema(
* @OA\Property(property="name", type="string"),
* @OA\Property(property="cover", type="string", format="byte"),
* @OA\Property(property="icon", type="string", format="byte"),
* @OA\Property(property="background", type="string", format="byte")
* ),
* @OA\Schema(
* @OA\Property(
* property="games",
* type="array",
* @OA\Items(
* @OA\Property(property="name", type="string"),
* @OA\Property(property="cover", type="string", format="byte"),
* @OA\Property(property="icon", type="string", format="byte"),
* @OA\Property(property="background", type="string", format="byte")
* )
* )
* )
* }
* )
* ),
* @OA\Response(
* response=200,
* description="Images successfully uploaded",
* @OA\JsonContent(
* @OA\Property(property="success", type="boolean"),
* @OA\Property(property="result", type="object",
* @OA\Property(property="uploaded", type="integer"),
* @OA\Property(property="errors", type="array", @OA\Items(type="string"))
* )
* )
* ),
* @OA\Response(
* response=500,
* description="Server error"
* )
* )
*
* @param Request $request
* @param Response $response
* @param array $args
* @return Response
*/
public function uploadImages(Request $request, Response $response, $args)
{
$data = $request->getParsedBody();
try {
$results = [
'uploaded' => 0,
'errors' => []
];
// Handle image uploads based on the format expected by the plugin
if (isset($data['name']) && isset($data['cover'])) {
// Single game image upload
$result = $this->handleImageUpload($data);
if ($result) {
$results['uploaded']++;
}
} elseif (isset($data['games']) && is_array($data['games'])) {
// Multiple games with images
foreach ($data['games'] as $gameData) {
$result = $this->handleImageUpload($gameData);
if ($result) {
$results['uploaded']++;
}
}
}
return $this->jsonResponse($response, [
'success' => true,
'result' => $results
]);
} catch (\Exception $e) {
return $this->jsonResponse($response->withStatus(500), [
'error' => $e->getMessage()
]);
}
}
/**
* Handle individual image upload
*/
private function handleImageUpload(array $gameData): bool
{
try {
// For now, we'll just validate the data format
// In a real implementation, you might want to save the images to disk
// and update the game records with the image paths
$name = $gameData['name'] ?? '';
$cover = $gameData['cover'] ?? '';
$icon = $gameData['icon'] ?? '';
$background = $gameData['background'] ?? '';
// Validate base64 images
if ($cover && !preg_match('/^data:image\/(jpeg|png|gif|webp);base64,/', $cover)) {
throw new \Exception("Invalid cover image format");
}
// Here you would typically:
// 1. Decode base64 images
// 2. Save them to the filesystem
// 3. Update the game record with the image paths
return true;
} catch (\Exception $e) {
error_log("Image upload failed for game {$name}: " . $e->getMessage());
return false;
}
}
/**
* Find existing game by platform_game_id and source_id
*/
private function findExistingGame(array $gameData): ?array
{
$stmt = $this->pdo->prepare("
SELECT id, title, platform_game_id, source_id
FROM games
WHERE platform_game_id = :platform_game_id AND source_id = :source_id
");
$stmt->execute([
'platform_game_id' => $gameData['platform_game_id'],
'source_id' => $gameData['source_id']
]);
return $stmt->fetch(\PDO::FETCH_ASSOC) ?: null;
}
/**
* Delete game
*/
private function deleteGame(int $gameId): void
{
$stmt = $this->pdo->prepare("DELETE FROM games WHERE id = :id");
$stmt->execute(['id' => $gameId]);
}
/**
* Transform Playnite game data to internal format
*/
private function transformPlayniteGame(array $game): array
{
// Find or create source
$source = $this->findOrCreateSource($game);
// Transform the game data similar to PlayniteImportService
return [
'title' => $game['Name'] ?? $game['name'] ?? '',
'game_key' => $this->generateGameKey($game['Name'] ?? $game['name'] ?? ''),
'description' => $this->cleanHtml($game['Description'] ?? $game['description'] ?? ''),
'platform_game_id' => $game['GameId'] ?? $game['game_id'] ?? '',
'platform' => $this->extractPlatformFromPlaynite($game),
'source_id' => $source['id'],
// Rich media
'background_image' => $game['BackgroundImage'] ?? $game['background'] ?? null,
'cover_image' => $game['CoverImage'] ?? $game['cover'] ?? null,
'icon' => $game['Icon'] ?? $game['icon'] ?? null,
// Play statistics
'playtime_minutes' => $this->parsePlaytime($game['Playtime'] ?? $game['playtime'] ?? 0),
'play_count' => $game['PlayCount'] ?? $game['play_count'] ?? 0,
// Enhanced ratings
'rating' => $this->normalizeRating($game['CriticScore'] ?? $game['critic_score'] ?? null),
'critic_score' => $game['CriticScore'] ?? $game['critic_score'] ?? null,
'community_score' => $game['CommunityScore'] ?? $game['community_score'] ?? null,
'user_score' => $game['UserScore'] ?? $game['user_score'] ?? null,
// Timestamps
'added_at' => isset($game['Added']) ? date('Y-m-d H:i:s', strtotime($game['Added'])) : null,
'modified_at' => isset($game['Modified']) ? date('Y-m-d H:i:s', strtotime($game['Modified'])) : null,
'last_played_at' => isset($game['LastActivity']) ? date('Y-m-d H:i:s', strtotime($game['LastActivity'])) : null,
// Playnite metadata
'metadata' => json_encode([
'playnite_id' => $game['Id'] ?? $game['playnite_id'] ?? null,
'version' => $game['Version'] ?? $game['version'] ?? null,
'hidden' => $this->toBoolean($game['Hidden'] ?? $game['hidden'] ?? false),
'notes' => $game['Notes'] ?? $game['notes'] ?? null,
'manual' => $game['Manual'] ?? $game['manual'] ?? null,
'pre_script' => $game['PreScript'] ?? $game['pre_script'] ?? null,
'post_script' => $game['PostScript'] ?? $game['post_script'] ?? null,
'game_started_script' => $game['GameStartedScript'] ?? $game['game_started_script'] ?? null,
'use_global_scripts' => [
'pre' => $this->toBoolean($game['UseGlobalPreScript'] ?? $game['use_global_pre_script'] ?? true),
'post' => $this->toBoolean($game['UseGlobalPostScript'] ?? $game['use_global_post_script'] ?? true),
'game_started' => $this->toBoolean($game['UseGlobalGameStartedScript'] ?? $game['use_global_game_started_script'] ?? true)
]
])
];
}
/**
* Find or create a source for the game
*/
private function findOrCreateSource(array $game): array
{
$sourceName = $game['Source']['Name'] ?? $game['source'] ?? 'Playnite';
$sourceId = $game['Source']['Id'] ?? $game['source_id'] ?? null;
// Try to find existing source
$stmt = $this->pdo->prepare("SELECT id, display_name FROM sources WHERE display_name = :name OR id = :source_id");
$stmt->execute([
'name' => $sourceName,
'source_id' => $sourceId
]);
$source = $stmt->fetch(\PDO::FETCH_ASSOC);
if (!$source) {
// Create new source
$stmt = $this->pdo->prepare("INSERT INTO sources (display_name, created_at, updated_at) VALUES (:name, NOW(), NOW())");
$stmt->execute(['name' => $sourceName]);
$source = ['id' => $this->pdo->lastInsertId(), 'display_name' => $sourceName];
}
return $source;
}
/**
* Generate a consistent game key for grouping
*/
private function generateGameKey(string $title): string
{
return \App\Models\Game::generateGameKey($title);
}
/**
* Extract platform from Playnite data
*/
private function extractPlatformFromPlaynite(array $game): string
{
if (isset($game['Platforms']) && is_array($game['Platforms'])) {
$platformNames = array_map(function($platform) {
return $platform['Name'] ?? 'Unknown';
}, $game['Platforms']);
return implode(', ', $platformNames);
}
if (isset($game['Platform']) && is_array($game['Platform'])) {
return $game['Platform']['Name'] ?? 'PC';
}
return $game['platform'] ?? 'PC';
}
/**
* Parse playtime from Playnite format (usually in seconds)
*/
private function parsePlaytime($playtime): int
{
if (is_numeric($playtime)) {
return (int)($playtime / 60); // Convert seconds to minutes
}
return 0;
}
/**
* Normalize rating to 0-10 scale
*/
private function normalizeRating($rating): ?float
{
if (is_numeric($rating)) {
$rating = (float)$rating;
// If rating is 0-100 scale, convert to 0-10
if ($rating > 10) {
return $rating / 10;
}
return $rating;
}
return null;
}
/**
* Clean HTML from description
*/
private function cleanHtml(?string $html): ?string
{
if (!$html) {
return null;
}
// Remove HTML tags but keep basic formatting
$text = strip_tags($html);
// Decode HTML entities
$text = html_entity_decode($text, ENT_QUOTES, 'UTF-8');
// Clean up extra whitespace
$text = preg_replace('/\s+/', ' ', $text);
return trim($text);
}
/**
* Convert a value to boolean
*/
private function toBoolean($value): bool
{
if ($value === null || $value === false || $value === 0 || $value === '0') {
return false;
}
if ($value === true || $value === 1 || $value === '1') {
return true;
}
if (is_string($value)) {
return !empty(trim($value));
}
return (bool) $value;
}
}

View File

@@ -0,0 +1,41 @@
<?php
/**
* @OA\OpenApi(
* @OA\Info(
* title="Playnite API",
* version="1.0.0",
* description="API for managing games and media from Playnite",
* @OA\Contact(
* email="support@example.com"
* ),
* @OA\License(
* name="Apache 2.0",
* url="http://www.apache.org/licenses/LICENSE-2.0.html"
* )
* ),
* @OA\Server(
* url="/api",
* description="API Server"
* ),
* @OA\Components(
* @OA\Schema(
* schema="Error",
* type="object",
* @OA\Property(property="success", type="boolean", example=false),
* @OA\Property(property="error", type="string", example="Error message")
* ),
* @OA\Schema(
* schema="Success",
* type="object",
* @OA\Property(property="success", type="boolean", example=true),
* @OA\Property(property="result", type="object")
* )
* )
* )
*
* @OA\Tag(
* name="Playnite",
* description="Endpoints for Playnite integration"
* )
*/

View File

@@ -80,7 +80,7 @@ class DashboardController extends Controller
'recent_games' => $recentGames,
'recent_movies' => $recentMovies,
'recent_syncs' => $recentSyncs,
'sync_stats' => $syncStats
//'sync_stats' => $syncStats
]);
}
}

View File

@@ -5,16 +5,164 @@ namespace App\Controllers;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use App\Models\Game;
use App\Services\SteamGridDbService;
use Slim\Views\Twig;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
class GameController extends Controller
{
private \PDO $pdo;
private SteamGridDbService $steamGridDb;
public function __construct(\PDO $pdo, Twig $view)
{
parent::__construct($view);
$this->pdo = $pdo;
$this->steamGridDb = new SteamGridDbService();
}
/**
* Search for games on SteamGridDB
*/
public function searchSteamGridDb(Request $request, Response $response, array $args): Response
{
$query = $request->getQueryParams()['q'] ?? '';
$results = [];
if (!empty($query)) {
$results = $this->steamGridDb->searchGames($query);
}
return $this->json($response, [
'success' => true,
'data' => $results
]);
}
/**
* Get media from SteamGridDB
*/
public function getSteamGridDbMedia(Request $request, Response $response, array $args): Response
{
$gameId = $args['gameId'] ?? null;
$type = $args['type'] ?? 'grids';
$media = [];
if ($gameId) {
switch ($type) {
case 'grids':
$media = $this->steamGridDb->getGrids($gameId, [
'styles' => ['alternate', 'blurred', 'white_logo', 'material', 'no_logo'],
'dimensions' => ['600x900', '920x430', '460x215', '920x430']
]);
break;
case 'heroes':
$media = $this->steamGridDb->getHeroes($gameId, [
'dimensions' => ['1920x620', '3840x1240']
]);
break;
case 'icons':
$media = $this->steamGridDb->getIcons($gameId, [
'dimensions' => ['32x32', '64x64', '128x128', '256x256', '512x512']
]);
break;
case 'logos':
$media = $this->steamGridDb->getLogos($gameId);
break;
}
}
return $this->json($response, [
'success' => true,
'data' => $media
]);
}
/**
* Download and set media from SteamGridDB
*/
public function setSteamGridDbMedia(Request $request, Response $response, array $args): Response
{
$gameId = $args['id'] ?? null;
$data = $request->getParsedBody();
$type = $data['type'] ?? '';
$url = $data['url'] ?? '';
$field = '';
if (!$gameId || !$type || !$url) {
return $this->json($response, [
'success' => false,
'message' => 'Missing required parameters'
], 400);
}
// Map media type to database field
switch ($type) {
case 'grid':
$field = 'image_url';
break;
case 'hero':
$field = 'banner_url';
break;
case 'icon':
$field = 'icon';
break;
case 'logo':
$field = 'logo_url';
break;
default:
return $this->json($response, [
'success' => false,
'message' => 'Invalid media type'
], 400);
}
// Download the media file
$tempFile = $this->steamGridDb->downloadMedia($url);
if (!$tempFile) {
return $this->json($response, [
'success' => false,
'message' => 'Failed to download media'
], 500);
}
// Move the file to the appropriate location
$uploadDir = __DIR__ . '/../../public/uploads/games/' . $gameId;
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
$filename = $type . '_' . uniqid() . '.' . pathinfo($url, PATHINFO_EXTENSION);
$filepath = $uploadDir . '/' . $filename;
$publicPath = '/uploads/games/' . $gameId . '/' . $filename;
if (!rename($tempFile, $filepath)) {
return $this->json($response, [
'success' => false,
'message' => 'Failed to save media file'
], 500);
}
// Update the game record
$game = Game::find($this->pdo, $gameId);
if (!$game) {
return $this->json($response, [
'success' => false,
'message' => 'Game not found'
], 404);
}
$game->{$field} = $publicPath;
$game->save($this->pdo);
return $this->json($response, [
'success' => true,
'data' => [
'url' => $publicPath,
'field' => $field
]
]);
}
public function index(Request $request, Response $response, $args)
@@ -44,8 +192,11 @@ class GameController extends Controller
// Get view mode
$viewMode = $queryParams['view'] ?? 'grid'; // grid, list, covers
// Get games with pagination and filters
$games = Game::getGroupedGamesWithPagination($this->pdo, $page, $perPage, $search, $genres, $platforms);
// Get sort parameter
$sort = $queryParams['sort'] ?? 'title_asc';
// Get games with pagination, filters, and sorting
$games = Game::getGroupedGamesWithPagination($this->pdo, $page, $perPage, $search, $genres, $platforms, $sort);
// Get total count for pagination
$totalCount = Game::getTotalCount($this->pdo, $search, $genres, $platforms);
@@ -82,6 +233,17 @@ class GameController extends Controller
'available_filters' => [
'genres' => $availableGenres,
'platforms' => $availablePlatforms
],
'sort' => $sort,
'sort_options' => [
'title_asc' => 'Title (A-Z)',
'title_desc' => 'Title (Z-A)',
'year_asc' => 'Release Year (Oldest First)',
'year_desc' => 'Release Year (Newest First)',
'playtime_desc' => 'Most Played',
'completion_desc' => 'Highest Completion',
'added_desc' => 'Recently Added',
'last_played_desc' => 'Last Played'
]
]);
}
@@ -92,9 +254,9 @@ class GameController extends Controller
// Find the main game entry (could be any platform version)
$stmt = $this->pdo->prepare("
SELECT g.*, s.display_name as source_name
SELECT g.*, g.platform as source_name
FROM games g
JOIN sources s ON g.source_id = s.id
WHERE g.game_key = :game_key
LIMIT 1
");

View File

@@ -44,8 +44,11 @@ class MovieController extends Controller
// Get view mode
$viewMode = $queryParams['view'] ?? 'grid'; // grid, list, covers
// Get movies with pagination and filters
$movies = Movie::getAllWithPagination($this->pdo, $page, $perPage, $search, $genres, $directors);
// Get sort parameter
$sort = $queryParams['sort'] ?? 'title_asc';
// Get movies with pagination, filters, and sorting
$movies = Movie::getAllWithPagination($this->pdo, $page, $perPage, $search, $genres, $directors, $sort);
// Get total count for pagination
$totalCount = Movie::getTotalCount($this->pdo, $search, $genres, $directors);
@@ -82,6 +85,18 @@ class MovieController extends Controller
'available_filters' => [
'genres' => $availableGenres,
'directors' => $availableDirectors
],
'sort' => $sort,
'sort_options' => [
'title_asc' => 'Title (A-Z)',
'title_desc' => 'Title (Z-A)',
'year_asc' => 'Release Year (Oldest First)',
'year_desc' => 'Release Year (Newest First)',
'rating_desc' => 'Highest Rated',
'views_desc' => 'Most Viewed',
'added_desc' => 'Recently Added',
'added_asc' => 'Oldest Added',
'last_watched_desc' => 'Last Watched'
]
]);
}

View File

@@ -33,30 +33,25 @@ class SearchController extends Controller
$results = [];
// Search movies (including adult videos)
$movieStmt = $this->pdo->prepare("
$searchTerm = $this->pdo->quote("%$search%");
$movieStmt = $this->pdo->query("
SELECT m.*, s.display_name as source_name, 'movie' as type
FROM movies m
JOIN sources s ON m.source_id = s.id
WHERE (m.title LIKE :search OR m.overview LIKE :search)
WHERE (m.title LIKE $searchTerm OR m.overview LIKE $searchTerm)
ORDER BY m.title
LIMIT 20
");
$searchParam = "%{$search}%";
$movieStmt->bindParam(':search', $searchParam, \PDO::PARAM_STR);
$movieStmt->execute();
$results['movies'] = $movieStmt->fetchAll(\PDO::FETCH_ASSOC);
// Search games
$gameStmt = $this->pdo->prepare("
SELECT g.*, s.display_name as source_name, 'game' as type
$gameStmt = $this->pdo->query("
SELECT g.*, 'game' as type
FROM games g
JOIN sources s ON g.source_id = s.id
WHERE (g.name LIKE :search OR g.description LIKE :search)
ORDER BY g.name
WHERE (g.title LIKE $searchTerm OR g.description LIKE $searchTerm)
ORDER BY g.title
LIMIT 20
");
$gameStmt->bindParam(':search', $searchParam, \PDO::PARAM_STR);
$gameStmt->execute();
$results['games'] = $gameStmt->fetchAll(\PDO::FETCH_ASSOC);
return $this->view->render($response, 'search/index.twig', [

View File

@@ -25,7 +25,7 @@ class AdultVideo extends Model
'external_id'
];
public static function getAllWithPagination(\PDO $pdo, int $page, int $perPage, string $search = '', array $genres = [], array $directors = []): array
public static function getAllWithPagination(\PDO $pdo, int $page, int $perPage, string $search = '', array $genres = [], array $directors = [], string $sort = 'recent'): array
{
$offset = ($page - 1) * $perPage;
@@ -61,7 +61,24 @@ class AdultVideo extends Model
$sql .= $whereClause . " av.director IN (" . implode(',', $placeholders) . ")";
}
$sql .= " ORDER BY av.created_at DESC LIMIT :limit OFFSET :offset";
// Add sorting
$sortOptions = [
'recent' => 'av.created_at DESC',
'oldest' => 'av.created_at ASC',
'title_asc' => 'av.title ASC',
'title_desc' => 'av.title DESC',
'year_asc' => 'av.release_date ASC',
'year_desc' => 'av.release_date DESC',
'rating_asc' => 'av.rating ASC',
'rating_desc' => 'av.rating DESC',
'views_asc' => 'av.watch_count ASC',
'views_desc' => 'av.watch_count DESC',
'runtime_asc' => 'av.runtime_minutes ASC',
'runtime_desc' => 'av.runtime_minutes DESC',
];
$sortOrder = $sortOptions[$sort] ?? $sortOptions['recent'];
$sql .= " ORDER BY " . $sortOrder . " LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':limit', $perPage, \PDO::PARAM_INT);
@@ -143,7 +160,7 @@ class AdultVideo extends Model
/**
* Get all actors associated with this adult video
*/
public function actors()
public function actors($args)
{
$stmt = $this->pdo->prepare("
SELECT a.*
@@ -152,7 +169,7 @@ class AdultVideo extends Model
WHERE aav.adult_video_id = :adult_video_id
ORDER BY a.name ASC
");
$stmt->execute(['adult_video_id' => $this->id]);
$stmt->execute(['adult_video_id' => $args]);
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
@@ -200,21 +217,6 @@ class AdultVideo extends Model
]);
}
/**
* Get TV show statistics
*/
public static function getStats(\PDO $pdo): array
{
$stmt = $pdo->query("
SELECT
COUNT(*) as total_adult_videos,
COUNT(CASE WHEN is_favorite = 1 THEN 1 END) as favorite_adult_videos,
AVG(rating) as avg_rating
FROM adult_videos
");
return $stmt->fetch(\PDO::FETCH_ASSOC);
}
/**
* Get available genres for filtering
*/
@@ -242,4 +244,36 @@ class AdultVideo extends Model
");
return $stmt->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* Get TV show statistics
*/
public static function getStats(\PDO $pdo): array
{
$stmt = $pdo->query("
SELECT
COUNT(*) as total_adult_videos,
COUNT(CASE WHEN is_favorite = 1 THEN 1 END) as favorite_adult_videos,
AVG(rating) as avg_rating
FROM adult_videos
");
return $stmt->fetch(\PDO::FETCH_ASSOC);
}
/**
* Search actors by name
*/
public static function searchActors(\PDO $pdo, string $query): array
{
$stmt = $pdo->prepare("
SELECT a.*
FROM actors a
WHERE a.name LIKE :query
ORDER BY a.name
LIMIT 10
");
$stmt->execute(['query' => "%{$query}%"]);
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
}

View File

@@ -177,9 +177,9 @@ class Game extends Model
}
$stmt = $this->pdo->prepare("
SELECT g.*, s.display_name as source_name
SELECT g.*, g.platform as source_name
FROM games g
JOIN sources s ON g.source_id = s.id
WHERE g.game_key = :game_key
ORDER BY g.platform, g.source_id
");
@@ -215,9 +215,9 @@ class Game extends Model
// Enhance each game with platform details
foreach ($games as &$game) {
$game['platforms'] = array_unique(explode(',', $game['platforms']));
$game['source_ids'] = array_unique(explode(',', $game['source_ids']));
$game['genres'] = array_unique(array_filter(explode(',', $game['genres'])));
$game['platforms'] = !empty($game['platforms']) ? array_unique(explode(',', $game['platforms'])) : [];
$game['source_ids'] = !empty($game['source_ids']) ? array_unique(explode(',', $game['source_ids'])) : [];
$game['genres'] = !empty($game['genres']) ? array_unique(array_filter(explode(',', $game['genres']))) : [];
}
return $games;
@@ -298,7 +298,7 @@ class Game extends Model
/**
* Get grouped games with pagination and search support
*/
public static function getGroupedGamesWithPagination(\PDO $pdo, int $page, int $perPage, string $search = '', array $genres = [], array $platforms = []): array
public static function getGroupedGamesWithPagination(\PDO $pdo, int $page, int $perPage, string $search = '', array $genres = [], array $platforms = [], string $sort = 'title_asc'): array
{
$offset = ($page - 1) * $perPage;
@@ -313,7 +313,9 @@ class Game extends Model
MAX(last_played_at) as last_played_at,
SUM(playtime_minutes) as total_playtime,
MAX(completion_percentage) as max_completion,
GROUP_CONCAT(DISTINCT genre ORDER BY genre) as genres
GROUP_CONCAT(DISTINCT genre ORDER BY genre) as genres,
MAX(release_date) as release_date,
MAX(added_at) as added_at
FROM games
WHERE game_key IS NOT NULL
";
@@ -343,7 +345,24 @@ class Game extends Model
$sql .= " AND platform IN (" . implode(',', $placeholders) . ")";
}
$sql .= " GROUP BY game_key, title ORDER BY last_played_at DESC, total_playtime DESC LIMIT :limit OFFSET :offset";
// Add sorting
$sortOptions = [
'title_asc' => 'title ASC',
'title_desc' => 'title DESC',
'year_asc' => 'release_date ASC NULLS LAST',
'year_desc' => 'release_date DESC NULLS LAST',
'playtime_asc' => 'total_playtime ASC',
'playtime_desc' => 'total_playtime DESC',
'completion_asc' => 'max_completion ASC NULLS LAST',
'completion_desc' => 'max_completion DESC NULLS LAST',
'added_asc' => 'added_at ASC NULLS LAST',
'added_desc' => 'added_at DESC NULLS LAST',
'last_played_asc' => 'last_played_at ASC NULLS LAST',
'last_played_desc' => 'last_played_at DESC NULLS LAST'
];
$sortClause = $sortOptions[$sort] ?? 'title ASC';
$sql .= " GROUP BY game_key, title ORDER BY $sortClause LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':limit', $perPage, \PDO::PARAM_INT);
@@ -358,20 +377,52 @@ class Game extends Model
// Enhance each game with platform details
foreach ($games as &$game) {
$game['platforms'] = array_unique(explode(',', $game['platforms']));
$game['source_ids'] = array_unique(explode(',', $game['source_ids']));
$game['genres'] = array_unique(array_filter(explode(',', $game['genres'])));
$game['platforms'] = !empty($game['platforms']) ? array_unique(explode(',', $game['platforms'])) : [];
$game['source_ids'] = !empty($game['source_ids']) ? array_unique(explode(',', $game['source_ids'])) : [];
$game['genres'] = !empty($game['genres']) ? array_unique(array_filter(explode(',', $game['genres']))) : [];
}
return $games;
}
/**
* Get Playnite-specific genres
* Get all unique genres from the games table
* Combines both Playnite JSON genres and regular genre field
*/
public function getGenres(): array
{
return $this->genres_json ?? [];
// First get genres from the regular genre field
$stmt = $this->pdo->query("SELECT DISTINCT genre FROM {$this->table} WHERE genre IS NOT NULL AND genre != ''");
$genres = [];
$results = $stmt->fetchAll(\PDO::FETCH_COLUMN);
// Flatten and deduplicate genres
foreach ($results as $genreList) {
$genreArray = array_map('trim', explode(',', $genreList));
$genres = array_merge($genres, $genreArray);
}
// Also get genres from Playnite JSON data
$stmt = $this->pdo->query("SELECT genres_json FROM {$this->table} WHERE genres_json IS NOT NULL AND genres_json != '[]'");
$jsonGenres = $stmt->fetchAll(\PDO::FETCH_COLUMN);
foreach ($jsonGenres as $json) {
$decoded = json_decode($json, true);
if (is_array($decoded)) {
foreach ($decoded as $genre) {
if (is_array($genre) && isset($genre['Name'])) {
$genres[] = $genre['Name'];
} elseif (is_string($genre)) {
$genres[] = $genre;
}
}
}
}
$genres = array_unique($genres);
sort($genres);
return array_values(array_filter($genres));
}
/**
@@ -398,6 +449,16 @@ class Game extends Model
return $this->tags_json ?? [];
}
/**
* Get all unique platforms from the games table
*/
public function getPlatforms(): array
{
$stmt = $this->pdo->query("SELECT DISTINCT platform FROM {$this->table} WHERE platform IS NOT NULL AND platform != '' ORDER BY platform");
return $stmt->fetchAll(\PDO::FETCH_COLUMN);
}
/**
* Get Playnite-specific features
*/

View File

@@ -46,6 +46,150 @@ class Movie extends Model
return $sourceData ? new Source($this->pdo, $sourceData) : null;
}
/**
* Get total count of movies with optional filters
*/
public static function getTotalCount(\PDO $pdo, string $search = '', array $genres = [], array $directors = []): int
{
$where = [];
$params = [];
$sql = "SELECT COUNT(*) as count FROM movies m JOIN sources s ON m.source_id = s.id";
if (!empty($search)) {
$where[] = "(m.title LIKE :search OR m.overview LIKE :search)";
$params[':search'] = "%$search%";
}
if (!empty($genres)) {
$genreConditions = [];
foreach ($genres as $i => $genre) {
$param = ":genre_$i";
$genreConditions[] = "m.genre LIKE $param";
$params[$param] = "%$genre%";
}
$where[] = "(" . implode(' OR ', $genreConditions) . ")";
}
if (!empty($directors)) {
$directorConditions = [];
foreach ($directors as $i => $director) {
$param = ":director_$i";
$directorConditions[] = "m.director LIKE $param";
$params[$param] = "%$director%";
}
$where[] = "(" . implode(' OR ', $directorConditions) . ")";
}
if (!empty($where)) {
$sql .= " WHERE " . implode(' AND ', $where);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
return (int)$stmt->fetchColumn();
}
/**
* Get paginated movies with optional filters
*/
public function getPaginated(
\PDO $pdo,
int $page = 1,
int $perPage = 20,
string $search = '',
array $genres = [],
string $sort = 'title_asc'
): array {
$offset = ($page - 1) * $perPage;
$where = [];
$params = [];
if (!empty($search)) {
$where[] = "(title LIKE :search OR overview LIKE :search OR director LIKE :search OR writer LIKE :search)";
$params[':search'] = "%$search%";
}
if (!empty($genres)) {
$genreConditions = [];
foreach ($genres as $i => $genre) {
$param = ":genre$i";
$genreConditions[] = "genre LIKE $param";
$params[$param] = "%$genre%";
}
$where[] = "(" . implode(' OR ', $genreConditions) . ")";
}
// Determine sort order
$orderBy = 'title ASC';
switch ($sort) {
case 'title_desc':
$orderBy = 'title DESC';
break;
case 'release_asc':
$orderBy = 'release_date ASC';
break;
case 'release_desc':
$orderBy = 'release_date DESC';
break;
case 'rating_desc':
$orderBy = 'rating DESC';
break;
case 'rating_asc':
$orderBy = 'rating ASC';
break;
}
$sql = "SELECT * FROM {$this->table}";
if (!empty($where)) {
$sql .= " WHERE " . implode(' AND ', $where);
}
$sql .= " ORDER BY $orderBy LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($sql);
// Bind parameters
foreach ($params as $key => $value) {
$stmt->bindValue($key, $value);
}
$stmt->bindValue(':limit', $perPage, \PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, \PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
/**
* Get all unique genres from movies
*/
public function getGenres(\PDO $pdo): array
{
$stmt = $pdo->query("SELECT DISTINCT genre FROM {$this->table} WHERE genre IS NOT NULL AND genre != ''");
$results = $stmt->fetchAll(\PDO::FETCH_COLUMN);
$genres = [];
foreach ($results as $genreList) {
$genreArray = array_map('trim', explode(',', $genreList));
$genres = array_merge($genres, $genreArray);
}
$genres = array_unique($genres);
sort($genres);
return array_values(array_filter($genres));
}
/**
* Get all unique directors from movies
*/
public function getDirectors(\PDO $pdo): array
{
$stmt = $pdo->query("SELECT DISTINCT director FROM {$this->table} WHERE director IS NOT NULL AND director != '' ORDER BY director");
return $stmt->fetchAll(\PDO::FETCH_COLUMN);
}
public function markAsWatched(): bool
{
$this->watched = true;
@@ -108,7 +252,7 @@ class Movie extends Model
$stmt->execute(['limit' => $limit]);
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
/*
public static function getTotalCount(\PDO $pdo, string $search = '', array $genres = [], array $directors = []): int
{
$sql = "SELECT COUNT(*) as count FROM movies m JOIN sources s ON m.source_id = s.id";
@@ -146,8 +290,8 @@ class Movie extends Model
$stmt->execute();
return (int) $stmt->fetch()['count'];
}
public static function getAllWithPagination(\PDO $pdo, int $page, int $perPage, string $search = '', array $genres = [], array $directors = []): array
*/
public static function getAllWithPagination(\PDO $pdo, int $page, int $perPage, string $search = '', array $genres = [], array $directors = [], string $sort = 'title_asc'): array
{
$offset = ($page - 1) * $perPage;
@@ -170,20 +314,47 @@ class Movie extends Model
$params["genre_{$index}"] = $genre;
}
$whereClause = !empty($search) ? " AND" : " WHERE";
$sql .= $whereClause . " m.genre IN (" . implode(',', $placeholders) . ")";
$sql .= $whereClause . " (";
foreach ($placeholders as $i => $placeholder) {
if ($i > 0) $sql .= " OR ";
$sql .= "m.genre LIKE $placeholder";
}
$sql .= ")";
}
if (!empty($directors)) {
$placeholders = [];
foreach ($directors as $index => $director) {
$placeholders[] = ":director_{$index}";
$params["director_{$index}"] = $director;
$params["director_{$index}"] = "%$director%";
}
$whereClause = (!empty($search) || !empty($genres)) ? " AND" : " WHERE";
$sql .= $whereClause . " m.director IN (" . implode(',', $placeholders) . ")";
$sql .= $whereClause . " (";
foreach ($placeholders as $i => $placeholder) {
if ($i > 0) $sql .= " OR ";
$sql .= "m.director LIKE $placeholder";
}
$sql .= ")";
}
$sql .= " ORDER BY m.title ASC LIMIT :limit OFFSET :offset";
// Add sorting
$sortOptions = [
'title_asc' => 'm.title ASC',
'title_desc' => 'm.title DESC',
'year_asc' => 'm.release_date ASC',
'year_desc' => 'm.release_date DESC',
'rating_asc' => 'm.rating ASC NULLS LAST',
'rating_desc' => 'm.rating DESC NULLS LAST',
'views_asc' => 'm.watch_count ASC',
'views_desc' => 'm.watch_count DESC',
'added_asc' => 'm.created_at ASC',
'added_desc' => 'm.created_at DESC',
'last_watched_asc' => 'm.last_watched_at ASC NULLS LAST',
'last_watched_desc' => 'm.last_watched_at DESC NULLS LAST'
];
$sortClause = $sortOptions[$sort] ?? 'm.title ASC';
$sql .= " ORDER BY $sortClause LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':limit', $perPage, \PDO::PARAM_INT);

View File

@@ -51,20 +51,6 @@ class TvShow extends Model
]);
}
/**
* Update the cast field with actor names
*/
public function updateCastField(): bool
{
$actors = $this->actors();
$actorNames = array_column($actors, 'name');
$castString = implode(', ', $actorNames);
return $this->update($this->id, [
'cast' => $castString
]);
}
/**
* Get TV show statistics
*/
@@ -81,44 +67,64 @@ class TvShow extends Model
}
/**
* Get total count with optional search
* Get total count with optional search and filters
*/
public static function getTotalCount(\PDO $pdo, string $search = '', array $genres = [], array $years = []): int
{
public static function getTotalCount(
\PDO $pdo,
string $search = '',
array $genres = [],
array $networks = [],
array $statuses = []
): int {
$sql = "SELECT COUNT(*) as count FROM tv_shows t JOIN sources s ON t.source_id = s.id";
$params = [];
$whereClauses = [];
if (!empty($search)) {
$sql .= " WHERE t.title LIKE :search";
$whereClauses[] = "(t.title LIKE :search OR t.overview LIKE :search)";
$params['search'] = "%{$search}%";
}
if (!empty($genres)) {
$placeholders = [];
foreach ($genres as $index => $genre) {
$placeholders[] = ":genre_{$index}";
$params["genre_{$index}"] = $genre;
$genreConditions = [];
foreach ($genres as $i => $genre) {
$param = ":genre_{$i}";
$genreConditions[] = "FIND_IN_SET({$param}, t.genre) > 0";
$params["genre_{$i}"] = $genre;
}
$whereClause = !empty($search) ? " AND" : " WHERE";
$sql .= $whereClause . " t.genre IN (" . implode(',', $placeholders) . ")";
$whereClauses[] = '(' . implode(' OR ', $genreConditions) . ')';
}
if (!empty($years)) {
$placeholders = [];
foreach ($years as $index => $year) {
$placeholders[] = ":year_{$index}";
$params["year_{$index}"] = $year;
if (!empty($networks)) {
$networkConditions = [];
foreach ($networks as $i => $network) {
$param = ":network_{$i}";
$networkConditions[] = "t.networks LIKE {$param}";
$params["network_{$i}"] = "%\"name\":\"{$network}\"%";
}
$whereClause = (!empty($search) || !empty($genres)) ? " AND" : " WHERE";
$sql .= $whereClause . " YEAR(first_air_date) IN (" . implode(',', $placeholders) . ")";
$whereClauses[] = '(' . implode(' OR ', $networkConditions) . ')';
}
if (!empty($statuses)) {
$statusConditions = [];
foreach ($statuses as $i => $status) {
$param = ":status_{$i}";
$statusConditions[] = "t.status = {$param}";
$params["status_{$i}"] = $status;
}
$whereClauses[] = '(' . implode(' OR ', $statusConditions) . ')';
}
if (!empty($whereClauses)) {
$sql .= ' WHERE ' . implode(' AND ', $whereClauses);
}
$stmt = $pdo->prepare($sql);
foreach ($params as $key => $value) {
$stmt->bindValue(":{$key}", $value);
$stmt->bindValue($key, $value);
}
$stmt->execute();
return (int) $stmt->fetch()['count'];
return (int) $stmt->fetch(\PDO::FETCH_COLUMN);
}
/**
@@ -206,6 +212,135 @@ class TvShow extends Model
return $sourceData ? new Source($this->pdo, $sourceData) : null;
}
/**
* Get paginated TV shows with filters
*/
public static function getPaginated(
\PDO $pdo,
int $page,
int $perPage,
string $search = '',
array $genres = [],
array $networks = [],
array $statuses = [],
string $sort = 'title_asc'
): array {
$offset = ($page - 1) * $perPage;
$sql = "
SELECT t.*, s.display_name as source_name
FROM tv_shows t
JOIN sources s ON t.source_id = s.id
";
$params = [];
$whereClauses = [];
if (!empty($search)) {
$whereClauses[] = "(t.title LIKE :search OR t.overview LIKE :search)";
$params['search'] = "%{$search}%";
}
if (!empty($genres)) {
$genreConditions = [];
foreach ($genres as $i => $genre) {
$param = ":genre_{$i}";
$genreConditions[] = "FIND_IN_SET({$param}, t.genre) > 0";
$params["genre_{$i}"] = $genre;
}
$whereClauses[] = '(' . implode(' OR ', $genreConditions) . ')';
}
if (!empty($networks)) {
$networkConditions = [];
foreach ($networks as $i => $network) {
$param = ":network_{$i}";
$networkConditions[] = "t.networks LIKE {$param}";
$params["network_{$i}"] = "%\"name\":\"{$network}\"%";
}
$whereClauses[] = '(' . implode(' OR ', $networkConditions) . ')';
}
if (!empty($statuses)) {
$statusConditions = [];
foreach ($statuses as $i => $status) {
$param = ":status_{$i}";
$statusConditions[] = "t.status = {$param}";
$params["status_{$i}"] = $status;
}
$whereClauses[] = '(' . implode(' OR ', $statusConditions) . ')';
}
if (!empty($whereClauses)) {
$sql .= ' WHERE ' . implode(' AND ', $whereClauses);
}
// Add sorting
$sortMap = [
'title_asc' => 't.title ASC',
'title_desc' => 't.title DESC',
'rating_desc' => 't.vote_average DESC NULLS LAST',
'rating_asc' => 't.vote_average ASC NULLS LAST',
'newest' => 't.first_air_date DESC NULLS LAST',
'oldest' => 't.first_air_date ASC NULLS LAST',
];
$sortClause = $sortMap[$sort] ?? 't.title ASC';
$sql .= " ORDER BY {$sortClause} LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':limit', $perPage, \PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, \PDO::PARAM_INT);
foreach ($params as $key => $value) {
$stmt->bindValue($key, $value);
}
$stmt->execute();
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
/**
* Get all available genres from TV shows
*/
public static function getGenres(\PDO $pdo): array
{
$stmt = $pdo->query("
SELECT DISTINCT TRIM(SUBSTRING_INDEX(SUBSTRING_INDEX(t.genre, ',', n.n), ',', -1)) as genre
FROM tv_shows t
JOIN (
SELECT 1 as n UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL
SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6
) n
WHERE n.n <= LENGTH(t.genre) - LENGTH(REPLACE(t.genre, ',', '')) + 1
AND t.genre IS NOT NULL AND t.genre != ''
ORDER BY genre
");
$genres = $stmt->fetchAll(\PDO::FETCH_COLUMN);
return array_values(array_filter(array_unique($genres)));
}
/**
* Get all available networks from TV shows
*/
public static function getNetworks(\PDO $pdo): array
{
$stmt = $pdo->query("SELECT DISTINCT networks FROM tv_shows WHERE networks IS NOT NULL AND networks != ''");
$networks = [];
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$showNetworks = json_decode($row['networks'], true) ?: [];
foreach ($showNetworks as $network) {
if (isset($network['name'])) {
$networks[$network['name']] = $network['name'];
}
}
}
sort($networks);
return array_values($networks);
}
public function getSeasonsWithEpisodes(): array
{
// Get all episodes for this TV show, grouped by season

View File

@@ -0,0 +1,132 @@
<?php
namespace App\Services;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
class SteamGridDbService
{
private const BASE_URI = 'https://www.steamgriddb.com/api/v2/';
private Client $client;
private ?string $apiKey;
public function __construct(?string $apiKey = null)
{
$this->apiKey = $apiKey ?? $_ENV['STEAMGRIDDB_API_KEY'] ?? null;
$this->client = new Client([
'base_uri' => self::BASE_URI,
'headers' => [
'Authorization' => 'Bearer ' . $this->apiKey,
'Accept' => 'application/json',
],
'http_errors' => false,
]);
}
/**
* Search for games by name
*/
public function searchGames(string $query): array
{
try {
$response = $this->client->get('search/autocomplete/' . urlencode($query));
$data = json_decode($response->getBody()->getContents(), true);
return $data['data'] ?? [];
} catch (GuzzleException $e) {
return [];
}
}
/**
* Get game by ID
*/
public function getGame(int $gameId): ?array
{
try {
$response = $this->client->get('games/id/' . $gameId);
$data = json_decode($response->getBody()->getContents(), true);
return $data['data'] ?? null;
} catch (GuzzleException $e) {
return null;
}
}
/**
* Get game grids (covers)
*/
public function getGrids(int $gameId, array $options = []): array
{
return $this->getMedia('grids/game/' . $gameId, $options);
}
/**
* Get game heroes (backgrounds)
*/
public function getHeroes(int $gameId, array $options = []): array
{
return $this->getMedia('heroes/game/' . $gameId, $options);
}
/**
* Get game icons
*/
public function getIcons(int $gameId, array $options = []): array
{
return $this->getMedia('icons/game/' . $gameId, $options);
}
/**
* Get game logos
*/
public function getLogos(int $gameId, array $options = []): array
{
return $this->getMedia('logos/game/' . $gameId, $options);
}
/**
* Download a media file
*/
public function downloadMedia(string $url): ?string
{
try {
$response = $this->client->get($url, ['stream' => true]);
if ($response->getStatusCode() !== 200) {
return null;
}
$tempFile = tempnam(sys_get_temp_dir(), 'sgdb_');
file_put_contents($tempFile, $response->getBody());
return $tempFile;
} catch (GuzzleException $e) {
return null;
}
}
private function getMedia(string $endpoint, array $options = []): array
{
$query = [];
if (!empty($options['styles'])) {
$query['styles'] = is_array($options['styles']) ? implode(',', $options['styles']) : $options['styles'];
}
if (!empty($options['dimensions'])) {
$query['dimensions'] = is_array($options['dimensions']) ? implode(',', $options['dimensions']) : $options['dimensions'];
}
if (!empty($options['mimes'])) {
$query['mimes'] = is_array($options['mimes']) ? implode(',', $options['mimes']) : $options['mimes'];
}
if (!empty($options['types'])) {
$query['types'] = is_array($options['types']) ? implode(',', $options['types']) : $options['types'];
}
try {
$response = $this->client->get($endpoint, ['query' => $query]);
$data = json_decode($response->getBody()->getContents(), true);
return $data['data'] ?? [];
} catch (GuzzleException $e) {
return [];
}
}
}

View File

@@ -10,7 +10,9 @@
"slim/psr7": "^1.6",
"slim/twig-view": "^3.3",
"php-di/php-di": "^7.0",
"illuminate/database": "^10.0"
"illuminate/database": "^10.0",
"zircote/swagger-php": "^5.5",
"php-middleware/php-debug-bar": "^1.0"
},
"autoload": {
"psr-4": {
@@ -23,5 +25,8 @@
"config": {
"optimize-autoloader": true
},
"minimum-stability": "stable"
"minimum-stability": "stable",
"require-dev": {
"maximebf/debugbar": "^1.23"
}
}

View File

@@ -1,12 +1,12 @@
<?php
return [
'driver' => env('DB_CONNECTION', 'sqlite'),
'host' => env('DB_HOST', '127.0.0.1'),
'driver' => env('DB_CONNECTION', 'mysql'),
'host' => env('DB_HOST', '192.168.1.102'),
'port' => env('DB_PORT', 3306),
'database' => env('DB_DATABASE', __DIR__ . '/../database/database.sqlite'),
'username' => env('DB_USERNAME', ''),
'password' => env('DB_PASSWORD', ''),
'database' => env('DB_DATABASE', 'phpmedialib'),
'username' => env('DB_USERNAME', 'phpmedialib'),
'password' => env('DB_PASSWORD', 'phpmedialib'),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'prefix' => env('DB_PREFIX', ''),
'schema' => env('DB_SCHEMA', 'public'),

16
database/Migration.php Normal file
View File

@@ -0,0 +1,16 @@
<?php
namespace App\Database;
abstract class Migration
{
protected \PDO $pdo;
public function __construct(\PDO $pdo)
{
$this->pdo = $pdo;
}
abstract public function up();
abstract public function down();
}

View File

@@ -0,0 +1,30 @@
<?php
namespace App\Database\Migrations;
use App\Database\Migration;
class CreateAdultVideoActorTables extends Migration
{
public function up()
{
// Create adult_video_actor pivot table
$this->pdo->exec("
CREATE TABLE IF NOT EXISTS adult_video_actor (
id INT AUTO_INCREMENT PRIMARY KEY,
adult_video_id INT NOT NULL,
actor_id INT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (adult_video_id) REFERENCES adult_videos(id) ON DELETE CASCADE,
FOREIGN KEY (actor_id) REFERENCES actors(id) ON DELETE CASCADE,
UNIQUE KEY unique_adult_video_actor (adult_video_id, actor_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
");
}
public function down()
{
$this->pdo->exec("DROP TABLE IF EXISTS adult_video_actor");
}
}

118
public/css/app.css Normal file
View File

@@ -0,0 +1,118 @@
.items,
.item {
flex-flow: row wrap;
}
.items .item,
.item .item {
margin: 20px;
width: 120px;
height: 180px;
overflow: hidden;
box-shadow: 0 5px 10px rgba(0,0,0,0.8);
transform-origin: center top;
transform-style: preserve-3d;
transform: translateZ(0);
transition: 0.3s;
}
.items .item img,
.item .item img {
width: 100%;
min-height: 100%;
}
.items .item figcaption,
.item .item figcaption {
bottom: 0;
left: 0;
right: 0;
padding: 20px;
padding-bottom: 10px;
font-size: 20px;
background: none;
color: #fff;
transform: translateY(100%);
transition: 0.3s;
}
.items .item:after,
.item .item:after {
content: '';
z-index: 10;
width: 200%;
height: 100%;
top: -90%;
left: -20px;
opacity: 0.1;
transform: rotate(45deg);
background: linear-gradient(to top, transparent, #fff 15%, rgba(255,255,255,0.5));
transition: 0.3s;
}
.items .item:hover,
.item .item:hover,
.items .item:focus,
.item .item:focus,
.items .item:active,
.item .item:active {
box-shadow: 0 8px 16px 3px rgba(0,0,0,0.6);
transform: translateY(-3px) scale(1.05) rotateX(15deg);
}
.items .item:hover figcaption,
.item .item:hover figcaption,
.items .item:focus figcaption,
.item .item:focus figcaption,
.items .item:active figcaption,
.item .item:active figcaption {
transform: none;
}
.items .item:hover:after,
.item .item:hover:after,
.items .item:focus:after,
.item .item:focus:after,
.items .item:active:after,
.item .item:active:after {
transform: rotate(25deg);
top: -40%;
opacity: 0.15;
}
.item .article {
overflow: hidden;
width: 350px;
height: 235px;
margin: 20px;
}
.item .article img {
width: 100%;
min-height: 100%;
transition: 0.2s;
}
.item .article figcaption {
font-size: 14px;
text-shadow: 0 1px 0 rgba(51,51,51,0.3);
color: #fff;
left: 0;
right: 0;
top: 0;
bottom: 0;
padding: 40px;
box-shadow: 0 0 2px rgba(0,0,0,0.2);
background: rgba(6,18,53,0.6);
opacity: 0;
transform: scale(1.15);
transition: 0.2s;
}
.item .article figcaption h3 {
color: #3792e3;
font-size: 16px;
margin-bottom: 0;
font-weight: bold;
}
.item .article:hover img,
.item .article:focus img,
.item .article:active img {
filter: blur(3px);
transform: scale(0.97);
}
.item .article:hover figcaption,
.item .article:focus figcaption,
.item .article:active figcaption {
opacity: 1;
transform: none;
}

View File

@@ -263,13 +263,13 @@ $container->set(\App\Controllers\SettingsController::class, function ($c) {
return new \App\Controllers\SettingsController($c->get(PDO::class), $c->get('view'));
});
// Register PlayniteImportController
$container->set(\App\Controllers\PlayniteImportController::class, function ($c) {
return new \App\Controllers\PlayniteImportController(
$c->get(PDO::class),
$c->get('view'),
$c->get(\App\Services\AuthService::class)
);
// Register API controllers
$container->set(\App\Controllers\Api\PlayniteController::class, function ($c) {
return new \App\Controllers\Api\PlayniteController($c->get(PDO::class));
});
$container->set(\App\Controllers\Api\AuthController::class, function ($c) {
return new \App\Controllers\Api\AuthController($c->get(\App\Services\AuthService::class));
});
// Register PlayniteImportService
@@ -298,6 +298,69 @@ $app = AppFactory::create();
$twig = $container->get('view');
$app->add(TwigMiddleware::create($app, $twig));
// PHP DebugBar Setup (only in development)
if ($_ENV['APP_DEBUG'] === 'true') {
$debugbar = new \DebugBar\StandardDebugBar();
// Set up the debug bar renderer with the correct base URL
$baseUrl = rtrim($app->getBasePath(), '/');
$debugbarRenderer = $debugbar->getJavascriptRenderer($baseUrl . '/phpdebugbar');
// Add DebugBar to Twig globals
$twig->getEnvironment()->addGlobal('debugbarRenderer', $debugbarRenderer);
// Add route to serve DebugBar assets
$app->get('/phpdebugbar/{path:.*}', function ($request, $response, $args) use ($debugbar) {
$debugbarRenderer = $debugbar->getJavascriptRenderer();
$path = $args['path'];
// Serve CSS files
if (preg_match('/\.css$/', $path)) {
$content = file_get_contents($debugbarRenderer->getBasePath() . '/' . $path);
$response->getBody()->write($content);
return $response->withHeader('Content-Type', 'text/css');
}
// Serve JS files
if (preg_match('/\.js$/', $path)) {
$content = file_get_contents($debugbarRenderer->getBasePath() . '/' . $path);
$response->getBody()->write($content);
return $response->withHeader('Content-Type', 'application/javascript');
}
// Serve other assets (fonts, etc.)
$content = @file_get_contents($debugbarRenderer->getBasePath() . '/' . $path);
if ($content !== false) {
$response->getBody()->write($content);
return $response;
}
return $response->withStatus(404);
});
// Add middleware to collect data
$app->add(function ($request, $handler) use ($debugbar) {
// Start timing the request
$debugbar['time']->startMeasure('app', 'Application');
try {
$response = $handler->handle($request);
// Stop timing if it was started
if ($debugbar['time']->hasStartedMeasure('app')) {
$debugbar['time']->stopMeasure('app');
}
return $response;
} catch (\Exception $e) {
// Make sure to stop timing even if an exception occurs
if ($debugbar['time']->hasStartedMeasure('app')) {
$debugbar['time']->stopMeasure('app');
}
throw $e;
}
});
}
// Add Error Middleware
$errorMiddleware = $app->addErrorMiddleware(
$_ENV['APP_DEBUG'] === 'true',
@@ -307,5 +370,6 @@ $errorMiddleware = $app->addErrorMiddleware(
// Register routes
require __DIR__ . '/../routes/web.php';
require __DIR__ . '/../routes/api.php';
$app->run();

View File

@@ -0,0 +1,125 @@
document.addEventListener('DOMContentLoaded', function() {
const videoId = document.getElementById('video-id').value;
const actorSearch = document.getElementById('actor-search');
const actorResults = document.getElementById('actor-results');
const actorsList = document.getElementById('actors-list');
// Debounce search
let searchTimeout;
actorSearch.addEventListener('input', function(e) {
clearTimeout(searchTimeout);
const query = e.target.value.trim();
if (query.length < 2) {
actorResults.innerHTML = '';
actorResults.classList.add('d-none');
return;
}
searchTimeout = setTimeout(() => {
searchActors(query);
}, 300);
});
// Search for actors
function searchActors(query) {
fetch(`/admin/adult-videos/search-actors?q=${encodeURIComponent(query)}`)
.then(response => response.json())
.then(data => {
actorResults.innerHTML = '';
if (data.data && data.data.length > 0) {
data.data.forEach(actor => {
const item = document.createElement('div');
item.className = 'list-group-item list-group-item-action';
item.textContent = actor.name;
item.addEventListener('click', () => addActorToVideo(actor.id, actor.name));
actorResults.appendChild(item);
});
actorResults.classList.remove('d-none');
} else {
const noResults = document.createElement('div');
noResults.className = 'list-group-item';
noResults.textContent = 'No actors found';
actorResults.appendChild(noResults);
actorResults.classList.remove('d-none');
}
});
}
// Add actor to video
function addActorToVideo(actorId, actorName) {
fetch(`/admin/adult-videos/${videoId}/actors`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
},
body: JSON.stringify({ actor_id: actorId })
})
.then(response => response.json())
.then(data => {
if (data.success) {
addActorToList(actorId, actorName);
actorSearch.value = '';
actorResults.innerHTML = '';
actorResults.classList.add('d-none');
} else {
alert('Failed to add actor: ' + (data.error || 'Unknown error'));
}
});
}
// Add actor to the UI list
function addActorToList(actorId, actorName) {
const item = document.createElement('div');
item.className = 'd-flex justify-content-between align-items-center mb-2';
item.dataset.actorId = actorId;
item.innerHTML = `
<span>${actorName}</span>
<button type="button" class="btn btn-sm btn-danger remove-actor" data-actor-id="${actorId}">
<i class="fas fa-times"></i> Remove
</button>
`;
actorsList.appendChild(item);
// Add event listener to the remove button
item.querySelector('.remove-actor').addEventListener('click', () => removeActor(actorId, item));
}
// Remove actor from video
function removeActor(actorId, element) {
if (confirm('Are you sure you want to remove this actor?')) {
fetch(`/admin/adult-videos/${videoId}/actors/${actorId}`, {
method: 'DELETE',
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
element.remove();
} else {
alert('Failed to remove actor: ' + (data.error || 'Unknown error'));
}
});
}
}
// Load existing actors
function loadActors() {
fetch(`/admin/adult/${videoId}/actors`)
.then(response => response.json())
.then(data => {
if (data.data && data.data.length > 0) {
data.data.forEach(actor => {
addActorToList(actor.id, actor.name);
});
}
});
}
// Initialize
loadActors();
});

View File

@@ -4,17 +4,28 @@
<div class="px-4 py-3">
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1 class="h3 fw-bold text-dark mb-1">Adult Performers</h1>
<h1 class="h3 fw-bold text-dark mb-1">Performers</h1>
<p class="text-muted mb-0">{{ actors|length }} performer{{ actors|length != 1 ? 's' : '' }}</p>
</div>
</div>
<div class="items">
{% if actors %}
<div class="row g-3">
{% for actor in actors %}
<div class="col-md-6 col-lg-4 col-xl-2">
<div class="card h-100">
<div class="card-body text-center">
<figure class="item" style="padding:0px">
<a href="{{ path_for('actors.show', {'id': actor.id}) }}" class="text-decoration-none">
<img src="{{ actor.thumbnail_path }}" />
<figcaption>{{ actor.name }}</figcaption>
</a>
</figure>
<!--
div class="col-md-6 col-lg-4 col-xl-2">
<div class="item h-100">
<div class="item-body text-center">
<a href="{{ path_for('actors.show', {'id': actor.id}) }}" class="text-decoration-none">
{% if actor.thumbnail_path %}
<img src="{{ actor.thumbnail_path }}" alt="{{ actor.name }}" class="rounded-circle mb-3" style="width: 80px; height: 80px; object-fit: cover;">
@@ -26,8 +37,8 @@
</div>
{% endif %}
<h5 class="card-title mb-2">{{ actor.name }}</h5>
<p class="card-text small text-muted">
<h5 class="item-title mb-2">{{ actor.name }}</h5>
<p class="item-text small text-muted">
{{ actor.total_media_count }} scene{{ actor.total_media_count != 1 ? 's' : '' }}
</p>
@@ -39,9 +50,11 @@
</a>
</div>
</div>
</div>
</div
-->
{% endfor %}
</div>
</div>
{% else %}
<div class="text-center py-5">
<svg class="text-muted mb-3" width="64" height="64" fill="none" viewBox="0 0 24 24" stroke="currentColor">

View File

@@ -0,0 +1,233 @@
{% extends 'admin/layout.twig' %}
{% block title %}{{ video ? 'Edit' : 'Add New' }} Adult Video - Admin Panel - MediaLib{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1 class="h3 mb-0">{{ video ? 'Edit' : 'Add New' }} Adult Video</h1>
<p class="text-muted mb-0">{{ video ? 'Update the video details' : 'Add a new video to your library' }}</p>
</div>
<a href="{{ path_for('admin.adult.index') }}" class="btn btn-outline-secondary">
<i class="bi bi-arrow-left me-2"></i>Back to List
</a>
</div>
<div class="card">
<div class="card-body">
{% if flash.getMessage('error') %}
<div class="alert alert-danger">
{{ flash.getMessage('error') | first }}
</div>
{% endif %}
<form method="post" action="{{ video ? path_for('admin.adult.edit', {id: video.id}) : path_for('admin.adult.create') }}" enctype="multipart/form-data">
<div class="row">
<div class="col-md-4 mb-3">
<div class="card h-100">
<div class="card-body text-center">
<div class="mb-3">
{% if video and video.poster_url %}
<img id="poster-preview" src="{{ video.poster_url }}" class="img-fluid rounded" alt="Poster" style="max-height: 400px;">
{% else %}
<div id="poster-preview" class="bg-light d-flex align-items-center justify-content-center" style="height: 400px;">
<i class="bi bi-image text-muted" style="font-size: 4rem;"></i>
</div>
{% endif %}
</div>
<div class="mb-3">
<label for="poster" class="form-label">Poster Image</label>
<input class="form-control" type="file" id="poster" name="poster" accept="image/*">
</div>
{% if video and video.poster_url %}
<div class="form-check form-switch mb-3">
<input class="form-check-input" type="checkbox" id="remove_poster" name="remove_poster">
<label class="form-check-label" for="remove_poster">Remove poster</label>
</div>
{% endif %}
</div>
</div>
</div>
<div class="col-md-8">
<div class="mb-3">
<label for="title" class="form-label">Title <span class="text-danger">*</span></label>
<input type="text" class="form-control" id="title" name="title" value="{{ video.title ?? '' }}" required>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="release_date" class="form-label">Release Date</label>
<input type="date" class="form-control" id="release_date" name="release_date" value="{{ video.release_date ?? '' }}">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="runtime_minutes" class="form-label">Runtime (minutes)</label>
<input type="number" class="form-control" id="runtime_minutes" name="runtime_minutes" min="0" value="{{ video.runtime_minutes ?? '' }}">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="director" class="form-label">Director</label>
<input type="text" class="form-control" id="director" name="director" value="{{ video.director ?? '' }}">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="genre" class="form-label">Genre</label>
<input type="text" class="form-control" id="genre" name="genre" value="{{ video.genre ?? '' }}">
</div>
</div>
</div>
<div class="mb-3">
<label for="overview" class="form-label">Overview</label>
<textarea class="form-control" id="overview" name="overview" rows="5">{{ video.overview ?? '' }}</textarea>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="rating" class="form-label">Rating (0-10)</label>
<input type="number" class="form-control" id="rating" name="rating" min="0" max="10" step="0.1" value="{{ video.rating ?? '' }}">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="external_id" class="form-label">External ID</label>
<input type="text" class="form-control" id="external_id" name="external_id" value="{{ video.external_id ?? '' }}">
</div>
</div>
</div>
<div class="form-check form-switch mb-3">
<input class="form-check-input" type="checkbox" id="is_favorite" name="is_favorite" {{ video and video.is_favorite ? 'checked' : '' }}>
<label class="form-check-label" for="is_favorite">Mark as favorite</label>
</div>
<div class="form-check form-switch mb-3">
<input class="form-check-input" type="checkbox" id="watched" name="watched" {{ video and video.watched ? 'checked' : '' }}>
<label class="form-check-label" for="watched">Mark as watched</label>
</div>
<!-- Actor Management Section -->
<div class="card mb-4">
<div class="card-header">
<h5 class="mb-0">Actors</h5>
</div>
<div class="card-body">
<!-- Hidden input for video ID -->
<input type="hidden" id="video-id" value="{{ video.id }}">
<!-- Actor Search -->
<div class="mb-3">
<label for="actor-search" class="form-label">Search and Add Actors</label>
<div class="input-group">
<input type="text" class="form-control" id="actor-search" placeholder="Search for actors...">
<button class="btn btn-outline-secondary" type="button" id="add-actor-btn">
<i class="bi bi-plus-lg"></i> Add
</button>
</div>
<div id="actor-results" class="list-group position-absolute d-none" style="z-index: 1000; max-height: 200px; overflow-y: auto;">
<!-- Search results will appear here -->
</div>
</div>
<!-- Current Actors -->
<div class="mb-3">
<label class="form-label">Current Actors</label>
<div id="actors-list" class="list-group">
<!-- Actors will be added here dynamically -->
</div>
</div>
</div>
</div>
<div class="d-flex justify-content-between">
<div>
<button type="submit" class="btn btn-primary">
<i class="bi bi-save me-2"></i>Save Changes
</button>
<a href="{{ path_for('admin.adult.index') }}" class="btn btn-outline-secondary">
<i class="bi bi-x-lg me-2"></i>Cancel
</a>
</div>
{% if video %}
<button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
<i class="bi bi-trash me-2"></i>Delete Video
</button>
{% endif %}
</div>
</div>
</div>
</form>
</div>
</div>
{% if video %}
<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel">Confirm Deletion</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Are you sure you want to delete this video? This action cannot be undone.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<form action="{{ path_for('admin.adult.delete', {id: video.id}) }}" method="post" class="d-inline">
<input type="hidden" name="_METHOD" value="DELETE">
<button type="submit" class="btn btn-danger">
<i class="bi bi-trash me-2"></i>Delete Video
</button>
</form>
</div>
</div>
</div>
</div>
{% endif %}
{% endblock %}
{% block styles %}
<style>
#actor-results {
width: 100%;
max-width: 100%;
}
#actor-results .list-group-item {
cursor: pointer;
}
#actor-results .list-group-item:hover {
background-color: #f8f9fa;
}
#actors-list .btn {
padding: 0.25rem 0.5rem;
font-size: 0.875rem;
}
</style>
{% endblock %}
{% block scripts %}
<script src="{{ base_url() }}/js/adult-video-actors.js"></script>
<script>
// Preview image before upload
document.getElementById('poster').addEventListener('change', function(e) {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const preview = document.getElementById('poster-preview');
preview.innerHTML = `<img src="${e.target.result}" class="img-fluid rounded" alt="Poster" style="max-height: 400px;">`;
}
reader.readAsDataURL(file);
}
});
</script>
{% endblock %}

View File

@@ -0,0 +1,212 @@
{% extends 'admin/layout.twig' %}
{% block title %}Manage Adult Videos - Admin Panel - MediaLib{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1 class="h3 mb-0">Manage Adult Videos</h1>
<p class="text-muted mb-0">View and manage your adult video library</p>
</div>
<a href="{{ path_for('admin.adult.create') }}" class="btn btn-primary">
<i class="bi bi-plus-circle me-2"></i>Add New Video
</a>
</div>
{# Search and Filters #}
<div class="card mb-4">
<div class="card-body">
<form method="get" action="{{ path_for('admin.adult.index') }}" class="mb-0">
<div class="row g-3">
<div class="col-md-4">
<div class="input-group">
<span class="input-group-text"><i class="bi bi-search"></i></span>
<input type="text" name="search" class="form-control" placeholder="Search videos..." value="{{ filters.search }}">
</div>
</div>
<div class="col-md-2">
<select name="genre" class="form-select">
<option value="">All Genres</option>
{% for genre in genres %}
<option value="{{ genre }}" {{ filters.genre == genre ? 'selected' : '' }}>{{ genre }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-2">
<select name="director" class="form-select">
<option value="">All Directors</option>
{% for director in directors %}
<option value="{{ director }}" {{ filters.director == director ? 'selected' : '' }}>{{ director }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-2">
<select name="sort" class="form-select">
<option value="title_asc" {{ filters.sort == 'title_asc' ? 'selected' : '' }}>Title (A-Z)</option>
<option value="title_desc" {{ filters.sort == 'title_desc' ? 'selected' : '' }}>Title (Z-A)</option>
<option value="rating_desc" {{ filters.sort == 'rating_desc' ? 'selected' : '' }}>Highest Rated</option>
<option value="rating_asc" {{ filters.sort == 'rating_asc' ? 'selected' : '' }}>Lowest Rated</option>
<option value="newest" {{ filters.sort == 'newest' ? 'selected' : '' }}>Newest First</option>
<option value="oldest" {{ filters.sort == 'oldest' ? 'selected' : '' }}>Oldest First</option>
</select>
</div>
<div class="col-md-2">
<div class="d-flex">
<button type="submit" class="btn btn-primary me-2">
<i class="bi bi-funnel me-1"></i> Apply
</button>
<a href="{{ path_for('admin.adult.index') }}" class="btn btn-outline-secondary">
<i class="bi bi-arrow-counterclockwise"></i>
</a>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="card">
<div class="card-body">
{% if flash.getMessage('success') %}
<div class="alert alert-success">
{{ flash.getMessage('success') | first }}
</div>
{% endif %}
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Thumbnail</th>
<th>Title</th>
<th>Director</th>
<th>Genre</th>
<th>Rating</th>
<th>Release Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for video in videos %}
<tr>
<td>
{% if video.poster_url %}
<img src="{{ video.poster_url }}" alt="{{ video.title }}" style="width: 60px; height: 90px; object-fit: cover;">
{% else %}
<div class="bg-light d-flex align-items-center justify-content-center" style="width: 60px; height: 90px;">
<i class="bi bi-film text-muted"></i>
</div>
{% endif %}
</td>
<td>
<div class="fw-medium">{{ video.title }}</div>
<small class="text-muted">{{ video.runtime_minutes ? video.runtime_minutes ~ ' min' : 'N/A' }}</small>
</td>
<td>{{ video.director ?? 'N/A' }}</td>
<td>{{ video.genre ?? 'N/A' }}</td>
<td>
{% if video.rating %}
<span class="badge bg-primary">{{ video.rating|number_format(1) }}/10</span>
{% else %}
<span class="text-muted">N/A</span>
{% endif %}
</td>
<td>{{ video.release_date ? video.release_date|date('Y-m-d') : 'N/A' }}</td>
<td>
<div class="btn-group btn-group-sm">
<a href="{{ path_for('admin.adult.edit', {id: video.id}) }}" class="btn btn-outline-primary">
<i class="bi bi-pencil"></i>
</a>
<form action="{{ path_for('admin.adult.delete', {id: video.id}) }}" method="post" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this video?');">
<input type="hidden" name="_METHOD" value="DELETE">
<button type="submit" class="btn btn-outline-danger">
<i class="bi bi-trash"></i>
</button>
</form>
</div>
</td>
</tr>
{% else %}
<tr>
<td colspan="7" class="text-center py-4">
<div class="text-muted">No videos found. <a href="{{ path_for('admin.adult.create') }}">Add your first video</a></div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if pagination.total > 1 %}
<div class="d-flex justify-content-between align-items-center mt-4">
<div class="text-muted">
Showing {{ pagination.from }} to {{ pagination.to }} of {{ pagination.total_items }} videos
</div>
<nav>
<ul class="pagination mb-0">
{% if pagination.current > 1 %}
<li class="page-item">
<a class="page-link" href="{{ path_for('admin.adult.index', {
'page': pagination.current - 1,
'search': filters.search,
'genre': filters.genre,
'director': filters.director,
'sort': filters.sort
}) }}" aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
{% else %}
<li class="page-item disabled">
<span class="page-link" aria-hidden="true">&laquo;</span>
</li>
{% endif %}
{% for i in 1..pagination.total %}
{% if i == pagination.current %}
<li class="page-item active" aria-current="page">
<span class="page-link">{{ i }}</span>
</li>
{% else %}
{% if (i >= pagination.current - 2 and i <= pagination.current + 2) or i == 1 or i == pagination.total %}
<li class="page-item">
<a class="page-link" href="{{ path_for('admin.adult.index', {
'page': i,
'search': filters.search,
'genre': filters.genre,
'director': filters.director,
'sort': filters.sort
}) }}">{{ i }}</a>
</li>
{% elseif (i == pagination.current - 3 or i == pagination.current + 3) %}
<li class="page-item disabled">
<span class="page-link">...</span>
</li>
{% endif %}
{% endif %}
{% endfor %}
{% if pagination.current < pagination.total %}
<li class="page-item">
<a class="page-link" href="{{ path_for('admin.adult.index', {
'page': pagination.current + 1,
'search': filters.search,
'genre': filters.genre,
'director': filters.director,
'sort': filters.sort
}) }}" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
{% else %}
<li class="page-item disabled">
<span class="page-link" aria-hidden="true">&raquo;</span>
</li>
{% endif %}
</ul>
</nav>
</div>
{% endif %}
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,737 @@
{% extends 'admin/layout.twig' %}
{% block title %}{{ title }} - Admin Panel - MediaLib{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1 class="h3 mb-0">{{ title }}</h1>
<p class="text-muted mb-0">{{ game ? 'Edit game details' : 'Add a new game to your library' }}</p>
</div>
<a href="{{ path_for('admin.games.index') }}" class="btn btn-outline-secondary">
<i class="bi bi-arrow-left me-2"></i>Back to Games
</a>
</div>
<div class="row">
<div class="col-lg-8">
<div class="card mb-4">
<div class="card-body">
{% if flash.getMessage('success') %}
<div class="alert alert-success">
{{ flash.getMessage('success') | first }}
</div>
{% endif %}
<form method="post" enctype="multipart/form-data">
<div class="mb-3">
<label for="title" class="form-label">Title *</label>
<input type="text" class="form-control" id="title" name="title" required
value="{{ old.title ?? game.title ?? '' }}">
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="release_date" class="form-label">Release Date</label>
<input type="date" class="form-control" id="release_date" name="release_date"
value="{{ old.release_date ?? (game.release_date ? game.release_date|date('Y-m-d') : '') }}">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="platform" class="form-label">Platform</label>
<select class="form-select" id="platform" name="platform">
<option value="">Select Platform</option>
<option value="PC" {{ (old.platform ?? game.platform ?? '') == 'PC' ? 'selected' : '' }}>PC</option>
<option value="PlayStation" {{ (old.platform ?? game.platform ?? '') == 'PlayStation' ? 'selected' : '' }}>PlayStation</option>
<option value="Xbox" {{ (old.platform ?? game.platform ?? '') == 'Xbox' ? 'selected' : '' }}>Xbox</option>
<option value="Nintendo" {{ (old.platform ?? game.platform ?? '') == 'Nintendo' ? 'selected' : '' }}>Nintendo</option>
<option value="Mobile" {{ (old.platform ?? game.platform ?? '') == 'Mobile' ? 'selected' : '' }}>Mobile</option>
<option value="Other" {{ (old.platform ?? game.platform ?? '') == 'Other' ? 'selected' : '' }}>Other</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="developer" class="form-label">Developer</label>
<input type="text" class="form-control" id="developer" name="developer"
value="{{ old.developer ?? game.developer ?? '' }}">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="publisher" class="form-label">Publisher</label>
<input type="text" class="form-control" id="publisher" name="publisher"
value="{{ old.publisher ?? game.publisher ?? '' }}">
</div>
</div>
</div>
<div class="mb-3">
<label for="genres" class="form-label">Genres (comma-separated)</label>
<input type="text" class="form-control" id="genres" name="genres"
value="{{ old.genres ?? (game.genres ? game.genres|join(', ') : '') }}">
<div class="form-text">Example: Action, Adventure, RPG</div>
</div>
<div class="mb-3">
<label for="description" class="form-label">Description</label>
<textarea class="form-control" id="description" name="description" rows="4">{{ old.description ?? game.description ?? '' }}</textarea>
</div>
<div class="mb-3">
<label for="cover_image" class="form-label">Cover Image URL</label>
<input type="text" class="form-control" id="cover_image" name="cover_image"
value="{{ old.cover_image ?? game.cover_image ?? '' }}">
</div>
<div class="mb-3">
<label for="trailer_url" class="form-label">Trailer URL</label>
<input type="text" class="form-control" id="trailer_url" name="trailer_url"
value="{{ old.trailer_url ?? game.trailer_url ?? '' }}">
</div>
<div class="d-flex justify-content-between">
<button type="submit" class="btn btn-primary">
<i class="bi bi-save me-2"></i>Save Changes
</button>
{% if game %}
<button type="button" class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
<i class="bi bi-trash me-2"></i>Delete Game
</button>
{% endif %}
</div>
</form>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card mb-4">
<div class="card-header">
<h5 class="mb-0">Cover Preview</h5>
</div>
<div class="card-body text-center">
<div id="coverPreview" class="mb-3" style="min-height: 300px; display: flex; align-items: center; justify-content: center; background-color: #f8f9fa;">
{% if game and game.cover_image %}
<img src="{{ game.cover_image }}" alt="Cover" class="img-fluid" style="max-height: 300px;">
{% else %}
<div class="text-muted">No cover available</div>
{% endif %}
</div>
</div>
</div>
<!-- SteamGridDB Media -->
{% if game %}
<div class="card mb-4">
<div class="card-header">
<h5 class="mb-0">SteamGridDB Media</h5>
</div>
<div class="card-body">
<div class="mb-3">
<label class="form-label">Search for game media</label>
<div class="input-group">
<input type="text" id="sgdb-search" class="form-control" placeholder="Search for a game...">
<button class="btn btn-primary" type="button" id="sgdb-search-btn">
<i class="bi bi-search"></i> Search
</button>
</div>
<div id="sgdb-search-results" class="mt-3"></div>
</div>
<div id="media-selection" class="d-none">
<h6>Available Media</h6>
<div class="mb-3">
<ul id="media-tabs" class="nav nav-tabs" role="tablist"></ul>
<div id="media-content" class="tab-content p-3 border border-top-0 rounded-bottom"></div>
</div>
<div class="d-flex justify-content-between align-items-center">
<button class="btn btn-sm btn-outline-secondary" id="back-to-search">
<i class="bi bi-arrow-left me-1"></i> Back to Search
</button>
<button class="btn btn-sm btn-primary set-media-btn" disabled>
<i class="bi bi-check-circle me-1"></i> Use Selected
</button>
</div>
</div>
</div>
</div>
{% endif %}
<!-- Metadata -->
<div class="card">
<div class="card-header">
<h5 class="mb-0">Metadata</h5>
</div>
<div class="card-body">
<div class="mb-2">
<span class="text-muted">Created:</span>
<span class="float-end">{{ game ? game.created_at|date('Y-m-d H:i') : 'New' }}</span>
</div>
<div class="mb-2">
<span class="text-muted">Last Updated:</span>
<span class="float-end">{{ game ? game.updated_at|date('Y-m-d H:i') : 'N/A' }}</span>
</div>
</div>
</div>
</div>
</div>
<!-- Delete Confirmation Modal -->
{% if game %}
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel">Confirm Deletion</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete "{{ game.title }}"? This action cannot be undone.</p>
<p class="text-danger"><strong>Warning:</strong> This will remove all data associated with this game.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<form action="{{ path_for('admin.games.delete', {id: game.id}) }}" method="post" class="d-inline">
<input type="hidden" name="_METHOD" value="DELETE">
<button type="submit" class="btn btn-danger">Delete Game</button>
</form>
</div>
</div>
</div>
</div>
{% endif %}
{% endblock %}
{% block styles %}
<style>
.media-tab-pane {
display: none;
}
.media-tab-pane.active {
display: block;
}
.media-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 1rem;
margin-top: 1rem;
}
.media-item {
cursor: pointer;
border: 2px solid transparent;
border-radius: 4px;
overflow: hidden;
transition: all 0.2s;
}
.media-item:hover {
border-color: var(--bs-primary);
transform: translateY(-2px);
}
.media-item.selected {
border-color: var(--bs-primary);
box-shadow: 0 0 0 2px var(--bs-primary);
}
.media-item img {
width: 100%;
height: auto;
aspect-ratio: 1;
object-fit: cover;
}
.media-preview {
max-width: 100%;
max-height: 300px;
margin: 1rem 0;
}
</style>
{% endblock %}
{% block scripts %}
<script>
// Define all functions first
async function loadGameMedia(gameId) {
const tabs = [
{ type: 'grids', title: 'Grids', field: 'cover_url' },
{ type: 'heroes', title: 'Heroes', field: 'banner_url' },
{ type: 'icons', title: 'Icons', field: 'icon_url' },
{ type: 'logos', title: 'Logos', field: 'logo_url' }
];
// Add hidden fields if they don't exist
const form = document.querySelector('form');
['banner_url', 'icon_url', 'logo_url'].forEach(field => {
if (!form.querySelector(`[name="${field}"]`)) {
const input = document.createElement('input');
input.type = 'hidden';
input.name = field;
input.id = field;
form.appendChild(input);
}
});
const tabsContainer = document.getElementById('media-tabs');
const contentContainer = document.getElementById('media-content');
// Clear existing content
tabsContainer.innerHTML = '';
contentContainer.innerHTML = '';
// Create tabs
const tabList = document.createElement('ul');
tabList.className = 'nav nav-tabs';
tabList.role = 'tablist';
// Create tab content
tabs.forEach((tab, index) => {
// Tab button
const tabItem = document.createElement('li');
tabItem.className = 'nav-item';
tabItem.role = 'presentation';
const tabButton = document.createElement('button');
tabButton.className = `nav-link ${index === 0 ? 'active' : ''}`;
tabButton.setAttribute('data-bs-toggle', 'tab');
tabButton.setAttribute('data-bs-target', `#${tab.type}-pane`);
tabButton.type = 'button';
tabButton.role = 'tab';
tabButton.textContent = tab.title;
tabItem.appendChild(tabButton);
tabList.appendChild(tabItem);
// Tab content
const tabPane = document.createElement('div');
tabPane.id = `${tab.type}-pane`;
tabPane.className = `media-tab-pane fade ${index === 0 ? 'show active' : ''}`;
tabPane.setAttribute('data-field', tab.field);
tabPane.role = 'tabpanel';
tabPane.innerHTML = `
<div class="d-flex justify-content-between align-items-center mb-3">
<h6>Select a ${tab.title.toLowerCase()} image</h6>
<div class="spinner-border spinner-border-sm" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
<div class="media-grid" id="${tab.type}-grid"></div>
<div class="mt-3">
<img src="" class="media-preview d-none img-thumbnail mb-2" alt="Selected image">
<button type="button" class="btn btn-sm btn-primary use-selected-btn" disabled>
<i class="bi bi-check-circle me-1"></i> Use Selected
</button>
</div>
`;
contentContainer.appendChild(tabPane);
// Load media for this tab
loadMediaForTab(tab.type, tab.field, gameId);
});
tabsContainer.appendChild(tabList);
// Show the media selection section
document.getElementById('media-selection').classList.remove('d-none');
}
async function loadMediaForTab(type, field, gameId) {
const grid = document.getElementById(`${type}-grid`);
if (!grid) return;
try {
const response = await fetch(`/admin/games/sgdb/media/${gameId}/${type}`);
const data = await response.json();
if (data.success && data.data && data.data.length > 0) {
grid.innerHTML = '';
data.data.forEach((item, index) => {
const mediaItem = document.createElement('div');
mediaItem.className = 'media-item';
mediaItem.setAttribute('data-url', item.url);
mediaItem.setAttribute('data-thumb', item.thumb || item.url);
mediaItem.setAttribute('title', item.style || item.dimensions || '');
const img = document.createElement('img');
img.src = item.thumb || item.url;
img.alt = `Image ${index + 1}`;
img.className = 'img-fluid';
mediaItem.appendChild(img);
grid.appendChild(mediaItem);
// Add click handler for media selection
mediaItem.addEventListener('click', function() {
const container = this.closest('.media-tab-pane');
container.querySelectorAll('.media-item').forEach(i => i.classList.remove('selected'));
this.classList.add('selected');
const url = this.getAttribute('data-url');
const field = container.getAttribute('data-field');
const preview = container.querySelector('.media-preview');
if (preview) {
preview.src = url;
preview.classList.remove('d-none');
}
// Enable the use selected button
const useButton = container.querySelector('.use-selected-btn');
if (useButton) {
useButton.disabled = false;
useButton.onclick = function() {
// Update the corresponding form field
const field = container.getAttribute('data-field');
let input = document.querySelector(`input[name="${field}"]`);
// If input doesn't exist, create it
if (!input) {
input = document.createElement('input');
input.type = 'hidden';
input.name = field;
input.id = field;
document.querySelector('form').appendChild(input);
}
input.value = url;
// For cover_url, also update the visible input if it exists
if (field === 'cover_url') {
const coverInput = document.getElementById('cover_url');
if (coverInput) {
coverInput.value = url;
}
}
// Show success message
const alert = document.createElement('div');
alert.className = 'alert alert-success mt-2';
alert.textContent = 'Media selected successfully!';
container.querySelector('.media-preview').insertAdjacentElement('afterend', alert);
// Remove the alert after 3 seconds
setTimeout(() => alert.remove(), 3000);
};
}
});
});
} else {
grid.innerHTML = '<div class="alert alert-info">No media found for this type.</div>';
}
} catch (error) {
console.error(`Error loading ${type}:`, error);
grid.innerHTML = '<div class="alert alert-danger">Failed to load media. Please try again.</div>';
}
}
// Media tabs
document.addEventListener('DOMContentLoaded', function() {
// Handle tab switching
const tabButtons = document.querySelectorAll('[data-bs-toggle="tab"]');
// Initialize first tab as active
if (tabButtons.length > 0) {
document.querySelector('#media-tabs .nav-link').click();
}
tabButtons.forEach(button => {
button.addEventListener('click', function(e) {
e.preventDefault();
const target = this.getAttribute('data-bs-target');
document.querySelectorAll('.media-tab-pane').forEach(pane => {
pane.classList.remove('active');
});
document.querySelector(target).classList.add('active');
// Update active tab button
tabButtons.forEach(btn => btn.classList.remove('active'));
this.classList.add('active');
});
});
// Load media for a specific game
async function loadGameMedia(gameId) {
const tabs = [
{ type: 'grids', title: 'Grids', field: 'image_url' },
{ type: 'heroes', title: 'Heroes', field: 'banner_url' },
{ type: 'icons', title: 'Icons', field: 'icon' },
{ type: 'logos', title: 'Logos', field: 'logo_url' }
];
const tabsContainer = document.getElementById('media-tabs');
const contentContainer = document.getElementById('media-content');
// Clear existing content
tabsContainer.innerHTML = '';
contentContainer.innerHTML = '';
// Create tabs
const tabList = document.createElement('ul');
tabList.className = 'nav nav-tabs';
tabList.role = 'tablist';
// Create tab content
tabs.forEach((tab, index) => {
// Tab button
const tabItem = document.createElement('li');
tabItem.className = 'nav-item';
tabItem.role = 'presentation';
const tabButton = document.createElement('button');
tabButton.className = `nav-link ${index === 0 ? 'active' : ''}`;
tabButton.setAttribute('data-bs-toggle', 'tab');
tabButton.setAttribute('data-bs-target', `#${tab.type}-pane`);
tabButton.type = 'button';
tabButton.role = 'tab';
tabButton.textContent = tab.title;
tabItem.appendChild(tabButton);
tabList.appendChild(tabItem);
// Tab content
const tabPane = document.createElement('div');
tabPane.id = `${tab.type}-pane`;
tabPane.className = `media-tab-pane fade ${index === 0 ? 'show active' : ''}`;
tabPane.setAttribute('data-field', tab.field);
tabPane.role = 'tabpanel';
tabPane.innerHTML = `
<div class="d-flex justify-content-between align-items-center mb-3">
<h6>Select a ${tab.title.toLowerCase()} image</h6>
<div class="spinner-border spinner-border-sm" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
<div class="media-grid" id="${tab.type}-grid"></div>
<img src="" class="media-preview d-none img-thumbnail" alt="Selected image">
`;
contentContainer.appendChild(tabPane);
// Load media for this tab
loadMediaForTab(tab.type, tab.field, gameId);
});
tabsContainer.appendChild(tabList);
// Show the first tab
if (tabs.length > 0) {
document.querySelector('#media-tabs .nav-link').click();
}
}
// Load media for a specific tab
async function loadMediaForTab(type, field, gameId) {
const grid = document.getElementById(`${type}-grid`);
if (!grid) return;
try {
const response = await fetch(`/admin/games/sgdb/media/${gameId}/${type}`);
const data = await response.json();
if (data.success && data.data.length > 0) {
grid.innerHTML = '';
data.data.forEach((item, index) => {
const img = document.createElement('div');
img.className = 'media-item';
img.setAttribute('data-url', item.url);
img.setAttribute('data-thumb', item.thumb || item.url);
img.setAttribute('title', item.style || item.dimensions || '');
const imgElement = document.createElement('img');
imgElement.src = item.thumb || item.url;
imgElement.alt = `Image ${index + 1}`;
imgElement.loading = 'lazy';
img.appendChild(imgElement);
grid.appendChild(img);
// Add click handler to update the form field
img.addEventListener('click', function() {
const url = this.getAttribute('data-url');
const input = document.querySelector(`input[name="${field}"]`);
if (input) {
input.value = url;
}
// Show preview
const preview = this.closest('.media-tab-pane').querySelector('.media-preview');
if (preview) {
preview.src = url;
preview.classList.remove('d-none');
}
});
});
} else {
grid.innerHTML = '<div class="col-12"><p class="text-muted">No media found.</p></div>';
}
} catch (error) {
console.error(`Error loading ${type}:`, error);
grid.innerHTML = '<div class="col-12"><p class="text-danger">Error loading media. Please try again.</p></div>';
}
}
// Handle form submission for setting media
document.querySelectorAll('.set-media-btn').forEach(button => {
button.addEventListener('click', async function() {
const tabPane = this.closest('.media-tab-pane');
const selectedItem = tabPane.querySelector('.media-item.selected');
if (!selectedItem) {
alert('Please select an image first');
return;
}
const url = selectedItem.getAttribute('data-url');
const field = tabPane.getAttribute('data-field');
const gameId = '{{ game.id ?? 0 }}';
try {
const response = await fetch(`/admin/games/${gameId}/sgdb/media`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
},
body: JSON.stringify({
type: field.replace('_url', '').replace('_', '-'),
url: url
})
});
const data = await response.json();
if (data.success) {
// Update the form field
const input = document.querySelector(`input[name="${field}"]`);
if (input) {
input.value = data.data.url;
}
// Show success message
const alert = document.createElement('div');
alert.className = 'alert alert-success mt-3';
alert.textContent = 'Media updated successfully';
tabPane.insertBefore(alert, tabPane.firstChild);
// Remove the message after 3 seconds
setTimeout(() => {
alert.remove();
}, 3000);
} else {
throw new Error(data.message || 'Failed to update media');
}
} catch (error) {
console.error('Error updating media:', error);
alert('Failed to update media: ' + error.message);
}
});
});
});
// Handle SteamGridDB search
const searchInput = document.getElementById('sgdb-search');
const searchBtn = document.getElementById('sgdb-search-btn');
const searchResults = document.getElementById('sgdb-search-results');
const mediaSelection = document.getElementById('media-selection');
const backToSearch = document.getElementById('back-to-search');
if (searchBtn && searchInput) {
// Search for games
searchBtn.addEventListener('click', async () => {
const query = searchInput.value.trim();
if (!query) return;
searchBtn.disabled = true;
searchBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Searching...';
searchResults.innerHTML = '<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div><p class="mt-2">Searching for games...</p></div>';
try {
const response = await fetch(`/admin/games/sgdb/search?q=${encodeURIComponent(query)}`);
const data = await response.json();
if (data.success && data.data && data.data.length > 0) {
let html = '<div class="list-group">';
data.data.forEach(game => {
html += `
<a href="#" class="list-group-item list-group-item-action" data-game-id="${game.id}">
<div class="d-flex w-100 justify-content-between">
<h6 class="mb-1">${game.name}</h6>
<small>${game.release_date ? new Date(game.release_date * 1000).getFullYear() : 'N/A'}</small>
</div>
<p class="mb-1">${game.platforms ? game.platforms.join(', ') : 'Unknown Platform'}</p>
</a>
`;
});
html += '</div>';
searchResults.innerHTML = html;
// Add click handlers for game selection
document.querySelectorAll('#sgdb-search-results .list-group-item').forEach(item => {
item.addEventListener('click', (e) => {
e.preventDefault();
const gameId = item.getAttribute('data-game-id');
loadGameMedia(gameId);
searchResults.innerHTML = '';
mediaSelection.classList.remove('d-none');
});
});
} else {
searchResults.innerHTML = '<div class="alert alert-info">No games found. Try a different search term.</div>';
}
} catch (error) {
console.error('Error searching SteamGridDB:', error);
searchResults.innerHTML = '<div class="alert alert-danger">Error searching for games. Please try again later.</div>';
} finally {
searchBtn.disabled = false;
searchBtn.innerHTML = '<i class="bi bi-search me-1"></i> Search';
}
});
// Handle search on Enter key
searchInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
searchBtn.click();
}
});
}
// Handle back to search button
if (backToSearch) {
backToSearch.addEventListener('click', () => {
mediaSelection.classList.add('d-none');
searchResults.innerHTML = '';
searchInput.value = '';
searchInput.focus();
});
}
// Preview cover when URL changes
document.getElementById('cover_url').addEventListener('input', function() {
const preview = document.getElementById('coverPreview');
const url = this.value.trim();
if (url) {
preview.innerHTML = `<img src="${url}" alt="Cover Preview" class="img-fluid" style="max-height: 300px;">`;
} else {
preview.innerHTML = '<div class="text-muted">No cover available</div>';
}
});
// Handle form submission
document.querySelector('form').addEventListener('submit', function(e) {
const title = document.getElementById('title').value.trim();
if (!title) {
e.preventDefault();
alert('Title is required');
return false;
}
return true;
});
</script>
{% endblock %}

View File

@@ -0,0 +1,218 @@
{% extends 'admin/layout.twig' %}
{% block title %}Manage Games - Admin Panel - MediaLib{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1 class="h3 mb-0">Manage Games</h1>
<p class="text-muted mb-0">View and manage your game library</p>
</div>
<a href="{{ path_for('admin.games.create') }}" class="btn btn-primary">
<i class="bi bi-plus-circle me-2"></i>Add New Game
</a>
</div>
<div class="card">
<div class="card-body">
{% if flash.getMessage('success') %}
<div class="alert alert-success">
{{ flash.getMessage('success') | first }}
</div>
{% endif %}
<!-- Search and Filter Form -->
<form method="get" class="mb-4">
<div class="row g-3">
<div class="col-md-4">
<div class="input-group">
<input type="text"
class="form-control"
name="search"
placeholder="Search games..."
value="{{ filters.search }}">
<button class="btn btn-primary" type="submit">
<i class="bi bi-search"></i>
</button>
</div>
</div>
<div class="col-md-2">
<select name="platform" class="form-select">
<option value="">All Platforms</option>
{% for platform in platforms %}
<option value="{{ platform }}" {{ filters.platform == platform ? 'selected' : '' }}>
{{ platform }}
</option>
{% endfor %}
</select>
</div>
<div class="col-md-2">
<select name="genre" class="form-select">
<option value="">All Genres</option>
{% for genre in genres %}
<option value="{{ genre }}" {{ filters.genre == genre ? 'selected' : '' }}>
{{ genre }}
</option>
{% endfor %}
</select>
</div>
<div class="col-md-2">
<select name="sort" class="form-select">
<option value="title_asc" {{ filters.sort == 'title_asc' ? 'selected' : '' }}>Title (A-Z)</option>
<option value="title_desc" {{ filters.sort == 'title_desc' ? 'selected' : '' }}>Title (Z-A)</option>
<option value="release_desc" {{ filters.sort == 'release_desc' ? 'selected' : '' }}>Newest First</option>
<option value="release_asc" {{ filters.sort == 'release_asc' ? 'selected' : '' }}>Oldest First</option>
<option value="rating_desc" {{ filters.sort == 'rating_desc' ? 'selected' : '' }}>Highest Rated</option>
</select>
</div>
<div class="col-md-2">
<div class="btn-group w-100">
<button type="submit" class="btn btn-primary">
<i class="bi bi-funnel me-1"></i> Filter
</button>
<a href="{{ path_for('admin.games') }}" class="btn btn-outline-secondary">
<i class="bi bi-x-lg"></i>
</a>
</div>
</div>
</div>
</form>
<!-- Results Summary -->
<div class="d-flex justify-content-between align-items-center mb-3">
<div class="text-muted">
Showing {{ pagination.from }} to {{ pagination.to }} of {{ pagination.total_items }} games
</div>
<div class="btn-group">
<button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="dropdown" aria-expanded="false">
<i class="bi bi-list-ul me-1"></i> View
</button>
<ul class="dropdown-menu dropdown-menu-end">
<li><a class="dropdown-item" href="#"><i class="bi bi-grid-3x3-gap-fill me-2"></i>Grid</a></li>
<li><a class="dropdown-item active" href="#"><i class="bi bi-list-ul me-2"></i>List</a></li>
</ul>
</div>
</div>
<div class="table-responsive">
<table class="table table-hover align-middle">
<thead class="table-light">
<tr>
<th style="width: 60px;">Cover</th>
<th>Title</th>
<th>Platform</th>
<th>Release Date</th>
<th>Rating</th>
<th class="text-end">Actions</th>
</tr>
</thead>
<tbody>
{% for game in games %}
<tr>
<td>
{% if game.cover_url %}
<img src="{{ game.cover_url }}" alt="{{ game.title }}" style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px;">
{% else %}
<div class="bg-light d-flex align-items-center justify-content-center" style="width: 50px; height: 50px; border-radius: 4px;">
<i class="bi bi-controller text-muted"></i>
</div>
{% endif %}
</td>
<td>
<div class="fw-medium">{{ game.title }}</div>
<small class="text-muted">{{ game.developer ? game.developer : 'N/A' }}</small>
</td>
<td>{{ game.platform ? game.platform : 'N/A' }}</td>
<td>{{ game.release_date ? game.release_date|date('Y') : 'N/A' }}</td>
<td>
{% if game.rating %}
<span class="badge bg-primary">{{ game.rating|number_format(1) }}/5</span>
{% else %}
<span class="text-muted">N/A</span>
{% endif %}
</td>
<td>
<div class="btn-group btn-group-sm">
<a href="{{ path_for('admin.games.edit', {id: game.id}) }}" class="btn btn-outline-primary">
<i class="bi bi-pencil"></i>
</a>
<form action="{{ path_for('admin.games.delete', {id: game.id}) }}" method="post" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this game?');">
<input type="hidden" name="_METHOD" value="DELETE">
<button type="submit" class="btn btn-outline-danger">
<i class="bi bi-trash"></i>
</button>
</form>
</div>
</td>
</tr>
{% else %}
<tr>
<td colspan="6" class="text-center py-4">
<div class="text-muted">No games found. <a href="{{ path_for('admin.games.create') }}">Add your first game</a></div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- Pagination -->
{% if pagination.total > 1 %}
<nav class="mt-4">
<ul class="pagination justify-content-center">
{% if pagination.current > 1 %}
<li class="page-item">
<a class="page-link" href="{{ path_for('admin.games', {}, {'page': pagination.current - 1, 'search': filters.search, 'platform': filters.platform, 'genre': filters.genre, 'sort': filters.sort}) }}" aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
{% endif %}
{% set start = max(1, pagination.current - 2) %}
{% set end = min(pagination.total, pagination.current + 2) %}
{% if start > 1 %}
<li class="page-item">
<a class="page-link" href="{{ path_for('admin.games', {}, {'page': 1, 'search': filters.search, 'platform': filters.platform, 'genre': filters.genre, 'sort': filters.sort}) }}">1</a>
</li>
{% if start > 2 %}
<li class="page-item disabled">
<span class="page-link">...</span>
</li>
{% endif %}
{% endif %}
{% for i in start..end %}
<li class="page-item {% if i == pagination.current %}active{% endif %}">
<a class="page-link" href="{{ path_for('admin.games', {}, {'page': i, 'search': filters.search, 'platform': filters.platform, 'genre': filters.genre, 'sort': filters.sort}) }}">
{{ i }}
</a>
</li>
{% endfor %}
{% if end < pagination.total %}
{% if end < pagination.total - 1 %}
<li class="page-item disabled">
<span class="page-link">...</span>
</li>
{% endif %}
<li class="page-item">
<a class="page-link" href="{{ path_for('admin.games', {}, {'page': pagination.total, 'search': filters.search, 'platform': filters.platform, 'genre': filters.genre, 'sort': filters.sort}) }}">
{{ pagination.total }}
</a>
</li>
{% endif %}
{% if pagination.current < pagination.total %}
<li class="page-item">
<a class="page-link" href="{{ path_for('admin.games', {}, {'page': pagination.current + 1, 'search': filters.search, 'platform': filters.platform, 'genre': filters.genre, 'sort': filters.sort}) }}" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
</div>
</div>
{% endblock %}

View File

@@ -215,25 +215,25 @@
<div class="sidebar-heading mt-4">Media</div>
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link" href="{{ path_for('games.index') }}" target="_blank">
<a class="nav-link" href="{{ path_for('admin.games') }}">
<i class="bi bi-joystick"></i>
<span>Games</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ path_for('movies.index') }}" target="_blank">
<a class="nav-link" href="{{ path_for('admin.movies') }}">
<i class="bi bi-film"></i>
<span>Movies</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ path_for('tvshows.index') }}" target="_blank">
<a class="nav-link" href="{{ path_for('admin.shows') }}">
<i class="bi bi-tv"></i>
<span>TV Shows</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ path_for('music.index') }}" target="_blank">
<a class="nav-link" href="{{ path_for('admin.music') }}">
<i class="bi bi-music-note-list"></i>
<span>Music</span>
</a>

View File

@@ -0,0 +1,196 @@
{% extends 'admin/layout.twig' %}
{% block title %}{{ title }} - Admin Panel - MediaLib{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1 class="h3 mb-0">{{ title }}</h1>
<p class="text-muted mb-0">{{ movie ? 'Edit movie details' : 'Add a new movie to your library' }}</p>
</div>
<a href="{{ path_for('admin.movies.index') }}" class="btn btn-outline-secondary">
<i class="bi bi-arrow-left me-2"></i>Back to Movies
</a>
</div>
<div class="row">
<div class="col-lg-8">
<div class="card mb-4">
<div class="card-body">
{% if flash.getMessage('success') %}
<div class="alert alert-success">
{{ flash.getMessage('success') | first }}
</div>
{% endif %}
<form method="post" enctype="multipart/form-data">
<div class="mb-3">
<label for="title" class="form-label">Title *</label>
<input type="text" class="form-control" id="title" name="title" required
value="{{ old.title ?? movie.title ?? '' }}">
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="release_date" class="form-label">Release Date</label>
<input type="date" class="form-control" id="release_date" name="release_date"
value="{{ old.release_date ?? (movie.release_date ? movie.release_date|date('Y-m-d') : '') }}">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="runtime" class="form-label">Runtime (minutes)</label>
<input type="number" class="form-control" id="runtime" name="runtime" min="1"
value="{{ old.runtime ?? movie.runtime ?? '' }}">
</div>
</div>
</div>
<div class="mb-3">
<label for="overview" class="form-label">Overview</label>
<textarea class="form-control" id="overview" name="overview" rows="4">{{ old.overview ?? movie.overview ?? '' }}</textarea>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="vote_average" class="form-label">Rating (0-10)</label>
<input type="number" class="form-control" id="vote_average" name="vote_average"
min="0" max="10" step="0.1"
value="{{ old.vote_average ?? movie.vote_average ?? '' }}">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="status" class="form-label">Status</label>
<select class="form-select" id="status" name="status">
<option value="released" {{ (old.status ?? movie.status ?? '') == 'released' ? 'selected' : '' }}>Released</option>
<option value="upcoming" {{ (old.status ?? movie.status ?? '') == 'upcoming' ? 'selected' : '' }}>Upcoming</option>
<option value="post_production" {{ (old.status ?? movie.status ?? '') == 'post_production' ? 'selected' : '' }}>Post Production</option>
</select>
</div>
</div>
</div>
<div class="mb-3">
<label for="poster_url" class="form-label">Poster URL</label>
<input type="text" class="form-control" id="poster_url" name="poster_url"
value="{{ old.poster_url ?? movie.poster_url ?? '' }}">
</div>
<div class="mb-3">
<label for="backdrop_url" class="form-label">Backdrop URL</label>
<input type="text" class="form-control" id="backdrop_url" name="backdrop_url"
value="{{ old.backdrop_url ?? movie.backdrop_url ?? '' }}">
</div>
<div class="d-flex justify-content-between">
<button type="submit" class="btn btn-primary">
<i class="bi bi-save me-2"></i>Save Changes
</button>
{% if movie %}
<button type="button" class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
<i class="bi bi-trash me-2"></i>Delete Movie
</button>
{% endif %}
</div>
</form>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card mb-4">
<div class="card-header">
<h5 class="mb-0">Poster Preview</h5>
</div>
<div class="card-body text-center">
<div id="posterPreview" class="mb-3" style="min-height: 300px; display: flex; align-items: center; justify-content: center; background-color: #f8f9fa;">
{% if movie and movie.poster_url %}
<img src="/images/{{ movie.poster_url }}" alt="Poster" class="img-fluid" style="max-height: 300px;">
{% else %}
<div class="text-muted">No poster available</div>
{% endif %}
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h5 class="mb-0">Metadata</h5>
</div>
<div class="card-body">
<div class="mb-2">
<span class="text-muted">Created:</span>
<span class="float-end">{{ movie ? movie.created_at|date('Y-m-d H:i') : 'New' }}</span>
</div>
<div class="mb-2">
<span class="text-muted">Last Updated:</span>
<span class="float-end">{{ movie ? movie.updated_at|date('Y-m-d H:i') : 'N/A' }}</span>
</div>
{% if movie and movie.tmdb_id %}
<div class="mt-3">
<a href="https://www.themoviedb.org/movie/{{ movie.tmdb_id }}" target="_blank" class="btn btn-sm btn-outline-primary w-100">
<i class="bi bi-box-arrow-up-right me-1"></i> View on TMDb
</a>
</div>
{% endif %}
</div>
</div>
</div>
</div>
<!-- Delete Confirmation Modal -->
{% if movie %}
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel">Confirm Deletion</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete "{{ movie.title }}"? This action cannot be undone.</p>
<p class="text-danger"><strong>Warning:</strong> This will remove all data associated with this movie.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<form action="{{ path_for('admin.movies.delete', {id: movie.id}) }}" method="post" class="d-inline">
<input type="hidden" name="_METHOD" value="DELETE">
<button type="submit" class="btn btn-danger">Delete Movie</button>
</form>
</div>
</div>
</div>
</div>
{% endif %}
{% endblock %}
{% block scripts %}
<script>
// Preview poster when URL changes
document.getElementById('poster_url').addEventListener('input', function() {
const preview = document.getElementById('posterPreview');
const url = this.value.trim();
if (url) {
preview.innerHTML = `<img src="${url}" alt="Poster Preview" class="img-fluid" style="max-height: 300px;">`;
} else {
preview.innerHTML = '<div class="text-muted">No poster available</div>';
}
});
// Handle form submission
document.querySelector('form').addEventListener('submit', function(e) {
const title = document.getElementById('title').value.trim();
if (!title) {
e.preventDefault();
alert('Title is required');
return false;
}
return true;
});
</script>
{% endblock %}

View File

@@ -0,0 +1,253 @@
{% extends 'admin/layout.twig' %}
{% block title %}Manage Movies - Admin Panel - MediaLib{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1 class="h3 mb-0">Manage Movies</h1>
<p class="text-muted mb-0">View and manage your movie library</p>
</div>
<a href="{{ path_for('admin.movies.create') }}" class="btn btn-primary">
<i class="bi bi-plus-circle me-2"></i>Add New Movie
</a>
</div>
<div class="card">
<div class="card-body">
{% if flash.success %}
<div class="alert alert-success">
{{ flash.success }}
</div>
{% endif %}
<!-- Search and Filter Form -->
<form method="get" class="mb-4">
<div class="row g-3">
<div class="col-md-4">
<div class="input-group">
<input type="text"
class="form-control"
name="search"
placeholder="Search movies..."
value="{{ filters.search }}">
<button class="btn btn-primary" type="submit">
<i class="bi bi-search"></i>
</button>
</div>
</div>
<div class="col-md-2">
<select name="genre" class="form-select">
<option value="">All Genres</option>
{% for genre in genres %}
<option value="{{ genre }}" {{ filters.genre == genre ? 'selected' : '' }}>
{{ genre }}
</option>
{% endfor %}
</select>
</div>
<div class="col-md-2">
<select name="director" class="form-select">
<option value="">All Directors</option>
{% for director in directors %}
<option value="{{ director }}" {{ filters.director == director ? 'selected' : '' }}>
{{ director }}
</option>
{% endfor %}
</select>
</div>
<div class="col-md-2">
<select name="sort" class="form-select">
<option value="title_asc" {{ filters.sort == 'title_asc' ? 'selected' : '' }}>Title (A-Z)</option>
<option value="title_desc" {{ filters.sort == 'title_desc' ? 'selected' : '' }}>Title (Z-A)</option>
<option value="release_desc" {{ filters.sort == 'release_desc' ? 'selected' : '' }}>Newest First</option>
<option value="release_asc" {{ filters.sort == 'release_asc' ? 'selected' : '' }}>Oldest First</option>
<option value="rating_desc" {{ filters.sort == 'rating_desc' ? 'selected' : '' }}>Highest Rated</option>
<option value="rating_asc" {{ filters.sort == 'rating_asc' ? 'selected' : '' }}>Lowest Rated</option>
</select>
</div>
<div class="col-md-2">
<div class="btn-group w-100">
<button type="submit" class="btn btn-primary">
<i class="bi bi-funnel me-1"></i> Filter
</button>
<a href="{{ path_for('admin.movies') }}" class="btn btn-outline-secondary">
<i class="bi bi-x-lg"></i>
</a>
</div>
</div>
</div>
</form>
<!-- Results Summary -->
<div class="d-flex justify-content-between align-items-center mb-3">
<div class="text-muted">
Showing {{ pagination.from }} to {{ pagination.to }} of {{ pagination.total_items }} movies
</div>
<div class="btn-group">
<button type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="dropdown" aria-expanded="false">
<i class="bi bi-list-ul me-1"></i> View
</button>
<ul class="dropdown-menu dropdown-menu-end">
<li><a class="dropdown-item" href="#"><i class="bi bi-grid-3x3-gap-fill me-2"></i>Grid</a></li>
<li><a class="dropdown-item active" href="#"><i class="bi bi-list-ul me-2"></i>List</a></li>
</ul>
</div>
</div>
<div class="table-responsive">
<table class="table table-hover align-middle">
<thead class="table-light">
<tr>
<th style="width: 60px;">Poster</th>
<th>Title</th>
<th>Year</th>
<th>Rating</th>
<th>Runtime</th>
<th class="text-end">Actions</th>
</tr>
</thead>
<tbody>
{% for movie in movies %}
<tr>
<td>
{% if movie.poster_path %}
<img src="{{ movie.poster_path }}" alt="{{ movie.title }}" style="width: 50px; height: 75px; object-fit: cover;">
{% else %}
<div class="bg-light d-flex align-items-center justify-content-center" style="width: 50px; height: 75px;">
<i class="bi bi-film text-muted"></i>
</div>
{% endif %}
</td>
<td>{{ movie.title }}</td>
<td>{{ movie.release_date|date('Y') }}</td>
<td>
{% if movie.vote_average %}
<span class="badge bg-primary">{{ movie.vote_average|number_format(1) }}/10</span>
{% else %}
<span class="text-muted">N/A</span>
{% endif %}
</td>
<td>{{ movie.runtime ? movie.runtime ~ ' min' : 'N/A' }}</td>
<td>
<div class="btn-group btn-group-sm">
<a href="{{ path_for('admin.movies.edit', {id: movie.id}) }}" class="btn btn-outline-primary">
<i class="bi bi-pencil"></i>
</a>
<form action="{{ path_for('admin.movies.delete', {id: movie.id}) }}" method="post" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this movie?');">
<input type="hidden" name="_METHOD" value="DELETE">
<button type="submit" class="btn btn-outline-danger">
<i class="bi bi-trash"></i>
</button>
</form>
</div>
</td>
</tr>
{% else %}
<tr>
<td colspan="6" class="text-center py-4">
<div class="text-muted">No movies found. <a href="{{ path_for('admin.movies.create') }}">Add your first movie</a></div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- Pagination -->
{% if pagination.total > 1 %}
<nav class="mt-4">
<ul class="pagination justify-content-center">
{% if pagination.current > 1 %}
<li class="page-item">
<a class="page-link"
href="{{ path_for('admin.movies', {}, {
'page': pagination.current - 1,
'search': filters.search,
'genre': filters.genre,
'director': filters.director,
'sort': filters.sort
}) }}"
aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
{% endif %}
{% set start = max(1, pagination.current - 2) %}
{% set end = min(pagination.total, pagination.current + 2) %}
{% if start > 1 %}
<li class="page-item">
<a class="page-link"
href="{{ path_for('admin.movies', {}, {
'page': 1,
'search': filters.search,
'genre': filters.genre,
'director': filters.director,
'sort': filters.sort
}) }}">1</a>
</li>
{% if start > 2 %}
<li class="page-item disabled">
<span class="page-link">...</span>
</li>
{% endif %}
{% endif %}
{% for i in start..end %}
<li class="page-item {% if i == pagination.current %}active{% endif %}">
<a class="page-link"
href="{{ path_for('admin.movies', {}, {
'page': i,
'search': filters.search,
'genre': filters.genre,
'director': filters.director,
'sort': filters.sort
}) }}">
{{ i }}
</a>
</li>
{% endfor %}
{% if end < pagination.total %}
{% if end < pagination.total - 1 %}
<li class="page-item disabled">
<span class="page-link">...</span>
</li>
{% endif %}
<li class="page-item">
<a class="page-link"
href="{{ path_for('admin.movies', {}, {
'page': pagination.total,
'search': filters.search,
'genre': filters.genre,
'director': filters.director,
'sort': filters.sort
}) }}">
{{ pagination.total }}
</a>
</li>
{% endif %}
{% if pagination.current < pagination.total %}
<li class="page-item">
<a class="page-link"
href="{{ path_for('admin.movies', {}, {
'page': pagination.current + 1,
'search': filters.search,
'genre': filters.genre,
'director': filters.director,
'sort': filters.sort
}) }}"
aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
</div>
</div>
{% endblock %}

View File

@@ -0,0 +1,222 @@
{% extends 'admin/layout.twig' %}
{% block title %}{{ title }} - Admin Panel - MediaLib{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1 class="h3 mb-0">{{ title }}</h1>
<p class="text-muted mb-0">{{ show ? 'Edit TV show details' : 'Add a new TV show to your library' }}</p>
</div>
<a href="{{ path_for('admin.shows.index') }}" class="btn btn-outline-secondary">
<i class="bi bi-arrow-left me-2"></i>Back to Shows
</a>
</div>
<div class="row">
<div class="col-lg-8">
<div class="card mb-4">
<div class="card-body">
{% if flash.getMessage('success') %}
<div class="alert alert-success">
{{ flash.getMessage('success') | first }}
</div>
{% endif %}
<form method="post" enctype="multipart/form-data">
<div class="mb-3">
<label for="title" class="form-label">Title *</label>
<input type="text" class="form-control" id="title" name="title" required
value="{{ old.title ?? show.title ?? '' }}">
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="first_air_date" class="form-label">First Air Date</label>
<input type="date" class="form-control" id="first_air_date" name="first_air_date"
value="{{ old.first_air_date ?? (show.first_air_date ? show.first_air_date|date('Y-m-d') : '') }}">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="status" class="form-label">Status</label>
<select class="form-select" id="status" name="status">
<option value="Returning Series" {{ (old.status ?? show.status ?? '') == 'Returning Series' ? 'selected' : '' }}>Returning Series</option>
<option value="Ended" {{ (old.status ?? show.status ?? '') == 'Ended' ? 'selected' : '' }}>Ended</option>
<option value="In Production" {{ (old.status ?? show.status ?? '') == 'In Production' ? 'selected' : '' }}>In Production</option>
<option value="Planned" {{ (old.status ?? show.status ?? '') == 'Planned' ? 'selected' : '' }}>Planned</option>
<option value="Canceled" {{ (old.status ?? show.status ?? '') == 'Canceled' ? 'selected' : '' }}>Canceled</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="number_of_seasons" class="form-label">Number of Seasons</label>
<input type="number" class="form-control" id="number_of_seasons" name="number_of_seasons" min="0"
value="{{ old.number_of_seasons ?? show.number_of_seasons ?? '0' }}">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="number_of_episodes" class="form-label">Number of Episodes</label>
<input type="number" class="form-control" id="number_of_episodes" name="number_of_episodes" min="0"
value="{{ old.number_of_episodes ?? show.number_of_episodes ?? '0' }}">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label for="network" class="form-label">Network</label>
<input type="text" class="form-control" id="network" name="network"
value="{{ old.network ?? show.network ?? '' }}">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="vote_average" class="form-label">Rating (0-10)</label>
<input type="number" class="form-control" id="vote_average" name="vote_average"
min="0" max="10" step="0.1"
value="{{ old.vote_average ?? show.vote_average ?? '' }}">
</div>
</div>
</div>
<div class="mb-3">
<label for="genres" class="form-label">Genres (comma-separated)</label>
<input type="text" class="form-control" id="genres" name="genres"
value="{{ old.genres ?? (show.genres ? show.genres|join(', ') : '') }}">
<div class="form-text">Example: Drama, Crime, Mystery</div>
</div>
<div class="mb-3">
<label for="overview" class="form-label">Overview</label>
<textarea class="form-control" id="overview" name="overview" rows="4">{{ old.overview ?? show.overview ?? '' }}</textarea>
</div>
<div class="mb-3">
<label for="poster_url" class="form-label">Poster URL</label>
<input type="text" class="form-control" id="poster_url" name="poster_url"
value="{{ old.poster_url ?? show.poster_url ?? '' }}">
</div>
<div class="mb-3">
<label for="backdrop_url" class="form-label">Backdrop URL</label>
<input type="text" class="form-control" id="backdrop_url" name="backdrop_url"
value="{{ old.backdrop_url ?? show.backdrop_url ?? '' }}">
</div>
<div class="d-flex justify-content-between">
<button type="submit" class="btn btn-primary">
<i class="bi bi-save me-2"></i>Save Changes
</button>
{% if show %}
<button type="button" class="btn btn-outline-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
<i class="bi bi-trash me-2"></i>Delete Show
</button>
{% endif %}
</div>
</form>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card mb-4">
<div class="card-header">
<h5 class="mb-0">Poster Preview</h5>
</div>
<div class="card-body text-center">
<div id="posterPreview" class="mb-3" style="min-height: 300px; display: flex; align-items: center; justify-content: center; background-color: #f8f9fa;">
{% if show and show.poster_url %}
<img src="{{ show.poster_url }}" alt="Poster" class="img-fluid" style="max-height: 300px;">
{% else %}
<div class="text-muted">No poster available</div>
{% endif %}
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h5 class="mb-0">Metadata</h5>
</div>
<div class="card-body">
<div class="mb-2">
<span class="text-muted">Created:</span>
<span class="float-end">{{ show ? show.created_at|date('Y-m-d H:i') : 'New' }}</span>
</div>
<div class="mb-2">
<span class="text-muted">Last Updated:</span>
<span class="float-end">{{ show ? show.updated_at|date('Y-m-d H:i') : 'N/A' }}</span>
</div>
{% if show and show.tmdb_id %}
<div class="mt-3">
<a href="https://www.themoviedb.org/tv/{{ show.tmdb_id }}" target="_blank" class="btn btn-sm btn-outline-primary w-100">
<i class="bi bi-box-arrow-up-right me-1"></i> View on TMDb
</a>
</div>
{% endif %}
</div>
</div>
</div>
</div>
<!-- Delete Confirmation Modal -->
{% if show %}
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel">Confirm Deletion</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete "{{ show.title }}"? This action cannot be undone.</p>
<p class="text-danger"><strong>Warning:</strong> This will remove all data associated with this show, including all seasons and episodes.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<form action="{{ path_for('admin.shows.delete', {id: show.id}) }}" method="post" class="d-inline">
<input type="hidden" name="_METHOD" value="DELETE">
<button type="submit" class="btn btn-danger">Delete Show</button>
</form>
</div>
</div>
</div>
</div>
{% endif %}
{% endblock %}
{% block scripts %}
<script>
// Preview poster when URL changes
document.getElementById('poster_url').addEventListener('input', function() {
const preview = document.getElementById('posterPreview');
const url = this.value.trim();
if (url) {
preview.innerHTML = `<img src="${url}" alt="Poster Preview" class="img-fluid" style="max-height: 300px;">`;
} else {
preview.innerHTML = '<div class="text-muted">No poster available</div>';
}
});
// Handle form submission
document.querySelector('form').addEventListener('submit', function(e) {
const title = document.getElementById('title').value.trim();
if (!title) {
e.preventDefault();
alert('Title is required');
return false;
}
return true;
});
</script>
{% endblock %}

View File

@@ -0,0 +1,202 @@
{% extends 'admin/layout.twig' %}
{% block title %}Manage TV Shows - Admin Panel - MediaLib{% endblock %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<h1 class="h3 mb-0">Manage TV Shows</h1>
<p class="text-muted mb-0">View and manage your TV show library</p>
</div>
<a href="{{ path_for('admin.shows.create') }}" class="btn btn-primary">
<i class="bi bi-plus-circle me-2"></i>Add New Show
</a>
</div>
{# Search and Filters #}
<div class="card mb-4">
<div class="card-body">
<form method="get" action="{{ path_for('admin.shows') }}" class="mb-0">
<div class="row g-3">
<div class="col-md-4">
<div class="input-group">
<span class="input-group-text"><i class="bi bi-search"></i></span>
<input type="text" name="search" class="form-control" placeholder="Search shows..." value="{{ filters.search }}">
</div>
</div>
<div class="col-md-2">
<select name="genre" class="form-select">
<option value="">All Genres</option>
{% for genre in genres %}
<option value="{{ genre }}" {{ filters.genre == genre ? 'selected' : '' }}>{{ genre }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-2">
<select name="status" class="form-select">
<option value="">All Statuses</option>
{% for status in statuses %}
<option value="{{ status }}" {{ filters.status == status ? 'selected' : '' }}>{{ status }}</option>
{% endfor %}
</select>
</div>
<div class="col-md-2">
<select name="sort" class="form-select">
<option value="title_asc" {{ filters.sort == 'title_asc' ? 'selected' : '' }}>Title (A-Z)</option>
<option value="title_desc" {{ filters.sort == 'title_desc' ? 'selected' : '' }}>Title (Z-A)</option>
<option value="rating_desc" {{ filters.sort == 'rating_desc' ? 'selected' : '' }}>Highest Rated</option>
<option value="rating_asc" {{ filters.sort == 'rating_asc' ? 'selected' : '' }}>Lowest Rated</option>
<option value="newest" {{ filters.sort == 'newest' ? 'selected' : '' }}>Newest First</option>
<option value="oldest" {{ filters.sort == 'oldest' ? 'selected' : '' }}>Oldest First</option>
</select>
</div>
<div class="col-md-2">
<div class="d-flex">
<button type="submit" class="btn btn-primary me-2">
<i class="bi bi-funnel me-1"></i> Apply
</button>
<a href="{{ path_for('admin.shows') }}" class="btn btn-outline-secondary">
<i class="bi bi-arrow-counterclockwise"></i>
</a>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="card">
<div class="card-body">
{% if flash.getMessage('success') %}
<div class="alert alert-success">
{{ flash.getMessage('success') | first }}
</div>
{% endif %}
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Poster</th>
<th>Title</th>
<th>First Aired</th>
<th>Seasons</th>
<th>Rating</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for show in shows %}
<tr>
<td>
{% if show.poster_path %}
<img src="{{ show.poster_path }}" alt="{{ show.title }}" style="width: 50px; height: 75px; object-fit: cover;">
{% else %}
<div class="bg-light d-flex align-items-center justify-content-center" style="width: 50px; height: 75px;">
<i class="bi bi-tv text-muted"></i>
</div>
{% endif %}
</td>
<td>
<div class="fw-medium">{{ show.title }}</div>
<small class="text-muted">{{ show.network ? show.network : 'N/A' }}</small>
</td>
<td>{{ show.first_air_date ? show.first_air_date|date('Y') : 'N/A' }}</td>
<td>{{ show.number_of_seasons ?? '0' }}</td>
<td>
{% if show.vote_average %}
<span class="badge bg-primary">{{ show.vote_average|number_format(1) }}/10</span>
{% else %}
<span class="text-muted">N/A</span>
{% endif %}
</td>
<td>
{% if show.status == 'Returning Series' %}
<span class="badge bg-success">Ongoing</span>
{% elseif show.status == 'Ended' %}
<span class="badge bg-secondary">Ended</span>
{% else %}
<span class="badge bg-info">{{ show.status ?? 'N/A' }}</span>
{% endif %}
</td>
<td>
<div class="btn-group btn-group-sm">
<a href="{{ path_for('admin.shows.edit', {id: show.id}) }}" class="btn btn-outline-primary">
<i class="bi bi-pencil"></i>
</a>
<form action="{{ path_for('admin.shows.delete', {id: show.id}) }}" method="post" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this show?');">
<input type="hidden" name="_METHOD" value="DELETE">
<button type="submit" class="btn btn-outline-danger">
<i class="bi bi-trash"></i>
</button>
</form>
</div>
</td>
</tr>
{% else %}
<tr>
<td colspan="7" class="text-center py-4">
<div class="text-muted">No TV shows found. <a href="{{ path_for('admin.shows.create') }}">Add your first show</a></div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% if pagination.total > 1 %}
<div class="d-flex justify-content-between align-items-center mt-4">
<div class="text-muted">
Showing {{ pagination.from }} to {{ pagination.to }} of {{ pagination.total_items }} shows
</div>
<nav>
<ul class="pagination mb-0">
{% if pagination.current > 1 %}
<li class="page-item">
<a class="page-link" href="{{ path_for('admin.shows', {'page': pagination.current - 1, 'search': filters.search, 'genre': filters.genre, 'status': filters.status, 'sort': filters.sort}) }}" aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
</a>
</li>
{% else %}
<li class="page-item disabled">
<span class="page-link" aria-hidden="true">&laquo;</span>
</li>
{% endif %}
{% for i in 1..pagination.total %}
{% if i == pagination.current %}
<li class="page-item active" aria-current="page">
<span class="page-link">{{ i }}</span>
</li>
{% else %}
{% if (i >= pagination.current - 2 and i <= pagination.current + 2) or i == 1 or i == pagination.total %}
<li class="page-item">
<a class="page-link" href="{{ path_for('admin.shows', {'page': i, 'search': filters.search, 'genre': filters.genre, 'status': filters.status, 'sort': filters.sort}) }}">{{ i }}</a>
</li>
{% elseif (i == pagination.current - 3 or i == pagination.current + 3) %}
<li class="page-item disabled">
<span class="page-link">...</span>
</li>
{% endif %}
{% endif %}
{% endfor %}
{% if pagination.current < pagination.total %}
<li class="page-item">
<a class="page-link" href="{{ path_for('admin.shows', {'page': pagination.current + 1, 'search': filters.search, 'genre': filters.genre, 'status': filters.status, 'sort': filters.sort}) }}" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
{% else %}
<li class="page-item disabled">
<span class="page-link" aria-hidden="true">&raquo;</span>
</li>
{% endif %}
</ul>
</nav>
</div>
{% endif %}
</div>
</div>
{% endblock %}

View File

@@ -88,6 +88,7 @@
<form method="GET" class="d-flex gap-2">
<input type="hidden" name="view" value="{{ view_mode }}">
<input type="hidden" name="per_page" value="{{ pagination.per_page }}">
<input type="hidden" name="sort" value="{{ sort }}">
{% for genre in filters.genres %}
<input type="hidden" name="genres[]" value="{{ genre }}">
{% endfor %}
@@ -111,11 +112,47 @@
</button>
</form>
<!-- Sort dropdown -->
<div class="dropdown">
<button class="btn btn-outline-secondary dropdown-toggle d-flex align-items-center" type="button" id="sortDropdown" data-bs-toggle="dropdown" aria-expanded="false">
<i class="bi bi-sort-down me-1"></i>
<span class="d-none d-sm-inline">Sort</span>
</button>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="sortDropdown">
{% for key, label in sort_options %}
<li>
{% set queryParams = {
'sort': key,
'view': view_mode,
'per_page': pagination.per_page != 24 ? pagination.per_page : null,
'search': search,
'genres': filters.genres,
'directors': filters.directors
} %}
<a class="dropdown-item d-flex justify-content-between align-items-center {{ sort == key ? 'active' : '' }}"
href="?{{ queryParams|filter((v, k) => v != '' and v is not empty)|url_encode }}">
{{ label }}
{% if sort == key %}
<i class="bi bi-check2 ms-2"></i>
{% endif %}
</a>
</li>
{% endfor %}
</ul>
</div>
<!-- View mode switcher -->
<div class="btn-group" role="group">
{% for mode in view_modes %}
<a
href="?view={{ mode }}{% if search %}&search={{ search }}{% endif %}{% if pagination.per_page != 24 %}&per_page={{ pagination.per_page }}{% endif %}{% for genre in filters.genres %}&genres[]={{ genre }}{% endfor %}{% for director in filters.directors %}&directors[]={{ director }}{% endfor %}"
href="?{{ {
'view': mode,
'sort': sort,
'per_page': pagination.per_page != 24 ? pagination.per_page : null,
'search': search,
'genres': filters.genres,
'directors': filters.directors
}|filter((v, k) => v != '' and v is not empty)|url_encode }}"
class="btn btn-outline-secondary {{ view_mode == mode ? 'active' : '' }}"
>
{% if mode == 'grid' %}
@@ -141,6 +178,10 @@
</div>
{% endif %}
<div class="text-muted small">
Sorted by: {{ sort_options[sort] }}
</div>
{% if movies is empty %}
<div class="text-center py-5">
<svg class="mx-auto text-muted mb-3" width="48" height="48" fill="none" viewBox="0 0 24 24" stroke="currentColor">

View File

@@ -192,7 +192,7 @@
<a href="{{ path_for('actors.show', {'id': actor.id}) }}" class="text-decoration-none">
<div class="d-flex flex-column align-items-center" style="width: 80px;">
{% if actor.thumbnail_path %}
<img src="/images/{{ actor.thumbnail_path }}" alt="{{ actor.name }}" class="rounded-circle mb-2" style="width: 50px; height: 50px; object-fit: cover;">
<img src="{{ actor.thumbnail_path }}" alt="{{ actor.name }}" class="rounded-circle mb-2" style="width: 50px; height: 50px; object-fit: cover;">
{% else %}
<div class="rounded-circle bg-light d-flex align-items-center justify-content-center mb-2" style="width: 50px; height: 50px;">
<svg class="text-muted" width="24" height="24" fill="none" viewBox="0 0 24 24" stroke="currentColor">

View File

@@ -111,26 +111,59 @@
</button>
</form>
<!-- View mode switcher -->
<div class="btn-group" role="group">
{% for mode in view_modes %}
<a
href="?view={{ mode }}{% if search %}&search={{ search }}{% endif %}{% if pagination.per_page != 24 %}&per_page={{ pagination.per_page }}{% endif %}{% for genre in filters.genres %}&genres[]={{ genre }}{% endfor %}{% for platform in filters.platforms %}&platforms[]={{ platform }}{% endfor %}"
class="btn btn-outline-secondary {{ view_mode == mode ? 'active' : '' }}"
>
{% if mode == 'grid' %}
<svg class="me-1" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"/>
</svg>
{% endif %}
{% if mode == 'list' %}
<svg class="me-1" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"/>
</svg>
{% endif %}
{{ mode|title }}
</a>
{% endfor %}
<div class="d-flex gap-2">
<!-- Sort dropdown -->
<div class="dropdown">
<button class="btn btn-outline-secondary dropdown-toggle" type="button" id="sortDropdown" data-bs-toggle="dropdown" aria-expanded="false">
<svg class="me-1" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12"/>
</svg>
<span class="d-none d-sm-inline">Sort</span>
</button>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="sortDropdown">
{% for key, label in sort_options %}
<li>
<a class="dropdown-item d-flex justify-content-between align-items-center {{ sort == key ? 'active' : '' }}"
href="?sort={{ key }}&view={{ view_mode }}{% if search %}&search={{ search }}{% endif %}{% if pagination.per_page != 24 %}&per_page={{ pagination.per_page }}{% endif %}{% for genre in filters.genres %}&genres[]={{ genre }}{% endfor %}{% for platform in filters.platforms %}&platforms[]={{ platform }}{% endfor %}">
{{ label }}
{% if sort == key %}
<svg width="16" height="16" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"/>
</svg>
{% endif %}
</a>
</li>
{% endfor %}
</ul>
</div>
<!-- View mode switcher -->
<div class="btn-group" role="group">
{% for mode in view_modes %}
<a
href="?view={{ mode }}&sort={{ sort }}{% if search %}&search={{ search }}{% endif %}{% if pagination.per_page != 24 %}&per_page={{ pagination.per_page }}{% endif %}{% for genre in filters.genres %}&genres[]={{ genre }}{% endfor %}{% for platform in filters.platforms %}&platforms[]={{ platform }}{% endfor %}"
class="btn btn-outline-secondary {{ view_mode == mode ? 'active' : '' }}"
title="{{ mode|title }} View"
>
{% if mode == 'grid' %}
<svg width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"/>
</svg>
{% endif %}
{% if mode == 'list' %}
<svg width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"/>
</svg>
{% endif %}
{% if mode == 'covers' %}
<svg width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
</svg>
{% endif %}
<span class="d-none d-sm-inline ms-1">{{ mode|title }}</span>
</a>
{% endfor %}
</div>
</div>
</div>
</div>

View File

@@ -1,415 +1,499 @@
{% extends "layouts/app.twig" %}
{% block content %}
<div class="px-4 py-6 sm:px-0">
<div class="container py-4">
<!-- Game Header -->
<div class="bg-white shadow rounded-lg mb-6">
<div class="px-6 py-4 border-b border-gray-200">
<div class="flex items-center justify-between">
<div class="flex items-center">
<div class="card mb-4 shadow-sm">
<div class="card-header bg-white">
<div class="d-flex justify-content-between align-items-center">
<div class="d-flex align-items-center">
{% if main_game.image_url %}
<img class="h-16 w-16 rounded-lg object-cover mr-4" src="{{ main_game.image_url }}" alt="{{ main_game.title }}">
<img class="me-3 rounded" src="{{ main_game.image_url }}" alt="{{ main_game.title }}" style="width: 64px; height: 64px; object-fit: cover;">
{% else %}
<div class="h-16 w-16 rounded-lg bg-gray-200 flex items-center justify-center mr-4">
<svg class="h-8 w-8 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.828 14.828a4 4 0 01-5.656 0M9 10h1m4 0h1m-7 8h12a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"/>
</svg>
<div class="bg-light rounded d-flex align-items-center justify-content-center me-3" style="width: 64px; height: 64px;">
<i class="bi bi-controller text-muted" style="font-size: 1.5rem;"></i>
</div>
{% endif %}
<div>
<h1 class="text-2xl font-bold text-gray-900">{{ main_game.title }}</h1>
<div class="flex items-center space-x-4 mt-1">
<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
<h1 class="h4 mb-1">{{ main_game.title }}</h1>
<div class="d-flex align-items-center gap-3">
<span class="badge bg-primary">
{{ platform_versions|length }} platform{{ platform_versions|length > 1 ? 's' : '' }}
</span>
{% if main_game.genre %}
<span class="text-sm text-gray-500">{{ main_game.genre }}</span>
<span class="text-muted small">{{ main_game.genre }}</span>
{% endif %}
</div>
</div>
</div>
<a href="{{ path_for('games.index') }}" class="text-indigo-600 hover:text-indigo-900 text-sm font-medium">
Back to Games
<a href="{{ path_for('games.index') }}" class="btn btn-outline-primary btn-sm">
<i class="bi bi-arrow-left me-1"></i> Back to Games
</a>
</div>
</div>
</div>
<!-- Platform Tabs -->
<div class="bg-white shadow rounded-lg">
<div class="border-b border-gray-200">
<nav class="-mb-px flex space-x-8 px-6" aria-label="Tabs">
<!-- Platform Tabs -->
<div class="card-body p-0">
<ul class="nav nav-tabs px-3" id="platformTabs" role="tablist">
{% for version in platform_versions %}
<button
class="platform-tab whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm {{ loop.first ? 'border-indigo-500 text-indigo-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}"
<li class="nav-item" role="presentation">
<button
class="nav-link {{ loop.first ? 'active' : 'text-muted' }} platform-tab"
id="tab-{{ version.platform|lower }}-{{ version.source_id }}"
data-bs-toggle="tab"
data-bs-target="#content-{{ version.platform|lower }}-{{ version.source_id }}"
type="button"
role="tab"
data-platform="{{ version.platform }}"
data-source="{{ version.source_id }}"
>
{{ version.platform }}
{% if version.source_name %}
<small class="text-muted">({{ version.source_name }})</small>
{% endif %}
</button>
</li>
{% endfor %}
</ul>
<!-- Tab Content -->
<div class="tab-content p-4" id="platformTabsContent">
{% for version in platform_versions %}
<div
class="tab-pane fade {{ loop.first ? 'show active' }}"
id="content-{{ version.platform|lower }}-{{ version.source_id }}"
role="tabpanel"
data-platform="{{ version.platform }}"
data-source="{{ version.source_id }}"
>
{{ version.platform }}
{% if version.source_name %}
<span class="ml-1 text-xs text-gray-400">({{ version.source_name }})</span>
{% endif %}
</button>
{% endfor %}
</nav>
</div>
<div class="row g-4">
<!-- Game Info -->
<div class="col-md-6 pb-3">
<div class="card h-100">
<div class="card-header">
<h5 class="card-title mb-0">Game Information</h5>
</div>
<div class="card-body">
<dl class="row mb-0">
{% if version.developer %}
<dt class="col-sm-5 text-muted small">Developer</dt>
<dd class="col-sm-7">{{ version.developer }}</dd>
{% endif %}
<!-- Platform Content -->
{% for version in platform_versions %}
<div class="platform-content {{ loop.first ? '' : 'hidden' }}" data-platform="{{ version.platform }}" data-source="{{ version.source_id }}">
<div class="px-6 py-6">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<!-- Game Info -->
<div>
<h3 class="text-lg font-medium text-gray-900 mb-4">Game Information</h3>
<dl class="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">
{% if version.developer %}
<div>
<dt class="text-sm font-medium text-gray-500">Developer</dt>
<dd class="mt-1 text-sm text-gray-900">{{ version.developer }}</dd>
</div>
{% endif %}
{% if version.publisher %}
<div>
<dt class="text-sm font-medium text-gray-500">Publisher</dt>
<dd class="mt-1 text-sm text-gray-900">{{ version.publisher }}</dd>
</div>
{% endif %}
{% if version.release_date %}
<div>
<dt class="text-sm font-medium text-gray-500">Release Date</dt>
<dd class="mt-1 text-sm text-gray-900">{{ version.release_date|date('M j, Y') }}</dd>
</div>
{% endif %}
<div>
<dt class="text-sm font-medium text-gray-500">Playtime</dt>
<dd class="mt-1 text-sm text-gray-900">{{ version.playtime_minutes|format_duration }}</dd>
</div>
{% if version.rating %}
<div>
<dt class="text-sm font-medium text-gray-500">Rating</dt>
<dd class="mt-1 text-sm text-gray-900">{{ version.rating }}/10</dd>
</div>
{% endif %}
{% if version.completion_percentage > 0 %}
<div>
<dt class="text-sm font-medium text-gray-500">Completion</dt>
<dd class="mt-1 text-sm text-gray-900">{{ version.completion_percentage }}%</dd>
</div>
{% endif %}
</dl>
</div>
{% if version.publisher %}
<dt class="col-sm-5 text-muted small">Publisher</dt>
<dd class="col-sm-7">{{ version.publisher }}</dd>
{% endif %}
<!-- Platform Stats -->
<div>
<h3 class="text-lg font-medium text-gray-900 mb-4">Platform Statistics</h3>
<dl class="grid grid-cols-1 gap-x-4 gap-y-4">
<div>
<dt class="text-sm font-medium text-gray-500">Source</dt>
<dd class="mt-1 text-sm text-gray-900">{{ version.source_name }}</dd>
</div>
{% if version.last_played_at %}
<div>
<dt class="text-sm font-medium text-gray-500">Last Played</dt>
<dd class="mt-1 text-sm text-gray-900">{{ version.last_played_at|date('M j, Y') }}</dd>
</div>
{% endif %}
{% if version.is_installed %}
<div>
<dt class="text-sm font-medium text-gray-500">Status</dt>
<dd class="mt-1">
<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
Installed
</span>
</dd>
</div>
{% endif %}
{% if version.is_favorite %}
<div>
<dt class="text-sm font-medium text-gray-500">Favorite</dt>
<dd class="mt-1">
<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">
Yes
</span>
</dd>
</div>
{% endif %}
</dl>
{% if version.release_date %}
<dt class="col-sm-5 text-muted small">Release Date</dt>
<dd class="col-sm-7">{{ version.release_date|date('M j, Y') }}</dd>
{% endif %}
<!-- Platform-specific metadata -->
{% set metadata = version.metadata|json_decode %}
{% if metadata %}
<div class="mt-6">
<h4 class="text-sm font-medium text-gray-900 mb-2">Platform Details</h4>
<div class="bg-gray-50 rounded-md p-3">
<dl class="grid grid-cols-1 gap-x-4 gap-y-2 text-sm">
{% if metadata.appid %}
<div>
<dt class="font-medium text-gray-500">App ID</dt>
<dd class="text-gray-900">{{ metadata.appid }}</dd>
</div>
{% endif %}
{% if metadata.playtime_windows or metadata.playtime_mac or metadata.playtime_linux %}
<div>
<dt class="font-medium text-gray-500">Platform Playtime</dt>
<dd class="text-gray-900">
{% if metadata.playtime_windows %}<span>Windows: {{ metadata.playtime_windows|format_duration }}</span>{% endif %}
{% if metadata.playtime_mac %}<span class="ml-2">Mac: {{ metadata.playtime_mac|format_duration }}</span>{% endif %}
{% if metadata.playtime_linux %}<span class="ml-2">Linux: {{ metadata.playtime_linux|format_duration }}</span>{% endif %}
<dt class="col-sm-5 text-muted small">Playtime</dt>
<dd class="col-sm-7">{{ version.playtime_minutes|format_duration }}</dd>
{% if version.rating %}
<dt class="col-sm-5 text-muted small">Rating</dt>
<dd class="col-sm-7">
<div class="d-flex align-items-center">
<div class="progress flex-grow-1 me-2" style="height: 6px;">
<div class="progress-bar bg-warning" role="progressbar" style="width: {{ version.rating * 10 }}%" aria-valuenow="{{ version.rating * 10 }}" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<span class="small">{{ version.rating }}/10</span>
</div>
</dd>
</div>
{% endif %}
{% if version.completion_percentage > 0 %}
<dt class="col-sm-5 text-muted small">Completion</dt>
<dd class="col-sm-7">
<div class="d-flex align-items-center">
<div class="progress flex-grow-1 me-2" style="height: 6px;">
<div class="progress-bar bg-success" role="progressbar" style="width: {{ version.completion_percentage }}%" aria-valuenow="{{ version.completion_percentage }}" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<span class="small">{{ version.completion_percentage }}%</span>
</div>
</dd>
{% endif %}
</dl>
</div>
</div>
</div>
<!-- Platform Stats -->
<div class="col-md-6 pb-3">
<div class="card h-100">
<div class="card-header">
<h5 class="card-title mb-0">Platform Statistics</h5>
</div>
<div class="card-body">
<dl class="row mb-0">
<dt class="col-sm-5 text-muted small">Source</dt>
<dd class="col-sm-7">{{ version.source_name }}</dd>
{% if version.last_played_at %}
<dt class="col-sm-5 text-muted small">Last Played</dt>
<dd class="col-sm-7">
<span data-bs-toggle="tooltip" data-bs-placement="top" title="{{ version.last_played_at|date('F j, Y H:i') }}">
{{ version.last_played_at|date('M j, Y') }}
</span>
</dd>
{% endif %}
{% if version.is_installed %}
<dt class="col-sm-5 text-muted small">Status</dt>
<dd class="col-sm-7">
<span class="badge bg-success">
<i class="bi bi-check-circle me-1"></i> Installed
</span>
</dd>
{% endif %}
{% if version.is_favorite %}
<dt class="col-sm-5 text-muted small">Favorite</dt>
<dd class="col-sm-7">
<span class="badge bg-danger">
<i class="bi bi-heart-fill me-1"></i> Yes
</span>
</dd>
{% endif %}
</dl>
<!-- Platform-specific metadata -->
{% set metadata = version.metadata|json_decode %}
{% if metadata %}
<hr class="my-3">
<h6 class="fw-bold mb-2">Platform Details</h6>
<dl class="row mb-0">
{% if metadata.appid %}
<dt class="col-sm-5 text-muted small">App ID</dt>
<dd class="col-sm-7">
<code>{{ metadata.appid }}</code>
</dd>
{% endif %}
{% if metadata.playtime_windows or metadata.playtime_mac or metadata.playtime_linux %}
<dt class="col-sm-5 text-muted small">Platform Playtime</dt>
<dd class="col-sm-7">
<div class="d-flex flex-column gap-1">
{% if metadata.playtime_windows %}
<div class="d-flex align-items-center">
<i class="bi bi-windows me-2 text-primary"></i>
<span class="small">{{ metadata.playtime_windows|format_duration }}</span>
</div>
{% endif %}
{% if metadata.playtime_mac %}
<div class="d-flex align-items-center">
<i class="bi bi-apple me-2 text-muted"></i>
<span class="small">{{ metadata.playtime_mac|format_duration }}</span>
</div>
{% endif %}
{% if metadata.playtime_linux %}
<div class="d-flex align-items-center">
<i class="bi bi-ubuntu me-2 text-warning"></i>
<span class="small">{{ metadata.playtime_linux|format_duration }}</span>
</div>
{% endif %}
</div>
</dd>
{% endif %}
</dl>
{% endif %}
</dl>
</div>
</div>
{% endif %}
</div>
</div>
{% if version.description %}
<div class="mt-6">
<h3 class="text-lg font-medium text-gray-900 mb-2">Description</h3>
<p class="text-sm text-gray-600">{{ version.description }}</p>
</div>
{% endif %}
<!-- Playnite Rich Metadata -->
{% set playniteGenres = version.genres_json|json_decode %}
{% if playniteGenres %}
<div class="mt-6">
<h3 class="text-lg font-medium text-gray-900 mb-3">Genres</h3>
<div class="flex flex-wrap gap-2">
{% for genre in playniteGenres %}
<span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-blue-100 text-blue-800">
{{ genre.Name }}
</span>
{% endfor %}
</div>
</div>
{% endif %}
{% set playniteTags = version.tags_json|json_decode %}
{% if playniteTags %}
<div class="mt-6">
<h3 class="text-lg font-medium text-gray-900 mb-3">Tags</h3>
<div class="flex flex-wrap gap-2">
{% for tag in playniteTags|slice(0, 20) %}
<span class="inline-flex items-center px-2 py-1 rounded text-sm font-medium bg-gray-100 text-gray-800">
{{ tag.Name }}
</span>
{% endfor %}
{% if playniteTags|length > 20 %}
<span class="text-sm text-gray-500">+{{ playniteTags|length - 20 }} more</span>
{% endif %}
</div>
</div>
{% endif %}
{% set playniteFeatures = version.features_json|json_decode %}
{% if playniteFeatures %}
<div class="mt-6">
<h3 class="text-lg font-medium text-gray-900 mb-3">Features</h3>
<div class="flex flex-wrap gap-2">
{% for feature in playniteFeatures %}
<span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800">
{{ feature.Name }}
</span>
{% endfor %}
</div>
</div>
{% endif %}
{% set playniteLinks = version.links_json|json_decode %}
{% if playniteLinks %}
<div class="mt-6">
<h3 class="text-lg font-medium text-gray-900 mb-3">Links</h3>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
{% for link in playniteLinks %}
<a href="{{ link.Url }}" target="_blank" rel="noopener noreferrer"
class="inline-flex items-center px-3 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 transition-colors duration-200">
<svg class="w-4 h-4 mr-2 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
<path d="M11 3a1 1 0 100 2h2.586l-6.293 6.293a1 1 0 101.414 1.414L15 6.414V9a1 1 0 102 0V4a1 1 0 00-1-1h-5z"/>
<path d="M5 5a2 2 0 00-2 2v6a2 2 0 002 2h6a2 2 0 002-2v-3a1 1 0 10-2 0v3H5V7h3a1 1 0 000-2H5z"/>
</svg>
{{ link.Name }}
</a>
{% endfor %}
</div>
</div>
{% endif %}
{% set playniteSeries = version.series_json|json_decode %}
{% if playniteSeries %}
<div class="mt-6">
<h3 class="text-lg font-medium text-gray-900 mb-3">Series</h3>
<div class="flex flex-wrap gap-2">
{% for series in playniteSeries %}
<span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-purple-100 text-purple-800">
{{ series.Name }}
</span>
{% endfor %}
</div>
</div>
{% endif %}
{% set playniteAgeRatings = version.age_ratings_json|json_decode %}
{% if playniteAgeRatings %}
<div class="mt-6">
<h3 class="text-lg font-medium text-gray-900 mb-3">Age Ratings</h3>
<div class="flex flex-wrap gap-2">
{% for ageRating in playniteAgeRatings %}
<span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-yellow-100 text-yellow-800">
{{ ageRating.Name }}
</span>
{% endfor %}
</div>
</div>
{% endif %}
<!-- Enhanced Ratings Display -->
{% if version.critic_score or version.community_score or version.user_score %}
<div class="mt-6">
<h3 class="text-lg font-medium text-gray-900 mb-3">Ratings</h3>
<div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
{% if version.critic_score %}
<div class="bg-gray-50 rounded-lg p-4">
<div class="flex items-center justify-between">
<div>
<p class="text-sm font-medium text-gray-500">Critic Score</p>
<p class="text-2xl font-bold text-gray-900">{{ version.critic_score }}%</p>
</div>
<div class="flex-shrink-0">
<svg class="w-8 h-8 text-yellow-400" fill="currentColor" viewBox="0 0 20 20">
<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
</svg>
</div>
</div>
</div>
{% endif %}
</div>
{% if version.community_score %}
<div class="bg-gray-50 rounded-lg p-4">
<div class="flex items-center justify-between">
<div>
<p class="text-sm font-medium text-gray-500">Community Score</p>
<p class="text-2xl font-bold text-gray-900">{{ version.community_score }}%</p>
</div>
<div class="flex-shrink-0">
<svg class="w-8 h-8 text-blue-400" fill="currentColor" viewBox="0 0 20 20">
<path d="M13 6a3 3 0 11-6 0 3 3 0 016 0zM18 8a2 2 0 11-4 0 2 2 0 014 0zM14 15a4 4 0 00-8 0v3h8v-3z"/>
</svg>
</div>
{% if version.description %}
<div class="col-12 pb-3">
<div class="card">
<div class="card-header">
<h5 class="card-title mb-0">Description</h5>
</div>
<div class="card-body">
<p class="card-text">{{ version.description }}</p>
</div>
</div>
{% endif %}
</div>
{% endif %}
{% if version.user_score %}
<div class="bg-gray-50 rounded-lg p-4">
<div class="flex items-center justify-between">
<div>
<p class="text-sm font-medium text-gray-500">User Score</p>
<p class="text-2xl font-bold text-gray-900">{{ version.user_score }}%</p>
</div>
<div class="flex-shrink-0">
<svg class="w-8 h-8 text-green-400" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
</svg>
<!-- Playnite Rich Metadata -->
<div class="col-12">
<div class="row g-3">
{% set playniteGenres = version.genres_json|json_decode %}
{% if playniteGenres %}
<div class="col-12">
<div class="card h-100">
<div class="card-header">
<h5 class="card-title mb-0">Genres</h5>
</div>
<div class="card-body">
<div class="d-flex flex-wrap gap-2">
{% for genre in playniteGenres %}
<span class="badge bg-primary bg-opacity-10 text-primary">
<i class="bi bi-tag me-1"></i> {{ genre.Name }}
</span>
{% endfor %}
</div>
</div>
</div>
</div>
{% endif %}
{% set playniteTags = version.tags_json|json_decode %}
{% if playniteTags %}
<div class="col-12">
<div class="card h-100">
<div class="card-header">
<h5 class="card-title mb-0">Tags</h5>
</div>
<div class="card-body">
<div class="d-flex flex-wrap gap-2">
{% for tag in playniteTags|slice(0, 20) %}
<span class="badge bg-secondary bg-opacity-10 text-secondary">
<i class="bi bi-tag-fill me-1"></i> {{ tag.Name }}
</span>
{% endfor %}
{% if playniteTags|length > 20 %}
<span class="badge bg-light text-muted">+{{ playniteTags|length - 20 }} more</span>
{% endif %}
</div>
</div>
</div>
</div>
{% endif %}
{% set playniteFeatures = version.features_json|json_decode %}
{% if playniteFeatures %}
<div class="col-12">
<div class="card h-100">
<div class="card-header">
<h5 class="card-title mb-0">Features</h5>
</div>
<div class="card-body">
<div class="d-flex flex-wrap gap-2">
{% for feature in playniteFeatures %}
<span class="badge bg-success bg-opacity-10 text-success">
<i class="bi bi-check-circle me-1"></i> {{ feature.Name }}
</span>
{% endfor %}
</div>
</div>
</div>
</div>
{% endif %}
{% set playniteLinks = version.links_json|json_decode %}
{% if playniteLinks %}
<div class="col-12">
<div class="card">
<div class="card-header">
<h5 class="card-title mb-0">Links</h5>
</div>
<div class="card-body">
<div class="row g-2">
{% for link in playniteLinks %}
<div class="col-12 col-sm-6">
<a href="{{ link.Url }}" target="_blank" rel="noopener noreferrer" class="btn btn-outline-secondary w-100 text-start">
<i class="bi bi-box-arrow-up-right me-2"></i> {{ link.Name }}
</a>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{% endif %}
{% set playniteSeries = version.series_json|json_decode %}
{% if playniteSeries %}
<div class="col-12">
<div class="card h-100">
<div class="card-header">
<h5 class="card-title mb-0">Series</h5>
</div>
<div class="card-body">
<div class="d-flex flex-wrap gap-2">
{% for series in playniteSeries %}
<span class="badge bg-purple bg-opacity-10 text-purple">
<i class="bi bi-collection me-1"></i> {{ series.Name }}
</span>
{% endfor %}
</div>
</div>
</div>
</div>
{% endif %}
{% set playniteAgeRatings = version.age_ratings_json|json_decode %}
{% if playniteAgeRatings %}
<div class="col-12">
<div class="card h-100">
<div class="card-header">
<h5 class="card-title mb-0">Age Ratings</h5>
</div>
<div class="card-body">
<div class="d-flex flex-wrap gap-2">
{% for ageRating in playniteAgeRatings %}
<span class="badge bg-warning bg-opacity-10 text-warning">
<i class="bi bi-exclamation-triangle me-1"></i> {{ ageRating.Name }}
</span>
{% endfor %}
</div>
</div>
</div>
</div>
{% endif %}
<!-- Enhanced Ratings Display -->
{% if version.critic_score or version.community_score or version.user_score %}
<div class="col-12">
<div class="card">
<div class="card-header">
<h5 class="card-title mb-0">Ratings</h5>
</div>
<div class="card-body">
<div class="row g-4">
{% if version.critic_score %}
<div class="col-12 col-md-4">
<div class="d-flex align-items-center p-3 bg-light rounded">
<div class="flex-shrink-0 me-3">
<i class="bi bi-star-fill text-warning" style="font-size: 1.75rem;"></i>
</div>
<div>
<div class="text-muted small">Critic Score</div>
<div class="h3 mb-0 fw-bold">{{ version.critic_score }}%</div>
</div>
</div>
</div>
{% endif %}
{% if version.community_score %}
<div class="col-12 col-md-4">
<div class="d-flex align-items-center p-3 bg-light rounded">
<div class="flex-shrink-0 me-3">
<i class="bi bi-people-fill text-primary" style="font-size: 1.75rem;"></i>
</div>
<div>
<div class="text-muted small">Community Score</div>
<div class="h3 mb-0 fw-bold">{{ version.community_score }}%</div>
</div>
</div>
</div>
{% endif %}
{% if version.user_score %}
<div class="col-12 col-md-4">
<div class="d-flex align-items-center p-3 bg-light rounded">
<div class="flex-shrink-0 me-3">
<i class="bi bi-person-check-fill text-success" style="font-size: 1.75rem;"></i>
</div>
<div>
<div class="text-muted small">Your Score</div>
<div class="h3 mb-0 fw-bold">{{ version.user_score }}%</div>
</div>
</div>
</div>
{% endif %}
</div>
</div>
</div>
</div>
{% endif %}
<!-- Playnite-specific Statistics -->
{% if version.play_count or version.install_size or version.completion_status %}
<div class="col-12">
<div class="card">
<div class="card-header">
<h5 class="card-title mb-0">Playnite Statistics</h5>
</div>
<div class="card-body">
<div class="row g-4">
{% if version.play_count %}
<div class="col-12 col-md-4">
<div class="d-flex align-items-center p-3 bg-light rounded">
<div class="flex-shrink-0 me-3">
<i class="bi bi-play-circle-fill text-primary" style="font-size: 1.75rem;"></i>
</div>
<div>
<div class="text-muted small">Play Count</div>
<div class="h3 mb-0 fw-bold">{{ version.play_count }}</div>
</div>
</div>
</div>
{% endif %}
{% if version.install_size %}
<div class="col-12 col-md-4">
<div class="d-flex align-items-center p-3 bg-light rounded">
<div class="flex-shrink-0 me-3">
<i class="bi bi-hdd-fill text-secondary" style="font-size: 1.75rem;"></i>
</div>
<div>
<div class="text-muted small">Install Size</div>
<div class="h3 mb-0 fw-bold">{{ (version.install_size / 1024 / 1024 / 1024)|round(1) }} GB</div>
</div>
</div>
</div>
{% endif %}
{% if version.completion_status %}
<div class="col-12 col-md-4">
<div class="d-flex align-items-center p-3 bg-light rounded">
<div class="flex-shrink-0 me-3">
<i class="bi bi-check-circle-fill text-success" style="font-size: 1.75rem;"></i>
</div>
<div>
<div class="text-muted small">Completion</div>
<div class="h3 mb-0 fw-bold">{{ version.completion_status }}</div>
</div>
</div>
</div>
{% endif %}
</div>
</div>
</div>
</div>
{% endif %}
</div>
{% endif %}
</div>
</div>
{% endif %}
<!-- Playnite-specific Statistics -->
{% if version.play_count or version.install_size or version.completion_status %}
<div class="mt-6">
<h3 class="text-lg font-medium text-gray-900 mb-3">Playnite Statistics</h3>
<div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
{% if version.play_count %}
<div class="bg-gray-50 rounded-lg p-4">
<div class="flex items-center justify-between">
<div>
<p class="text-sm font-medium text-gray-500">Play Count</p>
<p class="text-2xl font-bold text-gray-900">{{ version.play_count }}</p>
</div>
<div class="flex-shrink-0">
<svg class="w-8 h-8 text-indigo-400" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd"/>
</svg>
</div>
</div>
</div>
{% endif %}
{% if version.install_size %}
<div class="bg-gray-50 rounded-lg p-4">
<div class="flex items-center justify-between">
<div>
<p class="text-sm font-medium text-gray-500">Install Size</p>
<p class="text-lg font-bold text-gray-900">{{ (version.install_size / 1024 / 1024 / 1024)|round(1) }} GB</p>
</div>
<div class="flex-shrink-0">
<svg class="w-8 h-8 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M3 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm0 4a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z" clip-rule="evenodd"/>
</svg>
</div>
</div>
</div>
{% endif %}
{% if version.completion_status %}
<div class="bg-gray-50 rounded-lg p-4">
<div class="flex items-center justify-between">
<div>
<p class="text-sm font-medium text-gray-500">Completion Status</p>
<p class="text-lg font-bold text-gray-900">{{ version.completion_status }}</p>
</div>
<div class="flex-shrink-0">
<svg class="w-8 h-8 text-green-400" fill="currentColor" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
</svg>
</div>
</div>
</div>
{% endif %}
</div>
</div>
{% endif %}
{% endfor %}
</div>
</div>
{% endfor %}
</div>
</div>
<script>
// Platform tab switching functionality
// Initialize Bootstrap tooltips
document.addEventListener('DOMContentLoaded', function() {
const tabs = document.querySelectorAll('.platform-tab');
const contents = document.querySelectorAll('.platform-content');
// Initialize all tooltips
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl);
});
tabs.forEach(tab => {
tab.addEventListener('click', function() {
const platform = this.dataset.platform;
const source = this.dataset.source;
// Platform tab switching functionality (using Bootstrap's tab component)
const platformTabs = document.querySelectorAll('.platform-tab');
// Update tab styles
tabs.forEach(t => {
t.classList.remove('border-indigo-500', 'text-indigo-600');
t.classList.add('border-transparent', 'text-gray-500');
platformTabs.forEach(tab => {
tab.addEventListener('shown.bs.tab', function (event) {
const platform = event.target.dataset.platform;
const source = event.target.dataset.source;
// Update active tab styling
platformTabs.forEach(t => {
t.classList.remove('active', 'border-primary', 'text-primary');
t.classList.add('text-muted');
});
this.classList.remove('border-transparent', 'text-gray-500');
this.classList.add('border-indigo-500', 'text-indigo-600');
this.classList.remove('text-muted');
this.classList.add('active', 'border-primary', 'text-primary');
// Update content visibility
contents.forEach(content => {
if (content.dataset.platform === platform && content.dataset.source === source) {
content.classList.remove('hidden');
} else {
content.classList.add('hidden');
}
});
// Any additional tab change logic can go here
console.log(`Switched to platform: ${platform}, source: ${source}`);
});
});
});

View File

@@ -14,13 +14,19 @@
<link rel="stylesheet" href="{{ base_url() }}/build/assets/{{ manifest['resources/css/app.css'].file }}">
{% endif %}
{% else %}
<link rel="stylesheet" href="{{ base_url() }}/public/css/app.css">
<link rel="stylesheet" href="{{ base_url() }}/css/app.css">
{% endif %}
<!-- Favicon -->
<link rel="icon" type="image/svg+xml" href="{{ base_url() }}/favicon.svg">
<meta name="csrf-token" content="{{ csrf_token() }}">
{# DebugBar Assets #}
{% if debugbarRenderer is defined %}
{{ debugbarRenderer.renderHead()|raw }}
{% endif %}
<!-- In the head section -->
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
<!-- Before closing </head> tag -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<!-- jQuery (required for Select2) -->
@@ -112,6 +118,11 @@
</div>
</nav>
<!-- DebugBar -->
{% if debugbarRenderer is defined %}
{{ debugbarRenderer.render()|raw }}
{% endif %}
<!-- Page Content -->
<main class="container-fluid py-4">
{% block content %}{% endblock %}

View File

@@ -112,26 +112,57 @@
</form>
<!-- View mode switcher -->
<div class="btn-group" role="group">
<div class="btn-group me-2" role="group">
{% for mode in view_modes %}
<a
href="?view={{ mode }}{% if search %}&search={{ search }}{% endif %}{% if pagination.per_page != 24 %}&per_page={{ pagination.per_page }}{% endif %}{% for genre in filters.genres %}&genres[]={{ genre }}{% endfor %}{% for director in filters.directors %}&directors[]={{ director }}{% endfor %}"
href="?view={{ mode }}&sort={{ sort }}{% if search %}&search={{ search }}{% endif %}{% if pagination.per_page != 24 %}&per_page={{ pagination.per_page }}{% endif %}{% for genre in filters.genres %}&genres[]={{ genre }}{% endfor %}{% for director in filters.directors %}&directors[]={{ director }}{% endfor %}"
class="btn btn-outline-secondary {{ view_mode == mode ? 'active' : '' }}"
title="{{ mode|title }} View"
>
{% if mode == 'grid' %}
<svg class="me-1" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<svg width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zM14 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zM14 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"/>
</svg>
{% endif %}
{% if mode == 'list' %}
<svg class="me-1" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<svg width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16"/>
</svg>
{% endif %}
{{ mode|title }}
{% if mode == 'covers' %}
<svg width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
</svg>
{% endif %}
<span class="d-none d-sm-inline ms-1">{{ mode|title }}</span>
</a>
{% endfor %}
</div>
<!-- Sort dropdown -->
<div class="dropdown">
<button class="btn btn-outline-secondary dropdown-toggle" type="button" id="sortDropdown" data-bs-toggle="dropdown" aria-expanded="false">
<svg class="me-1" width="16" height="16" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12"/>
</svg>
<span class="d-none d-sm-inline">Sort</span>
</button>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="sortDropdown">
{% for key, label in sort_options %}
<li>
<a class="dropdown-item {% if sort == key %}active{% endif %}"
href="?sort={{ key }}&view={{ view_mode }}{% if search %}&search={{ search }}{% endif %}{% if pagination.per_page != 24 %}&per_page={{ pagination.per_page }}{% endif %}{% for genre in filters.genres %}&genres[]={{ genre }}{% endfor %}{% for director in filters.directors %}&directors[]={{ director }}{% endfor %}">
{{ label }}
{% if sort == key %}
<svg class="float-end mt-1" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
<path d="M12.5 15a.5.5 0 0 1-.5-.5v-13a.5.5 0 0 1 1 0v13a.5.5 0 0 1-.5.5zM10 8a.5.5 0 0 1-.5.5H3.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L3.707 7.5H9.5a.5.5 0 0 1 .5.5z"/>
</svg>
{% endif %}
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
@@ -219,8 +250,22 @@
{% elseif view_mode == 'covers' %}
<!-- Cover grid view -->
<div class="items">
<div class="row g-3">
{% for movie in movies %}
<figure class="item" style="padding:0px">
<a href="{{ path_for('movies.show', {'id': movie.id}) }}" class="text-decoration-none">
<img src="/images/{{ movie.poster_url }}" />
<figcaption>{{ movie.title }}</figcaption>
</a>
</figure>
<!--
<div class="col-6 col-sm-4 col-md-3 col-lg-2">
<div class="card h-100">
{% if movie.poster_url %}
@@ -245,7 +290,7 @@
{% endif %}
</div>
</div>
</div>
</div>-->
{% endfor %}
</div>
@@ -367,6 +412,50 @@
</div>
<style>
/* Sort dropdown styles */
.dropdown-menu {
min-width: 250px;
max-height: 400px;
overflow-y: auto;
}
.dropdown-item {
padding: 0.5rem 1.25rem;
white-space: normal;
line-height: 1.4;
}
.dropdown-item svg {
margin-top: 0.15rem;
}
/* Make sure the dropdown works on mobile */
@media (max-width: 575.98px) {
.dropdown-menu {
position: fixed !important;
top: auto !important;
left: 1rem !important;
right: 1rem !important;
width: auto !important;
margin-top: 0.5rem;
max-height: 70vh;
transform: none !important;
}
.dropdown-menu-end {
right: 1rem !important;
left: 1rem !important;
}
}
/* View mode buttons */
.btn-group .btn {
display: flex;
align-items: center;
justify-content: center;
padding: 0.375rem 0.75rem;
}
/* Custom styles for Select2 integration */
.select2-container {
z-index: 1050; /* Ensure Select2 dropdown appears above other elements */

View File

@@ -38,11 +38,11 @@
<h2 class="h5 fw-semibold text-dark mb-3">Movies ({{ results.movies|length }})</h2>
<div class="row g-3">
{% for movie in results.movies %}
<div class="col-12 col-sm-6 col-md-4 col-lg-3">
<div class="col-12 col-sm-6 col-md-4 col-lg-1">
<div class="card h-100">
{% if movie.poster_url %}
<div style="aspect-ratio: 2/3; background-color: #f8f9fa; border-radius: 0.375rem 0.375rem 0 0; overflow: hidden;">
<img src="{{ movie.poster_url }}" alt="{{ movie.title }}" class="w-100 h-100" style="object-fit: cover;">
<img src="/images/{{ movie.poster_url }}" alt="{{ movie.title }}" class="w-100 h-100" style="object-fit: cover;">
</div>
{% endif %}
<div class="card-body">
@@ -65,17 +65,17 @@
<h2 class="h5 fw-semibold text-dark mb-3">Games ({{ results.games|length }})</h2>
<div class="row g-3">
{% for game in results.games %}
<div class="col-12 col-sm-6 col-md-4 col-lg-3">
<div class="col-12 col-sm-6 col-md-4 col-lg-1">
<div class="card h-100">
{% if game.image_url %}
<div style="aspect-ratio: 16/9; background-color: #f8f9fa; border-radius: 0.375rem 0.375rem 0 0; overflow: hidden;">
<img src="{{ game.image_url }}" alt="{{ game.name }}" class="w-100 h-100" style="object-fit: cover;">
{% if game.cover_image %}
<div style="aspect-ratio: 2/3; background-color: #f8f9fa; border-radius: 0.375rem 0.375rem 0 0; overflow: hidden;">
<img src="{{ game.cover_image }}" alt="{{ game.name }}" class="w-100 h-100" style="object-fit: cover;">
</div>
{% endif %}
<div class="card-body">
<h6 class="card-title text-truncate">
<a href="/media/games/{{ game.game_key }}" class="text-decoration-none">
{{ game.name }}
{{ game.title }}
</a>
</h6>
<p class="card-text small text-muted">{{ game.source_name }}</p>

24
routes/api.php Normal file
View File

@@ -0,0 +1,24 @@
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Routing\RouteCollectorProxy;
// API routes (no authentication required for basic operations)
$app->group('/api', function (RouteCollectorProxy $apiGroup) {
// Playnite API endpoints
$apiGroup->group('/playnite', function (RouteCollectorProxy $playniteGroup) {
// Game management
$playniteGroup->post('/media', 'App\Controllers\Api\PlayniteController:insertGames')->setName('api.playnite.games');
$playniteGroup->put('/update/games/', 'App\Controllers\Api\PlayniteController:updateGames')->setName('api.playnite.update');
$playniteGroup->put('/v1/games/delete', 'App\Controllers\Api\PlayniteController:deleteGames')->setName('api.playnite.delete');
// Image upload
$playniteGroup->post('/image/base64', 'App\Controllers\Api\PlayniteController:uploadImages')->setName('api.playnite.images');
});
// User authentication check (requires authentication)
$apiGroup->get('/v1/users/me', 'App\Controllers\Api\AuthController:checkAuth')->setName('api.auth.check')->add('App\Http\Middleware\AuthMiddleware');
});

View File

@@ -68,6 +68,51 @@ $app->group('', function (RouteCollectorProxy $group) {
$adminGroup->get('', AdminController::class . ':index')->setName('admin.index');
$adminGroup->get('/settings', AdminController::class . ':settings')->setName('admin.settings');
// Media Management
$adminGroup->group('/movies', function (RouteCollectorProxy $group) {
$group->get('', AdminController::class . ':movies')->setName('admin.movies.index');
$group->map(['GET', 'POST'], '/create', AdminController::class . ':editMovie')->setName('admin.movies.create');
$group->map(['GET', 'POST'], '/{id}/edit', AdminController::class . ':editMovie')->setName('admin.movies.edit');
$group->delete('/{id}', AdminController::class . ':deleteMovie')->setName('admin.movies.delete');
});
$adminGroup->group('/games', function (RouteCollectorProxy $group) {
$group->get('', AdminController::class . ':games')->setName('admin.games.index');
$group->map(['GET', 'POST'], '/create', AdminController::class . ':editGame')->setName('admin.games.create');
$group->map(['GET', 'POST'], '/{id}/edit', AdminController::class . ':editGame')->setName('admin.games.edit');
$group->delete('/{id}', AdminController::class . ':deleteGame')->setName('admin.games.delete');
// SteamGridDB API routes
$group->group('/sgdb', function (RouteCollectorProxy $sgdb) {
$sgdb->get('/search', 'App\Controllers\GameController:searchSteamGridDb')->setName('admin.games.sgdb.search');
$sgdb->get('/media/{gameId}/{type}', 'App\Controllers\GameController:getSteamGridDbMedia')->setName('admin.games.sgdb.media');
$sgdb->post('/media/set', 'App\Controllers\GameController:setSteamGridDbMedia')->setName('admin.games.sgdb.media.set');
});
});
$adminGroup->group('/shows', function (RouteCollectorProxy $group) {
$group->get('', AdminController::class . ':shows')->setName('admin.shows.index');
$group->map(['GET', 'POST'], '/create', AdminController::class . ':editShow')->setName('admin.shows.create');
$group->map(['GET', 'POST'], '/{id}/edit', AdminController::class . ':editShow')->setName('admin.shows.edit');
$group->delete('/{id}', AdminController::class . ':deleteShow')->setName('admin.shows.delete');
});
$adminGroup->group('/adult', function (RouteCollectorProxy $group) {
$group->get('', [AdminController::class, 'adultVideos']);
$group->get('/create', [AdminController::class, 'createAdultVideo']);
$group->post('', [AdminController::class, 'storeAdultVideo']);
$group->get('/{id}/edit', [AdminController::class, 'editAdultVideo']);
$group->post('/{id}', [AdminController::class, 'updateAdultVideo']);
$group->post('/{id}/delete', [AdminController::class, 'deleteAdultVideo']);
// Actor management routes
$group->get('/{id}/actors', [AdminController::class, 'getAdultVideoActors']);
$group->post('/{id}/actors', [AdminController::class, 'addActorToAdultVideo']);
$group->delete('/{id}/actors/{actorId}', [AdminController::class, 'removeActorFromAdultVideo']);
$group->get('/search-actors', [AdminController::class, 'searchActors']);
});
// Media Sources
// Media Sources
$adminGroup->group('/sources', function (RouteCollectorProxy $sourcesGroup) {