Quản lý bộ nhớ dùng chung

Hướng dẫn này chứa các tác vụ liên quan đến việc quản lý bộ nhớ dùng chung, chẳng hạn như tạo bộ nhớ dùng chung và quản lý thành viên cũng như quyền bằng cách sử dụng API Google Drive.

Nếu muốn chỉ định các trường cần trả về trong phản hồi, bạn có thể đặt fields tham số hệ thống bằng bất kỳ phương thức nào của tài nguyên drives. Nếu bạn không chỉ định tham số fields, máy chủ sẽ trả về một tập hợp các trường mặc định dành riêng cho phương thức đó. Ví dụ: phương thức list chỉ trả về các trường kind, id, và name cho mỗi bộ nhớ dùng chung. Để biết thêm thông tin, hãy xem bài viết Trả về các trường cụ thể.

Để tìm hiểu thêm về giới hạn thư mục trong bộ nhớ dùng chung, hãy xem bài viết Giới hạn thư mục trong bộ nhớ dùng chung.

Tạo bộ nhớ dùng chung

Để tạo bộ nhớ dùng chung, hãy sử dụng create phương thức trên tài nguyên drives với requestId tham số.

Tham số requestId xác định nỗ lực logic để tạo bộ nhớ dùng chung một cách bất biến. Nếu yêu cầu hết thời gian chờ hoặc trả về lỗi không xác định ở phần phụ trợ, thì bạn có thể lặp lại cùng một yêu cầu và sẽ không tạo bản sao. requestId và nội dung của yêu cầu phải giữ nguyên.

Đoạn mã mẫu sau đây cho biết cách tạo bộ nhớ dùng chung:

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;
        }
    }
}

Các lệnh gọi đến phương thức create là bất biến.

Nếu bộ nhớ dùng chung được tạo thành công trong một yêu cầu trước đó hoặc do thử lại, thì phương thức này sẽ trả về một thực thể của tài nguyên drives. Đôi khi (chẳng hạn như sau một thời gian dài hoặc nếu nội dung của yêu cầu đã thay đổi), lỗi 409 có thể được trả về cho biết requestId phải bị loại bỏ.

Lấy bộ nhớ dùng chung

Để lấy siêu dữ liệu cho một bộ nhớ dùng chung, hãy sử dụng phương thức get trên tài nguyên drives với tham số đường dẫn driveId. Nếu bạn không biết mã bộ nhớ dùng chung, bạn có thể liệt kê tất cả bộ nhớ dùng chung bằng phương thức list.

Phương thức get trả về một bộ nhớ dùng chung dưới dạng thực thể của tài nguyên drives.

Để đưa ra yêu cầu với tư cách là quản trị viên miền, hãy đặt tham số truy vấn useDomainAdminAccess thành true. Để biết thêm thông tin, hãy xem bài viết Quản lý bộ nhớ dùng chung với tư cách là quản trị viên miền.

Liệt kê bộ nhớ dùng chung

Để liệt kê bộ nhớ dùng chung của người dùng, hãy sử dụng list phương thức trên drives tài nguyên. Phương thức này trả về danh sách bộ nhớ dùng chung.

Truyền các tham số truy vấn sau để tuỳ chỉnh việc phân trang hoặc lọc bộ nhớ dùng chung:

  • pageSize: Số lượng tối đa bộ nhớ dùng chung cần trả về trên mỗi trang.

  • pageToken: Mã thông báo trang nhận được từ một lệnh gọi danh sách trước đó. Cung cấp mã thông báo này để truy xuất trang tiếp theo.

  • q: Chuỗi truy vấn để tìm kiếm bộ nhớ dùng chung. Để biết thêm thông tin, hãy xem bài viết Tìm kiếm bộ nhớ dùng chung.

  • useDomainAdminAccess: Đặt thành true để đưa ra yêu cầu với tư cách là quản trị viên miền nhằm trả về tất cả bộ nhớ dùng chung của miền mà người yêu cầu là quản trị viên. Để biết thêm thông tin, hãy xem bài viết Quản lý bộ nhớ dùng chung với tư cách là quản trị viên miền.

Cập nhật bộ nhớ dùng chung

Để cập nhật siêu dữ liệu cho một bộ nhớ dùng chung, hãy sử dụng phương thức update trên tài nguyên drives với tham số đường dẫn driveId.

Phương thức này trả về một bộ nhớ dùng chung dưới dạng thực thể của tài nguyên drives.

Để đưa ra yêu cầu với tư cách là quản trị viên miền, hãy đặt tham số truy vấn useDomainAdminAccess thành true. Để biết thêm thông tin, hãy xem bài viết Quản lý bộ nhớ dùng chung với tư cách là quản trị viên miền.

Ẩn và hiện bộ nhớ dùng chung

Để ẩn một bộ nhớ dùng chung khỏi chế độ xem mặc định, hãy sử dụng phương thức hide trên tài nguyên drives với tham số driveId.

Khi một bộ nhớ dùng chung bị ẩn, Drive sẽ đánh dấu tài nguyên bộ nhớ dùng chung là hidden=true. Bộ nhớ dùng chung bị ẩn không xuất hiện trong giao diện người dùng Drive hoặc trong danh sách các tệp được trả về.

Để khôi phục bộ nhớ dùng chung về chế độ xem mặc định, hãy sử dụng phương thức unhide trên tài nguyên drives với tham số driveId.

Cả hai phương thức đều trả về một bộ nhớ dùng chung dưới dạng thực thể của tài nguyên drives.

Xoá bộ nhớ dùng chung

Để xoá vĩnh viễn một bộ nhớ dùng chung, hãy sử dụng phương thức delete trên tài nguyên drives với tham số driveId.

Trước khi xoá bộ nhớ dùng chung, bạn phải chuyển tất cả nội dung trong bộ nhớ dùng chung đó vào thùng rác hoặc xoá. Người dùng cũng phải có role=organizer trên thư mục bộ nhớ dùng chung. Để biết thêm thông tin, hãy xem bài viết Chuyển tệp và thư mục vào thùng rác hoặc xoá tệp và thư mục.

Truyền các tham số truy vấn sau để lọc bộ nhớ dùng chung:

  • useDomainAdminAccess: Đặt thành true để đưa ra yêu cầu với tư cách là quản trị viên miền nhằm trả về tất cả bộ nhớ dùng chung của miền mà người yêu cầu là quản trị viên. Để biết thêm thông tin, hãy xem bài viết Quản lý bộ nhớ dùng chung với tư cách là quản trị viên miền.

  • allowItemDeletion: Đặt thành true để xoá các mục trong bộ nhớ dùng chung. Chỉ được hỗ trợ khi useDomainAdminAccess cũng được đặt thành true.

Thêm hoặc xoá thành viên của bộ nhớ dùng chung

Thêm hoặc xoá thành viên của bộ nhớ dùng chung bằng cách sử dụng tài nguyên permissions.

Để thêm thành viên, hãy tạo quyền trên bộ nhớ dùng chung. Bạn cũng có thể sử dụng các phương thức cấp quyền trên từng tệp trong bộ nhớ dùng chung để cấp thêm đặc quyền cho thành viên hoặc cho phép người không phải là thành viên cộng tác trên các mục cụ thể.

Để biết thêm thông tin và mã mẫu, hãy xem bài viết Chia sẻ tệp, thư mục và bộ nhớ dùng chung.

Quản lý bộ nhớ dùng chung với tư cách là quản trị viên miền

Áp dụng tham số useDomainAdminAccess với tài nguyên drivespermissions để quản lý bộ nhớ dùng chung trong một tổ chức.

Người dùng gọi các phương thức này bằng useDomainAdminAccess=true phải có đặc quyền quản trị viên Drive and Docs . Quản trị viên có thể tìm kiếm bộ nhớ dùng chung hoặc cập nhật quyền cho bộ nhớ dùng chung thuộc sở hữu của tổ chức, bất kể quản trị viên có phải là thành viên của bất kỳ bộ nhớ dùng chung nào hay không.

Khi sử dụng tài khoản dịch vụ, bạn có thể phải mạo danh quản trị viên đã xác thực bằng cách sử dụng tính năng mạo danh tài khoản dịch vụ. Xin lưu ý rằng tài khoản dịch vụ không thuộc miền Google Workspace của bạn, không giống như tài khoản người dùng. Nếu bạn chia sẻ các tài sản của Google Workspace, chẳng hạn như tài liệu hoặc sự kiện, với toàn bộ miền Google Workspace, thì các tài sản đó sẽ không được chia sẻ với tài khoản dịch vụ. Để biết thêm thông tin, hãy xem bài viết Tổng quan về tài khoản dịch vụ.

Khôi phục bộ nhớ dùng chung không có người tổ chức

Đoạn mã mẫu sau đây cho biết cách khôi phục bộ nhớ dùng chung không còn người tổ chức.

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;
        }
    }
}

Ngăn người dùng tải xuống, in hoặc sao chép tệp

Bạn có thể giới hạn cách người dùng có thể tải xuống, in và sao chép tệp trong bộ nhớ dùng chung.

Để xác định xem người dùng có thể thay đổi các quy định hạn chế tải xuống do người tổ chức áp dụng của bộ nhớ dùng chung hay không, hãy kiểm tra trường boolean capabilities.canChangeDownloadRestriction. Nếu capabilities.canChangeDownloadRestriction được đặt thành true, thì bạn có thể áp dụng các quy định hạn chế tải xuống cho bộ nhớ dùng chung. Để biết thêm thông tin, hãy xem Tìm hiểu về các tính năng của tệp.

Tài nguyên drives chứa một tập hợp các trường boolean restrictions dùng để cho biết liệu có thể thực hiện một hành động trên bộ nhớ dùng chung hay không. Các quy định hạn chế áp dụng cho bộ nhớ dùng chung hoặc các mục bên trong bộ nhớ dùng chung. Bạn có thể đặt các quy định hạn chế bằng phương thức drives.update.

Để áp dụng các quy định hạn chế tải xuống cho bộ nhớ dùng chung, người quản lý bộ nhớ dùng chung có thể đặt trường restrictions.downloadRestriction của tài nguyên drives bằng đối tượng DownloadRestriction. Việc đặt trường boolean restrictedForReaders thành true sẽ khai báo rằng cả việc tải xuống và sao chép đều bị hạn chế đối với người đọc. Việc đặt trường boolean restrictedForWriters thành true sẽ khai báo rằng cả việc tải xuống và sao chép đều bị hạn chế đối với người viết. Xin lưu ý rằng nếu trường restrictedForWriterstrue, thì việc tải xuống và sao chép cũng bị hạn chế đối với người đọc. Tương tự, việc đặt restrictedForWriters thành truerestrictedForReaders thành false tương đương với việc đặt cả restrictedForWritersrestrictedForReaders thành true.

Khả năng tương thích ngược

Khi đối tượng DownloadRestriction được giới thiệu, chức năng của trường boolean restrictions.copyRequiresWriterPermission đã được cập nhật.

Giờ đây, việc đặt restrictions.copyRequiresWriterPermission thành true sẽ cập nhật trường boolean restrictedForReaders của đối tượng DownloadRestriction thành true để khai báo rằng cả việc tải xuống và sao chép đều bị hạn chế đối với người đọc.

Việc đặt trường copyRequiresWriterPermission thành false sẽ cập nhật cả trường restrictedForWritersrestrictedForReaders thành false. Điều này có nghĩa là các chế độ cài đặt hạn chế tải xuống hoặc sao chép sẽ bị xoá đối với tất cả người dùng.

Các trường kiểm soát tính năng tải xuống, in và sao chép

Bảng sau đây liệt kê các trường tài nguyên drives ảnh hưởng đến chức năng tải xuống, in và sao chép:

Trường Mô tả Phiên bản
capabilities.canCopy Liệu người dùng hiện tại có thể sao chép tệp trong bộ nhớ dùng chung hay không. v2 và v3
capabilities.canDownload Liệu người dùng hiện tại có thể tải tệp xuống trong bộ nhớ dùng chung hay không. v2 và v3
capabilities.canChangeCopyRequiresWriterPermission Liệu người dùng hiện tại có thể thay đổi quy định hạn chế copyRequiresWriterPermission của bộ nhớ dùng chung hay không. v2 và v3
capabilities.canResetDriveRestrictions Liệu người dùng hiện tại có thể đặt lại các quy định hạn chế của bộ nhớ dùng chung về mặc định hay không. v2 và v3
capabilities.canChangeDownloadRestriction Liệu người dùng hiện tại có thể thay đổi quy định hạn chế tải xuống của bộ nhớ dùng chung hay không. chỉ v3
restrictions.copyRequiresWriterPermission Liệu các tuỳ chọn sao chép, in hoặc tải tệp xuống bên trong bộ nhớ dùng chung có bị tắt đối với người đọc và người nhận xét hay không. Khi true, trường này sẽ đặt trường có tên tương tự thành true cho bất kỳ tệp nào bên trong bộ nhớ dùng chung này. v2 và v3
restrictions.downloadRestriction Các quy định hạn chế tải xuống do người quản lý bộ nhớ dùng chung áp dụng. chỉ v3

Giới hạn thư mục

Thư mục trong bộ nhớ dùng chung có một số giới hạn về bộ nhớ. Để biết thông tin, hãy xem Giới hạn bộ nhớ dùng chung trong Google Drive.

Giới hạn mục

Bộ nhớ dùng chung của mỗi người dùng có giới hạn là 500.000 mục, bao gồm tệp, thư mục và lối tắt.

Khi đạt đến giới hạn, bộ nhớ dùng chung sẽ không thể chấp nhận các mục nữa. Để tiếp tục nhận tệp, người dùng phải xoá vĩnh viễn các mục khỏi bộ nhớ dùng chung. Xin lưu ý rằng các mục trong thùng rác được tính vào giới hạn, nhưng các mục đã xoá vĩnh viễn thì không. Để biết thêm thông tin, hãy xem bài viết Chuyển tệp và thư mục vào thùng rác hoặc xoá tệp và thư mục.

Giới hạn độ sâu thư mục

Một thư mục trong bộ nhớ dùng chung không thể chứa quá 100 cấp thư mục được lồng. Điều này có nghĩa là bạn không thể lưu trữ thư mục con trong một thư mục có độ sâu hơn 99 cấp. Giới hạn này chỉ áp dụng cho thư mục con.

Các nỗ lực thêm hơn 100 cấp thư mục sẽ trả về phản hồi mã trạng thái teamDriveHierarchyTooDeep HTTP.