Box: Copy File
Copy the File and save it in the specified Folder
2020-09-01 (C) Questetra, Inc. (MIT License)
Configs
  • C1: OAuth2 Config Name *
  • 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: STRING DATA for New File ID
  • C6: STRING DATA for New File Viewing URL
Script
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);

  const token  = httpClient.getOAuth2Token( oauth2 );
  let folderId = decideFolderId();

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

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


  const newFileID = copyFile(token, 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 shoule 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(token, fileId){

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

    const response = httpClient.begin()
      .bearer(token)
      .get(url);

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

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

  let jsonRes;
   try {
     jsonRes = JSON.parse(responseTxt);
   } catch(e) {
     engine.log("failed to parse as json");
     throw `Failed to get parent folder and Failed to copy. status: ${status}`;
   }

    return jsonRes.parent.id;      
}


  //copy file on Box  @return {String}  ファイルの ID
function copyFile(token, 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()
    .bearer(token)
    .body(JSON.stringify(jsonReq), "application/json; charset=UTF-8")
    .post(url);

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

 let jsonRes;
 try {
   jsonRes = JSON.parse(responseTxt);
 } catch(e) {
   engine.log("failed to parse as json");
   throw `Failed to copy. status: ${status}`;
 }



if (status !== 201) {

    if (status === 409 && jsonRes["code"] === "item_name_in_use"){
         throw `Failed to copy . status: ${status}\n A file or folder with the same name already exists.`;
            }

    throw `Failed to copy. status: ${status}`;

   }


  return jsonRes.id;
}

Download

Capture

Notes

  1. Folder ID is contained in the URL. https://{sub-domain}.app.box.com/folder/(Folder ID)
  2. If there are filename or foldername conflicts, it results in an error.
  3. The refresh token for Box has the expiration. Use regularly to ensure that it does not exceed the expiration. (60 days, as of July 2019. https://box-content.readme.io/docs/oauth-20)

%d bloggers like this: