Fixed maximum number of requests per minute for assrt provider. #1953

This commit is contained in:
morpheus65535 2022-10-09 21:54:11 -04:00
parent af70cf1fc9
commit 167cb5dd98

View file

@ -1,6 +1,4 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import
import json
import logging import logging
import os import os
import re import re
@ -9,6 +7,7 @@ from babelfish import language_converters
from guessit import guessit from guessit import guessit
from requests import Session from requests import Session
from time import sleep from time import sleep
from math import ceil
from subliminal import Movie, Episode, ProviderError, __short_version__ from subliminal import Movie, Episode, ProviderError, __short_version__
from subliminal.exceptions import AuthenticationError, ConfigurationError, DownloadLimitExceeded, ProviderError from subliminal.exceptions import AuthenticationError, ConfigurationError, DownloadLimitExceeded, ProviderError
@ -24,34 +23,42 @@ language_converters.register('assrt = subliminal_patch.converters.assrt:AssrtCon
server_url = 'https://api.assrt.net/v1' server_url = 'https://api.assrt.net/v1'
supported_languages = list(language_converters['assrt'].to_assrt.keys()) supported_languages = list(language_converters['assrt'].to_assrt.keys())
def get_request_delay(max_request_per_minute):
return ceil(60 / max_request_per_minute)
def language_contains(subset, superset): def language_contains(subset, superset):
if subset.alpha3 != superset.alpha3: if subset.alpha3 != superset.alpha3:
return False return False
if superset.country != None and subset.country != superset.country: if superset.country is not None and subset.country != superset.country:
return False return False
if superset.script != None and subset.script != superset.script: if superset.script is not None and subset.script != superset.script:
return False return False
return True return True
def search_language_in_list(lang, langlist): def search_language_in_list(lang, langlist):
for l in langlist: for language in langlist:
if language_contains(lang, l): if language_contains(lang, language):
return l return language
return None return None
class AssrtSubtitle(Subtitle): class AssrtSubtitle(Subtitle):
"""Assrt Sbutitle.""" """Assrt Sbutitle."""
provider_name = 'assrt' provider_name = 'assrt'
guessit_options = { guessit_options = {
'allowed_languages': [ l[0] for l in supported_languages ], 'allowed_languages': [lang[0] for lang in supported_languages],
# 'allowed_countries': [ l[1] for l in supported_languages if len(l) > 1 ], # 'allowed_countries': [ l[1] for l in supported_languages if len(l) > 1 ],
'enforce_list': True 'enforce_list': True
} }
def __init__(self, language, subtitle_id, video_name, session, token): def __init__(self, language, subtitle_id, video_name, session, token, max_request_per_minute):
super(AssrtSubtitle, self).__init__(language) super(AssrtSubtitle, self).__init__(language)
self.session = session self.session = session
self.token = token self.token = token
self.max_request_per_minute = max_request_per_minute
self.subtitle_id = subtitle_id self.subtitle_id = subtitle_id
self.video_name = video_name self.video_name = video_name
self.release_info = video_name self.release_info = video_name
@ -63,7 +70,7 @@ class AssrtSubtitle(Subtitle):
return self._detail return self._detail
params = {'token': self.token, 'id': self.id} params = {'token': self.token, 'id': self.id}
logger.info('Get subtitle detail: GET /sub/detail %r', params) logger.info('Get subtitle detail: GET /sub/detail %r', params)
sleep(3) sleep(get_request_delay(self.max_request_per_minute))
r = self.session.get(server_url + '/sub/detail', params=params, timeout=10) r = self.session.get(server_url + '/sub/detail', params=params, timeout=10)
r.raise_for_status() r.raise_for_status()
@ -86,7 +93,7 @@ class AssrtSubtitle(Subtitle):
# second pass: keyword matching # second pass: keyword matching
codes = language_converters['assrt'].codes codes = language_converters['assrt'].codes
for f in files: for f in files:
langs = set([ Language.fromassrt(k) for k in codes if k in f['f'] ]) langs = set([Language.fromassrt(k) for k in codes if k in f['f']])
if self.language in langs: if self.language in langs:
self._defail = f self._defail = f
return f return f
@ -110,17 +117,29 @@ class AssrtSubtitle(Subtitle):
class AssrtProvider(Provider): class AssrtProvider(Provider):
"""Assrt Provider.""" """Assrt Provider."""
languages = {Language(*l) for l in supported_languages} languages = {Language(*lang) for lang in supported_languages}
video_types = (Episode, Movie) video_types = (Episode, Movie)
def __init__(self, token=None): def __init__(self, token=None):
if not token: if not token:
raise ConfigurationError('Token must be specified') raise ConfigurationError('Token must be specified')
self.token = token self.token = token
self.session = Session()
self.default_max_request_per_minute = 20
self.max_request_per_minute = None
def initialize(self): def initialize(self):
self.session = Session()
self.session.headers = {'User-Agent': os.environ.get("SZ_USER_AGENT", "Sub-Zero/2")} self.session.headers = {'User-Agent': os.environ.get("SZ_USER_AGENT", "Sub-Zero/2")}
res = self.session.get(server_url + '/user/quota', params={'token': self.token}, timeout=10)
res.raise_for_status()
try:
result = res.json()
except:
self.max_request_per_minute = self.default_max_request_per_minute
else:
if 'user' in result:
if 'quota' in result['user']:
self.max_request_per_minute = result['user']['quota']
def terminate(self): def terminate(self):
self.session.close() self.session.close()
@ -148,7 +167,7 @@ class AssrtProvider(Provider):
params = {'token': self.token, 'q': query, 'is_file': 1} params = {'token': self.token, 'q': query, 'is_file': 1}
logger.debug('Searching subtitles: GET /sub/search %r', params) logger.debug('Searching subtitles: GET /sub/search %r', params)
sleep(3) sleep(get_request_delay(self.max_request_per_minute))
res = self.session.get(server_url + '/sub/search', params=params, timeout=10) res = self.session.get(server_url + '/sub/search', params=params, timeout=10)
res.raise_for_status() res.raise_for_status()
result = res.json() result = res.json()
@ -169,7 +188,8 @@ class AssrtProvider(Provider):
language = Language.fromassrt(match.group('code')) language = Language.fromassrt(match.group('code'))
output_language = search_language_in_list(language, languages) output_language = search_language_in_list(language, languages)
if output_language: if output_language:
subtitles.append(AssrtSubtitle(output_language, sub['id'], sub['videoname'], self.session, self.token)) subtitles.append(AssrtSubtitle(output_language, sub['id'], sub['videoname'], self.session,
self.token, self.max_request_per_minute))
except: except:
pass pass
@ -179,7 +199,7 @@ class AssrtProvider(Provider):
return self.query(languages, video) return self.query(languages, video)
def download_subtitle(self, subtitle): def download_subtitle(self, subtitle):
sleep(3) sleep(get_request_delay(self.max_request_per_minute))
r = self.session.get(subtitle.download_link, timeout=10) r = self.session.get(subtitle.download_link, timeout=10)
r.raise_for_status() r.raise_for_status()