archive_methods.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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. is_static_file,
  48. progress,
  49. chmod_file,
  50. pretty_path,
  51. print_error_hints,
  52. check_link_structure,
  53. wget_output_path,
  54. run, PIPE, DEVNULL,
  55. )
  56. _RESULTS_TOTALS = { # globals are bad, mmkay
  57. 'skipped': 0,
  58. 'succeded': 0,
  59. 'failed': 0,
  60. }
  61. def load_link_index(link_dir, link):
  62. """check for an existing link archive in the given directory,
  63. and load+merge it into the given link dict
  64. """
  65. is_new = not os.path.exists(link_dir)
  66. if is_new:
  67. os.makedirs(link_dir)
  68. else:
  69. link = {
  70. **parse_json_link_index(link_dir),
  71. **link,
  72. }
  73. check_link_structure(link)
  74. print_link_status_line(link_dir, link, is_new)
  75. return link
  76. class ArchiveError(Exception):
  77. def __init__(self, message, hints=None):
  78. super().__init__(message)
  79. self.hints = hints
  80. def archive_link(link_dir, link, overwrite=True):
  81. """download the DOM, PDF, and a screenshot into a folder named after the link's timestamp"""
  82. ARCHIVE_METHODS = (
  83. (FETCH_TITLE, fetch_title),
  84. (FETCH_FAVICON, fetch_favicon),
  85. (FETCH_WGET, fetch_wget),
  86. (FETCH_PDF, fetch_pdf),
  87. (FETCH_SCREENSHOT, fetch_screenshot),
  88. (FETCH_DOM, fetch_dom),
  89. (FETCH_GIT, fetch_git),
  90. (FETCH_MEDIA, fetch_media),
  91. (SUBMIT_ARCHIVE_DOT_ORG, archive_dot_org),
  92. )
  93. active_methods = [method for toggle, method in ARCHIVE_METHODS if toggle]
  94. try:
  95. link = load_link_index(link_dir, link)
  96. for archive_method in active_methods:
  97. archive_method(link_dir, link, overwrite=overwrite)
  98. write_link_index(link_dir, link)
  99. update_main_index(link)
  100. except Exception as err:
  101. print(' ! Failed to archive link: {}: {}'.format(err.__class__.__name__, err))
  102. return link
  103. def print_link_status_line(link_dir, link, is_new):
  104. print('[{symbol_color}{symbol}{reset}] [{now}] "{title}"\n {blue}{url}{reset}'.format(
  105. symbol='+' if is_new else '*',
  106. symbol_color=ANSI['green' if is_new else 'black'],
  107. now=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  108. **{**link, 'title': link['title'] or link['url']},
  109. **ANSI,
  110. ))
  111. print(' > {}{}'.format(pretty_path(link_dir), ' (new)' if is_new else ''))
  112. def attach_result_to_link(method):
  113. """
  114. Instead of returning a result={output:'...', status:'success'} object,
  115. attach that result to the links's history & latest fields, then return
  116. the updated link object.
  117. """
  118. def decorator(fetch_func):
  119. @wraps(fetch_func)
  120. def timed_fetch_func(link_dir, link, overwrite=False, **kwargs):
  121. # initialize methods and history json field on link
  122. link['latest'] = link.get('latest') or {}
  123. link['latest'][method] = link['latest'].get(method) or None
  124. link['history'] = link.get('history') or {}
  125. link['history'][method] = link['history'].get(method) or []
  126. start_ts = datetime.now().timestamp()
  127. # if a valid method output is already present, dont run the fetch function
  128. if link['latest'][method] and not overwrite:
  129. print(' √ {}'.format(method))
  130. result = None
  131. else:
  132. print(' > {}'.format(method))
  133. result = fetch_func(link_dir, link, **kwargs)
  134. end_ts = datetime.now().timestamp()
  135. duration = str(end_ts * 1000 - start_ts * 1000).split('.')[0]
  136. # append a history item recording fail/success
  137. history_entry = {
  138. 'timestamp': str(start_ts).split('.')[0],
  139. }
  140. if result is None:
  141. history_entry['status'] = 'skipped'
  142. elif isinstance(result.get('output'), Exception):
  143. history_entry['status'] = 'failed'
  144. history_entry['duration'] = duration
  145. history_entry.update(result or {})
  146. link['history'][method].append(history_entry)
  147. else:
  148. history_entry['status'] = 'succeded'
  149. history_entry['duration'] = duration
  150. history_entry.update(result or {})
  151. link['history'][method].append(history_entry)
  152. link['latest'][method] = result['output']
  153. _RESULTS_TOTALS[history_entry['status']] += 1
  154. return link
  155. return timed_fetch_func
  156. return decorator
  157. @attach_result_to_link('wget')
  158. def fetch_wget(link_dir, link, requisites=FETCH_WGET_REQUISITES, warc=FETCH_WARC, timeout=TIMEOUT):
  159. """download full site using wget"""
  160. domain_dir = os.path.join(link_dir, domain(link['url']))
  161. existing_file = wget_output_path(link)
  162. if os.path.exists(domain_dir) and existing_file:
  163. return {'output': existing_file, 'status': 'skipped'}
  164. if warc:
  165. warc_dir = os.path.join(link_dir, 'warc')
  166. os.makedirs(warc_dir, exist_ok=True)
  167. warc_path = os.path.join('warc', str(int(datetime.now().timestamp())))
  168. # WGET CLI Docs: https://www.gnu.org/software/wget/manual/wget.html
  169. CMD = [
  170. WGET_BINARY,
  171. # '--server-response', # print headers for better error parsing
  172. '--no-verbose',
  173. '--adjust-extension',
  174. '--convert-links',
  175. '--force-directories',
  176. '--backup-converted',
  177. '--span-hosts',
  178. '--no-parent',
  179. '-e', 'robots=off',
  180. '--restrict-file-names=unix',
  181. '--timeout={}'.format(timeout),
  182. *(() if warc else ('--timestamping',)),
  183. *(('--warc-file={}'.format(warc_path),) if warc else ()),
  184. *(('--page-requisites',) if FETCH_WGET_REQUISITES else ()),
  185. *(('--user-agent={}'.format(WGET_USER_AGENT),) if WGET_USER_AGENT else ()),
  186. *(('--load-cookies', COOKIES_FILE) if COOKIES_FILE else ()),
  187. *((() if CHECK_SSL_VALIDITY else ('--no-check-certificate', '--no-hsts'))),
  188. link['url'],
  189. ]
  190. end = progress(timeout, prefix=' ')
  191. try:
  192. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  193. end()
  194. output = wget_output_path(link)
  195. output_tail = [
  196. line.strip()
  197. for line in (result.stdout + result.stderr).decode().rsplit('\n', 3)[-3:]
  198. if line.strip()
  199. ]
  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. hints = (
  209. 'Got wget response code {}:\n'.format(result.returncode),
  210. *output_tail,
  211. )
  212. if b'403: Forbidden' in result.stderr:
  213. raise ArchiveError('403 Forbidden (try changing WGET_USER_AGENT)', hints)
  214. if b'404: Not Found' in result.stderr:
  215. raise ArchiveError('404 Not Found', hints)
  216. if b'ERROR 500: Internal Server Error' in result.stderr:
  217. raise ArchiveError('500 Internal Server Error', hints)
  218. raise ArchiveError('Got an error from the server', hints)
  219. except Exception as e:
  220. end()
  221. output = e
  222. print_error_hints(cmd=CMD, pwd=link_dir, err=e)
  223. return {
  224. 'cmd': CMD,
  225. 'output': output,
  226. }
  227. @attach_result_to_link('pdf')
  228. def fetch_pdf(link_dir, link, timeout=TIMEOUT, **chrome_kwargs):
  229. """print PDF of site to file using chrome --headless"""
  230. if is_static_file(link['url']):
  231. return {'output': wget_output_path(link), 'status': 'skipped'}
  232. output = 'output.pdf'
  233. if os.path.exists(os.path.join(link_dir, output)):
  234. return {'output': output, 'status': 'skipped'}
  235. CMD = [
  236. *chrome_headless(timeout=timeout, **chrome_kwargs),
  237. '--print-to-pdf',
  238. link['url']
  239. ]
  240. end = progress(timeout, prefix=' ')
  241. hints = None
  242. try:
  243. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  244. end()
  245. if result.returncode:
  246. hints = (result.stderr or result.stdout).decode()
  247. raise ArchiveError('Failed to print PDF', hints)
  248. chmod_file('output.pdf', cwd=link_dir)
  249. except Exception as e:
  250. end()
  251. output = e
  252. print_error_hints(cmd=CMD, pwd=link_dir, err=e, hints=hints)
  253. return {
  254. 'cmd': CMD,
  255. 'output': output,
  256. }
  257. @attach_result_to_link('screenshot')
  258. def fetch_screenshot(link_dir, link, timeout=TIMEOUT, **chrome_kwargs):
  259. """take screenshot of site using chrome --headless"""
  260. if is_static_file(link['url']):
  261. return {'output': wget_output_path(link), 'status': 'skipped'}
  262. output = 'screenshot.png'
  263. if os.path.exists(os.path.join(link_dir, output)):
  264. return {'output': output, 'status': 'skipped'}
  265. CMD = [
  266. *chrome_headless(timeout=timeout, **chrome_kwargs),
  267. '--screenshot',
  268. link['url'],
  269. ]
  270. end = progress(timeout, prefix=' ')
  271. try:
  272. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  273. end()
  274. if result.returncode:
  275. hints = (result.stderr or result.stdout).decode()
  276. raise ArchiveError('Failed to take screenshot', hints)
  277. chmod_file(output, cwd=link_dir)
  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, **chrome_kwargs):
  288. """print HTML of site to file using chrome --dump-html"""
  289. if is_static_file(link['url']):
  290. return {'output': wget_output_path(link), 'status': 'skipped'}
  291. output = 'output.html'
  292. if os.path.exists(os.path.join(link_dir, output)):
  293. return {'output': output, 'status': 'skipped'}
  294. CMD = [
  295. *chrome_headless(timeout=timeout, **chrome_kwargs),
  296. '--dump-dom',
  297. link['url']
  298. ]
  299. end = progress(timeout, prefix=' ')
  300. try:
  301. with open(output_path, 'w+') as f:
  302. result = run(CMD, stdout=f, stderr=PIPE, cwd=link_dir, timeout=timeout)
  303. end()
  304. if result.returncode:
  305. hints = result.stderr.decode()
  306. raise ArchiveError('Failed to fetch DOM', hints)
  307. chmod_file(output, cwd=link_dir)
  308. except Exception as e:
  309. end()
  310. output = e
  311. print_error_hints(cmd=CMD, pwd=link_dir, err=e)
  312. return {
  313. 'cmd': CMD,
  314. 'output': output,
  315. }
  316. def parse_archive_dot_org_response(response):
  317. # Parse archive.org response headers
  318. headers = defaultdict(list)
  319. # lowercase all the header names and store in dict
  320. for header in response.splitlines():
  321. if b':' not in header or not header.strip():
  322. continue
  323. name, val = header.decode().split(':', 1)
  324. headers[name.lower().strip()].append(val.strip())
  325. # Get successful archive url in "content-location" header or any errors
  326. content_location = headers['content-location']
  327. errors = headers['x-archive-wayback-runtime-error']
  328. return content_location, errors
  329. @attach_result_to_link('archive_org')
  330. def archive_dot_org(link_dir, link, timeout=TIMEOUT):
  331. """submit site to archive.org for archiving via their service, save returned archive url"""
  332. output = 'archive.org.txt'
  333. archive_org_url = None
  334. path = os.path.join(link_dir, output)
  335. if os.path.exists(path):
  336. archive_org_url = open(path, 'r').read().strip()
  337. return {'output': archive_org_url, 'status': 'skipped'}
  338. submit_url = 'https://web.archive.org/save/{}'.format(link['url'])
  339. CMD = [
  340. CURL_BINARY,
  341. '--location',
  342. '--head',
  343. '--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
  344. '--max-time', str(timeout),
  345. *(() if CHECK_SSL_VALIDITY else ('--insecure',)),
  346. submit_url,
  347. ]
  348. end = progress(timeout, prefix=' ')
  349. try:
  350. result = run(CMD, stdout=PIPE, stderr=DEVNULL, cwd=link_dir, timeout=timeout)
  351. end()
  352. content_location, errors = parse_archive_dot_org_response(result.stdout)
  353. if content_location:
  354. archive_org_url = 'https://web.archive.org{}'.format(content_location[0])
  355. elif len(errors) == 1 and 'RobotAccessControlException' in errors[0]:
  356. archive_org_url = None
  357. # raise ArchiveError('Archive.org denied by {}/robots.txt'.format(domain(link['url'])))
  358. elif errors:
  359. raise ArchiveError(', '.join(errors))
  360. else:
  361. raise ArchiveError('Failed to find "content-location" URL header in Archive.org response.')
  362. except Exception as e:
  363. end()
  364. output = e
  365. print_error_hints(cmd=CMD, pwd=link_dir, err=e)
  366. if not isinstance(output, Exception):
  367. # instead of writing None when archive.org rejects the url write the
  368. # url to resubmit it to archive.org. This is so when the user visits
  369. # the URL in person, it will attempt to re-archive it, and it'll show the
  370. # nicer error message explaining why the url was rejected if it fails.
  371. archive_org_url = archive_org_url or submit_url
  372. with open(os.path.join(link_dir, output), 'w', encoding='utf-8') as f:
  373. f.write(archive_org_url)
  374. chmod_file('archive.org.txt', cwd=link_dir)
  375. output = archive_org_url
  376. return {
  377. 'cmd': CMD,
  378. 'output': output,
  379. }
  380. @attach_result_to_link('favicon')
  381. def fetch_favicon(link_dir, link, timeout=TIMEOUT):
  382. """download site favicon from google's favicon api"""
  383. output = 'favicon.ico'
  384. if os.path.exists(os.path.join(link_dir, output)):
  385. return {'output': output, 'status': 'skipped'}
  386. CMD = [
  387. CURL_BINARY,
  388. '--max-time', str(timeout),
  389. '--location',
  390. '--output', output,
  391. *(() if CHECK_SSL_VALIDITY else ('--insecure',)),
  392. 'https://www.google.com/s2/favicons?domain={}'.format(domain(link['url'])),
  393. ]
  394. end = progress(timeout, prefix=' ')
  395. try:
  396. run(CMD, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  397. end()
  398. chmod_file(output, cwd=link_dir)
  399. except Exception as e:
  400. end()
  401. output = e
  402. print_error_hints(cmd=CMD, pwd=link_dir, err=e)
  403. return {
  404. 'cmd': CMD,
  405. 'output': output,
  406. }
  407. @attach_result_to_link('title')
  408. def fetch_title(link_dir, link, timeout=TIMEOUT):
  409. """try to guess the page's title from its content"""
  410. # if link already has valid title, skip it
  411. if link['title'] and not link['title'].lower().startswith('http'):
  412. return {'output': link['title'], 'status': 'skipped'}
  413. if is_static_file(link['url']):
  414. return {'output': None, 'status': 'skipped'}
  415. end = progress(timeout, prefix=' ')
  416. try:
  417. title = fetch_page_title(link['url'], timeout=timeout, progress=False)
  418. end()
  419. output = title
  420. except Exception as e:
  421. end()
  422. output = e
  423. print(' {}Failed: {} {}{}'.format(ANSI['red'], e.__class__.__name__, e, ANSI['reset']))
  424. if title and title.strip():
  425. link['title'] = title
  426. output = title
  427. return {
  428. 'cmd': 'fetch_page_title("{}")'.format(link['url']),
  429. 'output': output,
  430. }
  431. @attach_result_to_link('media')
  432. def fetch_media(link_dir, link, timeout=MEDIA_TIMEOUT, overwrite=False):
  433. """Download playlists or individual video, audio, and subtitles using youtube-dl"""
  434. output = 'media'
  435. output_path = os.path.join(link_dir, 'media')
  436. if os.path.exists(output_path) and not overwrite:
  437. return {'output': output, 'status': 'skipped'}
  438. os.makedirs(output_path, exist_ok=True)
  439. CMD = [
  440. YOUTUBEDL_BINARY,
  441. '--write-description',
  442. '--write-info-json',
  443. '--write-annotations',
  444. '--yes-playlist',
  445. '--write-thumbnail',
  446. '--no-call-home',
  447. '--no-check-certificate',
  448. '--user-agent',
  449. '--all-subs',
  450. '--extract-audio',
  451. '--keep-video',
  452. '--ignore-errors',
  453. '--geo-bypass',
  454. '--audio-format', 'mp3',
  455. '--audio-quality', '320K',
  456. '--embed-thumbnail',
  457. '--add-metadata',
  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_path, timeout=timeout + 1)
  464. chmod_file(output, cwd=link_dir)
  465. end()
  466. if result.returncode:
  467. if (b'ERROR: Unsupported URL' in result.stderr
  468. or b'HTTP Error 404' in result.stderr
  469. or b'HTTP Error 403' in result.stderr
  470. or b'URL could be a direct video link' in result.stderr
  471. or b'Unable to extract container ID' in result.stderr):
  472. # These happen too frequently on non-media pages to warrant printing to console
  473. pass
  474. else:
  475. hints = (
  476. 'got youtubedl response code {}:'.format(result.returncode),
  477. *result.stderr.decode().split('\n'),
  478. )
  479. raise ArchiveError('Failed to download media', hints)
  480. except Exception as e:
  481. end()
  482. output = e
  483. print_error_hints(cmd=CMD, pwd=link_dir, err=e)
  484. return {
  485. 'cmd': CMD,
  486. 'output': output,
  487. }
  488. @attach_result_to_link('git')
  489. def fetch_git(link_dir, link, timeout=TIMEOUT):
  490. """download full site using git"""
  491. url_is_clonable = (
  492. domain(link['url']) in GIT_DOMAINS
  493. or link['url'].endswith('.git')
  494. )
  495. if not url_is_clonable or is_static_file(link['url']):
  496. return {'output': None, 'status': 'skipped'}
  497. output = 'git'
  498. output_path = os.path.join(link_dir, 'git')
  499. if os.path.exists(output_path):
  500. return {'output': output, 'status': 'skipped'}
  501. os.makedirs(output_path, exist_ok=True)
  502. CMD = [
  503. GIT_BINARY,
  504. 'clone',
  505. '--mirror',
  506. '--recursive',
  507. *(() if CHECK_SSL_VALIDITY else ('-c', 'http.sslVerify=false')),
  508. without_query(without_fragment(link['url'])),
  509. ]
  510. end = progress(timeout, prefix=' ')
  511. try:
  512. result = run(CMD, stdout=PIPE, stderr=PIPE, cwd=output_path, timeout=timeout + 1)
  513. end()
  514. if result.returncode == 128:
  515. # ignore failed re-download when the folder already exists
  516. pass
  517. elif result.returncode > 0:
  518. hints = 'got git response code {}:'.format(result.returncode)
  519. raise ArchiveError('Failed git download', hints)
  520. except Exception as e:
  521. end()
  522. output = e
  523. print_error_hints(cmd=CMD, pwd=link_dir, err=e)
  524. return {
  525. 'cmd': CMD,
  526. 'output': output,
  527. }
  528. def chrome_headless(binary=CHROME_BINARY, user_data_dir=CHROME_USER_DATA_DIR, headless=CHROME_HEADLESS, sandbox=CHROME_SANDBOX, check_ssl_validity=CHECK_SSL_VALIDITY, user_agent=CHROME_USER_AGENT, resolution=RESOLUTION, timeout=TIMEOUT):
  529. global CACHED_USER_DATA_DIR
  530. user_data_dir = user_data_dir or CACHED_USER_DATA_DIR
  531. cmd_args = [binary]
  532. if headless:
  533. cmd_args += ('--headless',)
  534. if not sandbox:
  535. # dont use GPU or sandbox when running inside docker container
  536. cmd_args += ('--no-sandbox', '--disable-gpu')
  537. if not check_ssl_validity:
  538. cmd_args += ('--disable-web-security', '--ignore-certificate-errors')
  539. if user_agent:
  540. cmd_args += ('--user-agent={}'.format(user_agent),)
  541. if resolution:
  542. cmd_args += ('--window-size={}'.format(RESOLUTION),)
  543. if timeout:
  544. cmd_args += ('--timeout={}'.format((timeout) * 1000),)
  545. # Find chrome user data directory
  546. default_profile_paths = (
  547. '~/.config/chromium',
  548. '~/.config/google-chrome',
  549. '~/.config/google-chrome-beta',
  550. '~/.config/google-chrome-unstable',
  551. '~/Library/Application Support/Chromium',
  552. '~/Library/Application Support/Google/Chrome',
  553. '~/Library/Application Support/Google/Chrome Canary',
  554. '~/AppData/Local/Chromium/User Data',
  555. '~/AppData/Local/Google/Chrome/User Data',
  556. '~/AppData/Local/Google/Chrome SxS/User Data',
  557. )
  558. if user_data_dir:
  559. cmd_args.append('--user-data-dir={}'.format(user_data_dir))
  560. else:
  561. for path in default_profile_paths:
  562. full_path = os.path.expanduser(path)
  563. if os.path.exists(full_path):
  564. CACHED_USER_DATA_DIR = full_path
  565. cmd_args.append('--user-data-dir={}'.format(full_path))
  566. break
  567. return cmd_args
  568. CACHED_USER_DATA_DIR = CHROME_USER_DATA_DIR