From 41c8d664b21c7006d9527166cd873b5da4c94294 Mon Sep 17 00:00:00 2001 From: hmacr Date: Fri, 4 Apr 2025 21:34:43 +0530 Subject: [PATCH] issues api and plugin --- plugins/github/server/github.ts | 34 ++++++++++-- plugins/github/server/index.ts | 13 +++++ plugins/github/server/issue.ts | 85 ++++++++++++++++++++++++++++++ server/routes/api/index.ts | 2 + server/routes/api/issues/index.ts | 1 + server/routes/api/issues/issues.ts | 63 ++++++++++++++++++++++ server/routes/api/issues/schema.ts | 12 +++++ server/types.ts | 12 +++++ server/utils/PluginManager.ts | 13 ++++- shared/schema.ts | 13 +++++ shared/types.ts | 9 ++++ 11 files changed, 253 insertions(+), 4 deletions(-) create mode 100644 plugins/github/server/issue.ts create mode 100644 server/routes/api/issues/index.ts create mode 100644 server/routes/api/issues/issues.ts create mode 100644 server/routes/api/issues/schema.ts diff --git a/plugins/github/server/github.ts b/plugins/github/server/github.ts index 0604488c7e..1767adbc1b 100644 --- a/plugins/github/server/github.ts +++ b/plugins/github/server/github.ts @@ -40,6 +40,32 @@ const requestPlugin = (octokit: Octokit) => ({ }, }), + requestRepos: async () => + octokit.request("GET /installation/repositories", { + headers: { + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + }, + }), + + createIssue: async ({ + owner, + repo, + title, + }: { + owner: string; + repo: string; + title: string; + }) => + octokit.request(`POST /repos/{owner}/{repo}/issues`, { + owner, + repo, + title, + headers: { + Accept: "application/vnd.github.text+json", + "X-GitHub-Api-Version": "2022-11-28", + }, + }), /** * Fetches app installations accessible to the user * @@ -82,9 +108,11 @@ const CustomOctokit = Octokit.plugin(requestPlugin); export class GitHub { private static appId = env.GITHUB_APP_ID; - private static appKey = env.GITHUB_APP_PRIVATE_KEY - ? Buffer.from(env.GITHUB_APP_PRIVATE_KEY, "base64").toString("ascii") - : undefined; + // private static appKey = env.GITHUB_APP_PRIVATE_KEY + // ? Buffer.from(env.GITHUB_APP_PRIVATE_KEY, "base64").toString("ascii") + // : undefined; + + private static appKey = env.GITHUB_APP_PRIVATE_KEY; private static clientId = env.GITHUB_CLIENT_ID; private static clientSecret = env.GITHUB_CLIENT_SECRET; diff --git a/plugins/github/server/index.ts b/plugins/github/server/index.ts index f42927aaa7..1c491784ad 100644 --- a/plugins/github/server/index.ts +++ b/plugins/github/server/index.ts @@ -1,9 +1,11 @@ +import { IntegrationService } from "@shared/types"; import { Minute } from "@shared/utils/time"; import { PluginManager, Hook } from "@server/utils/PluginManager"; import config from "../plugin.json"; import router from "./api/github"; import env from "./env"; import { GitHub } from "./github"; +import { GitHubIssueProvider } from "./issue"; import { uninstall } from "./uninstall"; const enabled = @@ -24,6 +26,17 @@ if (enabled) { type: Hook.UnfurlProvider, value: { unfurl: GitHub.unfurl, cacheExpiry: Minute.seconds }, }, + { + type: Hook.IssueProvider, + value: { + provider: { + listSources: GitHubIssueProvider.listRepos, + createIssue: GitHubIssueProvider.createIssue, + }, + service: IntegrationService.GitHub, + cacheExpiry: Minute.seconds, + }, + }, { type: Hook.Uninstall, value: uninstall, diff --git a/plugins/github/server/issue.ts b/plugins/github/server/issue.ts new file mode 100644 index 0000000000..3d11870e04 --- /dev/null +++ b/plugins/github/server/issue.ts @@ -0,0 +1,85 @@ +import { IssueSource } from "@shared/schema"; +import { + IntegrationService, + IntegrationType, + UnfurlResourceType, +} from "@shared/types"; +import Logger from "@server/logging/Logger"; +import { Integration, User } from "@server/models"; +import { CreateIssueResponse, IssueProvider } from "@server/types"; +import { GitHub } from "./github"; + +export class GitHubIssueProvider { + public static listRepos: IssueProvider["listSources"] = async ( + actor: User + ): Promise => { + const integrations = (await Integration.findAll({ + where: { + service: IntegrationService.GitHub, + teamId: actor.teamId, + }, + })) as Integration[]; + + const integrationRepos = await Promise.all( + integrations.map(async (integration) => this.getRepos(integration)) + ); + + return integrationRepos.flat(); + }; + + public static createIssue: IssueProvider["createIssue"] = async ( + title: string, + source: IssueSource, + actor: User + ): Promise => { + const integration = (await Integration.findOne({ + where: { + service: IntegrationService.GitHub, + teamId: actor.teamId, + "settings.github.installation.account.name": source.account.name, + }, + })) as Integration | undefined; + + if (!integration) { + return; + } + + try { + const client = await GitHub.authenticateAsInstallation( + integration.settings.github!.installation.id + ); + + const { data } = await client.createIssue({ + owner: source.account.name, + repo: source.name, + title, + }); + + return { + ...data, + type: UnfurlResourceType.Issue, + cacheKey: data.html_url, + }; + } catch (err) { + Logger.warn("Failed to create issue in GitHub", err); + return; + } + }; + + private static getRepos = async ( + integration: Integration + ): Promise => { + const client = await GitHub.authenticateAsInstallation( + integration.settings.github!.installation.id + ); + + const repos = await client.requestRepos(); + + return repos.data.repositories.map((repo) => ({ + id: String(repo.id), + name: repo.name, + account: { id: String(repo.owner.id), name: repo.owner.login }, + service: IntegrationService.GitHub, + })); + }; +} diff --git a/server/routes/api/index.ts b/server/routes/api/index.ts index de12822684..38e02ecb01 100644 --- a/server/routes/api/index.ts +++ b/server/routes/api/index.ts @@ -23,6 +23,7 @@ import groups from "./groups"; import imports from "./imports"; import installation from "./installation"; import integrations from "./integrations"; +import issues from "./issues"; import apiErrorHandler from "./middlewares/apiErrorHandler"; import apiResponse from "./middlewares/apiResponse"; import apiTracer from "./middlewares/apiTracer"; @@ -99,6 +100,7 @@ router.use("/", urls.routes()); router.use("/", userMemberships.routes()); router.use("/", reactions.routes()); router.use("/", imports.routes()); +router.use("/", issues.routes()); if (!env.isCloudHosted) { router.use("/", installation.routes()); diff --git a/server/routes/api/issues/index.ts b/server/routes/api/issues/index.ts new file mode 100644 index 0000000000..3234dd61f4 --- /dev/null +++ b/server/routes/api/issues/index.ts @@ -0,0 +1 @@ +export { default } from "./issues"; diff --git a/server/routes/api/issues/issues.ts b/server/routes/api/issues/issues.ts new file mode 100644 index 0000000000..ea8630025e --- /dev/null +++ b/server/routes/api/issues/issues.ts @@ -0,0 +1,63 @@ +import { InternalError, InvalidRequestError } from "@server/errors"; +import auth from "@server/middlewares/authentication"; +import validate from "@server/middlewares/validate"; +import presentUnfurl from "@server/presenters/unfurl"; +import { APIContext } from "@server/types"; +import { CacheHelper } from "@server/utils/CacheHelper"; +import { Hook, PluginManager } from "@server/utils/PluginManager"; +import { UserRole } from "@shared/types"; +import Router from "koa-router"; +import * as T from "./schema"; + +const router = new Router(); +const plugins = PluginManager.getHooks(Hook.IssueProvider); + +router.post( + "issues.list_sources", + auth({ role: UserRole.Member }), + async (ctx: APIContext) => { + const { user } = ctx.state.auth; + + const sources = await Promise.all( + plugins.map((plugin) => plugin.value.provider.listSources(user)) + ); + + ctx.body = { + data: sources.flat(), + }; + } +); + +router.post( + "issues.create", + auth({ role: UserRole.Member }), + validate(T.IssuesCreateSchema), + async (ctx: APIContext) => { + const { title, source } = ctx.input.body; + const { user } = ctx.state.auth; + + const plugin = plugins.find((p) => p.value.service === source.service); + + if (!plugin) { + throw InvalidRequestError(); + } + + const issue = await plugin.value.provider.createIssue(title, source, user); + + if (!issue) { + throw InternalError(); + } + + await CacheHelper.setData( + CacheHelper.getUnfurlKey(user.teamId, issue.cacheKey), + issue, + plugin.value.cacheExpiry + ); + + ctx.body = { + data: await presentUnfurl(issue), + }; + } +); + +export default router; diff --git a/server/routes/api/issues/schema.ts b/server/routes/api/issues/schema.ts new file mode 100644 index 0000000000..4fb4a5fb0c --- /dev/null +++ b/server/routes/api/issues/schema.ts @@ -0,0 +1,12 @@ +import { IssueSource } from "@shared/schema"; +import { z } from "zod"; +import { BaseSchema } from "../schema"; + +export const IssuesCreateSchema = BaseSchema.extend({ + body: z.object({ + title: z.string().nonempty(), + source: IssueSource, + }), +}); + +export type IssuesCreateReq = z.infer; diff --git a/server/types.ts b/server/types.ts index a0d1c44493..044ad20176 100644 --- a/server/types.ts +++ b/server/types.ts @@ -2,6 +2,7 @@ import { ParameterizedContext, DefaultContext } from "koa"; import { IRouterParamContext } from "koa-router"; import { InferAttributes, Model, Transaction } from "sequelize"; import { z } from "zod"; +import { IssueSource } from "@shared/schema"; import { CollectionSort, NavigationNode, @@ -585,6 +586,17 @@ export type UnfurlSignature = ( export type UninstallSignature = (integration: Integration) => Promise; +export type CreateIssueResponse = Unfurl & { cacheKey: string }; + +export type IssueProvider = { + listSources: (actor: User) => Promise; + createIssue: ( + title: string, + source: IssueSource, + actor: User + ) => Promise; +}; + export type Replace = { [P in keyof T as P extends K ? N : P]: T[P extends K ? K : P]; }; diff --git a/server/utils/PluginManager.ts b/server/utils/PluginManager.ts index 2db8d7010a..be9b81095b 100644 --- a/server/utils/PluginManager.ts +++ b/server/utils/PluginManager.ts @@ -3,12 +3,17 @@ import { glob } from "glob"; import type Router from "koa-router"; import isArray from "lodash/isArray"; import sortBy from "lodash/sortBy"; +import { IssueProviderIntegrationService } from "@shared/types"; import type BaseEmail from "@server/emails/templates/BaseEmail"; import env from "@server/env"; import Logger from "@server/logging/Logger"; import type BaseProcessor from "@server/queues/processors/BaseProcessor"; import type BaseTask from "@server/queues/tasks/BaseTask"; -import { UnfurlSignature, UninstallSignature } from "@server/types"; +import { + IssueProvider as TIssueProvider, + UnfurlSignature, + UninstallSignature, +} from "@server/types"; export enum PluginPriority { VeryHigh = 0, @@ -25,6 +30,7 @@ export enum Hook { API = "api", AuthProvider = "authProvider", EmailTemplate = "emailTemplate", + IssueProvider = "issueProvider", Processor = "processor", Task = "task", UnfurlProvider = "unfurl", @@ -39,6 +45,11 @@ type PluginValueMap = { [Hook.API]: Router; [Hook.AuthProvider]: { router: Router; id: string }; [Hook.EmailTemplate]: typeof BaseEmail; + [Hook.IssueProvider]: { + provider: TIssueProvider; + service: IssueProviderIntegrationService; + cacheExpiry: number; + }; [Hook.Processor]: typeof BaseProcessor; [Hook.Task]: typeof BaseTask; [Hook.Uninstall]: UninstallSignature; diff --git a/shared/schema.ts b/shared/schema.ts index 6a48435050..6d33291f58 100644 --- a/shared/schema.ts +++ b/shared/schema.ts @@ -3,6 +3,7 @@ import { CollectionPermission, type ImportableIntegrationService, IntegrationService, + IssueProviderIntegrationService, ProsemirrorDoc, } from "./types"; import { PageType } from "plugins/notion/shared/types"; @@ -57,3 +58,15 @@ export type ImportTaskOutput = { createdAt?: Date; updatedAt?: Date; }[]; + +export const IssueSource = z.object({ + id: z.string().nonempty(), + name: z.string().nonempty(), + account: z.object({ + id: z.string().nonempty(), + name: z.string().nonempty(), + }), + service: z.nativeEnum(IssueProviderIntegrationService), +}); + +export type IssueSource = z.infer; diff --git a/shared/types.ts b/shared/types.ts index 135d22fd91..1e19fad0e9 100644 --- a/shared/types.ts +++ b/shared/types.ts @@ -146,6 +146,15 @@ export const UserCreatableIntegrationService = { Umami: IntegrationService.Umami, } as const; +export type IssueProviderIntegrationService = Extract< + IntegrationService, + IntegrationService.GitHub +>; + +export const IssueProviderIntegrationService = { + Notion: IntegrationService.GitHub, +} as const; + export enum CollectionPermission { Read = "read", ReadWrite = "read_write",