reorganized controllers into folders by route

This commit is contained in:
bill bittner 2018-04-26 23:42:22 -07:00
parent b785edf100
commit dd012282d3
45 changed files with 264 additions and 245 deletions

View file

@ -1,4 +1,4 @@
const { checkChannelAvailability } = require('../../controllers/publishController.js');
const checkChannelAvailability = require('../utils/checkChannelAvailability.js');
const { sendGATimingEvent } = require('../../utils/googleAnalytics.js');
const { handleErrorResponse } = require('../utils/errorHandlers.js');

View file

@ -1,4 +1,4 @@
const { getChannelClaims } = require('../../controllers/serveController.js');
const { getChannelClaims } = require('../utils/serveHelpers.js');
const { handleErrorResponse } = require('../utils/errorHandlers.js');
const NO_CHANNEL = 'NO_CHANNEL';

View file

@ -1,4 +1,4 @@
const { getChannelData } = require('../../controllers/serveController.js');
const { getChannelData } = require('../utils/serveHelpers.js');
const { handleErrorResponse } = require('../utils/errorHandlers.js');
const NO_CHANNEL = 'NO_CHANNEL';

View file

@ -1,5 +1,5 @@
const { handleErrorResponse } = require('../utils/errorHandlers.js');
const db = require('../../models');
const db = require('../../models/index');
/*

View file

@ -1,4 +1,4 @@
const { claimNameIsAvailable } = require('../../controllers/publishController.js');
const checkClaimAvailability = require('../utils/checkClaimAvailability.js');
const { sendGATimingEvent } = require('../../utils/googleAnalytics.js');
const { handleErrorResponse } = require('../utils/errorHandlers.js');
@ -10,7 +10,7 @@ const { handleErrorResponse } = require('../utils/errorHandlers.js');
const claimAvailability = ({ ip, originalUrl, params: { name } }, res) => {
const gaStartTime = Date.now();
claimNameIsAvailable(name)
checkClaimAvailability(name)
.then(result => {
res.status(200).json(result);
sendGATimingEvent('end-to-end', 'claim name availability', name, gaStartTime, Date.now());

View file

@ -1,5 +1,5 @@
const { handleErrorResponse } = require('../utils/errorHandlers.js');
const db = require('../../models');
const db = require('../../models/index');
/*

View file

@ -1,5 +1,5 @@
const { getClaim } = require('../../utils/lbryApi.js');
const { addGetResultsToFileData, createFileData } = require('../../helpers/publishHelpers.js');
const { getClaim } = require('../../lbrynet');
const { addGetResultsToFileData, createFileData } = require('../utils/file.js');
const { handleErrorResponse } = require('../utils/errorHandlers.js');
const db = require('../../models');

View file

@ -1,4 +1,4 @@
const { getClaimList } = require('../../utils/lbryApi.js');
const { getClaimList } = require('../../lbrynet/index');
const { handleErrorResponse } = require('../utils/errorHandlers.js');
/*

View file

@ -1,4 +1,4 @@
const { getClaimId } = require('../../controllers/serveController.js');
const { getClaimId } = require('../utils/serveHelpers.js');
const { handleErrorResponse } = require('../utils/errorHandlers.js');
const NO_CHANNEL = 'NO_CHANNEL';

View file

@ -1,9 +1,15 @@
const { createBasicPublishParams, createThumbnailPublishParams, parsePublishApiRequestBody, parsePublishApiRequestFiles } = require('../../helpers/publishHelpers.js');
const { claimNameIsAvailable, publish } = require('../../controllers/publishController.js');
const { details: { host } } = require('../../../config/siteConfig.js');
const { authenticateUser } = require('../../auth/authentication.js');
const { sendGATimingEvent } = require('../../utils/googleAnalytics.js');
const { handleErrorResponse } = require('../utils/errorHandlers.js');
const { details: { host } } = require('../../../config/siteConfig.js');
const checkClaimAvailability = require('../utils/checkClaimAvailability');
const publish = require('../utils/publish.js');
const {
createBasicPublishParams,
createThumbnailPublishParams,
parsePublishApiRequestBody,
parsePublishApiRequestFiles,
} = require('../utils/publishHelpers.js');
/*
@ -29,7 +35,7 @@ const claimPublish = ({ body, files, headers, ip, originalUrl, user }, res) => {
Promise
.all([
authenticateUser(channelName, channelId, channelPassword, user),
claimNameIsAvailable(name),
checkClaimAvailability(name),
createBasicPublishParams(filePath, name, title, description, license, nsfw, thumbnail),
createThumbnailPublishParams(thumbnailFilePath, name, license, nsfw),
])
@ -39,7 +45,7 @@ const claimPublish = ({ body, files, headers, ip, originalUrl, user }, res) => {
publishParams['channel_name'] = channelName;
publishParams['channel_id'] = channelClaimId;
}
// publish the thumbnail
// publish the thumbnail, if one exists
if (thumbnailPublishParams) {
publish(thumbnailPublishParams, thumbnailFileName, thumbnailFileType);
}

View file

@ -1,4 +1,4 @@
const { resolveUri } = require('../../utils/lbryApi.js');
const { resolveUri } = require('../../lbrynet/index');
const { handleErrorResponse } = require('../utils/errorHandlers.js');
/*

View file

@ -1,5 +1,5 @@
const { handleErrorResponse } = require('../utils/errorHandlers.js');
const db = require('../../models');
const db = require('../../models/index');
/*

View file

@ -1,5 +1,5 @@
const { handleErrorResponse } = require('../utils/errorHandlers.js');
const db = require('../../models');
const db = require('../../models/index');
/*

View file

@ -1,4 +1,4 @@
const speechPassport = require('../../speechPassport');
const speechPassport = require('../../speechPassport/index');
const login = (req, res, next) => {
speechPassport.authenticate('local-login', (err, user, info) => {

View file

@ -1,134 +0,0 @@
const logger = require('winston');
const db = require('../models');
const lbryApi = require('../utils/lbryApi.js');
const publishHelpers = require('../helpers/publishHelpers.js');
const { publishing: { primaryClaimAddress, additionalClaimAddresses } } = require('../../config/siteConfig.js');
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
module.exports = {
publish (publishParams, fileName, fileType) {
return new Promise((resolve, reject) => {
let publishResults, certificateId, channelName;
// publish the file
return lbryApi.publishClaim(publishParams)
.then(tx => {
logger.info(`Successfully published ${publishParams.name} ${fileName}`, tx);
publishResults = tx;
// get the channel information
if (publishParams.channel_name) {
logger.debug(`this claim was published in channel: ${publishParams.channel_name}`);
return db.Channel.findOne({
where: {
channelName: publishParams.channel_name,
},
});
} else {
logger.debug('this claim was not published in a channel');
return null;
}
})
.then(channel => {
// set channel information
certificateId = null;
channelName = null;
if (channel) {
certificateId = channel.channelClaimId;
channelName = channel.channelName;
}
logger.debug(`certificateId: ${certificateId}`);
})
.then(() => {
// create the File record
const fileRecord = {
name : publishParams.name,
claimId : publishResults.claim_id,
title : publishParams.metadata.title,
description: publishParams.metadata.description,
address : publishParams.claim_address,
outpoint : `${publishResults.txid}:${publishResults.nout}`,
height : 0,
fileName,
filePath : publishParams.file_path,
fileType,
nsfw : publishParams.metadata.nsfw,
};
// create the Claim record
const claimRecord = {
name : publishParams.name,
claimId : publishResults.claim_id,
title : publishParams.metadata.title,
description: publishParams.metadata.description,
address : publishParams.claim_address,
thumbnail : publishParams.metadata.thumbnail,
outpoint : `${publishResults.txid}:${publishResults.nout}`,
height : 0,
contentType: fileType,
nsfw : publishParams.metadata.nsfw,
amount : publishParams.bid,
certificateId,
channelName,
};
// upsert criteria
const upsertCriteria = {
name : publishParams.name,
claimId: publishResults.claim_id,
};
// upsert the records
return Promise.all([db.upsert(db.File, fileRecord, upsertCriteria, 'File'), db.upsert(db.Claim, claimRecord, upsertCriteria, 'Claim')]);
})
.then(([file, claim]) => {
logger.debug('File and Claim records successfully created');
return Promise.all([file.setClaim(claim), claim.setFile(file)]);
})
.then(() => {
logger.debug('File and Claim records successfully associated');
resolve(publishResults); // resolve the promise with the result from lbryApi.publishClaim;
})
.catch(error => {
logger.error('PUBLISH ERROR', error);
publishHelpers.deleteTemporaryFile(publishParams.file_path); // delete the local file
reject(error);
});
});
},
claimNameIsAvailable (name) {
const claimAddresses = additionalClaimAddresses || [];
claimAddresses.push(primaryClaimAddress);
// find any records where the name is used
return db.Claim
.findAll({
attributes: ['address'],
where : {
name,
address: {
[Op.or]: claimAddresses,
},
},
})
.then(result => {
if (result.length >= 1) {
throw new Error('That claim is already in use');
};
return name;
})
.catch(error => {
throw error;
});
},
checkChannelAvailability (name) {
return db.Channel
.findAll({
where: { channelName: name },
})
.then(result => {
if (result.length >= 1) {
throw new Error('That channel has already been claimed');
}
return name;
})
.catch(error => {
throw error;
});
},
};

View file

@ -1,19 +0,0 @@
const logger = require('winston');
const db = require('../models');
module.exports = {
getRecentClaims () {
logger.debug('retrieving most recent claims');
return new Promise((resolve, reject) => {
// get the raw requests data
db.File.getRecentClaims()
.then(results => {
resolve(results);
})
.catch(error => {
logger.error('sequelize error', error);
reject(error);
});
});
},
};

View file

@ -4,7 +4,7 @@ module.exports = {
returnPaginatedChannelClaims (channelName, longChannelClaimId, claims, page) {
const totalPages = module.exports.determineTotalPages(claims);
const paginationPage = module.exports.getPageFromQuery(page);
const viewData = {
return {
channelName : channelName,
longChannelClaimId: longChannelClaimId,
claims : module.exports.extractPageFromClaims(claims, paginationPage),
@ -14,7 +14,6 @@ module.exports = {
totalPages : totalPages,
totalResults : module.exports.determineTotalClaims(claims),
};
return viewData;
},
getPageFromQuery (page) {
if (page) {
@ -30,8 +29,7 @@ module.exports = {
// logger.debug(`pageNumber ${pageNumber} is number?`, Number.isInteger(pageNumber));
const claimStartIndex = (pageNumber - 1) * CLAIMS_PER_PAGE;
const claimEndIndex = claimStartIndex + CLAIMS_PER_PAGE;
const pageOfClaims = claims.slice(claimStartIndex, claimEndIndex);
return pageOfClaims;
return claims.slice(claimStartIndex, claimEndIndex);
},
determineTotalPages (claims) {
if (!claims) {

View file

@ -0,0 +1,19 @@
const db = require('../../models');
const checkChannelAvailability = (name) => {
return db.Channel
.findAll({
where: { channelName: name },
})
.then(result => {
if (result.length >= 1) {
throw new Error('That channel has already been claimed');
}
return name;
})
.catch(error => {
throw error;
});
};
module.exports = checkChannelAvailability;

View file

@ -0,0 +1,31 @@
const db = require('../../models/index');
const { publishing: { primaryClaimAddress, additionalClaimAddresses } } = require('../../../config/siteConfig.js');
const Sequelize = require('sequelize');
const Op = Sequelize.Op;
const claimAvailability = (name) => {
const claimAddresses = additionalClaimAddresses || [];
claimAddresses.push(primaryClaimAddress);
// find any records where the name is used
return db.Claim
.findAll({
attributes: ['address'],
where : {
name,
address: {
[Op.or]: claimAddresses,
},
},
})
.then(result => {
if (result.length >= 1) {
throw new Error('That claim is already in use');
}
return name;
})
.catch(error => {
throw error;
});
};
module.exports = claimAvailability;

View file

@ -0,0 +1,13 @@
const logger = require('winston');
const fs = require('fs');
const deleteFile = (filePath) => {
fs.unlink(filePath, err => {
if (err) {
return logger.error(`error deleting temporary file ${filePath}`);
}
logger.debug(`successfully deleted ${filePath}`);
});
};
module.exports = deleteFile;

View file

@ -21,8 +21,8 @@ module.exports = {
message = error.message;
} else {
message = error;
};
};
}
}
return [status, message];
},
useObjectPropertiesIfNoKeys: function (err) {

View file

@ -0,0 +1,20 @@
module.exports = {
addGetResultsToFileData (fileInfo, getResult) {
fileInfo.fileName = getResult.file_name;
fileInfo.filePath = getResult.download_path;
return fileInfo;
},
createFileData ({ name, claimId, outpoint, height, address, nsfw, contentType }) {
return {
name,
claimId,
outpoint,
height,
address,
fileName: '',
filePath: '',
fileType: contentType,
nsfw,
};
},
};

View file

@ -0,0 +1,92 @@
const logger = require('winston');
const db = require('../../models');
const { publishClaim } = require('../../lbrynet');
const deleteFile = require('./deleteFile.js');
const publish = (publishParams, fileName, fileType) => {
return new Promise((resolve, reject) => {
let publishResults, certificateId, channelName;
// publish the file
return publishClaim(publishParams)
.then(tx => {
logger.info(`Successfully published ${publishParams.name} ${fileName}`, tx);
publishResults = tx;
// get the channel information
if (publishParams.channel_name) {
logger.debug(`this claim was published in channel: ${publishParams.channel_name}`);
return db.Channel.findOne({
where: {
channelName: publishParams.channel_name,
},
});
} else {
logger.debug('this claim was not published in a channel');
return null;
}
})
.then(channel => {
// set channel information
certificateId = null;
channelName = null;
if (channel) {
certificateId = channel.channelClaimId;
channelName = channel.channelName;
}
logger.debug(`certificateId: ${certificateId}`);
})
.then(() => {
// create the File record
const fileRecord = {
name : publishParams.name,
claimId : publishResults.claim_id,
title : publishParams.metadata.title,
description: publishParams.metadata.description,
address : publishParams.claim_address,
outpoint : `${publishResults.txid}:${publishResults.nout}`,
height : 0,
fileName,
filePath : publishParams.file_path,
fileType,
nsfw : publishParams.metadata.nsfw,
};
// create the Claim record
const claimRecord = {
name : publishParams.name,
claimId : publishResults.claim_id,
title : publishParams.metadata.title,
description: publishParams.metadata.description,
address : publishParams.claim_address,
thumbnail : publishParams.metadata.thumbnail,
outpoint : `${publishResults.txid}:${publishResults.nout}`,
height : 0,
contentType: fileType,
nsfw : publishParams.metadata.nsfw,
amount : publishParams.bid,
certificateId,
channelName,
};
// upsert criteria
const upsertCriteria = {
name : publishParams.name,
claimId: publishResults.claim_id,
};
// upsert the records
return Promise.all([db.upsert(db.File, fileRecord, upsertCriteria, 'File'), db.upsert(db.Claim, claimRecord, upsertCriteria, 'Claim')]);
})
.then(([file, claim]) => {
logger.debug('File and Claim records successfully created');
return Promise.all([file.setClaim(claim), claim.setFile(file)]);
})
.then(() => {
logger.debug('File and Claim records successfully associated');
resolve(publishResults); // resolve the promise with the result from lbryApi publishClaim;
})
.catch(error => {
logger.error('PUBLISH ERROR', error);
deleteFile(publishParams.file_path); // delete the local file
reject(error);
});
});
};
module.exports = publish;

View file

@ -1,7 +1,5 @@
const logger = require('winston');
const fs = require('fs');
const { details, publishing } = require('../../config/siteConfig.js');
const { details, publishing } = require('../../../config/siteConfig.js');
module.exports = {
parsePublishApiRequestBody ({name, nsfw, license, title, description, thumbnail}) {
@ -146,15 +144,6 @@ module.exports = {
channel_id : publishing.thumbnailChannelId,
};
},
deleteTemporaryFile (filePath) {
fs.unlink(filePath, err => {
if (err) {
logger.error(`error deleting temporary file ${filePath}`);
throw err;
}
logger.debug(`successfully deleted ${filePath}`);
});
},
addGetResultsToFileData (fileInfo, getResult) {
fileInfo.fileName = getResult.file_name;
fileInfo.filePath = getResult.download_path;

View file

@ -1,5 +1,5 @@
const logger = require('winston');
const { getClaimId, getLocalFileRecord } = require('../../controllers/serveController.js');
const { getClaimId, getLocalFileRecord } = require('./serveHelpers.js');
const { handleErrorResponse } = require('./errorHandlers.js');
const SERVE = 'SERVE';

View file

@ -1,6 +1,6 @@
const db = require('../models');
const db = require('../../models/index');
const logger = require('winston');
const { returnPaginatedChannelClaims } = require('./utils/channelPagination.js');
const { returnPaginatedChannelClaims } = require('./channelPagination.js');
const NO_CHANNEL = 'NO_CHANNEL';
const NO_CLAIM = 'NO_CLAIM';

View file

@ -1,24 +1,9 @@
const axios = require('axios');
const logger = require('winston');
const { api: { apiHost, apiPort } } = require('../../config/lbryConfig.js');
const lbryApiUri = 'http://' + apiHost + ':' + apiPort;
const { chooseGaLbrynetPublishLabel, sendGATimingEvent } = require('./googleAnalytics.js');
const handleLbrynetResponse = ({ data }, resolve, reject) => {
logger.debug('lbry api data:', data);
if (data.result) {
// check for an error
if (data.result.error) {
logger.debug('Lbrynet api error:', data.result.error);
reject(new Error(data.result.error));
return;
};
resolve(data.result);
return;
}
// fallback in case it just timed out
reject(JSON.stringify(data));
};
const lbrynetUri = 'http://' + apiHost + ':' + apiPort;
const { chooseGaLbrynetPublishLabel, sendGATimingEvent } = require('../utils/googleAnalytics.js');
const handleLbrynetResponse = require('./utils/handleLbrynetResponse.js');
module.exports = {
publishClaim (publishParams) {
@ -26,7 +11,7 @@ module.exports = {
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbryApiUri, {
.post(lbrynetUri, {
method: 'publish',
params: publishParams,
})
@ -44,7 +29,7 @@ module.exports = {
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbryApiUri, {
.post(lbrynetUri, {
method: 'get',
params: { uri, timeout: 20 },
})
@ -62,7 +47,7 @@ module.exports = {
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbryApiUri, {
.post(lbrynetUri, {
method: 'claim_list',
params: { name: claimName },
})
@ -80,7 +65,7 @@ module.exports = {
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbryApiUri, {
.post(lbrynetUri, {
method: 'resolve',
params: { uri },
})
@ -102,7 +87,7 @@ module.exports = {
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbryApiUri, {
.post(lbrynetUri, {
method: 'settings_get',
})
.then(({ data }) => {
@ -124,7 +109,7 @@ module.exports = {
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbryApiUri, {
.post(lbrynetUri, {
method: 'channel_new',
params: {
channel_name: name,

View file

@ -0,0 +1,19 @@
const logger = require('winston');
const handleLbrynetResponse = ({ data }, resolve, reject) => {
logger.debug('lbry api data:', data);
if (data.result) {
// check for an error
if (data.result.error) {
logger.debug('Lbrynet api error:', data.result.error);
reject(new Error(data.result.error));
return;
};
resolve(data.result);
return;
}
// fallback in case it just timed out
reject(JSON.stringify(data));
};
module.exports = handleLbrynetResponse;

View file

@ -1,16 +1,16 @@
const channelAvailability = require('./channelAvailability');
const channelClaims = require('./channelClaims');
const channelData = require('./channelData');
const channelShortId = require('./channelShortId');
const claimAvailability = require('./claimAvailability');
const claimData = require('./claimData');
const claimGet = require('./claimGet');
const claimLongId = require('./claimLongId');
const claimPublish = require('./claimPublish');
const claimResolve = require('./claimResolve');
const claimShortId = require('./claimShortId');
const claimList = require('./claimList');
const fileAvailability = require('./fileAvailability');
const channelAvailability = require('../../controllers/api/channelAvailability');
const channelClaims = require('../../controllers/api/channelClaims');
const channelData = require('../../controllers/api/channelData');
const channelShortId = require('../../controllers/api/channelShortId');
const claimAvailability = require('../../controllers/api/claimAvailability');
const claimData = require('../../controllers/api/claimData');
const claimGet = require('../../controllers/api/claimGet');
const claimLongId = require('../../controllers/api/claimLongId');
const claimPublish = require('../../controllers/api/claimPublish');
const claimResolve = require('../../controllers/api/claimResolve');
const claimShortId = require('../../controllers/api/claimShortId');
const claimList = require('../../controllers/api/claimList');
const fileAvailability = require('../../controllers/api/fileAvailability');
const multipartMiddleware = require('../utils/multipartMiddleware');

View file

@ -1,5 +1,5 @@
const serveAssetByClaim = require('./serveAssetByClaim');
const serveAssetByIdentifierAndClaim = require('./serveAssetByIdentifierAndClaim');
const serveAssetByClaim = require('../../controllers/assets/serveAssetByClaim');
const serveAssetByIdentifierAndClaim = require('../../controllers/assets/serveAssetByIdentifierAndClaim');
module.exports = (app, db) => {
app.get('/:identifier/:claim', serveAssetByIdentifierAndClaim);

View file

@ -1,8 +1,8 @@
const speechPassport = require('../../speechPassport');
const handleSignupRequest = require('./signup');
const handleLoginRequest = require('./login');
const handleLogoutRequest = require('./logout');
const handleUserRequest = require('./user');
const handleSignupRequest = require('../../controllers/auth/signup');
const handleLoginRequest = require('../../controllers/auth/login');
const handleLogoutRequest = require('../../controllers/auth/logout');
const handleUserRequest = require('../../controllers/auth/user');
module.exports = (app) => {
app.post('/signup', speechPassport.authenticate('local-signup'), handleSignupRequest);

View file

@ -1,4 +1,4 @@
const handlePageRequest = require('./sendReactApp');
const handlePageRequest = require('../../controllers/fallback/sendReactApp');
module.exports = (app) => {
app.get('*', handlePageRequest);

View file

@ -1,6 +1,6 @@
const handlePageRequest = require('./sendReactApp');
const handleEmbedRequest = require('./sendEmbedPage');
const redirect = require('./redirect');
const handlePageRequest = require('../../controllers/pages/sendReactApp');
const handleEmbedRequest = require('../../controllers/pages/sendEmbedPage');
const redirect = require('../../controllers/pages/redirect');
module.exports = (app) => {
app.get('/', handlePageRequest);

View file

@ -1,7 +1,7 @@
const PassportLocalStrategy = require('passport-local').Strategy;
const lbryApi = require('../../utils/lbryApi.js');
const { createChannel } = require('../../lbrynet');
const logger = require('winston');
const db = require('../../models/index');
const db = require('../../models');
module.exports = new PassportLocalStrategy(
{
@ -14,7 +14,7 @@ module.exports = new PassportLocalStrategy(
// server-side validaton of inputs (username, password)
// create the channel and retrieve the metadata
return lbryApi.createChannel(`@${username}`)
return createChannel(`@${username}`)
.then(tx => {
// create user record
const userData = {

View file

@ -2,7 +2,7 @@ const chai = require('chai');
const expect = chai.expect;
describe('publishHelpers.js', function () {
const publishHelpers = require('../../server/helpers/publishHelpers.js');
const publishHelpers = require('../../server/controllers/utils/publishHelpers.js');
describe('#parsePublishApiRequestBody()', function () {
it('should throw an error if no body', function () {