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

View file

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