Microsoft 365 OneDrive for Business: Delete Sharing Link

Microsoft 365 OneDrive for Business: Delete Sharing Link

Microsoft 365 OneDrive for Business: 共有リンク削除

This item deletes the specified Sharing Link from the file/folder in OneDrive.

Basic Configs
Step Name
Note
Auto Step icon
Configs for this Auto Step
conf_OAuth2
C1: OAuth2 Setting *
conf_DriveItemUrl
C2: File / Folder URL from which to delete the Sharing Link *
conf_SharingLinkId
C3: Sharing Link ID to delete *

Notes

  • This Auto Step is for OneDrive for Business of Microsoft 365
    • It does not work for OneDrive personal
  • To get the URL of a file/folder on OneDrive, open the Details window of the file/folder by clicking the Information icon, proceed to “More details”, and click the icon next to “Path”

Capture

See Also

Script (click to open)
  • An XML file that contains the code below is available to download
    • onedrive-file-link-delete.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

// OAuth2 config sample at [OAuth 2.0 Setting]
// - Authorization Endpoint URL: https://login.microsoftonline.com/{your-tenant-id}/oauth2/v2.0/authorize
// - Token Endpoint URL: https://login.microsoftonline.com/{your-tenant-id}/oauth2/v2.0/token
// - Scope: https://graph.microsoft.com/Files.ReadWrite.All offline_access
// - Consumer Key: (Get by Microsoft Azure Active Directory)
// - Consumer Secret: (Get by Microsoft Azure Active Directory)

const GRAPH_URI = 'https://graph.microsoft.com/v1.0/';

function main() {
    //// == 工程コンフィグの参照 / Config Retrieving ==
    const oauth2 = configs.getObject('conf_OAuth2');
    const driveItemUrl = retrieveDriveItemUrl();
    const sharingLinkId = retrieveSharingLinkId();

    //// == 演算 / Calculating ==
    const driveItemInfo = getDriveItemInfoByUrlAndCheckSharingLink(oauth2, driveItemUrl, sharingLinkId);
    deleteLink(oauth2, driveItemInfo, sharingLinkId);
}

/**
  * config からファイル / フォルダ URL の値を読み出す
  * URL が設定されていない場合はエラー
  * @returns {String} fileUrl ファイル URL
  */
function retrieveDriveItemUrl() {
    const driveItemUrlDef = configs.getObject('conf_DriveItemUrl');
    let driveItemUrl = '';
    if (driveItemUrlDef === null) {
        driveItemUrl = configs.get('conf_DriveItemUrl');
    } else {
        driveItemUrl = engine.findData(driveItemUrlDef);
    }
    if (driveItemUrl === null || driveItemUrl === '') {
        throw 'File / Folder URL is blank.';
    }
    return driveItemUrl;
}

/**
  * config から共有リンクの ID の値を読み出す
  * ID が設定されていない場合はエラー
  * @returns {String} sharingLinkId 共有リンクの ID
  */
function retrieveSharingLinkId() {
    const sharingLinkId = engine.findData(configs.getObject('conf_SharingLinkId'));
    if (sharingLinkId === null) {
        throw 'Sharing Link ID is blank.';
    }
    return sharingLinkId;
}

/**
  * OneDrive のファイル / フォルダのメタデータを取得し、JSONオブジェクトを返す
  * 指定した ID の共有リンクがあるかどうかを確認し、ない場合はエラー
  * APIの仕様: https://docs.microsoft.com/ja-jp/onedrive/developer/rest-api/api/shares_get?view=odsp-graph-online
  * @param {AuthSettingWrapper} oauth2  OAuth2 設定情報
  * @param {String} sharingUrl  ファイル / フォルダの共有 URL
  * @param {String} sharingLinkId  存在を確認する共有リンクの ID
  * @returns {Object} ファイル / フォルダ情報 {driveId, id}
  */
function getDriveItemInfoByUrlAndCheckSharingLink(oauth2, sharingUrl, sharingLinkId) {
    // encoding sharing URL
    const encodedSharingUrl = encodeSharingUrl(sharingUrl);

    // preparing for API Request
    const response = httpClient.begin()
        .authSetting(oauth2)
        .queryParam('select', 'id,parentReference')
        .queryParam('expand', 'permissions(select=id,link)')
        .get(`${GRAPH_URI}shares/${encodedSharingUrl}/driveItem`);
    const status = response.getStatusCode();
    const responseStr = response.getResponseAsString();
    if (status !== 200) {
        engine.log(responseStr);
        throw `Failed to get drive item. status: ${status}`;
    }
    const {
        id,
        parentReference: {
            driveId
        },
        permissions
    } = JSON.parse(responseStr);
    if (!hasSharingLink(permissions, sharingLinkId)) {
        throw 'The specified sharing link not found in the file/folder.';
    }
    return {driveId, id};
}

/**
  * パーミションの一覧に指定した ID の共有リンクがあるかどうか
  * @param {Array} permissions  パーミッションの一覧
  * @param {String} sharingLinkId  存在を確認する共有リンクの ID
  * @returns {boolean} 一覧に指定した ID の共有リンクがあるかどうか
  */
function hasSharingLink(permissions, sharingLinkId) {
    return permissions.some(permission => {
        if (permission.link !== undefined && permission.id === sharingLinkId) {
            return true;
        }
    });
}

/**
  * 共有URLを unpadded base64url 形式にエンコードする
  * @param {String} sharingUrl  共有URL
  * @returns {String} encodedSharingUrl  エンコードされた共有URL
  */
function encodeSharingUrl(sharingUrl) {
    let encodedSharingUrl = base64.encodeToUrlSafeString(sharingUrl);
    while (encodedSharingUrl.slice(-1) === '=') {
        encodedSharingUrl = encodedSharingUrl.slice(0, -1);
    }
    return `u!${encodedSharingUrl}`;
}

/**
  * OneDrive のファイル / フォルダの共有リンクを削除する
  * @param {AuthSettingWrapper} oauth2  OAuth2 設定情報
  * @param {Object} driveItemInfo ファイル / フォルダ情報 {driveId, id}
  * @param {String} driveItemInfo.driveId  ドライブ ID
  * @param {String} driveItemInfo.id  ファイル / フォルダ ID
  * @param {String} sharingLinkId  削除する共有リンクの ID
  */
function deleteLink(oauth2, {driveId, id}, sharingLinkId) {
    const response = httpClient.begin()
        .authSetting(oauth2)
        .delete(`${GRAPH_URI}drives/${driveId}/items/${id}/permissions/${encodeURIComponent(sharingLinkId)}`);
    const status = response.getStatusCode();
    const responseStr = response.getResponseAsString();
    // 204: No Content (successfully deleted, already deleted, or never existed)
    if (status !== 204) {
        engine.log(responseStr);
        throw `Failed to delete sharing link. status: ${status}`;
    }
}

    
Scroll to Top

Discover more from Questetra Support

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

Continue reading