2022-11-15 13:03:06 -05:00
|
|
|
import * as request from "request";
|
|
|
|
import { MatrixClient } from "matrix-bot-sdk";
|
|
|
|
|
|
|
|
interface OpenIDTokenInfo {
|
|
|
|
access_token: string,
|
|
|
|
expires_in: number,
|
|
|
|
matrix_server_name: string,
|
|
|
|
token_type: string
|
|
|
|
}
|
|
|
|
|
|
|
|
async function getOpenIDToken(client: MatrixClient): Promise<string> {
|
|
|
|
const tokenInfo: OpenIDTokenInfo = await client.doRequest("POST", `/_matrix/client/v3/user/${await client.getUserId()}/openid/request_token`, undefined, {});
|
|
|
|
return tokenInfo.access_token;
|
|
|
|
}
|
|
|
|
|
|
|
|
export interface CreateMjolnirResponse {
|
|
|
|
mjolnirUserId: string,
|
|
|
|
managementRoomId: string,
|
|
|
|
}
|
|
|
|
|
|
|
|
export class MjolnirWebAPIClient {
|
|
|
|
|
|
|
|
private constructor(
|
|
|
|
private readonly openIDToken: string,
|
|
|
|
private readonly baseURL: string,
|
|
|
|
) {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
public static async makeClient(client: MatrixClient, baseUrl: string): Promise<MjolnirWebAPIClient> {
|
|
|
|
const token = await getOpenIDToken(client);
|
2022-11-28 07:55:43 -05:00
|
|
|
return new MjolnirWebAPIClient(token, baseUrl);
|
2022-11-15 13:03:06 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
public async createMjolnir(roomToProtectId: string): Promise<CreateMjolnirResponse> {
|
|
|
|
const body: { mxid: string, roomId: string } = await new Promise((resolve, reject) => {
|
|
|
|
request.post(`${this.baseURL}/create`, {
|
|
|
|
json: {
|
|
|
|
openId: this.openIDToken,
|
|
|
|
roomId: roomToProtectId,
|
|
|
|
},
|
|
|
|
}, (error, response) => error ? reject(error) : resolve(response.body))
|
|
|
|
});
|
|
|
|
return {
|
|
|
|
mjolnirUserId: body.mxid,
|
|
|
|
managementRoomId: body.roomId
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|