"""Functions for managing error correction assets.""" from oto import response from assets import config from assets.models import image_location from assets.models import s3_file def rename_image_assets(product_id): """Rename image correction assets to overwrite the original assets. This assumes that the error correction image has been approved and thus its derivative assets should overwrite those for the original image. Args: product_id (int): id of the product that the image belongs to. Returns: Response: success or failure """ def get_image_path(image_format): return image_location.get_backend_image_filename( product_id, 'product', image_format).message cover_result = s3_file.rename_s3_file( config.ASSET_STORAGE_BUCKET_NAME, get_image_path('cover_correction'), get_image_path('cover')) large_cover_result = s3_file.rename_s3_file( config.ASSET_STORAGE_BUCKET_NAME, get_image_path('large_cover_correction'), get_image_path('large_cover')) if cover_result.status == 500 or large_cover_result.status == 500: return response.create_fatal_response( message=_embed_image_errors(cover_result, large_cover_result)) if cover_result.status == 404 or large_cover_result.status == 404: return response.create_not_found_response( message=_embed_image_errors(cover_result, large_cover_result)) return response.Response() def _embed_image_errors(cover_result, large_cover_result): """Embed errors from failed image responses into a single payload.""" payload = {} if not cover_result: payload['cover'] = cover_result.errors if not large_cover_result: payload['large_cover'] = large_cover_result.errors return payload