Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1d9242b81 | ||
|
|
85f5782876 | ||
|
|
c24cd1f9c0 | ||
|
|
32ad429773 |
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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})`));
|
||||
|
||||
@@ -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) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -10,10 +10,10 @@
|
||||
|
||||
## 설치 — `VoiceChangerSetup.exe` 하나만
|
||||
|
||||
1. `VoiceChangerSetup.exe` 를 실행합니다 (관리자 권한 확인 창이 뜹니다).
|
||||
1. `VoiceChangerSetup.exe` 를 **더블클릭**해서 실행합니다 (관리자 권한 확인 창이 뜹니다). "관리자 권한으로 실행" 이나 관리자 터미널로 시작하면 앱 파일을 복사하지 않고 안내만 합니다 (고른 폴더는 내 계정 권한으로만 다루기 때문).
|
||||
2. **설치할 폴더**를 고릅니다. 기본값은 `C:\VoiceChanger` 이고, 다른 드라이브(`D:\...`)나 한글 · 띄어쓰기가 들어간 경로도 됩니다.
|
||||
비어 있는 폴더나 새 폴더만 됩니다 (다른 파일이 든 폴더는 거절합니다). 상위 폴더가 일반 사용자 소유인 곳(예: 바탕 화면 · 문서 아래)도 거절합니다.
|
||||
Python · 엔진 · torch · 목소리 모델 · 설정 · 학습 파일 · 캐시 · 임시 파일이 **모두 이 폴더 안에만** 저장됩니다.
|
||||
비어 있는 폴더나 새 폴더만 됩니다 (다른 파일이 든 폴더는 거절합니다). 바탕 화면 · 문서 아래(예: `바탕 화면\VoiceChanger`)도 됩니다. OneDrive 로 동기화되는 폴더를 고르면 한 번 더 묻습니다.
|
||||
앱 · Python · 엔진 · torch · 목소리 모델 · 설정 · 학습 파일 · 캐시 · 임시 파일이 **모두 이 폴더 안에만** 저장됩니다.
|
||||
설치하면서 약 8GB 를 내려받고 모델을 만들수록 늘어나므로 15GB 이상 비어 있는 드라이브를 고르세요.
|
||||
3. 설치 프로그램이 마이크마다 변환 모듈을 붙이고(윈도우 소리가 1~2초 끊김), 검은 창에서 Python 3.12 · 엔진(Applio) ·
|
||||
torch(CUDA 12.8) · 엔진 기본 모델(rmvpe · contentvec · 사전학습 가중치 · ffmpeg)을 그 폴더로 내려받습니다. 10~20분 걸립니다.
|
||||
@@ -24,15 +24,18 @@
|
||||
디스코드 · 게임의 입력 장치는 **평소 쓰던 마이크 그대로** 두면 됩니다.
|
||||
|
||||
- 내려받다가 끊기면 설치 폴더의 `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` 에 설치합니다 (관리자만 고칠 수 있음).
|
||||
고른 폴더는 관리자 권한으로 건드리지 않습니다. 앱 파일 복사(`installer\deploy.ps1`)와 엔진 내려받기(`install.ps1`)는 설치를 시작한 사용자 권한으로 합니다.
|
||||
바탕 화면처럼 상위가 사용자 소유인 폴더는 설치 도중 다른 곳을 가리키는 정션으로 바꿔칠 수 있어서, 관리자 권한으로 그 경로를 다루면 엉뚱한 곳이 바뀔 수 있기 때문입니다.
|
||||
v1.0.1 까지 관리자 소유로 잠가 둔 설치 폴더는 설치 프로그램이 이전 실행 파일만 지우고 `<폴더>.old` 로 비켜 둔 뒤(`installer\legacy.ps1`, 상위가 관리자 소유일 때만) 모델 · 설정 · Python · 엔진을 새 폴더로 옮깁니다.
|
||||
- 폴더 밖에 남는 것은 윈도우가 관리하는 항목뿐입니다: 시작 메뉴 바로 가기, 프로그램 제거 목록, 마이크 모듈 등록(레지스트리).
|
||||
사용자 폴더(`%APPDATA%` · `%LOCALAPPDATA%` · `%TEMP%` · `.cache`)에는 아무것도 쓰지 않습니다.
|
||||
- 제거: 설정 → 앱 → 음성 변환기 → 제거. 마이크 설정을 원래대로 되돌리고, 만든 모델 · 녹음 · 설정까지 지울지 묻습니다.
|
||||
- 제거: 설정 → 앱 → 음성 변환기 → 제거. 마이크 설정을 원래대로 되돌리고 `C:\Program Files\VoiceChanger` 를 지웁니다. 고른 폴더(앱 · 모델 · 녹음 · 설정)는 남기므로 필요 없으면 직접 지웁니다 (내 계정 폴더라 관리자 권한 없이 지울 수 있음).
|
||||
|
||||
### 마이크 모듈은 어떻게 동작하나
|
||||
|
||||
윈도우는 마이크 소리를 앱에 넘기기 전에 오디오 처리 모듈(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`, v1.0.1 까지 고른 폴더의 `apo\` 에 있던 백업은 설치 프로그램이 이 자리로 옮기고 mic-apo.ps1 이 값을 검증).
|
||||
통화 앱(디스코드 등)이 여는 통화(Communications) 모드 스트림에도 붙도록 기본 · 통화 · 음성 · 미디어 모드로 등록합니다. 드라이버가 이미 모드 목록을 갖고 있으면 그 목록을 그대로 둡니다.
|
||||
|
||||
- 변환기가 꺼져 있으면 아무것도 하지 않습니다. 원래 목소리가 그대로 나갑니다
|
||||
@@ -54,6 +57,17 @@
|
||||
- 잡음 무시: 이 크기(dB)보다 작은 소리는 변환하지 않습니다. 키보드 소리가 들어가면 올리세요.
|
||||
- 설정은 `config\settings.json` 에 저장돼 다음에 그대로 열립니다.
|
||||
|
||||
## 녹음할 서버 정하기 — 녹음 서버
|
||||
|
||||
녹음 봇(동의 사이트 https://vc.tkrmagid.kr)이 어느 디스코드 서버에서 녹음할지 앱에서 켜고 끕니다.
|
||||
|
||||
1. 동의 사이트에 운영자 디스코드 계정으로 로그인해서 **앱 연결 키 만들기**를 누르고 키를 복사합니다 (한 번만 보입니다. 새로 만들면 예전 키는 못 씁니다).
|
||||
2. 앱의 **녹음 서버…** 버튼 → 사이트 주소(기본값 그대로)와 앱 연결 키를 넣고 **불러오기**.
|
||||
3. 녹음할 서버만 체크하고 **저장**. 끈 서버에서는 봇이 바로 나가고 더는 따라 들어가지 않습니다.
|
||||
|
||||
- 켠 서버에서도 녹음에 동의하고 그 서버를 녹음할 서버로 고른 사람의 목소리만 녹음합니다 (각자 사이트에서 고름).
|
||||
- 사이트 주소와 키는 `config\record-servers.json` 에 저장됩니다.
|
||||
|
||||
## 목소리 모델 학습 — `train.bat`
|
||||
|
||||
동의 사이트 서버에서 학습 데이터를 꺼냅니다 (동의 중인 사람만 꺼내짐):
|
||||
@@ -97,16 +111,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
|
||||
|
||||
@@ -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 보다 먼저 돌아야 해서 이 모듈을 불러올 때 바로 한다."""
|
||||
|
||||
154
voice-changer/app/record_servers.py
Normal file
154
voice-changer/app/record_servers.py
Normal 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()])
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
; 음성 변환기 설치 프로그램 (Inno Setup 6). 빌드: scripts/build-release.sh 가 만든 dist\payload 를 담는다.
|
||||
; ISCC.exe installer\VoiceChanger.iss → dist\VoiceChangerSetup.exe
|
||||
; 하는 일
|
||||
; 1. 설치할 폴더를 고르게 한다. Python · 엔진 · 모델 · 설정 · 캐시 · 임시 파일이 모두 그 폴더 안에만 생긴다
|
||||
; 2. 그 폴더에 앱 파일을 풀고, 마이크마다 변환 모듈(APO)을 붙인다 (가상 오디오 장치 설치 없음)
|
||||
; 3. Python · 엔진 · torch(CUDA) · 엔진 기본 모델을 그 폴더 안으로 내려받는다 (scripts\install.ps1, 10~20분)
|
||||
; 제거할 때는 마이크 설정을 원래대로 되돌리고, 모델 · 녹음까지 지울지 묻는다.
|
||||
; 1. 설치할 폴더를 고르게 한다 (바탕 화면 · 문서 아래도 됨). 앱 · Python · 엔진 · 모델 · 설정 · 캐시가 모두 그 폴더에 생긴다.
|
||||
; 2. 관리자 권한 · 오디오 서비스가 실행하는 부분(마이크 모듈 APO · mic-apo.ps1 · 제거 프로그램)은
|
||||
; Program Files\VoiceChanger({app})에 두고, 마이크마다 APO 를 붙인다 (가상 오디오 장치 설치 없음).
|
||||
; 3. 고른 폴더는 관리자 권한으로 건드리지 않는다. 앱 파일 복사와 Python · 엔진 · 기본 모델 내려받기는
|
||||
; 설치를 시작한 사용자 권한으로 한다 (scripts\deploy.ps1 → install.ps1, 10~20분).
|
||||
; 고른 폴더의 상위가 사용자 소유면 설치 중에 그 폴더를 다른 곳을 가리키는 정션으로 바꿔칠 수 있어서,
|
||||
; 관리자 권한으로 그 경로에 쓰거나 권한을 바꾸면 엉뚱한 곳이 바뀔 수 있기 때문이다.
|
||||
; 제거할 때는 마이크 설정을 원래대로 되돌리고 Program Files 쪽을 지운다. 고른 폴더는 남긴다 (사용자가 직접 지울 수 있음).
|
||||
|
||||
#define AppName "음성 변환기"
|
||||
#ifndef AppVersion
|
||||
@@ -16,11 +20,11 @@ AppId={{8C3F2A51-6D0B-4E7A-9F3C-2B5E1D7A4C90}
|
||||
AppName={#AppName}
|
||||
AppVersion={#AppVersion}
|
||||
AppPublisher=voice_copy
|
||||
DefaultDirName={sd}\VoiceChanger
|
||||
DisableDirPage=no
|
||||
; {app} 은 항상 Program Files\VoiceChanger. 사용자가 고르는 폴더는 아래 [Code] 의 DataPage
|
||||
DefaultDirName={commonpf}\VoiceChanger
|
||||
DisableDirPage=yes
|
||||
UsePreviousAppDir=no
|
||||
DisableProgramGroupPage=yes
|
||||
DirExistsWarning=no
|
||||
AllowUNCPath=no
|
||||
PrivilegesRequired=admin
|
||||
ArchitecturesAllowed=x64compatible
|
||||
ArchitecturesInstallIn64BitMode=x64compatible
|
||||
@@ -31,51 +35,105 @@ Compression=lzma2
|
||||
SolidCompression=yes
|
||||
WizardStyle=modern
|
||||
UninstallFilesDir={app}\uninstall
|
||||
UninstallDisplayIcon={app}\VoiceChanger.exe
|
||||
; 이전 제거 기록을 이어 쓰지 않는다. v1.0.2 의 기록에는 고른 폴더(바탕 화면 등)의 파일이 들어 있어서,
|
||||
; 이어 쓰면 제거할 때 관리자 권한으로 그 경로의 파일을 지우게 된다 (정션으로 바꿔치면 다른 곳의 같은 이름 파일이 지워짐)
|
||||
UninstallLogMode=overwrite
|
||||
UninstallDisplayIcon={app}\payload\VoiceChanger.exe
|
||||
UninstallDisplayName={#AppName}
|
||||
|
||||
[Languages]
|
||||
Name: "ko"; MessagesFile: "compiler:Languages\Korean.isl"
|
||||
|
||||
[Messages]
|
||||
ko.SelectDirLabel3=음성 변환기를 설치할 폴더를 골라 주세요.%n%nPython · 변환 엔진 · 목소리 모델 · 설정 · 학습 파일 · 캐시가 모두 이 폴더 안에만 저장됩니다. 설치 중에 약 8GB 를 내려받고, 모델을 만들면 더 늘어나므로 15GB 이상 여유가 있는 드라이브를 골라 주세요.
|
||||
ko.DiskSpaceMBLabel=설치 중에 약 8GB 를 더 내려받습니다. 15GB 이상 비어 있는 드라이브를 권합니다.
|
||||
|
||||
[Tasks]
|
||||
Name: "desktopicon"; Description: "바탕 화면에 바로 가기 만들기"; Flags: unchecked
|
||||
|
||||
[Files]
|
||||
Source: "secure-dir.ps1"; Flags: dontcopy
|
||||
Source: "..\dist\payload\*"; DestDir: "{app}"; Flags: recursesubdirs createallsubdirs ignoreversion
|
||||
Source: "legacy.ps1"; Flags: dontcopy
|
||||
Source: "deploy.ps1"; DestDir: "{app}\scripts"; Flags: ignoreversion
|
||||
Source: "..\dist\payload\apo\*"; DestDir: "{app}\apo"; Flags: ignoreversion
|
||||
Source: "..\dist\payload\scripts\mic-apo.ps1"; DestDir: "{app}\scripts"; Flags: ignoreversion
|
||||
; 고른 폴더에 사용자 권한으로 복사할 앱 파일
|
||||
Source: "..\dist\payload\*"; DestDir: "{app}\payload"; Excludes: "\apo,\apo\*,\scripts\mic-apo.ps1"; Flags: recursesubdirs createallsubdirs ignoreversion
|
||||
|
||||
[Icons]
|
||||
Name: "{autoprograms}\{#AppName}"; Filename: "{app}\VoiceChanger.exe"; WorkingDir: "{app}"
|
||||
Name: "{autodesktop}\{#AppName}"; Filename: "{app}\VoiceChanger.exe"; WorkingDir: "{app}"; Tasks: desktopicon
|
||||
; 바로 가기는 앱을 복사한 뒤 [Code] 에서 만든다 ([Icons] 는 대상 파일이 아직 없을 때 만들어져 대상이 빈 바로 가기가 됨)
|
||||
[UninstallDelete]
|
||||
Type: files; Name: "{autoprograms}\{#AppName}.lnk"
|
||||
Type: files; Name: "{autodesktop}\{#AppName}.lnk"
|
||||
|
||||
[Run]
|
||||
Filename: "{app}\VoiceChanger.exe"; Description: "음성 변환기 실행"; Flags: postinstall nowait skipifsilent unchecked
|
||||
Filename: "{code:DataDir}\VoiceChanger.exe"; Description: "음성 변환기 실행"; Flags: postinstall nowait skipifsilent unchecked runasoriginaluser; Check: DeployDone
|
||||
|
||||
[UninstallRun]
|
||||
Filename: "powershell.exe"; Parameters: "-NoProfile -ExecutionPolicy Bypass -File ""{app}\scripts\mic-apo.ps1"" -Uninstall -Root ""{app}"""; 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;
|
||||
const
|
||||
UninstKey = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{8C3F2A51-6D0B-4E7A-9F3C-2B5E1D7A4C90}_is1';
|
||||
|
||||
var
|
||||
DataPage: TInputDirWizardPage;
|
||||
LegacyOld: String;
|
||||
DeployOk: Boolean;
|
||||
UninstDataDir: String;
|
||||
|
||||
{ Program Files\VoiceChanger. 설치 폴더 상수와 같지만 그 상수는 InitializeWizard 때 아직 정해지지 않아서 따로 둔다 }
|
||||
function SysDir: String;
|
||||
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 + '"',
|
||||
'', SW_HIDE, ewWaitUntilTerminated, Result) then
|
||||
Result := -1;
|
||||
Log('secure-dir ' + Mode + ' exit=' + IntToStr(Result));
|
||||
Result := ExpandConstant('{commonpf}\VoiceChanger');
|
||||
end;
|
||||
|
||||
function PowerShell(const Args: String; const Show: Integer; var Code: Integer): Boolean;
|
||||
{ 앱 복사가 사용자 권한으로 끝났을 때만 설치 뒤 바로 실행한다.
|
||||
설치 프로그램을 관리자 권한으로 시작하면 "원래 사용자" 도 관리자라 deploy.ps1 이 거부(33)하고, 실행도 하지 않는다 }
|
||||
function DeployDone: Boolean;
|
||||
begin
|
||||
Result := Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
|
||||
'-NoProfile -ExecutionPolicy Bypass ' + Args, ExpandConstant('{app}'), Show, ewWaitUntilTerminated, Code);
|
||||
Result := DeployOk;
|
||||
end;
|
||||
|
||||
function DataDir(Param: String): String;
|
||||
begin
|
||||
Result := RemoveBackslashUnlessRoot(DataPage.Values[0]);
|
||||
end;
|
||||
|
||||
{ 명령줄 인자로 넘길 경로. "D:\" 처럼 \ 로 끝나면 닫는 따옴표가 이스케이프되므로 "D:\." 로 }
|
||||
function ArgPath(const S: String): String;
|
||||
begin
|
||||
Result := S;
|
||||
if Copy(Result, Length(Result), 1) = '\' then
|
||||
Result := Result + '.';
|
||||
end;
|
||||
|
||||
function PowerShellExe: String;
|
||||
begin
|
||||
Result := ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe');
|
||||
end;
|
||||
|
||||
procedure InitializeWizard;
|
||||
var
|
||||
Def, Prev: String;
|
||||
begin
|
||||
DataPage := CreateInputDirPage(wpSelectDir, '설치할 폴더', '음성 변환기를 어디에 설치할까요?',
|
||||
'앱 · Python · 변환 엔진 · 목소리 모델 · 설정 · 학습 파일 · 캐시가 모두 이 폴더에 저장됩니다. ' +
|
||||
'바탕 화면이나 문서 아래도 됩니다. 설치 중에 약 8GB 를 내려받고, 모델을 만들면 더 늘어나므로 15GB 이상 여유가 있는 드라이브를 골라 주세요.',
|
||||
False, 'VoiceChanger');
|
||||
DataPage.Add('');
|
||||
{ 기본값: /DATADIR=, 지난 설치에서 고른 폴더, v1.0.2 까지의 설치 폴더(제거 정보의 App Path), C:\VoiceChanger }
|
||||
Def := ExpandConstant('{param:DATADIR|}');
|
||||
if Def = '' then
|
||||
Def := GetPreviousData('DataDir', '');
|
||||
if (Def = '') and RegQueryStringValue(HKLM, UninstKey, 'Inno Setup: App Path', Prev) and
|
||||
(CompareText(RemoveBackslashUnlessRoot(Prev), SysDir) <> 0) then
|
||||
Def := Prev;
|
||||
if Def = '' then
|
||||
Def := ExpandConstant('{sd}\VoiceChanger');
|
||||
DataPage.Values[0] := Def;
|
||||
end;
|
||||
|
||||
procedure RegisterPreviousData(PreviousDataKey: Integer);
|
||||
begin
|
||||
SetPreviousData(PreviousDataKey, 'DataDir', DataDir(''));
|
||||
end;
|
||||
|
||||
function IsEmptyDir(const Dir: String): Boolean;
|
||||
@@ -97,113 +155,178 @@ begin
|
||||
end;
|
||||
end;
|
||||
|
||||
{ 다른 파일이 들어 있는 폴더에는 설치하지 않는다. 설치 폴더의 권한을 잠그고, 제거할 때 지우기 때문.
|
||||
이 앱을 이미 설치한 폴더(업데이트)나 비어 있는 · 새 폴더만 받는다. }
|
||||
function IsUnder(const Child, Parent: String): Boolean;
|
||||
begin
|
||||
Result := Pos(Lowercase(AddBackslash(Parent)), Lowercase(AddBackslash(Child))) = 1;
|
||||
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 IsUnder(Dir, OD) then
|
||||
begin
|
||||
Result := True;
|
||||
Exit;
|
||||
end;
|
||||
end;
|
||||
end;
|
||||
|
||||
{ 고른 폴더 확인 (읽기만 함). 문제가 있으면 안내 문구 }
|
||||
function CheckDataDir(const Dir: String): String;
|
||||
begin
|
||||
Result := '';
|
||||
if (Length(Dir) < 3) or (Copy(Dir, 2, 2) <> ':\') then
|
||||
Result := '드라이브 문자로 시작하는 폴더를 골라 주세요. (예: C:\VoiceChanger)'
|
||||
else if IsUnder(Dir, SysDir) or IsUnder(SysDir, Dir) then
|
||||
Result := SysDir + ' 은 설치 프로그램이 쓰는 곳입니다. 다른 폴더를 골라 주세요.'
|
||||
{ 다른 파일이 든 폴더에는 설치하지 않는다 (예: 바탕 화면 자체). 이 앱이 이미 설치된 폴더(업데이트)는 된다 }
|
||||
else if DirExists(Dir) and not IsEmptyDir(Dir) and not FileExists(AddBackslash(Dir) + 'VoiceChanger.exe') then
|
||||
Result := '이 폴더에는 이미 다른 파일이 있습니다. 비어 있는 폴더나 새 폴더를 골라 주세요. (예: ' + AddBackslash(Dir) + 'VoiceChanger)';
|
||||
end;
|
||||
|
||||
function NextButtonClick(CurPageID: Integer): Boolean;
|
||||
var
|
||||
Dir: String;
|
||||
Msg: String;
|
||||
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 CurPageID <> DataPage.ID then Exit;
|
||||
Msg := CheckDataDir(DataDir(''));
|
||||
if Msg <> '' then
|
||||
begin
|
||||
SuppressibleMsgBox('이 폴더에는 이미 다른 파일이 있습니다.' + #13#10 +
|
||||
'비어 있는 폴더나 새 폴더를 골라 주세요. (예: ' + AddBackslash(Dir) + 'VoiceChanger)', mbError, MB_OK, IDOK);
|
||||
SuppressibleMsgBox(Msg, 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(DataDir('')) 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;
|
||||
|
||||
procedure StartAudio;
|
||||
var
|
||||
Code: Integer;
|
||||
begin
|
||||
Exec(PowerShellExe, '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code);
|
||||
end;
|
||||
|
||||
function PrepareToInstall(var NeedsRestart: Boolean): String;
|
||||
var
|
||||
Code: Integer;
|
||||
ApoInUse: Boolean;
|
||||
begin
|
||||
Result := '';
|
||||
Result := CheckDataDir(DataDir('')); { 조용한 설치(/DATADIR=)에서도 확인 }
|
||||
if Result <> '' then Exit;
|
||||
{ 다시 설치(업데이트)할 때 오디오 엔진이 쥐고 있는 APO 파일을 바꿀 수 있게 잠깐 오디오 서비스를 멈춘다.
|
||||
설치 뒤 mic-apo.ps1 이 다시 켠다. }
|
||||
if FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll')) then
|
||||
Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
|
||||
'-NoProfile -Command "Stop-Service -Name AudioEndpointBuilder -Force"', '', SW_HIDE, ewWaitUntilTerminated, Code);
|
||||
{ 파일을 풀기 전에 설치 폴더를 관리자 소유로 잠근다. 실패하면 설치하지 않는다. }
|
||||
case SecureDir('Prepare', ExpandConstant('{app}')) of
|
||||
0: ;
|
||||
10: Result := '이 폴더에는 이미 다른 파일이 있습니다. 비어 있는 폴더나 새 폴더를 골라 주세요.';
|
||||
11: Result := '설치 폴더 안에 링크(정션 · 심볼릭 링크)가 있어 안전하게 설치할 수 없습니다. 링크를 지우거나 새 폴더를 골라 주세요.';
|
||||
v1.0.1 까지는 APO 가 고른 폴더의 apo\ 에 있었다 (legacy.ps1 이 지움). 설치 뒤 mic-apo.ps1 이 다시 켠다. }
|
||||
ApoInUse := FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll')) or FileExists(DataDir('') + '\apo\VoiceChangerAPO.dll');
|
||||
if ApoInUse then
|
||||
Exec(PowerShellExe, '-NoProfile -Command "Stop-Service -Name AudioEndpointBuilder -Force"', '', SW_HIDE, ewWaitUntilTerminated, Code);
|
||||
{ v1.0.0 · v1.0.1 이 관리자 소유로 잠가 둔 폴더면, 그 실행 부분을 지우고 <폴더>.old 로 비켜 둔다 (관리자 권한).
|
||||
상위 폴더가 관리자 소유라 일반 사용자가 바꿔칠 수 없을 때만 legacy.ps1 이 한다. }
|
||||
LegacyOld := DataDir('') + '.old';
|
||||
ExtractTemporaryFile('legacy.ps1');
|
||||
if not Exec(PowerShellExe, '-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{tmp}\legacy.ps1') +
|
||||
'" -App "' + ArgPath(DataDir('')) + '" -Sys "' + ExpandConstant('{app}') + '" -Old "' + LegacyOld + '"',
|
||||
'', SW_HIDE, ewWaitUntilTerminated, Code) then
|
||||
Code := -1;
|
||||
Log('legacy exit=' + IntToStr(Code));
|
||||
case Code of
|
||||
0: LegacyOld := '';
|
||||
1: ;
|
||||
20: Result := '이 폴더에 있는 이전 버전을 안전하게 옮길 수 없습니다. 새 폴더를 골라 주세요.';
|
||||
22: Result := LegacyOld + ' 폴더가 이미 있습니다. 그 폴더를 지우거나 다른 폴더를 골라 주세요.';
|
||||
else
|
||||
Result := '설치 폴더의 권한을 잠그지 못했습니다. 다른 폴더를 골라 다시 설치해 주세요.';
|
||||
Result := '이전 버전 폴더를 정리하지 못했습니다 (코드 ' + IntToStr(Code) + '). 다른 폴더를 골라 다시 설치해 주세요.';
|
||||
end;
|
||||
if (Result <> '') and FileExists(ExpandConstant('{app}\apo\VoiceChangerAPO.dll')) then
|
||||
Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code);
|
||||
if (Result <> '') and ApoInUse then
|
||||
StartAudio;
|
||||
end;
|
||||
|
||||
procedure CurStepChanged(CurStep: TSetupStep);
|
||||
var
|
||||
Code: Integer;
|
||||
Args: String;
|
||||
begin
|
||||
if CurStep <> ssPostInstall then Exit;
|
||||
{ 데이터 폴더에만 사용자 쓰기 권한을 주고, 관리자 권한으로 실행되는 파일이 잠겼는지 확인한다.
|
||||
확인이 안 되면 관리자 권한으로 아무것도 실행하지 않는다. }
|
||||
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 +
|
||||
'음성 변환기를 제거한 뒤 다른 폴더(예: C:\VoiceChanger)에 다시 설치해 주세요.', mbError, MB_OK, IDOK);
|
||||
Exit;
|
||||
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 Exec(PowerShellExe, '-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{app}\scripts\mic-apo.ps1') +
|
||||
'" -Install -Root "' + ExpandConstant('{app}') + '"', ExpandConstant('{app}'), SW_HIDE, ewWaitUntilTerminated, Code) or (Code <> 0) then
|
||||
begin
|
||||
Exec(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'), '-NoProfile -Command "Start-Service Audiosrv"', '', SW_HIDE, ewWaitUntilTerminated, Code);
|
||||
StartAudio;
|
||||
SuppressibleMsgBox('마이크에 변환 모듈을 붙이지 못했습니다. 설치가 끝난 뒤 음성 변환기의 "마이크 다시 연결" 을 눌러 주세요.', mbError, MB_OK, IDOK);
|
||||
end;
|
||||
|
||||
WizardForm.StatusLabel.Caption := 'Python · 변환 엔진 · 기본 모델을 설치 폴더로 내려받는 중... (10~20분, 검은 창에 진행 상황이 나옵니다)';
|
||||
{ 일반 권한(설치를 시작한 사용자)으로 받는다. 관리자 권한으로 사용자 쓰기 폴더(env · engine)의 코드를 돌리지 않게. }
|
||||
if not ExecAsOriginalUser(ExpandConstant('{sys}\WindowsPowerShell\v1.0\powershell.exe'),
|
||||
'-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{app}\scripts\install.ps1') + '"',
|
||||
ExpandConstant('{app}'), SW_SHOWNORMAL, ewWaitUntilTerminated, Code) or (Code <> 0) then
|
||||
WizardForm.StatusLabel.Caption := '앱을 복사하고 Python · 변환 엔진 · 기본 모델을 내려받는 중... (10~20분, 검은 창에 진행 상황이 나옵니다)';
|
||||
{ 설치를 시작한 사용자 권한으로: 고른 폴더에 앱 파일 복사 → 이전 버전의 데이터 폴더 옮기기 → install.ps1 }
|
||||
Args := '-NoProfile -ExecutionPolicy Bypass -File "' + ExpandConstant('{app}\scripts\deploy.ps1') + '" -Data "' + ArgPath(DataDir('')) + '"';
|
||||
if LegacyOld <> '' then
|
||||
Args := Args + ' -From "' + LegacyOld + '"';
|
||||
if not ExecAsOriginalUser(PowerShellExe, Args, ExpandConstant('{app}'), SW_SHOWNORMAL, ewWaitUntilTerminated, Code) then
|
||||
Code := -1;
|
||||
Log('deploy exit=' + IntToStr(Code));
|
||||
DeployOk := Code = 0;
|
||||
case Code of
|
||||
0: ;
|
||||
33: SuppressibleMsgBox('설치 프로그램이 관리자 권한으로 시작되어 앱 파일을 복사하지 않았습니다.' + #13#10 +
|
||||
'관리자 권한으로 실행하지 말고 VoiceChangerSetup.exe 를 그냥 더블클릭해서 다시 설치해 주세요.' + #13#10 +
|
||||
'(관리자 권한 확인 창이 뜨는 것은 정상입니다)', mbError, MB_OK, IDOK);
|
||||
31: SuppressibleMsgBox(DataDir('') + ' 이 다른 곳을 가리키는 링크(정션)라서 앱을 복사하지 않았습니다.' + #13#10 +
|
||||
'링크를 지우거나 다른 폴더를 골라 다시 설치해 주세요.', mbError, MB_OK, IDOK);
|
||||
32: SuppressibleMsgBox(DataDir('') + ' 에 앱 파일을 복사하지 못했습니다 (쓰기 권한이 없는 폴더일 수 있습니다).' + #13#10 +
|
||||
'내 계정으로 쓸 수 있는 폴더(예: C:\VoiceChanger, 바탕 화면)를 골라 다시 설치해 주세요.', mbError, MB_OK, IDOK);
|
||||
else
|
||||
SuppressibleMsgBox('엔진을 내려받지 못했습니다 (인터넷 연결을 확인해 주세요).' + #13#10 +
|
||||
'설치 폴더의 install.bat 을 실행하면 받은 곳부터 이어서 받습니다.', mbError, MB_OK, IDOK);
|
||||
DataDir('') + '\install.bat 을 실행하면 받은 곳부터 이어서 받습니다.', mbError, MB_OK, IDOK);
|
||||
end;
|
||||
if FileExists(DataDir('') + '\VoiceChanger.exe') then
|
||||
begin
|
||||
CreateShellLink(ExpandConstant('{autoprograms}\{#AppName}.lnk'), '{#AppName}', DataDir('') + '\VoiceChanger.exe', '', DataDir(''), '', 0, SW_SHOWNORMAL);
|
||||
if WizardIsTaskSelected('desktopicon') then
|
||||
CreateShellLink(ExpandConstant('{autodesktop}\{#AppName}.lnk'), '{#AppName}', DataDir('') + '\VoiceChanger.exe', '', DataDir(''), '', 0, SW_SHOWNORMAL);
|
||||
end;
|
||||
{ legacy.ps1 이 비켜 둔 이전 버전 폴더: 데이터 폴더를 다 옮겼으면 비어 있다 (상위가 관리자 소유라 이 경로는 안전) }
|
||||
if (LegacyOld <> '') and DirExists(LegacyOld) and not RemoveDir(LegacyOld) then
|
||||
SuppressibleMsgBox('이전 버전 폴더 ' + LegacyOld + ' 에 옮기지 못한 파일이 남아 있습니다. 확인한 뒤 지워 주세요.', mbInformation, MB_OK, IDOK);
|
||||
end;
|
||||
|
||||
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
|
||||
var
|
||||
App: String;
|
||||
Code: Integer;
|
||||
begin
|
||||
if CurUninstallStep = usUninstall then
|
||||
begin
|
||||
if not RegQueryStringValue(HKLM, UninstKey, 'Inno Setup CodeFile: DataDir', UninstDataDir) then
|
||||
UninstDataDir := '';
|
||||
Exit;
|
||||
end;
|
||||
{ 마이크 되돌리기([UninstallRun])와 설치 파일 지우기가 끝난 뒤 }
|
||||
if CurUninstallStep <> usPostUninstall then Exit;
|
||||
App := ExpandConstant('{app}');
|
||||
{ 설치 중에 내려받은 것들 (설치 파일 목록에 없어서 직접 지운다) }
|
||||
DelTree(App + '\env', True, True, True);
|
||||
DelTree(App + '\engine', True, True, True);
|
||||
DelTree(App + '\tools', True, True, True);
|
||||
DelTree(App + '\cache', True, True, True);
|
||||
DelTree(App + '\app\__pycache__', True, True, True);
|
||||
RemoveDir(App + '\app');
|
||||
{ 사용자가 만든 것은 물어보고 지운다. 조용히 제거할 때는 남겨 둔다 }
|
||||
{ 앱이 만든 폴더만 지운다. 설치 폴더 자체는 비어 있을 때만 지운다 (RemoveDir 는 빈 폴더만 지움) }
|
||||
if (not UninstallSilent) and (MsgBox('만든 목소리 모델 · 학습 파일 · 녹음 · 설정도 지울까요?' + #13#10 +
|
||||
'(models, training, datasets, config 폴더)' + #13#10#13#10 + '"아니요" 를 누르면 남겨 둡니다.', mbConfirmation, MB_YESNO) = IDYES) then
|
||||
begin
|
||||
DelTree(App + '\models', True, True, True);
|
||||
DelTree(App + '\training', True, True, True);
|
||||
DelTree(App + '\datasets', True, True, True);
|
||||
DelTree(App + '\config', True, True, True);
|
||||
end;
|
||||
RemoveDir(App + '\models');
|
||||
RemoveDir(App + '\training');
|
||||
RemoveDir(App + '\datasets');
|
||||
RemoveDir(App + '\config');
|
||||
DeleteFile(App + '\apo\mic-apo.log');
|
||||
RemoveDir(App + '\apo');
|
||||
RemoveDir(App);
|
||||
{ Program Files 쪽(관리자만 쓰는 곳)은 남은 기록 · 빈 폴더까지 지운다.
|
||||
제거 기록을 이어 쓰지 않아서(overwrite) 업그레이드 전부터 있던 폴더는 Inno 가 지우지 않는다. 제거 프로그램 파일은
|
||||
이 뒤에 지워지므로, 끝난 뒤 빈 uninstall 폴더와 설치 폴더를 지우는 cmd 를 따로 띄운다 (rmdir 은 빈 폴더만 지움) }
|
||||
DelTree(ExpandConstant('{app}\apo'), True, True, True);
|
||||
DelTree(ExpandConstant('{app}\scripts'), True, True, True);
|
||||
DelTree(ExpandConstant('{app}\payload'), True, True, True);
|
||||
Exec(ExpandConstant('{cmd}'), '/c ping -n 4 127.0.0.1 >nul & rmdir "' + ExpandConstant('{app}\uninstall') + '" & rmdir "' + ExpandConstant('{app}') + '"',
|
||||
'', SW_HIDE, ewNoWait, Code);
|
||||
{ 고른 폴더는 관리자 권한으로 지우지 않는다 (정션으로 바꿔쳐 다른 곳을 지우게 만들 수 있음). 내 계정 폴더라 직접 지울 수 있다 }
|
||||
if (UninstDataDir <> '') and DirExists(UninstDataDir) and not UninstallSilent then
|
||||
MsgBox('마이크 설정을 되돌리고 프로그램을 지웠습니다.' + #13#10#13#10 +
|
||||
'앱 · Python · 엔진 · 목소리 모델 · 녹음 · 설정이 든 폴더는 남겨 두었습니다:' + #13#10 + UninstDataDir + #13#10#13#10 +
|
||||
'필요 없으면 이 폴더를 직접 지워 주세요.', mbInformation, MB_OK);
|
||||
end;
|
||||
|
||||
58
voice-changer/installer/deploy.ps1
Normal file
58
voice-changer/installer/deploy.ps1
Normal file
@@ -0,0 +1,58 @@
|
||||
# 고른 폴더에 앱을 설치한다. 설치 프로그램이 "설치를 시작한 사용자" 권한으로 실행한다 (ExecAsOriginalUser).
|
||||
# 고른 폴더(바탕 화면 등)는 상위가 사용자 소유일 수 있어서 관리자 권한으로는 건드리지 않는다:
|
||||
# 관리자 권한으로 경로를 다루는 도중에 폴더를 정션으로 바꿔치면 엉뚱한 곳에 쓰거나 권한을 바꾸게 되기 때문.
|
||||
# deploy.ps1 -Data <고른 폴더> [-From <이전 버전 폴더>]
|
||||
# 1. 이전 버전 폴더에서 데이터 폴더(models · config · env 등)를 옮겨 온다
|
||||
# - v1.0.0 · v1.0.1: 설치 프로그램(legacy.ps1)이 <폴더>.old 로 비켜 두고 -From 으로 알려 줌
|
||||
# - v1.0.2: 고른 폴더가 관리자 소유로 잠겨 있으면, 상위 폴더가 내 것일 때 이름을 바꿔 비켜 두고 새로 만든다
|
||||
# 2. Program Files\VoiceChanger\payload 의 앱 파일을 복사한다
|
||||
# 3. scripts\install.ps1 로 Python · 엔진 · 기본 모델을 받는다
|
||||
# 종료 코드: 0 성공, 31 고른 폴더가 링크(정션), 32 폴더를 만들거나 복사하지 못함,
|
||||
# 33 관리자 권한으로 실행됨(설치 프로그램을 관리자 권한으로 시작하면 "원래 사용자" 도 관리자), 그 밖 = install.ps1 실패
|
||||
param([Parameter(Mandatory)][string]$Data, [string]$From)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
# 경로를 건드리기 전에 실제 토큰을 확인한다. 관리자 권한이면 이 스크립트가 지키려는 분리가 없어지므로 아무것도 하지 않는다
|
||||
$me = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
|
||||
if ($me.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
|
||||
Write-Host "[deploy] 관리자 권한으로 실행되어 중단합니다. 설치 프로그램을 그냥 더블클릭해서 실행해 주세요."
|
||||
exit 33
|
||||
}
|
||||
[Console]::OutputEncoding = [Text.Encoding]::UTF8
|
||||
$Payload = Join-Path (Split-Path -Parent $PSScriptRoot) 'payload'
|
||||
$DataDirs = 'models', 'training', 'datasets', 'config', 'cache', 'env', 'engine', 'tools'
|
||||
$Data = [IO.Path]::GetFullPath($Data).TrimEnd('\')
|
||||
|
||||
function Say($m) { Write-Host "[deploy] $m" }
|
||||
function Is-Link([string]$p) { ([IO.File]::GetAttributes($p) -band [IO.FileAttributes]::ReparsePoint) -ne 0 }
|
||||
function Can-Write([string]$d) {
|
||||
$t = Join-Path $d ".vc-write-test-$PID"
|
||||
try { [IO.File]::WriteAllText($t, ''); Remove-Item -LiteralPath $t -Force; return $true } catch { return $false }
|
||||
}
|
||||
|
||||
try {
|
||||
if (Test-Path -LiteralPath $Data) {
|
||||
if (Is-Link $Data) { Say "고른 폴더가 링크(정션)입니다: $Data"; exit 31 }
|
||||
if (-not (Can-Write $Data)) {
|
||||
$old = "$Data.old-$(Get-Date -Format yyyyMMddHHmmss)"
|
||||
Rename-Item -LiteralPath $Data -NewName (Split-Path -Leaf $old)
|
||||
Say "이전 버전 폴더를 비켜 둠: $old"
|
||||
$From = $old
|
||||
}
|
||||
}
|
||||
New-Item -ItemType Directory -Force -Path $Data | Out-Null
|
||||
if ($From -and (Test-Path -LiteralPath $From)) {
|
||||
foreach ($d in $DataDirs) {
|
||||
$s = Join-Path $From $d
|
||||
$t = Join-Path $Data $d
|
||||
if ((Test-Path -LiteralPath $s) -and -not (Test-Path -LiteralPath $t)) { Move-Item -LiteralPath $s -Destination $t; Say "옮김: $d" }
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
Say "실패: $($_.Exception.Message)"
|
||||
exit 32
|
||||
}
|
||||
& robocopy $Payload $Data /E /R:1 /W:1 /NFL /NDL /NJH /NJS /NP | Out-Host
|
||||
if ($LASTEXITCODE -ge 8) { Say "앱 파일을 복사하지 못함 (robocopy $LASTEXITCODE)"; exit 32 }
|
||||
$global:LASTEXITCODE = 0
|
||||
& (Join-Path $Data 'scripts\install.ps1')
|
||||
exit $LASTEXITCODE
|
||||
84
voice-changer/installer/legacy.ps1
Normal file
84
voice-changer/installer/legacy.ps1
Normal file
@@ -0,0 +1,84 @@
|
||||
# v1.0.0 · v1.0.1 이 설치한 폴더 정리 (설치 프로그램이 관리자 권한으로 {tmp} 에서 실행).
|
||||
# 그 버전은 고른 폴더를 관리자 소유로 잠그고 그 안에 실행 파일 · 제거 프로그램 · 마이크 모듈을 두었다.
|
||||
# 이제 앱 파일은 사용자 권한으로 복사하므로(deploy.ps1), 관리자 권한으로 하는 일은 이것뿐이다:
|
||||
# 이전 실행 부분을 이름을 지정해 지우고, 마이크 백업을 Program Files 쪽으로 옮기고, 폴더 이름을 -Old 로 바꾼다.
|
||||
# 남은 데이터 폴더(models · config · env 등, 일반 사용자가 쓸 수 있음)는 deploy.ps1 이 사용자 권한으로 새 폴더에 옮긴다.
|
||||
# 관리자가 아닌 누구도 이 폴더나 그 위 폴더를 지우거나 이름을 바꿀 수 없을 때만 한다 (소유자 · ACL 로 확인).
|
||||
# 그래야 일반 사용자가 이 작업 도중에 경로를 다른 곳을 가리키는 정션으로 바꿔칠 수 없다. ACL 은 관리자만 바꿀 수 있어서
|
||||
# 확인한 뒤에도 그대로다. v1.0.0 · v1.0.1 은 상위가 관리자 소유인 곳에만 설치했고 폴더를 이렇게 잠갔다.
|
||||
# -App <고른 폴더> -Sys <Program Files\VoiceChanger> -Old <새 이름 전체 경로>
|
||||
# 종료 코드: 0 = 이전 버전 폴더 아님(할 일 없음), 1 = 정리하고 -Old 로 옮김,
|
||||
# 20 = 이전 버전 폴더지만 안전하게 다룰 수 없음, 22 = -Old 가 이미 있음, 12 = 실패
|
||||
param([Parameter(Mandatory)][string]$App, [Parameter(Mandatory)][string]$Sys, [Parameter(Mandatory)][string]$Old)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$SY = 'S-1-5-18'; $BA = 'S-1-5-32-544'
|
||||
$TI = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'
|
||||
$Sid = [System.Security.Principal.SecurityIdentifier]
|
||||
$App = [IO.Path]::GetFullPath($App).TrimEnd('\')
|
||||
|
||||
function Say($m) { Write-Host "[legacy] $m" }
|
||||
function Is-Link([string]$p) { ([IO.File]::GetAttributes($p) -band [IO.FileAttributes]::ReparsePoint) -ne 0 }
|
||||
function Owner-Sid([string]$p) { (Get-Acl -LiteralPath $p).GetOwner($Sid).Value }
|
||||
# 관리자가 아닌 사람이 $p 를 지우거나 이름을 바꿀 수 있는지: 소유자가 관리자가 아니거나,
|
||||
# $p 에 DELETE · WRITE_DAC · WRITE_OWNER · GENERIC_ALL, 또는 상위 폴더에 DELETE_CHILD · WRITE_DAC · WRITE_OWNER · GENERIC_ALL 을 주는 항목이 있으면 그렇다
|
||||
$Admins = @($SY, $BA, $TI)
|
||||
function Grants([string]$p, [int]$bits) {
|
||||
$acl = Get-Acl -LiteralPath $p
|
||||
@($acl.GetAccessRules($true, $true, $Sid) | Where-Object { $_.AccessControlType -eq 'Allow' -and
|
||||
($_.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly) -eq 0 -and
|
||||
$_.IdentityReference.Value -notin $Admins -and ([int]$_.FileSystemRights -band $bits) }).Count -gt 0
|
||||
}
|
||||
function Swappable([string]$p) {
|
||||
$parent = Split-Path -Parent $p
|
||||
if (-not $parent) { return $false } # 드라이브 루트는 지우거나 이름을 바꿀 수 없음
|
||||
if ((Owner-Sid $p) -notin $Admins) { return $true }
|
||||
if (Grants $p (0x10000 -bor 0x40000 -bor 0x80000 -bor 0x10000000)) { return $true }
|
||||
if (Grants $parent (0x40 -bor 0x40000 -bor 0x80000 -bor 0x10000000)) { return $true }
|
||||
return $false
|
||||
}
|
||||
|
||||
try {
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $App 'uninstall\unins000.exe'))) { exit 0 }
|
||||
$p = $App
|
||||
while ($p) {
|
||||
if ((Is-Link $p) -or (Swappable $p)) { Say "안전하게 다룰 수 없음: $p (link=$(Is-Link $p) owner=$(Owner-Sid $p))"; exit 20 }
|
||||
$p = Split-Path -Parent $p
|
||||
}
|
||||
if (Test-Path -LiteralPath $Old) { Say "이미 있음: $Old"; exit 22 }
|
||||
# 이전 배포의 실행 부분만 이름을 지정해 지운다. 목록에 없는 파일은 남겨 두고 폴더째 -Old 로 옮긴다.
|
||||
$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', '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')
|
||||
'app\__pycache__' = @('*.pyc')
|
||||
}
|
||||
$n = 0
|
||||
foreach ($d in $known.Keys) {
|
||||
$dir = if ($d -eq '.') { $App } else { Join-Path $App $d }
|
||||
if (-not (Test-Path -LiteralPath $dir -PathType Container)) { continue }
|
||||
foreach ($pat in $known[$d]) {
|
||||
Get-ChildItem -LiteralPath $dir -Force -File -Filter $pat | ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force; $n++ }
|
||||
}
|
||||
}
|
||||
# 마이크 설정 백업 (apo\ 는 관리자만 쓰던 폴더). mic-apo.ps1 이 Program Files 쪽에서 읽고 값을 다시 검증한다
|
||||
$bk = Join-Path $App 'apo\mic-apo-backup.json'
|
||||
$sysBk = Join-Path $Sys 'apo\mic-apo-backup.json'
|
||||
if ((Test-Path -LiteralPath $bk) -and -not (Test-Path -LiteralPath $sysBk)) {
|
||||
New-Item -ItemType Directory -Force -Path (Split-Path $sysBk) | Out-Null
|
||||
Move-Item -LiteralPath $bk -Destination $sysBk
|
||||
Say "마이크 백업을 옮김: $sysBk"
|
||||
}
|
||||
foreach ($d in 'app\__pycache__', 'app', 'scripts', 'launcher', 'uninstall', 'apo') { # 비었을 때만
|
||||
$dir = Join-Path $App $d
|
||||
if ((Test-Path -LiteralPath $dir) -and -not [IO.Directory]::EnumerateFileSystemEntries($dir).GetEnumerator().MoveNext()) { Remove-Item -LiteralPath $dir -Force }
|
||||
}
|
||||
Rename-Item -LiteralPath $App -NewName (Split-Path -Leaf $Old)
|
||||
Say "이전 배포 파일 $n 개를 지우고 $Old 로 옮김"
|
||||
exit 1
|
||||
} catch {
|
||||
Say "실패: $($_.Exception.Message)"
|
||||
exit 12
|
||||
}
|
||||
@@ -1,153 +0,0 @@
|
||||
# 설치 폴더 보안 (설치 프로그램이 관리자 권한으로 {tmp} 에서 실행). 종료 코드로 결과를 알린다.
|
||||
# -Mode CheckParent -App <폴더> 가장 가까운 상위 폴더가 드라이브 루트이거나 관리자 · SYSTEM · TrustedInstaller 소유인지
|
||||
# 0 = 괜찮음, 20 = 일반 사용자 소유 (그 사용자가 설치 폴더를 통째로 바꿔치기할 수 있음)
|
||||
# -Mode Prepare -App <폴더> 파일을 풀기 전: 폴더를 만들고 소유자를 Administrators 로, 권한을 관리자 · SYSTEM 전체 +
|
||||
# Users 읽기로 잠근다. 업데이트면 이전 버전이 사용자 쓰기 폴더에 두었던 실행 부분을 지운다.
|
||||
# 10 = 다른 파일이 있는 폴더, 11 = 링크(정션 · 심볼릭 링크)가 있음, 12 = 잠그지 못함
|
||||
# -Mode Finish -App <폴더> 파일을 푼 뒤: 데이터 폴더에만 Users 수정 권한을 주고, 관리자 권한으로 실행되는 파일이
|
||||
# 관리자 소유이고 일반 사용자가 쓸 수 없는지 확인한다. 13 = 확인 실패
|
||||
param([Parameter(Mandatory)][string]$Mode, [Parameter(Mandatory)][string]$App)
|
||||
$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'
|
||||
$UserDirs = 'models', 'training', 'datasets', 'config', 'cache', 'env', 'engine', 'tools'
|
||||
# 쓰기 계열 권한 비트: WriteData · AppendData · WriteEA · DeleteChild · WriteAttributes · Delete · WriteDAC · WriteOwner + GENERIC_ALL/WRITE
|
||||
$WriteBits = 0x2 -bor 0x4 -bor 0x10 -bor 0x40 -bor 0x100 -bor 0x10000 -bor 0x40000 -bor 0x80000 -bor 0x10000000 -bor 0x40000000
|
||||
$Sid = [System.Security.Principal.SecurityIdentifier]
|
||||
$App = [IO.Path]::GetFullPath($App).TrimEnd('\')
|
||||
|
||||
function Say($m) { Write-Host "[secure-dir] $m" }
|
||||
function Is-Link([string]$p) { ([IO.File]::GetAttributes($p) -band [IO.FileAttributes]::ReparsePoint) -ne 0 }
|
||||
|
||||
# 링크를 따라 들어가지 않고 폴더 안을 모두 훑어, 설치 폴더 밖을 가리키는 첫 링크를 찾는다.
|
||||
# 안을 가리키는 링크는 괜찮다 (uv 가 tools\python 안에 "cpython-3.12-..." → "cpython-3.12.x-..." 정션을 만듦).
|
||||
function Link-Target([string]$p) {
|
||||
$t = @((Get-Item -LiteralPath $p -Force).Target) | Select-Object -First 1
|
||||
if (-not $t) { return $null }
|
||||
$t = [string]$t
|
||||
if ($t.StartsWith('\\?\')) { $t = $t.Substring(4) }
|
||||
if (-not [IO.Path]::IsPathRooted($t)) { $t = Join-Path (Split-Path -Parent $p) $t }
|
||||
return [IO.Path]::GetFullPath($t)
|
||||
}
|
||||
function Find-Link([string]$dir) {
|
||||
$stack = New-Object System.Collections.Stack
|
||||
$stack.Push($dir)
|
||||
while ($stack.Count) {
|
||||
foreach ($e in [IO.Directory]::EnumerateFileSystemEntries($stack.Pop())) {
|
||||
$a = [IO.File]::GetAttributes($e)
|
||||
if ($a -band [IO.FileAttributes]::ReparsePoint) {
|
||||
$t = Link-Target $e
|
||||
if (-not $t -or -not ($t.StartsWith($App + '\', [StringComparison]::OrdinalIgnoreCase))) { return "$e -> $t" }
|
||||
continue # 안쪽 링크: 따라 들어가지 않음 (가리키는 곳은 따로 훑음)
|
||||
}
|
||||
if ($a -band [IO.FileAttributes]::Directory) { $stack.Push($e) }
|
||||
}
|
||||
}
|
||||
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')
|
||||
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 }
|
||||
$link = Find-Link $App
|
||||
if ($link) { Say "링크 발견: $link"; exit 11 }
|
||||
}
|
||||
if ($upgrade) {
|
||||
# 이전 버전(21b4278)은 설치 폴더 전체를 사용자 쓰기로 두었다. 이전 배포에 들어 있던 실행 부분은 믿지 않고
|
||||
# 이름을 하나씩 지정해서만 지운다 (새 파일은 곧 다시 풂). 목록에 없는 파일(사용자가 넣어 둔 녹음 등)은 지우지 않고,
|
||||
# 아래에서 소유자 · 권한만 관리자 쪽으로 정리한다. 제거 기록(unins*.dat)은 제거할 때 관리자 권한으로 쓰이므로 꼭 지운다.
|
||||
$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')
|
||||
'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')
|
||||
'app\__pycache__' = @('*.pyc')
|
||||
}
|
||||
$n = 0
|
||||
foreach ($d in $known.Keys) {
|
||||
$dir = if ($d -eq '.') { $App } else { Join-Path $App $d }
|
||||
if (-not (Test-Path -LiteralPath $dir -PathType Container)) { continue }
|
||||
foreach ($pat in $known[$d]) {
|
||||
Get-ChildItem -LiteralPath $dir -Force -File -Filter $pat | ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force; $n++ }
|
||||
}
|
||||
}
|
||||
foreach ($d in 'app\__pycache__', 'app', 'scripts', 'launcher', 'uninstall') { # 비었을 때만
|
||||
$dir = Join-Path $App $d
|
||||
if ((Test-Path -LiteralPath $dir) -and -not [IO.Directory]::EnumerateFileSystemEntries($dir).GetEnumerator().MoveNext()) { Remove-Item -LiteralPath $dir -Force }
|
||||
}
|
||||
Say "업데이트: 이전 배포 파일 $n 개 정리 (그 밖의 파일은 남김)"
|
||||
}
|
||||
New-Item -ItemType Directory -Force -Path $App | Out-Null
|
||||
$sd = New-Object System.Security.AccessControl.DirectorySecurity
|
||||
# 소유자 · 그룹 · DACL 만 쓴다 (SACL 까지 쓰면 감사 특권이 필요함)
|
||||
$sd.SetSecurityDescriptorSddlForm("O:BAG:SYD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;BU)",
|
||||
[System.Security.AccessControl.AccessControlSections]'Owner, Group, Access')
|
||||
[IO.Directory]::SetAccessControl($App, $sd)
|
||||
foreach ($c in Get-ChildItem -LiteralPath $App -Force) {
|
||||
& icacls $c.FullName /setowner "*$BA" /C /Q | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { Say "소유자 변경 실패: $($c.FullName)"; exit 12 }
|
||||
if ($c.Name -notin $UserDirs) {
|
||||
# 관리자 쪽 하위 항목(apo\ 백업 등): 전부 관리자 소유, 명시 권한 없이 상속만
|
||||
& icacls $c.FullName /setowner "*$BA" /T /C /Q | Out-Null
|
||||
& icacls $c.FullName /reset /T /C /Q | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { Say "권한 초기화 실패: $($c.FullName)"; exit 12 }
|
||||
}
|
||||
}
|
||||
$acl = Get-Acl -LiteralPath $App
|
||||
$rules = @($acl.GetAccessRules($true, $true, $Sid))
|
||||
$bad = @($rules | ? { $_.IsInherited -or $_.IdentityReference.Value -notin @($SY, $BA, $BU) -or
|
||||
($_.IdentityReference.Value -eq $BU -and ([int]$_.FileSystemRights -band $WriteBits)) })
|
||||
if ($acl.GetOwner($Sid).Value -ne $BA -or -not $acl.AreAccessRulesProtected -or $bad.Count -gt 0) {
|
||||
Say "잠금 확인 실패: owner=$($acl.GetOwner($Sid).Value) protected=$($acl.AreAccessRulesProtected) bad=$($bad.Count)"
|
||||
exit 12
|
||||
}
|
||||
Say "잠금 완료"
|
||||
exit 0
|
||||
}
|
||||
|
||||
if ($Mode -eq 'Finish') {
|
||||
foreach ($d in $UserDirs) {
|
||||
$p = Join-Path $App $d
|
||||
if (-not (Test-Path -LiteralPath $p)) { New-Item -ItemType Directory -Path $p | Out-Null }
|
||||
if (Is-Link $p) { Say "데이터 폴더가 링크: $p"; exit 13 }
|
||||
$has = @((Get-Acl -LiteralPath $p).GetAccessRules($true, $false, $Sid) | ? {
|
||||
$_.IdentityReference.Value -eq $BU -and ([int]$_.FileSystemRights -band 0x2) -and $_.InheritanceFlags -eq 'ContainerInherit, ObjectInherit' })
|
||||
if (-not $has) {
|
||||
& icacls $p /grant "*${BU}:(OI)(CI)M" /C /Q | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { Say "데이터 폴더 권한 실패: $p"; exit 13 }
|
||||
}
|
||||
}
|
||||
# 관리자 권한으로 실행되거나 읽히는 것: 루트 파일, scripts\ app\ apo\ launcher\ uninstall\ 아래 전부
|
||||
$items = @(Get-Item -LiteralPath $App -Force) + @(Get-ChildItem -LiteralPath $App -Force -File)
|
||||
foreach ($d in 'scripts', 'app', 'apo', 'launcher', 'uninstall') {
|
||||
$p = Join-Path $App $d
|
||||
if (Test-Path -LiteralPath $p) { $items += Get-Item -LiteralPath $p -Force; $items += @(Get-ChildItem -LiteralPath $p -Recurse -Force) }
|
||||
}
|
||||
foreach ($it in $items) {
|
||||
if (Is-Link $it.FullName) { Say "링크: $($it.FullName)"; exit 13 }
|
||||
$acl = Get-Acl -LiteralPath $it.FullName
|
||||
$o = $acl.GetOwner($Sid).Value
|
||||
$w = @($acl.GetAccessRules($true, $true, $Sid) | ? { $_.AccessControlType -eq 'Allow' -and
|
||||
$_.IdentityReference.Value -notin @($SY, $BA, $TI) -and ([int]$_.FileSystemRights -band $WriteBits) })
|
||||
if ($o -notin @($BA, $SY) -or $w.Count -gt 0) { Say "확인 실패: $($it.FullName) owner=$o 쓰기권한=$($w.Count)"; exit 13 }
|
||||
}
|
||||
Say "확인 완료: $($items.Count)개"
|
||||
exit 0
|
||||
}
|
||||
throw "알 수 없는 Mode: $Mode"
|
||||
@@ -1,7 +1,9 @@
|
||||
# 마이크 APO 등록 · 해제 (관리자 권한). 설치 프로그램과 앱의 "마이크 다시 연결" 버튼이 실행한다.
|
||||
# mic-apo.ps1 -Install [-Root <설치 폴더>] 마이크마다 APO 를 붙이고 오디오 서비스를 다시 시작
|
||||
# mic-apo.ps1 -Uninstall [-Root <설치 폴더>] 원래 설정으로 되돌림
|
||||
# 바꾼 레지스트리 값의 원래 값은 <설치 폴더>\apo\mic-apo-backup.json 에 남겨 두고 해제할 때 되돌린다.
|
||||
# mic-apo.ps1 -Install [-Root <폴더>] 마이크마다 APO 를 붙이고 오디오 서비스를 다시 시작
|
||||
# mic-apo.ps1 -Uninstall [-Root <폴더>] 원래 설정으로 되돌림
|
||||
# <폴더> 는 apo\ 가 있는 곳이다. 설치 프로그램은 Program Files\VoiceChanger, zip 으로 풀어 쓰면 그 폴더.
|
||||
# 바꾼 레지스트리 값의 원래 값은 <폴더>\apo\mic-apo-backup.json 에 남겨 두고 해제할 때 되돌린다.
|
||||
# (v1.0.1 까지 고른 폴더의 apo\ 에 있던 백업은 설치 프로그램의 legacy.ps1 이 이 자리로 옮긴다)
|
||||
# apo\ 는 관리자만 쓸 수 있는 폴더다 (일반 사용자가 백업을 바꿔 관리자 권한으로 레지스트리를 쓰게 만들 수 없게).
|
||||
param([switch]$Install, [switch]$Uninstall, [string]$Root)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
27
voice-changer/tests/test_admin_root.py
Normal file
27
voice-changer/tests/test_admin_root.py
Normal 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()
|
||||
95
voice-changer/tests/test_record_servers.py
Normal file
95
voice-changer/tests/test_record_servers.py
Normal 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()
|
||||
Reference in New Issue
Block a user