feat: #7743 meta/themes.js

v1.18.x
Julian Lam 6 years ago
parent a15c50bf62
commit 7dc0eaf070

@ -1,221 +1,155 @@
'use strict'; 'use strict';
var nconf = require('nconf'); const path = require('path');
var winston = require('winston'); const nconf = require('nconf');
var fs = require('fs'); const winston = require('winston');
var path = require('path'); const _ = require('lodash');
var async = require('async');
const util = require('util');
const fs = require('fs');
const fsReaddir = util.promisify(fs.readdir);
const fsStat = util.promisify(fs.stat);
const fsReadfile = util.promisify(fs.readFile);
var file = require('../file');
var db = require('../database');
var Meta = require('../meta');
var events = require('../events');
var Themes = module.exports; const file = require('../file');
const db = require('../database');
const Meta = require('../meta');
const events = require('../events');
const utils = require('../../public/src/utils');
var themeNamePattern = /^(@.*?\/)?nodebb-theme-.*$/; const Themes = module.exports;
Themes.get = function (callback) { const themeNamePattern = /^(@.*?\/)?nodebb-theme-.*$/;
var themePath = nconf.get('themes_path');
Themes.get = async () => {
const themePath = nconf.get('themes_path');
if (typeof themePath !== 'string') { if (typeof themePath !== 'string') {
return callback(null, []); return [];
} }
async.waterfall([ let themes = await getThemes(themePath);
function (next) { themes = _.flatten(themes).filter(Boolean);
fs.readdir(themePath, next); themes = await Promise.all(themes.map(async (theme) => {
}, const config = path.join(themePath, theme, 'theme.json');
function (dirs, next) { try {
async.map(dirs.filter(function (dir) { const file = await fsReadfile(config, 'utf8');
return themeNamePattern.test(dir) || dir.startsWith('@'); const configObj = JSON.parse(file);
}), function (dir, next) {
var dirpath = path.join(themePath, dir); // Minor adjustments for API output
configObj.type = 'local';
fs.stat(dirpath, function (err, stat) { if (configObj.screenshot) {
if (err) { configObj.screenshot_url = nconf.get('relative_path') + '/css/previews/' + encodeURIComponent(configObj.id);
if (err.code === 'ENOENT') { } else {
return next(null, false); configObj.screenshot_url = nconf.get('relative_path') + '/assets/images/themes/default.png';
} }
return next(err);
} return configObj;
} catch (err) {
if (!stat.isDirectory()) { if (err.code === 'ENOENT') {
return next(null, null); return false;
} }
if (!dir.startsWith('@')) { winston.error('[themes] Unable to parse theme.json ' + theme);
return next(null, dir); return false;
} }
}));
fs.readdir(dirpath, function (err, themes) {
if (err) { return themes.filter(Boolean);
return next(err);
}
async.filter(themes.filter(function (theme) {
return themeNamePattern.test(theme);
}), function (theme, next) {
fs.stat(path.join(dirpath, theme), function (err, stat) {
if (err) {
if (err.code === 'ENOENT') {
return next(null, false);
}
return next(err);
}
next(null, stat.isDirectory());
});
}, function (err, themes) {
if (err) {
return next(err);
}
next(null, themes.map(function (theme) {
return dir + '/' + theme;
}));
});
});
});
}, next);
},
function (themes, next) {
themes = themes.reduce(function (prev, theme) {
if (!theme) {
return prev;
}
return prev.concat(theme);
}, []);
async.map(themes, function (theme, next) {
var config = path.join(themePath, theme, 'theme.json');
fs.readFile(config, 'utf8', function (err, file) {
if (err) {
if (err.code === 'ENOENT') {
return next(null, null);
}
return next(err);
}
try {
var configObj = JSON.parse(file);
// Minor adjustments for API output
configObj.type = 'local';
if (configObj.screenshot) {
configObj.screenshot_url = nconf.get('relative_path') + '/css/previews/' + encodeURIComponent(configObj.id);
} else {
configObj.screenshot_url = nconf.get('relative_path') + '/assets/images/themes/default.png';
}
next(null, configObj);
} catch (err) {
winston.error('[themes] Unable to parse theme.json ' + theme);
next(null, null);
}
});
}, next);
},
function (themes, next) {
themes = themes.filter(Boolean);
next(null, themes);
},
], callback);
}; };
Themes.set = function (data, callback) { async function getThemes(themePath) {
var themeData = { let dirs = await fsReaddir(themePath);
dirs = dirs.filter(dir => themeNamePattern.test(dir) || dir.startsWith('@'));
return await Promise.all(dirs.map(async (dir) => {
try {
const dirpath = path.join(themePath, dir);
const stat = await fsStat(dirpath);
if (!stat.isDirectory()) {
return false;
}
if (!dir.startsWith('@')) {
return dir;
}
const themes = await getThemes(path.join(themePath, dir));
return themes.map(theme => path.join(dir, theme));
} catch (err) {
if (err.code === 'ENOENT') {
return false;
}
throw err;
}
}));
}
Themes.set = async (data) => {
const themeData = {
'theme:type': data.type, 'theme:type': data.type,
'theme:id': data.id, 'theme:id': data.id,
'theme:staticDir': '', 'theme:staticDir': '',
'theme:templates': '', 'theme:templates': '',
'theme:src': '', 'theme:src': '',
}; };
const current = await Meta.configs.get('theme:id');
let config = await fsReadfile(path.join(nconf.get('themes_path'), data.id, 'theme.json'), 'utf8');
config = JSON.parse(config);
switch (data.type) { switch (data.type) {
case 'local': case 'local':
async.waterfall([ await db.sortedSetRemove('plugins:active', current);
async.apply(Meta.configs.get, 'theme:id'), await db.sortedSetAdd('plugins:active', 0, data.id);
function (current, next) {
async.series([ // Re-set the themes path (for when NodeBB is reloaded)
async.apply(db.sortedSetRemove, 'plugins:active', current), Themes.setPath(config);
async.apply(db.sortedSetAdd, 'plugins:active', 0, data.id),
], function (err) { themeData['theme:staticDir'] = config.staticDir ? config.staticDir : '';
next(err); themeData['theme:templates'] = config.templates ? config.templates : '';
}); themeData['theme:src'] = '';
}, themeData.bootswatchSkin = '';
function (next) {
fs.readFile(path.join(nconf.get('themes_path'), data.id, 'theme.json'), 'utf8', function (err, config) { await Meta.configs.setMultiple(themeData);
if (!err) { await events.log({
config = JSON.parse(config); type: 'theme-set',
next(null, config); uid: parseInt(data.uid, 10) || 0,
} else { ip: data.ip || '127.0.0.1',
next(err); text: data.id,
} });
});
},
function (config, next) {
themeData['theme:staticDir'] = config.staticDir ? config.staticDir : '';
themeData['theme:templates'] = config.templates ? config.templates : '';
themeData['theme:src'] = '';
themeData.bootswatchSkin = '';
Meta.configs.setMultiple(themeData, next);
// Re-set the themes path (for when NodeBB is reloaded)
Themes.setPath(config);
},
function (next) {
events.log({
type: 'theme-set',
uid: parseInt(data.uid, 10) || 0,
ip: data.ip || '127.0.0.1',
text: data.id,
}, next);
},
], callback);
Meta.reloadRequired = true; Meta.reloadRequired = true;
break; break;
case 'bootswatch': case 'bootswatch':
Meta.configs.setMultiple({ await Meta.configs.setMultiple({
'theme:src': data.src, 'theme:src': data.src,
bootswatchSkin: data.id.toLowerCase(), bootswatchSkin: data.id.toLowerCase(),
}, callback); });
break; break;
} }
}; };
Themes.setupPaths = function (callback) { Themes.setupPaths = async () => {
async.waterfall([ const data = await utils.promiseParallel({
function (next) { themesData: Themes.get(),
async.parallel({ currentThemeId: Meta.configs.get('theme:id'),
themesData: Themes.get, });
currentThemeId: function (next) {
Meta.configs.get('theme:id', next);
},
}, next);
},
function (data, next) {
var themeId = data.currentThemeId || 'nodebb-theme-persona';
if (process.env.NODE_ENV === 'development') {
winston.info('[themes] Using theme ' + themeId);
}
var themeObj = data.themesData.find(function (themeObj) { var themeId = data.currentThemeId || 'nodebb-theme-persona';
return themeObj.id === themeId;
});
if (!themeObj) { if (process.env.NODE_ENV === 'development') {
return callback(new Error('[[error:theme-not-found]]')); winston.info('[themes] Using theme ' + themeId);
} }
var themeObj = data.themesData.find(function (themeObj) {
return themeObj.id === themeId;
});
if (!themeObj) {
throw new Error('[[error:theme-not-found]]');
}
Themes.setPath(themeObj); Themes.setPath(themeObj);
next();
},
], callback);
}; };
Themes.setPath = function (themeObj) { Themes.setPath = function (themeObj) {

Loading…
Cancel
Save