-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
166 lines (151 loc) · 3.85 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
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
// through2 is a thin wrapper around node transform streams
var through = require('through2');
var prettyBytes = require('pretty-bytes');
var log = require('fancy-log');
var chalk = require('chalk');
var PluginError = require('plugin-error');
var mkdirp = require('mkdirp');
var rmdir = require('rmdir');
var request = require('request');
var path = require('path');
var inspect = require('util').inspect;
var fs = require('fs');
var md5 = require('md5');
var AUTH_TOKEN;
// Consts
const PLUGIN_NAME = 'gulp-tinypng';
const TEMP_DIR = '.gulp/tinypng/';
function prefixStream(prefixText) {
var stream = through();
stream.write(prefixText);
return stream;
}
var createTempDir = function() {
fs.access('.gulp/tinypng', fs.F_OK, function(err) {
if (err) {
mkdirp('.gulp/tinypng', function(err) {
if (err) {
console.error('Error creating temp folder');
}
});
}
});
}
var cleanTemp = function() {
rmdir('.gulp/tinypng', function(err, dirs, files) {
mkdirp('.gulp/tinypng', function(err) {
if (err) {
console.error('Error creating temp folder');
}
});
});
};
var download = function(uri, filename, complete) {
request.head(uri, function(err, res, body) {
request({
url: uri,
strictSSL: false
})
.pipe(fs.createWriteStream(TEMP_DIR + filename))
.on('close', function() {
complete();
});
});
};
var readTemp = function(filename, cb) {
fs.readFile('.gulp/tinypng/' + filename, function(err, data) {
if (err) {
return cb(new PluginError('gulp-tinypng', err));
}
cb(null, data);
});
};
// Plugin level function (dealing with files)
function gulpPrefixer(options) {
var apiKey = options.apiKey;
var cached = options.cached;
AUTH_TOKEN = new Buffer('api:' + apiKey).toString('base64')
if (!apiKey) {
throw new PluginError(PLUGIN_NAME, "Missing api key!");
}
apiKey = new Buffer(apiKey); // allocate ahead of time
if (!cached) {
cleanTemp();
} else {
createTempDir();
}
// Creating a stream through which each file will pass
var stream = through.obj(function(file, enc, callback) {
if (file.isNull()) {
this.push(file); // Do nothing if no contents
return callback();
}
if (file.isBuffer()) {
var prevLength = file.contents.length;
tinypng(file, function(data) {
file.contents = data;
this.push(file);
log('gulp-tinypng: ', chalk.green('✔ ') + file.relative + ' (saved ' +
prettyBytes(prevLength - data.length) + ' - ' + ((1 - data.length / prevLength) * 100).toFixed(0) + '%)');
return callback();
}.bind(this));
}
if (file.isStream()) {
throw new PluginError(PLUGIN_NAME, "Stream is not supported");
return callback();
}
});
// returning the file stream
return stream;
};
var tinyNewPng = function(file, cb) {
request({
url: 'https://api.tinypng.com/shrink',
method: 'POST',
strictSSL: false,
headers: {
'Accept': '*/*',
'Cache-Control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + AUTH_TOKEN
},
body: file.contents
}, function(error, response, body) {
var results, filename;
if (!error) {
// filename = path.basename(file.path);
filename = md5(file.contents);
results = JSON.parse(body);
// size
// ratio
// url
if (results.output && results.output.url) {
download(results.output.url, filename, function() {
fs.readFile(TEMP_DIR + filename, function(err, data) {
if (err) {
log('[error] : gulp-tinypng - ', err);
}
cb(data);
});
});
} else {
log('[error] : gulp-tinypng - ', results.message);
}
}
});
}
function tinypng(file, cb) {
var tmpFileName = md5(file.contents);
// console.log(tmpFileName);
readTemp(tmpFileName, function(err, tmpFile) {
if (err) {
tinyNewPng(file, function(data) {
cb(data);
})
} else {
cb(tmpFile);
}
})
};
// Exporting the plugin main function
module.exports = gulpPrefixer;