archive_methods.py 21 KB

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