Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

2.8 KB
Raw Blame
import {
  createTrigger,
  OutputSchema,
  TriggerStrategy,
  Property,
  MarkdownVariant,
} from '@activepieces/pieces-framework';
import {
  httpClient,
  HttpRequest,
  HttpMethod,
  HttpError,
} from '@activepieces/pieces-common';
import { calcomAuth } from '../auth';

export const registerWebhooks = ({
  name,
  description,
  displayName,
  sampleData,
  aiMetadata,
  outputSchema,
}: {
  name: string;
  description: string;
  displayName: string;
  sampleData: Record<string, unknown>;
  aiMetadata?: { description: string };
  outputSchema?: OutputSchema;
}) =>
  createTrigger({
    auth: calcomAuth,
    name,
    classification: 'READ',
    description,
    displayName,
    aiMetadata,
    outputSchema,
    props: {
      webhook_info: Property.MarkDown({
        value:
          'This webhook is added to your Cal.com account when you publish the flow and removed when you turn it off. It fires for bookings on the account that owns the API key.',
        variant: MarkdownVariant.INFO,
      }),
    },
    sampleData: sampleData,
    type: TriggerStrategy.WEBHOOK,
    async onEnable(context) {
      const request: HttpRequest = {
        method: HttpMethod.POST,
        url: `https://api.cal.com/v2/webhooks`,
        body: {
          triggers: [name],
          subscriberUrl: context.webhookUrl,
          active: true,
        },
        headers: {
          Authorization: `Bearer ${context.auth.secret_text}`,
          'cal-api-version': '2024-06-14',
        },
      };

      const response = await httpClient.sendRequest<WebhookResponseBody>(
        request
      );

      if (response.status === 200 || response.status === 201) {
        await context.store?.put(
          `cal_com_trigger_${name}`,
          response.body.data
        );
      }
    },
    async onDisable(context) {
      const data = await context.store?.get<WebhookInformation>(
        `cal_com_trigger_${name}`
      );
      if (data != null) {
        const request: HttpRequest = {
          method: HttpMethod.DELETE,
          url: `https://api.cal.com/v2/webhooks/${data.id}`,
          headers: {
            Authorization: `Bearer ${context.auth.secret_text}`,
            'cal-api-version': '2024-06-14',
          },
        };

        try {
          await httpClient.sendRequest(request);
        } catch (e) {
          if (!(e instanceof HttpError) || e.response.status !== 404) {
            throw e;
          }
        }
      }
    },
    async run(context) {
      return [context.payload.body];
    },
  });

interface WebhookInformation {
  id: string;
  userId: number;
  eventTypeId?: null | string;
  payloadTemplate?: null | string;
  triggers: string[];
  appId?: null | string;
  subscriberUrl: string;
}

interface WebhookResponseBody {
  data: WebhookInformation;
  status: string;
}