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);
}).catch(function(getUriError){
console.log(">> 'get' error:", getUriError.response.data);
console.log(">> 'get' error:", getUriError);
// reject the promise with an error message
reject(getUriError.response.data.error.message);
reject(getUriError);
return;
});
}
@ -82,16 +82,10 @@ module.exports = {
console.log(">> 'publish' success");
// return the claim we got
resolve(response.data);
return;
}).catch(function(error){
// receive response from LBRY
console.log(">> 'publish' error");
if (error.response.data.error){
reject(error.response.data.error);
} else {
reject(error);
}
return;
reject(error);
})
})
return deferred;
@ -134,16 +128,8 @@ module.exports = {
getClaimWithUri(freePublicClaimUri, resolve, reject);
})
.catch(function(error){
console.log(">> 'claim_list' error:", 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);
};
return;
console.log(">> 'claim_list' error.");
reject(error);
});
});
// 3. return the promise
@ -200,14 +186,8 @@ module.exports = {
*/
resolve(orderedPublicClaims);
}).catch(function(error){
console.log(">> 'claim_list' error:", 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);
};
console.log(">> 'claim_list' error");
reject(error);
})
});
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>
<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>
<h3>Examples:</h3>
<h2>Examples:</h2>
<ul>
<li><a href="/coconuts">spee.ch/coconuts</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/ca3023187e901df9e9aabd95d6ae09b6cc69b3f0">spee.ch/doitlive/ca3023187e901df9e9aabd95d6ae09b6cc69b3f0</a></li>
</ul>
<h3>Publish Your Own</h3>
<h2>Publish Your Own</h2>
<div id="publish">
<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"/>
@ -38,15 +40,14 @@
<br/>
<button id="publish-submit">Submit</button>
</form>
<p id="upload-status"></p>
</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>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>
<h4>Site Navigation</h4>
<h2>Documentation</h2>
<h3>Site Navigation</h3>
<ul>
<li><strong><a href="/">spee.ch</a></strong>.
<ul>
@ -72,7 +73,7 @@
</ul>
</li>
</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>
<ul>
<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="/siofu/client.js"></script>
<script>
// define global variables
var socket = io();
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(){
var preview = document.querySelector('img'); //selects the query named img
var claimName = document.querySelector('input[name=name]');
@ -106,19 +126,17 @@
preview.src = "";
};
}
// helper function to update status
function updatePublishStatus(msg){
document.getElementById("publish").innerHTML = msg;
document.getElementById("publish-status").innerHTML = msg;
}
// call the previewFile function
previewFile();
// prevent default on the submit button
uploader.listenOnSubmit(document.getElementById("publish-submit"), document.getElementById("siofu_input"));
document.getElementById("publish-submit").addEventListener("click", function(event){
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){
var name = document.getElementById('publish-name').value;
var license = document.getElementById('publish-license').value;
@ -127,12 +145,17 @@
event.file.meta.name = name;
event.file.meta.license = license;
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){
var percent = event.bytesLoaded / event.file.size * 100;
updatePublishStatus("File is " + percent.toFixed(2) + "% loaded to the server");
})
// add listener for publish status updates
socket.on("publish-status", function(msg){
updatePublishStatus(msg);
})

View file

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

View file

@ -6,56 +6,14 @@ module.exports = function(app) {
var lbryApi = require('../helpers/lbryApi.js');
var queueApi = require('../helpers/queueApi.js');
var siofu = require("socketio-file-upload");
// 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
*/
});
};
var socketHelpers = require('../helpers/socketHelpers.js');
io.on('connection', function(socket){
console.log('a user connected');
// listener for uploader
// attach upload listeners
var uploader = new siofu();
uploader.dir = path.join(__dirname, '../../Uploads');
uploader.listen(socket);
// attach upload listeners
uploader.on("error", function(event){
console.log("an error occured while uploading", event.error);
socket.emit("publish-status", event.error)
@ -64,12 +22,11 @@ module.exports = function(app) {
console.log("saved " + event.file.name);
if (event.file.success){
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 {
socket.emit("publish-status", "file saved, but with errors")
};
});
// handle disconnect
socket.on('disconnect', function(){
console.log('user disconnected');