mirror of
https://github.com/wkulhanek/bonob.git
synced 2025-12-21 17:33:29 +01:00
Move getGenres onto subsonic
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
import { option as O } from "fp-ts";
|
||||
import * as A from "fp-ts/Array";
|
||||
import { ordString } from "fp-ts/lib/Ord";
|
||||
import { pipe } from "fp-ts/lib/function";
|
||||
import { Md5 } from "ts-md5";
|
||||
import {
|
||||
@@ -195,13 +197,15 @@ export type GetTopSongsResponse = {
|
||||
};
|
||||
|
||||
export type GetInternetRadioStationsResponse = {
|
||||
internetRadioStations: { internetRadioStation: {
|
||||
id: string,
|
||||
name: string,
|
||||
streamUrl: string,
|
||||
homePageUrl?: string }[]
|
||||
}
|
||||
}
|
||||
internetRadioStations: {
|
||||
internetRadioStation: {
|
||||
id: string;
|
||||
name: string;
|
||||
streamUrl: string;
|
||||
homePageUrl?: string;
|
||||
}[];
|
||||
};
|
||||
};
|
||||
|
||||
export type GetSongResponse = {
|
||||
song: song;
|
||||
@@ -274,14 +278,20 @@ export const artistImageURN = (
|
||||
}
|
||||
};
|
||||
|
||||
export const asTrack = (album: Album, song: song, customPlayers: CustomPlayers): Track => ({
|
||||
export const asTrack = (
|
||||
album: Album,
|
||||
song: song,
|
||||
customPlayers: CustomPlayers
|
||||
): Track => ({
|
||||
id: song.id,
|
||||
name: song.title,
|
||||
encoding: pipe(
|
||||
customPlayers.encodingFor({ mimeType: song.contentType }),
|
||||
O.getOrElse(() => ({
|
||||
player: DEFAULT_CLIENT_APPLICATION,
|
||||
mimeType: song.transcodedContentType ? song.transcodedContentType : song.contentType
|
||||
O.getOrElse(() => ({
|
||||
player: DEFAULT_CLIENT_APPLICATION,
|
||||
mimeType: song.transcodedContentType
|
||||
? song.transcodedContentType
|
||||
: song.contentType,
|
||||
}))
|
||||
),
|
||||
duration: song.duration || 0,
|
||||
@@ -327,7 +337,9 @@ export const asGenre = (genreName: string) => ({
|
||||
name: genreName,
|
||||
});
|
||||
|
||||
export const maybeAsGenre = (genreName: string | undefined): Genre | undefined =>
|
||||
export const maybeAsGenre = (
|
||||
genreName: string | undefined
|
||||
): Genre | undefined =>
|
||||
pipe(
|
||||
genreName,
|
||||
O.fromNullable,
|
||||
@@ -340,7 +352,7 @@ export const asYear = (year: string) => ({
|
||||
});
|
||||
|
||||
export interface CustomPlayers {
|
||||
encodingFor({ mimeType }: { mimeType: string }): O.Option<Encoding>
|
||||
encodingFor({ mimeType }: { mimeType: string }): O.Option<Encoding>;
|
||||
}
|
||||
|
||||
export type CustomClient = {
|
||||
@@ -367,21 +379,22 @@ export class TranscodingCustomPlayers implements CustomPlayers {
|
||||
return new TranscodingCustomPlayers(new Map(parts));
|
||||
}
|
||||
|
||||
encodingFor = ({ mimeType }: { mimeType: string }): O.Option<Encoding> => pipe(
|
||||
this.transcodings.get(mimeType),
|
||||
O.fromNullable,
|
||||
O.map(transcodedMimeType => ({
|
||||
player:`${DEFAULT_CLIENT_APPLICATION}+${mimeType}`,
|
||||
mimeType: transcodedMimeType
|
||||
}))
|
||||
)
|
||||
encodingFor = ({ mimeType }: { mimeType: string }): O.Option<Encoding> =>
|
||||
pipe(
|
||||
this.transcodings.get(mimeType),
|
||||
O.fromNullable,
|
||||
O.map((transcodedMimeType) => ({
|
||||
player: `${DEFAULT_CLIENT_APPLICATION}+${mimeType}`,
|
||||
mimeType: transcodedMimeType,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
export const NO_CUSTOM_PLAYERS: CustomPlayers = {
|
||||
encodingFor(_) {
|
||||
return O.none
|
||||
return O.none;
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
export const DEFAULT_CLIENT_APPLICATION = "bonob";
|
||||
export const USER_AGENT = "bonob";
|
||||
@@ -674,8 +687,8 @@ export class Subsonic {
|
||||
this.getJSON<GetAlbumListResponse>(credentials, "/rest/getAlbumList2", {
|
||||
type: AlbumQueryTypeToSubsonicType[q.type],
|
||||
...(q.genre ? { genre: b64Decode(q.genre) } : {}),
|
||||
...(q.fromYear ? { fromYear: q.fromYear} : {}),
|
||||
...(q.toYear ? { toYear: q.toYear} : {}),
|
||||
...(q.fromYear ? { fromYear: q.fromYear } : {}),
|
||||
...(q.toYear ? { toYear: q.toYear } : {}),
|
||||
size: 500,
|
||||
offset: q._index,
|
||||
})
|
||||
@@ -686,11 +699,22 @@ export class Subsonic {
|
||||
total: albums.length == 500 ? total : q._index + albums.length,
|
||||
}));
|
||||
|
||||
getGenres = (credentials: Credentials) =>
|
||||
this.getJSON<GetGenresResponse>(credentials, "/rest/getGenres").then((it) =>
|
||||
pipe(
|
||||
it.genres.genre || [],
|
||||
A.filter((it) => it.albumCount > 0),
|
||||
A.map((it) => it.value),
|
||||
A.sort(ordString),
|
||||
A.map(maybeAsGenre),
|
||||
A.filter((it) => it != undefined)
|
||||
)
|
||||
);
|
||||
|
||||
// getStarred2 = (credentials: Credentials): Promise<{ albums: Album[] }> =>
|
||||
// this.getJSON<GetStarredResponse>(credentials, "/rest/getStarred2")
|
||||
// .then((it) => it.starred2)
|
||||
// .then((it) => ({
|
||||
// albums: it.album.map(asAlbum),
|
||||
// }));
|
||||
|
||||
}
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
|
||||
|
||||
import { option as O, taskEither as TE } from "fp-ts";
|
||||
import * as A from "fp-ts/Array";
|
||||
import { ordString } from "fp-ts/lib/Ord";
|
||||
import { pipe } from "fp-ts/lib/function";
|
||||
import {
|
||||
Credentials,
|
||||
@@ -20,37 +16,34 @@ import {
|
||||
AuthFailure,
|
||||
AuthSuccess,
|
||||
} from "./music_library";
|
||||
import {
|
||||
Subsonic,
|
||||
CustomPlayers,
|
||||
GetGenresResponse,
|
||||
GetAlbumResponse,
|
||||
asTrack,
|
||||
asAlbum,
|
||||
PingResponse,
|
||||
NO_CUSTOM_PLAYERS,
|
||||
asToken,
|
||||
parseToken,
|
||||
artistImageURN,
|
||||
USER_AGENT,
|
||||
GetPlaylistsResponse,
|
||||
GetPlaylistResponse,
|
||||
asPlayListSummary,
|
||||
coverArtURN,
|
||||
maybeAsGenre,
|
||||
GetSimilarSongsResponse,
|
||||
GetTopSongsResponse,
|
||||
GetInternetRadioStationsResponse,
|
||||
asYear,
|
||||
import {
|
||||
Subsonic,
|
||||
CustomPlayers,
|
||||
GetAlbumResponse,
|
||||
asTrack,
|
||||
asAlbum,
|
||||
PingResponse,
|
||||
NO_CUSTOM_PLAYERS,
|
||||
asToken,
|
||||
parseToken,
|
||||
artistImageURN,
|
||||
USER_AGENT,
|
||||
GetPlaylistsResponse,
|
||||
GetPlaylistResponse,
|
||||
asPlayListSummary,
|
||||
coverArtURN,
|
||||
maybeAsGenre,
|
||||
GetSimilarSongsResponse,
|
||||
GetTopSongsResponse,
|
||||
GetInternetRadioStationsResponse,
|
||||
asYear,
|
||||
} from "./subsonic";
|
||||
import _ from "underscore";
|
||||
|
||||
import axios from "axios";
|
||||
import { b64Encode } from "./b64";
|
||||
import logger from "./logger";
|
||||
import { assertSystem, BUrn } from "./burn";
|
||||
|
||||
|
||||
export class SubsonicMusicService implements MusicService {
|
||||
subsonic: Subsonic;
|
||||
customPlayers: CustomPlayers;
|
||||
@@ -63,7 +56,9 @@ export class SubsonicMusicService implements MusicService {
|
||||
this.customPlayers = customPlayers;
|
||||
}
|
||||
|
||||
generateToken = (credentials: Credentials): TE.TaskEither<AuthFailure, AuthSuccess> => {
|
||||
generateToken = (
|
||||
credentials: Credentials
|
||||
): TE.TaskEither<AuthFailure, AuthSuccess> => {
|
||||
const x: TE.TaskEither<AuthFailure, PingResponse> = TE.tryCatch(
|
||||
() =>
|
||||
this.subsonic.getJSON<PingResponse>(
|
||||
@@ -71,7 +66,7 @@ export class SubsonicMusicService implements MusicService {
|
||||
"/rest/ping.view"
|
||||
),
|
||||
(e) => new AuthFailure(e as string)
|
||||
)
|
||||
);
|
||||
return pipe(
|
||||
x,
|
||||
TE.flatMap(({ type }) =>
|
||||
@@ -94,8 +89,8 @@ export class SubsonicMusicService implements MusicService {
|
||||
userId: credentials.username,
|
||||
nickname: credentials.username,
|
||||
}))
|
||||
)
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
refreshToken = (serviceToken: string) =>
|
||||
this.generateToken(parseToken(serviceToken));
|
||||
@@ -105,7 +100,11 @@ export class SubsonicMusicService implements MusicService {
|
||||
private libraryFor = (
|
||||
credentials: Credentials & { type: string }
|
||||
): Promise<SubsonicMusicLibrary> => {
|
||||
const genericSubsonic = new SubsonicMusicLibrary(this.subsonic, credentials, this.customPlayers);
|
||||
const genericSubsonic = new SubsonicMusicLibrary(
|
||||
this.subsonic,
|
||||
credentials,
|
||||
this.customPlayers
|
||||
);
|
||||
// return Promise.resolve(genericSubsonic);
|
||||
|
||||
if (credentials.type == "navidrome") {
|
||||
@@ -125,7 +124,7 @@ export class SubsonicMusicService implements MusicService {
|
||||
),
|
||||
TE.map((it) => it.data.token as string | undefined)
|
||||
),
|
||||
}
|
||||
};
|
||||
return Promise.resolve(nd);
|
||||
} else {
|
||||
return Promise.resolve(genericSubsonic);
|
||||
@@ -133,25 +132,25 @@ export class SubsonicMusicService implements MusicService {
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
export class SubsonicMusicLibrary implements MusicLibrary {
|
||||
subsonic: Subsonic;
|
||||
credentials: Credentials
|
||||
customPlayers: CustomPlayers
|
||||
credentials: Credentials;
|
||||
customPlayers: CustomPlayers;
|
||||
|
||||
constructor(
|
||||
subsonic: Subsonic,
|
||||
credentials: Credentials,
|
||||
customPlayers: CustomPlayers
|
||||
) {
|
||||
this.subsonic = subsonic
|
||||
this.credentials = credentials
|
||||
this.customPlayers = customPlayers
|
||||
this.subsonic = subsonic;
|
||||
this.credentials = credentials;
|
||||
this.customPlayers = customPlayers;
|
||||
}
|
||||
|
||||
flavour = () => "subsonic"
|
||||
flavour = () => "subsonic";
|
||||
|
||||
bearerToken = (_: Credentials) => TE.right<AuthFailure, string | undefined>(undefined)
|
||||
bearerToken = (_: Credentials) =>
|
||||
TE.right<AuthFailure, string | undefined>(undefined);
|
||||
|
||||
artists = (q: ArtistQuery): Promise<Result<ArtistSummary>> =>
|
||||
this.subsonic
|
||||
@@ -164,28 +163,18 @@ export class SubsonicMusicLibrary implements MusicLibrary {
|
||||
name: it.name,
|
||||
image: it.image,
|
||||
})),
|
||||
}))
|
||||
}));
|
||||
|
||||
artist = async (id: string): Promise<Artist> =>
|
||||
this.subsonic.getArtistWithInfo(this.credentials, id)
|
||||
this.subsonic.getArtistWithInfo(this.credentials, id);
|
||||
|
||||
albums = async (q: AlbumQuery): Promise<Result<AlbumSummary>> =>
|
||||
this.subsonic.getAlbumList2(this.credentials, q)
|
||||
this.subsonic.getAlbumList2(this.credentials, q);
|
||||
|
||||
album = (id: string): Promise<Album> => this.subsonic.getAlbum(this.credentials, id)
|
||||
album = (id: string): Promise<Album> =>
|
||||
this.subsonic.getAlbum(this.credentials, id);
|
||||
|
||||
genres = () =>
|
||||
this.subsonic
|
||||
.getJSON<GetGenresResponse>(this.credentials, "/rest/getGenres")
|
||||
.then((it) =>
|
||||
pipe(
|
||||
it.genres.genre || [],
|
||||
A.filter((it) => it.albumCount > 0),
|
||||
A.map((it) => it.value),
|
||||
A.sort(ordString),
|
||||
A.map((it) => ({ id: b64Encode(it), name: it }))
|
||||
)
|
||||
)
|
||||
genres = () => this.subsonic.getGenres(this.credentials);
|
||||
|
||||
tracks = (albumId: string) =>
|
||||
this.subsonic
|
||||
@@ -194,10 +183,13 @@ export class SubsonicMusicLibrary implements MusicLibrary {
|
||||
})
|
||||
.then((it) => it.album)
|
||||
.then((album) =>
|
||||
(album.song || []).map((song) => asTrack(asAlbum(album), song, this.customPlayers))
|
||||
)
|
||||
(album.song || []).map((song) =>
|
||||
asTrack(asAlbum(album), song, this.customPlayers)
|
||||
)
|
||||
);
|
||||
|
||||
track = (trackId: string) => this.subsonic.getTrack(this.credentials, trackId)
|
||||
track = (trackId: string) =>
|
||||
this.subsonic.getTrack(this.credentials, trackId);
|
||||
|
||||
rate = (trackId: string, rating: Rating) =>
|
||||
Promise.resolve(true)
|
||||
@@ -232,189 +224,213 @@ export class SubsonicMusicLibrary implements MusicLibrary {
|
||||
return Promise.all(thingsToUpdate);
|
||||
})
|
||||
.then(() => true)
|
||||
.catch(() => false)
|
||||
|
||||
stream = async ({
|
||||
trackId,
|
||||
range,
|
||||
}: {
|
||||
trackId: string;
|
||||
range: string | undefined;
|
||||
}) =>
|
||||
this.subsonic.getTrack(this.credentials, trackId).then((track) =>
|
||||
this.subsonic
|
||||
.get(
|
||||
this.credentials,
|
||||
`/rest/stream`,
|
||||
{
|
||||
id: trackId,
|
||||
c: track.encoding.player,
|
||||
},
|
||||
{
|
||||
headers: pipe(
|
||||
range,
|
||||
O.fromNullable,
|
||||
O.map((range) => ({
|
||||
"User-Agent": USER_AGENT,
|
||||
Range: range,
|
||||
})),
|
||||
O.getOrElse(() => ({
|
||||
"User-Agent": USER_AGENT,
|
||||
}))
|
||||
),
|
||||
responseType: "stream",
|
||||
}
|
||||
)
|
||||
.then((stream) => ({
|
||||
status: stream.status,
|
||||
headers: {
|
||||
"content-type": stream.headers["content-type"],
|
||||
"content-length": stream.headers["content-length"],
|
||||
"content-range": stream.headers["content-range"],
|
||||
"accept-ranges": stream.headers["accept-ranges"],
|
||||
},
|
||||
stream: stream.data,
|
||||
}))
|
||||
)
|
||||
.catch(() => false);
|
||||
|
||||
coverArt = async (coverArtURN: BUrn, size?: number) =>
|
||||
Promise.resolve(coverArtURN)
|
||||
.then((it) => assertSystem(it, "subsonic"))
|
||||
.then((it) => this.subsonic.getCoverArt(this.credentials, it.resource.split(":")[1]!, size))
|
||||
.then((res) => ({
|
||||
contentType: res.headers["content-type"],
|
||||
data: Buffer.from(res.data, "binary"),
|
||||
stream = async ({
|
||||
trackId,
|
||||
range,
|
||||
}: {
|
||||
trackId: string;
|
||||
range: string | undefined;
|
||||
}) =>
|
||||
this.subsonic.getTrack(this.credentials, trackId).then((track) =>
|
||||
this.subsonic
|
||||
.get(
|
||||
this.credentials,
|
||||
`/rest/stream`,
|
||||
{
|
||||
id: trackId,
|
||||
c: track.encoding.player,
|
||||
},
|
||||
{
|
||||
headers: pipe(
|
||||
range,
|
||||
O.fromNullable,
|
||||
O.map((range) => ({
|
||||
"User-Agent": USER_AGENT,
|
||||
Range: range,
|
||||
})),
|
||||
O.getOrElse(() => ({
|
||||
"User-Agent": USER_AGENT,
|
||||
}))
|
||||
),
|
||||
responseType: "stream",
|
||||
}
|
||||
)
|
||||
.then((stream) => ({
|
||||
status: stream.status,
|
||||
headers: {
|
||||
"content-type": stream.headers["content-type"],
|
||||
"content-length": stream.headers["content-length"],
|
||||
"content-range": stream.headers["content-range"],
|
||||
"accept-ranges": stream.headers["accept-ranges"],
|
||||
},
|
||||
stream: stream.data,
|
||||
}))
|
||||
.catch((e) => {
|
||||
logger.error(
|
||||
`Failed getting coverArt for urn:'${coverArtURN}': ${e}`
|
||||
);
|
||||
return undefined;
|
||||
})
|
||||
);
|
||||
|
||||
scrobble = async (id: string) =>
|
||||
this.subsonic
|
||||
.getJSON(this.credentials, `/rest/scrobble`, {
|
||||
id,
|
||||
submission: true,
|
||||
})
|
||||
.then((_) => true)
|
||||
.catch(() => false)
|
||||
|
||||
nowPlaying = async (id: string) =>
|
||||
this.subsonic
|
||||
.getJSON(this.credentials, `/rest/scrobble`, {
|
||||
id,
|
||||
submission: false,
|
||||
})
|
||||
.then((_) => true)
|
||||
.catch(() => false)
|
||||
|
||||
searchArtists = async (query: string) =>
|
||||
this.subsonic
|
||||
.search3(this.credentials, { query, artistCount: 20 })
|
||||
.then(({ artists }) =>
|
||||
artists.map((artist) => ({
|
||||
id: artist.id,
|
||||
name: artist.name,
|
||||
image: artistImageURN({
|
||||
artistId: artist.id,
|
||||
artistImageURL: artist.artistImageUrl,
|
||||
}),
|
||||
}))
|
||||
)
|
||||
|
||||
searchAlbums = async (query: string) =>
|
||||
this.subsonic
|
||||
.search3(this.credentials, { query, albumCount: 20 })
|
||||
.then(({ albums }) => this.subsonic.toAlbumSummary(albums))
|
||||
|
||||
searchTracks = async (query: string) =>
|
||||
this.subsonic
|
||||
.search3(this.credentials, { query, songCount: 20 })
|
||||
.then(({ songs }) =>
|
||||
Promise.all(
|
||||
songs.map((it) => this.subsonic.getTrack(this.credentials, it.id))
|
||||
)
|
||||
coverArt = async (coverArtURN: BUrn, size?: number) =>
|
||||
Promise.resolve(coverArtURN)
|
||||
.then((it) => assertSystem(it, "subsonic"))
|
||||
.then((it) =>
|
||||
this.subsonic.getCoverArt(
|
||||
this.credentials,
|
||||
it.resource.split(":")[1]!,
|
||||
size
|
||||
)
|
||||
)
|
||||
.then((res) => ({
|
||||
contentType: res.headers["content-type"],
|
||||
data: Buffer.from(res.data, "binary"),
|
||||
}))
|
||||
.catch((e) => {
|
||||
logger.error(`Failed getting coverArt for urn:'${coverArtURN}': ${e}`);
|
||||
return undefined;
|
||||
});
|
||||
|
||||
playlists = async () =>
|
||||
this.subsonic
|
||||
.getJSON<GetPlaylistsResponse>(this.credentials, "/rest/getPlaylists")
|
||||
.then(({ playlists }) => (playlists.playlist || []).map(asPlayListSummary))
|
||||
scrobble = async (id: string) =>
|
||||
this.subsonic
|
||||
.getJSON(this.credentials, `/rest/scrobble`, {
|
||||
id,
|
||||
submission: true,
|
||||
})
|
||||
.then((_) => true)
|
||||
.catch(() => false);
|
||||
|
||||
playlist = async (id: string) =>
|
||||
this.subsonic
|
||||
.getJSON<GetPlaylistResponse>(this.credentials, "/rest/getPlaylist", {
|
||||
id,
|
||||
})
|
||||
.then(({ playlist }) => {
|
||||
let trackNumber = 1;
|
||||
return {
|
||||
id: playlist.id,
|
||||
name: playlist.name,
|
||||
coverArt: coverArtURN(playlist.coverArt),
|
||||
entries: (playlist.entry || []).map((entry) => ({
|
||||
...asTrack(
|
||||
{
|
||||
id: entry.albumId!,
|
||||
name: entry.album!,
|
||||
year: entry.year,
|
||||
genre: maybeAsGenre(entry.genre),
|
||||
artistName: entry.artist,
|
||||
artistId: entry.artistId,
|
||||
coverArt: coverArtURN(entry.coverArt),
|
||||
},
|
||||
entry,
|
||||
this.customPlayers
|
||||
),
|
||||
number: trackNumber++,
|
||||
})),
|
||||
};
|
||||
})
|
||||
nowPlaying = async (id: string) =>
|
||||
this.subsonic
|
||||
.getJSON(this.credentials, `/rest/scrobble`, {
|
||||
id,
|
||||
submission: false,
|
||||
})
|
||||
.then((_) => true)
|
||||
.catch(() => false);
|
||||
|
||||
createPlaylist = async (name: string) =>
|
||||
this.subsonic
|
||||
.getJSON<GetPlaylistResponse>(this.credentials, "/rest/createPlaylist", {
|
||||
name,
|
||||
})
|
||||
.then(({ playlist }) => ({
|
||||
searchArtists = async (query: string) =>
|
||||
this.subsonic
|
||||
.search3(this.credentials, { query, artistCount: 20 })
|
||||
.then(({ artists }) =>
|
||||
artists.map((artist) => ({
|
||||
id: artist.id,
|
||||
name: artist.name,
|
||||
image: artistImageURN({
|
||||
artistId: artist.id,
|
||||
artistImageURL: artist.artistImageUrl,
|
||||
}),
|
||||
}))
|
||||
);
|
||||
|
||||
searchAlbums = async (query: string) =>
|
||||
this.subsonic
|
||||
.search3(this.credentials, { query, albumCount: 20 })
|
||||
.then(({ albums }) => this.subsonic.toAlbumSummary(albums));
|
||||
|
||||
searchTracks = async (query: string) =>
|
||||
this.subsonic
|
||||
.search3(this.credentials, { query, songCount: 20 })
|
||||
.then(({ songs }) =>
|
||||
Promise.all(
|
||||
songs.map((it) => this.subsonic.getTrack(this.credentials, it.id))
|
||||
)
|
||||
);
|
||||
|
||||
playlists = async () =>
|
||||
this.subsonic
|
||||
.getJSON<GetPlaylistsResponse>(this.credentials, "/rest/getPlaylists")
|
||||
.then(({ playlists }) =>
|
||||
(playlists.playlist || []).map(asPlayListSummary)
|
||||
);
|
||||
|
||||
playlist = async (id: string) =>
|
||||
this.subsonic
|
||||
.getJSON<GetPlaylistResponse>(this.credentials, "/rest/getPlaylist", {
|
||||
id,
|
||||
})
|
||||
.then(({ playlist }) => {
|
||||
let trackNumber = 1;
|
||||
return {
|
||||
id: playlist.id,
|
||||
name: playlist.name,
|
||||
coverArt: coverArtURN(playlist.coverArt),
|
||||
}))
|
||||
entries: (playlist.entry || []).map((entry) => ({
|
||||
...asTrack(
|
||||
{
|
||||
id: entry.albumId!,
|
||||
name: entry.album!,
|
||||
year: entry.year,
|
||||
genre: maybeAsGenre(entry.genre),
|
||||
artistName: entry.artist,
|
||||
artistId: entry.artistId,
|
||||
coverArt: coverArtURN(entry.coverArt),
|
||||
},
|
||||
entry,
|
||||
this.customPlayers
|
||||
),
|
||||
number: trackNumber++,
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
deletePlaylist = async (id: string) =>
|
||||
this.subsonic
|
||||
.getJSON<GetPlaylistResponse>(this.credentials, "/rest/deletePlaylist", {
|
||||
id,
|
||||
})
|
||||
.then((_) => true)
|
||||
createPlaylist = async (name: string) =>
|
||||
this.subsonic
|
||||
.getJSON<GetPlaylistResponse>(this.credentials, "/rest/createPlaylist", {
|
||||
name,
|
||||
})
|
||||
.then(({ playlist }) => ({
|
||||
id: playlist.id,
|
||||
name: playlist.name,
|
||||
coverArt: coverArtURN(playlist.coverArt),
|
||||
}));
|
||||
|
||||
addToPlaylist = async (playlistId: string, trackId: string) =>
|
||||
this.subsonic
|
||||
.getJSON<GetPlaylistResponse>(this.credentials, "/rest/updatePlaylist", {
|
||||
playlistId,
|
||||
songIdToAdd: trackId,
|
||||
})
|
||||
.then((_) => true)
|
||||
deletePlaylist = async (id: string) =>
|
||||
this.subsonic
|
||||
.getJSON<GetPlaylistResponse>(this.credentials, "/rest/deletePlaylist", {
|
||||
id,
|
||||
})
|
||||
.then((_) => true);
|
||||
|
||||
removeFromPlaylist = async (playlistId: string, indicies: number[]) =>
|
||||
this.subsonic
|
||||
.getJSON<GetPlaylistResponse>(this.credentials, "/rest/updatePlaylist", {
|
||||
playlistId,
|
||||
songIndexToRemove: indicies,
|
||||
})
|
||||
.then((_) => true)
|
||||
addToPlaylist = async (playlistId: string, trackId: string) =>
|
||||
this.subsonic
|
||||
.getJSON<GetPlaylistResponse>(this.credentials, "/rest/updatePlaylist", {
|
||||
playlistId,
|
||||
songIdToAdd: trackId,
|
||||
})
|
||||
.then((_) => true);
|
||||
|
||||
similarSongs = async (id: string) =>
|
||||
this.subsonic
|
||||
.getJSON<GetSimilarSongsResponse>(
|
||||
this.credentials,
|
||||
"/rest/getSimilarSongs2",
|
||||
{ id, count: 50 }
|
||||
removeFromPlaylist = async (playlistId: string, indicies: number[]) =>
|
||||
this.subsonic
|
||||
.getJSON<GetPlaylistResponse>(this.credentials, "/rest/updatePlaylist", {
|
||||
playlistId,
|
||||
songIndexToRemove: indicies,
|
||||
})
|
||||
.then((_) => true);
|
||||
|
||||
similarSongs = async (id: string) =>
|
||||
this.subsonic
|
||||
.getJSON<GetSimilarSongsResponse>(
|
||||
this.credentials,
|
||||
"/rest/getSimilarSongs2",
|
||||
{ id, count: 50 }
|
||||
)
|
||||
.then((it) => it.similarSongs2.song || [])
|
||||
.then((songs) =>
|
||||
Promise.all(
|
||||
songs.map((song) =>
|
||||
this.subsonic
|
||||
.getAlbum(this.credentials, song.albumId!)
|
||||
.then((album) => asTrack(album, song, this.customPlayers))
|
||||
)
|
||||
)
|
||||
.then((it) => it.similarSongs2.song || [])
|
||||
);
|
||||
|
||||
topSongs = async (artistId: string) =>
|
||||
this.subsonic.getArtist(this.credentials, artistId).then(({ name }) =>
|
||||
this.subsonic
|
||||
.getJSON<GetTopSongsResponse>(this.credentials, "/rest/getTopSongs", {
|
||||
artist: name,
|
||||
count: 50,
|
||||
})
|
||||
.then((it) => it.topSongs.song || [])
|
||||
.then((songs) =>
|
||||
Promise.all(
|
||||
songs.map((song) =>
|
||||
@@ -424,60 +440,45 @@ export class SubsonicMusicLibrary implements MusicLibrary {
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
topSongs = async (artistId: string) =>
|
||||
this.subsonic.getArtist(this.credentials, artistId).then(({ name }) =>
|
||||
this.subsonic
|
||||
.getJSON<GetTopSongsResponse>(this.credentials, "/rest/getTopSongs", {
|
||||
artist: name,
|
||||
count: 50,
|
||||
})
|
||||
.then((it) => it.topSongs.song || [])
|
||||
.then((songs) =>
|
||||
Promise.all(
|
||||
songs.map((song) =>
|
||||
this.subsonic
|
||||
.getAlbum(this.credentials, song.albumId!)
|
||||
.then((album) => asTrack(album, song, this.customPlayers))
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
radioStations = async () => this.subsonic
|
||||
radioStations = async () =>
|
||||
this.subsonic
|
||||
.getJSON<GetInternetRadioStationsResponse>(
|
||||
this.credentials,
|
||||
"/rest/getInternetRadioStations"
|
||||
)
|
||||
.then((it) => it.internetRadioStations.internetRadioStation || [])
|
||||
.then((stations) => stations.map((it) => ({
|
||||
id: it.id,
|
||||
name: it.name,
|
||||
url: it.streamUrl,
|
||||
homePage: it.homePageUrl
|
||||
})))
|
||||
.then((stations) =>
|
||||
stations.map((it) => ({
|
||||
id: it.id,
|
||||
name: it.name,
|
||||
url: it.streamUrl,
|
||||
homePage: it.homePageUrl,
|
||||
}))
|
||||
);
|
||||
|
||||
radioStation = async (id: string) => this.radioStations()
|
||||
.then(it =>
|
||||
it.find(station => station.id === id)!
|
||||
)
|
||||
radioStation = async (id: string) =>
|
||||
this.radioStations().then((it) => it.find((station) => station.id === id)!);
|
||||
|
||||
years = async () => {
|
||||
const q: AlbumQuery = {
|
||||
_index: 0,
|
||||
_count: 100000, // FIXME: better than this, probably doesnt work anyway as max _count is 500 or something
|
||||
type: "alphabeticalByArtist",
|
||||
};
|
||||
const years = this.subsonic.getAlbumList2(this.credentials, q)
|
||||
.then(({ results }) =>
|
||||
results.map((album) => album.year || "?")
|
||||
.filter((item, i, ar) => ar.indexOf(item) === i)
|
||||
.sort()
|
||||
.map((year) => ({
|
||||
...asYear(year)
|
||||
}))
|
||||
.reverse()
|
||||
);
|
||||
return years;
|
||||
}
|
||||
const q: AlbumQuery = {
|
||||
_index: 0,
|
||||
_count: 100000, // FIXME: better than this, probably doesnt work anyway as max _count is 500 or something
|
||||
type: "alphabeticalByArtist",
|
||||
};
|
||||
const years = this.subsonic
|
||||
.getAlbumList2(this.credentials, q)
|
||||
.then(({ results }) =>
|
||||
results
|
||||
.map((album) => album.year || "?")
|
||||
.filter((item, i, ar) => ar.indexOf(item) === i)
|
||||
.sort()
|
||||
.map((year) => ({
|
||||
...asYear(year),
|
||||
}))
|
||||
.reverse()
|
||||
);
|
||||
return years;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,10 +1,21 @@
|
||||
import { v4 as uuid } from "uuid";
|
||||
import { Md5 } from "ts-md5";
|
||||
import tmp from "tmp";
|
||||
import fse from "fs-extra";
|
||||
import path from "path";
|
||||
import { pipe } from "fp-ts/lib/function";
|
||||
import { pipe } from "fp-ts/lib/function";
|
||||
import { option as O } from "fp-ts";
|
||||
|
||||
import sharp from "sharp";
|
||||
jest.mock("sharp");
|
||||
|
||||
import axios from "axios";
|
||||
jest.mock("axios");
|
||||
|
||||
import randomstring from "randomstring";
|
||||
jest.mock("randomstring");
|
||||
|
||||
import { URLBuilder } from "../src/url_builder";
|
||||
import {
|
||||
isValidImage,
|
||||
t,
|
||||
@@ -17,20 +28,13 @@ import {
|
||||
TranscodingCustomPlayers,
|
||||
CustomPlayers,
|
||||
NO_CUSTOM_PLAYERS,
|
||||
Subsonic,
|
||||
} from "../src/subsonic";
|
||||
|
||||
import sharp from "sharp";
|
||||
jest.mock("sharp");
|
||||
import { b64Encode } from "../src/b64";
|
||||
|
||||
import {
|
||||
Album,
|
||||
Artist,
|
||||
Track,
|
||||
} from "../src/music_library";
|
||||
import {
|
||||
anAlbum,
|
||||
aTrack,
|
||||
} from "./builders";
|
||||
import { Album, Artist, Track } from "../src/music_library";
|
||||
import { anAlbum, aTrack } from "./builders";
|
||||
import { BUrn } from "../src/burn";
|
||||
|
||||
describe("t", () => {
|
||||
@@ -61,26 +65,33 @@ describe("isValidImage", () => {
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("StreamClient(s)", () => {
|
||||
describe("CustomStreamClientApplications", () => {
|
||||
const customClients = TranscodingCustomPlayers.from("audio/flac,audio/mp3>audio/ogg")
|
||||
|
||||
const customClients = TranscodingCustomPlayers.from(
|
||||
"audio/flac,audio/mp3>audio/ogg"
|
||||
);
|
||||
|
||||
describe("clientFor", () => {
|
||||
describe("when there is a match", () => {
|
||||
it("should return the match", () => {
|
||||
expect(customClients.encodingFor({ mimeType: "audio/flac" })).toEqual(O.of({player: "bonob+audio/flac", mimeType:"audio/flac"}))
|
||||
expect(customClients.encodingFor({ mimeType: "audio/mp3" })).toEqual(O.of({player: "bonob+audio/mp3", mimeType:"audio/ogg"}))
|
||||
expect(customClients.encodingFor({ mimeType: "audio/flac" })).toEqual(
|
||||
O.of({ player: "bonob+audio/flac", mimeType: "audio/flac" })
|
||||
);
|
||||
expect(customClients.encodingFor({ mimeType: "audio/mp3" })).toEqual(
|
||||
O.of({ player: "bonob+audio/mp3", mimeType: "audio/ogg" })
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe("when there is no match", () => {
|
||||
it("should return undefined", () => {
|
||||
expect(customClients.encodingFor({ mimeType: "audio/bob" })).toEqual(O.none)
|
||||
expect(customClients.encodingFor({ mimeType: "audio/bob" })).toEqual(
|
||||
O.none
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("asURLSearchParams", () => {
|
||||
@@ -197,12 +208,13 @@ describe("cachingImageFetcher", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const maybeIdFromCoverArtUrn = (coverArt: BUrn | undefined) => pipe(
|
||||
coverArt,
|
||||
O.fromNullable,
|
||||
O.map(it => it.resource.split(":")[1]),
|
||||
O.getOrElseW(() => "")
|
||||
)
|
||||
const maybeIdFromCoverArtUrn = (coverArt: BUrn | undefined) =>
|
||||
pipe(
|
||||
coverArt,
|
||||
O.fromNullable,
|
||||
O.map((it) => it.resource.split(":")[1]),
|
||||
O.getOrElseW(() => "")
|
||||
);
|
||||
|
||||
const asSongJson = (track: Track) => ({
|
||||
id: track.id,
|
||||
@@ -241,8 +253,14 @@ describe("artistURN", () => {
|
||||
describe("a valid external URL", () => {
|
||||
it("should return an external URN", () => {
|
||||
expect(
|
||||
artistImageURN({ artistId: "someArtistId", artistImageURL: "http://example.com/image.jpg" })
|
||||
).toEqual({ system: "external", resource: "http://example.com/image.jpg" });
|
||||
artistImageURN({
|
||||
artistId: "someArtistId",
|
||||
artistImageURL: "http://example.com/image.jpg",
|
||||
})
|
||||
).toEqual({
|
||||
system: "external",
|
||||
resource: "http://example.com/image.jpg",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -252,7 +270,7 @@ describe("artistURN", () => {
|
||||
expect(
|
||||
artistImageURN({
|
||||
artistId: "someArtistId",
|
||||
artistImageURL: `http://example.com/${DODGY_IMAGE_NAME}`
|
||||
artistImageURL: `http://example.com/${DODGY_IMAGE_NAME}`,
|
||||
})
|
||||
).toEqual({ system: "subsonic", resource: "art:someArtistId" });
|
||||
});
|
||||
@@ -263,7 +281,7 @@ describe("artistURN", () => {
|
||||
expect(
|
||||
artistImageURN({
|
||||
artistId: "-1",
|
||||
artistImageURL: `http://example.com/${DODGY_IMAGE_NAME}`
|
||||
artistImageURL: `http://example.com/${DODGY_IMAGE_NAME}`,
|
||||
})
|
||||
).toBeUndefined();
|
||||
});
|
||||
@@ -274,7 +292,7 @@ describe("artistURN", () => {
|
||||
expect(
|
||||
artistImageURN({
|
||||
artistId: undefined,
|
||||
artistImageURL: `http://example.com/${DODGY_IMAGE_NAME}`
|
||||
artistImageURL: `http://example.com/${DODGY_IMAGE_NAME}`,
|
||||
})
|
||||
).toBeUndefined();
|
||||
});
|
||||
@@ -284,19 +302,28 @@ describe("artistURN", () => {
|
||||
describe("undefined", () => {
|
||||
describe("and artistId is valid", () => {
|
||||
it("should return artist art by artist id URN", () => {
|
||||
expect(artistImageURN({ artistId: "someArtistId", artistImageURL: undefined })).toEqual({system:"subsonic", resource:"art:someArtistId"});
|
||||
expect(
|
||||
artistImageURN({
|
||||
artistId: "someArtistId",
|
||||
artistImageURL: undefined,
|
||||
})
|
||||
).toEqual({ system: "subsonic", resource: "art:someArtistId" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("and artistId is -1", () => {
|
||||
it("should return error icon", () => {
|
||||
expect(artistImageURN({ artistId: "-1", artistImageURL: undefined })).toBeUndefined();
|
||||
expect(
|
||||
artistImageURN({ artistId: "-1", artistImageURL: undefined })
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("and artistId is undefined", () => {
|
||||
it("should return error icon", () => {
|
||||
expect(artistImageURN({ artistId: undefined, artistImageURL: undefined })).toBeUndefined();
|
||||
expect(
|
||||
artistImageURN({ artistId: undefined, artistImageURL: undefined })
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -311,10 +338,20 @@ describe("asTrack", () => {
|
||||
|
||||
describe("when the song has no artistId", () => {
|
||||
const album = anAlbum();
|
||||
const track = aTrack({ artist: { id: undefined, name: "Not in library so no id", image: undefined }});
|
||||
const track = aTrack({
|
||||
artist: {
|
||||
id: undefined,
|
||||
name: "Not in library so no id",
|
||||
image: undefined,
|
||||
},
|
||||
});
|
||||
|
||||
it("should provide no artistId", () => {
|
||||
const result = asTrack(album, { ...asSongJson(track) }, NO_CUSTOM_PLAYERS);
|
||||
const result = asTrack(
|
||||
album,
|
||||
{ ...asSongJson(track) },
|
||||
NO_CUSTOM_PLAYERS
|
||||
);
|
||||
expect(result.artist.id).toBeUndefined();
|
||||
expect(result.artist.name).toEqual("Not in library so no id");
|
||||
expect(result.artist.image).toBeUndefined();
|
||||
@@ -325,7 +362,11 @@ describe("asTrack", () => {
|
||||
const album = anAlbum();
|
||||
|
||||
it("should provide a ? to sonos", () => {
|
||||
const result = asTrack(album, { id: '1' } as any as song, NO_CUSTOM_PLAYERS);
|
||||
const result = asTrack(
|
||||
album,
|
||||
{ id: "1" } as any as song,
|
||||
NO_CUSTOM_PLAYERS
|
||||
);
|
||||
expect(result.artist.id).toBeUndefined();
|
||||
expect(result.artist.name).toEqual("?");
|
||||
expect(result.artist.image).toBeUndefined();
|
||||
@@ -338,14 +379,22 @@ describe("asTrack", () => {
|
||||
|
||||
describe("a value greater than 5", () => {
|
||||
it("should be returned as 0", () => {
|
||||
const result = asTrack(album, { ...asSongJson(track), userRating: 6 }, NO_CUSTOM_PLAYERS);
|
||||
const result = asTrack(
|
||||
album,
|
||||
{ ...asSongJson(track), userRating: 6 },
|
||||
NO_CUSTOM_PLAYERS
|
||||
);
|
||||
expect(result.rating.stars).toEqual(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a value less than 0", () => {
|
||||
it("should be returned as 0", () => {
|
||||
const result = asTrack(album, { ...asSongJson(track), userRating: -1 }, NO_CUSTOM_PLAYERS);
|
||||
const result = asTrack(
|
||||
album,
|
||||
{ ...asSongJson(track), userRating: -1 },
|
||||
NO_CUSTOM_PLAYERS
|
||||
);
|
||||
expect(result.rating.stars).toEqual(0);
|
||||
});
|
||||
});
|
||||
@@ -358,82 +407,281 @@ describe("asTrack", () => {
|
||||
describe("when there are no custom players", () => {
|
||||
describe("when subsonic reports no transcodedContentType", () => {
|
||||
it("should use the default client and default contentType", () => {
|
||||
const result = asTrack(album, {
|
||||
...asSongJson(track),
|
||||
contentType: "nonTranscodedContentType",
|
||||
transcodedContentType: undefined
|
||||
}, NO_CUSTOM_PLAYERS);
|
||||
const result = asTrack(
|
||||
album,
|
||||
{
|
||||
...asSongJson(track),
|
||||
contentType: "nonTranscodedContentType",
|
||||
transcodedContentType: undefined,
|
||||
},
|
||||
NO_CUSTOM_PLAYERS
|
||||
);
|
||||
|
||||
expect(result.encoding).toEqual({ player: "bonob", mimeType: "nonTranscodedContentType" })
|
||||
expect(result.encoding).toEqual({
|
||||
player: "bonob",
|
||||
mimeType: "nonTranscodedContentType",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("when subsonic reports a transcodedContentType", () => {
|
||||
it("should use the default client and transcodedContentType", () => {
|
||||
const result = asTrack(album, {
|
||||
...asSongJson(track),
|
||||
contentType: "nonTranscodedContentType",
|
||||
transcodedContentType: "transcodedContentType"
|
||||
}, NO_CUSTOM_PLAYERS);
|
||||
const result = asTrack(
|
||||
album,
|
||||
{
|
||||
...asSongJson(track),
|
||||
contentType: "nonTranscodedContentType",
|
||||
transcodedContentType: "transcodedContentType",
|
||||
},
|
||||
NO_CUSTOM_PLAYERS
|
||||
);
|
||||
|
||||
expect(result.encoding).toEqual({ player: "bonob", mimeType: "transcodedContentType" })
|
||||
expect(result.encoding).toEqual({
|
||||
player: "bonob",
|
||||
mimeType: "transcodedContentType",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("when there are custom players registered", () => {
|
||||
const streamClient = {
|
||||
encodingFor: jest.fn()
|
||||
}
|
||||
encodingFor: jest.fn(),
|
||||
};
|
||||
|
||||
describe("however no player is found for the default mimeType", () => {
|
||||
describe("and there is no transcodedContentType", () => {
|
||||
it("should use the default player with the default content type", () => {
|
||||
streamClient.encodingFor.mockReturnValue(O.none)
|
||||
streamClient.encodingFor.mockReturnValue(O.none);
|
||||
|
||||
const result = asTrack(album, {
|
||||
...asSongJson(track),
|
||||
contentType: "nonTranscodedContentType",
|
||||
transcodedContentType: undefined
|
||||
}, streamClient as unknown as CustomPlayers);
|
||||
|
||||
expect(result.encoding).toEqual({ player: "bonob", mimeType: "nonTranscodedContentType" });
|
||||
expect(streamClient.encodingFor).toHaveBeenCalledWith({ mimeType: "nonTranscodedContentType" });
|
||||
const result = asTrack(
|
||||
album,
|
||||
{
|
||||
...asSongJson(track),
|
||||
contentType: "nonTranscodedContentType",
|
||||
transcodedContentType: undefined,
|
||||
},
|
||||
streamClient as unknown as CustomPlayers
|
||||
);
|
||||
|
||||
expect(result.encoding).toEqual({
|
||||
player: "bonob",
|
||||
mimeType: "nonTranscodedContentType",
|
||||
});
|
||||
expect(streamClient.encodingFor).toHaveBeenCalledWith({
|
||||
mimeType: "nonTranscodedContentType",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("and there is a transcodedContentType", () => {
|
||||
it("should use the default player with the transcodedContentType", () => {
|
||||
streamClient.encodingFor.mockReturnValue(O.none)
|
||||
streamClient.encodingFor.mockReturnValue(O.none);
|
||||
|
||||
const result = asTrack(album, {
|
||||
...asSongJson(track),
|
||||
contentType: "nonTranscodedContentType",
|
||||
transcodedContentType: "transcodedContentType1"
|
||||
}, streamClient as unknown as CustomPlayers);
|
||||
|
||||
expect(result.encoding).toEqual({ player: "bonob", mimeType: "transcodedContentType1" });
|
||||
expect(streamClient.encodingFor).toHaveBeenCalledWith({ mimeType: "nonTranscodedContentType" });
|
||||
const result = asTrack(
|
||||
album,
|
||||
{
|
||||
...asSongJson(track),
|
||||
contentType: "nonTranscodedContentType",
|
||||
transcodedContentType: "transcodedContentType1",
|
||||
},
|
||||
streamClient as unknown as CustomPlayers
|
||||
);
|
||||
|
||||
expect(result.encoding).toEqual({
|
||||
player: "bonob",
|
||||
mimeType: "transcodedContentType1",
|
||||
});
|
||||
expect(streamClient.encodingFor).toHaveBeenCalledWith({
|
||||
mimeType: "nonTranscodedContentType",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("there is a player with the matching content type", () => {
|
||||
it("should use it", () => {
|
||||
const customEncoding = { player: "custom-player", mimeType: "audio/some-mime-type" };
|
||||
const customEncoding = {
|
||||
player: "custom-player",
|
||||
mimeType: "audio/some-mime-type",
|
||||
};
|
||||
streamClient.encodingFor.mockReturnValue(O.of(customEncoding));
|
||||
|
||||
const result = asTrack(album, {
|
||||
...asSongJson(track),
|
||||
contentType: "sourced-from/subsonic",
|
||||
transcodedContentType: "sourced-from/subsonic2"
|
||||
}, streamClient as unknown as CustomPlayers);
|
||||
|
||||
|
||||
const result = asTrack(
|
||||
album,
|
||||
{
|
||||
...asSongJson(track),
|
||||
contentType: "sourced-from/subsonic",
|
||||
transcodedContentType: "sourced-from/subsonic2",
|
||||
},
|
||||
streamClient as unknown as CustomPlayers
|
||||
);
|
||||
|
||||
expect(result.encoding).toEqual(customEncoding);
|
||||
expect(streamClient.encodingFor).toHaveBeenCalledWith({ mimeType: "sourced-from/subsonic" });
|
||||
});
|
||||
expect(streamClient.encodingFor).toHaveBeenCalledWith({
|
||||
mimeType: "sourced-from/subsonic",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const subsonicOK = (body: any = {}) => ({
|
||||
"subsonic-response": {
|
||||
status: "ok",
|
||||
version: "1.16.1",
|
||||
type: "subsonic",
|
||||
serverVersion: "0.45.1 (c55e6590)",
|
||||
...body,
|
||||
},
|
||||
});
|
||||
|
||||
const asGenreJson = (genre: { name: string; albumCount: number }) => ({
|
||||
songCount: 1475,
|
||||
albumCount: genre.albumCount,
|
||||
value: genre.name,
|
||||
});
|
||||
|
||||
const getGenresJson = (genres: { name: string; albumCount: number }[]) =>
|
||||
subsonicOK({
|
||||
genres: {
|
||||
genre: genres.map(asGenreJson),
|
||||
},
|
||||
});
|
||||
|
||||
const ok = (data: string | object) => ({
|
||||
status: 200,
|
||||
data,
|
||||
});
|
||||
|
||||
describe("subsonic", () => {
|
||||
const url = new URLBuilder("http://127.0.0.22:4567/some-context-path");
|
||||
const customPlayers = {
|
||||
encodingFor: jest.fn(),
|
||||
};
|
||||
const username = `user1-${uuid()}`;
|
||||
const password = `pass1-${uuid()}`;
|
||||
const credentials = { username, password };
|
||||
const subsonic = new Subsonic(url, customPlayers);
|
||||
|
||||
const mockRandomstring = jest.fn();
|
||||
const mockGET = jest.fn();
|
||||
const mockPOST = jest.fn();
|
||||
|
||||
const salt = "saltysalty";
|
||||
|
||||
const authParams = {
|
||||
u: username,
|
||||
v: "1.16.1",
|
||||
c: "bonob",
|
||||
t: t(password, salt),
|
||||
s: salt,
|
||||
};
|
||||
|
||||
const authParamsPlusJson = {
|
||||
...authParams,
|
||||
f: "json",
|
||||
};
|
||||
|
||||
const headers = {
|
||||
"User-Agent": "bonob",
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
jest.resetAllMocks();
|
||||
|
||||
randomstring.generate = mockRandomstring;
|
||||
axios.get = mockGET;
|
||||
axios.post = mockPOST;
|
||||
|
||||
mockRandomstring.mockReturnValue(salt);
|
||||
});
|
||||
|
||||
describe("getting genres", () => {
|
||||
describe("when there are none", () => {
|
||||
beforeEach(() => {
|
||||
mockGET.mockImplementationOnce(() =>
|
||||
Promise.resolve(ok(getGenresJson([])))
|
||||
);
|
||||
});
|
||||
|
||||
it("should return empty array", async () => {
|
||||
const result = await subsonic.getGenres(credentials);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
|
||||
expect(axios.get).toHaveBeenCalledWith(
|
||||
url.append({ pathname: "/rest/getGenres" }).href(),
|
||||
{
|
||||
params: asURLSearchParams(authParamsPlusJson),
|
||||
headers,
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when there is only 1 that has an albumCount > 0", () => {
|
||||
const genres = [
|
||||
{ name: "genre1", albumCount: 1 },
|
||||
{ name: "genreWithNoAlbums", albumCount: 0 },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
mockGET.mockImplementationOnce(() =>
|
||||
Promise.resolve(ok(getGenresJson(genres)))
|
||||
);
|
||||
});
|
||||
|
||||
it("should return them alphabetically sorted", async () => {
|
||||
const result = await subsonic.getGenres(credentials);
|
||||
|
||||
expect(result).toEqual([{ id: b64Encode("genre1"), name: "genre1" }]);
|
||||
|
||||
expect(axios.get).toHaveBeenCalledWith(
|
||||
url.append({ pathname: "/rest/getGenres" }).href(),
|
||||
{
|
||||
params: asURLSearchParams(authParamsPlusJson),
|
||||
headers,
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when there are many that have an albumCount > 0", () => {
|
||||
const genres = [
|
||||
{ name: "g1", albumCount: 1 },
|
||||
{ name: "g2", albumCount: 1 },
|
||||
{ name: "g3", albumCount: 1 },
|
||||
{ name: "g4", albumCount: 1 },
|
||||
{ name: "someGenreWithNoAlbums", albumCount: 0 },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
mockGET.mockImplementationOnce(() =>
|
||||
Promise.resolve(ok(getGenresJson(genres)))
|
||||
);
|
||||
});
|
||||
|
||||
it("should return them alphabetically sorted", async () => {
|
||||
const result = await subsonic.getGenres(credentials);
|
||||
|
||||
expect(result).toEqual([
|
||||
{ id: b64Encode("g1"), name: "g1" },
|
||||
{ id: b64Encode("g2"), name: "g2" },
|
||||
{ id: b64Encode("g3"), name: "g3" },
|
||||
{ id: b64Encode("g4"), name: "g4" },
|
||||
]);
|
||||
|
||||
expect(axios.get).toHaveBeenCalledWith(
|
||||
url.append({ pathname: "/rest/getGenres" }).href(),
|
||||
{
|
||||
params: asURLSearchParams(authParamsPlusJson),
|
||||
headers,
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user