o
    *gW                     @   sj  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
Z
d dlZd dlZd dlmZmZmZmZ d dlm  mZ G d	d
 d
Zdd ZG dd dZG dd dZG dd dZd0ddZd dlm	Z	mZ G dd dZdd Zdd Zd d! Z d"e!d#ee! fd$d%Z"d&e!d#eej# fd'd(Z$d1d)ej#d*e!d+ee!e!f d#eee!ef  fd,d-Z%d.d/ Z&dS )2    wraps)HttpResponseForbidden)redirect   )Users)FTPN)DictAnyOptionalListc                   @   s   e Zd ZdddZdd ZdS )	TelegramLog.6723497869:AAEKCB3YJUGnUFeMihLlr-FHblTuvtoVUZA-4155125438c                 C   s   || _ || _d S N)	BOT_TOKENGROUP_ID)selfr   r    r   8/var/www/html/DAI27/Adtlas_DAI/DAIManagementApp/utils.py__init__   s   
zTelegramLog.__init__c                 C   s   t | j}|| j| d S r   )telebotZTeleBotr   send_messager   )r   messagebotr   r   r   send_telegram_log   s   zTelegramLog.send_telegram_logN)r   r   )__name__
__module____qualname__r   r   r   r   r   r   r      s    
r   c                    s   t   fdd}|S )Nc                    sX   d| j v r(| j d r(| j d d kr(tjj| j d dd kr( | g|R i |S tdS )Nid_user)r   login)sessionr   objectsfilterr   )requestargskwargsfuncr   r   wrapper   s   :zcheck_user.<locals>.wrapperr   )r(   r)   r   r'   r   
check_user   s   r*   c                   @      e Zd Zdd ZdS )NoVastResultc                 C      || _ || _t|| _d S r   id_campaign	total_adsinttotal_impressionsr   r/   r0   r2   r   r   r   r   %      zNoVastResult.__init__Nr   r   r   r   r   r   r   r   r,   $       r,   c                   @   r+   )
VastResultc                 C   r-   r   r.   r3   r   r   r   r   +   r4   zVastResult.__init__Nr5   r   r   r   r   r7   *   r6   r7   c                   @   s6   e Zd ZdddZdd Zdd Zd	d
 Zdd ZdS )	FTPClient   Nc                 C   s&   || _ || _|| _|| _|  | _d S r   )
ftp_serverportusernamepassword_setup_loggerlogger)r   r:   r;   r<   r=   r   r   r   r   2   s
   zFTPClient.__init__c                 C   s@   t t}|t j t d}t  }|| || |S )Nz)%(asctime)s - %(levelname)s - %(message)s)	logging	getLoggerr   setLevelINFO	FormatterStreamHandlersetFormatter
addHandler)r   r?   	formatterchr   r   r   r>   9   s   



zFTPClient._setup_loggerc                 C   s0   t  | _| j| j| j | j| j| j d S r   )r   ftpconnectr:   r;   r    r<   r=   r   r   r   r   rK   B   s   zFTPClient.connectc                 C   s   t | dr| j  d S d S )NrJ   )hasattrrJ   quitrL   r   r   r   
disconnectG   s   
zFTPClient.disconnectc              
   C   s   zgzE|    | j| |dd }t|d}| jd| | W d    n1 s-w   Y  | jd| d| d W W |   dS  t	yg } z| j
d	|  W Y d }~W |   d
S d }~ww |   w )N/rbSTOR zFile 'z' uploaded successfully to ''TzFailed to upload file: F)rK   rJ   cwdsplitopen
storbinaryr?   inforO   	Exceptionerror)r   local_file_path
remote_dirfilename
local_fileer   r   r   upload_fileK   s"   
zFTPClient.upload_file)r9   NN)r   r   r   r   r>   rK   rO   ra   r   r   r   r   r8   0   s    
	r8   皙?皙?333333?皙?c                 C   s$   ||  |d|   ||  ||  S )a  
    Calculate the priority score for a campaign.
    
    Args:
    - TSA (float): Target Show Alignment value (between 0 and 1).
    - ARF (float): Airing Requirement Fulfillment value (between 0 and 1).
    - U (float): Urgency value (between 0 and 1).
    - P (float): Position value (between 0 and 1).
    - W_TSA (float): Weight for Target Show Alignment (default is 0.4).
    - W_ARF (float): Weight for Airing Requirement Fulfillment (default is 0.2).
    - W_U (float): Weight for Urgency (default is 0.3).
    - W_P (float): Weight for Position (default is 0.1).
    
    Returns:
    - float: Priority score for the campaign.
    r   r   )TSAARFUPZW_TSAZW_ARFZW_UZW_Pr   r   r   calculate_priority_score[   s   $rj   )r   
error_permc                   @   sb   e Zd ZdZd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S )FTPConnectoraf  
    A class to manage FTP connections and operations.

    Attributes:
        host (str): The FTP server hostname.
        port (int): The port number of the FTP server.
        username (str): The username for authentication.
        password (str): The password for authentication.
        ftp (FTP): An instance of the FTP class for FTP operations.
    Nc                 C   s"   || _ || _|| _|| _d| _dS )a  
        Initializes the FTPConnector with server details.

        Args:
            host (str): The FTP server hostname.
            port (int, optional): The port number of the FTP server. Defaults to None.
            username (str, optional): The username for authentication. Defaults to None.
            password (str, optional): The password for authentication. Defaults to None.
        N)hostr;   r<   r=   rJ   )r   rm   r;   r<   r=   r   r   r   r   }   s
   

zFTPConnector.__init__c              
   C   s   z'| j rt | _| j| j| j  nt| j| _| j| j| j td W dS  t	yA } ztd|  W Y d}~dS d}~ww )zj
        Connects to the FTP server.

        Raises:
            Exception: If connection fails.
        zConnected to FTP server.z Error connecting to FTP server: N)
r;   r   rJ   rK   rm   r    r<   r=   printrZ   r   r`   r   r   r   rK      s   zFTPConnector.connectc              
   C   sZ   z| j r| j   td W dS W dS  ty, } ztd|  W Y d}~dS d}~ww )zr
        Disconnects from the FTP server.

        Raises:
            Exception: If disconnection fails.
        zDisconnected from FTP server.z%Error disconnecting from FTP server: N)rJ   rN   rn   rZ   ro   r   r   r   rO      s   
zFTPConnector.disconnectc              
   C   s   zHz |    | jr| j }td |D ]}t| qntd W n ty: } ztd|  W Y d}~nd}~ww W |   dS W |   dS |   w )z0
        Lists files on the FTP server.
        zList of files on server:Not connected to FTP server.zError listing files: N)rK   rJ   nlstrn   rZ   rO   )r   filesfiler`   r   r   r   
list_files   s$   

zFTPConnector.list_filesc              
   C   s   zmzE|    | jrAt|d}|dd }| j| | jd| | W d   n1 s0w   Y  td| d| d ntd	 W n ty_ } ztd
|  W Y d}~nd}~ww W |   dS W |   dS |   w )a  
        Uploads a file to the FTP server.

        Args:
            local_path (str): The local path of the file to upload.
            remote_path (str): The remote path where the file will be uploaded.

        Raises:
            Exception: If file upload fails.
        rR   rP   rQ   rS   Nz	Uploaded  to .rp   zError uploading file: )	rK   rJ   rW   rV   rU   rX   rn   rZ   rO   )r   
local_pathremote_pathr_   Zremote_filenamer`   r   r   r   ra      s&   zFTPConnector.upload_filec              
   C   s   zaz9|    | jr5t|d}| jd| |j W d   n1 s$w   Y  td| d| d ntd W n tyS } ztd|  W Y d}~nd}~ww W |   dS W |   dS |   w )	a0  
        Downloads a file from the FTP server to the local machine.

        Args:
            remote_path (str): The remote path of the file on the server.
            local_path (str): The local path where the file will be saved.

        Raises:
            Exception: If file download fails.
        wbzRETR NzDownloaded ru   rv   rp   zError downloading file: )rK   rJ   rW   
retrbinarywritern   rZ   rO   )r   rx   rw   rs   r`   r   r   r   download_file   s"   zFTPConnector.download_filec              
   C      zDz|    | jr| j| td| d ntd W n ty6 } ztd|  W Y d}~nd}~ww W |   dS W |   dS |   w )z
        Creates a directory on the FTP server.

        Args:
            directory (str): The directory path to be created.

        Raises:
            Exception: If directory creation fails.
        zCreated directory: rv   rp   zError creating directory: N)rK   rJ   mkdrn   rZ   rO   r   	directoryr`   r   r   r   create_directory      
zFTPConnector.create_directoryc              
   C   r}   )z
        Deletes a file from the FTP server.

        Args:
            remote_path (str): The remote path of the file to be deleted.

        Raises:
            Exception: If file deletion fails.
        zDeleted file: rv   rp   zError deleting file: N)rK   rJ   deletern   rZ   rO   )r   rx   r`   r   r   r   delete_file  r   zFTPConnector.delete_filec              
   C   r}   )z
        Deletes a directory from the FTP server.

        Args:
            directory (str): The directory path to be deleted.

        Raises:
            Exception: If directory deletion fails.
        zDeleted directory: rv   rp   zError deleting directory: N)rK   rJ   rmdrn   rZ   rO   r   r   r   r   delete_directory!  r   zFTPConnector.delete_directoryc              
   C   s   zHz |    | jr| j|| td| d| d ntd W n ty: } ztd|  W Y d}~nd}~ww W |   dS W |   dS |   w )z
        Renames a file on the FTP server.

        Args:
            from_name (str): The current name of the file.
            to_name (str): The new name for the file.

        Raises:
            Exception: If file renaming fails.
        zRenamed file from ru   rv   rp   zError renaming file: N)rK   rJ   renamern   rZ   rO   )r   	from_nameZto_namer`   r   r   r   rename_file7  s   zFTPConnector.rename_file)NNN)r   r   r   __doc__r   rK   rO   rt   ra   r|   r   r   r   r   r   r   r   r   rl   q   s    
rl   c                 C   s8   t t| d\}}}}|d |d  | |d  }|S )N:i  <   i@B )mapr1   rV   )time_strhoursminutessecondsmicrosecondstotal_secondsr   r   r   hhmmssf_to_secondsP  s   r   c           	      C   s>  ddl m}m} || }ddi}||j}tj| |d}|jd krt|j |d}d| v r9|j|_|	  |S d| v rG|j|_
|	  |S d	| v rU|j|_|	  |S d
| v rc|j|_|	  |S d| v rq|j|_|	  |S d| v r|j|_|	  |S d| v rtd|j |j|_|	  |S |j|_|	  |S d S )Nr   )urlparseparse_qs
User-AgenteMozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36)urlheaderseventjs_startjs_first_quartilejs_midpointjs_third_quartilevast_impressiondoubleclickjs_completezCheck: )urllib.parser   r   queryrequestsgettextrn   tracking_start_statussavetracking_firstquartile_statustracking_midpoint_statustracking_thirdquartile_statusimpression_sprintserve_statusimpression_double_click_statustracking_completed_status)	r   replyr   r   
parsed_urlr   query_paramsresponseevent_valuer   r   r   vast_update_requests[  sT   




r   c                  C   s\   ddl m } m} 	 d}t|}|jdkr,| d }| d d }dd |D }|S d S )Nr   )datetime	timedeltazqhttps://almatv-stor.vizionr.fr/synthesia/almatv/playlist/manager/php/_getPlaylist.php?fields=title,isPub,duration   datac                 S   s(   g | ]}d |v r|d  dkri |qS )isPub1r   ).0itemr   r   r   
<listcomp>  s   ( z%visioner_playlist.<locals>.<listcomp>)r   r   r   r   status_codejson)r   r   r   r   	head_dataplaylist_dataprocessed_datar   r   r   visioner_playlist  s   

r   r   returnc              
   C   s   z#t j| dd}|  |jrtd|   |jW S td|   W dS  t jjyD } ztd|  dt|  W Y d}~dS d}~ww )z
    Fetch XML content from a URL and check status code.
    
    Args:
        url: The URL to send the request to
        
    Returns:
        The XML content as string if successful, None otherwise
       )timeoutz"Successfully fetched content from zNo content received from NzError fetching URL z: )	r   r   Zraise_for_statuscontentrn   r   
exceptionsZRequestExceptionstr)r   r   r`   r   r   r   fetch_xml_from_url  s   
r   xml_contentc              
   C   sT   zt | }td |W S  t jy) } ztdt|  W Y d}~dS d}~ww )z
    Parse XML content into an ElementTree.
    
    Args:
        xml_content: String containing XML data
        
    Returns:
        The root element of the parsed XML, or None if parsing failed
    zSuccessfully parsed XML contentzFailed to parse XML: N)ET
fromstringrn   
ParseErrorr   )r   rootr`   r   r   r   parse_xml_content  s   
r   r   tag_name
attributesc                 C   s  g }g }|  d| }tdt| d| d |D ]Q}d}|r5| D ]\}}	|||	kr4d} nq%|rl|jdd |j D g d	}
|D ]}|j|jd
d |j D d}|
d | qH||
 || q|r}tdt| d ||fS tdt| d| d ||fS )a  
    Extract data from XML elements based on tag name and optional attributes.
    
    Args:
        root: The root XML element
        tag_name: The tag to search for
        attributes: Optional dictionary of attribute names and values to match
                   If None, all elements with the tag_name will be returned
        
    Returns:
        List of dictionaries containing the matched elements' data
    z.//zFound z elements with tag 'rT   TFc                 S      i | ]\}}||qS r   r   r   kvr   r   r   
<dictcomp>      z.extract_data_by_attributes.<locals>.<dictcomp>)r   r   childrenc                 S   r   r   r   r   r   r   r   r     r   )tagr   r   r   z
Extracted z% elements matching attribute criteria)	findallrn   lenitemsr   r   attribr   append)r   r   r   resultsZelements_rootelementselementZmatches_criteria	attr_name
attr_valueZelement_datachildZ
child_datar   r   r   extract_data_by_attributes  s>   

r   c               	   C   s  ddl m}  dd l}ddlm} ddlm} ddlm} dd l	}dd l
}dd l}dd lm  m} 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ddd d!d"d#d$}	d%d&dd'd(d)d*d+d,}
d)}d-}d.d/i}| j|||
d0}d1|d2d3d4d5|d2d3d4d6|d2d3d4d7|d2d3d4d8|d2d3d4g}d9d:id9d;id9d<id9d=id9d>ig}d S )?Nr   )	call_vastr   )HTTPProxyAuth)ThreadPoolExecutor)	parse_url
Feuilletoni! Magazinei% u   Mini-Sériez	Magazine z
Mini-SerieSerieInformationi+ zMagazine Sportifi- zDessin Animei$ zMagazine Sportif TelefilmDocumentairei# 	Religieuxi( SportzLong Metragei" NewszLong-Metragei& i' i, i. )zDes Histoires Et Des Hommesu   SérieMusiqueTheatre	SpectacleJeux720567zAbtal albiharzar-MA   2M_TVFrance)whcontent_genrecontent_titlelanguagepod_max_durchannel_namecountrya  https://tv.springserve.com/vast/850576?w=1920&h=1080&cb={{CACHEBUSTER}}&ip={{IP}}&ua={{USER_AGENT}}&pod_max_dur={{POD_MAX_DUR}}&pod_ad_slots={{POD_AD_SLOTS}}&app_bundle={{APP_BUNDLE}}&app_name={{APP_NAME}}&app_store_url={{APP_STORE_URL}}&did={{DEVICE_ID}}&us_privacy={{US_PRIVACY}}r   r   )r   num_requestsparamsz185.124.241.179:1232314a2f5dfde475
51ae51af21)httpauthz89.116.242.185:12323z45.140.244.198:12323z193.106.198.128:12323z136.175.224.210:12323r
  z5http://14a2f5dfde475:51ae51af21@185.124.241.179:12323z4http://14a2f5dfde475:51ae51af21@89.116.242.185:12323z4http://14a2f5dfde475:51ae51af21@45.140.244.198:12323z5http://14a2f5dfde475:51ae51af21@193.106.198.128:12323z5http://14a2f5dfde475:51ae51af21@136.175.224.210:12323)tasksr   r   requests.authr   concurrent.futuresr   urllib3.utilr   randomr   osxml.etree.ElementTreeetreeElementTreedelay)r   r   r   r   r   r  r   r  r   iab_catr  r  r   r   vast
proxy_listproxies0r   r   r   call_vast_api  s   	

	r  )rb   rc   rd   re   r   )'	functoolsr   django.httpr   django.shortcutsr   modelsr   ftplibr   r@   r   r   typingr	   r
   r   r   r  r  r  r   r   r*   r,   r7   r8   rj   rk   rl   r   r   r   r   r   Elementr   r   r  r   r   r   r   <module>   s4    
+ `/2<