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

5.3 KB
Raw Blame
import {
  createTrigger,
  TriggerStrategy,
  Property,
  FilesService,
  isNil,
} from '@activepieces/pieces-framework';
import { GmailProps } from '../common/props';
import { gmailAuth, createGoogleClient, GmailAuthValue } from '../auth';
import { gmail as googleGmail } from '@googleapis/gmail';
import {
  parseStream,
  convertAttachment,
  getFirstFiveOrAll,
} from '../common/data';
import { GmailLabel } from '../common/models';
import { newAttachmentTriggerOutputSchema } from '../output-schemas';

type Props = {
  from?: string;
  to?: string;
  subject?: string;
  label?: GmailLabel;
  category?: string;
  filenameExtension?: string;
};

export const gmailNewAttachmentTrigger = createTrigger({
  auth: gmailAuth,
  name: 'new_attachment',
  classification: 'READ',
  displayName: 'New Attachment',
  description: 'Triggers for each attachment on a new email.',
  aiMetadata: {
    description:
      'Fires when a new email carrying one or more attachments arrives, optionally narrowed by sender, recipient, subject, label, category, or file extension. Each event represents a single attachment (a multi-attachment email emits one event per attachment) along with its source message.',
  },
  props: {
    from: GmailProps.from,
    to: { ...GmailProps.to, advanced: true },
    subject: GmailProps.subject,
    label: GmailProps.label({ required: false }),
    category: { ...GmailProps.category, advanced: true },
    filenameExtension: Property.ShortText({
      displayName: 'File Extension',
      description: 'Only attachments with this extension.',
      placeholder: 'pdf',
      required: false,
    }),
  },
  outputSchema: newAttachmentTriggerOutputSchema,
  sampleData: {},
  type: TriggerStrategy.POLLING,
  async onEnable(context) {
    if (context.isRepublish && !isNil(await context.store.get('lastPoll'))) {
      return;
    }
    await context.store.put('lastPoll', Date.now());
  },
  async onDisable(context) {
    return;
  },
  async run(context) {
    const lastFetchEpochMS = (await context.store.get<number>('lastPoll')) ?? 0;

    const items = await pollRecentMessages({
      auth: context.auth,
      props: context.propsValue,
      files: context.files,
      lastFetchEpochMS: lastFetchEpochMS,
    });

    const newLastEpochMilliSeconds = items.reduce(
      (acc, item) => Math.max(acc, item.epochMilliSeconds),
      lastFetchEpochMS
    );
    await context.store.put('lastPoll', newLastEpochMilliSeconds);
    return items
      .filter((f) => f.epochMilliSeconds > lastFetchEpochMS)
      .map((item) => item.data);
  },
  async test(context) {
    const lastFetchEpochMS = (await context.store.get<number>('lastPoll')) ?? 0;

    const items = await pollRecentMessages({
      auth: context.auth,
      props: context.propsValue,
      files: context.files,
      lastFetchEpochMS: lastFetchEpochMS,
    });

    return getFirstFiveOrAll(items.map((item) => item.data));
  },
});

async function pollRecentMessages({
  auth,
  props,
  files,
  lastFetchEpochMS,
}: {
  auth: GmailAuthValue;
  props: Props;
  files: FilesService;
  lastFetchEpochMS: number;
}): Promise<
  {
    epochMilliSeconds: number;
    data: unknown;
  }[]
> {
  const authClient = await createGoogleClient(auth);

  const gmail = googleGmail({ version: 'v1', auth: authClient });

  // construct query
  const query = ['has:attachment'];
  const maxResults = lastFetchEpochMS === 0 ? 5 : 20;
  const afterUnixSeconds = Math.floor(lastFetchEpochMS / 1000);

  if (props.from) query.push(`from:(${props.from})`);
  if (props.to) query.push(`to:(${props.to})`);
  if (props.subject) query.push(`subject:(${props.subject})`);
  if (props.label) query.push(`label:${props.label.name}`);
  if (props.category) query.push(`category:${props.category}`);
  if (props.filenameExtension)
    query.push(`filename:${props.filenameExtension}`);
  if (afterUnixSeconds != null && afterUnixSeconds > 0)
    query.push(`after:${afterUnixSeconds}`);

  // List Messages
  const messagesResponse = await gmail.users.messages.list({
    userId: 'me',
    q: query.join(' '),
    maxResults,
  });

  // Reverse to process oldest-first so partial progress doesn't skip messages
  const messages = (messagesResponse.data.messages || []).slice().reverse();

  const pollingResponse = [];
  for (const message of messages) {
    try {
      const rawMailResponse = await gmail.users.messages.get({
        userId: 'me',
        id: message.id!,
        format: 'raw',
      });

      const parsedMailResponse = await parseStream(
        Buffer.from(rawMailResponse.data.raw as string, 'base64').toString(
          'utf-8'
        )
      );

      const { attachments, ...restOfParsedMailResponse } = parsedMailResponse;
      const parsedAttachments = await convertAttachment(attachments, files);

      for (const attachment of parsedAttachments) {
        pollingResponse.push({
          epochMilliSeconds: Number(rawMailResponse.data.internalDate),
          data: {
            attachment,
            message: {
              id: message.id,
              ...restOfParsedMailResponse,
            },
          },
        });
      }
    } catch (error: any) {
      const isRateLimit =
        error.status === 429 ||
        (error.status === 403 &&
          /quota|rate.?limit/i.test(error.message ?? ''));
      if (isRateLimit) {
        break;
      }
      throw error;
    }
  }

  return pollingResponse;
}