eric6/Helpviewer/AdBlock/AdBlockPage.py

branch
maintenance
changeset 7286
7eb04391adf7
parent 7226
babe80d84a3e
parent 7285
1ff497f33f31
child 7287
1c17f2191bdd
equal deleted inserted replaced
7226:babe80d84a3e 7286:7eb04391adf7
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2009 - 2019 Detlev Offenbach <detlev@die-offenbachs.de>
4 #
5
6 """
7 Module implementing a class to apply AdBlock rules to a web page.
8 """
9
10 from __future__ import unicode_literals
11
12 from PyQt5.QtCore import QObject, QUrl
13
14
15 class AdBlockPage(QObject):
16 """
17 Class to apply AdBlock rules to a web page.
18 """
19 def hideBlockedPageEntries(self, page):
20 """
21 Public method to apply AdBlock rules to a web page.
22
23 @param page reference to the web page (HelpWebPage)
24 """
25 if page is None or page.mainFrame() is None:
26 return
27
28 import Helpviewer.HelpWindow
29 manager = Helpviewer.HelpWindow.HelpWindow.adBlockManager()
30 if not manager.isEnabled():
31 return
32
33 docElement = page.mainFrame().documentElement()
34
35 for entry in page.getAdBlockedPageEntries():
36 urlString = entry.urlString()
37 if urlString.endswith((".js", ".css")):
38 continue
39
40 urlEnd = ""
41 pos = urlString.rfind("/")
42 if pos >= 0:
43 urlEnd = urlString[pos + 1:]
44 if urlString.endswith("/"):
45 urlEnd = urlString[:-1]
46
47 selector = \
48 'img[src$="{0}"], iframe[src$="{0}"], embed[src$="{0}"]'\
49 .format(urlEnd)
50 elements = docElement.findAll(selector)
51
52 for element in elements:
53 src = element.attribute("src")
54 src = src.replace("../", "")
55 if src in urlString:
56 element.setStyleProperty("display", "none")
57
58 # apply domain specific element hiding rules
59 elementHiding = manager.elementHidingRulesForDomain(page.url())
60 if not elementHiding:
61 return
62
63 elementHiding += "{display: none !important;}\n</style>"
64
65 bodyElement = docElement.findFirst("body")
66 bodyElement.appendInside(
67 '<style type="text/css">\n/* AdBlock for eric */\n' +
68 elementHiding)
69
70
71 class AdBlockedPageEntry(object):
72 """
73 Class implementing a data structure for web page rules.
74 """
75 def __init__(self, rule, url):
76 """
77 Constructor
78
79 @param rule AdBlock rule to add (AdBlockRule)
80 @param url URL that matched the rule (QUrl)
81 """
82 self.rule = rule
83 self.url = QUrl(url)
84
85 def __eq__(self, other):
86 """
87 Special method to test equality.
88
89 @param other reference to the other entry (AdBlockedPageEntry)
90 @return flag indicating equality (boolean)
91 """
92 return self.rule == other.rule and self.url == other.url
93
94 def urlString(self):
95 """
96 Public method to get the URL as a string.
97
98 @return URL as a string (string)
99 """
100 return self.url.toString()

eric ide

mercurial