o
    Tg                     @   s   d dl Z d dlZd dlZd dlmZmZmZmZ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 ed	ZG d
d dZdS )    N)ListDictOptionalAnyUnion)Session)Notification)DeviceTokenService)settings)service_account)AuthorizedSession	adimsayarc                   @   s   e Zd Zedd Ze		ddedededed	eee	f d
ede
fddZe	ddee deded	eee	f de
f
ddZe		ddedededed	eee	f d
edefddZdS )PushNotificationServicec                  C   s*   t jjdtjtjtjdddgd} | jS )uD   Firebase 서비스 계정으로 액세스 토큰을 생성합니다.r   z#https://oauth2.googleapis.com/token)type
project_idprivate_keyZclient_emailZ	token_uriz2https://www.googleapis.com/auth/firebase.messaging)scopes)r   ZCredentialsZfrom_service_account_infor
   FIREBASE_PROJECT_IDFIREBASE_PRIVATE_KEYFIREBASE_CLIENT_EMAILtoken)credentials r   ./app/app/services/push_notification_service.py_get_access_token   s   
z)PushNotificationService._get_access_tokenNgeneraldbuser_idtitlemessagedatanotification_typereturnc           
   
   C   s   z:t | |}|std| d t| ||||| W dS dd |D }t||||}t| ||||| |W S  tyW }	 ztdt	|	  W Y d}	~	dS d}	~	ww )	u{   
        Firebase를 통해 사용자에게 푸시 알림을 보내고, 동시에 DB에 알림을 저장합니다.
           사용자 ID u<   에 대한 활성화된 디바이스 토큰이 없습니다.Tc                 S   s   g | ]}|j qS r   )Zdevice_token).0r   r   r   r   
<listcomp>7   s    z=PushNotificationService.send_push_to_user.<locals>.<listcomp>u   푸시 알림 전송 오류: NF)
r	   Zget_user_device_tokensloggerinfor   _save_notification_to_db_send_firebase_push	Exceptionerrorstr)
r   r   r   r   r    r!   device_tokensZtoken_valuessuccesser   r   r   send_push_to_user   s&   z)PushNotificationService.send_push_to_usertokensc              
   C   s>  z| st d W dS t }tj}d| d}d| dd}d}| D ]K}	d	|	||d
|p/i dddidddddiiidi}
tj|||
d}|jdkr_|d7 }t 	d|	dd  d q$t d|	dd  d|j
  q$t 	d| dt|   |dkW S  ty } zt dt|  W Y d}~dS d}~ww )uA   FCM HTTP v1 API를 사용하여 푸시 알림을 전송합니다.u/   푸시 알림을 보낼 토큰이 없습니다.Fz'https://fcm.googleapis.com/v1/projects/z/messages:sendzBearer zapplication/json)AuthorizationzContent-Typer   r   )r   r   highZsounddefault)prioritynotificationpayloadZaps)r   r6   r    ZandroidZapns)headersjson      u   푸시 알림 전송 성공: N
   z...u   푸시 알림 전송 실패: z... - u$   푸시 알림 전송 결과: 성공 /u1   Firebase 푸시 알림 전송 중 오류 발생: )r&   warningr   r   r
   r   requestspoststatus_coder'   textlenr*   r+   r,   )r1   r   r   r    access_tokenr   urlr8   Zsuccess_countr   r7   responser/   r   r   r   r)   E   sT   

"
z+PushNotificationService._send_firebase_pushc           	   
   C   s   z*ddl m} |j| |||||d}|   | | td| d|j d |W S  tyE } z| 	  t
dt|   d}~ww )	uB   
        알림을 데이터베이스에 저장합니다.
        r   )NotificationService)r   r   
notif_typer   r   r    r#   u7   에 대한 알림이 DB에 저장되었습니다. (ID: )u   알림 DB 저장 오류: N)!app.services.notification_servicerG   create_notificationcommitrefreshr&   r'   idr*   rollbackr+   r,   )	r   r   r   r   r    r!   rG   r6   r/   r   r   r   r(      s(   

z0PushNotificationService._save_notification_to_db)Nr   )N)__name__
__module____qualname__staticmethodr   r   intr,   r   r   boolr0   r   r)   r   r(   r   r   r   r   r      sh    

&
E
r   )r9   loggingr?   typingr   r   r   r   r   sqlalchemy.ormr   Zapp.models.notificationr   Z!app.services.device_token_servicer	   app.core.configr
   Zgoogle.oauth2r   Zgoogle.auth.transport.requestsr   	getLoggerr&   r   r   r   r   r   <module>   s    
