Microsoft 365 OneDrive for Business: Create JPG image

Microsoft 365 OneDrive for Business: Create JPG image

Microsoft 365 OneDrive for Business: JPG画像作成

This process converts a file on OneDrive into a JPG image and saves it to a data item.

Auto Step icon
Configs for this Auto Step
conf_OAuth2
C1: OAuth2 Setting *
conf_Url
C2: URL of the file to be convert to JPG image *
conf_FileName
C3: File name of the JPG file in data item *#{EL}
conf_FileWidth
C4: Width of the JPG file in data item *#{EL}
conf_FileHeight
C5: Height of the JPG file in data item *#{EL}
conf_FileData
C6: Data item to save the JPG file *
Script (click to open)

// OAuth2 config sample at [OAuth 2.0 Setting]
// - Authorization Endpoint URL: https://login.microsoftonline.com/common/oauth2/v2.0/authorize
// - Token Endpoint URL: https://login.microsoftonline.com/common/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)

// Global Variables
const GRAPH_URI = "https://graph.microsoft.com/v1.0/";

/**
  * Convert and download the file
  *   Reference)https://learn.microsoft.com/ja-jp/graph/api/driveitem-get-content-format?view=graph-rest-1.0
  */

main();
function main(){
  //// == 工程コンフィグの参照 / Config Retrieving ==
  const oauth2 = configs.get("conf_OAuth2");
  const fileUrl = retrieveFileUrl();
  const fileName = configs.get("conf_FileName");
  const fileWidth = configs.get("conf_FileWidth");
  const fileHeight = configs.get("conf_FileHeight");
  const fileDataDef = configs.getObject("conf_FileData");

  //// == ワークフローデータの参照 / Data Retrieving ==
  const files = engine.findData( configs.getObject("conf_Url") );
  if (files === null) {
    engine.setData(fileDataDef, [""]);
    return;
  }

  //// == 演算 / Calculating ==
  // ファイルURLよりファイル情報を取得 / Get file information from file URL
  const fileInfo = getFileInfoByUrl( fileUrl, oauth2 );

  // APIよりJPGファイルを取得 / Get JPG files from API
  const httpResponse = downloadJPGFileRequest(fileInfo, fileWidth, fileHeight, oauth2);

  // データ項目が空の場合、変数を初期化 / If data item is empty, initialize variable.
  let filesAttached = engine.findData( fileDataDef ); // java.util.ArrayList
  if( filesAttached === null ) {
    engine.log( "AutomatedTask FilesArray {C4} (empty)" );
    filesAttached = new java.util.ArrayList();
  }else{
    engine.log( "AutomatedTask FilesArray {C4}: " + filesAttached.size() + " files" );
  }

  // データ項目にレスポンスデータをセット / Set response data to data items
  const fileTmp = new com.questetra.bpms.core.event.scripttask.NewQfile(
                   fileName, httpResponse.getContentType(), httpResponse.getResponse()
                  );
  filesAttached.add( fileTmp );

  engine.setData( fileDataDef , filesAttached );
}

/**
  * Read the file URL value from the config
  * @return {String} config value
  */
function retrieveFileUrl() {
  const fileUrlDef = configs.getObject( "conf_Url" );
  let fileUrl;
  if ( fileUrlDef === null ) {
    fileUrl = configs.get( "conf_Url" )
  }else{
    fileUrl = engine.findData( fileUrlDef );
  }
  if ( fileUrl === "" || fileUrl === null){
    throw "File URL is empty."
  }
  return fileUrl;
}

/**
  * Get the file information (drive ID and file ID) from the folder URL,
  * Return an object (if the URL is empty, an error occurs)
  * @param {String} fileUrl  Folder URL
  * @param {String} oauth2  OAuth2 Settings
  * @return {Object} fileInfo  File information {driveId, fileId}
  */
function getFileInfoByUrl( fileUrl, oauth2 ) {
  let fileInfo;
  if ( fileUrl !== "" && fileUrl !== null ) {
    // Destructuring assignment
    const {
      id,
      parentReference: {
        driveId
      }
    } = getObjBySharingUrl( fileUrl, oauth2 );
    fileInfo = {driveId: `drives/${driveId}`, fileId: id};
  }
  return fileInfo;
}

/**
  * Gets metadata for OneDrive drive items (files, folders) and returns a JSON object.
  * API Specifications:https://docs.microsoft.com/ja-jp/onedrive/developer/rest-api/api/shares_get?view=odsp-graph-online
  * @param {String} sharingUrl  Shared URL for the file
  * @param {String} oauth2  OAuth2 Settings
  * @return {Object} responseObj  Drive item metadata JSON object
  */
function getObjBySharingUrl( sharingUrl, oauth2 ) {
  if (sharingUrl === "" || sharingUrl === null) {
    throw `Sharing URL is empty.`;
  }

  // encoding sharing URL
  const encodedSharingUrl = encodeSharingUrl(sharingUrl);

  // API Request
  const response = httpClient.begin()
    .authSetting( oauth2 )
    .get( `${GRAPH_URI}shares/${encodedSharingUrl}/driveItem` );

  const responseStr = logAndJudgeError(response, "GET");

  return JSON.parse( responseStr );
}

/**
  * Encode the shared URL into unpadded base64url format
  * @param {String} sharingUrl  Share URL
  * @return {String} encodedSharingUrl  Encoded Share URL
  */
function encodeSharingUrl( sharingUrl ) {
  let encodedSharingUrl = base64.encodeToUrlSafeString( sharingUrl );
  while ( encodedSharingUrl.slice(-1) === '=' ) {
    encodedSharingUrl = encodedSharingUrl.slice(0,-1);
  }
  return `u!${encodedSharingUrl}`;
}

/**
  * Gets the specified file in JPG file format based on FileInfo
  * @param {String} fileInfo  Download source item information {driveId, id}
  * @param {Numeric} fileWidth  File Width
  * @param {Numeric} fileHeight  File Height
  * @param {String} oauth2  OAuth2 Authentication Settings
  * @return {HttpResponseWrapper} response  Response
  */
function downloadJPGFileRequest(fileInfo, fileWidth, fileHeight, oauth2) {
  // Request PATH
  const apiUri = `${GRAPH_URI}${fileInfo.driveId}/items/${fileInfo.fileId}/content?format=jpg&width=${fileWidth}&height=${fileHeight}`;

  // API Request
  const response = httpClient.begin() // HttpRequestWrapper
    .authSetting( oauth2 ) // Request HEADER (OAuth2 Token)
    .get( apiUri ); // HttpResponseWrapper
  const httpStatus = response.getStatusCode();
  if (httpStatus >= 300) {
    const accessLog = `---GET request--- ${httpStatus}\n${response.getResponseAsString()}\n${fileInfo.driveId}\n${fileInfo.fileId}\n${apiUri}`;
    engine.log(accessLog);
    throw `Failed to download for PDF File. status: ${httpStatus}`;
  }
  return response;
}

/**
  * Outputs logs and throws an error when an error occurs
  * @param {HttpResponseWrapper} response  Response to a request
  * @param {String} requestType In what format did you make the request? ("GET" or "POST" or "PATCH")
  * @return {String} responseStr Response String
  */
function logAndJudgeError(response, requestType){
  const responseStr = response.getResponseAsString();
  const status = response.getStatusCode();
  if(status >= 300){
    const accessLog = `---${requestType} request--- ${status}\n${responseStr}\n`;
    engine.log(accessLog);
    throw `Failed in ${requestType} request. status: ${status}`;
  }
  return responseStr;
}

Download

warning Freely modifiable JavaScript (ECMAScript) code. No warranty whatsoever.
(Installation of add-on automated processes is only available in the Professional edition)

Notes

Capture

See also

Scroll to Top

Discover more from Questetra Support

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

Continue reading