DRY routes, error handling, links on publish #18

Merged
bones7242 merged 6 commits from master into master 2017-06-03 10:25:53 +02:00
14 changed files with 247 additions and 331 deletions

View file

@ -1,10 +1,7 @@
// load dependencies
var path = require('path'); var path = require('path');
var axios = require('axios'); var axios = require('axios');
// helper function to filter an array of claims for only free, public claims
function filterForFreePublicClaims(claimsListArray){ function filterForFreePublicClaims(claimsListArray){
//console.log(">> filterForFreePublicClaims, claimsListArray:", claimsListArray);
if (!claimsListArray) { if (!claimsListArray) {
return null; return null;
}; };
@ -14,7 +11,7 @@ function filterForFreePublicClaims(claimsListArray){
}); });
return freePublicClaims; return freePublicClaims;
} }
// helper function to decide if a claim is free and public
function isFreePublicClaim(claim){ function isFreePublicClaim(claim){
console.log(">> isFreePublicClaim, claim:", claim); console.log(">> isFreePublicClaim, claim:", claim);
if ((claim.value.stream.metadata.license === 'Public Domain' || claim.value.stream.metadata.license === 'Creative Commons') && if ((claim.value.stream.metadata.license === 'Public Domain' || claim.value.stream.metadata.license === 'Creative Commons') &&
@ -24,7 +21,7 @@ function isFreePublicClaim(claim){
return false; return false;
} }
} }
// helper function to order a set of claims
function orderTopClaims(claimsListArray){ function orderTopClaims(claimsListArray){
console.log(">> orderTopClaims, claimsListArray:"); console.log(">> orderTopClaims, claimsListArray:");
claimsListArray.sort(function(claimA, claimB){ claimsListArray.sort(function(claimA, claimB){
@ -46,8 +43,8 @@ function getClaimWithUri(uri, resolve, reject){
).then(function (getUriResponse) { ).then(function (getUriResponse) {
console.log(">> 'get claim' success..."); console.log(">> 'get claim' success...");
//check to make sure the daemon didn't just time out //check to make sure the daemon didn't just time out
if (getUriResponse.data.result.error === "Timeout"){ if (getUriResponse.data.result.error){
reject("get request to lbry daemon timed out"); reject(getUriResponse.data.result.error);
} }
console.log(">> response data:", getUriResponse.data); console.log(">> response data:", getUriResponse.data);
console.log(">> dl path =", getUriResponse.data.result.download_path) console.log(">> dl path =", getUriResponse.data.result.download_path)
@ -57,9 +54,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.");
// 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 +79,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);
reject(error.response.data.error);
} else {
reject(error);
}
return;
}) })
}) })
return deferred; return deferred;
@ -134,16 +125,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 reject(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);
};
return;
}); });
}); });
// 3. return the promise // 3. return the promise
@ -200,14 +183,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(error);
reject("Connection refused. The daemon may not be running.")
} else if (error.response.data.error) {
reject(error.response.data.error);
} else {
reject(error);
};
}) })
}); });
return deferred; return deferred;

View file

@ -1,22 +0,0 @@
// require amqp library
var amqp = require('amqplib/callback_api');
module.exports = {
addNewTaskToQueue: function(task){
// connect to RabbitMQ server
amqp.connect('amqp://localhost', function(err, conn) {
// create a channel
conn.createChannel(function(err, ch) {
var q = 'task_queue2'; // declaring a que is idempotent (it will only be created if it doesnt already exist)
var msg = task || "request received with no task!";
// declare a queue
ch.assertQueue(q, {durable: true});
// publish a message to the queue
ch.sendToQueue(q, new Buffer.from(msg), {persistent: true});
console.log(` [x] Sent '${msg}' to ${q}`);
});
// close the connection and exit
setTimeout(function() {conn.close() }, 500);
});
}
}

15
helpers/routeHelpers.js Normal file
View file

@ -0,0 +1,15 @@
var path = require('path');
module.exports = {
handleRequestError: function(error, res) {
if ((error === "NO_CLAIMS") || (error === "NO_FREE_PUBLIC_CLAIMS")){
res.status(307).sendFile(path.join(__dirname, '../public', 'noClaims.html'));
} else if (error.response){
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.");
} else {
res.status(400).send(error.toString());
};
}
}

57
helpers/socketHelpers.js Normal file
View file

@ -0,0 +1,57 @@
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) {
fs.unlink(filepath, function(err) {
if (err) throw err;
console.log('successfully deleted ' + filepath);
});
}
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", {name: name, result: data.result});
deleteTemporaryFile(filepath);
})
.catch(function(error){
console.log("error:", error);
socket.emit("publish-failure", handlePublishError(error));
deleteTemporaryFile(filepath);
});
}
}

View file

@ -23,10 +23,8 @@
}, },
"homepage": "https://github.com/billbitt/spee.ch-backend#readme", "homepage": "https://github.com/billbitt/spee.ch-backend#readme",
"dependencies": { "dependencies": {
"amqplib": "^0.5.1",
"axios": "^0.16.1", "axios": "^0.16.1",
"body-parser": "^1.17.1", "body-parser": "^1.17.1",
"connect-multiparty": "^2.0.0",
"express": "^4.15.2", "express": "^4.15.2",
"nodemon": "^1.11.0", "nodemon": "^1.11.0",
"socket.io": "^2.0.1", "socket.io": "^2.0.1",

View file

View file

Before

Width:  |  Height:  |  Size: 180 B

After

Width:  |  Height:  |  Size: 180 B

View file

@ -1,36 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Spee.ch Claim</title>
</head>
<body>
<div id="image">
<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>Status:</h3>
<p id="status">Your image is being retrieved</p>
</div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
var url = document.URL.substring(document.URL.indexOf('spee.ch/') + 8);
// request the claim through the socket
socket.emit("claim-request", url);
// listen for updates
socket.on("claim-update", function(data){
console.log("data:", data);
document.getElementById("status").innerHTML = data;
})
// receive the claim through the socket
socket.on("claim-send", function(data){
if (data.image) {
var base64Image = 'data:image/jpeg;base64,' + data.buffer;
document.getElementById("image").innerHTML = '<img src="' + base64Image + '"/>';
}
})
</script>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

View file

@ -5,91 +5,128 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Spee.ch</title> <title>Spee.ch</title>
<link rel="stylesheet" type="text/css" href="/assets/css/style.css">
</head> </head>
<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> <section>
<ul> <h2>Examples:</h2>
<li><a href="/coconuts">spee.ch/coconuts</a></li> <ul>
<li><a href="/wood">spee.ch/wood</a></li> <li><a href="/coconuts">spee.ch/coconuts</a></li>
<li><a href="/doitlive">spee.ch/doitlive</a></li> <li><a href="/wood">spee.ch/wood</a></li>
<li><a href="/doitlive/all">spee.ch/doitlive/all</a></li> <li><a href="/doitlive">spee.ch/doitlive</a></li>
<li><a href="/doitlive/ca3023187e901df9e9aabd95d6ae09b6cc69b3f0">spee.ch/doitlive/ca3023187e901df9e9aabd95d6ae09b6cc69b3f0</a></li> <li><a href="/doitlive/all">spee.ch/doitlive/all</a></li>
</ul> <li><a href="/doitlive/ca3023187e901df9e9aabd95d6ae09b6cc69b3f0">spee.ch/doitlive/ca3023187e901df9e9aabd95d6ae09b6cc69b3f0</a></li>
<h3>Publish Your Own</h3> </ul>
<div id="publish"> </section>
<form id="publish-form" action="" method="" enctype="multipart/form-data"> <section>
<input type="file" id="siofu_input" name="file" accept="video/*,image/*" onchange="previewFile()" enctype="multipart/form-data"/> <h2>Publish Your Own</h2>
<br/> <div id="publish">
<img id="image-preview" src="" height="200" alt="Image preview..."/> <form id="publish-form" action="" method="" enctype="multipart/form-data">
<br/> <input type="file" id="siofu_input" name="file" accept="video/*,image/*" onchange="previewFile()" enctype="multipart/form-data"/>
Name: <input type="text" id="publish-name" name="name" value="name"/> <br/>
<br/> <img id="image-preview" src="" height="200" alt="Image preview..."/>
License: <select type="text" id="publish-license" name="license" value="license"> <br/>
<option value="Public Domain">Public Domain</option> Name: <input type="text" id="publish-name" name="name" value="name"/>
<option value="Creative Commons">Creative Commons</option> <br/>
</select> License: <select type="text" id="publish-license" name="license" value="license">
<br/> <option value="Public Domain">Public Domain</option>
NSFW: <select type="text" id="publish-nsfw" name="nsfw" value="false"> <option value="Creative Commons">Creative Commons</option>
<option value="false">False</option> </select>
<option value="true">True</option> <br/>
</select> NSFW: <select type="text" id="publish-nsfw" name="nsfw" value="false">
<br/> <option value="false">False</option>
<button id="publish-submit">Submit</button> <option value="true">True</option>
</form> </select>
<p id="upload-status"></p> <br/>
</div> <button id="publish-submit">Submit</button>
</form>
<h3>Help Wanted!</h3> </div>
<p>If you would like to help make spee.ch amazing, join our slack channel.</p> </section>
<p>We are currently in need of a designer to help with styling spee.ch's front end, but all help is welcome!</p> <section>
<h2>Help Wanted!</h2>
<h3>Help</h3> <p>If you would like to help make spee.ch amazing, join our slack channel.</p>
<h4>Site Navigation</h4> <p>We are currently in need of a designer to help with styling spee.ch's front end, but all help is welcome!</p>
<ul> </section>
<li><strong><a href="/">spee.ch</a></strong>. <section>
<ul> <h2>Documentation</h2>
<li>To publish a file, navigate to the homepage.</li> <h3>Site Navigation</h3>
</ul> <ul>
</li> <li><strong><a href="/">spee.ch</a></strong>.
<li><strong>spee.ch/&ltthe name of the claim&gt</strong> <ul>
<ul> <li>To publish a file, navigate to the homepage.</li>
<li>To view the file with the largest bid at a claim.</li> </ul>
<li>E.g. <a href="/doitlive">spee.ch/doitlive</a>.</li> </li>
</ul> <li><strong>spee.ch/&ltthe name of the claim&gt</strong>
</li> <ul>
<li><strong>spee.ch/&lt the name of the claim &gt/&lt the claim_id &gt</strong> <li>To view the file with the largest bid at a claim.</li>
<ul> <li>E.g. <a href="/doitlive">spee.ch/doitlive</a>.</li>
<li>To view a specific file at a claim</li> </ul>
<li>E.g. <a href="/doitlive/c496c8c55ed79816fec39e36a78645aa4458edb5">spee.ch/doitlive/c496c8c55ed79816fec39e36a78645aa4458edb5</a></li> </li>
</ul> <li><strong>spee.ch/&lt the name of the claim &gt/&lt the claim_id &gt</strong>
</li> <ul>
<li><strong>spee.ch/&ltthe name of the claim&gt/all</strong> <li>To view a specific file at a claim</li>
<ul> <li>E.g. <a href="/doitlive/c496c8c55ed79816fec39e36a78645aa4458edb5">spee.ch/doitlive/c496c8c55ed79816fec39e36a78645aa4458edb5</a></li>
<li>To view a batch of files at a claim</li> </ul>
<li>E.g. <a href="/doitlive/all">spee.ch/doitlive/all</a></li> </li>
</ul> <li><strong>spee.ch/&ltthe name of the claim&gt/all</strong>
</li> <ul>
</ul> <li>To view a batch of files at a claim</li>
<h4>API</h4> <li>E.g. <a href="/doitlive/all">spee.ch/doitlive/all</a></li>
<p>Note: these are being used for testing durring spee.ch development and may not be maintained</p> </ul>
<ul> </li>
<li>A GET request to <strong>spee.ch/claim_list/&ltthe name of the claim&gt</strong> </ul>
<ul> <h3>API</h3>
<li>Will return the claim_list for the claim in json format. </li> <p>Note: these are being used for testing durring spee.ch development and may not be maintained</p>
<li>E.g. <a href="/claim_list/doitlive">spee.ch/claim_list/doitlive</a></li> <ul>
</ul> <li>A GET request to <strong>spee.ch/claim_list/&ltthe name of the claim&gt</strong>
</li> <ul>
</ul> <li>Will return the claim_list for the claim in json format. </li>
<li>E.g. <a href="/claim_list/doitlive">spee.ch/claim_list/doitlive</a></li>
</ul>
</li>
</ul>
</section>
<section>
<h2>Links</h2>
<a href="https://github.com/lbryio/spee.ch">github</a>
<a href="https://lbry.io/">lbry</a>
<a href="https://lbry.slack.com">slack</a>
</section>
<section>
<h2>Bugs</h2>
<p>Spee.ch is young and under continuous development so it will have bugs. Please leave an issue on our <a href="https://github.com/lbryio/spee.ch">github</a> if you experience a problem or have suggestions.</p>
<br>&nbsp;.w.
<br>(o|o)
<br>&nbsp;&nbsp;`'`
</section>
<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 = '<p>|';
for (var i = 0; i < x; i++){
bars += ' | ';
}
bars += '</p>';
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]');
@ -97,28 +134,25 @@
var previewReader = new FileReader(); var previewReader = new FileReader();
previewReader.onloadend = function () { previewReader.onloadend = function () {
preview.src = previewReader.result; preview.src = previewReader.result;
} };
if (selectedFile) { if (selectedFile) {
previewReader.readAsDataURL(selectedFile); // reads the data and sets the img src previewReader.readAsDataURL(selectedFile); // reads the data and sets the img src
claimName.value = selectedFile.name.substring(0, selectedFile.name.indexOf(".")); claimName.value = selectedFile.name.substring(0, selectedFile.name.indexOf("."));
} else { } else {
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,25 +161,37 @@
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);
}) })
socket.on("publish-failure", function(msg){
document.getElementById("publish").innerHTML = `<p>${msg}</p><p> --(✖╭╮✖)→ </p>`;
})
socket.on("publish-complete", function(msg){ socket.on("publish-complete", function(msg){
console.log("publish complete", msg); console.log("publish complete", msg);
var publishResults = `<p>You're publish is complete!</p>`; var publishResults = `<p>You're publish is complete!</p>`;
publishResults += `<p>The Claim ID is: ${msg.result.claim_id}</p>`; publishResults += `<p>Your Claim ID is: ${msg.result.claim_id}</p>`;
publishResults += `<p>The TX ID is: <a href="https://explorer.lbry.io/#!/transaction?id=${msg.result.txid}">${msg.result.txid}</a></p>`; publishResults += `<p>Your Transaction ID is: <a href="https://explorer.lbry.io/#!/transaction?id=${msg.result.txid}">${msg.result.txid}</a></p>`;
publishResults += `<p>Note: the transaction still needs to be published by the network. Click the tx id link to view the tx on the blockchain explorer</p>` publishResults += `<p>Here is a link to the claim where your asset was published: <a href="https://spee.ch/${msg.name}">spee.ch/${msg.name}</a></p>`;
publishResults += `<p><a href="/">Reload the page to publish another (fancy button coming soon)</a></p>`; publishResults += `<p>Here is a direct link to your asset: <a href="https://spee.ch/${msg.name}/${msg.result.claim_id}">spee.ch/${msg.name}/${msg.result.claim_id}</a></p>`;
publishResults += `<p><i>NOTE: the transaction still needs to be mined by the network before you can access it! This may take a few minutes. To to view the transaction on the blockchain explorer click the Transaction ID link above.</i></p>`
publishResults += `<p><a href="/">Reload the page to publish another</a></p>`;
document.getElementById("publish").innerHTML = publishResults; document.getElementById("publish").innerHTML = publishResults;
}) })
</script> </script>
</body> </body>
</html> </html>

View file

@ -1,11 +1,7 @@
// require dependencies
var path = require('path'); var path = require('path');
var axios = require('axios'); var axios = require('axios');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
// import helpers
var lbryApi = require('../helpers/lbryApi.js'); var lbryApi = require('../helpers/lbryApi.js');
var queueApi = require('../helpers/queueApi.js');
module.exports = function(app){ module.exports = function(app){
// route to return claim list in json // route to return claim list in json

View file

@ -1,41 +1,26 @@
// load dependencies
var path = require('path'); var path = require('path');
var multipart = require('connect-multiparty'); var routeHelpers = require('../helpers/routeHelpers.js');
var multipartMiddleware = multipart();
// load helpers
var lbryApi = require('../helpers/lbryApi.js'); var lbryApi = require('../helpers/lbryApi.js');
var queueApi = require('../helpers/queueApi.js');
// 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 routeHelpers.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,56 +28,33 @@ 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 routeHelpers.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 routeHelpers.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);
}); });
}); });
// route for the home page // route for the home page
app.get("/", function(req, res){ app.get("/", function(req, res){
res.status(200).sendFile(path.join(__dirname, '../public', 'index.html')); res.status(200).sendFile(path.join(__dirname, '../public', 'index.html'));
}); });
// 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("*", function(req, res){ app.use("*", function(req, res){
res.status(404).sendFile(path.join(__dirname, '../public', 'fourOhfour.html')); res.status(404).sendFile(path.join(__dirname, '../public', 'fourOhfour.html'));

View file

@ -1,61 +1,16 @@
module.exports = function(app) { module.exports = function(app) {
var http = require('http').Server(app); var http = require('http').Server(app);
var io = require('socket.io')(http); var io = require('socket.io')(http);
var fs = require('fs');
var path = require('path'); var path = require('path');
var lbryApi = require('../helpers/lbryApi.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 +19,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-failure", "file uploaded, but with errors")
}; };
}); });
// handle disconnect // handle disconnect
socket.on('disconnect', function(){ socket.on('disconnect', function(){
console.log('user disconnected'); console.log('user disconnected');

View file

@ -1,31 +0,0 @@
// load dependencies
var amqp = require('amqplib/callback_api');
// load helpers
var lbryApi = require('./helpers/lbryApi');
// open a connection and a channel
amqp.connect('amqp://localhost', function(err, conn) {
// open a channel
conn.createChannel(function(err, ch) {
var q = 'task_queue2';
// declare the cue (in case the publisher hasn't made it yet)
ch.assertQueue(q, {durable: true});
// tell the queue to only assign one task at a time to this worker
ch.prefetch(1);
// listen for messages & pass callback for what to do with the msgs
console.log(" [x] Waiting for messages in %s. To exit press ctrl+c", q);
ch.consume(q, function(msg) {
var task = JSON.parse(msg.content.toString());
console.log(` [o] Received a ${task.type} task`);
// initiate the task
switch(task.type) {
case 'publish':
console.log(" [-] publishing:", task.data);
lbryApi.publishClaim(task.data);
break;
default:
console.log(" [-] that task type is not recognized");
console.log(" [x] Done");
}
}, {noAck: true});
});
});