コード例 #1
0
def main():
    import sys

    QCoreApplication.setOrganizationName("QtExamples")
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    # QtWebEngine::initialize()

    if QT_NO_WIDGETS:
        app = QApplication(sys.argv)
    else:
        app = QGuiApplication(sys.argv)

    engine = QQmlApplicationEngine()
    server = Server(engine)

    engine.load(QUrl("qrc:/main.qml"))
    QTimer.singleShot(0, server.run)

    proxy = QNetworkProxy()
    proxy.setType(QNetworkProxy.HttpProxy)
    proxy.setHostName("localhost")
    proxy.setPort(5555)
    QNetworkProxy.setApplicationProxy(proxy)

    sys.exit(app.exec_())
コード例 #2
0
def set_proxy_in_qt_app(hostname, port):
    logging.info(f"Set proxy to {hostname}:{port} in Qt application")
    network_proxy = QNetworkProxy()
    network_proxy.setType(QNetworkProxy.HttpProxy)
    network_proxy.setHostName(hostname)
    network_proxy.setPort(port)
    QNetworkProxy.setApplicationProxy(network_proxy)
コード例 #3
0
    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.buffer_dict = {}
        self.view_dict = {}
        self.emacs_var_dict = {}

        self.update_emacs_var_dict(var_dict_string)

        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)
コード例 #4
0
    def __init__(self, args):
        global emacs_width, emacs_height

        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) = args
        emacs_width = int(emacs_width)
        emacs_height = int(emacs_height)

        self.buffer_dict = {}
        self.view_dict = {}

        self.start_finish()

        self.session_file_path = os.path.expanduser(
            "~/.emacs.d/eaf/session.json")

        # Set HTTP proxy.
        if proxy_host != "" and proxy_port != "":
            proxy = QNetworkProxy()
            proxy.setType(QNetworkProxy.HttpProxy)
            proxy.setHostName(proxy_host)
            proxy.setPort(int(proxy_port))
            QNetworkProxy.setApplicationProxy(proxy)
コード例 #5
0
        def _setupProxy( self ):
            # TODO: move proxy settings to ToolBOS.conf

            proxy = QNetworkProxy( )
            proxy.setType( QNetworkProxy.HttpProxy )
            proxy.setHostName( 'hri-proxy.honda-ri.de' )
            proxy.setPort( 3128 )

            QNetworkProxy.setApplicationProxy( proxy )
コード例 #6
0
    def __init__(self, args):
        global emacs_width, emacs_height, eaf_config_dir, proxy_string

        (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), '')

        self.buffer_dict = {}
        self.view_dict = {}
        self.emacs_var_dict = {}

        self.update_emacs_var_dict(var_dict_string)

        self.server = ThreadingEPCServer(('localhost', 0), log_traceback=True)

        self.server.logger.setLevel(logging.DEBUG)
        ch = logging.FileHandler(
            filename=os.path.expanduser('~/.emacs.d/eaf/epc_log.txt'),
            mode='w')
        ch.setLevel(logging.DEBUG)
        self.server.logger.addHandler(ch)

        self.server_thread = threading.Thread(target=self.server.serve_forever)
        self.server_thread.allow_reuse_address = True

        self.server.register_instance(self)

        self.server_thread.start()

        # NOTE:
        # Emacs epc client need fetch port from Python process print.
        # And this print must be first print code, otherwise Emacs client will failed to start.
        self.server.print_port()

        self.emacs_server_connect = build_emacs_server_connect(
            int(emacs_server_port))

        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)
コード例 #7
0
def set_proxy(string_proxy):
    proxy = QNetworkProxy()
    urlinfo = urlparse.urlparse(string_proxy)
    if urlinfo.scheme == 'socks5':
        proxy.setType(QNetworkProxy.Socks5Proxy)
    elif urlinfo.scheme == 'http':
        proxy.setType(QNetworkProxy.HttpProxy)
    else:
        proxy.setType(QNetworkProxy.NoProxy)
    proxy.setHostName(urlinfo.hostname)
    proxy.setPort(urlinfo.port)
    proxy.setUser(urlinfo.username)
    proxy.setPassword(urlinfo.password)
    QNetworkProxy.setApplicationProxy(proxy)
コード例 #8
0
ファイル: kcviewer.py プロジェクト: papamitra/kcviewer_py3
    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 = {}
コード例 #9
0
    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)
コード例 #10
0
 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)
コード例 #11
0
    def run(self):
        current_thread().name = "WebKit"
        # signal.signal(signal.SIGINT, signal.SIG_DFL)

        app = QApplication([])
        signal.signal(signal.SIGINT, self.onExit)
        signal.signal(signal.SIGINT, signal.SIG_DFL)

        # Helps to handle Ctrl+C action.
        self.timer = QTimer()
        self.timer.start(1000)
        self.timer.timeout.connect(lambda: None)

        #  Setup proxy for browser elements.
        if self.proxy is not None:
            url, port = self.proxy.split(":")

            proxy = QNetworkProxy()
            proxy.setType(QNetworkProxy.HttpProxy)
            proxy.setHostName(url)
            proxy.setPort(int(port))
            QNetworkProxy.setApplicationProxy(proxy)

        for i in range(self.poolsize):
            renderer = WebPage()
            renderer._pipequeue = self._pipequeue
            self._pool.append(renderer)

        # Hmm... QThread blocks GUI, this, python one not blocks.
        self.sidethread = SideThread(self)
        self.sidethread.daemon = True
        self.sidethread.start()

        # Load GUI if it's needed.
        if self.gui:
            self.mv = MainWindow()
            self.mv.show()

            for web in self._pool:
                view = QWebEngineView()
                view.setPage(web)
                self.mv.addTab(view, web.title())

        app.exec_()
コード例 #12
0
ファイル: browser.py プロジェクト: copyit/jd_coin
    def config(self):
        self.page().profile().setHttpUserAgent(config.ua)

        proxies = urllib.request.getproxies()
        http_proxy = proxies.get('http') or proxies.get('https')

        if http_proxy:
            parsed = urllib.parse.urlparse(http_proxy)
            proxy = QNetworkProxy()
            proxy.setType(QNetworkProxy.HttpProxy)
            proxy.setHostName(parsed.hostname)
            proxy.setPort(parsed.port)
            QNetworkProxy.setApplicationProxy(proxy)

        # NoPersistentCookies, Both session and persistent cookies are stored in memory.
        # http://doc.qt.io/qt-5/qwebengineprofile.html#PersistentCookiesPolicy-enum
        # cookies 会同步到 python 中,无需由 WebEngine 保存。若保存了,cookieAdded 会触发两次,一次从文件(缓存)加载,
        # 一次页面中 Set-Cookie 指令加载,反而复杂了。
        self.page().profile().setPersistentCookiesPolicy(0)
        self.setZoomFactor(1.2)  # 放大一下, 验证码看的清楚...
コード例 #13
0
        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 )
コード例 #14
0
    def set_proxy(self, buffer_ids, mode, address, whitelist):
        """
        Set the proxy for the current application.

        TODO: set it for the given buffers.
        TODO: handle whitelist.

        https://doc.qt.io/qt-5.9/qtwebengine-overview.html#proxy-support
        """
        # XXX: currently the address in proxy-mode is 'socks5://127.0.0.1:9050'.
        # After changes there (and Gtk side) we won't do this url mangling.
        parsed_url = urlparse(address)
        scheme = parsed_url.scheme.lower()
        if 'socks5' in scheme:
            proxy_type = QNetworkProxy.Socks5Proxy
        elif 'httpproxy' in scheme:
            proxy_type = QNetworkProxy.HttpProxy
        elif 'httpcaching' in scheme:
            proxy_type = QNetworkProxy.HttpCachingProxy
        elif 'default' in scheme:
            proxy_type = QNetworkProxy.DefaultProxy
            logging.warn("Using the default proxy is currently unimplemented.")

        if ':' in parsed_url.netloc:
            address, port = parsed_url.netloc.split(':')
            try:
                port = int(port)
            except Exception:
                logging.warn(
                    "Invalid port: '{}'. Could not parse it as an int.".
                    formatport)
                return False

        proxy = QNetworkProxy()
        proxy.setType(proxy_type)
        proxy.setHostName(address)
        proxy.setPort(port)

        QNetworkProxy.setApplicationProxy(proxy)
        logging.info("proxy set to address '{}'.".format(address))
コード例 #15
0
    def __init__(self, args):
        global emacs_width, emacs_height, eaf_config_dir, proxy_string, wm_focus_fix_list_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, wm_list_string) = args
        emacs_width = int(emacs_width)
        emacs_height = int(emacs_height)
        eaf_config_dir = os.path.join(os.path.expanduser(config_dir), '')
        wm_focus_fix_list_string = wm_list_string

        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)
コード例 #16
0
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)
コード例 #17
0
class MyWebView(QWebEngineView):
    def __init__(self, parent=None, user_id=None):
        super().__init__()

        self.parent = parent
        self.chekLoadFinish = False

        # 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, proxy, user_agent FROM accaunt where user_id=?',
                (user_id, ))
            row = cur.fetchone()
            self.login, self.password, proxy, user_agent = row

        con.close()

        #Path Cookies
        os.chdir('/root/PycharmProjects/HearSheep')
        pathCookies = '/root/PycharmProjects/HearSheep/cookies/' + str(user_id)

        if os.path.exists(pathCookies):
            pass
        else:
            os.chdir('/root/PycharmProjects/HearSheep/cookies')
            os.mkdir(str(user_id))
            pathCookies = '/root/PycharmProjects/HearSheep/cookies/' + str(
                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.loadStarted.connect(self.loadStart)
        self.loadFinished.connect(self.loadFinish)
        self.load(QtCore.QUrl('https://vk.com'))

    def handleProxyAuthReq(self, url, auth, proxyhost):
        auth.setUser(self.proxy.user())
        auth.setPassword(self.proxy.password())

    def loadStart(self):
        self.chekLoadFinish = False

    def loadFinish(self):
        self.chekLoadFinish = True

        if self.page().url().url() == 'https://vk.com/':
            self._auth()

    def _auth(self):
        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()')
コード例 #18
0
ファイル: donkey.py プロジェクト: wangyihit/donkey
def set_proxy(host, port):
    proxy = QNetworkProxy()
    proxy.setType(QNetworkProxy.HttpProxy)
    proxy.setHostName(host)
    proxy.setPort(port)
    QNetworkProxy.setApplicationProxy(proxy)
コード例 #19
0
                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_())
コード例 #20
0
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()")
コード例 #21
0
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()
コード例 #22
0
    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)
コード例 #23
0
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"))
コード例 #24
0
ファイル: proxy.py プロジェクト: zhsj/qwechat
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")