updated publish controller

This commit is contained in:
bill bittner 2017-08-16 11:00:17 -07:00
parent cddd7ac3b2
commit dd762ec10b
5 changed files with 117 additions and 135 deletions

View file

@ -3,96 +3,51 @@ const db = require('../models');
const lbryApi = require('../helpers/lbryApi.js'); const lbryApi = require('../helpers/lbryApi.js');
const publishHelpers = require('../helpers/publishHelpers.js'); const publishHelpers = require('../helpers/publishHelpers.js');
function checkNameAvailability (name) {
return new Promise((resolve, reject) => {
// find any records where the name is used
db.File
.findAll({ where: { name } })
.then(result => {
if (result.length >= 1) {
// filter out any results that were not published from a spee.ch wallet address
lbryApi
.getWalletList()
.then((walletList) => {
const filteredResult = result.filter((claim) => {
return walletList.includes(claim.address);
});
if (filteredResult.length >= 1) {
resolve(false);
} else {
resolve(true);
}
})
.catch((error) => {
reject(error);
});
} else {
resolve(true);
}
})
.catch(error => {
reject(error);
});
});
};
module.exports = { module.exports = {
publish (publishParams, fileName, fileType) { publish (publishParams, fileName, fileType) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let publishResults = {};
// 1. make sure the name is available // 1. make sure the name is available
checkNameAvailability(publishParams.name) publishHelpers.checkNameAvailability(publishParams.name)
// 2. publish the file
.then(result => { .then(result => {
if (result === true) { if (result === true) {
// 2. publish the file return lbryApi.publishClaim(publishParams);
lbryApi
.publishClaim(publishParams)
.then(result => {
logger.info(`Successfully published ${fileName}`, result);
// 3. update old record or create new one (update is in case the claim has been published before by this daemon)
db.upsert(
db.File,
{
name : publishParams.name,
claimId : result.claim_id,
address : publishParams.claim_address,
outpoint: `${result.txid}:${result.nout}`,
height : 0,
fileName,
filePath: publishParams.file_path,
fileType,
nsfw : publishParams.metadata.nsfw,
},
{
name : publishParams.name,
claimId: result.claim_id,
}
).then(() => {
// resolve the promise with the result from lbryApi.publishClaim;
resolve(result);
})
.catch(error => {
logger.error('Sequelize findOne error', error);
// reject the promise
reject(error);
});
})
.catch(error => {
// delete the local file
publishHelpers.deleteTemporaryFile(publishParams.file_path);
// reject the promise
reject(error);
});
} else { } else {
const err = new Error('That name has already been claimed by spee.ch. Please choose a new claim name.'); return new Error('That name has already been claimed by spee.ch. Please choose a new claim name.');
reject(err);
} }
}) })
// 3. upsert File record (update is in case the claim has been published before by this daemon)
.then(result => {
let fileRecord;
let upsertCriteria;
publishResults = result;
logger.info(`Successfully published ${fileName}`, publishResults);
fileRecord = {
name : publishParams.name,
claimId : publishResults.claim_id,
address : publishParams.claim_address,
outpoint: `${publishResults.txid}:${publishResults.nout}`,
height : 0,
fileName,
filePath: publishParams.file_path,
fileType,
nsfw : publishParams.metadata.nsfw,
};
upsertCriteria = {
name : publishParams.name,
claimId: publishResults.claim_id,
};
return Promise.all([db.upsert(db.File, fileRecord, upsertCriteria, 'File'), db.upsert(db.Claim, fileRecord, upsertCriteria, 'Claim')]);
})
.then((fileRecordResults, claimRecordResults) => {
logger.debug('File and Claim records successfully created');
resolve(publishResults); // resolve the promise with the result from lbryApi.publishClaim;
})
.catch(error => { .catch(error => {
publishHelpers.deleteTemporaryFile(publishParams.file_path); // delete the local file
reject(error); reject(error);
}); });
}); });
}, },
checkNameAvailability (name) {
return checkNameAvailability(name);
},
}; };

View file

@ -1,6 +1,8 @@
const logger = require('winston'); const logger = require('winston');
const config = require('config'); const config = require('config');
const fs = require('fs'); const fs = require('fs');
const db = require('../models');
const { getWalletList } = require('./lbryApi.js');
module.exports = { module.exports = {
validateFile (file, name, license, nsfw) { validateFile (file, name, license, nsfw) {
@ -90,4 +92,34 @@ module.exports = {
logger.debug(`successfully deleted ${filePath}`); logger.debug(`successfully deleted ${filePath}`);
}); });
}, },
checkNameAvailability (name) {
return new Promise((resolve, reject) => {
// find any records where the name is used
db.File.findAll({ where: { name } })
.then(result => {
if (result.length >= 1) {
// filter out any results that were not published from a spee.ch wallet address
getWalletList()
.then((walletList) => {
const filteredResult = result.filter((claim) => {
return walletList.includes(claim.address);
});
if (filteredResult.length >= 1) {
resolve(false);
} else {
resolve(true);
}
})
.catch((error) => {
reject(error);
});
} else {
resolve(true);
}
})
.catch(error => {
reject(error);
});
});
},
}; };

View file

@ -37,15 +37,15 @@ Object.keys(db).forEach(modelName => {
} }
}); });
db['upsert'] = (Model, values, condition) => { db['upsert'] = (Model, values, condition, tableName) => {
return Model return Model
.findOne({ where: condition }) .findOne({ where: condition })
.then(function (obj) { .then(function (obj) {
if (obj) { // update if (obj) { // update
logger.silly(`updating ${values.name}:${values.claimId} in File db`); logger.debug(`updating "${values.name}" "${values.claimId}" in db.${tableName}`);
return obj.update(values); return obj.update(values);
} else { // insert } else { // insert
logger.silly(`creating ${values.name}:${values.claimId} in File db`); logger.debug(`creating "${values.name}" "${values.claimId}" in db.${tableName}`);
return Model.create(values); return Model.create(values);
} }
}).catch(function (error) { }).catch(function (error) {

View file

@ -1,9 +1,9 @@
const logger = require('winston'); const logger = require('winston');
const multipart = require('connect-multiparty'); const multipart = require('connect-multiparty');
const multipartMiddleware = multipart(); const multipartMiddleware = multipart();
const publishController = require('../controllers/publishController.js'); const { publish } = require('../controllers/publishController.js');
const lbryApi = require('../helpers/lbryApi.js'); const { getClaimList, resolveUri } = require('../helpers/lbryApi.js');
const { createPublishParams, validateFile } = require('../helpers/publishHelpers.js'); const { createPublishParams, validateFile, checkNameAvailability } = require('../helpers/publishHelpers.js');
const errorHandlers = require('../helpers/errorHandlers.js'); const errorHandlers = require('../helpers/errorHandlers.js');
const { postToStats, sendGoogleAnalytics } = require('../controllers/statsController.js'); const { postToStats, sendGoogleAnalytics } = require('../controllers/statsController.js');
@ -13,47 +13,44 @@ module.exports = (app, hostedContentPath) => {
// google analytics // google analytics
sendGoogleAnalytics('SERVE', headers, ip, originalUrl); sendGoogleAnalytics('SERVE', headers, ip, originalUrl);
// serve the content // serve the content
lbryApi getClaimList(params.name)
.getClaimList(params.name) .then(claimsList => {
.then(claimsList => { postToStats('serve', originalUrl, ip, null, null, 'success');
postToStats('serve', originalUrl, ip, null, null, 'success'); res.status(200).json(claimsList);
res.status(200).json(claimsList); })
}) .catch(error => {
.catch(error => { errorHandlers.handleRequestError('publish', originalUrl, ip, error, res);
errorHandlers.handleRequestError('publish', originalUrl, ip, error, res); });
});
}); });
// route to check whether spee.ch has published to a claim // route to check whether spee.ch has published to a claim
app.get('/api/isClaimAvailable/:name', ({ ip, originalUrl, params }, res) => { app.get('/api/isClaimAvailable/:name', ({ ip, originalUrl, params }, res) => {
// send response // send response
publishController checkNameAvailability(params.name)
.checkNameAvailability(params.name) .then(result => {
.then(result => { if (result === true) {
if (result === true) { res.status(200).json(true);
res.status(200).json(true); } else {
} else { logger.debug(`Rejecting publish request because ${params.name} has already been published via spee.ch`);
logger.debug(`Rejecting publish request because ${params.name} has already been published via spee.ch`); res.status(200).json(false);
res.status(200).json(false); }
} })
}) .catch(error => {
.catch(error => { res.status(500).json(error);
res.status(500).json(error); });
});
}); });
// route to run a resolve request on the daemon // route to run a resolve request on the daemon
app.get('/api/resolve/:uri', ({ headers, ip, originalUrl, params }, res) => { app.get('/api/resolve/:uri', ({ headers, ip, originalUrl, params }, res) => {
// google analytics // google analytics
sendGoogleAnalytics('SERVE', headers, ip, originalUrl); sendGoogleAnalytics('SERVE', headers, ip, originalUrl);
// serve content // serve content
lbryApi resolveUri(params.uri)
.resolveUri(params.uri) .then(resolvedUri => {
.then(resolvedUri => { postToStats('serve', originalUrl, ip, null, null, 'success');
postToStats('serve', originalUrl, ip, null, null, 'success'); res.status(200).json(resolvedUri);
res.status(200).json(resolvedUri); })
}) .catch(error => {
.catch(error => { errorHandlers.handleRequestError('publish', originalUrl, ip, error, res);
errorHandlers.handleRequestError('publish', originalUrl, ip, error, res); });
});
}); });
// route to run a publish request on the daemon // route to run a publish request on the daemon
@ -79,14 +76,13 @@ module.exports = (app, hostedContentPath) => {
const fileType = file.type; const fileType = file.type;
const publishParams = createPublishParams(name, filePath, license, nsfw); const publishParams = createPublishParams(name, filePath, license, nsfw);
// publish the file // publish the file
publishController publish(publishParams, fileName, fileType)
.publish(publishParams, fileName, fileType) .then(result => {
.then(result => { postToStats('publish', originalUrl, ip, null, null, 'success');
postToStats('publish', originalUrl, ip, null, null, 'success'); res.status(200).json(result);
res.status(200).json(result); })
}) .catch(error => {
.catch(error => { errorHandlers.handleRequestError('publish', originalUrl, ip, error, res);
errorHandlers.handleRequestError('publish', originalUrl, ip, error, res); });
});
}); });
}; };

View file

@ -38,17 +38,16 @@ module.exports = (app, siofu, hostedContentPath) => {
// prepare the publish parameters // prepare the publish parameters
const publishParams = publishHelpers.createPublishParams(file.meta.name, file.pathName, file.meta.license, file.meta.nsfw); const publishParams = publishHelpers.createPublishParams(file.meta.name, file.pathName, file.meta.license, file.meta.nsfw);
// publish the file // publish the file
publishController publishController.publish(publishParams, file.name, file.meta.type)
.publish(publishParams, file.name, file.meta.type) .then(result => {
.then(result => { postToStats('publish', '/', null, null, null, 'success');
postToStats('publish', '/', null, null, null, 'success'); socket.emit('publish-complete', { name: publishParams.name, result });
socket.emit('publish-complete', { name: publishParams.name, result }); })
}) .catch(error => {
.catch(error => { error = errorHandlers.handlePublishError(error);
error = errorHandlers.handlePublishError(error); postToStats('publish', '/', null, null, null, error);
postToStats('publish', '/', null, null, null, error); socket.emit('publish-failure', error);
socket.emit('publish-failure', error); });
});
} else { } else {
logger.error(`An error occurred in uploading the client's file`); logger.error(`An error occurred in uploading the client's file`);
socket.emit('publish-failure', 'File uploaded, but with errors'); socket.emit('publish-failure', 'File uploaded, but with errors');