All files / app-play/src/app/routes replay.ts

91.45% Statements 107/117
88.88% Branches 56/63
94.11% Functions 16/17
91.07% Lines 102/112

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286                                                1x 1x                                                                                           14x 14x 14x 14x 14x 14x 14x 14x 14x 14x                   15x 4x 4x     11x 11x   1x   1x 1x 1x   10x 10x 2x 2x 2x 2x   8x 8x     8x   1x 1x 1x             2x 2x       2x 1x 1x     1x 2x                 5x 5x 4x   4x 4x   1x   4x 1x 1x 1x   3x 3x 1x 1x 2x   2x               4x                     4x 4x   1x   1x 1x 1x   3x         5x       12x 12x 12x     12x 5x 1x 1x 1x   2x   1x   4x   9x   4x 4x 4x 2x 2x   2x                           10x 10x 6x 12x 5x       5x 10x 5x 2x 1x     4x 4x 1x   3x 8x             2x 2x 1x 2x                          
// The replay route: a replay dropped or picked (`*.bmplay.json`), or kept in a replay slot, played back on the play
// screen of the gameplay family, whichever family recorded it, once the chart it was recorded on is found in the
// library; and a course replay (`*.bmcourse.json`, dropped or kept in a course's replay slot) played back as its course,
// once every stage's chart is.
 
import { computeChartFingerprint } from '@be-music/chart-model';
import { logger } from '@be-music/player-browser';
import { playerText } from '../../player-copy.ts';
import type { BrowserDroppedFile } from '@be-music/player-browser/collection';
import {
  COURSE_REPLAY_FILE_SUFFIX,
  REPLAY_FILE_SUFFIX,
  parseCourseReplay,
  parseReplay,
  type BeMusicCourseReplay,
  type BeMusicReplay,
} from '@be-music/player-engine/replay';
import type { LibraryChart, LibraryCourse, LibraryEntry } from '@be-music/player-scene-model';
import { courseFromReplay, describeCourseReplayStage, matchCourseReplayCharts } from '../../course-flow.ts';
import type { ReplayHistoryRecord } from '../../services/replay-slots.ts';
import type { ReplaySlotService } from '../../services/replay-slot-service.ts';
import type { LibraryService } from '../../services/library.ts';
import type { RecordsService } from '../../services/records.ts';
 
const dropLog = logger('drop');
const gamereplay = logger('gameplay');
 
export interface ReplayRouteDeps {
  /** The library the log's chart is looked for in. */
  readonly library: Pick<LibraryService, 'collection'>;
  /** The charts' SHA-256 and MD5, which a replay records. */
  readonly records: Pick<RecordsService, 'resolveChartSHA256' | 'resolveChartHashes'>;
  readonly setStatus: (text: string) => void;
  /** Shows a status about the play, which the select screen replaces when it comes back. */
  readonly setPlayStatus: (text: string) => void;
  /** Plays the chart back from the log (`PlayRoute.playChart`). */
  readonly playChart: (
    chartEntry: LibraryChart,
    overrides: { autoPlay: boolean; replay: BeMusicReplay },
  ) => Promise<void>;
  readonly showSelect: () => Promise<void>;
  /** The replay slots a replay is played from. */
  readonly replaySlots: Pick<ReplaySlotService, 'store' | 'targetOf'>;
  /** Plays an EXPERT / GRADE course replay back (`CourseRoute.startCourseReplay`). */
  readonly startCourseReplay: (course: LibraryCourse, courseLog: BeMusicCourseReplay) => Promise<void>;
  /** Plays a NONSTOP course replay back (`NonstopRoute.startNonstopCourse`). */
  readonly startNonstopCourse: (
    course: LibraryCourse,
    options: { decide?: boolean; replay?: BeMusicCourseReplay },
  ) => Promise<void>;
  /**
   * Tells the player which charts a replay needs that are not loaded (a replay's chart, a course replay's stage charts),
   * under `hint`; the replay does not start.
   */
  readonly showMissingReplayCharts: (hint: string, charts: readonly string[]) => void;
}
 
/** A replay played back from a file. */
export class ReplayRoute {
  private readonly library: ReplayRouteDeps['library'];
  private readonly records: ReplayRouteDeps['records'];
  private readonly setStatus: ReplayRouteDeps['setStatus'];
  private readonly setPlayStatus: ReplayRouteDeps['setPlayStatus'];
  private readonly playChart: ReplayRouteDeps['playChart'];
  private readonly showSelect: ReplayRouteDeps['showSelect'];
  private readonly replaySlots: ReplayRouteDeps['replaySlots'];
  private readonly startCourseReplay: ReplayRouteDeps['startCourseReplay'];
  private readonly startNonstopCourse: ReplayRouteDeps['startNonstopCourse'];
  private readonly showMissingReplayCharts: ReplayRouteDeps['showMissingReplayCharts'];
 
  public constructor(deps: ReplayRouteDeps) {
    this.replaySlots = deps.replaySlots;
    this.library = deps.library;
    this.records = deps.records;
    this.setStatus = deps.setStatus;
    this.setPlayStatus = deps.setPlayStatus;
    this.playChart = deps.playChart;
    this.showSelect = deps.showSelect;
    this.startCourseReplay = deps.startCourseReplay;
    this.startNonstopCourse = deps.startNonstopCourse;
    this.showMissingReplayCharts = deps.showMissingReplayCharts;
  }
 
  /**
   * Parses a dropped replay file and starts replay playback when the matching song is loaded. Matching prefers
   * the exact `chartPath` the log recorded (`play.native.chartPath`); older logs without it fall back to a
   * title + artist match. When no match (or the chart's `#RANDOM` roll differs so the resolved notes can't be
   * re-aligned), the failure lands in the status row instead of throwing — a bad drop must never wedge the UI.
   */
  public async startReplayReplayFromFile(file: Pick<BrowserDroppedFile, 'name' | 'text'>): Promise<void> {
    if (file.name.toLowerCase().endsWith(COURSE_REPLAY_FILE_SUFFIX)) {
      await this.startCourseReplayFromFile(file);
      return;
    }
    let replay: BeMusicReplay;
    try {
      replay = parseReplay(await file.text());
    } catch (error) {
      dropLog.warn('replay parse failed', error);
      // The drop took the select screen off the stage: it comes back, with the status.
      await this.showSelect();
      this.setStatus(playerText().replay.invalid((error as Error).message));
      return;
    }
    const chartEntry = await this.findSongForReplay(replay);
    if (!chartEntry) {
      await this.showSelect();
      this.setStatus(playerText().replay.notLoaded(replay.chart.title ?? playerText().replay.untitled));
      this.showMissingReplayCharts(playerText().replay.loadChart, [describeReplayChart(replay)]);
      return;
    }
    this.setPlayStatus(playerText().replay.replaying(chartEntry.title));
    try {
      // A replay plays on the gameplay family's own play screen, whichever family recorded it: the play session
      // re-applies the recorded arrangement and the engine replays the inputs the same way on every family.
      await this.playChart(chartEntry, { autoPlay: replay.play.mode === 'auto', replay: replay });
    } catch (error) {
      gamereplay.warn('replay replay failed', error);
      this.setStatus(playerText().replay.failed((error as Error).message));
      await this.showSelect();
    }
  }
 
  /** Opens a history entry through the same chart matching and playback as a dropped replay. */
  public async startReplayFromHistory(record: ReplayHistoryRecord): Promise<void> {
    let text: string | undefined;
    try {
      text = await this.replaySlots.store.readHistoryText(record.key);
    } catch (error) {
      gamereplay.warn('replay history read failed', error);
    }
    if (text === undefined) {
      this.setStatus(playerText().replay.historyUnreadable);
      return;
    }
 
    const suffix = record.target.kind === 'course' ? COURSE_REPLAY_FILE_SUFFIX : REPLAY_FILE_SUFFIX;
    await this.startReplayReplayFromFile({ name: `history${suffix}`, text: async () => text });
  }
 
  /**
   * Plays the replay kept in `slot` of a chart or course bar (the select screen's REPLAY), as a dropped one plays:
   * no record is kept and nothing is ranked. Returns whether a play starts, so the select screen plays the decide sound
   * only then; a slot that cannot be read says why on the status line.
   */
  public startReplayFromSlot(entry: Exclude<LibraryEntry, { kind: 'folder' }>, slot: number): boolean {
    const target = this.replaySlots.targetOf(entry);
    if (target === undefined || this.replaySlots.store.exists(target)[slot] !== true) return false;
    void (async () => {
      let payload;
      try {
        payload = await this.replaySlots.store.read(target, slot);
      } catch (error) {
        gamereplay.warn('replay slot read failed', error);
      }
      if (payload === undefined) {
        this.setStatus(playerText().replay.slotUnreadable(slot + 1));
        await this.showSelect();
        return;
      }
      try {
        if (payload.kind === 'chart' && entry.kind === 'chart') {
          this.setPlayStatus(playerText().replay.replayingSlot(slot + 1, entry.chart.title));
          await this.playChart(entry.chart, { autoPlay: payload.replay.play.mode === 'auto', replay: payload.replay });
        } else Eif (payload.kind === 'course' && entry.kind === 'course') {
          // As a dropped course replay plays: every stage's chart found, a NONSTOP course stitched again.
          await this.startCourseReplayFromLog(payload.replay);
        }
      } catch (error) {
        gamereplay.warn('replay slot replay failed', error);
        this.setStatus(playerText().replay.failed((error as Error).message));
        await this.showSelect();
      }
    })();
    return true;
  }
 
  /**
   * Parses a dropped course replay and plays it back as its course, as LR2 and beatoraja replay a course: only when every
   * stage's chart is loaded (matched by the hashes the log records), else the missing charts are listed and nothing
   * starts. The log's source does not matter here: a course replay from elsewhere (the Leaderboard) plays the same way
   * through {@link startCourseReplayFromLog}.
   */
  public async startCourseReplayFromFile(file: Pick<BrowserDroppedFile, 'text'>): Promise<void> {
    let courseLog: BeMusicCourseReplay;
    try {
      courseLog = parseCourseReplay(await file.text());
    } catch (error) {
      dropLog.warn('course replay parse failed', error);
      // The drop took the select screen off the stage: it comes back, with the status.
      await this.showSelect();
      this.setStatus(playerText().replay.invalidCourse((error as Error).message));
      return;
    }
    await this.startCourseReplayFromLog(courseLog);
  }
 
  /** Plays a parsed course replay back as its course, once every stage's chart is found in the library. */
  public async startCourseReplayFromLog(courseLog: BeMusicCourseReplay): Promise<void> {
    const matched = await matchCourseReplayCharts(
      courseLog,
      this.library.collection.charts,
      async (chartEntry, needFingerprint) => {
        const hashes = await this.records.resolveChartHashes(chartEntry);
        const chartFingerprint = needFingerprint ? fingerprintOf(chartEntry) : undefined;
        return { ...hashes, ...(chartFingerprint !== undefined ? { chartFingerprint } : {}) };
      },
    );
    const missing = matched.filter((stage) => stage.chart === undefined);
    if (missing.length > 0) {
      await this.showSelect();
      this.setStatus(playerText().replay.stagesMissing(missing.length, matched.length));
      this.showMissingReplayCharts(
        playerText().replay.loadStages(courseLog.course.name),
        missing.map(({ stage }) => describeCourseReplayStage(stage)),
      );
      return;
    }
    const course = courseFromReplay(
      courseLog,
      matched.map((stage) => stage.chart),
    );
    this.setPlayStatus(`Replaying course: ${course.definition.name}`);
    try {
      if (course.definition.kind === 'nonstop') {
        await this.startNonstopCourse(course, { decide: true, replay: courseLog });
        return;
      }
      await this.startCourseReplay(course, courseLog);
    } catch (error) {
      gamereplay.warn('course replay failed', error);
      await this.showSelect();
      this.setStatus(playerText().replay.courseFailed((error as Error).message));
    }
  }
 
  /**
   * Finds the loaded song a replay belongs to. Chart-file SHA-256 first (`chart.sha256`), then the recorded
   * `chartPath`, then a title + artist heuristic for logs recorded before either rode along.
   */
  private async findSongForReplay(replay: BeMusicReplay): Promise<LibraryChart | undefined> {
    // Content hash first — stable across sessions, machines, and file moves.
    const sha256 = replay.chart.sha256?.toLowerCase();
    if (sha256 !== undefined && sha256.length > 0) {
      for (const entry of this.library.collection.charts) {
        if ((await this.records.resolveChartSHA256(entry)) === sha256) {
          return entry;
        }
      }
    }
    const nativeChartPath = replay.play.native?.chartPath;
    if (typeof nativeChartPath === 'string' && nativeChartPath.length > 0) {
      const exact = this.library.collection.charts.find((entry) => entry.chartPath === nativeChartPath);
      if (exact) {
        return exact;
      }
    }
    const title = replay.chart.title;
    if (title === undefined || title.length === 0) {
      return undefined;
    }
    return this.library.collection.charts.find(
      (entry) => entry.title === title && (replay.chart.artist === undefined || entry.artist === replay.chart.artist),
    );
  }
}
 
/** How the missing-chart dialog names a replay's chart: its title and artist, else the hash or path it was looked for by. */
export function describeReplayChart(replay: Pick<BeMusicReplay, 'chart' | 'play'>): string {
  const { title, artist, sha256 } = replay.chart;
  if (title !== undefined && title.length > 0) return artist !== undefined ? `${title} / ${artist}` : title;
  const chartPath = replay.play.native?.chartPath;
  return (
    sha256 ?? (typeof chartPath === 'string' && chartPath.length > 0 ? chartPath : playerText().replay.untitledChart)
  );
}
 
/** A loaded chart's Be-Music chart fingerprint, for a course replay stage named by it alone. */
function fingerprintOf(chartEntry: LibraryChart): string | undefined {
  try {
    return computeChartFingerprint(chartEntry.chart, { chartPath: chartEntry.chartPath });
  } catch {
    return undefined;
  }
}