removed server and update route and config exports

This commit is contained in:
bill bittner 2018-03-27 12:32:07 -07:00
parent 8ed1b02ee6
commit ca787f3150
17 changed files with 141 additions and 11789 deletions

View file

@ -1,5 +1,34 @@
const loggerConfig = {
logLevel: 'debug', // options: silly, debug, verbose, info
const logger = require('winston');
function LoggerConfig () {
this.logLevel = 'debug';
this.configure = (config) => {
if (!config) {
return console.log('No logger config received.');
}
// 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.error('Level 0');
logger.warn('Level 1');
logger.info('Level 2');
logger.verbose('Level 3');
logger.debug('Level 4');
logger.silly('Level 5');
};
};
module.exports = loggerConfig;
module.exports = new LoggerConfig();

View file

@ -1,4 +1,4 @@
function MysqlConfig () {
function mysql () {
this.database = 'default';
this.username = 'default';
this.password = 'default';
@ -13,4 +13,4 @@ function MysqlConfig () {
};
};
module.exports = new MysqlConfig();
module.exports = new mysql();

View file

@ -1,3 +1,6 @@
const winstonSlackWebHook = require('winston-slack-webhook').SlackWebHook;
const winston = require('winston');
function SlackConfig () {
this.slackWebHook = 'default';
this.slackErrorChannel = 'default';
@ -6,10 +9,40 @@ function SlackConfig () {
if (!config) {
return console.log('No slack config received.');
}
// update variables
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 (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.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.');
}
};
};

11558
index.js

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,5 +1,5 @@
const logger = require('winston');
const db = require('../models/index');
const db = require('../models');
const lbryApi = require('../helpers/lbryApi.js');
const publishHelpers = require('../helpers/publishHelpers.js');
const { publishing: { primaryClaimAddress, additionalClaimAddresses } } = require('../../config/siteConfig.js');

View file

@ -1,12 +0,0 @@
const logger = require('winston');
module.exports = {
serializeSpeechUser (user, done) { // returns user data to be serialized into session
logger.debug('serializing user');
done(null, user);
},
deserializeSpeechUser (user, done) { // deserializes session and populates additional info to req.user
logger.debug('deserializing user');
done(null, user);
},
};

View file

@ -1,24 +0,0 @@
const { logLevel } = require('../../config/loggerConfig');
module.exports = (winston) => {
// configure
winston.configure({
transports: [
new (winston.transports.Console)({
level : logLevel,
timestamp : false,
colorize : true,
prettyPrint : true,
handleExceptions : true,
humanReadableUnhandledException: true,
}),
],
});
// test all the log levels
winston.error('Level 0');
winston.warn('Level 1');
winston.info('Level 2');
winston.verbose('Level 3');
winston.debug('Level 4');
winston.silly('Level 5');
};

View file

@ -1,34 +0,0 @@
const winstonSlackWebHook = require('winston-slack-webhook').SlackWebHook;
const slackConfig = require('../../config/slackConfig.js');
module.exports = (winston) => {
const {slackWebHook, slackErrorChannel, slackInfoChannel} = slackConfig;
if (slackWebHook) {
// add a transport for errors to slack
if (slackErrorChannel) {
winston.add(winstonSlackWebHook, {
name : 'slack-errors-transport',
level : 'warn',
webhookUrl: slackWebHook,
channel : slackErrorChannel,
username : 'spee.ch',
iconEmoji : ':face_with_head_bandage:',
});
};
if (slackInfoChannel) {
winston.add(winstonSlackWebHook, {
name : 'slack-info-transport',
level : 'info',
webhookUrl: slackWebHook,
channel : slackInfoChannel,
username : 'spee.ch',
iconEmoji : ':nerd_face:',
});
};
// send test message
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.');
}
};

View file

@ -1,8 +1,9 @@
const Sequelize = require('sequelize');
const logger = require('winston');
console.log('exporting sequelize models');
logger.info('exporting sequelize models');
const { database, username, password } = require('../../config/mysqlConfig');
const db = {};
// set sequelize options
const sequelize = new Sequelize(database, username, password, {

View file

@ -1,8 +1,6 @@
const logger = require('winston');
const multipart = require('connect-multiparty');
const { publishing: { uploadDirectory }, details: { host } } = require('../../config/siteConfig.js');
const multipartMiddleware = multipart({uploadDir: uploadDirectory});
const db = require('../models/index');
const { details: { host } } = require('../../config/siteConfig.js');
const db = require('../models');
const { claimNameIsAvailable, checkChannelAvailability, publish } = require('../controllers/publishController.js');
const { getClaimList, resolveUri, getClaim } = require('../helpers/lbryApi.js');
const { addGetResultsToFileData, createBasicPublishParams, createThumbnailPublishParams, parsePublishApiRequestBody, parsePublishApiRequestFiles, createFileData } = require('../helpers/publishHelpers.js');
@ -14,9 +12,9 @@ const { getChannelData, getChannelClaims, getClaimId } = require('../controllers
const NO_CHANNEL = 'NO_CHANNEL';
const NO_CLAIM = 'NO_CLAIM';
module.exports = (app) => {
module.exports = {
// route to check whether site has published to a channel
app.get('/api/channel/availability/:name', ({ ip, originalUrl, params: { name } }, res) => {
channelAvailabilityRoute ({ ip, originalUrl, params: { name } }, res) {
const gaStartTime = Date.now();
checkChannelAvailability(name)
.then(availableName => {
@ -26,9 +24,9 @@ module.exports = (app) => {
.catch(error => {
errorHandlers.handleErrorResponse(originalUrl, ip, error, res);
});
});
},
// route to get a short channel id from long channel Id
app.get('/api/channel/short-id/:longId/:name', ({ ip, originalUrl, params }, res) => {
channelShortIdRoute ({ ip, originalUrl, params }, res) {
db.Certificate.getShortChannelIdFromLongChannelId(params.longId, params.name)
.then(shortId => {
res.status(200).json(shortId);
@ -36,8 +34,8 @@ module.exports = (app) => {
.catch(error => {
errorHandlers.handleErrorResponse(originalUrl, ip, error, res);
});
});
app.get('/api/channel/data/:channelName/:channelClaimId', ({ ip, originalUrl, body, params }, res) => {
},
channelDataRoute ({ ip, originalUrl, body, params }, res) {
const channelName = params.channelName;
let channelClaimId = params.channelClaimId;
if (channelClaimId === 'none') channelClaimId = null;
@ -51,8 +49,8 @@ module.exports = (app) => {
.catch(error => {
errorHandlers.handleErrorResponse(originalUrl, ip, error, res);
});
});
app.get('/api/channel/claims/:channelName/:channelClaimId/:page', ({ ip, originalUrl, body, params }, res) => {
},
channelClaimsRoute ({ ip, originalUrl, body, params }, res) {
const channelName = params.channelName;
let channelClaimId = params.channelClaimId;
if (channelClaimId === 'none') channelClaimId = null;
@ -67,9 +65,9 @@ module.exports = (app) => {
.catch(error => {
errorHandlers.handleErrorResponse(originalUrl, ip, error, res);
});
});
},
// route to run a claim_list request on the daemon
app.get('/api/claim/list/:name', ({ ip, originalUrl, params }, res) => {
claimListRoute ({ ip, originalUrl, params }, res) {
getClaimList(params.name)
.then(claimsList => {
res.status(200).json(claimsList);
@ -77,9 +75,9 @@ module.exports = (app) => {
.catch(error => {
errorHandlers.handleErrorResponse(originalUrl, ip, error, res);
});
});
},
// route to get an asset
app.get('/api/claim/get/:name/:claimId', ({ ip, originalUrl, params }, res) => {
claimGetRoute ({ ip, originalUrl, params }, res) {
const name = params.name;
const claimId = params.claimId;
// resolve the claim
@ -103,9 +101,9 @@ module.exports = (app) => {
.catch(error => {
errorHandlers.handleErrorResponse(originalUrl, ip, error, res);
});
});
},
// route to check whether this site published to a claim
app.get('/api/claim/availability/:name', ({ ip, originalUrl, params: { name } }, res) => {
claimAvailabilityRoute ({ ip, originalUrl, params: { name } }, res) {
const gaStartTime = Date.now();
claimNameIsAvailable(name)
.then(result => {
@ -115,9 +113,9 @@ module.exports = (app) => {
.catch(error => {
errorHandlers.handleErrorResponse(originalUrl, ip, error, res);
});
});
},
// route to run a resolve request on the daemon
app.get('/api/claim/resolve/:name/:claimId', ({ headers, ip, originalUrl, params }, res) => {
claimResolveRoute ({ headers, ip, originalUrl, params }, res) {
resolveUri(`${params.name}#${params.claimId}`)
.then(resolvedUri => {
res.status(200).json(resolvedUri);
@ -125,9 +123,9 @@ module.exports = (app) => {
.catch(error => {
errorHandlers.handleErrorResponse(originalUrl, ip, error, res);
});
});
},
// route to run a publish request on the daemon
app.post('/api/claim/publish', multipartMiddleware, ({ body, files, headers, ip, originalUrl, user }, res) => {
claimPublishRoute ({ body, files, headers, ip, originalUrl, user }, res) {
// define variables
let channelName, channelId, channelPassword, description, fileName, filePath, fileType, gaStartTime, license, name, nsfw, thumbnail, thumbnailFileName, thumbnailFilePath, thumbnailFileType, title;
// record the start time of the request
@ -178,9 +176,9 @@ module.exports = (app) => {
.catch(error => {
errorHandlers.handleErrorResponse(originalUrl, ip, error, res);
});
});
},
// route to get a short claim id from long claim Id
app.get('/api/claim/short-id/:longId/:name', ({ ip, originalUrl, body, params }, res) => {
claimShortIdRoute ({ ip, originalUrl, body, params }, res) {
db.Claim.getShortClaimIdFromLongClaimId(params.longId, params.name)
.then(shortId => {
res.status(200).json({success: true, data: shortId});
@ -188,8 +186,8 @@ module.exports = (app) => {
.catch(error => {
errorHandlers.handleErrorResponse(originalUrl, ip, error, res);
});
});
app.post('/api/claim/long-id', ({ ip, originalUrl, body, params }, res) => {
},
claimLongIdRoute ({ ip, originalUrl, body, params }, res) {
logger.debug('body:', body);
const channelName = body.channelName;
const channelClaimId = body.channelClaimId;
@ -208,8 +206,8 @@ module.exports = (app) => {
.catch(error => {
errorHandlers.handleErrorResponse(originalUrl, ip, error, res);
});
});
app.get('/api/claim/data/:claimName/:claimId', ({ ip, originalUrl, body, params }, res) => {
},
claimDataRoute ({ ip, originalUrl, body, params }, res) {
const claimName = params.claimName;
let claimId = params.claimId;
if (claimId === 'none') claimId = null;
@ -223,9 +221,9 @@ module.exports = (app) => {
.catch(error => {
errorHandlers.handleErrorResponse(originalUrl, ip, error, res);
});
});
},
// route to see if asset is available locally
app.get('/api/file/availability/:name/:claimId', ({ ip, originalUrl, params }, res) => {
fileAvailabilityRoute ({ ip, originalUrl, params }, res) {
const name = params.name;
const claimId = params.claimId;
db.File.findOne({where: {name, claimId}})
@ -238,5 +236,5 @@ module.exports = (app) => {
.catch(error => {
errorHandlers.handleErrorResponse(originalUrl, ip, error, res);
});
});
},
};

View file

@ -1,98 +0,0 @@
// app dependencies
const express = require('express');
const bodyParser = require('body-parser');
const expressHandlebars = require('express-handlebars');
const Handlebars = require('handlebars');
const helmet = require('helmet');
const passport = require('passport');
const { serializeSpeechUser, deserializeSpeechUser } = require('./helpers/authHelpers.js');
const cookieSession = require('cookie-session');
const http = require('http');
// logging dependencies
const logger = require('winston');
function Server () {
this.configureMysql = (mysqlConfig) => {
require('../config/mysqlConfig.js').configure(mysqlConfig);
};
this.configureSite = (siteConfig) => {
require('../config/siteConfig.js').configure(siteConfig);
this.sessionKey = siteConfig.auth.sessionKey;
this.PORT = siteConfig.details.port;
};
this.configureSlack = (slackConfig) => {
require('../config/slackConfig.js').configure(slackConfig);
};
this.createApp = () => {
// create an Express application
const app = express();
// trust the proxy to get ip address for us
app.enable('trust proxy');
// add middleware
app.use(helmet()); // set HTTP headers to protect against well-known web vulnerabilties
app.use(express.static(`${__dirname}/public`)); // 'express.static' to serve static files from public directory
app.use(bodyParser.json()); // 'body parser' for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // 'body parser' for parsing application/x-www-form-urlencoded
app.use((req, res, next) => { // custom logging middleware to log all incoming http requests
logger.verbose(`Request on ${req.originalUrl} from ${req.ip}`);
next();
});
// configure passport
passport.serializeUser(serializeSpeechUser);
passport.deserializeUser(deserializeSpeechUser);
const localSignupStrategy = require('./passport/local-signup.js');
const localLoginStrategy = require('./passport/local-login.js');
passport.use('local-signup', localSignupStrategy);
passport.use('local-login', localLoginStrategy);
// initialize passport
app.use(cookieSession({
name : 'session',
keys : [this.sessionKey],
maxAge: 24 * 60 * 60 * 1000, // i.e. 24 hours
}));
app.use(passport.initialize());
app.use(passport.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('./routes/auth-routes.js')(app);
require('./routes/api-routes.js')(app);
require('./routes/page-routes.js')(app);
require('./routes/asset-routes.js')(app);
require('./routes/fallback-routes.js')(app);
this.app = app;
};
this.initialize = () => {
require('./helpers/configureLogger.js')(logger);
require('./helpers/configureSlack.js')(logger);
this.createApp();
this.server = http.Server(this.app);
};
this.start = () => {
const db = require('./models/index');
// sync sequelize
db.sequelize.sync()
// start the server
.then(() => {
this.server.listen(this.PORT, () => {
logger.info(`Server is listening on PORT ${this.PORT}`);
});
})
.catch((error) => {
logger.error(`Startup Error:`, error);
});
};
};
module.exports = Server;

View file

@ -1,13 +1,25 @@
const Server = require('./server/server.js');
const Components = require('./client/components');
const Containers = require('./client/containers');
const Pages = require('./client/pages');
// const Server = require('./server/server.js');
// const Components = require('./client/components');
// const Containers = require('./client/containers');
// const Pages = require('./client/pages');
const apiRoutes = require('./server/routes/apiRoutes.js');
const logger = require('./config/loggerConfig.js');
const mysql = require('./config/mysqlConfig.js');
const slack = require('./config/slackConfig.js');
const database = require('./server/models');
const exports = {
Server,
Components,
Containers,
Pages,
// Server,
// Components,
// Containers,
// Pages,
apiRoutes,
config: {
logger,
mysql,
slack,
},
database,
};
module.exports = exports;

View file

@ -1,32 +0,0 @@
const Path = require('path');
const REACT_ROOT = Path.resolve(__dirname, 'client/');
module.exports = {
target: 'web',
entry : ['babel-polyfill', 'whatwg-fetch', './client/client.js'],
output: {
path : Path.join(__dirname, 'public/bundle/'),
publicPath: 'public/bundle/',
filename : 'bundle.js',
},
module: {
loaders: [
{
test : /.jsx?$/,
loader : 'babel-loader',
exclude: /node_modules/,
query : {
presets: ['es2015', 'react', 'stage-2'],
},
},
],
},
resolve: {
modules: [
REACT_ROOT,
'node_modules',
__dirname,
],
extensions: ['.js', '.jsx', '.scss'],
},
};

View file

@ -1,7 +1,5 @@
const packageBaseConfig = require('./webpack.package.common.js');
const clientBaseConfig = require('./webpack.client.common.js');
module.exports = [
packageBaseConfig,
clientBaseConfig,
];

View file

@ -1,5 +1,4 @@
const packageBaseConfig = require('./webpack.package.common.js');
const clientBaseConfig = require('./webpack.client.common.js');
const merge = require('webpack-merge');
const devBuildConfig = {
@ -9,5 +8,4 @@ const devBuildConfig = {
module.exports = [
merge(packageBaseConfig, devBuildConfig),
merge(clientBaseConfig, devBuildConfig),
];

View file

@ -2,7 +2,6 @@ const webpack = require('webpack');
const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const packageBaseConfig = require('./webpack.package.common.js');
const clientBaseConfig = require('./webpack.client.common.js');
const productionBuildConfig = {
devtool: 'source-map',
@ -18,5 +17,4 @@ const productionBuildConfig = {
module.exports = [
merge(packageBaseConfig, productionBuildConfig),
merge(clientBaseConfig, productionBuildConfig),
];