Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ export function App() {
const scope = useScope(backend);
const jobs = useJobs(usable, scope);
// the account setup (#216): it opens by itself when a tab finds the account not set up, and from the settings
const profiles = useProfiles(usable, scope);
const profiles = useProfiles(usable, scope, jobs.jobs);
const profile = profiles.profiles ? currentProfile(profiles.profiles) : undefined;
const [setupOpen, setSetupOpen] = useState(false);
useEffect(() => {
Expand Down
10 changes: 8 additions & 2 deletions web/src/api/jobs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,19 @@ export const jobFileUrl = (id: string) => mediaAddress('jobs/' + encodeURICompon
/** The address of the job's server-sent events; the token goes in the address, as `EventSource` sends no header. */
export const jobEventsUrl = (id: string) => apiUrl('jobs/' + encodeURIComponent(id) + '/events', { access_token: token() });

/** The words of a job's command line that are not flags, `weflow` left out: `export`, `messages`, then the values. */
const wordsOf = (command: readonly string[]) => command.slice(1).filter(word => !word.startsWith('-'));

/** The command a job runs, by its first two words: `export messages`, `key db`. */
export const commandName = (command: readonly string[]) => wordsOf(command).slice(0, 2).join(' ');

/**
* What a job does, in words: 「导出聊天记录」 for `export messages`, … With `names` (conversations by id), the
* conversation it names: 「导出聊天记录 · 林沐」.
*/
export function describeCommand(command: string[], names?: ReadonlyMap<string, string>): string {
const words = command.slice(1).filter(word => !word.startsWith('-'));
const name = words.slice(0, 2).join(' ');
const words = wordsOf(command);
const name = commandName(command);
const known = COMMANDS[name] ?? COMMANDS[words[0]];
const what = known ? t(known) : name;
const about = names && command.find(word => names.has(word));
Expand Down
8 changes: 8 additions & 0 deletions web/src/api/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// directory and its accounts, saving settings, and testing that the database opens. The keys are fetched by
// `key db --save` / `key image --save`, which store them on the server: they never reach the page.
import { call, get } from './client';
import { commandName, type Job } from './jobs';
import { t } from '../i18n';
import type * as Contract from './contract.gen';

Expand Down Expand Up @@ -38,6 +39,13 @@ export const testDatabase = (signal?: AbortSignal) => get<Partial<Contract.DbCon
/** `key image --save` (Windows, Linux and macOS): the image keys from WeChat's cache, saved on the server. */
export const saveImageKeys = () => call<Contract.ImageKeys>('POST', 'key/image', { save: true });

/** The key a job saves in the current profile: `db` for `key db --save`, `image` for `key image --save`, else null. */
export function savedKey(job: Pick<Job, 'command'>): 'db' | 'image' | null {
if (!job.command.includes('--save')) return null;
const name = commandName(job.command);
return name === 'key db' ? 'db' : name === 'key image' ? 'image' : null;
}

/** A database key as `config set decrypt_key` takes it: 64 hexadecimal digits. */
export const isDatabaseKey = (value: string) => /^[0-9a-fA-F]{64}$/.test(value.trim());

Expand Down
18 changes: 18 additions & 0 deletions web/src/mock/server.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { afterEach, describe, expect, it, vi } from '#test';
import type { Job, ProfileSummary } from '../api/contract.gen';
import type { Params, SampleAnswer } from '../api/client';
import { savedKey } from '../api/setup';
import { server } from './server';

// The sample server keeps what changes for as long as the page (here, the test run) is open, and other test files use
Expand Down Expand Up @@ -111,6 +112,23 @@ describe('the sample server (#896)', () => {
expect(ask<Job[]>('GET', 'jobs').filter(j => [first.id, second.id, key.id].includes(j.id)).map(j => j.status)).toEqual(['succeeded', 'cancelled']);
});

it('saves the database key once its job has succeeded, as a job the page knows by its command (#1138)', () => {
vi.useFakeTimers({ toFake: ['Date'], now: Date.now() + 7_200_000 });
const t0 = Date.now();
ask('PUT', 'config/set', { key: 'current_profile', value: 'keyed-by-job' });
const keyed = () => ask<ProfileSummary[]>('GET', 'api/config/profiles').find(p => p.current)!.decryptKey;
expect(keyed()).toBe(false);
const job = start('key/db', { save: true });
expect(savedKey(job)).toBe('db');
at(t0 + 1000);
expect(ask<Job>('GET', 'jobs/' + job.id).status).toBe('running');
expect(keyed()).toBe(false);
at(t0 + 10_000);
expect(ask<Job>('GET', 'jobs/' + job.id)).toMatchObject({ status: 'succeeded', result: { success: true, data: { saved: ['decrypt_key'] } } });
expect(keyed()).toBe(true);
ask('PUT', 'config/set', { key: 'current_profile', value: 'default' });
});

it('refuses the page\'s versions, which need a server', () => {
expect(server.answer('GET', 'web/list', {}, false)).toEqual({ refused: true });
});
Expand Down
79 changes: 74 additions & 5 deletions web/src/settings/SetupWizard.test.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from '#test';
import type { Profile } from '../api/setup';
import { currentProfile, type Profile } from '../api/setup';
import { useJobs } from '../jobs/useJobs';
import { SetupDialog } from './SetupDialog';
import { SetupWizard } from './SetupWizard';
import { useProfiles } from './useProfiles';

afterEach(() => {
cleanup();
Expand Down Expand Up @@ -99,8 +100,7 @@ describe('SetupWizard', () => {
'GET /jobs': () => ok(jobs),
'GET /jobs/k1': () => ok({ ...job('succeeded'), result: { success: true, data: { method: 'wx_key', saved: ['decrypt_key'] } } }),
});
const onChanged = vi.fn();
render(<Wizard profile={{ ...PROFILE, dbPath: 'D:/x', wxid: 'wxid_a' }} onChanged={onChanged} />);
render(<Wizard profile={{ ...PROFILE, dbPath: 'D:/x', wxid: 'wxid_a' }} />);
await act(async () => {});
fireEvent.click(screen.getByRole('button', { name: '获取数据库密钥' }));
await act(async () => {});
Expand All @@ -125,12 +125,12 @@ describe('SetupWizard', () => {
expect(streams()).toBe(2);
expect(doing()).toContain('请在微信的登录窗口点击「进入微信」');

// the job's end, as its stream tells it
// the job's end, as its stream tells it; the profile is read again by useProfiles, not by the step
jobs = [job('succeeded')];
const done = { ...job('succeeded'), result: { success: true, data: { method: 'wx_key', saved: ['decrypt_key'] } } };
await act(async () => { emit('result', done); });
expect(screen.getByRole('status').textContent).toContain('已获取数据库密钥');
expect(onChanged).toHaveBeenCalled();
expect(screen.getByRole('button', { name: '获取数据库密钥' })).toBeTruthy();
});

it('takes a typed key only when it is 64 hexadecimal digits', async () => {
Expand Down Expand Up @@ -187,6 +187,75 @@ describe('SetupDialog', () => {
return <SetupDialog open profile={profile} jobs={jobs} onChanged={() => {}} onClose={() => {}} onDone={() => {}} />;
}

/** The dialog as the workspace holds it: the jobs and the profiles outlive it. */
function Workspace({ open }: { open: boolean }) {
const jobs = useJobs(true, 0);
const profiles = useProfiles(true, 0, jobs.jobs);
const profile = profiles.profiles ? currentProfile(profiles.profiles) : undefined;
return <SetupDialog open={open} profile={profile} jobs={jobs} onChanged={profiles.reload} onClose={() => {}} onDone={() => {}} />;
}

/** A server whose `key db --save` job, `id`, runs until `finish` ends it; the key is in the profile from then on. */
function keyServer(id: string) {
const job = (status: string) => ({ id, status, command: ['weflow', '--json', '--progress', 'key', 'db', '--save'], createdAt: 1, startedAt: null, finishedAt: null, exitCode: null, httpStatus: null, progress: null });
let jobs: unknown[] = [];
let keyed = false;
const calls = serve({
'GET /api/config/profiles': () => ok([{ ...PROFILE, dbPath: 'D:/x', wxid: 'wxid_a', decryptKey: keyed }]),
'POST /key/db': () => { jobs = [job('running')]; return json({ success: true, data: job('running') }, 202); },
'GET /jobs': () => ok(jobs),
['GET /jobs/' + id]: () => ok({ ...job(keyed ? 'succeeded' : 'running'), result: keyed ? { success: true, data: { saved: ['decrypt_key'] } } : null }),
});
const finish = async () => {
keyed = true;
jobs = [job('succeeded')];
const done = { ...job('succeeded'), result: { success: true, data: { saved: ['decrypt_key'] } } };
await act(async () => { for (const source of opened.filter(s => s.url.startsWith('/jobs/' + id + '/events') && !s.closed)) source.emit('result', done); });
};
return { calls, finish, started: () => calls.filter(c => c.method === 'POST' && c.url.startsWith('/key/db')).length };
}

it('shows the database key job running after another step, and starts no second one (#1138)', async () => {
const { started } = keyServer('k2');
render(<Workspace open />);
await act(async () => {});
expect(currentStep()).toContain('数据库密钥');
fireEvent.click(screen.getByRole('button', { name: '获取数据库密钥' }));
await act(async () => {});
expect(document.querySelector('.setup-running')).not.toBeNull();

fireEvent.click(screen.getByRole('button', { name: '3图片密钥' }));
fireEvent.click(screen.getByRole('button', { name: '2数据库密钥' }));
await act(async () => {});
expect(currentStep()).toContain('数据库密钥');
expect(document.querySelector('.setup-running')?.textContent).toContain('正在准备');
expect(screen.getByRole('button', { name: '取消' })).toBeTruthy();
expect(screen.queryByRole('button', { name: '获取数据库密钥' })).toBeNull();
expect(started()).toBe(1);
});

it('reads the profile again when the job saved the key with the setup closed (#1138)', async () => {
const { calls, finish } = keyServer('k3');
const profileReads = () => calls.filter(c => c.url.startsWith('/api/config/profiles')).length;
const { rerender } = render(<Workspace open />);
await act(async () => {});
fireEvent.click(screen.getByRole('button', { name: '获取数据库密钥' }));
await act(async () => {});

rerender(<Workspace open={false} />);
await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); });
expect(document.querySelector('.setup-content')).toBeNull();
const before = profileReads();
await finish();
expect(profileReads()).toBe(before + 1);

rerender(<Workspace open />);
await act(async () => {});
fireEvent.click(screen.getByRole('button', { name: '已完成数据库密钥' }));
expect(document.querySelector('.setup-state')?.textContent).toBe('当前档案已有数据库密钥。');
expect((screen.getByRole('button', { name: '下一步' }) as HTMLButtonElement).disabled).toBe(false);
});

it('starts a profile added under a set-up one at the data directory (#898)', () => {
serve({});
const setUp: Profile = { ...PROFILE, wxid: 'wxid_a', dbPath: 'D:/xwechat_files', decryptKey: true };
Expand Down
39 changes: 25 additions & 14 deletions web/src/settings/SetupWizard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { ApiError, sampling } from '../api/client';
import { isFinished, jobEventsUrl } from '../api/jobs';
import { onPresence, present } from '../api/presence';
import {
detectDirs, findAccounts, isDatabaseKey, saveImageKeys, setConfig, testDatabase,
detectDirs, findAccounts, isDatabaseKey, saveImageKeys, savedKey, setConfig, testDatabase,
type Account, type Profile,
} from '../api/setup';
import { SteadyLabel } from '../Chip';
Expand Down Expand Up @@ -144,29 +144,40 @@ function phaseText(phase: KeyPhase | null): string {
}
}

/** Step 2: `key db --save` as a job, or a key typed in and saved with `config set decrypt_key`. */
/**
* Step 2: `key db --save` as a job, or a key typed in and saved with `config set decrypt_key`. The job is looked for
* in the shared list, as the step is left and the setup closed while it runs (#1138); `useProfiles` reads the
* profile again once it has saved the key.
*/
function KeyStep({ profile, jobs, onSaved, onNext }: { profile: Profile | undefined; jobs: JobsState; onSaved(): void; onNext(): void }) {
const [jobId, setJobId] = useState<string | null>(null);
const [typed, setTyped] = useState('');
const [note, setNote] = useState<{ text: string; error?: boolean } | null>(null);
const job = findJob(jobs, jobId);
const phase = useKeyPhase(job && !isFinished(job.status) ? job.id : null);
const running = Boolean(job && !isFinished(job.status));
const [starting, setStarting] = useState(false);
// the one that runs first, should another tab have queued one more
const job = jobs.jobs.filter(j => savedKey(j) === 'db' && !isFinished(j.status)).at(-1);
const running = Boolean(job);
const phase = useKeyPhase(job?.id ?? null);
// the job seen running, to say how it ended
const [watched, setWatched] = useState<string | null>(null);
useEffect(() => { if (job) setWatched(job.id); }, [job?.id]);
const ended = findJob(jobs, watched);

useEffect(() => {
if (!job || !isFinished(job.status)) return;
if (job.status === 'succeeded') { setNote({ text: t('已获取数据库密钥,保存在服务端的当前档案里。') }); onSaved(); }
else if (job.status === 'failed') setNote({ text: (job.result?.error?.message || t('获取密钥失败。')) + ' ' + t('可以重试,或者手动填写密钥。'), error: true });
if (!ended || !isFinished(ended.status)) return;
if (ended.status === 'succeeded') setNote({ text: t('已获取数据库密钥,保存在服务端的当前档案里。') });
else if (ended.status === 'failed') setNote({ text: (ended.result?.error?.message || t('获取密钥失败。')) + ' ' + t('可以重试,或者手动填写密钥。'), error: true });
else setNote({ text: t('已取消。') });
setJobId(null);
}, [job?.status]);
setWatched(id => (id === ended.id ? null : id));
}, [ended?.status]);

const start = async () => {
setNote(null);
try { setJobId((await runJob(t('获取数据库密钥'), 'POST', 'key/db', { save: true }, false)).id); }
setStarting(true);
try { setWatched((await runJob(t('获取数据库密钥'), 'POST', 'key/db', { save: true }, false)).id); }
catch (problem) { setNote({ text: reason(problem, t('没有开始,请重试。')), error: true }); }
finally { setStarting(false); }
};
const cancel = () => { if (jobId) removeJob(jobId).catch(() => setNote({ text: t('取消失败,请重试。'), error: true })); };
const cancel = () => { if (job) removeJob(job.id).catch(() => setNote({ text: t('取消失败,请重试。'), error: true })); };
const saveTyped = async (event: FormEvent) => {
event.preventDefault();
try {
Expand All @@ -188,7 +199,7 @@ function KeyStep({ profile, jobs, onSaved, onNext }: { profile: Profile | undefi
<button type="button" className="secondary-button" onClick={cancel}>{t('取消')}</button>
</div>
: <div className="setup-actions start">
<button type="button" className="primary-button" onClick={start}><Key size={16} />{profile?.decryptKey ? t('重新获取') : t('获取数据库密钥')}</button>
<button type="button" className="primary-button" disabled={starting} onClick={start}><Key size={16} />{profile?.decryptKey ? t('重新获取') : t('获取数据库密钥')}</button>
</div>}
{note && <Note error={note.error}>{note.text}</Note>}
<details className="setup-manual">
Expand Down
26 changes: 21 additions & 5 deletions web/src/settings/useProfiles.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// The profiles of `config profiles` (#216) while the server is there: read again for another server or account
// (`scope`), and when the setup saved a setting.
import { useCallback, useEffect, useState } from 'react';
import { getProfiles, type Profile } from '../api/setup';
// (`scope`), when the setup saved a setting, and when a job that saves a key has succeeded.
import { useCallback, useEffect, useRef, useState } from 'react';
import { isFinished, type Job } from '../api/jobs';
import { getProfiles, savedKey, type Profile } from '../api/setup';

/** The profiles as read, and what reads them again. */
export interface ProfilesState {
Expand All @@ -12,12 +13,27 @@ export interface ProfilesState {
reload(): void;
}

/** `config profiles` while `enabled`, read again for another `scope` and on `reload`. */
export function useProfiles(enabled: boolean, scope: number): ProfilesState {
/**
* `config profiles` while `enabled`, read again for another `scope`, on `reload`, and once one of `jobs` that saves a
* key (`key db --save`, `key image --save`) has succeeded.
*/
export function useProfiles(enabled: boolean, scope: number, jobs: readonly Job[]): ProfilesState {
const [profiles, setProfiles] = useState<Profile[] | null>(null);
const [failed, setFailed] = useState(false);
const [round, setRound] = useState(0);
const reload = useCallback(() => setRound(n => n + 1), []);
// here rather than in the setup, which is closed or on another step while the job runs (#1138); a job first seen
// ended changed nothing since the profiles were read
const saving = useRef(new Set<string>());
useEffect(() => {
let saved = false;
for (const job of jobs) {
if (!savedKey(job)) continue;
if (!isFinished(job.status)) saving.current.add(job.id);
else if (saving.current.delete(job.id) && job.status === 'succeeded') saved = true;
}
if (saved) reload();
}, [jobs, reload]);
useEffect(() => {
if (!enabled) { setProfiles(null); setFailed(false); return; }
const controller = new AbortController();
Expand Down
Loading