-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
99 lines (87 loc) · 2.67 KB
/
index.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
'use strict';
var AWS = require('aws-sdk'),
URL = require('url'),
http = require('http'),
https = require('https'),
uuid = require('node-uuid'),
path = require('path'),
s3 = new AWS.S3();
var protocols = {
'http:': http,
'https:': https
};
var downloadPdf = function(url, fn) {
var urlObj = URL.parse(url),
protocol = protocols[urlObj.protocol];
if (path.extname(urlObj.pathname) !== '.pdf') {
throw '[URLError] Given url is not a pdf link';
}
protocol.get(url, function(res) {
var chunks = [];
var fileSize = res.headers['content-length'];
var downloadedSize = 0;
// Gets called each time when the buffer is full.
res.on('data', function (chunk) {
downloadedSize += chunk.length;
var percentage=(downloadedSize/fileSize * 100).toFixed(2);
console.log('downloading...' + percentage + '%');
chunks.push(chunk);
});
// Gets called once the stream is finished.
res.on('end', function () {
console.log('finished downloading.');
fn(null, chunks);
});
}).on('error', function(err) {
fn('[CaptureFailure] ' + err);
});
};
var validateKey = function (key) {
var key = key || uuid.v1(),
extension = path.extname(key);
if (!!extension && extension === '.pdf') {
return key;
} else {
return key + '.pdf';
}
};
var uploadToS3 = function(options, data, fn) {
var pdfBuffer = new Buffer.concat(data);
var params = {
Bucket: options.bucketName,
Key: validateKey(options.key),
ContentType: 'application/pdf',
ContentDisposition: 'inline',
Body: pdfBuffer
};
var uploadProgress = 0;
var fileUploadTask = new AWS.S3.ManagedUpload({
params: params,
partSize: options.uploadpartSize,
queueSize: options.uploadQueueSize
});
fileUploadTask.on('httpUploadProgress',function (progress){
uploadProgress = (progress.loaded/progress.total) * 100;
console.log('Upload Progress '+ uploadProgress.toFixed(2));
});
fileUploadTask.send(function(error,data){
if (error) {
console.log('Upload Failed');
} else{
console.log('Upload Completed');
}
});
};
var start = function(options, callback) {
if (!options.url) {
throw '[URLError] Url is empty or not provided.';
}
downloadPdf(options.url, function(err, data) {
if (err) {
throw '[DownloadError] Could not downlod the pdf';
} else {
uploadToS3(options, data, callback);
}
});
};
module.exports.start = start;