-
Notifications
You must be signed in to change notification settings - Fork 1
/
lnsubscribe.mjs
90 lines (78 loc) · 2.81 KB
/
lnsubscribe.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import grpc from '@grpc/grpc-js';
import protoLoader from '@grpc/proto-loader';
import Database from 'better-sqlite3';
import config from 'config';
import mailersend from './mailersend.js';
import * as EmailValidator from 'email-validator';
const appDb = new Database(config.get("applicationDatabase"));
function lnsubscribe(lndCredentials){
try{
const settingsDefault = appDb.prepare("SELECT * FROM settings WHERE id='default';").get();
const loaderOptions = {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true
};
const packageDefinition = protoLoader.loadSync('lightning.proto', loaderOptions);
const lnrpc = grpc.loadPackageDefinition(packageDefinition).lnrpc;
const macaroon = lndCredentials.macaroon
process.env.GRPC_SSL_CIPHER_SUITES = 'HIGH+ECDSA';
const lndCert = lndCredentials.cert;
const sslCreds = grpc.credentials.createSsl(lndCert);
const macaroonCreds = grpc.credentials.createFromMetadataGenerator(function(args, callback) {
let metadata = new grpc.Metadata();
metadata.add('macaroon', macaroon);
callback(null, metadata);
});
let creds = grpc.credentials.combineChannelCredentials(sslCreds, macaroonCreds);
let lightning = new lnrpc.Lightning(lndCredentials.lndEndpoint+":"+lndCredentials.lndPort, creds);
let request = {};
let call = lightning.subscribeInvoices(request);
call.on('data', function(response) {
console.log("SUBSCRIPTION: NEW EVENT: "+ response.state);
if(response.state=="SETTLED" || response.state=="CANCELED"){
let hexHash = Buffer.from(response.r_hash, "base64").toString("hex");
console.log("SUBSCRIPTION: hexHash: "+ hexHash);
const invoice = appDb.prepare("SELECT * FROM invoice WHERE r_hash=? AND status='OPEN';").get(hexHash);
if(!(typeof invoice === 'undefined')){
const dataUpdate = appDb.prepare("UPDATE invoice SET status=?, comment='' WHERE r_hash=?;").run(response.state,hexHash);
if(response.state=="SETTLED" && settingsDefault.sendmails){
mailersend(
settingsDefault.adminemail,
invoice.id,
settingsDefault.mailsubject,
settingsDefault.mailtext,
invoice.memo,
invoice.amount,
invoice.currency,
settingsDefault.mailersend_apikey,
settingsDefault.mailersend_template
);
if(EmailValidator.validate(invoice.comment)){
mailersend(
invoice.comment,
invoice.id,
settingsDefault.mailsubject,
settingsDefault.mailtext,
invoice.memo,
invoice.amount,
invoice.currency,
settingsDefault.mailersend_apikey,
settingsDefault.mailersend_template
);
}
}
}
}
});//on data end
call.on('end', function() {
console.log("SUBSCRIBE ENDED");
});
}
catch(err){
console.error(err);
}
}
export { lnsubscribe };