
    @i|                          d Z ddl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Z ej                  e      Z G d d      Z G d	 d
e      Z G d de      Z G d de      Z G d d      Zy# e$ r dZY Qw xY w)z)
Notification system for cronjob events.
    N)ListOptional)settings)	send_mail)CronExecutionc                   2    e Zd ZdZdedefdZddedefdZy)	NotificationBackendz%Base class for notification backends.	executionerror_messagec                     t         )zSend failure notification.)NotImplementedError)selfr
   r   s      V/home/cursorai/projects/django-cronjob-utils/src/django_cronjob_utils/notifications.pynotify_failurez"NotificationBackend.notify_failure   s    !!    messagec                      y)z%Send success notification (optional).N )r   r
   r   s      r   notify_successz"NotificationBackend.notify_success   s    r   N )__name__
__module____qualname____doc__r   strr   r   r   r   r   r	   r	      s+    /" "c "  r   r	   c                   ,    e Zd ZdZdefdZdedefdZy)EmailBackendzEmail notification backend.configc                     |j                  dg       | _        |j                  dt        j                        | _        |j                  dd      | _        y )N
recipients
from_emailsubject_templatezCronjob Failed: {task_name})getr!   r   DEFAULT_FROM_EMAILr"   r#   r   r   s     r   __init__zEmailBackend.__init__#   sA     **\26 **\83N3NO &

+=?\ ]r   r
   r   c                 L   | j                   st        j                  d       y| j                  j	                  |j
                  |j                        }d|j
                   d|j                   d|j                   d|j                   d|j                  xs d	 d
| d|j                  xs d	 d}	 t        ||| j                  | j                   d       t        j                  d|j
                          y# t        $ r"}t        j                  d|        Y d}~yd}~ww xY w)z$Send failure notification via email.z4Email backend configured but no recipients specifiedN)	task_name	task_codez!
Cronjob Execution Failed

Task:  (z)
Execution Date: z

Started: z
Error Code: N/Az

Error Message:
z

Message:
z4

Please check the execution logs for more details.
F)subjectr   r"   recipient_listfail_silentlyz(Email notification sent for failed task z#Failed to send email notification: )r!   loggerwarningr#   formatr)   r*   execution_datestarted
error_coder   r   r"   info	Exceptionerror)r   r
   r   r-   r   es         r   r   zEmailBackend.notify_failure(   s9   NNQR''..)))) / 

 2i112 3))* +



	 !!*U+ ,   e  "
	D??## KKB9CVCVBWXY 	DLL>qcBCC	Ds   1AC8 8	D#DD#N	r   r   r   r   dictr'   r   r   r   r   r   r   r   r       s)    %^t ^
&D &Dc &Dr   r   c                   ,    e Zd ZdZdefdZdedefdZy)SlackBackendzSlack notification backend.r   c                     |j                  d      | _        |j                  dd      | _        |j                  dd      | _        | j                  st	        d      y )Nwebhook_urlchannelz	#cronjobsusernameCronbotzSlack webhook_url is required)r$   r?   r@   rA   
ValueErrorr&   s     r   r'   zSlackBackend.__init__T   sQ    !::m4zz)[9

:y9<==  r   r
   r   c                 z   t         t        j                  d       y| j                  | j                  d|j
                   dd|j
                   d|j                   ddd	d
t        |j                        dd	d|j                  j                  d      dd	d|j                  xs ddd	d|dd dd	gdgd}	 t        j                  | j                  |d      }|j                          t        j                  d|j
                          y# t         $ r"}t        j                  d|        Y d}~yd}~ww xY w)z$Send failure notification via Slack.Nz[requests library is required for Slack notifications. Install it with: pip install requestsu   ❌ Cronjob Failed: dangerTaskr+   )T)titlevalueshortDateStarted%Y-%m-%d %H:%M:%Sz
Error Coder,   zError Messagei  F)colorfields)r@   rA   textattachments
   jsontimeoutz(Slack notification sent for failed task z#Failed to send Slack notification: )requestsr0   r8   r@   rA   r)   r*   r   r3   r4   strftimer5   postr?   raise_for_statusr6   r7   )r   r
   r   payloadresponser9   s         r   r   zSlackBackend.notify_failure\   sE   LLvw ||*9+>+>*?@ &"(i6I6I5J"YM`M`Laab3cnrs"(3y7O7O3P[_`"+i6G6G6P6PQd6eptu".9M9M9VQVaef"1M$3<OZ_`		
$	D}}T%5%5GRPH%%'KKB9CVCVBWXY 	DLL>qcBCC	Ds   :AD 	D:D55D:Nr:   r   r   r   r=   r=   Q   s'    %>t >D Dc Dr   r=   c                   ,    e Zd ZdZdefdZdedefdZy)TelegramBackendzTelegram notification backend.r   c                     |j                  d      | _        |j                  d      | _        | j                  st        d      | j                  st        d      d| j                   d| _        y )N	bot_tokenchat_idzTelegram bot_token is requiredzTelegram chat_id is requiredzhttps://api.telegram.org/botz/sendMessage)r$   r_   r`   rC   api_urlr&   s     r   r'   zTelegramBackend.__init__   s]    K0zz),~~=>>||;<<5dnn5E\Rr   r
   r   c                    t         t        j                  d       yd|j                   d|j                   d|j
                   d|j                  j                  d       d|j                  xs d	 d
|dd  }| j                  |dd}	 t        j                  | j                  |d      }|j                          t        j                  d|j                          y# t        $ r"}t        j                  d|        Y d}~yd}~ww xY w)z'Send failure notification via Telegram.Nz^requests library is required for Telegram notifications. Install it with: pip install requestsu(   ❌ <b>Cronjob Failed</b>

<b>Task:</b> r+   z)
<b>Date:</b> z
<b>Started:</b> rM   z
<b>Error Code:</b> r,   z

<b>Error:</b>
i  HTML)r`   rP   
parse_moderR   rS   z+Telegram notification sent for failed task z&Failed to send Telegram notification: )rV   r0   r8   r)   r*   r3   r4   rW   r5   r`   rX   ra   rY   r6   r7   )r   r
   r   r   rZ   r[   r9   s          r   r   zTelegramBackend.notify_failure   s   LLyz%//093F3F2G H%445 6(0099:MNO P""+"6"6"?%!@ A+ET235 	 || 
	G}}T\\LH%%'KKEiFYFYEZ[\ 	GLLA!EFF	Gs   
AC 	D
(DD
Nr:   r   r   r   r]   r]   |   s)    (	St 	SG Gc Gr   r]   c                   >    e Zd ZdZd Zd ZdedefdZd
dedefdZ	y	)NotificationManagerz)Manages notifications for cronjob events.c                 2    g | _         | j                          y )N)backends_load_backends)r   s    r   r'   zNotificationManager.__init__   s    35r   c                    t        t        di       j                  di       }|j                  dg       }d|v r7	 |j                  di       }| j                  j	                  t        |             d|v r7	 |j                  di       }| j                  j	                  t        |             d	|v r8	 |j                  d	i       }| j                  j	                  t        |             yy# t        $ r"}t        j                  d|        Y d}~d}~ww xY w# t        $ r"}t        j                  d|        Y d}~d}~ww xY w# t        $ r"}t        j                  d
|        Y d}~yd}~ww xY w)z&Load configured notification backends.CRONJOB_UTILSNOTIFICATIONS
on_failureemailz$Failed to initialize Email backend: Nslackz$Failed to initialize Slack backend: telegramz'Failed to initialize Telegram backend: )getattrr   r$   rh   appendr   r7   r0   r8   r=   r]   )r   r   rm   email_configr9   slack_configtelegram_configs          r   ri   z"NotificationManager._load_backends   sT   ?B7;;ORPZZb1
j I%zz'26$$\,%?@ j I%zz'26$$\,%?@ #L"(**Z"<$$__%EF $  ICA3GHHI  ICA3GHHI  LFqcJKKLsG   6C' 46D /6E '	D0DD	E D;;E 	E.E))E.r
   r   c                     | j                   D ]  }	 |j                  ||        y# t        $ r9}t        j	                  d|j
                  j                   d|        Y d}~Vd}~ww xY w)zNotify stakeholders of failure.Notification backend 	 failed: N)rh   r   r7   r0   r8   	__class__r   )r   r
   r   backendr9   s        r   r   z"NotificationManager.notify_failure   sg    }}G_&&y-@ %  _4W5F5F5O5O4PPYZ[Y\]^^_s   &	A(/A##A(r   c                    t        t        di       j                  di       }|j                  dg       }|sy| j                  D ]L  }|j                  j
                  j                         j                  dd      |v s:	 |j                  ||       N y# t        $ r9}t        j                  d|j                  j
                   d|        Y d}~d}~ww xY w)	z/Notify stakeholders of success (if configured).rk   rl   
on_successNrz   r   rw   rx   )rq   r   r$   rh   ry   r   lowerreplacer   r7   r0   r8   )r   r
   r   r   r|   rz   r9   s          r   r   z"NotificationManager.notify_success   s    ?B7;;ORPZZb1
}}G  ))//199)RHJVc**9g> % ! cLL#89J9J9S9S8TT]^_]`!abbcs   >B	C/CCNr   )
r   r   r   r   r'   ri   r   r   r   r   r   r   r   rf   rf      s<    3L6_ _c _c c cr   rf   )r   loggingtypingr   r   django.confr   django.core.mailr   django_cronjob_utils.modelsr   rV   ImportError	getLoggerr   r0   r	   r   r=   r]   rf   r   r   r   <module>r      s     !   & 5 
		8	$	 	.D& .Db(D& (DV(G) (GV7c 7cs  Hs   A. .A87A8