
    h                         d dl 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 d d	lmZ  G d
 de      Z G d de      Zy)    N)urlparse)settings)PermissionDenied)mail_managers)HttpResponsePermanentRedirect)is_valid_path)MiddlewareMixin)escape_leading_slashesc                   ,    e Zd ZdZeZd Zd Zd Zd Z	y)CommonMiddlewarea  
    "Common" middleware for taking care of some basic operations:

        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS

        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,
          append missing slashes and/or prepends missing "www."s.

            - If APPEND_SLASH is set and the initial URL doesn't end with a
              slash, and it is not found in urlpatterns, form a new URL by
              appending a slash at the end. If this new URL is found in
              urlpatterns, return an HTTP redirect to this new URL; otherwise
              process the initial URL as usual.

          This behavior can be customized by subclassing CommonMiddleware and
          overriding the response_redirect_class attribute.
    c                    |j                   j                  d      }|1t        j                  D ]  }|j	                  |      st        d       |j                         }t        j                  xr |xr |j                  d       }|r|j                  d|nd}| j                  |      r| j                  |      }n|j                         }|s||j                         k7  r||z  }| j                  |      S y)z
        Check for denied User-Agents and rewrite the URL based on
        settings.APPEND_SLASH and settings.PREPEND_WWW
        HTTP_USER_AGENTNzForbidden user agentzwww.z://www. )METAgetr   DISALLOWED_USER_AGENTSsearchr   get_hostPREPEND_WWW
startswithschemeshould_redirect_with_slashget_full_path_with_slashget_full_pathresponse_redirect_class)selfrequest
user_agentuser_agent_regexhostmust_prependredirect_urlpaths           [/var/www/html/ranktracker/api/venv/lib/python3.12/site-packages/django/middleware/common.pyprocess_requestz CommonMiddleware.process_request"   s     \\%%&78
!$,$C$C C #**:6*+ABBC
 !++TTT__V=T9TCO>UW **73009D((*D 47#8#8#::D L//== ;    c                     t         j                  rZ|j                  j                  d      s?t	        |dd      }t        |j                  |       xr t        d|j                  z  |      S y)z
        Return True if settings.APPEND_SLASH is True and appending a slash to
        the request path turns an invalid path into a valid one.
        /urlconfNz%s/F)r   APPEND_SLASH	path_infoendswithgetattrr   )r   r   r)   s      r$   r   z+CommonMiddleware.should_redirect_with_slash?   sf    
   ):):)C)CC)Hgy$7G!'"3"3W== Beg&7&77A r&   c                     |j                  d      }t        |      }t        j                  r:|j                  dv r,t        d|j                  |j                         |z   dz        |S )z
        Return the full path of the request with a trailing slash appended.

        Raise a RuntimeError if settings.DEBUG is True and request.method is
        POST, PUT, or PATCH.
        T)force_append_slash)POSTPUTPATCHa"  You called this URL via %(method)s, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining %(method)s data. Change your form to point to %(url)s (note the trailing slash), or set APPEND_SLASH=False in your Django settings.)methodurl)r   r
   r   DEBUGr3   RuntimeErrorr   )r   r   new_paths      r$   r   z)CommonMiddleware.get_full_path_with_slashL   ss     ((D(A)(3>>gnn0HHM
 &nn"++-8P		 	 r&   c                    |j                   dk(  r1| j                  |      r | j                  | j                  |            S |j                  s2|j                  d      s!t        t        |j                              |d<   |S )z
        When the status code of the response is 404, it may redirect to a path
        with an appended slash if should_redirect_with_slash() returns True.
          zContent-Length)	status_coder   r   r   	streaming
has_headerstrlencontent)r   r   responses      r$   process_responsez!CommonMiddleware.process_responsec   sv     3&..w733D4Q4QRY4Z[[ !!(*=*=>N*O),S1A1A-B)CH%&r&   N)
__name__
__module____qualname____doc__r   r   r%   r   r   rA    r&   r$   r   r      s#    $ <>:.r&   r   c                       e Zd Zd Zd Zd Zy)BrokenLinkEmailsMiddlewarec                    |j                   dk(  rt        j                  s|j                         }|j	                         }|j
                  j                  dd      }| j                  ||||      sm|j
                  j                  dd      }|j
                  j                  dd      }t        d| j                  ||      rdndd	|d
|d|d|d|d	d       |S )z=Send broken link emails for relevant 404 NOT FOUND responses.r9   HTTP_REFERERr   r   z<none>REMOTE_ADDRzBroken z	INTERNAL zlink on z
Referrer: z
Requested URL: z
User agent: z
IP address: 
T)fail_silently)
r:   r   r5   r   r   r   r   is_ignorable_requestr   is_internal_request)r   r   r@   domainr#   refereruaips           r$   rA   z+BrokenLinkEmailsMiddleware.process_responsex   s    3&x~~%%'F((*Dll&&~r:G,,WdFGL\\%%&7B\\%%mX>(,(@(@(QWYY
 +24RA"& r&   c                 l    t        t        j                  dt        j                  |      z  |            S )ze
        Return True if the referring URL is the same domain as the current
        request.
        z^https?://%s/)boolrematchescape)r   rP   rQ   s      r$   rO   z.BrokenLinkEmailsMiddleware.is_internal_request   s(     BHH_ryy/@@'JKKr&   c                 &   |syt         j                  rj                  d      r	|dd k(  ry| j                  ||      sd|v ryt	        |      }|j
                  d|fv r|j                  k(  ryt        fdt         j                  D              S )z
        Return True if the given request *shouldn't* notify the site managers
        according to project settings or in situations outlined by the inline
        comments.
        Tr(   N?r   c              3   @   K   | ]  }|j                          y w)N)r   ).0patternuris     r$   	<genexpr>zBBrokenLinkEmailsMiddleware.is_ignorable_request.<locals>.<genexpr>   s     R77>>#&Rs   )	r   r*   r,   rO   r   netlocr#   anyIGNORABLE_404_URLS)r   r   r_   rP   rQ   parsed_referers     `   r$   rN   z/BrokenLinkEmailsMiddleware.is_ignorable_request   s        S\\#%67c#2h;N ''8SG^ "'*  RL0^5H5HC5ORh6Q6QRRRr&   N)rB   rC   rD   rA   rO   rN   rF   r&   r$   rH   rH   v   s    *LSr&   rH   )rV   urllib.parser   django.confr   django.core.exceptionsr   django.core.mailr   django.httpr   django.urlsr   django.utils.deprecationr	   django.utils.httpr
   r   rH   rF   r&   r$   <module>rm      s=    	 !   3 * 5 % 4 4f fR8S 8Sr&   