From 116e0c64db9d2071261678486884c7a44471737f Mon Sep 17 00:00:00 2001 From: JackDandy Date: Mon, 3 Oct 2016 19:31:54 +0100 Subject: [PATCH] Change factor out cleanup_cache() into cleanup_cache() + delete_not_changed_in() for multiple use cases. Change make it simpler to add cache paths to cleanup_cache() using a list of tuples. Change PEP8 .. cleanup_cache > cleanup_Cache. --- sickbeard/helpers.py | 39 ++++++++++++++++++++++++++++----------- sickbeard/show_updater.py | 2 +- 2 files changed, 29 insertions(+), 12 deletions(-) diff --git a/sickbeard/helpers.py b/sickbeard/helpers.py index bf6758c5..a27d3e46 100644 --- a/sickbeard/helpers.py +++ b/sickbeard/helpers.py @@ -1466,21 +1466,39 @@ def scantree(path): yield entry -def cleanup_Cache(): - """Delete cached Images older then 30 days""" - basepath = ek.ek(os.path.join, sickbeard.CACHE_DIR, 'images') - cachepaths = [ek.ek(os.path.join, basepath, 'trakt')] - del_time = time.mktime((datetime.datetime.now() - datetime.timedelta(days=30)).timetuple()) - for c in cachepaths: +def cleanup_cache(): + """ + Delete old cached files + """ + delete_not_changed_in([ek.ek(os.path.join, sickbeard.CACHE_DIR, *x) for x in [ + ('images', 'trakt')]]) + + +def delete_not_changed_in(paths, days=30, minutes=0): + """ + Delete files under paths not changed in n days and/or n minutes. + If a file was modified later than days/and or minutes, then don't delete it. + + :param paths: List of paths to scan for files to delete + :param days: Purge files not modified in this number of days (default: 30 days) + :param minutes: Purge files not modified in this number of minutes (default: 0 minutes) + :return: tuple; number of files that qualify for deletion, number of qualifying files that failed to be deleted + """ + del_time = time.mktime((datetime.datetime.now() - datetime.timedelta(days=days, minutes=minutes)).timetuple()) + errors = 0 + qualified = 0 + for c in paths: try: for f in scantree(c): - if f.is_file(follow_symlinks=False) and f.stat(follow_symlinks=False).st_mtime < del_time: + if f.is_file(follow_symlinks=False) and del_time > f.stat(follow_symlinks=False).st_mtime: try: ek.ek(os.remove, f.path) - except: + except (StandardError, Exception): + errors += 1 + qualified += 1 + except (StandardError, Exception): pass - except: - pass + return qualified, errors def set_file_timestamp(filename, min_age=3, new_time=None): @@ -1490,4 +1508,3 @@ def set_file_timestamp(filename, min_age=3, new_time=None): ek.ek(os.utime, filename, new_time) except (StandardError, Exception): pass - diff --git a/sickbeard/show_updater.py b/sickbeard/show_updater.py index dd854e74..cb913e7e 100644 --- a/sickbeard/show_updater.py +++ b/sickbeard/show_updater.py @@ -60,7 +60,7 @@ class ShowUpdater: sickbeard.helpers.clear_unused_providers() # cleanup image cache - sickbeard.helpers.cleanup_Cache() + sickbeard.helpers.cleanup_cache() # add missing mapped ids if not sickbeard.background_mapping_task.is_alive():