@joplo-app/server 0.2.9 → 0.2.12
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/dist/build.d.ts +1 -0
- package/dist/build.js +25 -3
- package/dist/cloud.d.ts +85 -0
- package/dist/cloud.js +110 -0
- package/dist/contract.d.ts +28 -1
- package/dist/dev.d.ts +7 -1
- package/dist/dev.js +79 -5
- package/dist/index.d.ts +1 -1
- package/dist/local-review.d.ts +18 -0
- package/dist/local-review.js +133 -0
- package/dist/render.js +6 -3
- package/dist/voice-http.d.ts +71 -0
- package/dist/voice-http.js +245 -0
- package/dist/voice.d.ts +253 -0
- package/dist/voice.js +637 -0
- package/package.json +4 -4
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import { JoploError, LOCAL_REVIEW_MAX_EVENTS, LOCAL_REVIEW_MAX_FILE_BYTES, LocalReviewSession, localReviewStatus, stateAt } from '@joplo-app/core';
|
|
3
|
+
import { localReviewFile, localReviewWatcherCount, writeLocalReview } from '@joplo-app/core/node';
|
|
4
|
+
/** 对象键的插入顺序不构成新版本;数组顺序属于方案内容。 */
|
|
5
|
+
function stable(value) {
|
|
6
|
+
if (Array.isArray(value))
|
|
7
|
+
return value.map(stable);
|
|
8
|
+
if (value && typeof value === 'object')
|
|
9
|
+
return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, stable(v)]));
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
export function localReviewRevision(project, optionId) {
|
|
13
|
+
const option = project.options[optionId];
|
|
14
|
+
const feature = project.features[option.featureId];
|
|
15
|
+
const own = (values) => Object.fromEntries(Object.entries(values).filter(([, v]) => v.optionId === optionId || (v.optionId == null && (v.featureId == null || v.featureId === option.featureId))));
|
|
16
|
+
const value = { name: project.name, description: project.description, theme: project.theme, themes: project.themes, autoFocus: project.autoFocus,
|
|
17
|
+
feature, option, scenes: own(project.scenes), scenarios: own(project.scenarios), rules: own(project.rules), issues: own(project.issues),
|
|
18
|
+
cases: Object.fromEntries(Object.entries(project.cases).filter(([, c]) => c.featureId === option.featureId)),
|
|
19
|
+
};
|
|
20
|
+
return crypto.createHash('sha256').update(JSON.stringify(stable(value))).digest('hex');
|
|
21
|
+
}
|
|
22
|
+
export function localReviewContext(project, optionId, input) {
|
|
23
|
+
const option = project.options[optionId];
|
|
24
|
+
const scene = project.scenes[input.sceneId];
|
|
25
|
+
if (!option || !scene)
|
|
26
|
+
throw new JoploError('INVALID_REFERENCE', 'Review page or option no longer exists');
|
|
27
|
+
const layerScenes = Object.values(option.layers).map(l => l.sceneId);
|
|
28
|
+
let stepId = null;
|
|
29
|
+
let source = scene.root.source ?? option.source ?? null;
|
|
30
|
+
let scenarioName = null;
|
|
31
|
+
if (input.scenarioId !== null) {
|
|
32
|
+
const scenario = project.scenarios[input.scenarioId];
|
|
33
|
+
if (!scenario || scenario.optionId !== optionId || input.position > scenario.steps.length)
|
|
34
|
+
throw new JoploError('INVALID_REFERENCE', 'Review scenario or step does not belong to this option');
|
|
35
|
+
const state = stateAt(project, scenario.id, input.position);
|
|
36
|
+
if (state.sceneId !== scene.id && !layerScenes.includes(scene.id))
|
|
37
|
+
throw new JoploError('INVALID_REFERENCE', 'Review page is not visible at this step');
|
|
38
|
+
const step = scenario.steps[input.position - 1];
|
|
39
|
+
stepId = step?.id ?? null;
|
|
40
|
+
source = step?.source ?? source;
|
|
41
|
+
scenarioName = scenario.name;
|
|
42
|
+
}
|
|
43
|
+
else if (input.position !== 0 || (scene.optionId !== optionId && !layerScenes.includes(scene.id))) {
|
|
44
|
+
throw new JoploError('INVALID_REFERENCE', 'Review page does not belong to this option');
|
|
45
|
+
}
|
|
46
|
+
return { ...input, route: scene.route, pageTitle: scene.name, stepId, source, scenarioName };
|
|
47
|
+
}
|
|
48
|
+
/** 一个 Hub 是一个不可复用的实例身份;不同 Hub 即使打开同一项目,也写不同的会话文件。 */
|
|
49
|
+
export class LocalReviewHub {
|
|
50
|
+
baseUrl;
|
|
51
|
+
instanceId = crypto.randomUUID();
|
|
52
|
+
current = new Map();
|
|
53
|
+
sessions = new Map();
|
|
54
|
+
constructor(baseUrl) {
|
|
55
|
+
this.baseUrl = baseUrl;
|
|
56
|
+
}
|
|
57
|
+
key(dir, option) { return `${dir}\0${option}`; }
|
|
58
|
+
persist(session) {
|
|
59
|
+
if (!LocalReviewSession.safeParse(session).success)
|
|
60
|
+
throw new JoploError('INVALID_SCHEMA', 'Invalid local review record');
|
|
61
|
+
if (Buffer.byteLength(JSON.stringify(session)) > LOCAL_REVIEW_MAX_FILE_BYTES - (session.events.at(-1)?.type === 'feedback' ? 16_384 : 0))
|
|
62
|
+
throw new JoploError('USAGE', 'Local review storage limit reached. Confirm this review before starting another');
|
|
63
|
+
writeLocalReview(localReviewFile(session.projectDir, session.id), session);
|
|
64
|
+
this.sessions.set(session.id, session);
|
|
65
|
+
this.current.set(this.key(session.projectDir, session.optionId), session);
|
|
66
|
+
return session;
|
|
67
|
+
}
|
|
68
|
+
closeSession(session, reason) {
|
|
69
|
+
if (localReviewStatus(session) !== 'open')
|
|
70
|
+
return;
|
|
71
|
+
this.persist({ ...session, events: [...session.events, { sessionId: session.id, seq: session.events.length + 1, requestId: crypto.randomUUID(), createdAt: new Date().toISOString(), type: 'closed', reason }] });
|
|
72
|
+
}
|
|
73
|
+
sync(dir, projectId, project) {
|
|
74
|
+
for (const s of [...this.current.values()])
|
|
75
|
+
if (s.projectDir === dir && !project.options[s.optionId]) {
|
|
76
|
+
this.closeSession(s, 'option_removed');
|
|
77
|
+
this.current.delete(this.key(dir, s.optionId));
|
|
78
|
+
}
|
|
79
|
+
for (const option of Object.values(project.options)) {
|
|
80
|
+
const revision = localReviewRevision(project, option.id);
|
|
81
|
+
const old = this.current.get(this.key(dir, option.id));
|
|
82
|
+
if (old?.revision === revision && localReviewStatus(old) !== 'closed')
|
|
83
|
+
continue;
|
|
84
|
+
if (old)
|
|
85
|
+
this.closeSession(old, 'source_changed');
|
|
86
|
+
const id = `rv_${crypto.randomBytes(16).toString('hex')}`;
|
|
87
|
+
this.persist({ v: 1, id, instanceId: this.instanceId, ownerPid: process.pid, projectId, projectDir: dir, projectName: project.name,
|
|
88
|
+
featureId: option.featureId, featureName: project.features[option.featureId].name, optionId: option.id, optionName: option.name,
|
|
89
|
+
revision, createdAt: new Date().toISOString(), url: `${this.baseUrl()}#/${encodeURIComponent(projectId)}/f/${encodeURIComponent(option.featureId)}?o=${encodeURIComponent(option.id)}`,
|
|
90
|
+
events: [], });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
invalidate(dir, reason) {
|
|
94
|
+
for (const session of [...this.current.values()])
|
|
95
|
+
if (session.projectDir === dir) {
|
|
96
|
+
this.closeSession(session, reason);
|
|
97
|
+
this.current.delete(this.key(dir, session.optionId));
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
state(dir, optionId) {
|
|
101
|
+
const session = this.current.get(this.key(dir, optionId));
|
|
102
|
+
if (!session)
|
|
103
|
+
throw new JoploError('NOT_FOUND', 'No current review for this option. Wait for a successful compilation');
|
|
104
|
+
return { session, watchers: localReviewWatcherCount(dir, session.id) };
|
|
105
|
+
}
|
|
106
|
+
write(dir, project, input) {
|
|
107
|
+
const session = this.sessions.get(input.sessionId);
|
|
108
|
+
if (!session || session.projectDir !== dir)
|
|
109
|
+
throw new JoploError('NOT_FOUND', 'Review session does not belong to this project and instance');
|
|
110
|
+
const previous = session.events.find(e => e.requestId === input.requestId);
|
|
111
|
+
if (previous) {
|
|
112
|
+
const same = previous.type === input.type && (previous.type !== 'feedback' || input.type === 'feedback' && previous.body === input.body &&
|
|
113
|
+
previous.context.sceneId === input.context.sceneId && previous.context.scenarioId === input.context.scenarioId && previous.context.position === input.context.position);
|
|
114
|
+
if (!same)
|
|
115
|
+
throw new JoploError('IDEMPOTENCY_MISMATCH', 'Request id was already used for different feedback');
|
|
116
|
+
return { session, watchers: localReviewWatcherCount(dir, session.id) };
|
|
117
|
+
}
|
|
118
|
+
if (this.current.get(this.key(dir, session.optionId))?.id !== session.id || localReviewRevision(project, session.optionId) !== session.revision)
|
|
119
|
+
throw new JoploError('REVISION_CONFLICT', 'The option changed. Open its current review before submitting');
|
|
120
|
+
if (input.type === 'approved' && localReviewStatus(session) === 'approved')
|
|
121
|
+
return this.state(dir, session.optionId);
|
|
122
|
+
if (localReviewStatus(session) !== 'open')
|
|
123
|
+
throw new JoploError('REVISION_CONFLICT', 'This review has ended');
|
|
124
|
+
if (input.type === 'feedback' && session.events.length >= LOCAL_REVIEW_MAX_EVENTS - 1)
|
|
125
|
+
throw new JoploError('USAGE', 'This review has reached its feedback limit. Confirm it before starting a new review');
|
|
126
|
+
const base = { sessionId: session.id, seq: session.events.length + 1, requestId: input.requestId, createdAt: new Date().toISOString() };
|
|
127
|
+
const event = input.type === 'feedback'
|
|
128
|
+
? { ...base, type: 'feedback', body: input.body, context: localReviewContext(project, session.optionId, input.context) }
|
|
129
|
+
: { ...base, type: 'approved' };
|
|
130
|
+
this.persist({ ...session, events: [...session.events, event] });
|
|
131
|
+
return this.state(dir, session.optionId);
|
|
132
|
+
}
|
|
133
|
+
}
|
package/dist/render.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import fs from 'node:fs';
|
|
10
10
|
import path from 'node:path';
|
|
11
|
-
import { JoploError, SUBTITLE_HEIGHT, VIEWPORT_SIZE, isAppearanceFont, isAppearanceStroke, displaySceneId, findNode, isNodeDisabled, nodeLabel, positionAfterStep, resolveProps, stateAt, walkNodes } from '@joplo-app/core';
|
|
11
|
+
import { JoploError, SUBTITLE_HEIGHT, VIEWPORT_SIZE, isAppearanceFont, isAppearanceStroke, displaySceneId, findNode, isNodeDisabled, nodeLabel, positionAfterStep, resolveProps, scopeProject, stateAt, walkNodes } from '@joplo-app/core';
|
|
12
12
|
import { exportLocale } from "./locale.js";
|
|
13
13
|
import { createDev } from "./dev.js";
|
|
14
14
|
import { realProjectDir } from "./vite-shared.js";
|
|
@@ -92,11 +92,14 @@ export async function renderStep(opts) {
|
|
|
92
92
|
let browser = null;
|
|
93
93
|
try {
|
|
94
94
|
const payload = server.payload();
|
|
95
|
-
|
|
96
|
-
if (!project) {
|
|
95
|
+
if (!payload.project) {
|
|
97
96
|
const errs = payload.diagnostics.filter((d) => d.severity === 'error');
|
|
98
97
|
throw new JoploError('INVALID_SCHEMA', `Project compilation failed: ${errs.map((d) => `${d.at ?? ''} ${d.message}`).join('; ')}`, { diagnostics: payload.diagnostics });
|
|
99
98
|
}
|
|
99
|
+
// 按场景保密分享(D75):渲染页从同一个 payload 读 IR,替换成裁剪后的(watch: false,不会被重新编译覆盖)
|
|
100
|
+
if (opts.scope?.length)
|
|
101
|
+
payload.project = scopeProject(payload.project, opts.scope, 'publish').project;
|
|
102
|
+
const project = payload.project;
|
|
100
103
|
const sc = project.scenarios[opts.scenarioId];
|
|
101
104
|
if (!sc)
|
|
102
105
|
throw new JoploError('NOT_FOUND', `Scenario does not exist: ${opts.scenarioId} (available: ${Object.keys(project.scenarios).join(', ') || 'none'})`);
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type http from 'node:http';
|
|
2
|
+
import type { Project } from '@joplo-app/core';
|
|
3
|
+
import { ProfileStore, type FetchLike, type PublicProfile } from './voice.js';
|
|
4
|
+
export type VoiceState = {
|
|
5
|
+
/**
|
|
6
|
+
* 版本:每次算状态时递增(以微秒时钟为下限,dev 重启后也不会变小)。看板只接受 rev 不比当前小的状态:
|
|
7
|
+
* 推送、选择 / 生成的返回、profilesChanged 之后的重新读取可能乱序到达,晚到的旧状态不能覆盖新的。
|
|
8
|
+
*/
|
|
9
|
+
rev: number;
|
|
10
|
+
/** 看板里选的 profile(config 写了 voice.profile 时以 config 为准,见 source)。 */
|
|
11
|
+
selected: string | null;
|
|
12
|
+
source: 'config' | 'board' | null;
|
|
13
|
+
/** config 里写了、本机没有的 profile 名。 */
|
|
14
|
+
missing: string | null;
|
|
15
|
+
profile: PublicProfile | null;
|
|
16
|
+
/** 旁白与各角色的声音指纹(网页用 clipKey 找音频)。 */
|
|
17
|
+
voices: {
|
|
18
|
+
narrator: string | null;
|
|
19
|
+
roles: Record<string, string>;
|
|
20
|
+
};
|
|
21
|
+
narrator: string | null;
|
|
22
|
+
roles: Record<string, string>;
|
|
23
|
+
/** 片段键 → 音频地址。 */
|
|
24
|
+
clips: Record<string, string>;
|
|
25
|
+
/** 片段键 → 失败原因。 */
|
|
26
|
+
failures: Record<string, {
|
|
27
|
+
stepId: string;
|
|
28
|
+
message: string;
|
|
29
|
+
}>;
|
|
30
|
+
generating: {
|
|
31
|
+
done: number;
|
|
32
|
+
total: number;
|
|
33
|
+
failed: number;
|
|
34
|
+
} | null;
|
|
35
|
+
};
|
|
36
|
+
type Ctx = {
|
|
37
|
+
guardWrite: (needJson?: boolean) => boolean;
|
|
38
|
+
jsonBody: () => Promise<{
|
|
39
|
+
ok: true;
|
|
40
|
+
body: unknown;
|
|
41
|
+
} | {
|
|
42
|
+
ok: false;
|
|
43
|
+
}>;
|
|
44
|
+
send: (status: number, body: unknown) => void;
|
|
45
|
+
};
|
|
46
|
+
/** 用户目录写成 ~(看板显示 profile 存在哪里;不在用户目录下时原样)。 */
|
|
47
|
+
export declare function tildify(file: string, home?: string): string;
|
|
48
|
+
export declare class VoiceHub {
|
|
49
|
+
private readonly opts;
|
|
50
|
+
readonly store: ProfileStore;
|
|
51
|
+
private jobs;
|
|
52
|
+
/** 正在生成的段:项目 → (片段键 → 结果)。批量生成与边放边生成共用,同一段只请求一次。 */
|
|
53
|
+
private inflight;
|
|
54
|
+
private inflightOf;
|
|
55
|
+
constructor(home: string, opts: {
|
|
56
|
+
emit: (projectId: string, state: VoiceState) => void;
|
|
57
|
+
profilesChanged?: () => void;
|
|
58
|
+
fetch?: FetchLike;
|
|
59
|
+
env?: Record<string, string | undefined>;
|
|
60
|
+
});
|
|
61
|
+
private profiles;
|
|
62
|
+
private error;
|
|
63
|
+
/** /__joplo/voice/<rest>;不认识的路径返回 false。 */
|
|
64
|
+
handleGlobal(rest: string, req: http.IncomingMessage, ctx: Ctx): Promise<boolean>;
|
|
65
|
+
state(projectId: string, dir: string, project: Project | null): VoiceState;
|
|
66
|
+
/** /__joplo/p/:id/voice[/…];不认识的路径返回 false。 */
|
|
67
|
+
handleProject(projectId: string, dir: string, project: Project | null, rest: string, req: http.IncomingMessage, res: http.ServerResponse, ctx: Ctx): Promise<boolean>;
|
|
68
|
+
/** 关闭看板时停掉正在生成的任务。 */
|
|
69
|
+
close(): void;
|
|
70
|
+
}
|
|
71
|
+
export {};
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 朗读(D74)的看板接口。写接口都经 dev.ts 的 guardWrite(Origin + 本机令牌 + JSON)。
|
|
3
|
+
*
|
|
4
|
+
* 全局(本机):
|
|
5
|
+
* - GET /__joplo/voice/profiles → { profiles: PublicProfile[], file }(不含 Key;file = 本机存储文件,所有项目共用)
|
|
6
|
+
* - PUT /__joplo/voice/profiles/:id|new { profile, key? } → { profile, profiles }(key:省略 = 不改,null / '' = 删掉)
|
|
7
|
+
* - DELETE /__joplo/voice/profiles/:id → { profiles }(自建的删除,预设恢复默认)
|
|
8
|
+
* 保存、删除成功后调 opts.profilesChanged:dev.ts 推 joplo:voice { profilesChanged },打开着的看板重新取自己项目的声音状态
|
|
9
|
+
* (Key 是否保存、音色、声音指纹都可能变了)。
|
|
10
|
+
* - POST /__joplo/voice/test { id?, profile?, key?, text? } → { ok: true, audio: data URL, bytes, contentType }
|
|
11
|
+
* | { ok: false, error: { code, message, hint? } }(hint = 建议的返回内容与字段路径)
|
|
12
|
+
* 项目:
|
|
13
|
+
* - GET /__joplo/p/:id/voice → VoiceState
|
|
14
|
+
* - PUT /__joplo/p/:id/voice { profileId | null } → VoiceState(看板里选的,记在 .joplo/voice/index.json)
|
|
15
|
+
* - POST /__joplo/p/:id/voice/clip { locale, segment: { stepId, text, role } } → { key, url }(边放边生成一段;与批量生成共用 inflight,同一段并发只生成一次)
|
|
16
|
+
* - POST /__joplo/p/:id/voice/generate { locale, segments: [{ stepId, text, role }] } → { summary, state };进度推 joplo:voice
|
|
17
|
+
* - GET /__joplo/p/:id/voice/clips/:file → 音频
|
|
18
|
+
*/
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import os from 'node:os';
|
|
21
|
+
import path from 'node:path';
|
|
22
|
+
import { AUDIO_TYPES, ProfileStore, VoiceCache, VoiceError, normalizeProfile, resolveVoices, synthesize } from "./voice.js";
|
|
23
|
+
const MAX_SEGMENTS = 2000;
|
|
24
|
+
let lastRev = 0;
|
|
25
|
+
const nextRev = () => (lastRev = Math.max(lastRev + 1, Date.now() * 1000));
|
|
26
|
+
/** 用户目录写成 ~(看板显示 profile 存在哪里;不在用户目录下时原样)。 */
|
|
27
|
+
export function tildify(file, home = os.homedir()) {
|
|
28
|
+
return home && (file === home || file.startsWith(home + path.sep)) ? '~' + file.slice(home.length) : file;
|
|
29
|
+
}
|
|
30
|
+
const MAX_TEXT = 2000;
|
|
31
|
+
export class VoiceHub {
|
|
32
|
+
opts;
|
|
33
|
+
store;
|
|
34
|
+
jobs = new Map();
|
|
35
|
+
/** 正在生成的段:项目 → (片段键 → 结果)。批量生成与边放边生成共用,同一段只请求一次。 */
|
|
36
|
+
inflight = new Map();
|
|
37
|
+
inflightOf(projectId) {
|
|
38
|
+
let m = this.inflight.get(projectId);
|
|
39
|
+
if (!m)
|
|
40
|
+
this.inflight.set(projectId, (m = new Map()));
|
|
41
|
+
return m;
|
|
42
|
+
}
|
|
43
|
+
constructor(home, opts) {
|
|
44
|
+
this.opts = opts;
|
|
45
|
+
this.store = new ProfileStore(home, opts.env ?? process.env);
|
|
46
|
+
}
|
|
47
|
+
profiles = () => this.store.list().map((p) => this.store.publicOf(p));
|
|
48
|
+
error(ctx, e) {
|
|
49
|
+
if (e instanceof VoiceError)
|
|
50
|
+
return ctx.send(e.code === 'NOT_FOUND' ? 404 : e.code === 'BUSY' ? 409 : 400, { error: { code: e.code, message: e.message, ...(e.hint ? { hint: e.hint } : {}) } });
|
|
51
|
+
throw e;
|
|
52
|
+
}
|
|
53
|
+
/** /__joplo/voice/<rest>;不认识的路径返回 false。 */
|
|
54
|
+
async handleGlobal(rest, req, ctx) {
|
|
55
|
+
const method = req.method ?? 'GET';
|
|
56
|
+
if (rest === 'profiles' && method === 'GET')
|
|
57
|
+
return ctx.send(200, { profiles: this.profiles(), file: tildify(this.store.file) }), true;
|
|
58
|
+
const pm = /^profiles\/([a-z0-9][a-z0-9_-]{0,39}|new)$/.exec(rest);
|
|
59
|
+
if (pm && method === 'PUT') {
|
|
60
|
+
if (!ctx.guardWrite())
|
|
61
|
+
return true;
|
|
62
|
+
const b = await ctx.jsonBody();
|
|
63
|
+
if (!b.ok)
|
|
64
|
+
return true;
|
|
65
|
+
const body = (b.body ?? {});
|
|
66
|
+
try {
|
|
67
|
+
const key = body.key === undefined ? undefined : body.key === null ? null : typeof body.key === 'string' ? body.key : (() => { throw new VoiceError('INVALID', 'key must be a string or null'); })();
|
|
68
|
+
const saved = this.store.upsert(pm[1] === 'new' ? null : pm[1], body.profile, key);
|
|
69
|
+
ctx.send(200, { profile: this.store.publicOf(saved), profiles: this.profiles() });
|
|
70
|
+
this.opts.profilesChanged?.();
|
|
71
|
+
}
|
|
72
|
+
catch (e) {
|
|
73
|
+
this.error(ctx, e);
|
|
74
|
+
}
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
if (pm && pm[1] !== 'new' && method === 'DELETE') {
|
|
78
|
+
if (!ctx.guardWrite(false))
|
|
79
|
+
return true;
|
|
80
|
+
try {
|
|
81
|
+
this.store.remove(pm[1]);
|
|
82
|
+
ctx.send(200, { profiles: this.profiles() });
|
|
83
|
+
this.opts.profilesChanged?.();
|
|
84
|
+
}
|
|
85
|
+
catch (e) {
|
|
86
|
+
this.error(ctx, e);
|
|
87
|
+
}
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
if (rest === 'test' && method === 'POST') {
|
|
91
|
+
if (!ctx.guardWrite())
|
|
92
|
+
return true;
|
|
93
|
+
const b = await ctx.jsonBody();
|
|
94
|
+
if (!b.ok)
|
|
95
|
+
return true;
|
|
96
|
+
const body = (b.body ?? {});
|
|
97
|
+
try {
|
|
98
|
+
const saved = typeof body.id === 'string' ? this.store.get(body.id) : null;
|
|
99
|
+
if (typeof body.id === 'string' && !saved)
|
|
100
|
+
throw new VoiceError('NOT_FOUND', `Unknown voice profile: ${body.id}`);
|
|
101
|
+
// 草稿(还没保存的表单)优先;没传 Key 时用已保存的 / 环境变量里的
|
|
102
|
+
const draft = body.profile !== undefined ? { ...(saved ?? { id: 'draft' }), ...normalizeProfile(body.profile, saved ?? undefined), id: saved?.id ?? 'draft', ...(saved?.preset ? { preset: saved.preset } : {}) } : saved;
|
|
103
|
+
if (!draft)
|
|
104
|
+
throw new VoiceError('INVALID', 'Pass id or profile');
|
|
105
|
+
const key = typeof body.key === 'string' && body.key.trim() ? body.key.trim() : this.store.keyOf(saved ? { ...draft, key: saved.key } : draft);
|
|
106
|
+
if (!key && draft.kind !== 'http')
|
|
107
|
+
throw new VoiceError('NO_KEY', 'No API key: paste one, or set the environment variable shown next to the key field');
|
|
108
|
+
const text = typeof body.text === 'string' && body.text.trim() ? body.text.trim().slice(0, 200) : 'Hello, this is the Joplo narrator.';
|
|
109
|
+
const a = await synthesize(draft, key, text, draft.voice, { fetch: this.opts.fetch });
|
|
110
|
+
ctx.send(200, { ok: true, contentType: a.contentType, bytes: a.bytes.length, audio: `data:${a.contentType};base64,${a.bytes.toString('base64')}` });
|
|
111
|
+
}
|
|
112
|
+
catch (e) {
|
|
113
|
+
if (e instanceof VoiceError && e.code !== 'NOT_FOUND')
|
|
114
|
+
return ctx.send(200, { ok: false, error: { code: e.code, message: e.message, ...(e.hint ? { hint: e.hint } : {}) } }), true;
|
|
115
|
+
this.error(ctx, e);
|
|
116
|
+
}
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
state(projectId, dir, project) {
|
|
122
|
+
const cache = new VoiceCache(dir);
|
|
123
|
+
const idx = cache.read();
|
|
124
|
+
const r = resolveVoices(project?.voiceConfig, idx.profileId, this.store);
|
|
125
|
+
const cur = cache.current(r.voices);
|
|
126
|
+
const job = this.jobs.get(projectId);
|
|
127
|
+
const enc = encodeURIComponent;
|
|
128
|
+
return {
|
|
129
|
+
rev: nextRev(),
|
|
130
|
+
selected: idx.profileId,
|
|
131
|
+
source: r.source,
|
|
132
|
+
missing: r.missing,
|
|
133
|
+
profile: r.profile ? this.store.publicOf(r.profile) : null,
|
|
134
|
+
voices: r.voices,
|
|
135
|
+
narrator: r.narrator,
|
|
136
|
+
roles: r.roles,
|
|
137
|
+
clips: Object.fromEntries(Object.entries(cur.clips).map(([k, f]) => [k, `/__joplo/p/${enc(projectId)}/voice/clips/${f}`])),
|
|
138
|
+
failures: cur.failures,
|
|
139
|
+
generating: job ? { done: job.done, total: job.total, failed: job.failed } : null,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
/** /__joplo/p/:id/voice[/…];不认识的路径返回 false。 */
|
|
143
|
+
async handleProject(projectId, dir, project, rest, req, res, ctx) {
|
|
144
|
+
const method = req.method ?? 'GET';
|
|
145
|
+
if (rest === '' && method === 'GET')
|
|
146
|
+
return ctx.send(200, this.state(projectId, dir, project)), true;
|
|
147
|
+
if (rest === '' && method === 'PUT') {
|
|
148
|
+
if (!ctx.guardWrite())
|
|
149
|
+
return true;
|
|
150
|
+
const b = await ctx.jsonBody();
|
|
151
|
+
if (!b.ok)
|
|
152
|
+
return true;
|
|
153
|
+
const id = b.body?.profileId;
|
|
154
|
+
if (id !== null && (typeof id !== 'string' || !this.store.get(id)))
|
|
155
|
+
return ctx.send(400, { error: { code: 'USAGE', message: `Unknown voice profile: ${String(id)}` } }), true;
|
|
156
|
+
new VoiceCache(dir).select(id);
|
|
157
|
+
const st = this.state(projectId, dir, project);
|
|
158
|
+
this.opts.emit(projectId, st);
|
|
159
|
+
return ctx.send(200, st), true;
|
|
160
|
+
}
|
|
161
|
+
if (rest === 'generate' && method === 'POST') {
|
|
162
|
+
if (!ctx.guardWrite())
|
|
163
|
+
return true;
|
|
164
|
+
const b = await ctx.jsonBody();
|
|
165
|
+
if (!b.ok)
|
|
166
|
+
return true;
|
|
167
|
+
const body = (b.body ?? {});
|
|
168
|
+
const segs = Array.isArray(body.segments) ? body.segments : null;
|
|
169
|
+
const ok = segs && segs.length <= MAX_SEGMENTS && segs.every((s) => s && typeof s.stepId === 'string' && typeof s.text === 'string' && s.text.length <= MAX_TEXT && (s.role === null || typeof s.role === 'string'));
|
|
170
|
+
if (!ok)
|
|
171
|
+
return ctx.send(400, { error: { code: 'USAGE', message: `segments must be up to ${MAX_SEGMENTS} items of { stepId, text, role }` } }), true;
|
|
172
|
+
if (this.jobs.has(projectId))
|
|
173
|
+
return ctx.send(409, { error: { code: 'BUSY', message: 'Narration is already being generated for this project' } }), true;
|
|
174
|
+
const cache = new VoiceCache(dir);
|
|
175
|
+
const resolved = resolveVoices(project?.voiceConfig, cache.read().profileId, this.store);
|
|
176
|
+
const job = { done: 0, total: segs.length, failed: 0, abort: new AbortController() };
|
|
177
|
+
this.jobs.set(projectId, job);
|
|
178
|
+
let summary;
|
|
179
|
+
try {
|
|
180
|
+
summary = await cache.generate(segs, typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'en', resolved, this.store, {
|
|
181
|
+
fetch: this.opts.fetch,
|
|
182
|
+
signal: job.abort.signal,
|
|
183
|
+
inflight: this.inflightOf(projectId),
|
|
184
|
+
onProgress: (done, total, failed) => {
|
|
185
|
+
Object.assign(job, { done, total, failed });
|
|
186
|
+
this.opts.emit(projectId, this.state(projectId, dir, project));
|
|
187
|
+
},
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
finally {
|
|
191
|
+
this.jobs.delete(projectId);
|
|
192
|
+
}
|
|
193
|
+
const st = this.state(projectId, dir, project);
|
|
194
|
+
this.opts.emit(projectId, st);
|
|
195
|
+
return ctx.send(200, { summary, state: st }), true;
|
|
196
|
+
}
|
|
197
|
+
if (rest === 'clip' && method === 'POST') {
|
|
198
|
+
// 边放边生成:播放到这一步(或预取后面几步)时只生成这一段;同一段同时只生成一次
|
|
199
|
+
if (!ctx.guardWrite())
|
|
200
|
+
return true;
|
|
201
|
+
const b = await ctx.jsonBody();
|
|
202
|
+
if (!b.ok)
|
|
203
|
+
return true;
|
|
204
|
+
const body = (b.body ?? {});
|
|
205
|
+
const seg = body.segment;
|
|
206
|
+
if (!seg || typeof seg.stepId !== 'string' || typeof seg.text !== 'string' || seg.text.length > MAX_TEXT || (seg.role !== null && typeof seg.role !== 'string'))
|
|
207
|
+
return ctx.send(400, { error: { code: 'USAGE', message: 'segment must be { stepId, text, role }' } }), true;
|
|
208
|
+
const cache = new VoiceCache(dir);
|
|
209
|
+
const resolved = resolveVoices(project?.voiceConfig, cache.read().profileId, this.store);
|
|
210
|
+
const plan = cache.plan(seg, resolved);
|
|
211
|
+
if (!plan)
|
|
212
|
+
return ctx.send(400, { error: { code: 'INVALID', message: 'No voice provider is selected for this project' } }), true;
|
|
213
|
+
const p = cache.generateOne(seg, typeof body.locale === 'string' ? body.locale.slice(0, 20) : 'en', resolved, this.store, { fetch: this.opts.fetch, inflight: this.inflightOf(projectId) });
|
|
214
|
+
try {
|
|
215
|
+
const r = await p;
|
|
216
|
+
if (r.generated)
|
|
217
|
+
this.opts.emit(projectId, this.state(projectId, dir, project));
|
|
218
|
+
return ctx.send(200, { key: r.key, url: `/__joplo/p/${encodeURIComponent(projectId)}/voice/clips/${r.file}` }), true;
|
|
219
|
+
}
|
|
220
|
+
catch (e) {
|
|
221
|
+
this.opts.emit(projectId, this.state(projectId, dir, project));
|
|
222
|
+
return this.error(ctx, e), true;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const cm = /^clips\/([^/]+)$/.exec(rest);
|
|
226
|
+
if (cm && (method === 'GET' || method === 'HEAD')) {
|
|
227
|
+
const f = new VoiceCache(dir).fileOf(cm[1]);
|
|
228
|
+
if (!f)
|
|
229
|
+
return ctx.send(404, { error: { code: 'NOT_FOUND', message: 'No such audio clip' } }), true;
|
|
230
|
+
const ext = cm[1].split('.').pop();
|
|
231
|
+
const size = fs.statSync(f).size;
|
|
232
|
+
res.writeHead(200, { 'content-type': AUDIO_TYPES[ext], 'content-length': size, 'cache-control': 'private, max-age=31536000, immutable', 'x-content-type-options': 'nosniff' });
|
|
233
|
+
if (method === 'HEAD')
|
|
234
|
+
return res.end(), true;
|
|
235
|
+
fs.createReadStream(f).pipe(res);
|
|
236
|
+
return true;
|
|
237
|
+
}
|
|
238
|
+
return false;
|
|
239
|
+
}
|
|
240
|
+
/** 关闭看板时停掉正在生成的任务。 */
|
|
241
|
+
close() {
|
|
242
|
+
for (const j of this.jobs.values())
|
|
243
|
+
j.abort.abort();
|
|
244
|
+
}
|
|
245
|
+
}
|