Esempio n. 1
0
def create_profile():
    ans = getattr(create_profile, 'ans', None)
    if ans is None:
        ans = QWebEngineProfile(QApplication.instance())
        ua = 'calibre-editor-preview ' + __version__
        ans.setHttpUserAgent(ua)
        if is_running_from_develop:
            from calibre.utils.rapydscript import compile_editor
            compile_editor()
        js = P('editor.js', data=True, allow_user_override=False)
        cparser = P('csscolorparser.js', data=True, allow_user_override=False)

        insert_scripts(
            ans,
            create_script('csscolorparser.js', cparser),
            create_script('editor.js', js),
        )
        url_handler = UrlSchemeHandler(ans)
        ans.installUrlSchemeHandler(QByteArray(FAKE_PROTOCOL.encode('ascii')),
                                    url_handler)
        s = ans.settings()
        s.setDefaultTextEncoding('utf-8')
        s.setAttribute(s.FullScreenSupportEnabled, False)
        s.setAttribute(s.LinksIncludedInFocusChain, False)
        create_profile.ans = ans
    return ans
Esempio n. 2
0
def create_profile():
    ans = getattr(create_profile, 'ans', None)
    if ans is None:
        ans = QWebEngineProfile(QApplication.instance())
        osname = 'windows' if iswindows else ('macos' if ismacos else 'linux')
        # DO NOT change the user agent as it is used to workaround
        # Qt bugs see workaround_qt_bug() in ajax.pyj
        ua = 'calibre-viewer {} {}'.format(__version__, osname)
        ans.setHttpUserAgent(ua)
        if is_running_from_develop:
            from calibre.utils.rapydscript import compile_viewer
            prints('Compiling viewer code...')
            compile_viewer()
        js = P('viewer.js', data=True, allow_user_override=False)
        translations_json = get_translations_data() or b'null'
        js = js.replace(b'__TRANSLATIONS_DATA__', translations_json, 1)
        if in_develop_mode:
            js = js.replace(b'__IN_DEVELOP_MODE__', b'1')
        insert_scripts(ans, create_script('viewer.js', js))
        url_handler = UrlSchemeHandler(ans)
        ans.installUrlSchemeHandler(QByteArray(FAKE_PROTOCOL.encode('ascii')), url_handler)
        s = ans.settings()
        s.setDefaultTextEncoding('utf-8')
        s.setAttribute(QWebEngineSettings.WebAttribute.LinksIncludedInFocusChain, False)
        create_profile.ans = ans
    return ans
Esempio n. 3
0
def create_profile():
    ans = getattr(create_profile, 'ans', None)
    if ans is None:
        ans = QWebEngineProfile(QApplication.instance())
        ua = 'calibre-editor-preview ' + __version__
        ans.setHttpUserAgent(ua)
        if is_running_from_develop:
            from calibre.utils.rapydscript import compile_editor
            compile_editor()
        js = P('editor.js', data=True, allow_user_override=False)
        cparser = P('csscolorparser.js', data=True, allow_user_override=False)
        dark_mode_css = P('dark_mode.css',
                          data=True,
                          allow_user_override=False).decode('utf-8')

        insert_scripts(
            ans, create_script('csscolorparser.js', cparser),
            create_script('editor.js', js),
            create_script('dark-mode.js',
                          '''
            (function() {
                var settings = JSON.parse(navigator.userAgent.split('|')[1]);
                var dark_css = CSS;

                function apply_body_colors(event) {
                    if (document.documentElement) {
                        if (settings.bg) document.documentElement.style.backgroundColor = settings.bg;
                        if (settings.fg) document.documentElement.style.color = settings.fg;
                    }
                    if (document.body) {
                        if (settings.bg) document.body.style.backgroundColor = settings.bg;
                        if (settings.fg) document.body.style.color = settings.fg;
                    }
                }

                function apply_css() {
                    var css = '';
                    if (settings.link) css += 'html > body :link, html > body :link * { color: ' + settings.link + ' !important; }';
                    if (settings.is_dark_theme) { css += dark_css; }
                    var style = document.createElement('style');
                    style.textContent = css;
                    document.documentElement.appendChild(style);
                    apply_body_colors();
                }

                apply_body_colors();
                document.addEventListener("DOMContentLoaded", apply_css);
            })();
            '''.replace('CSS', json.dumps(dark_mode_css), 1),
                          injection_point=QWebEngineScript.InjectionPoint.
                          DocumentCreation))
        url_handler = UrlSchemeHandler(ans)
        ans.installUrlSchemeHandler(QByteArray(FAKE_PROTOCOL.encode('ascii')),
                                    url_handler)
        s = ans.settings()
        s.setDefaultTextEncoding('utf-8')
        s.setAttribute(s.FullScreenSupportEnabled, False)
        s.setAttribute(s.LinksIncludedInFocusChain, False)
        create_profile.ans = ans
    return ans
Esempio n. 4
0
 def create_webprofile(self):
     """Create a webengineprofile to use in all views."""
     if self.config.get("privacy_mode"):
         webprofile = QWebEngineProfile()
     else:
         webprofile = QWebEngineProfile.defaultProfile()
     debug("Browser session is private: {}".format(
         webprofile.isOffTheRecord()))
     if self.config.get("user_agent"):
         webprofile.setHttpUserAgent(self.config["user_agent"])
         debug('Set user agent to "{}"'.format(webprofile.httpUserAgent()))
     self.webprofile = webprofile
Esempio n. 5
0
def create_profile():
    ans = getattr(create_profile, 'ans', None)
    if ans is None:
        ans = QWebEngineProfile('viewer-lookup', QApplication.instance())
        ans.setHttpUserAgent(random_user_agent(allow_ie=False))
        ans.setCachePath(os.path.join(cache_dir(), 'ev2vl'))
        js = P('lookup.js', data=True, allow_user_override=False)
        insert_scripts(ans, create_script('lookup.js', js))
        s = ans.settings()
        s.setDefaultTextEncoding('utf-8')
        create_profile.ans = ans
    return ans
Esempio n. 6
0
def create_profile():
    ans = getattr(create_profile, 'ans', None)
    if ans is None:
        ans = QWebEngineProfile(QApplication.instance())
        ua = 'calibre-viewer ' + __version__
        ans.setHttpUserAgent(ua)
        if is_running_from_develop:
            from calibre.utils.rapydscript import compile_viewer
            print('Compiling viewer code...')
            compile_viewer()
        js = P('viewer.js', data=True, allow_user_override=False)
        translations_json = get_translations_data() or b'null'
        js = js.replace(b'__TRANSLATIONS_DATA__', translations_json, 1)
        insert_scripts(ans, create_script('viewer.js', js))
        url_handler = UrlSchemeHandler(ans)
        ans.installUrlSchemeHandler(QByteArray(FAKE_PROTOCOL.encode('ascii')), url_handler)
        s = ans.settings()
        s.setDefaultTextEncoding('utf-8')
        s.setAttribute(s.LinksIncludedInFocusChain, False)
        create_profile.ans = ans
    return ans
Esempio n. 7
0
    def __init__(self, opts, log, container_root):
        QObject.__init__(self)
        self.interceptor = RequestInterceptor(self)
        self.has_maths = {}
        self.interceptor.log = self.log = log
        self.interceptor.container_root = os.path.normcase(os.path.abspath(container_root))
        self.interceptor.resources_root = os.path.normcase(os.path.abspath(os.path.dirname(mathjax_dir())))
        ans = QWebEngineProfile(QApplication.instance())
        ua = 'calibre-pdf-output ' + __version__
        ans.setHttpUserAgent(ua)
        s = ans.settings()
        s.setDefaultTextEncoding('utf-8')
        ans.setUrlRequestInterceptor(self.interceptor)
        self.profile = ans

        self.opts = opts
        self.workers = []
        self.max_workers = detect_ncpus()
        if iswindows:
            self.original_signal_handlers = {}
        else:
            self.original_signal_handlers = setup_unix_signals(self)
Esempio n. 8
0
 def web_profile_setup(self, profile: QWebEngineProfile):
     profile.setHttpUserAgent(self.user_agent)
Esempio n. 9
0
class Njaxt(QtWidgets.QMainWindow, njaxt_ui.Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.fuzzer = None
        self.stopLoop = False
        self.fuzz_widget = FuzzerWidget()
        self.payload_widget = PayloadsWidget()
        self.init_webview()
        self.init_sigslot()
        self.show()

    def init_webview(self):
        self.webProfile = QWebEngineProfile(self.webView)
        self.webProfile.setHttpUserAgent(
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
        )
        self.webProfile.setHttpAcceptLanguage("en-US,en;q=0.8")
        self.webProfile.settings().setAttribute(
            QWebEngineSettings.LocalStorageEnabled, True)
        self.set_scripts()
        self.webPage = QWebEnginePage(self.webProfile, self)

        self.webView.setPage(self.webPage)
        self.webView.loadProgress.connect(self.set_progress)
        self.webView.loadFinished.connect(
            lambda: self.lineEdit.setText(self.webView.url().toString()))

    def set_scripts(self):
        script = QWebEngineScript()
        script.setInjectionPoint(QWebEngineScript.DocumentCreation)
        script.setWorldId(QWebEngineScript.MainWorld)
        script.setSourceCode("""(function() {
                                    var _old_alert = window.alert;
                                    window.alert = function() {
                                        document.activeElement.innerHTML += "<br>alerting";
                                        _old_alert.apply(window,arguments);
                                        document.activeElement.innerHTML += "<br>done alerting<br>";
                                    };
                                })();
                             """)
        self.webProfile.scripts().insert(script)

    def init_sigslot(self):
        self.lineEdit.returnPressed.connect(self.make_fuzzer)
        self.pushButton.clicked.connect(self.make_fuzzer)
        self.pushButtonReset.clicked.connect(self.handle_reset)

        self.actionAdvanced_Fuzzer.triggered.connect(self.show_fuzz)
        self.fuzz_widget.pushButton.clicked.connect(self.make_fuzzer)

        self.actionWordlist.triggered.connect(self.show_payloads)

    def set_progress(self, p):
        self.progressBar.setValue(p)

    def show_fuzz(self):
        self.fuzz_widget.show()

    def show_payloads(self):
        self.payload_widget.show()

    def make_fuzzer(self):
        if self.fuzz_widget.data:
            self.fuzzer = fuzzer.Fuzzer(self.fuzz_widget.data)
        else:
            self.fuzzer = fuzzer.Fuzzer({"url": self.lineEdit.text()})

        self.fuzz()

    def handle_reset(self):
        # Reset Fuzz Widget
        self.fuzz_widget.reset_widget()
        # Reset Main Form
        self.fuzzer = fuzzer.Fuzzer({"url": ""})
        self.init_webview()
        self.lineEdit.setText("")
        self.set_progress(0)
        self.stopLoop = False

    def detect_xss(self, source):
        if "<br>alerting" in source:
            print(self.lineEdit.text())
            self.stopLoop = True

    def fuzz(self):
        loop = QEventLoop()
        for request in self.fuzzer.requests(PAYLOADS):
            self.webView.loadFinished.connect(loop.quit)
            self.webView.load(request)
            loop.exec()
            self.webView.page().toHtml(self.detect_xss)
            if self.stopLoop:
                break
Esempio n. 10
0
    def __init__(self, url, disable_browser):

        # initialize
        super().__init__()
        self._view = None
        self._is_closing = False

        # initialize the main window
        self.setWindowTitle(APP_NAME)
        if IS_FROZEN:
            base_dir = os.path.join(sys._MEIPASS, "vasl_templates/webapp")  #pylint: disable=no-member,protected-access
        else:
            base_dir = os.path.join(os.path.split(__file__)[0], "webapp")
        self.setWindowIcon(
            QIcon(os.path.join(base_dir, "static/images/app.ico")))

        # create the menu
        menu_bar = QMenuBar(self)
        file_menu = menu_bar.addMenu("&File")

        def add_action(caption, icon, handler):
            """Add a menu action."""
            icon = QIcon(
                os.path.join(base_dir, "static/images/menu", icon
                             ) if icon else None)
            action = QAction(icon, caption, self)
            action.triggered.connect(handler)
            file_menu.addAction(action)

        add_action("&Settings", "settings.png", self.on_settings)
        add_action("&About", "info.png", self.on_about)
        file_menu.addSeparator()
        add_action("E&xit", "exit.png", self.on_exit)

        # set the window geometry
        if disable_browser:
            self.setFixedSize(300, 108)
        else:
            # restore it from the previous session
            val = app_settings.value("MainWindow/geometry")
            if val:
                self.restoreGeometry(val)
            else:
                self.resize(1000, 650)
            self.setMinimumSize(1000, 620)

        # initialize the layout
        layout = QVBoxLayout(self)
        layout.setMenuBar(menu_bar)
        # FUDGE! We offer the option to disable the QWebEngineView since getting it to run
        # under Windows (especially older versions) is unreliable (since it uses OpenGL).
        # By disabling it, the program will at least start (in particular, the webapp server),
        # and non-technical users can then open an external browser and connect to the webapp
        # that way. Sigh...
        if not disable_browser:

            # initialize the web view
            self._view = QWebEngineView()
            layout.addWidget(self._view)

            # initialize the web page
            # nb: we create an off-the-record profile to stop the view from using cached JS files :-/
            profile = QWebEngineProfile(None, self._view)
            version = APP_NAME.lower().replace(" ",
                                               "-") + "/" + APP_VERSION[1:]
            profile.setHttpUserAgent(
                re.sub(r"QtWebEngine/\S+", version, profile.httpUserAgent()))
            page = AppWebPage(profile, self._view)
            self._view.setPage(page)

            # create a web channel to communicate with the front-end
            web_channel = QWebChannel(page)
            # FUDGE! We would like to register a WebChannelHandler instance as the handler, but this crashes PyQt :-/
            # Instead, we register ourself as the handler, and delegate processing to a WebChannelHandler.
            # The downside is that PyQt emits lots of warnings about our member variables not being properties,
            # but we filter them out in qtMessageHandler() :-/
            self._web_channel_handler = WebChannelHandler(self)
            web_channel.registerObject("handler", self)
            page.setWebChannel(web_channel)

            # load the webapp
            url += "?pyqt=1"
            self._view.load(QUrl(url))

        else:

            # show a minimal UI
            label = QLabel()
            label.setTextFormat(Qt.RichText)
            label.setText(
                "Running the <em>{}</em> application. <br>" \
                "Click <a href='{}'>here</a> to connect." \
                "<p> Close this window when you're done.".format(
                APP_NAME, url
            ) )
            label.setStyleSheet(
                "QLabel { background-color: white ; padding: 0.5em ; }")
            label.setOpenExternalLinks(True)
            layout.addWidget(label)
            layout.setContentsMargins(QMargins(0, 0, 0, 0))

        # register the instance
        assert MainWindow.instance is None
        MainWindow.instance = self
Esempio n. 11
0
 def init_profile(self, browser):
     profile = QWebEngineProfile(browser)
     profile.setHttpUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36')
     return profile
Esempio n. 12
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("StubHub Price Bot")

        wx, wy = self.determin_window_size()
        #MainWindow.resize(1593, 832)
        MainWindow.resize(wy, wx)

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.activateButton = QtWidgets.QPushButton(self.centralwidget)
        self.activateButton.setGeometry(QtCore.QRect(10, 770, 61, 23))
        self.activateButton.setObjectName("activateButton")

        self.deactivateButton = QtWidgets.QPushButton(self.centralwidget)
        self.deactivateButton.setGeometry(QtCore.QRect(80, 770, 61, 23))
        self.deactivateButton.setObjectName("deactivateButton")

        self.refreshButton = QtWidgets.QPushButton(self.centralwidget)
        self.refreshButton.setGeometry(QtCore.QRect(150, 770, 71, 23))
        self.refreshButton.setObjectName("refreshButton")

        self.quitButton = QtWidgets.QPushButton(self.centralwidget)
        self.quitButton.setGeometry(QtCore.QRect(230, 770, 71, 23))
        self.quitButton.setObjectName("quitButton")

        self.cmbbox_site = QtWidgets.QComboBox(self.centralwidget)
        self.cmbbox_site.setGeometry(QtCore.QRect(70, 20, 151, 22))
        self.cmbbox_site.setObjectName("cmbboxSite")
        self.cmbbox_site.addItem("")
        self.cmbbox_site.addItem("https://stubhub.jp/")
        self.cmbbox_site.addItem("https://intl.stubhub.com")

        #self.username_field = QtWidgets.QLineEdit(self.centralwidget)
        self.username_field = CustomLineEdit(self.centralwidget)
        self.username_field.setGeometry(QtCore.QRect(70, 60, 151, 20))
        self.username_field.setObjectName("usernameField")

        #self.password_field = QtWidgets.QLineEdit(self.centralwidget)
        self.password_field = CustomLineEdit(self.centralwidget)
        self.password_field.setGeometry(QtCore.QRect(70, 90, 151, 21))
        self.password_field.setObjectName("passwordField")
        self.password_field.setEchoMode(QtWidgets.QLineEdit.Password)

        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(10, 20, 51, 16))
        self.label.setObjectName("label")

        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(10, 60, 47, 13))
        self.label_2.setObjectName("label_2")

        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(10, 90, 47, 13))
        self.label_3.setObjectName("label_3")

        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(10, 165, 51, 16))
        self.label_4.setObjectName("label_4")

        self.price_reduction_lbl = QtWidgets.QLabel(self.centralwidget)
        self.price_reduction_lbl.setGeometry(QtCore.QRect(10, 125, 120, 16))
        self.price_reduction_lbl.setObjectName("price_reduction_lbl")

        #self.reduct_field = QtWidgets.QLineEdit(self.centralwidget)
        self.reduct_field = CustomLineEdit(self.centralwidget)
        self.reduct_field.setGeometry(QtCore.QRect(180, 125, 40, 20))
        self.reduct_field.setObjectName("usernameField")
        self.reduct_field.setText("20")

        feedback_box = QTextEditLogger(self.centralwidget)
        feedback_box.setFormatter(logging.Formatter('%(message)s'))
        logging.getLogger().addHandler(feedback_box)

        feedback_box.widget.setGeometry(QtCore.QRect(10, 310, 440, 440))
        feedback_box.widget.setObjectName("feedbackBox")
        feedback_box.widget.setReadOnly(True)
        feedback_box.widget.setLineWrapMode(QtWidgets.QPlainTextEdit.NoWrap)
        feedback_box.widget.moveCursor(QTextCursor.End)

        feedback_box.widget.setStyleSheet("""
            QPlainTextEdit {background-color: #333345;
                           color: #AAFFDD;
                           font-family: Courier;
                           white-space: nowrap;
                           }
            """)

        feedback_box.setLevel(logging.INFO)
        self.add_file_logger()

        logging.getLogger().setLevel(logging.DEBUG)

        logging.info("Welcome\n")

        #self.freq_value_box = QtWidgets.QLineEdit(self.centralwidget)
        self.freq_value_box = CustomLineEdit(self.centralwidget)
        self.freq_value_box.setGeometry(QtCore.QRect(70, 165, 41, 20))
        self.freq_value_box.setObjectName("freqValueBox")

        self.cmbbox_freq = QtWidgets.QComboBox(self.centralwidget)
        self.cmbbox_freq.setGeometry(QtCore.QRect(140, 165, 81, 22))
        self.cmbbox_freq.setObjectName("cmbbox_freq")
        self.cmbbox_freq.addItem("")
        self.cmbbox_freq.addItem("minute")
        self.cmbbox_freq.addItem("hour")
        self.cmbbox_freq.addItem("day")

        self.exec_type_box = QtWidgets.QComboBox(self.centralwidget)
        self.exec_type_box.setGeometry(QtCore.QRect(70, 210, 151, 22))
        self.exec_type_box.setObjectName("execTypeBox")
        self.exec_type_box.addItem("")
        self.exec_type_box.addItem("Test")
        self.exec_type_box.addItem("Live")

        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(10, 210, 51, 16))
        self.label_5.setObjectName("label_5")

        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setGeometry(QtCore.QRect(10, 280, 51, 16))
        self.label_6.setObjectName("label_6")

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 872, 18))
        self.menubar.setObjectName("menubar")

        self.fileMenu = self.menubar.addMenu('File')
        self.optionAction = QAction('Options')
        self.exitAction = QAction('Exit')

        self.fileMenu.addAction(self.optionAction)
        self.fileMenu.addAction(self.exitAction)

        self.exitAction.triggered.connect(sys.exit)
        self.optionAction.triggered.connect(self.show_options)

        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        # get screen resolution
        self.web_view = QWebEngineView(self.centralwidget)
        #self.web_view = QWebEngineView()
        profile = QWebEngineProfile(self.web_view)
        profile.setHttpUserAgent(
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36"
        )
        webpage = QWebEnginePage(profile, self.web_view)
        self.web_view.setPage(webpage)

        self.web_view.setGeometry(QtCore.QRect(470, 20, 1100, 800))
        self.web_view.setObjectName("webContainer")
        self.web_view.setUrl(QtCore.QUrl("about:blank"))
        self.web_view.show()

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)