-
Notifications
You must be signed in to change notification settings - Fork 33
/
document-downloader.js
172 lines (149 loc) · 5.43 KB
/
document-downloader.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
/**
* @file Download file from tar file or manifest url, called by orchestrator.js
*/
'use strict';
import Fs from 'fs';
import Request from 'request';
import pkg from 'immutable';
import Promise from 'promise';
import Url from 'url';
import { mkdirp } from 'mkdirp';
import { dirname } from 'path';
import { fileTypeFromBuffer } from 'file-type';
import tar from 'tar-stream';
const { List } = pkg;
/**
* @exports lib/document-downloader
*/
const DocumentDownloader = {};
DocumentDownloader.fetch = url =>
new Promise((resolve, reject) => {
Request.get(
url,
{
timeout: 30000,
encoding: null, // If not specified, utf8 by default
},
(error, response, body) => {
if (error) {
reject(
new Error(
`Fetching ${url} triggered a network error: ${error.message}`,
),
);
} else if (response.statusCode !== 200) {
reject(
new Error(
`Fetching ${url} triggered an HTTP error: code ${response.statusCode}`,
),
);
} else resolve(body);
},
);
});
DocumentDownloader.fetchAll = urls =>
Promise.all(urls.toArray().map(DocumentDownloader.fetch)).then(List);
DocumentDownloader.install = (dest, content) => {
const path = dirname(dest);
mkdirp.sync(path);
return Promise.denodeify(Fs.writeFile)(dest, content);
};
DocumentDownloader.installAll = destsContents =>
// `e` is a tuple of [dest, content]
Promise.all(
destsContents.toArray().map(e => DocumentDownloader.install(e[0], e[1])),
);
/**
* Checks if a given filename is allowed to be published by the system.
*
* @param {string} filename - The filename to check against
* @returns {boolean} `true` if the filename is allowed, `false` otherwise
*/
DocumentDownloader.isAllowed = function isAllowed(filename) {
if (filename.toLowerCase().indexOf('.htaccess') !== -1) return false;
if (filename.toLowerCase().indexOf('.php') !== -1) return false;
if (filename.indexOf('CVS') !== -1) return false;
if (filename.indexOf('../') !== -1) return false;
if (filename.indexOf('://') !== -1) return false;
return true;
};
DocumentDownloader.fetchAndInstall = (url, dest) => {
const _ = DocumentDownloader; // Class name shortener
const mkdir = Promise.denodeify(Fs.mkdir);
return new Promise(resolve => {
Fs.access(dest, Fs.constants.F_OK, error => {
resolve(!error);
});
})
.then(pathExists => (!pathExists ? mkdir(dest) : null))
.then(() =>
_.fetch(url).then(content =>
fileTypeFromBuffer(content).then(type => {
if (type && type.mime !== 'application/x-tar') {
throw new TypeError('Only tar, html and manifest are supported.');
} else if (type && type.mime === 'application/x-tar') {
return new Promise((resolve, reject) => {
const extract = tar.extract();
let hasOverview = false;
extract.on('entry', (header, stream, callback) => {
stream.on('data', data => {
if (_.isAllowed(header.name)) {
if (header.name === 'Overview.html') {
hasOverview = true;
}
const path = dirname(`${dest}/${header.name}`);
mkdirp.sync(path);
Fs.writeFileSync(`${dest}/${header.name}`, data);
}
});
stream.on('end', () => {
callback();
});
});
extract.on('finish', () =>
hasOverview
? resolve()
: reject(new Error('No Overview.html in the tarball.')),
);
extract.end(content);
});
} else {
const contentUtf8 = content.toString('utf8');
// html files link <!DOCTYPE html> starts with '<'
if (contentUtf8.trim().charAt(0) !== '<') {
const filenames = _.getFilenames(contentUtf8).filter(_.isAllowed);
const dests = filenames
.set(0, 'Overview.html')
.map(filename => `${dest}/${filename}`);
const urls = filenames.map(filename => {
// If an entry in the manifest had a space in it,
// we assume it needs to be built from the spec-generator.
// See https://github.com/w3c/spec-generator
const specGeneratorComp = filename.split(' ');
const absUrl = new Url.URL(specGeneratorComp[0], url);
if (specGeneratorComp.length === 2) {
return `${global.SPEC_GENERATOR}?type=${encodeURIComponent(
specGeneratorComp[1],
)}&url=${encodeURIComponent(absUrl)}`;
}
return absUrl;
});
return _.fetchAll(urls).then(contents =>
// dests.zip(contents) -> [['Overview.html', '<!DOCTYPE>...'], ...]
_.installAll(dests.zip(contents)),
);
}
return _.install(`${dest}/Overview.html`, content);
}
}),
),
);
};
DocumentDownloader.getFilenames = function getFilenames(manifest) {
return manifest.split('\n').reduce((acc, line) => {
const filename = line.split('#')[0].trim();
if (filename !== '') return acc.push(filename);
return acc;
}, new List());
};
export default DocumentDownloader;