listFiles method

  1. @override
Future<List<CloudFile>> listFiles({
  1. required String path,
  2. bool recursive = false,
})
override

Lists files in a directory.

Implementation

@override
Future<List<CloudFile>> listFiles({
  required String path,
  bool recursive =
      false, // Recursive listing can be complex and quota-intensive
}) async {
  _checkAuth();

  final folder = await _getFolderByPath(path);
  if (folder == null || folder.id == null) {
    debugPrint("GoogleDriveProvider: Folder not found at $path");
    return [];
  }

  final List<CloudFile> cloudFiles = [];
  String? pageToken;
  do {
    final fileList = await driveApi.files.list(
      spaces: MultiCloudStorage.cloudAccess == CloudAccessType.appStorage
          ? 'appDataFolder'
          : 'drive',
      q: "'${folder.id}' in parents and trashed = false",
      $fields:
          'nextPageToken, files(id, name, size, modifiedTime, mimeType, parents)',
      pageToken: pageToken,
    );

    if (fileList.files != null) {
      for (final file in fileList.files!) {
        String currentItemPath = join(path, file.name ?? '');
        if (path == '/' || path.isEmpty) {
          currentItemPath = file.name ?? '';
        }

        cloudFiles.add(CloudFile(
          path: currentItemPath,
          name: file.name ?? 'Unnamed',
          size: file.size == null
              ? null
              : int.tryParse(file.size!), // Size is string
          modifiedTime: file.modifiedTime ?? DateTime.now(),
          isDirectory: file.mimeType == 'application/vnd.google-apps.folder',
          metadata: {
            'id': file.id,
            'mimeType': file.mimeType,
            'parents': file.parents,
          },
        ));
      }
    }
    pageToken = fileList.nextPageToken;
  } while (pageToken != null);

  if (recursive) {
    final List<CloudFile> subFolderFiles = [];
    for (final cf in cloudFiles) {
      if (cf.isDirectory) {
        subFolderFiles
            .addAll(await listFiles(path: cf.path, recursive: true));
      }
    }
    cloudFiles.addAll(subFolderFiles);
  }

  return cloudFiles;
}