@sonicloud/dsh-sonicloud-device 0.1.2 → 0.1.4
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/CHANGELOG.md +44 -1
- package/CHANGELOG.zh.md +44 -1
- package/README.md +36 -11
- package/README.zh.md +26 -1
- package/dist/build.json +1 -1
- package/dist/client.js +1594 -98
- package/docs/contributing/development.md +35 -5
- package/docs/specs/ci-cd.md +5 -4
- package/docs/specs/multilingual.md +98 -0
- package/docs/specs/smart-mouse-plugin.md +31 -1
- package/locale/de.json +7 -0
- package/locale/en.json +7 -0
- package/locale/es.json +7 -0
- package/locale/fr.json +7 -0
- package/locale/ja.json +7 -0
- package/locale/pt.json +7 -0
- package/locale/ru.json +7 -0
- package/locale/zh.json +7 -0
- package/native/README.md +4 -0
- package/native/desktop/VOICE_SOURCE.json +16 -0
- package/native/desktop/VoicePanel.cs +70 -33
- package/native/desktop/VoicePanel.swift +83 -19
- package/native/desktop/darwin-arm64/Sonicloud Voice.app/Contents/MacOS/sonicloud-voice +0 -0
- package/native/desktop/darwin-arm64/Sonicloud Voice.app/Contents/_CodeSignature/CodeResources +115 -0
- package/native/screenshot/README.md +34 -0
- package/native/screenshot/SOURCE.json +218 -0
- package/native/screenshot/darwin-arm64/screentool-macos-1.2.2.zip +0 -0
- package/native/screenshot/patches/hide-cloud-actions.patch +202 -0
- package/native/screenshot/patches/mac-permissions.patch +545 -0
- package/native/screenshot/patches/upstream-files.json +22 -0
- package/native/screenshot/win32-x64/PixPinScrollCapture.dll +0 -0
- package/native/screenshot/win32-x64/Qt5Core.dll +0 -0
- package/native/screenshot/win32-x64/Qt5Gui.dll +0 -0
- package/native/screenshot/win32-x64/Qt5Network.dll +0 -0
- package/native/screenshot/win32-x64/Qt5Svg.dll +0 -0
- package/native/screenshot/win32-x64/Qt5Widgets.dll +0 -0
- package/native/screenshot/win32-x64/iconengines/qsvgicon.dll +0 -0
- package/native/screenshot/win32-x64/imageformats/qjpeg.dll +0 -0
- package/native/screenshot/win32-x64/imageformats/qsvg.dll +0 -0
- package/native/screenshot/win32-x64/libcrypto-1_1-x64.dll +0 -0
- package/native/screenshot/win32-x64/libssl-1_1-x64.dll +0 -0
- package/native/screenshot/win32-x64/msvcp140.dll +0 -0
- package/native/screenshot/win32-x64/platforms/qwindows.dll +0 -0
- package/native/screenshot/win32-x64/qwindowsvistastyle.dll +0 -0
- package/native/screenshot/win32-x64/screenhelper.exe +0 -0
- package/native/screenshot/win32-x64/screentool.dll +0 -0
- package/native/screenshot/win32-x64/vcruntime140.dll +0 -0
- package/native/screenshot/win32-x64/vcruntime140_1.dll +0 -0
- package/package.json +5 -3
- package/src/asr/auth.mjs +9 -8
- package/src/asr/config.mjs +1 -1
- package/src/asr/stream.mjs +25 -24
- package/src/desktop/presentation.mjs +31 -11
- package/src/desktop/screenshot-worker.mjs +226 -0
- package/src/desktop/screenshot.mjs +186 -0
- package/src/devices/actions.mjs +7 -6
- package/src/devices/config.mjs +2 -1
- package/src/devices/diagnostics.mjs +4 -3
- package/src/devices/manager.mjs +72 -37
- package/src/devices/native-worker.mjs +4 -3
- package/src/devices/native.mjs +9 -8
- package/src/devices/queue.mjs +4 -3
- package/src/devices/recognition.mjs +5 -4
- package/src/devices/store.mjs +3 -2
- package/src/devices/translate.mjs +11 -10
- package/src/host/ai-conversation.mjs +8 -7
- package/src/host/index.mjs +12 -3
- package/src/host/locale.mjs +42 -0
- package/src/shared/devices.mjs +13 -12
- package/src/shared/i18n.mjs +47 -0
- package/src/shared/locales/de.json +155 -0
- package/src/shared/locales/en.json +155 -0
- package/src/shared/locales/es.json +155 -0
- package/src/shared/locales/fr.json +155 -0
- package/src/shared/locales/ja.json +155 -0
- package/src/shared/locales/pt.json +155 -0
- package/src/shared/locales/ru.json +155 -0
- package/src/shared/locales/zh.json +155 -0
- package/src/shared/remote.mjs +7 -1
package/src/asr/auth.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { message as msg } from '../shared/i18n.mjs';
|
|
1
2
|
import { BUILTIN_ASR } from './config.mjs';
|
|
2
3
|
import { isStableSn } from '../shared/devices.mjs';
|
|
3
4
|
|
|
4
5
|
export function createTokenRequest({ sn }) {
|
|
5
|
-
if (!isStableSn(sn)) throw new Error('
|
|
6
|
+
if (!isStableSn(sn)) throw new Error(msg('error.device'));
|
|
6
7
|
return { sn };
|
|
7
8
|
}
|
|
8
9
|
|
|
@@ -26,24 +27,24 @@ export function createTokenProvider(config, fetchImpl = globalThis.fetch, lifeti
|
|
|
26
27
|
});
|
|
27
28
|
payload = await response.json();
|
|
28
29
|
} catch (error) {
|
|
29
|
-
if (signal.aborted && !entry.abort.signal.aborted && !lifetime?.aborted) throw new Error('
|
|
30
|
+
if (signal.aborted && !entry.abort.signal.aborted && !lifetime?.aborted) throw new Error(msg('error.timeout'));
|
|
30
31
|
signal.throwIfAborted();
|
|
31
32
|
if (!isStableSn(service.sn)) throw error;
|
|
32
|
-
throw new Error('
|
|
33
|
+
throw new Error(msg('error.auth'));
|
|
33
34
|
}
|
|
34
35
|
signal.throwIfAborted();
|
|
35
36
|
if (!response.ok || payload?.code !== 0) {
|
|
36
37
|
const messages = {
|
|
37
|
-
4001: '
|
|
38
|
-
1002: '
|
|
38
|
+
4001: msg('error.device'), 1001: msg('error.auth'),
|
|
39
|
+
1002: msg('error.auth'), 1008: msg('error.deviceLimit'),
|
|
39
40
|
};
|
|
40
|
-
throw new Error(messages[payload?.code] ?? '
|
|
41
|
+
throw new Error(messages[payload?.code] ?? msg('error.auth'));
|
|
41
42
|
}
|
|
42
43
|
const { token, expire_time: expiry } = payload.data ?? {};
|
|
43
44
|
if (typeof token !== 'string' || !token.trim() || !Number.isSafeInteger(expiry) || expiry <= Date.now() / 1000) {
|
|
44
|
-
throw new Error('
|
|
45
|
+
throw new Error(msg('error.auth'));
|
|
45
46
|
}
|
|
46
|
-
if (entry.generation !== generation) throw new Error('
|
|
47
|
+
if (entry.generation !== generation) throw new Error(msg('error.auth'));
|
|
47
48
|
cachedToken = token; expiresAt = expiry * 1000;
|
|
48
49
|
return token;
|
|
49
50
|
}
|
package/src/asr/config.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export const BUILTIN_ASR = Object.freeze({
|
|
2
|
-
name: '
|
|
2
|
+
name: 'Sonicloud ASR',
|
|
3
3
|
streamUrl: 'wss://openapi.sinicloud.com/talentStreamAsr',
|
|
4
4
|
tokenUrl: 'https://dsh_device.sonicrhino.cc/api/open.sign/generate',
|
|
5
5
|
translateUrl: 'https://openapi.sinicloud.com/v1/translate/text',
|
package/src/asr/stream.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { message as msg } from '../shared/i18n.mjs';
|
|
1
2
|
import WebSocket from 'ws';
|
|
2
3
|
|
|
3
4
|
class Queue {
|
|
@@ -5,7 +6,7 @@ class Queue {
|
|
|
5
6
|
ended = false;
|
|
6
7
|
push(item) {
|
|
7
8
|
if (this.ended) return;
|
|
8
|
-
if (this.items.length >= 256) { this.items = [{ type: 'error', message: '
|
|
9
|
+
if (this.items.length >= 256) { this.items = [{ type: 'error', message: msg('error.audio') }]; this.end(); return; }
|
|
9
10
|
this.items.push(item); this.wake?.();
|
|
10
11
|
}
|
|
11
12
|
end() { this.ended = true; this.wake?.(); }
|
|
@@ -19,12 +20,12 @@ class Queue {
|
|
|
19
20
|
}
|
|
20
21
|
|
|
21
22
|
const errors = {
|
|
22
|
-
'4010': '
|
|
23
|
-
'4011': '
|
|
24
|
-
'4012': '
|
|
25
|
-
'4013': '
|
|
26
|
-
'4014': '
|
|
27
|
-
'-1': '
|
|
23
|
+
'4010': msg('error.auth'),
|
|
24
|
+
'4011': msg('error.quota'),
|
|
25
|
+
'4012': msg('error.auth'),
|
|
26
|
+
'4013': msg('error.busy'),
|
|
27
|
+
'4014': msg('error.auth'), '4015': msg('error.busy'),
|
|
28
|
+
'-1': msg('error.noSpeech'), '16': msg('error.noSpeech'),
|
|
28
29
|
};
|
|
29
30
|
|
|
30
31
|
// The live service also uses numeric strings and code 3 interim / code 10 final frames.
|
|
@@ -56,16 +57,16 @@ export async function* streamRecognition({ service, token, uplink, signal, onAut
|
|
|
56
57
|
socket.terminate();
|
|
57
58
|
};
|
|
58
59
|
const arm = (delay, message) => { clearTimeout(timer); timer = setTimeout(() => fail(message), delay); };
|
|
59
|
-
connectTimer = setTimeout(() => fail('
|
|
60
|
+
connectTimer = setTimeout(() => fail(msg('error.timeout')), connectTimeout);
|
|
60
61
|
const abort = () => { queue.end(); settleReady(false); socket.terminate(); };
|
|
61
62
|
signal.addEventListener('abort', abort, { once: true });
|
|
62
63
|
if (signal.aborted) abort();
|
|
63
|
-
socket.on('error', () => fail('
|
|
64
|
+
socket.on('error', () => fail(msg('error.connection')));
|
|
64
65
|
const transcript = (message, forcedFinal) => {
|
|
65
66
|
const begin = timestamp(message.Begin), end = timestamp(message.End);
|
|
66
67
|
if (!ready || complete || typeof message.result !== 'string' || message.result.length > 4096 ||
|
|
67
68
|
begin === undefined || end === undefined || (end > 0 && end < begin)) {
|
|
68
|
-
fail('
|
|
69
|
+
fail(msg('error.connection')); return false;
|
|
69
70
|
}
|
|
70
71
|
queue.push({ type: 'transcript', text: message.result, begin, end, final: forcedFinal ?? end > 0 });
|
|
71
72
|
return true;
|
|
@@ -73,20 +74,20 @@ export async function* streamRecognition({ service, token, uplink, signal, onAut
|
|
|
73
74
|
socket.on('message', data => {
|
|
74
75
|
if (queue.ended) return;
|
|
75
76
|
let message;
|
|
76
|
-
try { message = JSON.parse(data.toString()); } catch { fail('
|
|
77
|
+
try { message = JSON.parse(data.toString()); } catch { fail(msg('error.connection')); return; }
|
|
77
78
|
const code = String(message?.errCode);
|
|
78
79
|
if (code === '1000') {
|
|
79
80
|
if (ready) return;
|
|
80
81
|
ready = true; clearTimeout(connectTimer);
|
|
81
|
-
arm(idleTimeout, '
|
|
82
|
+
arm(idleTimeout, msg('error.audio')); queue.push({ type: 'ready' });
|
|
82
83
|
settleReady(true);
|
|
83
|
-
} else if (code === '1001') queue.push({ type: 'warning', message: '
|
|
84
|
+
} else if (code === '1001') queue.push({ type: 'warning', message: msg('warning.lowBalance') });
|
|
84
85
|
else if (code === '0') transcript(message);
|
|
85
86
|
else if (code === '3') {
|
|
86
87
|
// End can be nonzero on live rolling results; code 3 is never a final sentence.
|
|
87
88
|
if (Object.hasOwn(message, 'Begin') || Object.hasOwn(message, 'End')) transcript(message, false);
|
|
88
89
|
} else if (code === '10') {
|
|
89
|
-
if (!ended) { fail('
|
|
90
|
+
if (!ended) { fail(msg('error.connection')); return; }
|
|
90
91
|
// Older responses send the final sentence separately with code 0. Newer ones
|
|
91
92
|
// include it in code 10. Do not treat an untimed status message as transcript.
|
|
92
93
|
if ((Object.hasOwn(message, 'Begin') || Object.hasOwn(message, 'End')) && !transcript(message, true)) return;
|
|
@@ -96,12 +97,12 @@ export async function* streamRecognition({ service, token, uplink, signal, onAut
|
|
|
96
97
|
}
|
|
97
98
|
else {
|
|
98
99
|
if (code === '4010') onAuthFailure();
|
|
99
|
-
fail(errors[code] ?? (
|
|
100
|
+
fail(errors[code] ?? msg('error.connection'), code);
|
|
100
101
|
}
|
|
101
102
|
});
|
|
102
103
|
socket.on('close', () => {
|
|
103
104
|
if (queue.ended) return;
|
|
104
|
-
fail('
|
|
105
|
+
fail(msg('error.connection'));
|
|
105
106
|
});
|
|
106
107
|
const input = uplink[Symbol.asyncIterator]();
|
|
107
108
|
const upload = async () => {
|
|
@@ -114,21 +115,21 @@ export async function* streamRecognition({ service, token, uplink, signal, onAut
|
|
|
114
115
|
if (queue.ended || signal.aborted) return;
|
|
115
116
|
if (done) {
|
|
116
117
|
ended = true;
|
|
117
|
-
arm(finalTimeout, '
|
|
118
|
+
arm(finalTimeout, msg('error.timeout'));
|
|
118
119
|
queue.push({ type: 'finishing' });
|
|
119
120
|
socket.send('end'); return;
|
|
120
121
|
}
|
|
121
|
-
if (typeof value !== 'string' || value.length > 4400) throw new Error('
|
|
122
|
+
if (typeof value !== 'string' || value.length > 4400) throw new Error(msg('error.audio'));
|
|
122
123
|
const bytes = Buffer.from(value, 'base64');
|
|
123
|
-
if (bytes.toString('base64') !== value || bytes.length <= 80 || bytes.length > 3200 || bytes.length % 2) throw new Error('
|
|
124
|
+
if (bytes.toString('base64') !== value || bytes.length <= 80 || bytes.length > 3200 || bytes.length % 2) throw new Error(msg('error.audio'));
|
|
124
125
|
totalBytes += bytes.length;
|
|
125
|
-
if (totalBytes > 16_000 * 2 * 600) throw new Error('
|
|
126
|
-
if (socket.bufferedAmount > 320_000) throw new Error('
|
|
127
|
-
socket.send(bytes); arm(idleTimeout, '
|
|
126
|
+
if (totalBytes > 16_000 * 2 * 600) throw new Error(msg('error.duration'));
|
|
127
|
+
if (socket.bufferedAmount > 320_000) throw new Error(msg('error.generic'));
|
|
128
|
+
socket.send(bytes); arm(idleTimeout, msg('error.audio'));
|
|
128
129
|
}
|
|
129
130
|
} catch (error) {
|
|
130
|
-
if (!signal.aborted) fail(error.message === '
|
|
131
|
-
? error.message : '
|
|
131
|
+
if (!signal.aborted) fail(error.message === msg('error.audio') || error.message === msg('error.duration') || error.message === msg('error.generic')
|
|
132
|
+
? error.message : msg('error.audio'));
|
|
132
133
|
}
|
|
133
134
|
};
|
|
134
135
|
void upload();
|
|
@@ -1,22 +1,28 @@
|
|
|
1
|
+
import { message as msg, nativeDictionary, resolveLocale, safeMessage } from '../shared/i18n.mjs';
|
|
1
2
|
import { spawn } from 'node:child_process';
|
|
2
3
|
import { createInterface } from 'node:readline';
|
|
3
4
|
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { chmodSync, existsSync } from 'node:fs';
|
|
4
6
|
|
|
5
7
|
// Private stdio IPC: transcripts never appear in process arguments, files, or logs.
|
|
6
8
|
export class DesktopPresentation {
|
|
7
9
|
constructor({ platform = process.platform, arch = process.arch, launch = spawn, timeoutMs = 10000 } = {}) {
|
|
8
10
|
Object.assign(this, { platform, arch, launch, timeoutMs });
|
|
9
|
-
this.requests = new Map(); this.sequence = 0;
|
|
11
|
+
this.requests = new Map(); this.sequence = 0; this.locale = 'en';
|
|
10
12
|
}
|
|
11
13
|
start() {
|
|
12
|
-
if (this.closed) throw new Error('
|
|
14
|
+
if (this.closed) throw new Error(msg('error.closed'));
|
|
13
15
|
if (this.child) return;
|
|
14
16
|
const root = new URL('../../native/desktop/', import.meta.url);
|
|
15
17
|
let file, args = [];
|
|
16
|
-
if (this.platform === 'darwin')
|
|
18
|
+
if (this.platform === 'darwin') {
|
|
19
|
+
file = fileURLToPath(new URL(`darwin-${this.arch}/Sonicloud Voice.app/Contents/MacOS/sonicloud-voice`, root));
|
|
20
|
+
// Windows 生成的 npm 包不保留 Unix 执行位,启动前恢复随包程序权限。
|
|
21
|
+
if (existsSync(file)) chmodSync(file, 0o755);
|
|
22
|
+
}
|
|
17
23
|
else if (this.platform === 'win32') {
|
|
18
24
|
file = 'powershell.exe'; args = ['-NoProfile', '-NonInteractive', '-STA', '-ExecutionPolicy', 'Bypass', '-File', fileURLToPath(new URL('windows.ps1', root))];
|
|
19
|
-
} else throw new Error('
|
|
25
|
+
} else throw new Error(msg('error.panel'));
|
|
20
26
|
const child = this.launch(file, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
|
|
21
27
|
this.child = child;
|
|
22
28
|
const lines = createInterface({ input: child.stdout });
|
|
@@ -28,31 +34,36 @@ export class DesktopPresentation {
|
|
|
28
34
|
if (pending) {
|
|
29
35
|
clearTimeout(pending.timer); this.requests.delete(message.id);
|
|
30
36
|
if (message.ok) pending.resolve(message.value);
|
|
31
|
-
else pending.reject(new Error('
|
|
37
|
+
else pending.reject(new Error(message.message || msg('error.panel')));
|
|
32
38
|
}
|
|
33
39
|
});
|
|
34
40
|
const failed = () => {
|
|
35
41
|
if (this.child !== child) return;
|
|
36
42
|
this.child = undefined; lines.close();
|
|
37
|
-
for (const { reject, timer } of this.requests.values()) { clearTimeout(timer); reject(new Error('
|
|
43
|
+
for (const { reject, timer } of this.requests.values()) { clearTimeout(timer); reject(new Error(msg('error.panel'))); }
|
|
38
44
|
this.requests.clear();
|
|
39
45
|
if (!this.closed) this.onFault?.();
|
|
40
46
|
};
|
|
41
47
|
child.once('error', failed); child.once('exit', failed);
|
|
42
48
|
child.stdin.on('error', failed);
|
|
43
49
|
child.stderr.resume();
|
|
50
|
+
this.setLocale(this.locale);
|
|
51
|
+
}
|
|
52
|
+
setLocale(locale) {
|
|
53
|
+
this.locale = resolveLocale(locale);
|
|
54
|
+
this.send({ command: 'locale', language: this.locale, dictionary: nativeDictionary(this.locale) });
|
|
44
55
|
}
|
|
45
56
|
send(message) {
|
|
46
57
|
if (!this.child || this.closed) return;
|
|
47
58
|
this.child.stdin.write(JSON.stringify(message) + '\n');
|
|
48
59
|
}
|
|
49
|
-
request(message) {
|
|
60
|
+
request(message, { killOnTimeout = true } = {}) {
|
|
50
61
|
this.start();
|
|
51
62
|
const id = ++this.sequence;
|
|
52
63
|
return new Promise((resolve, reject) => {
|
|
53
64
|
const timer = setTimeout(() => {
|
|
54
|
-
this.requests.delete(id); reject(new Error('
|
|
55
|
-
this.child?.kill();
|
|
65
|
+
this.requests.delete(id); reject(new Error(msg('error.timeout')));
|
|
66
|
+
if (killOnTimeout) this.child?.kill();
|
|
56
67
|
}, this.timeoutMs);
|
|
57
68
|
this.requests.set(id, { resolve, reject, timer }); this.send({ ...message, id });
|
|
58
69
|
});
|
|
@@ -61,19 +72,28 @@ export class DesktopPresentation {
|
|
|
61
72
|
this.sessionId = run.id;
|
|
62
73
|
await this.request({ command: 'begin', sessionId: run.id, action: run.action });
|
|
63
74
|
}
|
|
75
|
+
async permissions(action = 'check') {
|
|
76
|
+
if (!['check', 'accessibility', 'refresh'].includes(action)) throw new Error(msg('error.permission'));
|
|
77
|
+
if (this.closed) throw new Error(msg('error.closed'));
|
|
78
|
+
if (this.platform !== 'darwin') return { supported: false, accessibility: true, helperApp: '' };
|
|
79
|
+
const value = await this.request({ command: 'permissions', action }, { killOnTimeout: false });
|
|
80
|
+
if (!value || value.supported !== true || typeof value.accessibility !== 'boolean' || typeof value.helperApp !== 'string')
|
|
81
|
+
throw new Error(msg('error.permission'));
|
|
82
|
+
return value;
|
|
83
|
+
}
|
|
64
84
|
event(event) {
|
|
65
85
|
if (event.type === 'devices' || event.type === 'request' || event.type === 'result') return;
|
|
66
86
|
if (event.sessionId && event.sessionId !== this.sessionId) return;
|
|
67
87
|
// Do not launch a native window for background device discovery messages.
|
|
68
88
|
if (!this.child) return;
|
|
69
|
-
this.send({ command: 'event', ...event });
|
|
89
|
+
this.send({ command: 'event', ...event, ...(event.message ? { message: safeMessage(event.message) } : {}) });
|
|
70
90
|
}
|
|
71
91
|
async complete(run, text) {
|
|
72
92
|
return this.request({ command: 'result', sessionId: run.id, text });
|
|
73
93
|
}
|
|
74
94
|
async close() {
|
|
75
95
|
this.closed = true;
|
|
76
|
-
for (const { reject, timer } of this.requests.values()) { clearTimeout(timer); reject(new Error('
|
|
96
|
+
for (const { reject, timer } of this.requests.values()) { clearTimeout(timer); reject(new Error(msg('error.closed'))); }
|
|
77
97
|
this.requests.clear();
|
|
78
98
|
const child = this.child; this.child = undefined;
|
|
79
99
|
if (child) await new Promise(resolve => {
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { message as msg } from '../shared/i18n.mjs';
|
|
2
|
+
import koffi from 'koffi';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
|
|
5
|
+
const [libraryPath, helperPath] = process.argv.slice(2);
|
|
6
|
+
if (process.platform === 'win32') process.env.PATH = dirname(libraryPath) + ';' + (process.env.PATH || '');
|
|
7
|
+
const inFlight = new Set();
|
|
8
|
+
const call = (fn, ...args) => {
|
|
9
|
+
const pending = new Promise((resolve, reject) => fn.async(...args, (error, value) => error ? reject(error) : resolve(value)));
|
|
10
|
+
inFlight.add(pending);
|
|
11
|
+
pending.then(() => inFlight.delete(pending), () => inFlight.delete(pending));
|
|
12
|
+
return pending;
|
|
13
|
+
};
|
|
14
|
+
const callbacks = [];
|
|
15
|
+
let api, handle, closing = false, closePromise, connected = false, connection, disconnected, stateRequest;
|
|
16
|
+
let capabilities = new Set();
|
|
17
|
+
let commands = Promise.resolve(), events = Promise.resolve();
|
|
18
|
+
function send(message) {
|
|
19
|
+
if (!process.connected) return;
|
|
20
|
+
try { process.send(message, () => {}); } catch { /* 父进程可能已经退出。 */ }
|
|
21
|
+
}
|
|
22
|
+
const notice = message => { if (!closing) send({ type: 'notice', message }); };
|
|
23
|
+
function finishConnection(error) {
|
|
24
|
+
if (!connection) return;
|
|
25
|
+
clearTimeout(connection.timer);
|
|
26
|
+
const pending = connection; connection = undefined;
|
|
27
|
+
if (error) pending.reject(error); else pending.resolve();
|
|
28
|
+
}
|
|
29
|
+
function finishState(error, value, request = stateRequest) {
|
|
30
|
+
if (!request || stateRequest !== request) return;
|
|
31
|
+
stateRequest = undefined; clearTimeout(request.timer);
|
|
32
|
+
if (error) request.reject(error); else request.resolve(value);
|
|
33
|
+
}
|
|
34
|
+
const errorMessage = rc => rc === -3 ? msg('error.busy')
|
|
35
|
+
: rc === -2 ? msg('error.screenshot') : msg('error.screenshot');
|
|
36
|
+
|
|
37
|
+
// 原生线程回调只保留事件文本并排队;所有 FFI 调用离开回调后异步执行。
|
|
38
|
+
function queueEvent(json) {
|
|
39
|
+
const text = String(json || '');
|
|
40
|
+
setImmediate(() => {
|
|
41
|
+
let event; try { event = JSON.parse(text); } catch { notice(msg('error.screenshot')); return; }
|
|
42
|
+
if (event.type === 'disconnected') {
|
|
43
|
+
connected = false; capabilities = new Set();
|
|
44
|
+
finishState(new Error(msg('error.permission')));
|
|
45
|
+
finishConnection(new Error(msg('error.screenshot')));
|
|
46
|
+
disconnected?.();
|
|
47
|
+
}
|
|
48
|
+
if (closing) return;
|
|
49
|
+
events = events.then(async () => {
|
|
50
|
+
if (closing) return;
|
|
51
|
+
if (['connected', 'disconnected', 'hello_ack', 'session_started', 'session_ended', 'pin_opened', 'pin_closed', 'state_report'].includes(event.type)) {
|
|
52
|
+
send({ type: 'event', event });
|
|
53
|
+
}
|
|
54
|
+
if (event.type === 'connected') {
|
|
55
|
+
const rc = await call(api.config, handle, JSON.stringify({ ocr_visible: false, trans_enabled: false }));
|
|
56
|
+
if (rc !== 0) { connected = false; finishConnection(new Error(msg('error.screenshot'))); return; }
|
|
57
|
+
connected = true; finishConnection();
|
|
58
|
+
} else if (event.type === 'hello_ack') {
|
|
59
|
+
capabilities = new Set(Array.isArray(event.capabilities) ? event.capabilities : []);
|
|
60
|
+
} else if (event.type === 'state_report') {
|
|
61
|
+
finishState(undefined, event);
|
|
62
|
+
} else if (event.type === 'disconnected') {
|
|
63
|
+
connected = false;
|
|
64
|
+
} else if (event.type === 'connect_failed') {
|
|
65
|
+
connected = false;
|
|
66
|
+
const message = event.code === 'stale_helper_refused'
|
|
67
|
+
? msg('error.screenshotBusy') : msg('error.screenshot');
|
|
68
|
+
if (connection) finishConnection(new Error(message)); else notice(message);
|
|
69
|
+
} else if (event.type === 'error' || event.type === 'word_failed') {
|
|
70
|
+
notice(event.code === 'permission_screen_required'
|
|
71
|
+
? msg('error.screenPermission')
|
|
72
|
+
: ['permission_busy', 'permission_request_busy'].includes(event.code) ? msg('error.screenshotBusy')
|
|
73
|
+
: msg('error.permission'));
|
|
74
|
+
} else if (['word_started', 'word_result', 'ocr_requested'].includes(event.type)) {
|
|
75
|
+
notice(msg('error.screenshotExport'));
|
|
76
|
+
}
|
|
77
|
+
}).catch(() => { connected = false; finishConnection(new Error(msg('error.screenshot'))); notice(msg('error.screenshot')); });
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function initialize() {
|
|
82
|
+
const library = koffi.load(libraryPath);
|
|
83
|
+
api = {
|
|
84
|
+
create: library.func('void *sct_create()'),
|
|
85
|
+
destroy: library.func('void sct_destroy_wait(void *h)'),
|
|
86
|
+
setEvent: library.func('int sct_set_event_callback(void *h, void *fn, void *user)'),
|
|
87
|
+
setLog: library.func('int sct_set_log_callback(void *h, void *fn, void *user)'),
|
|
88
|
+
helper: library.func('int sct_set_helper_path(void *h, const char *path)'),
|
|
89
|
+
connect: library.func('int sct_connect_async(void *h, int timeout_ms)'),
|
|
90
|
+
capture: library.func('int sct_start_capture(void *h, const char *trigger)'),
|
|
91
|
+
query: library.func('int sct_query_state(void *h)'),
|
|
92
|
+
config: library.func('int sct_set_config(void *h, const char *json)'),
|
|
93
|
+
shutdown: library.func('int sct_shutdown(void *h, const char *policy)'),
|
|
94
|
+
};
|
|
95
|
+
handle = await call(api.create);
|
|
96
|
+
if (!handle) throw new Error(msg('error.screenshot'));
|
|
97
|
+
const eventProto = koffi.proto('void SonicloudScreenshotEvent(void *user, const char *json, const uint8_t *payload, int len)');
|
|
98
|
+
const logProto = koffi.proto('void SonicloudScreenshotLog(void *user, int level, const char *message)');
|
|
99
|
+
callbacks.push(koffi.register((_user, json) => queueEvent(json), koffi.pointer(eventProto)));
|
|
100
|
+
callbacks.push(koffi.register(() => {}, koffi.pointer(logProto)));
|
|
101
|
+
if (await call(api.setEvent, handle, callbacks[0], null) !== 0 ||
|
|
102
|
+
await call(api.setLog, handle, callbacks[1], null) !== 0 ||
|
|
103
|
+
await call(api.helper, handle, helperPath) !== 0) throw new Error(msg('error.screenshot'));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function ensureConnected() {
|
|
107
|
+
if (closing) throw new Error(msg('error.closed'));
|
|
108
|
+
if (connected) return;
|
|
109
|
+
if (!connection) {
|
|
110
|
+
let resolve, reject;
|
|
111
|
+
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
|
|
112
|
+
connection = { promise, resolve, reject, timer: setTimeout(() => finishConnection(new Error(msg('error.timeout'))), 6500) };
|
|
113
|
+
call(api.connect, handle, 5000).then(rc => { if (rc !== 0) finishConnection(new Error(errorMessage(rc))); },
|
|
114
|
+
() => finishConnection(new Error(msg('error.screenshot'))));
|
|
115
|
+
}
|
|
116
|
+
return connection.promise;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function queryState() {
|
|
120
|
+
if (closing) throw new Error(msg('error.closed'));
|
|
121
|
+
if (stateRequest) return stateRequest.promise;
|
|
122
|
+
let resolve, reject;
|
|
123
|
+
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
|
|
124
|
+
const request = { promise, resolve, reject,
|
|
125
|
+
timer: setTimeout(() => finishState(new Error(msg('error.timeout')), undefined, request), 2500) };
|
|
126
|
+
stateRequest = request;
|
|
127
|
+
call(api.query, handle).then(rc => {
|
|
128
|
+
if (rc !== 0) finishState(new Error(msg('error.permission')), undefined, request);
|
|
129
|
+
}, () => finishState(new Error(msg('error.permission')), undefined, request));
|
|
130
|
+
return promise;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function permissionView(state) {
|
|
134
|
+
if (typeof state.perm_screen !== 'boolean' || typeof state.perm_a11y !== 'boolean')
|
|
135
|
+
throw new Error(msg('error.permission'));
|
|
136
|
+
return { supported: true, screenRecording: state.perm_screen, accessibility: state.perm_a11y,
|
|
137
|
+
helperApp: typeof state.helper_app === 'string' ? state.helper_app.slice(0, 4096) : '' };
|
|
138
|
+
}
|
|
139
|
+
const idle = state => state.capturing === false && state.pins_alive === 0 && state.pin_editing !== true;
|
|
140
|
+
|
|
141
|
+
async function stopHelper() {
|
|
142
|
+
let timer;
|
|
143
|
+
const stopped = new Promise(resolve => {
|
|
144
|
+
disconnected = () => resolve(true);
|
|
145
|
+
timer = setTimeout(() => resolve(false), 2000);
|
|
146
|
+
});
|
|
147
|
+
try {
|
|
148
|
+
const rc = await call(api.shutdown, handle, 'close_now');
|
|
149
|
+
if (rc !== 0) throw new Error(msg('error.permission'));
|
|
150
|
+
if (!await stopped) throw new Error(msg('error.permission'));
|
|
151
|
+
} finally { clearTimeout(timer); disconnected = undefined; }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function permissions(action) {
|
|
155
|
+
if (!['check', 'screen', 'accessibility', 'refresh'].includes(action)) throw new Error(msg('error.permission'));
|
|
156
|
+
if (process.platform !== 'darwin') return { supported: false, screenRecording: true, accessibility: true, helperApp: '' };
|
|
157
|
+
let state = await queryState();
|
|
158
|
+
let view = permissionView(state);
|
|
159
|
+
if (action === 'refresh' && (!view.screenRecording || !view.accessibility) && idle(state)) {
|
|
160
|
+
await stopHelper(); await ensureConnected();
|
|
161
|
+
state = await queryState(); view = permissionView(state);
|
|
162
|
+
}
|
|
163
|
+
if (action === 'screen' || action === 'accessibility') {
|
|
164
|
+
if (!idle(state)) throw new Error(msg('error.screenshotBusy'));
|
|
165
|
+
if (!capabilities.has('permission_preflight')) throw new Error(msg('error.permission'));
|
|
166
|
+
const rc = await call(api.config, handle, JSON.stringify({ permission_request: action }));
|
|
167
|
+
if (rc !== 0) throw new Error(msg('error.permission'));
|
|
168
|
+
// 系统授权由用户完成;写入请求只代表已受理,不能当作已授权。
|
|
169
|
+
}
|
|
170
|
+
return view;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
process.on('message', message => {
|
|
174
|
+
if (message?.command === 'close') { void close(); return; }
|
|
175
|
+
if (closing || !['capture', 'permissions'].includes(message?.command)) return;
|
|
176
|
+
commands = commands.then(async () => {
|
|
177
|
+
await initialized;
|
|
178
|
+
await ensureConnected();
|
|
179
|
+
if (closing) throw new Error(msg('error.closed'));
|
|
180
|
+
if (message.command === 'permissions') {
|
|
181
|
+
const value = await permissions(message.action ?? 'check');
|
|
182
|
+
send({ type: 'reply', requestId: message.requestId, ok: true, value });
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (process.platform === 'darwin' && !permissionView(await queryState()).screenRecording)
|
|
186
|
+
throw new Error(msg('error.screenPermission'));
|
|
187
|
+
const trigger = typeof message.trigger === 'string' ? message.trigger.replace(/[^a-zA-Z0-9_.-]/g, '_').slice(0, 64) : 'ui';
|
|
188
|
+
const rc = await call(api.capture, handle, trigger || 'ui');
|
|
189
|
+
if (rc !== 0) throw new Error(errorMessage(rc));
|
|
190
|
+
send({ type: 'reply', requestId: message.requestId, ok: true });
|
|
191
|
+
}).catch(error => { if (!closing) send({ type: 'reply', requestId: message.requestId, ok: false, message: error.message }); });
|
|
192
|
+
});
|
|
193
|
+
process.on('disconnect', () => { void close(); });
|
|
194
|
+
const initialized = initialize();
|
|
195
|
+
initialized.then(() => { if (!closing) send({ type: 'ready' }); }).catch(() => {
|
|
196
|
+
send({ type: 'fatal' }); void close();
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
function close() {
|
|
200
|
+
if (closePromise) return closePromise;
|
|
201
|
+
closing = true; connected = false;
|
|
202
|
+
finishConnection(new Error(msg('error.closed')));
|
|
203
|
+
finishState(new Error(msg('error.closed')));
|
|
204
|
+
closePromise = (async () => {
|
|
205
|
+
await initialized.catch(() => {});
|
|
206
|
+
await commands.catch(() => {}); await events.catch(() => {});
|
|
207
|
+
// 包含尚未返回的 connect_async FFI 调用,避免销毁与外部调用并发使用句柄。
|
|
208
|
+
await Promise.allSettled([...inFlight]);
|
|
209
|
+
if (handle) {
|
|
210
|
+
let timer;
|
|
211
|
+
const helperExited = new Promise(resolve => { disconnected = resolve; timer = setTimeout(resolve, 2000); });
|
|
212
|
+
try {
|
|
213
|
+
const rc = await call(api.shutdown, handle, 'close_now');
|
|
214
|
+
// 等待 helper 消费退出帧并断开,立即 destroy 会导致已写的帧被丢弃。
|
|
215
|
+
if (rc === 0) await helperExited;
|
|
216
|
+
} catch { /* 断连时仍继续完成销毁屏障。 */ }
|
|
217
|
+
finally { clearTimeout(timer); disconnected = undefined; }
|
|
218
|
+
await call(api.destroy, handle);
|
|
219
|
+
handle = undefined;
|
|
220
|
+
}
|
|
221
|
+
// destroy_wait 已确认原生线程及在途回调全部退出。
|
|
222
|
+
for (const callback of callbacks) koffi.unregister(callback);
|
|
223
|
+
if (process.connected) process.disconnect();
|
|
224
|
+
})().catch(() => { process.exitCode = 1; if (process.connected) process.disconnect(); });
|
|
225
|
+
return closePromise;
|
|
226
|
+
}
|