archive_methods.py 19 KB

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