bazarr/custom_libs/subliminal_patch/providers/subdivx.py

346 lines
10 KiB
Python
Raw Normal View History

2019-05-25 15:40:52 +00:00
# -*- coding: utf-8 -*-
2019-09-17 02:04:27 +00:00
from __future__ import absolute_import
2024-02-23 07:25:20 +00:00
from json import JSONDecodeError
2019-05-25 15:40:52 +00:00
import logging
2024-02-23 07:25:20 +00:00
import random
2021-03-28 18:32:21 +00:00
import re
2019-05-25 15:40:52 +00:00
from requests import Session
from subliminal import __short_version__
from subliminal.video import Episode
from subliminal.video import Movie
from subliminal_patch.exceptions import APIThrottled
from subliminal_patch.providers import Provider
from subliminal_patch.providers.utils import get_archive_from_bytes
from subliminal_patch.providers.utils import get_subtitle_from_archive
from subliminal_patch.providers.utils import update_matches
2024-02-23 07:25:20 +00:00
from subliminal_patch.providers.utils import USER_AGENTS
from subliminal_patch.subtitle import Subtitle
from subzero.language import Language
2019-05-25 15:40:52 +00:00
_SERVER_URL = "https://www.subdivx.com"
2021-03-28 18:32:21 +00:00
_CLEAN_TITLE_RES = [
2021-03-28 18:32:21 +00:00
(r"subt[ií]tulos de", ""),
(r"´|`", "'"),
(r" {2,}", " "),
]
_SPANISH_RE = re.compile(r"españa|ib[eé]rico|castellano|gallego|castilla|europ[ae]")
2021-12-30 19:41:16 +00:00
_YEAR_RE = re.compile(r"(\(\d{4}\))")
_YEAR_RE_INT = re.compile(r"\((\d{4})\)")
_SERIES_RE = re.compile(
r"\(?\d{4}\)?|(s\d{1,2}(e\d{1,2})?|(season|temporada)\s\d{1,2}).*?$",
flags=re.IGNORECASE,
)
_EPISODE_NUM_RE = re.compile(r"[eE](?P<x>\d{1,2})")
_SEASON_NUM_RE = re.compile(
r"(s|(season|temporada)\s)(?P<x>\d{1,2})", flags=re.IGNORECASE
)
_EPISODE_YEAR_RE = re.compile(r"\((?P<x>(19\d{2}|20[0-2]\d))\)")
2024-02-23 07:25:20 +00:00
_UNSUPPORTED_RE = re.compile(r"(extras|forzado(s)?|forced)\s?$", flags=re.IGNORECASE)
2021-12-30 19:41:16 +00:00
2019-05-25 15:40:52 +00:00
logger = logging.getLogger(__name__)
class SubdivxSubtitle(Subtitle):
2021-01-25 21:18:32 +00:00
provider_name = "subdivx"
2019-05-25 15:40:52 +00:00
hash_verifiable = False
def __init__(
self, language, video, page_link, title, description, uploader, download_url
):
2021-01-25 21:18:32 +00:00
super(SubdivxSubtitle, self).__init__(
language, hearing_impaired=False, page_link=page_link
)
self.video = video
2022-06-21 05:44:24 +00:00
self.download_url = download_url
self.uploader = uploader
2022-06-21 05:44:24 +00:00
self._title = str(title).strip()
self._description = str(description).strip()
self.release_info = self._title
2022-06-21 05:44:24 +00:00
if self._description:
self.release_info += " | " + self._description
2019-05-25 15:40:52 +00:00
@property
def id(self):
2019-09-21 12:09:11 +00:00
return self.page_link
2019-05-25 15:40:52 +00:00
def get_matches(self, video):
matches = set()
# episode
if isinstance(video, Episode):
# already matched within provider
2024-02-23 07:25:20 +00:00
matches.update(["title", "series", "season", "episode", "year"])
2019-05-25 15:40:52 +00:00
# movie
elif isinstance(video, Movie):
# already matched within provider
2024-02-23 07:25:20 +00:00
matches.update(["title", "year"])
2021-01-25 21:18:32 +00:00
update_matches(matches, video, self._description)
2019-05-25 15:40:52 +00:00
# Don't lowercase; otherwise it will match a lot of false positives
if video.release_group and video.release_group in self._description:
matches.add("release_group")
2019-05-25 15:40:52 +00:00
return matches
_IDUSER_COOKIE = "VkZaRk9WQlJQVDA12809"
2019-05-25 15:40:52 +00:00
class SubdivxSubtitlesProvider(Provider):
2021-01-25 21:18:32 +00:00
provider_name = "subdivx"
2019-05-25 15:40:52 +00:00
hash_verifiable = False
languages = {Language("spa", "MX")} | {Language.fromalpha2("es")}
video_types = (Episode, Movie)
2019-05-25 15:40:52 +00:00
subtitle_class = SubdivxSubtitle
multi_result_throttle = 2
def __init__(self):
2024-02-23 07:25:20 +00:00
self.session = Session()
2019-05-25 15:40:52 +00:00
def initialize(self):
2024-02-23 07:25:20 +00:00
# self.session.headers["User-Agent"] = f"Subliminal/{__short_version__}"
self.session.headers["User-Agent"] = random.choice(USER_AGENTS)
self.session.cookies.update({"iduser_cookie": _IDUSER_COOKIE})
2019-05-25 15:40:52 +00:00
def terminate(self):
self.session.close()
2024-02-23 07:25:20 +00:00
def _query(self, video, languages):
subtitles = []
2024-02-23 07:25:20 +00:00
episode = isinstance(video, Episode)
2024-02-23 07:25:20 +00:00
titles = [video.series if episode else video.title]
2024-02-23 07:25:20 +00:00
try:
titles.extend(video.alternative_titles)
except:
pass
else:
2024-02-23 07:25:20 +00:00
titles = titles[:5] # limit alt titles
2024-02-23 07:25:20 +00:00
logger.debug("Titles to look at: %s", titles)
2019-05-25 15:40:52 +00:00
2024-02-23 07:25:20 +00:00
if episode:
# TODO: cache pack queries (TV SHOW S01).
# Too many redundant server calls.
for title in titles:
for query in (
f"{title} S{video.season:02}E{video.episode:02}",
f"{title} S{video.season:02}",
):
subtitles += self._query_results(query, video)
# Try only with series title
if len(subtitles) <= 5:
subtitles += self._query_results(title, video)
else:
break
# Try with episode title as last resort
if not subtitles and video.title and video.title != title:
subtitles += self._query_results(video.title, video)
2019-05-25 15:40:52 +00:00
2024-02-23 07:25:20 +00:00
else:
for title in titles:
for query in (title, f"{title} ({video.year})"):
subtitles += self._query_results(query, video)
# Second query is a fallback
if subtitles:
break
2019-05-25 15:40:52 +00:00
return subtitles
2019-05-25 15:40:52 +00:00
2024-02-23 07:25:20 +00:00
def _query_results(self, query, video):
search_link = f"{_SERVER_URL}/inc/ajax.php"
2024-02-23 07:25:20 +00:00
payload = {"tabla": "resultados", "filtros": "", "buscar": query}
logger.debug("Query: %s", query)
2024-02-23 07:25:20 +00:00
response = self.session.post(search_link, data=payload)
2024-02-23 07:25:20 +00:00
if response.status_code == 500:
2024-02-23 07:25:20 +00:00
logger.debug(
"Error 500 (probably bad encoding of query causing issue on provider side): %s",
query,
)
return []
# Ensure it was successful
response.raise_for_status()
2019-05-25 15:40:52 +00:00
# Processing the JSON result
subtitles = []
2024-02-23 07:25:20 +00:00
try:
data = response.json()
except JSONDecodeError:
logger.debug("JSONDecodeError: %s", response.content)
return []
title_checker = _check_episode if isinstance(video, Episode) else _check_movie
# Iterate over each subtitle in the response
2024-02-23 07:25:20 +00:00
for item in data["aaData"]:
id = item["id"]
page_link = f"{_SERVER_URL}/descargar.php?id={id}"
title = _clean_title(item["titulo"])
description = item["descripcion"]
uploader = item["nick"]
download_url = f"{_SERVER_URL}/descargar.php?id={id}"
2024-02-23 07:25:20 +00:00
if _UNSUPPORTED_RE.search(title) is not None:
logger.debug("Skipping unsupported subtitles: %s", title)
continue
2019-05-25 15:40:52 +00:00
2024-02-23 07:25:20 +00:00
if not title_checker(video, title):
continue
2024-02-23 07:25:20 +00:00
spain = _SPANISH_RE.search(description.lower()) is not None
language = Language.fromalpha2("es") if spain else Language("spa", "MX")
2024-02-23 07:25:20 +00:00
subtitle = self.subtitle_class(
language, video, page_link, title, description, uploader, download_url
)
logger.debug("Found subtitle %r", subtitle)
subtitles.append(subtitle)
2024-02-23 07:25:20 +00:00
return subtitles
2019-05-25 15:40:52 +00:00
def list_subtitles(self, video, languages):
2024-02-23 07:25:20 +00:00
return self._query(video, languages)
2019-05-25 15:40:52 +00:00
def download_subtitle(self, subtitle):
# download the subtitle
logger.debug("Downloading subtitle %r", subtitle)
2019-09-21 12:09:11 +00:00
response = self.session.get(
subtitle.download_url,
headers={"Referer": _SERVER_URL},
timeout=30,
)
response.raise_for_status()
2019-05-25 15:40:52 +00:00
# TODO: add MustGetBlacklisted support
archive = get_archive_from_bytes(response.content)
if archive is None:
raise APIThrottled("Unknwon compressed format")
episode = None
if isinstance(subtitle.video, Episode):
episode = subtitle.video.episode
2019-05-25 15:40:52 +00:00
2024-02-23 07:25:20 +00:00
logger.debug("Episode number: %s", episode)
subtitle.content = get_subtitle_from_archive(archive, episode=episode)
2020-10-03 23:41:41 +00:00
def _clean_title(title):
"""
Normalize apostrophes and spaces to avoid matching problems
(e.g. Subtitulos de Carlito´s Way -> Carlito's Way)
"""
for og, new in _CLEAN_TITLE_RES:
title = re.sub(og, new, title, flags=re.IGNORECASE)
return title
def _check_episode(video, title):
ep_num = _EPISODE_NUM_RE.search(title)
season_num = _SEASON_NUM_RE.search(title)
year = _EPISODE_YEAR_RE.search(title)
# Only check if both video and Subdivx's title have year metadata
if year is not None and video.year:
year = int(year.group("x"))
2024-02-23 07:25:20 +00:00
# Tolerancy of 1 year difference
if abs(year - (video.year or 0)) > 1:
logger.debug("Series year doesn't match: %s", title)
return False
# Include matches where the episode title is present
2024-02-23 07:25:20 +00:00
if (
video.series.lower() in title.lower()
and (video.title or "").lower() in title.lower()
):
logger.debug("Episode title found in title: %s ~ %s", video.title, title)
return True
if season_num is None:
logger.debug("Not a season/episode: %s", title)
return False
season_num = int(season_num.group("x"))
if ep_num is not None:
ep_num = int(ep_num.group("x"))
ep_matches = (
(video.episode == ep_num) or (ep_num is None)
) and season_num == video.season
series_title = _SERIES_RE.sub("", title).strip()
distance = abs(len(series_title) - len(video.series))
2024-02-23 07:25:20 +00:00
series_matched = distance < 4 and ep_matches
logger.debug(
"Series matched? %s [%s -> %s] [title distance: %d]",
series_matched,
video,
title,
distance,
)
return series_matched
2021-12-30 19:41:16 +00:00
def _check_movie(video, title):
try:
year = int(_YEAR_RE_INT.search(title).group(1)) # type: ignore
except (AttributeError, ValueError):
logger.debug("Year not found in title (%s). Discarding movie", title)
return False
if video.year and abs(year - video.year) > 1:
logger.debug("Year not matching: %s -> %s", year, video.year)
2021-12-30 19:41:16 +00:00
return False
aka_split = re.split("aka", title, flags=re.IGNORECASE)
alt_title = None
if len(aka_split) == 2:
alt_title = aka_split[-1].strip()
try:
actual_movie_title = _YEAR_RE.split(title)[0].strip()
except IndexError:
return False
all_titles = [
v_title.lower() for v_title in [video.title, *video.alternative_titles]
]
return (
actual_movie_title.lower() in all_titles
or (alt_title or "").lower() in all_titles
)