-
Notifications
You must be signed in to change notification settings - Fork 0
/
phpbb_downloader.py
executable file
·307 lines (262 loc) · 10.8 KB
/
phpbb_downloader.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#!/usr/bin/env python
import bs4
import os
import re
import requests
import sys
import threading
from urllib.parse import parse_qs, urlparse
visited_links = []
downloaded_files = []
db_fname = ""
bl_fname = ""
downloadThreads = [] # a list of all the Thread objects
external_links = []
log_file = ""
logtext = ""
sys.setrecursionlimit(10000)
def myprint(text):
global logtext, log_file
print(text)
logtext += text + "\n"
if len(logtext) > 1000:
log = open(log_file, "a")
log.write(logtext)
logtext = ""
def save_to_database(url):
global db_fname
dbfile = open(db_fname, "a")
dbfile.write(url + "\n")
def save_broken_link(url):
global bl_fname
blfile = open(bl_fname, "a")
blfile.write(url + "\n")
def clean_link(base, url):
url = url.lstrip('.')
if not (url.startswith("http://") or url.startswith("https://")):
if url.startswith("/"):
url = "http://" + base + url
else:
url = "http://" + url
return url
def update_file_name(filename):
# remove ASCII character codes from filename
reg = re.compile(r'(%\d{0,2})')
filename = reg.sub(r'_', filename)
# if current url need to download, but file exists
try:
if os.path.isfile(filename):
# rename it
f_n, f_ext = os.path.splitext(filename)
i = 1
while os.path.isfile(f_n + "_({0})".format(str(i)) + f_ext):
i = i + 1
filename_new = f_n + "_({0})".format(str(i)) + f_ext
myprint('Rename file "{0}" to "{1}"'.format(filename, filename_new))
filename = filename_new
except:
myprint('Error! Cannot check filename "{0}"'.format(filename))
filename = ""
return filename
def download_if_not_ex(folder, filename, url, getfname=False):
global downloaded_files
flag = True
# if current file is not exist, download it
if not url in downloaded_files:
downloaded_files.append(url)
save_to_database(url)
try:
res = requests.get(url)
res.raise_for_status()
if getfname:
disp = res.headers['content-disposition']
fn = re.findall(r"filename\*=UTF-8''(.+)", disp)
filename = filename + "_" + fn[0]
except:
myprint("Error! Cannot download file: " + url)
flag = False
if flag:
filename = os.path.join(folder, filename)
filename = update_file_name(filename)
if filename != "":
someFile = open(filename, 'wb')
for chunk in res.iter_content(100000):
someFile.write(chunk)
someFile.close()
else:
myprint("Error! Cannot save downloaded file: " + url)
filename = "index.html#ERROR"
return os.path.basename(filename)
def download_recursively(url, basepath, folder, fname):
global visited_links, external_links
visited_links.append(url)
currlinks = {}
myprint('Download page "{0}"...'.format(url))
try:
res = requests.get(url)
res.raise_for_status()
except:
myprint("Error! Cannot open page: " + url)
save_broken_link(url)
return
soup = bs4.BeautifulSoup(res.text, 'html5lib')
# Download .css files to ./<netloc>
for link in soup.find_all('link', href=True):
tempUrl = clean_link(basepath, link['href'])
parsedUrl = urlparse(tempUrl)
if parsedUrl.path.endswith(".css") or parsedUrl.path.endswith("style.php"):
if parsedUrl.path.endswith("style.php"):
qr = parse_qs(parsedUrl.query, keep_blank_values=True)
tempUrl = parsedUrl.scheme + "://" + parsedUrl.netloc + parsedUrl.path + "?"
if 'id' in qr.keys():
tempUrl = tempUrl + 'id=' + ''.join(qr['id']) + '&'
if 'lang' in qr.keys():
tempUrl = tempUrl + 'lang=' + ''.join(qr['lang']) + '&'
tempUrl = tempUrl.rstrip('&')
css_fname = "style.css"
else:
css_fname = os.path.basename(parsedUrl.path)
css_fname = download_if_not_ex(folder, css_fname, tempUrl)
link['href'] = "./" + css_fname
else:
link['href'] = "#"
# Download .js files to ./<netloc>
for script in soup.find_all('script', src=True):
tempUrl = clean_link(basepath, script['src'])
parsedUrl = urlparse(tempUrl)
if parsedUrl.path.endswith(".js"):
js_fname = os.path.basename(parsedUrl.path)
js_fname = download_if_not_ex(folder, js_fname, tempUrl)
script['src'] = "./" + js_fname
else:
script['src'] = "#"
# Download image files in <img> tag to ./<netloc>
for img in soup.find_all('img', src=True):
tempUrl = clean_link(basepath, img['src'])
parsedUrl = urlparse(tempUrl)
getfname = False
img_fname = os.path.basename(parsedUrl.path)
qr = parse_qs(parsedUrl.query, keep_blank_values=True)
new_url = parsedUrl.scheme + "://" + parsedUrl.netloc + parsedUrl.path + "?"
if 'avatar' in qr.keys():
img_fname = ''.join(qr['avatar'])
new_url = new_url + 'avatar=' + img_fname + '&'
if 'id' in qr.keys():
img_fname = ''.join(qr['id'])
new_url = new_url + 'id=' + img_fname + '&'
getfname = True
new_url = new_url.rstrip('&')
new_url = new_url.rstrip('?')
img_fname = download_if_not_ex(folder, img_fname, new_url, getfname)
img['src'] = "./" + img_fname
# Download links in <a> tag
for a in soup.find_all('a', href=True):
tempUrl = clean_link(basepath, a['href'])
parsedUrl = urlparse(tempUrl)
if (parsedUrl.path.endswith("viewforum.php") or parsedUrl.path.endswith("viewtopic.php")) \
and parsedUrl.netloc == basepath.split('/')[0]:
qr = parse_qs(parsedUrl.query, keep_blank_values=True)
if 'f' in qr.keys() or 't' in qr.keys():
if parsedUrl.path.endswith("viewtopic.php") and ('t' not in qr.keys()):
a['href'] = "#"
continue
new_url = parsedUrl.scheme + "://" + parsedUrl.netloc + parsedUrl.path + "?"
if 'f' in qr.keys() and ('t' not in qr.keys()):
new_url = new_url + 'f=' + ''.join(qr['f']) + '&'
if 't' in qr.keys():
new_url = new_url + 't=' + ''.join(qr['t']) + '&'
if 'start' in qr.keys():
if ''.join(qr['start']) != "0":
new_url = new_url + 'start=' + ''.join(qr['start']) + '&'
new_url = new_url.rstrip('&')
new_fname = os.path.basename(new_url)
if parsedUrl.path == "":
new_fname = "index.html"
reg = re.compile(r'([.?=&])')
new_fname = reg.sub(r'_', new_fname)
new_fname += '.html'
a['href'] = "./" + new_fname
if new_url not in visited_links:
currlinks[new_url] = new_fname
elif parsedUrl.path.endswith("dl_file.php") and parsedUrl.netloc == basepath.split('/')[0]:
# get attachment
att_name = "some_file"
qr = parse_qs(parsedUrl.query, keep_blank_values=True)
new_url = parsedUrl.scheme + "://" + parsedUrl.netloc + parsedUrl.path + "?"
if 'site' in qr.keys():
new_url = new_url + 'site=' + ''.join(qr['site']) + '&'
if 'file' in qr.keys():
att_name = ''.join(qr['file'])
new_url = new_url + 'file=' + att_name + '&'
new_url = new_url.rstrip('&')
att_name = download_if_not_ex(folder, att_name, new_url)
a['href'] = "./" + att_name
elif parsedUrl.path.endswith("file.php") and parsedUrl.netloc == basepath.split('/')[0]:
# get attachment
getfname = True
att_name = ""
qr = parse_qs(parsedUrl.query, keep_blank_values=True)
new_url = parsedUrl.scheme + "://" + parsedUrl.netloc + parsedUrl.path + "?"
if 'id' in qr.keys():
att_name = ''.join(qr['id'])
new_url = new_url + 'id=' + att_name
att_name = download_if_not_ex(folder, att_name, new_url, getfname)
a['href'] = "./" + att_name
elif parsedUrl.netloc == basepath.split('/')[0]:
if parsedUrl.path.endswith("index.php"):
a['href'] = "./index.html"
else:
a['href'] = "#"
else:
if parsedUrl.netloc != "":
if tempUrl not in external_links:
external_links.append(tempUrl)
myprint("External link is found: " + tempUrl)
# Save main file with BeautifulSoup rewrites
temp_fname = ""
try:
temp_fname = os.path.join(folder, os.path.basename(fname))
tempFile = open(temp_fname, 'wb')
html = soup.prettify("utf-8")
tempFile.write(html)
tempFile.close()
except:
myprint('Error! Cannot save file from url "{0}" with name "{1}"'.format(url, temp_fname))
# Download other .html files from current page
for k_url, v_name in currlinks.items():
# Check visited urls again
if k_url not in visited_links:
download_recursively(k_url, basepath, folder, v_name)
def download_forum(url, numthreads):
numthreads = int(numthreads)
url = url.rstrip('/')
urlpars = urlparse(url)
fold = urlpars.netloc
os.makedirs(fold, exist_ok=True) # store files in ./<netloc>
basepath = fold + urlpars.path
fname = urlpars.path
if urlpars.path == "":
fname = 'index.html'
elif not (urlpars.path.endswith(".php") or urlpars.path.endswith(".html")):
fname = fname + ".html"
for i in range(numthreads):
downloadThread = threading.Thread(target=download_recursively,
args=[url, basepath, fold, fname])
downloadThreads.append(downloadThread)
downloadThread.start()
# Wait for all threads to end
for downloadThread in downloadThreads:
downloadThread.join()
myprint('Done.')
if len(sys.argv) == 6:
db_fname = sys.argv[3]
log_file = sys.argv[4]
bl_fname = sys.argv[5]
if os.path.isfile(db_fname):
db_file = open(db_fname, 'r')
downloaded_files = db_file.read().splitlines()
db_file.close()
download_forum(sys.argv[1], sys.argv[2])
else:
print('Usage: ./phpbb_downloader.py <url> <number_of_threads> <db_name> <log_name> <file_with_broken_links>')
print('Example: ./phpbb_downloader.py http://www.bokt.nl/forums/ 10 database.txt log.txt errorlinks.txt')