Revert "cuts release from staging" #997
123 changed files with 1629 additions and 1855 deletions
|
@ -7,7 +7,8 @@ import Img from 'react-image';
|
|||
const AssetPreview = ({ defaultThumbnail, claimData }) => {
|
||||
const {name, fileExt, contentType, thumbnail, title, blocked, transactionTime = 0} = claimData;
|
||||
const showUrl = createCanonicalLink({asset: {...claimData}});
|
||||
const embedUrl = `${showUrl}.${fileExt}?thumbnail=true`;
|
||||
console.log(transactionTime)
|
||||
const embedUrl = `${showUrl}.${fileExt}`;
|
||||
const ago = Date.now() / 1000 - transactionTime;
|
||||
const dayInSeconds = 60 * 60 * 24;
|
||||
const monthInSeconds = dayInSeconds * 30;
|
||||
|
|
|
@ -51,50 +51,50 @@ PUBLISHING:
|
|||
}
|
||||
|
||||
SERVING:
|
||||
|
||||
"dynamicFileSizing": {
|
||||
"enabled": false, - if you choose to allow your instance to serve transform images
|
||||
"maxDimension": 2000 - the maximum size you allow transform to scale
|
||||
},
|
||||
"markdownSettings": {
|
||||
"skipHtmlMain": true, - false: render html, in a somewhat unpredictable way~
|
||||
"escapeHtmlMain": true, - true: rather than render html, escape it and print it visibly
|
||||
"skipHtmlDescriptions": true, - as above, for descriptions
|
||||
"escapeHtmlDescriptions": true, - as above, for descriptions
|
||||
"allowedTypesMain": [], - markdown rendered as main content
|
||||
"allowedTypesDescriptions": [], - markdown rendered in description in content details
|
||||
"allowedTypesExample": [ - here are examples of allowed types
|
||||
"see react-markdown docs", `https://github.com/rexxars/react-markdown`
|
||||
"root",
|
||||
"text",
|
||||
"break",
|
||||
"paragraph",
|
||||
"emphasis",
|
||||
"strong",
|
||||
"thematicBreak",
|
||||
"blockquote",
|
||||
"delete",
|
||||
"link",
|
||||
"image", - you may not have a lot of control over how these are rendered
|
||||
"linkReference",
|
||||
"imageReference",
|
||||
"table",
|
||||
"tableHead",
|
||||
"tableBody",
|
||||
"tableRow",
|
||||
"tableCell",
|
||||
"list",
|
||||
"listItem",
|
||||
"heading",
|
||||
"inlineCode",
|
||||
"code",
|
||||
"html", - potentially DANGEROUS, intended for `serveOnlyApproved = true` environments, includes iframes, divs.
|
||||
"parsedHtml"
|
||||
],
|
||||
},
|
||||
"customFileExtensions": { - suggest a file extension for experimental content types you may be publishing
|
||||
"application/example-type": "example"
|
||||
}
|
||||
|
||||
"dynamicFileSizing": {
|
||||
"enabled": false, - if you choose to allow your instance to serve transform images
|
||||
"maxDimension": 2000 - the maximum size you allow transform to scale
|
||||
},
|
||||
"markdownSettings": {
|
||||
"skipHtmlMain": true, - false: render html, in a somewhat unpredictable way~
|
||||
"escapeHtmlMain": true, - true: rather than render html, escape it and print it visibly
|
||||
"skipHtmlDescriptions": true, - as above, for descriptions
|
||||
"escapeHtmlDescriptions": true, - as above, for descriptions
|
||||
"allowedTypesMain": [], - markdown rendered as main content
|
||||
"allowedTypesDescriptions": [], - markdown rendered in description in content details
|
||||
"allowedTypesExample": [ - here are examples of allowed types
|
||||
"see react-markdown docs", `https://github.com/rexxars/react-markdown`
|
||||
"root",
|
||||
"text",
|
||||
"break",
|
||||
"paragraph",
|
||||
"emphasis",
|
||||
"strong",
|
||||
"thematicBreak",
|
||||
"blockquote",
|
||||
"delete",
|
||||
"link",
|
||||
"image", - you may not have a lot of control over how these are rendered
|
||||
"linkReference",
|
||||
"imageReference",
|
||||
"table",
|
||||
"tableHead",
|
||||
"tableBody",
|
||||
"tableRow",
|
||||
"tableCell",
|
||||
"list",
|
||||
"listItem",
|
||||
"heading",
|
||||
"inlineCode",
|
||||
"code",
|
||||
"html", - potentially DANGEROUS, intended for `serveOnlyApproved = true` environments, includes iframes, divs.
|
||||
"parsedHtml"
|
||||
],
|
||||
},
|
||||
"customFileExtensions": { - suggest a file extension for experimental content types you may be publishing
|
||||
"application/example-type": "example"
|
||||
}
|
||||
|
||||
STARTUP:
|
||||
|
||||
|
|
134
package-lock.json
generated
134
package-lock.json
generated
|
@ -196,116 +196,6 @@
|
|||
"@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",
|
||||
|
@ -532,16 +422,6 @@
|
|||
"@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",
|
||||
|
@ -3439,11 +3319,6 @@
|
|||
"resolved": "https://registry.npmjs.org/cli-width/-/cli-width-2.2.0.tgz",
|
||||
"integrity": "sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk="
|
||||
},
|
||||
"clone": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/clone/-/clone-2.1.2.tgz",
|
||||
"integrity": "sha1-G39Ln1kfHo+DZwQBYANFoCiHQ18="
|
||||
},
|
||||
"clone-deep": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-2.0.2.tgz",
|
||||
|
@ -9042,15 +8917,6 @@
|
|||
"resolved": "https://registry.npmjs.org/nocache/-/nocache-2.0.0.tgz",
|
||||
"integrity": "sha1-ICtIAhoMTL3i34DeFaF0Q8i0OYA="
|
||||
},
|
||||
"node-cache": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/node-cache/-/node-cache-4.2.0.tgz",
|
||||
"integrity": "sha512-obRu6/f7S024ysheAjoYFEEBqqDWv4LOMNJEuO8vMeEw2AT4z+NCzO4hlc2lhI4vATzbCQv6kke9FVdx0RbCOw==",
|
||||
"requires": {
|
||||
"clone": "2.x",
|
||||
"lodash": "4.x"
|
||||
}
|
||||
},
|
||||
"node-fetch": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "http://registry.npmjs.org/node-fetch/-/node-fetch-2.1.2.tgz",
|
||||
|
|
|
@ -57,7 +57,6 @@
|
|||
"mime-types": "^2.1.21",
|
||||
"module-alias": "^2.1.0",
|
||||
"mysql2": "^1.6.4",
|
||||
"node-cache": "^4.2.0",
|
||||
"npm": "^6.3.0",
|
||||
"passport": "^0.4.0",
|
||||
"passport-local": "^1.0.0",
|
||||
|
@ -86,7 +85,6 @@
|
|||
"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",
|
||||
|
|
|
@ -14,11 +14,12 @@ try {
|
|||
let currentApp;
|
||||
|
||||
try {
|
||||
const Server = require('./server/').default;
|
||||
const Server = require('./server/');
|
||||
currentApp = Server;
|
||||
|
||||
const speech = new Server();
|
||||
speech.start();
|
||||
|
||||
} catch (error) {
|
||||
console.log('server startup error:', error);
|
||||
process.exit(1);
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import Sequelize from 'sequelize';
|
||||
import logger from 'winston';
|
||||
const Sequelize = require('sequelize');
|
||||
const logger = require('winston');
|
||||
|
||||
import abnormalClaimTable from './tables/abnormalClaimTable';
|
||||
import addressTable from './tables/addressTable';
|
||||
|
@ -22,45 +22,51 @@ 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');
|
||||
|
@ -68,17 +74,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,
|
||||
|
@ -87,7 +93,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];
|
||||
|
||||
|
|
|
@ -13,9 +13,6 @@ const getterMethods = {
|
|||
return mime.extension(this.content_type) ? mime.extension(this.content_type) : 'jpg';
|
||||
}
|
||||
},
|
||||
generated_outpoint() {
|
||||
return `${this.transaction_hash_id}:${this.vout}`;
|
||||
},
|
||||
};
|
||||
|
||||
export default (sequelize, { BOOLEAN, DATE, DECIMAL, ENUM, INTEGER, STRING, TEXT }) =>
|
||||
|
|
|
@ -187,18 +187,19 @@ export default (db, table, sequelize) => ({
|
|||
}
|
||||
},
|
||||
|
||||
resolveClaim: async claimId => {
|
||||
logger.debug(`Claim.resolveClaim: ${claimId}`);
|
||||
resolveClaim: async (name, claimId) => {
|
||||
logger.debug(`Claim.resolveClaim: ${name} ${claimId}`);
|
||||
return table
|
||||
.findAll({
|
||||
where: { claim_id: claimId },
|
||||
where: { name, claim_id: claimId },
|
||||
})
|
||||
.then(claimArray => {
|
||||
if (claimArray.length === 0) {
|
||||
return null;
|
||||
} else if (claimArray.length !== 1) {
|
||||
logger.warn(`more than one record matches${claimId} in db.Claim`);
|
||||
logger.warn(`more than one record matches ${name}#${claimId} in db.Claim`);
|
||||
}
|
||||
|
||||
return claimArray[0];
|
||||
});
|
||||
},
|
||||
|
@ -222,22 +223,23 @@ export default (db, table, sequelize) => ({
|
|||
return claimArray[0];
|
||||
});
|
||||
},
|
||||
getOutpoint: async claimId => {
|
||||
logger.debug(`finding outpoint for ${claimId}`);
|
||||
|
||||
getOutpoint: async (name, claimId) => {
|
||||
logger.debug(`finding outpoint for ${name}#${claimId}`);
|
||||
|
||||
return await table
|
||||
.findAll({
|
||||
where: { claim_id: claimId },
|
||||
attributes: ['transaction_hash_id', 'vout'],
|
||||
where: { name, claim_id: claimId },
|
||||
attributes: ['transaction_hash_id'],
|
||||
})
|
||||
.then(result => {
|
||||
if (result.length === 0) {
|
||||
throw new Error(`no record found for ${claimId}`);
|
||||
throw new Error(`no record found for ${name}#${claimId}`);
|
||||
} else if (result.length !== 1) {
|
||||
logger.warn(`more than one record matches ${claimId} in db.Claim`);
|
||||
logger.warn(`more than one record matches ${name}#${claimId} in db.Claim`);
|
||||
}
|
||||
|
||||
return `${result[0].transaction_hash_id}:${result[0].vout}`;
|
||||
return result[0].transaction_hash_id;
|
||||
});
|
||||
},
|
||||
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import logger from 'winston';
|
||||
import db from 'server/models';
|
||||
const logger = require('winston');
|
||||
const db = require('../../../models');
|
||||
|
||||
const updateBlockedList = (req, res) => {
|
||||
db.Blocked.refreshTable()
|
||||
|
@ -19,4 +19,4 @@ const updateBlockedList = (req, res) => {
|
|||
});
|
||||
};
|
||||
|
||||
export default updateBlockedList;
|
||||
module.exports = updateBlockedList;
|
||||
|
|
|
@ -1,17 +1,18 @@
|
|||
import db from 'server/models';
|
||||
const db = require('../../../../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;
|
||||
});
|
||||
};
|
||||
|
||||
export default checkChannelAvailability;
|
||||
module.exports = checkChannelAvailability;
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import checkChannelAvailability from './checkChannelAvailability.js';
|
||||
import { sendGATimingEvent } from '@serverutils/googleAnalytics.js';
|
||||
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
|
||||
const checkChannelAvailability = require('./checkChannelAvailability.js');
|
||||
const { sendGATimingEvent } = require('../../../../utils/googleAnalytics.js');
|
||||
const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
|
||||
|
||||
/*
|
||||
|
||||
|
@ -8,7 +8,7 @@ import { handleErrorResponse } from '../../../utils/errorHandlers.js';
|
|||
|
||||
*/
|
||||
|
||||
function addAtSymbolIfNecessary(name) {
|
||||
function addAtSymbolIfNecessary (name) {
|
||||
if (name.substring(0, 1) !== '@') {
|
||||
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) => {
|
|||
});
|
||||
};
|
||||
|
||||
export default channelAvailability;
|
||||
module.exports = channelAvailability;
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
import chainquery from 'chainquery';
|
||||
import logger from 'winston';
|
||||
import getClaimData from 'server/utils/getClaimData';
|
||||
import { returnPaginatedChannelClaims } from './channelPagination.js';
|
||||
const chainquery = require('chainquery').default;
|
||||
const logger = require('winston');
|
||||
const getClaimData = require('server/utils/getClaimData');
|
||||
const { returnPaginatedChannelClaims } = require('./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);
|
||||
};
|
||||
|
||||
export default getChannelClaims;
|
||||
module.exports = getChannelClaims;
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
|
||||
import getChannelClaims from './getChannelClaims.js';
|
||||
const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
|
||||
const getChannelClaims = require('./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) => {
|
|||
});
|
||||
};
|
||||
|
||||
export default channelClaims;
|
||||
module.exports = channelClaims;
|
||||
|
|
|
@ -1,25 +1,18 @@
|
|||
import db from 'server/models';
|
||||
import chainquery from 'chainquery';
|
||||
const db = require('server/models');
|
||||
const chainquery = require('chainquery').default;
|
||||
|
||||
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 {
|
||||
|
@ -29,4 +22,4 @@ const getChannelData = async (channelName, channelClaimId) => {
|
|||
};
|
||||
};
|
||||
|
||||
export default getChannelData;
|
||||
module.exports = getChannelData;
|
||||
|
|
|
@ -1,8 +1,7 @@
|
|||
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 { handleErrorResponse } = require('../../../utils/errorHandlers.js');
|
||||
const getChannelData = require('./getChannelData.js');
|
||||
const isApprovedChannel = require('../../../../../utils/isApprovedChannel');
|
||||
const { publishing: { serveOnlyApproved, approvedChannels } } = require('@config/siteConfig');
|
||||
|
||||
const NO_CHANNEL = 'NO_CHANNEL';
|
||||
const LONG_ID = 'longId';
|
||||
|
@ -21,9 +20,7 @@ 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,
|
||||
|
@ -49,4 +46,4 @@ const channelData = ({ ip, originalUrl, body, params }, res) => {
|
|||
});
|
||||
};
|
||||
|
||||
export default channelData;
|
||||
module.exports = channelData;
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import { handleErrorResponse } from 'server/controllers/utils/errorHandlers.js';
|
||||
import db from 'server/models';
|
||||
import chainquery from 'chainquery';
|
||||
const { handleErrorResponse } = require('server/controllers/utils/errorHandlers.js');
|
||||
const db = require('server/models');
|
||||
const chainquery = require('chainquery').default;
|
||||
|
||||
/*
|
||||
|
||||
|
@ -10,9 +10,7 @@ route to get a short channel id from long channel Id
|
|||
|
||||
const channelShortIdRoute = async ({ ip, originalUrl, params }, res) => {
|
||||
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);
|
||||
|
@ -24,4 +22,4 @@ const channelShortIdRoute = async ({ ip, originalUrl, params }, res) => {
|
|||
}
|
||||
};
|
||||
|
||||
export default channelShortIdRoute;
|
||||
module.exports = channelShortIdRoute;
|
||||
|
|
|
@ -1,37 +1,31 @@
|
|||
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';
|
||||
const logger = require('winston');
|
||||
const db = require('server/models');
|
||||
const { abandonClaim } = require('server/lbrynet');
|
||||
const deleteFile = require('../publish/deleteFile.js');
|
||||
const authenticateUser = require('../publish/authentication.js');
|
||||
|
||||
/*
|
||||
route to abandon a claim through the daemon
|
||||
DO AFTER THE REST WORKS
|
||||
*/
|
||||
|
||||
const claimAbandon = async (req, res) => {
|
||||
const { claimId } = req.body;
|
||||
const { user } = req;
|
||||
const {claimId} = req.body;
|
||||
const {user} = req;
|
||||
try {
|
||||
// This must not depend on db.Claim
|
||||
const [channel, claim] = await Promise.all([
|
||||
authenticateUser(user.channelName, null, null, user),
|
||||
chainquery.claim.queries.resolveClaim(claimId),
|
||||
db.Claim.findOne({where: {claimId}}),
|
||||
]);
|
||||
|
||||
if (!claim) throw new Error('That claim does not exist');
|
||||
if (!channel.channelName) throw new Error("You don't own this channel");
|
||||
if (!claim) throw new Error('That channel does not exist');
|
||||
if (!channel.channelName) throw new Error('You don\'t own this channel');
|
||||
|
||||
await abandonClaim({ claimId });
|
||||
// Add file_delete here.
|
||||
// Using db.File just to get the path. Use file_list.
|
||||
const file = await db.File.findOne({ where: { claimId } });
|
||||
await abandonClaim({claimId});
|
||||
const file = await db.File.findOne({where: {claimId}});
|
||||
await Promise.all([
|
||||
deleteFile(file.filePath),
|
||||
db.File.destroy({ where: { claimId } }),
|
||||
// Remove this
|
||||
db.Claim.destroy({ where: { claimId } }),
|
||||
db.File.destroy({where: {claimId}}),
|
||||
db.Claim.destroy({where: {claimId}}),
|
||||
]);
|
||||
logger.debug(`Claim abandoned: ${claimId}`);
|
||||
res.status(200).json({
|
||||
|
@ -47,4 +41,4 @@ const claimAbandon = async (req, res) => {
|
|||
}
|
||||
};
|
||||
|
||||
export default claimAbandon;
|
||||
module.exports = claimAbandon;
|
||||
|
|
|
@ -1,18 +1,16 @@
|
|||
import chainquery from 'chainquery';
|
||||
import Sequelize from 'sequelize';
|
||||
|
||||
import { publishing } from '@config/siteConfig';
|
||||
const { primaryClaimAddress, additionalClaimAddresses } = publishing;
|
||||
const chainquery = require('chainquery').default;
|
||||
const { publishing: { primaryClaimAddress, additionalClaimAddresses } } = require('@config/siteConfig');
|
||||
const Sequelize = require('sequelize');
|
||||
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,
|
||||
|
@ -20,11 +18,11 @@ const claimAvailability = async name => {
|
|||
},
|
||||
})
|
||||
.then(result => {
|
||||
return result.length <= 0;
|
||||
return (result.length <= 0);
|
||||
})
|
||||
.catch(error => {
|
||||
throw error;
|
||||
});
|
||||
};
|
||||
|
||||
export default claimAvailability;
|
||||
module.exports = claimAvailability;
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import checkClaimAvailability from './checkClaimAvailability.js';
|
||||
import { sendGATimingEvent } from '../../../../utils/googleAnalytics.js';
|
||||
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
|
||||
const checkClaimAvailability = require('./checkClaimAvailability.js');
|
||||
const { sendGATimingEvent } = require('../../../../utils/googleAnalytics.js');
|
||||
const { handleErrorResponse } = require('../../../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) => {
|
|||
});
|
||||
};
|
||||
|
||||
export default claimAvailability;
|
||||
module.exports = claimAvailability;
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
|
||||
import getClaimData from 'server/utils/getClaimData';
|
||||
import fetchClaimData from 'server/utils/fetchClaimData';
|
||||
import logger from 'winston';
|
||||
const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
|
||||
const getClaimData = require('server/utils/getClaimData');
|
||||
const fetchClaimData = require('server/utils/fetchClaimData');
|
||||
const chainquery = require('chainquery').default;
|
||||
const db = require('server/models');
|
||||
/*
|
||||
|
||||
route to return data for a claim
|
||||
|
@ -21,11 +22,11 @@ const claimData = async ({ ip, originalUrl, body, params }, res) => {
|
|||
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
data: await getClaimData(resolvedClaim),
|
||||
data : await getClaimData(resolvedClaim),
|
||||
});
|
||||
} catch (error) {
|
||||
handleErrorResponse(originalUrl, ip, error, res);
|
||||
}
|
||||
};
|
||||
|
||||
export default claimData;
|
||||
module.exports = claimData;
|
||||
|
|
|
@ -1,17 +1,12 @@
|
|||
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 RETRY_MS = 250;
|
||||
const TIMEOUT_MS = 15000;
|
||||
const MIN_BYTES = 15000000;
|
||||
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');
|
||||
|
||||
/*
|
||||
|
||||
|
@ -20,58 +15,49 @@ const MIN_BYTES = 15000000;
|
|||
*/
|
||||
|
||||
const claimGet = async ({ ip, originalUrl, params, headers }, res) => {
|
||||
logger.debug(`claim/get params`, params);
|
||||
const name = params.name;
|
||||
const claimId = params.claimId;
|
||||
|
||||
try {
|
||||
let claimDataFromChainquery = await chainquery.claim.queries
|
||||
.resolveClaim(claimId)
|
||||
.catch(() => null);
|
||||
|
||||
if (!claimDataFromChainquery) {
|
||||
let claimInfo = await chainquery.claim.queries.resolveClaim(name, claimId).catch(() => {});
|
||||
if (claimInfo) {
|
||||
logger.info('claim/get: claim resolved in chainquery');
|
||||
}
|
||||
if (!claimInfo) {
|
||||
claimInfo = await db.Claim.resolveClaim(name, claimId);
|
||||
}
|
||||
if (!claimInfo) {
|
||||
throw new Error('claim/get: resolveClaim: No matching uri found in Claim table');
|
||||
}
|
||||
if (headers && headers['user-agent'] && isBot(headers['user-agent'])) {
|
||||
logger.info(`ClaimGet Bot: From user-agent: ${headers['user-agent']} for: ${claimId}`);
|
||||
let lbrynetResolveResult = await resolveUri(`${name}#${claimId}`);
|
||||
const { message, completed } = lbrynetResolveResult;
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
message: 'Bot detected',
|
||||
message,
|
||||
completed: false,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
logger.info(`ClaimGet: From user-agent: ${headers['user-agent']} for: ${claimId}`);
|
||||
|
||||
let lbrynetResult = await getClaim(`${name}#${claimId}`);
|
||||
|
||||
if (!lbrynetResult) {
|
||||
throw new Error(`claim/get: getClaim Unable to Get ${name}#${claimId}`);
|
||||
}
|
||||
|
||||
const claimData = await getClaimData(claimDataFromChainquery);
|
||||
const fileReady = await awaitFileSize(lbrynetResult.outpoint, MIN_BYTES, RETRY_MS, TIMEOUT_MS);
|
||||
const claimData = await getClaimData(claimInfo);
|
||||
if (!claimData) {
|
||||
throw new Error('claim/get: getClaimData failed to get file blobs');
|
||||
}
|
||||
const fileReady = await awaitFileSize(lbrynetResult.outpoint, 10000000, 250, 10000);
|
||||
|
||||
if (fileReady !== 'ready') {
|
||||
throw new Error('claim/get: failed to get file after 10 seconds');
|
||||
}
|
||||
|
||||
const fileData = await createFileRecordDataAfterGet(claimData, lbrynetResult).catch(() => null);
|
||||
const fileData = await createFileRecordDataAfterGet(claimData, lbrynetResult);
|
||||
if (!fileData) {
|
||||
logger.error(
|
||||
'claim/get: createFileRecordDataAfterGet failed to create file dimensions in time'
|
||||
);
|
||||
throw new Error('claim/get: createFileRecordDataAfterGet failed to create file in time');
|
||||
}
|
||||
|
||||
const upsertCriteria = { name, claimId };
|
||||
const upsertResult = await db
|
||||
.upsert(db.File, fileData, upsertCriteria, 'File')
|
||||
.catch(() => null);
|
||||
|
||||
if (!upsertResult) {
|
||||
logger.error('claim/get: DB file upsert failed');
|
||||
}
|
||||
|
||||
await db.upsert(db.File, fileData, upsertCriteria, 'File');
|
||||
const { message, completed } = lbrynetResult;
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
|
@ -82,4 +68,4 @@ const claimGet = async ({ ip, originalUrl, params, headers }, res) => {
|
|||
handleErrorResponse(originalUrl, ip, error, res);
|
||||
}
|
||||
};
|
||||
export default claimGet;
|
||||
module.exports = claimGet;
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { getClaimList } from 'server/lbrynet';
|
||||
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
|
||||
const { getClaimList } = require('../../../../lbrynet');
|
||||
const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
|
||||
|
||||
/*
|
||||
|
||||
|
@ -17,4 +17,4 @@ const claimList = ({ ip, originalUrl, params }, res) => {
|
|||
});
|
||||
};
|
||||
|
||||
export default claimList;
|
||||
module.exports = claimList;
|
||||
|
|
|
@ -1,10 +1,9 @@
|
|||
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 db = require('server/models');
|
||||
const chainquery = require('chainquery').default;
|
||||
|
||||
import getClaimId from 'server/controllers/utils/getClaimId.js';
|
||||
const { handleErrorResponse } = require('server/controllers/utils/errorHandlers.js');
|
||||
|
||||
const getClaimId = require('server/controllers/utils/getClaimId.js');
|
||||
|
||||
const NO_CHANNEL = 'NO_CHANNEL';
|
||||
const NO_CLAIM = 'NO_CLAIM';
|
||||
|
@ -25,17 +24,8 @@ const claimLongId = ({ ip, originalUrl, body, params }, res) => {
|
|||
getClaimId(channelName, channelClaimId, claimName, claimId)
|
||||
.then(fullClaimId => {
|
||||
claimId = fullClaimId;
|
||||
if (!fullClaimId) {
|
||||
throw new Error('Unable to get fullClaimId');
|
||||
}
|
||||
return chainquery.claim.queries.getOutpoint(fullClaimId).catch(() => {
|
||||
logger.debug(`failed to get claimId from chainQuery given ${claimName} and ${fullClaimId}`);
|
||||
});
|
||||
return chainquery.claim.queries.getOutpoint(claimName, fullClaimId).catch(() => {});
|
||||
})
|
||||
// Remove this, replace with file_list
|
||||
// In the event that we need the longId of a claim just published
|
||||
// check to see if shortClaimId matches cache, then verify
|
||||
// Should we also verify
|
||||
.then(outpointResult => {
|
||||
if (!outpointResult) {
|
||||
return db.Claim.getOutpoint(claimName, claimId);
|
||||
|
@ -62,14 +52,14 @@ const claimLongId = ({ ip, originalUrl, body, params }, res) => {
|
|||
});
|
||||
}
|
||||
if (error === BLOCKED_CLAIM) {
|
||||
return res.status(451).json({
|
||||
return res.status(410).json({
|
||||
success: false,
|
||||
message:
|
||||
'In response to a complaint we received under the US Digital Millennium Copyright Act, we have blocked access to this content from our applications. For more details, see https://lbry.io/faq/dmca',
|
||||
'In response to a complaint we received under the US Digital Millennium Copyright Act, we have blocked access to this content from our applications. For more details, see https://lbry.com/faq/dmca',
|
||||
});
|
||||
}
|
||||
handleErrorResponse(originalUrl, ip, error, res);
|
||||
});
|
||||
};
|
||||
|
||||
export default claimLongId;
|
||||
module.exports = claimLongId;
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import logger from 'winston';
|
||||
import db from 'server/models';
|
||||
const logger = require('winston');
|
||||
const db = require('../../../../models');
|
||||
|
||||
const authenticateChannelCredentials = (channelName, channelId, userPassword) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
|
@ -10,9 +10,10 @@ 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');
|
||||
|
@ -50,7 +51,7 @@ const authenticateUser = (channelName, channelId, channelPassword, user) => {
|
|||
// case: no channelName or channel Id are provided (anonymous), regardless of whether user token is provided
|
||||
if (!channelName && !channelId) {
|
||||
resolve({
|
||||
channelName: null,
|
||||
channelName : null,
|
||||
channelClaimId: null,
|
||||
});
|
||||
return;
|
||||
|
@ -66,7 +67,7 @@ const authenticateUser = (channelName, channelId, channelPassword, user) => {
|
|||
return;
|
||||
}
|
||||
resolve({
|
||||
channelName: user.channelName,
|
||||
channelName : user.channelName,
|
||||
channelClaimId: user.channelClaimId,
|
||||
});
|
||||
return;
|
||||
|
@ -80,4 +81,4 @@ const authenticateUser = (channelName, channelId, channelPassword, user) => {
|
|||
});
|
||||
};
|
||||
|
||||
export default authenticateUser;
|
||||
module.exports = authenticateUser;
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import logger from 'winston';
|
||||
import { details, publishing } from '@config/siteConfig';
|
||||
const logger = require('winston');
|
||||
const { details, publishing } = require('@config/siteConfig');
|
||||
const createPublishParams = (
|
||||
filePath,
|
||||
name,
|
||||
|
@ -59,4 +59,4 @@ const createPublishParams = (
|
|||
return publishParams;
|
||||
};
|
||||
|
||||
export default createPublishParams;
|
||||
module.exports = createPublishParams;
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import logger from 'winston';
|
||||
import { details, publishing } from '@config/siteConfig';
|
||||
const logger = require('winston');
|
||||
const { details, publishing } = require('@config/siteConfig');
|
||||
|
||||
const createThumbnailPublishParams = (thumbnailFilePath, claimName, license, licenseUrl, nsfw) => {
|
||||
if (!thumbnailFilePath) {
|
||||
|
@ -26,4 +26,4 @@ const createThumbnailPublishParams = (thumbnailFilePath, claimName, license, lic
|
|||
};
|
||||
};
|
||||
|
||||
export default createThumbnailPublishParams;
|
||||
module.exports = createThumbnailPublishParams;
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
import logger from 'winston';
|
||||
import fs from 'fs';
|
||||
const logger = require('winston');
|
||||
const fs = require('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 => {
|
|||
});
|
||||
};
|
||||
|
||||
export default deleteFile;
|
||||
module.exports = deleteFile;
|
||||
|
|
|
@ -1,33 +1,30 @@
|
|||
import logger from 'winston';
|
||||
const logger = require('winston');
|
||||
|
||||
import { sendGATimingEvent } from 'server/utils/googleAnalytics.js';
|
||||
|
||||
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
|
||||
|
||||
import checkClaimAvailability from '../availability/checkClaimAvailability.js';
|
||||
|
||||
import publish from './publish.js';
|
||||
import createPublishParams from './createPublishParams.js';
|
||||
import createThumbnailPublishParams from './createThumbnailPublishParams.js';
|
||||
import parsePublishApiRequestBody from './parsePublishApiRequestBody.js';
|
||||
import parsePublishApiRequestFiles from './parsePublishApiRequestFiles.js';
|
||||
import authenticateUser from './authentication.js';
|
||||
|
||||
import chainquery from 'chainquery';
|
||||
import publishCache from 'server/utils/publishCache';
|
||||
import isApprovedChannel from '@globalutils/isApprovedChannel';
|
||||
import { details, publishing } from '@config/siteConfig';
|
||||
|
||||
import createCanonicalLink from '@globalutils/createCanonicalLink';
|
||||
const { host } = details;
|
||||
const {
|
||||
disabled,
|
||||
disabledMessage,
|
||||
publishOnlyApproved,
|
||||
approvedChannels,
|
||||
thumbnailChannel,
|
||||
thumbnailChannelId,
|
||||
} = publishing;
|
||||
details: { host },
|
||||
publishing: { disabled, disabledMessage },
|
||||
} = require('@config/siteConfig');
|
||||
|
||||
const { sendGATimingEvent } = require('server/utils/googleAnalytics.js');
|
||||
const isApprovedChannel = require('@globalutils/isApprovedChannel');
|
||||
const {
|
||||
publishing: { publishOnlyApproved, approvedChannels },
|
||||
} = 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 CLAIM_TAKEN = 'CLAIM_TAKEN';
|
||||
const UNAPPROVED_CHANNEL = 'UNAPPROVED_CHANNEL';
|
||||
|
||||
|
@ -72,7 +69,6 @@ const claimPublish = ({ body, files, headers, ip, originalUrl, user, tor }, res)
|
|||
thumbnailFileType,
|
||||
title,
|
||||
claimData,
|
||||
thumbData,
|
||||
claimId;
|
||||
// record the start time of the request
|
||||
gaStartTime = Date.now();
|
||||
|
@ -137,27 +133,20 @@ const claimPublish = ({ body, files, headers, ip, originalUrl, user, tor }, res)
|
|||
};
|
||||
throw error;
|
||||
}
|
||||
let promises = [];
|
||||
promises.push(publish(publishParams, fileName, fileType, filePath));
|
||||
// publish the thumbnail, if one exists
|
||||
if (thumbnailPublishParams) {
|
||||
promises.push(publish(thumbnailPublishParams, thumbnailFileName, thumbnailFileType));
|
||||
publish(thumbnailPublishParams, thumbnailFileName, thumbnailFileType);
|
||||
}
|
||||
// publish the asset
|
||||
return Promise.all(promises);
|
||||
return publish(publishParams, fileName, fileType, filePath);
|
||||
})
|
||||
.then(publishResults => {
|
||||
logger.debug('Publish success >', publishResults[0]);
|
||||
if (publishResults[1]) {
|
||||
logger.debug('Thumb Publish success >', publishResults[1]);
|
||||
thumbData = publishResults[1];
|
||||
}
|
||||
claimData = publishResults[0];
|
||||
|
||||
logger.info('Publish success >', publishResults);
|
||||
claimData = publishResults;
|
||||
({ claimId } = claimData);
|
||||
|
||||
if (channelName) {
|
||||
logger.verbose(`api/claim/publish: claimData.certificateId ${claimData.certificateId}`);
|
||||
logger.info(`api/claim/publish: claimData.certificateId ${claimData.certificateId}`);
|
||||
return chainquery.claim.queries.getShortClaimIdFromLongClaimId(
|
||||
claimData.certificateId,
|
||||
channelName
|
||||
|
@ -178,23 +167,6 @@ const claimPublish = ({ body, files, headers, ip, originalUrl, user, tor }, res)
|
|||
canonicalUrl = createCanonicalLink({ asset: { ...claimData, shortId } });
|
||||
}
|
||||
|
||||
// make sure we can look up the claimId until chainquery has it
|
||||
|
||||
let canonicalThumbUrl;
|
||||
if (thumbData) {
|
||||
canonicalThumbUrl = createCanonicalLink({
|
||||
asset: {
|
||||
channelName: thumbnailChannel,
|
||||
channelShortId: thumbnailChannelId,
|
||||
name: thumbData.name,
|
||||
},
|
||||
});
|
||||
logger.verbose('canonicalThumbUrl', canonicalThumbUrl);
|
||||
publishCache.set(canonicalThumbUrl, thumbData.claimId);
|
||||
publishCache.set(thumbData.claimId, thumbData);
|
||||
}
|
||||
publishCache.set(canonicalUrl, claimData.claimId);
|
||||
publishCache.set(claimData.claimId, claimData);
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
message: 'publish completed successfully',
|
||||
|
@ -208,6 +180,7 @@ const claimPublish = ({ body, files, headers, ip, originalUrl, user, tor }, res)
|
|||
claimData,
|
||||
},
|
||||
});
|
||||
// record the publish end time and send to google analytics
|
||||
sendGATimingEvent('end-to-end', 'publish', fileType, gaStartTime, Date.now());
|
||||
})
|
||||
.catch(error => {
|
||||
|
@ -221,4 +194,4 @@ const claimPublish = ({ body, files, headers, ip, originalUrl, user, tor }, res)
|
|||
});
|
||||
};
|
||||
|
||||
export default claimPublish;
|
||||
module.exports = claimPublish;
|
||||
|
|
|
@ -36,4 +36,4 @@ const parsePublishApiRequestBody = ({
|
|||
};
|
||||
};
|
||||
|
||||
export default parsePublishApiRequestBody;
|
||||
module.exports = parsePublishApiRequestBody;
|
||||
|
|
|
@ -1,14 +1,14 @@
|
|||
import chai from 'chai';
|
||||
const chai = require('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();
|
||||
});
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import path from 'path';
|
||||
import validateFileTypeAndSize from './validateFileTypeAndSize.js';
|
||||
import validateFileForPublish from './validateFileForPublish.js';
|
||||
const path = require('path');
|
||||
const validateFileTypeAndSize = require('./validateFileTypeAndSize.js');
|
||||
const validateFileForPublish = require('./validateFileForPublish.js');
|
||||
|
||||
const parsePublishApiRequestFiles = ({ file, thumbnail }, isUpdate) => {
|
||||
// make sure a file was provided
|
||||
|
@ -59,4 +59,4 @@ const parsePublishApiRequestFiles = ({ file, thumbnail }, isUpdate) => {
|
|||
return obj;
|
||||
};
|
||||
|
||||
export default parsePublishApiRequestFiles;
|
||||
module.exports = parsePublishApiRequestFiles;
|
||||
|
|
|
@ -1,19 +1,19 @@
|
|||
import chai from 'chai';
|
||||
const chai = require('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',
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
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 logger = require('winston');
|
||||
const db = require('../../../../models');
|
||||
const { publishClaim } = require('../../../../lbrynet');
|
||||
const { createFileRecordDataAfterPublish } = require('../../../../models/utils/createFileRecordData.js');
|
||||
const { createClaimRecordDataAfterPublish } = require('../../../../models/utils/createClaimRecordData.js');
|
||||
const deleteFile = require('./deleteFile.js');
|
||||
|
||||
const publish = async (publishParams, fileName, fileType) => {
|
||||
let publishResults;
|
||||
|
@ -29,39 +29,30 @@ const publish = async (publishParams, fileName, fileType) => {
|
|||
const certificateId = channel ? channel.channelClaimId : null;
|
||||
const channelName = channel ? channel.channelName : null;
|
||||
|
||||
const claimRecord = await createClaimRecordDataAfterPublish(
|
||||
certificateId,
|
||||
channelName,
|
||||
fileName,
|
||||
fileType,
|
||||
publishParams,
|
||||
publishResults
|
||||
);
|
||||
const { claimId } = claimRecord;
|
||||
const upsertCriteria = { name: publishParams.name, claimId };
|
||||
const claimRecord = await createClaimRecordDataAfterPublish(certificateId, channelName, fileName, fileType, publishParams, publishResults);
|
||||
const {claimId} = claimRecord;
|
||||
const upsertCriteria = {name: publishParams.name, claimId};
|
||||
if (newFile) {
|
||||
// this is the problem
|
||||
//
|
||||
fileRecord = await createFileRecordDataAfterPublish(
|
||||
fileName,
|
||||
fileType,
|
||||
publishParams,
|
||||
publishResults
|
||||
);
|
||||
fileRecord = await createFileRecordDataAfterPublish(fileName, fileType, publishParams, publishResults);
|
||||
} else {
|
||||
fileRecord = await db.File.findOne({ where: { claimId } }).then(result => result.dataValues);
|
||||
fileRecord = await db.File.findOne({where: {claimId}}).then(result => result.dataValues);
|
||||
}
|
||||
// TODO: refactor when SDK has dimension info
|
||||
|
||||
const [file, claim] = await Promise.all([
|
||||
db.upsert(db.File, fileRecord, upsertCriteria, 'File'),
|
||||
db.upsert(db.Claim, claimRecord, upsertCriteria, 'Claim'),
|
||||
]);
|
||||
logger.debug(`File and Claim records successfully created (${publishParams.name})`);
|
||||
// Remove this
|
||||
await Promise.all([file.setClaim(claim), claim.setFile(file)]);
|
||||
logger.debug(`File and Claim records successfully associated (${publishParams.name})`);
|
||||
logger.info(`File and Claim records successfully created (${publishParams.name})`);
|
||||
|
||||
return Object.assign({}, claimRecord, { outpoint });
|
||||
await Promise.all([
|
||||
file.setClaim(claim),
|
||||
claim.setFile(file),
|
||||
]);
|
||||
logger.info(`File and Claim records successfully associated (${publishParams.name})`);
|
||||
|
||||
return Object.assign({}, claimRecord, {outpoint});
|
||||
} catch (err) {
|
||||
// parse daemon response when err is a string
|
||||
// this needs work
|
||||
|
@ -70,12 +61,12 @@ const publish = async (publishParams, fileName, fileType) => {
|
|||
if (publishParams.file_path) {
|
||||
await deleteFile(publishParams.file_path);
|
||||
}
|
||||
const message =
|
||||
error.error && error.error.message ? error.error.message : 'Unknown publish error';
|
||||
const message = error.error && error.error.message ? error.error.message : 'Unknown publish error';
|
||||
return {
|
||||
error: true,
|
||||
message,
|
||||
};
|
||||
}
|
||||
};
|
||||
export default publish;
|
||||
|
||||
module.exports = publish;
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import logger from 'winston';
|
||||
const logger = require('winston');
|
||||
|
||||
import { publishing } from '@config/siteConfig.json';
|
||||
const { publishing } = require('@config/siteConfig.json');
|
||||
|
||||
const { fileSizeLimits } = publishing;
|
||||
|
||||
|
@ -35,4 +35,4 @@ const validateFileForPublish = file => {
|
|||
return file;
|
||||
};
|
||||
|
||||
export default validateFileForPublish;
|
||||
module.exports = validateFileForPublish;
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import logger from 'winston';
|
||||
const logger = require('winston');
|
||||
|
||||
const {
|
||||
publishing: { maxSizeImage = 10000000, maxSizeGif = 50000000, maxSizeVideo = 50000000 },
|
||||
|
@ -41,4 +41,4 @@ const validateFileTypeAndSize = file => {
|
|||
return file;
|
||||
};
|
||||
|
||||
export default validateFileTypeAndSize;
|
||||
module.exports = validateFileTypeAndSize;
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { resolveUri } from 'server/lbrynet/index';
|
||||
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
|
||||
const { resolveUri } = require('../../../../lbrynet/index');
|
||||
const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
|
||||
|
||||
/*
|
||||
|
||||
|
@ -17,4 +17,4 @@ const claimResolve = ({ headers, ip, originalUrl, params }, res) => {
|
|||
});
|
||||
};
|
||||
|
||||
export default claimResolve;
|
||||
module.exports = claimResolve;
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
|
||||
import chainquery from 'chainquery';
|
||||
const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
|
||||
const db = require('../../../../models');
|
||||
const chainquery = require('chainquery').default;
|
||||
|
||||
/*
|
||||
|
||||
|
@ -8,18 +9,17 @@ import chainquery from 'chainquery';
|
|||
*/
|
||||
|
||||
const claimShortId = async ({ ip, originalUrl, body, params }, res) => {
|
||||
// TODO: use new sdk partialId features when available
|
||||
try {
|
||||
let shortId = await chainquery.claim.queries
|
||||
.getShortClaimIdFromLongClaimId(params.longId, params.name)
|
||||
.catch(() => {
|
||||
return params.longId;
|
||||
});
|
||||
let shortId = await chainquery.claim.queries.getShortClaimIdFromLongClaimId(params.longId, params.name).catch(() => {});
|
||||
|
||||
res.status(200).json({ success: true, data: shortId });
|
||||
if (!shortId) {
|
||||
shortId = await db.Claim.getShortClaimIdFromLongClaimId(params.longId, params.name);
|
||||
}
|
||||
|
||||
res.status(200).json({success: true, data: shortId});
|
||||
} catch (error) {
|
||||
handleErrorResponse(originalUrl, ip, error, res);
|
||||
}
|
||||
};
|
||||
|
||||
export default claimShortId;
|
||||
module.exports = claimShortId;
|
||||
|
|
|
@ -1,20 +1,19 @@
|
|||
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
|
||||
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');
|
||||
|
||||
/*
|
||||
route to update a claim through the daemon
|
||||
|
@ -70,7 +69,6 @@ const claimUpdate = ({ body, files, headers, ip, originalUrl, user, tor }, res)
|
|||
licenseUrl,
|
||||
name,
|
||||
nsfw,
|
||||
outpoint,
|
||||
thumbnailFileName,
|
||||
thumbnailFilePath,
|
||||
thumbnailFileType,
|
||||
|
@ -107,34 +105,31 @@ const claimUpdate = ({ body, files, headers, ip, originalUrl, user, tor }, res)
|
|||
}
|
||||
|
||||
// check channel authorization
|
||||
//
|
||||
// Assume that if this is an update,
|
||||
// chainquery probably has the claim in mempool
|
||||
// so no cache check needed
|
||||
authenticateUser(channelName, channelId, channelPassword, user)
|
||||
.then(({ channelName, channelClaimId }) => {
|
||||
if (!channelId) {
|
||||
channelId = channelClaimId;
|
||||
}
|
||||
return chainquery.claim.queries.resolveClaimInChannel(name, channelClaimId).then(claim => {
|
||||
outpoint = claim.generated_outpoint;
|
||||
return claim.dataValues;
|
||||
});
|
||||
return chainquery.claim.queries
|
||||
.resolveClaimInChannel(name, channelClaimId)
|
||||
.then(claim => claim.dataValues);
|
||||
})
|
||||
.then(claim => {
|
||||
claimRecord = claim;
|
||||
if (claimRecord.content_type === 'video/mp4' && files.file) {
|
||||
thumbnailUpdate = true;
|
||||
}
|
||||
|
||||
if (!files.file || thumbnailUpdate) {
|
||||
// return Promise.all([
|
||||
// db.File.findOne({ where: { name, claimId: claim.claim_id } }),
|
||||
return getFileListFileByOutpoint(outpoint);
|
||||
// ]);
|
||||
return Promise.all([
|
||||
db.File.findOne({ where: { name, claimId: claim.claim_id } }),
|
||||
resolveUri(`${claim.name}#${claim.claim_id}`),
|
||||
]);
|
||||
}
|
||||
}) // remove fileResult
|
||||
.then(fileListResult => {
|
||||
logger.verbose('fileListResult', fileListResult);
|
||||
|
||||
return [null, null];
|
||||
})
|
||||
.then(([fileResult, resolution]) => {
|
||||
metadata = Object.assign(
|
||||
{},
|
||||
{
|
||||
|
@ -156,6 +151,7 @@ const claimUpdate = ({ body, files, headers, ip, originalUrl, user, tor }, res)
|
|||
channel_id: channelId,
|
||||
metadata,
|
||||
};
|
||||
|
||||
if (files.file) {
|
||||
if (thumbnailUpdate) {
|
||||
// publish new thumbnail
|
||||
|
@ -176,8 +172,8 @@ const claimUpdate = ({ body, files, headers, ip, originalUrl, user, tor }, res)
|
|||
publishParams['file_path'] = filePath;
|
||||
}
|
||||
} else {
|
||||
fileName = fileListResult.file_name;
|
||||
fileType = fileListResult.mime_type;
|
||||
fileName = fileResult.fileName;
|
||||
fileType = fileResult.fileType;
|
||||
publishParams['thumbnail'] = claimRecord.thumbnail_url;
|
||||
}
|
||||
|
||||
|
@ -209,8 +205,6 @@ const claimUpdate = ({ body, files, headers, ip, originalUrl, user, tor }, res)
|
|||
} else {
|
||||
canonicalUrl = createCanonicalLink({ asset: { ...publishResult, shortId } });
|
||||
}
|
||||
publishCache.set(canonicalUrl, publishResult.claimId);
|
||||
publishCache.set(publishResult.claimId, publishResult);
|
||||
|
||||
if (publishResult.error) {
|
||||
res.status(400).json({
|
||||
|
@ -241,4 +235,4 @@ const claimUpdate = ({ body, files, headers, ip, originalUrl, user, tor }, res)
|
|||
});
|
||||
};
|
||||
|
||||
export default claimUpdate;
|
||||
module.exports = claimUpdate;
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
|
||||
import db from 'server/models';
|
||||
const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
|
||||
const db = require('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) => {
|
|||
}
|
||||
};
|
||||
|
||||
export default claimViews;
|
||||
module.exports = claimViews;
|
||||
|
|
|
@ -1,14 +1,12 @@
|
|||
const {
|
||||
publishing: {
|
||||
primaryClaimAddress,
|
||||
uploadDirectory,
|
||||
thumbnailChannel,
|
||||
thumbnailChannelId,
|
||||
additionalClaimAddresses,
|
||||
disabled,
|
||||
disabledMessage,
|
||||
},
|
||||
} = require('@config/siteConfig');
|
||||
const { publishing: {
|
||||
primaryClaimAddress,
|
||||
uploadDirectory,
|
||||
thumbnailChannel,
|
||||
thumbnailChannelId,
|
||||
additionalClaimAddresses,
|
||||
disabled,
|
||||
disabledMessage,
|
||||
} } = require('@config/siteConfig');
|
||||
|
||||
/*
|
||||
|
||||
|
@ -28,4 +26,4 @@ const publishingConfig = (req, res) => {
|
|||
});
|
||||
};
|
||||
|
||||
export default publishingConfig;
|
||||
module.exports = publishingConfig;
|
||||
|
|
|
@ -1,10 +1,9 @@
|
|||
import logger from 'winston';
|
||||
const logger = require('winston');
|
||||
|
||||
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
|
||||
import { getFileListFileByOutpoint } from 'server/lbrynet';
|
||||
const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
|
||||
const { getFileListFileByOutpoint } = require('server/lbrynet');
|
||||
|
||||
import chainquery from 'chainquery';
|
||||
import publishCache from 'server/utils/publishCache';
|
||||
const chainquery = require('chainquery').default;
|
||||
|
||||
/*
|
||||
|
||||
|
@ -12,29 +11,31 @@ import publishCache from 'server/utils/publishCache';
|
|||
|
||||
*/
|
||||
|
||||
const fileAvailability = async ({ ip, originalUrl, params }, res) => {
|
||||
const fileAvailability = ({ ip, originalUrl, params }, res) => {
|
||||
const name = params.name;
|
||||
const claimId = params.claimId;
|
||||
|
||||
let outpoint;
|
||||
|
||||
logger.debug(`fileAvailability params: name:${name} claimId:${claimId}`);
|
||||
try {
|
||||
if (publishCache.get(claimId)) {
|
||||
return res.status(200).json({ success: true, data: true });
|
||||
} else {
|
||||
outpoint = await chainquery.claim.queries.resolveClaim(claimId).generated_outpoint;
|
||||
}
|
||||
logger.debug(`fileAvailability: outpoint: ${outpoint}`);
|
||||
let fileData = getFileListFileByOutpoint(outpoint);
|
||||
if (fileData && fileData[0]) {
|
||||
return res.status(200).json({ success: true, data: true });
|
||||
} else {
|
||||
res.status(200).json({ success: true, data: false });
|
||||
}
|
||||
} catch (error) {
|
||||
handleErrorResponse(originalUrl, ip, error, res);
|
||||
}
|
||||
// TODO: we probably eventually want to check the publishCache for the claimId too,
|
||||
// and shop the outpoint to file_list.
|
||||
return chainquery.claim.queries
|
||||
.resolveClaim(name, claimId)
|
||||
.then(result => {
|
||||
return `${result.dataValues.transaction_hash_id}:${result.dataValues.vout}`;
|
||||
})
|
||||
.then(outpoint => {
|
||||
logger.debug(`fileAvailability: outpoint: ${outpoint}`);
|
||||
return getFileListFileByOutpoint(outpoint);
|
||||
})
|
||||
.then(result => {
|
||||
if (result && result[0]) {
|
||||
return res.status(200).json({ success: true, data: true });
|
||||
} else {
|
||||
res.status(200).json({ success: true, data: false });
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
handleErrorResponse(originalUrl, ip, error, res);
|
||||
});
|
||||
};
|
||||
|
||||
export default fileAvailability;
|
||||
module.exports = fileAvailability;
|
||||
|
|
|
@ -1,13 +1,16 @@
|
|||
import db from 'server/models';
|
||||
const db = require('../../../../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({
|
||||
|
@ -22,4 +25,4 @@ const getChannelData = (channelName, channelClaimId) => {
|
|||
});
|
||||
};
|
||||
|
||||
export default getChannelData;
|
||||
module.exports = getChannelData;
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
|
||||
const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
|
||||
|
||||
import getChannelData from './getChannelData.js';
|
||||
const getChannelData = require('./getChannelData.js');
|
||||
|
||||
const NO_CHANNEL = 'NO_CHANNEL';
|
||||
|
||||
|
@ -32,4 +32,4 @@ const channelData = ({ ip, originalUrl, body, params }, res) => {
|
|||
});
|
||||
};
|
||||
|
||||
export default channelData;
|
||||
module.exports = channelData;
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
import logger from 'winston';
|
||||
import db from 'server/models';
|
||||
import getClaimId from '../../utils/getClaimId';
|
||||
import publishCache from 'server/utils/publishCache';
|
||||
const logger = require('winston');
|
||||
const db = require('../../../models');
|
||||
const getClaimId = require('../../utils/getClaimId');
|
||||
|
||||
import { details } from '@config/siteConfig';
|
||||
const { host, title: siteTitle } = details;
|
||||
const {
|
||||
details: { host, title: siteTitle },
|
||||
} = require('@config/siteConfig');
|
||||
|
||||
const getOEmbedDataForAsset = (channelName, channelClaimId, claimName, claimId) => {
|
||||
let fileData, claimData;
|
||||
|
@ -65,4 +65,4 @@ const getOEmbedDataForAsset = (channelName, channelClaimId, claimName, claimId)
|
|||
});
|
||||
};
|
||||
|
||||
export default getOEmbedDataForAsset;
|
||||
module.exports = getOEmbedDataForAsset;
|
||||
|
|
|
@ -1,26 +1,33 @@
|
|||
import db from 'server/models';
|
||||
import { details } from '@config/siteConfig';
|
||||
const { host, title: siteTitle } = details;
|
||||
const db = require('../../../models');
|
||||
|
||||
const {
|
||||
details: {
|
||||
host,
|
||||
title: siteTitle,
|
||||
},
|
||||
} = require('@config/siteConfig');
|
||||
|
||||
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
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
export default getOEmbedDataForChannel;
|
||||
module.exports = getOEmbedDataForChannel;
|
||||
|
|
|
@ -1,14 +1,12 @@
|
|||
import logger from 'winston';
|
||||
import lbryUri from '@globalutils/lbryUri';
|
||||
const logger = require('winston');
|
||||
const lbryUri = require('../../../../utils/lbryUri');
|
||||
|
||||
import getOEmbedDataForChannel from './getOEmbedDataForChannel';
|
||||
import getOEmbedDataForAsset from './getOEmbedDataForAsset';
|
||||
import parseSpeechUrl from './parseSpeechUrl';
|
||||
const getOEmbedDataForChannel = require('./getOEmbedDataForChannel');
|
||||
const getOEmbedDataForAsset = require('./getOEmbedDataForAsset');
|
||||
const parseSpeechUrl = require('./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);
|
||||
|
||||
|
@ -38,7 +36,7 @@ const getOEmbedData = (req, res) => {
|
|||
return res.status(200).json(data);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
.catch((error) => {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: error,
|
||||
|
@ -56,7 +54,7 @@ const getOEmbedData = (req, res) => {
|
|||
return res.status(200).json(data);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
.catch((error) => {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: error,
|
||||
|
@ -65,4 +63,4 @@ const getOEmbedData = (req, res) => {
|
|||
}
|
||||
};
|
||||
|
||||
export default getOEmbedData;
|
||||
module.exports = getOEmbedData;
|
||||
|
|
|
@ -1,10 +1,17 @@
|
|||
import logger from 'winston';
|
||||
const logger = require('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}`);
|
||||
|
||||
|
@ -14,4 +21,4 @@ const parseSpeechUrl = url => {
|
|||
};
|
||||
};
|
||||
|
||||
export default parseSpeechUrl;
|
||||
module.exports = parseSpeechUrl;
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
|
||||
import db from 'server/models';
|
||||
import getClaimData from 'server/utils/getClaimData';
|
||||
const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
|
||||
const db = require('server/models');
|
||||
const getClaimData = require('server/utils/getClaimData');
|
||||
|
||||
/*
|
||||
|
||||
|
@ -9,22 +9,25 @@ import getClaimData from 'server/utils/getClaimData';
|
|||
*/
|
||||
|
||||
const channelClaims = async ({ ip, originalUrl, body, params }, res) => {
|
||||
const { 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,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
@ -36,4 +39,4 @@ const channelClaims = async ({ ip, originalUrl, body, params }, res) => {
|
|||
handleErrorResponse(originalUrl, ip, 'Feature endpoint not found', res);
|
||||
};
|
||||
|
||||
export default channelClaims;
|
||||
module.exports = channelClaims;
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import logger from 'winston';
|
||||
import db from 'server/models';
|
||||
const logger = require('winston');
|
||||
const db = require('../../../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) => {
|
|||
});
|
||||
};
|
||||
|
||||
export default getTorList;
|
||||
module.exports = getTorList;
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
import { handleErrorResponse } from '../../../utils/errorHandlers.js';
|
||||
import logger from 'winston';
|
||||
import db from 'server/models';
|
||||
import { masterPassword } from '@private/authConfig.json';
|
||||
const { handleErrorResponse } = require('../../../utils/errorHandlers.js');
|
||||
const logger = require('winston');
|
||||
const db = require('../../../../models');
|
||||
const { masterPassword } = require('@private/authConfig.json');
|
||||
/*
|
||||
|
||||
route to update a password
|
||||
|
@ -22,8 +22,7 @@ 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',
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -61,9 +60,9 @@ const updateUserPassword = ({ ip, originalUrl, body }, res) => {
|
|||
newPassword,
|
||||
});
|
||||
})
|
||||
.catch(error => {
|
||||
.catch((error) => {
|
||||
handleErrorResponse(originalUrl, ip, error, res);
|
||||
});
|
||||
};
|
||||
|
||||
export default updateUserPassword;
|
||||
module.exports = updateUserPassword;
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { sendGAServeEvent } from '@serverutils/googleAnalytics';
|
||||
import getClaimIdAndServeAsset from '../utils/getClaimIdAndServeAsset.js';
|
||||
const { sendGAServeEvent } = require('../../../utils/googleAnalytics');
|
||||
const getClaimIdAndServeAsset = require('../utils/getClaimIdAndServeAsset.js');
|
||||
|
||||
/*
|
||||
|
||||
|
@ -14,4 +14,4 @@ const serveAsset = ({ headers, ip, originalUrl, params: { claimName, claimId } }
|
|||
getClaimIdAndServeAsset(null, null, claimName, claimId, originalUrl, ip, res, headers);
|
||||
};
|
||||
|
||||
export default serveAsset;
|
||||
module.exports = serveAsset;
|
||||
|
|
|
@ -1,14 +1,14 @@
|
|||
import logger from 'winston';
|
||||
const logger = require('winston');
|
||||
|
||||
import { sendGAServeEvent } from '@serverutils/googleAnalytics';
|
||||
import handleShowRender from 'server/render/handleShowRender';
|
||||
const { sendGAServeEvent } = require('../../../utils/googleAnalytics');
|
||||
const handleShowRender = require('../../../render/handleShowRender').default;
|
||||
|
||||
import lbryUri from '@globalutils/lbryUri.js';
|
||||
const lbryUri = require('../../../../utils/lbryUri.js');
|
||||
|
||||
import determineRequestType from '../utils/determineRequestType.js';
|
||||
import getClaimIdAndServeAsset from '../utils/getClaimIdAndServeAsset.js';
|
||||
const determineRequestType = require('../utils/determineRequestType.js');
|
||||
const getClaimIdAndServeAsset = require('../utils/getClaimIdAndServeAsset.js');
|
||||
|
||||
import { SHOW } from '../constants/request_types.js';
|
||||
const { SHOW } = require('../constants/request_types.js');
|
||||
|
||||
/*
|
||||
|
||||
|
@ -41,8 +41,8 @@ const serveByClaim = (req, res) => {
|
|||
|
||||
sendGAServeEvent(headers, ip, originalUrl);
|
||||
} catch (error) {
|
||||
return res.status(400).json({ success: false, message: error.message });
|
||||
return res.status(400).json({success: false, message: error.message});
|
||||
}
|
||||
};
|
||||
|
||||
export default serveByClaim;
|
||||
module.exports = serveByClaim;
|
||||
|
|
|
@ -1,15 +1,15 @@
|
|||
import logger from 'winston';
|
||||
const logger = require('winston');
|
||||
|
||||
import { sendGAServeEvent } from 'server/utils/googleAnalytics';
|
||||
import handleShowRender from 'server/render/handleShowRender';
|
||||
const { sendGAServeEvent } = require('../../../utils/googleAnalytics');
|
||||
const handleShowRender = require('../../../render/handleShowRender').default;
|
||||
|
||||
import lbryUri from '@globalutils/lbryUri.js';
|
||||
const lbryUri = require('../../../../utils/lbryUri.js');
|
||||
|
||||
import determineRequestType from '../utils/determineRequestType.js';
|
||||
import getClaimIdAndServeAsset from '../utils/getClaimIdAndServeAsset.js';
|
||||
import flipClaimNameAndId from '../utils/flipClaimNameAndId.js';
|
||||
const determineRequestType = require('../utils/determineRequestType.js');
|
||||
const getClaimIdAndServeAsset = require('../utils/getClaimIdAndServeAsset.js');
|
||||
const flipClaimNameAndId = require('../utils/flipClaimNameAndId.js');
|
||||
|
||||
import { SHOW } from '../constants/request_types.js';
|
||||
const { SHOW } = require('../constants/request_types.js');
|
||||
|
||||
/*
|
||||
|
||||
|
@ -30,9 +30,7 @@ const serverByIdentifierAndClaim = (req, res) => {
|
|||
}
|
||||
|
||||
({ claimName } = lbryUri.parseClaim(params.claim));
|
||||
({ isChannel, channelName, channelClaimId, claimId } = lbryUri.parseIdentifier(
|
||||
params.identifier
|
||||
));
|
||||
({ isChannel, channelName, channelClaimId, claimId } = lbryUri.parseIdentifier(params.identifier));
|
||||
|
||||
if (!isChannel) {
|
||||
[claimId, claimName] = flipClaimNameAndId(claimId, claimName);
|
||||
|
@ -49,21 +47,12 @@ 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});
|
||||
}
|
||||
};
|
||||
|
||||
export default serverByIdentifierAndClaim;
|
||||
module.exports = serverByIdentifierAndClaim;
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import { SERVE, SHOW } from '../constants/request_types.js';
|
||||
const { SERVE, SHOW } = require('../constants/request_types.js');
|
||||
|
||||
function clientWantsAsset({ accept, range }) {
|
||||
function clientWantsAsset ({accept, range}) {
|
||||
const imageIsWanted = accept && accept.match(/image\/.*/) && !accept.match(/text\/html/);
|
||||
const videoIsWanted = accept && accept.match(/video\/.*/) && !accept.match(/text\/html/);
|
||||
return imageIsWanted || videoIsWanted;
|
||||
|
@ -13,4 +13,4 @@ const determineRequestType = (hasFileExtension, headers) => {
|
|||
return SHOW;
|
||||
};
|
||||
|
||||
export default determineRequestType;
|
||||
module.exports = determineRequestType;
|
||||
|
|
|
@ -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];
|
||||
};
|
||||
|
||||
export default flipClaimNameAndId;
|
||||
module.exports = flipClaimNameAndId;
|
||||
|
|
|
@ -1,20 +1,13 @@
|
|||
import logger from 'winston';
|
||||
const logger = require('winston');
|
||||
|
||||
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';
|
||||
const db = require('../../../models');
|
||||
const chainquery = require('chainquery').default;
|
||||
const isApprovedChannel = require('../../../../utils/isApprovedChannel');
|
||||
|
||||
import { publishing } from '@config/siteConfig';
|
||||
const getClaimId = require('../../utils/getClaimId.js');
|
||||
const { handleErrorResponse } = require('../../utils/errorHandlers.js');
|
||||
|
||||
const { serveOnlyApproved, approvedChannels } = publishing;
|
||||
const serveFile = require('./serveFile.js');
|
||||
|
||||
const NO_CHANNEL = 'NO_CHANNEL';
|
||||
const NO_CLAIM = 'NO_CLAIM';
|
||||
|
@ -22,107 +15,118 @@ const BLOCKED_CLAIM = 'BLOCKED_CLAIM';
|
|||
const NO_FILE = 'NO_FILE';
|
||||
const CONTENT_UNAVAILABLE = 'CONTENT_UNAVAILABLE';
|
||||
|
||||
const RETRY_MS = 250;
|
||||
const TIMEOUT_MS = 15000;
|
||||
const MIN_BYTES = 15000000;
|
||||
const {
|
||||
publishing: { serveOnlyApproved, approvedChannels },
|
||||
} = require('@config/siteConfig');
|
||||
|
||||
const getClaimIdAndServeAsset = async (
|
||||
const getClaimIdAndServeAsset = (
|
||||
channelName,
|
||||
channelClaimId,
|
||||
claimName,
|
||||
partialClaimId,
|
||||
claimId,
|
||||
originalUrl,
|
||||
ip,
|
||||
res,
|
||||
headers
|
||||
) => {
|
||||
let outpoint;
|
||||
let channelId;
|
||||
let cqResult;
|
||||
let claimId = '';
|
||||
try {
|
||||
const queryObject = parseQueryString(originalUrl);
|
||||
claimId = await getClaimId(channelName, channelClaimId, claimName, partialClaimId);
|
||||
getClaimId(channelName, channelClaimId, claimName, claimId)
|
||||
.then(fullClaimId => {
|
||||
claimId = fullClaimId;
|
||||
return chainquery.claim.queries.resolveClaim(claimName, fullClaimId).catch(() => {});
|
||||
})
|
||||
.then(claim => {
|
||||
if (!claim) {
|
||||
logger.debug('Full claim id:', claimId);
|
||||
return db.Claim.findOne({
|
||||
where: {
|
||||
name: claimName,
|
||||
claimId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (publishCache.get(claimId)) {
|
||||
outpoint = publishCache.get(claimId).outpoint;
|
||||
channelId = publishCache.get(claimId).certificateId;
|
||||
} else {
|
||||
cqResult = await chainquery.claim.queries.resolveClaim(claimId);
|
||||
if (!cqResult || !cqResult.dataValues) {
|
||||
throw new Error(NO_CLAIM);
|
||||
}
|
||||
outpoint = cqResult.generated_outpoint;
|
||||
channelId = channelClaimId || cqResult.dataValues.publisher_id;
|
||||
}
|
||||
if (serveOnlyApproved && !isApprovedChannel({ longId: channelId }, approvedChannels)) {
|
||||
throw new Error(CONTENT_UNAVAILABLE);
|
||||
}
|
||||
// This throws "BLOCKED_CLAIM" on error
|
||||
await db.Blocked.isNotBlocked(outpoint);
|
||||
return claim;
|
||||
})
|
||||
.then(claim => {
|
||||
let claimDataValues = claim.dataValues;
|
||||
|
||||
let fileListResult = await getFileListFileByOutpoint(outpoint);
|
||||
if (fileListResult && fileListResult[0]) {
|
||||
serveFile(fileListResult[0], res, originalUrl);
|
||||
} else if (!isBot(headers['user-agent'])) {
|
||||
let lbrynetResult = await getClaim(`${claimName}#${claimId}`);
|
||||
if (!lbrynetResult || !lbrynetResult.claim_id) {
|
||||
throw new Error('LBRYNET_NO_GET');
|
||||
if (
|
||||
serveOnlyApproved &&
|
||||
!isApprovedChannel(
|
||||
{ longId: claimDataValues.publisher_id || claimDataValues.certificateId },
|
||||
approvedChannels
|
||||
)
|
||||
) {
|
||||
throw new Error(CONTENT_UNAVAILABLE);
|
||||
}
|
||||
let fileReady = await awaitFileSize(lbrynetResult.outpoint, MIN_BYTES, RETRY_MS, TIMEOUT_MS);
|
||||
if (fileReady !== 'ready') {
|
||||
throw new Error('claim/get: failed to get file after 15 seconds');
|
||||
|
||||
let outpoint =
|
||||
claimDataValues.outpoint ||
|
||||
`${claimDataValues.transaction_hash_id}:${claimDataValues.vout}`;
|
||||
logger.debug('Outpoint:', outpoint);
|
||||
return db.Blocked.isNotBlocked(outpoint).then(() => {
|
||||
// If content was found, is approved, and not blocked - log a view.
|
||||
if (headers && headers['user-agent'] && /LBRY/.test(headers['user-agent']) === false) {
|
||||
db.Views.create({
|
||||
time: Date.now(),
|
||||
isChannel: false,
|
||||
claimId: claimDataValues.claim_id || claimDataValues.claimId,
|
||||
publisherId: claimDataValues.publisher_id || claimDataValues.certificateId,
|
||||
ip,
|
||||
});
|
||||
}
|
||||
});
|
||||
})
|
||||
.then(() => {
|
||||
return db.File.findOne({
|
||||
where: {
|
||||
claimId,
|
||||
name: claimName,
|
||||
},
|
||||
});
|
||||
})
|
||||
.then(fileRecord => {
|
||||
if (!fileRecord) {
|
||||
throw NO_FILE;
|
||||
}
|
||||
serveFile(lbrynetResult, res, originalUrl);
|
||||
}
|
||||
if (
|
||||
(headers && headers['user-agent'] && /LBRY/.test(headers['user-agent']) === false) ||
|
||||
(queryObject && !queryObject.hasOwnProperty('thumbnail'))
|
||||
) {
|
||||
db.Views.create({
|
||||
time: Date.now(),
|
||||
isChannel: false,
|
||||
claimId: claimId,
|
||||
publisherId: channelId,
|
||||
ip,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
if (error === NO_CLAIM) {
|
||||
logger.debug('no claim found');
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'No matching claim id could be found for that url',
|
||||
});
|
||||
}
|
||||
if (error === NO_CHANNEL) {
|
||||
logger.debug('no channel found');
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'No matching channel id could be found for that url',
|
||||
});
|
||||
}
|
||||
if (error === CONTENT_UNAVAILABLE) {
|
||||
logger.debug('unapproved channel');
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'This content is unavailable',
|
||||
});
|
||||
}
|
||||
if (error === BLOCKED_CLAIM) {
|
||||
logger.debug('claim was blocked');
|
||||
return res.status(451).json({
|
||||
success: false,
|
||||
message:
|
||||
'In response to a complaint we received under the US Digital Millennium Copyright Act, we have blocked access to this content from our applications. For more details, see https://lbry.io/faq/dmca',
|
||||
});
|
||||
}
|
||||
if (error === NO_FILE) {
|
||||
logger.debug('no file available');
|
||||
return res.status(307).redirect(`/api/claim/get/${claimName}/${claimId}`);
|
||||
}
|
||||
handleErrorResponse(originalUrl, ip, error, res);
|
||||
}
|
||||
serveFile(fileRecord.dataValues, res, originalUrl);
|
||||
})
|
||||
.catch(error => {
|
||||
if (error === NO_CLAIM) {
|
||||
logger.debug('no claim found');
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'No matching claim id could be found for that url',
|
||||
});
|
||||
}
|
||||
if (error === NO_CHANNEL) {
|
||||
logger.debug('no channel found');
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'No matching channel id could be found for that url',
|
||||
});
|
||||
}
|
||||
if (error === CONTENT_UNAVAILABLE) {
|
||||
logger.debug('unapproved channel');
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'This content is unavailable',
|
||||
});
|
||||
}
|
||||
if (error === BLOCKED_CLAIM) {
|
||||
logger.debug('claim was blocked');
|
||||
return res.status(451).json({
|
||||
success: false,
|
||||
message:
|
||||
'In response to a complaint we received under the US Digital Millennium Copyright Act, we have blocked access to this content from our applications. For more details, see https://lbry.com/faq/dmca',
|
||||
});
|
||||
}
|
||||
if (error === NO_FILE) {
|
||||
logger.debug('no file available');
|
||||
return res.status(307).redirect(`/api/claim/get/${claimName}/${claimId}`);
|
||||
}
|
||||
handleErrorResponse(originalUrl, ip, error, res);
|
||||
});
|
||||
};
|
||||
|
||||
export default getClaimIdAndServeAsset;
|
||||
module.exports = getClaimIdAndServeAsset;
|
||||
|
|
|
@ -1,14 +1,15 @@
|
|||
import db from 'server/models';
|
||||
const db = require('../../../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;
|
||||
});
|
||||
};
|
||||
|
||||
export default getLocalFileRecord;
|
||||
module.exports = getLocalFileRecord;
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import logger from 'winston';
|
||||
const logger = require('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);
|
||||
};
|
||||
|
||||
export default logRequestData;
|
||||
module.exports = logRequestData;
|
||||
|
|
|
@ -1,18 +1,26 @@
|
|||
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 logger = require('winston');
|
||||
const transformImage = require('./transformImage');
|
||||
|
||||
const isValidQueryObject = require('server/utils/isValidQueryObj');
|
||||
const {
|
||||
serving: { dynamicFileSizing },
|
||||
} = require('@config/siteConfig');
|
||||
const { enabled: dynamicEnabled } = dynamicFileSizing;
|
||||
|
||||
const serveFile = async (
|
||||
{ download_path: filePath, mime_type: fileType, total_bytes: totalBytes },
|
||||
res,
|
||||
originalUrl
|
||||
) => {
|
||||
const queryObject = parseQueryString(originalUrl) || {};
|
||||
const serveFile = async ({ filePath, fileType }, res, originalUrl) => {
|
||||
const queryObject = {};
|
||||
// TODO: replace quick/dirty try catch with better practice
|
||||
try {
|
||||
originalUrl
|
||||
.split('?')[1]
|
||||
.split('&')
|
||||
.map(pair => {
|
||||
if (pair.includes('=')) {
|
||||
let parr = pair.split('=');
|
||||
queryObject[parr[0]] = parr[1];
|
||||
} else queryObject[pair] = true;
|
||||
});
|
||||
} catch (e) {}
|
||||
|
||||
if (!fileType) {
|
||||
logger.error(`no fileType provided for ${filePath}`);
|
||||
|
@ -57,4 +65,4 @@ const serveFile = async (
|
|||
}
|
||||
};
|
||||
|
||||
export default serveFile;
|
||||
module.exports = serveFile;
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
import gm from 'gm';
|
||||
import logger from 'winston';
|
||||
import { getImageHeightAndWidth } from '@serverutils/imageProcessing';
|
||||
const gm = require('gm');
|
||||
const logger = require('winston');
|
||||
const imageMagick = gm.subClass({ imageMagick: true });
|
||||
const { getImageHeightAndWidth } = require('../../../utils/imageProcessing');
|
||||
|
||||
export default function transformImage(path, queryObj) {
|
||||
module.exports = function transformImage(path, queryObj) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let { h: cHeight = null } = queryObj;
|
||||
let { w: cWidth = null } = queryObj;
|
||||
|
@ -39,7 +39,7 @@ export default function transformImage(path, queryObj) {
|
|||
reject(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
function _cropCenter(path, cropWidth, cropHeight, originalWidth, originalHeight) {
|
||||
let oAspect = originalWidth / originalHeight;
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import speechPassport from 'server/speechPassport/index';
|
||||
const speechPassport = require('../../../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);
|
||||
};
|
||||
|
||||
export default login;
|
||||
module.exports = login;
|
||||
|
|
|
@ -7,4 +7,4 @@ const logout = (req, res) => {
|
|||
res.status(200).json(responseObject);
|
||||
};
|
||||
|
||||
export default logout;
|
||||
module.exports = logout;
|
||||
|
|
|
@ -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,
|
||||
});
|
||||
};
|
||||
|
||||
export default signup;
|
||||
module.exports = signup;
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
const user = (req, res) => {
|
||||
const responseObject = {
|
||||
success: true,
|
||||
data: req.user,
|
||||
data : req.user,
|
||||
};
|
||||
res.status(200).json(responseObject);
|
||||
};
|
||||
|
||||
export default user;
|
||||
module.exports = user;
|
||||
|
|
|
@ -1,40 +1,42 @@
|
|||
import { assetDefaults, details } from '@config/siteConfig';
|
||||
const { thumbnail } = assetDefaults;
|
||||
const { host } = details;
|
||||
const {
|
||||
assetDefaults: { thumbnail },
|
||||
details: { host },
|
||||
} = require('@config/siteConfig');
|
||||
|
||||
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;
|
||||
|
@ -62,7 +64,11 @@ 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(':')) {
|
||||
|
@ -80,4 +86,4 @@ const sendVideoEmbedPage = async ({ params }, res) => {
|
|||
res.status(200).render('embed', { host, claimId, name, logoConfig });
|
||||
};
|
||||
|
||||
export default sendVideoEmbedPage;
|
||||
module.exports = sendVideoEmbedPage;
|
||||
|
|
|
@ -1,44 +1,45 @@
|
|||
import logger from 'winston';
|
||||
const logger = require('winston');
|
||||
|
||||
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;
|
||||
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
|
||||
} else {
|
||||
message = error;
|
||||
status = 400;
|
||||
if (error.message) {
|
||||
message = error.message;
|
||||
} else {
|
||||
message = error;
|
||||
}
|
||||
}
|
||||
}
|
||||
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,
|
||||
};
|
||||
}
|
||||
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,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
|
|
@ -1,25 +1,23 @@
|
|||
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 logger = require('winston');
|
||||
|
||||
const db = require('../../models');
|
||||
const chainquery = require('chainquery').default;
|
||||
|
||||
const getClaimIdByChannel = async (channelName, channelClaimId, claimName) => {
|
||||
logger.debug(`getClaimIdByChannel(${channelName}, ${channelClaimId}, ${claimName})`);
|
||||
const canonicalUrl = createCanonicalLink({
|
||||
asset: { channelName, channelShortId: channelClaimId, name: claimName },
|
||||
});
|
||||
|
||||
let channelId = await chainquery.claim.queries.getLongClaimId(channelName, channelClaimId);
|
||||
|
||||
if (channelId === null) {
|
||||
channelId = await db.Certificate.getLongChannelId(channelName, channelClaimId);
|
||||
}
|
||||
|
||||
const claimId = publishCache.get(canonicalUrl)
|
||||
? publishCache.get(canonicalUrl)
|
||||
: await chainquery.claim.queries.getClaimIdByLongChannelId(channelId, claimName);
|
||||
// TODO: Revisit with sdk-provided partialIds
|
||||
logger.debug(`getClaimIdByChannel returns`, claimId);
|
||||
let claimId = await chainquery.claim.queries.getClaimIdByLongChannelId(channelId, claimName);
|
||||
|
||||
if (claimId === null) {
|
||||
claimId = db.Claim.getClaimIdByLongChannelId(channelId, claimName);
|
||||
}
|
||||
|
||||
return claimId;
|
||||
};
|
||||
|
||||
|
@ -28,12 +26,14 @@ const getClaimId = async (channelName, channelClaimId, name, claimId) => {
|
|||
if (channelName) {
|
||||
return getClaimIdByChannel(channelName, channelClaimId, name);
|
||||
} else {
|
||||
const canonicalUrl = createCanonicalLink({ asset: { name: name, claimId } });
|
||||
let claimIdResult = publishCache.get(canonicalUrl)
|
||||
? publishCache.get(canonicalUrl)
|
||||
: await chainquery.claim.queries.getLongClaimId(name, claimId);
|
||||
let claimIdResult = await chainquery.claim.queries.getLongClaimId(name, claimId);
|
||||
|
||||
if (!claimIdResult) {
|
||||
claimIdResult = await db.Claim.getLongClaimId(name, claimId);
|
||||
}
|
||||
|
||||
return claimIdResult;
|
||||
}
|
||||
};
|
||||
|
||||
export default getClaimId;
|
||||
module.exports = getClaimId;
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
const redirect = route => {
|
||||
const redirect = (route) => {
|
||||
return (req, res) => {
|
||||
res.status(301).redirect(route);
|
||||
};
|
||||
};
|
||||
|
||||
export default redirect;
|
||||
module.exports = redirect;
|
||||
|
|
|
@ -1,33 +1,36 @@
|
|||
// load modules
|
||||
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';
|
||||
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');
|
||||
|
||||
// load local modules
|
||||
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 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 {
|
||||
const {
|
||||
logMetricsMiddleware,
|
||||
setRouteDataInContextMiddleware,
|
||||
} from './middleware/logMetricsMiddleware';
|
||||
import { sessionKey } from '@private/authConfig.json';
|
||||
import { details, startup } from '@config/siteConfig';
|
||||
const { port: PORT, blockListEndpoint } = details;
|
||||
const { performChecks, performUpdates } = startup;
|
||||
} = require('./middleware/logMetricsMiddleware');
|
||||
|
||||
const {
|
||||
details: { port: PORT, blockListEndpoint },
|
||||
startup: { performChecks, performUpdates },
|
||||
} = require('@config/siteConfig');
|
||||
|
||||
const { sessionKey } = require('@private/authConfig.json');
|
||||
|
||||
// configure.js doesn't handle new keys in config.json files yet. Make sure it doens't break.
|
||||
let finalBlockListEndpoint;
|
||||
|
@ -243,4 +246,4 @@ function Server() {
|
|||
};
|
||||
}
|
||||
|
||||
export default Server;
|
||||
module.exports = Server;
|
||||
|
|
|
@ -1,209 +1,212 @@
|
|||
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';
|
||||
|
||||
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');
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function getClaim(uri) {
|
||||
logger.debug(`lbryApi >> Getting Claim for "${uri}"`);
|
||||
const gaStartTime = Date.now();
|
||||
return new Promise((resolve, reject) => {
|
||||
axios
|
||||
.post(lbrynetUri, {
|
||||
method: 'get',
|
||||
params: {
|
||||
uri,
|
||||
timeout: getTimeout || 30,
|
||||
},
|
||||
})
|
||||
.then(response => {
|
||||
sendGATimingEvent('lbrynet', 'getClaim', 'GET', gaStartTime, Date.now());
|
||||
handleLbrynetResponse(response, resolve, reject);
|
||||
})
|
||||
.catch(error => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function abandonClaim({ claimId }) {
|
||||
logger.debug(`lbryApi >> Abandon claim "${claimId}"`);
|
||||
const gaStartTime = Date.now();
|
||||
try {
|
||||
const abandon = await axios.post(lbrynetUri, {
|
||||
method: 'claim_abandon',
|
||||
params: { claim_id: claimId },
|
||||
});
|
||||
sendGATimingEvent('lbrynet', 'abandonClaim', 'ABANDON_CLAIM', gaStartTime, Date.now());
|
||||
return abandon.data;
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
export function getFileListFileByOutpoint(outpoint) {
|
||||
logger.debug(`lbryApi >> Getting File_List for "${outpoint}"`);
|
||||
const gaStartTime = Date.now();
|
||||
return new Promise((resolve, reject) => {
|
||||
axios
|
||||
.post(lbrynetUri, {
|
||||
method: 'file_list',
|
||||
params: {
|
||||
outpoint,
|
||||
},
|
||||
})
|
||||
.then(response => {
|
||||
sendGATimingEvent('lbrynet', 'getFileList', 'FILE_LIST', gaStartTime, Date.now());
|
||||
handleLbrynetResponse(response, resolve, reject);
|
||||
})
|
||||
.catch(error => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function getClaimList(claimName) {
|
||||
logger.debug(`lbryApi >> Getting claim_list for "${claimName}"`);
|
||||
const gaStartTime = Date.now();
|
||||
return new Promise((resolve, reject) => {
|
||||
axios
|
||||
.post(lbrynetUri, {
|
||||
method: 'claim_list',
|
||||
params: { name: claimName },
|
||||
})
|
||||
.then(response => {
|
||||
sendGATimingEvent('lbrynet', 'getClaimList', 'CLAIM_LIST', gaStartTime, Date.now());
|
||||
handleLbrynetResponse(response, resolve, reject);
|
||||
})
|
||||
.catch(error => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
export function resolveUri(uri) {
|
||||
logger.debug(`lbryApi >> Resolving URI for "${uri}"`);
|
||||
const gaStartTime = Date.now();
|
||||
return new Promise((resolve, reject) => {
|
||||
axios
|
||||
.post(lbrynetUri, {
|
||||
method: 'resolve',
|
||||
params: { urls: uri },
|
||||
})
|
||||
.then(({ data }) => {
|
||||
sendGATimingEvent('lbrynet', 'resolveUri', 'RESOLVE', gaStartTime, Date.now());
|
||||
if (Object.keys(data.result).length === 0 && data.result.constructor === Object) {
|
||||
// workaround for daemon returning empty result object
|
||||
// https://github.com/lbryio/lbry/issues/1485
|
||||
db.Claim.findOne({ where: { claimId: uri.split('#')[1] } })
|
||||
.then(() => reject('This claim has not yet been confirmed on the LBRY blockchain'))
|
||||
.catch(() => reject(`Claim ${uri} does not exist`));
|
||||
} else if (data.result[uri].error) {
|
||||
// check for errors
|
||||
reject(data.result[uri].error);
|
||||
} else {
|
||||
// if no errors, resolve
|
||||
resolve(data.result[uri]);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
export function getDownloadDirectory() {
|
||||
logger.debug('lbryApi >> Retrieving the download directory path from lbry daemon...');
|
||||
const gaStartTime = Date.now();
|
||||
return new Promise((resolve, reject) => {
|
||||
axios
|
||||
.post(lbrynetUri, {
|
||||
method: 'settings_get',
|
||||
})
|
||||
.then(({ data }) => {
|
||||
sendGATimingEvent(
|
||||
'lbrynet',
|
||||
'getDownloadDirectory',
|
||||
'SETTINGS_GET',
|
||||
gaStartTime,
|
||||
Date.now()
|
||||
);
|
||||
if (data.result) {
|
||||
resolve(data.result.download_directory);
|
||||
} else {
|
||||
return new Error(
|
||||
'Successfully connected to lbry daemon, but unable to retrieve the download directory.'
|
||||
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()
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
logger.error('Lbrynet Error:', error);
|
||||
resolve('/home/lbry/Downloads/');
|
||||
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 },
|
||||
});
|
||||
});
|
||||
}
|
||||
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);
|
||||
});
|
||||
});
|
||||
}
|
||||
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);
|
||||
});
|
||||
});
|
||||
},
|
||||
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()
|
||||
);
|
||||
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);
|
||||
});
|
||||
});
|
||||
},
|
||||
};
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import logger from 'winston';
|
||||
const logger = require('winston');
|
||||
|
||||
export const handleLbrynetResponse = ({ data }, resolve, reject) => {
|
||||
const handleLbrynetResponse = ({ data }, resolve, reject) => {
|
||||
logger.debug('lbry api data:', data);
|
||||
if (data) {
|
||||
// check for an error
|
||||
|
@ -15,3 +15,5 @@ export const handleLbrynetResponse = ({ data }, resolve, reject) => {
|
|||
// fallback in case it just timed out
|
||||
reject(JSON.stringify(data));
|
||||
};
|
||||
|
||||
module.exports = handleLbrynetResponse;
|
||||
|
|
|
@ -1,8 +1,9 @@
|
|||
import fs from 'fs';
|
||||
const fs = require('fs');
|
||||
|
||||
import logger from 'winston';
|
||||
import { publishing } from '@config/siteConfig';
|
||||
const { publishingChannelWhitelist } = publishing;
|
||||
const logger = require('winston');
|
||||
const {
|
||||
publishing: { publishingChannelWhitelist },
|
||||
} = require('@config/siteConfig');
|
||||
const ipBanFile = './site/config/ipBan.txt';
|
||||
const forbiddenMessage =
|
||||
'<h1>Forbidden</h1>If you are seeing this by mistake, please contact us using <a href="https://chat.lbry.com/">https://chat.lbry.com/</a>';
|
||||
|
@ -22,7 +23,7 @@ if (fs.existsSync(ipBanFile)) {
|
|||
});
|
||||
}
|
||||
|
||||
export const autoblockPublishMiddleware = (req, res, next) => {
|
||||
const autoblockPublishMiddleware = (req, res, next) => {
|
||||
let ip = (req.headers['x-forwarded-for'] || req.connection.remoteAddress).split(/,\s?/)[0];
|
||||
|
||||
if (blockedAddresses.indexOf(ip) !== -1) {
|
||||
|
@ -55,7 +56,7 @@ export const autoblockPublishMiddleware = (req, res, next) => {
|
|||
}
|
||||
};
|
||||
|
||||
export const autoblockPublishBodyMiddleware = (req, res, next) => {
|
||||
const autoblockPublishBodyMiddleware = (req, res, next) => {
|
||||
if (req.body && publishingChannelWhitelist) {
|
||||
let ip = (req.headers['x-forwarded-for'] || req.connection.remoteAddress).split(/,\s?/)[0];
|
||||
const { channelName } = req.body;
|
||||
|
@ -66,3 +67,8 @@ export const autoblockPublishBodyMiddleware = (req, res, next) => {
|
|||
}
|
||||
next();
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
autoblockPublishMiddleware,
|
||||
autoblockPublishBodyMiddleware,
|
||||
};
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
import logger from 'winston';
|
||||
import db from '../models';
|
||||
import httpContext from 'express-http-context';
|
||||
const logger = require('winston');
|
||||
const db = require('../models');
|
||||
const httpContext = require('express-http-context');
|
||||
|
||||
export function logMetricsMiddleware(req, res, next) {
|
||||
function logMetricsMiddleware (req, res, next) {
|
||||
res.on('finish', () => {
|
||||
const userAgent = req.get('user-agent');
|
||||
const routePath = httpContext.get('routePath');
|
||||
|
@ -26,15 +26,15 @@ export 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,10 +43,15 @@ export function logMetricsMiddleware(req, res, next) {
|
|||
next();
|
||||
}
|
||||
|
||||
export function setRouteDataInContextMiddleware(routePath, routeData) {
|
||||
return function(req, res, next) {
|
||||
function setRouteDataInContextMiddleware (routePath, routeData) {
|
||||
return function (req, res, next) {
|
||||
httpContext.set('routePath', routePath);
|
||||
httpContext.set('routeData', routeData);
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
logMetricsMiddleware,
|
||||
setRouteDataInContextMiddleware,
|
||||
};
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
import multipart from 'connect-multiparty';
|
||||
import { publishing } from '@config/siteConfig';
|
||||
const { uploadDirectory } = publishing;
|
||||
const multipartMiddleware = multipart({ uploadDir: uploadDirectory });
|
||||
const multipart = require('connect-multiparty');
|
||||
const { publishing: { uploadDirectory } } = require('@config/siteConfig');
|
||||
const multipartMiddleware = multipart({uploadDir: uploadDirectory});
|
||||
|
||||
export default multipartMiddleware;
|
||||
module.exports = multipartMiddleware;
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
import logger from 'winston';
|
||||
const logger = require('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();
|
||||
};
|
||||
export default requestLogger;
|
||||
|
||||
module.exports = requestLogger;
|
||||
|
|
|
@ -1,22 +1,22 @@
|
|||
import logger from 'winston';
|
||||
import db from 'server/models';
|
||||
const logger = require('winston');
|
||||
const db = require('../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,4 +27,5 @@ const torCheck = (req, res, next) => {
|
|||
logger.error(error);
|
||||
});
|
||||
};
|
||||
export default torCheck;
|
||||
|
||||
module.exports = torCheck;
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
import logger from 'winston';
|
||||
const logger = require('winston');
|
||||
const BLOCKED_CLAIM = 'BLOCKED_CLAIM';
|
||||
|
||||
export default (sequelize, { STRING }) => {
|
||||
module.exports = (sequelize, { STRING }) => {
|
||||
const Blocked = sequelize.define(
|
||||
'Blocked',
|
||||
{
|
||||
outpoint: {
|
||||
type: STRING,
|
||||
type : STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
},
|
||||
|
@ -15,16 +15,15 @@ export default (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({
|
||||
|
@ -45,7 +44,7 @@ export default (sequelize, { STRING }) => {
|
|||
});
|
||||
};
|
||||
|
||||
Blocked.refreshTable = function(blockEndpoint) {
|
||||
Blocked.refreshTable = function (blockEndpoint) {
|
||||
let blockedList = [];
|
||||
|
||||
return fetch(blockEndpoint)
|
||||
|
|
|
@ -1,98 +1,98 @@
|
|||
import logger from 'winston';
|
||||
import returnShortId from './utils/returnShortId';
|
||||
const logger = require('winston');
|
||||
const returnShortId = require('./utils/returnShortId.js');
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => {
|
||||
module.exports = (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,13 +109,14 @@ export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => {
|
|||
});
|
||||
};
|
||||
|
||||
Certificate.getShortChannelIdFromLongChannelId = function(longChannelId, channelName) {
|
||||
Certificate.getShortChannelIdFromLongChannelId = function (longChannelId, channelName) {
|
||||
logger.debug(`getShortChannelIdFromLongChannelId ${channelName}:${longChannelId}`);
|
||||
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:
|
||||
|
@ -130,11 +131,11 @@ export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => {
|
|||
});
|
||||
};
|
||||
|
||||
Certificate.validateLongChannelId = function(name, claimId) {
|
||||
Certificate.validateLongChannelId = function (name, claimId) {
|
||||
logger.debug(`validateLongChannelId(${name}, ${claimId})`);
|
||||
return new Promise((resolve, reject) => {
|
||||
this.findOne({
|
||||
where: { name, claimId },
|
||||
where: {name, claimId},
|
||||
})
|
||||
.then(result => {
|
||||
if (!result) {
|
||||
|
@ -149,18 +150,19 @@ export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => {
|
|||
});
|
||||
};
|
||||
|
||||
Certificate.getLongChannelIdFromShortChannelId = function(channelName, channelClaimId) {
|
||||
Certificate.getLongChannelIdFromShortChannelId = function (channelName, channelClaimId) {
|
||||
logger.debug(`getLongChannelIdFromShortChannelId(${channelName}, ${channelClaimId})`);
|
||||
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:
|
||||
|
@ -176,13 +178,14 @@ export default (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:
|
||||
|
@ -198,7 +201,7 @@ export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => {
|
|||
});
|
||||
};
|
||||
|
||||
Certificate.getLongChannelId = function(channelName, channelClaimId) {
|
||||
Certificate.getLongChannelId = function (channelName, channelClaimId) {
|
||||
logger.debug(`getLongChannelId(${channelName}, ${channelClaimId})`);
|
||||
if (isLongChannelId(channelClaimId)) {
|
||||
return this.validateLongChannelId(channelName, channelClaimId);
|
||||
|
|
|
@ -1,13 +1,13 @@
|
|||
export default (sequelize, { STRING }) => {
|
||||
module.exports = (sequelize, { STRING }) => {
|
||||
const Channel = sequelize.define(
|
||||
'Channel',
|
||||
{
|
||||
channelName: {
|
||||
type: STRING,
|
||||
type : STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
channelClaimId: {
|
||||
type: STRING,
|
||||
type : STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
},
|
||||
|
|
|
@ -1,10 +1,13 @@
|
|||
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 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');
|
||||
|
||||
const NO_CLAIM = 'NO_CLAIM';
|
||||
|
||||
|
@ -50,7 +53,7 @@ function isShortClaimId(claimId) {
|
|||
return claimId && claimId.length < 40;
|
||||
}
|
||||
|
||||
export default (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => {
|
||||
module.exports = (sequelize, { STRING, BOOLEAN, INTEGER, TEXT, DECIMAL }) => {
|
||||
const Claim = sequelize.define(
|
||||
'Claim',
|
||||
{
|
||||
|
|
|
@ -1,35 +1,35 @@
|
|||
export default (sequelize, { STRING, BOOLEAN, INTEGER }) => {
|
||||
module.exports = (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: {
|
||||
|
|
|
@ -1,18 +1,22 @@
|
|||
import Sequelize from 'sequelize';
|
||||
import logger from 'winston';
|
||||
const Sequelize = require('sequelize');
|
||||
const logger = require('winston');
|
||||
|
||||
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 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 { database, username, password } from '@config/mysqlConfig';
|
||||
const {
|
||||
database,
|
||||
username,
|
||||
password,
|
||||
} = require('@config/mysqlConfig');
|
||||
|
||||
if (!database || !username || !password) {
|
||||
logger.warn('missing database, user, or password from mysqlConfig');
|
||||
|
@ -20,16 +24,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,
|
||||
|
@ -73,24 +77,23 @@ 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;
|
||||
});
|
||||
};
|
||||
|
||||
export default db;
|
||||
module.exports = db;
|
||||
|
|
|
@ -1,51 +1,51 @@
|
|||
export default (sequelize, { BOOLEAN, DATE, STRING }) => {
|
||||
module.exports = (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'],
|
||||
},
|
||||
|
|
|
@ -1,17 +1,16 @@
|
|||
import logger from 'winston';
|
||||
import { details } from '@config/siteConfig';
|
||||
const { ipAddress } = details;
|
||||
const logger = require('winston');
|
||||
const { details: { ipAddress } } = require('@config/siteConfig');
|
||||
|
||||
export default (sequelize, { STRING }) => {
|
||||
module.exports = (sequelize, { STRING }) => {
|
||||
const Tor = sequelize.define(
|
||||
'Tor',
|
||||
{
|
||||
address: {
|
||||
type: STRING,
|
||||
type : STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
fingerprint: {
|
||||
type: STRING,
|
||||
type : STRING,
|
||||
allowNull: true,
|
||||
},
|
||||
},
|
||||
|
@ -20,7 +19,7 @@ export default (sequelize, { STRING }) => {
|
|||
}
|
||||
);
|
||||
|
||||
Tor.refreshTable = function() {
|
||||
Tor.refreshTable = function () {
|
||||
let torList = [];
|
||||
return fetch(`https://check.torproject.org/api/bulk?ip=${ipAddress}&port=80`)
|
||||
.then(response => {
|
||||
|
@ -31,7 +30,7 @@ export default (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,
|
||||
});
|
||||
}
|
||||
|
@ -48,7 +47,7 @@ export default (sequelize, { STRING }) => {
|
|||
// return the new table
|
||||
return this.findAll({
|
||||
attributes: ['address', 'fingerprint'],
|
||||
raw: true,
|
||||
raw : true,
|
||||
});
|
||||
})
|
||||
.catch(error => {
|
||||
|
|
|
@ -1,48 +1,47 @@
|
|||
import chainquery from 'chainquery';
|
||||
const chainquery = require('chainquery').default;
|
||||
|
||||
export default (sequelize, { BOOLEAN, DATE, FLOAT, INTEGER, STRING }) => {
|
||||
module.exports = (sequelize, { BOOLEAN, DATE, FLOAT, INTEGER, STRING }) => {
|
||||
const Trending = sequelize.define(
|
||||
'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'],
|
||||
},
|
||||
|
@ -53,15 +52,16 @@ export default (sequelize, { BOOLEAN, DATE, FLOAT, INTEGER, STRING }) => {
|
|||
}
|
||||
);
|
||||
|
||||
Trending.getTrendingWeightData = async ({ hours = 2, minutes = 0, limit = 20 } = {}) => {
|
||||
Trending.getTrendingWeightData = async ({
|
||||
hours = 2,
|
||||
minutes = 0,
|
||||
limit = 20,
|
||||
} = {}) => {
|
||||
let time = new Date();
|
||||
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 @@ export default (sequelize, { BOOLEAN, DATE, FLOAT, INTEGER, STRING }) => {
|
|||
},
|
||||
});
|
||||
|
||||
return claimData.map(claimData => {
|
||||
return claimData.map((claimData) => {
|
||||
return Object.assign(trendingClaims[claimData.claim_id], claimData.dataValues);
|
||||
});
|
||||
};
|
||||
|
|
|
@ -1,17 +1,17 @@
|
|||
'use strict';
|
||||
import bcrypt from 'bcrypt';
|
||||
import logger from 'winston';
|
||||
const bcrypt = require('bcrypt');
|
||||
const logger = require('winston');
|
||||
|
||||
export default (sequelize, { STRING }) => {
|
||||
module.exports = (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 @@ export default (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,7 +46,8 @@ export default (sequelize, { STRING }) => {
|
|||
return;
|
||||
}
|
||||
// replace the current password with the new hash
|
||||
this.update({ password: hash })
|
||||
this
|
||||
.update({password: hash})
|
||||
.then(() => {
|
||||
resolve();
|
||||
})
|
||||
|
|
|
@ -1,37 +1,44 @@
|
|||
import db from 'server/models';
|
||||
const db = require('../index.js');
|
||||
|
||||
export const createClaimRecordDataAfterPublish = (
|
||||
certificateId,
|
||||
channelName,
|
||||
fileName,
|
||||
fileType,
|
||||
publishParams,
|
||||
publishResults
|
||||
) => {
|
||||
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,
|
||||
};
|
||||
});
|
||||
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,
|
||||
};
|
||||
|
|
|
@ -1,15 +1,14 @@
|
|||
import Sequelize from 'sequelize';
|
||||
import { database, username, password } from '@config/mysqlConfig';
|
||||
const Sequelize = require('sequelize');
|
||||
const {database, username, password} = require('@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();
|
||||
})
|
||||
|
@ -19,4 +18,4 @@ const createDatabaseIfNotExists = () => {
|
|||
});
|
||||
};
|
||||
|
||||
export default createDatabaseIfNotExists;
|
||||
module.exports = createDatabaseIfNotExists;
|
||||
|
|
|
@ -1,11 +1,22 @@
|
|||
import getMediaDimensions from 'server/utils/getMediaDimensions.js';
|
||||
const getMediaDimensions = require('../../utils/getMediaDimensions.js');
|
||||
|
||||
export async function createFileRecordDataAfterGet(resolveResult, getResult) {
|
||||
const { name, claimId, outpoint, contentType: fileType } = resolveResult;
|
||||
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,
|
||||
|
@ -19,17 +30,22 @@ export async function createFileRecordDataAfterGet(resolveResult, getResult) {
|
|||
};
|
||||
}
|
||||
|
||||
export async function createFileRecordDataAfterPublish(
|
||||
fileName,
|
||||
fileType,
|
||||
publishParams,
|
||||
publishResults
|
||||
) {
|
||||
const { name, file_path: filePath } = publishParams;
|
||||
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,
|
||||
|
@ -42,3 +58,8 @@ export async function createFileRecordDataAfterPublish(
|
|||
fileType,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createFileRecordDataAfterGet,
|
||||
createFileRecordDataAfterPublish,
|
||||
};
|
||||
|
|
|
@ -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;
|
||||
};
|
||||
|
||||
export default returnShortId;
|
||||
module.exports = returnShortId;
|
||||
|
|
|
@ -1,36 +1,36 @@
|
|||
import chai from 'chai';
|
||||
const chai = require('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');
|
||||
|
|
|
@ -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,10 +17,12 @@ 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));
|
||||
};
|
||||
|
||||
export const getInformationFromValues = numArr => {
|
||||
const getInformationFromValues = (numArr) => {
|
||||
let mean = getMean(numArr);
|
||||
|
||||
return {
|
||||
|
@ -29,10 +31,9 @@ export const getInformationFromValues = numArr => {
|
|||
};
|
||||
};
|
||||
|
||||
export const getZScore = (value, mean, sDeviation) =>
|
||||
sDeviation !== 0 ? (value - mean) / sDeviation : 0;
|
||||
const getZScore = (value, mean, sDeviation) => (sDeviation !== 0 ? (value - mean) / sDeviation : 0);
|
||||
|
||||
export const getFastPValue = zScore => {
|
||||
const getFastPValue = (zScore) => {
|
||||
if (zScore <= MIN_P) {
|
||||
return 0;
|
||||
}
|
||||
|
@ -46,10 +47,7 @@ export 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;
|
||||
|
@ -59,4 +57,11 @@ export const getFastPValue = zScore => {
|
|||
return sum;
|
||||
};
|
||||
|
||||
export const getWeight = (zScore, pValue) => zScore * pValue;
|
||||
const getWeight = (zScore, pValue) => (zScore * pValue);
|
||||
|
||||
module.exports = {
|
||||
getInformationFromValues,
|
||||
getZScore,
|
||||
getFastPValue,
|
||||
getWeight,
|
||||
};
|
||||
|
|
|
@ -1,32 +1,32 @@
|
|||
export default (sequelize, { BOOLEAN, DATE, STRING }) => {
|
||||
module.exports = (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 @@ export default (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 @@ export default (sequelize, { BOOLEAN, DATE, STRING }) => {
|
|||
);
|
||||
};
|
||||
|
||||
Views.getGetUniqueViewsbByClaimId = claimId => {
|
||||
Views.getGetUniqueViewsbByClaimId = (claimId) => {
|
||||
return Views.count({
|
||||
where: {
|
||||
claimId,
|
||||
},
|
||||
distinct: true,
|
||||
col: 'ip',
|
||||
col : 'ip',
|
||||
});
|
||||
};
|
||||
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
import md5File from 'md5-file';
|
||||
import path from 'path';
|
||||
const md5File = require('md5-file');
|
||||
const path = require('path');
|
||||
|
||||
const bundlePath = path.resolve('./public/bundle/bundle.js');
|
||||
const bundleHash = md5File.sync(bundlePath);
|
||||
const shortBundleHash = bundleHash.substring(0, 4);
|
||||
|
||||
export default (helmet, html, preloadedState) => {
|
||||
module.exports = (helmet, html, preloadedState) => {
|
||||
// take the html and preloadedState and return the full page
|
||||
return `
|
||||
<!DOCTYPE html>
|
||||
|
|
|
@ -1,87 +1,65 @@
|
|||
// middleware
|
||||
import multipartMiddleware from 'server/middleware/multipartMiddleware';
|
||||
import torCheckMiddleware from 'server/middleware/torCheckMiddleware';
|
||||
const { autoblockPublishMiddleware, autoblockPublishBodyMiddleware } = require('../../middleware/autoblockPublishMiddleware');
|
||||
const multipartMiddleware = require('../../middleware/multipartMiddleware');
|
||||
const torCheckMiddleware = require('../../middleware/torCheckMiddleware');
|
||||
// route handlers
|
||||
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');
|
||||
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');
|
||||
|
||||
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 ] },
|
||||
};
|
||||
|
|
|
@ -1,19 +1,11 @@
|
|||
import serveByClaim from 'server/controllers/assets/serveByClaim';
|
||||
import serveByIdentifierAndClaim from 'server/controllers/assets/serveByIdentifierAndClaim';
|
||||
const serveByClaim = require('../../controllers/assets/serveByClaim');
|
||||
const serveByIdentifierAndClaim = require('../../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 },
|
||||
};
|
||||
|
|
|
@ -1,15 +1,12 @@
|
|||
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';
|
||||
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');
|
||||
|
||||
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 },
|
||||
};
|
||||
|
|
|
@ -1,25 +1,21 @@
|
|||
import handlePageRequest from '../../controllers/pages/sendReactApp';
|
||||
import handleVideoEmbedRequest from '../../controllers/pages/sendVideoEmbedPage';
|
||||
import redirect from '../../controllers/utils/redirect';
|
||||
const handleVideoEmbedRequest = require('../../controllers/pages/sendVideoEmbedPage');
|
||||
const redirect = require('../../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
|
||||
};
|
||||
|
|
|
@ -1,12 +1,12 @@
|
|||
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';
|
||||
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');
|
||||
|
||||
passport.deserializeUser(deserializeUser);
|
||||
passport.serializeUser(serializeUser);
|
||||
passport.use('local-login', localLoginStrategy);
|
||||
passport.use('local-signup', localSignupStrategy);
|
||||
|
||||
export default passport;
|
||||
module.exports = passport;
|
||||
|
|
|
@ -3,4 +3,4 @@ const deserializeUser = (user, done) => {
|
|||
done(null, user);
|
||||
};
|
||||
|
||||
export default deserializeUser;
|
||||
module.exports = deserializeUser;
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue