-
-
Notifications
You must be signed in to change notification settings - Fork 224
/
zxing-scanner.component.ts
502 lines (404 loc) · 13.4 KB
/
zxing-scanner.component.ts
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
ElementRef,
EventEmitter,
Input,
OnChanges,
OnDestroy,
Output,
SimpleChanges,
ViewChild
} from '@angular/core';
import { Result } from '@zxing/library';
import { BrowserQRCodeReader } from './browser-qr-code-reader';
@Component({
// tslint:disable-next-line:component-selector
selector: 'zxing-scanner',
templateUrl: './zxing-scanner.component.html',
styleUrls: ['./zxing-scanner.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ZXingScannerComponent implements AfterViewInit, OnDestroy, OnChanges {
/**
* The ZXing code reader.
*/
private codeReader: BrowserQRCodeReader = new BrowserQRCodeReader(1500);
/**
* Has `navigator` access.
*/
private hasNavigator: boolean;
/**
* Says if some native API is supported.
*/
private isMediaDevicesSuported: boolean;
/**
* Says if some native API is supported.
*/
private isEnumerateDevicesSuported: boolean;
/**
* List of enable video-input devices.
*/
private videoInputDevices: MediaDeviceInfo[];
/**
* The actual device used to scan things.
*/
private videoInputDevice: MediaDeviceInfo;
/**
* Says if the user allowedthe use of the camera or not.
*/
private hasPermission: boolean;
/**
* Reference to the preview element, should be the `video` tag.
*/
@ViewChild('preview')
previewElemRef: ElementRef;
/**
* The scan throttling (time between scans) in milliseconds.
*/
@Input()
scanThrottling = 1500;
/**
* Allow start scan or not.
*/
@Input()
scannerEnabled = true;
/**
* The device that should be used to scan things.
*/
@Input()
device: MediaDeviceInfo;
/**
* The value of the HTML video's class attribute.
*/
@Input()
cssClass: string;
/**
* Enable or disable autofocus of the camera (might have an impact on performance)
*/
@Input()
autofocusEnabled = true;
/**
* Allow start scan or not.
*/
@Input()
set torch(on: boolean) {
this.codeReader.setTorch(on);
}
/**
* Emitts events when the torch compatibility is changed.
*/
@Output()
torchCompatible = new EventEmitter<boolean>();
/**
* Emitts events when a scan is successful performed, will inject the string value of the QR-code to the callback.
*/
@Output()
scanSuccess = new EventEmitter<string>();
/**
* Emitts events when a scan fails without errors, usefull to know how much scan tries where made.
*/
@Output()
scanFailure = new EventEmitter<void>();
/**
* Emitts events when a scan throws some error, will inject the error to the callback.
*/
@Output()
scanError = new EventEmitter<Error>();
/**
* Emitts events when a scan is performed, will inject the Result value of the QR-code scan (if available) to the callback.
*/
@Output()
scanComplete = new EventEmitter<Result>();
/**
* Emitts events when no cameras are found, will inject an exception (if available) to the callback.
*/
@Output()
camerasFound = new EventEmitter<MediaDeviceInfo[]>();
/**
* Emitts events when no cameras are found, will inject an exception (if available) to the callback.
*/
@Output()
camerasNotFound = new EventEmitter<any>();
/**
* Emitts events when the users answers for permission.
*/
@Output()
permissionResponse = new EventEmitter<boolean>();
/**
* Constructor to build the object and do some DI.
*/
constructor() {
this.hasNavigator = typeof navigator !== 'undefined';
this.isMediaDevicesSuported = this.hasNavigator && !!navigator.mediaDevices;
this.isEnumerateDevicesSuported = !!(this.isMediaDevicesSuported && navigator.mediaDevices.enumerateDevices);
}
/**
* Manages the bindinded property changes.
* @param changes
*/
ngOnChanges(changes: SimpleChanges): void {
if (changes.scannerEnabled) {
if (!this.scannerEnabled) {
this.resetScan();
} else if (this.videoInputDevice) {
this.scan(this.videoInputDevice.deviceId);
}
}
if (changes.device) {
if (this.device) {
this.changeDevice(this.device);
} else {
console.warn('zxing-scanner', 'device', 'Unselected device.');
this.resetScan();
}
}
if (changes.scanThrottling) {
this.setCodeReaderThrottling(this.scanThrottling);
}
}
/**
* Executed after the view initialization.
*/
ngAfterViewInit(): void {
// Chrome 63 fix
if (!this.previewElemRef) {
console.warn('zxing-scanner', 'Preview element not found!');
return;
}
// iOS 11 Fix
this.previewElemRef.nativeElement.setAttribute('autoplay', false);
this.previewElemRef.nativeElement.setAttribute('muted', true);
this.previewElemRef.nativeElement.setAttribute('playsinline', true);
this.previewElemRef.nativeElement.setAttribute('autofocus', this.autofocusEnabled);
this.askForPermission().subscribe((hasPermission: boolean) => {
if (hasPermission) {
// gets and enumerates all video devices
this.enumarateVideoDevices((videoInputDevices: MediaDeviceInfo[]) => {
if (videoInputDevices && videoInputDevices.length > 0) {
this.camerasFound.next(videoInputDevices);
} else {
this.camerasNotFound.next();
}
});
this.startScan(this.videoInputDevice);
this.codeReader.torchAvailable.subscribe(value => {
this.torchCompatible.emit(value);
});
} else {
if (hasPermission === false) {
console.warn('zxing-scanner', 'ngAfterViewInit', 'User has denied permission.');
} else {
console.warn('zxing-scanner', 'ngAfterViewInit', 'It was not possible to check for permissions.');
}
}
});
}
/**
* Executes some actions before destroy the component.
*/
ngOnDestroy(): void {
this.resetScan();
}
/**
* Starts a new QR-scanner to set a new scan throttling.
*
* @param throttling The scan speed in milliseconds.
*/
setCodeReaderThrottling(throttling: number): void {
this.codeReader = new BrowserQRCodeReader(throttling);
}
/**
* Properly changes the actual target device.
*
* @param device
*/
changeDevice(device: MediaDeviceInfo): void {
this.videoInputDevice = device;
this.startScan(device);
}
/**
* Properly changes the actual target device using it's deviceId.
*
* @param deviceId
*/
changeDeviceById(deviceId: string): void {
this.changeDevice(this.getDeviceById(deviceId));
}
/**
* Properly returns the target device using it's deviceId.
*
* @param deviceId
*/
getDeviceById(deviceId: string): MediaDeviceInfo {
return this.videoInputDevices.find(device => device.deviceId === deviceId);
}
/**
* Sets the permission value and emmits the event.
*/
setPermission(hasPermission: boolean | undefined): EventEmitter<boolean> {
this.hasPermission = hasPermission;
this.permissionResponse.next(hasPermission);
return this.permissionResponse;
}
/**
* Gets and registers all cammeras.
*/
askForPermission(): EventEmitter<boolean> {
if (!this.hasNavigator) {
console.error('zxing-scanner', 'askForPermission', 'Can\'t ask permission, navigator is not present.');
return this.setPermission(undefined);
}
if (!this.isMediaDevicesSuported) {
console.error('zxing-scanner', 'askForPermission', 'Can\'t get user media, this is not supported.');
return this.setPermission(undefined);
}
// Will try to ask for permission
navigator
.mediaDevices
.getUserMedia({ audio: false, video: true })
.then((stream: MediaStream) => {
try {
// Start stream so Browser can display permission-dialog ("Website wants to access your camera, allow?")
this.previewElemRef.nativeElement.srcObject = stream;
// After permission was granted, we can stop it again
stream.getVideoTracks().forEach(track => {
track.stop();
});
this.previewElemRef.nativeElement.srcObject = undefined;
// if the scripts lives until here, that's only one mean:
// permission granted
this.setPermission(true);
} catch (err) {
console.error('zxing-scanner', 'askForPermission', err);
// permission aborted
this.setPermission(undefined);
}
})
.catch((err: DOMException) => {
// failed to grant permission to video input
console.warn('zxing-scanner', 'askForPermission', err);
switch (err.name) {
case 'NotAllowedError':
// permission denied
this.setPermission(false);
break;
case 'NotFoundError':
this.camerasNotFound.next(err);
break;
default:
this.setPermission(undefined);
break;
}
});
// Returns the event emitter, so the dev can subscribe to it
return this.permissionResponse;
}
/**
* Starts the continuous scanning for the given device.
*
* @param deviceId The deviceId from the device.
*/
scan(deviceId: string): void {
try {
this.codeReader.decodeFromInputVideoDevice((result: any) => {
console.debug('zxing-scanner', 'scan', 'result: ', result);
if (result) {
this.dispatchScanSuccess(result);
} else {
this.dispatchScanFailure();
}
this.dispatchScanComplete(result);
}, deviceId, this.previewElemRef.nativeElement);
} catch (err) {
this.dispatchScanError(err);
this.dispatchScanComplete(undefined);
}
}
/**
* Starts the scanning if allowed.
*
* @param device The device to be used in the scan.
*/
startScan(device: MediaDeviceInfo): void {
if (this.scannerEnabled && device) {
this.scan(device.deviceId);
}
}
/**
* Stops the scan service.
*/
resetScan(): void {
this.codeReader.reset();
}
/**
* Dispatches the scan success event.
*
* @param result the scan result.
*/
private dispatchScanSuccess(result: Result): void {
this.scanSuccess.next(result.getText());
}
/**
* Dispatches the scan failure event.
*/
private dispatchScanFailure(): void {
this.scanFailure.next();
}
/**
* Dispatches the scan error event.
*
* @param err the error thing.
*/
private dispatchScanError(error: any): void {
this.scanError.next(error);
}
/**
* Dispatches the scan event.
*
* @param result the scan result.
*/
private dispatchScanComplete(result: Result): void {
this.scanComplete.next(result);
}
/**
* Enumerates all the available devices.
*
* @param successCallback
*/
enumarateVideoDevices(successCallback: any): void {
if (!this.hasNavigator) {
console.error('zxing-scanner', 'enumarateVideoDevices', 'Can\'t enumerate devices, navigator is not present.');
return;
}
if (!this.isEnumerateDevicesSuported) {
console.error('zxing-scanner', 'enumarateVideoDevices', 'Can\'t enumerate devices, method not supported.');
return;
}
navigator.mediaDevices.enumerateDevices().then((devices: MediaDeviceInfo[]) => {
this.videoInputDevices = [];
for (const deviceI of devices) {
// @todo type this as `MediaDeviceInfo`
const device: any = {};
// tslint:disable-next-line:forin
for (const key in deviceI) {
device[key] = deviceI[key];
}
if (device.kind === 'video') {
device.kind = 'videoinput';
}
if (!device.deviceId) {
device.deviceId = (<any>device).id;
}
if (!device.label) {
device.label = 'Camera (no-permission)';
}
if (device.kind === 'videoinput') {
this.videoInputDevices.push(device);
}
}
successCallback(this.videoInputDevices);
});
}
}