2
2
mirror of https://github.com/Llewellynvdm/nativefier.git synced 2024-09-28 20:29:04 +00:00
nativefier/src/infer/inferIcon.js

105 lines
2.9 KiB
JavaScript
Raw Normal View History

import pageIcon from 'page-icon';
2016-01-28 13:13:57 +00:00
import path from 'path';
import fs from 'fs';
import tmp from 'tmp';
import gitCloud from 'gitcloud';
import helpers from './../helpers/helpers';
2016-03-12 07:17:03 +00:00
const {downloadFile, allowedIconFormats} = helpers;
tmp.setGracefulCleanup();
function inferIconFromStore(targetUrl, platform) {
2016-03-12 07:17:03 +00:00
const allowedFormats = allowedIconFormats(platform);
return gitCloud('http://jiahaog.com/nativefier-icons/')
.then(fileIndex => {
2016-03-12 07:17:03 +00:00
const matchingIcons = fileIndex
.filter(item => {
2016-03-12 07:17:03 +00:00
// todo might have problems with matching length, e.g. `book` vs `facebook`
return targetUrl
.toLowerCase()
.includes(item.name);
})
2016-03-12 07:17:03 +00:00
.map(item => {
item.ext = path.extname(item.url);
return item;
});
let matchingUrl;
for (let format of allowedFormats) {
for (let icon of matchingIcons) {
if (icon.ext !== format) {
continue;
}
matchingUrl = icon.url;
}
}
if (!matchingUrl) {
return null;
}
return downloadFile(matchingUrl);
});
}
function writeFilePromise(outPath, data) {
return new Promise((resolve, reject) => {
fs.writeFile(outPath, data, error => {
if (error) {
reject(error);
return;
}
resolve(outPath);
});
});
}
function inferFromPage(targetUrl, platform, outDir) {
2016-03-09 06:50:25 +00:00
let preferredExt = 'png';
if (platform === 'win32') {
preferredExt = 'ico';
}
2016-03-12 07:17:03 +00:00
// todo might want to pass list of preferences instead
return pageIcon(targetUrl, {ext: preferredExt})
.then(icon => {
if (!icon) {
2016-03-12 07:17:03 +00:00
return null;
}
2016-03-12 07:17:03 +00:00
// note that ext from page icon does not contain a '.'
2016-03-08 15:57:19 +00:00
const outfilePath = path.join(outDir, `/icon.${icon.ext}`);
return writeFilePromise(outfilePath, icon.data);
});
2016-01-28 13:13:57 +00:00
}
/**
*
* @param {string} targetUrl
* @param {string} platform
* @param {string} outDir
2016-01-28 13:13:57 +00:00
*/
function inferIconFromUrlToPath(targetUrl, platform, outDir) {
return inferIconFromStore(targetUrl, platform)
2016-03-12 07:17:03 +00:00
.then(icon => {
if (!icon) {
return inferFromPage(targetUrl, platform, outDir);
}
2016-03-12 07:17:03 +00:00
const outfilePath = path.join(outDir, `/icon${icon.ext}`);
return writeFilePromise(outfilePath, icon.data);
});
}
2016-01-28 13:13:57 +00:00
/**
* @param {string} targetUrl
2016-03-09 06:50:25 +00:00
* @param {string} platform
2016-01-28 13:13:57 +00:00
*/
function inferIcon(targetUrl, platform) {
2016-01-28 13:13:57 +00:00
const tmpObj = tmp.dirSync({unsafeCleanup: true});
const tmpPath = tmpObj.name;
return inferIconFromUrlToPath(targetUrl, platform, tmpPath);
2016-01-28 13:13:57 +00:00
}
export default inferIcon;