feat: top genres report

This commit is contained in:
Julian Tölle 2021-10-26 20:09:52 +02:00
parent 62119d44b0
commit a0c28e2324
21 changed files with 317 additions and 104 deletions

View file

@ -8,6 +8,7 @@ import { RecentListens } from "./components/RecentListens";
import { ReportListens } from "./components/ReportListens";
import { ReportTopAlbums } from "./components/ReportTopAlbums";
import { ReportTopArtists } from "./components/ReportTopArtists";
import { ReportTopGenres } from "./components/ReportTopGenres";
import { ReportTopTracks } from "./components/ReportTopTracks";
import { useAuth } from "./hooks/use-auth";
import "./tailwind/generated.css";
@ -38,6 +39,7 @@ export function App() {
/>
<Route path="/reports/top-albums" exact component={ReportTopAlbums} />
<Route path="/reports/top-tracks" exact component={ReportTopTracks} />
<Route path="/reports/top-genres" exact component={ReportTopGenres} />
</Switch>
</main>
<footer>

View file

@ -9,6 +9,8 @@ import { TopAlbumsItem } from "./entities/top-albums-item";
import { TopAlbumsOptions } from "./entities/top-albums-options";
import { TopArtistsItem } from "./entities/top-artists-item";
import { TopArtistsOptions } from "./entities/top-artists-options";
import { TopGenresItem } from "./entities/top-genres-item";
import { TopGenresOptions } from "./entities/top-genres-options";
import { TopTracksItem } from "./entities/top-tracks-item";
import { TopTracksOptions } from "./entities/top-tracks-options";
@ -188,3 +190,40 @@ export const getTopTracks = async (
} = res;
return items;
};
export const getTopGenres = async (
options: TopGenresOptions,
client: AxiosInstance
): Promise<TopGenresItem[]> => {
const {
time: { timePreset, customTimeStart, customTimeEnd },
} = options;
const res = await client.get<{ items: TopGenresItem[] }>(
`/api/v1/reports/top-Genres`,
{
params: {
timePreset,
customTimeStart: formatISO(customTimeStart),
customTimeEnd: formatISO(customTimeEnd),
},
}
);
switch (res.status) {
case 200: {
break;
}
case 401: {
throw new UnauthenticatedError(`No token or token expired`);
}
default: {
throw new Error(`Unable to getTopGenres: ${res.status}`);
}
}
const {
data: { items },
} = res;
return items;
};

View file

@ -0,0 +1,4 @@
export interface Genre {
id: string;
name: string;
}

View file

@ -0,0 +1,8 @@
import { Genre } from "./genre";
import { TopArtistsItem } from "./top-artists-item";
export interface TopGenresItem {
genre: Genre;
artists: TopArtistsItem[];
count: number;
}

View file

@ -0,0 +1,5 @@
import { TimeOptions } from "./time-options";
export interface TopGenresOptions {
time: TimeOptions;
}

View file

@ -34,6 +34,9 @@ export const NavBar: React.FC = () => {
<Link to="/reports/top-tracks">
<NavItem>Top Tracks</NavItem>
</Link>
<Link to="/reports/top-genres">
<NavItem>Top Genres</NavItem>
</Link>
</>
)}
</div>

View file

@ -0,0 +1,106 @@
import React, { useMemo, useState } from "react";
import { Redirect } from "react-router-dom";
import { Artist } from "../api/entities/artist";
import { Genre } from "../api/entities/genre";
import { TimeOptions } from "../api/entities/time-options";
import { TimePreset } from "../api/entities/time-preset.enum";
import { TopArtistsItem } from "../api/entities/top-artists-item";
import { useTopGenres } from "../hooks/use-api";
import { useAuth } from "../hooks/use-auth";
import { capitalizeString } from "../util/capitalizeString";
import { getMaxCount } from "../util/getMaxCount";
import { ReportTimeOptions } from "./ReportTimeOptions";
import { TopListItem } from "./TopListItem";
export const ReportTopGenres: React.FC = () => {
const { user } = useAuth();
const [timeOptions, setTimeOptions] = useState<TimeOptions>({
timePreset: TimePreset.LAST_90_DAYS,
customTimeStart: new Date(0),
customTimeEnd: new Date(),
});
const options = useMemo(
() => ({
time: timeOptions,
}),
[timeOptions]
);
const { topGenres, isLoading } = useTopGenres(options);
const reportHasItems = !isLoading && topGenres.length !== 0;
if (!user) {
return <Redirect to="/" />;
}
const maxCount = getMaxCount(topGenres);
return (
<div className="md:flex md:justify-center p-4">
<div className="md:flex-shrink-0 min-w-full xl:min-w-0 xl:w-2/3 max-w-screen-lg">
<div className="flex justify-between">
<p className="text-2xl font-normal text-gray-700">Top Genres</p>
</div>
<div className="shadow-xl bg-gray-100 rounded p-5 m-2">
<ReportTimeOptions
timeOptions={timeOptions}
setTimeOptions={setTimeOptions}
/>
{isLoading && (
<div>
<div className="loader rounded-full border-8 h-64 w-64"></div>
</div>
)}
{!reportHasItems && (
<div>
<p>Report is emtpy! :(</p>
</div>
)}
{reportHasItems &&
topGenres.map(({ genre, artists, count }) => (
<ReportItem
genre={genre}
count={count}
artists={artists}
maxCount={maxCount}
/>
))}
</div>
</div>
</div>
);
};
const ReportItem: React.FC<{
genre: Genre;
artists: TopArtistsItem[];
count: number;
maxCount: number;
}> = ({ genre, artists, count, maxCount }) => {
const artistList = artists
.map(({ artist, count: artistCount }) => (
<ArtistItem artist={artist} count={artistCount} />
))
// @ts-expect-error
.reduce((acc, curr) => (acc === null ? [curr] : [acc, ", ", curr]), null);
return (
<TopListItem
key={genre.id}
title={capitalizeString(genre.name)}
subTitle={artistList}
count={count}
maxCount={maxCount}
/>
);
};
const ArtistItem: React.FC<{
artist: Artist;
count: number;
}> = ({ artist, count }) => (
<span title={`Listens: ${count}`}>{artist.name}</span>
);

View file

@ -3,7 +3,7 @@ import React from "react";
export interface TopListItemProps {
key: string;
title: string;
subTitle?: string;
subTitle?: string | React.ReactNode;
count: number;
/**

View file

@ -4,12 +4,14 @@ import {
getRecentListens,
getTopAlbums,
getTopArtists,
getTopGenres,
getTopTracks,
} from "../api/api";
import { ListenReportOptions } from "../api/entities/listen-report-options";
import { PaginationOptions } from "../api/entities/pagination-options";
import { TopAlbumsOptions } from "../api/entities/top-albums-options";
import { TopArtistsOptions } from "../api/entities/top-artists-options";
import { TopGenresOptions } from "../api/entities/top-genres-options";
import { TopTracksOptions } from "../api/entities/top-tracks-options";
import { useApiClient } from "./use-api-client";
import { useAsync } from "./use-async";
@ -105,3 +107,20 @@ export const useTopTracks = (options: TopTracksOptions) => {
return { topTracks, isLoading, error };
};
export const useTopGenres = (options: TopGenresOptions) => {
const { client } = useApiClient();
const fetchData = useMemo(
() => () => getTopGenres(options, client),
[options, client]
);
const {
value: topGenres,
pending: isLoading,
error,
} = useAsync(fetchData, INITIAL_EMPTY_ARRAY);
return { topGenres, isLoading, error };
};

View file

@ -0,0 +1,8 @@
export const capitalizeString = (str: string): string => {
const arr = str.split(" ");
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}
return arr.join(" ");
};

View file

@ -79,53 +79,9 @@ export class CreateGenreTables0000000000005 implements MigrationInterface {
}),
true
);
await queryRunner.createTable(
new Table({
name: "artist_genres",
columns: [
{
name: "artistId",
type: "uuid",
isPrimary: true,
},
{
name: "genreId",
type: "uuid",
isPrimary: true,
},
],
indices: [
new TableIndex({
name: "IDX_ARTIST_GENRES_ARTIST_ID",
columnNames: ["artistId"],
}),
new TableIndex({
name: "IDX_ARTIST_GENRES_GENRE_ID",
columnNames: ["genreId"],
}),
],
foreignKeys: [
new TableForeignKey({
name: "FK_ARTIST_ID",
columnNames: ["artistId"],
referencedColumnNames: ["id"],
referencedTableName: "artist",
}),
new TableForeignKey({
name: "FK_GENRE_ID",
columnNames: ["genreId"],
referencedColumnNames: ["id"],
referencedTableName: "genre",
}),
],
}),
true
);
}
async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.dropTable("album_genres");
await queryRunner.dropTable("artist_genres");
await queryRunner.dropTable("genre");
}

View file

@ -8,7 +8,6 @@ import {
} from "typeorm";
import { SpotifyLibraryDetails } from "../sources/spotify/spotify-library-details.entity";
import { Artist } from "./artist.entity";
import { Genre } from "./genre.entity";
import { Track } from "./track.entity";
@Entity()
@ -26,9 +25,6 @@ export class Album {
@OneToMany(() => Track, (track) => track.album)
tracks?: Track[];
@ManyToMany(() => Genre)
genres?: Genre[];
@Column(() => SpotifyLibraryDetails)
spotify: SpotifyLibraryDetails;
}

View file

@ -1,4 +1,10 @@
import { Column, Entity, ManyToMany, PrimaryGeneratedColumn } from "typeorm";
import {
Column,
Entity,
JoinTable,
ManyToMany,
PrimaryGeneratedColumn,
} from "typeorm";
import { SpotifyLibraryDetails } from "../sources/spotify/spotify-library-details.entity";
import { Album } from "./album.entity";
import { Genre } from "./genre.entity";
@ -15,6 +21,7 @@ export class Artist {
albums?: Album[];
@ManyToMany(() => Genre)
@JoinTable({ name: "artist_genres" })
genres?: Genre[];
@Column(() => SpotifyLibraryDetails)

View file

@ -1,10 +1,8 @@
import { SpotifyLibraryDetails } from "../../sources/spotify/spotify-library-details.entity";
import { Artist } from "../artist.entity";
import { Genre } from "../genre.entity";
export class CreateAlbumDto {
name: string;
artists: Artist[];
genres: Genre[];
spotify?: SpotifyLibraryDetails;
}

View file

@ -36,6 +36,7 @@ export class MusicLibraryService {
const artist = this.artistRepository.create();
artist.name = data.name;
artist.genres = data.genres;
artist.spotify = data.spotify;
try {

View file

@ -0,0 +1,10 @@
import { ValidateNested } from "class-validator";
import { User } from "../../users/user.entity";
import { ReportTimeDto } from "./report-time.dto";
export class GetTopGenresReportDto {
user: User;
@ValidateNested()
time: ReportTimeDto;
}

View file

@ -0,0 +1,10 @@
import { Genre } from "../../music-library/genre.entity";
import { TopArtistsReportDto } from "./top-artists-report.dto";
export class TopGenresReportDto {
items: {
genre: Genre;
artists: TopArtistsReportDto["items"];
count: number;
}[];
}

View file

@ -6,6 +6,7 @@ import { ListenReportDto } from "./dto/listen-report.dto";
import { ReportTimeDto } from "./dto/report-time.dto";
import { TopAlbumsReportDto } from "./dto/top-albums-report.dto";
import { TopArtistsReportDto } from "./dto/top-artists-report.dto";
import { TopGenresReportDto } from "./dto/top-genres-report.dto";
import { TopTracksReportDto } from "./dto/top-tracks-report.dto";
import { ReportsService } from "./reports.service";
import { Timeframe } from "./timeframe.enum";
@ -50,4 +51,13 @@ export class ReportsController {
): Promise<TopTracksReportDto> {
return this.reportsService.getTopTracks({ user, time });
}
@Get("top-genres")
@AuthAccessToken()
async getTopGenres(
@Query() time: ReportTimeDto,
@ReqUser() user: User
): Promise<TopGenresReportDto> {
return this.reportsService.getTopGenres({ user, time });
}
}

View file

@ -15,13 +15,17 @@ import {
sub,
} from "date-fns";
import { ListensService } from "../listens/listens.service";
import { User } from "../users/user.entity";
import { GetListenReportDto } from "./dto/get-listen-report.dto";
import { GetTopAlbumsReportDto } from "./dto/get-top-albums-report.dto";
import { GetTopArtistsReportDto } from "./dto/get-top-artists-report.dto";
import { GetTopGenresReportDto } from "./dto/get-top-genres-report.dto";
import { GetTopTracksReportDto } from "./dto/get-top-tracks-report.dto";
import { ListenReportDto } from "./dto/listen-report.dto";
import { ReportTimeDto } from "./dto/report-time.dto";
import { TopAlbumsReportDto } from "./dto/top-albums-report.dto";
import { TopArtistsReportDto } from "./dto/top-artists-report.dto";
import { TopGenresReportDto as TopGenresReportDto } from "./dto/top-genres-report.dto";
import { TopTracksReportDto } from "./dto/top-tracks-report.dto";
import { Interval } from "./interval";
import { Timeframe } from "./timeframe.enum";
@ -66,16 +70,11 @@ export class ReportsService {
constructor(private readonly listensService: ListensService) {}
async getListens(options: GetListenReportDto): Promise<ListenReportDto> {
const { user, timeFrame, time: timePreset } = options;
const { timeFrame, time: timePreset } = options;
const listens = await this.getListensQueryFromOptions(options).getMany();
const interval = this.getIntervalFromPreset(timePreset);
const listens = await this.listensService
.getScopedQueryBuilder()
.byUser(user)
.duringInterval(interval)
.getMany();
const { eachOfInterval, isSame } = timeframeToDateFns[timeFrame];
const reportItems = eachOfInterval(interval).map((date) => {
@ -91,14 +90,7 @@ export class ReportsService {
async getTopArtists(
options: GetTopArtistsReportDto
): Promise<TopArtistsReportDto> {
const { user, time: timePreset } = options;
const interval = this.getIntervalFromPreset(timePreset);
const getArtistsWithCountQB = this.listensService
.getScopedQueryBuilder()
.byUser(user)
.duringInterval(interval)
const getArtistsWithCountQB = this.getListensQueryFromOptions(options)
.leftJoin("listen.track", "track")
.leftJoinAndSelect("track.artists", "artists")
.groupBy("artists.id")
@ -132,18 +124,8 @@ export class ReportsService {
async getTopAlbums(
options: GetTopAlbumsReportDto
): Promise<TopAlbumsReportDto> {
const { user, time: timePreset } = options;
const interval = this.getIntervalFromPreset(timePreset);
const getListensQB = () =>
this.listensService
.getScopedQueryBuilder()
.byUser(user)
.duringInterval(interval);
const [rawAlbumsWithCount, rawAlbumDetails] = await Promise.all([
getListensQB()
this.getListensQueryFromOptions(options)
.leftJoin("listen.track", "track")
.leftJoinAndSelect("track.album", "album")
.groupBy("album.id")
@ -154,7 +136,7 @@ export class ReportsService {
// Because of the GROUP BY required to calculate the count we can
// not properly join the album relations in one query
getListensQB()
this.getListensQueryFromOptions(options)
.leftJoinAndSelect("listen.track", "track")
.leftJoinAndSelect("track.album", "album")
.leftJoinAndSelect("album.artists", "artists")
@ -181,18 +163,8 @@ export class ReportsService {
async getTopTracks(
options: GetTopTracksReportDto
): Promise<TopTracksReportDto> {
const { user, time: timePreset } = options;
const interval = this.getIntervalFromPreset(timePreset);
const getListensQB = () =>
this.listensService
.getScopedQueryBuilder()
.byUser(user)
.duringInterval(interval);
const [rawTracksWithCount, rawTrackDetails] = await Promise.all([
getListensQB()
this.getListensQueryFromOptions(options)
.leftJoin("listen.track", "track")
.groupBy("track.id")
.select("track.*")
@ -202,7 +174,7 @@ export class ReportsService {
// Because of the GROUP BY required to calculate the count we can
// not properly join the artist relations in one query
getListensQB()
this.getListensQueryFromOptions(options)
.leftJoinAndSelect("listen.track", "track")
.leftJoinAndSelect("track.artists", "artists")
.distinctOn(["track.id"])
@ -225,6 +197,77 @@ export class ReportsService {
};
}
async getTopGenres(
options: GetTopGenresReportDto
): Promise<TopGenresReportDto> {
const [rawGenresWithCount, rawGenresWithArtistsCount] = await Promise.all([
this.getListensQueryFromOptions(options)
.leftJoin("listen.track", "track")
.leftJoin("track.artists", "artists")
.leftJoin("artists.genres", "genres")
.groupBy("genres.id")
.select("genres.*")
.addSelect("count(*) as listens")
.orderBy("listens", "DESC")
.getRawMany(),
this.getListensQueryFromOptions(options)
.leftJoin("listen.track", "track")
.leftJoin("track.artists", "artists")
.leftJoin("artists.genres", "genres")
.groupBy("genres.id")
.addGroupBy("artists.id")
.select("genres.id", "genreID")
.addSelect("artists.*")
.addSelect("count(*) as listens")
.orderBy("listens", "DESC")
.getRawMany(),
]);
const items: TopGenresReportDto["items"] = rawGenresWithCount
.filter((rawGenre) => rawGenre.id) // Make sure that listen has related genre
.map((data) => ({
count: Number.parseInt(data.listens, 10),
genre: {
id: data.id,
name: data.name,
},
artists: rawGenresWithArtistsCount
.filter(({ genreID }) => genreID === data.id)
.map((artistsData) => ({
count: Number.parseInt(artistsData.listens, 10),
artist: {
id: artistsData.id,
name: artistsData.name,
spotify: {
id: artistsData.spotifyId,
uri: artistsData.spotifyUri,
type: artistsData.spotifyType,
href: artistsData.spotifyHref,
},
},
}))
.filter((_, i) => i < 5),
}));
return {
items,
};
}
private getListensQueryFromOptions(options: {
user: User;
time: ReportTimeDto;
}) {
const { user, time: timePreset } = options;
const interval = this.getIntervalFromPreset(timePreset);
return this.listensService
.getScopedQueryBuilder()
.byUser(user)
.duringInterval(interval);
}
private getIntervalFromPreset(options: {
timePreset: TimePreset;
customTimeStart?: string;

View file

@ -5,13 +5,6 @@ import { SimplifiedArtistObject } from "./simplified-artist-object";
// tslint:disable: variable-name
export class AlbumObject {
/**
* A list of the genres used to classify the album.
* For example: "Prog Rock" , "Post-Grunge".
* (If not yet classified, the array is empty.)
*/
genres: string[];
/**
* The artists of the album.
* Each artist object includes a link in href to more detailed information about the artist.

View file

@ -210,14 +210,9 @@ export class SpotifyService {
)
);
const genres = await Promise.all(
spotifyAlbum.genres.map((genreName) => this.importGenre(genreName))
);
return this.musicLibraryService.createAlbum({
name: spotifyAlbum.name,
artists,
genres,
spotify: {
id: spotifyAlbum.id,
uri: spotifyAlbum.uri,