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
12 changes: 6 additions & 6 deletions frontend/src/app/composition/createAppServices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import type {
ReminderApplicationDependencies,
ReminderApplicationPort,
} from '../../features/reminder/application/interfaces';
import { LocalReminderApplication } from '../../features/reminder/application';
import {
MockLocalScheduleReader,
MockReminderApplication,
MockReminderDispositionSync,
MockReminderStateStore,
} from '../../features/reminder/data/local';
import { MockAudioPlayback } from '../../infrastructure/audio';
import { ExpoAudioPlayback } from '../../infrastructure/audio';
import { MockLocationMonitor } from '../../infrastructure/location';
import {
MockPopup,
Expand All @@ -21,7 +21,7 @@ import {
NativeAlarmScheduler,
NativeDeviceCapability,
} from '../../infrastructure/notifications';
import { MockTimeListener } from '../../infrastructure/time';
import { IntervalTimeListener } from '../../infrastructure/time';
import { MockReminderPresenter } from '../../features/reminder/presentation';
import { ScheduleViewStore } from '../../features/schedule/presentation';

Expand All @@ -44,11 +44,11 @@ export function createAppServices(options: CreateAppServicesOptions = {}): AppSe
const auth = createAuthRuntime(options.auth);
const reminderPorts: ReminderApplicationDependencies = {
schedules: new MockLocalScheduleReader(),
time: new MockTimeListener(),
time: new IntervalTimeListener(),
location: new MockLocationMonitor(),
alarms: new NativeAlarmScheduler(),
delivery: new MockReminderDelivery(),
audio: new MockAudioPlayback(),
audio: new ExpoAudioPlayback(),
device: new NativeDeviceCapability(),
presenter: new MockReminderPresenter(),
systemNotification: new MockSystemNotification(),
Expand All @@ -58,7 +58,7 @@ export function createAppServices(options: CreateAppServicesOptions = {}): AppSe
state: new MockReminderStateStore(),
dispositionSync: new MockReminderDispositionSync(),
};
const reminder = new MockReminderApplication(reminderPorts);
const reminder = new LocalReminderApplication(reminderPorts);
const scheduleView = new ScheduleViewStore();
const runtime = new AppRuntime([
{
Expand Down
161 changes: 161 additions & 0 deletions frontend/src/infrastructure/audio/ExpoAudioPlayback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
import type {
AudioPlaybackPort,
AudioPlaybackReceipt,
AudioPlaybackRequest,
} from '../../features/reminder/application/interfaces';
import { buildAudioDataUri } from './audioDataUri';

// Metro 资源 id;高强度本地兜底铃声(与原生 AlarmSoundService 同源)。
const LOCAL_ALARM_SOUND = require('../../../assets/sounds/alarm_prompt.mp3') as number;

type AudioPlayerLike = {
pause: () => void;
replace: (source: string | number) => void;
play: () => void;
volume: number;
loop: boolean;
};

type ExpoAudioModule = {
createAudioPlayer: (source?: string | number | null) => AudioPlayerLike;
setAudioModeAsync: (mode: Record<string, unknown>) => Promise<void>;
};

/**
* 音频播放适配器:
* - TTS 有字节时播放并循环,直到 stop
* - 否则播放打包的 alarm_prompt.mp3(高强度本地兜底)
*/
export class ExpoAudioPlayback implements AudioPlaybackPort {
private player: AudioPlayerLike | null = null;
private activeScheduleId: string | null = null;
private modeReady: Promise<void> | null = null;

/** 默认走真实的动态 import;测试注入一个假实现,绕开 expo-audio 这个原生模块。 */
constructor(
private readonly loadExpoAudioModule: () => Promise<ExpoAudioModule | null> = loadExpoAudio,
) {}

async isTtsAvailable(): Promise<boolean> {
// TTS 字节管线尚未接入;有 data 时由 playTts 直接播放。
return false;
}

async playTts(request: AudioPlaybackRequest): Promise<AudioPlaybackReceipt> {
if (request.data == null || request.data.byteLength === 0) {
return {
playback_id: `tts-empty-${request.schedule_id}`,
played: false,
used_local_fallback: false,
};
}
const played = await this.playBytes(request.schedule_id, request.data, request.format ?? 'wav');
return {
playback_id: `tts-${request.schedule_id}`,
played,
used_local_fallback: false,
};
}

async playLocalFallback(request: AudioPlaybackRequest): Promise<AudioPlaybackReceipt> {
if (request.data != null && request.data.byteLength > 0) {
const played = await this.playBytes(
request.schedule_id,
request.data,
request.format ?? 'wav',
);
return {
playback_id: `local-${request.schedule_id}`,
played,
used_local_fallback: true,
};
}

const played = await this.playBundledAlarm(request.schedule_id);
return {
playback_id: `local-bundled-${request.schedule_id}`,
played,
used_local_fallback: true,
};
}

async stop(scheduleId: string): Promise<void> {
if (this.activeScheduleId !== scheduleId) return;
if (this.player != null) {
this.player.loop = false;
this.player.pause();
}
this.activeScheduleId = null;
}

private async playBytes(scheduleId: string, data: Uint8Array, format: string): Promise<boolean> {
const expoAudio = await this.loadExpoAudioModule();
if (expoAudio == null) return false;
if (!(await this.ensureAudioMode(expoAudio))) return false;

const player = this.ensurePlayer(expoAudio);
player.pause();
player.replace(buildAudioDataUri(data, format));
player.loop = true;
player.volume = 1;
this.activeScheduleId = scheduleId;
player.play();
return true;
}

private async playBundledAlarm(scheduleId: string): Promise<boolean> {
const expoAudio = await this.loadExpoAudioModule();
if (expoAudio == null) return false;
if (!(await this.ensureAudioMode(expoAudio))) return false;

const player = this.ensurePlayer(expoAudio);
player.pause();
player.replace(LOCAL_ALARM_SOUND);
player.loop = true;
player.volume = 1;
this.activeScheduleId = scheduleId;
player.play();
return true;
}

private ensurePlayer(expoAudio: ExpoAudioModule): AudioPlayerLike {
if (this.player == null) {
this.player = expoAudio.createAudioPlayer(null);
}
return this.player;
}

/**
* 返回 false 时调用方必须放弃这次播放,不能假装播放成功——静音模式/后台播放
* 没配置成功,即使真的调用 play() 用户也大概率听不到。不永久缓存失败:清掉
* modeReady 让下一次响铃重新尝试,而不是这次失败后整个 App 生命周期都跳过。
*/
private async ensureAudioMode(expoAudio: ExpoAudioModule): Promise<boolean> {
if (this.modeReady == null) {
this.modeReady = expoAudio.setAudioModeAsync({
allowsRecording: false,
interruptionMode: 'doNotMix',
playsInSilentMode: true,
shouldPlayInBackground: true,
shouldRouteThroughEarpiece: false,
});
}
try {
await this.modeReady;
return true;
} catch {
this.modeReady = null;
return false;
}
}
}

async function loadExpoAudio(): Promise<ExpoAudioModule | null> {
try {
const mod = await import('expo-audio');
if (typeof mod.createAudioPlayer !== 'function') return null;
return mod as unknown as ExpoAudioModule;
} catch {
return null;
}
}
32 changes: 0 additions & 32 deletions frontend/src/infrastructure/audio/MockAudioPlayback.ts

This file was deleted.

39 changes: 39 additions & 0 deletions frontend/src/infrastructure/audio/audioDataUri.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

const MIME_BY_FORMAT: Record<string, string> = {
aac: 'audio/aac',
m4a: 'audio/mp4',
mp3: 'audio/mpeg',
mpeg: 'audio/mpeg',
oga: 'audio/ogg',
ogg: 'audio/ogg',
wav: 'audio/wav',
wave: 'audio/wav',
};

export function encodeBase64(bytes: Uint8Array): string {
let output = '';
for (let index = 0; index < bytes.length; index += 3) {
const first = bytes[index] ?? 0;
const hasSecond = index + 1 < bytes.length;
const hasThird = index + 2 < bytes.length;
const second = hasSecond ? bytes[index + 1]! : 0;
const third = hasThird ? bytes[index + 2]! : 0;
const value = (first << 16) | (second << 8) | third;

output += BASE64_ALPHABET[(value >>> 18) & 63];
output += BASE64_ALPHABET[(value >>> 12) & 63];
output += hasSecond ? BASE64_ALPHABET[(value >>> 6) & 63] : '=';
output += hasThird ? BASE64_ALPHABET[value & 63] : '=';
}
return output;
}

export function buildAudioDataUri(bytes: Uint8Array, audioFormat: string): string {
const normalizedFormat = audioFormat.trim().toLowerCase().replace(/^\./, '');
if (!/^[a-z0-9][a-z0-9.+-]{0,31}$/.test(normalizedFormat)) {
throw new Error('Unsupported reminder audio format');
}
const mime = MIME_BY_FORMAT[normalizedFormat] ?? `audio/${normalizedFormat}`;
return `data:${mime};base64,${encodeBase64(bytes)}`;
}
3 changes: 2 additions & 1 deletion frontend/src/infrastructure/audio/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { MockAudioPlayback } from './MockAudioPlayback';
export { ExpoAudioPlayback } from './ExpoAudioPlayback';
export { buildAudioDataUri, encodeBase64 } from './audioDataUri';
38 changes: 38 additions & 0 deletions frontend/src/infrastructure/time/IntervalTimeListener.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type {
LocalTimeTick,
TimeListenerHandle,
TimeListenerOptions,
TimeListenerPort,
} from '../../features/reminder/application/interfaces';

const DEFAULT_INTERVAL_MS = 30_000;

/** 进程内周期时间观测,驱动 handleTime。 */
export class IntervalTimeListener implements TimeListenerPort {
Comment thread
LUPENGHAN marked this conversation as resolved.
private readonly timers = new Map<string, ReturnType<typeof setInterval>>();
private sequence = 0;

constructor(private readonly intervalMs: number = DEFAULT_INTERVAL_MS) {}

async start(
listener: (tick: LocalTimeTick) => void,
_options?: TimeListenerOptions,
): Promise<TimeListenerHandle> {
const listenerId = `interval-time-listener-${++this.sequence}`;
const emit = () => {
listener({ observed_at: new Date().toISOString() });
};
// 不在 start 同步打首 tick,交给调用方完成 rebuild 后再自然周期触发。
const timer = setInterval(emit, this.intervalMs);
this.timers.set(listenerId, timer);
return { listener_id: listenerId };
}

async stop(listenerId: string): Promise<void> {
const timer = this.timers.get(listenerId);
if (timer != null) {
clearInterval(timer);
this.timers.delete(listenerId);
}
}
}
1 change: 1 addition & 0 deletions frontend/src/infrastructure/time/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { MockTimeListener } from './MockTimeListener';
export { IntervalTimeListener } from './IntervalTimeListener';
16 changes: 16 additions & 0 deletions frontend/src/types/expo-audio.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
declare module 'expo-audio' {
export function createAudioPlayer(source?: string | number | null): {
pause: () => void;
replace: (source: string | number) => void;
play: () => void;
volume: number;
loop: boolean;
};

export function setAudioModeAsync(mode: Record<string, unknown>): Promise<void>;
}

declare module '*.mp3' {
const asset: number;
export default asset;
}
5 changes: 5 additions & 0 deletions frontend/tests/unit/app/createAppServices.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ describe('createAppServices', () => {
},
});
const stopReminder = jest.spyOn(services.reminder, 'stop');
const startTimeListener = jest.spyOn(services.reminderPorts.time, 'start');
services.scheduleView.replace(
{ accountId: 'acc_001', selectedDate: '2026-08-12', timezone: 'Asia/Shanghai' },
[],
Expand All @@ -29,6 +30,10 @@ describe('createAppServices', () => {
timezone: null,
});
expect(stopReminder).toHaveBeenCalledTimes(1);
// reminder 是真的 LocalReminderApplication,不是 Mock:start() 应该真的调用
// 到 reminderPorts.time.start(),证明组合根接的是会消费这些端口的引擎,
// 不是一个 start()/handleTime() 全是空操作的桩。
expect(startTimeListener).toHaveBeenCalledTimes(1);
});
});

Expand Down
Loading
Loading