archive_methods.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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. skipped_entirely = True
  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. if skipped_entirely:
  84. skipped_entirely = False
  85. print()
  86. else:
  87. continue
  88. log_archive_method_started(method_name)
  89. result = method_function(link_dir, link)
  90. log_archive_method_finished(result)
  91. link['history'][method_name].append(result)
  92. write_link_index(link_dir, link)
  93. patch_links_index(link)
  94. log_link_archiving_finished(link_dir, link, is_new, skipped_entirely)
  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. *(() if FETCH_WARC else ('--timestamping',)),
  194. *(('--warc-file={}'.format(warc_path),) if FETCH_WARC else ()),
  195. *(('--page-requisites',) if FETCH_WGET_REQUISITES else ()),
  196. *(('--user-agent={}'.format(WGET_USER_AGENT),) if WGET_USER_AGENT else ()),
  197. *(('--load-cookies', COOKIES_FILE) if COOKIES_FILE else ()),
  198. *((() if CHECK_SSL_VALIDITY else ('--no-check-certificate', '--no-hsts'))),
  199. link['url'],
  200. ]
  201. status = 'succeeded'
  202. timer = TimedProgress(timeout, prefix=' ')
  203. try:
  204. result = run(cmd, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  205. output = wget_output_path(link)
  206. # parse out number of files downloaded from last line of stderr:
  207. # "Downloaded: 76 files, 4.0M in 1.6s (2.52 MB/s)"
  208. output_tail = [
  209. line.strip()
  210. for line in (result.stdout + result.stderr).decode().rsplit('\n', 3)[-3:]
  211. if line.strip()
  212. ]
  213. files_downloaded = (
  214. int(output_tail[-1].strip().split(' ', 2)[1] or 0)
  215. if 'Downloaded:' in output_tail[-1]
  216. else 0
  217. )
  218. # Check for common failure cases
  219. if result.returncode > 0 and files_downloaded < 1:
  220. hints = (
  221. 'Got wget response code: {}.'.format(result.returncode),
  222. *output_tail,
  223. )
  224. if b'403: Forbidden' in result.stderr:
  225. raise ArchiveError('403 Forbidden (try changing WGET_USER_AGENT)', hints)
  226. if b'404: Not Found' in result.stderr:
  227. raise ArchiveError('404 Not Found', hints)
  228. if b'ERROR 500: Internal Server Error' in result.stderr:
  229. raise ArchiveError('500 Internal Server Error', hints)
  230. raise ArchiveError('Got an error from the server', hints)
  231. except Exception as err:
  232. status = 'failed'
  233. output = err
  234. finally:
  235. timer.end()
  236. return {
  237. 'cmd': cmd,
  238. 'pwd': link_dir,
  239. 'output': output,
  240. 'status': status,
  241. **timer.stats,
  242. }
  243. def should_fetch_pdf(link_dir, link):
  244. if is_static_file(link['url']):
  245. return False
  246. if os.path.exists(os.path.join(link_dir, 'output.pdf')):
  247. return False
  248. return FETCH_PDF
  249. def fetch_pdf(link_dir, link, timeout=TIMEOUT):
  250. """print PDF of site to file using chrome --headless"""
  251. output = 'output.pdf'
  252. cmd = [
  253. *chrome_args(timeout=timeout),
  254. '--print-to-pdf',
  255. link['url'],
  256. ]
  257. status = 'succeeded'
  258. timer = TimedProgress(timeout, prefix=' ')
  259. try:
  260. result = run(cmd, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  261. if result.returncode:
  262. hints = (result.stderr or result.stdout).decode()
  263. raise ArchiveError('Failed to print PDF', hints)
  264. chmod_file('output.pdf', cwd=link_dir)
  265. except Exception as err:
  266. status = 'failed'
  267. output = err
  268. finally:
  269. timer.end()
  270. return {
  271. 'cmd': cmd,
  272. 'pwd': link_dir,
  273. 'output': output,
  274. 'status': status,
  275. **timer.stats,
  276. }
  277. def should_fetch_screenshot(link_dir, link):
  278. if is_static_file(link['url']):
  279. return False
  280. if os.path.exists(os.path.join(link_dir, 'screenshot.png')):
  281. return False
  282. return FETCH_SCREENSHOT
  283. def fetch_screenshot(link_dir, link, timeout=TIMEOUT):
  284. """take screenshot of site using chrome --headless"""
  285. output = 'screenshot.png'
  286. cmd = [
  287. *chrome_args(timeout=timeout),
  288. '--screenshot',
  289. link['url'],
  290. ]
  291. status = 'succeeded'
  292. timer = TimedProgress(timeout, prefix=' ')
  293. try:
  294. result = run(cmd, stdout=PIPE, stderr=PIPE, cwd=link_dir, timeout=timeout)
  295. if result.returncode:
  296. hints = (result.stderr or result.stdout).decode()
  297. raise ArchiveError('Failed to take screenshot', hints)
  298. chmod_file(output, cwd=link_dir)
  299. except Exception as err:
  300. status = 'failed'
  301. output = err
  302. finally:
  303. timer.end()
  304. return {
  305. 'cmd': cmd,
  306. 'pwd': link_dir,
  307. 'output': output,
  308. 'status': status,
  309. **timer.stats,
  310. }
  311. def should_fetch_dom(link_dir, link):
  312. if is_static_file(link['url']):
  313. return False
  314. if os.path.exists(os.path.join(link_dir, 'output.html')):
  315. return False
  316. return FETCH_DOM
  317. def fetch_dom(link_dir, link, timeout=TIMEOUT):
  318. """print HTML of site to file using chrome --dump-html"""
  319. output = 'output.html'
  320. output_path = os.path.join(link_dir, output)
  321. cmd = [
  322. *chrome_args(timeout=timeout),
  323. '--dump-dom',
  324. link['url']
  325. ]
  326. status = 'succeeded'
  327. timer = TimedProgress(timeout, prefix=' ')
  328. try:
  329. with open(output_path, 'w+') as f:
  330. result = run(cmd, stdout=f, stderr=PIPE, cwd=link_dir, timeout=timeout)
  331. if result.returncode:
  332. hints = result.stderr.decode()
  333. raise ArchiveError('Failed to fetch DOM', hints)
  334. chmod_file(output, cwd=link_dir)
  335. except Exception as err:
  336. status = 'failed'
  337. output = err
  338. finally:
  339. timer.end()
  340. return {
  341. 'cmd': cmd,
  342. 'pwd': link_dir,
  343. 'output': output,
  344. 'status': status,
  345. **timer.stats,
  346. }
  347. def should_fetch_git(link_dir, link):
  348. if is_static_file(link['url']):
  349. return False
  350. if os.path.exists(os.path.join(link_dir, 'git')):
  351. return False
  352. is_clonable_url = (
  353. (domain(link['url']) in GIT_DOMAINS)
  354. or (extension(link['url']) == 'git')
  355. )
  356. if not is_clonable_url:
  357. return False
  358. return FETCH_GIT
  359. def fetch_git(link_dir, link, timeout=TIMEOUT):
  360. """download full site using git"""
  361. output = 'git'
  362. output_path = os.path.join(link_dir, 'git')
  363. os.makedirs(output_path, exist_ok=True)
  364. cmd = [
  365. GIT_BINARY,
  366. 'clone',
  367. '--mirror',
  368. '--recursive',
  369. *(() if CHECK_SSL_VALIDITY else ('-c', 'http.sslVerify=false')),
  370. without_query(without_fragment(link['url'])),
  371. ]
  372. status = 'succeeded'
  373. timer = TimedProgress(timeout, prefix=' ')
  374. try:
  375. result = run(cmd, stdout=PIPE, stderr=PIPE, cwd=output_path, timeout=timeout + 1)
  376. if result.returncode == 128:
  377. # ignore failed re-download when the folder already exists
  378. pass
  379. elif result.returncode > 0:
  380. hints = 'Got git response code: {}.'.format(result.returncode)
  381. raise ArchiveError('Failed git download', hints)
  382. except Exception as err:
  383. status = 'failed'
  384. output = err
  385. finally:
  386. timer.end()
  387. return {
  388. 'cmd': cmd,
  389. 'pwd': link_dir,
  390. 'output': output,
  391. 'status': status,
  392. **timer.stats,
  393. }
  394. def should_fetch_media(link_dir, link):
  395. if is_static_file(link['url']):
  396. return False
  397. if os.path.exists(os.path.join(link_dir, 'media')):
  398. return False
  399. return FETCH_MEDIA
  400. def fetch_media(link_dir, link, timeout=MEDIA_TIMEOUT):
  401. """Download playlists or individual video, audio, and subtitles using youtube-dl"""
  402. output = 'media'
  403. output_path = os.path.join(link_dir, 'media')
  404. os.makedirs(output_path, exist_ok=True)
  405. cmd = [
  406. YOUTUBEDL_BINARY,
  407. '--write-description',
  408. '--write-info-json',
  409. '--write-annotations',
  410. '--yes-playlist',
  411. '--write-thumbnail',
  412. '--no-call-home',
  413. '--no-check-certificate',
  414. '--user-agent',
  415. '--all-subs',
  416. '--extract-audio',
  417. '--keep-video',
  418. '--ignore-errors',
  419. '--geo-bypass',
  420. '--audio-format', 'mp3',
  421. '--audio-quality', '320K',
  422. '--embed-thumbnail',
  423. '--add-metadata',
  424. *(() if CHECK_SSL_VALIDITY else ('--no-check-certificate',)),
  425. link['url'],
  426. ]
  427. status = 'succeeded'
  428. timer = TimedProgress(timeout, prefix=' ')
  429. try:
  430. result = run(cmd, stdout=PIPE, stderr=PIPE, cwd=output_path, timeout=timeout + 1)
  431. chmod_file(output, cwd=link_dir)
  432. if result.returncode:
  433. if (b'ERROR: Unsupported URL' in result.stderr
  434. or b'HTTP Error 404' in result.stderr
  435. or b'HTTP Error 403' in result.stderr
  436. or b'URL could be a direct video link' in result.stderr
  437. or b'Unable to extract container ID' in result.stderr):
  438. # These happen too frequently on non-media pages to warrant printing to console
  439. pass
  440. else:
  441. hints = (
  442. 'Got youtube-dl response code: {}.'.format(result.returncode),
  443. *result.stderr.decode().split('\n'),
  444. )
  445. raise ArchiveError('Failed to download media', hints)
  446. except Exception as err:
  447. status = 'failed'
  448. output = err
  449. finally:
  450. timer.end()
  451. return {
  452. 'cmd': cmd,
  453. 'pwd': link_dir,
  454. 'output': output,
  455. 'status': status,
  456. **timer.stats,
  457. }
  458. def should_fetch_archive_dot_org(link_dir, link):
  459. if is_static_file(link['url']):
  460. return False
  461. if os.path.exists(os.path.join(link_dir, 'archive.org.txt')):
  462. # if open(path, 'r').read().strip() != 'None':
  463. return False
  464. return SUBMIT_ARCHIVE_DOT_ORG
  465. def archive_dot_org(link_dir, link, timeout=TIMEOUT):
  466. """submit site to archive.org for archiving via their service, save returned archive url"""
  467. output = 'archive.org.txt'
  468. archive_org_url = None
  469. submit_url = 'https://web.archive.org/save/{}'.format(link['url'])
  470. cmd = [
  471. CURL_BINARY,
  472. '--location',
  473. '--head',
  474. '--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
  475. '--max-time', str(timeout),
  476. *(() if CHECK_SSL_VALIDITY else ('--insecure',)),
  477. submit_url,
  478. ]
  479. status = 'succeeded'
  480. timer = TimedProgress(timeout, prefix=' ')
  481. try:
  482. result = run(cmd, stdout=PIPE, stderr=DEVNULL, cwd=link_dir, timeout=timeout)
  483. content_location, errors = parse_archive_dot_org_response(result.stdout)
  484. if content_location:
  485. archive_org_url = 'https://web.archive.org{}'.format(content_location[0])
  486. elif len(errors) == 1 and 'RobotAccessControlException' in errors[0]:
  487. archive_org_url = None
  488. # raise ArchiveError('Archive.org denied by {}/robots.txt'.format(domain(link['url'])))
  489. elif errors:
  490. raise ArchiveError(', '.join(errors))
  491. else:
  492. raise ArchiveError('Failed to find "content-location" URL header in Archive.org response.')
  493. except Exception as err:
  494. status = 'failed'
  495. output = err
  496. finally:
  497. timer.end()
  498. if not isinstance(output, Exception):
  499. # instead of writing None when archive.org rejects the url write the
  500. # url to resubmit it to archive.org. This is so when the user visits
  501. # the URL in person, it will attempt to re-archive it, and it'll show the
  502. # nicer error message explaining why the url was rejected if it fails.
  503. archive_org_url = archive_org_url or submit_url
  504. with open(os.path.join(link_dir, output), 'w', encoding='utf-8') as f:
  505. f.write(archive_org_url)
  506. chmod_file('archive.org.txt', cwd=link_dir)
  507. output = archive_org_url
  508. return {
  509. 'cmd': cmd,
  510. 'pwd': link_dir,
  511. 'output': output,
  512. 'status': status,
  513. **timer.stats,
  514. }
  515. def parse_archive_dot_org_response(response):
  516. # Parse archive.org response headers
  517. headers = defaultdict(list)
  518. # lowercase all the header names and store in dict
  519. for header in response.splitlines():
  520. if b':' not in header or not header.strip():
  521. continue
  522. name, val = header.decode().split(':', 1)
  523. headers[name.lower().strip()].append(val.strip())
  524. # Get successful archive url in "content-location" header or any errors
  525. content_location = headers['content-location']
  526. errors = headers['x-archive-wayback-runtime-error']
  527. return content_location, errors