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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
|
/*
This file is part of GNU Taler
(C) 2022 Taler Systems S.A.
GNU Taler is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 3, or (at your option) any later version.
GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
*/
import {
assertUnreachable,
parseTalerUri,
TalerUri,
TalerUriAction,
TranslatedString,
} from "@gnu-taler/taler-util";
import { useTranslationContext } from "@gnu-taler/web-util/browser";
import { css } from "@linaria/core";
import { styled } from "@linaria/react";
import jsQR, * as pr from "jsqr";
import { Fragment, h, VNode } from "preact";
import { useRef, useState } from "preact/hooks";
import { Alert } from "../mui/Alert.js";
import { Button } from "../mui/Button.js";
import { Grid } from "../mui/Grid.js";
import { InputFile } from "../mui/InputFile.js";
import { TextField } from "../mui/TextField.js";
import { EnabledBySettings } from "../components/EnabledBySettings.js";
const QrCanvas = css`
width: 80%;
margin-left: auto;
margin-right: auto;
padding: 8px;
background-color: black;
`;
const LINE_COLOR = "#FF3B58";
const Container = styled.div`
display: flex;
flex-direction: column;
& > * {
margin-bottom: 20px;
}
`;
export interface Props {
onDetected: (url: TalerUri) => void;
}
type XY = { x: number; y: number };
function drawLine(
canvas: CanvasRenderingContext2D,
begin: XY,
end: XY,
color: string,
) {
canvas.beginPath();
canvas.moveTo(begin.x, begin.y);
canvas.lineTo(end.x, end.y);
canvas.lineWidth = 4;
canvas.strokeStyle = color;
canvas.stroke();
}
function drawBox(context: CanvasRenderingContext2D, code: pr.QRCode) {
drawLine(
context,
code.location.topLeftCorner,
code.location.topRightCorner,
LINE_COLOR,
);
drawLine(
context,
code.location.topRightCorner,
code.location.bottomRightCorner,
LINE_COLOR,
);
drawLine(
context,
code.location.bottomRightCorner,
code.location.bottomLeftCorner,
LINE_COLOR,
);
drawLine(
context,
code.location.bottomLeftCorner,
code.location.topLeftCorner,
LINE_COLOR,
);
}
const SCAN_PER_SECONDS = 3;
const TIME_BETWEEN_FRAMES = 1000 / SCAN_PER_SECONDS;
async function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function drawIntoCanvasAndGetQR(
tag: HTMLVideoElement | HTMLImageElement,
canvas: HTMLCanvasElement,
): string | undefined {
const context = canvas.getContext("2d");
if (!context) {
throw Error("no 2d canvas context");
}
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(tag, 0, 0, canvas.width, canvas.height);
const imgData = context.getImageData(0, 0, canvas.width, canvas.height);
const code = jsQR.default(imgData.data, canvas.width, canvas.height, {
inversionAttempts: "attemptBoth",
});
if (code) {
drawBox(context, code);
return code.data;
}
return undefined;
}
async function readNextFrame(
video: HTMLVideoElement,
canvas: HTMLCanvasElement,
): Promise<string | undefined> {
const requestFrame =
"requestVideoFrameCallback" in video
? video.requestVideoFrameCallback.bind(video)
: requestAnimationFrame;
return new Promise<string | undefined>((ok, bad) => {
requestFrame(() => {
try {
const code = drawIntoCanvasAndGetQR(video, canvas);
ok(code);
} catch (error) {
bad(error);
}
});
});
}
async function createCanvasFromVideo(
video: HTMLVideoElement,
canvas: HTMLCanvasElement,
): Promise<string> {
const context = canvas.getContext("2d", {
willReadFrequently: true,
});
if (!context) {
throw Error("no 2d canvas context");
}
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
let last = Date.now();
let found: string | undefined = undefined;
while (!found) {
const timeSinceLast = Date.now() - last;
if (timeSinceLast < TIME_BETWEEN_FRAMES) {
await delay(TIME_BETWEEN_FRAMES - timeSinceLast);
}
last = Date.now();
found = await readNextFrame(video, canvas);
}
video.pause();
return found;
}
async function createCanvasFromFile(
source: string,
canvas: HTMLCanvasElement,
): Promise<string | undefined> {
const img = new Image(300, 300);
img.src = source;
canvas.width = img.width;
canvas.height = img.height;
return new Promise<string | undefined>((ok, bad) => {
img.addEventListener("load", (e) => {
try {
const code = drawIntoCanvasAndGetQR(img, canvas);
ok(code);
} catch (error) {
bad(error);
}
});
});
}
async function waitUntilReady(video: HTMLVideoElement): Promise<void> {
return new Promise((ok, bad) => {
if (video.readyState === video.HAVE_ENOUGH_DATA) {
return ok();
}
setTimeout(waitUntilReady, 100);
});
}
export function QrReaderPage({ onDetected }: Props): VNode {
const videoRef = useRef<HTMLVideoElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const [error, setError] = useState<TranslatedString | undefined>();
const [value, setValue] = useState("");
const [show, setShow] = useState<"canvas" | "video" | "nothing">("nothing");
const { i18n } = useTranslationContext();
function onChangeDetect(str: string) {
if (!!str) {
const uri = parseTalerUri(str)
if (!uri) {
setError(
i18n.str`URI is not valid. Taler URI should start with "taler://"`,
);
} else {
onDetected(uri)
setError(undefined);
}
} else {
setError(undefined);
}
setValue(str);
}
function onChange(str: string) {
if (!!str) {
if (!parseTalerUri(str)) {
setError(
i18n.str`URI is not valid. Taler URI should start with "taler://"`,
);
} else {
setError(undefined);
}
} else {
setError(undefined);
}
setValue(str);
}
async function startVideo() {
if (!videoRef.current || !canvasRef.current) {
return;
}
const video = videoRef.current;
if (!video || !video.played) return;
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: "environment" },
audio: false,
});
setShow("video");
setError(undefined);
video.srcObject = stream;
await video.play();
await waitUntilReady(video);
try {
const code = await createCanvasFromVideo(video, canvasRef.current);
if (code) {
onChangeDetect(code);
setShow("canvas");
}
stream.getTracks().forEach((e) => {
e.stop();
});
} catch (error) {
setError(i18n.str`something unexpected happen: ${error}`);
}
}
async function onFileRead(fileContent: string) {
if (!canvasRef.current) {
return;
}
setShow("nothing");
setError(undefined);
try {
const code = await createCanvasFromFile(fileContent, canvasRef.current);
if (code) {
onChangeDetect(code);
setShow("canvas");
} else {
setError(i18n.str`Could not found a QR code in the file`);
}
} catch (error) {
setError(i18n.str`something unexpected happen: ${error}`);
}
}
const uri = parseTalerUri(value);
const active = value === "";
return (
<Container>
<section>
<h1>
<i18n.Translate>
Scan a QR code or enter taler:// URI below
</i18n.Translate>
</h1>
<p>
<TextField
label="Taler URI"
variant="standard"
fullWidth
value={value}
onChange={onChange}
/>
</p>
<Grid container justifyContent="space-around" columns={2}>
<Grid item xs={2}>
<p>{error && <Alert severity="error">{error}</Alert>}</p>
</Grid>
{uri && (
<Grid item xs={2}>
<Button
disabled={!!error}
variant="contained"
color="success"
onClick={async () => {
if (uri) onDetected(uri);
}}
>
{(function (talerUri: TalerUri): VNode {
switch (talerUri.type) {
case TalerUriAction.Pay:
return <i18n.Translate>Pay invoice</i18n.Translate>
case TalerUriAction.Withdraw:
return <i18n.Translate>Withdrawal from bank</i18n.Translate>
case TalerUriAction.Refund:
return <i18n.Translate>Claim refund</i18n.Translate>
case TalerUriAction.PayPull:
return <i18n.Translate>Pay invoice</i18n.Translate>
case TalerUriAction.PayPush:
return <i18n.Translate>Accept payment</i18n.Translate>
case TalerUriAction.PayTemplate:
return <i18n.Translate>Complete order</i18n.Translate>
case TalerUriAction.Restore:
return <i18n.Translate>Restore wallet</i18n.Translate>
case TalerUriAction.DevExperiment:
return <i18n.Translate>Enable experiment</i18n.Translate>
case TalerUriAction.WithdrawExchange:
return <i18n.Translate>Withdraw from exchange</i18n.Translate>
case TalerUriAction.AddExchange:
return <i18n.Translate>Add exchange</i18n.Translate>
default: {
assertUnreachable(talerUri)
}
}
})(uri)}
</Button>
</Grid>
)}
<Grid item xs={1}>
<p>
<Button variant="contained" onClick={startVideo}>
Use Camera
</Button>
</p>
</Grid>
{!active && (
<Grid item xs={1}>
<p>
<Button
variant="contained"
onClick={async () => {
setShow("nothing");
onChange("");
}}
color="error"
>
<i18n.Translate>Clear</i18n.Translate>
</Button>
</p>
</Grid>
)}
<EnabledBySettings name="advancedMode">
<Grid item xs={2}>
<InputFile onChange={onFileRead}>Read QR from file</InputFile>
</Grid>
</EnabledBySettings>
</Grid>
</section>
<div>
<video
ref={videoRef}
style={{ display: show === "video" ? "unset" : "none" }}
playsInline={true}
/>
<canvas
id="este"
class={QrCanvas}
ref={canvasRef}
style={{ display: show === "canvas" ? "unset " : "none" }}
/>
</div>
</Container>
);
}
|