archive_methods.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. import os
  2. from typing import Dict, List, Tuple
  3. from collections import defaultdict
  4. from datetime import datetime
  5. from .schema import Link, ArchiveResult, ArchiveError
  6. from .index import (
  7. write_link_index,
  8. patch_links_index,
  9. load_json_link_index,
  10. )
  11. from .config import (
  12. CURL_BINARY,
  13. GIT_BINARY,
  14. WGET_BINARY,
  15. YOUTUBEDL_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. SUBMIT_ARCHIVE_DOT_ORG,
  27. TIMEOUT,
  28. MEDIA_TIMEOUT,
  29. ANSI,
  30. OUTPUT_DIR,
  31. GIT_DOMAINS,
  32. VERSION,
  33. WGET_USER_AGENT,
  34. CHECK_SSL_VALIDITY,
  35. COOKIES_FILE,
  36. CURL_VERSION,
  37. WGET_VERSION,
  38. CHROME_VERSION,
  39. GIT_VERSION,
  40. YOUTUBEDL_VERSION,
  41. ONLY_NEW,
  42. WGET_AUTO_COMPRESSION,
  43. )
  44. from .util import (
  45. enforce_types,
  46. domain,
  47. extension,
  48. without_query,
  49. without_fragment,
  50. fetch_page_title,
  51. is_static_file,
  52. TimedProgress,
  53. chmod_file,
  54. wget_output_path,
  55. chrome_args,
  56. run, PIPE, DEVNULL,
  57. Link,
  58. )
  59. from .logs import (
  60. log_link_archiving_started,
  61. log_link_archiving_finished,
  62. log_archive_method_started,
  63. log_archive_method_finished,
  64. )
  65. @enforce_types
  66. def archive_link(link: Link, page=None) -> Link:
  67. """download the DOM, PDF, and a screenshot into a folder named after the link's timestamp"""
  68. ARCHIVE_METHODS = (
  69. ('title', should_fetch_title, fetch_title),
  70. ('favicon', should_fetch_favicon, fetch_favicon),
  71. ('wget', should_fetch_wget, fetch_wget),
  72. ('pdf', should_fetch_pdf, fetch_pdf),
  73. ('screenshot', should_fetch_screenshot, fetch_screenshot),
  74. ('dom', should_fetch_dom, fetch_dom),
  75. ('git', should_fetch_git, fetch_git),
  76. ('media', should_fetch_media, fetch_media),
  77. ('archive_org', should_fetch_archive_dot_org, archive_dot_org),
  78. )
  79. try:
  80. is_new = not os.path.exists(link.link_dir)
  81. if is_new:
  82. os.makedirs(link.link_dir)
  83. link = load_json_link_index(link.link_dir, link)
  84. log_link_archiving_started(link.link_dir, link, is_new)
  85. link = link.overwrite(updated=datetime.now())
  86. stats = {'skipped': 0, 'succeeded': 0, 'failed': 0}
  87. for method_name, should_run, method_function in ARCHIVE_METHODS:
  88. try:
  89. if method_name not in link.history:
  90. link.history[method_name] = []
  91. if should_run(link.link_dir, link):
  92. log_archive_method_started(method_name)
  93. result = method_function(link.link_dir, link)
  94. link.history[method_name].append(result)
  95. stats[result.status] += 1
  96. log_archive_method_finished(result)
  97. else:
  98. stats['skipped'] += 1
  99. except Exception as e:
  100. raise Exception('Exception in archive_methods.fetch_{}(Link(url={}))'.format(
  101. method_name,
  102. link.url,
  103. )) from e
  104. # print(' ', stats)
  105. # If any changes were made, update the link index json and html
  106. write_link_index(link.link_dir, link)
  107. was_changed = stats['succeeded'] or stats['failed']
  108. if was_changed:
  109. patch_links_index(link)
  110. log_link_archiving_finished(link.link_dir, link, is_new, stats)
  111. except KeyboardInterrupt:
  112. raise
  113. except Exception as err:
  114. print(' ! Failed to archive link: {}: {}'.format(err.__class__.__name__, err))
  115. raise
  116. return link
  117. ### Archive Method Functions
  118. @enforce_types
  119. def should_fetch_title(link_dir: str, link: Link) -> bool:
  120. # if link already has valid title, skip it
  121. if link.title and not link.title.lower().startswith('http'):
  122. return False
  123. if is_static_file(link.url):
  124. return False
  125. return FETCH_TITLE
  126. @enforce_types
  127. def fetch_title(link_dir: str, link: Link, timeout: int=TIMEOUT) -> ArchiveResult:
  128. """try to guess the page's title from its content"""
  129. output = None
  130. cmd = [
  131. CURL_BINARY,
  132. link.url,
  133. '|',
  134. 'grep',
  135. '<title>',
  136. ]
  137. status = 'succeeded'
  138. timer = TimedProgress(timeout, prefix=' ')
  139. try:
  140. output = fetch_page_title(link.url, timeout=timeout, progress=False)
  141. if not output:
  142. raise ArchiveError('Unable to detect page title')
  143. except Exception as err:
  144. status = 'failed'
  145. output = err
  146. finally:
  147. timer.end()
  148. return ArchiveResult(
  149. cmd=cmd,
  150. pwd=link_dir,
  151. cmd_version=CURL_VERSION,
  152. output=output,
  153. status=status,
  154. **timer.stats,
  155. )
  156. @enforce_types
  157. def should_fetch_favicon(link_dir: str, link: Link) -> bool:
  158. if os.path.exists(os.path.join(link_dir, 'favicon.ico')):
  159. return False
  160. return FETCH_FAVICON
  161. @enforce_types
  162. def fetch_favicon(link_dir: str, link: Link, timeout: int=TIMEOUT) -> ArchiveResult:
  163. """download site favicon from google's favicon api"""
  164. output = 'favicon.ico'
  165. cmd = [
  166. CURL_BINARY,
  167. '--max-time', str(timeout),
  168. '--location',
  169. '--output', output,
  170. *(() if CHECK_SSL_VALIDITY else ('--insecure',)),
  171. 'https://www.google.com/s2/favicons?domain={}'.format(domain(link.url)),
  172. ]
  173. status = 'succeeded'
  174. timer = TimedProgress(timeout, prefix=' ')
  175. try:
  176. run(cmd, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  177. chmod_file(output, cwd=link_dir)
  178. except Exception as err:
  179. status = 'failed'
  180. output = err
  181. finally:
  182. timer.end()
  183. return ArchiveResult(
  184. cmd=cmd,
  185. pwd=link_dir,
  186. cmd_version=CURL_VERSION,
  187. output=output,
  188. status=status,
  189. **timer.stats,
  190. )
  191. @enforce_types
  192. def should_fetch_wget(link_dir: str, link: Link) -> bool:
  193. output_path = wget_output_path(link)
  194. if output_path and os.path.exists(os.path.join(link_dir, output_path)):
  195. return False
  196. return FETCH_WGET
  197. @enforce_types
  198. def fetch_wget(link_dir: str, link: Link, timeout: int=TIMEOUT) -> ArchiveResult:
  199. """download full site using wget"""
  200. if FETCH_WARC:
  201. warc_dir = os.path.join(link_dir, 'warc')
  202. os.makedirs(warc_dir, exist_ok=True)
  203. warc_path = os.path.join('warc', str(int(datetime.now().timestamp())))
  204. # WGET CLI Docs: https://www.gnu.org/software/wget/manual/wget.html
  205. output = None
  206. cmd = [
  207. WGET_BINARY,
  208. # '--server-response', # print headers for better error parsing
  209. '--no-verbose',
  210. '--adjust-extension',
  211. '--convert-links',
  212. '--force-directories',
  213. '--backup-converted',
  214. '--span-hosts',
  215. '--no-parent',
  216. '-e', 'robots=off',
  217. '--restrict-file-names=unix',
  218. '--timeout={}'.format(timeout),
  219. *(() if FETCH_WARC else ('--timestamping',)),
  220. *(('--warc-file={}'.format(warc_path),) if FETCH_WARC else ()),
  221. *(('--page-requisites',) if FETCH_WGET_REQUISITES else ()),
  222. *(('--user-agent={}'.format(WGET_USER_AGENT),) if WGET_USER_AGENT else ()),
  223. *(('--load-cookies', COOKIES_FILE) if COOKIES_FILE else ()),
  224. *(('--compression=auto',) if WGET_AUTO_COMPRESSION else ()),
  225. *((() if CHECK_SSL_VALIDITY else ('--no-check-certificate', '--no-hsts'))),
  226. link.url,
  227. ]
  228. status = 'succeeded'
  229. timer = TimedProgress(timeout, prefix=' ')
  230. try:
  231. result = run(cmd, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  232. output = wget_output_path(link)
  233. # parse out number of files downloaded from last line of stderr:
  234. # "Downloaded: 76 files, 4.0M in 1.6s (2.52 MB/s)"
  235. output_tail = [
  236. line.strip()
  237. for line in (result.stdout + result.stderr).decode().rsplit('\n', 3)[-3:]
  238. if line.strip()
  239. ]
  240. files_downloaded = (
  241. int(output_tail[-1].strip().split(' ', 2)[1] or 0)
  242. if 'Downloaded:' in output_tail[-1]
  243. else 0
  244. )
  245. # Check for common failure cases
  246. if result.returncode > 0 and files_downloaded < 1:
  247. hints = (
  248. 'Got wget response code: {}.'.format(result.returncode),
  249. *output_tail,
  250. )
  251. if b'403: Forbidden' in result.stderr:
  252. raise ArchiveError('403 Forbidden (try changing WGET_USER_AGENT)', hints)
  253. if b'404: Not Found' in result.stderr:
  254. raise ArchiveError('404 Not Found', hints)
  255. if b'ERROR 500: Internal Server Error' in result.stderr:
  256. raise ArchiveError('500 Internal Server Error', hints)
  257. raise ArchiveError('Got an error from the server', hints)
  258. except Exception as err:
  259. status = 'failed'
  260. output = err
  261. finally:
  262. timer.end()
  263. return ArchiveResult(
  264. cmd=cmd,
  265. pwd=link_dir,
  266. cmd_version=WGET_VERSION,
  267. output=output,
  268. status=status,
  269. **timer.stats,
  270. )
  271. @enforce_types
  272. def should_fetch_pdf(link_dir: str, link: Link) -> bool:
  273. if is_static_file(link.url):
  274. return False
  275. if os.path.exists(os.path.join(link_dir, 'output.pdf')):
  276. return False
  277. return FETCH_PDF
  278. @enforce_types
  279. def fetch_pdf(link_dir: str, link: Link, timeout: int=TIMEOUT) -> ArchiveResult:
  280. """print PDF of site to file using chrome --headless"""
  281. output = 'output.pdf'
  282. cmd = [
  283. *chrome_args(TIMEOUT=timeout),
  284. '--print-to-pdf',
  285. link.url,
  286. ]
  287. status = 'succeeded'
  288. timer = TimedProgress(timeout, prefix=' ')
  289. try:
  290. result = run(cmd, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  291. if result.returncode:
  292. hints = (result.stderr or result.stdout).decode()
  293. raise ArchiveError('Failed to print PDF', hints)
  294. chmod_file('output.pdf', cwd=link_dir)
  295. except Exception as err:
  296. status = 'failed'
  297. output = err
  298. finally:
  299. timer.end()
  300. return ArchiveResult(
  301. cmd=cmd,
  302. pwd=link_dir,
  303. cmd_version=CHROME_VERSION,
  304. output=output,
  305. status=status,
  306. **timer.stats,
  307. )
  308. @enforce_types
  309. def should_fetch_screenshot(link_dir: str, link: Link) -> bool:
  310. if is_static_file(link.url):
  311. return False
  312. if os.path.exists(os.path.join(link_dir, 'screenshot.png')):
  313. return False
  314. return FETCH_SCREENSHOT
  315. @enforce_types
  316. def fetch_screenshot(link_dir: str, link: Link, timeout: int=TIMEOUT) -> ArchiveResult:
  317. """take screenshot of site using chrome --headless"""
  318. output = 'screenshot.png'
  319. cmd = [
  320. *chrome_args(TIMEOUT=timeout),
  321. '--screenshot',
  322. link.url,
  323. ]
  324. status = 'succeeded'
  325. timer = TimedProgress(timeout, prefix=' ')
  326. try:
  327. result = run(cmd, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  328. if result.returncode:
  329. hints = (result.stderr or result.stdout).decode()
  330. raise ArchiveError('Failed to take screenshot', hints)
  331. chmod_file(output, cwd=link_dir)
  332. except Exception as err:
  333. status = 'failed'
  334. output = err
  335. finally:
  336. timer.end()
  337. return ArchiveResult(
  338. cmd=cmd,
  339. pwd=link_dir,
  340. cmd_version=CHROME_VERSION,
  341. output=output,
  342. status=status,
  343. **timer.stats,
  344. )
  345. @enforce_types
  346. def should_fetch_dom(link_dir: str, link: Link) -> bool:
  347. if is_static_file(link.url):
  348. return False
  349. if os.path.exists(os.path.join(link_dir, 'output.html')):
  350. return False
  351. return FETCH_DOM
  352. @enforce_types
  353. def fetch_dom(link_dir: str, link: Link, timeout: int=TIMEOUT) -> ArchiveResult:
  354. """print HTML of site to file using chrome --dump-html"""
  355. output = 'output.html'
  356. output_path = os.path.join(link_dir, output)
  357. cmd = [
  358. *chrome_args(TIMEOUT=timeout),
  359. '--dump-dom',
  360. link.url
  361. ]
  362. status = 'succeeded'
  363. timer = TimedProgress(timeout, prefix=' ')
  364. try:
  365. with open(output_path, 'w+') as f:
  366. result = run(cmd, stdout=f, stderr=PIPE, cwd=link_dir, timeout=timeout)
  367. if result.returncode:
  368. hints = result.stderr.decode()
  369. raise ArchiveError('Failed to fetch DOM', hints)
  370. chmod_file(output, cwd=link_dir)
  371. except Exception as err:
  372. status = 'failed'
  373. output = err
  374. finally:
  375. timer.end()
  376. return ArchiveResult(
  377. cmd=cmd,
  378. pwd=link_dir,
  379. cmd_version=CHROME_VERSION,
  380. output=output,
  381. status=status,
  382. **timer.stats,
  383. )
  384. @enforce_types
  385. def should_fetch_git(link_dir: str, link: Link) -> bool:
  386. if is_static_file(link.url):
  387. return False
  388. if os.path.exists(os.path.join(link_dir, 'git')):
  389. return False
  390. is_clonable_url = (
  391. (domain(link.url) in GIT_DOMAINS)
  392. or (extension(link.url) == 'git')
  393. )
  394. if not is_clonable_url:
  395. return False
  396. return FETCH_GIT
  397. @enforce_types
  398. def fetch_git(link_dir: str, link: Link, timeout: int=TIMEOUT) -> ArchiveResult:
  399. """download full site using git"""
  400. output = 'git'
  401. output_path = os.path.join(link_dir, 'git')
  402. os.makedirs(output_path, exist_ok=True)
  403. cmd = [
  404. GIT_BINARY,
  405. 'clone',
  406. '--mirror',
  407. '--recursive',
  408. *(() if CHECK_SSL_VALIDITY else ('-c', 'http.sslVerify=false')),
  409. without_query(without_fragment(link.url)),
  410. ]
  411. status = 'succeeded'
  412. timer = TimedProgress(timeout, prefix=' ')
  413. try:
  414. result = run(cmd, stdout=PIPE, stderr=PIPE, cwd=output_path, timeout=timeout + 1)
  415. if result.returncode == 128:
  416. # ignore failed re-download when the folder already exists
  417. pass
  418. elif result.returncode > 0:
  419. hints = 'Got git response code: {}.'.format(result.returncode)
  420. raise ArchiveError('Failed git download', hints)
  421. except Exception as err:
  422. status = 'failed'
  423. output = err
  424. finally:
  425. timer.end()
  426. return ArchiveResult(
  427. cmd=cmd,
  428. pwd=link_dir,
  429. cmd_version=GIT_VERSION,
  430. output=output,
  431. status=status,
  432. **timer.stats,
  433. )
  434. @enforce_types
  435. def should_fetch_media(link_dir: str, link: Link) -> bool:
  436. if is_static_file(link.url):
  437. return False
  438. if os.path.exists(os.path.join(link_dir, 'media')):
  439. return False
  440. return FETCH_MEDIA
  441. @enforce_types
  442. def fetch_media(link_dir: str, link: Link, timeout: int=MEDIA_TIMEOUT) -> ArchiveResult:
  443. """Download playlists or individual video, audio, and subtitles using youtube-dl"""
  444. output = 'media'
  445. output_path = os.path.join(link_dir, 'media')
  446. os.makedirs(output_path, exist_ok=True)
  447. cmd = [
  448. YOUTUBEDL_BINARY,
  449. '--write-description',
  450. '--write-info-json',
  451. '--write-annotations',
  452. '--yes-playlist',
  453. '--write-thumbnail',
  454. '--no-call-home',
  455. '--no-check-certificate',
  456. '--user-agent',
  457. '--all-subs',
  458. '--extract-audio',
  459. '--keep-video',
  460. '--ignore-errors',
  461. '--geo-bypass',
  462. '--audio-format', 'mp3',
  463. '--audio-quality', '320K',
  464. '--embed-thumbnail',
  465. '--add-metadata',
  466. *(() if CHECK_SSL_VALIDITY else ('--no-check-certificate',)),
  467. link.url,
  468. ]
  469. status = 'succeeded'
  470. timer = TimedProgress(timeout, prefix=' ')
  471. try:
  472. result = run(cmd, stdout=PIPE, stderr=PIPE, cwd=output_path, timeout=timeout + 1)
  473. chmod_file(output, cwd=link_dir)
  474. if result.returncode:
  475. if (b'ERROR: Unsupported URL' in result.stderr
  476. or b'HTTP Error 404' in result.stderr
  477. or b'HTTP Error 403' in result.stderr
  478. or b'URL could be a direct video link' in result.stderr
  479. or b'Unable to extract container ID' in result.stderr):
  480. # These happen too frequently on non-media pages to warrant printing to console
  481. pass
  482. else:
  483. hints = (
  484. 'Got youtube-dl response code: {}.'.format(result.returncode),
  485. *result.stderr.decode().split('\n'),
  486. )
  487. raise ArchiveError('Failed to download media', hints)
  488. except Exception as err:
  489. status = 'failed'
  490. output = err
  491. finally:
  492. timer.end()
  493. return ArchiveResult(
  494. cmd=cmd,
  495. pwd=link_dir,
  496. cmd_version=YOUTUBEDL_VERSION,
  497. output=output,
  498. status=status,
  499. **timer.stats,
  500. )
  501. @enforce_types
  502. def should_fetch_archive_dot_org(link_dir: str, link: Link) -> bool:
  503. if is_static_file(link.url):
  504. return False
  505. if os.path.exists(os.path.join(link_dir, 'archive.org.txt')):
  506. # if open(path, 'r').read().strip() != 'None':
  507. return False
  508. return SUBMIT_ARCHIVE_DOT_ORG
  509. @enforce_types
  510. def archive_dot_org(link_dir: str, link: Link, timeout: int=TIMEOUT) -> ArchiveResult:
  511. """submit site to archive.org for archiving via their service, save returned archive url"""
  512. output = 'archive.org.txt'
  513. archive_org_url = None
  514. submit_url = 'https://web.archive.org/save/{}'.format(link.url)
  515. cmd = [
  516. CURL_BINARY,
  517. '--location',
  518. '--head',
  519. '--user-agent', 'ArchiveBox/{} (+https://github.com/pirate/ArchiveBox/)'.format(VERSION), # be nice to the Archive.org people and show them where all this ArchiveBox traffic is coming from
  520. '--max-time', str(timeout),
  521. *(() if CHECK_SSL_VALIDITY else ('--insecure',)),
  522. submit_url,
  523. ]
  524. status = 'succeeded'
  525. timer = TimedProgress(timeout, prefix=' ')
  526. try:
  527. result = run(cmd, stdout=PIPE, stderr=DEVNULL, cwd=link_dir, timeout=timeout)
  528. content_location, errors = parse_archive_dot_org_response(result.stdout)
  529. if content_location:
  530. archive_org_url = 'https://web.archive.org{}'.format(content_location[0])
  531. elif len(errors) == 1 and 'RobotAccessControlException' in errors[0]:
  532. archive_org_url = None
  533. # raise ArchiveError('Archive.org denied by {}/robots.txt'.format(domain(link.url)))
  534. elif errors:
  535. raise ArchiveError(', '.join(errors))
  536. else:
  537. raise ArchiveError('Failed to find "content-location" URL header in Archive.org response.')
  538. except Exception as err:
  539. status = 'failed'
  540. output = err
  541. finally:
  542. timer.end()
  543. if not isinstance(output, Exception):
  544. # instead of writing None when archive.org rejects the url write the
  545. # url to resubmit it to archive.org. This is so when the user visits
  546. # the URL in person, it will attempt to re-archive it, and it'll show the
  547. # nicer error message explaining why the url was rejected if it fails.
  548. archive_org_url = archive_org_url or submit_url
  549. with open(os.path.join(link_dir, output), 'w', encoding='utf-8') as f:
  550. f.write(archive_org_url)
  551. chmod_file('archive.org.txt', cwd=link_dir)
  552. output = archive_org_url
  553. return ArchiveResult(
  554. cmd=cmd,
  555. pwd=link_dir,
  556. cmd_version=CURL_VERSION,
  557. output=output,
  558. status=status,
  559. **timer.stats,
  560. )
  561. @enforce_types
  562. def parse_archive_dot_org_response(response: bytes) -> Tuple[List[str], List[str]]:
  563. # Parse archive.org response headers
  564. headers: Dict[str, List[str]] = defaultdict(list)
  565. # lowercase all the header names and store in dict
  566. for header in response.splitlines():
  567. if b':' not in header or not header.strip():
  568. continue
  569. name, val = header.decode().split(':', 1)
  570. headers[name.lower().strip()].append(val.strip())
  571. # Get successful archive url in "content-location" header or any errors
  572. content_location = headers['content-location']
  573. errors = headers['x-archive-wayback-runtime-error']
  574. return content_location, errors