/
BeatmapsController.php
503 lines (444 loc) · 16.3 KB
/
BeatmapsController.php
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
<?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
namespace App\Http\Controllers;
use App\Enums\Ruleset;
use App\Exceptions\InvariantException;
use App\Jobs\Notifications\BeatmapOwnerChange;
use App\Libraries\BeatmapDifficultyAttributes;
use App\Libraries\Score\BeatmapScores;
use App\Libraries\Score\UserRank;
use App\Libraries\Search\ScoreSearch;
use App\Libraries\Search\ScoreSearchParams;
use App\Models\Beatmap;
use App\Models\BeatmapsetEvent;
use App\Models\User;
use App\Transformers\BeatmapTransformer;
use App\Transformers\ScoreTransformer;
/**
* @group Beatmaps
*/
class BeatmapsController extends Controller
{
const DEFAULT_API_INCLUDES = ['beatmapset.ratings', 'failtimes', 'max_combo'];
const DEFAULT_SCORE_INCLUDES = ['user', 'user.country', 'user.cover'];
public function __construct()
{
parent::__construct();
$this->middleware('require-scopes:public');
}
private static function assertSupporterOnlyOptions(?User $currentUser, string $type, array $mods): void
{
$isSupporter = $currentUser !== null && $currentUser->isSupporter();
if ($type !== 'global' && !$isSupporter) {
throw new InvariantException(osu_trans('errors.supporter_only'));
}
if (!empty($mods) && !is_api_request() && !$isSupporter) {
throw new InvariantException(osu_trans('errors.supporter_only'));
}
}
private static function beatmapScores(string $id, ?string $scoreTransformerType, ?bool $isLegacy): array
{
$beatmap = Beatmap::findOrFail($id);
if ($beatmap->approved <= 0) {
return ['scores' => []];
}
$params = get_params(request()->all(), null, [
'limit:int',
'mode',
'mods:string[]',
'type:string',
], ['null_missing' => true]);
$rulesetId = static::getRulesetId($params['mode']) ?? $beatmap->playmode;
$mods = array_values(array_filter($params['mods'] ?? []));
$type = presence($params['type'], 'global');
$currentUser = \Auth::user();
static::assertSupporterOnlyOptions($currentUser, $type, $mods);
$esFetch = new BeatmapScores([
'beatmap_ids' => [$beatmap->getKey()],
'is_legacy' => $isLegacy,
'limit' => $params['limit'],
'mods' => $mods,
'ruleset_id' => $rulesetId,
'type' => $type,
'user' => $currentUser,
]);
$scores = $esFetch->all()->loadMissing(['beatmap', 'user.country']);
$userScore = $esFetch->userBest();
$scoreTransformer = new ScoreTransformer($scoreTransformerType);
$results = [
'scores' => json_collection(
$scores,
$scoreTransformer,
static::DEFAULT_SCORE_INCLUDES
),
];
if (isset($userScore)) {
$results['user_score'] = [
'position' => $esFetch->rank($userScore),
'score' => json_item($userScore, $scoreTransformer, static::DEFAULT_SCORE_INCLUDES),
];
// TODO: remove this old camelCased json field
$results['userScore'] = $results['user_score'];
}
return $results;
}
private static function getRulesetId(?string $rulesetName): ?int
{
if ($rulesetName === null) {
return null;
}
return Ruleset::tryFromName($rulesetName)?->value
?? throw new InvariantException('invalid mode specified');
}
/**
* Get Beatmap Attributes
*
* Returns difficulty attributes of beatmap with specific mode and mods combination.
*
* ---
*
* ### Response format
*
* Field | Type
* ---------- | ----
* Attributes | [DifficultyAttributes](#beatmapdifficultyattributes)
*
* @urlParam beatmap integer required Beatmap id. Example: 2
* @bodyParam mods integer|string[]|Mod[] Mod combination. Can be either a bitset of mods, array of mod acronyms, or array of mods. Defaults to no mods. Example: 1
* @bodyParam ruleset Ruleset Ruleset of the difficulty attributes. Only valid if it's the beatmap ruleset or the beatmap can be converted to the specified ruleset. Defaults to ruleset of the specified beatmap. Example: osu
* @bodyParam ruleset_id integer The same as `ruleset` but in integer form. No-example
*
* @response {
* "attributes": {
* "max_combo": 100,
* ...
* }
* }
*/
public function attributes($id)
{
$beatmap = Beatmap::whereHas('beatmapset')->findOrFail($id);
$params = get_params(request()->all(), null, [
'mods:any',
'ruleset:string',
'ruleset_id:int',
], ['null_missing' => true]);
$rulesetId = $params['ruleset_id'];
abort_if(
$rulesetId !== null && Beatmap::modeStr($rulesetId) === null,
422,
'invalid ruleset_id specified'
);
if ($rulesetId === null && $params['ruleset'] !== null) {
$rulesetId = Beatmap::modeInt($params['ruleset']);
abort_if($rulesetId === null, 422, 'invalid ruleset specified');
}
if ($rulesetId === null) {
$rulesetId = $beatmap->playmode;
} else {
abort_if(
$rulesetId !== $beatmap->playmode && !$beatmap->canBeConverted(),
422,
"specified beatmap can't be converted to the specified ruleset"
);
}
if (isset($params['mods'])) {
if (is_numeric($params['mods'])) {
$params['mods'] = app('mods')->bitsetToIds((int) $params['mods']);
}
if (is_array($params['mods'])) {
if (count($params['mods']) > 0 && is_string(array_first($params['mods']))) {
$params['mods'] = array_map(fn ($m) => ['acronym' => $m], $params['mods']);
}
$mods = app('mods')->parseInputArray($rulesetId, $params['mods']);
} else {
abort(422, 'invalid mods specified');
}
}
return ['attributes' => BeatmapDifficultyAttributes::get($beatmap->getKey(), $rulesetId, $mods ?? [])];
}
/**
* Get Beatmaps
*
* Returns a list of beatmaps.
*
* ---
*
* ### Response format
*
* Field | Type | Description
* -------- | ------------------------------------- | -----------
* beatmaps | [BeatmapExtended](#beatmapextended)[] | Includes `beatmapset` (with `ratings`), `failtimes`, and `max_combo`.
*
* @queryParam ids[] integer Beatmap IDs to be returned. Specify once for each beatmap ID requested. Up to 50 beatmaps can be requested at once. Example: 1
*
* @response {
* "beatmaps": [
* {
* "id": 1,
* // Other Beatmap attributes...
* }
* ]
* }
*/
public function index()
{
$ids = array_slice(get_arr(request('ids'), 'get_int') ?? [], 0, 50);
if (count($ids) > 0) {
$beatmaps = Beatmap
::whereIn('beatmap_id', $ids)
->whereHas('beatmapset')
->with([
'beatmapset',
'beatmapset.userRatings' => fn ($q) => $q->select('beatmapset_id', 'rating'),
'failtimes',
])->withMaxCombo()
->orderBy('beatmap_id')
->get();
}
return [
'beatmaps' => json_collection($beatmaps ?? [], new BeatmapTransformer(), static::DEFAULT_API_INCLUDES),
];
}
/**
* Lookup Beatmap
*
* Returns beatmap.
*
* ---
*
* ### Response format
*
* See [Get Beatmap](#get-beatmap)
*
* @queryParam checksum A beatmap checksum.
* @queryParam filename A filename to lookup.
* @queryParam id A beatmap ID to lookup.
*
* @response "See Beatmap object section"
*/
public function lookup()
{
static $keyMap = [
'checksum' => 'checksum',
'filename' => 'filename',
'id' => 'beatmap_id',
];
$params = get_params(request()->all(), null, ['checksum:string', 'filename:string', 'id:int']);
foreach ($params as $key => $value) {
$beatmap = Beatmap::whereHas('beatmapset')->firstWhere($keyMap[$key], $value);
if ($beatmap !== null) {
break;
}
}
if (!isset($beatmap)) {
abort(404);
}
return json_item($beatmap, new BeatmapTransformer(), static::DEFAULT_API_INCLUDES);
}
/**
* Get Beatmap
*
* Gets beatmap data for the specified beatmap ID.
*
* ---
*
* ### Response format
*
* Returns [BeatmapExtended](#beatmapextended) object.
* Following attributes are included in the response object when applicable,
*
* Attribute | Notes
* ---------- | -----
* beatmapset | Includes ratings property.
* failtimes | |
* max_combo | |
*
* @urlParam beatmap integer required The ID of the beatmap.
*
* @response "See Beatmap object section."
*/
public function show($id)
{
$beatmap = Beatmap::whereHas('beatmapset')->findOrFail($id);
if (is_api_request()) {
return json_item($beatmap, new BeatmapTransformer(), static::DEFAULT_API_INCLUDES);
}
$beatmapset = $beatmap->beatmapset;
if ($beatmapset === null) {
abort(404);
}
$beatmapRuleset = $beatmap->mode;
if ($beatmapRuleset === 'osu') {
$params = get_params(request()->all(), null, [
'm:int', // legacy parameter
'mode', // legacy parameter
'ruleset',
], ['null_missing' => true]);
$ruleset = (
Ruleset::tryFromName($params['ruleset'])
?? Ruleset::tryFromName($params['mode'])
?? Ruleset::tryFrom($params['m'] ?? Ruleset::NULL)
)?->legacyName();
}
$ruleset ??= $beatmapRuleset;
return ujs_redirect(route('beatmapsets.show', ['beatmapset' => $beatmapset->getKey()]).'#'.$ruleset.'/'.$beatmap->getKey());
}
/**
* Get Beatmap scores
*
* Returns the top scores for a beatmap. Depending on user preferences, this may only show legacy scores.
*
* ---
*
* ### Response Format
*
* Returns [BeatmapScores](#beatmapscores). `Score` object inside includes `user` and the included `user` includes `country` and `cover`.
*
* @urlParam beatmap integer required Id of the [Beatmap](#beatmap).
*
* @queryParam legacy_only integer Whether or not to exclude lazer scores. Defaults to 0. Example: 0
* @queryParam mode The [Ruleset](#ruleset) to get scores for.
* @queryParam mods An array of matching Mods, or none // TODO.
* @queryParam type Beatmap score ranking type // TODO.
*/
public function scores($id)
{
return static::beatmapScores(
$id,
null,
// TODO: change to imported name after merge with other PRs
\App\Libraries\Search\ScoreSearchParams::showLegacyForUser(\Auth::user()),
);
}
/**
* Get Beatmap scores (non-legacy)
*
* Returns the top scores for a beatmap.
*
* ---
*
* ### Response Format
*
* Returns [BeatmapScores](#beatmapscores). `Score` object inside includes `user` and the included `user` includes `country` and `cover`.
*
* @urlParam beatmap integer required Id of the [Beatmap](#beatmap).
*
* @queryParam mode The [Ruleset](#ruleset) to get scores for.
* @queryParam mods An array of matching Mods, or none // TODO.
* @queryParam type Beatmap score ranking type // TODO.
*/
public function soloScores($id)
{
return static::beatmapScores($id, ScoreTransformer::TYPE_SOLO, null);
}
public function updateOwner($id)
{
$beatmap = Beatmap::findOrFail($id);
$currentUser = auth()->user();
priv_check('BeatmapUpdateOwner', $beatmap->beatmapset)->ensureCan();
$newUserId = get_int(request('beatmap.user_id'));
$beatmap->getConnection()->transaction(function () use ($beatmap, $currentUser, $newUserId) {
$beatmap->setOwner($newUserId);
BeatmapsetEvent::log(BeatmapsetEvent::BEATMAP_OWNER_CHANGE, $currentUser, $beatmap->beatmapset, [
'beatmap_id' => $beatmap->getKey(),
'beatmap_version' => $beatmap->version,
'new_user_id' => $beatmap->user_id,
'new_user_username' => $beatmap->user->username,
])->saveOrExplode();
});
if ($beatmap->user_id !== $currentUser->getKey()) {
(new BeatmapOwnerChange($beatmap, $currentUser))->dispatch();
}
return $beatmap->beatmapset->defaultDiscussionJson();
}
/**
* Get a User Beatmap score
*
* Return a [User](#user)'s score on a Beatmap
*
* ---
*
* ### Response Format
*
* Returns [BeatmapUserScore](#beatmapuserscore)
*
* The position returned depends on the requested mode and mods.
*
* @urlParam beatmap integer required Id of the [Beatmap](#beatmap).
* @urlParam user integer required Id of the [User](#user).
*
* @queryParam legacy_only integer Whether or not to exclude lazer scores. Defaults to 0. Example: 0
* @queryParam mode The [Ruleset](#ruleset) to get scores for.
* @queryParam mods An array of matching Mods, or none // TODO.
*/
public function userScore($beatmapId, $userId)
{
$beatmap = Beatmap::scoreable()->findOrFail($beatmapId);
$params = get_params(request()->all(), null, [
'mode:string',
'mods:string[]',
]);
$rulesetId = static::getRulesetId($params['mode'] ?? null) ?? $beatmap->playmode;
$mods = array_values(array_filter($params['mods'] ?? []));
$baseParams = ScoreSearchParams::fromArray([
'beatmap_ids' => [$beatmap->getKey()],
'is_legacy' => ScoreSearchParams::showLegacyForUser(\Auth::user()),
'limit' => 1,
'mods' => $mods,
'ruleset_id' => $rulesetId,
'sort' => 'score_desc',
'user_id' => (int) $userId,
]);
$score = (new ScoreSearch($baseParams))->records()->first();
abort_if($score === null, 404);
$rankParams = clone $baseParams;
$rankParams->beforeScore = $score;
$rankParams->userId = null;
$rank = UserRank::getRank($rankParams);
return [
'position' => $rank,
'score' => json_item(
$score,
new ScoreTransformer(),
['beatmap', ...static::DEFAULT_SCORE_INCLUDES]
),
];
}
/**
* Get a User Beatmap scores
*
* Return a [User](#user)'s scores on a Beatmap
*
* ---
*
* ### Response Format
*
* Field | Type
* ------ | ----
* scores | [Score](#score)[]
*
* @urlParam beatmap integer required Id of the [Beatmap](#beatmap).
* @urlParam user integer required Id of the [User](#user).
*
* @queryParam legacy_only integer Whether or not to exclude lazer scores. Defaults to 0. Example: 0
* @queryParam mode The [Ruleset](#ruleset) to get scores for. Defaults to beatmap mode
*/
public function userScoreAll($beatmapId, $userId)
{
$beatmap = Beatmap::scoreable()->findOrFail($beatmapId);
$mode = presence(get_string(request('mode'))) ?? $beatmap->mode;
$params = ScoreSearchParams::fromArray([
'beatmap_ids' => [$beatmap->getKey()],
'is_legacy' => ScoreSearchParams::showLegacyForUser(\Auth::user()),
'ruleset_id' => Beatmap::MODES[$mode],
'sort' => 'score_desc',
'user_id' => (int) $userId,
]);
$scores = (new ScoreSearch($params))->records();
return [
'scores' => json_collection($scores, new ScoreTransformer()),
];
}
}