archive_methods.py 18 KB

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