Revert "ES5 require to ES6 import"

This commit is contained in:
jessopb 2019-04-18 11:51:21 -04:00 committed by GitHub
parent 4ced80f4bb
commit 4733264f0e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
119 changed files with 1327 additions and 1412 deletions

120
package-lock.json generated
View file

@ -196,116 +196,6 @@
"@babel/types": "^7.0.0" "@babel/types": "^7.0.0"
} }
}, },
"@babel/helper-create-class-features-plugin": {
"version": "7.3.2",
"resolved": "https://registry.npmjs.org/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.3.2.tgz",
"integrity": "sha512-tdW8+V8ceh2US4GsYdNVNoohq5uVwOf9k6krjwW4E1lINcHgttnWcNqgdoessn12dAy8QkbezlbQh2nXISNY+A==",
"dev": true,
"requires": {
"@babel/helper-function-name": "^7.1.0",
"@babel/helper-member-expression-to-functions": "^7.0.0",
"@babel/helper-optimise-call-expression": "^7.0.0",
"@babel/helper-plugin-utils": "^7.0.0",
"@babel/helper-replace-supers": "^7.2.3"
},
"dependencies": {
"@babel/generator": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.3.3.tgz",
"integrity": "sha512-aEADYwRRZjJyMnKN7llGIlircxTCofm3dtV5pmY6ob18MSIuipHpA2yZWkPlycwu5HJcx/pADS3zssd8eY7/6A==",
"dev": true,
"requires": {
"@babel/types": "^7.3.3",
"jsesc": "^2.5.1",
"lodash": "^4.17.11",
"source-map": "^0.5.0",
"trim-right": "^1.0.1"
},
"dependencies": {
"@babel/types": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.3.3.tgz",
"integrity": "sha512-2tACZ80Wg09UnPg5uGAOUvvInaqLk3l/IAhQzlxLQOIXacr6bMsra5SH6AWw/hIDRCSbCdHP2KzSOD+cT7TzMQ==",
"dev": true,
"requires": {
"esutils": "^2.0.2",
"lodash": "^4.17.11",
"to-fast-properties": "^2.0.0"
}
}
}
},
"@babel/helper-replace-supers": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/@babel/helper-replace-supers/-/helper-replace-supers-7.2.3.tgz",
"integrity": "sha512-GyieIznGUfPXPWu0yLS6U55Mz67AZD9cUk0BfirOWlPrXlBcan9Gz+vHGz+cPfuoweZSnPzPIm67VtQM0OWZbA==",
"dev": true,
"requires": {
"@babel/helper-member-expression-to-functions": "^7.0.0",
"@babel/helper-optimise-call-expression": "^7.0.0",
"@babel/traverse": "^7.2.3",
"@babel/types": "^7.0.0"
}
},
"@babel/parser": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.3.3.tgz",
"integrity": "sha512-xsH1CJoln2r74hR+y7cg2B5JCPaTh+Hd+EbBRk9nWGSNspuo6krjhX0Om6RnRQuIvFq8wVXCLKH3kwKDYhanSg==",
"dev": true
},
"@babel/traverse": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.2.3.tgz",
"integrity": "sha512-Z31oUD/fJvEWVR0lNZtfgvVt512ForCTNKYcJBGbPb1QZfve4WGH8Wsy7+Mev33/45fhP/hwQtvgusNdcCMgSw==",
"dev": true,
"requires": {
"@babel/code-frame": "^7.0.0",
"@babel/generator": "^7.2.2",
"@babel/helper-function-name": "^7.1.0",
"@babel/helper-split-export-declaration": "^7.0.0",
"@babel/parser": "^7.2.3",
"@babel/types": "^7.2.2",
"debug": "^4.1.0",
"globals": "^11.1.0",
"lodash": "^4.17.10"
},
"dependencies": {
"@babel/types": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.3.3.tgz",
"integrity": "sha512-2tACZ80Wg09UnPg5uGAOUvvInaqLk3l/IAhQzlxLQOIXacr6bMsra5SH6AWw/hIDRCSbCdHP2KzSOD+cT7TzMQ==",
"dev": true,
"requires": {
"esutils": "^2.0.2",
"lodash": "^4.17.11",
"to-fast-properties": "^2.0.0"
}
}
}
},
"debug": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
"integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==",
"dev": true,
"requires": {
"ms": "^2.1.1"
}
},
"ms": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz",
"integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==",
"dev": true
},
"source-map": {
"version": "0.5.7",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz",
"integrity": "sha1-igOdLRAh0i0eoUyA2OpGi6LvP8w=",
"dev": true
}
}
},
"@babel/helper-define-map": { "@babel/helper-define-map": {
"version": "7.1.0", "version": "7.1.0",
"resolved": "https://registry.npmjs.org/@babel/helper-define-map/-/helper-define-map-7.1.0.tgz", "resolved": "https://registry.npmjs.org/@babel/helper-define-map/-/helper-define-map-7.1.0.tgz",
@ -532,16 +422,6 @@
"@babel/plugin-syntax-async-generators": "^7.2.0" "@babel/plugin-syntax-async-generators": "^7.2.0"
} }
}, },
"@babel/plugin-proposal-class-properties": {
"version": "7.3.3",
"resolved": "https://registry.npmjs.org/@babel/plugin-proposal-class-properties/-/plugin-proposal-class-properties-7.3.3.tgz",
"integrity": "sha512-XO9eeU1/UwGPM8L+TjnQCykuVcXqaO5J1bkRPIygqZ/A2L1xVMJ9aZXrY31c0U4H2/LHKL4lbFQLsxktSrc/Ng==",
"dev": true,
"requires": {
"@babel/helper-create-class-features-plugin": "^7.3.0",
"@babel/helper-plugin-utils": "^7.0.0"
}
},
"@babel/plugin-proposal-json-strings": { "@babel/plugin-proposal-json-strings": {
"version": "7.2.0", "version": "7.2.0",
"resolved": "https://registry.npmjs.org/@babel/plugin-proposal-json-strings/-/plugin-proposal-json-strings-7.2.0.tgz", "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-json-strings/-/plugin-proposal-json-strings-7.2.0.tgz",

View file

@ -86,7 +86,6 @@
"devDependencies": { "devDependencies": {
"@babel/cli": "^7.1.5", "@babel/cli": "^7.1.5",
"@babel/core": "^7.2.0", "@babel/core": "^7.2.0",
"@babel/plugin-proposal-class-properties": "^7.3.3",
"@babel/plugin-proposal-object-rest-spread": "^7.0.0", "@babel/plugin-proposal-object-rest-spread": "^7.0.0",
"@babel/polyfill": "^7.0.0", "@babel/polyfill": "^7.0.0",
"@babel/preset-env": "^7.2.0", "@babel/preset-env": "^7.2.0",

View file

@ -14,11 +14,12 @@ try {
let currentApp; let currentApp;
try { try {
const Server = require('./server/').default; const Server = require('./server/');
currentApp = Server; currentApp = Server;
const speech = new Server(); const speech = new Server();
speech.start(); speech.start();
} catch (error) { } catch (error) {
console.log('server startup error:', error); console.log('server startup error:', error);
process.exit(1); process.exit(1);

View file

@ -1,5 +1,5 @@
import Sequelize from 'sequelize'; const Sequelize = require('sequelize');
import logger from 'winston'; const logger = require('winston');
import abnormalClaimTable from './tables/abnormalClaimTable'; import abnormalClaimTable from './tables/abnormalClaimTable';
import addressTable from './tables/addressTable'; import addressTable from './tables/addressTable';
@ -22,45 +22,51 @@ import transactionAddressQueries from './queries/transactionAddressQueries';
import transactionQueries from './queries/transactionQueries'; import transactionQueries from './queries/transactionQueries';
const DATABASE_STRUCTURE = { const DATABASE_STRUCTURE = {
abnormal_claim: { 'abnormal_claim': {
table: abnormalClaimTable, table: abnormalClaimTable,
queries: abnormalClaimQueries, queries: abnormalClaimQueries,
}, },
address: { 'address': {
table: addressTable, table: addressTable,
queries: addressQueries, queries: addressQueries,
}, },
block: { 'block': {
table: blockTable, table: blockTable,
queries: blockQueries, queries: blockQueries,
}, },
claim: { 'claim': {
table: claimTable, table: claimTable,
queries: claimQueries, queries: claimQueries,
}, },
input: { 'input': {
table: inputTable, table: inputTable,
queries: inputQueries, queries: inputQueries,
}, },
output: { 'output': {
table: outputTable, table: outputTable,
queries: outputQueries, queries: outputQueries,
}, },
support: { 'support': {
table: supportTable, table: supportTable,
queries: supportQueries, queries: supportQueries,
}, },
transaction_address: { 'transaction_address': {
table: transactionAddressTable, table: transactionAddressTable,
queries: transactionAddressQueries, queries: transactionAddressQueries,
}, },
transaction: { 'transaction': {
table: transactionTable, table: transactionTable,
queries: transactionQueries, queries: transactionQueries,
}, },
}; };
const { host, port, database, username, password } = require('@config/chainqueryConfig'); const {
host,
port,
database,
username,
password,
} = require('@config/chainqueryConfig');
if (!database || !username || !password) { if (!database || !username || !password) {
logger.warn('missing database, user, or password from chainqueryConfig'); logger.warn('missing database, user, or password from chainqueryConfig');
@ -68,17 +74,17 @@ if (!database || !username || !password) {
// set sequelize options // set sequelize options
const sequelize = new Sequelize(database, username, password, { const sequelize = new Sequelize(database, username, password, {
host: host, host : host,
import: port, import : port,
dialect: 'mysql', dialect : 'mysql',
dialectOptions: { dialectOptions: {
decimalNumbers: true, decimalNumbers: true,
}, },
logging: false, logging: false,
pool: { pool : {
max: 5, max : 5,
min: 0, min : 0,
idle: 10000, idle : 10000,
acquire: 10000, acquire: 10000,
}, },
operatorsAliases: false, operatorsAliases: false,
@ -87,7 +93,7 @@ const sequelize = new Sequelize(database, username, password, {
const db = {}; const db = {};
const DATABASE_STRUCTURE_KEYS = Object.keys(DATABASE_STRUCTURE); const DATABASE_STRUCTURE_KEYS = Object.keys(DATABASE_STRUCTURE);
for (let i = 0; i < DATABASE_STRUCTURE_KEYS.length; i++) { for(let i = 0; i < DATABASE_STRUCTURE_KEYS.length; i++) {
let dbKey = DATABASE_STRUCTURE_KEYS[i]; let dbKey = DATABASE_STRUCTURE_KEYS[i];
let currentData = DATABASE_STRUCTURE[dbKey]; let currentData = DATABASE_STRUCTURE[dbKey];

View file

@ -1,5 +1,5 @@
import logger from 'winston'; const logger = require('winston');
import db from 'server/models'; const db = require('../../../models');
const updateBlockedList = (req, res) => { const updateBlockedList = (req, res) => {
db.Blocked.refreshTable() db.Blocked.refreshTable()
@ -19,4 +19,4 @@ const updateBlockedList = (req, res) => {
}); });
}; };
export default updateBlockedList; module.exports = updateBlockedList;

View file

@ -1,17 +1,18 @@
import db from 'server/models'; const db = require('../../../../models');
const checkChannelAvailability = name => { const checkChannelAvailability = (name) => {
return db.Channel.findAll({ return db.Channel
where: { .findAll({
channelName: name, where: {
}, channelName: name,
}) },
})
.then(result => { .then(result => {
return result.length <= 0; return (result.length <= 0);
}) })
.catch(error => { .catch(error => {
throw error; throw error;
}); });
}; };
export default checkChannelAvailability; module.exports = checkChannelAvailability;

View file

@ -1,6 +1,6 @@
import checkChannelAvailability from './checkChannelAvailability.js'; const checkChannelAvailability = require('./checkChannelAvailability.js');
import { sendGATimingEvent } from '@serverutils/googleAnalytics.js'; const { sendGATimingEvent } = require('../../../../utils/googleAnalytics.js');
import { handleErrorResponse } from '../../../utils/errorHandlers.js'; const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
/* /*
@ -8,7 +8,7 @@ import { handleErrorResponse } from '../../../utils/errorHandlers.js';
*/ */
function addAtSymbolIfNecessary(name) { function addAtSymbolIfNecessary (name) {
if (name.substring(0, 1) !== '@') { if (name.substring(0, 1) !== '@') {
return `@${name}`; return `@${name}`;
} }
@ -22,7 +22,7 @@ const channelAvailability = ({ ip, originalUrl, params: { name } }, res) => {
.then(isAvailable => { .then(isAvailable => {
let responseObject = { let responseObject = {
success: true, success: true,
data: isAvailable, data : isAvailable,
}; };
if (isAvailable) { if (isAvailable) {
responseObject['message'] = `${name} is available`; responseObject['message'] = `${name} is available`;
@ -37,4 +37,4 @@ const channelAvailability = ({ ip, originalUrl, params: { name } }, res) => {
}); });
}; };
export default channelAvailability; module.exports = channelAvailability;

View file

@ -1,7 +1,7 @@
import chainquery from 'chainquery'; const chainquery = require('chainquery').default;
import logger from 'winston'; const logger = require('winston');
import getClaimData from 'server/utils/getClaimData'; const getClaimData = require('server/utils/getClaimData');
import { returnPaginatedChannelClaims } from './channelPagination.js'; const { returnPaginatedChannelClaims } = require('./channelPagination.js');
const getChannelClaims = async (channelName, channelLongId, page) => { const getChannelClaims = async (channelName, channelLongId, page) => {
logger.debug(`getChannelClaims: ${channelName}, ${channelLongId}, ${page}`); logger.debug(`getChannelClaims: ${channelName}, ${channelLongId}, ${page}`);
@ -33,4 +33,4 @@ const getChannelClaims = async (channelName, channelLongId, page) => {
return returnPaginatedChannelClaims(channelName, channelShortId, processedChannelClaims, page); return returnPaginatedChannelClaims(channelName, channelShortId, processedChannelClaims, page);
}; };
export default getChannelClaims; module.exports = getChannelClaims;

View file

@ -1,5 +1,5 @@
import { handleErrorResponse } from '../../../utils/errorHandlers.js'; const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
import getChannelClaims from './getChannelClaims.js'; const getChannelClaims = require('./getChannelClaims.js');
const NO_CHANNEL = 'NO_CHANNEL'; const NO_CHANNEL = 'NO_CHANNEL';
@ -16,7 +16,7 @@ const channelClaims = ({ ip, originalUrl, body, params }, res) => {
const page = params.page; const page = params.page;
getChannelClaims(channelName, channelClaimId, page) getChannelClaims(channelName, channelClaimId, page)
.then(data => { .then(data => {
res.status(200).json({ success: true, data }); res.status(200).json({success: true, data});
}) })
.catch(error => { .catch(error => {
if (error === NO_CHANNEL) { if (error === NO_CHANNEL) {
@ -29,4 +29,4 @@ const channelClaims = ({ ip, originalUrl, body, params }, res) => {
}); });
}; };
export default channelClaims; module.exports = channelClaims;

View file

@ -1,25 +1,18 @@
import db from 'server/models'; const db = require('server/models');
import chainquery from 'chainquery'; const chainquery = require('chainquery').default;
const getChannelData = async (channelName, channelClaimId) => { const getChannelData = async (channelName, channelClaimId) => {
let longChannelClaimId = await chainquery.claim.queries let longChannelClaimId = await chainquery.claim.queries.getLongClaimId(channelName, channelClaimId).catch(() => false);
.getLongClaimId(channelName, channelClaimId)
.catch(() => false);
if (!longChannelClaimId) { if (!longChannelClaimId) {
// Allow an error to throw here if this fails // Allow an error to throw here if this fails
longChannelClaimId = await db.Certificate.getLongChannelId(channelName, channelClaimId); longChannelClaimId = await db.Certificate.getLongChannelId(channelName, channelClaimId);
} }
let shortChannelClaimId = await chainquery.claim.queries let shortChannelClaimId = await chainquery.claim.queries.getShortClaimIdFromLongClaimId(longChannelClaimId, channelName).catch(() => false);
.getShortClaimIdFromLongClaimId(longChannelClaimId, channelName)
.catch(() => false);
if (!shortChannelClaimId) { if (!shortChannelClaimId) {
shortChannelClaimId = await db.Certificate.getShortChannelIdFromLongChannelId( shortChannelClaimId = await db.Certificate.getShortChannelIdFromLongChannelId(longChannelClaimId, channelName);
longChannelClaimId,
channelName
);
} }
return { return {
@ -29,4 +22,4 @@ const getChannelData = async (channelName, channelClaimId) => {
}; };
}; };
export default getChannelData; module.exports = getChannelData;

View file

@ -1,8 +1,7 @@
import { handleErrorResponse } from '../../../utils/errorHandlers.js'; const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
import getChannelData from './getChannelData.js'; const getChannelData = require('./getChannelData.js');
import isApprovedChannel from '@globalutils/isApprovedChannel'; const isApprovedChannel = require('../../../../../utils/isApprovedChannel');
import { publishing } from '@config/siteConfig'; const { publishing: { serveOnlyApproved, approvedChannels } } = require('@config/siteConfig');
const { serveOnlyApproved, approvedChannels } = publishing;
const NO_CHANNEL = 'NO_CHANNEL'; const NO_CHANNEL = 'NO_CHANNEL';
const LONG_ID = 'longId'; const LONG_ID = 'longId';
@ -21,9 +20,7 @@ const channelData = ({ ip, originalUrl, body, params }, res) => {
if (channelClaimId === 'none') channelClaimId = null; if (channelClaimId === 'none') channelClaimId = null;
const chanObj = {}; const chanObj = {};
if (channelName) chanObj.name = channelName; if (channelName) chanObj.name = channelName;
if (channelClaimId) { if (channelClaimId) chanObj[(channelClaimId.length === LONG_CLAIM_LENGTH ? LONG_ID : SHORT_ID)] = channelClaimId;
chanObj[channelClaimId.length === LONG_CLAIM_LENGTH ? LONG_ID : SHORT_ID] = channelClaimId;
}
if (serveOnlyApproved && !isApprovedChannel(chanObj, approvedChannels)) { if (serveOnlyApproved && !isApprovedChannel(chanObj, approvedChannels)) {
return res.status(404).json({ return res.status(404).json({
success: false, success: false,
@ -49,4 +46,4 @@ const channelData = ({ ip, originalUrl, body, params }, res) => {
}); });
}; };
export default channelData; module.exports = channelData;

View file

@ -1,6 +1,6 @@
import { handleErrorResponse } from 'server/controllers/utils/errorHandlers.js'; const { handleErrorResponse } = require('server/controllers/utils/errorHandlers.js');
import db from 'server/models'; const db = require('server/models');
import chainquery from 'chainquery'; const chainquery = require('chainquery').default;
/* /*
@ -10,9 +10,7 @@ route to get a short channel id from long channel Id
const channelShortIdRoute = async ({ ip, originalUrl, params }, res) => { const channelShortIdRoute = async ({ ip, originalUrl, params }, res) => {
try { try {
let shortId = await chainquery.claim.queries let shortId = await chainquery.claim.queries.getShortClaimIdFromLongClaimId(params.longId, params.name).catch(() => false);
.getShortClaimIdFromLongClaimId(params.longId, params.name)
.catch(() => false);
if (!shortId) { if (!shortId) {
shortId = await db.Certificate.getShortChannelIdFromLongChannelId(params.longId, params.name); shortId = await db.Certificate.getShortChannelIdFromLongChannelId(params.longId, params.name);
@ -24,4 +22,4 @@ const channelShortIdRoute = async ({ ip, originalUrl, params }, res) => {
} }
}; };
export default channelShortIdRoute; module.exports = channelShortIdRoute;

View file

@ -1,9 +1,9 @@
import logger from 'winston'; const logger = require('winston');
import db from 'server/models'; const db = require('server/models');
import chainquery from 'chainquery'; const chainquery = require('chainquery').default;
import { abandonClaim } from 'server/lbrynet'; const { abandonClaim } = require('server/lbrynet');
import deleteFile from '../publish/deleteFile.js'; const deleteFile = require('../publish/deleteFile.js');
import authenticateUser from '../publish/authentication.js'; const authenticateUser = require('../publish/authentication.js');
/* /*
route to abandon a claim through the daemon route to abandon a claim through the daemon
@ -47,4 +47,4 @@ const claimAbandon = async (req, res) => {
} }
}; };
export default claimAbandon; module.exports = claimAbandon;

View file

@ -1,18 +1,16 @@
import chainquery from 'chainquery'; const chainquery = require('chainquery').default;
import Sequelize from 'sequelize'; const { publishing: { primaryClaimAddress, additionalClaimAddresses } } = require('@config/siteConfig');
const Sequelize = require('sequelize');
import { publishing } from '@config/siteConfig';
const { primaryClaimAddress, additionalClaimAddresses } = publishing;
const Op = Sequelize.Op; const Op = Sequelize.Op;
const claimAvailability = async name => { const claimAvailability = async (name) => {
const claimAddresses = additionalClaimAddresses || []; const claimAddresses = additionalClaimAddresses || [];
claimAddresses.push(primaryClaimAddress); claimAddresses.push(primaryClaimAddress);
// find any records where the name is used // find any records where the name is used
return chainquery.claim return chainquery.claim
.findAll({ .findAll({
attributes: ['claim_address'], attributes: ['claim_address'],
where: { where : {
name, name,
claim_address: { claim_address: {
[Op.or]: claimAddresses, [Op.or]: claimAddresses,
@ -20,11 +18,11 @@ const claimAvailability = async name => {
}, },
}) })
.then(result => { .then(result => {
return result.length <= 0; return (result.length <= 0);
}) })
.catch(error => { .catch(error => {
throw error; throw error;
}); });
}; };
export default claimAvailability; module.exports = claimAvailability;

View file

@ -1,6 +1,6 @@
import checkClaimAvailability from './checkClaimAvailability.js'; const checkClaimAvailability = require('./checkClaimAvailability.js');
import { sendGATimingEvent } from '../../../../utils/googleAnalytics.js'; const { sendGATimingEvent } = require('../../../../utils/googleAnalytics.js');
import { handleErrorResponse } from '../../../utils/errorHandlers.js'; const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
/* /*
@ -14,7 +14,7 @@ const claimAvailability = ({ ip, originalUrl, params: { name } }, res) => {
.then(isAvailable => { .then(isAvailable => {
let responseObject = { let responseObject = {
success: true, success: true,
data: isAvailable, data : isAvailable,
}; };
if (isAvailable) { if (isAvailable) {
responseObject['message'] = `That claim name is available`; responseObject['message'] = `That claim name is available`;
@ -29,4 +29,4 @@ const claimAvailability = ({ ip, originalUrl, params: { name } }, res) => {
}); });
}; };
export default claimAvailability; module.exports = claimAvailability;

View file

@ -1,7 +1,7 @@
import { handleErrorResponse } from '../../../utils/errorHandlers.js'; const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
import getClaimData from 'server/utils/getClaimData'; const getClaimData = require('server/utils/getClaimData');
import fetchClaimData from 'server/utils/fetchClaimData'; const fetchClaimData = require('server/utils/fetchClaimData');
import logger from 'winston'; const logger = require('winston');
/* /*
route to return data for a claim route to return data for a claim
@ -28,4 +28,4 @@ const claimData = async ({ ip, originalUrl, body, params }, res) => {
} }
}; };
export default claimData; module.exports = claimData;

View file

@ -1,13 +1,13 @@
import { createFileRecordDataAfterGet } from 'server/models/utils/createFileRecordData.js';
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
import getClaimData from 'server/utils/getClaimData';
import chainquery from 'chainquery';
import db from 'server/models';
import logger from 'winston';
import awaitFileSize from 'server/utils/awaitFileSize';
import isBot from 'isbot';
import publishCache from 'server/utils/publishCache';
const { getClaim, resolveUri } = require('server/lbrynet'); const { getClaim, resolveUri } = require('server/lbrynet');
const { createFileRecordDataAfterGet } = require('server/models/utils/createFileRecordData.js');
const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
const getClaimData = require('server/utils/getClaimData');
const chainquery = require('chainquery').default;
const db = require('server/models');
const logger = require('winston');
const awaitFileSize = require('server/utils/awaitFileSize');
const isBot = require('isbot');
const publishCache = require('server/utils/publishCache');
const RETRY_MS = 250; const RETRY_MS = 250;
const TIMEOUT_MS = 15000; const TIMEOUT_MS = 15000;
@ -83,4 +83,4 @@ const claimGet = async ({ ip, originalUrl, params, headers }, res) => {
handleErrorResponse(originalUrl, ip, error, res); handleErrorResponse(originalUrl, ip, error, res);
} }
}; };
export default claimGet; module.exports = claimGet;

View file

@ -1,5 +1,5 @@
import { getClaimList } from 'server/lbrynet'; const { getClaimList } = require('../../../../lbrynet');
import { handleErrorResponse } from '../../../utils/errorHandlers.js'; const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
/* /*
@ -17,4 +17,4 @@ const claimList = ({ ip, originalUrl, params }, res) => {
}); });
}; };
export default claimList; module.exports = claimList;

View file

@ -1,10 +1,10 @@
import db from 'server/models'; const db = require('server/models');
import chainquery from 'chainquery'; const chainquery = require('chainquery').default;
import logger from 'winston'; const logger = require('winston');
import publishCache from 'server/utils/publishCache'; const publishCache = require('server/utils/publishCache');
import { handleErrorResponse } from 'server/controllers/utils/errorHandlers.js'; const { handleErrorResponse } = require('server/controllers/utils/errorHandlers.js');
import getClaimId from 'server/controllers/utils/getClaimId.js'; const getClaimId = require('server/controllers/utils/getClaimId.js');
const NO_CHANNEL = 'NO_CHANNEL'; const NO_CHANNEL = 'NO_CHANNEL';
const NO_CLAIM = 'NO_CLAIM'; const NO_CLAIM = 'NO_CLAIM';
@ -72,4 +72,4 @@ const claimLongId = ({ ip, originalUrl, body, params }, res) => {
}); });
}; };
export default claimLongId; module.exports = claimLongId;

View file

@ -1,5 +1,5 @@
import logger from 'winston'; const logger = require('winston');
import db from 'server/models'; const db = require('../../../../models');
const authenticateChannelCredentials = (channelName, channelId, userPassword) => { const authenticateChannelCredentials = (channelName, channelId, userPassword) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -10,9 +10,10 @@ const authenticateChannelCredentials = (channelName, channelId, userPassword) =>
if (channelName) channelFindParams['channelName'] = channelName; if (channelName) channelFindParams['channelName'] = channelName;
if (channelId) channelFindParams['channelClaimId'] = channelId; if (channelId) channelFindParams['channelClaimId'] = channelId;
// find the channel // find the channel
db.Channel.findOne({ db.Channel
where: channelFindParams, .findOne({
}) where: channelFindParams,
})
.then(channel => { .then(channel => {
if (!channel) { if (!channel) {
logger.debug('no channel found'); logger.debug('no channel found');
@ -50,7 +51,7 @@ const authenticateUser = (channelName, channelId, channelPassword, user) => {
// case: no channelName or channel Id are provided (anonymous), regardless of whether user token is provided // case: no channelName or channel Id are provided (anonymous), regardless of whether user token is provided
if (!channelName && !channelId) { if (!channelName && !channelId) {
resolve({ resolve({
channelName: null, channelName : null,
channelClaimId: null, channelClaimId: null,
}); });
return; return;
@ -66,7 +67,7 @@ const authenticateUser = (channelName, channelId, channelPassword, user) => {
return; return;
} }
resolve({ resolve({
channelName: user.channelName, channelName : user.channelName,
channelClaimId: user.channelClaimId, channelClaimId: user.channelClaimId,
}); });
return; return;
@ -80,4 +81,4 @@ const authenticateUser = (channelName, channelId, channelPassword, user) => {
}); });
}; };
export default authenticateUser; module.exports = authenticateUser;

View file

@ -1,5 +1,5 @@
import logger from 'winston'; const logger = require('winston');
import { details, publishing } from '@config/siteConfig'; const { details, publishing } = require('@config/siteConfig');
const createPublishParams = ( const createPublishParams = (
filePath, filePath,
name, name,
@ -59,4 +59,4 @@ const createPublishParams = (
return publishParams; return publishParams;
}; };
export default createPublishParams; module.exports = createPublishParams;

View file

@ -1,5 +1,5 @@
import logger from 'winston'; const logger = require('winston');
import { details, publishing } from '@config/siteConfig'; const { details, publishing } = require('@config/siteConfig');
const createThumbnailPublishParams = (thumbnailFilePath, claimName, license, licenseUrl, nsfw) => { const createThumbnailPublishParams = (thumbnailFilePath, claimName, license, licenseUrl, nsfw) => {
if (!thumbnailFilePath) { if (!thumbnailFilePath) {
@ -26,4 +26,4 @@ const createThumbnailPublishParams = (thumbnailFilePath, claimName, license, lic
}; };
}; };
export default createThumbnailPublishParams; module.exports = createThumbnailPublishParams;

View file

@ -1,7 +1,7 @@
import logger from 'winston'; const logger = require('winston');
import fs from 'fs'; const fs = require('fs');
const deleteFile = filePath => { const deleteFile = (filePath) => {
fs.unlink(filePath, err => { fs.unlink(filePath, err => {
if (err) { if (err) {
return logger.error(`error deleting temporary file ${filePath}`); return logger.error(`error deleting temporary file ${filePath}`);
@ -10,4 +10,4 @@ const deleteFile = filePath => {
}); });
}; };
export default deleteFile; module.exports = deleteFile;

View file

@ -1,33 +1,30 @@
import logger from 'winston'; const logger = require('winston');
import { sendGATimingEvent } from 'server/utils/googleAnalytics.js';
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
import checkClaimAvailability from '../availability/checkClaimAvailability.js';
import publish from './publish.js';
import createPublishParams from './createPublishParams.js';
import createThumbnailPublishParams from './createThumbnailPublishParams.js';
import parsePublishApiRequestBody from './parsePublishApiRequestBody.js';
import parsePublishApiRequestFiles from './parsePublishApiRequestFiles.js';
import authenticateUser from './authentication.js';
import chainquery from 'chainquery';
import publishCache from 'server/utils/publishCache';
import isApprovedChannel from '@globalutils/isApprovedChannel';
import { details, publishing } from '@config/siteConfig';
import createCanonicalLink from '@globalutils/createCanonicalLink';
const { host } = details;
const { const {
disabled, details: { host },
disabledMessage, publishing: { disabled, disabledMessage },
publishOnlyApproved, } = require('@config/siteConfig');
approvedChannels,
thumbnailChannel, const { sendGATimingEvent } = require('server/utils/googleAnalytics.js');
thumbnailChannelId, const isApprovedChannel = require('@globalutils/isApprovedChannel');
} = publishing; const {
publishing: { publishOnlyApproved, approvedChannels, thumbnailChannel, thumbnailChannelId },
} = require('@config/siteConfig');
const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
const checkClaimAvailability = require('../availability/checkClaimAvailability.js');
const publish = require('./publish.js');
const createPublishParams = require('./createPublishParams.js');
const createThumbnailPublishParams = require('./createThumbnailPublishParams.js');
const parsePublishApiRequestBody = require('./parsePublishApiRequestBody.js');
const parsePublishApiRequestFiles = require('./parsePublishApiRequestFiles.js');
const authenticateUser = require('./authentication.js');
const chainquery = require('chainquery').default;
const createCanonicalLink = require('@globalutils/createCanonicalLink');
const publishCache = require('server/utils/publishCache');
const CLAIM_TAKEN = 'CLAIM_TAKEN'; const CLAIM_TAKEN = 'CLAIM_TAKEN';
const UNAPPROVED_CHANNEL = 'UNAPPROVED_CHANNEL'; const UNAPPROVED_CHANNEL = 'UNAPPROVED_CHANNEL';
@ -221,4 +218,4 @@ const claimPublish = ({ body, files, headers, ip, originalUrl, user, tor }, res)
}); });
}; };
export default claimPublish; module.exports = claimPublish;

View file

@ -36,4 +36,4 @@ const parsePublishApiRequestBody = ({
}; };
}; };
export default parsePublishApiRequestBody; module.exports = parsePublishApiRequestBody;

View file

@ -1,14 +1,14 @@
import chai from 'chai'; const chai = require('chai');
const expect = chai.expect; const expect = chai.expect;
describe('#parsePublishApiRequestBody()', function() { describe('#parsePublishApiRequestBody()', function () {
const parsePublishApiRequestBody = require('./parsePublishApiRequestBody.js'); const parsePublishApiRequestBody = require('./parsePublishApiRequestBody.js');
it('should throw an error if no body', function() { it('should throw an error if no body', function () {
expect(parsePublishApiRequestBody.bind(this, null)).to.throw(); expect(parsePublishApiRequestBody.bind(this, null)).to.throw();
}); });
it('should throw an error if no body.name', function() { it('should throw an error if no body.name', function () {
const bodyNoName = {}; const bodyNoName = {};
expect(parsePublishApiRequestBody.bind(this, bodyNoName)).to.throw(); expect(parsePublishApiRequestBody.bind(this, bodyNoName)).to.throw();
}); });

View file

@ -1,6 +1,6 @@
import path from 'path'; const path = require('path');
import validateFileTypeAndSize from './validateFileTypeAndSize.js'; const validateFileTypeAndSize = require('./validateFileTypeAndSize.js');
import validateFileForPublish from './validateFileForPublish.js'; const validateFileForPublish = require('./validateFileForPublish.js');
const parsePublishApiRequestFiles = ({ file, thumbnail }, isUpdate) => { const parsePublishApiRequestFiles = ({ file, thumbnail }, isUpdate) => {
// make sure a file was provided // make sure a file was provided
@ -59,4 +59,4 @@ const parsePublishApiRequestFiles = ({ file, thumbnail }, isUpdate) => {
return obj; return obj;
}; };
export default parsePublishApiRequestFiles; module.exports = parsePublishApiRequestFiles;

View file

@ -1,19 +1,19 @@
import chai from 'chai'; const chai = require('chai');
const expect = chai.expect; const expect = chai.expect;
describe('#parsePublishApiRequestFiles()', function() { describe('#parsePublishApiRequestFiles()', function () {
const parsePublishApiRequestFiles = require('./parsePublishApiRequestFiles.js'); const parsePublishApiRequestFiles = require('./parsePublishApiRequestFiles.js');
it('should throw an error if no files', function() { it('should throw an error if no files', function () {
expect(parsePublishApiRequestFiles.bind(this, null)).to.throw(); expect(parsePublishApiRequestFiles.bind(this, null)).to.throw();
}); });
it('should throw an error if no files.file', function() { it('should throw an error if no files.file', function () {
const filesNoFile = {}; const filesNoFile = {};
expect(parsePublishApiRequestFiles.bind(this, filesNoFile)).to.throw(); expect(parsePublishApiRequestFiles.bind(this, filesNoFile)).to.throw();
}); });
it('should throw an error if file.size is too large', function() { it('should throw an error if file.size is too large', function () {
const filesTooBig = { const filesTooBig = {
file: { file: {
name: 'file.jpg', name: 'file.jpg',
@ -25,7 +25,7 @@ describe('#parsePublishApiRequestFiles()', function() {
expect(parsePublishApiRequestFiles.bind(this, filesTooBig)).to.throw(); expect(parsePublishApiRequestFiles.bind(this, filesTooBig)).to.throw();
}); });
it('should throw error if not an accepted file type', function() { it('should throw error if not an accepted file type', function () {
const filesWrongType = { const filesWrongType = {
file: { file: {
name: 'file.jpg', name: 'file.jpg',
@ -37,7 +37,7 @@ describe('#parsePublishApiRequestFiles()', function() {
expect(parsePublishApiRequestFiles.bind(this, filesWrongType)).to.throw(); expect(parsePublishApiRequestFiles.bind(this, filesWrongType)).to.throw();
}); });
it('should throw NO error if no problems', function() { it('should throw NO error if no problems', function () {
const filesNoProblems = { const filesNoProblems = {
file: { file: {
name: 'file.jpg', name: 'file.jpg',

View file

@ -1,9 +1,11 @@
import logger from 'winston'; const logger = require('winston');
import db from '../../../../models'; const db = require('../../../../models');
import { publishClaim } from '../../../../lbrynet'; const { publishClaim } = require('../../../../lbrynet');
import { createFileRecordDataAfterPublish } from '../../../../models/utils/createFileRecordData.js'; const { createFileRecordDataAfterPublish } = require('server/models/utils/createFileRecordData.js');
import { createClaimRecordDataAfterPublish } from '../../../../models/utils/createClaimRecordData.js'; const {
import deleteFile from './deleteFile.js'; createClaimRecordDataAfterPublish,
} = require('server/models/utils/createClaimRecordData.js');
const deleteFile = require('./deleteFile.js');
const publish = async (publishParams, fileName, fileType) => { const publish = async (publishParams, fileName, fileType) => {
let publishResults; let publishResults;
@ -78,4 +80,5 @@ const publish = async (publishParams, fileName, fileType) => {
}; };
} }
}; };
export default publish;
module.exports = publish;

View file

@ -1,6 +1,6 @@
import logger from 'winston'; const logger = require('winston');
import { publishing } from '@config/siteConfig.json'; const { publishing } = require('@config/siteConfig.json');
const { fileSizeLimits } = publishing; const { fileSizeLimits } = publishing;
@ -35,4 +35,4 @@ const validateFileForPublish = file => {
return file; return file;
}; };
export default validateFileForPublish; module.exports = validateFileForPublish;

View file

@ -1,4 +1,4 @@
import logger from 'winston'; const logger = require('winston');
const { const {
publishing: { maxSizeImage = 10000000, maxSizeGif = 50000000, maxSizeVideo = 50000000 }, publishing: { maxSizeImage = 10000000, maxSizeGif = 50000000, maxSizeVideo = 50000000 },
@ -41,4 +41,4 @@ const validateFileTypeAndSize = file => {
return file; return file;
}; };
export default validateFileTypeAndSize; module.exports = validateFileTypeAndSize;

View file

@ -1,5 +1,5 @@
import { resolveUri } from 'server/lbrynet/index'; const { resolveUri } = require('../../../../lbrynet/index');
import { handleErrorResponse } from '../../../utils/errorHandlers.js'; const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
/* /*
@ -17,4 +17,4 @@ const claimResolve = ({ headers, ip, originalUrl, params }, res) => {
}); });
}; };
export default claimResolve; module.exports = claimResolve;

View file

@ -1,5 +1,5 @@
import { handleErrorResponse } from '../../../utils/errorHandlers.js'; const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
import chainquery from 'chainquery'; const chainquery = require('chainquery').default;
/* /*
@ -22,4 +22,4 @@ const claimShortId = async ({ ip, originalUrl, body, params }, res) => {
} }
}; };
export default claimShortId; module.exports = claimShortId;

View file

@ -1,20 +1,21 @@
import logger from 'winston'; const logger = require('winston');
import { sendGATimingEvent } from '@serverutils/googleAnalytics.js'; const db = require('server/models');
import { handleErrorResponse } from '../../../utils/errorHandlers.js'; const {
import publish from '../publish/publish.js'; details,
import parsePublishApiRequestBody from '../publish/parsePublishApiRequestBody'; publishing: { disabled, disabledMessage, primaryClaimAddress },
import parsePublishApiRequestFiles from '../publish/parsePublishApiRequestFiles.js'; } = require('@config/siteConfig');
import authenticateUser from '../publish/authentication.js'; const { resolveUri } = require('server/lbrynet');
import createThumbnailPublishParams from '../publish/createThumbnailPublishParams.js'; const { sendGATimingEvent } = require('../../../../utils/googleAnalytics.js');
import chainquery from 'chainquery'; const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
import { getFileListFileByOutpoint } from 'server/lbrynet'; const publish = require('../publish/publish.js');
import publishCache from 'server/utils/publishCache'; const parsePublishApiRequestBody = require('../publish/parsePublishApiRequestBody');
import createCanonicalLink from '@globalutils/createCanonicalLink'; const parsePublishApiRequestFiles = require('../publish/parsePublishApiRequestFiles.js');
import isApprovedChannel from '@globalutils/isApprovedChannel'; const authenticateUser = require('../publish/authentication.js');
import { details, publishing } from '@config/siteConfig'; const createThumbnailPublishParams = require('../publish/createThumbnailPublishParams.js');
const { disabled, disabledMessage, primaryClaimAddress } = publishing; const chainquery = require('chainquery').default;
const createCanonicalLink = require('@globalutils/createCanonicalLink');
//, approvedChannels, thumbnailChannel, thumbnailChannelId const { getFileListFileByOutpoint } = require('server/lbrynet');
const publishCache = require('server/utils/publishCache');
/* /*
route to update a claim through the daemon route to update a claim through the daemon
@ -241,4 +242,4 @@ const claimUpdate = ({ body, files, headers, ip, originalUrl, user, tor }, res)
}); });
}; };
export default claimUpdate; module.exports = claimUpdate;

View file

@ -1,5 +1,5 @@
import { handleErrorResponse } from '../../../utils/errorHandlers.js'; const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
import db from 'server/models'; const db = require('server/models');
/* /*
@ -16,7 +16,7 @@ const claimViews = async ({ ip, originalUrl, body, params }, res) => {
res.status(200).json({ res.status(200).json({
success: true, success: true,
data: { data : {
[claimId]: viewCount, [claimId]: viewCount,
}, },
}); });
@ -25,4 +25,4 @@ const claimViews = async ({ ip, originalUrl, body, params }, res) => {
} }
}; };
export default claimViews; module.exports = claimViews;

View file

@ -1,14 +1,12 @@
const { const { publishing: {
publishing: { primaryClaimAddress,
primaryClaimAddress, uploadDirectory,
uploadDirectory, thumbnailChannel,
thumbnailChannel, thumbnailChannelId,
thumbnailChannelId, additionalClaimAddresses,
additionalClaimAddresses, disabled,
disabled, disabledMessage,
disabledMessage, } } = require('@config/siteConfig');
},
} = require('@config/siteConfig');
/* /*
@ -28,4 +26,4 @@ const publishingConfig = (req, res) => {
}); });
}; };
export default publishingConfig; module.exports = publishingConfig;

View file

@ -1,10 +1,10 @@
import logger from 'winston'; const logger = require('winston');
import { handleErrorResponse } from '../../../utils/errorHandlers.js'; const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
import { getFileListFileByOutpoint } from 'server/lbrynet'; const { getFileListFileByOutpoint } = require('server/lbrynet');
import chainquery from 'chainquery'; const chainquery = require('chainquery').default;
import publishCache from 'server/utils/publishCache'; const publishCache = require('server/utils/publishCache');
/* /*
@ -37,4 +37,4 @@ const fileAvailability = async ({ ip, originalUrl, params }, res) => {
} }
}; };
export default fileAvailability; module.exports = fileAvailability;

View file

@ -1,13 +1,16 @@
import db from 'server/models'; const db = require('../../../../models');
const getChannelData = (channelName, channelClaimId) => { const getChannelData = (channelName, channelClaimId) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let longChannelClaimId; let longChannelClaimId;
// 1. get the long channel Id (make sure channel exists) // 1. get the long channel Id (make sure channel exists)
db.Certificate.getLongChannelId(channelName, channelClaimId) db.Certificate
.getLongChannelId(channelName, channelClaimId)
.then(fullClaimId => { .then(fullClaimId => {
longChannelClaimId = fullClaimId; longChannelClaimId = fullClaimId;
return db.Certificate.getShortChannelIdFromLongChannelId(fullClaimId, channelName); return db
.Certificate
.getShortChannelIdFromLongChannelId(fullClaimId, channelName);
}) })
.then(shortChannelClaimId => { .then(shortChannelClaimId => {
resolve({ resolve({
@ -22,4 +25,4 @@ const getChannelData = (channelName, channelClaimId) => {
}); });
}; };
export default getChannelData; module.exports = getChannelData;

View file

@ -1,6 +1,6 @@
import { handleErrorResponse } from '../../../utils/errorHandlers.js'; const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
import getChannelData from './getChannelData.js'; const getChannelData = require('./getChannelData.js');
const NO_CHANNEL = 'NO_CHANNEL'; const NO_CHANNEL = 'NO_CHANNEL';
@ -32,4 +32,4 @@ const channelData = ({ ip, originalUrl, body, params }, res) => {
}); });
}; };
export default channelData; module.exports = channelData;

View file

@ -1,10 +1,11 @@
import logger from 'winston'; const logger = require('winston');
import db from 'server/models'; const db = require('../../../models');
import getClaimId from '../../utils/getClaimId'; const getClaimId = require('../../utils/getClaimId');
import publishCache from 'server/utils/publishCache'; const publishCache = require('server/utils/publishCache');
import { details } from '@config/siteConfig'; const {
const { host, title: siteTitle } = details; details: { host, title: siteTitle },
} = require('@config/siteConfig');
const getOEmbedDataForAsset = (channelName, channelClaimId, claimName, claimId) => { const getOEmbedDataForAsset = (channelName, channelClaimId, claimName, claimId) => {
let fileData, claimData; let fileData, claimData;
@ -65,4 +66,4 @@ const getOEmbedDataForAsset = (channelName, channelClaimId, claimName, claimId)
}); });
}; };
export default getOEmbedDataForAsset; module.exports = getOEmbedDataForAsset;

View file

@ -1,26 +1,33 @@
import db from 'server/models'; const db = require('../../../models');
import { details } from '@config/siteConfig';
const { host, title: siteTitle } = details; const {
details: {
host,
title: siteTitle,
},
} = require('@config/siteConfig');
const getOEmbedDataForChannel = (channelName, channelClaimId) => { const getOEmbedDataForChannel = (channelName, channelClaimId) => {
return db.Certificate.findOne({ return db.Certificate
where: { .findOne({
name: channelName, where: {
claimId: channelClaimId, name : channelName,
}, claimId: channelClaimId,
}).then(certificateRecord => { },
const certificateData = certificateRecord.dataValues; })
return { .then(certificateRecord => {
version: 1.0, const certificateData = certificateRecord.dataValues;
provider_name: siteTitle, return {
provider_url: host, version : 1.0,
type: 'link', provider_name: siteTitle,
author_name: certificateData.name, provider_url : host,
title: `${certificateData.name}'s channel on Spee.ch`, type : 'link',
author_url: `${host}/${certificateData.name}:${certificateData.claimId}`, author_name : certificateData.name,
cache_age: 86400, // one day in seconds title : `${certificateData.name}'s channel on Spee.ch`,
}; author_url : `${host}/${certificateData.name}:${certificateData.claimId}`,
}); cache_age : 86400, // one day in seconds
};
});
}; };
export default getOEmbedDataForChannel; module.exports = getOEmbedDataForChannel;

View file

@ -1,14 +1,12 @@
import logger from 'winston'; const logger = require('winston');
import lbryUri from '@globalutils/lbryUri'; const lbryUri = require('../../../../utils/lbryUri');
import getOEmbedDataForChannel from './getOEmbedDataForChannel'; const getOEmbedDataForChannel = require('./getOEmbedDataForChannel');
import getOEmbedDataForAsset from './getOEmbedDataForAsset'; const getOEmbedDataForAsset = require('./getOEmbedDataForAsset');
import parseSpeechUrl from './parseSpeechUrl'; const parseSpeechUrl = require('./parseSpeechUrl');
const getOEmbedData = (req, res) => { const getOEmbedData = (req, res) => {
const { const { query: { url, format } } = req;
query: { url, format },
} = req;
logger.debug('req url', url); logger.debug('req url', url);
logger.debug('req format', format); logger.debug('req format', format);
@ -38,7 +36,7 @@ const getOEmbedData = (req, res) => {
return res.status(200).json(data); return res.status(200).json(data);
} }
}) })
.catch(error => { .catch((error) => {
return res.status(404).json({ return res.status(404).json({
success: false, success: false,
message: error, message: error,
@ -56,7 +54,7 @@ const getOEmbedData = (req, res) => {
return res.status(200).json(data); return res.status(200).json(data);
} }
}) })
.catch(error => { .catch((error) => {
return res.status(404).json({ return res.status(404).json({
success: false, success: false,
message: error, message: error,
@ -65,4 +63,4 @@ const getOEmbedData = (req, res) => {
} }
}; };
export default getOEmbedData; module.exports = getOEmbedData;

View file

@ -1,10 +1,17 @@
import logger from 'winston'; const logger = require('winston');
const parseSpeechUrl = url => { const parseSpeechUrl = (url) => {
const componentsRegex = new RegExp( const componentsRegex = new RegExp(
'([^:/?#]+://)' + '([^/?#]*)' + '(/)' + '([^/?#]*)' + '(/)' + '([^/?#]*)' '([^:/?#]+://)' +
'([^/?#]*)' +
'(/)' +
'([^/?#]*)' +
'(/)' +
'([^/?#]*)'
); );
const [, , , , paramOne, , paramTwo] = componentsRegex.exec(url).map(match => match || null); const [, , , , paramOne, , paramTwo] = componentsRegex
.exec(url)
.map(match => match || null);
logger.debug(`params from speech url: ${paramOne} ${paramTwo}`); logger.debug(`params from speech url: ${paramOne} ${paramTwo}`);
@ -14,4 +21,4 @@ const parseSpeechUrl = url => {
}; };
}; };
export default parseSpeechUrl; module.exports = parseSpeechUrl;

View file

@ -1,6 +1,6 @@
import { handleErrorResponse } from '../../../utils/errorHandlers.js'; const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
import db from 'server/models'; const db = require('server/models');
import getClaimData from 'server/utils/getClaimData'; const getClaimData = require('server/utils/getClaimData');
/* /*
@ -9,22 +9,25 @@ import getClaimData from 'server/utils/getClaimData';
*/ */
const channelClaims = async ({ ip, originalUrl, body, params }, res) => { const channelClaims = async ({ ip, originalUrl, body, params }, res) => {
const { name, page } = params; const {
name,
page,
} = params;
if (name === 'trending') { if (name === 'trending') {
const result = await db.Trending.getTrendingClaims(); const result = await db.Trending.getTrendingClaims();
const claims = await Promise.all(result.map(claim => getClaimData(claim))); const claims = await Promise.all(result.map((claim) => getClaimData(claim)));
return res.status(200).json({ return res.status(200).json({
success: true, success: true,
data: { data : {
channelName: name, channelName : name,
claims, claims,
longChannelClaimId: name, longChannelClaimId: name,
currentPage: 1, currentPage : 1,
nextPage: null, nextPage : null,
previousPage: null, previousPage : null,
totalPages: 1, totalPages : 1,
totalResults: claims.length, totalResults : claims.length,
}, },
}); });
} }
@ -36,4 +39,4 @@ const channelClaims = async ({ ip, originalUrl, body, params }, res) => {
handleErrorResponse(originalUrl, ip, 'Feature endpoint not found', res); handleErrorResponse(originalUrl, ip, 'Feature endpoint not found', res);
}; };
export default channelClaims; module.exports = channelClaims;

View file

@ -1,5 +1,5 @@
import logger from 'winston'; const logger = require('winston');
import db from 'server/models'; const db = require('../../../models');
/* /*
@ -13,7 +13,7 @@ const getTorList = (req, res) => {
logger.debug('number of records', result.length); logger.debug('number of records', result.length);
res.status(200).json(result); res.status(200).json(result);
}) })
.catch(error => { .catch((error) => {
logger.error(error); logger.error(error);
res.status(500).json({ res.status(500).json({
success: false, success: false,
@ -22,4 +22,4 @@ const getTorList = (req, res) => {
}); });
}; };
export default getTorList; module.exports = getTorList;

View file

@ -1,7 +1,7 @@
import { handleErrorResponse } from '../../../utils/errorHandlers.js'; const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
import logger from 'winston'; const logger = require('winston');
import db from 'server/models'; const db = require('../../../../models');
import { masterPassword } from '@private/authConfig.json'; const { masterPassword } = require('@private/authConfig.json');
/* /*
route to update a password route to update a password
@ -22,8 +22,7 @@ const updateUserPassword = ({ ip, originalUrl, body }, res) => {
if (!userName || !oldPassword || !newPassword) { if (!userName || !oldPassword || !newPassword) {
return res.status(400).json({ return res.status(400).json({
success: false, success: false,
message: message: 'body should include userName (channel name without the @), oldPassword, & newPassword',
'body should include userName (channel name without the @), oldPassword, & newPassword',
}); });
} }
@ -61,9 +60,9 @@ const updateUserPassword = ({ ip, originalUrl, body }, res) => {
newPassword, newPassword,
}); });
}) })
.catch(error => { .catch((error) => {
handleErrorResponse(originalUrl, ip, error, res); handleErrorResponse(originalUrl, ip, error, res);
}); });
}; };
export default updateUserPassword; module.exports = updateUserPassword;

View file

@ -1,5 +1,5 @@
import { sendGAServeEvent } from '@serverutils/googleAnalytics'; const { sendGAServeEvent } = require('../../../utils/googleAnalytics');
import getClaimIdAndServeAsset from '../utils/getClaimIdAndServeAsset.js'; const getClaimIdAndServeAsset = require('../utils/getClaimIdAndServeAsset.js');
/* /*
@ -14,4 +14,4 @@ const serveAsset = ({ headers, ip, originalUrl, params: { claimName, claimId } }
getClaimIdAndServeAsset(null, null, claimName, claimId, originalUrl, ip, res, headers); getClaimIdAndServeAsset(null, null, claimName, claimId, originalUrl, ip, res, headers);
}; };
export default serveAsset; module.exports = serveAsset;

View file

@ -1,14 +1,14 @@
import logger from 'winston'; const logger = require('winston');
import { sendGAServeEvent } from '@serverutils/googleAnalytics'; const { sendGAServeEvent } = require('../../../utils/googleAnalytics');
import handleShowRender from 'server/render/handleShowRender'; const handleShowRender = require('../../../render/handleShowRender').default;
import lbryUri from '@globalutils/lbryUri.js'; const lbryUri = require('../../../../utils/lbryUri.js');
import determineRequestType from '../utils/determineRequestType.js'; const determineRequestType = require('../utils/determineRequestType.js');
import getClaimIdAndServeAsset from '../utils/getClaimIdAndServeAsset.js'; const getClaimIdAndServeAsset = require('../utils/getClaimIdAndServeAsset.js');
import { SHOW } from '../constants/request_types.js'; const { SHOW } = require('../constants/request_types.js');
/* /*
@ -41,8 +41,8 @@ const serveByClaim = (req, res) => {
sendGAServeEvent(headers, ip, originalUrl); sendGAServeEvent(headers, ip, originalUrl);
} catch (error) { } catch (error) {
return res.status(400).json({ success: false, message: error.message }); return res.status(400).json({success: false, message: error.message});
} }
}; };
export default serveByClaim; module.exports = serveByClaim;

View file

@ -1,15 +1,15 @@
import logger from 'winston'; const logger = require('winston');
import { sendGAServeEvent } from 'server/utils/googleAnalytics'; const { sendGAServeEvent } = require('../../../utils/googleAnalytics');
import handleShowRender from 'server/render/handleShowRender'; const handleShowRender = require('../../../render/handleShowRender').default;
import lbryUri from '@globalutils/lbryUri.js'; const lbryUri = require('../../../../utils/lbryUri.js');
import determineRequestType from '../utils/determineRequestType.js'; const determineRequestType = require('../utils/determineRequestType.js');
import getClaimIdAndServeAsset from '../utils/getClaimIdAndServeAsset.js'; const getClaimIdAndServeAsset = require('../utils/getClaimIdAndServeAsset.js');
import flipClaimNameAndId from '../utils/flipClaimNameAndId.js'; const flipClaimNameAndId = require('../utils/flipClaimNameAndId.js');
import { SHOW } from '../constants/request_types.js'; const { SHOW } = require('../constants/request_types.js');
/* /*
@ -30,9 +30,7 @@ const serverByIdentifierAndClaim = (req, res) => {
} }
({ claimName } = lbryUri.parseClaim(params.claim)); ({ claimName } = lbryUri.parseClaim(params.claim));
({ isChannel, channelName, channelClaimId, claimId } = lbryUri.parseIdentifier( ({ isChannel, channelName, channelClaimId, claimId } = lbryUri.parseIdentifier(params.identifier));
params.identifier
));
if (!isChannel) { if (!isChannel) {
[claimId, claimName] = flipClaimNameAndId(claimId, claimName); [claimId, claimName] = flipClaimNameAndId(claimId, claimName);
@ -49,21 +47,12 @@ const serverByIdentifierAndClaim = (req, res) => {
claimId, claimId,
}); });
getClaimIdAndServeAsset( getClaimIdAndServeAsset(channelName, channelClaimId, claimName, claimId, originalUrl, ip, res, headers);
channelName,
channelClaimId,
claimName,
claimId,
originalUrl,
ip,
res,
headers
);
sendGAServeEvent(headers, ip, originalUrl); sendGAServeEvent(headers, ip, originalUrl);
} catch (error) { } catch (error) {
return res.status(400).json({ success: false, message: error.message }); return res.status(400).json({success: false, message: error.message});
} }
}; };
export default serverByIdentifierAndClaim; module.exports = serverByIdentifierAndClaim;

View file

@ -1,6 +1,6 @@
import { SERVE, SHOW } from '../constants/request_types.js'; const { SERVE, SHOW } = require('../constants/request_types.js');
function clientWantsAsset({ accept, range }) { function clientWantsAsset ({accept, range}) {
const imageIsWanted = accept && accept.match(/image\/.*/) && !accept.match(/text\/html/); const imageIsWanted = accept && accept.match(/image\/.*/) && !accept.match(/text\/html/);
const videoIsWanted = accept && accept.match(/video\/.*/) && !accept.match(/text\/html/); const videoIsWanted = accept && accept.match(/video\/.*/) && !accept.match(/text\/html/);
return imageIsWanted || videoIsWanted; return imageIsWanted || videoIsWanted;
@ -13,4 +13,4 @@ const determineRequestType = (hasFileExtension, headers) => {
return SHOW; return SHOW;
}; };
export default determineRequestType; module.exports = determineRequestType;

View file

@ -1,14 +1,14 @@
function isValidClaimId(claimId) { function isValidClaimId (claimId) {
return claimId.length === 40 && !/[^A-Za-z0-9]/g.test(claimId); return ((claimId.length === 40) && !/[^A-Za-z0-9]/g.test(claimId));
} };
function isValidShortId(claimId) { function isValidShortId (claimId) {
return claimId.length === 1; // it should really evaluate the short url itself return claimId.length === 1; // it should really evaluate the short url itself
} };
function isValidShortIdOrClaimId(input) { function isValidShortIdOrClaimId (input) {
return isValidClaimId(input) || isValidShortId(input); return (isValidClaimId(input) || isValidShortId(input));
} };
const flipClaimNameAndId = (identifier, name) => { const flipClaimNameAndId = (identifier, name) => {
// this is a patch for backwards compatability with '/name/claimId' url format // this is a patch for backwards compatability with '/name/claimId' url format
@ -20,4 +20,4 @@ const flipClaimNameAndId = (identifier, name) => {
return [identifier, name]; return [identifier, name];
}; };
export default flipClaimNameAndId; module.exports = flipClaimNameAndId;

View file

@ -1,20 +1,16 @@
import logger from 'winston'; const logger = require('winston');
import db from 'server/models'; const db = require('server/models');
import chainquery from 'chainquery'; const chainquery = require('chainquery').default;
import { getFileListFileByOutpoint, getClaim } from 'server/lbrynet'; const isApprovedChannel = require('@globalutils/isApprovedChannel');
import getClaimId from '../../utils/getClaimId.js'; const { getFileListFileByOutpoint, getClaim } = require('server/lbrynet');
import { handleErrorResponse } from '../../utils/errorHandlers.js'; const getClaimId = require('../../utils/getClaimId.js');
import awaitFileSize from 'server/utils/awaitFileSize'; const { handleErrorResponse } = require('../../utils/errorHandlers.js');
import serveFile from './serveFile.js'; const awaitFileSize = require('server/utils/awaitFileSize');
import parseQueryString from 'server/utils/parseQuerystring'; const serveFile = require('./serveFile.js');
import publishCache from 'server/utils/publishCache'; const parseQueryString = require('server/utils/parseQuerystring');
import isBot from 'isbot'; const publishCache = require('server/utils/publishCache');
import isApprovedChannel from '@globalutils/isApprovedChannel'; const isBot = require('isbot');
import { publishing } from '@config/siteConfig';
const { serveOnlyApproved, approvedChannels } = publishing;
const NO_CHANNEL = 'NO_CHANNEL'; const NO_CHANNEL = 'NO_CHANNEL';
const NO_CLAIM = 'NO_CLAIM'; const NO_CLAIM = 'NO_CLAIM';
@ -26,6 +22,10 @@ const RETRY_MS = 250;
const TIMEOUT_MS = 15000; const TIMEOUT_MS = 15000;
const MIN_BYTES = 15000000; const MIN_BYTES = 15000000;
const {
publishing: { serveOnlyApproved, approvedChannels },
} = require('@config/siteConfig');
const getClaimIdAndServeAsset = async ( const getClaimIdAndServeAsset = async (
channelName, channelName,
channelClaimId, channelClaimId,
@ -125,4 +125,4 @@ const getClaimIdAndServeAsset = async (
} }
}; };
export default getClaimIdAndServeAsset; module.exports = getClaimIdAndServeAsset;

View file

@ -1,14 +1,15 @@
import db from 'server/models'; const db = require('../../../models');
const NO_FILE = 'NO_FILE'; const NO_FILE = 'NO_FILE';
const getLocalFileRecord = (claimId, name) => { const getLocalFileRecord = (claimId, name) => {
return db.File.findOne({ where: { claimId, name } }).then(file => { return db.File.findOne({where: {claimId, name}})
if (!file) { .then(file => {
return NO_FILE; if (!file) {
} return NO_FILE;
return file.dataValues; }
}); return file.dataValues;
});
}; };
export default getLocalFileRecord; module.exports = getLocalFileRecord;

View file

@ -1,4 +1,4 @@
import logger from 'winston'; const logger = require('winston');
const logRequestData = (responseType, claimName, channelName, claimId) => { const logRequestData = (responseType, claimName, channelName, claimId) => {
logger.debug('responseType ===', responseType); logger.debug('responseType ===', responseType);
@ -7,4 +7,4 @@ const logRequestData = (responseType, claimName, channelName, claimId) => {
logger.debug('claim id ===', claimId); logger.debug('claim id ===', claimId);
}; };
export default logRequestData; module.exports = logRequestData;

View file

@ -1,10 +1,10 @@
import logger from 'winston'; const logger = require('winston');
import transformImage from './transformImage'; const transformImage = require('./transformImage');
import parseQueryString from 'server/utils/parseQuerystring'; const parseQueryString = require('server/utils/parseQuerystring');
import isValidQueryObject from 'server/utils/isValidQueryObj'; const isValidQueryObject = require('server/utils/isValidQueryObj');
import { serving } from '@config/siteConfig'; const {
const { dynamicFileSizing } = serving; serving: { dynamicFileSizing },
} = require('@config/siteConfig');
const { enabled: dynamicEnabled } = dynamicFileSizing; const { enabled: dynamicEnabled } = dynamicFileSizing;
const serveFile = async ( const serveFile = async (
@ -57,4 +57,4 @@ const serveFile = async (
} }
}; };
export default serveFile; module.exports = serveFile;

View file

@ -1,9 +1,9 @@
import gm from 'gm'; const gm = require('gm');
import logger from 'winston'; const logger = require('winston');
import { getImageHeightAndWidth } from '@serverutils/imageProcessing';
const imageMagick = gm.subClass({ imageMagick: true }); const imageMagick = gm.subClass({ imageMagick: true });
const { getImageHeightAndWidth } = require('../../../utils/imageProcessing');
export default function transformImage(path, queryObj) { module.exports = function transformImage(path, queryObj) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let { h: cHeight = null } = queryObj; let { h: cHeight = null } = queryObj;
let { w: cWidth = null } = queryObj; let { w: cWidth = null } = queryObj;
@ -39,7 +39,7 @@ export default function transformImage(path, queryObj) {
reject(e); reject(e);
} }
}); });
} };
function _cropCenter(path, cropWidth, cropHeight, originalWidth, originalHeight) { function _cropCenter(path, cropWidth, cropHeight, originalWidth, originalHeight) {
let oAspect = originalWidth / originalHeight; let oAspect = originalWidth / originalHeight;

View file

@ -1,4 +1,4 @@
import speechPassport from 'server/speechPassport/index'; const speechPassport = require('../../../speechPassport/index');
const login = (req, res, next) => { const login = (req, res, next) => {
speechPassport.authenticate('local-login', (err, user, info) => { speechPassport.authenticate('local-login', (err, user, info) => {
@ -11,13 +11,13 @@ const login = (req, res, next) => {
message: info.message, message: info.message,
}); });
} }
req.logIn(user, err => { req.logIn(user, (err) => {
if (err) { if (err) {
return next(err); return next(err);
} }
return res.status(200).json({ return res.status(200).json({
success: true, success : true,
channelName: req.user.channelName, channelName : req.user.channelName,
channelClaimId: req.user.channelClaimId, channelClaimId: req.user.channelClaimId,
shortChannelId: req.user.shortChannelId, shortChannelId: req.user.shortChannelId,
}); });
@ -25,4 +25,4 @@ const login = (req, res, next) => {
})(req, res, next); })(req, res, next);
}; };
export default login; module.exports = login;

View file

@ -7,4 +7,4 @@ const logout = (req, res) => {
res.status(200).json(responseObject); res.status(200).json(responseObject);
}; };
export default logout; module.exports = logout;

View file

@ -1,10 +1,10 @@
const signup = (req, res) => { const signup = (req, res) => {
res.status(200).json({ res.status(200).json({
success: true, success : true,
channelName: req.user.channelName, channelName : req.user.channelName,
channelClaimId: req.user.channelClaimId, channelClaimId: req.user.channelClaimId,
shortChannelId: req.user.shortChannelId, shortChannelId: req.user.shortChannelId,
}); });
}; };
export default signup; module.exports = signup;

View file

@ -1,9 +1,9 @@
const user = (req, res) => { const user = (req, res) => {
const responseObject = { const responseObject = {
success: true, success: true,
data: req.user, data : req.user,
}; };
res.status(200).json(responseObject); res.status(200).json(responseObject);
}; };
export default user; module.exports = user;

View file

@ -1,40 +1,42 @@
import { assetDefaults, details } from '@config/siteConfig'; const {
const { thumbnail } = assetDefaults; assetDefaults: { thumbnail },
const { host } = details; details: { host },
} = require('@config/siteConfig');
const padSizes = { const padSizes = {
small: 'padSmall', small : 'padSmall',
medium: 'padMedium', medium: 'padMedium',
large: 'padLarge', large : 'padLarge',
}; };
const argumentProcessors = { const argumentProcessors = {
bottom: async config => { 'bottom': async (config) => {
config.classNames.push('bottom'); config.classNames.push('bottom');
}, },
right: async config => { 'right': async (config) => {
config.classNames.push('right'); config.classNames.push('right');
}, },
pad: async (config, val) => { 'pad': async (config, val) => {
config.classNames.push(padSizes[val]); config.classNames.push(padSizes[val]);
}, },
logoClaim: async (config, val) => { 'logoClaim': async (config, val) => {
config.logoUrl = `${host}/${val}`; config.logoUrl = `${host}/${val}`;
}, },
link: async (config, val) => { 'link': async (config, val) => {
config.logoLink = val; config.logoLink = val;
}, },
}; };
const parseLogoConfigParam = async rawConfig => { const parseLogoConfigParam = async (rawConfig) => {
if (rawConfig) { if (rawConfig) {
let parsedConfig = { let parsedConfig = {
classNames: ['logoLink'], classNames: ['logoLink'],
logoUrl: thumbnail, logoUrl : thumbnail,
}; };
let splitConfig; let splitConfig;
try { try {
splitConfig = rawConfig.split(','); splitConfig = rawConfig.split(',');
} catch (e) {} } catch (e) { }
if (!splitConfig) { if (!splitConfig) {
return false; return false;
@ -62,7 +64,11 @@ const parseLogoConfigParam = async rawConfig => {
}; };
const sendVideoEmbedPage = async ({ params }, res) => { const sendVideoEmbedPage = async ({ params }, res) => {
let { claimId, config, name } = params; let {
claimId,
config,
name,
} = params;
// if channel then swap name and claimId for order // if channel then swap name and claimId for order
if (name[0] === '@' && name.includes(':')) { if (name[0] === '@' && name.includes(':')) {
@ -80,4 +86,4 @@ const sendVideoEmbedPage = async ({ params }, res) => {
res.status(200).render('embed', { host, claimId, name, logoConfig }); res.status(200).render('embed', { host, claimId, name, logoConfig });
}; };
export default sendVideoEmbedPage; module.exports = sendVideoEmbedPage;

View file

@ -1,44 +1,45 @@
import logger from 'winston'; const logger = require('winston');
export function handleErrorResponse(originalUrl, ip, error, res) { module.exports = {
logger.error(`Error on ${originalUrl}`, useObjectPropertiesIfNoKeys(error)); handleErrorResponse: function (originalUrl, ip, error, res) {
const [status, message] = returnErrorMessageAndStatus(error); logger.error(`Error on ${originalUrl}`, module.exports.useObjectPropertiesIfNoKeys(error));
res.status(status).json(createErrorResponsePayload(status, message)); const [status, message] = module.exports.returnErrorMessageAndStatus(error);
} res
.status(status)
export function returnErrorMessageAndStatus(error) { .json(module.exports.createErrorResponsePayload(status, message));
let status, message; },
// check for daemon being turned off returnErrorMessageAndStatus: function (error) {
if (error.code === 'ECONNREFUSED') { let status, message;
status = 503; // check for daemon being turned off
message = 'Connection refused. The daemon may not be running.'; if (error.code === 'ECONNREFUSED') {
// fallback for everything else status = 503;
} else { message = 'Connection refused. The daemon may not be running.';
status = 400; // fallback for everything else
if (error.message) {
message = error.message;
} else { } else {
message = error; status = 400;
if (error.message) {
message = error.message;
} else {
message = error;
}
} }
} return [status, message];
return [status, message]; },
} useObjectPropertiesIfNoKeys: function (err) {
if (Object.keys(err).length === 0) {
export function useObjectPropertiesIfNoKeys(err) { let newErrorObject = {};
if (Object.keys(err).length === 0) { Object.getOwnPropertyNames(err).forEach((key) => {
let newErrorObject = {}; newErrorObject[key] = err[key];
Object.getOwnPropertyNames(err).forEach(key => { });
newErrorObject[key] = err[key]; return newErrorObject;
}); }
return newErrorObject; return err;
} },
return err; createErrorResponsePayload (status, message) {
} return {
status,
function createErrorResponsePayload(status, message) { success: false,
return { message,
status, };
success: false, },
message, };
};
}

View file

@ -1,8 +1,8 @@
import logger from 'winston'; const logger = require('winston');
import db from 'server/models'; const db = require('../../models');
import chainquery from 'chainquery'; const chainquery = require('chainquery').default;
import publishCache from 'server/utils/publishCache'; const publishCache = require('server/utils/publishCache');
import createCanonicalLink from '@globalutils/createCanonicalLink'; const createCanonicalLink = require('@globalutils/createCanonicalLink');
const getClaimIdByChannel = async (channelName, channelClaimId, claimName) => { const getClaimIdByChannel = async (channelName, channelClaimId, claimName) => {
logger.debug(`getClaimIdByChannel(${channelName}, ${channelClaimId}, ${claimName})`); logger.debug(`getClaimIdByChannel(${channelName}, ${channelClaimId}, ${claimName})`);
@ -36,4 +36,4 @@ const getClaimId = async (channelName, channelClaimId, name, claimId) => {
} }
}; };
export default getClaimId; module.exports = getClaimId;

View file

@ -1,7 +1,7 @@
const redirect = route => { const redirect = (route) => {
return (req, res) => { return (req, res) => {
res.status(301).redirect(route); res.status(301).redirect(route);
}; };
}; };
export default redirect; module.exports = redirect;

View file

@ -1,33 +1,36 @@
// load modules // load modules
import express from 'express'; const express = require('express');
import bodyParser from 'body-parser'; const bodyParser = require('body-parser');
import expressHandlebars from 'express-handlebars'; const expressHandlebars = require('express-handlebars');
import helmet from 'helmet'; const helmet = require('helmet');
import cookieSession from 'cookie-session'; const cookieSession = require('cookie-session');
import http from 'http'; const http = require('http');
import logger from 'winston'; const logger = require('winston');
import Path from 'path'; const Path = require('path');
import httpContext from 'express-http-context'; const httpContext = require('express-http-context');
// load local modules // load local modules
import db from './models'; const db = require('./models');
import requestLogger from './middleware/requestLogger'; const requestLogger = require('./middleware/requestLogger');
import createDatabaseIfNotExists from './models/utils/createDatabaseIfNotExists'; const createDatabaseIfNotExists = require('./models/utils/createDatabaseIfNotExists');
import { getAccountBalance } from './lbrynet/index'; const { getAccountBalance } = require('./lbrynet/index');
import configureLogging from './utils/configureLogging'; const configureLogging = require('./utils/configureLogging');
import configureSlack from './utils/configureSlack'; const configureSlack = require('./utils/configureSlack');
import { setupBlockList } from './utils/blockList'; const { setupBlockList } = require('./utils/blockList');
import speechPassport from './speechPassport'; const speechPassport = require('./speechPassport');
import processTrending from './utils/processTrending'; const processTrending = require('./utils/processTrending');
import { const {
logMetricsMiddleware, logMetricsMiddleware,
setRouteDataInContextMiddleware, setRouteDataInContextMiddleware,
} from './middleware/logMetricsMiddleware'; } = require('./middleware/logMetricsMiddleware');
import { sessionKey } from '@private/authConfig.json';
import { details, startup } from '@config/siteConfig'; const {
const { port: PORT, blockListEndpoint } = details; details: { port: PORT, blockListEndpoint },
const { performChecks, performUpdates } = startup; startup: { performChecks, performUpdates },
} = require('@config/siteConfig');
const { sessionKey } = require('@private/authConfig.json');
// configure.js doesn't handle new keys in config.json files yet. Make sure it doens't break. // configure.js doesn't handle new keys in config.json files yet. Make sure it doens't break.
let finalBlockListEndpoint; let finalBlockListEndpoint;
@ -243,4 +246,4 @@ function Server() {
}; };
} }
export default Server; module.exports = Server;

View file

@ -1,209 +1,212 @@
import axios from 'axios'; const axios = require('axios');
import logger from 'winston'; const logger = require('winston');
import db from 'server/models'; const { apiHost, apiPort, getTimeout } = require('@config/lbryConfig');
import { handleLbrynetResponse } from './utils/handleLbrynetResponse.js';
import { apiHost, apiPort, getTimeout } from '@config/lbryConfig';
import { chooseGaLbrynetPublishLabel, sendGATimingEvent } from '../utils/googleAnalytics.js';
import { publishing } from '@config/siteConfig';
const lbrynetUri = 'http://' + apiHost + ':' + apiPort; const lbrynetUri = 'http://' + apiHost + ':' + apiPort;
const db = require('../models');
const { chooseGaLbrynetPublishLabel, sendGATimingEvent } = require('../utils/googleAnalytics.js');
const handleLbrynetResponse = require('./utils/handleLbrynetResponse.js');
const { publishing } = require('@config/siteConfig');
export function publishClaim(publishParams) { module.exports = {
logger.debug(`lbryApi >> Publishing claim to "${publishParams.name}"`); publishClaim(publishParams) {
const gaStartTime = Date.now(); logger.debug(`lbryApi >> Publishing claim to "${publishParams.name}"`);
return new Promise((resolve, reject) => { const gaStartTime = Date.now();
axios return new Promise((resolve, reject) => {
.post(lbrynetUri, { axios
method: 'publish', .post(lbrynetUri, {
params: publishParams, method: 'publish',
}) params: publishParams,
.then(response => { })
sendGATimingEvent( .then(response => {
'lbrynet', sendGATimingEvent(
'publish', 'lbrynet',
chooseGaLbrynetPublishLabel(publishParams), 'publish',
gaStartTime, chooseGaLbrynetPublishLabel(publishParams),
Date.now() gaStartTime,
); Date.now()
handleLbrynetResponse(response, resolve, reject);
})
.catch(error => {
reject(error);
});
});
}
export function getClaim(uri) {
logger.debug(`lbryApi >> Getting Claim for "${uri}"`);
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbrynetUri, {
method: 'get',
params: {
uri,
timeout: getTimeout || 30,
},
})
.then(response => {
sendGATimingEvent('lbrynet', 'getClaim', 'GET', gaStartTime, Date.now());
handleLbrynetResponse(response, resolve, reject);
})
.catch(error => {
reject(error);
});
});
}
export async function abandonClaim({ claimId }) {
logger.debug(`lbryApi >> Abandon claim "${claimId}"`);
const gaStartTime = Date.now();
try {
const abandon = await axios.post(lbrynetUri, {
method: 'claim_abandon',
params: { claim_id: claimId },
});
sendGATimingEvent('lbrynet', 'abandonClaim', 'ABANDON_CLAIM', gaStartTime, Date.now());
return abandon.data;
} catch (error) {
logger.error(error);
return error;
}
}
export function getFileListFileByOutpoint(outpoint) {
logger.debug(`lbryApi >> Getting File_List for "${outpoint}"`);
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbrynetUri, {
method: 'file_list',
params: {
outpoint,
},
})
.then(response => {
sendGATimingEvent('lbrynet', 'getFileList', 'FILE_LIST', gaStartTime, Date.now());
handleLbrynetResponse(response, resolve, reject);
})
.catch(error => {
reject(error);
});
});
}
export function getClaimList(claimName) {
logger.debug(`lbryApi >> Getting claim_list for "${claimName}"`);
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbrynetUri, {
method: 'claim_list',
params: { name: claimName },
})
.then(response => {
sendGATimingEvent('lbrynet', 'getClaimList', 'CLAIM_LIST', gaStartTime, Date.now());
handleLbrynetResponse(response, resolve, reject);
})
.catch(error => {
reject(error);
});
});
}
export function resolveUri(uri) {
logger.debug(`lbryApi >> Resolving URI for "${uri}"`);
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbrynetUri, {
method: 'resolve',
params: { urls: uri },
})
.then(({ data }) => {
sendGATimingEvent('lbrynet', 'resolveUri', 'RESOLVE', gaStartTime, Date.now());
if (Object.keys(data.result).length === 0 && data.result.constructor === Object) {
// workaround for daemon returning empty result object
// https://github.com/lbryio/lbry/issues/1485
db.Claim.findOne({ where: { claimId: uri.split('#')[1] } })
.then(() => reject('This claim has not yet been confirmed on the LBRY blockchain'))
.catch(() => reject(`Claim ${uri} does not exist`));
} else if (data.result[uri].error) {
// check for errors
reject(data.result[uri].error);
} else {
// if no errors, resolve
resolve(data.result[uri]);
}
})
.catch(error => {
reject(error);
});
});
}
export function getDownloadDirectory() {
logger.debug('lbryApi >> Retrieving the download directory path from lbry daemon...');
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbrynetUri, {
method: 'settings_get',
})
.then(({ data }) => {
sendGATimingEvent(
'lbrynet',
'getDownloadDirectory',
'SETTINGS_GET',
gaStartTime,
Date.now()
);
if (data.result) {
resolve(data.result.download_directory);
} else {
return new Error(
'Successfully connected to lbry daemon, but unable to retrieve the download directory.'
); );
} handleLbrynetResponse(response, resolve, reject);
}) })
.catch(error => { .catch(error => {
logger.error('Lbrynet Error:', error); reject(error);
resolve('/home/lbry/Downloads/'); });
});
},
getClaim(uri) {
logger.debug(`lbryApi >> Getting Claim for "${uri}"`);
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbrynetUri, {
method: 'get',
params: {
uri,
timeout: getTimeout || 30,
},
})
.then(response => {
sendGATimingEvent('lbrynet', 'getClaim', 'GET', gaStartTime, Date.now());
handleLbrynetResponse(response, resolve, reject);
})
.catch(error => {
reject(error);
});
});
},
getFileListFileByOutpoint(outpoint) {
logger.debug(`lbryApi >> Getting File_List for "${outpoint}"`);
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbrynetUri, {
method: 'file_list',
params: {
outpoint,
},
})
.then(response => {
sendGATimingEvent('lbrynet', 'getFileList', 'FILE_LIST', gaStartTime, Date.now());
handleLbrynetResponse(response, resolve, reject);
})
.catch(error => {
reject(error);
});
});
},
async abandonClaim({ claimId }) {
logger.debug(`lbryApi >> Abandon claim "${claimId}"`);
const gaStartTime = Date.now();
try {
const abandon = await axios.post(lbrynetUri, {
method: 'claim_abandon',
params: { claim_id: claimId },
}); });
}); sendGATimingEvent('lbrynet', 'abandonClaim', 'ABANDON_CLAIM', gaStartTime, Date.now());
} return abandon.data;
export function createChannel(name) { } catch (error) {
logger.debug(`lbryApi >> Creating channel for ${name}...`); logger.error(error);
const gaStartTime = Date.now(); return error;
return new Promise((resolve, reject) => { }
axios },
.post(lbrynetUri, { getClaimList(claimName) {
method: 'channel_new', logger.debug(`lbryApi >> Getting claim_list for "${claimName}"`);
params: { const gaStartTime = Date.now();
channel_name: name, return new Promise((resolve, reject) => {
amount: publishing.channelClaimBidAmount, axios
}, .post(lbrynetUri, {
}) method: 'claim_list',
.then(response => { params: { name: claimName },
sendGATimingEvent('lbrynet', 'createChannel', 'CHANNEL_NEW', gaStartTime, Date.now()); })
handleLbrynetResponse(response, resolve, reject); .then(response => {
}) sendGATimingEvent('lbrynet', 'getClaimList', 'CLAIM_LIST', gaStartTime, Date.now());
.catch(error => { handleLbrynetResponse(response, resolve, reject);
reject(error); })
}); .catch(error => {
}); reject(error);
} });
export function getAccountBalance() { });
const gaStartTime = Date.now(); },
return new Promise((resolve, reject) => { resolveUri(uri) {
axios logger.debug(`lbryApi >> Resolving URI for "${uri}"`);
.post(lbrynetUri, { const gaStartTime = Date.now();
method: 'account_balance', return new Promise((resolve, reject) => {
}) axios
.then(response => { .post(lbrynetUri, {
sendGATimingEvent('lbrynet', 'getAccountBalance', 'SETTINGS_GET', gaStartTime, Date.now()); method: 'resolve',
handleLbrynetResponse(response, resolve, reject); params: { urls: uri },
}) })
.catch(error => { .then(({ data }) => {
reject(error); sendGATimingEvent('lbrynet', 'resolveUri', 'RESOLVE', gaStartTime, Date.now());
}); if (Object.keys(data.result).length === 0 && data.result.constructor === Object) {
}); // workaround for daemon returning empty result object
} // https://github.com/lbryio/lbry/issues/1485
db.Claim.findOne({ where: { claimId: uri.split('#')[1] } })
.then(() => reject('This claim has not yet been confirmed on the LBRY blockchain'))
.catch(() => reject(`Claim ${uri} does not exist`));
} else if (data.result[uri].error) {
// check for errors
reject(data.result[uri].error);
} else {
// if no errors, resolve
resolve(data.result[uri]);
}
})
.catch(error => {
reject(error);
});
});
},
getDownloadDirectory() {
logger.debug('lbryApi >> Retrieving the download directory path from lbry daemon...');
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbrynetUri, {
method: 'settings_get',
})
.then(({ data }) => {
sendGATimingEvent(
'lbrynet',
'getDownloadDirectory',
'SETTINGS_GET',
gaStartTime,
Date.now()
);
if (data.result) {
resolve(data.result.download_dir);
} else {
return new Error(
'Successfully connected to lbry daemon, but unable to retrieve the download directory.'
);
}
})
.catch(error => {
logger.error('Lbrynet Error:', error);
resolve('/home/lbry/Downloads/');
});
});
},
createChannel(name) {
logger.debug(`lbryApi >> Creating channel for ${name}...`);
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbrynetUri, {
method: 'channel_new',
params: {
channel_name: name,
amount: publishing.channelClaimBidAmount,
},
})
.then(response => {
sendGATimingEvent('lbrynet', 'createChannel', 'CHANNEL_NEW', gaStartTime, Date.now());
handleLbrynetResponse(response, resolve, reject);
})
.catch(error => {
reject(error);
});
});
},
getAccountBalance() {
const gaStartTime = Date.now();
return new Promise((resolve, reject) => {
axios
.post(lbrynetUri, {
method: 'account_balance',
})
.then(response => {
sendGATimingEvent(
'lbrynet',
'getAccountBalance',
'SETTINGS_GET',
gaStartTime,
Date.now()
);
handleLbrynetResponse(response, resolve, reject);
})
.catch(error => {
reject(error);
});
});
},
};

View file

@ -1,6 +1,6 @@
import logger from 'winston'; const logger = require('winston');
export const handleLbrynetResponse = ({ data }, resolve, reject) => { const handleLbrynetResponse = ({ data }, resolve, reject) => {
logger.debug('lbry api data:', data); logger.debug('lbry api data:', data);
if (data) { if (data) {
// check for an error // check for an error
@ -15,3 +15,5 @@ export const handleLbrynetResponse = ({ data }, resolve, reject) => {
// fallback in case it just timed out // fallback in case it just timed out
reject(JSON.stringify(data)); reject(JSON.stringify(data));
}; };
module.exports = handleLbrynetResponse;

View file

@ -1,8 +1,9 @@
import fs from 'fs'; const fs = require('fs');
import logger from 'winston'; const logger = require('winston');
import { publishing } from '@config/siteConfig'; const {
const { publishingChannelWhitelist } = publishing; publishing: { publishingChannelWhitelist },
} = require('@config/siteConfig');
const ipBanFile = './site/config/ipBan.txt'; const ipBanFile = './site/config/ipBan.txt';
const forbiddenMessage = const forbiddenMessage =
'<h1>Forbidden</h1>If you are seeing this by mistake, please contact us using <a href="https://chat.lbry.com/">https://chat.lbry.com/</a>'; '<h1>Forbidden</h1>If you are seeing this by mistake, please contact us using <a href="https://chat.lbry.com/">https://chat.lbry.com/</a>';
@ -22,7 +23,7 @@ if (fs.existsSync(ipBanFile)) {
}); });
} }
export const autoblockPublishMiddleware = (req, res, next) => { const autoblockPublishMiddleware = (req, res, next) => {
let ip = (req.headers['x-forwarded-for'] || req.connection.remoteAddress).split(/,\s?/)[0]; let ip = (req.headers['x-forwarded-for'] || req.connection.remoteAddress).split(/,\s?/)[0];
if (blockedAddresses.indexOf(ip) !== -1) { if (blockedAddresses.indexOf(ip) !== -1) {
@ -55,7 +56,7 @@ export const autoblockPublishMiddleware = (req, res, next) => {
} }
}; };
export const autoblockPublishBodyMiddleware = (req, res, next) => { const autoblockPublishBodyMiddleware = (req, res, next) => {
if (req.body && publishingChannelWhitelist) { if (req.body && publishingChannelWhitelist) {
let ip = (req.headers['x-forwarded-for'] || req.connection.remoteAddress).split(/,\s?/)[0]; let ip = (req.headers['x-forwarded-for'] || req.connection.remoteAddress).split(/,\s?/)[0];
const { channelName } = req.body; const { channelName } = req.body;
@ -66,3 +67,8 @@ export const autoblockPublishBodyMiddleware = (req, res, next) => {
} }
next(); next();
}; };
module.exports = {
autoblockPublishMiddleware,
autoblockPublishBodyMiddleware,
};

View file

@ -1,8 +1,8 @@
import logger from 'winston'; const logger = require('winston');
import db from '../models'; const db = require('../models');
import httpContext from 'express-http-context'; const httpContext = require('express-http-context');
export function logMetricsMiddleware(req, res, next) { function logMetricsMiddleware (req, res, next) {
res.on('finish', () => { res.on('finish', () => {
const userAgent = req.get('user-agent'); const userAgent = req.get('user-agent');
const routePath = httpContext.get('routePath'); const routePath = httpContext.get('routePath');
@ -26,15 +26,15 @@ export function logMetricsMiddleware(req, res, next) {
} }
db.Metrics.create({ db.Metrics.create({
time: Date.now(), time : Date.now(),
isInternal: /node-fetch/.test(userAgent), isInternal: /node-fetch/.test(userAgent),
isChannel: res.isChannel, isChannel : res.isChannel,
claimId: res.claimId, claimId : res.claimId,
routePath: httpContext.get('routePath'), routePath : httpContext.get('routePath'),
params: JSON.stringify(req.params), params : JSON.stringify(req.params),
ip: req.headers['x-forwarded-for'] || req.connection.remoteAddress, ip : req.headers['x-forwarded-for'] || req.connection.remoteAddress,
request: req.url, request : req.url,
routeData: JSON.stringify(httpContext.get('routeData')), routeData : JSON.stringify(httpContext.get('routeData')),
referrer, referrer,
userAgent, userAgent,
}); });
@ -43,10 +43,15 @@ export function logMetricsMiddleware(req, res, next) {
next(); next();
} }
export function setRouteDataInContextMiddleware(routePath, routeData) { function setRouteDataInContextMiddleware (routePath, routeData) {
return function(req, res, next) { return function (req, res, next) {
httpContext.set('routePath', routePath); httpContext.set('routePath', routePath);
httpContext.set('routeData', routeData); httpContext.set('routeData', routeData);
next(); next();
}; };
} }
module.exports = {
logMetricsMiddleware,
setRouteDataInContextMiddleware,
};

View file

@ -1,6 +1,5 @@
import multipart from 'connect-multiparty'; const multipart = require('connect-multiparty');
import { publishing } from '@config/siteConfig'; const { publishing: { uploadDirectory } } = require('@config/siteConfig');
const { uploadDirectory } = publishing; const multipartMiddleware = multipart({uploadDir: uploadDirectory});
const multipartMiddleware = multipart({ uploadDir: uploadDirectory });
export default multipartMiddleware; module.exports = multipartMiddleware;

View file

@ -1,8 +1,8 @@
import logger from 'winston'; const logger = require('winston');
const requestLogger = (req, res, next) => { const requestLogger = (req, res, next) => { // custom logging middleware to log all incoming http requests
// custom logging middleware to log all incoming http requests
logger.debug(`Request on ${req.originalUrl} from ${req.ip}`); logger.debug(`Request on ${req.originalUrl} from ${req.ip}`);
next(); next();
}; };
export default requestLogger;
module.exports = requestLogger;

View file

@ -1,22 +1,22 @@
import logger from 'winston'; const logger = require('winston');
import db from 'server/models'; const db = require('../models');
const torCheck = (req, res, next) => { const torCheck = (req, res, next) => {
const { ip } = req; const { ip } = req;
logger.debug(`tor check for: ${ip}`); logger.debug(`tor check for: ${ip}`);
return db.Tor.findAll({ return db.Tor.findAll(
where: { {
address: ip, where: {
}, address: ip,
raw: true, },
}) raw: true,
})
.then(result => { .then(result => {
if (result.length >= 1) { if (result.length >= 1) {
logger.info('Tor request blocked:', ip); logger.info('Tor request blocked:', ip);
const failureResponse = { const failureResponse = {
success: false, success: false,
message: message: 'Unfortunately this api route is not currently available for tor users. We are working on a solution that will allow tor users to use this endpoint in the future.',
'Unfortunately this api route is not currently available for tor users. We are working on a solution that will allow tor users to use this endpoint in the future.',
}; };
res.status(403).json(failureResponse); res.status(403).json(failureResponse);
} else { } else {
@ -27,4 +27,5 @@ const torCheck = (req, res, next) => {
logger.error(error); logger.error(error);
}); });
}; };
export default torCheck;
module.exports = torCheck;

View file

@ -1,12 +1,12 @@
import logger from 'winston'; const logger = require('winston');
const BLOCKED_CLAIM = 'BLOCKED_CLAIM'; const BLOCKED_CLAIM = 'BLOCKED_CLAIM';
export default (sequelize, { STRING }) => { module.exports = (sequelize, { STRING }) => {
const Blocked = sequelize.define( const Blocked = sequelize.define(
'Blocked', 'Blocked',
{ {
outpoint: { outpoint: {
type: STRING, type : STRING,
allowNull: false, allowNull: false,
}, },
}, },
@ -15,16 +15,15 @@ export default (sequelize, { STRING }) => {
} }
); );
Blocked.getBlockList = function() { Blocked.getBlockList = function () {
logger.debug('returning full block list'); logger.debug('returning full block list');
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.findAll().then(list => { this.findAll()
return resolve(list); .then(list => { return resolve(list) });
});
}); });
}; };
Blocked.isNotBlocked = function(outpoint) { Blocked.isNotBlocked = function (outpoint) {
logger.debug(`checking to see if ${outpoint} is not blocked`); logger.debug(`checking to see if ${outpoint} is not blocked`);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.findOne({ this.findOne({
@ -45,7 +44,7 @@ export default (sequelize, { STRING }) => {
}); });
}; };
Blocked.refreshTable = function(blockEndpoint) { Blocked.refreshTable = function (blockEndpoint) {
let blockedList = []; let blockedList = [];
return fetch(blockEndpoint) return fetch(blockEndpoint)

View file

@ -1,98 +1,98 @@
import logger from 'winston'; const logger = require('winston');
import returnShortId from './utils/returnShortId'; const returnShortId = require('./utils/returnShortId.js');
const NO_CHANNEL = 'NO_CHANNEL'; const NO_CHANNEL = 'NO_CHANNEL';
function isLongChannelId(channelId) { function isLongChannelId (channelId) {
return channelId && channelId.length === 40; return (channelId && (channelId.length === 40));
} }
function isShortChannelId(channelId) { function isShortChannelId (channelId) {
return channelId && channelId.length < 40; return (channelId && (channelId.length < 40));
} }
export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => { module.exports = (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => {
const Certificate = sequelize.define( const Certificate = sequelize.define(
'Certificate', 'Certificate',
{ {
address: { address: {
type: STRING, type : STRING,
default: null, default: null,
}, },
amount: { amount: {
type: DECIMAL(19, 8), type : DECIMAL(19, 8),
default: null, default: null,
}, },
claimId: { claimId: {
type: STRING, type : STRING,
default: null, default: null,
}, },
claimSequence: { claimSequence: {
type: INTEGER, type : INTEGER,
default: null, default: null,
}, },
decodedClaim: { decodedClaim: {
type: BOOLEAN, type : BOOLEAN,
default: null, default: null,
}, },
depth: { depth: {
type: INTEGER, type : INTEGER,
default: null, default: null,
}, },
effectiveAmount: { effectiveAmount: {
type: DECIMAL(19, 8), type : DECIMAL(19, 8),
default: null, default: null,
}, },
hasSignature: { hasSignature: {
type: BOOLEAN, type : BOOLEAN,
default: null, default: null,
}, },
height: { height: {
type: INTEGER, type : INTEGER,
default: null, default: null,
}, },
hex: { hex: {
type: TEXT('long'), type : TEXT('long'),
default: null, default: null,
}, },
name: { name: {
type: STRING, type : STRING,
default: null, default: null,
}, },
nout: { nout: {
type: INTEGER, type : INTEGER,
default: null, default: null,
}, },
txid: { txid: {
type: STRING, type : STRING,
default: null, default: null,
}, },
validAtHeight: { validAtHeight: {
type: INTEGER, type : INTEGER,
default: null, default: null,
}, },
outpoint: { outpoint: {
type: STRING, type : STRING,
default: null, default: null,
}, },
valueVersion: { valueVersion: {
type: STRING, type : STRING,
default: null, default: null,
}, },
claimType: { claimType: {
type: STRING, type : STRING,
default: null, default: null,
}, },
certificateVersion: { certificateVersion: {
type: STRING, type : STRING,
default: null, default: null,
}, },
keyType: { keyType: {
type: STRING, type : STRING,
default: null, default: null,
}, },
publicKey: { publicKey: {
type: TEXT('long'), type : TEXT('long'),
default: null, default: null,
}, },
}, },
@ -109,13 +109,14 @@ export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => {
}); });
}; };
Certificate.getShortChannelIdFromLongChannelId = function(longChannelId, channelName) { Certificate.getShortChannelIdFromLongChannelId = function (longChannelId, channelName) {
logger.debug(`getShortChannelIdFromLongChannelId ${channelName}:${longChannelId}`); logger.debug(`getShortChannelIdFromLongChannelId ${channelName}:${longChannelId}`);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.findAll({ this
where: { name: channelName }, .findAll({
order: [['height', 'ASC']], where: {name: channelName},
}) order: [['height', 'ASC']],
})
.then(result => { .then(result => {
switch (result.length) { switch (result.length) {
case 0: case 0:
@ -130,11 +131,11 @@ export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => {
}); });
}; };
Certificate.validateLongChannelId = function(name, claimId) { Certificate.validateLongChannelId = function (name, claimId) {
logger.debug(`validateLongChannelId(${name}, ${claimId})`); logger.debug(`validateLongChannelId(${name}, ${claimId})`);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.findOne({ this.findOne({
where: { name, claimId }, where: {name, claimId},
}) })
.then(result => { .then(result => {
if (!result) { if (!result) {
@ -149,18 +150,19 @@ export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => {
}); });
}; };
Certificate.getLongChannelIdFromShortChannelId = function(channelName, channelClaimId) { Certificate.getLongChannelIdFromShortChannelId = function (channelName, channelClaimId) {
logger.debug(`getLongChannelIdFromShortChannelId(${channelName}, ${channelClaimId})`); logger.debug(`getLongChannelIdFromShortChannelId(${channelName}, ${channelClaimId})`);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.findAll({ this
where: { .findAll({
name: channelName, where: {
claimId: { name : channelName,
[sequelize.Op.like]: `${channelClaimId}%`, claimId: {
[sequelize.Op.like]: `${channelClaimId}%`,
},
}, },
}, order: [['height', 'ASC']],
order: [['height', 'ASC']], })
})
.then(result => { .then(result => {
switch (result.length) { switch (result.length) {
case 0: case 0:
@ -176,13 +178,14 @@ export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => {
}); });
}; };
Certificate.getLongChannelIdFromChannelName = function(channelName) { Certificate.getLongChannelIdFromChannelName = function (channelName) {
logger.debug(`getLongChannelIdFromChannelName(${channelName})`); logger.debug(`getLongChannelIdFromChannelName(${channelName})`);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.findAll({ this
where: { name: channelName }, .findAll({
order: [['effectiveAmount', 'DESC'], ['height', 'ASC']], where: { name: channelName },
}) order: [['effectiveAmount', 'DESC'], ['height', 'ASC']],
})
.then(result => { .then(result => {
switch (result.length) { switch (result.length) {
case 0: case 0:
@ -198,7 +201,7 @@ export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => {
}); });
}; };
Certificate.getLongChannelId = function(channelName, channelClaimId) { Certificate.getLongChannelId = function (channelName, channelClaimId) {
logger.debug(`getLongChannelId(${channelName}, ${channelClaimId})`); logger.debug(`getLongChannelId(${channelName}, ${channelClaimId})`);
if (isLongChannelId(channelClaimId)) { if (isLongChannelId(channelClaimId)) {
return this.validateLongChannelId(channelName, channelClaimId); return this.validateLongChannelId(channelName, channelClaimId);

View file

@ -1,13 +1,13 @@
export default (sequelize, { STRING }) => { module.exports = (sequelize, { STRING }) => {
const Channel = sequelize.define( const Channel = sequelize.define(
'Channel', 'Channel',
{ {
channelName: { channelName: {
type: STRING, type : STRING,
allowNull: false, allowNull: false,
}, },
channelClaimId: { channelClaimId: {
type: STRING, type : STRING,
allowNull: false, allowNull: false,
}, },
}, },

View file

@ -1,10 +1,13 @@
import logger from 'winston'; const logger = require('winston');
import returnShortId from './utils/returnShortId.js'; const returnShortId = require('./utils/returnShortId.js');
import isApprovedChannel from '@globalutils/isApprovedChannel'; const isApprovedChannel = require('../../utils/isApprovedChannel');
import { assetDefaults, details, publishing } from '@config/siteConfig'; const {
const { thumbnail: defaultThumbnail } = assetDefaults; assetDefaults: { thumbnail: defaultThumbnail },
const { host } = details; details: { host },
const { serveOnlyApproved, approvedChannels } = publishing; } = require('@config/siteConfig');
const {
publishing: { serveOnlyApproved, approvedChannels },
} = require('@config/siteConfig');
const NO_CLAIM = 'NO_CLAIM'; const NO_CLAIM = 'NO_CLAIM';
@ -50,7 +53,7 @@ function isShortClaimId(claimId) {
return claimId && claimId.length < 40; return claimId && claimId.length < 40;
} }
export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => { module.exports = (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => {
const Claim = sequelize.define( const Claim = sequelize.define(
'Claim', 'Claim',
{ {

View file

@ -1,35 +1,35 @@
export default (sequelize, { STRING, BOOLEAN, INTEGER }) => { module.exports = (sequelize, { STRING, BOOLEAN, INTEGER }) => {
const File = sequelize.define( const File = sequelize.define(
'File', 'File',
{ {
name: { name: {
type: STRING, type : STRING,
allowNull: false, allowNull: false,
}, },
claimId: { claimId: {
type: STRING, type : STRING,
allowNull: false, allowNull: false,
}, },
outpoint: { outpoint: {
type: STRING, type : STRING,
allowNull: false, allowNull: false,
}, },
fileHeight: { fileHeight: {
type: INTEGER, type : INTEGER,
allowNull: false, allowNull: false,
default: 0, default : 0,
}, },
fileWidth: { fileWidth: {
type: INTEGER, type : INTEGER,
allowNull: false, allowNull: false,
default: 0, default : 0,
}, },
fileName: { fileName: {
type: STRING, type : STRING,
allowNull: false, allowNull: false,
}, },
filePath: { filePath: {
type: STRING, type : STRING,
allowNull: false, allowNull: false,
}, },
fileType: { fileType: {

View file

@ -1,18 +1,22 @@
import Sequelize from 'sequelize'; const Sequelize = require('sequelize');
import logger from 'winston'; const logger = require('winston');
import Blocked from './blocked'; const Blocked = require('./blocked');
import Certificate from './certificate'; const Certificate = require('./certificate');
import Channel from './channel'; const Channel = require('./channel');
import Claim from './claim'; const Claim = require('./claim');
import File from './file'; const File = require('./file');
import Metrics from './metrics'; const Metrics = require('./metrics');
import Tor from './tor'; const Tor = require('./tor');
import Trending from './trending'; const Trending = require('./trending');
import User from './user'; const User = require('./user');
import Views from './views'; const Views = require('./views');
import { database, username, password } from '@config/mysqlConfig'; const {
database,
username,
password,
} = require('@config/mysqlConfig');
if (!database || !username || !password) { if (!database || !username || !password) {
logger.warn('missing database, user, or password from mysqlConfig'); logger.warn('missing database, user, or password from mysqlConfig');
@ -20,16 +24,16 @@ if (!database || !username || !password) {
// set sequelize options // set sequelize options
const sequelize = new Sequelize(database, username, password, { const sequelize = new Sequelize(database, username, password, {
host: 'localhost', host : 'localhost',
dialect: 'mysql', dialect : 'mysql',
dialectOptions: { dialectOptions: {
decimalNumbers: true, decimalNumbers: true,
}, },
logging: false, logging: false,
pool: { pool : {
max: 5, max : 5,
min: 0, min : 0,
idle: 10000, idle : 10000,
acquire: 10000, acquire: 10000,
}, },
operatorsAliases: false, operatorsAliases: false,
@ -73,24 +77,23 @@ db.sequelize = sequelize;
db.Sequelize = Sequelize; db.Sequelize = Sequelize;
// add an 'upsert' method to the db object // add an 'upsert' method to the db object
db.upsert = (Model, values, condition, tableName) => { db.upsert = (Model, values, condition, tableName) => {
return Model.findOne({ return Model
where: condition, .findOne({
}) where: condition,
})
.then(obj => { .then(obj => {
if (obj) { if (obj) { // update
// update
logger.debug(`updating record in db.${tableName}`); logger.debug(`updating record in db.${tableName}`);
return obj.update(values); return obj.update(values);
} else { } else { // insert
// insert
logger.debug(`creating record in db.${tableName}`); logger.debug(`creating record in db.${tableName}`);
return Model.create(values); return Model.create(values);
} }
}) })
.catch(function(error) { .catch(function (error) {
logger.error(`${tableName}.upsert error`, error); logger.error(`${tableName}.upsert error`, error);
throw error; throw error;
}); });
}; };
export default db; module.exports = db;

View file

@ -1,51 +1,51 @@
export default (sequelize, { BOOLEAN, DATE, STRING }) => { module.exports = (sequelize, { BOOLEAN, DATE, STRING }) => {
const Metrics = sequelize.define( const Metrics = sequelize.define(
'Metrics', 'Metrics',
{ {
time: { time: {
type: DATE(6), type : DATE(6),
defaultValue: sequelize.NOW, defaultValue: sequelize.NOW,
}, },
isInternal: { isInternal: {
type: BOOLEAN, type: BOOLEAN,
}, },
isChannel: { isChannel: {
type: BOOLEAN, type : BOOLEAN,
defaultValue: false, defaultValue: false,
}, },
claimId: { claimId: {
type: STRING, type : STRING,
defaultValue: null, defaultValue: null,
}, },
ip: { ip: {
type: STRING, type : STRING,
defaultValue: null, defaultValue: null,
}, },
request: { request: {
type: STRING, type : STRING,
defaultValue: null, defaultValue: null,
}, },
userAgent: { userAgent: {
type: STRING, type : STRING,
defaultValue: null, defaultValue: null,
}, },
referrer: { referrer: {
type: STRING, type : STRING,
defaultValue: null, defaultValue: null,
}, },
routePath: { routePath: {
type: STRING, type : STRING,
defaultValue: null, defaultValue: null,
}, },
params: { params: {
type: STRING, type : STRING,
defaultValue: null, defaultValue: null,
}, },
}, },
{ {
freezeTableName: true, freezeTableName: true,
timestamps: false, // don't use default timestamps columns timestamps : false, // don't use default timestamps columns
indexes: [ indexes : [
{ {
fields: ['isInternal', 'isChannel', 'time', 'claimId', 'routePath'], fields: ['isInternal', 'isChannel', 'time', 'claimId', 'routePath'],
}, },

View file

@ -1,17 +1,16 @@
import logger from 'winston'; const logger = require('winston');
import { details } from '@config/siteConfig'; const { details: { ipAddress } } = require('@config/siteConfig');
const { ipAddress } = details;
export default (sequelize, { STRING }) => { module.exports = (sequelize, { STRING }) => {
const Tor = sequelize.define( const Tor = sequelize.define(
'Tor', 'Tor',
{ {
address: { address: {
type: STRING, type : STRING,
allowNull: false, allowNull: false,
}, },
fingerprint: { fingerprint: {
type: STRING, type : STRING,
allowNull: true, allowNull: true,
}, },
}, },
@ -20,7 +19,7 @@ export default (sequelize, { STRING }) => {
} }
); );
Tor.refreshTable = function() { Tor.refreshTable = function () {
let torList = []; let torList = [];
return fetch(`https://check.torproject.org/api/bulk?ip=${ipAddress}&port=80`) return fetch(`https://check.torproject.org/api/bulk?ip=${ipAddress}&port=80`)
.then(response => { .then(response => {
@ -31,7 +30,7 @@ export default (sequelize, { STRING }) => {
// prep the records // prep the records
for (let i = 0; i < jsonResponse.length; i++) { for (let i = 0; i < jsonResponse.length; i++) {
torList.push({ torList.push({
address: jsonResponse[i].Address, address : jsonResponse[i].Address,
fingerprint: jsonResponse[i].Fingerprint, fingerprint: jsonResponse[i].Fingerprint,
}); });
} }
@ -48,7 +47,7 @@ export default (sequelize, { STRING }) => {
// return the new table // return the new table
return this.findAll({ return this.findAll({
attributes: ['address', 'fingerprint'], attributes: ['address', 'fingerprint'],
raw: true, raw : true,
}); });
}) })
.catch(error => { .catch(error => {

View file

@ -1,48 +1,47 @@
import chainquery from 'chainquery'; const chainquery = require('chainquery').default;
export default (sequelize, { BOOLEAN, DATE, FLOAT, INTEGER, STRING }) => { module.exports = (sequelize, { BOOLEAN, DATE, FLOAT, INTEGER, STRING }) => {
const Trending = sequelize.define( const Trending = sequelize.define(
'Trending', 'Trending',
{ {
time: { time: { /* TODO: Historical analysis and log roll */
/* TODO: Historical analysis and log roll */ type : DATE(6),
type: DATE(6),
defaultValue: sequelize.NOW, defaultValue: sequelize.NOW,
}, },
isChannel: { isChannel: {
type: BOOLEAN, type : BOOLEAN,
defaultValue: false, defaultValue: false,
}, },
claimId: { claimId: {
type: STRING, type : STRING,
defaultValue: null, defaultValue: null,
}, },
publisherId: { publisherId: {
type: STRING, type : STRING,
defaultValue: null, defaultValue: null,
}, },
intervalViews: { intervalViews: {
type: INTEGER, type : INTEGER,
defaultValue: 0, defaultValue: 0,
}, },
weight: { weight: {
type: FLOAT, type : FLOAT,
defaultValue: 0, defaultValue: 0,
}, },
zScore: { zScore: {
type: FLOAT, type : FLOAT,
defaultValue: 0, defaultValue: 0,
}, },
pValue: { pValue: {
type: FLOAT, type : FLOAT,
defaultValue: 0, defaultValue: 0,
}, },
// TODO: Calculate t-statistics // TODO: Calculate t-statistics
}, },
{ {
freezeTableName: true, freezeTableName: true,
timestamps: false, // don't use default timestamps columns timestamps : false, // don't use default timestamps columns
indexes: [ indexes : [
{ {
fields: ['claimId'], fields: ['claimId'],
}, },
@ -53,15 +52,16 @@ export default (sequelize, { BOOLEAN, DATE, FLOAT, INTEGER, STRING }) => {
} }
); );
Trending.getTrendingWeightData = async ({ hours = 2, minutes = 0, limit = 20 } = {}) => { Trending.getTrendingWeightData = async ({
hours = 2,
minutes = 0,
limit = 20,
} = {}) => {
let time = new Date(); let time = new Date();
time.setHours(time.getHours() - hours); time.setHours(time.getHours() - hours);
time.setMinutes(time.getMinutes() - minutes); time.setMinutes(time.getMinutes() - minutes);
const sqlTime = time const sqlTime = time.toISOString().slice(0, 19).replace('T', ' ');
.toISOString()
.slice(0, 19)
.replace('T', ' ');
const selectString = 'DISTINCT(claimId), weight'; const selectString = 'DISTINCT(claimId), weight';
const whereString = `isChannel = false and time > '${sqlTime}'`; const whereString = `isChannel = false and time > '${sqlTime}'`;
@ -89,7 +89,7 @@ export default (sequelize, { BOOLEAN, DATE, FLOAT, INTEGER, STRING }) => {
}, },
}); });
return claimData.map(claimData => { return claimData.map((claimData) => {
return Object.assign(trendingClaims[claimData.claim_id], claimData.dataValues); return Object.assign(trendingClaims[claimData.claim_id], claimData.dataValues);
}); });
}; };

View file

@ -1,17 +1,17 @@
'use strict'; 'use strict';
import bcrypt from 'bcrypt'; const bcrypt = require('bcrypt');
import logger from 'winston'; const logger = require('winston');
export default (sequelize, { STRING }) => { module.exports = (sequelize, { STRING }) => {
const User = sequelize.define( const User = sequelize.define(
'User', 'User',
{ {
userName: { userName: {
type: STRING, type : STRING,
allowNull: false, allowNull: false,
}, },
password: { password: {
type: STRING, type : STRING,
allowNull: false, allowNull: false,
}, },
}, },
@ -24,11 +24,11 @@ export default (sequelize, { STRING }) => {
User.hasOne(db.Channel); User.hasOne(db.Channel);
}; };
User.prototype.comparePassword = function(password) { User.prototype.comparePassword = function (password) {
return bcrypt.compare(password, this.password); return bcrypt.compare(password, this.password);
}; };
User.prototype.changePassword = function(newPassword) { User.prototype.changePassword = function (newPassword) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// generate a salt string to use for hashing // generate a salt string to use for hashing
bcrypt.genSalt((saltError, salt) => { bcrypt.genSalt((saltError, salt) => {
@ -46,7 +46,8 @@ export default (sequelize, { STRING }) => {
return; return;
} }
// replace the current password with the new hash // replace the current password with the new hash
this.update({ password: hash }) this
.update({password: hash})
.then(() => { .then(() => {
resolve(); resolve();
}) })

View file

@ -1,37 +1,44 @@
import db from 'server/models'; const db = require('../index.js');
export const createClaimRecordDataAfterPublish = ( const createClaimRecordDataAfterPublish = (certificateId, channelName, fileName, fileType, publishParams, publishResults) => {
certificateId,
channelName,
fileName,
fileType,
publishParams,
publishResults
) => {
const { const {
name, name,
metadata: { title, description, thumbnail, nsfw }, metadata: {
title,
description,
thumbnail,
nsfw,
},
claim_address: address, claim_address: address,
bid: amount, bid: amount,
} = publishParams; } = publishParams;
const { claim_id: claimId, txid, nout } = publishResults; const {
claim_id: claimId,
txid,
nout,
} = publishResults;
return db.Claim.getCurrentHeight().then(height => { return db.Claim.getCurrentHeight()
return { .then(height => {
name, return {
claimId, name,
title, claimId,
description, title,
address, description,
thumbnail, address,
outpoint: `${txid}:${nout}`, thumbnail,
height, outpoint : `${txid}:${nout}`,
contentType: fileType, height,
nsfw, contentType: fileType,
amount, nsfw,
certificateId, amount,
channelName, certificateId,
}; channelName,
}); };
});
};
module.exports = {
createClaimRecordDataAfterPublish,
}; };

View file

@ -1,15 +1,14 @@
import Sequelize from 'sequelize'; const Sequelize = require('sequelize');
import { database, username, password } from '@config/mysqlConfig'; const {database, username, password} = require('@config/mysqlConfig');
const createDatabaseIfNotExists = () => { const createDatabaseIfNotExists = () => {
const sequelize = new Sequelize('', username, password, { const sequelize = new Sequelize('', username, password, {
dialect: 'mysql', dialect : 'mysql',
logging: false, logging : false,
operatorsAliases: false, operatorsAliases: false,
}); });
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
sequelize sequelize.query(`CREATE DATABASE IF NOT EXISTS ${database};`)
.query(`CREATE DATABASE IF NOT EXISTS ${database};`)
.then(() => { .then(() => {
resolve(); resolve();
}) })
@ -19,4 +18,4 @@ const createDatabaseIfNotExists = () => {
}); });
}; };
export default createDatabaseIfNotExists; module.exports = createDatabaseIfNotExists;

View file

@ -1,11 +1,22 @@
import getMediaDimensions from 'server/utils/getMediaDimensions.js'; const getMediaDimensions = require('../../utils/getMediaDimensions.js');
export async function createFileRecordDataAfterGet(resolveResult, getResult) { async function createFileRecordDataAfterGet (resolveResult, getResult) {
const { name, claimId, outpoint, contentType: fileType } = resolveResult; const {
name,
claimId,
outpoint,
contentType: fileType,
} = resolveResult;
const { file_name: fileName, download_path: filePath } = getResult; const {
file_name: fileName,
download_path: filePath,
} = getResult;
const { height: fileHeight, width: fileWidth } = await getMediaDimensions(fileType, filePath); const {
height: fileHeight,
width: fileWidth,
} = await getMediaDimensions(fileType, filePath);
return { return {
name, name,
@ -19,17 +30,22 @@ export async function createFileRecordDataAfterGet(resolveResult, getResult) {
}; };
} }
export async function createFileRecordDataAfterPublish( async function createFileRecordDataAfterPublish (fileName, fileType, publishParams, publishResults) {
fileName, const {
fileType, name,
publishParams, file_path: filePath,
publishResults } = publishParams;
) {
const { name, file_path: filePath } = publishParams;
const { claim_id: claimId, txid, nout } = publishResults; const {
claim_id: claimId,
txid,
nout,
} = publishResults;
const { height: fileHeight, width: fileWidth } = await getMediaDimensions(fileType, filePath); const {
height: fileHeight,
width: fileWidth,
} = await getMediaDimensions(fileType, filePath);
return { return {
name, name,
@ -42,3 +58,8 @@ export async function createFileRecordDataAfterPublish(
fileType, fileType,
}; };
} }
module.exports = {
createFileRecordDataAfterGet,
createFileRecordDataAfterPublish,
};

View file

@ -16,10 +16,10 @@ const returnShortId = (claimsArray, longId) => {
shortIdLength += 1; shortIdLength += 1;
shortId = longId.substring(0, shortIdLength); shortId = longId.substring(0, shortIdLength);
possibleMatches = possibleMatches.filter(element => { possibleMatches = possibleMatches.filter(element => {
return element.claimId && element.claimId.substring(0, shortIdLength) === shortId; return (element.claimId && (element.claimId.substring(0, shortIdLength) === shortId));
}); });
} }
return shortId; return shortId;
}; };
export default returnShortId; module.exports = returnShortId;

View file

@ -1,36 +1,36 @@
import chai from 'chai'; const chai = require('chai');
const expect = chai.expect; const expect = chai.expect;
describe('#parsePublishApiRequestBody()', function() { describe('#parsePublishApiRequestBody()', function () {
const returnShortId = require('./returnShortId.js'); const returnShortId = require('./returnShortId.js');
let dummyClaimsArray; let dummyClaimsArray;
let dummyLongId; let dummyLongId;
it('should thow an error if the claimId is not in the claim list', function() { it('should thow an error if the claimId is not in the claim list', function () {
dummyClaimsArray = [ dummyClaimsArray = [
{ claimId: 'a123456789' }, {claimId: 'a123456789'},
{ claimId: 'b123456789' }, {claimId: 'b123456789'},
{ claimId: 'c123456789' }, {claimId: 'c123456789'},
]; ];
dummyLongId = 'xxxxxxxxxx'; dummyLongId = 'xxxxxxxxxx';
expect(returnShortId.bind(this, dummyClaimsArray, dummyLongId)).to.throw(); expect(returnShortId.bind(this, dummyClaimsArray, dummyLongId)).to.throw();
}); });
it('should return the shortest unique claim id', function() { it('should return the shortest unique claim id', function () {
dummyClaimsArray = [ dummyClaimsArray = [
{ claimId: 'a123456789' }, {claimId: 'a123456789'},
{ claimId: 'b123456789' }, {claimId: 'b123456789'},
{ claimId: 'c123456789' }, {claimId: 'c123456789'},
]; ];
dummyLongId = 'c123456789'; dummyLongId = 'c123456789';
expect(returnShortId(dummyClaimsArray, dummyLongId)).to.equal('c'); expect(returnShortId(dummyClaimsArray, dummyLongId)).to.equal('c');
}); });
it('if there is a conflict between unqiue ids, it should give preference to the one with the lowest height', function() { it('if there is a conflict between unqiue ids, it should give preference to the one with the lowest height', function () {
dummyClaimsArray = [ dummyClaimsArray = [
{ claimId: 'a123456789', height: 10 }, {claimId: 'a123456789', height: 10},
{ claimId: 'ab12345678', height: 11 }, {claimId: 'ab12345678', height: 11},
{ claimId: 'ab12341111', height: 12 }, {claimId: 'ab12341111', height: 12},
]; ];
dummyLongId = 'a123456789'; dummyLongId = 'a123456789';
expect(returnShortId(dummyClaimsArray, dummyLongId)).to.equal('a'); expect(returnShortId(dummyClaimsArray, dummyLongId)).to.equal('a');

View file

@ -5,7 +5,7 @@ const MAX_P_PRECISION = Math.exp(-16); // Rought estimation of V8 precision, -16
const MIN_P = -6.44357455534; // v8 float 0.0...0 const MIN_P = -6.44357455534; // v8 float 0.0...0
const MAX_P = 6.44357455534; // v8 float 1.0...0 const MAX_P = 6.44357455534; // v8 float 1.0...0
const getMean = numArr => { const getMean = (numArr) => {
let total = 0; let total = 0;
let length = numArr.length; // store local to reduce potential prop lookups let length = numArr.length; // store local to reduce potential prop lookups
@ -17,10 +17,12 @@ const getMean = numArr => {
}; };
const getStandardDeviation = (numArr, mean) => { const getStandardDeviation = (numArr, mean) => {
return Math.sqrt(numArr.reduce((sq, n) => sq + Math.pow(n - mean, 2), 0) / (numArr.length - 1)); return Math.sqrt(numArr.reduce((sq, n) => (
sq + Math.pow(n - mean, 2)
), 0) / (numArr.length - 1));
}; };
export const getInformationFromValues = numArr => { const getInformationFromValues = (numArr) => {
let mean = getMean(numArr); let mean = getMean(numArr);
return { return {
@ -29,10 +31,9 @@ export const getInformationFromValues = numArr => {
}; };
}; };
export const getZScore = (value, mean, sDeviation) => const getZScore = (value, mean, sDeviation) => (sDeviation !== 0 ? (value - mean) / sDeviation : 0);
sDeviation !== 0 ? (value - mean) / sDeviation : 0;
export const getFastPValue = zScore => { const getFastPValue = (zScore) => {
if (zScore <= MIN_P) { if (zScore <= MIN_P) {
return 0; return 0;
} }
@ -46,10 +47,7 @@ export const getFastPValue = zScore => {
let term = 1; let term = 1;
while (Math.abs(term) > MAX_P_PRECISION) { while (Math.abs(term) > MAX_P_PRECISION) {
term = term = ONE_DIV_SQRT_2PI * Math.pow(-1, k) * Math.pow(zScore, k) / (2 * k + 1) / Math.pow(2, k) * Math.pow(zScore, k + 1) / factorialK;
(((ONE_DIV_SQRT_2PI * Math.pow(-1, k) * Math.pow(zScore, k)) / (2 * k + 1) / Math.pow(2, k)) *
Math.pow(zScore, k + 1)) /
factorialK;
sum += term; sum += term;
k++; k++;
factorialK *= k; factorialK *= k;
@ -59,4 +57,11 @@ export const getFastPValue = zScore => {
return sum; return sum;
}; };
export const getWeight = (zScore, pValue) => zScore * pValue; const getWeight = (zScore, pValue) => (zScore * pValue);
module.exports = {
getInformationFromValues,
getZScore,
getFastPValue,
getWeight,
};

View file

@ -1,32 +1,32 @@
export default (sequelize, { BOOLEAN, DATE, STRING }) => { module.exports = (sequelize, { BOOLEAN, DATE, STRING }) => {
const Views = sequelize.define( const Views = sequelize.define(
'Views', 'Views',
{ {
time: { time: {
type: DATE(6), type : DATE(6),
defaultValue: sequelize.NOW, defaultValue: sequelize.NOW,
}, },
isChannel: { isChannel: {
type: BOOLEAN, type : BOOLEAN,
defaultValue: false, defaultValue: false,
}, },
claimId: { claimId: {
type: STRING, type : STRING,
defaultValue: null, defaultValue: null,
}, },
publisherId: { publisherId: {
type: STRING, type : STRING,
defaultValue: null, defaultValue: null,
}, },
ip: { ip: {
type: STRING, type : STRING,
defaultValue: null, defaultValue: null,
}, },
}, },
{ {
freezeTableName: true, freezeTableName: true,
timestamps: false, // don't use default timestamps columns timestamps : false, // don't use default timestamps columns
indexes: [ indexes : [
{ {
fields: ['time', 'isChannel', 'claimId', 'publisherId', 'ip'], fields: ['time', 'isChannel', 'claimId', 'publisherId', 'ip'],
}, },
@ -34,15 +34,15 @@ export default (sequelize, { BOOLEAN, DATE, STRING }) => {
} }
); );
Views.getUniqueViews = ({ hours = 0, minutes = 30 } = {}) => { Views.getUniqueViews = ({
hours = 0,
minutes = 30,
} = {}) => {
let time = new Date(); let time = new Date();
time.setHours(time.getHours() - hours); time.setHours(time.getHours() - hours);
time.setMinutes(time.getMinutes() - minutes); time.setMinutes(time.getMinutes() - minutes);
const sqlTime = time const sqlTime = time.toISOString().slice(0, 19).replace('T', ' ');
.toISOString()
.slice(0, 19)
.replace('T', ' ');
const selectString = 'claimId, publisherId, isChannel, COUNT(DISTINCT ip) as views'; const selectString = 'claimId, publisherId, isChannel, COUNT(DISTINCT ip) as views';
const groupString = 'claimId, publisherId, isChannel'; const groupString = 'claimId, publisherId, isChannel';
@ -53,13 +53,13 @@ export default (sequelize, { BOOLEAN, DATE, STRING }) => {
); );
}; };
Views.getGetUniqueViewsbByClaimId = claimId => { Views.getGetUniqueViewsbByClaimId = (claimId) => {
return Views.count({ return Views.count({
where: { where: {
claimId, claimId,
}, },
distinct: true, distinct: true,
col: 'ip', col : 'ip',
}); });
}; };

View file

@ -1,11 +1,11 @@
import md5File from 'md5-file'; const md5File = require('md5-file');
import path from 'path'; const path = require('path');
const bundlePath = path.resolve('./public/bundle/bundle.js'); const bundlePath = path.resolve('./public/bundle/bundle.js');
const bundleHash = md5File.sync(bundlePath); const bundleHash = md5File.sync(bundlePath);
const shortBundleHash = bundleHash.substring(0, 4); const shortBundleHash = bundleHash.substring(0, 4);
export default (helmet, html, preloadedState) => { module.exports = (helmet, html, preloadedState) => {
// take the html and preloadedState and return the full page // take the html and preloadedState and return the full page
return ` return `
<!DOCTYPE html> <!DOCTYPE html>

View file

@ -1,87 +1,65 @@
// middleware // middleware
import multipartMiddleware from 'server/middleware/multipartMiddleware'; const { autoblockPublishMiddleware, autoblockPublishBodyMiddleware } = require('../../middleware/autoblockPublishMiddleware');
import torCheckMiddleware from 'server/middleware/torCheckMiddleware'; const multipartMiddleware = require('../../middleware/multipartMiddleware');
const torCheckMiddleware = require('../../middleware/torCheckMiddleware');
// route handlers // route handlers
import channelAvailability from 'server/controllers/api/channel/availability'; const channelAvailability = require('../../controllers/api/channel/availability');
import channelClaims from 'server/controllers/api/channel/claims'; const channelClaims = require('../../controllers/api/channel/claims');
import channelData from 'server/controllers/api/channel/data'; const channelData = require('../../controllers/api/channel/data');
import channelShortId from 'server/controllers/api/channel/shortId'; const channelShortId = require('../../controllers/api/channel/shortId');
import claimAvailability from 'server/controllers/api/claim/availability'; const claimAvailability = require('../../controllers/api/claim/availability');
import claimData from 'server/controllers/api/claim/data/'; const claimData = require('../../controllers/api/claim/data/');
import claimGet from 'server/controllers/api/claim/get'; const claimGet = require('../../controllers/api/claim/get');
import claimList from 'server/controllers/api/claim/list'; const claimList = require('../../controllers/api/claim/list');
import claimLongId from 'server/controllers/api/claim/longId'; const claimLongId = require('../../controllers/api/claim/longId');
import claimPublish from 'server/controllers/api/claim/publish'; const claimPublish = require('../../controllers/api/claim/publish');
import claimAbandon from 'server/controllers/api/claim/abandon'; const claimAbandon = require('../../controllers/api/claim/abandon');
import claimUpdate from 'server/controllers/api/claim/update'; const claimUpdate = require('../../controllers/api/claim/update');
import claimResolve from 'server/controllers/api/claim/resolve'; const claimResolve = require('../../controllers/api/claim/resolve');
import claimShortId from 'server/controllers/api/claim/shortId'; const claimShortId = require('../../controllers/api/claim/shortId');
import claimViews from 'server/controllers/api/claim/views'; const claimViews = require('../../controllers/api/claim/views');
import fileAvailability from 'server/controllers/api/file/availability'; const fileAvailability = require('../../controllers/api/file/availability');
import specialClaims from 'server/controllers/api/special/claims'; const specialClaims = require('../../controllers/api/special/claims');
import userPassword from 'server/controllers/api/user/password'; const userPassword = require('../../controllers/api/user/password');
import publishingConfig from 'server/controllers/api/config/site/publishing'; const publishingConfig = require('../../controllers/api/config/site/publishing');
import getTorList from 'server/controllers/api/tor'; const getTorList = require('../../controllers/api/tor');
import getBlockedList from 'server/controllers/api/blocked'; const getBlockedList = require('../../controllers/api/blocked');
import getOEmbedData from 'server/controllers/api/oEmbed'; const getOEmbedData = require('../../controllers/api/oEmbed');
const {
autoblockPublishMiddleware,
autoblockPublishBodyMiddleware,
} = require('server/middleware/autoblockPublishMiddleware');
export default { export default {
// homepage routes // homepage routes
'/api/homepage/data/channels': { controller: [torCheckMiddleware, channelData] }, '/api/homepage/data/channels' : { controller: [ torCheckMiddleware, channelData ] },
// channel routes // channel routes
'/api/channel/availability/:name': { controller: [torCheckMiddleware, channelAvailability] }, '/api/channel/availability/:name' : { controller: [ torCheckMiddleware, channelAvailability ] },
'/api/channel/short-id/:longId/:name': { controller: [torCheckMiddleware, channelShortId] }, '/api/channel/short-id/:longId/:name' : { controller: [ torCheckMiddleware, channelShortId ] },
'/api/channel/data/:channelName/:channelClaimId': { '/api/channel/data/:channelName/:channelClaimId' : { controller: [ torCheckMiddleware, channelData ] },
controller: [torCheckMiddleware, channelData], '/api/channel/claims/:channelName/:channelClaimId/:page': { controller: [ torCheckMiddleware, channelClaims ] },
},
'/api/channel/claims/:channelName/:channelClaimId/:page': {
controller: [torCheckMiddleware, channelClaims],
},
// sepcial routes // sepcial routes
'/api/special/:name/:page': { controller: [torCheckMiddleware, specialClaims] }, '/api/special/:name/:page': { controller: [ torCheckMiddleware, specialClaims ] },
// claim routes // claim routes
'/api/claim/availability/:name': { controller: [torCheckMiddleware, claimAvailability] }, '/api/claim/availability/:name' : { controller: [ torCheckMiddleware, claimAvailability ] },
'/api/claim/data/:claimName/:claimId': { controller: [torCheckMiddleware, claimData] }, '/api/claim/data/:claimName/:claimId' : { controller: [ torCheckMiddleware, claimData ] },
'/api/claim/get/:name/:claimId': { controller: [torCheckMiddleware, claimGet] }, '/api/claim/get/:name/:claimId' : { controller: [ torCheckMiddleware, claimGet ] },
'/api/claim/list/:name': { controller: [torCheckMiddleware, claimList] }, '/api/claim/list/:name' : { controller: [ torCheckMiddleware, claimList ] },
'/api/claim/long-id': { method: 'post', controller: [torCheckMiddleware, claimLongId] }, // note: should be a 'get' '/api/claim/long-id' : { method: 'post', controller: [ torCheckMiddleware, claimLongId ] }, // note: should be a 'get'
'/api/claim/publish': { '/api/claim/publish' : { method: 'post', controller: [ torCheckMiddleware, autoblockPublishMiddleware, multipartMiddleware, autoblockPublishBodyMiddleware, claimPublish ] },
method: 'post', '/api/claim/update' : { method: 'post', controller: [ torCheckMiddleware, multipartMiddleware, claimUpdate ] },
controller: [ '/api/claim/abandon' : { method: 'post', controller: [ torCheckMiddleware, multipartMiddleware, claimAbandon ] },
torCheckMiddleware, '/api/claim/resolve/:name/:claimId' : { controller: [ torCheckMiddleware, claimResolve ] },
autoblockPublishMiddleware, '/api/claim/short-id/:longId/:name' : { controller: [ torCheckMiddleware, claimShortId ] },
multipartMiddleware, '/api/claim/views/:claimId' : { controller: [ torCheckMiddleware, claimViews ] },
autoblockPublishBodyMiddleware,
claimPublish,
],
},
'/api/claim/update': {
method: 'post',
controller: [torCheckMiddleware, multipartMiddleware, claimUpdate],
},
'/api/claim/abandon': {
method: 'post',
controller: [torCheckMiddleware, multipartMiddleware, claimAbandon],
},
'/api/claim/resolve/:name/:claimId': { controller: [torCheckMiddleware, claimResolve] },
'/api/claim/short-id/:longId/:name': { controller: [torCheckMiddleware, claimShortId] },
'/api/claim/views/:claimId': { controller: [torCheckMiddleware, claimViews] },
// file routes // file routes
'/api/file/availability/:name/:claimId': { controller: [torCheckMiddleware, fileAvailability] }, '/api/file/availability/:name/:claimId': { controller: [ torCheckMiddleware, fileAvailability ] },
// user routes // user routes
'/api/user/password/': { method: 'put', controller: [torCheckMiddleware, userPassword] }, '/api/user/password/' : { method: 'put', controller: [ torCheckMiddleware, userPassword ] },
// configs // configs
'/api/config/site/publishing': { controller: [torCheckMiddleware, publishingConfig] }, '/api/config/site/publishing' : { controller: [ torCheckMiddleware, publishingConfig ] },
// tor // tor
'/api/tor': { controller: [torCheckMiddleware, getTorList] }, '/api/tor' : { controller: [ torCheckMiddleware, getTorList ] },
// blocked // blocked
'/api/blocked': { controller: [torCheckMiddleware, getBlockedList] }, '/api/blocked' : { controller: [ torCheckMiddleware, getBlockedList ] },
// open embed // open embed
'/api/oembed': { controller: [torCheckMiddleware, getOEmbedData] }, '/api/oembed' : { controller: [ torCheckMiddleware, getOEmbedData ] },
}; };

View file

@ -1,19 +1,11 @@
import serveByClaim from 'server/controllers/assets/serveByClaim'; const serveByClaim = require('../../controllers/assets/serveByClaim');
import serveByIdentifierAndClaim from 'server/controllers/assets/serveByIdentifierAndClaim'; const serveByIdentifierAndClaim = require('../../controllers/assets/serveByIdentifierAndClaim');
// TODO: Adjust build & sources to use import/export everywhere // TODO: Adjust build & sources to use import/export everywhere
const Actions = require('@actions').default; const Actions = require('@actions').default;
const Sagas = require('@sagas').default; const Sagas = require('@sagas').default;
export default { export default {
'/:identifier/:claim': { '/:identifier/:claim': { controller: serveByIdentifierAndClaim, action: Actions.onHandleShowPageUri, saga: Sagas.handleShowPageUri },
controller: serveByIdentifierAndClaim, '/:claim' : { controller: serveByClaim, action: Actions.onHandleShowPageUri, saga: Sagas.handleShowPageUri },
action: Actions.onHandleShowPageUri,
saga: Sagas.handleShowPageUri,
},
'/:claim': {
controller: serveByClaim,
action: Actions.onHandleShowPageUri,
saga: Sagas.handleShowPageUri,
},
}; };

View file

@ -1,15 +1,12 @@
import speechPassport from '../../speechPassport'; const speechPassport = require('../../speechPassport');
import handleSignupRequest from '../../controllers/auth/signup'; const handleSignupRequest = require('../../controllers/auth/signup');
import handleLoginRequest from '../../controllers/auth/login'; const handleLoginRequest = require('../../controllers/auth/login');
import handleLogoutRequest from '../../controllers/auth/logout'; const handleLogoutRequest = require('../../controllers/auth/logout');
import handleUserRequest from '../../controllers/auth/user'; const handleUserRequest = require('../../controllers/auth/user');
export default { export default {
'/signup': { '/signup': { method: 'post', controller: [ speechPassport.authenticate('local-signup'), handleSignupRequest ] },
method: 'post', '/auth' : { method: 'post', controller: handleLoginRequest },
controller: [speechPassport.authenticate('local-signup'), handleSignupRequest],
},
'/auth': { method: 'post', controller: handleLoginRequest },
'/logout': { controller: handleLogoutRequest }, '/logout': { controller: handleLogoutRequest },
'/user': { controller: handleUserRequest }, '/user' : { controller: handleUserRequest },
}; };

View file

@ -1,25 +1,21 @@
import handlePageRequest from '../../controllers/pages/sendReactApp'; import handlePageRequest from '../../controllers/pages/sendReactApp';
import handleVideoEmbedRequest from '../../controllers/pages/sendVideoEmbedPage'; const handleVideoEmbedRequest = require('../../controllers/pages/sendVideoEmbedPage');
import redirect from '../../controllers/utils/redirect'; const redirect = require('../../controllers/utils/redirect');
// TODO: Adjust build & sources to use import/export everywhere // TODO: Adjust build & sources to use import/export everywhere
const Actions = require('@actions').default; const Actions = require('@actions').default;
const Sagas = require('@sagas').default; const Sagas = require('@sagas').default;
export default { export default {
'/': { '/' : { controller: handlePageRequest, action: Actions.onHandleShowHomepage, saga: Sagas.handleShowHomepage },
controller: handlePageRequest, '/login' : { controller: handlePageRequest },
action: Actions.onHandleShowHomepage, '/about' : { controller: handlePageRequest },
saga: Sagas.handleShowHomepage, '/tos' : { controller: handlePageRequest },
}, '/faq' : { controller: handlePageRequest },
'/login': { controller: handlePageRequest }, '/trending' : { controller: redirect('/popular') },
'/about': { controller: handlePageRequest }, '/popular' : { controller: handlePageRequest },
'/tos': { controller: handlePageRequest }, '/new' : { controller: handlePageRequest },
'/faq': { controller: handlePageRequest }, '/edit/:claimId' : { controller: handlePageRequest },
'/trending': { controller: redirect('/popular') }, '/multisite' : { controller: handlePageRequest },
'/popular': { controller: handlePageRequest }, '/video-embed/:name/:claimId/:config?': { controller: handleVideoEmbedRequest }, // for twitter
'/new': { controller: handlePageRequest },
'/edit/:claimId': { controller: handlePageRequest },
'/multisite': { controller: handlePageRequest },
'/video-embed/:name/:claimId/:config?': { controller: handleVideoEmbedRequest }, // for twitter
}; };

View file

@ -1,12 +1,12 @@
import passport from 'passport'; const passport = require('passport');
import localLoginStrategy from './utils/local-login.js'; const localLoginStrategy = require('./utils/local-login.js');
import localSignupStrategy from './utils/local-signup.js'; const localSignupStrategy = require('./utils/local-signup.js');
import serializeUser from './utils/serializeUser.js'; const serializeUser = require('./utils/serializeUser.js');
import deserializeUser from './utils/deserializeUser.js'; const deserializeUser = require('./utils/deserializeUser.js');
passport.deserializeUser(deserializeUser); passport.deserializeUser(deserializeUser);
passport.serializeUser(serializeUser); passport.serializeUser(serializeUser);
passport.use('local-login', localLoginStrategy); passport.use('local-login', localLoginStrategy);
passport.use('local-signup', localSignupStrategy); passport.use('local-signup', localSignupStrategy);
export default passport; module.exports = passport;

View file

@ -3,4 +3,4 @@ const deserializeUser = (user, done) => {
done(null, user); done(null, user);
}; };
export default deserializeUser; module.exports = deserializeUser;

View file

@ -1,15 +1,15 @@
import db from 'server/models';
const PassportLocalStrategy = require('passport-local').Strategy; const PassportLocalStrategy = require('passport-local').Strategy;
const logger = require('winston'); const logger = require('winston');
const db = require('../../models');
const returnUserAndChannelInfo = userInstance => { const returnUserAndChannelInfo = (userInstance) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let userInfo = {}; let userInfo = {};
userInfo['id'] = userInstance.id; userInfo['id'] = userInstance.id;
userInfo['userName'] = userInstance.userName; userInfo['userName'] = userInstance.userName;
userInstance userInstance
.getChannel() .getChannel()
.then(({ channelName, channelClaimId }) => { .then(({channelName, channelClaimId}) => {
userInfo['channelName'] = channelName; userInfo['channelName'] = channelName;
userInfo['channelClaimId'] = channelClaimId; userInfo['channelClaimId'] = channelClaimId;
return db.Certificate.getShortChannelIdFromLongChannelId(channelClaimId, channelName); return db.Certificate.getShortChannelIdFromLongChannelId(channelClaimId, channelName);
@ -24,26 +24,26 @@ const returnUserAndChannelInfo = userInstance => {
}); });
}; };
const Strategy = new PassportLocalStrategy( module.exports = new PassportLocalStrategy(
{ {
usernameField: 'username', usernameField: 'username',
passwordField: 'password', passwordField: 'password',
}, },
(username, password, done) => { (username, password, done) => {
return db.User.findOne({ return db.User
where: { userName: username }, .findOne({
}) where: {userName: username},
})
.then(user => { .then(user => {
if (!user) { if (!user) {
logger.debug('no user found'); logger.debug('no user found');
return done(null, false, { message: 'Incorrect username or password' }); return done(null, false, {message: 'Incorrect username or password'});
} }
return user return user.comparePassword(password)
.comparePassword(password)
.then(isMatch => { .then(isMatch => {
if (!isMatch) { if (!isMatch) {
logger.debug('incorrect password'); logger.debug('incorrect password');
return done(null, false, { message: 'Incorrect username or password' }); return done(null, false, {message: 'Incorrect username or password'});
} }
logger.debug('Password was a match, returning User'); logger.debug('Password was a match, returning User');
return returnUserAndChannelInfo(user) return returnUserAndChannelInfo(user)
@ -63,5 +63,3 @@ const Strategy = new PassportLocalStrategy(
}); });
} }
); );
export default Strategy;

View file

@ -1,12 +1,10 @@
import { createChannel } from 'server/lbrynet';
const PassportLocalStrategy = require('passport-local').Strategy; const PassportLocalStrategy = require('passport-local').Strategy;
const { createChannel } = require('../../lbrynet');
const logger = require('winston'); const logger = require('winston');
const db = require('server/models'); const db = require('../../models');
const { const { publishing: { closedRegistration } } = require('@config/siteConfig');
publishing: { closedRegistration },
} = require('@config/siteConfig');
const Strategy = new PassportLocalStrategy( module.exports = new PassportLocalStrategy(
{ {
usernameField: 'username', usernameField: 'username',
passwordField: 'password', passwordField: 'password',
@ -30,23 +28,19 @@ const Strategy = new PassportLocalStrategy(
logger.verbose('userData >', userData); logger.verbose('userData >', userData);
// create user record // create user record
const channelData = { const channelData = {
channelName: `@${username}`, channelName : `@${username}`,
channelClaimId: tx.claim_id, channelClaimId: tx.claim_id,
}; };
logger.verbose('channelData >', channelData); logger.verbose('channelData >', channelData);
// create certificate record // create certificate record
const certificateData = { const certificateData = {
claimId: tx.claim_id, claimId: tx.claim_id,
name: `@${username}`, name : `@${username}`,
// address, // address,
}; };
logger.verbose('certificateData >', certificateData); logger.verbose('certificateData >', certificateData);
// save user and certificate to db // save user and certificate to db
return Promise.all([ return Promise.all([db.User.create(userData), db.Channel.create(channelData), db.Certificate.create(certificateData)]);
db.User.create(userData),
db.Channel.create(channelData),
db.Certificate.create(certificateData),
]);
}) })
.then(([newUser, newChannel, newCertificate]) => { .then(([newUser, newChannel, newCertificate]) => {
logger.verbose('user and certificate successfully created'); logger.verbose('user and certificate successfully created');
@ -60,10 +54,7 @@ const Strategy = new PassportLocalStrategy(
}) })
.then(() => { .then(() => {
logger.verbose('user and certificate successfully associated'); logger.verbose('user and certificate successfully associated');
return db.Certificate.getShortChannelIdFromLongChannelId( return db.Certificate.getShortChannelIdFromLongChannelId(userInfo.channelClaimId, userInfo.channelName);
userInfo.channelClaimId,
userInfo.channelName
);
}) })
.then(shortChannelId => { .then(shortChannelId => {
userInfo['shortChannelId'] = shortChannelId; userInfo['shortChannelId'] = shortChannelId;
@ -75,4 +66,3 @@ const Strategy = new PassportLocalStrategy(
}); });
} }
); );
export default Strategy;

View file

@ -3,4 +3,4 @@ const serializeUser = (user, done) => {
done(null, user); done(null, user);
}; };
export default serializeUser; module.exports = serializeUser;

View file

@ -1,18 +1,17 @@
// load dependencies // load dependencies
import logger from 'winston'; const logger = require('winston');
import db from 'server/models'; const db = require('../models');
require('../helpers/configureLogger.js')(logger); require('../helpers/configureLogger.js')(logger);
let totalClaims = 0; let totalClaims = 0;
let totalClaimsNoCertificate = 0; let totalClaimsNoCertificate = 0;
db.sequelize db.sequelize.sync() // sync sequelize
.sync() // sync sequelize
.then(() => { .then(() => {
logger.info('finding claims with no channels'); logger.info('finding claims with no channels');
return db.Claim.findAll({ return db.Claim.findAll({
where: { where: {
channelName: null, channelName : null,
certificateId: { certificateId: {
$ne: null, $ne: null,
}, },
@ -22,9 +21,10 @@ db.sequelize
.then(claimsArray => { .then(claimsArray => {
totalClaims = claimsArray.length; totalClaims = claimsArray.length;
const claimsUpdatePromises = claimsArray.map(claim => { const claimsUpdatePromises = claimsArray.map(claim => {
return db.Certificate.findOne({ return db.Certificate
where: { claimId: claim.get('certificateId') }, .findOne({
}) where: { claimId: claim.get('certificateId') },
})
.then(certificate => { .then(certificate => {
// if a certificate is found... // if a certificate is found...
if (certificate) { if (certificate) {
@ -49,6 +49,6 @@ db.sequelize
logger.info('total claims found with no matching certificate record', totalClaimsNoCertificate); logger.info('total claims found with no matching certificate record', totalClaimsNoCertificate);
logger.debug('all done'); logger.debug('all done');
}) })
.catch(error => { .catch((error) => {
logger.error(error); logger.error(error);
}); });

Some files were not shown because too many files have changed in this diff Show more