这是我的理解:
- You want to give the permission to a file and folder using multiple email addresses.
- 例如,您想使用类似的数组
userValues = ["[email protected] /cdn-cgi/l/email-protection", "user2"@abc.com", "[email protected] /cdn-cgi/l/email-protection"];
- 您希望使用 Google Apps 脚本来实现此目的。
问题和解决方法:
在现阶段,Drive.Permissions.insert()
可以为一封电子邮件创建权限。不幸的是,无法通过一次调用使用多个电子邮件来创建权限Drive.Permissions.insert()
。如果你想使用数组和Drive.Permissions.insert
,现阶段需要运行Drive.Permissions.insert
在 for 循环中。
作为解决方法,在这里,我想建议使用批量请求。使用批量请求时,一次API调用可以完成100个API调用,并且可以与异步进程一起运行。
模式一:
在此模式中,批处理请求使用 UrlFetchApp 运行。
示例脚本:
在运行脚本之前,请设置文件 ID 和电子邮件地址。如果要给文件夹添加权限,请将文件夹ID设置为###
of const fileId = "###";
.
function myFunction() {
const fileId = "###"; // Please set the file ID.
const userValues = ["[email protected] /cdn-cgi/l/email-protection", "user2"@abc.com", "[email protected] /cdn-cgi/l/email-protection"]; // Please set the email addresses.
const resources = userValues.map(e => ({role: "writer", type: "user", emailAddress: e}));
const boundary = "xxxxxxxxxx";
const payload = resources.reduce((s, e, i) => {
s += "Content-Type: application/http\r\n" +
"Content-ID: " + i + "\r\n\r\n" +
"POST https://www.googleapis.com/drive/v3/files/" + fileId + "/permissions?sendNotificationEmails=false" + "\r\n" +
"Content-Type: application/json; charset=utf-8\r\n\r\n" +
JSON.stringify(e) + "\r\n" +
"--" + boundary + "\r\n";
return s;
}, "--" + boundary + "\r\n");
const params = {
method: "post",
contentType: "multipart/mixed; boundary=" + boundary,
payload: payload,
headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
};
const res = UrlFetchApp.fetch("https://www.googleapis.com/batch", params);
console.log(res.getContentText())
}
模式2:
在此模式中,使用用于批量请求的 Google Apps 脚本库。
示例脚本:
在运行脚本之前,请设置文件 ID 和电子邮件地址,并且请安装GAS库。 https://github.com/tanaikech/BatchRequest#how-to-install
function myFunction() {
const fileId = "###"; // Please set the file ID.
const userValues = ["[email protected] /cdn-cgi/l/email-protection", "user2"@abc.com", "[email protected] /cdn-cgi/l/email-protection"]; // Please set the email addresses.
const reqs = userValues.map(e => ({
method: "POST",
endpoint: "https://www.googleapis.com/drive/v3/files/" + fileId + "/permissions?sendNotificationEmails=false",
requestBody: {role: "writer", type: "user", emailAddress: e},
}));
const requests = {batchPath: "batch/drive/v3", requests: reqs};
const res = BatchRequest.Do(requests);
console.log(res.getContentText())
}
Note:
- 请在脚本编辑器中启用 V8。
- 在上面的脚本中,作为示例脚本,最大请求数为100。如果您想请求超过100,请修改上面的脚本。请小心这一点。
参考:
- 批量请求 https://developers.google.com/drive/api/v3/batch
- 权限:创建 https://developers.google.com/drive/api/v3/reference/permissions/create
- GAS库的BatchRequest https://github.com/tanaikech/BatchRequest