forked from itgalaxy/favicons
-
Notifications
You must be signed in to change notification settings - Fork 1
/
helpers-es5.js
455 lines (399 loc) · 22.3 KB
/
helpers-es5.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
/* eslint camelcase: 0, no-shadow: 0 */
var path = require('path'),
fs = require('fs'),
_ = require('underscore'),
color = require('tinycolor2'),
cheerio = require('cheerio'),
colors = require('colors'),
jsonxml = require('jsontoxml'),
sizeOf = require('image-size'),
async = require('async'),
mkdirp = require('mkdirp'),
Jimp = require('jimp'),
svg2png = require('svg2png'),
File = require('vinyl'),
Reflect = require('harmony-reflect'),
NRC = require('node-rest-client').Client,
PLATFORM_OPTIONS = require('./config/platform-options.json');
(function () {
'use strict';
var xmlconfig = { prettyPrint: true, xmlHeader: true, indent: ' ' },
client = new NRC(),
HEX_MAX = 255,
NON_EXISTANT = -1,
ROTATE_DEGREES = 90,
HTTP_SUCCESS = 200;
client.setMaxListeners(0);
function helpers(options) {
function contains(array, element) {
return array.indexOf(element.toLowerCase()) > NON_EXISTANT;
}
function relative(directory) {
return path.join(options.path, directory).replace(/\\/g, '/');
}
function print(context, message) {
var newMessage = '';
if (options.logging && message) {
_.each(message.split(' '), function (item) {
newMessage += ' ' + (/^\d+x\d+$/gm.test(item) ? colors.magenta(item) : item);
});
console.log(colors.green('[Favicons]') + ' ' + context.yellow + ':' + newMessage + '...');
}
}
function readFile(filepath, callback) {
fs.readFile(filepath, callback);
}
function updateDocument(document, code, tags, next) {
var $ = cheerio.load(document, { decodeEntities: false }),
target = $('head').length > 0 ? $('head') : $.root(),
newCode = cheerio.load(code.join('\n'), { decodeEntities: false });
async.each(tags, function (platform, callback) {
async.forEachOf(platform, function (tag, selector, cb) {
if (options.replace) {
$(selector).remove();
} else if ($(selector).length) {
newCode(selector).remove();
}
return cb(null);
}, callback);
}, function (error) {
target.append(newCode.html());
return next(error, $.html().replace(/^\s*$[\n\r]{1,}/gm, ''));
});
}
function preparePlatformOptions(platform, options) {
if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) != 'object') {
options = {};
}
_.each(options, function (value, key) {
var platformOptionsRef = PLATFORM_OPTIONS[key];
if (typeof platformOptionsRef == 'undefined' || platformOptionsRef.platforms.indexOf(platform) == -1) {
return Reflect.deleteProperty(options, key);
}
});
_.each(PLATFORM_OPTIONS, function (_ref, key) {
var platforms = _ref.platforms;
var defaultTo = _ref.defaultTo;
if (typeof options[key] == 'undefined' && platforms.indexOf(platform) != -1) {
options[key] = defaultTo;
}
});
return options;
}
return {
General: {
preparePlatformOptions: preparePlatformOptions,
background: function background(hex) {
print('General:background', 'Parsing colour ' + hex);
var rgba = color(hex).toRgb();
return Jimp.rgbaToInt(rgba.r, rgba.g, rgba.b, rgba.a * HEX_MAX);
},
source: function source(_source, callback) {
var sourceset = [];
print('General:source', 'Source type is ' + (typeof _source === 'undefined' ? 'undefined' : _typeof(_source)));
if (!_source || !_source.length) {
return callback('No source provided');
} else if (Buffer.isBuffer(_source)) {
sourceset = [{ size: sizeOf(_source), file: _source }];
callback(null, sourceset);
} else if (Array.isArray(_source)) {
async.each(_source, function (file, cb) {
return readFile(file, function (error, buffer) {
if (error) {
return cb(error);
}
sourceset.push({
size: sizeOf(buffer),
file: buffer
});
cb(null);
});
}, function (error) {
return callback(error || sourceset.length ? null : 'Favicons source is invalid', sourceset);
});
} else if (typeof _source === 'string') {
readFile(_source, function (error, buffer) {
if (error) {
return callback(error);
}
sourceset = [{ size: sizeOf(buffer), file: buffer }];
callback(null, sourceset);
});
} else {
return callback('Invalid source type provided');
}
},
vinyl: function vinyl(object) {
return new File({
path: object.name,
contents: Buffer.isBuffer(object.contents) ? object.contents : new Buffer(object.contents)
});
}
},
HTML: {
parse: function parse(html, callback) {
print('HTML:parse', 'HTML found, parsing and modifying source');
var $ = cheerio.load(html),
link = $('*').is('link'),
attribute = link ? 'href' : 'content',
value = $('*').first().attr(attribute);
if (path.extname(value)) {
$('*').first().attr(attribute, relative(value));
} else if (value.slice(0, 1) === '#') {
$('*').first().attr(attribute, options.background);
} else if (html.indexOf('application-name') !== NON_EXISTANT || html.indexOf('apple-mobile-web-app-title') !== NON_EXISTANT) {
$('*').first().attr(attribute, options.appName);
}
return callback(null, $.html());
},
update: function update(document, code, tags, callback) {
var encoding = { encoding: 'utf8' };
async.waterfall([function (cb) {
return mkdirp(path.dirname(document), cb);
}, function (made, cb) {
return fs.readFile(document, encoding, function (error, data) {
return cb(null, error ? null : data);
});
}, function (data, cb) {
return data ? updateDocument(data, code, tags, cb) : cb(null, code.join('\n'));
}, function (html, cb) {
return fs.writeFile(document, html, options, cb);
}], callback);
}
},
Files: {
create: function create(properties, name, callback) {
print('Files:create', 'Creating file: ' + name);
if (name === 'manifest.json') {
properties.name = options.appName;
properties.short_name = options.appShortName;
properties.description = options.appDescription;
properties.dir = options.dir;
properties.lang = options.lang;
properties.display = options.display;
properties.orientation = options.orientation;
properties.start_url = options.start_url;
properties.background_color = options.background;
properties.theme_color = options.theme_color;
_.map(properties.icons, function (icon) {
return icon.src = relative(icon.src);
});
properties = JSON.stringify(properties, null, 2);
} else if (name === 'manifest.webapp') {
properties.version = options.version;
properties.name = options.appName;
properties.description = options.appDescription;
properties.developer.name = options.developerName;
properties.developer.url = options.developerURL;
properties.icons = _.mapObject(properties.icons, function (property) {
return relative(property);
});
properties = JSON.stringify(properties, null, 2);
} else if (name === 'browserconfig.xml') {
_.map(properties[0].children[0].children[0].children, function (property) {
if (property.name === 'TileColor') {
property.text = options.background;
} else {
property.attrs.src = relative(property.attrs.src);
}
});
properties = jsonxml(properties, xmlconfig);
} else if (name === 'yandex-browser-manifest.json') {
properties.version = options.version;
properties.api_version = 1;
properties.layout.logo = relative(properties.layout.logo);
properties.layout.color = options.background;
properties = JSON.stringify(properties, null, 2);
} else if (/\.html$/.test(name)) {
properties = properties.join('\n');
}
return callback(null, { name: name, contents: properties });
}
},
Images: {
create: function create(properties, background, callback) {
var jimp = null;
print('Image:create', 'Creating empty ' + properties.width + 'x' + properties.height + ' canvas with ' + (properties.transparent ? 'transparent' : background) + ' background');
jimp = new Jimp(properties.width, properties.height, properties.transparent ? 0x00000000 : background, function (error, canvas) {
return callback(error, canvas, jimp);
});
},
read: function read(file, callback) {
print('Image:read', 'Reading file: ' + file.buffer);
return Jimp.read(file, callback);
},
nearest: function nearest(sourceset, properties, offset, callback) {
print('Image:nearest', 'Find nearest icon to ' + properties.width + 'x' + properties.height + ' with offset ' + offset);
var offsetSize = offset * 2,
width = properties.width - offsetSize,
height = properties.height - offsetSize,
sideSize = Math.max(width, height),
svgSource = _.find(sourceset, function (source) {
return source.size.type == 'svg';
});
var nearestIcon = sourceset[0],
nearestSideSize = Math.max(nearestIcon.size.width, nearestIcon.size.height);
if (svgSource) {
print('Image:nearest', 'SVG source will be saved as ' + width + 'x' + height);
svg2png(svgSource.file, { height: height, width: width }).then(function (resizedBuffer) {
return callback(null, {
size: sizeOf(resizedBuffer),
file: resizedBuffer
});
}).catch(callback);
} else {
_.each(sourceset, function (icon) {
var max = Math.max(icon.size.width, icon.size.height);
if ((nearestSideSize > max || nearestSideSize < sideSize) && max >= sideSize) {
nearestIcon = icon;
nearestSideSize = max;
}
});
callback(null, nearestIcon);
}
},
resize: function resize(image, properties, offset, callback) {
print('Images:resize', 'Resizing image to contain in ' + properties.width + 'x' + properties.height + ' with offset ' + offset);
var offsetSize = offset * 2;
image.contain(properties.width - offsetSize, properties.height - offsetSize, Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE);
return callback(null, image);
},
composite: function composite(canvas, image, properties, offset, maximum, callback) {
var offsetSize = offset * 2,
maximumWithOffset = maximum - offsetSize,
offsetHeight = properties.height - maximumWithOffset > 0 ? (properties.height - maximumWithOffset) / 2 : 0,
offsetWidth = properties.width - maximumWithOffset > 0 ? (properties.width - maximumWithOffset) / 2 : 0,
circle = path.join(__dirname, 'mask.png'),
overlay = path.join(__dirname, 'overlay.png');
if (properties.rotate) {
print('Images:composite', 'Rotating image by ' + ROTATE_DEGREES);
image.rotate(ROTATE_DEGREES);
}
var compositeIcon = function compositeIcon() {
print('Images:composite', 'Compositing ' + maximum + 'x' + maximum + ' favicon on ' + properties.width + 'x' + properties.height + ' canvas with offset ' + offset);
canvas.composite(image, offsetWidth, offsetHeight);
};
if (properties.mask) {
print('Images:composite', 'Masking composite image on circle');
async.parallel([function (cb) {
return Jimp.read(circle, cb);
}, function (cb) {
return Jimp.read(overlay, cb);
}], function (error, images) {
images[0].resize(maximum, Jimp.AUTO);
images[1].resize(maximum, Jimp.AUTO);
canvas.mask(images[0], 0, 0);
canvas.composite(images[1], 0, 0);
compositeIcon();
return callback(error, canvas);
});
} else {
compositeIcon();
return callback(null, canvas);
}
},
getBuffer: function getBuffer(canvas, callback) {
print('Images:getBuffer', 'Collecting image buffer from canvas');
canvas.getBuffer(Jimp.MIME_PNG, callback);
}
},
RFG: {
configure: function configure(sourceset, request, callback) {
print('RFG:configure', 'Configuring RFG API request');
var svgSource = _.find(sourceset, function (source) {
return source.size.type == 'svg';
});
options.background = '#' + color(options.background).toHex();
request.master_picture.content = (svgSource || _.max(sourceset, function (_ref2) {
var _ref2$size = _ref2.size;
var width = _ref2$size.width;
var height = _ref2$size.height;
return Math.max(width, height);
})).file.toString('base64');
request.files_location.path = options.path;
if (options.icons.android) {
request.favicon_design.android_chrome.theme_color = options.background;
request.favicon_design.android_chrome.manifest.name = options.appName;
request.favicon_design.android_chrome.manifest.display = options.display;
request.favicon_design.android_chrome.manifest.orientation = options.orientation;
} else {
Reflect.deleteProperty(request.favicon_design, 'android_chrome');
}
if (options.icons.appleIcon) {
var appleIconOptions = preparePlatformOptions('appleIcon', options.icons.appleIcon);
request.favicon_design.ios.background_color = options.background;
request.favicon_design.ios.margin = Math.round(57 / 100 * appleIconOptions.offset);
} else {
Reflect.deleteProperty(request.favicon_design, 'ios');
}
if (options.icons.appleStartup) {
request.favicon_design.ios.startup_image.background_color = options.background;
} else if (request.favicon_design.ios) {
Reflect.deleteProperty(request.favicon_design.ios, 'startup_image');
}
if (options.icons.coast) {
var coastOptions = preparePlatformOptions('coast', options.icons.coast);
request.favicon_design.coast.background_color = options.background;
request.favicon_design.coast.margin = Math.round(228 / 100 * coastOptions.offset);
} else {
Reflect.deleteProperty(request.favicon_design, 'coast');
}
if (!options.icons.favicons) {
Reflect.deleteProperty(request.favicon_design, 'desktop_browser');
}
if (options.icons.firefox) {
var firefoxOptions = preparePlatformOptions('firefox', options.icons.firefox);
request.favicon_design.firefox_app.background_color = options.background;
request.favicon_design.firefox_app.margin = Math.round(60 / 100 * firefoxOptions.offset);
request.favicon_design.firefox_app.manifest.app_name = options.appName;
request.favicon_design.firefox_app.manifest.app_description = options.appDescription;
request.favicon_design.firefox_app.manifest.developer_name = options.developerName;
request.favicon_design.firefox_app.manifest.developer_url = options.developerURL;
} else {
Reflect.deleteProperty(request.favicon_design, 'firefox_app');
}
if (options.icons.windows) {
request.favicon_design.windows.background_color = options.background;
} else {
Reflect.deleteProperty(request.favicon_design, 'windows');
}
if (options.icons.yandex) {
request.favicon_design.yandex_browser.background_color = options.background;
request.favicon_design.yandex_browser.manifest.version = options.version;
} else {
Reflect.deleteProperty(request.favicon_design, 'yandex_browser');
}
return callback(null, request);
},
request: function request(_request, callback) {
print('RFG:request', 'Posting a request to the RFG API');
client.post('http://realfavicongenerator.net/api/favicon', {
data: { favicon_generation: _request },
headers: { 'Content-Type': 'application/json' }
}, function (data, response) {
var result = data.favicon_generation_result;
return result && response.statusCode === HTTP_SUCCESS ? callback(null, {
files: result.favicon.files_urls,
html: result.favicon.html_code
}) : callback(result.result.error_message);
});
},
fetch: function fetch(address, callback) {
var name = path.basename(address),
image = contains(['.png', '.jpg', '.bmp', '.ico', '.svg'], path.extname(name));
print('RFG:fetch', 'Fetching ' + (image ? 'image' : 'file') + ' from RFG: ' + address);
client.get(address, function (buffer, response) {
var success = buffer && response.statusCode === HTTP_SUCCESS;
return success ? callback(null, {
file: image ? null : { name: name, contents: buffer },
image: image ? { name: name, contents: buffer } : null
}) : callback('Could not fetch URL: ' + address);
});
}
}
};
}
module.exports = helpers;
})();