maubot-tmdb/tmdb/tmdb_api.py

262 lines
8.3 KiB
Python
Raw Normal View History

"""
This file is part of tmdb-bot.
tmdb-bot is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3 as published by
the Free Software Foundation.
tmdb-bot is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with tmdb-bot. If not, see <https://www.gnu.org/licenses/>.
"""
# pylint: disable=missing-class-docstring,missing-function-docstring
import asyncio
2021-03-16 20:45:27 +00:00
from html import escape
import aiohttp
import aiohttp.client_exceptions
2020-06-22 12:15:28 +01:00
class TmdbApi:
2020-06-22 12:15:28 +01:00
def __init__(self):
self.session = aiohttp.ClientSession()
self.language = "en"
2020-06-23 16:47:37 +01:00
self.valid = False
self.overview = ""
self.cast = []
self.web_url = ""
self.title = ""
self.vote_average = 0.0
self.base_url_poster = ""
self.base_url = ""
self.api_key = ""
self.poster_sizes = []
self.base_url_images = ""
async def load_parameters(self):
self.api_key = "51d75c00dc1502dc894b7773ec3e7a15"
2020-06-22 12:15:28 +01:00
self.base_url = "https://api.themoviedb.org/3/"
async with self.session.get(
self.base_url + "configuration", params=self.get_apikey()
) as resp:
result = await resp.json()
self.base_url_images = result["images"]["secure_base_url"]
self.base_url_poster = (
self.base_url_images + result["images"]["poster_sizes"][-4]
)
self.poster_sizes = result["images"]["poster_sizes"]
2020-06-22 12:15:28 +01:00
def get_apikey(self):
return {"api_key": self.api_key}
2020-06-22 12:15:28 +01:00
async def request(self, request_uri, params: dict | None = None):
if not params:
params = {}
url = self.base_url + request_uri.lstrip("/")
2020-06-24 09:45:18 +01:00
params.update(self.get_apikey())
params.update({"language": self.language})
result = None
async with self.session.get(url, params=params) as resp:
result = await resp.json()
self.valid = True
return result
2020-06-22 12:15:28 +01:00
2020-06-22 13:41:31 +01:00
def set_language(self, language):
self.language = language
async def close_session(self):
await self.session.close()
2021-11-18 20:48:13 +00:00
def set_poster_size(self, size):
for x in self.poster_sizes:
if x == size:
self.base_url_poster = self.base_url_images + x
return x
return None
2021-03-16 16:56:02 +00:00
class TmdbApiSingle(TmdbApi):
def __init__(self):
super().__init__()
self.title = ""
2021-03-16 16:56:02 +00:00
self.id = None
self.poster_url = ""
2021-09-23 12:39:40 +01:00
self.poster_binary = None
self.overview = ""
self.web_url = ""
2021-03-16 16:56:02 +00:00
self.vote_average = None
2020-06-22 12:15:28 +01:00
def get_image_binary(self):
2021-09-23 12:39:40 +01:00
return self.poster_binary
async def query_image_binary(self):
self.poster_url = ""
2020-06-23 16:47:37 +01:00
if self.poster_url:
2023-05-31 11:53:09 +01:00
try:
async with self.session.get(self.poster_url) as resp:
self.poster_binary = await resp.read()
except aiohttp.client_exceptions.ClientConnectorError:
self.poster_binary = None
2020-06-23 16:47:37 +01:00
else:
2021-09-23 12:39:40 +01:00
self.poster_binary = None
2021-03-16 20:45:27 +00:00
2021-03-16 16:56:02 +00:00
class MoviePopular(TmdbApi):
def __init__(self):
super().__init__()
self.list = []
self.length = 0
2021-11-08 21:28:34 +00:00
async def query(self) -> int:
result = await self.request("/movie/popular")
self.length = result["total_results"]
self.list = result["results"]
2021-03-16 16:56:02 +00:00
return self.length
def getListHtml(self, length: int = 0) -> str:
2021-03-16 20:45:27 +00:00
html = ""
if length:
loop = length
else:
loop = self.length
movie_id = 1
2021-03-16 20:45:27 +00:00
for element in self.list[:loop]:
html += (
f"<p>{str(movie_id)} - "
f'<a href="https://www.themoviedb.org/movie/{str(element["id"])}">'
f"{escape(element['title'])}</a> - {str(int(element['vote_average']*10))}%</p>"
)
movie_id += 1
2021-03-16 20:45:27 +00:00
return html
def getListText(self, length: int = 0) -> str:
2021-03-16 20:45:27 +00:00
text = ""
if length:
loop = length
else:
loop = self.length
for element in self.list[:loop]:
text += element["title"]
2021-03-16 20:45:27 +00:00
return text
def getDict(self, length: int = 0) -> dict[int, int]:
result = {}
if length:
loop = length
else:
loop = self.length
movie_id = 1
for element in self.list[:loop]:
result[movie_id] = str(element["id"])
movie_id += 1
return result
2021-11-18 20:48:13 +00:00
async def getMovieByNumber(self, number):
movie = Movie()
await movie.load_parameters()
movie.base_url_poster = self.base_url_poster
item = self.list[int(number) - 1]
await movie.setData(item)
return movie
2020-06-22 12:15:28 +01:00
2021-03-16 16:56:02 +00:00
class Movie(TmdbApiSingle):
2021-11-18 20:48:13 +00:00
async def setData(self, data):
self.title = data["title"]
2021-11-18 20:48:13 +00:00
if not self.title:
self.valid = False
self.id = data["id"]
self.poster_url = self.base_url_poster + data.get(
"poster_path", "__no_poster_path__"
)
self.overview = data["overview"]
self.web_url = "https://www.themoviedb.org/movie/" + str(self.id)
self.vote_average = data["vote_average"]
await asyncio.gather(self.query_cast(self.id), self.query_image_binary())
2021-11-18 20:48:13 +00:00
return self.id
async def search_title(self, title: str, year: int = 0) -> int:
2020-06-24 09:45:18 +01:00
payload = {}
payload["query"] = title
2020-06-26 15:41:44 +01:00
if year:
payload["year"] = year
json = await self.request("search/movie", params=payload)
if json["total_results"] > 0:
movie_id = json["results"][0]["id"]
2021-09-23 12:39:40 +01:00
await self.query_details(movie_id)
await asyncio.gather(self.query_cast(movie_id), self.query_image_binary())
2020-06-22 12:15:28 +01:00
return movie_id
self.valid = False
return 0
async def search_id(self, movie_id):
await self.query_details(movie_id)
await asyncio.gather(self.query_cast(movie_id), self.query_image_binary())
return movie_id
async def query_details(self, movie_id):
data = await self.request("movie/" + str(movie_id))
self.title = data["title"]
2021-08-20 09:07:57 +01:00
if not self.title:
self.valid = False
self.id = data["id"]
self.poster_url = self.base_url_poster + data.get(
"poster_path", "__no_poster_path__"
)
self.overview = data["overview"]
self.web_url = "https://www.themoviedb.org/movie/" + str(self.id)
self.vote_average = data["vote_average"]
async def query_cast(self, movie_id):
data = await self.request("movie/" + str(movie_id) + "/credits")
2020-06-22 12:15:28 +01:00
self.cast = []
for actor in data["cast"]:
self.cast.append(actor["name"])
2020-06-22 12:15:28 +01:00
def get_cast(self, amount):
return self.cast[:amount]
2020-06-24 09:45:18 +01:00
2021-03-16 16:56:02 +00:00
class TvShow(TmdbApiSingle):
async def search_title(self, title, year: int = 0) -> int:
2020-06-24 09:45:18 +01:00
payload = {}
payload["query"] = title
2021-12-12 10:26:28 +00:00
if year:
payload["first_air_date_year"] = str(year)
json = await self.request("/search/tv", params=payload)
if json["total_results"] > 0:
movie_id = json["results"][0]["id"]
2021-09-23 12:39:40 +01:00
await self.query_details(movie_id)
await asyncio.gather(self.query_cast(), self.query_image_binary())
2020-06-24 09:45:18 +01:00
return movie_id
self.valid = False
return 0
2020-06-24 09:45:18 +01:00
async def query_details(self, movie_id):
data = await self.request("tv/" + str(movie_id))
self.title = data["name"]
2021-08-20 09:07:57 +01:00
if not self.title:
self.valid = False
self.id = data["id"]
self.poster_url = self.base_url_poster + data.get(
"poster_path", "__no_poster_path__"
)
self.overview = data["overview"]
self.web_url = "https://www.themoviedb.org/tv/" + str(self.id)
self.vote_average = data["vote_average"]
2021-09-23 12:39:40 +01:00
async def query_cast(self):
data = await self.request("tv/" + str(self.id) + "/credits")
2020-06-24 09:45:18 +01:00
self.cast = []
for actor in data["cast"]:
self.cast.append(actor["name"])
2020-06-24 09:45:18 +01:00
def get_cast(self, amount):
return self.cast[:amount]