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.
306 lines
10 KiB
306 lines
10 KiB
5 years ago
|
# -*- coding: utf-8 -*-
|
||
|
from __future__ import absolute_import
|
||
|
import logging
|
||
|
import io
|
||
|
|
||
|
from requests import Session
|
||
4 years ago
|
from requests.adapters import HTTPAdapter
|
||
|
from requests.packages.urllib3.util.retry import Retry
|
||
|
|
||
5 years ago
|
from guessit import guessit
|
||
|
from subliminal_patch.providers import Provider
|
||
4 years ago
|
from subliminal_patch.subtitle import Subtitle, guess_matches
|
||
4 years ago
|
from subliminal_patch.exceptions import TooManyRequests
|
||
5 years ago
|
from subliminal.video import Episode, Movie
|
||
5 years ago
|
from subzero.language import Language
|
||
4 years ago
|
from subliminal.exceptions import ServiceUnavailable
|
||
5 years ago
|
|
||
|
import gzip
|
||
|
import random
|
||
|
from time import sleep
|
||
|
from xml.etree import ElementTree
|
||
|
|
||
|
logger = logging.getLogger(__name__)
|
||
|
|
||
5 years ago
|
|
||
5 years ago
|
class BSPlayerSubtitle(Subtitle):
|
||
|
"""BSPlayer Subtitle."""
|
||
4 years ago
|
provider_name = "bsplayer"
|
||
5 years ago
|
hash_verifiable = True
|
||
5 years ago
|
|
||
4 years ago
|
def __init__(self, language, filename, subtype, video, link, subid):
|
||
5 years ago
|
super(BSPlayerSubtitle, self).__init__(language)
|
||
|
self.language = language
|
||
|
self.filename = filename
|
||
|
self.page_link = link
|
||
|
self.subtype = subtype
|
||
|
self.video = video
|
||
4 years ago
|
self.subid = subid
|
||
3 years ago
|
self.release_info = filename
|
||
5 years ago
|
|
||
|
@property
|
||
|
def id(self):
|
||
4 years ago
|
return self.subid
|
||
5 years ago
|
|
||
|
def get_matches(self, video):
|
||
|
matches = set()
|
||
|
matches |= guess_matches(video, guessit(self.filename))
|
||
5 years ago
|
|
||
|
# episode
|
||
|
if isinstance(video, Episode):
|
||
|
# already matched in search query
|
||
4 years ago
|
matches.update(["title", "series", "season", "episode", "year"])
|
||
5 years ago
|
|
||
|
# movie
|
||
|
elif isinstance(video, Movie):
|
||
|
# already matched in search query
|
||
4 years ago
|
matches.update(["title", "year"])
|
||
5 years ago
|
|
||
4 years ago
|
matches.add("hash")
|
||
5 years ago
|
|
||
|
return matches
|
||
|
|
||
|
|
||
|
class BSPlayerProvider(Provider):
|
||
|
"""BSPlayer Provider."""
|
||
4 years ago
|
|
||
|
# fmt: off
|
||
5 years ago
|
languages = {Language('por', 'BR')} | {Language(l) for l in [
|
||
|
'ara', 'bul', 'ces', 'dan', 'deu', 'ell', 'eng', 'fin', 'fra', 'hun', 'ita', 'jpn', 'kor', 'nld', 'pol', 'por',
|
||
|
'ron', 'rus', 'spa', 'swe', 'tur', 'ukr', 'zho'
|
||
|
]}
|
||
3 years ago
|
video_types = (Episode, Movie)
|
||
5 years ago
|
SEARCH_THROTTLE = 8
|
||
5 years ago
|
hash_verifiable = True
|
||
4 years ago
|
# fmt: on
|
||
5 years ago
|
|
||
|
# batantly based on kodi's bsplayer plugin
|
||
|
# also took from BSPlayer-Subtitles-Downloader
|
||
|
def __init__(self):
|
||
|
self.initialize()
|
||
|
|
||
|
def initialize(self):
|
||
|
self.session = Session()
|
||
4 years ago
|
# Try to avoid bsplayer throttling increasing retries time (0, 4, 6, 8, 10)
|
||
|
retry = Retry(connect=5, backoff_factor=2)
|
||
|
adapter = HTTPAdapter(max_retries=retry)
|
||
|
self.session.mount("http://", adapter)
|
||
|
|
||
3 years ago
|
# commented out this part to prevent usage of this provider and return no subtitles
|
||
|
# self.search_url = self.get_sub_domain()
|
||
|
# self.login()
|
||
5 years ago
|
|
||
|
def terminate(self):
|
||
|
self.session.close()
|
||
|
self.logout()
|
||
|
|
||
4 years ago
|
def api_request(self, func_name="logIn", params="", tries=5):
|
||
5 years ago
|
headers = {
|
||
4 years ago
|
"User-Agent": "BSPlayer/2.x (1022.12360)",
|
||
|
"Content-Type": "text/xml; charset=utf-8",
|
||
|
"Connection": "close",
|
||
|
"SOAPAction": '"http://api.bsplayer-subtitles.com/v1.php#{func_name}"'.format(
|
||
|
func_name=func_name
|
||
|
),
|
||
5 years ago
|
}
|
||
|
data = (
|
||
|
'<?xml version="1.0" encoding="UTF-8"?>\n'
|
||
|
'<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" '
|
||
|
'xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" '
|
||
|
'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '
|
||
|
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns1="{search_url}">'
|
||
|
'<SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
|
||
4 years ago
|
"<ns1:{func_name}>{params}</ns1:{func_name}></SOAP-ENV:Body></SOAP-ENV:Envelope>"
|
||
5 years ago
|
).format(search_url=self.search_url, func_name=func_name, params=params)
|
||
4 years ago
|
logger.debug("Sending request: %s." % func_name)
|
||
5 years ago
|
for i in iter(range(tries)):
|
||
|
try:
|
||
|
self.session.headers.update(headers.items())
|
||
|
res = self.session.post(self.search_url, data)
|
||
4 years ago
|
return ElementTree.fromstring(res.text.strip())
|
||
5 years ago
|
|
||
|
except Exception as ex:
|
||
4 years ago
|
logger.error(f"Exception parsing response: {ex}")
|
||
|
if func_name == "logIn":
|
||
5 years ago
|
self.search_url = self.get_sub_domain()
|
||
5 years ago
|
|
||
5 years ago
|
sleep(1)
|
||
4 years ago
|
|
||
|
raise TooManyRequests(f"Too many retries: {tries}")
|
||
5 years ago
|
|
||
|
def login(self):
|
||
4 years ago
|
# Setting attribute here as initialize() will reset it
|
||
|
if hasattr(self, "token"):
|
||
|
logger.debug("Token already met. Skipping logging")
|
||
5 years ago
|
return True
|
||
|
|
||
|
root = self.api_request(
|
||
4 years ago
|
func_name="logIn",
|
||
|
params=(
|
||
|
"<username></username>"
|
||
|
"<password></password>"
|
||
|
"<AppID>BSPlayer v2.67</AppID>"
|
||
|
),
|
||
5 years ago
|
)
|
||
4 years ago
|
res = root.find(".//return")
|
||
|
# avoid AttributeError
|
||
|
if not res:
|
||
|
return False
|
||
|
|
||
|
if res.find("status").text == "OK":
|
||
|
self.token = res.find("data").text
|
||
|
logger.debug("Logged In Successfully.")
|
||
5 years ago
|
return True
|
||
|
return False
|
||
|
|
||
|
def logout(self):
|
||
|
# If already logged out / not logged in
|
||
4 years ago
|
# if not self.token:
|
||
|
# return True
|
||
|
if not hasattr(self, "token"):
|
||
|
logger.debug("Already logged out")
|
||
5 years ago
|
return True
|
||
|
|
||
|
root = self.api_request(
|
||
4 years ago
|
func_name="logOut",
|
||
|
params="<handle>{token}</handle>".format(token=self.token),
|
||
5 years ago
|
)
|
||
4 years ago
|
res = root.find(".//return")
|
||
5 years ago
|
self.token = None
|
||
4 years ago
|
|
||
|
# avoid AttributeError
|
||
|
if not res:
|
||
|
logger.debug("Root logout returned None")
|
||
|
return False
|
||
|
|
||
|
if res.find("status").text == "OK":
|
||
|
logger.debug("Logged Out Successfully.")
|
||
5 years ago
|
return True
|
||
4 years ago
|
|
||
5 years ago
|
return False
|
||
|
|
||
|
def query(self, video, video_hash, language):
|
||
|
if not self.login():
|
||
4 years ago
|
logger.debug("Token not found. Can't perform query")
|
||
5 years ago
|
return []
|
||
|
|
||
|
if isinstance(language, (tuple, list, set)):
|
||
|
# language_ids = ",".join(language)
|
||
|
# language_ids = 'spa'
|
||
4 years ago
|
language_ids = ",".join(sorted(l.opensubtitles for l in language))
|
||
5 years ago
|
|
||
|
if video.imdb_id is None:
|
||
4 years ago
|
imdbId = "*"
|
||
5 years ago
|
else:
|
||
|
imdbId = video.imdb_id
|
||
|
sleep(self.SEARCH_THROTTLE)
|
||
|
root = self.api_request(
|
||
4 years ago
|
func_name="searchSubtitles",
|
||
5 years ago
|
params=(
|
||
4 years ago
|
"<handle>{token}</handle>"
|
||
|
"<movieHash>{movie_hash}</movieHash>"
|
||
|
"<movieSize>{movie_size}</movieSize>"
|
||
|
"<languageId>{language_ids}</languageId>"
|
||
|
"<imdbId>{imdbId}</imdbId>"
|
||
|
).format(
|
||
|
token=self.token,
|
||
|
movie_hash=video_hash,
|
||
|
movie_size=video.size,
|
||
|
language_ids=language_ids,
|
||
|
imdbId=imdbId,
|
||
|
),
|
||
5 years ago
|
)
|
||
4 years ago
|
res = root.find(".//return/result")
|
||
|
|
||
|
if not res:
|
||
|
logger.debug("No subtitles found")
|
||
5 years ago
|
return []
|
||
|
|
||
4 years ago
|
status = res.find("status").text
|
||
|
if status != "OK":
|
||
|
logger.debug(f"No subtitles found (bad status: {status})")
|
||
|
return []
|
||
|
|
||
|
items = root.findall(".//return/data/item")
|
||
5 years ago
|
subtitles = []
|
||
|
if items:
|
||
4 years ago
|
logger.debug("Subtitles Found.")
|
||
5 years ago
|
for item in items:
|
||
4 years ago
|
subID = item.find("subID").text
|
||
|
subDownloadLink = item.find("subDownloadLink").text
|
||
|
subLang = Language.fromopensubtitles(item.find("subLang").text)
|
||
|
subName = item.find("subName").text
|
||
|
subFormat = item.find("subFormat").text
|
||
5 years ago
|
subtitles.append(
|
||
4 years ago
|
BSPlayerSubtitle(
|
||
|
subLang, subName, subFormat, video, subDownloadLink, subID
|
||
|
)
|
||
5 years ago
|
)
|
||
|
return subtitles
|
||
|
|
||
|
def list_subtitles(self, video, languages):
|
||
3 years ago
|
return []
|
||
|
# commented out this part to prevent usage of this provider and return no subtitles
|
||
|
# return self.query(video, video.hashes["bsplayer"], languages)
|
||
5 years ago
|
|
||
|
def get_sub_domain(self):
|
||
4 years ago
|
# API_URL_TEMPLATE = None
|
||
|
# session = Session()
|
||
5 years ago
|
# s1-9, s101-109
|
||
4 years ago
|
|
||
|
# Don't test again
|
||
|
# fixme: Setting attribute here as initialize() may reset it (maybe
|
||
|
# there's a more elegant way?)
|
||
|
if hasattr(self, "API_URL_TEMPLATE"):
|
||
|
logger.debug(f"Working subdomain already met: {self.API_URL_TEMPLATE}")
|
||
|
return self.API_URL_TEMPLATE
|
||
|
else:
|
||
|
self.API_URL_TEMPLATE = None
|
||
|
|
||
|
# fmt: off
|
||
5 years ago
|
SUB_DOMAINS = ['s1', 's2', 's3', 's4', 's5', 's6', 's7', 's8',
|
||
5 years ago
|
's101', 's102', 's103', 's104', 's105', 's106', 's107', 's108', 's109']
|
||
4 years ago
|
# fmt: on
|
||
4 years ago
|
random.shuffle(SUB_DOMAINS)
|
||
4 years ago
|
# Limit to 8 tests
|
||
|
for domain in SUB_DOMAINS[:8]:
|
||
4 years ago
|
TEST_URL = "http://{}.api.bsplayer-subtitles.com".format(domain)
|
||
|
try:
|
||
4 years ago
|
logging.debug("Testing BSplayer sub-domain {}".format(TEST_URL))
|
||
4 years ago
|
res = self.session.get(TEST_URL, timeout=3)
|
||
4 years ago
|
except:
|
||
|
continue
|
||
|
else:
|
||
|
res.raise_for_status()
|
||
|
|
||
|
if res.status_code == 200:
|
||
4 years ago
|
logger.debug(f"Found working subdomain: {domain}")
|
||
|
self.API_URL_TEMPLATE = (
|
||
|
"http://{}.api.bsplayer-subtitles.com/v1.php".format(domain)
|
||
|
)
|
||
4 years ago
|
break
|
||
|
else:
|
||
4 years ago
|
sleep(1)
|
||
4 years ago
|
continue
|
||
|
|
||
4 years ago
|
if self.API_URL_TEMPLATE:
|
||
|
return self.API_URL_TEMPLATE
|
||
|
|
||
|
raise ServiceUnavailable("No API URL template was found")
|
||
5 years ago
|
|
||
|
def download_subtitle(self, subtitle):
|
||
4 years ago
|
# session = Session()
|
||
|
_addheaders = {"User-Agent": "Mozilla/4.0 (compatible; Synapse)"}
|
||
|
self.session.headers.update(_addheaders)
|
||
|
res = self.session.get(subtitle.page_link)
|
||
5 years ago
|
if res:
|
||
4 years ago
|
if res.text == "500":
|
||
|
raise ServiceUnavailable("Error 500 on server")
|
||
5 years ago
|
|
||
|
with gzip.GzipFile(fileobj=io.BytesIO(res.content)) as gf:
|
||
5 years ago
|
subtitle.content = gf.read()
|
||
5 years ago
|
subtitle.normalize()
|
||
|
|
||
|
return subtitle
|
||
4 years ago
|
raise ServiceUnavailable("Problems conecting to the server")
|