archive_methods.py 19 KB

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