|
| 1 | +import os |
| 2 | +import logging |
| 3 | + |
| 4 | +from django.core.management.base import BaseCommand |
| 5 | + |
| 6 | +from website.models import Artifact, Talk, Poster, Publication |
| 7 | + |
| 8 | +# This retrieves a Python logging instance (or creates it) |
| 9 | +_logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +# Map a file extension to the magic-byte signature we expect its content to |
| 13 | +# start with. Used to disambiguate orphaned files that the bug renamed WITHOUT |
| 14 | +# extensions (so we can't tell pdf from pptx from the name alone). Returns None |
| 15 | +# for extensions we can't verify, in which case we refuse to guess. |
| 16 | +def _expected_kind_for_ext(ext): |
| 17 | + ext = ext.lower() |
| 18 | + if ext == ".pdf": |
| 19 | + return "pdf" |
| 20 | + if ext in (".pptx", ".docx", ".key", ".zip"): |
| 21 | + return "zip" # modern Office / Keynote / zip-based formats |
| 22 | + if ext in (".ppt", ".doc"): |
| 23 | + return "ole" # legacy OLE compound formats |
| 24 | + return None |
| 25 | + |
| 26 | + |
| 27 | +def _sniff_kind(path): |
| 28 | + """Best-effort content type of a file from its leading magic bytes.""" |
| 29 | + try: |
| 30 | + with open(path, "rb") as fh: |
| 31 | + head = fh.read(8) |
| 32 | + except OSError: |
| 33 | + return None |
| 34 | + if head.startswith(b"%PDF"): |
| 35 | + return "pdf" |
| 36 | + if head.startswith(b"PK\x03\x04"): |
| 37 | + return "zip" |
| 38 | + if head.startswith(b"\xff\xd8\xff"): |
| 39 | + return "jpeg" |
| 40 | + if head.startswith(b"\xd0\xcf\x11\xe0"): |
| 41 | + return "ole" |
| 42 | + return None |
| 43 | + |
| 44 | + |
| 45 | +class Command(BaseCommand): |
| 46 | + help = ( |
| 47 | + "Repairs artifacts whose pdf_file/raw_file row points at a file that no " |
| 48 | + "longer exists on disk because a rename moved it but the save() never " |
| 49 | + "committed (the #1390 dotted-name bug: a name like '...Dr.SangMook2009' " |
| 50 | + "made os.path.splitext eat the extension, the file was renamed " |
| 51 | + "extension-less on disk, and thumbnail generation then raised before " |
| 52 | + "super().save()). The file CONTENT is safe on disk under the malformed " |
| 53 | + "name; this finds that orphan (by matching the standardized base and " |
| 54 | + "confirming its content type, since the orphan has no usable " |
| 55 | + "extension), renames it to the correct standardized name, and repoints " |
| 56 | + "the DB. Divergence-gated and idempotent: a row whose files already " |
| 57 | + "exist on disk is skipped, so this is a safe no-op once repaired. Run " |
| 58 | + "with --dry-run first to review exactly what it would touch." |
| 59 | + ) |
| 60 | + |
| 61 | + MODELS = (Talk, Poster, Publication) |
| 62 | + |
| 63 | + def add_arguments(self, parser): |
| 64 | + parser.add_argument( |
| 65 | + "--dry-run", |
| 66 | + action="store_true", |
| 67 | + help="Report what would be repaired without touching disk or DB.", |
| 68 | + ) |
| 69 | + |
| 70 | + def handle(self, *args, **options): |
| 71 | + dry_run = options["dry_run"] |
| 72 | + _logger.info( |
| 73 | + f"Running repair_diverged_artifact_filenames (dry_run={dry_run})." |
| 74 | + ) |
| 75 | + |
| 76 | + repaired = unrecoverable = 0 |
| 77 | + for model in self.MODELS: |
| 78 | + for artifact in model.objects.prefetch_related("authors").all(): |
| 79 | + result = self._repair_artifact(artifact, dry_run) |
| 80 | + repaired += result["repaired"] |
| 81 | + unrecoverable += result["unrecoverable"] |
| 82 | + |
| 83 | + verb = "Would repair" if dry_run else "Repaired" |
| 84 | + _logger.info( |
| 85 | + f"repair_diverged_artifact_filenames: {verb} {repaired} file(s); " |
| 86 | + f"{unrecoverable} diverged file(s) could not be matched to an " |
| 87 | + f"orphan on disk and were left untouched." |
| 88 | + ) |
| 89 | + |
| 90 | + def _repair_artifact(self, artifact, dry_run): |
| 91 | + model_name = type(artifact).__name__ |
| 92 | + repaired = unrecoverable = 0 |
| 93 | + fixed_any = False |
| 94 | + |
| 95 | + for field_name in ("pdf_file", "raw_file"): |
| 96 | + file_field = getattr(artifact, field_name) |
| 97 | + if not file_field: |
| 98 | + continue |
| 99 | + # Only act on a true divergence: the DB names a file that is gone. |
| 100 | + if file_field.storage.exists(file_field.name): |
| 101 | + continue |
| 102 | + |
| 103 | + outcome = self._repair_field(artifact, field_name, dry_run) |
| 104 | + if outcome == "repaired": |
| 105 | + repaired += 1 |
| 106 | + fixed_any = True |
| 107 | + elif outcome == "unrecoverable": |
| 108 | + unrecoverable += 1 |
| 109 | + _logger.warning( |
| 110 | + f"{model_name} id={artifact.pk}: {field_name} points at " |
| 111 | + f"missing '{file_field.name}' and no matching orphan was " |
| 112 | + f"found on disk; left untouched for manual review." |
| 113 | + ) |
| 114 | + |
| 115 | + # If we repointed any files for real, persist + regenerate the thumbnail |
| 116 | + # via a normal save(). With the extension bug fixed the names are already |
| 117 | + # standardized, so save() does no further renaming; it just writes the |
| 118 | + # corrected field names and rebuilds the (now-missing) thumbnail. |
| 119 | + if fixed_any and not dry_run: |
| 120 | + artifact.save() |
| 121 | + |
| 122 | + return {"repaired": repaired, "unrecoverable": unrecoverable} |
| 123 | + |
| 124 | + def _repair_field(self, artifact, field_name, dry_run): |
| 125 | + """Locate the orphaned file for one diverged field and fix it. |
| 126 | +
|
| 127 | + Returns "repaired", "unrecoverable", or "noop". |
| 128 | + """ |
| 129 | + model_name = type(artifact).__name__ |
| 130 | + file_field = getattr(artifact, field_name) |
| 131 | + |
| 132 | + # The extension is still correct in the (stale) DB name; the standardized |
| 133 | + # base comes from generate_filename. Together they form the correct name. |
| 134 | + ext = os.path.splitext(file_field.name)[1] |
| 135 | + correct_base = Artifact.generate_filename(artifact) |
| 136 | + # get_valid_filename is applied by the rename path; mirror it so our |
| 137 | + # on-disk comparisons match what the buggy rename actually wrote. |
| 138 | + from django.utils.text import get_valid_filename |
| 139 | + valid_base = get_valid_filename(correct_base) |
| 140 | + correct_basename = get_valid_filename(correct_base + ext) |
| 141 | + |
| 142 | + directory = os.path.dirname(file_field.path) |
| 143 | + rel_dir = os.path.dirname(file_field.name) |
| 144 | + if not os.path.isdir(directory): |
| 145 | + return "unrecoverable" |
| 146 | + |
| 147 | + expected_kind = _expected_kind_for_ext(ext) |
| 148 | + |
| 149 | + # Candidate orphans: the bug wrote the file as the (extension-less) valid |
| 150 | + # base, possibly with a "-<timestamp>" uniqueness suffix from colliding |
| 151 | + # with the sibling files. Match those, then confirm by content type so we |
| 152 | + # never mis-pair a pdf with a pptx/thumbnail (they share the base name). |
| 153 | + candidates = [] |
| 154 | + for entry in os.listdir(directory): |
| 155 | + if entry == valid_base or entry.startswith(valid_base + "-"): |
| 156 | + full = os.path.join(directory, entry) |
| 157 | + if os.path.isfile(full): |
| 158 | + candidates.append(entry) |
| 159 | + |
| 160 | + matches = [ |
| 161 | + c for c in candidates |
| 162 | + if expected_kind is not None |
| 163 | + and _sniff_kind(os.path.join(directory, c)) == expected_kind |
| 164 | + ] |
| 165 | + |
| 166 | + if len(matches) != 1: |
| 167 | + _logger.debug( |
| 168 | + f"{model_name} id={artifact.pk}: {field_name} expected kind=" |
| 169 | + f"{expected_kind}; candidates={candidates}; content-matches=" |
| 170 | + f"{matches} (need exactly 1)." |
| 171 | + ) |
| 172 | + return "unrecoverable" |
| 173 | + |
| 174 | + orphan = matches[0] |
| 175 | + target_full = os.path.join(directory, correct_basename) |
| 176 | + target_rel = os.path.join(rel_dir, correct_basename) |
| 177 | + |
| 178 | + _logger.info( |
| 179 | + f"[{'dry-run' if dry_run else 'apply'}] {model_name} " |
| 180 | + f"id={artifact.pk}: {field_name} '{file_field.name}' (missing) -> " |
| 181 | + f"on-disk orphan '{orphan}' renamed to '{correct_basename}' and " |
| 182 | + f"repointed." |
| 183 | + ) |
| 184 | + |
| 185 | + if dry_run: |
| 186 | + return "repaired" |
| 187 | + |
| 188 | + # If the target name is somehow already taken by a different file, don't |
| 189 | + # clobber it — bail out for manual review. |
| 190 | + if os.path.exists(target_full) and orphan != correct_basename: |
| 191 | + _logger.warning( |
| 192 | + f"{model_name} id={artifact.pk}: target '{correct_basename}' " |
| 193 | + f"already exists; not overwriting. Left for manual review." |
| 194 | + ) |
| 195 | + return "unrecoverable" |
| 196 | + |
| 197 | + os.rename(os.path.join(directory, orphan), target_full) |
| 198 | + # Persist the corrected name directly with update() rather than relying |
| 199 | + # on the caller's save(): save() may set update_fields=['thumbnail'] when |
| 200 | + # it rebuilds the stale thumbnail, which would drop a pdf_file/raw_file |
| 201 | + # write. update() guarantees the repointed name lands in the DB. We also |
| 202 | + # set it in memory so the caller's save() regenerates the thumbnail from |
| 203 | + # the now-correct pdf path. |
| 204 | + type(artifact).objects.filter(pk=artifact.pk).update( |
| 205 | + **{field_name: target_rel} |
| 206 | + ) |
| 207 | + file_field.name = target_rel |
| 208 | + return "repaired" |
0 commit comments