o
    gZ/                  	   @   sF  d Z ddlZddlZddlZddlZddlmZ ddlmZ ddlm	Z	m
Z
 ddlZddlZddlZddlZddlZddlmZ ddlmZmZmZmZmZ ddlmZmZmZmZmZ dd	lmZ dd
l m!Z! ddl"m#Z# ddl$m%Z% ddl&m'Z' ddl(m)Z) eddgdddiig dZ*e*+dde,fddZ-e*+dde,fddZ.e*/dedededfde,d e
e, d!e
e0 fd"d#Z1e*+d$	dAde,fd%d&Z2e*+d'd(e,fd)d*Z3e*+d+d,e,fd-d.Z4e*+d/d0d1 Z5e*+d2de,fd3d4Z6e*+d5dAde,fd6d7Z7e*j8d8d9d:gd;edd<d=fd>e,fd?d@Z9dS )Bz%Fast API module for general utilities    N)datetime)BytesIO)IOOptional)ClientError)	APIRouterBodyHTTPExceptionQuery
UploadFile)FileResponseJSONResponseRedirectResponseResponseStreamingResponse)get_brand_from_url)PublicComparables)validate_url)fetch_brand_details)get_google_fonts_list)S3BucketStoragez
/utilities	utilities  descriptionz	Not found)prefixtags	responsesdependenciesz/validate_urlurlc                 C   s"   t  | }|rddiS tddd)zValidate the input urlmessagezURL is validr   zURL is not validstatus_codedetail)r   r	   )r   validate_response r$   1/var/www/html/XCapMarket/controllers/utilities.pyvalidate)   s   
r&   z/validate/tickertickerc                 C   s    t  | }|stdddS dS )zValidate the input tickerr   zTicker is not validr       )r   get_ticker_datar	   )r'   ticker_datar$   r$   r%   validate_ticker3   s   r+   z/upload_file/.s3_file_pathsource_file_paths3_filec           	   
      s   z&t jd }|dd}t|d}|j| ||d}|r%tdd|idW S W dS  tyP } z|jd	 d
 dkrBtdd| d|tdd| d|d}~w t	yg } ztddd| id|d}~w ty~ } ztddd| id|d}~ww )a  
    Uploads a file to the specified location in the S3 bucket and returns a JSON response indicating the result.

    Args:
        s3_file_path (str): The path to upload the file to in the S3 bucket.
        source_file_path (str): The path of the file to upload from the local system.

    Returns:
        JSONResponse: A JSON response indicating the success or failure of the upload operation.
    xcap_s3_storager.    bucket_name)r,   r-   r.   r(   r   r!   contentErrorCode	NoSuchKey  Exception occurred: r    Error: N  )
osenvirongetr   upload_file_to_s3_bucketr   r   responser	   
ValueError)	r,   r-   r.   r/   s3_storage_objresulteveher$   r$   r%   r?   =   s:   


r?   z
/get_file/c              
      s   z&t jd }t|d}|j| d}t|d}|r%tdd|idW S W dS  tyP } z|j	d d	 d
krBt
dd| d|t
dd| d|d}~w tyg } zt
ddd| id|d}~ww )a3  
    Retrieves a file from the specified location in the S3 bucket and returns its content as base64 encoded JSON.

    Args:
        s3_file_path (str): The path of the file to retrieve from the S3 bucket.

    Returns:
        JSONResponse: A JSON response containing the base64 encoded file content.
    r/   r1   )r,   zutf-8r(   r   r3   r5   r6   r7   r;   r9   r    r:   N)r<   r=   r   get_file_from_s3_bucketbase64	b64encodedecoder   r   r@   r	   rA   )r,   r/   rB   file_contentrD   rE   r$   r$   r%   rG   v   s,   


rG   z/search_files/keywordc              
      s   zt jd }t|d}|j| d}tdd|idW S  tyC } z|jd d d	kr5td
d| d|td
d| d|d}~w tyZ } ztd
dd| id|d}~ww )a  
    Search for files containing the specified keyword in the S3 bucket and return a JSON response.

    Args:
        keyword (str): The keyword to search for in file names.

    Returns:
        JSONResponse: A JSON response containing the list of matching file paths.
    r/   r1   )rL   r(   matching_filesr3   r5   r6   r7   r;   r9   r    r:   Nr   )	r<   r=   r   search_files_in_bucketr   r   r@   r	   rA   )rL   r/   rB   rM   rD   rE   r$   r$   r%   search_files_in_s3_bucket   s&   


rO   zscheduled_task_status/{task_id}task_idc                    s<   ddl m} || }| r| |j|jdS | |jdS )z,Check the status of the research slide task.r   )celery)rP   statusrC   )rP   rR   )tasks.celery_workerrQ   AsyncResultreadyrR   rC   )rP   rQ   taskr$   r$   r%   research_slide_status   s   
rW   z/fonts/googlec                     s   t  I dH } td| dS )z
    Retrieves a list of all available Google Font families.
    Caches the response for 7 days to minimize API calls.

    Returns:
        JSONResponse: A JSON response containing just the font family names.
    Nr(   r3   )r   r   )
fonts_datar$   r$   r%   get_google_fonts   s   	rY   z/fetch_brandc                    s    t | I dH }tdd|idS )z
    Fetch brand details for a given URL using the Brandfetch API.

    Args:
        url (str): The URL of the company to fetch brand details for.

    Returns:
        JSONResponse: The brand details retrieved from the Brandfetch API.
    Nr(   datar3   )r   r   )r   rZ   r$   r$   r%   fetch_brand   s   r[   z/fetch-and-previewc              
      s   | s	t dddzTt 4 I d H 7}|| 4 I d H }|  t| I d H }W d   I d H  n1 I d H s:w   Y  W d   I d H  n1 I d H sOw   Y  t|dddidW S  tjyx } zt	t
|dd	W  Y d }~S d }~ww )
Nr;   zURL is requiredr    application/pdfContent-Dispositionzinline; filename=invoice.pdf)
media_typeheadersr8   )r4   r!   )r	   aiohttpClientSessionr>   raise_for_statusr   readr   r   r   str)r   sessionr@   pdf_contentrD   r$   r$   r%   download_pdf   s&   *(rg   z
/sign_blobGETHEAD)methodszUnsigned URL or S3 object key)r   unsigned_urlc           
   
      sL  zzt jd }ddlm} | dr|| }|jd}| dr,|| }|jd}n| }|s6tddd	t|d
}|	|\}}|du rNt
d|idW S |r[|dr[t|dW S |rk|drkt|ddidW S t|dd|dd  idW S  ty } z	tdt|d	|d}~w ty }	 z
tdd|	 d	|	d}	~	ww )a6  
    Generates a signed URL for an S3 object from an unsigned URL or S3 file key,
    and returns a response based on the file type.

    For image files (e.g. .jpg, .png, etc.) the function will return a redirect
    to the signed URL so that it can be used directly in an <img src="..."> tag.
    For other file types, it returns the signed URL inside a JSON response.

    Query Parameters:
        unsigned_url (str): The unsigned URL or S3 object key.

    Returns:
        Either a RedirectResponse (for image files) or a JSONResponse with the signed URL.
    r/   r   )urlparsehttp/zs3://r;   zInvalid unsigned URL provided.r    r1   N
signed_url)r4   zimage/)r   r\   r]   zinline; filename=document.pdf)r   r_   zinline; filename=document.r8   zUnexpected error: )r<   r=   urllib.parserl   
startswithpathlstripr	   r   generate_signed_urlr   r   splitrA   rd   	Exception)
rk   r/   rl   parseds3_key
s3_storagero   	mime_typerD   exr$   r$   r%   generate_signed_url_blob  sL   



r}   )N):__doc__rH   jsonloggingr<   r   ior   typingr   r   r`   backoffboto3redisrequestsbotocore.exceptionsr   fastapir   r   r	   r
   r   fastapi.responsesr   r   r   r   r   (services.company_profile.logo_standaloner   %services.stock_info.public_comparabler   utilsr   utils.brand.brand_fetchr   utils.google_fonts_servicer   utils.s3_storager   r   r>   rd   r&   r+   postdictr?   rG   rO   rW   rY   r[   rg   	api_router}   r$   r$   r$   r%   <module>   s    
		8-)

