
    si-.                         d dl Z d dl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 d dlmZ d	gZ ej"                  e      Zd
 ZddZd Zd Zd ZddZd Zd Zd Zd Zy)    N)service_account)Credentials)Flow)Request)build)MediaFileUpload)	HttpErrorz*https://www.googleapis.com/auth/drive.filec                 P    t         j                  j                  | t              }|S )z:Authenticate using service account (for Google Workspace).scopes)r   r   from_service_account_fileSCOPES)service_account_filecredss     9/var/www/python-projects/worksol/horilla_backup/gdrive.pyauthenticater      s*    ''AAV B E L    c                 |    |r0t        d|d| |t              }|j                  t                      |S t	        d      )zBAuthenticate using OAuth 2.0 (for personal and business accounts).N#https://oauth2.googleapis.com/token)tokenrefresh_token	token_uri	client_idclient_secretr   z<No refresh token provided. Please complete OAuth flow first.)r   r   refreshr   
ValueError)r   r   r   r   s       r   authenticate_oauthr      sB    ';'
 	gi WXXr   c           	      \    t        j                  d| |dd|gdit              }||_        |S )z-Create OAuth flow for initial authentication.webz)https://accounts.google.com/o/oauth2/authr   )r   r   auth_urir   redirect_urisr   )r   from_client_configr   redirect_uri)r   r   r#   flows       r   create_oauth_flowr%   .   sD    ""&!.GB".	
 D %DKr   c                 6    | j                  dd      \  }}||fS )z)Get the authorization URL for OAuth flow.offlinetrue)access_typeinclude_granted_scopes)authorization_url)r$   r+   states      r   get_oauth_authorization_urlr-   @   s0    #55%  6  u e##r   c                     | j                  |       | j                  }|j                  |j                  |j                  r|j                  j                         dS ddS )z'Exchange authorization code for tokens.)codeN)access_tokenr   
expires_in)fetch_tokencredentialsr   r   expiry	timestamp)r$   r/   r3   s      r   exchange_oauth_coder6   I   sg    $""K $))$228C8J8Jk((224  QU r   c                    	 |dk(  r*|j                  d      }|st        d      t        |      }nm|dk(  rZ|j                  d      }|j                  d      }|j                  d      }t        |||g      st        d      t	        |||      }nt        d	|       t        d
d|      }	t        j                  j                  |       |gd}
t        | d      }|	j                         j                  |
|d      j                         }t        j                  d|  d|j                  d       d|        |j                  d      S # t        $ r}|j                   r|j                   d   ni }|j                  dd      }|dk(  r(|dk(  r#t        j#                  d|        t%        d      t        j#                  d|        t%        d|       d}~wt$        $ r+}t        j#                  d|        t%        d|       d}~ww xY w) a  
    Upload file to Google Drive using either service account or OAuth authentication.
    
    Args:
        file_path (str): Path to the file to upload
        parent_folder_id (str): Google Drive folder ID where file will be uploaded
        auth_method (str): Either 'service_account' or 'oauth'
        **auth_params: Authentication parameters based on method:
            - For service_account: service_account_file
            - For oauth: client_id, client_secret, refresh_token
    r   r   zCservice_account_file is required for service account authenticationoauthr   r   r   zQclient_id, client_secret, and refresh_token are required for OAuth authenticationzInvalid auth_method: drivev3r3   )nameparentsT)	resumableid)body
media_bodyfieldszSuccessfully uploaded z to Google Drive with ID: z using r   reasonunknownstorageQuotaExceededzeGoogle Drive upload failed: Service accounts cannot upload to personal Google Drive accounts. Error: zwService accounts cannot upload to personal Google Drive accounts. Switch to OAuth authentication for personal accounts.z+Google Drive upload failed with HttpError: zGoogle Drive API error: Nz-Unexpected error during Google Drive upload: zUpload failed: )getr   r   allr   r   ospathbasenamer   filescreateexecuteloggerinfor	   error_detailserror	Exception)	file_pathparent_folder_idauth_methodauth_paramsr   r   r   r   r   servicefile_metadatamediafileerP   error_reasons                   r   upload_filer]   U   s#   ./++#.??3I#J ' !fgg !56EG##4I'OOO<M'OOO<M	=-@A !tuu&y-OE4[MBCC59!#!1!1)!<JZI[\	T:MMOV5VFWY 	 	,YK7QRVRZRZ[_R`Qaahithuvwxx~ 
<./oo*2$((9=11kEV6VLL  A  BC  AD  E  F R S S LLFqcJK6qc:;; /DQCHI/!-../s%   EE
 
	HBGH!&HHc                      t        | |d|      S )z2Legacy upload function for backward compatibility.r   )r   )r]   )rS   r   rT   s      r   upload_file_legacyr_      s    y"24E\pqqr   c                    	 t        |       }t        dd|      }|j                         j                  |d      j	                         }|j                  dd      }|j                  d      r
d	d
| dd	dS dd| dddS # t
        $ r[}|j                  j                  dk(  rddddcY d}~S |j                  j                  dk(  rddddcY d}~S dd| ddcY d}~S d}~wt        $ r}dd| ddcY d}~S d}~ww xY w)a%  
    Validate Google Drive access for service accounts.
    
    Args:
        service_account_file (str): Path to service account JSON file
        folder_id (str): Google Drive folder ID
        
    Returns:
        dict: Validation result with success status, message, and folder info
    r9   r:   r;   zid,name,parents,driveIdfileIdrB   r<   UnknowndriveIdTzValid Shared Drive folder: "")successmessageis_shared_driveFzERROR: "z" is in a personal Google Drive account. Service accounts cannot upload to personal Google Drive folders. You need a Google Workspace account with Shared Drives, or use OAuth authentication instead of a service account.  z?Folder not found or service account does not have access to it.N  zRAccess denied. If using personal Google Drive, service accounts are not supported.zError validating folder: zUnexpected error: )	r   r   rK   rF   rM   r	   respstatusrR   )r   	folder_idr   rW   folder_infofolder_namer[   s          r   validate_shared_drive_accessrp      sC   1
1259 mmo))C\)]eeg!oofi8 ??9%9+aH#'  !%k] 3U V $)   66==C \#' 
 VV]]c! o#'  !6qc:#' 
  
+A3/#
 	

sN   A4B 7	B 	C?
C (C?.C C?C C? C?,C:4C?:C?c                    	 |sddddS t        | ||      }t        dd|      }|j                         j                  |d      j	                         }|j                  d	d
      }dd| dddS # t
        $ r[}|j                  j                  dk(  rddddcY d}~S |j                  j                  dk(  rddddcY d}~S dd| ddcY d}~S d}~wt        $ r+}t        j                  d|        dd| ddcY d}~S d}~ww xY w)ak  
    Validate Google Drive folder access using OAuth authentication.
    
    Args:
        client_id (str): OAuth client ID
        client_secret (str): OAuth client secret  
        refresh_token (str): OAuth refresh token
        folder_id (str): Google Drive folder ID
        
    Returns:
        dict: Validation result with success status and message
    FzDOAuth not authorized yet. Please complete OAuth authorization first.)rf   rg   folder_accessibler9   r:   r;   zid,name,parentsra   r<   rc   TzOAuth access to folder "z" verified successfully.ri   zEFolder not found. Please check the folder ID and make sure it exists.Nrj   zTAccess denied to folder. Please make sure you have permission to access this folder.zError accessing folder: zOAuth folder validation error: zValidation error: )r   r   rK   rF   rM   r	   rk   rl   rR   rN   rQ   )	r   r   r   rm   r   rW   rn   ro   r[   s	            r   validate_oauth_folder_accessrs      s@   .
 a%*  #9m]K59 mmo))CT)U]]_!oofi8 1+>VW!%
 	
  66==C b%* 
 VV]]c! q%*  !5aS9%* 
  
6qc:;+A3/!&
 	

sM   A0 A%A0 0	D9CDC;DC	DD D;DDc                    | dk(  r$|j                  d      }|sdddS t        ||      S | dk(  rJ|j                  d      }|j                  d      }|j                  d	      }|r|sdd
dS t        ||||      S dd|  dS )aF  
    Universal folder validation function that works with both auth methods.
    
    Args:
        auth_method (str): Either 'service_account' or 'oauth'
        folder_id (str): Google Drive folder ID
        **auth_params: Authentication parameters based on method
        
    Returns:
        dict: Validation result
    r   r   Fz@Service account file is required for service account validation.)rf   rg   r8   r   r   r   z;OAuth client credentials are required for OAuth validation.zUnknown authentication method: )rF   rp   rs   )rU   rm   rV   r   r   r   r   s          r   validate_folder_accessru     s     ''*/EF# ]  ,,@)LL		OOK0	#8#8 X 
 ,I}mU^__ 8F
 	
r   )N)rH   logginggoogle.oauth2r   google.oauth2.credentialsr   google_auth_oauthlib.flowr   google.auth.transport.requestsr   googleapiclient.discoveryr   googleapiclient.httpr   googleapiclient.errorsr	   r   	getLogger__name__rN   r   r   r%   r-   r6   r]   r_   rp   rs   ru    r   r   <module>r      ss    	  ) 1 * 2 + 0 ,
6	7 
		8	$Y($$	:/|r
<
~;
|%
r   