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

feat: implement search page #39

Merged
merged 8 commits into from
Sep 28, 2023
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
25 changes: 24 additions & 1 deletion apps/main/src/library/library.resolver.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,30 @@ import { Test, TestingModule } from "@nestjs/testing";

import { LibraryResolver } from "@library/library.resolver";
import { LibraryScannerService } from "@library/library.scanner.service";
import { LibraryService } from "@library/library.service";

describe("LibraryResolver", () => {
let resolver: LibraryResolver;
let libraryScannerService: Record<string, jest.Mock>;
let libraryService: Record<string, jest.Mock>;

beforeEach(async () => {
libraryScannerService = {
scanLibrary: jest.fn(),
subscribeToLibraryScanningStateChanged: jest.fn(),
};

libraryService = {
getSearchSuggestions: jest.fn(),
search: jest.fn(),
};

const module: TestingModule = await Test.createTestingModule({
providers: [LibraryResolver, { provide: LibraryScannerService, useValue: libraryScannerService }],
providers: [
LibraryResolver,
{ provide: LibraryScannerService, useValue: libraryScannerService },
{ provide: LibraryService, useValue: libraryService },
],
}).compile();

resolver = module.get<LibraryResolver>(LibraryResolver);
Expand All @@ -35,4 +46,16 @@ describe("LibraryResolver", () => {

expect(libraryScannerService.subscribeToLibraryScanningStateChanged).toHaveBeenCalled();
});

it("should be able to get search suggestions", async () => {
await resolver.searchSuggestions();

expect(libraryService.getSearchSuggestions).toHaveBeenCalled();
});

it("should be able to search library", async () => {
await resolver.search("test");

expect(libraryService.search).toHaveBeenCalledWith("test");
});
});
21 changes: 19 additions & 2 deletions apps/main/src/library/library.resolver.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@
import { Inject } from "@nestjs/common";
import { Mutation, Resolver, Subscription } from "@nestjs/graphql";
import { Args, Mutation, Query, Resolver, Subscription } from "@nestjs/graphql";

import { LibraryScannerService } from "@library/library.scanner.service";
import { LibraryService } from "@library/library.service";

import { SearchSuggestion } from "@library/models/search-suggestion.model";
import { SearchResult } from "@library/models/search-result.model";

@Resolver()
export class LibraryResolver {
public constructor(@Inject(LibraryScannerService) private readonly libraryScannerService: LibraryScannerService) {}
public constructor(
@Inject(LibraryScannerService) private readonly libraryScannerService: LibraryScannerService,
@Inject(LibraryService) private readonly libraryService: LibraryService,
) {}

@Query(() => SearchResult)
public async search(@Args("query", { type: () => String }) query: string): Promise<SearchResult> {
return this.libraryService.search(query);
}

@Query(() => [SearchSuggestion])
public async searchSuggestions(): Promise<SearchSuggestion[]> {
return this.libraryService.getSearchSuggestions();
}

@Mutation(() => Boolean)
public async scanLibrary(): Promise<boolean> {
Expand Down
45 changes: 44 additions & 1 deletion apps/main/src/library/library.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,34 @@
import { Test, TestingModule } from "@nestjs/testing";

import { LibraryService } from "@library/library.service";
import { AlbumService } from "@album/album.service";
import { MusicService } from "@music/music.service";
import { ArtistService } from "@artist/artist.service";

describe("LibraryService", () => {
let service: LibraryService;
let musicService: Record<string, jest.Mock>;
let albumService: Record<string, jest.Mock>;
let artistService: Record<string, jest.Mock>;

beforeEach(async () => {
musicService = {
findAll: jest.fn().mockResolvedValue([{ id: 0, title: "title", artistIds: [0], albumId: 0 }]),
};
albumService = {
findAll: jest.fn().mockResolvedValue([{ id: 0, title: "title", musicIds: [0] }]),
};
artistService = {
findAll: jest.fn().mockResolvedValue([{ id: 0, name: "name", albumIds: [0], musicIds: [0] }]),
};

const module: TestingModule = await Test.createTestingModule({
providers: [LibraryService],
providers: [
LibraryService,
{ provide: MusicService, useValue: musicService },
{ provide: AlbumService, useValue: albumService },
{ provide: ArtistService, useValue: artistService },
],
}).compile();

service = module.get<LibraryService>(LibraryService);
Expand All @@ -16,4 +37,26 @@ describe("LibraryService", () => {
it("should be defined", () => {
expect(service).toBeDefined();
});

it("should be able to get search suggestion items", async () => {
await service.getSearchSuggestions();

expect(musicService.findAll).toHaveBeenCalled();
expect(albumService.findAll).toHaveBeenCalled();
expect(artistService.findAll).toHaveBeenCalled();
});

it("should be able to search library", async () => {
const result = await service.search("e");

expect(musicService.findAll).toHaveBeenCalled();
expect(albumService.findAll).toHaveBeenCalled();
expect(artistService.findAll).toHaveBeenCalled();

expect(result).toEqual({
musics: [expect.objectContaining({ id: 0 })],
albums: [expect.objectContaining({ id: 0 })],
artists: [expect.objectContaining({ id: 0 })],
});
});
});
98 changes: 96 additions & 2 deletions apps/main/src/library/library.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,98 @@
import { Injectable } from "@nestjs/common";
import _ from "lodash";

import { Inject, Injectable } from "@nestjs/common";

import { MusicService } from "@music/music.service";
import { ArtistService } from "@artist/artist.service";
import { AlbumService } from "@album/album.service";

import { SearchSuggestion, SearchSuggestionType } from "@library/models/search-suggestion.model";
import { SearchResult } from "@library/models/search-result.model";

@Injectable()
export class LibraryService {}
export class LibraryService {
public constructor(
@Inject(MusicService) private readonly musicService: MusicService,
@Inject(ArtistService) private readonly artistService: ArtistService,
@Inject(AlbumService) private readonly albumService: AlbumService,
) {}

public async getSearchSuggestions(): Promise<SearchSuggestion[]> {
const musics = await this.musicService.findAll();
const artists = await this.artistService.findAll();
const albums = await this.albumService.findAll();

return [
...musics
.map(music => ({ id: music.id, title: music.title, type: SearchSuggestionType.Music }))
.filter((item): item is SearchSuggestion => Boolean(item.title)),
...artists.map(artist => ({ id: artist.id, title: artist.name, type: SearchSuggestionType.Artist })),
...albums.map(album => ({ id: album.id, title: album.title, type: SearchSuggestionType.Album })),
];
}

public async search(query: string) {
const result = new SearchResult();
const musics = await this.musicService.findAll();
const artists = await this.artistService.findAll();
const albums = await this.albumService.findAll();

const musicMap = _.chain(musics).keyBy("id").mapValues().value();
const artistMap = _.chain(artists).keyBy("id").mapValues().value();
const albumMap = _.chain(albums).keyBy("id").mapValues().value();

query = query.toLowerCase();

const matchedMusics = _.chain(musics)
.filter(m => !!m.title?.toLowerCase()?.includes(query))
.value();

const matchedArtists = _.chain(artists)
.filter(a => !!a.name?.toLowerCase()?.includes(query))
.value();

const matchedAlbums = _.chain(albums)
.filter(a => !!a.title?.toLowerCase()?.includes(query))
.value();

for (const album of matchedAlbums) {
matchedMusics.push(
..._.chain(album.musicIds)
.map(id => musicMap[id])
.value(),
);
}

for (const artist of matchedArtists) {
matchedAlbums.push(
..._.chain(artist.albumIds)
.map(id => albumMap[id])
.value(),
);

matchedMusics.push(
..._.chain(artist.musicIds)
.map(id => musicMap[id])
.value(),
);
}

for (const music of matchedMusics) {
matchedArtists.push(
..._.chain(music.artistIds)
.map(id => artistMap[id])
.value(),
);

if (music.albumId) {
matchedAlbums.push(albumMap[music.albumId]);
}
}

result.musics = _.chain(matchedMusics).uniqBy("id").value();
result.artists = _.chain(matchedArtists).uniqBy("id").value();
result.albums = _.chain(matchedAlbums).uniqBy("id").value();

return result;
}
}
17 changes: 17 additions & 0 deletions apps/main/src/library/models/search-result.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Field, ObjectType } from "@nestjs/graphql";

import { Music } from "@music/models/music.model";
import { Artist } from "@artist/models/artist.model";
import { Album } from "@album/models/album.model";

@ObjectType()
export class SearchResult {
@Field(() => [Music])
public musics!: Music[];

@Field(() => [Artist])
public artists!: Artist[];

@Field(() => [Album])
public albums!: Album[];
}
21 changes: 21 additions & 0 deletions apps/main/src/library/models/search-suggestion.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Field, Int, ObjectType, registerEnumType } from "@nestjs/graphql";

export enum SearchSuggestionType {
Music = "Music",
Album = "Album",
Artist = "Artist",
}

registerEnumType(SearchSuggestionType, { name: "SearchSuggestionType" });

@ObjectType()
export class SearchSuggestion {
@Field(() => Int)
public id!: number;

@Field(() => String)
public title!: string;

@Field(() => SearchSuggestionType)
public type!: SearchSuggestionType;
}
2 changes: 1 addition & 1 deletion apps/renderer/src/components/AlbumArtist/List.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export function AlbumArtistList({ items, onPlayItem, type }: AlbumArtistListProp
key={item.id}
item={item}
onPlay={onPlayItem}
onSelectChange={handleSelectChange}
onSelectChange={selection ? handleSelectChange : undefined}
/>
))}
</Root>
Expand Down
7 changes: 7 additions & 0 deletions apps/renderer/src/components/Layout/SideBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import AddRoundedIcon from "@mui/icons-material/AddRounded";
import DeleteIcon from "@mui/icons-material/Delete";
import AlbumRoundedIcon from "@mui/icons-material/AlbumRounded";
import PeopleAltRoundedIcon from "@mui/icons-material/PeopleAltRounded";
import SearchRoundedIcon from "@mui/icons-material/SearchRounded";

import { ScrollbarThumb } from "@components/ScrollbarThumb";
import { Content, Root } from "@components/Layout/SideBar.styles";
Expand All @@ -32,6 +33,12 @@ export function SideBar() {
label: t("pages.home"),
icon: <HomeRoundedIcon />,
},
{
id: "/search",
type: "button",
label: t("pages.search"),
icon: <SearchRoundedIcon />,
},
{
id: "/settings",
type: "button",
Expand Down
2 changes: 2 additions & 0 deletions apps/renderer/src/components/Layout/index.styles.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ export const GlobalStyles = css`
body,
#app {
height: 100vh;

overflow: hidden;
}

@font-face {
Expand Down
24 changes: 24 additions & 0 deletions apps/renderer/src/components/Library/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {
executeDeletePlaylist,
executeDeletePlaylistItems,
executeRenamePlaylist,
querySearch,
querySearchSuggestions,
useAlbumQuery,
useAlbumsQuery,
useArtistQuery,
Expand Down Expand Up @@ -47,6 +49,28 @@ export class Library {
this.dialog = dialog;
}

public async search(query: string) {
const { data, error } = await querySearch(this.client, {
variables: { query },
});

if (error) {
throw error;
} else if (!data) {
throw new Error(this.t("search.errors.undefined-error"));
}

return data.search;
}
public async getSearchSuggestions() {
const { data, error } = await querySearchSuggestions(this.client);
if (error) {
throw error;
}

return data?.searchSuggestions ?? [];
}

public useAlbum(id: number) {
const { data, error } = useAlbumQuery({ variables: { id } });

Expand Down
Loading