archive_methods.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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 -N -E -np -x -H -k -K -S --restrict-file-names=unix'.split(' '),
  172. *(('-p',) if FETCH_WGET_REQUISITES else ()),
  173. *(('--user-agent={}'.format(WGET_USER_AGENT),) if WGET_USER_AGENT else ()),
  174. *((() if CHECK_SSL_VALIDITY else ('--no-check-certificate',))),
  175. link['url'],
  176. ]
  177. end = progress(timeout, prefix=' ')
  178. try:
  179. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout + 1) # index.html
  180. end()
  181. output = wget_output_path(link, look_in=domain_dir)
  182. # Check for common failure cases
  183. if result.returncode > 0:
  184. print(' got wget response code {}:'.format(result.returncode))
  185. if result.returncode != 8:
  186. print('\n'.join(' ' + line for line in (result.stderr or result.stdout).decode().rsplit('\n', 10)[-10:] if line.strip()))
  187. if b'403: Forbidden' in result.stderr:
  188. raise Exception('403 Forbidden (try changing WGET_USER_AGENT)')
  189. if b'404: Not Found' in result.stderr:
  190. raise Exception('404 Not Found')
  191. if b'ERROR 500: Internal Server Error' in result.stderr:
  192. raise Exception('500 Internal Server Error')
  193. if result.returncode == 4:
  194. raise Exception('Failed wget download')
  195. except Exception as e:
  196. end()
  197. print(' Run to see full output:', 'cd {}; {}'.format(link_dir, ' '.join(CMD)))
  198. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  199. output = e
  200. return {
  201. 'cmd': CMD,
  202. 'output': output,
  203. }
  204. @attach_result_to_link('pdf')
  205. def fetch_pdf(link_dir, link, timeout=TIMEOUT, user_data_dir=CHROME_USER_DATA_DIR):
  206. """print PDF of site to file using chrome --headless"""
  207. if link['type'] in ('PDF', 'image'):
  208. return {'output': wget_output_path(link)}
  209. if os.path.exists(os.path.join(link_dir, 'output.pdf')):
  210. return {'output': 'output.pdf', 'status': 'skipped'}
  211. CMD = [
  212. *chrome_headless(user_data_dir=user_data_dir),
  213. '--print-to-pdf',
  214. link['url']
  215. ]
  216. end = progress(timeout, prefix=' ')
  217. try:
  218. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout + 1) # output.pdf
  219. end()
  220. if result.returncode:
  221. print(' ', (result.stderr or result.stdout).decode())
  222. raise Exception('Failed to print PDF')
  223. chmod_file('output.pdf', cwd=link_dir)
  224. output = 'output.pdf'
  225. except Exception as e:
  226. end()
  227. print(' Run to see full output:', 'cd {}; {}'.format(link_dir, ' '.join(CMD)))
  228. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  229. output = e
  230. return {
  231. 'cmd': CMD,
  232. 'output': output,
  233. }
  234. @attach_result_to_link('screenshot')
  235. def fetch_screenshot(link_dir, link, timeout=TIMEOUT, user_data_dir=CHROME_USER_DATA_DIR, resolution=RESOLUTION):
  236. """take screenshot of site using chrome --headless"""
  237. if link['type'] in ('PDF', 'image'):
  238. return {'output': wget_output_path(link)}
  239. if os.path.exists(os.path.join(link_dir, 'screenshot.png')):
  240. return {'output': 'screenshot.png', 'status': 'skipped'}
  241. CMD = [
  242. *chrome_headless(user_data_dir=user_data_dir),
  243. '--screenshot',
  244. '--window-size={}'.format(resolution),
  245. '--hide-scrollbars',
  246. # '--full-page', # TODO: make this actually work using ./bin/screenshot fullPage: true
  247. link['url'],
  248. ]
  249. end = progress(timeout, prefix=' ')
  250. try:
  251. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout + 1) # sreenshot.png
  252. end()
  253. if result.returncode:
  254. print(' ', (result.stderr or result.stdout).decode())
  255. raise Exception('Failed to take screenshot')
  256. chmod_file('screenshot.png', cwd=link_dir)
  257. output = 'screenshot.png'
  258. except Exception as e:
  259. end()
  260. print(' Run to see full output:', 'cd {}; {}'.format(link_dir, ' '.join(CMD)))
  261. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  262. output = e
  263. return {
  264. 'cmd': CMD,
  265. 'output': output,
  266. }
  267. @attach_result_to_link('dom')
  268. def fetch_dom(link_dir, link, timeout=TIMEOUT, user_data_dir=CHROME_USER_DATA_DIR):
  269. """print HTML of site to file using chrome --dump-html"""
  270. if link['type'] in ('PDF', 'image'):
  271. return {'output': wget_output_path(link)}
  272. output_path = os.path.join(link_dir, 'output.html')
  273. if os.path.exists(output_path):
  274. return {'output': 'output.html', 'status': 'skipped'}
  275. CMD = [
  276. *chrome_headless(user_data_dir=user_data_dir),
  277. '--dump-dom',
  278. link['url']
  279. ]
  280. end = progress(timeout, prefix=' ')
  281. try:
  282. with open(output_path, 'w+') as f:
  283. result = run(CMD, stdout=f, stderr=PIPE, cwd=link_dir, timeout=timeout + 1) # output.html
  284. end()
  285. if result.returncode:
  286. print(' ', (result.stderr).decode())
  287. raise Exception('Failed to fetch DOM')
  288. chmod_file('output.html', cwd=link_dir)
  289. output = 'output.html'
  290. except Exception as e:
  291. end()
  292. print(' Run to see full output:', 'cd {}; {}'.format(link_dir, ' '.join(CMD)))
  293. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  294. output = e
  295. return {
  296. 'cmd': CMD,
  297. 'output': output,
  298. }
  299. @attach_result_to_link('archive_org')
  300. def archive_dot_org(link_dir, link, timeout=TIMEOUT):
  301. """submit site to archive.org for archiving via their service, save returned archive url"""
  302. path = os.path.join(link_dir, 'archive.org.txt')
  303. if os.path.exists(path):
  304. archive_org_url = open(path, 'r').read().strip()
  305. return {'output': archive_org_url, 'status': 'skipped'}
  306. submit_url = 'https://web.archive.org/save/{}'.format(link['url'])
  307. success = False
  308. CMD = ['curl', '-L', '-I', '-X', 'GET', submit_url]
  309. end = progress(timeout, prefix=' ')
  310. try:
  311. result = run(CMD, stdout=PIPE, stderr=DEVNULL, cwd=link_dir, timeout=timeout + 1) # archive.org.txt
  312. end()
  313. # Parse archive.org response headers
  314. headers = defaultdict(list)
  315. # lowercase all the header names and store in dict
  316. for header in result.stdout.splitlines():
  317. if b':' not in header or not header.strip():
  318. continue
  319. name, val = header.decode().split(':', 1)
  320. headers[name.lower().strip()].append(val.strip())
  321. # Get successful archive url in "content-location" header or any errors
  322. content_location = headers['content-location']
  323. errors = headers['x-archive-wayback-runtime-error']
  324. if content_location:
  325. saved_url = 'https://web.archive.org{}'.format(content_location[0])
  326. success = True
  327. elif len(errors) == 1 and 'RobotAccessControlException' in errors[0]:
  328. output = submit_url
  329. # raise Exception('Archive.org denied by {}/robots.txt'.format(link['domain']))
  330. elif errors:
  331. raise Exception(', '.join(errors))
  332. else:
  333. raise Exception('Failed to find "content-location" URL header in Archive.org response.')
  334. except Exception as e:
  335. end()
  336. print(' Visit url to see output:', ' '.join(CMD))
  337. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  338. output = e
  339. if success:
  340. with open(os.path.join(link_dir, 'archive.org.txt'), 'w', encoding='utf-8') as f:
  341. f.write(saved_url)
  342. chmod_file('archive.org.txt', cwd=link_dir)
  343. output = saved_url
  344. return {
  345. 'cmd': CMD,
  346. 'output': output,
  347. }
  348. @attach_result_to_link('favicon')
  349. def fetch_favicon(link_dir, link, timeout=TIMEOUT):
  350. """download site favicon from google's favicon api"""
  351. if os.path.exists(os.path.join(link_dir, 'favicon.ico')):
  352. return {'output': 'favicon.ico', 'status': 'skipped'}
  353. CMD = ['curl', 'https://www.google.com/s2/favicons?domain={domain}'.format(**link)]
  354. fout = open('{}/favicon.ico'.format(link_dir), 'w')
  355. end = progress(timeout, prefix=' ')
  356. try:
  357. run(CMD, stdout=fout, stderr=DEVNULL, cwd=link_dir, timeout=timeout + 1) # favicon.ico
  358. fout.close()
  359. end()
  360. chmod_file('favicon.ico', cwd=link_dir)
  361. output = 'favicon.ico'
  362. except Exception as e:
  363. fout.close()
  364. end()
  365. print(' Run to see full output:', ' '.join(CMD))
  366. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  367. output = e
  368. return {
  369. 'cmd': CMD,
  370. 'output': output,
  371. }
  372. @attach_result_to_link('media')
  373. def fetch_media(link_dir, link, timeout=MEDIA_TIMEOUT, overwrite=False):
  374. """Download playlists or individual video, audio, and subtitles using youtube-dl"""
  375. # import ipdb; ipdb.set_trace()
  376. output = os.path.join(link_dir, 'media')
  377. already_done = os.path.exists(output) and os.listdir(output)
  378. if already_done and not overwrite:
  379. return {'output': 'media', 'status': 'skipped'}
  380. os.makedirs(output, exist_ok=True)
  381. CMD = [
  382. 'youtube-dl',
  383. '--write-description',
  384. '--write-info-json',
  385. '--write-annotations',
  386. '--yes-playlist',
  387. '--write-thumbnail',
  388. '--no-call-home',
  389. '--no-check-certificate',
  390. '--user-agent',
  391. '--all-subs',
  392. '-x',
  393. '-k',
  394. '--audio-format', 'mp3',
  395. '--audio-quality', '320K',
  396. '--embed-thumbnail',
  397. '--add-metadata',
  398. link['url'],
  399. ]
  400. end = progress(timeout, prefix=' ')
  401. try:
  402. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=output, timeout=timeout + 1) # audio/audio.mp3
  403. end()
  404. if result.returncode:
  405. if b'ERROR: Unsupported URL' in result.stderr:
  406. pass
  407. else:
  408. print(' got youtubedl response code {}:'.format(result.returncode))
  409. print(result.stderr)
  410. raise Exception('Failed to download media')
  411. except Exception as e:
  412. end()
  413. print(' Run to see full output:', 'cd {}; {}'.format(link_dir, ' '.join(CMD)))
  414. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  415. output = e
  416. return {
  417. 'cmd': CMD,
  418. 'output': output,
  419. }
  420. @attach_result_to_link('git')
  421. def fetch_git(link_dir, link, timeout=TIMEOUT):
  422. """download full site using git"""
  423. if not (link['domain'] in GIT_DOMAINS
  424. or link['url'].endswith('.git')
  425. or link['type'] == 'git'):
  426. return
  427. if os.path.exists(os.path.join(link_dir, 'git')):
  428. return {'output': 'git', 'status': 'skipped'}
  429. CMD = ['git', 'clone', '--recursive', link['url'], 'git']
  430. output = 'git'
  431. end = progress(timeout, prefix=' ')
  432. try:
  433. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout + 1) # git/<reponame>
  434. end()
  435. if result.returncode > 0:
  436. print(' got git response code {}:'.format(result.returncode))
  437. raise Exception('Failed git download')
  438. except Exception as e:
  439. end()
  440. print(' Run to see full output:', 'cd {}; {}'.format(link_dir, ' '.join(CMD)))
  441. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  442. output = e
  443. return {
  444. 'cmd': CMD,
  445. 'output': output,
  446. }
  447. @attach_result_to_link('warc')
  448. def fetch_warc(link_dir, link, timeout=TIMEOUT):
  449. """download full site using wget's warc saving feature"""
  450. output = os.path.join(link_dir, 'warc')
  451. if os.path.exists(output) and os.listdir(output):
  452. return {'output': 'warc', 'status': 'skipped'}
  453. os.makedirs(output, exist_ok=True)
  454. CMD = [
  455. 'wget',
  456. '--warc-file={}'.format(int(datetime.now().timestamp())),
  457. *(('--user-agent={}'.format(WGET_USER_AGENT),) if WGET_USER_AGENT else ()),
  458. *((() if CHECK_SSL_VALIDITY else ('--no-check-certificate',))),
  459. link['url'],
  460. ]
  461. end = progress(timeout, prefix=' ')
  462. try:
  463. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=output, timeout=timeout + 1) # warc/at-00000.warc.gz
  464. end()
  465. # Check for common failure cases
  466. if result.returncode > 0:
  467. print(' got wget response code {}:'.format(result.returncode))
  468. if result.returncode != 8:
  469. print('\n'.join(' ' + line for line in (result.stderr or result.stdout).decode().rsplit('\n', 10)[-10:] if line.strip()))
  470. if b'403: Forbidden' in result.stderr:
  471. raise Exception('403 Forbidden (try changing WGET_USER_AGENT)')
  472. if b'404: Not Found' in result.stderr:
  473. raise Exception('404 Not Found')
  474. if b'ERROR 500: Internal Server Error' in result.stderr:
  475. raise Exception('500 Internal Server Error')
  476. if result.returncode == 4:
  477. raise Exception('Failed warc download')
  478. except Exception as e:
  479. end()
  480. print(' Run to see full output:', 'cd {}; {}'.format(link_dir, ' '.join(CMD)))
  481. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  482. output = e
  483. return {
  484. 'cmd': CMD,
  485. 'output': output,
  486. }
  487. def chrome_headless(binary=CHROME_BINARY, user_data_dir=CHROME_USER_DATA_DIR):
  488. args = [binary, '--headless'] # '--disable-gpu'
  489. if not CHROME_SANDBOX:
  490. args.append('--no-sandbox')
  491. default_profile = os.path.expanduser('~/Library/Application Support/Google/Chrome/Default')
  492. if user_data_dir:
  493. args.append('--user-data-dir={}'.format(user_data_dir))
  494. elif os.path.exists(default_profile):
  495. args.append('--user-data-dir={}'.format(default_profile))
  496. return args