0

Share File

by
Published today

Share a Google Drive file or folder with a user, group, domain or anyone with the link.

Script gdrive Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 48 minutes ago
1
//native
2

3
/**
4
 * Share File
5
 * Grant access to a file or folder by creating a permission: a user or group (by email), a whole Google Workspace domain, or anyone with the link. `owner` transfers ownership (user only, same domain for Workspace accounts).
6
 */
7
export async function main(
8
  auth: RT.Gdrive,
9
  file_id: string,
10
  type: "user" | "group" | "domain" | "anyone",
11
  role:
12
    "reader" | "commenter" | "writer" | "fileOrganizer" | "organizer" | "owner",
13
  email_address: string | undefined,
14
  domain: string | undefined,
15
  allow_file_discovery: boolean = false,
16
  send_notification_email: boolean = true,
17
  email_message: string | undefined
18
) {
19
  const url = new URL(
20
    `https://www.googleapis.com/drive/v3/files/${file_id}/permissions`
21
  )
22
  url.searchParams.append("supportsAllDrives", "true")
23
  if (role === "owner") url.searchParams.append("transferOwnership", "true")
24
  // Notification emails only apply to user and group grants.
25
  if (type === "user" || type === "group") {
26
    url.searchParams.append(
27
      "sendNotificationEmail",
28
      String(send_notification_email)
29
    )
30
    if (
31
      send_notification_email &&
32
      email_message !== undefined &&
33
      email_message !== ""
34
    )
35
      url.searchParams.append("emailMessage", email_message)
36
  }
37

38
  const body: { [key: string]: any } = { type, role }
39
  if (type === "user" || type === "group") body.emailAddress = email_address
40
  if (type === "domain") body.domain = domain
41
  if (type === "domain" || type === "anyone")
42
    body.allowFileDiscovery = allow_file_discovery
43

44
  const response = await fetch(url, {
45
    method: "POST",
46
    headers: {
47
      Authorization: `Bearer ${auth.token}`,
48
      "Content-Type": "application/json",
49
      Accept: "application/json",
50
    },
51
    body: JSON.stringify(body),
52
  })
53

54
  if (!response.ok) {
55
    throw new Error(`${response.status} ${await response.text()}`)
56
  }
57

58
  return await response.json()
59
}
60