U
    ùüÌ`AO  ã                   @   sh   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 ddlm	Z	m
Z
mZmZmZ G dd„ deƒZdS )é    N)ÚHTTPAdapter)ÚRetryé   )ÚAuthenticationErrorÚInvalidDataErrorÚFCMErrorÚFCMServerErrorÚFCMNotRegisteredErrorc                   @   sÚ   e Zd ZdZdZdZdZdZdZdZ	dZ
d'd
d„Zdd„ Zdd„ Zdd„ Zd	d	d	d	d	d	d	d	dd	d	ddd	d	d	d	d	d	d	d	d	d	dd	i fdd„Zdd„ Zd(dd„Zdd„ Zg fdd„Zdd„ Zdd „ Zd!d"„ Zd#d$„ Zd%d&„ Zd	S ))ÚBaseAPIa  
    Base class for the pyfcm API wrapper for FCM

    Attributes:
        api_key (str): Firebase API key
        proxy_dict (dict): use proxy (keys: `http`, `https`)
        env (str): for example "app_engine"
        json_encoder
        adapter: requests.adapters.HTTPAdapter()
    zapplication/jsonz#https://fcm.googleapis.com/fcm/sendz$https://iid.googleapis.com/iid/info/iè  ZnormalÚhighé   Nc                 C   s4  |r|| _ n$t dd ¡r(t dd ¡| _ ntdƒ‚d | _t ¡ | _tdddgtj	t
dgƒB d�}| j d|prt|d	�¡ | j d
|pŠt|d	�¡ | jj |  ¡ ¡ | j | jt| jd	�¡ |rêt|tƒrêd|ksÖd|krê|| _| jj |¡ g | _|dk�r*zddlm} | ¡  W n tk
�r(   Y nX || _d S )NZFCM_API_KEYz;Please provide the api_key in the google-services.json filer   iö  i÷  ZPOST)Zbackoff_factorZstatus_forcelistZallowed_methodszhttp://)Zmax_retrieszhttps://ÚhttpÚhttpsZ
app_enginer   )Ú	appengine)Ú_FCM_API_KEYÚosÚgetenvr   ZFCM_REQ_PROXIESÚrequestsZSessionÚrequests_sessionr   ZDEFAULT_ALLOWED_METHODSÚ	frozensetZmountr   ÚheadersÚupdateÚrequest_headersÚINFO_END_POINTÚINFO_RETRIESÚ
isinstanceÚdictZproxiesÚsend_request_responsesZrequests_toolbelt.adaptersr   ZmonkeypatchÚModuleNotFoundErrorÚjson_encoder)ÚselfZapi_keyZ
proxy_dictÚenvr   ZadapterZretriesr   © r"   úm/var/www/html/staging.mfahmagazine.net/magazine_api/magazine_env/lib/python3.8/site-packages/pyfcm/baseapi.pyÚ__init__-   s2    

ÿ
zBaseAPI.__init__c                 C   s   | j d| j dœS )zˆ
        Generates request headers including Content-Type and Authorization

        Returns:
            dict: request headers
        zkey=)zContent-TypeZAuthorization)ÚCONTENT_TYPEr   ©r    r"   r"   r#   r   L   s    þzBaseAPI.request_headersc                 c   sR   z| W n t k
r    t}Y nX |dt|ƒ| jƒD ]}|||| j … V  q4dS )a  
        Splits registration ids in several lists of max 1000 registration ids per list

        Args:
            registration_ids (list): FCM device registration ID

        Yields:
            generator: list including lists with registration ids
        r   N)Ú	NameErrorÚrangeÚlenÚFCM_MAX_RECIPIENTS)r    Úregistration_idsÚxrangeÚir"   r"   r#   Úregistration_id_chunksX   s    

zBaseAPI.registration_id_chunksc                 C   s   t j|dd| jdd� d¡S )zÃ
        Standardized json.dumps function with separators and sorted keys set

        Args:
            data (dict or list): data to be dumped

        Returns:
            string: json
        )ú,ú:TF)Ú
separatorsÚ	sort_keysÚclsÚensure_asciiÚutf8)ÚjsonÚdumpsr   Úencode)r    Údatar"   r"   r#   Ú
json_dumpsk   s    
ûúzBaseAPI.json_dumpsFc                 K   s\  t ƒ }|r,t|ƒdkr ||d< n|d |d< |r:||d< n|rJd| |d< |rZ| j|d< n
| j|d< |	rp|	|d< |r|||d	< |
d
k	r t|
tƒr˜|
|d< ntdƒ‚|r¬||d< |r¸||d< |rØt|t ƒrÐ||d< ntdƒ‚i |d< |rð||d d< |�r||d d< n:|�r||d d< |�r>t|tƒ�r6||d d< ntdƒ‚|�rR||d d< n:|�rd||d d< |�rŒt|tƒ�r„||d d< ntdƒ‚|�rž||d d< |�r¸t|tƒ�r¸||d< |�rÊ||d d< t|tƒ�rì|dk�rì||d d< |�rþ||d d< |�r||d d < |�r"||d d!< |�r2| 	|¡ |�rF|d  	|¡ |�rR|d= |  
|¡S )"aä  
        Parses parameters of FCMNotification's methods to FCM nested json

        Args:
            registration_ids (list, optional): FCM device registration IDs
            topic_name (str, optional): Name of the topic to deliver messages to
            message_body (str, optional): Message string to display in the notification tray
            message_title (str, optional): Message title to display in the notification tray
            message_icon (str, optional): Icon that apperas next to the notification
            sound (str, optional): The sound file name to play. Specify "Default" for device default sound.
            condition (str, optiona): Topic condition to deliver messages to
            collapse_key (str, optional): Identifier for a group of messages
                that can be collapsed so that only the last message gets sent
                when delivery can be resumed. Defaults to `None`.
            delay_while_idle (bool, optional): deprecated
            time_to_live (int, optional): How long (in seconds) the message
                should be kept in FCM storage if the device is offline. The
                maximum time to live supported is 4 weeks. Defaults to `None`
                which uses the FCM default of 4 weeks.
            restricted_package_name (str, optional): Name of package
            low_priority (bool, optional): Whether to send notification with
                the low priority flag. Defaults to `False`.
            dry_run (bool, optional): If `True` no message will be sent but request will be tested.
            data_message (dict, optional): Custom key-value pairs
            click_action (str, optional): Action associated with a user click on the notification
            badge (str, optional): Badge of notification
            color (str, optional): Color of the icon
            tag (str, optional): Group notification by tag
            body_loc_key (str, optional): Indicates the key to the body string for localization
            body_loc_args (list, optional): Indicates the string value to replace format
                specifiers in body string for localization
            title_loc_key (str, optional): Indicates the key to the title string for localization
            title_loc_args (list, optional): Indicates the string value to replace format
                specifiers in title string for localization
            content_available (bool, optional): Inactive client app is awoken
            remove_notification (bool, optional): Only send a data message
            android_channel_id (str, optional): Starting in Android 8.0 (API level 26),
                all notifications must be assigned to a channel. For each channel, you can set the
                visual and auditory behavior that is applied to all notifications in that channel.
                Then, users can change these settings and decide which notification channels from
                your app should be intrusive or visible at all.
            extra_notification_kwargs (dict, optional): More notification keyword arguments
            **extra_kwargs (dict, optional): More keyword arguments

        Returns:
            string: json

        Raises:
            InvalidDataError: parameters do have the wrong type or format
        r   r+   r   ÚtoÚ	conditionz
/topics/%sÚpriorityÚdelay_while_idleÚcollapse_keyNÚtime_to_livez'Provided time_to_live is not an integerÚrestricted_package_nameÚdry_runr9   z,Provided data_message is in the wrong formatZnotificationZiconÚbodyÚbody_loc_keyÚbody_loc_argsz body_loc_args should be an arrayÚtitleÚtitle_loc_keyÚtitle_loc_argsz!title_loc_args should be an arrayÚandroid_channel_idÚcontent_availableÚclick_actionÚbadgeÚcolorÚtagÚsound)r   r)   ÚFCM_LOW_PRIORITYÚFCM_HIGH_PRIORITYr   Úintr   ÚlistÚboolr   r:   )r    r+   Ú
topic_nameZmessage_bodyZmessage_titleZmessage_iconrO   r<   r?   r>   r@   rA   Zlow_priorityrB   Zdata_messagerK   rL   rM   rN   rD   rE   rG   rH   rJ   Zremove_notificationrI   Zextra_notification_kwargsZextra_kwargsZfcm_payloadr"   r"   r#   Úparse_payload}   sˆ    N







zBaseAPI.parse_payloadc                 C   sX   | j j| j||d�}d|jkrTt|jd ƒdkrTt|jd ƒ}t |¡ |  ||¡S |S )N)r9   ÚtimeoutzRetry-Afterr   )r   ÚpostÚFCM_END_POINTr   rR   ÚtimeÚsleepÚ
do_request)r    ÚpayloadrW   ÚresponseZ
sleep_timer"   r"   r#   r\   /  s    
zBaseAPI.do_requestc                 C   s,   g | _ |D ]}|  ||¡}| j  |¡ q
d S )N)r   r\   Úappend)r    ÚpayloadsrW   r]   r^   r"   r"   r#   Úsend_request7  s    zBaseAPI.send_requestc                 C   s   | j j| j| ddid�S )zØ
        Makes a request for registration info and returns the response object

        Args:
            registration_id: id to be checked

        Returns:
            response of registration info request
        ÚdetailsÚtrue)Úparams)r   Úgetr   )r    Úregistration_idr"   r"   r#   Úregistration_info_request=  s    
þz!BaseAPI.registration_info_requestc                 C   s0   g }|D ]"}|   |¡}|jdkr| |¡ q|S )zØ
        Checks registration ids and excludes inactive ids

        Args:
            registration_ids (list, optional): list of ids to be cleaned

        Returns:
            list: cleaned registration ids
        éÈ   )rg   Ústatus_coder_   )r    r+   Zvalid_registration_idsrf   rb   r"   r"   r#   Úclean_registration_idsL  s    


zBaseAPI.clean_registration_idsc                 C   s    |   |¡}|jdkr| ¡ S dS )a  
        Returns details related to a registration id if it exists otherwise return None

        Args:
            registration_id: id to be checked

        Returns:
            dict: info about registration id
            None: if id doesn't exist
        rh   N)rg   ri   r6   )r    rf   r^   r"   r"   r#   Úget_registration_id_info]  s    

z BaseAPI.get_registration_id_infoc                 C   sZ   d}d| |dœ}| j j||d�}|jdkr0dS |jdkrP| ¡ }t|d ƒ‚ntƒ ‚d	S )
a„  
        Subscribes a list of registration ids to a topic

        Args:
            registration_ids (list): ids to be subscribed
            topic_name (str): name of topic

        Returns:
            True: if operation succeeded

        Raises:
            InvalidDataError: data sent to server was incorrectly formatted
            FCMError: an error occured on the server
        z*https://iid.googleapis.com/iid/v1:batchAddú/topics/©r;   Zregistration_tokens©r6   rh   Té�  ÚerrorN©r   rX   ri   r6   r   r   ©r    r+   rU   Úurlr]   r^   rp   r"   r"   r#   Ú#subscribe_registration_ids_to_topicm  s    þ

z+BaseAPI.subscribe_registration_ids_to_topicc                 C   sZ   d}d| |dœ}| j j||d�}|jdkr0dS |jdkrP| ¡ }t|d ƒ‚ntƒ ‚d	S )
aŠ  
        Unsubscribes a list of registration ids from a topic

        Args:
            registration_ids (list): ids to be unsubscribed
            topic_name (str): name of topic

        Returns:
            True: if operation succeeded

        Raises:
            InvalidDataError: data sent to server was incorrectly formatted
            FCMError: an error occured on the server
        z-https://iid.googleapis.com/iid/v1:batchRemoverl   rm   rn   rh   Tro   rp   Nrq   rr   r"   r"   r#   Ú'unsubscribe_registration_ids_from_topicŠ  s    þ

z/BaseAPI.unsubscribe_registration_ids_from_topicc           
      C   sT  g dddg ddœ}| j D �]4}|jdk�rd|jkrPt|jd ƒdkrPtdƒ‚n°| ¡ }| dd¡}| dd¡}| d	d¡}| d
d¡}| dg ¡}| dd¡}	|	r¨d}|rº|d  |¡ |d  |7  < |d	  |7  < |d
  |7  < |d  |¡ |	|d< q|jdk�rt	dƒ‚q|jdk�r0t
|jƒ‚q|jdk�rFtdƒ‚qtdƒ‚q|S )a  
        Parses the json response sent back by the server and tries to get out the important return variables

        Returns:
            dict: multicast_ids (list), success (int), failure (int), canonical_ids (int),
                results (list) and optional topic_message_id (str but None by default)

        Raises:
            FCMServerError: FCM is temporary not available
            AuthenticationError: error authenticating the sender account
            InvalidDataError: data passed to FCM was incorrecly structured
        r   N)Úmulticast_idsÚsuccessÚfailureÚcanonical_idsÚresultsÚtopic_message_idrh   zcontent-lengthz2FCM server connection error, the response is emptyÚmulticast_idrw   rx   ry   rz   Ú
message_idr   rv   r{   i‘  z4There was an error authenticating the sender accountro   i”  zToken not registeredz%FCM server is temporarily unavailable)r   ri   r   rR   r   r6   re   r_   Úextendr   r   Útextr	   )
r    Zresponse_dictr^   Zparsed_responser|   rw   rx   ry   rz   r}   r"   r"   r#   Úparse_responses§  sF    ú	




zBaseAPI.parse_responsesc                    sJ   dd l }ddlm} ‡ fdd„|D ƒ}| ¡  |ˆ jˆ  ¡ ||d�¡}|S )Nr   r   )Úfetch_tasksc                    s   g | ]}ˆ j f |Ž‘qS r"   )rV   )Ú.0rd   r&   r"   r#   Ú
<listcomp>ã  s     z.BaseAPI.send_async_request.<locals>.<listcomp>)Z	end_pointr   r`   rW   )ÚasyncioZ	async_fcmr�   Znew_event_loopZrun_until_completerY   r   )r    Zparams_listrW   r„   r�   r`   Z	responsesr"   r&   r#   Úsend_async_requestÞ  s
     zBaseAPI.send_async_request)NNNNN)NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r%   rY   r   r*   rP   rQ   r   r$   r   r.   r:   rV   r\   ra   rg   rj   rk   rt   ru   r€   r…   r"   r"   r"   r#   r
      sb   
æ
 3
7r
   )r6   r   rZ   r   Zrequests.adaptersr   Zurllib3r   Úerrorsr   r   r   r   r	   Úobjectr
   r"   r"   r"   r#   Ú<module>   s   