mirror of
https://github.com/turt2live/matrix-dimension.git
synced 2024-10-01 05:05:53 +00:00
Self-service Slack provisioning
Fixes https://github.com/turt2live/matrix-dimension/issues/5 Fixes https://github.com/turt2live/matrix-dimension/issues/8
This commit is contained in:
parent
02e58e7a8d
commit
99e0647cd7
104
src/api/dimension/DimensionSlackService.ts
Normal file
104
src/api/dimension/DimensionSlackService.ts
Normal file
@ -0,0 +1,104 @@
|
||||
import { DELETE, GET, Path, PathParam, POST, QueryParam } from "typescript-rest";
|
||||
import { ScalarService } from "../scalar/ScalarService";
|
||||
import { ApiError } from "../ApiError";
|
||||
import { LogService } from "matrix-js-snippets";
|
||||
import { BridgedChannel, SlackBridge } from "../../bridges/SlackBridge";
|
||||
import { SlackChannel, SlackTeam } from "../../bridges/models/slack";
|
||||
|
||||
interface BridgeRoomRequest {
|
||||
teamId: string;
|
||||
channelId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* API for interacting with the Slack bridge
|
||||
*/
|
||||
@Path("/api/v1/dimension/slack")
|
||||
export class DimensionSlackService {
|
||||
|
||||
@GET
|
||||
@Path("room/:roomId/link")
|
||||
public async getLink(@QueryParam("scalar_token") scalarToken: string, @PathParam("roomId") roomId: string): Promise<BridgedChannel> {
|
||||
const userId = await ScalarService.getTokenOwner(scalarToken);
|
||||
|
||||
try {
|
||||
const slack = new SlackBridge(userId);
|
||||
return slack.getLink(roomId);
|
||||
} catch (e) {
|
||||
LogService.error("DimensionSlackService", e);
|
||||
throw new ApiError(400, "Error getting bridge info");
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("room/:roomId/link")
|
||||
public async bridgeRoom(@QueryParam("scalar_token") scalarToken: string, @PathParam("roomId") roomId: string, request: BridgeRoomRequest): Promise<BridgedChannel> {
|
||||
const userId = await ScalarService.getTokenOwner(scalarToken);
|
||||
|
||||
try {
|
||||
const slack = new SlackBridge(userId);
|
||||
await slack.requestEventsLink(roomId, request.teamId, request.channelId);
|
||||
return slack.getLink(roomId);
|
||||
} catch (e) {
|
||||
LogService.error("DimensionSlackService", e);
|
||||
throw new ApiError(400, "Error bridging room");
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("room/:roomId/link")
|
||||
public async unbridgeRoom(@QueryParam("scalar_token") scalarToken: string, @PathParam("roomId") roomId: string): Promise<any> {
|
||||
const userId = await ScalarService.getTokenOwner(scalarToken);
|
||||
|
||||
try {
|
||||
const slack = new SlackBridge(userId);
|
||||
const link = await slack.getLink(roomId);
|
||||
if (link.isWebhook) await slack.removeWebhooksLink(roomId);
|
||||
else await slack.removeEventsLink(roomId, link.teamId, link.channelId);
|
||||
return {}; // 200 OK
|
||||
} catch (e) {
|
||||
LogService.error("DimensionSlackService", e);
|
||||
throw new ApiError(400, "Error unbridging room");
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("teams")
|
||||
public async getTeams(@QueryParam("scalar_token") scalarToken: string): Promise<SlackTeam[]> {
|
||||
const userId = await ScalarService.getTokenOwner(scalarToken);
|
||||
|
||||
const slack = new SlackBridge(userId);
|
||||
const teams = await slack.getTeams();
|
||||
if (!teams) throw new ApiError(404, "No teams found");
|
||||
return teams;
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("teams/:teamId/channels")
|
||||
public async getChannels(@QueryParam("scalar_token") scalarToken: string, @PathParam("teamId") teamId: string): Promise<SlackChannel[]> {
|
||||
const userId = await ScalarService.getTokenOwner(scalarToken);
|
||||
|
||||
try {
|
||||
const slack = new SlackBridge(userId);
|
||||
return slack.getChannels(teamId);
|
||||
} catch (e) {
|
||||
LogService.error("DimensionSlackService", e);
|
||||
throw new ApiError(400, "Error getting channel info");
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("auth")
|
||||
public async getAuthUrl(@QueryParam("scalar_token") scalarToken: string): Promise<{ authUrl: string }> {
|
||||
const userId = await ScalarService.getTokenOwner(scalarToken);
|
||||
|
||||
try {
|
||||
const slack = new SlackBridge(userId);
|
||||
const authUrl = await slack.getAuthUrl();
|
||||
return {authUrl};
|
||||
} catch (e) {
|
||||
LogService.error("DimensionSlackService", e);
|
||||
throw new ApiError(400, "Error getting auth info");
|
||||
}
|
||||
}
|
||||
}
|
@ -6,6 +6,7 @@ import * as request from "request";
|
||||
import { ModularSlackResponse } from "../models/ModularResponses";
|
||||
import SlackBridgeRecord from "../db/models/SlackBridgeRecord";
|
||||
import {
|
||||
AuthUrlResponse,
|
||||
BridgedChannelResponse,
|
||||
ChannelsResponse,
|
||||
GetBotUserIdResponse,
|
||||
@ -98,7 +99,7 @@ export class SlackBridge {
|
||||
}
|
||||
}
|
||||
|
||||
public async requestEventsLink(roomId: string, channelId: string, teamId: string): Promise<any> {
|
||||
public async requestEventsLink(roomId: string, teamId: string, channelId: string): Promise<any> {
|
||||
const bridge = await this.getDefaultBridge();
|
||||
|
||||
const requestBody = {
|
||||
@ -116,7 +117,7 @@ export class SlackBridge {
|
||||
}
|
||||
}
|
||||
|
||||
public async removeEventsLink(roomId: string, channelId: string, teamId: string): Promise<any> {
|
||||
public async removeEventsLink(roomId: string, teamId: string, channelId: string): Promise<any> {
|
||||
const bridge = await this.getDefaultBridge();
|
||||
|
||||
const requestBody = {
|
||||
@ -205,6 +206,33 @@ export class SlackBridge {
|
||||
}
|
||||
}
|
||||
|
||||
public async getAuthUrl(): Promise<string> {
|
||||
const bridge = await this.getDefaultBridge();
|
||||
|
||||
const requestBody = {
|
||||
user_id: this.requestingUserId,
|
||||
};
|
||||
|
||||
try {
|
||||
if (bridge.upstreamId) {
|
||||
delete requestBody["user_id"];
|
||||
const response = await this.doUpstreamRequest<ModularSlackResponse<AuthUrlResponse>>(bridge, "POST", "/bridges/slack/_matrix/provision/authurl", null, requestBody);
|
||||
if (!response || !response.replies || !response.replies[0] || !response.replies[0].response) {
|
||||
// noinspection ExceptionCaughtLocallyJS
|
||||
throw new Error("Invalid response from Modular for Slack get auth url for " + this.requestingUserId);
|
||||
}
|
||||
return response.replies[0].response.auth_uri;
|
||||
} else {
|
||||
const response = await this.doProvisionRequest<AuthUrlResponse>(bridge, "POST", "/_matrix/provision/authurl", null, requestBody);
|
||||
return response.auth_uri;
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.status === 404) return null;
|
||||
LogService.error("SlackBridge", e);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private async doUpstreamRequest<T>(bridge: IrcBridgeRecord, method: string, endpoint: string, qs?: any, body?: any): Promise<T> {
|
||||
const upstream = await Upstream.findByPrimary(bridge.upstreamId);
|
||||
const token = await UserScalarToken.findOne({
|
||||
|
@ -104,6 +104,8 @@ import { SpotifyWidgetWrapperComponent } from "./widget-wrappers/spotify/spotify
|
||||
import { AdminCustomSimpleBotsApiService } from "./shared/services/admin/admin-custom-simple-bots-api.service";
|
||||
import { AdminCustomBotsComponent } from "./admin/custom-bots/custom-bots.component";
|
||||
import { AdminAddCustomBotComponent } from "./admin/custom-bots/add/add.component";
|
||||
import { SlackApiService } from "./shared/services/integrations/slack-api.service";
|
||||
import { SlackBridgeConfigComponent } from "./configs/bridge/slack/slack.bridge.component";
|
||||
import { AdminSlackBridgeManageSelfhostedComponent } from "./admin/bridges/slack/manage-selfhosted/manage-selfhosted.component";
|
||||
import { AdminSlackBridgeComponent } from "./admin/bridges/slack/slack.component";
|
||||
import { AdminSlackApiService } from "./shared/services/admin/admin-slack-api.service";
|
||||
@ -193,6 +195,7 @@ import { AdminSlackApiService } from "./shared/services/admin/admin-slack-api.se
|
||||
SpotifyWidgetWrapperComponent,
|
||||
AdminCustomBotsComponent,
|
||||
AdminAddCustomBotComponent,
|
||||
SlackBridgeConfigComponent,
|
||||
AdminSlackBridgeManageSelfhostedComponent,
|
||||
AdminSlackBridgeComponent,
|
||||
|
||||
@ -221,6 +224,7 @@ import { AdminSlackApiService } from "./shared/services/admin/admin-slack-api.se
|
||||
AdminGitterApiService,
|
||||
GitterApiService,
|
||||
AdminCustomSimpleBotsApiService,
|
||||
SlackApiService,
|
||||
AdminSlackApiService,
|
||||
{provide: Window, useValue: window},
|
||||
|
||||
|
@ -41,6 +41,7 @@ import { SpotifyWidgetConfigComponent } from "./configs/widget/spotify/spotify.w
|
||||
import { SpotifyWidgetWrapperComponent } from "./widget-wrappers/spotify/spotify.component";
|
||||
import { AdminCustomBotsComponent } from "./admin/custom-bots/custom-bots.component";
|
||||
import { AdminSlackBridgeComponent } from "./admin/bridges/slack/slack.component";
|
||||
import { SlackBridgeConfigComponent } from "./configs/bridge/slack/slack.bridge.component";
|
||||
|
||||
const routes: Routes = [
|
||||
{path: "", component: HomeComponent},
|
||||
@ -238,6 +239,11 @@ const routes: Routes = [
|
||||
component: GitterBridgeConfigComponent,
|
||||
data: {breadcrumb: "Gitter Bridge Configuration", name: "Gitter Bridge Configuration"},
|
||||
},
|
||||
{
|
||||
path: "slack",
|
||||
component: SlackBridgeConfigComponent,
|
||||
data: {breadcrumb: "Slack Bridge Configuration", name: "Slack Bridge Configuration"},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
59
web/app/configs/bridge/slack/slack.bridge.component.html
Normal file
59
web/app/configs/bridge/slack/slack.bridge.component.html
Normal file
@ -0,0 +1,59 @@
|
||||
<my-bridge-config [bridgeComponent]="this">
|
||||
<ng-template #bridgeParamsTemplate>
|
||||
<my-ibox [isCollapsible]="false">
|
||||
<h5 class="my-ibox-title">
|
||||
Bridge to Slack
|
||||
</h5>
|
||||
<div class="my-ibox-content" *ngIf="loadingTeams">
|
||||
<my-spinner></my-spinner>
|
||||
</div>
|
||||
<div class="my-ibox-content" *ngIf="!loadingTeams">
|
||||
<div *ngIf="isBridged && bridge.config.link.isWebhook">
|
||||
This room is bridged to Slack using webhooks. Webhook bridging is legacy and doesn't support as
|
||||
rich bridging as the new approach. It is recommended to re-create the bridge with the new process.
|
||||
<br />
|
||||
<button type="button" class="btn btn-sm btn-danger" [disabled]="isBusy" (click)="unbridgeRoom()">
|
||||
Unbridge
|
||||
</button>
|
||||
</div>
|
||||
<div *ngIf="isBridged && !bridge.config.link.isWebhook">
|
||||
This room is bridged to "{{ bridge.config.link.channelName }}" on Slack.
|
||||
<button type="button" class="btn btn-sm btn-danger" [disabled]="isBusy" (click)="unbridgeRoom()">
|
||||
Unbridge
|
||||
</button>
|
||||
</div>
|
||||
<div *ngIf="!isBridged && needsAuth">
|
||||
<p>
|
||||
In order to bridge Slack channels, you'll need to authorize the bridge to access your teams
|
||||
and channels. Please click the button below to do so.
|
||||
</p>
|
||||
<a [href]="authUrl" rel="noopener" target="_blank">
|
||||
<img src="/img/slack_auth_button.png" class="slack-auth-button" alt="sign in with slack" />
|
||||
</a>
|
||||
</div>
|
||||
<div *ngIf="!isBridged && !needsAuth">
|
||||
<label class="label-block">
|
||||
Team
|
||||
<select class="form-control form-control-sm" [(ngModel)]="teamId"
|
||||
(change)="loadChannels()" [disabled]="isBusy">
|
||||
<option *ngFor="let team of teams" [ngValue]="team.id">
|
||||
{{ team.name }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="label-block">
|
||||
Channel
|
||||
<select class="form-control form-control-sm" [(ngModel)]="channelId" [disabled]="isBusy">
|
||||
<option *ngFor="let channel of channels" [ngValue]="channel.id">
|
||||
{{ channel.name }}
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<button type="button" class="btn btn-sm btn-primary" [disabled]="isBusy" (click)="bridgeRoom()">
|
||||
Bridge
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</my-ibox>
|
||||
</ng-template>
|
||||
</my-bridge-config>
|
9
web/app/configs/bridge/slack/slack.bridge.component.scss
Normal file
9
web/app/configs/bridge/slack/slack.bridge.component.scss
Normal file
@ -0,0 +1,9 @@
|
||||
.actions-col {
|
||||
width: 120px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.slack-auth-button {
|
||||
width: 170px;
|
||||
height: 40px;
|
||||
}
|
129
web/app/configs/bridge/slack/slack.bridge.component.ts
Normal file
129
web/app/configs/bridge/slack/slack.bridge.component.ts
Normal file
@ -0,0 +1,129 @@
|
||||
import { Component, OnInit } from "@angular/core";
|
||||
import { BridgeComponent } from "../bridge.component";
|
||||
import { FE_SlackChannel, FE_SlackLink, FE_SlackTeam } from "../../../shared/models/slack";
|
||||
import { SlackApiService } from "../../../shared/services/integrations/slack-api.service";
|
||||
import { ScalarClientApiService } from "../../../shared/services/scalar/scalar-client-api.service";
|
||||
import { DomSanitizer, SafeUrl } from "@angular/platform-browser";
|
||||
|
||||
interface SlackConfig {
|
||||
botUserId: string;
|
||||
link: FE_SlackLink;
|
||||
}
|
||||
|
||||
@Component({
|
||||
templateUrl: "slack.bridge.component.html",
|
||||
styleUrls: ["slack.bridge.component.scss"],
|
||||
})
|
||||
export class SlackBridgeConfigComponent extends BridgeComponent<SlackConfig> implements OnInit {
|
||||
|
||||
public teamId: string;
|
||||
public channelId: string;
|
||||
public teams: FE_SlackTeam[];
|
||||
public channels: FE_SlackChannel[];
|
||||
public isBusy: boolean;
|
||||
public loadingTeams = true;
|
||||
public needsAuth = false;
|
||||
public authUrl: SafeUrl;
|
||||
|
||||
private timerId: any;
|
||||
|
||||
constructor(private slack: SlackApiService, private scalar: ScalarClientApiService, private sanitizer: DomSanitizer) {
|
||||
super("slack");
|
||||
}
|
||||
|
||||
public ngOnInit() {
|
||||
super.ngOnInit();
|
||||
|
||||
this.tryLoadTeams();
|
||||
}
|
||||
|
||||
private tryLoadTeams() {
|
||||
this.slack.getTeams().then(teams => {
|
||||
this.teams = teams;
|
||||
this.teamId = this.teams[0].id;
|
||||
this.needsAuth = false;
|
||||
this.loadingTeams = false;
|
||||
this.loadChannels();
|
||||
|
||||
if (this.timerId) {
|
||||
clearInterval(this.timerId);
|
||||
}
|
||||
}).catch(error => {
|
||||
if (error.status === 404) {
|
||||
this.needsAuth = true;
|
||||
|
||||
if (!this.authUrl) {
|
||||
this.slack.getAuthUrl().then(url => {
|
||||
this.authUrl = this.sanitizer.bypassSecurityTrustResourceUrl(url);
|
||||
this.loadingTeams = false;
|
||||
}).catch(error2 => {
|
||||
console.error(error2);
|
||||
this.toaster.pop("error", "Error getting Slack authorization information");
|
||||
});
|
||||
|
||||
this.timerId = setInterval(() => {
|
||||
this.tryLoadTeams();
|
||||
}, 1000);
|
||||
}
|
||||
} else {
|
||||
console.error(error);
|
||||
this.toaster.pop("error", "Error getting teams");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public get isBridged(): boolean {
|
||||
return !!this.bridge.config.link;
|
||||
}
|
||||
|
||||
public loadChannels() {
|
||||
this.isBusy = true;
|
||||
this.slack.getChannels(this.teamId).then(channels => {
|
||||
this.channels = channels;
|
||||
this.channelId = this.channels[0].id;
|
||||
this.isBusy = false;
|
||||
}).catch(error => {
|
||||
console.error(error);
|
||||
this.toaster.pop("error", "Error getting channels for team");
|
||||
this.isBusy = false;
|
||||
});
|
||||
}
|
||||
|
||||
public async bridgeRoom(): Promise<any> {
|
||||
this.isBusy = true;
|
||||
|
||||
try {
|
||||
await this.scalar.inviteUser(this.roomId, this.bridge.config.botUserId);
|
||||
} catch (e) {
|
||||
if (!e.response || !e.response.error || !e.response.error._error ||
|
||||
e.response.error._error.message.indexOf("already in the room") === -1) {
|
||||
this.isBusy = false;
|
||||
this.toaster.pop("error", "Error inviting bridge");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
this.slack.bridgeRoom(this.roomId, this.teamId, this.channelId).then(link => {
|
||||
this.bridge.config.link = link;
|
||||
this.isBusy = false;
|
||||
this.toaster.pop("success", "Bridge requested");
|
||||
}).catch(error => {
|
||||
this.isBusy = false;
|
||||
console.error(error);
|
||||
this.toaster.pop("error", "Error requesting bridge");
|
||||
});
|
||||
}
|
||||
|
||||
public unbridgeRoom(): void {
|
||||
this.isBusy = true;
|
||||
this.slack.unbridgeRoom(this.roomId).then(() => {
|
||||
this.bridge.config.link = null;
|
||||
this.isBusy = false;
|
||||
this.toaster.pop("success", "Bridge removed");
|
||||
}).catch(error => {
|
||||
this.isBusy = false;
|
||||
console.error(error);
|
||||
this.toaster.pop("error", "Error removing bridge");
|
||||
});
|
||||
}
|
||||
}
|
@ -12,3 +12,13 @@ export interface FE_SlackLink {
|
||||
channelId: string;
|
||||
teamId: string;
|
||||
}
|
||||
|
||||
export interface FE_SlackTeam {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface FE_SlackChannel {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
@ -27,6 +27,7 @@ export class IntegrationsRegistry {
|
||||
"telegram": {},
|
||||
"webhooks": {},
|
||||
"gitter": {},
|
||||
"slack": {},
|
||||
},
|
||||
"widget": {
|
||||
"custom": {
|
||||
|
38
web/app/shared/services/integrations/slack-api.service.ts
Normal file
38
web/app/shared/services/integrations/slack-api.service.ts
Normal file
@ -0,0 +1,38 @@
|
||||
import { Injectable } from "@angular/core";
|
||||
import { Http } from "@angular/http";
|
||||
import { AuthedApi } from "../authed-api";
|
||||
import { FE_SlackChannel, FE_SlackLink, FE_SlackTeam } from "../../models/slack";
|
||||
|
||||
@Injectable()
|
||||
export class SlackApiService extends AuthedApi {
|
||||
constructor(http: Http) {
|
||||
super(http);
|
||||
}
|
||||
|
||||
public bridgeRoom(roomId: string, teamId: string, channelId: string): Promise<FE_SlackLink> {
|
||||
return this.authedPost("/api/v1/dimension/slack/room/" + roomId + "/link", {teamId, channelId})
|
||||
.map(r => r.json()).toPromise();
|
||||
}
|
||||
|
||||
public unbridgeRoom(roomId: string): Promise<any> {
|
||||
return this.authedDelete("/api/v1/dimension/slack/room/" + roomId + "/link")
|
||||
.map(r => r.json()).toPromise();
|
||||
}
|
||||
|
||||
public getLink(roomId: string): Promise<FE_SlackLink> {
|
||||
return this.authedGet("/api/v1/dimension/slack/room/" + roomId + "/link")
|
||||
.map(r => r.json()).toPromise();
|
||||
}
|
||||
|
||||
public getTeams(): Promise<FE_SlackTeam[]> {
|
||||
return this.authedGet("/api/v1/dimension/slack/teams").map(r => r.json()).toPromise();
|
||||
}
|
||||
|
||||
public getChannels(teamId: string): Promise<FE_SlackChannel[]> {
|
||||
return this.authedGet("/api/v1/dimension/slack/teams/" + teamId + "/channels").map(r => r.json()).toPromise();
|
||||
}
|
||||
|
||||
public getAuthUrl(): Promise<string> {
|
||||
return this.authedGet("/api/v1/dimension/slack/auth").map(r => r.json()).toPromise().then(r => r["authUrl"]);
|
||||
}
|
||||
}
|
BIN
web/public/img/avatars/slack.png
Normal file
BIN
web/public/img/avatars/slack.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 14 KiB |
BIN
web/public/img/slack_auth_button.png
Normal file
BIN
web/public/img/slack_auth_button.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 6.1 KiB |
Loading…
Reference in New Issue
Block a user