json.py 5.3 KB

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