def addSubscriptionFromUrl(self, url): """ Public method to ad an AdBlock subscription given the abp URL. @param url URL to subscribe an AdBlock subscription @type QUrl @return flag indicating success @rtype bool """ if url.path() != "subscribe": return False title = QUrl.fromPercentEncoding( QByteArray(QUrlQuery(url).queryItemValue("title").encode())) if not title: return False res = E5MessageBox.yesNo( None, self.tr("Subscribe?"), self.tr("""<p>Subscribe to this AdBlock subscription?</p>""" """<p>{0}</p>""").format(title)) if res: from .AdBlockSubscription import AdBlockSubscription from WebBrowser.WebBrowserWindow import WebBrowserWindow dlg = WebBrowserWindow.adBlockManager().showDialog() subscription = AdBlockSubscription( url, False, WebBrowserWindow.adBlockManager()) WebBrowserWindow.adBlockManager().addSubscription(subscription) dlg.addSubscription(subscription, False) dlg.setFocus() dlg.raise_() return res
def accept(self): """ Public slot handling the acceptance of the dialog. """ hosts = [] for row in range(self.hostList.count()): hosts.append(self.hostList.item(row).text()) from WebBrowser.WebBrowserWindow import WebBrowserWindow WebBrowserWindow.adBlockManager().setExceptions(hosts) super(AdBlockExceptionsDialog, self).accept()
def hideBlockedPageEntries(self, page): """ Public method to apply AdBlock rules to a web page. @param page reference to the web page (HelpWebPage) """ if page is None: return from WebBrowser.WebBrowserWindow import WebBrowserWindow manager = WebBrowserWindow.adBlockManager() if not manager.isEnabled(): return # apply global element hiding rules elementHiding = manager.elementHidingRules(page.url()) if elementHiding: script = Scripts.setCss(elementHiding) page.runJavaScript(script, WebBrowserPage.SafeJsWorld) # apply domain specific element hiding rules elementHiding = manager.elementHidingRulesForDomain(page.url()) if elementHiding: script = Scripts.setCss(elementHiding) page.runJavaScript(script, WebBrowserPage.SafeJsWorld)
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()
def __rulesDownloaded(self, reply): """ Private slot to deal with the downloaded rules. @param reply reference to the network reply @type QNetworkReply """ response = reply.readAll() reply.close() self.__downloading = None if reply.error() != QNetworkReply.NoError: if not self.__defaultSubscription: # don't show error if we try to load the default E5MessageBox.warning( None, self.tr("Downloading subscription rules"), self.tr( """<p>Subscription rules could not be""" """ downloaded.</p><p>Error: {0}</p>""") .format(reply.errorString())) else: # reset after first download attempt self.__defaultSubscription = False return if response.isEmpty(): E5MessageBox.warning( None, self.tr("Downloading subscription rules"), self.tr("""Got empty subscription rules.""")) return fileName = self.rulesFileName() QFile.remove(fileName) f = QFile(fileName) if not f.open(QIODevice.ReadWrite): E5MessageBox.warning( None, self.tr("Downloading subscription rules"), self.tr( """Unable to open AdBlock file '{0}' for writing.""") .file(fileName)) return from WebBrowser.WebBrowserWindow import WebBrowserWindow if ( WebBrowserWindow.adBlockManager().useLimitedEasyList() and self.url().toString().startswith( WebBrowserWindow.adBlockManager().getDefaultSubscriptionUrl()) ): limited = True # ignore Third-party advertisers rules for performance # whitelist rules at the end will be used index = response.indexOf( "!---------------------------" "Third-party advertisers" "---------------------------!") part1 = response.left(index) index = response.indexOf( "!-----------------------" "Whitelists to fix broken sites" "------------------------!") part2 = response.mid(index) f.write(part1) f.write(part2) else: limited = False f.write(response) f.close() self.__lastUpdate = QDateTime.currentDateTime() if limited or self.__validateCheckSum(fileName): self.__loadRules() else: QFile.remove(fileName) self.__downloading = None reply.deleteLater()
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