Edited code to be ES6, added eslint and some basic linting configuration
Edited code to be ES6, added eslint and some basic linting configuration,(also includes husky for auto eslint before push)
This commit is contained in:
parent
c89061c83f
commit
085d099040
19 changed files with 4038 additions and 606 deletions
2
.eslintignore
Normal file
2
.eslintignore
Normal file
|
@ -0,0 +1,2 @@
|
|||
node_modules/
|
||||
public/
|
35
.eslintrc
Normal file
35
.eslintrc
Normal 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"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
|
@ -1,57 +1,58 @@
|
|||
var fs = require('fs');
|
||||
var lbryApi = require('../helpers/libraries/lbryApi.js');
|
||||
var config = require('config');
|
||||
var errorHandlers = require("../helpers/libraries/errorHandlers.js");
|
||||
const fs = require('fs')
|
||||
const lbryApi = require('../helpers/libraries/lbryApi.js')
|
||||
const config = require('config')
|
||||
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) {
|
||||
console.log("nsfw:", nsfw, typeof nsfw);
|
||||
var publishParams = {
|
||||
"name": claim,
|
||||
"file_path": filePath,
|
||||
"bid": 0.01,
|
||||
"metadata": {
|
||||
"description": claim + " published via spee.ch",
|
||||
"title": claim,
|
||||
"author": "spee.ch",
|
||||
"language": "en",
|
||||
"license": license,
|
||||
"nsfw": (nsfw.toLowerCase() === "on")
|
||||
},
|
||||
"claim_address": walledAddress,
|
||||
"change_address": walledAddress
|
||||
};
|
||||
return publishParams;
|
||||
function createPublishParams (claim, filePath, license, nsfw) {
|
||||
console.log('nsfw:', nsfw, typeof nsfw)
|
||||
const publishParams = {
|
||||
name : claim,
|
||||
file_path: filePath,
|
||||
bid : 0.01,
|
||||
metadata : {
|
||||
description: `${claim} published via spee.ch`,
|
||||
title : claim,
|
||||
author : 'spee.ch',
|
||||
language : 'en',
|
||||
license,
|
||||
nsfw : nsfw.toLowerCase() === 'on',
|
||||
},
|
||||
claim_address : walledAddress,
|
||||
change_address: walledAddress,
|
||||
}
|
||||
return publishParams
|
||||
}
|
||||
|
||||
function deleteTemporaryFile(filePath) {
|
||||
fs.unlink(filePath, function(err) {
|
||||
if (err) throw err;
|
||||
console.log('successfully deleted ' + filePath);
|
||||
});
|
||||
function deleteTemporaryFile (filePath) {
|
||||
fs.unlink(filePath, err => {
|
||||
if (err) throw err
|
||||
console.log(`successfully deleted ${filePath}`)
|
||||
})
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
publish: function(claim, fileName, filePath, fileType, license, nsfw, socket, visitor) {
|
||||
// update the client
|
||||
socket.emit("publish-status", "Your image is being published (this might take a second)...");
|
||||
// send to analytics
|
||||
visitor.event("Publish Route", "Publish Request", filePath).send();
|
||||
// create the publish object
|
||||
var publishParams = createPublishParams(claim, filePath, license, nsfw);
|
||||
// get a promise to publish
|
||||
lbryApi.publishClaim(publishParams, fileName, fileType)
|
||||
.then(function(result){
|
||||
visitor.event("Publish Route", "Publish Success", filePath).send();
|
||||
console.log("publish promise success. Tx info:", result)
|
||||
socket.emit("publish-complete", {name: claim, result: result});
|
||||
})
|
||||
.catch(function(error){
|
||||
visitor.event("Publish Route", "Publish Failure", filePath).send();
|
||||
console.log("error:", error);
|
||||
socket.emit("publish-failure", errorHandlers.handlePublishError(error));
|
||||
deleteTemporaryFile(filePath);
|
||||
});
|
||||
}
|
||||
}
|
||||
publish (claim, fileName, filePath, fileType, license, nsfw, socket, visitor) {
|
||||
// update the client
|
||||
socket.emit('publish-status', 'Your image is being published (this might take a second)...')
|
||||
// send to analytics
|
||||
visitor.event('Publish Route', 'Publish Request', filePath).send()
|
||||
// create the publish object
|
||||
const publishParams = createPublishParams(claim, filePath, license, nsfw)
|
||||
// get a promise to publish
|
||||
lbryApi
|
||||
.publishClaim(publishParams, fileName, fileType)
|
||||
.then(result => {
|
||||
visitor.event('Publish Route', 'Publish Success', filePath).send()
|
||||
console.log('publish promise success. Tx info:', result)
|
||||
socket.emit('publish-complete', { name: claim, result })
|
||||
})
|
||||
.catch(error => {
|
||||
visitor.event('Publish Route', 'Publish Failure', filePath).send()
|
||||
console.log('error:', error)
|
||||
socket.emit('publish-failure', errorHandlers.handlePublishError(error))
|
||||
deleteTemporaryFile(filePath)
|
||||
})
|
||||
},
|
||||
}
|
||||
|
|
|
@ -1,102 +1,112 @@
|
|||
var lbryApi = require('../helpers/libraries/lbryApi.js');
|
||||
var db = require("../models");
|
||||
const lbryApi = require('../helpers/libraries/lbryApi.js')
|
||||
const db = require('../models')
|
||||
|
||||
var getAllFreePublicClaims = require("../helpers/functions/getAllFreePublicClaims.js");
|
||||
var isFreePublicClaim = require("../helpers/functions/isFreePublicClaim.js");
|
||||
const getAllFreePublicClaims = require('../helpers/functions/getAllFreePublicClaims.js')
|
||||
const isFreePublicClaim = require('../helpers/functions/isFreePublicClaim.js')
|
||||
|
||||
function getClaimAndHandleResponse(claimUri, resolve, reject){
|
||||
lbryApi.getClaim(claimUri)
|
||||
.then(function(result){
|
||||
resolve({
|
||||
file_name: result.file_name,
|
||||
file_path: result.download_path,
|
||||
file_type: result.mime_type
|
||||
});
|
||||
}).catch(function(error){
|
||||
reject(error)
|
||||
});
|
||||
function getClaimAndHandleResponse (claimUri, resolve, reject) {
|
||||
lbryApi
|
||||
.getClaim(claimUri)
|
||||
.then(({ file_name, download_path, mime_type }) => {
|
||||
resolve({
|
||||
file_name,
|
||||
file_path: download_path,
|
||||
file_type: mime_type,
|
||||
})
|
||||
})
|
||||
.catch(error => {
|
||||
reject(error)
|
||||
})
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getClaimByName: function(claimName){
|
||||
var deferred = new Promise(function (resolve, reject){
|
||||
console.log(">> lbryHelpers >> getClaim BasedOnNameOnly:", claimName);
|
||||
// get all free public claims
|
||||
getAllFreePublicClaims(claimName)
|
||||
.then(function(freePublicClaimList){
|
||||
console.log(">> Decided on public claim id:", freePublicClaimList[0].claim_id);
|
||||
var freePublicClaimOutpoint = freePublicClaimList[0].txid + ":" + freePublicClaimList[0].nout;
|
||||
var freePublicClaimUri = freePublicClaimList[0].name + "#" + freePublicClaimList[0].claim_id;
|
||||
// check to see if the file is available locally
|
||||
db.File.findOne({where: { claim_id: freePublicClaimList[0].claim_id }})
|
||||
.then(function(claim){
|
||||
// if a found locally...
|
||||
if (claim){
|
||||
console.log(">> A matching claim_id was found locally");
|
||||
// if the outpoint's match return it
|
||||
if (claim.dataValues.outpoint === freePublicClaimOutpoint){
|
||||
console.log(">> Local outpoint matched");
|
||||
resolve(claim.dataValues);
|
||||
// if the outpoint's don't match, fetch updated claim
|
||||
} else {
|
||||
console.log(">> local outpoint did not match");
|
||||
getClaimAndHandleResponse(freePublicClaimUri, resolve, reject);
|
||||
}
|
||||
// ... otherwise use daemon to retrieve it
|
||||
} else {
|
||||
// 'get' the claim
|
||||
getClaimAndHandleResponse(freePublicClaimUri, resolve, reject)
|
||||
}
|
||||
}).catch(function(error){
|
||||
reject(error);
|
||||
});
|
||||
}).catch(function(error){
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
return deferred;
|
||||
},
|
||||
getClaimByClaimId: function(claimName, claimId){
|
||||
var deferred = new Promise(function (resolve, reject){
|
||||
var uri = claimName + "#" + claimId;
|
||||
console.log(">> lbryHelpers >> getClaimBasedOnUri:", uri);
|
||||
// resolve the Uri
|
||||
lbryApi.resolveUri(uri) // note: use 'spread' and make parallel with db.File.findOne()
|
||||
.then(function(result){ // note should just be 'result' returned.
|
||||
// get the outpoint
|
||||
var resolvedOutpoint = result[uri].claim.txid + ":" + result[uri].claim.nout;
|
||||
// check locally for the claim
|
||||
db.File.findOne({where: { claim_id: claimId }})
|
||||
.then(function(claim){
|
||||
// if a found locally...
|
||||
if (claim){
|
||||
console.log(">> A matching claim_id was found locally");
|
||||
// if the outpoint's match return it
|
||||
if (claim.dataValues.outpoint === resolvedOutpoint){
|
||||
console.log(">> Local outpoint matched");
|
||||
resolve(claim.dataValues);
|
||||
// if the outpoint's don't match, fetch updated claim
|
||||
} else {
|
||||
console.log(">> Local outpoint did not match");
|
||||
getClaimAndHandleResponse(uri, resolve, reject);
|
||||
}
|
||||
// ... otherwise use daemon to retrieve it
|
||||
} else {
|
||||
// check to make sure it is free and public (note: no need for another resolve?)
|
||||
if (isFreePublicClaim(result[uri].claim)){
|
||||
// 'get' the claim
|
||||
getClaimAndHandleResponse(uri, resolve, reject);
|
||||
} else {
|
||||
reject("NO_FREE_PUBLIC_CLAIMS");
|
||||
}
|
||||
}
|
||||
}).catch(function(error){
|
||||
reject(error)
|
||||
});
|
||||
}).catch(function(error){
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
return deferred;
|
||||
}
|
||||
getClaimByName (claimName) {
|
||||
const deferred = new Promise((resolve, reject) => {
|
||||
console.log('>> lbryHelpers >> getClaim BasedOnNameOnly:', claimName)
|
||||
// get all free public claims
|
||||
getAllFreePublicClaims(claimName)
|
||||
.then(freePublicClaimList => {
|
||||
console.log('>> Decided on public claim id:', freePublicClaimList[0].claim_id)
|
||||
const freePublicClaimOutpoint = `${freePublicClaimList[0].txid}:${freePublicClaimList[0].nout}`
|
||||
const freePublicClaimUri = `${freePublicClaimList[0].name}#${freePublicClaimList[0].claim_id}`
|
||||
// check to see if the file is available locally
|
||||
db.File
|
||||
.findOne({ where: { claim_id: freePublicClaimList[0].claim_id } })
|
||||
.then(claim => {
|
||||
// if a found locally...
|
||||
if (claim) {
|
||||
console.log('>> A matching claim_id was found locally')
|
||||
// if the outpoint's match return it
|
||||
if (claim.dataValues.outpoint === freePublicClaimOutpoint) {
|
||||
console.log('>> Local outpoint matched')
|
||||
resolve(claim.dataValues)
|
||||
// if the outpoint's don't match, fetch updated claim
|
||||
} else {
|
||||
console.log('>> local outpoint did not match')
|
||||
getClaimAndHandleResponse(freePublicClaimUri, resolve, reject)
|
||||
}
|
||||
// ... otherwise use daemon to retrieve it
|
||||
} else {
|
||||
// 'get' the claim
|
||||
getClaimAndHandleResponse(freePublicClaimUri, resolve, reject)
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
.catch(error => {
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
return deferred
|
||||
},
|
||||
getClaimByClaimId (claimName, claimId) {
|
||||
const deferred = new Promise((resolve, reject) => {
|
||||
const uri = `${claimName}#${claimId}`
|
||||
console.log('>> lbryHelpers >> getClaimBasedOnUri:', uri)
|
||||
// resolve the Uri
|
||||
lbryApi
|
||||
.resolveUri(uri) // note: use 'spread' and make parallel with db.File.findOne()
|
||||
.then(result => {
|
||||
// note should just be 'result' returned.
|
||||
// get the outpoint
|
||||
const resolvedOutpoint = `${result[uri].claim.txid}:${result[uri].claim.nout}`
|
||||
// check locally for the claim
|
||||
db.File
|
||||
.findOne({ where: { claim_id: claimId } })
|
||||
.then(claim => {
|
||||
// if a found locally...
|
||||
if (claim) {
|
||||
console.log('>> A matching claim_id was found locally')
|
||||
// if the outpoint's match return it
|
||||
if (claim.dataValues.outpoint === resolvedOutpoint) {
|
||||
console.log('>> Local outpoint matched')
|
||||
resolve(claim.dataValues)
|
||||
// if the outpoint's don't match, fetch updated claim
|
||||
} else {
|
||||
console.log('>> Local outpoint did not match')
|
||||
getClaimAndHandleResponse(uri, resolve, reject)
|
||||
}
|
||||
// ... otherwise use daemon to retrieve it
|
||||
} else {
|
||||
// check to make sure it is free and public (note: no need for another resolve?)
|
||||
if (isFreePublicClaim(result[uri].claim)) {
|
||||
// 'get' the claim
|
||||
getClaimAndHandleResponse(uri, resolve, reject)
|
||||
} else {
|
||||
reject('NO_FREE_PUBLIC_CLAIMS')
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
.catch(error => {
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
return deferred
|
||||
},
|
||||
}
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
var getAllFreePublicClaims = require("../helpers/functions/getAllFreePublicClaims.js");
|
||||
const getAllFreePublicClaims = require('../helpers/functions/getAllFreePublicClaims.js')
|
||||
|
||||
module.exports = {
|
||||
getAllClaims: function(claimName){
|
||||
return getAllFreePublicClaims(claimName);
|
||||
}
|
||||
}
|
||||
getAllClaims (claimName) {
|
||||
return getAllFreePublicClaims(claimName)
|
||||
},
|
||||
}
|
||||
|
|
|
@ -1,61 +1,63 @@
|
|||
var isFreePublicClaim = require("./isFreePublicClaim.js");
|
||||
var lbryApi = require('../libraries/lbryApi.js');
|
||||
const isFreePublicClaim = require('./isFreePublicClaim.js')
|
||||
const lbryApi = require('../libraries/lbryApi.js')
|
||||
|
||||
function filterForFreePublicClaims(claimsListArray){
|
||||
//console.log("claims list:", claimsListArray)
|
||||
if (!claimsListArray) {
|
||||
return null;
|
||||
};
|
||||
var freePublicClaims = claimsListArray.filter(function(claim){
|
||||
if (!claim.value){
|
||||
return false;
|
||||
}
|
||||
return (isFreePublicClaim(claim));
|
||||
});
|
||||
return freePublicClaims;
|
||||
function filterForFreePublicClaims (claimsListArray) {
|
||||
// console.log("claims list:", claimsListArray)
|
||||
if (!claimsListArray) {
|
||||
return null
|
||||
}
|
||||
const freePublicClaims = claimsListArray.filter(claim => {
|
||||
if (!claim.value) {
|
||||
return false
|
||||
}
|
||||
return isFreePublicClaim(claim)
|
||||
})
|
||||
return freePublicClaims
|
||||
}
|
||||
|
||||
function orderTopClaims(claimsListArray){
|
||||
console.log(">> orderTopClaims");
|
||||
claimsListArray.sort(function(claimA, claimB){
|
||||
if (claimA.amount === claimB.amount){
|
||||
return (claimA.height > claimB.height);
|
||||
} else {
|
||||
return (claimA.amount < claimB.amount);
|
||||
}
|
||||
})
|
||||
return claimsListArray;
|
||||
function orderTopClaims (claimsListArray) {
|
||||
console.log('>> orderTopClaims')
|
||||
claimsListArray.sort(({ amountA, heightA }, { amountB, heightB }) => {
|
||||
if (amountA === amountB) {
|
||||
return heightA > heightB
|
||||
} else {
|
||||
return amountA < amountB
|
||||
}
|
||||
})
|
||||
return claimsListArray
|
||||
}
|
||||
|
||||
module.exports = function(claimName){
|
||||
var deferred = new Promise(function(resolve, reject){
|
||||
// make a call to the daemon to get the claims list
|
||||
lbryApi.getClaimsList(claimName)
|
||||
.then(function(result){
|
||||
var claimsList = result.claims;
|
||||
console.log(">> Number of claims:", claimsList.length)
|
||||
// return early if no claims were found
|
||||
if (claimsList.length === 0){
|
||||
reject("NO_CLAIMS");
|
||||
console.log("exiting due to lack of claims");
|
||||
return;
|
||||
}
|
||||
// filter the claims to return only free, public claims
|
||||
var freePublicClaims = filterForFreePublicClaims(claimsList);
|
||||
// return early if no free, public claims were found
|
||||
if (!freePublicClaims || (freePublicClaims.length === 0)){
|
||||
reject("NO_FREE_PUBLIC_CLAIMS");
|
||||
console.log("exiting due to lack of free or public claims");
|
||||
return;
|
||||
}
|
||||
// order the claims
|
||||
var orderedPublicClaims = orderTopClaims(freePublicClaims);
|
||||
// resolve the promise
|
||||
resolve(orderedPublicClaims);
|
||||
}).catch(function(error){
|
||||
console.log(">> 'claim_list' error");
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
return deferred;
|
||||
}
|
||||
module.exports = claimName => {
|
||||
const deferred = new Promise((resolve, reject) => {
|
||||
// make a call to the daemon to get the claims list
|
||||
lbryApi
|
||||
.getClaimsList(claimName)
|
||||
.then(({ claims }) => {
|
||||
const claimsList = claims
|
||||
console.log('>> Number of claims:', claimsList.length)
|
||||
// return early if no claims were found
|
||||
if (claimsList.length === 0) {
|
||||
reject('NO_CLAIMS')
|
||||
console.log('exiting due to lack of claims')
|
||||
return
|
||||
}
|
||||
// filter the claims to return only free, public claims
|
||||
const freePublicClaims = filterForFreePublicClaims(claimsList)
|
||||
// return early if no free, public claims were found
|
||||
if (!freePublicClaims || freePublicClaims.length === 0) {
|
||||
reject('NO_FREE_PUBLIC_CLAIMS')
|
||||
console.log('exiting due to lack of free or public claims')
|
||||
return
|
||||
}
|
||||
// order the claims
|
||||
const orderedPublicClaims = orderTopClaims(freePublicClaims)
|
||||
// resolve the promise
|
||||
resolve(orderedPublicClaims)
|
||||
})
|
||||
.catch(error => {
|
||||
console.log(">> 'claim_list' error")
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
return deferred
|
||||
}
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
|
||||
module.exports = function(claim){
|
||||
console.log(">> check: isFreePublicClaim?");
|
||||
if (((claim.value.stream.metadata.license.indexOf("Public Domain") != -1 ) || (claim.value.stream.metadata.license.indexOf("Creative Commons") != -1 ))
|
||||
&&
|
||||
(!claim.value.stream.metadata.fee || claim.value.stream.metadata.fee.amount === 0)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
module.exports = ({ value }) => {
|
||||
console.log('>> check: isFreePublicClaim?')
|
||||
if (
|
||||
(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)
|
||||
) {
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,22 +1,22 @@
|
|||
module.exports = {
|
||||
handleRequestError: function(error, res) {
|
||||
if ((error === "NO_CLAIMS") || (error === "NO_FREE_PUBLIC_CLAIMS")){
|
||||
res.status(307).render('noClaims');
|
||||
} 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());
|
||||
};
|
||||
},
|
||||
handlePublishError: function(error) {
|
||||
if (error.code === "ECONNREFUSED"){
|
||||
return "Connection refused. The daemon may not be running.";
|
||||
} else if (error.response.data.error) {
|
||||
return error.response.data.error;
|
||||
} else {
|
||||
return error;
|
||||
};
|
||||
}
|
||||
handleRequestError (error, res) {
|
||||
if (error === 'NO_CLAIMS' || error === 'NO_FREE_PUBLIC_CLAIMS') {
|
||||
res.status(307).render('noClaims')
|
||||
} 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())
|
||||
}
|
||||
},
|
||||
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
|
||||
}
|
||||
},
|
||||
}
|
||||
|
|
|
@ -1,101 +1,117 @@
|
|||
var axios = require('axios');
|
||||
var db = require("../../models");
|
||||
const axios = require('axios')
|
||||
const db = require('../../models')
|
||||
|
||||
module.exports = {
|
||||
publishClaim: function(publishParams, fileName, fileType){
|
||||
var deferred = new Promise(function(resolve, reject){
|
||||
console.log(">> lbryApi >> publishClaim:", publishParams);
|
||||
axios.post('http://localhost:5279/lbryapi', {
|
||||
"method": "publish",
|
||||
"params": publishParams
|
||||
}).then(function (response) {
|
||||
console.log(">> 'publish' success", response);
|
||||
var result = response.data.result;
|
||||
db.File.create({
|
||||
name: publishParams.name,
|
||||
claim_id: result.claim_id,
|
||||
outpoint: result.txid + ":" + result.nout,
|
||||
file_name: fileName,
|
||||
file_path: publishParams.file_path,
|
||||
file_type: fileType,
|
||||
nsfw: publishParams.metadata.nsfw,
|
||||
}).catch(function(error){
|
||||
console.log('An error occurred when writing to the MySQL database:', error);
|
||||
});
|
||||
resolve(result);
|
||||
}).catch(function(error){
|
||||
console.log(">> 'publish' error");
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
return deferred;
|
||||
},
|
||||
getClaim: function(uri){
|
||||
var deferred = new Promise(function(resolve, reject){
|
||||
console.log(">> lbryApi >> getClaim:", uri);
|
||||
axios.post('http://localhost:5279/lbryapi', {
|
||||
"method": "get",
|
||||
"params": { "uri": uri, "timeout": 20}
|
||||
}).then(function (response) {
|
||||
console.log(">> 'get' success");
|
||||
//check to make sure the daemon didn't just time out
|
||||
if (response.data.result.error){
|
||||
reject(response.data.result.error);
|
||||
}
|
||||
/*
|
||||
note: put in a check to make sure we do not resolve until the download is actually complete (response.data.completed === true)
|
||||
*/
|
||||
// save a record of the file to the Files table
|
||||
var result = response.data.result
|
||||
db.File.create({
|
||||
name: result.name,
|
||||
claim_id: result.claim_id,
|
||||
outpoint: result.outpoint,
|
||||
file_name: result.file_name,
|
||||
file_path: result.download_path,
|
||||
file_type: result.mime_type,
|
||||
nsfw: result.metadata.stream.metadata.nsfw,
|
||||
}).catch(function(error){
|
||||
console.log('An error occurred when writing to the MySQL database:', error);
|
||||
});
|
||||
resolve(result);
|
||||
}).catch(function(error){
|
||||
console.log(">> 'get' error");
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
return deferred;
|
||||
},
|
||||
getClaimsList: function(claimName){
|
||||
var deferred = new Promise(function(resolve, reject){
|
||||
console.log(">> lbryApi >> getClaimList:", claimName);
|
||||
axios.post('http://localhost:5279/lbryapi', {
|
||||
method: "claim_list",
|
||||
params: { name: claimName }
|
||||
}).then(function (response) {
|
||||
console.log(">> 'claim_list' success");
|
||||
resolve(response.data.result);
|
||||
}).catch(function(error){
|
||||
console.log(">> 'claim_list' error");
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
return deferred;
|
||||
},
|
||||
resolveUri: function(uri){
|
||||
var deferred = new Promise(function(resolve, reject){
|
||||
console.log(">> lbryApi >> resolveUri:", uri);
|
||||
axios.post('http://localhost:5279/lbryapi', {
|
||||
"method": "resolve",
|
||||
"params": { "uri": uri}
|
||||
}).then(function(response){
|
||||
console.log(">> 'resolve' success");
|
||||
resolve(response.data.result);
|
||||
}).catch(function(error){
|
||||
console.log(">> 'resolve' error");
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
return deferred;
|
||||
}
|
||||
publishClaim (publishParams, fileName, fileType) {
|
||||
const deferred = new Promise((resolve, reject) => {
|
||||
console.log('>> lbryApi >> publishClaim:', publishParams)
|
||||
axios
|
||||
.post('http://localhost:5279/lbryapi', {
|
||||
method: 'publish',
|
||||
params: publishParams,
|
||||
})
|
||||
.then(response => {
|
||||
console.log(">> 'publish' success", response)
|
||||
const result = response.data.result
|
||||
db.File
|
||||
.create({
|
||||
name : publishParams.name,
|
||||
claim_id : result.claim_id,
|
||||
outpoint : `${result.txid}:${result.nout}`,
|
||||
file_name: fileName,
|
||||
file_path: publishParams.file_path,
|
||||
file_type: fileType,
|
||||
nsfw : publishParams.metadata.nsfw,
|
||||
})
|
||||
.catch(error => {
|
||||
console.log('An error occurred when writing to the MySQL database:', error)
|
||||
})
|
||||
resolve(result)
|
||||
})
|
||||
.catch(error => {
|
||||
console.log(">> 'publish' error")
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
return deferred
|
||||
},
|
||||
getClaim (uri) {
|
||||
const deferred = new Promise((resolve, reject) => {
|
||||
console.log('>> lbryApi >> getClaim:', uri)
|
||||
axios
|
||||
.post('http://localhost:5279/lbryapi', {
|
||||
method: 'get',
|
||||
params: { uri, timeout: 20 },
|
||||
})
|
||||
.then(({ data }) => {
|
||||
console.log(">> 'get' success")
|
||||
// check to make sure the daemon didn't just time out
|
||||
if (data.result.error) {
|
||||
reject(data.result.error)
|
||||
}
|
||||
/*
|
||||
note: put in a check to make sure we do not resolve until the download is actually complete (response.data.completed === true)
|
||||
*/
|
||||
// save a record of the file to the Files table
|
||||
const result = data.result
|
||||
db.File
|
||||
.create({
|
||||
name : result.name,
|
||||
claim_id : result.claim_id,
|
||||
outpoint : result.outpoint,
|
||||
file_name: result.file_name,
|
||||
file_path: result.download_path,
|
||||
file_type: result.mime_type,
|
||||
nsfw : result.metadata.stream.metadata.nsfw,
|
||||
})
|
||||
.catch(error => {
|
||||
console.log('An error occurred when writing to the MySQL database:', error)
|
||||
})
|
||||
resolve(result)
|
||||
})
|
||||
.catch(error => {
|
||||
console.log(">> 'get' error")
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
return deferred
|
||||
},
|
||||
getClaimsList (claimName) {
|
||||
const deferred = new Promise((resolve, reject) => {
|
||||
console.log('>> lbryApi >> getClaimList:', claimName)
|
||||
axios
|
||||
.post('http://localhost:5279/lbryapi', {
|
||||
method: 'claim_list',
|
||||
params: { name: claimName },
|
||||
})
|
||||
.then(({ data }) => {
|
||||
console.log(">> 'claim_list' success")
|
||||
resolve(data.result)
|
||||
})
|
||||
.catch(error => {
|
||||
console.log(">> 'claim_list' error")
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
return deferred
|
||||
},
|
||||
resolveUri (uri) {
|
||||
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
|
||||
},
|
||||
}
|
||||
|
|
|
@ -1,35 +1,39 @@
|
|||
module.exports = function(sequelize, DataTypes){
|
||||
var File = sequelize.define("File", {
|
||||
name: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false
|
||||
},
|
||||
claim_id: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false
|
||||
},
|
||||
outpoint: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false
|
||||
},
|
||||
file_name: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false
|
||||
},
|
||||
file_path: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false
|
||||
},
|
||||
file_type: {
|
||||
type: DataTypes.STRING,
|
||||
},
|
||||
nsfw: {
|
||||
type: DataTypes.BOOLEAN,
|
||||
allowNull: false,
|
||||
defaultValue: false
|
||||
}
|
||||
}, {
|
||||
freezeTableName: true
|
||||
});
|
||||
return File;
|
||||
}
|
||||
module.exports = (sequelize, { STRING, BOOLEAN }) => {
|
||||
const File = sequelize.define(
|
||||
'File',
|
||||
{
|
||||
name: {
|
||||
type : STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
claim_id: {
|
||||
type : STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
outpoint: {
|
||||
type : STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
file_name: {
|
||||
type : STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
file_path: {
|
||||
type : STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
file_type: {
|
||||
type: STRING,
|
||||
},
|
||||
nsfw: {
|
||||
type : BOOLEAN,
|
||||
allowNull : false,
|
||||
defaultValue: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
freezeTableName: true,
|
||||
}
|
||||
)
|
||||
return 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');
|
||||
var path = require('path');
|
||||
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);
|
||||
const connectionUri = config.get('Database.MySqlConnectionUri')
|
||||
const sequelize = new Sequelize(connectionUri)
|
||||
|
||||
sequelize
|
||||
.authenticate()
|
||||
.then(() => {
|
||||
console.log('Connection has been established successfully.');
|
||||
console.log('Connection has been established successfully.')
|
||||
})
|
||||
.catch(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');
|
||||
console.error('Unable to connect to the database:', err)
|
||||
})
|
||||
.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) {
|
||||
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
3351
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
15
package.json
15
package.json
|
@ -5,7 +5,10 @@
|
|||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
"start": "node server.js",
|
||||
"lint": "eslint .",
|
||||
"fix": "eslint . --fix",
|
||||
"precommit": "eslint ."
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
@ -34,5 +37,15 @@
|
|||
"socket.io": "^2.0.1",
|
||||
"socketio-file-upload": "^0.6.0",
|
||||
"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"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,28 +1,30 @@
|
|||
var errorHandlers = require("../helpers/libraries/errorHandlers.js");
|
||||
var lbryApi = require("../helpers/libraries/lbryApi.js");
|
||||
const errorHandlers = require('../helpers/libraries/errorHandlers.js')
|
||||
const lbryApi = require('../helpers/libraries/lbryApi.js')
|
||||
|
||||
module.exports = function(app){
|
||||
// route to run a claim_list request on the daemon
|
||||
app.get("/api/claim_list/:claim", function(req, res){
|
||||
lbryApi.getClaimsList(req.params.claim)
|
||||
.then(function(claimsList){
|
||||
console.log("/api/claim_list/:claim success.");
|
||||
res.status(200).json(claimsList);
|
||||
})
|
||||
.catch(function(error){
|
||||
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){
|
||||
lbryApi.resolveUri(req.params.uri)
|
||||
.then(function(resolvedUri){
|
||||
console.log("/api/resolve/:claim success.");
|
||||
res.status(200).json(resolvedUri);
|
||||
}).catch(function(error){
|
||||
errorHandlers.handleRequestError(error, res);
|
||||
});
|
||||
});
|
||||
|
||||
}
|
||||
module.exports = app => {
|
||||
// route to run a claim_list request on the daemon
|
||||
app.get('/api/claim_list/:claim', ({ params }, res) => {
|
||||
lbryApi
|
||||
.getClaimsList(params.claim)
|
||||
.then(claimsList => {
|
||||
console.log('/api/claim_list/:claim success.')
|
||||
res.status(200).json(claimsList)
|
||||
})
|
||||
.catch(error => {
|
||||
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', ({ params }, res) => {
|
||||
lbryApi
|
||||
.resolveUri(params.uri)
|
||||
.then(resolvedUri => {
|
||||
console.log('/api/resolve/:claim success.')
|
||||
res.status(200).json(resolvedUri)
|
||||
})
|
||||
.catch(error => {
|
||||
errorHandlers.handleRequestError(error, res)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
module.exports = function(app){
|
||||
// route for the home page
|
||||
app.get("/", function(req, res){
|
||||
res.status(200).render('index');
|
||||
});
|
||||
// a catch-all route if someone visits a page that does not exist
|
||||
app.use("*", function(req, res){
|
||||
res.status(404).render('fourOhFour');
|
||||
});
|
||||
module.exports = app => {
|
||||
// route for the home page
|
||||
app.get('/', (req, res) => {
|
||||
res.status(200).render('index')
|
||||
})
|
||||
// a catch-all route if someone visits a page that does not exist
|
||||
app.use('*', (req, res) => {
|
||||
res.status(404).render('fourOhFour')
|
||||
})
|
||||
}
|
||||
|
|
|
@ -1,63 +1,67 @@
|
|||
var errorHandlers = require("../helpers/libraries/errorHandlers.js");
|
||||
var serveController = require("../controllers/serveController.js");
|
||||
const errorHandlers = require('../helpers/libraries/errorHandlers.js')
|
||||
const serveController = require('../controllers/serveController.js')
|
||||
|
||||
function serveFile(fileInfo, res){
|
||||
// set default options
|
||||
var options = {
|
||||
headers: {
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Content-Type": fileInfo.file_type
|
||||
}
|
||||
};
|
||||
// adjust default options as needed
|
||||
switch (fileInfo.file_type){
|
||||
case "image/jpeg":
|
||||
break;
|
||||
case "image/gif":
|
||||
break;
|
||||
case "image/png":
|
||||
break;
|
||||
case "video/mp4":
|
||||
break;
|
||||
default:
|
||||
console.log("sending unknown file type as .jpeg");
|
||||
options["headers"]["Content-Type"] = "image/jpeg";
|
||||
break;
|
||||
}
|
||||
// send file
|
||||
res.status(200).sendFile(fileInfo.file_path, options);
|
||||
function serveFile ({ fileType, filePath }, res) {
|
||||
// set default options
|
||||
const options = {
|
||||
headers: {
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Content-Type' : fileType,
|
||||
},
|
||||
}
|
||||
// adjust default options as needed
|
||||
switch (fileType) {
|
||||
case 'image/jpeg':
|
||||
break
|
||||
case 'image/gif':
|
||||
break
|
||||
case 'image/png':
|
||||
break
|
||||
case 'video/mp4':
|
||||
break
|
||||
default:
|
||||
console.log('sending unknown file type as .jpeg')
|
||||
options['headers']['Content-Type'] = 'image/jpeg'
|
||||
break
|
||||
}
|
||||
// send file
|
||||
res.status(200).sendFile(filePath, options)
|
||||
}
|
||||
|
||||
module.exports = function(app, ua, googleAnalyticsId){
|
||||
// route to fetch one free public claim
|
||||
app.get("/:name/:claim_id", function(req, res){
|
||||
var routeString = req.params.name + "/" + req.params.claim_id;
|
||||
// google analytics
|
||||
ua(googleAnalyticsId, {https: true}).event("Serve Route", "/name/claimId", routeString).send();
|
||||
// begin image-serve processes
|
||||
console.log(">> GET request on /" + routeString);
|
||||
serveController.getClaimByClaimId(req.params.name, req.params.claim_id)
|
||||
.then(function(fileInfo){
|
||||
console.log("/:name/:claim_id success.", fileInfo.file_name);
|
||||
serveFile(fileInfo, res);
|
||||
}).catch(function(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
|
||||
ua(googleAnalyticsId, {https: true}).event("Serve Route", "/name", req.params.name).send();
|
||||
// begin image-serve processes
|
||||
console.log(">> GET request on /" + req.params.name);
|
||||
serveController.getClaimByName(req.params.name)
|
||||
.then(function(fileInfo){
|
||||
console.log("/:name success.", fileInfo.file_name);
|
||||
serveFile(fileInfo, res);
|
||||
}).catch(function(error){
|
||||
console.log("/:name error:", error);
|
||||
errorHandlers.handleRequestError(error, res);
|
||||
});
|
||||
});
|
||||
}
|
||||
module.exports = (app, ua, googleAnalyticsId) => {
|
||||
// route to fetch one free public claim
|
||||
app.get('/:name/:claim_id', ({ params }, res) => {
|
||||
const routeString = `${params.name}/${params.claim_id}`
|
||||
// google analytics
|
||||
ua(googleAnalyticsId, { https: true }).event('Serve Route', '/name/claimId', routeString).send()
|
||||
// begin image-serve processes
|
||||
console.log(`>> GET request on /${routeString}`)
|
||||
serveController
|
||||
.getClaimByClaimId(params.name, params.claim_id)
|
||||
.then(fileInfo => {
|
||||
console.log('/:name/:claim_id success.', fileInfo.file_name)
|
||||
serveFile(fileInfo, res)
|
||||
})
|
||||
.catch(error => {
|
||||
console.log('/:name/:claim_id error:', error)
|
||||
errorHandlers.handleRequestError(error, res)
|
||||
})
|
||||
})
|
||||
// route to fetch one free public claim
|
||||
app.get('/:name', ({ params }, res) => {
|
||||
// google analytics
|
||||
ua(googleAnalyticsId, { https: true }).event('Serve Route', '/name', params.name).send()
|
||||
// begin image-serve processes
|
||||
console.log(`>> GET request on /${params.name}`)
|
||||
serveController
|
||||
.getClaimByName(params.name)
|
||||
.then(fileInfo => {
|
||||
console.log('/:name success.', fileInfo.file_name)
|
||||
serveFile(fileInfo, res)
|
||||
})
|
||||
.catch(error => {
|
||||
console.log('/:name error:', error)
|
||||
errorHandlers.handleRequestError(error, res)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
|
|
@ -1,22 +1,22 @@
|
|||
var errorHandlers = require("../helpers/libraries/errorHandlers.js");
|
||||
var showController = require("../controllers/showController.js");
|
||||
const errorHandlers = require('../helpers/libraries/errorHandlers.js')
|
||||
const showController = require('../controllers/showController.js')
|
||||
|
||||
module.exports = function(app, ua, googleAnalyticsId){
|
||||
// route to fetch all free public claims
|
||||
app.get("/:name/all", function(req, res){
|
||||
console.log(">> GET request on /" + req.params.name + "/all");
|
||||
// google analytics
|
||||
ua(googleAnalyticsId, {https: true}).event("Show Routes", "/name/all", req.params.name + "/all").send();
|
||||
// fetch all free public claims
|
||||
showController.getAllClaims(req.params.name)
|
||||
.then(function(orderedFreePublicClaims){
|
||||
console.log("/:name/all success.");
|
||||
res.status(200).render('allClaims', { claims: orderedFreePublicClaims });
|
||||
return;
|
||||
})
|
||||
.catch(function(error){
|
||||
console.log("/:name/all error:", error);
|
||||
errorHandlers.handleRequestError(error, res);
|
||||
})
|
||||
});
|
||||
module.exports = (app, ua, googleAnalyticsId) => {
|
||||
// route to fetch all free public claims
|
||||
app.get('/:name/all', ({ params }, res) => {
|
||||
console.log(`>> GET request on /${params.name}/all`)
|
||||
// google analytics
|
||||
ua(googleAnalyticsId, { https: true }).event('Show Routes', '/name/all', `${params.name}/all`).send()
|
||||
// fetch all free public claims
|
||||
showController
|
||||
.getAllClaims(params.name)
|
||||
.then(orderedFreePublicClaims => {
|
||||
console.log('/:name/all success.')
|
||||
res.status(200).render('allClaims', { claims: orderedFreePublicClaims })
|
||||
})
|
||||
.catch(error => {
|
||||
console.log('/:name/all error:', error)
|
||||
errorHandlers.handleRequestError(error, res)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
|
|
@ -1,42 +1,42 @@
|
|||
var publishController = require('../controllers/publishController.js');
|
||||
const publishController = require('../controllers/publishController.js')
|
||||
|
||||
module.exports = function(app, siofu, hostedContentPath, ua, googleAnalyticsId) {
|
||||
var http = require('http').Server(app);
|
||||
var 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');
|
||||
});
|
||||
});
|
||||
module.exports = (app, siofu, hostedContentPath, ua, googleAnalyticsId) => {
|
||||
const http = require('http').Server(app)
|
||||
const io = require('socket.io')(http)
|
||||
|
||||
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
|
||||
}
|
||||
|
|
99
server.js
99
server.js
|
@ -1,69 +1,68 @@
|
|||
// load dependencies
|
||||
var express = require('express');
|
||||
var bodyParser = require('body-parser');
|
||||
var path = require('path');
|
||||
var siofu = require("socketio-file-upload");
|
||||
var expressHandlebars = require("express-handlebars");
|
||||
var Handlebars = require('handlebars');
|
||||
var axios = require('axios');
|
||||
var config = require('config');
|
||||
var ua = require('universal-analytics');
|
||||
const express = require('express')
|
||||
const bodyParser = require('body-parser')
|
||||
const siofu = require('socketio-file-upload')
|
||||
const expressHandlebars = require('express-handlebars')
|
||||
const Handlebars = require('handlebars')
|
||||
const config = require('config')
|
||||
const ua = require('universal-analytics')
|
||||
|
||||
var googleAnalyticsId = config.get('AnalyticsConfig.googleId');
|
||||
var hostedContentPath = config.get('Database.PublishUploadPath');
|
||||
const googleAnalyticsId = config.get('AnalyticsConfig.googleId')
|
||||
const hostedContentPath = config.get('Database.PublishUploadPath')
|
||||
|
||||
// set port
|
||||
var PORT = 3000;
|
||||
const PORT = 3000
|
||||
// initialize express app
|
||||
var app = express();
|
||||
//require our models for syncing
|
||||
var db = require("./models");
|
||||
const app = express()
|
||||
// require our models for syncing
|
||||
const db = require('./models')
|
||||
|
||||
// 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
|
||||
app.use(bodyParser.json()); // for parsing application/json
|
||||
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
|
||||
app.use(siofu.router);
|
||||
app.use(bodyParser.json()) // for parsing application/json
|
||||
app.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
|
||||
app.use(siofu.router)
|
||||
|
||||
// configure handlebars & register it with Express app
|
||||
var hbs = expressHandlebars.create({
|
||||
defaultLayout: 'main', // sets the default layout
|
||||
handlebars: Handlebars, // includes basic handlebars for access to that library
|
||||
helpers: { // define any extra helpers you may need
|
||||
googleAnalytics: function(){
|
||||
var googleApiKey = config.get('AnalyticsConfig.googleId')
|
||||
return new Handlebars.SafeString(`<script>
|
||||
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
|
||||
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
|
||||
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
|
||||
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
|
||||
ga('create', '${googleApiKey}', 'auto');
|
||||
ga('send', 'pageview');
|
||||
</script>`);
|
||||
}
|
||||
}
|
||||
});
|
||||
app.engine('handlebars', hbs.engine);
|
||||
app.set('view engine', 'handlebars');
|
||||
const hbs = expressHandlebars.create({
|
||||
defaultLayout: 'main', // sets the default layout
|
||||
handlebars : Handlebars, // includes basic handlebars for access to that library
|
||||
helpers : {
|
||||
// define any extra helpers you may need
|
||||
googleAnalytics () {
|
||||
const googleApiKey = config.get('AnalyticsConfig.googleId')
|
||||
return new Handlebars.SafeString(
|
||||
`<script>
|
||||
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
|
||||
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
|
||||
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
|
||||
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
|
||||
ga('create', '${googleApiKey}', 'auto');
|
||||
ga('send', 'pageview');
|
||||
</script>`
|
||||
)
|
||||
},
|
||||
},
|
||||
})
|
||||
app.engine('handlebars', hbs.engine)
|
||||
app.set('view engine', 'handlebars')
|
||||
|
||||
// require express routes
|
||||
require("./routes/api-routes.js")(app);
|
||||
require("./routes/show-routes.js")(app, ua, googleAnalyticsId);
|
||||
require("./routes/serve-routes.js")(app, ua, googleAnalyticsId);
|
||||
require("./routes/home-routes.js")(app);
|
||||
require('./routes/api-routes.js')(app)
|
||||
require('./routes/show-routes.js')(app, ua, googleAnalyticsId)
|
||||
require('./routes/serve-routes.js')(app, ua, googleAnalyticsId)
|
||||
require('./routes/home-routes.js')(app)
|
||||
|
||||
// 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
|
||||
// wrap the server in socket.io to intercept incoming sockets requests
|
||||
// start server
|
||||
db.sequelize.sync({})
|
||||
.then(function(){
|
||||
http.listen(PORT, function() {
|
||||
console.log("Listening on PORT " + PORT);
|
||||
});
|
||||
});
|
||||
|
||||
db.sequelize.sync({}).then(() => {
|
||||
http.listen(PORT, () => {
|
||||
console.log(`Listening on PORT ${PORT}`)
|
||||
})
|
||||
})
|
||||
|
|
Loading…
Reference in a new issue