util.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. import os
  2. import re
  3. import sys
  4. import time
  5. import json
  6. import urllib.request
  7. from decimal import Decimal
  8. from urllib.parse import quote
  9. from datetime import datetime
  10. from subprocess import run, PIPE, DEVNULL
  11. from multiprocessing import Process
  12. from config import (
  13. IS_TTY,
  14. OUTPUT_PERMISSIONS,
  15. REPO_DIR,
  16. SOURCES_DIR,
  17. OUTPUT_DIR,
  18. ARCHIVE_DIR,
  19. TIMEOUT,
  20. TERM_WIDTH,
  21. SHOW_PROGRESS,
  22. ANSI,
  23. CHROME_BINARY,
  24. FETCH_WGET,
  25. FETCH_PDF,
  26. FETCH_SCREENSHOT,
  27. FETCH_DOM,
  28. FETCH_FAVICON,
  29. FETCH_MEDIA,
  30. SUBMIT_ARCHIVE_DOT_ORG,
  31. )
  32. # URL helpers
  33. without_scheme = lambda url: url.replace('http://', '').replace('https://', '').replace('ftp://', '')
  34. without_query = lambda url: url.split('?', 1)[0]
  35. without_hash = lambda url: url.split('#', 1)[0]
  36. without_path = lambda url: url.split('/', 1)[0]
  37. domain = lambda url: without_hash(without_query(without_path(without_scheme(url))))
  38. base_url = lambda url: without_scheme(url) # uniq base url used to dedupe links
  39. short_ts = lambda ts: ts.split('.')[0]
  40. URL_REGEX = 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
  41. def check_dependencies():
  42. """Check that all necessary dependencies are installed, and have valid versions"""
  43. python_vers = float('{}.{}'.format(sys.version_info.major, sys.version_info.minor))
  44. if python_vers < 3.5:
  45. print('{}[X] Python version is not new enough: {} (>3.5 is required){}'.format(ANSI['red'], python_vers, ANSI['reset']))
  46. print(' See https://github.com/pirate/ArchiveBox#troubleshooting for help upgrading your Python installation.')
  47. raise SystemExit(1)
  48. if FETCH_PDF or FETCH_SCREENSHOT or FETCH_DOM:
  49. if run(['which', CHROME_BINARY], stdout=DEVNULL).returncode:
  50. print('{}[X] Missing dependency: {}{}'.format(ANSI['red'], CHROME_BINARY, ANSI['reset']))
  51. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format(CHROME_BINARY))
  52. print(' See https://github.com/pirate/ArchiveBox for help.')
  53. raise SystemExit(1)
  54. # parse chrome --version e.g. Google Chrome 61.0.3114.0 canary / Chromium 59.0.3029.110 built on Ubuntu, running on Ubuntu 16.04
  55. try:
  56. result = run([CHROME_BINARY, '--version'], stdout=PIPE)
  57. version_str = result.stdout.decode('utf-8')
  58. version_lines = re.sub("(Google Chrome|Chromium) (\\d+?)\\.(\\d+?)\\.(\\d+?).*?$", "\\2", version_str).split('\n')
  59. version = [l for l in version_lines if l.isdigit()][-1]
  60. if int(version) < 59:
  61. print(version_lines)
  62. print('{red}[X] Chrome version must be 59 or greater for headless PDF, screenshot, and DOM saving{reset}'.format(**ANSI))
  63. print(' See https://github.com/pirate/ArchiveBox for help.')
  64. raise SystemExit(1)
  65. except (IndexError, TypeError, OSError):
  66. print('{red}[X] Failed to parse Chrome version, is it installed properly?{reset}'.format(**ANSI))
  67. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format(CHROME_BINARY))
  68. print(' See https://github.com/pirate/ArchiveBox for help.')
  69. raise SystemExit(1)
  70. if FETCH_WGET:
  71. if run(['which', 'wget'], stdout=DEVNULL).returncode or run(['wget', '--version'], stdout=DEVNULL).returncode:
  72. print('{red}[X] Missing dependency: wget{reset}'.format(**ANSI))
  73. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('wget'))
  74. print(' See https://github.com/pirate/ArchiveBox for help.')
  75. raise SystemExit(1)
  76. if FETCH_FAVICON or SUBMIT_ARCHIVE_DOT_ORG:
  77. if run(['which', 'curl'], stdout=DEVNULL).returncode or run(['curl', '--version'], stdout=DEVNULL).returncode:
  78. print('{red}[X] Missing dependency: curl{reset}'.format(**ANSI))
  79. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('curl'))
  80. print(' See https://github.com/pirate/ArchiveBox for help.')
  81. raise SystemExit(1)
  82. if FETCH_MEDIA:
  83. if run(['which', 'youtube-dl'], stdout=DEVNULL).returncode or run(['youtube-dl', '--version'], stdout=DEVNULL).returncode:
  84. print('{red}[X] Missing dependency: youtube-dl{reset}'.format(**ANSI))
  85. print(' Run ./setup.sh, then confirm it was installed with: {} --version'.format('youtube-dl'))
  86. print(' See https://github.com/pirate/ArchiveBox for help.')
  87. raise SystemExit(1)
  88. def chmod_file(path, cwd='.', permissions=OUTPUT_PERMISSIONS, timeout=30):
  89. """chmod -R <permissions> <cwd>/<path>"""
  90. if not os.path.exists(os.path.join(cwd, path)):
  91. raise Exception('Failed to chmod: {} does not exist (did the previous step fail?)'.format(path))
  92. chmod_result = run(['chmod', '-R', permissions, path], cwd=cwd, stdout=DEVNULL, stderr=PIPE, timeout=timeout)
  93. if chmod_result.returncode == 1:
  94. print(' ', chmod_result.stderr.decode())
  95. raise Exception('Failed to chmod {}/{}'.format(cwd, path))
  96. def progress(seconds=TIMEOUT, prefix=''):
  97. """Show a (subprocess-controlled) progress bar with a <seconds> timeout,
  98. returns end() function to instantly finish the progress
  99. """
  100. if not SHOW_PROGRESS:
  101. return lambda: None
  102. chunk = '█' if sys.stdout.encoding == 'UTF-8' else '#'
  103. chunks = TERM_WIDTH - len(prefix) - 20 # number of progress chunks to show (aka max bar width)
  104. def progress_bar(seconds, prefix):
  105. """show timer in the form of progress bar, with percentage and seconds remaining"""
  106. try:
  107. for s in range(seconds * chunks):
  108. progress = s / chunks / seconds * 100
  109. bar_width = round(progress/(100/chunks))
  110. # ████████████████████ 0.9% (1/60sec)
  111. sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)'.format(
  112. prefix,
  113. ANSI['green'],
  114. (chunk * bar_width).ljust(chunks),
  115. ANSI['reset'],
  116. round(progress, 1),
  117. round(s/chunks),
  118. seconds,
  119. ))
  120. sys.stdout.flush()
  121. time.sleep(1 / chunks)
  122. # ██████████████████████████████████ 100.0% (60/60sec)
  123. sys.stdout.write('\r{0}{1}{2}{3} {4}% ({5}/{6}sec)\n'.format(
  124. prefix,
  125. ANSI['red'],
  126. chunk * chunks,
  127. ANSI['reset'],
  128. 100.0,
  129. seconds,
  130. seconds,
  131. ))
  132. sys.stdout.flush()
  133. except KeyboardInterrupt:
  134. print()
  135. pass
  136. p = Process(target=progress_bar)
  137. p.start()
  138. def end():
  139. """immediately finish progress and clear the progressbar line"""
  140. nonlocal p
  141. if p is None: # protect from double termination
  142. return
  143. p.terminate()
  144. p = None
  145. sys.stdout.write('\r{}{}\r'.format((' ' * TERM_WIDTH), ANSI['reset'])) # clear whole terminal line
  146. sys.stdout.flush()
  147. return end
  148. def pretty_path(path):
  149. """convert paths like .../ArchiveBox/archivebox/../output/abc into output/abc"""
  150. return path.replace(REPO_DIR + '/', '')
  151. def save_source(raw_text):
  152. if not os.path.exists(SOURCES_DIR):
  153. os.makedirs(SOURCES_DIR)
  154. ts = str(datetime.now().timestamp()).split('.', 1)[0]
  155. source_path = os.path.join(SOURCES_DIR, '{}-{}.txt'.format('stdin', ts))
  156. with open(source_path, 'w', encoding='utf-8') as f:
  157. f.write(raw_text)
  158. return source_path
  159. def download_url(url):
  160. """download a given url's content into downloads/domain.txt"""
  161. if not os.path.exists(SOURCES_DIR):
  162. os.makedirs(SOURCES_DIR)
  163. ts = str(datetime.now().timestamp()).split('.', 1)[0]
  164. source_path = os.path.join(SOURCES_DIR, '{}-{}.txt'.format(domain(url), ts))
  165. print('[*] [{}] Downloading {} > {}'.format(
  166. datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
  167. url,
  168. pretty_path(source_path),
  169. ))
  170. end = progress(TIMEOUT, prefix=' ')
  171. try:
  172. downloaded_xml = urllib.request.urlopen(url).read().decode('utf-8')
  173. end()
  174. except Exception as e:
  175. end()
  176. print('[!] Failed to download {}\n'.format(url))
  177. print(' ', e)
  178. raise SystemExit(1)
  179. with open(source_path, 'w', encoding='utf-8') as f:
  180. f.write(downloaded_xml)
  181. return source_path
  182. def fetch_page_title(url, default=True):
  183. """Attempt to guess a page's title by downloading the html"""
  184. if default is True:
  185. default = url
  186. try:
  187. html_content = urllib.request.urlopen(url).read().decode('utf-8')
  188. match = re.search('<title>(.*?)</title>', html_content)
  189. return match.group(1) if match else default or None
  190. except Exception:
  191. if default is False:
  192. raise
  193. return default
  194. def str_between(string, start, end=None):
  195. """(<abc>12345</def>, <abc>, </def>) -> 12345"""
  196. content = string.split(start, 1)[-1]
  197. if end is not None:
  198. content = content.rsplit(end, 1)[0]
  199. return content
  200. def get_link_type(link):
  201. """Certain types of links need to be handled specially, this figures out when that's the case"""
  202. if link['base_url'].endswith('.pdf'):
  203. return 'PDF'
  204. elif link['base_url'].rsplit('.', 1) in ('pdf', 'png', 'jpg', 'jpeg', 'svg', 'bmp', 'gif', 'tiff', 'webp'):
  205. return 'image'
  206. elif 'wikipedia.org' in link['domain']:
  207. return 'wiki'
  208. elif 'youtube.com' in link['domain']:
  209. return 'youtube'
  210. elif 'soundcloud.com' in link['domain']:
  211. return 'soundcloud'
  212. elif 'youku.com' in link['domain']:
  213. return 'youku'
  214. elif 'vimeo.com' in link['domain']:
  215. return 'vimeo'
  216. return None
  217. def merge_links(a, b):
  218. """deterministially merge two links, favoring longer field values over shorter,
  219. and "cleaner" values over worse ones.
  220. """
  221. longer = lambda key: a[key] if len(a[key]) > len(b[key]) else b[key]
  222. earlier = lambda key: a[key] if a[key] < b[key] else b[key]
  223. url = longer('url')
  224. longest_title = longer('title')
  225. cleanest_title = a['title'] if '://' not in a['title'] else b['title']
  226. link = {
  227. 'timestamp': earlier('timestamp'),
  228. 'url': url,
  229. 'domain': domain(url),
  230. 'base_url': base_url(url),
  231. 'tags': longer('tags'),
  232. 'title': longest_title if '://' not in longest_title else cleanest_title,
  233. 'sources': list(set(a.get('sources', []) + b.get('sources', []))),
  234. }
  235. link['type'] = get_link_type(link)
  236. return link
  237. def find_link(folder, links):
  238. """for a given archive folder, find the corresponding link object in links"""
  239. url = parse_url(folder)
  240. if url:
  241. for link in links:
  242. if (link['base_url'] in url) or (url in link['url']):
  243. return link
  244. timestamp = folder.split('.')[0]
  245. for link in links:
  246. if link['timestamp'].startswith(timestamp):
  247. if link['domain'] in os.listdir(os.path.join(ARCHIVE_DIR, folder)):
  248. return link # careful now, this isn't safe for most ppl
  249. if link['domain'] in parse_url(folder):
  250. return link
  251. return None
  252. def parse_url(folder):
  253. """for a given archive folder, figure out what url it's for"""
  254. link_json = os.path.join(ARCHIVE_DIR, folder, 'index.json')
  255. if os.path.exists(link_json):
  256. with open(link_json, 'r') as f:
  257. try:
  258. link_json = f.read().strip()
  259. if link_json:
  260. link = json.loads(link_json)
  261. return link['base_url']
  262. except ValueError:
  263. print('File contains invalid JSON: {}!'.format(link_json))
  264. archive_org_txt = os.path.join(ARCHIVE_DIR, folder, 'archive.org.txt')
  265. if os.path.exists(archive_org_txt):
  266. with open(archive_org_txt, 'r') as f:
  267. original_link = f.read().strip().split('/http', 1)[-1]
  268. with_scheme = 'http{}'.format(original_link)
  269. return with_scheme
  270. return ''
  271. def manually_merge_folders(source, target):
  272. """prompt for user input to resolve a conflict between two archive folders"""
  273. if not IS_TTY:
  274. return
  275. fname = lambda path: path.split('/')[-1]
  276. print(' {} and {} have conflicting files, which do you want to keep?'.format(fname(source), fname(target)))
  277. print(' - [enter]: do nothing (keep both)')
  278. print(' - a: prefer files from {}'.format(source))
  279. print(' - b: prefer files from {}'.format(target))
  280. print(' - q: quit and resolve the conflict manually')
  281. try:
  282. answer = input('> ').strip().lower()
  283. except KeyboardInterrupt:
  284. answer = 'q'
  285. assert answer in ('', 'a', 'b', 'q'), 'Invalid choice.'
  286. if answer == 'q':
  287. print('\nJust run ArchiveBox again to pick up where you left off.')
  288. raise SystemExit(0)
  289. elif answer == '':
  290. return
  291. files_in_source = set(os.listdir(source))
  292. files_in_target = set(os.listdir(target))
  293. for file in files_in_source:
  294. if file in files_in_target:
  295. to_delete = target if answer == 'a' else source
  296. run(['rm', '-Rf', os.path.join(to_delete, file)])
  297. run(['mv', os.path.join(source, file), os.path.join(target, file)])
  298. if not set(os.listdir(source)):
  299. run(['rm', '-Rf', source])
  300. def fix_folder_path(archive_path, link_folder, link):
  301. """given a folder, merge it to the canonical 'correct' path for the given link object"""
  302. source = os.path.join(archive_path, link_folder)
  303. target = os.path.join(archive_path, link['timestamp'])
  304. url_in_folder = parse_url(source)
  305. if not (url_in_folder in link['base_url']
  306. or link['base_url'] in url_in_folder):
  307. raise ValueError('The link does not match the url for this folder.')
  308. if not os.path.exists(target):
  309. # target doesn't exist so nothing needs merging, simply move A to B
  310. run(['mv', source, target])
  311. else:
  312. # target folder exists, check for conflicting files and attempt manual merge
  313. files_in_source = set(os.listdir(source))
  314. files_in_target = set(os.listdir(target))
  315. conflicting_files = files_in_source & files_in_target
  316. if not conflicting_files:
  317. for file in files_in_source:
  318. run(['mv', os.path.join(source, file), os.path.join(target, file)])
  319. if os.path.exists(source):
  320. files_in_source = set(os.listdir(source))
  321. if files_in_source:
  322. manually_merge_folders(source, target)
  323. else:
  324. run(['rm', '-R', source])
  325. def migrate_data():
  326. # migrate old folder to new OUTPUT folder
  327. old_dir = os.path.join(REPO_DIR, 'html')
  328. if os.path.exists(old_dir):
  329. print('[!] WARNING: Moved old output folder "html" to new location: {}'.format(OUTPUT_DIR))
  330. run(['mv', old_dir, OUTPUT_DIR], timeout=10)
  331. def cleanup_archive(archive_path, links):
  332. """move any incorrectly named folders to their canonical locations"""
  333. # for each folder that exists, see if we can match it up with a known good link
  334. # if we can, then merge the two folders (TODO: if not, move it to lost & found)
  335. unmatched = []
  336. bad_folders = []
  337. if not os.path.exists(archive_path):
  338. return
  339. for folder in os.listdir(archive_path):
  340. try:
  341. files = os.listdir(os.path.join(archive_path, folder))
  342. except NotADirectoryError:
  343. continue
  344. if files:
  345. link = find_link(folder, links)
  346. if link is None:
  347. unmatched.append(folder)
  348. continue
  349. if folder != link['timestamp']:
  350. bad_folders.append((folder, link))
  351. else:
  352. # delete empty folders
  353. run(['rm', '-R', os.path.join(archive_path, folder)])
  354. if bad_folders and IS_TTY and input('[!] Cleanup archive? y/[n]: ') == 'y':
  355. print('[!] Fixing {} improperly named folders in archive...'.format(len(bad_folders)))
  356. for folder, link in bad_folders:
  357. fix_folder_path(archive_path, folder, link)
  358. elif bad_folders:
  359. print('[!] Warning! {} folders need to be merged, fix by running ArchiveBox.'.format(len(bad_folders)))
  360. if unmatched:
  361. print('[!] Warning! {} unrecognized folders in html/archive/'.format(len(unmatched)))
  362. print(' '+ '\n '.join(unmatched))
  363. def wget_output_path(link, look_in=None):
  364. """calculate the path to the wgetted .html file, since wget may
  365. adjust some paths to be different than the base_url path.
  366. See docs on wget --adjust-extension (-E)
  367. """
  368. # if we have it stored, always prefer the actual output path to computed one
  369. if link.get('latest', {}).get('wget'):
  370. return link['latest']['wget']
  371. urlencode = lambda s: quote(s, encoding='utf-8', errors='replace')
  372. if link['type'] in ('PDF', 'image'):
  373. return urlencode(link['base_url'])
  374. # Since the wget algorithm to for -E (appending .html) is incredibly complex
  375. # instead of trying to emulate it here, we just look in the output folder
  376. # to see what html file wget actually created as the output
  377. wget_folder = link['base_url'].rsplit('/', 1)[0].split('/')
  378. look_in = os.path.join(ARCHIVE_DIR, link['timestamp'], *wget_folder)
  379. if look_in and os.path.exists(look_in):
  380. html_files = [
  381. f for f in os.listdir(look_in)
  382. if re.search(".+\\.[Hh][Tt][Mm][Ll]?$", f, re.I | re.M)
  383. ]
  384. if html_files:
  385. return urlencode(os.path.join(*wget_folder, html_files[0]))
  386. return None
  387. # If finding the actual output file didn't work, fall back to the buggy
  388. # implementation of the wget .html appending algorithm
  389. # split_url = link['url'].split('#', 1)
  390. # query = ('%3F' + link['url'].split('?', 1)[-1]) if '?' in link['url'] else ''
  391. # if re.search(".+\\.[Hh][Tt][Mm][Ll]?$", split_url[0], re.I | re.M):
  392. # # already ends in .html
  393. # return urlencode(link['base_url'])
  394. # else:
  395. # # .html needs to be appended
  396. # without_scheme = split_url[0].split('://', 1)[-1].split('?', 1)[0]
  397. # if without_scheme.endswith('/'):
  398. # if query:
  399. # return urlencode('#'.join([without_scheme + 'index.html' + query + '.html', *split_url[1:]]))
  400. # return urlencode('#'.join([without_scheme + 'index.html', *split_url[1:]]))
  401. # else:
  402. # if query:
  403. # return urlencode('#'.join([without_scheme + '/index.html' + query + '.html', *split_url[1:]]))
  404. # elif '/' in without_scheme:
  405. # return urlencode('#'.join([without_scheme + '.html', *split_url[1:]]))
  406. # return urlencode(link['base_url'] + '/index.html')
  407. def derived_link_info(link):
  408. """extend link info with the archive urls and other derived data"""
  409. link_info = {
  410. **link,
  411. 'date': datetime.fromtimestamp(Decimal(link['timestamp'])).strftime('%Y-%m-%d %H:%M'),
  412. 'google_favicon_url': 'https://www.google.com/s2/favicons?domain={domain}'.format(**link),
  413. 'favicon_url': 'archive/{timestamp}/favicon.ico'.format(**link),
  414. 'files_url': 'archive/{timestamp}/index.html'.format(**link),
  415. 'archive_url': 'archive/{}/{}'.format(link['timestamp'], wget_output_path(link) or 'index.html'),
  416. 'pdf_link': 'archive/{timestamp}/output.pdf'.format(**link),
  417. 'screenshot_link': 'archive/{timestamp}/screenshot.png'.format(**link),
  418. 'dom_link': 'archive/{timestamp}/output.html'.format(**link),
  419. 'archive_org_url': 'https://web.archive.org/web/{base_url}'.format(**link),
  420. }
  421. # PDF and images are handled slightly differently
  422. # wget, screenshot, & pdf urls all point to the same file
  423. if link['type'] in ('PDF', 'image'):
  424. link_info.update({
  425. 'archive_url': 'archive/{timestamp}/{base_url}'.format(**link),
  426. 'pdf_link': 'archive/{timestamp}/{base_url}'.format(**link),
  427. 'screenshot_link': 'archive/{timestamp}/{base_url}'.format(**link),
  428. 'dom_link': 'archive/{timestamp}/{base_url}'.format(**link),
  429. 'title': '{title} ({type})'.format(**link),
  430. })
  431. return link_info