Compare commits

...

14 Commits

Author SHA1 Message Date
simojenki
da1860d556 Update README 2021-09-30 19:01:45 +10:00
Simon J
b6ba9c5a52 Use bat query param rather than header when streaming as headers not passed in HEAD requests from sonos. Improve handling of failures when fetching coverArt to return undefined rather than throwing exception (#59) 2021-09-30 12:19:43 +10:00
simojenki
fbb621c7c4 Add additional debug logging around /stream endpoint 2021-09-30 10:30:49 +10:00
Simon J
1cf7453908 Awaiting responses in setPlayedSeconds (#58) 2021-09-27 21:12:53 +10:00
Simon J
c312778e13 Marking nowPlaying in smapi setPlayedSeconds handler so does not mark when sonos pre-caches a track (#57) 2021-09-27 19:13:47 +10:00
Simon J
36d0023a1e Migrate Navidrome support to generic subsonic clone support (#55)
Renaming BONOB_* env vars to BNB_*
2021-09-27 14:03:14 +10:00
simojenki
c60d2e7745 Fix build error 2021-09-21 11:41:14 +10:00
simojenki
0bc2d39a37 Disabled sonos should return false for all mutations 2021-09-21 11:15:51 +10:00
simojenki
a0043668d2 Update README: 2021-09-21 11:05:24 +10:00
simojenki
9b00c96aa0 Update README 2021-09-21 11:04:26 +10:00
Simon J
d508eaebcf Change ND genre ids to b64 encoded strings of genre, so as to differentiate between genre name and id (#54) 2021-09-21 10:53:02 +10:00
Simon J
be4fcdff24 Support for register using a seed host (#51) 2021-09-12 15:34:09 +10:00
Simon J
91cc450451 Fix bug where register failed to wrun (#49) 2021-09-09 15:02:37 +10:00
Simon J
c1815e5e48 Feature/up (#48)
* Upgrade production dependencies

* Upgrade dev dependencies
2021-09-07 22:56:59 +10:00
28 changed files with 3022 additions and 3183 deletions

View File

@@ -31,9 +31,9 @@ RUN apk add --no-cache --update --virtual .gyp \
FROM node:16.6-alpine
ENV BONOB_PORT=4534
ENV BNB_PORT=4534
EXPOSE $BONOB_PORT
EXPOSE $BNB_PORT
WORKDIR /bonob
@@ -49,5 +49,6 @@ COPY src/Sonoswsdl-1.19.4-20190411.142401-3.wsdl ./src/Sonoswsdl-1.19.4-20190411
RUN apk add --no-cache --update vips
USER nobody
WORKDIR /bonob/src
CMD ["node", "/bonob/src/app.js"]
CMD ["node", "app.js"]

139
README.md
View File

@@ -2,13 +2,13 @@
A sonos SMAPI implementation to allow registering sources of music with sonos.
Currently only a single integration allowing Navidrome to be registered with sonos. In theory as Navidrome implements the subsonic API, it *may* work with other subsonic api clones.
Support for Subsonic API clones (tested against Navidrome and Gonic).
![Build](https://github.com/simojenki/bonob/workflows/Build/badge.svg)
## Features
- Integrates with Navidrome
- Integrates with Subsonic API clones (Navidrome, Gonic)
- Browse by Artist, Albums, Genres, Playlist, Random Albums, Starred Albums, Recently Added Albums, Recently Played Albums, Most Played Albums
- Artist Art
- Album Art
@@ -18,7 +18,7 @@ Currently only a single integration allowing Navidrome to be registered with son
- Discovery of sonos devices using seed IP address
- Auto register bonob service with sonos system
- Multiple registrations within a single household.
- Transcoding performed by Navidrome with specific player for bonob/sonos, customisable by mimeType
- Transcoding support for flacs using a specific player for the flac mimeType bonob/sonos
- Ability to search by Album, Artist, Track
- Ability to play a playlist
- Ability to add/remove playlists
@@ -33,8 +33,8 @@ bonob is ditributed via docker and can be run in a number of ways
```bash
docker run \
-e BONOB_SONOS_AUTO_REGISTER=true \
-e BONOB_SONOS_DEVICE_DISCOVERY=true \
-e BNB_SONOS_AUTO_REGISTER=true \
-e BNB_SONOS_DEVICE_DISCOVERY=true \
-p 4534:4534 \
--network host \
simojenki/bonob
@@ -46,10 +46,10 @@ Now open http://localhost:4534 in your browser, you should see sonos devices, an
```bash
docker run \
-e BONOB_PORT=3000 \
-e BONOB_SONOS_SEED_HOST=192.168.1.123 \
-e BONOB_SONOS_AUTO_REGISTER=true \
-e BONOB_SONOS_DEVICE_DISCOVERY=true \
-e BNB_PORT=3000 \
-e BNB_SONOS_SEED_HOST=192.168.1.123 \
-e BNB_SONOS_AUTO_REGISTER=true \
-e BNB_SONOS_DEVICE_DISCOVERY=true \
-p 3000:3000 \
simojenki/bonob
```
@@ -66,19 +66,21 @@ Start bonob outside the LAN with sonos discovery & registration disabled as they
```bash
docker run \
-e BONOB_PORT=4534 \
-e BONOB_SONOS_SERVICE_NAME=MyAwesomeMusic \
-e BONOB_SECRET=changeme \
-e BONOB_URL=https://my-server.example.com/bonob \
-e BONOB_SONOS_AUTO_REGISTER=false \
-e BONOB_SONOS_DEVICE_DISCOVERY=false \
-e BONOB_NAVIDROME_URL=https://my-navidrome-service.com:4533 \
-e BNB_PORT=4534 \
-e BNB_SONOS_SERVICE_NAME=MyAwesomeMusic \
-e BNB_SECRET=changeme \
-e BNB_URL=https://my-server.example.com/bonob \
-e BNB_SONOS_AUTO_REGISTER=false \
-e BNB_SONOS_DEVICE_DISCOVERY=false \
-e BNB_SUBSONIC_URL=https://my-navidrome-service.com:4533 \
-p 4534:4534 \
simojenki/bonob
```
Now within the LAN that contains the sonos devices run bonob the registration process.
#### Using auto-discovery
```bash
docker run \
--rm \
@@ -86,6 +88,15 @@ docker run \
simojenki/bonob register https://my-server.example.com/bonob
```
#### Using a seed host
```bash
docker run \
--rm \
-e BNB_SONOS_SEED_HOST=192.168.1.163 \
simojenki/bonob register https://my-server.example.com/bonob
```
### Running bonob and navidrome using docker-compose
```yaml
@@ -113,72 +124,96 @@ services:
- "4534:4534"
restart: unless-stopped
environment:
BONOB_PORT: 4534
BNB_PORT: 4534
# ip address of your machine running bonob
BONOB_URL: http://192.168.1.111:4534
BONOB_SECRET: changeme
BONOB_SONOS_AUTO_REGISTER: true
BONOB_SONOS_DEVICE_DISCOVERY: true
BONOB_SONOS_SERVICE_ID: 246
BNB_URL: http://192.168.1.111:4534
BNB_SECRET: changeme
BNB_SONOS_AUTO_REGISTER: true
BNB_SONOS_DEVICE_DISCOVERY: true
BNB_SONOS_SERVICE_ID: 246
# ip address of one of your sonos devices
BONOB_SONOS_SEED_HOST: 192.168.1.121
BONOB_NAVIDROME_URL: http://navidrome:4533
BNB_SONOS_SEED_HOST: 192.168.1.121
BNB_SUBSONIC_URL: http://navidrome:4533
```
## Configuration
item | default value | description
---- | ------------- | -----------
BONOB_PORT | 4534 | Default http port for bonob to listen on
BONOB_URL | http://$(hostname):4534 | URL (including path) for bonob so that sonos devices can communicate. **This must be either the public IP or DNS entry of the bonob instance so that the sonos devices can communicate with it.**
BONOB_SECRET | bonob | secret used for encrypting credentials
BONOB_SONOS_AUTO_REGISTER | false | Whether or not to try and auto-register on startup
BONOB_SONOS_DEVICE_DISCOVERY | true | whether or not sonos device discovery should be enabled
BONOB_SONOS_SEED_HOST | undefined | sonos device seed host for discovery, or ommitted for for auto-discovery
BONOB_SONOS_SERVICE_NAME | bonob | service name for sonos
BONOB_SONOS_SERVICE_ID | 246 | service id for sonos
BONOB_NAVIDROME_URL | http://$(hostname):4533 | URL for navidrome
BONOB_NAVIDROME_CUSTOM_CLIENTS | undefined | Comma delimeted mime types for custom navidrome clients when streaming. ie. "audio/flac,audio/ogg" would use client = 'bonob+audio/flac' for flacs, and 'bonob+audio/ogg' for oggs.
BONOB_SCROBBLE_TRACKS | true | Whether to scrobble the playing of a track if it has been played for >30s
BONOB_REPORT_NOW_PLAYING | true | Whether to report a track as now playing
BONOB_ICON_FOREGROUND_COLOR | undefined | Icon foreground color in sonos app, must be a valid [svg color](https://www.december.com/html/spec/colorsvg.html)
BONOB_ICON_BACKGROUND_COLOR | undefined | Icon background color in sonos app, must be a valid [svg color](https://www.december.com/html/spec/colorsvg.html)
BNB_PORT | 4534 | Default http port for bonob to listen on
BNB_URL | http://$(hostname):4534 | URL (including path) for bonob so that sonos devices can communicate. **This must be either the public IP or DNS entry of the bonob instance so that the sonos devices can communicate with it.**
BNB_SECRET | bonob | secret used for encrypting credentials
BNB_SONOS_AUTO_REGISTER | false | Whether or not to try and auto-register on startup
BNB_SONOS_DEVICE_DISCOVERY | true | Enable/Disable sonos device discovery entirely. Setting this to 'false' will disable sonos device search, regardless of whether a seed host is specified.
BNB_SONOS_SEED_HOST | undefined | sonos device seed host for discovery, or ommitted for for auto-discovery
BNB_SONOS_SERVICE_NAME | bonob | service name for sonos
BNB_SONOS_SERVICE_ID | 246 | service id for sonos
BNB_SUBSONIC_URL | http://$(hostname):4533 | URL for subsonic clone
BNB_SUBSONIC_CUSTOM_CLIENTS | undefined | Comma delimeted mime types for custom subsonic clients when streaming. ie. "audio/flac,audio/ogg" would use client = 'bonob+audio/flac' for flacs, and 'bonob+audio/ogg' for oggs.
BNB_SCROBBLE_TRACKS | true | Whether to scrobble the playing of a track if it has been played for >30s
BNB_REPORT_NOW_PLAYING | true | Whether to report a track as now playing
BNB_ICON_FOREGROUND_COLOR | undefined | Icon foreground color in sonos app, must be a valid [svg color](https://www.december.com/html/spec/colorsvg.html)
BNB_ICON_BACKGROUND_COLOR | undefined | Icon background color in sonos app, must be a valid [svg color](https://www.december.com/html/spec/colorsvg.html)
## Initialising service within sonos app
- Configure bonob, make sure to set BONOB_URL. **bonob must be accessible from your sonos devices on BONOB_URL, otherwise it will fail to initialise within the sonos app, so make sure you test this in your browser by putting BONOB_URL in the address bar and seeing the bonob information page**
- Configure bonob, make sure to set BNB_URL. **bonob must be accessible from your sonos devices on BNB_URL, otherwise it will fail to initialise within the sonos app, so make sure you test this in your browser by putting BNB_URL in the address bar and seeing the bonob information page**
- Start bonob,
- Open sonos app on your device
- Settings -> Services & Voice -> + Add a Service
- Select your Music Service, default name is 'bonob', can be overriden with configuration BONOB_SONOS_SERVICE_NAME
- Select your Music Service, default name is 'bonob', can be overriden with configuration BNB_SONOS_SERVICE_NAME
- Press 'Add to Sonos' -> 'Linking sonos with bonob' -> Authorize
- Your device should open a browser and you should now see a login screen, enter your navidrome credentials
- Your device should open a browser and you should now see a login screen, enter your subsonic clone credentials
- You should get 'Login successful!'
- Go back into the sonos app and complete the process
- You should now be able to play music from navidrome
- Within navidrome a new player will be created, 'bonob (username)', so you can configure transcoding specifically for sonos
- You should now be able to play music on your sonos devices from you subsonic clone
- Within the subsonic clone a new player will be created, 'bonob (username)', so you can configure transcoding specifically for sonos
## Implementing a different music source other than navidrome
## Implementing a different music source other than a subsonic clone
- Implement the MusicService/MusicLibrary interface
- Startup bonob with your new implementation.
## Sample Icon colors
## A note on transcoding
tldr; Transcoding to mp3/m4a is not supported as sonos devices will not play the track. Transcoding to flac works however, use BNB_SUBSONIC_CUSTOM_CLIENTS=audio/flac if you want to transcode flac->flac ie. to downsample HD flacs (see below).
Sonos devices are very particular about how audio streams are presented to them, see [streaming basics](https://developer.sonos.com/build/content-service-add-features/streaming-basics/). When using transcoding both Navidrome and Gonic report no 'content-length', nor do they support range queries, this will cause the sonos device to fail to play the track.
## Cusomisation
### Audio File type specific transcoding options within Subsonic
In some situations you may wish to have different 'Players' within you Subsonic server so that you can configure different transcoding options depending on the file type. For example if you have flacs with a mixture of frequency formats where not all are supported by sonos [See issue #52](https://github.com/simojenki/bonob/issues/52) & [Sonos supported audio formats](https://developer.sonos.com/build/content-service-add-features/supported-audio-formats/)
In this case you could set;
```bash
BNB_SUBSONIC_CUSTOM_CLIENTS="audio/flac"
```
-e BONOB_ICON_FOREGROUND_COLOR=white \
-e BONOB_ICON_BACKGROUND_COLOR=darkgrey
This would result in 2 players in Navidrome, one called 'bonob', the other called 'bonob+audio/flac'. You could then configure a custom flac transcoder in Navidrome that re-samples the flacs to a sonos supported format, ie [Using something like this](https://stackoverflow.com/questions/41420391/ffmpeg-flac-24-bit-96khz-to-16-bit-48khz);
```bash
ffmpeg -i %s -af aresample=resampler=soxr:out_sample_fmt=s16:out_sample_rate=48000 -f flac -
```
### Changing Icon colors
```bash
-e BNB_ICON_FOREGROUND_COLOR=white \
-e BNB_ICON_BACKGROUND_COLOR=darkgrey
```
![White & Dark Grey](https://github.com/simojenki/bonob/blob/master/docs/images/whiteDarkGrey.png?raw=true)
```bash
-e BNB_ICON_FOREGROUND_COLOR=chartreuse \
-e BNB_ICON_BACKGROUND_COLOR=fuchsia
```
```
-e BONOB_ICON_FOREGROUND_COLOR=chartreuse \
-e BONOB_ICON_BACKGROUND_COLOR=fuchsia
```
![Chartreuse & Fuchsia](https://github.com/simojenki/bonob/blob/master/docs/images/chartreuseFuchsia.png?raw=true)
## Credits
- Icons courtesy of: [Navidrome](https://www.navidrome.org/), [Vectornator](https://www.vectornator.io/icons), and @jicho

View File

@@ -22,13 +22,13 @@ services:
- "4534:4534"
restart: unless-stopped
environment:
BONOB_PORT: 4534
BNB_PORT: 4534
# ip address of your machine running bonob
BONOB_URL: http://192.168.1.111:4534
BONOB_SECRET: changeme
BONOB_SONOS_SERVICE_ID: 246
BONOB_SONOS_AUTO_REGISTER: "true"
BONOB_SONOS_DEVICE_DISCOVERY: "true"
BNB_URL: http://192.168.1.111:4534
BNB_SECRET: changeme
BNB_SONOS_SERVICE_ID: 246
BNB_SONOS_AUTO_REGISTER: "true"
BNB_SONOS_DEVICE_DISCOVERY: "true"
# ip address of one of your sonos devices
BONOB_SONOS_SEED_HOST: 192.168.1.121
BONOB_NAVIDROME_URL: http://navidrome:4533
BNB_SONOS_SEED_HOST: 192.168.1.121
BNB_SUBSONIC_URL: http://navidrome:4533

View File

@@ -6,52 +6,52 @@
"author": "simojenki <simojenki@users.noreply.github.com>",
"license": "GPL-3.0-only",
"dependencies": {
"@svrooij/sonos": "^2.3.0",
"@types/express": "^4.17.11",
"@types/morgan": "^1.9.2",
"@types/node": "^14.14.22",
"@types/sharp": "^0.27.1",
"@types/underscore": "1.10.24",
"@types/uuid": "^8.3.0",
"axios": "^0.21.1",
"dayjs": "^1.10.4",
"eta": "^1.12.1",
"@svrooij/sonos": "^2.4.0",
"@types/express": "^4.17.13",
"@types/morgan": "^1.9.3",
"@types/node": "^16.7.13",
"@types/sharp": "^0.28.6",
"@types/underscore": "^1.11.3",
"@types/uuid": "^8.3.1",
"axios": "^0.21.4",
"dayjs": "^1.10.6",
"eta": "^1.12.3",
"express": "^4.17.1",
"fp-ts": "^2.9.5",
"libxmljs2": "^0.27.0",
"fp-ts": "^2.11.1",
"libxmljs2": "^0.28.0",
"morgan": "^1.10.0",
"node-html-parser": "^2.1.0",
"sharp": "^0.27.2",
"soap": "^0.37.0",
"ts-md5": "^1.2.7",
"typescript": "^4.1.3",
"underscore": "^1.12.1",
"node-html-parser": "^4.1.4",
"sharp": "^0.29.1",
"soap": "^0.42.0",
"ts-md5": "^1.2.9",
"typescript": "^4.4.2",
"underscore": "^1.13.1",
"uuid": "^8.3.2",
"winston": "^3.3.3",
"x2js": "^3.4.1"
"x2js": "^3.4.2"
},
"devDependencies": {
"@types/chai": "^4.2.14",
"@types/jest": "^26.0.20",
"@types/mocha": "^8.2.0",
"@types/supertest": "^2.0.10",
"chai": "^4.2.0",
"@types/chai": "^4.2.21",
"@types/jest": "^27.0.1",
"@types/mocha": "^9.0.0",
"@types/supertest": "^2.0.11",
"chai": "^4.3.4",
"get-port": "^5.1.1",
"image-js": "^0.32.0",
"jest": "^26.6.3",
"nodemon": "^2.0.7",
"supertest": "^6.1.3",
"ts-jest": "^26.4.4",
"image-js": "^0.33.0",
"jest": "^27.1.0",
"nodemon": "^2.0.12",
"supertest": "^6.1.6",
"ts-jest": "^27.0.5",
"ts-mockito": "^2.6.1",
"ts-node": "^9.1.1",
"ts-node": "^10.2.1",
"xmldom-ts": "^0.3.1",
"xpath-ts": "^1.3.13"
},
"scripts": {
"clean": "rm -Rf build",
"clean": "rm -Rf build node_modules",
"build": "tsc",
"dev": "BONOB_ICON_FOREGROUND_COLOR=white BONOB_ICON_BACKGROUND_COLOR=darkgrey BONOB_SONOS_SERVICE_NAME=bonobDev BONOB_SONOS_DEVICE_DISCOVERY=true nodemon -V ./src/app.ts",
"devr": "BONOB_ICON_FOREGROUND_COLOR=white BONOB_ICON_BACKGROUND_COLOR=darkgrey BONOB_SONOS_SERVICE_NAME=bonobDev BONOB_SONOS_DEVICE_DISCOVERY=true BONOB_SONOS_AUTO_REGISTER=true nodemon -V ./src/app.ts",
"dev": "BNB_ICON_FOREGROUND_COLOR=white BNB_ICON_BACKGROUND_COLOR=darkgrey BNB_SONOS_SERVICE_NAME=bonobDev BNB_SONOS_DEVICE_DISCOVERY=true nodemon -V ./src/app.ts",
"devr": "BNB_ICON_FOREGROUND_COLOR=white BNB_ICON_BACKGROUND_COLOR=darkgrey BNB_SONOS_SERVICE_NAME=bonobDev BNB_SONOS_DEVICE_DISCOVERY=true BNB_SONOS_AUTO_REGISTER=true nodemon -V ./src/app.ts",
"register-dev": "ts-node ./src/register.ts http://$(hostname):4534",
"test": "jest",
"gitinfo": "git describe --tags > .gitinfo"

View File

@@ -5,6 +5,7 @@ import crypto from "crypto";
import { Encryption } from "./encryption";
import logger from "./logger";
import { Clock, SystemClock } from "./clock";
import { b64Encode, b64Decode } from "./b64";
type AccessToken = {
value: string;
@@ -60,14 +61,12 @@ export class EncryptedAccessTokens implements AccessTokens {
}
mint = (authToken: string): string =>
Buffer.from(JSON.stringify(this.encryption.encrypt(authToken))).toString(
"base64"
);
b64Encode(JSON.stringify(this.encryption.encrypt(authToken)));
authTokenFor(value: string): string | undefined {
try {
return this.encryption.decrypt(
JSON.parse(Buffer.from(value, "base64").toString("ascii"))
JSON.parse(b64Decode(value))
);
} catch {
logger.warn("Failed to decrypt access token...");

View File

@@ -2,7 +2,7 @@ import path from "path";
import fs from "fs";
import server from "./server";
import logger from "./logger";
import { appendMimeTypeToClientFor, DEFAULT, Navidrome } from "./navidrome";
import { appendMimeTypeToClientFor, DEFAULT, Subsonic } from "./subsonic";
import encryption from "./encryption";
import { InMemoryAccessTokens, sha256 } from "./access_tokens";
import { InMemoryLinkCodes } from "./link_codes";
@@ -22,22 +22,22 @@ const bonob = bonobService(
"AppLink"
);
const sonosSystem = sonos(config.sonos.deviceDiscovery, config.sonos.seedHost);
const sonosSystem = sonos(config.sonos.discovery);
const streamUserAgent = config.navidrome.customClientsFor
? appendMimeTypeToClientFor(config.navidrome.customClientsFor.split(","))
const streamUserAgent = config.subsonic.customClientsFor
? appendMimeTypeToClientFor(config.subsonic.customClientsFor.split(","))
: DEFAULT;
const navidrome = new Navidrome(
config.navidrome.url,
const subsonic = new Subsonic(
config.subsonic.url,
encryption(config.secret),
streamUserAgent
);
const featureFlagAwareMusicService: MusicService = {
generateToken: navidrome.generateToken,
generateToken: subsonic.generateToken,
login: (authToken: string) =>
navidrome.login(authToken).then((library) => {
subsonic.login(authToken).then((library) => {
return {
...library,
scrobble: (id: string) => {
@@ -90,7 +90,7 @@ if (config.sonos.autoRegister) {
);
}
});
} else if(config.sonos.deviceDiscovery) {
} else if(config.sonos.discovery.enabled) {
sonosSystem.devices().then(devices => {
devices.forEach(d => {
logger.info(`Found device ${d.name}(${d.group}) @ ${d.ip}:${d.port}`)

2
src/b64.ts Normal file
View File

@@ -0,0 +1,2 @@
export const b64Encode = (value: string) => Buffer.from(value).toString("base64");
export const b64Decode = (value: string) => Buffer.from(value, "base64").toString("ascii");

View File

@@ -2,54 +2,91 @@ import { hostname } from "os";
import logger from "./logger";
import url from "./url_builder";
export const WORD = /^\w+$/;
type EnvVarOpts = {
default: string | undefined;
legacy: string[] | undefined;
validationPattern: RegExp | undefined;
};
export function envVar(
name: string,
opts: Partial<EnvVarOpts> = {
default: undefined,
legacy: undefined,
validationPattern: undefined,
}
) {
const result = [name, ...(opts.legacy || [])]
.map((it) => ({ key: it, value: process.env[it] }))
.find((it) => it.value);
if (
result &&
result.value &&
opts.validationPattern &&
!result.value.match(opts.validationPattern)
) {
throw `Invalid value specified for '${name}', must match ${opts.validationPattern}`;
}
if(result && result.value && result.key != name) {
logger.warn(`Configuration key '${result.key}' is deprecated, replace with '${name}'`)
}
return result?.value || opts.default;
}
export const bnbEnvVar = (key: string, opts: Partial<EnvVarOpts> = {}) =>
envVar(`BNB_${key}`, {
...opts,
legacy: [`BONOB_${key}`, ...(opts.legacy || [])],
});
export default function () {
const port = +(process.env["BONOB_PORT"] || 4534);
const bonobUrl =
process.env["BONOB_URL"] ||
process.env["BONOB_WEB_ADDRESS"] ||
`http://${hostname()}:${port}`;
const port = +bnbEnvVar("PORT", { default: "4534" })!;
const bonobUrl = bnbEnvVar("URL", {
legacy: ["BONOB_WEB_ADDRESS"],
default: `http://${hostname()}:${port}`,
})!;
if (bonobUrl.match("localhost")) {
logger.error(
"BONOB_URL containing localhost is almost certainly incorrect, sonos devices will not be able to communicate with bonob using localhost, please specify either public IP or DNS entry"
"BNB_URL containing localhost is almost certainly incorrect, sonos devices will not be able to communicate with bonob using localhost, please specify either public IP or DNS entry"
);
process.exit(1);
}
const wordFrom = (envVar: string) => {
const value = process.env[envVar];
if (value && value != "") {
if (value.match(/^\w+$/)) return value;
else throw `Invalid color specified for ${envVar}`;
} else {
return undefined;
}
};
return {
port,
bonobUrl: url(bonobUrl),
secret: process.env["BONOB_SECRET"] || "bonob",
secret: bnbEnvVar("SECRET", { default: "bonob" })!,
icons: {
foregroundColor: wordFrom("BONOB_ICON_FOREGROUND_COLOR"),
backgroundColor: wordFrom("BONOB_ICON_BACKGROUND_COLOR"),
foregroundColor: bnbEnvVar("ICON_FOREGROUND_COLOR", {
validationPattern: WORD,
}),
backgroundColor: bnbEnvVar("ICON_BACKGROUND_COLOR", {
validationPattern: WORD,
}),
},
sonos: {
serviceName: process.env["BONOB_SONOS_SERVICE_NAME"] || "bonob",
deviceDiscovery:
(process.env["BONOB_SONOS_DEVICE_DISCOVERY"] || "true") == "true",
seedHost: process.env["BONOB_SONOS_SEED_HOST"],
serviceName: bnbEnvVar("SONOS_SERVICE_NAME", { default: "bonob" })!,
discovery: {
enabled:
bnbEnvVar("SONOS_DEVICE_DISCOVERY", { default: "true" }) == "true",
seedHost: bnbEnvVar("SONOS_SEED_HOST"),
},
autoRegister:
(process.env["BONOB_SONOS_AUTO_REGISTER"] || "false") == "true",
sid: Number(process.env["BONOB_SONOS_SERVICE_ID"] || "246"),
bnbEnvVar("SONOS_AUTO_REGISTER", { default: "false" }) == "true",
sid: Number(bnbEnvVar("SONOS_SERVICE_ID", { default: "246" })),
},
navidrome: {
url: process.env["BONOB_NAVIDROME_URL"] || `http://${hostname()}:4533`,
customClientsFor:
process.env["BONOB_NAVIDROME_CUSTOM_CLIENTS"] || undefined,
subsonic: {
url: bnbEnvVar("SUBSONIC_URL", { legacy: ["BONOB_NAVIDROME_URL"], default: `http://${hostname()}:4533` })!,
customClientsFor: bnbEnvVar("SUBSONIC_CUSTOM_CLIENTS", { legacy: ["BONOB_NAVIDROME_CUSTOM_CLIENTS"] }),
},
scrobbleTracks: (process.env["BONOB_SCROBBLE_TRACKS"] || "true") == "true",
scrobbleTracks: bnbEnvVar("SCROBBLE_TRACKS", { default: "true" }) == "true",
reportNowPlaying:
(process.env["BONOB_REPORT_NOW_PLAYING"] || "true") == "true",
bnbEnvVar("REPORT_NOW_PLAYING", { default: "true" }) == "true",
};
}

View File

@@ -41,7 +41,7 @@ export type KEY =
const translations: Record<SUPPORTED_LANG, Record<KEY, string>> = {
"en-US": {
AppLinkMessage: "Linking sonos with $BONOB_SONOS_SERVICE_NAME",
AppLinkMessage: "Linking sonos with $BNB_SONOS_SERVICE_NAME",
artists: "Artists",
albums: "Albums",
tracks: "Tracks",
@@ -62,7 +62,7 @@ const translations: Record<SUPPORTED_LANG, Record<KEY, string>> = {
devices: "Devices",
services: "Services",
login: "Login",
logInToBonob: "Log in to $BONOB_SONOS_SERVICE_NAME",
logInToBonob: "Log in to $BNB_SONOS_SERVICE_NAME",
username: "Username",
password: "Password",
successfullyRegistered: "Successfully registered",
@@ -75,7 +75,7 @@ const translations: Record<SUPPORTED_LANG, Record<KEY, string>> = {
noSonosDevices: "No sonos devices",
},
"nl-NL": {
AppLinkMessage: "Sonos koppelen aan $BONOB_SONOS_SERVICE_NAME",
AppLinkMessage: "Sonos koppelen aan $BNB_SONOS_SERVICE_NAME",
artists: "Artiesten",
albums: "Albums",
tracks: "Nummers",
@@ -96,7 +96,7 @@ const translations: Record<SUPPORTED_LANG, Record<KEY, string>> = {
devices: "Apparaten",
services: "Services",
login: "Inloggen",
logInToBonob: "Login op $BONOB_SONOS_SERVICE_NAME",
logInToBonob: "Login op $BNB_SONOS_SERVICE_NAME",
username: "Gebruikersnaam",
password: "Wachtwoord",
successfullyRegistered: "Registratie geslaagd",
@@ -151,7 +151,7 @@ export default (serviceName: string): I8N =>
translations["en-US"];
return (key: KEY) => {
const value = langToUse[key]?.replace(
"$BONOB_SONOS_SERVICE_NAME",
"$BNB_SONOS_SERVICE_NAME",
serviceName
);
if (value) return value;

View File

@@ -52,6 +52,7 @@ export type AlbumSummary = {
name: string;
year: string | undefined;
genre: Genre | undefined;
coverArt: string | undefined;
artistName: string;
artistId: string;
@@ -71,6 +72,7 @@ export type Track = {
duration: number;
number: number | undefined;
genre: Genre | undefined;
coverArt: string | undefined;
album: AlbumSummary;
artist: ArtistSummary;
};
@@ -118,6 +120,7 @@ export const albumToAlbumSummary = (it: Album): AlbumSummary => ({
genre: it.genre,
artistName: it.artistName,
artistId: it.artistId,
coverArt: it.coverArt
});
export const playlistToPlaylistSummary = (it: Playlist): PlaylistSummary => ({
@@ -174,7 +177,7 @@ export interface MusicLibrary {
trackId: string;
range: string | undefined;
}): Promise<TrackStream>;
coverArt(id: string, type: "album" | "artist", size?: number): Promise<CoverArt | undefined>;
coverArt(id: string, size?: number): Promise<CoverArt | undefined>;
nowPlaying(id: string): Promise<boolean>
scrobble(id: string): Promise<boolean>
searchArtists(query: string): Promise<ArtistSummary[]>;

View File

@@ -1,4 +1,5 @@
import registrar from "./registrar";
import readConfig from "./config";
import { URLBuilder } from "./url_builder";
const params = process.argv.slice(2);
@@ -9,7 +10,10 @@ if (params.length != 1) {
}
const bonobUrl = new URLBuilder(params[0]!);
registrar(bonobUrl)()
const config = readConfig();
registrar(bonobUrl, config.sonos.discovery.seedHost)()
.then((success) => {
if (success) {
console.log(`Successfully registered bonob @ ${bonobUrl} with sonos`);

View File

@@ -1,19 +1,35 @@
import axios from "axios";
import _ from "underscore";
import logger from "./logger";
import sonos, { bonobService } from "./sonos";
import { URLBuilder } from "./url_builder";
export default (bonobUrl: URLBuilder) => async () => {
const about = bonobUrl.append({ pathname: "/about" });
logger.info(`Fetching bonob service about from ${about}`);
return axios
.get(about.href())
.then((res) => {
if (res.status == 200) return res.data;
else throw `Unexpected response status ${res.status} from ${about}`;
})
.then((about) =>
bonobService(about.service.name, about.service.sid, bonobUrl)
)
.then((bonobService) => sonos(true).register(bonobService));
};
export default (
bonobUrl: URLBuilder,
seedHost?: string
) =>
async () => {
const about = bonobUrl.append({ pathname: "/about" });
logger.info(`Fetching bonob service about from ${about}`);
return axios
.get(about.href())
.then((res) => {
if (res.status == 200) return res.data;
else throw `Unexpected response status ${res.status} from ${about}`;
})
.then((res) => {
const name = _.get(res, ["service", "name"]);
const sid = _.get(res, ["service", "sid"]);
if (!name || !sid) {
throw `Unexpected response from ${about.href()}, expected service.name and service.sid`;
}
return {
name,
sid: Number.parseInt(sid),
};
})
.then(({ name, sid }: { name: string; sid: number }) =>
bonobService(name, sid, bonobUrl)
)
.then((service) => sonos({ enabled: true, seedHost }).register(service));
};

View File

@@ -3,6 +3,7 @@ import express, { Express, Request } from "express";
import * as Eta from "eta";
import path from "path";
import sharp from "sharp";
import { v4 as uuid } from "uuid";
import { PassThrough, Transform, TransformCallback } from "stream";
@@ -15,6 +16,7 @@ import {
LOGIN_ROUTE,
CREATE_REGISTRATION_ROUTE,
REMOVE_REGISTRATION_ROUTE,
sonosifyMimeType,
} from "./smapi";
import { LinkCodes, InMemoryLinkCodes } from "./link_codes";
import { MusicService, isSuccess } from "./music_service";
@@ -288,11 +290,15 @@ function server(
app.get("/stream/track/:id", async (req, res) => {
const id = req.params["id"]!;
const trace = uuid();
logger.info(
`-> /stream/track/${id}, headers=${JSON.stringify(req.headers)}`
`${trace} bnb<- ${req.method} ${req.path}?${
JSON.stringify(req.query)
}, headers=${JSON.stringify(req.headers)}`
);
const authToken = pipe(
req.header(BONOB_ACCESS_TOKEN_HEADER),
req.query[BONOB_ACCESS_TOKEN_HEADER] as string,
O.fromNullable,
O.map((accessToken) => accessTokens.authTokenFor(accessToken)),
O.getOrElseW(() => undefined)
@@ -310,42 +316,44 @@ function server(
})
.then((stream) => ({ musicLibrary: it, stream }))
)
.then(({ musicLibrary, stream }) => {
.then(({ stream }) => {
logger.info(
`stream response from music service for ${id}, status=${
`${trace} bnb<- stream response from music service for ${id}, status=${
stream.status
}, headers=(${JSON.stringify(stream.headers)})`
);
const sonosisfyContentType = (contentType: string) =>
contentType
.split(";")
.map((it) => it.trim())
.map((it) => sonosifyMimeType(it))
.join("; ");
const respondWith = ({
status,
filter,
headers,
sendStream,
nowPlaying,
}: {
status: number;
filter: Transform;
headers: Record<string, string | undefined>;
headers: Record<string, string>;
sendStream: boolean;
nowPlaying: boolean;
}) => {
logger.info(
`<- /stream/track/${id}, status=${status}, headers=${JSON.stringify(
headers
)}`
`${trace} bnb-> ${
req.path
}, status=${status}, headers=${JSON.stringify(headers)}`
);
(nowPlaying
? musicLibrary.nowPlaying(id)
: Promise.resolve(true)
).then((_) => {
res.status(status);
Object.entries(stream.headers)
.filter(([_, v]) => v !== undefined)
.forEach(([header, value]) => res.setHeader(header, value));
if (sendStream) stream.stream.pipe(filter).pipe(res);
else res.send();
});
res.status(status);
Object.entries(headers)
.filter(([_, v]) => v !== undefined)
.forEach(([header, value]) => {
res.setHeader(header, value!);
});
if (sendStream) stream.stream.pipe(filter).pipe(res);
else res.send();
};
if (stream.status == 200) {
@@ -353,25 +361,27 @@ function server(
status: 200,
filter: new PassThrough(),
headers: {
"content-type": stream.headers["content-type"],
"content-type": sonosisfyContentType(
stream.headers["content-type"]
),
"content-length": stream.headers["content-length"],
"accept-ranges": stream.headers["accept-ranges"],
},
sendStream: req.method == "GET",
nowPlaying: req.method == "GET",
});
} else if (stream.status == 206) {
respondWith({
status: 206,
filter: new PassThrough(),
headers: {
"content-type": stream.headers["content-type"],
"content-type": sonosisfyContentType(
stream.headers["content-type"]
),
"content-length": stream.headers["content-length"],
"content-range": stream.headers["content-range"],
"accept-ranges": stream.headers["accept-ranges"],
},
sendStream: req.method == "GET",
nowPlaying: req.method == "GET",
});
} else {
respondWith({
@@ -379,7 +389,6 @@ function server(
filter: new PassThrough(),
headers: {},
sendStream: req.method == "GET",
nowPlaying: false,
});
}
});
@@ -457,25 +466,22 @@ function server(
"centre",
];
app.get("/art/:type/:ids/size/:size", (req, res) => {
app.get("/art/:ids/size/:size", (req, res) => {
const authToken = accessTokens.authTokenFor(
req.query[BONOB_ACCESS_TOKEN_HEADER] as string
);
const type = req.params["type"]!;
const ids = req.params["ids"]!.split("&");
const size = Number.parseInt(req.params["size"]!);
if (!authToken) {
return res.status(401).send();
} else if (type != "artist" && type != "album") {
return res.status(400).send();
} else if (!(size > 0)) {
return res.status(400).send();
}
return musicService
.login(authToken)
.then((it) => Promise.all(ids.map((id) => it.coverArt(id, type, size))))
.then((it) => Promise.all(ids.map((id) => it.coverArt(id, size))))
.then((coverArts) => coverArts.filter((it) => it))
.then(shuffle)
.then((coverArts) => {
@@ -513,12 +519,9 @@ function server(
}
})
.catch((e: Error) => {
logger.error(
`Failed fetching image ${type}/${ids.join("&")}/size/${size}`,
{
cause: e,
}
);
logger.error(`Failed fetching image ${ids.join("&")}/size/${size}`, {
cause: e,
});
return res.status(500).send();
});
});

View File

@@ -18,7 +18,6 @@ import {
Track,
} from "./music_service";
import { AccessTokens } from "./access_tokens";
import { BONOB_ACCESS_TOKEN_HEADER } from "./server";
import { Clock } from "./clock";
import { URLBuilder } from "./url_builder";
import { asLANGs, I8N } from "./i8n";
@@ -215,10 +214,7 @@ const genre = (bonobUrl: URLBuilder, genre: Genre) => ({
itemType: "container",
id: `genre:${genre.id}`,
title: genre.name,
albumArtURI: iconArtURI(
bonobUrl,
iconForGenre(genre.name)
).href(),
albumArtURI: iconArtURI(bonobUrl, iconForGenre(genre.name)).href(),
});
const playlist = (bonobUrl: URLBuilder, playlist: Playlist) => ({
@@ -238,31 +234,38 @@ export const playlistAlbumArtURL = (
bonobUrl: URLBuilder,
playlist: Playlist
) => {
const ids = uniq(playlist.entries.map((it) => it.album?.id).filter((it) => it));
const ids = uniq(
playlist.entries.map((it) => it.coverArt).filter((it) => it)
);
if (ids.length == 0) {
return iconArtURI(bonobUrl, "error");
} else {
return bonobUrl.append({
pathname: `/art/album/${ids.slice(0, 9).join("&")}/size/180`
pathname: `/art/${ids.slice(0, 9).join("&")}/size/180`,
});
}
};
export const defaultAlbumArtURI = (bonobUrl: URLBuilder, album: AlbumSummary) =>
bonobUrl.append({ pathname: `/art/album/${album.id}/size/180` });
export const iconArtURI = (
export const defaultAlbumArtURI = (
bonobUrl: URLBuilder,
icon: ICON
{ coverArt }: { coverArt: string | undefined }
) =>
coverArt
? bonobUrl.append({ pathname: `/art/${coverArt}/size/180` })
: iconArtURI(bonobUrl, "vinyl");
export const iconArtURI = (bonobUrl: URLBuilder, icon: ICON) =>
bonobUrl.append({
pathname: `/icon/${icon}/size/legacy`
pathname: `/icon/${icon}/size/legacy`,
});
export const defaultArtistArtURI = (
bonobUrl: URLBuilder,
artist: ArtistSummary
) => bonobUrl.append({ pathname: `/art/artist/${artist.id}/size/180` });
) => bonobUrl.append({ pathname: `/art/artist:${artist.id}/size/180` });
export const sonosifyMimeType = (mimeType: string) =>
mimeType == "audio/x-flac" ? "audio/flac" : mimeType;
export const album = (bonobUrl: URLBuilder, album: AlbumSummary) => ({
itemType: "album",
@@ -281,17 +284,17 @@ export const album = (bonobUrl: URLBuilder, album: AlbumSummary) => ({
export const track = (bonobUrl: URLBuilder, track: Track) => ({
itemType: "track",
id: `track:${track.id}`,
mimeType: track.mimeType,
mimeType: sonosifyMimeType(track.mimeType),
title: track.name,
trackMetadata: {
album: track.album.name,
albumId: track.album.id,
albumId: `album:${track.album.id}`,
albumArtist: track.artist.name,
albumArtistId: track.artist.id,
albumArtURI: defaultAlbumArtURI(bonobUrl, track.album).href(),
albumArtistId: `artist:${track.artist.id}`,
albumArtURI: defaultAlbumArtURI(bonobUrl, track).href(),
artist: track.artist.name,
artistId: track.artist.id,
artistId: `artist:${track.artist.id}`,
duration: track.duration,
genre: track.album.genre?.name,
genreId: track.album.genre?.id,
@@ -368,7 +371,7 @@ function bindSmapiSoapServiceToExpress(
const urlWithToken = (accessToken: string) =>
bonobUrl.append({
searchParams: {
"bat": accessToken,
bat: accessToken,
},
});
@@ -400,14 +403,9 @@ function bindSmapiSoapServiceToExpress(
getMediaURIResult: bonobUrl
.append({
pathname: `/stream/${type}/${typeId}`,
searchParams: { "bat": accessToken }
})
.href(),
httpHeaders: [
{
header: BONOB_ACCESS_TOKEN_HEADER,
value: accessToken,
},
],
})),
getMediaMetadata: async (
{ id }: { id: string },
@@ -506,23 +504,7 @@ function bindSmapiSoapServiceToExpress(
return musicLibrary.track(typeId).then((it) => ({
getExtendedMetadataResult: {
mediaMetadata: {
id: `track:${it.id}`,
itemType: "track",
title: it.name,
mimeType: it.mimeType,
trackMetadata: {
artistId: `artist:${it.artist.id}`,
artist: it.artist.name,
albumId: `album:${it.album.id}`,
album: it.album.name,
genre: it.genre?.name,
genreId: it.genre?.id,
duration: it.duration,
albumArtURI: defaultAlbumArtURI(
urlWithToken(accessToken),
it.album
).href(),
},
...track(urlWithToken(accessToken), it),
},
},
}));
@@ -900,18 +882,29 @@ function bindSmapiSoapServiceToExpress(
.then(({ musicLibrary, type, typeId }) => {
switch (type) {
case "track":
musicLibrary.track(typeId).then(({ duration }) => {
if (
(duration < 30 && +seconds >= 10) ||
(duration >= 30 && +seconds >= 30)
) {
musicLibrary.scrobble(typeId);
}
});
return musicLibrary
.track(typeId)
.then(({ duration }) => {
if (
(duration < 30 && +seconds >= 10) ||
(duration >= 30 && +seconds >= 30)
) {
return musicLibrary.scrobble(typeId);
} else {
return Promise.resolve(true);
}
})
.then(() => {
if (+seconds > 0) {
return musicLibrary.nowPlaying(typeId);
} else {
return Promise.resolve(true);
}
});
break;
default:
logger.info("Unsupported scrobble", { id, seconds });
break;
return Promise.resolve(true);
}
})
.then((_) => ({

View File

@@ -9,7 +9,20 @@ import qs from "querystring";
import { URLBuilder } from "./url_builder";
import { LANG } from "./i8n";
export const SONOS_LANG: LANG[] = ["en-US", "da-DK", "de-DE", "es-ES", "fr-FR", "it-IT", "ja-JP", "nb-NO", "nl-NL", "pt-BR", "sv-SE", "zh-CN"]
export const SONOS_LANG: LANG[] = [
"en-US",
"da-DK",
"de-DE",
"es-ES",
"fr-FR",
"it-IT",
"ja-JP",
"nb-NO",
"nl-NL",
"pt-BR",
"sv-SE",
"zh-CN",
];
export const PRESENTATION_AND_STRINGS_VERSION = "21";
@@ -88,8 +101,8 @@ export interface Sonos {
export const SONOS_DISABLED: Sonos = {
devices: () => Promise.resolve([]),
services: () => Promise.resolve([]),
remove: (_: number) => Promise.resolve(true),
register: (_: Service) => Promise.resolve(true),
remove: (_: number) => Promise.resolve(false),
register: (_: Service) => Promise.resolve(false),
};
export const asService = (musicService: MusicService): Service => ({
@@ -118,7 +131,7 @@ export const asDevice = (sonosDevice: SonosDevice): Device => ({
export const asRemoveCustomdForm = (csrfToken: string, sid: number) => ({
csrfToken,
sid: `${sid}`
sid: `${sid}`,
});
export const asCustomdForm = (csrfToken: string, service: Service) => ({
@@ -168,7 +181,10 @@ export function autoDiscoverySonos(sonosSeedHost?: string): Sonos {
});
};
const post = async (action: string, customdForm: (csrfToken: string) => any) => {
const post = async (
action: string,
customdForm: (csrfToken: string) => any
) => {
const anyDevice = await sonosDevices().then((devices) => head(devices));
if (!anyDevice) {
@@ -195,7 +211,7 @@ export function autoDiscoverySonos(sonosSeedHost?: string): Sonos {
);
return false;
}
const form = customdForm(csrfToken)
const form = customdForm(csrfToken);
logger.info(`${action} with sonos @ ${customd}`, { form });
return axios
.post(customd, new URLSearchParams(qs.stringify(form)), {
@@ -218,16 +234,22 @@ export function autoDiscoverySonos(sonosSeedHost?: string): Sonos {
)
.then((it) => it.map(asService)),
remove: async (sid: number) => post("remove", (csrfToken) => asRemoveCustomdForm(csrfToken, sid)),
remove: async (sid: number) =>
post("remove", (csrfToken) => asRemoveCustomdForm(csrfToken, sid)),
register: async (service: Service) => post("register", (csrfToken) => asCustomdForm(csrfToken, service)),
register: async (service: Service) =>
post("register", (csrfToken) => asCustomdForm(csrfToken, service)),
};
}
const sonos = (
discoveryEnabled: boolean = true,
sonosSeedHost: string | undefined = undefined
): Sonos =>
discoveryEnabled ? autoDiscoverySonos(sonosSeedHost) : SONOS_DISABLED;
export type Discovery = {
enabled: boolean;
seedHost?: string;
};
export default sonos;
export default (
sonosDiscovery: Discovery = { enabled: true }
): Sonos =>
sonosDiscovery.enabled
? autoDiscoverySonos(sonosDiscovery.seedHost)
: SONOS_DISABLED;

View File

@@ -21,11 +21,13 @@ import {
} from "./music_service";
import X2JS from "x2js";
import sharp from "sharp";
import _, { pick } from "underscore";
import _ from "underscore";
import axios, { AxiosRequestConfig } from "axios";
import { Encryption } from "./encryption";
import randomString from "./random_string";
import { b64Encode, b64Decode } from "./b64";
import logger from "./logger";
export const BROWSER_HEADERS = {
accept:
@@ -147,7 +149,7 @@ export type song = {
_artist: string;
_track: string | undefined;
_genre: string;
_coverArt: string;
_coverArt: string | undefined;
_created: "2004-11-08T23:36:11";
_duration: string | undefined;
_bitRate: "128";
@@ -178,6 +180,7 @@ export type entry = {
_track: string;
_year: string;
_genre: string;
_coverArt: string;
_contentType: string;
_duration: string;
_albumId: string;
@@ -222,6 +225,12 @@ export function isError(
return (subsonicResponse as SubsonicError).error !== undefined;
}
export const splitCoverArtId = (coverArt: string): [string, string] => {
const parts = coverArt.split(":").filter((it) => it.length > 0);
if (parts.length < 2) throw `'${coverArt}' is an invalid coverArt id'`;
return [parts[0]!, parts.slice(1).join(":")];
};
export type IdName = {
id: string;
name: string;
@@ -238,6 +247,9 @@ export type getAlbumListParams = {
export const MAX_ALBUM_LIST = 500;
const maybeAsCoverArt = (coverArt: string | undefined) =>
coverArt ? `coverArt:${coverArt}` : undefined;
const asTrack = (album: Album, song: song) => ({
id: song._id,
name: song._title,
@@ -245,6 +257,7 @@ const asTrack = (album: Album, song: song) => ({
duration: parseInt(song._duration || "0"),
number: parseInt(song._track || "0"),
genre: maybeAsGenre(song._genre),
coverArt: maybeAsCoverArt(song._coverArt),
album,
artist: {
id: song._artistId,
@@ -259,10 +272,11 @@ const asAlbum = (album: album) => ({
genre: maybeAsGenre(album._genre),
artistId: album._artistId,
artistName: album._artist,
coverArt: maybeAsCoverArt(album._coverArt),
});
export const asGenre = (genreName: string) => ({
id: genreName,
id: b64Encode(genreName),
name: genreName,
});
@@ -297,7 +311,7 @@ export const asURLSearchParams = (q: any) => {
return urlSearchParams;
};
export class Navidrome implements MusicService {
export class Subsonic implements MusicService {
url: string;
encryption: Encryption;
streamClientApplication: StreamClientApplication;
@@ -334,7 +348,7 @@ export class Navidrome implements MusicService {
})
.then((response) => {
if (response.status != 200 && response.status != 206) {
throw `Navidrome failed with a ${response.status || "no!"} status`;
throw `Subsonic failed with a ${response.status || "no!"} status`;
} else return response;
});
@@ -367,27 +381,23 @@ export class Navidrome implements MusicService {
)
.then((json) => json["subsonic-response"])
.then((json) => {
if (isError(json)) throw `Navidrome error:${json.error._message}`;
if (isError(json)) throw `Subsonic error:${json.error._message}`;
else return json as unknown as T;
});
generateToken = async (credentials: Credentials) =>
this.getJSON(credentials, "/rest/ping.view")
.then(() => ({
authToken: Buffer.from(
authToken: b64Encode(
JSON.stringify(this.encryption.encrypt(JSON.stringify(credentials)))
).toString("base64"),
),
userId: credentials.username,
nickname: credentials.username,
}))
.catch((e) => ({ message: `${e}` }));
parseToken = (token: string): Credentials =>
JSON.parse(
this.encryption.decrypt(
JSON.parse(Buffer.from(token, "base64").toString("ascii"))
)
);
JSON.parse(this.encryption.decrypt(JSON.parse(b64Decode(token))));
getArtists = (
credentials: Credentials
@@ -430,6 +440,7 @@ export class Navidrome implements MusicService {
genre: maybeAsGenre(album._genre),
artistId: album._artistId,
artistName: album._artist,
coverArt: maybeAsCoverArt(album._coverArt),
}));
getArtist = (
@@ -443,14 +454,7 @@ export class Navidrome implements MusicService {
.then((it) => ({
id: it._id,
name: it._name,
albums: (it.album || []).map((album) => ({
id: album._id,
name: album._name,
year: album._year,
genre: maybeAsGenre(album._genre),
artistId: it._id,
artistName: it._name,
})),
albums: this.toAlbumSummary(it.album || []),
}));
getArtistWithInfo = (credentials: Credentials, id: string) =>
@@ -490,6 +494,7 @@ export class Navidrome implements MusicService {
genre: maybeAsGenre(album._genre),
artistId: album._artistId,
artistName: album._artist,
coverArt: maybeAsCoverArt(album._coverArt),
}));
search3 = (credentials: Credentials, q: any) =>
@@ -505,12 +510,12 @@ export class Navidrome implements MusicService {
}));
async login(token: string) {
const navidrome = this;
const subsonic = this;
const credentials: Credentials = this.parseToken(token);
const musicLibrary: MusicLibrary = {
artists: (q: ArtistQuery): Promise<Result<ArtistSummary>> =>
navidrome
subsonic
.getArtists(credentials)
.then(slice2(q))
.then(([page, total]) => ({
@@ -518,34 +523,30 @@ export class Navidrome implements MusicService {
results: page.map((it) => ({ id: it.id, name: it.name })),
})),
artist: async (id: string): Promise<Artist> =>
navidrome.getArtistWithInfo(credentials, id),
albums: async (q: AlbumQuery): Promise<Result<AlbumSummary>> => {
return Promise.all([
navidrome
subsonic.getArtistWithInfo(credentials, id),
albums: async (q: AlbumQuery): Promise<Result<AlbumSummary>> =>
Promise.all([
subsonic
.getArtists(credentials)
.then((it) =>
_.inject(it, (total, artist) => total + artist.albumCount, 0)
),
navidrome
subsonic
.getJSON<GetAlbumListResponse>(credentials, "/rest/getAlbumList2", {
...pick(q, "type", "genre"),
type: q.type,
...(q.genre ? { genre: b64Decode(q.genre) } : {}),
size: 500,
offset: q._index,
})
.then((response) => response.albumList2.album || [])
.then(navidrome.toAlbumSummary),
.then(subsonic.toAlbumSummary),
]).then(([total, albums]) => ({
results: albums.slice(0, q._count),
total:
albums.length == 500
? total
: q._index + albums.length,
}));
},
album: (id: string): Promise<Album> =>
navidrome.getAlbum(credentials, id),
total: albums.length == 500 ? total : q._index + albums.length,
})),
album: (id: string): Promise<Album> => subsonic.getAlbum(credentials, id),
genres: () =>
navidrome
subsonic
.getJSON<GetGenresResponse>(credentials, "/rest/getGenres")
.then((it) =>
pipe(
@@ -553,11 +554,11 @@ export class Navidrome implements MusicService {
A.filter((it) => Number.parseInt(it._albumCount) > 0),
A.map((it) => it.__text),
A.sort(ordString),
A.map((it) => ({ id: it, name: it }))
A.map((it) => ({ id: b64Encode(it), name: it }))
)
),
tracks: (albumId: string) =>
navidrome
subsonic
.getJSON<GetAlbumResponse>(credentials, "/rest/getAlbum", {
id: albumId,
})
@@ -565,7 +566,7 @@ export class Navidrome implements MusicService {
.then((album) =>
(album.song || []).map((song) => asTrack(asAlbum(album), song))
),
track: (trackId: string) => navidrome.getTrack(credentials, trackId),
track: (trackId: string) => subsonic.getTrack(credentials, trackId),
stream: async ({
trackId,
range,
@@ -573,8 +574,8 @@ export class Navidrome implements MusicService {
trackId: string;
range: string | undefined;
}) =>
navidrome.getTrack(credentials, trackId).then((track) =>
navidrome
subsonic.getTrack(credentials, trackId).then((track) =>
subsonic
.get(
credentials,
`/rest/stream`,
@@ -608,52 +609,72 @@ export class Navidrome implements MusicService {
stream: res.data,
}))
),
coverArt: async (id: string, type: "album" | "artist", size?: number) => {
if (type == "album") {
return navidrome.getCoverArt(credentials, id, size).then((res) => ({
contentType: res.headers["content-type"],
data: Buffer.from(res.data, "binary"),
}));
} else {
return navidrome.getArtistWithInfo(credentials, id).then((artist) => {
if (artist.image.large) {
return axios
.get(artist.image.large!, {
headers: BROWSER_HEADERS,
responseType: "arraybuffer",
})
.then((res) => {
const image = Buffer.from(res.data, "binary");
if (size) {
return sharp(image)
.resize(size)
.toBuffer()
.then((resized) => ({
contentType: res.headers["content-type"],
data: resized,
}));
} else {
return {
contentType: res.headers["content-type"],
data: image,
};
}
});
} else if (artist.albums.length > 0) {
return navidrome
.getCoverArt(credentials, artist.albums[0]!.id, size)
.then((res) => ({
contentType: res.headers["content-type"],
data: Buffer.from(res.data, "binary"),
}));
} else {
coverArt: async (coverArt: string, size?: number) => {
const [type, id] = splitCoverArtId(coverArt);
if (type == "coverArt") {
return subsonic
.getCoverArt(credentials, id, size)
.then((res) => ({
contentType: res.headers["content-type"],
data: Buffer.from(res.data, "binary"),
}))
.catch((e) => {
logger.error(`Failed getting coverArt ${coverArt}: ${e}`);
return undefined;
}
});
});
} else {
return subsonic
.getArtistWithInfo(credentials, id)
.then((artist) => {
const albumsWithCoverArt = artist.albums.filter(
(it) => it.coverArt
);
if (artist.image.large) {
return axios
.get(artist.image.large!, {
headers: BROWSER_HEADERS,
responseType: "arraybuffer",
})
.then((res) => {
const image = Buffer.from(res.data, "binary");
if (size) {
return sharp(image)
.resize(size)
.toBuffer()
.then((resized) => ({
contentType: res.headers["content-type"],
data: resized,
}));
} else {
return {
contentType: res.headers["content-type"],
data: image,
};
}
});
} else if (albumsWithCoverArt.length > 0) {
return subsonic
.getCoverArt(
credentials,
splitCoverArtId(albumsWithCoverArt[0]!.coverArt!)[1],
size
)
.then((res) => ({
contentType: res.headers["content-type"],
data: Buffer.from(res.data, "binary"),
}));
} else {
return undefined;
}
})
.catch((e) => {
logger.error(`Failed getting coverArt ${coverArt}: ${e}`);
return undefined;
});
}
},
scrobble: async (id: string) =>
navidrome
subsonic
.get(credentials, `/rest/scrobble`, {
id,
submission: true,
@@ -661,7 +682,7 @@ export class Navidrome implements MusicService {
.then((_) => true)
.catch(() => false),
nowPlaying: async (id: string) =>
navidrome
subsonic
.get(credentials, `/rest/scrobble`, {
id,
submission: false,
@@ -669,7 +690,7 @@ export class Navidrome implements MusicService {
.then((_) => true)
.catch(() => false),
searchArtists: async (query: string) =>
navidrome
subsonic
.search3(credentials, { query, artistCount: 20 })
.then(({ artists }) =>
artists.map((artist) => ({
@@ -678,26 +699,26 @@ export class Navidrome implements MusicService {
}))
),
searchAlbums: async (query: string) =>
navidrome
subsonic
.search3(credentials, { query, albumCount: 20 })
.then(({ albums }) => navidrome.toAlbumSummary(albums)),
.then(({ albums }) => subsonic.toAlbumSummary(albums)),
searchTracks: async (query: string) =>
navidrome
subsonic
.search3(credentials, { query, songCount: 20 })
.then(({ songs }) =>
Promise.all(
songs.map((it) => navidrome.getTrack(credentials, it._id))
songs.map((it) => subsonic.getTrack(credentials, it._id))
)
),
playlists: async () =>
navidrome
subsonic
.getJSON<GetPlaylistsResponse>(credentials, "/rest/getPlaylists")
.then((it) => it.playlists.playlist || [])
.then((playlists) =>
playlists.map((it) => ({ id: it._id, name: it._name }))
),
playlist: async (id: string) =>
navidrome
subsonic
.getJSON<GetPlaylistResponse>(credentials, "/rest/getPlaylist", {
id,
})
@@ -714,6 +735,7 @@ export class Navidrome implements MusicService {
duration: parseInt(entry._duration || "0"),
number: trackNumber++,
genre: maybeAsGenre(entry._genre),
coverArt: maybeAsCoverArt(entry._coverArt),
album: {
id: entry._albumId,
name: entry._album,
@@ -721,6 +743,7 @@ export class Navidrome implements MusicService {
genre: maybeAsGenre(entry._genre),
artistName: entry._artist,
artistId: entry._artistId,
coverArt: maybeAsCoverArt(entry._coverArt),
},
artist: {
id: entry._artistId,
@@ -730,34 +753,34 @@ export class Navidrome implements MusicService {
};
}),
createPlaylist: async (name: string) =>
navidrome
subsonic
.getJSON<GetPlaylistResponse>(credentials, "/rest/createPlaylist", {
name,
})
.then((it) => it.playlist)
.then((it) => ({ id: it._id, name: it._name })),
deletePlaylist: async (id: string) =>
navidrome
subsonic
.getJSON<GetPlaylistResponse>(credentials, "/rest/deletePlaylist", {
id,
})
.then((_) => true),
addToPlaylist: async (playlistId: string, trackId: string) =>
navidrome
subsonic
.getJSON<GetPlaylistResponse>(credentials, "/rest/updatePlaylist", {
playlistId,
songIdToAdd: trackId,
})
.then((_) => true),
removeFromPlaylist: async (playlistId: string, indicies: number[]) =>
navidrome
subsonic
.getJSON<GetPlaylistResponse>(credentials, "/rest/updatePlaylist", {
playlistId,
songIndexToRemove: indicies,
})
.then((_) => true),
similarSongs: async (id: string) =>
navidrome
subsonic
.getJSON<GetSimilarSongsResponse>(
credentials,
"/rest/getSimilarSongs2",
@@ -767,15 +790,15 @@ export class Navidrome implements MusicService {
.then((songs) =>
Promise.all(
songs.map((song) =>
navidrome
subsonic
.getAlbum(credentials, song._albumId)
.then((album) => asTrack(album, song))
)
)
),
topSongs: async (artistId: string) =>
navidrome.getArtist(credentials, artistId).then(({ name }) =>
navidrome
subsonic.getArtist(credentials, artistId).then(({ name }) =>
subsonic
.getJSON<GetTopSongsResponse>(credentials, "/rest/getTopSongs", {
artist: name,
count: 50,
@@ -784,7 +807,7 @@ export class Navidrome implements MusicService {
.then((songs) =>
Promise.all(
songs.map((song) =>
navidrome
subsonic
.getAlbum(credentials, song._albumId)
.then((album) => asTrack(album, song))
)

17
tests/b64.test.ts Normal file
View File

@@ -0,0 +1,17 @@
import { b64Encode, b64Decode } from "../src/b64";
describe("b64", () => {
const value = "foobar100";
const encoded = Buffer.from(value).toString("base64");
describe("encode", () => {
it("should encode", () => {
expect(b64Encode(value)).toEqual(encoded);
});
});
describe("decode", () => {
it("should decode", () => {
expect(b64Decode(encoded)).toEqual(value);
});
});
});

View File

@@ -5,6 +5,7 @@ import { Credentials } from "../src/smapi";
import { Service, Device } from "../src/sonos";
import { Album, Artist, Track, albumToAlbumSummary, artistToArtistSummary, PlaylistSummary, Playlist } from "../src/music_service";
import randomString from "../src/random_string";
import { b64Encode } from "../src/b64";
const randomInt = (max: number) => Math.floor(Math.random() * Math.floor(max));
const randomIpAddress = () => `127.0.${randomInt(255)}.${randomInt(255)}`;
@@ -111,16 +112,18 @@ export function anArtist(fields: Partial<Artist> = {}): Artist {
return artist;
}
export const HIP_HOP = { id: "genre_hip_hop", name: "Hip-Hop" };
export const METAL = { id: "genre_metal", name: "Metal" };
export const NEW_WAVE = { id: "genre_new_wave", name: "New Wave" };
export const POP = { id: "genre_pop", name: "Pop" };
export const POP_ROCK = { id: "genre_pop_rock", name: "Pop Rock" };
export const REGGAE = { id: "genre_reggae", name: "Reggae" };
export const ROCK = { id: "genre_rock", name: "Rock" };
export const SKA = { id: "genre_ska", name: "Ska" };
export const PUNK = { id: "genre_punk", name: "Punk" };
export const TRIP_HOP = { id: "genre_trip_hop", name: "Trip Hop" };
export const aGenre = (name: string) => ({ id: b64Encode(name), name })
export const HIP_HOP = aGenre("Hip-Hop");
export const METAL = aGenre("Metal");
export const NEW_WAVE = aGenre("New Wave");
export const POP = aGenre("Pop");
export const POP_ROCK = aGenre("Pop Rock");
export const REGGAE = aGenre("Reggae");
export const ROCK = aGenre("Rock");
export const SKA = aGenre("Ska");
export const PUNK = aGenre("Punk");
export const TRIP_HOP = aGenre("Trip Hop");
export const SAMPLE_GENRES = [HIP_HOP, METAL, NEW_WAVE, POP, POP_ROCK, REGGAE, ROCK, SKA];
export const randomGenre = () => SAMPLE_GENRES[randomInt(SAMPLE_GENRES.length)];
@@ -138,6 +141,7 @@ export function aTrack(fields: Partial<Track> = {}): Track {
genre,
artist: artistToArtistSummary(artist),
album: albumToAlbumSummary(anAlbum({ artistId: artist.id, artistName: artist.name, genre })),
coverArt: `coverArt:${uuid()}`,
...fields,
};
}
@@ -151,6 +155,7 @@ export function anAlbum(fields: Partial<Album> = {}): Album {
year: `19${randomInt(99)}`,
artistId: `Artist ${uuid()}`,
artistName: `Artist ${randomString()}`,
coverArt: `coverArt:${uuid()}`,
...fields,
};
}
@@ -167,7 +172,8 @@ export const BLONDIE: Artist = {
year: "1976",
genre: NEW_WAVE,
artistId: BLONDIE_ID,
artistName: BLONDIE_NAME
artistName: BLONDIE_NAME,
coverArt: `coverArt:${uuid()}`
},
{
id: uuid(),
@@ -175,7 +181,8 @@ export const BLONDIE: Artist = {
year: "1978",
genre: POP_ROCK,
artistId: BLONDIE_ID,
artistName: BLONDIE_NAME
artistName: BLONDIE_NAME,
coverArt: `coverArt:${uuid()}`
},
],
image: {
@@ -192,9 +199,9 @@ export const BOB_MARLEY: Artist = {
id: BOB_MARLEY_ID,
name: BOB_MARLEY_NAME,
albums: [
{ id: uuid(), name: "Burin'", year: "1973", genre: REGGAE, artistId: BOB_MARLEY_ID, artistName: BOB_MARLEY_NAME },
{ id: uuid(), name: "Exodus", year: "1977", genre: REGGAE, artistId: BOB_MARLEY_ID, artistName: BOB_MARLEY_NAME },
{ id: uuid(), name: "Kaya", year: "1978", genre: SKA, artistId: BOB_MARLEY_ID, artistName: BOB_MARLEY_NAME },
{ id: uuid(), name: "Burin'", year: "1973", genre: REGGAE, artistId: BOB_MARLEY_ID, artistName: BOB_MARLEY_NAME, coverArt: `coverArt:${uuid()}` },
{ id: uuid(), name: "Exodus", year: "1977", genre: REGGAE, artistId: BOB_MARLEY_ID, artistName: BOB_MARLEY_NAME, coverArt: `coverArt:${uuid()}` },
{ id: uuid(), name: "Kaya", year: "1978", genre: SKA, artistId: BOB_MARLEY_ID, artistName: BOB_MARLEY_NAME, coverArt: `coverArt:${uuid()}` },
],
image: {
small: "http://localhost/BOB_MARLEY/sml",
@@ -231,6 +238,7 @@ export const METALLICA: Artist = {
genre: METAL,
artistId: METALLICA_ID,
artistName: METALLICA_NAME,
coverArt: `coverArt:${uuid()}`
},
{
id: uuid(),
@@ -238,7 +246,8 @@ export const METALLICA: Artist = {
year: "1986",
genre: METAL,
artistId: METALLICA_ID,
artistName: METALLICA_NAME,
artistName: METALLICA_NAME,
coverArt: `coverArt:${uuid()}`
},
],
image: {

View File

@@ -1,5 +1,79 @@
import { hostname } from "os";
import config from "../src/config";
import config, { envVar, WORD } from "../src/config";
describe("envVar", () => {
const OLD_ENV = process.env;
beforeEach(() => {
jest.resetModules();
process.env = { ...OLD_ENV };
process.env["bnb-var"] = "bnb-var-value";
process.env["bnb-legacy2"] = "bnb-legacy2-value";
process.env["bnb-legacy3"] = "bnb-legacy3-value";
});
afterEach(() => {
process.env = OLD_ENV;
});
describe("when the env var exists", () => {
describe("and there are no legacy env vars that match", () => {
it("should return the env var", () => {
expect(envVar("bnb-var")).toEqual("bnb-var-value");
});
});
describe("and there are legacy env vars that match", () => {
it("should return the env var", () => {
expect(
envVar("bnb-var", {
default: "not valid",
legacy: ["bnb-legacy1", "bnb-legacy2", "bnb-legacy3"],
})
).toEqual("bnb-var-value");
});
});
});
describe("when the env var doesnt exist", () => {
describe("and there are no legacy env vars specified", () => {
describe("and there is no default value specified", () => {
it("should be undefined", () => {
expect(envVar("bnb-not-set")).toBeUndefined();
});
});
describe("and there is a default value specified", () => {
it("should return the default", () => {
expect(envVar("bnb-not-set", { default: "widget" })).toEqual(
"widget"
);
});
});
});
describe("when there are legacy env vars specified", () => {
it("should return the value from the first matched legacy env var", () => {
expect(
envVar("bnb-not-set", {
legacy: ["bnb-legacy1", "bnb-legacy2", "bnb-legacy3"],
})
).toEqual("bnb-legacy2-value");
});
});
});
describe("validationPattern", () => {
it("should fail when the value does not match the pattern", () => {
expect(
() => envVar("bnb-var", {
validationPattern: /^foobar$/,
})
).toThrowError(`Invalid value specified for 'bnb-var', must match ${/^foobar$/}`)
});
});
});
describe("config", () => {
const OLD_ENV = process.env;
@@ -43,26 +117,22 @@ describe("config", () => {
}
describe("bonobUrl", () => {
describe("when BONOB_URL is specified", () => {
it("should be used", () => {
const url = "http://bonob1.example.com:8877/";
process.env["BONOB_URL"] = url;
["BNB_URL", "BONOB_URL", "BONOB_WEB_ADDRESS"].forEach(key => {
describe(`when ${key} is specified`, () => {
it("should be used", () => {
const url = "http://bonob1.example.com:8877/";
expect(config().bonobUrl.href()).toEqual(url);
process.env["BNB_URL"] = "";
process.env["BONOB_URL"] = "";
process.env["BONOB_WEB_ADDRESS"] = "";
process.env[key] = url;
expect(config().bonobUrl.href()).toEqual(url);
});
});
});
describe("when BONOB_URL is not specified, however legacy BONOB_WEB_ADDRESS is specified", () => {
it("should be used", () => {
const url = "http://bonob2.example.com:9988/";
process.env["BONOB_URL"] = "";
process.env["BONOB_WEB_ADDRESS"] = url;
expect(config().bonobUrl.href()).toEqual(url);
});
});
describe("when neither BONOB_URL nor BONOB_WEB_ADDRESS are specified", () => {
describe("when none of BNB_URL, BONOB_URL, BONOB_WEB_ADDRESS are specified", () => {
describe("when BONOB_PORT is not specified", () => {
it(`should default to http://${hostname()}:4534`, () => {
expect(config().bonobUrl.href()).toEqual(
@@ -71,6 +141,15 @@ describe("config", () => {
});
});
describe("when BNB_PORT is specified as 3322", () => {
it(`should default to http://${hostname()}:3322`, () => {
process.env["BNB_PORT"] = "3322";
expect(config().bonobUrl.href()).toEqual(
`http://${hostname()}:3322/`
);
});
});
describe("when BONOB_PORT is specified as 3322", () => {
it(`should default to http://${hostname()}:3322`, () => {
process.env["BONOB_PORT"] = "3322";
@@ -82,90 +161,69 @@ describe("config", () => {
});
});
describe("navidrome", () => {
describe("url", () => {
describe("when BONOB_NAVIDROME_URL is not specified", () => {
it(`should default to http://${hostname()}:4533`, () => {
expect(config().navidrome.url).toEqual(`http://${hostname()}:4533`);
});
});
describe("when BONOB_NAVIDROME_URL is ''", () => {
it(`should default to http://${hostname()}:4533`, () => {
process.env["BONOB_NAVIDROME_URL"] = "";
expect(config().navidrome.url).toEqual(`http://${hostname()}:4533`);
});
});
describe("when BONOB_NAVIDROME_URL is specified", () => {
it(`should use it`, () => {
const url = "http://navidrome.example.com:1234";
process.env["BONOB_NAVIDROME_URL"] = url;
expect(config().navidrome.url).toEqual(url);
});
});
});
});
describe("icons", () => {
describe("foregroundColor", () => {
describe("when BONOB_ICON_FOREGROUND_COLOR is not specified", () => {
it(`should default to undefined`, () => {
expect(config().icons.foregroundColor).toEqual(undefined);
["BNB_ICON_FOREGROUND_COLOR", "BONOB_ICON_FOREGROUND_COLOR"].forEach(k => {
describe(`when ${k} is not specified`, () => {
it(`should default to undefined`, () => {
expect(config().icons.foregroundColor).toEqual(undefined);
});
});
});
describe("when BONOB_ICON_FOREGROUND_COLOR is ''", () => {
it(`should default to undefined`, () => {
process.env["BONOB_ICON_FOREGROUND_COLOR"] = "";
expect(config().icons.foregroundColor).toEqual(undefined);
describe(`when ${k} is ''`, () => {
it(`should default to undefined`, () => {
process.env[k] = "";
expect(config().icons.foregroundColor).toEqual(undefined);
});
});
});
describe("when BONOB_ICON_FOREGROUND_COLOR is specified", () => {
it(`should use it`, () => {
process.env["BONOB_ICON_FOREGROUND_COLOR"] = "pink";
expect(config().icons.foregroundColor).toEqual("pink");
describe(`when ${k} is specified`, () => {
it(`should use it`, () => {
process.env[k] = "pink";
expect(config().icons.foregroundColor).toEqual("pink");
});
});
});
describe("when BONOB_ICON_FOREGROUND_COLOR is an invalid string", () => {
it(`should blow up`, () => {
process.env["BONOB_ICON_FOREGROUND_COLOR"] = "#dfasd";
expect(() => config()).toThrow(
"Invalid color specified for BONOB_ICON_FOREGROUND_COLOR"
);
describe(`when ${k} is an invalid string`, () => {
it(`should blow up`, () => {
process.env[k] = "#dfasd";
expect(() => config()).toThrow(
`Invalid value specified for 'BNB_ICON_FOREGROUND_COLOR', must match ${WORD}`
);
});
});
});
});
describe("backgroundColor", () => {
describe("when BONOB_ICON_BACKGROUND_COLOR is not specified", () => {
it(`should default to undefined`, () => {
expect(config().icons.backgroundColor).toEqual(undefined);
["BNB_ICON_BACKGROUND_COLOR", "BONOB_ICON_BACKGROUND_COLOR"].forEach(k => {
describe(`when ${k} is not specified`, () => {
it(`should default to undefined`, () => {
expect(config().icons.backgroundColor).toEqual(undefined);
});
});
});
describe("when BONOB_ICON_BACKGROUND_COLOR is ''", () => {
it(`should default to undefined`, () => {
process.env["BONOB_ICON_BACKGROUND_COLOR"] = "";
expect(config().icons.backgroundColor).toEqual(undefined);
describe(`when ${k} is ''`, () => {
it(`should default to undefined`, () => {
process.env[k] = "";
expect(config().icons.backgroundColor).toEqual(undefined);
});
});
});
describe("when BONOB_ICON_BACKGROUND_COLOR is specified", () => {
it(`should use it`, () => {
process.env["BONOB_ICON_BACKGROUND_COLOR"] = "blue";
expect(config().icons.backgroundColor).toEqual("blue");
describe(`when ${k} is specified`, () => {
it(`should use it`, () => {
process.env[k] = "blue";
expect(config().icons.backgroundColor).toEqual("blue");
});
});
});
describe("when BONOB_ICON_BACKGROUND_COLOR is an invalid string", () => {
it(`should blow up`, () => {
process.env["BONOB_ICON_BACKGROUND_COLOR"] = "#red";
expect(() => config()).toThrow(
"Invalid color specified for BONOB_ICON_BACKGROUND_COLOR"
);
describe(`when ${k} is an invalid string`, () => {
it(`should blow up`, () => {
process.env[k] = "#red";
expect(() => config()).toThrow(
`Invalid value specified for 'BNB_ICON_BACKGROUND_COLOR', must match ${WORD}`
);
});
});
});
});
@@ -176,9 +234,11 @@ describe("config", () => {
expect(config().secret).toEqual("bonob");
});
it("should be overridable", () => {
process.env["BONOB_SECRET"] = "new secret";
expect(config().secret).toEqual("new secret");
["BNB_SECRET", "BONOB_SECRET"].forEach(key => {
it(`should be overridable using ${key}`, () => {
process.env[key] = "new secret";
expect(config().secret).toEqual("new secret");
});
});
});
@@ -188,83 +248,116 @@ describe("config", () => {
expect(config().sonos.serviceName).toEqual("bonob");
});
it("should be overridable", () => {
process.env["BONOB_SONOS_SERVICE_NAME"] = "foobar1000";
expect(config().sonos.serviceName).toEqual("foobar1000");
["BNB_SONOS_SERVICE_NAME", "BONOB_SONOS_SERVICE_NAME"].forEach(k => {
it("should be overridable", () => {
process.env[k] = "foobar1000";
expect(config().sonos.serviceName).toEqual("foobar1000");
});
});
});
describeBooleanConfigValue(
"deviceDiscovery",
"BONOB_SONOS_DEVICE_DISCOVERY",
true,
(config) => config.sonos.deviceDiscovery
);
["BNB_SONOS_DEVICE_DISCOVERY", "BONOB_SONOS_DEVICE_DISCOVERY"].forEach(k => {
describeBooleanConfigValue(
"deviceDiscovery",
k,
true,
(config) => config.sonos.discovery.enabled
);
});
describe("seedHost", () => {
it("should default to undefined", () => {
expect(config().sonos.seedHost).toBeUndefined();
expect(config().sonos.discovery.seedHost).toBeUndefined();
});
it("should be overridable", () => {
process.env["BONOB_SONOS_SEED_HOST"] = "123.456.789.0";
expect(config().sonos.seedHost).toEqual("123.456.789.0");
["BNB_SONOS_SEED_HOST", "BONOB_SONOS_SEED_HOST"].forEach(k => {
it("should be overridable", () => {
process.env[k] = "123.456.789.0";
expect(config().sonos.discovery.seedHost).toEqual("123.456.789.0");
});
});
});
describeBooleanConfigValue(
"autoRegister",
"BONOB_SONOS_AUTO_REGISTER",
false,
(config) => config.sonos.autoRegister
);
["BNB_SONOS_AUTO_REGISTER", "BONOB_SONOS_AUTO_REGISTER"].forEach(k => {
describeBooleanConfigValue(
"autoRegister",
k,
false,
(config) => config.sonos.autoRegister
);
});
describe("sid", () => {
it("should default to 246", () => {
expect(config().sonos.sid).toEqual(246);
});
it("should be overridable", () => {
process.env["BONOB_SONOS_SERVICE_ID"] = "786";
expect(config().sonos.sid).toEqual(786);
["BNB_SONOS_SERVICE_ID", "BONOB_SONOS_SERVICE_ID"].forEach(k => {
it("should be overridable", () => {
process.env[k] = "786";
expect(config().sonos.sid).toEqual(786);
});
});
});
});
describe("navidrome", () => {
describe("subsonic", () => {
describe("url", () => {
it("should default to http://${hostname()}:4533", () => {
expect(config().navidrome.url).toEqual(`http://${hostname()}:4533`);
});
it("should be overridable", () => {
process.env["BONOB_NAVIDROME_URL"] = "http://farfaraway.com";
expect(config().navidrome.url).toEqual("http://farfaraway.com");
["BNB_SUBSONIC_URL", "BONOB_SUBSONIC_URL", "BONOB_NAVIDROME_URL"].forEach(k => {
describe(`when ${k} is not specified`, () => {
it(`should default to http://${hostname()}:4533`, () => {
expect(config().subsonic.url).toEqual(`http://${hostname()}:4533`);
});
});
describe(`when ${k} is ''`, () => {
it(`should default to http://${hostname()}:4533`, () => {
process.env[k] = "";
expect(config().subsonic.url).toEqual(`http://${hostname()}:4533`);
});
});
describe(`when ${k} is specified`, () => {
it(`should use it for ${k}`, () => {
const url = "http://navidrome.example.com:1234";
process.env[k] = url;
expect(config().subsonic.url).toEqual(url);
});
});
});
});
describe("customClientsFor", () => {
it("should default to undefined", () => {
expect(config().navidrome.customClientsFor).toBeUndefined();
expect(config().subsonic.customClientsFor).toBeUndefined();
});
it("should be overridable", () => {
process.env["BONOB_NAVIDROME_CUSTOM_CLIENTS"] = "whoop/whoop";
expect(config().navidrome.customClientsFor).toEqual("whoop/whoop");
["BNB_SUBSONIC_CUSTOM_CLIENTS", "BONOB_SUBSONIC_CUSTOM_CLIENTS", "BONOB_NAVIDROME_CUSTOM_CLIENTS"].forEach(k => {
it(`should be overridable for ${k}`, () => {
process.env[k] = "whoop/whoop";
expect(config().subsonic.customClientsFor).toEqual("whoop/whoop");
});
});
});
});
["BNB_SCROBBLE_TRACKS", "BONOB_SCROBBLE_TRACKS"].forEach(k => {
describeBooleanConfigValue(
"scrobbleTracks",
k,
true,
(config) => config.scrobbleTracks
);
});
describeBooleanConfigValue(
"scrobbleTracks",
"BONOB_SCROBBLE_TRACKS",
true,
(config) => config.scrobbleTracks
);
describeBooleanConfigValue(
"reportNowPlaying",
"BONOB_REPORT_NOW_PLAYING",
true,
(config) => config.reportNowPlaying
);
["BNB_REPORT_NOW_PLAYING", "BONOB_REPORT_NOW_PLAYING"].forEach(k => {
describeBooleanConfigValue(
"reportNowPlaying",
k,
true,
(config) => config.reportNowPlaying
);
});
});

View File

@@ -467,9 +467,9 @@ describe("InMemoryMusicService", () => {
it("should provide an array of artists", async () => {
expect(await musicLibrary.genres()).toEqual([
HIP_HOP,
SKA,
POP,
ROCK,
SKA,
]);
});
});

View File

@@ -5,6 +5,8 @@ import { pipe } from "fp-ts/lib/function";
import { ordString, fromCompare } from "fp-ts/lib/Ord";
import { shuffle } from "underscore";
import { b64Encode, b64Decode } from "../src/b64";
import {
MusicService,
Credentials,
@@ -37,9 +39,7 @@ export class InMemoryMusicService implements MusicService {
this.users[username] == password
) {
return Promise.resolve({
authToken: Buffer.from(JSON.stringify({ username, password })).toString(
"base64"
),
authToken: b64Encode(JSON.stringify({ username, password })),
userId: username,
nickname: username,
});
@@ -49,9 +49,7 @@ export class InMemoryMusicService implements MusicService {
}
login(token: string): Promise<MusicLibrary> {
const credentials = JSON.parse(
Buffer.from(token, "base64").toString("ascii")
) as Credentials;
const credentials = JSON.parse(b64Decode(token)) as Credentials;
if (this.users[credentials.username] != credentials.password)
return Promise.reject("Invalid auth token");
@@ -127,7 +125,7 @@ export class InMemoryMusicService implements MusicService {
),
stream: (_: { trackId: string; range: string | undefined }) =>
Promise.reject("unsupported operation"),
coverArt: (id: string, _: "album" | "artist", size?: number) =>
coverArt: (id: string, size?: number) =>
Promise.reject(`Cannot retrieve coverArt for ${id}, size ${size}`),
scrobble: async (_: string) => {
return Promise.resolve(true);

137
tests/registrar.test.ts Normal file
View File

@@ -0,0 +1,137 @@
import axios from "axios";
jest.mock("axios");
const fakeSonos = {
register: jest.fn(),
};
import sonos, { bonobService } from "../src/sonos";
jest.mock("../src/sonos");
import registrar from "../src/registrar";
import { URLBuilder } from "../src/url_builder";
describe("registrar", () => {
beforeEach(() => {
jest.clearAllMocks();
jest.resetAllMocks();
});
describe("when the bonob service can not be found", () => {
it("should fail", async () => {
const status = 409;
(axios.get as jest.Mock).mockResolvedValue({
status,
});
const bonobUrl = new URLBuilder("http://fail.example.com/bonob");
return expect(registrar(bonobUrl)()).rejects.toEqual(
`Unexpected response status ${status} from ${bonobUrl
.append({ pathname: "/about" })
.href()}`
);
});
});
describe("when the bonob service returns unexpected content", () => {
it("should fail", async () => {
(axios.get as jest.Mock).mockResolvedValue({
status: 200,
// invalid response from /about as does not have name and sid
data: {}
});
const bonobUrl = new URLBuilder("http://fail.example.com/bonob");
return expect(registrar(bonobUrl)()).rejects.toEqual(
`Unexpected response from ${bonobUrl
.append({ pathname: "/about" })
.href()}, expected service.name and service.sid`
);
});
});
describe("when the bonob service can be found", () => {
const bonobUrl = new URLBuilder("http://success.example.com/bonob");
const serviceDetails = {
name: "bob",
sid: 123,
};
const service = "service";
beforeEach(() => {
(axios.get as jest.Mock).mockResolvedValue({
status: 200,
data: {
service: serviceDetails,
},
});
(bonobService as jest.Mock).mockResolvedValue(service);
(sonos as jest.Mock).mockReturnValue(fakeSonos);
});
describe("seedHost", () => {
describe("is specified", () => {
it("should register using the seed host", async () => {
fakeSonos.register.mockResolvedValue(true);
const seedHost = "127.0.0.11";
expect(await registrar(bonobUrl, seedHost)()).toEqual(
true
);
expect(bonobService).toHaveBeenCalledWith(
serviceDetails.name,
serviceDetails.sid,
bonobUrl
);
expect(sonos).toHaveBeenCalledWith({ enabled: true, seedHost });
expect(fakeSonos.register).toHaveBeenCalledWith(service);
});
});
describe("is not specified", () => {
it("should register without using the seed host", async () => {
fakeSonos.register.mockResolvedValue(true);
expect(await registrar(bonobUrl)()).toEqual(
true
);
expect(bonobService).toHaveBeenCalledWith(
serviceDetails.name,
serviceDetails.sid,
bonobUrl
);
expect(sonos).toHaveBeenCalledWith({ enabled: true });
expect(fakeSonos.register).toHaveBeenCalledWith(service);
});
});
});
describe("when registration succeeds", () => {
it("should fetch the service details and register", async () => {
fakeSonos.register.mockResolvedValue(true);
expect(await registrar(bonobUrl)()).toEqual(
true
);
});
});
describe("when registration fails", () => {
it("should fetch the service details and register", async () => {
fakeSonos.register.mockResolvedValue(false);
expect(await registrar(bonobUrl)()).toEqual(
false
);
});
});
});
});

View File

@@ -186,7 +186,7 @@ describe("server", () => {
bonobUrl,
new InMemoryMusicService(),
{
version: "v123.456"
version: "v123.456",
}
);
@@ -230,49 +230,48 @@ describe("server", () => {
name: "bonobMissing",
sid: 88,
});
const fakeSonos: Sonos = {
devices: () => Promise.resolve([]),
services: () =>
Promise.resolve([]),
services: () => Promise.resolve([]),
remove: () => Promise.resolve(false),
register: () => Promise.resolve(false),
};
const server = makeServer(
fakeSonos,
missingBonobService,
bonobUrl,
new InMemoryMusicService()
);
describe("devices list", () => {
it("should be empty", async () => {
const res = await request(server)
.get(bonobUrl.append({ pathname: "/" }).path())
.set("accept-language", acceptLanguage)
.send();
expect(res.status).toEqual(200);
expect(res.text).toMatch(`<h2>${lang("devices")} \(0\)</h2>`);
expect(res.text).not.toMatch(/class=device/);
expect(res.text).toContain(lang("noSonosDevices"));
expect(res.text).toContain(lang("noSonosDevices"));
});
});
describe("services", () => {
it("should be empty", async () => {
const res = await request(server)
.get(bonobUrl.append({ pathname: "/" }).path())
.set("accept-language", acceptLanguage)
.send();
expect(res.status).toEqual(200);
expect(res.text).toMatch(`<h2>${lang("services")} \(0\)</h2>`);
});
});
});
describe("there are 2 devices and bonob is not registered", () => {
const service1 = aService({
name: "s1",
@@ -294,19 +293,19 @@ describe("server", () => {
name: "bonobMissing",
sid: 88,
});
const device1: Device = aDevice({
name: "device1",
ip: "172.0.0.1",
port: 4301,
});
const device2: Device = aDevice({
name: "device2",
ip: "172.0.0.2",
port: 4302,
});
const fakeSonos: Sonos = {
devices: () => Promise.resolve([device1, device2]),
services: () =>
@@ -314,35 +313,35 @@ describe("server", () => {
remove: () => Promise.resolve(false),
register: () => Promise.resolve(false),
};
const server = makeServer(
fakeSonos,
missingBonobService,
bonobUrl,
new InMemoryMusicService()
);
describe("devices list", () => {
it("should contain the devices returned from sonos", async () => {
const res = await request(server)
.get(bonobUrl.append({ pathname: "/" }).path())
.set("accept-language", acceptLanguage)
.send();
expect(res.status).toEqual(200);
expect(res.text).toMatch(`<h2>${lang("devices")} \(2\)</h2>`);
expect(res.text).toMatch(/device1\s+\(172.0.0.1:4301\)/);
expect(res.text).toMatch(/device2\s+\(172.0.0.2:4302\)/);
});
});
describe("services", () => {
it("should contain a list of services returned from sonos", async () => {
const res = await request(server)
.get(bonobUrl.append({ pathname: "/" }).path())
.set("accept-language", acceptLanguage)
.send();
expect(res.status).toEqual(200);
expect(res.text).toMatch(`<h2>${lang("services")} \(4\)</h2>`);
expect(res.text).toMatch(/s1\s+\(1\)/);
@@ -351,7 +350,7 @@ describe("server", () => {
expect(res.text).toMatch(/s4\s+\(4\)/);
});
});
describe("registration status", () => {
it("should be not-registered", async () => {
const res = await request(server)
@@ -372,10 +371,10 @@ describe("server", () => {
});
});
});
describe("there are 2 devices and bonob is registered", () => {
const service1 = aService();
const service2 = aService();
const device1: Device = aDevice({
@@ -383,32 +382,33 @@ describe("server", () => {
ip: "172.0.0.1",
port: 4301,
});
const device2: Device = aDevice({
name: "device2",
ip: "172.0.0.2",
port: 4302,
});
const bonobService = aService({
name: "bonobNotMissing",
sid: 99,
});
const fakeSonos: Sonos = {
devices: () => Promise.resolve([device1, device2]),
services: () => Promise.resolve([service1, service2, bonobService]),
services: () =>
Promise.resolve([service1, service2, bonobService]),
remove: () => Promise.resolve(false),
register: () => Promise.resolve(false),
};
const server = makeServer(
fakeSonos,
bonobService,
bonobUrl,
new InMemoryMusicService()
);
describe("registration status", () => {
it("should be registered", async () => {
const res = await request(server)
@@ -707,7 +707,6 @@ describe("server", () => {
const musicLibrary = {
stream: jest.fn(),
scrobble: jest.fn(),
nowPlaying: jest.fn(),
};
let now = dayjs();
const accessTokens = new ExpiringAccessTokens({ now: () => now });
@@ -756,13 +755,14 @@ describe("server", () => {
it("should return a 401", async () => {
now = now.add(1, "day");
const res = await request(server)
.head(
bonobUrl
.append({ pathname: `/stream/track/${trackId}` })
.path()
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
const res = await request(server).head(
bonobUrl
.append({
pathname: `/stream/track/${trackId}`,
searchParams: { bat: accessToken },
})
.path()
);
expect(res.status).toEqual(401);
});
@@ -774,7 +774,8 @@ describe("server", () => {
const trackStream = {
status: 200,
headers: {
"content-type": "audio/mp3; charset=utf-8",
// audio/x-flac should be mapped to x-flac
"content-type": "audio/x-flac; whoop; foo-bar",
"content-length": "123",
},
stream: streamContent(""),
@@ -786,14 +787,13 @@ describe("server", () => {
const res = await request(server)
.head(
bonobUrl
.append({ pathname: `/stream/track/${trackId}` })
.append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path()
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
);
expect(res.status).toEqual(trackStream.status);
expect(res.headers["content-type"]).toEqual(
"audio/mp3; charset=utf-8"
"audio/flac; whoop; foo-bar"
);
expect(res.headers["content-length"]).toEqual("123");
expect(res.body).toEqual({});
@@ -812,8 +812,10 @@ describe("server", () => {
musicLibrary.stream.mockResolvedValue(trackStream);
const res = await request(server)
.head(`/stream/track/${trackId}`)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
.head(bonobUrl
.append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path()
);
expect(res.status).toEqual(404);
expect(res.body).toEqual({});
@@ -840,10 +842,9 @@ describe("server", () => {
const res = await request(server)
.get(
bonobUrl
.append({ pathname: `/stream/track/${trackId}` })
.append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path()
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
);
expect(res.status).toEqual(401);
});
@@ -863,14 +864,12 @@ describe("server", () => {
const res = await request(server)
.get(
bonobUrl
.append({ pathname: `/stream/track/${trackId}` })
.append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path()
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
);
expect(res.status).toEqual(404);
expect(musicLibrary.nowPlaying).not.toHaveBeenCalled();
expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId });
});
});
@@ -883,26 +882,25 @@ describe("server", () => {
const stream = {
status: 200,
headers: {
"content-type": "audio/mp3",
// audio/x-flac should be mapped to audio/flac
"content-type": "audio/x-flac; charset=utf-8",
},
stream: streamContent(content),
};
musicService.login.mockResolvedValue(musicLibrary);
musicLibrary.stream.mockResolvedValue(stream);
musicLibrary.nowPlaying.mockResolvedValue(true);
const res = await request(server)
.get(
bonobUrl
.append({ pathname: `/stream/track/${trackId}` })
.append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path()
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
);
expect(res.status).toEqual(stream.status);
expect(res.headers["content-type"]).toEqual(
"audio/mp3; charset=utf-8"
"audio/flac; charset=utf-8"
);
expect(res.header["accept-ranges"]).toBeUndefined();
expect(res.headers["content-length"]).toEqual(
@@ -911,7 +909,6 @@ describe("server", () => {
expect(Object.keys(res.headers)).not.toContain("content-range");
expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.nowPlaying).toHaveBeenCalledWith(trackId);
expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId });
});
});
@@ -931,15 +928,13 @@ describe("server", () => {
musicService.login.mockResolvedValue(musicLibrary);
musicLibrary.stream.mockResolvedValue(stream);
musicLibrary.nowPlaying.mockResolvedValue(true);
const res = await request(server)
.get(
bonobUrl
.append({ pathname: `/stream/track/${trackId}` })
.append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path()
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
);
expect(res.status).toEqual(stream.status);
expect(res.headers["content-type"]).toEqual(
@@ -951,7 +946,6 @@ describe("server", () => {
expect(Object.keys(res.headers)).not.toContain("content-range");
expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.nowPlaying).toHaveBeenCalledWith(trackId);
expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId });
});
});
@@ -970,15 +964,13 @@ describe("server", () => {
musicService.login.mockResolvedValue(musicLibrary);
musicLibrary.stream.mockResolvedValue(stream);
musicLibrary.nowPlaying.mockResolvedValue(true);
const res = await request(server)
.get(
bonobUrl
.append({ pathname: `/stream/track/${trackId}` })
.append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path()
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
);
expect(res.status).toEqual(stream.status);
expect(res.header["content-type"]).toEqual(
@@ -990,7 +982,6 @@ describe("server", () => {
expect(res.header["content-range"]).toBeUndefined();
expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.nowPlaying).toHaveBeenCalledWith(trackId);
expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId });
});
});
@@ -1010,15 +1001,13 @@ describe("server", () => {
musicService.login.mockResolvedValue(musicLibrary);
musicLibrary.stream.mockResolvedValue(stream);
musicLibrary.nowPlaying.mockResolvedValue(true);
const res = await request(server)
.get(
bonobUrl
.append({ pathname: `/stream/track/${trackId}` })
.append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path()
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
);
expect(res.status).toEqual(stream.status);
expect(res.header["content-type"]).toEqual(
@@ -1032,7 +1021,6 @@ describe("server", () => {
);
expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.nowPlaying).toHaveBeenCalledWith(trackId);
expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId });
});
});
@@ -1053,17 +1041,15 @@ describe("server", () => {
musicService.login.mockResolvedValue(musicLibrary);
musicLibrary.stream.mockResolvedValue(stream);
musicLibrary.nowPlaying.mockResolvedValue(true);
const requestedRange = "40-";
const res = await request(server)
.get(
bonobUrl
.append({ pathname: `/stream/track/${trackId}` })
.append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path()
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken)
.set("Range", requestedRange);
expect(res.status).toEqual(stream.status);
@@ -1076,7 +1062,6 @@ describe("server", () => {
expect(res.header["content-range"]).toBeUndefined();
expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.nowPlaying).toHaveBeenCalledWith(trackId);
expect(musicLibrary.stream).toHaveBeenCalledWith({
trackId,
range: requestedRange,
@@ -1099,15 +1084,13 @@ describe("server", () => {
musicService.login.mockResolvedValue(musicLibrary);
musicLibrary.stream.mockResolvedValue(stream);
musicLibrary.nowPlaying.mockResolvedValue(true);
const res = await request(server)
.get(
bonobUrl
.append({ pathname: `/stream/track/${trackId}` })
.append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path()
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken)
.set("Range", "4000-5000");
expect(res.status).toEqual(stream.status);
@@ -1122,7 +1105,6 @@ describe("server", () => {
);
expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.nowPlaying).toHaveBeenCalledWith(trackId);
expect(musicLibrary.stream).toHaveBeenCalledWith({
trackId,
range: "4000-5000",
@@ -1173,7 +1155,7 @@ describe("server", () => {
describe("when there is no access-token", () => {
it("should return a 401", async () => {
const res = await request(server).get(`/art/album/123/size/180`);
const res = await request(server).get(`/art/coverArt:123/size/180`);
expect(res.status).toEqual(401);
});
@@ -1184,7 +1166,7 @@ describe("server", () => {
now = now.add(1, "day");
const res = await request(server).get(
`/art/album/123/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
`/art/coverArt:123/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
);
expect(res.status).toEqual(401);
@@ -1192,18 +1174,6 @@ describe("server", () => {
});
describe("when there is a valid access token", () => {
describe("some invalid art type", () => {
it("should return a 400", async () => {
const res = await request(server)
.get(
`/art/foo/${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
expect(res.status).toEqual(400);
});
});
describe("artist art", () => {
["0", "-1", "foo"].forEach((size) => {
describe(`invalid size of ${size}`, () => {
@@ -1211,7 +1181,7 @@ describe("server", () => {
musicService.login.mockResolvedValue(musicLibrary);
const res = await request(server)
.get(
`/art/artist/${albumId}/size/${size}?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
`/art/artist:${albumId}/size/${size}?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1231,7 +1201,7 @@ describe("server", () => {
const res = await request(server)
.get(
`/art/artist/${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
`/art/artist:${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1242,8 +1212,7 @@ describe("server", () => {
expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.coverArt).toHaveBeenCalledWith(
albumId,
"artist",
`artist:${albumId}`,
180
);
});
@@ -1257,7 +1226,7 @@ describe("server", () => {
const res = await request(server)
.get(
`/art/artist/${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
`/art/artist:${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1267,11 +1236,24 @@ describe("server", () => {
});
describe("fetching multiple images as a collage", () => {
const png = fs.readFileSync(path.join(__dirname, '..', 'docs', 'images', 'chartreuseFuchsia.png'));
const png = fs.readFileSync(
path.join(
__dirname,
"..",
"docs",
"images",
"chartreuseFuchsia.png"
)
);
describe("fetching a collage of 4 when all are available", () => {
it("should return the image and a 200", async () => {
const ids = ["1", "2", "3", "4"];
const ids = [
"artist:1",
"artist:2",
"coverArt:3",
"coverArt:4",
];
musicService.login.mockResolvedValue(musicLibrary);
@@ -1285,7 +1267,7 @@ describe("server", () => {
const res = await request(server)
.get(
`/art/artist/${ids.join(
`/art/${ids.join(
"&"
)}/size/200?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
@@ -1296,11 +1278,7 @@ describe("server", () => {
expect(musicService.login).toHaveBeenCalledWith(authToken);
ids.forEach((id) => {
expect(musicLibrary.coverArt).toHaveBeenCalledWith(
id,
"artist",
200
);
expect(musicLibrary.coverArt).toHaveBeenCalledWith(id, 200);
});
const image = await Image.load(res.body);
@@ -1311,7 +1289,7 @@ describe("server", () => {
describe("fetching a collage of 4, however only 1 is available", () => {
it("should return the single image", async () => {
const ids = ["1", "2", "3", "4"];
const ids = ["artist:1", "artist:2", "artist:3", "artist:4"];
musicService.login.mockResolvedValue(musicLibrary);
@@ -1321,26 +1299,28 @@ describe("server", () => {
musicLibrary.coverArt.mockResolvedValueOnce(
coverArtResponse({
data: png,
contentType: "image/some-mime-type"
contentType: "image/some-mime-type",
})
);
const res = await request(server)
.get(
`/art/artist/${ids.join(
`/art/${ids.join(
"&"
)}/size/200?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
expect(res.status).toEqual(200);
expect(res.header["content-type"]).toEqual("image/some-mime-type");
expect(res.header["content-type"]).toEqual(
"image/some-mime-type"
);
});
});
describe("fetching a collage of 4 and all are missing", () => {
it("should return a 404", async () => {
const ids = ["1", "2", "3", "4"];
const ids = ["artist:1", "artist:2", "artist:3", "artist:4"];
musicService.login.mockResolvedValue(musicLibrary);
@@ -1350,7 +1330,7 @@ describe("server", () => {
const res = await request(server)
.get(
`/art/artist/${ids.join(
`/art/${ids.join(
"&"
)}/size/200?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
@@ -1362,7 +1342,17 @@ describe("server", () => {
describe("fetching a collage of 9 when all are available", () => {
it("should return the image and a 200", async () => {
const ids = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
const ids = [
"artist:1",
"artist:2",
"coverArt:3",
"artist:4",
"artist:5",
"artist:6",
"artist:7",
"artist:8",
"artist:9",
];
musicService.login.mockResolvedValue(musicLibrary);
@@ -1376,7 +1366,7 @@ describe("server", () => {
const res = await request(server)
.get(
`/art/artist/${ids.join(
`/art/${ids.join(
"&"
)}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
@@ -1387,11 +1377,7 @@ describe("server", () => {
expect(musicService.login).toHaveBeenCalledWith(authToken);
ids.forEach((id) => {
expect(musicLibrary.coverArt).toHaveBeenCalledWith(
id,
"artist",
180
);
expect(musicLibrary.coverArt).toHaveBeenCalledWith(id, 180);
});
const image = await Image.load(res.body);
@@ -1402,7 +1388,17 @@ describe("server", () => {
describe("fetching a collage of 9 when only 2 are available", () => {
it("should still return an image and a 200", async () => {
const ids = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
const ids = [
"artist:1",
"artist:2",
"artist:3",
"artist:4",
"artist:5",
"artist:6",
"artist:7",
"artist:8",
"artist:9",
];
musicService.login.mockResolvedValue(musicLibrary);
@@ -1426,7 +1422,7 @@ describe("server", () => {
const res = await request(server)
.get(
`/art/artist/${ids.join(
`/art/${ids.join(
"&"
)}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
@@ -1437,22 +1433,30 @@ describe("server", () => {
expect(musicService.login).toHaveBeenCalledWith(authToken);
ids.forEach((id) => {
expect(musicLibrary.coverArt).toHaveBeenCalledWith(
id,
"artist",
180
);
expect(musicLibrary.coverArt).toHaveBeenCalledWith(id, 180);
});
const image = await Image.load(res.body);
expect(image.width).toEqual(180);
expect(image.height).toEqual(180);
});
});
});
describe("fetching a collage of 11", () => {
it("should still return an image and a 200, though will only display 9", async () => {
const ids = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"];
const ids = [
"artist:1",
"artist:2",
"artist:3",
"artist:4",
"artist:5",
"artist:6",
"artist:7",
"artist:8",
"artist:9",
"artist:10",
"artist:11",
];
musicService.login.mockResolvedValue(musicLibrary);
@@ -1466,7 +1470,7 @@ describe("server", () => {
const res = await request(server)
.get(
`/art/artist/${ids.join(
`/art/${ids.join(
"&"
)}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
@@ -1477,18 +1481,14 @@ describe("server", () => {
expect(musicService.login).toHaveBeenCalledWith(authToken);
ids.forEach((id) => {
expect(musicLibrary.coverArt).toHaveBeenCalledWith(
id,
"artist",
180
);
expect(musicLibrary.coverArt).toHaveBeenCalledWith(id, 180);
});
const image = await Image.load(res.body);
expect(image.width).toEqual(180);
expect(image.height).toEqual(180);
});
});
});
describe("when the image is not available", () => {
it("should return a 404", async () => {
@@ -1498,7 +1498,7 @@ describe("server", () => {
const res = await request(server)
.get(
`/art/artist/${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
`/art/coverArt:${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1515,7 +1515,7 @@ describe("server", () => {
const res = await request(server)
.get(
`/art/artist/${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
`/art/artist:${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1531,7 +1531,7 @@ describe("server", () => {
musicService.login.mockResolvedValue(musicLibrary);
const res = await request(server)
.get(
`/art/album/${albumId}/size/${size}?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
`/art/coverArt:${albumId}/size/${size}?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1553,7 +1553,7 @@ describe("server", () => {
const res = await request(server)
.get(
`/art/album/${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
`/art/coverArt:${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1564,8 +1564,7 @@ describe("server", () => {
expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.coverArt).toHaveBeenCalledWith(
albumId,
"album",
`coverArt:${albumId}`,
180
);
});
@@ -1578,7 +1577,7 @@ describe("server", () => {
const res = await request(server)
.get(
`/art/album/${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
`/art/album:${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1593,7 +1592,7 @@ describe("server", () => {
const res = await request(server)
.get(
`/art/album/${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
`/art/album:${albumId}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
)
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1723,12 +1722,18 @@ describe("server", () => {
expect(svg).toContain(`fill="brightpink"`);
});
function itShouldBeFestive(theme: string, date: string, id: string, color1: string, color2: string) {
function itShouldBeFestive(
theme: string,
date: string,
id: string,
color1: string,
color2: string
) {
it(`should return a ${theme} icon on ${date}`, async () => {
const response = await request(
server({ now: () => dayjs(date) })
).get(`/icon/${type}/size/180`);
expect(response.status).toEqual(200);
const svg = Buffer.from(response.body).toString();
expect(svg).toContain(`id="${id}"`);
@@ -1737,14 +1742,50 @@ describe("server", () => {
});
}
itShouldBeFestive("christmas '22", "2022/12/25", "christmas", "red", "green")
itShouldBeFestive("christmas '23", "2023/12/25", "christmas", "red", "green")
itShouldBeFestive(
"christmas '22",
"2022/12/25",
"christmas",
"red",
"green"
);
itShouldBeFestive(
"christmas '23",
"2023/12/25",
"christmas",
"red",
"green"
);
itShouldBeFestive("halloween", "2022/10/31", "halloween", "black", "orange")
itShouldBeFestive("halloween", "2023/10/31", "halloween", "black", "orange")
itShouldBeFestive(
"halloween",
"2022/10/31",
"halloween",
"black",
"orange"
);
itShouldBeFestive(
"halloween",
"2023/10/31",
"halloween",
"black",
"orange"
);
itShouldBeFestive("cny '22", "2022/02/01", "yoTiger", "red", "yellow")
itShouldBeFestive("cny '23", "2023/01/22", "yoRabbit", "red", "yellow")
itShouldBeFestive(
"cny '22",
"2022/02/01",
"yoTiger",
"red",
"yellow"
);
itShouldBeFestive(
"cny '23",
"2023/01/22",
"yoRabbit",
"red",
"yellow"
);
});
});
});

View File

@@ -23,6 +23,7 @@ import {
searchResult,
iconArtURI,
playlistAlbumArtURL,
sonosifyMimeType,
} from "../src/smapi";
import {
@@ -48,7 +49,7 @@ import {
} from "../src/music_service";
import { AccessTokens } from "../src/access_tokens";
import dayjs from "dayjs";
import url from "../src/url_builder";
import url, { URLBuilder } from "../src/url_builder";
import { iconForGenre } from "../src/icon";
const parseXML = (value: string) => new DOMParserImpl().parseFromString(value);
@@ -252,7 +253,8 @@ describe("track", () => {
const bonobUrl = url("http://localhost:4567/foo?access-token=1234");
const someTrack = aTrack({
id: uuid(),
mimeType: "audio/something",
// audio/x-flac should be mapped to audio/flac
mimeType: "audio/x-flac",
name: "great song",
duration: randomInt(1000),
number: randomInt(100),
@@ -262,22 +264,23 @@ describe("track", () => {
genre: { id: "genre101", name: "some genre" },
}),
artist: anArtist({ name: "great artist", id: uuid() }),
coverArt:"coverArt:887766"
});
expect(track(bonobUrl, someTrack)).toEqual({
itemType: "track",
id: `track:${someTrack.id}`,
mimeType: someTrack.mimeType,
mimeType: 'audio/flac',
title: someTrack.name,
trackMetadata: {
album: someTrack.album.name,
albumId: someTrack.album.id,
albumId: `album:${someTrack.album.id}`,
albumArtist: someTrack.artist.name,
albumArtistId: someTrack.artist.id,
albumArtURI: `http://localhost:4567/foo/art/album/${someTrack.album.id}/size/180?access-token=1234`,
albumArtistId: `artist:${someTrack.artist.id}`,
albumArtURI: `http://localhost:4567/foo/art/${someTrack.coverArt}/size/180?access-token=1234`,
artist: someTrack.artist.name,
artistId: someTrack.artist.id,
artistId: `artist:${someTrack.artist.id}`,
duration: someTrack.duration,
genre: someTrack.album.genre?.name,
genreId: someTrack.album.genre?.id,
@@ -304,12 +307,28 @@ describe("album", () => {
});
});
describe("sonosifyMimeType", () => {
describe("when is audio/x-flac", () => {
it("should be mapped to audio/flac", () => {
expect(sonosifyMimeType("audio/x-flac")).toEqual("audio/flac");
});
});
describe("when it is not audio/x-flac", () => {
it("should be returned as is", () => {
expect(sonosifyMimeType("audio/flac")).toEqual("audio/flac");
expect(sonosifyMimeType("audio/mpeg")).toEqual("audio/mpeg");
expect(sonosifyMimeType("audio/whoop")).toEqual("audio/whoop");
});
});
});
describe("playlistAlbumArtURL", () => {
describe("when the playlist has no albumIds", () => {
describe("when the playlist has no coverArt ids", () => {
it("should return question mark icon", () => {
const bonobUrl = url("http://localhost:1234/context-path?search=yes");
const playlist = aPlaylist({
entries: [aTrack({ album: undefined }), aTrack({ album: undefined })],
entries: [aTrack({ coverArt: undefined }), aTrack({ coverArt: undefined })],
});
expect(playlistAlbumArtURL(bonobUrl, playlist).href()).toEqual(
@@ -318,20 +337,20 @@ describe("playlistAlbumArtURL", () => {
});
});
describe("when the playlist has 2 distinct albumIds", () => {
describe("when the playlist has 2 distinct coverArt ids", () => {
it("should return them on the url to the image", () => {
const bonobUrl = url("http://localhost:1234/context-path?search=yes");
const playlist = aPlaylist({
entries: [
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "1" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "2" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "1" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "2" })) }),
aTrack({ coverArt: "1" }),
aTrack({ coverArt: "2" }),
aTrack({ coverArt: "1" }),
aTrack({ coverArt: "2" }),
],
});
expect(playlistAlbumArtURL(bonobUrl, playlist).href()).toEqual(
`http://localhost:1234/context-path/art/album/1&2/size/180?search=yes`
`http://localhost:1234/context-path/art/1&2/size/180?search=yes`
);
});
});
@@ -341,52 +360,75 @@ describe("playlistAlbumArtURL", () => {
const bonobUrl = url("http://localhost:1234/context-path?search=yes");
const playlist = aPlaylist({
entries: [
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "1" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "2" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "2" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "3" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "4" })) }),
aTrack({ coverArt: "1" }),
aTrack({ coverArt: "2" }),
aTrack({ coverArt: "2" }),
aTrack({ coverArt: "3" }),
aTrack({ coverArt: "4" }),
],
});
expect(playlistAlbumArtURL(bonobUrl, playlist).href()).toEqual(
`http://localhost:1234/context-path/art/album/1&2&3&4/size/180?search=yes`
`http://localhost:1234/context-path/art/1&2&3&4/size/180?search=yes`
);
});
});
describe("when the playlist has 9 distinct albumIds", () => {
it("should return 9 of the ids on the url", () => {
describe("when the playlist has at least 9 distinct albumIds", () => {
it("should return the first 9 of the ids on the url", () => {
const bonobUrl = url("http://localhost:1234/context-path?search=yes");
const playlist = aPlaylist({
entries: [
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "1" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "2" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "3" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "4" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "5" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "6" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "7" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "8" })) }),
aTrack({ album: albumToAlbumSummary(anAlbum({ id: "9" })) }),
aTrack({ coverArt: "1" }),
aTrack({ coverArt: "2" }),
aTrack({ coverArt: "2" }),
aTrack({ coverArt: "2" }),
aTrack({ coverArt: "3" }),
aTrack({ coverArt: "4" }),
aTrack({ coverArt: "5" }),
aTrack({ coverArt: "6" }),
aTrack({ coverArt: "7" }),
aTrack({ coverArt: "8" }),
aTrack({ coverArt: "9" }),
aTrack({ coverArt: "10" }),
aTrack({ coverArt: "11" }),
],
});
expect(playlistAlbumArtURL(bonobUrl, playlist).href()).toEqual(
`http://localhost:1234/context-path/art/album/1&2&3&4&5&6&7&8&9/size/180?search=yes`
`http://localhost:1234/context-path/art/1&2&3&4&5&6&7&8&9/size/180?search=yes`
);
});
});
});
describe("defaultAlbumArtURI", () => {
it("should create the correct URI", () => {
const bonobUrl = url("http://localhost:1234/context-path?search=yes");
const album = anAlbum();
const bonobUrl = new URLBuilder("http://bonob.example.com:8080/context?search=yes");
expect(defaultAlbumArtURI(bonobUrl, album).href()).toEqual(
`http://localhost:1234/context-path/art/album/${album.id}/size/180?search=yes`
);
describe("when there is an album coverArt", () => {
it("should use it in the image url", () => {
expect(
defaultAlbumArtURI(
bonobUrl,
anAlbum({ coverArt: "coverArt:123" })
).href()
).toEqual(
"http://bonob.example.com:8080/context/art/coverArt:123/size/180?search=yes"
);
});
});
describe("when there is no album coverArt", () => {
it("should return a vinly icon image", () => {
expect(
defaultAlbumArtURI(
bonobUrl,
anAlbum({ coverArt: undefined })
).href()
).toEqual(
"http://bonob.example.com:8080/context/icon/vinyl/size/legacy?search=yes"
);
});
});
});
@@ -396,7 +438,7 @@ describe("defaultArtistArtURI", () => {
const artist = anArtist();
expect(defaultArtistArtURI(bonobUrl, artist).href()).toEqual(
`http://localhost:1234/something/art/artist/${artist.id}/size/180?s=123`
`http://localhost:1234/something/art/artist:${artist.id}/size/180?s=123`
);
});
});
@@ -430,6 +472,7 @@ describe("api", () => {
deletePlaylist: jest.fn(),
removeFromPlaylist: jest.fn(),
scrobble: jest.fn(),
nowPlaying: jest.fn(),
};
const accessTokens = {
mint: jest.fn(),
@@ -448,7 +491,7 @@ describe("api", () => {
const accessToken = `accessToken-${uuid()}`;
const bonobUrlWithAccessToken = bonobUrl.append({
searchParams: { "bat": accessToken },
searchParams: { bat: accessToken },
});
const service = bonobService("test-api", 133, bonobUrl, "AppLink");
@@ -1020,7 +1063,7 @@ describe("api", () => {
title: genre.name,
albumArtURI: iconArtURI(
bonobUrl,
iconForGenre(genre.name),
iconForGenre(genre.name)
).href(),
})),
index: 0,
@@ -1045,7 +1088,7 @@ describe("api", () => {
title: genre.name,
albumArtURI: iconArtURI(
bonobUrl,
iconForGenre(genre.name),
iconForGenre(genre.name)
).href(),
})),
index: 1,
@@ -2302,14 +2345,17 @@ describe("api", () => {
artistId: `artist:${track.artist.id}`,
artist: track.artist.name,
albumId: `album:${track.album.id}`,
albumArtist: track.artist.name,
albumArtistId: `artist:${track.artist.id}`,
album: track.album.name,
genre: track.genre?.name,
genreId: track.genre?.id,
duration: track.duration,
albumArtURI: defaultAlbumArtURI(
bonobUrlWithAccessToken,
track.album
track
).href(),
trackNumber: track.number,
},
},
},
@@ -2425,12 +2471,9 @@ describe("api", () => {
getMediaURIResult: bonobUrl
.append({
pathname: `/stream/track/${trackId}`,
searchParams: { "bat": accessToken }
})
.href(),
httpHeaders: {
header: "bat",
value: accessToken,
},
});
expect(musicService.login).toHaveBeenCalledWith(authToken);
@@ -2510,7 +2553,7 @@ describe("api", () => {
expect(root[0]).toEqual({
getMediaMetadataResult: track(
bonobUrl.with({
searchParams: { "bat": accessToken },
searchParams: { bat: accessToken },
}),
someTrack
),
@@ -2765,9 +2808,11 @@ describe("api", () => {
function itShouldScroble({
trackId,
secondsPlayed,
shouldMarkNowPlaying,
}: {
trackId: string;
secondsPlayed: number;
shouldMarkNowPlaying: boolean,
}) {
it("should scrobble", async () => {
musicLibrary.scrobble.mockResolvedValue(true);
@@ -2782,15 +2827,22 @@ describe("api", () => {
expect(accessTokens.mint).toHaveBeenCalledWith(authToken);
expect(musicLibrary.track).toHaveBeenCalledWith(trackId);
expect(musicLibrary.scrobble).toHaveBeenCalledWith(trackId);
if(shouldMarkNowPlaying) {
expect(musicLibrary.nowPlaying).toHaveBeenCalledWith(trackId);
} else {
expect(musicLibrary.nowPlaying).not.toHaveBeenCalled();
}
});
}
function itShouldNotScroble({
trackId,
secondsPlayed,
shouldMarkNowPlaying,
}: {
trackId: string;
secondsPlayed: number;
shouldMarkNowPlaying: boolean,
}) {
it("should scrobble", async () => {
const result = await ws.setPlayedSecondsAsync({
@@ -2803,6 +2855,11 @@ describe("api", () => {
expect(accessTokens.mint).toHaveBeenCalledWith(authToken);
expect(musicLibrary.track).toHaveBeenCalledWith(trackId);
expect(musicLibrary.scrobble).not.toHaveBeenCalled();
if(shouldMarkNowPlaying) {
expect(musicLibrary.nowPlaying).toHaveBeenCalledWith(trackId);
} else {
expect(musicLibrary.nowPlaying).not.toHaveBeenCalled();
}
});
}
@@ -2813,16 +2870,24 @@ describe("api", () => {
);
});
describe("when the played length is 30 seconds", () => {
itShouldScroble({ trackId, secondsPlayed: 30 });
describe("when the seconds played is 30 seconds", () => {
itShouldScroble({ trackId, secondsPlayed: 30, shouldMarkNowPlaying: true });
});
describe("when the played length is > 30 seconds", () => {
itShouldScroble({ trackId, secondsPlayed: 90 });
describe("when the seconds played is > 30 seconds", () => {
itShouldScroble({ trackId, secondsPlayed: 90, shouldMarkNowPlaying: true });
});
describe("when the played length is < 30 seconds", () => {
itShouldNotScroble({ trackId, secondsPlayed: 29 });
describe("when the seconds played is < 30 seconds", () => {
itShouldNotScroble({ trackId, secondsPlayed: 29, shouldMarkNowPlaying: true });
});
describe("when the seconds played is 1 seconds", () => {
itShouldNotScroble({ trackId, secondsPlayed: 1, shouldMarkNowPlaying: true });
});
describe("when the seconds played is 0 seconds", () => {
itShouldNotScroble({ trackId, secondsPlayed: 0, shouldMarkNowPlaying: false });
});
});
@@ -2833,16 +2898,24 @@ describe("api", () => {
);
});
describe("when the played length is 30 seconds", () => {
itShouldScroble({ trackId, secondsPlayed: 30 });
describe("when the seconds played is 30 seconds", () => {
itShouldScroble({ trackId, secondsPlayed: 30, shouldMarkNowPlaying: true });
});
describe("when the played length is > 30 seconds", () => {
itShouldScroble({ trackId, secondsPlayed: 90 });
describe("when the seconds played is > 30 seconds", () => {
itShouldScroble({ trackId, secondsPlayed: 90, shouldMarkNowPlaying: true });
});
describe("when the played length is < 30 seconds", () => {
itShouldNotScroble({ trackId, secondsPlayed: 29 });
describe("when the seconds played is < 30 seconds", () => {
itShouldNotScroble({ trackId, secondsPlayed: 29, shouldMarkNowPlaying: true });
});
describe("when the seconds played is 1 seconds", () => {
itShouldNotScroble({ trackId, secondsPlayed: 1, shouldMarkNowPlaying: true });
});
describe("when the seconds played is 0 seconds", () => {
itShouldNotScroble({ trackId, secondsPlayed: 0, shouldMarkNowPlaying: false });
});
});
@@ -2853,20 +2926,28 @@ describe("api", () => {
);
});
describe("when the played length is 29 seconds", () => {
itShouldScroble({ trackId, secondsPlayed: 30 });
describe("when the seconds played is 29 seconds", () => {
itShouldScroble({ trackId, secondsPlayed: 30, shouldMarkNowPlaying: true });
});
describe("when the played length is > 29 seconds", () => {
itShouldScroble({ trackId, secondsPlayed: 30 });
describe("when the seconds played is > 29 seconds", () => {
itShouldScroble({ trackId, secondsPlayed: 30, shouldMarkNowPlaying: true });
});
describe("when the played length is 10 seconds", () => {
itShouldScroble({ trackId, secondsPlayed: 10 });
describe("when the seconds played is 10 seconds", () => {
itShouldScroble({ trackId, secondsPlayed: 10, shouldMarkNowPlaying: true });
});
describe("when the played length is < 10 seconds", () => {
itShouldNotScroble({ trackId, secondsPlayed: 9 });
describe("when the seconds played is < 10 seconds", () => {
itShouldNotScroble({ trackId, secondsPlayed: 9, shouldMarkNowPlaying: true });
});
describe("when the seconds played is 1 seconds", () => {
itShouldNotScroble({ trackId, secondsPlayed: 1, shouldMarkNowPlaying: true });
});
describe("when the seconds played is 0 seconds", () => {
itShouldNotScroble({ trackId, secondsPlayed: 0, shouldMarkNowPlaying: false });
});
});
});
@@ -2881,6 +2962,7 @@ describe("api", () => {
expect(result[0]).toEqual({ setPlayedSecondsResult: null });
expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(accessTokens.mint).toHaveBeenCalledWith(authToken);
expect(musicLibrary.nowPlaying).not.toHaveBeenCalled();
expect(musicLibrary.scrobble).not.toHaveBeenCalled();
});
});

View File

@@ -274,12 +274,13 @@ describe("sonos", () => {
describe("when is disabled", () => {
it("should return a disabled client", async () => {
const disabled = sonos(false);
const disabled = sonos({ enabled: false });
expect(disabled).toEqual(SONOS_DISABLED);
expect(await disabled.devices()).toEqual([]);
expect(await disabled.services()).toEqual([]);
expect(await disabled.register(aService())).toEqual(true);
expect(await disabled.register(aService())).toEqual(false);
expect(await disabled.remove(123)).toEqual(false);
});
});
@@ -310,7 +311,7 @@ describe("sonos", () => {
);
sonosManager.InitializeWithDiscovery.mockResolvedValue(true);
const actualDevices = await sonos(true, undefined).devices();
const actualDevices = await sonos({ enabled: true }).devices();
expect(SonosManager).toHaveBeenCalledTimes(1);
expect(sonosManager.InitializeWithDiscovery).toHaveBeenCalledWith(10);
@@ -331,7 +332,7 @@ describe("sonos", () => {
);
sonosManager.InitializeWithDiscovery.mockResolvedValue(true);
const actualDevices = await sonos(true, "").devices();
const actualDevices = await sonos({ enabled: true, seedHost: "" }).devices();
expect(SonosManager).toHaveBeenCalledTimes(1);
expect(sonosManager.InitializeWithDiscovery).toHaveBeenCalledWith(10);
@@ -354,7 +355,7 @@ describe("sonos", () => {
);
sonosManager.InitializeFromDevice.mockResolvedValue(true);
const actualDevices = await sonos(true, seedHost).devices();
const actualDevices = await sonos({ enabled: true, seedHost }).devices();
expect(SonosManager).toHaveBeenCalledTimes(1);
expect(sonosManager.InitializeFromDevice).toHaveBeenCalledWith(
@@ -377,7 +378,7 @@ describe("sonos", () => {
);
sonosManager.InitializeWithDiscovery.mockResolvedValue(true);
const actualDevices = await sonos(true, undefined).devices();
const actualDevices = await sonos({ enabled: true, seedHost: undefined }).devices();
expect(actualDevices).toEqual([
{
@@ -408,7 +409,7 @@ describe("sonos", () => {
);
sonosManager.InitializeWithDiscovery.mockResolvedValue(false);
expect(await sonos(true, "").devices()).toEqual([]);
expect(await sonos({ enabled: true, seedHost: "" }).devices()).toEqual([]);
});
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,10 @@
import { Express } from "express";
import { ReadStream } from "fs";
import { IHttpClient } from "soap";
import request from "supertest";
import * as req from "axios";
function supersoap(server: Express) {
function supersoap(server: Express): IHttpClient {
return {
request: (
rurl: string,
@@ -15,12 +18,19 @@ function supersoap(server: Express) {
data == null
? request(server).get(withoutHost).send()
: request(server).post(withoutHost).send(data);
req
return req
.set(exheaders || {})
.then((response) => callback(null, response, response.text))
.catch(callback);
},
}
requestStream: (
_: string,
_2: any
): req.AxiosPromise<ReadStream> => {
throw "Not Implemented!!";
},
};
}
export default supersoap
export default supersoap;

3431
yarn.lock

File diff suppressed because it is too large Load Diff