From feae86528cba80ae9f0bcb189451ee3fb02d88be Mon Sep 17 00:00:00 2001 From: Étienne Loks Date: Fri, 19 Feb 2021 11:40:03 +0100 Subject: media_find_missing_files: try first to fix bad links --- .../management/commands/media_find_missing_files.py | 12 +++++++++++- ishtar_common/utils.py | 16 +++++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) (limited to 'ishtar_common') diff --git a/ishtar_common/management/commands/media_find_missing_files.py b/ishtar_common/management/commands/media_find_missing_files.py index 73f4e0ccf..13159bfa7 100644 --- a/ishtar_common/management/commands/media_find_missing_files.py +++ b/ishtar_common/management/commands/media_find_missing_files.py @@ -20,8 +20,9 @@ import os.path import sys -from ishtar_common.utils import get_used_media, try_fix_file +from ishtar_common.utils import get_used_media, try_fix_file, get_broken_links +from django.conf import settings from django.core.management.base import BaseCommand @@ -67,6 +68,15 @@ class Command(BaseCommand): self.stdout.write("hard option has no effect if try-fix or " "find-fix are not set.\n") + if try_fix: + # first try to fix broken links + out = None + for l in get_broken_links(settings.MEDIA_ROOT): + if not out: + self.stdout.write("* fixes broken links:\n") + out = True + try_fix_file(l, hard=hard) + missing = [] for media in get_used_media(exclude=exclude, limit=limit): if not os.path.isfile(media): diff --git a/ishtar_common/utils.py b/ishtar_common/utils.py index a3bc23e21..b4542688b 100644 --- a/ishtar_common/utils.py +++ b/ishtar_common/utils.py @@ -1499,6 +1499,20 @@ MEDIA_RE = [ ] +def get_broken_links(path): + for root, dirs, files in os.walk(path): + for filename in files: + path = os.path.join(root, filename) + if os.path.islink(path): + target_path = os.readlink(path) + # resolve relative symlinks + if not os.path.isabs(target_path): + target_path = os.path.join(os.path.dirname(path), + target_path) + if not os.path.exists(target_path): + yield path + + def simplify_name(full_path_name, check_existing=False, min_len=15): """ Simplify a file name by removing auto save suffixes @@ -1766,7 +1780,7 @@ def try_fix_file(filename, make_copy=True, hard=False): for path, __, files in os.walk(settings.MEDIA_ROOT): for f in files: result = _try_copy(path, f, filename, simplified_ref_name, - make_copy, min_len=15) # 15 - less agressive + make_copy, min_len=10) if result: return result -- cgit v1.2.3