* Parse imdb\kinopoisk limited
* Кинопоиск всегда пытается резолвится через imdb базу
* Improve append message
This commit is contained in:
localhost_frssoft 2022-09-04 02:32:25 +03:00
parent 012841dda2
commit f46235ae22
3 changed files with 48 additions and 31 deletions

View file

@ -86,7 +86,18 @@ def convert_datasets_to_db():
def get_title_by_id(films_ids=list):
tt_list = []
for i in films_ids:
tt_film = c.execute(f"SELECT * FROM titles WHERE tt_id={i}").fetchone()
tt_film = c.execute("SELECT * FROM titles WHERE tt_id = (?)", (i,)).fetchone()
tt_list.append(tt_film)
return tt_list
def get_title_by_names_and_year(film_names=list):
tt_list = []
for i in film_names:
tt_film = c.execute('''SELECT * FROM titles
WHERE (original_name = (?) OR ru_name = (?))
AND year = (?)''', i).fetchone()
if tt_film:
tt_list.append(tt_film)
if tt_list != []:
return tt_list

View file

@ -1,3 +1,4 @@
from src.imdb_datasets_worker import get_title_by_names_and_year
import requests
import time
@ -9,7 +10,7 @@ with open(".auth_kinopoisk", mode='rt') as key_file:
token = key_file.read().replace('\n', '')
def get_kinopoisk_movie(film=list):
def get_kinopoisk_movie_to_imdb(film=list):
films_resolved = []
for i in film:
headers = {
@ -18,11 +19,13 @@ def get_kinopoisk_movie(film=list):
r = requests.get(kinopoisk_api_url + "/films/" + i, headers=headers)
if r.status_code == 200:
film_data = r.json()
films_resolved.append((film_data['type'], film_data['year'], film_data['nameOriginal'], film_data['nameRu']))
elif r.status_code in (400, 404):
films_resolved.append(("404",))
films_resolved.append((film_data['nameOriginal'], film_data['nameRu'], film_data['year']))
else:
continue
time.sleep(0.2)
return films_resolved
parsed_imdb_titles = get_title_by_names_and_year(films_resolved)
if parsed_imdb_titles != []:
return parsed_imdb_titles

View file

@ -1,6 +1,6 @@
from config import hour_poll_posting, bot_acct, instance, limit_all_movies_poll, max_fail_limit
from config import hour_poll_posting, bot_acct, instance, limit_all_movies_poll, limit_movies_per_user, max_fail_limit
from src.fedi_api import get_status_context, get_status, post_status, mute_user
from src.kinopoisk_api import get_kinopoisk_movie
from src.kinopoisk_api import get_kinopoisk_movie_to_imdb
from src.imdb_datasets_worker import get_title_by_id
from src.fmn_database import add_movie_to_poll, get_already_watched, get_suggested_movies_count
from src.fmn_states_db import get_state, add_state
@ -21,18 +21,16 @@ def parse_links(text=str):
regex = r"kinopoisk\.ru/"
if re.search(regex, text.lower(), flags=re.MULTILINE):
kinopoisk_ids = re.findall(r"film/(\d{1,})", text.lower())
return kinopoisk_ids
else:
return None
if kinopoisk_ids != []:
return kinopoisk_ids[:limit_movies_per_user]
def parse_links_imdb(text=str):
regex = r"imdb\.com/"
if re.search(regex, text.lower(), flags=re.MULTILINE):
imdb_ids = re.findall(r"tt(\d{1,})", text.lower())
return imdb_ids
else:
return None
if imdb_ids != []:
return imdb_ids[:limit_movies_per_user]
def scan_context_thread():
@ -95,26 +93,28 @@ def scan_context_thread():
fail_limit[acct] += 1
continue
if parsed_result is not None:
suggested_movies = get_kinopoisk_movie(parsed_result)
index_type = 0
index_name = 2
index_ru_name = 3
index_year = 1
elif parsed_result_imdb is not None:
suggested_movies = get_title_by_id(parsed_result_imdb)
index_type = 1
index_name = 2
index_ru_name = 3
index_year = 4
if parsed_result is not None:
print(parsed_result)
suggested_movies = get_kinopoisk_movie_to_imdb(parsed_result)
if suggested_movies is None:
post_status('Не удалось выполнить запрос: возможно некорректный тип фильма, попробуйте использовать imdb.com', id_st)
fail_limit[acct] += 1
continue
elif parsed_result_imdb is not None:
suggested_movies = get_title_by_id(parsed_result_imdb)
message_writer = []
success = False
for movie in suggested_movies:
logger.debug(str(movie))
if movie[index_type] == "404":
message_writer.append("Не найдено.")
fail_limit[acct] += 1
elif movie[index_type] not in ("movie", "FILM", "video"):
elif movie[index_type] not in ("movie", "video"):
type_of_title = movie[index_type]
message_writer.append(f"Не принято:\n- Нам не подходят: сериалы, короткометражные и документальные фильмы")
logger.info(f'Предложение {acct} отклонено: не подходящий тип фильма: {type_of_title}')
@ -147,20 +147,23 @@ def scan_context_thread():
continue
add_result = add_movie_to_poll(acct, name, name_ru, year)
if add_result == 0:
message_writer.append(f"✅ Принято: {movie_string}")
logger.info(f'Предложение от {acct} принято: {name} {name_ru} {year}')
success = True
elif add_result == 1:
post_status("❌ Этот фильм уже был предложен", id_st)
message_writer.append("❌ Этот фильм уже был предложен")
logger.info(f'Предложение от {acct} было отлонено - фильм в опросе существует')
fail_limit[acct] += 1
else:
post_status("❌ Вы не можете добавить больше 2х фильмов", id_st)
message_writer.append("❌ Вы не можете добавить больше 2х фильмов")
logger.info(f'Предложение от {acct} было отлонено - лимит на пользователя')
fail_limit[acct] += 1
if message_writer != []:
post_status('\n'.join(message_writer) + "\nБлагодарим за ваше предложение!", id_st)
message = ''
if success:
message = "\nБлагодарим за ваше предложение!"
post_status('\n'.join(message_writer) + message, id_st)
time.sleep(30)