bazarr/libs/subliminal_patch/providers/sucha.py

189 lines
6.0 KiB
Python
Raw Normal View History

2020-09-30 17:39:25 +00:00
# -*- coding: utf-8 -*-
2020-10-11 19:40:07 +00:00
import io
2020-09-30 17:39:25 +00:00
import logging
import os
import zipfile
2020-10-11 19:40:07 +00:00
import rarfile
2020-09-30 17:39:25 +00:00
from requests import Session
from guessit import guessit
2020-10-11 19:40:07 +00:00
from subliminal import Episode, Movie
2020-09-30 17:39:25 +00:00
from subliminal.exceptions import ServiceUnavailable
2020-10-11 19:40:07 +00:00
from subliminal.subtitle import SUBTITLE_EXTENSIONS, fix_line_ending
from subliminal_patch.exceptions import APIThrottled
2020-09-30 17:39:25 +00:00
from subliminal_patch.providers import Provider
from subliminal_patch.subtitle import Subtitle, guess_matches
2020-10-11 19:40:07 +00:00
from subzero.language import Language
2020-09-30 17:39:25 +00:00
logger = logging.getLogger(__name__)
2020-12-03 18:23:52 +00:00
server_url = "http://sapidb.caretas.club/"
2020-09-30 17:39:25 +00:00
page_url = "https://sucha.caretas.club/"
class SuchaSubtitle(Subtitle):
provider_name = "sucha"
hash_verifiable = False
def __init__(
2020-10-11 19:40:07 +00:00
self,
language,
2020-12-03 18:23:52 +00:00
release_info,
2020-10-11 19:40:07 +00:00
filename,
2020-12-03 18:23:52 +00:00
download_id,
download_type,
2020-10-11 19:40:07 +00:00
matches,
2020-09-30 17:39:25 +00:00
):
super(SuchaSubtitle, self).__init__(
2020-12-03 18:23:52 +00:00
language, hearing_impaired=False, page_link=page_url
2020-09-30 17:39:25 +00:00
)
2020-12-03 18:23:52 +00:00
self.download_id = download_id
self.download_type = download_type
2020-09-30 17:39:25 +00:00
self.language = language
2020-12-03 18:23:52 +00:00
self.guessed_release_info = release_info
2020-09-30 17:39:25 +00:00
self.filename = filename
2020-12-03 18:23:52 +00:00
self.release_info = (
release_info if len(release_info) > len(filename) else filename
)
2020-09-30 17:39:25 +00:00
self.found_matches = matches
@property
def id(self):
2020-12-03 18:23:52 +00:00
return self.download_id
2020-09-30 17:39:25 +00:00
def get_matches(self, video):
2020-12-03 18:23:52 +00:00
self.found_matches |= guess_matches(
video,
guessit(
self.filename,
{"type": "episode" if isinstance(video, Episode) else "movie"},
),
)
self.found_matches |= guess_matches(
video,
guessit(
self.guessed_release_info,
{"type": "episode" if isinstance(video, Episode) else "movie"},
),
)
2020-09-30 17:39:25 +00:00
return self.found_matches
class SuchaProvider(Provider):
"""Sucha Provider"""
languages = {Language.fromalpha2(l) for l in ["es"]}
language_list = list(languages)
video_types = (Episode, Movie)
def initialize(self):
self.session = Session()
self.session.headers = {
"User-Agent": os.environ.get("SZ_USER_AGENT", "Sub-Zero/2")
}
def terminate(self):
self.session.close()
def query(self, languages, video):
2020-12-03 18:23:52 +00:00
movie_year = video.year if video.year else "0"
is_episode = isinstance(video, Episode)
2020-09-30 17:39:25 +00:00
language = self.language_list[0]
if is_episode:
q = {
"query": "{} S{:02}E{:02}".format(
video.series, video.season, video.episode
)
}
else:
2020-12-03 18:23:52 +00:00
q = {"query": video.title, "year": movie_year}
2020-09-30 17:39:25 +00:00
logger.debug("Searching subtitles: {}".format(q["query"]))
2020-12-03 18:23:52 +00:00
res = self.session.get(
server_url + ("episode" if is_episode else "movie"), params=q, timeout=10
)
2020-09-30 17:39:25 +00:00
res.raise_for_status()
result = res.json()
2020-12-03 21:36:32 +00:00
subtitles = []
for i in result:
matches = set()
try:
2020-12-03 18:23:52 +00:00
if (
video.title.lower() in i["title"].lower()
or video.title.lower() in i["alt_title"].lower()
):
2020-09-30 17:39:25 +00:00
matches.add("title")
2020-12-03 21:36:32 +00:00
except TypeError:
logger.debug("No subtitles found")
return []
if is_episode:
if (
q["query"].lower() in i["title"].lower()
or q["query"].lower() in i["alt_title"].lower()
):
matches.add("title")
matches.add("series")
matches.add("season")
matches.add("episode")
2020-09-30 17:39:25 +00:00
matches.add("year")
2020-12-03 21:36:32 +00:00
if str(i["year"]) == video.year:
matches.add("year")
subtitles.append(
SuchaSubtitle(
language,
i["release"],
i["filename"],
str(i["id"]),
"episode" if is_episode else "movie",
matches,
2020-09-30 17:39:25 +00:00
)
2020-12-03 21:36:32 +00:00
)
return subtitles
2020-09-30 17:39:25 +00:00
def list_subtitles(self, video, languages):
return self.query(languages, video)
def _check_response(self, response):
if response.status_code != 200:
raise ServiceUnavailable("Bad status code: " + str(response.status_code))
def _get_archive(self, content):
archive_stream = io.BytesIO(content)
if rarfile.is_rarfile(archive_stream):
logger.debug("Identified rar archive")
archive = rarfile.RarFile(archive_stream)
elif zipfile.is_zipfile(archive_stream):
logger.debug("Identified zip archive")
archive = zipfile.ZipFile(archive_stream)
else:
raise APIThrottled("Unsupported compressed format")
return archive
def get_file(self, archive):
for name in archive.namelist():
if os.path.split(name)[-1].startswith("."):
continue
if not name.lower().endswith(SUBTITLE_EXTENSIONS):
continue
if (
"[eng]" in name.lower()
or ".en." in name.lower()
or ".eng." in name.lower()
):
continue
logger.debug("Returning from archive: {}".format(name))
return archive.read(name)
raise APIThrottled("Can not find the subtitle in the compressed file")
def download_subtitle(self, subtitle):
logger.info("Downloading subtitle %r", subtitle)
response = self.session.get(
2020-12-03 18:23:52 +00:00
server_url + "download",
params={"id": subtitle.download_id, "type": subtitle.download_type},
timeout=10,
2020-09-30 17:39:25 +00:00
)
response.raise_for_status()
self._check_response(response)
archive = self._get_archive(response.content)
subtitle_file = self.get_file(archive)
subtitle.content = fix_line_ending(subtitle_file)