archive_methods.py 18 KB

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