-
Notifications
You must be signed in to change notification settings - Fork 1
/
update.py
65 lines (53 loc) · 2.01 KB
/
update.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
from pathlib import Path
from typing import Any, List
from urllib.request import urlopen, HTTPError, URLError
class FileReader:
@staticmethod
def readFile(filename: str) -> List[str]:
with open(filename) as file:
return set(file.readlines())
class FileWriter:
@staticmethod
def write(filename: str, text: str, mode: str = 'w+') -> None:
with open(filename, mode=mode) as file:
file.write(text)
@staticmethod
def writelines(filename: str, text: Any, mode: str = 'w+') -> None:
with open(filename, mode=mode) as file:
file.writelines(text)
@staticmethod
def create_empty_file(filename: str) -> None:
with open(filename, 'w+'):
pass
class BlocklistUpdater:
def __init__(self, reader: FileReader = FileReader(), writer: FileWriter = FileWriter()):
self.reader = reader
self.writer = writer
self.adlists = "adlists.list"
def update(self, filename: str) -> None:
self.writer.create_empty_file(self.adlists)
blocklist = self.reader.readFile(filename)
print(f"Original size: {len(blocklist)}")
blocklist = self._request_data(blocklist)
print(f"New size: {len(blocklist)}")
self.writer.writelines(filename, blocklist)
def _request_data(self, blocklist: List[str]) -> List[str]:
for url in blocklist.copy():
try:
self._append_to_adlists(url)
except HTTPError:
print(f"Error at {url}\n")
blocklist.remove(url)
except URLError:
print(f"Connection refused by {url}\n")
blocklist.remove(url)
return blocklist
def _append_to_adlists(self, url: str) -> None:
with urlopen(url) as response:
self.writer.write(
self.adlists,
str(response.read().decode("utf-8")),
'a+'
)
if __name__ == '__main__':
BlocklistUpdater().update("blocklist.txt")