o
    i2                  
   @   s  d dl Z d dlZd dlZd dlZd dlmZ d dlmZmZm	Z	 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mZ d d	lmZ d d
lmZ d dlmZ d dlmZmZm Z m!Z! ej"ddddZ#G dd dZ$ee$Z%de&de'fddZ(	d,de&dee& de	ee& ee& f fddZ)e#j*dddej+ej,ddd d!d"fd#e'fd$dZ-e#j*d%d&dej+ed'd% Z.e#j*d(d)dej+ed*d+ Z/dS )-    N)asynccontextmanager)AsyncGeneratorOptionalTuple)logger)Columns)Live)Panel)synchronize_apisynchronizer)requires_login)console)API)configremove_user_configupdate_user_configuser_config_pathauthz Manage Pipecat Cloud credentialsT)namehelpno_args_is_helpc                   @   s`   e Zd Zdd Zedeeee ee ee f df fddZ	dd	e
d
e
dee fddZdS )	_AuthFlowc                 C   s   d S N )selfr   r   R/home/ubuntu/.local/lib/python3.10/site-packages/pipecatcloud/cli/commands/auth.py__init__$   s   z_AuthFlow.__init__returnNc              
   C  s  zt  4 I d H i}td }t| |j|ddid4 I d H 9}|jdkr1td|j |	 I d H }|d | _
|d | _|d	 }|d
}| j
||fV  W d   I d H  n1 I d H sbw   Y  W d   I d H  W d S 1 I d H syw   Y  W d S  ty   dV  Y d S w )N
login_pathuse_codetrue)params   zFailed to start auth flow: token_flow_idwait_secretweb_urlcode)NNN)aiohttpClientSessionr   construct_api_urlr   debugpoststatus	Exceptionjsonr#   r$   get)r   sessionurlrespdatar%   r&   r   r   r   start'   s&   




*2z_AuthFlow.start      D@      @timeoutnetwork_timeoutc              
      s  t   }t 4 I d H }t   | |k rz|jtd td | j| jdtj	|| dd4 I d H \}|j
dkr| I d H }|d dkrh|d	 W  d   I d H  W W  d   I d H  S |d d
kr	 W d   I d H  W W d   I d H  d
S t dI d H  	 W d   I d H  W q1 I d H sw   Y  W n t jtjfy   Y qw t   | |k s	 W d   I d H  d S 1 I d H sw   Y  d S )Napi_hostlogin_status_path)r#   r$   )total)r!   r7   r"   r,   completetokenfailure   )asyncioget_event_looptimer'   r(   r/   r   r#   r$   ClientTimeoutr,   r.   sleepTimeoutErrorClientError)r   r7   r8   
start_timer0   r2   r3   r   r   r   finish;   s@   
00z_AuthFlow.finish)r5   r6   )__name__
__module____qualname__r   r   r   r   r   strr4   floatrH   r   r   r   r   r   #   s      r   r1   r   c              
   C   s   z7dt jv p
dt jv }tt jdpt jd}|r |s W dS t }t|tjr2|jdvr2W dS || W S  tj	t
tfyE   Y dS w )NWSL_DISTRO_NAMEWSL_INTEROPDISPLAYWAYLAND_DISPLAYF)openzx-www-browserzxdg-open)osenvironboolr/   
webbrowser
isinstanceGenericBrowserr   open_new_tabErrorImportErrorAttributeError)r1   is_wslhas_displaybrowserr   r   r   	_open_urlX   s   r`   r=   
active_orgc              
      sx  t  4 I d H }|jtd dd|  id4 I d H {}|jdkr| I d H }|d }|rZ|D ]&}|d |krY|d |d f  W  d   I d H  W  d   I d H  S q3|r||d	 d |d	 d fW  d   I d H  W  d   I d H  S 	 W d   I d H  W d   I d H  d
S td|j 1 I d H sw   Y  W d   I d H  d S 1 I d H sw   Y  d S )Norganization_pathAuthorizationzBearer )headersr"   organizationsr   verboseNamer   )NNz)Failed to retrieve account organization: )r'   r(   r/   r   r)   r,   r.   r-   )r=   ra   r0   r2   r3   re   orgr   r   r   _get_account_orgm   s6   

.rh   loginz*Login to Pipecat Cloud and get a new token)r   r   Fz
--headlessz-hzJSkip opening a browser window for authentication and print the URL instead)r   headlessc                    s:  t d}t }|rtd|  z| 4 I d H \}}}|d u r8td 	 W d   I d H  W d S | rTtddd td| dd td| d	dd ntt	d
| d| d| dddd | st
jdddd}| dkrtd t
 W  d   I d H  W S t| | rtddd t D ]}| I d H }|d ur nq|d u rtddd t
 W  d   I d H  W S tddd zt||I d H \}	}
td|
 d|	 d |	d u r W n ty   tddd t
  Y W  d   I d H  W S w tddd tdt dd nttjd d!d"dd#}t D ]}| I d H }|d ur9 n|td$|d%  d& q)|d u rm|  td' t
 W  d    W  d   I d H  W S |tjd(d!d" z"t||I d H \}	}
|  td|
 d|	 d |	d u r W n) ty   |  td) t
  Y W  d    W  d   I d H  W S w W d    n	1 sw   Y  td*t d+ W d   I d H  n1 I d H sw   Y  W n ty } zt| td, W Y d }~nd }~ww td- t||	 d S ).Nrg   zCurrent active org: z[Unable to connect to Pipecat Cloud API. Please check your network connection and try again.z%
To authenticate with Pipecat Cloud:
T)flushz  Visit this URL: z  Then enter this code: 
zN[bold]To authenticate with Pipecat Cloud:[/bold]

Visit this URL:
[blue][link=]z1[/link][/blue]

Then enter this code:
[cyan bold]z[/cyan bold]z$[bold]Authentication Required[/bold]blue)titleborder_stylez1
Press Enter to open the browser (or 'q' to quit) F)defaultshow_defaultqz)[yellow]Authentication cancelled[/yellow]z)Waiting for authentication to complete...zError: Authentication failedzObtaining account data...zSetting namespace to z ()zError: Account has no associated namespace. Have you completed the onboarding process? Please first sign in via the web dashboard.z)Web authentication finished successfully!zAccount details stored to z4[dim]Waiting for authentication to complete...[/dim]dotsspinner	transientz8[dim]Waiting for authentication to complete... (attempt    z)[/dim]zAuthentication failedz![dim]Obtaining account data[/dim]z{Account has no associated namespace. Have you completed the onboarding process? Please first sign in via the web dashboard.zRWeb authentication finished successfully!
[dim]Account details stored to [magenta]z[/magenta][/dim]z7Unexpected login error occured. Please contact support.z![dim]Storing credentials...[/dim])r   r/   r   r   r*   r4   r   errorprintr	   typerpromptlowerExitr`   	itertoolscountrH   rh   r-   r   r   r,   updatestopsuccessr   )rj   ra   	auth_flowr#   r%   r&   responseattemptresultaccount_nameaccount_name_verboseliveer   r   r   ri      s  


#/
5	


U

`&*l

logoutzLogout from Pipecat Cloudc                      sV   t jddd t  W d    n1 sw   Y  t jddtd dd d S )	NzRemoving user IDrv   rw   zbUser credentials for Pipecat Cloud removed. Please sign out via dashboard to fully revoke session.z[dim]Please visit:[/dim] dashboard_hostz	/sign-out)subtitle)r   r,   r   r   r   r/   r   r   r   r   r     s   
whoamiz=Display data about the current user. Also show Daily API key.c                     s  t d} zttjddddd}tj|dI d H \}}|r,t W  d    W S |	td tj
| |d	I d H \}}|rRt  t W  d    W S |d
 rZ|d s[ |	tjddd d }ztj| |d	I d H \}}W n	 ty~   Y nw |  td|d d  d|d  d|d
  d|r|ddnd g}t| W d    W d S 1 sw   Y  W d S  ty   td Y d S w )Nrg   z*[dim]Requesting current user data...[/dim]rv   rw   Try   )r   z;[dim]Requesting user namespace / organization data...[/dim])rg   r   r   verbose_namez$[dim]Fetching Daily API key...[/dim]zP[bold]User ID[/bold]
[bold]Active Organization[/bold]
[bold]Daily API Key[/bold]useruserIdrl   z [dim](z)[/dim]
apiKeyz[dim]N/A[/dim]z2Unable to obtain user data. Please contact support)r   r/   r   r   r,   r   r   r~   r   r   organizations_currentprint_errororganizations_daily_keyr-   r   r   r   r|   )rg   r   	user_datar|   accountdaily_api_keymessager   r   r   whomai!  s\   
	
&-r   r   )0r@   r   rS   rV   
contextlibr   typingr   r   r   r'   r~   logurur   rich.columnsr   	rich.liver   
rich.panelr	   pipecatcloud._utils.async_utilsr
   r   pipecatcloud._utils.auth_utilsr   !pipecatcloud._utils.console_utilsr   pipecatcloud.cli.apir   pipecatcloud.cli.configr   r   r   r   Typerauth_clir   AuthFlowrL   rU   r`   rh   commandcreate_blockingOptionri   r   r   r   r   r   r   <module>   sf   2
 
