From 3f5b20f5db285113d9f745939cff1e11237d29aa Mon Sep 17 00:00:00 2001 From: bill bittner Date: Tue, 5 Jun 2018 16:24:27 -0700 Subject: [PATCH 01/15] changed functions to consts --- server/utils/googleAnalytics.js | 33 ++++++++++++++++----------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/server/utils/googleAnalytics.js b/server/utils/googleAnalytics.js index 1932b145..65680f24 100644 --- a/server/utils/googleAnalytics.js +++ b/server/utils/googleAnalytics.js @@ -2,7 +2,7 @@ const logger = require('winston'); const ua = require('universal-analytics'); const { analytics : { googleId }, details: { title } } = require('../../config/siteConfig.js'); -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 createPublishTimingEventParams = (category, variable, label, startTime, endTime) => { const duration = endTime - startTime; return { userTimingCategory : category, @@ -21,43 +21,42 @@ function createPublishTimingEventParams (category, variable, label, startTime, e userTimingTime : duration, userTimingLabel : label, }; -} +}; -function sendGoogleAnalyticsEvent (ip, params) { +const sendGoogleAnalyticsEvent = (ip, params) => { 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`); }); -} +}; -function sendGoogleAnalyticsTiming (visitorId, params) { +const sendGoogleAnalyticsTiming = (visitorId, params) => { const visitor = ua(googleId, visitorId, { 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`); }); -} +}; -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 sendGATimingEvent = (category, variable, label, startTime, endTime) => { const params = createPublishTimingEventParams(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, -- 2.45.2 From 6851ace4dd39469e9b55101f90bb651e20eb2033 Mon Sep 17 00:00:00 2001 From: bill bittner Date: Tue, 5 Jun 2018 18:01:29 -0700 Subject: [PATCH 02/15] updated siteConfig logging --- config/siteConfig.js | 4 +++- server/utils/googleAnalytics.js | 14 ++++++++------ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/config/siteConfig.js b/config/siteConfig.js index 38a5bc67..0f92cbbe 100644 --- a/config/siteConfig.js +++ b/config/siteConfig.js @@ -1,3 +1,5 @@ +const logger = require('winston'); + function SiteConfig () { this.analytics = { googleId: 'default', @@ -31,7 +33,7 @@ function SiteConfig () { return console.log('No site config received.'); } const { analytics, assetDefaults, auth, details, publishing } = config; - console.log('Configuring site details...'); + logger.info('configuring site details...'); this.analytics = analytics; this.assetDefaults = assetDefaults; this.auth = auth; diff --git a/server/utils/googleAnalytics.js b/server/utils/googleAnalytics.js index 65680f24..67abb91e 100644 --- a/server/utils/googleAnalytics.js +++ b/server/utils/googleAnalytics.js @@ -13,7 +13,7 @@ const createServeEventParams = (headers, ip, originalUrl) => { }; }; -const createPublishTimingEventParams = (category, variable, label, startTime, endTime) => { +const createTimingEventParams = (category, variable, label, startTime, endTime) => { const duration = endTime - startTime; return { userTimingCategory : category, @@ -24,23 +24,25 @@ const createPublishTimingEventParams = (category, variable, label, startTime, en }; const sendGoogleAnalyticsEvent = (ip, params) => { + logger.debug('googleId', googleId); const visitorId = ip.replace(/\./g, '-'); const visitor = ua(googleId, visitorId, { strictCidFormat: false, https: true }); visitor.event(params, (err) => { if (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); }); }; -const sendGoogleAnalyticsTiming = (visitorId, params) => { - const visitor = ua(googleId, visitorId, { strictCidFormat: false, https: true }); +const sendGoogleAnalyticsTiming = (siteTitle, params) => { + logger.debug('googleId', googleId); + const visitor = ua(googleId, siteTitle, { strictCidFormat: false, https: true }); visitor.timing(params, (err) => { if (err) { return logger.error('Google Analytics Event Error >>', err); } - logger.debug(`Timing event successfully sent to google analytics`); + logger.debug(`Timing event successfully sent to google analytics`, params); }); }; @@ -50,7 +52,7 @@ const sendGAServeEvent = (headers, ip, originalUrl) => { }; const sendGATimingEvent = (category, variable, label, startTime, endTime) => { - const params = createPublishTimingEventParams(category, variable, label, startTime, endTime); + const params = createTimingEventParams(category, variable, label, startTime, endTime); sendGoogleAnalyticsTiming(title, params); }; -- 2.45.2 From 7ee0b14a097978a6b5420acec1f84c24548fc77e Mon Sep 17 00:00:00 2001 From: bill bittner Date: Tue, 5 Jun 2018 18:35:19 -0700 Subject: [PATCH 03/15] changed ../config to @config --- index.js | 160 ++++++++++++---------------- test/end-to-end/end-to-end.tests.js | 4 +- 2 files changed, 73 insertions(+), 91 deletions(-) diff --git a/index.js b/index.js index 0762fed2..a5cac8e2 100644 --- a/index.js +++ b/index.js @@ -1,4 +1,4 @@ -// app dependencies +// load modules const express = require('express'); const bodyParser = require('body-parser'); const expressHandlebars = require('express-handlebars'); @@ -7,102 +7,84 @@ 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 requestLogger = require('./server/middleware/requestLogger.js'); +const siteConfig = require('@config/siteConfig.js'); const createDatabaseIfNotExists = require('./server/models/utils/createDatabaseIfNotExists.js'); const { getWalletBalance } = require('./server/lbrynet/index'); -function Server () { - this.configureLogger = loggerConfig.update; - this.configureMysql = mysqlConfig.update; - this.configureSite = siteConfig.update; - this.configureSlack = slackConfig.update; - this.createApp = () => { - // create an Express application - const app = express(); +/* create app */ +// create an Express application +const app = express(); +// trust the proxy to get ip address for us +app.enable('trust proxy'); - // 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()); +// 'express.static' to serve static files from public directory +const publicPath = Path.resolve(process.cwd(), 'public'); +app.use(express.static(publicPath)); +logger.info(`serving static files from default static path at ${publicPath}.`); +// 'body parser' for parsing application/json +app.use(bodyParser.json()); +// 'body parser' for parsing application/x-www-form-urlencoded +app.use(bodyParser.urlencoded({ extended: true })); +// 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], +})); +app.use(speechPassport.initialize()); +app.use(speechPassport.session()); +// configure handlebars & register it with express app +const hbs = expressHandlebars.create({ + defaultLayout: 'embed', + handlebars : Handlebars, +}); +app.engine('handlebars', hbs.engine); +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); - /* add middleware */ +/* create server */ +const server = http.Server(app); - // set HTTP headers to protect against well-known web vulnerabilties - app.use(helmet()); +/* start the server */ +const db = require('./server/models/index'); +const PORT = siteConfig.details.port; - // 'express.static' to serve static files from public directory - const publicPath = Path.resolve(process.cwd(), 'public'); - app.use(express.static(publicPath)); - logger.info(`serving static files from default static path at ${publicPath}.`); - - // 'body parser' for parsing application/json - app.use(bodyParser.json()); - - // 'body parser' for parsing application/x-www-form-urlencoded - app.use(bodyParser.urlencoded({ extended: true })); - - // 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], - })); - app.use(speechPassport.initialize()); - app.use(speechPassport.session()); - - // configure handlebars & register it with express app - const hbs = expressHandlebars.create({ - defaultLayout: 'embed', - handlebars : Handlebars, - }); - app.engine('handlebars', hbs.engine); - 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); - - this.app = app; - }; - this.initialize = () => { - this.createApp(); - this.server = http.Server(this.app); - }; - this.start = () => { - const db = require('./server/models/index'); - const PORT = siteConfig.details.port; - // sync sequelize - createDatabaseIfNotExists() - .then(() => { - return getWalletBalance(); - }) - .then(balance => { - logger.info('starting LBC balance:', balance); - db.sequelize.sync(); - this.server.listen(PORT, () => { - logger.info(`Server is listening on PORT ${PORT}`); - }); - }) - .catch(error => { - if (error.code === 'ECONNREFUSED') { - return logger.error('Connection refused. The daemon may not be running.') - } else if (error.message) { - logger.error(error.message); - } - logger.error(error); +const startServer = () => { + return createDatabaseIfNotExists() + .then(() => { + return getWalletBalance(); + }) + .then(balance => { + logger.info('starting LBC balance:', balance); + db.sequelize.sync(); + server.listen(PORT, () => { + logger.info(`Server is listening on PORT ${PORT}`); }); - }; + }) + .catch(error => { + if (error.code === 'ECONNREFUSED') { + return logger.error('Connection refused. The daemon may not be running.') + } else if (error.message) { + logger.error(error.message); + } + logger.error(error); + }); }; -module.exports = Server; +module.exports = startServer; diff --git a/test/end-to-end/end-to-end.tests.js b/test/end-to-end/end-to-end.tests.js index 0c206c39..7d994189 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.js'); +const { testChannel, testChannelId, testChannelPassword } = require('@devConfig/testingConfig.js'); const requestTimeout = 20000; const publishTimeout = 120000; const fs = require('fs'); -- 2.45.2 From c1f5552e9985bf584348461930c042edae785be9 Mon Sep 17 00:00:00 2001 From: bill bittner Date: Tue, 5 Jun 2018 18:55:44 -0700 Subject: [PATCH 04/15] removed configs and moved logging and slack configuration to server/utils/ --- config/lbryConfig.js | 8 --- config/loggerConfig.js | 36 ------------- config/mysqlConfig.js | 20 -------- config/siteConfig.js | 45 ---------------- config/slackConfig.js | 51 ------------------- index.js | 25 +++++++-- .../availability/checkClaimAvailability.js | 2 +- .../claim/publish/createBasicPublishParams.js | 2 +- .../publish/createThumbnailPublishParams.js | 2 +- server/controllers/api/claim/publish/index.js | 2 +- server/controllers/pages/sendEmbedPage.js | 2 +- server/lbrynet/index.js | 2 +- server/models/claim.js | 2 +- server/models/index.js | 2 +- .../models/utils/createDatabaseIfNotExists.js | 2 +- server/render/src/handlePageRender.jsx | 2 +- server/render/src/handleShowRender.jsx | 2 +- server/routes/utils/multipartMiddleware.js | 2 +- server/utils/configureLogging.js | 32 ++++++++++++ server/utils/configureSlack.js | 44 ++++++++++++++++ server/utils/googleAnalytics.js | 2 +- 21 files changed, 109 insertions(+), 178 deletions(-) delete mode 100644 config/lbryConfig.js delete mode 100644 config/loggerConfig.js delete mode 100644 config/mysqlConfig.js delete mode 100644 config/siteConfig.js delete mode 100644 config/slackConfig.js create mode 100644 server/utils/configureLogging.js create mode 100644 server/utils/configureSlack.js 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 0f92cbbe..00000000 --- a/config/siteConfig.js +++ /dev/null @@ -1,45 +0,0 @@ -const logger = require('winston'); - -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; - logger.info('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 a5cac8e2..efb9f616 100644 --- a/index.js +++ b/index.js @@ -12,30 +12,45 @@ const Path = require('path'); // load local modules const requestLogger = require('./server/middleware/requestLogger.js'); const siteConfig = require('@config/siteConfig.js'); +const PORT = siteConfig.details.port; const createDatabaseIfNotExists = require('./server/models/utils/createDatabaseIfNotExists.js'); -const { getWalletBalance } = require('./server/lbrynet/index'); +const { getWalletBalance } = require('./server/lbrynet'); +const db = require('./server/models'); + +// configure logging +const configureLogging = require('./server/utils/configureLogging.js'); +configureLogging(); + +// configure slack logging +const configureSlack = require('./server/utils/configureSlack.js'); +configureSlack(); /* create app */ -// create an Express application 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()); + // 'express.static' to serve static files from public directory const publicPath = Path.resolve(process.cwd(), 'public'); app.use(express.static(publicPath)); logger.info(`serving static files from default static path at ${publicPath}.`); + // 'body parser' for parsing application/json app.use(bodyParser.json()); + // 'body parser' for parsing application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: true })); + // 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({ @@ -44,6 +59,7 @@ app.use(cookieSession({ })); app.use(speechPassport.initialize()); app.use(speechPassport.session()); + // configure handlebars & register it with express app const hbs = expressHandlebars.create({ defaultLayout: 'embed', @@ -51,6 +67,7 @@ const hbs = expressHandlebars.create({ }); app.engine('handlebars', hbs.engine); app.set('view engine', 'handlebars'); + // set the routes on the app require('./server/routes/auth/index')(app); require('./server/routes/api/index')(app); @@ -62,8 +79,6 @@ require('./server/routes/fallback/index')(app); const server = http.Server(app); /* start the server */ -const db = require('./server/models/index'); -const PORT = siteConfig.details.port; const startServer = () => { return createDatabaseIfNotExists() diff --git a/server/controllers/api/claim/availability/checkClaimAvailability.js b/server/controllers/api/claim/availability/checkClaimAvailability.js index 68c31056..2a969551 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.js'); 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..3fac2c8f 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.js'); 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..1d89dc99 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.js'); 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..8e62b402 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.js'); const { sendGATimingEvent } = require('../../../../utils/googleAnalytics.js'); diff --git a/server/controllers/pages/sendEmbedPage.js b/server/controllers/pages/sendEmbedPage.js index ae3979b1..99eb89df 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.js'); const sendEmbedPage = ({ params }, res) => { const claimId = params.claimId; diff --git a/server/lbrynet/index.js b/server/lbrynet/index.js index 90a45875..7b27e423 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 { api: { apiHost, apiPort } } = require('@config/lbryConfig.js'); 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..cf41e273 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.js'); const NO_CLAIM = 'NO_CLAIM'; diff --git a/server/models/index.js b/server/models/index.js index 748db1b8..d6ba3b6a 100644 --- a/server/models/index.js +++ b/server/models/index.js @@ -9,7 +9,7 @@ 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.js'); // 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..21c968a3 100644 --- a/server/models/utils/createDatabaseIfNotExists.js +++ b/server/models/utils/createDatabaseIfNotExists.js @@ -1,7 +1,7 @@ const Sequelize = require('sequelize'); const createDatabaseIfNotExists = () => { - const {database, username, password} = require('../../../config/mysqlConfig.js'); + const {database, username, password} = require('@config/mysqlConfig.js'); const sequelize = new Sequelize('', username, password, { dialect : 'mysql', logging : false, diff --git a/server/render/src/handlePageRender.jsx b/server/render/src/handlePageRender.jsx index ae17bae0..e4179674 100644 --- a/server/render/src/handlePageRender.jsx +++ b/server/render/src/handlePageRender.jsx @@ -9,7 +9,7 @@ import App from '@app'; import renderFullPage from '../renderFullPage.js'; import Helmet from 'react-helmet'; -const siteConfig = require('../../../config/siteConfig.js'); +const siteConfig = require('@config/siteConfig.js'); module.exports = (req, res) => { let context = {}; diff --git a/server/render/src/handleShowRender.jsx b/server/render/src/handleShowRender.jsx index 28cd2bb0..6ffdd5a6 100644 --- a/server/render/src/handleShowRender.jsx +++ b/server/render/src/handleShowRender.jsx @@ -13,7 +13,7 @@ import Sagas from '@sagas'; import Actions from '@actions'; import Helmet from 'react-helmet'; -const siteConfig = require('../../../config/siteConfig.js'); +const siteConfig = require('@config/siteConfig.js'); const returnSagaWithParams = (saga, params) => { return function * () { diff --git a/server/routes/utils/multipartMiddleware.js b/server/routes/utils/multipartMiddleware.js index bd2e98f6..9304fc18 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.js'); const multipartMiddleware = multipart({uploadDir: uploadDirectory}); module.exports = multipartMiddleware; diff --git a/server/utils/configureLogging.js b/server/utils/configureLogging.js new file mode 100644 index 00000000..e877d89f --- /dev/null +++ b/server/utils/configureLogging.js @@ -0,0 +1,32 @@ +const logger = require('winston'); + +const { logLevel } = require('@config/loggerConfig'); + +function configureLogging () { + if (!logLevel) { + return logger.warn('No logLevel config received.'); + } + logger.info('configuring winston logger...'); + // 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 = configureLogging; diff --git a/server/utils/configureSlack.js b/server/utils/configureSlack.js new file mode 100644 index 00000000..88806acc --- /dev/null +++ b/server/utils/configureSlack.js @@ -0,0 +1,44 @@ +const winstonSlackWebHook = require('winston-slack-webhook').SlackWebHook; +const logger = require('winston'); + +const config = require('@config/loggerConfig'); + +function configureSlack () { + if (!config) { + return logger.warn('No slack config found'); + } + const {slackWebHook, slackErrorChannel, slackInfoChannel} = config; + // update variables + logger.info('configuring slack logger...'); + + // update slack webhook settings + if (!slackWebHook) { + return logger.warn('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:', + }); + } + // 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:', + }); + } + // send test messages + logger.info('Slack logging is online.'); +} + +module.exports = configureSlack; diff --git a/server/utils/googleAnalytics.js b/server/utils/googleAnalytics.js index 67abb91e..48f5f9b1 100644 --- a/server/utils/googleAnalytics.js +++ b/server/utils/googleAnalytics.js @@ -1,6 +1,6 @@ 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.js'); const createServeEventParams = (headers, ip, originalUrl) => { return { -- 2.45.2 From 70393d4eb4f9a0c9db156eacd3a385f7a656c4d6 Mon Sep 17 00:00:00 2001 From: bill bittner Date: Tue, 5 Jun 2018 19:05:26 -0700 Subject: [PATCH 05/15] updated lbryApi config format --- server/lbrynet/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/lbrynet/index.js b/server/lbrynet/index.js index 7b27e423..bd819971 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.js'); const lbrynetUri = 'http://' + apiHost + ':' + apiPort; const { chooseGaLbrynetPublishLabel, sendGATimingEvent } = require('../utils/googleAnalytics.js'); const handleLbrynetResponse = require('./utils/handleLbrynetResponse.js'); -- 2.45.2 From a1210149b3217009b7315eedb3414289da8a7c1e Mon Sep 17 00:00:00 2001 From: bill bittner Date: Tue, 5 Jun 2018 19:34:24 -0700 Subject: [PATCH 06/15] removed .js suffix from config --- index.js | 2 +- .../api/claim/availability/checkClaimAvailability.js | 2 +- .../controllers/api/claim/publish/createBasicPublishParams.js | 2 +- .../api/claim/publish/createThumbnailPublishParams.js | 2 +- server/controllers/api/claim/publish/index.js | 2 +- server/controllers/pages/sendEmbedPage.js | 2 +- server/lbrynet/index.js | 2 +- server/models/claim.js | 2 +- server/models/index.js | 2 +- server/models/utils/createDatabaseIfNotExists.js | 2 +- server/render/build/handlePageRender.js | 2 +- server/render/build/handleShowRender.js | 2 +- server/render/src/handlePageRender.jsx | 2 +- server/render/src/handleShowRender.jsx | 2 +- server/routes/utils/multipartMiddleware.js | 2 +- server/utils/googleAnalytics.js | 2 +- test/end-to-end/end-to-end.tests.js | 2 +- 17 files changed, 17 insertions(+), 17 deletions(-) diff --git a/index.js b/index.js index efb9f616..5c903af4 100644 --- a/index.js +++ b/index.js @@ -11,7 +11,7 @@ const Path = require('path'); // load local modules const requestLogger = require('./server/middleware/requestLogger.js'); -const siteConfig = require('@config/siteConfig.js'); +const siteConfig = require('@config/siteConfig'); const PORT = siteConfig.details.port; const createDatabaseIfNotExists = require('./server/models/utils/createDatabaseIfNotExists.js'); const { getWalletBalance } = require('./server/lbrynet'); diff --git a/server/controllers/api/claim/availability/checkClaimAvailability.js b/server/controllers/api/claim/availability/checkClaimAvailability.js index 2a969551..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 3fac2c8f..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 1d89dc99..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 8e62b402..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 99eb89df..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 bd819971..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 { 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 cf41e273..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 d6ba3b6a..5795f782 100644 --- a/server/models/index.js +++ b/server/models/index.js @@ -9,7 +9,7 @@ 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'); // 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 21c968a3..e7ae8faa 100644 --- a/server/models/utils/createDatabaseIfNotExists.js +++ b/server/models/utils/createDatabaseIfNotExists.js @@ -1,7 +1,7 @@ const Sequelize = require('sequelize'); const createDatabaseIfNotExists = () => { - const {database, username, password} = require('@config/mysqlConfig.js'); + const {database, username, password} = require('@config/mysqlConfig'); 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..ea51a1c0 100644 --- a/server/render/build/handlePageRender.js +++ b/server/render/build/handlePageRender.js @@ -22,7 +22,7 @@ var _reactHelmet = _interopRequireDefault(require("react-helmet")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var siteConfig = require('../../../config/siteConfig.js'); +var siteConfig = require('@config/siteConfig'); module.exports = function (req, res) { var context = {}; // customize the reducer by passing in intial state configs diff --git a/server/render/build/handleShowRender.js b/server/render/build/handleShowRender.js index c7b08082..57327785 100644 --- a/server/render/build/handleShowRender.js +++ b/server/render/build/handleShowRender.js @@ -30,7 +30,7 @@ var _reactHelmet = _interopRequireDefault(require("react-helmet")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var siteConfig = require('../../../config/siteConfig.js'); +var siteConfig = require('@config/siteConfig'); var returnSagaWithParams = function returnSagaWithParams(saga, params) { return ( diff --git a/server/render/src/handlePageRender.jsx b/server/render/src/handlePageRender.jsx index e4179674..ec9e7eb7 100644 --- a/server/render/src/handlePageRender.jsx +++ b/server/render/src/handlePageRender.jsx @@ -9,7 +9,7 @@ import App from '@app'; import renderFullPage from '../renderFullPage.js'; import Helmet from 'react-helmet'; -const siteConfig = require('@config/siteConfig.js'); +const siteConfig = require('@config/siteConfig'); module.exports = (req, res) => { let context = {}; diff --git a/server/render/src/handleShowRender.jsx b/server/render/src/handleShowRender.jsx index 6ffdd5a6..a1ea0172 100644 --- a/server/render/src/handleShowRender.jsx +++ b/server/render/src/handleShowRender.jsx @@ -13,7 +13,7 @@ import Sagas from '@sagas'; import Actions from '@actions'; import Helmet from 'react-helmet'; -const siteConfig = require('@config/siteConfig.js'); +const siteConfig = require('@config/siteConfig'); const returnSagaWithParams = (saga, params) => { return function * () { diff --git a/server/routes/utils/multipartMiddleware.js b/server/routes/utils/multipartMiddleware.js index 9304fc18..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/googleAnalytics.js b/server/utils/googleAnalytics.js index 48f5f9b1..57614569 100644 --- a/server/utils/googleAnalytics.js +++ b/server/utils/googleAnalytics.js @@ -1,6 +1,6 @@ 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'); const createServeEventParams = (headers, ip, originalUrl) => { return { diff --git a/test/end-to-end/end-to-end.tests.js b/test/end-to-end/end-to-end.tests.js index 7d994189..ee055b0a 100644 --- a/test/end-to-end/end-to-end.tests.js +++ b/test/end-to-end/end-to-end.tests.js @@ -1,7 +1,7 @@ const chai = require('chai'); const expect = chai.expect; const chaiHttp = require('chai-http'); -const { details: { host } } = require('@config/siteConfig.js'); +const { details: { host } } = require('@config/siteConfig'); const { testChannel, testChannelId, testChannelPassword } = require('@devConfig/testingConfig.js'); const requestTimeout = 20000; const publishTimeout = 120000; -- 2.45.2 From 7c847ceea8147f88629d3b71873f1ac5d62d1af0 Mon Sep 17 00:00:00 2001 From: bill bittner Date: Wed, 6 Jun 2018 08:30:30 -0700 Subject: [PATCH 07/15] added module aliasing --- index.js | 130 +++++++++++++++------------- package-lock.json | 5 ++ package.json | 1 + server/utils/createModuleAliases.js | 11 +++ 4 files changed, 85 insertions(+), 62 deletions(-) create mode 100644 server/utils/createModuleAliases.js diff --git a/index.js b/index.js index 5c903af4..63a1d2b4 100644 --- a/index.js +++ b/index.js @@ -8,80 +8,86 @@ const cookieSession = require('cookie-session'); const http = require('http'); const logger = require('winston'); const Path = require('path'); +const moduleAlias = require('module-alias'); // load local modules const requestLogger = require('./server/middleware/requestLogger.js'); -const siteConfig = require('@config/siteConfig'); -const PORT = siteConfig.details.port; const createDatabaseIfNotExists = require('./server/models/utils/createDatabaseIfNotExists.js'); const { getWalletBalance } = require('./server/lbrynet'); const db = require('./server/models'); - -// configure logging const configureLogging = require('./server/utils/configureLogging.js'); -configureLogging(); - -// configure slack logging const configureSlack = require('./server/utils/configureSlack.js'); -configureSlack(); +const speechPassport = require('./server/speechPassport'); +const createModuleAliases = require('./utils/createModuleAliases.js'); -/* create app */ -const app = express(); +// set up aliasing +const customAliases = createModuleAliases(); +logger.debug('custom aliases', customAliases); +moduleAlias.addAliases(customAliases); -// trust the proxy to get ip address for us -app.enable('trust proxy'); - -// set HTTP headers to protect against well-known web vulnerabilties -app.use(helmet()); - -// 'express.static' to serve static files from public directory -const publicPath = Path.resolve(process.cwd(), 'public'); -app.use(express.static(publicPath)); -logger.info(`serving static files from default static path at ${publicPath}.`); - -// 'body parser' for parsing application/json -app.use(bodyParser.json()); - -// 'body parser' for parsing application/x-www-form-urlencoded -app.use(bodyParser.urlencoded({ extended: true })); - -// 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], -})); -app.use(speechPassport.initialize()); -app.use(speechPassport.session()); - -// configure handlebars & register it with express app -const hbs = expressHandlebars.create({ - defaultLayout: 'embed', - handlebars : Handlebars, -}); -app.engine('handlebars', hbs.engine); -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); - -/* create server */ -const server = http.Server(app); - -/* start the server */ +// load aliased modules +const siteConfig = require('@config/siteConfig'); +const PORT = siteConfig.details.port; const startServer = () => { - return createDatabaseIfNotExists() + // configure logging + configureLogging(); + + // configure slack logging + configureSlack(); + + /* create app */ + const app = express(); + + // trust the proxy to get ip address for us + app.enable('trust proxy'); + + // set HTTP headers to protect against well-known web vulnerabilties + app.use(helmet()); + + // 'express.static' to serve static files from public directory + const publicPath = Path.resolve(process.cwd(), 'public'); + app.use(express.static(publicPath)); + logger.info(`serving static files from default static path at ${publicPath}.`); + + // 'body parser' for parsing application/json + app.use(bodyParser.json()); + + // 'body parser' for parsing application/x-www-form-urlencoded + app.use(bodyParser.urlencoded({ extended: true })); + + // add custom middleware (note: build out to accept dynamically use what is in server/middleware/ + app.use(requestLogger); + + // initialize passport + const sessionKey = siteConfig.auth.sessionKey; + app.use(cookieSession({ + name : 'session', + keys : [sessionKey], + })); + app.use(speechPassport.initialize()); + app.use(speechPassport.session()); + + // configure handlebars & register it with express app + const hbs = expressHandlebars.create({ + defaultLayout: 'embed', + handlebars : Handlebars, + }); + app.engine('handlebars', hbs.engine); + app.set('view engine', 'handlebars'); + + // set the routes on the 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); + + /* create server */ + const server = http.Server(app); + + /* start the server */ + createDatabaseIfNotExists() .then(() => { return getWalletBalance(); }) 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/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; +}; -- 2.45.2 From 60a74b51afce4edb0aea86aec9eb58f5eb805e12 Mon Sep 17 00:00:00 2001 From: bill bittner Date: Wed, 6 Jun 2018 12:01:11 -0700 Subject: [PATCH 08/15] changed reducers etc to take configs directly via alias --- client/build/reducers/index.js | 17 +- client/build/reducers/publish.js | 200 +++++++++--------- client/build/reducers/site.js | 83 ++++---- client/src/reducers/index.js | 19 +- client/src/reducers/publish.js | 180 ++++++++-------- client/src/reducers/site.js | 82 ++++--- index.js | 180 +++++++++------- server/models/index.js | 9 +- .../models/utils/createDatabaseIfNotExists.js | 2 +- server/render/build/handlePageRender.js | 12 +- server/render/build/handleShowRender.js | 12 +- server/render/src/handlePageRender.jsx | 15 +- server/render/src/handleShowRender.jsx | 15 +- server/utils/configureLogging.js | 14 +- server/utils/configureSlack.js | 14 +- 15 files changed, 426 insertions(+), 428 deletions(-) diff --git a/client/build/reducers/index.js b/client/build/reducers/index.js index cccf793d..1602ea2e 100644 --- a/client/build/reducers/index.js +++ b/client/build/reducers/index.js @@ -19,15 +19,12 @@ 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) - }); -}; +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..6e665be6 100644 --- a/client/build/reducers/publish.js +++ b/client/build/reducers/publish.js @@ -9,113 +9,115 @@ 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")); + +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 = 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; + } }; -var _default = customizedPublishReducer; exports.default = _default; \ No newline at end of file diff --git a/client/build/reducers/site.js b/client/build/reducers/site.js index ea6c37f1..a11f58bc 100644 --- a/client/build/reducers/site.js +++ b/client/build/reducers/site.js @@ -5,50 +5,49 @@ Object.defineProperty(exports, "__esModule", { }); exports.default = void 0; -var customizedSiteReducer = function customizedSiteReducer(siteConfig) { - var initialState = {}; +var _siteConfig = _interopRequireDefault(require("@config/siteConfig")); - 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' +}; + +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 + }; +} + +var _default = 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; + } }; -var _default = customizedSiteReducer; exports.default = _default; \ No newline at end of file diff --git a/client/src/reducers/index.js b/client/src/reducers/index.js index 794888e1..99b725df 100644 --- a/client/src/reducers/index.js +++ b/client/src/reducers/index.js @@ -1,18 +1,15 @@ import { combineReducers } from 'redux'; + 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..ad64b3f3 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'; + +// 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 (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..1c3bbbf2 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'; - 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 (state = initialState, action) => { + switch (action.type) { + default: + return state; + } +}; diff --git a/index.js b/index.js index 63a1d2b4..7910bbf2 100644 --- a/index.js +++ b/index.js @@ -1,3 +1,10 @@ +// set up aliasing +const moduleAlias = require('module-alias'); +const createModuleAliases = require('./server/utils/createModuleAliases.js'); +const customAliases = createModuleAliases(); +console.log('custom aliases', customAliases); +moduleAlias.addAliases(customAliases); + // load modules const express = require('express'); const bodyParser = require('body-parser'); @@ -8,104 +15,119 @@ const cookieSession = require('cookie-session'); const http = require('http'); const logger = require('winston'); const Path = require('path'); -const moduleAlias = require('module-alias'); // 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'); -const db = require('./server/models'); const configureLogging = require('./server/utils/configureLogging.js'); const configureSlack = require('./server/utils/configureSlack.js'); const speechPassport = require('./server/speechPassport'); -const createModuleAliases = require('./utils/createModuleAliases.js'); -// set up aliasing -const customAliases = createModuleAliases(); -logger.debug('custom aliases', customAliases); -moduleAlias.addAliases(customAliases); - -// load aliased modules +// test configs const siteConfig = require('@config/siteConfig'); +console.log('siteConfig:', siteConfig); +const mysqlConfig = require('@config/mysqlConfig'); +console.log('mysqlConfig:', mysqlConfig); +const slackConfig = require('@config/slackConfig'); +console.log('slackConfig:', slackConfig); +const loggerConfig = require('@config/loggerConfig'); +console.log('loggerConfig:', loggerConfig); + const PORT = siteConfig.details.port; -const startServer = () => { - // configure logging - configureLogging(); +function Server () { + this.initialize = () => { + // configure logging + configureLogging(); + // configure slack logging + configureSlack(); + }; + this.createApp = () => { + /* create app */ + const app = express(); - // configure slack logging - configureSlack(); + // trust the proxy to get ip address for us + app.enable('trust proxy'); - /* create app */ - const app = express(); + // set HTTP headers to protect against well-known web vulnerabilties + app.use(helmet()); - // trust the proxy to get ip address for us - app.enable('trust proxy'); + // 'express.static' to serve static files from public directory + const publicPath = Path.resolve(process.cwd(), 'public'); + app.use(express.static(publicPath)); + logger.info(`serving static files from default static path at ${publicPath}.`); - // set HTTP headers to protect against well-known web vulnerabilties - app.use(helmet()); + // 'body parser' for parsing application/json + app.use(bodyParser.json()); - // 'express.static' to serve static files from public directory - const publicPath = Path.resolve(process.cwd(), 'public'); - app.use(express.static(publicPath)); - logger.info(`serving static files from default static path at ${publicPath}.`); + // 'body parser' for parsing application/x-www-form-urlencoded + app.use(bodyParser.urlencoded({ extended: true })); - // 'body parser' for parsing application/json - app.use(bodyParser.json()); + // add custom middleware (note: build out to accept dynamically use what is in server/middleware/ + app.use(requestLogger); - // 'body parser' for parsing application/x-www-form-urlencoded - app.use(bodyParser.urlencoded({ extended: true })); + // initialize passport + const sessionKey = siteConfig.auth.sessionKey; + app.use(cookieSession({ + name : 'session', + keys : [sessionKey], + })); + app.use(speechPassport.initialize()); + app.use(speechPassport.session()); - // add custom middleware (note: build out to accept dynamically use what is in server/middleware/ - app.use(requestLogger); - - // initialize passport - const sessionKey = siteConfig.auth.sessionKey; - app.use(cookieSession({ - name : 'session', - keys : [sessionKey], - })); - app.use(speechPassport.initialize()); - app.use(speechPassport.session()); - - // configure handlebars & register it with express app - const hbs = expressHandlebars.create({ - defaultLayout: 'embed', - handlebars : Handlebars, - }); - app.engine('handlebars', hbs.engine); - app.set('view engine', 'handlebars'); - - // set the routes on the 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); - - /* create server */ - const server = http.Server(app); - - /* start the server */ - createDatabaseIfNotExists() - .then(() => { - return getWalletBalance(); - }) - .then(balance => { - logger.info('starting LBC balance:', balance); - db.sequelize.sync(); - server.listen(PORT, () => { - logger.info(`Server is listening on PORT ${PORT}`); - }); - }) - .catch(error => { - if (error.code === 'ECONNREFUSED') { - return logger.error('Connection refused. The daemon may not be running.') - } else if (error.message) { - logger.error(error.message); - } - logger.error(error); + // configure handlebars & register it with express app + const hbs = expressHandlebars.create({ + defaultLayout: 'embed', + handlebars : Handlebars, }); -}; + app.engine('handlebars', hbs.engine); + app.set('view engine', 'handlebars'); -module.exports = startServer; + // set the routes on the 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.createServer = () => { + /* create server */ + this.server = http.Server(this.app); + }; + this.syncDatabase = () => { + return createDatabaseIfNotExists() + .then(() => { + db.sequelize.sync(); + }) + }; + 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') { + return logger.error('Connection refused. The daemon may not be running.') + } else if (error.message) { + logger.error(error.message); + } + logger.error(error); + }); + }; +} + +module.exports = Server; diff --git a/server/models/index.js b/server/models/index.js index 5795f782..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'); +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 e7ae8faa..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'); 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 ea51a1c0..0e5dd197 100644 --- a/server/render/build/handlePageRender.js +++ b/server/render/build/handlePageRender.js @@ -22,23 +22,17 @@ var _reactHelmet = _interopRequireDefault(require("react-helmet")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var siteConfig = require('@config/siteConfig'); - 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 57327785..ac1ac7cc 100644 --- a/server/render/build/handleShowRender.js +++ b/server/render/build/handleShowRender.js @@ -30,8 +30,6 @@ var _reactHelmet = _interopRequireDefault(require("react-helmet")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var siteConfig = require('@config/siteConfig'); - 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 ec9e7eb7..9f9320d6 100644 --- a/server/render/src/handlePageRender.jsx +++ b/server/render/src/handlePageRender.jsx @@ -9,26 +9,19 @@ import App from '@app'; import renderFullPage from '../renderFullPage.js'; import Helmet from 'react-helmet'; -const siteConfig = require('@config/siteConfig'); - 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 a1ea0172..5f48afe4 100644 --- a/server/render/src/handleShowRender.jsx +++ b/server/render/src/handleShowRender.jsx @@ -13,8 +13,6 @@ import Sagas from '@sagas'; import Actions from '@actions'; import Helmet from 'react-helmet'; -const siteConfig = require('@config/siteConfig'); - const returnSagaWithParams = (saga, params) => { return function * () { yield call(saga, params); @@ -24,17 +22,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 +42,9 @@ module.exports = (req, res) => { const html = renderToString( - - - + + + ); diff --git a/server/utils/configureLogging.js b/server/utils/configureLogging.js index e877d89f..49af20bb 100644 --- a/server/utils/configureLogging.js +++ b/server/utils/configureLogging.js @@ -1,17 +1,21 @@ const logger = require('winston'); -const { logLevel } = require('@config/loggerConfig'); +const config = require('@config/loggerConfig'); +const { logLevel } = config; function configureLogging () { - if (!logLevel) { - return logger.warn('No logLevel config received.'); - } 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 : this.logLevel, + level : logLevel || 'debug', timestamp : false, colorize : true, prettyPrint : true, diff --git a/server/utils/configureSlack.js b/server/utils/configureSlack.js index 88806acc..feef1122 100644 --- a/server/utils/configureSlack.js +++ b/server/utils/configureSlack.js @@ -1,19 +1,17 @@ const winstonSlackWebHook = require('winston-slack-webhook').SlackWebHook; const logger = require('winston'); -const config = require('@config/loggerConfig'); +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'); } - const {slackWebHook, slackErrorChannel, slackInfoChannel} = config; - // update variables - logger.info('configuring slack logger...'); - // update slack webhook settings if (!slackWebHook) { - return logger.warn('Slack logging is not enabled because no slackWebHook config var provided.'); + return logger.info('Slack logging is not enabled because no slackWebHook config var provided.'); } // add a transport for errors to slack if (slackErrorChannel) { @@ -25,6 +23,8 @@ function configureSlack () { 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) { @@ -36,6 +36,8 @@ function configureSlack () { 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.'); -- 2.45.2 From 5cb421c0e7b3ecd051b4789ae3e309f8cc06a127 Mon Sep 17 00:00:00 2001 From: bill bittner Date: Wed, 6 Jun 2018 13:10:12 -0700 Subject: [PATCH 09/15] added file ending to config path in redux --- client/build/components/GAListener/index.js | 79 +++++++++++---------- client/build/reducers/index.js | 2 + client/build/reducers/publish.js | 2 +- client/build/reducers/site.js | 2 +- client/src/components/GAListener/index.jsx | 44 +++++++----- client/src/reducers/index.js | 2 + client/src/reducers/publish.js | 2 +- client/src/reducers/site.js | 2 +- 8 files changed, 76 insertions(+), 59 deletions(-) diff --git a/client/build/components/GAListener/index.js b/client/build/components/GAListener/index.js index 54a99a0f..b69e3a54 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; - _reactGa.default.initialize(googleId); +if (!_siteConfig.default) { + console.log('no site config found for GAListener'); +} - var GAListener = - /*#__PURE__*/ - function (_React$Component) { - function GAListener() { - _classCallCheck(this, GAListener); +if (_siteConfig.default.analytics) { + googleId = _siteConfig.default.analytics.googleId; +} - return _possibleConstructorReturn(this, _getPrototypeOf(GAListener).apply(this, arguments)); +_reactGa.default.initialize(googleId); + +var GAListener = +/*#__PURE__*/ +function (_React$Component) { + function GAListener() { + _classCallCheck(this, GAListener); + + 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); } + }, { + key: "sendPageView", + value: function sendPageView(location) { + _reactGa.default.set({ + page: location.pathname + }); - _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) { - _reactGa.default.set({ - page: location.pathname - }); + _reactGa.default.pageview(location.pathname); + } + }, { + key: "render", + value: function render() { + return this.props.children; + } + }]); - _reactGa.default.pageview(location.pathname); - } - }, { - 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); +var _default = (0, _reactRouterDom.withRouter)(GAListener); - return (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 1602ea2e..9bc6f63b 100644 --- a/client/build/reducers/index.js +++ b/client/build/reducers/index.js @@ -19,6 +19,8 @@ var _channelCreate = _interopRequireDefault(require("./channelCreate")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +// modules +// local modules var _default = (0, _redux.combineReducers)({ channel: _channel.default, channelCreate: _channelCreate.default, diff --git a/client/build/reducers/publish.js b/client/build/reducers/publish.js index 6e665be6..142417b3 100644 --- a/client/build/reducers/publish.js +++ b/client/build/reducers/publish.js @@ -9,7 +9,7 @@ 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")); +var _siteConfig = _interopRequireDefault(require("@config/siteConfig.json")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } diff --git a/client/build/reducers/site.js b/client/build/reducers/site.js index a11f58bc..34c7035e 100644 --- a/client/build/reducers/site.js +++ b/client/build/reducers/site.js @@ -5,7 +5,7 @@ Object.defineProperty(exports, "__esModule", { }); exports.default = void 0; -var _siteConfig = _interopRequireDefault(require("@config/siteConfig")); +var _siteConfig = _interopRequireDefault(require("@config/siteConfig.json")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } diff --git a/client/src/components/GAListener/index.jsx b/client/src/components/GAListener/index.jsx index 516034ec..63afb758 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) { + console.log('no site config found for GAListener'); +} - sendPageView (location) { - GoogleAnalytics.set({ page: location.pathname }); - GoogleAnalytics.pageview(location.pathname); - } +if (siteConfig.analytics) { + ({ googleId } = siteConfig.analytics); +} - render () { - return this.props.children; - } - } +GoogleAnalytics.initialize(googleId); - return withRouter(GAListener); -}; +class GAListener extends React.Component { + componentDidMount () { + this.sendPageView(this.props.history.location); + this.props.history.listen(this.sendPageView); + } -export default customGAListener; + sendPageView (location) { + GoogleAnalytics.set({ page: location.pathname }); + GoogleAnalytics.pageview(location.pathname); + } + + render () { + return this.props.children; + } +} + +export default withRouter(GAListener); diff --git a/client/src/reducers/index.js b/client/src/reducers/index.js index 99b725df..75893410 100644 --- a/client/src/reducers/index.js +++ b/client/src/reducers/index.js @@ -1,5 +1,7 @@ +// modules import { combineReducers } from 'redux'; +// local modules import PublishReducer from './publish'; import ChannelReducer from './channel'; import ShowReducer from './show'; diff --git a/client/src/reducers/publish.js b/client/src/reducers/publish.js index ad64b3f3..1cbfc5b9 100644 --- a/client/src/reducers/publish.js +++ b/client/src/reducers/publish.js @@ -1,7 +1,7 @@ import * as actions from '../constants/publish_action_types'; import { LOGIN } from '../constants/publish_channel_select_states'; -import siteConfig from '@config/siteConfig'; +import siteConfig from '@config/siteConfig.json'; // parse inputs let disabledConfig = false; diff --git a/client/src/reducers/site.js b/client/src/reducers/site.js index 1c3bbbf2..b22e0fe9 100644 --- a/client/src/reducers/site.js +++ b/client/src/reducers/site.js @@ -1,4 +1,4 @@ -import siteConfig from '@config/siteConfig'; +import siteConfig from '@config/siteConfig.json'; let initialState = { description : 'default description', -- 2.45.2 From fdd1e79a2c8f9140122af0370d73e4df5252609d Mon Sep 17 00:00:00 2001 From: bill bittner Date: Wed, 6 Jun 2018 13:45:54 -0700 Subject: [PATCH 10/15] renamed app component --- client/build/app.js | 4 ++-- client/src/app.js | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) 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/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; -- 2.45.2 From f41ac47c3e37213aec3e3f437fa9bf88985388bd Mon Sep 17 00:00:00 2001 From: bill bittner Date: Wed, 6 Jun 2018 15:12:07 -0700 Subject: [PATCH 11/15] rebuilt without console logs --- client/build/reducers/publish.js | 8 ++++---- client/build/reducers/site.js | 8 ++++---- client/src/reducers/publish.js | 2 +- client/src/reducers/site.js | 2 +- index.js | 27 ++++++++++++------------- server/render/build/handlePageRender.js | 4 ++-- server/render/build/handleShowRender.js | 4 ++-- server/render/src/handlePageRender.jsx | 3 ++- server/render/src/handleShowRender.jsx | 3 ++- server/utils/checkForConfig.js | 9 +++++++++ server/utils/googleAnalytics.js | 2 -- 11 files changed, 40 insertions(+), 32 deletions(-) create mode 100644 server/utils/checkForConfig.js diff --git a/client/build/reducers/publish.js b/client/build/reducers/publish.js index 142417b3..e1b0f4f0 100644 --- a/client/build/reducers/publish.js +++ b/client/build/reducers/publish.js @@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = void 0; +exports.default = _default; var actions = _interopRequireWildcard(require("../constants/publish_action_types")); @@ -61,7 +61,7 @@ var initialState = { thumbnailChannelId: thumbnailChannelId }; -var _default = function _default() { +function _default() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments.length > 1 ? arguments[1] : undefined; @@ -118,6 +118,6 @@ var _default = function _default() { default: return state; } -}; +} -exports.default = _default; \ No newline at end of file +; \ No newline at end of file diff --git a/client/build/reducers/site.js b/client/build/reducers/site.js index 34c7035e..604f2e5d 100644 --- a/client/build/reducers/site.js +++ b/client/build/reducers/site.js @@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = void 0; +exports.default = _default; var _siteConfig = _interopRequireDefault(require("@config/siteConfig.json")); @@ -40,7 +40,7 @@ if (_siteConfig.default) { }; } -var _default = function _default() { +function _default() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments.length > 1 ? arguments[1] : undefined; @@ -48,6 +48,6 @@ var _default = function _default() { default: return state; } -}; +} -exports.default = _default; \ No newline at end of file +; \ No newline at end of file diff --git a/client/src/reducers/publish.js b/client/src/reducers/publish.js index 1cbfc5b9..29a31d7d 100644 --- a/client/src/reducers/publish.js +++ b/client/src/reducers/publish.js @@ -46,7 +46,7 @@ const initialState = { thumbnailChannelId, }; -export default (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 diff --git a/client/src/reducers/site.js b/client/src/reducers/site.js index b22e0fe9..6b0b3e61 100644 --- a/client/src/reducers/site.js +++ b/client/src/reducers/site.js @@ -38,7 +38,7 @@ if (siteConfig) { }; } -export default (state = initialState, action) => { +export default function (state = initialState, action) { switch (action.type) { default: return state; diff --git a/index.js b/index.js index 7910bbf2..7d6f789c 100644 --- a/index.js +++ b/index.js @@ -1,10 +1,17 @@ -// set up aliasing +// set up module aliasing const moduleAlias = require('module-alias'); const createModuleAliases = require('./server/utils/createModuleAliases.js'); const customAliases = createModuleAliases(); -console.log('custom aliases', customAliases); 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'); @@ -25,17 +32,10 @@ const configureLogging = require('./server/utils/configureLogging.js'); const configureSlack = require('./server/utils/configureSlack.js'); const speechPassport = require('./server/speechPassport'); -// test configs -const siteConfig = require('@config/siteConfig'); -console.log('siteConfig:', siteConfig); -const mysqlConfig = require('@config/mysqlConfig'); -console.log('mysqlConfig:', mysqlConfig); -const slackConfig = require('@config/slackConfig'); -console.log('slackConfig:', slackConfig); -const loggerConfig = require('@config/loggerConfig'); -console.log('loggerConfig:', loggerConfig); - -const PORT = siteConfig.details.port; +const { + details: { port: PORT }, + auth: { sessionKey }, +} = require('@config/siteConfig'); function Server () { this.initialize = () => { @@ -69,7 +69,6 @@ function Server () { app.use(requestLogger); // initialize passport - const sessionKey = siteConfig.auth.sessionKey; app.use(cookieSession({ name : 'session', keys : [sessionKey], diff --git a/server/render/build/handlePageRender.js b/server/render/build/handlePageRender.js index 0e5dd197..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,8 +20,6 @@ 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 }; } module.exports = function (req, res) { diff --git a/server/render/build/handleShowRender.js b/server/render/build/handleShowRender.js index ac1ac7cc..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,8 +28,6 @@ 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 returnSagaWithParams = function returnSagaWithParams(saga, params) { diff --git a/server/render/src/handlePageRender.jsx b/server/render/src/handlePageRender.jsx index 9f9320d6..f10704b1 100644 --- a/server/render/src/handlePageRender.jsx +++ b/server/render/src/handlePageRender.jsx @@ -3,11 +3,12 @@ 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'; module.exports = (req, res) => { let context = {}; diff --git a/server/render/src/handleShowRender.jsx b/server/render/src/handleShowRender.jsx index 5f48afe4..8621b597 100644 --- a/server/render/src/handleShowRender.jsx +++ b/server/render/src/handleShowRender.jsx @@ -6,12 +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 returnSagaWithParams = (saga, params) => { return function * () { 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/googleAnalytics.js b/server/utils/googleAnalytics.js index 57614569..77aca08c 100644 --- a/server/utils/googleAnalytics.js +++ b/server/utils/googleAnalytics.js @@ -31,7 +31,6 @@ const sendGoogleAnalyticsEvent = (ip, params) => { if (err) { return logger.error('Google Analytics Event Error >>', err); } - logger.debug(`Event successfully sent to google analytics`, params); }); }; @@ -42,7 +41,6 @@ const sendGoogleAnalyticsTiming = (siteTitle, params) => { if (err) { return logger.error('Google Analytics Event Error >>', err); } - logger.debug(`Timing event successfully sent to google analytics`, params); }); }; -- 2.45.2 From bf771998a8c93dd2949dfafbb3bdde2ff1fac040 Mon Sep 17 00:00:00 2001 From: bill bittner Date: Wed, 6 Jun 2018 15:59:30 -0700 Subject: [PATCH 12/15] added debug log back --- server/utils/googleAnalytics.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server/utils/googleAnalytics.js b/server/utils/googleAnalytics.js index 77aca08c..6907d347 100644 --- a/server/utils/googleAnalytics.js +++ b/server/utils/googleAnalytics.js @@ -31,6 +31,7 @@ const sendGoogleAnalyticsEvent = (ip, params) => { if (err) { return logger.error('Google Analytics Event Error >>', err); } + logger.debug(`Event successfully sent to google analytics`, params); }); }; @@ -41,6 +42,7 @@ const sendGoogleAnalyticsTiming = (siteTitle, params) => { if (err) { return logger.error('Google Analytics Event Error >>', err); } + logger.debug(`Event successfully sent to google analytics`, params); }); }; -- 2.45.2 From 5484e39eaa609ae91787022951c49e25ddc01177 Mon Sep 17 00:00:00 2001 From: bill bittner Date: Thu, 7 Jun 2018 10:05:34 -0700 Subject: [PATCH 13/15] moved google analytics initialization inside if statement --- client/build/components/GAListener/index.js | 4 ++-- client/src/components/GAListener/index.jsx | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/client/build/components/GAListener/index.js b/client/build/components/GAListener/index.js index b69e3a54..2c3cb57c 100644 --- a/client/build/components/GAListener/index.js +++ b/client/build/components/GAListener/index.js @@ -41,9 +41,9 @@ if (!_siteConfig.default) { if (_siteConfig.default.analytics) { googleId = _siteConfig.default.analytics.googleId; -} -_reactGa.default.initialize(googleId); + _reactGa.default.initialize(googleId); +} var GAListener = /*#__PURE__*/ diff --git a/client/src/components/GAListener/index.jsx b/client/src/components/GAListener/index.jsx index 63afb758..f0293a6e 100644 --- a/client/src/components/GAListener/index.jsx +++ b/client/src/components/GAListener/index.jsx @@ -12,10 +12,9 @@ if (!siteConfig) { if (siteConfig.analytics) { ({ googleId } = siteConfig.analytics); + GoogleAnalytics.initialize(googleId); } -GoogleAnalytics.initialize(googleId); - class GAListener extends React.Component { componentDidMount () { this.sendPageView(this.props.history.location); -- 2.45.2 From 98ea4d226fcd15c127f7e58472f39e1cbfe83741 Mon Sep 17 00:00:00 2001 From: bill bittner Date: Thu, 7 Jun 2018 10:27:56 -0700 Subject: [PATCH 14/15] added logic to skip GA if no id provided --- client/build/components/GAListener/index.js | 22 ++++++++++++++------- client/src/components/GAListener/index.jsx | 17 ++++++++++++---- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/client/build/components/GAListener/index.js b/client/build/components/GAListener/index.js index 2c3cb57c..e1c1a5d4 100644 --- a/client/build/components/GAListener/index.js +++ b/client/build/components/GAListener/index.js @@ -36,12 +36,18 @@ function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || functio var googleId = null; if (!_siteConfig.default) { - console.log('no site config found for GAListener'); + console.log('WARNING: no site config found for GAListener'); } -if (_siteConfig.default.analytics) { - googleId = _siteConfig.default.analytics.googleId; +if (!_siteConfig.default.analytics) { + console.log('WARNING: no analytics configs found in siteConfig.json'); +} +if (_siteConfig.default && _siteConfig.default.analytics) { + googleId = _siteConfig.default.analytics.googleId; +} + +if (googleId) { _reactGa.default.initialize(googleId); } @@ -63,11 +69,13 @@ function (_React$Component) { }, { key: "sendPageView", value: function sendPageView(location) { - _reactGa.default.set({ - page: location.pathname - }); + if (googleId) { + _reactGa.default.set({ + page: location.pathname + }); - _reactGa.default.pageview(location.pathname); + _reactGa.default.pageview(location.pathname); + } } }, { key: "render", diff --git a/client/src/components/GAListener/index.jsx b/client/src/components/GAListener/index.jsx index f0293a6e..31ed6395 100644 --- a/client/src/components/GAListener/index.jsx +++ b/client/src/components/GAListener/index.jsx @@ -7,11 +7,18 @@ import siteConfig from '@config/siteConfig.json'; let googleId = null; if (!siteConfig) { - console.log('no site config found for GAListener'); + console.log('WARNING: no site config found for GAListener'); } -if (siteConfig.analytics) { +if (!siteConfig.analytics) { + console.log('WARNING: no analytics configs found in siteConfig.json'); +} + +if (siteConfig && siteConfig.analytics) { ({ googleId } = siteConfig.analytics); +} + +if (googleId) { GoogleAnalytics.initialize(googleId); } @@ -22,8 +29,10 @@ class GAListener extends React.Component { } sendPageView (location) { - GoogleAnalytics.set({ page: location.pathname }); - GoogleAnalytics.pageview(location.pathname); + if (googleId) { + GoogleAnalytics.set({ page: location.pathname }); + GoogleAnalytics.pageview(location.pathname); + } } render () { -- 2.45.2 From 18953ed70257bfb7487f9fe05af82f5c99f2fbd8 Mon Sep 17 00:00:00 2001 From: bill bittner Date: Thu, 7 Jun 2018 10:33:15 -0700 Subject: [PATCH 15/15] escape hatch for analytics events and removed unnecessary console logs --- client/build/components/GAListener/index.js | 8 -------- client/src/components/GAListener/index.jsx | 8 -------- server/utils/googleAnalytics.js | 8 ++++++-- 3 files changed, 6 insertions(+), 18 deletions(-) diff --git a/client/build/components/GAListener/index.js b/client/build/components/GAListener/index.js index e1c1a5d4..2e5d81bd 100644 --- a/client/build/components/GAListener/index.js +++ b/client/build/components/GAListener/index.js @@ -35,14 +35,6 @@ function _getPrototypeOf(o) { _getPrototypeOf = Object.getPrototypeOf || functio var googleId = null; -if (!_siteConfig.default) { - console.log('WARNING: no site config found for GAListener'); -} - -if (!_siteConfig.default.analytics) { - console.log('WARNING: no analytics configs found in siteConfig.json'); -} - if (_siteConfig.default && _siteConfig.default.analytics) { googleId = _siteConfig.default.analytics.googleId; } diff --git a/client/src/components/GAListener/index.jsx b/client/src/components/GAListener/index.jsx index 31ed6395..718fb4ca 100644 --- a/client/src/components/GAListener/index.jsx +++ b/client/src/components/GAListener/index.jsx @@ -6,14 +6,6 @@ import siteConfig from '@config/siteConfig.json'; let googleId = null; -if (!siteConfig) { - console.log('WARNING: no site config found for GAListener'); -} - -if (!siteConfig.analytics) { - console.log('WARNING: no analytics configs found in siteConfig.json'); -} - if (siteConfig && siteConfig.analytics) { ({ googleId } = siteConfig.analytics); } diff --git a/server/utils/googleAnalytics.js b/server/utils/googleAnalytics.js index 6907d347..a193155b 100644 --- a/server/utils/googleAnalytics.js +++ b/server/utils/googleAnalytics.js @@ -24,7 +24,9 @@ const createTimingEventParams = (category, variable, label, startTime, endTime) }; const sendGoogleAnalyticsEvent = (ip, params) => { - logger.debug('googleId', googleId); + 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) => { @@ -36,7 +38,9 @@ const sendGoogleAnalyticsEvent = (ip, params) => { }; const sendGoogleAnalyticsTiming = (siteTitle, params) => { - logger.debug('googleId', googleId); + 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) { -- 2.45.2