aboutsummaryrefslogtreecommitdiff
path: root/clientapi/routing/room_hierarchy.go
blob: 2884d2c32d6abf7ccffe006c1eed1f6760a3e378 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
// Copyright 2023 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package routing

import (
	"net/http"
	"strconv"
	"sync"

	"github.com/google/uuid"
	roomserverAPI "github.com/matrix-org/dendrite/roomserver/api"
	"github.com/matrix-org/dendrite/roomserver/types"
	userapi "github.com/matrix-org/dendrite/userapi/api"
	"github.com/matrix-org/gomatrixserverlib/fclient"
	"github.com/matrix-org/gomatrixserverlib/spec"
	"github.com/matrix-org/util"
	log "github.com/sirupsen/logrus"
)

// For storing pagination information for room hierarchies
type RoomHierarchyPaginationCache struct {
	cache map[string]roomserverAPI.RoomHierarchyWalker
	mu    sync.Mutex
}

// Create a new, empty, pagination cache.
func NewRoomHierarchyPaginationCache() RoomHierarchyPaginationCache {
	return RoomHierarchyPaginationCache{
		cache: map[string]roomserverAPI.RoomHierarchyWalker{},
	}
}

// Get a cached page, or nil if there is no associated page in the cache.
func (c *RoomHierarchyPaginationCache) Get(token string) *roomserverAPI.RoomHierarchyWalker {
	c.mu.Lock()
	defer c.mu.Unlock()
	line, ok := c.cache[token]
	if ok {
		return &line
	} else {
		return nil
	}
}

// Add a cache line to the pagination cache.
func (c *RoomHierarchyPaginationCache) AddLine(line roomserverAPI.RoomHierarchyWalker) string {
	c.mu.Lock()
	defer c.mu.Unlock()
	token := uuid.NewString()
	c.cache[token] = line
	return token
}

// Query the hierarchy of a room/space
//
// Implements /_matrix/client/v1/rooms/{roomID}/hierarchy
func QueryRoomHierarchy(req *http.Request, device *userapi.Device, roomIDStr string, rsAPI roomserverAPI.ClientRoomserverAPI, paginationCache *RoomHierarchyPaginationCache) util.JSONResponse {
	parsedRoomID, err := spec.NewRoomID(roomIDStr)
	if err != nil {
		return util.JSONResponse{
			Code: http.StatusNotFound,
			JSON: spec.InvalidParam("room is unknown/forbidden"),
		}
	}
	roomID := *parsedRoomID

	suggestedOnly := false // Defaults to false (spec-defined)
	switch req.URL.Query().Get("suggested_only") {
	case "true":
		suggestedOnly = true
	case "false":
	case "": // Empty string is returned when query param is not set
	default:
		return util.JSONResponse{
			Code: http.StatusBadRequest,
			JSON: spec.InvalidParam("query parameter 'suggested_only', if set, must be 'true' or 'false'"),
		}
	}

	limit := 1000 // Default to 1000
	limitStr := req.URL.Query().Get("limit")
	if limitStr != "" {
		var maybeLimit int
		maybeLimit, err = strconv.Atoi(limitStr)
		if err != nil || maybeLimit < 0 {
			return util.JSONResponse{
				Code: http.StatusBadRequest,
				JSON: spec.InvalidParam("query parameter 'limit', if set, must be a positive integer"),
			}
		}
		limit = maybeLimit
		if limit > 1000 {
			limit = 1000 // Maximum limit of 1000
		}
	}

	maxDepth := -1 // '-1' representing no maximum depth
	maxDepthStr := req.URL.Query().Get("max_depth")
	if maxDepthStr != "" {
		var maybeMaxDepth int
		maybeMaxDepth, err = strconv.Atoi(maxDepthStr)
		if err != nil || maybeMaxDepth < 0 {
			return util.JSONResponse{
				Code: http.StatusBadRequest,
				JSON: spec.InvalidParam("query parameter 'max_depth', if set, must be a positive integer"),
			}
		}
		maxDepth = maybeMaxDepth
	}

	from := req.URL.Query().Get("from")

	var walker roomserverAPI.RoomHierarchyWalker
	if from == "" { // No pagination token provided, so start new hierarchy walker
		walker = roomserverAPI.NewRoomHierarchyWalker(types.NewDeviceNotServerName(*device), roomID, suggestedOnly, maxDepth)
	} else { // Attempt to resume cached walker
		cachedWalker := paginationCache.Get(from)

		if cachedWalker == nil || cachedWalker.SuggestedOnly != suggestedOnly || cachedWalker.MaxDepth != maxDepth {
			return util.JSONResponse{
				Code: http.StatusBadRequest,
				JSON: spec.InvalidParam("pagination not found for provided token ('from') with given 'max_depth', 'suggested_only' and room ID"),
			}
		}

		walker = *cachedWalker
	}

	discoveredRooms, nextWalker, err := rsAPI.QueryNextRoomHierarchyPage(req.Context(), walker, limit)

	if err != nil {
		switch err.(type) {
		case roomserverAPI.ErrRoomUnknownOrNotAllowed:
			util.GetLogger(req.Context()).WithError(err).Debugln("room unknown/forbidden when handling CS room hierarchy request")
			return util.JSONResponse{
				Code: http.StatusForbidden,
				JSON: spec.Forbidden("room is unknown/forbidden"),
			}
		default:
			log.WithError(err).Errorf("failed to fetch next page of room hierarchy (CS API)")
			return util.JSONResponse{
				Code: http.StatusInternalServerError,
				JSON: spec.Unknown("internal server error"),
			}
		}
	}

	nextBatch := ""
	// nextWalker will be nil if there's no more rooms left to walk
	if nextWalker != nil {
		nextBatch = paginationCache.AddLine(*nextWalker)
	}

	return util.JSONResponse{
		Code: http.StatusOK,
		JSON: RoomHierarchyClientResponse{
			Rooms:     discoveredRooms,
			NextBatch: nextBatch,
		},
	}

}

// Success response for /_matrix/client/v1/rooms/{roomID}/hierarchy
type RoomHierarchyClientResponse struct {
	Rooms     []fclient.RoomHierarchyRoom `json:"rooms"`
	NextBatch string                      `json:"next_batch,omitempty"`
}