-
Notifications
You must be signed in to change notification settings - Fork 1
/
nuget.js
100 lines (77 loc) · 2.84 KB
/
nuget.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
var http = require('http');
var url = require('url');
var fs = require('fs');
var logOptions = function(protocol, options) {
if (options.port !== undefined) {
console.log(options.method + ' ' + protocol + '://' + options.host + ':' + options.port + options.path);
}
else {
console.log(options.method + ' ' + protocol + '://' + options.host + options.path);
}
}
//TODO: consider passing in the destination stream rather than then folder...
var downloadPackage = function (protocol, host, port, path, userAgent, folder, callback) {
var options = {
host: host,
path: path,
method: 'GET',
headers: { 'User-Agent': userAgent, 'NuGet-Operation': 'Install' }
};
if (port !== undefined) {
options.port = port;
}
logOptions(protocol, options);
var channel;
if (protocol === 'http') {
channel = require('http');
}
else {
channel = require('https');
}
var req = channel.request(options, function (res) {
if (res.statusCode > 300 && res.statusCode < 400 && res.headers.location) {
var location = url.parse(res.headers.location);
if (location.host) {
downloadPackage(location.protocol, location.host, location.port, location.path, userAgent, folder, callback);
} else {
downloadPackage(location.protocol, options.host, options.port, location.path, userAgent, folder, callback);
}
}
else if (res.statusCode != 200) {
callback({ protocol: protocol, request: options, statusCode: res.statusCode }, null)
return;
}
else {
if (res.headers['content-disposition']) {
var filename = res.headers['content-disposition'].replace(/^.*filename=/, '').replace(/^"|$"/g, '');
}
else {
// we must be getting the nupkg from blob storage and there seems to be
// no content-disposition header so extra one from the request URI
var filename = options.path.substr(options.path.lastIndexOf('/') + 1);
}
var writeStream = fs.createWriteStream(folder.replace(/\/$/, '') + '/' + filename);
res.pipe(writeStream);
res.on('end', function () {
writeStream.end();
callback(null, filename);
});
writeStream.on('error', function (e) {
callback(e, null);
});
}
});
req.end();
req.on('error', function (e) {
callback('error', null);
});
}
var packagePath = function (name, version) {
var path = '/api/v2/Package/' + name;
if (version !== null) {
path += '/' + version;
}
return path;
}
exports.downloadPackage = downloadPackage;
exports.packagePath = packagePath;