74 lines
3.1 KiB
Python

from __future__ import annotations
import logging
import os
import requests
import nzb2media
import nzb2media.utils.common
from nzb2media.auto_process.common import ProcessResult
from nzb2media.utils.encoding import convert_to_ascii
from nzb2media.utils.network import server_responding
from nzb2media.utils.paths import remote_dir
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
def process(*, section: str, dir_name: str, input_name: str = '', input_category: str = '', status: int = 0, **kwargs) -> ProcessResult:
log.debug(f'Unused kwargs: {kwargs}')
# Get configuration
if nzb2media.CFG is None:
raise RuntimeError('Configuration not loaded.')
cfg = nzb2media.CFG[section][input_category]
# Base URL
ssl = int(cfg.get('ssl', 0))
scheme = 'https' if ssl else 'http'
host = cfg['host']
port = cfg['port']
web_root = cfg.get('web_root', '')
# Authentication
apikey = cfg.get('apikey', '')
# Params
remote_path = int(cfg.get('remote_path', 0))
# Misc
apc_version = '2.04'
comicrn_version = '1.01'
# Begin processing
url = nzb2media.utils.common.create_url(scheme, host, port, web_root)
if not server_responding(url):
log.error('Server did not respond. Exiting')
return ProcessResult.failure(f'{section}: Failed to post-process - {section} did not respond.')
input_name, dir_name = convert_to_ascii(input_name, dir_name)
clean_name, ext = os.path.splitext(input_name)
if len(ext) == 4: # we assume this was a standard extension.
input_name = clean_name
params = {'cmd': 'forceProcess', 'apikey': apikey, 'nzb_folder': remote_dir(dir_name) if remote_path else dir_name}
if input_name is not None:
params['nzb_name'] = input_name
params['failed'] = int(status)
params['apc_version'] = apc_version
params['comicrn_version'] = comicrn_version
success = False
log.debug(f'Opening URL: {url}')
try:
response = requests.post(url, params=params, stream=True, verify=False, timeout=(30, 300))
except requests.ConnectionError:
log.error('Unable to open URL')
return ProcessResult.failure(f'{section}: Failed to post-process - Unable to connect to {section}')
log.debug(response.text)
if response.status_code not in [requests.codes.ok, requests.codes.created, requests.codes.accepted]:
log.error(f'Server returned status {response.status_code}')
return ProcessResult.failure(f'{section}: Failed to post-process - Server returned status {response.status_code}')
for line in response.text.split('\n'):
if line:
log.debug(line)
if 'Post Processing SUCCESSFUL' in line:
success = True
if success:
log.debug('SUCCESS: This issue has been processed successfully')
return ProcessResult.success(f'{section}: Successfully post-processed {input_name}')
log.warning('The issue does not appear to have successfully processed. ' 'Please check your Logs')
return ProcessResult.failure(f'{section}: Failed to post-process - Returned log from {section} was not as expected.')