-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
327 lines (282 loc) · 9.53 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
var async = require('async');
var ftp = require('ftp');
var fs = require('fs');
var path = require('path');
function createFtpQueue(opts) {
var client;
var queue = [];
function initClient(cb) {
client = new ftp();
client.on('ready', cb);
client.connect(opts.connect);
}
function getRemoteName(filename) {
return path.join(opts.remoteDir, path.relative(opts.dir, filename)).replace(/\\/g, '/');
}
function doSend(filename) {
if (!client) {
initClient(doSend.bind(null, filename));
return;
}
var remoteName = getRemoteName(filename);
console.log("Uploading " + filename + " as " + remoteName + ".");
client.put(filename, remoteName, function(err) {
console.log(err ? "Couldn't upload " + filename + ":\n" + err : filename + ' uploaded.');
advanceQueue(err);
});
}
function doDelete(filename) {
if (!client) {
initClient(doDelete.bind(null, filename));
return;
}
var remoteName = getRemoteName(filename);
console.log("Deleting " + remoteName + ".");
client.delete(remoteName, function(err) {
console.log(err ? "Couldn't delete " + filename + ":\n" + err : filename + ' deleted.');
advanceQueue(err);
});
}
function doMkdir(filename) {
if (!client) {
initClient(doMkdir.bind(null, filename));
return;
}
var remoteName = getRemoteName(filename);
console.log("Adding " + remoteName + ".");
client.mkdir(remoteName, function(err) {
console.log(err ? "Couldn't add " + filename + ":\n" + err : filename + ' added.');
advanceQueue(err);
});
}
function doRmdir(filename) {
if (!client) {
initClient(doMkdir.bind(null, filename));
return;
}
var remoteName = getRemoteName(filename);
console.log("Deleting " + remoteName + ".");
client.rmdir(remoteName, function(err) {
console.log(err ? "Couldn't delete " + filename + ":\n" + err : filename + ' deleted.');
advanceQueue(err);
});
}
function doList(dirname) {
if (!client) {
initClient(doList.bind(null, dirname));
return;
}
var remoteName = getRemoteName(dirname);
console.log("Listing " + remoteName + ".");
// some bs to deal with this callback possibly being called multiple times.
// the result we want is not always the first or last one called.
var result = [], resultTimer;
client.list(remoteName, function(err, list) {
if (err) {
result = true;
console.log("Couldn't list " + dirname + ":\n" + err);
advanceQueue(err, list);
}
if (result === true || result.length) return;
if (list && list.length) {
result = list;
}
if (resultTimer) return;
resultTimer = setTimeout(function() {
console.log(dirname + ' listed.');
advanceQueue(null, result);
}, 100);
});
}
function execute(entry) {
var file = entry.file;
var action = entry.action;
switch(action) {
case 'upsert' : doSend(file); break;
case 'delete' : doDelete(file); break;
case 'mkdir' : doMkdir(file); break;
case 'rmdir' : doRmdir(file); break;
case 'list' : doList(file); break;
default : throw new Error("Unexpected action " + action); break;
}
}
function entryEquals(a, b) {
return a.action === b.action &&
a.file === b.file
a.callback === b.callback;
}
function addToQueue(entry) {
if (queue.slice(1).some(entryEquals.bind(null, entry))) {
return;
}
queue.push(entry);
if (queue.length === 1) {
execute(entry);
}
}
function advanceQueue(err, currentResult) {
var finished = queue.shift();
if (finished.callback) {
finished.callback(err, currentResult);
}
if (queue.length) {
execute(queue[0]);
}
}
function addFile(filename) {
addToQueue({ file : filename, action : 'upsert' });
}
function removeFile(filename) {
addToQueue({ file : filename, action : 'delete' });
}
function addDir(filename) {
addToQueue({ file : filename, action : 'mkdir' });
}
function removeDir(filename) {
addToQueue({ file : filename, action : 'rmdir' });
}
function listFiles(dirname, callback) {
addToQueue({ file : dirname, action : 'list', callback : callback });
}
return {
addFile : addFile,
removeFile : removeFile,
addDir : addDir,
removeDir : removeDir,
listFiles : listFiles
};
}
function watchRecursive(dir, opts, onchange, cb) {
fs.watch(dir, opts, function(event, filename) {
onchange(event, filename, path.join(dir, filename));
});
fs.readdir(dir, function(err, files) {
function recurse(file, cb) {
file = path.join(dir, file);
fs.stat(file, function(err, stat) {
if (err) return cb(err);
if (stat.isDirectory()) {
return watchRecursive(file, opts, onchange, cb);
}
return cb();
});
}
async.each(files, recurse, cb);
});
}
function makeFile(name, type) {
return {
name : name.name || name,
type : name.type || type
};
}
function makeFilesViaStat(dirname, files, cb) {
async.map(files, function(file, cb) {
fs.stat(path.join(dirname, file), function(err, stat) {
if (err) return cb(err, stat);
cb(null, makeFile(file, stat.isDirectory() ? 'd' : '-'));
})
}, cb);
}
function fileEqual(a, b) {
return a.name === b.name && a.type === b.type;
}
function getDirectoryDiff(oldFiles, newFiles) {
var removed = oldFiles.filter(function(oldFile) {
return !newFiles.some(fileEqual.bind(null, oldFile));
});
var added = newFiles.filter(function(newFile) {
return !oldFiles.some(fileEqual.bind(null, newFile));
});
return {
added : added,
removed : removed
};
}
module.exports = function(opts, cb) {
var filter = opts.filter;
var ftpQueue = createFtpQueue(opts);
var dir = path.resolve('.', opts.dir);
var firedRecently = {};
function getAndSetFiredRecently(pathname) {
if (firedRecently[pathname]) return true;
firedRecently[pathname] = true;
setTimeout(function() { delete firedRecently[pathname]; }, opts.minChangePeriod || 250);
return false;
}
function handleDirectoryChange(pathname) {
async.parallel([
async.waterfall.bind(async, [
fs.readdir.bind(fs, pathname),
makeFilesViaStat.bind(null, pathname)
]),
async.waterfall.bind(async, [
ftpQueue.listFiles.bind(ftpQueue, pathname),
function normalizeRemoteFiles(remoteFiles, cb) {
cb(null, remoteFiles.map(makeFile)
.filter(function(obj) {
return obj.name !== '.' &&
obj.name !== '..';
}));
}
])
], function(err, results) {
if (err) throw err;
var localFiles = results[0];
var remoteFiles = results[1];
var dirDiff = getDirectoryDiff(remoteFiles, localFiles);
//console.log(localFiles, remoteFiles, dirDiff);
dirDiff.added.forEach(function(file) {
var fullname = path.join(pathname, file.name);
if (getAndSetFiredRecently(fullname)) return;
if (file.type === 'd') {
ftpQueue.addDir(fullname);
} else {
ftpQueue.addFile(fullname);
}
});
dirDiff.removed.forEach(function(file) {
var fullname = path.join(pathname, file.name);
if (getAndSetFiredRecently(fullname)) return;
if (file.type === 'd') {
ftpQueue.removeDir(fullname);
} else {
ftpQueue.removeFile(fullname);
}
});
});
}
watchRecursive(dir || '.', {
persistent : opts.hasOwnProperty('persistent') ?
opts.persistent :
true
}, function(event, filename, pathname) {
if (!filename) {
// happens on adds and deletes - no filename provided
return;
}
if (getAndSetFiredRecently(pathname)) return;
console.log(pathname + ' changed.');
fs.stat(pathname, function(err, stat) {
if (err) throw err;
if (stat.isDirectory()) {
handleDirectoryChange(pathname);
} else {
ftpQueue.addFile(pathname);
}
});
}, cb || function() {});
};
module.exports.exampleOpts = {
dir : '.',
remoteDir : '/',
filter : null,
persistent : true,
connect : {
host : 'remote.com',
port : '1337',
secure : true,
user : 'name',
password : 'god'
}
};