diff --git a/controllers/publishController.js b/controllers/publishController.js index b00329f4..f6e84fac 100644 --- a/controllers/publishController.js +++ b/controllers/publishController.js @@ -3,96 +3,51 @@ const db = require('../models'); const lbryApi = require('../helpers/lbryApi.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 = { publish (publishParams, fileName, fileType) { return new Promise((resolve, reject) => { + let publishResults = {}; // 1. make sure the name is available - checkNameAvailability(publishParams.name) + publishHelpers.checkNameAvailability(publishParams.name) + // 2. publish the file .then(result => { if (result === true) { - // 2. publish the file - 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); - }); + return lbryApi.publishClaim(publishParams); } else { - const err = new Error('That name has already been claimed by spee.ch. Please choose a new claim name.'); - reject(err); + return new Error('That name has already been claimed by spee.ch. Please choose a new claim name.'); } }) + // 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 => { + publishHelpers.deleteTemporaryFile(publishParams.file_path); // delete the local file reject(error); }); }); }, - checkNameAvailability (name) { - return checkNameAvailability(name); - }, }; diff --git a/helpers/publishHelpers.js b/helpers/publishHelpers.js index f54f8b33..63de7afe 100644 --- a/helpers/publishHelpers.js +++ b/helpers/publishHelpers.js @@ -1,6 +1,8 @@ const logger = require('winston'); const config = require('config'); const fs = require('fs'); +const db = require('../models'); +const { getWalletList } = require('./lbryApi.js'); module.exports = { validateFile (file, name, license, nsfw) { @@ -90,4 +92,34 @@ module.exports = { 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); + }); + }); + }, }; diff --git a/models/index.js b/models/index.js index cd09a195..fa8e8606 100644 --- a/models/index.js +++ b/models/index.js @@ -37,15 +37,15 @@ Object.keys(db).forEach(modelName => { } }); -db['upsert'] = (Model, values, condition) => { +db['upsert'] = (Model, values, condition, tableName) => { return Model .findOne({ where: condition }) .then(function (obj) { 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); } 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); } }).catch(function (error) { diff --git a/routes/api-routes.js b/routes/api-routes.js index a2a6955f..ebd385a7 100644 --- a/routes/api-routes.js +++ b/routes/api-routes.js @@ -1,9 +1,9 @@ const logger = require('winston'); const multipart = require('connect-multiparty'); const multipartMiddleware = multipart(); -const publishController = require('../controllers/publishController.js'); -const lbryApi = require('../helpers/lbryApi.js'); -const { createPublishParams, validateFile } = require('../helpers/publishHelpers.js'); +const { publish } = require('../controllers/publishController.js'); +const { getClaimList, resolveUri } = require('../helpers/lbryApi.js'); +const { createPublishParams, validateFile, checkNameAvailability } = require('../helpers/publishHelpers.js'); const errorHandlers = require('../helpers/errorHandlers.js'); const { postToStats, sendGoogleAnalytics } = require('../controllers/statsController.js'); @@ -13,47 +13,44 @@ module.exports = (app, hostedContentPath) => { // google analytics sendGoogleAnalytics('SERVE', headers, ip, originalUrl); // serve the content - lbryApi - .getClaimList(params.name) - .then(claimsList => { - postToStats('serve', originalUrl, ip, null, null, 'success'); - res.status(200).json(claimsList); - }) - .catch(error => { - errorHandlers.handleRequestError('publish', originalUrl, ip, error, res); - }); + getClaimList(params.name) + .then(claimsList => { + postToStats('serve', originalUrl, ip, null, null, 'success'); + res.status(200).json(claimsList); + }) + .catch(error => { + errorHandlers.handleRequestError('publish', originalUrl, ip, error, res); + }); }); // route to check whether spee.ch has published to a claim app.get('/api/isClaimAvailable/:name', ({ ip, originalUrl, params }, res) => { // send response - publishController - .checkNameAvailability(params.name) - .then(result => { - if (result === true) { - res.status(200).json(true); - } else { - logger.debug(`Rejecting publish request because ${params.name} has already been published via spee.ch`); - res.status(200).json(false); - } - }) - .catch(error => { - res.status(500).json(error); - }); + checkNameAvailability(params.name) + .then(result => { + if (result === true) { + res.status(200).json(true); + } else { + logger.debug(`Rejecting publish request because ${params.name} has already been published via spee.ch`); + res.status(200).json(false); + } + }) + .catch(error => { + res.status(500).json(error); + }); }); // route to run a resolve request on the daemon app.get('/api/resolve/:uri', ({ headers, ip, originalUrl, params }, res) => { // google analytics sendGoogleAnalytics('SERVE', headers, ip, originalUrl); // serve content - lbryApi - .resolveUri(params.uri) - .then(resolvedUri => { - postToStats('serve', originalUrl, ip, null, null, 'success'); - res.status(200).json(resolvedUri); - }) - .catch(error => { - errorHandlers.handleRequestError('publish', originalUrl, ip, error, res); - }); + resolveUri(params.uri) + .then(resolvedUri => { + postToStats('serve', originalUrl, ip, null, null, 'success'); + res.status(200).json(resolvedUri); + }) + .catch(error => { + errorHandlers.handleRequestError('publish', originalUrl, ip, error, res); + }); }); // route to run a publish request on the daemon @@ -79,14 +76,13 @@ module.exports = (app, hostedContentPath) => { const fileType = file.type; const publishParams = createPublishParams(name, filePath, license, nsfw); // publish the file - publishController - .publish(publishParams, fileName, fileType) - .then(result => { - postToStats('publish', originalUrl, ip, null, null, 'success'); - res.status(200).json(result); - }) - .catch(error => { - errorHandlers.handleRequestError('publish', originalUrl, ip, error, res); - }); + publish(publishParams, fileName, fileType) + .then(result => { + postToStats('publish', originalUrl, ip, null, null, 'success'); + res.status(200).json(result); + }) + .catch(error => { + errorHandlers.handleRequestError('publish', originalUrl, ip, error, res); + }); }); }; diff --git a/routes/sockets-routes.js b/routes/sockets-routes.js index 5df76845..7a1ade72 100644 --- a/routes/sockets-routes.js +++ b/routes/sockets-routes.js @@ -38,17 +38,16 @@ module.exports = (app, siofu, hostedContentPath) => { // prepare the publish parameters const publishParams = publishHelpers.createPublishParams(file.meta.name, file.pathName, file.meta.license, file.meta.nsfw); // publish the file - publishController - .publish(publishParams, file.name, file.meta.type) - .then(result => { - postToStats('publish', '/', null, null, null, 'success'); - socket.emit('publish-complete', { name: publishParams.name, result }); - }) - .catch(error => { - error = errorHandlers.handlePublishError(error); - postToStats('publish', '/', null, null, null, error); - socket.emit('publish-failure', error); - }); + publishController.publish(publishParams, file.name, file.meta.type) + .then(result => { + postToStats('publish', '/', null, null, null, 'success'); + socket.emit('publish-complete', { name: publishParams.name, result }); + }) + .catch(error => { + error = errorHandlers.handlePublishError(error); + postToStats('publish', '/', null, null, null, error); + socket.emit('publish-failure', error); + }); } else { logger.error(`An error occurred in uploading the client's file`); socket.emit('publish-failure', 'File uploaded, but with errors');