refactor pickServerCandidates into statefull class

so we don't need to iterate over all members for every permalink
This commit is contained in:
Bruno Windels 2019-02-21 15:36:37 +01:00
parent a26b62ef94
commit c2791b9470

View file

@ -25,45 +25,6 @@ export const baseUrl = `https://${host}`;
// to add to permalinks. The servers are appended as ?via=example.org // to add to permalinks. The servers are appended as ?via=example.org
const MAX_SERVER_CANDIDATES = 3; const MAX_SERVER_CANDIDATES = 3;
export function makeEventPermalink(roomId, eventId) {
const permalinkBase = `${baseUrl}/#/${roomId}/${eventId}`;
// If the roomId isn't actually a room ID, don't try to list the servers.
// Aliases are already routable, and don't need extra information.
if (roomId[0] !== '!') return permalinkBase;
const serverCandidates = pickServerCandidates(roomId);
return `${permalinkBase}${encodeServerCandidates(serverCandidates)}`;
}
export function makeUserPermalink(userId) {
return `${baseUrl}/#/${userId}`;
}
export function makeRoomPermalink(roomId) {
const permalinkBase = `${baseUrl}/#/${roomId}`;
// If the roomId isn't actually a room ID, don't try to list the servers.
// Aliases are already routable, and don't need extra information.
if (roomId[0] !== '!') return permalinkBase;
const serverCandidates = pickServerCandidates(roomId);
return `${permalinkBase}${encodeServerCandidates(serverCandidates)}`;
}
export function makeGroupPermalink(groupId) {
return `${baseUrl}/#/${groupId}`;
}
export function encodeServerCandidates(candidates) {
if (!candidates || candidates.length === 0) return '';
return `?via=${candidates.map(c => encodeURIComponent(c)).join("&via=")}`;
}
export function pickServerCandidates(roomId) {
const client = MatrixClientPeg.get();
const room = client.getRoom(roomId);
if (!room) return [];
// Permalinks can have servers appended to them so that the user // Permalinks can have servers appended to them so that the user
// receiving them can have a fighting chance at joining the room. // receiving them can have a fighting chance at joining the room.
@ -108,10 +69,121 @@ export function pickServerCandidates(roomId) {
// The receiving user can then manually append the known-good server to // The receiving user can then manually append the known-good server to
// the list and magically have the link work. // the list and magically have the link work.
export class RoomPermaLinkCreator {
constructor(room) {
this._room = room;
this._highestPlUserId = null;
this._populationMap = null;
this._bannedHostsRegexps = null;
this._allowedHostsRegexps = null;
this._serverCandidates = null;
this.onPowerlevel = this.onPowerlevel.bind(this);
this.onMembership = this.onMembership.bind(this);
this.onRoomState = this.onRoomState.bind(this);
}
load() {
this._updateAllowedServers();
this._updatePopulationMap();
this._updateServerCandidates();
}
start() {
this.load();
this._room.on("RoomMember.membership", this.onMembership);
this._room.on("RoomMember.powerLevel", this.onPowerlevel);
this._room.on("RoomState.events", this.onRoomState);
}
stop() {
this._room.off("RoomMember.membership", this.onMembership);
this._room.off("RoomMember.powerLevel", this.onPowerlevel);
this._room.off("RoomState.events", this.onRoomState);
}
forEvent(eventId) {
const roomId = this._room.roomId;
const permalinkBase = `${baseUrl}/#/${roomId}/${eventId}`;
// If the roomId isn't actually a room ID, don't try to list the servers.
// Aliases are already routable, and don't need extra information.
if (roomId[0] !== '!') return permalinkBase;
return `${permalinkBase}${encodeServerCandidates(this._serverCandidates)}`;
}
forRoom() {
const roomId = this._room.roomId;
const permalinkBase = `${baseUrl}/#/${roomId}`;
return `${permalinkBase}${encodeServerCandidates(this._serverCandidates)}`;
}
onRoomState(event) {
if (event.getType() === "m.room.server_acl") {
this._updateAllowedServers();
this._updatePopulationMap();
this._updateServerCandidates();
}
}
onMembership(evt, member, oldMembership) {
const userId = member.userId;
const membership = member.membership;
const serverName = getServerName(userId);
const hasJoined = oldMembership !== "join" && membership === "join";
const hasLeft = oldMembership === "join" && membership !== "join";
if (hasLeft) {
this._populationMap[serverName]--;
} else if (hasJoined) {
this._populationMap[serverName]++;
}
this._updateHighestPlUser();
this._updateServerCandidates();
}
onPowerlevel() {
this._updateHighestPlUser();
this._updateServerCandidates();
}
_updateHighestPlUser() {
const plEvent = this._room.currentState.getStateEvents("m.room.power_levels", "");
const content = plEvent.getContent();
if (content) {
const users = content.users;
if (users) {
const entries = Object.entries(users);
const allowedEntries = entries.filter(([userId]) => {
const member = this._room.getMember(userId);
if (!member || member.membership !== "join") {
return false;
}
const serverName = getServerName(userId);
return !isHostnameIpAddress(serverName) &&
!isHostInRegex(serverName, this._bannedHostsRegexps) &&
isHostInRegex(serverName, this._allowedHostsRegexps);
});
const maxEntry = allowedEntries.reduce((max, entry) => {
return (entry[1] > max[1]) ? entry : max;
}, [null, 0]);
const [userId, powerLevel] = maxEntry;
// object wasn't empty, and max entry wasn't a demotion from the default
if (userId !== null && powerLevel > (content.users_default || 0)) {
this._highestPlUserId = userId;
return;
}
}
}
this._highestPlUserId = null;
}
_updateAllowedServers() {
const bannedHostsRegexps = []; const bannedHostsRegexps = [];
let allowedHostsRegexps = [new RegExp(".*")]; // default allow everyone let allowedHostsRegexps = [new RegExp(".*")]; // default allow everyone
if (room.currentState) { if (this._room.currentState) {
const aclEvent = room.currentState.getStateEvents("m.room.server_acl", ""); const aclEvent = this._room.currentState.getStateEvents("m.room.server_acl", "");
if (aclEvent && aclEvent.getContent()) { if (aclEvent && aclEvent.getContent()) {
const getRegex = (hostname) => new RegExp("^" + utils.globToRegexp(hostname, false) + "$"); const getRegex = (hostname) => new RegExp("^" + utils.globToRegexp(hostname, false) + "$");
@ -123,38 +195,67 @@ export function pickServerCandidates(roomId) {
allowed.forEach(h => allowedHostsRegexps.push(getRegex(h))); allowed.forEach(h => allowedHostsRegexps.push(getRegex(h)));
} }
} }
this._bannedHostsRegexps = bannedHostsRegexps;
const populationMap: {[server:string]:number} = {}; this._allowedHostsRegexps = allowedHostsRegexps;
const highestPlUser = {userId: null, powerLevel: 0, serverName: null};
for (const member of room.getJoinedMembers()) {
const serverName = member.userId.split(":").splice(1).join(":");
if (member.powerLevel > highestPlUser.powerLevel && !isHostnameIpAddress(serverName)
&& !isHostInRegex(serverName, bannedHostsRegexps) && isHostInRegex(serverName, allowedHostsRegexps)) {
highestPlUser.userId = member.userId;
highestPlUser.powerLevel = member.powerLevel;
highestPlUser.serverName = serverName;
} }
if (!populationMap[serverName]) populationMap[serverName] = 0; _updatePopulationMap() {
const populationMap: {[server:string]:number} = {};
for (const member of this._room.getJoinedMembers()) {
const serverName = getServerName(member.userId);
if (!populationMap[serverName]) {
populationMap[serverName] = 0;
}
populationMap[serverName]++; populationMap[serverName]++;
} }
this._populationMap = populationMap;
const candidates = [];
if (highestPlUser.powerLevel >= 50) candidates.push(highestPlUser.serverName);
const beforePopulation = candidates.length;
const serversByPopulation = Object.keys(populationMap)
.sort((a, b) => populationMap[b] - populationMap[a])
.filter(a => !candidates.includes(a) && !isHostnameIpAddress(a)
&& !isHostInRegex(a, bannedHostsRegexps) && isHostInRegex(a, allowedHostsRegexps));
for (let i = beforePopulation; i < MAX_SERVER_CANDIDATES; i++) {
const idx = i - beforePopulation;
if (idx >= serversByPopulation.length) break;
candidates.push(serversByPopulation[idx]);
} }
return candidates; _updateServerCandidates() {
let candidates = [];
if (this._highestPlUserId) {
candidates.push(getServerName(this._highestPlUserId));
}
const serversByPopulation = Object.keys(this._populationMap)
.sort((a, b) => this._populationMap[b] - this._populationMap[a])
.filter(a => !candidates.includes(a) && !isHostnameIpAddress(a)
&& !isHostInRegex(a, this._bannedHostsRegexps) && isHostInRegex(a, this._allowedHostsRegexps));
const remainingServers = serversByPopulation.slice(0, MAX_SERVER_CANDIDATES - candidates.length);
candidates = candidates.concat(remainingServers);
this._serverCandidates = candidates;
}
}
export function makeUserPermalink(userId) {
return `${baseUrl}/#/${userId}`;
}
export function makeRoomPermalink(roomId) {
const permalinkBase = `${baseUrl}/#/${roomId}`;
// If the roomId isn't actually a room ID, don't try to list the servers.
// Aliases are already routable, and don't need extra information.
if (roomId[0] !== '!') return permalinkBase;
const serverCandidates = pickServerCandidates(roomId);
return `${permalinkBase}${encodeServerCandidates(serverCandidates)}`;
}
export function makeGroupPermalink(groupId) {
return `${baseUrl}/#/${groupId}`;
}
export function encodeServerCandidates(candidates) {
if (!candidates || candidates.length === 0) return '';
return `?via=${candidates.map(c => encodeURIComponent(c)).join("&via=")}`;
}
function getServerName(userId) {
return userId.split(":").splice(1).join(":");
} }
function getHostnameFromMatrixDomain(domain) { function getHostnameFromMatrixDomain(domain) {