Merge pull request #33 from filipnyquist/fillerino-es6

Edited code to be ES6, added eslint and some basic linting configuration
This commit is contained in:
Bill Bittner 2017-06-18 09:40:50 -07:00 committed by GitHub
commit b6b1b0ab1d
19 changed files with 4041 additions and 608 deletions

2
.eslintignore Normal file
View file

@ -0,0 +1,2 @@
node_modules/
public/

35
.eslintrc Normal file
View file

@ -0,0 +1,35 @@
{
"extends": "standard",
"env": {
"es6": true,
"jest": true,
"node": true
},
"globals": {
"GENTLY": true
},
"rules": {
"no-multi-spaces": 0,
"new-cap": 0,
"prefer-promise-reject-errors":0,
"comma-dangle": [
"error",
"always-multiline"
],
"key-spacing": [
"error",
{
"multiLine": {
"beforeColon": false,
"afterColon": true
},
"align": {
"beforeColon": false,
"afterColon": true,
"on": "colon",
"mode": "strict"
}
}
]
}
}

View file

@ -1,57 +1,58 @@
var fs = require('fs'); const fs = require('fs')
var lbryApi = require('../helpers/libraries/lbryApi.js'); const lbryApi = require('../helpers/libraries/lbryApi.js')
var config = require('config'); const config = require('config')
var errorHandlers = require("../helpers/libraries/errorHandlers.js"); const errorHandlers = require('../helpers/libraries/errorHandlers.js')
var 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)
var publishParams = { const publishParams = {
"name": claim, name : claim,
"file_path": filePath, file_path: filePath,
"bid": 0.01, bid : 0.01,
"metadata": { metadata : {
"description": claim + " published via spee.ch", description: `${claim} published via spee.ch`,
"title": claim, title : claim,
"author": "spee.ch", author : 'spee.ch',
"language": "en", language : 'en',
"license": license, license,
"nsfw": (nsfw.toLowerCase() === "on") nsfw : nsfw.toLowerCase() === 'on',
}, },
"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, function(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: function(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
var publishParams = createPublishParams(claim, filePath, license, nsfw); const publishParams = createPublishParams(claim, filePath, license, nsfw)
// get a promise to publish // get a promise to publish
lbryApi.publishClaim(publishParams, fileName, fileType) lbryApi
.then(function(result){ .publishClaim(publishParams, fileName, fileType)
visitor.event("Publish Route", "Publish Success", filePath).send(); .then(result => {
console.log("publish promise success. Tx info:", result) visitor.event('Publish Route', 'Publish Success', filePath).send()
socket.emit("publish-complete", {name: claim, result: result}); console.log('publish promise success. Tx info:', result)
}) socket.emit('publish-complete', { name: claim, result })
.catch(function(error){ })
visitor.event("Publish Route", "Publish Failure", filePath).send(); .catch(error => {
console.log("error:", error); visitor.event('Publish Route', 'Publish Failure', filePath).send()
socket.emit("publish-failure", errorHandlers.handlePublishError(error)); console.log('error:', error)
deleteTemporaryFile(filePath); socket.emit('publish-failure', errorHandlers.handlePublishError(error))
}); deleteTemporaryFile(filePath)
} })
} },
}

View file

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

View file

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

View file

@ -1,61 +1,63 @@
var isFreePublicClaim = require("./isFreePublicClaim.js"); const isFreePublicClaim = require('./isFreePublicClaim.js')
var 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
}; }
var freePublicClaims = claimsListArray.filter(function(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(function(claimA, claimB){ claimsListArray.sort(({ amountA, heightA }, { amountB, heightB }) => {
if (claimA.amount === claimB.amount){ if (amountA === amountB) {
return (claimA.height > claimB.height); return heightA > heightB
} else { } else {
return (claimA.amount < claimB.amount); return amountA < amountB
} }
}) })
return claimsListArray; return claimsListArray
} }
module.exports = function(claimName){ module.exports = claimName => {
var deferred = new Promise(function(resolve, reject){ const deferred = new Promise((resolve, reject) => {
// make a call to the daemon to get the claims list // make a call to the daemon to get the claims list
lbryApi.getClaimsList(claimName) lbryApi
.then(function(result){ .getClaimsList(claimName)
var claimsList = result.claims; .then(({ claims }) => {
console.log(">> Number of claims:", claimsList.length) const claimsList = claims
// return early if no claims were found console.log('>> Number of claims:', claimsList.length)
if (claimsList.length === 0){ // return early if no claims were found
reject("NO_CLAIMS"); if (claimsList.length === 0) {
console.log("exiting due to lack of claims"); reject('NO_CLAIMS')
return; console.log('exiting due to lack of claims')
} return
// filter the claims to return only free, public claims }
var freePublicClaims = filterForFreePublicClaims(claimsList); // filter the claims to return only free, public claims
// return early if no free, public claims were found const freePublicClaims = filterForFreePublicClaims(claimsList)
if (!freePublicClaims || (freePublicClaims.length === 0)){ // return early if no free, public claims were found
reject("NO_FREE_PUBLIC_CLAIMS"); if (!freePublicClaims || freePublicClaims.length === 0) {
console.log("exiting due to lack of free or public claims"); reject('NO_FREE_PUBLIC_CLAIMS')
return; console.log('exiting due to lack of free or public claims')
} return
// order the claims }
var orderedPublicClaims = orderTopClaims(freePublicClaims); // order the claims
// resolve the promise const orderedPublicClaims = orderTopClaims(freePublicClaims)
resolve(orderedPublicClaims); // resolve the promise
}).catch(function(error){ resolve(orderedPublicClaims)
console.log(">> 'claim_list' error"); })
reject(error); .catch(error => {
}); console.log(">> 'claim_list' error")
}); reject(error)
return deferred; })
} })
return deferred
}

View file

@ -1,11 +1,11 @@
module.exports = ({ value }) => {
module.exports = function(claim){ console.log('>> check: isFreePublicClaim?')
console.log(">> check: isFreePublicClaim?"); if (
if (((claim.value.stream.metadata.license.indexOf("Public Domain") != -1 ) || (claim.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)
(!claim.value.stream.metadata.fee || claim.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: function(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: function(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,101 +1,117 @@
var axios = require('axios'); const axios = require('axios')
var db = require("../../models"); const db = require('../../models')
module.exports = { module.exports = {
publishClaim: function(publishParams, fileName, fileType){ publishClaim (publishParams, fileName, fileType) {
var deferred = new Promise(function(resolve, reject){ const deferred = new Promise((resolve, reject) => {
console.log(">> lbryApi >> publishClaim:", publishParams); console.log('>> lbryApi >> publishClaim:', publishParams)
axios.post('http://localhost:5279/lbryapi', { axios
"method": "publish", .post('http://localhost:5279/lbryapi', {
"params": publishParams method: 'publish',
}).then(function (response) { params: publishParams,
console.log(">> 'publish' success", response); })
var result = response.data.result; .then(response => {
db.File.create({ console.log(">> 'publish' success", response)
name: publishParams.name, const result = response.data.result
claim_id: result.claim_id, db.File
outpoint: result.txid + ":" + result.nout, .create({
file_name: fileName, name : publishParams.name,
file_path: publishParams.file_path, claim_id : result.claim_id,
file_type: fileType, outpoint : `${result.txid}:${result.nout}`,
nsfw: publishParams.metadata.nsfw, file_name: fileName,
}).catch(function(error){ file_path: publishParams.file_path,
console.log('An error occurred when writing to the MySQL database:', error); file_type: fileType,
}); nsfw : publishParams.metadata.nsfw,
resolve(result); })
}).catch(function(error){ .catch(error => {
console.log(">> 'publish' error"); console.log('An error occurred when writing to the MySQL database:', error)
reject(error); })
}); resolve(result)
}); })
return deferred; .catch(error => {
}, console.log(">> 'publish' error")
getClaim: function(uri){ reject(error)
var deferred = new Promise(function(resolve, reject){ })
console.log(">> lbryApi >> getClaim:", uri); })
axios.post('http://localhost:5279/lbryapi', { return deferred
"method": "get", },
"params": { "uri": uri, "timeout": 20} getClaim (uri) {
}).then(function (response) { const deferred = new Promise((resolve, reject) => {
console.log(">> 'get' success"); console.log('>> lbryApi >> getClaim:', uri)
//check to make sure the daemon didn't just time out axios
if (response.data.result.error){ .post('http://localhost:5279/lbryapi', {
reject(response.data.result.error); method: 'get',
} params: { uri, timeout: 20 },
/* })
note: put in a check to make sure we do not resolve until the download is actually complete (response.data.completed === true) .then(({ data }) => {
*/ console.log(">> 'get' success")
// save a record of the file to the Files table // check to make sure the daemon didn't just time out
var result = response.data.result if (data.result.error) {
db.File.create({ reject(data.result.error)
name: result.name, }
claim_id: result.claim_id, /*
outpoint: result.outpoint, note: put in a check to make sure we do not resolve until the download is actually complete (response.data.completed === true)
file_name: result.file_name, */
file_path: result.download_path, // save a record of the file to the Files table
file_type: result.mime_type, const result = data.result
nsfw: result.metadata.stream.metadata.nsfw, db.File
}).catch(function(error){ .create({
console.log('An error occurred when writing to the MySQL database:', error); name : result.name,
}); claim_id : result.claim_id,
resolve(result); outpoint : result.outpoint,
}).catch(function(error){ file_name: result.file_name,
console.log(">> 'get' error"); file_path: result.download_path,
reject(error); file_type: result.mime_type,
}); nsfw : result.metadata.stream.metadata.nsfw,
}); })
return deferred; .catch(error => {
}, console.log('An error occurred when writing to the MySQL database:', error)
getClaimsList: function(claimName){ })
var deferred = new Promise(function(resolve, reject){ resolve(result)
console.log(">> lbryApi >> getClaimList:", claimName); })
axios.post('http://localhost:5279/lbryapi', { .catch(error => {
method: "claim_list", console.log(">> 'get' error")
params: { name: claimName } reject(error)
}).then(function (response) { })
console.log(">> 'claim_list' success"); })
resolve(response.data.result); return deferred
}).catch(function(error){ },
console.log(">> 'claim_list' error"); getClaimsList (claimName) {
reject(error); const deferred = new Promise((resolve, reject) => {
}); console.log('>> lbryApi >> getClaimList:', claimName)
}); axios
return deferred; .post('http://localhost:5279/lbryapi', {
}, method: 'claim_list',
resolveUri: function(uri){ params: { name: claimName },
var deferred = new Promise(function(resolve, reject){ })
console.log(">> lbryApi >> resolveUri:", uri); .then(({ data }) => {
axios.post('http://localhost:5279/lbryapi', { console.log(">> 'claim_list' success")
"method": "resolve", resolve(data.result)
"params": { "uri": uri} })
}).then(function(response){ .catch(error => {
console.log(">> 'resolve' success"); console.log(">> 'claim_list' error")
resolve(response.data.result); reject(error)
}).catch(function(error){ })
console.log(">> 'resolve' error"); })
reject(error); return deferred
}); },
}); resolveUri (uri) {
return deferred; const deferred = new Promise((resolve, reject) => {
} console.log('>> lbryApi >> resolveUri:', uri)
axios
.post('http://localhost:5279/lbryapi', {
method: 'resolve',
params: { uri },
})
.then(({ data }) => {
console.log(">> 'resolve' success")
resolve(data.result)
})
.catch(error => {
console.log(">> 'resolve' error")
reject(error)
})
})
return deferred
},
} }

View file

@ -1,35 +1,39 @@
module.exports = function(sequelize, DataTypes){ module.exports = (sequelize, { STRING, BOOLEAN }) => {
var File = sequelize.define("File", { const File = sequelize.define(
name: { 'File',
type: DataTypes.STRING, {
allowNull: false name: {
}, type : STRING,
claim_id: { allowNull: false,
type: DataTypes.STRING, },
allowNull: false claim_id: {
}, type : STRING,
outpoint: { allowNull: false,
type: DataTypes.STRING, },
allowNull: false outpoint: {
}, type : STRING,
file_name: { allowNull: false,
type: DataTypes.STRING, },
allowNull: false file_name: {
}, type : STRING,
file_path: { allowNull: false,
type: DataTypes.STRING, },
allowNull: false file_path: {
}, type : STRING,
file_type: { allowNull: false,
type: DataTypes.STRING, },
}, file_type: {
nsfw: { type: STRING,
type: DataTypes.BOOLEAN, },
allowNull: false, nsfw: {
defaultValue: false type : BOOLEAN,
} allowNull : false,
}, { defaultValue: false,
freezeTableName: true },
}); },
return File; {
} freezeTableName: true,
}
)
return File
}

View file

@ -1,41 +1,34 @@
'use strict'; const fs = require('fs')
const path = require('path')
const Sequelize = require('sequelize')
const basename = path.basename(module.filename)
const config = require('config')
const db = {}
var fs = require('fs'); const connectionUri = config.get('Database.MySqlConnectionUri')
var path = require('path'); const sequelize = new Sequelize(connectionUri)
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var config = require('config');
var db = {};
var connectionUri = config.get('Database.MySqlConnectionUri');
var 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(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
}) })
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) { fs.readdirSync(__dirname).filter(file => file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js').forEach(file => {
const model = sequelize['import'](path.join(__dirname, file))
db[model.name] = model
})
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

3351
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -5,7 +5,10 @@
"main": "server.js", "main": "server.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js" "start": "node server.js",
"lint": "eslint .",
"fix": "eslint . --fix",
"precommit": "eslint ."
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@ -34,5 +37,15 @@
"socket.io": "^2.0.1", "socket.io": "^2.0.1",
"socketio-file-upload": "^0.6.0", "socketio-file-upload": "^0.6.0",
"universal-analytics": "^0.4.13" "universal-analytics": "^0.4.13"
},
"devDependencies": {
"eslint": "3.19.0",
"eslint-config-standard": "10.2.1",
"eslint-plugin-import": "^2.2.0",
"eslint-plugin-node": "^4.2.2",
"eslint-plugin-promise": "3.5.0",
"eslint-plugin-react": "6.10.3",
"eslint-plugin-standard": "3.0.1",
"husky": "^0.13.4"
} }
} }

View file

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

View file

@ -1,10 +1,10 @@
module.exports = function(app){ module.exports = app => {
// route for the home page // route for the home page
app.get("/", function(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("*", function(req, res){ app.use('*', (req, res) => {
res.status(404).render('fourOhFour'); res.status(404).render('fourOhFour')
}); })
} }

View file

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

View file

@ -1,22 +1,22 @@
var errorHandlers = require("../helpers/libraries/errorHandlers.js"); const errorHandlers = require('../helpers/libraries/errorHandlers.js')
var showController = require("../controllers/showController.js"); const showController = require('../controllers/showController.js')
module.exports = function(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", function(req, res){ app.get('/:name/all', ({ params }, res) => {
console.log(">> GET request on /" + req.params.name + "/all"); console.log(`>> GET request on /${params.name}/all`)
// google analytics // 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', `${params.name}/all`).send()
// fetch all free public claims // fetch all free public claims
showController.getAllClaims(req.params.name) showController
.then(function(orderedFreePublicClaims){ .getAllClaims(params.name)
console.log("/:name/all success."); .then(orderedFreePublicClaims => {
res.status(200).render('allClaims', { claims: orderedFreePublicClaims }); console.log('/:name/all success.')
return; res.status(200).render('allClaims', { claims: orderedFreePublicClaims })
}) })
.catch(function(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 @@
var publishController = require('../controllers/publishController.js'); const publishController = require('../controllers/publishController.js')
module.exports = function(app, siofu, hostedContentPath, ua, googleAnalyticsId) { module.exports = (app, siofu, hostedContentPath, ua, googleAnalyticsId) => {
var http = require('http').Server(app); const http = require('http').Server(app)
var io = require('socket.io')(http); const io = require('socket.io')(http)
io.on('connection', function(socket){
console.log('a user connected via sockets');
// create visitor record
var visitor = ua(googleAnalyticsId, {https: true});
// attach upload listeners
var uploader = new siofu();
uploader.dir = hostedContentPath;
uploader.listen(socket);
uploader.on("start", function(event){
// server side test to make sure file is not a bad file type
if (/\.exe$/.test(event.file.name)) {
uploader.abort(event.file.id, socket);
}
});
uploader.on("error", function(event){
console.log("an error occured while uploading", event.error);
socket.emit("publish-status", event.error)
});
uploader.on("saved", function(event){
console.log("uploaded ", event.file.name);
if (event.file.success){
socket.emit("publish-status", "file upload successfully completed");
publishController.publish(event.file.meta.name, event.file.name, event.file.pathName, event.file.meta.type, event.file.meta.license, event.file.meta.nsfw, socket, visitor)
} else {
socket.emit("publish-failure", "file uploaded, but with errors")
// to-do: remove the file
};
});
// handle disconnect
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
return http; io.on('connection', socket => {
} console.log('a user connected via sockets')
// create visitor record
const visitor = ua(googleAnalyticsId, { https: true })
// attach upload listeners
const uploader = new siofu()
uploader.dir = hostedContentPath
uploader.listen(socket)
uploader.on('start', ({ file }) => {
// server side test to make sure file is not a bad file type
if (/\.exe$/.test(file.name)) {
uploader.abort(file.id, socket)
}
})
uploader.on('error', ({ error }) => {
console.log('an error occured while uploading', error)
socket.emit('publish-status', error)
})
uploader.on('saved', ({ file }) => {
console.log('uploaded ', file.name)
if (file.success) {
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)
} else {
socket.emit('publish-failure', 'file uploaded, but with errors')
// to-do: remove the file
}
})
// handle disconnect
socket.on('disconnect', () => {
console.log('user disconnected')
})
})
return http
}

View file

@ -1,69 +1,68 @@
// load dependencies // load dependencies
var express = require('express'); const express = require('express')
var bodyParser = require('body-parser'); const bodyParser = require('body-parser')
var path = require('path'); const siofu = require('socketio-file-upload')
var siofu = require("socketio-file-upload"); const expressHandlebars = require('express-handlebars')
var expressHandlebars = require("express-handlebars"); const Handlebars = require('handlebars')
var Handlebars = require('handlebars'); const config = require('config')
var axios = require('axios'); const ua = require('universal-analytics')
var config = require('config');
var ua = require('universal-analytics');
var googleAnalyticsId = config.get('AnalyticsConfig.googleId'); const googleAnalyticsId = config.get('AnalyticsConfig.googleId')
var hostedContentPath = config.get('Database.PublishUploadPath'); const hostedContentPath = config.get('Database.PublishUploadPath')
// set port // set port
var PORT = 3000; const PORT = 3000
// initialize express app // initialize express app
var app = express(); const app = express()
//require our models for syncing // require our models for syncing
var 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
var hbs = expressHandlebars.create({ const hbs = expressHandlebars.create({
defaultLayout: 'main', // sets the default layout defaultLayout: 'main', // sets the default layout
handlebars: Handlebars, // includes basic handlebars for access to that library handlebars : Handlebars, // includes basic handlebars for access to that library
helpers: { // define any extra helpers you may need helpers : {
googleAnalytics: function(){ // define any extra helpers you may need
var googleApiKey = config.get('AnalyticsConfig.googleId') googleAnalytics () {
return new Handlebars.SafeString(`<script> const googleApiKey = config.get('AnalyticsConfig.googleId')
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ return new Handlebars.SafeString(
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), `<script>
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
ga('create', '${googleApiKey}', 'auto'); m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
ga('send', 'pageview'); })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
</script>`); ga('create', '${googleApiKey}', 'auto');
} ga('send', 'pageview');
} </script>`
}); )
app.engine('handlebars', hbs.engine); },
app.set('view engine', 'handlebars'); },
})
app.engine('handlebars', hbs.engine)
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
var 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({}) db.sequelize.sync({}).then(() => {
.then(function(){ http.listen(PORT, () => {
http.listen(PORT, function() { console.log(`Listening on PORT ${PORT}`)
console.log("Listening on PORT " + PORT); })
}); })
});