json.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. __package__ = 'archivebox.index'
  2. import os
  3. import sys
  4. import json as pyjson
  5. from datetime import datetime
  6. from typing import List, Optional, Iterator, Any
  7. from .schema import Link, ArchiveResult
  8. from ..system import atomic_write
  9. from ..util import enforce_types
  10. from ..config import (
  11. VERSION,
  12. OUTPUT_DIR,
  13. FOOTER_INFO,
  14. GIT_SHA,
  15. DEPENDENCIES,
  16. JSON_INDEX_FILENAME,
  17. ARCHIVE_DIR_NAME,
  18. )
  19. MAIN_INDEX_HEADER = {
  20. 'info': 'This is an index of site data archived by ArchiveBox: The self-hosted web archive.',
  21. 'schema': 'archivebox.index.json',
  22. 'copyright_info': FOOTER_INFO,
  23. 'meta': {
  24. 'project': 'ArchiveBox',
  25. 'version': VERSION,
  26. 'git_sha': GIT_SHA,
  27. 'website': 'https://ArchiveBox.io',
  28. 'docs': 'https://github.com/pirate/ArchiveBox/wiki',
  29. 'source': 'https://github.com/pirate/ArchiveBox',
  30. 'issues': 'https://github.com/pirate/ArchiveBox/issues',
  31. 'dependencies': DEPENDENCIES,
  32. },
  33. }
  34. ### Main Links Index
  35. @enforce_types
  36. def parse_json_main_index(out_dir: str=OUTPUT_DIR) -> Iterator[Link]:
  37. """parse an archive index json file and return the list of links"""
  38. index_path = os.path.join(out_dir, JSON_INDEX_FILENAME)
  39. if os.path.exists(index_path):
  40. with open(index_path, 'r', encoding='utf-8') as f:
  41. links = pyjson.load(f)['links']
  42. for link_json in links:
  43. yield Link.from_json(link_json)
  44. return ()
  45. @enforce_types
  46. def write_json_main_index(links: List[Link], out_dir: str=OUTPUT_DIR) -> None:
  47. """write the json link index to a given path"""
  48. assert isinstance(links, List), 'Links must be a list, not a generator.'
  49. assert not links or isinstance(links[0].history, dict)
  50. assert not links or isinstance(links[0].sources, list)
  51. if links and links[0].history.get('title'):
  52. assert isinstance(links[0].history['title'][0], ArchiveResult)
  53. if links and links[0].sources:
  54. assert isinstance(links[0].sources[0], str)
  55. main_index_json = {
  56. **MAIN_INDEX_HEADER,
  57. 'num_links': len(links),
  58. 'updated': datetime.now(),
  59. 'last_run_cmd': sys.argv,
  60. 'links': links,
  61. }
  62. atomic_write(os.path.join(out_dir, JSON_INDEX_FILENAME), main_index_json)
  63. ### Link Details Index
  64. @enforce_types
  65. def write_json_link_details(link: Link, out_dir: Optional[str]=None) -> None:
  66. """write a json file with some info about the link"""
  67. out_dir = out_dir or link.link_dir
  68. path = os.path.join(out_dir, JSON_INDEX_FILENAME)
  69. atomic_write(path, link._asdict(extended=True))
  70. @enforce_types
  71. def parse_json_link_details(out_dir: str) -> Optional[Link]:
  72. """load the json link index from a given directory"""
  73. existing_index = os.path.join(out_dir, JSON_INDEX_FILENAME)
  74. if os.path.exists(existing_index):
  75. with open(existing_index, 'r', encoding='utf-8') as f:
  76. try:
  77. link_json = pyjson.load(f)
  78. return Link.from_json(link_json)
  79. except pyjson.JSONDecodeError:
  80. pass
  81. return None
  82. @enforce_types
  83. def parse_json_links_details(out_dir: str) -> Iterator[Link]:
  84. """read through all the archive data folders and return the parsed links"""
  85. for entry in os.scandir(os.path.join(out_dir, ARCHIVE_DIR_NAME)):
  86. if entry.is_dir(follow_symlinks=True):
  87. if os.path.exists(os.path.join(entry.path, 'index.json')):
  88. link = parse_json_link_details(entry.path)
  89. if link:
  90. yield link
  91. ### Helpers
  92. class ExtendedEncoder(pyjson.JSONEncoder):
  93. """
  94. Extended json serializer that supports serializing several model
  95. fields and objects
  96. """
  97. def default(self, obj):
  98. cls_name = obj.__class__.__name__
  99. if hasattr(obj, '_asdict'):
  100. return obj._asdict()
  101. elif isinstance(obj, bytes):
  102. return obj.decode()
  103. elif isinstance(obj, datetime):
  104. return obj.isoformat()
  105. elif isinstance(obj, Exception):
  106. return '{}: {}'.format(obj.__class__.__name__, obj)
  107. elif cls_name in ('dict_items', 'dict_keys', 'dict_values'):
  108. return tuple(obj)
  109. return pyjson.JSONEncoder.default(self, obj)
  110. @enforce_types
  111. def to_json(obj: Any, indent: Optional[int]=4, sort_keys: bool=True, cls=ExtendedEncoder) -> str:
  112. return pyjson.dumps(obj, indent=indent, sort_keys=sort_keys, cls=ExtendedEncoder)