U
    m5hX                     @   s\  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 dd 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)FTPN)DictAnyOptionalListc              	   C   s:   t |d | d}|  D ]}|| qW 5 Q R X d S )N/zwb+)openchunkswrite)filepathfilenamedestinationchunk r   */var/www/html/Focus/src/apps/core/utils.pyhandle_uploaded_file   s    r   c                   @   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   r   r   __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                    s>   d| j kr2| j d r2| j d d kr2 | f||S tdS d S )Nid_userz
auth:login)sessionr   )requestargskwargsfuncr   r   wrapper   s    "zcheck_user.<locals>.wrapperr   )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 r   id_campaign	total_adsinttotal_impressionsr   r2   r3   r5   r   r   r   r   *   s    zNoVastResult.__init__Nr$   r%   r&   r   r   r   r   r   r0   )   s   r0   c                   @   s   e Zd Zdd ZdS )
VastResultc                 C   s   || _ || _t|| _d S r   r1   r6   r   r   r   r   0   s    zVastResult.__init__Nr7   r   r   r   r   r8   /   s   r8   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   7   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?   >   s    



zFTPClient._setup_loggerc                 C   s0   t  | _| j| j| j | j| j| j d S r   )r   ftpconnectr;   r<   loginr=   r>   r   r   r   r   rL   G   s    zFTPClient.connectc                 C   s   t | dr| j  d S )NrK   )hasattrrK   quitrN   r   r   r   
disconnectL   s    
zFTPClient.disconnectc              
   C   s   zzp|   | j| |dd }t|d}| jd| | W 5 Q R X | jd| d| d W W FdS  t	k
r } z | j
d	|  W Y W d
S d }~X Y nX W 5 |    X d S )Nr   rbSTOR zFile 'z' uploaded successfully to ''TzFailed to upload file: F)rQ   rL   rK   cwdsplitr   
storbinaryr@   info	Exceptionerror)r   local_file_path
remote_dirr   
local_fileer   r   r   upload_fileP   s    
 zFTPClient.upload_file)r:   NN)r$   r%   r&   r   r?   rL   rQ   r`   r   r   r   r   r9   5   s
   
	r9   皙?皙?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   )ZTSAZARFUPZW_TSAZW_ARFZW_UZW_Pr   r   r   calculate_priority_score`   s    rh   )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>   rK   )r   rk   r<   r=   r>   r   r   r   r      s
    
zFTPConnector.__init__c              
   C   s   zL| j r$t | _| j| j| j  nt| j| _| j| j| j td W n0 t	k
r| } ztd|  W 5 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)
r<   r   rK   rL   rk   rM   r=   r>   printrZ   r   r_   r   r   r   rL      s    zFTPConnector.connectc              
   C   sR   z| j r| j   td W n0 tk
rL } ztd|  W 5 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)rK   rP   rl   rZ   rm   r   r   r   rQ      s    
zFTPConnector.disconnectc              
   C   s   zvz@|   | jr8| j }td |D ]}t| q(ntd W n0 tk
rr } ztd|  W 5 d}~X Y nX W 5 |    X dS )z0
        Lists files on the FTP server.
        zList of files on server:Not connected to FTP server.zError listing files: N)rQ   rL   rK   nlstrl   rZ   )r   filesr   r_   r   r   r   
list_files   s    
$zFTPConnector.list_filesc              
   C   s   zzv|   | jrnt|d4}|dd }| j| | jd| | W 5 Q R X td| d| d ntd W n0 tk
r } ztd	|  W 5 d
}~X Y nX W 5 |    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.
        rS   r   rR   rT   z	Uploaded  to .rn   zError uploading file: N)	rQ   rL   rK   r   rW   rV   rX   rl   rZ   )r   
local_pathremote_pathr^   Zremote_filenamer_   r   r   r   r`      s    $zFTPConnector.upload_filec              
   C   s   zz^|   | jrVt|d}| jd| |j W 5 Q R X td| d| d ntd W n0 tk
r } ztd|  W 5 d}~X Y nX W 5 |    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 zDownloaded rr   rs   rn   zError downloading file: N)rQ   rL   rK   r   
retrbinaryr   rl   rZ   )r   ru   rt   r   r_   r   r   r   download_file   s     $zFTPConnector.download_filec              
   C   s~   znz8|   | jr0| j| td| d ntd W n0 tk
rj } ztd|  W 5 d}~X Y nX W 5 |    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: rs   rn   zError creating directory: N)rQ   rL   rK   mkdrl   rZ   r   	directoryr_   r   r   r   create_directory   s    
$zFTPConnector.create_directoryc              
   C   s~   znz8|   | jr0| j| td| d ntd W n0 tk
rj } ztd|  W 5 d}~X Y nX W 5 |    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: rs   rn   zError deleting file: N)rQ   rL   rK   deleterl   rZ   )r   ru   r_   r   r   r   delete_file  s    
$zFTPConnector.delete_filec              
   C   s~   znz8|   | jr0| j| td| d ntd W n0 tk
rj } ztd|  W 5 d}~X Y nX W 5 |    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: rs   rn   zError deleting directory: N)rQ   rL   rK   rmdrl   rZ   rz   r   r   r   delete_directory&  s    
$zFTPConnector.delete_directoryc              
   C   s   zvz@|   | jr8| j|| td| d| d ntd W n0 tk
rr } ztd|  W 5 d}~X Y nX W 5 |    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 rr   rs   rn   zError renaming file: N)rQ   rL   rK   renamerl   rZ   )r   	from_nameZto_namer_   r   r   r   rename_file<  s    $zFTPConnector.rename_file)NNN)r$   r%   r&   __doc__r   rL   rQ   rq   r`   rx   r|   r~   r   r   r   r   r   r   rj   v   s   
rj   c                 C   s8   t t| d\}}}}|d |d  | |d  }|S )N:i  <   i@B )mapr4   rW   )time_strhoursminutessecondsmicrosecondstotal_secondsr   r   r   hhmmssf_to_secondsU  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_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eventZjs_startZjs_first_quartileZjs_midpointZjs_third_quartileZvast_impressionZdoubleclickZjs_completezCheck: )urllib.parser   r   queryrequestsgettextrl   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responseZevent_valuer   r   r   vast_update_requests`  sF     










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   zJt j| dd}|  |jr4td|   |jW S td|   W dS W nD t jjk
r } z"td|  dt|  W Y 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contentrl   r   
exceptionsRequestExceptionstr)r   r   r_   r   r   r   fetch_xml_from_url  s    

r   )xml_contentr   c              
   C   sZ   zt | }td |W S  t jk
rT } ztdt|  W Y 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
fromstringrl   
ParseErrorr   )r   rootr_   r   r   r   parse_xml_content  s    
r   )r   tag_name
attributesr   c                 C   s  g }g }|  d| }tdt| d| d |D ]}d}|rj| D ]\}}	|||	krJd} qjqJ|r6|jdd |j D g d	}
|D ]2}|j|jd
d |j D d}|
d | q||
 || q6|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 'rU   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     s      )tagr   r   r   z
Extracted z% elements matching attribute criteria)	findallrl   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  s8    
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 )/Nre   )	call_vastr   )HTTPProxyAuth)ThreadPoolExecutor)	parse_urli! i% i+ i- i$ i# i( i" i& i' i, i. )Z
FeuilletonZMagazineu   Mini-Sériez	Magazine z
Mini-SerieZSerieZInformationzMagazine SportifDessin AnimezMagazine Sportif ZTelefilmZDocumentaireZ	ReligieuxZSportzLong MetrageZNewszLong-MetragezDes Histoires Et Des Hommesu   SérieZMusiqueZTheatreZ	SpectacleZJeuxZ720Z567r   zAbtal albiharzar-MA   Z2M_TVFrance)whZcontent_genreZcontent_titlelanguageZ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: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   Zrequests.authr   concurrent.futuresr   Z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  sx    
	 r   )ra   rb   rc   rd   )N)&	functoolsr   django.httpr   django.shortcutsr   ftplibr   rA   r   r   typingr   r   r	   r
   r   r   r   r   r   r   r/   r0   r8   r9   rh   ri   rj   r   r   r   r   r   Elementr   r   r   r   r   r   r   <module>   s2   +
 `/,<