diff --git a/client/build/app.js b/client/build/app.js index b77df70b..f740da7e 100644 --- a/client/build/app.js +++ b/client/build/app.js @@ -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; \ No newline at end of file diff --git a/client/build/components/GAListener/index.js b/client/build/components/GAListener/index.js index 54a99a0f..2e5d81bd 100644 --- a/client/build/components/GAListener/index.js +++ b/client/build/components/GAListener/index.js @@ -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,49 +33,54 @@ 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__*/ - function (_React$Component) { - function GAListener() { - _classCallCheck(this, GAListener); +var GAListener = +/*#__PURE__*/ +function (_React$Component) { + function GAListener() { + _classCallCheck(this, GAListener); - return _possibleConstructorReturn(this, _getPrototypeOf(GAListener).apply(this, arguments)); + return _possibleConstructorReturn(this, _getPrototypeOf(GAListener).apply(this, arguments)); + } + + _createClass(GAListener, [{ + key: "componentDidMount", + value: function componentDidMount() { + this.sendPageView(this.props.history.location); + this.props.history.listen(this.sendPageView); } - - _createClass(GAListener, [{ - key: "componentDidMount", - value: function componentDidMount() { - this.sendPageView(this.props.history.location); - this.props.history.listen(this.sendPageView); - } - }, { - key: "sendPageView", - value: function sendPageView(location) { + }, { + key: "sendPageView", + value: function sendPageView(location) { + if (googleId) { _reactGa.default.set({ page: location.pathname }); _reactGa.default.pageview(location.pathname); } - }, { - key: "render", - value: function render() { - return this.props.children; - } - }]); + } + }, { + key: "render", + value: function render() { + return this.props.children; + } + }]); - _inherits(GAListener, _React$Component); + _inherits(GAListener, _React$Component); - return GAListener; - }(_react.default.Component); + return GAListener; +}(_react.default.Component); - return (0, _reactRouterDom.withRouter)(GAListener); -}; +var _default = (0, _reactRouterDom.withRouter)(GAListener); -var _default = customGAListener; exports.default = _default; \ No newline at end of file diff --git a/client/build/reducers/index.js b/client/build/reducers/index.js index cccf793d..9bc6f63b 100644 --- a/client/build/reducers/index.js +++ b/client/build/reducers/index.js @@ -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)({ - channel: _channel.default, - channelCreate: _channelCreate.default, - publish: (0, _publish.default)(siteConfig), - show: _show.default, - site: (0, _site.default)(siteConfig) - }); -}; +// modules +// local modules +var _default = (0, _redux.combineReducers)({ + channel: _channel.default, + channelCreate: _channelCreate.default, + publish: _publish.default, + show: _show.default, + site: _site.default +}); -var _default = customizedReducers; exports.default = _default; \ No newline at end of file diff --git a/client/build/reducers/publish.js b/client/build/reducers/publish.js index a7ee6054..e1b0f4f0 100644 --- a/client/build/reducers/publish.js +++ b/client/build/reducers/publish.js @@ -3,119 +3,121 @@ 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 = ''; +// 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; - } - } // create initial state +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 - var initialState = { - disabled: disabledConfig, - disabledMessage: disabledMessageConfig, - publishInChannel: false, - selectedChannel: _publish_channel_select_states.LOGIN, - showMetadataInputs: false, - status: { - status: null, - message: null - }, - error: { - file: null, - url: null, - channel: null - }, +var initialState = { + disabled: disabledConfig, + disabledMessage: disabledMessageConfig, + publishInChannel: false, + selectedChannel: _publish_channel_select_states.LOGIN, + showMetadataInputs: false, + status: { + status: null, + message: null + }, + error: { file: null, - claim: '', - metadata: { - title: '', - description: '', - license: '', - nsfw: false - }, - thumbnail: null, - thumbnailChannel: thumbnailChannel, - thumbnailChannelId: thumbnailChannelId - }; - return function () { - var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; - var action = arguments.length > 1 ? arguments[1] : undefined; - - switch (action.type) { - case actions.FILE_SELECTED: - return Object.assign({}, initialState, { - // note: clears to initial state - file: action.data - }); - - case actions.FILE_CLEAR: - return initialState; - - case actions.METADATA_UPDATE: - return Object.assign({}, state, { - metadata: Object.assign({}, state.metadata, _defineProperty({}, action.data.name, action.data.value)) - }); - - case actions.CLAIM_UPDATE: - return Object.assign({}, state, { - claim: action.data - }); - - case actions.SET_PUBLISH_IN_CHANNEL: - return Object.assign({}, state, { - publishInChannel: action.channel - }); - - case actions.PUBLISH_STATUS_UPDATE: - return Object.assign({}, state, { - status: action.data - }); - - case actions.ERROR_UPDATE: - return Object.assign({}, state, { - error: Object.assign({}, state.error, _defineProperty({}, action.data.name, action.data.value)) - }); - - case actions.SELECTED_CHANNEL_UPDATE: - return Object.assign({}, state, { - selectedChannel: action.data - }); - - case actions.TOGGLE_METADATA_INPUTS: - return Object.assign({}, state, { - showMetadataInputs: action.data - }); - - case actions.THUMBNAIL_NEW: - return Object.assign({}, state, { - thumbnail: action.data - }); - - default: - return state; - } - }; + url: null, + channel: null + }, + file: null, + claim: '', + metadata: { + title: '', + description: '', + license: '', + nsfw: false + }, + thumbnail: null, + thumbnailChannel: thumbnailChannel, + thumbnailChannelId: thumbnailChannelId }; -var _default = customizedPublishReducer; -exports.default = _default; \ No newline at end of file +function _default() { + var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; + var action = arguments.length > 1 ? arguments[1] : undefined; + + switch (action.type) { + case actions.FILE_SELECTED: + return Object.assign({}, initialState, { + // note: clears to initial state + file: action.data + }); + + case actions.FILE_CLEAR: + return initialState; + + case actions.METADATA_UPDATE: + return Object.assign({}, state, { + metadata: Object.assign({}, state.metadata, _defineProperty({}, action.data.name, action.data.value)) + }); + + case actions.CLAIM_UPDATE: + return Object.assign({}, state, { + claim: action.data + }); + + case actions.SET_PUBLISH_IN_CHANNEL: + return Object.assign({}, state, { + publishInChannel: action.channel + }); + + case actions.PUBLISH_STATUS_UPDATE: + return Object.assign({}, state, { + status: action.data + }); + + case actions.ERROR_UPDATE: + return Object.assign({}, state, { + error: Object.assign({}, state.error, _defineProperty({}, action.data.name, action.data.value)) + }); + + case actions.SELECTED_CHANNEL_UPDATE: + return Object.assign({}, state, { + selectedChannel: action.data + }); + + case actions.TOGGLE_METADATA_INPUTS: + return Object.assign({}, state, { + showMetadataInputs: action.data + }); + + case actions.THUMBNAIL_NEW: + return Object.assign({}, state, { + thumbnail: action.data + }); + + default: + return state; + } +} + +; \ No newline at end of file diff --git a/client/build/reducers/site.js b/client/build/reducers/site.js index ea6c37f1..604f2e5d 100644 --- a/client/build/reducers/site.js +++ b/client/build/reducers/site.js @@ -3,52 +3,51 @@ 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, - defaultThumbnail = _siteConfig$assetDefa.thumbnail, - defaultDescription = _siteConfig$assetDefa.description, - _siteConfig$details = siteConfig.details, - description = _siteConfig$details.description, - host = _siteConfig$details.host, - title = _siteConfig$details.title, - twitter = _siteConfig$details.twitter; - initialState = { - description: description, - googleAnalyticsId: googleAnalyticsId, - host: host, - title: title, - twitter: twitter, - 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' - }; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return function () { - var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; - var action = arguments.length > 1 ? arguments[1] : undefined; - - switch (action.type) { - default: - return state; - } - }; +var initialState = { + description: 'default description', + googleAnalyticsId: 'default google id', + host: 'default host', + title: 'default title', + twitter: 'default twitter', + defaultDescription: 'default description', + defaultThumbnail: 'default thumbnail' }; -var _default = customizedSiteReducer; -exports.default = _default; \ No newline at end of file +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.default.details, + description = _siteConfig$details.description, + host = _siteConfig$details.host, + title = _siteConfig$details.title, + twitter = _siteConfig$details.twitter; + initialState = { + description: description, + googleAnalyticsId: googleAnalyticsId, + host: host, + title: title, + twitter: twitter, + defaultDescription: defaultDescription, + defaultThumbnail: defaultThumbnail + }; +} + +function _default() { + var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; + var action = arguments.length > 1 ? arguments[1] : undefined; + + switch (action.type) { + default: + return state; + } +} + +; \ No newline at end of file diff --git a/client/src/app.js b/client/src/app.js index ce77de14..f6c23062 100644 --- a/client/src/app.js +++ b/client/src/app.js @@ -8,7 +8,7 @@ import ShowPage from '@pages/ShowPage'; import FourOhFourPage from '@pages/FourOhFourPage'; import MultisitePage from '@pages/MultisitePage'; -const customizedApp = () => { +const App = () => { return ( @@ -22,4 +22,4 @@ const customizedApp = () => { ); }; -export default customizedApp; +export default App; diff --git a/client/src/components/GAListener/index.jsx b/client/src/components/GAListener/index.jsx index 516034ec..718fb4ca 100644 --- a/client/src/components/GAListener/index.jsx +++ b/client/src/components/GAListener/index.jsx @@ -2,28 +2,34 @@ 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'; - GoogleAnalytics.initialize(googleId); +let googleId = null; - class GAListener extends React.Component { - componentDidMount () { - this.sendPageView(this.props.history.location); - this.props.history.listen(this.sendPageView); - } +if (siteConfig && siteConfig.analytics) { + ({ googleId } = siteConfig.analytics); +} - sendPageView (location) { - GoogleAnalytics.set({ page: location.pathname }); - GoogleAnalytics.pageview(location.pathname); - } +if (googleId) { + GoogleAnalytics.initialize(googleId); +} - render () { - return this.props.children; - } +class GAListener extends React.Component { + componentDidMount () { + this.sendPageView(this.props.history.location); + this.props.history.listen(this.sendPageView); + } + + sendPageView (location) { + if (googleId) { + GoogleAnalytics.set({ page: location.pathname }); + GoogleAnalytics.pageview(location.pathname); } + } - return withRouter(GAListener); -}; + render () { + return this.props.children; + } +} -export default customGAListener; +export default withRouter(GAListener); diff --git a/client/src/reducers/index.js b/client/src/reducers/index.js index 794888e1..75893410 100644 --- a/client/src/reducers/index.js +++ b/client/src/reducers/index.js @@ -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({ - channel : ChannelReducer, - channelCreate: ChannelCreateReducer, - publish : PublishReducer(siteConfig), - show : ShowReducer, - site : SiteReducer(siteConfig), - }) -}; - -export default customizedReducers; +export default combineReducers({ + channel : ChannelReducer, + channelCreate: ChannelCreateReducer, + publish : PublishReducer, + show : ShowReducer, + site : SiteReducer, +}); diff --git a/client/src/reducers/publish.js b/client/src/reducers/publish.js index 6138cbe9..29a31d7d 100644 --- a/client/src/reducers/publish.js +++ b/client/src/reducers/publish.js @@ -1,96 +1,96 @@ import * as actions from '../constants/publish_action_types'; import { LOGIN } from '../constants/publish_channel_select_states'; -const customizedPublishReducer = (siteConfig) => { - // parse inputs - let disabledConfig = false; - let disabledMessageConfig = 'none'; - let thumbnailChannel = ''; - let thumbnailChannelId = ''; - if (siteConfig) { - if (siteConfig.publishing) { - disabledConfig = siteConfig.publishing.disabled; - disabledMessageConfig = siteConfig.publishing.disabledMessage; - thumbnailChannel = siteConfig.publishing.thumbnailChannel; - thumbnailChannelId = siteConfig.publishing.thumbnailChannelId; - } +import siteConfig from '@config/siteConfig.json'; + +// parse inputs +let disabledConfig = false; +let disabledMessageConfig = 'none'; +let thumbnailChannel = ''; +let thumbnailChannelId = ''; +if (siteConfig) { + if (siteConfig.publishing) { + disabledConfig = siteConfig.publishing.disabled; + disabledMessageConfig = siteConfig.publishing.disabledMessage; + thumbnailChannel = siteConfig.publishing.thumbnailChannel; + thumbnailChannelId = siteConfig.publishing.thumbnailChannelId; } - // create initial state - const initialState = { - disabled : disabledConfig, - disabledMessage : disabledMessageConfig, - publishInChannel : false, - selectedChannel : LOGIN, - showMetadataInputs: false, - status : { - status : null, - message: null, - }, - error: { - file : null, - url : null, - channel: null, - }, - file : null, - claim : '', - metadata: { - title : '', - description: '', - license : '', - nsfw : false, - }, - thumbnail: null, - thumbnailChannel, - thumbnailChannelId, - }; - return (state = initialState, action) => { - switch (action.type) { - case actions.FILE_SELECTED: - return Object.assign({}, initialState, { // note: clears to initial state - file: action.data, - }); - case actions.FILE_CLEAR: - return initialState; - case actions.METADATA_UPDATE: - return Object.assign({}, state, { - metadata: Object.assign({}, state.metadata, { - [action.data.name]: action.data.value, - }), - }); - case actions.CLAIM_UPDATE: - return Object.assign({}, state, { - claim: action.data, - }); - case actions.SET_PUBLISH_IN_CHANNEL: - return Object.assign({}, state, { - publishInChannel: action.channel, - }); - case actions.PUBLISH_STATUS_UPDATE: - return Object.assign({}, state, { - status: action.data, - }); - case actions.ERROR_UPDATE: - return Object.assign({}, state, { - error: Object.assign({}, state.error, { - [action.data.name]: action.data.value, - }), - }); - case actions.SELECTED_CHANNEL_UPDATE: - return Object.assign({}, state, { - selectedChannel: action.data, - }); - case actions.TOGGLE_METADATA_INPUTS: - return Object.assign({}, state, { - showMetadataInputs: action.data, - }); - case actions.THUMBNAIL_NEW: - return Object.assign({}, state, { - thumbnail: action.data, - }); - default: - return state; - } - }; +} + +// create initial state +const initialState = { + disabled : disabledConfig, + disabledMessage : disabledMessageConfig, + publishInChannel : false, + selectedChannel : LOGIN, + showMetadataInputs: false, + status : { + status : null, + message: null, + }, + error: { + file : null, + url : null, + channel: null, + }, + file : null, + claim : '', + metadata: { + title : '', + description: '', + license : '', + nsfw : false, + }, + thumbnail: null, + thumbnailChannel, + thumbnailChannelId, }; -export default customizedPublishReducer; +export default function (state = initialState, action) { + switch (action.type) { + case actions.FILE_SELECTED: + return Object.assign({}, initialState, { // note: clears to initial state + file: action.data, + }); + case actions.FILE_CLEAR: + return initialState; + case actions.METADATA_UPDATE: + return Object.assign({}, state, { + metadata: Object.assign({}, state.metadata, { + [action.data.name]: action.data.value, + }), + }); + case actions.CLAIM_UPDATE: + return Object.assign({}, state, { + claim: action.data, + }); + case actions.SET_PUBLISH_IN_CHANNEL: + return Object.assign({}, state, { + publishInChannel: action.channel, + }); + case actions.PUBLISH_STATUS_UPDATE: + return Object.assign({}, state, { + status: action.data, + }); + case actions.ERROR_UPDATE: + return Object.assign({}, state, { + error: Object.assign({}, state.error, { + [action.data.name]: action.data.value, + }), + }); + case actions.SELECTED_CHANNEL_UPDATE: + return Object.assign({}, state, { + selectedChannel: action.data, + }); + case actions.TOGGLE_METADATA_INPUTS: + return Object.assign({}, state, { + showMetadataInputs: action.data, + }); + case actions.THUMBNAIL_NEW: + return Object.assign({}, state, { + thumbnail: action.data, + }); + default: + return state; + } +}; diff --git a/client/src/reducers/site.js b/client/src/reducers/site.js index 5a1b1584..6b0b3e61 100644 --- a/client/src/reducers/site.js +++ b/client/src/reducers/site.js @@ -1,48 +1,46 @@ -const customizedSiteReducer = (siteConfig) => { - let initialState = {}; - if (siteConfig) { - const { - analytics: { - googleId: googleAnalyticsId, - }, - assetDefaults: { - thumbnail: defaultThumbnail, - description: defaultDescription, - }, - details: { - description, - host, - title, - twitter, - }, - } = siteConfig; +import siteConfig from '@config/siteConfig.json'; - initialState = { +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: { + googleId: googleAnalyticsId, + }, + assetDefaults: { + thumbnail: defaultThumbnail, + description: defaultDescription, + }, + details: { description, - googleAnalyticsId, host, title, twitter, - 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) => { - switch (action.type) { - default: - return state; - } - }; -}; + }, + } = siteConfig; -export default customizedSiteReducer; + initialState = { + description, + googleAnalyticsId, + host, + title, + twitter, + defaultDescription, + defaultThumbnail, + }; +} + +export default function (state = initialState, action) { + switch (action.type) { + default: + return state; + } +}; diff --git a/config/lbryConfig.js b/config/lbryConfig.js deleted file mode 100644 index 0e3a5c82..00000000 --- a/config/lbryConfig.js +++ /dev/null @@ -1,8 +0,0 @@ -const lbryConfig = { - api: { - apiHost: 'localhost', - apiPort: '5279', - }, -}; - -module.exports = lbryConfig; diff --git a/config/loggerConfig.js b/config/loggerConfig.js deleted file mode 100644 index df81d7e5..00000000 --- a/config/loggerConfig.js +++ /dev/null @@ -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(); diff --git a/config/mysqlConfig.js b/config/mysqlConfig.js deleted file mode 100644 index 07301eb8..00000000 --- a/config/mysqlConfig.js +++ /dev/null @@ -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(); diff --git a/config/siteConfig.js b/config/siteConfig.js deleted file mode 100644 index 38a5bc67..00000000 --- a/config/siteConfig.js +++ /dev/null @@ -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(); diff --git a/config/slackConfig.js b/config/slackConfig.js deleted file mode 100644 index 56008a27..00000000 --- a/config/slackConfig.js +++ /dev/null @@ -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(); diff --git a/index.js b/index.js index 0762fed2..7d6f789c 100644 --- a/index.js +++ b/index.js @@ -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; diff --git a/package-lock.json b/package-lock.json index 11a4515a..2e9a4fd1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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", diff --git a/package.json b/package.json index 386622ae..065928fb 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/server/controllers/api/claim/availability/checkClaimAvailability.js b/server/controllers/api/claim/availability/checkClaimAvailability.js index 68c31056..37ecdfda 100644 --- a/server/controllers/api/claim/availability/checkClaimAvailability.js +++ b/server/controllers/api/claim/availability/checkClaimAvailability.js @@ -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; diff --git a/server/controllers/api/claim/publish/createBasicPublishParams.js b/server/controllers/api/claim/publish/createBasicPublishParams.js index 7ede4ad7..6ab4acd8 100644 --- a/server/controllers/api/claim/publish/createBasicPublishParams.js +++ b/server/controllers/api/claim/publish/createBasicPublishParams.js @@ -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`); diff --git a/server/controllers/api/claim/publish/createThumbnailPublishParams.js b/server/controllers/api/claim/publish/createThumbnailPublishParams.js index c10d9cd9..1032c9a3 100644 --- a/server/controllers/api/claim/publish/createThumbnailPublishParams.js +++ b/server/controllers/api/claim/publish/createThumbnailPublishParams.js @@ -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) { diff --git a/server/controllers/api/claim/publish/index.js b/server/controllers/api/claim/publish/index.js index 0a748753..15e48ee9 100644 --- a/server/controllers/api/claim/publish/index.js +++ b/server/controllers/api/claim/publish/index.js @@ -1,4 +1,4 @@ -const { details: { host } } = require('../../../../../config/siteConfig.js'); +const { details: { host } } = require('@config/siteConfig'); const { sendGATimingEvent } = require('../../../../utils/googleAnalytics.js'); diff --git a/server/controllers/pages/sendEmbedPage.js b/server/controllers/pages/sendEmbedPage.js index ae3979b1..d4bef437 100644 --- a/server/controllers/pages/sendEmbedPage.js +++ b/server/controllers/pages/sendEmbedPage.js @@ -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; diff --git a/server/lbrynet/index.js b/server/lbrynet/index.js index 90a45875..bab4ede0 100644 --- a/server/lbrynet/index.js +++ b/server/lbrynet/index.js @@ -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'); diff --git a/server/models/claim.js b/server/models/claim.js index 75a221f5..4200e485 100644 --- a/server/models/claim.js +++ b/server/models/claim.js @@ -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'; diff --git a/server/models/index.js b/server/models/index.js index 748db1b8..e2011bc8 100644 --- a/server/models/index.js +++ b/server/models/index.js @@ -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, { diff --git a/server/models/utils/createDatabaseIfNotExists.js b/server/models/utils/createDatabaseIfNotExists.js index 4a717067..7349b492 100644 --- a/server/models/utils/createDatabaseIfNotExists.js +++ b/server/models/utils/createDatabaseIfNotExists.js @@ -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, diff --git a/server/render/build/handlePageRender.js b/server/render/build/handlePageRender.js index e7a40f60..f07cbe55 100644 --- a/server/render/build/handlePageRender.js +++ b/server/render/build/handlePageRender.js @@ -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 diff --git a/server/render/build/handleShowRender.js b/server/render/build/handleShowRender.js index c7b08082..0dbef501 100644 --- a/server/render/build/handleShowRender.js +++ b/server/render/build/handleShowRender.js @@ -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 diff --git a/server/render/src/handlePageRender.jsx b/server/render/src/handlePageRender.jsx index ae17bae0..f10704b1 100644 --- a/server/render/src/handlePageRender.jsx +++ b/server/render/src/handlePageRender.jsx @@ -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( - - - + + + ); diff --git a/server/render/src/handleShowRender.jsx b/server/render/src/handleShowRender.jsx index 28cd2bb0..8621b597 100644 --- a/server/render/src/handleShowRender.jsx +++ b/server/render/src/handleShowRender.jsx @@ -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( - - - + + + ); diff --git a/server/routes/utils/multipartMiddleware.js b/server/routes/utils/multipartMiddleware.js index bd2e98f6..c193e147 100644 --- a/server/routes/utils/multipartMiddleware.js +++ b/server/routes/utils/multipartMiddleware.js @@ -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; diff --git a/server/utils/checkForConfig.js b/server/utils/checkForConfig.js new file mode 100644 index 00000000..44fc80ff --- /dev/null +++ b/server/utils/checkForConfig.js @@ -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); +}; diff --git a/server/utils/configureLogging.js b/server/utils/configureLogging.js new file mode 100644 index 00000000..49af20bb --- /dev/null +++ b/server/utils/configureLogging.js @@ -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; diff --git a/server/utils/configureSlack.js b/server/utils/configureSlack.js new file mode 100644 index 00000000..feef1122 --- /dev/null +++ b/server/utils/configureSlack.js @@ -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; diff --git a/server/utils/createModuleAliases.js b/server/utils/createModuleAliases.js new file mode 100644 index 00000000..4420a6a7 --- /dev/null +++ b/server/utils/createModuleAliases.js @@ -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; +}; diff --git a/server/utils/googleAnalytics.js b/server/utils/googleAnalytics.js index 1932b145..a193155b 100644 --- a/server/utils/googleAnalytics.js +++ b/server/utils/googleAnalytics.js @@ -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, diff --git a/test/end-to-end/end-to-end.tests.js b/test/end-to-end/end-to-end.tests.js index 0c206c39..ee055b0a 100644 --- a/test/end-to-end/end-to-end.tests.js +++ b/test/end-to-end/end-to-end.tests.js @@ -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');