Merge branch '3.0' of https://github.com/calzoneman/sync into 3.0
[KisSync.git] / src / camo.js
blob37c7f956b4cb5438395ee5a0480d6954b3025e51
1 import crypto from 'crypto';
2 import * as urlparse from 'url';
4 const LOGGER = require('@calzoneman/jsli')('camo');
6 function isWhitelisted(camoConfig, url) {
7 const whitelistedDomains = camoConfig.getWhitelistedDomainsRegexp();
8 const parsed = urlparse.parse(url);
9 return whitelistedDomains.test('.' + parsed.hostname);
12 export function camoify(camoConfig, url) {
13 if (typeof url !== 'string') {
14 throw new TypeError(`camoify expected a string, not [${url}]`);
17 if (isWhitelisted(camoConfig, url)) {
18 return url.replace(/^http:/, 'https:');
21 const hmac = crypto.createHmac('sha1', camoConfig.getKey());
22 hmac.update(url);
23 const digest = hmac.digest('hex');
24 // https://github.com/atmos/camo#url-formats
25 if (camoConfig.getEncoding() === 'hex') {
26 const hexUrl = Buffer.from(url, 'utf8').toString('hex');
27 return `${camoConfig.getServer()}/${digest}/${hexUrl}`;
28 } else {
29 const encoded = encodeURIComponent(url);
30 return `${camoConfig.getServer()}/${digest}?url=${encoded}`;
34 export function transformImgTags(camoConfig, tagName, attribs) {
35 if (typeof attribs.src === 'string') {
36 try {
37 const oldSrc = attribs.src;
38 attribs.src = camoify(camoConfig, attribs.src);
39 LOGGER.debug('Camoified "%s" to "%s"', oldSrc, attribs.src);
40 } catch (error) {
41 LOGGER.error(`Failed to generate camo URL for "${attribs.src}": ${error}`);
45 return { tagName, attribs };