1# Copyright 2016 OpenMarket Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import logging
16from typing import Dict
17
18from twisted.web.resource import NoResource, Resource
19
20logger = logging.getLogger(__name__)
21
22
23def create_resource_tree(
24    desired_tree: Dict[str, Resource], root_resource: Resource
25) -> Resource:
26    """Create the resource tree for this homeserver.
27
28    This in unduly complicated because Twisted does not support putting
29    child resources more than 1 level deep at a time.
30
31    Args:
32        desired_tree: Dict from desired paths to desired resources.
33        root_resource: The root resource to add the tree to.
34    Returns:
35        The ``root_resource`` with a tree of child resources added to it.
36    """
37
38    # ideally we'd just use getChild and putChild but getChild doesn't work
39    # unless you give it a Request object IN ADDITION to the name :/ So
40    # instead, we'll store a copy of this mapping so we can actually add
41    # extra resources to existing nodes. See self._resource_id for the key.
42    resource_mappings: Dict[str, Resource] = {}
43    for full_path_str, res in desired_tree.items():
44        # twisted requires all resources to be bytes
45        full_path = full_path_str.encode("utf-8")
46
47        logger.info("Attaching %s to path %s", res, full_path)
48        last_resource = root_resource
49        for path_seg in full_path.split(b"/")[1:-1]:
50            if path_seg not in last_resource.listNames():
51                # resource doesn't exist, so make a "dummy resource"
52                child_resource: Resource = NoResource()
53                last_resource.putChild(path_seg, child_resource)
54                res_id = _resource_id(last_resource, path_seg)
55                resource_mappings[res_id] = child_resource
56                last_resource = child_resource
57            else:
58                # we have an existing Resource, use that instead.
59                res_id = _resource_id(last_resource, path_seg)
60                last_resource = resource_mappings[res_id]
61
62        # ===========================
63        # now attach the actual desired resource
64        last_path_seg = full_path.split(b"/")[-1]
65
66        # if there is already a resource here, thieve its children and
67        # replace it
68        res_id = _resource_id(last_resource, last_path_seg)
69        if res_id in resource_mappings:
70            # there is a dummy resource at this path already, which needs
71            # to be replaced with the desired resource.
72            existing_dummy_resource = resource_mappings[res_id]
73            for child_name in existing_dummy_resource.listNames():
74                child_res_id = _resource_id(existing_dummy_resource, child_name)
75                child_resource = resource_mappings[child_res_id]
76                # steal the children
77                res.putChild(child_name, child_resource)
78
79        # finally, insert the desired resource in the right place
80        last_resource.putChild(last_path_seg, res)
81        res_id = _resource_id(last_resource, last_path_seg)
82        resource_mappings[res_id] = res
83
84    return root_resource
85
86
87def _resource_id(resource: Resource, path_seg: bytes) -> str:
88    """Construct an arbitrary resource ID so you can retrieve the mapping
89    later.
90
91    If you want to represent resource A putChild resource B with path C,
92    the mapping should looks like _resource_id(A,C) = B.
93
94    Args:
95        resource: The *parent* Resourceb
96        path_seg: The name of the child Resource to be attached.
97    Returns:
98        A unique string which can be a key to the child Resource.
99    """
100    return "%s-%r" % (resource, path_seg)
101