refactored /helpers into /helpers and /controllers

This commit is contained in:
bill bittner 2017-06-16 17:48:51 -07:00
parent 5c40a5ccd0
commit 6d9523ff39
12 changed files with 148 additions and 143 deletions

View file

@ -1,20 +1,10 @@
var fs = require('fs'); var fs = require('fs');
var lbryApi = require('./lbryApi.js'); var lbryApi = require('../helpers/libraries/lbryApi.js');
var config = require('config'); var config = require('config');
var db = require("../models"); var errorHandlers = require("../helpers/libraries/errorHandlers.js");
var walledAddress = config.get('WalletConfig.lbryAddress'); var walledAddress = config.get('WalletConfig.lbryAddress');
function handlePublishError(error) {
if (error.code === "ECONNREFUSED"){
return "Connection refused. The daemon may not be running.";
} else if (error.response.data.error) {
return error.response.data.error;
} else {
return error;
};
}
function createPublishParams(name, filePath, license, nsfw) { function createPublishParams(name, filePath, license, nsfw) {
var publishParams = { var publishParams = {
"name": name, "name": name,
@ -26,7 +16,7 @@ function createPublishParams(name, filePath, license, nsfw) {
"author": "spee.ch", "author": "spee.ch",
"language": "en", "language": "en",
"license": license, "license": license,
"nsfw": nsfw "nsfw": (nsfw.toLowerCase() === "true")
}, },
"claim_address": walledAddress, "claim_address": walledAddress,
"change_address": walledAddress //requires daemon 0.12.2rc1 or above "change_address": walledAddress //requires daemon 0.12.2rc1 or above
@ -43,7 +33,6 @@ function deleteTemporaryFile(filePath) {
module.exports = { module.exports = {
publish: function(name, filePath, fileType, license, nsfw, socket, visitor) { publish: function(name, filePath, fileType, license, nsfw, socket, visitor) {
nsfw = (nsfw.toLowerCase() === "true");
// 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
@ -60,7 +49,7 @@ module.exports = {
.catch(function(error){ .catch(function(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", handlePublishError(error)); socket.emit("publish-failure", errorHandlers.handlePublishError(error));
deleteTemporaryFile(filePath); deleteTemporaryFile(filePath);
}); });
} }

View file

@ -1,77 +1,8 @@
var path = require('path'); var lbryApi = require('../helpers/libraries/lbryApi.js');
var axios = require('axios');
var lbryApi = require('./lbryApi');
var db = require("../models"); var db = require("../models");
function filterForFreePublicClaims(claimsListArray){ var getAllFreePublicClaims = require("../helpers/functions/getAllFreePublicClaims.js");
//console.log("claims list:", claimsListArray) var isFreePublicClaim = require("../helpers/functions/isFreePublicClaim.js");
if (!claimsListArray) {
return null;
};
var freePublicClaims = claimsListArray.filter(function(claim){
if (!claim.value){
return false;
}
return (((claim.value.stream.metadata.license.indexOf('Public Domain') != -1) || (claim.value.stream.metadata.license.indexOf('Creative Commons') != -1)) &&
(!claim.value.stream.metadata.fee || claim.value.stream.metadata.fee === 0));
});
return freePublicClaims;
}
function isFreePublicClaim(claim){
console.log(">> isFreePublicClaim? claim:", claim);
if ((claim.value.stream.metadata.license === 'Public Domain' || claim.value.stream.metadata.license === 'Creative Commons') &&
(!claim.value.stream.metadata.fee || claim.value.stream.metadata.fee.amount === 0)) {
return true;
} else {
return false;
}
}
function orderTopClaims(claimsListArray){
console.log(">> orderTopClaims");
claimsListArray.sort(function(claimA, claimB){
if (claimA.amount === claimB.amount){
return (claimA.height > claimB.height);
} else {
return (claimA.amount < claimB.amount);
}
})
return claimsListArray;
}
function getAllFreePublicClaims(claimName){
var deferred = new Promise(function(resolve, reject){
// make a call to the daemon to get the claims list
lbryApi.getClaimsList(claimName)
.then(function(data){
var claimsList = data.result.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;
}
// filter the claims to return only free, public claims
var 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;
}
// order the claims
var orderedPublicClaims = orderTopClaims(freePublicClaims);
// resolve the promise
resolve(orderedPublicClaims);
}).catch(function(error){
console.log(">> 'claim_list' error");
reject(error);
});
});
return deferred;
}
function getClaimAndHandleResponse(claimUri, resolve, reject){ function getClaimAndHandleResponse(claimUri, resolve, reject){
lbryApi.getClaim(claimUri) lbryApi.getClaim(claimUri)
@ -87,7 +18,7 @@ function getClaimAndHandleResponse(claimUri, resolve, reject){
} }
module.exports = { module.exports = {
getClaimBasedOnNameOnly: function(claimName){ getClaimByName: function(claimName){
var deferred = new Promise(function (resolve, reject){ var deferred = new Promise(function (resolve, reject){
console.log(">> lbryHelpers >> getClaim BasedOnNameOnly:", claimName); console.log(">> lbryHelpers >> getClaim BasedOnNameOnly:", claimName);
// get all free public claims // get all free public claims
@ -125,7 +56,7 @@ module.exports = {
}); });
return deferred; return deferred;
}, },
getClaimBasedOnUri: function(claimName, claimId){ getClaimByClaimId: function(claimName, claimId){
var deferred = new Promise(function (resolve, reject){ var deferred = new Promise(function (resolve, reject){
var uri = claimName + "#" + claimId; var uri = claimName + "#" + claimId;
console.log(">> lbryHelpers >> getClaimBasedOnUri:", uri); console.log(">> lbryHelpers >> getClaimBasedOnUri:", uri);
@ -167,8 +98,5 @@ module.exports = {
}); });
}); });
return deferred; return deferred;
},
getAllClaims: function(claimName){
return getAllFreePublicClaims(claimName);
} }
} }

View file

@ -0,0 +1,7 @@
var getAllFreePublicClaims = require("../helpers/functions/getAllFreePublicClaims.js");
module.exports = {
getAllClaims: function(claimName){
return getAllFreePublicClaims(claimName); // to-do: does this need to be returned?
}
}

View file

@ -0,0 +1,61 @@
var isFreePublicClaim = require("./isFreePublicClaim.js");
var lbryApi = require('../libraries/lbryApi.js');
function filterForFreePublicClaims(claimsListArray){
//console.log("claims list:", claimsListArray)
if (!claimsListArray) {
return null;
};
var freePublicClaims = claimsListArray.filter(function(claim){
if (!claim.value){
return false;
}
return (isFreePublicClaim(claim));
});
return freePublicClaims;
}
function orderTopClaims(claimsListArray){
console.log(">> orderTopClaims");
claimsListArray.sort(function(claimA, claimB){
if (claimA.amount === claimB.amount){
return (claimA.height > claimB.height);
} else {
return (claimA.amount < claimB.amount);
}
})
return claimsListArray;
}
module.exports = function(claimName){
var deferred = new Promise(function(resolve, reject){
// make a call to the daemon to get the claims list
lbryApi.getClaimsList(claimName)
.then(function(result){
var claimsList = result.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;
}
// filter the claims to return only free, public claims
var 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;
}
// order the claims
var orderedPublicClaims = orderTopClaims(freePublicClaims);
// resolve the promise
resolve(orderedPublicClaims);
}).catch(function(error){
console.log(">> 'claim_list' error");
reject(error);
});
});
return deferred;
}

View file

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

View file

@ -1,5 +1,3 @@
var path = require('path');
module.exports = { module.exports = {
handleRequestError: function(error, res) { handleRequestError: function(error, res) {
if ((error === "NO_CLAIMS") || (error === "NO_FREE_PUBLIC_CLAIMS")){ if ((error === "NO_CLAIMS") || (error === "NO_FREE_PUBLIC_CLAIMS")){
@ -11,5 +9,14 @@ module.exports = {
} else { } else {
res.status(400).send(error.toString()); res.status(400).send(error.toString());
}; };
} },
handlePublishError: function(error) {
if (error.code === "ECONNREFUSED"){
return "Connection refused. The daemon may not be running.";
} else if (error.response.data.error) {
return error.response.data.error;
} else {
return error;
};
}
} }

View file

@ -1,5 +1,5 @@
var axios = require('axios'); var axios = require('axios');
var db = require("../models"); var db = require("../../models");
module.exports = { module.exports = {
publishClaim: function(publishParams, fileType){ publishClaim: function(publishParams, fileType){
@ -9,19 +9,20 @@ module.exports = {
"method": "publish", "method": "publish",
"params": publishParams "params": publishParams
}).then(function (response) { }).then(function (response) {
console.log(">> 'publish' success", response); console.log(">> 'publish' success");
var result = response.data.result;
db.File.create({ db.File.create({
name: publishParams.name, name: publishParams.name,
claim_id: response.data.result.claim_id, claim_id: result.claim_id,
outpoint: response.data.result.outpoint, outpoint: result.txid + ":" + result.nout,
file_name: "test", file_name: "test",
file_path: publishParams.filePath, file_path: publishParams.file_path,
file_type: fileType, file_type: fileType,
nsfw: nsfw, nsfw: publishParams.metadata.nsfw,
}).catch(function(error){ }).catch(function(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(response.data.result); resolve(result);
}).catch(function(error){ }).catch(function(error){
console.log(">> 'publish' error"); console.log(">> 'publish' error");
reject(error); reject(error);
@ -36,7 +37,7 @@ module.exports = {
"method": "get", "method": "get",
"params": { "uri": uri, "timeout": 20} "params": { "uri": uri, "timeout": 20}
}).then(function (response) { }).then(function (response) {
console.log(">> 'get' success", response.data); 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 (response.data.result.error){ if (response.data.result.error){
reject(response.data.result.error); reject(response.data.result.error);
@ -45,24 +46,22 @@ module.exports = {
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
var result = response.data.result
db.File.create({ db.File.create({
name: response.data.result.name, name: result.name,
claim_id: response.data.result.claim_id, claim_id: result.claim_id,
outpoint: response.data.result.outpoint, outpoint: result.outpoint,
file_name: response.data.result.file_name, file_name: result.file_name,
file_path: response.data.result.download_path, file_path: result.download_path,
file_type: response.data.result.mime_type, file_type: result.mime_type,
nsfw: response.data.result.metadata.stream.metadata.nsfw, nsfw: result.metadata.stream.metadata.nsfw,
}).catch(function(error){ }).catch(function(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 the promise resolve(result);
resolve(response.data.result);
}).catch(function(error){ }).catch(function(error){
console.log(">> 'get' error"); console.log(">> 'get' error");
// reject the promise with an error message
reject(error); reject(error);
return;
}); });
}); });
return deferred; return deferred;
@ -75,7 +74,7 @@ module.exports = {
params: { name: claimName } params: { name: claimName }
}).then(function (response) { }).then(function (response) {
console.log(">> 'claim_list' success"); console.log(">> 'claim_list' success");
resolve(response.data); resolve(response.data.result);
}).catch(function(error){ }).catch(function(error){
console.log(">> 'claim_list' error"); console.log(">> 'claim_list' error");
reject(error); reject(error);

View file

@ -1,15 +1,17 @@
var errorHandlers = require("../helpers/libraries/errorHandlers.js");
var lbryApi = require("../helpers/libraries/lbryApi.js");
module.exports = function(app, routeHelpers, lbryApi){ module.exports = function(app){
// route to run a claim_list request on the daemon // route to run a claim_list request on the daemon
app.get("/api/claim_list/:claim", function(req, res){ app.get("/api/claim_list/:claim", function(req, res){
lbryApi.getClaimsList(req.params.claim) lbryApi.getClaimsList(req.params.claim)
.then(function(orderedFreePublicImages){ .then(function(claimsList){
console.log("/api/claim_list/:claim success."); console.log("/api/claim_list/:claim success.");
res.status(200).json(orderedFreePublicImages); res.status(200).json(claimsList);
}) })
.catch(function(error){ .catch(function(error){
console.log("/api/claim_list/:name error:", error); console.log("/api/claim_list/:name error:", error);
routeHelpers.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
@ -19,7 +21,7 @@ module.exports = function(app, routeHelpers, lbryApi){
console.log("/api/resolve/:claim success."); console.log("/api/resolve/:claim success.");
res.status(200).json(resolvedUri); res.status(200).json(resolvedUri);
}).catch(function(error){ }).catch(function(error){
routeHelpers.handleRequestError(error, res); errorHandlers.handleRequestError(error, res);
}); });
}); });

View file

@ -1,3 +1,6 @@
var errorHandlers = require("../helpers/libraries/errorHandlers.js");
var serveController = require("../controllers/serveController.js");
function serveFile(fileInfo, res){ function serveFile(fileInfo, res){
// set default options // set default options
var options = { var options = {
@ -25,7 +28,7 @@ function serveFile(fileInfo, res){
res.status(200).sendFile(fileInfo.file_path, options); res.status(200).sendFile(fileInfo.file_path, options);
} }
module.exports = function(app, routeHelpers, lbryHelpers, ua, googleAnalyticsId){ module.exports = function(app, ua, googleAnalyticsId){
// route to fetch one free public claim // route to fetch one free public claim
app.get("/:name/:claim_id", function(req, res){ app.get("/:name/:claim_id", function(req, res){
var routeString = req.params.name + "/" + req.params.claim_id; var routeString = req.params.name + "/" + req.params.claim_id;
@ -33,13 +36,13 @@ module.exports = function(app, routeHelpers, lbryHelpers, ua, googleAnalyticsId)
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);
lbryHelpers.getClaimBasedOnUri(req.params.name, req.params.claim_id) serveController.getClaimByClaimId(req.params.name, req.params.claim_id)
.then(function(fileInfo){ .then(function(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(function(error){ }).catch(function(error){
console.log("/:name/:claim_id error:", error) console.log("/:name/:claim_id error:", error)
routeHelpers.handleRequestError(error, res); errorHandlers.handleRequestError(error, res);
}); });
}); });
// route to fetch one free public claim // route to fetch one free public claim
@ -48,14 +51,13 @@ module.exports = function(app, routeHelpers, lbryHelpers, ua, googleAnalyticsId)
ua(googleAnalyticsId, {https: true}).event("Serve Route", "/name", req.params.name).send(); ua(googleAnalyticsId, {https: true}).event("Serve Route", "/name", req.params.name).send();
// begin image-serve processes // begin image-serve processes
console.log(">> GET request on /" + req.params.name); console.log(">> GET request on /" + req.params.name);
lbryHelpers.getClaimBasedOnNameOnly(req.params.name) serveController.getClaimByName(req.params.name)
.then(function(fileInfo){ .then(function(fileInfo){
console.log("/:name success.", fileInfo.file_name); console.log("/:name success.", fileInfo.file_name);
serveFile(fileInfo, res); serveFile(fileInfo, res);
}).catch(function(error){ }).catch(function(error){
console.log("/:name error:", error); console.log("/:name error:", error);
routeHelpers.handleRequestError(error, res); errorHandlers.handleRequestError(error, res);
}); });
}); });
} }

View file

@ -1,11 +1,14 @@
var errorHandlers = require("../helpers/libraries/errorHandlers.js");
var showController = require("../controllers/serveController.js");
module.exports = function(app, routeHelpers, lbryHelpers, ua, googleAnalyticsId){ module.exports = function(app, ua, googleAnalyticsId){
// route to fetch all free public claims // route to fetch all free public claims
app.get("/:name/all", function(req, res){ app.get("/:name/all", function(req, res){
console.log(">> GET request on /" + req.params.name + "/all"); console.log(">> GET request on /" + req.params.name + "/all");
// google analytics
ua(googleAnalyticsId, {https: true}).event("Show Routes", "/name/all", req.params.name + "/all").send(); ua(googleAnalyticsId, {https: true}).event("Show Routes", "/name/all", req.params.name + "/all").send();
// create promise // fetch all free public claims
lbryHelpers.getAllClaims(req.params.name) showController.getAllClaims(req.params.name)
.then(function(orderedFreePublicClaims){ .then(function(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 });
@ -13,7 +16,7 @@ module.exports = function(app, routeHelpers, lbryHelpers, ua, googleAnalyticsId)
}) })
.catch(function(error){ .catch(function(error){
console.log("/:name/all error:", error); console.log("/:name/all error:", error);
routeHelpers.handleRequestError(error, res); errorHandlers.handleRequestError(error, res);
}) })
}); });
} }

View file

@ -1,6 +1,6 @@
var socketHelpers = require('../helpers/socketHelpers.js'); var publishController = require('../controllers/publishController.js');
module.exports = function(app, path, siofu, hostedContentPath, ua, googleAnalyticsId) { module.exports = function(app, siofu, hostedContentPath, ua, googleAnalyticsId) {
var http = require('http').Server(app); var http = require('http').Server(app);
var io = require('socket.io')(http); var io = require('socket.io')(http);
@ -10,7 +10,7 @@ module.exports = function(app, path, siofu, hostedContentPath, ua, googleAnalyti
var visitor = ua(googleAnalyticsId, {https: true}); var visitor = ua(googleAnalyticsId, {https: true});
// attach upload listeners // attach upload listeners
var uploader = new siofu(); var uploader = new siofu();
uploader.dir = hostedContentPath; //path.join(__dirname, '../../Uploads'); uploader.dir = hostedContentPath;
uploader.listen(socket); uploader.listen(socket);
uploader.on("start", function(event){ uploader.on("start", function(event){
// 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
@ -26,7 +26,7 @@ module.exports = function(app, path, siofu, hostedContentPath, ua, googleAnalyti
console.log("saved ", event.file.name, "deets:", event.file); console.log("saved ", event.file.name, "deets:", event.file);
if (event.file.success){ if (event.file.success){
socket.emit("publish-status", "file upload successfully completed"); socket.emit("publish-status", "file upload successfully completed");
socketHelpers.publish(event.file.meta.name, event.file.pathName, event.file.meta.type, event.file.meta.license, event.file.meta.nsfw, socket, visitor) publishController.publish(event.file.meta.name, event.file.pathName, event.file.meta.type, event.file.meta.license, event.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")
}; };

View file

@ -9,10 +9,6 @@ var axios = require('axios');
var config = require('config'); var config = require('config');
var ua = require('universal-analytics'); var ua = require('universal-analytics');
var routeHelpers = require('./helpers/routeHelpers.js');
var lbryApi = require('./helpers/lbryApi.js');
var lbryHelpers = require('./helpers/lbryHelpers.js');
var googleAnalyticsId = config.get('AnalyticsConfig.googleId'); var googleAnalyticsId = config.get('AnalyticsConfig.googleId');
var hostedContentPath = config.get('Database.DownloadAddress'); var hostedContentPath = config.get('Database.DownloadAddress');
@ -53,13 +49,13 @@ 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, routeHelpers, lbryApi); require("./routes/api-routes.js")(app);
require("./routes/show-routes.js")(app, routeHelpers, lbryHelpers, ua, googleAnalyticsId); require("./routes/show-routes.js")(app, ua, googleAnalyticsId);
require("./routes/serve-routes.js")(app, routeHelpers, lbryHelpers, 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
var http = require("./routes/sockets-routes.js")(app, path, siofu, hostedContentPath, ua, googleAnalyticsId); var 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