
    B3                        d Z ddlmZ ddlmZ ddlm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dlmZ ddlmZ ddlmZ ddlmZ dZdZdZd ZdZd Zd Zd Zd Zd Z d Z!d Z"d Z#d Z$d Z%d6d Z&	 	 d7d!Z'd" Z(d# Z)d$ Z*d% Z+d& Z,d' Z-d( Z.d) Z/d* Z0d+ Z1d, Z2d- Z3d. Z4d/ Z5d0 Z6d1 Z7d2 Z8d3 Z9d4 Z:d5 Z;y)8z,General utilties for Cloud Domains commands.    )absolute_import)division)unicode_literalsN)encoding)
operations)registrations)flags)
exceptions)log)
properties)	resources)yaml)
console_io)fileszdomains.projects.locationsz%domains.projects.locations.operationsz(domains.projects.locations.registrationsc                  j    t         j                  j                  j                  j	                  d      S )NT)required)r   VALUEScoreprojectGet     .lib/googlecloudsdk/command_lib/domains/util.py<lambda>r   '   s$    :$$))1155t5Dr      c                       fd}|S )Nc                 L    t        | j                        j                         S N)ParseRegistrationnameSelfLink)resourceapi_versions    r   UriFuncz%RegistrationsUriFunc.<locals>.UriFunc,   s    [(--8AACCr   r   )r#   r$   s   ` r   RegistrationsUriFuncr%   +   s    D	.r   c                 "   t        j                  |       }|j                  |j                  j                  j
                  |j                  j                  j                  fvr.t        j                  dj                  |j                              y )NzIThe registration resource must be in state ACTIVE or SUSPENDED, not '{}'.)
r   GetMessagesModulestateRegistrationStateValueValuesEnumACTIVE	SUSPENDEDr
   Errorformat)r#   registrationmessagess      r   AssertRegistrationOperationalr1   1   s~    ,,[9(007700::   

	f\//02 2	r   c                 8   | yt        j                  |       }	 t        j                  ||      }g }t        j                  |      D ]J  }dj                  |d   D cg c]  }|j                  dz    c}      }	||d   D 
cg c]  }
|	|
z   	 c}
z  }L |j                          |r4t        j                  dj                  |dj                  |                  |S # t        $ r*}t        j                  dj                  ||            d}~ww xY wc c}w c c}
w )	a  Parse a Yaml file.

  Args:
    path: Yaml file path. If path is None returns None.
    message_type: Message type to parse YAML into.
    error_message: Error message to print in case of parsing error.

  Returns:
    parsed message of type message_type.
  Nz{}: {} r   .   z{}.
Problematic fields: '{}'z, )r   	load_pathr   PyValueToMessage	Exceptionr
   r-   r.   UnrecognizedFieldIterjoinfieldsort)pathmessage_typeerror_messageraw_messageparsed_messageeunknown_fieldsmessageedgeouter_messager;   s              r   ParseMessageFromYamlFilerG   =   s    
\t$+>..|[IN
 .//?gGG'!*E*$TZZ#-*EFM'!*E*}u,*EEN @ 


	*22=3799^3L	NO O 
 
 >


8??=!<
==> FEs#   C D
D	D%%D

Dc                 h    | j                  d      }t        |d         |d<   dj                  |      S )z(Normalizes domain name in resource name./)splitNormalizeDomainNamer:   )domainpartss     r   NormalizeResourceNamerO   ^   s0    
,,s
%!%),%)	%r   c                    | st        j                  d      	 | j                  d      j                         }|j	                         j                  d      }|S # t        $ r*}t        j                  dj                  | |            d}~ww xY w)z.Normalizes domain name (including punycoding).zEmpty domain nameidnar4   zInvalid domain name '{}': {}.N)r
   r-   encodedecodelowerrstripUnicodeErrorr.   )rM   
normalizedrB   s      r   rL   rL   e   s    	


.
//Pv&--/J!!#**3/J 
 
 P


<CCFAN
OOPs   >A 	B"%BBc                 B    | j                  d      j                  d      S )Nzutf-8rQ   )rR   rS   rM   s    r   PunycodeToUnicoderZ   q   s    	w		&	&v	..r   c                 D    | syd}t        j                  ||       rd| v ryy)NFz"^[a-z0-9-]+(\.[a-z0-9-]+)+\.{0,1}$z..T)rematch)rM   patterns     r   ValidateDomainNamer_   u   s'    	1'	'6	"dfn	r   c                 @    | d uxr t        | j                               S r   )boolstrip)ss    r   ValidateNonEmptyrd      s    	
$	*4	?*r   c                 r    | d uxr2 t        |       dk(  xr" | j                         xr | j                         S )N   )lenisalphaisupper)rcs    r   ValidateRegionCoderk      s/    	4	JCGqL	JRZZ\	JbjjlJr   c                 J    | syd}t        t        j                  ||             S )NFz^[^@\s]+@[^@\s]+\.[^@\s]+$)ra   r\   r]   )emailr^   s     r   ValidateEmailrn      s#    	)'	bhhw&	''r   c                 n    |rt         j                  j                  |       t        j                  |       S )zPrompt for user input.

  Args:
    prompt_string: Message to print in the line with prompt.
    message: Optional message to print before prompt.

  Returns:
    User provided value.
  )r   statusPrintr   PromptResponse)prompt_stringrD   s     r   Promptrt      s*     JJW		"	"=	11r   c                     |rt         j                  j                  |       	 |t        j                  | |      }|s|S t        j
                  |       } ||      r|S t         j                  j                  |       \)a  Prompt for user input and validate output.

  Args:
    prompt_string: Message to print in the line with prompt.
    validator: Validation function (str) -> bool.
    error_message: Message to print if provided value is not correct.
    message: Optional message to print before prompt.
    default: Optional default value.

  Returns:
    Valid user provided value or default if not None and user chose it.
  )rD   default)r   rp   rq   r   PromptWithDefaultrr   )rs   	validatorr?   rD   rv   answers         r   PromptWithValidatorrz      ss    " JJW++2f((7fm	jj}% 	r   c                 f    t         j                  j                         }|j                  d|        |S )Ndomains)r   REGISTRYCloneRegisterApiByName)r#   registrys     r   GetRegistryr      s+    %%'(
Y4	/r   c                 R    t        |       j                  |t        ddt              S Nglobal)
projectsIdlocationsId)params
collection)r   Parse_PROJECTREGISTRATIONS_COLLECTION)r#   r/   s     r   r   r      s2    	[	!	'	' ! * 
( 
+ +r   c                 R    t        |       j                  |t        ddt              S r   )r   r   r   OPERATIONS_COLLECTION)r#   	operations     r   ParseOperationr      s2    	[	!	'	' ! ' 
( 
( (r   c                 *    | | j                  d      d  S )Nr4   )findrY   s    r   DomainNamespacer      s     
C !	""r   c                 z    t        j                  |       }|y t        j                  |      j	                  |      S r   )r   r'   r	   TransferLockEnumMapperGetEnumForChoice)r#   transfer_lock_stater0   s      r   ParseTransferLockStater      s<    ,,[9( 		%	%h	/	@	@
 r   c                    t        | j                        }t        j                  d| d| ddd      }|syd}t	        |      D ]  \  }}|| j                  |      k(  s|} t        j                  ||d	| 
      }||   S )a  Prompts the user for the new enum_type value.

  Args:
    enum_mapper: Instance of the EnumMapper.
    enum_type: A string with enum type name to print.
    current_value: Current value of the enum.

  Returns:
    The new enum choice or None if the enum shouldn't be updated.
  zYour current z is: r4   zDo you want to change itF)rv   Nr   zSpecify new )optionsrv   rD   )listchoicesr   PromptContinue	enumerateGetChoiceForEnumPromptChoice)	enum_mapper	enum_typecurrent_valuer   updatecurrent_choiceienumindexs	            r   PromptForEnumr      s     $$%'$$i[m_A6 &
 
.7#ga{++M::n $ 
!
!YK(%
 
r   c                     t        j                  |       }t        j                  |      }t	        |d|      }|yt        | |      S )z-Prompts the user for new transfer lock state.zTransfer Lock stateN)r   r'   r	   r   r   r   )r#   transfer_lockr0   r   results        r   PromptForTransferLockStater     sF    ,,[9(,,X6+&;]K&^	V	44r   c                 z    t        j                  |       }|y t        j                  |      j	                  |      S r   )r   r'   r	   RenewalMethodEnumMapperr   )r#   renewal_methodr0   s      r   ParseRenewalMethodr     s<    ,,[9(		&	&x	0	A	A
 r   c                     t        j                  |       }t        j                  |      }t	        |d|      }|yt        | |      S )z(Prompts the user for new renewal method.zpreferred Renewal MethodN)r   r'   r	   r   r   r   )r#   preferred_renewal_methodr0   r   r   s        r   PromptForRenewalMethodr     sL    ,,[9(--h7+-/G& ^	K	00r   c                      d} t         j                  j                  |        t        j                  ddt
              }|S )z(Prompts the user to enter the auth code.zaPlease provide the authorization code from the domain's current registrar to transfer the domain.zAuthorization code:  z& Authorization code must not be empty.)promptr?   validation_callable)r   rp   rq   r   PromptPasswordrd   )rD   	auth_codes     r   PromptForAuthCoder   &  s>    1' **7''$<*,) 
r   c           	          | y | }t        |t              st        j                  |       }dj	                  |d   t        |j                  dd      dz        |j                  dd            S )Nz{}.{:02d} {}unitsnanosr   逖 currencyCoder3   )
isinstancedictr   MessageToDictr.   intget)rdrs     r   TransformMoneyTyper   3  sg    Y"	B					"B			r'{Cw0Be0L,M!vvnb9
; ;r   c                     t        j                  d|       }|r|j                         \  }}nt        d      d|v r1|j	                  d      }t        |d|       t        ||dz   d       |fS t        |      d|fS )z6Parses money string as tuple (units, cents, currency).z^(\d+|\d+\.\d{2})\s*([A-Z]{3})$z3Value could not be parsed as number + currency coder4   Nr5   r   )r\   r]   groups
ValueErrorr   r   )moneyr]   numberrc   r   s        r   _ParseMoneyr   =  s    
((5u
=%
IFA
J
KKF]KKEvfu~F519:$6 7::v;1r   c                     |sy	 t        |      \  }}}|dk(  rd}t	        j
                  |       }|j                  t        |      |dz  |      S # t        $ r t        j                  d| d      w xY w)z"Parses money string as type Money.NzYearly price 'zF' is invalid. Please specify the amount followed by the currency code.$USDr   )r   r   r   )r   r   r
   r-   r   r'   Moneyr   )r#   price_stringr   centscurrencyr0   s         r   ParseYearlyPricer   K  s    	(6E5( _H,,[9(	Jeem( 
 
D D 
 


\N +5 5 s   A #A3c                 X    | j                   d| _         |j                   d|_         | |k(  S )Nr   )r   )xys     r   
EqualPricer   a  s+    WW_AGWW_AG	
a-r   c                 p    t        j                  dj                  t        |             dddd      }|r| S y)z)Asks the user to accept the yearly price.zYearly price: {}
z5Do you agree to pay this yearly price for your domainTF)rs   throw_if_unattendedcancel_on_norv   N)r   r   r.   r   )priceacks     r   PromptForYearlyPriceAckr   i  s?    !!!!"4U";<K	# 	Lr   c                     | syd| v d| v fS )zParses registration notices.

  Args:
    notices: list of notices (lowercase-strings).

  Returns:
    Pair (public privacy ack: bool, hsts ack: bool).
  )FFz#public-contact-data-acknowledgementzhsts-preloadedr   )noticess    r   ParseRegisterNoticesr   w  s      
	.'	9;Kw;V	VVr   c                 j    t        j                  dj                  t        |       |       ddd      }|S )Nzp{} is a secure namespace. You may purchase {} now but it will require an SSL certificate for website connection.TF)r   r   rv   )r   r   r.   r   )rM   r   s     r   PromptForHSTSAckr     s;    !!<=CV6"F>,	# 
*r   c                 R   t        | |j                        }|r>t        j                  j	                  dj                  |j                                      |S d}t        j                  j                  |       }|j                  ||j                  |j                                     }|S )a   Handles waiting for the operation and printing information about it.

  Args:
    api_version: Cloud Domains API version to call.
    response: Response from the API call
    asynchronous: If true, do not wait for the operation

  Returns:
    The last information about the operation.
  zStarted '{}'zWaiting for '{}' to complete)r   r    r   rp   rq   r.   Namer   ClientFromApiVersionWaitForOperation)r#   responseasynchronousoperation_refrD   operations_clients         r   r   r     s     !hmm<-JJ%,,]-?-?-ABC 
/	 /G"))88E 11w~~m&8&8&:;=H	/r   c                 2    | syt        j                  |       S )zReads the text contents from the given path.

  Args:
    path: str, The file path to read.

  Raises:
    Error: If the file cannot be read.

  Returns:
    str, The text string read from the file.
  N)r   ReadFileContents)r=   s    r   r   r     s     
				%%r   c                     | j                   r| j                   S | j                  rt        | j                  t              S y)z-Returns the batch size for listing resources.N)	page_sizelimitmin_MAX_LIST_BATCH_SIZE)argss    r   GetListBatchSizer     s/    	^^>>zztzz/00r   r   )NN)<__doc__
__future__r   r   r   r\   apitools.base.pyr   googlecloudsdk.api_lib.domainsr   r   "googlecloudsdk.command_lib.domainsr	   googlecloudsdk.corer
   r   r   r   r   googlecloudsdk.core.consoler   googlecloudsdk.core.utilr   LOCATIONS_COLLECTIONr   r   r   r   r%   r1   rG   rO   rL   rZ   r_   rd   rk   rn   rt   rz   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>r      s   3 &  ' 	 % 5 8 4 * # * ) $ 2 *3 ? E D 	2B	/+K(2$ !% $	&B+(#@5	1
;D,W,&"r   