60 lines
2.1 KiB
Python
60 lines
2.1 KiB
Python
from datetime import timedelta
|
|
|
|
from rest_framework import viewsets
|
|
from rest_framework.decorators import action
|
|
from rest_framework.response import Response
|
|
|
|
from tmdbv3api import TMDb, Search, Movie
|
|
|
|
from myapi.models import Film
|
|
from myapi.serializers import FilmSerializer
|
|
from ulm_cine_club_api.settings.base import TMDB_API_KEY
|
|
|
|
tmdb = TMDb()
|
|
tmdb.api_key = TMDB_API_KEY
|
|
tmdb.language = "fr"
|
|
|
|
|
|
class TmdbViewSet(viewsets.ViewSet):
|
|
@action(methods=["GET"], detail=False)
|
|
def search(self, request):
|
|
query = request.query_params["query"]
|
|
search = Search()
|
|
tmdb_results = search.movies({"query": query})
|
|
res = [
|
|
{
|
|
"id": film["id"],
|
|
"release_date": film["release_date"],
|
|
"title": film["title"],
|
|
"poster_path": film["poster_path"],
|
|
}
|
|
for film in tmdb_results
|
|
]
|
|
return Response(res)
|
|
|
|
@action(methods=["GET"], detail=True)
|
|
def fill(self, request, pk=None):
|
|
tmdb_movie = Movie().details(pk, "images,credits,keywords")
|
|
internal_movie = Film(
|
|
title=tmdb_movie["title"],
|
|
imdb_id=tmdb_movie["imdb_id"],
|
|
tmdb_id=tmdb_movie["id"],
|
|
synopsis=tmdb_movie["overview"],
|
|
poster_link=tmdb_movie["poster_path"],
|
|
duration=timedelta(minutes=tmdb_movie["runtime"]),
|
|
release_year=tmdb_movie["release_date"][:4],
|
|
director=next(person["name"] for person in tmdb_movie["credits"]["crew"] if person["job"] == "Director"),
|
|
actors=[person["name"] for person in tmdb_movie["credits"]["cast"][:5]],
|
|
origin_country=", ".join(
|
|
short_country_name(country["name"]) for country in tmdb_movie["production_countries"]
|
|
), # TODO iso to French name
|
|
is_in_color=not any(keyword["id"] == 12999 for keyword in tmdb_movie["keywords"]["keywords"])
|
|
)
|
|
serializer = FilmSerializer(internal_movie)
|
|
return Response(serializer.data)
|
|
|
|
|
|
def short_country_name(country_name: str):
|
|
if country_name == "United States of America":
|
|
return "USA"
|
|
return country_name
|