Google Drive: Create Shared Link
Creates a shared link for the specified file or folder on Google Drive. An error occurs when the file/folder is already shared with anyone or within the domain.
Configs: Common
  • Step Name
  • Note
Configs
  • C1: User connects to Google Drive (must be App Administrator) *
  • C2: File / Folder ID to share *
  • C3: Shared range *
  • C4: Role (Editable or not) *
  • C5: Domain to share (required if the shared range is domain)
  • C6: Enable discovery through search within the domain
  • C7: Data Item that will save URL of shared File / Folder

Notes

  • Users in C1 need to have a configured connection with Google Drive in [Account Settings] > [Google Connectivity]
    • Google Workspace Connectivity ([System Settings] > [Google Connectivity]) must be enabled on the workflow platform ([System Administrator Authorization] required )
  • You can create shared links of files and folders created by [Google Drive: File Upload], [Google Drive: Create Folder], and [Google Sheets: Create File].

Capture

See also

Script (click to open)
  • An XML file that contains the code below is available to download


main();

function main() {
  const quser = getQuser();
  const fileId = getFileId();
  const sharedRange = configs.get("conf_SharedRange");
  const role = configs.get("conf_Role");
  const domain = configs.get("conf_Domain");
  if (sharedRange === "domain" && domain === "") {
    throw "Domain to share isn't set.";
  }
  const allowFileDiscovery = configs.getObject("conf_AllowFileDiscovery");
  const urlDataDef = configs.getObject("conf_SharedUrlItem");

  checkIfAlreadyShared(quser, fileId);
  createPermission(quser, fileId, sharedRange, role, domain, allowFileDiscovery);

  if (urlDataDef !== null) {
    const sharedUrl = getWebViewLink(quser, fileId);
    engine.setData(urlDataDef, sharedUrl);
  }
}

/**
 * 実行ユーザを取得する
 * @return {QuserView} 実行ユーザ
 */
function getQuser() {
    const quser = configs.getObject("conf_UserID");
    if (quser === null) {
        throw "User not found";
    }
    engine.log(`User Name: ${quser.getName()}`);
    return quser;
}

/**
 * データ項目からファイル / フォルダの ID を取得する
 * @return {String}  ファイル / フォルダの ID
 */
function getFileId() {
    const fileId = engine.findData(configs.getObject("conf_FileIdsItem"));
    if (fileId === null || fileId === "") {
        throw "File / Folder ID isn't set.";
    }
    return fileId;
}

/**
  * Google Drive API で共有設定の一覧を取得し、
  * anyone / domain の共有設定がすでにある場合はエラー
  * @param {QuserView} quser  Google Drive に接続するユーザ
  * @param {String} fileId  ファイル / フォルダの ID
  */
function checkIfAlreadyShared(quser, fileId) {
  const url = `https://www.googleapis.com/drive/v3/files/${encodeURIComponent(fileId)}/permissions`;
    const response = httpClient.begin()
        .googleOAuth2(quser, "Drive")
        .queryParam("fields", "permissions/type")
        .queryParam("supportsAllDrives", "true")
        .get(url);
    const status = response.getStatusCode();
    const responseStr = response.getResponseAsString();
    if (status >= 300) {
        engine.log(responseStr)
        throw `Failed to get permission list. File:${fileId}, Status:${status}`;
    }
    const {permissions} = JSON.parse(responseStr);

    const alreadyShared = permissions
        .some(permission => permission.type === "anyone" || permission.type === "domain");
    if (alreadyShared) {
        throw `The item (ID: ${fileId}) is already shared.`;
    }
}

/**
  * Google Drive API で共有設定をする
  * create permission on Google Drive
  * @param {QuserView} quser  Google Drive に接続するユーザ
  * @param {String} fileId  ファイル / フォルダの ID
  * @param {String} type 共有範囲
  * @param {String} role ロール
  * @param {String} domain  共有先ドメイン
  * @param {String} allowFileDiscovery  検索可能にするかどうか
  * @return {String} 共有リンク
  */
function createPermission(quser, fileId, type, role, domain, allowFileDiscovery) {
  const json = {role, type};
  if (type === "domain") {
    json["domain"] = domain;
    json["allowFileDiscovery"] = allowFileDiscovery;
  }
  const url = `https://www.googleapis.com/drive/v3/files/${encodeURIComponent(fileId)}/permissions`;
  const responsePermission = httpClient.begin()
    .googleOAuth2(quser, "Drive")
    .queryParam("supportsAllDrives", "true")
    .body(JSON.stringify(json), "application/json; charset=UTF-8")
    .post(url);
  const status = responsePermission.getStatusCode();
  if (status >= 300) {
    engine.log(responsePermission.getResponseAsString())
    throw `Failed to create permission. File:${fileId}, Status:${status}`;
  }
}

/**
  * Google Drive API でファイル / フォルダの表示 URL を取得する
  * @param {QuserView} quser  Google Drive に接続するユーザ
  * @param {String} fileId  ファイル / フォルダの ID
  * @return {String} 表示 URL
  */
function getWebViewLink(quser, fileId) {
  const url = `https://www.googleapis.com/drive/v3/files/${encodeURIComponent(fileId)}`;
  const responseGet = httpClient.begin()
    .googleOAuth2(quser, "Drive")
    .queryParam("fields", "webViewLink")
    .queryParam("supportsAllDrives", "true")
    .get(url);
  const getStatus = responseGet.getStatusCode();
  if (getStatus >= 300) {
    engine.log(responseGet.getResponseAsString())
    throw `Failed to get item info. File:${fileId}, Status:${getStatus}`;
  }
  const resJson = JSON.parse(responseGet.getResponseAsString());
  return resJson.webViewLink;
}

1 thought on “Google Drive: Create Shared Link”

  1. Pingback: Utilizing Google Drive from Workflow – Sending files to people outside the company – Questetra Support

Comments are closed.

%d bloggers like this: