keeweb/app/scripts/comp/transport.js

73 lines
2.6 KiB
JavaScript
Raw Normal View History

2015-11-13 20:56:22 +01:00
'use strict';
2015-12-12 09:53:50 +01:00
var Launcher = require('./launcher'),
Logger = require('../util/logger');
var logger = new Logger('transport');
2015-11-13 20:56:22 +01:00
var Transport = {
httpGet: function(config) {
var tmpFile;
var fs = Launcher.req('fs');
if (config.file) {
tmpFile = Launcher.getTempPath(config.file);
if (fs.existsSync(tmpFile)) {
try {
if (config.cache && fs.statSync(tmpFile).size > 0) {
2015-12-12 09:53:50 +01:00
logger.info('File already downloaded ' + config.url);
2015-11-13 20:56:22 +01:00
return config.success(tmpFile);
} else {
fs.unlinkSync(tmpFile);
}
} catch (e) {
fs.unlink(tmpFile);
}
}
}
var proto = config.url.split(':')[0];
2015-12-12 09:53:50 +01:00
logger.info('GET ' + config.url);
2015-11-14 17:58:34 +01:00
var opts = Launcher.req('url').parse(config.url);
opts.headers = { 'User-Agent': navigator.userAgent };
Launcher.req(proto).get(opts, function(res) {
2015-12-12 09:53:50 +01:00
logger.info('Response from ' + config.url + ': ' + res.statusCode);
2015-11-13 20:56:22 +01:00
if (res.statusCode === 200) {
if (config.file) {
var file = fs.createWriteStream(tmpFile);
res.pipe(file);
file.on('finish', function() {
file.close(function() { config.success(tmpFile); });
});
file.on('error', function(err) { config.error(err); });
} else {
var data = [];
res.on('data', function(chunk) { data.push(chunk); });
res.on('end', function() {
data = window.Buffer.concat(data);
if (config.utf8) {
data = data.toString('utf8');
}
config.success(data);
});
}
2015-11-22 13:03:54 +01:00
} else if (res.headers.location && [301, 302].indexOf(res.statusCode) >= 0) {
if (config.noRedirect) {
return config.error('Too many redirects');
}
config.url = res.headers.location;
config.noRedirect = true;
Transport.httpGet(config);
2015-11-13 20:56:22 +01:00
} else {
config.error('HTTP status ' + res.statusCode);
}
}).on('error', function(e) {
2015-12-12 09:53:50 +01:00
logger.error('Cannot GET ' + config.url, e);
2015-11-13 20:56:22 +01:00
if (tmpFile) {
fs.unlink(tmpFile);
}
config.error(e);
});
}
};
module.exports = Transport;