Semicolon rule added #34

Merged
filipnyquist merged 1 commit from fillerino-semi-fix into master 2017-06-19 18:42:03 +02:00
16 changed files with 289 additions and 284 deletions

View file

@ -16,6 +16,11 @@
"error", "error",
"always-multiline" "always-multiline"
], ],
"semi": [
"error",
"always",
{ "omitLastInOneLineBlock": true }
],
"key-spacing": [ "key-spacing": [
"error", "error",
{ {

View file

@ -1,12 +1,12 @@
const fs = require('fs') const fs = require('fs');
const lbryApi = require('../helpers/libraries/lbryApi.js') const lbryApi = require('../helpers/libraries/lbryApi.js');
const config = require('config') const config = require('config');
const errorHandlers = require('../helpers/libraries/errorHandlers.js') 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) { function createPublishParams (claim, filePath, license, nsfw) {
console.log('nsfw:', nsfw, typeof nsfw) console.log('nsfw:', nsfw, typeof nsfw);
const publishParams = { const publishParams = {
name : claim, name : claim,
file_path: filePath, file_path: filePath,
@ -21,38 +21,38 @@ function createPublishParams (claim, filePath, license, nsfw) {
}, },
claim_address : walledAddress, claim_address : walledAddress,
change_address: walledAddress, change_address: walledAddress,
} };
return publishParams return publishParams;
} }
function deleteTemporaryFile (filePath) { function deleteTemporaryFile (filePath) {
fs.unlink(filePath, err => { fs.unlink(filePath, err => {
if (err) throw err if (err) throw err;
console.log(`successfully deleted ${filePath}`) console.log(`successfully deleted ${filePath}`);
}) });
} }
module.exports = { module.exports = {
publish (claim, fileName, filePath, fileType, license, nsfw, socket, visitor) { publish (claim, fileName, filePath, fileType, license, nsfw, socket, visitor) {
// update the client // 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 // send to analytics
visitor.event('Publish Route', 'Publish Request', filePath).send() visitor.event('Publish Route', 'Publish Request', filePath).send();
// create the publish object // create the publish object
const publishParams = createPublishParams(claim, filePath, license, nsfw) const publishParams = createPublishParams(claim, filePath, license, nsfw);
// get a promise to publish // get a promise to publish
lbryApi lbryApi
.publishClaim(publishParams, fileName, fileType) .publishClaim(publishParams, fileName, fileType)
.then(result => { .then(result => {
visitor.event('Publish Route', 'Publish Success', filePath).send() visitor.event('Publish Route', 'Publish Success', filePath).send();
console.log('publish promise success. Tx info:', result) console.log('publish promise success. Tx info:', result);
socket.emit('publish-complete', { name: claim, result }) socket.emit('publish-complete', { name: claim, result });
}) })
.catch(error => { .catch(error => {
visitor.event('Publish Route', 'Publish Failure', filePath).send() visitor.event('Publish Route', 'Publish Failure', filePath).send();
console.log('error:', error) console.log('error:', error);
socket.emit('publish-failure', errorHandlers.handlePublishError(error)) socket.emit('publish-failure', errorHandlers.handlePublishError(error));
deleteTemporaryFile(filePath) deleteTemporaryFile(filePath);
}) });
}, },
} };

View file

@ -1,8 +1,8 @@
const lbryApi = require('../helpers/libraries/lbryApi.js') const lbryApi = require('../helpers/libraries/lbryApi.js');
const db = require('../models') const db = require('../models');
const getAllFreePublicClaims = require('../helpers/functions/getAllFreePublicClaims.js') const getAllFreePublicClaims = require('../helpers/functions/getAllFreePublicClaims.js');
const isFreePublicClaim = require('../helpers/functions/isFreePublicClaim.js') const isFreePublicClaim = require('../helpers/functions/isFreePublicClaim.js');
function getClaimAndHandleResponse (claimUri, resolve, reject) { function getClaimAndHandleResponse (claimUri, resolve, reject) {
lbryApi lbryApi
@ -12,103 +12,103 @@ function getClaimAndHandleResponse (claimUri, resolve, reject) {
file_name, file_name,
file_path: download_path, file_path: download_path,
file_type: mime_type, file_type: mime_type,
}) });
}) })
.catch(error => { .catch(error => {
reject(error) reject(error);
}) });
} }
module.exports = { module.exports = {
getClaimByName (claimName) { getClaimByName (claimName) {
const deferred = new Promise((resolve, reject) => { const deferred = new Promise((resolve, reject) => {
console.log('>> lbryHelpers >> getClaim BasedOnNameOnly:', claimName) console.log('>> lbryHelpers >> getClaim BasedOnNameOnly:', claimName);
// get all free public claims // get all free public claims
getAllFreePublicClaims(claimName) getAllFreePublicClaims(claimName)
.then(freePublicClaimList => { .then(freePublicClaimList => {
const claimId = freePublicClaimList[0].claim_id const claimId = freePublicClaimList[0].claim_id;
const name = freePublicClaimList[0].name const name = freePublicClaimList[0].name;
const freePublicClaimOutpoint = `${freePublicClaimList[0].txid}:${freePublicClaimList[0].nout}` const freePublicClaimOutpoint = `${freePublicClaimList[0].txid}:${freePublicClaimList[0].nout}`;
const freePublicClaimUri = name + '#' + claimId const freePublicClaimUri = name + '#' + claimId;
console.log('>> Decided on public claim id:', claimId) console.log('>> Decided on public claim id:', claimId);
// check to see if the file is available locally // check to see if the file is available locally
db.File db.File
.findOne({ where: { name: name, claim_id: claimId } }) .findOne({ where: { name: name, claim_id: claimId } })
.then(claim => { .then(claim => {
// if a matching claim is found locally... // if a matching claim is found locally...
if (claim) { 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 the outpoint's match return it
if (claim.dataValues.outpoint === freePublicClaimOutpoint) { if (claim.dataValues.outpoint === freePublicClaimOutpoint) {
console.log('>> Local outpoint matched') console.log('>> Local outpoint matched');
resolve(claim.dataValues) resolve(claim.dataValues);
// if the outpoint's don't match, fetch updated claim // if the outpoint's don't match, fetch updated claim
} else { } else {
console.log('>> local outpoint did not match') console.log('>> local outpoint did not match');
getClaimAndHandleResponse(freePublicClaimUri, resolve, reject) getClaimAndHandleResponse(freePublicClaimUri, resolve, reject);
} }
// ... otherwise use daemon to retrieve it // ... otherwise use daemon to retrieve it
} else { } else {
// 'get' the claim // 'get' the claim
getClaimAndHandleResponse(freePublicClaimUri, resolve, reject) getClaimAndHandleResponse(freePublicClaimUri, resolve, reject);
} }
}) })
.catch(error => { .catch(error => {
reject(error) reject(error);
}) });
}) })
.catch(error => { .catch(error => {
reject(error) reject(error);
}) });
}) });
return deferred return deferred;
}, },
getClaimByClaimId (claimName, claimId) { getClaimByClaimId (claimName, claimId) {
const deferred = new Promise((resolve, reject) => { const deferred = new Promise((resolve, reject) => {
const uri = `${claimName}#${claimId}` const uri = `${claimName}#${claimId}`;
console.log('>> lbryHelpers >> getClaimBasedOnUri:', uri) console.log('>> lbryHelpers >> getClaimBasedOnUri:', uri);
// resolve the Uri // resolve the Uri
lbryApi lbryApi
.resolveUri(uri) // note: use 'spread' and make parallel with db.File.findOne() .resolveUri(uri) // note: use 'spread' and make parallel with db.File.findOne()
.then(result => { .then(result => {
// note should just be 'result' returned. // note should just be 'result' returned.
// get the outpoint // 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 // check locally for the claim
db.File db.File
.findOne({ where: { claim_id: claimId } }) .findOne({ where: { claim_id: claimId } })
.then(claim => { .then(claim => {
// if a found locally... // if a found locally...
if (claim) { 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 the outpoint's match return it
if (claim.dataValues.outpoint === resolvedOutpoint) { if (claim.dataValues.outpoint === resolvedOutpoint) {
console.log('>> Local outpoint matched') console.log('>> Local outpoint matched');
resolve(claim.dataValues) resolve(claim.dataValues);
// if the outpoint's don't match, fetch updated claim // if the outpoint's don't match, fetch updated claim
} else { } else {
console.log('>> Local outpoint did not match') console.log('>> Local outpoint did not match');
getClaimAndHandleResponse(uri, resolve, reject) getClaimAndHandleResponse(uri, resolve, reject);
} }
// ... otherwise use daemon to retrieve it // ... otherwise use daemon to retrieve it
} else { } else {
// check to make sure it is free and public (note: no need for another resolve?) // check to make sure it is free and public (note: no need for another resolve?)
if (isFreePublicClaim(result[uri].claim)) { if (isFreePublicClaim(result[uri].claim)) {
// 'get' the claim // 'get' the claim
getClaimAndHandleResponse(uri, resolve, reject) getClaimAndHandleResponse(uri, resolve, reject);
} else { } else {
reject('NO_FREE_PUBLIC_CLAIMS') reject('NO_FREE_PUBLIC_CLAIMS');
} }
} }
}) })
.catch(error => { .catch(error => {
reject(error) reject(error);
}) });
}) })
.catch(error => { .catch(error => {
reject(error) reject(error);
}) });
}) });
return deferred return deferred;
}, },
} };

View file

@ -1,7 +1,7 @@
const getAllFreePublicClaims = require('../helpers/functions/getAllFreePublicClaims.js') const getAllFreePublicClaims = require('../helpers/functions/getAllFreePublicClaims.js');
module.exports = { module.exports = {
getAllClaims (claimName) { getAllClaims (claimName) {
return getAllFreePublicClaims(claimName) return getAllFreePublicClaims(claimName);
}, },
} };

View file

@ -1,30 +1,30 @@
const isFreePublicClaim = require('./isFreePublicClaim.js') const isFreePublicClaim = require('./isFreePublicClaim.js');
const lbryApi = require('../libraries/lbryApi.js') const lbryApi = require('../libraries/lbryApi.js');
function filterForFreePublicClaims (claimsListArray) { function filterForFreePublicClaims (claimsListArray) {
// console.log("claims list:", claimsListArray) // console.log("claims list:", claimsListArray)
if (!claimsListArray) { if (!claimsListArray) {
return null return null;
} }
const freePublicClaims = claimsListArray.filter(claim => { const freePublicClaims = claimsListArray.filter(claim => {
if (!claim.value) { if (!claim.value) {
return false return false;
} }
return isFreePublicClaim(claim) return isFreePublicClaim(claim);
}) });
return freePublicClaims return freePublicClaims;
} }
function orderTopClaims (claimsListArray) { function orderTopClaims (claimsListArray) {
console.log('>> orderTopClaims') console.log('>> orderTopClaims');
claimsListArray.sort(({ amountA, heightA }, { amountB, heightB }) => { claimsListArray.sort(({ amountA, heightA }, { amountB, heightB }) => {
if (amountA === amountB) { if (amountA === amountB) {
return heightA > heightB return heightA > heightB;
} else { } else {
return amountA < amountB return amountA < amountB;
} }
}) });
return claimsListArray return claimsListArray;
} }
module.exports = claimName => { module.exports = claimName => {
@ -33,31 +33,31 @@ module.exports = claimName => {
lbryApi lbryApi
.getClaimsList(claimName) .getClaimsList(claimName)
.then(({ claims }) => { .then(({ claims }) => {
const claimsList = claims const claimsList = claims;
console.log('>> Number of claims:', claimsList.length) console.log('>> Number of claims:', claimsList.length);
// return early if no claims were found // return early if no claims were found
if (claimsList.length === 0) { if (claimsList.length === 0) {
reject('NO_CLAIMS') reject('NO_CLAIMS');
console.log('exiting due to lack of claims') console.log('exiting due to lack of claims');
return return;
} }
// filter the claims to return only free, public claims // 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 // return early if no free, public claims were found
if (!freePublicClaims || freePublicClaims.length === 0) { if (!freePublicClaims || freePublicClaims.length === 0) {
reject('NO_FREE_PUBLIC_CLAIMS') reject('NO_FREE_PUBLIC_CLAIMS');
console.log('exiting due to lack of free or public claims') console.log('exiting due to lack of free or public claims');
return return;
} }
// order the claims // order the claims
const orderedPublicClaims = orderTopClaims(freePublicClaims) const orderedPublicClaims = orderTopClaims(freePublicClaims);
// resolve the promise // resolve the promise
resolve(orderedPublicClaims) resolve(orderedPublicClaims);
}) })
.catch(error => { .catch(error => {
console.log(">> 'claim_list' error") console.log(">> 'claim_list' error");
reject(error) reject(error);
}) });
}) });
return deferred return deferred;
} };

View file

@ -1,11 +1,11 @@
module.exports = ({ value }) => { module.exports = ({ value }) => {
console.log('>> check: isFreePublicClaim?') console.log('>> check: isFreePublicClaim?');
if ( if (
(value.stream.metadata.license.indexOf('Public Domain') !== -1 || value.stream.metadata.license.indexOf('Creative Commons') !== -1) && (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) (!value.stream.metadata.fee || value.stream.metadata.fee.amount === 0)
) { ) {
return true return true;
} else { } else {
return false return false;
} }
} };

View file

@ -1,22 +1,22 @@
module.exports = { module.exports = {
handleRequestError (error, res) { handleRequestError (error, res) {
if (error === 'NO_CLAIMS' || error === 'NO_FREE_PUBLIC_CLAIMS') { if (error === 'NO_CLAIMS' || error === 'NO_FREE_PUBLIC_CLAIMS') {
res.status(307).render('noClaims') res.status(307).render('noClaims');
} else if (error.response) { } 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') { } 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 { } else {
res.status(400).send(error.toString()) res.status(400).send(error.toString());
} }
}, },
handlePublishError (error) { handlePublishError (error) {
if (error.code === 'ECONNREFUSED') { 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) { } else if (error.response.data.error) {
return error.response.data.error return error.response.data.error;
} else { } else {
return error return error;
} }
}, },
} };

View file

@ -1,18 +1,18 @@
const axios = require('axios') const axios = require('axios');
const db = require('../../models') const db = require('../../models');
module.exports = { module.exports = {
publishClaim (publishParams, fileName, fileType) { publishClaim (publishParams, fileName, fileType) {
const deferred = new Promise((resolve, reject) => { const deferred = new Promise((resolve, reject) => {
console.log('>> lbryApi >> publishClaim:', publishParams) console.log('>> lbryApi >> publishClaim:', publishParams);
axios axios
.post('http://localhost:5279/lbryapi', { .post('http://localhost:5279/lbryapi', {
method: 'publish', method: 'publish',
params: publishParams, params: publishParams,
}) })
.then(response => { .then(response => {
console.log(">> 'publish' success", response) console.log(">> 'publish' success", response);
const result = response.data.result const result = response.data.result;
db.File db.File
.create({ .create({
name : publishParams.name, name : publishParams.name,
@ -24,36 +24,36 @@ module.exports = {
nsfw : publishParams.metadata.nsfw, nsfw : publishParams.metadata.nsfw,
}) })
.catch(error => { .catch(error => {
console.log('An error occurred when writing to the MySQL database:', error) console.log('An error occurred when writing to the MySQL database:', error);
}) });
resolve(result) resolve(result);
}) })
.catch(error => { .catch(error => {
console.log(">> 'publish' error") console.log(">> 'publish' error");
reject(error) reject(error);
}) });
}) });
return deferred return deferred;
}, },
getClaim (uri) { getClaim (uri) {
const deferred = new Promise((resolve, reject) => { const deferred = new Promise((resolve, reject) => {
console.log('>> lbryApi >> getClaim:', uri) console.log('>> lbryApi >> getClaim:', uri);
axios axios
.post('http://localhost:5279/lbryapi', { .post('http://localhost:5279/lbryapi', {
method: 'get', method: 'get',
params: { uri, timeout: 20 }, params: { uri, timeout: 20 },
}) })
.then(({ data }) => { .then(({ data }) => {
console.log(">> 'get' success") console.log(">> 'get' success");
// check to make sure the daemon didn't just time out // check to make sure the daemon didn't just time out
if (data.result.error) { 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) 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 // save a record of the file to the Files table
const result = data.result const result = data.result;
db.File db.File
.create({ .create({
name : result.name, name : result.name,
@ -65,53 +65,53 @@ module.exports = {
nsfw : result.metadata.stream.metadata.nsfw, nsfw : result.metadata.stream.metadata.nsfw,
}) })
.catch(error => { .catch(error => {
console.log('An error occurred when writing to the MySQL database:', error) console.log('An error occurred when writing to the MySQL database:', error);
}) });
resolve(result) resolve(result);
}) })
.catch(error => { .catch(error => {
console.log(">> 'get' error") console.log(">> 'get' error");
reject(error) reject(error);
}) });
}) });
return deferred return deferred;
}, },
getClaimsList (claimName) { getClaimsList (claimName) {
const deferred = new Promise((resolve, reject) => { const deferred = new Promise((resolve, reject) => {
console.log('>> lbryApi >> getClaimList:', claimName) console.log('>> lbryApi >> getClaimList:', claimName);
axios axios
.post('http://localhost:5279/lbryapi', { .post('http://localhost:5279/lbryapi', {
method: 'claim_list', method: 'claim_list',
params: { name: claimName }, params: { name: claimName },
}) })
.then(({ data }) => { .then(({ data }) => {
console.log(">> 'claim_list' success") console.log(">> 'claim_list' success");
resolve(data.result) resolve(data.result);
}) })
.catch(error => { .catch(error => {
console.log(">> 'claim_list' error") console.log(">> 'claim_list' error");
reject(error) reject(error);
}) });
}) });
return deferred return deferred;
}, },
resolveUri (uri) { resolveUri (uri) {
const deferred = new Promise((resolve, reject) => { const deferred = new Promise((resolve, reject) => {
console.log('>> lbryApi >> resolveUri:', uri) console.log('>> lbryApi >> resolveUri:', uri);
axios axios
.post('http://localhost:5279/lbryapi', { .post('http://localhost:5279/lbryapi', {
method: 'resolve', method: 'resolve',
params: { uri }, params: { uri },
}) })
.then(({ data }) => { .then(({ data }) => {
console.log(">> 'resolve' success") console.log(">> 'resolve' success");
resolve(data.result) resolve(data.result);
}) })
.catch(error => { .catch(error => {
console.log(">> 'resolve' error") console.log(">> 'resolve' error");
reject(error) reject(error);
}) });
}) });
return deferred return deferred;
}, },
} };

View file

@ -34,6 +34,6 @@ module.exports = (sequelize, { STRING, BOOLEAN }) => {
{ {
freezeTableName: true, freezeTableName: true,
} }
) );
return File return File;
} };

View file

@ -1,34 +1,34 @@
const fs = require('fs') const fs = require('fs');
const path = require('path') const path = require('path');
const Sequelize = require('sequelize') const Sequelize = require('sequelize');
const basename = path.basename(module.filename) const basename = path.basename(module.filename);
const config = require('config') const config = require('config');
const db = {} const db = {};
const connectionUri = config.get('Database.MySqlConnectionUri') const connectionUri = config.get('Database.MySqlConnectionUri');
const sequelize = new Sequelize(connectionUri) const sequelize = new Sequelize(connectionUri);
sequelize sequelize
.authenticate() .authenticate()
.then(() => { .then(() => {
console.log('Connection has been established successfully.') console.log('Connection has been established successfully.');
}) })
.catch(err => { .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 => { fs.readdirSync(__dirname).filter(file => file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js').forEach(file => {
const model = sequelize['import'](path.join(__dirname, file)) const model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model db[model.name] = model;
}) });
Object.keys(db).forEach(modelName => { Object.keys(db).forEach(modelName => {
if (db[modelName].associate) { 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;

View file

@ -1,5 +1,5 @@
const errorHandlers = require('../helpers/libraries/errorHandlers.js') const errorHandlers = require('../helpers/libraries/errorHandlers.js');
const lbryApi = require('../helpers/libraries/lbryApi.js') const lbryApi = require('../helpers/libraries/lbryApi.js');
module.exports = app => { module.exports = app => {
// route to run a claim_list request on the daemon // route to run a claim_list request on the daemon
@ -7,24 +7,24 @@ module.exports = app => {
lbryApi lbryApi
.getClaimsList(params.claim) .getClaimsList(params.claim)
.then(claimsList => { .then(claimsList => {
console.log('/api/claim_list/:claim success.') console.log('/api/claim_list/:claim success.');
res.status(200).json(claimsList) res.status(200).json(claimsList);
}) })
.catch(error => { .catch(error => {
console.log('/api/claim_list/:name error:', error) console.log('/api/claim_list/:name error:', error);
errorHandlers.handleRequestError(error, res) errorHandlers.handleRequestError(error, res);
}) });
}) });
// route to run a resolve request on the daemon // route to run a resolve request on the daemon
app.get('/api/resolve/:uri', ({ params }, res) => { app.get('/api/resolve/:uri', ({ params }, res) => {
lbryApi lbryApi
.resolveUri(params.uri) .resolveUri(params.uri)
.then(resolvedUri => { .then(resolvedUri => {
console.log('/api/resolve/:claim success.') console.log('/api/resolve/:claim success.');
res.status(200).json(resolvedUri) res.status(200).json(resolvedUri);
}) })
.catch(error => { .catch(error => {
errorHandlers.handleRequestError(error, res) errorHandlers.handleRequestError(error, res);
}) });
}) });
} };

View file

@ -1,10 +1,10 @@
module.exports = app => { module.exports = app => {
// route for the home page // route for the home page
app.get('/', (req, res) => { 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 // a catch-all route if someone visits a page that does not exist
app.use('*', (req, res) => { app.use('*', (req, res) => {
res.status(404).render('fourOhFour') res.status(404).render('fourOhFour');
}) });
} };

View file

@ -1,5 +1,5 @@
const errorHandlers = require('../helpers/libraries/errorHandlers.js') const errorHandlers = require('../helpers/libraries/errorHandlers.js');
const serveController = require('../controllers/serveController.js') const serveController = require('../controllers/serveController.js');
function serveFile ({ file_type, file_path }, res) { function serveFile ({ file_type, file_path }, res) {
// set default options // set default options
@ -8,61 +8,61 @@ function serveFile ({ file_type, file_path }, res) {
'X-Content-Type-Options': 'nosniff', 'X-Content-Type-Options': 'nosniff',
'Content-Type' : file_type, 'Content-Type' : file_type,
}, },
} };
// adjust default options as needed // adjust default options as needed
// eslint-disable-next-line camelcase // eslint-disable-next-line camelcase
switch (file_type) { switch (file_type) {
case 'image/jpeg': case 'image/jpeg':
break break;
case 'image/gif': case 'image/gif':
break break;
case 'image/png': case 'image/png':
break break;
case 'video/mp4': case 'video/mp4':
break break;
default: default:
console.log('sending unknown file type as .jpeg') console.log('sending unknown file type as .jpeg');
options['headers']['Content-Type'] = 'image/jpeg' options['headers']['Content-Type'] = 'image/jpeg';
break break;
} }
// send file // send file
res.status(200).sendFile(file_path, options) res.status(200).sendFile(file_path, options);
} }
module.exports = (app, ua, googleAnalyticsId) => { module.exports = (app, ua, googleAnalyticsId) => {
// route to fetch one free public claim // route to fetch one free public claim
app.get('/:name/:claim_id', ({ params }, res) => { app.get('/:name/:claim_id', ({ params }, res) => {
const routeString = `${params.name}/${params.claim_id}` const routeString = `${params.name}/${params.claim_id}`;
// google analytics // 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 // begin image-serve processes
console.log(`>> GET request on /${routeString}`) console.log(`>> GET request on /${routeString}`);
serveController serveController
.getClaimByClaimId(params.name, params.claim_id) .getClaimByClaimId(params.name, params.claim_id)
.then(fileInfo => { .then(fileInfo => {
console.log('/:name/:claim_id success.', fileInfo.file_name) console.log('/:name/:claim_id success.', fileInfo.file_name);
serveFile(fileInfo, res) serveFile(fileInfo, res);
}) })
.catch(error => { .catch(error => {
console.log('/:name/:claim_id error:', error) console.log('/:name/:claim_id error:', error);
errorHandlers.handleRequestError(error, res) errorHandlers.handleRequestError(error, res);
}) });
}) });
// route to fetch one free public claim // route to fetch one free public claim
app.get('/:name', ({ params }, res) => { app.get('/:name', ({ params }, res) => {
// google analytics // 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 // begin image-serve processes
console.log(`>> GET request on /${params.name}`) console.log(`>> GET request on /${params.name}`);
serveController serveController
.getClaimByName(params.name) .getClaimByName(params.name)
.then(fileInfo => { .then(fileInfo => {
console.log('/:name success.', fileInfo.file_name) console.log('/:name success.', fileInfo.file_name);
serveFile(fileInfo, res) serveFile(fileInfo, res);
}) })
.catch(error => { .catch(error => {
console.log('/:name error:', error) console.log('/:name error:', error);
errorHandlers.handleRequestError(error, res) errorHandlers.handleRequestError(error, res);
}) });
}) });
} };

View file

@ -1,22 +1,22 @@
const errorHandlers = require('../helpers/libraries/errorHandlers.js') const errorHandlers = require('../helpers/libraries/errorHandlers.js');
const showController = require('../controllers/showController.js') const showController = require('../controllers/showController.js');
module.exports = (app, ua, googleAnalyticsId) => { module.exports = (app, ua, googleAnalyticsId) => {
// route to fetch all free public claims // route to fetch all free public claims
app.get('/:name/all', ({ params }, res) => { app.get('/:name/all', ({ params }, res) => {
console.log(`>> GET request on /${params.name}/all`) console.log(`>> GET request on /${params.name}/all`);
// google analytics // 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 // fetch all free public claims
showController showController
.getAllClaims(params.name) .getAllClaims(params.name)
.then(orderedFreePublicClaims => { .then(orderedFreePublicClaims => {
console.log('/:name/all success.') console.log('/:name/all success.');
res.status(200).render('allClaims', { claims: orderedFreePublicClaims }) res.status(200).render('allClaims', { claims: orderedFreePublicClaims });
}) })
.catch(error => { .catch(error => {
console.log('/:name/all error:', error) console.log('/:name/all error:', error);
errorHandlers.handleRequestError(error, res) errorHandlers.handleRequestError(error, res);
}) });
}) });
} };

View file

@ -1,42 +1,42 @@
const publishController = require('../controllers/publishController.js') const publishController = require('../controllers/publishController.js');
module.exports = (app, siofu, hostedContentPath, ua, googleAnalyticsId) => { module.exports = (app, siofu, hostedContentPath, ua, googleAnalyticsId) => {
const http = require('http').Server(app) const http = require('http').Server(app);
const io = require('socket.io')(http) const io = require('socket.io')(http);
io.on('connection', socket => { io.on('connection', socket => {
console.log('a user connected via sockets') console.log('a user connected via sockets');
// create visitor record // create visitor record
const visitor = ua(googleAnalyticsId, { https: true }) const visitor = ua(googleAnalyticsId, { https: true });
// attach upload listeners // attach upload listeners
const uploader = new siofu() const uploader = new siofu();
uploader.dir = hostedContentPath uploader.dir = hostedContentPath;
uploader.listen(socket) uploader.listen(socket);
uploader.on('start', ({ file }) => { uploader.on('start', ({ file }) => {
// server side test to make sure file is not a bad file type // server side test to make sure file is not a bad file type
if (/\.exe$/.test(file.name)) { if (/\.exe$/.test(file.name)) {
uploader.abort(file.id, socket) uploader.abort(file.id, socket);
} }
}) });
uploader.on('error', ({ error }) => { uploader.on('error', ({ error }) => {
console.log('an error occured while uploading', error) console.log('an error occured while uploading', error);
socket.emit('publish-status', error) socket.emit('publish-status', error);
}) });
uploader.on('saved', ({ file }) => { uploader.on('saved', ({ file }) => {
console.log('uploaded ', file.name) console.log('uploaded ', file.name);
if (file.success) { if (file.success) {
socket.emit('publish-status', 'file upload successfully completed') 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) publishController.publish(file.meta.name, file.name, file.pathName, file.meta.type, file.meta.license, file.meta.nsfw, socket, visitor);
} else { } else {
socket.emit('publish-failure', 'file uploaded, but with errors') socket.emit('publish-failure', 'file uploaded, but with errors');
// to-do: remove the file // to-do: remove the file
} }
}) });
// handle disconnect // handle disconnect
socket.on('disconnect', () => { socket.on('disconnect', () => {
console.log('user disconnected') console.log('user disconnected');
}) });
}) });
return http return http;
} };

View file

@ -1,29 +1,29 @@
// load dependencies // load dependencies
const express = require('express') const express = require('express');
const bodyParser = require('body-parser') const bodyParser = require('body-parser');
const siofu = require('socketio-file-upload') const siofu = require('socketio-file-upload');
const expressHandlebars = require('express-handlebars') const expressHandlebars = require('express-handlebars');
const Handlebars = require('handlebars') const Handlebars = require('handlebars');
const config = require('config') const config = require('config');
const ua = require('universal-analytics') const ua = require('universal-analytics');
const googleAnalyticsId = config.get('AnalyticsConfig.googleId') const googleAnalyticsId = config.get('AnalyticsConfig.googleId');
const hostedContentPath = config.get('Database.PublishUploadPath') const hostedContentPath = config.get('Database.PublishUploadPath');
// set port // set port
const PORT = 3000 const PORT = 3000;
// initialize express app // initialize express app
const app = express() const app = express();
// require our models for syncing // 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) // 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 // configure express app
app.use(bodyParser.json()) // for parsing application/json app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(siofu.router) app.use(siofu.router);
// configure handlebars & register it with Express app // configure handlebars & register it with Express app
const hbs = expressHandlebars.create({ const hbs = expressHandlebars.create({
@ -32,7 +32,7 @@ const hbs = expressHandlebars.create({
helpers : { helpers : {
// define any extra helpers you may need // define any extra helpers you may need
googleAnalytics () { googleAnalytics () {
const googleApiKey = config.get('AnalyticsConfig.googleId') const googleApiKey = config.get('AnalyticsConfig.googleId');
return new Handlebars.SafeString( return new Handlebars.SafeString(
`<script> `<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
@ -42,27 +42,27 @@ const hbs = expressHandlebars.create({
ga('create', '${googleApiKey}', 'auto'); ga('create', '${googleApiKey}', 'auto');
ga('send', 'pageview'); ga('send', 'pageview');
</script>` </script>`
) );
}, },
}, },
}) });
app.engine('handlebars', hbs.engine) app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars') app.set('view engine', 'handlebars');
// require express routes // require express routes
require('./routes/api-routes.js')(app) require('./routes/api-routes.js')(app);
require('./routes/show-routes.js')(app, ua, googleAnalyticsId) require('./routes/show-routes.js')(app, ua, googleAnalyticsId);
require('./routes/serve-routes.js')(app, ua, googleAnalyticsId) require('./routes/serve-routes.js')(app, ua, googleAnalyticsId);
require('./routes/home-routes.js')(app) require('./routes/home-routes.js')(app);
// require socket.io routes // 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 // sync sequelize
// wrap the server in socket.io to intercept incoming sockets requests // wrap the server in socket.io to intercept incoming sockets requests
// start server // start server
db.sequelize.sync({}).then(() => { db.sequelize.sync({}).then(() => {
http.listen(PORT, () => { http.listen(PORT, () => {
console.log(`Listening on PORT ${PORT}`) console.log(`Listening on PORT ${PORT}`);
}) });
}) });