-
Notifications
You must be signed in to change notification settings - Fork 24
/
uploader.js
86 lines (72 loc) · 1.93 KB
/
uploader.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
'use strict';
// ./uploader server filepath token id
var fs = require('fs');
var os = require('os');
var crypto = require('crypto');
var urllib = require('urllib');
var formstream = require('formstream');
var tunnel = require('tunnel-agent');
var argv = process.argv.slice(2);
var server = argv[0];
var filepath = argv[1];
var token = argv[2];
var id = argv[3];
var type = argv[4];
// check args
if (!server || !filepath || !token || !id) {
console.log('参数错误');
console.log('\t usage: ./uploader server filepath token id');
process.exit(1);
}
// check filepath
fs.stat(filepath, function (err, stat) {
if (err) {
console.log('文件不存在');
console.log(err.message);
process.exit(1);
return;
}
if (stat.size <= 0) {
console.log('空文件');
process.exit(1);
return;
}
var form = formstream();
form.file('file', filepath, filepath, stat.size);
var nonce = '' + parseInt((Math.random() * 100000000000), 10);
// get signature
var shasum = crypto.createHash('sha1');
shasum.update([process.env.agentid || os.hostname(), token, nonce, id].join(''));
var sign = shasum.digest('hex');
var url = 'http://' + server + '/files/' + id + '?nonce=' + nonce + '&sign=' + sign + '&type=' + type;
var gateway = process.env.GATEWAY;
if (gateway) {
// upload to gateway
url = 'http://' + gateway + '/file?target=' + encodeURIComponent(url);
}
var agent = false;
if (process.env.http_proxy) {
var parts = process.env.http_proxy.split(':');
agent = tunnel.httpOverHttp({
proxy: {
host: parts[0],
port: parts[1]
}
});
}
var opts = {
dataType: 'json',
type: 'POST',
timeout: 60000 * 20, // 20分钟超时
headers: form.headers(),
stream: form,
agent: agent
};
urllib.request(url, opts, function (err, data, res) {
if (err) {
throw err;
}
console.log(JSON.stringify(data));
process.exit(0);
});
});