html.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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.pk}-{(snapshot.updated or snapshot.added).timestamp()}-snapshot-icons'
  98. def calc_snapshot_icons():
  99. from core.models import ArchiveResult
  100. # start = datetime.now(timezone.utc)
  101. if hasattr(snapshot, '_prefetched_objects_cache') and 'archiveresult_set' in snapshot._prefetched_objects_cache:
  102. archive_results = [
  103. result
  104. for result in snapshot.archiveresult_set.all()
  105. if result.status == "succeeded" and result.output
  106. ]
  107. else:
  108. archive_results = snapshot.archiveresult_set.filter(status="succeeded", output__isnull=False)
  109. link = snapshot.as_link()
  110. path = link.archive_path
  111. canon = link.canonical_outputs()
  112. output = ""
  113. output_template = '<a href="/{}/{}" class="exists-{}" title="{}">{}</a> &nbsp;'
  114. icons = {
  115. "singlefile": "❶",
  116. "wget": "🆆",
  117. "dom": "🅷",
  118. "pdf": "📄",
  119. "screenshot": "💻",
  120. "media": "📼",
  121. "git": "🅶",
  122. "archive_org": "🏛",
  123. "readability": "🆁",
  124. "mercury": "🅼",
  125. "warc": "📦"
  126. }
  127. exclude = ["favicon", "title", "headers", "htmltotext", "archive_org"]
  128. # Missing specific entry for WARC
  129. extractor_outputs = defaultdict(lambda: None)
  130. for extractor, _ in ArchiveResult.EXTRACTOR_CHOICES:
  131. for result in archive_results:
  132. if result.extractor == extractor and result:
  133. extractor_outputs[extractor] = result
  134. for extractor, _ in ArchiveResult.EXTRACTOR_CHOICES:
  135. if extractor not in exclude:
  136. existing = extractor_outputs[extractor] and extractor_outputs[extractor].status == 'succeeded' and extractor_outputs[extractor].output
  137. # Check filesystsem to see if anything is actually present (too slow, needs optimization/caching)
  138. # if existing:
  139. # existing = (Path(path) / existing)
  140. # if existing.is_file():
  141. # existing = True
  142. # elif existing.is_dir():
  143. # existing = any(existing.glob('*.*'))
  144. output += format_html(output_template, path, canon[f"{extractor}_path"], str(bool(existing)),
  145. extractor, icons.get(extractor, "?"))
  146. if extractor == "wget":
  147. # warc isn't technically it's own extractor, so we have to add it after wget
  148. # get from db (faster but less thurthful)
  149. exists = extractor_outputs[extractor] and extractor_outputs[extractor].status == 'succeeded' and extractor_outputs[extractor].output
  150. # get from filesystem (slower but more accurate)
  151. # exists = list((Path(path) / canon["warc_path"]).glob("*.warc.gz"))
  152. output += format_html(output_template, path, canon["warc_path"], str(bool(exists)), "warc", icons.get("warc", "?"))
  153. if extractor == "archive_org":
  154. # The check for archive_org is different, so it has to be handled separately
  155. # get from db (faster)
  156. exists = extractor in extractor_outputs and extractor_outputs[extractor] and extractor_outputs[extractor].status == 'succeeded' and extractor_outputs[extractor].output
  157. # get from filesystem (slower)
  158. # target_path = Path(path) / "archive.org.txt"
  159. # exists = target_path.exists()
  160. output += '<a href="{}" class="exists-{}" title="{}">{}</a> '.format(canon["archive_org_path"], str(exists),
  161. "archive_org", icons.get("archive_org", "?"))
  162. 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))
  163. # end = datetime.now(timezone.utc)
  164. # print(((end - start).total_seconds()*1000) // 1, 'ms')
  165. return result
  166. return cache.get_or_set(cache_key, calc_snapshot_icons)
  167. # return calc_snapshot_icons()