Box: Copy File
Copies a file and saves it in a specified folder.
Configs
  • C1: OAuth2 Setting *
  • C2: Source File ID
  • C3: Folder ID to store (The same folder of Source File if blank)
  • C4: New File Name (named automatically if blank)#{EL}
  • C5: Data item to save New File ID
  • C6: Data item to save New File Viewing URL
Script (click to open)

main();
function main(){
  //// == Config Retrieving / 工程コンフィグの参照 ==
  const oauth2 = configs.get( "conf_OAuth2" ) ;
  const fileId = decideFileId();

  if(fileId === "" || fileId === null){
    throw "No Source File ID";
  }

  const newFileName = configs.get( "conf_NewFileName" );
  checkNewFileName(newFileName);

  let folderId = decideFolderId();

  if(folderId === "" || folderId === null){
    //空の場合は"元ファイルが配置されているフォルダ"とする when folder id isn't set, set "same folder"
    folderId = getFolderID(oauth2, fileId);
  }

  const saveIdData = configs.getObject( "conf_DataForId" );
  const saveUrlData = configs.getObject( "conf_DataForUrl" );

  const newFileID = copyFile(oauth2, folderId, fileId, newFileName);

  if (saveIdData !== null) {
    engine.setData(saveIdData, newFileID);
  }
  if (saveUrlData !== null) {
    engine.setData(saveUrlData, `https://app.box.com/file/${newFileID}`);
  }
}

/**
  * ファイルのIDをconfigから読み出して出力する。
  * @return {String}  ファイルの ID
  */
function decideFileId(){
  let fileId = "";
  const fileIdDef = configs.getObject("conf_SourceFileId");
  if(fileIdDef === null){
    fileId = configs.get( "conf_SourceFileId");
  }else{
    fileId = engine.findData(fileIdDef);
  }
  return fileId;
}


/**
  * 新しいファイルのファイル名をチェックする。(サポートされていない文字が使われていないか)
  */
function checkNewFileName(newFileName){

//ファイル名が255文字を超えていないか
  if(newFileName.length > 255){
    throw "File Name should be less than 256 characters";
  }

//ファイル名に「/」や「\」が含まれていないか
  const reg = new RegExp('[/\\\\]');
  if(newFileName.search(reg) !== -1) {
    throw "Invalid File Name";
  }

//ファイル名の先頭と末尾に半角スペースが使われていないか
  if(newFileName.slice(0,1) === " " || newFileName.slice(-1) === " ") {
    throw "Invalid File Name";
  }

//ファイル名が「.」や「..」ではないか
  if(newFileName === "." || newFileName === ".."){
    throw "Invalid File Name";
  }
}

/**
  * フォルダのIDをconfigから読み出して出力する。
  * @return {String}  フォルダの ID
  */
function decideFolderId(){
  let folderId = "";
  const folderIdDef = configs.getObject("conf_FolderId");
  if(folderIdDef === null){
    folderId = configs.get( "conf_FolderId");
  }else{
    folderId = engine.findData(folderIdDef);
  }
  return folderId;
}

/**
  * get parent folderID of file
  * ファイルが配置されているフォルダのIDを取得する。
  * @return {String}  フォルダの ID
  */
function getFolderID(oauth2, fileId){

  const url = `https://api.box.com/2.0/files/${fileId}`;

  const response = httpClient.begin()
    .authSetting(oauth2)
    .queryParam("fields", "parent")
    .get(url);

  const status = response.getStatusCode();
  const responseTxt = response.getResponseAsString();

  engine.log(`status: ${status}`);

  if(status !== 200){
    engine.log(responseTxt);
    throw `Failed to get parent folder and Failed to copy.`;
  }
  const jsonRes = JSON.parse(responseTxt);
  return jsonRes.parent.id;
}

/**
  * Box 上のファイルを指定フォルダに指定ファイル名でコピーする。
  * @return {String}  コピーしたファイルの ID
  */
//copy file on Box  @return {String}  ファイルの ID
function copyFile(oauth2, folderId, fileId, newFileName) {
  let jsonReq = {};
  jsonReq["parent"] = {"id": folderId };

  if ( newFileName !== "" && newFileName !== null ){ 
    jsonReq["name"] = newFileName;
  }  
  
  const url = `https://api.box.com/2.0/files/${fileId}/copy`;

  const response = httpClient.begin()
    .authSetting(oauth2)
    .body(JSON.stringify(jsonReq), "application/json; charset=UTF-8")
    .post(url);

  const status = response.getStatusCode();
  const responseTxt = response.getResponseAsString();
  
  engine.log(`status: ${status}`);

  if (status !== 201) {
    engine.log(responseTxt);
    throw "Failed to copy.";
  }
  const jsonRes = JSON.parse(responseTxt);
  return jsonRes.id;
}

Download

2021-03-22 (C) Questetra, Inc. (MIT License)
https://support.questetra.com/addons/box-file-copy/
The Addon-import feature is available with Professional or Enterprise edition.

Notes

  1. The folder ID is contained in the URL: https://{sub-domain}.app.box.com/folder/(Folder ID)
  2. If there are file name or folder name conflicts it will result in an error.
  3. Box refresh tokens have an expiration date. Use regularly to ensure that it does not expire. (Box: Token & URL Expiration)

Capture

See also

1 thought on “Box: Copy File”

  1. Pingback: Utilising Box From Your Workflow – Questetra Support

Comments are closed.

%d bloggers like this: