Debian Codegraph @

asusrouter/tools/dump.py

raw
1 """Dump tools for AsusRouter.
2
3 This module contains all needed to dump the raw data from the router
4 for the following analysis and testing.
5 """
6
7 from __future__ import annotations
8
9 import asyncio
10 from datetime import UTC, datetime
11 import json
12 import os
13 from types import TracebackType
14 from typing import Any, Self
15 import zipfile
16
17 from asusrouter.modules.endpoint import Endpoint
18
19
20 class AsusRouterDump:
21 """AsusRouter Dumper."""
22
23 _endpoint: Endpoint
24 _datetime: str
25
26 def __init__(
27 self, output_folder: str, full_dump: bool = False, archive: bool = True
28 ) -> None:
29 """Initialize."""
30
31 self.log: dict[str, str] = {}
32
33 self._output_folder = output_folder
34 self.full_dump = full_dump
35 self.zip = archive
36
37 self._init_datetime = datetime.now(UTC)
38
39 if self.zip:
40 self._zipfile = zipfile.ZipFile(
41 os.path.join( # noqa: PTH118
42 self._output_folder,
43 (
44 "AsusRouter-"
45 f"{self._init_datetime.isoformat().replace(':', '-')}"
46 ".zip"
47 ),
48 ),
49 "w",
50 )
51 else:
52 # Create subfolder for the dump
53 self._output_folder = os.path.join( # noqa: PTH118
54 output_folder,
55 f"AsusRouter-"
56 f"{self._init_datetime.isoformat().replace(':', '-')}",
57 )
58 os.makedirs(self._output_folder) # noqa: PTH103
59
60 def __enter__(self) -> Self:
61 """Enter the runtime context related to this object."""
62
63 return self
64
65 def __exit__(
66 self,
67 exc_type: type[BaseException] | None,
68 exc_value: BaseException | None,
69 traceback: TracebackType | None,
70 ) -> None:
71 """Exit the runtime context and save the log."""
72
73 if self.zip:
74 # Write the log data to the zip file
75 self._zipfile.writestr(
76 "log.json", json.dumps(self.log, default=str)
77 )
78 self._zipfile.close()
79 else:
80 log_filename = os.path.join(self._output_folder, "log.json") # noqa: PTH118
81 with open(log_filename, "w", encoding="utf-8") as f: # noqa: PTH123
82 json.dump(self.log, f, default=str)
83
84 async def dump(
85 self,
86 endpoint: Endpoint,
87 payload: dict[str, Any],
88 resp_status: int,
89 resp_headers: dict[str, Any],
90 resp_content: bytes,
91 ) -> None:
92 """Dump the data."""
93
94 self._endpoint = endpoint
95 self._datetime = datetime.now(UTC).isoformat().replace(":", "-")
96
97 self.log[self._datetime] = f"Endpoint.{endpoint.name}"
98
99 # Write the response content to a file
100 loop = asyncio.get_running_loop()
101 await loop.run_in_executor(None, self._write_content, resp_content)
102
103 # Write the metadata to a file
104 metadata = {
105 "endpoint": endpoint,
106 "payload": payload,
107 "resp_status": resp_status,
108 "resp_headers": resp_headers,
109 }
110 await loop.run_in_executor(None, self._write_metadata, metadata)
111
112 def _write_content(self, content: str) -> None:
113 """Write the content to a file."""
114
115 if self.full_dump:
116 filename = f"{self._datetime}-{self._endpoint}.content"
117 if self.zip:
118 self._zipfile.writestr(filename, content)
119 else:
120 with open( # noqa: PTH123
121 os.path.join(self._output_folder, filename), # noqa: PTH118
122 "w",
123 encoding="utf-8",
124 ) as f:
125 f.write(content)
126
127 def _write_metadata(self, metadata: dict[str, Any]) -> None:
128 """Write the metadata to a file."""
129
130 if self.full_dump:
131 filename = f"{self._datetime}-{self._endpoint}.json"
132 if self.zip:
133 self._zipfile.writestr(
134 filename, json.dumps(metadata, default=str)
135 )
136 else:
137 with open( # noqa: PTH123
138 os.path.join(self._output_folder, filename), # noqa: PTH118
139 "w",
140 encoding="utf-8",
141 ) as f:
142 json.dump(metadata, f, default=str)