
    2                     v   S r SSKrSSKJr  SSKJr  SSKJr  SSKJr  SSK	J
r
  SSK	Jr  SS	K	Jr  SS
K	Jr  SSK	Jr  SSKJr  SSKJr  SrSrSrS rSrS rS rS rS rS rS rS rS rS r S r!S3S jr"  S4S jr#S r$S  r%S! r&S" r'S# r(S$ r)S% r*S& r+S' r,S( r-S) r.S* r/S+ r0S, r1S- r2S. r3S/ r4S0 r5S1 r6S2 r7g)5z,General utilties for Cloud Domains commands.    N)encoding)
operations)registrations)flags)
exceptions)log)
properties)	resources)yaml)
console_io)fileszdomains.projects.locationsz%domains.projects.locations.operationsz(domains.projects.locations.registrationsc                  d    [         R                  R                  R                  R	                  SS9$ )NT)required)r	   VALUEScoreprojectGet     .lib/googlecloudsdk/command_lib/domains/util.py<lambda>r   $   s$    :$$))1155t5Dr      c                    ^  U 4S jnU$ )Nc                 L   > [        TU R                  5      R                  5       $ N)ParseRegistrationnameSelfLink)resourceapi_versions    r   UriFunc%RegistrationsUriFunc.<locals>.UriFunc)   s    [(--8AACCr   r   )r    r!   s   ` r   RegistrationsUriFuncr#   (   s    D	.r   c                 *   [         R                  " U 5      nUR                  UR                  R                  R
                  UR                  R                  R                  4;  a/  [        R                  " SR                  UR                  5      5      eg )NzIThe registration resource must be in state ACTIVE or SUSPENDED, not '{}'.)
r   GetMessagesModulestateRegistrationStateValueValuesEnumACTIVE	SUSPENDEDr   Errorformat)r    registrationmessagess      r   AssertRegistrationOperationalr/   .   s~    ,,[9(007700::   

	f\//02 2	r   c                 V   U c  g[         R                  " U 5      n [        R                  " X5      n/ n[        R                  " U5       HN  nSR                  US    Vs/ s H  oR                  S-   PM     sn5      n	XgS    V
s/ s H  oU
-   PM	     sn
-  nMP     UR                  5         U(       a5  [
        R                  " SR                  USR                  U5      5      5      eU$ ! [         a*  n[
        R                  " SR                  X%5      5      eSnAff = fs  snf s  sn
f )	zParse 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_messager9   s              r   ParseMessageFromYamlFilerE   :   s    
\t$+>..|IN
 .//?gGG'!*E*$ZZ#-*EFM!*E*u,*EEN @ 


	*22=3799^3L	NO O 
 
 >


8??=<
==> FEs#   C* D!
D&*
D4%DDc                 h    U R                  S5      n[        US   5      US'   SR                  U5      $ )z(Normalizes domain name in resource name./)splitNormalizeDomainNamer8   )domainpartss     r   NormalizeResourceNamerM   [   s0    
,,s
%!%),%)	%r   c                 ,   U (       d  [         R                  " S5      e U R                  S5      R                  5       nUR	                  5       R                  S5      nU$ ! [         a*  n[         R                  " SR                  X5      5      eSnAff = f)z.Normalizes domain name (including punycoding).zEmpty domain nameidnar2   zInvalid domain name '{}': {}.N)r   r+   encodedecodelowerrstripUnicodeErrorr,   )rK   
normalizedr@   s      r   rJ   rJ   b   s    	


.
//Pv&--/J!!#**3/J 
 
 P


<CCFN
OOPs   >A 
B)%BBc                 B    U R                  S5      R                  S5      $ )Nzutf-8rO   )rP   rQ   rK   s    r   PunycodeToUnicoderX   n   s    	w		&	&v	..r   c                 \    U (       d  gSn[         R                  " X5      (       a  SU ;   a  gg)NFz"^[a-z0-9-]+(\.[a-z0-9-]+)+\.{0,1}$z..T)rematch)rK   patterns     r   ValidateDomainNamer]   r   s(    	1'	'	"	"dfn	r   c                 J    U S L=(       a    [        U R                  5       5      $ r   )boolstrip)ss    r   ValidateNonEmptyrb   |   s    	
$	*4	?*r   c                     U S L=(       a<    [        U 5      S:H  =(       a'    U R                  5       =(       a    U R                  5       $ )N   )lenisalphaisupper)rcs    r   ValidateRegionCoderi      s/    	4	JCGqL	JRZZ\	JbjjlJr   c                 T    U (       d  gSn[        [        R                  " X5      5      $ )NFz^[^@\s]+@[^@\s]+\.[^@\s]+$)r_   rZ   r[   )emailr\   s     r   ValidateEmailrl      s!    	)'	bhhw&	''r   c                 z    U(       a  [         R                  R                  U5        [        R                  " U 5      $ )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_stringrB   s     r   Promptrr      s*     JJW		"	"=	11r   c                    U(       a  [         R                  R                  U5         Ub  [        R                  " XS9nU(       d  U$ O[        R
                  " U 5      nU" U5      (       a  U$ [         R                  R                  U5        Mg  )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.
)rB   default)r   rn   ro   r   PromptWithDefaultrp   )rq   	validatorr=   rB   rt   answers         r   PromptWithValidatorrx      s{    " JJW++2f  ((7fm	jj}% 	r   c                 f    [         R                  R                  5       nUR                  SU 5        U$ )Ndomains)r
   REGISTRYCloneRegisterApiByName)r    registrys     r   GetRegistryr      s+    %%'(
Y4	/r   c                 L    [        U 5      R                  U[        SS.[        S9$ Nglobal)
projectsIdlocationsId)params
collection)r   Parse_PROJECTREGISTRATIONS_COLLECTION)r    r-   s     r   r   r      s2    	[	!	'	' ! * 
( 
+ +r   c                 L    [        U 5      R                  U[        SS.[        S9$ r   )r   r   r   OPERATIONS_COLLECTION)r    	operations     r   ParseOperationr      s2    	[	!	'	' ! ' 
( 
( (r   c                 (    X R                  S5      S  $ )Nr2   )findrW   s    r   DomainNamespacer      s     
C !	""r   c                     [         R                  " U 5      nUc  g [        R                  " U5      R	                  U5      $ r   )r   r%   r   TransferLockEnumMapperGetEnumForChoice)r    transfer_lock_stater.   s      r   ParseTransferLockStater      s<    ,,[9( 		%	%h	/	@	@
 r   c                    [        U R                  5      n[        R                  " SU SU S3SSS9nU(       d  gSn[	        U5       H  u  pgXpR                  U5      :X  d  M  UnM     [        R                  " UUS	U 3S
9nX8   $ )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: r2   zDo you want to change itF)rt   Nr   zSpecify new )optionsrt   rB   )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                     [         R                  " U 5      n[        R                  " U5      n[	        USU5      nUc  g[        X5      $ )z-Prompts the user for new transfer lock state.zTransfer Lock stateN)r   r%   r   r   r   r   )r    transfer_lockr.   r   results        r   PromptForTransferLockStater     sD    ,,[9(,,X6+&;]K&^		44r   c                     [         R                  " U 5      nUc  g [        R                  " U5      R	                  U5      $ r   )r   r%   r   RenewalMethodEnumMapperr   )r    renewal_methodr.   s      r   ParseRenewalMethodr     s<    ,,[9(		&	&x	0	A	A
 r   c                     [         R                  " U 5      n[        R                  " U5      n[	        USU5      nUc  g[        X5      $ )z(Prompts the user for new renewal method.zpreferred Renewal MethodN)r   r%   r   r   r   r   )r    preferred_renewal_methodr.   r   r   s        r   PromptForRenewalMethodr     sJ    ,,[9(--h7+-/G& ^	K	00r   c                  |    Sn [         R                  R                  U 5        [        R                  " SS[
        S9nU$ )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   rn   ro   r   PromptPasswordrb   )rB   	auth_codes     r   PromptForAuthCoder   #  s>    1' **7''$<*,) 
r   c           	          U c  g U n[        U[        5      (       d  [        R                  " U 5      nSR	                  US   [        UR                  SS5      S-  5      UR                  SS5      5      $ )Nz{}.{:02d} {}unitsnanosr   逖 currencyCoder1   )
isinstancedictr   MessageToDictr,   intget)rdrs     r   TransformMoneyTyper   0  sj    Y"	B						"B			r'{Cw0Be0L,M!vvnb9
; ;r   c                    [         R                  " SU 5      nU(       a  UR                  5       u  p#O[        S5      eSU;   a0  UR	                  S5      n[        USU 5      [        X$S-   S 5      U4$ [        U5      SU4$ )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 coder2   Nr3   r   )rZ   r[   groups
ValueErrorr   r   )moneyr[   numberra   r   s        r   _ParseMoneyr   :  s}    
((5u
=%
IFA
J
KKF]KKEvfu~F19:$6 7::v;1r   c                     U(       d  g [        U5      u  p#nUS:X  a  Sn[        R
                  " U 5      nUR                  [        U5      US-  US9$ ! [         a    [        R                  " SU S35      ef = f)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currencyr.   s         r   ParseYearlyPricer   H  s    	(6E( _H,,[9(	Jeem( 
 
D D 
 


\N +5 5 s   A %A8c                 Z    U R                   c  SU l         UR                   c  SUl         X:H  $ )Nr   )r   )xys     r   
EqualPricer   ^  s)    WW_AGWW_AG	
-r   c                 v    [         R                  " SR                  [        U 5      5      SSSSS9nU(       a  U $ g)z)Asks the user to accept the yearly price.zYearly price: {}
z5Do you agree to pay this yearly price for your domainTF)rq   throw_if_unattendedcancel_on_nort   N)r   r   r,   r   )priceacks     r   PromptForYearlyPriceAckr   f  s?    !!!!"4U";<K	# 	Lr   c                 &    U (       d  gSU ;   SU ;   4$ )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   t  s      
	.'	9;Kw;V	VVr   c                 f    [         R                  " SR                  [        U 5      U 5      SSSS9nU$ )Nzp{} is a secure namespace. You may purchase {} now but it will require an SSL certificate for website connection.TF)r   r   rt   )r   r   r,   r   )rK   r   s     r   PromptForHSTSAckr     s;    !!<=CV6"F>,	# 
*r   c                 X   [        XR                  5      nU(       a>  [        R                  R	                  SR                  UR                  5       5      5        U$ Sn[        R                  R                  U 5      nUR                  X4R                  UR                  5       5      5      nU$ )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   rn   ro   r,   Namer   ClientFromApiVersionWaitForOperation)r    responseasynchronousoperation_refrB   operations_clients         r   r   r     s     !mm<-JJ%,,]-?-?-ABC 
/	 /G"))88E 11~~m&8&8&:;=H	/r   c                 >    U (       d  g[         R                  " U 5      $ )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                     U R                   (       a  U R                   $ U R                  (       a  [        U R                  [        5      $ g)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)8__doc__rZ   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#   r/   rE   rM   rJ   rX   r]   rb   ri   rl   rr   rx   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   