-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblurrd.js
136 lines (92 loc) · 2.6 KB
/
blurrd.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
'use strict';
var _ = require('lodash'),
gm = require('gm'),
url = require('url'),
path = require('path'),
cheerio = require('cheerio'),
request = require('request');
if(typeof Promise !== 'function') {
var Promise = require('bluebird');
}
module.exports = function(src, options) {
return new Promise(function(resolve, reject) {
var funcs;
options = _.merge({
cheerio: {},
selector: 'img',
max: 24,
quality: 60,
dlProtocol: 'http:',
transformer: 'basic',
transformerOpts: {}
}, options);
if(typeof options.transformer === 'object') {
funcs = options.transformer;
} else if(typeof options.transformer === 'string') {
try {
funcs = require(options.transformer);
} catch(err) {
funcs = undefined;
}
if(!funcs) {
try {
funcs = require(path.join(__dirname, 'transformers', options.transformer));
} catch(err) {
throw new Error(options.transformer + ' is not a valid path or one of the default transformers');
}
}
} else {
throw new Error('malformed option for transformer');
}
[
'prepareImg',
'inject'
].forEach(function(key) {
if(typeof funcs[key] !== 'function') {
throw new Error(`transformer must have a ${key} function`);
}
});
var imgPromises = [];
var $ = cheerio.load(src, options.cheerio),
imgElements = $(options.selector);
imgElements.each(function(index, el) {
el = $(this);
imgPromises.push(new Promise(function(resolve, reject) {
var src = el.attr('src'),
dlSrc = url.parse(src);
if (!dlSrc.protocol) {
dlSrc.protocol = options.dlProcotol;
}
request({
url: url.format(dlSrc),
encoding: null
}, function(err, res, body) {
if(err) {
reject(err);
} else {
gm(body)
.resize(options.max, options.max)
.noProfile()
.quality(options.quality)
.strip()
.type('optimize')
.toBuffer('JPG', function(err, raw) {
if(err) {
reject(err);
} else {
funcs.prepareImg(src, raw, el, options.transformerOpts);
resolve();
}
});
}
});
}));
});
Promise.all(imgPromises).then(function() {
funcs.inject($, options.transformerOpts);
resolve($.html());
}, function(err) {
reject(err);
});
});
};