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

6.2 KB
Raw Blame
import {
  createTrigger,
  AppConnectionValueForAuthProperty,
  isNil,
  Property,
} from '@activepieces/pieces-framework';
import { TriggerStrategy } from '@activepieces/pieces-framework';
import { googleCalendarAuth } from '../common';
import {
  DedupeStrategy,
  Polling,
  pollingHelper,
} from '@activepieces/pieces-common';
import { getCalendars } from '../common/helper';
import { CalendarObject } from '../common/types';
import { calendarOutputSchema } from '../output-schemas';

const polling: Polling<
  AppConnectionValueForAuthProperty<typeof googleCalendarAuth>,
  {
    access_role_filter: string[] | undefined;
    calendar_name_filter: string | undefined;
    exclude_shared: boolean | undefined;
  }
> = {
  strategy: DedupeStrategy.LAST_ITEM,
  items: async ({ auth, store, propsValue }) => {
    const { access_role_filter, calendar_name_filter, exclude_shared } =
      propsValue;

    const currentCalendars = await getCalendars(auth);

    let filteredCalendars = currentCalendars;

    if (access_role_filter && access_role_filter.length > 0) {
      filteredCalendars = filteredCalendars.filter((cal) =>
        access_role_filter.includes(cal.accessRole)
      );
    }

    if (calendar_name_filter && calendar_name_filter.trim()) {
      const searchTerm = calendar_name_filter.toLowerCase().trim();
      filteredCalendars = filteredCalendars.filter(
        (cal) =>
          cal.summary?.toLowerCase().includes(searchTerm) ||
          cal.description?.toLowerCase().includes(searchTerm)
      );
    }

    if (exclude_shared) {
      filteredCalendars = filteredCalendars.filter(
        (cal) => cal.accessRole === 'owner' || cal.primary
      );
    }

    const currentCalendarIds = filteredCalendars.map((cal) => cal.id);

    const oldCalendarIds = (await store.get<string[]>('calendars')) || [];
    const oldCalendarIdsSet = new Set(oldCalendarIds);

    const newCalendars = filteredCalendars.filter(
      (cal) => !oldCalendarIdsSet.has(cal.id)
    );

    await store.put('calendars', currentCalendarIds);

    return newCalendars.map((cal) => ({
      id: cal.id,
      data: {
        ...cal,
        isOwned: cal.accessRole === 'owner' || cal.primary,
        isShared: cal.accessRole !== 'owner' && !cal.primary,
        calendarType: cal.primary
          ? 'primary'
          : cal.accessRole === 'owner'
          ? 'owned'
          : 'shared',
      },
    }));
  },
};

export const newCalendar = createTrigger({
  auth: googleCalendarAuth,
  name: 'new_calendar',
  classification: 'READ',
  displayName: 'New Calendar',
  description: 'Fires when a new calendar is created or becomes accessible.',
  aiMetadata: {
    description: 'Fires when a calendar newly appears in the connected account\'s calendar list, whether created or shared in, detected by polling. Each fired item is the new calendar. Can be filtered by access role, a name/description text match, and an option to exclude shared calendars.',
  },
  propertyGroups: [
    {
      key: 'filters',
      display: 'section',
      label: 'Filters',
      icon: 'filter',
      props: ['access_role_filter', 'calendar_name_filter', 'exclude_shared'],
    },
  ],
  props: {
    access_role_filter: Property.StaticMultiSelectDropdown({
      displayName: 'Access Role Filter',
      description: 'Leave empty to fire for every access role.',
      required: false,
      options: {
        options: [
          { label: 'Owner', value: 'owner' },
          { label: 'Writer', value: 'writer' },
          { label: 'Reader', value: 'reader' },
          { label: 'Free/Busy Reader', value: 'freeBusyReader' },
        ],
      },
    }),
    calendar_name_filter: Property.ShortText({
      displayName: 'Calendar Name Filter',
      description: 'Only calendars whose name or description contain this.',
      required: false,
    }),
    exclude_shared: Property.Checkbox({
      displayName: 'Exclude Shared Calendars',
      description: 'Fires only for calendars you own.',
      required: false,
      defaultValue: false,
    }),
  },
  outputSchema: calendarOutputSchema,
  type: TriggerStrategy.POLLING,
  sampleData: {
    id: '[email protected]',
    summary: 'New Project Team Calendar',
    description: 'A shared calendar for the new project team.',
    timeZone: 'Asia/Kolkata',
    backgroundColor: '#9fe1e7',
    foregroundColor: '#000000',
    accessRole: 'owner',
    isOwned: true,
    isShared: false,
    calendarType: 'owned',
    primary: false,
  },

  async onEnable(context) {
    if (context.isRepublish && !isNil(await context.store.get('calendars'))) {
      return;
    }
    const calendars = await getCalendars(context.auth);

    const { access_role_filter, calendar_name_filter, exclude_shared } =
      context.propsValue;
    let filteredCalendars = calendars;

    if (access_role_filter && access_role_filter.length > 0) {
      filteredCalendars = filteredCalendars.filter((cal) =>
        access_role_filter.includes(cal.accessRole)
      );
    }

    if (calendar_name_filter && calendar_name_filter.trim()) {
      const searchTerm = calendar_name_filter.toLowerCase().trim();
      filteredCalendars = filteredCalendars.filter(
        (cal) =>
          cal.summary?.toLowerCase().includes(searchTerm) ||
          cal.description?.toLowerCase().includes(searchTerm)
      );
    }

    if (exclude_shared) {
      filteredCalendars = filteredCalendars.filter(
        (cal) => cal.accessRole === 'owner' || cal.primary
      );
    }

    await context.store.put(
      'calendars',
      filteredCalendars.map((cal) => cal.id)
    );

    await pollingHelper.onEnable(polling, context);
  },

  async onDisable(context) {
    await pollingHelper.onDisable(polling, context);
  },

  async run(context) {
    return await pollingHelper.poll(polling, context);
  },

  async test(context) {
    const calendars = await getCalendars(context.auth);
    const recentCalendars = calendars.slice(-1);
    return recentCalendars.map((cal: CalendarObject) => ({
      id: cal.id,
      data: {
        ...cal,
        isOwned: cal.accessRole === 'owner' || cal.primary,
        isShared: cal.accessRole !== 'owner' && !cal.primary,
        calendarType: cal.primary
          ? 'primary'
          : cal.accessRole === 'owner'
          ? 'owned'
          : 'shared',
      },
    }));
  },
});