import { HttpStatusCode } from "@rocket.chat/apps-engine/definition/accessors"; import { IApiResponse } from "@rocket.chat/apps-engine/definition/api"; import { Context } from "./Context"; import { SCIMGroup } from "./scim/Group"; import { SCIMUser } from "./scim/User"; import { IScimEndpoint, ScimEndpoint } from "./ScimEndpoint"; export class GroupEndpoint extends ScimEndpoint implements IScimEndpoint { public path = "Groups/:id"; public async _get(ctx: Context): Promise { const getTeamInfo = async () => { const teamRaw = await ctx.rc.team.info(ctx.id()); this.handleError(teamRaw); return teamRaw.teamInfo; }; const getTeamMembers = async () => { const membersRaw = await ctx.rc.team.members(ctx.id()); this.handleError(membersRaw); return membersRaw.members; }; const teamArgs = await Promise.all([getTeamInfo(), getTeamMembers()]); const group = SCIMGroup.fromRC(...teamArgs); return this.success(group); } public async _put(ctx: Context): Promise { const membersRaw = await ctx.rc.team.members(ctx.id()); this.handleError(membersRaw); const targetIds = new Set( SCIMGroup.fromPlain(ctx.content()).members.map((x) => x.value), ); const currentIds = new Set( membersRaw.members.map((x: ITeamMember) => x.user._id), ); const removeMember = async (userId: string) => { const removeMembersRaw = await ctx.rc.team.removeMember({ userId, teamId: ctx.id(), }); this.handleError(removeMembersRaw); }; const addMembers = async (userIds: Array) => { const addMembersRaw = await ctx.rc.team.addMembers({ teamId: ctx.id(), members: userIds.map((userId) => ({ userId, roles: ["member"], })), }); this.handleError(addMembersRaw); }; const promises: Array> = []; for (const currentId of currentIds) { if (!targetIds.has(currentId)) { promises.push(removeMember(currentId)); } } const addMemberIds: Array = []; for (const targetId of targetIds) { if (!currentIds.has(targetId)) { addMemberIds.push(targetId); } } if (addMemberIds.length > 0) { promises.push(addMembers(addMemberIds)); } await Promise.all(promises); return this._get(ctx); } public async _delete(ctx: Context): Promise { const o = await ctx.rc.team.delete({ teamId: ctx.id() }); this.handleError(o); return this.response({ status: HttpStatusCode.NO_CONTENT, }); } }