Merge branch 'dev' into feature/posts-tips

This commit is contained in:
emad-salah 2020-10-03 16:21:33 +01:00
commit f68c0bce98
3 changed files with 168 additions and 66 deletions

View file

@ -83,7 +83,12 @@
"no-undefined": "off", "no-undefined": "off",
"no-process-env": "off" "no-process-env": "off",
// I am now convinced TODO comments closer to the relevant code are better
// than GH issues. Especially when it only concerns a single function /
// routine.
"no-warning-comments": "off"
}, },
"parser": "babel-eslint", "parser": "babel-eslint",
"env": { "env": {

View file

@ -697,7 +697,24 @@ module.exports = async (
alias, alias,
publicKey publicKey
}, },
follows: await GunGetters.Follows.currentFollows() follows: await GunGetters.Follows.currentFollows(),
data: {
invoices: await Common.makePromise((res, rej) => {
lightning.listInvoices(
{
reversed: true,
num_max_invoices: 50
},
(err, lres) => {
if (err) {
rej(new Error(err.details))
} else {
res(lres)
}
}
)
})
}
}) })
return true return true
@ -3071,22 +3088,32 @@ module.exports = async (
}) })
ap.post('/api/lnd/cb/:methodName', (req, res) => { ap.post('/api/lnd/cb/:methodName', (req, res) => {
const { lightning } = LightningServices.services try {
const { methodName } = req.params const { lightning } = LightningServices.services
const args = req.body const { methodName } = req.params
const args = req.body
lightning[methodName](args, (err, lres) => { lightning[methodName](args, (err, lres) => {
if (err) { if (err) {
res.status(500).json({ res.status(500).json({
errorMessage: err.details errorMessage: err.details
}) })
} else if (lres) { } else if (lres) {
res.status(200).json(lres) res.status(200).json(lres)
} else { } else {
res.status(500).json({ res.status(500).json({
errorMessage: 'Unknown error' errorMessage: 'Unknown error'
}) })
} }
}) })
} catch (err) {
logger.warn(`Error inside api cb:`)
logger.error(err)
logger.error(err.message)
return res.status(500).json({
errorMessage: err.message
})
}
}) })
} }

View file

@ -1,9 +1,14 @@
/** @prettier */ /** @prettier */
// app/sockets.js // @ts-check
const logger = require('winston') const logger = require('winston')
const Encryption = require('../utils/encryptionStore') const Encryption = require('../utils/encryptionStore')
const LightningServices = require('../utils/lightningServices') const LightningServices = require('../utils/lightningServices')
const {
getGun,
getUser,
isAuthenticated
} = require('../services/gunDB/Mediator')
const onPing = (socket, subID) => { const onPing = (socket, subID) => {
logger.warn('Subscribing to pings socket...' + subID) logger.warn('Subscribing to pings socket...' + subID)
@ -21,8 +26,6 @@ module.exports = (
/** @type {import('socket.io').Server} */ /** @type {import('socket.io').Server} */
io io
) => { ) => {
const Mediator = require('../services/gunDB/Mediator/index.js')
// This should be used for encrypting and emitting your data // This should be used for encrypting and emitting your data
const emitEncryptedEvent = ({ eventName, data, socket }) => { const emitEncryptedEvent = ({ eventName, data, socket }) => {
try { try {
@ -255,67 +258,134 @@ module.exports = (
} }
} }
io.on('connection', socket => { io.of('default').on('connection', socket => {
logger.info(`io.onconnection`) logger.info(`io.onconnection`)
logger.info('socket.handshake', socket.handshake) logger.info('socket.handshake', socket.handshake)
const isOneTimeUseSocket = !!socket.handshake.query.IS_GUN_AUTH
const isLNDSocket = !!socket.handshake.query.IS_LND_SOCKET const isLNDSocket = !!socket.handshake.query.IS_LND_SOCKET
const isNotificationsSocket = !!socket.handshake.query const isNotificationsSocket = !!socket.handshake.query
.IS_NOTIFICATIONS_SOCKET .IS_NOTIFICATIONS_SOCKET
if (!isLNDSocket) { if (!isLNDSocket) {
/** printing out the client who joined */ /** printing out the client who joined */
logger.info('New socket client connected (id=' + socket.id + ').') logger.info('New socket client connected (id=' + socket.id + ').')
} }
if (isOneTimeUseSocket) { if (isLNDSocket) {
logger.info('New socket is one time use') const subID = Math.floor(Math.random() * 1000).toString()
socket.on('IS_GUN_AUTH', () => { const isNotifications = isNotificationsSocket ? 'notifications' : ''
try { logger.info('[LND] New LND Socket created:' + isNotifications + subID)
const isGunAuth = Mediator.isAuthenticated() const cancelInvoiceStream = onNewInvoice(socket, subID)
socket.emit('IS_GUN_AUTH', { const cancelTransactionStream = onNewTransaction(socket, subID)
ok: true, const cancelPingStream = onPing(socket, subID)
msg: { socket.on('disconnect', () => {
isGunAuth logger.info('LND socket disconnected:' + isNotifications + subID)
}, cancelInvoiceStream()
origBody: {} cancelTransactionStream()
}) cancelPingStream()
socket.disconnect()
} catch (err) {
socket.emit('IS_GUN_AUTH', {
ok: false,
msg: err.message,
origBody: {}
})
socket.disconnect()
}
}) })
} else { }
if (isLNDSocket) { })
const subID = Math.floor(Math.random() * 1000).toString()
const isNotifications = isNotificationsSocket ? 'notifications' : '' io.of('gun').on('connect', socket => {
logger.info('[LND] New LND Socket created:' + isNotifications + subID) // TODO: off()
const cancelInvoiceStream = onNewInvoice(socket, subID)
const cancelTransactionStream = onNewTransaction(socket, subID) try {
const cancelPingStream = onPing(socket, subID) if (!isAuthenticated()) {
socket.on('disconnect', () => { socket.emit('$shock', 'NOT_AUTH')
logger.info('LND socket disconnected:' + isNotifications + subID)
cancelInvoiceStream()
cancelTransactionStream()
cancelPingStream()
})
return return
} }
logger.info('New socket is NOT one time use')
// this is where we create the websocket connection
// with the GunDB service.
Mediator.createMediator(socket)
/** listening if client has disconnected */ const { $shock } = socket.handshake.query
socket.on('disconnect', () => {
logger.info('client disconnected (id=' + socket.id + ').') const [root, path, method] = $shock.split('::')
// eslint-disable-next-line init-declarations
let node
if (root === '$gun') {
node = getGun()
} else if (root === '$user') {
node = getUser()
} else {
node = getGun().user(root)
}
for (const bit of path.split('.')) {
node = node.get(bit)
}
/**
* @param {unknown} data
* @param {string} key
*/
const listener = (data, key) => {
try {
socket.emit('$shock', data, key)
} catch (err) {
logger.error(
`Error for gun rpc socket, query ${$shock} -> ${err.message}`
)
}
}
if (method === 'on') {
node.on(listener)
} else if (method === 'open') {
node.open(listener)
} else if (method === 'map.on') {
node.map().on(listener)
} else if (method === 'map.once') {
node.map().once(listener)
} else {
throw new TypeError(
`Invalid method for gun rpc call : ${method}, query: ${$shock}`
)
}
} catch (err) {
logger.error('GUNRPC: ' + err.message)
}
})
io.of('/lndstreaming').on('connect', socket => {
// TODO: unsubscription
/**
* Streaming stuff in LND uses these events: data, status, end, error.
*/
try {
const { services } = LightningServices
const { service, method, args: unParsed } = socket.handshake.query
const args = JSON.parse(unParsed)
const call = services[service][method](args)
call.on('data', data => {
socket.emit('data', data)
}) })
call.on('status', status => {
socket.emit('status', status)
})
call.on('end', () => {
socket.emit('end')
})
call.on('error', err => {
// 'error' is a reserved event name we can't use it
socket.emit('$error', err)
})
// Possibly allow streaming writes such as sendPaymentV2
socket.on('write', args => {
call.write(args)
})
} catch (err) {
logger.error('LNDRPC: ' + err.message)
} }
}) })