2 Commits

Author SHA1 Message Date
EJClaw
c24cd1f9c0 voice-changer: allow installing under user-owned folders (Desktop); move admin-run parts to Program Files
The installer refused folders whose parent is user-owned (Desktop, Documents) because a user could swap
the whole install folder and get the elevated/audiodg-run parts replaced. Instead of refusing, the parts
that run with admin rights or inside audiodg now live in {commonpf}\VoiceChanger, which only admins can
change; the chosen folder keeps the app, Python, engine, models and data.

- VoiceChanger.iss: SysDir = {commonpf}\VoiceChanger holds apo\ (VoiceChangerAPO.dll), scripts\mic-apo.ps1
  and the uninstaller (UninstallFilesDir). CheckParent removed. Upgrade detection also matches the previous
  install dir from the uninstall registry (PrevAppDir) since uninstall\ is no longer inside the app folder.
  Stop the audio service when either the new or the v1.0.1-layout APO exists. Ask before installing into
  a OneDrive-synced folder.
- secure-dir.ps1: drop CheckParent; Prepare takes -Upgrade.
- mic-apo.ps1: -From <previous app folder> migrates a v1.0.1 apo\ or 21b4278 config\ backup (validated as
  before) into the Program Files apo\, removing the emptied old apo\.
- app: admin_root() finds Program Files\VoiceChanger (falls back to the app folder for the zip layout);
  hooked-mic list, mic-apo log and the reconnect button use it.

Windows 11 VM (Inno 6.7.4 build, AppVersion 1.0.2): v1.0.1 at C:\VoiceChanger -> upgrade: backup moved
byte-equal, APO re-pointed to Program Files, old apo\ scripts\mic-apo.ps1 uninstall\ gone; fresh install to
C:\Users\ci\Desktop\VoiceChanger (owner WIN-CI\ci) with full engine download: exit 0, audiodg loads
C:\Program Files\VoiceChanger\apo\VoiceChangerAPO.dll, 440 Hz APO test + Communications stream PASS;
basic-user token can rename the Desktop folder but every Program Files write/rename is ERROR_ACCESS_DENIED;
reinstall over the same folder keeps user files; uninstall restores FxProperties (only the endpoint
timestamp properties differ, same as v1.0.1) and removes both folders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 22:09:39 +09:00
EJClaw
32ad429773 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>
2026-11-11 21:16:53 +09:00
18 changed files with 629 additions and 68 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

@@ -12,7 +12,7 @@
1. `VoiceChangerSetup.exe` 를 실행합니다 (관리자 권한 확인 창이 뜹니다).
2. **설치할 폴더**를 고릅니다. 기본값은 `C:\VoiceChanger` 이고, 다른 드라이브(`D:\...`)나 한글 · 띄어쓰기가 들어간 경로도 됩니다.
비어 있는 폴더나 새 폴더만 됩니다 (다른 파일이 든 폴더는 거절합니다). 상위 폴더가 일반 사용자 소유인 곳(예: 바탕 화면 · 문서 아래)도 거절합니다.
비어 있는 폴더나 새 폴더만 됩니다 (다른 파일이 든 폴더는 거절합니다). 바탕 화면 · 문서 아래(예: `바탕 화면\VoiceChanger`)도 됩니다. OneDrive 로 동기화되는 폴더를 고르면 한 번 더 묻습니다.
Python · 엔진 · torch · 목소리 모델 · 설정 · 학습 파일 · 캐시 · 임시 파일이 **모두 이 폴더 안에만** 저장됩니다.
설치하면서 약 8GB 를 내려받고 모델을 만들수록 늘어나므로 15GB 이상 비어 있는 드라이브를 고르세요.
3. 설치 프로그램이 마이크마다 변환 모듈을 붙이고(윈도우 소리가 1~2초 끊김), 검은 창에서 Python 3.12 · 엔진(Applio) ·
@@ -24,7 +24,7 @@
디스코드 · 게임의 입력 장치는 **평소 쓰던 마이크 그대로** 두면 됩니다.
- 내려받다가 끊기면 설치 폴더의 `install.bat` 을 실행합니다. 받은 곳부터 이어서 받습니다.
- 권한: 설치 프로그램이 설치 폴더의 소유자를 Administrators 로 바꾸고 잠근 뒤 확인합니다(`installer\secure-dir.ps1`, 실패하면 설치 중단). 설치 폴더와 실행 파일 · `app\` · `scripts\` · `apo\` · `uninstall\` 은 관리자만 고칠 수 있습니다. 일반 사용자는 `models` · `training` · `datasets` · `config` · `cache` · `env` · `engine` · `tools` 에만 씁니다. 엔진 내려받기(`install.ps1`)는 관리자 권한 없이 돕니다.
- 권한: 관리자 권한 · 오디오 서비스가 실행하는 마이크 모듈(`apo\`) · `mic-apo.ps1` · 제거 프로그램은 고른 폴더가 아니라 `C:\Program Files\VoiceChanger` 에 설치합니다 (고른 폴더의 상위가 사용자 소유여도 폴더를 바꿔쳐 관리자 권한을 얻지 못하게). 설치 프로그램은 고른 폴더의 소유자도 Administrators 로 바꾸고 잠근 뒤 확인합니다(`installer\secure-dir.ps1`, 실패하면 설치 중단). 설치 폴더와 실행 파일 · `app\` · `scripts\` 는 관리자만 고칠 수 있습니다. 일반 사용자는 `models` · `training` · `datasets` · `config` · `cache` · `env` · `engine` · `tools` 에만 씁니다. 엔진 내려받기(`install.ps1`)는 관리자 권한 없이 돕니다.
- 폴더 밖에 남는 것은 윈도우가 관리하는 항목뿐입니다: 시작 메뉴 바로 가기, 프로그램 제거 목록, 마이크 모듈 등록(레지스트리).
사용자 폴더(`%APPDATA%` · `%LOCALAPPDATA%` · `%TEMP%` · `.cache`)에는 아무것도 쓰지 않습니다.
- 제거: 설정 → 앱 → 음성 변환기 → 제거. 마이크 설정을 원래대로 되돌리고, 만든 모델 · 녹음 · 설정까지 지울지 묻습니다.
@@ -32,7 +32,7 @@
### 마이크 모듈은 어떻게 동작하나
윈도우는 마이크 소리를 앱에 넘기기 전에 오디오 처리 모듈(APO, Equalizer APO 와 같은 방식)을 거칩니다.
설치 프로그램이 `apo\VoiceChangerAPO.dll` 을 각 마이크의 처리 단계에 붙입니다 (`scripts\mic-apo.ps1`, 바꾼 값의 원래 값은 `apo\mic-apo-backup.json`, 이전 버전의 `config\mic-apo-backup.json` 은 값을 검증한 뒤 옮김).
설치 프로그램이 `C:\Program Files\VoiceChanger\apo\VoiceChangerAPO.dll` 을 각 마이크의 처리 단계에 붙입니다 (`scripts\mic-apo.ps1`, 바꾼 값의 원래 값은 같은 곳의 `apo\mic-apo-backup.json`, 이전 버전이 앱 폴더의 `apo\` · `config\` 에 둔 백업은 값을 검증한 뒤 옮김).
통화 앱(디스코드 등)이 여는 통화(Communications) 모드 스트림에도 붙도록 기본 · 통화 · 음성 · 미디어 모드로 등록합니다. 드라이버가 이미 모드 목록을 갖고 있으면 그 목록을 그대로 둡니다.
- 변환기가 꺼져 있으면 아무것도 하지 않습니다. 원래 목소리가 그대로 나갑니다
@@ -54,6 +54,17 @@
- 잡음 무시: 이 크기(dB)보다 작은 소리는 변환하지 않습니다. 키보드 소리가 들어가면 올리세요.
- 설정은 `config\settings.json` 에 저장돼 다음에 그대로 열립니다.
## 녹음할 서버 정하기 — 녹음 서버
녹음 봇(동의 사이트 https://vc.tkrmagid.kr)이 어느 디스코드 서버에서 녹음할지 앱에서 켜고 끕니다.
1. 동의 사이트에 운영자 디스코드 계정으로 로그인해서 **앱 연결 키 만들기**를 누르고 키를 복사합니다 (한 번만 보입니다. 새로 만들면 예전 키는 못 씁니다).
2. 앱의 **녹음 서버…** 버튼 → 사이트 주소(기본값 그대로)와 앱 연결 키를 넣고 **불러오기**.
3. 녹음할 서버만 체크하고 **저장**. 끈 서버에서는 봇이 바로 나가고 더는 따라 들어가지 않습니다.
- 켠 서버에서도 녹음에 동의하고 그 서버를 녹음할 서버로 고른 사람의 목소리만 녹음합니다 (각자 사이트에서 고름).
- 사이트 주소와 키는 `config\record-servers.json` 에 저장됩니다.
## 목소리 모델 학습 — `train.bat`
동의 사이트 서버에서 학습 데이터를 꺼냅니다 (동의 중인 사람만 꺼내짐):
@@ -97,16 +108,18 @@ 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) 코드
apo\ 마이크 모듈 VoiceChangerAPO.dll 과 소스 (vcapo.cpp, 주고받는 규약 vccore.h)
scripts\mic-apo.ps1 마이크 모듈 붙이기 · 떼기 (관리자)
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(이름 · 성별 · 출처 · 라이선스)
config\ 설정 · 마이크 모듈 백업
cache\ 임시 파일 · torch · huggingface · matplotlib 등 라이브러리 캐시 (지워도 됨)
engine\ env\ tools\ 설치하면 생기는 폴더 (엔진 · Python · uv)
uninstall\ 제거 프로그램
uninstall\ 제거 프로그램 *
```
`*` 표시는 설치 프로그램으로 설치하면 고른 폴더가 아니라 `C:\Program Files\VoiceChanger` 에 들어갑니다 (zip 으로 풀어 쓰면 같은 폴더).
## 배포 파일 만들기
```bash

View File

@@ -15,6 +15,15 @@ SETTINGS = CONFIG / "settings.json"
CACHE = ROOT / "cache"
def admin_root() -> Path:
"""마이크 모듈(apo\\)과 그것을 붙이는 scripts\\mic-apo.ps1 이 있는 폴더. 관리자 권한으로 실행되는 부분이라
설치 프로그램은 앱 폴더가 아니라 Program Files\\VoiceChanger 에 둔다. 그곳에 없으면(zip 으로 푼 경우) 앱 폴더."""
pf = os.environ.get("ProgramW6432") or os.environ.get("ProgramFiles")
if pf and (Path(pf) / "VoiceChanger" / "scripts" / "mic-apo.ps1").is_file():
return Path(pf) / "VoiceChanger"
return ROOT
def keep_files_in_root():
"""라이브러리가 사용자 폴더(%TEMP% · %USERPROFILE%\\.cache · %APPDATA%)에 쓰는 캐시와 임시 파일을
모두 설치 폴더 안 cache\\ 로 돌린다. 다른 import 보다 먼저 돌아야 해서 이 모듈을 불러올 때 바로 한다."""

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

@@ -13,8 +13,9 @@ import time
import tkinter as tk
from tkinter import messagebox, ttk
from common import ROOT, SETTINGS, load_json, save_json, use_engine
from common import SETTINGS, admin_root, 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}
@@ -33,7 +34,7 @@ def list_devices():
def hooked_mics() -> list:
"""설치할 때 마이크 모듈을 붙인 마이크들 (scripts/mic-apo.ps1 이 apo\\ 에 남긴 목록)."""
try:
items = json.loads((ROOT / "apo" / "mic-apo.json").read_text(encoding="utf-8-sig"))
items = json.loads((admin_root() / "apo" / "mic-apo.json").read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
return []
items = items if isinstance(items, list) else [items]
@@ -46,7 +47,7 @@ def is_hooked(name: str, hooked: list) -> bool:
def reconnect_params(root=None) -> str:
"""관리자 PowerShell 에 넘길 인자. Windows 경로에는 " 가 들어갈 수 없어서 큰따옴표로만 감싸면 공백 · 한글 경로도 안전하다."""
root = ROOT if root is None else root
root = admin_root() if root is None else root
script, r = str(root / "scripts" / "mic-apo.ps1"), str(root)
if r.endswith("\\"): # "D:\" 처럼 \ 로 끝나면 닫는 따옴표가 이스케이프되므로 "D:\." 로
r += "."
@@ -56,7 +57,7 @@ def reconnect_params(root=None) -> str:
def mic_apo_log_tail(lines: int = 8) -> str:
"""scripts/mic-apo.ps1 이 apo\\mic-apo.log 에 남긴 마지막 기록."""
try:
text = (ROOT / "apo" / "mic-apo.log").read_text(encoding="utf-8-sig", errors="replace")
text = (admin_root() / "apo" / "mic-apo.log").read_text(encoding="utf-8-sig", errors="replace")
except OSError:
return "(기록 없음)"
return "\n".join(text.strip().splitlines()[-lines:])
@@ -82,7 +83,7 @@ def reconnect_mics() -> int:
k32.CloseHandle.argtypes = [wintypes.HANDLE]
sei = SHELLEXECUTEINFOW(cbSize=ctypes.sizeof(SHELLEXECUTEINFOW), fMask=0x40, # SEE_MASK_NOCLOSEPROCESS
lpVerb="runas", lpFile="powershell.exe", lpParameters=reconnect_params(),
lpDirectory=str(ROOT), nShow=0)
lpDirectory=str(admin_root()), nShow=0)
if not shell32.ShellExecuteExW(ctypes.byref(sei)):
return -ctypes.get_last_error()
try:
@@ -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

@@ -2,7 +2,10 @@
; ISCC.exe installer\VoiceChanger.iss → dist\VoiceChangerSetup.exe
; 하는 일
; 1. 설치할 폴더를 고르게 한다. Python · 엔진 · 모델 · 설정 · 캐시 · 임시 파일이 모두 그 폴더 안에만 생긴다
; 2. 그 폴더에 앱 파일을 풀고, 마이크마다 변환 모듈(APO)을 붙인다 (가상 오디오 장치 설치 없음)
; (바탕 화면처럼 일반 사용자 폴더 아래도 됨)
; 2. 그 폴더에 앱 파일을 풀고, 마이크마다 변환 모듈(APO)을 붙인다 (가상 오디오 장치 설치 없음).
; 관리자 권한 · 오디오 서비스가 실행하는 부분(APO · mic-apo.ps1 · 제거 프로그램)은 고른 폴더가 아니라
; Program Files\VoiceChanger 에 둔다. 고른 폴더의 상위가 사용자 소유면 그 사용자가 폴더를 통째로 바꿔칠 수 있기 때문
; 3. Python · 엔진 · torch(CUDA) · 엔진 기본 모델을 그 폴더 안으로 내려받는다 (scripts\install.ps1, 10~20분)
; 제거할 때는 마이크 설정을 원래대로 되돌리고, 모델 · 녹음까지 지울지 묻는다.
@@ -10,6 +13,8 @@
#ifndef AppVersion
#define AppVersion "1.0.0"
#endif
; 관리자 권한 · 오디오 서비스(audiodg)가 실행하는 부분. Program Files 아래라 관리자만 고칠 수 있다
#define SysDir "{commonpf}\VoiceChanger"
[Setup]
AppId={{8C3F2A51-6D0B-4E7A-9F3C-2B5E1D7A4C90}
@@ -30,7 +35,7 @@ OutputBaseFilename=VoiceChangerSetup
Compression=lzma2
SolidCompression=yes
WizardStyle=modern
UninstallFilesDir={app}\uninstall
UninstallFilesDir={#SysDir}\uninstall
UninstallDisplayIcon={app}\VoiceChanger.exe
UninstallDisplayName={#AppName}
@@ -46,7 +51,9 @@ Name: "desktopicon"; Description: "바탕 화면에 바로 가기 만들기"; Fl
[Files]
Source: "secure-dir.ps1"; Flags: dontcopy
Source: "..\dist\payload\*"; DestDir: "{app}"; Flags: recursesubdirs createallsubdirs ignoreversion
Source: "..\dist\payload\*"; DestDir: "{app}"; Excludes: "\apo,\apo\*,\scripts\mic-apo.ps1"; Flags: recursesubdirs createallsubdirs ignoreversion
Source: "..\dist\payload\apo\*"; DestDir: "{#SysDir}\apo"; Flags: ignoreversion
Source: "..\dist\payload\scripts\mic-apo.ps1"; DestDir: "{#SysDir}\scripts"; Flags: ignoreversion
[Icons]
Name: "{autoprograms}\{#AppName}"; Filename: "{app}\VoiceChanger.exe"; WorkingDir: "{app}"
@@ -56,17 +63,18 @@ Name: "{autodesktop}\{#AppName}"; Filename: "{app}\VoiceChanger.exe"; WorkingDir
Filename: "{app}\VoiceChanger.exe"; Description: "음성 변환기 실행"; Flags: postinstall nowait skipifsilent unchecked
[UninstallRun]
Filename: "powershell.exe"; Parameters: "-NoProfile -ExecutionPolicy Bypass -File ""{app}\scripts\mic-apo.ps1"" -Uninstall -Root ""{app}"""; Flags: runhidden waituntilterminated; RunOnceId: "MicApoUninstall"
Filename: "powershell.exe"; Parameters: "-NoProfile -ExecutionPolicy Bypass -File ""{#SysDir}\scripts\mic-apo.ps1"" -Uninstall -Root ""{#SysDir}"""; Flags: runhidden waituntilterminated; RunOnceId: "MicApoUninstall"
[Code]
{ 설치 폴더 보안은 secure-dir.ps1 (설치 프로그램에 들어 있고 임시 폴더에 풀어서 관리자 권한으로 실행)이 맡는다.
관리자 권한으로 실행되는 것(설치 폴더 루트의 exe, app\, scripts\, apo\, uninstall\)은 관리자만 고칠 수 있고,
일반 사용자는 데이터 폴더(models · training · datasets · config · cache · env · engine · tools)에만 쓴다. }
function SecureDir(const Mode, Dir: String): Integer;
설치 폴더의 실행 파일 · app\ · scripts\ 는 관리자만 고칠 수 있고,
일반 사용자는 데이터 폴더(models · training · datasets · config · cache · env · engine · tools)에만 쓴다.
관리자 권한으로 실행되는 APO · mic-apo.ps1 · 제거 프로그램은 Program Files 쪽(SysDir)에 있다. }
function SecureDir(const Mode, Dir, Extra: String): Integer;
begin
ExtractTemporaryFile('secure-dir.ps1');
if not Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
'-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{tmp}\secure-dir.ps1') + '" -Mode ' + Mode + ' -App "' + Dir + '"',
'-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{tmp}\secure-dir.ps1') + '" -Mode ' + Mode + ' -App "' + Dir + '"' + Extra,
'', SW_HIDE, ewWaitUntilTerminated, Result) then
Result := -1;
Log('secure-dir ' + Mode + ' exit=' + IntToStr(Result));
@@ -97,6 +105,48 @@ begin
end;
end;
{ 이 앱을 이미 설치한 폴더인지. v1.0.1 까지는 제거 프로그램이 설치 폴더 안(uninstall\)에 있었고,
지금은 Program Files 쪽에 있으므로 이전 설치 위치(관리자만 쓰는 제거 정보 레지스트리, PrevAppDir)와도 비교한다. }
function IsOurInstall(const Dir: String): Boolean;
begin
Result := FileExists(AddBackslash(Dir) + 'uninstall\unins000.exe') or
((WizardForm.PrevAppDir <> '') and DirExists(Dir) and
(CompareText(RemoveBackslashUnlessRoot(WizardForm.PrevAppDir), RemoveBackslashUnlessRoot(Dir)) = 0));
end;
{ 마이크 백업을 옮겨 올 이전 설치 폴더. 명령줄에서 "D:\" 처럼 \ 로 끝나면 닫는 따옴표가 이스케이프되므로 "D:\." 로 }
function PrevRoot: String;
begin
Result := RemoveBackslashUnlessRoot(WizardForm.PrevAppDir);
if Result = '' then
Result := RemoveBackslashUnlessRoot(ExpandConstant('{app}'));
if Copy(Result, Length(Result), 1) = '\' then
Result := Result + '.';
end;
{ OneDrive 로 동기화되는 폴더(바탕 화면이 OneDrive 로 옮겨진 PC 가 많음)인지 }
function InOneDrive(const Dir: String): Boolean;
var
I: Integer;
OD: String;
begin
Result := False;
for I := 0 to 2 do
begin
case I of
0: OD := GetEnv('OneDrive');
1: OD := GetEnv('OneDriveConsumer');
else
OD := GetEnv('OneDriveCommercial');
end;
if (OD <> '') and (Pos(Lowercase(AddBackslash(OD)), Lowercase(AddBackslash(Dir))) = 1) then
begin
Result := True;
Exit;
end;
end;
end;
{ 다른 파일이 들어 있는 폴더에는 설치하지 않는다. 설치 폴더의 권한을 잠그고, 제거할 때 지우기 때문.
이 앱을 이미 설치한 폴더(업데이트)나 비어 있는 · 새 폴더만 받는다. }
function NextButtonClick(CurPageID: Integer): Boolean;
@@ -106,41 +156,47 @@ begin
Result := True;
if CurPageID <> wpSelectDir then Exit;
Dir := WizardDirValue;
if DirExists(Dir) and not IsEmptyDir(Dir) and not FileExists(AddBackslash(Dir) + 'uninstall\unins000.exe') then
if DirExists(Dir) and not IsEmptyDir(Dir) and not IsOurInstall(Dir) then
begin
SuppressibleMsgBox('이 폴더에는 이미 다른 파일이 있습니다.' + #13#10 +
'비어 있는 폴더나 새 폴더를 골라 주세요. (예: ' + AddBackslash(Dir) + 'VoiceChanger)', mbError, MB_OK, IDOK);
Result := False;
Exit;
end;
{ 상위 폴더가 일반 사용자 소유면 그 사용자가 설치 폴더를 통째로 다른 것으로 바꿔칠 수 있다 }
if SecureDir('CheckParent', Dir) <> 0 then
begin
SuppressibleMsgBox('이 위치의 상위 폴더는 관리자 소유가 아니라서 설치할 수 없습니다.' + #13#10 +
'드라이브 바로 아래(예: C:\VoiceChanger, D:\VoiceChanger)나 Program Files 처럼 관리자가 관리하는 곳을 골라 주세요.', mbError, MB_OK, IDOK);
if InOneDrive(Dir) and (SuppressibleMsgBox('이 폴더는 OneDrive 로 동기화됩니다.' + #13#10 +
'설치하면서 받는 8GB 이상(Python · 엔진 · 모델)이 OneDrive 에 올라가고, OneDrive 가 공간 확보로 파일을 내리면 음성 변환기가 실행되지 않을 수 있습니다.' + #13#10#13#10 +
'그래도 여기에 설치할까요? ("아니요" 를 누르고 C:\VoiceChanger 처럼 OneDrive 밖의 폴더를 고르는 것을 권합니다)',
mbConfirmation, MB_YESNO, IDYES) <> IDYES) then
Result := False;
end;
end;
function PrepareToInstall(var NeedsRestart: Boolean): String;
var
Code: Integer;
ApoInUse: Boolean;
Extra: String;
begin
Result := '';
{ 다시 설치(업데이트)할 때 오디오 엔진이 쥐고 있는 APO 파일을 바꿀 수 있게 잠깐 오디오 서비스를 멈춘다.
설치 뒤 mic-apo.ps1 이 다시 켠다. }
if FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll')) then
{ 이전 버전(v1.0.1 까지)은 APO 를 설치 폴더의 apo\ 에 두었다. secure-dir 이 그 파일을 지운다. }
ApoInUse := FileExists(ExpandConstant('{#SysDir}\apo\VoiceChangerAPO.dll')) or FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll'));
if ApoInUse then
Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
'-NoProfile -Command "Stop-Service -Name AudioEndpointBuilder -Force"', '', SW_HIDE, ewWaitUntilTerminated, Code);
if IsOurInstall(ExpandConstant('{app}')) then
Extra := ' -Upgrade'
else
Extra := '';
{ 파일을 풀기 전에 설치 폴더를 관리자 소유로 잠근다. 실패하면 설치하지 않는다. }
case SecureDir('Prepare', ExpandConstant('{app}')) of
case SecureDir('Prepare', ExpandConstant('{app}'), Extra) of
0: ;
10: Result := '이 폴더에는 이미 다른 파일이 있습니다. 비어 있는 폴더나 새 폴더를 골라 주세요.';
11: Result := '설치 폴더 안에 링크(정션 · 심볼릭 링크)가 있어 안전하게 설치할 수 없습니다. 링크를 지우거나 새 폴더를 골라 주세요.';
else
Result := '설치 폴더의 권한을 잠그지 못했습니다. 다른 폴더를 골라 다시 설치해 주세요.';
end;
if (Result <> '') and FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll')) then
if (Result <> '') and ApoInUse then
Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code);
end;
@@ -151,7 +207,7 @@ begin
if CurStep <> ssPostInstall then Exit;
{ 데이터 폴더에만 사용자 쓰기 권한을 주고, 관리자 권한으로 실행되는 파일이 잠겼는지 확인한다.
확인이 안 되면 관리자 권한으로 아무것도 실행하지 않는다. }
if SecureDir('Finish', ExpandConstant('{app}')) <> 0 then
if SecureDir('Finish', ExpandConstant('{app}'), '') <> 0 then
begin
Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code);
SuppressibleMsgBox('설치 폴더의 권한을 확인하지 못해 마이크 연결과 엔진 내려받기를 하지 않았습니다.' + #13#10 +
@@ -160,7 +216,8 @@ begin
end;
WizardForm.StatusLabel.Caption := '마이크에 변환 모듈을 붙이는 중... (윈도우 소리가 잠깐 끊깁니다)';
if not PowerShell('-File "' + ExpandConstant('{app}\scripts\mic-apo.ps1') + '" -Install -Root "' + ExpandConstant('{app}') + '"', SW_HIDE, Code) or (Code <> 0) then
if not PowerShell('-File "' + ExpandConstant('{#SysDir}\scripts\mic-apo.ps1') + '" -Install -Root "' + ExpandConstant('{#SysDir}') +
'" -From "' + PrevRoot + '"', SW_HIDE, Code) or (Code <> 0) then
begin
Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code);
SuppressibleMsgBox('마이크에 변환 모듈을 붙이지 못했습니다. 설치가 끝난 뒤 음성 변환기의 "마이크 다시 연결" 을 눌러 주세요.', mbError, MB_OK, IDOK);
@@ -203,7 +260,11 @@ begin
RemoveDir(App + '\training');
RemoveDir(App + '\datasets');
RemoveDir(App + '\config');
DeleteFile(App + '\apo\mic-apo.log');
RemoveDir(App + '\apo');
RemoveDir(App);
{ Program Files 쪽: mic-apo.ps1 이 남긴 기록 }
DeleteFile(ExpandConstant('{#SysDir}\apo\mic-apo.log'));
RemoveDir(ExpandConstant('{#SysDir}\apo'));
RemoveDir(ExpandConstant('{#SysDir}\scripts'));
RemoveDir(ExpandConstant('{#SysDir}'));
end;

View File

@@ -1,12 +1,12 @@
# 설치 폴더 보안 (설치 프로그램이 관리자 권한으로 {tmp} 에서 실행). 종료 코드로 결과를 알린다.
# -Mode CheckParent -App <폴더> 가장 가까운 상위 폴더가 드라이브 루트이거나 관리자 · SYSTEM · TrustedInstaller 소유인지
# 0 = 괜찮음, 20 = 일반 사용자 소유 (그 사용자가 설치 폴더를 통째로 바꿔치기할 수 있음)
# -Mode Prepare -App <폴더> 파일을 풀기 전: 폴더를 만들고 소유자를 Administrators 로, 권한을 관리자 · SYSTEM 전체 +
# Users 읽기로 잠근다. 업데이트면 이전 버전이 사용자 쓰기 폴더에 두었던 실행 부분을 지운다.
# (상위 폴더는 일반 사용자 소유여도 된다. 관리자 권한으로 실행되는 APO · mic-apo.ps1 · 제거 프로그램은 설치 폴더가 아니라
# Program Files\VoiceChanger 에 있어서, 사용자가 설치 폴더를 통째로 바꿔쳐도 관리자 권한을 얻지 못한다)
# -Mode Prepare -App <폴더> [-Upgrade] 파일을 풀기 전: 폴더를 만들고 소유자를 Administrators 로, 권한을 관리자 · SYSTEM 전체 +
# Users 읽기로 잠근다. 업데이트(-Upgrade 또는 v1.0.1 까지의 uninstall\ 이 있음)면 이전 버전이 사용자 쓰기 폴더에 두었던 실행 부분을 지운다.
# 10 = 다른 파일이 있는 폴더, 11 = 링크(정션 · 심볼릭 링크)가 있음, 12 = 잠그지 못함
# -Mode Finish -App <폴더> 파일을 푼 뒤: 데이터 폴더에만 Users 수정 권한을 주고, 관리자 권한으로 실행되는 파일이
# 관리자 소유이고 일반 사용자가 쓸 수 없는지 확인한다. 13 = 확인 실패
param([Parameter(Mandatory)][string]$Mode, [Parameter(Mandatory)][string]$App)
param([Parameter(Mandatory)][string]$Mode, [Parameter(Mandatory)][string]$App, [switch]$Upgrade)
$ErrorActionPreference = 'Stop'
$SY = 'S-1-5-18'; $BA = 'S-1-5-32-544'; $BU = 'S-1-5-32-545'
$TI = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'
@@ -46,20 +46,9 @@ function Find-Link([string]$dir) {
return $null
}
function Owner-Sid([string]$p) { (Get-Acl -LiteralPath $p).GetOwner($Sid).Value }
if ($Mode -eq 'CheckParent') {
$p = Split-Path -Parent $App
while ($p -and -not (Test-Path -LiteralPath $p)) { $p = Split-Path -Parent $p }
if (-not $p -or $p -eq [IO.Path]::GetPathRoot($p)) { Say "상위: 드라이브 루트"; exit 0 }
$o = Owner-Sid $p
Say "상위: $p 소유자 $o"
if ($o -in @($BA, $SY, $TI)) { exit 0 }
exit 20
}
if ($Mode -eq 'Prepare') {
$upgrade = Test-Path -LiteralPath (Join-Path $App 'uninstall\unins000.exe')
$upgrade = $Upgrade -or (Test-Path -LiteralPath (Join-Path $App 'uninstall\unins000.exe'))
if (Test-Path -LiteralPath $App) {
if (Is-Link $App) { Say "설치 폴더가 링크: $App"; exit 11 }
if (-not $upgrade -and [IO.Directory]::EnumerateFileSystemEntries($App).GetEnumerator().MoveNext()) { exit 10 }
@@ -73,7 +62,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

@@ -1,9 +1,11 @@
# 마이크 APO 등록 · 해제 (관리자 권한). 설치 프로그램과 앱의 "마이크 다시 연결" 버튼이 실행한다.
# mic-apo.ps1 -Install [-Root <설치 폴더>] 마이크마다 APO 를 붙이고 오디오 서비스를 다시 시작
# mic-apo.ps1 -Uninstall [-Root <설치 폴더>] 원래 설정으로 되돌림
# 바꾼 레지스트리 값의 원래 값은 <설치 폴더>\apo\mic-apo-backup.json 에 남겨 두고 해제할 때 되돌린다.
# mic-apo.ps1 -Install [-Root <폴더>] [-From <이전 설치 폴더>] 마이크마다 APO 를 붙이고 오디오 서비스를 다시 시작
# mic-apo.ps1 -Uninstall [-Root <폴더>] 원래 설정으로 되돌림
# <폴더> 는 apo\ 가 있는 곳이다. 설치 프로그램은 Program Files\VoiceChanger, zip 으로 풀어 쓰면 그 폴더.
# 바꾼 레지스트리 값의 원래 값은 <폴더>\apo\mic-apo-backup.json 에 남겨 두고 해제할 때 되돌린다.
# apo\ 는 관리자만 쓸 수 있는 폴더다 (일반 사용자가 백업을 바꿔 관리자 권한으로 레지스트리를 쓰게 만들 수 없게).
param([switch]$Install, [switch]$Uninstall, [string]$Root)
# -From: 이전 버전이 백업을 둔 앱 폴더 (21b4278 은 config\, v1.0.1 까지는 앱 폴더의 apo\). 값을 검증한 뒤 옮긴다.
param([switch]$Install, [switch]$Uninstall, [string]$Root, [string]$From)
$ErrorActionPreference = 'Stop'
if (-not $Root) { $Root = Split-Path -Parent $PSScriptRoot }
$Root = (Resolve-Path $Root).Path
@@ -14,7 +16,8 @@ $Dll = Join-Path $Root 'apo\VoiceChangerAPO.dll'
$Config = Join-Path $Root 'apo'
$BackupFile = Join-Path $Config 'mic-apo-backup.json'
$ListFile = Join-Path $Config 'mic-apo.json' # 앱이 읽는 "모듈을 붙인 마이크" 목록
$OldListFile = Join-Path $Root 'config\mic-apo.json' # 이전 버전(21b4278)의 목록 위치 (설치 · 제거 때 지움)
$OldDirs = @($Root) + @(if ($From -and (Test-Path -LiteralPath $From)) { (Resolve-Path -LiteralPath $From).Path })
$OldListFiles = @($OldDirs | ForEach-Object { Join-Path $_ 'config\mic-apo.json' }) # 이전 버전(21b4278)의 목록 위치 (설치 · 제거 때 지움)
# 실행 기록은 관리자만 쓸 수 있는 apo\mic-apo.log 에 남긴다 (앱이 실패 이유를 보여 줄 때 읽음)
$LogFile = Join-Path $Config 'mic-apo.log'
function Write-RunLog($m) { try { Add-Content -Path $LogFile -Value "[$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')] $m" -Encoding UTF8 } catch {} }
@@ -160,8 +163,11 @@ function Current-Original([string]$sub) {
function Load-Backup {
$b = @{}
$src = $BackupFile
$old = Join-Path $Root 'config\mic-apo-backup.json' # 이전 버전(21b4278)의 위치
if (-not (Test-Path $src) -and (Test-Path $old)) { $src = $old; Log "이전 백업을 옮김: $old" }
if (-not (Test-Path -LiteralPath $src)) {
$old = @(foreach ($d in $OldDirs) { Join-Path $d 'apo\mic-apo-backup.json'; Join-Path $d 'config\mic-apo-backup.json' }) |
Where-Object { $_ -ne $BackupFile -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
if ($old) { $src = $old; Log "이전 백업을 옮김: $old" }
}
if (Test-Path $src) {
try { $j = Get-Content $src -Raw -Encoding UTF8 | ConvertFrom-Json } catch { $j = $null; Log "백업을 읽지 못함: $src" }
if ($j) {
@@ -179,9 +185,11 @@ function Load-Backup {
}
}
}
if ($src -eq $old) {
if ($src -ne $BackupFile) {
Save-Backup $b
Remove-Item -Force $old -ErrorAction SilentlyContinue
Remove-Item -LiteralPath $src -Force -ErrorAction SilentlyContinue
$d = Split-Path $src # v1.0.1 까지의 앱 폴더 apo\ 는 비었으면 지운다
if ((Split-Path -Leaf $d) -eq 'apo' -and -not (Get-ChildItem -LiteralPath $d -Force)) { Remove-Item -LiteralPath $d -Force }
}
return $b
}
@@ -268,7 +276,7 @@ function Install-Apo {
}
New-Item -ItemType Directory -Force $Config | Out-Null
ConvertTo-Json -InputObject @($done) -Depth 3 | Set-Content $ListFile -Encoding UTF8
Remove-Item -Force $OldListFile -ErrorAction SilentlyContinue
Remove-Item -Force $OldListFiles -ErrorAction SilentlyContinue
Restart-Audio
if ($done.Count -eq 0) { throw '마이크를 하나도 연결하지 못했습니다' }
}
@@ -293,7 +301,7 @@ function Uninstall-Apo {
foreach ($sub in @("SOFTWARE\Classes\AudioEngine\AudioProcessingObjects\$Clsid", "SOFTWARE\Classes\CLSID\$Clsid")) {
if ($HKLM.OpenSubKey($sub)) { $HKLM.DeleteSubKeyTree($sub) }
}
Remove-Item -Force $BackupFile, $ListFile, $OldListFile -ErrorAction SilentlyContinue
Remove-Item -Force (@($BackupFile, $ListFile) + $OldListFiles) -ErrorAction SilentlyContinue
Restart-Audio
}

View File

@@ -0,0 +1,27 @@
"""관리자 권한으로 도는 부분(apo\\ · mic-apo.ps1)을 설치 프로그램이 둔 Program Files\\VoiceChanger 에서 찾는지."""
import os
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "app"))
import common # noqa: E402
class AdminRootTest(unittest.TestCase):
def test_installed_uses_program_files(self):
with tempfile.TemporaryDirectory() as pf:
(Path(pf) / "VoiceChanger" / "scripts").mkdir(parents=True)
(Path(pf) / "VoiceChanger" / "scripts" / "mic-apo.ps1").write_text("x")
with mock.patch.dict(os.environ, {"ProgramW6432": pf}):
self.assertEqual(common.admin_root(), Path(pf) / "VoiceChanger")
def test_zip_layout_uses_app_folder(self):
with tempfile.TemporaryDirectory() as pf, mock.patch.dict(os.environ, {"ProgramW6432": pf}):
self.assertEqual(common.admin_root(), common.ROOT)
if __name__ == "__main__":
unittest.main()

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()