2
2
mirror of https://github.com/Llewellynvdm/nativefier.git synced 2024-12-23 10:38:55 +00:00

Implement automatic retrieval of png

This commit is contained in:
Jia Hao 2016-01-28 21:13:57 +08:00
parent 63a539cd69
commit ecbb84146f
2 changed files with 98 additions and 14 deletions

62
src/inferIcon.js Normal file
View File

@ -0,0 +1,62 @@
import request from 'request';
import path from 'path';
import fs from 'fs';
import tmp from 'tmp';
tmp.setGracefulCleanup();
const BEST_ICON_API = 'http://localhost: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: 1000,
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;

View File

@ -7,10 +7,12 @@ import cheerio from 'cheerio';
import validator from 'validator';
import sanitize from 'sanitize-filename';
import _ from 'lodash';
import async from 'async';
import inferIcon from './inferIcon';
const TEMPLATE_APP_DIR = path.join(__dirname, '../', 'app');
const ELECTRON_VERSION = '0.36.4';
const DEFAULT_APP_NAME = 'My App';
const DEFAULT_APP_NAME = 'APP';
function optionsFactory(name,
targetUrl,
@ -69,9 +71,25 @@ function optionsFactory(name,
insecure: insecure
};
async.waterfall([
callback => {
if (options.icon) {
callback(null, options);
return;
}
inferIcon(options.targetUrl, (error, pngPath) => {
if (error) {
console.warn('Cannot automatically retrieve the app icon:', error);
} else {
options.icon = pngPath;
}
callback(null, options);
});
},
(options, callback) => {
if (name && name.length > 0) {
options.name = name;
callback(null, sanitizeOptions(options));
callback(null, options);
return;
}
@ -83,7 +101,11 @@ function optionsFactory(name,
options.name = pageTitle;
}
callback(null, sanitizeOptions(options));
callback(null, options);
});
}
], (error, options) => {
callback(error, sanitizeOptions(options));
});
}