refactor: isolate playback and upload use cases
ci / module boundaries / boundaries (push) Successful in 6s
ci / api / api (push) Successful in 47s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m2s
ci / db / db (push) Successful in 1m4s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 1m30s
ci / ts / ts (packages + web) (push) Successful in 2m54s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m14s
ci / module boundaries / boundaries (push) Successful in 6s
ci / api / api (push) Successful in 47s
ci / contract / contract (сгенерированный код совпадает с openapi.yaml) (push) Successful in 1m2s
ci / db / db (push) Successful in 1m4s
ci / docker / docker (образы собираются — их сервер собирает сам при обновлении) (push) Successful in 1m30s
ci / ts / ts (packages + web) (push) Successful in 2m54s
ci / mobile / mobile (Metro-бандл Android) (push) Successful in 1m14s
This commit is contained in:
1 parent
c84f90e2cc
commit
e158558da3
56 files changed
+3337
-2196
No files matched your search
@@ -0,0 +1,7 @@
|
||||
# Android
|
||||
|
||||
- `src/player/controller.ts` — фасад и зеркало native-очереди; `service.ts` — фоновые события. Владельцем воспроизводимой очереди остаётся TrackPlayer.
|
||||
- Общая политика волны — `packages/core/src`; офлайн-адаптация — `src/player/offlineWave.ts`, `src/offline`.
|
||||
- Сессия/настройки — `src/lib`; маршруты — `src/app`. Сохраняй работу при выгруженном UI и изоляцию офлайн-данных по пользователю/серверу.
|
||||
- `pnpm --filter @pipu/mobile typecheck`, `pnpm --filter @pipu/mobile test`.
|
||||
- Изменения native playback требуют проверки на устройстве: background, смена трека, offline→online. Unit-тесты не заменяют эту проверку.
|
||||
@@ -1,6 +1,11 @@
|
||||
import NetInfo from '@react-native-community/netinfo';
|
||||
import {
|
||||
EventBuffer,
|
||||
WaveCoordinator,
|
||||
EARLY_SKIP_MS,
|
||||
type WaveInfo,
|
||||
type WaveOutcome,
|
||||
type WaveFeedback,
|
||||
PlayAttempt,
|
||||
normalizeGain,
|
||||
unwrap,
|
||||
@@ -24,12 +29,7 @@ import { eventId } from './eventId';
|
||||
|
||||
export { offlineWave };
|
||||
|
||||
export interface WaveInfo {
|
||||
sessionId: string;
|
||||
activity: string | null;
|
||||
mood: string | null;
|
||||
fallback: boolean;
|
||||
}
|
||||
export type { WaveInfo } from '@pipu/core';
|
||||
|
||||
export interface PlayerState {
|
||||
ready: boolean;
|
||||
@@ -44,10 +44,6 @@ export interface PlayerState {
|
||||
wave: WaveInfo | null;
|
||||
}
|
||||
|
||||
type WaveOutcome = 'complete' | 'skip' | 'skip_early' | 'like' | 'dislike';
|
||||
|
||||
const WAVE_REFILL_AT = 2;
|
||||
const EARLY_SKIP_MS = 30_000;
|
||||
const SAVE_EVERY_MS = 10_000;
|
||||
|
||||
const playable = (t: Track) => t.available && (!!t.stream_url || downloads.isDownloaded(t.id));
|
||||
@@ -84,8 +80,13 @@ class Controller {
|
||||
private attempt: PlayAttempt | null = null;
|
||||
private lastPositionMs = 0;
|
||||
private lastSave = 0;
|
||||
private waveFeedback: { track_id: string; outcome: WaveOutcome }[] = [];
|
||||
private waveLoading = false;
|
||||
private readonly wavePolicy = new WaveCoordinator({
|
||||
next: async (id: string, feedback: WaveFeedback[]) => unwrap(
|
||||
await this.session!.client.POST('/api/v1/wave/sessions/{id}/next', {
|
||||
params: { path: { id } }, body: { feedback },
|
||||
}),
|
||||
),
|
||||
});
|
||||
private neutralSwitch = false; // следующая смена трека — из-за нового контекста волны
|
||||
private setupDone: Promise<void> | null = null;
|
||||
private listeners = new Set<() => void>();
|
||||
@@ -308,18 +309,22 @@ class Controller {
|
||||
if (!this.session) return;
|
||||
await this.setup();
|
||||
this.leaveWave();
|
||||
const version = this.wavePolicy.version;
|
||||
let res;
|
||||
try {
|
||||
res = unwrap(await this.session.client.POST('/api/v1/wave/sessions', { body: { activity, mood } }));
|
||||
} catch (e) {
|
||||
if (!this.wavePolicy.isCurrent(version)) return;
|
||||
// Нет связи с сервером — офлайн-волна из скачанного.
|
||||
const local = offlineWave(downloads.downloaded());
|
||||
if (!local.length) throw e;
|
||||
return this.playList(local, 0, { type: 'collection', id: 'downloads' });
|
||||
}
|
||||
if (!this.wavePolicy.isCurrent(version)) return;
|
||||
const tracks = res.tracks.filter(playable);
|
||||
if (!tracks.length) return;
|
||||
this.finishAttempt(this.lastPositionMs / 1000);
|
||||
this.wavePolicy.activate(res.session_id);
|
||||
this.update({
|
||||
queue: tracks, index: 0, track: tracks[0] ?? null, context: { type: 'wave', id: res.session_id },
|
||||
wave: { sessionId: res.session_id, activity: res.activity, mood: res.mood, fallback: res.fallback },
|
||||
@@ -332,13 +337,16 @@ class Controller {
|
||||
async setWaveContext(activity: string | null, mood: string | null) {
|
||||
const wave = this.state.wave;
|
||||
if (!wave || !this.session) return this.startWave(activity, mood);
|
||||
const version = this.wavePolicy.changeContext(wave.sessionId);
|
||||
const res = unwrap(
|
||||
await this.session.client.PATCH('/api/v1/wave/sessions/{id}', {
|
||||
params: { path: { id: wave.sessionId } },
|
||||
body: { activity, mood },
|
||||
}),
|
||||
);
|
||||
await this.replaceUpcoming(res.tracks);
|
||||
if (!this.wavePolicy.isCurrent(version)) return;
|
||||
await this.replaceUpcoming(res.tracks, () => this.wavePolicy.isCurrent(version));
|
||||
if (!this.wavePolicy.isCurrent(version)) return;
|
||||
this.update({ wave: { ...wave, activity: res.activity, mood: res.mood, fallback: res.fallback } });
|
||||
// Новый контекст звучит сразу; прерванный трек — не скип для волны (как в вебе).
|
||||
if (res.tracks.some(playable)) {
|
||||
@@ -351,8 +359,8 @@ class Controller {
|
||||
|
||||
private leaveWave() {
|
||||
const wave = this.state.wave;
|
||||
this.wavePolicy.activate(null);
|
||||
if (!wave) return;
|
||||
this.waveFeedback = [];
|
||||
this.update({ wave: null });
|
||||
void this.session?.client
|
||||
.DELETE('/api/v1/wave/sessions/{id}', { params: { path: { id: wave.sessionId } } })
|
||||
@@ -360,46 +368,36 @@ class Controller {
|
||||
}
|
||||
|
||||
private noteWave(trackId: string, outcome: WaveOutcome) {
|
||||
if (this.state.wave) this.waveFeedback.push({ track_id: trackId, outcome });
|
||||
this.wavePolicy.note(trackId, outcome);
|
||||
}
|
||||
|
||||
/** Убрать не начатые треки и поставить новые (после реакции или смены контекста). */
|
||||
private async replaceUpcoming(tracks: Track[]) {
|
||||
private async replaceUpcoming(tracks: Track[], current: () => boolean = () => true) {
|
||||
const keep = this.state.queue.slice(0, this.state.index + 1);
|
||||
await TrackPlayer.removeUpcomingTracks();
|
||||
const add = tracks.filter(playable);
|
||||
await TrackPlayer.add(await this.toRntp(add));
|
||||
this.update({ queue: [...keep, ...add] });
|
||||
const native = await this.toRntp(add);
|
||||
if (!current()) return;
|
||||
await TrackPlayer.removeUpcomingTracks();
|
||||
if (!current()) return;
|
||||
await TrackPlayer.add(native);
|
||||
if (current()) this.update({ queue: [...keep, ...add] });
|
||||
}
|
||||
|
||||
private async refillWave(refresh = false) {
|
||||
const wave = this.state.wave;
|
||||
if (!wave || !this.session || this.waveLoading) return;
|
||||
if (!this.session) return;
|
||||
const remaining = this.state.queue.length - this.state.index - 1;
|
||||
if (!refresh && remaining > WAVE_REFILL_AT) return;
|
||||
this.waveLoading = true;
|
||||
const feedback = this.waveFeedback;
|
||||
this.waveFeedback = [];
|
||||
try {
|
||||
const res = unwrap(
|
||||
await this.session.client.POST('/api/v1/wave/sessions/{id}/next', {
|
||||
params: { path: { id: wave.sessionId } },
|
||||
body: { feedback },
|
||||
}),
|
||||
);
|
||||
if (this.state.wave?.sessionId !== wave.sessionId) return;
|
||||
if (refresh) await this.replaceUpcoming(res.tracks);
|
||||
await this.wavePolicy.refill(remaining, refresh, async (res, current) => {
|
||||
if (refresh) await this.replaceUpcoming(res.tracks, current);
|
||||
else {
|
||||
const add = res.tracks.filter(playable);
|
||||
await TrackPlayer.add(await this.toRntp(add));
|
||||
const native = await this.toRntp(add);
|
||||
if (!current()) return;
|
||||
await TrackPlayer.add(native);
|
||||
if (!current()) return;
|
||||
this.update({ queue: [...this.state.queue, ...add] });
|
||||
}
|
||||
this.update({ wave: { ...wave, fallback: res.fallback } });
|
||||
} catch {
|
||||
this.waveFeedback = [...feedback, ...this.waveFeedback];
|
||||
} finally {
|
||||
this.waveLoading = false;
|
||||
}
|
||||
if (current()) this.update({ wave: { ...this.state.wave!, fallback: res.fallback } });
|
||||
});
|
||||
}
|
||||
|
||||
// --- состояние ---
|
||||
@@ -443,6 +441,7 @@ class Controller {
|
||||
}
|
||||
|
||||
async reset() {
|
||||
this.wavePolicy.activate(null);
|
||||
this.attempt = null;
|
||||
this.update({ queue: [], track: null, index: 0, playing: false, positionMs: 0, wave: null, context: null });
|
||||
if (this.setupDone) await TrackPlayer.reset().catch(() => undefined);
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { AuthSession, Track } from '@pipu/core';
|
||||
import { beforeEach, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('@react-native-community/netinfo', () => ({ default: {
|
||||
fetch: async () => ({ type: 'wifi' }), addEventListener: () => () => {},
|
||||
} }));
|
||||
vi.mock('../src/lib/prefs', () => ({
|
||||
qualityPrefs: { load: async () => ({ wifi: 'high', cellular: 'medium' }) },
|
||||
playerCache: { clearIfRequested: async () => {} },
|
||||
}));
|
||||
vi.mock('../src/offline/events', () => ({ PersistentEvents: class {} }));
|
||||
vi.mock('../src/offline/downloads', () => ({
|
||||
downloads: { isDownloaded: () => false, localTrack: () => undefined, localCover: () => undefined, downloaded: () => [] },
|
||||
sizedCover: (s: string) => s,
|
||||
}));
|
||||
vi.mock('react-native-track-player', () => ({
|
||||
default: {
|
||||
isServiceRunning: async () => true, setupPlayer: async () => {}, updateOptions: async () => {},
|
||||
addEventListener: vi.fn(), reset: vi.fn().mockResolvedValue(undefined),
|
||||
add: vi.fn().mockResolvedValue(undefined), play: vi.fn().mockResolvedValue(undefined),
|
||||
skip: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
AppKilledPlaybackBehavior: {}, Capability: {}, Event: {}, State: {},
|
||||
}));
|
||||
|
||||
function track(id: string): Track {
|
||||
return { id, title: id, duration_ms: 1000, artists: [],
|
||||
album: { id: 'album', title: 'Album', year: null, cover_url: null, cover_colors: [] },
|
||||
genres: [], disc_no: 1, track_no: 1, available: true, stream_url: `/s/${id}?sig=x`, reaction: null, features: null };
|
||||
}
|
||||
function deferred<T>() {
|
||||
let resolve!: (v: T) => void;
|
||||
const promise = new Promise<T>((yes) => { resolve = yes; });
|
||||
return { promise, resolve };
|
||||
}
|
||||
const reply = (id: string) => ({ data: { session_id: id, activity: null, mood: null, fallback: false, tracks: [track(id)] }, response: new Response() });
|
||||
|
||||
beforeEach(() => { vi.resetModules(); vi.clearAllMocks(); });
|
||||
|
||||
it('ignores a wave creation response after the player is reset', async () => {
|
||||
const { player } = await import('../src/player/controller');
|
||||
const native = (await import('react-native-track-player')).default;
|
||||
const pending = deferred<ReturnType<typeof reply>>();
|
||||
const post = vi.fn().mockReturnValue(pending.promise);
|
||||
player.attach({ client: { POST: post } } as unknown as AuthSession, 'http://localhost', null);
|
||||
const start = player.startWave(null, null);
|
||||
await vi.waitFor(() => expect(post).toHaveBeenCalled());
|
||||
await player.reset();
|
||||
pending.resolve(reply('old'));
|
||||
await start;
|
||||
expect(player.getState().wave).toBeNull();
|
||||
expect(player.getState().queue).toEqual([]);
|
||||
expect(native.add).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not let a late context response replace a manually selected playlist', async () => {
|
||||
const { player } = await import('../src/player/controller');
|
||||
const pending = deferred<ReturnType<typeof reply>>();
|
||||
const session = { client: {
|
||||
POST: vi.fn().mockResolvedValue(reply('wave')),
|
||||
PATCH: vi.fn().mockReturnValue(pending.promise), DELETE: vi.fn().mockResolvedValue({}),
|
||||
} };
|
||||
player.attach(session as unknown as AuthSession, 'http://localhost', null);
|
||||
await player.startWave(null, null);
|
||||
const change = player.setWaveContext('focus', null);
|
||||
await player.playList([track('manual')], 0, { type: 'album', id: 'album' });
|
||||
pending.resolve(reply('stale'));
|
||||
await change;
|
||||
expect(player.getState().wave).toBeNull();
|
||||
expect(player.getState().queue.map((t) => t.id)).toEqual(['manual']);
|
||||
expect(player.getState().context?.type).toBe('album');
|
||||
});
|
||||
Reference in new issue
Block a user