json.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. __package__ = 'archivebox.index'
  2. import os
  3. import sys
  4. import json as pyjson
  5. from pathlib import Path
  6. from datetime import datetime, timezone
  7. from typing import List, Optional, Iterator, Any, Union
  8. from archivebox.config import VERSION, DATA_DIR, CONSTANTS, SERVER_CONFIG, SHELL_CONFIG
  9. from .schema import Link
  10. from archivebox.misc.system import atomic_write
  11. from ..util import enforce_types
  12. @enforce_types
  13. def generate_json_index_from_links(links: List[Link], with_headers: bool):
  14. from django.conf import settings
  15. MAIN_INDEX_HEADER = {
  16. 'info': 'This is an index of site data archived by ArchiveBox: The self-hosted web archive.',
  17. 'schema': 'archivebox.index.json',
  18. 'copyright_info': SERVER_CONFIG.FOOTER_INFO,
  19. 'meta': {
  20. 'project': 'ArchiveBox',
  21. 'version': VERSION,
  22. 'git_sha': VERSION, # not used anymore, but kept for backwards compatibility
  23. 'website': 'https://ArchiveBox.io',
  24. 'docs': 'https://github.com/ArchiveBox/ArchiveBox/wiki',
  25. 'source': 'https://github.com/ArchiveBox/ArchiveBox',
  26. 'issues': 'https://github.com/ArchiveBox/ArchiveBox/issues',
  27. 'dependencies': settings.BINARIES.to_dict(),
  28. },
  29. }
  30. if with_headers:
  31. output = {
  32. **MAIN_INDEX_HEADER,
  33. 'num_links': len(links),
  34. 'updated': datetime.now(timezone.utc),
  35. 'last_run_cmd': sys.argv,
  36. 'links': links,
  37. }
  38. else:
  39. output = links
  40. return to_json(output, indent=4, sort_keys=True)
  41. @enforce_types
  42. def parse_json_main_index(out_dir: Path=DATA_DIR) -> Iterator[Link]:
  43. """parse an archive index json file and return the list of links"""
  44. index_path = Path(out_dir) / CONSTANTS.JSON_INDEX_FILENAME
  45. if index_path.exists():
  46. with open(index_path, 'r', encoding='utf-8') as f:
  47. try:
  48. links = pyjson.load(f)['links']
  49. if links:
  50. Link.from_json(links[0])
  51. except Exception as err:
  52. print(" {lightyellow}! Found an index.json in the project root but couldn't load links from it: {} {}".format(
  53. err.__class__.__name__,
  54. err,
  55. **SHELL_CONFIG.ANSI,
  56. ))
  57. return ()
  58. for link_json in links:
  59. try:
  60. yield Link.from_json(link_json)
  61. except KeyError:
  62. try:
  63. detail_index_path = CONSTANTS.ARCHIVE_DIR / link_json['timestamp']
  64. yield parse_json_link_details(str(detail_index_path))
  65. except KeyError:
  66. # as a last effort, try to guess the missing values out of existing ones
  67. try:
  68. yield Link.from_json(link_json, guess=True)
  69. except KeyError:
  70. # print(" {lightyellow}! Failed to load the index.json from {}".format(detail_index_path, **ANSI))
  71. continue
  72. return ()
  73. ### Link Details Index
  74. @enforce_types
  75. def write_json_link_details(link: Link, out_dir: Optional[str]=None) -> None:
  76. """write a json file with some info about the link"""
  77. out_dir = out_dir or link.link_dir
  78. path = Path(out_dir) / CONSTANTS.JSON_INDEX_FILENAME
  79. atomic_write(str(path), link._asdict(extended=True))
  80. @enforce_types
  81. def parse_json_link_details(out_dir: Union[Path, str], guess: bool=False) -> Optional[Link]:
  82. """load the json link index from a given directory"""
  83. existing_index = Path(out_dir) / CONSTANTS.JSON_INDEX_FILENAME
  84. if existing_index.exists():
  85. with open(existing_index, 'r', encoding='utf-8') as f:
  86. try:
  87. link_json = pyjson.load(f)
  88. return Link.from_json(link_json, guess)
  89. except pyjson.JSONDecodeError:
  90. pass
  91. return None
  92. @enforce_types
  93. def parse_json_links_details(out_dir: Union[Path, str]) -> Iterator[Link]:
  94. """read through all the archive data folders and return the parsed links"""
  95. for entry in os.scandir(CONSTANTS.ARCHIVE_DIR):
  96. if entry.is_dir(follow_symlinks=True):
  97. if (Path(entry.path) / 'index.json').exists():
  98. try:
  99. link = parse_json_link_details(entry.path)
  100. except KeyError:
  101. link = None
  102. if link:
  103. yield link
  104. ### Helpers
  105. class ExtendedEncoder(pyjson.JSONEncoder):
  106. """
  107. Extended json serializer that supports serializing several model
  108. fields and objects
  109. """
  110. def default(self, obj):
  111. cls_name = obj.__class__.__name__
  112. if hasattr(obj, '_asdict'):
  113. return obj._asdict()
  114. elif isinstance(obj, bytes):
  115. return obj.decode()
  116. elif isinstance(obj, datetime):
  117. return obj.isoformat()
  118. elif isinstance(obj, Exception):
  119. return '{}: {}'.format(obj.__class__.__name__, obj)
  120. elif cls_name in ('dict_items', 'dict_keys', 'dict_values'):
  121. return tuple(obj)
  122. return pyjson.JSONEncoder.default(self, obj)
  123. @enforce_types
  124. def to_json(obj: Any, indent: Optional[int]=4, sort_keys: bool=True, cls=ExtendedEncoder) -> str:
  125. return pyjson.dumps(obj, indent=indent, sort_keys=sort_keys, cls=ExtendedEncoder)