
    `gj28                        d Z ddlm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 ddlZddlmZmZ dZ G d d	e      Z G d
 de      Z G d d      Zy)z-Reusable Microsoft Graph REST client helpers.    )annotationsN)Path)AnyAsyncIterator	AwaitableCallable)GraphCredentialsMicrosoftGraphTokenProviderz https://graph.microsoft.com/v1.0c                      e Zd ZdZy)MicrosoftGraphClientErrorz%Base class for Graph client failures.N)__name__
__module____qualname____doc__     O/root/.hermes/venv/lib/python3.12/site-packages/tools/microsoft_graph_client.pyr   r      s    /r   r   c                  F     e Zd ZdZddd	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ xZS )MicrosoftGraphAPIErrorz&Raised when a Graph API request fails.Nretry_after_secondspayloadc          
         || _         || _        || _        || _        || _        t
        |   d| d| d| d|        y )NzMicrosoft Graph API error z for  : )status_codemethodurlr   r   super__init__)selfr   r   r   messager   r   	__class__s          r   r    zMicrosoftGraphAPIError.__init__   sS     '#6 (U6(!C57)T	
r   )r   intr   strr   r%   r"   r%   r   zfloat | Noner   r   returnNone)r   r   r   r   r    __classcell__)r#   s   @r   r   r      s\    0 -1

 
 	

 
 *
 
 

 
r   r   c                     e Zd ZdZedddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZedd       Zddd		 	 	 	 	 	 	 dd
Zddd	 	 	 	 	 	 	 d dZ	ddd	 	 	 	 	 	 	 d dZ
dd	 	 	 	 	 d!dZddd		 	 	 	 	 	 	 d"dZddd		 	 	 	 	 	 	 d#dZddd	 	 	 	 	 	 	 	 	 d$dZdddd	 	 	 	 	 	 	 	 	 	 	 d%dZd&dZed'd       Zed(d       Zed)d       Zed*d       Ze	 	 	 	 	 	 	 	 d+d       Zy),MicrosoftGraphClientzAMinimal async Microsoft Graph client with retries and pagination.g      N@   NzHermes-Agent/graph-client)base_urltimeoutmax_retries	transportsleep
user_agentc                   || _         |j                  d      | _        || _        t	        dt        |            | _        || _        |xs t        j                  | _
        || _        y )N/r   )token_providerrstripr,   r-   maxr$   r.   
_transportasyncior0   _sleepr1   )r!   r4   r,   r-   r.   r/   r0   r1   s           r   r    zMicrosoftGraphClient.__init__0   sU     - ,q#k"23#,w}}$r   c                R    t        j                         }t        |      } | |fi |S )N)r	   from_envr
   )clskwargscredentialsproviders       r   r;   zMicrosoftGraphClient.from_envC   s*    &//1.{;8&v&&r   paramsheadersc               j   K   | j                  d|||       d {   }| j                  |      S 7 w)NGETr@   _request_decode_json)r!   pathrA   rB   responses        r   get_jsonzMicrosoftGraphClient.get_jsonI   s8      ud67SS  ** T   313	json_bodyrB   c               j   K   | j                  d|||       d {   }| j                  |      S 7 w)NPOSTrL   rE   r!   rH   rM   rB   rI   s        r   	post_jsonzMicrosoftGraphClient.post_jsonS   s9      vtyRYZZ  ** [rK   c                  K   | j                  d|||       d {   }|j                  dk(  s|j                  si S | j                  |      S 7 2w)NPATCHrL      rF   r   contentrG   rP   s        r   
patch_jsonzMicrosoftGraphClient.patch_json]   sT      w	SZ[[3&h.>.>I  ** \s   AA3ArB   c                  K   | j                  d||       d {   }|j                  dk(  s|j                  sd|j                  dS | j                  |      S 7 ?w)NDELETErX   rT   T)deletedr   rU   )r!   rH   rB   rI   s       r   deletezMicrosoftGraphClient.deletei   s]      xwGG3&h.>.>#H4H4HII  ** Hs   AAA Ac              T  K   | j                  |      }t        |xs i       }|r| j                  d||xs d |       d {   }| j                  |      }t	        |t              s"t        dt        |      j                   d      | |j                  d      }i }|ry y 7 dw)NrD   r@   z,Expected paginated Graph response dict, got .z@odata.nextLink)	_resolve_urldictrF   rG   
isinstancer   typer   get)r!   rH   rA   rB   next_urlnext_paramsrI   r   s           r   iterate_pagesz"MicrosoftGraphClient.iterate_pagest   s       $0066<R(!]]"*d	 +  H ''1Ggt,/B4=CYCYBZZ[\  M{{#45HK s   ?B(B&A!B($B(c                  K   g }| j                  |||      2 3 d {   }|j                  d      }t        |t              s+|j	                  |       =7 86 |S w)Nr@   value)rf   rc   ra   listextend)r!   rH   rA   rB   itemspagerh   s          r   collect_paginatedz&MicrosoftGraphClient.collect_paginated   sb      ,,T&',R 	$ 	$$HHW%E%&U#	$R s+   AAAA"AAAAi   )rB   
chunk_sizec               b  K   | j                  |      }t        |      }|j                  j                  dd       |j	                  |j
                  dz         }d}d}	|| j                  k  r[| j                  j                  |dkD  xr | j                  |	             d{   }
d|
 d| j                  d	}|r|j                  |       	 t        j                  t        j                  | j                        | j                   
      4 d{   }|j#                  d||      4 d{   }|j$                  dk\  r)|j'                          d{    | j)                  d||      }|}	|j$                  dk(  rz|| j                  k  rk| j                  j+                          | j-                  | j/                  ||             d{    |dz  }	 ddd      d{    ddd      d{    | j1                  |      r`|| j                  k  rQ| j-                  | j/                  ||             d{    |dz  }	 ddd      d{    ddd      d{    ||j2                  j5                  d      }|j7                  d      5 }|j9                  |      2 3 d{   }|s|j;                  |       |j?                  d       tA        d| d      7 G7 7 7 7 *7 7 
7 7 7 7 U6 	 ddd       n# 1 sw Y   nxY wddd      d{  7   n# 1 d{  7  sw Y   nxY wddd      d{  7   n# 1 d{  7  sw Y   nxY wn# t        j<                  $ ro}|}	|j?                  d       || j                  k\  rtA        d| d|       || j-                  | j/                  d|             d{  7   |dz  }Y d}~d}~ww xY wtC        jD                  ||       tG        |      |jI                         jJ                  dS w)a3  Download a Graph resource to disk, streaming the response body.

        The body is written chunk-by-chunk via ``response.aiter_bytes`` with
        the ``httpx.AsyncClient`` kept open for the duration of the iteration,
        so recordings and other large artifacts do not need to fit in memory.
        T)parentsexist_okz.partr   Nforce_refreshBearer application/jsonAuthorizationAcceptz
User-Agentr-   r/   rD   rX          zcontent-typewb)rn   )
missing_okz(Microsoft Graph download failed for GET r   )rH   
size_bytescontent_typez3Microsoft Graph download exhausted retries for GET r^   )&r_   r   parentmkdirwith_suffixsuffixr.   r4   get_access_token_should_refresh_tokenr1   updatehttpxAsyncClientTimeoutr-   r7   streamr   aread_build_api_errorclear_cacher9   _retry_delay_should_retryrB   rc   openaiter_byteswrite	HTTPErrorunlinkr   osreplacer%   statst_size)r!   rH   destinationrB   rn   r   target
tmp_targetattempt
last_errortokenrequest_headersclientrI   	api_errorr   handlechunkexcs                      r   download_to_filez%MicrosoftGraphClient.download_to_file   s-     %k"D48''(?@
'+
)))-->>%kTd.H.H.T ?  E $+5'!2,"ooO
 &&w/8 ,,!MM$,,7"oo -8 -8 %}} /  -   )8 )8 "#//36 #+.."222(,(=(=eS((SI)2J !) 4 4 ;$+d.>.>$> $ 3 3 ? ? A&*kk$($5$5h$H'" !" !" !(1 (+)8 )8	-8 -8 -88 !% 2 28 <$+d.>.>$>&*kk$($5$5h$H'" !" !" !(1 (?)8 )8	-8 -8 -8J #,O'/'7'7';';N'K'__T2 8f/7/C/C+5 0D 0 8 8e $)$*LL$7& 	T*'A#aH
 	
[-8)8 3!"#)8	-8>!"7)8	-8R8 08 8 8I)8 )8 )8 )8 )8	-8 -8 -8 -8 -8\ ?? 	 
!!T!2d...3B3%r#O kk$"3"3D'"BCCC1	 JJz6*F$kkm33 , s  B!P/#K*$*P/AM- K-M- M.K0/M2$L0K3A5L0K6
L0M"K9#M'M- 2K<3M- 7P/9AL0=K?>
L0MLMM- #L$M- (P/*.L0L+L/L0L3L7L	"P/-M- 0M3L06L09M<M- ?L0MM- LL		L0LL0M)L,*M0M	6L97M	>MM- MM- M)M M)%M- ,P/-O/ AO*O
O*$P/*O//A P/)rA   rM   rB   c          	     *  K   | j                  |      }d}d }|| j                  k  r| j                  j                  |dkD  xr | j	                  |             d {   }	d|	 d| j
                  d}
|d|
d<   |r|
j                  |       	 t        j                  t        j                  | j                        | j                        4 d {   }|j                  |||||
       d {   }d d d       d {    j"                  dk  r|S | j%                  |||      }|}|j"                  dk(  rY|| j                  k  rJ| j                  j'                          | j                  | j!                  ||             d {    |dz  }{| j)                  |      r?|| j                  k  r0| j                  | j!                  ||             d {    |dz  }|t        d| d
| d      7 7 (7 7 # 1 d {  7  sw Y   xY w# t        j                  $ r`}|}|| j                  k\  rt        d	| d
| d|       || j                  | j!                  d |             d {  7   |dz  }Y d }~nd }~ww xY w7 7 w)Nr   rr   rt   ru   rv   zContent-Typery   )rA   jsonrB   z#Microsoft Graph request failed for r   r   r|   rz   r{   z.Microsoft Graph request exhausted retries for r^   )r_   r.   r4   r   r   r1   r   r   r   r   r-   r7   requestr   r   r9   r   r   r   r   r   )r!   r   path_or_urlrA   rM   rB   r   r   r   r   r   r   rI   r   r   s                  r   rF   zMicrosoftGraphClient._request  s     ,'+
)))-->>%kTd.H.H.T ?  E $+5'!2,"ooO
 $2D/&&w/ ,,!MM$,,7"oo 
 
 %+^^%& / &4 &  H	
 
* ##c)--fc8DI"J##s*w9I9I/I##//1kk$"3"3Hg"FGGG1!!(+$:J:J0Jkk$"3"3Hg"FGGG1O'<VHAcU!L
 	
m
 	
 
 
 
 ??  
d...3=fXQse2cUS kk$"3"3D'"BCCC1$ H
 Hs   AJG71JAH G:H H0G=1H5H  H H BJJAJJ J:H =H H HH	HH J+A
J5I86
J JJJJc                x    |j                  d      r|S |j                  d      r|nd| }| j                   | S )N)zhttp://zhttps://r3   )
startswithr,   )r!   r   rH   s      r   r_   z!MicrosoftGraphClient._resolve_urlK  sE    !!"9:)44S9{;-?P--''r   c                    	 | j                         S # t        $ r?}t        d| j                  j                   d| j                  j
                         |d }~ww xY w)Nz0Microsoft Graph response was not valid JSON for r   )r   
ValueErrorr   r   r   r   )rI   r   s     r   rG   z!MicrosoftGraphClient._decode_jsonQ  sc    	==?" 	+B##**+1X-=-=-A-A,BD 	s    	A:AAc                ^    | y| j                   dk(  xs d| j                   cxk  xr dk  S c S )NTi  i  iX  )r   )rI   s    r   r   z"MicrosoftGraphClient._should_retry[  s7    ##s*OcX5I5I.OC.OO.OOr   c                D    t        | t              xr | j                  dk(  S )Nr{   )ra   r   r   )errors    r   r   z*MicrosoftGraphClient._should_refresh_tokena  s!    %!78UU=N=NRU=UUr   c                    | 3| j                   j                  d      }|r	 t        dt        |            S t        ddd|z  z        S # t        $ r Y w xY w)NRetry-Afterg        g       @g      ?   )rB   rc   r6   floatr   min)rI   r   retry_afters      r   r   z!MicrosoftGraphClient._retry_delaye  sd    "**..}=KsE+$677 3qG|,-- " s   A 	AAc                2   d }|j                   j                         xs d}	 |j                         }t	        |t
              ro|j                  d      }t	        |t
              r<|j                  d      }|j                  d      }|r
|r| d| }n |rt        |      }nt	        |t              r|}d }|j                  j                  d      }	|	r	 t        |	      }t        |j                  | ||||      S # t        $ r d }Y w xY w# t        $ r d }Y 9w xY w)Nzunknown errorr   coder"   r   r   r   )textstripr   r   ra   r`   rc   r%   rB   r   r   r   )
r   r   rI   r   r"   r   r   inner_messager   header_values
             r   r   z%MicrosoftGraphClient._build_api_errorp  s     --%%':?	mmoG gt$KK(E%&yy( %		) 4M!%b8G"!-0GE3'$(''++M:##L1 &   +
 	
/  	G	(  #"#s#   C7 D 7DDDD)r4   r
   r,   r%   r-   r   r.   r$   r/   zhttpx.AsyncBaseTransport | Noner0   z)Callable[[float], Awaitable[None]] | Noner1   r%   r&   r'   )r=   r   r&   z'MicrosoftGraphClient')rH   r%   rA   dict[str, Any] | NonerB   dict[str, str] | Noner&   r   )rH   r%   rM   
Any | NonerB   r   r&   r   )rH   r%   rB   r   r&   dict[str, Any])rH   r%   rA   r   rB   r   r&   zAsyncIterator[dict[str, Any]])rH   r%   rA   r   rB   r   r&   z	list[Any])
rH   r%   r   z
str | PathrB   r   rn   r$   r&   r   )r   r%   r   r%   rA   r   rM   r   rB   r   r&   httpx.Response)r   r%   r&   r%   )rI   r   r&   r   )rI   httpx.Response | Noner&   bool)r   zException | Noner&   r   )rI   r   r   r$   r&   r   )r   r%   r   r%   rI   r   r&   r   )r   r   r   r   DEFAULT_GRAPH_BASE_URLr    classmethodr;   rJ   rQ   rW   r\   rf   rm   r   rF   r_   staticmethodrG   r   r   r   r   r   r   r   r*   r*   -   s   K /59;?5%3% 	%
 % % 3% 9% % 
%& ' ' )-)-++ &	+
 '+ 
+ !%)-++ 	+
 '+ 
+ !%)-
+
+ 	
+
 '
+ 

+  *.		+	+ '		+
 
	+ )-)- &	
 ' 
': )-)- &	
 ' 
& *.f
f
  f

 'f
 f
 
f
Z )- $)-F
F
 F

 &F
 F
 'F
 
F
P(   P P
 V V . . '
'
'
 !'
 
 	'
 '
r   r*   )r   
__future__r   r8   r   pathlibr   typingr   r   r   r   r   tools.microsoft_graph_authr	   r
   r   RuntimeErrorr   r   r*   r   r   r   <module>r      sM    3 "  	  : :  T < 0 0
6 
.k
 k
r   