"""Thumbnails Logic.""" from typing import Any import boto3 from video.constants.thumbnails import ( DEFAULT_IMAGE_SIZE, THUMBNAILS_BUCKET, THUMBNAILS_CDN_URL, THUMBNAILS_PATH, UPLOAD_CUSTOM_THUMBNAIL, ) from video.exceptions import InvalidRequest, ProductVideoNotFound from video.logic import cloudfront as cloudfront_logic from video.models.s3 import s3_token from video.models.sql.classes import product_video def get_available_thumbnails(job_id: int, image_size: str | None) -> list[str]: """Get the list of available thumbnails for a job. Args: job_id (int): ID of the job. image_size (str): The image size (small or original-size). """ image_size = image_size or DEFAULT_IMAGE_SIZE result = boto3.client("s3").list_objects_v2( Bucket=THUMBNAILS_BUCKET, Prefix=THUMBNAILS_PATH.format(image_size=image_size, job_id=job_id), ) thumbnails = [] for item in result.get("Contents", []): key = item["Key"] path = key.replace("thumbnails/", "") url = "{}/{}".format(THUMBNAILS_CDN_URL, path) thumbnails.append(url) return thumbnails def get_product_thumbnail( product_id: int, image_size: str | None, expire_at: int | None ) -> str: """Get the thumbnail associated with a product. Args: product_id (int): ID of the product. image_size (str): The image size. expire_at (int): Timestamp in seconds when the url becomes invalid. Raises: ProductVideoNotFound: If no product data is found. """ image_size = image_size or DEFAULT_IMAGE_SIZE product_data = product_video.get(product_id) if not product_data: raise ProductVideoNotFound() thumbnail_path = product_data.get("thumbnail_path") thumbnail_url = "{}/{}/{}".format(THUMBNAILS_CDN_URL, image_size, thumbnail_path) signed_thumbnail_url = cloudfront_logic.get_signed_url( thumbnail_url, expire_at=expire_at ) return signed_thumbnail_url def generate_upload_token_for_custom_thumbnail(data: dict[str, Any]) -> dict[str, Any]: """Generate a S3 token to upload a custom thumbnail. Args: data (dict): The data to generate the token. Returns: dict: containing the token. """ job_id: int = data["workflow_job_id"] filename: str = data["filename"] if not filename.strip(): raise InvalidRequest("filename must be a non-empty string") return s3_token.get_s3_token(job_id, UPLOAD_CUSTOM_THUMBNAIL, filename)