List Drive API by mimetype

Drive API (v2) , iteratively collects files by mimetype ( in this case, PDFs ) in the code.


var ROOT_FOLDER_ID = 'YOUR_ROOT_FOLDER_ID' //<-- CHANGE THIS
function runpngFinder() {
  // Example for a specific folder:
  const allpngs = findpngsInFolder(ROOT_FOLDER_ID);// Images folder

  if (allpngs.length > 0) {
    Logger.log('Found %s png files.', allpngs.length);
    // Log results as a JSON string for easy viewing of all data.
    Logger.log(JSON.stringify(allpngs, null, 2)); 
    
    // You can also create a spreadsheet with this data:
     createSpreadsheetWithData(allpngs); 
  } else {
    Logger.log('No png files were found in the specified folder and its subfolders.');
  }
}


/**
 * Finds all png files recursively within a given Google Drive folder using Drive API v2.
 *
 * @param {string} folderId The ID of the folder to start searching from. Defaults to the root folder 'root'.
 * @return {Array<Object>} An array of objects, where each object contains details of a found png.
 * Returns an empty array if the start folder is not found or is invalid.
 */
function findpngsInFolder(folderId = 'root') {
  // This array will hold the final results.
  const pngsData = [];

  /**
   * A recursive helper function to traverse the folder tree.
   * @param {string} currentFolderId The ID of the folder currently being searched.
   * @param {string} currentFolderName The name of the folder currently being searched.
   */
  function searchIn(currentFolderId, currentFolderName) {
    // --- Step 1: Find all png files in the current folder ---
    try {
      const fileQuery = `'${currentFolderId}' in parents and mimeType = 'image/png' and trashed = false`;
      let pageToken;
      do {
        const fileList = Drive.Files.list({
          q: fileQuery,
          maxResults: 1000,
          pageToken: pageToken
        });

        if (fileList.items && fileList.items.length > 0) {
          for (const file of fileList.items) {
            pngsData.push({
              fileName: file.title,
              fileId: file.id,
              fileUrl: file.alternateLink,
              parentFolderId: currentFolderId,
              parentFolderName: currentFolderName
            });
          }
        }
        pageToken = fileList.nextPageToken;
      } while (pageToken);

    } catch (e) {
      Logger.log(`Error listing png files in folder "${currentFolderName}" (ID: ${currentFolderId}): ${e.toString()}`);
    }

    // --- Step 2: Find all subfolders in the current folder ---
    try {
      const folderQuery = `'${currentFolderId}' in parents and mimeType = 'application/vnd.google-apps.folder' and trashed = false`;
      let pageToken;
      do {
        const folderList = Drive.Files.list({
          q: folderQuery,
          maxResults: 1000,
          pageToken: pageToken
        });
        
        // --- Step 3: Recursively call the function for each subfolder ---
        if (folderList.items && folderList.items.length > 0) {
          for (const subfolder of folderList.items) {
            searchIn(subfolder.id, subfolder.title);
          }
        }
        pageToken = folderList.nextPageToken;
      } while (pageToken);

    } catch (e) {
      Logger.log(`Error listing subfolders in folder "${currentFolderName}" (ID: ${currentFolderId}): ${e.toString()}`);
    }
  }

  // --- Get the name of the starting folder and kick off the search ---
  let startFolderName;
  try {
    if (folderId === 'root') {
      startFolderName = 'My Drive (Root)';
    } else {
      const folder = Drive.Files.get(folderId);
      // Ensure it's actually a folder before starting
      if (folder.mimeType === 'application/vnd.google-apps.folder') {
        startFolderName = folder.title;
      } else {
         Logger.log(`Error: The provided ID "${folderId}" does not belong to a folder.`);
         return []; // Return empty if ID is not a folder
      }
    }
    // Start the recursive search from the top-level folder
    searchIn(folderId, startFolderName);
  } catch (e) {
    Logger.log(`Error accessing start folder with ID: "${folderId}". Please check if the ID is correct and you have permission. Error: ${e.toString()}`);
    return []; // Return empty array if start folder is invalid
  }

  return pngsData;
}


/**
 * (Optional) Helper function to write the data to a new spreadsheet.
 * @param {Array<Object>} data The array of png data objects.
 */
function createSpreadsheetWithData(data) {
  if (data.length === 0) return;

  const ss = SpreadsheetApp.create('png Files Report');
  const sheet = ss.getActiveSheet();
  
  // Create headers
  const headers = Object.keys(data[0]);
  sheet.appendRow(headers);
  sheet.getRange(1, 1, 1, headers.length).setFontWeight('bold');

  // Populate data
  const rows = data.map(obj => Object.values(obj));
  sheet.getRange(2, 1, rows.length, headers.length).setValues(rows);

  Logger.log('Report created at: ' + ss.getUrl());
}