Fix configs loading #470

Merged
bones7242 merged 15 commits from fix-configs-loading into master 2018-06-07 19:40:01 +02:00
38 changed files with 595 additions and 627 deletions

View file

@ -23,7 +23,7 @@ var _MultisitePage = _interopRequireDefault(require("@pages/MultisitePage"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var customizedApp = function customizedApp() {
var App = function App() {
return _react.default.createElement(_reactRouterDom.Switch, null, _react.default.createElement(_reactRouterDom.Route, {
exact: true,
path: "/",
@ -53,5 +53,5 @@ var customizedApp = function customizedApp() {
}));
};
var _default = customizedApp;
var _default = App;
exports.default = _default;

View file

@ -11,6 +11,8 @@ var _reactGa = _interopRequireDefault(require("react-ga"));
var _reactRouterDom = require("react-router-dom");
var _siteConfig = _interopRequireDefault(require("@config/siteConfig.json"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
@ -31,10 +33,15 @@ function _assertThisInitialized(self) { if (self === void 0) { throw new Referen
function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || function _getPrototypeOf(o) { return o.__proto__; }; return _getPrototypeOf(o); }
var customGAListener = function customGAListener(siteConfig) {
var googleId = siteConfig.analytics.googleId;
var googleId = null;
if (_siteConfig.default && _siteConfig.default.analytics) {
googleId = _siteConfig.default.analytics.googleId;
}
if (googleId) {
_reactGa.default.initialize(googleId);
}
var GAListener =
/*#__PURE__*/
@ -54,12 +61,14 @@ var customGAListener = function customGAListener(siteConfig) {
}, {
key: "sendPageView",
value: function sendPageView(location) {
if (googleId) {
_reactGa.default.set({
page: location.pathname
});
_reactGa.default.pageview(location.pathname);
}
}
}, {
key: "render",
value: function render() {
@ -72,8 +81,6 @@ var customGAListener = function customGAListener(siteConfig) {
return GAListener;
}(_react.default.Component);
return (0, _reactRouterDom.withRouter)(GAListener);
};
var _default = (0, _reactRouterDom.withRouter)(GAListener);
var _default = customGAListener;
exports.default = _default;

View file

@ -19,15 +19,14 @@ var _channelCreate = _interopRequireDefault(require("./channelCreate"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var customizedReducers = function customizedReducers(siteConfig) {
return (0, _redux.combineReducers)({
// modules
// local modules
var _default = (0, _redux.combineReducers)({
channel: _channel.default,
channelCreate: _channelCreate.default,
publish: (0, _publish.default)(siteConfig),
publish: _publish.default,
show: _show.default,
site: (0, _site.default)(siteConfig)
site: _site.default
});
};
var _default = customizedReducers;
exports.default = _default;

View file

@ -3,29 +3,32 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
exports.default = _default;
var actions = _interopRequireWildcard(require("../constants/publish_action_types"));
var _publish_channel_select_states = require("../constants/publish_channel_select_states");
var _siteConfig = _interopRequireDefault(require("@config/siteConfig.json"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var customizedPublishReducer = function customizedPublishReducer(siteConfig) {
// parse inputs
var disabledConfig = false;
var disabledMessageConfig = 'none';
var thumbnailChannel = '';
var thumbnailChannelId = '';
if (siteConfig) {
if (siteConfig.publishing) {
disabledConfig = siteConfig.publishing.disabled;
disabledMessageConfig = siteConfig.publishing.disabledMessage;
thumbnailChannel = siteConfig.publishing.thumbnailChannel;
thumbnailChannelId = siteConfig.publishing.thumbnailChannelId;
if (_siteConfig.default) {
if (_siteConfig.default.publishing) {
disabledConfig = _siteConfig.default.publishing.disabled;
disabledMessageConfig = _siteConfig.default.publishing.disabledMessage;
thumbnailChannel = _siteConfig.default.publishing.thumbnailChannel;
thumbnailChannelId = _siteConfig.default.publishing.thumbnailChannelId;
}
} // create initial state
@ -57,7 +60,8 @@ var customizedPublishReducer = function customizedPublishReducer(siteConfig) {
thumbnailChannel: thumbnailChannel,
thumbnailChannelId: thumbnailChannelId
};
return function () {
function _default() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState;
var action = arguments.length > 1 ? arguments[1] : undefined;
@ -114,8 +118,6 @@ var customizedPublishReducer = function customizedPublishReducer(siteConfig) {
default:
return state;
}
};
};
}
var _default = customizedPublishReducer;
exports.default = _default;
;

View file

@ -3,17 +3,28 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
exports.default = _default;
var customizedSiteReducer = function customizedSiteReducer(siteConfig) {
var initialState = {};
var _siteConfig = _interopRequireDefault(require("@config/siteConfig.json"));
if (siteConfig) {
var googleAnalyticsId = siteConfig.analytics.googleId,
_siteConfig$assetDefa = siteConfig.assetDefaults,
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var initialState = {
description: 'default description',
googleAnalyticsId: 'default google id',
host: 'default host',
title: 'default title',
twitter: 'default twitter',
defaultDescription: 'default description',
defaultThumbnail: 'default thumbnail'
};
if (_siteConfig.default) {
var googleAnalyticsId = _siteConfig.default.analytics.googleId,
_siteConfig$assetDefa = _siteConfig.default.assetDefaults,
defaultThumbnail = _siteConfig$assetDefa.thumbnail,
defaultDescription = _siteConfig$assetDefa.description,
_siteConfig$details = siteConfig.details,
_siteConfig$details = _siteConfig.default.details,
description = _siteConfig$details.description,
host = _siteConfig$details.host,
title = _siteConfig$details.title,
@ -27,19 +38,9 @@ var customizedSiteReducer = function customizedSiteReducer(siteConfig) {
defaultDescription: defaultDescription,
defaultThumbnail: defaultThumbnail
};
} else {
initialState = {
description: 'default description',
googleAnalyticsId: 'default google id',
host: 'default host',
title: 'default title',
twitter: 'default twitter',
defaultDescription: 'default description',
defaultThumbnail: 'default thumbnail'
};
}
return function () {
function _default() {
var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState;
var action = arguments.length > 1 ? arguments[1] : undefined;
@ -47,8 +48,6 @@ var customizedSiteReducer = function customizedSiteReducer(siteConfig) {
default:
return state;
}
};
};
}
var _default = customizedSiteReducer;
exports.default = _default;
;

View file

@ -8,7 +8,7 @@ import ShowPage from '@pages/ShowPage';
import FourOhFourPage from '@pages/FourOhFourPage';
import MultisitePage from '@pages/MultisitePage';
const customizedApp = () => {
const App = () => {
return (
<Switch>
<Route exact path='/' component={HomePage} />
@ -22,4 +22,4 @@ const customizedApp = () => {
);
};
export default customizedApp;
export default App;

View file

@ -2,10 +2,17 @@ import React from 'react';
import GoogleAnalytics from 'react-ga';
import { withRouter } from 'react-router-dom';
const customGAListener = (siteConfig) => {
const { analytics: { googleId } } = siteConfig;
import siteConfig from '@config/siteConfig.json';
let googleId = null;
if (siteConfig && siteConfig.analytics) {
({ googleId } = siteConfig.analytics);
}
if (googleId) {
GoogleAnalytics.initialize(googleId);
}
class GAListener extends React.Component {
componentDidMount () {
@ -14,16 +21,15 @@ const customGAListener = (siteConfig) => {
}
sendPageView (location) {
if (googleId) {
GoogleAnalytics.set({ page: location.pathname });
GoogleAnalytics.pageview(location.pathname);
}
}
render () {
return this.props.children;
}
}
return withRouter(GAListener);
};
export default customGAListener;
export default withRouter(GAListener);

View file

@ -1,18 +1,17 @@
// modules
import { combineReducers } from 'redux';
// local modules
import PublishReducer from './publish';
import ChannelReducer from './channel';
import ShowReducer from './show';
import SiteReducer from './site';
import ChannelCreateReducer from './channelCreate';
const customizedReducers = (siteConfig) => {
return combineReducers({
export default combineReducers({
channel : ChannelReducer,
channelCreate: ChannelCreateReducer,
publish : PublishReducer(siteConfig),
publish : PublishReducer,
show : ShowReducer,
site : SiteReducer(siteConfig),
})
};
export default customizedReducers;
site : SiteReducer,
});

View file

@ -1,7 +1,8 @@
import * as actions from '../constants/publish_action_types';
import { LOGIN } from '../constants/publish_channel_select_states';
const customizedPublishReducer = (siteConfig) => {
import siteConfig from '@config/siteConfig.json';
// parse inputs
let disabledConfig = false;
let disabledMessageConfig = 'none';
@ -15,6 +16,7 @@ const customizedPublishReducer = (siteConfig) => {
thumbnailChannelId = siteConfig.publishing.thumbnailChannelId;
}
}
// create initial state
const initialState = {
disabled : disabledConfig,
@ -43,7 +45,8 @@ const customizedPublishReducer = (siteConfig) => {
thumbnailChannel,
thumbnailChannelId,
};
return (state = initialState, action) => {
export default function (state = initialState, action) {
switch (action.type) {
case actions.FILE_SELECTED:
return Object.assign({}, initialState, { // note: clears to initial state
@ -91,6 +94,3 @@ const customizedPublishReducer = (siteConfig) => {
return state;
}
};
};
export default customizedPublishReducer;

View file

@ -1,5 +1,15 @@
const customizedSiteReducer = (siteConfig) => {
let initialState = {};
import siteConfig from '@config/siteConfig.json';
let initialState = {
description : 'default description',
googleAnalyticsId : 'default google id',
host : 'default host',
title : 'default title',
twitter : 'default twitter',
defaultDescription: 'default description',
defaultThumbnail : 'default thumbnail',
};
if (siteConfig) {
const {
analytics: {
@ -26,23 +36,11 @@ const customizedSiteReducer = (siteConfig) => {
defaultDescription,
defaultThumbnail,
};
} else {
initialState = {
description : 'default description',
googleAnalyticsId : 'default google id',
host : 'default host',
title : 'default title',
twitter : 'default twitter',
defaultDescription: 'default description',
defaultThumbnail : 'default thumbnail',
};
}
return (state = initialState, action) => {
export default function (state = initialState, action) {
switch (action.type) {
default:
return state;
}
};
};
export default customizedSiteReducer;

View file

@ -1,8 +0,0 @@
const lbryConfig = {
api: {
apiHost: 'localhost',
apiPort: '5279',
},
};
module.exports = lbryConfig;

View file

@ -1,36 +0,0 @@
const logger = require('winston');
function LoggerConfig () {
this.logLevel = 'debug';
this.update = (config) => {
if (!config) {
return logger.warn('No logger config received.');
}
logger.info('configuring winston logger...');
// update values with local config params
const {logLevel} = config;
this.logLevel = logLevel;
// configure the winston logger
logger.configure({
transports: [
new (logger.transports.Console)({
level : this.logLevel,
timestamp : false,
colorize : true,
prettyPrint : true,
handleExceptions : true,
humanReadableUnhandledException: true,
}),
],
});
// test all the log levels
logger.info('testing winston log levels...');
logger.warn('Testing: Log Level 1');
logger.info('Testing: Log Level 2');
logger.verbose('Testing: Log Level 3');
logger.debug('Testing: Log Level 4');
logger.silly('Testing: Log Level 5');
};
};
module.exports = new LoggerConfig();

View file

@ -1,20 +0,0 @@
const logger = require('winston');
function MysqlConfig () {
this.database = 'default';
this.username = 'default';
this.password = 'default';
this.update = (config) => {
if (!config) {
return logger.warn('No MySQL config received.');
}
// configure credentials
logger.info('configuring mysql...');
const { database, username, password } = config;
this.database = database;
this.username = username;
this.password = password;
};
}
module.exports = new MysqlConfig();

View file

@ -1,43 +0,0 @@
function SiteConfig () {
this.analytics = {
googleId: 'default',
};
this.assetDefaults = {
description: 'An asset published on Spee.ch',
thumbnail : 'https://spee.ch/assets/img/video_thumb_default.png',
title : 'A Spee.ch Implementation',
};
this.auth = {
sessionKey: 'default',
};
this.details = {
description: 'Welcome to my decentralized image and video sharing site.',
host : 'http://localhost:3000',
port : 3000,
title : 'My Spee.ch Site',
twitter : '@exampleTwitterHandle',
};
this.publishing = {
additionalClaimAddresses: [],
disabled : false,
disabledMessage : 'Please check back soon.',
primaryClaimAddress : 'default',
thumbnailChannel : 'default',
thumbnailChannelId : 'default',
uploadDirectory : '/home/lbry/Uploads',
};
this.update = (config) => {
if (!config) {
return console.log('No site config received.');
}
const { analytics, assetDefaults, auth, details, publishing } = config;
console.log('Configuring site details...');
this.analytics = analytics;
this.assetDefaults = assetDefaults;
this.auth = auth;
this.details = details;
this.publishing = publishing;
};
}
module.exports = new SiteConfig();

View file

@ -1,51 +0,0 @@
const winstonSlackWebHook = require('winston-slack-webhook').SlackWebHook;
const winston = require('winston');
function SlackConfig () {
this.slackWebHook = 'default';
this.slackErrorChannel = 'default';
this.slackInfoChannel = 'default';
this.update = (config) => {
if (!config) {
return winston.warn('No slack config received');
}
// update variables
winston.info('configuring slack logger...');
const {slackWebHook, slackErrorChannel, slackInfoChannel} = config;
this.slackWebHook = slackWebHook;
this.slackErrorChannel = slackErrorChannel;
this.slackInfoChannel = slackInfoChannel;
// update slack webhook settings
if (this.slackWebHook) {
// add a transport for errors to slack
if (this.slackErrorChannel) {
winston.add(winstonSlackWebHook, {
name : 'slack-errors-transport',
level : 'warn',
webhookUrl: this.slackWebHook,
channel : this.slackErrorChannel,
username : 'spee.ch',
iconEmoji : ':face_with_head_bandage:',
});
};
if (this.slackInfoChannel) {
winston.add(winstonSlackWebHook, {
name : 'slack-info-transport',
level : 'info',
webhookUrl: this.slackWebHook,
channel : this.slackInfoChannel,
username : 'spee.ch',
iconEmoji : ':nerd_face:',
});
};
// send test messages
winston.info('testing slack logger...');
winston.error('Slack "error" logging is online.');
winston.info('Slack "info" logging is online.');
} else {
winston.warn('Slack logging is not enabled because no slackWebHook config var provided.');
}
};
};
module.exports = new SlackConfig();

View file

@ -1,4 +1,18 @@
// app dependencies
// set up module aliasing
const moduleAlias = require('module-alias');
const createModuleAliases = require('./server/utils/createModuleAliases.js');
const customAliases = createModuleAliases();
moduleAlias.addAliases(customAliases);
// test configs
const checkForConfig = require('./server/utils/checkForConfig.js');
checkForConfig('siteConfig');
checkForConfig('mysqlConfig');
checkForConfig('slackConfig');
checkForConfig('loggerConfig');
checkForConfig('siteConfig');
// load modules
const express = require('express');
const bodyParser = require('body-parser');
const expressHandlebars = require('express-handlebars');
@ -7,29 +21,36 @@ const helmet = require('helmet');
const cookieSession = require('cookie-session');
const http = require('http');
const logger = require('winston');
const requestLogger = require('./server/middleware/requestLogger.js');
const Path = require('path');
const loggerConfig = require('./config/loggerConfig.js');
const mysqlConfig = require('./config/mysqlConfig.js');
const siteConfig = require('./config/siteConfig.js');
const slackConfig = require('./config/slackConfig.js');
// load local modules
const db = require('./server/models');
const requestLogger = require('./server/middleware/requestLogger.js');
const createDatabaseIfNotExists = require('./server/models/utils/createDatabaseIfNotExists.js');
const { getWalletBalance } = require('./server/lbrynet/index');
const { getWalletBalance } = require('./server/lbrynet');
const configureLogging = require('./server/utils/configureLogging.js');
const configureSlack = require('./server/utils/configureSlack.js');
const speechPassport = require('./server/speechPassport');
const {
details: { port: PORT },
auth: { sessionKey },
} = require('@config/siteConfig');
function Server () {
this.configureLogger = loggerConfig.update;
this.configureMysql = mysqlConfig.update;
this.configureSite = siteConfig.update;
this.configureSlack = slackConfig.update;
this.initialize = () => {
// configure logging
configureLogging();
// configure slack logging
configureSlack();
};
this.createApp = () => {
// create an Express application
/* create app */
const app = express();
// trust the proxy to get ip address for us
app.enable('trust proxy');
/* add middleware */
// set HTTP headers to protect against well-known web vulnerabilties
app.use(helmet());
@ -47,10 +68,7 @@ function Server () {
// add custom middleware (note: build out to accept dynamically use what is in server/middleware/
app.use(requestLogger);
// configure passport
const speechPassport = require('./server/speechPassport/index');
// initialize passport
const sessionKey = siteConfig.auth.sessionKey;
app.use(cookieSession({
name : 'session',
keys : [sessionKey],
@ -67,32 +85,38 @@ function Server () {
app.set('view engine', 'handlebars');
// set the routes on the app
require('./server/routes/auth/index')(app);
require('./server/routes/api/index')(app);
require('./server/routes/pages/index')(app);
require('./server/routes/assets/index')(app);
require('./server/routes/fallback/index')(app);
require('./server/routes/auth')(app);
require('./server/routes/api')(app);
require('./server/routes/pages')(app);
require('./server/routes/assets')(app);
require('./server/routes/fallback')(app);
this.app = app;
};
this.initialize = () => {
this.createApp();
this.createServer = () => {
/* create server */
this.server = http.Server(this.app);
};
this.start = () => {
const db = require('./server/models/index');
const PORT = siteConfig.details.port;
// sync sequelize
createDatabaseIfNotExists()
this.syncDatabase = () => {
return createDatabaseIfNotExists()
.then(() => {
return getWalletBalance();
})
.then(balance => {
logger.info('starting LBC balance:', balance);
db.sequelize.sync();
this.server.listen(PORT, () => {
})
};
this.start = () => {
this.initialize();
this.createApp();
this.createServer();
/* start the server */
Promise.all([
this.syncDatabase(),
getWalletBalance(),
])
.then(([syncResult, walletBalance]) => {
logger.info('starting LBC balance:', walletBalance);
return this.server.listen(PORT, () => {
logger.info(`Server is listening on PORT ${PORT}`);
});
})
})
.catch(error => {
if (error.code === 'ECONNREFUSED') {
@ -103,6 +127,6 @@ function Server () {
logger.error(error);
});
};
};
}
module.exports = Server;

5
package-lock.json generated
View file

@ -5291,6 +5291,11 @@
}
}
},
"module-alias": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/module-alias/-/module-alias-2.0.6.tgz",
"integrity": "sha1-q7LPoHAU9QNRStUGHG8D15tZGIk="
},
"moment": {
"version": "2.22.1",
"resolved": "http://registry.npmjs.org/moment/-/moment-2.22.1.tgz",

View file

@ -38,6 +38,7 @@
"express": "^4.15.2",
"express-handlebars": "^3.0.0",
"helmet": "^3.8.1",
"module-alias": "^2.0.6",
"mysql2": "^1.3.5",
"passport": "^0.4.0",
"passport-local": "^1.0.0",

View file

@ -1,5 +1,5 @@
const db = require('../../../../models');
const { publishing: { primaryClaimAddress, additionalClaimAddresses } } = require('../../../../../config/siteConfig.js');
const { publishing: { primaryClaimAddress, additionalClaimAddresses } } = require('@config/siteConfig');
const Sequelize = require('sequelize');
const Op = Sequelize.Op;

View file

@ -1,5 +1,5 @@
const logger = require('winston');
const { details, publishing } = require('../../../../../config/siteConfig.js');
const { details, publishing } = require('@config/siteConfig');
const createBasicPublishParams = (filePath, name, title, description, license, nsfw, thumbnail) => {
logger.debug(`Creating Publish Parameters`);

View file

@ -1,5 +1,5 @@
const logger = require('winston');
const { details, publishing } = require('../../../../../config/siteConfig.js');
const { details, publishing } = require('@config/siteConfig');
const createThumbnailPublishParams = (thumbnailFilePath, claimName, license, nsfw) => {
if (!thumbnailFilePath) {

View file

@ -1,4 +1,4 @@
const { details: { host } } = require('../../../../../config/siteConfig.js');
const { details: { host } } = require('@config/siteConfig');
const { sendGATimingEvent } = require('../../../../utils/googleAnalytics.js');

View file

@ -1,4 +1,4 @@
const { details: { host } } = require('../../../config/siteConfig.js');
const { details: { host } } = require('@config/siteConfig');
const sendEmbedPage = ({ params }, res) => {
const claimId = params.claimId;

View file

@ -1,6 +1,6 @@
const axios = require('axios');
const logger = require('winston');
const { api: { apiHost, apiPort } } = require('../../config/lbryConfig.js');
const { apiHost, apiPort } = require('@config/lbryConfig');
const lbrynetUri = 'http://' + apiHost + ':' + apiPort;
const { chooseGaLbrynetPublishLabel, sendGATimingEvent } = require('../utils/googleAnalytics.js');
const handleLbrynetResponse = require('./utils/handleLbrynetResponse.js');

View file

@ -1,6 +1,6 @@
const logger = require('winston');
const returnShortId = require('./utils/returnShortId.js');
const { assetDefaults: { thumbnail: defaultThumbnail }, details: { host } } = require('../../config/siteConfig.js');
const { assetDefaults: { thumbnail: defaultThumbnail }, details: { host } } = require('@config/siteConfig');
const NO_CLAIM = 'NO_CLAIM';

View file

@ -1,3 +1,6 @@
const Sequelize = require('sequelize');
const logger = require('winston');
const Certificate = require('./certificate.js');
const Channel = require('./channel.js');
const Claim = require('./claim.js');
@ -6,10 +9,10 @@ const Request = require('./request.js');
const User = require('./user.js');
const Blocked = require('./blocked.js');
const Sequelize = require('sequelize');
const logger = require('winston');
const {database, username, password} = require('../../config/mysqlConfig.js');
const {database, username, password} = require('@config/mysqlConfig');
if (!database || !username || !password) {
logger.warn('missing database, user, or password from mysqlConfig');
}
// set sequelize options
const sequelize = new Sequelize(database, username, password, {

View file

@ -1,7 +1,7 @@
const Sequelize = require('sequelize');
const {database, username, password} = require('@config/mysqlConfig');
const createDatabaseIfNotExists = () => {
const {database, username, password} = require('../../../config/mysqlConfig.js');
const sequelize = new Sequelize('', username, password, {
dialect : 'mysql',
logging : false,

View file

@ -10,6 +10,8 @@ var _reactRedux = require("react-redux");
var _reactRouterDom = require("react-router-dom");
var _reactHelmet = _interopRequireDefault(require("react-helmet"));
var _reducers = _interopRequireDefault(require("@reducers"));
var _GAListener = _interopRequireDefault(require("@components/GAListener"));
@ -18,27 +20,19 @@ var _app = _interopRequireDefault(require("@app"));
var _renderFullPage = _interopRequireDefault(require("../renderFullPage.js"));
var _reactHelmet = _interopRequireDefault(require("react-helmet"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var siteConfig = require('../../../config/siteConfig.js');
module.exports = function (req, res) {
var context = {}; // customize the reducer by passing in intial state configs
var context = {}; // create a new Redux store instance
var MyReducers = (0, _reducers.default)(siteConfig);
var MyApp = _app.default;
var MyGAListener = (0, _GAListener.default)(siteConfig); // create a new Redux store instance
var store = (0, _redux.createStore)(MyReducers); // render component to a string
var store = (0, _redux.createStore)(_reducers.default); // render component to a string
var html = (0, _server.renderToString)(_react.default.createElement(_reactRedux.Provider, {
store: store
}, _react.default.createElement(_reactRouterDom.StaticRouter, {
location: req.url,
context: context
}, _react.default.createElement(MyGAListener, null, _react.default.createElement(MyApp, null))))); // get head tags from helmet
}, _react.default.createElement(_GAListener.default, null, _react.default.createElement(_app.default, null))))); // get head tags from helmet
var helmet = _reactHelmet.default.renderStatic(); // check for a redirect

View file

@ -16,6 +16,8 @@ var _reduxSaga = _interopRequireDefault(require("redux-saga"));
var _effects = require("redux-saga/effects");
var _reactHelmet = _interopRequireDefault(require("react-helmet"));
var _reducers = _interopRequireDefault(require("@reducers"));
var _GAListener = _interopRequireDefault(require("@components/GAListener"));
@ -26,12 +28,8 @@ var _sagas = _interopRequireDefault(require("@sagas"));
var _actions = _interopRequireDefault(require("@actions"));
var _reactHelmet = _interopRequireDefault(require("react-helmet"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var siteConfig = require('../../../config/siteConfig.js');
var returnSagaWithParams = function returnSagaWithParams(saga, params) {
return (
/*#__PURE__*/
@ -54,16 +52,12 @@ var returnSagaWithParams = function returnSagaWithParams(saga, params) {
};
module.exports = function (req, res) {
var context = {}; // configure the reducers by passing initial state configs
var MyReducers = (0, _reducers.default)(siteConfig);
var MyApp = _app.default;
var MyGAListener = (0, _GAListener.default)(siteConfig); // create and apply middleware
var context = {}; // create and apply middleware
var sagaMiddleware = (0, _reduxSaga.default)();
var middleware = (0, _redux.applyMiddleware)(sagaMiddleware); // create a new Redux store instance
var store = (0, _redux.createStore)(MyReducers, middleware); // create saga
var store = (0, _redux.createStore)(_reducers.default, middleware); // create saga
var action = _actions.default.onHandleShowPageUri(req.params);
@ -76,7 +70,7 @@ module.exports = function (req, res) {
}, _react.default.createElement(_reactRouterDom.StaticRouter, {
location: req.url,
context: context
}, _react.default.createElement(MyGAListener, null, _react.default.createElement(MyApp, null))))); // get head tags from helmet
}, _react.default.createElement(_GAListener.default, null, _react.default.createElement(_app.default, null))))); // get head tags from helmet
var helmet = _reactHelmet.default.renderStatic(); // check for a redirect

View file

@ -3,32 +3,26 @@ import { renderToString } from 'react-dom/server';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { StaticRouter } from 'react-router-dom';
import Helmet from 'react-helmet';
import Reducers from '@reducers';
import GAListener from '@components/GAListener';
import App from '@app';
import renderFullPage from '../renderFullPage.js';
import Helmet from 'react-helmet';
const siteConfig = require('../../../config/siteConfig.js');
module.exports = (req, res) => {
let context = {};
// customize the reducer by passing in intial state configs
const MyReducers = Reducers(siteConfig);
const MyApp = App;
const MyGAListener = GAListener(siteConfig);
// create a new Redux store instance
const store = createStore(MyReducers);
const store = createStore(Reducers);
// render component to a string
const html = renderToString(
<Provider store={store}>
<StaticRouter location={req.url} context={context}>
<MyGAListener>
<MyApp />
</MyGAListener>
<GAListener>
<App />
</GAListener>
</StaticRouter>
</Provider>
);

View file

@ -6,14 +6,13 @@ import { StaticRouter } from 'react-router-dom';
import renderFullPage from '../renderFullPage';
import createSagaMiddleware from 'redux-saga';
import { call } from 'redux-saga/effects';
import Helmet from 'react-helmet';
import Reducers from '@reducers';
import GAListener from '@components/GAListener';
import App from '@app';
import Sagas from '@sagas';
import Actions from '@actions';
import Helmet from 'react-helmet';
const siteConfig = require('../../../config/siteConfig.js');
const returnSagaWithParams = (saga, params) => {
return function * () {
@ -24,17 +23,12 @@ const returnSagaWithParams = (saga, params) => {
module.exports = (req, res) => {
let context = {};
// configure the reducers by passing initial state configs
const MyReducers = Reducers(siteConfig);
const MyApp = App;
const MyGAListener = GAListener(siteConfig);
// create and apply middleware
const sagaMiddleware = createSagaMiddleware();
const middleware = applyMiddleware(sagaMiddleware);
// create a new Redux store instance
const store = createStore(MyReducers, middleware);
const store = createStore(Reducers, middleware);
// create saga
const action = Actions.onHandleShowPageUri(req.params);
@ -49,9 +43,9 @@ module.exports = (req, res) => {
const html = renderToString(
<Provider store={store}>
<StaticRouter location={req.url} context={context}>
<MyGAListener>
<MyApp />
</MyGAListener>
<GAListener>
<App />
</GAListener>
</StaticRouter>
</Provider>
);

View file

@ -1,5 +1,5 @@
const multipart = require('connect-multiparty');
const { publishing: { uploadDirectory } } = require('../../../config/siteConfig.js');
const { publishing: { uploadDirectory } } = require('@config/siteConfig');
const multipartMiddleware = multipart({uploadDir: uploadDirectory});
module.exports = multipartMiddleware;

View file

@ -0,0 +1,9 @@
const logger = require('winston');
module.exports = (name) => {
const config = require(`@config/${name}`);
if (!config) {
return logger.warn(`Server could not find config file for ${name}.`);
}
logger.debug(`found ${name} config:`, config);
};

View file

@ -0,0 +1,36 @@
const logger = require('winston');
const config = require('@config/loggerConfig');
const { logLevel } = config;
function configureLogging () {
logger.info('configuring winston logger...');
if (!config) {
return logger.warn('No logger config found');
}
if (!logLevel) {
logger.warn('No logLevel found in config.');
}
// configure the winston logger
logger.configure({
transports: [
new (logger.transports.Console)({
level : logLevel || 'debug',
timestamp : false,
colorize : true,
prettyPrint : true,
handleExceptions : true,
humanReadableUnhandledException: true,
}),
],
});
// test all the log levels
logger.info('testing winston log levels...');
logger.warn('Testing: Log Level 1');
logger.info('Testing: Log Level 2');
logger.verbose('Testing: Log Level 3');
logger.debug('Testing: Log Level 4');
logger.silly('Testing: Log Level 5');
}
module.exports = configureLogging;

View file

@ -0,0 +1,46 @@
const winstonSlackWebHook = require('winston-slack-webhook').SlackWebHook;
const logger = require('winston');
const config = require('@config/slackConfig');
const {slackWebHook, slackErrorChannel, slackInfoChannel} = config;
function configureSlack () {
logger.info('configuring slack logger...');
if (!config) {
return logger.warn('No slack config found');
}
// update slack webhook settings
if (!slackWebHook) {
return logger.info('Slack logging is not enabled because no slackWebHook config var provided.');
}
// add a transport for errors to slack
if (slackErrorChannel) {
logger.add(winstonSlackWebHook, {
name : 'slack-errors-transport',
level : 'warn',
webhookUrl: slackWebHook,
channel : slackErrorChannel,
username : 'spee.ch',
iconEmoji : ':face_with_head_bandage:',
});
} else {
logger.warn('No slack error channel logging set up');
}
// add a transport for info in slack
if (slackInfoChannel) {
logger.add(winstonSlackWebHook, {
name : 'slack-info-transport',
level : 'info',
webhookUrl: slackWebHook,
channel : slackInfoChannel,
username : 'spee.ch',
iconEmoji : ':nerd_face:',
});
} else {
logger.warn('No slack info channel logging set up');
}
// send test messages
logger.info('Slack logging is online.');
}
module.exports = configureSlack;

View file

@ -0,0 +1,11 @@
const { resolve } = require('path');
const WWW_SPEECH_ROOT = resolve(process.cwd());
module.exports = () => {
let moduleAliases = {};
// default aliases
moduleAliases['@config'] = resolve(WWW_SPEECH_ROOT, 'config');
moduleAliases['@public'] = resolve(WWW_SPEECH_ROOT, 'public');
// return finished aliases
return moduleAliases;
};

View file

@ -1,8 +1,8 @@
const logger = require('winston');
const ua = require('universal-analytics');
const { analytics : { googleId }, details: { title } } = require('../../config/siteConfig.js');
const { analytics : { googleId }, details: { title } } = require('@config/siteConfig');
function createServeEventParams (headers, ip, originalUrl) {
const createServeEventParams = (headers, ip, originalUrl) => {
return {
eventCategory : 'client requests',
eventAction : 'serve request',
@ -11,9 +11,9 @@ function createServeEventParams (headers, ip, originalUrl) {
userAgentOverride: headers['user-agent'],
documentReferrer : headers['referer'],
};
}
};
function createPublishTimingEventParams (category, variable, label, startTime, endTime) {
const createTimingEventParams = (category, variable, label, startTime, endTime) => {
const duration = endTime - startTime;
return {
userTimingCategory : category,
@ -21,43 +21,48 @@ function createPublishTimingEventParams (category, variable, label, startTime, e
userTimingTime : duration,
userTimingLabel : label,
};
}
};
function sendGoogleAnalyticsEvent (ip, params) {
const sendGoogleAnalyticsEvent = (ip, params) => {
if (!googleId) {
return logger.debug('Skipping analytics event because no GoogleId present in configs');
}
const visitorId = ip.replace(/\./g, '-');
const visitor = ua(googleId, visitorId, { strictCidFormat: false, https: true });
visitor.event(params, (err) => {
if (err) {
logger.error('Google Analytics Event Error >>', err);
return logger.error('Google Analytics Event Error >>', err);
}
logger.debug(`Event successfully sent to google analytics`);
logger.debug(`Event successfully sent to google analytics`, params);
});
}
};
function sendGoogleAnalyticsTiming (visitorId, params) {
const visitor = ua(googleId, visitorId, { strictCidFormat: false, https: true });
const sendGoogleAnalyticsTiming = (siteTitle, params) => {
if (!googleId) {
return logger.debug('Skipping analytics timing because no GoogleId present in configs');
}
const visitor = ua(googleId, siteTitle, { strictCidFormat: false, https: true });
visitor.timing(params, (err) => {
if (err) {
logger.error('Google Analytics Event Error >>', err);
return logger.error('Google Analytics Event Error >>', err);
}
logger.debug(`Timing event successfully sent to google analytics`);
logger.debug(`Event successfully sent to google analytics`, params);
});
}
};
function sendGAServeEvent (headers, ip, originalUrl) {
logger.debug('headers:', headers);
const sendGAServeEvent = (headers, ip, originalUrl) => {
const params = createServeEventParams(headers, ip, originalUrl);
sendGoogleAnalyticsEvent(ip, params);
}
};
function sendGATimingEvent (category, variable, label, startTime, endTime) {
const params = createPublishTimingEventParams(category, variable, label, startTime, endTime);
const sendGATimingEvent = (category, variable, label, startTime, endTime) => {
const params = createTimingEventParams(category, variable, label, startTime, endTime);
sendGoogleAnalyticsTiming(title, params);
}
};
function chooseGaLbrynetPublishLabel ({ channel_name: channelName, channel_id: channelId }) {
const chooseGaLbrynetPublishLabel = ({ channel_name: channelName, channel_id: channelId }) => {
return (channelName || channelId ? 'PUBLISH_IN_CHANNEL_CLAIM' : 'PUBLISH_ANONYMOUS_CLAIM');
}
};
module.exports = {
sendGAServeEvent,

View file

@ -1,8 +1,8 @@
const chai = require('chai');
const expect = chai.expect;
const chaiHttp = require('chai-http');
const { details: { host } } = require('../../config/siteConfig.js');
const { testChannel, testChannelId, testChannelPassword } = require('../../devConfig/testingConfig.js');
const { details: { host } } = require('@config/siteConfig');
const { testChannel, testChannelId, testChannelPassword } = require('@devConfig/testingConfig.js');
const requestTimeout = 20000;
const publishTimeout = 120000;
const fs = require('fs');