Пример #1
0
 def interceptRequest(self, info):
     url = info.requestUrl()
     if url.hasQuery() and url.path().endswith('api'):
         query = QUrlQuery(url.query())
         p = query.queryItemValue('p')
         model = query.queryItemValue('model')
         r18 = query.queryItemValue('r18')
         self.get_live2d_data(p, model, r18)
         # 重定向
         info.redirect(
             QUrl('http://127.0.0.1:{0}/model/model.json'.format(
                 self.port)))
Пример #2
0
    def key(self, job, url):
        key = url.path().lstrip("/")
        query = QUrlQuery(url)
        command = query.queryItemValue("command")
        keymap = query.queryItemValue("keymap")

        if ":" in command:
            modname, fname = command.split(":", 1)
            fn = getattr(importlib.import_module(modname), fname)
            command_name = fn.__name__
            named_command = False
        else:
            command_name = command
            cmd = COMMANDS[command]
            fn = cmd.binding
            named_command = True
            modname = fn.__module__
        command_doc = fn.__doc__
        src_url = get_src_url(fn)

        def _get_all_keys(km):
            acc = []

            cmd = command_name if named_command else fn

            def add(prefix, cmd_):
                if cmd == cmd_:
                    acc.append(" ".join(str(k) for k in prefix))

            km.traverse_commands(add)
            return acc

        try:
            all_keys = _get_all_keys(KEYMAPS[keymap])
        except KeyError:
            all_keys = (key, )

        self.reply_template(
            job, "key", {
                "command_name": command_name,
                "keymap": keymap,
                "key": key,
                "command_doc": command_doc,
                "named_command": named_command,
                "command_src_url": src_url,
                "modname": modname,
                "all_keys": all_keys,
            })
Пример #3
0
def qute_pdfjs(url: QUrl) -> _HandlerRet:
    """Handler for qute://pdfjs.

    Return the pdf.js viewer or redirect to original URL if the file does not
    exist.
    """
    if url.path() == '/file':
        filename = QUrlQuery(url).queryItemValue('filename')
        if not filename:
            raise UrlInvalidError("Missing filename")
        if '/' in filename or os.sep in filename:
            raise RequestDeniedError("Path separator in filename.")

        path = _pdf_path(filename)
        with open(path, 'rb') as f:
            data = f.read()

        mimetype = utils.guess_mimetype(filename, fallback=True)
        return mimetype, data

    if url.path() == '/web/viewer.html':
        query = QUrlQuery(url)
        filename = query.queryItemValue("filename")
        if not filename:
            raise UrlInvalidError("Missing filename")

        path = _pdf_path(filename)
        if not os.path.isfile(path):
            source = query.queryItemValue('source')
            if not source:  # This may happen with old URLs stored in history
                raise UrlInvalidError("Missing source")
            raise Redirect(QUrl(source))

        data = pdfjs.generate_pdfjs_page(filename, url)
        return 'text/html', data

    try:
        data = pdfjs.get_pdfjs_res(url.path())
    except pdfjs.PDFJSNotFound as e:
        # Logging as the error might get lost otherwise since we're not showing
        # the error page if a single asset is missing. This way we don't lose
        # information, as the failed pdfjs requests are still in the log.
        log.misc.warning(
            "pdfjs resource requested but not found: {}".format(e.path))
        raise NotFoundError("Can't find pdfjs resource '{}'".format(e.path))
    else:
        mimetype = utils.guess_mimetype(url.fileName(), fallback=True)
        return mimetype, data
Пример #4
0
    def requestPixmap(self, id, size):
        url = QUrl(id)
        query = QUrlQuery(url.query())
        map_dir = QDir(url.toLocalFile()).path()
        dot_size = round(float(query.queryItemValue('dot_size')))
        should_flip = query.queryItemValue('flip') in ['True', 'true']
        opacity = round(float(query.queryItemValue('opacity')))

        try:
            img, size = self._generate_heatmap(map_dir, dot_size, opacity)
            if should_flip:
                img = flip(img)
            p = QPixmap.fromImage(img.toqimage())
            return p, size
        except Exception:
            return QPixmap(), QSize(-1, -1)
Пример #5
0
    def pydoc(self, job, url):
        from pygments.formatters import HtmlFormatter
        from pygments.lexers.python import Python3Lexer
        from pygments import highlight

        modname = url.path().lstrip("/")
        query = QUrlQuery(url)
        extras = {}
        if query.hasQueryItem("hl_lines"):
            start, end = query.queryItemValue("hl_lines").split("-")
            extras["hl_lines"] = list(range(int(start), int(end) + 1))

        mod = importlib.import_module(modname)
        filepath = inspect.getsourcefile(mod)

        formatter = HtmlFormatter(title="Module %s" % modname,
                                  full=True,
                                  lineanchors="line",
                                  **extras)

        with open(filepath) as f:
            code = highlight(f.read(), Python3Lexer(), formatter)

        buffer = QBuffer(self)
        buffer.setData(code.encode("utf-8"))
        job.reply(b"text/html", buffer)
Пример #6
0
 def acceptNavigationRequest(self, url, _type, isMainFrame):
     query = QUrlQuery(url)
     if query.hasQueryItem("requrl"):
         orig_url = query.queryItemValue("requrl", QUrl.FullyDecoded)
         url = QUrl(orig_url)
         QDesktopServices.openUrl(url)
         return False
     return super().acceptNavigationRequest(url, _type, isMainFrame)
Пример #7
0
def _qute_settings_set(url):
    """Handler for qute://settings/set."""
    query = QUrlQuery(url)
    option = query.queryItemValue('option', QUrl.FullyDecoded)
    value = query.queryItemValue('value', QUrl.FullyDecoded)

    # https://github.com/qutebrowser/qutebrowser/issues/727
    if option == 'content.javascript.enabled' and value == 'false':
        msg = ("Refusing to disable javascript via qute://settings "
               "as it needs javascript support.")
        message.error(msg)
        return 'text/html', b'error: ' + msg.encode('utf-8')

    try:
        config.instance.set_str(option, value, save_yaml=True)
        return 'text/html', b'ok'
    except configexc.Error as e:
        message.error(str(e))
        return 'text/html', b'error: ' + str(e).encode('utf-8')
Пример #8
0
def _qute_settings_set(url):
    """Handler for qute://settings/set."""
    query = QUrlQuery(url)
    option = query.queryItemValue('option', QUrl.FullyDecoded)
    value = query.queryItemValue('value', QUrl.FullyDecoded)

    # https://github.com/qutebrowser/qutebrowser/issues/727
    if option == 'content.javascript.enabled' and value == 'false':
        msg = ("Refusing to disable javascript via qute://settings "
               "as it needs javascript support.")
        message.error(msg)
        return 'text/html', b'error: ' + msg.encode('utf-8')

    try:
        config.instance.set_str(option, value, save_yaml=True)
        return 'text/html', b'ok'
    except configexc.Error as e:
        message.error(str(e))
        return 'text/html', b'error: ' + str(e).encode('utf-8')
Пример #9
0
    def __adBlockPage(self):
        """
        Private method to build the AdBlock page.
        
        @return built AdBlock page
        @rtype str
        """
        query = QUrlQuery(self.__job.requestUrl())
        rule = query.queryItemValue("rule")
        subscription = query.queryItemValue("subscription")
        title = self.tr("Content blocked by AdBlock Plus")
        message = self.tr("Blocked by rule: <i>{0} ({1})</i>").format(
            rule, subscription)

        page = readAllFileContents(":/html/adblockPage.html")
        page = page.replace("@FAVICON@", "qrc:icons/adBlockPlus16.png")
        page = page.replace("@IMAGE@", "qrc:icons/adBlockPlus64.png")
        page = page.replace("@TITLE@", title)
        page = page.replace("@MESSAGE@", message)

        return page
Пример #10
0
def qute_log(url: QUrl) -> _HandlerRet:
    """Handler for qute://log.

    There are three query parameters:

    - level: The minimum log level to print.
    For example, qute://log?level=warning prints warnings and errors.
    Level can be one of: vdebug, debug, info, warning, error, critical.

    - plain: If given (and not 'false'), plaintext is shown.

    - logfilter: A filter string like the --logfilter commandline argument
      accepts.
    """
    query = QUrlQuery(url)
    plain = (query.hasQueryItem('plain')
             and query.queryItemValue('plain').lower() != 'false')

    if log.ram_handler is None:
        content = "Log output was disabled." if plain else None
    else:
        level = query.queryItemValue('level')
        if not level:
            level = 'vdebug'

        filter_str = query.queryItemValue('logfilter')

        try:
            logfilter = (log.LogFilter.parse(filter_str, only_debug=False)
                         if filter_str else None)
        except log.InvalidLogFilterError as e:
            raise UrlInvalidError(e)

        content = log.ram_handler.dump_log(html=not plain,
                                           level=level,
                                           logfilter=logfilter)

    template = 'pre.html' if plain else 'log.html'
    src = jinja.render(template, title='log', content=content)
    return 'text/html', src
Пример #11
0
 def __pageLoadFinished(self):
     """
     Private slot handling the loadFinished signal.
     """
     url = self.__browser.url()
     if url.toString().startswith(
             "https://accounts.google.com/o/oauth2/approval/v2"):
         urlQuery = QUrlQuery(url)
         approvalCode = urlQuery.queryItemValue("approvalCode",
                                                QUrl.FullyDecoded)
         if approvalCode:
             self.approvalCodeReceived.emit(approvalCode)
             self.close()
Пример #12
0
    def __parseUrl(self, url):
        """
        Private method to parse the AdBlock URL for the subscription.
        
        @param url AdBlock URL for the subscription (QUrl)
        """
        if url.scheme() != "abp":
            return

        if url.path() != "subscribe":
            return

        if qVersion() >= "5.0.0":
            from PyQt5.QtCore import QUrlQuery
            urlQuery = QUrlQuery(url)
            self.__title = urlQuery.queryItemValue("title")
            self.__enabled = urlQuery.queryItemValue("enabled") != "false"
            self.__location = QByteArray(urlQuery.queryItemValue("location"))

            # Check for required subscription
            self.__requiresLocation = urlQuery.queryItemValue(
                "requiresLocation")
            self.__requiresTitle = urlQuery.queryItemValue("requiresTitle")
            if self.__requiresLocation and self.__requiresTitle:
                import Helpviewer.HelpWindow
                Helpviewer.HelpWindow.HelpWindow.adBlockManager()\
                    .loadRequiredSubscription(self.__requiresLocation,
                                              self.__requiresTitle)

            lastUpdateString = urlQuery.queryItemValue("lastUpdate")
            self.__lastUpdate = QDateTime.fromString(lastUpdateString,
                                                     Qt.ISODate)
        else:
            self.__title = \
                QUrl.fromPercentEncoding(url.encodedQueryItemValue("title"))
            self.__enabled = QUrl.fromPercentEncoding(
                url.encodedQueryItemValue("enabled")) != "false"
            self.__location = QByteArray(
                QUrl.fromPercentEncoding(
                    url.encodedQueryItemValue("location")))

            # Check for required subscription
            self.__requiresLocation = QUrl.fromPercentEncoding(
                url.encodedQueryItemValue("requiresLocation"))
            self.__requiresTitle = QUrl.fromPercentEncoding(
                url.encodedQueryItemValue("requiresTitle"))
            if self.__requiresLocation and self.__requiresTitle:
                import Helpviewer.HelpWindow
                Helpviewer.HelpWindow.HelpWindow.adBlockManager()\
                    .loadRequiredSubscription(self.__requiresLocation,
                                              self.__requiresTitle)

            lastUpdateByteArray = url.encodedQueryItemValue("lastUpdate")
            lastUpdateString = QUrl.fromPercentEncoding(lastUpdateByteArray)
            self.__lastUpdate = QDateTime.fromString(lastUpdateString,
                                                     Qt.ISODate)

        self.__loadRules()
Пример #13
0
 def __parseUrl(self, url):
     """
     Private method to parse the AdBlock URL for the subscription.
     
     @param url AdBlock URL for the subscription (QUrl)
     """
     if url.scheme() != "abp":
         return
     
     if url.path() != "subscribe":
         return
     
     if qVersion() >= "5.0.0":
         from PyQt5.QtCore import QUrlQuery
         urlQuery = QUrlQuery(url)
         self.__title = urlQuery.queryItemValue("title")
         self.__enabled = urlQuery.queryItemValue("enabled") != "false"
         self.__location = QByteArray(urlQuery.queryItemValue("location"))
         
         # Check for required subscription
         self.__requiresLocation = urlQuery.queryItemValue(
             "requiresLocation")
         self.__requiresTitle = urlQuery.queryItemValue("requiresTitle")
         if self.__requiresLocation and self.__requiresTitle:
             import Helpviewer.HelpWindow
             Helpviewer.HelpWindow.HelpWindow.adBlockManager()\
                 .loadRequiredSubscription(self.__requiresLocation,
                                           self.__requiresTitle)
         
         lastUpdateString = urlQuery.queryItemValue("lastUpdate")
         self.__lastUpdate = QDateTime.fromString(lastUpdateString,
                                                  Qt.ISODate)
     else:
         self.__title = \
             QUrl.fromPercentEncoding(url.encodedQueryItemValue("title"))
         self.__enabled = QUrl.fromPercentEncoding(
             url.encodedQueryItemValue("enabled")) != "false"
         self.__location = QByteArray(QUrl.fromPercentEncoding(
             url.encodedQueryItemValue("location")))
         
         # Check for required subscription
         self.__requiresLocation = QUrl.fromPercentEncoding(
             url.encodedQueryItemValue("requiresLocation"))
         self.__requiresTitle = QUrl.fromPercentEncoding(
             url.encodedQueryItemValue("requiresTitle"))
         if self.__requiresLocation and self.__requiresTitle:
             import Helpviewer.HelpWindow
             Helpviewer.HelpWindow.HelpWindow.adBlockManager()\
                 .loadRequiredSubscription(self.__requiresLocation,
                                           self.__requiresTitle)
         
         lastUpdateByteArray = url.encodedQueryItemValue("lastUpdate")
         lastUpdateString = QUrl.fromPercentEncoding(lastUpdateByteArray)
         self.__lastUpdate = QDateTime.fromString(lastUpdateString,
                                                  Qt.ISODate)
     
     self.__loadRules()
Пример #14
0
def search_and_render(url, fulltext_hp, fulltext_de):
    query = QUrlQuery(url)
    mode = query.queryItemValue('mode')
    phrase = query.queryItemValue('phrase')
    filters = query.queryItemValue('filters')

    r = []
    if mode in MODE_DICT:
        spec = MODE_DICT[mode]
        searcher = fulltext_hp if (spec['searcher'] == 'hp') else fulltext_de
        collector = searcher.make_collector(spec['limit'])
        res = searcher.search(collector,
                              query_str1=phrase,
                              query_str2=filters,
                              itemtypes=spec['itemtypes'],
                              highlight=spec['highlight'])
        r.append(_render_header(spec['title'], mode, phrase, filters))
        r.append(spec['renderer'](res, mode))
        r.append(_render_footer())
    else:
        r.append(_render_header('Advanced Search', mode, phrase, filters))
        r.append(_render_footer())

    return ''.join(r)
Пример #15
0
    def onAnchorClicked(self, url: QUrl):
        from notes.ui.MainWindow import MainWindow
        import webbrowser

        host = url.host()
        scheme = url.scheme()

        if scheme == "http" or scheme == "https":
            webbrowser.open(url.toString())
        elif scheme == "notesmanager":
            url.setScheme("file")

            local_path = url.toLocalFile()
            query = QUrlQuery(url)
            uuid = query.queryItemValue("uuid")

            if local_path == self.notebook.attachment_base.filename:
                self.noteViewManager.openNote(self.noteViewManager.notebook.get_note_by_uuid(uuid))
            else:
                spawn = MainWindow(None, local_path, uuid)
                spawn.show()
Пример #16
0
 def __parseUrl(self, url):
     """
     Private method to parse the AdBlock URL for the subscription.
     
     @param url AdBlock URL for the subscription
     @type QUrl
     """
     if url.scheme() != "abp":
         return
     
     if url.path() != "subscribe":
         return
     
     urlQuery = QUrlQuery(url)
     self.__title = QUrl.fromPercentEncoding(
         QByteArray(urlQuery.queryItemValue("title").encode()))
     self.__enabled = urlQuery.queryItemValue("enabled") != "false"
     self.__location = QByteArray(QUrl.fromPercentEncoding(
         QByteArray(urlQuery.queryItemValue("location").encode()))
         .encode("utf-8"))
     
     # Check for required subscription
     self.__requiresLocation = QUrl.fromPercentEncoding(
         QByteArray(urlQuery.queryItemValue(
             "requiresLocation").encode()))
     self.__requiresTitle = QUrl.fromPercentEncoding(
         QByteArray(urlQuery.queryItemValue("requiresTitle").encode()))
     if self.__requiresLocation and self.__requiresTitle:
         from WebBrowser.WebBrowserWindow import WebBrowserWindow
         WebBrowserWindow.adBlockManager().loadRequiredSubscription(
             self.__requiresLocation, self.__requiresTitle)
     
     lastUpdateString = urlQuery.queryItemValue("lastUpdate")
     self.__lastUpdate = QDateTime.fromString(lastUpdateString,
                                              Qt.ISODate)
     
     self.__loadRules()
Пример #17
0
    def acceptNavigationRequest(self, url, type_, isMainFrame):
        """
        Public method to determine, if a request may be accepted.
        
        @param url URL to navigate to
        @type QUrl
        @param type_ type of the navigation request
        @type QWebEnginePage.NavigationType
        @param isMainFrame flag indicating, that the request originated from
            the main frame
        @type bool
        @return flag indicating acceptance
        @rtype bool
        """
        scheme = url.scheme()
        if scheme == "mailto":
            QDesktopServices.openUrl(url)
            return False

        # AdBlock
        if url.scheme() == "abp":
            if WebBrowserWindow.adBlockManager().addSubscriptionFromUrl(url):
                return False

        # GreaseMonkey
        if PYQT_WEBENGINE_VERSION >= 0x50e00:  # PyQtWebEngine >= 5.14.0
            navigationType = type_ in [
                QWebEnginePage.NavigationTypeLinkClicked,
                QWebEnginePage.NavigationTypeRedirect
            ]
        else:
            navigationType = type_ == QWebEnginePage.NavigationTypeLinkClicked
        if navigationType and url.toString().endswith(".user.js"):
            WebBrowserWindow.greaseMonkeyManager().downloadScript(url)
            return False

        if url.scheme() == "eric":
            if url.path() == "AddSearchProvider":
                query = QUrlQuery(url)
                self.view().mainWindow().openSearchManager().addEngine(
                    QUrl(query.queryItemValue("url")))
                return False
            elif url.path() == "PrintPage":
                self.printPageRequested.emit()
                return False

        # Safe Browsing
        self.__badSite = False
        from WebBrowser.SafeBrowsing.SafeBrowsingManager import (
            SafeBrowsingManager)
        if (SafeBrowsingManager.isEnabled() and url.scheme()
                not in SafeBrowsingManager.getIgnoreSchemes()):
            threatLists = (
                WebBrowserWindow.safeBrowsingManager().lookupUrl(url)[0])
            if threatLists:
                threatMessages = (WebBrowserWindow.safeBrowsingManager().
                                  getThreatMessages(threatLists))
                res = E5MessageBox.warning(
                    WebBrowserWindow.getWindow(),
                    self.tr("Suspicuous URL detected"),
                    self.tr("<p>The URL <b>{0}</b> was found in the Safe"
                            " Browsing database.</p>{1}").format(
                                url.toString(), "".join(threatMessages)),
                    E5MessageBox.StandardButtons(E5MessageBox.Abort
                                                 | E5MessageBox.Ignore),
                    E5MessageBox.Abort)
                if res == E5MessageBox.Abort:
                    self.safeBrowsingAbort.emit()
                    return False

                self.__badSite = True
                threatType = (
                    WebBrowserWindow.safeBrowsingManager().getThreatType(
                        threatLists[0]))
                self.safeBrowsingBad.emit(threatType, "".join(threatMessages))

        result = QWebEnginePage.acceptNavigationRequest(
            self, url, type_, isMainFrame)

        if result:
            if isMainFrame:
                isWeb = url.scheme() in ("http", "https", "ftp", "ftps",
                                         "file")
                globalJsEnabled = WebBrowserWindow.webSettings().testAttribute(
                    QWebEngineSettings.JavascriptEnabled)
                if isWeb:
                    enable = globalJsEnabled
                else:
                    enable = True
                self.settings().setAttribute(
                    QWebEngineSettings.JavascriptEnabled, enable)

                self.__channelUrl = url
                self.__setupChannelTimer.start()
            self.navigationRequestAccepted.emit(url, type_, isMainFrame)

        return result