Commit 45409254 authored by echel0n's avatar echel0n

Fixed "unsupported operand type(s) for +=: 'NoneType' and 'str'" in...

Fixed "unsupported operand type(s) for +=: 'NoneType' and 'str'" in _get_episode_search_strings function.
Fixed "invalid literal for int() with base 10" in load_from_nfo function.
Fixed "'NoneType' object has no attribute 'text'" in get_rss_feed function.
Added health check for backend API.
parent 5d6bdbd5
import requests
import time
from urllib.parse import urljoin
import requests.exceptions
from keycloak.exceptions import KeycloakClientError
from oauthlib.oauth2 import MissingTokenError, InvalidClientIdError, TokenExpiredError, InvalidGrantError, OAuth2Token
from requests_oauthlib import OAuth2Session
from sqlalchemy import orm
......@@ -14,7 +16,8 @@ from sickrage.core.databases.cache import CacheDB
class API(object):
def __init__(self):
self.name = 'SR-API'
self.api_url = 'https://www.sickrage.ca/api/v3/'
self.api_base = 'https://www.sickrage.ca/api/'
self.api_version = 'v3'
self.client_id = sickrage.app.oidc_client_id
self.client_secret = sickrage.app.oidc_client_secret
......@@ -68,9 +71,13 @@ class API(object):
def token_url(self):
try:
return sickrage.app.oidc_client.well_known['token_endpoint']
except requests.exceptions.RequestException:
except KeycloakClientError:
return "https://auth.sickrage.ca/auth/realms/sickrage/protocol/openid-connect/token"
@property
def health(self):
return requests.get(urljoin(self.api_base, "oauth/health")).ok
@property
def userinfo(self):
return self._request('GET', 'userinfo')
......@@ -103,8 +110,12 @@ class API(object):
latest_exception = None
for i in range(3):
if not self.health:
latest_exception = "SiCKRAGE backend API is currently unreachable ..."
continue
try:
resp = self.session.request(method, urljoin(self.api_url, url), timeout=timeout, hooks={'response': self.throttle_hook}, **kwargs)
resp = self.session.request(method, urljoin(self.api_base, "/".join([self.api_version, url])), timeout=timeout, hooks={'response': self.throttle_hook}, **kwargs)
resp.raise_for_status()
if resp.status_code == 204:
return
......@@ -113,9 +124,9 @@ class API(object):
return resp.json()
except ValueError:
return resp.content
except TokenExpiredError as e:
except TokenExpiredError:
self.refresh_token()
except (InvalidClientIdError, MissingTokenError, InvalidGrantError) as e:
except (InvalidClientIdError, MissingTokenError, InvalidGrantError):
latest_exception = "Invalid token error, please re-authenticate by logging out then logging back in from web-ui"
break
except requests.exceptions.ReadTimeout:
......
......@@ -98,8 +98,9 @@ class TVCache(object):
def get_rss_feed(self, url, params=None):
try:
if self.provider.login():
resp = WebSession().get(url, params=params).text
return feedparser.parse(resp)
resp = WebSession().get(url, params=params)
if resp:
return feedparser.parse(resp.text)
except Exception as e:
sickrage.app.log.debug("RSS Error: {}".format(e))
......
......@@ -413,7 +413,7 @@ class TVEpisode(MainDBBase):
self.airdate = datetime.date.min
if epDetails.findtext('aired'):
rawAirdate = [int(x) for x in epDetails.findtext('aired').split("-")]
rawAirdate = [int(x.strip()) for x in epDetails.findtext('aired').split("-")]
self.airdate = datetime.date(rawAirdate[0], rawAirdate[1], rawAirdate[2])
self.hasnfo = True
......
......@@ -210,11 +210,12 @@ class GenericProvider(object):
episode_string += episode_object.airdate.strftime('%b')
elif show_object.anime:
# If the show name is a season scene exception, we want to use the indexer episode number.
if (episode_object.scene_season > 1 and show_name in get_scene_exceptions(show_object.indexer_id, episode_object.scene_season)):
if episode_object.scene_season > 1 and show_name in get_scene_exceptions(show_object.indexer_id, episode_object.scene_season):
# This is apparently a season exception, let's use the scene_episode instead of absolute
ep = episode_object.scene_episode
else:
ep = episode_object.scene_absolute_number
episode_string += '{episode:0>2}'.format(episode=ep)
episode_string_fallback = episode_string + '{episode:0>3}'.format(episode=ep)
else:
......@@ -225,7 +226,8 @@ class GenericProvider(object):
if add_string:
episode_string += self.search_separator + add_string
episode_string_fallback += self.search_separator + add_string
if episode_string_fallback:
episode_string_fallback += self.search_separator + add_string
search_string['Episode'].append(episode_string.strip())
if episode_string_fallback:
......
......@@ -135,24 +135,23 @@ class GKTorrentProvider(TorrentProvider):
return results
def _get_download_link(self, url, download_type="torrent"):
try:
data = self.session.get(url).text
except Exception:
return
links = {
"torrent": "",
"magnet": "",
}
with bs4_parser(data) as html:
downloads = html.find('div', {'class': 'download'})
if downloads:
for download in downloads.findAll('a'):
link = download['href']
if link.startswith("magnet"):
links["magnet"] = link
else:
links["torrent"] = urljoin(self.urls['base_url'], link)
try:
data = self.session.get(url).text
with bs4_parser(data) as html:
downloads = html.find('div', {'class': 'download'})
if downloads:
for download in downloads.findAll('a'):
link = download['href']
if link.startswith("magnet"):
links["magnet"] = link
else:
links["torrent"] = urljoin(self.urls['base_url'], link)
except Exception:
pass
return links[download_type]
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment