Chặn tải xuống (chỉ cho xem trực tuyến) file ở Google Drive

📝 Bước 1: Bật Drive Advanced Service

  1. Trong Apps Script:

    • Vào Services (bên trái màn hình).
    • Tìm Drive API → Nhấn Add.
  2. Trong Google Cloud Console:


📝 Bước 2: Code mới sử dụng Advanced Drive API (v3)

function restrictDownloadInFolder() {
  const folderId = 'FOLDER_ID'; // Thay bằng ID thư mục gốc
  const rootFolder = DriveApp.getFolderById(folderId);
  let processedFiles = 0;

  function restrictFile(file) {
    try {
      const fileId = file.getId();

      // Cập nhật permission: Chặn tải xuống, in, sao chép
      const resource = {
        viewersCanCopyContent: false, // Ngăn sao chép và in
        copyRequiresWriterPermission: true
      };

      const updatedFile = Drive.Files.update(resource, fileId);
      Logger.log(`✅ Đã chặn tải xuống & sao chép: ${file.getName()}`);
      processedFiles++;
    } catch (e) {
      Logger.log(`⚠️ Lỗi với file ${file.getName()}: ${e.message}`);
    }
  }

  function processFolder(folder) {
    const files = folder.getFiles();
    while (files.hasNext()) {
      restrictFile(files.next());
    }

    const subfolders = folder.getFolders();
    while (subfolders.hasNext()) {
      processFolder(subfolders.next());
    }
  }

  processFolder(rootFolder);
  Logger.log(`🎉 Hoàn tất! Đã chặn tải xuống cho ${processedFiles} file.`);
}

📝 Giải thích mã:

  • viewersCanCopyContent: false:
    • Chặn người xem tải xuống, in và sao chép.
  • copyRequiresWriterPermission: true:
    • Chỉ cho phép người chỉnh sửa sao chép file.

🚀 Hướng dẫn chạy:

  1. Vào Apps Script → Dán code trên.
  2. Thay FOLDER_ID bằng ID thư mục.
  3. Chạy hàm restrictDownloadInFolder.
  4. Cho phép quyền truy cập khi được yêu cầu.

🛡️ Lưu ý:

  • Người Viewer sẽ không thể:
    ✅ Tải xuống
    ✅ In file
    ✅ Sao chép nội dung

  • Người Editor hoặc Owner vẫn có thể tải (nếu muốn chặn, cần hạ quyền xuống Viewer).

Post a Comment

0 Comments