- 您想授予使用多个电子邮件地址的文件和文件夹的权限。
- 例如,您想使用像
userValues = ["user1@abc.com", "user2"@abc.com", "user3@abc.com"]; 这样的数组
- 您希望使用 Google Apps 脚本实现此目的。
我可以像上面那样理解。如果我的理解是正确的,这个答案怎么样?请认为这只是几个可能的答案之一。
问题和解决方法:
在当前阶段,Drive.Permissions.insert() 可以为一封电子邮件创建权限。遗憾的是,无法通过一通Drive.Permissions.insert() 来创建多个电子邮件的权限。如果要使用数组和Drive.Permissions.insert,在当前阶段,需要在for循环中运行Drive.Permissions.insert。
作为一种解决方法,在这里,我想建议使用批处理请求。使用批量请求时,一个API调用可以完成100个API调用,并且可以与异步进程一起运行。
模式一:
在此模式中,批处理请求使用 UrlFetchApp 运行。
示例脚本:
在运行脚本之前,请设置文件 ID 和电子邮件地址。如果要给文件夹添加权限,请将文件夹ID设置为const fileId = "###";的###。
function myFunction() {
const fileId = "###"; // Please set the file ID.
const userValues = ["user1@abc.com", "user2"@abc.com", "user3@abc.com"]; // 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 和电子邮件地址,以及please install the GAS library.
function myFunction() {
const fileId = "###"; // Please set the file ID.
const userValues = ["user1@abc.com", "user2"@abc.com", "user3@abc.com"]; // 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())
}
注意:
- 请在脚本编辑器中启用 V8。
- 在上面的脚本中,作为一个示例脚本,请求的最大数量是100。如果你想请求超过100,请修改上面的脚本。请注意这一点。
参考资料: