Skip to content

Commit

Permalink
os lyrics
Browse files Browse the repository at this point in the history
  • Loading branch information
kgarner7 committed Feb 2, 2024
1 parent 9e4664a commit 73cd647
Show file tree
Hide file tree
Showing 9 changed files with 181 additions and 45 deletions.
16 changes: 16 additions & 0 deletions src/renderer/api/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ import type {
LyricsResponse,
ServerInfo,
ServerInfoArgs,
StructuredLyricsArgs,
StructuredLyric,
} from '/@/renderer/api/types';
import { ServerType } from '/@/renderer/types';
import { DeletePlaylistResponse, RandomSongListArgs } from './types';
Expand Down Expand Up @@ -90,6 +92,7 @@ export type ControllerEndpoint = Partial<{
getServerInfo: (args: ServerInfoArgs) => Promise<ServerInfo>;
getSongDetail: (args: SongDetailArgs) => Promise<SongDetailResponse>;
getSongList: (args: SongListArgs) => Promise<SongListResponse>;
getStructuredLyrics: (args: StructuredLyricsArgs) => Promise<StructuredLyric[]>;
getTopSongs: (args: TopSongListArgs) => Promise<TopSongListResponse>;
getUserList: (args: UserListArgs) => Promise<UserListResponse>;
removeFromPlaylist: (args: RemoveFromPlaylistArgs) => Promise<RemoveFromPlaylistResponse>;
Expand Down Expand Up @@ -135,6 +138,7 @@ const endpoints: ApiController = {
getServerInfo: jfController.getServerInfo,
getSongDetail: jfController.getSongDetail,
getSongList: jfController.getSongList,
getStructuredLyrics: undefined,
getTopSongs: jfController.getTopSongList,
getUserList: undefined,
removeFromPlaylist: jfController.removeFromPlaylist,
Expand Down Expand Up @@ -172,6 +176,7 @@ const endpoints: ApiController = {
getServerInfo: ssController.getServerInfo,
getSongDetail: ndController.getSongDetail,
getSongList: ndController.getSongList,
getStructuredLyrics: ssController.getStructuredLyrics,
getTopSongs: ssController.getTopSongList,
getUserList: ndController.getUserList,
removeFromPlaylist: ndController.removeFromPlaylist,
Expand Down Expand Up @@ -206,6 +211,7 @@ const endpoints: ApiController = {
getServerInfo: ssController.getServerInfo,
getSongDetail: undefined,
getSongList: undefined,
getStructuredLyrics: ssController.getStructuredLyrics,
getTopSongs: ssController.getTopSongList,
getUserList: undefined,
scrobble: ssController.scrobble,
Expand Down Expand Up @@ -496,6 +502,15 @@ const getServerInfo = async (args: ServerInfoArgs) => {
)?.(args);
};

const getStructuredLyrics = async (args: StructuredLyricsArgs) => {
return (
apiController(
'getStructuredLyrics',
args.apiClientProps.server?.type,
) as ControllerEndpoint['getStructuredLyrics']
)?.(args);
};

export const controller = {
addToPlaylist,
authenticate,
Expand All @@ -518,6 +533,7 @@ export const controller = {
getServerInfo,
getSongDetail,
getSongList,
getStructuredLyrics,
getTopSongList,
getUserList,
removeFromPlaylist,
Expand Down
8 changes: 8 additions & 0 deletions src/renderer/api/subsonic/subsonic-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ export const contract = c.router({
200: ssType._response.serverInfo,
},
},
getStructuredLyrics: {
method: 'GET',
path: 'getLyricsBySongId.view',
query: ssType._parameters.structuredLyrics,
responses: {
200: ssType._response.structuredLyrics,
},
},
getTopSongsList: {
method: 'GET',
path: 'getTopSongs.view',
Expand Down
48 changes: 48 additions & 0 deletions src/renderer/api/subsonic/subsonic-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import {
RandomSongListArgs,
ServerInfo,
ServerInfoArgs,
StructuredLyricsArgs,
StructuredLyric,
} from '/@/renderer/api/types';
import { randomString } from '/@/renderer/utils';

Expand Down Expand Up @@ -397,13 +399,59 @@ const getServerInfo = async (args: ServerInfoArgs): Promise<ServerInfo> => {
return { features, id: apiClientProps.server?.id, version: ping.body.serverVersion };
};

export const getStructuredLyrics = async (
args: StructuredLyricsArgs,
): Promise<StructuredLyric[]> => {
const { query, apiClientProps } = args;

const res = await ssApiClient(apiClientProps).getStructuredLyrics({
query: {
id: query.songId,
},
});

if (res.status !== 200) {
throw new Error('Failed to get server extensions');
}

const lyrics = res.body.lyricsList?.structuredLyrics;

if (!lyrics) {
return [];
}

return lyrics.map((lyric) => {
const baseLyric = {
artist: lyric.displayArtist || '',
lang: lyric.lang,
name: lyric.displayTitle || '',
remote: false,
source: apiClientProps.server?.name || 'music server',
};

if (lyric.synced) {
return {
...baseLyric,
lyrics: lyric.line.map((line) => [line.start!, line.value]),
synced: true,
};
}
return {
...baseLyric,
lyrics: lyric.line.map((line) => [line.value]).join('\n'),
synced: false,
};
});
};

export const ssController = {
authenticate,
createFavorite,
getArtistInfo,
getMusicFolderList,
getRandomSongList,
getServerInfo,
getStructuredLyrics,
getTopSongList,
removeFavorite,
scrobble,
Expand Down
28 changes: 28 additions & 0 deletions src/renderer/api/subsonic/subsonic-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,32 @@ const serverInfo = z.object({
openSubsonicExtensions: z.array(extension),
});

const structuredLyricsParameters = z.object({
id: z.string(),
});

const lyricLine = z.object({
start: z.number().optional(),
value: z.string(),
});

const structuredLyric = z.object({
displayArtist: z.string().optional(),
displayTitle: z.string().optional(),
lang: z.string(),
line: z.array(lyricLine),
offset: z.number().optional(),
synced: z.boolean(),
});

const structuredLyrics = z.object({
lyricsList: z
.object({
structuredLyrics: z.array(structuredLyric).optional(),
})
.optional(),
});

export const ssType = {
_parameters: {
albumList: albumListParameters,
Expand All @@ -232,6 +258,7 @@ export const ssType = {
scrobble: scrobbleParameters,
search3: search3Parameters,
setRating: setRatingParameters,
structuredLyrics: structuredLyricsParameters,
topSongsList: topSongsListParameters,
},
_response: {
Expand All @@ -252,6 +279,7 @@ export const ssType = {
serverInfo,
setRating,
song,
structuredLyrics,
topSongsList,
},
};
32 changes: 22 additions & 10 deletions src/renderer/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1092,17 +1092,11 @@ export type InternetProviderLyricSearchResponse = {
source: LyricSource;
};

export type SynchronizedLyricMetadata = {
lyrics: SynchronizedLyricsArray;
remote: boolean;
} & Omit<InternetProviderLyricResponse, 'lyrics'>;

export type UnsynchronizedLyricMetadata = {
lyrics: string;
export type FullLyricsMetadata = {
lyrics: LyricsResponse;
remote: boolean;
} & Omit<InternetProviderLyricResponse, 'lyrics'>;

export type FullLyricsMetadata = SynchronizedLyricMetadata | UnsynchronizedLyricMetadata;
source: string;
} & Omit<InternetProviderLyricResponse, 'id' | 'lyrics' | 'source'>;

export type LyricOverride = Omit<InternetProviderLyricResponse, 'lyrics'>;

Expand Down Expand Up @@ -1153,3 +1147,21 @@ export type ServerInfo = {
id?: string;
version: string;
};

export type StructuredLyricsArgs = {
query: LyricsQuery;
} & BaseEndpointArgs;

export type StructuredUnsyncedLyric = {
lyrics: string;
synced: false;
} & Omit<FullLyricsMetadata, 'lyrics'>;

export type StructuredSyncedLyric = {
lyrics: SynchronizedLyricsArray;
synced: true;
} & Omit<FullLyricsMetadata, 'lyrics'>;

export type StructuredLyric = {
lang: string;
} & (StructuredUnsyncedLyric | StructuredSyncedLyric);
74 changes: 44 additions & 30 deletions src/renderer/features/lyrics/lyrics.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Center, Group } from '@mantine/core';
import { AnimatePresence, motion } from 'framer-motion';
import { ErrorBoundary } from 'react-error-boundary';
import { RiInformationFill } from 'react-icons/ri';
import styled from 'styled-components';
import { useSongLyricsByRemoteId, useSongLyricsBySong } from './queries/lyric-query';
import { SynchronizedLyrics } from './synchronized-lyrics';
import { Spinner, TextTitle } from '/@/renderer/components';
import { SynchronizedLyrics, SynchronizedLyricsProps } from './synchronized-lyrics';
import { Select, Spinner, TextTitle } from '/@/renderer/components';
import { ErrorFallback } from '/@/renderer/features/action-required';
import { UnsynchronizedLyrics } from '/@/renderer/features/lyrics/unsynchronized-lyrics';
import { useCurrentSong, usePlayerStore } from '/@/renderer/store';
import {
FullLyricsMetadata,
LyricsOverride,
SynchronizedLyricMetadata,
UnsynchronizedLyricMetadata,
} from '/@/renderer/api/types';
UnsynchronizedLyrics,
UnsynchronizedLyricsProps,
} from '/@/renderer/features/lyrics/unsynchronized-lyrics';
import { useCurrentSong, usePlayerStore } from '/@/renderer/store';
import { FullLyricsMetadata, LyricSource, LyricsOverride } from '/@/renderer/api/types';
import { LyricsActions } from '/@/renderer/features/lyrics/lyrics-actions';
import { queryKeys } from '/@/renderer/api/query-keys';
import { queryClient } from '/@/renderer/lib/react-query';
Expand Down Expand Up @@ -84,17 +82,9 @@ const ScrollContainer = styled(motion.div)`
}
`;

function isSynchronized(
data: Partial<FullLyricsMetadata> | undefined,
): data is SynchronizedLyricMetadata {
// Type magic. The only difference between Synchronized and Unsynchhronized is
// the datatype of lyrics. This makes Typescript happier later...
if (!data) return false;
return Array.isArray(data.lyrics);
}

export const Lyrics = () => {
const currentSong = useCurrentSong();
const [index, setIndex] = useState(0);

const { data, isInitialLoading } = useSongLyricsBySong(
{
Expand Down Expand Up @@ -139,7 +129,7 @@ export const Lyrics = () => {
},
query: {
remoteSongId: override?.id,
remoteSource: override?.source,
remoteSource: override?.source as LyricSource | undefined,
song: currentSong,
},
serverId: currentSong?.serverId,
Expand All @@ -150,6 +140,7 @@ export const Lyrics = () => {
(state) => state.current.song,
() => {
setOverride(undefined);
setIndex(0);
},
{ equalityFn: (a, b) => a?.id === b?.id },
);
Expand All @@ -159,16 +150,29 @@ export const Lyrics = () => {
};
}, []);

const isLoadingLyrics = isInitialLoading || isOverrideLoading;
const [lyrics, synced] = useMemo(() => {
if (Array.isArray(data)) {
if (data.length > 0) {
const selectedLyric = data[Math.min(index, data.length)];
return [selectedLyric, selectedLyric.synced];
}
} else if (data?.lyrics) {
return [data, Array.isArray(data.lyrics)];
}

const hasNoLyrics = !data?.lyrics;
return [undefined, false];
}, [data, index]);

const lyricsMetadata:
| Partial<SynchronizedLyricMetadata>
| Partial<UnsynchronizedLyricMetadata>
| undefined = data;
const languages = useMemo(() => {
if (Array.isArray(data)) {
return data.map((lyric, idx) => ({ label: lyric.lang, value: idx.toString() }));
}
return [];
}, [data]);

const isLoadingLyrics = isInitialLoading || isOverrideLoading;

const isSynchronizedLyrics = isSynchronized(lyricsMetadata);
const hasNoLyrics = !lyrics;

return (
<ErrorBoundary FallbackComponent={ErrorFallback}>
Expand Down Expand Up @@ -198,18 +202,28 @@ export const Lyrics = () => {
initial={{ opacity: 0 }}
transition={{ duration: 0.5 }}
>
{isSynchronizedLyrics ? (
<SynchronizedLyrics {...lyricsMetadata} />
{synced ? (
<SynchronizedLyrics {...(lyrics as SynchronizedLyricsProps)} />
) : (
<UnsynchronizedLyrics
{...(lyricsMetadata as UnsynchronizedLyricMetadata)}
{...(lyrics as UnsynchronizedLyricsProps)}
/>
)}
</ScrollContainer>
)}
</AnimatePresence>
)}
<ActionsContainer>
{languages.length > 1 && (
<Select
clearable={false}
data={languages}
style={{ bottom: 50, position: 'absolute' }}
value={index.toString()}
onChange={(value) => setIndex(parseInt(value!, 10))}
/>
)}

<LyricsActions
onRemoveLyric={handleOnRemoveLyric}
onResetLyric={handleOnResetLyric}
Expand Down
Loading

0 comments on commit 73cd647

Please sign in to comment.