1// Copyright 2017 Vector Creations 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
15package routing
16
17import (
18	"encoding/json"
19	"net/http"
20
21	"github.com/matrix-org/dendrite/clientapi/jsonerror"
22	"github.com/matrix-org/dendrite/roomserver/api"
23	"github.com/matrix-org/dendrite/setup/config"
24	userapi "github.com/matrix-org/dendrite/userapi/api"
25	"github.com/matrix-org/gomatrixserverlib"
26	"github.com/matrix-org/util"
27)
28
29type getMembershipResponse struct {
30	Chunk []gomatrixserverlib.ClientEvent `json:"chunk"`
31}
32
33type getJoinedRoomsResponse struct {
34	JoinedRooms []string `json:"joined_rooms"`
35}
36
37// https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-rooms-roomid-joined-members
38type getJoinedMembersResponse struct {
39	Joined map[string]joinedMember `json:"joined"`
40}
41
42type joinedMember struct {
43	DisplayName string `json:"display_name"`
44	AvatarURL   string `json:"avatar_url"`
45}
46
47// The database stores 'displayname' without an underscore.
48// Deserialize into this and then change to the actual API response
49type databaseJoinedMember struct {
50	DisplayName string `json:"displayname"`
51	AvatarURL   string `json:"avatar_url"`
52}
53
54// GetMemberships implements GET /rooms/{roomId}/members
55func GetMemberships(
56	req *http.Request, device *userapi.Device, roomID string, joinedOnly bool,
57	_ *config.ClientAPI,
58	rsAPI api.RoomserverInternalAPI,
59) util.JSONResponse {
60	queryReq := api.QueryMembershipsForRoomRequest{
61		JoinedOnly: joinedOnly,
62		RoomID:     roomID,
63		Sender:     device.UserID,
64	}
65	var queryRes api.QueryMembershipsForRoomResponse
66	if err := rsAPI.QueryMembershipsForRoom(req.Context(), &queryReq, &queryRes); err != nil {
67		util.GetLogger(req.Context()).WithError(err).Error("rsAPI.QueryMembershipsForRoom failed")
68		return jsonerror.InternalServerError()
69	}
70
71	if !queryRes.HasBeenInRoom {
72		return util.JSONResponse{
73			Code: http.StatusForbidden,
74			JSON: jsonerror.Forbidden("You aren't a member of the room and weren't previously a member of the room."),
75		}
76	}
77
78	if joinedOnly {
79		var res getJoinedMembersResponse
80		res.Joined = make(map[string]joinedMember)
81		for _, ev := range queryRes.JoinEvents {
82			var content databaseJoinedMember
83			if err := json.Unmarshal(ev.Content, &content); err != nil {
84				util.GetLogger(req.Context()).WithError(err).Error("failed to unmarshal event content")
85				return jsonerror.InternalServerError()
86			}
87			res.Joined[ev.Sender] = joinedMember(content)
88		}
89		return util.JSONResponse{
90			Code: http.StatusOK,
91			JSON: res,
92		}
93	}
94	return util.JSONResponse{
95		Code: http.StatusOK,
96		JSON: getMembershipResponse{queryRes.JoinEvents},
97	}
98}
99
100func GetJoinedRooms(
101	req *http.Request,
102	device *userapi.Device,
103	rsAPI api.RoomserverInternalAPI,
104) util.JSONResponse {
105	var res api.QueryRoomsForUserResponse
106	err := rsAPI.QueryRoomsForUser(req.Context(), &api.QueryRoomsForUserRequest{
107		UserID:         device.UserID,
108		WantMembership: "join",
109	}, &res)
110	if err != nil {
111		util.GetLogger(req.Context()).WithError(err).Error("QueryRoomsForUser failed")
112		return jsonerror.InternalServerError()
113	}
114	if res.RoomIDs == nil {
115		res.RoomIDs = []string{}
116	}
117	return util.JSONResponse{
118		Code: http.StatusOK,
119		JSON: getJoinedRoomsResponse{res.RoomIDs},
120	}
121}
122