Nativefier/src/infer/inferIcon.js

104 lines
2.9 KiB
JavaScript
Raw Normal View History

import pageIcon from 'page-icon';
2016-01-28 14:13:57 +01: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 08:17:03 +01:00
const {downloadFile, allowedIconFormats} = helpers;
tmp.setGracefulCleanup();
function inferIconFromStore(targetUrl, platform) {
2016-03-12 08:17:03 +01:00
const allowedFormats = allowedIconFormats(platform);
return gitCloud('http://jiahaog.com/nativefier-icons/')
.then(fileIndex => {
2016-03-12 08:17:03 +01:00
const matchingIcons = fileIndex
.filter(item => {
2016-03-12 08:17:03 +01:00
// todo might have problems with matching length, e.g. `book` vs `facebook`
return targetUrl
.toLowerCase()
.includes(item.name);
})
2016-03-12 08:17:03 +01: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) {
let preferredExt = '.png';
2016-03-09 07:50:25 +01:00
if (platform === 'win32') {
preferredExt = '.ico';
2016-03-09 07:50:25 +01:00
}
2016-03-12 08:17:03 +01:00
// todo might want to pass list of preferences instead
return pageIcon(targetUrl, {ext: preferredExt})
.then(icon => {
if (!icon) {
2016-03-12 08:17:03 +01:00
return null;
}
2016-03-12 08:17:03 +01:00
const outfilePath = path.join(outDir, `/icon${icon.ext}`);
return writeFilePromise(outfilePath, icon.data);
});
2016-01-28 14:13:57 +01:00
}
/**
*
* @param {string} targetUrl
* @param {string} platform
* @param {string} outDir
2016-01-28 14:13:57 +01:00
*/
function inferIconFromUrlToPath(targetUrl, platform, outDir) {
return inferIconFromStore(targetUrl, platform)
2016-03-12 08:17:03 +01:00
.then(icon => {
if (!icon) {
return inferFromPage(targetUrl, platform, outDir);
}
2016-03-12 08:17:03 +01:00
const outfilePath = path.join(outDir, `/icon${icon.ext}`);
return writeFilePromise(outfilePath, icon.data);
});
}
2016-01-28 14:13:57 +01:00
/**
* @param {string} targetUrl
2016-03-09 07:50:25 +01:00
* @param {string} platform
2016-01-28 14:13:57 +01:00
*/
function inferIcon(targetUrl, platform) {
2016-01-28 14:13:57 +01:00
const tmpObj = tmp.dirSync({unsafeCleanup: true});
const tmpPath = tmpObj.name;
return inferIconFromUrlToPath(targetUrl, platform, tmpPath);
2016-01-28 14:13:57 +01:00
}
export default inferIcon;