2022-08-29 17:56:31 -06:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const assert = require('assert');
|
|
|
|
const urlJoin = require('url-join');
|
|
|
|
|
2022-09-08 00:30:04 -06:00
|
|
|
const { fetchEndpointAsJson } = require('../fetch-endpoint');
|
2023-04-11 14:09:44 -06:00
|
|
|
const getServerNameFromMatrixRoomIdOrAlias = require('./get-server-name-from-matrix-room-id-or-alias');
|
2022-08-29 17:56:31 -06:00
|
|
|
|
2022-09-08 00:30:04 -06:00
|
|
|
const config = require('../config');
|
2023-05-01 23:39:01 -06:00
|
|
|
const StatusError = require('../errors/status-error');
|
2022-08-29 17:56:31 -06:00
|
|
|
const matrixServerUrl = config.get('matrixServerUrl');
|
|
|
|
assert(matrixServerUrl);
|
|
|
|
|
2023-05-01 23:39:01 -06:00
|
|
|
async function ensureRoomJoined(
|
|
|
|
accessToken,
|
|
|
|
roomIdOrAlias,
|
|
|
|
{ viaServers = new Set(), abortSignal } = {}
|
|
|
|
) {
|
2023-04-11 14:09:44 -06:00
|
|
|
// We use a `Set` to ensure that we don't have duplicate servers in the list
|
|
|
|
assert(viaServers instanceof Set);
|
|
|
|
|
|
|
|
// Let's do our best for the user to join the room. Since room ID's are
|
|
|
|
// unroutable on their own and won't be found if the server doesn't already
|
|
|
|
// know about the room, we'll try to join the room via the server name that
|
|
|
|
// we derived from the room ID or alias.
|
|
|
|
const viaServersWithAssumptions = new Set(viaServers);
|
|
|
|
const derivedServerName = getServerNameFromMatrixRoomIdOrAlias(roomIdOrAlias);
|
|
|
|
if (derivedServerName) {
|
|
|
|
viaServersWithAssumptions.add(derivedServerName);
|
|
|
|
}
|
|
|
|
|
2022-08-29 17:56:31 -06:00
|
|
|
let qs = new URLSearchParams();
|
2023-04-11 14:09:44 -06:00
|
|
|
Array.from(viaServersWithAssumptions).forEach((viaServer) => {
|
2022-08-29 17:56:31 -06:00
|
|
|
qs.append('server_name', viaServer);
|
|
|
|
});
|
|
|
|
|
|
|
|
const joinEndpoint = urlJoin(
|
|
|
|
matrixServerUrl,
|
2022-10-27 00:09:13 -06:00
|
|
|
`_matrix/client/r0/join/${encodeURIComponent(roomIdOrAlias)}?${qs.toString()}`
|
2022-08-29 17:56:31 -06:00
|
|
|
);
|
2022-09-08 18:15:07 -06:00
|
|
|
try {
|
2022-11-03 03:12:00 -06:00
|
|
|
const { data: joinData } = await fetchEndpointAsJson(joinEndpoint, {
|
2022-09-08 18:15:07 -06:00
|
|
|
method: 'POST',
|
|
|
|
accessToken,
|
2023-05-01 23:39:01 -06:00
|
|
|
abortSignal,
|
2022-09-08 18:15:07 -06:00
|
|
|
});
|
2022-10-27 00:09:13 -06:00
|
|
|
assert(
|
|
|
|
joinData.room_id,
|
|
|
|
`Join endpoint (${joinEndpoint}) did not return \`room_id\` as expected. This is probably a problem with that homeserver.`
|
|
|
|
);
|
|
|
|
return joinData.room_id;
|
2022-09-08 18:15:07 -06:00
|
|
|
} catch (err) {
|
|
|
|
throw new StatusError(403, `Archiver is unable to join room: ${err.message}`);
|
|
|
|
}
|
2022-08-29 17:56:31 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = ensureRoomJoined;
|