You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
279 lines
9.3 KiB
279 lines
9.3 KiB
4 years ago
|
# -*- coding: utf-8 -*-
|
||
|
import logging
|
||
4 years ago
|
|
||
4 years ago
|
import re
|
||
|
|
||
4 years ago
|
from urllib import parse
|
||
|
|
||
|
from bs4 import BeautifulSoup as bso
|
||
4 years ago
|
from requests import Session
|
||
|
from subzero.language import Language
|
||
4 years ago
|
from guessit import guessit
|
||
4 years ago
|
|
||
|
from subliminal import Episode
|
||
4 years ago
|
from subliminal.cache import SHOW_EXPIRATION_TIME, region, EPISODE_EXPIRATION_TIME
|
||
4 years ago
|
from subliminal.exceptions import ServiceUnavailable
|
||
4 years ago
|
from subliminal_patch.exceptions import APIThrottled
|
||
4 years ago
|
from subliminal_patch.providers import Provider
|
||
4 years ago
|
from subliminal_patch.subtitle import Subtitle, guess_matches
|
||
|
from subliminal.subtitle import fix_line_ending
|
||
4 years ago
|
|
||
4 years ago
|
logger = logging.getLogger(__name__)
|
||
|
|
||
|
|
||
4 years ago
|
_EP_NUM_PATTERN = re.compile(r".*\d+x(0+)?(\d+) - .*?")
|
||
|
_CSS1 = "span.iconos-subtitulos"
|
||
|
_CSS2 = "ul > li.rng.download.green > a.fas.fa-bullhorn.notifi_icon"
|
||
|
|
||
4 years ago
|
BASE_URL = "https://www.tusubtitulo.com"
|
||
4 years ago
|
|
||
4 years ago
|
|
||
|
|
||
|
class TuSubtituloSubtitle(Subtitle):
|
||
|
provider_name = "tusubtitulo"
|
||
4 years ago
|
hash_verifiable = False
|
||
4 years ago
|
|
||
4 years ago
|
def __init__(self, language, sub_dict, matches):
|
||
4 years ago
|
super(TuSubtituloSubtitle, self).__init__(
|
||
4 years ago
|
language, hearing_impaired=False, page_link=sub_dict["download_url"]
|
||
4 years ago
|
)
|
||
|
self.language = language
|
||
4 years ago
|
self.sub_dict = sub_dict
|
||
|
self.release_info = sub_dict["metadata"]
|
||
4 years ago
|
self.found_matches = matches
|
||
|
|
||
|
@property
|
||
|
def id(self):
|
||
4 years ago
|
return self.sub_dict["download_url"]
|
||
4 years ago
|
|
||
|
def get_matches(self, video):
|
||
4 years ago
|
self.found_matches |= guess_matches(
|
||
|
video,
|
||
|
guessit(
|
||
|
self.release_info,
|
||
|
{"type": "episode"},
|
||
|
),
|
||
|
)
|
||
4 years ago
|
return self.found_matches
|
||
|
|
||
|
|
||
|
class TuSubtituloProvider(Provider):
|
||
|
"""TuSubtitulo.com Provider"""
|
||
|
|
||
4 years ago
|
languages = {Language.fromietf(lang) for lang in ["en", "es"]} | {
|
||
|
Language("spa", "MX")
|
||
|
}
|
||
4 years ago
|
logger.debug(languages)
|
||
|
video_types = (Episode,)
|
||
|
|
||
|
def initialize(self):
|
||
|
self.session = Session()
|
||
|
self.session.headers = {
|
||
4 years ago
|
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36",
|
||
4 years ago
|
"referer": BASE_URL,
|
||
4 years ago
|
}
|
||
|
|
||
|
def terminate(self):
|
||
|
self.session.close()
|
||
|
|
||
4 years ago
|
def _index_titles(self):
|
||
4 years ago
|
r = self.session.get(f"{BASE_URL}/series.php?/")
|
||
4 years ago
|
r.raise_for_status()
|
||
|
soup = bso(r.content, "html.parser")
|
||
4 years ago
|
|
||
4 years ago
|
for a in soup.find_all("a"):
|
||
|
href_url = a.get("href")
|
||
|
if "show" in href_url:
|
||
4 years ago
|
yield {"title": a.text, "url": href_url}
|
||
4 years ago
|
|
||
4 years ago
|
@staticmethod
|
||
|
def _title_available(item):
|
||
4 years ago
|
try:
|
||
4 years ago
|
title = item[2].find_all("a")[0]
|
||
4 years ago
|
episode_number = _EP_NUM_PATTERN.search(title.text).group(2)
|
||
|
# episode_number = re.search(r".*\d+x(0+)?(\d+) - .*?", title.text).group(2)
|
||
4 years ago
|
episode_id = title.get("href").split("/")[4]
|
||
|
return {"episode_number": episode_number, "episode_id": episode_id}
|
||
4 years ago
|
except IndexError:
|
||
|
return
|
||
|
|
||
4 years ago
|
@staticmethod
|
||
|
def _source_separator(item):
|
||
4 years ago
|
try:
|
||
|
text = item[3].text.replace("\n", "")
|
||
|
if "Vers" in text:
|
||
|
source = text.replace("Versión ", "")
|
||
|
if not source:
|
||
4 years ago
|
return "Unknown"
|
||
4 years ago
|
return source
|
||
|
except IndexError:
|
||
|
return
|
||
|
|
||
4 years ago
|
@staticmethod
|
||
|
def _get_episode_dicts(episodes, season_subs, season_number):
|
||
4 years ago
|
for i in episodes:
|
||
|
for t in season_subs:
|
||
|
if i["episode_id"] == t["episode_id"]:
|
||
|
yield {
|
||
|
"episode": i["episode_number"],
|
||
|
"season": season_number,
|
||
|
"metadata": t["metadata"],
|
||
|
"download_url": t["download_url"],
|
||
|
"language": t["language"],
|
||
|
}
|
||
|
|
||
4 years ago
|
@staticmethod
|
||
|
def _scrape_episode_info(source_var, tables, tr):
|
||
4 years ago
|
inc = 1
|
||
|
while True:
|
||
|
try:
|
||
|
content = tables[tr + inc].find_all("td")
|
||
|
|
||
4 years ago
|
language = content[4].text.lower()
|
||
|
if "eng" in language:
|
||
|
language = Language.fromietf("en")
|
||
|
elif "lat" in language:
|
||
|
language = Language("spa", "MX")
|
||
|
elif "esp" in language:
|
||
|
language = Language.fromietf("es")
|
||
4 years ago
|
else:
|
||
|
language = None
|
||
|
|
||
|
completed = "%" not in content[5].text
|
||
|
download_url = (
|
||
3 years ago
|
parse.unquote(content[6].find_all("a")[1].get("href").split("?sub=")[-1])
|
||
4 years ago
|
)
|
||
|
episode_id = download_url.split("/")[4]
|
||
|
|
||
|
if language and completed:
|
||
|
yield {
|
||
|
"episode_id": episode_id,
|
||
|
"metadata": source_var,
|
||
|
"download_url": download_url,
|
||
|
"language": language,
|
||
|
}
|
||
|
inc += 1
|
||
|
except IndexError:
|
||
|
break
|
||
|
|
||
4 years ago
|
@region.cache_on_arguments(expiration_time=EPISODE_EXPIRATION_TIME)
|
||
|
def _get_episodes(self, show_id, season):
|
||
4 years ago
|
r = self.session.get(f"{BASE_URL}/show/{show_id}/{season}")
|
||
|
r.raise_for_status()
|
||
|
sopa = bso(r.content, "lxml")
|
||
4 years ago
|
tables = sopa.find_all("tr")
|
||
|
seasons = [i.text for i in tables[1].find_all("a")]
|
||
4 years ago
|
|
||
|
if not any(season == season_ for season_ in seasons):
|
||
4 years ago
|
return
|
||
4 years ago
|
|
||
4 years ago
|
season_subs = []
|
||
|
episodes = []
|
||
|
|
||
|
for tr in range(len(tables)):
|
||
|
data = tables[tr].find_all("td")
|
||
4 years ago
|
|
||
4 years ago
|
title = self._title_available(data)
|
||
4 years ago
|
if title:
|
||
|
episodes.append(title)
|
||
4 years ago
|
|
||
4 years ago
|
source_var = self._source_separator(data)
|
||
4 years ago
|
if not source_var:
|
||
|
continue
|
||
|
|
||
4 years ago
|
season_subs += list(self._scrape_episode_info(source_var, tables, tr))
|
||
|
|
||
|
return list(self._get_episode_dicts(episodes, season_subs, season))
|
||
4 years ago
|
|
||
4 years ago
|
@region.cache_on_arguments(expiration_time=SHOW_EXPIRATION_TIME)
|
||
|
def _get_title(self, title):
|
||
|
titles = list(self._index_titles())
|
||
|
for item in titles:
|
||
|
if title.lower() == item["title"].lower():
|
||
|
return item
|
||
4 years ago
|
|
||
|
def search(self, title, season, episode):
|
||
4 years ago
|
found_tv_show = self._get_title(title)
|
||
4 years ago
|
if not found_tv_show:
|
||
4 years ago
|
logger.debug("Title not found: %s", title)
|
||
4 years ago
|
return
|
||
4 years ago
|
|
||
4 years ago
|
tv_show_id = found_tv_show["url"].split("/")[2].replace(" ", "")
|
||
4 years ago
|
results = self._get_episodes(tv_show_id, season)
|
||
4 years ago
|
episode_list = []
|
||
|
if results:
|
||
|
for i in results:
|
||
4 years ago
|
if i["episode"] == episode:
|
||
4 years ago
|
episode_list.append(i)
|
||
|
if episode_list:
|
||
|
return episode_list
|
||
4 years ago
|
|
||
|
logger.debug("No results")
|
||
|
|
||
|
def scrape_download_url(self, episode_dict):
|
||
|
logger.debug("Scrapping download URL")
|
||
|
r = self.session.get(episode_dict["download_url"])
|
||
|
r.raise_for_status()
|
||
|
|
||
|
discriminator = f".{episode_dict['season']}.{episode_dict['episode']}."
|
||
|
soup = bso(r.content, "lxml")
|
||
|
|
||
4 years ago
|
for url, selected in zip(soup.select(_CSS1), soup.select(_CSS2)):
|
||
3 years ago
|
meta = parse.unquote(".".join(
|
||
4 years ago
|
selected.get("href").split(discriminator)[-1].split(".")[:-1]
|
||
3 years ago
|
))
|
||
4 years ago
|
if meta in episode_dict["download_url"]:
|
||
|
|
||
|
id_url = url.find_all("a")[0].get("href")
|
||
|
sub_id = parse.parse_qs(parse.urlparse(id_url).query)["id"][0]
|
||
|
lang_id = parse.parse_qs(parse.urlparse(id_url).query)["lang"][0]
|
||
|
version_ = parse.parse_qs(parse.urlparse(id_url).query)["fversion"][0]
|
||
|
|
||
|
return f"{BASE_URL}/updated/{lang_id}/{sub_id}/{version_}"
|
||
4 years ago
|
|
||
4 years ago
|
def query(self, video):
|
||
4 years ago
|
query = f"{video.series} {video.season} {video.episode}"
|
||
|
logger.debug(f"Searching subtitles: {query}")
|
||
4 years ago
|
results = self.search(video.series, str(video.season), str(video.episode))
|
||
|
|
||
|
if results:
|
||
|
subtitles = []
|
||
4 years ago
|
for sub in results:
|
||
4 years ago
|
matches = set()
|
||
|
# self.search only returns results for the specific episode
|
||
4 years ago
|
matches.update(["title", "series", "season", "episode", "year"])
|
||
4 years ago
|
subtitles.append(
|
||
|
TuSubtituloSubtitle(
|
||
4 years ago
|
sub["language"],
|
||
4 years ago
|
sub,
|
||
4 years ago
|
matches,
|
||
|
)
|
||
|
)
|
||
|
return subtitles
|
||
4 years ago
|
|
||
|
logger.debug("No subtitles found")
|
||
|
return []
|
||
4 years ago
|
|
||
|
def list_subtitles(self, video, languages):
|
||
3 years ago
|
# return self.query(video)
|
||
|
|
||
|
# returning no subtitles automatically to prevent requests to the provider who explicitly requested to be
|
||
|
# removed in https://github.com/morpheus65535/bazarr/issues/1591
|
||
|
return []
|
||
4 years ago
|
|
||
4 years ago
|
@staticmethod
|
||
|
def _check_response(response):
|
||
4 years ago
|
if response.status_code != 200:
|
||
4 years ago
|
raise ServiceUnavailable(f"Bad status code: {response.status_code}")
|
||
4 years ago
|
|
||
|
def download_subtitle(self, subtitle):
|
||
|
logger.info("Downloading subtitle %r", subtitle)
|
||
4 years ago
|
download_url_ = self.scrape_download_url(subtitle.sub_dict)
|
||
|
|
||
|
if not download_url_:
|
||
|
raise APIThrottled("Can't scrape download url")
|
||
|
|
||
|
response = self.session.get(download_url_, timeout=10, allow_redirects=True)
|
||
4 years ago
|
self._check_response(response)
|
||
|
subtitle.content = fix_line_ending(response.content)
|