json.py 4.6 KB

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