Pick recording servers from the voice-changer app; fix per-server recording status

consent-recorder: operators (ADMIN_DISCORD_IDS) create an app key on the
site; the app calls GET/POST /api/guilds with it to turn servers on/off.
Turned-off servers are left immediately. recordingNow() now checks the
user picked that server, so someone who only chose server A is not shown
as recorded while sitting in a B channel the bot records for others.

voice-changer: new "녹음 서버" dialog (record_servers.py), network in a
worker thread, key saved in config/record-servers.json; upgrade cleanup
list knows the new file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-11-11 21:16:53 +09:00
parent f45d349f96
commit 32ad429773
14 changed files with 473 additions and 8 deletions

View File

@@ -9,6 +9,8 @@ PUBLIC_URL=https://voice.example.com
OPERATOR_NAME=사금향
# 녹음할 디스코드 서버 아이디 (쉼표로 여러 개). 비우면 봇이 들어간 모든 서버
ALLOWED_GUILD_IDS=
# 음성 변환기 앱에서 녹음할 서버를 켜고 끌 수 있는 디스코드 아이디 (쉼표로 여러 개). 사이트에 로그인하면 "앱 연결 키"를 만들 수 있다
ADMIN_DISCORD_IDS=293719842274541579
HOST=127.0.0.1
PORT=8787
DATA_DIR=./data

View File

@@ -12,6 +12,7 @@
서버마다 음성 연결은 하나라서 한 서버에서 동의자가 여러 채널에 흩어져 있으면 지금 채널 유지 → 방금 움직인 사람 → 동의자가 많은 채널 순으로 고른다 (`src/follow.ts`).
- 녹음 (`src/recorder.ts`): 디스코드가 사람별로 따로 보내는 음성 스트림 중 **동의한 사람 것만 구독**한다. 동의 안 한 사람의 소리는 받지도 저장하지도 않는다.
말이 0.8초 끊길 때마다 파일 하나(최대 30초, 0.5초 미만 버림), Opus 그대로 `data/recordings/<아이디>/<날짜>/<id>.ogg`. 말하는 도중 철회하면 쓰던 파일도 버린다.
- 운영자 (`ADMIN_DISCORD_IDS`): 사이트에서 **앱 연결 키**를 만들고, 음성 변환기 앱의 "녹음 서버" 화면에서 그 키로 봇이 녹음할 서버를 켜고 끈다 (`GET/POST /api/guilds`, `Authorization: Bearer <키>`, 키는 해시로만 저장, 새로 만들면 예전 키는 무효). 끈 서버에서는 바로 나간다. `.env` 의 `ALLOWED_GUILD_IDS` 밖의 서버는 앱에서도 켤 수 없다.
- 알림: 봇이 채널에 들어가면 그 채널 채팅에 녹음 안내(누구 목소리만 녹음하는지 + 사이트 주소)를 남기고, 봇 상태를 "🔴 동의한 사람 녹음 중"으로 바꾼다.
- 동의 기록: `consent_log` 테이블에 동의 · 철회 · 삭제 · 내보내기를 시각과 문구 버전으로 남긴다. 동의 문구를 바꾸면 `src/consent-text.ts` 의 `CONSENT_VERSION` 을 올린다 → 예전 동의자는 다시 동의할 때까지 녹음하지 않는다.
- 보안: OAuth state 는 로그인을 시작한 브라우저 쿠키와 맞춰 확인, 동의 제출은 화면의 문구 버전이 지금 버전과 같을 때만, 세션 · state 는 해시로만 저장, 디스코드 액세스 토큰은 저장하지 않음, 모든 form 에 CSRF 토큰 + Origin 확인, 클릭재킹 차단(`frame-ancestors 'none'`, `X-Frame-Options: DENY`), https 쿠키는 `__Host-` + Secure.

View File

@@ -84,6 +84,7 @@ export class FollowBot {
recordingNow(userId: string): string | null {
for (const [gid, r] of this.recorders) {
const g = this.client.guilds.cache.get(gid);
if (!this.store.isConsentedIn(userId, gid)) continue; // 이 서버는 녹음하지 않기로 한 사람 (다른 동의자를 녹음 중인 채널에 같이 있어도)
if (g?.voiceStates.cache.get(userId)?.channelId === r.channelId) return g.channels.cache.get(r.channelId)?.name ?? '음성채널';
}
return null;
@@ -95,8 +96,22 @@ export class FollowBot {
this.queue.set(guild.id, next);
}
/** .env 의 ALLOWED_GUILD_IDS 안에 있고, 운영자가 앱에서 끄지 않은 서버 */
private allowedGuild(guild: Guild): boolean {
return !this.cfg.allowedGuildIds.size || this.cfg.allowedGuildIds.has(guild.id);
return (!this.cfg.allowedGuildIds.size || this.cfg.allowedGuildIds.has(guild.id)) && this.store.guildEnabled(guild.id);
}
/** 운영자가 켜고 끌 수 있는 서버 (봇이 들어가 있고 ALLOWED_GUILD_IDS 안에 있는 곳) */
adminGuilds(): { id: string; name: string; enabled: boolean }[] {
return [...this.client.guilds.cache.values()]
.filter((g) => !this.cfg.allowedGuildIds.size || this.cfg.allowedGuildIds.has(g.id))
.map((g) => ({ id: g.id, name: g.name, enabled: this.store.guildEnabled(g.id) }))
.sort((a, b) => a.name.localeCompare(b.name, 'ko'));
}
/** 운영자가 서버를 켜고 끈 직후: 끈 서버에서는 바로 나가고, 켠 서버에는 동의자가 있으면 따라 들어간다 */
guildSettingsChanged(): void {
for (const g of this.client.guilds.cache.values()) this.schedule(g);
}
private canJoin(ch: VoiceBasedChannel): boolean {

View File

@@ -13,6 +13,8 @@ export interface Config {
operatorName: string;
/** 비어 있으면 봇이 들어간 모든 서버 */
allowedGuildIds: Set<string>;
/** 앱 연결 키를 만들어 녹음할 서버를 켜고 끌 수 있는 디스코드 아이디 */
adminIds: Set<string>;
channelNotice: boolean;
/** 테스트에서 가짜 디스코드 API 로 바꿀 때만 */
discordApi: string;
@@ -52,6 +54,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env, needBot = true)
dataDir: path.resolve(env.DATA_DIR?.trim() || './data'),
operatorName: env.OPERATOR_NAME?.trim() || '사금향',
allowedGuildIds: new Set((env.ALLOWED_GUILD_IDS ?? '').split(',').map((s) => s.trim()).filter(Boolean)),
adminIds: new Set((env.ADMIN_DISCORD_IDS ?? '').split(',').map((s) => s.trim()).filter(Boolean)),
channelNotice: (env.CHANNEL_NOTICE ?? '1') !== '0',
discordApi: env.DISCORD_API?.trim() || 'https://discord.com/api/v10',
discordAuthorizeUrl: env.DISCORD_AUTHORIZE_URL?.trim() || 'https://discord.com/oauth2/authorize',

View File

@@ -73,6 +73,17 @@ export class Store {
guild_id TEXT NOT NULL,
PRIMARY KEY (user_id, guild_id)
);
-- 운영자가 음성 변환기 앱에서 끈 서버 (줄이 없으면 켜짐)
CREATE TABLE IF NOT EXISTS guild_settings (
guild_id TEXT PRIMARY KEY,
enabled INTEGER NOT NULL
);
-- 음성 변환기 앱 연결 키 (운영자 한 사람당 하나, 해시만 저장)
CREATE TABLE IF NOT EXISTS app_keys (
user_id TEXT PRIMARY KEY,
key_hash TEXT NOT NULL UNIQUE,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS recordings (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
@@ -165,6 +176,43 @@ export class Store {
return this.db.prepare('SELECT action, version, at, detail FROM consent_log WHERE user_id = ? ORDER BY id').all(userId) as any;
}
// ---- 운영자: 녹음할 서버 · 앱 연결 키 ----
/** 운영자가 끄지 않은 서버면 true (처음에는 모두 켜짐) */
guildEnabled(guildId: string): boolean {
const r = this.db.prepare('SELECT enabled FROM guild_settings WHERE guild_id = ?').get(guildId) as { enabled: number } | undefined;
return !r || r.enabled === 1;
}
setGuildEnabled(byUser: string, settings: Record<string, boolean>, now = Date.now()): void {
const up = this.db.prepare(
'INSERT INTO guild_settings (guild_id, enabled) VALUES (?, ?) ON CONFLICT(guild_id) DO UPDATE SET enabled = excluded.enabled',
);
for (const [g, on] of Object.entries(settings)) up.run(g, on ? 1 : 0);
const on = Object.keys(settings).filter((g) => settings[g]).sort();
this.log(byUser, 'admin_guilds', now, `on=${on.join(',')}`);
}
/** 새 앱 연결 키 (예전 키는 바로 못 쓰게 됨). 화면에 한 번만 보여 준다 */
newAppKey(userId: string, now = Date.now()): string {
const key = `vc_${crypto.randomBytes(24).toString('base64url')}`;
this.db
.prepare('INSERT INTO app_keys (user_id, key_hash, created_at) VALUES (?, ?, ?) ON CONFLICT(user_id) DO UPDATE SET key_hash = excluded.key_hash, created_at = excluded.created_at')
.run(userId, sha256(key), now);
this.log(userId, 'app_key', now);
return key;
}
appKeyUser(key: string): string | undefined {
const r = this.db.prepare('SELECT user_id FROM app_keys WHERE key_hash = ?').get(sha256(key)) as { user_id: string } | undefined;
return r?.user_id;
}
appKeyCreatedAt(userId: string): number | undefined {
const r = this.db.prepare('SELECT created_at FROM app_keys WHERE user_id = ?').get(userId) as { created_at: number } | undefined;
return r ? Number(r.created_at) : undefined;
}
// ---- 녹음 ----
addRecording(r: RecordingRow): void {

View File

@@ -13,6 +13,8 @@ const site = createSite(cfg, store, {
discardActive: (id) => bot.discardActive(id),
recordingNow: (id) => bot.recordingNow(id),
userGuilds: (id) => bot.userGuilds(id),
adminGuilds: () => bot.adminGuilds(),
guildSettingsChanged: () => bot.guildSettingsChanged(),
});
site.listen(cfg.port, cfg.host, () => console.log(`[site] ${cfg.publicUrl} (http://${cfg.host}:${cfg.port})`));

View File

@@ -13,6 +13,10 @@ export interface SiteHooks {
recordingNow(userId: string): string | null;
/** 봇과 이 사람이 함께 들어가 있는 서버 (녹음할 서버로 고를 수 있는 곳) */
userGuilds(userId: string): Promise<{ id: string; name: string }[]>;
/** 운영자가 켜고 끌 수 있는 서버 (음성 변환기 앱의 "녹음 서버" 화면) */
adminGuilds(): { id: string; name: string; enabled: boolean }[];
/** 운영자가 서버를 켜고 끈 직후 */
guildSettingsChanged(): void;
}
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]!);
@@ -29,7 +33,7 @@ button,.btn{display:inline-block;border:0;border-radius:10px;padding:11px 18px;f
button.danger{background:var(--danger)}button.ghost{background:transparent;color:var(--muted);padding:6px 0}
.status{font-weight:700}.status.on{color:var(--ok)}.status.off{color:var(--muted)}.rec{color:var(--danger);font-weight:700}
.err{background:#fde7e9;color:#8a1c1c;border-radius:10px;padding:10px 14px}
form.inline{display:inline}fieldset{border:0;padding:0;margin:12px 0}legend{font-weight:700;padding:0}
form.inline{display:inline}code.key{display:block;word-break:break-all;background:var(--bg);border-radius:8px;padding:10px 12px;font-size:15px;user-select:all}fieldset{border:0;padding:0;margin:12px 0}legend{font-weight:700;padding:0}
`;
function page(title: string, body: string): string {
@@ -58,6 +62,10 @@ function cookies(req: http.IncomingMessage): Record<string, string> {
}
async function readForm(req: http.IncomingMessage): Promise<URLSearchParams> {
return new URLSearchParams(await readBody(req));
}
async function readBody(req: http.IncomingMessage): Promise<string> {
const chunks: Buffer[] = [];
let size = 0;
for await (const c of req) {
@@ -65,7 +73,7 @@ async function readForm(req: http.IncomingMessage): Promise<URLSearchParams> {
if (size > 16 * 1024) throw new HttpError(413, '요청이 너무 큽니다');
chunks.push(c as Buffer);
}
return new URLSearchParams(Buffer.concat(chunks).toString('utf8'));
return Buffer.concat(chunks).toString('utf8');
}
class HttpError extends Error {
@@ -122,6 +130,28 @@ export function createSite(cfg: Config, store: Store, hooks: SiteHooks): http.Se
return { ...cur, form };
}
const isAdmin = (userId: string) => cfg.adminIds.has(userId);
/** 음성 변환기 앱 → 사이트. Authorization: Bearer <앱 연결 키>, 키 주인이 지금도 운영자여야 한다 */
function appUser(req: http.IncomingMessage): string {
const m = /^Bearer (\S+)$/.exec(req.headers.authorization ?? '');
const user = m ? store.appKeyUser(m[1]) : undefined;
if (!user || !isAdmin(user)) throw new HttpError(401, '앱 연결 키가 맞지 않습니다');
return user;
}
const json = (res: http.ServerResponse, status: number, data: unknown) => send(res, status, JSON.stringify(data), 'application/json; charset=utf-8');
/** 운영자 화면: 음성 변환기 앱 연결 키 */
function adminCard(s: SessionRow, csrf: string, newKey?: string): string {
if (!isAdmin(s.user_id)) return '';
const made = store.appKeyCreatedAt(s.user_id);
return `<div class="card"><h2>음성 변환기 앱 연결 (운영자)</h2>
<p>음성 변환기 앱의 <b>녹음 서버</b> 화면에 이 사이트 주소와 앱 연결 키를 넣으면, 앱에서 봇이 녹음할 서버를 켜고 끌 수 있습니다.</p>
${newKey ? `<p>새 앱 연결 키 (이 화면에서 한 번만 보입니다. 앱에 붙여 넣으세요):</p><p><code class="key">${esc(newKey)}</code></p>` : made ? `<p class="muted">${fmtTime(made)}에 만든 키를 쓰고 있습니다. 새로 만들면 예전 키는 바로 못 씁니다.</p>` : ''}
<form method="post" action="/app-key">${csrf}<button type="submit">${made ? '앱 연결 키 새로 만들기' : '앱 연결 키 만들기'}</button></form></div>`;
}
function landing(error?: string): string {
return page(
'목소리 녹음 동의',
@@ -149,7 +179,7 @@ ${guilds.map((g) => `<label class="check"><input type="checkbox" name="guild" va
return picked;
}
async function home(s: SessionRow, error?: string): Promise<string> {
async function home(s: SessionRow, error?: string, newKey?: string): Promise<string> {
const guilds = await hooks.userGuilds(s.user_id);
const picked = new Set(store.consentGuilds(s.user_id));
const pickedNames = guilds.filter((g) => picked.has(g.id)).map((g) => esc(g.name));
@@ -186,6 +216,7 @@ ${error ? `<p class="err">${esc(error)}</p>` : ''}
<div class="card">${status}<p>녹음된 내 목소리: <b>${stats.count}개 · ${fmtDur(stats.total_ms)}</b></p>
${stats.count ? `<form method="post" action="/delete" class="inline">${csrf}<button class="danger" type="submit">녹음 파일 모두 삭제</button></form>` : ''}</div>
${consentForm}
${adminCard(s, csrf, newKey)}
<form method="post" action="/logout">${csrf}<button class="ghost" type="submit">로그아웃</button></form>`,
);
}
@@ -271,6 +302,31 @@ ${consentForm}
store.deleteRecordings(s.user_id);
return redirect(res, '/');
}
case 'POST /app-key': {
const { s } = await authedForm(req);
if (!isAdmin(s.user_id)) throw new HttpError(403, '운영자만 만들 수 있습니다');
return send(res, 200, await home(s, undefined, store.newAppKey(s.user_id)));
}
case 'GET /api/guilds': {
appUser(req);
return json(res, 200, { guilds: hooks.adminGuilds() });
}
case 'POST /api/guilds': {
const user = appUser(req);
let body: { enabled?: unknown };
try {
body = JSON.parse(await readBody(req));
} catch {
throw new HttpError(400, 'JSON 이 아닙니다');
}
if (!Array.isArray(body?.enabled) || !body.enabled.every((g) => typeof g === 'string')) throw new HttpError(400, 'enabled 는 서버 아이디 목록이어야 합니다');
const known = hooks.adminGuilds();
const on = new Set(body.enabled as string[]);
if ([...on].some((g) => !known.some((k) => k.id === g))) throw new HttpError(400, '봇이 들어가 있지 않은 서버입니다');
store.setGuildEnabled(user, Object.fromEntries(known.map((g) => [g.id, on.has(g.id)])));
hooks.guildSettingsChanged();
return json(res, 200, { guilds: hooks.adminGuilds() });
}
case 'POST /logout': {
const { sid } = await authedForm(req);
store.endSession(sid);
@@ -285,7 +341,8 @@ ${consentForm}
handle(req, res).catch((e) => {
const status = e instanceof HttpError ? e.status : 500;
if (!(e instanceof HttpError)) console.error('[site] 오류', e);
if (!res.headersSent) send(res, status, landing(e instanceof HttpError ? e.message : '서버 오류가 났습니다. 잠시 뒤 다시 해 주세요.'));
if (!res.headersSent && req.url?.startsWith('/api/')) json(res, status, { error: e instanceof HttpError ? e.message : '서버 오류' });
else if (!res.headersSent) send(res, status, landing(e instanceof HttpError ? e.message : '서버 오류가 났습니다. 잠시 뒤 다시 해 주세요.'));
else res.end();
});
});

View File

@@ -55,3 +55,39 @@ test('녹음할 서버로 고르지 않은 서버에서는 동의자라도 따
await bot.client.destroy();
store.close();
});
test('녹음 중 표시는 그 서버를 고른 사람에게만 (다른 동의자를 녹음 중인 채널에 같이 있어도)', async () => {
const store = new Store(':memory:');
store.consent({ id: 'u1', username: 'a' });
store.consent({ id: 'u3', username: 'c' });
store.setConsentGuilds('u1', ['g']);
store.setConsentGuilds('u3', ['other']);
const cfg = loadConfig({ PUBLIC_URL: 'http://localhost', DISCORD_CLIENT_ID: 'c', DISCORD_CLIENT_SECRET: 's' }, false);
const bot = new FollowBot(cfg, store);
const guild = fakeGuild();
guild.voiceStates.cache.set('u3', { id: 'u3', channelId: 'A', member: { user: { bot: false } } });
guild.channels = { cache: new Map([['A', { name: 'A채널' }]]) };
(bot.client.guilds.cache as any).set('g', guild);
(bot as any).recorders.set('g', { channelId: 'A' });
assert.equal(bot.recordingNow('u1'), 'A채널');
assert.equal(bot.recordingNow('u3'), null);
(bot as any).recorders.clear();
(bot.client.guilds.cache as any).clear();
await bot.client.destroy();
store.close();
});
test('운영자가 앱에서 끈 서버는 따라가지 않는다', async () => {
const store = new Store(':memory:');
const cfg = loadConfig({ PUBLIC_URL: 'http://localhost', DISCORD_CLIENT_ID: 'c', DISCORD_CLIENT_SECRET: 's' }, false);
const bot = new FollowBot(cfg, store);
const guild = { ...fakeGuild(), name: '서버' };
(bot.client.guilds.cache as any).set('g', guild);
assert.equal((bot as any).allowedGuild(guild), true); // 처음에는 켜짐
store.setGuildEnabled('admin', { g: false });
assert.equal((bot as any).allowedGuild(guild), false);
assert.deepEqual(bot.adminGuilds(), [{ id: 'g', name: '서버', enabled: false }]);
(bot.client.guilds.cache as any).clear();
await bot.client.destroy();
store.close();
});

View File

@@ -18,6 +18,8 @@ let base = '';
let tmp = '';
const changed: string[] = [];
const events: string[] = [];
const guildOn: Record<string, boolean> = {};
let settingsChanged = 0;
before(async () => {
tmp = fs.mkdtempSync(path.join(os.homedir(), '.tmp-consent-'));
@@ -46,7 +48,7 @@ before(async () => {
site.close();
base = `http://127.0.0.1:${port}`;
const cfg = loadConfig(
{ PUBLIC_URL: base, DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec', DATA_DIR: tmp, OPERATOR_NAME: '승한', DISCORD_API: `http://127.0.0.1:${dport}` },
{ PUBLIC_URL: base, DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec', DATA_DIR: tmp, OPERATOR_NAME: '승한', ADMIN_DISCORD_IDS: USER.id, DISCORD_API: `http://127.0.0.1:${dport}` },
false,
);
site = createSite(cfg, store, {
@@ -57,6 +59,8 @@ before(async () => {
{ id: 'g1', name: '첫째 서버' },
{ id: 'g2', name: '둘째 서버' },
],
adminGuilds: () => ['g1', 'g2'].map((id) => ({ id, name: id, enabled: store.guildEnabled(id) })),
guildSettingsChanged: () => settingsChanged++,
});
await new Promise<void>((r) => site.listen(port, '127.0.0.1', r));
});
@@ -171,6 +175,41 @@ test('디스코드 로그인 → 모든 항목 체크해야 동의 → 철회하
assert.doesNotMatch(await (await get('/', cookie)).text(), /하늘님/);
});
test('운영자는 앱 연결 키를 만들어 앱에서 녹음할 서버를 켜고 끈다', async () => {
const { cookie, csrf } = await login();
assert.match(await (await get('/', cookie)).text(), /음성 변환기 앱 연결/);
assert.equal((await post('/app-key', cookie, {})).status, 403); // CSRF
const page = await (await post('/app-key', cookie, { csrf })).text();
const key = /<code class="key">([^<]+)<\/code>/.exec(page)![1];
const api = (method: string, k: string, body?: unknown) =>
fetch(base + '/api/guilds', { method, headers: { authorization: `Bearer ${k}`, 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
assert.equal((await fetch(base + '/api/guilds')).status, 401);
assert.equal((await api('GET', 'vc_wrong')).status, 401);
const list = await (await api('GET', key)).json();
assert.deepEqual(list.guilds.map((g: any) => [g.id, g.enabled]), [['g1', true], ['g2', true]]);
const r = await api('POST', key, { enabled: ['g1'] });
assert.equal(r.status, 200);
assert.deepEqual((await r.json()).guilds.map((g: any) => [g.id, g.enabled]), [['g1', true], ['g2', false]]);
assert.equal(store.guildEnabled('g2'), false);
assert.equal(settingsChanged, 1);
assert.equal((await api('POST', key, { enabled: ['nope'] })).status, 400);
assert.equal((await api('POST', key, { enabled: 'g1' })).status, 400);
assert.equal(store.guildEnabled('g2'), false);
// 새 키를 만들면 예전 키는 못 쓴다
const page2 = await (await post('/app-key', cookie, { csrf })).text();
const key2 = /<code class="key">([^<]+)<\/code>/.exec(page2)![1];
assert.equal((await api('GET', key)).status, 401);
assert.equal((await api('POST', key2, { enabled: ['g1', 'g2'] })).status, 200);
assert.equal(store.guildEnabled('g2'), true);
// 운영자가 아닌 사람의 키는 거절 (운영자 목록에서 빠진 경우 포함)
assert.equal((await api('GET', store.newAppKey('999999'))).status, 401);
assert.equal((await post('/logout', cookie, { csrf })).status, 303);
});
test('클릭재킹 막기 헤더', async () => {
const r = await get('/');
assert.equal(r.headers.get('x-frame-options'), 'DENY');

View File

@@ -54,6 +54,17 @@
- 잡음 무시: 이 크기(dB)보다 작은 소리는 변환하지 않습니다. 키보드 소리가 들어가면 올리세요.
- 설정은 `config\settings.json` 에 저장돼 다음에 그대로 열립니다.
## 녹음할 서버 정하기 — 녹음 서버
녹음 봇(동의 사이트 https://vc.tkrmagid.kr)이 어느 디스코드 서버에서 녹음할지 앱에서 켜고 끕니다.
1. 동의 사이트에 운영자 디스코드 계정으로 로그인해서 **앱 연결 키 만들기**를 누르고 키를 복사합니다 (한 번만 보입니다. 새로 만들면 예전 키는 못 씁니다).
2. 앱의 **녹음 서버…** 버튼 → 사이트 주소(기본값 그대로)와 앱 연결 키를 넣고 **불러오기**.
3. 녹음할 서버만 체크하고 **저장**. 끈 서버에서는 봇이 바로 나가고 더는 따라 들어가지 않습니다.
- 켠 서버에서도 녹음에 동의하고 그 서버를 녹음할 서버로 고른 사람의 목소리만 녹음합니다 (각자 사이트에서 고름).
- 사이트 주소와 키는 `config\record-servers.json` 에 저장됩니다.
## 목소리 모델 학습 — `train.bat`
동의 사이트 서버에서 학습 데이터를 꺼냅니다 (동의 중인 사람만 꺼내짐):
@@ -97,7 +108,7 @@ VoiceChanger.exe 실행기 (env\Scripts\pythonw.exe app\voice_changer.py 를
install.bat 엔진 내려받기 · 이어 받기 (scripts\install.ps1, 설치 프로그램도 이것을 실행)
train.bat 학습 (app\train.py)
examples.bat 예시 모델 (app\examples.py)
app\ 화면 · 학습 · 모델 목록 · 마이크 모듈 연결(mic_bridge.py) 코드
app\ 화면 · 학습 · 모델 목록 · 마이크 모듈 연결(mic_bridge.py) · 녹음 서버(record_servers.py) 코드
apo\ 마이크 모듈 VoiceChangerAPO.dll 과 소스 (vcapo.cpp, 주고받는 규약 vccore.h)
scripts\mic-apo.ps1 마이크 모듈 붙이기 · 떼기 (관리자)
models\<아이디>\ model.pth · model.index · info.json(이름 · 성별 · 출처 · 라이선스)

View File

@@ -0,0 +1,154 @@
"""녹음 서버: 녹음 봇(consent-recorder)이 어느 디스코드 서버에서 녹음할지 이 앱에서 켜고 끈다.
녹음 동의 사이트에 운영자 계정으로 로그인해 만든 "앱 연결 키"로 사이트 API(/api/guilds)를 부른다.
서버를 켜 두어도 그 서버에서 녹음에 동의하고 그 서버를 고른 사람의 목소리만 녹음한다.
"""
import json
import queue
import threading
import tkinter as tk
import urllib.error
import urllib.parse
import urllib.request
from tkinter import ttk
from common import CONFIG, load_json, save_json
DEFAULT_SITE = "https://vc.tkrmagid.kr"
STORE = CONFIG / "record-servers.json" # 사이트 주소 · 앱 연결 키
class ApiError(Exception):
pass
def api_url(site: str) -> str:
site = site.strip().rstrip("/")
u = urllib.parse.urlparse(site)
local = u.hostname in ("localhost", "127.0.0.1")
if not u.hostname or (u.scheme != "https" and not (u.scheme == "http" and local)):
raise ApiError("사이트 주소는 https:// 로 시작해야 합니다")
return site + "/api/guilds"
def call(site: str, key: str, enabled=None, timeout: float = 10) -> list:
"""서버 목록 [{id, name, enabled}]. enabled(켤 서버 아이디 목록)를 주면 그대로 저장한 뒤 목록을 돌려준다."""
key = key.strip()
if not key:
raise ApiError("앱 연결 키를 넣어 주세요")
body = None if enabled is None else json.dumps({"enabled": list(enabled)}).encode()
req = urllib.request.Request(api_url(site), data=body, method="GET" if body is None else "POST",
headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
data = json.loads(r.read().decode("utf-8"))
except urllib.error.HTTPError as e:
try:
msg = json.loads(e.read().decode("utf-8")).get("error")
except (ValueError, AttributeError):
msg = None
if e.code == 401:
raise ApiError("앱 연결 키가 맞지 않습니다. 사이트에서 새로 만든 키를 넣어 주세요") from None
raise ApiError(msg or f"사이트 오류 ({e.code})") from None
except (urllib.error.URLError, TimeoutError, OSError) as e:
raise ApiError(f"사이트에 연결할 수 없습니다: {getattr(e, 'reason', e)}") from None
except ValueError:
raise ApiError("사이트 응답이 올바르지 않습니다") from None
guilds = data.get("guilds") if isinstance(data, dict) else None
if not isinstance(guilds, list):
raise ApiError("사이트 응답이 올바르지 않습니다")
return [{"id": str(g["id"]), "name": str(g["name"]), "enabled": bool(g["enabled"])} for g in guilds]
class ServerDialog:
"""메인 화면의 "녹음 서버" 버튼으로 여는 창."""
def __init__(self, root: tk.Tk):
saved = load_json(STORE, {})
self.win = w = tk.Toplevel(root)
w.title("녹음 서버")
w.transient(root)
w.minsize(460, 320)
self.results = queue.Queue()
self.checks = {} # 서버 아이디 → BooleanVar
pad = dict(padx=10, pady=4)
ttk.Label(w, text="녹음 봇이 녹음할 디스코드 서버를 켜고 끕니다. 켠 서버에서도 녹음에 동의하고 그 서버를 고른 사람의 목소리만 녹음합니다.",
wraplength=440, foreground="#555").grid(row=0, column=0, columnspan=3, sticky="w", **pad)
ttk.Label(w, text="사이트 주소").grid(row=1, column=0, sticky="w", **pad)
self.site = tk.StringVar(value=saved.get("site", DEFAULT_SITE))
ttk.Entry(w, textvariable=self.site).grid(row=1, column=1, columnspan=2, sticky="ew", padx=10)
ttk.Label(w, text="앱 연결 키").grid(row=2, column=0, sticky="w", **pad)
self.key = tk.StringVar(value=saved.get("key", ""))
ttk.Entry(w, textvariable=self.key, show="•").grid(row=2, column=1, sticky="ew", padx=10)
self.load_btn = ttk.Button(w, text="불러오기", command=self.load)
self.load_btn.grid(row=2, column=2, sticky="e", padx=10)
ttk.Label(w, text="키는 사이트에 운영자 디스코드 계정으로 로그인한 뒤 \"앱 연결 키 만들기\"로 만듭니다.",
foreground="#555").grid(row=3, column=0, columnspan=3, sticky="w", padx=10)
self.list = ttk.Frame(w)
self.list.grid(row=4, column=0, columnspan=3, sticky="nsew", **pad)
self.save_btn = ttk.Button(w, text="저장", command=self.save, state="disabled")
self.save_btn.grid(row=5, column=0, columnspan=3, pady=6)
self.status = ttk.Label(w, text="")
self.status.grid(row=6, column=0, columnspan=3, sticky="w", **pad)
w.columnconfigure(1, weight=1)
w.rowconfigure(4, weight=1)
if self.key.get():
self.load()
def _run(self, text, enabled=None):
"""네트워크는 작업 스레드에서 (창이 멈추지 않게), 결과는 메인 스레드에서 그린다."""
site, key = self.site.get(), self.key.get()
self.load_btn.config(state="disabled")
self.save_btn.config(state="disabled")
self.status.config(text=text, foreground="")
def work():
try:
self.results.put((True, call(site, key, enabled)))
except ApiError as e:
self.results.put((False, str(e)))
threading.Thread(target=work, daemon=True).start()
self.win.after(100, self._poll, site, key, enabled is not None)
def _poll(self, site, key, saved):
try:
ok, data = self.results.get_nowait()
except queue.Empty:
if self.win.winfo_exists():
self.win.after(100, self._poll, site, key, saved)
return
if not self.win.winfo_exists():
return
self.load_btn.config(state="normal")
if not ok:
self.status.config(text=f"⚠ {data}", foreground="#b00020")
if self.checks:
self.save_btn.config(state="normal")
return
save_json(STORE, {"site": site.strip().rstrip("/"), "key": key.strip()}) # 맞는 키만 기억한다
self.show(data)
on = [g["name"] for g in data if g["enabled"]]
done = "저장했습니다" if saved else "불러왔습니다"
self.status.config(text=f"✓ {done}. 녹음하는 서버: {', '.join(on) if on else '없음'}", foreground="#188038")
def show(self, guilds):
for c in self.list.winfo_children():
c.destroy()
self.checks = {}
if not guilds:
ttk.Label(self.list, text="봇이 들어가 있는 서버가 없습니다.").pack(anchor="w")
return
for g in guilds:
v = tk.BooleanVar(value=g["enabled"])
self.checks[g["id"]] = v
ttk.Checkbutton(self.list, text=g["name"], variable=v).pack(anchor="w", pady=2)
self.save_btn.config(state="normal")
def load(self):
self._run("불러오는 중…")
def save(self):
self._run("저장하는 중…", [gid for gid, v in self.checks.items() if v.get()])

View File

@@ -15,6 +15,7 @@ from tkinter import messagebox, ttk
from common import ROOT, SETTINGS, load_json, save_json, use_engine
from models import GENDERS, auto_pitch, list_models
from record_servers import ServerDialog
LATENCY = {"낮음 (약 0.15초, GPU 여유 필요)": 128, "보통 (약 0.25초)": 250, "안정 (약 0.4초)": 400}
@@ -331,6 +332,7 @@ class App:
self.start_btn.pack(side="left", padx=6)
self.stop_btn = ttk.Button(b, text="■ 정지", command=self.stop, state="disabled")
self.stop_btn.pack(side="left", padx=6)
ttk.Button(b, text="녹음 서버…", command=lambda: ServerDialog(self.root)).pack(side="left", padx=6)
self.status = ttk.Label(f, text="꺼짐")
self.status.grid(row=12, column=0, columnspan=3, sticky="w", **pad)

View File

@@ -73,7 +73,7 @@ if ($Mode -eq 'Prepare') {
$known = [ordered]@{
'.' = @('VoiceChanger.exe', 'install.bat', 'train.bat', 'examples.bat', 'README.md')
'scripts' = @('install.ps1', 'mic-apo.ps1')
'app' = @('common.py', 'examples.py', 'mic_bridge.py', 'models.py', 'setup_engine.py', 'train.py', 'voice_changer.py')
'app' = @('common.py', 'examples.py', 'mic_bridge.py', 'models.py', 'record_servers.py', 'setup_engine.py', 'train.py', 'voice_changer.py')
'launcher' = @('launcher.c')
'apo' = @('VoiceChangerAPO.dll', 'vcapo.cpp', 'vccore.h', 'vcapo.def', 'mic-apo.json', 'mic-apo.log')
'uninstall' = @('unins*.exe', 'unins*.dat', 'unins*.msg')

View File

@@ -0,0 +1,95 @@
"""앱의 "녹음 서버" 화면이 녹음 동의 사이트 API(/api/guilds)와 주고받는 부분 (가짜 사이트로)."""
import json
import os
import sys
import tempfile
import threading
import unittest
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "app"))
os.environ.setdefault("VC_ROOT", tempfile.mkdtemp())
try:
import tkinter # noqa: F401 (record_servers 가 불러옴)
except ImportError:
tkinter = None
KEY = "vc_good"
STATE = {"g1": True, "g2": True}
class FakeSite(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def reply(self, code, data):
body = json.dumps(data, ensure_ascii=False).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def guilds(self):
return {"guilds": [{"id": g, "name": {"g1": "첫째 서버", "g2": "둘째 서버"}[g], "enabled": on} for g, on in STATE.items()]}
def do_GET(self):
if self.path != "/api/guilds" or self.headers.get("Authorization") != f"Bearer {KEY}":
return self.reply(401, {"error": "앱 연결 키가 맞지 않습니다"})
self.reply(200, self.guilds())
def do_POST(self):
if self.headers.get("Authorization") != f"Bearer {KEY}":
return self.reply(401, {"error": "앱 연결 키가 맞지 않습니다"})
on = json.loads(self.rfile.read(int(self.headers["Content-Length"])))["enabled"]
if any(g not in STATE for g in on):
return self.reply(400, {"error": "봇이 들어가 있지 않은 서버입니다"})
for g in STATE:
STATE[g] = g in on
self.reply(200, self.guilds())
@unittest.skipIf(tkinter is None, "tkinter 없음")
class RecordServersTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.httpd = HTTPServer(("127.0.0.1", 0), FakeSite)
threading.Thread(target=cls.httpd.serve_forever, daemon=True).start()
cls.site = f"http://127.0.0.1:{cls.httpd.server_port}/"
@classmethod
def tearDownClass(cls):
cls.httpd.shutdown()
def test_load_and_save(self):
from record_servers import call
self.assertEqual(call(self.site, KEY), [
{"id": "g1", "name": "첫째 서버", "enabled": True},
{"id": "g2", "name": "둘째 서버", "enabled": True},
])
after = call(self.site, f" {KEY} ", ["g2"])
self.assertEqual([(g["id"], g["enabled"]) for g in after], [("g1", False), ("g2", True)])
self.assertEqual(STATE, {"g1": False, "g2": True})
call(self.site, KEY, ["g1", "g2"])
def test_errors_are_korean_messages(self):
from record_servers import ApiError, call
with self.assertRaisesRegex(ApiError, "앱 연결 키가 맞지 않습니다"):
call(self.site, "vc_wrong")
with self.assertRaisesRegex(ApiError, "앱 연결 키를 넣어"):
call(self.site, " ")
with self.assertRaisesRegex(ApiError, "봇이 들어가 있지 않은 서버"):
call(self.site, KEY, ["nope"])
with self.assertRaisesRegex(ApiError, "https://"):
call("http://example.com", KEY) # 키가 평문으로 나가지 않게 https 만 (localhost 예외)
port = self.httpd.server_port + 1 if self.httpd.server_port < 65535 else 1
with self.assertRaisesRegex(ApiError, "연결할 수 없습니다"):
call(f"http://127.0.0.1:{port}", KEY, timeout=2)
if __name__ == "__main__":
unittest.main()