archive_methods.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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_FAVICON,
  13. FETCH_TITLE,
  14. FETCH_WGET,
  15. FETCH_WGET_REQUISITES,
  16. FETCH_PDF,
  17. FETCH_SCREENSHOT,
  18. FETCH_DOM,
  19. FETCH_WARC,
  20. FETCH_GIT,
  21. FETCH_MEDIA,
  22. RESOLUTION,
  23. CHECK_SSL_VALIDITY,
  24. SUBMIT_ARCHIVE_DOT_ORG,
  25. WGET_USER_AGENT,
  26. CHROME_USER_DATA_DIR,
  27. CHROME_SANDBOX,
  28. TIMEOUT,
  29. MEDIA_TIMEOUT,
  30. ANSI,
  31. ARCHIVE_DIR,
  32. GIT_DOMAINS,
  33. GIT_SHA,
  34. )
  35. from util import (
  36. check_dependencies,
  37. fetch_page_title,
  38. progress,
  39. chmod_file,
  40. pretty_path,
  41. run, PIPE, DEVNULL
  42. )
  43. _RESULTS_TOTALS = { # globals are bad, mmkay
  44. 'skipped': 0,
  45. 'succeded': 0,
  46. 'failed': 0,
  47. }
  48. def archive_links(archive_path, links, source=None, resume=None):
  49. check_dependencies()
  50. to_archive = Peekable(links_after_timestamp(links, resume))
  51. idx, link = 0, to_archive.peek(0)
  52. try:
  53. for idx, link in enumerate(to_archive):
  54. link_dir = os.path.join(ARCHIVE_DIR, link['timestamp'])
  55. archive_link(link_dir, link)
  56. except (KeyboardInterrupt, SystemExit, Exception) as e:
  57. print('{lightyellow}[X] [{now}] Downloading paused on link {timestamp} ({idx}/{total}){reset}'.format(
  58. **ANSI,
  59. now=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  60. idx=idx+1,
  61. timestamp=link['timestamp'],
  62. total=len(links),
  63. ))
  64. print(' Continue where you left off by running:')
  65. print(' {} {}'.format(
  66. pretty_path(sys.argv[0]),
  67. link['timestamp'],
  68. ))
  69. if not isinstance(e, KeyboardInterrupt):
  70. raise e
  71. raise SystemExit(1)
  72. def archive_link(link_dir, link, overwrite=True):
  73. """download the DOM, PDF, and a screenshot into a folder named after the link's timestamp"""
  74. try:
  75. update_existing = os.path.exists(link_dir)
  76. if update_existing:
  77. link = {
  78. **parse_json_link_index(link_dir),
  79. **link,
  80. }
  81. else:
  82. os.makedirs(link_dir)
  83. log_link_archive(link_dir, link, update_existing)
  84. if FETCH_FAVICON:
  85. link = fetch_favicon(link_dir, link, overwrite=overwrite)
  86. if FETCH_TITLE:
  87. link = fetch_title(link_dir, link, overwrite=overwrite)
  88. if FETCH_WGET:
  89. link = fetch_wget(link_dir, link, overwrite=overwrite)
  90. if FETCH_PDF:
  91. link = fetch_pdf(link_dir, link, overwrite=overwrite)
  92. if FETCH_SCREENSHOT:
  93. link = fetch_screenshot(link_dir, link, overwrite=overwrite)
  94. if FETCH_DOM:
  95. link = fetch_dom(link_dir, link, overwrite=overwrite)
  96. if SUBMIT_ARCHIVE_DOT_ORG:
  97. link = archive_dot_org(link_dir, link, overwrite=overwrite)
  98. if FETCH_GIT:
  99. link = fetch_git(link_dir, link, overwrite=overwrite)
  100. if FETCH_MEDIA:
  101. link = fetch_media(link_dir, link, overwrite=overwrite)
  102. write_link_index(link_dir, link)
  103. except Exception as err:
  104. print(' ! Failed to archive link: {}: {}'.format(err.__class__.__name__, err))
  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, 'title': link['title'] or link['url']},
  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, warc=FETCH_WARC, 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. if warc:
  170. warc_dir = os.path.join(link_dir, 'warc')
  171. os.makedirs(warc_dir, exist_ok=True)
  172. warc_path = os.path.join('warc', str(int(datetime.now().timestamp())))
  173. # WGET CLI Docs: https://www.gnu.org/software/wget/manual/wget.html
  174. CMD = [
  175. 'wget',
  176. # '--server-response', # print headers for better error parsing
  177. '--no-verbose',
  178. '--adjust-extension',
  179. '--convert-links',
  180. '--force-directories',
  181. '--backup-converted',
  182. '--span-hosts',
  183. '--no-parent',
  184. '-e', 'robots=off',
  185. '--restrict-file-names=unix',
  186. '--timeout={}'.format(timeout),
  187. *(() if warc else ('--timestamping',)),
  188. *(('--warc-file={}'.format(warc_path),) if warc else ()),
  189. *(('--page-requisites',) if FETCH_WGET_REQUISITES else ()),
  190. *(('--user-agent={}'.format(WGET_USER_AGENT),) if WGET_USER_AGENT else ()),
  191. *((() if CHECK_SSL_VALIDITY else ('--no-check-certificate', '--no-hsts'))),
  192. link['url'],
  193. ]
  194. end = progress(timeout, prefix=' ')
  195. try:
  196. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout) # index.html
  197. end()
  198. output = wget_output_path(link, look_in=domain_dir)
  199. output_tail = [' ' + line for line in (result.stdout + result.stderr).decode().rsplit('\n', 3)[-3:] if line.strip()]
  200. # parse out number of files downloaded from "Downloaded: 76 files, 4.0M in 1.6s (2.52 MB/s)"
  201. files_downloaded = (
  202. int(output_tail[-1].strip().split(' ', 2)[1] or 0)
  203. if 'Downloaded:' in output_tail[-1]
  204. else 0
  205. )
  206. # Check for common failure cases
  207. if result.returncode > 0 and files_downloaded < 1:
  208. print(' Got wget response code {}:'.format(result.returncode))
  209. print('\n'.join(output_tail))
  210. if b'403: Forbidden' in result.stderr:
  211. raise Exception('403 Forbidden (try changing WGET_USER_AGENT)')
  212. if b'404: Not Found' in result.stderr:
  213. raise Exception('404 Not Found')
  214. if b'ERROR 500: Internal Server Error' in result.stderr:
  215. raise Exception('500 Internal Server Error')
  216. raise Exception('Got an error from the server')
  217. except Exception as e:
  218. end()
  219. print(' {}Some resources were skipped: {}{}'.format(ANSI['lightyellow'], e, ANSI['reset']))
  220. print(' Run to see full output:')
  221. print(' cd {};'.format(link_dir))
  222. print(' {}'.format(' '.join(CMD).replace(WGET_USER_AGENT, '"{}"'.format(WGET_USER_AGENT))))
  223. output = e
  224. return {
  225. 'cmd': CMD,
  226. 'output': output,
  227. }
  228. @attach_result_to_link('pdf')
  229. def fetch_pdf(link_dir, link, timeout=TIMEOUT, user_data_dir=CHROME_USER_DATA_DIR):
  230. """print PDF of site to file using chrome --headless"""
  231. if link['type'] in ('PDF', 'image'):
  232. return {'output': wget_output_path(link)}
  233. if os.path.exists(os.path.join(link_dir, 'output.pdf')):
  234. return {'output': 'output.pdf', 'status': 'skipped'}
  235. CMD = [
  236. *chrome_headless(user_data_dir=user_data_dir),
  237. '--print-to-pdf',
  238. '--hide-scrollbars',
  239. '--timeout={}'.format((timeout) * 1000),
  240. *(() if CHECK_SSL_VALIDITY else ('--disable-web-security', '--ignore-certificate-errors')),
  241. link['url']
  242. ]
  243. end = progress(timeout, prefix=' ')
  244. try:
  245. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout) # output.pdf
  246. end()
  247. if result.returncode:
  248. print(' ', (result.stderr or result.stdout).decode())
  249. raise Exception('Failed to print PDF')
  250. chmod_file('output.pdf', cwd=link_dir)
  251. output = 'output.pdf'
  252. except Exception as e:
  253. end()
  254. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  255. print(' Run to see full output:')
  256. print(' cd {};'.format(link_dir))
  257. print(' {}'.format(' '.join(CMD)))
  258. output = e
  259. return {
  260. 'cmd': CMD,
  261. 'output': output,
  262. }
  263. @attach_result_to_link('screenshot')
  264. def fetch_screenshot(link_dir, link, timeout=TIMEOUT, user_data_dir=CHROME_USER_DATA_DIR, resolution=RESOLUTION):
  265. """take screenshot of site using chrome --headless"""
  266. if link['type'] in ('PDF', 'image'):
  267. return {'output': wget_output_path(link)}
  268. if os.path.exists(os.path.join(link_dir, 'screenshot.png')):
  269. return {'output': 'screenshot.png', 'status': 'skipped'}
  270. CMD = [
  271. *chrome_headless(user_data_dir=user_data_dir),
  272. '--screenshot',
  273. '--window-size={}'.format(resolution),
  274. '--hide-scrollbars',
  275. '--timeout={}'.format((timeout) * 1000),
  276. *(() if CHECK_SSL_VALIDITY else ('--disable-web-security', '--ignore-certificate-errors')),
  277. # '--full-page', # TODO: make this actually work using ./bin/screenshot fullPage: true
  278. link['url'],
  279. ]
  280. end = progress(timeout, prefix=' ')
  281. try:
  282. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout) # sreenshot.png
  283. end()
  284. if result.returncode:
  285. print(' ', (result.stderr or result.stdout).decode())
  286. raise Exception('Failed to take screenshot')
  287. chmod_file('screenshot.png', cwd=link_dir)
  288. output = 'screenshot.png'
  289. except Exception as e:
  290. end()
  291. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  292. print(' Run to see full output:')
  293. print(' cd {};'.format(link_dir))
  294. print(' {}'.format(' '.join(CMD)))
  295. output = e
  296. return {
  297. 'cmd': CMD,
  298. 'output': output,
  299. }
  300. @attach_result_to_link('dom')
  301. def fetch_dom(link_dir, link, timeout=TIMEOUT, user_data_dir=CHROME_USER_DATA_DIR):
  302. """print HTML of site to file using chrome --dump-html"""
  303. if link['type'] in ('PDF', 'image'):
  304. return {'output': wget_output_path(link)}
  305. output_path = os.path.join(link_dir, 'output.html')
  306. if os.path.exists(output_path):
  307. return {'output': 'output.html', 'status': 'skipped'}
  308. CMD = [
  309. *chrome_headless(user_data_dir=user_data_dir),
  310. '--dump-dom',
  311. '--timeout={}'.format((timeout) * 1000),
  312. link['url']
  313. ]
  314. end = progress(timeout, prefix=' ')
  315. try:
  316. with open(output_path, 'w+') as f:
  317. result = run(CMD, stdout=f, stderr=PIPE, cwd=link_dir, timeout=timeout) # output.html
  318. end()
  319. if result.returncode:
  320. print(' ', (result.stderr).decode())
  321. raise Exception('Failed to fetch DOM')
  322. chmod_file('output.html', cwd=link_dir)
  323. output = 'output.html'
  324. except Exception as e:
  325. end()
  326. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  327. print(' Run to see full output:')
  328. print(' cd {};'.format(link_dir))
  329. print(' {}'.format(' '.join(CMD)))
  330. output = e
  331. return {
  332. 'cmd': CMD,
  333. 'output': output,
  334. }
  335. @attach_result_to_link('archive_org')
  336. def archive_dot_org(link_dir, link, timeout=TIMEOUT):
  337. """submit site to archive.org for archiving via their service, save returned archive url"""
  338. path = os.path.join(link_dir, 'archive.org.txt')
  339. if os.path.exists(path):
  340. archive_org_url = open(path, 'r').read().strip()
  341. return {'output': archive_org_url, 'status': 'skipped'}
  342. submit_url = 'https://web.archive.org/save/{}'.format(link['url'])
  343. success = False
  344. CMD = [
  345. 'curl',
  346. '--location',
  347. '--head',
  348. '--user-agent', 'ArchiveBox/{} (+https://github.com/pirate/ArchiveBox/)'.format(GIT_SHA),
  349. '--max-time', str(timeout),
  350. '--get',
  351. *(() if CHECK_SSL_VALIDITY else ('--insecure',)),
  352. submit_url,
  353. ]
  354. end = progress(timeout, prefix=' ')
  355. try:
  356. result = run(CMD, stdout=PIPE, stderr=DEVNULL, cwd=link_dir, timeout=timeout) # archive.org.txt
  357. end()
  358. # Parse archive.org response headers
  359. headers = defaultdict(list)
  360. # lowercase all the header names and store in dict
  361. for header in result.stdout.splitlines():
  362. if b':' not in header or not header.strip():
  363. continue
  364. name, val = header.decode().split(':', 1)
  365. headers[name.lower().strip()].append(val.strip())
  366. # Get successful archive url in "content-location" header or any errors
  367. content_location = headers['content-location']
  368. errors = headers['x-archive-wayback-runtime-error']
  369. if content_location:
  370. saved_url = 'https://web.archive.org{}'.format(content_location[0])
  371. success = True
  372. elif len(errors) == 1 and 'RobotAccessControlException' in errors[0]:
  373. output = submit_url
  374. # raise Exception('Archive.org denied by {}/robots.txt'.format(link['domain']))
  375. elif errors:
  376. raise Exception(', '.join(errors))
  377. else:
  378. raise Exception('Failed to find "content-location" URL header in Archive.org response.')
  379. except Exception as e:
  380. end()
  381. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  382. print(' Run to see full output:')
  383. print(' {}'.format(' '.join(CMD)))
  384. output = e
  385. if success:
  386. with open(os.path.join(link_dir, 'archive.org.txt'), 'w', encoding='utf-8') as f:
  387. f.write(saved_url)
  388. chmod_file('archive.org.txt', cwd=link_dir)
  389. output = saved_url
  390. return {
  391. 'cmd': CMD,
  392. 'output': output,
  393. }
  394. @attach_result_to_link('favicon')
  395. def fetch_favicon(link_dir, link, timeout=TIMEOUT):
  396. """download site favicon from google's favicon api"""
  397. if os.path.exists(os.path.join(link_dir, 'favicon.ico')):
  398. return {'output': 'favicon.ico', 'status': 'skipped'}
  399. CMD = [
  400. 'curl',
  401. '--max-time', str(timeout),
  402. 'https://www.google.com/s2/favicons?domain={domain}'.format(**link),
  403. ]
  404. fout = open('{}/favicon.ico'.format(link_dir), 'w')
  405. end = progress(timeout, prefix=' ')
  406. try:
  407. run(CMD, stdout=fout, stderr=DEVNULL, cwd=link_dir, timeout=timeout) # favicon.ico
  408. fout.close()
  409. end()
  410. chmod_file('favicon.ico', cwd=link_dir)
  411. output = 'favicon.ico'
  412. except Exception as e:
  413. fout.close()
  414. end()
  415. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  416. print(' Run to see full output:')
  417. print(' {}'.format(' '.join(CMD)))
  418. output = e
  419. return {
  420. 'cmd': CMD,
  421. 'output': output,
  422. }
  423. @attach_result_to_link('title')
  424. def fetch_title(link_dir, link, timeout=TIMEOUT):
  425. """try to guess the page's title from its content"""
  426. # if link already has valid title, skip it
  427. if link['title'] and not link['title'].lower().startswith('http'):
  428. return {'output': link['title'], 'cmd': 'fetch_page_title("{}")'.format(link['url'])}
  429. end = progress(timeout, prefix=' ')
  430. try:
  431. title = fetch_page_title(link['url'], timeout=timeout, progress=False)
  432. end()
  433. output = title
  434. except Exception as e:
  435. end()
  436. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  437. output = e
  438. return {
  439. 'cmd': 'fetch_page_title("{}")'.format(link['url']),
  440. 'output': output,
  441. }
  442. @attach_result_to_link('media')
  443. def fetch_media(link_dir, link, timeout=MEDIA_TIMEOUT, overwrite=False):
  444. """Download playlists or individual video, audio, and subtitles using youtube-dl"""
  445. # import ipdb; ipdb.set_trace()
  446. output = os.path.join(link_dir, 'media')
  447. already_done = os.path.exists(output) # and os.listdir(output)
  448. if already_done and not overwrite:
  449. return {'output': 'media', 'status': 'skipped'}
  450. os.makedirs(output, exist_ok=True)
  451. CMD = [
  452. 'youtube-dl',
  453. '--write-description',
  454. '--write-info-json',
  455. '--write-annotations',
  456. '--yes-playlist',
  457. '--write-thumbnail',
  458. '--no-call-home',
  459. '--no-check-certificate',
  460. '--user-agent',
  461. '--all-subs',
  462. '-x',
  463. '-k',
  464. '--audio-format', 'mp3',
  465. '--audio-quality', '320K',
  466. '--embed-thumbnail',
  467. '--add-metadata',
  468. link['url'],
  469. ]
  470. end = progress(timeout, prefix=' ')
  471. try:
  472. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=output, timeout=timeout + 1) # audio/audio.mp3
  473. chmod_file('media', cwd=link_dir)
  474. output = 'media'
  475. end()
  476. if result.returncode:
  477. if (b'ERROR: Unsupported URL' in result.stderr
  478. or b'HTTP Error 404' in result.stderr
  479. or b'HTTP Error 403' in result.stderr
  480. or b'URL could be a direct video link' in result.stderr
  481. or b'Unable to extract container ID' in result.stderr):
  482. # These happen too frequently on non-media pages to warrant printing to console
  483. pass
  484. else:
  485. print(' got youtubedl response code {}:'.format(result.returncode))
  486. print(result.stderr)
  487. raise Exception('Failed to download media')
  488. except Exception as e:
  489. end()
  490. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  491. print(' Run to see full output:')
  492. print(' cd {};'.format(link_dir))
  493. print(' {}'.format(' '.join(CMD)))
  494. output = e
  495. return {
  496. 'cmd': CMD,
  497. 'output': output,
  498. }
  499. @attach_result_to_link('git')
  500. def fetch_git(link_dir, link, timeout=TIMEOUT):
  501. """download full site using git"""
  502. if not (link['domain'] in GIT_DOMAINS
  503. or link['url'].endswith('.git')
  504. or link['type'] == 'git'):
  505. return
  506. if os.path.exists(os.path.join(link_dir, 'git')):
  507. return {'output': 'git', 'status': 'skipped'}
  508. CMD = ['git', 'clone', '--mirror', '--recursive', link['url'].split('#')[0], 'git']
  509. output = 'git'
  510. end = progress(timeout, prefix=' ')
  511. try:
  512. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout + 1) # git/<reponame>
  513. end()
  514. if result.returncode > 0:
  515. print(' got git response code {}:'.format(result.returncode))
  516. raise Exception('Failed git download')
  517. except Exception as e:
  518. end()
  519. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  520. print(' Run to see full output:')
  521. print(' cd {};'.format(link_dir))
  522. print(' {}'.format(' '.join(CMD)))
  523. output = e
  524. return {
  525. 'cmd': CMD,
  526. 'output': output,
  527. }
  528. def chrome_headless(binary=CHROME_BINARY, user_data_dir=CHROME_USER_DATA_DIR):
  529. args = [binary, '--headless'] # '--disable-gpu'
  530. if not CHROME_SANDBOX:
  531. args.append('--no-sandbox')
  532. default_profile = os.path.expanduser('~/Library/Application Support/Google/Chrome')
  533. if user_data_dir:
  534. args.append('--user-data-dir={}'.format(user_data_dir))
  535. elif os.path.exists(default_profile):
  536. args.append('--user-data-dir={}'.format(default_profile))
  537. return args