-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClearURLsCore.py
executable file
·78 lines (70 loc) · 2.93 KB
/
ClearURLsCore.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
'''
* ClearURLs
* Copyright (c) 2019 Kevin Röbert
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
from urllib.parse import unquote
from urllib.request import urlopen
import json
import re
'''
* Python class that used the ClearURLs data.min.json
* to clean urls. Also redirections included.
*
* @param dataURL The url to the data.min.json,
* default is the gitlab repo of ClearURLs
'''
class ClearURLsCore:
def __init__(self, dataURl
= "https://gitlab.com/KevinRoebert/ClearUrls/raw/master/data/data.min.json"):
self.dataURL = dataURl
self.pages = {}
self.initRules()
def initRules(self):
# download ClearURLs rule set
#data = urlopen(self.dataURL).read()
#load rule set from local file
data = open("data.min.json").read()
json_data = json.loads(data)
# extract and expand rules
for provider in json_data["providers"]:
urlPattern = json_data["providers"][provider]["urlPattern"]
self.pages[urlPattern] = {
"rules": [],
"exceptions": [],
"redirections": []
}
for rule in json_data["providers"][provider]["rules"]:
self.pages[urlPattern]["rules"].append("([\\/|\\?]|(&|&))("+rule+"=[^\\/|\\?|&]*)")
self.pages[urlPattern]["exceptions"] = json_data["providers"][provider]["exceptions"]
self.pages[urlPattern]["redirections"] = json_data["providers"][provider]["redirections"]
def clean(self, url):
domain = re.sub("\\?.*", "", url)
fields = "?"+re.sub(".*?\\?", "", url)
for page in self.pages:
if re.search(page, url):
for exception in self.pages[page]["exceptions"]:
if re.search(exception, url):
return url
for redirection in self.pages[page]["redirections"]:
if re.search(redirection, url):
result = re.search(redirection, url).group(1)
return unquote(result)
for rule in self.pages[page]["rules"]:
fields = re.sub(rule, "", fields)
finalFields = re.findall("[^\\/|\\?|&]+=[^\\/|\\?|&]+", fields)
if len(finalFields) > 0:
return domain + "?" + "&".join(finalFields);
return domain