forked from Automattic/knox
/
client.js
355 lines (314 loc) · 8.14 KB
/
client.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
/*!
* knox - Client
* Copyright(c) 2010 LearnBoost <dev@learnboost.com>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var utils = require('./utils')
, auth = require('./auth')
, http = require('http')
, url = require('url')
, join = require('path').join
, mime = require('./mime')
, fs = require('fs');
/**
* Initialize a `Client` with the given `options`.
*
* Required:
*
* - `key` amazon api key
* - `secret` amazon secret
* - `bucket` bucket name string, ex: "learnboost"
*
* @param {Object} options
* @api public
*/
var Client = module.exports = exports = function Client(options) {
if (!options.key) throw new Error('aws "key" required');
if (!options.secret) throw new Error('aws "secret" required');
if (!options.bucket) throw new Error('aws "bucket" required');
this.endpoint = options.bucket + '.s3.amazonaws.com';
utils.merge(this, options);
};
/**
* Request with `filename` the given `method`, and optional `headers`.
*
* @param {String} method
* @param {String} filename
* @param {Object} headers
* @return {ClientRequest}
* @api private
*/
Client.prototype.request = function(method, filename, headers){
var options = { host: this.endpoint, port: 80 }
, date = new Date
, headers = headers || {};
// Default headers
utils.merge(headers, {
Date: date.toUTCString()
, Host: this.endpoint
});
// Authorization header
headers.Authorization = auth.authorization({
key: this.key
, secret: this.secret
, verb: method
, date: date
, resource: join('/', this.bucket, filename)
, contentType: headers['Content-Type']
, amazonHeaders: auth.canonicalizeHeaders(headers)
});
// Issue request
options.method = method;
options.path = join('/', filename);
options.headers = headers;
var req = http.request(options);
req.url = this.url(filename);
return req;
};
/**
* PUT data to `filename` with optional `headers`.
*
* Example:
*
* // Fetch the size
* fs.stat('Readme.md', function(err, stat){
* // Create our request
* var req = client.put('/test/Readme.md', {
* 'Content-Length': stat.size
* , 'Content-Type': 'text/plain'
* });
* fs.readFile('Readme.md', function(err, buf){
* // Output response
* req.on('response', function(res){
* console.log(res.statusCode);
* console.log(res.headers);
* res.on('data', function(chunk){
* console.log(chunk.toString());
* });
* });
* // Send the request with the file's Buffer obj
* req.end(buf);
* });
* });
*
* @param {String} filename
* @param {Object} headers
* @return {ClientRequest}
* @api public
*/
Client.prototype.put = function(filename, headers){
headers = utils.merge({
Expect: '100-continue'
, 'x-amz-acl': 'public-read'
}, headers || {});
return this.request('PUT', filename, headers);
};
/**
* PUT the file at `src` to `filename`, with callback `fn`
* receiving a possible exception, and the response object.
*
* NOTE: this method reads the _entire_ file into memory using
* fs.readFile(), and is not recommended or large files.
*
* Example:
*
* client
* .putFile('package.json', '/test/package.json', function(err, res){
* if (err) throw err;
* console.log(res.statusCode);
* console.log(res.headers);
* });
*
* @param {String} src
* @param {String} filename
* @param {Object|Function} headers
* @param {Function} fn
* @api public
*/
Client.prototype.putFile = function(src, filename, headers, fn){
var self = this;
if ('function' == typeof headers) {
fn = headers;
headers = {};
};
fs.readFile(src, function(err, buf){
if (err) return fn(err);
headers = utils.merge({
'Content-Length': buf.length
, 'Content-Type': mime.lookup(src)
}, headers);
self.put(filename, headers).on('response', function(res){
fn(null, res);
}).end(buf);
});
};
/**
* PUT the given `stream` as `filename` with optional `headers`.
*
* @param {Stream} stream
* @param {String} filename
* @param {Object|Function} headers
* @param {Function} fn
* @api public
*/
Client.prototype.putStream = function(stream, filename, headers, fn){
var self = this;
if ('function' == typeof headers) {
fn = headers;
headers = {};
};
var startStream = function(err, stat) {
if (err) return fn(err);
// TODO: sys.pump() wtf?
headers['Content-Length'] = stat.size;
// skip mime.lookup
if (!headers['Content-Type']) {
headers['Content-Type'] = mime.lookup(stream.path);
}
var req = self.put(filename, headers);
req.on('response', function(res) {
fn(null, res);
});
stream
.on('error', function(err){fn(null, err); })
.on('data', function(chunk){ req.write(chunk); })
.on('end', function(){ req.end(); });
};
var contentLength = headers['Content-Length'];
if (contentLength && contentLength > 0) { // skip fs.stat
startStream(null, {size: contentLength});
}
else {
fs.stat(stream.path, startStream);
}
};
/**
* GET `filename` with optional `headers`.
*
* @param {String} filename
* @param {Object} headers
* @return {ClientRequest}
* @api public
*/
Client.prototype.get = function(filename, headers){
return this.request('GET', filename, headers);
};
/**
* GET `filename` with optional `headers` and callback `fn`
* with a possible exception and the response.
*
* @param {String} filename
* @param {Object|Function} headers
* @param {Function} fn
* @api public
*/
Client.prototype.getFile = function(filename, headers, fn){
if ('function' == typeof headers) {
fn = headers;
headers = {};
}
return this.get(filename, headers).on('response', function(res){
fn(null, res);
}).end();
};
/**
* Issue a HEAD request on `filename` with optional `headers.
*
* @param {String} filename
* @param {Object} headers
* @return {ClientRequest}
* @api public
*/
Client.prototype.head = function(filename, headers){
return this.request('HEAD', filename, headers);
};
/**
* Issue a HEAD request on `filename` with optional `headers`
* and callback `fn` with a possible exception and the response.
*
* @param {String} filename
* @param {Object|Function} headers
* @param {Function} fn
* @api public
*/
Client.prototype.headFile = function(filename, headers, fn){
if ('function' == typeof headers) {
fn = headers;
headers = {};
}
return this.head(filename, headers).on('response', function(res){
fn(null, res);
}).end();
};
/**
* DELETE `filename` with optional `headers.
*
* @param {String} filename
* @param {Object} headers
* @return {ClientRequest}
* @api public
*/
Client.prototype.del = function(filename, headers){
return this.request('DELETE', filename, headers);
};
/**
* DELETE `filename` with optional `headers`
* and callback `fn` with a possible exception and the response.
*
* @param {String} filename
* @param {Object|Function} headers
* @param {Function} fn
* @api public
*/
Client.prototype.deleteFile = function(filename, headers, fn){
if ('function' == typeof headers) {
fn = headers;
headers = {};
}
return this.del(filename, headers).on('response', function(res){
fn(null, res);
}).end();
};
/**
* Return a url to the given `filename`.
*
* @param {String} filename
* @return {String}
* @api public
*/
Client.prototype.url = function(filename){
return 'http://' + join(this.endpoint, filename);
};
/**
* Return an S3 presigned url to the given `filename`.
*
* @param {String} filename
* @param {Date} expiration
* @return {String}
* @api public
*/
Client.prototype.signedUrl = function(filename, expiration){
var epoch = Math.floor(expiration.getTime()/1000);
var signature = auth.signQuery({
secret: this.secret,
date: epoch,
resource: '/' + this.bucket + url.parse(filename).pathname
});
return this.url(filename) +
'?Expires=' + epoch +
'&AWSAccessKeyId=' + this.key +
'&Signature=' + escape(signature);
};
/**
* Shortcut for `new Client()`.
*
* @param {Object} options
* @see Client()
* @api public
*/
exports.createClient = function(options){
return new Client(options);
};