Further refactor forks.py -> sickbeard.py

This commit is contained in:
p0psicles 2021-02-14 11:14:57 +01:00
commit fc6833e3a5
3 changed files with 127 additions and 147 deletions

View file

@ -1,22 +1,31 @@
import core # coding=utf-8
from .pymedusa import PyMedusa
from __future__ import (
import requests absolute_import,
import six division,
from oauthlib.oauth2 import LegacyApplicationClient print_function,
from requests_oauthlib import OAuth2Session unicode_literals,
from six import iteritems )
import core import core
from core import logger from core import logger
from oauthlib.oauth2 import LegacyApplicationClient
import requests
from requests_oauthlib import OAuth2Session
import six
from six import iteritems
class InitSickBeard(object): class InitSickBeard(object):
"""Sickbeard init class. """Sickbeard init class.
Used to determin which sickbeard fork object to initialize. Used to determin which sickbeard fork object to initialize.
""" """
def __init__(self, cfg, section, input_category): def __init__(self, cfg, section, input_category):
# As a bonus let's also put the config on self. # As a bonus let's also put the config on self.
self.config = cfg self.config = cfg
@ -35,9 +44,34 @@ class InitSickBeard(object):
self.sso_username = cfg.get('sso_username', '') self.sso_username = cfg.get('sso_username', '')
self.sso_password = cfg.get('sso_password', '') self.sso_password = cfg.get('sso_password', '')
self.fork = 'auto' self.fork = 'auto'
replace = {
'medusa': 'Medusa',
'medusa-api': 'Medusa-api',
'sickbeard-api': 'SickBeard-api',
'sickgear': 'SickGear',
'sickchill': 'SickChill',
'stheno': 'Stheno',
}
_val = cfg.get('fork', 'auto')
f1 = replace.get(_val, _val)
try:
self.fork = f1, core.FORKS[f1]
except KeyError:
self.fork = 'auto'
self.protocol = 'https://' if self.ssl else 'http://'
def auto_fork(self):
# auto-detect correct section
# config settings
if core.FORK_SET: # keep using determined fork for multiple (manual) post-processing
logger.info('{section}:{category} fork already set to {fork}'.format
(section=self.section, category=self.input_category, fork=core.FORK_SET[0]))
return core.FORK_SET[0], core.FORK_SET[1]
cfg = dict(core.CFG[self.section][self.input_category])
replace = { replace = {
'medusa': 'Medusa', 'medusa': 'Medusa',
'medusa-api': 'Medusa-api', 'medusa-api': 'Medusa-api',
@ -52,7 +86,82 @@ class InitSickBeard(object):
fork = f1, core.FORKS[f1] fork = f1, core.FORKS[f1]
except KeyError: except KeyError:
fork = 'auto' fork = 'auto'
protocol = 'https://' if self.ssl else 'http://' protocol = 'https://' if self.ssl else 'http://'
if self.section == 'NzbDrone':
logger.info('Attempting to verify {category} fork'.format
(category=self.input_category))
url = '{protocol}{host}:{port}{root}/api/rootfolder'.format(
protocol=protocol, host=self.host, port=self.port, root=self.web_root,
)
headers = {'X-Api-Key': self.apikey}
try:
r = requests.get(url, headers=headers, stream=True, verify=False)
except requests.ConnectionError:
logger.warning('Could not connect to {0}:{1} to verify fork!'.format(self.section, self.input_category))
if not r.ok:
logger.warning('Connection to {section}:{category} failed! '
'Check your configuration'.format
(section=self.section, category=self.input_category))
fork = ['default', {}]
elif self.section == 'SiCKRAGE':
logger.info('Attempting to verify {category} fork'.format
(category=self.input_category))
if self.api_version >= 2:
url = '{protocol}{host}:{port}{root}/api/v{api_version}/ping'.format(
protocol=protocol, host=self.host, port=self.port, root=self.web_root, api_version=self.api_version
)
api_params = {}
else:
url = '{protocol}{host}:{port}{root}/api/v{api_version}/{apikey}/'.format(
protocol=protocol, host=self.host, port=self.port, root=self.web_root, api_version=self.api_version, apikey=self.apikey,
)
api_params = {'cmd': 'postprocess', 'help': '1'}
try:
if self.api_version >= 2 and self.sso_username and self.sso_password:
oauth = OAuth2Session(client=LegacyApplicationClient(client_id=core.SICKRAGE_OAUTH_CLIENT_ID))
oauth_token = oauth.fetch_token(client_id=core.SICKRAGE_OAUTH_CLIENT_ID,
token_url=core.SICKRAGE_OAUTH_TOKEN_URL,
username=self.sso_username,
password=self.sso_password)
r = requests.get(url, headers={'Authorization': 'Bearer ' + oauth_token['access_token']}, stream=True, verify=False)
else:
r = requests.get(url, params=api_params, stream=True, verify=False)
if not r.ok:
logger.warning('Connection to {section}:{category} failed! '
'Check your configuration'.format(
section=self.section, category=self.input_category
))
except requests.ConnectionError:
logger.warning('Could not connect to {0}:{1} to verify API version!'.format(self.section, self.input_category))
params = {
'path': None,
'failed': None,
'process_method': None,
'force_replace': None,
'return_data': None,
'type': None,
'delete': None,
'force_next': None,
'is_priority': None
}
fork = ['default', params]
elif fork == 'auto':
fork = self.detect_fork()
logger.info('{section}:{category} fork set to {fork}'.format
(section=self.section, category=self.input_category, fork=fork[0]))
core.FORK_SET = fork
return fork[0], fork[1]
@staticmethod @staticmethod
def _api_check(r, params, rem_params): def _api_check(r, params, rem_params):
@ -92,7 +201,7 @@ class InitSickBeard(object):
def detect_fork(self): def detect_fork(self):
"""Try to detect a specific fork.""" """Try to detect a specific fork."""
detected = False
params = core.ALL_FORKS params = core.ALL_FORKS
rem_params = [] rem_params = []
logger.info('Attempting to auto-detect {category} fork'.format(category=self.input_category)) logger.info('Attempting to auto-detect {category} fork'.format(category=self.input_category))

View file

@ -36,6 +36,8 @@ from core.utils import (
remove_dir, remove_dir,
server_responding, server_responding,
) )
from core.auto_process.managers.sickbeard import InitSickBeard
requests.packages.urllib3.disable_warnings() requests.packages.urllib3.disable_warnings()
@ -55,9 +57,13 @@ def process(section, dir_name, input_name=None, failed=False, client_agent='manu
sso_username = cfg.get('sso_username', '') sso_username = cfg.get('sso_username', '')
sso_password = cfg.get('sso_password', '') sso_password = cfg.get('sso_password', '')
# Refactor into an OO structure.
# For now let's do botch the OO and the serialized code, until everything has been migrated.
init_sickbeard = InitSickBeard(cfg, section, input_category)
if server_responding('{0}{1}:{2}{3}'.format(protocol, host, port, web_root)): if server_responding('{0}{1}:{2}{3}'.format(protocol, host, port, web_root)):
# auto-detect correct fork # auto-detect correct fork
fork, fork_params = auto_fork(section, input_category) fork, fork_params = init_sickbeard.auto_fork()
elif not username and not apikey and not sso_username: elif not username and not apikey and not sso_username:
logger.info('No SickBeard / SiCKRAGE username or Sonarr apikey entered. Performing transcoder functions only') logger.info('No SickBeard / SiCKRAGE username or Sonarr apikey entered. Performing transcoder functions only')
fork, fork_params = 'None', {} fork, fork_params = 'None', {}

View file

@ -1,135 +0,0 @@
# coding=utf-8
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
import requests
import six
from oauthlib.oauth2 import LegacyApplicationClient
from requests_oauthlib import OAuth2Session
from six import iteritems
import core
from core import logger
from core.auto_process.managers.sickbeard import InitSickBeard
def auto_fork(section, input_category):
# auto-detect correct section
# config settings
if core.FORK_SET: # keep using determined fork for multiple (manual) post-processing
logger.info('{section}:{category} fork already set to {fork}'.format
(section=section, category=input_category, fork=core.FORK_SET[0]))
return core.FORK_SET[0], core.FORK_SET[1]
cfg = dict(core.CFG[section][input_category])
# Refactor into an OO structure.
# For now let's do botch the OO and the serialized code, until everything has been migrated.
init_sickbeard = InitSickBeard(cfg, section, input_category)
host = cfg.get('host')
port = cfg.get('port')
username = cfg.get('username', '')
password = cfg.get('password', '')
sso_username = cfg.get('sso_username', '')
sso_password = cfg.get('sso_password', '')
apikey = cfg.get('apikey', '')
api_version = int(cfg.get('api_version', 2))
ssl = int(cfg.get('ssl', 0))
web_root = cfg.get('web_root', '')
replace = {
'medusa': 'Medusa',
'medusa-api': 'Medusa-api',
'sickbeard-api': 'SickBeard-api',
'sickgear': 'SickGear',
'sickchill': 'SickChill',
'stheno': 'Stheno',
}
_val = cfg.get('fork', 'auto')
f1 = replace.get(_val, _val)
try:
fork = f1, core.FORKS[f1]
except KeyError:
fork = 'auto'
protocol = 'https://' if ssl else 'http://'
detected = False
if section == 'NzbDrone':
logger.info('Attempting to verify {category} fork'.format
(category=input_category))
url = '{protocol}{host}:{port}{root}/api/rootfolder'.format(
protocol=protocol, host=host, port=port, root=web_root,
)
headers = {'X-Api-Key': apikey}
try:
r = requests.get(url, headers=headers, stream=True, verify=False)
except requests.ConnectionError:
logger.warning('Could not connect to {0}:{1} to verify fork!'.format(section, input_category))
if not r.ok:
logger.warning('Connection to {section}:{category} failed! '
'Check your configuration'.format
(section=section, category=input_category))
fork = ['default', {}]
elif section == 'SiCKRAGE':
logger.info('Attempting to verify {category} fork'.format
(category=input_category))
if api_version >= 2:
url = '{protocol}{host}:{port}{root}/api/v{api_version}/ping'.format(
protocol=protocol, host=host, port=port, root=web_root, api_version=api_version
)
api_params = {}
else:
url = '{protocol}{host}:{port}{root}/api/v{api_version}/{apikey}/'.format(
protocol=protocol, host=host, port=port, root=web_root, api_version=api_version, apikey=apikey,
)
api_params = {'cmd': 'postprocess', 'help': '1'}
try:
if api_version >= 2 and sso_username and sso_password:
oauth = OAuth2Session(client=LegacyApplicationClient(client_id=core.SICKRAGE_OAUTH_CLIENT_ID))
oauth_token = oauth.fetch_token(client_id=core.SICKRAGE_OAUTH_CLIENT_ID,
token_url=core.SICKRAGE_OAUTH_TOKEN_URL,
username=sso_username,
password=sso_password)
r = requests.get(url, headers={'Authorization': 'Bearer ' + oauth_token['access_token']}, stream=True, verify=False)
else:
r = requests.get(url, params=api_params, stream=True, verify=False)
if not r.ok:
logger.warning('Connection to {section}:{category} failed! '
'Check your configuration'.format
(section=section, category=input_category))
except requests.ConnectionError:
logger.warning('Could not connect to {0}:{1} to verify API version!'.format(section, input_category))
params = {
'path': None,
'failed': None,
'process_method': None,
'force_replace': None,
'return_data': None,
'type': None,
'delete': None,
'force_next': None,
'is_priority': None
}
fork = ['default', params]
elif fork == 'auto':
fork = init_sickbeard.detect_fork()
logger.info('{section}:{category} fork set to {fork}'.format
(section=section, category=input_category, fork=fork[0]))
core.FORK_SET = fork
return fork[0], fork[1]