E5Network/E5NetworkProxyFactory.py

Wed, 26 May 2010 17:53:53 +0200

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Wed, 26 May 2010 17:53:53 +0200
changeset 286
652f5159f1c3
parent 283
efe6750fb0ec
child 289
baf4c1354c6a
permissions
-rw-r--r--

Prepared to have individual proxies per scheme.

# -*- coding: utf-8 -*-

# Copyright (c) 2010 Detlev Offenbach <detlev@die-offenbachs.de>
#

"""
Module implementing a network proxy factory.
"""

import sys
import os

from PyQt4.QtCore import QUrl, Qt, QCoreApplication
from PyQt4.QtGui import QMessageBox, QDialog
from PyQt4.QtNetwork import QNetworkProxyFactory, QNetworkProxy, QNetworkProxyQuery

from UI.AuthenticationDialog import AuthenticationDialog

import Preferences

class E5NetworkProxyFactory(QNetworkProxyFactory):
    """
    Class implementing a network proxy factory.
    """
    def __init__(self):
        """
        Constructor
        """
        QNetworkProxyFactory.__init__(self)
    
    def queryProxy(self, query):
        """
        Public method to determine a proxy for a given query.
        
        @param query reference to the query object (QNetworkProxyQuery)
        @return list of proxies in order of preference (list of QNetworkProxy)
        """
        if query.queryType() == QNetworkProxyQuery.UrlRequest and \
           query.protocolTag() in ["http", "https", "ftp"] and \
           Preferences.getUI("UseProxy"):
            if Preferences.getUI("UseSystemProxy"):
                proxyList = QNetworkProxyFactory.systemProxyForQuery(query)
                if sys.platform not in ["darwin", "nt"] and \
                   len(proxyList) == 1 and \
                   proxyList[0].type() == QNetworkProxy.NoProxy:
                    # try it the Python way
                    # scan the environment for variables named <scheme>_proxy
                    # scan over whole environment to make this case insensitive
                    for name, value in os.environ.items():
                        name = name.lower()
                        if value and name[-6:] == '_proxy' and \
                           name[:-6] == query.protocolTag().lower():
                            url = QUrl(value)
                            if url.scheme() in ["http", "https"]:
                                proxyType = QNetworkProxy.HttpProxy
                            else:
                                proxyType = QNetworkProxy.FtpCachingProxy
                            proxy = QNetworkProxy(proxyType, url.host(), url.port(), 
                                                  url.userName(), url.password())
                            proxyList = [proxy]
                            break
                proxyList[0].setUser(Preferences.getUI("ProxyUser/Http"))
                proxyList[0].setPassword(Preferences.getUI("ProxyPassword/Http"))
                return proxyList
            else:
                host = Preferences.getUI("ProxyHost/Http")
                if not host:
                    QMessageBox.critical(None,
                        self.trUtf8("Proxy Configuration Error"),
                        self.trUtf8("""Proxy usage was activated"""
                                    """ but no proxy host configured."""))
                    return [QNetworkProxy(QNetworkProxy.DefaultProxy)]
                else:
                    proxy = QNetworkProxy(QNetworkProxy.HttpProxy, host, 
                        Preferences.getUI("ProxyPort/Http"),
                        Preferences.getUI("ProxyUser/Http"),
                        Preferences.getUI("ProxyPassword/Http"))
                    return [proxy, QNetworkProxy(QNetworkProxy.DefaultProxy)]
        else:
            return [QNetworkProxy(QNetworkProxy.NoProxy)]

def proxyAuthenticationRequired(proxy, auth):
    """
    Module slot to handle a proxy authentication request.
    
    @param proxy reference to the proxy object (QNetworkProxy)
    @param auth reference to the authenticator object (QAuthenticator)
    """
    info = QCoreApplication.translate("E5NetworkProxyFactory", "<b>Connect to proxy '{0}' using:</b>")\
        .format(Qt.escape(proxy.hostName()))
    
    dlg = AuthenticationDialog(info, proxy.user(), True)
    if dlg.exec_() == QDialog.Accepted:
        username, password = dlg.getData()
        auth.setUser(username)
        auth.setPassword(password)
        if dlg.shallSave():
            Preferences.setUI("ProxyUser/Http", username)
            Preferences.setUI("ProxyPassword/Http", password)
            proxy.setUser(username)
            proxy.setPassword(password)

eric ide

mercurial