-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathbridge-info-state.ts
More file actions
149 lines (138 loc) · 5.27 KB
/
Copy pathbridge-info-state.ts
File metadata and controls
149 lines (138 loc) · 5.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import { Bridge } from "../bridge";
import { Logger } from "..";
import PQueue from "p-queue";
const log = new Logger("BridgeStateSyncer");
export interface MappingInfo {
creator?: string;
protocol: {
id: string;
displayname?: string;
// eslint-disable-next-line camelcase
avatar_url?: `mxc://${string}`;
// eslint-disable-next-line camelcase
external_url?: string;
};
network?: {
id: string;
displayname?: string;
// eslint-disable-next-line camelcase
avatar_url?: `mxc://${string}`;
// eslint-disable-next-line camelcase
external_url?: string;
};
channel: {
id: string;
displayname?: string;
// eslint-disable-next-line camelcase
avatar_url?: `mxc://${string}`;
// eslint-disable-next-line camelcase
external_url?: string;
};
}
export interface MSC2346Content extends MappingInfo {
bridgebot: string;
}
export interface InitialEvent {
type: string,
content: Record<string, unknown>,
state_key: string,
}
interface Opts<BridgeMappingInfo> {
/**
* The name of the bridge implementation, ideally in Java package naming format:
* @example org.matrix.matrix-appservice-irc
*/
bridgeName: string;
/**
* This should return some standard information about a given
* mapping.
*/
getMapping: (roomId: string, info: BridgeMappingInfo) => Promise<MappingInfo>;
}
/**
* This class ensures that rooms contain a valid bridge info
* event ([MSC2346](https://github.com/matrix-org/matrix-doc/pull/2346))
* which displays the connected protocol, network and room.
*/
export class BridgeInfoStateSyncer<BridgeMappingInfo> {
public static readonly EventType = "uk.half-shot.bridge";
constructor(private bridge: Bridge, private opts: Opts<BridgeMappingInfo>) {
}
/**
* Check all rooms and ensure they have correct state.
* @param allMappings All bridged room mappings
* @param concurrency How many rooms to handle at a time, defaults to 3.
*/
public async initialSync(allMappings: Record<string, BridgeMappingInfo[]>, concurrency = 3): Promise<void> {
log.info("Beginning sync of bridge state events");
const syncQueue = new PQueue({ concurrency });
Object.entries(allMappings).forEach(([roomId, mappings]) => {
syncQueue.add(() => this.syncRoom(roomId, mappings));
});
return syncQueue.onIdle();
}
private async syncRoom(roomId: string, mappings: BridgeMappingInfo[]) {
log.info(`Syncing ${roomId}`);
const intent = this.bridge.getIntent();
for (const mappingInfo of mappings) {
const realMapping = await this.opts.getMapping(roomId, mappingInfo);
const key = this.createStateKey(realMapping);
const content = this.createBridgeInfoContent(realMapping);
try {
const eventData: MSC2346Content|null = await intent.getStateEvent(
roomId, BridgeInfoStateSyncer.EventType, key, true
);
if (eventData !== null) { // If found, validate.
if (JSON.stringify(eventData) === JSON.stringify(content)) {
continue;
}
log.debug(`${key} for ${roomId} is invalid, updating`);
}
}
catch (ex) {
log.warn(`Encountered error when trying to sync ${roomId}`, ex);
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(realMapping);
try {
await intent.sendStateEvent(
roomId, BridgeInfoStateSyncer.EventType, key, eventContent as unknown as Record<string, unknown>
);
}
catch (ex) {
log.error(
`Failed to update room with new state content: ${ex instanceof Error ? ex.message : ex}`
);
}
}
}
public async createInitialState(roomId: string, bridgeMappingInfo: BridgeMappingInfo): Promise<InitialEvent> {
const mapping = await this.opts.getMapping(roomId, bridgeMappingInfo);
return {
type: BridgeInfoStateSyncer.EventType,
content: this.createBridgeInfoContent(mapping) as unknown as Record<string, unknown>,
state_key: this.createStateKey(mapping),
};
}
public createStateKey(mapping: MappingInfo) {
const networkId = mapping.network ? mapping.network?.id.replace(/\//g, "%2F") + "/" : "";
const channel = mapping.channel.id.replace(/\//g, "%2F");
return `${this.opts.bridgeName}:/${networkId}${channel}`;
}
public createBridgeInfoContent(mapping: MappingInfo)
: MSC2346Content {
const content: MSC2346Content = {
bridgebot: this.bridge.botUserId,
protocol: mapping.protocol,
channel: mapping.channel,
};
if (mapping.creator) {
content.creator = mapping.creator;
}
if (mapping.network) {
content.network = mapping.network;
}
return content;
}
}