1 var REST = library.REST.REST();
  2 var myData = {};
  3 var myDest;
  4 var myUnzip = false;
  5 var myReplace = false;
  6 
  7 /**
  8  * Used to increment files with the same name  test.txt becomes test 1.txt
  9  * @param theParentPath
 10  * @param theOldName
 11  * @returns {string}
 12  */
 13 function incrementName(theParentPath, theOldName) {
 14   var anExtension = theOldName.substring(
 15     theOldName.lastIndexOf("."),
 16     theOldName.length
 17   );
 18   var aFileNumber;
 19   var aNewName;
 20   if (theOldName.lastIndexOf(" ") != -1) {
 21     aNewName = theOldName.substring(0, theOldName.lastIndexOf(" "));
 22     aFileNumber = theOldName.substring(
 23       theOldName.lastIndexOf(" "),
 24       theOldName.lastIndexOf(anExtension)
 25     );
 26     if (aFileNumber == null || aFileNumber == " ") {
 27       aFileNumber = 0;
 28     } else {
 29       var aMightBeNumber = aFileNumber;
 30       aFileNumber = parseInt(aFileNumber);
 31       if (isNaN(aFileNumber)) {
 32         //aFileNumber isn't a number. add the original back to the name
 33         aNewName += aMightBeNumber;
 34         aFileNumber = 0;
 35       }
 36     }
 37   } else {
 38     aFileNumber = 0;
 39     aNewName = theOldName.substring(0, theOldName.lastIndexOf("."));
 40   }
 41   aFileNumber++;
 42   while (
 43     fileManager.isFile(
 44       theParentPath + aNewName + " " + aFileNumber + anExtension
 45     )
 46   ) {
 47     aFileNumber++;
 48   }
 49   return aNewName + " " + aFileNumber + anExtension;
 50 }
 51 
 52 function upload(theDest, theUnzip, theReplace) {
 53   try {
 54     var anUploadedFile = context.getUploadedFile();
 55     if (anUploadedFile == null) {
 56       REST.submitError(
 57         theDest,
 58         "A file was not attached to the form-data of the Body of the POST"
 59       );
 60       return;
 61     }
 62     // Create the destination directory path if it does not already exist
 63     var aPathArray = theDest.toString().split("/");
 64     var aPath = "";
 65     for (var i = 0; i < aPathArray.length; i++) {
 66       // Continue on empty paths.
 67       if (aPathArray[i] === "") {
 68         continue;
 69       }
 70       aPath += aPathArray[i] + "/";
 71 
 72       var aDoImport = !fileManager.isManagedFolderPath(aPath);
 73       var importingFolder = fileManager.folderNewByPath(aPath);
 74 
 75       //Exclude the renditions folder from import
 76       if (aDoImport && importingFolder.path.indexOf("Renditions") !== 0) {
 77         fileManager.folderImport(importingFolder, false);
 78       }
 79     }
 80     var aManagedFolder = new ManagedFolder(theDest);
 81     if (aManagedFolder == null) {
 82       REST.submitError(theDest, "Folder not found");
 83       return;
 84     }
 85     doUpload(anUploadedFile, aManagedFolder.path, theUnzip, theReplace);
 86   } catch (err) {
 87     REST.submitError(theDest, "Failed to upload: " + err.toString());
 88     return JSON.stringify(myData, null, 2);
 89   }
 90 }
 91 
 92 /**
 93  * Copies the xmp from the xmpAsset to theAsset and keeps both assets unmanaged.
 94  *
 95  * @param theAsset the destination asset.
 96  * @param theXmpAsset the asset with the source XMP.
 97  */
 98 function setXmp(theAsset, theXmpAsset) {
 99   var aSourceMeta =
100     theXmpAsset.xmp && theXmpAsset.xmp.meta ? theXmpAsset.xmp.meta : null;
101   var aDestMeta = theAsset.xmp && theAsset.xmp.meta ? theAsset.xmp.meta : null;
102 
103   if (aSourceMeta != null && aDestMeta != null) {
104     logger.info("---------- Apply source meta");
105     var aProperties = aSourceMeta.getFields();
106     for (var i = 0; i < aProperties.length; i++) {
107       var aProperty = aProperties[i];
108       var aField = aSourceMeta.getField(aProperty);
109       aDestMeta.addField(aProperty, aField);
110     }
111   } else {
112     logger.info("---------- Still o source meta");
113   }
114   theAsset.writeXmp();
115 }
116 
117 function doUpload(theUploadedFile, theDestination, theUnzip, theReplace) {
118   var anImportedFile;
119   var aDecompressedDir;
120   var anIterator;
121 
122   if (theUploadedFile.constructor === Array) {
123     for (var i = 0; i < theUploadedFile.length; i++) {
124       var aFileExtension = theUploadedFile[i].name.split(".").pop();
125       var isLoneXMP = true;
126 
127       if (aFileExtension != "xmp") {
128         // if it's not an XMP file, see if it has a matching XMP to stick to it.
129         for (var j = 0; j < theUploadedFile.length; j++) {
130           // Found a matching .XMP add to the mapping to apply it later
131           if (
132             theUploadedFile[j].name ==
133             theUploadedFile[i].name.split(".")[0] + ".xmp"
134           ) {
135             setXmp(theUploadedFile[i], theUploadedFile[j]);
136             break;
137           }
138         }
139       } else {
140         // If it is an XMP file, see if it's a lone XMP (no matching asset), if so, upload like a normal data asset
141         for (var j = 0; j < theUploadedFile.length; j++) {
142           if (
143             theUploadedFile[j].name.split(".").pop() != "xmp" &&
144             theUploadedFile[j].name.split(".")[0] ===
145               theUploadedFile[i].name.split(".")[0]
146           ) {
147             isLoneXMP = false;
148             break;
149           }
150         }
151       }
152 
153       // Copy file here, in case we rename it.
154       var aFileToUpload = theUploadedFile[i];
155 
156       // Uniquify and update xmp mapping if needed
157       if (
158         fileManager.isFile(theDestination + aFileToUpload.name) &&
159         !theReplace
160       ) {
161         aFileToUpload = fileManager.fileRename(
162           aFileToUpload,
163           incrementName(theDestination, aFileToUpload.name)
164         );
165       }
166 
167       // Lone XMP or regular asset, upload like normal
168       if (aFileExtension != "xmp" || isLoneXMP) {
169         anImportedFile = fileManager.fileMove(
170           aFileToUpload,
171           new ManagedFolder(theDestination),
172           theReplace
173         );
174 
175         if (aFileToUpload.name.indexOf(".zip") > 0 && theUnzip == true) {
176           aDecompressedDir = fileManager.decompressFiles(
177             anImportedFile,
178             new ManagedFolder(theDestination)
179           );
180           fileManager.fileDelete(anImportedFile);
181           anIterator = aDecompressedDir.getContents();
182           while (anIterator.hasNext()) {
183             aFileOrFolder = anIterator.next();
184             if (fileManager.isFile(aFileOrFolder.path)) {
185               workflowManager.triggerAssetAdded(aFileOrFolder);
186               myData[aFileOrFolder.assetId] = aFileOrFolder.path;
187             }
188           }
189         } else {
190           workflowManager.triggerAssetAdded(anImportedFile);
191           myData[anImportedFile.assetId] = anImportedFile.path;
192         }
193       }
194     }
195   } else {
196     if (
197       fileManager.isFile(theDestination + theUploadedFile.name) &&
198       !theReplace
199     ) {
200       theUploadedFile = fileManager.fileRename(
201         theUploadedFile,
202         incrementName(theDestination, theUploadedFile.name)
203       );
204     }
205     anImportedFile = fileManager.fileMove(
206       theUploadedFile,
207       new ManagedFolder(theDestination),
208       theReplace
209     );
210     if (theUploadedFile.name.indexOf(".zip") > 0 && theUnzip == true) {
211       aDecompressedDir = fileManager.decompressFiles(
212         anImportedFile,
213         new ManagedFolder(theDestination)
214       );
215       fileManager.fileDelete(anImportedFile);
216       anIterator = aDecompressedDir.getContents();
217       while (anIterator.hasNext()) {
218         aFileOrFolder = anIterator.next();
219         if (fileManager.isFile(aFileOrFolder.path)) {
220           workflowManager.triggerAssetAdded(aFileOrFolder);
221           myData[aFileOrFolder.assetId] = aFileOrFolder.path;
222         }
223       }
224     } else {
225       workflowManager.triggerAssetAdded(anImportedFile);
226       myData[anImportedFile.assetId] = anImportedFile.path;
227     }
228   }
229 }
230 
231 /**
232  * Uploads a file from the form data into mediabeacon at the given destination or the standard directory
233  * @description Uploads a file from the form data into mediabeacon at the given destination or the standard directory. The results are parsed into a text object keyed by AssetID from the JSON file in which they are contained, and by default are displayed to the user.
234  * @example 'MBurl'/wf/restapi/1/upload?dest=['PathToParent']&unzip=true
235  * @example <a target="_blank" href=http://127.0.0.1:55555/wf/restapi/1/upload?dest=["Assets/Library/"]&unzip=true>http://127.0.0.1:55555/wf/restapi/1/upload?dest=["Assets/Library/"]&unzip=true</a>
236  * @class Uploads a file from the form data into mediabeacon at the given destination or the standard directory
237  * @name Upload
238  * @param dest where to upload the file to
239  * @param unzip set to "true" to unzip the uploaded file
240  * @param file  the file needs to be added to the body of the POST in the form data with the name "file"
241  * @returns ( {'AssetID': "path",...} )
242  */
243 function main() {
244   myUnzip = REST.getParameter("unzip", false);
245   myDest = REST.getParameter("dest", true);
246   myReplace = REST.getParameter("replace", false);
247 
248   if (myData.error != null) {
249     return REST.formatResponse();
250   }
251   upload(myDest, myUnzip, myReplace);
252   return REST.formatResponse();
253 }
254 main();
255