Google Drive: Create Shared Link

Google Drive: Create Shared Link

Google ドライブ: 共有リンク作成

This item 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.

Auto Step icon
Basic Configs
Step Name
Note
Configs for this Auto Step
conf_UserID
C1: User connects to Google Drive (must be App Administrator) *
conf_FileIdsItem
C2: File / Folder ID to share *
conf_SharedRange
C3: Shared range *
conf_Role
C4: Role (Editable or not) *
conf_Domain
C5: Domain to share (required if the shared range is domain)
conf_AllowFileDiscovery
C6: Enable discovery through search within the domain
conf_SharedUrlItem
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
    • google-drive-permission-create.xml (C) Questetra, Inc. (MIT License)
    • If you are using Professional, you can modify the contents of this file and use it as your own add-on auto step


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.

Scroll to Top

Discover more from Questetra Support

Subscribe now to keep reading and get access to the full archive.

Continue reading