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
22 changes: 18 additions & 4 deletions api-directory.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,16 @@
- POST `/api/account/profile`:FormData,可提交 `nickname`、`introduction`、`avatar`,返回更新后的资料。
- GET `/api/avatar/{avatarId}`:头像,前端只用这一个接口(`UserAvatar` 组件 / `useAvatarUrl`)。已知 `avatarId` 时直接使用、不发请求:资料对象自带 `avatarId`;总分榜(`/api/maiscore/sum/...` 的 `players[].player`)、季赛榜(`/api/maiscore/leaderboard/period` 每条的 `player`)和评论(`authorProfile`)附带精简资料 `UserBrief` = `{ id, username, nickname, avatarId }`(未上传头像时 `avatarId` 为 `default`,`nickname` 可能为空串;账号已删除或评论为占位符时为 null);单曲排行榜 `scores[][].player` 的 `id`、`avatarId` 也已填充。只有谱面上传者(谱面响应不带资料)以及上述资料为 null 或缺失时,才按用户名读 GET `/api/account/profile?username=...` 取 `avatarId`,同名只请求一次并与个人空间共用缓存;用户不存在或无用户名时用 `default`。这些榜单和评论仍显示用户名,不换成昵称。`/api/account/icon?username=...` 仅留给 MajdataPlay,前端不再调用。
- 头像和简介上传后刷新资料,避免旧头像缓存;昵称用于显示,用户名继续用于链接、归属判断和 API 查询。
- GET `/api/account/recent?username=...`、GET `/api/account/scores` 的已有调用协议保持兼容。
- GET `/api/account/recent?username=...` 的已有调用协议保持兼容;GET `/api/account/scores` 的每条成绩增加 `levelHash`(见下文「按 level hash 存储成绩」)。

## 排行、收藏与评论

| 功能 | 对齐结果 |
| --- | --- |
| 全站总分榜 | 改用 GET `/api/maiscore/sum/all?page=0&pageSize=...` |
| 上传者榜 | 改用 GET `/api/maiscore/sum/chart/by-uploader/{uploader}?page=0&pageSize=...`(`uploader` 作为路径段转义);旧 `/api/stats/score-sums` 已废弃 |
| 单曲排行榜/成绩卡排名 | 改用 GET `/api/maiscore/leaderboard/chart/by-id/{chartId}`;旧 GET `/api/maichart/{chartId}/score` 已废弃 |
| 季赛榜 | 改用 POST `/api/maiscore/leaderboard/period`,请求体不变;旧 POST `/api/playhistory/ranking` 已废弃 |
| 单曲排行榜/成绩卡排名 | 单曲排行榜用 GET `/api/maiscore/leaderboard/chart/by-id/{chartId}`,响应为 `{ hash, levelHashes, scores }`;成绩卡排名在成绩带 `levelHash` 时用 GET `/api/maiscore/leaderboard/chart/by-level/{levelHash}`,否则退回 `by-id`;旧 GET `/api/maichart/{chartId}/score` 已废弃 |
| 季赛榜 | 改用 POST `/api/maiscore/leaderboard/period`,请求体用 `songIds`(谱面 Id 数组);旧 POST `/api/playhistory/ranking` 已废弃 |
| 总分返回值 | 从旧数组和 `dxAccSum` 改为 `{ geneTime, players: [{ userId, username, acc: { dx, classic }, player }] }`,`player` 为 `UserBrief \| null` |
| 收藏歌单列表 | GET `/api/account/favorite/collection/list` 返回 `songHashs`,卡片的 `count` 从数组长度计算 |
| 谱面投票 | PUT `/api/maichart/{chartId}/vote`,JSON `{ value: 1 \| 0 \| -1 }`,返回 `{ score, upvotes, downvotes, myVote }`;旧的 like/dislike Form 接口只保留给游戏客户端 |
Expand All @@ -46,7 +46,21 @@
| 管理员 | 前端用 GET `/api/admin/groups` 是否返回 200 判断当前用户是否为管理员,管理员可移除任何评论 |
| 单曲排行榜 | `player` 的昵称、头像信息用于显示,用户名用于个人空间链接 |

已核对仍兼容的接口:谱面搜索/排序/详情及文件下载、上传及哈希检查、删除、标签更新、歌单创建/修改/删除/曲目增删、收藏/取消收藏、季赛榜请求和最近游玩数据、机台扫码授权。列表排序新增 `hotp`(热门)与 `topp`(分数),`likep` 不再使用。
已核对仍兼容的接口:谱面搜索/排序/详情及文件下载、上传及哈希检查、删除、标签更新、歌单创建/删除、收藏/取消收藏、最近游玩数据、机台扫码授权。列表排序新增 `hotp`(热门)与 `topp`(分数),`likep` 不再使用。歌单修改、曲目增删和季赛榜请求已按下文改为谱面 Id。

## 按 level hash 存储成绩(TeamMajdata/mmfcapi#44)

后端改为按各难度 inote 的 SHA-256(level hash)存成绩,按谱面 Id(`MaiChart.Id`)存互动、投票、评论和歌单,契约见后端仓库 `docs/level-hash.md`。前端只使用后端返回的 level hash,不自己计算。

| 功能 | 接口 | 前端的谱面 Id / level hash 来源 |
| --- | --- | --- |
| 单曲排行榜 | GET `/api/maiscore/leaderboard/chart/by-id/{chartId}`,响应 `{ hash, levelHashes, scores }`;`levelHashes` 固定 7 项,`scores` 仍为 8 项 | 谱面页 URL 的 `id` |
| 成绩卡排名 | GET `/api/maiscore/leaderboard/chart/by-level/{levelHash}`,响应 `{ levelHash, scores }`;没有合法 `levelHash`(迁移未完成的旧成绩、最近游玩卡片)时退回 `by-id` | `/api/account/scores` 每条成绩的 `levelHash`;退回时用 `chartInfo.id` |
| 季赛榜及单曲明细 | POST `/api/maiscore/leaderboard/period`,`songIds` 代替 `songHashes` | 季赛歌单 `songlist` 的 `items[].id` |
| 歌单增删曲目 | POST `/api/collection/{id}/diff`,`chartIdsToAdd` / `chartIdsToRemove` 代替 `hashesToAdd` / `hashesToRemove`;是否已收录仍按 `hashlist` 返回的 hash 判断 | 谱面页的谱面 Id |
| 歌单管理保存 | POST `/api/collection/{id}/modify`,`items` 为谱面 Id 数组 | 原有曲目取 `songlist` 的 `items[].id`,新增曲目取搜索结果的 `id`,不再为取 hash 请求 `summary` |

`hashlist`、`songlist`、`favorite/collection/list` 的响应不变。谱面信息 `/api/maichart/{chartId}/info`、POST `/api/maichart/info` 新增的 `levelHashes` 前端暂未使用(前端读的是 `summary`)。按谱面查成绩总和的 `/api/maiscore/sum/chart/by-id/{chartId}` 前端目前没有调用点。前端没有提交成绩的地方,`POST /api/maiscore/level/{levelHash}`(请求体须带 `chartId`)只供游戏客户端使用。

## 需要后端修复的阻碍

Expand Down
24 changes: 15 additions & 9 deletions src/components/collection/CollectionModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import { useCollections } from '@/hooks';
interface CollectionModalProps {
isOpen: boolean;
onClose: () => void;
/** 谱面 Id(MaiChart.Id),加入或移出谱单时提交 */
chartId?: string;
/** 谱面当前的 maidata hash,用于判断是否已在谱单中 */
songHash?: string;
onCreate?: () => void;
}
Expand Down Expand Up @@ -43,7 +46,7 @@ const listItemVariants = {
}),
};

export default function CollectionModal({ isOpen, onClose, songHash: songId, onCreate }: CollectionModalProps) {
export default function CollectionModal({ isOpen, onClose, chartId, songHash, onCreate }: CollectionModalProps) {
const { t } = useTranslation();
const [isCreating, setIsCreating] = useState(false);
const [newName, setNewName] = useState('');
Expand Down Expand Up @@ -93,10 +96,13 @@ export default function CollectionModal({ isOpen, onClose, songHash: songId, onC
return (c.name || '').toLowerCase().includes(q) || (c.description || '').toLowerCase().includes(q);
});

// 增删按谱面 Id 提交,是否已收录按 hash 判断,两者都有才能切换
const canToggle = !!chartId && !!songHash;

const handleToggle = useCallback(async (collectionId: string) => {
if (!songId) return;
await toggleSongInCollection(collectionId, songId);
}, [songId, toggleSongInCollection]);
if (!chartId || !songHash) return;
await toggleSongInCollection(collectionId, { chartId, songHash });
}, [chartId, songHash, toggleSongInCollection]);

const handleCreate = useCallback(async () => {
if (!newName.trim() || creatingLoading) return;
Expand Down Expand Up @@ -218,19 +224,19 @@ export default function CollectionModal({ isOpen, onClose, songHash: songId, onC
<div className="flex flex-col gap-1.5">
{filteredCollections.map((collection, index) => {
const isAdding = isPending(collection.id);
const isInCollection = songId ? isSongInCollection(collection.id, songId) : false;
const isInCollection = isSongInCollection(collection.id, songHash);
return (
<motion.button
key={collection.id}
custom={index}
variants={listItemVariants}
initial="hidden"
animate="visible"
whileHover={songId ? { scale: 1.01 } : undefined}
whileTap={songId ? { scale: 0.98 } : undefined}
whileHover={canToggle ? { scale: 1.01 } : undefined}
whileTap={canToggle ? { scale: 0.98 } : undefined}
disabled={!!isAdding}
onClick={songId ? () => handleToggle(collection.id) : undefined}
className={`group flex items-start gap-3 rounded-xl p-3 text-left transition-colors ${songId ? 'cursor-pointer hover:bg-white/5' : 'cursor-default'
onClick={canToggle ? () => handleToggle(collection.id) : undefined}
className={`group flex items-start gap-3 rounded-xl p-3 text-left transition-colors ${canToggle ? 'cursor-pointer hover:bg-white/5' : 'cursor-default'
} ${isInCollection ? 'bg-blue-500/10' : ''} ${isAdding ? 'bg-blue-500/10' : ''}`}
>
<div className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-lg transition-colors ${isAdding ? 'bg-blue-500/15' : isInCollection ? 'bg-blue-500/15' : 'bg-white/5 group-hover:bg-white/10'
Expand Down
70 changes: 45 additions & 25 deletions src/components/score/ScoreCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,35 @@ import { apiFetcher } from '@/utils/apiClient';
import { endpoints } from '@/config/api';
import { getComboState } from '@/utils';
import { useUsername } from '@/hooks';
import type { Score, ChartScore } from '@/types';
import type { Score, ChartScore, ChartLeaderboardResponse, LevelLeaderboardResponse } from '@/types';

type UserRank = { rank: number; total: number };

/** 后端返回的 level hash 是 64 位小写 hex;迁移期的旧成绩可能缺失或为 null */
function isLevelHash(value: unknown): value is string {
return typeof value === 'string' && /^[0-9a-f]{64}$/.test(value);
}

/**
* 从谱面成绩列表中查找指定用户的排名
* 在单个榜单中查找指定用户的排名
*/
function findRankInList(scoreList: ChartScore[] | undefined, target: string): UserRank | null {
if (!Array.isArray(scoreList)) return null;

const rankIndex = scoreList.findIndex(
(score) => score.player?.username?.trim().toLowerCase() === target
);
return rankIndex === -1 ? null : { rank: rankIndex + 1, total: scoreList.length };
}

/**
* 从谱面各难度的成绩列表中查找指定用户的排名:先找 levelIndex 对应的难度,找不到再扫其他难度
*/
function findUserRank(
payload: { scores?: ChartScore[][] } | null,
username: string,
levelIndex: number
): { rank: number; total: number } | null {
): UserRank | null {
const scores = payload?.scores;
if (!scores || !Array.isArray(scores)) return null;

Expand All @@ -33,15 +52,8 @@ function findUserRank(
].filter((index) => index >= 0 && index < scores.length);

for (const index of candidateIndexes) {
const scoreList = scores[index];
if (!Array.isArray(scoreList)) continue;

const rankIndex = scoreList.findIndex(
(score) => score.player?.username?.trim().toLowerCase() === target
);
if (rankIndex !== -1) {
return { rank: rankIndex + 1, total: scoreList.length };
}
const result = findRankInList(scores[index], target);
if (result) return result;
}

return null;
Expand All @@ -68,23 +80,31 @@ export function ScoreCard({
const currentUsername = useUsername();
const targetUsername = rankUsername || currentUsername;

const { data: chartScores } = useSWR(
showRank && targetUsername ? endpoints.maiscore.chartLeaderboard(score.chartInfo.id) : null,
// 成绩带有 level hash(来自 account/scores)时直接查该难度的榜;
// 旧成绩或没有 level hash 的数据(如最近游玩)退回按谱面 Id 查各难度的榜
const levelHash = isLevelHash(score.levelHash) ? score.levelHash : null;
const shouldFetchRank = showRank && !!targetUsername;

const { data: levelScores } = useSWR<LevelLeaderboardResponse>(
shouldFetchRank && levelHash ? endpoints.maiscore.levelLeaderboard(levelHash) : null,
apiFetcher
);
const { data: chartScores } = useSWR<ChartLeaderboardResponse>(
shouldFetchRank && !levelHash ? endpoints.maiscore.chartLeaderboard(score.chartInfo.id) : null,
apiFetcher
);

// 计算最终使用的排名信息
const resolvedRank = useMemo(() => {
if (!showRank || !chartScores || !targetUsername) return null;
const result = findUserRank(chartScores, targetUsername, score.chartLevel);
return result?.rank ?? null;
}, [showRank, chartScores, targetUsername, score.chartLevel]);

const resolvedRankTotal = useMemo(() => {
if (!showRank || !chartScores || !targetUsername) return null;
const result = findUserRank(chartScores, targetUsername, score.chartLevel);
return result?.total ?? null;
}, [showRank, chartScores, targetUsername, score.chartLevel]);
const userRank = useMemo(() => {
if (!shouldFetchRank) return null;
if (levelHash) {
return levelScores ? findRankInList(levelScores.scores, targetUsername.trim().toLowerCase()) : null;
}
return chartScores ? findUserRank(chartScores, targetUsername, score.chartLevel) : null;
}, [shouldFetchRank, levelHash, levelScores, chartScores, targetUsername, score.chartLevel]);

const resolvedRank = userRank?.rank ?? null;
const resolvedRankTotal = userRank?.total ?? null;

const comboStateNumber = typeof score.comboState === 'number' ? score.comboState : Number(score.comboState);
const comboStateText = comboStateNumber > 0 ? getComboState(comboStateNumber) : '';
Expand Down
2 changes: 1 addition & 1 deletion src/components/season/SeasonLeaderboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ interface SeasonLeaderboardProps {

export default function SeasonLeaderboard({ event, status, chartState }: SeasonLeaderboardProps) {
const { t } = useTranslation();
const ranking = useSeasonRanking(event, status, chartState.songhashes ?? null);
const ranking = useSeasonRanking(event, status, chartState.songIds ?? null);
const { entries } = ranking;
const error = chartState.error ?? ranking.error;
const isLoading = chartState.isLoading || ranking.isLoading;
Expand Down
9 changes: 5 additions & 4 deletions src/components/song/ScoreRanking.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { getComboState, getLevelName } from '@/utils';
import { LoadingSpinner } from '@/components';
import UserAvatar from '@/components/user/UserAvatar';
import { Link } from 'react-router-dom';
import type { ChartScore, ScoreListProps } from '@/types';
import type { ChartLeaderboardResponse, ChartScore, ScoreListProps } from '@/types';

const fetcher = (url: string) =>
fetch(url, { mode: 'cors', credentials: 'include' }).then((res) => res.json());
Expand Down Expand Up @@ -357,14 +357,15 @@ export function ScoreRanking({ songid }: ScoreListProps) {
const [activeLevel, setActiveLevel] = useState<number>(0);
const [transitionDirection, setTransitionDirection] = useState<1 | -1>(1);

const { data, error, isLoading } = useSWR(
const { data, error, isLoading } = useSWR<ChartLeaderboardResponse>(
endpoints.maiscore.chartLeaderboard(songid),
fetcher,
{ revalidateOnFocus: true }
);

// 获取所有有效等级
const levels = useMemo(() => data?.levels || [], [data?.levels]);
// 排行榜响应只有 hash、levelHashes、scores,不含难度定数,所以定数一直为空(既有问题);
// 要显示定数需另从谱面信息取
const levels: string[] = [];
const scoreLevels = useMemo(() => data?.scores || [], [data?.scores]);

// 确保 activeLevel 在有效范围内
Expand Down
2 changes: 1 addition & 1 deletion src/components/user/UserSeasons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export default function UserSeasons({ username }: { username: string }) {
function UserSeasonResult({ event, status, username }: Omit<UserSeasonCardProps, 'entry'> & { username: string }) {
const { t } = useTranslation();
const charts = useSeasonCharts(event.asset);
const ranking = useSeasonRanking(event, status, charts.songhashes ?? null);
const ranking = useSeasonRanking(event, status, charts.songIds ?? null);
// Use the same complete standings as the season page, then select this user.
const entry = ranking.entries?.find(row => row.username === username);
const error = charts.error ?? ranking.error;
Expand Down
9 changes: 7 additions & 2 deletions src/config/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@ export const apiroot3 = '/api3/api';
export const endpoints = {
// 成绩排行与统计,统一位于 /api/maiscore 下
maiscore: {
// 单谱面排行榜,返回 8 个难度各自的前 10 名
// 单谱面排行榜,响应 { hash, levelHashes, scores }:levelHashes 固定 7 项,下标为难度序号,
// 没有 inote 的难度为 null;scores[level] 为该难度按 level hash 查到的前 10 名,共 8 项,最后一项恒为空数组
chartLeaderboard: (chartId: string | number) =>
`${apiroot3}/maiscore/leaderboard/chart/by-id/${encodeURIComponent(chartId)}`,
// POST,按谱面 Hash 集合和时间段统计排行(季赛榜)
// 单个难度(level hash)的排行榜,响应 { levelHash, scores };成绩按 level hash 共享,
// 内容相同的难度(换源前后、不同谱面)是同一个榜。levelHash 不是 64 位小写 hex 时返回 400
levelLeaderboard: (levelHash: string) =>
`${apiroot3}/maiscore/leaderboard/chart/by-level/${encodeURIComponent(levelHash)}`,
// POST,按谱面 Id 集合(请求体 songIds)和时间段统计排行(季赛榜)
periodLeaderboard: `${apiroot3}/maiscore/leaderboard/period`,
// 成绩总和榜;uploader 为空时为全站榜,否则只统计该上传者的谱面
scoreSums: (uploader: string, page: number, pageSize: number) =>
Expand Down
15 changes: 12 additions & 3 deletions src/hooks/useCollections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@ import type { Collection, CollectionDanInfo } from '@/types';
const fetcher = (url: string) =>
fetch(url, { mode: 'cors', credentials: 'include' }).then((res) => res.json());

/** 要加入或移出谱单的谱面 */
export interface CollectionChart {
/** 谱面 Id(MaiChart.Id),谱单增删按它提交 */
chartId: string;
/** 谱面当前的 maidata hash,用于对照 hashlist 判断是否已在谱单中 */
songHash: string;
}

export function useCollections() {
const { t } = useTranslation();
const { username } = useUserContext();
Expand Down Expand Up @@ -78,15 +86,16 @@ export function useCollections() {
);

// 切换歌曲在收藏夹中的状态(添加 / 移除)
// hashlist 仍返回 hash,所以按 hash 判断是否已收录;增删请求按谱面 Id 提交
const toggleSongInCollection = useCallback(
async (collectionId: string, songHash: string) => {
async (collectionId: string, { chartId, songHash }: CollectionChart) => {
if (!username) return;
const isIn = isSongInCollection(collectionId, songHash);
setPendingIds((prev) => new Set(prev).add(collectionId));
try {
const body = isIn
? { hashesToRemove: [songHash] }
: { hashesToAdd: [songHash] };
? { chartIdsToRemove: [chartId] }
: { chartIdsToAdd: [chartId] };

const res = await fetch(endpoints.collection.diff(collectionId), {
method: 'POST',
Expand Down
Loading
Loading