]> git.immae.eu Git - perso/Immae/Projets/Nodejs/Surfer.git/blob - cli/actions.js
protect _admin/
[perso/Immae/Projets/Nodejs/Surfer.git] / cli / actions.js
1 'use strict';
2
3 exports.login = login;
4 exports.put = put;
5 exports.get = get;
6 exports.del = del;
7
8 var superagent = require('superagent'),
9 config = require('./config.js'),
10 readlineSync = require('readline-sync'),
11 safe = require('safetydance'),
12 async = require('async'),
13 fs = require('fs'),
14 request = require('request'),
15 url = require('url'),
16 path = require('path');
17
18 require('colors');
19
20 var API = '/api/files/';
21
22 var gQuery = {};
23
24 function checkConfig() {
25 if (!config.server() || !config.username() || !config.password()) {
26 console.log('You have run "login" first');
27 process.exit(1);
28 }
29
30 gQuery = { username: config.username(), password: config.password() };
31
32 console.error('Using server %s', config.server().cyan);
33 }
34
35 function collectFiles(filesOrFolders, options) {
36 var tmp = [];
37
38 filesOrFolders.forEach(function (filePath) {
39 var baseName = path.basename(filePath);
40 if (!options.all && baseName[0] === '.' && baseName.length > 1) return;
41
42 var stat = fs.statSync(filePath);
43
44 if (stat.isFile()) {
45 tmp.push(filePath);
46 } else if (stat.isDirectory()) {
47 var files = fs.readdirSync(filePath).map(function (file) { return path.join(filePath, file); });
48 tmp = tmp.concat(collectFiles(files, options));
49 } else {
50 console.log('Skipping %s', filePath.cyan);
51 }
52 });
53
54 return tmp;
55 }
56
57 function login(uri) {
58 var tmp = url.parse(uri);
59 if (!tmp.slashes) tmp = url.parse('https://' + uri);
60
61 var server = tmp.protocol + '//' + tmp.host;
62
63 console.log('Using server', server.cyan);
64
65 var username = readlineSync.question('Username: ');
66 var password = readlineSync.question('Password: ', { noEchoBack: true });
67
68 superagent.get(server + API + '/').query({ username: username, password: password }).end(function (error, result) {
69 if (error && error.code === 'ENOTFOUND') {
70 console.log('Server %s not found.'.red, server.bold);
71 process.exit(1);
72 }
73 if (error && error.code) {
74 console.log('Failed to connect to server %s'.red, server.bold, error.code);
75 process.exit(1);
76 }
77 if (result.status === 401) {
78 console.log('Login failed.'.red);
79 process.exit(1);
80 }
81
82 config.set('server', server);
83 config.set('username', username);
84
85 // TODO this is clearly bad and needs fixing
86 config.set('password', password);
87
88 gQuery = { username: username, password: password };
89
90 console.log('Login successful'.green);
91 });
92 }
93
94 function put(filePath, otherFilePaths, options) {
95 checkConfig();
96
97 var destination = '';
98
99 // take the last argument as destination
100 if (otherFilePaths.length > 0) {
101 destination = otherFilePaths.pop();
102 if (otherFilePaths.length > 0 && destination[destination.length-1] !== '/') destination += '/';
103 }
104
105 var files = collectFiles([ filePath ].concat(otherFilePaths), options);
106
107 async.eachSeries(files, function (file, callback) {
108 var relativeFilePath;
109
110 if (path.isAbsolute(file)) {
111 relativeFilePath = path.basename(file);
112 } else if (path.resolve(file).indexOf(process.cwd()) === 0) { // relative to current dir
113 relativeFilePath = path.resolve(file).slice(process.cwd().length + 1);
114 } else { // relative but somewhere else
115 relativeFilePath = path.basename(file);
116 }
117
118 var destinationPath = (destination ? '/' + destination : '') + '/' + relativeFilePath;
119 console.log('Uploading file %s -> %s', relativeFilePath.cyan, destinationPath.cyan);
120
121 superagent.put(config.server() + API + destinationPath).query(gQuery).attach('file', file).end(function (error, result) {
122 if (result && result.statusCode === 403) return callback(new Error('Upload destination ' + destinationPath + ' not allowed'));
123 if (result && result.statusCode !== 201) return callback(new Error('Error uploading file: ' + result.statusCode));
124 if (error) return callback(error);
125
126 console.log('Uploaded to ' + config.server() + destinationPath);
127
128 callback(null);
129 });
130 }, function (error) {
131 if (error) {
132 console.log('Failed to put file.', error.message.red);
133 process.exit(1);
134 }
135
136 console.log('Done');
137 });
138 }
139
140 function get(filePath) {
141 checkConfig();
142
143 // if no argument provided, fetch root
144 filePath = filePath || '/';
145
146 request.get(config.server() + API + filePath, { qs: gQuery }, function (error, result, body) {
147 if (result && result.statusCode === 401) return console.log('Login failed');
148 if (result && result.statusCode === 404) return console.log('No such file or directory %s', filePath.yellow);
149 if (error) return console.error(error);
150
151 // 222 indicates directory listing
152 if (result.statusCode === 222) {
153 var files = safe.JSON.parse(body);
154 if (!files || files.entries.length === 0) {
155 console.log('No files on the server. Use %s to upload some.', 'surfer put <file>'.yellow);
156 } else {
157 console.log('Entries:');
158 files.entries.forEach(function (entry) {
159 console.log('\t %s', entry.isDirectory ? entry.filePath + '/' : entry.filePath);
160 });
161 }
162 } else {
163 process.stdout.write(body);
164 }
165 });
166 // var req = superagent.get(config.server() + API + filePath);
167 // req.query(gQuery);
168 // req.end(function (error, result) {
169 // if (error && error.status === 401) return console.log('Login failed');
170 // if (error && error.status === 404) return console.log('No such file or directory');
171 // if (error) return console.log('Failed', result ? result.body : error);
172
173 // if (result.body && result.body.entries) {
174 // console.log('Files:');
175 // result.body.entries.forEach(function (entry) {
176 // console.log('\t %s', entry);
177 // });
178 // } else {
179 // req.pipe(process.stdout);
180 // }
181 // });
182 }
183
184 function del(filePath, options) {
185 checkConfig();
186
187 var query = safe.JSON.parse(safe.JSON.stringify(gQuery));
188 query.recursive = options.recursive;
189 query.dryRun = options.dryRun;
190
191 var relativeFilePath = path.resolve(filePath).slice(process.cwd().length + 1);
192 superagent.del(config.server() + API + relativeFilePath).query(query).end(function (error, result) {
193 if (error && error.status === 401) return console.log('Login failed'.red);
194 if (error && error.status === 404) return console.log('No such file or directory');
195 if (error && error.status === 403) return console.log('Failed. Target is a directory. Use %s to delete directories.', '--recursive'.yellow);
196 if (error) return console.log('Failed', result ? result.body : error);
197
198 if (options.dryRun) {
199 console.log('This would remove %s files:', result.body.entries.length);
200 result.body.entries.forEach(function (entry) {
201 console.log('\t %s', entry);
202 });
203 } else {
204 console.log('Success. Removed %s files.', result.body.entries.length);
205 }
206 });
207 }