archive_methods.py 20 KB

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