archive_methods.py 22 KB

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