Debian Codegraph @

hass_nabucasa/files.py

raw
1 """Manage cloud files."""
2
3 from __future__ import annotations
4
5 import base64
6 from collections.abc import AsyncGenerator, AsyncIterator, Callable, Coroutine
7 import contextlib
8 from enum import StrEnum
9 import hashlib
10 import logging
11 from typing import Any, Protocol, TypedDict
12
13 from aiohttp import (
14 ClientResponseError,
15 ClientTimeout,
16 StreamReader,
17 )
18
19 from .api import (
20 ApiBase,
21 CloudApiError,
22 CloudApiNonRetryableError,
23 api_exception_handler,
24 )
25
26 _LOGGER = logging.getLogger(__name__)
27
28 _FILE_TRANSFER_TIMEOUT = 43200.0 # 43200s == 12h
29
30
31 class StorageType(StrEnum):
32 """Storage types."""
33
34 BACKUP = "backup"
35
36
37 class FilesError(CloudApiError):
38 """Exception raised when handling files."""
39
40
41 class _FilesHandlerUrlResponse(TypedDict):
42 """URL Response from files handler."""
43
44 url: str
45
46
47 class FilesHandlerDownloadDetails(_FilesHandlerUrlResponse):
48 """Download details from files handler."""
49
50
51 class FilesHandlerUploadDetails(_FilesHandlerUrlResponse):
52 """Upload details from files handler."""
53
54 headers: dict[str, str]
55
56
57 class StoredFile(TypedDict):
58 """Stored file."""
59
60 Key: str
61 Size: int
62 LastModified: str
63 Metadata: dict[str, Any]
64
65
66 class UploadProgressCallback(Protocol):
67 """Protocol for upload progress callbacks."""
68
69 def __call__(self, *, bytes_uploaded: int) -> None:
70 """Handle upload progress updates."""
71
72
73 async def calculate_b64md5(
74 open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]],
75 size: int,
76 ) -> str:
77 """Calculate the MD5 hash of a file.
78
79 Raises FilesError if the bytes read from the stream does not match the size.
80 """
81 file_hash = hashlib.md5() # noqa: S324 Disable warning about using md5
82 bytes_read = 0
83 stream = await open_stream()
84 async for chunk in stream:
85 bytes_read += len(chunk)
86 file_hash.update(chunk)
87 if bytes_read != size:
88 raise FilesError(
89 f"Indicated size {size} does not match actual size {bytes_read}"
90 )
91 return base64.b64encode(file_hash.digest()).decode()
92
93
94 class Files(ApiBase):
95 """Class to help manage files."""
96
97 @property
98 def non_retryable_error_codes(self) -> set[str]:
99 """Get the non-retryable error codes."""
100 return {"NC-SH-FH-03"}
101
102 async def upload(
103 self,
104 *,
105 storage_type: StorageType,
106 open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]],
107 filename: str,
108 base64md5hash: str,
109 size: int,
110 metadata: dict[str, Any] | None = None,
111 on_progress: UploadProgressCallback | None = None,
112 ) -> list[StoredFile]:
113 """Upload a file."""
114 _LOGGER.debug("Uploading %s file with name %s", storage_type, filename)
115 try:
116 details: FilesHandlerUploadDetails = await self._call_cloud_api(
117 action="storage_files_upload",
118 jsondata={
119 "storage_type": storage_type,
120 "filename": filename,
121 "md5": base64md5hash,
122 "size": size,
123 "metadata": metadata,
124 },
125 )
126 except CloudApiNonRetryableError:
127 raise
128 except CloudApiError as err:
129 raise FilesError(err, orig_exc=err) from err
130
131 async def _progress_tracker(
132 stream: AsyncIterator[bytes],
133 ) -> AsyncGenerator[bytes]:
134 """Generate data for upload, while tracking progress."""
135 # We should not call this if on_progress is None.
136 assert on_progress is not None
137 bytes_uploaded = 0
138 async for chunk in stream:
139 bytes_uploaded += len(chunk)
140 on_progress(bytes_uploaded=bytes_uploaded)
141 yield chunk
142
143 try:
144 stream = await open_stream()
145 response = await self._call_raw_api(
146 method="PUT",
147 url=details["url"],
148 data=_progress_tracker(stream) if on_progress is not None else stream,
149 headers=details["headers"] | {"content-length": str(size)},
150 client_timeout=ClientTimeout(
151 connect=10.0,
152 total=_FILE_TRANSFER_TIMEOUT,
153 ),
154 include_path_in_log=False,
155 )
156
157 self._do_log_response(response, include_path_in_log=False)
158 if 400 <= (status := response.status) < 500:
159 # We can try to get some context.
160 error = await response.text()
161 if error and "<Message>" in error and "</Message>" in error:
162 with contextlib.suppress(AttributeError, IndexError):
163 # This is ugly but it's the best we can do, we have no control
164 # over the error message structure, so we try what we can.
165 error = error.split("<Message>")[1].split("</Message>")[0]
166 raise FilesError(
167 f"Failed to upload: ({status}) {error[:256].replace('\n', ' ')}"
168 )
169 response.raise_for_status()
170 except CloudApiError as err:
171 raise FilesError(err, orig_exc=err) from err
172 except ClientResponseError as err:
173 raise FilesError(
174 f"Failed to upload: ({err.status}) {err.message}",
175 orig_exc=err,
176 ) from err
177
178 # We need to list files to clear the cache after a successful upload.
179 return await self.list(storage_type, clear_cache=True)
180
181 async def download(
182 self,
183 storage_type: StorageType,
184 filename: str,
185 ) -> StreamReader:
186 """Download a file."""
187 _LOGGER.debug("Downloading %s file with name %s", storage_type, filename)
188 try:
189 details: FilesHandlerDownloadDetails = await self._call_cloud_api(
190 action="storage_files_download",
191 action_values={
192 "storage_type": storage_type,
193 "filename": filename,
194 },
195 )
196 except CloudApiNonRetryableError:
197 raise
198 except CloudApiError as err:
199 raise FilesError(err, orig_exc=err) from err
200
201 try:
202 response = await self._call_raw_api(
203 method="GET",
204 headers={},
205 url=details["url"],
206 client_timeout=ClientTimeout(
207 connect=10.0,
208 total=_FILE_TRANSFER_TIMEOUT,
209 ),
210 include_path_in_log=False,
211 )
212
213 self._do_log_response(response, include_path_in_log=False)
214 response.raise_for_status()
215 except CloudApiError as err:
216 raise FilesError(err, orig_exc=err) from err
217 except ClientResponseError as err:
218 raise FilesError(
219 f"Failed to download: ({err.status}) {err.message}",
220 orig_exc=err,
221 ) from err
222
223 return response.content
224
225 @api_exception_handler(FilesError)
226 async def list(
227 self,
228 storage_type: StorageType,
229 *,
230 clear_cache: bool = False,
231 ) -> list[StoredFile]:
232 """List files."""
233 files: list[StoredFile] = await self._call_cloud_api(
234 action="storage_files_list",
235 action_values={
236 "storage_type": storage_type,
237 },
238 params={"clearCache": str(clear_cache).lower()},
239 )
240 return files
241
242 @api_exception_handler(FilesError)
243 async def delete(
244 self,
245 storage_type: StorageType,
246 filename: str,
247 ) -> None:
248 """Delete a file."""
249 _LOGGER.debug("Deleting %s file with name %s", storage_type, filename)
250 await self._call_cloud_api(
251 action="storage_files_delete",
252 method="DELETE",
253 jsondata={
254 "storage_type": storage_type,
255 "filename": filename,
256 },
257 )