All files / app-leaderboard/src/pages data.ts

100% Statements 42/42
87.5% Branches 28/32
100% Functions 15/15
100% Lines 38/38

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 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344                                        11x                                                                                                                                   41x 41x   27x 27x   41x 41x 41x     41x 41x   41x 41x 41x                   41x                                                                                 41x                         44x                                                     123x           41x                                     41x 41x     41x             11x         23x 1x       2x                                 2x                                 2x 2x 2x 2x 1x       14x                       14x                       10x                 9x                             9x   8x               9x        
import { and, asc, countDistinct, desc, eq, isNull, or, sql, type SQL } from 'drizzle-orm';
import { clearLampRank } from '@be-music/player-engine/ruleset';
import { avatarURL } from '../avatars.ts';
import type { Database } from '../db/client.ts';
import type { RulesetId } from '../rulesets.ts';
import {
  chart,
  chartAlias,
  chartset,
  courseScore,
  courseScoreResult,
  profile,
  score,
  scoreResult,
  user,
} from '../db/schema.ts';
import { byRulesetOrder } from '../rulesets.ts';
import type { ChartAlias } from './external.ts';
import { PLAY_INFO_COLUMNS, toPlayInfo, type PlayInfo } from '../play-info.ts';
 
const LIGHT_ASSIST_EASY_RANK = clearLampRank('LIGHT_ASSIST_EASY');
 
export interface RecentScore {
  scoreId: string;
  createdAt: number;
  handle: string;
  displayName: string;
  anonymous: boolean;
  avatarUrl: string;
  chartFingerprint: string;
  title: string | null;
  artist: string | null;
  laneMode: string | null;
  /** Whether the chart is listed; a play of one that is not reaches lists only for its own player. */
  chartListed: boolean;
  /** Hidden by its player; a hidden play reaches lists only for its own player. */
  hidden: boolean;
  playLevel: string | null;
  difficulty: number | null;
  playedRuleset: RulesetId;
  /** The lane arrangement (`RANDOM`, ...), `OFF` for none; null or `-` when unknown. */
  laneOption: string | null;
  assisted: boolean;
  exScore: number;
  noteCount: number;
  clearLamp: number;
  missCount: number;
  gaugeType: string;
  gaugeFinal: number | null;
  /**
   * The player's best on the chart before this play, under the same ruleset and assist class; undefined for their
   * first play of it.
   */
  previous?: { exScore: number; clearLamp: number; missCount: number };
  /** Where the play's EX-Score stands among the other players' bests on the chart, and how many players there are. */
  rank: number;
  players: number;
  /** The play's info popover, read in the same query. */
  info: PlayInfo;
}
 
export interface RecentScoresFilter {
  limit: number;
  /** The ruleset whose figures each row shows (the viewer's display ruleset). */
  ruleset: RulesetId;
  /** Include anonymous players. Off by default, like the rankings. */
  includeAnonymous: boolean;
  /** Include charts not listed yet (fewer than two players). Off by default (docs/leaderboard.md section 7). */
  includeUnlisted: boolean;
  /**
   * A player who also sees their own plays of charts not listed yet, while their account is anonymous, and that they
   * hid (the signed-in viewer), while everyone else's stay out. Ignored where the filters already let them all in.
   */
  ownerUserId?: string;
  /** Only this player's plays. */
  handle?: string;
}
 
/**
 * The newest accepted plays, each with its figures under the display ruleset (every play is simulated under all three,
 * so any ruleset has figures). Anonymous players and unlisted charts are left out unless asked for.
 */
export async function loadRecentScores(db: Database, filter: RecentScoresFilter): Promise<RecentScore[]> {
  // The page is picked first, from the plays alone, newest first: the figures and the per-play subqueries below then run
  // for the rows shown rather than for every play that passes the filters (SQLite does not flatten a subquery with a
  // LIMIT into a join, so the page stays a walk down `score_created_idx` that stops at `limit`).
  const conditions: SQL[] = [];
  if (!filter.includeAnonymous) {
    // A viewer's own plays show even while their account is anonymous.
    const named = eq(user.isAnonymous, false);
    conditions.push(filter.ownerUserId === undefined ? named : or(named, eq(score.userId, filter.ownerUserId))!);
  }
  Eif (!filter.includeUnlisted) {
    const listed = eq(chart.status, 'listed');
    conditions.push(filter.ownerUserId === undefined ? listed : or(listed, eq(score.userId, filter.ownerUserId))!);
  }
  // Hidden plays stay out, except for their own player.
  const shown = eq(score.hidden, false);
  conditions.push(filter.ownerUserId === undefined ? shown : or(shown, eq(score.userId, filter.ownerUserId))!);
  // Plays stored without ranking (another tempo, a course stage) stay out of every list.
  conditions.push(isNull(score.unranked));
  if (filter.handle !== undefined) conditions.push(eq(profile.handle, filter.handle));
  const page = db
    .select({ id: score.id, createdAt: score.createdAt })
    .from(score)
    .innerJoin(chart, eq(chart.chartFingerprint, score.chartFingerprint))
    .innerJoin(user, eq(user.id, score.userId))
    .innerJoin(profile, eq(profile.userId, score.userId))
    .where(and(...conditions))
    .orderBy(desc(score.createdAt), desc(score.id))
    .limit(filter.limit)
    .as('page');
  const rows = await db
    .select({
      scoreId: score.id,
      createdAt: score.createdAt,
      handle: profile.handle,
      displayName: profile.displayName,
      anonymous: user.isAnonymous,
      avatarKey: profile.avatarKey,
      chartFingerprint: score.chartFingerprint,
      title: chart.title,
      artist: chart.artist,
      laneMode: chart.laneMode,
      chartStatus: chart.status,
      hidden: score.hidden,
      playLevel: chart.playLevel,
      difficulty: chart.difficulty,
      playedRuleset: score.playedRuleset,
      laneOption: score.laneOption,
      assisted: score.assisted,
      exScore: scoreResult.exScore,
      noteCount: scoreResult.noteCount,
      clearLamp: scoreResult.clearLamp,
      missCount: scoreResult.missCount,
      gaugeType: scoreResult.gaugeType,
      gaugeFinal: scoreResult.gaugeFinal,
      info: PLAY_INFO_COLUMNS,
      ...previousBest(filter.ruleset),
      ...standing(filter),
    })
    .from(page)
    .innerJoin(score, eq(score.id, page.id))
    // A truncated result stays out of the lists, as an unranked play does (ADR 0019).
    .innerJoin(
      scoreResult,
      and(eq(scoreResult.scoreId, score.id), eq(scoreResult.ruleset, filter.ruleset), isNull(scoreResult.outcome)),
    )
    .innerJoin(chart, eq(chart.chartFingerprint, score.chartFingerprint))
    .innerJoin(user, eq(user.id, score.userId))
    .innerJoin(profile, eq(profile.userId, score.userId))
    // Ordered by the page's own columns, so the page drives the join rather than a scan of every play in index order.
    .orderBy(desc(page.createdAt), desc(page.id));
  return rows.map(
    ({
      createdAt,
      chartStatus,
      anonymous,
      avatarKey,
      previousEx,
      previousLamp,
      previousMiss,
      above,
      players,
      info,
      ...row
    }) => ({
      ...row,
      info: toPlayInfo(info),
      avatarUrl: avatarURL(row.handle, avatarKey),
      createdAt: createdAt.getTime(),
      anonymous: anonymous === true,
      chartListed: chartStatus === 'listed',
      ...(previousEx === null
        ? {}
        : {
            previous: {
              exScore: Number(previousEx),
              clearLamp: Number(previousLamp),
              missCount: Number(previousMiss),
            },
          }),
      rank: Number(above) + 1,
      players: Number(players),
    }),
  );
}
 
/**
 * The player's earlier plays of the chart under the ruleset and the play's assist class: their best EX-Score, best
 * lamp and fewest misses. The plays come off `score_user_chart_idx`, so each row costs one short index range.
 */
function previousBest(ruleset: RulesetId) {
  const earlier = (column: SQL) => sql`(
    select ${column} from score p join score_result pr on pr.score_id = p.id and pr.ruleset = ${ruleset}
    where p.user_id = ${score.userId} and p.chart_fingerprint = ${score.chartFingerprint}
      and p.assisted = ${score.assisted} and p.created_at < ${score.createdAt} and p.hidden = 0
      and p.unranked is null
  )`;
  return {
    previousEx: sql<number | null>`${earlier(sql`max(pr.ex_score)`)}`,
    // Stored lamp ranks are append-only, not an order: LIGHT ASSIST EASY (10) sits between ASSIST EASY (2) and EASY
    // (3), so the best lamp is the maximum by a sort key that puts it at 2.5, read back as its rank.
    previousLamp: sql<
      number | null
    >`(select case when m = 2.5 then ${LIGHT_ASSIST_EASY_RANK} else m end from (select ${earlier(
      sql`max(case pr.clear_lamp when ${LIGHT_ASSIST_EASY_RANK} then 2.5 else pr.clear_lamp end)`,
    )} as m))`,
    previousMiss: sql<number | null>`${earlier(sql`min(pr.miss_count)`)}`,
  };
}
 
/**
 * The play's place in the chart's ranking (the kept bests under the display ruleset and the play's assist class): how
 * many other players' bests beat its EX-Score, and how many players the ranking has. Anonymous players count only when
 * the list includes them, as in the rankings.
 */
function standing(filter: RecentScoresFilter) {
  const anonymous = filter.includeAnonymous ? sql`` : sql`and coalesce(u.is_anonymous, 0) = 0`;
  const ranking = sql`from best_score b join "user" u on u.id = b.user_id
    where b.chart_fingerprint = ${score.chartFingerprint} and b.ruleset = ${filter.ruleset}
      and b.assisted = ${score.assisted} ${anonymous}`;
  return {
    above: sql<number>`(select count(*) ${ranking} and b.user_id <> ${score.userId} and b.best_ex > ${scoreResult.exScore})`,
    players: sql<number>`(select count(*) ${ranking})`,
  };
}
 
export async function loadChart(db: Database, chartFingerprint: string) {
  return db.query.chart.findFirst({ where: eq(chart.chartFingerprint, chartFingerprint) });
}
 
/** The chartset a chart is filed under, for the breadcrumbs and the link to it. */
export async function loadChartsetOf(db: Database, chartsetId: string | null) {
  if (chartsetId === null) return undefined;
  return db.query.chartset.findFirst({ where: eq(chartset.id, chartsetId) });
}
 
export async function loadChartset(db: Database, id: string) {
  return db.query.chartset.findFirst({ where: eq(chartset.id, id) });
}
 
export interface ChartsetChart {
  chartFingerprint: string;
  title: string | null;
  subtitle: string | null;
  artist: string | null;
  laneMode: string | null;
  noteCount: number;
  packType: 'included' | 'additional' | null;
  listed: boolean;
  players: number;
}
 
/** The charts of a chartset with their player counts: the work's own charts first, then the add-ons, by note count. */
export async function loadChartsetCharts(db: Database, chartsetId: string): Promise<ChartsetChart[]> {
  const rows = await db
    .select({
      chartFingerprint: chart.chartFingerprint,
      title: chart.title,
      subtitle: chart.subtitle,
      artist: chart.artist,
      laneMode: chart.laneMode,
      noteCount: chart.noteCount,
      packType: chart.packType,
      status: chart.status,
      players: countDistinct(score.userId),
    })
    .from(chart)
    .leftJoin(score, and(eq(score.chartFingerprint, chart.chartFingerprint), isNull(score.unranked)))
    .where(eq(chart.chartsetId, chartsetId))
    .groupBy(chart.chartFingerprint)
    .orderBy(asc(chart.noteCount));
  const order = (packType: ChartsetChart['packType']): number =>
    packType === 'included' ? 0 : packType === 'additional' ? 1 : 2;
  return rows
    .map(({ status, ...row }) => ({ ...row, listed: status === 'listed' }))
    .sort((a, b) => order(a.packType) - order(b.packType) || a.noteCount - b.noteCount);
}
 
export async function loadPlayer(db: Database, handle: string) {
  const [row] = await db
    .select({
      userId: profile.userId,
      handle: profile.handle,
      displayName: profile.displayName,
      anonymous: user.isAnonymous,
      avatarKey: profile.avatarKey,
      joinedAt: profile.createdAt,
    })
    .from(profile)
    .innerJoin(user, eq(user.id, profile.userId))
    .where(eq(profile.handle, handle.toLowerCase()));
  return row === undefined
    ? undefined
    : {
        ...row,
        anonymous: row.anonymous === true,
        joinedAt: row.joinedAt.getTime(),
        avatarUrl: avatarURL(row.handle, row.avatarKey),
      };
}
 
/** The file hashes known for a chart, in a stable order. */
export async function loadChartAliases(db: Database, chartFingerprint: string): Promise<ChartAlias[]> {
  return db
    .select({ kind: chartAlias.kind, hash: chartAlias.hash })
    .from(chartAlias)
    .where(eq(chartAlias.chartFingerprint, chartFingerprint))
    .orderBy(chartAlias.kind, chartAlias.hash);
}
 
/** One course run with its player (null when the profile is gone) and its figures under every ruleset, for its page. */
export async function loadCourseRun(db: Database, courseScoreId: string) {
  const [[row], results] = await Promise.all([
    db
      .select({
        run: courseScore,
        handle: profile.handle,
        displayName: profile.displayName,
        anonymous: user.isAnonymous,
        avatarKey: profile.avatarKey,
      })
      .from(courseScore)
      .leftJoin(user, eq(user.id, courseScore.userId))
      .leftJoin(profile, eq(profile.userId, courseScore.userId))
      .where(eq(courseScore.id, courseScoreId)),
    db.select().from(courseScoreResult).where(eq(courseScoreResult.courseScoreId, courseScoreId)),
  ]);
  if (row === undefined) return undefined;
  const player =
    row.handle !== null && row.displayName !== null
      ? {
          handle: row.handle,
          displayName: row.displayName,
          anonymous: row.anonymous === true,
          avatarKey: row.avatarKey,
        }
      : null;
  return { run: row.run, player, results: results.sort(byRulesetOrder) };
}
 
export type { PlayInfo } from '../play-info.ts';