2
0

archive_methods.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. import os
  2. import sys
  3. from functools import wraps
  4. from collections import defaultdict
  5. from datetime import datetime
  6. from subprocess import run, PIPE, DEVNULL
  7. from peekable import Peekable
  8. from index import wget_output_path, parse_json_link_index, write_link_index
  9. from links import links_after_timestamp
  10. from config import (
  11. CHROME_BINARY,
  12. FETCH_WGET,
  13. FETCH_WGET_REQUISITES,
  14. FETCH_PDF,
  15. FETCH_SCREENSHOT,
  16. FETCH_DOM,
  17. FETCH_WARC,
  18. FETCH_GIT,
  19. FETCH_MEDIA,
  20. RESOLUTION,
  21. CHECK_SSL_VALIDITY,
  22. SUBMIT_ARCHIVE_DOT_ORG,
  23. FETCH_AUDIO,
  24. FETCH_VIDEO,
  25. FETCH_FAVICON,
  26. WGET_USER_AGENT,
  27. CHROME_USER_DATA_DIR,
  28. CHROME_SANDBOX,
  29. TIMEOUT,
  30. MEDIA_TIMEOUT,
  31. ANSI,
  32. ARCHIVE_DIR,
  33. GIT_DOMAINS,
  34. )
  35. from util import (
  36. check_dependencies,
  37. progress,
  38. chmod_file,
  39. pretty_path,
  40. )
  41. _RESULTS_TOTALS = { # globals are bad, mmkay
  42. 'skipped': 0,
  43. 'succeded': 0,
  44. 'failed': 0,
  45. }
  46. def archive_links(archive_path, links, source=None, resume=None):
  47. check_dependencies()
  48. to_archive = Peekable(links_after_timestamp(links, resume))
  49. idx, link = 0, to_archive.peek(0)
  50. try:
  51. for idx, link in enumerate(to_archive):
  52. link_dir = os.path.join(ARCHIVE_DIR, link['timestamp'])
  53. archive_link(link_dir, link)
  54. except (KeyboardInterrupt, SystemExit, Exception) as e:
  55. print('{lightyellow}[X] [{now}] Downloading paused on link {timestamp} ({idx}/{total}){reset}'.format(
  56. **ANSI,
  57. now=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  58. idx=idx+1,
  59. timestamp=link['timestamp'],
  60. total=len(links),
  61. ))
  62. print(' Continue where you left off by running:')
  63. print(' {} {}'.format(
  64. pretty_path(sys.argv[0]),
  65. link['timestamp'],
  66. ))
  67. if not isinstance(e, KeyboardInterrupt):
  68. raise e
  69. raise SystemExit(1)
  70. def archive_link(link_dir, link, overwrite=True):
  71. """download the DOM, PDF, and a screenshot into a folder named after the link's timestamp"""
  72. update_existing = os.path.exists(link_dir)
  73. if update_existing:
  74. link = {
  75. **parse_json_link_index(link_dir),
  76. **link,
  77. }
  78. else:
  79. os.makedirs(link_dir)
  80. log_link_archive(link_dir, link, update_existing)
  81. if FETCH_FAVICON:
  82. link = fetch_favicon(link_dir, link, overwrite=overwrite)
  83. if FETCH_WGET:
  84. link = fetch_wget(link_dir, link, overwrite=overwrite)
  85. if FETCH_PDF:
  86. link = fetch_pdf(link_dir, link, overwrite=overwrite)
  87. if FETCH_SCREENSHOT:
  88. link = fetch_screenshot(link_dir, link, overwrite=overwrite)
  89. if FETCH_DOM:
  90. link = fetch_dom(link_dir, link, overwrite=overwrite)
  91. if FETCH_WARC:
  92. link = fetch_warc(link_dir, link, overwrite=overwrite)
  93. if SUBMIT_ARCHIVE_DOT_ORG:
  94. link = archive_dot_org(link_dir, link, overwrite=overwrite)
  95. # if FETCH_AUDIO:
  96. # link = fetch_audio(link_dir, link, overwrite=overwrite)
  97. # if FETCH_VIDEO:
  98. # link = fetch_video(link_dir, link, overwrite=overwrite)
  99. if FETCH_GIT:
  100. link = fetch_git(link_dir, link, overwrite=overwrite)
  101. if FETCH_MEDIA:
  102. link = fetch_media(link_dir, link, overwrite=overwrite)
  103. write_link_index(link_dir, link)
  104. # print()
  105. return link
  106. def log_link_archive(link_dir, link, update_existing):
  107. print('[{symbol_color}{symbol}{reset}] [{now}] "{title}"\n {blue}{url}{reset}'.format(
  108. symbol='*' if update_existing else '+',
  109. symbol_color=ANSI['black' if update_existing else 'green'],
  110. now=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  111. **link,
  112. **ANSI,
  113. ))
  114. print(' > {}{}'.format(pretty_path(link_dir), '' if update_existing else ' (new)'))
  115. if link['type']:
  116. print(' i {}'.format(link['type']))
  117. def attach_result_to_link(method):
  118. """
  119. Instead of returning a result={output:'...', status:'success'} object,
  120. attach that result to the links's history & latest fields, then return
  121. the updated link object.
  122. """
  123. def decorator(fetch_func):
  124. @wraps(fetch_func)
  125. def timed_fetch_func(link_dir, link, overwrite=False, **kwargs):
  126. # initialize methods and history json field on link
  127. link['latest'] = link.get('latest') or {}
  128. link['latest'][method] = link['latest'].get(method) or None
  129. link['history'] = link.get('history') or {}
  130. link['history'][method] = link['history'].get(method) or []
  131. start_ts = datetime.now().timestamp()
  132. # if a valid method output is already present, dont run the fetch function
  133. if link['latest'][method] and not overwrite:
  134. print(' √ {}'.format(method))
  135. result = None
  136. else:
  137. print(' > {}'.format(method))
  138. result = fetch_func(link_dir, link, **kwargs)
  139. end_ts = datetime.now().timestamp()
  140. duration = str(end_ts * 1000 - start_ts * 1000).split('.')[0]
  141. # append a history item recording fail/success
  142. history_entry = {
  143. 'timestamp': str(start_ts).split('.')[0],
  144. }
  145. if result is None:
  146. history_entry['status'] = 'skipped'
  147. elif isinstance(result.get('output'), Exception):
  148. history_entry['status'] = 'failed'
  149. history_entry['duration'] = duration
  150. history_entry.update(result or {})
  151. link['history'][method].append(history_entry)
  152. else:
  153. history_entry['status'] = 'succeded'
  154. history_entry['duration'] = duration
  155. history_entry.update(result or {})
  156. link['history'][method].append(history_entry)
  157. link['latest'][method] = result['output']
  158. _RESULTS_TOTALS[history_entry['status']] += 1
  159. return link
  160. return timed_fetch_func
  161. return decorator
  162. @attach_result_to_link('wget')
  163. def fetch_wget(link_dir, link, requisites=FETCH_WGET_REQUISITES, timeout=TIMEOUT):
  164. """download full site using wget"""
  165. domain_dir = os.path.join(link_dir, link['domain'])
  166. existing_file = wget_output_path(link)
  167. if os.path.exists(domain_dir) and existing_file:
  168. return {'output': existing_file, 'status': 'skipped'}
  169. CMD = [
  170. # WGET CLI Docs: https://www.gnu.org/software/wget/manual/wget.html
  171. 'wget',
  172. # '--server-response',
  173. '--no-verbose',
  174. '--timestamping',
  175. '--adjust-extension',
  176. '--convert-links',
  177. '--force-directories',
  178. '--backup-converted',
  179. '--span-hosts',
  180. '--no-parent',
  181. '--restrict-file-names=unix',
  182. *(('--page-requisites',) if FETCH_WGET_REQUISITES else ()),
  183. *(('--user-agent="{}"'.format(WGET_USER_AGENT),) if WGET_USER_AGENT else ()),
  184. *((() if CHECK_SSL_VALIDITY else ('--no-check-certificate',))),
  185. link['url'],
  186. ]
  187. end = progress(timeout, prefix=' ')
  188. try:
  189. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout + 1) # index.html
  190. end()
  191. output = wget_output_path(link, look_in=domain_dir)
  192. # Check for common failure cases
  193. if result.returncode > 0:
  194. print(' got wget response code {}:'.format(result.returncode))
  195. if result.returncode != 8:
  196. print('\n'.join(' ' + line for line in (result.stderr or result.stdout).decode().rsplit('\n', 10)[-10:] if line.strip()))
  197. if b'403: Forbidden' in result.stderr:
  198. raise Exception('403 Forbidden (try changing WGET_USER_AGENT)')
  199. if b'404: Not Found' in result.stderr:
  200. raise Exception('404 Not Found')
  201. if b'ERROR 500: Internal Server Error' in result.stderr:
  202. raise Exception('500 Internal Server Error')
  203. if result.returncode == 4:
  204. raise Exception('Failed wget download')
  205. except Exception as e:
  206. end()
  207. print(' Run to see full output:', 'cd {}; {}'.format(link_dir, ' '.join(CMD)))
  208. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  209. output = e
  210. return {
  211. 'cmd': CMD,
  212. 'output': output,
  213. }
  214. @attach_result_to_link('pdf')
  215. def fetch_pdf(link_dir, link, timeout=TIMEOUT, user_data_dir=CHROME_USER_DATA_DIR):
  216. """print PDF of site to file using chrome --headless"""
  217. if link['type'] in ('PDF', 'image'):
  218. return {'output': wget_output_path(link)}
  219. if os.path.exists(os.path.join(link_dir, 'output.pdf')):
  220. return {'output': 'output.pdf', 'status': 'skipped'}
  221. CMD = [
  222. *chrome_headless(user_data_dir=user_data_dir),
  223. '--print-to-pdf',
  224. link['url']
  225. ]
  226. end = progress(timeout, prefix=' ')
  227. try:
  228. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout + 1) # output.pdf
  229. end()
  230. if result.returncode:
  231. print(' ', (result.stderr or result.stdout).decode())
  232. raise Exception('Failed to print PDF')
  233. chmod_file('output.pdf', cwd=link_dir)
  234. output = 'output.pdf'
  235. except Exception as e:
  236. end()
  237. print(' Run to see full output:', 'cd {}; {}'.format(link_dir, ' '.join(CMD)))
  238. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  239. output = e
  240. return {
  241. 'cmd': CMD,
  242. 'output': output,
  243. }
  244. @attach_result_to_link('screenshot')
  245. def fetch_screenshot(link_dir, link, timeout=TIMEOUT, user_data_dir=CHROME_USER_DATA_DIR, resolution=RESOLUTION):
  246. """take screenshot of site using chrome --headless"""
  247. if link['type'] in ('PDF', 'image'):
  248. return {'output': wget_output_path(link)}
  249. if os.path.exists(os.path.join(link_dir, 'screenshot.png')):
  250. return {'output': 'screenshot.png', 'status': 'skipped'}
  251. CMD = [
  252. *chrome_headless(user_data_dir=user_data_dir),
  253. '--screenshot',
  254. '--window-size={}'.format(resolution),
  255. '--hide-scrollbars',
  256. # '--full-page', # TODO: make this actually work using ./bin/screenshot fullPage: true
  257. link['url'],
  258. ]
  259. end = progress(timeout, prefix=' ')
  260. try:
  261. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout + 1) # sreenshot.png
  262. end()
  263. if result.returncode:
  264. print(' ', (result.stderr or result.stdout).decode())
  265. raise Exception('Failed to take screenshot')
  266. chmod_file('screenshot.png', cwd=link_dir)
  267. output = 'screenshot.png'
  268. except Exception as e:
  269. end()
  270. print(' Run to see full output:', 'cd {}; {}'.format(link_dir, ' '.join(CMD)))
  271. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  272. output = e
  273. return {
  274. 'cmd': CMD,
  275. 'output': output,
  276. }
  277. @attach_result_to_link('dom')
  278. def fetch_dom(link_dir, link, timeout=TIMEOUT, user_data_dir=CHROME_USER_DATA_DIR):
  279. """print HTML of site to file using chrome --dump-html"""
  280. if link['type'] in ('PDF', 'image'):
  281. return {'output': wget_output_path(link)}
  282. output_path = os.path.join(link_dir, 'output.html')
  283. if os.path.exists(output_path):
  284. return {'output': 'output.html', 'status': 'skipped'}
  285. CMD = [
  286. *chrome_headless(user_data_dir=user_data_dir),
  287. '--dump-dom',
  288. link['url']
  289. ]
  290. end = progress(timeout, prefix=' ')
  291. try:
  292. with open(output_path, 'w+') as f:
  293. result = run(CMD, stdout=f, stderr=PIPE, cwd=link_dir, timeout=timeout + 1) # output.html
  294. end()
  295. if result.returncode:
  296. print(' ', (result.stderr).decode())
  297. raise Exception('Failed to fetch DOM')
  298. chmod_file('output.html', cwd=link_dir)
  299. output = 'output.html'
  300. except Exception as e:
  301. end()
  302. print(' Run to see full output:', 'cd {}; {}'.format(link_dir, ' '.join(CMD)))
  303. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  304. output = e
  305. return {
  306. 'cmd': CMD,
  307. 'output': output,
  308. }
  309. @attach_result_to_link('archive_org')
  310. def archive_dot_org(link_dir, link, timeout=TIMEOUT):
  311. """submit site to archive.org for archiving via their service, save returned archive url"""
  312. path = os.path.join(link_dir, 'archive.org.txt')
  313. if os.path.exists(path):
  314. archive_org_url = open(path, 'r').read().strip()
  315. return {'output': archive_org_url, 'status': 'skipped'}
  316. submit_url = 'https://web.archive.org/save/{}'.format(link['url'])
  317. success = False
  318. CMD = ['curl', '-L', '-I', '-X', 'GET', submit_url]
  319. end = progress(timeout, prefix=' ')
  320. try:
  321. result = run(CMD, stdout=PIPE, stderr=DEVNULL, cwd=link_dir, timeout=timeout + 1) # archive.org.txt
  322. end()
  323. # Parse archive.org response headers
  324. headers = defaultdict(list)
  325. # lowercase all the header names and store in dict
  326. for header in result.stdout.splitlines():
  327. if b':' not in header or not header.strip():
  328. continue
  329. name, val = header.decode().split(':', 1)
  330. headers[name.lower().strip()].append(val.strip())
  331. # Get successful archive url in "content-location" header or any errors
  332. content_location = headers['content-location']
  333. errors = headers['x-archive-wayback-runtime-error']
  334. if content_location:
  335. saved_url = 'https://web.archive.org{}'.format(content_location[0])
  336. success = True
  337. elif len(errors) == 1 and 'RobotAccessControlException' in errors[0]:
  338. output = submit_url
  339. # raise Exception('Archive.org denied by {}/robots.txt'.format(link['domain']))
  340. elif errors:
  341. raise Exception(', '.join(errors))
  342. else:
  343. raise Exception('Failed to find "content-location" URL header in Archive.org response.')
  344. except Exception as e:
  345. end()
  346. print(' Visit url to see output:', ' '.join(CMD))
  347. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  348. output = e
  349. if success:
  350. with open(os.path.join(link_dir, 'archive.org.txt'), 'w', encoding='utf-8') as f:
  351. f.write(saved_url)
  352. chmod_file('archive.org.txt', cwd=link_dir)
  353. output = saved_url
  354. return {
  355. 'cmd': CMD,
  356. 'output': output,
  357. }
  358. @attach_result_to_link('favicon')
  359. def fetch_favicon(link_dir, link, timeout=TIMEOUT):
  360. """download site favicon from google's favicon api"""
  361. if os.path.exists(os.path.join(link_dir, 'favicon.ico')):
  362. return {'output': 'favicon.ico', 'status': 'skipped'}
  363. CMD = ['curl', 'https://www.google.com/s2/favicons?domain={domain}'.format(**link)]
  364. fout = open('{}/favicon.ico'.format(link_dir), 'w')
  365. end = progress(timeout, prefix=' ')
  366. try:
  367. run(CMD, stdout=fout, stderr=DEVNULL, cwd=link_dir, timeout=timeout + 1) # favicon.ico
  368. fout.close()
  369. end()
  370. chmod_file('favicon.ico', cwd=link_dir)
  371. output = 'favicon.ico'
  372. except Exception as e:
  373. fout.close()
  374. end()
  375. print(' Run to see full output:', ' '.join(CMD))
  376. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  377. output = e
  378. return {
  379. 'cmd': CMD,
  380. 'output': output,
  381. }
  382. @attach_result_to_link('media')
  383. def fetch_media(link_dir, link, timeout=MEDIA_TIMEOUT, overwrite=False):
  384. """Download playlists or individual video, audio, and subtitles using youtube-dl"""
  385. # import ipdb; ipdb.set_trace()
  386. output = os.path.join(link_dir, 'media')
  387. already_done = os.path.exists(output) and os.listdir(output)
  388. if already_done and not overwrite:
  389. return {'output': 'media', 'status': 'skipped'}
  390. os.makedirs(output, exist_ok=True)
  391. CMD = [
  392. 'youtube-dl',
  393. '--write-description',
  394. '--write-info-json',
  395. '--write-annotations',
  396. '--yes-playlist',
  397. '--write-thumbnail',
  398. '--no-call-home',
  399. '--no-check-certificate',
  400. '--user-agent',
  401. '--all-subs',
  402. '-x',
  403. '-k',
  404. '--audio-format', 'mp3',
  405. '--audio-quality', '320K',
  406. '--embed-thumbnail',
  407. '--add-metadata',
  408. link['url'],
  409. ]
  410. end = progress(timeout, prefix=' ')
  411. try:
  412. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=output, timeout=timeout + 1) # audio/audio.mp3
  413. end()
  414. if result.returncode:
  415. if b'ERROR: Unsupported URL' in result.stderr:
  416. pass
  417. else:
  418. print(' got youtubedl response code {}:'.format(result.returncode))
  419. print(result.stderr)
  420. raise Exception('Failed to download media')
  421. except Exception as e:
  422. end()
  423. print(' Run to see full output:', 'cd {}; {}'.format(link_dir, ' '.join(CMD)))
  424. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  425. output = e
  426. return {
  427. 'cmd': CMD,
  428. 'output': output,
  429. }
  430. @attach_result_to_link('git')
  431. def fetch_git(link_dir, link, timeout=TIMEOUT):
  432. """download full site using git"""
  433. if not (link['domain'] in GIT_DOMAINS
  434. or link['url'].endswith('.git')
  435. or link['type'] == 'git'):
  436. return
  437. if os.path.exists(os.path.join(link_dir, 'git')):
  438. return {'output': 'git', 'status': 'skipped'}
  439. CMD = ['git', 'clone', '--recursive', link['url'], 'git']
  440. output = 'git'
  441. end = progress(timeout, prefix=' ')
  442. try:
  443. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout + 1) # git/<reponame>
  444. end()
  445. if result.returncode > 0:
  446. print(' got git response code {}:'.format(result.returncode))
  447. raise Exception('Failed git download')
  448. except Exception as e:
  449. end()
  450. print(' Run to see full output:', 'cd {}; {}'.format(link_dir, ' '.join(CMD)))
  451. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  452. output = e
  453. return {
  454. 'cmd': CMD,
  455. 'output': output,
  456. }
  457. @attach_result_to_link('warc')
  458. def fetch_warc(link_dir, link, timeout=TIMEOUT):
  459. """download full site using wget's warc saving feature"""
  460. output = os.path.join(link_dir, 'warc')
  461. if os.path.exists(output) and os.listdir(output):
  462. return {'output': 'warc', 'status': 'skipped'}
  463. os.makedirs(output, exist_ok=True)
  464. CMD = [
  465. 'wget',
  466. '--warc-file={}'.format(int(datetime.now().timestamp())),
  467. *(('--user-agent="{}"'.format(WGET_USER_AGENT),) if WGET_USER_AGENT else ()),
  468. *((() if CHECK_SSL_VALIDITY else ('--no-check-certificate',))),
  469. link['url'],
  470. ]
  471. end = progress(timeout, prefix=' ')
  472. try:
  473. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=output, timeout=timeout + 1) # warc/at-00000.warc.gz
  474. end()
  475. # Check for common failure cases
  476. if result.returncode > 0:
  477. print(' got wget response code {}:'.format(result.returncode))
  478. if result.returncode != 8:
  479. print('\n'.join(' ' + line for line in (result.stderr or result.stdout).decode().rsplit('\n', 10)[-10:] if line.strip()))
  480. if b'403: Forbidden' in result.stderr:
  481. raise Exception('403 Forbidden (try changing WGET_USER_AGENT)')
  482. if b'404: Not Found' in result.stderr:
  483. raise Exception('404 Not Found')
  484. if b'ERROR 500: Internal Server Error' in result.stderr:
  485. raise Exception('500 Internal Server Error')
  486. if result.returncode == 4:
  487. raise Exception('Failed warc download')
  488. except Exception as e:
  489. end()
  490. print(' Run to see full output:', 'cd {}; {}'.format(link_dir, ' '.join(CMD)))
  491. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  492. output = e
  493. return {
  494. 'cmd': CMD,
  495. 'output': output,
  496. }
  497. def chrome_headless(binary=CHROME_BINARY, user_data_dir=CHROME_USER_DATA_DIR):
  498. args = [binary, '--headless'] # '--disable-gpu'
  499. if not CHROME_SANDBOX:
  500. args.append('--no-sandbox')
  501. default_profile = os.path.expanduser('~/Library/Application Support/Google/Chrome/Default')
  502. if user_data_dir:
  503. args.append('--user-data-dir={}'.format(user_data_dir))
  504. elif os.path.exists(default_profile):
  505. args.append('--user-data-dir={}'.format(default_profile))
  506. return args