Skip to content

Instantly share code, notes, and snippets.

@proteusvacuum
Last active November 10, 2022 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save proteusvacuum/9fdd0e45c28e9dd425df952471699859 to your computer and use it in GitHub Desktop.
Save proteusvacuum/9fdd0e45c28e9dd425df952471699859 to your computer and use it in GitHub Desktop.

FIRST PART

  1. Edit build_id below with the ID of an app build that is giving you the image error
  2. It will print out a list of files that it couldn't find
  3. Find a copy of all of these files and put them in a single folder in an accessible place (e.g. /home/cchq/images). You can just copy all the images from the /commcare/image/data/ folder from an old zip of the same version.
from corehq.apps.app_manager.models import Application
from corehq.apps.domain import SHARED_DOMAIN

from corehq.apps.hqmedia.models import CommCareImage
from couchdbkit.exceptions import ResourceNotFound
from corehq.blobs import CODES, get_blob_db

options = {
    "build_id": "BUILD ID OF YOUR APP",
}

db = get_blob_db()

app = Application.get(options["build_id"])
multimedia_map = app.multimedia_map

missing_multimedia = {}

for path, media_map in app.multimedia_map.items():
    image = CommCareImage.get(media_map.multimedia_id)
    try:
        image.fetch_attachment(image.attachment_id)
    except ResourceNotFound as e:
        missing_multimedia[path.split('/')[-1]] = image.get_id

if missing_multimedia:
    print("Missing files: \n{}".format("\n".join(missing_multimedia.keys())))
else:
    print("All multimedia is present")

SECOND PART

  1. In the same open shell, edit the "base_path" here to point to where you saved all the images. Include the trailing /
  2. It should update all of the files correctly.
options = {
    "base_path": "/home/farid/Desktop/images/",
}

for missing_file, image_id in missing_multimedia.items():
    image = CommCareImage.get(image_id)
    filename = options["base_path"] + missing_file

    with open(filename, "rb") as f:
        image_data = f.read()

    image.put_attachment(
        image_data,
        image.attachment_id,
        content_type=image.get_mime_type(image_data, filename=missing_file),
        domain=SHARED_DOMAIN,
    )

    print(f"Successfully updated image {missing_file}")

Run the "FIRST PART", above. It should tell you all multimedia is present.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment