def switch_image_urls_to_local()

in bedrock/contentful/migrations/0007_data_switch_to_local_images.py [0:0]


def switch_image_urls_to_local(apps, schema_editor):
    ContentfulEntry = apps.get_model("contentful", "ContentfulEntry")

    resource_center_pages = ContentfulEntry.objects.filter(
        content_type=CONTENT_TYPE_PAGE_RESOURCE_CENTER,
    )
    for page in resource_center_pages:
        # Some safety checks. If these fail, the migration breaks and it gets rolled back

        if page.slug != "unknown":
            _print(f"Checking page {page.contentful_id} {page.slug} [{page.locale}]")
        # First the "SEO" images, which are also used on the listing page
        assert "info" in page.data

        if "seo" in page.data["info"] and "image" in page.data["info"]["seo"]:
            _print(f"Updating SEO image URL for {page.contentful_id}. Slug: {page.slug}")

            image_url = page.data["info"]["seo"]["image"]
            updated_image_url = f"/media/img/products/vpn/resource-center/{_url_to_local_filename(image_url)}"
            page.data["info"]["seo"]["image"] = updated_image_url

            _print("Saving SEO info changes\n")
            page.save()

        # Now check for images in the body of the page
        assert len(page.data["entries"]) == 1
        assert "body" in page.data["entries"][0]

        body = page.data["entries"][0]["body"]
        old_to_new = defaultdict(str)
        matches = re.findall(contentful_cdn_images_pattern, body)

        if matches:
            _print(f"Found {len(matches)} URLs to update")
            for link in matches:
                old_to_new[link] = f'"/media/img/products/vpn/resource-center/{_url_to_local_filename(link[1:-1])}"'

            for old, new in old_to_new.items():
                body = body.replace(old, new)

            page.data["entries"][0]["body"] = body
            _print("Saving page changes\n")
            page.save()
        else:
            if page.slug != "unknown":
                _print("No changes needed to page body\n")