From dd0886baf409b4007368226c3c28188a5be5fadc Mon Sep 17 00:00:00 2001 From: jessop Date: Fri, 12 Apr 2019 10:25:06 -0400 Subject: [PATCH] replaces most require with es6 import/export --- package-lock.json | 120 +++++ package.json | 1 + server.js | 3 +- server/chainquery/index.js | 46 +- server/controllers/api/blocked/index.js | 6 +- .../availability/checkChannelAvailability.js | 19 +- .../api/channel/availability/index.js | 12 +- .../api/channel/claims/getChannelClaims.js | 10 +- .../controllers/api/channel/claims/index.js | 8 +- .../api/channel/data/getChannelData.js | 19 +- server/controllers/api/channel/data/index.js | 15 +- .../controllers/api/channel/shortId/index.js | 12 +- server/controllers/api/claim/abandon/index.js | 14 +- .../availability/checkClaimAvailability.js | 16 +- .../api/claim/availability/index.js | 10 +- server/controllers/api/claim/data/index.js | 10 +- server/controllers/api/claim/get/index.js | 20 +- server/controllers/api/claim/list/index.js | 6 +- server/controllers/api/claim/longId/index.js | 14 +- .../api/claim/publish/authentication.js | 17 +- .../api/claim/publish/createPublishParams.js | 6 +- .../publish/createThumbnailPublishParams.js | 6 +- .../api/claim/publish/deleteFile.js | 8 +- server/controllers/api/claim/publish/index.js | 55 +-- .../publish/parsePublishApiRequestBody.js | 2 +- .../parsePublishApiRequestBody.test.js | 8 +- .../publish/parsePublishApiRequestFiles.js | 8 +- .../parsePublishApiRequestFiles.test.js | 14 +- .../controllers/api/claim/publish/publish.js | 17 +- .../claim/publish/validateFileForPublish.js | 6 +- .../claim/publish/validateFileTypeAndSize.js | 4 +- server/controllers/api/claim/resolve/index.js | 6 +- server/controllers/api/claim/shortId/index.js | 6 +- server/controllers/api/claim/update/index.js | 37 +- server/controllers/api/claim/views/index.js | 8 +- .../api/config/site/publishing/index.js | 22 +- .../api/file/availability/index.js | 12 +- .../api/homepage/data/getChannelData.js | 11 +- server/controllers/api/homepage/data/index.js | 6 +- .../api/oEmbed/getOEmbedDataForAsset.js | 15 +- .../api/oEmbed/getOEmbedDataForChannel.js | 51 +-- server/controllers/api/oEmbed/index.js | 20 +- .../controllers/api/oEmbed/parseSpeechUrl.js | 17 +- .../controllers/api/special/claims/index.js | 29 +- server/controllers/api/tor/index.js | 8 +- server/controllers/api/user/password/index.js | 15 +- server/controllers/assets/serveAsset/index.js | 6 +- .../controllers/assets/serveByClaim/index.js | 18 +- .../assets/serveByIdentifierAndClaim/index.js | 35 +- .../assets/utils/determineRequestType.js | 6 +- .../assets/utils/flipClaimNameAndId.js | 20 +- .../assets/utils/getClaimIdAndServeAsset.js | 34 +- .../assets/utils/getLocalFileRecord.js | 17 +- .../assets/utils/logRequestData.js | 4 +- server/controllers/assets/utils/serveFile.js | 16 +- .../assets/utils/transformImage.js | 10 +- server/controllers/auth/login/index.js | 10 +- server/controllers/auth/logout/index.js | 2 +- server/controllers/auth/signup/index.js | 6 +- server/controllers/auth/user/index.js | 4 +- .../controllers/pages/sendVideoEmbedPage.js | 36 +- server/controllers/utils/errorHandlers.js | 83 ++-- server/controllers/utils/getClaimId.js | 12 +- server/controllers/utils/redirect.js | 4 +- server/index.js | 53 ++- server/lbrynet/index.js | 413 +++++++++--------- server/lbrynet/utils/handleLbrynetResponse.js | 6 +- .../middleware/autoblockPublishMiddleware.js | 18 +- server/middleware/logMetricsMiddleware.js | 33 +- server/middleware/multipartMiddleware.js | 9 +- server/middleware/requestLogger.js | 8 +- server/middleware/torCheckMiddleware.js | 23 +- server/models/blocked.js | 17 +- server/models/certificate.js | 101 +++-- server/models/channel.js | 6 +- server/models/claim.js | 19 +- server/models/file.js | 20 +- server/models/index.js | 59 ++- server/models/metrics.js | 24 +- server/models/tor.js | 17 +- server/models/trending.js | 40 +- server/models/user.js | 17 +- server/models/utils/createClaimRecordData.js | 63 ++- .../models/utils/createDatabaseIfNotExists.js | 13 +- server/models/utils/createFileRecordData.js | 49 +-- server/models/utils/returnShortId.js | 4 +- server/models/utils/returnShortId.test.js | 28 +- server/models/utils/trendingAnalysis.js | 27 +- server/models/views.js | 30 +- server/render/renderFullPage.js | 6 +- server/routes/api/index.js | 118 +++-- server/routes/assets/index.js | 16 +- server/routes/auth/index.js | 19 +- server/routes/pages/index.js | 30 +- server/speechPassport/index.js | 12 +- .../speechPassport/utils/deserializeUser.js | 2 +- server/speechPassport/utils/local-login.js | 24 +- server/speechPassport/utils/local-signup.js | 26 +- server/speechPassport/utils/serializeUser.js | 2 +- server/task-scripts/update-channel-names.js | 18 +- server/task-scripts/update-password.js | 14 +- server/utils/awaitFileSize.js | 6 +- server/utils/blockList.js | 26 +- server/utils/configureLogging.js | 20 +- server/utils/configureSlack.js | 33 +- server/utils/createModuleAliases.js | 4 +- server/utils/fetchClaimData.js | 10 +- server/utils/getClaimData.js | 23 +- server/utils/getMediaDimensions.js | 14 +- server/utils/googleAnalytics.js | 46 +- server/utils/imageProcessing.js | 8 +- server/utils/isRequestLocal.js | 11 +- server/utils/isValidQueryObj.js | 3 +- server/utils/parseQuerystring.js | 2 +- server/utils/processTrending.js | 29 +- server/utils/publishCache.js | 4 +- server/utils/videoProcessing.js | 10 +- utils/createModuleAliases.js | 2 +- utils/isApprovedChannel.js | 6 +- 119 files changed, 1412 insertions(+), 1327 deletions(-) diff --git a/package-lock.json b/package-lock.json index 0ae0bc20..a9a4d4b1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -196,6 +196,116 @@ "@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": { "version": "7.1.0", "resolved": "https://registry.npmjs.org/@babel/helper-define-map/-/helper-define-map-7.1.0.tgz", @@ -422,6 +532,16 @@ "@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": { "version": "7.2.0", "resolved": "https://registry.npmjs.org/@babel/plugin-proposal-json-strings/-/plugin-proposal-json-strings-7.2.0.tgz", diff --git a/package.json b/package.json index 888402ce..7ede97a3 100644 --- a/package.json +++ b/package.json @@ -86,6 +86,7 @@ "devDependencies": { "@babel/cli": "^7.1.5", "@babel/core": "^7.2.0", + "@babel/plugin-proposal-class-properties": "^7.3.3", "@babel/plugin-proposal-object-rest-spread": "^7.0.0", "@babel/polyfill": "^7.0.0", "@babel/preset-env": "^7.2.0", diff --git a/server.js b/server.js index f65a8a46..90d20adb 100644 --- a/server.js +++ b/server.js @@ -14,12 +14,11 @@ try { let currentApp; try { - const Server = require('./server/'); + const Server = require('./server/').default; currentApp = Server; const speech = new Server(); speech.start(); - } catch (error) { console.log('server startup error:', error); process.exit(1); diff --git a/server/chainquery/index.js b/server/chainquery/index.js index 9211e29e..9976a270 100644 --- a/server/chainquery/index.js +++ b/server/chainquery/index.js @@ -1,5 +1,5 @@ -const Sequelize = require('sequelize'); -const logger = require('winston'); +import Sequelize from 'sequelize'; +import logger from 'winston'; import abnormalClaimTable from './tables/abnormalClaimTable'; import addressTable from './tables/addressTable'; @@ -22,51 +22,45 @@ import transactionAddressQueries from './queries/transactionAddressQueries'; import transactionQueries from './queries/transactionQueries'; const DATABASE_STRUCTURE = { - 'abnormal_claim': { + abnormal_claim: { table: abnormalClaimTable, queries: abnormalClaimQueries, }, - 'address': { + address: { table: addressTable, queries: addressQueries, }, - 'block': { + block: { table: blockTable, queries: blockQueries, }, - 'claim': { + claim: { table: claimTable, queries: claimQueries, }, - 'input': { + input: { table: inputTable, queries: inputQueries, }, - 'output': { + output: { table: outputTable, queries: outputQueries, }, - 'support': { + support: { table: supportTable, queries: supportQueries, }, - 'transaction_address': { + transaction_address: { table: transactionAddressTable, queries: transactionAddressQueries, }, - 'transaction': { + transaction: { table: transactionTable, queries: transactionQueries, }, }; -const { - host, - port, - database, - username, - password, -} = require('@config/chainqueryConfig'); +const { host, port, database, username, password } = require('@config/chainqueryConfig'); if (!database || !username || !password) { logger.warn('missing database, user, or password from chainqueryConfig'); @@ -74,17 +68,17 @@ if (!database || !username || !password) { // set sequelize options const sequelize = new Sequelize(database, username, password, { - host : host, - import : port, - dialect : 'mysql', + host: host, + import: port, + dialect: 'mysql', dialectOptions: { decimalNumbers: true, }, logging: false, - pool : { - max : 5, - min : 0, - idle : 10000, + pool: { + max: 5, + min: 0, + idle: 10000, acquire: 10000, }, operatorsAliases: false, @@ -93,7 +87,7 @@ const sequelize = new Sequelize(database, username, password, { const db = {}; 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 currentData = DATABASE_STRUCTURE[dbKey]; diff --git a/server/controllers/api/blocked/index.js b/server/controllers/api/blocked/index.js index aad2dfc2..57304c9a 100644 --- a/server/controllers/api/blocked/index.js +++ b/server/controllers/api/blocked/index.js @@ -1,5 +1,5 @@ -const logger = require('winston'); -const db = require('../../../models'); +import logger from 'winston'; +import db from 'server/models'; const updateBlockedList = (req, res) => { db.Blocked.refreshTable() @@ -19,4 +19,4 @@ const updateBlockedList = (req, res) => { }); }; -module.exports = updateBlockedList; +export default updateBlockedList; diff --git a/server/controllers/api/channel/availability/checkChannelAvailability.js b/server/controllers/api/channel/availability/checkChannelAvailability.js index 3261c63f..aeba57af 100644 --- a/server/controllers/api/channel/availability/checkChannelAvailability.js +++ b/server/controllers/api/channel/availability/checkChannelAvailability.js @@ -1,18 +1,17 @@ -const db = require('../../../../models'); +import db from 'server/models'; -const checkChannelAvailability = (name) => { - return db.Channel - .findAll({ - where: { - channelName: name, - }, - }) +const checkChannelAvailability = name => { + return db.Channel.findAll({ + where: { + channelName: name, + }, + }) .then(result => { - return (result.length <= 0); + return result.length <= 0; }) .catch(error => { throw error; }); }; -module.exports = checkChannelAvailability; +export default checkChannelAvailability; diff --git a/server/controllers/api/channel/availability/index.js b/server/controllers/api/channel/availability/index.js index 5e3d0995..5b410003 100644 --- a/server/controllers/api/channel/availability/index.js +++ b/server/controllers/api/channel/availability/index.js @@ -1,6 +1,6 @@ -const checkChannelAvailability = require('./checkChannelAvailability.js'); -const { sendGATimingEvent } = require('../../../../utils/googleAnalytics.js'); -const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); +import checkChannelAvailability from './checkChannelAvailability.js'; +import { sendGATimingEvent } from '@serverutils/googleAnalytics.js'; +import { handleErrorResponse } from '../../../utils/errorHandlers.js'; /* @@ -8,7 +8,7 @@ const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); */ -function addAtSymbolIfNecessary (name) { +function addAtSymbolIfNecessary(name) { if (name.substring(0, 1) !== '@') { return `@${name}`; } @@ -22,7 +22,7 @@ const channelAvailability = ({ ip, originalUrl, params: { name } }, res) => { .then(isAvailable => { let responseObject = { success: true, - data : isAvailable, + data: isAvailable, }; if (isAvailable) { responseObject['message'] = `${name} is available`; @@ -37,4 +37,4 @@ const channelAvailability = ({ ip, originalUrl, params: { name } }, res) => { }); }; -module.exports = channelAvailability; +export default channelAvailability; diff --git a/server/controllers/api/channel/claims/getChannelClaims.js b/server/controllers/api/channel/claims/getChannelClaims.js index 8b7eee60..488b3689 100644 --- a/server/controllers/api/channel/claims/getChannelClaims.js +++ b/server/controllers/api/channel/claims/getChannelClaims.js @@ -1,7 +1,7 @@ -const chainquery = require('chainquery').default; -const logger = require('winston'); -const getClaimData = require('server/utils/getClaimData'); -const { returnPaginatedChannelClaims } = require('./channelPagination.js'); +import chainquery from 'chainquery'; +import logger from 'winston'; +import getClaimData from 'server/utils/getClaimData'; +import { returnPaginatedChannelClaims } from './channelPagination.js'; const getChannelClaims = async (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); }; -module.exports = getChannelClaims; +export default getChannelClaims; diff --git a/server/controllers/api/channel/claims/index.js b/server/controllers/api/channel/claims/index.js index 473394b2..b74d68ff 100644 --- a/server/controllers/api/channel/claims/index.js +++ b/server/controllers/api/channel/claims/index.js @@ -1,5 +1,5 @@ -const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); -const getChannelClaims = require('./getChannelClaims.js'); +import { handleErrorResponse } from '../../../utils/errorHandlers.js'; +import getChannelClaims from './getChannelClaims.js'; const NO_CHANNEL = 'NO_CHANNEL'; @@ -16,7 +16,7 @@ const channelClaims = ({ ip, originalUrl, body, params }, res) => { const page = params.page; getChannelClaims(channelName, channelClaimId, page) .then(data => { - res.status(200).json({success: true, data}); + res.status(200).json({ success: true, data }); }) .catch(error => { if (error === NO_CHANNEL) { @@ -29,4 +29,4 @@ const channelClaims = ({ ip, originalUrl, body, params }, res) => { }); }; -module.exports = channelClaims; +export default channelClaims; diff --git a/server/controllers/api/channel/data/getChannelData.js b/server/controllers/api/channel/data/getChannelData.js index 97b49dad..b30fd12e 100644 --- a/server/controllers/api/channel/data/getChannelData.js +++ b/server/controllers/api/channel/data/getChannelData.js @@ -1,18 +1,25 @@ -const db = require('server/models'); -const chainquery = require('chainquery').default; +import db from 'server/models'; +import chainquery from 'chainquery'; const getChannelData = async (channelName, channelClaimId) => { - let longChannelClaimId = await chainquery.claim.queries.getLongClaimId(channelName, channelClaimId).catch(() => false); + let longChannelClaimId = await chainquery.claim.queries + .getLongClaimId(channelName, channelClaimId) + .catch(() => false); if (!longChannelClaimId) { // Allow an error to throw here if this fails longChannelClaimId = await db.Certificate.getLongChannelId(channelName, channelClaimId); } - let shortChannelClaimId = await chainquery.claim.queries.getShortClaimIdFromLongClaimId(longChannelClaimId, channelName).catch(() => false); + let shortChannelClaimId = await chainquery.claim.queries + .getShortClaimIdFromLongClaimId(longChannelClaimId, channelName) + .catch(() => false); if (!shortChannelClaimId) { - shortChannelClaimId = await db.Certificate.getShortChannelIdFromLongChannelId(longChannelClaimId, channelName); + shortChannelClaimId = await db.Certificate.getShortChannelIdFromLongChannelId( + longChannelClaimId, + channelName + ); } return { @@ -22,4 +29,4 @@ const getChannelData = async (channelName, channelClaimId) => { }; }; -module.exports = getChannelData; +export default getChannelData; diff --git a/server/controllers/api/channel/data/index.js b/server/controllers/api/channel/data/index.js index 612eb016..843c5510 100644 --- a/server/controllers/api/channel/data/index.js +++ b/server/controllers/api/channel/data/index.js @@ -1,7 +1,8 @@ -const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); -const getChannelData = require('./getChannelData.js'); -const isApprovedChannel = require('../../../../../utils/isApprovedChannel'); -const { publishing: { serveOnlyApproved, approvedChannels } } = require('@config/siteConfig'); +import { handleErrorResponse } from '../../../utils/errorHandlers.js'; +import getChannelData from './getChannelData.js'; +import isApprovedChannel from '@globalutils/isApprovedChannel'; +import { publishing } from '@config/siteConfig'; +const { serveOnlyApproved, approvedChannels } = publishing; const NO_CHANNEL = 'NO_CHANNEL'; const LONG_ID = 'longId'; @@ -20,7 +21,9 @@ const channelData = ({ ip, originalUrl, body, params }, res) => { if (channelClaimId === 'none') channelClaimId = null; const chanObj = {}; if (channelName) chanObj.name = channelName; - if (channelClaimId) chanObj[(channelClaimId.length === LONG_CLAIM_LENGTH ? LONG_ID : SHORT_ID)] = channelClaimId; + if (channelClaimId) { + chanObj[channelClaimId.length === LONG_CLAIM_LENGTH ? LONG_ID : SHORT_ID] = channelClaimId; + } if (serveOnlyApproved && !isApprovedChannel(chanObj, approvedChannels)) { return res.status(404).json({ success: false, @@ -46,4 +49,4 @@ const channelData = ({ ip, originalUrl, body, params }, res) => { }); }; -module.exports = channelData; +export default channelData; diff --git a/server/controllers/api/channel/shortId/index.js b/server/controllers/api/channel/shortId/index.js index 1c604688..5bc7cd11 100644 --- a/server/controllers/api/channel/shortId/index.js +++ b/server/controllers/api/channel/shortId/index.js @@ -1,6 +1,6 @@ -const { handleErrorResponse } = require('server/controllers/utils/errorHandlers.js'); -const db = require('server/models'); -const chainquery = require('chainquery').default; +import { handleErrorResponse } from 'server/controllers/utils/errorHandlers.js'; +import db from 'server/models'; +import chainquery from 'chainquery'; /* @@ -10,7 +10,9 @@ route to get a short channel id from long channel Id const channelShortIdRoute = async ({ ip, originalUrl, params }, res) => { try { - let shortId = await chainquery.claim.queries.getShortClaimIdFromLongClaimId(params.longId, params.name).catch(() => false); + let shortId = await chainquery.claim.queries + .getShortClaimIdFromLongClaimId(params.longId, params.name) + .catch(() => false); if (!shortId) { shortId = await db.Certificate.getShortChannelIdFromLongChannelId(params.longId, params.name); @@ -22,4 +24,4 @@ const channelShortIdRoute = async ({ ip, originalUrl, params }, res) => { } }; -module.exports = channelShortIdRoute; +export default channelShortIdRoute; diff --git a/server/controllers/api/claim/abandon/index.js b/server/controllers/api/claim/abandon/index.js index 9226878d..6dd58b82 100644 --- a/server/controllers/api/claim/abandon/index.js +++ b/server/controllers/api/claim/abandon/index.js @@ -1,9 +1,9 @@ -const logger = require('winston'); -const db = require('server/models'); -const chainquery = require('chainquery').default; -const { abandonClaim } = require('server/lbrynet'); -const deleteFile = require('../publish/deleteFile.js'); -const authenticateUser = require('../publish/authentication.js'); +import logger from 'winston'; +import db from 'server/models'; +import chainquery from 'chainquery'; +import { abandonClaim } from 'server/lbrynet'; +import deleteFile from '../publish/deleteFile.js'; +import authenticateUser from '../publish/authentication.js'; /* route to abandon a claim through the daemon @@ -47,4 +47,4 @@ const claimAbandon = async (req, res) => { } }; -module.exports = claimAbandon; +export default claimAbandon; diff --git a/server/controllers/api/claim/availability/checkClaimAvailability.js b/server/controllers/api/claim/availability/checkClaimAvailability.js index 691cfae9..39cca8cd 100644 --- a/server/controllers/api/claim/availability/checkClaimAvailability.js +++ b/server/controllers/api/claim/availability/checkClaimAvailability.js @@ -1,16 +1,18 @@ -const chainquery = require('chainquery').default; -const { publishing: { primaryClaimAddress, additionalClaimAddresses } } = require('@config/siteConfig'); -const Sequelize = require('sequelize'); +import chainquery from 'chainquery'; +import Sequelize from 'sequelize'; + +import { publishing } from '@config/siteConfig'; +const { primaryClaimAddress, additionalClaimAddresses } = publishing; const Op = Sequelize.Op; -const claimAvailability = async (name) => { +const claimAvailability = async name => { const claimAddresses = additionalClaimAddresses || []; claimAddresses.push(primaryClaimAddress); // find any records where the name is used return chainquery.claim .findAll({ attributes: ['claim_address'], - where : { + where: { name, claim_address: { [Op.or]: claimAddresses, @@ -18,11 +20,11 @@ const claimAvailability = async (name) => { }, }) .then(result => { - return (result.length <= 0); + return result.length <= 0; }) .catch(error => { throw error; }); }; -module.exports = claimAvailability; +export default claimAvailability; diff --git a/server/controllers/api/claim/availability/index.js b/server/controllers/api/claim/availability/index.js index d73e68e6..9ae1d5b0 100644 --- a/server/controllers/api/claim/availability/index.js +++ b/server/controllers/api/claim/availability/index.js @@ -1,6 +1,6 @@ -const checkClaimAvailability = require('./checkClaimAvailability.js'); -const { sendGATimingEvent } = require('../../../../utils/googleAnalytics.js'); -const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); +import checkClaimAvailability from './checkClaimAvailability.js'; +import { sendGATimingEvent } from '../../../../utils/googleAnalytics.js'; +import { handleErrorResponse } from '../../../utils/errorHandlers.js'; /* @@ -14,7 +14,7 @@ const claimAvailability = ({ ip, originalUrl, params: { name } }, res) => { .then(isAvailable => { let responseObject = { success: true, - data : isAvailable, + data: isAvailable, }; if (isAvailable) { responseObject['message'] = `That claim name is available`; @@ -29,4 +29,4 @@ const claimAvailability = ({ ip, originalUrl, params: { name } }, res) => { }); }; -module.exports = claimAvailability; +export default claimAvailability; diff --git a/server/controllers/api/claim/data/index.js b/server/controllers/api/claim/data/index.js index e0147850..33846f41 100644 --- a/server/controllers/api/claim/data/index.js +++ b/server/controllers/api/claim/data/index.js @@ -1,7 +1,7 @@ -const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); -const getClaimData = require('server/utils/getClaimData'); -const fetchClaimData = require('server/utils/fetchClaimData'); -const logger = require('winston'); +import { handleErrorResponse } from '../../../utils/errorHandlers.js'; +import getClaimData from 'server/utils/getClaimData'; +import fetchClaimData from 'server/utils/fetchClaimData'; +import logger from 'winston'; /* route to return data for a claim @@ -28,4 +28,4 @@ const claimData = async ({ ip, originalUrl, body, params }, res) => { } }; -module.exports = claimData; +export default claimData; diff --git a/server/controllers/api/claim/get/index.js b/server/controllers/api/claim/get/index.js index 248c6e80..883a0bc8 100644 --- a/server/controllers/api/claim/get/index.js +++ b/server/controllers/api/claim/get/index.js @@ -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 { 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 TIMEOUT_MS = 15000; @@ -83,4 +83,4 @@ const claimGet = async ({ ip, originalUrl, params, headers }, res) => { handleErrorResponse(originalUrl, ip, error, res); } }; -module.exports = claimGet; +export default claimGet; diff --git a/server/controllers/api/claim/list/index.js b/server/controllers/api/claim/list/index.js index bb7eb1d0..94ad3ee0 100644 --- a/server/controllers/api/claim/list/index.js +++ b/server/controllers/api/claim/list/index.js @@ -1,5 +1,5 @@ -const { getClaimList } = require('../../../../lbrynet'); -const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); +import { getClaimList } from 'server/lbrynet'; +import { handleErrorResponse } from '../../../utils/errorHandlers.js'; /* @@ -17,4 +17,4 @@ const claimList = ({ ip, originalUrl, params }, res) => { }); }; -module.exports = claimList; +export default claimList; diff --git a/server/controllers/api/claim/longId/index.js b/server/controllers/api/claim/longId/index.js index 0e6ceefd..dec98220 100644 --- a/server/controllers/api/claim/longId/index.js +++ b/server/controllers/api/claim/longId/index.js @@ -1,10 +1,10 @@ -const db = require('server/models'); -const chainquery = require('chainquery').default; -const logger = require('winston'); -const publishCache = require('server/utils/publishCache'); -const { handleErrorResponse } = require('server/controllers/utils/errorHandlers.js'); +import db from 'server/models'; +import chainquery from 'chainquery'; +import logger from 'winston'; +import publishCache from 'server/utils/publishCache'; +import { handleErrorResponse } from 'server/controllers/utils/errorHandlers.js'; -const getClaimId = require('server/controllers/utils/getClaimId.js'); +import getClaimId from 'server/controllers/utils/getClaimId.js'; const NO_CHANNEL = 'NO_CHANNEL'; const NO_CLAIM = 'NO_CLAIM'; @@ -72,4 +72,4 @@ const claimLongId = ({ ip, originalUrl, body, params }, res) => { }); }; -module.exports = claimLongId; +export default claimLongId; diff --git a/server/controllers/api/claim/publish/authentication.js b/server/controllers/api/claim/publish/authentication.js index 7464e294..81b0cdfd 100644 --- a/server/controllers/api/claim/publish/authentication.js +++ b/server/controllers/api/claim/publish/authentication.js @@ -1,5 +1,5 @@ -const logger = require('winston'); -const db = require('../../../../models'); +import logger from 'winston'; +import db from 'server/models'; const authenticateChannelCredentials = (channelName, channelId, userPassword) => { return new Promise((resolve, reject) => { @@ -10,10 +10,9 @@ const authenticateChannelCredentials = (channelName, channelId, userPassword) => if (channelName) channelFindParams['channelName'] = channelName; if (channelId) channelFindParams['channelClaimId'] = channelId; // find the channel - db.Channel - .findOne({ - where: channelFindParams, - }) + db.Channel.findOne({ + where: channelFindParams, + }) .then(channel => { if (!channel) { logger.debug('no channel found'); @@ -51,7 +50,7 @@ const authenticateUser = (channelName, channelId, channelPassword, user) => { // case: no channelName or channel Id are provided (anonymous), regardless of whether user token is provided if (!channelName && !channelId) { resolve({ - channelName : null, + channelName: null, channelClaimId: null, }); return; @@ -67,7 +66,7 @@ const authenticateUser = (channelName, channelId, channelPassword, user) => { return; } resolve({ - channelName : user.channelName, + channelName: user.channelName, channelClaimId: user.channelClaimId, }); return; @@ -81,4 +80,4 @@ const authenticateUser = (channelName, channelId, channelPassword, user) => { }); }; -module.exports = authenticateUser; +export default authenticateUser; diff --git a/server/controllers/api/claim/publish/createPublishParams.js b/server/controllers/api/claim/publish/createPublishParams.js index 0a51cba8..73209d4e 100644 --- a/server/controllers/api/claim/publish/createPublishParams.js +++ b/server/controllers/api/claim/publish/createPublishParams.js @@ -1,5 +1,5 @@ -const logger = require('winston'); -const { details, publishing } = require('@config/siteConfig'); +import logger from 'winston'; +import { details, publishing } from '@config/siteConfig'; const createPublishParams = ( filePath, name, @@ -59,4 +59,4 @@ const createPublishParams = ( return publishParams; }; -module.exports = createPublishParams; +export default createPublishParams; diff --git a/server/controllers/api/claim/publish/createThumbnailPublishParams.js b/server/controllers/api/claim/publish/createThumbnailPublishParams.js index a848aab5..2912b292 100644 --- a/server/controllers/api/claim/publish/createThumbnailPublishParams.js +++ b/server/controllers/api/claim/publish/createThumbnailPublishParams.js @@ -1,5 +1,5 @@ -const logger = require('winston'); -const { details, publishing } = require('@config/siteConfig'); +import logger from 'winston'; +import { details, publishing } from '@config/siteConfig'; const createThumbnailPublishParams = (thumbnailFilePath, claimName, license, licenseUrl, nsfw) => { if (!thumbnailFilePath) { @@ -26,4 +26,4 @@ const createThumbnailPublishParams = (thumbnailFilePath, claimName, license, lic }; }; -module.exports = createThumbnailPublishParams; +export default createThumbnailPublishParams; diff --git a/server/controllers/api/claim/publish/deleteFile.js b/server/controllers/api/claim/publish/deleteFile.js index 2d9fe69f..8c98d89f 100644 --- a/server/controllers/api/claim/publish/deleteFile.js +++ b/server/controllers/api/claim/publish/deleteFile.js @@ -1,7 +1,7 @@ -const logger = require('winston'); -const fs = require('fs'); +import logger from 'winston'; +import fs from 'fs'; -const deleteFile = (filePath) => { +const deleteFile = filePath => { fs.unlink(filePath, err => { if (err) { return logger.error(`error deleting temporary file ${filePath}`); @@ -10,4 +10,4 @@ const deleteFile = (filePath) => { }); }; -module.exports = deleteFile; +export default deleteFile; diff --git a/server/controllers/api/claim/publish/index.js b/server/controllers/api/claim/publish/index.js index 2cbb555b..eb1876af 100644 --- a/server/controllers/api/claim/publish/index.js +++ b/server/controllers/api/claim/publish/index.js @@ -1,30 +1,33 @@ -const logger = require('winston'); +import logger from '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 { - details: { host }, - publishing: { disabled, disabledMessage }, -} = require('@config/siteConfig'); - -const { sendGATimingEvent } = require('server/utils/googleAnalytics.js'); -const isApprovedChannel = require('@globalutils/isApprovedChannel'); -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'); + disabled, + disabledMessage, + publishOnlyApproved, + approvedChannels, + thumbnailChannel, + thumbnailChannelId, +} = publishing; const CLAIM_TAKEN = 'CLAIM_TAKEN'; const UNAPPROVED_CHANNEL = 'UNAPPROVED_CHANNEL'; @@ -218,4 +221,4 @@ const claimPublish = ({ body, files, headers, ip, originalUrl, user, tor }, res) }); }; -module.exports = claimPublish; +export default claimPublish; diff --git a/server/controllers/api/claim/publish/parsePublishApiRequestBody.js b/server/controllers/api/claim/publish/parsePublishApiRequestBody.js index f98c3369..8a40e342 100644 --- a/server/controllers/api/claim/publish/parsePublishApiRequestBody.js +++ b/server/controllers/api/claim/publish/parsePublishApiRequestBody.js @@ -36,4 +36,4 @@ const parsePublishApiRequestBody = ({ }; }; -module.exports = parsePublishApiRequestBody; +export default parsePublishApiRequestBody; diff --git a/server/controllers/api/claim/publish/parsePublishApiRequestBody.test.js b/server/controllers/api/claim/publish/parsePublishApiRequestBody.test.js index e1a43c99..8e559958 100644 --- a/server/controllers/api/claim/publish/parsePublishApiRequestBody.test.js +++ b/server/controllers/api/claim/publish/parsePublishApiRequestBody.test.js @@ -1,14 +1,14 @@ -const chai = require('chai'); +import chai from 'chai'; const expect = chai.expect; -describe('#parsePublishApiRequestBody()', function () { +describe('#parsePublishApiRequestBody()', function() { 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(); }); - it('should throw an error if no body.name', function () { + it('should throw an error if no body.name', function() { const bodyNoName = {}; expect(parsePublishApiRequestBody.bind(this, bodyNoName)).to.throw(); }); diff --git a/server/controllers/api/claim/publish/parsePublishApiRequestFiles.js b/server/controllers/api/claim/publish/parsePublishApiRequestFiles.js index 6979740e..b59ba8f8 100644 --- a/server/controllers/api/claim/publish/parsePublishApiRequestFiles.js +++ b/server/controllers/api/claim/publish/parsePublishApiRequestFiles.js @@ -1,6 +1,6 @@ -const path = require('path'); -const validateFileTypeAndSize = require('./validateFileTypeAndSize.js'); -const validateFileForPublish = require('./validateFileForPublish.js'); +import path from 'path'; +import validateFileTypeAndSize from './validateFileTypeAndSize.js'; +import validateFileForPublish from './validateFileForPublish.js'; const parsePublishApiRequestFiles = ({ file, thumbnail }, isUpdate) => { // make sure a file was provided @@ -59,4 +59,4 @@ const parsePublishApiRequestFiles = ({ file, thumbnail }, isUpdate) => { return obj; }; -module.exports = parsePublishApiRequestFiles; +export default parsePublishApiRequestFiles; diff --git a/server/controllers/api/claim/publish/parsePublishApiRequestFiles.test.js b/server/controllers/api/claim/publish/parsePublishApiRequestFiles.test.js index 2eb7733d..49b704e6 100644 --- a/server/controllers/api/claim/publish/parsePublishApiRequestFiles.test.js +++ b/server/controllers/api/claim/publish/parsePublishApiRequestFiles.test.js @@ -1,19 +1,19 @@ -const chai = require('chai'); +import chai from 'chai'; const expect = chai.expect; -describe('#parsePublishApiRequestFiles()', function () { +describe('#parsePublishApiRequestFiles()', function() { 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(); }); - it('should throw an error if no files.file', function () { + it('should throw an error if no files.file', function() { const filesNoFile = {}; 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 = { file: { name: 'file.jpg', @@ -25,7 +25,7 @@ describe('#parsePublishApiRequestFiles()', function () { 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 = { file: { name: 'file.jpg', @@ -37,7 +37,7 @@ describe('#parsePublishApiRequestFiles()', function () { 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 = { file: { name: 'file.jpg', diff --git a/server/controllers/api/claim/publish/publish.js b/server/controllers/api/claim/publish/publish.js index d97b5073..2670a308 100644 --- a/server/controllers/api/claim/publish/publish.js +++ b/server/controllers/api/claim/publish/publish.js @@ -1,11 +1,9 @@ -const logger = require('winston'); -const db = require('../../../../models'); -const { publishClaim } = require('../../../../lbrynet'); -const { createFileRecordDataAfterPublish } = require('server/models/utils/createFileRecordData.js'); -const { - createClaimRecordDataAfterPublish, -} = require('server/models/utils/createClaimRecordData.js'); -const deleteFile = require('./deleteFile.js'); +import logger from 'winston'; +import db from '../../../../models'; +import { publishClaim } from '../../../../lbrynet'; +import { createFileRecordDataAfterPublish } from '../../../../models/utils/createFileRecordData.js'; +import { createClaimRecordDataAfterPublish } from '../../../../models/utils/createClaimRecordData.js'; +import deleteFile from './deleteFile.js'; const publish = async (publishParams, fileName, fileType) => { let publishResults; @@ -80,5 +78,4 @@ const publish = async (publishParams, fileName, fileType) => { }; } }; - -module.exports = publish; +export default publish; diff --git a/server/controllers/api/claim/publish/validateFileForPublish.js b/server/controllers/api/claim/publish/validateFileForPublish.js index 1047c048..dbb63a1a 100644 --- a/server/controllers/api/claim/publish/validateFileForPublish.js +++ b/server/controllers/api/claim/publish/validateFileForPublish.js @@ -1,6 +1,6 @@ -const logger = require('winston'); +import logger from 'winston'; -const { publishing } = require('@config/siteConfig.json'); +import { publishing } from '@config/siteConfig.json'; const { fileSizeLimits } = publishing; @@ -35,4 +35,4 @@ const validateFileForPublish = file => { return file; }; -module.exports = validateFileForPublish; +export default validateFileForPublish; diff --git a/server/controllers/api/claim/publish/validateFileTypeAndSize.js b/server/controllers/api/claim/publish/validateFileTypeAndSize.js index 997e6710..160f19bc 100644 --- a/server/controllers/api/claim/publish/validateFileTypeAndSize.js +++ b/server/controllers/api/claim/publish/validateFileTypeAndSize.js @@ -1,4 +1,4 @@ -const logger = require('winston'); +import logger from 'winston'; const { publishing: { maxSizeImage = 10000000, maxSizeGif = 50000000, maxSizeVideo = 50000000 }, @@ -41,4 +41,4 @@ const validateFileTypeAndSize = file => { return file; }; -module.exports = validateFileTypeAndSize; +export default validateFileTypeAndSize; diff --git a/server/controllers/api/claim/resolve/index.js b/server/controllers/api/claim/resolve/index.js index 9b057bda..ab54cf1f 100644 --- a/server/controllers/api/claim/resolve/index.js +++ b/server/controllers/api/claim/resolve/index.js @@ -1,5 +1,5 @@ -const { resolveUri } = require('../../../../lbrynet/index'); -const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); +import { resolveUri } from 'server/lbrynet/index'; +import { handleErrorResponse } from '../../../utils/errorHandlers.js'; /* @@ -17,4 +17,4 @@ const claimResolve = ({ headers, ip, originalUrl, params }, res) => { }); }; -module.exports = claimResolve; +export default claimResolve; diff --git a/server/controllers/api/claim/shortId/index.js b/server/controllers/api/claim/shortId/index.js index 2d62bbe7..c627bc49 100644 --- a/server/controllers/api/claim/shortId/index.js +++ b/server/controllers/api/claim/shortId/index.js @@ -1,5 +1,5 @@ -const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); -const chainquery = require('chainquery').default; +import { handleErrorResponse } from '../../../utils/errorHandlers.js'; +import chainquery from 'chainquery'; /* @@ -22,4 +22,4 @@ const claimShortId = async ({ ip, originalUrl, body, params }, res) => { } }; -module.exports = claimShortId; +export default claimShortId; diff --git a/server/controllers/api/claim/update/index.js b/server/controllers/api/claim/update/index.js index 6ca73f3a..d2b2b668 100644 --- a/server/controllers/api/claim/update/index.js +++ b/server/controllers/api/claim/update/index.js @@ -1,21 +1,20 @@ -const logger = require('winston'); -const db = require('server/models'); -const { - details, - publishing: { disabled, disabledMessage, primaryClaimAddress }, -} = require('@config/siteConfig'); -const { resolveUri } = require('server/lbrynet'); -const { sendGATimingEvent } = require('../../../../utils/googleAnalytics.js'); -const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); -const publish = require('../publish/publish.js'); -const parsePublishApiRequestBody = require('../publish/parsePublishApiRequestBody'); -const parsePublishApiRequestFiles = require('../publish/parsePublishApiRequestFiles.js'); -const authenticateUser = require('../publish/authentication.js'); -const createThumbnailPublishParams = require('../publish/createThumbnailPublishParams.js'); -const chainquery = require('chainquery').default; -const createCanonicalLink = require('@globalutils/createCanonicalLink'); -const { getFileListFileByOutpoint } = require('server/lbrynet'); -const publishCache = require('server/utils/publishCache'); +import logger from 'winston'; +import { sendGATimingEvent } from '@serverutils/googleAnalytics.js'; +import { handleErrorResponse } from '../../../utils/errorHandlers.js'; +import publish from '../publish/publish.js'; +import parsePublishApiRequestBody from '../publish/parsePublishApiRequestBody'; +import parsePublishApiRequestFiles from '../publish/parsePublishApiRequestFiles.js'; +import authenticateUser from '../publish/authentication.js'; +import createThumbnailPublishParams from '../publish/createThumbnailPublishParams.js'; +import chainquery from 'chainquery'; +import { getFileListFileByOutpoint } from 'server/lbrynet'; +import publishCache from 'server/utils/publishCache'; +import createCanonicalLink from '@globalutils/createCanonicalLink'; +import isApprovedChannel from '@globalutils/isApprovedChannel'; +import { details, publishing } from '@config/siteConfig'; +const { disabled, disabledMessage, primaryClaimAddress } = publishing; + +//, approvedChannels, thumbnailChannel, thumbnailChannelId /* route to update a claim through the daemon @@ -242,4 +241,4 @@ const claimUpdate = ({ body, files, headers, ip, originalUrl, user, tor }, res) }); }; -module.exports = claimUpdate; +export default claimUpdate; diff --git a/server/controllers/api/claim/views/index.js b/server/controllers/api/claim/views/index.js index 11e6500b..b85a4775 100644 --- a/server/controllers/api/claim/views/index.js +++ b/server/controllers/api/claim/views/index.js @@ -1,5 +1,5 @@ -const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); -const db = require('server/models'); +import { handleErrorResponse } from '../../../utils/errorHandlers.js'; +import db from 'server/models'; /* @@ -16,7 +16,7 @@ const claimViews = async ({ ip, originalUrl, body, params }, res) => { res.status(200).json({ success: true, - data : { + data: { [claimId]: viewCount, }, }); @@ -25,4 +25,4 @@ const claimViews = async ({ ip, originalUrl, body, params }, res) => { } }; -module.exports = claimViews; +export default claimViews; diff --git a/server/controllers/api/config/site/publishing/index.js b/server/controllers/api/config/site/publishing/index.js index 31c73160..a87b1a29 100644 --- a/server/controllers/api/config/site/publishing/index.js +++ b/server/controllers/api/config/site/publishing/index.js @@ -1,12 +1,14 @@ -const { publishing: { - primaryClaimAddress, - uploadDirectory, - thumbnailChannel, - thumbnailChannelId, - additionalClaimAddresses, - disabled, - disabledMessage, -} } = require('@config/siteConfig'); +const { + publishing: { + primaryClaimAddress, + uploadDirectory, + thumbnailChannel, + thumbnailChannelId, + additionalClaimAddresses, + disabled, + disabledMessage, + }, +} = require('@config/siteConfig'); /* @@ -26,4 +28,4 @@ const publishingConfig = (req, res) => { }); }; -module.exports = publishingConfig; +export default publishingConfig; diff --git a/server/controllers/api/file/availability/index.js b/server/controllers/api/file/availability/index.js index a6f2e6cd..d5cb27a2 100644 --- a/server/controllers/api/file/availability/index.js +++ b/server/controllers/api/file/availability/index.js @@ -1,10 +1,10 @@ -const logger = require('winston'); +import logger from 'winston'; -const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); -const { getFileListFileByOutpoint } = require('server/lbrynet'); +import { handleErrorResponse } from '../../../utils/errorHandlers.js'; +import { getFileListFileByOutpoint } from 'server/lbrynet'; -const chainquery = require('chainquery').default; -const publishCache = require('server/utils/publishCache'); +import chainquery from 'chainquery'; +import publishCache from 'server/utils/publishCache'; /* @@ -37,4 +37,4 @@ const fileAvailability = async ({ ip, originalUrl, params }, res) => { } }; -module.exports = fileAvailability; +export default fileAvailability; diff --git a/server/controllers/api/homepage/data/getChannelData.js b/server/controllers/api/homepage/data/getChannelData.js index a0db2374..260a9b0b 100644 --- a/server/controllers/api/homepage/data/getChannelData.js +++ b/server/controllers/api/homepage/data/getChannelData.js @@ -1,16 +1,13 @@ -const db = require('../../../../models'); +import db from 'server/models'; const getChannelData = (channelName, channelClaimId) => { return new Promise((resolve, reject) => { let longChannelClaimId; // 1. get the long channel Id (make sure channel exists) - db.Certificate - .getLongChannelId(channelName, channelClaimId) + db.Certificate.getLongChannelId(channelName, channelClaimId) .then(fullClaimId => { longChannelClaimId = fullClaimId; - return db - .Certificate - .getShortChannelIdFromLongChannelId(fullClaimId, channelName); + return db.Certificate.getShortChannelIdFromLongChannelId(fullClaimId, channelName); }) .then(shortChannelClaimId => { resolve({ @@ -25,4 +22,4 @@ const getChannelData = (channelName, channelClaimId) => { }); }; -module.exports = getChannelData; +export default getChannelData; diff --git a/server/controllers/api/homepage/data/index.js b/server/controllers/api/homepage/data/index.js index 610f1cb5..015dec65 100644 --- a/server/controllers/api/homepage/data/index.js +++ b/server/controllers/api/homepage/data/index.js @@ -1,6 +1,6 @@ -const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); +import { handleErrorResponse } from '../../../utils/errorHandlers.js'; -const getChannelData = require('./getChannelData.js'); +import getChannelData from './getChannelData.js'; const NO_CHANNEL = 'NO_CHANNEL'; @@ -32,4 +32,4 @@ const channelData = ({ ip, originalUrl, body, params }, res) => { }); }; -module.exports = channelData; +export default channelData; diff --git a/server/controllers/api/oEmbed/getOEmbedDataForAsset.js b/server/controllers/api/oEmbed/getOEmbedDataForAsset.js index bcdd1727..317f300b 100644 --- a/server/controllers/api/oEmbed/getOEmbedDataForAsset.js +++ b/server/controllers/api/oEmbed/getOEmbedDataForAsset.js @@ -1,11 +1,10 @@ -const logger = require('winston'); -const db = require('../../../models'); -const getClaimId = require('../../utils/getClaimId'); -const publishCache = require('server/utils/publishCache'); +import logger from 'winston'; +import db from 'server/models'; +import getClaimId from '../../utils/getClaimId'; +import publishCache from 'server/utils/publishCache'; -const { - details: { host, title: siteTitle }, -} = require('@config/siteConfig'); +import { details } from '@config/siteConfig'; +const { host, title: siteTitle } = details; const getOEmbedDataForAsset = (channelName, channelClaimId, claimName, claimId) => { let fileData, claimData; @@ -66,4 +65,4 @@ const getOEmbedDataForAsset = (channelName, channelClaimId, claimName, claimId) }); }; -module.exports = getOEmbedDataForAsset; +export default getOEmbedDataForAsset; diff --git a/server/controllers/api/oEmbed/getOEmbedDataForChannel.js b/server/controllers/api/oEmbed/getOEmbedDataForChannel.js index 8f2afab3..a3d24ec3 100644 --- a/server/controllers/api/oEmbed/getOEmbedDataForChannel.js +++ b/server/controllers/api/oEmbed/getOEmbedDataForChannel.js @@ -1,33 +1,26 @@ -const db = require('../../../models'); - -const { - details: { - host, - title: siteTitle, - }, -} = require('@config/siteConfig'); +import db from 'server/models'; +import { details } from '@config/siteConfig'; +const { host, title: siteTitle } = details; const getOEmbedDataForChannel = (channelName, channelClaimId) => { - return db.Certificate - .findOne({ - where: { - name : channelName, - claimId: channelClaimId, - }, - }) - .then(certificateRecord => { - const certificateData = certificateRecord.dataValues; - return { - version : 1.0, - provider_name: siteTitle, - provider_url : host, - type : 'link', - author_name : certificateData.name, - title : `${certificateData.name}'s channel on Spee.ch`, - author_url : `${host}/${certificateData.name}:${certificateData.claimId}`, - cache_age : 86400, // one day in seconds - }; - }); + return db.Certificate.findOne({ + where: { + name: channelName, + claimId: channelClaimId, + }, + }).then(certificateRecord => { + const certificateData = certificateRecord.dataValues; + return { + version: 1.0, + provider_name: siteTitle, + provider_url: host, + type: 'link', + author_name: certificateData.name, + title: `${certificateData.name}'s channel on Spee.ch`, + author_url: `${host}/${certificateData.name}:${certificateData.claimId}`, + cache_age: 86400, // one day in seconds + }; + }); }; -module.exports = getOEmbedDataForChannel; +export default getOEmbedDataForChannel; diff --git a/server/controllers/api/oEmbed/index.js b/server/controllers/api/oEmbed/index.js index 690b1fa0..256c29d1 100644 --- a/server/controllers/api/oEmbed/index.js +++ b/server/controllers/api/oEmbed/index.js @@ -1,12 +1,14 @@ -const logger = require('winston'); -const lbryUri = require('../../../../utils/lbryUri'); +import logger from 'winston'; +import lbryUri from '@globalutils/lbryUri'; -const getOEmbedDataForChannel = require('./getOEmbedDataForChannel'); -const getOEmbedDataForAsset = require('./getOEmbedDataForAsset'); -const parseSpeechUrl = require('./parseSpeechUrl'); +import getOEmbedDataForChannel from './getOEmbedDataForChannel'; +import getOEmbedDataForAsset from './getOEmbedDataForAsset'; +import parseSpeechUrl from './parseSpeechUrl'; const getOEmbedData = (req, res) => { - const { query: { url, format } } = req; + const { + query: { url, format }, + } = req; logger.debug('req url', url); logger.debug('req format', format); @@ -36,7 +38,7 @@ const getOEmbedData = (req, res) => { return res.status(200).json(data); } }) - .catch((error) => { + .catch(error => { return res.status(404).json({ success: false, message: error, @@ -54,7 +56,7 @@ const getOEmbedData = (req, res) => { return res.status(200).json(data); } }) - .catch((error) => { + .catch(error => { return res.status(404).json({ success: false, message: error, @@ -63,4 +65,4 @@ const getOEmbedData = (req, res) => { } }; -module.exports = getOEmbedData; +export default getOEmbedData; diff --git a/server/controllers/api/oEmbed/parseSpeechUrl.js b/server/controllers/api/oEmbed/parseSpeechUrl.js index 9b330f17..b677966f 100644 --- a/server/controllers/api/oEmbed/parseSpeechUrl.js +++ b/server/controllers/api/oEmbed/parseSpeechUrl.js @@ -1,17 +1,10 @@ -const logger = require('winston'); +import logger from 'winston'; -const parseSpeechUrl = (url) => { +const parseSpeechUrl = url => { 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}`); @@ -21,4 +14,4 @@ const parseSpeechUrl = (url) => { }; }; -module.exports = parseSpeechUrl; +export default parseSpeechUrl; diff --git a/server/controllers/api/special/claims/index.js b/server/controllers/api/special/claims/index.js index 851d2a93..c7378477 100644 --- a/server/controllers/api/special/claims/index.js +++ b/server/controllers/api/special/claims/index.js @@ -1,6 +1,6 @@ -const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); -const db = require('server/models'); -const getClaimData = require('server/utils/getClaimData'); +import { handleErrorResponse } from '../../../utils/errorHandlers.js'; +import db from 'server/models'; +import getClaimData from 'server/utils/getClaimData'; /* @@ -9,25 +9,22 @@ const getClaimData = require('server/utils/getClaimData'); */ const channelClaims = async ({ ip, originalUrl, body, params }, res) => { - const { - name, - page, - } = params; + const { name, page } = params; if (name === 'trending') { 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({ success: true, - data : { - channelName : name, + data: { + channelName: name, claims, longChannelClaimId: name, - currentPage : 1, - nextPage : null, - previousPage : null, - totalPages : 1, - totalResults : claims.length, + currentPage: 1, + nextPage: null, + previousPage: null, + totalPages: 1, + totalResults: claims.length, }, }); } @@ -39,4 +36,4 @@ const channelClaims = async ({ ip, originalUrl, body, params }, res) => { handleErrorResponse(originalUrl, ip, 'Feature endpoint not found', res); }; -module.exports = channelClaims; +export default channelClaims; diff --git a/server/controllers/api/tor/index.js b/server/controllers/api/tor/index.js index c5a8d64a..dd013154 100644 --- a/server/controllers/api/tor/index.js +++ b/server/controllers/api/tor/index.js @@ -1,5 +1,5 @@ -const logger = require('winston'); -const db = require('../../../models'); +import logger from 'winston'; +import db from 'server/models'; /* @@ -13,7 +13,7 @@ const getTorList = (req, res) => { logger.debug('number of records', result.length); res.status(200).json(result); }) - .catch((error) => { + .catch(error => { logger.error(error); res.status(500).json({ success: false, @@ -22,4 +22,4 @@ const getTorList = (req, res) => { }); }; -module.exports = getTorList; +export default getTorList; diff --git a/server/controllers/api/user/password/index.js b/server/controllers/api/user/password/index.js index ddfb3f44..c5c47499 100644 --- a/server/controllers/api/user/password/index.js +++ b/server/controllers/api/user/password/index.js @@ -1,7 +1,7 @@ -const { handleErrorResponse } = require('../../../utils/errorHandlers.js'); -const logger = require('winston'); -const db = require('../../../../models'); -const { masterPassword } = require('@private/authConfig.json'); +import { handleErrorResponse } from '../../../utils/errorHandlers.js'; +import logger from 'winston'; +import db from 'server/models'; +import { masterPassword } from '@private/authConfig.json'; /* route to update a password @@ -22,7 +22,8 @@ const updateUserPassword = ({ ip, originalUrl, body }, res) => { if (!userName || !oldPassword || !newPassword) { return res.status(400).json({ success: false, - message: 'body should include userName (channel name without the @), oldPassword, & newPassword', + message: + 'body should include userName (channel name without the @), oldPassword, & newPassword', }); } @@ -60,9 +61,9 @@ const updateUserPassword = ({ ip, originalUrl, body }, res) => { newPassword, }); }) - .catch((error) => { + .catch(error => { handleErrorResponse(originalUrl, ip, error, res); }); }; -module.exports = updateUserPassword; +export default updateUserPassword; diff --git a/server/controllers/assets/serveAsset/index.js b/server/controllers/assets/serveAsset/index.js index c953ca51..e3c0d72b 100644 --- a/server/controllers/assets/serveAsset/index.js +++ b/server/controllers/assets/serveAsset/index.js @@ -1,5 +1,5 @@ -const { sendGAServeEvent } = require('../../../utils/googleAnalytics'); -const getClaimIdAndServeAsset = require('../utils/getClaimIdAndServeAsset.js'); +import { sendGAServeEvent } from '@serverutils/googleAnalytics'; +import getClaimIdAndServeAsset from '../utils/getClaimIdAndServeAsset.js'; /* @@ -14,4 +14,4 @@ const serveAsset = ({ headers, ip, originalUrl, params: { claimName, claimId } } getClaimIdAndServeAsset(null, null, claimName, claimId, originalUrl, ip, res, headers); }; -module.exports = serveAsset; +export default serveAsset; diff --git a/server/controllers/assets/serveByClaim/index.js b/server/controllers/assets/serveByClaim/index.js index 41701d2d..4d474634 100644 --- a/server/controllers/assets/serveByClaim/index.js +++ b/server/controllers/assets/serveByClaim/index.js @@ -1,14 +1,14 @@ -const logger = require('winston'); +import logger from 'winston'; -const { sendGAServeEvent } = require('../../../utils/googleAnalytics'); -const handleShowRender = require('../../../render/handleShowRender').default; +import { sendGAServeEvent } from '@serverutils/googleAnalytics'; +import handleShowRender from 'server/render/handleShowRender'; -const lbryUri = require('../../../../utils/lbryUri.js'); +import lbryUri from '@globalutils/lbryUri.js'; -const determineRequestType = require('../utils/determineRequestType.js'); -const getClaimIdAndServeAsset = require('../utils/getClaimIdAndServeAsset.js'); +import determineRequestType from '../utils/determineRequestType.js'; +import getClaimIdAndServeAsset from '../utils/getClaimIdAndServeAsset.js'; -const { SHOW } = require('../constants/request_types.js'); +import { SHOW } from '../constants/request_types.js'; /* @@ -41,8 +41,8 @@ const serveByClaim = (req, res) => { sendGAServeEvent(headers, ip, originalUrl); } catch (error) { - return res.status(400).json({success: false, message: error.message}); + return res.status(400).json({ success: false, message: error.message }); } }; -module.exports = serveByClaim; +export default serveByClaim; diff --git a/server/controllers/assets/serveByIdentifierAndClaim/index.js b/server/controllers/assets/serveByIdentifierAndClaim/index.js index b1cffe8e..27942c0d 100644 --- a/server/controllers/assets/serveByIdentifierAndClaim/index.js +++ b/server/controllers/assets/serveByIdentifierAndClaim/index.js @@ -1,15 +1,15 @@ -const logger = require('winston'); +import logger from 'winston'; -const { sendGAServeEvent } = require('../../../utils/googleAnalytics'); -const handleShowRender = require('../../../render/handleShowRender').default; +import { sendGAServeEvent } from 'server/utils/googleAnalytics'; +import handleShowRender from 'server/render/handleShowRender'; -const lbryUri = require('../../../../utils/lbryUri.js'); +import lbryUri from '@globalutils/lbryUri.js'; -const determineRequestType = require('../utils/determineRequestType.js'); -const getClaimIdAndServeAsset = require('../utils/getClaimIdAndServeAsset.js'); -const flipClaimNameAndId = require('../utils/flipClaimNameAndId.js'); +import determineRequestType from '../utils/determineRequestType.js'; +import getClaimIdAndServeAsset from '../utils/getClaimIdAndServeAsset.js'; +import flipClaimNameAndId from '../utils/flipClaimNameAndId.js'; -const { SHOW } = require('../constants/request_types.js'); +import { SHOW } from '../constants/request_types.js'; /* @@ -30,7 +30,9 @@ const serverByIdentifierAndClaim = (req, res) => { } ({ claimName } = lbryUri.parseClaim(params.claim)); - ({ isChannel, channelName, channelClaimId, claimId } = lbryUri.parseIdentifier(params.identifier)); + ({ isChannel, channelName, channelClaimId, claimId } = lbryUri.parseIdentifier( + params.identifier + )); if (!isChannel) { [claimId, claimName] = flipClaimNameAndId(claimId, claimName); @@ -47,12 +49,21 @@ const serverByIdentifierAndClaim = (req, res) => { claimId, }); - getClaimIdAndServeAsset(channelName, channelClaimId, claimName, claimId, originalUrl, ip, res, headers); + getClaimIdAndServeAsset( + channelName, + channelClaimId, + claimName, + claimId, + originalUrl, + ip, + res, + headers + ); sendGAServeEvent(headers, ip, originalUrl); } catch (error) { - return res.status(400).json({success: false, message: error.message}); + return res.status(400).json({ success: false, message: error.message }); } }; -module.exports = serverByIdentifierAndClaim; +export default serverByIdentifierAndClaim; diff --git a/server/controllers/assets/utils/determineRequestType.js b/server/controllers/assets/utils/determineRequestType.js index 02e08fbc..236c7cb0 100644 --- a/server/controllers/assets/utils/determineRequestType.js +++ b/server/controllers/assets/utils/determineRequestType.js @@ -1,6 +1,6 @@ -const { SERVE, SHOW } = require('../constants/request_types.js'); +import { SERVE, SHOW } from '../constants/request_types.js'; -function clientWantsAsset ({accept, range}) { +function clientWantsAsset({ accept, range }) { const imageIsWanted = accept && accept.match(/image\/.*/) && !accept.match(/text\/html/); const videoIsWanted = accept && accept.match(/video\/.*/) && !accept.match(/text\/html/); return imageIsWanted || videoIsWanted; @@ -13,4 +13,4 @@ const determineRequestType = (hasFileExtension, headers) => { return SHOW; }; -module.exports = determineRequestType; +export default determineRequestType; diff --git a/server/controllers/assets/utils/flipClaimNameAndId.js b/server/controllers/assets/utils/flipClaimNameAndId.js index c41ebd02..a25a05f4 100644 --- a/server/controllers/assets/utils/flipClaimNameAndId.js +++ b/server/controllers/assets/utils/flipClaimNameAndId.js @@ -1,14 +1,14 @@ -function isValidClaimId (claimId) { - return ((claimId.length === 40) && !/[^A-Za-z0-9]/g.test(claimId)); -}; +function isValidClaimId(claimId) { + return claimId.length === 40 && !/[^A-Za-z0-9]/g.test(claimId); +} -function isValidShortId (claimId) { - return claimId.length === 1; // it should really evaluate the short url itself -}; +function isValidShortId(claimId) { + return claimId.length === 1; // it should really evaluate the short url itself +} -function isValidShortIdOrClaimId (input) { - return (isValidClaimId(input) || isValidShortId(input)); -}; +function isValidShortIdOrClaimId(input) { + return isValidClaimId(input) || isValidShortId(input); +} const flipClaimNameAndId = (identifier, name) => { // this is a patch for backwards compatability with '/name/claimId' url format @@ -20,4 +20,4 @@ const flipClaimNameAndId = (identifier, name) => { return [identifier, name]; }; -module.exports = flipClaimNameAndId; +export default flipClaimNameAndId; diff --git a/server/controllers/assets/utils/getClaimIdAndServeAsset.js b/server/controllers/assets/utils/getClaimIdAndServeAsset.js index cc1f4f89..40fa8865 100644 --- a/server/controllers/assets/utils/getClaimIdAndServeAsset.js +++ b/server/controllers/assets/utils/getClaimIdAndServeAsset.js @@ -1,16 +1,20 @@ -const logger = require('winston'); +import logger from 'winston'; -const db = require('server/models'); -const chainquery = require('chainquery').default; -const isApprovedChannel = require('@globalutils/isApprovedChannel'); -const { getFileListFileByOutpoint, getClaim } = require('server/lbrynet'); -const getClaimId = require('../../utils/getClaimId.js'); -const { handleErrorResponse } = require('../../utils/errorHandlers.js'); -const awaitFileSize = require('server/utils/awaitFileSize'); -const serveFile = require('./serveFile.js'); -const parseQueryString = require('server/utils/parseQuerystring'); -const publishCache = require('server/utils/publishCache'); -const isBot = require('isbot'); +import db from 'server/models'; +import chainquery from 'chainquery'; +import { getFileListFileByOutpoint, getClaim } from 'server/lbrynet'; +import getClaimId from '../../utils/getClaimId.js'; +import { handleErrorResponse } from '../../utils/errorHandlers.js'; +import awaitFileSize from 'server/utils/awaitFileSize'; +import serveFile from './serveFile.js'; +import parseQueryString from 'server/utils/parseQuerystring'; +import publishCache from 'server/utils/publishCache'; +import isBot from 'isbot'; +import isApprovedChannel from '@globalutils/isApprovedChannel'; + +import { publishing } from '@config/siteConfig'; + +const { serveOnlyApproved, approvedChannels } = publishing; const NO_CHANNEL = 'NO_CHANNEL'; const NO_CLAIM = 'NO_CLAIM'; @@ -22,10 +26,6 @@ const RETRY_MS = 250; const TIMEOUT_MS = 15000; const MIN_BYTES = 15000000; -const { - publishing: { serveOnlyApproved, approvedChannels }, -} = require('@config/siteConfig'); - const getClaimIdAndServeAsset = async ( channelName, channelClaimId, @@ -125,4 +125,4 @@ const getClaimIdAndServeAsset = async ( } }; -module.exports = getClaimIdAndServeAsset; +export default getClaimIdAndServeAsset; diff --git a/server/controllers/assets/utils/getLocalFileRecord.js b/server/controllers/assets/utils/getLocalFileRecord.js index 53f8a469..656f0cb7 100644 --- a/server/controllers/assets/utils/getLocalFileRecord.js +++ b/server/controllers/assets/utils/getLocalFileRecord.js @@ -1,15 +1,14 @@ -const db = require('../../../models'); +import db from 'server/models'; const NO_FILE = 'NO_FILE'; const getLocalFileRecord = (claimId, name) => { - return db.File.findOne({where: {claimId, name}}) - .then(file => { - if (!file) { - return NO_FILE; - } - return file.dataValues; - }); + return db.File.findOne({ where: { claimId, name } }).then(file => { + if (!file) { + return NO_FILE; + } + return file.dataValues; + }); }; -module.exports = getLocalFileRecord; +export default getLocalFileRecord; diff --git a/server/controllers/assets/utils/logRequestData.js b/server/controllers/assets/utils/logRequestData.js index dde074c2..4e76883f 100644 --- a/server/controllers/assets/utils/logRequestData.js +++ b/server/controllers/assets/utils/logRequestData.js @@ -1,4 +1,4 @@ -const logger = require('winston'); +import logger from 'winston'; const logRequestData = (responseType, claimName, channelName, claimId) => { logger.debug('responseType ===', responseType); @@ -7,4 +7,4 @@ const logRequestData = (responseType, claimName, channelName, claimId) => { logger.debug('claim id ===', claimId); }; -module.exports = logRequestData; +export default logRequestData; diff --git a/server/controllers/assets/utils/serveFile.js b/server/controllers/assets/utils/serveFile.js index 558fe611..abb8678a 100644 --- a/server/controllers/assets/utils/serveFile.js +++ b/server/controllers/assets/utils/serveFile.js @@ -1,10 +1,10 @@ -const logger = require('winston'); -const transformImage = require('./transformImage'); -const parseQueryString = require('server/utils/parseQuerystring'); -const isValidQueryObject = require('server/utils/isValidQueryObj'); -const { - serving: { dynamicFileSizing }, -} = require('@config/siteConfig'); +import logger from 'winston'; +import transformImage from './transformImage'; +import parseQueryString from 'server/utils/parseQuerystring'; +import isValidQueryObject from 'server/utils/isValidQueryObj'; +import { serving } from '@config/siteConfig'; +const { dynamicFileSizing } = serving; + const { enabled: dynamicEnabled } = dynamicFileSizing; const serveFile = async ( @@ -57,4 +57,4 @@ const serveFile = async ( } }; -module.exports = serveFile; +export default serveFile; diff --git a/server/controllers/assets/utils/transformImage.js b/server/controllers/assets/utils/transformImage.js index 2d8408b4..e3e76b1a 100644 --- a/server/controllers/assets/utils/transformImage.js +++ b/server/controllers/assets/utils/transformImage.js @@ -1,9 +1,9 @@ -const gm = require('gm'); -const logger = require('winston'); +import gm from 'gm'; +import logger from 'winston'; +import { getImageHeightAndWidth } from '@serverutils/imageProcessing'; const imageMagick = gm.subClass({ imageMagick: true }); -const { getImageHeightAndWidth } = require('../../../utils/imageProcessing'); -module.exports = function transformImage(path, queryObj) { +export default function transformImage(path, queryObj) { return new Promise((resolve, reject) => { let { h: cHeight = null } = queryObj; let { w: cWidth = null } = queryObj; @@ -39,7 +39,7 @@ module.exports = function transformImage(path, queryObj) { reject(e); } }); -}; +} function _cropCenter(path, cropWidth, cropHeight, originalWidth, originalHeight) { let oAspect = originalWidth / originalHeight; diff --git a/server/controllers/auth/login/index.js b/server/controllers/auth/login/index.js index e88de217..ee99e05a 100644 --- a/server/controllers/auth/login/index.js +++ b/server/controllers/auth/login/index.js @@ -1,4 +1,4 @@ -const speechPassport = require('../../../speechPassport/index'); +import speechPassport from 'server/speechPassport/index'; const login = (req, res, next) => { speechPassport.authenticate('local-login', (err, user, info) => { @@ -11,13 +11,13 @@ const login = (req, res, next) => { message: info.message, }); } - req.logIn(user, (err) => { + req.logIn(user, err => { if (err) { return next(err); } return res.status(200).json({ - success : true, - channelName : req.user.channelName, + success: true, + channelName: req.user.channelName, channelClaimId: req.user.channelClaimId, shortChannelId: req.user.shortChannelId, }); @@ -25,4 +25,4 @@ const login = (req, res, next) => { })(req, res, next); }; -module.exports = login; +export default login; diff --git a/server/controllers/auth/logout/index.js b/server/controllers/auth/logout/index.js index a2a7a490..df963f1e 100644 --- a/server/controllers/auth/logout/index.js +++ b/server/controllers/auth/logout/index.js @@ -7,4 +7,4 @@ const logout = (req, res) => { res.status(200).json(responseObject); }; -module.exports = logout; +export default logout; diff --git a/server/controllers/auth/signup/index.js b/server/controllers/auth/signup/index.js index 8db397cb..7fd35a4d 100644 --- a/server/controllers/auth/signup/index.js +++ b/server/controllers/auth/signup/index.js @@ -1,10 +1,10 @@ const signup = (req, res) => { res.status(200).json({ - success : true, - channelName : req.user.channelName, + success: true, + channelName: req.user.channelName, channelClaimId: req.user.channelClaimId, shortChannelId: req.user.shortChannelId, }); }; -module.exports = signup; +export default signup; diff --git a/server/controllers/auth/user/index.js b/server/controllers/auth/user/index.js index 8e3b3979..e614bd6c 100644 --- a/server/controllers/auth/user/index.js +++ b/server/controllers/auth/user/index.js @@ -1,9 +1,9 @@ const user = (req, res) => { const responseObject = { success: true, - data : req.user, + data: req.user, }; res.status(200).json(responseObject); }; -module.exports = user; +export default user; diff --git a/server/controllers/pages/sendVideoEmbedPage.js b/server/controllers/pages/sendVideoEmbedPage.js index 2a07ba0c..71d51461 100644 --- a/server/controllers/pages/sendVideoEmbedPage.js +++ b/server/controllers/pages/sendVideoEmbedPage.js @@ -1,42 +1,40 @@ -const { - assetDefaults: { thumbnail }, - details: { host }, -} = require('@config/siteConfig'); - +import { assetDefaults, details } from '@config/siteConfig'; +const { thumbnail } = assetDefaults; +const { host } = details; const padSizes = { - small : 'padSmall', + small: 'padSmall', medium: 'padMedium', - large : 'padLarge', + large: 'padLarge', }; const argumentProcessors = { - 'bottom': async (config) => { + bottom: async config => { config.classNames.push('bottom'); }, - 'right': async (config) => { + right: async config => { config.classNames.push('right'); }, - 'pad': async (config, val) => { + pad: async (config, val) => { config.classNames.push(padSizes[val]); }, - 'logoClaim': async (config, val) => { + logoClaim: async (config, val) => { config.logoUrl = `${host}/${val}`; }, - 'link': async (config, val) => { + link: async (config, val) => { config.logoLink = val; }, }; -const parseLogoConfigParam = async (rawConfig) => { +const parseLogoConfigParam = async rawConfig => { if (rawConfig) { let parsedConfig = { classNames: ['logoLink'], - logoUrl : thumbnail, + logoUrl: thumbnail, }; let splitConfig; try { splitConfig = rawConfig.split(','); - } catch (e) { } + } catch (e) {} if (!splitConfig) { return false; @@ -64,11 +62,7 @@ const parseLogoConfigParam = async (rawConfig) => { }; 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 (name[0] === '@' && name.includes(':')) { @@ -86,4 +80,4 @@ const sendVideoEmbedPage = async ({ params }, res) => { res.status(200).render('embed', { host, claimId, name, logoConfig }); }; -module.exports = sendVideoEmbedPage; +export default sendVideoEmbedPage; diff --git a/server/controllers/utils/errorHandlers.js b/server/controllers/utils/errorHandlers.js index c2d6cac5..ac324878 100644 --- a/server/controllers/utils/errorHandlers.js +++ b/server/controllers/utils/errorHandlers.js @@ -1,45 +1,44 @@ -const logger = require('winston'); +import logger from 'winston'; -module.exports = { - handleErrorResponse: function (originalUrl, ip, error, res) { - logger.error(`Error on ${originalUrl}`, module.exports.useObjectPropertiesIfNoKeys(error)); - const [status, message] = module.exports.returnErrorMessageAndStatus(error); - res - .status(status) - .json(module.exports.createErrorResponsePayload(status, message)); - }, - returnErrorMessageAndStatus: function (error) { - let status, message; - // check for daemon being turned off - if (error.code === 'ECONNREFUSED') { - status = 503; - message = 'Connection refused. The daemon may not be running.'; - // fallback for everything else +export function handleErrorResponse(originalUrl, ip, error, res) { + logger.error(`Error on ${originalUrl}`, useObjectPropertiesIfNoKeys(error)); + const [status, message] = returnErrorMessageAndStatus(error); + res.status(status).json(createErrorResponsePayload(status, message)); +} + +export function returnErrorMessageAndStatus(error) { + let status, message; + // check for daemon being turned off + if (error.code === 'ECONNREFUSED') { + status = 503; + message = 'Connection refused. The daemon may not be running.'; + // fallback for everything else + } else { + status = 400; + if (error.message) { + message = error.message; } else { - status = 400; - if (error.message) { - message = error.message; - } else { - message = error; - } + message = error; } - return [status, message]; - }, - useObjectPropertiesIfNoKeys: function (err) { - if (Object.keys(err).length === 0) { - let newErrorObject = {}; - Object.getOwnPropertyNames(err).forEach((key) => { - newErrorObject[key] = err[key]; - }); - return newErrorObject; - } - return err; - }, - createErrorResponsePayload (status, message) { - return { - status, - success: false, - message, - }; - }, -}; + } + return [status, message]; +} + +export function useObjectPropertiesIfNoKeys(err) { + if (Object.keys(err).length === 0) { + let newErrorObject = {}; + Object.getOwnPropertyNames(err).forEach(key => { + newErrorObject[key] = err[key]; + }); + return newErrorObject; + } + return err; +} + +function createErrorResponsePayload(status, message) { + return { + status, + success: false, + message, + }; +} diff --git a/server/controllers/utils/getClaimId.js b/server/controllers/utils/getClaimId.js index eb007bd9..87424f85 100644 --- a/server/controllers/utils/getClaimId.js +++ b/server/controllers/utils/getClaimId.js @@ -1,8 +1,8 @@ -const logger = require('winston'); -const db = require('../../models'); -const chainquery = require('chainquery').default; -const publishCache = require('server/utils/publishCache'); -const createCanonicalLink = require('@globalutils/createCanonicalLink'); +import logger from 'winston'; +import db from 'server/models'; +import chainquery from 'chainquery'; +import publishCache from 'server/utils/publishCache'; +import createCanonicalLink from '@globalutils/createCanonicalLink'; const getClaimIdByChannel = async (channelName, channelClaimId, claimName) => { logger.debug(`getClaimIdByChannel(${channelName}, ${channelClaimId}, ${claimName})`); @@ -36,4 +36,4 @@ const getClaimId = async (channelName, channelClaimId, name, claimId) => { } }; -module.exports = getClaimId; +export default getClaimId; diff --git a/server/controllers/utils/redirect.js b/server/controllers/utils/redirect.js index 8f2df4dd..8a25fa06 100644 --- a/server/controllers/utils/redirect.js +++ b/server/controllers/utils/redirect.js @@ -1,7 +1,7 @@ -const redirect = (route) => { +const redirect = route => { return (req, res) => { res.status(301).redirect(route); }; }; -module.exports = redirect; +export default redirect; diff --git a/server/index.js b/server/index.js index e3806779..fda573d9 100644 --- a/server/index.js +++ b/server/index.js @@ -1,36 +1,33 @@ // load modules -const express = require('express'); -const bodyParser = require('body-parser'); -const expressHandlebars = require('express-handlebars'); -const helmet = require('helmet'); -const cookieSession = require('cookie-session'); -const http = require('http'); -const logger = require('winston'); -const Path = require('path'); -const httpContext = require('express-http-context'); +import express from 'express'; +import bodyParser from 'body-parser'; +import expressHandlebars from 'express-handlebars'; +import helmet from 'helmet'; +import cookieSession from 'cookie-session'; +import http from 'http'; +import logger from 'winston'; +import Path from 'path'; +import httpContext from 'express-http-context'; // load local modules -const db = require('./models'); -const requestLogger = require('./middleware/requestLogger'); -const createDatabaseIfNotExists = require('./models/utils/createDatabaseIfNotExists'); -const { getAccountBalance } = require('./lbrynet/index'); -const configureLogging = require('./utils/configureLogging'); -const configureSlack = require('./utils/configureSlack'); -const { setupBlockList } = require('./utils/blockList'); -const speechPassport = require('./speechPassport'); -const processTrending = require('./utils/processTrending'); +import db from './models'; +import requestLogger from './middleware/requestLogger'; +import createDatabaseIfNotExists from './models/utils/createDatabaseIfNotExists'; +import { getAccountBalance } from './lbrynet/index'; +import configureLogging from './utils/configureLogging'; +import configureSlack from './utils/configureSlack'; +import { setupBlockList } from './utils/blockList'; +import speechPassport from './speechPassport'; +import processTrending from './utils/processTrending'; -const { +import { logMetricsMiddleware, setRouteDataInContextMiddleware, -} = require('./middleware/logMetricsMiddleware'); - -const { - details: { port: PORT, blockListEndpoint }, - startup: { performChecks, performUpdates }, -} = require('@config/siteConfig'); - -const { sessionKey } = require('@private/authConfig.json'); +} from './middleware/logMetricsMiddleware'; +import { sessionKey } from '@private/authConfig.json'; +import { details, startup } from '@config/siteConfig'; +const { port: PORT, blockListEndpoint } = details; +const { performChecks, performUpdates } = startup; // configure.js doesn't handle new keys in config.json files yet. Make sure it doens't break. let finalBlockListEndpoint; @@ -246,4 +243,4 @@ function Server() { }; } -module.exports = Server; +export default Server; diff --git a/server/lbrynet/index.js b/server/lbrynet/index.js index caecb74a..d7c5a5a4 100644 --- a/server/lbrynet/index.js +++ b/server/lbrynet/index.js @@ -1,212 +1,209 @@ -const axios = require('axios'); -const logger = require('winston'); -const { apiHost, apiPort, getTimeout } = require('@config/lbryConfig'); -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'); +import axios from 'axios'; +import logger from 'winston'; +import db from 'server/models'; +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'; -module.exports = { - publishClaim(publishParams) { - logger.debug(`lbryApi >> Publishing claim to "${publishParams.name}"`); - const gaStartTime = Date.now(); - return new Promise((resolve, reject) => { - axios - .post(lbrynetUri, { - method: 'publish', - params: publishParams, - }) - .then(response => { - sendGATimingEvent( - 'lbrynet', - 'publish', - chooseGaLbrynetPublishLabel(publishParams), - gaStartTime, - Date.now() - ); - handleLbrynetResponse(response, resolve, reject); - }) - .catch(error => { - reject(error); - }); - }); - }, - 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 }, +const lbrynetUri = 'http://' + apiHost + ':' + apiPort; + +export function publishClaim(publishParams) { + logger.debug(`lbryApi >> Publishing claim to "${publishParams.name}"`); + const gaStartTime = Date.now(); + return new Promise((resolve, reject) => { + axios + .post(lbrynetUri, { + method: 'publish', + params: publishParams, + }) + .then(response => { + sendGATimingEvent( + 'lbrynet', + 'publish', + chooseGaLbrynetPublishLabel(publishParams), + gaStartTime, + Date.now() + ); + handleLbrynetResponse(response, resolve, reject); + }) + .catch(error => { + reject(error); }); - sendGATimingEvent('lbrynet', 'abandonClaim', 'ABANDON_CLAIM', gaStartTime, Date.now()); - return abandon.data; - } catch (error) { - logger.error(error); - return error; - } - }, - 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 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 }, }); - }, - 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); - }); - }); - }, - 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() + 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.' ); - 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); - }); - }); - }, -}; + } + }) + .catch(error => { + logger.error('Lbrynet Error:', error); + resolve('/home/lbry/Downloads/'); + }); + }); +} +export function 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); + }); + }); +} +export function 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); + }); + }); +} diff --git a/server/lbrynet/utils/handleLbrynetResponse.js b/server/lbrynet/utils/handleLbrynetResponse.js index a5cc72a4..138f5031 100644 --- a/server/lbrynet/utils/handleLbrynetResponse.js +++ b/server/lbrynet/utils/handleLbrynetResponse.js @@ -1,6 +1,6 @@ -const logger = require('winston'); +import logger from 'winston'; -const handleLbrynetResponse = ({ data }, resolve, reject) => { +export const handleLbrynetResponse = ({ data }, resolve, reject) => { logger.debug('lbry api data:', data); if (data) { // check for an error @@ -15,5 +15,3 @@ const handleLbrynetResponse = ({ data }, resolve, reject) => { // fallback in case it just timed out reject(JSON.stringify(data)); }; - -module.exports = handleLbrynetResponse; diff --git a/server/middleware/autoblockPublishMiddleware.js b/server/middleware/autoblockPublishMiddleware.js index 426323a1..8bad323c 100644 --- a/server/middleware/autoblockPublishMiddleware.js +++ b/server/middleware/autoblockPublishMiddleware.js @@ -1,9 +1,8 @@ -const fs = require('fs'); +import fs from 'fs'; -const logger = require('winston'); -const { - publishing: { publishingChannelWhitelist }, -} = require('@config/siteConfig'); +import logger from 'winston'; +import { publishing } from '@config/siteConfig'; +const { publishingChannelWhitelist } = publishing; const ipBanFile = './site/config/ipBan.txt'; const forbiddenMessage = '

Forbidden

If you are seeing this by mistake, please contact us using https://chat.lbry.com/'; @@ -23,7 +22,7 @@ if (fs.existsSync(ipBanFile)) { }); } -const autoblockPublishMiddleware = (req, res, next) => { +export const autoblockPublishMiddleware = (req, res, next) => { let ip = (req.headers['x-forwarded-for'] || req.connection.remoteAddress).split(/,\s?/)[0]; if (blockedAddresses.indexOf(ip) !== -1) { @@ -56,7 +55,7 @@ const autoblockPublishMiddleware = (req, res, next) => { } }; -const autoblockPublishBodyMiddleware = (req, res, next) => { +export const autoblockPublishBodyMiddleware = (req, res, next) => { if (req.body && publishingChannelWhitelist) { let ip = (req.headers['x-forwarded-for'] || req.connection.remoteAddress).split(/,\s?/)[0]; const { channelName } = req.body; @@ -67,8 +66,3 @@ const autoblockPublishBodyMiddleware = (req, res, next) => { } next(); }; - -module.exports = { - autoblockPublishMiddleware, - autoblockPublishBodyMiddleware, -}; diff --git a/server/middleware/logMetricsMiddleware.js b/server/middleware/logMetricsMiddleware.js index e4ddaceb..f9f0a748 100644 --- a/server/middleware/logMetricsMiddleware.js +++ b/server/middleware/logMetricsMiddleware.js @@ -1,8 +1,8 @@ -const logger = require('winston'); -const db = require('../models'); -const httpContext = require('express-http-context'); +import logger from 'winston'; +import db from '../models'; +import httpContext from 'express-http-context'; -function logMetricsMiddleware (req, res, next) { +export function logMetricsMiddleware(req, res, next) { res.on('finish', () => { const userAgent = req.get('user-agent'); const routePath = httpContext.get('routePath'); @@ -26,15 +26,15 @@ function logMetricsMiddleware (req, res, next) { } db.Metrics.create({ - time : Date.now(), + time: Date.now(), isInternal: /node-fetch/.test(userAgent), - isChannel : res.isChannel, - claimId : res.claimId, - routePath : httpContext.get('routePath'), - params : JSON.stringify(req.params), - ip : req.headers['x-forwarded-for'] || req.connection.remoteAddress, - request : req.url, - routeData : JSON.stringify(httpContext.get('routeData')), + isChannel: res.isChannel, + claimId: res.claimId, + routePath: httpContext.get('routePath'), + params: JSON.stringify(req.params), + ip: req.headers['x-forwarded-for'] || req.connection.remoteAddress, + request: req.url, + routeData: JSON.stringify(httpContext.get('routeData')), referrer, userAgent, }); @@ -43,15 +43,10 @@ function logMetricsMiddleware (req, res, next) { next(); } -function setRouteDataInContextMiddleware (routePath, routeData) { - return function (req, res, next) { +export function setRouteDataInContextMiddleware(routePath, routeData) { + return function(req, res, next) { httpContext.set('routePath', routePath); httpContext.set('routeData', routeData); next(); }; } - -module.exports = { - logMetricsMiddleware, - setRouteDataInContextMiddleware, -}; diff --git a/server/middleware/multipartMiddleware.js b/server/middleware/multipartMiddleware.js index c193e147..d92fe081 100644 --- a/server/middleware/multipartMiddleware.js +++ b/server/middleware/multipartMiddleware.js @@ -1,5 +1,6 @@ -const multipart = require('connect-multiparty'); -const { publishing: { uploadDirectory } } = require('@config/siteConfig'); -const multipartMiddleware = multipart({uploadDir: uploadDirectory}); +import multipart from 'connect-multiparty'; +import { publishing } from '@config/siteConfig'; +const { uploadDirectory } = publishing; +const multipartMiddleware = multipart({ uploadDir: uploadDirectory }); -module.exports = multipartMiddleware; +export default multipartMiddleware; diff --git a/server/middleware/requestLogger.js b/server/middleware/requestLogger.js index 990b9c1f..a423534a 100644 --- a/server/middleware/requestLogger.js +++ b/server/middleware/requestLogger.js @@ -1,8 +1,8 @@ -const logger = require('winston'); +import logger from 'winston'; -const requestLogger = (req, res, next) => { // custom logging middleware to log all incoming http requests +const requestLogger = (req, res, next) => { + // custom logging middleware to log all incoming http requests logger.debug(`Request on ${req.originalUrl} from ${req.ip}`); next(); }; - -module.exports = requestLogger; +export default requestLogger; diff --git a/server/middleware/torCheckMiddleware.js b/server/middleware/torCheckMiddleware.js index 62c42af5..9c67e2d9 100644 --- a/server/middleware/torCheckMiddleware.js +++ b/server/middleware/torCheckMiddleware.js @@ -1,22 +1,22 @@ -const logger = require('winston'); -const db = require('../models'); +import logger from 'winston'; +import db from 'server/models'; const torCheck = (req, res, next) => { const { ip } = req; logger.debug(`tor check for: ${ip}`); - return db.Tor.findAll( - { - where: { - address: ip, - }, - raw: true, - }) + return db.Tor.findAll({ + where: { + address: ip, + }, + raw: true, + }) .then(result => { if (result.length >= 1) { logger.info('Tor request blocked:', ip); const failureResponse = { success: false, - 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.', + 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.', }; res.status(403).json(failureResponse); } else { @@ -27,5 +27,4 @@ const torCheck = (req, res, next) => { logger.error(error); }); }; - -module.exports = torCheck; +export default torCheck; diff --git a/server/models/blocked.js b/server/models/blocked.js index fff43d51..344ca4f9 100644 --- a/server/models/blocked.js +++ b/server/models/blocked.js @@ -1,12 +1,12 @@ -const logger = require('winston'); +import logger from 'winston'; const BLOCKED_CLAIM = 'BLOCKED_CLAIM'; -module.exports = (sequelize, { STRING }) => { +export default (sequelize, { STRING }) => { const Blocked = sequelize.define( 'Blocked', { outpoint: { - type : STRING, + type: STRING, allowNull: false, }, }, @@ -15,15 +15,16 @@ module.exports = (sequelize, { STRING }) => { } ); - Blocked.getBlockList = function () { + Blocked.getBlockList = function() { logger.debug('returning full block list'); return new Promise((resolve, reject) => { - this.findAll() - .then(list => { return resolve(list) }); + this.findAll().then(list => { + return resolve(list); + }); }); }; - Blocked.isNotBlocked = function (outpoint) { + Blocked.isNotBlocked = function(outpoint) { logger.debug(`checking to see if ${outpoint} is not blocked`); return new Promise((resolve, reject) => { this.findOne({ @@ -44,7 +45,7 @@ module.exports = (sequelize, { STRING }) => { }); }; - Blocked.refreshTable = function (blockEndpoint) { + Blocked.refreshTable = function(blockEndpoint) { let blockedList = []; return fetch(blockEndpoint) diff --git a/server/models/certificate.js b/server/models/certificate.js index 5dc5120a..253eb1cc 100644 --- a/server/models/certificate.js +++ b/server/models/certificate.js @@ -1,98 +1,98 @@ -const logger = require('winston'); -const returnShortId = require('./utils/returnShortId.js'); +import logger from 'winston'; +import returnShortId from './utils/returnShortId'; const NO_CHANNEL = 'NO_CHANNEL'; -function isLongChannelId (channelId) { - return (channelId && (channelId.length === 40)); +function isLongChannelId(channelId) { + return channelId && channelId.length === 40; } -function isShortChannelId (channelId) { - return (channelId && (channelId.length < 40)); +function isShortChannelId(channelId) { + return channelId && channelId.length < 40; } -module.exports = (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => { +export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => { const Certificate = sequelize.define( 'Certificate', { address: { - type : STRING, + type: STRING, default: null, }, amount: { - type : DECIMAL(19, 8), + type: DECIMAL(19, 8), default: null, }, claimId: { - type : STRING, + type: STRING, default: null, }, claimSequence: { - type : INTEGER, + type: INTEGER, default: null, }, decodedClaim: { - type : BOOLEAN, + type: BOOLEAN, default: null, }, depth: { - type : INTEGER, + type: INTEGER, default: null, }, effectiveAmount: { - type : DECIMAL(19, 8), + type: DECIMAL(19, 8), default: null, }, hasSignature: { - type : BOOLEAN, + type: BOOLEAN, default: null, }, height: { - type : INTEGER, + type: INTEGER, default: null, }, hex: { - type : TEXT('long'), + type: TEXT('long'), default: null, }, name: { - type : STRING, + type: STRING, default: null, }, nout: { - type : INTEGER, + type: INTEGER, default: null, }, txid: { - type : STRING, + type: STRING, default: null, }, validAtHeight: { - type : INTEGER, + type: INTEGER, default: null, }, outpoint: { - type : STRING, + type: STRING, default: null, }, valueVersion: { - type : STRING, + type: STRING, default: null, }, claimType: { - type : STRING, + type: STRING, default: null, }, certificateVersion: { - type : STRING, + type: STRING, default: null, }, keyType: { - type : STRING, + type: STRING, default: null, }, publicKey: { - type : TEXT('long'), + type: TEXT('long'), default: null, }, }, @@ -109,14 +109,13 @@ module.exports = (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => { }); }; - Certificate.getShortChannelIdFromLongChannelId = function (longChannelId, channelName) { + Certificate.getShortChannelIdFromLongChannelId = function(longChannelId, channelName) { logger.debug(`getShortChannelIdFromLongChannelId ${channelName}:${longChannelId}`); return new Promise((resolve, reject) => { - this - .findAll({ - where: {name: channelName}, - order: [['height', 'ASC']], - }) + this.findAll({ + where: { name: channelName }, + order: [['height', 'ASC']], + }) .then(result => { switch (result.length) { case 0: @@ -131,11 +130,11 @@ module.exports = (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => { }); }; - Certificate.validateLongChannelId = function (name, claimId) { + Certificate.validateLongChannelId = function(name, claimId) { logger.debug(`validateLongChannelId(${name}, ${claimId})`); return new Promise((resolve, reject) => { this.findOne({ - where: {name, claimId}, + where: { name, claimId }, }) .then(result => { if (!result) { @@ -150,19 +149,18 @@ module.exports = (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => { }); }; - Certificate.getLongChannelIdFromShortChannelId = function (channelName, channelClaimId) { + Certificate.getLongChannelIdFromShortChannelId = function(channelName, channelClaimId) { logger.debug(`getLongChannelIdFromShortChannelId(${channelName}, ${channelClaimId})`); return new Promise((resolve, reject) => { - this - .findAll({ - where: { - name : channelName, - claimId: { - [sequelize.Op.like]: `${channelClaimId}%`, - }, + this.findAll({ + where: { + name: channelName, + claimId: { + [sequelize.Op.like]: `${channelClaimId}%`, }, - order: [['height', 'ASC']], - }) + }, + order: [['height', 'ASC']], + }) .then(result => { switch (result.length) { case 0: @@ -178,14 +176,13 @@ module.exports = (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => { }); }; - Certificate.getLongChannelIdFromChannelName = function (channelName) { + Certificate.getLongChannelIdFromChannelName = function(channelName) { logger.debug(`getLongChannelIdFromChannelName(${channelName})`); return new Promise((resolve, reject) => { - this - .findAll({ - where: { name: channelName }, - order: [['effectiveAmount', 'DESC'], ['height', 'ASC']], - }) + this.findAll({ + where: { name: channelName }, + order: [['effectiveAmount', 'DESC'], ['height', 'ASC']], + }) .then(result => { switch (result.length) { case 0: @@ -201,7 +198,7 @@ module.exports = (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => { }); }; - Certificate.getLongChannelId = function (channelName, channelClaimId) { + Certificate.getLongChannelId = function(channelName, channelClaimId) { logger.debug(`getLongChannelId(${channelName}, ${channelClaimId})`); if (isLongChannelId(channelClaimId)) { return this.validateLongChannelId(channelName, channelClaimId); diff --git a/server/models/channel.js b/server/models/channel.js index 9421ee52..ab3927d0 100644 --- a/server/models/channel.js +++ b/server/models/channel.js @@ -1,13 +1,13 @@ -module.exports = (sequelize, { STRING }) => { +export default (sequelize, { STRING }) => { const Channel = sequelize.define( 'Channel', { channelName: { - type : STRING, + type: STRING, allowNull: false, }, channelClaimId: { - type : STRING, + type: STRING, allowNull: false, }, }, diff --git a/server/models/claim.js b/server/models/claim.js index acede7b3..675b0c1a 100644 --- a/server/models/claim.js +++ b/server/models/claim.js @@ -1,13 +1,10 @@ -const logger = require('winston'); -const returnShortId = require('./utils/returnShortId.js'); -const isApprovedChannel = require('../../utils/isApprovedChannel'); -const { - assetDefaults: { thumbnail: defaultThumbnail }, - details: { host }, -} = require('@config/siteConfig'); -const { - publishing: { serveOnlyApproved, approvedChannels }, -} = require('@config/siteConfig'); +import logger from 'winston'; +import returnShortId from './utils/returnShortId.js'; +import isApprovedChannel from '@globalutils/isApprovedChannel'; +import { assetDefaults, details, publishing } from '@config/siteConfig'; +const { thumbnail: defaultThumbnail } = assetDefaults; +const { host } = details; +const { serveOnlyApproved, approvedChannels } = publishing; const NO_CLAIM = 'NO_CLAIM'; @@ -53,7 +50,7 @@ function isShortClaimId(claimId) { return claimId && claimId.length < 40; } -module.exports = (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => { +export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => { const Claim = sequelize.define( 'Claim', { diff --git a/server/models/file.js b/server/models/file.js index 0566384d..d75df685 100644 --- a/server/models/file.js +++ b/server/models/file.js @@ -1,35 +1,35 @@ -module.exports = (sequelize, { STRING, BOOLEAN, INTEGER }) => { +export default (sequelize, { STRING, BOOLEAN, INTEGER }) => { const File = sequelize.define( 'File', { name: { - type : STRING, + type: STRING, allowNull: false, }, claimId: { - type : STRING, + type: STRING, allowNull: false, }, outpoint: { - type : STRING, + type: STRING, allowNull: false, }, fileHeight: { - type : INTEGER, + type: INTEGER, allowNull: false, - default : 0, + default: 0, }, fileWidth: { - type : INTEGER, + type: INTEGER, allowNull: false, - default : 0, + default: 0, }, fileName: { - type : STRING, + type: STRING, allowNull: false, }, filePath: { - type : STRING, + type: STRING, allowNull: false, }, fileType: { diff --git a/server/models/index.js b/server/models/index.js index 7f4ba767..53b0438e 100644 --- a/server/models/index.js +++ b/server/models/index.js @@ -1,22 +1,18 @@ -const Sequelize = require('sequelize'); -const logger = require('winston'); +import Sequelize from 'sequelize'; +import logger from 'winston'; -const Blocked = require('./blocked'); -const Certificate = require('./certificate'); -const Channel = require('./channel'); -const Claim = require('./claim'); -const File = require('./file'); -const Metrics = require('./metrics'); -const Tor = require('./tor'); -const Trending = require('./trending'); -const User = require('./user'); -const Views = require('./views'); +import Blocked from './blocked'; +import Certificate from './certificate'; +import Channel from './channel'; +import Claim from './claim'; +import File from './file'; +import Metrics from './metrics'; +import Tor from './tor'; +import Trending from './trending'; +import User from './user'; +import Views from './views'; -const { - database, - username, - password, -} = require('@config/mysqlConfig'); +import { database, username, password } from '@config/mysqlConfig'; if (!database || !username || !password) { logger.warn('missing database, user, or password from mysqlConfig'); @@ -24,16 +20,16 @@ if (!database || !username || !password) { // set sequelize options const sequelize = new Sequelize(database, username, password, { - host : 'localhost', - dialect : 'mysql', + host: 'localhost', + dialect: 'mysql', dialectOptions: { decimalNumbers: true, }, logging: false, - pool : { - max : 5, - min : 0, - idle : 10000, + pool: { + max: 5, + min: 0, + idle: 10000, acquire: 10000, }, operatorsAliases: false, @@ -77,23 +73,24 @@ db.sequelize = sequelize; db.Sequelize = Sequelize; // add an 'upsert' method to the db object db.upsert = (Model, values, condition, tableName) => { - return Model - .findOne({ - where: condition, - }) + return Model.findOne({ + where: condition, + }) .then(obj => { - if (obj) { // update + if (obj) { + // update logger.debug(`updating record in db.${tableName}`); return obj.update(values); - } else { // insert + } else { + // insert logger.debug(`creating record in db.${tableName}`); return Model.create(values); } }) - .catch(function (error) { + .catch(function(error) { logger.error(`${tableName}.upsert error`, error); throw error; }); }; -module.exports = db; +export default db; diff --git a/server/models/metrics.js b/server/models/metrics.js index 8dfd9435..4021f934 100644 --- a/server/models/metrics.js +++ b/server/models/metrics.js @@ -1,51 +1,51 @@ -module.exports = (sequelize, { BOOLEAN, DATE, STRING }) => { +export default (sequelize, { BOOLEAN, DATE, STRING }) => { const Metrics = sequelize.define( 'Metrics', { time: { - type : DATE(6), + type: DATE(6), defaultValue: sequelize.NOW, }, isInternal: { type: BOOLEAN, }, isChannel: { - type : BOOLEAN, + type: BOOLEAN, defaultValue: false, }, claimId: { - type : STRING, + type: STRING, defaultValue: null, }, ip: { - type : STRING, + type: STRING, defaultValue: null, }, request: { - type : STRING, + type: STRING, defaultValue: null, }, userAgent: { - type : STRING, + type: STRING, defaultValue: null, }, referrer: { - type : STRING, + type: STRING, defaultValue: null, }, routePath: { - type : STRING, + type: STRING, defaultValue: null, }, params: { - type : STRING, + type: STRING, defaultValue: null, }, }, { freezeTableName: true, - timestamps : false, // don't use default timestamps columns - indexes : [ + timestamps: false, // don't use default timestamps columns + indexes: [ { fields: ['isInternal', 'isChannel', 'time', 'claimId', 'routePath'], }, diff --git a/server/models/tor.js b/server/models/tor.js index a314e92d..13cab732 100644 --- a/server/models/tor.js +++ b/server/models/tor.js @@ -1,16 +1,17 @@ -const logger = require('winston'); -const { details: { ipAddress } } = require('@config/siteConfig'); +import logger from 'winston'; +import { details } from '@config/siteConfig'; +const { ipAddress } = details; -module.exports = (sequelize, { STRING }) => { +export default (sequelize, { STRING }) => { const Tor = sequelize.define( 'Tor', { address: { - type : STRING, + type: STRING, allowNull: false, }, fingerprint: { - type : STRING, + type: STRING, allowNull: true, }, }, @@ -19,7 +20,7 @@ module.exports = (sequelize, { STRING }) => { } ); - Tor.refreshTable = function () { + Tor.refreshTable = function() { let torList = []; return fetch(`https://check.torproject.org/api/bulk?ip=${ipAddress}&port=80`) .then(response => { @@ -30,7 +31,7 @@ module.exports = (sequelize, { STRING }) => { // prep the records for (let i = 0; i < jsonResponse.length; i++) { torList.push({ - address : jsonResponse[i].Address, + address: jsonResponse[i].Address, fingerprint: jsonResponse[i].Fingerprint, }); } @@ -47,7 +48,7 @@ module.exports = (sequelize, { STRING }) => { // return the new table return this.findAll({ attributes: ['address', 'fingerprint'], - raw : true, + raw: true, }); }) .catch(error => { diff --git a/server/models/trending.js b/server/models/trending.js index 5b9d206c..b2a3d663 100644 --- a/server/models/trending.js +++ b/server/models/trending.js @@ -1,47 +1,48 @@ -const chainquery = require('chainquery').default; +import chainquery from 'chainquery'; -module.exports = (sequelize, { BOOLEAN, DATE, FLOAT, INTEGER, STRING }) => { +export default (sequelize, { BOOLEAN, DATE, FLOAT, INTEGER, STRING }) => { const Trending = sequelize.define( 'Trending', { - time: { /* TODO: Historical analysis and log roll */ - type : DATE(6), + time: { + /* TODO: Historical analysis and log roll */ + type: DATE(6), defaultValue: sequelize.NOW, }, isChannel: { - type : BOOLEAN, + type: BOOLEAN, defaultValue: false, }, claimId: { - type : STRING, + type: STRING, defaultValue: null, }, publisherId: { - type : STRING, + type: STRING, defaultValue: null, }, intervalViews: { - type : INTEGER, + type: INTEGER, defaultValue: 0, }, weight: { - type : FLOAT, + type: FLOAT, defaultValue: 0, }, zScore: { - type : FLOAT, + type: FLOAT, defaultValue: 0, }, pValue: { - type : FLOAT, + type: FLOAT, defaultValue: 0, }, // TODO: Calculate t-statistics }, { freezeTableName: true, - timestamps : false, // don't use default timestamps columns - indexes : [ + timestamps: false, // don't use default timestamps columns + indexes: [ { fields: ['claimId'], }, @@ -52,16 +53,15 @@ module.exports = (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(); time.setHours(time.getHours() - hours); time.setMinutes(time.getMinutes() - minutes); - const sqlTime = time.toISOString().slice(0, 19).replace('T', ' '); + const sqlTime = time + .toISOString() + .slice(0, 19) + .replace('T', ' '); const selectString = 'DISTINCT(claimId), weight'; const whereString = `isChannel = false and time > '${sqlTime}'`; @@ -89,7 +89,7 @@ module.exports = (sequelize, { BOOLEAN, DATE, FLOAT, INTEGER, STRING }) => { }, }); - return claimData.map((claimData) => { + return claimData.map(claimData => { return Object.assign(trendingClaims[claimData.claim_id], claimData.dataValues); }); }; diff --git a/server/models/user.js b/server/models/user.js index 831566a8..bee1bd6c 100644 --- a/server/models/user.js +++ b/server/models/user.js @@ -1,17 +1,17 @@ 'use strict'; -const bcrypt = require('bcrypt'); -const logger = require('winston'); +import bcrypt from 'bcrypt'; +import logger from 'winston'; -module.exports = (sequelize, { STRING }) => { +export default (sequelize, { STRING }) => { const User = sequelize.define( 'User', { userName: { - type : STRING, + type: STRING, allowNull: false, }, password: { - type : STRING, + type: STRING, allowNull: false, }, }, @@ -24,11 +24,11 @@ module.exports = (sequelize, { STRING }) => { User.hasOne(db.Channel); }; - User.prototype.comparePassword = function (password) { + User.prototype.comparePassword = function(password) { return bcrypt.compare(password, this.password); }; - User.prototype.changePassword = function (newPassword) { + User.prototype.changePassword = function(newPassword) { return new Promise((resolve, reject) => { // generate a salt string to use for hashing bcrypt.genSalt((saltError, salt) => { @@ -46,8 +46,7 @@ module.exports = (sequelize, { STRING }) => { return; } // replace the current password with the new hash - this - .update({password: hash}) + this.update({ password: hash }) .then(() => { resolve(); }) diff --git a/server/models/utils/createClaimRecordData.js b/server/models/utils/createClaimRecordData.js index 547b6158..ebceb8c2 100644 --- a/server/models/utils/createClaimRecordData.js +++ b/server/models/utils/createClaimRecordData.js @@ -1,44 +1,37 @@ -const db = require('../index.js'); +import db from 'server/models'; -const createClaimRecordDataAfterPublish = (certificateId, channelName, fileName, fileType, publishParams, publishResults) => { +export const createClaimRecordDataAfterPublish = ( + certificateId, + channelName, + fileName, + fileType, + publishParams, + publishResults +) => { const { name, - metadata: { - title, - description, - thumbnail, - nsfw, - }, + metadata: { title, description, thumbnail, nsfw }, claim_address: address, bid: amount, } = publishParams; - const { - claim_id: claimId, - txid, - nout, - } = publishResults; + const { claim_id: claimId, txid, nout } = publishResults; - return db.Claim.getCurrentHeight() - .then(height => { - return { - name, - claimId, - title, - description, - address, - thumbnail, - outpoint : `${txid}:${nout}`, - height, - contentType: fileType, - nsfw, - amount, - certificateId, - channelName, - }; - }); -}; - -module.exports = { - createClaimRecordDataAfterPublish, + return db.Claim.getCurrentHeight().then(height => { + return { + name, + claimId, + title, + description, + address, + thumbnail, + outpoint: `${txid}:${nout}`, + height, + contentType: fileType, + nsfw, + amount, + certificateId, + channelName, + }; + }); }; diff --git a/server/models/utils/createDatabaseIfNotExists.js b/server/models/utils/createDatabaseIfNotExists.js index 7349b492..dd2cea49 100644 --- a/server/models/utils/createDatabaseIfNotExists.js +++ b/server/models/utils/createDatabaseIfNotExists.js @@ -1,14 +1,15 @@ -const Sequelize = require('sequelize'); -const {database, username, password} = require('@config/mysqlConfig'); +import Sequelize from 'sequelize'; +import { database, username, password } from '@config/mysqlConfig'; const createDatabaseIfNotExists = () => { const sequelize = new Sequelize('', username, password, { - dialect : 'mysql', - logging : false, + dialect: 'mysql', + logging: false, operatorsAliases: false, }); return new Promise((resolve, reject) => { - sequelize.query(`CREATE DATABASE IF NOT EXISTS ${database};`) + sequelize + .query(`CREATE DATABASE IF NOT EXISTS ${database};`) .then(() => { resolve(); }) @@ -18,4 +19,4 @@ const createDatabaseIfNotExists = () => { }); }; -module.exports = createDatabaseIfNotExists; +export default createDatabaseIfNotExists; diff --git a/server/models/utils/createFileRecordData.js b/server/models/utils/createFileRecordData.js index fdcb9ce0..a7d973cc 100644 --- a/server/models/utils/createFileRecordData.js +++ b/server/models/utils/createFileRecordData.js @@ -1,22 +1,11 @@ -const getMediaDimensions = require('../../utils/getMediaDimensions.js'); +import getMediaDimensions from 'server/utils/getMediaDimensions.js'; -async function createFileRecordDataAfterGet (resolveResult, getResult) { - const { - name, - claimId, - outpoint, - contentType: fileType, - } = resolveResult; +export async function createFileRecordDataAfterGet(resolveResult, getResult) { + 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 { name, @@ -30,22 +19,17 @@ async function createFileRecordDataAfterGet (resolveResult, getResult) { }; } -async function createFileRecordDataAfterPublish (fileName, fileType, publishParams, publishResults) { - const { - name, - file_path: filePath, - } = publishParams; +export async function createFileRecordDataAfterPublish( + fileName, + fileType, + publishParams, + publishResults +) { + 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 { name, @@ -58,8 +42,3 @@ async function createFileRecordDataAfterPublish (fileName, fileType, publishPara fileType, }; } - -module.exports = { - createFileRecordDataAfterGet, - createFileRecordDataAfterPublish, -}; diff --git a/server/models/utils/returnShortId.js b/server/models/utils/returnShortId.js index 9c362c61..5c9a6bc8 100644 --- a/server/models/utils/returnShortId.js +++ b/server/models/utils/returnShortId.js @@ -16,10 +16,10 @@ const returnShortId = (claimsArray, longId) => { shortIdLength += 1; shortId = longId.substring(0, shortIdLength); possibleMatches = possibleMatches.filter(element => { - return (element.claimId && (element.claimId.substring(0, shortIdLength) === shortId)); + return element.claimId && element.claimId.substring(0, shortIdLength) === shortId; }); } return shortId; }; -module.exports = returnShortId; +export default returnShortId; diff --git a/server/models/utils/returnShortId.test.js b/server/models/utils/returnShortId.test.js index 56b8cbb9..9b2d49d8 100644 --- a/server/models/utils/returnShortId.test.js +++ b/server/models/utils/returnShortId.test.js @@ -1,36 +1,36 @@ -const chai = require('chai'); +import chai from 'chai'; const expect = chai.expect; -describe('#parsePublishApiRequestBody()', function () { +describe('#parsePublishApiRequestBody()', function() { const returnShortId = require('./returnShortId.js'); let dummyClaimsArray; 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 = [ - {claimId: 'a123456789'}, - {claimId: 'b123456789'}, - {claimId: 'c123456789'}, + { claimId: 'a123456789' }, + { claimId: 'b123456789' }, + { claimId: 'c123456789' }, ]; dummyLongId = 'xxxxxxxxxx'; 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 = [ - {claimId: 'a123456789'}, - {claimId: 'b123456789'}, - {claimId: 'c123456789'}, + { claimId: 'a123456789' }, + { claimId: 'b123456789' }, + { claimId: 'c123456789' }, ]; dummyLongId = 'c123456789'; 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 = [ - {claimId: 'a123456789', height: 10}, - {claimId: 'ab12345678', height: 11}, - {claimId: 'ab12341111', height: 12}, + { claimId: 'a123456789', height: 10 }, + { claimId: 'ab12345678', height: 11 }, + { claimId: 'ab12341111', height: 12 }, ]; dummyLongId = 'a123456789'; expect(returnShortId(dummyClaimsArray, dummyLongId)).to.equal('a'); diff --git a/server/models/utils/trendingAnalysis.js b/server/models/utils/trendingAnalysis.js index 759d10c6..5404490c 100644 --- a/server/models/utils/trendingAnalysis.js +++ b/server/models/utils/trendingAnalysis.js @@ -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 MAX_P = 6.44357455534; // v8 float 1.0...0 -const getMean = (numArr) => { +const getMean = numArr => { let total = 0; let length = numArr.length; // store local to reduce potential prop lookups @@ -17,12 +17,10 @@ const getMean = (numArr) => { }; 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)); }; -const getInformationFromValues = (numArr) => { +export const getInformationFromValues = numArr => { let mean = getMean(numArr); return { @@ -31,9 +29,10 @@ const getInformationFromValues = (numArr) => { }; }; -const getZScore = (value, mean, sDeviation) => (sDeviation !== 0 ? (value - mean) / sDeviation : 0); +export const getZScore = (value, mean, sDeviation) => + sDeviation !== 0 ? (value - mean) / sDeviation : 0; -const getFastPValue = (zScore) => { +export const getFastPValue = zScore => { if (zScore <= MIN_P) { return 0; } @@ -47,7 +46,10 @@ const getFastPValue = (zScore) => { let term = 1; while (Math.abs(term) > MAX_P_PRECISION) { - 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; + 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; sum += term; k++; factorialK *= k; @@ -57,11 +59,4 @@ const getFastPValue = (zScore) => { return sum; }; -const getWeight = (zScore, pValue) => (zScore * pValue); - -module.exports = { - getInformationFromValues, - getZScore, - getFastPValue, - getWeight, -}; +export const getWeight = (zScore, pValue) => zScore * pValue; diff --git a/server/models/views.js b/server/models/views.js index 9bb6f218..6859cf26 100644 --- a/server/models/views.js +++ b/server/models/views.js @@ -1,32 +1,32 @@ -module.exports = (sequelize, { BOOLEAN, DATE, STRING }) => { +export default (sequelize, { BOOLEAN, DATE, STRING }) => { const Views = sequelize.define( 'Views', { time: { - type : DATE(6), + type: DATE(6), defaultValue: sequelize.NOW, }, isChannel: { - type : BOOLEAN, + type: BOOLEAN, defaultValue: false, }, claimId: { - type : STRING, + type: STRING, defaultValue: null, }, publisherId: { - type : STRING, + type: STRING, defaultValue: null, }, ip: { - type : STRING, + type: STRING, defaultValue: null, }, }, { freezeTableName: true, - timestamps : false, // don't use default timestamps columns - indexes : [ + timestamps: false, // don't use default timestamps columns + indexes: [ { fields: ['time', 'isChannel', 'claimId', 'publisherId', 'ip'], }, @@ -34,15 +34,15 @@ module.exports = (sequelize, { BOOLEAN, DATE, STRING }) => { } ); - Views.getUniqueViews = ({ - hours = 0, - minutes = 30, - } = {}) => { + Views.getUniqueViews = ({ hours = 0, minutes = 30 } = {}) => { let time = new Date(); time.setHours(time.getHours() - hours); time.setMinutes(time.getMinutes() - minutes); - const sqlTime = time.toISOString().slice(0, 19).replace('T', ' '); + const sqlTime = time + .toISOString() + .slice(0, 19) + .replace('T', ' '); const selectString = 'claimId, publisherId, isChannel, COUNT(DISTINCT ip) as views'; const groupString = 'claimId, publisherId, isChannel'; @@ -53,13 +53,13 @@ module.exports = (sequelize, { BOOLEAN, DATE, STRING }) => { ); }; - Views.getGetUniqueViewsbByClaimId = (claimId) => { + Views.getGetUniqueViewsbByClaimId = claimId => { return Views.count({ where: { claimId, }, distinct: true, - col : 'ip', + col: 'ip', }); }; diff --git a/server/render/renderFullPage.js b/server/render/renderFullPage.js index 7454d043..fb2b461a 100644 --- a/server/render/renderFullPage.js +++ b/server/render/renderFullPage.js @@ -1,11 +1,11 @@ -const md5File = require('md5-file'); -const path = require('path'); +import md5File from 'md5-file'; +import path from 'path'; const bundlePath = path.resolve('./public/bundle/bundle.js'); const bundleHash = md5File.sync(bundlePath); const shortBundleHash = bundleHash.substring(0, 4); -module.exports = (helmet, html, preloadedState) => { +export default (helmet, html, preloadedState) => { // take the html and preloadedState and return the full page return ` diff --git a/server/routes/api/index.js b/server/routes/api/index.js index a2b1c2b8..44e89c3a 100644 --- a/server/routes/api/index.js +++ b/server/routes/api/index.js @@ -1,65 +1,87 @@ // middleware -const { autoblockPublishMiddleware, autoblockPublishBodyMiddleware } = require('../../middleware/autoblockPublishMiddleware'); -const multipartMiddleware = require('../../middleware/multipartMiddleware'); -const torCheckMiddleware = require('../../middleware/torCheckMiddleware'); +import multipartMiddleware from 'server/middleware/multipartMiddleware'; +import torCheckMiddleware from 'server/middleware/torCheckMiddleware'; // route handlers -const channelAvailability = require('../../controllers/api/channel/availability'); -const channelClaims = require('../../controllers/api/channel/claims'); -const channelData = require('../../controllers/api/channel/data'); -const channelShortId = require('../../controllers/api/channel/shortId'); -const claimAvailability = require('../../controllers/api/claim/availability'); -const claimData = require('../../controllers/api/claim/data/'); -const claimGet = require('../../controllers/api/claim/get'); -const claimList = require('../../controllers/api/claim/list'); -const claimLongId = require('../../controllers/api/claim/longId'); -const claimPublish = require('../../controllers/api/claim/publish'); -const claimAbandon = require('../../controllers/api/claim/abandon'); -const claimUpdate = require('../../controllers/api/claim/update'); -const claimResolve = require('../../controllers/api/claim/resolve'); -const claimShortId = require('../../controllers/api/claim/shortId'); -const claimViews = require('../../controllers/api/claim/views'); -const fileAvailability = require('../../controllers/api/file/availability'); -const specialClaims = require('../../controllers/api/special/claims'); -const userPassword = require('../../controllers/api/user/password'); -const publishingConfig = require('../../controllers/api/config/site/publishing'); -const getTorList = require('../../controllers/api/tor'); -const getBlockedList = require('../../controllers/api/blocked'); -const getOEmbedData = require('../../controllers/api/oEmbed'); +import channelAvailability from 'server/controllers/api/channel/availability'; +import channelClaims from 'server/controllers/api/channel/claims'; +import channelData from 'server/controllers/api/channel/data'; +import channelShortId from 'server/controllers/api/channel/shortId'; +import claimAvailability from 'server/controllers/api/claim/availability'; +import claimData from 'server/controllers/api/claim/data/'; +import claimGet from 'server/controllers/api/claim/get'; +import claimList from 'server/controllers/api/claim/list'; +import claimLongId from 'server/controllers/api/claim/longId'; +import claimPublish from 'server/controllers/api/claim/publish'; +import claimAbandon from 'server/controllers/api/claim/abandon'; +import claimUpdate from 'server/controllers/api/claim/update'; +import claimResolve from 'server/controllers/api/claim/resolve'; +import claimShortId from 'server/controllers/api/claim/shortId'; +import claimViews from 'server/controllers/api/claim/views'; +import fileAvailability from 'server/controllers/api/file/availability'; +import specialClaims from 'server/controllers/api/special/claims'; +import userPassword from 'server/controllers/api/user/password'; +import publishingConfig from 'server/controllers/api/config/site/publishing'; +import getTorList from 'server/controllers/api/tor'; +import getBlockedList from 'server/controllers/api/blocked'; +import getOEmbedData from 'server/controllers/api/oEmbed'; +const { + autoblockPublishMiddleware, + autoblockPublishBodyMiddleware, +} = require('server/middleware/autoblockPublishMiddleware'); export default { // homepage routes - '/api/homepage/data/channels' : { controller: [ torCheckMiddleware, channelData ] }, + '/api/homepage/data/channels': { controller: [torCheckMiddleware, channelData] }, // channel routes - '/api/channel/availability/:name' : { controller: [ torCheckMiddleware, channelAvailability ] }, - '/api/channel/short-id/:longId/:name' : { controller: [ torCheckMiddleware, channelShortId ] }, - '/api/channel/data/:channelName/:channelClaimId' : { controller: [ torCheckMiddleware, channelData ] }, - '/api/channel/claims/:channelName/:channelClaimId/:page': { controller: [ torCheckMiddleware, channelClaims ] }, + '/api/channel/availability/:name': { controller: [torCheckMiddleware, channelAvailability] }, + '/api/channel/short-id/:longId/:name': { controller: [torCheckMiddleware, channelShortId] }, + '/api/channel/data/:channelName/:channelClaimId': { + controller: [torCheckMiddleware, channelData], + }, + '/api/channel/claims/:channelName/:channelClaimId/:page': { + controller: [torCheckMiddleware, channelClaims], + }, // sepcial routes - '/api/special/:name/:page': { controller: [ torCheckMiddleware, specialClaims ] }, + '/api/special/:name/:page': { controller: [torCheckMiddleware, specialClaims] }, // claim routes - '/api/claim/availability/:name' : { controller: [ torCheckMiddleware, claimAvailability ] }, - '/api/claim/data/:claimName/:claimId' : { controller: [ torCheckMiddleware, claimData ] }, - '/api/claim/get/:name/:claimId' : { controller: [ torCheckMiddleware, claimGet ] }, - '/api/claim/list/:name' : { controller: [ torCheckMiddleware, claimList ] }, - '/api/claim/long-id' : { method: 'post', controller: [ torCheckMiddleware, claimLongId ] }, // note: should be a 'get' - '/api/claim/publish' : { method: 'post', controller: [ torCheckMiddleware, autoblockPublishMiddleware, multipartMiddleware, 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 ] }, + '/api/claim/availability/:name': { controller: [torCheckMiddleware, claimAvailability] }, + '/api/claim/data/:claimName/:claimId': { controller: [torCheckMiddleware, claimData] }, + '/api/claim/get/:name/:claimId': { controller: [torCheckMiddleware, claimGet] }, + '/api/claim/list/:name': { controller: [torCheckMiddleware, claimList] }, + '/api/claim/long-id': { method: 'post', controller: [torCheckMiddleware, claimLongId] }, // note: should be a 'get' + '/api/claim/publish': { + method: 'post', + controller: [ + torCheckMiddleware, + autoblockPublishMiddleware, + multipartMiddleware, + 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 - '/api/file/availability/:name/:claimId': { controller: [ torCheckMiddleware, fileAvailability ] }, + '/api/file/availability/:name/:claimId': { controller: [torCheckMiddleware, fileAvailability] }, // user routes - '/api/user/password/' : { method: 'put', controller: [ torCheckMiddleware, userPassword ] }, + '/api/user/password/': { method: 'put', controller: [torCheckMiddleware, userPassword] }, // configs - '/api/config/site/publishing' : { controller: [ torCheckMiddleware, publishingConfig ] }, + '/api/config/site/publishing': { controller: [torCheckMiddleware, publishingConfig] }, // tor - '/api/tor' : { controller: [ torCheckMiddleware, getTorList ] }, + '/api/tor': { controller: [torCheckMiddleware, getTorList] }, // blocked - '/api/blocked' : { controller: [ torCheckMiddleware, getBlockedList ] }, + '/api/blocked': { controller: [torCheckMiddleware, getBlockedList] }, // open embed - '/api/oembed' : { controller: [ torCheckMiddleware, getOEmbedData ] }, + '/api/oembed': { controller: [torCheckMiddleware, getOEmbedData] }, }; diff --git a/server/routes/assets/index.js b/server/routes/assets/index.js index 14a724b0..eed94b7c 100644 --- a/server/routes/assets/index.js +++ b/server/routes/assets/index.js @@ -1,11 +1,19 @@ -const serveByClaim = require('../../controllers/assets/serveByClaim'); -const serveByIdentifierAndClaim = require('../../controllers/assets/serveByIdentifierAndClaim'); +import serveByClaim from 'server/controllers/assets/serveByClaim'; +import serveByIdentifierAndClaim from 'server/controllers/assets/serveByIdentifierAndClaim'; // TODO: Adjust build & sources to use import/export everywhere const Actions = require('@actions').default; const Sagas = require('@sagas').default; export default { - '/:identifier/:claim': { controller: serveByIdentifierAndClaim, action: Actions.onHandleShowPageUri, saga: Sagas.handleShowPageUri }, - '/:claim' : { controller: serveByClaim, action: Actions.onHandleShowPageUri, saga: Sagas.handleShowPageUri }, + '/:identifier/:claim': { + controller: serveByIdentifierAndClaim, + action: Actions.onHandleShowPageUri, + saga: Sagas.handleShowPageUri, + }, + '/:claim': { + controller: serveByClaim, + action: Actions.onHandleShowPageUri, + saga: Sagas.handleShowPageUri, + }, }; diff --git a/server/routes/auth/index.js b/server/routes/auth/index.js index 26a90686..f76ab4e2 100644 --- a/server/routes/auth/index.js +++ b/server/routes/auth/index.js @@ -1,12 +1,15 @@ -const speechPassport = require('../../speechPassport'); -const handleSignupRequest = require('../../controllers/auth/signup'); -const handleLoginRequest = require('../../controllers/auth/login'); -const handleLogoutRequest = require('../../controllers/auth/logout'); -const handleUserRequest = require('../../controllers/auth/user'); +import speechPassport from '../../speechPassport'; +import handleSignupRequest from '../../controllers/auth/signup'; +import handleLoginRequest from '../../controllers/auth/login'; +import handleLogoutRequest from '../../controllers/auth/logout'; +import handleUserRequest from '../../controllers/auth/user'; export default { - '/signup': { method: 'post', controller: [ speechPassport.authenticate('local-signup'), handleSignupRequest ] }, - '/auth' : { method: 'post', controller: handleLoginRequest }, + '/signup': { + method: 'post', + controller: [speechPassport.authenticate('local-signup'), handleSignupRequest], + }, + '/auth': { method: 'post', controller: handleLoginRequest }, '/logout': { controller: handleLogoutRequest }, - '/user' : { controller: handleUserRequest }, + '/user': { controller: handleUserRequest }, }; diff --git a/server/routes/pages/index.js b/server/routes/pages/index.js index 99aa7902..f9838057 100644 --- a/server/routes/pages/index.js +++ b/server/routes/pages/index.js @@ -1,21 +1,25 @@ import handlePageRequest from '../../controllers/pages/sendReactApp'; -const handleVideoEmbedRequest = require('../../controllers/pages/sendVideoEmbedPage'); -const redirect = require('../../controllers/utils/redirect'); +import handleVideoEmbedRequest from '../../controllers/pages/sendVideoEmbedPage'; +import redirect from '../../controllers/utils/redirect'; // TODO: Adjust build & sources to use import/export everywhere const Actions = require('@actions').default; const Sagas = require('@sagas').default; export default { - '/' : { controller: handlePageRequest, action: Actions.onHandleShowHomepage, saga: Sagas.handleShowHomepage }, - '/login' : { controller: handlePageRequest }, - '/about' : { controller: handlePageRequest }, - '/tos' : { controller: handlePageRequest }, - '/faq' : { controller: handlePageRequest }, - '/trending' : { controller: redirect('/popular') }, - '/popular' : { controller: handlePageRequest }, - '/new' : { controller: handlePageRequest }, - '/edit/:claimId' : { controller: handlePageRequest }, - '/multisite' : { controller: handlePageRequest }, - '/video-embed/:name/:claimId/:config?': { controller: handleVideoEmbedRequest }, // for twitter + '/': { + controller: handlePageRequest, + action: Actions.onHandleShowHomepage, + saga: Sagas.handleShowHomepage, + }, + '/login': { controller: handlePageRequest }, + '/about': { controller: handlePageRequest }, + '/tos': { controller: handlePageRequest }, + '/faq': { controller: handlePageRequest }, + '/trending': { controller: redirect('/popular') }, + '/popular': { controller: handlePageRequest }, + '/new': { controller: handlePageRequest }, + '/edit/:claimId': { controller: handlePageRequest }, + '/multisite': { controller: handlePageRequest }, + '/video-embed/:name/:claimId/:config?': { controller: handleVideoEmbedRequest }, // for twitter }; diff --git a/server/speechPassport/index.js b/server/speechPassport/index.js index 60ec1808..c746e32c 100644 --- a/server/speechPassport/index.js +++ b/server/speechPassport/index.js @@ -1,12 +1,12 @@ -const passport = require('passport'); -const localLoginStrategy = require('./utils/local-login.js'); -const localSignupStrategy = require('./utils/local-signup.js'); -const serializeUser = require('./utils/serializeUser.js'); -const deserializeUser = require('./utils/deserializeUser.js'); +import passport from 'passport'; +import localLoginStrategy from './utils/local-login.js'; +import localSignupStrategy from './utils/local-signup.js'; +import serializeUser from './utils/serializeUser.js'; +import deserializeUser from './utils/deserializeUser.js'; passport.deserializeUser(deserializeUser); passport.serializeUser(serializeUser); passport.use('local-login', localLoginStrategy); passport.use('local-signup', localSignupStrategy); -module.exports = passport; +export default passport; diff --git a/server/speechPassport/utils/deserializeUser.js b/server/speechPassport/utils/deserializeUser.js index 4697bd10..80d723c6 100644 --- a/server/speechPassport/utils/deserializeUser.js +++ b/server/speechPassport/utils/deserializeUser.js @@ -3,4 +3,4 @@ const deserializeUser = (user, done) => { done(null, user); }; -module.exports = deserializeUser; +export default deserializeUser; diff --git a/server/speechPassport/utils/local-login.js b/server/speechPassport/utils/local-login.js index d9f889c8..a2c4cb3a 100644 --- a/server/speechPassport/utils/local-login.js +++ b/server/speechPassport/utils/local-login.js @@ -1,15 +1,15 @@ +import db from 'server/models'; const PassportLocalStrategy = require('passport-local').Strategy; const logger = require('winston'); -const db = require('../../models'); -const returnUserAndChannelInfo = (userInstance) => { +const returnUserAndChannelInfo = userInstance => { return new Promise((resolve, reject) => { let userInfo = {}; userInfo['id'] = userInstance.id; userInfo['userName'] = userInstance.userName; userInstance .getChannel() - .then(({channelName, channelClaimId}) => { + .then(({ channelName, channelClaimId }) => { userInfo['channelName'] = channelName; userInfo['channelClaimId'] = channelClaimId; return db.Certificate.getShortChannelIdFromLongChannelId(channelClaimId, channelName); @@ -24,26 +24,26 @@ const returnUserAndChannelInfo = (userInstance) => { }); }; -module.exports = new PassportLocalStrategy( +const Strategy = new PassportLocalStrategy( { usernameField: 'username', passwordField: 'password', }, (username, password, done) => { - return db.User - .findOne({ - where: {userName: username}, - }) + return db.User.findOne({ + where: { userName: username }, + }) .then(user => { if (!user) { 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.comparePassword(password) + return user + .comparePassword(password) .then(isMatch => { if (!isMatch) { 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'); return returnUserAndChannelInfo(user) @@ -63,3 +63,5 @@ module.exports = new PassportLocalStrategy( }); } ); + +export default Strategy; diff --git a/server/speechPassport/utils/local-signup.js b/server/speechPassport/utils/local-signup.js index 2662b721..42cbd451 100644 --- a/server/speechPassport/utils/local-signup.js +++ b/server/speechPassport/utils/local-signup.js @@ -1,10 +1,12 @@ +import { createChannel } from 'server/lbrynet'; const PassportLocalStrategy = require('passport-local').Strategy; -const { createChannel } = require('../../lbrynet'); const logger = require('winston'); -const db = require('../../models'); -const { publishing: { closedRegistration } } = require('@config/siteConfig'); +const db = require('server/models'); +const { + publishing: { closedRegistration }, +} = require('@config/siteConfig'); -module.exports = new PassportLocalStrategy( +const Strategy = new PassportLocalStrategy( { usernameField: 'username', passwordField: 'password', @@ -28,19 +30,23 @@ module.exports = new PassportLocalStrategy( logger.verbose('userData >', userData); // create user record const channelData = { - channelName : `@${username}`, + channelName: `@${username}`, channelClaimId: tx.claim_id, }; logger.verbose('channelData >', channelData); // create certificate record const certificateData = { claimId: tx.claim_id, - name : `@${username}`, + name: `@${username}`, // address, }; logger.verbose('certificateData >', certificateData); // save user and certificate to db - return Promise.all([db.User.create(userData), db.Channel.create(channelData), db.Certificate.create(certificateData)]); + return Promise.all([ + db.User.create(userData), + db.Channel.create(channelData), + db.Certificate.create(certificateData), + ]); }) .then(([newUser, newChannel, newCertificate]) => { logger.verbose('user and certificate successfully created'); @@ -54,7 +60,10 @@ module.exports = new PassportLocalStrategy( }) .then(() => { logger.verbose('user and certificate successfully associated'); - return db.Certificate.getShortChannelIdFromLongChannelId(userInfo.channelClaimId, userInfo.channelName); + return db.Certificate.getShortChannelIdFromLongChannelId( + userInfo.channelClaimId, + userInfo.channelName + ); }) .then(shortChannelId => { userInfo['shortChannelId'] = shortChannelId; @@ -66,3 +75,4 @@ module.exports = new PassportLocalStrategy( }); } ); +export default Strategy; diff --git a/server/speechPassport/utils/serializeUser.js b/server/speechPassport/utils/serializeUser.js index ebb44c82..c1d7b033 100644 --- a/server/speechPassport/utils/serializeUser.js +++ b/server/speechPassport/utils/serializeUser.js @@ -3,4 +3,4 @@ const serializeUser = (user, done) => { done(null, user); }; -module.exports = serializeUser; +export default serializeUser; diff --git a/server/task-scripts/update-channel-names.js b/server/task-scripts/update-channel-names.js index 2ea7e9ec..9f698aeb 100644 --- a/server/task-scripts/update-channel-names.js +++ b/server/task-scripts/update-channel-names.js @@ -1,17 +1,18 @@ // load dependencies -const logger = require('winston'); -const db = require('../models'); +import logger from 'winston'; +import db from 'server/models'; require('../helpers/configureLogger.js')(logger); let totalClaims = 0; let totalClaimsNoCertificate = 0; -db.sequelize.sync() // sync sequelize +db.sequelize + .sync() // sync sequelize .then(() => { logger.info('finding claims with no channels'); return db.Claim.findAll({ where: { - channelName : null, + channelName: null, certificateId: { $ne: null, }, @@ -21,10 +22,9 @@ db.sequelize.sync() // sync sequelize .then(claimsArray => { totalClaims = claimsArray.length; const claimsUpdatePromises = claimsArray.map(claim => { - return db.Certificate - .findOne({ - where: { claimId: claim.get('certificateId') }, - }) + return db.Certificate.findOne({ + where: { claimId: claim.get('certificateId') }, + }) .then(certificate => { // if a certificate is found... if (certificate) { @@ -49,6 +49,6 @@ db.sequelize.sync() // sync sequelize logger.info('total claims found with no matching certificate record', totalClaimsNoCertificate); logger.debug('all done'); }) - .catch((error) => { + .catch(error => { logger.error(error); }); diff --git a/server/task-scripts/update-password.js b/server/task-scripts/update-password.js index f740d543..934ed6ed 100644 --- a/server/task-scripts/update-password.js +++ b/server/task-scripts/update-password.js @@ -1,6 +1,6 @@ // load dependencies -const logger = require('winston'); -const db = require('../models'); +import logger from 'winston'; +import db from '../models'; // configure logging require('../helpers/configureLogger.js')(logger); @@ -11,7 +11,8 @@ logger.debug('old password:', oldPassword); const newPassword = process.argv[4]; logger.debug('new password:', newPassword); -db.sequelize.sync() // sync sequelize +db.sequelize + .sync() // sync sequelize .then(() => { logger.info('finding user profile'); return db.User.findOne({ @@ -24,10 +25,7 @@ db.sequelize.sync() // sync sequelize if (!user) { throw new Error('no user found'); } - return Promise.all([ - user.comparePassword(oldPassword), - user, - ]); + return Promise.all([user.comparePassword(oldPassword), user]); }) .then(([isMatch, user]) => { if (!isMatch) { @@ -39,6 +37,6 @@ db.sequelize.sync() // sync sequelize .then(() => { logger.debug('Password successfully updated'); }) - .catch((error) => { + .catch(error => { logger.error(error); }); diff --git a/server/utils/awaitFileSize.js b/server/utils/awaitFileSize.js index c1a9543e..84724b81 100644 --- a/server/utils/awaitFileSize.js +++ b/server/utils/awaitFileSize.js @@ -1,5 +1,5 @@ -const { getFileListFileByOutpoint } = require('server/lbrynet'); -const logger = require('winston'); +import { getFileListFileByOutpoint } from 'server/lbrynet'; +import logger from 'winston'; function delay(t) { return new Promise(function(resolve) { @@ -27,4 +27,4 @@ const awaitFileSize = (outpoint, size, interval, timeout) => { return checkFileList(); }; -module.exports = awaitFileSize; +export default awaitFileSize; diff --git a/server/utils/blockList.js b/server/utils/blockList.js index 0c7637c2..a3737564 100644 --- a/server/utils/blockList.js +++ b/server/utils/blockList.js @@ -1,26 +1,32 @@ -const logger = require('winston'); -const db = require('../models'); +import logger from 'winston'; +import db from 'server/models'; let blockList = new Set(); -const setupBlockList = (intervalInSeconds = 60) => { +export const setupBlockList = (intervalInSeconds = 60) => { const fetchList = () => { return new Promise((resolve, reject) => { db.Blocked.getBlockList() - .then((result) => { + .then(result => { blockList.clear(); if (result.length > 0) { - result.map((item) => { blockList.add(item.dataValues.outpoint) }); + result.map(item => { + blockList.add(item.dataValues.outpoint); + }); resolve(); } else reject(); }) - .catch(e => { console.error('list was empty', e) }); + .catch(e => { + console.error('list was empty', e); + }); }); }; - setInterval(() => { fetchList() }, intervalInSeconds * 1000); + setInterval(() => { + fetchList(); + }, intervalInSeconds * 1000); return fetchList(); }; -module.exports = { - isBlocked: (outpoint) => { return blockList.has(outpoint) }, - setupBlockList, + +export const isBlocked = outpoint => { + return blockList.has(outpoint); }; diff --git a/server/utils/configureLogging.js b/server/utils/configureLogging.js index 49af20bb..985730ff 100644 --- a/server/utils/configureLogging.js +++ b/server/utils/configureLogging.js @@ -1,9 +1,9 @@ -const logger = require('winston'); +import logger from 'winston'; -const config = require('@config/loggerConfig'); +import config from '@config/loggerConfig'; const { logLevel } = config; -function configureLogging () { +export default function configureLogging() { logger.info('configuring winston logger...'); if (!config) { return logger.warn('No logger config found'); @@ -14,12 +14,12 @@ function configureLogging () { // configure the winston logger logger.configure({ transports: [ - new (logger.transports.Console)({ - level : logLevel || 'debug', - timestamp : false, - colorize : true, - prettyPrint : true, - handleExceptions : true, + new logger.transports.Console({ + level: logLevel || 'debug', + timestamp: false, + colorize: true, + prettyPrint: true, + handleExceptions: true, humanReadableUnhandledException: true, }), ], @@ -32,5 +32,3 @@ function configureLogging () { logger.debug('Testing: Log Level 4'); logger.silly('Testing: Log Level 5'); } - -module.exports = configureLogging; diff --git a/server/utils/configureSlack.js b/server/utils/configureSlack.js index feef1122..6e9d2644 100644 --- a/server/utils/configureSlack.js +++ b/server/utils/configureSlack.js @@ -1,10 +1,9 @@ -const winstonSlackWebHook = require('winston-slack-webhook').SlackWebHook; -const logger = require('winston'); +import { SlackWebHook as winstonSlackWebHook } from 'winston-slack-webhook'; +import logger from 'winston'; +import config from '@config/slackConfig'; +const { slackWebHook, slackErrorChannel, slackInfoChannel } = config; -const config = require('@config/slackConfig'); -const {slackWebHook, slackErrorChannel, slackInfoChannel} = config; - -function configureSlack () { +export default function configureSlack() { logger.info('configuring slack logger...'); if (!config) { return logger.warn('No slack config found'); @@ -16,12 +15,12 @@ function configureSlack () { // add a transport for errors to slack if (slackErrorChannel) { logger.add(winstonSlackWebHook, { - name : 'slack-errors-transport', - level : 'warn', + name: 'slack-errors-transport', + level: 'warn', webhookUrl: slackWebHook, - channel : slackErrorChannel, - username : 'spee.ch', - iconEmoji : ':face_with_head_bandage:', + channel: slackErrorChannel, + username: 'spee.ch', + iconEmoji: ':face_with_head_bandage:', }); } else { logger.warn('No slack error channel logging set up'); @@ -29,12 +28,12 @@ function configureSlack () { // add a transport for info in slack if (slackInfoChannel) { logger.add(winstonSlackWebHook, { - name : 'slack-info-transport', - level : 'info', + name: 'slack-info-transport', + level: 'info', webhookUrl: slackWebHook, - channel : slackInfoChannel, - username : 'spee.ch', - iconEmoji : ':nerd_face:', + channel: slackInfoChannel, + username: 'spee.ch', + iconEmoji: ':nerd_face:', }); } else { logger.warn('No slack info channel logging set up'); @@ -42,5 +41,3 @@ function configureSlack () { // send test messages logger.info('Slack logging is online.'); } - -module.exports = configureSlack; diff --git a/server/utils/createModuleAliases.js b/server/utils/createModuleAliases.js index 4420a6a7..89312986 100644 --- a/server/utils/createModuleAliases.js +++ b/server/utils/createModuleAliases.js @@ -1,7 +1,7 @@ -const { resolve } = require('path'); +import { resolve } from 'path'; const WWW_SPEECH_ROOT = resolve(process.cwd()); -module.exports = () => { +export default () => { let moduleAliases = {}; // default aliases moduleAliases['@config'] = resolve(WWW_SPEECH_ROOT, 'config'); diff --git a/server/utils/fetchClaimData.js b/server/utils/fetchClaimData.js index 2f3e0014..2e5dbafb 100644 --- a/server/utils/fetchClaimData.js +++ b/server/utils/fetchClaimData.js @@ -1,11 +1,9 @@ -const chainquery = require('chainquery').default; -const { getFileListFileByOutpoint } = require('server/lbrynet'); -const publishCache = require('server/utils/publishCache'); -const logger = require('winston'); +import chainquery from 'chainquery'; +import { getFileListFileByOutpoint } from 'server/lbrynet'; +import publishCache from 'server/utils/publishCache'; const fetchClaimData = async params => { let { claimId } = params; - logger.debug('fetchClaimData params:', params); if (claimId === 'none') { claimId = null; @@ -21,4 +19,4 @@ const fetchClaimData = async params => { } }; -module.exports = fetchClaimData; +export default fetchClaimData; diff --git a/server/utils/getClaimData.js b/server/utils/getClaimData.js index bbea5aa5..caa70f21 100644 --- a/server/utils/getClaimData.js +++ b/server/utils/getClaimData.js @@ -1,14 +1,14 @@ -const { - details: { host }, - assetDefaults: { thumbnail }, -} = require('@config/siteConfig'); -const chainquery = require('chainquery').default; -const mime = require('mime-types'); -const { isBlocked } = require('./blockList'); -const publishCache = require('server/utils/publishCache'); -const logger = require('winston'); +import chainquery from 'chainquery'; +import mime from 'mime-types'; +import { isBlocked } from './blockList'; +import publishCache from 'server/utils/publishCache'; +import logger from 'winston'; -module.exports = async (data, chName = null, chShortId = null) => { +import { details, assetDefaults } from '@config/siteConfig'; +const { host } = details; +const { thumbnail } = assetDefaults; + +export default async (data, chName = null, chShortId = null) => { // TODO: Refactor getching the channel name out; requires invasive changes. let dataFromFileList, dataFromChainquery, outpoint, certificateId; @@ -32,10 +32,9 @@ module.exports = async (data, chName = null, chShortId = null) => { let channelShortId = chShortId; let channelName = chName; // TODO: Factor blocked out - let blocked = false; + let blocked; if (isBlocked(outpoint)) { - logger.debug('blocking content'); blocked = true; } diff --git a/server/utils/getMediaDimensions.js b/server/utils/getMediaDimensions.js index d130fd40..b526f136 100644 --- a/server/utils/getMediaDimensions.js +++ b/server/utils/getMediaDimensions.js @@ -1,8 +1,8 @@ -const logger = require('winston'); -const { getImageHeightAndWidth } = require('./imageProcessing'); -const { getVideoHeightAndWidth } = require('./videoProcessing'); +import logger from 'winston'; +import { getImageHeightAndWidth } from './imageProcessing'; +import { getVideoHeightAndWidth } from './videoProcessing'; -async function getMediaDimensions (fileType, filePath) { +export default async function getMediaDimensions(fileType, filePath) { let height = 0; let width = 0; switch (fileType) { @@ -11,11 +11,11 @@ async function getMediaDimensions (fileType, filePath) { case 'image/png': case 'image/gif': logger.debug('creating File data for an image'); - [ height, width ] = await getImageHeightAndWidth(filePath); + [height, width] = await getImageHeightAndWidth(filePath); break; case 'video/mp4': logger.debug('creating File data for a video'); - [ height, width ] = await getVideoHeightAndWidth(filePath); + [height, width] = await getVideoHeightAndWidth(filePath); break; default: logger.error('unable to create File dimension data for unspported file type:', fileType); @@ -26,5 +26,3 @@ async function getMediaDimensions (fileType, filePath) { width, }; } - -module.exports = getMediaDimensions; diff --git a/server/utils/googleAnalytics.js b/server/utils/googleAnalytics.js index a193155b..90a9b595 100644 --- a/server/utils/googleAnalytics.js +++ b/server/utils/googleAnalytics.js @@ -1,25 +1,28 @@ -const logger = require('winston'); -const ua = require('universal-analytics'); -const { analytics : { googleId }, details: { title } } = require('@config/siteConfig'); +import logger from 'winston'; +import ua from 'universal-analytics'; +import { analytics, details } from '@config/siteConfig'; + +const { googleId } = analytics; +const { title } = details; const createServeEventParams = (headers, ip, originalUrl) => { return { - eventCategory : 'client requests', - eventAction : 'serve request', - eventLabel : originalUrl, - ipOverride : ip, + eventCategory: 'client requests', + eventAction: 'serve request', + eventLabel: originalUrl, + ipOverride: ip, userAgentOverride: headers['user-agent'], - documentReferrer : headers['referer'], + documentReferrer: headers['referer'], }; }; const createTimingEventParams = (category, variable, label, startTime, endTime) => { const duration = endTime - startTime; return { - userTimingCategory : category, + userTimingCategory: category, userTimingVariableName: variable, - userTimingTime : duration, - userTimingLabel : label, + userTimingTime: duration, + userTimingLabel: label, }; }; @@ -29,7 +32,7 @@ const sendGoogleAnalyticsEvent = (ip, params) => { } const visitorId = ip.replace(/\./g, '-'); const visitor = ua(googleId, visitorId, { strictCidFormat: false, https: true }); - visitor.event(params, (err) => { + visitor.event(params, err => { if (err) { return logger.error('Google Analytics Event Error >>', err); } @@ -42,7 +45,7 @@ const sendGoogleAnalyticsTiming = (siteTitle, params) => { return logger.debug('Skipping analytics timing because no GoogleId present in configs'); } const visitor = ua(googleId, siteTitle, { strictCidFormat: false, https: true }); - visitor.timing(params, (err) => { + visitor.timing(params, err => { if (err) { return logger.error('Google Analytics Event Error >>', err); } @@ -50,22 +53,19 @@ const sendGoogleAnalyticsTiming = (siteTitle, params) => { }); }; -const sendGAServeEvent = (headers, ip, originalUrl) => { +export const sendGAServeEvent = (headers, ip, originalUrl) => { const params = createServeEventParams(headers, ip, originalUrl); sendGoogleAnalyticsEvent(ip, params); }; -const sendGATimingEvent = (category, variable, label, startTime, endTime) => { +export const sendGATimingEvent = (category, variable, label, startTime, endTime) => { const params = createTimingEventParams(category, variable, label, startTime, endTime); sendGoogleAnalyticsTiming(title, params); }; -const chooseGaLbrynetPublishLabel = ({ channel_name: channelName, channel_id: channelId }) => { - return (channelName || channelId ? 'PUBLISH_IN_CHANNEL_CLAIM' : 'PUBLISH_ANONYMOUS_CLAIM'); -}; - -module.exports = { - sendGAServeEvent, - sendGATimingEvent, - chooseGaLbrynetPublishLabel, +export const chooseGaLbrynetPublishLabel = ({ + channel_name: channelName, + channel_id: channelId, +}) => { + return channelName || channelId ? 'PUBLISH_IN_CHANNEL_CLAIM' : 'PUBLISH_ANONYMOUS_CLAIM'; }; diff --git a/server/utils/imageProcessing.js b/server/utils/imageProcessing.js index 45e21a76..4ac46403 100644 --- a/server/utils/imageProcessing.js +++ b/server/utils/imageProcessing.js @@ -1,6 +1,6 @@ -const sizeOf = require('image-size'); +import sizeOf from 'image-size'; -const getImageHeightAndWidth = (filePath) => { +export const getImageHeightAndWidth = filePath => { return new Promise((resolve, reject) => { try { const { height, width } = sizeOf(filePath); @@ -10,7 +10,3 @@ const getImageHeightAndWidth = (filePath) => { } }); }; - -module.exports = { - getImageHeightAndWidth, -}; diff --git a/server/utils/isRequestLocal.js b/server/utils/isRequestLocal.js index aabc7d25..615a612a 100644 --- a/server/utils/isRequestLocal.js +++ b/server/utils/isRequestLocal.js @@ -1,6 +1,11 @@ -module.exports = function (req) { +export default function(req) { let reqIp = req.connection.remoteAddress; let host = req.get('host'); - return reqIp === '127.0.0.1' || reqIp === '::ffff:127.0.0.1' || reqIp === '::1' || host.indexOf('localhost') !== -1; -}; + return ( + reqIp === '127.0.0.1' || + reqIp === '::ffff:127.0.0.1' || + reqIp === '::1' || + host.indexOf('localhost') !== -1 + ); +} diff --git a/server/utils/isValidQueryObj.js b/server/utils/isValidQueryObj.js index cbebb337..b0d1a2c3 100644 --- a/server/utils/isValidQueryObj.js +++ b/server/utils/isValidQueryObj.js @@ -20,5 +20,4 @@ const isValidQueryObj = queryObj => { ((yOrigin <= maxDimension && yOrigin >= 0) || yOrigin === null) ); }; - -module.exports = isValidQueryObj; +export default isValidQueryObj; diff --git a/server/utils/parseQuerystring.js b/server/utils/parseQuerystring.js index 01e916c1..1e413868 100644 --- a/server/utils/parseQuerystring.js +++ b/server/utils/parseQuerystring.js @@ -1,6 +1,6 @@ const queryObject = {}; // TODO: replace quick/dirty try catch with better practice -module.exports = originalUrl => { +export default originalUrl => { try { originalUrl .split('?')[1] diff --git a/server/utils/processTrending.js b/server/utils/processTrending.js index 893e511f..ccaffcf4 100644 --- a/server/utils/processTrending.js +++ b/server/utils/processTrending.js @@ -1,14 +1,14 @@ -const db = require('server/models'); -const { +import db from 'server/models'; +import { getInformationFromValues, getZScore, getFastPValue, getWeight, -} = require('server/models/utils/trendingAnalysis'); +} from 'server/models/utils/trendingAnalysis'; -const logger = require('winston'); +import logger from 'winston'; -module.exports = async () => { +export default async () => { try { const claims = await db.Trending.getTrendingClaims(); const claimViews = await db.Views.getUniqueViews(); @@ -20,20 +20,13 @@ module.exports = async () => { const time = Date.now(); // Must create statistical analytics before we can process zScores, etc - const viewsNumArray = claimViews.map((claimViewsEntry) => claimViewsEntry.views); - const { - mean, - standardDeviation, - } = getInformationFromValues(viewsNumArray); + const viewsNumArray = claimViews.map(claimViewsEntry => claimViewsEntry.views); + const { mean, standardDeviation } = getInformationFromValues(viewsNumArray); for (let i = 0; i < claimViews.length; i++) { let claimViewsEntry = claimViews[i]; - const { - isChannel, - claimId, - publisherId, - } = claimViewsEntry; + const { isChannel, claimId, publisherId } = claimViewsEntry; const zScore = getZScore(claimViewsEntry.views, mean, standardDeviation); const pValue = getFastPValue(zScore); @@ -41,9 +34,9 @@ module.exports = async () => { const trendingData = { time, - isChannel : claimViewsEntry.isChannel, - claimId : claimViewsEntry.claimId, - publisherId : claimViewsEntry.publisherId, + isChannel: claimViewsEntry.isChannel, + claimId: claimViewsEntry.claimId, + publisherId: claimViewsEntry.publisherId, intervalViews: claimViewsEntry.views, weight, zScore, diff --git a/server/utils/publishCache.js b/server/utils/publishCache.js index c770cb5b..d8abddb1 100644 --- a/server/utils/publishCache.js +++ b/server/utils/publishCache.js @@ -1,4 +1,4 @@ -const NodeCache = require('node-cache'); +import NodeCache from 'node-cache'; const CACHE_TIMEOUT_IN_SECONDS = 10; const publishCache = new NodeCache({ stdTTL: CACHE_TIMEOUT_IN_SECONDS }); /* @@ -18,4 +18,4 @@ const publishCache = new NodeCache({ stdTTL: CACHE_TIMEOUT_IN_SECONDS }); */ -module.exports = publishCache; +export default publishCache; diff --git a/server/utils/videoProcessing.js b/server/utils/videoProcessing.js index 508f6d10..038a8dc6 100644 --- a/server/utils/videoProcessing.js +++ b/server/utils/videoProcessing.js @@ -1,11 +1,7 @@ -const getVideoDimensions = require('get-video-dimensions'); +import getVideoDimensions from 'get-video-dimensions'; -async function getVideoHeightAndWidth (filePath) { +export async function getVideoHeightAndWidth(filePath) { const videoDimensions = await getVideoDimensions(filePath); const { height, width } = videoDimensions; - return [ height, width ]; + return [height, width]; } - -module.exports = { - getVideoHeightAndWidth, -}; diff --git a/utils/createModuleAliases.js b/utils/createModuleAliases.js index 47560faa..cf8236a0 100644 --- a/utils/createModuleAliases.js +++ b/utils/createModuleAliases.js @@ -37,7 +37,7 @@ module.exports = () => { // aliases for utils moduleAliases['@globalutils'] = resolve('utils'); moduleAliases['@clientutils'] = resolve(`${DEFAULT_ROOT}/utils`); - // moduleAliases['@serverutils'] = resolve('server/utils'); + moduleAliases['@serverutils'] = resolve('server/utils'); // aliases for constants moduleAliases['@clientConstants'] = resolve(`${DEFAULT_ROOT}/constants`); diff --git a/utils/isApprovedChannel.js b/utils/isApprovedChannel.js index aaf8dcf8..8aed520f 100644 --- a/utils/isApprovedChannel.js +++ b/utils/isApprovedChannel.js @@ -1,9 +1,9 @@ -function isApprovedChannel (channel, channels) { +function isApprovedChannel(channel, channels) { const { name, shortId: short, longId: long } = channel; return Boolean( (long && channels.find(chan => chan.longId === long)) || - (name && short && channels.find(chan => chan.name === name && chan.shortId === short)) + (name && short && channels.find(chan => chan.name === name && chan.shortId === short)) ); } -module.exports = isApprovedChannel; +export default isApprovedChannel;