
    vgu              
       4   d Z ddlmc mZ ddlmZ ddlZi 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dddd d!d"d#d$d%i d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPZg dQZ	 G dR dS      Z
y)Tz
This module provides a Python interface to interact with a COSEC biometric device.
It allows users to perform various operations such as configuring device settings,
managing users, retrieving attendance events, etc.
    N)	b64encode0
Successful1z"Failed - Invalid Login Credentials2zDate and time manual set failed3zInvalid Date/Time4z%Maximum users are already configured.5zImage size is too big.6zImage format not supported7zCard 1 and card 2 are identical8zCard ID exists9zdFinger print template/ Palm template/ Face template        already exists/ Face Image already exists10zNo Record Found11zTemplate size/ format mismatch12zFP Memory full13zUser id not found14zCredential limit reached15z&Reader mismatch/ Reader not configured16zDevice Busy17zInternal process error 18zPIN already exists19zCredential not found20zMemory Card Not Found21zReference User ID exists22zWrong Selection23zPalm template mode mismatch24z(Feature not enabled in the configuration25z2Message already exists for same user for same date26zMInvalid smart card format/Parameters not applicable as per card type defined.27zTime Out28zRead/Write failed29zWrong Card Type30zkey mismatch31zinvalid card32zScan failed33zInvalid valuezCredential does not matchFailurezFace Not DetectedzUser ConflictzEnroll ConflictzFace Mask DetectedzFull Face Not VisiblezFace Not Straight)3435363738394041)zenroll-on-devicez	week-day0z	week-day1z	week-day2z	week-day3z	week-day4z	week-day5z	week-day6alarmztamper-alarmzauto-alarm-ackzthresh-temp-exceededzallow-exit-when-lockedzauto-relockz
asc-activezdoor-sense-activezexit-switchzaux-output-enablezgreeting-msg-enablezbuzzer-muteenablezenable-signal-waitzread-csnc                       e Zd ZdZddZd Zd Zd Zd ZddZ	ddZ
dd	Zdd
ZddZddZddZddZddZddZd dZd Zd Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d!dZd Zd"dZd#dZd Zd Zd Zd$dZy)%COSECBiometrica  
    A Python interface to interact with a COSEC biometric device.

    This class provides methods for configuring device settings, managing users,
    retrieving attendance events, and other operations.

    Usage:
        1. Instantiate the COSECBiometric class with the required parameters:
            IP address, port, username, and password.
        2. Use the provided methods to perform specific actions on the biometric device.
    c                     || _         || _        || _        || _        || _        d| j                         i| _        d| j                    d| _        g | _        y)a  
        Initialize the COSECBiometric object with the specified parameters.

        Args:
            machine_ip (str): The IP address of the COSEC biometric device.
            port (int): The port number of the COSEC biometric device.
            username (str): The username for accessing the biometric device.
            password (str): The password for accessing the biometric device.
            timeout (int, optional): The timeout for HTTP requests (default is 60 seconds).
        Authorizationzhttp://z/device.cgiN)	_COSECBiometric__ip_COSECBiometric__port_COSECBiometric__timeout_COSECBiometric__username_COSECBiometric__password%_COSECBiometric__generate_auth_header_COSECBiometric__header_COSECBiometric__base_url_COSECBiometric__user_fields)self
machine_ipportusernamepasswordtimeouts         #/var/www/horilla/biometric/cosec.py__init__zCOSECBiometric.__init__b   sX     	 ""($*E*E*GH#DII;k:    c                     | j                    d| j                   j                         }dt        |      j	                         z   S )a  
        Generate the Authorization header for making authenticated requests to the COSEC
        biometric device.

        This method creates an Authorization header using the provided username and
        password, encoded in Base64 format as per the Basic authentication scheme.

        Returns:
            str: The Authorization header value in the format 'Basic <base64_encoded_credentials>'.
        :zBasic )r9   r:   encoder   decode)r?   credentialss     rE   __generate_auth_headerz%COSECBiometric.__generate_auth_headerv   s@     )4??*;<CCE)K077999rG   c                     	 t        j                  |dz   | j                  | j                        }| j	                  |      S # t         j
                  $ r ddicY S w xY w)a  
        This method sends an HTTP GET request to the specified URL with the
        appropriate headers, and then parses the response to handle different scenarios
        such as timeouts, access errors, unsupported content types, and valid responses.
        &format=xmlheadersrD   TimeoutzRequest Timeout)requestsgetr<   r8   _COSECBiometric__parse_responserR   )r?   urlresponses      rE   __send_requestzCOSECBiometric.__send_request   s]    	2||m#T]]DNNH ((22 	2011	2s   ?A AAc                    |j                   dk7  rddiS |j                  j                  d      dk7  rddiS |j                  j	                  d      }t        j                  |      }|j                  j                         }|s|j                  d      }|rbg }|j                  d      D ]J  }i }|D ]  }	|	j                  ||	j                  <    |j                  d	      d
k(  s:|j                  |       L |S |D 	ci c]  }	|	j                  |	j                   }}	|j                  d      rt        j                  |d         }
|
|d<   |S i }||d<   |S c c}	w )a  
        Parse the response received from the COSEC biometric device.

        This method parses the HTTP response received from the COSEC biometric device,
        handles different scenarios such as HTTP status codes, content types,
        and response formats, and extracts relevant data from the response.

        Args:
            response (requests.Response): The HTTP response object received from
            the device.

        Returns:
            dict: A dictionary representing the parsed response. If the response status
            code is 200 (OK), and the content type is XML, the dictionary may contain
            response data. If there is an error or unsupported content, the dictionary
            will contain an appropriate error message.
           ErrorzAccess ErrorzContent-Typeztext/xmlzUnsupported contentutf-8Eventszevent-id101Response-Codemessageerror)status_coderQ   rT   contentrK   ET
fromstringtextstripfindalltagappendcosec_api_response_codes)r?   rW   response_dataroottext_contenteventsparsed_responseevent
event_dictelemr`   s              rE   __parse_responsezCOSECBiometric.__parse_response   so   $ 3&^,,/:=233 ((//8}}]+yy(\\(+F"$!\\(3 ;E!#J % 9/3yy
488,9!~~j1U:'..z:;   DH"H4488TYY#6"H"H"&&76::'8G 29OI.  !O'3OG$ #Is   ;Ec                 ~   |dk(  r| j                    d| d}n*|dk(  r| j                    d| d}n| j                    d| d}| j                  |      }|j                         }|j                         D cg c]	  }||vs| }}|r1dj                  |      }t	        d| d	dj                  |             y
c c}w )a`  
        Authenticate and validate the arguments before sending a request to the COSEC
        biometric device.

        This method verifies that the provided arguments are supported by the
        specified URL endpoint and raises a ValueError if any unsupported arguments
        are found.

        Args:
            url (str): The URL endpoint for the request.
            kwargs (dict): A dictionary containing the arguments to be authenticated.

        Raises:
            ValueError: If any of the provided arguments are not supported by the specified
                        URL endpoint.
        special-function/z?action=get&sp-fn-index=1smart-card-formatz?action=get&card-type=1&index=1z?action=getz, zAThe following argument(s) are not supported                    : z. Supported arguments are: N)r=   _COSECBiometric__send_requestkeysjoin
ValueError)r?   rV   kwargsrW   supported_argsargunsupported_argsunsupported_args_strs           rE   __authenticate_argumentsz'COSECBiometric.__authenticate_arguments   s    " $$__%Qse+DEC''__%Qse+JKC__%Qse;7C&&s+!+1;;=VCC~<UCVV#'99-=#> +,,G		R`HaGbd   Ws   6	B: B:c                     | j                    d| }|dk(  rO| j                  d|       |ddj                  |j                         D cg c]  \  }}| d|  c}}      z   z  }| j	                  |      S c c}}w )a  
        Configure or retrieve basic settings of the COSEC biometric device.

        This method allows the user to configure or retrieve basic settings of
        the COSEC biometric device, such as device name, IP settings, time settings,
        etc.
        z/device-basic-config?action=setzdevice-basic-config&=r=   '_COSECBiometric__authenticate_argumentsr{   itemsry   r?   actionr}   rV   keyvalues         rE   basic_configzCOSECBiometric.basic_config   s     !!=fXFU?))*?H3flln"U
UcU!E7#3"UVVVC""3'' #V   	A7c                     | j                    d| }|dk(  rO| j                  d|       |ddj                  |j                         D cg c]  \  }}| d|  c}}      z   z  }| j	                  |      S c c}}w )a?  
        Configure or retrieve parameters related to the finger reader of the COSEC
        biometric device.

        This method allows the user to configure or retrieve parameters related to
        the finger reader of the COSEC biometric device, such as sensitivity, timeout,
        template format, etc.
        z/finger-parameter?action=r   zfinger-parameterr   r   r   r   s         rE   %finger_reader_parameter_configurationz4COSECBiometric.finger_reader_parameter_configuration   s     !!:6(CU?))*<fE3flln"U
UcU!E7#3"UVVVC""3'' #Vr   c                     | j                    d| }|dk(  rb| j                  d|       |ddj                  |j                         D cg c]  \  }}| d|t        v rt        |      n| ! c}}      z   z  }| j                  |      S c c}}w )a:  
        Configure or retrieve enrollment options of the COSEC biometric device.

        This method allows the user to configure or retrieve enrollment options
        of the COSEC biometric device, such as enabling or disabling self-enrollment,
        setting enrollment timeout, template format, etc.
        z/enroll-options?action=r   zenroll-optionsr   r   r=   r   r{   r   true_false_argumentsintry   r   s         rE   enrollment_configurationz'COSECBiometric.enrollment_configuration       !!8AU?))*:FC3 '-lln"U e132F+FSZERS  C ""3''   	$B
c                     | j                    d| }|dk(  rb| j                  d|       |ddj                  |j                         D cg c]  \  }}| d|t        v rt        |      n| ! c}}      z   z  }| j                  |      S c c}}w )a  
        Configure or retrieve access settings of the COSEC biometric device.

        This method allows the user to configure or retrieve access settings of the
        COSEC biometric device, such as door access control, alarm settings,
        exit switches, etc
        z/access-setting?action=r   zaccess-settingr   r   r   r   s         rE   access_settings_configurationz,COSECBiometric.access_settings_configuration  r   r   c                     | j                    d| }|dk(  rb| j                  d|       |ddj                  |j                         D cg c]  \  }}| d|t        v rt        |      n| ! c}}      z   z  }| j                  |      S c c}}w )a:  
        Configure or retrieve alarm settings of the COSEC biometric device.

        This method allows the user to configure or retrieve alarm settings of
        the COSEC biometric device, such as enabling or disabling alarms, setting
        alarm thresholds, configuring alarm acknowledgements, etc.
        z/alarm?action=r   r0   r   r   r   r   s         rE   alarm_configurationz"COSECBiometric.alarm_configuration/  s     !x8U?))'6:3 '-lln"U e132F+FSZERS  C ""3''r   c                     | j                    d| }|dk(  rb| j                  d|       |ddj                  |j                         D cg c]  \  }}| d|t        v rt        |      n| ! c}}      z   z  }| j                  |      S c c}}w )aH  
        Configure or retrieve date and time settings of the COSEC biometric device.

        This method allows the user to configure or retrieve date and time settings
        of the COSEC biometric device, such as setting the current date and time,
        configuring time zones, enabling daylight saving time, etc.
        z/date-time?action=r   z	date-timer   r   r   r   s         rE   date_and_time_configurationz*COSECBiometric.date_and_time_configurationC  s     !!3F8<U?))+v>3 '-lln"U e132F+FSZERS  C ""3''r   c                     | j                    d| }|dk(  rb| j                  d|       |ddj                  |j                         D cg c]  \  }}| d|t        v rt        |      n| ! c}}      z   z  }| j                  |      S c c}}w )aM  
        Configure or retrieve door features settings of the COSEC biometric device.

        This method allows the user to configure or retrieve door features settings
        of the COSEC biometric device, such as enabling or disabling door senses,
        setting door open durations, configuring auxiliary outputs, etc.
        z/door-feature?action=r   zdoor-featurer   r   r   r   s         rE   door_features_configurationz*COSECBiometric.door_features_configurationV       !!6vh?U?)).&A3 '-lln"U e132F+FSZERS  C ""3''r   c                     | j                    d| }|dk(  rb| j                  d|       |ddj                  |j                         D cg c]  \  }}| d|t        v rt        |      n| ! c}}      z   z  }| j                  |      S c c}}w )a5  
        Configure or retrieve system timer settings of the COSEC biometric device.

        This method allows the user to configure or retrieve system timer settings
        of the COSEC biometric device, such as setting the system idle timeout,
        configuring system heartbeat intervals, etc.
        z/system-timer?action=r   zsystem-timerr   r   r   r   s         rE   system_timer_configurationz)COSECBiometric.system_timer_configurationi  r   r   c                 &   | j                    d| d| }|dk(  rb| j                  d|       |ddj                  |j                         D cg c]  \  }}| d|t        v rt        |      n| ! c}}      z   z  }| j                  |      S c c}}w )z
        Configure special functions on the COSEC biometric device.

        This method allows configuring special functions on the COSEC biometric device,
        such as enabling or disabling
        specific functionalities
        z/special-function?action=z&sp-fn-index=r   rv   r   r   r   )r?   r   sp_fn_indexr}   rV   r   r   s          rE   special_function_configurationz-COSECBiometric.special_function_configuration|  s     !!:6(-P[}]U?))*<fE3 '-lln"U e132F+FSZERS  C ""3''s   $Bc                     | j                    d| }|dk(  rb| j                  d|       |ddj                  |j                         D cg c]  \  }}| d|t        v rt        |      n| ! c}}      z   z  }| j                  |      S c c}}w )a8  
        Configure or retrieve Wiegand interface settings of the COSEC biometric device.

        This method allows the user to configure or retrieve Wiegand interface settings
        of the COSEC biometric device,such as setting up Wiegand card readers, configuring
        Wiegand data formats, etc.
        z/wiegand-interface?action=r   zwiegand-interfacer   r   r   r   s         rE   wiegand_interfacez COSECBiometric.wiegand_interface  s     !!;F8DU?))*=vF3 '-lln"U e132F+FSZERS  C ""3''r   c                 ,   | j                    d| d| d| }|dk(  rb| j                  d|       |ddj                  |j                         D cg c]  \  }}| d|t        v rt        |      n| ! c}}      z   z  }| j                  |      S c c}}w )a(  
        Configure or retrieve smart card format settings of the COSEC biometric device.

        This method allows the user to configure or retrieve smart card format settings
        of the COSEC biometric device,
        such as setting up card types and their corresponding formats.
        z/smart-card-format?action=z&card-type=z&index=r   rx   r   r   r   )r?   r   	card_typeindexr}   rV   r   r   s           rE   smart_card_formatz COSECBiometric.smart_card_format  s     9&)GE74 	
 U?))*=vF3 '-lln"U e132F+FSZERS  C ""3''s   $Bc                 F    | j                    d| }| j                  |      S )a  
        Retrieve user information from the COSEC biometric device.

        This method retrieves user information, such as user details,
        credentials, and access rights, from the COSEC biometric device based
        on the provided user ID.
        z/users?action=get&user-id=r=   ry   r?   user_idrV   s      rE   get_cosec_userzCOSECBiometric.get_cosec_user  s+     !!;G9E""3''rG   c                    | j                  |      }|j                  d      st        |j                               | _        nd}d}|dk7  r| j
                   d| d| d}t        j                  || j                  | j                        }|j                  d	k(  r|j                  j                  d
      }t        j                  |      }	|	j                  d      j                  }|dk(  rA| j                  |      }t        |j                               | _        | j!                  |       n|dz  }|dk7  rd}
|D ]=  }|j#                  d      d   | j                  vs$|
|j#                  d      d   dz   z  }
? |
rt%        |
 d      y)a  
        Check if the provided URL arguments are supported for the COSEC
        biometric device's user configuration.

        This method verifies if the provided URL arguments are supported
        for configuring or retrieving user settings on the COSEC biometric
        device. It compares the provided arguments with the supported fields
        retrieved from the device for user configuration.
        r_      r   r   /users?action=set&user-id=z&ref-user-id=rO   rP   rZ   r\    r   r   z , z5 argument is not support on this biometric device APIN)r   rT   listrz   r>   r=   rS   r<   r8   rb   rc   rK   rd   re   findrf   delete_cosec_usersplitr|   )r?   r   url_argumentsuserref_user_idcoderV   rW   rl   rm   fieldsr   s               rE   check_user_url_argumentsz'COSECBiometric.check_user_url_arguments  s    ""7+xx(!%diik!2D KD#+''A'#K== 
 $<< ''3.$,$4$4$;$;G$DM==7D99_5::Ds{#227;-1$))+->*..w71$K% #+&   	4Cyy~a (:(::#))C.+e33	4 (OP  rG   Nc                    |r|st        d      g }| j                   d}|j                  d|        |j                  d|        |r)t        |      dkD  r|dd n|}|j                  d|        |,|dvrt        d	      |j                  d
t	        |              |,|dvrt        d      |j                  dt	        |              |,|dvrt        d      |j                  dt	        |              |	r@|
r>|r<|j                  d|	        |j                  d|
        |j                  d|        |r*|r(|j                  d|        |j                  d|        |r|j                  d|        ||j                  d|        |,|dvrt        d      |j                  dt	        |              |r|j                  d|        |r|j                  d|        |,|dvrt        d      |j                  dt	        |              |r@|r>|r<|j                  d|        |j                  d|        |j                  d|        |r|j                  d|        |,|dvrt        d       |j                  d!t	        |              |,|dvrt        d"      |j                  d#t	        |              | j                  ||       |d$d$j                  |      z   z  }| j                  |      S )%a
  
        Set or update user information on the COSEC biometric device.

        This method allows setting or updating user information on the COSEC
        biometric device, including user details, access rights, credentials,
        validity periods, etc.
        z>Both user_id and ref_id are mandatory for create & edit a userz/users?action=setzuser-id=zref-user-id=   Nzname=)TFz/user_active must be either True, False, or Nonezuser-active=z'vip must be either True, False, or Nonezvip=z3validity_enable must be either True, False, or Nonezvalidity-enable=zvalidity-date-dd=zvalidity-date-mm=zvalidity-date-yyyy=zvalidity-time-hh=zvalidity-time-mm=z	user-pin=zby-pass-finger=z0by_pass_palm must be either True, False, or Nonezby-pass-palm=zcard1=zcard2=z.dob_enable must be either True, False, or Nonezdob-enable=zdob-dd=zdob-mm=z	dob-yyyy=zuser-group=z:self_enrollment_enable must be either True, False, or Nonezself-enrollment-enable=z-enable_fr must be either True, False, or Nonez
enable-fr=r   )r|   r=   rj   lenr   r   r{   ry   )r?   r   r   nameuser_activevipvalidity_enablevalidity_time_hhvalidity_time_mmvalidity_date_ddvalidity_date_mmvalidity_date_yyyyuser_pincard1card2by_pass_finger
dob_enabledob_dddob_mmdob_yyyyby_pass_palm
user_groupself_enrollment_enable	enable_frr   rV   truncated_names                              rE   set_cosec_userzCOSECBiometric.set_cosec_user  s   B kP  !!23xy12|K=9:*-d)b.T#2YdN  5(8!9:"-/ !RSS  <K0@/A!BC? -' !JKK  4Cz!23&m3 !VWW  #3C4H3I!JK 05G   #45E4F!GH  #45E4F!GH  #67I6J!KL 0   #45E4F!GH  #45E4F!GH   9XJ!78%  ?>2B!CD#=0 !STT  =\1B0C!DE   6%!12  6%!12!. !QRR  ;s:.?!@Af   76(!34  76(!34  9XJ!78
   ;zl!;<!-%]: P    )#.D*E)FG  - !PQQ  :c)n-=!>?%%g}=sSXXm,,,""3''rG   c                 F    | j                    d| }| j                  |      S )z
        Delete a user from the COSEC biometric device.

        This method deletes a user with the specified user ID from the COSEC
        biometric device.
        z/users?action=delete&user-id=r   r   s      rE   r   z COSECBiometric.delete_cosec_user  s+     !!>wiH""3''rG   c                 `    | j                    d| dt        |       d}| j                  |      S )zZ
        Enable or disable face recognition for a user in cosec biometric device.
        r   z&enable-fr=rO   )r=   r   ry   )r?   r   r   rV   s       rE   enable_user_face_recognitionz+COSECBiometric.enable_user_face_recognition  s@    
 9'#i.)6 	 ""3''rG   c                     t        |t              rt        |t              st        d      |dk  s|dkD  rt        d      |dk  s|dkD  rt        d      | j                   d| d| d	| }| j	                  |      S )
a@  
        Retrieve the credential of a user from the COSEC biometric device.

        This method retrieves the credential of a user, such as fingerprint,
        card, palm template, face template, or face image, from the COSEC biometric
        device based on the provided user ID
        and credential type.
        z6type and finger_index arguments value must be integersr      zType must be between 1 and 6
   z%Finger index must be between 1 and 10z/credential?action=get&type=z	&user-id=z&finger-index=)
isinstancer   r|   r=   ry   )r?   r   credential_typefinger_indexrV   s        rE   get_user_credentialz"COSECBiometric.get_user_credential  s     /3/z,PS7TUVVQ/A"5;<<!|b0DEE ;O;Ly|n> 	 ""3''rG   c                 F    | j                    d| }| j                  |      S )aJ  
        Retrieve the credential of a user from the COSEC biometric device.

        This method retrieves the count of credentials of a user, such as fingerprint,
        card, palm template, face template, or face image, from the COSEC biometric
        device based on the provided user ID
        and credential type.
        z!/command?action=getcount&user-id=r   r   s      rE   get_user_credential_countz(COSECBiometric.get_user_credential_count  s+     !!B7)L""3''rG   c                     t         dk  s	t         dkD  rt        d      | j                   d| d| }| j                  |      S )aJ  
        Delete a specific type of credential associated
        with a user from the COSEC biometric device.

        This method deletes a specific type of credential
        associated with a user, such as fingerprint,
        card, palm template, face template, or face image,
        from the COSEC biometric device.
        r   r   zType must be between 0 and 6z"/credential?action=delete&user-id=z&type=)typer|   r=   ry   )r?   r   r   rV   s       rE   delete_cosec_user_credentialz+COSECBiometric.delete_cosec_user_credential  sL     !8tax;<<!!CG9FSbRcd""3''rG   c                 B    | j                    d}| j                  |      S )z
        Retrieve the total number of users configured on the COSEC biometric device.

        This method retrieves the total number of users configured on the COSEC biometric device.
        z/command?action=getusercountr   )r?   rV   s     rE   get_user_countzCOSECBiometric.get_user_count  s'     !!=>""3''rG   c                 R    | j                    d| d| d| }| j                  |      S )z
        Retrieve attendance events from the COSEC biometric device.

        This method retrieves attendance events, such as punch-in and punch-out records,
        from the COSEC biometric device.
        z(/events?action=getevent&roll-over-count=z&seq-number=z&no-of-events=r   )r?   roll_over_countseq_numno_of_eventsrV   s        rE   get_attendance_eventsz$COSECBiometric.get_attendance_events  sA     GGX7)>,A 	 ""3''rG   )<   )rT   )rT   r   )rT   r   r   )NNNNNNNNNNNNNNNNNNNNN)T)r   r   )r   r   d   )__name__
__module____qualname____doc__rF   r;   ry   rU   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    rG   rE   r3   r3   U   s    
 (:2.` D( ("(*(*(((&(&(&(&(&(.	(+b #1O(b(((4
(($((rG   r3   )r   xml.etree.ElementTreeetreeElementTreerd   base64r   rS   rk   r   r3   r   rG   rE   <module>r      s   # "  ,,	-, 	*, 		,
 	0, 	!, 	%, 	*, 	,  
3, 	
, 	
*, 	
, 	
,  	
$!," 	
2#,$ 	-%,& 	
#',( 	
),* 	
 +,, 	
!-,. 	
$/,0 	
1,2 	
'3,4 	
45,6 	
>7,8 	
Y9,: 	*;,< 	
=,> 	
?,@ 	.A,B 	.C,D 	-E,F 	/G,H &





!
W, \ 6M
( M
(rG   