@sparkelf/dsh-mobile-bridge-server 0.2.1 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/QR_SCANNER_LICENSE +21 -0
- package/THIRD_PARTY_NOTICES.md +12 -0
- package/ZXING_CPP_LICENSE +201 -0
- package/ZXING_WASM_LICENSE +21 -0
- package/package.json +19 -2
- package/src/phone.ts +603 -19
- package/src/server.ts +153 -17
- package/src/wechat.spec.ts +0 -38
package/src/phone.ts
CHANGED
|
@@ -51,6 +51,18 @@ self.addEventListener('activate', event => { event.waitUntil(self.clients.claim(
|
|
|
51
51
|
self.addEventListener('message', event => {
|
|
52
52
|
if (!event.data) return
|
|
53
53
|
if (event.data.type === 'pair') {
|
|
54
|
+
if (wsValue) wsValue.close(1000, 'pair replaced')
|
|
55
|
+
wsValue = null
|
|
56
|
+
wsPromise = null
|
|
57
|
+
if (!revoked) {
|
|
58
|
+
const replacedError = new Error('pair replaced')
|
|
59
|
+
for (const entry of pending.values()) {
|
|
60
|
+
if (entry.websocketPort) { entry.websocketPort.postMessage({ kind: 'websocket-error', message: replacedError.message }); entry.websocketPort.close() }
|
|
61
|
+
else if (entry.controller) void entry.controller.abort(replacedError)
|
|
62
|
+
else entry.reject(replacedError)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
pending.clear()
|
|
54
66
|
pairValue = event.data.pair
|
|
55
67
|
keyPromise = null
|
|
56
68
|
revoked = false
|
|
@@ -62,6 +74,11 @@ self.addEventListener('message', event => {
|
|
|
62
74
|
}
|
|
63
75
|
if (event.data.type === 'application-websocket') {
|
|
64
76
|
const port = event.ports[0]
|
|
77
|
+
if (revoked) {
|
|
78
|
+
port.start()
|
|
79
|
+
pending.set('q' + (++counter), { websocketPort: port })
|
|
80
|
+
return
|
|
81
|
+
}
|
|
65
82
|
event.waitUntil(openApplicationSocket(event.data, port).catch(error => {
|
|
66
83
|
console.error('[dsh-mobile-bridge] application websocket setup failed', error)
|
|
67
84
|
port.postMessage({ kind: 'websocket-error', message: error.message })
|
|
@@ -70,6 +87,7 @@ self.addEventListener('message', event => {
|
|
|
70
87
|
})
|
|
71
88
|
|
|
72
89
|
let wsPromise = null
|
|
90
|
+
let wsValue = null
|
|
73
91
|
let counter = 0
|
|
74
92
|
const pending = new Map()
|
|
75
93
|
|
|
@@ -77,36 +95,41 @@ function wsReady() {
|
|
|
77
95
|
if (wsPromise) return wsPromise
|
|
78
96
|
wsPromise = new Promise((resolve, reject) => {
|
|
79
97
|
const ws = new WebSocket(location.origin.replace(/^http/, 'ws') + '/ws/client')
|
|
98
|
+
wsValue = ws
|
|
80
99
|
ws.onopen = () => resolve(ws)
|
|
81
100
|
ws.onerror = () => {
|
|
82
|
-
wsPromise = null
|
|
83
101
|
const error = new Error('bridge socket failed')
|
|
84
102
|
console.error('[dsh-mobile-bridge] bridge socket failed', error)
|
|
85
103
|
reject(error)
|
|
86
104
|
}
|
|
87
105
|
ws.onclose = event => {
|
|
106
|
+
const isCurrent = wsValue === ws
|
|
107
|
+
if (!isCurrent) return
|
|
108
|
+
wsValue = null
|
|
88
109
|
wsPromise = null
|
|
89
110
|
const error = new Error('bridge socket closed')
|
|
111
|
+
// 普通传输断开结算请求并触发重连;4003 定向下线保留现有请求为静默终态,直到用户离开 modal。
|
|
90
112
|
const settlePending = () => {
|
|
91
113
|
for (const entry of pending.values()) {
|
|
92
114
|
if (entry.websocketPort) {
|
|
93
|
-
|
|
115
|
+
entry.websocketPort.postMessage({ kind: 'websocket-error', message: error.message })
|
|
94
116
|
entry.websocketPort.close()
|
|
95
|
-
} else if (entry.controller)
|
|
96
|
-
|
|
97
|
-
else entry.reject(error)
|
|
117
|
+
} else if (entry.controller) {
|
|
118
|
+
void entry.controller.abort(error).catch(streamError => { console.error('[dsh-mobile-bridge] event stream settlement failed', streamError) })
|
|
119
|
+
} else entry.reject(error)
|
|
98
120
|
}
|
|
99
121
|
pending.clear()
|
|
100
122
|
}
|
|
101
|
-
if (event.code === 4003) {
|
|
123
|
+
if (event.code === 4003 && isCurrent) {
|
|
102
124
|
pairValue = null
|
|
103
125
|
keyPromise = null
|
|
104
126
|
revoked = true
|
|
105
127
|
void caches.open(PAIR_CACHE).then(cache => cache.put(PAIR_CACHE_KEY, new Response(JSON.stringify({ revoked: true }), { headers: { 'content-type': 'application/json' } }))).catch(error => { console.error('[dsh-mobile-bridge] revoked pair persistence failed', error) })
|
|
106
128
|
void self.clients.matchAll({ type: 'window' })
|
|
107
|
-
.then(clients =>
|
|
108
|
-
|
|
109
|
-
|
|
129
|
+
.then(clients => {
|
|
130
|
+
for (const client of clients) client.postMessage({ type: 'dsh-mobile-bridge:revoked' })
|
|
131
|
+
})
|
|
132
|
+
.catch(error => { console.error('[dsh-mobile-bridge] revoked client notification failed', error) })
|
|
110
133
|
return
|
|
111
134
|
}
|
|
112
135
|
settlePending()
|
|
@@ -190,7 +213,10 @@ self.addEventListener('fetch', event => {
|
|
|
190
213
|
console.error('[dsh-mobile-bridge] persisted pair state failed', error)
|
|
191
214
|
return new Response('Mobile Bridge pair state failed', { status: 500 })
|
|
192
215
|
}
|
|
193
|
-
if (revoked)
|
|
216
|
+
if (revoked) {
|
|
217
|
+
if (event.request.mode === 'navigate') return revokedResponse()
|
|
218
|
+
return new Promise(() => {})
|
|
219
|
+
}
|
|
194
220
|
if (!keyPromise) keyPromise = deriveKey(pair.k ?? '', pair.s)
|
|
195
221
|
const key = await keyPromise
|
|
196
222
|
const request = event.request
|
|
@@ -329,20 +355,20 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
329
355
|
var $ = function (id) { return document.getElementById(id) }
|
|
330
356
|
var COPY = {
|
|
331
357
|
zh: {
|
|
332
|
-
preferences: '显示偏好', title: '移动连接', scanFirst: '
|
|
358
|
+
preferences: '显示偏好', title: '移动连接', scanFirst: '扫描桌面端显示的配对二维码', openScanner: '打开相机扫码', scannerTitle: '扫描配对二维码', closeScanner: '关闭相机', cameraStarting: '正在打开相机', cameraReady: '将二维码放入扫描框', cameraFocused: '正在连续对焦,请将二维码放入扫描框', cameraAdjusting: '正在自动调焦', cameraLocked: '已锁定清晰焦点,请将二维码放入扫描框', qrDetected: '已识别,正在连接', cameraUnavailable: '无法使用相机,请检查浏览器相机权限。', invalidPairQr: '请扫描桌面端显示的 Mobile Bridge 配对二维码。', email: '邮箱', emailPlaceholder: 'name@example.com',
|
|
333
359
|
code: '验证码', codePlaceholder: '6 位验证码', send: '发送', sending: '发送中', sent: '验证码已发送',
|
|
334
360
|
pairingCode: '配对码', pairingPlaceholder: '6 位字符', connect: '登录并连接', connecting: '正在连接', light: '浅色', dark: '深色',
|
|
335
361
|
ownerCode: '桌面所有者邮箱收到验证码,请输入', passphrase: '输入桌面端设置的加密口令', cancelled: '已取消',
|
|
336
|
-
serviceWorkerUnsupported: '此浏览器不支持 Service Worker。', serviceWorkerTimeout: '移动连接初始化超时,请重新扫描最新二维码。',
|
|
362
|
+
serviceWorkerUnsupported: '此浏览器不支持 Service Worker。', serviceWorkerTimeout: '移动连接初始化超时,请重新扫描最新二维码。', serviceWorkerUpdateFailed: '移动连接更新失败,请刷新页面后重新扫描。',
|
|
337
363
|
unknownPair: '配对码无效或桌面端已离线,请扫描最新二维码。', expiredPair: '配对码已过期,请扫描最新二维码。',
|
|
338
364
|
usedPair: '配对码已使用,请扫描最新二维码。', invalidCode: '验证码无效或已过期。'
|
|
339
365
|
},
|
|
340
366
|
en: {
|
|
341
|
-
preferences: 'Display preferences', title: 'Mobile connection', scanFirst: 'Scan the QR code shown on the desktop', email: 'Email', emailPlaceholder: 'name@example.com',
|
|
367
|
+
preferences: 'Display preferences', title: 'Mobile connection', scanFirst: 'Scan the pairing QR shown on the desktop', openScanner: 'Open camera scanner', scannerTitle: 'Scan pairing QR', closeScanner: 'Close camera', cameraStarting: 'Opening camera', cameraReady: 'Place the QR code inside the frame', cameraFocused: 'Continuous focus active. Place the QR code inside the frame', cameraAdjusting: 'Adjusting focus automatically', cameraLocked: 'Sharpest focus locked. Place the QR code inside the frame', qrDetected: 'QR recognized. Connecting', cameraUnavailable: 'The camera is unavailable. Check this browser’s camera permission.', invalidPairQr: 'Scan the Mobile Bridge pairing QR shown on the desktop.', email: 'Email', emailPlaceholder: 'name@example.com',
|
|
342
368
|
code: 'Verification code', codePlaceholder: '6-digit code', send: 'Send', sending: 'Sending', sent: 'Code sent',
|
|
343
369
|
pairingCode: 'Pairing code', pairingPlaceholder: '6 characters', connect: 'Sign in and connect', connecting: 'Connecting', light: 'Light', dark: 'Dark',
|
|
344
370
|
ownerCode: 'Enter the code sent to the desktop owner email', passphrase: 'Enter the passphrase configured on the desktop', cancelled: 'Cancelled',
|
|
345
|
-
serviceWorkerUnsupported: 'This browser does not support Service Workers.', serviceWorkerTimeout: 'Mobile connection setup timed out. Scan the latest QR code again.',
|
|
371
|
+
serviceWorkerUnsupported: 'This browser does not support Service Workers.', serviceWorkerTimeout: 'Mobile connection setup timed out. Scan the latest QR code again.', serviceWorkerUpdateFailed: 'Mobile connection update failed. Refresh the page and scan again.',
|
|
346
372
|
unknownPair: 'The pairing code is invalid or the desktop is offline. Scan the latest QR code.', expiredPair: 'The pairing code expired. Scan the latest QR code.',
|
|
347
373
|
usedPair: 'The pairing code was already used. Scan the latest QR code.', invalidCode: 'The verification code is invalid or expired.'
|
|
348
374
|
}
|
|
@@ -355,6 +381,7 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
355
381
|
document.querySelector('.preferences').setAttribute('aria-label', tr('preferences'))
|
|
356
382
|
document.querySelectorAll('[data-i18n]').forEach(function (node) { node.textContent = tr(node.getAttribute('data-i18n')) })
|
|
357
383
|
document.querySelectorAll('[data-i18n-placeholder]').forEach(function (node) { node.placeholder = tr(node.getAttribute('data-i18n-placeholder')) })
|
|
384
|
+
document.querySelectorAll('[data-i18n-aria-label]').forEach(function (node) { node.setAttribute('aria-label', tr(node.getAttribute('data-i18n-aria-label'))) })
|
|
358
385
|
$('langZh').setAttribute('aria-pressed', String(language === 'zh'))
|
|
359
386
|
$('langEn').setAttribute('aria-pressed', String(language === 'en'))
|
|
360
387
|
}
|
|
@@ -386,6 +413,7 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
386
413
|
if (message === 'invalid or expired code') return tr('invalidCode')
|
|
387
414
|
if (message === 'serviceWorkerUnsupported') return tr('serviceWorkerUnsupported')
|
|
388
415
|
if (message === 'serviceWorkerTimeout') return tr('serviceWorkerTimeout')
|
|
416
|
+
if (message === 'serviceWorkerUpdateFailed') return tr('serviceWorkerUpdateFailed')
|
|
389
417
|
if (message === 'cancelled') return tr('cancelled')
|
|
390
418
|
return message
|
|
391
419
|
}
|
|
@@ -416,18 +444,570 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
416
444
|
registration.active.postMessage({ type: 'pair', pair: pair }, [channel.port2])
|
|
417
445
|
})
|
|
418
446
|
}
|
|
447
|
+
function activateLatestWorker(registration) {
|
|
448
|
+
return registration.update().then(function () {
|
|
449
|
+
var worker = registration.installing || registration.waiting
|
|
450
|
+
if (!worker || worker.state === 'activated') return registration
|
|
451
|
+
return new Promise(function (resolve, reject) {
|
|
452
|
+
var timer = setTimeout(function () {
|
|
453
|
+
worker.removeEventListener('statechange', changed)
|
|
454
|
+
reject(new Error('serviceWorkerTimeout'))
|
|
455
|
+
}, 10000)
|
|
456
|
+
function changed() {
|
|
457
|
+
if (worker.state === 'activated') {
|
|
458
|
+
clearTimeout(timer)
|
|
459
|
+
worker.removeEventListener('statechange', changed)
|
|
460
|
+
resolve(registration)
|
|
461
|
+
} else if (worker.state === 'redundant') {
|
|
462
|
+
clearTimeout(timer)
|
|
463
|
+
worker.removeEventListener('statechange', changed)
|
|
464
|
+
reject(new Error('serviceWorkerUpdateFailed'))
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
worker.addEventListener('statechange', changed)
|
|
468
|
+
changed()
|
|
469
|
+
})
|
|
470
|
+
})
|
|
471
|
+
}
|
|
472
|
+
|
|
419
473
|
function registerSw(pair) {
|
|
420
474
|
if (!('serviceWorker' in navigator)) return Promise.reject(new Error('serviceWorkerUnsupported'))
|
|
421
|
-
return navigator.serviceWorker.register('/sw.js', { scope: '/' })
|
|
475
|
+
return navigator.serviceWorker.register('/sw.js', { scope: '/', updateViaCache: 'none' })
|
|
476
|
+
.then(activateLatestWorker)
|
|
422
477
|
.then(function () { return navigator.serviceWorker.ready })
|
|
423
478
|
.then(function (registration) { return persistPair(registration, pair) })
|
|
424
479
|
.then(waitForControl)
|
|
425
480
|
}
|
|
426
481
|
function navigateToHarness() {
|
|
427
|
-
|
|
428
|
-
|
|
482
|
+
var navigate = function () {
|
|
483
|
+
history.replaceState(null, '', '/')
|
|
484
|
+
location.assign('/')
|
|
485
|
+
}
|
|
486
|
+
if (document.readyState === 'loading') {
|
|
487
|
+
// 先提交 landing 的 DOM 生命周期,再在下一帧切换 Harness,避免两次顶层 navigation 相互取消。
|
|
488
|
+
document.addEventListener('DOMContentLoaded', function () { requestAnimationFrame(navigate) }, { once: true })
|
|
489
|
+
} else navigate()
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
var scannerInstance = null
|
|
493
|
+
var scannerSession = 0
|
|
494
|
+
var scannerStream = null
|
|
495
|
+
var scannerDecodeFrame = 0
|
|
496
|
+
var scannerDecodeUsesVideoCallback = false
|
|
497
|
+
var scannerDecodeBusy = false
|
|
498
|
+
var scannerDecodeFailed = false
|
|
499
|
+
var scannerLastDecodeAt = 0
|
|
500
|
+
var scannerDecodeCanvas = document.createElement('canvas')
|
|
501
|
+
var scannerScriptPromises = {}
|
|
502
|
+
var scannerWasmOverrides = { locateFile: function () { return '/bridge/zxing-reader.wasm' } }
|
|
503
|
+
var scannerResultTimer = 0
|
|
504
|
+
var scannerDiagnosticSocket = null
|
|
505
|
+
var scannerDiagnosticTimer = 0
|
|
506
|
+
var scannerAdjustmentTimer = 0
|
|
507
|
+
var scannerAnalysisCanvas = document.createElement('canvas')
|
|
508
|
+
var scannerAdjustmentIndex = 0
|
|
509
|
+
var scannerAttempts = 0
|
|
510
|
+
var scannerOpenedAt = 0
|
|
511
|
+
var scannerLastError = ''
|
|
512
|
+
|
|
513
|
+
function reportScanner(event, detail) {
|
|
514
|
+
if (!scannerDiagnosticSocket || scannerDiagnosticSocket.readyState !== WebSocket.OPEN) return
|
|
515
|
+
scannerDiagnosticSocket.send(JSON.stringify(Object.assign({ event: event }, detail || {})))
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function scannerTrackSettings() {
|
|
519
|
+
var stream = $('scannerVideo').srcObject
|
|
520
|
+
var track = stream && stream.getVideoTracks()[0]
|
|
521
|
+
return track && typeof track.getSettings === 'function' ? track.getSettings() : {}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function loadScannerScript(source, globalName) {
|
|
525
|
+
if (window[globalName]) return Promise.resolve(window[globalName])
|
|
526
|
+
if (scannerScriptPromises[source]) return scannerScriptPromises[source]
|
|
527
|
+
scannerScriptPromises[source] = new Promise(function (resolve, reject) {
|
|
528
|
+
var script = document.createElement('script')
|
|
529
|
+
script.src = source
|
|
530
|
+
script.onload = function () { resolve(window[globalName]) }
|
|
531
|
+
script.onerror = function () { reject(new Error('Failed to load scanner resource: ' + source)) }
|
|
532
|
+
document.head.appendChild(script)
|
|
533
|
+
})
|
|
534
|
+
return scannerScriptPromises[source]
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function supportsNativeQrDetector() {
|
|
538
|
+
if (typeof window.BarcodeDetector !== 'function' || typeof window.BarcodeDetector.getSupportedFormats !== 'function') return Promise.resolve(false)
|
|
539
|
+
return window.BarcodeDetector.getSupportedFormats()
|
|
540
|
+
.then(function (formats) { return formats.includes('qr_code') })
|
|
541
|
+
.catch(function (error) {
|
|
542
|
+
console.info('[dsh-mobile-bridge] native BarcodeDetector capability check failed', error)
|
|
543
|
+
reportScanner('error', { state: 'barcode-detector', name: error.name, message: error.message, stack: error.stack })
|
|
544
|
+
return false
|
|
545
|
+
})
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// 诊断通道只发送 camera/decoder 结构化状态,不发送相机画面、cookie 或配对文本。
|
|
549
|
+
function startScannerDiagnostics() {
|
|
550
|
+
scannerAttempts = 0
|
|
551
|
+
scannerLastError = ''
|
|
552
|
+
scannerOpenedAt = Date.now()
|
|
553
|
+
scannerDiagnosticSocket = new WebSocket(location.origin.replace(/^http/, 'ws') + '/ws/scanner')
|
|
554
|
+
scannerDiagnosticSocket.onopen = function () {
|
|
555
|
+
reportScanner('open', { state: 'capability-pending' })
|
|
556
|
+
}
|
|
557
|
+
scannerDiagnosticSocket.onerror = function () {
|
|
558
|
+
console.error('[dsh-mobile-bridge] scanner diagnostics socket failed', new Error('Scanner diagnostics WebSocket failed'))
|
|
559
|
+
}
|
|
560
|
+
scannerDiagnosticTimer = setInterval(function () {
|
|
561
|
+
var settings = scannerTrackSettings()
|
|
562
|
+
reportScanner('scan', {
|
|
563
|
+
attempts: scannerAttempts,
|
|
564
|
+
elapsedMs: Date.now() - scannerOpenedAt,
|
|
565
|
+
width: settings.width,
|
|
566
|
+
height: settings.height,
|
|
567
|
+
frameRate: settings.frameRate,
|
|
568
|
+
facingMode: settings.facingMode,
|
|
569
|
+
focusMode: settings.focusMode,
|
|
570
|
+
exposureMode: settings.exposureMode,
|
|
571
|
+
zoom: settings.zoom,
|
|
572
|
+
focusDistance: settings.focusDistance,
|
|
573
|
+
exposureCompensation: settings.exposureCompensation,
|
|
574
|
+
message: scannerLastError
|
|
575
|
+
})
|
|
576
|
+
}, 2000)
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function stopScannerDiagnostics(reason) {
|
|
580
|
+
clearInterval(scannerDiagnosticTimer)
|
|
581
|
+
scannerDiagnosticTimer = 0
|
|
582
|
+
reportScanner('close', { state: reason, attempts: scannerAttempts, elapsedMs: Date.now() - scannerOpenedAt })
|
|
583
|
+
if (scannerDiagnosticSocket) scannerDiagnosticSocket.close(1000, 'scanner closed')
|
|
584
|
+
scannerDiagnosticSocket = null
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// 相机轨道只属于取景页;关闭、识别成功和页面离开都会销毁 scanner 并释放设备。
|
|
588
|
+
function stopScanner(reason) {
|
|
589
|
+
scannerSession += 1
|
|
590
|
+
clearTimeout(scannerResultTimer)
|
|
591
|
+
scannerResultTimer = 0
|
|
592
|
+
clearTimeout(scannerAdjustmentTimer)
|
|
593
|
+
scannerAdjustmentTimer = 0
|
|
594
|
+
stopScannerDiagnostics(reason || 'closed')
|
|
595
|
+
var video = $('scannerVideo')
|
|
596
|
+
if (scannerDecodeFrame) {
|
|
597
|
+
if (scannerDecodeUsesVideoCallback) video.cancelVideoFrameCallback(scannerDecodeFrame)
|
|
598
|
+
else cancelAnimationFrame(scannerDecodeFrame)
|
|
599
|
+
}
|
|
600
|
+
scannerDecodeFrame = 0
|
|
601
|
+
scannerDecodeBusy = false
|
|
602
|
+
scannerDecodeFailed = false
|
|
603
|
+
var activeStream = video.srcObject
|
|
604
|
+
if (activeStream) activeStream.getTracks().forEach(function (track) { track.stop() })
|
|
605
|
+
if (scannerInstance) scannerInstance.destroy()
|
|
606
|
+
scannerInstance = null
|
|
607
|
+
if (scannerStream) scannerStream.getTracks().forEach(function (track) { track.stop() })
|
|
608
|
+
scannerStream = null
|
|
609
|
+
video.srcObject = null
|
|
610
|
+
var frame = $('scannerFrame')
|
|
611
|
+
frame.className = 'scannerFrame'
|
|
612
|
+
frame.removeAttribute('style')
|
|
613
|
+
$('wasmOutlinePolygon').removeAttribute('points')
|
|
614
|
+
$('scanner').hidden = true
|
|
615
|
+
document.body.classList.remove('scannerOpen')
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
function setScannerStatus(key, error) {
|
|
619
|
+
$('scannerStatus').textContent = tr(key)
|
|
620
|
+
$('scannerStatus').classList.toggle('error', error)
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
function scannerRangeValue(range, ratio) {
|
|
624
|
+
var step = typeof range.step === 'number' && range.step > 0 ? range.step : 0.1
|
|
625
|
+
var raw = range.min + (range.max - range.min) * ratio
|
|
626
|
+
return Math.min(range.max, Math.max(range.min, Math.round((raw - range.min) / step) * step + range.min))
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
function scannerSharpness() {
|
|
630
|
+
var video = $('scannerVideo')
|
|
631
|
+
var region = scannerRegion(video)
|
|
632
|
+
var size = 192
|
|
633
|
+
scannerAnalysisCanvas.width = size
|
|
634
|
+
scannerAnalysisCanvas.height = size
|
|
635
|
+
var context = scannerAnalysisCanvas.getContext('2d')
|
|
636
|
+
context.drawImage(video, region.x, region.y, region.width, region.height, 0, 0, size, size)
|
|
637
|
+
var pixels = context.getImageData(0, 0, size, size).data
|
|
638
|
+
var edge = 0
|
|
639
|
+
var clipped = 0
|
|
640
|
+
var samples = 0
|
|
641
|
+
for (var y = 1; y < size; y += 1) {
|
|
642
|
+
for (var x = 1; x < size; x += 1) {
|
|
643
|
+
var offset = (y * size + x) * 4
|
|
644
|
+
var left = offset - 4
|
|
645
|
+
var up = offset - size * 4
|
|
646
|
+
var value = (pixels[offset] + pixels[offset + 1] * 2 + pixels[offset + 2]) / 4
|
|
647
|
+
var leftValue = (pixels[left] + pixels[left + 1] * 2 + pixels[left + 2]) / 4
|
|
648
|
+
var upValue = (pixels[up] + pixels[up + 1] * 2 + pixels[up + 2]) / 4
|
|
649
|
+
edge += Math.abs(value - leftValue) + Math.abs(value - upValue)
|
|
650
|
+
if (value > 248) clipped += 1
|
|
651
|
+
samples += 1
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
return Math.max(0, edge / (samples * 2) - clipped / samples * 80)
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
// 对设备真实支持的焦距各评估一次ROI清晰度,随后锁定最高分,不再无限往返调焦。
|
|
658
|
+
function startScannerAdjustments(track, capabilities) {
|
|
659
|
+
clearTimeout(scannerAdjustmentTimer)
|
|
660
|
+
scannerAdjustmentIndex = 0
|
|
661
|
+
var plans = []
|
|
662
|
+
var focusModes = Array.isArray(capabilities.focusMode) ? capabilities.focusMode : []
|
|
663
|
+
var zoomRange = capabilities.zoom
|
|
664
|
+
var exposureRange = capabilities.exposureCompensation
|
|
665
|
+
var basePlan = {}
|
|
666
|
+
if (zoomRange && typeof zoomRange.min === 'number' && typeof zoomRange.max === 'number' && zoomRange.max > zoomRange.min) {
|
|
667
|
+
var limitedZoom = { min: zoomRange.min, max: Math.min(zoomRange.max, Math.max(zoomRange.min, 1.5)), step: zoomRange.step }
|
|
668
|
+
basePlan.zoom = scannerRangeValue(limitedZoom, 0.5)
|
|
669
|
+
}
|
|
670
|
+
if (exposureRange && typeof exposureRange.min === 'number' && typeof exposureRange.max === 'number' && exposureRange.min < 0) {
|
|
671
|
+
var negativeExposure = { min: exposureRange.min, max: Math.min(0, exposureRange.max), step: exposureRange.step }
|
|
672
|
+
basePlan.exposureCompensation = scannerRangeValue(negativeExposure, 0.45)
|
|
673
|
+
}
|
|
674
|
+
var focusRange = capabilities.focusDistance
|
|
675
|
+
if (focusModes.includes('manual') && focusRange && typeof focusRange.min === 'number' && typeof focusRange.max === 'number' && focusRange.max > focusRange.min) {
|
|
676
|
+
;[0, 0.34, 0.67, 1].forEach(function (ratio) {
|
|
677
|
+
plans.push(Object.assign({}, basePlan, { focusMode: 'manual', focusDistance: scannerRangeValue(focusRange, ratio) }))
|
|
678
|
+
})
|
|
679
|
+
}
|
|
680
|
+
reportScanner('controls', {
|
|
681
|
+
state: plans.length ? 'adjustment-ready' : 'adjustment-unavailable',
|
|
682
|
+
zoomMin: zoomRange && zoomRange.min,
|
|
683
|
+
zoomMax: zoomRange && zoomRange.max,
|
|
684
|
+
focusMin: focusRange && focusRange.min,
|
|
685
|
+
focusMax: focusRange && focusRange.max,
|
|
686
|
+
exposureMin: exposureRange && exposureRange.min,
|
|
687
|
+
exposureMax: exposureRange && exposureRange.max
|
|
688
|
+
})
|
|
689
|
+
if (plans.length === 0) return
|
|
690
|
+
var best = null
|
|
691
|
+
var evaluateNext = function () {
|
|
692
|
+
if (!scannerInstance || scannerResultTimer) return
|
|
693
|
+
if (scannerAdjustmentIndex >= plans.length) {
|
|
694
|
+
if (!best) {
|
|
695
|
+
reportScanner('controls', { state: 'adjustment-failed' })
|
|
696
|
+
return
|
|
697
|
+
}
|
|
698
|
+
track.applyConstraints({ advanced: [best.plan] })
|
|
699
|
+
.then(function () {
|
|
700
|
+
if (!scannerInstance || scannerResultTimer) return
|
|
701
|
+
var settings = scannerTrackSettings()
|
|
702
|
+
setScannerStatus('cameraLocked', false)
|
|
703
|
+
reportScanner('adjustment', { state: 'locked', sharpness: best.score, zoom: settings.zoom, focusDistance: settings.focusDistance, focusMode: settings.focusMode, exposureCompensation: settings.exposureCompensation })
|
|
704
|
+
})
|
|
705
|
+
.catch(function (error) {
|
|
706
|
+
console.info('[dsh-mobile-bridge] camera focus lock failed', error)
|
|
707
|
+
reportScanner('error', { state: 'focus-lock', name: error.name, message: error.message, stack: error.stack })
|
|
708
|
+
})
|
|
709
|
+
return
|
|
710
|
+
}
|
|
711
|
+
var plan = plans[scannerAdjustmentIndex]
|
|
712
|
+
scannerAdjustmentIndex += 1
|
|
713
|
+
track.applyConstraints({ advanced: [plan] })
|
|
714
|
+
.then(function () {
|
|
715
|
+
if (!scannerInstance || scannerResultTimer) return
|
|
716
|
+
scannerAdjustmentTimer = setTimeout(function () {
|
|
717
|
+
if (!scannerInstance || scannerResultTimer) return
|
|
718
|
+
var settings = scannerTrackSettings()
|
|
719
|
+
var score = Math.round(scannerSharpness() * 100) / 100
|
|
720
|
+
if (!best || score > best.score) best = { plan: plan, score: score }
|
|
721
|
+
var label = tr('cameraAdjusting')
|
|
722
|
+
if (typeof settings.zoom === 'number') label += ' · ' + settings.zoom.toFixed(1) + '×'
|
|
723
|
+
$('scannerStatus').textContent = label
|
|
724
|
+
$('scannerStatus').classList.remove('error')
|
|
725
|
+
reportScanner('adjustment', { state: 'sample', sharpness: score, zoom: settings.zoom, focusDistance: settings.focusDistance, focusMode: settings.focusMode, exposureCompensation: settings.exposureCompensation })
|
|
726
|
+
evaluateNext()
|
|
727
|
+
}, 1000)
|
|
728
|
+
})
|
|
729
|
+
.catch(function (error) {
|
|
730
|
+
console.info('[dsh-mobile-bridge] automatic camera adjustment failed', error)
|
|
731
|
+
reportScanner('error', { state: 'adjustment', name: error.name, message: error.message, stack: error.stack })
|
|
732
|
+
evaluateNext()
|
|
733
|
+
})
|
|
734
|
+
}
|
|
735
|
+
scannerAdjustmentTimer = setTimeout(evaluateNext, 1600)
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
// 浏览器能力是相机控制的事实源;先请求高分辨率和曝光,再启动一次性焦点评估。
|
|
739
|
+
function configureScannerTrack() {
|
|
740
|
+
var stream = $('scannerVideo').srcObject
|
|
741
|
+
var track = stream && stream.getVideoTracks()[0]
|
|
742
|
+
if (!track || typeof track.getCapabilities !== 'function' || typeof track.applyConstraints !== 'function') {
|
|
743
|
+
reportScanner('controls', { state: 'capabilities-unavailable' })
|
|
744
|
+
return Promise.resolve(false)
|
|
745
|
+
}
|
|
746
|
+
var capabilities = track.getCapabilities()
|
|
747
|
+
var advanced = {}
|
|
748
|
+
if (Array.isArray(capabilities.focusMode) && capabilities.focusMode.includes('continuous')) advanced.focusMode = 'continuous'
|
|
749
|
+
if (Array.isArray(capabilities.exposureMode) && capabilities.exposureMode.includes('continuous')) advanced.exposureMode = 'continuous'
|
|
750
|
+
if (capabilities.pointsOfInterest) advanced.pointsOfInterest = [{ x: 0.5, y: 0.5 }]
|
|
751
|
+
var exposureRange = capabilities.exposureCompensation
|
|
752
|
+
if (exposureRange && typeof exposureRange.min === 'number' && typeof exposureRange.max === 'number' && exposureRange.min < 0) {
|
|
753
|
+
var negativeExposure = { min: exposureRange.min, max: Math.min(0, exposureRange.max), step: exposureRange.step }
|
|
754
|
+
advanced.exposureCompensation = scannerRangeValue(negativeExposure, 0.45)
|
|
755
|
+
}
|
|
756
|
+
var zoomRange = capabilities.zoom
|
|
757
|
+
if (zoomRange && typeof zoomRange.min === 'number' && typeof zoomRange.max === 'number' && zoomRange.max > zoomRange.min) {
|
|
758
|
+
var limitedZoom = { min: zoomRange.min, max: Math.min(zoomRange.max, Math.max(zoomRange.min, 1.5)), step: zoomRange.step }
|
|
759
|
+
advanced.zoom = scannerRangeValue(limitedZoom, 0.5)
|
|
760
|
+
}
|
|
761
|
+
return (Object.keys(advanced).length === 0 ? Promise.resolve() : track.applyConstraints({ advanced: [advanced] }))
|
|
762
|
+
.catch(function (error) {
|
|
763
|
+
console.info('[dsh-mobile-bridge] initial camera controls unavailable', error)
|
|
764
|
+
reportScanner('error', { state: 'controls', name: error.name, message: error.message, stack: error.stack })
|
|
765
|
+
})
|
|
766
|
+
.then(function () {
|
|
767
|
+
var settings = scannerTrackSettings()
|
|
768
|
+
reportScanner('controls', { state: 'initial-applied', focusMode: settings.focusMode, exposureMode: settings.exposureMode, zoom: settings.zoom, focusDistance: settings.focusDistance, exposureCompensation: settings.exposureCompensation })
|
|
769
|
+
startScannerAdjustments(track, capabilities)
|
|
770
|
+
return settings.focusMode === 'continuous'
|
|
771
|
+
})
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
function relayHostname(hostname) {
|
|
775
|
+
return hostname.startsWith('www.') ? hostname.slice(4) : hostname
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// 摄像头二维码是外部输入;只允许当前 relay 的 www/apex 别名、精确配对路径和 hash。
|
|
779
|
+
function parseScannedPair(value) {
|
|
780
|
+
var target = new URL(value)
|
|
781
|
+
var sameRelay = target.protocol === location.protocol && target.port === location.port && relayHostname(target.hostname) === relayHostname(location.hostname)
|
|
782
|
+
if (!sameRelay || target.pathname !== '/bridge/' || !target.hash) throw new Error('invalidPairQr')
|
|
783
|
+
return target
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
function acceptScannedPair(target) {
|
|
787
|
+
stopScanner('accepted')
|
|
788
|
+
location.assign(target.href)
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
function onScannerResult(result) {
|
|
792
|
+
if (scannerResultTimer) return
|
|
793
|
+
reportScanner('decoded', { corners: result.cornerPoints.length })
|
|
794
|
+
try {
|
|
795
|
+
var target = parseScannedPair(result.data)
|
|
796
|
+
clearTimeout(scannerAdjustmentTimer)
|
|
797
|
+
scannerAdjustmentTimer = 0
|
|
798
|
+
$('scannerFrame').classList.remove('invalid')
|
|
799
|
+
setScannerStatus('qrDetected', false)
|
|
800
|
+
reportScanner('accepted', { valid: true, corners: result.cornerPoints.length })
|
|
801
|
+
scannerResultTimer = setTimeout(function () {
|
|
802
|
+
scannerResultTimer = 0
|
|
803
|
+
acceptScannedPair(target)
|
|
804
|
+
}, 320)
|
|
805
|
+
} catch (error) {
|
|
806
|
+
console.info('[dsh-mobile-bridge] camera QR rejected', error)
|
|
807
|
+
$('scannerFrame').classList.add('invalid')
|
|
808
|
+
setScannerStatus('invalidPairQr', true)
|
|
809
|
+
reportScanner('rejected', { valid: false, corners: result.cornerPoints.length, name: error.name, message: error.message, stack: error.stack })
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
function scannerRegion(video) {
|
|
814
|
+
var size = Math.round(Math.min(video.videoWidth, video.videoHeight) * 2 / 3)
|
|
815
|
+
var outputSize = Math.min(size, 800)
|
|
816
|
+
return {
|
|
817
|
+
x: Math.round((video.videoWidth - size) / 2),
|
|
818
|
+
y: Math.round((video.videoHeight - size) / 2),
|
|
819
|
+
width: size,
|
|
820
|
+
height: size,
|
|
821
|
+
downScaledWidth: outputSize,
|
|
822
|
+
downScaledHeight: outputSize
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
function finishScannerStart(session, profile) {
|
|
827
|
+
return configureScannerTrack().then(function (continuousFocus) {
|
|
828
|
+
if (session !== scannerSession) return false
|
|
829
|
+
var settings = scannerTrackSettings()
|
|
830
|
+
setScannerStatus(continuousFocus ? 'cameraFocused' : 'cameraReady', false)
|
|
831
|
+
reportScanner('camera', {
|
|
832
|
+
state: 'ready',
|
|
833
|
+
name: profile,
|
|
834
|
+
width: settings.width,
|
|
835
|
+
height: settings.height,
|
|
836
|
+
frameRate: settings.frameRate,
|
|
837
|
+
facingMode: settings.facingMode,
|
|
838
|
+
focusMode: settings.focusMode,
|
|
839
|
+
exposureMode: settings.exposureMode,
|
|
840
|
+
zoom: settings.zoom,
|
|
841
|
+
focusDistance: settings.focusDistance,
|
|
842
|
+
exposureCompensation: settings.exposureCompensation
|
|
843
|
+
})
|
|
844
|
+
return true
|
|
845
|
+
})
|
|
429
846
|
}
|
|
430
847
|
|
|
848
|
+
function startNativeScanner(session, QrScanner) {
|
|
849
|
+
if (session !== scannerSession) return Promise.resolve()
|
|
850
|
+
$('scannerFrame').classList.remove('manual')
|
|
851
|
+
scannerInstance = new QrScanner($('scannerVideo'), function (result) {
|
|
852
|
+
scannerAttempts += 1
|
|
853
|
+
onScannerResult(result)
|
|
854
|
+
}, {
|
|
855
|
+
onDecodeError: function (error) {
|
|
856
|
+
scannerAttempts += 1
|
|
857
|
+
scannerLastError = error && error.message ? error.message : String(error)
|
|
858
|
+
},
|
|
859
|
+
preferredCamera: 'environment',
|
|
860
|
+
maxScansPerSecond: 12,
|
|
861
|
+
calculateScanRegion: scannerRegion,
|
|
862
|
+
highlightScanRegion: true,
|
|
863
|
+
highlightCodeOutline: true,
|
|
864
|
+
overlay: $('scannerFrame'),
|
|
865
|
+
returnDetailedScanResult: true
|
|
866
|
+
})
|
|
867
|
+
reportScanner('library', { state: 'ready', name: 'native-barcode-detector' })
|
|
868
|
+
return scannerInstance.start().then(function () { return finishScannerStart(session, 'native-barcode-detector') })
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
function drawWasmOutline(position, size) {
|
|
872
|
+
var points = [position.topLeft, position.topRight, position.bottomRight, position.bottomLeft]
|
|
873
|
+
.map(function (point) { return point.x.toFixed(1) + ',' + point.y.toFixed(1) })
|
|
874
|
+
.join(' ')
|
|
875
|
+
$('wasmOutline').setAttribute('viewBox', '0 0 ' + size + ' ' + size)
|
|
876
|
+
$('wasmOutlinePolygon').setAttribute('points', points)
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
function scheduleWasmScan(session) {
|
|
880
|
+
if (session !== scannerSession || !scannerInstance || scannerDecodeBusy || scannerResultTimer) return
|
|
881
|
+
var video = $('scannerVideo')
|
|
882
|
+
if (typeof video.requestVideoFrameCallback === 'function') {
|
|
883
|
+
scannerDecodeUsesVideoCallback = true
|
|
884
|
+
scannerDecodeFrame = video.requestVideoFrameCallback(function (now) { scanWasmFrame(session, now) })
|
|
885
|
+
} else {
|
|
886
|
+
scannerDecodeUsesVideoCallback = false
|
|
887
|
+
scannerDecodeFrame = requestAnimationFrame(function (now) { scanWasmFrame(session, now) })
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
function scanWasmFrame(session, now) {
|
|
892
|
+
scannerDecodeFrame = 0
|
|
893
|
+
if (session !== scannerSession || !scannerInstance) return
|
|
894
|
+
if (now - scannerLastDecodeAt < 140) { scheduleWasmScan(session); return }
|
|
895
|
+
scannerLastDecodeAt = now
|
|
896
|
+
var video = $('scannerVideo')
|
|
897
|
+
var region = scannerRegion(video)
|
|
898
|
+
var outputSize = Math.min(region.width, 720)
|
|
899
|
+
scannerDecodeCanvas.width = outputSize
|
|
900
|
+
scannerDecodeCanvas.height = outputSize
|
|
901
|
+
var context = scannerDecodeCanvas.getContext('2d')
|
|
902
|
+
context.drawImage(video, region.x, region.y, region.width, region.height, 0, 0, outputSize, outputSize)
|
|
903
|
+
var image = context.getImageData(0, 0, outputSize, outputSize)
|
|
904
|
+
scannerDecodeBusy = true
|
|
905
|
+
scannerAttempts += 1
|
|
906
|
+
window.ZXingWASM.readBarcodes(image, {
|
|
907
|
+
formats: ['QRCode'],
|
|
908
|
+
tryHarder: true,
|
|
909
|
+
tryRotate: true,
|
|
910
|
+
tryInvert: true,
|
|
911
|
+
tryDownscale: false,
|
|
912
|
+
tryDenoise: true,
|
|
913
|
+
binarizer: 'LocalAverage',
|
|
914
|
+
maxNumberOfSymbols: 1
|
|
915
|
+
}).then(function (results) {
|
|
916
|
+
if (session !== scannerSession) return
|
|
917
|
+
var result = results.find(function (candidate) { return candidate.isValid })
|
|
918
|
+
if (!result) {
|
|
919
|
+
scannerLastError = 'No QR code found'
|
|
920
|
+
return
|
|
921
|
+
}
|
|
922
|
+
scannerLastError = ''
|
|
923
|
+
drawWasmOutline(result.position, outputSize)
|
|
924
|
+
onScannerResult({
|
|
925
|
+
data: result.text,
|
|
926
|
+
cornerPoints: [result.position.topLeft, result.position.topRight, result.position.bottomRight, result.position.bottomLeft]
|
|
927
|
+
})
|
|
928
|
+
}).catch(function (error) {
|
|
929
|
+
console.error('[dsh-mobile-bridge] ZXing WASM frame decode failed', error)
|
|
930
|
+
if (session !== scannerSession) return
|
|
931
|
+
scannerDecodeFailed = true
|
|
932
|
+
setScannerStatus('cameraUnavailable', true)
|
|
933
|
+
reportScanner('error', { state: 'zxing-decode', name: error.name, message: error.message, stack: error.stack })
|
|
934
|
+
}).then(function () {
|
|
935
|
+
scannerDecodeBusy = false
|
|
936
|
+
if (session === scannerSession && scannerInstance && !scannerDecodeFailed) scheduleWasmScan(session)
|
|
937
|
+
})
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
function startWasmScanner(session) {
|
|
941
|
+
if (session !== scannerSession) return Promise.resolve()
|
|
942
|
+
var video = $('scannerVideo')
|
|
943
|
+
var frame = $('scannerFrame')
|
|
944
|
+
frame.classList.add('manual')
|
|
945
|
+
reportScanner('library', { state: 'ready', name: 'zxing-wasm' })
|
|
946
|
+
return navigator.mediaDevices.getUserMedia({
|
|
947
|
+
audio: false,
|
|
948
|
+
video: { facingMode: { ideal: 'environment' }, width: { ideal: 1440 }, height: { ideal: 1920 } }
|
|
949
|
+
}).then(function (stream) {
|
|
950
|
+
if (session !== scannerSession) {
|
|
951
|
+
stream.getTracks().forEach(function (track) { track.stop() })
|
|
952
|
+
return false
|
|
953
|
+
}
|
|
954
|
+
scannerStream = stream
|
|
955
|
+
scannerInstance = { destroy: function () {} }
|
|
956
|
+
video.srcObject = stream
|
|
957
|
+
return video.play().then(function () { return true })
|
|
958
|
+
}).then(function (started) {
|
|
959
|
+
if (!started || session !== scannerSession) return
|
|
960
|
+
return finishScannerStart(session, 'zxing-wasm').then(function (ready) {
|
|
961
|
+
if (ready) scheduleWasmScan(session)
|
|
962
|
+
})
|
|
963
|
+
})
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
function openScanner() {
|
|
967
|
+
var session = scannerSession + 1
|
|
968
|
+
scannerSession = session
|
|
969
|
+
scannerDecodeFailed = false
|
|
970
|
+
scannerLastDecodeAt = 0
|
|
971
|
+
$('scanner').hidden = false
|
|
972
|
+
document.body.classList.add('scannerOpen')
|
|
973
|
+
setScannerStatus('cameraStarting', false)
|
|
974
|
+
startScannerDiagnostics()
|
|
975
|
+
supportsNativeQrDetector().then(function (nativeDetector) {
|
|
976
|
+
if (session !== scannerSession) return
|
|
977
|
+
if (nativeDetector) {
|
|
978
|
+
reportScanner('library', { state: 'loading', name: 'qr-scanner' })
|
|
979
|
+
return loadScannerScript('/bridge/qr-scanner.js', 'QrScanner')
|
|
980
|
+
.then(function (QrScanner) { return startNativeScanner(session, QrScanner) })
|
|
981
|
+
}
|
|
982
|
+
reportScanner('library', { state: 'loading', name: 'zxing-wasm' })
|
|
983
|
+
return loadScannerScript('/bridge/zxing-reader.js', 'ZXingWASM')
|
|
984
|
+
.then(function (ZXingWASM) {
|
|
985
|
+
if (session !== scannerSession) return
|
|
986
|
+
return ZXingWASM.prepareZXingModule({
|
|
987
|
+
overrides: scannerWasmOverrides,
|
|
988
|
+
fireImmediately: true
|
|
989
|
+
})
|
|
990
|
+
})
|
|
991
|
+
.then(function () { return startWasmScanner(session) })
|
|
992
|
+
}).catch(function (error) {
|
|
993
|
+
console.error('[dsh-mobile-bridge] camera start failed', error)
|
|
994
|
+
if (session !== scannerSession) return
|
|
995
|
+
var video = $('scannerVideo')
|
|
996
|
+
var activeStream = video.srcObject
|
|
997
|
+
if (activeStream) activeStream.getTracks().forEach(function (track) { track.stop() })
|
|
998
|
+
if (scannerInstance) scannerInstance.destroy()
|
|
999
|
+
scannerInstance = null
|
|
1000
|
+
scannerStream = null
|
|
1001
|
+
video.srcObject = null
|
|
1002
|
+
setScannerStatus('cameraUnavailable', true)
|
|
1003
|
+
reportScanner('error', { state: 'camera-start', name: error.name, message: error.message, stack: error.stack })
|
|
1004
|
+
})
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
$('openScanner').onclick = openScanner
|
|
1008
|
+
$('closeScanner').onclick = function () { stopScanner('closed') }
|
|
1009
|
+
window.addEventListener('pagehide', function () { stopScanner('pagehide') })
|
|
1010
|
+
|
|
431
1011
|
var fragment = location.hash.slice(1)
|
|
432
1012
|
if (fragment) {
|
|
433
1013
|
try {
|
|
@@ -465,8 +1045,12 @@ export const CLIENT_SOURCE = `/* DSH mobile bridge client bootstrap: login, pair
|
|
|
465
1045
|
var stored = localStorage.getItem('dshmb-pair')
|
|
466
1046
|
$('loginForm').hidden = !stored
|
|
467
1047
|
$('scanFirst').hidden = !!stored
|
|
468
|
-
if (!fragment && stored
|
|
469
|
-
|
|
1048
|
+
if (!fragment && stored) {
|
|
1049
|
+
$('x').textContent = tr('connecting')
|
|
1050
|
+
api('/api/me')
|
|
1051
|
+
.then(function () { return registerSw(JSON.parse(stored)) })
|
|
1052
|
+
.then(navigateToHarness)
|
|
1053
|
+
.catch(showError)
|
|
470
1054
|
}
|
|
471
1055
|
$('s').onclick = function () {
|
|
472
1056
|
var button = $('s')
|