Compare commits

...

3 Commits

Author SHA1 Message Date
Râu Cao
833ab50616 Automatically refresh lndhub token once a day 2023-11-22 21:12:24 +01:00
Râu Cao
35844b577c Handle failed API requests, reauth when token expired 2023-11-22 21:08:01 +01:00
Râu Cao
b51bbd446c Wait longer, increase check interval for payment checks 2023-11-22 21:07:01 +01:00
2 changed files with 89 additions and 49 deletions

View File

@@ -42,16 +42,24 @@ function startPingInterval () {
}
function waitForInvoicePaid (room, nick, invoice, retries=0) {
let timeout = 3000;
if (retries >= 300) {
console.log(`Invoice not paid after 15 minutes: ${invoice.payment_hash}`);
return false;
let timeout = 5000;
if (retries >= 500) {
// TODO ask user to request voice again to create a new invoice
return false;
}
}
lndhub.getInvoice(invoice.payment_hash).then(async data => {
if (data.is_paid) {
if (data && data.is_paid) {
console.log(`Invoice paid: ${invoice.payment_hash}`);
await grantVoice(room, nick);
} else {
setTimeout(waitForInvoicePaid, 3000, room, nick, invoice, retries++);
if (!data) console.warn('Fetching invoice status failed');
setTimeout(waitForInvoicePaid, timeout, room, nick, invoice, retries++);
}
});
}
@@ -85,10 +93,14 @@ async function handleVoiceRequest (stanza) {
console.log(`${nick} requested voice in ${room}`);
const invoice = await lndhub.createInvoice(config.amounts.voice, `Donation for ${room}`);
console.log(`Created lightning invoice for ${nick}: ${invoice.payment_hash}`)
await respondToVoiceRequest(room, nick, invoice);
waitForInvoicePaid(room, nick, invoice);
if (invoice) {
console.log(`Created lightning invoice for ${nick}: ${invoice.payment_hash}`)
await respondToVoiceRequest(room, nick, invoice);
waitForInvoicePaid(room, nick, invoice);
} else {
console.warn(`Invoice creation failed!`);
// TODO notify ops contact
}
} catch(err) {
console.error(err);
}
@@ -105,10 +117,16 @@ async function connectXmpp () {
}
function connectLndhub () {
return lndhub.auth(config.lndhub.username, config.lndhub.password).then(() => {
console.log("Connected to Lndhub");
return lndhub.auth(config.lndhub.username, config.lndhub.password).then(connected => {
if (connected) {
console.log("Connected to Lndhub");
// automatically refresh auth token once a day
setInterval(lndhub.reauth, 86400000);
} else {
process.exit(1);
}
}).catch(err => {
console.warn(`Lndhub auth failed: ${err}`);
console.error(`Lndhub connection failed: ${err}`);
});
}

View File

@@ -5,61 +5,83 @@ export default class Lndhub {
this.baseUrl = baseUrl;
}
async callEndpoint (method, path, payload) {
const options = { method, headers: { 'Content-Type': 'application/json' } };
if (path !== '/auth') {
options.headers['Authorization'] = `Bearer ${this.accessToken}`;
}
if (typeof payload !== 'undefined') {
options.body = JSON.stringify(payload);
}
const res = await fetch(`${this.baseUrl}${path}`, options);
return res.json();
}
async handleErroredRequest (result, retryFunction, args=[]) {
console.warn('API request failed:', result.message);
if (result.code === 1) {
return this.reauth().then(connected => {
if (connected) {
console.warn('Lndhub reconnected, trying again...');
return this[retryFunction](...args);
}
});
} else {
return false;
}
}
async auth (username, password) {
const payload = { "login": username, "password": password };
const data = await this.callEndpoint('post', '/auth', payload);
console.log('data', data);
const res = await fetch(`${this.baseUrl}/auth`, {
method: 'post',
body: JSON.stringify(payload),
headers: { 'Content-Type': 'application/json' }
});
const data = await res.json();
this.refreshToken = data.refresh_token;
this.accessToken = data.access_token;
if (data.error) {
console.warn('Lndhub connection failed:', data.message);
return false;
} else {
this.refreshToken = data.refresh_token;
this.accessToken = data.access_token;
return true;
}
}
async reauth (refreshToken) {
const payload = { "refresh_token": this.refreshToken };
const data = await this.callEndpoint('post', '/auth', payload);
const res = await fetch(`${this.baseUrl}/auth`, {
method: 'post',
body: JSON.stringify(payload),
headers: { 'Content-Type': 'application/json' }
});
const data = await res.json();
this.accessToken = data.access_token;
if (data.error) {
console.warn('Lndhub re-auth failed:', data.message);
return false;
} else {
if (this.accessToken !== data.access_token) {
console.log('Lndhub access token refreshed');
}
this.accessToken = data.access_token;
return true;
}
}
async createInvoice (amount, description) {
const payload = { amount, description };
let data = await this.callEndpoint('post', '/v2/invoices', payload);
const res = await fetch(`${this.baseUrl}/v2/invoices`, {
method: 'post',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.accessToken}`
}
});
const data = await res.json();
// TODO re-auth if token has expired
return data;
if (data.error) {
return this.handleErroredRequest(data, 'createInvoice', Array.from(arguments));
} else {
return data;
}
}
async getInvoice (paymentHash) {
const res = await fetch(`${this.baseUrl}/v2/invoices/${paymentHash}`, {
method: 'get',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.accessToken}`
}
});
const data = await res.json();
// TODO re-auth if token has expired
const data = await this.callEndpoint('get', `/v2/invoices/${paymentHash}`);
return data;
if (data.error) {
return this.handleErroredRequest(data, 'getInvoice', Array.from(arguments));
} else {
return data;
}
}
}