def setProxy(self,arg): item = arg.split(':') if len(item) == 2: proxy = QNetworkProxy(QNetworkProxy.HttpProxy,item[0],int(item[1])) QNetworkProxy.setApplicationProxy(proxy) else: QNetworkProxyFactory.setUseSystemConfiguration(True)
def setUp(self): if len(argv) == 2: site = argv[1] else: site = None options = extract_options(site) if options['cookie_file'] is not None: options['cookie_file'] = ( expanduser("~/.eilat/cookies/") + options['cookie_file']) # Proxy if options['use_proxy']: proxy = QNetworkProxy() proxy.setType(QNetworkProxy.HttpProxy) proxy.setHostName('localhost') proxy.setPort(3128) QNetworkProxy.setApplicationProxy(proxy) self.mainwin = MainWin(clipboard=CLIPBOARD, options=options, parent=None) if site: self.mainwin.add_tab(site) else: self.mainwin.add_tab() self.mainwin.show()
def __init__(self, args, parent=None): QObject.__init__(self, parent) # variable declarations self.m_defaultPageSettings = {} self.m_pages = [] self.m_verbose = args.verbose self.m_page = WebPage(self) self.m_returnValue = 0 self.m_terminated = False # setup the values from args self.m_scriptFile = args.script self.m_args = args.script_args self.m_filesystem = FileSystem(self) self.m_pages.append(self.m_page) do_action('PhantomInitPre') if not args.proxy: QNetworkProxyFactory.setUseSystemConfiguration(True) else: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, args.proxy[0], int(args.proxy[1])) QNetworkProxy.setApplicationProxy(proxy) # Provide WebPage with a non-standard Network Access Manager self.m_netAccessMan = NetworkAccessManager(args.disk_cache, args.ignore_ssl_errors, self) self.m_page.setNetworkAccessManager(self.m_netAccessMan) self.m_page.javaScriptConsoleMessageSent.connect( self.printConsoleMessage) self.m_defaultPageSettings['loadImages'] = args.load_images self.m_defaultPageSettings['loadPlugins'] = args.load_plugins self.m_defaultPageSettings['userAgent'] = self.m_page.userAgent() self.m_defaultPageSettings[ 'localAccessRemote'] = args.local_access_remote self.m_page.applySettings(self.m_defaultPageSettings) self.libraryPath = os.path.dirname(os.path.abspath(self.m_scriptFile)) # inject our properties and slots into javascript self.m_page.mainFrame().addToJavaScriptWindowObject('phantom', self) self.m_page.mainFrame().addToJavaScriptWindowObject( 'fs', self.m_filesystem) bootstrap = QFile(':/bootstrap.js') if not bootstrap.open(QFile.ReadOnly): sys.exit('Can not bootstrap!') bootstrapper = str(bootstrap.readAll()) bootstrap.close() if not bootstrapper: sys.exit('Can not bootstrap!') self.m_page.mainFrame().evaluateJavaScript(bootstrapper) do_action('PhantomInitPost')
def set_proxy_settings(): http = backend.pm.Iface().getConfig().get("general", "http_proxy") if http and not http == "None": items = parse_proxy(http) QNetworkProxy.setApplicationProxy( QNetworkProxy(QNetworkProxy.HttpProxy, items['host'], int(items['port']), items['user'] or '', items['pass'] or ''))
def create_proxy(host, port, username=None, password=None): """ Create a new QNetworkProxy object """ port = int(port) if username is not None and password is not None: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, host, port, username, password) else: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, host, port) return proxy
def __init__(self, parent, args): QObject.__init__(self, parent) # variable declarations self.m_defaultPageSettings = {} self.m_pages = [] self.m_verbose = args.verbose self.m_page = WebPage(self) self.m_returnValue = 0 self.m_terminated = False # setup the values from args self.m_scriptFile = args.script self.m_args = args.script_args self.m_filesystem = FileSystem(self) self.m_pages.append(self.m_page) do_action('PhantomInitPre') if args.proxy is None: QNetworkProxyFactory.setUseSystemConfiguration(True) else: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, args.proxy[0], int(args.proxy[1])) QNetworkProxy.setApplicationProxy(proxy) # Provide WebPage with a non-standard Network Access Manager self.m_netAccessMan = NetworkAccessManager(self, args.disk_cache, args.cookies, args.ignore_ssl_errors) self.m_page.setNetworkAccessManager(self.m_netAccessMan) self.m_page.javaScriptConsoleMessageSent.connect(self.printConsoleMessage) self.m_defaultPageSettings['loadImages'] = args.load_images self.m_defaultPageSettings['loadPlugins'] = args.load_plugins self.m_defaultPageSettings['javascriptEnabled'] = True self.m_defaultPageSettings['XSSAuditingEnabled'] = False self.m_defaultPageSettings['userAgent'] = self.m_page.userAgent() self.m_defaultPageSettings['localAccessRemote'] = args.local_access_remote self.m_page.applySettings(self.m_defaultPageSettings) self.libraryPath = os.path.dirname(os.path.abspath(self.m_scriptFile)) # inject our properties and slots into javascript self.m_page.mainFrame().addToJavaScriptWindowObject('phantom', self) self.m_page.mainFrame().addToJavaScriptWindowObject('fs', self.m_filesystem) bootstrap = QFile(':/bootstrap.js') if not bootstrap.open(QFile.ReadOnly): sys.exit('Can not bootstrap!') bootstrapper = str(bootstrap.readAll()) bootstrap.close() if not bootstrapper: sys.exit('Can not bootstrap!') self.m_page.mainFrame().evaluateJavaScript(bootstrapper) do_action('PhantomInitPost')
def _customProxyList(self): proxies = [] for host, port, username, password in self.proxy_list: if username is not None and password is not None: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, host, port, username, password) else: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, host, port) proxies.append(proxy) return proxies
def __init__(self): QWebPage.__init__(self) self.networkAccessManager = QNetworkAccessManager() self.networkNoProxy = QNetworkProxy(QNetworkProxy.NoProxy) self.networkProxy = QNetworkProxy(QNetworkProxy.HttpProxy, "127.0.0.1", 8087) self.setNetworkAccessManager(self.networkAccessManager) self.loadFinished.connect(self._loadFinished)
def __init__(self, args, parent = None): QObject.__init__(self, parent) # variable declarations self.m_loadStatus = self.m_state = QString() self.m_var = self.m_paperSize = self.m_loadScript_cache = {} self.m_verbose = args.verbose self.m_page = WebPage(self) self.m_clipRect = QRect() # setup the values from args self.m_script = QString.fromUtf8(args.script[0].read()) self.m_scriptFile = args.script[0].name self.m_args = args.script[1:] self.m_upload_file = args.upload_file autoLoadImages = False if args.load_images == 'no' else True pluginsEnabled = True if args.load_plugins == 'yes' else False args.script[0].close() palette = self.m_page.palette() palette.setBrush(QPalette.Base, Qt.transparent) self.m_page.setPalette(palette) if not args.proxy: QNetworkProxyFactory.setUseSystemConfiguration(True) else: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, args.proxy[0], int(args.proxy[1])) QNetworkProxy.setApplicationProxy(proxy) self.m_page.settings().setAttribute(QWebSettings.AutoLoadImages, autoLoadImages) self.m_page.settings().setAttribute(QWebSettings.PluginsEnabled, pluginsEnabled) self.m_page.settings().setAttribute(QWebSettings.FrameFlatteningEnabled, True) self.m_page.settings().setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True) self.m_page.settings().setAttribute(QWebSettings.LocalStorageEnabled, True) self.m_page.settings().setLocalStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) self.m_page.settings().setOfflineStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) # Ensure we have a document.body. self.m_page.mainFrame().setHtml('<html><body></body></html>') self.m_page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) self.m_page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) # if our script was called in a different directory, change to it # to make any dealings with files be relative to the scripts directory if os.path.dirname(self.m_scriptFile): os.chdir(os.path.dirname(self.m_scriptFile)) if self.m_verbose: m_netAccessMan = NetworkAccessManager(self) self.m_page.setNetworkAccessManager(m_netAccessMan) # inject our properties and slots into javascript self.connect(self.m_page.mainFrame(), SIGNAL('javaScriptWindowObjectCleared()'), self.inject) self.connect(self.m_page, SIGNAL('loadFinished(bool)'), self.finish)
def __init__(self, args, parent = None): QObject.__init__(self, parent) # variable declarations self.m_loadStatus = self.m_state = '' self.m_var = self.m_paperSize = self.m_loadScript_cache = {} self.m_verbose = args.verbose self.m_page = WebPage(self) self.m_clipRect = QRect() # setup the values from args self.m_script = args.script.read() self.m_scriptFile = args.script.name self.m_scriptDir = os.path.dirname(args.script.name) if sys.platform.startswith('win'): self.m_scriptDir += '\\' else: self.m_scriptDir += '/' self.m_args = args.script_args self.m_upload_file = args.upload_file autoLoadImages = False if args.load_images == 'no' else True pluginsEnabled = True if args.load_plugins == 'yes' else False args.script.close() palette = self.m_page.palette() palette.setBrush(QPalette.Base, Qt.transparent) self.m_page.setPalette(palette) if not args.proxy: QNetworkProxyFactory.setUseSystemConfiguration(True) else: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, args.proxy[0], int(args.proxy[1])) QNetworkProxy.setApplicationProxy(proxy) self.m_page.settings().setAttribute(QWebSettings.AutoLoadImages, autoLoadImages) self.m_page.settings().setAttribute(QWebSettings.PluginsEnabled, pluginsEnabled) self.m_page.settings().setAttribute(QWebSettings.FrameFlatteningEnabled, True) self.m_page.settings().setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True) self.m_page.settings().setAttribute(QWebSettings.LocalStorageEnabled, True) self.m_page.settings().setLocalStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) self.m_page.settings().setOfflineStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) # Ensure we have a document.body. self.m_page.mainFrame().setHtml('<html><body></body></html>') self.m_page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) self.m_page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) if self.m_verbose: m_netAccessMan = NetworkAccessManager(args.disk_cache, self) self.m_page.setNetworkAccessManager(m_netAccessMan) # inject our properties and slots into javascript self.m_page.mainFrame().javaScriptWindowObjectCleared.connect(self.inject) self.m_page.loadFinished.connect(self.finish)
def _setQtProxy(self): proxy_str = '' if self.proxy.has_key('http'): proxy_str = self.proxy['http'] elif self.proxy.has_key('https'): proxy_str = self.proxy['https'] if proxy_str != '': p = urlparse.urlparse(proxy_str) proxy = QNetworkProxy(QNetworkProxy.HttpProxy, p.hostname, p.port) QNetworkProxy.setApplicationProxy(proxy)
def create_proxy(host, port, username=None, password=None, type=None): """ Create a new QNetworkProxy object """ if type is None: type = 'HTTP' validate_proxy_type(type) proxy_type = PROXY_TYPES[type.upper()] port = int(port) if username is not None and password is not None: proxy = QNetworkProxy(proxy_type, host, port, username, password) else: proxy = QNetworkProxy(proxy_type, host, port) return proxy
def set_proxy(proxy): proxy_url = QUrl(proxy) if unicode(proxy_url.scheme()).startswith('http'): protocol = QNetworkProxy.HttpProxy else: protocol = QNetworkProxy.Socks5Proxy QNetworkProxy.setApplicationProxy( QNetworkProxy( protocol, proxy_url.host(), proxy_url.port(), proxy_url.userName(), proxy_url.password()))
def __init__(self, parent, args): super(Phantom, self).__init__(parent) # variable declarations self.m_defaultPageSettings = {} self.m_pages = [] self.m_servers = [] self.m_verbose = args.verbose self.m_page = WebPage(self, args) self.m_returnValue = 0 self.m_terminated = False # setup the values from args self.app_args = args self.m_scriptFile = args.script self.m_args = args.script_args self.m_scriptEncoding = Encode(args.script_encoding, 'utf-8') self.m_outputEncoding = Encode(args.output_encoding, sys.stdout.encoding_sys) self.m_pages.append(self.m_page) do_action('PhantomInitPre') if args.proxy is None: QNetworkProxyFactory.setUseSystemConfiguration(True) else: proxy = QNetworkProxy(args.proxy_type, args.proxy[0], int(args.proxy[1])) QNetworkProxy.setApplicationProxy(proxy) self.m_page.javaScriptConsoleMessageSent.connect( self.printConsoleMessage) self.m_defaultPageSettings['loadImages'] = args.load_images self.m_defaultPageSettings['loadPlugins'] = args.load_plugins self.m_defaultPageSettings['javascriptEnabled'] = True self.m_defaultPageSettings['XSSAuditingEnabled'] = False self.m_defaultPageSettings['userAgent'] = self.m_page.userAgent() self.m_defaultPageSettings[ 'localToRemoteUrlAccessEnabled'] = args.local_to_remote_url_access self.m_page.applySettings(self.m_defaultPageSettings) self.libraryPath = os.path.dirname(os.path.abspath(self.m_scriptFile)) # inject our properties and slots into javascript self.m_page.mainFrame().addToJavaScriptWindowObject('phantom', self) with QPyFile(':/bootstrap.js') as f: self.m_page.mainFrame().evaluateJavaScript(f.readAll()) do_action('PhantomInitPost')
def __init__(self, args, parent = None): QObject.__init__(self, parent) # variable declarations self.m_loadStatus = self.m_state = self.m_userAgent = QString() self.m_page = WebPage(self) self.m_var = self.m_paperSize = self.m_loadScript_cache = {} # setup the values from args self.m_script = QString.fromUtf8(args.script[0].read()) self.m_scriptFile = args.script[0].name self.m_args = args.script[1:] self.m_upload_file = args.upload_file autoLoadImages = False if args.load_images == 'no' else True pluginsEnabled = True if args.load_plugins == 'yes' else False args.script[0].close() palette = self.m_page.palette() palette.setBrush(QPalette.Base, Qt.transparent) self.m_page.setPalette(palette) if not args.proxy: QNetworkProxyFactory.setUseSystemConfiguration(True) else: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, args.proxy[0], int(args.proxy[1])) QNetworkProxy.setApplicationProxy(proxy) self.m_page.settings().setAttribute(QWebSettings.AutoLoadImages, autoLoadImages) self.m_page.settings().setAttribute(QWebSettings.PluginsEnabled, pluginsEnabled) self.m_page.settings().setAttribute(QWebSettings.FrameFlatteningEnabled, True) self.m_page.settings().setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True) self.m_page.settings().setAttribute(QWebSettings.LocalStorageEnabled, True) self.m_page.settings().setLocalStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) self.m_page.settings().setOfflineStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) # Ensure we have a document.body. self.m_page.mainFrame().setHtml('<html><body></body></html>') self.m_page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) self.m_page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) # if our script was called in a different directory, change to it # to make any dealings with files be relative to the scripts directory if os.path.dirname(self.m_scriptFile): os.chdir(os.path.dirname(self.m_scriptFile)) # inject our properties and slots into javascript self.setObjectName('phantom') self.connect(self.m_page.mainFrame(), SIGNAL('javaScriptWindowObjectCleared()'), self.inject) self.connect(self.m_page, SIGNAL('loadFinished(bool)'), self.finish)
def __init__(self, args, parent=None): QObject.__init__(self, parent) # variable declarations self.m_defaultPageSettings = {} self.m_verbose = args.verbose self.m_page = WebPage(self) self.m_returnValue = 0 self.m_terminated = False # setup the values from args self.m_script = args.script self.m_scriptFile = args.script_name self.m_args = args.script_args do_action('PhantomInitPre', Bunch(locals())) if not args.proxy: QNetworkProxyFactory.setUseSystemConfiguration(True) else: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, args.proxy[0], int(args.proxy[1])) QNetworkProxy.setApplicationProxy(proxy) # Provide WebPage with a non-standard Network Access Manager self.m_netAccessMan = NetworkAccessManager(args.disk_cache, args.ignore_ssl_errors, self) self.m_page.setNetworkAccessManager(self.m_netAccessMan) self.m_page.javaScriptConsoleMessageSent.connect(self.printConsoleMessage) self.m_defaultPageSettings['loadImages'] = args.load_images self.m_defaultPageSettings['loadPlugins'] = args.load_plugins self.m_defaultPageSettings['userAgent'] = self.m_page.userAgent() self.m_page.applySettings(self.m_defaultPageSettings) # inject our properties and slots into javascript self.m_page.mainFrame().addToJavaScriptWindowObject('phantom', self) bootstrap = QFile(':/bootstrap.js') if not bootstrap.open(QFile.ReadOnly): qCritical('Can not bootstrap!') sys.exit(1) bootstrapper = str(bootstrap.readAll()) bootstrap.close() if not bootstrapper: qCritical('Can not bootstrap!') sys.exit(1) self.m_page.mainFrame().evaluateJavaScript(bootstrapper) do_action('PhantomInitPost', Bunch(locals()))
def request(self, iri, method="GET", extra_headers=None, oauth_credentials=None, post_content=None): """Return a deferred that will be fired with a Response object.""" uri = self.iri_to_uri(iri) request = QNetworkRequest(QUrl(uri)) request.setSslConfiguration(self.ssl_config) headers = yield self.build_request_headers(uri, method, extra_headers, oauth_credentials) for key, value in headers.items(): request.setRawHeader(key, value) post_buffer = QBuffer() post_buffer.setData(post_content) try: result = yield self._perform_request(request, method, post_buffer) except ProxyUnauthorizedError as e: app_proxy = QNetworkProxy.applicationProxy() proxy_host = app_proxy.hostName() if app_proxy else "proxy server" got_creds = yield self.request_proxy_auth_credentials( proxy_host, self.proxy_retry) if got_creds: self.proxy_retry = True result = yield self.request(iri, method, extra_headers, oauth_credentials, post_content) else: excp = WebClientError('Proxy creds needed.', e) defer.returnValue(excp) defer.returnValue(result)
def set_proxy(self, proxy=None): """Set the proxy or using system configuration as None,supported socks5 http{s}. @param proxy: Example:socks5://username:[email protected]:7070 """ proxy_type = None if proxy: parse = urlparse(proxy) scheme = parse.scheme hostname = parse.hostname port = parse.port username = parse.username or '' password = parse.password or '' if scheme == 'socks5': proxy_type = QNetworkProxy.Socks5Proxy elif scheme in ('http', 'https'): proxy_type = QNetworkProxy.HttpProxy if proxy_type: self.page.networkAccessManager().setProxy( QNetworkProxy(proxy_type, hostname, port, username, password) ) else: QNetworkProxyFactory.setUseSystemConfiguration(True)
def configure_proxy(self): proxy = urlparse(os.environ.get('http_proxy') or os.environ.get('HTTP_PROXY')) if proxy.hostname is not None and proxy.port is not None: q_network_proxy = QNetworkProxy(QNetworkProxy.HttpProxy, proxy.hostname, proxy.port) if proxy.username is not None: q_network_proxy.setUser(proxy.username) if proxy.password is not None: q_network_proxy.setPassword(proxy.password) QNetworkProxy.setApplicationProxy(q_network_proxy)
def __init__(self, parent, args): super(Phantom, self).__init__(parent) # variable declarations self.m_defaultPageSettings = {} self.m_pages = [] self.m_verbose = args.verbose self.m_page = WebPage(self, args) self.m_returnValue = 0 self.m_terminated = False # setup the values from args self.app_args = args self.m_scriptFile = args.script self.m_args = args.script_args self.m_scriptEncoding = Encode(args.script_encoding, 'utf-8') self.m_outputEncoding = Encode(args.output_encoding, sys.stdout.encoding_sys) self.m_pages.append(self.m_page) do_action('PhantomInitPre') if args.proxy is None: QNetworkProxyFactory.setUseSystemConfiguration(True) else: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, args.proxy[0], int(args.proxy[1])) QNetworkProxy.setApplicationProxy(proxy) self.m_page.javaScriptConsoleMessageSent.connect(self.printConsoleMessage) self.m_defaultPageSettings['loadImages'] = args.load_images self.m_defaultPageSettings['loadPlugins'] = args.load_plugins self.m_defaultPageSettings['javascriptEnabled'] = True self.m_defaultPageSettings['XSSAuditingEnabled'] = False self.m_defaultPageSettings['userAgent'] = self.m_page.userAgent() self.m_defaultPageSettings['localToRemoteUrlAccessEnabled'] = args.local_to_remote_url_access self.m_page.applySettings(self.m_defaultPageSettings) self.libraryPath = os.path.dirname(os.path.abspath(self.m_scriptFile)) # inject our properties and slots into javascript self.m_page.mainFrame().addToJavaScriptWindowObject('phantom', self) with QPyFile(':/bootstrap.js') as f: bootstrap = str(f.readAll()) self.m_page.mainFrame().evaluateJavaScript(bootstrap) do_action('PhantomInitPost')
def check_proxy_enabled(host, port): """Check if the proxy is enabled.""" port = int(port) if sys.platform.startswith("linux"): settings = gsettings.get_proxy_settings() enabled = len(settings) > 0 if enabled: proxy = build_proxy(settings) QNetworkProxy.setApplicationProxy(proxy) else: logger.info("Proxy is disabled.") return enabled else: QNetworkProxyFactory.setUseSystemConfiguration(True) query = QNetworkProxyQuery(host, port) proxies = QNetworkProxyFactory.systemProxyForQuery(query) return len(proxies) and proxies[0].type() != QNetworkProxy.NoProxy
def __set_proxy_slot(self, host, port): proxy = QNetworkProxy() if not host: proxy.setType(QNetworkProxy.NoProxy) else: proxy.setType(QNetworkProxy.HttpProxy) proxy.setHostName(host) proxy.setPort(port) self.__web_view.page().networkAccessManager().setProxy(proxy) self.__set_proxy_condition.acquire() self.__set_proxy_condition.notifyAll() self.__set_proxy_condition.release()
def _set_proxy(self, manager): proxy_settings = manager.get_proxy_settings() if proxy_settings.config == 'Manual': if proxy_settings.server and proxy_settings.port: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, hostName=proxy_settings.server, port=int(proxy_settings.port)) if proxy_settings.authenticated: proxy.setPassword(proxy_settings.password) proxy.setUser(proxy_settings.username) QNetworkProxy.setApplicationProxy(proxy) elif proxy_settings.config == 'System': QNetworkProxyFactory.setUseSystemConfiguration(True) else: QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.NoProxy))
def proxy(self, value): """System wide proxy """ proxy_url = QtCore.QUrl(value) #TODO: Una regexp para filtar basura y quitar el try except if not value: network_proxy = QNetworkProxy(QNetworkProxy.NoProxy) else: try: protocol = QNetworkProxy.NoProxy if proxy_url.scheme().startswith('http'): protocol = QNetworkProxy.HttpProxy else: protocol = QNetworkProxy.Socks5Proxy network_proxy = QNetworkProxy(protocol, proxy_url.host(), proxy_url.port(), proxy_url.userName(), proxy_url.password()) except: network_proxy = QNetworkProxy(QNetworkProxy.NoProxy) QNetworkProxy.setApplicationProxy( network_proxy )
def build_proxy(settings_groups): """Create a QNetworkProxy from these settings.""" proxy_groups = [ ("socks", QNetworkProxy.Socks5Proxy), ("https", QNetworkProxy.HttpProxy), ("http", QNetworkProxy.HttpProxy), ] for group, proxy_type in proxy_groups: if group not in settings_groups: continue settings = settings_groups[group] if "host" in settings and "port" in settings: return QNetworkProxy(proxy_type, hostName=settings.get("host", ""), port=settings.get("port", 0), user=settings.get("username", ""), password=settings.get("password", "")) logger.error("No proxy correctly configured.") return QNetworkProxy(QNetworkProxy.DefaultProxy)
def startpickup(self, purse): # ставим Tor в качестве прокси, чтобы ходить на сайт по многу раз proxy = QNetworkProxy(QNetworkProxy.Socks5Proxy, TOR_HOST, TOR_PORT) QNetworkProxy.setApplicationProxy(proxy) newnym() ''' b = Browser() b.get('http://2ip.ru/') ip = b.js("$('div.ip big').text()") hostname = b.js("$('.ip-info-entry table:eq(1) tr:eq(0) td').text().trim()") os = b.js("$('.ip-info-entry table:eq(1) tr:eq(1) td').text().trim()") browser = b.js("$('.ip-info-entry table:eq(1) tr:eq(2) td').text().trim()") location = b.js("$('.ip-info-entry table:eq(1) tr:eq(3) td').text().trim()") provider = b.js("$('.ip-info-entry table:eq(1) tr:eq(4) td').text().trim()") log.info('start(): proxy: %s:%s, ip: %s, hostname: %s, os: %s, browser: %s, location: %s, provider: %s' % (colorize((TOR_HOST, TOR_PORT, ip, hostname, os, browser, location, provider)))) ''' self.purse = purse QTimer.singleShot(0, self.pickup)
def setup_proxy(self): """Setup the proxy settings if needed.""" # QtNetwork knows how to use the system settings on both Win and Mac if sys.platform.startswith("linux"): settings = gsettings.get_proxy_settings() enabled = len(settings) > 0 if enabled and WebClient.proxy_instance is None: proxy = build_proxy(settings) QNetworkProxy.setApplicationProxy(proxy) WebClient.proxy_instance = proxy elif enabled and WebClient.proxy_instance: logger.info("Proxy already in use.") else: logger.info("Proxy is disabled.") else: if WebClient.proxy_instance is None: logger.info("Querying OS for proxy.") query = QNetworkProxyQuery(QUrl(PROXY_REQUEST)) proxies = QNetworkProxyFactory.systemProxyForQuery(query) QNetworkProxy.setApplicationProxy(proxies[0]) WebClient.proxy_instance = proxies[0]
def setProxy(self, proxy): """Parse proxy components from proxy """ if proxy: fragments = common.parse_proxy(proxy) if fragments['host']: QNetworkAccessManager.setProxy( self, QNetworkProxy(QNetworkProxy.HttpProxy, fragments['host'], int(fragments['port']), fragments['username'], fragments['password'])) else: common.logger.info('Invalid proxy: ' + str(proxy))
def setProxy(self, proxy): """Allow setting string as proxy """ if proxy: fragments = common.parse_proxy(proxy) if fragments.host: QNetworkAccessManager.setProxy(self, QNetworkProxy(QNetworkProxy.HttpProxy, fragments.host, int(fragments.port), fragments.username, fragments.password ) ) else: common.logger.info('Invalid proxy: ' + str(proxy)) proxy = None
def saveConfig(self): settings = QSettings() settings.setValue("mainWindow/geometry", QVariant(self.saveGeometry())) settings.setValue("mainWindow/state", QVariant(self.saveState())) session = self.feedView.siteServer.session from cPickle import dumps session = dumps(session) settings.setValue("session", QVariant(session)) proxy = QNetworkProxy.applicationProxy() proxyType = (proxy.type() == QNetworkProxy.Socks5Proxy) and 2 or ( (proxy.type() == QNetworkProxy.HttpProxy) and 1 or 0 ) settings.setValue("proxy/type", QVariant(proxyType)) settings.setValue("proxy/host", QVariant(proxy.hostName())) settings.setValue("proxy/port", QVariant(proxy.port())) settings.setValue("proxy/user", QVariant(proxy.user())) settings.setValue("proxy/password", QVariant(proxy.password()))
def set_proxy(self, type, host='localhost', port=8888, user='', password=''): """Set up proxy for FURTHER connections. :param type: proxy type to use: \ none/default/socks5/https/http. :param host: proxy server ip or host name. :param port: proxy port. """ _types = { 'default': QNetworkProxy.DefaultProxy, 'none': QNetworkProxy.NoProxy, 'socks5': QNetworkProxy.Socks5Proxy, 'https': QNetworkProxy.HttpProxy, 'http': QNetworkProxy.HttpCachingProxy } if type is None: type = 'none' type = type.lower() if type in ['none', 'default']: self.manager.setProxy(QNetworkProxy(_types[type])) return elif type in _types: proxy = QNetworkProxy(_types[type], hostName=host, port=port, user=user, password=password) self.manager.setProxy(proxy) else: raise ValueError, 'Unsupported proxy type:' + type \ + '\nsupported types are: none/socks5/http/https/default'
def updateSettings(self): self.ffNickname.clear() self.ffRemoteKey.clear() if self.feedView.siteServer.session.user: self.ffNickname.setText(self.feedView.siteServer.session.user) if self.feedView.siteServer.session.remoteKey: self.ffRemoteKey.setText(self.feedView.siteServer.session.remoteKey) proxy = QNetworkProxy.applicationProxy() self.proxyType.setCurrentIndex( (proxy.type() == QNetworkProxy.Socks5Proxy) and 2 or ( (proxy.type() == QNetworkProxy.HttpProxy) and 1 or 0 ) ) if self.proxyType.currentIndex() != 0: self.proxyHost.setText(proxy.hostName()) self.proxyPort.setValue(proxy.port()) if proxy.user(): self.proxyAuth.setCheckState(Qt.Checked) self.proxyAuthUser.setText(proxy.user()) self.proxyAuthPassword.setText(proxy.password())
def setProxy(self, proxy): """Allow setting string as proxy """ if isinstance(proxy, basestring): match = re.match('((?P<username>\w+):(?P<password>\w+)@)?(?P<host>\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})(:(?P<port>\d+))?', proxy) if match: groups = match.groupdict() username = groups.get('username') or '' password = groups.get('password') or '' host = groups.get('host') port = groups.get('port') #print host, port, username, password proxy = QNetworkProxy(QNetworkProxy.HttpProxy, host, int(port), username, password) else: common.logger.info('Invalid proxy:' + proxy) proxy = None if proxy: QNetworkAccessManager.setProxy(self, proxy)
def removeProxy(self): """Removes the proxy configuration """ proxy = QNetworkProxy(); proxy.setType(QNetworkProxy.NoProxy); self.setProxy(proxy)
def get_proxy(): """Adaption by source of Plugin Installer - Version 1.0.10""" settings = QSettings() settings.beginGroup("proxy") if settings.value("/proxyEnabled", False, type=bool): proxy = QNetworkProxy() proxyType = settings.value("/proxyType", 0, type=int) if proxyType in ["1", "Socks5Proxy"]: proxy.setType(QNetworkProxy.Socks5Proxy) elif proxyType in ["2", "NoProxy"]: proxy.setType(QNetworkProxy.NoProxy) elif proxyType in ["3", "HttpProxy"]: proxy.setType(QNetworkProxy.HttpProxy) elif proxyType in ["4", "HttpCachingProxy"] and QT_VERSION >= 0X040400: proxy.setType(QNetworkProxy.HttpCachingProxy) elif proxyType in ["5", "FtpCachingProxy"] and QT_VERSION >= 0X040400: proxy.setType(QNetworkProxy.FtpCachingProxy) else: proxy.setType(QNetworkProxy.DefaultProxy) proxy.setHostName(settings.value("/proxyHost")) proxy.setPort(settings.value("/proxyPort", type=int)) proxy.setUser(settings.value("/proxyUser")) proxy.setPassword(settings.value("/proxyPassword")) settings.endGroup() return proxy
def _defaultProxyList(self): return [QNetworkProxy(QNetworkProxy.DefaultProxy)]
def prox(self,mode,user,password,host,port): proxy = QNetworkProxy() if mode == "DefaultProxy": proxy.setType(QNetworkProxy.DefaultProxy) elif mode == "Socks5Proxy": proxy.setType(QNetworkProxy.Socks5Proxy) proxy.setHostName(host) proxy.setPort(int(port)) proxy.setUser(self.usern) proxy.setPassword(self.passw) QNetworkProxy.setApplicationProxy(proxy) elif mode == "HttpProxy": proxy.setType(QNetworkProxy.HttpProxy) proxy.setHostName(host) proxy.setPort(int(port)) proxy.setUser(self.usern) proxy.setPassword(self.passw) QNetworkProxy.setApplicationProxy(proxy) elif mode == "HttpCachingProxy": proxy.setType(QNetworkProxy.HttpCachingProxy) proxy.setHostName(host) proxy.setPort(int(port)) proxy.setUser(self.usern) proxy.setPassword(self.passw) QNetworkProxy.setApplicationProxy(proxy) elif mode == "FtpCachingProxy": proxy.setType(QNetworkProxy.FtpCachingProxy) proxy.setHostName(host) proxy.setPort(int(port)) proxy.setUser(self.usern) proxy.setPassword(self.passw) QNetworkProxy.setApplicationProxy(proxy)
def reset_proxy_settings(): QNetworkProxy.setApplicationProxy(QNetworkProxy())
def __init__(self, verbose): QtGui.QMainWindow.__init__(self) self.setWindowTitle("Photini photo metadata editor") self.selection = list() # logger window self.loggerwindow = LoggerWindow(verbose) self.logger = logging.getLogger(self.__class__.__name__) # config store self.config_store = ConfigStore('editor') # set network proxy proxies = getproxies() if 'http' in proxies: parsed = urlparse(proxies['http']) QNetworkProxy.setApplicationProxy( QNetworkProxy(QNetworkProxy.HttpProxy, parsed.hostname, parsed.port)) # restore size size = self.width(), self.height() self.resize(*eval( self.config_store.get('main_window', 'size', str(size)))) # image selector self.image_list = ImageList(self.config_store) self.image_list.selection_changed.connect(self.new_selection) self.image_list.new_metadata.connect(self.new_metadata) # prepare list of tabs and associated stuff self.tab_list = ( {'name' : '&Descriptive metadata', 'class' : Descriptive}, {'name' : '&Technical metadata', 'class' : Technical}, {'name' : 'Map (&Google)', 'class' : GoogleMap}, {'name' : 'Map (&Bing)', 'class' : BingMap}, {'name' : 'Map (&OSM)', 'class' : OpenStreetMap}, {'name' : '&Flickr upload', 'class' : FlickrUploader}, {'name' : '&Picasa upload', 'class' : PicasaUploader}, {'name' : '&Import from camera', 'class' : Importer}, ) for tab in self.tab_list: tab['key'] = tab['name'].replace('&', '').replace(' ', '_') tab['key'] = tab['key'].replace('(', '').replace(')', '').lower() if tab['class']: tab['object'] = tab['class'](self.config_store, self.image_list) else: tab['object'] = None # file menu file_menu = self.menuBar().addMenu('File') open_action = QtGui.QAction('Open images', self) open_action.setShortcuts(['Ctrl+O']) open_action.triggered.connect(self.image_list.open_files) file_menu.addAction(open_action) self.save_action = QtGui.QAction('Save images with new data', self) self.save_action.setShortcuts(['Ctrl+S']) self.save_action.setEnabled(False) self.save_action.triggered.connect(self.image_list.save_files) file_menu.addAction(self.save_action) self.close_action = QtGui.QAction('Close selected images', self) self.close_action.setEnabled(False) self.close_action.triggered.connect(self.close_files) file_menu.addAction(self.close_action) close_all_action = QtGui.QAction('Close all images', self) close_all_action.triggered.connect(self.close_all_files) file_menu.addAction(close_all_action) file_menu.addSeparator() quit_action = QtGui.QAction('Quit', self) quit_action.setShortcuts(['Ctrl+Q', 'Ctrl+W']) quit_action.triggered.connect( QtGui.QApplication.instance().closeAllWindows) file_menu.addAction(quit_action) # options menu options_menu = self.menuBar().addMenu('Options') settings_action = QtGui.QAction('Settings', self) settings_action.triggered.connect(self.edit_settings) options_menu.addAction(settings_action) options_menu.addSeparator() for tab in self.tab_list: tab['action'] = QtGui.QAction(tab['name'].replace('&', ''), self) tab['action'].setCheckable(True) if tab['class']: tab['action'].setChecked( eval(self.config_store.get('tabs', tab['key'], 'True'))) else: tab['action'].setEnabled(False) tab['action'].triggered.connect(self.add_tabs) options_menu.addAction(tab['action']) # help menu help_menu = self.menuBar().addMenu('Help') about_action = QtGui.QAction('About Photini', self) about_action.triggered.connect(self.about) help_menu.addAction(about_action) help_menu.addSeparator() help_action = QtGui.QAction('Photini documentation', self) help_action.triggered.connect(self.open_docs) help_menu.addAction(help_action) # main application area self.central_widget = QtGui.QSplitter() self.central_widget.setOrientation(Qt.Vertical) self.central_widget.setChildrenCollapsible(False) self.tabs = QtGui.QTabWidget() self.tabs.currentChanged.connect(self.new_tab) self.add_tabs() self.central_widget.addWidget(self.tabs) self.central_widget.addWidget(self.image_list) size = self.central_widget.sizes() self.central_widget.setSizes(eval( self.config_store.get('main_window', 'split', str(size)))) self.central_widget.splitterMoved.connect(self.new_split) self.setCentralWidget(self.central_widget)
def _set_proxy(self, manager): proxy_settings = manager.get_proxy_settings() if proxy_settings.config == 'Manual': if proxy_settings.server and proxy_settings.port: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, hostName=proxy_settings.server, port=int(proxy_settings.port)) if proxy_settings.authenticated: proxy.setPassword(proxy_settings.password) proxy.setUser(proxy_settings.username) QNetworkProxy.setApplicationProxy(proxy) elif proxy_settings.config == 'System': QNetworkProxyFactory.setUseSystemConfiguration(True) else: QNetworkProxy.setApplicationProxy( QNetworkProxy(QNetworkProxy.NoProxy))
def __init__(self, parent, args): super(Phantom, self).__init__(parent) self.returnValue = 0 self.verbose = args.verbose if args.proxy is not None: (host,port) = args.proxy.split(":") if args.proxy_type == 'socks5': proxy = QNetworkProxy(QNetworkProxy.Socks5Proxy, host, int(port)) else: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, host, int(port)) QNetworkProxy.setApplicationProxy(proxy) #self.m_webPage.setNetworkAccessManager(self) self.javaScriptConsoleMessageSent.connect(self.printConsoleMessage) self.startedSent.connect(self.onStarted) if not args.silent: self.view = QtWebKit.QWebView() self.contentPage = ContentPage(self.view,self,args) self.contentPage.settings().setAttribute(QtWebKit.QWebSettings.DeveloperExtrasEnabled, True) self.view.setPage(self.contentPage) self.view.show() else: self.contentPage = ContentPage(self,self,args) #self.contentPage.settings().setAttribute(QtWebKit.QWebSettings.WebSecurityEnabled, False) self.controllerPage = ControllerPage(self,self.contentPage, args) self.controllerPage.mainFrame().addToJavaScriptWindowObject('phantom', self) self.stdin = StdIn(self.controllerPage,self,self.contentPage) QTimer.singleShot(0, lambda: self.onStarted()) self.controllerPage and self.controllerPage.mainFrame().evaluateJavaScript(""" var fs = { write: function() {} }; function ret(id,msg) {phantom.ret(id,msg)}; function errret(id,msg) {phantom.errret(id,msg)}; function quoteString(str) { var c, i, l = str.length, o = '"'; for (i = 0; i < l; i += 1) { c = str.charAt(i); if (c >= ' ') { if (c === '\\\\' || c === '"') { o += '\\\\'; } o += c; } else { switch (c) { case '\\b': o += '\\\\b'; break; case '\\f': o += '\\\\f'; break; case '\\n': o += '\\\\n'; break; case '\\r': o += '\\\\r'; break; case '\\t': o += '\\\\t'; break; default: c = c.charCodeAt(); o += '\\\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); } } } return o + '"'; } function detectType(value) { var s = typeof value; if (s === 'object') { if (value) { if (value instanceof Array) { s = 'array'; } else if (value instanceof RegExp) { s = 'regexp'; } else if (value instanceof Date) { s = 'date'; } } else { s = 'null'; } } return s; } page.evaluate = function (func, args) { var str, arg, argType, i, l; if (!(func instanceof Function || typeof func === 'string' || func instanceof String)) { throw "Wrong use of WebPage#evaluate"; } str = 'function() { return (' + func.toString() + ')('; for (i = 1, l = arguments.length; i < l; i++) { arg = arguments[i]; argType = detectType(arg); switch (argType) { case "object": //< for type "object" case "array": //< for type "array" str += JSON.stringify(arg) + "," break; case "date": //< for type "date" str += "new Date(" + JSON.stringify(arg) + ")," break; case "string": //< for type "string" str += quoteString(arg) + ','; break; default: // for types: "null", "number", "function", "regexp", "undefined" str += arg + ','; break; } } str = str.replace(/,$/, '') + '); }'; return this.evaluateJavaScript(str); }; """)
def get_proxy(): """Adaption by source of Plugin Installer - Version 1.0.10""" settings = QSettings() settings.beginGroup('proxy') if settings.value('/proxyEnabled', False, type=bool): proxy = QNetworkProxy() try: proxy_type = settings.value('/proxyType', 0, type=int) except TypeError: # Catch for this: # TypeError: unable to convert a QVariant of type 10 to a # QMetaType of type 2 # TODO: can we do anything to handle this more gracefully? TS settings.setValue('/proxyType', 0) return proxy if proxy_type in ['1', 'Socks5Proxy']: proxy.setType(QNetworkProxy.Socks5Proxy) elif proxy_type in ['2', 'NoProxy']: proxy.setType(QNetworkProxy.NoProxy) elif proxy_type in ['3', 'HttpProxy']: proxy.setType(QNetworkProxy.HttpProxy) elif proxy_type in ['4', 'HttpCachingProxy'] and QT_VERSION >= 0X040400: proxy.setType(QNetworkProxy.HttpCachingProxy) elif proxy_type in ['5', 'FtpCachingProxy'] and QT_VERSION >= 0X040400: proxy.setType(QNetworkProxy.FtpCachingProxy) else: proxy.setType(QNetworkProxy.DefaultProxy) proxy.setHostName(settings.value('/proxyHost')) proxy.setPort(settings.value('/proxyPort', type=int)) user = settings.value('/proxyUser', type=str) password = settings.value('/proxyPassword', type=str) if user is not None: proxy.setUser(user) if password is not None and user is not None: proxy.setPassword(password) settings.endGroup() return proxy
current = home s = QSettings() for key, val in settings.iteritems(): settings_key = key for key2, val2 in current.iteritems(): if key2 == settings_key: settings_val = val2 current_setting = s.value(str(val).decode('unicode-escape')) s.setValue(unicode(str(val)), settings_val) s.sync() proxyEnabled = s.value("proxy/proxyEnabled", "") proxyType = s.value("proxy/proxyType", "") proxyHost = s.value("proxy/proxyHost", "") proxyPort = s.value("proxy/proxyPort", "") proxyUser = s.value("proxy/proxyUser", "") proxyPassword = s.value("proxy/proxyPassword", "") proxy = QNetworkProxy() proxy.setType(QNetworkProxy.HttpProxy) proxy.setHostName(proxyHost) proxy.setPort(int(proxyPort)) proxy.setUser(proxyUser) proxy.setPassword(proxyPassword) QNetworkProxy.setApplicationProxy(proxy) net_man = QgsNetworkAccessManager.instance() stringlist = "" net_man.setupDefaultProxyAndCache() net_man.setFallbackProxyAndExcludes(proxy, stringlist)
def createWidgets(self): """ Create all qt widgets """ self.setWindowTitle(self.tr("Extensive Testing Client - Web Browser")) self.setWindowIcon(QIcon(":/main.png")) self.dockToolbarWebBrowser = QToolBar(self) self.dockToolbarWebBrowser.setToolButtonStyle( Qt.ToolButtonTextBesideIcon) browserLayoutGroup = QVBoxLayout() browserLayoutGroup.addWidget(self.dockToolbarWebBrowser) toolbarBrowserLayoutGroup = QHBoxLayout() self.locationEdit = QLineEdit(self) self.locationEdit.setSizePolicy( QSizePolicy.Expanding, self.locationEdit.sizePolicy().verticalPolicy()) self.webCounter = QLabel("(0%)") toolbarBrowserLayoutGroup.addWidget(QLabel("Load URL:")) toolbarBrowserLayoutGroup.addWidget(self.webCounter) toolbarBrowserLayoutGroup.addWidget(self.locationEdit) self.webTitle = QLabel("Title:") self.webView = QWebView() if QtHelper.str2bool( Settings.instance().readValue(key='Server/proxy-web-active')): proxy = QNetworkProxy() proxy.setType(3) # http proxy.setHostName( Settings.instance().readValue(key='Server/addr-proxy-http')) proxy.setPort( int(Settings.instance().readValue( key='Server/port-proxy-http'))) self.webView.page().networkAccessManager().setProxy(proxy) if QT_VERSION_STR.startswith("4."): self.webInspector = QWebInspector() self.webView.settings().setAttribute( QWebSettings.DeveloperExtrasEnabled, True) self.webInspector.setPage(self.webView.page()) self.webView.setHtml( '<html><head></head><body>No content loaded</body></html>') self.webView.settings().setAttribute(QWebSettings.PluginsEnabled, True) self.webView.settings().setAttribute( QWebSettings.JavascriptCanOpenWindows, True) browserLayoutGroup.addLayout(toolbarBrowserLayoutGroup) browserLayoutGroup.addWidget(self.webTitle) self.webTab = QTabWidget() self.webTab.addTab(self.webView, "Web Page") if QT_VERSION_STR.startswith("4."): self.webTab.addTab(self.webInspector, "Source Inspector") browserLayoutGroup.addWidget(self.webTab) self.setLayout(browserLayoutGroup)
def __init__(self, parent=None): " Initialize QWidget inside MyMainWindow " super(MyMainWindow, self).__init__(parent) QWidget.__init__(self) self.statusBar().showMessage(" " + __doc__) self.setStyleSheet("QStatusBar{color:grey;}") self.setWindowTitle(__doc__) self.setWindowIcon(QIcon.fromTheme("face-monkey")) self.setFont(QFont("Ubuntu Light", 10)) self.setMaximumSize(QDesktopWidget().screenGeometry().width(), QDesktopWidget().screenGeometry().height()) # directory auto completer self.completer = QCompleter(self) self.dirs = QDirModel(self) self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot) self.completer.setModel(self.dirs) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer.setCompletionMode(QCompleter.PopupCompletion) # process self.process = QProcess(self) # self.process.finished.connect(self.on_process_finished) # self.process.error.connect(self.on_process_error) # Proxy support, by reading http_proxy os env variable proxy_url = QUrl(environ.get("http_proxy", "")) QNetworkProxy.setApplicationProxy( QNetworkProxy( QNetworkProxy.HttpProxy if str(proxy_url.scheme()).startswith("http") else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(), proxy_url.userName(), proxy_url.password(), ) ) if "http_proxy" in environ else None print((" INFO: Proxy Auto-Config as " + str(proxy_url))) # basic widgets layouts and set up self.mainwidget = QTabWidget() self.mainwidget.setToolTip(__doc__) self.mainwidget.setMovable(True) self.mainwidget.setTabShape(QTabWidget.Triangular) self.mainwidget.setTabsClosable(True) self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu) self.mainwidget.tabCloseRequested.connect( lambda: self.mainwidget.setTabPosition(1) if self.mainwidget.tabPosition() == 0 else self.mainwidget.setTabPosition(0) ) self.setCentralWidget(self.mainwidget) self.dock1 = QDockWidget() self.dock2 = QDockWidget() self.dock3 = QDockWidget() for a in (self.dock1, self.dock2, self.dock3): a.setWindowModality(Qt.NonModal) a.setWindowOpacity(0.9) a.setWindowTitle(__doc__ if a.windowTitle() == "" else a.windowTitle()) a.setStyleSheet(" QDockWidget::title{text-align:center;}") a.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.mainwidget.addTab(a, QIcon.fromTheme("face-cool"), str(a.windowTitle()).strip().lower()) # Paleta de colores para pintar transparente self.palette().setBrush(QPalette.Base, Qt.transparent) self.setPalette(self.palette()) self.setAttribute(Qt.WA_OpaquePaintEvent, False) # toolbar and basic actions self.toolbar = QToolBar(self) self.toolbar.setIconSize(QSize(24, 24)) # spacer widget for left self.left_spacer = QWidget(self) self.left_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # spacer widget for right self.right_spacer = QWidget(self) self.right_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) qaqq = QAction(QIcon.fromTheme("application-exit"), "Quit", self) qaqq.setShortcut("Ctrl+Q") qaqq.triggered.connect(exit) qamin = QAction(QIcon.fromTheme("go-down"), "Minimize", self) qamin.triggered.connect(lambda: self.showMinimized()) qamax = QAction(QIcon.fromTheme("go-up"), "Maximize", self) qanor = QAction(QIcon.fromTheme("go-up"), "AutoCenter AutoResize", self) qanor.triggered.connect(self.center) qatim = QAction(QIcon.fromTheme("go-up"), "View Date and Time", self) qatim.triggered.connect(self.timedate) qabug = QAction(QIcon.fromTheme("help-about"), "Report a Problem", self) qabug.triggered.connect( lambda: qabug.setDisabled(True) if not call("xdg-open mailto:" + "*****@*****.**".decode("rot13"), shell=True) else " ERROR " ) qamax.triggered.connect(lambda: self.showMaximized()) qaqt = QAction(QIcon.fromTheme("help-about"), "About Qt", self) qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self)) qaslf = QAction(QIcon.fromTheme("help-about"), "About Self", self) qaslf.triggered.connect( lambda: QMessageBox.about( self.mainwidget, __doc__, "".join( ( __doc__, linesep, "version ", __version__, ", (", __license__, "), by ", __author__, ", ( ", __email__, " )", linesep, ) ), ) ) qasrc = QAction(QIcon.fromTheme("applications-development"), "View Source Code", self) qasrc.triggered.connect(lambda: call("xdg-open " + __file__, shell=1)) qakb = QAction(QIcon.fromTheme("input-keyboard"), "Keyboard Shortcuts", self) qakb.triggered.connect( lambda: QMessageBox.information(self.mainwidget, "Keyboard Shortcuts", " Ctrl+Q = Quit ") ) qapic = QAction(QIcon.fromTheme("camera-photo"), "Take a Screenshot", self) qapic.triggered.connect( lambda: QPixmap.grabWindow(QApplication.desktop().winId()).save( QFileDialog.getSaveFileName( self.mainwidget, " Save Screenshot As ...", path.expanduser("~"), ";;(*.png) PNG", "png" ) ) ) qatb = QAction(QIcon.fromTheme("help-browser"), "Toggle ToolBar", self) qatb.triggered.connect(lambda: self.toolbar.hide() if self.toolbar.isVisible() is True else self.toolbar.show()) qati = QAction(QIcon.fromTheme("help-browser"), "Switch ToolBar Icon Size", self) qati.triggered.connect( lambda: self.toolbar.setIconSize(self.toolbar.iconSize() * 4) if self.toolbar.iconSize().width() * 4 == 24 else self.toolbar.setIconSize(self.toolbar.iconSize() / 4) ) qasb = QAction(QIcon.fromTheme("help-browser"), "Toggle Tabs Bar", self) qasb.triggered.connect( lambda: self.mainwidget.tabBar().hide() if self.mainwidget.tabBar().isVisible() is True else self.mainwidget.tabBar().show() ) qadoc = QAction(QIcon.fromTheme("help-browser"), "On-line Docs", self) qadoc.triggered.connect(lambda: open_new_tab(__url__)) qapy = QAction(QIcon.fromTheme("help-browser"), "About Python", self) qapy.triggered.connect(lambda: open_new_tab("http://python.org/about")) qali = QAction(QIcon.fromTheme("help-browser"), "Read Licence", self) qali.triggered.connect(lambda: open_new_tab(__full_licence__)) qacol = QAction(QIcon.fromTheme("preferences-system"), "Set GUI Colors", self) qacol.triggered.connect( lambda: self.setStyleSheet( """ * { background-color: %s } """ % QColorDialog.getColor().name() ) ) qatit = QAction(QIcon.fromTheme("preferences-system"), "Set the App Window Title", self) qatit.triggered.connect(self.seTitle) qafnt = QAction(QIcon.fromTheme("help-about"), "Set GUI Font", self) if KDE: font = QFont() qafnt.triggered.connect( lambda: self.setStyleSheet("*{font-family: %s}" % font.toString()) if KFontDialog.getFont(font)[0] == QDialog.Accepted else "" ) else: qafnt.triggered.connect( lambda: self.setStyleSheet("*{font-family: %s}" % QFontDialog.getFont()[0].toString()) ) self.toolbar.addWidget(self.left_spacer) self.toolbar.addSeparator() for b in ( qaqq, qamin, qanor, qamax, qasrc, qakb, qacol, qatim, qatb, qati, qasb, qatit, qafnt, qapic, qadoc, qali, qaslf, qaqt, qapy, qabug, ): self.toolbar.addAction(b) self.addToolBar(Qt.TopToolBarArea, self.toolbar) self.toolbar.addSeparator() self.toolbar.addWidget(self.right_spacer) def contextMenuRequested(point): " quick and dirty custom context menu " menu = QMenu() menu.addActions( ( qaqq, qamin, qanor, qamax, qasrc, qakb, qacol, qati, qasb, qatb, qatim, qatit, qafnt, qapic, qadoc, qali, qaslf, qaqt, qapy, qabug, ) ) menu.exec_(self.mapToGlobal(point)) self.mainwidget.customContextMenuRequested.connect(contextMenuRequested) def must_be_checked(widget_list): " widget tuple passed as argument should be checked as ON " for each_widget in widget_list: try: each_widget.setChecked(True) except: pass def must_have_tooltip(widget_list): " widget tuple passed as argument should have tooltips " for each_widget in widget_list: try: each_widget.setToolTip(each_widget.text()) except: each_widget.setToolTip(each_widget.currentText()) finally: each_widget.setCursor(QCursor(Qt.PointingHandCursor)) def must_autofillbackground(widget_list): " widget tuple passed as argument should have filled background " for each_widget in widget_list: try: each_widget.setAutoFillBackground(True) except: pass ####################################################################### self.group1 = QGroupBox() self.group1.setTitle(" Blender ") self.arch = QLabel("<center><b>" + architecture()[0]) self.ost = QLabel("<center><b>" + sys.platform) self.downf = QLineEdit(path.join(path.expanduser("~"), "blender")) self.downf.setCompleter(self.completer) self.borig = QPushButton(QIcon.fromTheme("folder-open"), "Open") self.borig.clicked.connect( lambda: self.downf.setText( path.join( str(QFileDialog.getExistingDirectory(self.mainwidget, "Open a Folder", path.expanduser("~"))), "blender", ) ) ) self.bugs = QPushButton(QIcon.fromTheme("help-faq"), "Report Bugs!") self.bugs.clicked.connect(lambda: open_new_tab("http://www.blender.org/development/report-a-bug")) self.go = QPushButton(QIcon.fromTheme("emblem-favorite"), "Run Blender") self.go.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.go.clicked.connect(self.run) vboxg1 = QVBoxLayout(self.group1) for each_widget in ( self.go, QLabel(""), QLabel('<h3 style="color:white;"> Download Folder Path: </h3>'), self.downf, self.borig, QLabel('<h3 style="color:white;"> Bugs: </h3>'), self.bugs, QLabel('<h3 style="color:white;"> OS: </h3>'), self.ost, QLabel('<h3 style="color:white;"> Architexture: </h3>'), self.arch, QLabel( """<i style="color:white;"> Warning: this builds arent as stable as releases, use at your own risk</i>""" ), ): vboxg1.addWidget(each_widget) self.group2 = QGroupBox() self.group2.setTitle("Options") self.nwfl = QCheckBox("Force opening with borders") self.smll = QCheckBox("Auto Center and Auto Resize the Window") self.lrgf = QCheckBox("Start with the console window open") self.case = QCheckBox("BGE: Run on 50 hertz without dropping frames") self.cnvt = QCheckBox("BGE: Use Vertex Arrays for rendering") self.blnk = QCheckBox("BGE: No Texture Mipmapping") self.spac = QCheckBox("BGE: Linear Texture Mipmap instead of Nearest") self.whit = QCheckBox("Turn Debugging ON") self.tabz = QCheckBox("Enable floating point exceptions") self.sprs = QCheckBox("Disable the crash handler") self.filn = QCheckBox("Enable debug messages from FFmpeg library") self.plac = QCheckBox("Enable debug messages for python") self.plac = QCheckBox("Enable debug messages for the event system") self.plac = QCheckBox("Enable debug messages for event handling") self.plac = QCheckBox("Enable debug messages for the window manager") self.tbs = QComboBox(self.group2) self.tbs.addItems(["0", "1", "2", "3"]) self.nice = QComboBox(self.group2) self.nice.addItems(["0", "1", "2", "3"]) vboxg2 = QVBoxLayout(self.group2) for each_widget in ( self.nwfl, self.smll, self.lrgf, self.case, self.cnvt, self.blnk, self.spac, self.whit, self.tabz, self.sprs, self.filn, QLabel("BLAH BLAH BLAH"), self.tbs, QLabel("BLAH BLAH BLAH"), self.nice, ): vboxg2.addWidget(each_widget) group3 = QGroupBox() group3.setTitle("Even More Options") self.plai = QCheckBox("Enable debug messages from libmv library") self.nocr = QCheckBox("Skip reading the startup.blend in the home dir") self.ridt = QCheckBox("Set BLENDER_SYSTEM_DATAFILES environment var") self.nocm = QCheckBox("Set BLENDER_SYSTEM_SCRIPTS environment var") self.rdif = QCheckBox("Set BLENDER_SYSTEM_PYTHON environment var") self.clip = QCheckBox("Disable joystick support") self.noti = QCheckBox("Disable GLSL shading") self.pret = QCheckBox("Force sound system to None") self.lolz = QCheckBox("Disable automatic python script execution") self.odif = QCheckBox("Run blender with an interactive console") self.plac = QCheckBox("Enable all debug messages, excludes libmv") self.plac = QCheckBox("Enable time profiling for background jobs") self.plac = QCheckBox("Do not use native pixel size for high res") self.wdth = QComboBox(group3) self.wdth.addItems(["OPENAL", "NULL", "SDL", "JACK"]) self.bcknd = QComboBox(group3) self.bcknd.addItems(["0", "5", "10", "15", "20"]) vboxg3 = QVBoxLayout(group3) for each_widget in ( self.plai, self.nocr, self.ridt, self.nocm, self.rdif, self.pret, self.clip, self.noti, self.lolz, self.odif, self.plac, QLabel('<b style="color:white">Force sound system to specific device'), self.wdth, QLabel('<b style="color:white">CPU Priority'), self.bcknd, ): vboxg3.addWidget(each_widget) # dock 2 the waterfall scrollable = QScrollArea() scrollable.setWidget(QLabel("".join((urlopen("http://builder.blender.org/waterfall").readlines()[23:])))) self.dock2.setWidget(scrollable) # dock 3 the build status stats = QLabel( "<center>" + "".join((urlopen("http://builder.blender.org/one_line_per_build").readlines()[23:])).strip() + "</center>" ) self.dock3.setWidget(stats) # configure some widget settings must_be_checked((self.nwfl, self.smll, self.lrgf, self.clip, self.cnvt, self.plai, self.noti)) must_have_tooltip( ( self.plai, self.nocr, self.ridt, self.nocm, self.rdif, self.pret, self.clip, self.noti, self.lolz, self.odif, self.plac, self.wdth, self.bcknd, self.nwfl, self.smll, self.lrgf, self.case, self.cnvt, self.blnk, self.spac, self.whit, self.tabz, self.sprs, self.filn, self.tbs, self.nice, self.arch, self.ost, ) ) must_autofillbackground( ( self.plai, self.nocr, self.ridt, self.nocm, self.rdif, self.pret, self.clip, self.noti, self.lolz, self.odif, self.plac, self.wdth, self.bcknd, self.nwfl, self.smll, self.lrgf, self.case, self.cnvt, self.blnk, self.spac, self.whit, self.tabz, self.sprs, self.filn, self.tbs, self.nice, scrollable, stats, self.arch, self.ost, ) ) container = QWidget() hbox = QHBoxLayout(container) for each_widget in (self.group2, self.group1, group3): hbox.addWidget(each_widget) self.dock1.setWidget(container)
def setTempProxy(self, host, port=None, username=None, password=None): proxy = QNetworkProxy() proxy.setType(QNetworkProxy.HttpProxy) if username: proxy.setUser(username) if password: proxy.setPassword(password) if port: proxy.setPort(port) proxy.setHostName(host) self.page().networkAccessManager().setProxy(proxy)
def __init__(self, args, parent=None): QObject.__init__(self, parent) # variable declarations self.m_loadStatus = self.m_state = '' self.m_var = self.m_paperSize = self.m_loadScript_cache = {} self.m_verbose = args.verbose self.m_page = WebPage(self) self.m_clipRect = QRect() # setup the values from args self.m_script = args.script.read() self.m_scriptFile = args.script.name self.m_scriptDir = os.path.dirname(args.script.name) + '/' self.m_args = args.script_args self.m_upload_file = args.upload_file autoLoadImages = False if args.load_images == 'no' else True pluginsEnabled = True if args.load_plugins == 'yes' else False args.script.close() do_action('PhantomInitPre', Bunch(locals())) palette = self.m_page.palette() palette.setBrush(QPalette.Base, Qt.transparent) self.m_page.setPalette(palette) if not args.proxy: QNetworkProxyFactory.setUseSystemConfiguration(True) else: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, args.proxy[0], int(args.proxy[1])) QNetworkProxy.setApplicationProxy(proxy) self.m_page.settings().setAttribute(QWebSettings.AutoLoadImages, autoLoadImages) self.m_page.settings().setAttribute(QWebSettings.PluginsEnabled, pluginsEnabled) self.m_page.settings().setAttribute( QWebSettings.FrameFlatteningEnabled, True) self.m_page.settings().setAttribute( QWebSettings.OfflineStorageDatabaseEnabled, True) self.m_page.settings().setAttribute(QWebSettings.LocalStorageEnabled, True) self.m_page.settings().setLocalStoragePath( QDesktopServices.storageLocation(QDesktopServices.DataLocation)) self.m_page.settings().setOfflineStoragePath( QDesktopServices.storageLocation(QDesktopServices.DataLocation)) # Ensure we have a document.body. self.m_page.mainFrame().setHtml('<html><body></body></html>') self.m_page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) self.m_page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) m_netAccessMan = NetworkAccessManager(args.disk_cache, args.ignore_ssl_errors, self) self.m_page.setNetworkAccessManager(m_netAccessMan) # inject our properties and slots into javascript self.m_page.mainFrame().javaScriptWindowObjectCleared.connect( self.inject) self.m_page.loadFinished.connect(self.finish) do_action('PhantomInitPost', Bunch(locals()))
def configure_proxy(cls, hostname, port, user=None, password=None, proxy_type=QNetworkProxy.HttpProxy): """ Configure network proxy layer. @param proxy_type: see QNetworkProxy.ProxyType. Default: HttpProxy. @param hostname: Proxy hostname. @param port: Proxy port. @param username: Proxy username (optional). @param passwrod: Proxy password (optional). """ proxy = QNetworkProxy() proxy.setType(proxy_type) proxy.setHostName(hostname) proxy.setPort(port) if user and password is not None: proxy.setUser(user) proxy.setPassword(password) QNetworkProxy.setApplicationProxy(proxy)
def _get_default_proxy_list(self): return [QNetworkProxy(QNetworkProxy.DefaultProxy)]
def _set_proxy(self, proxy): """Set the proxy to be used.""" QNetworkProxy.setApplicationProxy(proxy) self.nam.setProxy(proxy)
def removeProxy(self): """Removes the proxy configuration """ proxy = QNetworkProxy() proxy.setType(QNetworkProxy.NoProxy) self.setProxy(proxy)
def configureProxy(self, host, port, user=None, password=None): """Add a proxy configuration for the Network Requests. :param host: the proxy host :param port: the proxy port :param user: if the proxy has authentication this param sets the user to be used. It should be None if it's not required to access with a user :param password: if the proxy has authentication this param sets the password to be used. It should be None if it's not required to access with a password """ proxy = QNetworkProxy() proxy.setType(QNetworkProxy.HttpProxy) proxy.setHostName(host) proxy.setPort(port) if user is not None: proxy.setUser(user) if password is not None: proxy.setPassword(password) self._proxyAuth = (user, password) self.setProxy(proxy)
def set_proxy(self, string_proxy): """Set proxy [http|socks5]://username:password@hostname:port""" urlinfo = urlparse.urlparse(string_proxy) proxy = QNetworkProxy() if urlinfo.scheme == 'socks5' : proxy.setType(1) elif urlinfo.scheme == 'http' : proxy.setType(3) else : proxy.setType(2) self.manager.setProxy(proxy) return self.manager.proxy() proxy.setHostName(urlinfo.hostname) proxy.setPort(urlinfo.port) if urlinfo.username != None : proxy.setUser(urlinfo.username) else : proxy.setUser('') if urlinfo.password != None : proxy.setPassword(urlinfo.password) else : proxy.setPassword('') self.manager.setProxy(proxy) return self.manager.proxy()