-
-
Notifications
You must be signed in to change notification settings - Fork 227
/
zxing-scanner.component.ts
567 lines (461 loc) · 15 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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
ElementRef,
EventEmitter,
Inject,
Input,
OnChanges,
OnDestroy,
Output,
PLATFORM_ID,
SimpleChanges,
ViewChild
} from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
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;
/**
* 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 current device used to scan things.
*/
private videoInputDevice: MediaDeviceInfo;
/**
* If the user-agent allowed the use of the camera or not.
*/
private hasPermission: boolean;
/**
* If any media device were found.
*/
private set _hasDevices(hasDevice: boolean) {
this.hasDevices.next(hasDevice);
}
/**
* 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;
/**
* 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>();
/**
* Emitts events when has devices status is update.
*/
@Output()
hasDevices = new EventEmitter<boolean>();
/**
* Constructor to build the object and do some DI.
*/
constructor() {
this.codeReader = new BrowserQRCodeReader();
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.
*/
async ngAfterViewInit(): Promise<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);
const hasPermission = await this.askForPermission();
// @NOTE: look forward to remove these logs below, they may be not needed.
if (hasPermission === false) {
console.warn('zxing-scanner', 'ngAfterViewInit', 'User has denied permission.');
}
if (hasPermission === undefined) {
console.warn('zxing-scanner', 'ngAfterViewInit', 'Permissions not asked.');
}
if (hasPermission === null) {
console.warn('zxing-scanner', 'ngAfterViewInit', 'It was not possible to check for permissions.');
}
// gets and enumerates all video devices
this.enumarateVideoDevices().then((videoInputDevices: MediaDeviceInfo[]) => {
if (videoInputDevices && videoInputDevices.length > 0) {
this._hasDevices = true;
this.camerasFound.next(videoInputDevices);
} else {
this._hasDevices = false;
this.camerasNotFound.next();
}
});
// There's nothin' to do anymore if we don't have permissions.
if (hasPermission !== true) {
return;
}
this.startScan(this.videoInputDevice);
this.codeReader.torchAvailable.subscribe((value: boolean) => {
this.torchCompatible.emit(value);
});
}
/**
* 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);
this.restartScan();
}
/**
* 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.
*/
private setPermission(hasPermission: boolean | null) {
this.hasPermission = hasPermission;
this.permissionResponse.next(hasPermission);
return this.permissionResponse;
}
/**
* Gets and registers all cammeras.
*
* @todo Return a Promise.
*/
async askForPermission(): Promise<boolean> {
if (!this.hasNavigator) {
console.error('zxing-scanner', 'askForPermission', 'Can\'t ask permission, navigator is not present.');
this.setPermission(null);
return this.hasPermission;
}
if (!this.isMediaDevicesSuported) {
console.error('zxing-scanner', 'askForPermission', 'Can\'t get user media, this is not supported.');
this.setPermission(null);
return this.hasPermission;
}
let stream: MediaStream;
try {
// Will try to ask for permission
stream = await navigator.mediaDevices.getUserMedia({ audio: false, video: true });
} catch (err) {
return this.handlePermissionException(err);
}
let permission: boolean;
try {
// Start stream so Browser can display its permission-dialog
this.codeReader.bindVideoSrc(this.previewElemRef.nativeElement, stream);
// After permission was granted, we can stop it again
stream.getVideoTracks().forEach(track => {
track.stop();
});
// should stop the opened stream
this.codeReader.unbindVideoSrc(this.previewElemRef.nativeElement);
// if the scripts lives until here, that's only one mean:
// permission granted
permission = true;
this.setPermission(permission);
} catch (err) {
console.error('zxing-scanner', 'askForPermission', err);
// permission aborted
permission = null;
this.setPermission(permission);
}
// Returns the event emitter, so the dev can subscribe to it
return permission;
}
/**
* Returns the filtered permission.
*
* @param err
*/
private handlePermissionException(err: DOMException): boolean {
// failed to grant permission to video input
console.warn('zxing-scanner', 'askForPermission', err);
let permission: boolean;
switch (err.name) {
// usually caused by not secure origins
case 'DOMException':
case 'NotSupportedError':
// could not claim
permission = null;
// can't check devices
this._hasDevices = null;
break;
// user denied permission
case 'NotAllowedError':
// claimed and denied permission
permission = false;
// this means that input devices exists
this._hasDevices = true;
break;
// the device has no attached input devices
case 'NotFoundError':
// no permissions claimed
permission = null;
// because there was no devices
this._hasDevices = false;
this.camerasNotFound.next(err);
break;
default:
console.warn('@zxing/ngx-scanner', 'I was not able to define if I have permissions for camera or not.');
// unknown
permission = null;
// this._hasDevices = undefined;
break;
}
this.setPermission(permission);
return permission;
}
/**
* Starts the continuous scanning for the given device.
*
* @param deviceId The deviceId from the device.
*/
scan(deviceId: string): void {
try {
this.codeReader.decodeFromInputVideoDevice((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();
}
/**
* Stops and starts back the scan.
*/
restartScan(): void {
this.restartScan();
this.startScan(this.device);
}
/**
* 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.
*/
private async enumarateVideoDevices(): Promise<MediaDeviceInfo[]> {
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;
}
const devices = await navigator.mediaDevices.enumerateDevices();
this.videoInputDevices = [];
for (const device of devices) {
// @todo type this as `MediaDeviceInfo`
const videoDevice: any = {};
// tslint:disable-next-line:forin
for (const key in device) {
videoDevice[key] = device[key];
}
if (videoDevice.kind === 'video') {
videoDevice.kind = 'videoinput';
}
if (!videoDevice.deviceId) {
videoDevice.deviceId = (<any>videoDevice).id;
}
if (!videoDevice.label) {
videoDevice.label = 'Camera (no permission 🚫)';
}
if (videoDevice.kind === 'videoinput') {
this.videoInputDevices.push(videoDevice);
}
}
return this.videoInputDevices;
}
}