B
    *gW                 @   s`  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d-ddZd dlm	Z	mZ G dd dZdd Zdd Zd d! Z e!ee! d"d#d$Z"e!eej# d%d&d'Z$d.ej#e!ee!e!f eee!ef  d(d)d*Z%d+d, Z&dS )/    )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 )N)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                sV   d| j krJ| j d rJ| j d d krJtjj| j d dd krJ | f||S tdS d S )Nid_user)r   login)sessionr   objectsfilterr   )requestargskwargs)funcr   r   wrapper   s    :zcheck_user.<locals>.wrapper)r   )r%   r&   r   )r%   r   
check_user   s    r'   c               @   s   e Zd Zdd ZdS )NoVastResultc             C   s   || _ || _t|| _d S )N)id_campaign	total_adsinttotal_impressions)r   r)   r*   r,   r   r   r   r   %   s    zNoVastResult.__init__N)r   r   r   r   r   r   r   r   r(   $   s   r(   c               @   s   e Zd Zdd ZdS )
VastResultc             C   s   || _ || _t|| _d S )N)r)   r*   r+   r,   )r   r)   r*   r,   r   r   r   r   +   s    zVastResult.__init__N)r   r   r   r   r   r   r   r   r-   *   s   r-   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 )N)
ftp_serverportusernamepassword_setup_loggerlogger)r   r0   r1   r2   r3   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   r5   	formatterchr   r   r   r4   9   s    



zFTPClient._setup_loggerc             C   s0   t  | _| j| j| j | j| j| j d S )N)r   ftpconnectr0   r1   r   r2   r3   )r   r   r   r   rA   B   s    zFTPClient.connectc             C   s   t | dr| j  d S )Nr@   )hasattrr@   quit)r   r   r   r   
disconnectG   s    
zFTPClient.disconnectc          
   C   s   zyj|    | j| |dd }t|d}| jd| | W d Q R X | jd| d| d dS  tk
r } z| j	d	|  d
S d }~X Y nX W d | 
  X d S )N/rbzSTOR zFile 'z' uploaded successfully to ''TzFailed to upload file: F)rA   r@   cwdsplitopen
storbinaryr5   info	ExceptionerrorrD   )r   local_file_path
remote_dirfilename
local_fileer   r   r   upload_fileK   s    zFTPClient.upload_file)r/   NN)r   r   r   r   r4   rA   rD   rU   r   r   r   r   r.   0   s
   
	r.   皙?皙?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    r^   )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)hostr1   r2   r3   r@   )r   ra   r1   r2   r3   r   r   r   r   }   s
    
zFTPConnector.__init__c          
   C   s   yL| j r$t | _| j| j| j  nt| j| _| j| j| j td W n0 t	k
r| } ztd|  W dd}~X Y nX dS )zj
        Connects to the FTP server.

        Raises:
            Exception: If connection fails.
        zConnected to FTP server.z Error connecting to FTP server: N)
r1   r   r@   rA   ra   r   r2   r3   printrN   )r   rT   r   r   r   rA      s    zFTPConnector.connectc          
   C   sR   y| j r| j   td W n0 tk
rL } ztd|  W dd}~X Y nX dS )zr
        Disconnects from the FTP server.

        Raises:
            Exception: If disconnection fails.
        zDisconnected from FTP server.z%Error disconnecting from FTP server: N)r@   rC   rb   rN   )r   rT   r   r   r   rD      s    
zFTPConnector.disconnectc          
   C   s   zzyD|    | jr<| j }td x|D ]}t| q*W ntd W n0 tk
rv } ztd|  W dd}~X Y nX W d|   X dS )z0
        Lists files on the FTP server.
        zList of files on server:zNot connected to FTP server.zError listing files: N)rA   r@   nlstrb   rN   rD   )r   filesfilerT   r   r   r   
list_files   s    

$zFTPConnector.list_filesc          
   C   s   zyv|    | jrnt|d4}|dd }| j| | jd| | W dQ R X td| d| d ntd	 W n0 tk
r } ztd
|  W dd}~X Y nX W d|   X dS )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.
        rG   rE   rF   zSTOR Nz	Uploaded z to .zNot connected to FTP server.zError uploading file: )	rA   r@   rK   rJ   rI   rL   rb   rN   rD   )r   
local_pathremote_pathrS   Zremote_filenamerT   r   r   r   rU      s    $zFTPConnector.upload_filec          
   C   s   zy^|    | jrVt|d}| jd| |j W dQ R X td| d| d ntd W n0 tk
r } ztd|  W dd}~X Y nX W d|   X dS )	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 z to rg   zNot connected to FTP server.zError downloading file: )rA   r@   rK   
retrbinarywriterb   rN   rD   )r   ri   rh   re   rT   r   r   r   download_file   s     $zFTPConnector.download_filec          
   C   s~   zny8|    | jr0| j| td| d ntd W n0 tk
rj } ztd|  W dd}~X Y nX W d|   X dS )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: rg   zNot connected to FTP server.zError creating directory: N)rA   r@   mkdrb   rN   rD   )r   	directoryrT   r   r   r   create_directory   s    
$zFTPConnector.create_directoryc          
   C   s~   zny8|    | jr0| j| td| d ntd W n0 tk
rj } ztd|  W dd}~X Y nX W d|   X dS )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: rg   zNot connected to FTP server.zError deleting file: N)rA   r@   deleterb   rN   rD   )r   ri   rT   r   r   r   delete_file  s    
$zFTPConnector.delete_filec          
   C   s~   zny8|    | jr0| j| td| d ntd W n0 tk
rj } ztd|  W dd}~X Y nX W d|   X dS )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: rg   zNot connected to FTP server.zError deleting directory: N)rA   r@   rmdrb   rN   rD   )r   ro   rT   r   r   r   delete_directory!  s    
$zFTPConnector.delete_directoryc          
   C   s   zvy@|    | jr8| j|| td| d| d ntd W n0 tk
rr } ztd|  W dd}~X Y nX W d|   X dS )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 z to rg   zNot connected to FTP server.zError renaming file: N)rA   r@   renamerb   rN   rD   )r   	from_nameZto_namerT   r   r   r   rename_file7  s    $zFTPConnector.rename_file)NNN)r   r   r   __doc__r   rA   rD   rf   rU   rm   rp   rr   rt   rw   r   r   r   r   r`   q   s   

r`   c             C   s8   t t| d\}}}}|d |d  | |d  }|S )N:i  <   i@B )mapr+   rJ   )time_strhoursminutessecondsmicrosecondstotal_secondsr   r   r   hhmmssf_to_secondsP  s    r   c       	      C   s4  ddl m}m} || }ddi}||j}tj| |d}|jd kr0t|j |d}d| krr|j|_|	  nd| kr|j|_
|	  nd	| kr|j|_|	  nd
| kr|j|_|	  nld| kr|j|_|	  nRd| kr|j|_|	  n8d| krtd|j |j|_|	  n|j|_|	  |S d S )Nr   )urlparseparse_qsz
User-AgentzeMozilla/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textrb   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[  sB    










r   c              C   s^   ddl m } m} d}t|}|jdkrV| d }| d d }dd |D }|S 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 |kr|d  dkr|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   yFt j| dd}|  |jr2td|   |jS td|   dS W n> t jjk
r } ztd|  dt|  dS d}~X Y nX dS )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   raise_for_statuscontentrb   r   
exceptionsRequestExceptionstr)r   r   rT   r   r   r   fetch_xml_from_url  s    
r   )xml_contentr   c          
   C   sR   yt | }td |S  t jk
rL } ztdt|  dS d}~X Y nX dS )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
fromstringrb   
ParseErrorr   )r   rootrT   r   r   r   parse_xml_content  s    
r   )r   tag_name
attributesr   c             C   s   g }g }|  d| }tdt| d| d x|D ]}d}|rnx(| D ]\}}	|||	krNd}P qNW |r8|jdd |j D g d	}
x:|D ]2}|j|jd
d |j D d}|
d | qW ||
 || q8W |rtdt| d n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 'rH   TFc             S   s   i | ]\}}||qS r   r   )r   kvr   r   r   
<dictcomp>  s    z.extract_data_by_attributes.<locals>.<dictcomp>)r   r   childrenc             S   s   i | ]\}}||qS r   r   )r   r   r   r   r   r   r     s    )tagr   r   r   z
Extracted z% elements matching attribute criteria)	findallrb   lenitemsr   r   attribr   append)r   r   r   resultsZelements_rootelementselementZmatches_criteria	attr_nameZ
attr_valueZelement_datachildZ
child_datar   r   r   extract_data_by_attributes  s4    


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} 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|||
d }d!|d"d#d$d%|d"d#d$d&|d"d#d$d'|d"d#d$d(|d"d#d$g}d)d*id)d+id)d,id)d-id)d.ig}d S )/Nr   )	call_vastr   )HTTPProxyAuth)ThreadPoolExecutor)	parse_urli! i% i+ i- i$ i# i( i" i& i' i, i. )
FeuilletonZMagazineu   Mini-Sériez	Magazine z
Mini-SerieZSerieZInformationzMagazine SportifzDessin AnimezMagazine Sportif ZTelefilmZDocumentaireZ	ReligieuxZSportzLong MetrageZNewszLong-MetragezDes Histoires Et Des Hommesu   SérieZMusiqueZTheatreZ	SpectacleZJeux720567zDessin Animez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}}z
User-AgentzeMozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36)r   num_requestsparamsz185.124.241.179:12323Z14a2f5dfde475Z
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   Ziab_catr   r   r   r   vastZ
proxy_listZproxies0r   r   r   call_vast_api  sl    
	r   )rV   rW   rX   rY   )N)'	functoolsr   django.httpr   django.shortcutsr   modelsr   ftplibr   r6   r   r   typingr   r	   r
   r   r   r   r   r   r   r'   r(   r-   r.   r^   r_   r`   r   r   r   r   r   Elementr   r   r   r   r   r   r   <module>   s2   +
 `/,<