diff --git a/.eslintrc b/.eslintrc index 0ac182a5..25af7e9b 100644 --- a/.eslintrc +++ b/.eslintrc @@ -16,6 +16,11 @@ "error", "always-multiline" ], + "semi": [ + "error", + "always", + { "omitLastInOneLineBlock": true } + ], "key-spacing": [ "error", { diff --git a/controllers/publishController.js b/controllers/publishController.js index d1b33f3c..52868893 100644 --- a/controllers/publishController.js +++ b/controllers/publishController.js @@ -1,12 +1,12 @@ -const fs = require('fs') -const lbryApi = require('../helpers/libraries/lbryApi.js') -const config = require('config') -const errorHandlers = require('../helpers/libraries/errorHandlers.js') +const fs = require('fs'); +const lbryApi = require('../helpers/libraries/lbryApi.js'); +const config = require('config'); +const errorHandlers = require('../helpers/libraries/errorHandlers.js'); -const walledAddress = config.get('WalletConfig.lbryAddress') +const walledAddress = config.get('WalletConfig.lbryAddress'); function createPublishParams (claim, filePath, license, nsfw) { - console.log('nsfw:', nsfw, typeof nsfw) + console.log('nsfw:', nsfw, typeof nsfw); const publishParams = { name : claim, file_path: filePath, @@ -21,38 +21,38 @@ function createPublishParams (claim, filePath, license, nsfw) { }, claim_address : walledAddress, change_address: walledAddress, - } - return publishParams + }; + return publishParams; } function deleteTemporaryFile (filePath) { fs.unlink(filePath, err => { - if (err) throw err - console.log(`successfully deleted ${filePath}`) - }) + if (err) throw err; + console.log(`successfully deleted ${filePath}`); + }); } module.exports = { publish (claim, fileName, filePath, fileType, license, nsfw, socket, visitor) { // update the client - socket.emit('publish-status', 'Your image is being published (this might take a second)...') + socket.emit('publish-status', 'Your image is being published (this might take a second)...'); // send to analytics - visitor.event('Publish Route', 'Publish Request', filePath).send() + visitor.event('Publish Route', 'Publish Request', filePath).send(); // create the publish object - const publishParams = createPublishParams(claim, filePath, license, nsfw) + const publishParams = createPublishParams(claim, filePath, license, nsfw); // get a promise to publish lbryApi .publishClaim(publishParams, fileName, fileType) .then(result => { - visitor.event('Publish Route', 'Publish Success', filePath).send() - console.log('publish promise success. Tx info:', result) - socket.emit('publish-complete', { name: claim, result }) + visitor.event('Publish Route', 'Publish Success', filePath).send(); + console.log('publish promise success. Tx info:', result); + socket.emit('publish-complete', { name: claim, result }); }) .catch(error => { - visitor.event('Publish Route', 'Publish Failure', filePath).send() - console.log('error:', error) - socket.emit('publish-failure', errorHandlers.handlePublishError(error)) - deleteTemporaryFile(filePath) - }) + visitor.event('Publish Route', 'Publish Failure', filePath).send(); + console.log('error:', error); + socket.emit('publish-failure', errorHandlers.handlePublishError(error)); + deleteTemporaryFile(filePath); + }); }, -} +}; diff --git a/controllers/serveController.js b/controllers/serveController.js index 32e9d632..f980161d 100644 --- a/controllers/serveController.js +++ b/controllers/serveController.js @@ -1,8 +1,8 @@ -const lbryApi = require('../helpers/libraries/lbryApi.js') -const db = require('../models') +const lbryApi = require('../helpers/libraries/lbryApi.js'); +const db = require('../models'); -const getAllFreePublicClaims = require('../helpers/functions/getAllFreePublicClaims.js') -const isFreePublicClaim = require('../helpers/functions/isFreePublicClaim.js') +const getAllFreePublicClaims = require('../helpers/functions/getAllFreePublicClaims.js'); +const isFreePublicClaim = require('../helpers/functions/isFreePublicClaim.js'); function getClaimAndHandleResponse (claimUri, resolve, reject) { lbryApi @@ -12,103 +12,103 @@ function getClaimAndHandleResponse (claimUri, resolve, reject) { file_name, file_path: download_path, file_type: mime_type, - }) + }); }) .catch(error => { - reject(error) - }) + reject(error); + }); } module.exports = { getClaimByName (claimName) { const deferred = new Promise((resolve, reject) => { - console.log('>> lbryHelpers >> getClaim BasedOnNameOnly:', claimName) + console.log('>> lbryHelpers >> getClaim BasedOnNameOnly:', claimName); // get all free public claims getAllFreePublicClaims(claimName) .then(freePublicClaimList => { - const claimId = freePublicClaimList[0].claim_id - const name = freePublicClaimList[0].name - const freePublicClaimOutpoint = `${freePublicClaimList[0].txid}:${freePublicClaimList[0].nout}` - const freePublicClaimUri = name + '#' + claimId - console.log('>> Decided on public claim id:', claimId) + const claimId = freePublicClaimList[0].claim_id; + const name = freePublicClaimList[0].name; + const freePublicClaimOutpoint = `${freePublicClaimList[0].txid}:${freePublicClaimList[0].nout}`; + const freePublicClaimUri = name + '#' + claimId; + console.log('>> Decided on public claim id:', claimId); // check to see if the file is available locally db.File .findOne({ where: { name: name, claim_id: claimId } }) .then(claim => { // if a matching claim is found locally... if (claim) { - console.log('>> A matching claim_id was found locally') + console.log('>> A matching claim_id was found locally'); // if the outpoint's match return it if (claim.dataValues.outpoint === freePublicClaimOutpoint) { - console.log('>> Local outpoint matched') - resolve(claim.dataValues) + console.log('>> Local outpoint matched'); + resolve(claim.dataValues); // if the outpoint's don't match, fetch updated claim } else { - console.log('>> local outpoint did not match') - getClaimAndHandleResponse(freePublicClaimUri, resolve, reject) + console.log('>> local outpoint did not match'); + getClaimAndHandleResponse(freePublicClaimUri, resolve, reject); } // ... otherwise use daemon to retrieve it } else { // 'get' the claim - getClaimAndHandleResponse(freePublicClaimUri, resolve, reject) + getClaimAndHandleResponse(freePublicClaimUri, resolve, reject); } }) .catch(error => { - reject(error) - }) + reject(error); + }); }) .catch(error => { - reject(error) - }) - }) - return deferred + reject(error); + }); + }); + return deferred; }, getClaimByClaimId (claimName, claimId) { const deferred = new Promise((resolve, reject) => { - const uri = `${claimName}#${claimId}` - console.log('>> lbryHelpers >> getClaimBasedOnUri:', uri) + const uri = `${claimName}#${claimId}`; + console.log('>> lbryHelpers >> getClaimBasedOnUri:', uri); // resolve the Uri lbryApi .resolveUri(uri) // note: use 'spread' and make parallel with db.File.findOne() .then(result => { // note should just be 'result' returned. // get the outpoint - const resolvedOutpoint = `${result[uri].claim.txid}:${result[uri].claim.nout}` + const resolvedOutpoint = `${result[uri].claim.txid}:${result[uri].claim.nout}`; // check locally for the claim db.File .findOne({ where: { claim_id: claimId } }) .then(claim => { // if a found locally... if (claim) { - console.log('>> A matching claim_id was found locally') + console.log('>> A matching claim_id was found locally'); // if the outpoint's match return it if (claim.dataValues.outpoint === resolvedOutpoint) { - console.log('>> Local outpoint matched') - resolve(claim.dataValues) + console.log('>> Local outpoint matched'); + resolve(claim.dataValues); // if the outpoint's don't match, fetch updated claim } else { - console.log('>> Local outpoint did not match') - getClaimAndHandleResponse(uri, resolve, reject) + console.log('>> Local outpoint did not match'); + getClaimAndHandleResponse(uri, resolve, reject); } // ... otherwise use daemon to retrieve it } else { // check to make sure it is free and public (note: no need for another resolve?) if (isFreePublicClaim(result[uri].claim)) { // 'get' the claim - getClaimAndHandleResponse(uri, resolve, reject) + getClaimAndHandleResponse(uri, resolve, reject); } else { - reject('NO_FREE_PUBLIC_CLAIMS') + reject('NO_FREE_PUBLIC_CLAIMS'); } } }) .catch(error => { - reject(error) - }) + reject(error); + }); }) .catch(error => { - reject(error) - }) - }) - return deferred + reject(error); + }); + }); + return deferred; }, -} +}; diff --git a/controllers/showController.js b/controllers/showController.js index 2def0f59..c5fa80a8 100644 --- a/controllers/showController.js +++ b/controllers/showController.js @@ -1,7 +1,7 @@ -const getAllFreePublicClaims = require('../helpers/functions/getAllFreePublicClaims.js') +const getAllFreePublicClaims = require('../helpers/functions/getAllFreePublicClaims.js'); module.exports = { getAllClaims (claimName) { - return getAllFreePublicClaims(claimName) + return getAllFreePublicClaims(claimName); }, -} +}; diff --git a/helpers/functions/getAllFreePublicClaims.js b/helpers/functions/getAllFreePublicClaims.js index 9faa69bc..17e8721f 100644 --- a/helpers/functions/getAllFreePublicClaims.js +++ b/helpers/functions/getAllFreePublicClaims.js @@ -1,30 +1,30 @@ -const isFreePublicClaim = require('./isFreePublicClaim.js') -const lbryApi = require('../libraries/lbryApi.js') +const isFreePublicClaim = require('./isFreePublicClaim.js'); +const lbryApi = require('../libraries/lbryApi.js'); function filterForFreePublicClaims (claimsListArray) { // console.log("claims list:", claimsListArray) if (!claimsListArray) { - return null + return null; } const freePublicClaims = claimsListArray.filter(claim => { if (!claim.value) { - return false + return false; } - return isFreePublicClaim(claim) - }) - return freePublicClaims + return isFreePublicClaim(claim); + }); + return freePublicClaims; } function orderTopClaims (claimsListArray) { - console.log('>> orderTopClaims') + console.log('>> orderTopClaims'); claimsListArray.sort(({ amountA, heightA }, { amountB, heightB }) => { if (amountA === amountB) { - return heightA > heightB + return heightA > heightB; } else { - return amountA < amountB + return amountA < amountB; } - }) - return claimsListArray + }); + return claimsListArray; } module.exports = claimName => { @@ -33,31 +33,31 @@ module.exports = claimName => { lbryApi .getClaimsList(claimName) .then(({ claims }) => { - const claimsList = claims - console.log('>> Number of claims:', claimsList.length) + const claimsList = claims; + console.log('>> Number of claims:', claimsList.length); // return early if no claims were found if (claimsList.length === 0) { - reject('NO_CLAIMS') - console.log('exiting due to lack of claims') - return + reject('NO_CLAIMS'); + console.log('exiting due to lack of claims'); + return; } // filter the claims to return only free, public claims - const freePublicClaims = filterForFreePublicClaims(claimsList) + const freePublicClaims = filterForFreePublicClaims(claimsList); // return early if no free, public claims were found if (!freePublicClaims || freePublicClaims.length === 0) { - reject('NO_FREE_PUBLIC_CLAIMS') - console.log('exiting due to lack of free or public claims') - return + reject('NO_FREE_PUBLIC_CLAIMS'); + console.log('exiting due to lack of free or public claims'); + return; } // order the claims - const orderedPublicClaims = orderTopClaims(freePublicClaims) + const orderedPublicClaims = orderTopClaims(freePublicClaims); // resolve the promise - resolve(orderedPublicClaims) + resolve(orderedPublicClaims); }) .catch(error => { - console.log(">> 'claim_list' error") - reject(error) - }) - }) - return deferred -} + console.log(">> 'claim_list' error"); + reject(error); + }); + }); + return deferred; +}; diff --git a/helpers/functions/isFreePublicClaim.js b/helpers/functions/isFreePublicClaim.js index 4dcce462..6e9a5f0c 100644 --- a/helpers/functions/isFreePublicClaim.js +++ b/helpers/functions/isFreePublicClaim.js @@ -1,11 +1,11 @@ module.exports = ({ value }) => { - console.log('>> check: isFreePublicClaim?') + console.log('>> check: isFreePublicClaim?'); if ( (value.stream.metadata.license.indexOf('Public Domain') !== -1 || value.stream.metadata.license.indexOf('Creative Commons') !== -1) && (!value.stream.metadata.fee || value.stream.metadata.fee.amount === 0) ) { - return true + return true; } else { - return false + return false; } -} +}; diff --git a/helpers/libraries/errorHandlers.js b/helpers/libraries/errorHandlers.js index a4e72331..dd375666 100644 --- a/helpers/libraries/errorHandlers.js +++ b/helpers/libraries/errorHandlers.js @@ -1,22 +1,22 @@ module.exports = { handleRequestError (error, res) { if (error === 'NO_CLAIMS' || error === 'NO_FREE_PUBLIC_CLAIMS') { - res.status(307).render('noClaims') + res.status(307).render('noClaims'); } else if (error.response) { - res.status(error.response.status).send(error.response.data.error.message) + res.status(error.response.status).send(error.response.data.error.message); } else if (error.code === 'ECONNREFUSED') { - res.status(400).send('Connection refused. The daemon may not be running.') + res.status(400).send('Connection refused. The daemon may not be running.'); } else { - res.status(400).send(error.toString()) + res.status(400).send(error.toString()); } }, handlePublishError (error) { if (error.code === 'ECONNREFUSED') { - return 'Connection refused. The daemon may not be running.' + return 'Connection refused. The daemon may not be running.'; } else if (error.response.data.error) { - return error.response.data.error + return error.response.data.error; } else { - return error + return error; } }, -} +}; diff --git a/helpers/libraries/lbryApi.js b/helpers/libraries/lbryApi.js index 1ee67652..d7d26b88 100644 --- a/helpers/libraries/lbryApi.js +++ b/helpers/libraries/lbryApi.js @@ -1,18 +1,18 @@ -const axios = require('axios') -const db = require('../../models') +const axios = require('axios'); +const db = require('../../models'); module.exports = { publishClaim (publishParams, fileName, fileType) { const deferred = new Promise((resolve, reject) => { - console.log('>> lbryApi >> publishClaim:', publishParams) + console.log('>> lbryApi >> publishClaim:', publishParams); axios .post('http://localhost:5279/lbryapi', { method: 'publish', params: publishParams, }) .then(response => { - console.log(">> 'publish' success", response) - const result = response.data.result + console.log(">> 'publish' success", response); + const result = response.data.result; db.File .create({ name : publishParams.name, @@ -24,36 +24,36 @@ module.exports = { nsfw : publishParams.metadata.nsfw, }) .catch(error => { - console.log('An error occurred when writing to the MySQL database:', error) - }) - resolve(result) + console.log('An error occurred when writing to the MySQL database:', error); + }); + resolve(result); }) .catch(error => { - console.log(">> 'publish' error") - reject(error) - }) - }) - return deferred + console.log(">> 'publish' error"); + reject(error); + }); + }); + return deferred; }, getClaim (uri) { const deferred = new Promise((resolve, reject) => { - console.log('>> lbryApi >> getClaim:', uri) + console.log('>> lbryApi >> getClaim:', uri); axios .post('http://localhost:5279/lbryapi', { method: 'get', params: { uri, timeout: 20 }, }) .then(({ data }) => { - console.log(">> 'get' success") + console.log(">> 'get' success"); // check to make sure the daemon didn't just time out if (data.result.error) { - reject(data.result.error) + reject(data.result.error); } /* note: put in a check to make sure we do not resolve until the download is actually complete (response.data.completed === true) */ // save a record of the file to the Files table - const result = data.result + const result = data.result; db.File .create({ name : result.name, @@ -65,53 +65,53 @@ module.exports = { nsfw : result.metadata.stream.metadata.nsfw, }) .catch(error => { - console.log('An error occurred when writing to the MySQL database:', error) - }) - resolve(result) + console.log('An error occurred when writing to the MySQL database:', error); + }); + resolve(result); }) .catch(error => { - console.log(">> 'get' error") - reject(error) - }) - }) - return deferred + console.log(">> 'get' error"); + reject(error); + }); + }); + return deferred; }, getClaimsList (claimName) { const deferred = new Promise((resolve, reject) => { - console.log('>> lbryApi >> getClaimList:', claimName) + console.log('>> lbryApi >> getClaimList:', claimName); axios .post('http://localhost:5279/lbryapi', { method: 'claim_list', params: { name: claimName }, }) .then(({ data }) => { - console.log(">> 'claim_list' success") - resolve(data.result) + console.log(">> 'claim_list' success"); + resolve(data.result); }) .catch(error => { - console.log(">> 'claim_list' error") - reject(error) - }) - }) - return deferred + console.log(">> 'claim_list' error"); + reject(error); + }); + }); + return deferred; }, resolveUri (uri) { const deferred = new Promise((resolve, reject) => { - console.log('>> lbryApi >> resolveUri:', uri) + console.log('>> lbryApi >> resolveUri:', uri); axios .post('http://localhost:5279/lbryapi', { method: 'resolve', params: { uri }, }) .then(({ data }) => { - console.log(">> 'resolve' success") - resolve(data.result) + console.log(">> 'resolve' success"); + resolve(data.result); }) .catch(error => { - console.log(">> 'resolve' error") - reject(error) - }) - }) - return deferred + console.log(">> 'resolve' error"); + reject(error); + }); + }); + return deferred; }, -} +}; diff --git a/models/file.js b/models/file.js index e1e0a73b..3f379ecd 100644 --- a/models/file.js +++ b/models/file.js @@ -34,6 +34,6 @@ module.exports = (sequelize, { STRING, BOOLEAN }) => { { freezeTableName: true, } - ) - return File -} + ); + return File; +}; diff --git a/models/index.js b/models/index.js index fb5bd569..31cfa33a 100644 --- a/models/index.js +++ b/models/index.js @@ -1,34 +1,34 @@ -const fs = require('fs') -const path = require('path') -const Sequelize = require('sequelize') -const basename = path.basename(module.filename) -const config = require('config') -const db = {} +const fs = require('fs'); +const path = require('path'); +const Sequelize = require('sequelize'); +const basename = path.basename(module.filename); +const config = require('config'); +const db = {}; -const connectionUri = config.get('Database.MySqlConnectionUri') -const sequelize = new Sequelize(connectionUri) +const connectionUri = config.get('Database.MySqlConnectionUri'); +const sequelize = new Sequelize(connectionUri); sequelize .authenticate() .then(() => { - console.log('Connection has been established successfully.') + console.log('Connection has been established successfully.'); }) .catch(err => { - console.error('Unable to connect to the database:', err) - }) + console.error('Unable to connect to the database:', err); + }); fs.readdirSync(__dirname).filter(file => file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js').forEach(file => { - const model = sequelize['import'](path.join(__dirname, file)) - db[model.name] = model -}) + const model = sequelize['import'](path.join(__dirname, file)); + db[model.name] = model; +}); Object.keys(db).forEach(modelName => { if (db[modelName].associate) { - db[modelName].associate(db) + db[modelName].associate(db); } -}) +}); -db.sequelize = sequelize -db.Sequelize = Sequelize +db.sequelize = sequelize; +db.Sequelize = Sequelize; -module.exports = db +module.exports = db; diff --git a/routes/api-routes.js b/routes/api-routes.js index 6697efd0..ffb5441a 100644 --- a/routes/api-routes.js +++ b/routes/api-routes.js @@ -1,5 +1,5 @@ -const errorHandlers = require('../helpers/libraries/errorHandlers.js') -const lbryApi = require('../helpers/libraries/lbryApi.js') +const errorHandlers = require('../helpers/libraries/errorHandlers.js'); +const lbryApi = require('../helpers/libraries/lbryApi.js'); module.exports = app => { // route to run a claim_list request on the daemon @@ -7,24 +7,24 @@ module.exports = app => { lbryApi .getClaimsList(params.claim) .then(claimsList => { - console.log('/api/claim_list/:claim success.') - res.status(200).json(claimsList) + console.log('/api/claim_list/:claim success.'); + res.status(200).json(claimsList); }) .catch(error => { - console.log('/api/claim_list/:name error:', error) - errorHandlers.handleRequestError(error, res) - }) - }) + console.log('/api/claim_list/:name error:', error); + errorHandlers.handleRequestError(error, res); + }); + }); // route to run a resolve request on the daemon app.get('/api/resolve/:uri', ({ params }, res) => { lbryApi .resolveUri(params.uri) .then(resolvedUri => { - console.log('/api/resolve/:claim success.') - res.status(200).json(resolvedUri) + console.log('/api/resolve/:claim success.'); + res.status(200).json(resolvedUri); }) .catch(error => { - errorHandlers.handleRequestError(error, res) - }) - }) -} + errorHandlers.handleRequestError(error, res); + }); + }); +}; diff --git a/routes/home-routes.js b/routes/home-routes.js index da4fcb22..90565557 100644 --- a/routes/home-routes.js +++ b/routes/home-routes.js @@ -1,10 +1,10 @@ module.exports = app => { // route for the home page app.get('/', (req, res) => { - res.status(200).render('index') - }) + res.status(200).render('index'); + }); // a catch-all route if someone visits a page that does not exist app.use('*', (req, res) => { - res.status(404).render('fourOhFour') - }) -} + res.status(404).render('fourOhFour'); + }); +}; diff --git a/routes/serve-routes.js b/routes/serve-routes.js index 8bf7b738..29747d4f 100644 --- a/routes/serve-routes.js +++ b/routes/serve-routes.js @@ -1,5 +1,5 @@ -const errorHandlers = require('../helpers/libraries/errorHandlers.js') -const serveController = require('../controllers/serveController.js') +const errorHandlers = require('../helpers/libraries/errorHandlers.js'); +const serveController = require('../controllers/serveController.js'); function serveFile ({ file_type, file_path }, res) { // set default options @@ -8,61 +8,61 @@ function serveFile ({ file_type, file_path }, res) { 'X-Content-Type-Options': 'nosniff', 'Content-Type' : file_type, }, - } + }; // adjust default options as needed // eslint-disable-next-line camelcase switch (file_type) { case 'image/jpeg': - break + break; case 'image/gif': - break + break; case 'image/png': - break + break; case 'video/mp4': - break + break; default: - console.log('sending unknown file type as .jpeg') - options['headers']['Content-Type'] = 'image/jpeg' - break + console.log('sending unknown file type as .jpeg'); + options['headers']['Content-Type'] = 'image/jpeg'; + break; } // send file - res.status(200).sendFile(file_path, options) + res.status(200).sendFile(file_path, options); } module.exports = (app, ua, googleAnalyticsId) => { // route to fetch one free public claim app.get('/:name/:claim_id', ({ params }, res) => { - const routeString = `${params.name}/${params.claim_id}` + const routeString = `${params.name}/${params.claim_id}`; // google analytics - ua(googleAnalyticsId, { https: true }).event('Serve Route', '/name/claimId', routeString).send() + ua(googleAnalyticsId, { https: true }).event('Serve Route', '/name/claimId', routeString).send(); // begin image-serve processes - console.log(`>> GET request on /${routeString}`) + console.log(`>> GET request on /${routeString}`); serveController .getClaimByClaimId(params.name, params.claim_id) .then(fileInfo => { - console.log('/:name/:claim_id success.', fileInfo.file_name) - serveFile(fileInfo, res) + console.log('/:name/:claim_id success.', fileInfo.file_name); + serveFile(fileInfo, res); }) .catch(error => { - console.log('/:name/:claim_id error:', error) - errorHandlers.handleRequestError(error, res) - }) - }) + console.log('/:name/:claim_id error:', error); + errorHandlers.handleRequestError(error, res); + }); + }); // route to fetch one free public claim app.get('/:name', ({ params }, res) => { // google analytics - ua(googleAnalyticsId, { https: true }).event('Serve Route', '/name', params.name).send() + ua(googleAnalyticsId, { https: true }).event('Serve Route', '/name', params.name).send(); // begin image-serve processes - console.log(`>> GET request on /${params.name}`) + console.log(`>> GET request on /${params.name}`); serveController .getClaimByName(params.name) .then(fileInfo => { - console.log('/:name success.', fileInfo.file_name) - serveFile(fileInfo, res) + console.log('/:name success.', fileInfo.file_name); + serveFile(fileInfo, res); }) .catch(error => { - console.log('/:name error:', error) - errorHandlers.handleRequestError(error, res) - }) - }) -} + console.log('/:name error:', error); + errorHandlers.handleRequestError(error, res); + }); + }); +}; diff --git a/routes/show-routes.js b/routes/show-routes.js index 21a2f5ce..ac0eed12 100644 --- a/routes/show-routes.js +++ b/routes/show-routes.js @@ -1,22 +1,22 @@ -const errorHandlers = require('../helpers/libraries/errorHandlers.js') -const showController = require('../controllers/showController.js') +const errorHandlers = require('../helpers/libraries/errorHandlers.js'); +const showController = require('../controllers/showController.js'); module.exports = (app, ua, googleAnalyticsId) => { // route to fetch all free public claims app.get('/:name/all', ({ params }, res) => { - console.log(`>> GET request on /${params.name}/all`) + console.log(`>> GET request on /${params.name}/all`); // google analytics - ua(googleAnalyticsId, { https: true }).event('Show Routes', '/name/all', `${params.name}/all`).send() + ua(googleAnalyticsId, { https: true }).event('Show Routes', '/name/all', `${params.name}/all`).send(); // fetch all free public claims showController .getAllClaims(params.name) .then(orderedFreePublicClaims => { - console.log('/:name/all success.') - res.status(200).render('allClaims', { claims: orderedFreePublicClaims }) + console.log('/:name/all success.'); + res.status(200).render('allClaims', { claims: orderedFreePublicClaims }); }) .catch(error => { - console.log('/:name/all error:', error) - errorHandlers.handleRequestError(error, res) - }) - }) -} + console.log('/:name/all error:', error); + errorHandlers.handleRequestError(error, res); + }); + }); +}; diff --git a/routes/sockets-routes.js b/routes/sockets-routes.js index e476519b..148034f7 100644 --- a/routes/sockets-routes.js +++ b/routes/sockets-routes.js @@ -1,42 +1,42 @@ -const publishController = require('../controllers/publishController.js') +const publishController = require('../controllers/publishController.js'); module.exports = (app, siofu, hostedContentPath, ua, googleAnalyticsId) => { - const http = require('http').Server(app) - const io = require('socket.io')(http) + const http = require('http').Server(app); + const io = require('socket.io')(http); io.on('connection', socket => { - console.log('a user connected via sockets') + console.log('a user connected via sockets'); // create visitor record - const visitor = ua(googleAnalyticsId, { https: true }) + const visitor = ua(googleAnalyticsId, { https: true }); // attach upload listeners - const uploader = new siofu() - uploader.dir = hostedContentPath - uploader.listen(socket) + const uploader = new siofu(); + uploader.dir = hostedContentPath; + uploader.listen(socket); uploader.on('start', ({ file }) => { // server side test to make sure file is not a bad file type if (/\.exe$/.test(file.name)) { - uploader.abort(file.id, socket) + uploader.abort(file.id, socket); } - }) + }); uploader.on('error', ({ error }) => { - console.log('an error occured while uploading', error) - socket.emit('publish-status', error) - }) + console.log('an error occured while uploading', error); + socket.emit('publish-status', error); + }); uploader.on('saved', ({ file }) => { - console.log('uploaded ', file.name) + console.log('uploaded ', file.name); if (file.success) { - socket.emit('publish-status', 'file upload successfully completed') - publishController.publish(file.meta.name, file.name, file.pathName, file.meta.type, file.meta.license, file.meta.nsfw, socket, visitor) + socket.emit('publish-status', 'file upload successfully completed'); + publishController.publish(file.meta.name, file.name, file.pathName, file.meta.type, file.meta.license, file.meta.nsfw, socket, visitor); } else { - socket.emit('publish-failure', 'file uploaded, but with errors') + socket.emit('publish-failure', 'file uploaded, but with errors'); // to-do: remove the file } - }) + }); // handle disconnect socket.on('disconnect', () => { - console.log('user disconnected') - }) - }) + console.log('user disconnected'); + }); + }); - return http -} + return http; +}; diff --git a/server.js b/server.js index 0f3f0cbe..c70742cb 100644 --- a/server.js +++ b/server.js @@ -1,29 +1,29 @@ // load dependencies -const express = require('express') -const bodyParser = require('body-parser') -const siofu = require('socketio-file-upload') -const expressHandlebars = require('express-handlebars') -const Handlebars = require('handlebars') -const config = require('config') -const ua = require('universal-analytics') +const express = require('express'); +const bodyParser = require('body-parser'); +const siofu = require('socketio-file-upload'); +const expressHandlebars = require('express-handlebars'); +const Handlebars = require('handlebars'); +const config = require('config'); +const ua = require('universal-analytics'); -const googleAnalyticsId = config.get('AnalyticsConfig.googleId') -const hostedContentPath = config.get('Database.PublishUploadPath') +const googleAnalyticsId = config.get('AnalyticsConfig.googleId'); +const hostedContentPath = config.get('Database.PublishUploadPath'); // set port -const PORT = 3000 +const PORT = 3000; // initialize express app -const app = express() +const app = express(); // require our models for syncing -const db = require('./models') +const db = require('./models'); // make express look in the public directory for assets (css/js/img) -app.use(express.static(`${__dirname}/public`)) +app.use(express.static(`${__dirname}/public`)); // configure express app -app.use(bodyParser.json()) // for parsing application/json -app.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded -app.use(siofu.router) +app.use(bodyParser.json()); // for parsing application/json +app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded +app.use(siofu.router); // configure handlebars & register it with Express app const hbs = expressHandlebars.create({ @@ -32,7 +32,7 @@ const hbs = expressHandlebars.create({ helpers : { // define any extra helpers you may need googleAnalytics () { - const googleApiKey = config.get('AnalyticsConfig.googleId') + const googleApiKey = config.get('AnalyticsConfig.googleId'); return new Handlebars.SafeString( `` - ) + ); }, }, -}) -app.engine('handlebars', hbs.engine) -app.set('view engine', 'handlebars') +}); +app.engine('handlebars', hbs.engine); +app.set('view engine', 'handlebars'); // require express routes -require('./routes/api-routes.js')(app) -require('./routes/show-routes.js')(app, ua, googleAnalyticsId) -require('./routes/serve-routes.js')(app, ua, googleAnalyticsId) -require('./routes/home-routes.js')(app) +require('./routes/api-routes.js')(app); +require('./routes/show-routes.js')(app, ua, googleAnalyticsId); +require('./routes/serve-routes.js')(app, ua, googleAnalyticsId); +require('./routes/home-routes.js')(app); // require socket.io routes -const http = require('./routes/sockets-routes.js')(app, siofu, hostedContentPath, ua, googleAnalyticsId) +const http = require('./routes/sockets-routes.js')(app, siofu, hostedContentPath, ua, googleAnalyticsId); // sync sequelize // wrap the server in socket.io to intercept incoming sockets requests // start server db.sequelize.sync({}).then(() => { http.listen(PORT, () => { - console.log(`Listening on PORT ${PORT}`) - }) -}) + console.log(`Listening on PORT ${PORT}`); + }); +});