共有ドライブを管理する

このドキュメントでは、Google Drive API を使用して共有ドライブを作成したり、メンバーと権限を管理したりするなど、共有ドライブの管理に関連するタスクについて説明します。

レスポンスで返すフィールドを指定する場合は、drives リソースの任意の方法で fields システム パラメータを設定できます。fields パラメータを指定しない場合、サーバーはメソッドに固有のデフォルトのフィールド セットを返します。たとえば、list メソッドは、各共有ドライブの kindidname フィールドのみを返します。詳細については、特定のフィールドを返すをご覧ください。

共有ドライブのフォルダの制限について詳しくは、共有ドライブのフォルダの制限をご覧ください。

前提条件

共有ドライブを作成して管理するには、次の要件を満たしていることを確認してください。

  • Google Workspace アカウント: 共有ドライブは、サポートされている Google Workspace エディション(Business Standard、Business Plus、Enterprise、Education など)でご利用いただけます。個人の Google アカウント(@gmail.com)では共有ドライブを作成できません。
  • 作成権限: ドメイン管理者は、組織内のユーザーが共有ドライブを作成できるかどうかを設定できます。認証されたユーザーは、共有ドライブの作成が許可されている組織部門に属している必要があります。
  • OAuth 2.0 スコープ: アプリは https://www.googleapis.com/auth/drive スコープで承認されている必要があります。
  • ロール: ユーザーが共有ドライブを作成すると、その共有ドライブに対する organizer ロールが自動的に割り当てられます。ドライブの設定の管理、ドライブの名前の変更、メンバーの追加または削除、共有ドライブの削除には、すべて organizer ロールが必要です。ロールの詳細については、共有ドライブのロールをご覧ください。
  • ドメイン管理者アクセス: ドメイン管理者は、useDomainAdminAccess=true を渡すことで、メンバーシップに関係なく組織内の任意の共有ドライブを管理できます。詳しくは、ドメイン管理者として共有ドライブを管理するをご覧ください。

共有ドライブを作成する

共有ドライブを作成するには、requestId パラメータを指定して drives リソースの create メソッドを使用します。

requestId パラメータは、共有ドライブのべき等作成の論理的な試行を識別します。リクエストがタイムアウトした場合や、バックエンドで不明なエラーが返された場合、同じリクエストを繰り返しても重複は作成されません。requestId とリクエストの本文は同じである必要があります。

次のコードサンプルは、共有ドライブの作成方法を示しています。

Java

drive/snippets/drive_v3/src/main/java/CreateDrive.java
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.Drive;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Arrays;
import java.util.UUID;

/* class to demonstrate use-case of Drive's create drive. */
public class CreateDrive {

  /**
   * Create a drive.
   *
   * @return Newly created drive id.
   * @throws IOException if service account credentials file not found.
   */
  public static String createDrive() throws IOException {
        /*Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity for
        guides on implementing OAuth2 for your application.*/
    GoogleCredentials credentials =
        GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    com.google.api.services.drive.Drive service =
        new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(),
            GsonFactory.getDefaultInstance(),
            requestInitializer)
            .setApplicationName("Drive samples")
            .build();

    Drive driveMetadata = new Drive();
    driveMetadata.setName("Project Resources");
    String requestId = UUID.randomUUID().toString();
    try {
      Drive drive = service.drives().create(requestId,
              driveMetadata)
          .execute();
      System.out.println("Drive ID: " + drive.getId());

      return drive.getId();
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      System.err.println("Unable to create drive: " + e.getDetails());
      throw e;
    }
  }
}

Python

drive/snippets/drive-v3/drive_snippet/create_drive.py
import uuid

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def create_drive():
  """Create a drive.
  Returns:
      Id of the created drive

  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  creds, _ = google.auth.default()

  try:
    # create drive api client
    service = build("drive", "v3", credentials=creds)

    drive_metadata = {"name": "Project Resources"}
    request_id = str(uuid.uuid4())
    # pylint: disable=maybe-no-member
    drive = (
        service.drives()
        .create(body=drive_metadata, requestId=request_id, fields="id")
        .execute()
    )
    print(f'Drive ID: {drive.get("id")}')

  except HttpError as error:
    print(f"An error occurred: {error}")
    drive = None

  return drive.get("id")


if __name__ == "__main__":
  create_drive()

Node.js

drive/snippets/drive_v3/drive_snippets/create_drive.js
import {GoogleAuth} from 'google-auth-library';
import {google} from 'googleapis';
import {v4 as uuid} from 'uuid';

/**
 * Creates a new shared drive.
 * @return {Promise<string>} The ID of the created shared drive.
 */
async function createDrive() {
  // Authenticate with Google and get an authorized client.
  // TODO (developer): Use an appropriate auth mechanism for your app.
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Drive API client (v3).
  const service = google.drive({version: 'v3', auth});

  // The metadata for the new shared drive.
  const driveMetadata = {
    name: 'Project resources',
  };

  // A unique request ID to avoid creating duplicate shared drives.
  const requestId = uuid();

  // Create the new shared drive.
  const Drive = await service.drives.create({
    requestBody: driveMetadata,
    requestId,
    fields: 'id',
  });

  // Print the ID of the new shared drive.
  console.log('Drive Id:', Drive.data.id);
  if (!Drive.data.id) {
    throw new Error('Drive ID not found.');
  }
  return Drive.data.id;
}

PHP

drive/snippets/drive_v3/src/DriveCreateDrive.php
<?php
use Google\Client;
use Google\Service\Drive;
use Ramsey\Uuid\Uuid;
function createDrive()
{
    try {
        $client = new Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope(Drive::DRIVE);
        $driveService = new Drive($client);

        $driveMetadata = new Drive\Drive(array(
                'name' => 'Project Resources'));
        $requestId = Uuid::uuid4()->toString();
        $drive = $driveService->drives->create($requestId, $driveMetadata, array(
                'fields' => 'id'));
        printf("Drive ID: %s\n", $drive->id);
        return $drive->id;
    } catch(Exception $e)  {
        echo "Error Message: ".$e;
    }  

}

.NET

drive/snippets/drive_v3/DriveV3Snippets/CreateDrive.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate use of Drive's create drive.
    public class CreateDrive
    {
        /// <summary>
        /// Create a drive.
        /// </summary>
        /// <returns>newly created drive Id.</returns>
        public static string DriveCreateDrive()
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                var driveMetadata = new Drive()
                {
                    Name = "Project Resources"
                };
                var requestId = Guid.NewGuid().ToString();
                var request = service.Drives.Create(driveMetadata, requestId);
                request.Fields = "id";
                var drive = request.Execute();
                Console.WriteLine("Drive ID: " + drive.Id);
                return drive.Id;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

create メソッドの呼び出しはべき等です。

前のリクエストで共有ドライブが正常に作成された場合、または再試行によって共有ドライブが正常に作成された場合、このメソッドは drives リソースのインスタンスを返します。長時間経過した場合やリクエストの本文が変更された場合など、requestId を破棄する必要があることを示す 409 エラーが返されることがあります。

共有ドライブを取得する

共有ドライブのメタデータを取得するには、driveId パス パラメータを使用して drives リソースで get メソッドを使用します。ドライブ ID がわからない場合は、list メソッドを使用してすべての共有ドライブを一覧表示できます。

get メソッドは、共有ドライブを drives リソースのインスタンスとして返します。

ドメイン管理者としてリクエストを発行するには、useDomainAdminAccess クエリ パラメータを true に設定します。詳しくは、ドメイン管理者として共有ドライブを管理するをご覧ください。

共有ドライブを一覧表示する

ユーザーの共有ドライブを一覧表示するには、drives リソースの list メソッドを使用します。このメソッドは、共有ドライブのリストを返します。

次のクエリ パラメータを渡して、共有ドライブのページネーションをカスタマイズしたり、共有ドライブをフィルタしたりします。

  • pageSize: ページごとに返す共有ドライブの最大数。

  • pageToken: 前回のリスト呼び出しから受け取ったページトークン。後続のページを取得するには、このトークンを指定します。

  • q: 共有ドライブを検索するためのクエリ文字列。詳しくは、共有ドライブを検索するをご覧ください。

  • useDomainAdminAccess: リクエストをドメイン管理者として発行し、リクエスト元が管理者であるドメインのすべての共有ドライブを返すには、true に設定します。詳しくは、ドメイン管理者として共有ドライブを管理するをご覧ください。

共有ドライブを更新する

共有ドライブのメタデータを更新するには、driveId パス パラメータを使用して drives リソースの update メソッドを使用します。

このメソッドは、共有ドライブを drives リソースのインスタンスとして返します。

ドメイン管理者としてリクエストを発行するには、useDomainAdminAccess クエリ パラメータを true に設定します。詳しくは、ドメイン管理者として共有ドライブを管理するをご覧ください。

共有ドライブを表示または非表示にする

共有ドライブをデフォルト ビューから非表示にするには、driveId パラメータを使用して drives リソースの hide メソッドを使用します。

共有ドライブが非表示になると、ドライブは共有ドライブ リソースを hidden=true としてマークします。非表示の共有ドライブは、ドライブの UI や返されたファイルのリストに表示されません。

共有ドライブをデフォルトのビューに復元するには、driveId パラメータを使用して drives リソースの unhide メソッドを使用します。

どちらのメソッドも、共有ドライブを drives リソースのインスタンスとして返します。

共有ドライブを削除する

共有ドライブを完全に削除するには、driveId パラメータを使用して drives リソースの delete メソッドを使用します。

共有ドライブを削除する前に、共有ドライブ内のすべてのコンテンツをゴミ箱に移動するか、削除する必要があります。また、ユーザーには共有ドライブ フォルダに対する role=organizer 権限も必要です。詳しくは、ファイルとフォルダをゴミ箱に移動または削除するをご覧ください。

次のクエリ パラメータを渡します。

  • useDomainAdminAccess: ドメイン管理者としてリクエストを発行するには、true に設定します。詳しくは、ドメイン管理者として共有ドライブを管理するをご覧ください。

  • allowItemDeletion: 共有ドライブ内のアイテムを削除するには、true に設定します。useDomainAdminAccesstrue に設定されている場合にのみサポートされます。

共有ドライブのメンバーを追加または削除する

permissions リソースを使用して、共有ドライブのメンバーを追加または削除します。

メンバーを追加するには、共有ドライブに権限を作成します。権限付与の方法は、共有ドライブ内の個々のファイルにも使用できます。これにより、メンバーに追加の権限を付与したり、メンバー以外のユーザーが特定のアイテムで共同編集できるようにしたりできます。

詳細とサンプルコードについては、ファイル、フォルダ、ドライブを共有するをご覧ください。

ドメイン管理者として共有ドライブを管理する

drives リソースと permissions リソースで useDomainAdminAccess パラメータを適用して、組織全体の共有ドライブを管理します。

useDomainAdminAccess=true を使用してこれらのメソッドを呼び出すユーザーには、Drive and Docs 管理者権限が必要です。管理者は、特定の共有ドライブのメンバーであるかどうかに関係なく、共有ドライブを検索したり、組織が所有する共有ドライブの権限を更新したりできます。

サービス アカウントを使用する場合は、サービス アカウントの権限借用を使用して、認証された管理者の権限を借用する必要がある場合があります。ユーザー アカウントとは異なり、サービス アカウントは Google Workspace ドメインに属していません。ドキュメントやイベントなどの Google Workspace アセットを Google Workspace ドメイン全体で共有しても、サービス アカウントとは共有されません。詳細については、サービス アカウントの概要をご覧ください。

主催者がいない共有ドライブを復元する

次のコードサンプルは、管理者がいなくなった共有ドライブを復元する方法を示しています。

Java

drive/snippets/drive_v3/src/main/java/RecoverDrive.java
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.Drive;
import com.google.api.services.drive.model.DriveList;
import com.google.api.services.drive.model.Permission;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/* class to demonstrate use-case of Drive's shared drive without an organizer. */
public class RecoverDrive {

  /**
   * Find all shared drives without an organizer and add one.
   *
   * @param realUser User's email id.
   * @return All shared drives without an organizer.
   * @throws IOException if shared drive not found.
   */
  public static List<Drive> recoverDrives(String realUser)
      throws IOException {
        /*Load pre-authorized user credentials from the environment.
        TODO(developer) - See https://developers.google.com/identity for
        guides on implementing OAuth2 for your application.*/
    GoogleCredentials credentials =
        GoogleCredentials.getApplicationDefault().createScoped(Arrays.asList(DriveScopes.DRIVE));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

    // Build a new authorized API client service.
    com.google.api.services.drive.Drive service =
        new com.google.api.services.drive.Drive.Builder(new NetHttpTransport(),
            GsonFactory.getDefaultInstance(),
            requestInitializer)
            .setApplicationName("Drive samples")
            .build();
    List<Drive> drives = new ArrayList<Drive>();

    // Find all shared drives without an organizer and add one.
    // Note: This example does not capture all cases. Shared drives
    // that have an empty group as the sole organizer, or an
    // organizer outside the organization are not captured. A
    // more exhaustive approach would evaluate each shared drive
    // and the associated permissions and groups to ensure an active
    // organizer is assigned.
    String pageToken = null;
    Permission newOrganizerPermission = new Permission()
        .setType("user")
        .setRole("organizer");

    newOrganizerPermission.setEmailAddress(realUser);


    do {
      DriveList result = service.drives().list()
          .setQ("organizerCount = 0")
          .setFields("nextPageToken, drives(id, name)")
          .setUseDomainAdminAccess(true)
          .setPageToken(pageToken)
          .execute();
      for (Drive drive : result.getDrives()) {
        System.out.printf("Found drive without organizer: %s (%s)\n",
            drive.getName(), drive.getId());
        // Note: For improved efficiency, consider batching
        // permission insert requests
        Permission permissionResult = service.permissions()
            .create(drive.getId(), newOrganizerPermission)
            .setUseDomainAdminAccess(true)
            .setSupportsAllDrives(true)
            .setFields("id")
            .execute();
        System.out.printf("Added organizer permission: %s\n",
            permissionResult.getId());

      }

      drives.addAll(result.getDrives());

      pageToken = result.getNextPageToken();
    } while (pageToken != null);

    return drives;
  }
}

Python

drive/snippets/drive-v3/drive_snippet/recover_drives.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def recover_drives(real_user):
  """Find all shared drives without an organizer and add one.
  Args:
      real_user:User ID for the new organizer.
  Returns:
      drives object

  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  creds, _ = google.auth.default()
  try:
    # create drive api client
    service = build("drive", "v3", credentials=creds)

    drives = []

    # pylint: disable=maybe-no-member
    page_token = None
    new_organizer_permission = {
        "type": "user",
        "role": "organizer",
        "emailAddress": "user@example.com",
    }
    new_organizer_permission["emailAddress"] = real_user

    while True:
      response = (
          service.drives()
          .list(
              q="organizerCount = 0",
              fields="nextPageToken, drives(id, name)",
              useDomainAdminAccess=True,
              pageToken=page_token,
          )
          .execute()
      )
      for drive in response.get("drives", []):
        print(
            "Found shared drive without organizer: "
            f"{drive.get('title')}, {drive.get('id')}"
        )
        permission = (
            service.permissions()
            .create(
                fileId=drive.get("id"),
                body=new_organizer_permission,
                useDomainAdminAccess=True,
                supportsAllDrives=True,
                fields="id",
            )
            .execute()
        )
        print(f'Added organizer permission: {permission.get("id")}')

      drives.extend(response.get("drives", []))
      page_token = response.get("nextPageToken", None)
      if page_token is None:
        break

  except HttpError as error:
    print(f"An error occurred: {error}")

  return drives


if __name__ == "__main__":
  recover_drives(real_user="gduser1@workspacesamples.dev")

Node.js

drive/snippets/drive_v3/drive_snippets/recover_drives.js
import {GoogleAuth} from 'google-auth-library';
import {google} from 'googleapis';

/**
 * Finds all shared drives without an organizer and adds one.
 * @param {string} userEmail The email of the user to assign ownership to.
 * @return {Promise<object[]>} A list of the recovered drives.
 */
async function recoverDrives(userEmail) {
  // Authenticate with Google and get an authorized client.
  // TODO (developer): Use an appropriate auth mechanism for your app.
  const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/drive',
  });

  // Create a new Drive API client (v3).
  const service = google.drive({version: 'v3', auth});

  // The permission to add to the shared drive.
  const newOrganizerPermission = {
    type: 'user',
    role: 'organizer',
    emailAddress: userEmail, // e.g., 'user@example.com'
  };

  // List all shared drives with no organizers.
  const result = await service.drives.list({
    q: 'organizerCount = 0',
    fields: 'nextPageToken, drives(id, name)',
    useDomainAdminAccess: true,
  });

  // Add the new organizer to each found shared drive.
  for (const drive of result.data.drives ?? []) {
    if (!drive.id) {
      continue;
    }

    console.log('Found shared drive without organizer:', drive.name, drive.id);
    await service.permissions.create({
      requestBody: newOrganizerPermission,
      fileId: drive.id,
      useDomainAdminAccess: true,
      supportsAllDrives: true,
      fields: 'id',
    });
  }
  return result.data.drives ?? [];
}

PHP

drive/snippets/drive_v3/src/DriveRecoverDrives.php
<?php
use Google\Client;
use Google\Service\Drive;
use Ramsey\Uuid\Uuid;
function recoverDrives()
{
   try {
    $client = new Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope(Drive::DRIVE);
    $driveService = new Drive($client);

    $realUser = readline("Enter user email address: ");

    $drives = array();
    // Find all shared drives without an organizer and add one.
    // Note: This example does not capture all cases. Shared drives
    // that have an empty group as the sole organizer, or an
    // organizer outside the organization are not captured. A
    // more exhaustive approach would evaluate each shared drive
    // and the associated permissions and groups to ensure an active
    // organizer is assigned.
    $pageToken = null;
    $newOrganizerPermission = new Drive\Permission(array(
        'type' => 'user',
        'role' => 'organizer',
        'emailAddress' => 'user@example.com'
    ));
    $newOrganizerPermission['emailAddress'] = $realUser;
    do {
        $response = $driveService->drives->listDrives(array(
            'q' => 'organizerCount = 0',
            'fields' => 'nextPageToken, drives(id, name)',
            'useDomainAdminAccess' => true,
            'pageToken' => $pageToken
        ));
        foreach ($response->drives as $drive) {
            printf("Found shared drive without organizer: %s (%s)\n",
                $drive->name, $drive->id);
            $permission = $driveService->permissions->create($drive->id,
                $newOrganizerPermission,
                array(
                    'fields' => 'id',
                    'useDomainAdminAccess' => true,
                    'supportsAllDrives' => true
                ));
            printf("Added organizer permission: %s\n", $permission->id);
        }
        array_push($drives, $response->drives);
        $pageToken = $response->pageToken;
    } while ($pageToken != null);
    return $drives;
   } catch(Exception $e) {
      echo "Error Message: ".$e;
   }
}

.NET

drive/snippets/drive_v3/DriveV3Snippets/RecoverDrives.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;

namespace DriveV3Snippets
{
    // Class to demonstrate use-case of Drive's shared drive without an organizer.
    public class RecoverDrives
    {
        /// <summary>
        /// Find all shared drives without an organizer and add one.
        /// </summary>
        /// <param name="realUser">User ID for the new organizer.</param>
        /// <returns>all shared drives without an organizer.</returns>
        public static IList<Drive> DriveRecoverDrives(string realUser)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(DriveService.Scope.Drive);

                // Create Drive API service.
                var service = new DriveService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive API Snippets"
                });

                var drives = new List<Drive>();
                // Find all shared drives without an organizer and add one.
                // Note: This example does not capture all cases. Shared drives
                // that have an empty group as the sole organizer, or an
                // organizer outside the organization are not captured. A
                // more exhaustive approach would evaluate each shared drive
                // and the associated permissions and groups to ensure an active
                // organizer is assigned.
                string pageToken = null;
                var newOrganizerPermission = new Permission()
                {
                    Type = "user",
                    Role = "organizer",
                    EmailAddress = realUser
                };

                do
                {
                    var request = service.Drives.List();
                    request.UseDomainAdminAccess = true;
                    request.Q = "organizerCount = 0";
                    request.Fields = "nextPageToken, drives(id, name)";
                    request.PageToken = pageToken;
                    var result = request.Execute();
                    foreach (var drive in result.Drives)
                    {
                        Console.WriteLine(("Found abandoned shared drive: {0} ({1})",
                            drive.Name, drive.Id));
                        // Note: For improved efficiency, consider batching
                        // permission insert requests
                        var permissionRequest = service.Permissions.Create(
                            newOrganizerPermission,
                            drive.Id
                        );
                        permissionRequest.UseDomainAdminAccess = true;
                        permissionRequest.SupportsAllDrives = true;
                        permissionRequest.Fields = "id";
                        var permissionResult = permissionRequest.Execute();
                        Console.WriteLine("Added organizer permission: {0}", permissionResult.Id);
                    }

                    pageToken = result.NextPageToken;
                } while (pageToken != null);

                return drives;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

ユーザーがファイルをダウンロード、印刷、コピーできないようにする

共有ドライブ内のファイルのダウンロード、印刷、コピーをユーザーがどのように行えるかを制限できます。

ユーザーが共有ドライブの主催者が適用したダウンロード制限を変更できるかどうかを判断するには、capabilities.canChangeDownloadRestriction ブール値フィールドを確認します。capabilities.canChangeDownloadRestrictiontrue に設定されている場合、共有ドライブにダウンロード制限を適用できます。詳細については、ファイル機能についてをご覧ください。

drives リソースには、共有ドライブでアクションを実行できるかどうかを示すために使用されるブール値の restrictions フィールドのコレクションが含まれています。制限は、共有ドライブまたは共有ドライブ内のアイテムに適用されます。制限は drives.update メソッドを使用して設定できます。

共有ドライブにダウンロード制限を適用するには、共有ドライブの管理者が DownloadRestriction オブジェクトを使用して drives リソースの restrictions.downloadRestriction フィールドを設定します。restrictedForReaders ブール値フィールドを true に設定すると、読者のダウンロードとコピーの両方が制限されることが宣言されます。restrictedForWriters ブール値フィールドを true に設定すると、作成者のダウンロードとコピーの両方が制限されることが宣言されます。restrictedForWriters フィールドが true の場合、閲覧者によるダウンロードとコピーも制限されます。同様に、restrictedForWriterstrue に、restrictedForReadersfalse に設定することは、restrictedForWritersrestrictedForReaders の両方を true に設定することと同じです。

下位互換性

DownloadRestriction オブジェクトの導入に伴い、restrictions.copyRequiresWriterPermission ブール値フィールドの機能が更新されました。

restrictions.copyRequiresWriterPermissiontrue に設定すると、DownloadRestriction オブジェクトの restrictedForReaders ブール値フィールドが true に更新され、閲覧者に対してダウンロードとコピーの両方が制限されることが宣言されます。

copyRequiresWriterPermission フィールドを false に設定すると、restrictedForWriters フィールドと restrictedForReaders フィールドの両方が false に更新されます。つまり、すべてのユーザーのダウンロードまたはコピーの制限設定が削除されます。

ダウンロード、印刷、コピー機能を制御するフィールド

次の表に、ダウンロード、印刷、コピーの機能に影響する drives リソース フィールドを示します。

フィールド 説明 バージョン
capabilities.canCopy 現在のユーザーが共有ドライブ内のファイルをコピーできるかどうか。 v2 & v3
capabilities.canDownload 現在のユーザーが共有ドライブ内のファイルをダウンロードできるかどうか。 v2 & v3
capabilities.canChangeCopyRequiresWriterPermissionRestriction 現在のユーザーが共有ドライブの copyRequiresWriterPermission 制限を変更できるかどうか。 v2 & v3
capabilities.canResetDriveRestrictions 現在のユーザーが共有ドライブの制限をデフォルトにリセットできるかどうか。 v2 & v3
capabilities.canChangeDownloadRestriction 現在のユーザーが共有ドライブのダウンロード制限を変更できるかどうか。 v3 のみ
restrictions.copyRequiresWriterPermission 共有ドライブ内のファイルをコピー、印刷、ダウンロードするオプションが閲覧者とコメント投稿者に対して無効になっているかどうか。true の場合、この共有ドライブ内のすべてのファイルについて、同様の名前のフィールドが true に設定されます。 v2 & v3
restrictions.downloadRestriction 共有ドライブの管理者が適用したダウンロードの制限。 v3 のみ

フォルダの制限

共有ドライブには、アイテム数とフォルダの深さの上限があります。また、保存容量の使用量は、個々のユーザーの個人的なマイドライブの保存容量の割り当てではなく、組織のプールされた保存容量に対して管理されます。詳しくは、Google ドライブでの共有ドライブの制限をご覧ください。

アイテム数の上限

共有ドライブに保存できるアイテム数は最大 50 万個です。これにはファイル、フォルダ、ショートカットが含まれます。

上限に達すると、共有ドライブにアイテムを追加できなくなります。ファイルの受信を再開するには、共有ドライブからアイテムを完全に削除する必要があります。ゴミ箱内のアイテムは上限にカウントされますが、完全に削除されたアイテムはカウントされません。詳しくは、ファイルとフォルダをゴミ箱に移動または削除するをご覧ください。

フォルダの階層の深さの制限

共有ドライブ内のフォルダをネストできるのは 100 レベルまでです。つまり、99 階層を超えるフォルダの下に子フォルダを保存することはできません。この制限は子フォルダにのみ適用されます。

100 階層を超えるフォルダを追加しようとすると、teamDriveHierarchyTooDeep HTTP ステータス コード レスポンスが返されます。