| 1 |
import { getById, writeError, writeInfo, a, div } from "/common.module.js"; |
| 2 |
|
| 3 |
|
| 4 |
const url_like_regex = |
| 5 |
/^[-a-zA-Z0-9@:%_\+.~#?& |
| 6 |
|
| 7 |
|
| 8 |
function arraysEqual(a, b) { |
| 9 |
if (a === b) return true; |
| 10 |
if (a == null || b == null) return false; |
| 11 |
if (a.length !== b.length) return false; |
| 12 |
|
| 13 |
for (var i = 0; i < a.length; ++i) { |
| 14 |
if (a[i] !== b[i]) return false; |
| 15 |
} |
| 16 |
return true; |
| 17 |
} |
| 18 |
|
| 19 |
function logQRValue(value) { |
| 20 |
if (URL.canParse(value)) { |
| 21 |
writeInfo(div(a(new URL(url).href, value))); |
| 22 |
} else if (url_like_regex.test(value)) { |
| 23 |
|
| 24 |
if (!value.startsWith("http://") && !value.startsWith("https://")) { |
| 25 |
value = "https://" + value; |
| 26 |
} |
| 27 |
writeInfo(div(a(value, value))); |
| 28 |
} else { |
| 29 |
writeInfo(value); |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
export function onLoad() { |
| 34 |
|
| 35 |
if (!("BarcodeDetector" in globalThis)) { |
| 36 |
writeError( |
| 37 |
"Barcode Detector is not supported by this browser. Make sure Shape Detection API is turned on.", |
| 38 |
); |
| 39 |
} else { |
| 40 |
writeInfo("Barcode Detector supported!"); |
| 41 |
|
| 42 |
|
| 43 |
const barcodeDetector = new BarcodeDetector({ |
| 44 |
formats: ["qr_code"], |
| 45 |
}); |
| 46 |
|
| 47 |
const initBarcodescan = (stream) => { |
| 48 |
writeInfo("Starting scanner..."); |
| 49 |
var lastbarcodes = []; |
| 50 |
setInterval(() => { |
| 51 |
barcodeDetector |
| 52 |
.detect(stream) |
| 53 |
.then((barcodes) => { |
| 54 |
if (barcodes.length === 0) { |
| 55 |
} else { |
| 56 |
const values = barcodes.map( |
| 57 |
(barcode) => barcode.rawValue, |
| 58 |
); |
| 59 |
if (arraysEqual(values, lastbarcodes)) { |
| 60 |
return; |
| 61 |
} |
| 62 |
|
| 63 |
values.forEach(logQRValue); |
| 64 |
lastbarcodes = values; |
| 65 |
} |
| 66 |
}) |
| 67 |
.catch((err) => { |
| 68 |
writeError(err); |
| 69 |
}); |
| 70 |
}, 1000); |
| 71 |
}; |
| 72 |
|
| 73 |
var video = getById("video"); |
| 74 |
video.setAttribute("playsinline", ""); |
| 75 |
video.setAttribute("autoplay", ""); |
| 76 |
video.setAttribute("muted", ""); |
| 77 |
video.style.width = "100%"; |
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
var facingMode = "environment"; |
| 82 |
var constraints = { |
| 83 |
audio: false, |
| 84 |
video: { |
| 85 |
facingMode: facingMode, |
| 86 |
}, |
| 87 |
}; |
| 88 |
|
| 89 |
|
| 90 |
navigator.mediaDevices |
| 91 |
.getUserMedia(constraints) |
| 92 |
.then(function success(stream) { |
| 93 |
video.srcObject = stream; |
| 94 |
}) |
| 95 |
.finally(() => { |
| 96 |
writeInfo("Initialized video stream"); |
| 97 |
initBarcodescan(video); |
| 98 |
}); |
| 99 |
} |
| 100 |
} |