Skip to content
This repository was archived by the owner on Sep 11, 2024. It is now read-only.

Commit 408f4df

Browse files
author
Germain
authored
Add public room directory hook (#8626)
1 parent e87bda9 commit 408f4df

File tree

4 files changed

+464
-0
lines changed

4 files changed

+464
-0
lines changed
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
/*
2+
Copyright 2022 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import { useCallback, useEffect, useState } from "react";
18+
import { IProtocol, IPublicRoomsChunkRoom } from "matrix-js-sdk/src/client";
19+
import { IRoomDirectoryOptions } from "matrix-js-sdk/src/@types/requests";
20+
21+
import { MatrixClientPeg } from "../MatrixClientPeg";
22+
import SdkConfig from "../SdkConfig";
23+
import SettingsStore from "../settings/SettingsStore";
24+
import { Protocols } from "../utils/DirectoryUtils";
25+
26+
export const ALL_ROOMS = "ALL_ROOMS";
27+
const LAST_SERVER_KEY = "mx_last_room_directory_server";
28+
const LAST_INSTANCE_KEY = "mx_last_room_directory_instance";
29+
30+
export interface IPublicRoomsOpts {
31+
limit: number;
32+
query?: string;
33+
}
34+
35+
let thirdParty: Protocols;
36+
37+
export const usePublicRoomDirectory = () => {
38+
const [publicRooms, setPublicRooms] = useState<IPublicRoomsChunkRoom[]>([]);
39+
40+
const [roomServer, setRoomServer] = useState<string | null | undefined>(undefined);
41+
const [instanceId, setInstanceId] = useState<string | null | undefined>(undefined);
42+
const [protocols, setProtocols] = useState<Protocols | null>(null);
43+
44+
const [ready, setReady] = useState(false);
45+
const [loading, setLoading] = useState(false);
46+
47+
async function initProtocols() {
48+
if (!MatrixClientPeg.get()) {
49+
// We may not have a client yet when invoked from welcome page
50+
setReady(true);
51+
} else if (thirdParty) {
52+
setProtocols(thirdParty);
53+
} else {
54+
const response = await MatrixClientPeg.get().getThirdpartyProtocols();
55+
thirdParty = response;
56+
setProtocols(response);
57+
}
58+
}
59+
60+
function setConfig(server: string, instanceId?: string) {
61+
if (!ready) {
62+
throw new Error("public room configuration not initialised yet");
63+
} else {
64+
setRoomServer(server);
65+
setInstanceId(instanceId ?? null);
66+
}
67+
}
68+
69+
const search = useCallback(async ({
70+
limit = 20,
71+
query,
72+
}: IPublicRoomsOpts): Promise<boolean> => {
73+
if (!query?.length) {
74+
setPublicRooms([]);
75+
return true;
76+
}
77+
78+
const opts: IRoomDirectoryOptions = { limit };
79+
80+
if (roomServer != MatrixClientPeg.getHomeserverName()) {
81+
opts.server = roomServer;
82+
}
83+
84+
if (instanceId === ALL_ROOMS) {
85+
opts.include_all_networks = true;
86+
} else if (instanceId) {
87+
opts.third_party_instance_id = instanceId;
88+
}
89+
90+
if (query) {
91+
opts.filter = {
92+
generic_search_term: query,
93+
};
94+
}
95+
96+
try {
97+
setLoading(true);
98+
const { chunk } = await MatrixClientPeg.get().publicRooms(opts);
99+
setPublicRooms(chunk);
100+
return true;
101+
} catch (e) {
102+
console.error("Could not fetch public rooms for params", opts, e);
103+
setPublicRooms([]);
104+
return false;
105+
} finally {
106+
setLoading(false);
107+
}
108+
}, [roomServer, instanceId]);
109+
110+
useEffect(() => {
111+
initProtocols();
112+
}, []);
113+
114+
useEffect(() => {
115+
if (protocols === null) {
116+
return;
117+
}
118+
119+
const myHomeserver = MatrixClientPeg.getHomeserverName();
120+
const lsRoomServer = localStorage.getItem(LAST_SERVER_KEY);
121+
const lsInstanceId = localStorage.getItem(LAST_INSTANCE_KEY);
122+
123+
let roomServer = myHomeserver;
124+
if (
125+
SdkConfig.getObject("room_directory")?.get("servers")?.includes(lsRoomServer) ||
126+
SettingsStore.getValue("room_directory_servers")?.includes(lsRoomServer)
127+
) {
128+
roomServer = lsRoomServer;
129+
}
130+
131+
let instanceId: string | null = null;
132+
if (roomServer === myHomeserver && (
133+
lsInstanceId === ALL_ROOMS ||
134+
Object.values(protocols).some((p: IProtocol) => {
135+
p.instances.some(i => i.instance_id === lsInstanceId);
136+
})
137+
)) {
138+
instanceId = lsInstanceId;
139+
}
140+
141+
setReady(true);
142+
setInstanceId(instanceId);
143+
setRoomServer(roomServer);
144+
}, [protocols]);
145+
146+
useEffect(() => {
147+
localStorage.setItem(LAST_SERVER_KEY, roomServer);
148+
}, [roomServer]);
149+
150+
useEffect(() => {
151+
localStorage.setItem(LAST_INSTANCE_KEY, instanceId);
152+
}, [instanceId]);
153+
154+
return {
155+
ready,
156+
loading,
157+
publicRooms,
158+
protocols,
159+
roomServer,
160+
instanceId,
161+
search,
162+
setConfig,
163+
} as const;
164+
};

src/hooks/useUserDirectory.ts

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
/*
2+
Copyright 2022 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import { useCallback, useState } from "react";
18+
19+
import { MatrixClientPeg } from "../MatrixClientPeg";
20+
import { DirectoryMember } from "../utils/direct-messages";
21+
22+
export interface IUserDirectoryOpts {
23+
limit: number;
24+
query?: string;
25+
}
26+
27+
export const useUserDirectory = () => {
28+
const [users, setUsers] = useState<DirectoryMember[]>([]);
29+
30+
const [loading, setLoading] = useState(false);
31+
32+
const search = useCallback(async ({
33+
limit = 20,
34+
query: term,
35+
}: IUserDirectoryOpts): Promise<boolean> => {
36+
if (!term?.length) {
37+
setUsers([]);
38+
return true;
39+
}
40+
41+
try {
42+
setLoading(true);
43+
const { results } = await MatrixClientPeg.get().searchUserDirectory({
44+
limit,
45+
term,
46+
});
47+
setUsers(results.map(user => new DirectoryMember(user)));
48+
return true;
49+
} catch (e) {
50+
console.error("Could not fetch user in user directory for params", { limit, term }, e);
51+
setUsers([]);
52+
return false;
53+
} finally {
54+
setLoading(false);
55+
}
56+
}, []);
57+
58+
return {
59+
ready: true,
60+
loading,
61+
users,
62+
search,
63+
} as const;
64+
};
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
/*
2+
Copyright 2022 The Matrix.org Foundation C.I.C.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
import { mount } from "enzyme";
18+
import { sleep } from "matrix-js-sdk/src/utils";
19+
import React from "react";
20+
import { act } from "react-dom/test-utils";
21+
22+
import { usePublicRoomDirectory } from "../../src/hooks/usePublicRoomDirectory";
23+
import { MatrixClientPeg } from "../../src/MatrixClientPeg";
24+
import { stubClient } from "../test-utils/test-utils";
25+
26+
function PublicRoomComponent({ onClick }) {
27+
const roomDirectory = usePublicRoomDirectory();
28+
29+
const {
30+
ready,
31+
loading,
32+
publicRooms,
33+
} = roomDirectory;
34+
35+
return <div onClick={() => onClick(roomDirectory)}>
36+
{ (!ready || loading) && `ready: ${ready}, loading: ${loading}` }
37+
{ publicRooms[0] && (
38+
`Name: ${publicRooms[0].name}`
39+
) }
40+
</div>;
41+
}
42+
43+
describe("usePublicRoomDirectory", () => {
44+
let cli;
45+
46+
beforeEach(() => {
47+
stubClient();
48+
cli = MatrixClientPeg.get();
49+
50+
MatrixClientPeg.getHomeserverName = () => "matrix.org";
51+
cli.getThirdpartyProtocols = () => Promise.resolve({});
52+
cli.publicRooms = (({ filter: { generic_search_term: query } }) => Promise.resolve({
53+
chunk: [{
54+
room_id: "hello world!",
55+
name: query,
56+
world_readable: true,
57+
guest_can_join: true,
58+
num_joined_members: 1,
59+
}],
60+
total_room_count_estimate: 1,
61+
}));
62+
});
63+
64+
it("should display public rooms when searching", async () => {
65+
const query = "ROOM NAME";
66+
67+
const wrapper = mount(<PublicRoomComponent onClick={(hook) => {
68+
hook.search({
69+
limit: 1,
70+
query,
71+
});
72+
}} />);
73+
74+
expect(wrapper.text()).toBe("ready: false, loading: false");
75+
76+
await act(async () => {
77+
await sleep(1);
78+
wrapper.simulate("click");
79+
return act(() => sleep(1));
80+
});
81+
82+
expect(wrapper.text()).toContain(query);
83+
});
84+
85+
it("should work with empty queries", async () => {
86+
const wrapper = mount(<PublicRoomComponent onClick={(hook) => {
87+
hook.search({
88+
limit: 1,
89+
query: "",
90+
});
91+
}} />);
92+
93+
await act(async () => {
94+
await sleep(1);
95+
wrapper.simulate("click");
96+
return act(() => sleep(1));
97+
});
98+
99+
expect(wrapper.text()).toBe("");
100+
});
101+
102+
it("should recover from a server exception", async () => {
103+
cli.publicRooms = () => { throw new Error("Oops"); };
104+
const query = "ROOM NAME";
105+
106+
const wrapper = mount(<PublicRoomComponent onClick={(hook) => {
107+
hook.search({
108+
limit: 1,
109+
query,
110+
});
111+
}} />);
112+
await act(async () => {
113+
await sleep(1);
114+
wrapper.simulate("click");
115+
return act(() => sleep(1));
116+
});
117+
118+
expect(wrapper.text()).toBe("");
119+
});
120+
});

0 commit comments

Comments
 (0)