Add peppiness

This commit is contained in:
Labrys of Knossos 2022-12-09 16:20:18 -05:00
commit d2dfd135c6
19 changed files with 172 additions and 170 deletions

View file

@ -392,7 +392,7 @@ def configure_updates():
# Set Current Version # Set Current Version
logger.info( logger.info(
'nzbToMedia Version:{version} Branch:{branch} ({system} {release})'.format(version=NZBTOMEDIA_VERSION, branch=GIT_BRANCH, system=platform.system(), release=platform.release()), f'nzbToMedia Version:{NZBTOMEDIA_VERSION} Branch:{GIT_BRANCH} ({platform.system()} {platform.release()})',
) )

View file

@ -70,7 +70,7 @@ def process(
if not server_responding(url): if not server_responding(url):
logger.error('Server did not respond. Exiting', section) logger.error('Server did not respond. Exiting', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - {section} did not respond.' f'{section}: Failed to post-process - {section} did not respond.',
) )
input_name, dir_name = convert_to_ascii(input_name, dir_name) input_name, dir_name = convert_to_ascii(input_name, dir_name)
@ -89,7 +89,7 @@ def process(
logger.error('Unable to open URL') logger.error('Unable to open URL')
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Unable to connect to ' f'{section}: Failed to post-process - Unable to connect to '
f'{section}' f'{section}',
) )
logger.postprocess(f'{r.text}', section) logger.postprocess(f'{r.text}', section)
@ -98,16 +98,16 @@ def process(
logger.error(f'Server returned status {r.status_code}', section) logger.error(f'Server returned status {r.status_code}', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Server returned status ' f'{section}: Failed to post-process - Server returned status '
f'{r.status_code}' f'{r.status_code}',
) )
elif r.text == 'OK': elif r.text == 'OK':
logger.postprocess(f'SUCCESS: ForceProcess for {dir_name} has been started in LazyLibrarian', section) logger.postprocess(f'SUCCESS: ForceProcess for {dir_name} has been started in LazyLibrarian', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
else: else:
logger.error(f'FAILED: ForceProcess of {dir_name} has Failed in LazyLibrarian', section) logger.error(f'FAILED: ForceProcess of {dir_name} has Failed in LazyLibrarian', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Returned log from {section} ' f'{section}: Failed to post-process - Returned log from {section} '
f'was not as expected.' f'was not as expected.',
) )

View file

@ -72,7 +72,7 @@ def process(
if not server_responding(url): if not server_responding(url):
logger.error('Server did not respond. Exiting', section) logger.error('Server did not respond. Exiting', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - {section} did not respond.' f'{section}: Failed to post-process - {section} did not respond.',
) )
input_name, dir_name = convert_to_ascii(input_name, dir_name) input_name, dir_name = convert_to_ascii(input_name, dir_name)
@ -101,13 +101,13 @@ def process(
logger.error('Unable to open URL', section) logger.error('Unable to open URL', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Unable to connect to ' f'{section}: Failed to post-process - Unable to connect to '
f'{section}' f'{section}',
) )
if r.status_code not in [requests.codes.ok, requests.codes.created, requests.codes.accepted]: if r.status_code not in [requests.codes.ok, requests.codes.created, requests.codes.accepted]:
logger.error(f'Server returned status {r.status_code}', section) logger.error(f'Server returned status {r.status_code}', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Server returned status ' f'{section}: Failed to post-process - Server returned status '
f'{r.status_code}' f'{r.status_code}',
) )
result = r.text result = r.text
@ -122,11 +122,11 @@ def process(
if success: if success:
logger.postprocess('SUCCESS: This issue has been processed successfully', section) logger.postprocess('SUCCESS: This issue has been processed successfully', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
else: else:
logger.warning('The issue does not appear to have successfully processed. Please check your Logs', section) logger.warning('The issue does not appear to have successfully processed. Please check your Logs', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Returned log from ' f'{section}: Failed to post-process - Returned log from '
f'{section} was not as expected.' f'{section} was not as expected.',
) )

View file

@ -69,9 +69,7 @@ def process(
url = core.utils.common.create_url(scheme, host, port, web_root) url = core.utils.common.create_url(scheme, host, port, web_root)
if not server_responding(url): if not server_responding(url):
logger.error('Server did not respond. Exiting', section) logger.error('Server did not respond. Exiting', section)
return ProcessResult.failure( return ProcessResult.failure(f'{section}: Failed to post-process - {section} did not respond.')
f'{section}: Failed to post-process - {section} did not respond.'
)
input_name, dir_name = convert_to_ascii(input_name, dir_name) input_name, dir_name = convert_to_ascii(input_name, dir_name)
@ -96,7 +94,7 @@ def process(
logger.error('Unable to open URL') logger.error('Unable to open URL')
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Unable to connect to ' f'{section}: Failed to post-process - Unable to connect to '
f'{section}' f'{section}',
) )
result = r.json() result = r.json()
@ -108,29 +106,29 @@ def process(
except Exception: except Exception:
logger.error(f'Unable to move {dir_name} to {os.path.join(library, input_name)}', section) logger.error(f'Unable to move {dir_name} to {os.path.join(library, input_name)}', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Unable to move files' f'{section}: Failed to post-process - Unable to move files',
) )
else: else:
logger.error('No library specified to move files to. Please edit your configuration.', section) logger.error('No library specified to move files to. Please edit your configuration.', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - No library defined in ' f'{section}: Failed to post-process - No library defined in '
f'{section}' f'{section}',
) )
if r.status_code not in [requests.codes.ok, requests.codes.created, requests.codes.accepted]: if r.status_code not in [requests.codes.ok, requests.codes.created, requests.codes.accepted]:
logger.error(f'Server returned status {r.status_code}', section) logger.error(f'Server returned status {r.status_code}', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Server returned status ' f'{section}: Failed to post-process - Server returned status '
f'{r.status_code}' f'{r.status_code}',
) )
elif result['success']: elif result['success']:
logger.postprocess(f'SUCCESS: Status for {gamez_id} has been set to {download_status} in Gamez', section) logger.postprocess(f'SUCCESS: Status for {gamez_id} has been set to {download_status} in Gamez', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
else: else:
logger.error(f'FAILED: Status for {gamez_id} has NOT been updated in Gamez', section) logger.error(f'FAILED: Status for {gamez_id} has NOT been updated in Gamez', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Returned log from {section} ' f'{section}: Failed to post-process - Returned log from {section} '
f'was not as expected.' f'was not as expected.',
) )

View file

@ -57,7 +57,7 @@ class PyMedusaApiV1(SickBeard):
) )
return ProcessResult.failure( return ProcessResult.failure(
f'{self.sb_init.section}: Failed to post-process - Unable to ' f'{self.sb_init.section}: Failed to post-process - Unable to '
f'connect to {self.sb_init.section}' f'connect to {self.sb_init.section}',
) )
successful_status_codes = [ successful_status_codes = [
@ -72,18 +72,18 @@ class PyMedusaApiV1(SickBeard):
) )
result = ProcessResult.failure( result = ProcessResult.failure(
f'{self.sb_init.section}: Failed to post-process - Server ' f'{self.sb_init.section}: Failed to post-process - Server '
f'returned status {response.status_code}' f'returned status {response.status_code}',
) )
elif response.json()['result'] == 'success': elif response.json()['result'] == 'success':
result = ProcessResult.success( result = ProcessResult.success(
f'{self.sb_init.section}: Successfully post-processed ' f'{self.sb_init.section}: Successfully post-processed '
f'{self.input_name}' f'{self.input_name}',
) )
else: else:
# We did not receive Success confirmation. # We did not receive Success confirmation.
result = ProcessResult.failure( result = ProcessResult.failure(
f'{self.sb_init.section}: Failed to post-process - Returned ' f'{self.sb_init.section}: Failed to post-process - Returned '
f'log from {self.sb_init.section} was not as expected.' f'log from {self.sb_init.section} was not as expected.',
) )
return result return result
@ -99,7 +99,7 @@ class PyMedusaApiV2(SickBeard):
if not sb_init.apikey: if not sb_init.apikey:
logger.error( logger.error(
'For the section SickBeard `fork = medusa-apiv2` you also ' 'For the section SickBeard `fork = medusa-apiv2` you also '
'need to configure an `apikey`' 'need to configure an `apikey`',
) )
raise ValueError('Missing apikey for fork: medusa-apiv2') raise ValueError('Missing apikey for fork: medusa-apiv2')
@ -160,7 +160,7 @@ class PyMedusaApiV2(SickBeard):
) )
return ProcessResult.failure( return ProcessResult.failure(
f'{self.sb_init.section}: Unable to send postprocess request ' f'{self.sb_init.section}: Unable to send postprocess request '
f'to PyMedusa' f'to PyMedusa',
) )
# Get UUID # Get UUID
@ -203,12 +203,12 @@ class PyMedusaApiV2(SickBeard):
if response.get('success'): if response.get('success'):
result = ProcessResult.success( result = ProcessResult.success(
f'{self.sb_init.section}: Successfully post-processed ' f'{self.sb_init.section}: Successfully post-processed '
f'{self.input_name}' f'{self.input_name}',
) )
else: else:
# We did not receive Success confirmation. # We did not receive Success confirmation.
result = ProcessResult.failure( result = ProcessResult.failure(
f'{self.sb_init.section}: Failed to post-process - Returned ' f'{self.sb_init.section}: Failed to post-process - Returned '
f'log from {self.sb_init.section} was not as expected.' f'log from {self.sb_init.section} was not as expected.',
) )
return result return result

View file

@ -65,7 +65,7 @@ class InitSickBeard:
# keep using determined fork for multiple (manual) post-processing # keep using determined fork for multiple (manual) post-processing
logger.info( logger.info(
f'{self.section}:{self.input_category} fork already set to ' f'{self.section}:{self.input_category} fork already set to '
f'{core.FORK_SET[0]}' f'{core.FORK_SET[0]}',
) )
return core.FORK_SET[0], core.FORK_SET[1] return core.FORK_SET[0], core.FORK_SET[1]
@ -108,13 +108,13 @@ class InitSickBeard:
except requests.ConnectionError: except requests.ConnectionError:
logger.warning( logger.warning(
f'Could not connect to {self.section}:' f'Could not connect to {self.section}:'
f'{self.input_category} to verify fork!' f'{self.input_category} to verify fork!',
) )
if not r.ok: if not r.ok:
logger.warning( logger.warning(
f'Connection to {self.section}:{self.input_category} ' f'Connection to {self.section}:{self.input_category} '
f'failed! Check your configuration' f'failed! Check your configuration',
) )
self.fork = ['default', {}] self.fork = ['default', {}]
@ -148,8 +148,8 @@ class InitSickBeard:
): ):
oauth = OAuth2Session( oauth = OAuth2Session(
client=LegacyApplicationClient( client=LegacyApplicationClient(
client_id=core.SICKRAGE_OAUTH_CLIENT_ID client_id=core.SICKRAGE_OAUTH_CLIENT_ID,
) ),
) )
oauth_token = oauth.fetch_token( oauth_token = oauth.fetch_token(
client_id=core.SICKRAGE_OAUTH_CLIENT_ID, client_id=core.SICKRAGE_OAUTH_CLIENT_ID,
@ -175,12 +175,12 @@ class InitSickBeard:
if not r.ok: if not r.ok:
logger.warning( logger.warning(
f'Connection to {self.section}:{self.input_category} ' f'Connection to {self.section}:{self.input_category} '
f'failed! Check your configuration' f'failed! Check your configuration',
) )
except requests.ConnectionError: except requests.ConnectionError:
logger.warning( logger.warning(
f'Could not connect to {self.section}:' f'Could not connect to {self.section}:'
f'{self.input_category} to verify API version!' f'{self.input_category} to verify API version!',
) )
params = { params = {
@ -201,7 +201,7 @@ class InitSickBeard:
self.detect_fork() self.detect_fork()
logger.info( logger.info(
f'{self.section}:{self.input_category} fork set to {self.fork[0]}' f'{self.section}:{self.input_category} fork set to {self.fork[0]}',
) )
core.FORK_SET = self.fork core.FORK_SET = self.fork
self.fork, self.fork_params = self.fork[0], self.fork[1] self.fork, self.fork_params = self.fork[0], self.fork[1]
@ -235,7 +235,7 @@ class InitSickBeard:
excess_parameters = set(params).difference(optional_parameters) excess_parameters = set(params).difference(optional_parameters)
excess_parameters.remove('cmd') # Don't remove cmd from api params excess_parameters.remove('cmd') # Don't remove cmd from api params
logger.debug( logger.debug(
f'Removing excess parameters: ' f'{sorted(excess_parameters)}' f'Removing excess parameters: ' f'{sorted(excess_parameters)}',
) )
rem_params.extend(excess_parameters) rem_params.extend(excess_parameters)
return rem_params, True return rem_params, True
@ -298,7 +298,7 @@ class InitSickBeard:
except requests.ConnectionError: except requests.ConnectionError:
logger.info( logger.info(
f'Could not connect to {self.section}:{self.input_category} ' f'Could not connect to {self.section}:{self.input_category} '
f'to perform auto-fork detection!' f'to perform auto-fork detection!',
) )
r = [] r = []
@ -323,7 +323,7 @@ class InitSickBeard:
logger.info( logger.info(
f'Could not connect to {self.section}:' f'Could not connect to {self.section}:'
f'{self.input_category} to perform auto-fork ' f'{self.input_category} to perform auto-fork '
f'detection!' f'detection!',
) )
rem_params, found = self._api_check(r, params, rem_params) rem_params, found = self._api_check(r, params, rem_params)
params['cmd'] = 'postprocess' params['cmd'] = 'postprocess'
@ -348,18 +348,18 @@ class InitSickBeard:
self.fork = fork self.fork = fork
logger.info( logger.info(
f'{self.section}:{self.input_category} fork auto-detection ' f'{self.section}:{self.input_category} fork auto-detection '
f'successful ...' f'successful ...',
) )
elif rem_params: elif rem_params:
logger.info( logger.info(
f'{self.section}:{self.input_category} fork auto-detection ' f'{self.section}:{self.input_category} fork auto-detection '
f'found custom params {params}' f'found custom params {params}',
) )
self.fork = ['custom', params] self.fork = ['custom', params]
else: else:
logger.info( logger.info(
f'{self.section}:{self.input_category} fork auto-detection ' f'{self.section}:{self.input_category} fork auto-detection '
f'failed' f'failed',
) )
self.fork = list(core.FORKS.items())[ self.fork = list(core.FORKS.items())[
list(core.FORKS.keys()).index(core.FORK_DEFAULT) list(core.FORKS.keys()).index(core.FORK_DEFAULT)
@ -381,7 +381,7 @@ class InitSickBeard:
else: else:
logger.info( logger.info(
f'{self.section}:{self.input_category} Could not create a ' f'{self.section}:{self.input_category} Could not create a '
f'fork object for {self.fork}. Probaly class not added yet.' f'fork object for {self.fork}. Probaly class not added yet.',
) )
@ -402,7 +402,7 @@ class SickBeard:
self.delete_failed = int(self.sb_init.config.get('delete_failed', 0)) self.delete_failed = int(self.sb_init.config.get('delete_failed', 0))
self.nzb_extraction_by = self.sb_init.config.get( self.nzb_extraction_by = self.sb_init.config.get(
'nzbExtractionBy', 'Downloader' 'nzbExtractionBy', 'Downloader',
) )
self.process_method = self.sb_init.config.get('process_method') self.process_method = self.sb_init.config.get('process_method')
self.remote_path = int(self.sb_init.config.get('remote_path', 0)) self.remote_path = int(self.sb_init.config.get('remote_path', 0))
@ -581,11 +581,11 @@ class SickBeard:
) )
except requests.ConnectionError: except requests.ConnectionError:
logger.error( logger.error(
f'Unable to open URL: {self.url}', self.sb_init.section f'Unable to open URL: {self.url}', self.sb_init.section,
) )
result = ProcessResult.failure( result = ProcessResult.failure(
f'{self.sb_init.section}: Failed to post-process - Unable to ' f'{self.sb_init.section}: Failed to post-process - Unable to '
f'connect to {self.sb_init.section}' f'connect to {self.sb_init.section}',
) )
else: else:
successful_statuses = [ successful_statuses = [
@ -600,7 +600,7 @@ class SickBeard:
) )
result = ProcessResult.failure( result = ProcessResult.failure(
f'{self.sb_init.section}: Failed to post-process - Server ' f'{self.sb_init.section}: Failed to post-process - Server '
f'returned status {response.status_code}' f'returned status {response.status_code}',
) )
else: else:
result = self.process_response(response) result = self.process_response(response)
@ -631,12 +631,12 @@ class SickBeard:
if self.success: if self.success:
result = ProcessResult.success( result = ProcessResult.success(
f'{self.sb_init.section}: Successfully post-processed ' f'{self.sb_init.section}: Successfully post-processed '
f'{self.input_name}' f'{self.input_name}',
) )
else: else:
# We did not receive Success confirmation. # We did not receive Success confirmation.
result = ProcessResult.failure( result = ProcessResult.failure(
f'{self.sb_init.section}: Failed to post-process - Returned ' f'{self.sb_init.section}: Failed to post-process - Returned '
f'log from {self.sb_init.section} was not as expected.' f'log from {self.sb_init.section} was not as expected.',
) )
return result return result

View file

@ -104,9 +104,7 @@ def process(
release = None release = None
else: else:
logger.error('Server did not respond. Exiting', section) logger.error('Server did not respond. Exiting', section)
return ProcessResult.failure( return ProcessResult.failure(f'{section}: Failed to post-process - {section} did not respond.')
f'{section}: Failed to post-process - {section} did not respond.'
)
# pull info from release found if available # pull info from release found if available
release_id = None release_id = None
@ -296,8 +294,10 @@ def process(
status_code=1, status_code=1,
) )
else: else:
logger.error(f'FAILED: {method} scan was unable to finish for folder {dir_name}. exiting!', logger.error(
section) f'FAILED: {method} scan was unable to finish for folder {dir_name}. exiting!',
section,
)
return ProcessResult( return ProcessResult(
message=f'{section}: Failed to post-process - Server did not return success', message=f'{section}: Failed to post-process - Server did not return success',
status_code=1, status_code=1,
@ -334,8 +334,10 @@ def process(
remove_dir(dir_name) remove_dir(dir_name)
if not release_id and not media_id: if not release_id and not media_id:
logger.error(f'Could not find a downloaded movie in the database matching {input_name}, exiting!', logger.error(
section) f'Could not find a downloaded movie in the database matching {input_name}, exiting!',
section,
)
return ProcessResult( return ProcessResult(
message='{0}: Failed to post-process - Failed download not found in {0}'.format(section), message='{0}: Failed to post-process - Failed download not found in {0}'.format(section),
status_code=1, status_code=1,
@ -385,7 +387,7 @@ def process(
logger.error(f'Unable to open URL {url}', section) logger.error(f'Unable to open URL {url}', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Unable to connect to ' f'{section}: Failed to post-process - Unable to connect to '
f'{section}' f'{section}',
) )
result = r.json() result = r.json()
@ -393,18 +395,18 @@ def process(
logger.error(f'Server returned status {r.status_code}', section) logger.error(f'Server returned status {r.status_code}', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Server returned status ' f'{section}: Failed to post-process - Server returned status '
f'{r.status_code}' f'{r.status_code}',
) )
elif result['success']: elif result['success']:
logger.postprocess('SUCCESS: Snatched the next highest release ...', section) logger.postprocess('SUCCESS: Snatched the next highest release ...', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully snatched next highest release' f'{section}: Successfully snatched next highest release',
) )
else: else:
logger.postprocess('SUCCESS: Unable to find a new release to snatch now. CP will keep searching!', section) logger.postprocess('SUCCESS: Unable to find a new release to snatch now. CP will keep searching!', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: No new release found now. ' f'{section}: No new release found now. '
f'{section} will keep searching' f'{section} will keep searching',
) )
# Added a release that was not in the wanted list so confirm rename successful by finding this movie media.list. # Added a release that was not in the wanted list so confirm rename successful by finding this movie media.list.
@ -414,7 +416,7 @@ def process(
if no_status_check: if no_status_check:
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully processed but no change in status ' f'{section}: Successfully processed but no change in status '
f'confirmed' f'confirmed',
) )
# we will now check to see if CPS has finished renaming before returning to TorrentToMedia and unpausing. # we will now check to see if CPS has finished renaming before returning to TorrentToMedia and unpausing.
@ -434,13 +436,13 @@ def process(
title = release[release_id]['title'] title = release[release_id]['title']
logger.postprocess(f'SUCCESS: Movie {title} has now been added to CouchPotato with release status of [{str(release_status_new).upper()}]', section) logger.postprocess(f'SUCCESS: Movie {title} has now been added to CouchPotato with release status of [{str(release_status_new).upper()}]', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
if release_status_new != release_status_old: if release_status_new != release_status_old:
logger.postprocess(f'SUCCESS: Release {release_id} has now been marked with a status of [{str(release_status_new).upper()}]', section) logger.postprocess(f'SUCCESS: Release {release_id} has now been marked with a status of [{str(release_status_new).upper()}]', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
except Exception: except Exception:
pass pass
@ -452,7 +454,7 @@ def process(
if command_status in ['completed']: if command_status in ['completed']:
logger.debug('The Scan command has completed successfully. Renaming was successful.', section) logger.debug('The Scan command has completed successfully. Renaming was successful.', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
elif command_status in ['failed']: elif command_status in ['failed']:
logger.debug('The Scan command has failed. Renaming was not successful.', section) logger.debug('The Scan command has failed. Renaming was not successful.', section)
@ -464,13 +466,13 @@ def process(
if not os.path.isdir(dir_name): if not os.path.isdir(dir_name):
logger.postprocess(f'SUCCESS: Input Directory [{dir_name}] has been processed and removed', section) logger.postprocess(f'SUCCESS: Input Directory [{dir_name}] has been processed and removed', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
elif not list_media_files(dir_name, media=True, audio=False, meta=False, archives=True): elif not list_media_files(dir_name, media=True, audio=False, meta=False, archives=True):
logger.postprocess(f'SUCCESS: Input Directory [{dir_name}] has no remaining media files. This has been fully processed.', section) logger.postprocess(f'SUCCESS: Input Directory [{dir_name}] has no remaining media files. This has been fully processed.', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
# pause and let CouchPotatoServer/Radarr catch its breath # pause and let CouchPotatoServer/Radarr catch its breath
@ -481,7 +483,7 @@ def process(
logger.debug(f'The Scan command did not return status completed, but complete Download Handling is enabled. Passing back to {section}.', section) logger.debug(f'The Scan command did not return status completed, but complete Download Handling is enabled. Passing back to {section}.', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Complete DownLoad Handling is enabled. Passing back ' f'{section}: Complete DownLoad Handling is enabled. Passing back '
f'to {section}' f'to {section}',
) )
logger.warning( logger.warning(
f'{input_name} does not appear to have changed status after {wait_for} minutes, Please check your logs.', f'{input_name} does not appear to have changed status after {wait_for} minutes, Please check your logs.',
@ -489,7 +491,7 @@ def process(
) )
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - No change in status' f'{section}: Failed to post-process - No change in status',
) )

View file

@ -77,7 +77,7 @@ def process(
if not server_responding(url): if not server_responding(url):
logger.error('Server did not respond. Exiting', section) logger.error('Server did not respond. Exiting', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - {section} did not respond.' f'{section}: Failed to post-process - {section} did not respond.',
) )
if not os.path.isdir(dir_name) and os.path.isfile(dir_name): # If the input directory is a file, assume single file download and split dir/name. if not os.path.isdir(dir_name) and os.path.isfile(dir_name): # If the input directory is a file, assume single file download and split dir/name.
@ -127,7 +127,7 @@ def process(
# The status hasn't changed. uTorrent can resume seeding now. # The status hasn't changed. uTorrent can resume seeding now.
logger.warning(f'The music album does not appear to have changed status after {wait_for} minutes. Please check your Logs', section) logger.warning(f'The music album does not appear to have changed status after {wait_for} minutes. Please check your Logs', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - No change in wanted status' f'{section}: Failed to post-process - No change in wanted status',
) )
elif status == 0 and section == 'Lidarr': elif status == 0 and section == 'Lidarr':
@ -148,7 +148,7 @@ def process(
logger.error(f'Unable to open URL: {url}', section) logger.error(f'Unable to open URL: {url}', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Unable to connect to ' f'{section}: Failed to post-process - Unable to connect to '
f'{section}' f'{section}',
) )
try: try:
@ -158,7 +158,7 @@ def process(
except Exception as e: except Exception as e:
logger.warning(f'No scan id was returned due to: {e}', section) logger.warning(f'No scan id was returned due to: {e}', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Unable to start scan' f'{section}: Failed to post-process - Unable to start scan',
) )
n = 0 n = 0
@ -175,12 +175,12 @@ def process(
if not os.path.exists(dir_name): if not os.path.exists(dir_name):
logger.debug(f'The directory {dir_name} has been removed. Renaming was successful.', section) logger.debug(f'The directory {dir_name} has been removed. Renaming was successful.', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
elif command_status and command_status in ['completed']: elif command_status and command_status in ['completed']:
logger.debug('The Scan command has completed successfully. Renaming was successful.', section) logger.debug('The Scan command has completed successfully. Renaming was successful.', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
elif command_status and command_status in ['failed']: elif command_status and command_status in ['failed']:
logger.debug('The Scan command has failed. Renaming was not successful.', section) logger.debug('The Scan command has failed. Renaming was not successful.', section)
@ -200,7 +200,7 @@ def process(
logger.postprocess(f'FAILED: The download failed. Sending failed download to {section} for CDH processing', section) logger.postprocess(f'FAILED: The download failed. Sending failed download to {section} for CDH processing', section)
# Return as failed to flag this in the downloader. # Return as failed to flag this in the downloader.
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Download Failed. Sending back to {section}' f'{section}: Download Failed. Sending back to {section}',
) )
else: else:
logger.warning('FAILED DOWNLOAD DETECTED', section) logger.warning('FAILED DOWNLOAD DETECTED', section)
@ -210,7 +210,7 @@ def process(
# Return as failed to flag this in the downloader. # Return as failed to flag this in the downloader.
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process. {section} does not ' f'{section}: Failed to post-process. {section} does not '
f'support failed downloads' f'support failed downloads',
) )
@ -254,7 +254,7 @@ def force_process(params, url, apikey, input_name, dir_name, section, wait_for):
logger.error(f'Unable to open URL {url}', section) logger.error(f'Unable to open URL {url}', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Unable to connect to ' f'{section}: Failed to post-process - Unable to connect to '
f'{section}' f'{section}',
) )
logger.debug(f'Result: {r.text}', section) logger.debug(f'Result: {r.text}', section)
@ -262,7 +262,7 @@ def force_process(params, url, apikey, input_name, dir_name, section, wait_for):
if r.status_code not in [requests.codes.ok, requests.codes.created, requests.codes.accepted]: if r.status_code not in [requests.codes.ok, requests.codes.created, requests.codes.accepted]:
logger.error(f'Server returned status {r.status_code}', section) logger.error(f'Server returned status {r.status_code}', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Server returned status {r.status_code}' f'{section}: Failed to post-process - Server returned status {r.status_code}',
) )
elif r.text == 'OK': elif r.text == 'OK':
logger.postprocess(f'SUCCESS: Post-Processing started for {input_name} in folder {dir_name} ...', section) logger.postprocess(f'SUCCESS: Post-Processing started for {input_name} in folder {dir_name} ...', section)
@ -270,7 +270,7 @@ def force_process(params, url, apikey, input_name, dir_name, section, wait_for):
logger.error(f'FAILED: Post-Processing has NOT started for {input_name} in folder {dir_name}. exiting!', section) logger.error(f'FAILED: Post-Processing has NOT started for {input_name} in folder {dir_name}. exiting!', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Returned log from {section} ' f'{section}: Failed to post-process - Returned log from {section} '
f'was not as expected.' f'was not as expected.',
) )
# we will now wait for this album to be processed before returning to TorrentToMedia and unpausing. # we will now wait for this album to be processed before returning to TorrentToMedia and unpausing.
@ -280,12 +280,12 @@ def force_process(params, url, apikey, input_name, dir_name, section, wait_for):
if current_status is not None and current_status != release_status: # Something has changed. CPS must have processed this movie. if current_status is not None and current_status != release_status: # Something has changed. CPS must have processed this movie.
logger.postprocess(f'SUCCESS: This release is now marked as status [{current_status}]', section) logger.postprocess(f'SUCCESS: This release is now marked as status [{current_status}]', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
if not os.path.isdir(dir_name): if not os.path.isdir(dir_name):
logger.postprocess(f'SUCCESS: The input directory {dir_name} has been removed Processing must have finished.', section) logger.postprocess(f'SUCCESS: The input directory {dir_name} has been removed Processing must have finished.', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
time.sleep(10 * wait_for) time.sleep(10 * wait_for)
# The status hasn't changed. # The status hasn't changed.

View file

@ -102,7 +102,7 @@ def process(
else: else:
logger.error('Server did not respond. Exiting', section) logger.error('Server did not respond. Exiting', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - {section} did not respond.' f'{section}: Failed to post-process - {section} did not respond.',
) )
if client_agent == core.TORRENT_CLIENT_AGENT and core.USE_LINK == 'move-sym': if client_agent == core.TORRENT_CLIENT_AGENT and core.USE_LINK == 'move-sym':
@ -206,7 +206,7 @@ def process(
else: else:
logger.error(f'FAILED: Transcoding failed for files in {dir_name}', section) logger.error(f'FAILED: Transcoding failed for files in {dir_name}', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Transcoding failed' f'{section}: Failed to post-process - Transcoding failed',
) )
# Part of the refactor # Part of the refactor
@ -282,7 +282,7 @@ def process(
if section == 'NzbDrone' and not apikey: if section == 'NzbDrone' and not apikey:
logger.info('No Sonarr apikey entered. Processing completed.') logger.info('No Sonarr apikey entered. Processing completed.')
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
logger.postprocess('SUCCESS: The download succeeded, sending a post-process request', section) logger.postprocess('SUCCESS: The download succeeded, sending a post-process request', section)
else: else:
@ -295,7 +295,7 @@ def process(
logger.postprocess(f'FAILED: The download failed. Sending failed download to {fork} for CDH processing', section) logger.postprocess(f'FAILED: The download failed. Sending failed download to {fork} for CDH processing', section)
# Return as failed to flag this in the downloader. # Return as failed to flag this in the downloader.
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Download Failed. Sending back to {section}' f'{section}: Download Failed. Sending back to {section}',
) )
else: else:
logger.postprocess(f'FAILED: The download failed. {fork} branch does not handle failed downloads. Nothing to process', section) logger.postprocess(f'FAILED: The download failed. {fork} branch does not handle failed downloads. Nothing to process', section)
@ -303,10 +303,7 @@ def process(
logger.postprocess(f'Deleting failed files and folder {dir_name}', section) logger.postprocess(f'Deleting failed files and folder {dir_name}', section)
remove_dir(dir_name) remove_dir(dir_name)
# Return as failed to flag this in the downloader. # Return as failed to flag this in the downloader.
return ProcessResult.failure( return ProcessResult.failure(f'{section}: Failed to post-process. {section} does not support failed downloads')
f'{section}: Failed to post-process. {section} does not '
f'support failed downloads'
)
route = '' route = ''
if section == 'SickBeard': if section == 'SickBeard':
@ -360,10 +357,12 @@ def process(
if api_version >= 2 and sso_username and sso_password: if api_version >= 2 and sso_username and sso_password:
oauth = OAuth2Session(client=LegacyApplicationClient(client_id=core.SICKRAGE_OAUTH_CLIENT_ID)) oauth = OAuth2Session(client=LegacyApplicationClient(client_id=core.SICKRAGE_OAUTH_CLIENT_ID))
oauth_token = oauth.fetch_token(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, token_url=core.SICKRAGE_OAUTH_TOKEN_URL,
username=sso_username, username=sso_username,
password=sso_password) password=sso_password,
)
s.headers.update({'Authorization': 'Bearer ' + oauth_token['access_token']}) s.headers.update({'Authorization': 'Bearer ' + oauth_token['access_token']})
params = { params = {
@ -374,7 +373,7 @@ def process(
'returnData': str(bool(fork_params['return_data'])).lower(), 'returnData': str(bool(fork_params['return_data'])).lower(),
'delete': str(bool(fork_params['delete'])).lower(), 'delete': str(bool(fork_params['delete'])).lower(),
'forceNext': str(bool(fork_params['force_next'])).lower(), 'forceNext': str(bool(fork_params['force_next'])).lower(),
'nzbName': fork_params['nzbName'] 'nzbName': fork_params['nzbName'],
} }
else: else:
params = fork_params params = fork_params
@ -387,14 +386,14 @@ def process(
logger.error(f'Unable to open URL: {url}', section) logger.error(f'Unable to open URL: {url}', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Unable to connect to ' f'{section}: Failed to post-process - Unable to connect to '
f'{section}' f'{section}',
) )
if r.status_code not in [requests.codes.ok, requests.codes.created, requests.codes.accepted]: if r.status_code not in [requests.codes.ok, requests.codes.created, requests.codes.accepted]:
logger.error(f'Server returned status {r.status_code}', section) logger.error(f'Server returned status {r.status_code}', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Server returned status ' f'{section}: Failed to post-process - Server returned status '
f'{r.status_code}' f'{r.status_code}',
) )
success = False success = False
@ -441,7 +440,7 @@ def process(
if success: if success:
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
elif section == 'NzbDrone' and started: elif section == 'NzbDrone' and started:
n = 0 n = 0
@ -458,12 +457,12 @@ def process(
if not os.path.exists(dir_name): if not os.path.exists(dir_name):
logger.debug(f'The directory {dir_name} has been removed. Renaming was successful.', section) logger.debug(f'The directory {dir_name} has been removed. Renaming was successful.', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
elif command_status and command_status in ['completed']: elif command_status and command_status in ['completed']:
logger.debug('The Scan command has completed successfully. Renaming was successful.', section) logger.debug('The Scan command has completed successfully. Renaming was successful.', section)
return ProcessResult.success( return ProcessResult.success(
f'{section}: Successfully post-processed {input_name}' f'{section}: Successfully post-processed {input_name}',
) )
elif command_status and command_status in ['failed']: elif command_status and command_status in ['failed']:
logger.debug('The Scan command has failed. Renaming was not successful.', section) logger.debug('The Scan command has failed. Renaming was not successful.', section)
@ -473,8 +472,10 @@ def process(
url2 = core.utils.common.create_url(scheme, host, port, route) url2 = core.utils.common.create_url(scheme, host, port, route)
if completed_download_handling(url2, headers, section=section): if completed_download_handling(url2, headers, section=section):
logger.debug(f'The Scan command did not return status completed, but complete Download Handling is enabled. Passing back to {section}.', logger.debug(
section) f'The Scan command did not return status completed, but complete Download Handling is enabled. Passing back to {section}.',
section,
)
return ProcessResult( return ProcessResult(
message=f'{section}: Complete DownLoad Handling is enabled. ' message=f'{section}: Complete DownLoad Handling is enabled. '
f'Passing back to {section}', f'Passing back to {section}',
@ -483,11 +484,11 @@ def process(
else: else:
logger.warning('The Scan command did not return a valid status. Renaming was not successful.', section) logger.warning('The Scan command did not return a valid status. Renaming was not successful.', section)
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process {input_name}' f'{section}: Failed to post-process {input_name}',
) )
else: else:
# We did not receive Success confirmation. # We did not receive Success confirmation.
return ProcessResult.failure( return ProcessResult.failure(
f'{section}: Failed to post-process - Returned log from {section} ' f'{section}: Failed to post-process - Returned log from {section} '
f'was not as expected.' f'was not as expected.',
) )

View file

@ -41,12 +41,12 @@ class InitialSchema(main_db.SchemaUpgrade):
if cur_db_version < MIN_DB_VERSION: if cur_db_version < MIN_DB_VERSION:
logger.log_error_and_exit( logger.log_error_and_exit(
'Your database version ({current}) is too old to migrate from what this version of nzbToMedia supports ({min}).\nPlease remove nzbtomedia.db file to begin fresh.'.format(current=cur_db_version, min=MIN_DB_VERSION), f'Your database version ({cur_db_version}) is too old to migrate from what this version of nzbToMedia supports ({MIN_DB_VERSION}).\nPlease remove nzbtomedia.db file to begin fresh.',
) )
if cur_db_version > MAX_DB_VERSION: if cur_db_version > MAX_DB_VERSION:
logger.log_error_and_exit( logger.log_error_and_exit(
'Your database version ({current}) has been incremented past what this version of nzbToMedia supports ({max}).\nIf you have used other forks of nzbToMedia, your database may be unusable due to their modifications.'.format(current=cur_db_version, max=MAX_DB_VERSION), f'Your database version ({cur_db_version}) has been incremented past what this version of nzbToMedia supports ({MAX_DB_VERSION}).\nIf you have used other forks of nzbToMedia, your database may be unusable due to their modifications.',
) )
if cur_db_version < MAX_DB_VERSION: # We need to upgrade. if cur_db_version < MAX_DB_VERSION: # We need to upgrade.
queries = [ queries = [

View file

@ -46,8 +46,10 @@ def extract(file_path, output_destination):
if not os.getenv('TR_TORRENT_DIR'): if not os.getenv('TR_TORRENT_DIR'):
devnull = open(os.devnull, 'w') devnull = open(os.devnull, 'w')
for cmd in required_cmds: for cmd in required_cmds:
if call(['which', cmd], stdout=devnull, if call(
stderr=devnull): # note, returns 0 if exists, or 1 if doesn't exist. ['which', cmd], stdout=devnull,
stderr=devnull,
): # note, returns 0 if exists, or 1 if doesn't exist.
for k, v in extract_commands.items(): for k, v in extract_commands.items():
if cmd in v[0]: if cmd in v[0]:
if not call(['which', '7zr'], stdout=devnull, stderr=devnull): # we do have '7zr' if not call(['which', '7zr'], stdout=devnull, stderr=devnull): # we do have '7zr'
@ -57,9 +59,7 @@ def extract(file_path, output_destination):
elif not call(['which', '7za'], stdout=devnull, stderr=devnull): # we do have '7za' elif not call(['which', '7za'], stdout=devnull, stderr=devnull): # we do have '7za'
extract_commands[k] = ['7za', 'x', '-y'] extract_commands[k] = ['7za', 'x', '-y']
else: else:
core.logger.error('EXTRACTOR: {cmd} not found, ' core.logger.error(f'EXTRACTOR: {cmd} not found, disabling support for {k}')
'disabling support for {feature}'.format
(cmd=cmd, feature=k))
del extract_commands[k] del extract_commands[k]
devnull.close() devnull.close()
else: else:
@ -84,8 +84,7 @@ def extract(file_path, output_destination):
if ext[1] in extract_commands: if ext[1] in extract_commands:
cmd = extract_commands[ext[1]] cmd = extract_commands[ext[1]]
else: else:
core.logger.debug('EXTRACTOR: Unknown file type: {ext}'.format core.logger.debug(f'EXTRACTOR: Unknown file type: {ext[1]}')
(ext=ext[1]))
return False return False
# Create outputDestination folder # Create outputDestination folder
@ -96,10 +95,8 @@ def extract(file_path, output_destination):
else: else:
passwords = [] passwords = []
core.logger.info('Extracting {file} to {destination}'.format core.logger.info(f'Extracting {file_path} to {output_destination}')
(file=file_path, destination=output_destination)) core.logger.debug(f'Extracting {cmd} {file_path} {output_destination}')
core.logger.debug('Extracting {cmd} {file} {destination}'.format
(cmd=cmd, file=file_path, destination=output_destination))
orig_files = [] orig_files = []
orig_dirs = [] orig_dirs = []
@ -122,13 +119,12 @@ def extract(file_path, output_destination):
else: else:
cmd = core.NICENESS + cmd cmd = core.NICENESS + cmd
cmd2 = cmd cmd2 = cmd
if not 'gunzip' in cmd: #gunzip doesn't support password if not 'gunzip' in cmd: # gunzip doesn't support password
cmd2.append('-p-') # don't prompt for password. cmd2.append('-p-') # don't prompt for password.
p = Popen(cmd2, stdout=devnull, stderr=devnull, startupinfo=info) # should extract files fine. p = Popen(cmd2, stdout=devnull, stderr=devnull, startupinfo=info) # should extract files fine.
res = p.wait() res = p.wait()
if res == 0: # Both Linux and Windows return 0 for successful. if res == 0: # Both Linux and Windows return 0 for successful.
core.logger.info('EXTRACTOR: Extraction was successful for {file} to {destination}'.format core.logger.info(f'EXTRACTOR: Extraction was successful for {file_path} to {output_destination}')
(file=file_path, destination=output_destination))
success = 1 success = 1
elif len(passwords) > 0 and not 'gunzip' in cmd: elif len(passwords) > 0 and not 'gunzip' in cmd:
core.logger.info('EXTRACTOR: Attempting to extract with passwords') core.logger.info('EXTRACTOR: Attempting to extract with passwords')
@ -142,17 +138,13 @@ def extract(file_path, output_destination):
p = Popen(cmd2, stdout=devnull, stderr=devnull, startupinfo=info) # should extract files fine. p = Popen(cmd2, stdout=devnull, stderr=devnull, startupinfo=info) # should extract files fine.
res = p.wait() res = p.wait()
if (res >= 0 and platform == 'Windows') or res == 0: if (res >= 0 and platform == 'Windows') or res == 0:
core.logger.info('EXTRACTOR: Extraction was successful ' core.logger.info(f'EXTRACTOR: Extraction was successful for {file_path} to {output_destination} using password: {password}')
'for {file} to {destination} using password: {pwd}'.format
(file=file_path, destination=output_destination, pwd=password))
success = 1 success = 1
break break
else: else:
continue continue
except Exception: except Exception:
core.logger.error('EXTRACTOR: Extraction failed for {file}. ' core.logger.error(f'EXTRACTOR: Extraction failed for {file_path}. Could not call command {cmd}')
'Could not call command {cmd}'.format
(file=file_path, cmd=cmd))
os.chdir(pwd) os.chdir(pwd)
return False return False
@ -177,7 +169,5 @@ def extract(file_path, output_destination):
pass pass
return True return True
else: else:
core.logger.error('EXTRACTOR: Extraction failed for {file}. ' core.logger.error(f'EXTRACTOR: Extraction failed for {file_path}. Result was {res}')
'Result was {result}'.format
(file=file_path, result=res))
return False return False

View file

@ -57,7 +57,7 @@ class DBConnection:
sql_result = cursor.fetchone()[0] sql_result = cursor.fetchone()[0]
else: else:
logger.log( logger.log(
'{name}: {query} with args {args}'.format(name=self.filename, query=query, args=args), logger.DB, f'{self.filename}: {query} with args {args}', logger.DB,
) )
cursor = self.connection.cursor() cursor = self.connection.cursor()
cursor.execute(query, args) cursor.execute(query, args)
@ -133,7 +133,7 @@ class DBConnection:
sql_result = self.connection.execute(query) sql_result = self.connection.execute(query)
else: else:
logger.log( logger.log(
'{name}: {query} with args {args}'.format(name=self.filename, query=query, args=args), logger.DB, f'{self.filename}: {query} with args {args}', logger.DB,
) )
sql_result = self.connection.execute(query, args) sql_result = self.connection.execute(query, args)
self.connection.commit() self.connection.commit()
@ -231,25 +231,25 @@ def pretty_name(class_name):
def _process_upgrade(connection, upgrade_class): def _process_upgrade(connection, upgrade_class):
instance = upgrade_class(connection) instance = upgrade_class(connection)
logger.log( logger.log(
'Checking {name} database upgrade'.format(name=pretty_name(upgrade_class.__name__)), logger.DEBUG, f'Checking {pretty_name(upgrade_class.__name__)} database upgrade', logger.DEBUG,
) )
if not instance.test(): if not instance.test():
logger.log( logger.log(
'Database upgrade required: {name}'.format(name=pretty_name(upgrade_class.__name__)), logger.MESSAGE, f'Database upgrade required: {pretty_name(upgrade_class.__name__)}', logger.MESSAGE,
) )
try: try:
instance.execute() instance.execute()
except sqlite3.DatabaseError as error: except sqlite3.DatabaseError as error:
print( print(
'Error in {name}: {msg}'.format(name=upgrade_class.__name__, msg=error), f'Error in {upgrade_class.__name__}: {error}',
) )
raise raise
logger.log( logger.log(
'{name} upgrade completed'.format(name=upgrade_class.__name__), logger.DEBUG, f'{upgrade_class.__name__} upgrade completed', logger.DEBUG,
) )
else: else:
logger.log( logger.log(
'{name} upgrade not required'.format(name=upgrade_class.__name__), logger.DEBUG, f'{upgrade_class.__name__} upgrade not required', logger.DEBUG,
) )
for upgradeSubClass in upgrade_class.__subclasses__(): for upgradeSubClass in upgrade_class.__subclasses__():

View file

@ -41,6 +41,7 @@ def import_subs(filename):
except Exception as e: except Exception as e:
logger.error(f'Failed to download subtitles for {filename} due to: {e}', 'SUBTITLES') logger.error(f'Failed to download subtitles for {filename} due to: {e}', 'SUBTITLES')
def rename_subs(path): def rename_subs(path):
filepaths = [] filepaths = []
sub_ext = ['.srt', '.sub', '.idx'] sub_ext = ['.srt', '.sub', '.idx']
@ -52,13 +53,13 @@ def rename_subs(path):
for filename in filenames: for filename in filenames:
filepaths.extend([os.path.join(directory, filename)]) filepaths.extend([os.path.join(directory, filename)])
subfiles = [item for item in filepaths if os.path.splitext(item)[1] in sub_ext] subfiles = [item for item in filepaths if os.path.splitext(item)[1] in sub_ext]
subfiles.sort() #This should sort subtitle names by language (alpha) and Number (where multiple) subfiles.sort() # This should sort subtitle names by language (alpha) and Number (where multiple)
renamed = [] renamed = []
for sub in subfiles: for sub in subfiles:
subname, ext = os.path.splitext(os.path.basename(sub)) subname, ext = os.path.splitext(os.path.basename(sub))
if name in subname: # The sub file name already includes the video name. if name in subname: # The sub file name already includes the video name.
continue continue
words = re.findall('[a-zA-Z]+',str(subname)) # find whole words in string words = re.findall('[a-zA-Z]+', str(subname)) # find whole words in string
# parse the words for language descriptors. # parse the words for language descriptors.
lan = None lan = None
for word in words: for word in words:
@ -71,7 +72,7 @@ def rename_subs(path):
lan = Language.fromname(word.lower()) lan = Language.fromname(word.lower())
if lan: if lan:
break break
except: #if we didn't find a language, try next word. except: # if we didn't find a language, try next word.
continue continue
# rename the sub file as name.lan.ext # rename the sub file as name.lan.ext
if not lan: if not lan:
@ -81,7 +82,7 @@ def rename_subs(path):
new_sub_name = f'{name}.{str(lan)}' new_sub_name = f'{name}.{str(lan)}'
new_sub = os.path.join(directory, new_sub_name) # full path and name less ext new_sub = os.path.join(directory, new_sub_name) # full path and name less ext
if f'{new_sub}{ext}' in renamed: # If duplicate names, add unique number before ext. if f'{new_sub}{ext}' in renamed: # If duplicate names, add unique number before ext.
for i in range(1,len(renamed)+1): for i in range(1, len(renamed) + 1):
if f'{new_sub}.{i}{ext}' in renamed: if f'{new_sub}.{i}{ext}' in renamed:
continue continue
new_sub = f'{new_sub}.{i}' new_sub = f'{new_sub}.{i}'
@ -90,8 +91,9 @@ def rename_subs(path):
if os.path.isfile(new_sub): # Don't copy over existing - final check. if os.path.isfile(new_sub): # Don't copy over existing - final check.
logger.debug(f'Unable to rename sub file {sub} as destination {new_sub} already exists') logger.debug(f'Unable to rename sub file {sub} as destination {new_sub} already exists')
continue continue
logger.debug('Renaming sub file from {old} to {new}'.format logger.debug(
(old=sub, new=new_sub)) f'Renaming sub file from {sub} to {new_sub}',
)
renamed.append(new_sub) renamed.append(new_sub)
try: try:
os.rename(sub, new_sub) os.rename(sub, new_sub)

View file

@ -13,7 +13,8 @@ from core.utils import (
def process(): def process():
# Perform Manual Post-Processing # Perform Manual Post-Processing
logger.warning( logger.warning(
'Invalid number of arguments received from client, Switching to manual run mode ...') 'Invalid number of arguments received from client, Switching to manual run mode ...',
)
# Post-Processing Result # Post-Processing Result
result = ProcessResult( result = ProcessResult(
@ -27,13 +28,15 @@ def process():
continue continue
for dir_name in get_dirs(section, subsection, link='move'): for dir_name in get_dirs(section, subsection, link='move'):
logger.info( logger.info(
f'Starting manual run for {section}:{subsection} - Folder: {dir_name}') f'Starting manual run for {section}:{subsection} - Folder: {dir_name}',
)
logger.info( logger.info(
f'Checking database for download info for {os.path.basename(dir_name)} ...' f'Checking database for download info for {os.path.basename(dir_name)} ...',
) )
core.DOWNLOAD_INFO = get_download_info( core.DOWNLOAD_INFO = get_download_info(
os.path.basename(dir_name), 0) os.path.basename(dir_name), 0,
)
if core.DOWNLOAD_INFO: if core.DOWNLOAD_INFO:
logger.info(f'Found download info for {os.path.basename(dir_name)}, setting variables now ...') logger.info(f'Found download info for {os.path.basename(dir_name)}, setting variables now ...')
client_agent = core.DOWNLOAD_INFO[0]['client_agent'] or 'manual' client_agent = core.DOWNLOAD_INFO[0]['client_agent'] or 'manual'
@ -48,12 +51,15 @@ def process():
input_name = os.path.basename(dir_name) input_name = os.path.basename(dir_name)
results = nzb.process(dir_name, input_name, 0, results = nzb.process(
dir_name, input_name, 0,
client_agent=client_agent, client_agent=client_agent,
download_id=download_id or None, download_id=download_id or None,
input_category=subsection) input_category=subsection,
)
if results.status_code != 0: if results.status_code != 0:
logger.error( logger.error(
f'A problem was reported when trying to perform a manual run for {section}:{subsection}.') f'A problem was reported when trying to perform a manual run for {section}:{subsection}.',
)
result = results result = results
return result return result

View file

@ -19,7 +19,8 @@ from core.utils import (
def process(input_directory, input_name=None, status=0, client_agent='manual', download_id=None, input_category=None, failure_link=None): def process(input_directory, input_name=None, status=0, client_agent='manual', download_id=None, input_category=None, failure_link=None):
if core.SAFE_MODE and input_directory == core.NZB_DEFAULT_DIRECTORY: if core.SAFE_MODE and input_directory == core.NZB_DEFAULT_DIRECTORY:
logger.error( logger.error(
f'The input directory:[{input_directory}] is the Default Download Directory. Please configure category directories to prevent processing of other media.') f'The input directory:[{input_directory}] is the Default Download Directory. Please configure category directories to prevent processing of other media.',
)
return ProcessResult( return ProcessResult(
message='', message='',
status_code=-1, status_code=-1,
@ -62,7 +63,8 @@ def process(input_directory, input_name=None, status=0, client_agent='manual', d
section = core.CFG.findsection('ALL').isenabled() section = core.CFG.findsection('ALL').isenabled()
if section is None: if section is None:
logger.error( logger.error(
f'Category:[{input_category}] is not defined or is not enabled. Please rename it or ensure it is enabled for the appropriate section in your autoProcessMedia.cfg and try again.') f'Category:[{input_category}] is not defined or is not enabled. Please rename it or ensure it is enabled for the appropriate section in your autoProcessMedia.cfg and try again.',
)
return ProcessResult( return ProcessResult(
message='', message='',
status_code=-1, status_code=-1,
@ -72,7 +74,8 @@ def process(input_directory, input_name=None, status=0, client_agent='manual', d
if len(section) > 1: if len(section) > 1:
logger.error( logger.error(
f'Category:[{input_category}] is not unique, {section.keys()} are using it. Please rename it or disable all other sections using the same category name in your autoProcessMedia.cfg and try again.') f'Category:[{input_category}] is not unique, {section.keys()} are using it. Please rename it or disable all other sections using the same category name in your autoProcessMedia.cfg and try again.',
)
return ProcessResult( return ProcessResult(
message='', message='',
status_code=-1, status_code=-1,

View file

@ -72,7 +72,7 @@ def rename_file(filename, newfile_path):
if os.path.isfile(newfile_path): if os.path.isfile(newfile_path):
newfile_path = os.path.splitext(newfile_path)[0] + '.NTM' + os.path.splitext(newfile_path)[1] newfile_path = os.path.splitext(newfile_path)[0] + '.NTM' + os.path.splitext(newfile_path)[1]
logger.debug( logger.debug(
'Replacing file name {old} with download name {new}'.format(old=filename, new=newfile_path), 'EXCEPTION', f'Replacing file name {filename} with download name {newfile_path}', 'EXCEPTION',
) )
try: try:
os.rename(filename, newfile_path) os.rename(filename, newfile_path)
@ -88,7 +88,7 @@ def replace_filename(filename, dirname, name):
elif media_pattern.search(name.replace(' ', '.').lower()) is not None: elif media_pattern.search(name.replace(' ', '.').lower()) is not None:
newname = name.replace(' ', '.') newname = name.replace(' ', '.')
logger.debug( logger.debug(
'Replacing file name {old} with download name {new}'.format(old=head, new=newname), 'EXCEPTION', f'Replacing file name {head} with download name {newname}', 'EXCEPTION',
) )
else: else:
logger.warning(f'No name replacement determined for {head}', 'EXCEPTION') logger.warning(f'No name replacement determined for {head}', 'EXCEPTION')
@ -118,7 +118,7 @@ def reverse_filename(filename, dirname, name):
newname = head[::-1].title() newname = head[::-1].title()
newname = newname.replace(' ', '.') newname = newname.replace(' ', '.')
logger.debug( logger.debug(
'Reversing filename {old} to {new}'.format(old=head, new=newname), 'EXCEPTION', f'Reversing filename {head} to {newname}', 'EXCEPTION',
) )
newfile = newname + file_extension newfile = newname + file_extension
newfile_path = os.path.join(dirname, newfile) newfile_path = os.path.join(dirname, newfile)
@ -146,7 +146,7 @@ def rename_script(dirname):
if os.path.isfile(dest): if os.path.isfile(dest):
continue continue
logger.debug( logger.debug(
'Renaming file {source} to {destination}'.format(source=orig, destination=dest), 'EXCEPTION', f'Renaming file {orig} to {dest}', 'EXCEPTION',
) )
try: try:
os.rename(orig, dest) os.rename(orig, dest)

View file

@ -216,7 +216,7 @@ def backup_versioned_file(old_file, version):
break break
except Exception as error: except Exception as error:
logger.log( logger.log(
'Error while trying to back up {old} to {new} : {msg}'.format(old=old_file, new=new_file, msg=error), logger.WARNING, f'Error while trying to back up {old_file} to {new_file} : {error}', logger.WARNING,
) )
num_tries += 1 num_tries += 1
time.sleep(1) time.sleep(1)

View file

@ -124,7 +124,7 @@ def category_search(input_directory, input_name, input_category, root, categorie
tordir = True tordir = True
elif input_name and os.path.isdir(os.path.join(input_directory, sanitize_name(input_name))): elif input_name and os.path.isdir(os.path.join(input_directory, sanitize_name(input_name))):
logger.info( logger.info(
'SEARCH: Found torrent directory {} in input directory directory {}'.format(sanitize_name(input_name), input_directory), f'SEARCH: Found torrent directory {sanitize_name(input_name)} in input directory directory {input_directory}',
) )
input_directory = os.path.join(input_directory, sanitize_name(input_name)) input_directory = os.path.join(input_directory, sanitize_name(input_name))
logger.info(f'SEARCH: Setting input_directory to {input_directory}') logger.info(f'SEARCH: Setting input_directory to {input_directory}')
@ -136,7 +136,7 @@ def category_search(input_directory, input_name, input_category, root, categorie
tordir = True tordir = True
elif input_name and os.path.isfile(os.path.join(input_directory, sanitize_name(input_name))): elif input_name and os.path.isfile(os.path.join(input_directory, sanitize_name(input_name))):
logger.info( logger.info(
'SEARCH: Found torrent file {} in input directory directory {}'.format(sanitize_name(input_name), input_directory,), f'SEARCH: Found torrent file {sanitize_name(input_name)} in input directory directory {input_directory}',
) )
input_directory = os.path.join(input_directory, sanitize_name(input_name)) input_directory = os.path.join(input_directory, sanitize_name(input_name))
logger.info(f'SEARCH: Setting input_directory to {input_directory}') logger.info(f'SEARCH: Setting input_directory to {input_directory}')

View file

@ -98,7 +98,7 @@ def remove_read_only(filename):
if not file_attribute & stat.S_IWRITE: if not file_attribute & stat.S_IWRITE:
# File is read-only, so make it writeable # File is read-only, so make it writeable
logger.debug( logger.debug(
'Read only mode on file {name}. Attempting to make it writeable'.format(name=filename), f'Read only mode on file {filename}. Attempting to make it writeable',
) )
try: try:
os.chmod(filename, stat.S_IWRITE) os.chmod(filename, stat.S_IWRITE)