Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if (options.help) {
/* tslint:disable:no-console */
console.log(usage([
{
content: "A tool to set all the bridged rooms to visible in the directory.",
header: "Add rooms to directory",
},
{
header: "Options",
optionList: optionDefinitions,
},
]));
process.exit(0);
}
const yamlConfig = yaml.safeLoad(fs.readFileSync("./discord-registration.yaml", "utf8"));
const registration = AppServiceRegistration.fromObject(yamlConfig);
const config: DiscordBridgeConfig = yaml.safeLoad(fs.readFileSync(options.config, "utf8")) as DiscordBridgeConfig;
if (registration === null) {
throw new Error("Failed to parse registration file");
}
const clientFactory = new ClientFactory({
appServiceUserId: `@${registration.sender_localpart}:${config.bridge.domain}`,
token: registration.as_token,
url: config.bridge.homeserverUrl,
});
const bridge = new Bridge({
controller: {
onEvent: () => { },
},
const yamlConfig = yaml.safeLoad(fs.readFileSync("discord-registration.yaml", "utf8"));
const registration = AppServiceRegistration.fromObject(yamlConfig);
const config: DiscordBridgeConfig = yaml.safeLoad(fs.readFileSync(options.config, "utf8")) as DiscordBridgeConfig;
if (registration === null) {
throw new Error("Failed to parse registration file");
}
const clientFactory = new ClientFactory({
appServiceUserId: `@${registration.sender_localpart}:${config.bridge.domain}`,
token: registration.as_token,
url: config.bridge.homeserverUrl,
});
const client = clientFactory.getClientAs();
const intent = new Intent(client, client, {registered: true});
async function run() {
try {
await intent.setPowerLevel(options.roomid, options.userid, options.power);
console.log("Power levels set");
process.exit(0);
} catch (err) {
console.error("Could not apply power levels to room:", err);
process.exit(1);
}
}
run(); // tslint:disable-line no-floating-promises
constructor() {
this.cli = new Cli({
bridgeConfig: {
affectsRegistration: true,
schema: "./config/config.schema.yaml",
},
registrationPath: "purple-registration.yaml",
generateRegistration: this.generateRegistration,
run: this.runBridge.bind(this),
});
this.cfg = new Config();
this.deduplicator = new Deduplicator();
// For testing w/o libpurple.
// this.purple = new MockPurpleInstance();
// setTimeout(() => {
// (this.purple as MockPurpleInstance).emit("received-im-msg", {
// sender: "testacc@localhost/",
// message: "test",
]));
process.exit(0);
}
const yamlConfig = yaml.safeLoad(fs.readFileSync("./discord-registration.yaml", "utf8"));
const registration = AppServiceRegistration.fromObject(yamlConfig);
const config = new DiscordBridgeConfig();
config.applyConfig(yaml.safeLoad(fs.readFileSync(options.config, "utf8")) as DiscordBridgeConfig);
config.applyEnvironmentOverrides(process.env);
if (registration === null) {
throw new Error("Failed to parse registration file");
}
const botUserId = `@${registration.sender_localpart}:${config.bridge.domain}`;
const clientFactory = new ClientFactory({
appServiceUserId: botUserId,
token: registration.as_token,
url: config.bridge.homeserverUrl,
});
const bridge = new Bridge({
clientFactory,
controller: {
onEvent: () => { },
},
domain: config.bridge.domain,
homeserverUrl: config.bridge.homeserverUrl,
intentOptions: {
clients: {
dontJoin: true, // handled manually
},
]));
process.exit(0);
}
const yamlConfig = yaml.safeLoad(fs.readFileSync("./discord-registration.yaml", "utf8"));
const registration = AppServiceRegistration.fromObject(yamlConfig);
const config = new DiscordBridgeConfig();
config.applyConfig(yaml.safeLoad(fs.readFileSync(options.config, "utf8")) as DiscordBridgeConfig);
config.applyEnvironmentOverrides(process.env);
if (registration === null) {
throw new Error("Failed to parse registration file");
}
const botUserId = `@${registration.sender_localpart}:${config.bridge.domain}`;
const clientFactory = new ClientFactory({
appServiceUserId: botUserId,
token: registration.as_token,
url: config.bridge.homeserverUrl,
});
const bridge = new Bridge({
clientFactory,
controller: {
onEvent: () => { },
},
domain: config.bridge.domain,
homeserverUrl: config.bridge.homeserverUrl,
intentOptions: {
clients: {
dontJoin: true, // handled manually
},
async function run() {
await bridge.loadDatabases();
const store = new DiscordStore(config.database);
await store.init(undefined, bridge.getRoomStore());
const discordbot = new DiscordBot(botUserId, config, bridge, store);
await discordbot.init();
bridge._clientFactory = clientFactory;
bridge._botClient = bridge._clientFactory.getClientAs();
bridge._botIntent = new Intent(bridge._botClient, bridge._botClient, { registered: true });
await discordbot.ClientFactory.init();
const client = await discordbot.ClientFactory.getClient();
// first set update_icon to true if needed
const mxRoomEntries = await bridge.getRoomStore().getEntriesByRemoteRoomData({
update_name: true,
update_topic: true,
});
const promiseList: Promise[] = [];
mxRoomEntries.forEach((entry) => {
if (entry.remote.get("plumbed")) {
return; // skipping plumbed rooms
}
const updateIcon = entry.remote.get("update_icon");
if (updateIcon !== undefined && updateIcon !== null) {
private createRtmClient(token: string, logLabel: string): RTMClient {
const LOG_LEVELS = ["debug", "info", "warn", "error", "silent"];
const connLog = Logging.get(`RTM-${logLabel.substr(0, LOG_TEAM_LEN)}`);
const logLevel = LOG_LEVELS.indexOf(this.main.config.rtm!.log_level || "silent");
const rtm = new RTMClient(token, {
logLevel: LogLevel.DEBUG, // We will filter this ourselves.
logger: {
getLevel: () => LogLevel.DEBUG,
setLevel: () => {},
setName: () => {}, // We handle both of these ourselves.
debug: logLevel <= 0 ? connLog.debug.bind(connLog) : () => {},
warn: logLevel <= 1 ? connLog.warn.bind(connLog) : () => {},
info: logLevel <= 2 ? connLog.info.bind(connLog) : () => {},
error: logLevel <= 3 ? connLog.error.bind(connLog) : () => {},
} as Logger,
});
rtm.on("error", (error) => {
// We must handle this lest the process be killed.
IUserStateChanged,
IChatStringState,
IChatTyping,
IStoreRemoteUser,
IChatReadReceipt,
} from "./purple/PurpleEvents";
import { ProfileSync } from "./ProfileSync";
import { Util } from "./Util";
import { ProtoHacks } from "./ProtoHacks";
import { Store } from "./Store";
import { Deduplicator } from "./Deduplicator";
import { Config } from "./Config";
import * as entityDecode from "parse-entities";
import { MessageFormatter } from "./MessageFormatter";
import { IEventRequest, IEventRequestData } from "./MatrixTypes";
const log = Logging.get("MatrixRoomHandler");
const ACCOUNT_LOCK_MS = 1000;
const EVENT_MAPPING_SIZE = 16384;
/**
* Handles creation and handling of rooms.
*/
export class MatrixRoomHandler {
private bridge: Bridge;
private accountRoomLock: Set;
private remoteEventIdMapping: Map; // remote_id -> event_id
private roomCreationLock: Map>;
constructor(
private purple: IPurpleInstance,
private profileSync: ProfileSync,
private store: Store,
import { IConfigAutoReg } from "./Config";
import { Bridge, MatrixUser } from "matrix-appservice-bridge";
import * as request from "request-promise-native";
import { Util } from "./Util";
import { Logging } from "matrix-appservice-bridge";
import { Store } from "./Store";
import { IPurpleInstance } from "./purple/IPurpleInstance";
import { IPurpleAccount } from "./purple/IPurpleAccount";
import { PurpleProtocol } from "./purple/PurpleProtocol";
import { MUSER_TYPE_ACCOUNT } from "./StoreTypes";
const log = Logging.get("AutoRegistration");
export interface IAutoRegHttpOpts {
method: string;
usernameResult: string|null;
}
export interface IAutoRegStep {
type: "http"|"executable"|"implicit";
path: string;
opts: IAutoRegHttpOpts|undefined;
parameters: {[key: string]: string}; // key -> parameter value
paramsToStore: string[];
headers: {[key: string]: string}; // key -> value
}
export class AutoRegistration {
public GetIntentFromDiscordMember(member: Discord.GuildMember | Discord.User, webhookID?: string): Intent {
if (webhookID) {
// webhookID and user IDs are the same, they are unique, so no need to prefix _webhook_
const name = member instanceof Discord.User ? member.username : member.user.username;
const nameId = new MatrixUser(`@${name}`).localpart;
return this.bridge.getIntentFromLocalpart(`_discord_${webhookID}_${nameId}`);
}
return this.bridge.getIntentFromLocalpart(`_discord_${member.id}`);
}