Added flake to drone.yaml

Changes proposed by flake
This commit is contained in:
lomion 2021-03-16 16:35:02 +01:00
parent 5cb36d7f34
commit 2eb62a790f
6 changed files with 58 additions and 60 deletions

View file

@ -3,14 +3,15 @@ pipeline:
image: python image: python
commands: commands:
- pip install -r requirements.txt - pip install -r requirements.txt
- pip install flake8
- python3 test_tmdb.py - python3 test_tmdb.py
- flake8 --ignore=E501
build: build:
image: alpine image: alpine
commands: commands:
- apk add zip - apk add zip
- ./create_release.sh ${DRONE_COMMIT_SHA:0:8} - ./create_release.sh ${DRONE_COMMIT_SHA:0:8}
- ls *.mbp
upload: upload:
image: uploader image: uploader

View file

@ -7,7 +7,7 @@ from sqlalchemy import create_engine
class TestTmdbMethods(unittest.TestCase): class TestTmdbMethods(unittest.TestCase):
### TMDB API # TMDB API
def test_search_item(self): def test_search_item(self):
movie = Movie() movie = Movie()
id = movie.search_title('Breakfast Club') id = movie.search_title('Breakfast Club')
@ -16,19 +16,19 @@ class TestTmdbMethods(unittest.TestCase):
def test_cast(self): def test_cast(self):
movie = Movie() movie = Movie()
movie.search_title('Breakfast Club') movie.search_title('Breakfast Club')
self.assertEqual('Anthony Michael Hall', movie.cast[0]) self.assertEqual('Emilio Estevez', movie.cast[0])
def test_title(self): def test_title(self):
movie = Movie() movie = Movie()
movie.search_title('Breakfast Club') movie.search_title('Breakfast Club')
self.assertEqual('The Breakfast Club', movie.title) self.assertEqual('The Breakfast Club', movie.title)
def test_overview(self): def test_overview(self):
movie = Movie() movie = Movie()
movie.search_title('Breakfast Club') movie.search_title('Breakfast Club')
description = 'Five high school students from different walks of' description = 'Five high school students from different walks of'
self.assertEqual(description, movie.overview[:len(description)]) self.assertEqual(description, movie.overview[:len(description)])
def test_change_language(self): def test_change_language(self):
movie = Movie() movie = Movie()
movie.set_language('en') movie.set_language('en')
@ -38,7 +38,6 @@ class TestTmdbMethods(unittest.TestCase):
def test_html_construction(self): def test_html_construction(self):
movie = Movie() movie = Movie()
tmdb = TmdbBot("","" ,"" ,"" ,"" ,"" ,"" ,"" ,"" )
movie.query_details('550') movie.query_details('550')
constructor = MessageConstructor(movie) constructor = MessageConstructor(movie)
constructor.overview_length = 10 constructor.overview_length = 10
@ -49,7 +48,7 @@ class TestTmdbMethods(unittest.TestCase):
<p>Taken from www.themoviedb.org</p>""") <p>Taken from www.themoviedb.org</p>""")
def test_database_language(self): def test_database_language(self):
engine = create_engine('sqlite:///test.db', echo = True) engine = create_engine('sqlite:///test.db', echo=True)
db = Database(engine) db = Database(engine)
db.set_language('@testuser:example.com', 'de') db.set_language('@testuser:example.com', 'de')
self.assertEqual(str(db.get_language('@testuser:example.com')), 'de') self.assertEqual(str(db.get_language('@testuser:example.com')), 'de')
@ -75,14 +74,14 @@ class TestTmdbMethods(unittest.TestCase):
self.assertEqual(id, 841) self.assertEqual(id, 841)
def test_split_year(self): def test_split_year(self):
tmdb = TmdbBot("","" ,"" ,"" ,"" ,"" ,"" ,"" ,"" ) tmdb = TmdbBot("", "", "", "", "", "", "", "", "")
title, year = tmdb.split_title_year('Dune') title, year = tmdb.split_title_year('Dune')
self.assertEqual('Dune', title) self.assertEqual('Dune', title)
self.assertEqual(None, year) self.assertEqual(None, year)
title, year = tmdb.split_title_year('Dune y:2020 ') title, year = tmdb.split_title_year('Dune y:2020 ')
self.assertEqual('Dune', title) self.assertEqual('Dune', title)
self.assertEqual(2020, year) self.assertEqual(2020, year)
def test_set_poster_size(self): def test_set_poster_size(self):
movie = Movie() movie = Movie()
size = movie.set_poster_size("w500") size = movie.set_poster_size("w500")
@ -91,7 +90,7 @@ class TestTmdbMethods(unittest.TestCase):
size = movie.set_poster_size("w666") size = movie.set_poster_size("w666")
self.assertEqual(size, None) self.assertEqual(size, None)
# TV Shows # TV Shows
def test_search_tvshow(self): def test_search_tvshow(self):
movie = TvShow() movie = TvShow()
id = movie.search_title('The Flash') id = movie.search_title('The Flash')
@ -102,16 +101,16 @@ class TestTmdbMethods(unittest.TestCase):
movie.search_title('The Flash') movie.search_title('The Flash')
self.assertEqual('The Flash', movie.title) self.assertEqual('The Flash', movie.title)
def test_cast(self): def test_cast_2(self):
movie = TvShow() movie = TvShow()
movie.search_title('The Flash') movie.search_title('The Flash')
#self.assertEqual('Tom Cavanagh', movie.cast[0])
self.assertEqual('Danielle Panabaker', movie.cast[2]) self.assertEqual('Danielle Panabaker', movie.cast[2])
def test_poster_path(self): def test_poster_path(self):
movie = Movie() movie = Movie()
id = movie.search_title('Dune') movie.search_title('Dune')
self.assertEqual(movie.poster_url, "http://image.tmdb.org/t/p/w92/9HNZTw2D3cM1yA08FF5SeWEO9eX.jpg") self.assertEqual(movie.poster_url, "http://image.tmdb.org/t/p/w92/9HNZTw2D3cM1yA08FF5SeWEO9eX.jpg")
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View file

@ -1 +0,0 @@
from .tmdb import TmdbBot

View file

@ -14,16 +14,15 @@ 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/>. along with tmdb-bot. If not, see <https://www.gnu.org/licenses/>.
''' '''
from sqlalchemy import (Column, String, Integer, ForeignKey, Table, MetaData, from sqlalchemy import (Column, String, Integer, Table, MetaData, select)
select, and_)
from sqlalchemy.engine.base import Engine from sqlalchemy.engine.base import Engine
class Database: class Database:
db: Engine db: Engine
def __init__(self, db: Engine) -> None: def __init__(self, db: Engine) -> None:
self.db = db self.db = db
meta = MetaData() meta = MetaData()
meta.bind = db meta.bind = db
@ -32,35 +31,35 @@ class Database:
Column("user_id", String(255), nullable=False), Column("user_id", String(255), nullable=False),
Column("language", String(255), nullable=False),) Column("language", String(255), nullable=False),)
self.tmdb_poster_size = Table("tmdb_poster_size", meta, self.tmdb_poster_size = Table("tmdb_poster_size", meta,
Column("id", Integer, primary_key=True, autoincrement=True), Column("id", Integer, primary_key=True, autoincrement=True),
Column("user_id", String(255), nullable=False), Column("user_id", String(255), nullable=False),
Column("size", String(255), nullable=False),) Column("size", String(255), nullable=False),)
meta.create_all(db) meta.create_all(db)
def set_language(self, user_id, language): def set_language(self, user_id, language):
with self.db.begin() as tx: with self.db.begin() as tx:
tx.execute(self.language.delete().where(self.language.c.user_id == user_id)) tx.execute(self.language.delete().where(self.language.c.user_id == user_id))
tx.execute(self.language.insert().values(user_id=user_id, language=language)) tx.execute(self.language.insert().values(user_id=user_id, language=language))
def get_language(self, user_id): def get_language(self, user_id):
rows = self.db.execute(select([self.language.c.language]) rows = self.db.execute(select([self.language.c.language])
.where(self.language.c.user_id == user_id)) .where(self.language.c.user_id == user_id))
row = rows.fetchone() row = rows.fetchone()
if row: if row:
return row['language'] return row['language']
else: else:
return None return None
def set_poster_size(self, user_id, size): def set_poster_size(self, user_id, size):
with self.db.begin() as tx: with self.db.begin() as tx:
tx.execute(self.tmdb_poster_size.delete().where(self.tmdb_poster_size.c.user_id == user_id)) tx.execute(self.tmdb_poster_size.delete().where(self.tmdb_poster_size.c.user_id == user_id))
tx.execute(self.tmdb_poster_size.insert().values(user_id=user_id, size=size)) tx.execute(self.tmdb_poster_size.insert().values(user_id=user_id, size=size))
def get_poster_size(self, user_id): def get_poster_size(self, user_id):
rows = self.db.execute(select([self.tmdb_poster_size.c.size]) rows = self.db.execute(select([self.tmdb_poster_size.c.size])
.where(self.tmdb_poster_size.c.user_id == user_id)) .where(self.tmdb_poster_size.c.user_id == user_id))
row = rows.fetchone() row = rows.fetchone()
if row: if row:
return row['size'] return row['size']
else: else:
return None return None

View file

@ -24,12 +24,13 @@ from maubot.handlers import command
from tmdb.tmdb_api import TmdbApi, Movie, TvShow from tmdb.tmdb_api import TmdbApi, Movie, TvShow
from tmdb.database import Database from tmdb.database import Database
class MessageConstructor(): class MessageConstructor():
def __init__(self, movie : TmdbApi): def __init__(self, movie: TmdbApi):
self.movie = movie self.movie = movie
self.overview_length = 200 self.overview_length = 200
self.cast_length = 3 self.cast_length = 3
def three_dotts(self): def three_dotts(self):
if len(self.movie.overview) > self.overview_length: if len(self.movie.overview) > self.overview_length:
return " [...]" return " [...]"
@ -39,10 +40,9 @@ class MessageConstructor():
def cast(self): def cast(self):
cast = "Acting: " cast = "Acting: "
for actor in self.movie.cast[:self.cast_length]: for actor in self.movie.cast[:self.cast_length]:
cast+= f'{actor}, ' cast += f'{actor}, '
return cast[:-2] return cast[:-2]
def construct_html_message(self) -> str: def construct_html_message(self) -> str:
html_message = f"""<p><a href="{self.movie.web_url}"><b>{escape(self.movie.title)}</b></a></p> html_message = f"""<p><a href="{self.movie.web_url}"><b>{escape(self.movie.title)}</b></a></p>
<p>{escape(self.movie.overview)[:self.overview_length]}{self.three_dotts()}</p> <p>{escape(self.movie.overview)[:self.overview_length]}{self.three_dotts()}</p>
@ -83,10 +83,10 @@ class TmdbBot(Plugin):
async def send_notice(self, evt: MessageEvent, message: str = "") -> None: async def send_notice(self, evt: MessageEvent, message: str = "") -> None:
content = TextMessageEventContent( content = TextMessageEventContent(
msgtype=MessageType.NOTICE, format=Format.HTML, msgtype=MessageType.NOTICE, format=Format.HTML,
body=message) body=message)
await evt.respond(content) await evt.respond(content)
async def send_help(self, evt: MessageEvent) -> None: async def send_help(self, evt: MessageEvent) -> None:
html = """<p>Use <b>!tmdb id movie {tmdb id}</b> to get movie detail for tmdb-id.</p> html = """<p>Use <b>!tmdb id movie {tmdb id}</b> to get movie detail for tmdb-id.</p>
<p>Use <b>!tmdb movie {title} [y:{release year}]</b> to get movie detail based on the given title.</p> <p>Use <b>!tmdb movie {title} [y:{release year}]</b> to get movie detail based on the given title.</p>
@ -109,7 +109,7 @@ class TmdbBot(Plugin):
info=ImageInfo(mimetype='image/jpg')) info=ImageInfo(mimetype='image/jpg'))
await evt.respond(content) await evt.respond(content)
def split_title_year(self, message : str) -> (str, int): def split_title_year(self, message: str) -> (str, int):
m = re.search(r'^(.*) (y:\d\d\d\d)', message) m = re.search(r'^(.*) (y:\d\d\d\d)', message)
if m: if m:
title = m.group(1) title = m.group(1)
@ -117,12 +117,12 @@ class TmdbBot(Plugin):
return (title, year) return (title, year)
return (message, None) return (message, None)
def set_language(self, evt: MessageEvent, movie : TmdbApi): def set_language(self, evt: MessageEvent, movie: TmdbApi):
language = self.db.get_language(evt.sender) language = self.db.get_language(evt.sender)
if language: if language:
movie.set_language(language) movie.set_language(language)
def poster_size(self, evt: MessageEvent, movie : TmdbApi): def poster_size(self, evt: MessageEvent, movie: TmdbApi):
size = self.db.get_poster_size(evt.sender) size = self.db.get_poster_size(evt.sender)
if size: if size:
movie.set_poster_size(size) movie.set_poster_size(size)
@ -159,8 +159,8 @@ class TmdbBot(Plugin):
await self.send_movie_info(evt, movie) await self.send_movie_info(evt, movie)
else: else:
content = TextMessageEventContent( content = TextMessageEventContent(
msgtype=MessageType.NOTICE, format=Format.HTML, msgtype=MessageType.NOTICE, format=Format.HTML,
body=f"No movie found!") body=f"No movie found!")
await evt.respond(content) await evt.respond(content)
@command.new("movie-search", help="Movie lookup by Title") @command.new("movie-search", help="Movie lookup by Title")
@ -171,8 +171,8 @@ class TmdbBot(Plugin):
async def movie_language(self, evt: MessageEvent, message: str = "") -> None: async def movie_language(self, evt: MessageEvent, message: str = "") -> None:
self.db.set_language(evt.sender, message) self.db.set_language(evt.sender, message)
content = TextMessageEventContent( content = TextMessageEventContent(
msgtype=MessageType.NOTICE, format=Format.HTML, msgtype=MessageType.NOTICE, format=Format.HTML,
body=f"Language set to {message}!") body=f"Language set to {message}!")
await evt.respond(content) await evt.respond(content)
async def set_poster_size(self, evt: MessageEvent, message: str = None) -> None: async def set_poster_size(self, evt: MessageEvent, message: str = None) -> None:

View file

@ -15,6 +15,7 @@ along with tmdb-bot. If not, see <https://www.gnu.org/licenses/>.
''' '''
import requests import requests
class TmdbApi(): class TmdbApi():
def __init__(self): def __init__(self):
self.load_parameters() self.load_parameters()
@ -27,23 +28,22 @@ class TmdbApi():
self.language = 'en' self.language = 'en'
self.valid = False self.valid = False
def load_parameters(self): def load_parameters(self):
self.api_key = '51d75c00dc1502dc894b7773ec3e7a15' self.api_key = '51d75c00dc1502dc894b7773ec3e7a15'
self.base_url = "https://api.themoviedb.org/3/" self.base_url = "https://api.themoviedb.org/3/"
result = requests.get(self.base_url + 'configuration', params = self.get_apikey()).json() result = requests.get(self.base_url + 'configuration', params=self.get_apikey()).json()
self.base_url_images = result['images']['base_url'] self.base_url_images = result['images']['base_url']
self.base_url_poster = self.base_url_images + result['images']['poster_sizes'][0] self.base_url_poster = self.base_url_images + result['images']['poster_sizes'][0]
self.poster_sizes = result['images']['poster_sizes'] self.poster_sizes = result['images']['poster_sizes']
def get_apikey(self): def get_apikey(self):
return { 'api_key' : self.api_key } return {'api_key': self.api_key}
def request(self, request_uri, params : dict = {}): def request(self, request_uri, params: dict = {}):
url = self.base_url + request_uri.lstrip('/') url = self.base_url + request_uri.lstrip('/')
params.update(self.get_apikey()) params.update(self.get_apikey())
params.update({ 'language' : self.language }) params.update({'language': self.language})
result = requests.get(url, params=params) result = requests.get(url, params=params)
self.valid = True self.valid = True
return result return result
@ -56,7 +56,7 @@ class TmdbApi():
return requests.get(self.poster_url).content return requests.get(self.poster_url).content
else: else:
return None return None
def set_poster_size(self, size): def set_poster_size(self, size):
for x in self.poster_sizes: for x in self.poster_sizes:
if x == size: if x == size:
@ -68,8 +68,8 @@ class TmdbApi():
class Movie(TmdbApi): class Movie(TmdbApi):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
def search_title(self, title : str, year: int = None) -> int: def search_title(self, title: str, year: int = None) -> int:
payload = {} payload = {}
payload['query'] = title payload['query'] = title
if year: if year:
@ -90,13 +90,13 @@ class Movie(TmdbApi):
self.web_url = 'https://www.themoviedb.org/movie/' + str(self.id) self.web_url = 'https://www.themoviedb.org/movie/' + str(self.id)
self.vote_average = str(data['vote_average']) self.vote_average = str(data['vote_average'])
self.query_cast() self.query_cast()
def query_cast(self): def query_cast(self):
data = self.request('movie/'+str(self.id)+'/credits').json() data = self.request('movie/' + str(self.id) + '/credits').json()
self.cast = [] self.cast = []
for actor in data['cast']: for actor in data['cast']:
self.cast.append(actor['name']) self.cast.append(actor['name'])
def get_cast(self, amount): def get_cast(self, amount):
return self.cast[:amount] return self.cast[:amount]
@ -104,7 +104,7 @@ class Movie(TmdbApi):
class TvShow(TmdbApi): class TvShow(TmdbApi):
def __init__(self): def __init__(self):
super().__init__() super().__init__()
def search_title(self, title): def search_title(self, title):
payload = {} payload = {}
payload['query'] = title payload['query'] = title
@ -124,12 +124,12 @@ class TvShow(TmdbApi):
self.web_url = 'https://www.themoviedb.org/tv/' + str(self.id) self.web_url = 'https://www.themoviedb.org/tv/' + str(self.id)
self.vote_average = str(data['vote_average']) self.vote_average = str(data['vote_average'])
self.query_cast() self.query_cast()
def query_cast(self): def query_cast(self):
data = self.request('tv/'+str(self.id)+'/credits').json() data = self.request('tv/' + str(self.id) + '/credits').json()
self.cast = [] self.cast = []
for actor in data['cast']: for actor in data['cast']:
self.cast.append(actor['name']) self.cast.append(actor['name'])
def get_cast(self, amount): def get_cast(self, amount):
return self.cast[:amount] return self.cast[:amount]