clean and manage errs

This commit is contained in:
hatim boufnichel 2021-01-24 18:27:21 +01:00
parent 9f4a0b05d2
commit 6d8c82b693
2 changed files with 95 additions and 96 deletions

View file

@ -242,6 +242,8 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
*/ */
const invoicePaidCb = async paidInvoice => { const invoicePaidCb = async paidInvoice => {
console.log('INVOICE PAID') console.log('INVOICE PAID')
let breakError = null
let orderMetadata //eslint-disable-line init-declarations
const hashString = paidInvoice.r_hash.toString('hex') const hashString = paidInvoice.r_hash.toString('hex')
const { const {
amt_paid_sat: amt, amt_paid_sat: amt,
@ -254,6 +256,7 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
case 'tip': { case 'tip': {
const postID = ackInfo const postID = ackInfo
if (!Common.isPopulatedString(postID)) { if (!Common.isPopulatedString(postID)) {
breakError = 'invalid ackInfo provided for postID'
break //create the coordinate, but stop because of the invalid id break //create the coordinate, but stop because of the invalid id
} }
getUser() getUser()
@ -273,6 +276,7 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
console.log('ACK INFO') console.log('ACK INFO')
console.log(ackInfo) console.log(ackInfo)
if (!Common.isPopulatedString(postID)) { if (!Common.isPopulatedString(postID)) {
breakError = 'invalid ackInfo provided for postID'
break //create the coordinate, but stop because of the invalid id break //create the coordinate, but stop because of the invalid id
} }
console.log('IS STRING') console.log('IS STRING')
@ -289,6 +293,7 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
!selectedPost.status || !selectedPost.status ||
selectedPost.status !== 'publish' selectedPost.status !== 'publish'
) { ) {
breakError = 'ackInfo provided does not correspond to a valid post'
break //create the coordinate, but stop because of the invalid post break //create the coordinate, but stop because of the invalid post
} }
console.log('IS POST') console.log('IS POST')
@ -298,6 +303,7 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
const contentsToSend = {} const contentsToSend = {}
const mySecret = require('../../Mediator').getMySecret() const mySecret = require('../../Mediator').getMySecret()
console.log('SECRET OK') console.log('SECRET OK')
let privateFound = false
await Common.Utils.asyncForEach( await Common.Utils.asyncForEach(
Object.entries(selectedPost.contentItems), Object.entries(selectedPost.contentItems),
async ([contentID, item]) => { async ([contentID, item]) => {
@ -310,10 +316,16 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
if (!item.isPrivate) { if (!item.isPrivate) {
return return
} }
privateFound = true
const decrypted = await SEA.decrypt(item.magnetURI, mySecret) const decrypted = await SEA.decrypt(item.magnetURI, mySecret)
contentsToSend[contentID] = decrypted contentsToSend[contentID] = decrypted
} }
) )
if (!privateFound) {
breakError =
'post provided from ackInfo does not contain private content'
break //no private content in this post
}
const ackData = { unlockedContents: contentsToSend } const ackData = { unlockedContents: contentsToSend }
const toSend = JSON.stringify(ackData) const toSend = JSON.stringify(ackData)
const encrypted = await SEA.encrypt(toSend, secret) const encrypted = await SEA.encrypt(toSend, secret)
@ -339,7 +351,8 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
} }
}) })
}) })
console.log('RES SENT') console.log('RES SENT CONTENT')
orderMetadata = JSON.stringify(ordResponse)
break break
} }
case 'torrentSeed': { case 'torrentSeed': {
@ -347,6 +360,7 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
const seedUrl = process.env.TORRENT_SEED_URL const seedUrl = process.env.TORRENT_SEED_URL
const seedToken = process.env.TORRENT_SEED_TOKEN const seedToken = process.env.TORRENT_SEED_TOKEN
if (!seedUrl || !seedToken) { if (!seedUrl || !seedToken) {
breakError = 'torrentSeed service not available'
break //service not available break //service not available
} }
console.log('SEED URL OK') console.log('SEED URL OK')
@ -365,6 +379,7 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
body: JSON.stringify(reqData) body: JSON.stringify(reqData)
}) })
if (res.status !== 200) { if (res.status !== 200) {
breakError = 'torrentSeed service currently not available'
break //request didnt work, save coordinate anyway break //request didnt work, save coordinate anyway
} }
console.log('RES SEED OK') console.log('RES SEED OK')
@ -392,6 +407,8 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
} }
}) })
}) })
console.log('RES SENT SEED')
orderMetadata = JSON.stringify(serviceResponse)
break break
} }
case 'other': //not implemented yet but save them as a coordinate anyways case 'other': //not implemented yet but save them as a coordinate anyways
@ -399,6 +416,7 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
default: default:
return //exit because not implemented return //exit because not implemented
} }
const metadata = breakError ? JSON.stringify(breakError) : orderMetadata
const myGunPub = getUser()._.sea.pub const myGunPub = getUser()._.sea.pub
SchemaManager.AddOrder({ SchemaManager.AddOrder({
type: orderType, type: orderType,
@ -410,8 +428,13 @@ const listenerForAddr = (addr, SEA) => async (order, orderID) => {
toLndPub: paymentAddr, toLndPub: paymentAddr,
fromGunPub: order.from, fromGunPub: order.from,
toGunPub: myGunPub, toGunPub: myGunPub,
invoiceMemo: memo invoiceMemo: memo,
metadata
}) })
if (breakError) {
throw new Error(breakError)
}
} }
console.log('WAITING INVOICE TO BE PAID') console.log('WAITING INVOICE TO BE PAID')
new Promise(res => SchemaManager.addListenInvoice(invoice.r_hash, res)) new Promise(res => SchemaManager.addListenInvoice(invoice.r_hash, res))

View file

@ -106,52 +106,50 @@ const checkOrderInfo = order => {
return null return null
} }
/** /*
* *
* @param {CoordinateOrder} orderInfo * @param {CoordinateOrder} orderInfo
* @param {string} coordinateSHA256 * @param {string} coordinateSHA256
*/ *//*
const dateIndexCreateCb = (orderInfo, coordinateSHA256) => { const dateIndexCreateCb = (orderInfo, coordinateSHA256) => {
//if (this.memIndex) { need bind to use this here //if (this.memIndex) { need bind to use this here
//update date memIndex //update date memIndex
//} //}
const date = new Date(orderInfo.timestamp || 0) const date = new Date(orderInfo.timestamp || 0)
//use UTC for consistency? //use UTC for consistency?
const year = date.getUTCFullYear().toString() const year = date.getUTCFullYear().toString()
const month = date.getUTCMonth().toString() const month = date.getUTCMonth().toString()
getGunUser() getGunUser()
.get(Key.DATE_COORDINATE_INDEX) .get(Key.DATE_COORDINATE_INDEX)
.get(year) .get(year)
.get(month) .get(month)
.set(coordinateSHA256) .set(coordinateSHA256)
} }*/
/** /*
* if not provided, assume current month and year * if not provided, assume current month and year
* @param {number|null} year * @param {number|null} year
* @param {number|null} month * @param {number|null} month
*/ *//*
const getMonthCoordinates = async (year = null, month = null) => { const getMonthCoordinates = async (year = null, month = null) => {
const now = Date.now() const now = Date.now()
//@ts-expect-error const stringYear = year !== null ? year.toString() : now.getUTCFullYear().toString()
const stringYear = year !== null ? year.toString() : now.getUTCFullYear().toString() const stringMonth = month !== null ? month.toString() : now.getUTCMonth().toString()
//@ts-expect-error
const stringMonth = month !== null ? month.toString() : now.getUTCMonth().toString()
const data = await new Promise(res => { const data = await new Promise(res => {
getGunUser() getGunUser()
.get(Key.DATE_COORDINATE_INDEX) .get(Key.DATE_COORDINATE_INDEX)
.get(stringYear) .get(stringYear)
.get(stringMonth) .get(stringMonth)
.load(res) .load(res)
}) })
const coordinatesArray = Object const coordinatesArray = Object
.values(data) .values(data)
.filter(coordinateSHA256 => typeof coordinateSHA256 === 'string') .filter(coordinateSHA256 => typeof coordinateSHA256 === 'string')
return coordinatesArray return coordinatesArray
} }*/
/** /**
* *
@ -320,25 +318,11 @@ const handleUnconfirmedTx = (tx, order) => {
} }
class SchemaManager { class SchemaManager {
constructor(opts = { memIndex: false }) {//config flag? //constructor() {
this.memIndex = opts.memIndex // this.orderCreateIndexCallbacks.push(dateIndexCreateCb) //create more Cbs and put them here for more indexes callbacks
this.orderCreateIndexCallbacks.push(dateIndexCreateCb) //create more Cbs and put them here for more indexes callbacks //}
}
dateIndexName = 'dateIndex'
memIndex = false //save the index data in memory for faster access
// MEM INDEX, will be used only if memIndex === true
memDateIndex = {} //not implemented yet
memGunPubIndex = {} //not implemented yet
memLndPubIndex = {} //not implemented yet
memTypeIndex = {} //not implemented yet
//
//dateIndexName = 'dateIndex'
/** /**
* @type {((order : CoordinateOrder,coordinateSHA256 : string)=>void)[]} * @type {((order : CoordinateOrder,coordinateSHA256 : string)=>void)[]}
*/ */
@ -347,6 +331,7 @@ class SchemaManager {
/** /**
* @param {CoordinateOrder} orderInfo * @param {CoordinateOrder} orderInfo
*/ */
// eslint-disable-next-line class-methods-use-this
async AddOrder(orderInfo) { async AddOrder(orderInfo) {
const checkErr = checkOrderInfo(orderInfo) const checkErr = checkOrderInfo(orderInfo)
if (checkErr) { if (checkErr) {
@ -369,7 +354,6 @@ class SchemaManager {
amount: orderInfo.amount, amount: orderInfo.amount,
description: orderInfo.description, description: orderInfo.description,
metadata: orderInfo.metadata, metadata: orderInfo.metadata,
timestamp: orderInfo.timestamp || Date.now(), timestamp: orderInfo.timestamp || Date.now(),
} }
const orderString = JSON.stringify(filteredOrder) const orderString = JSON.stringify(filteredOrder)
@ -400,36 +384,33 @@ class SchemaManager {
}) })
//update all indexes with //update all indexes with
this.orderCreateIndexCallbacks.forEach(cb => cb(filteredOrder, coordinateSHA256)) //this.orderCreateIndexCallbacks.forEach(cb => cb(filteredOrder, coordinateSHA256))
} }
/** /*
* if not provided, assume current month and year * if not provided, assume current month and year
* @param {number|null} year * @param {number|null} year
* @param {number|null} month * @param {number|null} month
* @returns {Promise<CoordinateOrder[]>} from newer to older * @returns {Promise<CoordinateOrder[]>} from newer to older
*/ *//*
async getMonthOrders(year = null, month = null) { async getMonthOrders(year = null, month = null) {
const now = new Date() const now = new Date()
const intYear = year !== null ? year : now.getUTCFullYear() const intYear = year !== null ? year : now.getUTCFullYear()
const intMonth = month !== null ? month : now.getUTCMonth() const intMonth = month !== null ? month : now.getUTCMonth()
let coordinates = null let coordinates = null
if (this.memIndex) { if (this.memIndex) {
//get coordinates from this.memDateIndex //get coordinates from this.memDateIndex
} else { } else {
coordinates = await getMonthCoordinates(intYear, intMonth) coordinates = await getMonthCoordinates(intYear, intMonth)
} }
/** const orders = []
* @type {CoordinateOrder[]} if (!coordinates) {
*/
const orders = []
if (!coordinates) {
return orders return orders
} }
await Common.Utils.asyncForEach(coordinates, async coordinateSHA256 => { await Common.Utils.asyncForEach(coordinates, async coordinateSHA256 => {
const encryptedOrderString = await getGunUser() const encryptedOrderString = await getGunUser()
.get(Key.COORDINATES) .get(Key.COORDINATES)
.get(coordinateSHA256) .get(coordinateSHA256)
@ -440,17 +421,12 @@ class SchemaManager {
const mySecret = require('../gunDB/Mediator').getMySecret() const mySecret = require('../gunDB/Mediator').getMySecret()
const SEA = require('../gunDB/Mediator').mySEA const SEA = require('../gunDB/Mediator').mySEA
const decryptedString = await SEA.decrypt(encryptedOrderString, mySecret) const decryptedString = await SEA.decrypt(encryptedOrderString, mySecret)
/**
* @type {CoordinateOrder}
*/
const orderJSON = JSON.parse(decryptedString) const orderJSON = JSON.parse(decryptedString)
orders.push(orderJSON) orders.push(orderJSON)
}) })
//@ts-expect-error const orderedOrders = orders.sort((a, b) => b.timestamp - a.timestamp)
const orderedOrders = orders.sort((a, b) => b.timestamp - a.timestamp) return orderedOrders
return orderedOrders }*/
}
/** /**
* @typedef {Common.Schema.InvoiceWhenListed & {r_hash:Buffer,payment_addr:string}} Invoice * @typedef {Common.Schema.InvoiceWhenListed & {r_hash:Buffer,payment_addr:string}} Invoice