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

7.2 KB
Raw Blame
import {
  httpClient,
  HttpMethod,
  AuthenticationType,
  HttpRequest,
} from '@activepieces/pieces-common';
import { Property } from '@activepieces/pieces-framework';
import dayjs from 'dayjs';
import { drive as googleDrive } from '@googleapis/drive';
import { googleDriveAuth, GoogleDriveAuthValue, getAccessToken, createGoogleClient } from '../auth';

const FOLDER_DROPDOWN_PAGE_SIZE = 1000;

const escapeDriveQueryLiteral = (value: string): string =>
  value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");

async function fetchFolderDropdownOptions({
  auth,
  searchValue,
  includeTeamDrives,
}: {
  auth: GoogleDriveAuthValue | undefined;
  searchValue: string | undefined;
  includeTeamDrives: boolean | undefined;
}) {
  if (!auth) {
    return {
      disabled: true,
      options: [],
      placeholder: 'Connect your Google account first',
    };
  }
  const accessToken = await getAccessToken(auth);
  const trimmedSearchValue = searchValue?.trim() ?? '';
  const qParts = [
    "mimeType='application/vnd.google-apps.folder'",
    'trashed = false',
  ];
  if (trimmedSearchValue.length > 0) {
    qParts.push(`name contains '${escapeDriveQueryLiteral(trimmedSearchValue)}'`);
  }
  const request: HttpRequest = {
    method: HttpMethod.GET,
    url: `https://www.googleapis.com/drive/v3/files`,
    queryParams: {
      q: qParts.join(' and '),
      includeItemsFromAllDrives: includeTeamDrives ? 'true' : 'false',
      supportsAllDrives: 'true',
      corpora: includeTeamDrives ? 'allDrives' : 'user',
      pageSize: String(FOLDER_DROPDOWN_PAGE_SIZE),
      fields: 'nextPageToken, files(id, name)',
    },
    authentication: {
      type: AuthenticationType.BEARER_TOKEN,
      token: accessToken,
    },
  };
  let folders: { id: string; name: string }[] = [];
  let truncated = false;
  try {
    const response = await httpClient.sendRequest<{
      files: { id: string; name: string }[];
      nextPageToken?: string;
    }>(request);
    folders = response.body.files ?? [];
    truncated = Boolean(response.body.nextPageToken);
  } catch (e) {
    throw new Error(`Failed to get folders\nError:${e}`);
  }

  return {
    disabled: false,
    placeholder: truncated
      ? `Showing the first ${folders.length} matches. Type to narrow the list, or paste an ID with Dynamic value.`
      : undefined,
    options: folders.map((folder: { id: string; name: string }) => {
      return {
        label: folder.name,
        value: folder.id,
      };
    }),
  };
}

function parentFolderDropdown({
  displayName,
  description,
}: {
  displayName: string;
  description: string;
}) {
  return Property.Dropdown({
    displayName,
    description,
    required: false,
    auth: googleDriveAuth,
    refreshers: ['include_team_drives'],
    refreshOnSearch: true,
    options: async ({ auth, include_team_drives }, ctx) =>
      fetchFolderDropdownOptions({
        auth: auth as GoogleDriveAuthValue | undefined,
        searchValue: ctx?.searchValue,
        includeTeamDrives: include_team_drives as boolean | undefined,
      }),
  });
}

export const common = {
  properties: {
    parentFolder: parentFolderDropdown({
      displayName: 'Parent Folder',
      description:
        'Leave empty for the root of My Drive. Type to search by folder name.',
    }),
    include_team_drives: Property.Checkbox({
      displayName: 'Include Team Drives',
      description: 'Also include shared drives, not only My Drive.',
      defaultValue: false,
      required: false,
    }),
  },

  parentFolderDropdown,
  escapeDriveQueryLiteral,
  fetchFolderDropdownOptions,

  async getFiles(
    auth: GoogleDriveAuthValue,
    search?: {
      parent?: string;
      createdTime?: string | number | Date;
      createdTimeOp?: string;
      changedSince?: string | number | Date;
      mimeTypes?: string[];
      excludeShortcuts?: boolean;
      maxPages?: number;
      includeTeamDrive?: boolean;
    },
    order?: string
  ) {
    const authClient = await createGoogleClient(auth);

    const drive = googleDrive({ version: 'v3', auth: authClient });

    const q: string[] = [];
    if (search?.parent)
      q.push(`'${escapeDriveQueryLiteral(search.parent)}' in parents`);
    if (search?.createdTime)
      q.push(
        `createdTime ${search.createdTimeOp ?? '>'} '${dayjs(
          search.createdTime
        ).format()}'`
      );
    if (search?.changedSince) {
      const changedSince = dayjs(search.changedSince).format();
      q.push(
        `(modifiedTime > '${changedSince}' or createdTime > '${changedSince}')`
      );
    }
    if (search?.mimeTypes?.length)
      q.push(
        `(${search.mimeTypes
          .map(
            (mimeType) => `mimeType='${escapeDriveQueryLiteral(mimeType)}'`
          )
          .join(' or ')})`
      );
    if (search?.excludeShortcuts)
      q.push(`mimeType!='application/vnd.google-apps.shortcut'`);
    q.push(`trashed = false`);
    const allFiles: any[] = [];
    let pageToken: string | undefined = undefined;
    let pagesFetched = 0;
    do {
      const listParams: Record<string, any> = {
        q: q.concat("mimeType!='application/vnd.google-apps.folder'").join(' and '),
        fields:
          'nextPageToken, files(id, name, mimeType, webViewLink, kind, createdTime, modifiedTime)',
        orderBy: order ?? 'createdTime desc',
        supportsAllDrives: true,
        includeItemsFromAllDrives: search?.includeTeamDrive,
        corpora: search?.includeTeamDrive ? 'allDrives' : 'user',
      };
      if (pageToken) listParams.pageToken = pageToken;
      const response = await drive.files.list(listParams);
      allFiles.push(...(response.data.files ?? []));
      pageToken = response.data.nextPageToken ?? undefined;
      pagesFetched += 1;
      if (search?.maxPages && pagesFetched >= search.maxPages) break;
    } while (pageToken);

    return allFiles;
  },

  async getFolders(
    auth: GoogleDriveAuthValue,
    search?: {
      parent?: string;
      createdTime?: string | number | Date;
      createdTimeOp?: string;
      includeTeamDrive?: boolean;
    },
    order?: string
  ) {
    const authClient = await createGoogleClient(auth);

    const drive = googleDrive({ version: 'v3', auth: authClient });

    const q: string[] = [`mimeType='application/vnd.google-apps.folder'`];
    if (search?.parent)
      q.push(`'${escapeDriveQueryLiteral(search.parent)}' in parents`);
    if (search?.createdTime)
      q.push(
        `createdTime ${search.createdTimeOp ?? '>'} '${dayjs(
          search.createdTime
        ).format()}'`
      );
    q.push(`trashed = false`);
    const allFolders: any[] = [];
    let pageToken: string | undefined = undefined;
    do {
      const listParams: Record<string, any> = {
        q: q.join(' and '),
        fields: 'nextPageToken, files(id, name, createdTime)',
        orderBy: order ?? 'createdTime desc',
        supportsAllDrives: true,
        includeItemsFromAllDrives: search?.includeTeamDrive,
        corpora: search?.includeTeamDrive ? 'allDrives' : 'user',
      };
      if (pageToken) listParams.pageToken = pageToken;
      const response = await drive.files.list(listParams);
      allFolders.push(...(response.data.files ?? []));
      pageToken = response.data.nextPageToken ?? undefined;
    } while (pageToken);

    return allFolders;
  },
};