All files / app-play/src course-table-import.ts

94.62% Statements 88/93
93.15% Branches 68/73
100% Functions 20/20
94.8% Lines 73/77

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                              10x   10x             10x                                                 119x 119x 118x 118x 118x   4x           52x 37x 37x 37x 35x 35x 107x 107x   35x   1x                     22x 18x 18x 18x 109x   2x           64x                     8x 8x 8x 8x             8x               7x 7x 6x               19x 19x 6x               18x 17x         1x 18x                 41x 41x 23x 22x                                     43x 43x 43x 44x 44x 44x         44x     43x 43x                     26x 44x 44x                 32x 16x 15x               9x 9x               31x 31x                   9x 9x   1x   8x 7x 7x 5x   5x         9x    
// Importing the courses a difficulty table publishes in its header (`header.json`), from the table's URL. The fetch,
// the stored URL list and the group merge live here; the Options dialog's Course folder only binds the controls, and the
// library service (`services/library.ts`) refreshes the course folders.
import type { CourseDefinitionGroup } from '@be-music/player-browser/collection';
import { fetchTableHeaderCourses, parseTableHeaderCourses, type TableFetchText } from '@be-music/player-engine/course';
import {
  COURSE_TABLE_MAX_AGE_MS,
  readThroughRemoteCache,
  type RemoteCacheSource,
  type RemoteCacheStore,
} from './services/remote-cache.ts';
import { PLAYER_STORAGE_PREFIX } from './ui/options/folders.ts';
import { resolveURLLoadFetchURL } from './url-load.ts';
 
/** `localStorage` key of the difficulty-table URLs whose courses are imported again on load. */
export const COURSE_TABLE_URLS_STORAGE_KEY = `${PLAYER_STORAGE_PREFIX}course-table-urls`;
/** `localStorage` key of the well-known tables ({@link DEFAULT_COURSE_TABLE_URLS}) the player removed from the list. */
export const REMOVED_DEFAULT_COURSE_TABLE_URLS_STORAGE_KEY = `${PLAYER_STORAGE_PREFIX}course-table-removed-defaults`;
 
/**
 * Well-known difficulty tables whose headers list courses, imported until the player stores a list of their own. Each
 * is the page URL players share; its `bmstable` meta names the header. Tables whose header lists no course (Overjoy,
 * DP Stella) are left out, since an import of one only reports that it has none.
 */
export const DEFAULT_COURSE_TABLE_URLS: readonly string[] = [
  // NEW GENERATION 通常難易度表 (▽) and 発狂難易度表 (▼)
  'https://rattoto10.jounin.jp/table.html',
  'https://rattoto10.jounin.jp/table_insane.html',
  // Satellite, Stella, DP Satellite
  'https://stellabms.xyz/sl/table.html',
  'https://stellabms.xyz/st/table.html',
  'https://stellabms.xyz/dp/table.html',
  // Stardust, Starlight
  'https://mqppppp.neocities.org/StardustTable.html',
  'https://djkuroakari.github.io/starlighttable.html',
  // Luminous (LN)
  'https://ladymade-star.github.io/luminous/table.html',
];
 
/** A difficulty table's courses, read as one course group. */
export interface ImportedCourseTable {
  group: CourseDefinitionGroup;
  headerURL: string;
  /** The table's song list (`data_url`), where the download pages of its courses' stages are looked up. */
  dataURL?: string;
}
 
/** The trimmed URL when it is an absolute http(s) URL, else `undefined`. */
export function normalizeCourseTableURL(input: string): string | undefined {
  const trimmed = input.trim();
  if (trimmed.length === 0) return undefined;
  try {
    const url = new URL(trimmed);
    return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : undefined;
  } catch {
    return undefined;
  }
}
 
/** Stored table URLs, keeping only valid, distinct http(s) URLs in their stored order. */
export function parseStoredCourseTableURLs(raw: string | null | undefined): string[] {
  if (!raw) return [];
  try {
    const parsed: unknown = JSON.parse(raw);
    if (!Array.isArray(parsed)) return [];
    const urls: string[] = [];
    for (const value of parsed) {
      const url = typeof value === 'string' ? normalizeCourseTableURL(value) : undefined;
      if (url !== undefined && !urls.includes(url)) urls.push(url);
    }
    return urls;
  } catch {
    return [];
  }
}
 
/**
 * The remembered table URLs: the stored list, or {@link DEFAULT_COURSE_TABLE_URLS} while none is stored, less the
 * well-known tables the player removed. Empty when storage is blocked. A stored empty list reads as none: builds before
 * the well-known tables stored one with every Options save (and synced it to their account), so it says nothing about
 * the tables the player wants; removing the last table records the removed well-known tables instead.
 */
export function readStoredCourseTableURLs(storage: Pick<Storage, 'getItem'> | undefined = defaultStorage()): string[] {
  if (storage === undefined) return [];
  try {
    const urls = parseStoredCourseTableURLs(storage.getItem(COURSE_TABLE_URLS_STORAGE_KEY));
    const removed = parseStoredCourseTableURLs(storage.getItem(REMOVED_DEFAULT_COURSE_TABLE_URLS_STORAGE_KEY));
    return (urls.length > 0 ? urls : [...DEFAULT_COURSE_TABLE_URLS]).filter((url) => !removed.includes(url));
  } catch {
    return [];
  }
}
 
/** The well-known tables `urls` lacks: what a stored list records as removed, so an empty list stays empty. */
export function removedDefaultCourseTableURLs(urls: readonly string[]): string[] {
  return DEFAULT_COURSE_TABLE_URLS.filter((url) => !urls.includes(url));
}
 
/**
 * Stores `urls` as the remembered tables, with the well-known tables it lacks as removed, and returns what was stored;
 * blocked storage keeps it for this session.
 */
export function storeCourseTableURLs(
  urls: readonly string[],
  storage: Pick<Storage, 'setItem'> | undefined = defaultStorage(),
): string[] {
  const stored = parseStoredCourseTableURLs(JSON.stringify(urls));
  try {
    storage?.setItem(COURSE_TABLE_URLS_STORAGE_KEY, JSON.stringify(stored));
    storage?.setItem(
      REMOVED_DEFAULT_COURSE_TABLE_URLS_STORAGE_KEY,
      JSON.stringify(removedDefaultCourseTableURLs(stored)),
    );
  } catch {
    // Private windows / blocked storage: the list still applies for this session.
  }
  return stored;
}
 
/** Adds `url` to the remembered table URLs (once) and returns the new list; blocked storage keeps it for this session. */
export function rememberCourseTableURL(
  url: string,
  storage: Pick<Storage, 'getItem' | 'setItem'> | undefined = defaultStorage(),
): string[] {
  const urls = readStoredCourseTableURLs(storage);
  if (urls.includes(url)) return urls;
  return storeCourseTableURLs([...urls, url], storage);
}
 
/** `groups` with `group` added, replacing the group that has the same label in place. */
export function mergeCourseGroup(
  groups: readonly CourseDefinitionGroup[],
  group: CourseDefinitionGroup,
): CourseDefinitionGroup[] {
  const index = groups.findIndex((existing) => existing.label === group.label);
  if (index < 0) return [...groups, group];
  return groups.map((existing, i) => (i === index ? group : existing));
}
 
/**
 * A status line for a failed import. `fetch` rejects with a bare `TypeError` when the request never completes (offline,
 * or a host that serves no proxy route and a table site that sends no CORS header), so that case says what to do.
 */
export function describeCourseTableImportError(error: unknown): string {
  if (error instanceof TypeError) {
    return (
      'Course table import failed: the table could not be fetched from here. Save the table’s header file ' +
      '(the JSON its page names in <meta name="bmstable">, usually header.json) and drop it here instead'
    );
  }
  const message = error instanceof Error ? error.message : String(error);
  return `Course table import failed: ${message}`;
}
 
/**
 * Fetches a URL's body as text with the browser `fetch`, rejecting a non-2xx response. A cross-origin URL goes through
 * the player's same-origin proxy (as `?music=` archives do), since most table sites send no CORS header. Relative
 * header URLs still resolve against `url` itself, not the proxy.
 */
export async function fetchCourseTableText(url: string, init?: RequestInit): Promise<string> {
  const fetchURL = resolveURLLoadFetchURL(url);
  const response = await (init === undefined ? fetch(fetchURL) : fetch(fetchURL, init));
  if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
  return response.text();
}
 
/**
 * A table fetch that keeps what it read between visits (the table's page, header and song list), so the tables load
 * again without asking their sites for a day ({@link COURSE_TABLE_MAX_AGE_MS}), or until `refreshedSince` (a reload of
 * the folders). A read due goes to the site as a revalidation (`no-cache`), which the proxy passes on with the
 * browser's validators, and a site that cannot be reached leaves the copy kept last time in use. `onRead` hears where
 * each read came from.
 */
export function createCachedCourseTableFetchText(options: {
  store: RemoteCacheStore | undefined;
  refreshedSince?: number;
  cacheOnly?: boolean;
  signal?: AbortSignal;
  now?: () => number;
  fetchText?: (url: string, init?: RequestInit) => Promise<string>;
  onRead?: (url: string, source: RemoteCacheSource) => void;
}): TableFetchText {
  const fetchText = options.fetchText ?? fetchCourseTableText;
  const now = options.now ?? Date.now;
  return async (url) => {
    const { signal } = options;
    signal?.throwIfAborted();
    Iif (options.cacheOnly) {
      const kept = await options.store?.get(`table:${url}`);
      if (kept === undefined) throw new Error('Difficulty table is not cached');
      return new TextDecoder().decode(kept.bytes);
    }
    const read = await readThroughRemoteCache(
      `table:${url}`,
      async () => {
        signal?.throwIfAborted();
        return new TextEncoder().encode(
          await fetchText(url, { cache: 'no-cache', ...(signal === undefined ? {} : { signal }) }),
        );
      },
      options.store,
      {
        maxAgeMs: COURSE_TABLE_MAX_AGE_MS,
        ...(options.refreshedSince !== undefined ? { refreshedSince: options.refreshedSince } : {}),
      },
      now(),
    );
    signal?.throwIfAborted();
    options.onRead?.(url, read.source);
    return new TextDecoder().decode(read.bytes);
  };
}
 
/** Reads a difficulty table's courses from its page or header URL. Throws when the table has no course. */
export async function importCourseTable(
  url: string,
  fetchText: TableFetchText = fetchCourseTableText,
): Promise<ImportedCourseTable> {
  const table = await fetchTableHeaderCourses(url, fetchText);
  if (table.courses.length === 0) throw new Error(`${table.label} lists no course`);
  return {
    group: { label: table.label, kind: 'difficulty-table', courses: table.courses },
    headerURL: table.headerURL,
    ...(table.dataURL !== undefined ? { dataURL: table.dataURL } : {}),
  };
}
 
function defaultStorage(): Storage | undefined {
  try {
    return typeof window === 'undefined' ? undefined : window.localStorage;
  } catch {
    return undefined;
  }
}
 
/** Whether a dropped file may be a saved difficulty-table header: a JSON file named `header.json`, as tables name it. */
export function isTableHeaderFilePath(path: string): boolean {
  const name = path.replaceAll('\\', '/').split('/').at(-1) ?? path;
  return name.toLowerCase() === 'header.json';
}
 
/**
 * Reads a saved difficulty-table header (`header.json`) into its course group, the way a table URL import reads it:
 * labelled with the table's `name` (else its `symbol`, else `fallbackLabel`). `undefined` when the text is not a JSON
 * object or lists no course, so the file can go on to the other loaders.
 */
export function readTableHeaderFile(text: string, fallbackLabel: string): CourseDefinitionGroup | undefined {
  let header: unknown;
  try {
    header = JSON.parse(text);
  } catch {
    return undefined;
  }
  if (typeof header !== 'object' || header === null || Array.isArray(header)) return undefined;
  const courses = parseTableHeaderCourses(header).flat();
  if (courses.length === 0) return undefined;
  const { name, symbol } = header as { name?: unknown; symbol?: unknown };
  const label =
    typeof name === 'string' && name.trim().length > 0
      ? name.trim()
      : typeof symbol === 'string' && symbol.trim().length > 0
        ? symbol.trim()
        : fallbackLabel;
  return { label, kind: 'difficulty-table', courses };
}