o
    6Wco                     @   s<  d dl Z d dlZd dlZd dlmZmZ d dlZd dlmZm	Z	 d dl
mZmZmZ d dlmZ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 d dlZd
d Zedd Zedd Zedd Zedd Zedd Z edd Z!e	 Z"ddlm#Z# eeedZ$G dd de%Z&G dd deZ'dddZ(dS )    N)wrapspartial)
LocalProxy
LocalStack)
BaseLoaderChoiceLoaderTemplateNotFound)current_appjsonrequest_app_ctx_stack   )verifier)logger)to_dateto_timeto_timedeltac                  C   sZ   t tdr
ttdS t tdr)ttd} | D ]}t | | dr(t| | d  S qdS dS )zFind our instance of Ask, navigating Local's and possible blueprints.

    Note: This only supports returning a reference to the first instance of Ask found.
    ask
blueprintsN)hasattrr	   getattr)r   Zblueprint_name r   0D:\Flask\env\Lib\site-packages\flask_ask/core.pyfind_ask   s   



r   c                   C      t  jS N)r   r   r   r   r   r   <lambda>       r   c                   C   r   r   )r   sessionr   r   r   r   r       r   c                   C   r   r   )r   versionr   r   r   r   r   !   r   c                   C   r   r   )r   contextr   r   r   r   r   "   r   c                   C   r   r   )r   convert_errorsr   r   r   r   r   #   r   c                   C   r   r   )r   current_streamr   r   r   r   r   $   r   )models)datetime	timedeltac                   @   s  e Zd ZdZdFddZdd Zdd Zed	d
 Zedd Z	edd Z
dd Zdd Zdd Zi i i fddZddii i fddZddii i fddZddii i fddZddii i fdd Zi i i fd!d"Zed#d$ Zejd%d$ Zed&d' Zejd(d' Zed)d* Zejd+d* Zed,d- Zejd.d- Zed/d0 Zejd1d0 Zed2d3 Zejd4d3 ZdGd6d7Zd8d9 Zd:d; Zd<d= Zd>d? Zd@dA Z dBdC Z!dDdE Z"dS )HAska  The Ask object provides the central interface for interacting with the Alexa service.

    Ask object maps Alexa Requests to flask view functions and handles Alexa sessions.
    The constructor is passed a Flask App instance, and URL endpoint.
    The Flask instance allows the convienient API of endpoints and their view functions,
    so that Alexa requests may be mapped with syntax similar to a typical Flask server.
    Route provides the entry point for the skill, and must be provided if an app is given.

    Keyword Arguments:
        app {Flask object} -- App instance - created with Flask(__name__) (default: {None})
        route {str} -- entry point to which initial Alexa Requests are forwarded (default: {None})

    Nc                 C   sx   || _ || _i | _i | _i | _i | _d | _d | _d | _i | _	i | _
i | _|d ur/| | d S |d ur:| | d S d S r   )app_route_intent_view_funcs_intent_converts_intent_defaults_intent_mappings_launch_view_func_session_ended_view_func_on_session_started_callbackZ_player_request_view_funcsZ_player_mappingsZ_player_convertsinit_appinit_blueprint)selfr(   Zroute	blueprintr   r   r   __init__;   s"   zAsk.__init__c                 C   sF   | j du r	td| |_|j| j | jdgd t|jt|g|_dS )a3  Initializes Ask app by setting configuration variables, loading templates, and maps Ask route to a flask view.

        The Ask instance is given the following configuration variables by calling on Flask's configuration:

        `ASK_APPLICATION_ID`:

            Turn on application ID verification by setting this variable to an application ID or a
            list of allowed application IDs. By default, application ID verification is disabled and a
            warning is logged. This variable should be set in production to ensure
            requests are being sent by the applications you specify.
            Default: None

        `ASK_VERIFY_REQUESTS`:

            Enables or disables Alexa request verification, which ensures requests sent to your skill
            are from Amazon's Alexa service. This setting should not be disabled in production.
            It is useful for mocking JSON requests in automated tests.
            Default: True

        ASK_VERIFY_TIMESTAMP_DEBUG:

            Turn on request timestamp verification while debugging by setting this to True.
            Timestamp verification helps mitigate against replay attacks. It relies on the system clock
            being synchronized with an NTP server. This setting should not be enabled in production.
            Default: False
        Nz1route is a required argument when app is not NonePOST	view_funcmethods)r)   	TypeErrorr   add_url_rule_flask_view_funcr   jinja_loader
YamlLoader)r3   r(   r   r   r   r1   N   s
   
zAsk.init_appc                 C   s@   | j dur	td| |_|jd| jdgd tt|g|_dS )zInitialize a Flask Blueprint, similar to init_app, but without the access
        to the application config.
        :param blueprint: Flask Blueprint instance
        :return: None
        Nz*route cannot be set when using blueprints! r6   r7   )r)   r:   r   r;   r<   r   r>   r=   )r3   r4   r   r   r   r2   q   s
   
zAsk.init_blueprintc                 C      t jddS )NZASK_VERIFY_REQUESTSTr	   configgetr3   r   r   r   ask_verify_requests      zAsk.ask_verify_requestsc                 C   r@   )NZASK_VERIFY_TIMESTAMP_DEBUGFrA   rD   r   r   r   ask_verify_timestamp_debug   rF   zAsk.ask_verify_timestamp_debugc                 C   s   t jdd S )NZASK_APPLICATION_IDrA   rD   r   r   r   ask_application_id   rF   zAsk.ask_application_idc                 C   s
   || _ dS )a  Decorator to call wrapped function upon starting a session.

        @ask.on_session_started
        def new_session():
            log.info('new session started')

        Because both launch and intent requests may begin a session, this decorator is used call
        a function regardless of how the session began.

        Arguments:
            f {function} -- function to be called when session is started.
        N)r0   r3   fr   r   r   on_session_started   s   
zAsk.on_session_startedc                       | _ t| fdd}|S )a  Decorator maps a view function as the endpoint for an Alexa LaunchRequest and starts the skill.

        @ask.launch
        def launched():
            return question('Welcome to Foo')

        The wrapped function is registered as the launch view function and renders the response
        for requests to the Launch URL.
        A request to the launch URL is verified with the Alexa server before the payload is
        passed to the view function.

        Arguments:
            f {function} -- Launch view function
        c                         j | i | d S r   r<   argskwrD   r   r   wrapper      zAsk.launch.<locals>.wrapper)r.   r   r3   rJ   rR   r   rD   r   launch   s   z
Ask.launchc                    rL   )a  Decorator routes Alexa SessionEndedRequest to the wrapped view function to end the skill.

        @ask.session_ended
        def session_ended():
            return "", 200

        The wrapped function is registered as the session_ended view function
        and renders the response for requests to the end of the session.

        Arguments:
            f {function} -- session_ended view function
        c                     rM   r   rN   rO   rD   r   r   rR      rS   z"Ask.session_ended.<locals>.wrapper)r/   r   rT   r   rD   r   session_ended   s   zAsk.session_endedc                    s    fdd}|S )a  Decorator routes an Alexa IntentRequest and provides the slot parameters to the wrapped function.

        Functions decorated as an intent are registered as the view function for the Intent's URL,
        and provide the backend responses to give your Skill its functionality.

        @ask.intent('WeatherIntent', mapping={'city': 'City'})
        def weather(city):
            return statement('I predict great weather for {}'.format(city))

        Arguments:
            intent_name {str} -- Name of the intent request to be mapped to the decorated function

        Keyword Arguments:
            mapping {dict} -- Maps parameters to intent slots of a different name
                default: {}

            convert {dict} -- Converts slot values to data types before assignment to parameters
                default: {}

            default {dict} --  Provides default values for Intent slots if Alexa reuqest
                returns no corresponding slot, or a slot with an empty value
                default: {}
        c                    s@   | j < j<  j< j< t| fdd}| S )Nc                     rM   r   rN   rO   rD   r   r   rR      rS   z.Ask.intent.<locals>.decorator.<locals>.wrapperr*   r-   r+   r,   r   rJ   rR   convertdefaultintent_namemappingr3   r   r   	decorator      



zAsk.intent.<locals>.decoratorr   )r3   r\   r]   rZ   r[   r^   r   rY   r   intent   s   
z
Ask.intentoffsetZoffsetInMillisecondsc                        fdd}|S )a3  Decorator routes an AudioPlayer.PlaybackStarted Request to the wrapped function.

        Request sent when Alexa begins playing the audio stream previously sent in a Play directive.
        This lets your skill verify that playback began successfully.
        This request is also sent when Alexa resumes playback after pausing it for a voice request.

        The wrapped view function may accept parameters from the AudioPlayer Request.
        In addition to locale, requestId, timestamp, and type
        AudioPlayer Requests include:
            offsetInMilliseconds - Position in stream when request was sent.
                Not end of stream, often few ms after Play Directive offset.
                This parameter is automatically mapped to 'offset' by default

            token - token of the stream that is nearly finished.

        @ask.on_playback_started()
        def on_playback_start(token, offset):
            logger.info('stream has token {}'.format(token))
            logger.info('Current position within the stream is {} ms'.format(offset))
        c                    @   | j d< jd<  jd< jd< t| fdd}| S )NzAudioPlayer.PlaybackStartedc                     rM   r   rN   rP   kwargsrD   r   r   rR     rS   z;Ask.on_playback_started.<locals>.decorator.<locals>.wrapperrW   rX   rZ   r[   r]   r3   r   r   r^     r_   z*Ask.on_playback_started.<locals>.decoratorr   r3   r]   rZ   r[   r^   r   rf   r   on_playback_started   s   
zAsk.on_playback_startedc                    rb   )a  Decorator routes an AudioPlayer.PlaybackFinished Request to the wrapped function.

        This type of request is sent when the stream Alexa is playing comes to an end on its own.

        Note: If your skill explicitly stops the playback with the Stop directive,
        Alexa sends PlaybackStopped instead of PlaybackFinished.

        The wrapped view function may accept parameters from the AudioPlayer Request.
        In addition to locale, requestId, timestamp, and type
        AudioPlayer Requests include:
            offsetInMilliseconds - Position in stream when request was sent.
                Not end of stream, often few ms after Play Directive offset.
                This parameter is automatically mapped to 'offset' by default.

                token - token of the stream that is nearly finished.

        Audioplayer Requests do not include the stream URL, it must be accessed from current_stream.url
        c                    rc   )NzAudioPlayer.PlaybackFinishedc                     rM   r   rN   rd   rD   r   r   rR   '  rS   z<Ask.on_playback_finished.<locals>.decorator.<locals>.wrapperrW   rX   rf   r   r   r^   !  r_   z+Ask.on_playback_finished.<locals>.decoratorr   rg   r   rf   r   on_playback_finished  s   
zAsk.on_playback_finishedc                    rb   )a)  Decorator routes an AudioPlayer.PlaybackStopped Request to the wrapped function.

        Sent when Alexa stops playing an audio stream in response to one of the following:
            -AudioPlayer.Stop
            -AudioPlayer.Play with a playBehavior of REPLACE_ALL.
            -AudioPlayer.ClearQueue with a clearBehavior of CLEAR_ALL.

        This request is also sent if the user makes a voice request to Alexa,
        since this temporarily pauses the playback.
        In this case, the playback begins automatically once the voice interaction is complete.

        Note: If playback stops because the audio stream comes to an end on its own,
        Alexa sends PlaybackFinished instead of PlaybackStopped.

        The wrapped view function may accept parameters from the AudioPlayer Request.
        In addition to locale, requestId, timestamp, and type
        AudioPlayer Requests include:
            offsetInMilliseconds - Position in stream when request was sent.
                Not end of stream, often few ms after Play Directive offset.
                This parameter is automatically mapped to 'offset' by default.

                token - token of the stream that is nearly finished.

        Audioplayer Requests do not include the stream URL, it must be accessed from current_stream.url
        c                    rc   )NzAudioPlayer.PlaybackStoppedc                     rM   r   rN   rd   rD   r   r   rR   M  rS   z;Ask.on_playback_stopped.<locals>.decorator.<locals>.wrapperrW   rX   rf   r   r   r^   G  r_   z*Ask.on_playback_stopped.<locals>.decoratorr   rg   r   rf   r   on_playback_stopped-  s   
zAsk.on_playback_stoppedc                    rb   )a  Decorator routes an AudioPlayer.PlaybackNearlyFinished Request to the wrapped function.

        This AudioPlayer Request sent when the device is ready to receive a new stream.
        To progress through a playlist, respond to this request with an enqueue or play_next audio response.

        **Note** that this request is sent when Alexa is ready to receive a new stream to enqueue, and not
        necessarily when the stream's offset is near the end.
        The request may be sent by Alexa immediately after your skill sends a Play Directive.

        The wrapped view function may accept parameters from the AudioPlayer Request.
        In addition to locale, requestId, timestamp, and type
        This AudioPlayer Request includes:
        AudioPlayer Requests include:
            offsetInMilliseconds - Position in stream when request was sent.
                Not end of stream, often few ms after Play Directive offset.
                This parameter is automatically mapped to 'offset' by default.

                token - token of the stream that is nearly finished.

        Audioplayer Requests do not include the stream URL, and must be accessed from current_stream

        Example usage:

        @ask.on_playback_nearly_finished()
        def play_next_stream():
            audio().enqueue(my_next_song)

        # offsetInMilliseconds is mapped to offset by default for convenience
        @ask.on_playback_nearly_finished()
        def show_request_feedback(offset, token):
            logging.info('Nearly Finished')
            logging.info('Stream at {} ms when Playback Request sent'.format(offset))
            logging.info('Stream holds the token {}'.format(token))
            logging.info('Streaming from {}'.format(current_stream.url))

        # example of changing the default parameter mapping
        @ask.on_playback_nearly_finished(mapping={'pos': 'offsetInMilliseconds', 'stream_token': 'token'})
        def show_request_feedback(pos, stream_token):
            _infodump('Nearly Finished')
            _infodump('Stream at {} ms when Playback Request sent'.format(pos))
            _infodump('Stream holds the token {}'.format(stream_token))
        c                    rc   )Nz"AudioPlayer.PlaybackNearlyFinishedc                     rM   r   rN   rd   rD   r   r   rR     rS   zCAsk.on_playback_nearly_finished.<locals>.decorator.<locals>.wrapperrW   rX   rf   r   r   r^   ~  r_   z2Ask.on_playback_nearly_finished.<locals>.decoratorr   rg   r   rf   r   on_playback_nearly_finishedS  s   +
zAsk.on_playback_nearly_finishedc                    rb   )a  Decorator routes an AudioPlayer.PlaybackFailed Request to the wrapped function.

        This AudioPlayer Request sent when Alexa encounters an error when attempting to play a stream.

        The wrapped view function may accept parameters from the AudioPlayer Request.
        In addition to locale, requestId, timestamp, and type
        
        PlayBackFailed Requests include:
            error - Contains error info under parameters type and message

            token - represents the stream that failed to play.

            currentPlaybackState - Details about the playback activity occurring at the time of the error
                Contains the following parameters:

                    token - represents the audio stream currently playing when the error occurred.
                        Note that this may be different from the value of the request.token property.

                    offsetInMilliseconds - Position in stream when request was sent.
                        Not end of stream, often few ms after Play Directive offset.
                        This parameter is automatically mapped to 'offset' by default.

                    playerActivity - player state when the error occurred
        c                    rc   )NzAudioPlayer.PlaybackFailedc                     rM   r   rN   rd   rD   r   r   rR     rS   z:Ask.on_playback_failed.<locals>.decorator.<locals>.wrapperrW   rX   rf   r   r   r^     r_   z)Ask.on_playback_failed.<locals>.decoratorr   rg   r   rf   r   on_playback_failed  s   
zAsk.on_playback_failedc                 C      t tjdd S )N_ask_requestr   r   toprD   r   r   r   r     rF   zAsk.requestc                 C      |t j_d S r   )r   rp   rn   r3   valuer   r   r   r        c                 C      t tjdt S )N_ask_sessionr   r   rp   r#   _FieldrD   r   r   r   r        zAsk.sessionc                 C   rq   r   )r   rp   rv   rr   r   r   r   r     rt   c                 C   rm   )N_ask_versionro   rD   r   r   r   r     rF   zAsk.versionc                 C   rq   r   )r   rp   rz   rr   r   r   r   r     rt   c                 C   rm   )N_ask_contextro   rD   r   r   r   r      rF   zAsk.contextc                 C   rq   r   )r   rp   r{   rr   r   r   r   r      rt   c                 C   rm   )N_ask_convert_errorsro   rD   r   r   r   r!     rF   zAsk.convert_errorsc                 C   rq   r   )r   rp   r|   rr   r   r   r   r!     rt   c                 C   ru   )N_ask_current_streamrw   rD   r   r   r   r"     ry   zAsk.current_streamc                 C   rq   r   )r   rp   r}   rr   r   r   r   r"     rt   Tc           	      C   s   t j}t|}|r^t jd }t jd }t|}t||| t	|d d }t
jr/| jr4t| z
|d d d }W n tyQ   |d d	 d d }Y nw | jd ur^t|| j |S )
NZSignaturecertchainurl	Signaturer   	timestampr   ZapplicationZapplicationIdr    System)flask_requestdatar
   loadsheadersr   Zload_certificateZverify_signature	aniso8601Zparse_datetimer	   debugrG   Zverify_timestampKeyErrorrH   Zverify_application_id)	r3   verifyZraw_bodyZalexa_request_payloadZcert_url	signaturecertr   Zapplication_idr   r   r   _alexa_request  s0   





zAsk._alexa_requestc                 C   sX   t  }|j| jj |j|   |  }|d kr"|j| || _ttj d S r   )r#   rx   __dict__updater"   _from_directive_from_context_dbgdump)r3   Zfresh_streamZcontext_infor   r   r   _update_stream  s   zAsk._update_streamc                 C   s   t | jdi S )NAudioPlayer)r   r    rD   r   r   r   r     s   zAsk._from_contextc                 C   s,   t j}|r| jjrd| jjjv ri S |S i S )NZPauseIntent)_stream_bufferrp   r   r`   name)r3   from_bufferr   r   r   r   	  s   zAsk._from_directivec                 O   sH  | j | jd}t| t|}|j| _|j| _t|dt | _t|d| j	| _	| j	s1t | _	| j	j
s;t | j	_
|   z| j	jrM| jd urM|   W n	 tyW   Y nw d }| jj}|dkrj| jrj|  }n(|dkrv| jrv|  }n|dkr| jr| | jj }nd|v r| | jj }|d urt|tjr| S |S dS )	N)r   r    r   ZLaunchRequestZSessionEndedRequestZIntentRequestr   )r?   i  )r   rE   r   r#   rx   r   r   r   r    r   
attributesr   newr0   AttributeErrortyper.   r/   r*   _map_intent_to_view_funcr`   _map_player_request_to_func
isinstanceZ	_ResponseZrender_response)r3   rP   re   Zask_payloadrequest_bodyresultZrequest_typer   r   r   r<     sD   



zAsk._flask_view_funcc                 C   s:   | j |j }t|}|j}| |j|}t|g|R  S )z7Provides appropiate parameters to the intent functions.)r*   r   inspect
getargspecrP   _map_params_to_view_argsr   )r3   r`   r8   argspec	arg_names
arg_valuesr   r   r   r   <  s
   
zAsk._map_intent_to_view_funcc                 C   s>   | j |dd }t|}|j}| ||}t|g|R  S )z=Provides appropriate parameters to the on_playback functions.c                   S   s   d S r   r   r   r   r   r   r   H  s    z1Ask._map_player_request_to_func.<locals>.<lambda>)r*   rC   r   r   rP   r   r   )r3   Zplayer_request_typer8   r   r   r   r   r   r   r   E  s
   
zAsk._map_player_request_to_funcc                 C   sn  g }| j |}| j|}| j|}i }i }t| jdd }	|	d ur@|	jd ur?|	j D ]}
t|	j|
}t|dd ||j< q-n| jD ]}t| j|d ||< qC|D ]`}|||}||}|d u sf|dkrz||v ry|| }t	|t
jrw| }|}n2||v r|| }|tv r|}t| }n|}z||}W n ty } z
|||< W Y d }~nd }~ww || qQ|| _|S )Nr`   rs   r?   )r+   rC   r,   r-   r   r   slotskeysr   r   collectionsCallable_converters	Exceptionappendr!   )r3   Z	view_namer   r   rZ   r[   r]   r!   Zrequest_datar`   Zslot_keyZslot_object
param_nameZarg_nameZparam_or_slot	arg_valuedefault_valueZshorthand_or_functionZ	shorthandZconvert_funcer   r   r   r   P  sP   



zAsk._map_params_to_view_argsNNN)T)#__name__
__module____qualname____doc__r5   r1   r2   propertyrE   rG   rH   rK   rU   rV   r`   rh   ri   rj   rk   rl   r   setterr   r   r    r!   r"   r   r   r   r   r<   r   r   r   r   r   r   r   r'   ,   sh    
#


$!&7%












+	r'   c                   @   s&   e Zd Zd	ddZdd Zdd ZdS )
r>   templates.yamlc                 C   s&   |j tjj | | _i | _|   d S r   )	root_pathospathsepr]   _reload_mapping)r3   r(   r   r   r   r   r5     s   zYamlLoader.__init__c                 C   sb   t j| jr/t j| j| _t| j}t| | _	W d    d S 1 s(w   Y  d S d S r   )
r   r   isfilegetmtime
last_mtimeopenyamlZ	safe_loadreadr]   rI   r   r   r   r     s   "zYamlLoader._reload_mappingc                    s`   t j js	dS  jt j jkr    jv r, j d  fddfS tS )Nr   c                      s    j kS r   )r]   rC   r   r3   sourcetemplater   r   r     s    z'YamlLoader.get_source.<locals>.<lambda>)r   r   r   r   r   r   r]   r   )r3   environmentr   r   r   r   
get_source  s   

zYamlLoader.get_sourceN)r   )r   r   r   r5   r   r   r   r   r   r   r>   ~  s    
r>      c                 C   s    t j| |||d}t| d S )N)indentr[   cls)r
   dumpsr   r   )objr   r[   r   msgr   r   r   r     s   r   )r   NN))r   r   r   	functoolsr   r   r   Zwerkzeug.localr   r   Zjinja2r   r   r   Zflaskr	   r
   r   r   r   r?   r   r   rZ   r   r   r   r   r   r   r   r    r!   r"   r   r#   r   objectr'   r>   r   r   r   r   r   <module>   s:        V