Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2016
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.99 KB | None | 0 0
  1. 'use strict';
  2. var path = require('path');
  3. var util = require('util');
  4. var Connection = require('ssh2');
  5. var async = require('async');
  6. var parents = require('parents');
  7. var assign = require('object-assign');
  8. var fs = require('fs-extra');
  9. var chalk = require('chalk');
  10. var Q = require('q');
  11.  
  12. var normalizePath = function (path) {
  13. return path.replace(/\\/g, '/');
  14. };
  15.  
  16. module.exports = function (options, callback) {
  17.  
  18. return Q.Promise(function(resolve, reject){
  19. options = assign({
  20. "host": "",
  21. "port": "36000",
  22. "user": "",
  23. "pass": "",
  24. "remotePath": "",
  25. "sourcePath": "./",
  26. "remotePlatform": "unix"
  27. }, options);
  28.  
  29.  
  30. if (options.host === undefined || options.host === '') {
  31. throw new Error('sftp2', '`host` required.');
  32. }
  33.  
  34. var fileCount = 0;
  35. var fileLength = 0;
  36.  
  37. options.password = options.password || options.pass;
  38. options.username = options.username || options.user || 'anonymous';
  39.  
  40.  
  41. var remotePath = options.remotePath;
  42. var sourcePath = options.sourcePath;
  43. var remotePlatform = options.remotePlatform;
  44.  
  45. var mkDirCache = {};
  46.  
  47. var finished = false;
  48. var connectionCache = null;
  49.  
  50. var items = [];
  51. fs.walk(sourcePath)
  52. .on('data', function (item) {
  53. if (!item.stats.isDirectory()) {
  54. items.push(item);
  55. }
  56. })
  57. .on('end', function () {
  58. fileLength = items.length;
  59.  
  60. if (fileLength <= 0) {
  61. console.log('sftp2:', chalk.yellow('No files uploaded'));
  62. } else {
  63. return uploadFiles(items);
  64. }
  65. });
  66.  
  67. function uploadFiles(files) {
  68.  
  69. connectSftp(function (sftp) {
  70. async.eachSeries(files, function (file, done) {
  71. var filepath = file.path.replace(/\\/, '/');
  72.  
  73. var pathArr = sourcePath.replace(/\/$/, '').split('/');
  74.  
  75. var projectName = pathArr[pathArr.length - 1];
  76.  
  77. var relativePath = filepath.split(projectName + path.sep)[1];
  78.  
  79. var finalRemotePath = normalizePath(path.join(remotePath, relativePath));
  80.  
  81. var dirname = path.dirname(finalRemotePath);
  82.  
  83. var fileDirs = parents(dirname)
  84. .map(function (d) {
  85. return d.replace(/^\/~/, "~");
  86. })
  87. .map(normalizePath);
  88.  
  89. if (dirname.search(/^\//) === 0) {
  90. fileDirs = fileDirs.map(function (dir) {
  91. if (dir.search(/^\//) === 0) {
  92. return dir;
  93. }
  94. return '/' + dir;
  95. });
  96. }
  97.  
  98.  
  99. fileDirs = fileDirs.filter(function (d) {
  100. return d.length >= remotePath.length && !mkDirCache[d];
  101. });
  102.  
  103. async.whilst(function () {
  104. return fileDirs && fileDirs.length;
  105. }, function (next) {
  106. var d = fileDirs.pop();
  107. mkDirCache[d] = true;
  108.  
  109. if (remotePlatform && remotePlatform.toLowerCase().indexOf('win') !== -1) {
  110. d = d.replace('/', '\\');
  111. }
  112.  
  113. sftp.mkdir(d, {mode: '0755'}, function () {
  114. next();
  115. });
  116. }, function () {
  117.  
  118. var readStream = fs.createReadStream(filepath);
  119.  
  120. var stream = sftp.createWriteStream(finalRemotePath, {
  121. flags: 'w',
  122. encoding: null,
  123. mode: '0666',
  124. autoClose: true
  125. });
  126.  
  127. readStream.pipe(stream);
  128.  
  129. stream.on('close', function (err) {
  130.  
  131. if (err) {
  132. throw new Error('sftp2', err);
  133. } else {
  134.  
  135. fileCount++;
  136.  
  137. }
  138.  
  139. done();
  140.  
  141. });
  142.  
  143. });
  144.  
  145. }, function () {
  146. console.log('sftp2:', chalk.green(fileCount, fileCount === 1 ? 'file' : 'files', 'uploaded successfully'));
  147.  
  148. finished = true;
  149.  
  150. if (sftp) {
  151. sftp.end();
  152. }
  153. if (connectionCache) {
  154. connectionCache.end();
  155. }
  156.  
  157. if(callback){
  158. callback();
  159. }
  160.  
  161. resolve()
  162.  
  163.  
  164.  
  165. });
  166. });
  167. }
  168.  
  169. function connectSftp(callback) {
  170. console.log('Authenticating with password.');
  171.  
  172. var c = new Connection();
  173. connectionCache = c;
  174. c.on('ready', function () {
  175.  
  176. c.sftp(function (err, sftp) {
  177. if (err) {
  178. throw err;
  179. }
  180.  
  181. sftp.on('end', function () {
  182. // console.log('SFTP :: SFTP session closed');
  183. sftp = null;
  184. if (!finished) {
  185. console.log('error', new Error('sftp2', "SFTP abrupt closure"))
  186. }
  187. });
  188.  
  189. callback(sftp);
  190. });
  191.  
  192. });
  193.  
  194. c.on('error', function (err) {
  195. console.log('sftp2', err);
  196. reject(err);
  197. });
  198.  
  199. c.on('end', function () {
  200. // console.log('Connection :: end');
  201. });
  202.  
  203. c.on('close', function (had_error) {
  204. if (!finished) {
  205. console.log('sftp2', "SFTP abrupt closure");
  206. }
  207. // console.log('Connection :: close', had_error !== false ? "with error" : "");
  208.  
  209. });
  210.  
  211.  
  212. /*
  213. * connection options, may be a key
  214. */
  215. var connection_options = {
  216. host: options.host,
  217. port: options.port || 22,
  218. username: options.username
  219. };
  220.  
  221. if (options.password) {
  222. connection_options.password = options.password;
  223. }
  224.  
  225. if (options.timeout) {
  226. connection_options.readyTimeout = options.timeout;
  227. }
  228.  
  229.  
  230. c.connect(connection_options);
  231. }
  232.  
  233. });
  234.  
  235. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement