archive_methods.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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. patch_index_title_hack,
  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. HEADLESS_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. except Exception as err:
  95. print(' ! Failed to archive link: {}: {}'.format(err.__class__.__name__, err))
  96. return link
  97. def print_link_status_line(link_dir, link, is_new):
  98. print('[{symbol_color}{symbol}{reset}] [{now}] "{title}"\n {blue}{url}{reset}'.format(
  99. symbol='+' if is_new else '*',
  100. symbol_color=ANSI['green' if is_new else 'black'],
  101. now=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  102. **{**link, 'title': link['title'] or link['url']},
  103. **ANSI,
  104. ))
  105. print(' > {}{}'.format(pretty_path(link_dir), ' (new)' if is_new else ''))
  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, domain(link['url']))
  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_BINARY,
  167. # '--server-response', # print headers for better error parsing
  168. '--no-verbose',
  169. '--adjust-extension',
  170. '--convert-links',
  171. '--force-directories',
  172. '--backup-converted',
  173. '--span-hosts',
  174. '--no-parent',
  175. '-e', 'robots=off',
  176. '--restrict-file-names=unix',
  177. '--timeout={}'.format(timeout),
  178. *(() if warc else ('--timestamping',)),
  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. *(('--load-cookies', COOKIES_FILE) if COOKIES_FILE else ()),
  183. *((() if CHECK_SSL_VALIDITY else ('--no-check-certificate', '--no-hsts'))),
  184. link['url'],
  185. ]
  186. end = progress(timeout, prefix=' ')
  187. try:
  188. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  189. end()
  190. output = wget_output_path(link, look_in=domain_dir)
  191. output_tail = [' ' + line for line in (result.stdout + result.stderr).decode().rsplit('\n', 3)[-3:] if line.strip()]
  192. # parse out number of files downloaded from "Downloaded: 76 files, 4.0M in 1.6s (2.52 MB/s)"
  193. files_downloaded = (
  194. int(output_tail[-1].strip().split(' ', 2)[1] or 0)
  195. if 'Downloaded:' in output_tail[-1]
  196. else 0
  197. )
  198. # Check for common failure cases
  199. if result.returncode > 0 and files_downloaded < 1:
  200. print(' Got wget response code {}:'.format(result.returncode))
  201. print('\n'.join(output_tail))
  202. if b'403: Forbidden' in result.stderr:
  203. raise Exception('403 Forbidden (try changing WGET_USER_AGENT)')
  204. if b'404: Not Found' in result.stderr:
  205. raise Exception('404 Not Found')
  206. if b'ERROR 500: Internal Server Error' in result.stderr:
  207. raise Exception('500 Internal Server Error')
  208. raise Exception('Got an error from the server')
  209. except Exception as e:
  210. end()
  211. output = e
  212. print_error_hints(cmd=CMD, pwd=link_dir, err=e)
  213. return {
  214. 'cmd': CMD,
  215. 'output': output,
  216. }
  217. @attach_result_to_link('pdf')
  218. def fetch_pdf(link_dir, link, timeout=TIMEOUT, user_data_dir=CHROME_USER_DATA_DIR):
  219. """print PDF of site to file using chrome --headless"""
  220. if link['type'] in ('PDF', 'image'):
  221. return {'output': wget_output_path(link)}
  222. if os.path.exists(os.path.join(link_dir, 'output.pdf')):
  223. return {'output': 'output.pdf', 'status': 'skipped'}
  224. CMD = [
  225. *chrome_headless(user_data_dir=user_data_dir),
  226. '--print-to-pdf',
  227. '--hide-scrollbars',
  228. '--timeout={}'.format((timeout) * 1000),
  229. *(() if CHECK_SSL_VALIDITY else ('--disable-web-security', '--ignore-certificate-errors')),
  230. *(('--user-agent={}'.format(HEADLESS_USER_AGENT),) if HEADLESS_USER_AGENT else ()),
  231. link['url']
  232. ]
  233. end = progress(timeout, prefix=' ')
  234. try:
  235. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  236. end()
  237. if result.returncode:
  238. print(' ', (result.stderr or result.stdout).decode())
  239. raise Exception('Failed to print PDF')
  240. chmod_file('output.pdf', cwd=link_dir)
  241. output = 'output.pdf'
  242. except Exception as e:
  243. end()
  244. output = e
  245. print_error_hints(cmd=CMD, pwd=link_dir, err=e)
  246. return {
  247. 'cmd': CMD,
  248. 'output': output,
  249. }
  250. @attach_result_to_link('screenshot')
  251. def fetch_screenshot(link_dir, link, timeout=TIMEOUT, user_data_dir=CHROME_USER_DATA_DIR, resolution=RESOLUTION):
  252. """take screenshot of site using chrome --headless"""
  253. if link['type'] in ('PDF', 'image'):
  254. return {'output': wget_output_path(link)}
  255. if os.path.exists(os.path.join(link_dir, 'screenshot.png')):
  256. return {'output': 'screenshot.png', 'status': 'skipped'}
  257. CMD = [
  258. *chrome_headless(user_data_dir=user_data_dir),
  259. '--screenshot',
  260. '--window-size={}'.format(resolution),
  261. '--hide-scrollbars',
  262. '--timeout={}'.format((timeout) * 1000),
  263. *(() if CHECK_SSL_VALIDITY else ('--disable-web-security', '--ignore-certificate-errors')),
  264. *(('--user-agent={}'.format(HEADLESS_USER_AGENT),) if HEADLESS_USER_AGENT else ()),
  265. # '--full-page', # TODO: make this actually work using ./bin/screenshot fullPage: true
  266. link['url'],
  267. ]
  268. end = progress(timeout, prefix=' ')
  269. try:
  270. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  271. end()
  272. if result.returncode:
  273. print(' ', (result.stderr or result.stdout).decode())
  274. raise Exception('Failed to take screenshot')
  275. chmod_file('screenshot.png', cwd=link_dir)
  276. output = 'screenshot.png'
  277. except Exception as e:
  278. end()
  279. output = e
  280. print_error_hints(cmd=CMD, pwd=link_dir, err=e)
  281. return {
  282. 'cmd': CMD,
  283. 'output': output,
  284. }
  285. @attach_result_to_link('dom')
  286. def fetch_dom(link_dir, link, timeout=TIMEOUT, user_data_dir=CHROME_USER_DATA_DIR):
  287. """print HTML of site to file using chrome --dump-html"""
  288. if link['type'] in ('PDF', 'image'):
  289. return {'output': wget_output_path(link)}
  290. output_path = os.path.join(link_dir, 'output.html')
  291. if os.path.exists(output_path):
  292. return {'output': 'output.html', 'status': 'skipped'}
  293. CMD = [
  294. *chrome_headless(user_data_dir=user_data_dir),
  295. '--dump-dom',
  296. '--timeout={}'.format((timeout) * 1000),
  297. *(('--user-agent={}'.format(HEADLESS_USER_AGENT),) if HEADLESS_USER_AGENT else ()),
  298. link['url']
  299. ]
  300. end = progress(timeout, prefix=' ')
  301. try:
  302. with open(output_path, 'w+') as f:
  303. result = run(CMD, stdout=f, stderr=PIPE, cwd=link_dir, timeout=timeout)
  304. end()
  305. if result.returncode:
  306. print(' ', (result.stderr).decode())
  307. raise Exception('Failed to fetch DOM')
  308. chmod_file('output.html', cwd=link_dir)
  309. output = 'output.html'
  310. except Exception as e:
  311. end()
  312. output = e
  313. print_error_hints(cmd=CMD, pwd=link_dir, err=e)
  314. return {
  315. 'cmd': CMD,
  316. 'output': output,
  317. }
  318. def parse_archive_dot_org_response(response):
  319. # Parse archive.org response headers
  320. headers = defaultdict(list)
  321. # lowercase all the header names and store in dict
  322. for header in response.splitlines():
  323. if b':' not in header or not header.strip():
  324. continue
  325. name, val = header.decode().split(':', 1)
  326. headers[name.lower().strip()].append(val.strip())
  327. # Get successful archive url in "content-location" header or any errors
  328. content_location = headers['content-location']
  329. errors = headers['x-archive-wayback-runtime-error']
  330. return content_location, errors
  331. @attach_result_to_link('archive_org')
  332. def archive_dot_org(link_dir, link, timeout=TIMEOUT):
  333. """submit site to archive.org for archiving via their service, save returned archive url"""
  334. output = 'archive.org.txt'
  335. archive_org_url = None
  336. path = os.path.join(link_dir, output)
  337. if os.path.exists(path):
  338. archive_org_url = open(path, 'r').read().strip()
  339. return {'output': archive_org_url, 'status': 'skipped'}
  340. submit_url = 'https://web.archive.org/save/{}'.format(link['url'])
  341. CMD = [
  342. CURL_BINARY,
  343. '--location',
  344. '--head',
  345. '--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
  346. '--max-time', str(timeout),
  347. *(() if CHECK_SSL_VALIDITY else ('--insecure',)),
  348. submit_url,
  349. ]
  350. end = progress(timeout, prefix=' ')
  351. try:
  352. result = run(CMD, stdout=PIPE, stderr=DEVNULL, cwd=link_dir, timeout=timeout)
  353. end()
  354. content_location, errors = parse_archive_dot_org_response(result.stdout)
  355. if content_location:
  356. archive_org_url = 'https://web.archive.org{}'.format(content_location[0])
  357. elif len(errors) == 1 and 'RobotAccessControlException' in errors[0]:
  358. archive_org_url = None
  359. # raise Exception('Archive.org denied by {}/robots.txt'.format(domain(link['url'])))
  360. elif errors:
  361. raise Exception(', '.join(errors))
  362. else:
  363. raise Exception('Failed to find "content-location" URL header in Archive.org response.')
  364. except Exception as e:
  365. end()
  366. output = e
  367. print_error_hints(cmd=CMD, pwd=link_dir, err=e)
  368. if not isinstance(output, Exception):
  369. # instead of writing None when archive.org rejects the url write the
  370. # url to resubmit it to archive.org. This is so when the user visits
  371. # the URL in person, it will attempt to re-archive it, and it'll show the
  372. # nicer error message explaining why the url was rejected if it fails.
  373. archive_org_url = archive_org_url or submit_url
  374. with open(os.path.join(link_dir, output), 'w', encoding='utf-8') as f:
  375. f.write(archive_org_url)
  376. chmod_file('archive.org.txt', cwd=link_dir)
  377. output = archive_org_url
  378. return {
  379. 'cmd': CMD,
  380. 'output': output,
  381. }
  382. @attach_result_to_link('favicon')
  383. def fetch_favicon(link_dir, link, timeout=TIMEOUT):
  384. """download site favicon from google's favicon api"""
  385. output = 'favicon.ico'
  386. if os.path.exists(os.path.join(link_dir, output)):
  387. return {'output': output, 'status': 'skipped'}
  388. CMD = [
  389. CURL_BINARY,
  390. '--max-time', str(timeout),
  391. '--location',
  392. '--output', output,
  393. *(() if CHECK_SSL_VALIDITY else ('--insecure',)),
  394. 'https://www.google.com/s2/favicons?domain={}'.format(domain(link['url'])),
  395. ]
  396. end = progress(timeout, prefix=' ')
  397. try:
  398. run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  399. end()
  400. chmod_file('favicon.ico', cwd=link_dir)
  401. output = 'favicon.ico'
  402. except Exception as e:
  403. end()
  404. output = e
  405. print_error_hints(cmd=CMD, pwd=link_dir, err=e)
  406. return {
  407. 'cmd': CMD,
  408. 'output': output,
  409. }
  410. @attach_result_to_link('title')
  411. def fetch_title(link_dir, link, timeout=TIMEOUT):
  412. """try to guess the page's title from its content"""
  413. # if link already has valid title, skip it
  414. if link['title'] and not link['title'].lower().startswith('http'):
  415. return {'output': link['title'], 'status': 'skipped'}
  416. end = progress(timeout, prefix=' ')
  417. try:
  418. title = fetch_page_title(link['url'], timeout=timeout, progress=False)
  419. end()
  420. output = title
  421. except Exception as e:
  422. end()
  423. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  424. output = e
  425. # titles should show up in the global index immediatley for better UX,
  426. # do a hacky immediate replacement to add them in as we're archiving
  427. # TODO: figure out how to do this without gnarly string replacement
  428. if title:
  429. link['title'] = title
  430. patch_index_title_hack(link['url'], 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