o
    iiH>                     @   s  d dl mZmZmZmZ d dlmZ d dlmZ d dl	m
Z
mZ d dlmZ d dlmZmZmZmZmZmZmZmZmZ d dlmZ d dlZd d	lmZ d dlZd d
lm Z  d dl!Z!d dl"Z"d dl#Z#d dl$Z$d dl!Z!ee dd dgZ%dZ&dZ'dZ(e"j)e'dd e"j)e(dd da*ej+ej,dd e-e.Z/dd Z0d+ddZ1dd Z2e#3 Z4dd Z5dd Z6d e7d!e8d"e7fd#d$Z9e j:d%d&gd'd(d) Z;e#j<e1dd*=  dS ),    )Flask	send_filejsonifyrequest)CORS)service_account)buildMediaFileUpload)MediaIoBaseDownload)	connect_to_databaseinsertQuerySearchCriteriainsertQuerySearchRequestsupdateProgressPercentageupdateRowStatusupdateExecTimeAndQuotaselectStatusupdateStatusupdate_filename)get_video_metadataN)	HttpError)app*)originsz%https://www.googleapis.com/auth/drivezconfigs/credentials.jsonuploadstempUploadsTexist_okz)%(asctime)s - %(levelname)s - %(message)s)levelformatc                  C   s"   t jjttd} tdd| d}|S )N)scopesdrivev3)credentials)r   Credentialsfrom_service_account_fileSERVICE_ACCOUNT_FILESCOPESr   )r"   service r(   6/var/www/edux/Edux_v2/controllers/search_controller.pyget_drive_service    s
   r*   returnc                  C   s|   	 t tD ]1} t jt| }| dr7zt| W q ty6 } ztd|  d|  W Y d}~qd}~ww qt	
d q)z*Process Excel files in the uploads folder.T.xlsxzError processing file : N
   )oslistdirUPLOAD_FOLDERpathjoinendswithget_details_from_youtube	Exceptionprinttimesleep)filename	file_pather(   r(   r)   process_files&   s   
 
r=   c                 C   s  g }|   D ]\}}t|d r|d nd }t|d r"|d nd }t|d r/|d nd }t|d r<|d nd }t|d rI|d nd }t|d rV|d nd }	t|d rc|d nd }
t|d rp|d nd	}t|d
 r}|d
 nd }t|d r|d nd }t|d r|d nd }t|d r|d nd}|dvr|d|d  d |dkr|s|d|d  d t|tr|dkr|d|d  d t|tr|dkr|d|d  d q|S )N
SearchTypeLanguageStandardSubjectTopicSubTopicFreeTextSearchMaxResultsPerPlaylists2   	ChannelIdLicenceTypeVideoDuration
MaxResultsi  )Videos	PlaylistsAllChannelVideoszInvalid SearchType at row    z7. Must be 'Videos', 'Playlists', or 'AllChannelVideos'.rM   z2ChannelId is required for AllChannelVideos at row .r   zInvalid MaxResults at row z. Must be a positive integer.z&Invalid MaxResultsPerPlaylists at row )iterrowspdnotnaappend
isinstanceint)dferrorsindexrowsearch_typelanguagestandardsubjecttopicsubtopicfreeTextSearchmax_videos_per_playlist
channel_idvideo_licensevideo_durationmax_resultsr(   r(   r)   validate_upload_file3   s0   rf   c           '      C   s  t  }t| }t|}tj }d}t| tj	| 
d}t|d }t||d ttds4dt_zzg }| D ]\}	}
t||}td| |dkr7t|
d r]|
d nd }t|
d	 rj|
d	 nd }t|
d
 rw|
d
 nd }t|
d r|
d nd }t|
d r|
d nd }t|
d r|
d nd }t|
d r|
d nd }t|
d r|
d nd }t|
d r|
d nd }t|
d r|
d nd }t|
d r|
d nd }t|
d r|
d nd }t|
d r|
d nd }d}t|r|}nPt|r||d 7 }t|r||d 7 }t|r0|dtt| d 7 }t|r<||d 7 }t|rH||d 7 }t|rR||7 }| }td| d t|||||||||||||d|}td zt|||||||\}}td t|d| W n{ ty } ztd|  t|d| W Y d }~q>d }~w ty } z)td|  |jjd krd!t|v rt|d"| nt|d| W Y d }~q>d }~w ty } ztd#|	d$  d%|  t|d| W Y d }~q>d }~ww |	d$ | d& }t| td'| t ||| t j|7  _td(| d)tj  |!| q>|sEt"d* t# } ntj$|d+d,} t|%dd%d-d.d d/ d0 }!d1}"tj&|"|!}#tj'|"d+d2 | j(|#d3d4 t)||#| tj }$t*|$| j+d5}%td6|%d d7|%d$ d8 t|%d d9 t|%d$  d: }&|dkrt,||&tjd| |dkrt,||&tjd| W n[ ty } z(td|  |jjd krd!t|v rtd; t||d" t|d|  d }~w ty } ztd<|  t||d t|d| W Y d }~nd }~ww W tj-| r,t.|  d S td=|  d S tj-| rAt.|  w td=|  w )>N _r   zIn-Progresstotal_quota_used
stopstatusStoppedr>   Boardr?   r@   rA   rB   rC   rD   rE   rG   rH   rI   rJ    zClass zBuilt search_criteria: ''StartedzRequest startingzResponse data received	CompletedzValueError: FailedzHttpError: i  quotaExceededzQuota Exhaustedz Unexpected error processing row rN   r-   d   z	searchId:zQuota used for this request: z. Total quota used: z7No videos passed filtering - creating empty result fileT)ignore_index:-   r,   responseFolderr   F)rX   <   zTotal difference in minutes: minssecz mins z seczQuota exceededzUnexpected error: z$File not found, could not remove: %s)/r   rQ   
read_excellendatetimenowr7   r/   r2   basenamesplitrU   r   hasattrthread_localri   rP   r   rR   strstriploggerinfor   r   r   
ValueError	exceptionr   respstatusr6   r   rS   warning	DataFrameconcatreplacer3   makedirsto_excelupload_filedivmodsecondsr   existsremove)'r;   
connectionrV   total_records	timestamp
stopStatuspartssearchIdall_responsesrX   rY   rZ   boardr[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   search_criteriasearchRowIdresponse_df	quotaUsedveher<   completePercentfinal_dfresponse_file	directoryfile_path_resultend_timeminutes
differencer(   r(   r)   r5   X   s   





$



$
 


r5   c                 C   sB   d| d}|   j|dd }|dg }|sd S |d d S )Nzname='zE' and mimeType='application/vnd.google-apps.folder' and trashed=falsezfiles(id, name))qfieldsfilesr   id)r   listexecuteget)r'   folder_namequeryresultsitemsr(   r(   r)   get_folder_id   s   r   r   filePathr   c              
   C   s  t d t d|  t d| t }| s$t d t| t|d| dS |s8t d t|d| t|| d dS zt }t|d}|s[t d	 t| t|d| t|| d W dS t d
| tj	||gd}t | t
|dd}| j||dd }|d}	|d}
t d|	 |	r|
st d t| t|| d t|d| W dS t d | }d}|||	|
| f |  |  |  t| W dS  ty } zt|d| t|| d t| t d| W Y d}~dS d}~ww )zXUpload the excel file to Google Drive and update the file ID and name in MySQL database.zUploading file to Google driverowidr   zError: Row ID is requiredrq   NzError: FilePath is requiredRKSSzError: Folder not foundfolder)nameparentszAapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet)mimetypezid, name)body
media_bodyr   r   r   fileIdz,Error: Failed to upload file to Google DrivezFile Uploaded successfullyzUUPDATE search_requests SET OutputFileId = %s, OutputFileName = %s WHERE SearchID = %szError Processing the file)r7   r   r/   r   r   r   r*   r   r2   r   r	   r   creater   r   cursorcommitcloser6   )r   r   r   r   r'   	folder_idfile_metadatamediauploaded_filefile_id	file_namer   update_queryr<   r(   r(   r)   r      st   










r   z/process_excelPOST)methodsc            
   
   C   s  t  } dtjvrtddidfS tjd }|jdkr"tddidfS tjda|r|jdrt	j	
 }t| |jd	t|t}|d u rLtdd
idfS | d|j }tjt|}|| zt|}W n ty } zt| tddidfW  Y d }~S d }~ww tdtt| t|d	krt| tddiS t|}|rt| td|ddfS t| || tjt|}	t||	 td|jddfS tddidfS )NfileerrorzNo file foundi  rg   zNo file is selectedusernamer,   r   z-Failed to insert search request into databasei  rh   zFile template is not supportedLengthzEmpty file uploadedzFile validation failed)r   detailszFile uploaded successfully)messager      z<Unsupported file format. Please upload an Excel file (.xlsx))r   r   r   r   r:   formr   USERNAMEr4   r~   r   r   r   r/   r2   r3   TEMP_FOLDERsaverQ   r|   r6   r   r7   r}   rf   r   r1   rename)
r   r   r   r   new_filenametemp_file_pathrV   r<   rW   final_file_pathr(   r(   r)   process_excel*  sF   







r   )targetdaemon)r+   N)>flaskr   r   r   r   
flask_corsr   google.oauth2r   googleapiclient.discoveryr   r	   googleapiclient.httpr
   configs.databaseConnectionr   r   r   r   r   r   r   r   r   service.VideoCallr   logginggoogleapiclient.errorsr   pandasrQ   	flask_appr   r~   r/   	threadingr8   r&   r%   r1   r   r   r   basicConfigINFO	getLogger__name__r   r*   r=   rf   localr   r5   r   rU   r   r   router   Threadstartr(   r(   r(   r)   <module>   sJ    ,

# >
0