Skip to content

Commit

Permalink
Adding autocomplete and filesystem like ops
Browse files Browse the repository at this point in the history
  • Loading branch information
bhagyas committed Oct 23, 2018
1 parent 381a9d5 commit 14b66fa
Show file tree
Hide file tree
Showing 3 changed files with 168 additions and 38 deletions.
4 changes: 4 additions & 0 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,9 @@ MIT License
== Author
- Bhagya Nirmaan Silva (about.me/bhagyas)

== Privacy Policy

There are no analytics gathered upon the use of the tool. However, the author reserves the right to add analytics on a later release to improve features provided by the tool.

== Contributors
None
199 changes: 162 additions & 37 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

const AlfrescoApi = require("alfresco-js-api-node");
const vorpal = require('vorpal')();
const fsAutocomplete = require('vorpal-autocomplete-fs');

var fs = require('fs');
var AsciiTable = require('ascii-table')
var flatten = require('flat')
Expand All @@ -22,10 +24,11 @@ vorpal
this.log('logging in..');
let password;

console.log(JSON.stringify(args));
let self = this;
self.log(JSON.stringify(args));
if (args.host) {
host = args.host;
console.log("Updating host: " + args.host);
this.log("Updating host: " + args.host);
vorpal.localStorage.setItem('host', args.host);
alfrescoJsApi.changeEcmHost(host);
}
Expand All @@ -37,7 +40,7 @@ vorpal
}

alfrescoJsApi.login(args.username, password).then(function (data) {
console.log('API authentication performed successfully. Login ticket:' + data);
self.log('API authentication performed successfully. Login ticket:' + data);
vorpal.localStorage.setItem('ticket', data);
}, function (error) {
console.error(error);
Expand All @@ -48,18 +51,19 @@ vorpal


vorpal
.command('list-sites [info]', 'Lists all sites.')
.command('list sites [info]', 'Lists all sites.')
.option('-I --info', "Show all info for each site")
.types({
boolean: ['i', 'info']
})
.action(function (args, callback) {
let self = this;
alfrescoJsApi.core.sitesApi.getSites().then(function (data) {
console.log('API called successfully. Returned data for ' + data.list.entries.length + ' sites');
self.log('API called successfully. Returned data for ' + data.list.entries.length + ' sites');
let sites = data.list.entries.map((item) => {
let i = {};
if (args.options.info) {
i[item.entry.id] = item.entry;
i[item.entry.id] = item.entry ;
} else {
i[item.entry.id] = item.entry.title + (item.entry.description ? " - " + item.entry.description : "");
}
Expand All @@ -69,9 +73,9 @@ vorpal
let rows = flatten(sites);
var table = new AsciiTable();
if (args.info) {
table.setHeading('site-id/property', 'value');
table.setHeading('site-id/property', 'value', "id");
} else {
table.setHeading('site-id', 'site-name');
table.setHeading('site-id', 'site-name', "id");
}
for (var key in rows) {
if (args.property) {
Expand All @@ -83,17 +87,18 @@ vorpal
}
}

console.log(table.toString());
self.log(table.toString());
}, function (error) {
console.error(error);
});
callback();
});

vorpal.command('list-people', "Lists all users in system.")
vorpal.command('list people', "Lists all users in system.")
.action(function (args, callback) {
let self = this;
alfrescoJsApi.core.peopleApi.getPersons().then(function (data) {
console.log('API called successfully. Returned data for ' + data.list.entries.length + ' users.');
self.log('API called successfully. Returned data for ' + data.list.entries.length + ' users.');

//TODO: Add the user information table.
}, function (error) {
Expand All @@ -109,54 +114,84 @@ vorpal
callback();
});

vorpal.command('list parents <nodeRef>', 'Lists parents for a given nodeRef.')

.action(function(args, cb){
// alfrescoJsApi.nodes.getParents(args.nodeRef).then((data) => {
// data.list.entries.forEach(entry => {
// this.log(entry.entry.nodeId)
// })
// }).then(() => {
// cb();
// })
let self = this;
alfrescoJsApi.core.childAssociationsApi.listParents(args.nodeRef, {}).then(function(data) {
self.log('API called successfully. ' + data.list.entries.length + ' parent(s) found.');
data.list.entries.forEach(element => {
self.log(element.entry.id);
});
cb();
}, function(error) {
console.error(error);
cb();
});
}
);

vorpal
.command('upload-file <destinationNodeRef> <filePath> [autoRename]', 'Uploads a file to the given destination.')
.option('-arn', "--autoRename", "Automatically rename the file if a similarly named file exists.")
.action(function (args, callback) {
let ongoing = false;
let self = this;
var fileToUpload = fs.createReadStream(args.filePath);
const bar1 = new _cliProgress.Bar({}, _cliProgress.Presets.shades_classic);
bar1.start();
alfrescoJsApi.upload.uploadFile(fileToUpload, null, args.destinationNodeRef, null, {autoRename: args.options.autoRename})
let upload = alfrescoJsApi.upload.uploadFile(fileToUpload, null, args.destinationNodeRef, null, {autoRename: args.options.autoRename})
.on('progress', (progress) => {

bar1.update(progress.percent);
// console.log( 'Total :' + progress.total );
// console.log( 'Loaded :' + progress.loaded );
// console.log( 'Percent :' + progress.percent );
// this.log( 'Total :' + progress.total );
// this.log( 'Loaded :' + progress.loaded );
// this.log( 'Percent :' + progress.percent );
// vorpal.ui.redraw('progress: ' + progress.percent);
})
.on('success', () => {
bar1.stop();
vorpal.ui.redraw.clear()
console.log('Your File is uploaded');
callback();
self.log('Your File is uploaded');

})
.on('abort', () => {
bar1.stop();
console.info('Upload Aborted');
callback();
self.log('Upload Aborted');
})
.on('error', () => {
bar1.stop();
console.log('Error during the upload');
callback();
self.log('There was an error during the upload');
})
.on('unauthorized', () => {
bar1.stop();
console.log('You are unauthorized');
self.log('You are unauthorized');
});

upload.then(()=>{
callback();
}).catch(() => {
callback();
});

});
})
.autocomplete(fsAutocomplete());

vorpal.command('view-metadata <nodeRef> [property]', "Shows metadata for the selected node.")
vorpal.command('view-metadata [nodeRef] [property]', "Shows metadata for the selected node.")
.option('-p', '--property', 'Show only a particualr property.')
.alias('info')
.alias('stat')
.action(function (args, callback) {
alfrescoJsApi.nodes.getNodeInfo(args.nodeRef).then(function (data) {
console.log('Name: ' + data.name);
let self = this;
alfrescoJsApi.nodes.getNodeInfo(getCurrentNodeRef(args.nodeRef)).then(function (data) {
self.log('name: ' + data.name);
let rows = flatten(data);
var table = new AsciiTable();
table.setHeading('property', 'value');
Expand All @@ -170,10 +205,10 @@ vorpal.command('view-metadata <nodeRef> [property]', "Shows metadata for the sel
}
}

console.log(table.toString());
self.log(table.toString());

}, function (error) {
console.log('This node does not exist');
self.log('This node does not exist');
});
callback();
});
Expand All @@ -184,7 +219,7 @@ vorpal.command('move-node <nodeRef> <destinationNodeRef>', "Moves a node to a de
});


vorpal.command("delete-node <nodeRef>", "Deletes a given node.")
vorpal.command("delete node <nodeRef>", "Deletes a given node.")
.action(function (args, callback) {
this.log('deleting node: ' + args.nodeRef)
callback();
Expand All @@ -196,19 +231,19 @@ vorpal.command("about", "About Alfresco CLI")
callback();
});

vorpal.command("create-folder <folderName> <destinationNodeRef> [path]", "Create folder")
vorpal.command("create folder <folderName> <destinationNodeRef> [path]", "Create folder")
.option('-p', "--path", "Relative path from the destination nodeRef.")
.alias('mkdir')
.action(function (args, callback) {
let self = this;
alfrescoJsApi.nodes.createFolder(args.folderName, args.path, args.destinationNodeRef).then(function (data) {
console.log('The folder is created.');
self.log('The folder is created.');
}, function (error) {
console.log('Error in creation of this folder or folder already exist' + error);
self.log('Error in creation of this folder or folder already exist' + error);
});
callback();
});


let init = async () => {
let ticket = vorpal.localStorage.getItem('ticket');
let _host = vorpal.localStorage.getItem('host');
Expand All @@ -217,25 +252,115 @@ let init = async () => {
host = _host;
alfrescoJsApi.changeEcmHost(_host);
await alfrescoJsApi.loginTicket(ticket).then(function (data) {
console.log("Automatically logged into host: " + host + " with ticket: " + ticket);
console.log("If this is not intended, please logout from the terminal.");
vorpal.log("Automatically logged into host: " + host + " with ticket: " + ticket);
vorpal.log("If this is not intended, please logout from the terminal.");
}, function (error) {
throw error;
});
} else {
throw new Error("Invalid login ticket.");
}
} catch (e) {
console.log("Please make sure you are logged in before issuing any commands.")
vorpal.log("You are not logged in. Please make sure you are logged in before issuing any commands.")
}
};

vorpal.command("cd [nodeRef]", "Change into a nodeRef")
.action(function (args, callback) {
let self = this;

if(args.nodeRef == ".."){
//find and move to the parent.
let list = alfrescoJsApi.core.childAssociationsApi.listParents(getCurrentNodeRef());

list.then(function(data) {
self.log('API called successfully. ' + data.list.entries.length + ' parent(s) found.');
let parentNodeRef;
data.list.entries.forEach(element => {
self.log(element.entry.id);
parentNodeRef = element.entry.id;
});
if(parentNodeRef) {
setCurrentNodeRef(parentNodeRef);
callback();
}else{
throw new Error("Unable to find a navigable parent.");
}
}).catch((e) => {
self.log(e);
callback();
});
}else{
//TODO: Validate the nodeRef.
setCurrentNodeRef(args.nodeRef);
}
callback();
});

vorpal.command('clear', "Clears the current node context.")
.alias('cls')
.action((args, callback) => {
setCurrentNodeRef("")
callback();
});


function setCurrentNodeRef(nodeRef){
vorpal.localStorage.setItem('currentNodeRef', nodeRef);
vorpal.log(vorpal.localStorage.getItem('currentNodeRef'));
vorpal.delimiter(getDelimiter());
}

vorpal.command('ls [nodeRef]', "List all children of a given folder.")
.action(function(args, callback){
let self = this;
try{
let nodeRef = getCurrentNodeRef(args.nodeRef);

self.log(`listing content for nodeRef : ${nodeRef}`)

alfrescoJsApi.nodes.getNodeChildren(nodeRef).then(function (data) {
data.list.entries.map(item => {
self.log(`${item.entry.id} ${item.entry.name} ${item.entry.nodeType}`)
});
self.log('The number of children in this folder are ' + data.list.pagination.count );
}, function (error) {
self.log('This node does not exist');
});
}catch(e){
self.log(e.message);
}
callback();
});

vorpal.localStorage('alfresco-cli');
vorpal.history('alfresco-cli');

function getCurrentNodeRef(nodeRef) {
if(nodeRef){
return nodeRef;
}
let storedNodeRef = vorpal.localStorage.getItem('currentNodeRef');

if(!storedNodeRef){
throw new Error("Unable to find applicable nodeRef.");
}

return storedNodeRef;
}

function getDelimiter() {
let item;
try {
item = getCurrentNodeRef();
return `alfresco-cli:${item}$`;
}catch(error){
return `alfresco-cli$`;
}
}

vorpal
.delimiter('alfresco-cli$')
.delimiter(getDelimiter())
.show();

init();
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
"inquirer": "^6.2.0",
"shelljs": "^0.8.2",
"ts-node": "^7.0.1",
"vorpal": "^1.12.0"
"vorpal": "^1.12.0",
"vorpal-autocomplete-fs": "0.0.3"
},
"devDependencies": {
"typescript": "^3.1.3"
Expand Down

0 comments on commit 14b66fa

Please sign in to comment.