html.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. __package__ = 'archivebox.index'
  2. from pathlib import Path
  3. from datetime import datetime, timezone
  4. from collections import defaultdict
  5. from typing import List, Optional, Iterator, Mapping
  6. from django.utils.html import format_html, mark_safe
  7. from django.core.cache import cache
  8. from .schema import Link
  9. from ..system import atomic_write
  10. from ..logging_util import printable_filesize
  11. from ..util import (
  12. enforce_types,
  13. ts_to_date_str,
  14. urlencode,
  15. htmlencode,
  16. urldecode,
  17. )
  18. from ..config import (
  19. OUTPUT_DIR,
  20. VERSION,
  21. FOOTER_INFO,
  22. HTML_INDEX_FILENAME,
  23. SAVE_ARCHIVE_DOT_ORG,
  24. PREVIEW_ORIGINALS,
  25. )
  26. MAIN_INDEX_TEMPLATE = 'static_index.html'
  27. MINIMAL_INDEX_TEMPLATE = 'minimal_index.html'
  28. LINK_DETAILS_TEMPLATE = 'snapshot.html'
  29. TITLE_LOADING_MSG = 'Not yet archived...'
  30. ### Main Links Index
  31. @enforce_types
  32. def parse_html_main_index(out_dir: Path=OUTPUT_DIR) -> Iterator[str]:
  33. """parse an archive index html file and return the list of urls"""
  34. index_path = Path(out_dir) / HTML_INDEX_FILENAME
  35. if index_path.exists():
  36. with open(index_path, 'r', encoding='utf-8') as f:
  37. for line in f:
  38. if 'class="link-url"' in line:
  39. yield line.split('"')[1]
  40. return ()
  41. @enforce_types
  42. def generate_index_from_links(links: List[Link], with_headers: bool):
  43. if with_headers:
  44. output = main_index_template(links)
  45. else:
  46. output = main_index_template(links, template=MINIMAL_INDEX_TEMPLATE)
  47. return output
  48. @enforce_types
  49. def main_index_template(links: List[Link], template: str=MAIN_INDEX_TEMPLATE) -> str:
  50. """render the template for the entire main index"""
  51. return render_django_template(template, {
  52. 'version': VERSION,
  53. 'git_sha': VERSION, # not used anymore, but kept for backwards compatibility
  54. 'num_links': str(len(links)),
  55. 'date_updated': datetime.now(timezone.utc).strftime('%Y-%m-%d'),
  56. 'time_updated': datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M'),
  57. 'links': [link._asdict(extended=True) for link in links],
  58. 'FOOTER_INFO': FOOTER_INFO,
  59. })
  60. ### Link Details Index
  61. @enforce_types
  62. def write_html_link_details(link: Link, out_dir: Optional[str]=None) -> None:
  63. out_dir = out_dir or link.link_dir
  64. rendered_html = link_details_template(link)
  65. atomic_write(str(Path(out_dir) / HTML_INDEX_FILENAME), rendered_html)
  66. @enforce_types
  67. def link_details_template(link: Link) -> str:
  68. from ..extractors.wget import wget_output_path
  69. link_info = link._asdict(extended=True)
  70. return render_django_template(LINK_DETAILS_TEMPLATE, {
  71. **link_info,
  72. **link_info['canonical'],
  73. 'title': htmlencode(
  74. link.title
  75. or (link.base_url if link.is_archived else TITLE_LOADING_MSG)
  76. ),
  77. 'url_str': htmlencode(urldecode(link.base_url)),
  78. 'archive_url': urlencode(
  79. wget_output_path(link)
  80. or (link.domain if link.is_archived else '')
  81. ) or 'about:blank',
  82. 'extension': link.extension or 'html',
  83. 'tags': link.tags or 'untagged',
  84. 'size': printable_filesize(link.archive_size) if link.archive_size else 'pending',
  85. 'status': 'archived' if link.is_archived else 'not yet archived',
  86. 'status_color': 'success' if link.is_archived else 'danger',
  87. 'oldest_archive_date': ts_to_date_str(link.oldest_archive_date),
  88. 'SAVE_ARCHIVE_DOT_ORG': SAVE_ARCHIVE_DOT_ORG,
  89. 'PREVIEW_ORIGINALS': PREVIEW_ORIGINALS,
  90. })
  91. @enforce_types
  92. def render_django_template(template: str, context: Mapping[str, str]) -> str:
  93. """render a given html template string with the given template content"""
  94. from django.template.loader import render_to_string
  95. return render_to_string(template, context)
  96. def snapshot_icons(snapshot) -> str:
  97. cache_key = f'{snapshot.id}-{(snapshot.updated or snapshot.added).timestamp()}-snapshot-icons'
  98. def calc_snapshot_icons():
  99. from core.models import EXTRACTORS
  100. # start = datetime.now(timezone.utc)
  101. archive_results = snapshot.archiveresult_set.filter(status="succeeded", output__isnull=False)
  102. link = snapshot.as_link()
  103. path = link.archive_path
  104. canon = link.canonical_outputs()
  105. output = ""
  106. output_template = '<a href="/{}/{}" class="exists-{}" title="{}">{}</a> &nbsp;'
  107. icons = {
  108. "singlefile": "❶",
  109. "wget": "🆆",
  110. "dom": "🅷",
  111. "pdf": "📄",
  112. "screenshot": "💻",
  113. "media": "📼",
  114. "git": "🅶",
  115. "archive_org": "🏛",
  116. "readability": "🆁",
  117. "mercury": "🅼",
  118. "warc": "📦"
  119. }
  120. exclude = ["favicon", "title", "headers", "htmltotext", "archive_org"]
  121. # Missing specific entry for WARC
  122. extractor_outputs = defaultdict(lambda: None)
  123. for extractor, _ in EXTRACTORS:
  124. for result in archive_results:
  125. if result.extractor == extractor and result:
  126. extractor_outputs[extractor] = result
  127. for extractor, _ in EXTRACTORS:
  128. if extractor not in exclude:
  129. existing = extractor_outputs[extractor] and extractor_outputs[extractor].status == 'succeeded' and extractor_outputs[extractor].output
  130. # Check filesystsem to see if anything is actually present (too slow, needs optimization/caching)
  131. # if existing:
  132. # existing = (Path(path) / existing)
  133. # if existing.is_file():
  134. # existing = True
  135. # elif existing.is_dir():
  136. # existing = any(existing.glob('*.*'))
  137. output += format_html(output_template, path, canon[f"{extractor}_path"], str(bool(existing)),
  138. extractor, icons.get(extractor, "?"))
  139. if extractor == "wget":
  140. # warc isn't technically it's own extractor, so we have to add it after wget
  141. # get from db (faster but less thurthful)
  142. exists = extractor_outputs[extractor] and extractor_outputs[extractor].status == 'succeeded' and extractor_outputs[extractor].output
  143. # get from filesystem (slower but more accurate)
  144. # exists = list((Path(path) / canon["warc_path"]).glob("*.warc.gz"))
  145. output += format_html(output_template, path, canon["warc_path"], str(bool(exists)), "warc", icons.get("warc", "?"))
  146. if extractor == "archive_org":
  147. # The check for archive_org is different, so it has to be handled separately
  148. # get from db (faster)
  149. exists = extractor in extractor_outputs and extractor_outputs[extractor] and extractor_outputs[extractor].status == 'succeeded' and extractor_outputs[extractor].output
  150. # get from filesystem (slower)
  151. # target_path = Path(path) / "archive.org.txt"
  152. # exists = target_path.exists()
  153. output += '<a href="{}" class="exists-{}" title="{}">{}</a> '.format(canon["archive_org_path"], str(exists),
  154. "archive_org", icons.get("archive_org", "?"))
  155. result = format_html('<span class="files-icons" style="font-size: 1.1em; opacity: 0.8; min-width: 240px; display: inline-block">{}<span>', mark_safe(output))
  156. # end = datetime.now(timezone.utc)
  157. # print(((end - start).total_seconds()*1000) // 1, 'ms')
  158. return result
  159. return cache.get_or_set(cache_key, calc_snapshot_icons)
  160. # return calc_snapshot_icons()