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 __init__(self, parent=None): super().__init__(parent) self.setupTrayIcon() self.setIcon() self.trayIcon.show() self.setupView() self.view.load(QUrl(config.WX_URL)) self.view.setZoomFactor(self.physicalDpiX() * 0.008) self.setupLayout() QNetworkProxy.setApplicationProxy(proxy)
def proxy_from_url(url): """Create a QNetworkProxy from QUrl and a proxy type. Args: url: URL of a proxy (possibly with credentials). Return: New QNetworkProxy. """ if not url.isValid(): raise InvalidUrlError(url) scheme = url.scheme() if scheme in ['pac+http', 'pac+https', 'pac+file']: return pac.PACFetcher(url) types = { 'http': QNetworkProxy.HttpProxy, 'socks': QNetworkProxy.Socks5Proxy, 'socks5': QNetworkProxy.Socks5Proxy, 'direct': QNetworkProxy.NoProxy, } if scheme not in types: raise InvalidProxyTypeError(scheme) proxy = QNetworkProxy(types[scheme], url.host()) if url.port() != -1: proxy.setPort(url.port()) if url.userName(): proxy.setUser(url.userName()) if url.password(): proxy.setPassword(url.password()) return proxy
def _parse_proxy_entry(proxy_str): """Parse one proxy string entry, as described in PAC specification.""" config = [c.strip() for c in proxy_str.split(' ') if c] if not config: raise ParseProxyError("Empty proxy entry") elif config[0] == "DIRECT": if len(config) != 1: raise ParseProxyError("Invalid number of parameters for " + "DIRECT") return QNetworkProxy(QNetworkProxy.NoProxy) elif config[0] == "PROXY": if len(config) != 2: raise ParseProxyError("Invalid number of parameters for PROXY") host, port = PACResolver._parse_proxy_host(config[1]) return QNetworkProxy(QNetworkProxy.HttpProxy, host, port) elif config[0] in ["SOCKS", "SOCKS5"]: if len(config) != 2: raise ParseProxyError("Invalid number of parameters for SOCKS") host, port = PACResolver._parse_proxy_host(config[1]) return QNetworkProxy(QNetworkProxy.Socks5Proxy, host, port) else: err = "Unknown proxy type: {}" raise ParseProxyError(err.format(config[0]))
def configure_proxy(self): try: from urllib.parse import unquote except ImportError: from urllib import unquote url = os.environ.get('http_proxy') or os.environ.get( 'HTTP_PROXY') or '' url_decode = unquote(url) proxy = urlparse(url_decode) 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 disable_proxy(self): global proxy_string proxy_string = "" proxy = QNetworkProxy() proxy.setType(QNetworkProxy.NoProxy) self.is_proxy = False QNetworkProxy.setApplicationProxy(proxy)
def __init__(self, parent, apithread): super(NetworkAccessManager, self).__init__(parent) self.apithread = apithread proxy_url = os.environ.get('http_proxy') if proxy_url: url = urllib.parse.urlparse(proxy_url) proxy = QNetworkProxy() proxy.setType(QNetworkProxy.HttpProxy) proxy.setHostName(url.hostname) proxy.setPort(url.port) self.setProxy(proxy) self.reply_content = {}
def proxyAuthentication(self, requestUrl, auth, proxyHost): """ Public slot to handle a proxy authentication request. @param requestUrl requested URL @type QUrl @param auth reference to the authenticator object @type QAuthenticator @param proxyHost name of the proxy host @type str """ proxy = QNetworkProxy.applicationProxy() if proxy.user() and proxy.password(): auth.setUser(proxy.user()) auth.setPassword(proxy.password()) return proxyAuthenticationRequired(proxy, auth)
def transform(self, value): if not value: return None elif value == 'system': return SYSTEM_PROXY elif value == 'none': return QNetworkProxy(QNetworkProxy.NoProxy) url = QUrl(value) typ = self.PROXY_TYPES[url.scheme()] proxy = QNetworkProxy(typ, url.host()) if url.port() != -1: proxy.setPort(url.port()) if url.userName(): proxy.setUser(url.userName()) if url.password(): proxy.setPassword(url.password()) return proxy
def __init__( self, windowTitle, parent=None ): super( WebBrowser, self ).__init__() screen = QApplication.desktop().screenGeometry() self._browser = QWebView( parent=parent ) self._browser.resize( screen.width( ) / 4 * 3, screen.height() / 4 * 3 ) # TODO: move proxy settings to ToolBOS.conf proxy = QNetworkProxy( ) proxy.setType( QNetworkProxy.HttpProxy ) proxy.setHostName( 'hri-proxy.honda-ri.de' ) proxy.setPort( 3128 ) nm = self._browser.page().networkAccessManager() nm.setProxy( proxy ) nm.sslErrors.connect( QNetworkReply.ignoreSslErrors ) self._browser.setWindowTitle( windowTitle )
def resolve(self, query): """Resolve a query via PAC. Args: QNetworkProxyQuery. Return a list of QNetworkProxy objects in order of preference. """ self._wait() try: return self._pac.resolve(query) except (EvalProxyError, ParseProxyError) as e: log.network.exception("Error in PAC resolution: {}.".format(e)) # .invalid is guaranteed to be inaccessible in RFC 6761. # Port 9 is for DISCARD protocol -- DISCARD servers act like # /dev/null. # Later NetworkManager.createRequest will detect this and display # an error message. error_host = "pac-resolve-error.qutebrowser.invalid" return QNetworkProxy(QNetworkProxy.HttpProxy, error_host, 9)
def __init__(self, url, parent=None): """Resolve a PAC proxy from URL. Args: url: QUrl of a PAC proxy. """ super().__init__(parent) pac_prefix = "pac+" assert url.scheme().startswith(pac_prefix) url.setScheme(url.scheme()[len(pac_prefix):]) self._pac_url = url self._manager = QNetworkAccessManager() self._manager.setProxy(QNetworkProxy(QNetworkProxy.NoProxy)) self._pac = None self._error_message = None self._reply = None
def proxy_from_url(url): """Create a QNetworkProxy from QUrl and a proxy type. Args: url: URL of a proxy (possibly with credentials). Return: New QNetworkProxy. """ if not url.isValid(): raise InvalidUrlError(url) scheme = url.scheme() if scheme in ['pac+http', 'pac+https', 'pac+file']: fetcher = pac.PACFetcher(url) fetcher.fetch() return fetcher types = { 'http': QNetworkProxy.HttpProxy, 'socks': QNetworkProxy.Socks5Proxy, 'socks5': QNetworkProxy.Socks5Proxy, 'direct': QNetworkProxy.NoProxy, } if scheme not in types: raise InvalidProxyTypeError(scheme) proxy = QNetworkProxy(types[scheme], url.host()) if url.port() != -1: proxy.setPort(url.port()) if url.userName(): proxy.setUser(url.userName()) if url.password(): proxy.setPassword(url.password()) return proxy
class TestProxyFromUrl: @pytest.mark.parametrize('url, expected', [ ('socks://example.com/', QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')), ('socks5://example.com', QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')), ('socks5://example.com:2342', QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2342)), ('socks5://[email protected]', QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 0, 'foo')), ('socks5://foo:[email protected]', QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 0, 'foo', 'bar')), ('socks5://foo:[email protected]:2323', QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2323, 'foo', 'bar')), ('direct://', QNetworkProxy(QNetworkProxy.NoProxy)), ]) def test_proxy_from_url_valid(self, url, expected): assert urlutils.proxy_from_url(QUrl(url)) == expected @pytest.mark.qt_log_ignore( r'^QHttpNetworkConnectionPrivate::_q_hostLookupFinished could not ' r'de-queue request, failed to report HostNotFoundError') @pytest.mark.parametrize('scheme', ['pac+http', 'pac+https']) def test_proxy_from_url_pac(self, scheme, qapp): fetcher = urlutils.proxy_from_url(QUrl('{}://foo'.format(scheme))) assert isinstance(fetcher, pac.PACFetcher) @pytest.mark.parametrize( 'url, exception', [ ('blah', urlutils.InvalidProxyTypeError), (':', urlutils.InvalidUrlError), # invalid URL # Invalid/unsupported scheme ('ftp://example.com/', urlutils.InvalidProxyTypeError), ('socks4://example.com/', urlutils.InvalidProxyTypeError), ]) def test_invalid(self, url, exception): with pytest.raises(exception): urlutils.proxy_from_url(QUrl(url))
def __init__(self, url, parent=None): """Resolve a PAC proxy from URL. Args: url: QUrl of a PAC proxy. """ super().__init__(parent) pac_prefix = "pac+" assert url.scheme().startswith(pac_prefix) url.setScheme(url.scheme()[len(pac_prefix):]) self._pac_url = url with log.disable_qt_msghandler(): # WORKAROUND for a hang when messages are printed, see our # NetworkAccessManager subclass for details. self._manager: Optional[ QNetworkAccessManager] = QNetworkAccessManager() self._manager.setProxy(QNetworkProxy(QNetworkProxy.NoProxy)) self._pac = None self._error_message = None self._reply = None
class TestProxyFromUrl: @pytest.mark.parametrize('url, expected', [ ('socks://example.com/', QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')), ('socks5://example.com', QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')), ('socks5://example.com:2342', QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2342)), ('socks5://[email protected]', QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 0, 'foo')), ('socks5://foo:[email protected]', QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 0, 'foo', 'bar')), ('socks5://foo:[email protected]:2323', QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2323, 'foo', 'bar')), ('direct://', QNetworkProxy(QNetworkProxy.NoProxy)), ]) def test_proxy_from_url_valid(self, url, expected): assert urlutils.proxy_from_url(QUrl(url)) == expected @pytest.mark.parametrize('scheme', ['pac+http', 'pac+https']) def test_proxy_from_url_pac(self, scheme, qapp): fetcher = urlutils.proxy_from_url(QUrl('{}://foo'.format(scheme))) assert isinstance(fetcher, pac.PACFetcher) @pytest.mark.parametrize( 'url, exception', [ ('blah', urlutils.InvalidProxyTypeError), (':', urlutils.InvalidUrlError), # invalid URL # Invalid/unsupported scheme ('ftp://example.com/', urlutils.InvalidProxyTypeError), ('socks4://example.com/', urlutils.InvalidProxyTypeError), ]) def test_invalid(self, url, exception): with pytest.raises(exception): urlutils.proxy_from_url(QUrl(url))
def _get_default_proxy_list(self): return [QNetworkProxy(QNetworkProxy.DefaultProxy)]
server = ThreadingEPCServer(('localhost', 0), log_traceback=True) server_thread = threading.Thread(target=server.serve_forever) server_thread.allow_reuse_address = True emacs_xwindow_id = 0 buffer_dict = {} cookie_jar = CookieJar() print_console_info = False if len(sys.argv) >= 2 and sys.argv[1] == "--enable-proxy": QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.Socks5Proxy, "127.0.0.1", 7070)) def call_message(message): call_method("message", [message]) def call_method(method_name, args): handler = server.clients[0] handler.call(method_name, args) def handle_active_window(active_window_id): global emacs_xwindow_id emacs_real_id = get_parent_window_id(emacs_xwindow_id) call_method("message", ["handle_active_window: %s %s %s" % (active_window_id, emacs_xwindow_id, emacs_real_id)])
def __init__(self, args): global emacs_width, emacs_height, eaf_config_dir, proxy_string dbus.service.Object.__init__( self, dbus.service.BusName(EAF_DBUS_NAME, bus=dbus.SessionBus()), EAF_OBJECT_NAME) (emacs_width, emacs_height, proxy_host, proxy_port, proxy_type, config_dir, var_dict_string) = args emacs_width = int(emacs_width) emacs_height = int(emacs_height) eaf_config_dir = os.path.expanduser(config_dir) self.buffer_dict = {} self.view_dict = {} self.emacs_var_dict = {} self.update_emacs_var_dict(var_dict_string) self.first_start(self.webengine_include_private_codec()) self.session_file = os.path.join(eaf_config_dir, "session.json") # Set Network proxy. if proxy_host != "" and proxy_port != "": proxy_string = "{0}://{1}:{2}".format(proxy_type, proxy_host, proxy_port) proxy = QNetworkProxy() if proxy_type == "socks5": proxy.setType(QNetworkProxy.Socks5Proxy) elif proxy_type == "http": proxy.setType(QNetworkProxy.HttpProxy) proxy.setHostName(proxy_host) proxy.setPort(int(proxy_port)) QNetworkProxy.setApplicationProxy(proxy)
def __init__(self, args): global emacs_width, emacs_height, eaf_config_dir dbus.service.Object.__init__( self, dbus.service.BusName(EAF_DBUS_NAME, bus=dbus.SessionBus()), EAF_OBJECT_NAME) (emacs_width, emacs_height, proxy_host, proxy_port, proxy_type, config_dir, var_dict_string) = args emacs_width = int(emacs_width) emacs_height = int(emacs_height) eaf_config_dir = os.path.expanduser(config_dir) self.emacs_var_dict = {} for var_pair in var_dict_string.split("ᛡ"): (var_name, var_value) = var_pair.split("ᛝ") self.emacs_var_dict[var_name] = var_value self.buffer_dict = {} self.view_dict = {} self.start_finish() self.session_file = os.path.join(eaf_config_dir, "session.json") # Set Network proxy. if proxy_host != "" and proxy_port != "": proxy = QNetworkProxy() if proxy_type == "socks5": proxy.setType(QNetworkProxy.Socks5Proxy) elif proxy_type == "http": proxy.setType(QNetworkProxy.HttpProxy) proxy.setHostName(proxy_host) proxy.setPort(int(proxy_port)) QNetworkProxy.setApplicationProxy(proxy)
def apply(self): QNetworkProxy.setApplicationProxy(self)
def reset_proxy_settings(): QNetworkProxy.setApplicationProxy(QNetworkProxy())
class _WebEngineRendererHelper(QObject): """ This helper class is doing the real work. It is required to allow WebEngineRenderer.render() to be called "asynchronously" (but always from Qt's GUI thread). """ def __init__(self, parent): """ Copies the properties from the parent (WebEngineRenderer) object, creates the required instances of QWebPage, QWebView and QMainWindow and registers some Slots. """ QObject.__init__(self) # Copy properties from parent for key, value in parent.__dict__.items(): setattr(self, key, value) # Determine Proxy settings proxy = QNetworkProxy(QNetworkProxy.NoProxy) if 'http_proxy' in os.environ: proxy_url = QUrl(os.environ['http_proxy']) if proxy_url.scheme().startswith('http'): protocol = QNetworkProxy.HttpProxy else: protocol = QNetworkProxy.Socks5Proxy proxy = QNetworkProxy(protocol, proxy_url.host(), proxy_url.port(), proxy_url.userName(), proxy_url.password()) # Create and connect required PyQt5 objects self._page = CustomWebPage(logger=self.logger, ignore_alert=self.ignoreAlert, ignore_confirm=self.ignoreConfirm, ignore_prompt=self.ignorePrompt, interrupt_js=self.interruptJavaScript) self._qt_proxy = QNetworkProxy() self._qt_proxy.setApplicationProxy(proxy) self._view = QWebEngineView() self._view.setPage(self._page) _window_flags = Qt.WindowFlags() self._window = QMainWindow(flags=_window_flags) self._window.setCentralWidget(self._view) self._qt_network_access_manager = QNetworkAccessManager() # Import QWebSettings for key, value in self.qWebSettings.items(): self._page.settings().setAttribute(key, value) # Connect required event listeners # assert False, "Not finish" self._page.loadFinished.connect(self._on_load_finished) self._page.loadStarted.connect(self._on_load_started) self._qt_network_access_manager.sslErrors.connect(self._on_ssl_errors) self._qt_network_access_manager.finished.connect(self._on_each_reply) # The way we will use this, it seems to be unnecessary to have Scrollbars enabled self._scroll_area = QAbstractScrollArea() self._scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self._scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # Show this widget self._window.show() def __del__(self): """ Clean up Qt5 objects. """ self._window.close() del self._window del self._view del self._page def render(self, res): """ The real worker. Loads the page (_load_page) and awaits the end of the given 'delay'. While it is waiting outstanding QApplication events are processed. After the given delay, the Window or Widget (depends on the value of 'grabWholeWindow' is drawn into a QScreen and post processed (_post_process_image). """ self._load_page(res, self.width, self.height, self.timeout) # Wait for end of timer. In this time, process # other outstanding Qt events. if self.wait > 0: if self.logger: self.logger.debug("Waiting {} seconds ".format(self.wait)) wait_to_time = time.time() + self.wait while time.time() < wait_to_time: if self.app.hasPendingEvents(): self.app.processEvents() if self.renderTransparentBackground: # Another possible drawing solution image = QImage(self._page.viewportSize(), QImage.Format_ARGB32) image.fill(QColor(255, 0, 0, 0).rgba()) # http://ariya.blogspot.com/2009/04/transparent-qwebview-and-qwebpage.html palette = self._view.palette() palette.setBrush(QPalette.Base, Qt.transparent) self._page.setPalette(palette) self._view.setAttribute(Qt.WA_OpaquePaintEvent, False) painter = QPainter(image) painter.setBackgroundMode(Qt.TransparentMode) self._window.render(painter) painter.end() else: if self.grabWholeWindow: # Note that this does not fully ensure that the # window still has the focus when the screen is # grabbed. This might result in a race condition. self._view.activateWindow() qt_screen = self.app.primaryScreen() image = qt_screen.grabWindow(sip.voidptr(0)) else: image = self._window.grab() return self._post_process_image(image) def _load_page(self, res, width, height, timeout): """ This method implements the logic for retrieving and displaying the requested page. """ # This is an event-based application. So we have to wait until # "loadFinished(bool)" raised. cancel_at = time.time() + timeout self.__loading = True self.__loadingResult = False # Default # When "res" is of type tuple, it has two elements where the first # element is the HTML code to render and the second element is a string # setting the base URL for the interpreted HTML code. # When resource is of type str or unicode, it is handled as URL which # shall be loaded if type(res) == tuple: url = res[1] else: url = res if self.encodedUrl: qt_url = QUrl().fromEncoded(url) else: qt_url = QUrl(url) # Set the required cookies, if any self.cookieJar = CookieJar(self.cookies, qt_url) self._qt_network_access_manager.setCookieJar(self.cookieJar) # Load the page if type(res) == tuple: self._page.setHtml(res[0], qt_url) # HTML, baseUrl else: self._page.load(qt_url) while self.__loading: if timeout > 0 and time.time() >= cancel_at: raise RuntimeError("Request timed out on {}".format(res)) while self.app.hasPendingEvents() and self.__loading: self.app.processEvents() if self.logger: self.logger.debug("Processing result") if not self.__loading_result: if self.logger: self.logger.warning("Failed to load {}".format(res)) # Set initial viewport (the size of the "window") size = self._page.contentsSize() if self.logger: self.logger.debug("contentsSize: %s", size) if width > 0: size.setWidth(width) if height > 0: size.setHeight(height) self._window.resize(size.toSize()) def _post_process_image(self, q_image): """ If 'scaleToWidth' or 'scaleToHeight' are set to a value greater than zero this method will scale the image using the method defined in 'scaleRatio'. """ if self.scaleToWidth > 0 or self.scaleToHeight > 0: # Scale this image if self.scaleRatio == 'keep': ratio = Qt.KeepAspectRatio elif self.scaleRatio in ['expand', 'crop']: ratio = Qt.KeepAspectRatioByExpanding else: # 'ignore' ratio = Qt.IgnoreAspectRatio q_image = q_image.scaled(self.scaleToWidth, self.scaleToHeight, ratio, Qt.SmoothTransformation) if self.scaleRatio == 'crop': q_image = q_image.copy(0, 0, self.scaleToWidth, self.scaleToHeight) return q_image @pyqtSlot(QNetworkReply, name='finished') def _on_each_reply(self, reply): """ Logs each requested uri """ self.logger.debug("Received {}".format(reply.url().toString())) # Event for "loadStarted()" signal @pyqtSlot(name='loadStarted') def _on_load_started(self): """ Slot that sets the '__loading' property to true """ if self.logger: self.logger.debug("loading started") self.__loading = True # Event for "loadFinished(bool)" signal @pyqtSlot(bool, name='loadFinished') def _on_load_finished(self, result): """ Slot that sets the '__loading' property to false and stores the result code in '__loading_result'. """ if self.logger: self.logger.debug("loading finished with result %s", result) self.__loading = False self.__loading_result = result # Event for "sslErrors(QNetworkReply *,const QList<QSslError>&)" signal @pyqtSlot('QNetworkReply*', 'QList<QSslError>', name='sslErrors') def _on_ssl_errors(self, reply, errors): """ Slot that writes SSL warnings into the log but ignores them. """ for e in errors: if self.logger: self.logger.warn("SSL: " + e.errorString()) reply.ignoreSslErrors() @property def window(self): return self._window
class proxyTest(): def __init__(self, proxyprotocol=QNetworkProxy.Socks5Proxy, proxyhostname="127.0.0.1", proxyhostport=1080, targethosturl="http://www.google.com", getproxyStatus=False, timeout=False): self.protocol = proxyprotocol self.proxyhostName = proxyhostname self.port = int(proxyhostport) self.url = targethosturl self.proxyStatus = getproxyStatus self.reply = None self.stopCheckProxy = None self.req = None self.qnam = QNetworkAccessManager() if (self.proxyStatus): self.req = QNetworkRequest(QUrl(self.url)) self.proxy = QNetworkProxy() self.proxy.setType(self.protocol) self.proxy.setHostName(self.proxyhostName) self.proxy.setPort(self.port) self.proxy.setApplicationProxy(self.proxy) if timeout == 0: self.startRequest() else: self.stopCheckProxy = QTimer() self.stopCheckProxy.timeout.connect(self.timeoutStopCheckProxy) self.stopCheckProxy.setSingleShot(True) if timeout > 15 or timeout < 0: timeout = 5 # after five seconds stop checking the proxy and destroy this class self.stopCheckProxy.start(1000 * timeout) self.startRequest() def startRequest(self): self.reply = self.qnam.get(self.req) self.reply.finished.connect(self.handleResponse) self.proxyStatus.elapsedTimer.start() def timeoutStopCheckProxy(self): """ Frequent detection of proxy server, memory overflow may occur. Therefore, it should be automatically destroyed within the stipulated time. Not sure if GC is working """ self.reply.abort() self.reply.close() # print(sys.getrefcount(self)) del self.protocol self.proxyhostName self.port self.url self.reply self.stopCheckProxy del self.req self.qnam self.proxy del self def handleResponse(self): errorCode = self.reply.error() if errorCode == QNetworkReply.NoError: self.proxyStatus.setTargetHostReplyMessage( replyMessage=str(self.reply.readAll(), "utf-8")) self.proxyStatus.setTargetHostReply(reply=True) self.proxyStatus.setProxyisWorking(True) else: self.proxyStatus.setProxyErrorString( errorString=self.reply.errorString()) self.proxyStatus.setProxyError( error=True) # proxy connection error self.proxyStatus.setProxyErrorCode(errorCode=self.reply.error()) self.proxyStatus.setProxyisWorking(False) self.proxyStatus.setElapsedTime( self.proxyStatus.elapsedTimer.elapsed()) self.proxyStatus.signal.emit()
def __init__(self, protocol=False, proxyhostName=False, port=False, v2rayapi=False, bridgetreasureChest=False): super().__init__() self.translate = QCoreApplication.translate self.update = { "enable": True, "schedule": { "date": 8, "time": 4 }, "install": "auto", # ## auto install/ manual install "downloadFile": False, "silentInstall": True } self.daysoftheweek = (self.translate("v2rayUpdatePanel", "Select a Day for update"), self.translate("v2rayUpdatePanel", "Every Monday"), self.translate("v2rayUpdatePanel", "Every Tuesday"), self.translate("v2rayUpdatePanel", "Every Wednesday"), self.translate("v2rayUpdatePanel", "Every Thursday"), self.translate("v2rayUpdatePanel", "Every Friday"), self.translate("v2rayUpdatePanel", "Every Saturday"), self.translate("v2rayUpdatePanel", "Every Sunday"), self.translate("v2rayUpdatePanel", "Every Day")) self.downloadFiles = ("v2ray-windows-64.zip", "v2ray-macos.zip", "v2ray-linux-64.zip", "v2ray-windows-32.zip", "v2ray-linux-32.zip", "v2ray-freebsd-32.zip", "v2ray-freebsd-64.zip", "v2ray-linux-arm.zip", "v2ray-linux-arm64.zip", "v2ray-linux-mips.zip", "v2ray-linux-mips64.zip", "v2ray-linux-mips64le.zip", "v2ray-linux-mipsle.zip", "v2ray-openbsd-32.zip", "v2ray-openbsd-64.zip", "v2ray-linux-s390x.zip") self.protocol = protocol self.proxyhostName = proxyhostName self.port = port if (v2rayapi): self.v2rayAPI = v2rayapi else: self.v2rayAPI = v2rayAPI() self.bridgetreasureChest = bridgetreasureChest if not self.bridgetreasureChest: from bridgehouse.extension import bridgetreasureChest self.bridgetreasureChest = bridgetreasureChest.bridgetreasureChest( ) self.v2raycoreAPIURL = QUrl( r"""https://api.github.com/repos/v2ray/v2ray-core/releases/latest""" ) self.spinBoxPort = QSpinBox() self.lineEditProxy = QLineEdit() self.radioButtonSocks5 = QRadioButton("Socks") self.radioButtonHttp = QRadioButton("Http") self.groupBoxViaProxy = QGroupBox( self.translate("v2rayUpdatePanel", "Via Proxy")) self.groupBoxViaProxy.setCheckable(True) self.proxy = QNetworkProxy() if (self.protocol and self.proxyhostName and self.port and v2rayapi): self.settingProxyhost(protocol, proxyhostName, port) self.groupBoxViaProxy.setChecked(True) else: self.groupBoxViaProxy.setChecked(False)
def setProxy(self, enable, hostname, port, username, password): proxy = QNetworkProxy() if enable: proxy.setType(QNetworkProxy.HttpProxy) print("启动代理") print("主机名", hostname) print("端口", port) print("用户名", username) print("密码", password) else: proxy.setType(QNetworkProxy.NoProxy) print("取消代理") proxy.setHostName(hostname) proxy.setPort(port) proxy.setUser(username) proxy.setPassword(password) QNetworkProxy.setApplicationProxy(proxy)
class MyWebView(QWebEngineView): def __init__(self, parent=None, acc=None): super().__init__() self.parent = parent self.session = acc.session self.user_id = acc.user_id self.chekLoadFinish = False self.progress = 0 # Connect sql and get data os.chdir('/root/PycharmProjects/HearSheep') con = sql.connect(os.getcwd() + '/db/db.sqlite3') cur = con.cursor() with con: cur.execute('SELECT login, pass, token, proxy, user_agent FROM accaunt where user_id=?', (self.user_id,)) row = cur.fetchone() self.login, self.password, self.token, proxy, user_agent = row con.close() # Path Cookies os.chdir('/root/PycharmProjects/HearSheep') pathCookies = '/root/PycharmProjects/HearSheep/cookies/' + str(self.user_id) if os.path.exists(pathCookies): pass else: os.chdir('/root/PycharmProjects/HearSheep/cookies') os.mkdir(str(self.user_id)) pathCookies = '/root/PycharmProjects/HearSheep/cookies/' + str(self.user_id) # settings profile = self.page().profile() profile.setPersistentStoragePath(pathCookies) profile.setHttpUserAgent(user_agent) profile.setHttpAcceptLanguage("ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4") urlinfo = parse.urlparse(proxy) self.proxy = QNetworkProxy() self.proxy.setType(QNetworkProxy.HttpProxy) self.proxy.setHostName(urlinfo.hostname) self.proxy.setPort(urlinfo.port) self.proxy.setUser(urlinfo.username) self.proxy.setPassword(urlinfo.password) QNetworkProxy.setApplicationProxy(self.proxy) self.page().proxyAuthenticationRequired.connect(self.handleProxyAuthReq) self.loadProgress.connect(self.setProgress) self.load(QtCore.QUrl('https://vk.com/')) self.auth() def handleProxyAuthReq(self, url, auth, proxyhost): auth.setUser(self.proxy.user()) auth.setPassword(self.proxy.password()) def setProgress(self, value): self.progress = value def waitForSignal(self): loop = QEventLoop() def work(value): print('loop', value) if value > 95: loop.quit() self.loadProgress.connect(work) loop.exec_() self.loadProgress.disconnect() time.sleep(2) return True def auth(self): self.waitForSignal() if self.page().url().url() == 'https://vk.com/' or self.page().url().url() == 'https://vk.com/index.php': page = self.page() page.runJavaScript( 'document.querySelector("#index_email").value = "{}"'.format(self.login)) page.runJavaScript( 'document.querySelector("#index_pass").value = "{}"'.format(self.password)) page.runJavaScript( 'document.querySelector("#index_login_button").click()') print('auth complete') def joinTheChat(self, chat): number_chat, count_users, invite_link = chat print('connect to', invite_link) self.load(QtCore.QUrl(invite_link)) print('waiting load inviting page') self.waitForSignal() page = self.page() page.runJavaScript( "document.querySelector('button.flat_button.round_button._im_join_chat.im-invitation--join').click()") print('waiting after clicking the button "connect"') self.waitForSignal() # Check the entry in the chat print('get dialogs') getUrl = UrlAPI(self.token) response = self.session.get(getUrl.messages.getDialogs(count=3), proxies=self.session.proxies) dialogs = json.loads(response.text)['response']['items'] for dialog in dialogs: print(dialog) if dialog['message']['title'] == 'Читаем стихи': print('Find') os.chdir('/root/PycharmProjects/HearSheep') con = sql.connect(os.getcwd() + '/db/db.sqlite3') cur = con.cursor() with con: cur.execute('INSERT INTO accaunt_chat(user_id,chat_id,number_chat) VALUES(?,?,?)', (self.user_id, dialog['message']['chat_id'], number_chat)) cur.execute('UPDATE chat SET count_users=? WHERE number_chat=?', (count_users+1, number_chat)) con.close() print('joined the chat') return True print("not joined the chat") return False def createChat(self): getUrl = UrlAPI(self.token) response = self.session.get(getUrl.messages.createChat(title='Читаем стихи'), proxies=self.session.proxies) jResponse = json.loads(response.text) if 'response' in jResponse: chat_id = jResponse['response'] peer_id = 2000000000 + chat_id res = self.session.get(getUrl.messages.getInviteLink(peer_id=peer_id), proxies=self.session.proxies) jRes = json.loads(res.text)['response'] invite_link = jRes['link'] os.chdir('/root/PycharmProjects/HearSheep') con = sql.connect(os.getcwd() + '/db/db.sqlite3') cur = con.cursor() with con: cur.execute('INSERT INTO chat(number_chat,count_users,invite_link) VALUES (NULL,1,?)', (invite_link, )) cur.execute('SELECT number_chat FROM chat WHERE invite_link=?', (invite_link, )) row = cur.fetchone() number_chat = row[0] cur.execute('INSERT INTO accaunt_chat(user_id,chat_id,number_chat) VALUES (?,?,?)', (self.user_id, chat_id, number_chat)) con.close() print('the chat created') return True print("the chat don't created") return False def sendMessage(self): page = self.page() page.runJavaScript( "document.getElementById('im_editable88230675').innerHTML = 'Йо!'") page.runJavaScript( "document.querySelector('button.im-send-btn.im-chat-input--send.im-send-btn_saudio._im_send.im-send-btn_audio').click()")
import config from PyQt5.QtNetwork import QNetworkProxy proxy = QNetworkProxy() if not config.PROXY_ENABLE: proxy.setType(QNetworkProxy.NoProxy) else: proxy_type = config.PROXY_INFO[0] if proxy_type == "socks5": proxy.setType(QNetworkProxy.Socks5Proxy) proxy.setHostName(config.PROXY_INFO[1]) proxy.setPort(config.PROXY_INFO[2]) else: raise Exception("Not implemented proxy type")
def __init__(self, url): super(PersephonepWindow, self).__init__() self.setAttribute(Qt.WA_DeleteOnClose, True) # def Generate(self, url): self.initurl = url # config # initurl = 'https://www.google.co.jp' # setting window self.window = QWebEngineView() # # Set WebPage with javascript console output. # self.window.setPage(WebPageWithJSConsole(self.window)) # proxy = QNetworkProxy() proxy.setType(QNetworkProxy.NoProxy) QNetworkProxy.setApplicationProxy(proxy) # condig url self.window.load(QUrl(self.initurl)) self.window.setWindowTitle(__program__) # setting button self.reload_button = QPushButton('reload') self.reload_button.setToolTip('Reload this page.') self.reload_button.clicked.connect(self.window.reload) ## ## Download dialog ## self.progress = QProgressBar(self) self.progress.setMaximum(100) self.progress.setStyleSheet(PROGRESS_STYLE) self.progress.hide() self.downloading_filename = '' ## ## self.url_edit = QLineEdit() self.url_edit.setText(self.initurl) self.url_edit.setReadOnly(True) self.url_edit.setToolTip('URL box') self.home_button = QPushButton('home') self.home_button.setToolTip('Move to the home page.') self.home_button.clicked.connect(self.loadHomePage) # signal catch from moving web pages. ## ## Download dialog ## self.window.urlChanged.connect(self.updateCurrentUrl) self.window.page().profile().downloadRequested.connect( self.on_download_requested) ## self.tab = QGridLayout() self.tab.setSpacing(0) self.tab.addWidget(self.reload_button, 1, 2) self.tab.addWidget(self.url_edit, 1, 3, 1, 10) self.tab.addWidget(self.window, 2, 0, 5, 16) self.tab.addWidget(self.progress, 7, 0, 1, 3) #### Download self.setLayout(self.tab)
def enable_proxy(self): global proxy_string proxy_string = "{0}://{1}:{2}".format(self.proxy[0], self.proxy[1], self.proxy[2]) proxy = QNetworkProxy() if self.proxy[0] == "socks5": proxy.setType(QNetworkProxy.Socks5Proxy) elif self.proxy[0] == "http": proxy.setType(QNetworkProxy.HttpProxy) proxy.setHostName(self.proxy[1]) proxy.setPort(int(self.proxy[2])) self.is_proxy = True QNetworkProxy.setApplicationProxy(proxy)
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"]: # use proxy at all ? if not Preferences.getUI("UseProxy"): return [QNetworkProxy(QNetworkProxy.NoProxy)] # test for exceptions exceptions = Preferences.getUI("ProxyExceptions") if exceptions != self.__exceptions: self.__setExceptions(exceptions) urlHost = query.url().host() for matcher in self.__hostnameMatchers: if matcher.match(urlHost): return [QNetworkProxy(QNetworkProxy.NoProxy)] # determine proxy if Preferences.getUI("UseSystemProxy"): proxyList = QNetworkProxyFactory.systemProxyForQuery(query) if not Globals.isWindowsPlatform() 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() == "http": proxyType = QNetworkProxy.HttpProxy elif url.scheme() == "https": proxyType = QNetworkProxy.HttpCachingProxy elif url.scheme() == "ftp": proxyType = QNetworkProxy.FtpCachingProxy else: proxyType = QNetworkProxy.HttpProxy proxy = QNetworkProxy(proxyType, url.host(), url.port(), url.userName(), url.password()) proxyList = [proxy] break if proxyList: scheme = schemeFromProxyType(proxyList[0].type()) if scheme == "": scheme = "Http" if scheme != "NoProxy": proxyList[0].setUser( Preferences.getUI("ProxyUser/{0}".format(scheme))) proxyList[0].setPassword( Preferences.getUI( "ProxyPassword/{0}".format(scheme))) return proxyList else: return [QNetworkProxy(QNetworkProxy.NoProxy)] else: if Preferences.getUI("UseHttpProxyForAll"): protocolKey = "Http" else: protocolKey = query.protocolTag().capitalize() host = Preferences.getUI("ProxyHost/{0}".format(protocolKey)) if not host: E5MessageBox.critical( None, QCoreApplication.translate( "E5NetworkProxyFactory", "Proxy Configuration Error"), QCoreApplication.translate( "E5NetworkProxyFactory", """Proxy usage was activated""" """ but no proxy host for protocol""" """ '{0}' configured.""").format(protocolKey)) return [QNetworkProxy(QNetworkProxy.DefaultProxy)] else: if protocolKey in ["Http", "Https", "Ftp"]: if query.protocolTag() == "ftp": proxyType = QNetworkProxy.FtpCachingProxy elif query.protocolTag() == "https": proxyType = QNetworkProxy.HttpCachingProxy else: proxyType = QNetworkProxy.HttpProxy proxy = QNetworkProxy( proxyType, host, Preferences.getUI("ProxyPort/" + protocolKey), Preferences.getUI("ProxyUser/" + protocolKey), Preferences.getUI("ProxyPassword/" + protocolKey)) else: proxy = QNetworkProxy(QNetworkProxy.DefaultProxy) return [proxy, QNetworkProxy(QNetworkProxy.DefaultProxy)] else: return [QNetworkProxy(QNetworkProxy.NoProxy)]
def set_no_proxy_in_qt_app(): logging.info(f"Set no proxy in Qt application") QNetworkProxy.setApplicationProxy(QNetworkProxy())
class updateV2ray(QObject): downloadFinish = pyqtSignal() def __init__(self, v2rayapi=False, url=False, checkDownloadInfo=False, downloadV2raycore=False): super().__init__() self.downloadURL = url self.reply = None self.outFile = None self.fileName = None self.httpRequestAborted = False self.v2rayAPI = v2rayapi self.v2raycoreAPIURL = QUrl( r"""https://api.github.com/repos/v2ray/v2ray-core/releases/latest""" ) Qt.Everyday = 8 self.downloadPath = False self.qnam = QNetworkAccessManager() self.startV2ray = False self.stopV2ray = False self.translate = QCoreApplication.translate self.msgBox = QMessageBox() self.fly = QApplication.desktop().screen().rect().center( ) - self.msgBox.rect().center() self.silentInstall = False self.installOption = "auto" if (self.v2rayAPI and self.downloadURL and checkDownloadInfo): self.getV2raycoreInfoFromGithub() elif (self.v2rayAPI and self.downloadURL and downloadV2raycore): self.downloadV2raycore() else: pass def getv2raycoreAPIURL(self): return self.v2raycoreAPIURL def enableSilentInstall(self): self.silentInstall = True def downloadV2raycore(self, url=False): if (url): self.downloadURL = url fileInfo = QFileInfo(self.downloadURL.path()) self.fileName = fileName = fileInfo.fileName() if not fileName: fileName = "v2ray.zip" if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): if (not self.silentInstall): self.msgBox.information( QDialog().move(self.fly), self.translate("updateV2ray", "Download {}").format(fileName), self.translate("updateV2ray", "Unable to save the file {}: {}.").format( fileName, self.outFile.errorString())) self.outFile = None return self.httpRequestAborted = False if (not self.silentInstall): self.progressDialog = QProgressDialog() self.progressDialog.setLabelText( self.translate("updateV2ray", "v2ray-core is downloading...")) self.progressDialog.canceled.connect(self.cancelDownload) self.startRequest(self.downloadURL) def startRequest(self, url): self.reply = self.qnam.get(QNetworkRequest(url)) self.reply.finished.connect(self.httpFinished) self.reply.readyRead.connect(self.httpReadyRead) if (not self.silentInstall): self.reply.downloadProgress.connect(self.updateDataReadProgress) def httpReadyRead(self): if self.outFile is not None: self.outFile.write(self.reply.readAll()) def updateDataReadProgress(self, bytesRead, totalBytes): if self.httpRequestAborted: return self.progressDialog.setMaximum(totalBytes) self.progressDialog.setValue(bytesRead) def cancelDownload(self): self.httpRequestAborted = True if self.reply is not None: self.reply.abort() if QFile.exists(self.fileName): QFile.remove(self.fileName) def httpFinished(self): if self.httpRequestAborted: if self.outFile is not None: self.outFile.close() self.outFile.remove() del self.outFile self.reply.deleteLater() self.reply = None if not self.silentInstall: self.progressDialog.hide() return if not self.silentInstall: self.progressDialog.hide() self.outFile.flush() self.outFile.close() redirectionTarget = self.reply.attribute( QNetworkRequest.RedirectionTargetAttribute) if self.reply.error(): self.outFile.remove() if not self.silentInstall: self.msgBox.information( QDialog().move(self.fly), self.translate("updateV2ray", "Download"), self.translate("updateV2ray", "Download failed: {}.").format( self.reply.errorString())) self.progressDialog.close() elif redirectionTarget is not None: newUrl = self.downloadURL.resolved(redirectionTarget) self.downloadURL = newUrl self.reply.deleteLater() self.reply = None self.outFile.open(QIODevice.WriteOnly) self.outFile.resize(0) self.startRequest(self.downloadURL) return else: self.reply.deleteLater() self.reply = None self.outFile = None self.downloadFinish.emit() def getV2raycoreInfoFromGithub(self, url=False): if (url): self.downloadURL = url self.reqV2raycore = QNetworkRequest(self.downloadURL) self.qnam.finished.connect(self.handleResponse) self.qnam.get(self.reqV2raycore) def handleResponse(self, reply): """ Read all API from https://api.github.com/repos/v2ray/v2ray-core/releases/latest """ errorCode = reply.error() if (self.v2rayAPI): if errorCode == QNetworkReply.NoError: self.v2rayAPI.setv2raycoreAPI(str(reply.readAll(), "utf-8")) self.createDownloadINFO() else: self.v2rayAPI.setV2raycoreErrorString(reply.errorString()) self.v2rayAPI.setv2raycoreAPI(False) self.v2rayAPI.checkDownloadInfo.emit() def createDownloadINFO(self): api = None try: api = json.loads(self.v2rayAPI.getv2raycoreAPI()) except Exception: api = None if (api): try: # this code for get Latest release Download Files' path for i in api["assets"]: self.v2rayAPI.setdownloadINFO(i["name"], i["browser_download_url"]) self.v2rayAPI.setV2raycoreVersion(api["tag_name"]) except Exception: pass def setautoupdateProxy(self, proxy): self.proxy = QNetworkProxy() protocol = copy.deepcopy(proxy[0]) proxyhostName = copy.deepcopy(proxy[1]) proxyPort = copy.deepcopy(proxy[2]) self.proxy.setType(protocol) self.proxy.setHostName(proxyhostName) self.proxy.setPort(int(proxyPort)) self.proxy.setApplicationProxy(self.proxy) def getcurrentTime(self): currentTime = False if updateV2rayQTime().isMorning(): currentTime = 1 elif updateV2rayQTime().isAfternoon(): currentTime = 2 elif updateV2rayQTime().isEvening(): currentTime = 3 elif updateV2rayQTime().isNight(): currentTime = 4 return currentTime def checkDonwloadinfo(self): self.getV2raycoreInfoFromGithub(self.v2raycoreAPIURL) self.v2rayAPI.checkDownloadInfo.connect( lambda: self.getdownloadPath(self.usingVersion)) def getdownloadPath(self, usingVersion): download = False if (self.v2rayAPI.getv2raycoreAPI()): self.downloadPath = False for file, filePath in self.v2rayAPI.getdownloadINFO().items(): if self.downloadFile == file: self.downloadPath = copy.deepcopy(filePath) break self.latestVersion = copy.deepcopy( self.v2rayAPI.getV2raycoreVersion()) if not usingVersion: download = True elif self.checkNewestfileDownload(usingVersion, self.latestVersion): download = True if (download and self.downloadPath): self.downloadV2rayCoreNow(self.downloadFile, self.downloadPath, self.latestVersion) def downloadV2rayCoreNow(self, downloadFile=False, downloadPath=False, latestVersion=False, bridgetreasureChest=False, bridgeSingal=False): if not downloadPath or not latestVersion or not downloadFile: return False if (bridgetreasureChest): self.bridgetreasureChest = bridgetreasureChest if (bridgeSingal): self.startV2ray = bridgeSingal[0] self.stopV2ray = bridgeSingal[1] self.checkdownloadFileExists(downloadPath) self.downloadV2raycore(QUrl(downloadPath)) self.downloadFinish.connect( lambda: self.installDownloadFile(downloadFile, latestVersion)) def installDownloadFile(self, downloadFile, latestVersion): if self.installOption == "manual": self.msgBox.information( QDialog().move(self.fly), self.translate("updateV2ray", "update"), self.translate( "updateV2ray", "The newest v2ray-core: {} .\nversion: {} was downloaded,\nPlease check." ).format(downloadFile, latestVersion)) elif self.installOption == "auto": if self.unzipdownloadFile( downloadFile, latestVersion) and (not self.silentInstall): self.msgBox.information( QDialog().move(self.fly), self.translate("updateV2ray", "update"), self.translate( "updateV2ray", "The newest v2ray-core: {} .\n version: {} was installed. \nPlease restart V2ray-shell" ).format(downloadFile, latestVersion)) def checkdownloadFileExists(self, downloadPath): if (not downloadPath or not downloadPath): return False filePath = QUrl(downloadPath) fileInfo = QFileInfo(filePath.path()) fileName = fileInfo.fileName() if QFile.exists(fileName): QFile.remove(fileName) return True def unzipdownloadFile(self, downladFile, latestVersion): import zipfile fileInfo = None self.newV2rayPath = None if QFile.exists(downladFile): fileInfo = QFileInfo(QFile(downladFile)) else: return False def checkFilesize(file): v2rayFile = QFile(file.absoluteFilePath()) # check file size need open the file v2rayFile.open(QIODevice.ReadOnly | QIODevice.Text) if v2rayFile.error() == v2rayFile.NoError: if v2rayFile.size() > 600000: v2rayFile.close() return True else: v2rayFile.close() return False if (fileInfo): with zipfile.ZipFile(fileInfo.absoluteFilePath(), "r") as zip_ref: for i in zip_ref.namelist(): absoluteFilePath = fileInfo.absolutePath( ) + QDir.separator() + i if re.search("/v2ray.exe$", absoluteFilePath): # ## windows self.newV2rayPath = None self.newV2rayPath = QFileInfo(QFile(absoluteFilePath)) if self.newV2rayPath and checkFilesize( self.newV2rayPath): break if re.search("/v2ray$", absoluteFilePath): # ## other self.newV2rayPath = None self.newV2rayPath = QFileInfo(QFile(absoluteFilePath)) if self.newV2rayPath and checkFilesize( self.newV2rayPath): break try: zip_ref.extractall(fileInfo.absolutePath()) except PermissionError: return if sys.platform.startswith('win'): pass else: os.chmod(self.newV2rayPath.absoluteFilePath(), 0o755) os.chmod( self.newV2rayPath.absoluteFilePath()[:-5] + "v2ctl", 0o755) if self.newV2rayPath: if (self.stopV2ray): self.stopV2ray.emit() self.bridgetreasureChest.setV2raycoreFilePath( self.newV2rayPath.absoluteFilePath()) self.bridgetreasureChest.setV2raycoreVersion(latestVersion) self.bridgetreasureChest.save.emit() if (self.startV2ray): self.startV2ray.emit() return True else: return False def checkNewestfileDownload(self, usingVersion, latestVersion): if not usingVersion: return True v = re.search("v", str(usingVersion)) if (v): usingVersion = usingVersion[1:].split('.') else: return False del v v = re.search("v", str(latestVersion)) if (v): latestVersion = latestVersion[1:].split('.') else: return False latestMilestone, latestRelease = int(latestVersion[0]), int( latestVersion[1]) usingMilestone, usingRelease = int(usingVersion[0]), int( usingVersion[1]) if (latestMilestone > usingMilestone): return True if ((latestMilestone == usingMilestone) and (latestRelease > usingRelease)): return True return False def partsoftheDay(self): """ Morning : 05:00 to 12:00 (5, 6, 7, 8, 9, 10, 11, 12) Afternoon : 13:00 to 17:00 (13, 14, 15, 16, 17) Evening : 18:00 to 21:00 (18, 19, 20, 21) Night : 22:00 to 04:00 (22, 23, 0, 1, 2, 3, 4) """ return (self.translate("updateV2ray", "Morning"), self.translate("updateV2ray", "Afternoon"), self.translate("updateV2ray", "Evening"), self.translate("updateV2ray", "Night"))
def __init__(self, args): global emacs_width, emacs_height, eaf_config_dir, proxy_string # Parse init arguments. (emacs_width, emacs_height, proxy_host, proxy_port, proxy_type, config_dir, emacs_server_port, var_dict_string) = args emacs_width = int(emacs_width) emacs_height = int(emacs_height) eaf_config_dir = os.path.join(os.path.expanduser(config_dir), '') # Init variables. self.buffer_dict = {} self.view_dict = {} self.emacs_var_dict = {} self.session_file = os.path.join(eaf_config_dir, "session.json") # Update Emacs var dictionary. self.update_emacs_var_dict(var_dict_string) # Init EPC client port. init_epc_client(int(emacs_server_port)) # Build EPC server. self.server = ThreadingEPCServer(('localhost', 0), log_traceback=True) self.server.logger.setLevel(logging.DEBUG) self.server.allow_reuse_address = True if not os.path.exists(eaf_config_dir): os.makedirs(eaf_config_dir) ch = logging.FileHandler(filename=os.path.join(eaf_config_dir, 'epc_log.txt'), mode='w') ch.setLevel(logging.DEBUG) self.server.logger.addHandler(ch) self.server.register_instance( self) # register instance functions let elisp side call # Start EPC server with sub-thread, avoid block Qt main loop. self.server_thread = threading.Thread(target=self.server.serve_forever) self.server_thread.start() # Pass epc port and webengine codec information to Emacs when first start EAF. eval_in_emacs('eaf--first-start', [ self.server.server_address[1], self.webengine_include_private_codec() ]) # Set Network proxy. if proxy_host != "" and proxy_port != "": proxy_string = "{0}://{1}:{2}".format(proxy_type, proxy_host, proxy_port) proxy = QNetworkProxy() if proxy_type == "socks5": proxy.setType(QNetworkProxy.Socks5Proxy) elif proxy_type == "http": proxy.setType(QNetworkProxy.HttpProxy) proxy.setHostName(proxy_host) proxy.setPort(int(proxy_port)) QNetworkProxy.setApplicationProxy(proxy)
class v2rayUpdatePanel(QDialog): def __init__(self, protocol=False, proxyhostName=False, port=False, v2rayapi=False, bridgetreasureChest=False): super().__init__() self.translate = QCoreApplication.translate self.update = { "enable": True, "schedule": { "date": 8, "time": 4 }, "install": "auto", # ## auto install/ manual install "downloadFile": False, "silentInstall": True } self.daysoftheweek = (self.translate("v2rayUpdatePanel", "Select a Day for update"), self.translate("v2rayUpdatePanel", "Every Monday"), self.translate("v2rayUpdatePanel", "Every Tuesday"), self.translate("v2rayUpdatePanel", "Every Wednesday"), self.translate("v2rayUpdatePanel", "Every Thursday"), self.translate("v2rayUpdatePanel", "Every Friday"), self.translate("v2rayUpdatePanel", "Every Saturday"), self.translate("v2rayUpdatePanel", "Every Sunday"), self.translate("v2rayUpdatePanel", "Every Day")) self.downloadFiles = ("v2ray-windows-64.zip", "v2ray-macos.zip", "v2ray-linux-64.zip", "v2ray-windows-32.zip", "v2ray-linux-32.zip", "v2ray-freebsd-32.zip", "v2ray-freebsd-64.zip", "v2ray-linux-arm.zip", "v2ray-linux-arm64.zip", "v2ray-linux-mips.zip", "v2ray-linux-mips64.zip", "v2ray-linux-mips64le.zip", "v2ray-linux-mipsle.zip", "v2ray-openbsd-32.zip", "v2ray-openbsd-64.zip", "v2ray-linux-s390x.zip") self.protocol = protocol self.proxyhostName = proxyhostName self.port = port if (v2rayapi): self.v2rayAPI = v2rayapi else: self.v2rayAPI = v2rayAPI() self.bridgetreasureChest = bridgetreasureChest if not self.bridgetreasureChest: from bridgehouse.extension import bridgetreasureChest self.bridgetreasureChest = bridgetreasureChest.bridgetreasureChest( ) self.v2raycoreAPIURL = QUrl( r"""https://api.github.com/repos/v2ray/v2ray-core/releases/latest""" ) self.spinBoxPort = QSpinBox() self.lineEditProxy = QLineEdit() self.radioButtonSocks5 = QRadioButton("Socks") self.radioButtonHttp = QRadioButton("Http") self.groupBoxViaProxy = QGroupBox( self.translate("v2rayUpdatePanel", "Via Proxy")) self.groupBoxViaProxy.setCheckable(True) self.proxy = QNetworkProxy() if (self.protocol and self.proxyhostName and self.port and v2rayapi): self.settingProxyhost(protocol, proxyhostName, port) self.groupBoxViaProxy.setChecked(True) else: self.groupBoxViaProxy.setChecked(False) def createPanel(self): labelProxy = QLabel(self.translate("v2rayUpdatePanel", "Proxy: ")) self.lineEditProxy.setFixedWidth(256) self.spinBoxPort.setRange(0, 65535) self.spinBoxPort.setValue(1080) self.buttonCheck = QPushButton( self.translate("v2rayUpdatePanel", "Check")) self.labelCheckResult = QLabel( self.translate("v2rayUpdatePanel", " Check the latest V2Ray-core version")) labelcurrentV2raycoreVersion = QLabel( self.translate("v2rayUpdatePanel", "Can't get V2Ray-core's version")) version = self.bridgetreasureChest.getV2raycoreVersion() if (version): labelFont = QFont() labelFont.setPointSize(12) labelFont.setBold(True) labelcurrentV2raycoreVersion.setFont(labelFont) labelcurrentV2raycoreVersion.setText( self.translate( "v2rayUpdatePanel", "The current version of V2Ray is: {}").format(version)) labelDownloadPath = QLabel( self.translate("v2rayUpdatePanel", "V2Ray-core Download Path: ")) self.lineEditDownloadPath = QLineEdit() self.lineEditDownloadPath.setFixedWidth(512) self.lineEditDownloadPath.setReadOnly( False if v2rayshellDebug else True) self.comboBoxv2raycoreVersion = QComboBox() self.buttonDownload = QPushButton( self.translate("v2rayUpdatePanel", "Download")) hboxProxyAddress = QHBoxLayout() hboxProxyAddress.addWidget(labelProxy) hboxProxyAddress.addWidget(self.lineEditProxy) hboxProxyAddress.addWidget(self.spinBoxPort) hboxProxyAddress.addStretch() hboxRadioButton = QHBoxLayout() hboxRadioButton.addWidget(self.radioButtonSocks5) hboxRadioButton.addWidget(self.radioButtonHttp) hboxRadioButton.addStretch() vboxViaProxy = QVBoxLayout() vboxViaProxy.addLayout(hboxProxyAddress) vboxViaProxy.addLayout(hboxRadioButton) self.groupBoxViaProxy.setLayout(vboxViaProxy) hboxCheckStatus = QHBoxLayout() hboxCheckStatus.addWidget(self.buttonCheck) hboxCheckStatus.addWidget(self.labelCheckResult) hboxCheckStatus.addWidget(self.comboBoxv2raycoreVersion) hboxCheckStatus.addStretch() hboxDownloadPath = QHBoxLayout() hboxDownloadPath.addWidget(labelDownloadPath) hboxDownloadPath.addWidget(self.lineEditDownloadPath) hboxDownloadPath.addWidget(self.buttonDownload) hboxDownloadPath.addStretch() self.groupBoxupdateSchedule = QGroupBox( self.translate("v2rayUpdatePanel", "Automatic Updates")) self.groupBoxupdateSchedule.setCheckable(True) self.groupBoxupdateSchedule.setChecked(False) self.comboBoxScheduledate = QComboBox() self.comboBoxScheduledate.addItems(self.daysoftheweek) labelAt = QLabel(self.translate("v2rayUpdatePanel", "at")) self.comboBoxScheduletime = QComboBox() self.comboBoxScheduletime.addItems(self.partsoftheDay()) labelDownloadFile = QLabel( self.translate("v2rayUpdatePanel", " Download: ")) self.comboBoxDownloadFile = QComboBox() self.comboBoxDownloadFile.addItems(self.downloadFiles) hboxSchedule = QHBoxLayout() hboxSchedule.addWidget(self.comboBoxScheduledate) hboxSchedule.addWidget(labelAt) hboxSchedule.addWidget(self.comboBoxScheduletime) hboxSchedule.addWidget(labelDownloadFile) hboxSchedule.addWidget(self.comboBoxDownloadFile) hboxSchedule.addStretch() labelThen = QLabel(self.translate("v2rayUpdatePanel", "Then ")) self.radioButtonAuto = QRadioButton( self.translate("v2rayUpdatePanel", "Auto")) self.radioButtonManual = QRadioButton( self.translate("v2rayUpdatePanel", "Manual")) self.radioButtonManual.setChecked(True) self.checkBoxsilentInstall = QCheckBox( self.translate("v2rayUpdatePanel", "Silently")) labelInstallV2raycore = QLabel( self.translate("v2rayUpdatePanel", "Install V2Ray-core")) hboxRadioButtonAutoManual = QHBoxLayout() hboxRadioButtonAutoManual.addWidget(labelThen) hboxRadioButtonAutoManual.addWidget(self.radioButtonAuto) hboxRadioButtonAutoManual.addWidget(self.radioButtonManual) hboxRadioButtonAutoManual.addSpacerItem(QSpacerItem(25, 5)) hboxRadioButtonAutoManual.addWidget(self.checkBoxsilentInstall) hboxRadioButtonAutoManual.addWidget(labelInstallV2raycore) hboxRadioButtonAutoManual.addStretch() self.buttonApplyandClose = QPushButton( self.translate("v2rayUpdatePanel", "Apply and Close")) self.buttonCancel = QPushButton( self.translate("v2rayUpdatePanel", "Cancel")) hboxbuttonApplyCloseCancel = QHBoxLayout() hboxbuttonApplyCloseCancel.addStretch() hboxbuttonApplyCloseCancel.addWidget(self.buttonApplyandClose) hboxbuttonApplyCloseCancel.addWidget(self.buttonCancel) vboxSchedule = QVBoxLayout() vboxSchedule.addLayout(hboxSchedule) vboxSchedule.addLayout(hboxRadioButtonAutoManual) self.groupBoxupdateSchedule.setLayout(vboxSchedule) vboxUpdatPanel = QVBoxLayout() vboxUpdatPanel.addWidget(self.groupBoxViaProxy) vboxUpdatPanel.addWidget(labelcurrentV2raycoreVersion) vboxUpdatPanel.addLayout(hboxCheckStatus) vboxUpdatPanel.addLayout(hboxDownloadPath) vboxUpdatPanel.addWidget(self.groupBoxupdateSchedule) vboxUpdatPanel.addLayout(hboxbuttonApplyCloseCancel) vboxUpdatPanel.addStretch() if v2rayshellDebug: hbox = QHBoxLayout() self.updatev2ray = updateV2ray() self.autoupdate = autoCheckUpdate() self.__testBtn = QPushButton("__Test") self.__testGetGithubRelease = QPushButton("__TestGetGithubRelease") self.__testDownload = QPushButton("__TestDownloadformGithub") hbox.addWidget(self.__testBtn) hbox.addWidget(self.__testGetGithubRelease) hbox.addWidget(self.__testDownload) vboxUpdatPanel.addLayout(hbox) # self.__testBtn.clicked.connect(lambda: self.updatev2ray.unzipdownloadFile("v2ray-linux-mips64le.zip")) self.__testGetGithubRelease.clicked.connect( self.autoupdate.checkGithubV2RaycoreLastestReleaseVersion) self.__testDownload.clicked.connect( self.autoupdate.tryupdateV2Raycore) self.settingupdateSchedule() self.setLayout(vboxUpdatPanel) self.createUpadtePanelSignals() def createUpadtePanelSignals(self): self.comboBoxv2raycoreVersion.currentTextChanged.connect( self.ondownloadVersionSelect) self.buttonCheck.clicked.connect(self.onbuttonCheckV2raycoreversion) self.buttonDownload.clicked.connect(self.ondownloadV2raycore) self.groupBoxViaProxy.clicked.connect(self.ongroupBoxViaProxy) self.buttonCancel.clicked.connect(self.close) self.buttonApplyandClose.clicked.connect( self.onupdatebuttonApplyandClose) def onupdatebuttonApplyandClose(self): self.bridgetreasureChest.clearUpdate() update = {} update["enable"] = True if self.groupBoxupdateSchedule.isChecked( ) else False update["schedule"] = {} update["schedule"]["date"] = int( self.comboBoxScheduledate.currentIndex()) update["schedule"]["time"] = int( self.comboBoxScheduletime.currentIndex()) update["install"] = "auto" if self.radioButtonAuto.isChecked( ) else "manual" update["downloadFile"] = self.comboBoxDownloadFile.currentText() update["silentInstall"] = True if self.checkBoxsilentInstall.isChecked( ) else False self.bridgetreasureChest.setUpdateSchedule(update) self.bridgetreasureChest.save.emit() self.close() def settingupdateSchedule(self): if self.bridgetreasureChest.updateisEnable(): self.groupBoxupdateSchedule.setChecked(True) else: self.groupBoxupdateSchedule.setChecked(False) downloadFile = self.bridgetreasureChest.getupdatedownloadFile() if downloadFile in self.downloadFiles: self.comboBoxDownloadFile.setCurrentText(downloadFile) try: self.comboBoxScheduledate.setCurrentIndex( self.bridgetreasureChest.getupdateScheduledate()) except Exception: # a new panel will get a false value from config.v2rayshell pass try: self.comboBoxScheduletime.setCurrentIndex( self.bridgetreasureChest.getupdateScheduletime()) except Exception: pass installOption = self.bridgetreasureChest.getupdateinstallOption() if installOption == "auto": self.radioButtonAuto.setChecked(True) self.radioButtonManual.setChecked(False) else: self.radioButtonManual.setChecked(True) self.radioButtonAuto.setChecked(False) self.checkBoxsilentInstall.setChecked( True if self.bridgetreasureChest.getsilentInstall() else False) def partsoftheDay(self): """ Morning : 05:00 to 12:00 (5, 6, 7, 8, 9, 10, 11, 12) Afternoon : 13:00 to 17:00 (13, 14, 15, 16, 17) Evening : 18:00 to 21:00 (18, 19, 20, 21) Night : 22:00 to 04:00 (22, 23, 0, 1, 2, 3, 4) """ return (self.translate("v2rayUpdatePanel", "Select a time for update"), self.translate("v2rayUpdatePanel", "Morning"), self.translate("v2rayUpdatePanel", "Afternoon"), self.translate("v2rayUpdatePanel", "Evening"), self.translate("v2rayUpdatePanel", "Night")) def settingProxyhost(self, protocol, proxyhostName, port): """ update v2ray need via proxy """ self.proxy.setType(protocol) self.proxy.setHostName(proxyhostName) self.proxy.setPort(int(port)) self.proxy.setApplicationProxy(self.proxy) if (protocol == QNetworkProxy.Socks5Proxy): self.radioButtonSocks5.setChecked(True) self.radioButtonHttp.setChecked(False) if (protocol == QNetworkProxy.HttpProxy): self.radioButtonHttp.setChecked(True) self.radioButtonSocks5.setChecked(False) self.lineEditProxy.setText(proxyhostName) self.spinBoxPort.setValue(int(port)) def checkisViaProxy(self): if self.groupBoxViaProxy.isChecked(): if self.lineEditProxy.text() == "" or self.spinBoxPort.value( ) == 0: self.lineEditDownloadPath.clear() self.comboBoxv2raycoreVersion.clear() return else: if (self.radioButtonSocks5.isChecked()): protocol = QNetworkProxy.Socks5Proxy elif (self.radioButtonHttp.isChecked()): protocol = QNetworkProxy.HttpProxy self.proxy.setType(protocol) self.proxy.setHostName(self.lineEditProxy.text()) self.proxy.setPort(self.spinBoxPort.value()) self.proxy.setApplicationProxy(self.proxy) else: self.proxy.setType(QNetworkProxy.NoProxy) self.proxy.setApplicationProxy(self.proxy) def ongroupBoxViaProxy(self): self.checkisViaProxy() def onbuttonCheckV2raycoreversion(self): self.checkisViaProxy() labelFont = QFont() labelFont.setPointSize(12) labelFont.setBold(True) self.labelCheckResult.setFont(labelFont) self.labelCheckResult.setText( self.translate("v2rayUpdatePanel", "Checking...")) self.updateV2ray = updateV2ray(self.v2rayAPI, self.v2raycoreAPIURL, checkDownloadInfo=True, downloadV2raycore=False) self.v2rayAPI.checkDownloadInfo.connect( self.settingUpdateDownloadFiles) def ondownloadVersionSelect(self): currentv2raycoreVersion = self.comboBoxv2raycoreVersion.currentText() if currentv2raycoreVersion != "": downloadINFO = self.v2rayAPI.getdownloadINFO() downloadPath = downloadINFO[currentv2raycoreVersion] self.lineEditDownloadPath.setText(downloadPath) else: self.lineEditDownloadPath.clear() def settingUpdateDownloadFiles(self): if (not self.v2rayAPI.getv2raycoreAPI()): self.labelCheckResult.setText( self.v2rayAPI.getV2raycoreErrorString()) self.lineEditDownloadPath.clear() self.comboBoxv2raycoreVersion.clear() return downloadINFO = copy.deepcopy(self.v2rayAPI.getdownloadINFO()) try: downloadINFO["metadata.txt"] metadata = True except Exception: metadata = False if (metadata): del downloadINFO[ "metadata.txt"] # ## metadata.txt should not in the download list if (downloadINFO): k = 1 self.comboBoxv2raycoreVersion.clear() self.comboBoxv2raycoreVersion.insertItem(0, "") for i in downloadINFO.keys(): self.comboBoxv2raycoreVersion.insertItem(++k, str(i)) self.comboBoxv2raycoreVersion.setSizeAdjustPolicy( QComboBox.AdjustToContents) self.labelCheckResult.setText( self.translate("v2rayUpdatePanel", "The latest version is: {}").format( self.v2rayAPI.getV2raycoreVersion())) def ondownloadV2raycore(self): self.checkisViaProxy() filePath = self.lineEditDownloadPath.text() if (filePath != ""): self.updateV2ray = updateV2ray(self.v2rayAPI, QUrl(filePath), checkDownloadInfo=False, downloadV2raycore=True)
socket.disconnectFromHost() if proxy_socket.error() != QTcpSocket.RemoteHostClosedError: url = proxy_socket.property('url').toUrl() error_string = proxy_socket.errorString() if self.debug: self.log.write('Error for %s %s\n\n' % (url, error_string)) proxy_socket.deleteLater() if __name__ == '__main__': app = QCoreApplication(sys.argv) server = Server() manager = QNetworkAccessManager() manager.finished.connect(server.stopServing) manager.finished.connect(app.quit) proxy = QNetworkProxy() proxy.setType(QNetworkProxy.HttpProxy) proxy.setHostName('127.0.0.1') proxy.setPort(server.port()) proxy.setUser(server.username) proxy.setPassword(server.password) manager.setProxy(proxy) reply = manager.get(QNetworkRequest(QUrl('http://aws.amazon.com/'))) sys.exit(app.exec_())