
    Wwg[                        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 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 d dlmZmZ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' d dl(m)Z* d dl+m,Z, dZ- G d dej\                        Z/ G d dej`                        Z1 G d de      Z2dZ3de	e1ge
f   fdZ4y)    N)deepcopy)timezone)AnyCallableDictListUnion)parser)gettz)settings)GenericRelation)ContentType)serializers)FieldDoesNotExistObjectDoesNotExistValidationError)DEFAULT_DB_ALIASmodels)QQuerySet)formats)	smart_str)gettext_lazy)mask_strz<error forming object repr>c                       e Zd ZdZddefdZd Zd Zd Zd Z	d Z
d	 Zd
 Zdeeee   f   dee   fdZdeeef   dee   deeef   fdZy)LogEntryManagerz<
    Custom manager for the :py:class:`LogEntry` model.
    	force_logc                 |   ddl m} |j                  dd      }| j                  |      }||r|j	                  dt
        j                  j                  |             |j	                  d|       	 t        |      }|j	                  d|       |j	                  d| j                  |             t        |t              r|j	                  d	|       t        |d
d      }t        |      r|j	                  d |              |j	                  d |               | j                   di |S y# t        $ r	 t        }Y w xY w)a  
        Helper method to create a new log entry. This method automatically populates some fields when no
        explicit value is given.

        :param instance: The model instance to log a change for.
        :type instance: Model
        :param force_log: Create a LogEntry even if no changes exist.
        :type force_log: bool
        :param kwargs: Field overrides for the :py:class:`LogEntry` object.
        :return: The new log entry or `None` if there were no changes.
        :rtype: LogEntry
        r   get_cidchangesNcontent_type	object_pkobject_reprserialized_data	object_idget_additional_dataadditional_datacid )auditlog.cidr    get_get_pk_value
setdefaultr   objectsget_for_modelr   r   DEFAULT_OBJECT_REPR_get_serialized_data_or_none
isinstanceintgetattrcallablecreate)	selfinstancer   kwargsr    r!   pkr$   r'   s	            F/var/www/horilla/myenv/lib/python3.12/site-packages/auditlog/models.py
log_createzLogEntryManager.log_create$   s/    	)**Y-)) 3 3 A A( K k2.2'1 m[9!4#D#DX#N "c"!!+r2")(4I4"P+,!!"35H5JK eWY/4;;(((# & 212s   0D) )D;:D;c                    ddl m} | j                  |      }|r&|j                  dt        j
                  j                  |             |j                  d|       	 t        |      }|j                  d|       |j                  dt        j                  j                         t        |t              r|j                  d|       t        |dd	      }	t!        |	      r|j                  d
 |	              |D cg c]  }t        |       }
}|d||
di|d<   |j                  d |               | j"                  di |S y	# t        $ r	 t        }Y w xY wc c}w )aY  Create a new "changed" log entry from m2m record.

        :param changed_queryset: The added or removed related objects.
        :type changed_queryset: QuerySet
        :param instance: The model instance to log a change for.
        :type instance: Model
        :param operation: "add" or "delete".
        :type action: str
        :param field_name: The name of the changed m2m field.
        :type field_name: str
        :param kwargs: Field overrides for the :py:class:`LogEntry` object.
        :return: The new log entry or `None` if there were no changes.
        :rtype: LogEntry
        r   r   r"   r#   r$   actionr&   r'   Nr(   m2m)type	operationr/   r!   r)   r*   )r+   r    r-   r.   r   r/   r0   r   r   r1   LogEntryActionUPDATEr3   r4   r5   r6   r7   )r8   changed_querysetr9   rB   
field_namer:   r    r;   r$   r'   r/   s              r<   log_m2m_changeszLogEntryManager.log_m2m_changesP   sN   " 	)) 3 3 A A( K k2.2'1 m[9h(>(>?"c"!!+r2")(4I4"P+,!!"35H5JK;KLxy*LGL!!*&!F9 eWY/4;;(((1 & 212 Ms   E 9EEEc                 H   t        |t        j                        s| j                         S t        j
                  j                  |j                        }| j                  |      }t        |t              r| j                  ||      S | j                  |t        |            S )a  
        Get log entries for the specified model instance.

        :param instance: The model instance to get log entries for.
        :type instance: Model
        :return: QuerySet of log entries for the given model instance.
        :rtype: QuerySet
        )r"   r&   )r"   r#   )r3   r   Modelnoner   r/   r0   	__class__r-   r4   filterr   )r8   r9   r"   r;   s       r<   get_for_objectzLogEntryManager.get_for_object   s~     (FLL199;"**889K9KL)b#;;LB;GG;;LIbM;RR    c                 h   t        |t              r|j                         dk(  r| j                         S t        j
                  j                  |j                        }t        |j                  |j                  j                  j                  j                  d            }t        |d   t              r9| j                  |      j                  t        |            j!                         S t        |j                  j                  j                  t"        j$                        rQ|D cg c]  }t'        |       }}| j                  |      j                  t        |            j!                         S | j                  |      j                  t        |            j!                         S c c}w )a  
        Get log entries for the objects in the specified queryset.

        :param queryset: The queryset to get the log entries for.
        :type queryset: QuerySet
        :return: The LogEntry objects for the objects in the given queryset.
        :rtype: QuerySet
        r   T)flatr"   )object_id__in)object_pk__in)r3   r   countrK   r   r/   r0   modellistvalues_list_metar;   namer4   rM   r   distinctr   	UUIDFieldr   )r8   querysetr"   primary_keysr;   s        r<   get_for_objectszLogEntryManager.get_for_objects   sA    (H-1AQ1F99;"**88H  !5!5!8!8!=!=D I
 l1os+656
 ,,//1A1AB4@AbIbMALA656 656 Bs   )F/c                     t        |t        j                        s| j                         S t        j
                  j                  |      }| j                  |      S )z
        Get log entries for all objects of a specified type.

        :param model: The model to get log entries for.
        :type model: class
        :return: QuerySet of log entries for the given model.
        :rtype: QuerySet
        rR   )
issubclassr   rJ   rK   r   r/   r0   rM   )r8   rV   r"   s      r<   r0   zLogEntryManager.get_for_model   sE     %.99;"**88?{{{55rO   c                     |j                   j                  j                  }t        ||d      }t	        |t
        j                        r| j                  |      }|S )z
        Get the primary key field value for a model instance.

        :param instance: The model instance to get the primary key for.
        :type instance: Model
        :return: The primary key value of the given model instance.
        N)rY   r;   rZ   r5   r3   r   rJ   r-   )r8   r9   pk_fieldr;   s       r<   r-   zLogEntryManager._get_pk_value   sL     >>$$))Xx. b&,,'##B'B	rO   c           	         ddl m} |j                  |j                        sy |j	                  |j                        }|d   sy |j                  |j                        }|j                  di       }|d   r"|j                  d| j                  ||             | j                  |      }t        t        j                  t        j                  d|ffi |      d         }|d   }|r| j                  ||      }|S )	Nr   auditlogserialize_dataserialize_kwargsserialize_auditlog_fields_onlyfieldsjsonmask_fields)auditlog.registryrf   containsrL   get_serialize_optionsget_model_fieldsr,   r.   _get_applicable_model_fields"_get_copy_with_python_typed_fieldsdictrk   loadsr   	serialize_mask_serialized_fields)	r8   r9   rf   optsmodel_fieldsr:   instance_copydatarl   s	            r<   r2   z,LogEntryManager._get_serialized_data_or_none   s    .  !3!34--h.@.@A$%001C1CD,b101$;;HlS ??IJJ{,,Vm5EPPQRST
 #=1//kBDrO   c                 (   	 t        |      }|j                  j                  D ]L  }|j                  rt        ||j                        }	 t        ||j                  |j                  |             N |S # t        $ r |}Y tw xY w# t        $ r Y mw xY w)a  
        Attempt to create copy of instance and coerce types on instance fields

        The Django core serializer assumes that the values on object fields are
        correctly typed to their respective fields. Updates made to an object's
        in-memory state may not meet this assumption. To prevent this violation, values
        are typed by calling `to_python` from the field object, the result is set on a
        copy of the instance and the copy is sent to the serializer.
        )
r   	TypeErrorrY   rj   is_relationr5   rZ   setattr	to_pythonr   )r8   r9   ry   fieldvalues        r<   rr   z2LogEntryManager._get_copy_with_python_typed_fields   s    	%$X.M #((// 	E$$uzz:M5::uu7MN		   	%$M	% ' s#   A4 
&B4BB	BBrx   returnc                     |d   }|d   }|j                   j                  D cg c]  }|j                   }}|s|s|S t        t	        |xs |      j                  |            S c c}w )Ninclude_fieldsexclude_fields)rY   rj   rZ   rW   set
difference)r8   r9   rx   r   r   r   all_field_namess          r<   rq   z,LogEntryManager._get_applicable_model_fields  sl     &&67%&673;>>3H3HI%5::IIn""C9/:EEnUVV Js   A%rz   rl   c                     |j                  d      }i }|j                         D ]-  \  }}t        |t              r||v rt	        |      ||<   )|||<   / ||d<   |S )Nrj   )popitemsr3   strr   )r8   rz   rl   all_field_datamasked_field_datakeyr   s          r<   rv   z'LogEntryManager._mask_serialized_fields   so     (+(..0 	/JC%%#*<)1%!#&).!#&		/ +XrO   N)F)__name__
__module____qualname____doc__boolr=   rH   rN   r_   r0   r-   r2   rr   r   r   r   rq   r   rv   r*   rO   r<   r   r      s    *d *X3jS*#J6" :.
W&*3S	>&:
W	c
WcN15c	c3hrO   r   c            
          e Zd ZdZ G d d      Z ej                  dej                  d ed            Z	 ej                  dd	 ed
            Z ej                  ddd ed            Z ej                   ed            Z ej                   d      Z ej$                  ej&                   ed      d      Z ej                  d ed            Z ej                   d ed            Z ej                  ej0                  ej2                  ddd ed            Z ej                  d	ddd ed            Z ej8                  dd ed            Z ej<                  ej@                  d ed            Z! ej                   dd ed            Z" e#       Z$ G d d       Z%d! Z&e'd"        Z(e'd*d#       Z)e'd$        Z*d%e+ej                  ejX                  f   d&e-d'e.fd(Z/y))+rC   a)  
    Represents an entry in the audit log. The content type is saved along with the textual and numeric
    (if available) primary key, as well as the textual representation of the object when it was saved.
    It holds the action performed and the fields that were changed in the transaction.

    If AuditlogMiddleware is used, the actor will be set automatically. Keep in mind that
    editing / re-saving LogEntry instances may set the actor to a wrong value - editing LogEntry
    instances is not recommended (and it should not be necessary).
    c                   l    e Zd 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fZ	y
)LogEntry.Actiona  
        The actions that Auditlog distinguishes: creating, updating and deleting objects. Viewing objects
        is not logged. The values of the actions are numeric, a higher integer value means a more intrusive
        action. This may be useful in some cases when comparing actions because the ``__lt``, ``__lte``,
        ``__gt``, ``__gte`` lookup filters can be used in queries.

        The valid actions are :py:attr:`Action.CREATE`, :py:attr:`Action.UPDATE`,
        :py:attr:`Action.DELETE` and :py:attr:`Action.ACCESS`.
        r            r7   updatedeleteaccessN)
r   r   r   r   CREATErE   DELETEACCESS_choicesr*   rO   r<   rD   r   ;  sV    	  Qx[!Qx[!Qx[!Qx[!	
rO   rD   zcontenttypes.ContentType+zcontent type)to	on_deleterelated_nameverbose_nameT   z	object pk)db_index
max_lengthr   z	object id)blankr   nullr   zobject representation)r   )r   r?   )r   r   r   zchange message)r   r   )r   r   actor)r   r   r   r   r   r   zCorrelation ID)r   r   r   r   r   zremote address)r   r   r   	timestamp)defaultr   r   zadditional datac                   6    e Zd ZdZdgZ ed      Z ed      Zy)LogEntry.Metar   z
-timestampz	log entryzlog entriesN)r   r   r   get_latest_byorderingr   r   verbose_name_pluralr*   rO   r<   Metar     s"    # >~.rO   r   c                 j   | j                   | j                  j                  k(  rt        d      }ni| j                   | j                  j                  k(  rt        d      }n:| j                   | j                  j
                  k(  rt        d      }nt        d      }|j                  | j                        S )NzCreated {repr:s}zUpdated {repr:s}zDeleted {repr:s}zLogged {repr:s})repr)r?   rD   r   r   rE   r   formatr$   )r8   fstrings     r<   __str__zLogEntry.__str__  s    ;;$++,,,*+G[[DKK...*+G[[DKK...*+G)*G~~4#3#3~44rO   c                     t        |       S )zY
        :return: The changes recorded in this log entry as a dictionary object.
        )changes_func)r8   s    r<   changes_dictzLogEntry.changes_dict  s    
 D!!rO   c           	          g }| j                   j                         D ]2  \  }}dj                  |||d   ||d         }|j                  |       4 |j	                  |      S )aa  
        Return the changes recorded in this log entry as a string. The formatting of the string can be
        customized by setting alternate values for colon, arrow and separator. If the formatting is still
        not satisfying, please use :py:func:`LogEntry.changes_dict` and format the string yourself.

        :param colon: The string to place between the field name and the values.
        :param arrow: The string to place between each old and new value.
        :param separator: The string to place between each field.
        :return: A readable string of the changes in this log entry.
        z.{field_name:s}{colon:s}{old:s}{arrow:s}{new:s}r   r   )rG   colonoldarrownew)r   r   r   appendjoin)r8   r   r   	separator
substringsr   values	substrings           r<   changes_strzLogEntry.changes_str  sy     
!..446 	)ME6HOO 1I1I P I i(	) ~~j))rO   c                    ddl m} | j                  j                         }d}|j	                  |j
                  j                        r%|j                  |j
                  j                        }i }| j                  j                         D ]V  \  }}	 |j
                  j                  |      }g }d}	t        |dg       rt        |j                        }	t        t        |dd      dg       rt        |j                  j                        }	|	r|D ]  }
	 t!        j"                  |
      }
t%        |
      g j&                  u r?|j)                  dj+                  |
D cg c]  }|	j-                  |d       c}             n!|j)                  |	j-                  |
d              n	 |j1                         }|D ]  }
|dv r	 t5        j6                  |
      }
|d	k(  r|
j9                         }
nc|d
k(  r|
j;                         }
nM|dk(  rH|
j=                  t>        j@                        }
|
jC                  tE        tF        jH                              }
tK        jL                  |
      }
n|dv r| jQ                  ||
      }
tS        |
      dkD  r|
dd  d}
|j)                  |
        |r$|jT                  |d   v r|d   |jT                     }nt        |d|jT                        }|||<   Y |S # t        $ r	 |||<   Y mw xY wc c}w # t.        $ r% |j)                  |	j-                  |
d             Y w xY w# t2        $ r Y w xY w# tN        $ r Y w xY w)zw
        :return: The changes recorded in this log entry intended for display to users as a dictionary object.
        r   re   Nr   
base_fieldz, None)DateTimeField	DateField	TimeFieldr   r   r   )tzinfo)
ForeignKeyOneToOneField   z...mapping_fieldsr   )+rm   rf   r"   model_classrn   rY   rV   rp   r   r   	get_fieldr   r5   rs   r   r   astliteral_evalrA   rL   r   r   r,   	Exceptionget_internal_typeAttributeErrorr
   parsedatetimereplacer   utc
astimezoner   r   	TIME_ZONEr   localize
ValueError!_get_changes_display_for_fk_fieldlenrZ   )r8   rf   rV   rx   changes_display_dictrG   r   r   values_displaychoices_dictr   val
field_typer   s                 r<   r   zLogEntry.changes_display_dict  s:   
 	/ !!--/U[[../#44U[[5F5FGL!"&"3"3"9"9"; A	@J--j9  NLui,#EMM2wulD99bI#E$4$4$<$<=# OEO # 0 0 7;",,6*11 $		NS$Ts\%5%5c6%B$T!" +11,2B2B5&2QRO!&!8!8!:J $ 1E!%PP!$*LL$7E)[8(-

!+{!:(-

!+!>(-X\\(J(-(8(8x?Q?Q9R(S$+$4$4U$;E $'FF $ F Fue T 5zC'#(#;-s 3"))%0-12 

l;K.L L+,<=ejjI&unejjI1? .CA	@D $#} % 39$Z0$ %U
 % O&--l.>.>uf.MNO
 &    * ! !s\   K%AK?K:0-K?!L0;B#M %K76K7:K??*L-,L-0	L=<L= 	MMr   r   r   c                 J   |dk(  r|S 	 |j                   j                  j                  j                  |      }	 t        |j                   j                  j                  |            S # t        $ r |cY S w xY w# t        $ r  d|j                   j                   d| dcY S w xY w)zc
        :return: A string representing a given FK value and the field to which it belongs
        r   )r;   z	Deleted 'z' ())
related_modelrY   r;   r   r   r   r/   r,   r   r   )r8   r   r   pk_values       r<   r   z*LogEntry._get_changes_display_for_fk_field  s     F?L	**0033==eDH	IU0088<<<IJJ	  	L	 " 	Iu22;;<CwaHH	Is"   /A( .A9 (A65A69&B"!B"N)z: u    → z; )0r   r   r   r   rD   r   r   CASCADEr   r"   	CharFieldr#   BigIntegerFieldr&   	TextFieldr$   	JSONFieldr%   PositiveSmallIntegerFieldr   r?   changes_textr!   r   AUTH_USER_MODELSET_NULLr   r)   GenericIPAddressFieldremote_addrr   django_timezonenowr   r(   r   r/   r   r   propertyr   r   r   r	   r   r   r   r   r*   rO   r<   rC   rC   0  sP   
 
. %6$$%..~&	L !  #AkNI '&&T1[>I #&""2I0JKK&f&&D1O-V--Qx[4F $6##$Q?O=PQLfDq9I7JKGF##//wZE &

'(C /&..A.>,?K %$$##{^I
 'f&&A.?,@O G/ /
5 " " * *2 P$ P$dI6,,f.B.BBCILOI	IrO   rC   c                   2     e Zd ZdZd fd	Zef fd	Z xZS )AuditlogHistoryFielda  
    A subclass of py:class:`django.contrib.contenttypes.fields.GenericRelation` that sets some default
    variables. This makes it easier to access Auditlog's log entries, for example in templates.

    By default, this field will assume that your primary keys are numeric, simply because this is the most
    common case. However, if you have a non-integer primary key, you can simply pass ``pk_indexable=False``
    to the constructor, and Auditlog will fall back to using a non-indexed text based field for this model.

    Using this field will not automatically register the model for automatic logging. This is done so you
    can be more flexible with how you use this field.

    :param pk_indexable: Whether the primary key for this model is not an :py:class:`int` or :py:class:`long`.
    :type pk_indexable: bool
    :param delete_related: Delete referenced auditlog entries together with the tracked object.
        Defaults to False to keep the integrity of the auditlog.
    :type delete_related: bool
    c                 h    t         |d<   |rd|d<   nd|d<   d|d<   || _        t        |   di | y )Nr   r&   object_id_fieldr#   r"   content_type_fieldr*   )rC   delete_relatedsuper__init__)r8   pk_indexabler  r:   rL   s       r<   r  zAuditlogHistoryField.__init__5  sH    t(3F$%(3F$%'5#$,"6"rO   c                 @    | j                   rt        | 	  ||      S g S )zV
        Return all objects related to ``objs`` via this ``GenericRelation``.
        )r  r  bulk_related_objects)r8   objsusingrL   s      r<   r  z)AuditlogHistoryField.bulk_related_objectsA  s'     7/e<<
 	rO   )TF)r   r   r   r   r  r   r  __classcell__)rL   s   @r<   r   r   "  s    $
# 0@ 
 
rO   r   r   c                  j    dt         dt        fd} dt         dt        fd}t        j                  r| S |S )Nr9   r   c                     | j                   r| j                   S | j                  rBt        j                  t              5  t        j                  | j                        cd d d        S i S # 1 sw Y   i S xY wN)r!   r   
contextlibsuppressr   rk   rt   r9   s    r<   json_then_textz%_changes_func.<locals>.json_then_textS  s_    ###""$$Z0 9zz("7"789 9	9	s   A))A3c                 "    | j                   xs i S r  )r!   r  s    r<   r   z_changes_func.<locals>.default[  s    %2%rO   )rC   r   r   0AUDITLOG_USE_TEXT_CHANGES_IF_JSON_IS_NOT_PRESENT)r  r   s     r<   _changes_funcr  R  s>     d &( &t & @@NrO   )5r   r  rk   copyr   datetimer   typingr   r   r   r   r	   dateutilr
   dateutil.tzr   django.confr   "django.contrib.contenttypes.fieldsr   "django.contrib.contenttypes.modelsr   django.corer   django.core.exceptionsr   r   r   	django.dbr   r   django.db.modelsr   r   django.utilsr   r   django.utils.encodingr   django.utils.translationr   r   auditlog.diffr   r1   Managerr   rJ   rC   r   r   r  r*   rO   r<   <module>r'     s    
     3 3     > : # 
 / (   4 + 6 "3 Nfnn NboIv|| oId)? )Z x
D 01 rO   