2
2
mirror of https://github.com/Llewellynvdm/nativefier.git synced 2024-06-29 00:23:47 +00:00
nativefier/src/inferIcon.js
2016-01-28 23:56:29 +08:00

63 lines
1.5 KiB
JavaScript

import request from 'request';
import path from 'path';
import fs from 'fs';
import tmp from 'tmp';
tmp.setGracefulCleanup();
const BEST_ICON_API = 'http://45.55.116.63:8080/icon';
/**
*
* @param {string} targetUrl
* @param {string} outDir
* @param {inferIconCallback} callback
*/
function inferIconFromUrlToPath(targetUrl, outDir, callback) {
const outfilePath = path.join(outDir, '/icon.png');
request({
url: BEST_ICON_API,
qs: {
url: targetUrl,
size: 57,
formats: 'png'
},
encoding: null
}, (error, response, body) => {
if (error) {
callback(error);
return;
}
try {
const parsedError = JSON.parse(body).error;
callback(parsedError);
} catch (exception) {
if (/<html>/i.test(body)) {
callback('BestIcon server 502 error');
return;
}
// body is an image
fs.writeFile(outfilePath, body, error => {
callback(error, outfilePath);
});
}
});
}
/**
* @callback inferIconCallback
* @param error
* @param {string} [iconPath]
*/
/**
* @param {string} targetUrl
* @param {inferIconCallback} callback
*/
function inferIcon(targetUrl, callback) {
const tmpObj = tmp.dirSync({unsafeCleanup: true});
const tmpPath = tmpObj.name;
inferIconFromUrlToPath(targetUrl, tmpPath, callback);
}
export default inferIcon;