DropBox for Business Integration

JavaScript sample code for Script Task


 

In this article, we show how a script task can be used to integrate with DropBox for Business. The script will write the files in a Straatos Task into a directory in DropBox. The task in Straatos can have Original Document as well as Additional Data files.

 

Preparation Dropbox for Business

 

  1. If you don't have already a DropBox for Business account, go here to created one https://www.dropbox.com/business (30 days trial account is available).
  2. There is a 30 days trial account
  3. Once you have setup an account, go to https://www.dropbox.com/developers/apps
  4. Click on 'create app'
  5. In the screen that appears, choose in 1) the Dropbox Buisness API. In 2) the Team Member File Access and in 3) give the app a name. For example 'CumulusPro - Straatos'.
  6. In the next screen, generate the access code. This will allow the script from Straatos to send the files without a user authentication process.
  7. You can continue updating the app in dropbox based on your own preferences, but for the purpose of this example, we don't need more information.

Straatos Workflow Setup

 

For the example, we create a simple workfow where users can create a new task in MyHome, select the DropBox Folder the document should be stored in and then upload a document. The document will then get exported to that folder.

  1. Create a new Workflow 'DropBox'
  2. Create 3 new index fields
    1. TeamMemberId (string, hidden). This will be used to store the TeamMemberId from Dropbox
    2. Namespaces (string, hidden). Used to store the Namespaces (folder) information from Dropbox
    3. Folder (lookup), this will be the dropdown the user selects the folder. As values enter the Dropbox folder. Ensure the 'value' matches the name in dropbox.
    4. Create a 4 step process as per the screenshot below:
    5. In the start event 'Start Upload Documents', ensure that in the settings, the mode is set to 'Task (form based)
    6. Publish the Workflow
    7. Assign a user in Straatos with the role 'Start Upload Documents'
    8. Login to Straatos with the user account assigned to 'Start Upload Documents', create a new Task, upload some documents (an 'Original Document' and at least one 'Attachment'). Then press 'Complete'.

 

We have now created the workflow and added a task with documents we can use to write and test our DropBox Script.

 

 

Script Task for Getting Folders from DropBox

 

In order to export the documents to dropbox, we need to match the user selected folder name with the folders in dropbox. Dropbox provides an ID for each folder. This information we need to provide when we upload the documents. For this sample, we retrieve the folders from dropbox and get the ID we need. We save then the ID in the 'Namespaces' field we created earlier.

 

  1. In the workflow designer, open the settings of the 'Get Folders & Members Info'. This will open an empty Javascript editor.
  2. Enter the following code:
    try {
        Namespaces = '';
    
        straatos.ajax({
            url: 'https://api.dropboxapi.com/2/team/namespaces/list',
            method: 'POST',
            headers: {'Content-Type': 'application/json' , 'Authorization':'Bearer <your api token>'},
            data: JSON.stringify({"limit": 1})
        }).done(function (dataString) {
            var resp = JSON.parse(dataString).namespaces;
            console.log('++ resp: ' + JSON.stringify(resp));
            if(resp && resp.length > 0) {
                for(var i=0; i<resp.length; i++) {
                    if(resp[i].name == Folder){
                        Namespaces = resp[i].namespace_id;
                    }
                }
            }
        }).fail(function (jqXHR, error) {
            console.log('Error:' + error);
            straatos.setError('Error: ' + error);
        });
    
    } catch(err) {
        console.log('Error: ' + err);   
    }

    in the 'Bearer' section above, replace the <your api token> with the token generated in Dropbox.
    The script will call the dropbox API and loop through the results. It checks if for the dropbox folder name that matches the folder selected in the UI and then saves teh namespace id into the Namespaces variable.

 

Script Task for Getting Teammember ID from DropBox

 

When a document is uploaded, we need to provide a Teammember Id. For this script example, we retrieve a list of teammembers from DropBox and use the first teammember to upload the document as. In a production implemenation, this could be checked against the Straatos Loginname or agains a fix ID used to upload documents.

 

We will add the code in the script step ''Get Folders & Members Info', just below the Folders code in the section above.

  1. In the workflow designer, open the settings of the 'Get Folders & Members Info'
  2. Place the cursor just below the last line of code.
  3. Add the following code:
    try {
        TeamMemberId = '';
    
        straatos.ajax({
            url: 'https://api.dropboxapi.com/2/team/members/list',
            method: 'POST',
            headers: {'Content-Type': 'application/json' , 'Authorization':'Bearer <your api token>'},
            data: JSON.stringify({"limit": 100, "include_removed": false})
        }).done(function (dataString) {
            var resp = JSON.parse(dataString).members;
            if(resp && resp.length > 0) {
                for(var i=0; i<resp.length; i++) {
                    var elem = resp[i];
                    var profile = (elem).profile;
                    var email = (profile).email;
                    var status = JSON.stringify((profile).status);
                    status = status.split(':')[1];
                    
                    if(status == '"active"}') {
                        TeamMemberId = (profile).team_member_id;
                    }
                }
            }
        }).fail(function (jqXHR, error) {
            console.log('Error:' + error);
            straatos.setError('Error: ' + error);
        });
        console.log('tmid ' + TeamMemberId);
    } catch(err) {
        console.log('Error: ' + err);   
    }


    in the 'Bearer' section above, replace the <your api token> with the token generated in Dropbox.
    The script above gets a list of teammembers from dropbox. It then loops through the list and selects an acvite teammember. At this stage, the script could also check for a user with the same name in Straatos or a fixed user for which the document should be uploaded to.

Script Task for Uploading the documents to DropBox

 

Now that we have all the information needed to upload the documents to DropBox, we can write the script to upload.

In the script, we will upload the Original Document in the Straatos task (if there is one) as well as any additional documents. For additional documents, we will use the original filename that has been uploaded. For the Original Document, we will assign a UUID as the filename.

  1. In the workflow designer, open the settings of the 'Export To Dropbox Business'. This will open an empty Javascript editor.
  2. Enter the following code
    // SETUP ADDITIONAL DATA
    var uploadUrls = [], uploadfileNames = [];
    var documentInfo = straatos.adapter.getDocumentInfo();
    
    for (var h=0; h<documentInfo.additionalData.length; h++){
        uploadUrls[h] = documentInfo.additionalData[h].url + '?w=' + straatos.webServiceKey;
        uploadfileNames[h] = getFileName(documentInfo.additionalData[h].key);
    }
    
    // Setup the Original Document for export
    if(documentInfo.originalURL) {
        var urlsLength = uploadUrls.length;
        uploadUrls[urlsLength] = documentInfo.originalURL + '?w=' + straatos.webServiceKey;
        uploadfileNames[urlsLength] = straatos.uuid() + '.pdf';
        console.log('++ original URL: ' + uploadUrls[urlsLength]);
        console.log('++ fileName: ' + uploadfileNames[urlsLength]);
    }
    
    
    //---- saving file URLs-------//
    var teamMemberId = TeamMemberId;
    if(uploadUrls && uploadUrls.length > 0) {
        for(var i=0; i < uploadUrls.length; i++) {
            saveURL(uploadUrls[i], uploadfileNames[i]);
        }
    }
    
    function getFileName(keyName) {
        var fileName = '';
        if(keyName && keyName.length > 0) {
            fileName = keyName.substring(keyName.lastIndexOf(':') + 1);
        }
        console.log('++ fileName: ' + fileName);
        return fileName;
    }
    
    function saveURL(fileUrl, fileName) {
        console.log('++ fileURL: ' + fileUrl);
        console.log('++ fileKey: ' + fileName);
        try {
            fileName = "/" + fileName;
            console.log('++ ' + fileName);
            straatos.ajax({
                url: 'https://api.dropboxapi.com/2/files/save_url',
                method: 'POST',
                headers: {'Content-Type': 'application/json' , 'Authorization':'Bearer <your api token>',
                          "Dropbox-API-Select-User": teamMemberId,
                          "Dropbox-API-Path-Root": JSON.stringify({".tag": "namespace_id", "namespace_id": Namespaces})
                         },
                data: JSON.stringify({"path": fileName, "url": fileUrl})
    
            }).done(function (dataString) {
                var resp = JSON.parse(dataString);
                console.log('++ resp: ' + JSON.stringify(resp));
            }).fail(function (jqXHR, error) {
                console.log('+++ Error:' + error);
                straatos.setError('Error: ' + error);
            });
    
        } catch(err) {
            console.log('+++++++++ Error: ' + err);   
        }
    }

    in the 'Bearer' section above, replace the <your api token> with the token generated in Dropbox.

 

Test the Export

 

Once the above sections have been completed, test the export with the Straatos task created earlier. The documents should now be exported to the directory in Dropbox:

Create your own Knowledge Base