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.
276 lines
10 KiB
276 lines
10 KiB
6 years ago
|
# -*- coding: utf-8 -*-
|
||
5 years ago
|
from __future__ import absolute_import
|
||
6 years ago
|
import logging
|
||
|
import re
|
||
|
import io
|
||
|
import os
|
||
5 years ago
|
import codecs
|
||
|
from hashlib import sha1
|
||
6 years ago
|
from random import randint
|
||
|
from bs4 import BeautifulSoup
|
||
|
from zipfile import ZipFile, is_zipfile
|
||
|
from rarfile import RarFile, is_rarfile
|
||
|
from requests import Session
|
||
|
from guessit import guessit
|
||
5 years ago
|
from dogpile.cache.api import NO_VALUE
|
||
6 years ago
|
from subliminal_patch.providers import Provider
|
||
4 years ago
|
from subliminal_patch.subtitle import Subtitle, guess_matches
|
||
5 years ago
|
from subliminal_patch.utils import sanitize, fix_inconsistent_naming
|
||
6 years ago
|
from subliminal.video import Episode, Movie
|
||
|
from subliminal.subtitle import fix_line_ending
|
||
5 years ago
|
from subliminal.cache import region
|
||
6 years ago
|
from subzero.language import Language
|
||
|
from .utils import FIRST_THOUSAND_OR_SO_USER_AGENTS as AGENT_LIST
|
||
|
|
||
|
logger = logging.getLogger(__name__)
|
||
|
|
||
5 years ago
|
|
||
5 years ago
|
def fix_tv_naming(title):
|
||
|
"""Fix TV show titles with inconsistent naming using dictionary, but do not sanitize them.
|
||
|
|
||
|
:param str title: original title.
|
||
|
:return: new title.
|
||
|
:rtype: str
|
||
|
|
||
|
"""
|
||
|
return fix_inconsistent_naming(title, {"Marvel's Daredevil": "Daredevil",
|
||
|
"Marvel's Luke Cage": "Luke Cage",
|
||
|
"Marvel's Iron Fist": "Iron Fist",
|
||
|
"Marvel's Jessica Jones": "Jessica Jones",
|
||
5 years ago
|
"DC's Legends of Tomorrow": "Legends of Tomorrow",
|
||
|
"Doctor Who (2005)": "Doctor Who",
|
||
4 years ago
|
"Star Trek: Deep Space Nine": "Star Trek DS9",
|
||
|
"Star Trek: The Next Generation": "Star Trek TNG",
|
||
3 years ago
|
"Superman & Lois": "Superman and Lois",
|
||
5 years ago
|
}, True)
|
||
|
|
||
5 years ago
|
|
||
4 years ago
|
def fix_movie_naming(title):
|
||
|
return fix_inconsistent_naming(title, {"Back to the Future Part": "Back to the Future",
|
||
|
}, True)
|
||
|
|
||
|
|
||
6 years ago
|
class SubsSabBzSubtitle(Subtitle):
|
||
|
"""SubsSabBz Subtitle."""
|
||
|
provider_name = 'subssabbz'
|
||
|
|
||
5 years ago
|
def __init__(self, language, filename, type, video, link, fps, num_cds):
|
||
|
super(SubsSabBzSubtitle, self).__init__(language)
|
||
6 years ago
|
self.filename = filename
|
||
6 years ago
|
self.page_link = link
|
||
6 years ago
|
self.type = type
|
||
6 years ago
|
self.video = video
|
||
5 years ago
|
self.fps = fps
|
||
|
self.num_cds = num_cds
|
||
4 years ago
|
self.release_info = filename
|
||
|
if fps:
|
||
|
if video.fps and float(video.fps) == fps:
|
||
|
self.release_info += " <b>[{:.3f}]</b>".format(fps)
|
||
|
else:
|
||
|
self.release_info += " [{:.3f}]".format(fps)
|
||
6 years ago
|
|
||
|
@property
|
||
|
def id(self):
|
||
5 years ago
|
return self.page_link + self.filename
|
||
|
|
||
|
def get_fps(self):
|
||
|
return self.fps
|
||
6 years ago
|
|
||
6 years ago
|
def make_picklable(self):
|
||
5 years ago
|
self.content = None
|
||
5 years ago
|
self._is_valid = False
|
||
6 years ago
|
return self
|
||
|
|
||
6 years ago
|
def get_matches(self, video):
|
||
|
matches = set()
|
||
|
|
||
|
video_filename = video.name
|
||
|
video_filename = os.path.basename(video_filename)
|
||
|
video_filename, _ = os.path.splitext(video_filename)
|
||
5 years ago
|
video_filename = re.sub(r'\[\w+\]$', '', video_filename).strip().upper()
|
||
6 years ago
|
|
||
|
subtitle_filename = self.filename
|
||
|
subtitle_filename = os.path.basename(subtitle_filename)
|
||
|
subtitle_filename, _ = os.path.splitext(subtitle_filename)
|
||
5 years ago
|
subtitle_filename = re.sub(r'\[\w+\]$', '', subtitle_filename).strip().upper()
|
||
6 years ago
|
|
||
5 years ago
|
if ((video_filename == subtitle_filename) or
|
||
|
(self.single_file is True and video_filename in self.notes.upper())):
|
||
5 years ago
|
matches.add('hash')
|
||
6 years ago
|
|
||
5 years ago
|
if video.year and self.year == video.year:
|
||
|
matches.add('year')
|
||
|
|
||
|
if isinstance(video, Movie):
|
||
|
if video.imdb_id and self.imdb_id == video.imdb_id:
|
||
|
matches.add('imdb_id')
|
||
|
|
||
5 years ago
|
matches |= guess_matches(video, guessit(self.title, {'type': self.type}))
|
||
5 years ago
|
|
||
|
guess_filename = guessit(self.filename, video.hints)
|
||
|
matches |= guess_matches(video, guess_filename)
|
||
|
|
||
|
if isinstance(video, Movie) and (self.num_cds > 1 or 'cd' in guess_filename):
|
||
|
# reduce score of subtitles for multi-disc movie releases
|
||
|
return set()
|
||
|
|
||
6 years ago
|
return matches
|
||
|
|
||
|
|
||
|
class SubsSabBzProvider(Provider):
|
||
|
"""SubsSabBz Provider."""
|
||
5 years ago
|
languages = {Language(l) for l in [
|
||
6 years ago
|
'bul', 'eng'
|
||
|
]}
|
||
3 years ago
|
video_types = (Episode, Movie)
|
||
6 years ago
|
|
||
|
def initialize(self):
|
||
|
self.session = Session()
|
||
|
self.session.headers['User-Agent'] = AGENT_LIST[randint(0, len(AGENT_LIST) - 1)]
|
||
|
self.session.headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
|
||
|
self.session.headers["Accept-Language"] = "en-US,en;q=0.5"
|
||
|
self.session.headers["Accept-Encoding"] = "gzip, deflate, br"
|
||
|
self.session.headers["DNT"] = "1"
|
||
|
self.session.headers["Connection"] = "keep-alive"
|
||
|
self.session.headers["Upgrade-Insecure-Requests"] = "1"
|
||
|
self.session.headers["Cache-Control"] = "max-age=0"
|
||
|
|
||
|
def terminate(self):
|
||
|
self.session.close()
|
||
|
|
||
|
def query(self, language, video):
|
||
|
subtitles = []
|
||
|
isEpisode = isinstance(video, Episode)
|
||
|
|
||
|
params = {
|
||
|
'act': 'search',
|
||
|
'movie': '',
|
||
|
'select-language': '2',
|
||
|
'upldr': '',
|
||
|
'yr': '',
|
||
|
'release': ''
|
||
|
}
|
||
|
|
||
|
if isEpisode:
|
||
5 years ago
|
params['movie'] = "%s %02d %02d" % (sanitize(fix_tv_naming(video.series), {'\''}), video.season, video.episode)
|
||
6 years ago
|
else:
|
||
|
params['yr'] = video.year
|
||
4 years ago
|
params['movie'] = sanitize(fix_movie_naming(video.title), {'\''})
|
||
6 years ago
|
|
||
|
if language == 'en' or language == 'eng':
|
||
|
params['select-language'] = 1
|
||
|
|
||
|
logger.info('Searching subtitle %r', params)
|
||
|
response = self.session.post('http://subs.sab.bz/index.php?', params=params, allow_redirects=False, timeout=10, headers={
|
||
|
'Referer': 'http://subs.sab.bz/',
|
||
|
})
|
||
|
|
||
|
response.raise_for_status()
|
||
|
|
||
|
if response.status_code != 200:
|
||
|
logger.debug('No subtitles found')
|
||
|
return subtitles
|
||
|
|
||
5 years ago
|
soup = BeautifulSoup(response.content, 'lxml')
|
||
6 years ago
|
rows = soup.findAll('tr', {'class': 'subs-row'})
|
||
|
|
||
5 years ago
|
# Search on first 25 rows only
|
||
|
for row in rows[:25]:
|
||
6 years ago
|
a_element_wrapper = row.find('td', { 'class': 'c2field' })
|
||
|
if a_element_wrapper:
|
||
|
element = a_element_wrapper.find('a')
|
||
|
if element:
|
||
|
link = element.get('href')
|
||
4 years ago
|
notes = re.sub(r'ddrivetip\(\'<div.*/></div>(.*)\',\'#[0-9]+\'\)', r'\1', element.get('onmouseover'))
|
||
5 years ago
|
title = element.get_text()
|
||
|
|
||
|
try:
|
||
|
year = int(str(element.next_sibling).strip(' ()'))
|
||
|
except:
|
||
|
year = None
|
||
|
|
||
|
td = row.findAll('td')
|
||
|
|
||
|
try:
|
||
|
num_cds = int(td[6].get_text())
|
||
|
except:
|
||
|
num_cds = None
|
||
|
|
||
|
try:
|
||
|
fps = float(td[7].get_text())
|
||
|
except:
|
||
|
fps = None
|
||
|
|
||
|
try:
|
||
|
uploader = td[8].get_text()
|
||
|
except:
|
||
|
uploader = None
|
||
|
|
||
|
try:
|
||
|
imdb_id = re.findall(r'imdb.com/title/(tt\d+)/?$', td[9].find('a').get('href'))[0]
|
||
|
except:
|
||
|
imdb_id = None
|
||
|
|
||
6 years ago
|
logger.info('Found subtitle link %r', link)
|
||
5 years ago
|
sub = self.download_archive_and_add_subtitle_files(link, language, video, fps, num_cds)
|
||
|
for s in sub:
|
||
|
s.title = title
|
||
|
s.notes = notes
|
||
|
s.year = year
|
||
5 years ago
|
s.uploader = uploader
|
||
5 years ago
|
s.imdb_id = imdb_id
|
||
5 years ago
|
s.single_file = True if len(sub) == 1 and num_cds == 1 else False
|
||
5 years ago
|
subtitles = subtitles + sub
|
||
6 years ago
|
return subtitles
|
||
|
|
||
|
def list_subtitles(self, video, languages):
|
||
|
return [s for l in languages for s in self.query(l, video)]
|
||
|
|
||
|
def download_subtitle(self, subtitle):
|
||
6 years ago
|
if subtitle.content:
|
||
|
pass
|
||
|
else:
|
||
|
seeking_subtitle_file = subtitle.filename
|
||
5 years ago
|
arch = self.download_archive_and_add_subtitle_files(subtitle.page_link, subtitle.language, subtitle.video,
|
||
|
subtitle.fps, subtitle.num_cds)
|
||
6 years ago
|
for s in arch:
|
||
|
if s.filename == seeking_subtitle_file:
|
||
|
subtitle.content = s.content
|
||
6 years ago
|
|
||
5 years ago
|
def process_archive_subtitle_files(self, archiveStream, language, video, link, fps, num_cds):
|
||
6 years ago
|
subtitles = []
|
||
|
type = 'episode' if isinstance(video, Episode) else 'movie'
|
||
5 years ago
|
for file_name in sorted(archiveStream.namelist()):
|
||
6 years ago
|
if file_name.lower().endswith(('.srt', '.sub')):
|
||
|
logger.info('Found subtitle file %r', file_name)
|
||
5 years ago
|
subtitle = SubsSabBzSubtitle(language, file_name, type, video, link, fps, num_cds)
|
||
5 years ago
|
subtitle.content = fix_line_ending(archiveStream.read(file_name))
|
||
6 years ago
|
subtitles.append(subtitle)
|
||
|
return subtitles
|
||
|
|
||
5 years ago
|
def download_archive_and_add_subtitle_files(self, link, language, video, fps, num_cds):
|
||
6 years ago
|
logger.info('Downloading subtitle %r', link)
|
||
5 years ago
|
cache_key = sha1(link.encode("utf-8")).digest()
|
||
|
request = region.get(cache_key)
|
||
|
if request is NO_VALUE:
|
||
|
request = self.session.get(link, headers={
|
||
|
'Referer': 'http://subs.sab.bz/index.php?'
|
||
|
})
|
||
|
request.raise_for_status()
|
||
|
region.set(cache_key, request)
|
||
|
else:
|
||
|
logger.info('Cache file: %s', codecs.encode(cache_key, 'hex_codec').decode('utf-8'))
|
||
6 years ago
|
|
||
4 years ago
|
try:
|
||
|
archive_stream = io.BytesIO(request.content)
|
||
|
if is_rarfile(archive_stream):
|
||
|
return self.process_archive_subtitle_files(RarFile(archive_stream), language, video, link, fps, num_cds)
|
||
|
elif is_zipfile(archive_stream):
|
||
|
return self.process_archive_subtitle_files(ZipFile(archive_stream), language, video, link, fps, num_cds)
|
||
|
except:
|
||
|
pass
|
||
|
|
||
|
logger.error('Ignore unsupported archive %r', request.headers)
|
||
|
region.delete(cache_key)
|
||
|
return []
|