
    Dj	7                        d Z ddlZddlZddlmZmZmZ ddlmZ ddlm	Z	 ddl
mZmZmZmZmZmZ ddl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 dd	lmZ dd
lm Z m!Z!m"Z"m#Z#m$Z$ erddl%m&Z&  e'h d          Z( G d dej)                  Z*dS )zPyicloud Session handling    N)JSONDecodeErrordumpload)pathmatch)TYPE_CHECKINGAnyNoReturnOptionalUnioncast)Response)CONTENT_TYPECONTENT_TYPE_JSONCONTENT_TYPE_TEXT_JSONERROR_ACCESS_DENIEDERROR_AUTHENTICATION_FAILEDERROR_ZONE_NOT_FOUNDHEADER_DATAAppleAuthError)PyiCloudCookieJar)PyiCloud2FARequiredExceptionPyiCloud2SARequiredExceptionPyiCloudAPIResponseExceptionPyiCloudAuthRequiredException$PyiCloudServiceNotActivatedException)PyiCloudService>   middataptknsalttopictxnidakdataidmsdatanextStep	next_step
push_tokensessionUUIDsession_uuidencryptedCodesource_app_idencrypted_codetopics_by_hashconnection_pathc                   B    e Zd ZdZ	 	 d%dddededed	eeeef                  d
df fdZe	d
eee
f         fd            Ze	d
ej        fd            Zd&dZd&dZd'ded
dfdZded
dfdZded
efdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 d(d
efdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 d(d
efdZd
ef fdZd
ef fdZedej        j        d
efd            Zdeded
efdZ ded
dfdZ!dedee"eef                  d ed
efd!Z#e	d)d"            Z$e	d
efd#            Z%e	d
efd$            Z& xZ'S )*PyiCloudSessionziCloud session.FNservicer   	client_idcookie_directoryverifyheadersreturnc                    t                                                       || _        || _        || _        t          | j                  | _        i | _        t          j
        t                    | _        |r| j                            |           |                                  | j                            d          s| j                            d|i           dS dS )z>Initialize the persisted requests session used by the service.filenamer4   N)super__init___servicer6   _cookie_directoryr   cookiejar_pathcookies_datalogging	getLogger__name___loggerr7   update_load_session_dataget)selfr3   r4   r5   r6   r7   	__class__s         K/home/thesage/.hermes/venv/lib/python3.11/site-packages/pyicloud/session.pyr=   zPyiCloudSession.__init__?   s     	)0&6($2EFFF%'
'.'8'B'B 	)L(((!!!z~~k** 	8J{I677777	8 	8    c                     | j         S )zGets the session data)rB   rJ   s    rL   r    zPyiCloudSession.dataZ   s     zrM   c                     | j         S )zGets the request logger)rF   rO   s    rL   loggerzPyiCloudSession.logger_   s     |rM   c                    t           j                            | j                  r	 t	          t
          | j                                                   nk# t          t          f$ rW}| j
                            d| j        |           t	          t
          | j                                                   Y d}~nd}~ww xY w| j
                            d| j                   i | _        	 t!          | j        d          5 }t          |          | _        ddd           dS # 1 swxY w Y   dS # t"          t          f$ r | j
                            d           Y dS w xY w)zLoad session_data from file.zDFailed to load cookie jar %s: %s; starting without persisted cookiesNzUsing session file %sutf-8encodingzSession file does not exist)osr   existsr@   r   r   rA   r   OSError
ValueErrorrF   warningcleardebugsession_pathrB   openr   info)rJ   exc	session_fs      rL   rH   z"PyiCloudSession._load_session_datad   s   7>>$-.. 		>>&55::<<<<Z( > > >$$Z'  
 &55;;========> 	2D4EFFF%'
	=d''::: -i!)__
- - - - - - - - - - - - - - - - - - 
 	= 	= 	= L;<<<<<<		=sN   ,A B;$AB66B;&D+ <DD+ D""D+ %D"&D+ ++EEc                    | j         r?t          j                            | j                   st          j        | j         d           t          | j        dd          5 }t          d t          | j	                  
                                D             |           | j                            d| j                   ddd           n# 1 swxY w Y   	 t          t          | j                                                   | j                            d	| j                   dS # t$          t&          f$ r&}| j                            d
|           Y d}~dS d}~ww xY w)zSave session_data to file.T)exist_okwrS   rT   c                 ,    i | ]\  }}|t           v||S  )NON_PERSISTED_SESSION_KEYS).0keyvalues      rL   
<dictcomp>z6PyiCloudSession._save_session_data.<locals>.<dictcomp>   s4       "U"<<< <<<rM   zSaved session data to file: %sNzSaved cookies data to file: %szFailed to save cookies data: %s)r?   rV   r   isdirmakedirsr^   r]   r   dictrB   itemsrQ   r\   r   r   rA   saver@   rX   rY   rZ   )rJ   outfiler`   s      rL   _save_session_dataz"PyiCloudSession._save_session_data|   s   ! 	?"'--8N*O*O 	?K.>>>>$#S7;;; 
	Sw &*4:&6&6&<&<&>&>  
    K>@QRRR
	S 
	S 
	S 
	S 
	S 
	S 
	S 
	S 
	S 
	S 
	S 
	S 
	S 
	S 
	S	H"DL1166888K>@STTTTT$ 	H 	H 	HK A3GGGGGGGGG	Hs,   AC		CCAD# #E4EETremove_filesc                    	 t          t          | j                                                   nY# t          t
          f$ rE}| j                            d| j        |           t          | j                  | _        Y d}~nd}~ww xY wi | _	        |r8| j        | j
        fD ]'}	 t          j        |           # t          $ r Y $w xY wdS |                                  dS )z)Clear persisted session and cookie state.zAFailed to clear cookie jar %s: %s; resetting in-memory cookie jarr:   N)r   r   rA   r[   KeyErrorRuntimeErrorrF   rZ   r@   rB   r]   rV   removeFileNotFoundErrorrr   )rJ   rs   r`   persisted_paths       rL   clear_persistencez!PyiCloudSession.clear_persistence   s    	K"DL11779999,' 	K 	K 	KL  S#  
 -d6IJJJDLLLLLL	K 
 	&#'#68I"J  In----(   H  ##%%%%%s'   ,/ B ;B  B"B77
CCresponsec                     t          j                    D ]U\  }}|j                            |          r6|}| j                            ||j                            |          i           VdS )z"Update session_data with new data.N)r   ro   r7   rI   rB   rG   )rJ   r{   headerrj   session_args        rL   _update_session_dataz$PyiCloudSession._update_session_data   sx    (.00 	O 	OMFE##F++ O#(
!!;0@0D0DV0L0L"MNNN	O 	OrM   c                     |j                             t          d          }t          t          g}|                    d          d         |v S )zHReturn whether a response advertises one of the accepted JSON mimetypes. ;r   )r7   rI   r   r   r   split)rJ   r{   content_typejson_mimetypess       rL   _is_json_responsez!PyiCloudSession._is_json_response   sG    $,00rBB"%
 !!#&&q)^;;rM   c                 L    |                      |||||||||	|
||||||          S )zCDispatch a request through the normalized session request pipeline.paramsr    r7   rA   filesauthtimeoutallow_redirectsproxieshooksstreamr6   certjson)_requestrJ   methodurlr   r    r7   rA   r   r   r   r   r   r   r   r6   r   r   s                    rL   requestzPyiCloudSession.request   sO    ( }}+!  
 
 	
rM   c                 L    |                      |||||||||	|
||||||          S )z9Dispatch a request without response-status normalization.r   )_request_rawr   s                    rL   request_rawzPyiCloudSession.request_raw   sQ    *   +! ! 
 
 	
rM   c                 :   | j                             d||           	  t                      j        d||d|}n6# t          j        j        $ r}|                     |           Y d}~nd}~ww xY w|                     |           | 	                                 |S )zCPerform a request and persist cookies/session data without raising.%s %sr   r   Nrf   )
rQ   r\   r<   r   requests
exceptionsRequestException_raise_request_exceptionr   rr   )rJ   r   r   kwargsr{   errrK   s         rL   r   zPyiCloudSession._request_raw	  s     		
 	
 	

	/!0 "" " " "HH
 "3 	/ 	/ 	/))#........	/!!(+++!!!s   < A/A**A/c                    | j                             d||           	  t                      j        d||d|}|                     |           |                                  t          |j                  }|j        s]| 	                    |          p/|t          j        t          j        t          j        t          j        fv fr|                     ||          S |                                 | 	                    |          s|S |                     |           |S # t$          j        j        $ r }|                     |           Y d}~dS d}~ww xY w)zRequest method.r   r   )status_coder{   Nrf   )rQ   r\   r<   r   r   rr   intr   okr   r   TWO_FACTOR_REQUIREDFIND_MY_REAUTH_REQUIREDLOGIN_TOKEN_EXPIREDGENERAL_AUTH_ERROR_handle_request_errorraise_for_status_decode_json_responser   r   r   r   )rJ   r   r   r   r{   r   r   rK   s          rL   r   zPyiCloudSession._request"  s    		
 	
 	
$	/!0 "" " " "H %%h///##%%%"8#788K; &&x00 "6":"6"5		$  11 +% 2   
 %%'''))(33  &&x000O"3 	/ 	/ 	/))#.........	/s$   B<D *D D E2EEr   c                     t          | t          j                  r-| j        &t	          | j        j        | j        j                  | t	          d          | )zKNormalize low-level requests failures into the session's public error type.N)reasoncodezRequest failed to iCloud)
isinstancer   	HTTPErrorr{   r   textr   )r   s    rL   r   z(PyiCloudSession._raise_request_exceptionU  s_     c8-.. 	3<3K.|(\-    ++EFFCOrM   r   c                 j   |t           j        k    r[|                     |          rF|                                                    d          dk    rt          | j        j        |          |t           j        k    rt          | j        j        |          | 
                    |||j                   dS )zHandle request error.authTypehsa2)apple_idr{   N)r   r   r   r   rI   r   r3   account_namer   r   _raise_errorr   )rJ   r   r{   s      rL   r   z%PyiCloudSession._handle_request_error`  s     >===&&x00 >$$Z00F::.2!   
 .@@@/2!   
 	(KAAAAArM   c           	      |   t          |j                  dk    rdS 	 |                                }t          |t                    r|                    d          }|p|                    d          }|p|                    d          }|p|                    d          }|rt          |t                    sd}|rG|                    d          }|p|                    d	          }|                     |||           dS dS dS # t          $ r. | j	        
                    d
t          |dd                     Y dS w xY w)zDecode JSON response.r   NerrorMessager   errorReasonerrorzUnknown reason	errorCodeserverErrorCodezFFailed to parse response body as JSON despite JSON mimetype; status=%sr   unknown)lencontentr   r   rn   rI   strr   r   rQ   r\   getattr)rJ   r{   r    r   r   s        rL   r   z%PyiCloudSession._decode_json_responsex  sl   x  A%%F	@HD$%% >(,(@(@5488H#5#5:488M#:#:4488G#4#4 .*VS"9"9 .-F >6:hh{6K6KD>488,=#>#>D%%hf=====> >> >
  	 	 	KX-;;     	s   C!D 4D;:D;r   r   c                 n   | j         j        r|dk    rt          | j         j                  |t          t
          fv rd}t          |||          |t          k    r|dz   }t          |t                    r2|t          j        t          j        t          j        t          j        fv rd}t          |||          )zGRaise the session's public exception for a parsed iCloud error payload.z$Missing X-APPLE-WEBAUTH-TOKEN cookiezUPlease log into https://icloud.com/ to manually finish setting up your iCloud servicezd.  Please wait a few minutes then try again.The remote servers might be trying to throttle requests.z$Authentication required for Account.)r3   requires_2sar   r   r   r   r   r   r   r   r   r   r   r   r   r   )rJ   r{   r   r   s       rL   r   zPyiCloudSession._raise_error  s    
 L%	J@@@.t|/HIII(*EFFF8  7vtXNNN&&& K K  dC   	<T.2.-	.
 &
 &
 <F*64BBBrM   c                     | j         S )zGets the service.)r>   rO   s    rL   r3   zPyiCloudSession.service  s     }rM   c                     t          j        | j        d                    d | j        j        D                       dz             S )zGet path for cookiejar file.r   c                 2    g | ]}t          d |          |S z\wr   rh   cs     rL   
<listcomp>z2PyiCloudSession.cookiejar_path.<locals>.<listcomp>  %    MMM1U5!__MQMMMrM   z
.cookiejarr   joinr?   r3   r   rO   s    rL   r@   zPyiCloudSession.cookiejar_path  sI     y"GGMM 9MMMNN
 
 	
rM   c                     t          j        | j        d                    d | j        j        D                       dz             S )zGet path for session data file.r   c                 2    g | ]}t          d |          |S r   r   r   s     rL   r   z0PyiCloudSession.session_path.<locals>.<listcomp>  r   rM   z.sessionr   rO   s    rL   r]   zPyiCloudSession.session_path  sI     y"GGMM 9MMMNN
 
 	
rM   )FN)r8   N)T)NNNNNNNTNNNNNN)r8   r   )(rE   
__module____qualname____doc__r   boolr   rn   r=   propertyr
   r    rC   LoggerrQ   rH   rr   rz   r   r   r   r   r   r   r   staticmethodr   r   r   r   r   r   r   r   r   r   r3   r@   r]   __classcell__)rK   s   @rL   r2   r2   <   s        ,08 8"8 8 	8
 8 $sCx.)8 
8 8 8 8 8 86 d38n    X     X= = = =0H H H H,& &d &d & & & &0OX O$ O O O O<( <t < < < < #%
 %
$ 
%%
 %
 %
 %
V #&
 &
$ 
%&
 &
 &
 &
P
 
     21/
 
1/ 1/ 1/ 1/ 1/ 1/f Ph&9&J Px P P P \PBB B 
	B B B B0h 4    4C C(0sCx(ACKNC	C C C C<    X 
 
 
 
 X
 
c 
 
 
 X
 
 
 
 
rM   r2   )+r   rC   rV   r   r   r   r   r   rer   typingr	   r
   r   r   r   r   r   requests.modelsr   pyicloud.constr   r   r   r   r   r   r   r   pyicloud.cookie_jarr   pyicloud.exceptionsr   r   r   r   r   pyicloud.baser   	frozensetrg   Sessionr2   rf   rM   rL   <module>r      s      				 , , , , , , , , , ,             F F F F F F F F F F F F F F F F  $ $ $ $ $ $	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 2 1 1 1 1 1               .------ 'Y    0I
 I
 I
 I
 I
h& I
 I
 I
 I
 I
rM   