211 lines
8.6 KiB
JavaScript
211 lines
8.6 KiB
JavaScript
'use strict';
|
|
|
|
exports = module.exports = {
|
|
list,
|
|
listByUser,
|
|
add,
|
|
get,
|
|
update,
|
|
remove,
|
|
getIcon
|
|
};
|
|
|
|
const assert = require('assert'),
|
|
apps = require('./apps.js'),
|
|
BoxError = require('./boxerror.js'),
|
|
database = require('./database.js'),
|
|
debug = require('debug')('box:applinks'),
|
|
jsdom = require('jsdom'),
|
|
safe = require('safetydance'),
|
|
superagent = require('superagent'),
|
|
uuid = require('uuid'),
|
|
validator = require('validator');
|
|
|
|
const APPLINKS_FIELDS= [ 'id', 'accessRestrictionJson', 'creationTime', 'updateTime', 'ts', 'label', 'tagsJson', 'icon', 'upstreamUri' ].join(',');
|
|
|
|
function postProcess(result) {
|
|
assert.strictEqual(typeof result, 'object');
|
|
|
|
assert(result.tagsJson === null || typeof result.tagsJson === 'string');
|
|
result.tags = safe.JSON.parse(result.tagsJson) || [];
|
|
delete result.tagsJson;
|
|
|
|
assert(result.accessRestrictionJson === null || typeof result.accessRestrictionJson === 'string');
|
|
result.accessRestriction = safe.JSON.parse(result.accessRestrictionJson);
|
|
if (result.accessRestriction && !result.accessRestriction.users) result.accessRestriction.users = [];
|
|
delete result.accessRestrictionJson;
|
|
|
|
result.ts = new Date(result.ts).getTime();
|
|
|
|
result.icon = result.icon ? result.icon : null;
|
|
|
|
}
|
|
|
|
function validateUpstreamUri(upstreamUri) {
|
|
assert.strictEqual(typeof upstreamUri, 'string');
|
|
|
|
if (!upstreamUri) return new BoxError(BoxError.BAD_FIELD, 'upstreamUri cannot be empty');
|
|
|
|
if (!upstreamUri.includes('://')) return new BoxError(BoxError.BAD_FIELD, 'upstreamUri has no schema');
|
|
|
|
const uri = safe(() => new URL(upstreamUri));
|
|
if (!uri) return new BoxError(BoxError.BAD_FIELD, `upstreamUri is invalid: ${safe.error.message}`);
|
|
if (uri.protocol !== 'http:' && uri.protocol !== 'https:') return new BoxError(BoxError.BAD_FIELD, 'upstreamUri has an unsupported scheme');
|
|
|
|
return null;
|
|
}
|
|
|
|
async function list() {
|
|
const results = await database.query(`SELECT ${APPLINKS_FIELDS} FROM applinks ORDER BY upstreamUri`);
|
|
|
|
results.forEach(postProcess);
|
|
|
|
return results;
|
|
}
|
|
|
|
async function listByUser(user) {
|
|
assert.strictEqual(typeof user, 'object');
|
|
|
|
const result = await list();
|
|
return result.filter((app) => apps.canAccess(app, user));
|
|
}
|
|
|
|
async function detectMetaInfo(applink) {
|
|
assert.strictEqual(typeof applink, 'object');
|
|
|
|
const [error, response] = await safe(superagent.get(applink.upstreamUri).set('User-Agent', 'Mozilla'));
|
|
if (error || !response.text) throw new BoxError(BoxError.BAD_FIELD, 'cannot fetch upstream uri for favicon and label');
|
|
|
|
if (applink.favicon && applink.label) return;
|
|
|
|
// set redirected URI if any for favicon url
|
|
const redirectUri = (response.redirects && response.redirects.length) ? response.redirects[0] : null;
|
|
|
|
const dom = new jsdom.JSDOM(response.text);
|
|
if (!applink.icon) {
|
|
let favicon = '';
|
|
if (dom.window.document.querySelector('link[rel="apple-touch-icon"]')) favicon = dom.window.document.querySelector('link[rel="apple-touch-icon"]').href ;
|
|
if (!favicon.endsWith('.png') && dom.window.document.querySelector('meta[name="msapplication-TileImage"]')) favicon = dom.window.document.querySelector('meta[name="msapplication-TileImage"]').content ;
|
|
if (!favicon.endsWith('.png') && dom.window.document.querySelector('link[rel="shortcut icon"]')) favicon = dom.window.document.querySelector('link[rel="shortcut icon"]').href ;
|
|
if (!favicon.endsWith('.png') && dom.window.document.querySelector('link[rel="icon"]')) {
|
|
let iconElements = dom.window.document.querySelectorAll('link[rel="icon"]');
|
|
if (iconElements.length) {
|
|
favicon = iconElements[0].href; // choose first one for a start
|
|
|
|
// check if we have sizes attributes and then choose the largest one
|
|
iconElements = Array.from(iconElements).filter(function (e) {
|
|
return e.attributes.getNamedItem('sizes') && e.attributes.getNamedItem('sizes').value;
|
|
}).sort(function (a, b) {
|
|
return parseInt(b.attributes.getNamedItem('sizes').value.split('x')[0]) - parseInt(a.attributes.getNamedItem('sizes').value.split('x')[0]);
|
|
});
|
|
if (iconElements.length) favicon = iconElements[0].href;
|
|
}
|
|
}
|
|
if (!favicon.endsWith('.png') && dom.window.document.querySelector('meta[itemprop="image"]')) favicon = dom.window.document.querySelector('meta[itemprop="image"]').content;
|
|
|
|
if (favicon) {
|
|
if (favicon.startsWith('/')) favicon = (redirectUri || applink.upstreamUri) + favicon;
|
|
|
|
debug(`detectMetaInfo: found icon: ${favicon}`);
|
|
|
|
const [error, response] = await safe(superagent.get(favicon));
|
|
if (error) console.error(`Failed to fetch icon ${favicon}: `, error);
|
|
else if (response.ok && response.headers['content-type'] === 'image/png') applink.icon = response.body;
|
|
else console.error(`Failed to fetch icon ${favicon}: statusCode=${response.status}`);
|
|
} else {
|
|
console.error(`Unable to find a suitable icon for ${applink.upstreamUri}`);
|
|
}
|
|
}
|
|
|
|
if (!applink.label) {
|
|
if (dom.window.document.querySelector('meta[property="og:title"]')) applink.label = dom.window.document.querySelector('meta[property="og:title"]').content;
|
|
else if (dom.window.document.querySelector('meta[property="og:site_name"]')) applink.label = dom.window.document.querySelector('meta[property="og:site_name"]').content;
|
|
else if (dom.window.document.title) applink.label = dom.window.document.title;
|
|
}
|
|
}
|
|
|
|
async function add(applink) {
|
|
assert.strictEqual(typeof applink, 'object');
|
|
assert.strictEqual(typeof applink.upstreamUri, 'string');
|
|
|
|
debug(`add: ${applink.upstreamUri}`, applink);
|
|
|
|
let error = validateUpstreamUri(applink.upstreamUri);
|
|
if (error) throw error;
|
|
|
|
if (applink.icon) {
|
|
if (!validator.isBase64(applink.icon)) throw new BoxError(BoxError.BAD_FIELD, 'icon is not base64');
|
|
applink.icon = Buffer.from(applink.icon, 'base64');
|
|
}
|
|
|
|
await detectMetaInfo(applink);
|
|
|
|
const data = {
|
|
id: uuid.v4(),
|
|
accessRestrictionJson: applink.accessRestriction ? JSON.stringify(applink.accessRestriction) : null,
|
|
label: applink.label || '',
|
|
tagsJson: applink.tags ? JSON.stringify(applink.tags) : null,
|
|
icon: applink.icon || null,
|
|
upstreamUri: applink.upstreamUri
|
|
};
|
|
|
|
const query = 'INSERT INTO applinks (id, accessRestrictionJson, label, tagsJson, icon, upstreamUri) VALUES (?, ?, ?, ?, ?, ?)';
|
|
const args = [ data.id, data.accessRestrictionJson, data.label, data.tagsJson, data.icon, data.upstreamUri ];
|
|
|
|
[error] = await safe(database.query(query, args));
|
|
if (error) throw error;
|
|
|
|
return data.id;
|
|
}
|
|
|
|
async function get(applinkId) {
|
|
assert.strictEqual(typeof applinkId, 'string');
|
|
|
|
const result = await database.query(`SELECT ${APPLINKS_FIELDS} FROM applinks WHERE id = ?`, [ applinkId ]);
|
|
if (result.length === 0) return null;
|
|
|
|
postProcess(result[0]);
|
|
|
|
return result[0];
|
|
}
|
|
|
|
async function update(applinkId, applink) {
|
|
assert.strictEqual(typeof applinkId, 'string');
|
|
assert.strictEqual(typeof applink, 'object');
|
|
assert.strictEqual(typeof applink.upstreamUri, 'string');
|
|
|
|
debug(`update: ${applink.upstreamUri}`, applink);
|
|
|
|
let error = validateUpstreamUri(applink.upstreamUri);
|
|
if (error) throw error;
|
|
|
|
if (applink.icon) {
|
|
if (!validator.isBase64(applink.icon)) throw new BoxError(BoxError.BAD_FIELD, 'icon is not base64');
|
|
applink.icon = Buffer.from(applink.icon, 'base64');
|
|
}
|
|
|
|
await detectMetaInfo(applink);
|
|
|
|
const query = 'UPDATE applinks SET label=?, icon=?, upstreamUri=?, tagsJson=?, accessRestrictionJson=? WHERE id = ?';
|
|
const args = [ applink.label, applink.icon || null, applink.upstreamUri, applink.tags ? JSON.stringify(applink.tags) : null, applink.accessRestriction ? JSON.stringify(applink.accessRestriction) : null, applinkId ];
|
|
|
|
const result = await database.query(query, args);
|
|
if (result.affectedRows !== 1) throw new BoxError(BoxError.NOT_FOUND, 'Applink not found');
|
|
}
|
|
|
|
async function remove(applinkId) {
|
|
assert.strictEqual(typeof applinkId, 'string');
|
|
|
|
const result = await database.query('DELETE FROM applinks WHERE id = ?', [ applinkId ]);
|
|
if (result.affectedRows !== 1) throw new BoxError(BoxError.NOT_FOUND, 'Applink not found');
|
|
}
|
|
|
|
async function getIcon(applinkId) {
|
|
assert.strictEqual(typeof applinkId, 'string');
|
|
|
|
const applink = await get(applinkId);
|
|
if (!applink) throw new BoxError(BoxError.NOT_FOUND, 'Applink not found');
|
|
|
|
return applink.icon;
|
|
}
|