Add new API endpoints for media retrieval by country and enhance configuration
Some checks failed
Test Suite / test (push) Has been cancelled
Some checks failed
Test Suite / test (push) Has been cancelled
- Introduced `/api/tmdb` and `/api/collection/missing-locations` endpoints to the backend for improved media management. - Added a new `get_media_by_country` function in the collection API to fetch media items based on country codes. - Updated configuration to allow overriding *arr base URLs via environment variables for better flexibility. - Enhanced frontend with a new `MissingLocations` component and integrated it into the routing structure. - Improved the `CollectionMap` component to handle country selection and display media items accordingly. - Added testing dependencies in `requirements.txt` and updated frontend configuration for testing support.
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
"""Collection API endpoints"""
|
||||
from fastapi import APIRouter, Query
|
||||
from fastapi import APIRouter, Query, HTTPException
|
||||
from typing import List, Optional
|
||||
import json
|
||||
from app.core.database import init_db, pool as db_pool
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -61,3 +62,70 @@ async def get_collection_summary(
|
||||
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/by-country")
|
||||
async def get_media_by_country(
|
||||
country_code: str = Query(..., description="ISO 3166-1 alpha-2 country code"),
|
||||
types: Optional[str] = Query(None, description="Comma-separated list: movie,show,music")
|
||||
):
|
||||
"""
|
||||
Get list of media items for a specific country.
|
||||
Returns media items with their details.
|
||||
"""
|
||||
await init_db()
|
||||
if db_pool is None:
|
||||
raise HTTPException(status_code=503, detail="Database not available")
|
||||
|
||||
# Validate country code
|
||||
if len(country_code) != 2 or not country_code.isalpha():
|
||||
raise HTTPException(status_code=400, detail="Country code must be 2 letters (ISO 3166-1 alpha-2)")
|
||||
|
||||
country_code = country_code.upper()
|
||||
|
||||
# Parse types filter
|
||||
type_filter = []
|
||||
if types:
|
||||
type_filter = [t.strip() for t in types.split(",") if t.strip() in ["movie", "show", "music"]]
|
||||
|
||||
async with db_pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
query = """
|
||||
SELECT
|
||||
mi.id,
|
||||
mi.source_kind,
|
||||
mi.source_item_id,
|
||||
mi.title,
|
||||
mi.year,
|
||||
mi.media_type
|
||||
FROM moviemap.media_country mc
|
||||
JOIN moviemap.media_item mi ON mc.media_item_id = mi.id
|
||||
WHERE mc.country_code = %s
|
||||
"""
|
||||
params = [country_code]
|
||||
|
||||
if type_filter:
|
||||
query += " AND mi.media_type = ANY(%s)"
|
||||
params.append(type_filter)
|
||||
|
||||
query += " ORDER BY mi.title"
|
||||
|
||||
await cur.execute(query, params)
|
||||
rows = await cur.fetchall()
|
||||
|
||||
items = []
|
||||
for row in rows:
|
||||
items.append({
|
||||
"id": str(row[0]),
|
||||
"source_kind": row[1],
|
||||
"source_item_id": row[2],
|
||||
"title": row[3],
|
||||
"year": row[4],
|
||||
"media_type": row[5],
|
||||
})
|
||||
|
||||
return {
|
||||
"country_code": country_code,
|
||||
"count": len(items),
|
||||
"items": items
|
||||
}
|
||||
|
||||
|
||||
87
backend/app/api/missing_locations.py
Normal file
87
backend/app/api/missing_locations.py
Normal file
@@ -0,0 +1,87 @@
|
||||
"""Missing locations API endpoints"""
|
||||
from fastapi import APIRouter, Query, HTTPException
|
||||
from typing import Optional
|
||||
from app.core.database import init_db, pool as db_pool
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_missing_locations(
|
||||
source_kind: Optional[str] = Query(None, description="Filter by source: radarr, sonarr, lidarr"),
|
||||
media_type: Optional[str] = Query(None, description="Filter by media type: movie, show, music"),
|
||||
limit: int = Query(100, ge=1, le=1000, description="Maximum number of items to return"),
|
||||
offset: int = Query(0, ge=0, description="Number of items to skip")
|
||||
):
|
||||
"""
|
||||
Get list of media items without country metadata.
|
||||
Returns paginated list of media items that don't have any country associations.
|
||||
"""
|
||||
await init_db()
|
||||
if db_pool is None:
|
||||
raise HTTPException(status_code=503, detail="Database not available")
|
||||
|
||||
async with db_pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
# Build query
|
||||
where_clauses = ["mc.media_item_id IS NULL"]
|
||||
params = []
|
||||
|
||||
if source_kind:
|
||||
where_clauses.append("mi.source_kind = %s")
|
||||
params.append(source_kind)
|
||||
if media_type:
|
||||
where_clauses.append("mi.media_type = %s")
|
||||
params.append(media_type)
|
||||
|
||||
where_clause = " AND ".join(where_clauses)
|
||||
|
||||
# Get total count
|
||||
count_query = f"""
|
||||
SELECT COUNT(DISTINCT mi.id)
|
||||
FROM moviemap.media_item mi
|
||||
LEFT JOIN moviemap.media_country mc ON mi.id = mc.media_item_id
|
||||
WHERE {where_clause}
|
||||
"""
|
||||
await cur.execute(count_query, params)
|
||||
total_count = (await cur.fetchone())[0]
|
||||
|
||||
# Get items
|
||||
query = f"""
|
||||
SELECT
|
||||
mi.id,
|
||||
mi.source_kind,
|
||||
mi.source_item_id,
|
||||
mi.title,
|
||||
mi.year,
|
||||
mi.media_type
|
||||
FROM moviemap.media_item mi
|
||||
LEFT JOIN moviemap.media_country mc ON mi.id = mc.media_item_id
|
||||
WHERE {where_clause}
|
||||
ORDER BY mi.title
|
||||
LIMIT %s OFFSET %s
|
||||
"""
|
||||
params.extend([limit, offset])
|
||||
|
||||
await cur.execute(query, params)
|
||||
rows = await cur.fetchall()
|
||||
|
||||
items = []
|
||||
for row in rows:
|
||||
items.append({
|
||||
"id": str(row[0]),
|
||||
"source_kind": row[1],
|
||||
"source_item_id": row[2],
|
||||
"title": row[3],
|
||||
"year": row[4],
|
||||
"media_type": row[5],
|
||||
})
|
||||
|
||||
return {
|
||||
"total": total_count,
|
||||
"returned": len(items),
|
||||
"offset": offset,
|
||||
"limit": limit,
|
||||
"items": items
|
||||
}
|
||||
|
||||
71
backend/app/api/tmdb.py
Normal file
71
backend/app/api/tmdb.py
Normal file
@@ -0,0 +1,71 @@
|
||||
"""TMDB API endpoints for searching movies and TV shows"""
|
||||
from fastapi import APIRouter, Query, HTTPException
|
||||
from typing import Optional
|
||||
import httpx
|
||||
from app.core.config import settings
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
TMDB_BASE_URL = "https://api.themoviedb.org/3"
|
||||
|
||||
|
||||
@router.get("/search")
|
||||
async def search_tmdb(
|
||||
query: str = Query(..., description="Search query"),
|
||||
type: str = Query("movie", description="Type: movie or tv")
|
||||
):
|
||||
"""
|
||||
Search TMDB for movies or TV shows.
|
||||
Returns a list of results with title, year, and other metadata.
|
||||
"""
|
||||
if not settings.tmdb_api_key:
|
||||
raise HTTPException(status_code=503, detail="TMDB API key not configured")
|
||||
|
||||
if type not in ["movie", "tv"]:
|
||||
raise HTTPException(status_code=400, detail="Type must be 'movie' or 'tv'")
|
||||
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(
|
||||
f"{TMDB_BASE_URL}/search/{type}",
|
||||
params={
|
||||
"api_key": settings.tmdb_api_key,
|
||||
"query": query,
|
||||
"language": "en-US",
|
||||
},
|
||||
timeout=10.0
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
results = []
|
||||
for item in data.get("results", [])[:10]: # Limit to 10 results
|
||||
result = {
|
||||
"id": item.get("id"),
|
||||
"title": item.get("title") or item.get("name"),
|
||||
"year": None,
|
||||
"type": type,
|
||||
"overview": item.get("overview"),
|
||||
"poster_path": item.get("poster_path"),
|
||||
}
|
||||
|
||||
# Extract year from release_date or first_air_date
|
||||
date_str = item.get("release_date") or item.get("first_air_date")
|
||||
if date_str:
|
||||
try:
|
||||
result["year"] = int(date_str.split("-")[0])
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
|
||||
results.append(result)
|
||||
|
||||
return {
|
||||
"query": query,
|
||||
"type": type,
|
||||
"results": results
|
||||
}
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise HTTPException(status_code=e.response.status_code, detail=f"TMDB API error: {e.response.text[:200]}")
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Failed to search TMDB: {str(e)}")
|
||||
|
||||
@@ -21,10 +21,10 @@ class Settings(BaseSettings):
|
||||
radarr_api_key: str = os.getenv("RADARR_API_KEY", "")
|
||||
lidarr_api_key: str = os.getenv("LIDARR_API_KEY", "")
|
||||
|
||||
# *arr base URLs
|
||||
sonarr_url: str = "http://127.0.0.1:8989"
|
||||
radarr_url: str = "http://127.0.0.1:7878"
|
||||
lidarr_url: str = "http://127.0.0.1:8686"
|
||||
# *arr base URLs (can be overridden via environment variables)
|
||||
sonarr_url: str = os.getenv("SONARR_URL", "http://127.0.0.1:8989")
|
||||
radarr_url: str = os.getenv("RADARR_URL", "http://127.0.0.1:7878")
|
||||
lidarr_url: str = os.getenv("LIDARR_URL", "http://127.0.0.1:8686")
|
||||
|
||||
# Admin
|
||||
admin_token: Optional[str] = os.getenv("MOVIEMAP_ADMIN_TOKEN")
|
||||
|
||||
Reference in New Issue
Block a user