Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement MSC2346 - Bridge state info #941

Merged
merged 10 commits into from
Jan 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/941.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add support for MSC2346; adding information about the bridged channel into room state.
6 changes: 5 additions & 1 deletion config.sample.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,11 @@ ircService:
# through the bridge e.g. caller ID as there is no way to /ACCEPT.
# Default: "" (no user modes)
# userModes: "R"

# Set information about the bridged channel in the room state, so that client's may
# present relevant UI to the user. MSC2346
bridgeInfoState:
enabled: false
initial: false
# Configuration for an ident server. If you are running a public bridge it is
# advised you setup an ident server so IRC mods can ban specific matrix users
# rather than the application service itself.
Expand Down
7 changes: 7 additions & 0 deletions config.schema.yml
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@ properties:
mapIrcMentionsToMatrix:
type: "string"
enum: ["on", "off", "force-off"]
bridgeInfoState:
type: "object"
properties:
enabled:
type: "boolean"
initial:
type: "boolean"
servers:
type: "object"
# all properties must follow the following
Expand Down
8 changes: 8 additions & 0 deletions src/bridge/AdminRoomHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,14 @@ export class AdminRoomHandler {
}
});
}
if (this.ircBridge.stateSyncer) {
initialState.push(
this.ircBridge.stateSyncer.createInitialState(
server,
ircChannel,
)
)
}
const ircRoom = await this.ircBridge.trackChannel(server, ircChannel, key);
const response = await this.ircBridge.getAppServiceBridge().getIntent(
sender,
Expand Down
147 changes: 147 additions & 0 deletions src/bridge/BridgeStateSyncer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import { DataStore } from "../datastore/DataStore";
import { QueuePool } from "../util/QueuePool";
import { Bridge } from "matrix-appservice-bridge";
import logging from "../logging";
import { IrcBridge } from "./IrcBridge";
import { IrcServer } from "../irc/IrcServer";

const log = logging("BridgeStateSyncer");

const SYNC_CONCURRENCY = 3;

interface QueueItem {
roomId: string;
mappings: Array<{networkId: string; channel: string}>;
}

/**
* This class will set bridge room state according to [MSC2346](https://github.com/matrix-org/matrix-doc/pull/2346)
*/
export class BridgeStateSyncer {
public static readonly EventType = "uk.half-shot.bridge";
private syncQueue: QueuePool<QueueItem>;
constructor(private datastore: DataStore, private bridge: Bridge, private ircBridge: IrcBridge) {
this.syncQueue = new QueuePool(SYNC_CONCURRENCY, this.syncRoom.bind(this));
}

public async beginSync() {
log.info("Beginning sync of bridge state events");
const allMappings = await this.datastore.getAllChannelMappings();
Object.entries(allMappings).forEach(([roomId, mappings]) => {
this.syncQueue.enqueue(roomId, {roomId, mappings});
});
}

private async syncRoom(item: QueueItem) {
log.info(`Syncing ${item.roomId}`);
const intent = this.bridge.getIntent();
for (const mapping of item.mappings) {
const key = BridgeStateSyncer.createStateKey(mapping.networkId, mapping.channel);
try {
const eventData = await this.getStateEvent(item.roomId, BridgeStateSyncer.EventType, key);
if (eventData !== null) { // If found, validate.
const expectedContent = this.createBridgeInfoContent(
mapping.networkId, mapping.channel
);

const isValid = expectedContent.channel.id === eventData.channel.id &&
expectedContent.network.id === eventData.network.id &&
expectedContent.network.displayname === eventData.network.displayname &&
expectedContent.protocol.id === eventData.protocol.id &&
expectedContent.protocol.displayname === eventData.protocol.displayname;

if (isValid) {
log.debug(`${key} is valid`);
continue;
}
log.info(`${key} is invalid`);
}
}
catch (ex) {
log.warn(`Encountered error when trying to sync ${item.roomId}`);
break; // To be on the safe side, do not retry this room.
}

// Event wasn't found or was invalid, let's try setting one.
const eventContent = this.createBridgeInfoContent(mapping.networkId, mapping.channel);
const owner = await this.determineProvisionedOwner(item.roomId, mapping.networkId, mapping.channel);
eventContent.creator = owner || intent.client.credentials.userId;
try {
await intent.sendStateEvent(item.roomId, BridgeStateSyncer.EventType, key, eventContent);
}
catch (ex) {
log.error(`Failed to update room with new state content: ${ex.message}`);
}
}
}

public createInitialState(server: IrcServer, channel: string, owner?: string) {
return {
type: BridgeStateSyncer.EventType,
content: this.createBridgeInfoContent(server, channel, owner),
state_key: BridgeStateSyncer.createStateKey(server.domain, channel)
};
}

public static createStateKey(networkId: string, channel: string) {
networkId = networkId.replace(/\//g, "%2F");
channel = channel.replace(/\//g, "%2F");
return `org.matrix.appservice-irc://irc/${networkId}/${channel}`
}

public createBridgeInfoContent(networkIdOrServer: string|IrcServer, channel: string, creator?: string) {
const server = typeof(networkIdOrServer) === "string" ?
this.ircBridge.getServer(networkIdOrServer) : networkIdOrServer;
if (!server) {
throw Error("Server not known");
}
const serverName = server.getReadableName();
return {
creator: creator || "", // Is this known?
protocol: {
id: "irc",
displayname: "IRC",
},
network: {
id: server.domain,
displayname: serverName,
},
channel: {
id: channel,
external_url: `irc://${server.domain}/${channel}`
}
}
}

private async determineProvisionedOwner(roomId: string, networkId: string, channel: string): Promise<string|null> {
const room = await this.datastore.getRoom(roomId, networkId, channel);
if (!room || room.data.origin !== "provision") {
return null;
}
// Find out who dun it
try {
const ev = await this.getStateEvent(roomId, "m.room.bridging", `irc://${networkId}/${channel}`);
if (ev?.status === "success") {
return ev.user_id;
}
// Event not found or invalid, leave blank.
}
catch (ex) {
log.warn(`Failed to get m.room.bridging information for room: ${ex.message}`);
}
return null;
}

private async getStateEvent(roomId: string, eventType: string, key: string) {
const intent = this.bridge.getIntent();
try {
return await intent.getStateEvent(roomId, eventType, key);
}
catch (ex) {
if (ex.errcode !== "M_NOT_FOUND") {
throw ex;
}
}
return null;
}
}
38 changes: 35 additions & 3 deletions src/bridge/IrcBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ import { DataStore } from "../datastore/DataStore";
import { MatrixAction } from "../models/MatrixAction";
import { BridgeConfig } from "../config/BridgeConfig";
import { MembershipQueue } from "../util/MembershipQueue";

import { BridgeStateSyncer } from "./BridgeStateSyncer";

const log = getLogger("IrcBridge");
const DEFAULT_PORT = 8090;
Expand Down Expand Up @@ -67,6 +67,8 @@ export class IrcBridge {
}|null = null;
private membershipCache: MembershipCache;
private readonly membershipQueue: MembershipQueue;
private bridgeStateSyncer!: BridgeStateSyncer;

constructor(public readonly config: BridgeConfig, private registration: AppServiceRegistration) {
// TODO: Don't log this to stdout
Logging.configure({console: config.ircService.logging.level});
Expand Down Expand Up @@ -313,6 +315,10 @@ export class IrcBridge {
return this.config.homeserver.domain;
}

public get stateSyncer() {
return this.bridgeStateSyncer;
}

public async run(port: number|null) {
const dbConfig = this.config.database;
// cli port, then config port, then default port
Expand Down Expand Up @@ -414,6 +420,17 @@ export class IrcBridge {
this.membershipCache.setMemberEntry(roomId, this.appServiceUserId, "join");
}

if (this.config.ircService.bridgeInfoState?.enabled) {
this.bridgeStateSyncer = new BridgeStateSyncer(this.dataStore, this.bridge, this);
if (this.config.ircService.bridgeInfoState.initial) {
this.bridgeStateSyncer.beginSync().then(() => {
log.info("Bridge state syncing completed");
}).catch((err) => {
log.error("Bridge state syncing resulted in an error:", err);
});
}
}

log.info("Joining mapped Matrix rooms...");
await this.joinMappedMatrixRooms();
log.info("Syncing relevant membership lists...");
Expand Down Expand Up @@ -1010,12 +1027,12 @@ export class IrcBridge {
}
});
const bridgingEvent = stateEvents.find((ev: {type: string}) => ev.type === "m.room.bridging");
const bridgeInfoEvent = stateEvents.find((ev: {type: string}) => ev.type === BridgeStateSyncer.EventType);
if (bridgingEvent) {
// The room had a bridge state event, so try to stick it in the new one.
try {
await this.bridge.getIntent().sendStateEvent(
newRoomId,
"m.room.bridging",
bridgingEvent.type,
bridgingEvent.state_key,
bridgingEvent.content
);
Expand All @@ -1026,6 +1043,21 @@ export class IrcBridge {
log.warn("Could not send m.room.bridging event to new room:", ex);
}
}
if (bridgeInfoEvent) {
try {
await this.bridge.getIntent().sendStateEvent(
newRoomId,
bridgeInfoEvent.type,
bridgingEvent.state_key,
bridgingEvent.content
);
log.info("Bridge info event copied to new room");
}
catch (ex) {
// We may not have permissions to do so, which means we are basically stuffed.
log.warn("Could not send bridge info event to new room:", ex);
}
}
await Bluebird.all(rooms.map((room) => {
return this.getBotClient(room.getServer()).then((bot) => {
// This will invoke NAMES and make members join the new room,
Expand Down
9 changes: 9 additions & 0 deletions src/bridge/IrcHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,15 @@ export class IrcHandler {
}
});
}

if (this.ircBridge.stateSyncer) {
initialState.push(
this.ircBridge.stateSyncer.createInitialState(
server,
channel,
)
)
}
const ircRoom = await this.ircBridge.trackChannel(server, channel);
const response = await this.ircBridge.getAppServiceBridge().getIntent(
virtualMatrixUser.getId()
Expand Down
8 changes: 8 additions & 0 deletions src/bridge/MatrixHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1029,6 +1029,14 @@ export class MatrixHandler {
}
});
}
if (this.ircBridge.stateSyncer) {
options.initial_state.push(
this.ircBridge.stateSyncer.createInitialState(
channelInfo.server,
channelInfo.channel,
)
)
}
if (channelInfo.server.forceRoomVersion()) {
options.room_version = channelInfo.server.forceRoomVersion();
}
Expand Down
4 changes: 4 additions & 0 deletions src/config/BridgeConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ export interface BridgeConfig {
address: string;
port: number;
};
bridgeInfoState?: {
enabled: boolean;
initial: boolean;
};
};
sentry?: {
enabled: boolean;
Expand Down
11 changes: 11 additions & 0 deletions src/provisioning/Provisioner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import * as express from "express";
import { IrcServer } from "../irc/IrcServer";
import { IrcUser } from "../models/IrcUser";
import { BridgedClient, GetNicksResponseOperators } from "../irc/BridgedClient";
import { BridgeStateSyncer } from "../bridge/BridgeStateSyncer";

const log = logging("Provisioner");

Expand Down Expand Up @@ -566,6 +567,16 @@ export class Provisioner {
return;
}
await this.updateBridgingState(roomId, userId, 'success', skey);
// Send bridge info state event
if (this.ircBridge.stateSyncer) {
const intent = this.ircBridge.getAppServiceBridge().getIntent();
await intent.sendStateEvent(
roomId,
BridgeStateSyncer.EventType,
BridgeStateSyncer.createStateKey(server.domain, ircChannel),
this.ircBridge.stateSyncer.createBridgeInfoContent(server, ircChannel, userId)
);
}
}

private removeRequest (server: IrcServer, opNick: string) {
Expand Down