]> git.immae.eu Git - perso/Immae/Projets/Nodejs/Surfer.git/blobdiff - cli/actions.js
add surfer put examples and fix put
[perso/Immae/Projets/Nodejs/Surfer.git] / cli / actions.js
index ea2a3a1d1e5b6280151bf3ea7076b31da54c902d..3fd240302a3287cb214176021740cc0520f96f3d 100644 (file)
@@ -1,6 +1,7 @@
 'use strict';
 
 exports.login = login;
+exports.logout = logout;
 exports.put = put;
 exports.get = get;
 exports.del = del;
@@ -19,17 +20,31 @@ require('colors');
 
 var API = '/api/files/';
 
+var gServer = '';
 var gQuery = {};
 
-function checkConfig() {
-    if (!config.server() || !config.username() || !config.password()) {
-        console.log('You have run "login" first');
+function checkConfig(options) {
+    if (!options.parent.server && !config.server()) {
+        console.log('Run %s first, or provide %s', 'surfer login'.bold, '--server <url>'.bold);
         process.exit(1);
     }
 
-    gQuery = { username: config.username(), password: config.password() };
+    if (options.parent.server) {
+        var tmp = url.parse(options.parent.server);
+        if (!tmp.slashes) tmp = url.parse('https://' + options.parent.server);
+        gServer = tmp.protocol + '//' + tmp.host;
+    } else {
+        gServer = config.server();
+    }
+
+    if (!options.parent.token && !config.accessToken()) {
+        console.log('Run %s first or provide %s', 'surfer login'.bold, '--token <access token>'.bold);
+        process.exit(1);
+    }
 
-    console.error('Using server %s', config.server().cyan);
+    gQuery = { access_token: options.parent.token || config.accessToken() };
+
+    console.error('Using server %s', gServer.cyan);
 }
 
 function collectFiles(filesOrFolders, options) {
@@ -54,7 +69,7 @@ function collectFiles(filesOrFolders, options) {
     return tmp;
 }
 
-function login(uri) {
+function login(uri, options) {
     var tmp = url.parse(uri);
     if (!tmp.slashes) tmp = url.parse('https://' + uri);
 
@@ -62,10 +77,12 @@ function login(uri) {
 
     console.log('Using server', server.cyan);
 
-    var username = readlineSync.question('Username: ');
-    var password = readlineSync.question('Password: ', { noEchoBack: true });
+    var username = options.username || readlineSync.question('Username: ');
+    var password = options.password || readlineSync.question('Password: ', { hideEchoBack: true, mask: '' });
+
+    if (!username || !password) process.exit(1);
 
-    superagent.get(server + API + '/').query({ username: username, password: password }).end(function (error, result) {
+    superagent.post(server + '/api/login').send({ username: username, password: password }).end(function (error, result) {
         if (error && error.code === 'ENOTFOUND') {
             console.log('Server %s not found.'.red, server.bold);
             process.exit(1);
@@ -74,60 +91,93 @@ function login(uri) {
             console.log('Failed to connect to server %s'.red, server.bold, error.code);
             process.exit(1);
         }
-        if (result.status === 401) {
-            console.log('Login failed.'.red);
-            process.exit(1);
-        }
+        if (result.status !== 201) {
+            console.log('Login failed.\n'.red);
 
-        config.set('server', server);
-        config.set('username', username);
+            // remove the password to avoid a login loop
+            delete options.password;
 
-        // TODO this is clearly bad and needs fixing
-        config.set('password', password);
+            return login(uri, options);
+        }
 
-        gQuery = { username: username, password: password };
+        // TODO remove at some point, this is just to clear the previous old version values
+        config.set('username', '');
+        config.set('password', '');
+
+        config.set('server', server);
+        config.set('accessToken', result.body.accessToken);
 
         console.log('Login successful'.green);
     });
 }
 
-function put(filePath, otherFilePaths, options) {
-    checkConfig();
+function logout() {
+    if (!config.accessToken()) return console.log('Done'.green);
 
-    var destination = '';
+    superagent.post(gServer + '/api/logout').query({ access_token: config.accessToken() }).end(function (error, result) {
+        if (result && result.statusCode !== 200) console.log('Failed to logout: ' + result.statusCode);
+        if (error) console.log(error);
 
-    // take the last argument as destination
-    if (otherFilePaths.length > 0) {
-        destination = otherFilePaths.pop();
-        if (otherFilePaths.length > 0 && destination[destination.length-1] !== '/') destination += '/';
-    }
+        // TODO remove at some point, this is just to clear the previous old version values
+        config.set('username', '');
+        config.set('password', '');
+        config.set('server', '');
+        config.set('accessToken', '');
+
+        console.log('Done'.green);
+    });
+}
 
-    var files = collectFiles([ filePath ].concat(otherFilePaths), options);
+function putOne(filePath, destination, options, callback) {
+    const absoluteFilePath = path.resolve(filePath);
+    const stat = safe.fs.statSync(absoluteFilePath);
+    if (!stat) return callback(`Could not stat ${filePath}: ${safe.error.message}`);
+
+    let files, base;
+
+    if (stat.isFile()) {
+        base = destination + path.basename(filePath);
+        files = [ absoluteFilePath ];
+    } else if (stat.isDirectory()) {
+        base = destination + (filePath.endsWith('.') ? '' : path.basename(filePath) + '/');
+        files = collectFiles([ absoluteFilePath ], options);
+    } else {
+        return callback(); // ignore
+    }
 
     async.eachSeries(files, function (file, callback) {
-        var relativeFilePath;
-
-        if (path.isAbsolute(file)) {
-            relativeFilePath = path.basename(file);
-        } else if (path.resolve(file).indexOf(process.cwd()) === 0) { // relative to current dir
-            relativeFilePath = path.resolve(file).slice(process.cwd().length + 1);
-        } else { // relative but somewhere else
-            relativeFilePath = path.basename(file);
-        }
+        let relativeFilePath = file.slice(absoluteFilePath.length + 1); // will be '' when filePath is a file
+        let destinationPath = base + relativeFilePath;
+        console.log('Uploading file %s -> %s', file.cyan, destinationPath.cyan);
 
-        var destinationPath = (destination ? '/' + destination : '') + '/' + relativeFilePath;
-        console.log('Uploading file %s -> %s', relativeFilePath.cyan, destinationPath.cyan);
-
-        superagent.post(config.server() + API + destinationPath).query(gQuery).attach('file', file).end(function (error, result) {
+        superagent.post(gServer + API + destinationPath).query(gQuery).attach('file', file).end(function (error, result) {
             if (result && result.statusCode === 403) return callback(new Error('Upload destination ' + destinationPath + ' not allowed'));
             if (result && result.statusCode !== 201) return callback(new Error('Error uploading file: ' + result.statusCode));
             if (error) return callback(error);
 
-            console.log('Uploaded to ' + config.server() + destinationPath);
+            console.log('Uploaded to ' + gServer + destinationPath);
 
             callback(null);
         });
-    }, function (error) {
+    }, callback);
+}
+
+function put(filePaths, options) {
+    checkConfig(options);
+
+    if (filePaths.length < 2) {
+        console.log('target directory is required.'.red);
+        process.exit(1);
+    }
+
+    let destination = filePaths.pop();
+    if (!path.isAbsolute(destination)) {
+        console.log('target directory must be absolute'.red);
+        process.exit(1);
+    }
+    if (!destination.endsWith('/')) destination += '/';
+
+    async.eachSeries(filePaths, (filePath, iteratorDone) => putOne(filePath, destination, options, iteratorDone), function (error) {
         if (error) {
             console.log('Failed to put file.', error.message.red);
             process.exit(1);
@@ -137,13 +187,13 @@ function put(filePath, otherFilePaths, options) {
     });
 }
 
-function get(filePath) {
-    checkConfig();
+function get(filePath, options) {
+    checkConfig(options);
 
     // if no argument provided, fetch root
     filePath = filePath || '/';
 
-    request.get(config.server() + API + filePath, { qs: gQuery }, function (error, result, body) {
+    request.get(gServer + API + filePath, { qs: gQuery }, function (error, result, body) {
         if (result && result.statusCode === 401) return console.log('Login failed');
         if (result && result.statusCode === 404) return console.log('No such file or directory %s', filePath.yellow);
         if (error) return console.error(error);
@@ -163,7 +213,7 @@ function get(filePath) {
             process.stdout.write(body);
         }
     });
-    // var req = superagent.get(config.server() + API + filePath);
+    // var req = superagent.get(gServer + API + filePath);
     // req.query(gQuery);
     // req.end(function (error, result) {
     //     if (error && error.status === 401) return console.log('Login failed');
@@ -182,14 +232,14 @@ function get(filePath) {
 }
 
 function del(filePath, options) {
-    checkConfig();
+    checkConfig(options);
 
     var query = safe.JSON.parse(safe.JSON.stringify(gQuery));
     query.recursive = options.recursive;
     query.dryRun = options.dryRun;
 
     var relativeFilePath = path.resolve(filePath).slice(process.cwd().length + 1);
-    superagent.del(config.server() + API + relativeFilePath).query(query).end(function (error, result) {
+    superagent.del(gServer + API + relativeFilePath).query(query).end(function (error, result) {
         if (error && error.status === 401) return console.log('Login failed'.red);
         if (error && error.status === 404) return console.log('No such file or directory');
         if (error && error.status === 403) return console.log('Failed. Target is a directory. Use %s to delete directories.', '--recursive'.yellow);