Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Show custom user tags on beatmapset #11750

Merged
merged 27 commits into from
Jan 14, 2025
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
545c945
render user tags
notbakaneko Dec 10, 2024
4ae47f9
cache tags locally, only cache beatmap tags with ids and counts; retu…
notbakaneko Dec 12, 2024
4a55d98
return tags with counts with beatmaps
notbakaneko Dec 13, 2024
b3fcdfa
add TagJsonWithCount type
notbakaneko Dec 13, 2024
d883075
merge user and mapper tags, place mapper tags at the end
notbakaneko Dec 13, 2024
3c9a6f5
do the sorting in controller
notbakaneko Dec 13, 2024
1503ceb
lint
notbakaneko Dec 17, 2024
f5552af
return id and counts seperately from full tag
notbakaneko Dec 17, 2024
5ad134a
remove route (get from beatmapset instead)
notbakaneko Dec 17, 2024
3c9c2e5
not nullable
notbakaneko Dec 17, 2024
9e01f3d
don't need the extra join/relation anymore; make into query
notbakaneko Dec 18, 2024
715db03
copy and return typed value instead of messing with original object
notbakaneko Dec 18, 2024
dd68826
don't double fetch from redis for transformer
notbakaneko Dec 18, 2024
2b3bb42
should be unique
notbakaneko Dec 19, 2024
05db2c1
removed/unused
notbakaneko Dec 19, 2024
0eefd0b
missing non-incrementing
notbakaneko Dec 19, 2024
c9ad28d
memoize all
notbakaneko Dec 19, 2024
421504c
add composite key test; add missing timestamp properties
notbakaneko Dec 20, 2024
efad0be
tie break with names
notbakaneko Dec 20, 2024
cde18d0
don't dedupe mapper tags since they might be names
notbakaneko Dec 20, 2024
572b046
show user tags per beatmap
notbakaneko Dec 24, 2024
73162ed
already a copy
notbakaneko Jan 14, 2025
585fa90
tags not being deduped anymore
notbakaneko Jan 14, 2025
efd6470
fix property ordering
notbakaneko Jan 14, 2025
be47400
only used in one place now...
notbakaneko Jan 14, 2025
3dee3fc
can be a scope?
notbakaneko Jan 14, 2025
bdffa17
Merge branch 'master' into feature/beatmapset-show-user-tags
nanaya Jan 14, 2025
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
16 changes: 0 additions & 16 deletions app/Http/Controllers/BeatmapTagsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,6 @@ public function __construct()
'destroy',
],
]);

$this->middleware('require-scopes:public', ['only' => 'index']);
}

public function index($beatmapId)
{
$topBeatmapTags = cache_remember_mutexed(
"beatmap_tags:{$beatmapId}",
$GLOBALS['cfg']['osu']['tags']['beatmap_tags_cache_duration'],
[],
fn () => Tag::topTags($beatmapId),
);

return [
'beatmap_tags' => $topBeatmapTags,
];
}

public function destroy($beatmapId, $tagId)
Expand Down
2 changes: 2 additions & 0 deletions app/Http/Controllers/BeatmapsetsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,7 @@ private function showJson($beatmapset)
'beatmaps.failtimes',
'beatmaps.max_combo',
'beatmaps.owners',
'beatmaps.top_tag_ids',
'converts',
'converts.failtimes',
'converts.owners',
Expand All @@ -415,6 +416,7 @@ private function showJson($beatmapset)
'pack_tags',
'ratings',
'recent_favourites',
'related_tags',
'related_users',
'user',
]);
Expand Down
12 changes: 1 addition & 11 deletions app/Http/Controllers/TagsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,6 @@

namespace App\Http\Controllers;

use App\Models\Tag;
use App\Transformers\TagTransformer;

class TagsController extends Controller
{
public function __construct()
Expand All @@ -21,15 +18,8 @@ public function __construct()

public function index()
{
$tags = cache_remember_mutexed(
'tags',
$GLOBALS['cfg']['osu']['tags']['tags_cache_duration'],
[],
fn () => Tag::all(),
);

return [
'tags' => json_collection($tags, new TagTransformer()),
'tags' => app('tags')->json(),
];
}
}
17 changes: 16 additions & 1 deletion app/Models/Beatmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use App\Exceptions\InvariantException;
use App\Jobs\EsDocument;
use App\Libraries\Transactions\AfterCommit;
use App\Traits\Memoizes;
use DB;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
Expand Down Expand Up @@ -53,7 +54,7 @@
*/
class Beatmap extends Model implements AfterCommit
{
use SoftDeletes;
use Memoizes, SoftDeletes;

public $convert = false;

Expand Down Expand Up @@ -348,6 +349,20 @@ public function status()
return array_search($this->approved, Beatmapset::STATES, true);
}

public function topTagIds()
{
// TODO: Add option to multi query when beatmapset requests all tags for beatmaps?
return $this->memoize(
__FUNCTION__,
fn () => cache_remember_mutexed(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mutexed seems not very useful when it's just db access? Like, nothing would work if the db is unhealthy.

"beatmap_top_tag_ids:{$this->getKey()}",
$GLOBALS['cfg']['osu']['tags']['beatmap_tags_cache_duration'],
[],
fn () => BeatmapTag::topTagIdsQuery($this->getKey())->get()->toArray(),
),
);
}

private function getDifficultyrating()
{
if ($this->convert) {
Expand Down
15 changes: 15 additions & 0 deletions app/Models/BeatmapTag.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,29 @@
/**
* @property-read Beatmap $beatmap
* @property int $beatmap_id
* @property \Carbon\Carbon $created_at
* @property int $tag_id
* @property \Carbon\Carbon $updated_at
* @property-read User $user
* @property int $user_id
*/
class BeatmapTag extends Model
{
protected $primaryKey = ':composite';
notbakaneko marked this conversation as resolved.
Show resolved Hide resolved
protected $primaryKeys = ['beatmap_id', 'tag_id', 'user_id'];
public $incrementing = false;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

position public before protected?


public static function topTagIdsQuery(int $beatmapId, int $limit = 50)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is it not a scope

{
return static::where('beatmap_id', $beatmapId)
->whereHas('user', fn ($userQuery) => $userQuery->default())
->groupBy('tag_id')
->select('tag_id')
->selectRaw('COUNT(*) as count')
->orderBy('count', 'desc')
->orderBy('tag_id', 'asc')
->limit($limit);
}

public function beatmap()
{
Expand Down
16 changes: 0 additions & 16 deletions app/Models/Tag.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,4 @@ public function beatmapTags(): HasMany
{
return $this->hasMany(BeatmapTag::class);
}

public static function topTags($beatmapId)
{
return static
::joinRelation(
'beatmapTags',
fn ($q) => $q->where('beatmap_id', $beatmapId)->whereHas('user', fn ($userQuery) => $userQuery->default())
)
->groupBy('id')
->select('id', 'name')
->selectRaw('COUNT(*) as count')
->orderBy('count', 'desc')
->orderBy('id', 'desc')
->limit(50)
->get();
}
}
1 change: 1 addition & 0 deletions app/Providers/AppServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class AppServiceProvider extends ServiceProvider
'layout-cache' => Singletons\LayoutCache::class,
'medals' => Singletons\Medals::class,
'smilies' => Singletons\Smilies::class,
'tags' => Singletons\Tags::class,
'user-cover-presets' => Singletons\UserCoverPresets::class,
];

Expand Down
44 changes: 44 additions & 0 deletions app/Singletons/Tags.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

declare(strict_types=1);

namespace App\Singletons;

use App\Models\Tag;
use App\Traits\Memoizes;
use App\Transformers\TagTransformer;
use Illuminate\Support\Collection;

class Tags
{
use Memoizes;

/**
* @return Collection<Tag>
*/
public function all(): Collection
{
return $this->memoize(__FUNCTION__, fn () => Tag::all());
}

public function get(int $id): ?Tag
{
$allById = $this->memoize(
'allById',
fn () => $this->all()->keyBy('id'),
);

return $allById[$id] ?? null;
}

public function json(): array
{
return $this->memoize(
__FUNCTION__,
fn () => json_collection($this->all(), new TagTransformer()),
);
}
}
6 changes: 6 additions & 0 deletions app/Transformers/BeatmapCompactTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class BeatmapCompactTransformer extends TransformerAbstract
'failtimes',
'max_combo',
'owners',
'top_tag_ids',
'user',
];

Expand Down Expand Up @@ -83,6 +84,11 @@ public function includeOwners(Beatmap $beatmap)
]);
}

public function includeTopTagIds(Beatmap $beatmap)
{
return $this->primitive($beatmap->topTagIds());
}

public function includeUser(Beatmap $beatmap)
{
return $this->item(
Expand Down
19 changes: 19 additions & 0 deletions app/Transformers/BeatmapsetCompactTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class BeatmapsetCompactTransformer extends TransformerAbstract
'ratings',
'recent_favourites',
'related_users',
'related_tags',
'user',
];

Expand Down Expand Up @@ -299,6 +300,24 @@ public function includeRelatedUsers(Beatmapset $beatmapset)
return $this->collection($users, new UserCompactTransformer());
}

public function includeRelatedTags(Beatmapset $beatmapset)
{
$beatmaps = $this->beatmaps($beatmapset);
$tagIdSet = new Set($beatmaps->flatMap->topTagIds()->pluck('tag_id'));

$cachedTags = app('tags');
$json = [];

foreach ($tagIdSet as $tagId) {
$tag = $cachedTags->get($tagId);
if ($tag !== null) {
$json[] = $tag;
}
}

return $this->primitive($json);
}

private function beatmaps(Beatmapset $beatmapset, ?Fractal\ParamBag $params = null): EloquentCollection
{
$rel = $beatmapset->trashed() || ($params !== null && $params->get('with_trashed')) ? 'allBeatmaps' : 'beatmaps';
Expand Down
2 changes: 1 addition & 1 deletion database/factories/TagFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class TagFactory extends Factory
public function definition(): array
{
return [
'name' => fn () => "Tag {$this->faker->word}",
'name' => fn () => "Tag {$this->faker->unique()->word}",
'description' => fn () => $this->faker->sentence,
];
}
Expand Down
47 changes: 47 additions & 0 deletions resources/js/beatmapsets-show/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// See the LICENCE file in the repository root for full licence text.

import { BeatmapsetJsonForShow } from 'interfaces/beatmapset-extended-json';
import TagJson from 'interfaces/tag-json';
import UserJson from 'interfaces/user-json';
import { keyBy } from 'lodash';
import { action, computed, makeObservable, observable, runInAction } from 'mobx';
Expand All @@ -10,6 +11,7 @@ import core from 'osu-core-singleton';
import { find, findDefault, group } from 'utils/beatmap-helper';
import { parse } from 'utils/beatmapset-page-hash';
import { parseJson } from 'utils/json';
import { present } from 'utils/string';
import { currentUrl } from 'utils/turbolinks';

export type ScoreLoadingState = null | 'error' | 'loading' | 'supporter_only' | 'unranked';
Expand All @@ -23,6 +25,16 @@ interface State {
showingNsfwWarning: boolean;
}

type TagJsonWithCount = TagJson & { count: number };

function asTagJsonWithCount(tag: TagJson) {
return {
count: 0,
...tag,
};
}


export default class Controller {
@observable hoveredBeatmap: null | BeatmapJsonForBeatmapsetShow = null;
@observable state: State;
Expand Down Expand Up @@ -70,6 +82,41 @@ export default class Controller {
return this.beatmaps.get(this.currentBeatmap.mode) ?? [];
}

@computed
get relatedTags() {
notbakaneko marked this conversation as resolved.
Show resolved Hide resolved
const map = new Map<number, TagJson>();

for (const tag of this.beatmapset.related_tags) {
map.set(tag.id, tag);
}

return map;
}

@computed
get tags() {
const userTags: TagJsonWithCount[] = [];

if (this.currentBeatmap.top_tag_ids != null) {
for (const tagId of this.currentBeatmap.top_tag_ids) {
const maybeTag = this.relatedTags.get(tagId.tag_id);
if (maybeTag == null) continue;

const tag = asTagJsonWithCount(maybeTag);
tag.count = tagId.count;
userTags.push(asTagJsonWithCount(tag));
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can just push { ...maybeTag, count: tagId.count }

(also why is it converting the thing twice)

}
}

return {
mapperTags: this.beatmapset.tags.split(' ').filter(present),
userTags: userTags.sort((a, b) => {
const diff = b.count - a.count;
return diff !== 0 ? diff : a.name.localeCompare(b.name);
}),
};
}

@computed
get usersById() {
return keyBy(this.beatmapset.related_users, 'id') as Partial<Record<number, UserJson>>;
Expand Down
19 changes: 12 additions & 7 deletions resources/js/beatmapsets-show/info.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ export default class Info extends React.Component<Props> {
return ret;
}

private get tags() {
const tags = this.controller.tags;

return [
...tags.userTags.map((tag) => tag.name),
...tags.mapperTags,
];
}

private get withEditDescription() {
return this.controller.beatmapset.description.bbcode != null;
}
Expand All @@ -84,10 +93,6 @@ export default class Info extends React.Component<Props> {
}

render() {
const tags = this.controller.beatmapset.tags
.split(' ')
.filter(present);

return (
<div className='beatmapset-info u-fancy-scrollbar'>
{this.isEditingDescription &&
Expand Down Expand Up @@ -191,14 +196,14 @@ export default class Info extends React.Component<Props> {
</div>
</div>

{tags.length > 0 &&
{this.tags.length > 0 &&
<div className='beatmapset-info__row beatmapset-info__row--value-overflow'>
<h3 className='beatmapset-info__header'>
{trans('beatmapsets.show.info.tags')}
</h3>
<div className='beatmapset-info__value-overflow'>
{tags.map((tag, i) => (
<React.Fragment key={`${tag}-${i}`}>
{this.tags.map((tag) => (
<React.Fragment key={`${tag}`}>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the -${i} is required to avoid duplicate keys (mainly for mapper tags but also now in conjunction with user tags)

<a
className='beatmapset-info__link'
href={route('beatmapsets.index', { q: tag })}
Expand Down
1 change: 1 addition & 0 deletions resources/js/interfaces/beatmap-json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ interface BeatmapJsonAvailableIncludes {
failtimes: BeatmapFailTimesArray;
max_combo: number;
owners: BeatmapOwnerJson[];
top_tag_ids: { count: number; tag_id: number }[];
user: UserJson;
}

Expand Down
Loading
Loading