cineclub-site/server/myapi/views/tmdb_views.py

65 lines
2.3 KiB
Python
Raw Normal View History

from datetime import timedelta
2022-05-30 00:18:09 +02:00
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
2022-06-10 00:18:56 +02:00
from tmdbv3api import TMDb, Search, Movie
from json import load
2022-06-10 00:18:56 +02:00
from myapi.models import Film
2022-12-04 01:25:56 +01:00
from myapi.serializers import FilmSerializer, FromTmdbFilmSerializer
2022-06-10 00:18:56 +02:00
from ulm_cine_club_api.settings.base import TMDB_API_KEY
2022-05-30 00:18:09 +02:00
tmdb = TMDb()
2022-06-10 00:18:56 +02:00
tmdb.api_key = TMDB_API_KEY
2022-05-30 00:18:09 +02:00
tmdb.language = "fr"
ISO_TO_FR = {}
with open("myapi/iso-3166_country_french.json") as f:
ISO_TO_FR = load(f)
2022-05-30 00:18:09 +02:00
class TmdbViewSet(viewsets.ViewSet):
2022-06-10 00:21:06 +02:00
@action(methods=["GET"], detail=False)
2022-05-30 00:18:09 +02:00
def search(self, request):
2022-06-10 00:21:06 +02:00
query = request.query_params["query"]
2022-05-30 00:18:09 +02:00
search = Search()
2022-06-10 00:21:06 +02:00
tmdb_results = search.movies({"query": query})
res = [
{
2022-12-04 01:25:56 +01:00
"tmdb_id": film["id"],
2022-05-30 00:18:09 +02:00
"release_date": film["release_date"],
"title": film["title"],
2022-06-10 00:21:06 +02:00
"poster_path": film["poster_path"],
}
for film in tmdb_results
]
2022-05-30 00:18:09 +02:00
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= f'https://image.tmdb.org/t/p/w200{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"])
)
2022-12-04 01:25:56 +01:00
serializer = FromTmdbFilmSerializer(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