o
    f8V                     @   sJ  d Z zddlmZ W n ey   ddlmZ Y nw ddlmZ ddlZddl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mZ dd	lmZ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%m&Z& dZ'dZ(dZ)dZ*dZ+e'edfe(edfe)edfe*edfe+edffZ,e'edfe(edfe)edfe*edfe+edffZ-d ed!fd"ed#fd$ed%fd&ed'fd(ed)fd*ed+fd,ed-fd.ed/fd0ed1fg	Z.d2d3 Z/d4d5 Z0G d6d7 d7ej1Z2G d8d9 d9ej1Z3G d:d; d;ej1Z4G d<d= d=ej1Z5G d>d? d?ej1Z6G d@dA dAej1Z7dS )BzDatabase models.    )available_timezones)	timedeltaN)current_app	schedules)FormatExceptionMissingFieldExceptionWrongArgumentExceptionget_description)settings)MultipleObjectsReturnedValidationError)MaxValueValidatorMinValueValidator)models)gettext_lazy   )	querysets
validators)clocked)TzAwareCrontab
make_awarenowdayshoursminutessecondsmicrosecondsDaysHoursMinutesSecondsMicrosecondsDayHourMinuteSecondMicroseconddawn_astronomicalzAstronomical dawn
dawn_civilz
Civil dawndawn_nauticalzNautical dawndusk_astronomicalzAstronomical dusk
dusk_civilz
Civil duskdusk_nauticalzNautical dusk
solar_noonz
Solar noonsunriseSunrisesunsetSunsetc                 C   s   | r
t | ddpdS )z"Representation of cron expression.  *)strreplace)field r9   L/var/www/html/venv/lib/python3.10/site-packages/django_celery_beat/models.pycronexp;   s   r;   c                  C   s<   z
t tdtj } W n
 ty   Y dS w | t v r| S dS )zReturn timezone string from Django settings ``CELERY_TIMEZONE`` variable.

    If is not defined or is not a valid timezone, return ``"UTC"`` instead.
    z%s_TIMEZONEUTC)getattrr
   r   	namespaceAttributeErrorr   )CELERY_TIMEZONEr9   r9   r:    crontab_schedule_celery_timezone@   s   

rA   c                   @   s   e Zd ZdZejdeededdZej	ddeded	e
d
edgdZej	ddedede
dedgdZG dd dZedd Zedd Zdd ZdS )SolarSchedulezSchedule following astronomical patterns.

    Example: to run every sunrise in New York City:

    >>> event='sunrise', latitude=40.7128, longitude=74.0060
       zSolar Eventz/The type of solar event when the job should run
max_lengthchoicesverbose_name	help_text	      Latitudez4Run the task when the event happens at this latitudeiZ   )
max_digitsdecimal_placesrG   rH   r   	Longitudez5Run the task when the event happens at this longitudeiL   c                   @   s(   e Zd ZdZedZedZdZdZdS )zSolarSchedule.MetaTable information.zsolar eventzsolar eventseventlatitude	longitudeN)	__name__
__module____qualname____doc___rG   verbose_name_pluralorderingunique_togetherr9   r9   r9   r:   Metai   s    r^   c                 C   s   t j| j| j| jdd dS )Nc                   S   
   t t S Nr   r9   r9   r9   r:   <lambda>v      
 z(SolarSchedule.schedule.<locals>.<lambda>nowfun)r   solarrS   rT   rU   selfr9   r9   r:   scheduleq   s
   zSolarSchedule.schedulec                 C   sJ   |j |j|jd}z
| jjdi |W S  | jy$   | di | Y S w )NrR   r9   )rS   latlonobjectsgetDoesNotExistclsrh   specr9   r9   r:   from_schedulex   s   zSolarSchedule.from_schedulec                 C   s   d |  | j| jS )Nz{} ({}, {}))formatget_event_displayrT   rU   rf   r9   r9   r:   __str__   s
   zSolarSchedule.__str__N)rV   rW   rX   rY   r   	CharFieldSOLAR_SCHEDULESrZ   rS   DecimalFieldr   r   rT   rU   r^   propertyrh   classmethodrq   rt   r9   r9   r9   r:   rB   O   s2    

rB   c                   @   s   e Zd ZdZeZeZeZeZeZe	Z	e
jdedededgdZe
jde	eded	d
ZG dd dZedd ZeefddZdd Zedd ZdS )IntervalSchedulezpSchedule executing on a regular interval.

    Example: execute every 2 days:

    >>> every=2, period=DAYS
    FzNumber of Periodsz@Number of interval periods to wait before running the task againr   )nullrG   rH   r   rC   zInterval Periodz4The type of period between task runs (Example: days)rD   c                   @   s(   e Zd ZdZedZedZddgZdS )zIntervalSchedule.MetarQ   interval	intervalsperiodeveryNrV   rW   rX   rY   rZ   rG   r[   r\   r9   r9   r9   r:   r^      
    r^   c                 C   s$   t jtdi | j| jidd dS )Nc                   S   r_   r`   r   r9   r9   r9   r:   ra      rb   z+IntervalSchedule.schedule.<locals>.<lambda>rc   r9   )r   rh   r   r~   r   rf   r9   r9   r:   rh      s   zIntervalSchedule.schedulec                 C   sh   t |j d}z	| jj||dW S  | jy!   | ||d Y S  ty3   | jj||d  Y S w )Nr   )r   r~   )	max	run_everytotal_secondsrk   rl   rm   r   filterfirst)ro   rh   r~   r   r9   r9   r:   rq      s   zIntervalSchedule.from_schedulec                 C   sv   d }| j dkr tD ]\}}|| jkr| } nq	td|S tD ]\}}|| jkr1| } nq"td| j |S )Nr   zevery {}zevery {} {})r   SINGULAR_PERIODSr~   lowerrZ   rr   PERIOD_CHOICES)rg   readable_periodr~   _readable_periodr9   r9   r:   rt      s   


zIntervalSchedule.__str__c                 C   s   | j d d S )N)r~   rf   r9   r9   r:   period_singular   s   z IntervalSchedule.period_singularN)rV   rW   rX   rY   DAYSHOURSMINUTESSECONDSMICROSECONDSr   r   IntegerFieldrZ   r   r   ru   r~   r^   rx   rh   ry   rq   rt   r   r9   r9   r9   r:   rz      s6    
	rz   c                   @   sT   e Zd ZdZejededdZG dd dZdd Z	e
d	d
 Zedd ZdS )ClockedSchedulezclocked schedule.z
Clock TimezRun the task at clocked time)rG   rH   c                   @   s&   e Zd ZdZedZedZdgZdS )zClockedSchedule.MetarQ   r   clocked_timeNr   r9   r9   r9   r:   r^      s
    
r^   c                 C   s   t | j S r`   )r   r   rf   r9   r9   r:   rt      s   zClockedSchedule.__str__c                 C   s   t | jd}|S )N)r   )r   r   )rg   cr9   r9   r:   rh      s   zClockedSchedule.schedulec                 C   sh   d|j i}z
| jjdi |W S  | jy    | di | Y S  ty3   | jjdi |  Y S w )Nr   r9   )r   rk   rl   rm   r   r   r   rn   r9   r9   r:   rq      s   
zClockedSchedule.from_scheduleN)rV   rW   rX   rY   r   DateTimeFieldrZ   r   r^   rt   rx   rh   ry   rq   r9   r9   r9   r:   r      s    
r   c                   @   s  e Zd ZdZejddededejgdZ	ejddeded	ej
gdZejd
dededejgdZejddededejgdZejddededejgdZejedededdZG dd dZedd Zdd Zedd Zedd Zd S )!CrontabSchedulezTimezone Aware Crontab-like schedule.

    Example:  Run every hour at 0 minutes for days of month 10-15:

    >>> minute="0", hour="*", day_of_week="*",
    ... day_of_month="10-15", month_of_year="*"
       r5   z	Minute(s)z9Cron Minutes to Run. Use "*" for "all". (Example: "0,30"))rE   defaultrG   rH   r   `   zHour(s)z7Cron Hours to Run. Use "*" for "all". (Example: "8,20")|   zDay(s) Of The MonthzCCron Days Of The Month to Run. Use "*" for "all". (Example: "1,15")@   zMonth(s) Of The YearzKCron Months (1-12) Of The Year to Run. Use "*" for "all". (Example: "1,12")zDay(s) Of The Weekz`Cron Days Of The Week to Run. Use "*" for "all", Sunday is 0 or 7, Monday is 1. (Example: "0,5")FzCron Timezonez5Timezone to Run the Cron Schedule on. Default is UTC.)r   use_pytzrG   rH   c                   @   s(   e Zd ZdZedZedZg dZdS )zCrontabSchedule.MetarQ   crontabcrontabs)month_of_yearday_of_monthday_of_weekhourminutetimezoneNr   r9   r9   r9   r:   r^   6  r   r^   c              
   C   s   zt j| j| j| j| j| jd}tddd |jD }W n t	y,   t| j}Y nw d
t| jt| jt| jt| j|}zt|}W n tttfy^   | dt| j  Y S w | dt| j S )Nr   r   r   r   r   ,c                 s   s    | ]}t |V  qd S r`   )r6   ).0dayr9   r9   r:   	<genexpr>H  s    z1CrontabSchedule.human_readable.<locals>.<genexpr>z{} {} {} {} {}r3   )r   r   r   r   r   r   r   r;   join
ValueErrorrr   r	   r   r   r   r6   r   )rg   r   r   cron_expressionhuman_readabler9   r9   r:   r   >  s6   
zCrontabSchedule.human_readablec              	   C   s8   d t| jt| jt| jt| jt| jt| jS )Nz{} {} {} {} {} (m/h/dM/MY/d) {})	rr   r;   r   r   r   r   r   r6   r   rf   r9   r9   r:   rt   [  s
   zCrontabSchedule.__str__c                 C   sN   t j| j| j| j| j| jd}ttddr%t	| j| j| j| j| j| j
d}|S )Nr   DJANGO_CELERY_BEAT_TZ_AWARET)r   r   r   r   r   tz)r   r   r   r   r   r   r   r=   r
   r   r   )rg   r   r9   r9   r:   rh   b  s"   zCrontabSchedule.schedulec                 C   s|   |j |j|j|j|j|jd}z
| jjdi |W S  | jy*   | di | Y S  t	y=   | jj
di |  Y S w )N)r   r   r   r   r   r   r9   )_orig_minute
_orig_hour_orig_day_of_week_orig_day_of_month_orig_month_of_yearr   rk   rl   rm   r   r   r   rn   r9   r9   r:   rq   v  s   zCrontabSchedule.from_scheduleN)rV   rW   rX   rY   r   ru   rZ   r   minute_validatorr   hour_validatorr   day_of_month_validatorr   month_of_year_validatorr   day_of_week_validatorr   timezone_fieldTimeZoneFieldrA   r   r^   rx   r   rt   rh   ry   rq   r9   r9   r9   r:   r      st    	

r   c                   @   s^   e Zd ZdZejddddZejddZG dd dZ	e
d	d
 Ze
dd Ze
dd ZdS )PeriodicTasksaQ  Helper table for tracking updates to periodic tasks.

    This stores a single row with ``ident=1``. ``last_update`` is updated via
    signals whenever anything changes in the :class:`~.PeriodicTask` model.
    Basically this acts like a DB data audit trigger.
    Doing this so we also track deletions, and not just insert/update.
    r   T)r   primary_keyuniqueF)r{   c                   @   s   e Zd ZedZedZdS )zPeriodicTasks.Metazperiodic task trackzperiodic task tracksN)rV   rW   rX   rZ   rG   r[   r9   r9   r9   r:   r^     s    r^   c                 K   s   |j s	|   d S d S r`   )
no_changesupdate_changed)ro   instancekwargsr9   r9   r:   changed  s   zPeriodicTasks.changedc                 K   s   | j jddt id d S )Nr   last_update)identdefaults)rk   update_or_creater   )ro   r   r9   r9   r:   r     s   zPeriodicTasks.update_changedc                 C   s*   z	| j jddjW S  | jy   Y d S w )Nr   )r   )rk   rl   r   rm   )ro   r9   r9   r:   last_change  s
   zPeriodicTasks.last_changeN)rV   rW   rX   rY   r   SmallIntegerFieldr   r   r   r^   ry   r   r   r   r9   r9   r9   r:   r     s    

r   c                	       s  e Zd ZdZejddededdZejddedd	Zej	e
ejdded
eddZej	eejddededdZej	eejddededdZej	eejddededdZejddededdZejddededdZejddddededdZejddddededdZejdddded ed!dZejdded"ed#dZejded$gdded%ed&d'Zejdded(ed)d*Zejdded+ed,d*Zej d-ed.ed/d0Z!ejdded1ed2d*Z"ej ded3ed4d0Z#ejd-d-d-dded5ed6d7Z$ejd8d-ed9ed:d;Z%ejded<ed=d>Z&ejded?ed@dAZ'e(j)* Z+d-Z,G dBdC dCZ- fdDdEZ. fdFdGZ/ fdHdIZ0dJdK Z1e2dLdM Z3dNdO Z4e2dPdQ Z5e2dRdS Z6  Z7S )TPeriodicTaskz#Model representing a periodic task.   TNamezShort Description For This Task)rE   r   rG   rH   z	Task NamezXThe Name of the Celery Task that Should be Run.  (Example: "proj.tasks.import_contacts"))rE   rG   rH   zInterval SchedulezYInterval Schedule to run the task on.  Set only one schedule type, leave the others null.)	on_deleter{   blankrG   rH   zCrontab SchedulezXCrontab Schedule to run the task on.  Set only one schedule type, leave the others null.zSolar SchedulezVSolar Schedule to run the task on.  Set only one schedule type, leave the others null.zClocked SchedulezXClocked Schedule to run the task on.  Set only one schedule type, leave the others null.z[]zPositional Argumentsz=JSON encoded positional arguments (Example: ["arg1", "arg2"]))r   r   rG   rH   z{}zKeyword Argumentsz?JSON encoded keyword arguments (Example: {"argument": "value"})NzQueue OverridezDQueue defined in CELERY_TASK_QUEUES. Leave None for default queuing.)rE   r   r{   r   rG   rH   Exchangez,Override Exchange for low-level AMQP routingzRouting Keyz/Override Routing Key for low-level AMQP routingzAMQP Message Headersz2JSON encoded message headers for the AMQP message.   PriorityzcPriority Number between 0 and 255. Supported by: RabbitMQ, Redis (priority reversed, 0 is highest).)r   r   r   r{   rG   rH   zExpires DatetimezHDatetime after which the schedule will no longer trigger the task to run)r   r{   rG   rH   zExpires timedelta with secondszPTimedelta with seconds which the schedule will no longer trigger the task to runFzOne-off Taskz:If True, the schedule will only run the task a single time)r   rG   rH   zStart DatetimezBDatetime when the schedule should begin triggering the task to runEnabledz$Set to False to disable the schedulezLast Run DatetimezdDatetime that the schedule last triggered the task to run. Reset to None if enabled is set to False.)auto_nowauto_now_addeditabler   r{   rG   rH   r   zTotal Run CountzCRunning count of how many times the schedule has triggered the task)r   r   rG   rH   zLast Modifiedz1Datetime that this PeriodicTask was last modified)r   rG   rH   Descriptionz<Detailed description about the details of this Periodic Task)r   rG   rH   c                   @   s    e Zd ZdZedZedZdS )zPeriodicTask.MetarQ   zperiodic taskzperiodic tasksN)rV   rW   rX   rY   rZ   rG   r[   r9   r9   r9   r:   r^   C  s    r^   c                    s   t  j|i | g d} fdd|D }t|dkr tdd}t|dkr8i }|D ]}|g||< q,t| jrD jsFd}t|d S d S )	Nr|   r   re   r   c                    s   g | ]	}t  |r|qS r9   )r=   )r   srf   r9   r:   
<listcomp>M  s    
z0PeriodicTask.validate_unique.<locals>.<listcomp>r   z8One of clocked, interval, crontab, or solar must be set.z<Only one of clocked, interval, crontab, or solar must be setr   z.clocked must be one off, one_off must set True)supervalidate_uniquelenr   r   one_off)rg   argsr   schedule_typesselected_schedule_typeserr_msg
error_infoselected_schedule_type	__class__rf   r:   r   I  s"   zPeriodicTask.validate_uniquec                    sl   | j pd | _ | jp
d | _| jpd | _| jpd | _| jsd | _|   |   t j	|i | t
|  d S r`   )exchangerouting_keyqueueheadersenabledlast_run_at_clean_expiresr   r   saver   r   rg   r   r   r   r9   r:   r   c  s   zPeriodicTask.savec                    s    t  j|i | t|  d S r`   )r   deleter   r   r   r   r9   r:   r   o  s   zPeriodicTask.deletec                 C   s$   | j d ur| jrttdd S d S )Nz2Only one can be set, in expires and expire_seconds)expire_secondsexpiresr   rZ   rf   r9   r9   r:   r   s  s
   zPeriodicTask._clean_expiresc                 C   s   | j p| jS r`   )r   r   rf   r9   r9   r:   expires_y  s   zPeriodicTask.expires_c                 C   s6   d}| j rd}| jrd}| jrd}| jrd}|| S )Nz{0.name}: {{no schedule}}z{0.name}: {0.interval}z{0.name}: {0.crontab}z{0.name}: {0.solar}z{0.name}: {0.clocked})r|   r   re   r   rr   )rg   fmtr9   r9   r:   rt   }  s   
zPeriodicTask.__str__c                 C   s4   | j r| j S | jr| jS | jr| jS | jr| jS d S r`   r   rf   r9   r9   r:   	scheduler  s   zPeriodicTask.schedulerc                 C   s   | j jS r`   )r   rh   rf   r9   r9   r:   rh     s   zPeriodicTask.schedule)8rV   rW   rX   rY   r   ru   rZ   nametask
ForeignKeyrz   CASCADEr|   r   r   rB   re   r   r   	TextFieldr   r   r   r   r   r   PositiveIntegerFieldr   priorityr   r   r   BooleanFieldr   
start_timer   r   total_run_countdate_changeddescriptionr   PeriodicTaskQuerySet
as_managerrk   r   r^   r   r   r   r   rx   r   rt   r   rh   __classcell__r9   r9   r   r:   r     s,   	








r   )8rY   zoneinfor   ImportErrorbackports.zoneinfodatetimer   r   celeryr   r   cron_descriptorr   r   r   r	   django.confr
   django.core.exceptionsr   r   django.core.validatorsr   r   	django.dbr   django.utils.translationr   rZ   r4   r   r   clockedscheduler   	tzcrontabr   utilsr   r   r   r   r   r   r   r   r   rv   r;   rA   ModelrB   rz   r   r   r   r   r9   r9   r9   r:   <module>   sn    





	




	







>H" !