Example #1
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)
Example #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)
Example #3
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_())
Example #4
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)
Example #5
0
 def newsite(self):
     while not self.request():
         QtWidgets.qApp.processEvents()
         print('Proxy bad')
     QtWidgets.qApp.processEvents()
     QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy, self.proxi_ip, self.proxi_port))
     self.load(QUrl('https://vk.com/id447929742?z=video447929742_456239017%2F2819f4855e1e422801%2Fpl_wall_447929742'))
     return True
Example #6
0
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 ''))
Example #7
0
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, 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)
Example #9
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 )
    def disable_proxy(self):
        global proxy_string

        proxy_string = ""

        proxy = QNetworkProxy()
        proxy.setType(QNetworkProxy.NoProxy)

        self.is_proxy = False
        QNetworkProxy.setApplicationProxy(proxy)
Example #11
0
 def configure_proxy(self):
     proxy = urlparse(
         os.environ.get('http_proxy') or os.environ.get('HTTP_PROXY'))
     if proxy.hostname is not None and proxy.port is not None:
         q_network_proxy = QNetworkProxy(QNetworkProxy.HttpProxy,
                                         proxy.hostname, proxy.port)
         if proxy.username is not None:
             q_network_proxy.setUser(proxy.username)
         if proxy.password is not None:
             q_network_proxy.setPassword(proxy.password)
         QNetworkProxy.setApplicationProxy(q_network_proxy)
Example #12
0
    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'))
Example #13
0
    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)
Example #14
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)
Example #15
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)
Example #16
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)
    def run(self):
        # To work around funky GC conflicts with C++ code by ensuring QApplication terminates last
        global app

        signal.signal(signal.SIGTERM, on_sigterm)
        signal.signal(signal.SIGINT, signal.SIG_DFL)

        cfg = config.load()

        argv = sys.argv.copy()
        if self.display_mode == config.DisplayMode.HIDDEN:
            argv += ["-platform", "minimal"]
        app = QApplication(argv)

        if self.proxy:
            parsed = urlparse(self.proxy)
            if parsed.scheme.startswith("socks5"):
                proxy_type = QNetworkProxy.Socks5Proxy
            elif parsed.scheme.startswith("http"):
                proxy_type = QNetworkProxy.HttpProxy
            else:
                raise ValueError("Unsupported proxy type", parsed.scheme)
            proxy = QNetworkProxy(proxy_type, parsed.hostname, parsed.port)

            QNetworkProxy.setApplicationProxy(proxy)

        # In order to make Python able to handle signals
        force_python_execution = QTimer()
        force_python_execution.start(200)

        def ignore():
            pass

        force_python_execution.timeout.connect(ignore)
        web = WebBrowser(cfg.auto_fill_rules, self._states.put)

        startup_info = self._commands.get()
        logger.info("Browser started", startup_info=startup_info)

        logger.info("Loading page", url=startup_info.url)

        web.authenticate_at(QUrl(startup_info.url), startup_info.credentials)

        web.show()
        rc = app.exec_()

        logger.info("Exiting browser")
        return rc
Example #18
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)
Example #19
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_()
Example #20
0
    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)  # 放大一下, 验证码看的清楚...
Example #21
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))
Example #22
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)
Example #23
0
def reset_proxy_settings():
    QNetworkProxy.setApplicationProxy(QNetworkProxy())
Example #24
0
    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)])
Example #25
0
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
Example #26
0
def set_no_proxy_in_qt_app():
    logging.info(f"Set no proxy in Qt application")
    QNetworkProxy.setApplicationProxy(QNetworkProxy())
Example #27
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)
Example #28
0
 def apply(self):
     QNetworkProxy.setApplicationProxy(self)
Example #29
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"))
Example #30
0
def reset_proxy_settings():
    QNetworkProxy.setApplicationProxy(QNetworkProxy())
Example #31
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)
Example #32
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()
Example #33
0
    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)