Add the admin section for the webhooks bridge

This commit is contained in:
Travis Ralston 2018-10-20 14:07:30 -06:00
parent 3dad15de72
commit 7b5285cd57
11 changed files with 368 additions and 0 deletions

View File

@ -0,0 +1,106 @@
import { GET, Path, PathParam, POST, QueryParam } from "typescript-rest";
import { AdminService } from "./AdminService";
import { Cache, CACHE_INTEGRATIONS, CACHE_TELEGRAM_BRIDGE } from "../../MemoryCache";
import { LogService } from "matrix-js-snippets";
import { ApiError } from "../ApiError";
import WebhookBridgeRecord from "../../db/models/WebhookBridgeRecord";
interface CreateWithUpstream {
upstreamId: number;
}
interface CreateSelfhosted {
provisionUrl: string;
sharedSecret: string;
}
interface BridgeResponse {
id: number;
upstreamId?: number;
provisionUrl?: string;
sharedSecret?: string;
isEnabled: boolean;
}
/**
* Administrative API for configuring Webhook bridge instances.
*/
@Path("/api/v1/dimension/admin/webhooks")
export class AdminWebhooksService {
@GET
@Path("all")
public async getBridges(@QueryParam("scalar_token") scalarToken: string): Promise<BridgeResponse[]> {
await AdminService.validateAndGetAdminTokenOwner(scalarToken);
const bridges = await WebhookBridgeRecord.findAll();
return Promise.all(bridges.map(async b => {
return {
id: b.id,
upstreamId: b.upstreamId,
provisionUrl: b.provisionUrl,
sharedSecret: b.sharedSecret,
isEnabled: b.isEnabled,
};
}));
}
@GET
@Path(":bridgeId")
public async getBridge(@QueryParam("scalar_token") scalarToken: string, @PathParam("bridgeId") bridgeId: number): Promise<BridgeResponse> {
await AdminService.validateAndGetAdminTokenOwner(scalarToken);
const webhookBridge = await WebhookBridgeRecord.findByPrimary(bridgeId);
if (!webhookBridge) throw new ApiError(404, "Webhook Bridge not found");
return {
id: webhookBridge.id,
upstreamId: webhookBridge.upstreamId,
provisionUrl: webhookBridge.provisionUrl,
sharedSecret: webhookBridge.sharedSecret,
isEnabled: webhookBridge.isEnabled,
};
}
@POST
@Path(":bridgeId")
public async updateBridge(@QueryParam("scalar_token") scalarToken: string, @PathParam("bridgeId") bridgeId: number, request: CreateSelfhosted): Promise<BridgeResponse> {
const userId = await AdminService.validateAndGetAdminTokenOwner(scalarToken);
const bridge = await WebhookBridgeRecord.findByPrimary(bridgeId);
if (!bridge) throw new ApiError(404, "Bridge not found");
bridge.provisionUrl = request.provisionUrl;
bridge.sharedSecret = request.sharedSecret;
await bridge.save();
LogService.info("AdminWebhooksService", userId + " updated Webhook Bridge " + bridge.id);
Cache.for(CACHE_TELEGRAM_BRIDGE).clear();
Cache.for(CACHE_INTEGRATIONS).clear();
return this.getBridge(scalarToken, bridge.id);
}
@POST
@Path("new/upstream")
public async newConfigForUpstream(@QueryParam("scalar_token") _scalarToken: string, _request: CreateWithUpstream): Promise<BridgeResponse> {
throw new ApiError(400, "Cannot create a webhook bridge from an upstream");
}
@POST
@Path("new/selfhosted")
public async newSelfhosted(@QueryParam("scalar_token") scalarToken: string, request: CreateSelfhosted): Promise<BridgeResponse> {
const userId = await AdminService.validateAndGetAdminTokenOwner(scalarToken);
const bridge = await WebhookBridgeRecord.create({
provisionUrl: request.provisionUrl,
sharedSecret: request.sharedSecret,
isEnabled: true,
});
LogService.info("AdminWebhooksService", userId + " created a new Webhook Bridge with provisioning URL " + request.provisionUrl);
Cache.for(CACHE_TELEGRAM_BRIDGE).clear();
Cache.for(CACHE_INTEGRATIONS).clear();
return this.getBridge(scalarToken, bridge.id);
}
}

View File

@ -0,0 +1,32 @@
<div class="dialog">
<div class="dialog-header">
<h4>{{ isAdding ? "Add a new" : "Edit" }} self-hosted webhook bridge</h4>
</div>
<div class="dialog-content">
<p>Self-hosted webhook bridges must have <code>provisioning</code> enabled in the configuration.</p>
<label class="label-block">
Provisioning URL
<span class="text-muted ">The public URL for the bridge.</span>
<input type="text" class="form-control"
placeholder="https://webhooks.example.org:9000/"
[(ngModel)]="provisionUrl" [disabled]="isSaving"/>
</label>
<label class="label-block">
Shared Secret
<span class="text-muted ">The provisioning secret defined in the configuration.</span>
<input type="text" class="form-control"
placeholder="some_secret_value"
[(ngModel)]="sharedSecret" [disabled]="isSaving"/>
</label>
</div>
<div class="dialog-footer">
<button type="button" (click)="add()" title="close" class="btn btn-primary btn-sm">
<i class="far fa-save"></i> Save
</button>
<button type="button" (click)="dialog.close()" title="close" class="btn btn-secondary btn-sm">
<i class="far fa-times-circle"></i> Cancel
</button>
</div>
</div>

View File

@ -0,0 +1,58 @@
import { Component } from "@angular/core";
import { ToasterService } from "angular2-toaster";
import { DialogRef, ModalComponent } from "ngx-modialog";
import { BSModalContext } from "ngx-modialog/plugins/bootstrap";
import { AdminWebhooksApiService } from "../../../../shared/services/admin/admin-webhooks-api.service";
export class ManageSelfhostedWebhooksBridgeDialogContext extends BSModalContext {
public provisionUrl: string;
public sharedSecret: string;
public allowTgPuppets = false;
public allowMxPuppets = false;
public bridgeId: number;
}
@Component({
templateUrl: "./manage-selfhosted.component.html",
styleUrls: ["./manage-selfhosted.component.scss"],
})
export class AdminWebhooksBridgeManageSelfhostedComponent implements ModalComponent<ManageSelfhostedWebhooksBridgeDialogContext> {
public isSaving = false;
public provisionUrl: string;
public sharedSecret: string;
public bridgeId: number;
public isAdding = false;
constructor(public dialog: DialogRef<ManageSelfhostedWebhooksBridgeDialogContext>,
private webhooksApi: AdminWebhooksApiService,
private toaster: ToasterService) {
this.provisionUrl = dialog.context.provisionUrl;
this.sharedSecret = dialog.context.sharedSecret;
this.bridgeId = dialog.context.bridgeId;
this.isAdding = !this.bridgeId;
}
public add() {
this.isSaving = true;
if (this.isAdding) {
this.webhooksApi.newSelfhosted(this.provisionUrl, this.sharedSecret).then(() => {
this.toaster.pop("success", "Webhook bridge added");
this.dialog.close();
}).catch(err => {
console.error(err);
this.isSaving = false;
this.toaster.pop("error", "Failed to create Webhook bridge");
});
} else {
this.webhooksApi.updateSelfhosted(this.bridgeId, this.provisionUrl, this.sharedSecret).then(() => {
this.toaster.pop("success", "Webhook bridge updated");
this.dialog.close();
}).catch(err => {
console.error(err);
this.isSaving = false;
this.toaster.pop("error", "Failed to update Webhook bridge");
});
}
}
}

View File

@ -0,0 +1,41 @@
<div *ngIf="isLoading">
<my-spinner></my-spinner>
</div>
<div *ngIf="!isLoading">
<my-ibox title="Webhooks Bridge Configuration">
<div class="my-ibox-content">
<p>
<a href="https://github.com/turt2live/matrix-appservice-webhooks" target="_blank">matrix-appservice-webhooks</a>
provides Slack-compatible webhooks for Matrix, making it easy to send updates into a room.
</p>
<table class="table table-striped table-condensed table-bordered">
<thead>
<tr>
<th>Name</th>
<th class="text-center" style="width: 120px;">Actions</th>
</tr>
</thead>
<tbody>
<tr *ngIf="!configurations || configurations.length === 0">
<td colspan="2"><i>No bridge configurations.</i></td>
</tr>
<tr *ngFor="let bridge of configurations trackById">
<td>
{{ bridge.upstreamId ? "matrix.org's bridge" : "Self-hosted bridge" }}
<span class="text-muted" style="display: inline-block;" *ngIf="!bridge.upstreamId">({{ bridge.provisionUrl }})</span>
</td>
<td class="text-center">
<span class="editButton" (click)="editBridge(bridge)">
<i class="fa fa-pencil-alt"></i>
</span>
</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-success btn-sm" (click)="addSelfHostedBridge()" [disabled]="configurations && configurations.length > 0">
<i class="fa fa-plus"></i> Add self-hosted bridge
</button>
</div>
</my-ibox>
</div>

View File

@ -0,0 +1,3 @@
.editButton {
cursor: pointer;
}

View File

@ -0,0 +1,70 @@
import { Component, OnInit } from "@angular/core";
import { ToasterService } from "angular2-toaster";
import { Modal, overlayConfigFactory } from "ngx-modialog";
import {
AdminWebhooksBridgeManageSelfhostedComponent,
ManageSelfhostedWebhooksBridgeDialogContext
} from "./manage-selfhosted/manage-selfhosted.component";
import { FE_WebhooksBridge } from "../../../shared/models/webhooks";
import { AdminWebhooksApiService } from "../../../shared/services/admin/admin-webhooks-api.service";
@Component({
templateUrl: "./webhooks.component.html",
styleUrls: ["./webhooks.component.scss"],
})
export class AdminWebhooksBridgeComponent implements OnInit {
public isLoading = true;
public isUpdating = false;
public configurations: FE_WebhooksBridge[] = [];
constructor(private webhooksApi: AdminWebhooksApiService,
private toaster: ToasterService,
private modal: Modal) {
}
public ngOnInit() {
this.reload().then(() => this.isLoading = false);
}
private async reload(): Promise<any> {
try {
this.configurations = await this.webhooksApi.getBridges();
} catch (err) {
console.error(err);
this.toaster.pop("error", "Error loading bridges");
}
}
public addSelfHostedBridge() {
this.modal.open(AdminWebhooksBridgeManageSelfhostedComponent, overlayConfigFactory({
isBlocking: true,
size: 'lg',
provisionUrl: '',
sharedSecret: '',
allowPuppets: false,
}, ManageSelfhostedWebhooksBridgeDialogContext)).result.then(() => {
this.reload().catch(err => {
console.error(err);
this.toaster.pop("error", "Failed to get an update Webhooks bridge list");
});
});
}
public editBridge(bridge: FE_WebhooksBridge) {
this.modal.open(AdminWebhooksBridgeManageSelfhostedComponent, overlayConfigFactory({
isBlocking: true,
size: 'lg',
provisionUrl: bridge.provisionUrl,
sharedSecret: bridge.sharedSecret,
bridgeId: bridge.id,
}, ManageSelfhostedWebhooksBridgeDialogContext)).result.then(() => {
this.reload().catch(err => {
console.error(err);
this.toaster.pop("error", "Failed to get an update Webhooks bridge list");
});
});
}
}

View File

@ -85,6 +85,9 @@ import { TelegramApiService } from "./shared/services/integrations/telegram-api.
import { TelegramBridgeConfigComponent } from "./configs/bridge/telegram/telegram.bridge.component";
import { TelegramAskUnbridgeComponent } from "./configs/bridge/telegram/ask-unbridge/ask-unbridge.component";
import { TelegramCannotUnbridgeComponent } from "./configs/bridge/telegram/cannot-unbridge/cannot-unbridge.component";
import { AdminWebhooksBridgeManageSelfhostedComponent } from "./admin/bridges/webhooks/manage-selfhosted/manage-selfhosted.component";
import { AdminWebhooksBridgeComponent } from "./admin/bridges/webhooks/webhooks.component";
import { AdminWebhooksApiService } from "./shared/services/admin/admin-webhooks-api.service";
@NgModule({
imports: [
@ -157,6 +160,8 @@ import { TelegramCannotUnbridgeComponent } from "./configs/bridge/telegram/canno
TelegramBridgeConfigComponent,
TelegramAskUnbridgeComponent,
TelegramCannotUnbridgeComponent,
AdminWebhooksBridgeManageSelfhostedComponent,
AdminWebhooksBridgeComponent,
// Vendor
],
@ -178,6 +183,7 @@ import { TelegramCannotUnbridgeComponent } from "./configs/bridge/telegram/canno
StickerApiService,
AdminTelegramApiService,
TelegramApiService,
AdminWebhooksApiService,
{provide: Window, useValue: window},
// Vendor
@ -198,6 +204,7 @@ import { TelegramCannotUnbridgeComponent } from "./configs/bridge/telegram/canno
AdminTelegramBridgeManageSelfhostedComponent,
TelegramAskUnbridgeComponent,
TelegramCannotUnbridgeComponent,
AdminWebhooksBridgeManageSelfhostedComponent,
]
})
export class AppModule {

View File

@ -29,6 +29,7 @@ import { StickerpickerComponent } from "./configs/stickerpicker/stickerpicker.co
import { StickerPickerWidgetWrapperComponent } from "./widget-wrappers/sticker-picker/sticker-picker.component";
import { AdminTelegramBridgeComponent } from "./admin/bridges/telegram/telegram.component";
import { TelegramBridgeConfigComponent } from "./configs/bridge/telegram/telegram.bridge.component";
import { AdminWebhooksBridgeComponent } from "./admin/bridges/webhooks/webhooks.component";
const routes: Routes = [
{path: "", component: HomeComponent},
@ -94,6 +95,11 @@ const routes: Routes = [
component: AdminTelegramBridgeComponent,
data: {breadcrumb: "Telegram Bridge", name: "Telegram Bridge"},
},
{
path: "webhooks",
component: AdminWebhooksBridgeComponent,
data: {breadcrumb: "Webhook Bridge", name: "Webhook Bridge"},
},
],
},
{

View File

@ -0,0 +1,7 @@
export interface FE_WebhooksBridge {
id: number;
upstreamId?: number;
provisionUrl?: string;
sharedSecret?: string;
isEnabled: boolean;
}

View File

@ -0,0 +1,38 @@
import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import { AuthedApi } from "../authed-api";
import { FE_Upstream } from "../../models/admin-responses";
import { FE_WebhooksBridge } from "../../models/webhooks";
@Injectable()
export class AdminWebhooksApiService extends AuthedApi {
constructor(http: Http) {
super(http);
}
public getBridges(): Promise<FE_WebhooksBridge[]> {
return this.authedGet("/api/v1/dimension/admin/webhooks/all").map(r => r.json()).toPromise();
}
public getBridge(bridgeId: number): Promise<FE_WebhooksBridge> {
return this.authedGet("/api/v1/dimension/admin/webhooks/" + bridgeId).map(r => r.json()).toPromise();
}
public newFromUpstream(upstream: FE_Upstream): Promise<FE_WebhooksBridge> {
return this.authedPost("/api/v1/dimension/admin/webhooks/new/upstream", {upstreamId: upstream.id}).map(r => r.json()).toPromise();
}
public newSelfhosted(provisionUrl: string, sharedSecret: string): Promise<FE_WebhooksBridge> {
return this.authedPost("/api/v1/dimension/admin/webhooks/new/selfhosted", {
provisionUrl: provisionUrl,
sharedSecret: sharedSecret,
}).map(r => r.json()).toPromise();
}
public updateSelfhosted(bridgeId: number, provisionUrl: string, sharedSecret: string): Promise<FE_WebhooksBridge> {
return this.authedPost("/api/v1/dimension/admin/webhooks/" + bridgeId, {
provisionUrl: provisionUrl,
sharedSecret: sharedSecret,
}).map(r => r.json()).toPromise();
}
}