forked from robclark56/lightningtip-PHP
-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlightningTip.js
324 lines (232 loc) · 9.87 KB
/
lightningTip.js
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
///////// CHANGE ME ////////
var requestUrl = window.location.protocol + "//" + window.location.hostname + "/lightningTip.php";
///////// END CHANGE ME ////////
// To prohibit multiple requests at the same time
var running = false;
var invoice;
var qrCode;
var defaultGetInvoice;
// Data capacities for QR codes with mode byte and error correction level L (7%)
// Shortest invoice: 194 characters
// Longest invoice: 1223 characters (as far as I know)
var qrCodeDataCapacities = [
{"typeNumber": 9, "capacity": 230},
{"typeNumber": 10, "capacity": 271},
{"typeNumber": 11, "capacity": 321},
{"typeNumber": 12, "capacity": 367},
{"typeNumber": 13, "capacity": 425},
{"typeNumber": 14, "capacity": 458},
{"typeNumber": 15, "capacity": 520},
{"typeNumber": 16, "capacity": 586},
{"typeNumber": 17, "capacity": 644},
{"typeNumber": 18, "capacity": 718},
{"typeNumber": 19, "capacity": 792},
{"typeNumber": 20, "capacity": 858},
{"typeNumber": 21, "capacity": 929},
{"typeNumber": 22, "capacity": 1003},
{"typeNumber": 23, "capacity": 1091},
{"typeNumber": 24, "capacity": 1171},
{"typeNumber": 25, "capacity": 1273}
];
// TODO: solve this without JavaScript
// Fixes weird bug which moved the button up one pixel when its content was changed
window.onload = function () {
var button = document.getElementById("lightningTipGetInvoice");
button.style.height = (button.clientHeight + 1) + "px";
button.style.width = (button.clientWidth + 1) + "px";
};
var testnet = getVal('testnet'); //see if GET param testnet is set (URL?testnet=1)
console.log('Testnet = ' + testnet);
if ( testnet !== null ) {
requestUrl = requestUrl + '?testnet=1';
console.log('requestUrl = ' + requestUrl );
}
// TODO: show invoice even if JavaScript is disabled
// TODO: fix scaling on phones
// TODO: show price in dollar?
function getInvoice() {
if (running === false) {
running = true;
var tipValue = document.getElementById("lightningTipAmount").value.trim();
if (tipValue === "") {
showErrorMessage("No tip amount set");
return;
} else if (isNaN(tipValue)) {
showErrorMessage("Tip amount must be a number");
return;
} else if (tipValue < 1) {
showErrorMessage("Tip amount must be at least 1 sat");
return;
} else if (parseInt(tipValue).toString() != tipValue) {
showErrorMessage("Tip amount should be a whole number of sats (no decimals)");
return;
}
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
//console.log("RESPONSE: " + request.responseText);
try {
var json = JSON.parse(request.responseText);
if (request.status === 200) {
console.log("Got invoice: " + json.Invoice);
console.log("Invoice expires in: " + json.Expiry);
console.log("Starting listening for invoice to get settled");
listenInvoiceSettled(json.r_hash_str);
invoice = json.Invoice;
// Update UI
var wrapper = document.getElementById("lightningTip");
wrapper.innerHTML = "<a>Your tip request</a>";
wrapper.innerHTML += "<input type='text' class='lightningTipInput' id='lightningTipInvoice' onclick='copyInvoiceToClipboard()' value='" + invoice + "' readonly>";
wrapper.innerHTML += "<div id='lightningTipQR'></div>";
wrapper.innerHTML += "<div id='lightningTipTools'>" +
"<button class='lightningTipButton' id='lightningTipCopy' onclick='copyInvoiceToClipboard()'>Copy</button>" +
"<button class='lightningTipButton' id='lightningTipOpen'>Open</button>" +
"<a id='lightningTipExpiry'></a>" +
"</div>";
startTimer(json.Expiry, document.getElementById("lightningTipExpiry"));
// Fixes bug which caused the content of #lightningTipTools to be visually outside of #lightningTip
document.getElementById("lightningTipTools").style.height = document.getElementById("lightningTipCopy").clientHeight + "px";
document.getElementById("lightningTipOpen").onclick = function () {
location.href = "lightning:" + json.Invoice;
};
showQRCode();
running = false;
} else {
showErrorMessage(json.Error);
}
} catch (exception) {
console.error(exception);
showErrorMessage("Failed to reach backend");
}
}
};
request.open("POST", requestUrl , true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var params = "Action=getinvoice&Amount=" + parseInt(tipValue) + "&Message=" + encodeURIComponent(document.getElementById("lightningTipMessage").innerText);
console.log(params);
request.send(params);
var button = document.getElementById("lightningTipGetInvoice");
defaultGetInvoice = button.innerHTML;
button.innerHTML = "<div class='spinner'></div>";
} else {
console.warn("Last request still pending");
}
}
function listenInvoiceSettled(r_hash_str) {
var interval = setInterval(function () {
var request = new XMLHttpRequest();
//Prevent multiple calls for same invoice settled over slow networks.
var IsSettled = false;
if ( IsSettled == true) {
return;
}
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
//console.log("RESPONSE: " + request.responseText);
var json = JSON.parse(request.responseText);
if (json.settled) {
console.log("Invoice settled");
IsSettled = true;
clearInterval(interval);
showThankYouScreen();
}
}
};
request.open("POST", requestUrl, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var params = "Action=invoicesettled&r_hash_str=" + r_hash_str;
request.send(params);
}, 2000);
// }
}
function showThankYouScreen() {
var wrapper = document.getElementById("lightningTip");
wrapper.innerHTML = "<p id=\"lightningTipLogo\">⚡</p>";
wrapper.innerHTML += "<a id='lightningTipFinished'>Thank you for your tip!</a>";
}
function startTimer(duration, element) {
showTimer(duration, element);
var interval = setInterval(function () {
if (duration > 1) {
duration--;
showTimer(duration, element);
} else {
showExpired();
clearInterval(interval);
}
}, 1000);
}
function showTimer(duration, element) {
var seconds = Math.floor(duration % 60);
var minutes = Math.floor((duration / 60) % 60);
var hours = Math.floor((duration / (60 * 60)) % 24);
seconds = addLeadingZeros(seconds);
minutes = addLeadingZeros(minutes);
if (hours > 0) {
element.innerHTML = hours + ":" + minutes + ":" + seconds;
} else {
element.innerHTML = minutes + ":" + seconds;
}
}
function showExpired() {
var wrapper = document.getElementById("lightningTip");
wrapper.innerHTML = "<p id=\"lightningTipLogo\">⚡</p>";
wrapper.innerHTML += "<a id='lightningTipFinished'>Your tip request expired!</a>";
}
function addLeadingZeros(value) {
return ("0" + value).slice(-2);
}
function showQRCode() {
var element = document.getElementById("lightningTipQR");
createQRCode();
element.innerHTML = qrCode;
var size = document.getElementById("lightningTipInvoice").clientWidth + "px";
var qrElement = element.children[0];
qrElement.style.height = size;
qrElement.style.width = size;
}
function createQRCode() {
var invoiceLength = invoice.length;
// Just in case an invoice bigger than expected gets created
var typeNumber = 26;
for (var i = 0; i < qrCodeDataCapacities.length; i++) {
var dataCapacity = qrCodeDataCapacities[i];
if (invoiceLength < dataCapacity.capacity) {
typeNumber = dataCapacity.typeNumber;
break;
}
}
console.log("Creating QR code with type number: " + typeNumber);
var qr = qrcode(typeNumber, "L");
qr.addData(invoice);
qr.make();
qrCode = qr.createImgTag(6, 6);
}
function copyInvoiceToClipboard() {
var element = document.getElementById("lightningTipInvoice");
element.select();
document.execCommand('copy');
console.log("Copied invoice to clipboard");
}
function showErrorMessage(message) {
running = false;
console.error(message);
var error = document.getElementById("lightningTipError");
error.parentElement.style.marginTop = "0.5em";
error.innerHTML = message;
var button = document.getElementById("lightningTipGetInvoice");
// Only necessary if it has a child (div with class spinner)
if (button.children.length !== 0) {
button.innerHTML = defaultGetInvoice;
}
}
function divRestorePlaceholder(element) {
// <br> and <div><br></div> mean that there is no user input
if (element.innerHTML === "<br>" || element.innerHTML === "<div><br></div>") {
element.innerHTML = "";
}
}
function getVal(str) {
var v = window.location.search.match(new RegExp('(?:[\?\&]'+str+'=)([^&]+)'));
return v ? v[1] : null;
}