Debian Codegraph @

aiowebdav2/parser.py

raw
1 """Response and request parsers/creator for WebDAV protocol."""
2
3 from io import BytesIO
4 import logging
5 from urllib.parse import unquote, urlparse, urlsplit
6
7 from lxml import etree
8
9 from .exceptions import MethodNotSupportedError, RemoteResourceNotFoundError
10 from .models import Property, PropertyRequest, QuotaInfo
11 from .urn import Urn
12
13 _LOGGER = logging.getLogger(__name__)
14
15
16 class WebDavXmlUtils:
17 """WebDAV XML utils."""
18
19 @staticmethod
20 def parse_get_list_info_response(content: bytes) -> list[dict[str, str]]:
21 """Parse of response content XML from WebDAV server and extract file and directory infos.
22
23 :param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path.
24 :return: list of information, the information is a dictionary and it values with following keys:
25 `created`: date of resource creation,
26 `name`: name of resource,
27 `size`: size of resource,
28 `modified`: date of resource modification,
29 `etag`: etag of resource,
30 `content_type`: content type of resource,
31 `isdir`: type of resource,
32 `path`: path of resource.
33 """
34 try:
35 tree = etree.fromstring(content)
36 infos = []
37 for response in tree.findall(".//{DAV:}response"):
38 href_el = next(iter(response.findall(".//{DAV:}href")), None)
39 if href_el is None:
40 continue
41 path = unquote(urlsplit(href_el.text).path)
42 is_dir = len(response.findall(".//{DAV:}collection")) > 0
43 info = WebDavXmlUtils.get_info_from_response(response)
44 info["isdir"] = str(is_dir)
45 info["path"] = path
46 infos.append(info)
47 except etree.XMLSyntaxError as err:
48 _LOGGER.warning("Failed to parse list info response XML: %s", err)
49 return []
50
51 return infos
52
53 @staticmethod
54 def parse_get_list_property_response(
55 content: bytes, properties: list[PropertyRequest], hostname: str
56 ) -> dict[str, list[Property]]:
57 """Parse of response content XML from WebDAV server and extract file and directory properties."""
58 try:
59 tree = etree.fromstring(content)
60 properties_dict = {}
61 for response in tree.findall(".//{DAV:}response"):
62 href_el = next(iter(response.findall(".//{DAV:}href")), None)
63 if href_el is None:
64 continue
65 path = unquote(urlsplit(href_el.text).path)
66 prefix = urlparse(hostname).path
67 path = path.removeprefix(prefix)
68 properties_dict[path] = WebDavXmlUtils.parse_get_properties_response(
69 etree.tostring(response), properties
70 )
71 except etree.XMLSyntaxError as err:
72 _LOGGER.warning("Failed to parse list property response XML: %s", err)
73 return {}
74
75 return properties_dict
76
77 @staticmethod
78 def parse_get_list_response(content: bytes) -> list[Urn]:
79 """Parse of response content XML from WebDAV server and extract file and directory names.
80
81 :param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path.
82 :return: list of extracted file or directory names.
83 """
84 try:
85 tree = etree.fromstring(content)
86 urns = []
87 for response in tree.findall(".//{DAV:}response"):
88 href_el = next(iter(response.findall(".//{DAV:}href")), None)
89 if href_el is None:
90 continue
91 href = Urn.separate + unquote(urlsplit(href_el.text).path)
92 is_dir = len(response.findall(".//{DAV:}collection")) > 0
93 urns.append(Urn(href, directory=is_dir))
94 except etree.XMLSyntaxError as err:
95 _LOGGER.warning("Failed to parse list response XML: %s", err)
96 return []
97
98 return urns
99
100 @staticmethod
101 def create_free_space_request_content() -> bytes:
102 """Create an XML for requesting of free space on remote WebDAV server.
103
104 :return: the XML string of request content.
105 """
106 root = etree.Element("propfind", xmlns="DAV:")
107 prop = etree.SubElement(root, "prop")
108 etree.SubElement(prop, "quota-available-bytes")
109 etree.SubElement(prop, "quota-used-bytes")
110 tree = etree.ElementTree(root)
111 return WebDavXmlUtils.etree_to_string(tree)
112
113 @staticmethod
114 def parse_free_space_response(content: bytes, hostname: str) -> int | None:
115 """Parse of response content XML from WebDAV server and extract an amount of free space.
116
117 :param content: the XML content of HTTP response from WebDAV server for getting free space.
118 :param hostname: the server hostname.
119 :return: an amount of free space in bytes.
120 """
121 try:
122 tree = etree.fromstring(content)
123 node = tree.find(".//{DAV:}quota-available-bytes")
124 if node is not None:
125 return int(node.text)
126 raise MethodNotSupportedError(name="free", server=hostname)
127 except TypeError as err:
128 raise MethodNotSupportedError(name="free", server=hostname) from err
129 except etree.XMLSyntaxError as err:
130 _LOGGER.warning("Failed to parse free space response XML: %s", err)
131 return None
132
133 @staticmethod
134 def parse_quota_response(content: bytes, hostname: str) -> QuotaInfo:
135 """Parse of response content XML from WebDAV server and extract quota information.
136
137 :param content: the XML content of HTTP response from WebDAV server.
138 :param hostname: the server hostname.
139 :return: QuotaInfo with available and used bytes.
140 :raises MethodNotSupportedError: when no quota properties are present in the response.
141 """
142 try:
143 tree = etree.fromstring(content)
144 available_node = tree.find(".//{DAV:}quota-available-bytes")
145 used_node = tree.find(".//{DAV:}quota-used-bytes")
146 if available_node is None and used_node is None:
147 raise MethodNotSupportedError(name="quota", server=hostname)
148 return QuotaInfo(
149 available_bytes=(
150 int(available_node.text)
151 if available_node is not None and available_node.text
152 else None
153 ),
154 used_bytes=(
155 int(used_node.text)
156 if used_node is not None and used_node.text
157 else None
158 ),
159 )
160 except (TypeError, ValueError) as err:
161 raise MethodNotSupportedError(name="quota", server=hostname) from err
162 except etree.XMLSyntaxError as err:
163 _LOGGER.warning("Failed to parse quota response XML: %s", err)
164 return QuotaInfo(available_bytes=None, used_bytes=None)
165
166 @staticmethod
167 def get_info_from_response(response: etree.Element) -> dict[str, str]:
168 """Get information attributes from response.
169
170 :param response: XML object of response for the remote resource defined by path
171 :return: a dictionary of information attributes and them values with following keys:
172 `created`: date of resource creation,
173 `name`: name of resource,
174 `size`: size of resource,
175 `modified`: date of resource modification,
176 `etag`: etag of resource,
177 `content_type`: content type of resource.
178 """
179 find_attributes = {
180 "created": ".//{DAV:}creationdate",
181 "name": ".//{DAV:}displayname",
182 "size": ".//{DAV:}getcontentlength",
183 "modified": ".//{DAV:}getlastmodified",
184 "etag": ".//{DAV:}getetag",
185 "content_type": ".//{DAV:}getcontenttype",
186 }
187 info = {}
188 for name, value in find_attributes.items():
189 info[name] = (response.findtext(value) or "").strip()
190 return info
191
192 @staticmethod
193 def parse_info_response(content: bytes, path: str, hostname: str) -> dict[str, str]:
194 """Parse of response content XML from WebDAV server and extract an information about resource.
195
196 :param content: the XML content of HTTP response from WebDAV server.
197 :param path: the path to resource.
198 :param hostname: the server hostname.
199 :return: a dictionary of information attributes and them values with following keys:
200 `created`: date of resource creation,
201 `name`: name of resource,
202 `size`: size of resource,
203 `modified`: date of resource modification,
204 `etag`: etag of resource,
205 `content_type`: content type of resource.
206 """
207 response = WebDavXmlUtils.extract_response_for_path(
208 content=content, path=path, hostname=hostname, action="info"
209 )
210 return WebDavXmlUtils.get_info_from_response(response)
211
212 @staticmethod
213 def parse_is_dir_response(content: bytes, path: str, hostname: str) -> bool:
214 """Parse of response content XML from WebDAV server and extract an information about resource.
215
216 :param content: the XML content of HTTP response from WebDAV server.
217 :param path: the path to resource.
218 :param hostname: the server hostname.
219 :return: True in case the remote resource is directory and False otherwise.
220 """
221 response = WebDavXmlUtils.extract_response_for_path(
222 content=content, path=path, hostname=hostname, action="is_dir"
223 )
224 resource_type = response.find(".//{DAV:}resourcetype")
225 if resource_type is None:
226 raise MethodNotSupportedError(name="is_dir", server=hostname)
227 dir_type = resource_type.find("{DAV:}collection")
228
229 return dir_type is not None
230
231 @staticmethod
232 def create_get_property_batch_request_content(
233 requested_properties: list[PropertyRequest],
234 ) -> bytes:
235 """Create an XML for requesting of getting a property value of remote WebDAV resource.
236
237 :param requested_properties: the property attributes as dictionary with following keys:
238 `namespace`: (optional) the namespace for XML property which will be get,
239 `name`: the name of property which will be get.
240 :return: the XML string of request content.
241 """
242 root = etree.Element("propfind", xmlns="DAV:")
243 prop = etree.SubElement(root, "prop")
244 for requested_property in requested_properties:
245 etree.SubElement(
246 prop, requested_property.name, xmlns=requested_property.namespace
247 )
248 tree = etree.ElementTree(root)
249 return WebDavXmlUtils.etree_to_string(tree)
250
251 @staticmethod
252 def parse_get_properties_response(
253 content: bytes, requested_properties: list[PropertyRequest]
254 ) -> list[Property]:
255 """Parse of response content XML from WebDAV server for getting metadata property value for some resource.
256
257 :param content: the XML content of response as string.
258 :param requested_properties: the requested property as list
259 :return: the value of property if it has been found or None otherwise.
260 """
261 tree = etree.fromstring(content)
262 return [
263 Property(
264 name=requested_property.name,
265 namespace=requested_property.namespace,
266 value=value,
267 )
268 for requested_property in requested_properties
269 if (
270 value := WebDavXmlUtils.get_property_value(
271 tree, requested_property.name
272 )
273 )
274 ]
275
276 @staticmethod
277 def get_property_value(tree: etree.Element, name: str) -> str | None:
278 """Get property value from XML tree.
279
280 :param tree: the XML tree.
281 :param name: the name of property for finding a value in response
282 :return: the value of property if it has been found or None otherwise.
283 """
284 xpath = "//*[local-name() = $name]"
285 results = tree.xpath(xpath, name=name)
286 return results[0].text if results else None
287
288 @staticmethod
289 def create_set_property_batch_request_content(properties: list[Property]) -> bytes:
290 """Create an XML for requesting of setting a property values for remote WebDAV resource in batch.
291
292 :param properties: the property attributes as list of dictionaries with following keys:
293 `namespace`: (optional) the namespace for XML property which will be set,
294 `name`: the name of property which will be set,
295 `value`: (optional) the value of property which will be set. Defaults is empty string.
296 :return: the XML string of request content.
297 """
298 root_node = etree.Element("propertyupdate", xmlns="DAV:")
299 set_node = etree.SubElement(root_node, "set")
300 prop_node = etree.SubElement(set_node, "prop")
301 for prop in properties:
302 opt_node = etree.SubElement(prop_node, prop.name, xmlns=prop.namespace)
303 opt_node.text = prop.value
304 tree = etree.ElementTree(root_node)
305 return WebDavXmlUtils.etree_to_string(tree)
306
307 @staticmethod
308 def etree_to_string(tree: etree.ElementTree) -> bytes:
309 """Create string from lxml.etree.ElementTree with XML declaration and UTF-8 encoding.
310
311 :param tree: the instance of ElementTree
312 :return: the string of XML.
313 """
314 buff = BytesIO()
315 tree.write(buff, xml_declaration=True, encoding="UTF-8")
316 return buff.getvalue()
317
318 @staticmethod
319 def extract_response_for_path(
320 content: bytes, path: str, hostname: str, *, action: str = "extract"
321 ) -> etree.Element:
322 """Extract single response for specified remote resource.
323
324 :param content: raw content of response as string.
325 :param path: the path to needed remote resource.
326 :param hostname: the server hostname.
327 :return: XML object of response for the remote resource defined by path.
328 """
329 prefix = urlparse(hostname).path
330 try:
331 tree = etree.fromstring(content)
332 responses = tree.findall("{DAV:}response")
333 n_path = Urn.normalize_path(path)
334
335 for resp in responses:
336 href = resp.findtext("{DAV:}href")
337 if href is None:
338 continue
339 if Urn.compare_path(n_path, href) or Urn.compare_path(
340 n_path, href.removeprefix(prefix)
341 ):
342 return resp
343 raise RemoteResourceNotFoundError(path)
344 except etree.XMLSyntaxError as err:
345 raise MethodNotSupportedError(name=action, server=hostname) from err