cleaned up promises

This commit is contained in:
bill bittner 2017-06-02 20:56:33 -07:00
parent 4742c43135
commit 610951fe99
9 changed files with 139 additions and 141 deletions

View file

@ -57,9 +57,9 @@ function getClaimWithUri(uri, resolve, reject){
*/ */
resolve(getUriResponse.data.result.download_path); resolve(getUriResponse.data.result.download_path);
}).catch(function(getUriError){ }).catch(function(getUriError){
console.log(">> 'get' error:", getUriError.response.data); console.log(">> 'get' error:", getUriError);
// reject the promise with an error message // reject the promise with an error message
reject(getUriError.response.data.error.message); reject(getUriError);
return; return;
}); });
} }
@ -82,16 +82,10 @@ module.exports = {
console.log(">> 'publish' success"); console.log(">> 'publish' success");
// return the claim we got // return the claim we got
resolve(response.data); resolve(response.data);
return;
}).catch(function(error){ }).catch(function(error){
// receive response from LBRY // receive response from LBRY
console.log(">> 'publish' error"); console.log(">> 'publish' error");
if (error.response.data.error){
reject(error.response.data.error);
} else {
reject(error); reject(error);
}
return;
}) })
}) })
return deferred; return deferred;
@ -134,16 +128,8 @@ module.exports = {
getClaimWithUri(freePublicClaimUri, resolve, reject); getClaimWithUri(freePublicClaimUri, resolve, reject);
}) })
.catch(function(error){ .catch(function(error){
console.log(">> 'claim_list' error:", error); console.log(">> 'claim_list' error.");
// reject the promise with an approriate message
if (error.code === "ECONNREFUSED"){
reject("Connection refused. The daemon may not be running.")
} else if (error.response.data.error) {
reject(error.response.data.error);
} else {
reject(error); reject(error);
};
return;
}); });
}); });
// 3. return the promise // 3. return the promise
@ -200,14 +186,8 @@ module.exports = {
*/ */
resolve(orderedPublicClaims); resolve(orderedPublicClaims);
}).catch(function(error){ }).catch(function(error){
console.log(">> 'claim_list' error:", error); console.log(">> 'claim_list' error");
if (error.code === "ECONNREFUSED"){
reject("Connection refused. The daemon may not be running.")
} else if (error.response.data.error) {
reject(error.response.data.error);
} else {
reject(error); reject(error);
};
}) })
}); });
return deferred; return deferred;

0
helpers/routeHelpers.js Normal file
View file

55
helpers/socketHelpers.js Normal file
View file

@ -0,0 +1,55 @@
//var fs = require('fs');
var lbryApi = require('../helpers/lbryApi.js');
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) {
var publishParams = {
"name": name,
"file_path": filepath,
"bid": 0.1,
"metadata": {
"description": name + " published via spee.ch",
"title": name,
"author": "spee.ch",
"language": "en",
"license": license,
"nsfw": (nsfw.toLowerCase() === "true")
}
};
return publishParams;
}
function deleteTemporaryFile(filepath, name){
fs.unlink(filepath, function(err){
if (err) throw err;
console.log('successfully deleted ' + name);
});
}
module.exports = {
publish: function(name, filepath, license, nsfw, socket) {
// update the client
socket.emit("publish-status", "Your image is being published (this might take a second)...");
// create the publish object
var publishParams = createPublishParams(name, filepath, license, nsfw);
// get a promise to publish
lbryApi.publishClaim(publishParams)
.then(function(data){
console.log("publish promise success. Tx info:", data)
socket.emit("publish-complete", data);
deleteTemporaryFile(filepath, name);
})
.catch(function(error){
console.log("error:", error);
socket.emit("publish-status", handlePublishError(error));
deleteTemporaryFile(filepath, name);
});
}
}

View file

Before

Width:  |  Height:  |  Size: 180 B

After

Width:  |  Height:  |  Size: 180 B

View file

@ -0,0 +1,2 @@

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

View file

@ -9,7 +9,8 @@
<body> <body>
<h1>spee.ch</h1> <h1>spee.ch</h1>
<p>spee.ch is a single-serving site that reads and publishes images to and from the <a href="https://lbry.io">LBRY</a> blockchain.</p> <p>spee.ch is a single-serving site that reads and publishes images to and from the <a href="https://lbry.io">LBRY</a> blockchain.</p>
<h3>Examples:</h3>
<h2>Examples:</h2>
<ul> <ul>
<li><a href="/coconuts">spee.ch/coconuts</a></li> <li><a href="/coconuts">spee.ch/coconuts</a></li>
<li><a href="/wood">spee.ch/wood</a></li> <li><a href="/wood">spee.ch/wood</a></li>
@ -17,7 +18,8 @@
<li><a href="/doitlive/all">spee.ch/doitlive/all</a></li> <li><a href="/doitlive/all">spee.ch/doitlive/all</a></li>
<li><a href="/doitlive/ca3023187e901df9e9aabd95d6ae09b6cc69b3f0">spee.ch/doitlive/ca3023187e901df9e9aabd95d6ae09b6cc69b3f0</a></li> <li><a href="/doitlive/ca3023187e901df9e9aabd95d6ae09b6cc69b3f0">spee.ch/doitlive/ca3023187e901df9e9aabd95d6ae09b6cc69b3f0</a></li>
</ul> </ul>
<h3>Publish Your Own</h3>
<h2>Publish Your Own</h2>
<div id="publish"> <div id="publish">
<form id="publish-form" action="" method="" enctype="multipart/form-data"> <form id="publish-form" action="" method="" enctype="multipart/form-data">
<input type="file" id="siofu_input" name="file" accept="video/*,image/*" onchange="previewFile()" enctype="multipart/form-data"/> <input type="file" id="siofu_input" name="file" accept="video/*,image/*" onchange="previewFile()" enctype="multipart/form-data"/>
@ -38,15 +40,14 @@
<br/> <br/>
<button id="publish-submit">Submit</button> <button id="publish-submit">Submit</button>
</form> </form>
<p id="upload-status"></p>
</div> </div>
<h3>Help Wanted!</h3> <h2>Help Wanted!</h2>
<p>If you would like to help make spee.ch amazing, join our slack channel.</p> <p>If you would like to help make spee.ch amazing, join our slack channel.</p>
<p>We are currently in need of a designer to help with styling spee.ch's front end, but all help is welcome!</p> <p>We are currently in need of a designer to help with styling spee.ch's front end, but all help is welcome!</p>
<h3>Help</h3> <h2>Documentation</h2>
<h4>Site Navigation</h4> <h3>Site Navigation</h3>
<ul> <ul>
<li><strong><a href="/">spee.ch</a></strong>. <li><strong><a href="/">spee.ch</a></strong>.
<ul> <ul>
@ -72,7 +73,7 @@
</ul> </ul>
</li> </li>
</ul> </ul>
<h4>API</h4> <h3>API</h3>
<p>Note: these are being used for testing durring spee.ch development and may not be maintained</p> <p>Note: these are being used for testing durring spee.ch development and may not be maintained</p>
<ul> <ul>
<li>A GET request to <strong>spee.ch/claim_list/&ltthe name of the claim&gt</strong> <li>A GET request to <strong>spee.ch/claim_list/&ltthe name of the claim&gt</strong>
@ -86,10 +87,29 @@
<script src="/socket.io/socket.io.js"></script> <script src="/socket.io/socket.io.js"></script>
<script src="/siofu/client.js"></script> <script src="/siofu/client.js"></script>
<script> <script>
// define global variables
var socket = io(); var socket = io();
var uploader = new SocketIOFileUpload(socket); var uploader = new SocketIOFileUpload(socket);
// function to handle image preview
function createProgressBar(element, size){
var x = 1;
var adder = 1;
function addOne(){
var bars = '<h3>|';
for (var i = 0; i < x; i++){
bars += ' | ';
}
bars += '</h3>';
element.innerHTML = bars;
if (x === size){
adder = -1;
} else if ( x === 0){
adder = 1;
}
x += adder;
};
setInterval(addOne, 300);
}
function previewFile(){ function previewFile(){
var preview = document.querySelector('img'); //selects the query named img var preview = document.querySelector('img'); //selects the query named img
var claimName = document.querySelector('input[name=name]'); var claimName = document.querySelector('input[name=name]');
@ -106,19 +126,17 @@
preview.src = ""; preview.src = "";
}; };
} }
// helper function to update status
function updatePublishStatus(msg){ function updatePublishStatus(msg){
document.getElementById("publish").innerHTML = msg; document.getElementById("publish-status").innerHTML = msg;
} }
// call the previewFile function
previewFile(); uploader.listenOnSubmit(document.getElementById("publish-submit"), document.getElementById("siofu_input"));
// prevent default on the submit button
document.getElementById("publish-submit").addEventListener("click", function(event){ document.getElementById("publish-submit").addEventListener("click", function(event){
event.preventDefault(); event.preventDefault();
}) })
// upload through the socket
uploader.listenOnSubmit(document.getElementById("publish-submit"), document.getElementById("siofu_input"));
// add listeners to the uploader
uploader.addEventListener("start", function(event){ uploader.addEventListener("start", function(event){
var name = document.getElementById('publish-name').value; var name = document.getElementById('publish-name').value;
var license = document.getElementById('publish-license').value; var license = document.getElementById('publish-license').value;
@ -127,12 +145,17 @@
event.file.meta.name = name; event.file.meta.name = name;
event.file.meta.license = license; event.file.meta.license = license;
event.file.meta.nsfw = nsfw; event.file.meta.nsfw = nsfw;
// set the html of the publish area
document.getElementById("publish").innerHTML = '<div id="publish-status"></div><div id="progress-bar"></div>';
// start the progress bar
createProgressBar(document.getElementById("progress-bar"), 12);
}); });
uploader.addEventListener("progress", function(event){ uploader.addEventListener("progress", function(event){
var percent = event.bytesLoaded / event.file.size * 100; var percent = event.bytesLoaded / event.file.size * 100;
updatePublishStatus("File is " + percent.toFixed(2) + "% loaded to the server"); updatePublishStatus("File is " + percent.toFixed(2) + "% loaded to the server");
}) })
// add listener for publish status updates
socket.on("publish-status", function(msg){ socket.on("publish-status", function(msg){
updatePublishStatus(msg); updatePublishStatus(msg);
}) })

View file

@ -6,36 +6,37 @@ var multipartMiddleware = multipart();
var lbryApi = require('../helpers/lbryApi.js'); var lbryApi = require('../helpers/lbryApi.js');
var queueApi = require('../helpers/queueApi.js'); var queueApi = require('../helpers/queueApi.js');
function handleRequestError(error, res) {
if ((error === "NO_CLAIMS") || (error === "NO_FREE_PUBLIC_CLAIMS")){
res.status(307).sendFile(path.join(__dirname, '../public', 'noClaims.html'));
} else if (error === "Invalid URI") {
res.status(400).sendFile(path.join(__dirname, '../public', 'invalidUri.html'));
} else {
res.status(400).send(error);
};
}
// routes to export // routes to export
module.exports = function(app){ module.exports = function(app){
// route to fetch one free public claim // route to fetch one free public claim
app.get("/favicon.ico", function(req, res){ app.get("/favicon.ico", function(req, res){
console.log(" >> GET request on favicon.ico"); console.log(" >> GET request on favicon.ico");
res.sendFile(path.join(__dirname, '../public', 'favicon.ico')); res.sendFile(path.join(__dirname, '../public/assets/img', 'favicon.ico'));
}); });
// route to fetch one free public claim // route to fetch one free public claim
app.get("/:name/all", function(req, res){ app.get("/:name/all", function(req, res){
var name = req.params.name; console.log(">> GET request on /" + req.params.name + " (all)");
console.log(">> GET request on /" + name + " (all)");
// create promise // create promise
var promise = lbryApi.getAllClaims(name); lbryApi.getAllClaims(req.params.name)
// handle the promise resolve .then(function(orderedFreePublicClaims){
promise.then(function(orderedFreePublicClaims){ console.log("/:name/all success.")
console.log("/name/all promise success.")
res.status(200).send(orderedFreePublicClaims); res.status(200).send(orderedFreePublicClaims);
return; return;
}) })
// handle the promise rejection
.catch(function(error){ .catch(function(error){
console.log("/name/all/ promise error:", error); console.log("/:name/all error:", error);
// handle the error handleRequestError(error, res);
if ((error === "NO_CLAIMS") || (error === "NO_FREE_PUBLIC_CLAIMS")){
res.status(307).sendFile(path.join(__dirname, '../public', 'noClaims.html'));
return;
} else {
res.status(400).send(error);
return;
};
}) })
}); });
// route to fetch one free public claim // route to fetch one free public claim
@ -43,48 +44,28 @@ module.exports = function(app){
var uri = req.params.name + "#" + req.params.claim_id; var uri = req.params.name + "#" + req.params.claim_id;
console.log(">> GET request on /" + uri); console.log(">> GET request on /" + uri);
// create promise // create promise
var promise = lbryApi.getClaimBasedOnUri(uri); lbryApi.getClaimBasedOnUri(uri)
// handle the promise resolve .then(function(filePath){
promise.then(function(filePath){ console.log("/:name/:claim_id success.");
console.log("/name/claim_id promise success - filepath:", filePath)
res.status(200).sendFile(filePath); res.status(200).sendFile(filePath);
return;
}) })
// handle the promise rejection
.catch(function(error){ .catch(function(error){
console.log("/name/claim_id/ promise error:", error) console.log("/:name/:claim_id error.")
// handle the error handleRequestError(error, res);
if (error === "Invalid URI") {
res.status(400).sendFile(path.join(__dirname, '../public', 'invalidUri.html'));
return;
} else {
res.status(400).send(error);
return;
};
}); });
}); });
// route to fetch one free public claim // route to fetch one free public claim
app.get("/:name", function(req, res){ app.get("/:name", function(req, res){
var name = req.params.name; console.log(">> GET request on /" + req.params.name);
console.log(">> GET request on /" + name);
// create promise // create promise
var promise = lbryApi.getClaimBasedOnNameOnly(name); lbryApi.getClaimBasedOnNameOnly(req.params.name)
// handle the promise resolve .then(function(filePath){
promise.then(function(filePath){ console.log("/:name success.")
console.log("/name promise success - filepath:", filePath)
res.status(200).sendFile(filePath); res.status(200).sendFile(filePath);
return; }).catch(function(error){
}) console.log("/:name error.");
// handle the promise rejection handleRequestError(error, res);
.catch(function(error){
console.log("/name/ promise error:", error);
// handle the error
if ((error === "NO_CLAIMS") || (error === "NO_FREE_PUBLIC_CLAIMS")){
res.status(307).sendFile(path.join(__dirname, '../public', 'noClaims.html'));
return;
};
res.status(400).send(error);
}); });
}); });

View file

@ -6,56 +6,14 @@ module.exports = function(app) {
var lbryApi = require('../helpers/lbryApi.js'); var lbryApi = require('../helpers/lbryApi.js');
var queueApi = require('../helpers/queueApi.js'); var queueApi = require('../helpers/queueApi.js');
var siofu = require("socketio-file-upload"); var siofu = require("socketio-file-upload");
var socketHelpers = require('../helpers/socketHelpers.js');
// functions to create a publishing object
function createPublishParams(name, filepath, license, nsfw){
var publishParams = {
"name": name,
"file_path": filepath,
"bid": 0.1,
"metadata": {
"description": name + " published via spee.ch",
"title": name,
"author": "spee.ch",
"language": "en",
"license": license,
"nsfw": (nsfw.toLowerCase() === "true")
}
};
return publishParams;
}
// publish an image to lbry
function publish(name, filepath, license, nsfw, socket){
// update the client
socket.emit("publish-status", "Your image is being published (this might take a second)...");
// create the publish object
var publishParams = createPublishParams(name, filepath, license, nsfw);
// get a promise to publish
var promise = lbryApi.publishClaim(publishParams);
// handle promise
promise.then(function(data){
console.log("publish promise success. Tx info:", data)
socket.emit("publish-complete", data);
/*
note: remember to delete the local file
*/
})
.catch(function(error){
console.log("error:", error);
socket.emit("publish-status", "publish failed");
/*
note: remember to delete the local file
*/
});
};
io.on('connection', function(socket){ io.on('connection', function(socket){
console.log('a user connected'); console.log('a user connected');
// listener for uploader // attach upload listeners
var uploader = new siofu(); var uploader = new siofu();
uploader.dir = path.join(__dirname, '../../Uploads'); uploader.dir = path.join(__dirname, '../../Uploads');
uploader.listen(socket); uploader.listen(socket);
// attach upload listeners
uploader.on("error", function(event){ uploader.on("error", function(event){
console.log("an error occured while uploading", event.error); console.log("an error occured while uploading", event.error);
socket.emit("publish-status", event.error) socket.emit("publish-status", event.error)
@ -64,12 +22,11 @@ module.exports = function(app) {
console.log("saved " + event.file.name); console.log("saved " + event.file.name);
if (event.file.success){ if (event.file.success){
socket.emit("publish-status", "file upload successfully completed"); socket.emit("publish-status", "file upload successfully completed");
publish(event.file.meta.name, event.file.pathName, event.file.meta.license,event.file.meta.nsfw, socket) socketHelpers.publish(event.file.meta.name, event.file.pathName, event.file.meta.license,event.file.meta.nsfw, socket)
} else { } else {
socket.emit("publish-status", "file saved, but with errors") socket.emit("publish-status", "file saved, but with errors")
}; };
}); });
// handle disconnect // handle disconnect
socket.on('disconnect', function(){ socket.on('disconnect', function(){
console.log('user disconnected'); console.log('user disconnected');