mirror of
https://github.com/SickGear/SickGear.git
synced 2025-01-07 10:33:38 +00:00
Merge pull request #449 from JackDandy/feature/ChangeProvBTN
Change provider BTN code simplify and PEP8.
This commit is contained in:
commit
50978cfcd3
2 changed files with 108 additions and 117 deletions
|
@ -27,6 +27,7 @@
|
||||||
* Add new tld variants to provider TPB
|
* Add new tld variants to provider TPB
|
||||||
* Add test for authenticity to provider TPB to notify of 3rd party block
|
* Add test for authenticity to provider TPB to notify of 3rd party block
|
||||||
* Change provider TD login process to use General Config/Advanced/Proxy host setting
|
* Change provider TD login process to use General Config/Advanced/Proxy host setting
|
||||||
|
* Change provider BTN code simplify and PEP8
|
||||||
* Change provider BTS login process to use General Config/Advanced/Proxy host setting
|
* Change provider BTS login process to use General Config/Advanced/Proxy host setting
|
||||||
* Change provider FSH login process to use General Config/Advanced/Proxy host setting
|
* Change provider FSH login process to use General Config/Advanced/Proxy host setting
|
||||||
* Change provider RSS torrent code to use General Config/Advanced/Proxy host setting, simplify and PEP8
|
* Change provider RSS torrent code to use General Config/Advanced/Proxy host setting, simplify and PEP8
|
||||||
|
|
|
@ -1,6 +1,4 @@
|
||||||
# coding=utf-8
|
# coding=utf-8
|
||||||
# Author: Daniel Heimans
|
|
||||||
# URL: http://code.google.com/p/sickbeard
|
|
||||||
#
|
#
|
||||||
# This file is part of SickGear.
|
# This file is part of SickGear.
|
||||||
#
|
#
|
||||||
|
@ -17,12 +15,12 @@
|
||||||
# You should have received a copy of the GNU General Public License
|
# You should have received a copy of the GNU General Public License
|
||||||
# along with SickGear. If not, see <http://www.gnu.org/licenses/>.
|
# along with SickGear. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
import datetime
|
||||||
import time
|
import time
|
||||||
import socket
|
|
||||||
import math
|
import math
|
||||||
from datetime import datetime
|
import socket
|
||||||
|
|
||||||
import generic
|
from . import generic
|
||||||
from sickbeard import classes, scene_exceptions, logger, tvcache
|
from sickbeard import classes, scene_exceptions, logger, tvcache
|
||||||
from sickbeard.helpers import sanitizeSceneName
|
from sickbeard.helpers import sanitizeSceneName
|
||||||
from sickbeard.exceptions import ex, AuthException
|
from sickbeard.exceptions import ex, AuthException
|
||||||
|
@ -30,57 +28,50 @@ from lib import jsonrpclib
|
||||||
|
|
||||||
|
|
||||||
class BTNProvider(generic.TorrentProvider):
|
class BTNProvider(generic.TorrentProvider):
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
generic.TorrentProvider.__init__(self, 'BTN', True, False)
|
generic.TorrentProvider.__init__(self, 'BTN')
|
||||||
|
|
||||||
|
self.url_base = 'https://broadcasthe.net'
|
||||||
|
self.url_api = 'http://api.btnapps.net'
|
||||||
|
|
||||||
|
self.url = self.url_base
|
||||||
|
|
||||||
self.api_key = None
|
self.api_key = None
|
||||||
self.ratio = None
|
|
||||||
self.cache = BTNCache(self)
|
self.cache = BTNCache(self)
|
||||||
self.url = 'http://api.btnapps.net'
|
|
||||||
|
|
||||||
def _checkAuth(self):
|
def _check_auth_from_data(self, data_json):
|
||||||
if not self.api_key:
|
|
||||||
raise AuthException("Your authentication credentials for " + self.name + " are missing, check your config.")
|
|
||||||
|
|
||||||
return True
|
if data_json is None:
|
||||||
|
|
||||||
def _checkAuthFromData(self, parsedJSON):
|
|
||||||
|
|
||||||
if parsedJSON is None:
|
|
||||||
return self._checkAuth()
|
return self._checkAuth()
|
||||||
|
|
||||||
if 'api-error' in parsedJSON:
|
if 'api-error' not in data_json:
|
||||||
logger.log(u"Incorrect authentication credentials for " + self.name + " : " + parsedJSON['api-error'],
|
return True
|
||||||
logger.DEBUG)
|
|
||||||
raise AuthException(
|
|
||||||
"Your authentication credentials for " + self.name + " are incorrect, check your config.")
|
|
||||||
|
|
||||||
return True
|
logger.log(u'Incorrect authentication credentials for %s : %s' % (self.name, data_json['api-error']),
|
||||||
|
logger.DEBUG)
|
||||||
|
raise AuthException('Your authentication credentials for %s are incorrect, check your config.' % self.name)
|
||||||
|
|
||||||
def _doSearch(self, search_params, search_mode='eponly', epcount=0, age=0):
|
def _doSearch(self, search_params, search_mode='eponly', epcount=0, age=0):
|
||||||
|
|
||||||
self._checkAuth()
|
self._checkAuth()
|
||||||
|
|
||||||
params = {}
|
params = {}
|
||||||
apikey = self.api_key
|
|
||||||
|
|
||||||
# age in seconds
|
|
||||||
if age:
|
|
||||||
params['age'] = "<=" + str(int(age))
|
|
||||||
|
|
||||||
if search_params:
|
if search_params:
|
||||||
params.update(search_params)
|
params.update(search_params)
|
||||||
|
|
||||||
parsedJSON = self._api_call(apikey, params)
|
if age:
|
||||||
if not parsedJSON:
|
params['age'] = '<=%i' % age # age in seconds
|
||||||
logger.log(u"No data returned from " + self.name, logger.ERROR)
|
|
||||||
return []
|
|
||||||
|
|
||||||
if self._checkAuthFromData(parsedJSON):
|
results = []
|
||||||
|
|
||||||
if 'torrents' in parsedJSON:
|
data_json = self._api_call(params)
|
||||||
found_torrents = parsedJSON['torrents']
|
if not (data_json and self._check_auth_from_data(data_json)):
|
||||||
else:
|
self._log_result('rpc search', 0, self.name)
|
||||||
found_torrents = {}
|
else:
|
||||||
|
|
||||||
|
found_torrents = {} if 'torrents' not in data_json else data_json['torrents']
|
||||||
|
|
||||||
# We got something, we know the API sends max 1000 results at a time.
|
# We got something, we know the API sends max 1000 results at a time.
|
||||||
# See if there are more than 1000 results for our query, if not we
|
# See if there are more than 1000 results for our query, if not we
|
||||||
|
@ -89,95 +80,93 @@ class BTNProvider(generic.TorrentProvider):
|
||||||
max_pages = 150
|
max_pages = 150
|
||||||
results_per_page = 1000
|
results_per_page = 1000
|
||||||
|
|
||||||
if 'results' in parsedJSON and int(parsedJSON['results']) >= results_per_page:
|
if 'results' in data_json and int(data_json['results']) >= results_per_page:
|
||||||
pages_needed = int(math.ceil(int(parsedJSON['results']) / results_per_page))
|
pages_needed = int(math.ceil(int(data_json['results']) / results_per_page))
|
||||||
if pages_needed > max_pages:
|
if pages_needed > max_pages:
|
||||||
pages_needed = max_pages
|
pages_needed = max_pages
|
||||||
|
|
||||||
# +1 because range(1,4) = 1, 2, 3
|
# +1 because range(1,4) = 1, 2, 3
|
||||||
for page in range(1, pages_needed + 1):
|
for page in range(1, pages_needed + 1):
|
||||||
parsedJSON = self._api_call(apikey, params, results_per_page, page * results_per_page)
|
data_json = self._api_call(params, results_per_page, page * results_per_page)
|
||||||
# Note that this these are individual requests and might time out individually. This would result in 'gaps'
|
# Note that this these are individual requests and might time out individually. This would result in 'gaps'
|
||||||
# in the results. There is no way to fix this though.
|
# in the results. There is no way to fix this though.
|
||||||
if 'torrents' in parsedJSON:
|
if 'torrents' in data_json:
|
||||||
found_torrents.update(parsedJSON['torrents'])
|
found_torrents.update(data_json['torrents'])
|
||||||
|
|
||||||
results = []
|
cnt = len(results)
|
||||||
for torrentid, torrent_info in found_torrents.iteritems():
|
for torrentid, torrent_info in found_torrents.iteritems():
|
||||||
(title, url) = self._get_title_and_url(torrent_info)
|
title, url = self._get_title_and_url(torrent_info)
|
||||||
|
|
||||||
if title and url:
|
if title and url:
|
||||||
results.append(torrent_info)
|
results.append(torrent_info)
|
||||||
|
self._log_result('search', len(results) - cnt, self.name + ' JSON-RPC API')
|
||||||
|
|
||||||
return results
|
return results
|
||||||
|
|
||||||
return []
|
def _api_call(self, params=None, results_per_page=1000, offset=0):
|
||||||
|
|
||||||
def _api_call(self, apikey, params={}, results_per_page=1000, offset=0):
|
if None is params:
|
||||||
|
params = {}
|
||||||
|
|
||||||
server = jsonrpclib.Server(self.url)
|
logger.log(u'Searching with parameters: ' + str(params), logger.DEBUG)
|
||||||
parsedJSON = {}
|
|
||||||
|
|
||||||
logger.log(u'Searching with parameters: %s' % params, logger.DEBUG)
|
|
||||||
|
|
||||||
|
parsed_json = {}
|
||||||
|
server = jsonrpclib.Server(self.url_api)
|
||||||
try:
|
try:
|
||||||
parsedJSON = server.getTorrents(apikey, params, int(results_per_page), int(offset))
|
parsed_json = server.getTorrents(self.api_key, params, int(results_per_page), int(offset))
|
||||||
|
|
||||||
except jsonrpclib.jsonrpc.ProtocolError as error:
|
except jsonrpclib.jsonrpc.ProtocolError as error:
|
||||||
logger.log(u"JSON-RPC protocol error while accessing " + self.name + ": " + ex(error), logger.ERROR)
|
if 'Call Limit' in error.message:
|
||||||
parsedJSON = {'api-error': ex(error)}
|
logger.log(u'Request ignored because the %s 150 calls/hr limit was reached' % self.name, logger.WARNING)
|
||||||
return parsedJSON
|
else:
|
||||||
|
logger.log(u'JSON-RPC protocol error while accessing %s: %s' % (self.name, ex(error)), logger.ERROR)
|
||||||
|
return {'api-error': ex(error)}
|
||||||
|
|
||||||
except socket.timeout:
|
except socket.timeout:
|
||||||
logger.log(u"Timeout while accessing " + self.name, logger.WARNING)
|
logger.log(u'Timeout while accessing ' + self.name, logger.WARNING)
|
||||||
|
|
||||||
except socket.error as error:
|
except socket.error as error:
|
||||||
# Note that sometimes timeouts are thrown as socket errors
|
# timeouts are sometimes thrown as socket errors
|
||||||
logger.log(u"Socket error while accessing " + self.name + ": " + error[1], logger.ERROR)
|
logger.log(u'Socket error while accessing %s: %s' % (self.name, error[1]), logger.ERROR)
|
||||||
|
|
||||||
except Exception as error:
|
except Exception as error:
|
||||||
errorstring = str(error)
|
errorstring = str(error)
|
||||||
if (errorstring.startswith('<') and errorstring.endswith('>')):
|
if errorstring.startswith('<') and errorstring.endswith('>'):
|
||||||
errorstring = errorstring[1:-1]
|
errorstring = errorstring[1:-1]
|
||||||
logger.log(u"Unknown error while accessing " + self.name + ": " + errorstring, logger.ERROR)
|
logger.log(u'Error while accessing %s: %s' % (self.name, errorstring), logger.ERROR)
|
||||||
|
|
||||||
return parsedJSON
|
return parsed_json
|
||||||
|
|
||||||
def _get_title_and_url(self, parsedJSON):
|
def _get_title_and_url(self, data_json):
|
||||||
|
|
||||||
# The BTN API gives a lot of information in response,
|
# The BTN API gives a lot of information in response,
|
||||||
# however SickGear is built mostly around Scene or
|
# however SickGear is built mostly around Scene or
|
||||||
# release names, which is why we are using them here.
|
# release names, which is why we are using them here.
|
||||||
|
|
||||||
if 'ReleaseName' in parsedJSON and parsedJSON['ReleaseName']:
|
if 'ReleaseName' in data_json and data_json['ReleaseName']:
|
||||||
title = parsedJSON['ReleaseName']
|
title = data_json['ReleaseName']
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# If we don't have a release name we need to get creative
|
# If we don't have a release name we need to get creative
|
||||||
title = u''
|
title = u''
|
||||||
if 'Series' in parsedJSON:
|
keys = ['Series', 'GroupName', 'Resolution', 'Source', 'Codec']
|
||||||
title += parsedJSON['Series']
|
for key in keys:
|
||||||
if 'GroupName' in parsedJSON:
|
if key in data_json:
|
||||||
title += '.' + parsedJSON['GroupName'] if title else parsedJSON['GroupName']
|
title += ('', '.')[any(title)] + data_json[key]
|
||||||
if 'Resolution' in parsedJSON:
|
|
||||||
title += '.' + parsedJSON['Resolution'] if title else parsedJSON['Resolution']
|
|
||||||
if 'Source' in parsedJSON:
|
|
||||||
title += '.' + parsedJSON['Source'] if title else parsedJSON['Source']
|
|
||||||
if 'Codec' in parsedJSON:
|
|
||||||
title += '.' + parsedJSON['Codec'] if title else parsedJSON['Codec']
|
|
||||||
if title:
|
if title:
|
||||||
title = title.replace(' ', '.')
|
title = title.replace(' ', '.')
|
||||||
|
|
||||||
url = None
|
url = None
|
||||||
if 'DownloadURL' in parsedJSON:
|
if 'DownloadURL' in data_json:
|
||||||
url = parsedJSON['DownloadURL']
|
url = data_json['DownloadURL']
|
||||||
if url:
|
if url:
|
||||||
# unescaped / is valid in JSON, but it can be escaped
|
# unescaped / is valid in JSON, but it can be escaped
|
||||||
url = url.replace("\\/", "/")
|
url = url.replace('\\/', '/')
|
||||||
|
|
||||||
return (title, url)
|
return title, url
|
||||||
|
|
||||||
|
def _get_season_search_strings(self, ep_obj, **kwargs):
|
||||||
|
|
||||||
def _get_season_search_strings(self, ep_obj):
|
|
||||||
search_params = []
|
search_params = []
|
||||||
current_params = {'category': 'Season'}
|
current_params = {'category': 'Season'}
|
||||||
|
|
||||||
|
@ -185,14 +174,16 @@ class BTNProvider(generic.TorrentProvider):
|
||||||
if ep_obj.show.air_by_date or ep_obj.show.sports:
|
if ep_obj.show.air_by_date or ep_obj.show.sports:
|
||||||
# Search for the year of the air by date show
|
# Search for the year of the air by date show
|
||||||
current_params['name'] = str(ep_obj.airdate).split('-')[0]
|
current_params['name'] = str(ep_obj.airdate).split('-')[0]
|
||||||
|
elif ep_obj.show.is_anime:
|
||||||
|
current_params['name'] = '%s' % ep_obj.scene_absolute_number
|
||||||
else:
|
else:
|
||||||
current_params['name'] = 'Season ' + str(ep_obj.scene_season)
|
current_params['name'] = 'Season ' + str(ep_obj.scene_season)
|
||||||
|
|
||||||
# search
|
# search
|
||||||
if ep_obj.show.indexer == 1:
|
if 1 == ep_obj.show.indexer:
|
||||||
current_params['tvdb'] = ep_obj.show.indexerid
|
current_params['tvdb'] = ep_obj.show.indexerid
|
||||||
search_params.append(current_params)
|
search_params.append(current_params)
|
||||||
elif ep_obj.show.indexer == 2:
|
elif 2 == ep_obj.show.indexer:
|
||||||
current_params['tvrage'] = ep_obj.show.indexerid
|
current_params['tvrage'] = ep_obj.show.indexerid
|
||||||
search_params.append(current_params)
|
search_params.append(current_params)
|
||||||
else:
|
else:
|
||||||
|
@ -206,7 +197,7 @@ class BTNProvider(generic.TorrentProvider):
|
||||||
|
|
||||||
return search_params
|
return search_params
|
||||||
|
|
||||||
def _get_episode_search_strings(self, ep_obj, add_string=''):
|
def _get_episode_search_strings(self, ep_obj, add_string='', **kwargs):
|
||||||
|
|
||||||
if not ep_obj:
|
if not ep_obj:
|
||||||
return [{}]
|
return [{}]
|
||||||
|
@ -221,15 +212,17 @@ class BTNProvider(generic.TorrentProvider):
|
||||||
# BTN uses dots in dates, we just search for the date since that
|
# BTN uses dots in dates, we just search for the date since that
|
||||||
# combined with the series identifier should result in just one episode
|
# combined with the series identifier should result in just one episode
|
||||||
search_params['name'] = date_str.replace('-', '.')
|
search_params['name'] = date_str.replace('-', '.')
|
||||||
|
elif ep_obj.show.anime:
|
||||||
|
search_params['name'] = '%s' % ep_obj.scene_absolute_number
|
||||||
else:
|
else:
|
||||||
# Do a general name search for the episode, formatted like SXXEYY
|
# Do a general name search for the episode, formatted like SXXEYY
|
||||||
search_params['name'] = "S%02dE%02d" % (ep_obj.scene_season, ep_obj.scene_episode)
|
search_params['name'] = 'S%02dE%02d' % (ep_obj.scene_season, ep_obj.scene_episode)
|
||||||
|
|
||||||
# search
|
# search
|
||||||
if ep_obj.show.indexer == 1:
|
if 1 == ep_obj.show.indexer:
|
||||||
search_params['tvdb'] = ep_obj.show.indexerid
|
search_params['tvdb'] = ep_obj.show.indexerid
|
||||||
to_return.append(search_params)
|
to_return.append(search_params)
|
||||||
elif ep_obj.show.indexer == 2:
|
elif 2 == ep_obj.show.indexer:
|
||||||
search_params['tvrage'] = ep_obj.show.indexerid
|
search_params['tvrage'] = ep_obj.show.indexerid
|
||||||
to_return.append(search_params)
|
to_return.append(search_params)
|
||||||
else:
|
else:
|
||||||
|
@ -243,12 +236,8 @@ class BTNProvider(generic.TorrentProvider):
|
||||||
|
|
||||||
return to_return
|
return to_return
|
||||||
|
|
||||||
def _doGeneralSearch(self, search_string):
|
|
||||||
# 'search' looks as broad is it can find. Can contain episode overview and title for example,
|
|
||||||
# use with caution!
|
|
||||||
return self._doSearch({'search': search_string})
|
|
||||||
|
|
||||||
def findPropers(self, search_date=None):
|
def findPropers(self, search_date=None):
|
||||||
|
|
||||||
results = []
|
results = []
|
||||||
|
|
||||||
search_terms = ['%.proper.%', '%.repack.%']
|
search_terms = ['%.proper.%', '%.repack.%']
|
||||||
|
@ -257,45 +246,46 @@ class BTNProvider(generic.TorrentProvider):
|
||||||
for item in self._doSearch({'release': term}, age=4 * 24 * 60 * 60):
|
for item in self._doSearch({'release': term}, age=4 * 24 * 60 * 60):
|
||||||
if item['Time']:
|
if item['Time']:
|
||||||
try:
|
try:
|
||||||
result_date = datetime.fromtimestamp(float(item['Time']))
|
result_date = datetime.datetime.fromtimestamp(float(item['Time']))
|
||||||
except TypeError:
|
except TypeError:
|
||||||
result_date = None
|
continue
|
||||||
|
|
||||||
if result_date:
|
if not search_date or result_date > search_date:
|
||||||
if not search_date or result_date > search_date:
|
title, url = self._get_title_and_url(item)
|
||||||
title, url = self._get_title_and_url(item)
|
results.append(classes.Proper(title, url, result_date, self.show))
|
||||||
results.append(classes.Proper(title, url, result_date, self.show))
|
|
||||||
|
|
||||||
return results
|
return results
|
||||||
|
|
||||||
def seedRatio(self):
|
def get_cache_data(self, **kwargs):
|
||||||
return self.ratio
|
|
||||||
|
# Get the torrents uploaded since last check.
|
||||||
|
seconds_since_last_update = int(math.ceil(time.time() - time.mktime(kwargs['age'])))
|
||||||
|
|
||||||
|
# default to 15 minutes
|
||||||
|
seconds_min_time = kwargs['min_time'] * 60
|
||||||
|
if seconds_min_time > seconds_since_last_update:
|
||||||
|
seconds_since_last_update = seconds_min_time
|
||||||
|
|
||||||
|
# Set maximum to 24 hours (24 * 60 * 60 = 86400 seconds) of "RSS" data search,
|
||||||
|
# older items will be done through backlog
|
||||||
|
if 86400 < seconds_since_last_update:
|
||||||
|
logger.log(u'Only trying to fetch the last 24 hours even though the last known successful update on %s was over 24 hours'
|
||||||
|
% self.name, logger.WARNING)
|
||||||
|
seconds_since_last_update = 86400
|
||||||
|
|
||||||
|
return self._doSearch(search_params=None, age=seconds_since_last_update)
|
||||||
|
|
||||||
|
|
||||||
class BTNCache(tvcache.TVCache):
|
class BTNCache(tvcache.TVCache):
|
||||||
def __init__(self, provider):
|
|
||||||
tvcache.TVCache.__init__(self, provider)
|
|
||||||
|
|
||||||
# At least 15 minutes between queries
|
def __init__(self, this_provider):
|
||||||
self.minTime = 15
|
tvcache.TVCache.__init__(self, this_provider)
|
||||||
|
|
||||||
|
self.minTime = 15 # cache update frequency
|
||||||
|
|
||||||
def _getRSSData(self):
|
def _getRSSData(self):
|
||||||
# Get the torrents uploaded since last check.
|
|
||||||
seconds_since_last_update = math.ceil(time.time() - time.mktime(self._getLastUpdate().timetuple()))
|
|
||||||
|
|
||||||
# default to 15 minutes
|
return self.provider.get_cache_data(age=self._getLastUpdate().timetuple(), min_time=self.minTime)
|
||||||
seconds_minTime = self.minTime * 60
|
|
||||||
if seconds_since_last_update < seconds_minTime:
|
|
||||||
seconds_since_last_update = seconds_minTime
|
|
||||||
|
|
||||||
# Set maximum to 24 hours (24 * 60 * 60 = 86400 seconds) of "RSS" data search, older things will need to be done through backlog
|
|
||||||
if seconds_since_last_update > 86400:
|
|
||||||
logger.log(
|
|
||||||
u"The last known successful update on " + self.provider.name + " was more than 24 hours ago, only trying to fetch the last 24 hours!",
|
|
||||||
logger.WARNING)
|
|
||||||
seconds_since_last_update = 86400
|
|
||||||
|
|
||||||
return self.provider._doSearch(search_params=None, age=seconds_since_last_update)
|
|
||||||
|
|
||||||
|
|
||||||
provider = BTNProvider()
|
provider = BTNProvider()
|
||||||
|
|
Loading…
Reference in a new issue