HEX
Server: Apache
System: Linux insrv.serversdaddy.com 5.14.0-362.24.2.el9_3.x86_64 #1 SMP PREEMPT_DYNAMIC Sat Mar 30 14:11:54 EDT 2024 x86_64
User: jsaha (1066)
PHP: 8.3.6
Disabled: exec,passthru,shell_exec,system
Upload Files
File: //lib/python3.9/site-packages/__pycache__/speedtest.cpython-39.pyc
a

�;8dM��@sHddlZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZ
zddlZejZWney�dZeZYn0dZGdd�de�Zdae�Zejdd�dkZejdd�dkZejdd�d	kZzddlZWn:e�y0zddlZWne�y*dZYn0Yn0z<ddlmmZ zdd
lm!Z"Wne�yjYn0Wn0e�y�ddl#m$Z%ddlm&Z&dZ Yn0z4dd
l'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1WnDe�ydd
l2m(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1Yn0zddl3m4Z4m5Z5Wn$e�yRddl6m4Z4m5Z5Yn0zddl3m7Z7Wn>e�y�zddl6m7Z7Wne�y�dZ7Yn0Yn0zddl3m8Z8Wne�y�dZ8Yn0zddl9m9Z9Wn e�y�ddl:m9Z9Yn0zddl;m;Z;Wn e�y0ddl<m;Z;Yn0zddl;m=Z=WnFe�y�zddl<m=Z=Wn e�y�ddl>m=Z=Yn0Yn0zddl?m@Z@Wn e�y�ddl@m@Z@Yn0z(ddlAmBZCddlAmDZEeFZGeHZIeJZKWn8e�yddlLmMZCddlLmNZEdZGdZIdZKYn0zddlOmPZPdZQWnNe�y�zddlPmPZPdZQWn$e�yzddlRmPZPmQZQYn0Yn0zddlSZSWn�e�yddlTZTddlRmUZUmVZVGdd �d eU�ZWeXeTd!�ZYzeWejZ�Z[eWej\�Z]Wn e^�yejZZ[ej\Z]Yn0d"d#�Z_d$d%�Z`Yn0[Sd&d#�Z_d'd%�Z`e�rBe jajbZcne�rNe"jdZce�r^ejejfZgnejejhZgzJddliZizeijjfZkWnel�y�em�ZkYn0e*e+ejneijoe5fekZpWn&e�y�dZie*e+ejne5fZpYn0Gd(d)�d)eq�ZrGd*d+�d+er�ZsGd,d-�d-er�ZtGd.d/�d/er�ZuGd0d1�d1er�ZvGd2d3�d3et�ZwGd4d5�d5et�ZxGd6d7�d7er�ZyGd8d9�d9er�ZzGd:d;�d;er�Z{Gd<d=�d=er�Z|Gd>d?�d?er�Z}Gd@dA�dAer�Z~GdBdC�dCer�ZGdDdE�dEer�Z�GdFdG�dGer�Z�edfdHdI�Z�GdJdK�dKe4�Z�e7�rGdLdM�dMe7�Z�d�dNdO�Z�GdPdQ�dQe,�Z�GdRdS�dSe,�Z�d�dUdV�Z�GdWdX�dXe�Z�dYdZ�Z�d[d\�Z�d]d^�Z�d�d`da�Z�d�dbdc�Z�ddde�Z�dfdg�Z�dhdi�Z�djdk�Z�Gdldm�dmeje�Z�Gdndo�doe�Z�Gdpdq�dqeje�Z�Gdrds�dse�Z�Gdtdu�due�Z�dvdw�Z�dxdy�Z�d�d{d|�Z�d}d~�Z�dd��Z�d�d�d��Z�d�d��Z�d�d��Z�e�d�k�rDe��dS)��Nz2.1.3c@seZdZdZedd��ZdS)�FakeShutdownEventz�Class to fake a threading.Event.isSet so that users of this module
    are not required to register their own threading.Event()
    cCsdS)z#Dummy method to always return falseF�rrr�-/usr/lib/python3.9/site-packages/speedtest.py�isSet.szFakeShutdownEvent.isSetN)�__name__�
__module__�__qualname__�__doc__�staticmethodrrrrrr)srF�)r�)r�)�r)�_Element)�minidom)�
ExpatError)
�urlopen�Request�	HTTPError�URLError�AbstractHTTPHandler�ProxyHandler�HTTPDefaultErrorHandler�HTTPRedirectHandler�HTTPErrorProcessor�OpenerDirector)�HTTPConnection�
BadStatusLine)�HTTPSConnection)�
FakeSocket)�Queue)�urlparse)�parse_qs)�md5)�ArgumentParser)�SUPPRESS)�OptionParser)�
SUPPRESS_HELP�int�string�float)�StringIO)r+�BytesIO)�
TextIOWrapper�FileIOcs,eZdZdZ�fdd�Z�fdd�Z�ZS)�_Py3Utf8OutputzVUTF-8 encoded wrapper around stdout for py3, to override
        ASCII stdout
        cs(t|��d�}tt|�j|ddd�dS)N�w�utf8�strict)�encoding�errors)r.�fileno�superr/�__init__)�self�f�kwargs�buf��	__class__rrr7�s
�z_Py3Utf8Output.__init__cstt|��|�|��dS�N)r6r/�write�flush)r8�sr<rrr?�sz_Py3Utf8Output.write)rrrr	r7r?�
__classcell__rrr<rr/�sr/�printcCs|S)zNo-op encode to utf-8 for py3r��vrrr�to_utf8�srFcOs<|�d�tjkrt|d<n|�dt�|d<t|i|��dS)z>Wrapper function for py3 to print, with a utf-8 encoded stdout�fileN)�get�sys�stderr�_py3_utf8_stderr�_py3_utf8_stdout�
_py3_print��argsr:rrr�print_�s
rPcCs*z|�dd�WSty$|YS0dS)z)Encode value to utf-8 if possible for py2r1r2N)�encode�AttributeErrorrDrrrrF�sc
s.|�dtj���durdS�fdd�}d}|�dd�}|dur`t|t�rNd}nt|t�s`td��|�d	d�}|dur�t|t�r�d}nt|t�s�td
��|r�td��|s�|D]}t|t�r�d}q�q�|r�td�}td
�}nd}d
}|dur�|}|dur�|}t|�D] \}	}|	�r||�||��q||�dS)z�The new-style print function for Python 2.4 and 2.5.

        Taken from https://pypi.python.org/pypi/six/

        Modified to set encoding to UTF-8 always, and to flush after write
        rGNcslt|t�st|�}d}t�t�rVt|t�rV|durVt�dd�}|durJd}|�||�}��|����dS)Nr1r4r2)	�
isinstanceZ
basestring�strrG�unicode�getattrrQr?r@)�datar3r4��fprrr?�s

��
zprint_.<locals>.writeF�sepTzsep must be None or a string�endzend must be None or a stringz$invalid keyword arguments to print()�
� )�poprI�stdoutrSrUrT�	TypeError�	enumerate)
rOr:r?Zwant_unicoderZr[�arg�newline�space�irrXrrP�sL





c@seZdZdZdS)�SpeedtestExceptionzBase exception for this moduleN�rrrr	rrrrrf(srfc@seZdZdZdS)�SpeedtestCLIErrorz9Generic exception for raising errors during CLI operationNrgrrrrrh,srhc@seZdZdZdS)�SpeedtestHTTPErrorz#Base HTTP exception for this moduleNrgrrrrri0sric@seZdZdZdS)�SpeedtestConfigErrorzConfiguration XML is invalidNrgrrrrrj4srjc@seZdZdZdS)�SpeedtestServersErrorzServers XML is invalidNrgrrrrrk8srkc@seZdZdZdS)�ConfigRetrievalErrorzCould not retrieve config.phpNrgrrrrrl<srlc@seZdZdZdS)�ServersRetrievalErrorz(Could not retrieve speedtest-servers.phpNrgrrrrrm@srmc@seZdZdZdS)�InvalidServerIDTypez/Server ID used for filtering was not an integerNrgrrrrrnDsrnc@seZdZdZdS)�NoMatchedServersz!No servers matched when filteringNrgrrrrroHsroc@seZdZdZdS)�SpeedtestMiniConnectFailurez7Could not connect to the provided speedtest mini serverNrgrrrrrpLsrpc@seZdZdZdS)�InvalidSpeedtestMiniServerzjServer provided as a speedtest mini server does not actually appear
    to be a speedtest mini server
    NrgrrrrrqPsrqc@seZdZdZdS)�ShareResultsConnectFailurez6Could not connect to speedtest.net API to POST resultsNrgrrrrrrVsrrc@seZdZdZdS)�ShareResultsSubmitFailurezRUnable to successfully POST results to speedtest.net API after
    connection
    NrgrrrrrsZsrsc@seZdZdZdS)�SpeedtestUploadTimeoutz~testlength configuration reached during upload
    Used to ensure the upload halts when no additional data should be sent
    Nrgrrrrrt`srtc@seZdZdZdS)�SpeedtestBestServerFailurezUnable to determine best serverNrgrrrrrufsruc@seZdZdZdS)�SpeedtestMissingBestServerz?get_best_server not called or not able to determine best serverNrgrrrrrvjsrvc
	Cs�|\}}d}t�||dtj�D]�}|\}}}	}
}d}zFt�|||	�}|turZ|�t|��|rh|�|�|�|�|WStjy�t	�}|dur�|�
�Yq0q|dur�|�n
t�d��dS)a�Connect to *address* and return the socket object.

    Convenience function.  Connect to *address* (a 2-tuple ``(host,
    port)``) and return the socket object.  Passing the optional
    *timeout* parameter will set the timeout on the socket instance
    before attempting to connect.  If no *timeout* is supplied, the
    global default timeout setting returned by :func:`getdefaulttimeout`
    is used.  If *source_address* is set it must be a tuple of (host, port)
    for the socket to bind as a source address before making the connection.
    An host of '' or port 0 tells the OS to use the default.

    Largely vendored from Python 2.7, modified to work with Python 2.4
    Nrz!getaddrinfo returns an empty list)�socketZgetaddrinfoZSOCK_STREAM�_GLOBAL_DEFAULT_TIMEOUTZ
settimeoutr*Zbind�connect�error�
get_exception�close)
Zaddress�timeout�source_address�host�port�err�resZafZsocktype�protoZ	canonnameZsa�sockrrr�create_connectionns(


r�c@s eZdZdZdd�Zdd�ZdS)�SpeedtestHTTPConnectionzUCustom HTTPConnection to support source_address across
    Python 2.4 - Python 3
    cOsF|�dd�}|�dd�}d|_tj|g|�Ri|��||_||_dS�Nr~r}�
)r^�_tunnel_hostrr7r~r}�r8rOr:r~r}rrrr7�sz SpeedtestHTTPConnection.__init__c	Csdz t�|j|jf|j|j�|_Wn0ttfyPt|j|jf|j|j�|_Yn0|j	r`|�
�dS)z3Connect to the host and port specified in __init__.N)rwr�rr�r}r~r�rRr`r��_tunnel�r8rrrry�s
�

�zSpeedtestHTTPConnection.connectN)rrrr	r7ryrrrrr��sr�c@s$eZdZdZdZdd�Zdd�ZdS)�SpeedtestHTTPSConnectionz^Custom HTTPSConnection to support source_address across
        Python 2.4 - Python 3
        i�cOsF|�dd�}|�dd�}d|_tj|g|�Ri|��||_||_dSr�)r^r�rr7r}r~r�rrrr7�sz!SpeedtestHTTPSConnection.__init__cCs<z t�|j|jf|j|j�|_Wn0ttfyPt|j|jf|j|j�|_Yn0|j	r`|�
�tr�zFi}ttd�r�|j	r�|j	|d<n
|j|d<|j
j|jfi|��|_WnBty�t�|j�|_z|j|j_Wnty�Yn0Yn0nHt�r0zt|jt�|j��|_Wnt�y,td��Yn0ntd��dS)z(Connect to a host on a given (SSL) port.Z
SSLContext�server_hostnamez?This version of Python does not support HTTPS/SSL functionalityN)rwr�rr�r}r~r�rRr`r�r��ssl�hasattr�_contextZwrap_socketr�rrf)r8r:rrrry�sL
�

�

��z SpeedtestHTTPSConnection.connectN)rrrr	Zdefault_portr7ryrrrrr��sr�cs����fdd�}|S)z�Cross Python 2.4 - Python 3 callable to build an ``HTTPConnection`` or
    ``HTTPSConnection`` with the args we need

    Called from ``http(s)_open`` methods of ``SpeedtestHTTPHandler`` or
    ``SpeedtestHTTPSHandler``
    cs,|���d���r�|d<�|fi|��S)N�r~r}�context)�update)rr:��
connectionr�r~r}rr�inners�z _build_connection.<locals>.innerr)r�r~r}r�r�rr�r�_build_connection�sr�c@s(eZdZdZd	dd�Zdd�ZejZdS)
�SpeedtestHTTPHandlerz�Custom ``HTTPHandler`` that can build a ``HTTPConnection`` with the
    args we need for ``source_address`` and ``timeout``
    rNr�cCst�||�||_||_dSr>)rr7r~r})r8�
debuglevelr~r}rrrr7szSpeedtestHTTPHandler.__init__cCs|�tt|j|j�|�Sr>)�do_openr�r�r~r}�r8�reqrrr�	http_opens��zSpeedtestHTTPHandler.http_open)rNr�)	rrrr	r7r�r�do_request_Zhttp_requestrrrrr�s

r�c@s(eZdZdZd	dd�Zdd�ZejZdS)
�SpeedtestHTTPSHandlerz�Custom ``HTTPSHandler`` that can build a ``HTTPSConnection`` with the
    args we need for ``source_address`` and ``timeout``
    rNr�cCs"t�||�||_||_||_dSr>)rr7r�r~r})r8r�r�r~r}rrrr7(szSpeedtestHTTPSHandler.__init__cCs|�tt|j|j|jd�|�S)N)r�)r�r�r�r~r}r�r�rrr�
https_open/s��z SpeedtestHTTPSHandler.https_open)rNNr�)	rrrr	r7r�rr�Z
https_requestrrrrr�$s�
r�r�cCs�td|dd�|r0|df}td|fdd�nd}t�t||d�t||d�t�t�t�g}t�}dt�fg|_	|D]}|�
|�qt|S)	z�Function similar to ``urllib2.build_opener`` that will build
    an ``OpenerDirector`` with the explicit handlers we want,
    ``source_address`` for binding, ``timeout`` and our custom
    `User-Agent`
    zTimeout set to %dT��debugrzBinding to source address: %rNr�z
User-agent)�printerrr�r�rrrr�build_user_agentZ
addheadersZadd_handler)r~r}�source_address_tuple�handlers�openerZhandlerrrr�build_opener=s.
����r�c@s eZdZdZdd�Zdd�ZdS)�GzipDecodedResponsez�A file-like object to decode a response encoded with the gzip
    method, as described in RFC 1952.

    Largely copied from ``xmlrpclib``/``xmlrpc.client`` and modified
    to work for py2.4-py3
    cCsftstd��tpt}|�|_|�d�}t|�dkr4qB|j�|�q|j�d�tj	j
|d|jd�dS)NzEHTTP response body is gzip encoded, but gzip support is not available�r�rb)�mode�fileobj)�gziprir,r+�io�read�lenr?�seek�GzipFiler7)r8�response�IO�chunkrrrr7hs
zGzipDecodedResponse.__init__cCs,ztj�|�W|j��n|j��0dSr>)r�r�r|r�r�rrrr|xszGzipDecodedResponse.closeN)rrrr	r7r|rrrrr�asr�cCst��dS)zgHelper function to work with py2.4-py3 for getting the current
    exception in a try/except block
    �)rI�exc_inforrrrr{sr{cCs�|\}}|\}}d}t�||�}t�||�}t�|d�t�|d�t�t�|��t�t�|��t�|d�t�|d�}	dt�t�|	�t�d|	��}
||
}|S)z4Determine distance between 2 sets of [lat,lon] in kmi�rr�)�mathZradiansZsinZcosZatan2Zsqrt)�originZdestinationZlat1Zlon1Zlat2Zlon2ZradiusZdlatZdlon�a�c�drrr�distance�s"���� r�cCsLddt��t��dfdt��ddtf}d�|�}td|d	d
�|S)z0Build a Mozilla/5.0 compatible User-Agent stringzMozilla/5.0z(%s; U; %s; en-us)rz	Python/%sz(KHTML, like Gecko)zspeedtest-cli/%sr]zUser-Agent: %sTr�)�platformZarchitectureZpython_version�__version__�joinr�)Zua_tuple�
user_agentrrrr��s
�
�
r��0c	Cs�|si}|ddkr.dt|�}d||f}n|}d|vr@d}nd}d||ttj��d�|f}|�d	d
i�tddt|�|fd
d�t|||d�S)znBuild a urllib2 request object

    This function automatically adds a User-Agent header to all requests

    r�:)�http�httpsz%s%s�?�&z%s%sx=%s.%s��z
Cache-Controlzno-cache�%s %s)�GETZPOSTTr�)rW�headers)�boolr(�timeit�timer�r�r)	�urlrWr��bump�secure�schemeZschemed_url�delimZ	final_urlrrr�
build_request�s(���r�cCsl|r|j}nt}z6||�}|��|��kr>td|��dd�|dfWStyft�}d|fYS0dS)zyHelper function to catch common exceptions encountered when
    establishing a connection with a HTTP/HTTPS request

    zRedirected to %sTr�FN)�openr�get_full_url�geturlr��HTTP_ERRORSr{)�requestr�Z_open�uh�errr�
catch_request�s
r�cCs>z|jj}Wnty$|j}Yn0|d�dkr:t|�S|S)zzHelper function to return either a Gzip reader if
    ``Content-Encoding`` is ``gzip`` otherwise the response itself

    zcontent-encodingr�)r��	getheaderrRr�)r�r�rrr�get_response_stream�sr�cCs |�|�d}tt|j����S)z�Retrieve an attribute from an XML document and return it in a
    consistent format

    Only used with xml.dom.minidom, which is likely only to be used
    with python versions older than 2.5
    r)�getElementsByTagName�dict�list�
attributes�items)ZdomZtag_name�elemrrr�get_attributes_by_tag_name�sr�csd�fdd�	}|S)zNBuilt in callback function used by Thread classes for printing
    status
    FcsF���rdStj�d�|d|kr8|dur8tj�d�tj��dS)N�.r�Tr\)rrIr_r?r@)�current�total�startr[��shutdown_eventrrr�szprint_dots.<locals>.inner)FFr�r�r�rr�r�
print_dots�sr�cOsdSr>rrNrrr�
do_nothing
sr�c@s"eZdZdZddd�Zdd�ZdS)�HTTPDownloaderz!Thread class for retrieving a URLNcCsXtj�|�||_dg|_||_||_||_|r:|j|_	nt
|_	|rL||_nt�|_dS�Nr)
�	threading�Threadr7r��result�	starttimer}rer��_openerr�_shutdown_eventr)r8rer�r�r}r�r�rrrr7s
zHTTPDownloader.__init__cCs�zrt��|j|jkrp|�|j�}|j��sht��|j|jkrh|j�	t
|�d���|jddkr"qhq"|��Wn"t
y�Ynty�Yn0dS)N�(���r)r��
default_timerr�r}r�r�r�rr��appendr�r�r|�IOErrorr�)r8r9rrr�run&s 
��zHTTPDownloader.run)NN�rrrr	r7r�rrrrr�s
�
r�c@s@eZdZdZddd�Zdd�Zedd��Zdd
d�Zdd
�Z	dS)�HTTPUploaderDataz]File like object to improve cutting off the upload once the timeout
    has been reached
    NcCs8||_||_||_|r||_nt�|_d|_dg|_dSr�)�lengthr�r}r�r�_datar�)r8rr�r}r�rrrr7<szHTTPUploaderData.__init__cCsnd}ttt|j�d��}tp t}z,|d||dt|j�d����|_Wntyhtd��Yn0dS)NZ$0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZgB@zcontent1=%sr�	zMInsufficient memory to pre-allocate upload data. Please use --no-pre-allocate)	r(�roundrr,r+rQr�MemoryErrorrh)r8�charsZ
multiplierr�rrr�pre_allocateJs��
�zHTTPUploaderData.pre_allocatecCs|js|��|jSr>)rrr�rrrrWZszHTTPUploaderData.datar�cCsHt��|j|jkr>|j��s>|j�|�}|j�	t
|��|St��dSr>)r�r�r�r}r�rrWr�r�r�r�rt)r8�nr�rrrr�`s�zHTTPUploaderData.readcCs|jSr>)rr�rrr�__len__iszHTTPUploaderData.__len__)N)r�)
rrrr	r7r�propertyrWr�r	rrrrr7s


	rc@s"eZdZdZddd�Zdd�ZdS)�HTTPUploaderzThread class for putting a URLNcCsftj�|�||_||jj_|_||_d|_||_	||_
|rH|j|_nt
|_|rZ||_nt�|_dSr�)r�r�r7r�rWr�r��sizer�r}rer�r�rr�r)r8rer�r�rr}r�r�rrrr7ps
zHTTPUploader.__init__c	Cs�|j}z�t��|j|jkr�|j��s�z|�|�}Wn8tylt	|j�
�|j�|j
�d�}|�|�}Yn0|�d�|��t|jjj�|_nd|_Wn<ttfy�t|jjj�|_Ynty�d|_Yn0dS)N)rW�r)r�r�r�r�r}r�rr�r`r�r�rWr�rr|�sumr�r�r�rtr�)r8r�r9rrrr��s(�
�

zHTTPUploader.run)NNr�rrrrrms
�
rc@sTeZdZdZddd�Zdd�Zd	d
�Zdd�Zeddd��Z	ddd�Z
ddd�ZdS)�SpeedtestResultsatClass for holding the results of a speedtest, including:

    Download speed
    Upload speed
    Ping/Latency to test server
    Data about server that the test was run against

    Additionally this class can return a result data as a dictionary or CSV,
    as well as submit a POST of the result data to the speedtest.net API
    to get a share results image link.
    rNFcCsv||_||_||_|dur"i|_n||_|p.i|_d|_dtj����|_	d|_
d|_|rd||_nt
�|_||_dS)Nz%sZr)�download�upload�ping�server�client�_share�datetimeZutcnowZ	isoformat�	timestamp�bytes_received�
bytes_sentr�r��_secure)r8rrrrrr�r�rrrr7�s
zSpeedtestResults.__init__cCst|���Sr>)�reprr�r�rrr�__repr__�szSpeedtestResults.__repr__c
Csb|jr|jStt|jdd��}tt|jd��}tt|jdd��}d|jdd|ddd|d	d
|ddtd
|||df����	�dddd|j
d|jd|jdg}ddi}tdd�
|���||jd�}t||jd�\}}|r�t|��|��}	|j}
|��t|
�dk�rtd��t|	���}|�d�}|�rFt|�dk�rNtd��d|d|_|jS) zRPOST data to the speedtest.net API to obtain a share results
        link
        �@�@rzrecommendedserverid=%s�idzping=%szscreenresolution=zpromo=zdownload=%sz
screendpi=z	upload=%sztestmethod=httpzhash=%sz%s-%s-%s-%sZ297aae72ztouchscreen=nonezstartmode=pingselectz
accuracy=1zbytesreceived=%szbytessent=%szserverid=%sZRefererz*http://c.speedtest.net/flash/speedtest.swfz ://www.speedtest.net/api/api.phpr�)rWr�r��r���z)Could not submit results to speedtest.net�resultidr�z&http://www.speedtest.net/result/%s.png)rr(rrrrrr#rQZ	hexdigestrrr�r�rr�r�rrr��coder|rsr"�decoderHr�)
r8rrrZapi_datar�r�r9r�r�r"Zqsargsr!rrr�share�sT
���
zSpeedtestResults.sharec
Cs*|j|j|j|j|j|j|j|j|jd�	S)z Return dictionary of result data)	rrrrrrrr$r)	rrrrrrrrrr�rrrr�s�zSpeedtestResults.dict�,cCs:gd�}t�}tj||dd�}|�dd�|D��|��S)zReturn CSV Headers)
z	Server IDZSponsorzServer NameZ	TimestampZDistanceZPingZDownloadZUploadZSharez
IP Address���	delimiter�lineterminatorcSsg|]}t|��qSr�rF��.0rErrr�
<listcomp>�z/SpeedtestResults.csv_header.<locals>.<listcomp>)r+�csv�writer�writerow�getvalue)r(�row�outr0rrr�
csv_headers
zSpeedtestResults.csv_headercCs�|��}t�}tj||dd�}|dd|dd|dd|d|dd|d	|d
|d|jpfd|jdg
}|�d
d�|D��|��S)zReturn data in CSV formatr&r'rr�sponsor�namerr�rrrZipcSsg|]}t|��qSrr*r+rrrr-%r.z(SpeedtestResults.csv.<locals>.<listcomp>)r�r+r/r0rrr1r2)r8r(rWr4r0r3rrrr/s�zSpeedtestResults.csvcCs.i}|r|�ddd��tj|��fi|��S)zReturn data in JSON format�T)ZindentZ	sort_keys)r��json�dumpsr�)r8Zprettyr:rrrr9(s�zSpeedtestResults.json)rrrNNNF)r%)r%)F)rrrr	r7rr$r�r
r5r/r9rrrrr�s�
=


rc@sreZdZdZddd�Zedd��Zd	d
�Zddd�Zd
d�Z	ddd�Z
ddd�Zedfdd�Z
eddfdd�ZdS)�	Speedtestz>Class for performing standard speedtest.net testing operationsNr�FcCs�i|_||_||_t||�|_||_|r0||_nt�|_|��|durT|j�	|�i|_
g|_i|_t
|jd|j|d�|_dS)Nr)rr�r�)�config�_source_address�_timeoutr�r�rr�r�
get_configr��servers�closest�_bestr�results)r8r<r~r}r�r�rrrr77s&�zSpeedtest.__init__cCs|js|��|jSr>)rB�get_best_serverr�rrr�bestTszSpeedtest.bestcCs�i}trd|d<td||jd�}t||jd�\}}|r>t|��g}t|�}z|�|�d��Wn t	t
fy~tt���Yn0t|d�dkrJq�qJ|�
�|�
�t|j�d	kr�d
Sd���|�}td|d
d�zlzt�|�}Wn(tj�yt�}td|��Yn0|�d�j}	|�d�j}
|�d�j}|�d�j}Wnrt�y�zt�|�}Wn&t�y�t�}td|��Yn0t|d�}	t|d�}
t|d�}t|d�}Yn0dd�|	d�d�D�}
t|d�}t|d�}gd�}||dd
�gd�d�}t|d�}tt� ||��}|t|
d�d�}t|d�t|	d �d!d�}t|d"�t|
d"�d�}|j!�"||
||||||d#��zt#|d$�t#|d%�f|_$Wn0t%�y�td&|�&d$�|�&d%�f��Yn0td'|j!d
d�|j!S)(zgDownload the speedtest.net configuration and return only the data
        we are interested in
        r��Accept-Encodingz)://www.speedtest.net/speedtest-config.php�r�r�rr�r�rr Nr&zConfig XML:
%sTr�z)Malformed speedtest.net configuration: %sz
server-configrrrcSsg|]}|rt|��qSr)r()r,rerrrr-�sz(Speedtest.get_config.<locals>.<listcomp>Z	ignoreidsr%�ratioZ
maxchunkcount)i�iiiiiipr�)
i^i�i�r�i�i�i�	i�i�
i�)rrZ
threadsperurl�threadsZthreadcountrZ
testlength)r�ignore_servers�sizes�countsrIr�
upload_max�lat�lonzUnknown location: lat=%r lon=%rz
Config:
%r)'r�r�rr�r�rlr�r�r��OSError�EOFErrorr{r�r|r(r"rQr�r��ET�
fromstring�
ParseErrorrj�find�attribrR�DOM�parseStringrr��splitr�Zceilr<r�r*�lat_lon�
ValueErrorrH)r8r�r�r�r�Zconfigxml_list�streamZ	configxml�rootZ
server_configrrrrJrHrMZup_sizesrKZ
size_countZupload_countrLrIrrrrr?Zs���
�



��
�
�

��
��
zSpeedtest.get_configcCs�|durg}|durg}|j��||fD]F}t|�D]8\}}zt|�||<Wq6tyltd|��Yq60q6q*gd�}i}tr�d|d<g}|D�]�}	�z�td|	|jddf||j	d	�}
t
|
|jd
�\}}|r�|�d|�t
��t|�}
g}z|�|
�d��Wn"ttf�y*t
t���Yn0t|d
�dkr�qBq�|
��|��t|j�dk�rht
��d���|�}td|dd�z�zFzt�|�}Wn(tj�y�t�}td|��Yn0t|d�}WnTt�y"zt� |�}Wn&t!�yt�}td|��Yn0|�"d�}Yn0Wn$t#t$j%j&j!f�yJt
��Yn0|D�]
}z
|j'}Wn&t�y�t(t)|j*�+���}Yn0|�r�t|�,d��|v�r��qPt|�,d��|jdv�sPt|�,d��|v�rؐqPz(t-|j.t/|�,d��t/|�,d��f�}Wnt0�yY�qPYn0||d<z|j|�|�Wn t1�yX|g|j|<Yn0�qPW�q�Wq�t
�y�Yq�Yq�0q�|�s�|�r�|j�s�t2��|jS)z�Retrieve a the list of speedtest.net servers, optionally filtered
        to servers matching those specified in the ``servers`` argument
        Nz)%s is an invalid server type, must be int)z1://www.speedtest.net/speedtest-servers-static.phpz3http://c.speedtest.net/speedtest-servers-static.phpz*://www.speedtest.net/speedtest-servers.phpz,http://c.speedtest.net/speedtest-servers.phpr�rFz
%s?threads=%srIrrGr�%sr�r�rr r&zServers XML:
%sTr�z'Malformed speedtest.net server list: %srrrJrNrOr�)3r@�clearrar(r[rnr�r�r<rr�r�r�rmr�r�rPrQr{r�r|r"rQr�r�rRrSrTrk�
etree_iterrRrWrXrr��SyntaxError�xmlZparsersZexpatrVr�r�r�r�rHr�rZr*�	Exception�KeyErrorro)r8r@�excludeZserver_listrerA�urlsr�r4r�r�r�r�r\Zserversxml_listZ
serversxmlr]�elementsrrVr�rrr�get_servers�s�
�
���
�


���zSpeedtest.get_serversc
	CsBt|�}tj�|d�\}}|r.tj�|�}n|}t|�}t||jd�\}}|r^td|��n|�	�}	|�
�t�d|	�
��}
|
s�dD]p}z|j�d||f�}Wnty�Yq�0|�	����
�}|jdkr�t|���dkr�t�d	|�r�|g}
q�q�|�r|
�std
|��d|ddd|�d
�|
dfddd�g|_|jS)zaInstead of querying for a list of servers, set a link to a
        speedtest mini server
        rrzFailed to connect to %szupload_?[Ee]xtension: "([^"]+)")ZphpZaspZaspxZjspz%s/speedtest/upload.%sr r�z
size=[0-9]z!Invalid Speedtest Mini Server: %szSpeedtest Minir�/)r6r7r�r��latencyr)r!�os�path�splitext�dirnamer�r�r�rpr�r|�re�findallr#r�rc�stripr"r��
splitlines�matchrq�rstripr@)
r8r�urlpartsr7�extr�r�r�r��text�	extensionr9rWrrr�set_mini_serverLsX��
�
�
���
	zSpeedtest.set_mini_serverrcCsn|js|��t|j���D]8}|j|D]"}|j�|�t|j�|kr*qPq*qqVqtd|jdd�|jS)z`Limit servers to the closest speedtest.net servers based on
        geographic distance
        zClosest Servers:
%rTr�)r@rh�sorted�keysrAr�r�r�)r8�limitr�rArrr�get_closest_servers�szSpeedtest.get_closest_serversc
Cs:|s|js|��}|j}|jr*|jdf}nd}t�}i}|D�]�}g}tj�|d�}ttj	�	�d�}d||f}	t
dd�D�]&}
d|	|
f}tdd	|fd
d�t|	�}zz|ddkr�t
|d
|d�}
nt|d
|d�}
d|i}d|d|df}t��}|
jd	||d�|
��}t��|}Wn8t�y^t�}td|d
d�|�d�Yq~Yn0|�d�}t|j�dk�r�|d��k�r�|�|�n
|�d�|
��q~tt|�ddd�}|||<q<zt|���d}Wnt�y�td��Yn0||}||d<||j_ ||j_!|j"�#|�td|d
d�|S)znPerform a speedtest.net "ping" to determine which speedtest.net
        server has the lowest latency
        rNr�r�z%s/latency.txt?x=%srz%s.%sr�r�Tr�r�r�)r~z
User-Agentz%s?%srr8)r�z	ERROR: %rirr z	test=testr
rz-Unable to connect to servers to test latency.rjzBest Server:
%r)$rAr}r=r�rkrlrnr(r�r��ranger�r!r�r�r�r�Zgetresponser�r{r�r��statusrQr|rrrzr{�
IndexErrorrurCrrrBr�)r8r@r�r�rCrZcumr�ZstampZlatency_urlreZthis_latency_urlru�hr�rlr��rr�r�rwZavgZfastestrErrrrD�sv
���





zSpeedtest.get_best_serverc	s�g}�jddD]@}td�jdd�D]&}|�dtj��jd�||f�q*qt|�}g}t|�D]\}}	|�t	|	|�j
d��qh|p��jdd�ddi������fd	d
�}
g����fdd�}t��}tj
|
|||fd
�}
tj
|||fd
�}t���|
��|��t}||
��r.|
jdd��q||��rH|jdd��q.t��}t���j_�jj|�d�j_�jjdk�r�d�jdd<�jjS)z�Test download speed against speedtest.net

        A ``threads`` value of ``None`` will fall back to those dictated
        by the speedtest.net configuration
        rKrrrLz%s/random%sx%s.jpgr�)r�r�rIc	s�t|�D]v\}}t||��jdd�j�jd�}�d�krLtj�d�q2|��|�	|d��dd7<�||dd�qdS)	Nrr�r�r�rI���MbP?Tr��r�)
rar�r<r�r�r�r��sleepr��put��q�requests�
request_countrer��thread��callback�	in_flight�max_threadsr8r�rr�producer�s�z$Speedtest.download.<locals>.producercsft}t��|krb|�d�}||�r0|jdd�q�dd8<��t|j���|j|dd�qdS�NTr��r}rIr��r[)�thread_is_aliver�rHr�r�rr�re�r�r��	_is_aliver��r��finishedr�rr�consumers
z$Speedtest.download.<locals>.consumer��targetrOr�r�� @i���r)r<r~r�rkrlrnrEr�rar�rr r�r�r�r�r�r�r�rrCrr)r8r�rIrfr�_r�r�rer�r�r�r��prod_thread�cons_threadr��stopr�r�r�r�r�r8r�rr�sN�
�
��

�zSpeedtest.downloadTc	s�g}�jddD](}td�jdd�D]}|�|�q*q�jd}g}t|�D]Z\}	}t|d�jdd�jd�}
|r�|
��d|i}|�t�jd	|
�j	|d
�|f�qR|p��jdd�ddi������fdd
�}g����fdd�}
t
|�p�jdd�}tj||||fd�}tj|
||fd�}t
���|��|��t}||��rd|jdd��qJ||��r~|jdd��qdt
��}t���j_�jj|�d�j_�jjS)z�Test upload speed against speedtest.net

        A ``threads`` value of ``None`` will fall back to those dictated
        by the speedtest.net configuration
        rKrrrLrMrr�zContent-lengthr�)r�r�rIc
s�t|d|��D]�\}}t||d�|d�jdd�j�jd�}�d�kr^tj�d�qD|��|�	|d��dd7<�||dd	�qdS)
Nrr�rrr�rIr�Tr�)
rarr<r�r�r�r�r�r�r�r�r�rrr�Vs �	z"Speedtest.upload.<locals>.producercsbt}t��|kr^|�d�}||�r0|jdd�q�dd8<��|j��|j|dd�qdSr�)r�r�rHr�r�r�rer�r�rrr�js
z"Speedtest.upload.<locals>.consumerr�g�������?r�r�)r<r~r�rarr�rr�rErr r�r�r�r�r�r�r�rrCrr)r8r�rrIrKrr�r�r�rerWr�r�r�r�r�r�r�r�rr�rr-s`
����
��

�zSpeedtest.upload)NNr�FN)NN)r)N)rrrr	r7r
rEr?rhryr}rDr�rrrrrrr;4s�

t
~6

LKr;cs�fdd�}|S)zWCatch Ctrl-C key sequence and set a SHUTDOWN_EVENT for our threaded
    operations
    cs"���tddd�t�d�dS)N�
Cancelling...T�rzr)�setr�rI�exit)Zsignum�framer�rrr��szctrl_c.<locals>.innerrr�rr�r�ctrl_c�sr�cCs0tdt�tdtj�dd��t�d�dS)zPrint the versionzspeedtest-cli %sz	Python %sr\r&rN)r�r�rI�version�replacer�rrrrr��sr�r%cCsttj|d��t�d�dS)zPrint the CSV Headers�r(rN)r�rr5rIr�r�rrrr5�sr5cCs�d}t|d�}z|j|_Wnty,Yn0|jddddddd	�|jd
dddddd	�|jd
dddd�|jddddddd�|jdddd�|jddddd�|jddddd�|jdd td!d"�|jd#ddd$d�|jd%ddd&d�|jd'dd(d�|jd)td*d+d,�|jd-td*d.d,�|jd/d0d1�|jd2d3d1�|jd4d5td6d"�|jd7dd8d�|jd9d:dddd;d<�|jd=dd>d�|jd?dttd@�|��}t	|t
��r�|dA}n|}|S)BzAFunction to handle building and parsing of command line argumentsz�Command line interface for testing internet bandwidth using speedtest.net.
--------------------------------------------------------------------------
https://github.com/sivel/speedtest-cli)�descriptionz
--no-downloadrTZstore_constFzDo not perform download test)�dest�default�action�const�helpz--no-uploadrzDo not perform upload testz--singleZ
store_truezYOnly use a single connection instead of multiple. This simulates a typical file transfer.)r�r�r�z--bytes�units)Zbyter�)�bitr�zxDisplay values in bytes instead of bits. Does not affect the image generated by --share, nor output from --json or --csv)r�r�r�r�r�z--sharez]Generate and provide a URL to the speedtest.net share results image, not displayed with --csv)r�r�z--simplez4Suppress verbose output, only show basic information)r�r�r�z--csvzvSuppress verbose output, only show basic information in CSV format. Speeds listed in bit/s and not affected by --bytesz--csv-delimiterr%z<Single character delimiter to use in CSV output. Default ",")r��typer�z--csv-headerzPrint CSV headersz--jsonzwSuppress verbose output, only show basic information in JSON format. Speeds listed in bit/s and not affected by --bytesz--listz:Display a list of speedtest.net servers sorted by distancez--serverr�zCSpecify a server ID to test against. Can be supplied multiple times)r�r�r�z	--excludez?Exclude a server from selection. Can be supplied multiple timesz--miniz URL of the Speedtest Mini server)r�z--sourcezSource IP address to bind toz	--timeoutr�z#HTTP timeout in seconds. Default 10z--securezPUse HTTPS instead of HTTP when communicating with speedtest.net operated serversz--no-pre-allocaterz�Do not pre allocate upload data. Pre allocation is enabled by default to improve upload performance. To support systems with insufficient memory, use this option to avoid a MemoryError)r�r�r�r�r�z	--versionz Show the version number and exitz--debug)r�r�r�r)�	ArgParserZ
add_option�add_argumentrR�PARSER_TYPE_STR�PARSER_TYPE_INT�PARSER_TYPE_FLOAT�ARG_SUPPRESS�
parse_argsrS�tuple)r��parser�optionsrOrrrr��s��

�
�
�
��
�
�
�
�
��
�
�
�����
r�cCsTdtfdtfd�}|��D]4\}}t||d�r|ddurtd|d|f��qdS)	z�Check if an argument was provided that depends on a module that may
    not be part of the Python standard library.

    If such an argument is supplied, and the module does not exist, exit
    with an error stating which module is missing.
    zjson/simplejson python modulezSSL support)r9r�Fr�Nz(%s is not installed. --%s is unavailabler)r9rr�rV�
SystemExit)rOZ
optional_argsrb�inforrr�validate_optional_args�s�
�r�cKsX|rtsdS|r.tj��r$d|}q2d|}n|}|r@tj|d<|sTt|fi|��dS)z4Helper function print a string with various featuresNzDEBUG: %sz	DEBUG: %srG)�DEBUGrIr_�isattyrJrP)r)�quietr�rzr:r4rrrr�s



r�c

Cs�t��}t�tjt|��t�}|jr,t�|js@|js@t	d��t
|j�dkrVt	d��|jrft|j�t
|�t|dd�}|dkr�d}|r�da|js�|js�|jr�d}nd}|js�|jr�d}nd}|s�|r�t}nt|�}td|�zt|j|j|jd	�}Wn0tft�y(td
dd�t	t���Yn0|j�r�z|��Wn0tft�yntddd�t	t���Yn0t |j!�"��D]V\}}|D]F}	d
|	}
zt|
�Wn*t#�y�t�}|j$t$j%k�rȂYn0�q��q~t&�'d�td|j(d|�|j)�s�td|�z|j|j*|j+d�Wn�t,�yNt	dd�-dd�|j*D����Yn`tft�y|tddd�t	t���Yn2t.�y�t	dd�-dd�|j*D����Yn0|j*�r�t
|j*�dk�r�td|�n
td|�|�/�n|j)�r|�/|�0|j)��|j1}td|j*|�|j�rvtd|dt2|�d�|j|d|j3d �td!|jd"d"|j4d|j4df|�n
td#|�|j�r�td$|dt2|�d�|j||j5d|j3d%�td&|jd"d"|j4d|j4df|�n
td'|�td(|�6�dd)�|j�s|j7�r|�7�|j�rptd*|j8|jd"d"|j4d|j4d|jd"d"|j4d|j4df�n0|j�r�t|j|jd+��n|j�r�t|���|j7�r�|�s�td,|�7��d-S).zRun the full speedtest.net testz0Cannot supply both --no-download and --no-uploadr�z*--csv-delimiter must be a single characterr�FZSUPPRESSHELPTz)Retrieving speedtest.net configuration...)r~r}r�z'Cannot retrieve speedtest configurationr�z%Cannot retrieve speedtest server listz:%(id)5s) %(sponsor)s (%(name)s, %(country)s) [%(d)0.2f km]rz Testing from %(isp)s (%(ip)s)...rz'Retrieving speedtest.net server list...)r@rezNo matched servers: %sz, css|]}d|VqdS�r^Nr�r,rArrr�	<genexpr>yr.zshell.<locals>.<genexpr>z,%s is an invalid server type, must be an intcss|]}d|VqdSr�rr�rrrr��r.z1Retrieving information for the selected server...z&Selecting best server based on ping...z>Hosted by %(sponsor)s (%(name)s) [%(d)0.2f km]: %(latency)s mszTesting download speed)r&r\r�)Nr�)r�rIzDownload: %0.2f M%s/srzSkipping download testzTesting upload speed)r�rrIzUpload: %0.2f M%s/szSkipping upload testzResults:
%rr�z5Ping: %s ms
Download: %0.2f M%s/s
Upload: %0.2f M%s/sr�zShare results: %sN)9r��Event�signal�SIGINTr�r�r�rrrhr�Z
csv_delimiterr5r�rVr��simpler/r9r�r�r�r;�sourcer}r�rlr�r{r�rhrmrzr@r�r��errnoZEPIPErIr�r<Zminirreror�rnrDryrCr�Zsingler�rr�r$r)
r�rOr�r�Zmachine_formatr�Z	speedtestr�r@r�liner�rCrrr�shell!s

�
�
�
����


��
�����

�����
��r�c	Csxz
t�Wnhty(tddd�YnLttfyrt�}t|dd�dvrnd|}|sbd|}td	|��Yn0dS)
Nr�Tr�r"r�)rrr^z%rz	ERROR: %s)r��KeyboardInterruptr�rfr�r{rV)r��msgrrr�main�s
r��__main__)N)Nr�)NNr�F)N)r%)FFF)�rkror/rIr�r�r�rwr�rr�r�Zxml.parsers.expatrbr�r�Z	GZIP_BASE�ImportError�objectr�rr�rx�version_infoZPY25PLUSZPY26PLUSZPY32PLUSr9Z
simplejsonZxml.etree.ElementTreeZetreeZElementTreerRrZ
ET_ElementZxml.domrrWrZurllib2rrrrrrrrrrZurllib.requestZhttplibrrZhttp.clientrrr Zqueuer!�urllib.parser"ZcgiZhashlibr#�argparser$r�r%r�r(r�rTr�r*r�Zoptparser&r'Z	cStringIOr+r,r�Z__builtin__�builtinsr-r.r/rVrMr_rLrJrKrPrFrPZElement�iterr`Zgetiteratorr��is_aliver�ZisAliver�ZCertificateErrorZ
CERT_ERRORrRr�rzZSSLErrorr�rcrfrhrirjrkrlrmrnrorprqrrrsrtrurvr�r�r�r�r�r�r�r�r{r�r�r�r�r�r�r�r�r�rrrr;r�r�r5r�r�r�r�r�rrrrr�<module>s�



46



=

���
)"B

$
$
&60Z
V
#