Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

2.5 KB
Raw Blame
import { withIntegrationLink } from "../../github/services/with-integration-link";
import { activityTable } from "../../../database/schema";
import { findExternalLink } from "../../github/services/link-manager";
import {
  findAllIntegrationsByGiteaRepo,
  repoOwnerLogin,
} from "../services/integration-lookup";
import { isKaneoComment } from "../utils/comment-origin";
import { baseUrlFromRepositoryHtmlUrl } from "../utils/webhook-repo";

type IssueCommentCreatedPayload = {
  action: string;
  issue: {
    number: number;
  };
  comment: {
    id: number;
    body: string;
    html_url: string;
    user: {
      login?: string;
      username?: string;
      avatar_url: string;
    } | null;
    created_at: string;
  };
  repository: {
    owner: { login?: string; username?: string };
    name: string;
    html_url: string;
  };
};

export async function handleGiteaIssueCommentCreated(
  payload: IssueCommentCreatedPayload,
  integrationId?: string,
) {
  const { issue, comment, repository } = payload;

  if (payload.action !== "created" || isKaneoComment(comment.body)) {
    return;
  }

  const username = comment.user?.login ?? comment.user?.username ?? "";
  if (username.endsWith("[bot]")) {
    return;
  }

  const baseUrl = baseUrlFromRepositoryHtmlUrl(repository.html_url);
  if (!baseUrl) return;

  const owner = repoOwnerLogin(repository);
  const integrations = await findAllIntegrationsByGiteaRepo(
    baseUrl,
    owner,
    repository.name,
    integrationId,
  );

  for (const integration of integrations) {
    const existingLink = await findExternalLink(
      integration.id,
      "issue",
      issue.number.toString(),
    );

    if (!existingLink) {
      continue;
    }

    await withIntegrationLink(
      existingLink,
      integration,
      async (db, _afterCommit, existingLink) => {
        await db
          .insert(activityTable)
          .values({
            taskId: existingLink.taskId,
            type: "comment",
            content: comment.body,
            externalUserName: username || "Unknown",
            externalUserAvatar: comment.user?.avatar_url ?? null,
            externalSource: "gitea",
            externalUrl: comment.html_url,
            eventData: {
              externalCommentId: comment.id,
            },
          })
          .onConflictDoNothing({
            target: [
              activityTable.taskId,
              activityTable.externalSource,
              activityTable.externalUrl,
            ],
          });
      },
    );
  }
}