forked from sstur/shopify-ftp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shopify.js
executable file
·459 lines (422 loc) · 14.7 KB
/
shopify.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
#!/usr/bin/env node
/*global process, Buffer*/
(function() {
"use strict";
var fs = require('fs');
var commander = require('commander');
var request = require('request');
var ftpd = require('ftpd');
var path = require('path');
commander
.version(require('./package.json').version)
.option('-p, --port [port]', 'listen on specified port')
.option('-b, --bind [address]', 'bind to specified address')
.parse(process.argv);
var PATH_SEP = path.sep;
var _slice = Array.prototype.slice;
var config = {
port: commander.port || 2121,
bind: commander.bind || '127.0.0.1'
};
var ftp = createServer(config);
ftp.listen(config.port, config.bind, function() {
log('FTP server listening on ' + config.bind + ':' + config.port);
});
function createServer(config) {
var ftp = new ftpd.FtpServer(config.bind, {
pasvPortRangeStart: config.pasvPortRangeStart || 4000,
pasvPortRangeEnd: config.pasvPortRangeEnd || 5000,
getInitialCwd: function(connection, callback) {
connection.emit('get-initial-cwd', callback);
},
getRoot: function(connection) {
return '/';
},
useReadFile: true,
useWriteFile: true
});
//todo: this is kinda hacky
ftp.on('client:connected', clientConnected.bind(null, config));
return ftp;
}
function clientConnected(config, ftpCon) {
config = Object.create(config);
log('FTP connection from ' + ftpCon.socket.remoteAddress);
ftpCon.on('command:user', function(username, success, failure) {
var parsed = parseUser(username);
config.username = username;
config.api_key = parsed.api_key;
config.name = parsed.name;
success();
});
ftpCon.on('command:pass', function(password, success, failure) {
config.password = password;
var proxy = new Proxy(config);
proxy.getThemes(function(error, themes) {
if (error) return failure(error);
proxy.initThemes = themes;
success(config.username, proxy);
});
});
ftpCon.on('close', function() {
log('Connection closed');
});
ftpCon.on('get-initial-cwd', function(callback) {
callback(null, '/');
});
}
function Proxy(config) {
this.config = config;
this.itemCache = {
'/': {role: 'directory'}
};
}
Proxy.prototype = {
readdir: function(path, callback) {
// special case: when we authenticated we received a initial list of
// themes. we don't want to re-fetch right away, so we cache this list
// for the *first* readdir
var initThemes = this.initThemes;
delete this.initThemes;
console.log('readdir', path);
if (path === '/') {
if (initThemes) {
callback(null, getNames(initThemes));
} else {
this.getThemes(function(error, themes) {
if (error) return callback(error);
callback(null, getNames(themes));
}.bind(this));
}
} else {
this.getTheme(path, function(error, theme) {
if (error) return callback(error);
this.getAssets(theme, function(error) {
if (error) return callback(error);
var names = {};
var prefix = path + '/';
Object.keys(this.itemCache).forEach(function(itemPath) {
if (itemPath.indexOf(prefix) === 0) {
var name = itemPath.slice(prefix.length).split('/')[0];
names[name] = 1;
}
});
callback(null, Object.keys(names));
}.bind(this));
}.bind(this));
}
},
//get theme from cache for specified file path
getTheme: function(path, callback) {
var themeName = path.slice(1).split('/')[0];
var theme = this.itemCache['/' + themeName];
if (theme) return callback(null, theme);
this.getThemes(function(error) {
if (error) return callback(error);
var theme = this.itemCache['/' + themeName];
if (!theme) {
error = new Error('Not found: /' + themeName);
console.error(error.stack);
return callback(error)
}
callback(null, theme);
}.bind(this));
},
getThemes: function(callback) {
this.get('/admin/themes', function(error, body) {
if (error) return callback(error);
console.log('fetched themes');
var themes = body.themes;
themes.forEach(function(theme) {
theme.name = theme.name.replace(/\//g, '-');
this.itemCache['/' + theme.name] = theme;
}, this);
callback(null, themes);
}.bind(this));
},
getAssets: function(theme, callback) {
this.get('/admin/themes/' + theme.id + '/assets', function(error, body) {
if (error) return callback(error);
console.log('fetched assets for:', theme.name);
var assets = body.assets;
var itemCache = this.itemCache;
var directories = {};
assets.forEach(function(asset) {
itemCache['/' + theme.name + '/' + asset.key] = asset;
var parts = asset.key.split('/');
asset.name = parts.pop();
//for directory path a/b/c add a, a/b, a/b/c to list of directories
parts.forEach(function(name, i) {
var dirName = parts.slice(0, i + 1).join('/');
if (!directories[dirName]) {
directories[dirName] = [];
}
});
var dirName = parts.join('/');
directories[dirName].push(asset);
});
Object.keys(directories).forEach(function(dirName) {
itemCache['/' + theme.name + '/' + dirName] = {
name: dirName,
role: 'directory',
created_at: theme.created_at,
updated_at: theme.updated_at
};
});
callback(null, directories);
}.bind(this));
},
stat: function(path, callback) {
this.getTheme(path, function(error, theme) {
if (error) return callback(error);
var item = this.itemCache[path];
if (!item) {
//todo: why do we have to fetch here?
this.getAssets(theme, function(error) {
if (error) return callback(error);
if (!this.itemCache[path]) {
error = new Error('Not found: ' + path);
console.error(error.stack);
return callback(error)
}
this.stat(path, callback);
}.bind(this));
return;
}
var type = (item.role) ? 'directory' : 'file';
callback(null, new StatsObject(type, item));
}.bind(this));
},
mkdir: function(path, mode, callback) {
// cannot create directories
var error = new Error('EACCES, permission denied');
error.code = 'EACCES';
return callback(error);
},
rmdir: function(path, callback) {
// cannot remove directories
var error = new Error('EACCES, permission denied');
error.code = 'EACCES';
return callback(error);
},
// limitation: cannot move/copy between themes
rename: function(src, dst, callback) {
// should be of format /theme/folder/file.name
var srcParts = src.slice(1).split('/');
var dstParts = dst.slice(1).split('/');
if (srcParts.length < 3 || dstParts.length < 3) {
var error = new Error('EACCES, permission denied');
error.code = 'EACCES';
return callback(error);
}
this.getTheme(src, function(error, theme) {
if (error) return callback(error);
//todo: ensure the asset is not a directory
var srcPath = src.slice(1).split('/').slice(1).join('/');
var dstPath = dst.slice(1).split('/').slice(1).join('/');
var data = {
asset: {
key: dstPath,
source_key: srcPath
}
};
this.put('/admin/themes/' + theme.id + '/assets', data, function(error, body) {
if (error) return callback(error);
var qs = {
'asset[key]': srcPath
};
this.delete('/admin/themes/' + theme.id + '/assets', qs, function(error, body) {
callback(error);
});
}.bind(this));
}.bind(this));
},
// limitation: not all files can be deleted
unlink: function(path, callback) {
this.getTheme(path, function(error, theme) {
if (error) return callback(error);
path = path.slice(1).split('/').slice(1).join('/');
var qs = {
'asset[key]': path
};
this.delete('/admin/themes/' + theme.id + '/assets', qs, function(error, body) {
callback(error);
});
}.bind(this));
},
createReadStream: function(path, opts) {
console.log('createReadStream', path, opts);
throw new Error('Not implemented');
},
createWriteStream: function(path, opts) {
console.log('createReadStream', path, opts);
throw new Error('Not implemented');
},
readFile: function(path, callback) {
var item = this.itemCache[path];
this.getTheme(path, function(error, theme) {
if (error) return callback(error);
if (!item) {
//todo: why do we have to fetch here?
this.getAssets(theme, function(error) {
if (error) return callback(error);
if (!this.itemCache[path]) {
error = new Error('Not found: ' + path);
console.log(error.stack);
return callback(error)
}
this.readFile(path, callback);
}.bind(this));
return;
}
path = path.slice(1).split('/').slice(1).join('/');
if (item.public_url) {
request({url: item.public_url, encoding: null}, function(error, response, body) {
if (error) return callback(error);
callback(null, body);
});
} else {
var qs = {
'asset[key]': path
};
this.get('/admin/themes/' + theme.id + '/assets', qs, function(error, body) {
if (error) return callback(error);
var asset = body.asset;
var data = (asset.value) ? new Buffer(asset.value) : new Buffer(asset.attachment, 'base64');
callback(null, data);
});
}
}.bind(this));
},
writeFile: function(path, data, callback) {
this.getTheme(path, function(error, theme) {
if (error) return callback(error);
path = path.slice(1).split('/').slice(1).join('/');
var params = {
asset: {
key: path,
attachment: data.toString('base64')
}
};
this.put('/admin/themes/' + theme.id + '/assets', params, function(error, body) {
callback(error);
}.bind(this));
}.bind(this));
},
get: function(resource, qs, callback) {
var args = _slice.call(arguments);
callback = args.pop();
qs = (typeof args[args.length - 1] === 'object') ? args.pop() : null;
request(this.url(resource, qs), function(error, response, body) {
if (error) return callback(error);
if (response.statusCode !== 200) {
return callback(new Error('HTTP Response Status: ' + response.statusCode))
}
var contentType = response.headers['content-type'].split(';')[0].toLowerCase();
if (contentType === 'application/json') {
try {
body = JSON.parse(body);
} catch(e) {
return callback(new Error('Unable to parse response JSON; Content-Length: ' + response.headers['content-length']));
}
return callback(null, body)
} else {
return callback(new Error('Unexpected Content-Type'));
}
});
},
put: function(resource, data, callback) {
var args = _slice.call(arguments);
callback = args.pop();
data = (typeof args[args.length - 1] === 'object') ? args.pop() : {};
request(
{method: 'PUT', url: this.url(resource), body: data, json: true},
function(error, response, body) {
if (error) return callback(error);
callback(null, body)
}
);
},
delete: function(resource, qs, callback) {
var args = _slice.call(arguments);
callback = args.pop();
qs = (typeof args[args.length - 1] === 'object') ? args.pop() : null;
request(
{method: 'DELETE', url: this.url(resource, qs), json: true},
function(error, response, body) {
if (error) {
callback(error);
} else {
callback(null, body);
}
}
);
},
url: function(resource, qs) {
var config = this.config;
var result = 'https://' + config.api_key + ':' + config.password + '@' + config.name + '.myshopify.com' + resource + '.json';
if (qs) {
qs = Object.keys(qs).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(qs[key]);
});
result += '?' + qs.join('&');
}
return result;
}
};
// Windows path support
if (PATH_SEP !== '/') {
[
'readdir', 'stat', 'mkdir', 'rmdir', 'rename', 'unlink', 'createReadStream',
'createWriteStream', 'readFile', 'writeFile'
].forEach(function(methodName) {
var oldMethod = Proxy.prototype[methodName];
var numToFix = (methodName === 'rename') ? 2 : 1;
Proxy.prototype[methodName] = function() {
var args = _slice.call(arguments);
for (var i = 0; i < numToFix; i++) {
args[i] = args[i].split(PATH_SEP).join('/');
}
return oldMethod.apply(this, args);
};
});
}
function StatsObject(type, item) {
this.name = item.name || '';
this.type = type;
this.size = item.size || 0;
this.mtime = (typeof item.updated_at === 'string') ? new Date(Date.parse(item.updated_at)) : item.updated_at;
this.ctime = (typeof item.created_at === 'string') ? new Date(Date.parse(item.created_at)) : item.created_at;
this.atime = this.mtime;
}
StatsObject.prototype = {
isFile: function() {
return (this.type === 'file');
},
isDirectory: function() {
return (this.type === 'directory');
},
isBlockDevice: function() { return false; },
isCharacterDevice: function() { return false; },
isSymbolicLink: function() { return false; },
isFIFO: function() { return false; },
isSocket: function() { return false; }
};
// Allow us to embed our api key + name in the username
// example: e660fd027591bed89e9688d443e48fee@mystore or e660fd027591bed89e9688d443e48fee#mystore
function parseUser(string) {
var parts = string.split(/[@#]/);
return {
api_key: parts[0],
name: parts[1]
};
}
function getNames(list) {
return list.map(function(item) {
return item.name;
});
}
function log() {
console.error.apply(console, arguments);
}
})();