This commit is contained in:
Will Hunt 2021-05-02 17:40:48 +01:00
parent 782bd5e1f3
commit 68d082df19
5 changed files with 52 additions and 66 deletions

View File

@ -10,7 +10,7 @@ import { MatrixEvent, MatrixMessageContent } from "../MatrixEvent";
export interface GitHubDiscussionConnectionState { export interface GitHubDiscussionConnectionState {
owner: string; owner: string;
name: string; repo: string;
id: number; id: number;
discussion: number; discussion: number;
} }
@ -31,7 +31,7 @@ export class GitHubDiscussionConnection implements IConnection {
static readonly QueryRoomRegex = /#github_disc_(.+)_(.+)_(\d+):.*/; static readonly QueryRoomRegex = /#github_disc_(.+)_(.+)_(\d+):.*/;
public static async createDiscussionRoom( public static async createDiscussionRoom(
as: Appservice, userId: string, owner: string, name: string, discussion: Discussion, as: Appservice, userId: string, owner: string, repo: string, discussion: Discussion,
tokenStore: UserTokenStore, commentProcessor: CommentProcessor, messageClient: MessageSenderClient tokenStore: UserTokenStore, commentProcessor: CommentProcessor, messageClient: MessageSenderClient
) { ) {
const commentIntent = await getIntentForUser({ const commentIntent = await getIntentForUser({
@ -40,7 +40,7 @@ export class GitHubDiscussionConnection implements IConnection {
}, as); }, as);
const state: GitHubDiscussionConnectionState = { const state: GitHubDiscussionConnectionState = {
owner, owner,
name, repo,
id: discussion.id, id: discussion.id,
discussion: discussion.number, discussion: discussion.number,
}; };
@ -48,7 +48,7 @@ export class GitHubDiscussionConnection implements IConnection {
invite: [userId, as.botUserId], invite: [userId, as.botUserId],
preset: 'private_chat', preset: 'private_chat',
name: `${discussion.title} (${owner}/${name})`, name: `${discussion.title} (${owner}/${name})`,
room_alias_name: `github_disc_${owner.toLowerCase()}_${name.toLowerCase()}_${discussion.number}`, room_alias_name: `github_disc_${owner.toLowerCase()}_${repo.toLowerCase()}_${discussion.number}`,
initial_state: [{ initial_state: [{
content: state, content: state,
state_key: '', state_key: '',
@ -92,8 +92,8 @@ export class GitHubDiscussionConnection implements IConnection {
return this.state.discussion; return this.state.discussion;
} }
public get name() { public get repo() {
return this.state.name; return this.state.repo;
} }
public get owner() { public get owner() {
@ -101,6 +101,10 @@ export class GitHubDiscussionConnection implements IConnection {
} }
public toString() { public toString() {
return `GitHubDiscussion ${this.owner}/${this.name}#${this.state.discussion}`; return `GitHubDiscussion ${this.owner}/${this.repo}#${this.state.discussion}`;
}
public onDiscussionCommentCreated() {
this.messageClient.sendMatrixMessage()
} }
} }

View File

@ -106,6 +106,7 @@ export class GithubBridge {
this.messageClient, this.messageClient,
instance); instance);
} }
return; return;
} }
@ -124,12 +125,27 @@ export class GithubBridge {
(c instanceof GitHubRepoConnection && c.org === org && c.repo === repo)) as (GitHubIssueConnection|GitLabRepoConnection)[]; (c instanceof GitHubRepoConnection && c.org === org && c.repo === repo)) as (GitHubIssueConnection|GitLabRepoConnection)[];
} }
private getConnectionsForGithubRepo(org: string, repo: string): GitHubRepoConnection[] { private getConnectionsForGithubRepo(org: string, repo: string): GitHubRepoConnection[] {
org = org.toLowerCase(); org = org.toLowerCase();
repo = repo.toLowerCase(); repo = repo.toLowerCase();
return this.connections.filter((c) => (c instanceof GitHubRepoConnection && c.org === org && c.repo === repo)) as GitHubRepoConnection[]; return this.connections.filter((c) => (c instanceof GitHubRepoConnection && c.org === org && c.repo === repo)) as GitHubRepoConnection[];
} }
private getConnectionsForGithubDiscussion(owner: string, repo: string, discussionNumber: number) {
owner = owner.toLowerCase();
repo = repo.toLowerCase();
return this.connections.filter(
(c) => (
c instanceof GitHubDiscussionConnection &&
c.owner === owner &&
c.repo === repo &&
c.discussionNumber === discussionNumber
)
) as GitHubDiscussionConnection[];
}
private getConnectionsForGitLabIssueWebhook(repoHome: string, issueId: number) { private getConnectionsForGitLabIssueWebhook(repoHome: string, issueId: number) {
if (!this.config.gitlab) { if (!this.config.gitlab) {
throw Error('GitLab configuration missing, cannot handle note'); throw Error('GitLab configuration missing, cannot handle note');
@ -384,11 +400,11 @@ export class GithubBridge {
}) })
}); });
this.queue.on<IGitLabWebhookIssueStateEvent>("github.discussion_comment.created", async ({data}) => { this.queue.on<GitHubWebhookTypes.DiscussionCommentCreatedEvent>("github.discussion_comment.created", async ({data}) => {
const connections = this.getConnectionsForGitLabIssueWebhook(data.repository.homepage, data.object_attributes.iid); const connections = this.getConnectionsForGithubDiscussion(data.repository.owner.login, data.repository.name, data.discussion.number);
connections.map(async (c) => { connections.map(async (c) => {
try { try {
await c.onIssueClosed(); await c.onDiscussionCommentCreated(data);
} catch (ex) { } catch (ex) {
log.warn(`Connection ${c.toString()} failed to handle comment.created:`, ex); log.warn(`Connection ${c.toString()} failed to handle comment.created:`, ex);
} }

View File

@ -253,7 +253,7 @@ export class NotificationProcessor {
} }
private async handleUserNotification(roomId: string, notif: GitHubUserNotification, filter: NotifFilter) { private async handleUserNotification(roomId: string, notif: GitHubUserNotification, filter: NotifFilter) {
log.info("New notification event:", notif); log.debug("New notification event:", notif);
if (!filter.shouldSendNotification( if (!filter.shouldSendNotification(
notif.subject.latest_comment_url_data?.user?.login, notif.subject.latest_comment_url_data?.user?.login,
notif.repository.full_name, notif.repository.full_name,

View File

@ -7,7 +7,7 @@ import qs from "querystring";
import { Server } from "http"; import { Server } from "http";
import axios from "axios"; import axios from "axios";
import { IGitLabWebhookEvent } from "./Gitlab/WebhookTypes"; import { IGitLabWebhookEvent } from "./Gitlab/WebhookTypes";
import { Webhooks as OctokitWebhooks } from "@octokit/webhooks" import { EmitterWebhookEvent, Webhooks as OctokitWebhooks } from "@octokit/webhooks"
const log = new LogWrapper("GithubWebhooks"); const log = new LogWrapper("GithubWebhooks");
export interface OAuthRequest { export interface OAuthRequest {
@ -51,16 +51,7 @@ export class Webhooks extends EventEmitter {
this.ghWebhooks = new OctokitWebhooks({ this.ghWebhooks = new OctokitWebhooks({
secret: config.github?.webhook.secret as string, secret: config.github?.webhook.secret as string,
}); });
this.ghWebhooks.onAny(({id, name, payload}) => { this.ghWebhooks.onAny(e => this.onGitHubPayload(e));
log.info(`Got GitHub webhook event ${id} ${name}`);
this.queue.push({
eventName: `github.name`,
sender: "GithubWebhooks",
data: payload,
}).catch((err) => {
log.error(`Failed to emit payload: ${err}`);
});
});
} }
this.expressApp.use(express.json({ this.expressApp.use(express.json({
@ -101,6 +92,21 @@ export class Webhooks extends EventEmitter {
} }
} }
private async onGitHubPayload({id, name, payload}: EmitterWebhookEvent) {
log.info(`Got GitHub webhook event ${id} ${name}`);
console.log(payload);
const action = (payload as unknown as {action: string|undefined}).action;
try {
await this.queue.push({
eventName: `github.${name}${action ? `.${action}` : ""}`,
sender: "Webhooks",
data: payload,
});
} catch (err) {
log.error(`Failed to emit payload ${id}: ${err}`);
}
}
private onPayload(req: Request, res: Response) { private onPayload(req: Request, res: Response) {
log.debug(`New webhook: ${req.url}`); log.debug(`New webhook: ${req.url}`);
try { try {
@ -122,7 +128,6 @@ export class Webhooks extends EventEmitter {
}).catch((err) => { }).catch((err) => {
log.error(`Failed handle GitHubEvent: ${err}`); log.error(`Failed handle GitHubEvent: ${err}`);
}); });
res.sendStatus(200);
return; return;
} else if (req.headers['x-gitlab-token']) { } else if (req.headers['x-gitlab-token']) {
res.sendStatus(200); res.sendStatus(200);

View File

@ -392,11 +392,6 @@
"@octokit/types" "^6.12.2" "@octokit/types" "^6.12.2"
btoa-lite "^1.0.0" btoa-lite "^1.0.0"
"@octokit/openapi-types@^5.3.2":
version "5.3.2"
resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-5.3.2.tgz#b8ac43c5c3d00aef61a34cf744e315110c78deb4"
integrity sha512-NxF1yfYOUO92rCx3dwvA2onF30Vdlg7YUkMVXkeptqpzA3tRLplThhFleV/UKWFgh7rpKu1yYRbvNDUtzSopKA==
"@octokit/openapi-types@^6.0.0": "@octokit/openapi-types@^6.0.0":
version "6.0.0" version "6.0.0"
resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-6.0.0.tgz#7da8d7d5a72d3282c1a3ff9f951c8133a707480d" resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-6.0.0.tgz#7da8d7d5a72d3282c1a3ff9f951c8133a707480d"
@ -431,21 +426,7 @@
deprecation "^2.0.0" deprecation "^2.0.0"
once "^1.4.0" once "^1.4.0"
"@octokit/request@^5.3.0", "@octokit/request@^5.4.12": "@octokit/request@^5.3.0", "@octokit/request@^5.4.11", "@octokit/request@^5.4.12", "@octokit/request@^5.4.14":
version "5.4.14"
resolved "https://registry.yarnpkg.com/@octokit/request/-/request-5.4.14.tgz#ec5f96f78333bb2af390afa5ff66f114b063bc96"
integrity sha512-VkmtacOIQp9daSnBmDI92xNIeLuSRDOIuplp/CJomkvzt7M18NXgG044Cx/LFKLgjKt9T2tZR6AtJayba9GTSA==
dependencies:
"@octokit/endpoint" "^6.0.1"
"@octokit/request-error" "^2.0.0"
"@octokit/types" "^6.7.1"
deprecation "^2.0.0"
is-plain-object "^5.0.0"
node-fetch "^2.6.1"
once "^1.4.0"
universal-user-agent "^6.0.0"
"@octokit/request@^5.4.11", "@octokit/request@^5.4.14":
version "5.4.15" version "5.4.15"
resolved "https://registry.yarnpkg.com/@octokit/request/-/request-5.4.15.tgz#829da413dc7dd3aa5e2cdbb1c7d0ebe1f146a128" resolved "https://registry.yarnpkg.com/@octokit/request/-/request-5.4.15.tgz#829da413dc7dd3aa5e2cdbb1c7d0ebe1f146a128"
integrity sha512-6UnZfZzLwNhdLRreOtTkT9n57ZwulCve8q3IT/Z477vThu6snfdkBuhxnChpOKNGxcQ71ow561Qoa6uqLdPtag== integrity sha512-6UnZfZzLwNhdLRreOtTkT9n57ZwulCve8q3IT/Z477vThu6snfdkBuhxnChpOKNGxcQ71ow561Qoa6uqLdPtag==
@ -467,14 +448,7 @@
"@octokit/plugin-request-log" "^1.0.2" "@octokit/plugin-request-log" "^1.0.2"
"@octokit/plugin-rest-endpoint-methods" "5.0.0" "@octokit/plugin-rest-endpoint-methods" "5.0.0"
"@octokit/types@^6.0.3", "@octokit/types@^6.11.0", "@octokit/types@^6.7.1": "@octokit/types@^6.0.3", "@octokit/types@^6.10.0", "@octokit/types@^6.11.0", "@octokit/types@^6.12.2", "@octokit/types@^6.13.0", "@octokit/types@^6.7.1":
version "6.12.2"
resolved "https://registry.yarnpkg.com/@octokit/types/-/types-6.12.2.tgz#5b44add079a478b8eb27d78cf384cc47e4411362"
integrity sha512-kCkiN8scbCmSq+gwdJV0iLgHc0O/GTPY1/cffo9kECu1MvatLPh9E+qFhfRIktKfHEA6ZYvv6S1B4Wnv3bi3pA==
dependencies:
"@octokit/openapi-types" "^5.3.2"
"@octokit/types@^6.10.0", "@octokit/types@^6.12.2", "@octokit/types@^6.13.0":
version "6.13.0" version "6.13.0"
resolved "https://registry.yarnpkg.com/@octokit/types/-/types-6.13.0.tgz#779e5b7566c8dde68f2f6273861dd2f0409480d0" resolved "https://registry.yarnpkg.com/@octokit/types/-/types-6.13.0.tgz#779e5b7566c8dde68f2f6273861dd2f0409480d0"
integrity sha512-W2J9qlVIU11jMwKHUp5/rbVUeErqelCsO5vW5PKNb7wAXQVUz87Rc+imjlEvpvbH8yUb+KHmv8NEjVZdsdpyxA== integrity sha512-W2J9qlVIU11jMwKHUp5/rbVUeErqelCsO5vW5PKNb7wAXQVUz87Rc+imjlEvpvbH8yUb+KHmv8NEjVZdsdpyxA==
@ -2976,15 +2950,7 @@ methods@~1.1.2:
resolved "https://registry.yarnpkg.com/methods/-/methods-1.1.2.tgz#5529a4d67654134edcc5266656835b0f851afcee" resolved "https://registry.yarnpkg.com/methods/-/methods-1.1.2.tgz#5529a4d67654134edcc5266656835b0f851afcee"
integrity sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4= integrity sha1-VSmk1nZUE07cxSZmVoNbD4Ua/O4=
micromatch@^4.0.2: micromatch@^4.0.2, micromatch@^4.0.4:
version "4.0.2"
resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.2.tgz#4fcb0999bf9fbc2fcbdd212f6d629b9a56c39259"
integrity sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q==
dependencies:
braces "^3.0.1"
picomatch "^2.0.5"
micromatch@^4.0.4:
version "4.0.4" version "4.0.4"
resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.4.tgz#896d519dfe9db25fce94ceb7a500919bf881ebf9" resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.4.tgz#896d519dfe9db25fce94ceb7a500919bf881ebf9"
integrity sha512-pRmzw/XUcwXGpD9aI9q/0XOwLNygjETJ8y0ao0wdqprrzDa4YnxLcz7fQRZr8voh8V10kGhABbNcHVk5wHgWwg== integrity sha512-pRmzw/XUcwXGpD9aI9q/0XOwLNygjETJ8y0ao0wdqprrzDa4YnxLcz7fQRZr8voh8V10kGhABbNcHVk5wHgWwg==
@ -3368,12 +3334,7 @@ performance-now@^2.1.0:
resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b" resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b"
integrity sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns= integrity sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns=
picomatch@^2.0.4, picomatch@^2.0.5, picomatch@^2.2.1, picomatch@^2.2.2: picomatch@^2.0.4, picomatch@^2.2.1, picomatch@^2.2.2, picomatch@^2.2.3:
version "2.2.2"
resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.2.tgz#21f333e9b6b8eaff02468f5146ea406d345f4dad"
integrity sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==
picomatch@^2.2.3:
version "2.2.3" version "2.2.3"
resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.3.tgz#465547f359ccc206d3c48e46a1bcb89bf7ee619d" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.2.3.tgz#465547f359ccc206d3c48e46a1bcb89bf7ee619d"
integrity sha512-KpELjfwcCDUb9PeigTs2mBJzXUPzAuP2oPcA989He8Rte0+YUAjw1JVedDhuTKPkHjSYzMN3npC9luThGYEKdg== integrity sha512-KpELjfwcCDUb9PeigTs2mBJzXUPzAuP2oPcA989He8Rte0+YUAjw1JVedDhuTKPkHjSYzMN3npC9luThGYEKdg==