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.
223 lines
7.7 KiB
223 lines
7.7 KiB
6 years ago
|
# -*- coding: utf-8 -*-
|
||
|
import logging
|
||
|
import os
|
||
|
import re
|
||
|
|
||
|
from babelfish import language_converters
|
||
|
from guessit import guessit
|
||
|
from requests import Session
|
||
2 years ago
|
from requests.exceptions import JSONDecodeError
|
||
2 years ago
|
from time import sleep
|
||
2 years ago
|
from math import ceil
|
||
6 years ago
|
|
||
2 years ago
|
from subliminal import Movie, Episode
|
||
6 years ago
|
from subliminal.exceptions import AuthenticationError, ConfigurationError, DownloadLimitExceeded, ProviderError
|
||
|
from subliminal_patch.subtitle import Subtitle, guess_matches
|
||
|
from subliminal.subtitle import fix_line_ending
|
||
|
from subliminal_patch.providers import Provider
|
||
|
from subzero.language import Language
|
||
|
|
||
|
logger = logging.getLogger(__name__)
|
||
|
|
||
|
language_converters.register('assrt = subliminal_patch.converters.assrt:AssrtConverter')
|
||
|
|
||
|
server_url = 'https://api.assrt.net/v1'
|
||
5 years ago
|
supported_languages = list(language_converters['assrt'].to_assrt.keys())
|
||
6 years ago
|
|
||
2 years ago
|
|
||
|
def get_request_delay(max_request_per_minute):
|
||
|
return ceil(60 / max_request_per_minute)
|
||
|
|
||
|
|
||
5 years ago
|
def language_contains(subset, superset):
|
||
|
if subset.alpha3 != superset.alpha3:
|
||
|
return False
|
||
2 years ago
|
if superset.country is not None and subset.country != superset.country:
|
||
5 years ago
|
return False
|
||
2 years ago
|
if superset.script is not None and subset.script != superset.script:
|
||
5 years ago
|
return False
|
||
|
return True
|
||
|
|
||
2 years ago
|
|
||
5 years ago
|
def search_language_in_list(lang, langlist):
|
||
2 years ago
|
for language in langlist:
|
||
|
if language_contains(lang, language):
|
||
|
return language
|
||
5 years ago
|
return None
|
||
6 years ago
|
|
||
2 years ago
|
|
||
2 years ago
|
def check_status_code(resp):
|
||
|
try:
|
||
|
response = resp.json()
|
||
|
if 'status' in response and 'errmsg' in response:
|
||
|
raise ProviderError(f'{response["errmsg"]} ({response["status"]})')
|
||
2 years ago
|
except JSONDecodeError:
|
||
2 years ago
|
pass
|
||
|
|
||
|
|
||
6 years ago
|
class AssrtSubtitle(Subtitle):
|
||
|
"""Assrt Sbutitle."""
|
||
|
provider_name = 'assrt'
|
||
|
guessit_options = {
|
||
2 years ago
|
'allowed_languages': [lang[0] for lang in supported_languages],
|
||
4 years ago
|
# 'allowed_countries': [ l[1] for l in supported_languages if len(l) > 1 ],
|
||
6 years ago
|
'enforce_list': True
|
||
|
}
|
||
|
|
||
2 years ago
|
def __init__(self, language, subtitle_id, video_name, session, token, max_request_per_minute):
|
||
6 years ago
|
super(AssrtSubtitle, self).__init__(language)
|
||
|
self.session = session
|
||
|
self.token = token
|
||
2 years ago
|
self.max_request_per_minute = max_request_per_minute
|
||
6 years ago
|
self.subtitle_id = subtitle_id
|
||
|
self.video_name = video_name
|
||
4 years ago
|
self.release_info = video_name
|
||
6 years ago
|
self.url = None
|
||
|
self._detail = None
|
||
|
|
||
|
def _get_detail(self):
|
||
|
if self._detail:
|
||
|
return self._detail
|
||
|
params = {'token': self.token, 'id': self.id}
|
||
5 years ago
|
logger.info('Get subtitle detail: GET /sub/detail %r', params)
|
||
2 years ago
|
sleep(get_request_delay(self.max_request_per_minute))
|
||
2 years ago
|
r = self.session.get(server_url + '/sub/detail', params=params, timeout=15)
|
||
2 years ago
|
check_status_code(r)
|
||
6 years ago
|
r.raise_for_status()
|
||
|
|
||
|
result = r.json()
|
||
2 years ago
|
if not len(result['sub']['subs']):
|
||
|
logger.error('Can\'t get subtitle details')
|
||
|
return False
|
||
6 years ago
|
sub = result['sub']['subs'][0]
|
||
2 years ago
|
if not len(sub['filelist']):
|
||
|
logger.error('Can\'t get filelist from subtitle details')
|
||
|
return False
|
||
6 years ago
|
files = sub['filelist']
|
||
|
|
||
|
# first pass: guessit
|
||
|
for f in files:
|
||
|
guess = guessit(f['f'], self.guessit_options)
|
||
|
langs = set()
|
||
|
if 'language' in guess:
|
||
|
langs.update(guess['language'])
|
||
|
if 'subtitle_language' in guess:
|
||
|
langs.update(guess['subtitle_language'])
|
||
|
if self.language in langs:
|
||
|
self._defail = f
|
||
|
return f
|
||
|
|
||
|
# second pass: keyword matching
|
||
|
codes = language_converters['assrt'].codes
|
||
|
for f in files:
|
||
2 years ago
|
langs = set([Language.fromassrt(k) for k in codes if k in f['f']])
|
||
6 years ago
|
if self.language in langs:
|
||
|
self._defail = f
|
||
|
return f
|
||
|
|
||
|
# fallback: pick up first file if nothing matches
|
||
|
return files[0]
|
||
|
|
||
|
@property
|
||
|
def id(self):
|
||
|
return self.subtitle_id
|
||
|
|
||
|
@property
|
||
|
def download_link(self):
|
||
|
detail = self._get_detail()
|
||
|
return detail['url']
|
||
|
|
||
|
def get_matches(self, video):
|
||
|
matches = guess_matches(video, guessit(self.video_name))
|
||
|
return matches
|
||
|
|
||
|
|
||
|
class AssrtProvider(Provider):
|
||
|
"""Assrt Provider."""
|
||
2 years ago
|
languages = {Language(*lang) for lang in supported_languages}
|
||
3 years ago
|
video_types = (Episode, Movie)
|
||
6 years ago
|
|
||
|
def __init__(self, token=None):
|
||
|
if not token:
|
||
|
raise ConfigurationError('Token must be specified')
|
||
|
self.token = token
|
||
2 years ago
|
self.session = Session()
|
||
|
self.max_request_per_minute = None
|
||
6 years ago
|
|
||
|
def initialize(self):
|
||
6 years ago
|
self.session.headers = {'User-Agent': os.environ.get("SZ_USER_AGENT", "Sub-Zero/2")}
|
||
2 years ago
|
res = self.session.get(server_url + '/user/quota', params={'token': self.token}, timeout=15)
|
||
2 years ago
|
check_status_code(res)
|
||
2 years ago
|
res.raise_for_status()
|
||
2 years ago
|
result = res.json()
|
||
|
if 'user' in result and 'quota' in result['user']:
|
||
|
self.max_request_per_minute = result['user']['quota']
|
||
|
|
||
2 years ago
|
if not isinstance(self.max_request_per_minute, int):
|
||
2 years ago
|
raise ProviderError(f'Cannot get user request quota per minute from provider: {result}')
|
||
|
|
||
2 years ago
|
if self.max_request_per_minute <= 0:
|
||
|
raise ProviderError(f'User request quota is not a positive integer: {self.max_request_per_minute}')
|
||
6 years ago
|
|
||
|
def terminate(self):
|
||
|
self.session.close()
|
||
|
|
||
|
def query(self, languages, video):
|
||
|
# query the server
|
||
|
keywords = []
|
||
|
if isinstance(video, Movie):
|
||
|
if video.title:
|
||
4 years ago
|
# title = "".join(e for e in video.title if e.isalnum())
|
||
|
title = video.title
|
||
5 years ago
|
keywords.append(title)
|
||
6 years ago
|
if video.year:
|
||
|
keywords.append(str(video.year))
|
||
|
elif isinstance(video, Episode):
|
||
|
if video.series:
|
||
4 years ago
|
# series = "".join(e for e in video.series if e.isalnum())
|
||
|
series = video.series
|
||
5 years ago
|
keywords.append(series)
|
||
6 years ago
|
if video.season and video.episode:
|
||
|
keywords.append('S%02dE%02d' % (video.season, video.episode))
|
||
|
elif video.episode:
|
||
|
keywords.append('E%02d' % video.episode)
|
||
|
query = ' '.join(keywords)
|
||
|
|
||
|
params = {'token': self.token, 'q': query, 'is_file': 1}
|
||
5 years ago
|
logger.debug('Searching subtitles: GET /sub/search %r', params)
|
||
2 years ago
|
sleep(get_request_delay(self.max_request_per_minute))
|
||
2 years ago
|
res = self.session.get(server_url + '/sub/search', params=params, timeout=15)
|
||
2 years ago
|
check_status_code(res)
|
||
6 years ago
|
res.raise_for_status()
|
||
|
result = res.json()
|
||
|
|
||
|
# parse the subtitles
|
||
5 years ago
|
pattern = re.compile(r'lang(?P<code>\w+)')
|
||
6 years ago
|
subtitles = []
|
||
|
for sub in result['sub']['subs']:
|
||
|
if 'lang' not in sub:
|
||
|
continue
|
||
|
for key in sub['lang']['langlist'].keys():
|
||
|
match = pattern.match(key)
|
||
|
try:
|
||
|
language = Language.fromassrt(match.group('code'))
|
||
5 years ago
|
output_language = search_language_in_list(language, languages)
|
||
|
if output_language:
|
||
2 years ago
|
subtitles.append(AssrtSubtitle(output_language, sub['id'], sub['videoname'], self.session,
|
||
|
self.token, self.max_request_per_minute))
|
||
6 years ago
|
except:
|
||
|
pass
|
||
|
|
||
|
return subtitles
|
||
|
|
||
|
def list_subtitles(self, video, languages):
|
||
|
return self.query(languages, video)
|
||
|
|
||
|
def download_subtitle(self, subtitle):
|
||
2 years ago
|
sleep(get_request_delay(self.max_request_per_minute))
|
||
2 years ago
|
r = self.session.get(subtitle.download_link, timeout=15)
|
||
2 years ago
|
check_status_code(r)
|
||
6 years ago
|
r.raise_for_status()
|
||
|
|
||
|
subtitle.content = fix_line_ending(r.content)
|