net.js
7.79 KB
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
import _ from 'lodash';
import fs from './fs';
import url from 'url';
import B from 'bluebird';
import { toReadableSizeString } from './util';
import log from './logger';
import Ftp from 'jsftp';
import Timer from './timing';
import axios from 'axios';
import FormData from 'form-data';
function toAxiosAuth (auth) {
if (!_.isPlainObject(auth)) {
return null;
}
const axiosAuth = {
username: auth.username || auth.user,
password: auth.password || auth.pass,
};
return (axiosAuth.username && axiosAuth.password) ? axiosAuth : null;
}
async function uploadFileToHttp (localFileStream, parsedUri, uploadOptions = {}) {
const {
method = 'POST',
timeout = 5000,
headers,
auth,
fileFieldName = 'file',
formFields,
} = uploadOptions;
const { href } = parsedUri;
const requestOpts = {
url: href,
method,
timeout,
maxContentLength: Infinity,
maxBodyLength: Infinity,
};
const axiosAuth = toAxiosAuth(auth);
if (axiosAuth) {
requestOpts.auth = axiosAuth;
}
if (fileFieldName) {
const form = new FormData();
form.append(fileFieldName, localFileStream);
if (formFields) {
let pairs = [];
if (_.isArray(formFields)) {
pairs = formFields;
} else if (_.isPlainObject(formFields)) {
pairs = _.toPairs(formFields);
}
for (const [key, value] of pairs) {
if (_.toLower(key) !== _.toLower(fileFieldName)) {
form.append(key, value);
}
}
}
requestOpts.headers = Object.assign({}, _.isPlainObject(headers) ? headers : {},
form.getHeaders());
requestOpts.data = form;
} else {
if (_.isPlainObject(headers)) {
requestOpts.headers = headers;
}
requestOpts.data = localFileStream;
}
log.debug(`Performing ${method} to ${href} with options (excluding data): ` +
JSON.stringify(_.omit(requestOpts, ['data'])));
const {status, statusText} = await axios(requestOpts);
log.info(`Server response: ${status} ${statusText}`);
}
async function uploadFileToFtp (localFileStream, parsedUri, uploadOptions = {}) {
const {
auth,
user,
pass,
} = uploadOptions;
const {
hostname,
port,
protocol,
pathname,
} = parsedUri;
const ftpOpts = {
host: hostname,
port: port || 21,
};
if ((auth?.user && auth?.pass) || (user && pass)) {
ftpOpts.user = auth?.user || user;
ftpOpts.pass = auth?.pass || pass;
}
log.debug(`${protocol} upload options: ${JSON.stringify(ftpOpts)}`);
return await new B((resolve, reject) => {
new Ftp(ftpOpts).put(localFileStream, pathname, (err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
/**
* @typedef {Object} AuthCredentials
* @property {string} user - Non-empty user name
* @property {string} pass - Non-empty password
*/
/**
* @typedef {Object} FtpUploadOptions
* @property {boolean} isMetered [true] - Whether to log the actual upload performance
* (e.g. timings and speed)
* @property {AuthCredentials} auth
*/
/**
* @typedef {Object} HttpUploadOptions
* @property {boolean} isMetered [true] - Whether to log the actual upload performance
* (e.g. timings and speed)
* @property {string} method [POST] - The HTTP method used for file upload
* @property {AuthCredentials} auth
* @property {number} timeout [5000] - The actual request timeout in milliseconds
* @property {Object} headers - Additional request headers mapping
* @property {?string} fileFieldName [file] - The name of the form field containing the file
* content to be uploaded. Any falsy value make the request to use non-multipart upload
* @property {Array<Pair>|Object} formFields - The additional form fields
* to be included into the upload request. This property is only considered if
* `fileFieldName` is set
*/
/**
* Uploads the given file to a remote location. HTTP(S) and FTP
* protocols are supported.
*
* @param {string} localPath - The path to a file on the local storage.
* @param {string} remoteUri - The remote URI to upload the file to.
* @param {?FtpUploadOptions|HttpUploadOptions} uploadOptions
*/
async function uploadFile (localPath, remoteUri, uploadOptions = {}) {
if (!await fs.exists(localPath)) {
throw new Error (`'${localPath}' does not exists or is not accessible`);
}
const {
isMetered = true,
} = uploadOptions;
const parsedUri = url.parse(remoteUri);
const {size} = await fs.stat(localPath);
if (isMetered) {
log.info(`Uploading '${localPath}' of ${toReadableSizeString(size)} size to '${remoteUri}'`);
}
const timer = new Timer().start();
if (['http:', 'https:'].includes(parsedUri.protocol)) {
if (!uploadOptions.fileFieldName) {
uploadOptions.headers = Object.assign({},
_.isPlainObject(uploadOptions.headers) ? uploadOptions.headers : {},
{'Content-Length': size}
);
}
await uploadFileToHttp(fs.createReadStream(localPath), parsedUri, uploadOptions);
} else if (parsedUri.protocol === 'ftp:') {
await uploadFileToFtp(fs.createReadStream(localPath), parsedUri, uploadOptions);
} else {
throw new Error(`Cannot upload the file at '${localPath}' to '${remoteUri}'. ` +
`Unsupported remote protocol '${parsedUri.protocol}'. ` +
`Only http/https and ftp/ftps protocols are supported.`);
}
if (isMetered) {
log.info(`Uploaded '${localPath}' of ${toReadableSizeString(size)} size in ` +
`${timer.getDuration().asSeconds.toFixed(3)}s`);
}
}
/**
* @typedef {Object} DownloadOptions
* @property {boolean} isMetered [true] - Whether to log the actual download performance
* (e.g. timings and speed)
* @property {AuthCredentials} auth
* @property {number} timeout [5000] - The actual request timeout in milliseconds
* @property {Object} headers - Request headers mapping
*/
/**
* Downloads the given file via HTTP(S)
*
* @param {string} remoteUrl - The remote url
* @param {string} dstPath - The local path to download the file to
* @param {?DownloadOptions} downloadOptions
* @throws {Error} If download operation fails
*/
async function downloadFile (remoteUrl, dstPath, downloadOptions = {}) {
const {
isMetered = true,
auth,
timeout = 5000,
headers,
} = downloadOptions;
const requestOpts = {
url: remoteUrl,
responseType: 'stream',
timeout,
};
const axiosAuth = toAxiosAuth(auth);
if (axiosAuth) {
requestOpts.auth = axiosAuth;
}
if (_.isPlainObject(headers)) {
requestOpts.headers = headers;
}
const timer = new Timer().start();
let responseLength;
try {
const writer = fs.createWriteStream(dstPath);
const {
data: responseStream,
headers: responseHeaders,
} = await axios(requestOpts);
responseLength = parseInt(responseHeaders['content-length'], 10);
responseStream.pipe(writer);
await new B((resolve, reject) => {
responseStream.once('error', reject);
writer.once('finish', resolve);
writer.once('error', (e) => {
responseStream.unpipe(writer);
reject(e);
});
});
} catch (err) {
throw new Error(`Cannot download the file from ${remoteUrl}: ${err.message}`);
}
const {size} = await fs.stat(dstPath);
if (responseLength && size !== responseLength) {
await fs.rimraf(dstPath);
throw new Error(`The size of the file downloaded from ${remoteUrl} (${size} bytes) ` +
`differs from the one in Content-Length response header (${responseLength} bytes)`);
}
if (isMetered) {
const secondsElapsed = timer.getDuration().asSeconds;
log.debug(`${remoteUrl} (${toReadableSizeString(size)}) ` +
`has been downloaded to '${dstPath}' in ${secondsElapsed.toFixed(3)}s`);
if (secondsElapsed >= 2) {
const bytesPerSec = Math.floor(size / secondsElapsed);
log.debug(`Approximate download speed: ${toReadableSizeString(bytesPerSec)}/s`);
}
}
}
export { uploadFile, downloadFile };