archive_methods.py 19 KB

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