Compare commits

...

23 Commits

Author SHA1 Message Date
simojenki
c1010df803 Update README 2021-10-08 11:48:56 +11:00
Simon J
cc95beb4f2 Ability to see TopRated/starred albums (#63) 2021-10-08 00:08:32 +11:00
simojenki
6116975d7a Fix issue fetching public resources from web container when running out of docker 2021-10-07 19:57:21 +11:00
Simon J
8f3d2bddf7 Ability to heart and star tracks whilst playing
Ability to heart and star tracks whilst playing
2021-10-07 15:57:09 +11:00
simojenki
a02b8c1ecd Re-enable tests removed with .only 2021-10-03 18:49:16 +11:00
simojenki
effb02f46e Removed http://moapi.sonos.com/Test/TestService.php from sonos wsdl as causes noise in logs 2021-10-03 18:47:26 +11:00
Simon J
d7a7747fab Ability to cache subsonic artist images locally on disk (#61) 2021-10-03 16:36:50 +11:00
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
simojenki
287e203449 Setting node version to 16.6 in ci.yaml actions pipeline 2021-09-07 21:15:24 +10:00
Simon J
92be208a35 Fix bug navigating from album to artist (#47) 2021-09-07 10:24:46 +10:00
44 changed files with 5135 additions and 4031 deletions

View File

@@ -21,7 +21,7 @@ jobs:
- -
uses: actions/setup-node@v1 uses: actions/setup-node@v1
with: with:
node-version: 16.x node-version: 16.6.x
- -
run: yarn install run: yarn install
- -

View File

@@ -31,9 +31,9 @@ RUN apk add --no-cache --update --virtual .gyp \
FROM node:16.6-alpine FROM node:16.6-alpine
ENV BONOB_PORT=4534 ENV BNB_PORT=4534
EXPOSE $BONOB_PORT EXPOSE $BNB_PORT
WORKDIR /bonob 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 RUN apk add --no-cache --update vips
USER nobody USER nobody
WORKDIR /bonob/src
CMD ["node", "/bonob/src/app.js"] CMD ["node", "app.js"]

161
README.md
View File

@@ -2,28 +2,26 @@
A sonos SMAPI implementation to allow registering sources of music with sonos. 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) ![Build](https://github.com/simojenki/bonob/workflows/Build/badge.svg)
## Features ## 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 - Browse by Artist, Albums, Random, Favourites, Top Rated, Playlist, Genres, Recently Added Albums, Recently Played Albums, Most Played Albums
- Artist Art - Artist & Album Art
- Album Art
- View Related Artists via Artist -> '...' -> Menu -> Related Arists - View Related Artists via Artist -> '...' -> Menu -> Related Arists
- Now playing & Track Scrobbling - Now playing & Track Scrobbling
- Search by Album, Artist, Track
- Playlist editing through sonos app.
- Marking of songs as favourites and with ratings through the sonos app.
- Localization (only en-US & nl-NL supported currently, require translations for other languages). [Sonos localization and supported languages](https://developer.sonos.com/build/content-service-add-features/strings-and-localization/)
- Auto discovery of sonos devices - Auto discovery of sonos devices
- Discovery of sonos devices using seed IP address - Discovery of sonos devices using seed IP address
- Auto register bonob service with sonos system - Auto registration with sonos on start
- Multiple registrations within a single household. - 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
- Ability to add/remove tracks from a playlist
- Localization (only en-US & nl-NL supported currently, require translations for other languages). [Sonos localization and supported languages](https://developer.sonos.com/build/content-service-add-features/strings-and-localization/)
## Running ## Running
@@ -33,8 +31,8 @@ bonob is ditributed via docker and can be run in a number of ways
```bash ```bash
docker run \ docker run \
-e BONOB_SONOS_AUTO_REGISTER=true \ -e BNB_SONOS_AUTO_REGISTER=true \
-e BONOB_SONOS_DEVICE_DISCOVERY=true \ -e BNB_SONOS_DEVICE_DISCOVERY=true \
-p 4534:4534 \ -p 4534:4534 \
--network host \ --network host \
simojenki/bonob simojenki/bonob
@@ -46,10 +44,10 @@ Now open http://localhost:4534 in your browser, you should see sonos devices, an
```bash ```bash
docker run \ docker run \
-e BONOB_PORT=3000 \ -e BNB_PORT=3000 \
-e BONOB_SONOS_SEED_HOST=192.168.1.123 \ -e BNB_SONOS_SEED_HOST=192.168.1.123 \
-e BONOB_SONOS_AUTO_REGISTER=true \ -e BNB_SONOS_AUTO_REGISTER=true \
-e BONOB_SONOS_DEVICE_DISCOVERY=true \ -e BNB_SONOS_DEVICE_DISCOVERY=true \
-p 3000:3000 \ -p 3000:3000 \
simojenki/bonob simojenki/bonob
``` ```
@@ -66,19 +64,21 @@ Start bonob outside the LAN with sonos discovery & registration disabled as they
```bash ```bash
docker run \ docker run \
-e BONOB_PORT=4534 \ -e BNB_PORT=4534 \
-e BONOB_SONOS_SERVICE_NAME=MyAwesomeMusic \ -e BNB_SONOS_SERVICE_NAME=MyAwesomeMusic \
-e BONOB_SECRET=changeme \ -e BNB_SECRET=changeme \
-e BONOB_URL=https://my-server.example.com/bonob \ -e BNB_URL=https://my-server.example.com/bonob \
-e BONOB_SONOS_AUTO_REGISTER=false \ -e BNB_SONOS_AUTO_REGISTER=false \
-e BONOB_SONOS_DEVICE_DISCOVERY=false \ -e BNB_SONOS_DEVICE_DISCOVERY=false \
-e BONOB_NAVIDROME_URL=https://my-navidrome-service.com:4533 \ -e BNB_SUBSONIC_URL=https://my-navidrome-service.com:4533 \
-p 4534:4534 \ -p 4534:4534 \
simojenki/bonob simojenki/bonob
``` ```
Now within the LAN that contains the sonos devices run bonob the registration process. Now within the LAN that contains the sonos devices run bonob the registration process.
#### Using auto-discovery
```bash ```bash
docker run \ docker run \
--rm \ --rm \
@@ -86,6 +86,15 @@ docker run \
simojenki/bonob register https://my-server.example.com/bonob 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 ### Running bonob and navidrome using docker-compose
```yaml ```yaml
@@ -113,76 +122,98 @@ services:
- "4534:4534" - "4534:4534"
restart: unless-stopped restart: unless-stopped
environment: environment:
BONOB_PORT: 4534 BNB_PORT: 4534
# ip address of your machine running bonob # ip address of your machine running bonob
BONOB_URL: http://192.168.1.111:4534 BNB_URL: http://192.168.1.111:4534
BONOB_SECRET: changeme BNB_SECRET: changeme
BONOB_SONOS_AUTO_REGISTER: true BNB_SONOS_AUTO_REGISTER: true
BONOB_SONOS_DEVICE_DISCOVERY: true BNB_SONOS_DEVICE_DISCOVERY: true
BONOB_SONOS_SERVICE_ID: 246 BNB_SONOS_SERVICE_ID: 246
# ip address of one of your sonos devices # ip address of one of your sonos devices
BONOB_SONOS_SEED_HOST: 192.168.1.121 BNB_SONOS_SEED_HOST: 192.168.1.121
BONOB_NAVIDROME_URL: http://navidrome:4533 BNB_SUBSONIC_URL: http://navidrome:4533
``` ```
## Configuration ## Configuration
item | default value | description item | default value | description
---- | ------------- | ----------- ---- | ------------- | -----------
BONOB_PORT | 4534 | Default http port for bonob to listen on BNB_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.** 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.**
BONOB_SECRET | bonob | secret used for encrypting credentials BNB_SECRET | bonob | secret used for encrypting credentials
BONOB_SONOS_AUTO_REGISTER | false | Whether or not to try and auto-register on startup BNB_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 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.
BONOB_SONOS_SEED_HOST | undefined | sonos device seed host for discovery, or ommitted for for auto-discovery BNB_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 BNB_SONOS_SERVICE_NAME | bonob | service name for sonos
BONOB_SONOS_SERVICE_ID | 246 | service id for sonos BNB_SONOS_SERVICE_ID | 246 | service id for sonos
BONOB_NAVIDROME_URL | http://$(hostname):4533 | URL for navidrome BNB_SUBSONIC_URL | http://$(hostname):4533 | URL for subsonic clone
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. 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.
BONOB_SCROBBLE_TRACKS | true | Whether to scrobble the playing of a track if it has been played for >30s BNB_SUBSONIC_ARTIST_IMAGE_CACHE | undefined | Path for caching of artist images as are sourced externally. ie. Navidrome provides spotify URLs
BONOB_REPORT_NOW_PLAYING | true | Whether to report a track as now playing BNB_SCROBBLE_TRACKS | true | Whether to scrobble the playing of a track if it has been played for >30s
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) BNB_REPORT_NOW_PLAYING | true | Whether to report a track as now playing
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_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 ## 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, - Start bonob
- Open sonos app on your device - Open sonos app on your device
- Settings -> Services & Voice -> + Add a Service - 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 - 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!' - You should get 'Login successful!'
- Go back into the sonos app and complete the process - Go back into the sonos app and complete the process
- You should now be able to play music from navidrome - You should now be able to play music on your sonos devices from you subsonic clone
- Within navidrome a new player will be created, 'bonob (username)', so you can configure transcoding specifically for sonos - 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 - Implement the MusicService/MusicLibrary interface
- Startup bonob with your new implementation. - 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) ![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) ![Chartreuse & Fuchsia](https://github.com/simojenki/bonob/blob/master/docs/images/chartreuseFuchsia.png?raw=true)
## Credits ## Credits
- Icons courtesy of: [Navidrome](https://www.navidrome.org/), [Vectornator](https://www.vectornator.io/icons), and @jicho - Icons courtesy of: [Navidrome](https://www.navidrome.org/), [Vectornator](https://www.vectornator.io/icons), and @jicho
## TODO
- Artist Radio

View File

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

View File

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

View File

@@ -2059,7 +2059,7 @@
<wsdl:service name="Sonos"> <wsdl:service name="Sonos">
<wsdl:port name="SonosSoap" binding="tns:SonosSoap"> <wsdl:port name="SonosSoap" binding="tns:SonosSoap">
<soap:address location="http://moapi.sonos.com/Test/TestService.php"/> <soap:address location="/about"/>
</wsdl:port> </wsdl:port>
</wsdl:service> </wsdl:service>

View File

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

View File

@@ -2,7 +2,13 @@ import path from "path";
import fs from "fs"; import fs from "fs";
import server from "./server"; import server from "./server";
import logger from "./logger"; import logger from "./logger";
import { appendMimeTypeToClientFor, DEFAULT, Navidrome } from "./navidrome"; import {
appendMimeTypeToClientFor,
axiosImageFetcher,
cachingImageFetcher,
DEFAULT,
Subsonic,
} from "./subsonic";
import encryption from "./encryption"; import encryption from "./encryption";
import { InMemoryAccessTokens, sha256 } from "./access_tokens"; import { InMemoryAccessTokens, sha256 } from "./access_tokens";
import { InMemoryLinkCodes } from "./link_codes"; import { InMemoryLinkCodes } from "./link_codes";
@@ -22,22 +28,27 @@ const bonob = bonobService(
"AppLink" "AppLink"
); );
const sonosSystem = sonos(config.sonos.deviceDiscovery, config.sonos.seedHost); const sonosSystem = sonos(config.sonos.discovery);
const streamUserAgent = config.navidrome.customClientsFor const streamUserAgent = config.subsonic.customClientsFor
? appendMimeTypeToClientFor(config.navidrome.customClientsFor.split(",")) ? appendMimeTypeToClientFor(config.subsonic.customClientsFor.split(","))
: DEFAULT; : DEFAULT;
const navidrome = new Navidrome( const artistImageFetcher = config.subsonic.artistImageCache
config.navidrome.url, ? cachingImageFetcher(config.subsonic.artistImageCache, axiosImageFetcher)
: axiosImageFetcher;
const subsonic = new Subsonic(
config.subsonic.url,
encryption(config.secret), encryption(config.secret),
streamUserAgent streamUserAgent,
artistImageFetcher
); );
const featureFlagAwareMusicService: MusicService = { const featureFlagAwareMusicService: MusicService = {
generateToken: navidrome.generateToken, generateToken: subsonic.generateToken,
login: (authToken: string) => login: (authToken: string) =>
navidrome.login(authToken).then((library) => { subsonic.login(authToken).then((library) => {
return { return {
...library, ...library,
scrobble: (id: string) => { scrobble: (id: string) => {
@@ -60,7 +71,9 @@ const featureFlagAwareMusicService: MusicService = {
export const GIT_INFO = path.join(__dirname, "..", ".gitinfo"); export const GIT_INFO = path.join(__dirname, "..", ".gitinfo");
const version = fs.existsSync(GIT_INFO) ? fs.readFileSync(GIT_INFO).toString().trim() : "v??" const version = fs.existsSync(GIT_INFO)
? fs.readFileSync(GIT_INFO).toString().trim()
: "v??";
const app = server( const app = server(
sonosSystem, sonosSystem,
@@ -74,7 +87,7 @@ const app = server(
iconColors: config.icons, iconColors: config.icons,
applyContextPath: true, applyContextPath: true,
logRequests: true, logRequests: true,
version version,
} }
); );
@@ -90,12 +103,12 @@ if (config.sonos.autoRegister) {
); );
} }
}); });
} else if(config.sonos.deviceDiscovery) { } else if (config.sonos.discovery.enabled) {
sonosSystem.devices().then(devices => { sonosSystem.devices().then((devices) => {
devices.forEach(d => { devices.forEach((d) => {
logger.info(`Found device ${d.name}(${d.group}) @ ${d.ip}:${d.port}`) logger.info(`Found device ${d.name}(${d.group}) @ ${d.ip}:${d.port}`);
}) });
}) });
} }
export default app; export default app;

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,92 @@ import { hostname } from "os";
import logger from "./logger"; import logger from "./logger";
import url from "./url_builder"; 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 () { export default function () {
const port = +(process.env["BONOB_PORT"] || 4534); const port = +bnbEnvVar("PORT", { default: "4534" })!;
const bonobUrl = const bonobUrl = bnbEnvVar("URL", {
process.env["BONOB_URL"] || legacy: ["BONOB_WEB_ADDRESS"],
process.env["BONOB_WEB_ADDRESS"] || default: `http://${hostname()}:${port}`,
`http://${hostname()}:${port}`; })!;
if (bonobUrl.match("localhost")) { if (bonobUrl.match("localhost")) {
logger.error( 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); 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 { return {
port, port,
bonobUrl: url(bonobUrl), bonobUrl: url(bonobUrl),
secret: process.env["BONOB_SECRET"] || "bonob", secret: bnbEnvVar("SECRET", { default: "bonob" })!,
icons: { icons: {
foregroundColor: wordFrom("BONOB_ICON_FOREGROUND_COLOR"), foregroundColor: bnbEnvVar("ICON_FOREGROUND_COLOR", {
backgroundColor: wordFrom("BONOB_ICON_BACKGROUND_COLOR"), validationPattern: WORD,
}),
backgroundColor: bnbEnvVar("ICON_BACKGROUND_COLOR", {
validationPattern: WORD,
}),
}, },
sonos: { sonos: {
serviceName: process.env["BONOB_SONOS_SERVICE_NAME"] || "bonob", serviceName: bnbEnvVar("SONOS_SERVICE_NAME", { default: "bonob" })!,
deviceDiscovery: discovery: {
(process.env["BONOB_SONOS_DEVICE_DISCOVERY"] || "true") == "true", enabled:
seedHost: process.env["BONOB_SONOS_SEED_HOST"], bnbEnvVar("SONOS_DEVICE_DISCOVERY", { default: "true" }) == "true",
seedHost: bnbEnvVar("SONOS_SEED_HOST"),
},
autoRegister: autoRegister:
(process.env["BONOB_SONOS_AUTO_REGISTER"] || "false") == "true", bnbEnvVar("SONOS_AUTO_REGISTER", { default: "false" }) == "true",
sid: Number(process.env["BONOB_SONOS_SERVICE_ID"] || "246"), sid: Number(bnbEnvVar("SONOS_SERVICE_ID", { default: "246" })),
}, },
navidrome: { subsonic: {
url: process.env["BONOB_NAVIDROME_URL"] || `http://${hostname()}:4533`, url: bnbEnvVar("SUBSONIC_URL", { legacy: ["BONOB_NAVIDROME_URL"], default: `http://${hostname()}:4533` })!,
customClientsFor: customClientsFor: bnbEnvVar("SUBSONIC_CUSTOM_CLIENTS", { legacy: ["BONOB_NAVIDROME_CUSTOM_CLIENTS"] }),
process.env["BONOB_NAVIDROME_CUSTOM_CLIENTS"] || undefined, artistImageCache: bnbEnvVar("SUBSONIC_ARTIST_IMAGE_CACHE"),
}, },
scrobbleTracks: (process.env["BONOB_SCROBBLE_TRACKS"] || "true") == "true", scrobbleTracks: bnbEnvVar("SCROBBLE_TRACKS", { default: "true" }) == "true",
reportNowPlaying: reportNowPlaying:
(process.env["BONOB_REPORT_NOW_PLAYING"] || "true") == "true", bnbEnvVar("REPORT_NOW_PLAYING", { default: "true" }) == "true",
}; };
} }

View File

@@ -12,7 +12,7 @@ export type KEY =
| "playlists" | "playlists"
| "genres" | "genres"
| "random" | "random"
| "starred" | "topRated"
| "recentlyAdded" | "recentlyAdded"
| "recentlyPlayed" | "recentlyPlayed"
| "mostPlayed" | "mostPlayed"
@@ -37,18 +37,25 @@ export type KEY =
| "invalidLinkCode" | "invalidLinkCode"
| "loginSuccessful" | "loginSuccessful"
| "loginFailed" | "loginFailed"
| "noSonosDevices"; | "noSonosDevices"
| "favourites"
| "LOVE"
| "LOVE_SUCCESS"
| "STAR"
| "UNSTAR"
| "STAR_SUCCESS"
| "UNSTAR_SUCCESS";
const translations: Record<SUPPORTED_LANG, Record<KEY, string>> = { const translations: Record<SUPPORTED_LANG, Record<KEY, string>> = {
"en-US": { "en-US": {
AppLinkMessage: "Linking sonos with $BONOB_SONOS_SERVICE_NAME", AppLinkMessage: "Linking sonos with $BNB_SONOS_SERVICE_NAME",
artists: "Artists", artists: "Artists",
albums: "Albums", albums: "Albums",
tracks: "Tracks", tracks: "Tracks",
playlists: "Playlists", playlists: "Playlists",
genres: "Genres", genres: "Genres",
random: "Random", random: "Random",
starred: "Starred", topRated: "Top Rated",
recentlyAdded: "Recently added", recentlyAdded: "Recently added",
recentlyPlayed: "Recently played", recentlyPlayed: "Recently played",
mostPlayed: "Most played", mostPlayed: "Most played",
@@ -62,7 +69,7 @@ const translations: Record<SUPPORTED_LANG, Record<KEY, string>> = {
devices: "Devices", devices: "Devices",
services: "Services", services: "Services",
login: "Login", login: "Login",
logInToBonob: "Log in to $BONOB_SONOS_SERVICE_NAME", logInToBonob: "Log in to $BNB_SONOS_SERVICE_NAME",
username: "Username", username: "Username",
password: "Password", password: "Password",
successfullyRegistered: "Successfully registered", successfullyRegistered: "Successfully registered",
@@ -73,16 +80,23 @@ const translations: Record<SUPPORTED_LANG, Record<KEY, string>> = {
loginSuccessful: "Login successful!", loginSuccessful: "Login successful!",
loginFailed: "Login failed!", loginFailed: "Login failed!",
noSonosDevices: "No sonos devices", noSonosDevices: "No sonos devices",
favourites: "Favourites",
STAR: "Star",
UNSTAR: "Un-star",
STAR_SUCCESS: "Track starred",
UNSTAR_SUCCESS: "Track un-starred",
LOVE: "Love",
LOVE_SUCCESS: "Track loved"
}, },
"nl-NL": { "nl-NL": {
AppLinkMessage: "Sonos koppelen aan $BONOB_SONOS_SERVICE_NAME", AppLinkMessage: "Sonos koppelen aan $BNB_SONOS_SERVICE_NAME",
artists: "Artiesten", artists: "Artiesten",
albums: "Albums", albums: "Albums",
tracks: "Nummers", tracks: "Nummers",
playlists: "Afspeellijsten", playlists: "Afspeellijsten",
genres: "Genres", genres: "Genres",
random: "Willekeurig", random: "Willekeurig",
starred: "Favorieten", topRated: "Best beoordeeld",
recentlyAdded: "Onlangs toegevoegd", recentlyAdded: "Onlangs toegevoegd",
recentlyPlayed: "Onlangs afgespeeld", recentlyPlayed: "Onlangs afgespeeld",
mostPlayed: "Meest afgespeeld", mostPlayed: "Meest afgespeeld",
@@ -96,7 +110,7 @@ const translations: Record<SUPPORTED_LANG, Record<KEY, string>> = {
devices: "Apparaten", devices: "Apparaten",
services: "Services", services: "Services",
login: "Inloggen", login: "Inloggen",
logInToBonob: "Login op $BONOB_SONOS_SERVICE_NAME", logInToBonob: "Login op $BNB_SONOS_SERVICE_NAME",
username: "Gebruikersnaam", username: "Gebruikersnaam",
password: "Wachtwoord", password: "Wachtwoord",
successfullyRegistered: "Registratie geslaagd", successfullyRegistered: "Registratie geslaagd",
@@ -107,6 +121,13 @@ const translations: Record<SUPPORTED_LANG, Record<KEY, string>> = {
loginSuccessful: "Inloggen gelukt!", loginSuccessful: "Inloggen gelukt!",
loginFailed: "Inloggen mislukt!", loginFailed: "Inloggen mislukt!",
noSonosDevices: "Geen Sonos-apparaten", noSonosDevices: "Geen Sonos-apparaten",
favourites: "Favorieten",
STAR: "Ster ",
UNSTAR: "Een ster",
STAR_SUCCESS: "Nummer met ster",
UNSTAR_SUCCESS: "Track zonder ster",
LOVE: "Liefde",
LOVE_SUCCESS: "Volg geliefd"
}, },
}; };
@@ -151,7 +172,7 @@ export default (serviceName: string): I8N =>
translations["en-US"]; translations["en-US"];
return (key: KEY) => { return (key: KEY) => {
const value = langToUse[key]?.replace( const value = langToUse[key]?.replace(
"$BONOB_SONOS_SERVICE_NAME", "$BNB_SONOS_SERVICE_NAME",
serviceName serviceName
); );
if (value) return value; if (value) return value;

View File

@@ -166,7 +166,7 @@ export type ICON =
| "playlists" | "playlists"
| "genres" | "genres"
| "random" | "random"
| "starred" | "topRated"
| "recentlyAdded" | "recentlyAdded"
| "recentlyPlayed" | "recentlyPlayed"
| "mostPlayed" | "mostPlayed"
@@ -225,7 +225,10 @@ export type ICON =
| "skywalker" | "skywalker"
| "leia" | "leia"
| "r2d2" | "r2d2"
| "yoda"; | "yoda"
| "heart"
| "star"
| "solidStar";
const iconFrom = (name: string) => const iconFrom = (name: string) =>
new SvgIcon( new SvgIcon(
@@ -241,7 +244,7 @@ export const ICONS: Record<ICON, SvgIcon> = {
playlists: iconFrom("navidrome-playlists.svg"), playlists: iconFrom("navidrome-playlists.svg"),
genres: iconFrom("Theatre-Mask-111172.svg"), genres: iconFrom("Theatre-Mask-111172.svg"),
random: iconFrom("navidrome-random.svg"), random: iconFrom("navidrome-random.svg"),
starred: iconFrom("navidrome-topRated.svg"), topRated: iconFrom("navidrome-topRated.svg"),
recentlyAdded: iconFrom("navidrome-recentlyAdded.svg"), recentlyAdded: iconFrom("navidrome-recentlyAdded.svg"),
recentlyPlayed: iconFrom("navidrome-recentlyPlayed.svg"), recentlyPlayed: iconFrom("navidrome-recentlyPlayed.svg"),
mostPlayed: iconFrom("navidrome-mostPlayed.svg"), mostPlayed: iconFrom("navidrome-mostPlayed.svg"),
@@ -300,6 +303,9 @@ export const ICONS: Record<ICON, SvgIcon> = {
leia: iconFrom("Princess-Leia-68568.svg"), leia: iconFrom("Princess-Leia-68568.svg"),
r2d2: iconFrom("R2-D2-39423.svg"), r2d2: iconFrom("R2-D2-39423.svg"),
yoda: iconFrom("Yoda-68107.svg"), yoda: iconFrom("Yoda-68107.svg"),
heart: iconFrom("Heart-85038.svg"),
star: iconFrom("Star-16101.svg"),
solidStar: iconFrom("Star-43879.svg")
}; };
export const STAR_WARS = [ICONS.c3po, ICONS.chewy, ICONS.darth, ICONS.skywalker, ICONS.leia, ICONS.r2d2, ICONS.yoda]; export const STAR_WARS = [ICONS.c3po, ICONS.chewy, ICONS.darth, ICONS.skywalker, ICONS.leia, ICONS.r2d2, ICONS.yoda];

View File

@@ -52,9 +52,10 @@ export type AlbumSummary = {
name: string; name: string;
year: string | undefined; year: string | undefined;
genre: Genre | undefined; genre: Genre | undefined;
coverArt: string | undefined;
artistName: string; artistName: string | undefined;
artistId: string; artistId: string | undefined;
}; };
export type Album = AlbumSummary & {}; export type Album = AlbumSummary & {};
@@ -64,6 +65,11 @@ export type Genre = {
id: string; id: string;
} }
export type Rating = {
love: boolean;
stars: number;
}
export type Track = { export type Track = {
id: string; id: string;
name: string; name: string;
@@ -71,8 +77,10 @@ export type Track = {
duration: number; duration: number;
number: number | undefined; number: number | undefined;
genre: Genre | undefined; genre: Genre | undefined;
coverArt: string | undefined;
album: AlbumSummary; album: AlbumSummary;
artist: ArtistSummary; artist: ArtistSummary;
rating: Rating;
}; };
export type Paging = { export type Paging = {
@@ -99,7 +107,7 @@ export const asResult = <T>([results, total]: [T[], number]) => ({
export type ArtistQuery = Paging; export type ArtistQuery = Paging;
export type AlbumQueryType = 'alphabeticalByArtist' | 'alphabeticalByName' | 'byGenre' | 'random' | 'recent' | 'frequent' | 'newest' | 'starred'; export type AlbumQueryType = 'alphabeticalByArtist' | 'alphabeticalByName' | 'byGenre' | 'random' | 'recentlyPlayed' | 'mostPlayed' | 'recentlyAdded' | 'favourited' | 'starred';
export type AlbumQuery = Paging & { export type AlbumQuery = Paging & {
type: AlbumQueryType; type: AlbumQueryType;
@@ -118,6 +126,7 @@ export const albumToAlbumSummary = (it: Album): AlbumSummary => ({
genre: it.genre, genre: it.genre,
artistName: it.artistName, artistName: it.artistName,
artistId: it.artistId, artistId: it.artistId,
coverArt: it.coverArt
}); });
export const playlistToPlaylistSummary = (it: Playlist): PlaylistSummary => ({ export const playlistToPlaylistSummary = (it: Playlist): PlaylistSummary => ({
@@ -174,7 +183,8 @@ export interface MusicLibrary {
trackId: string; trackId: string;
range: string | undefined; range: string | undefined;
}): Promise<TrackStream>; }): Promise<TrackStream>;
coverArt(id: string, type: "album" | "artist", size?: number): Promise<CoverArt | undefined>; rate(trackId: string, rating: Rating): Promise<boolean>;
coverArt(id: string, size?: number): Promise<CoverArt | undefined>;
nowPlaying(id: string): Promise<boolean> nowPlaying(id: string): Promise<boolean>
scrobble(id: string): Promise<boolean> scrobble(id: string): Promise<boolean>
searchArtists(query: string): Promise<ArtistSummary[]>; searchArtists(query: string): Promise<ArtistSummary[]>;

View File

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

View File

@@ -1,9 +1,14 @@
import axios from "axios"; import axios from "axios";
import _ from "underscore";
import logger from "./logger"; import logger from "./logger";
import sonos, { bonobService } from "./sonos"; import sonos, { bonobService } from "./sonos";
import { URLBuilder } from "./url_builder"; import { URLBuilder } from "./url_builder";
export default (bonobUrl: URLBuilder) => async () => { export default (
bonobUrl: URLBuilder,
seedHost?: string
) =>
async () => {
const about = bonobUrl.append({ pathname: "/about" }); const about = bonobUrl.append({ pathname: "/about" });
logger.info(`Fetching bonob service about from ${about}`); logger.info(`Fetching bonob service about from ${about}`);
return axios return axios
@@ -12,8 +17,19 @@ export default (bonobUrl: URLBuilder) => async () => {
if (res.status == 200) return res.data; if (res.status == 200) return res.data;
else throw `Unexpected response status ${res.status} from ${about}`; else throw `Unexpected response status ${res.status} from ${about}`;
}) })
.then((about) => .then((res) => {
bonobService(about.service.name, about.service.sid, bonobUrl) const name = _.get(res, ["service", "name"]);
) const sid = _.get(res, ["service", "sid"]);
.then((bonobService) => sonos(true).register(bonobService)); 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,8 @@ import express, { Express, Request } from "express";
import * as Eta from "eta"; import * as Eta from "eta";
import path from "path"; import path from "path";
import sharp from "sharp"; import sharp from "sharp";
import { v4 as uuid } from "uuid";
import dayjs from "dayjs";
import { PassThrough, Transform, TransformCallback } from "stream"; import { PassThrough, Transform, TransformCallback } from "stream";
@@ -15,6 +17,9 @@ import {
LOGIN_ROUTE, LOGIN_ROUTE,
CREATE_REGISTRATION_ROUTE, CREATE_REGISTRATION_ROUTE,
REMOVE_REGISTRATION_ROUTE, REMOVE_REGISTRATION_ROUTE,
sonosifyMimeType,
ratingFromInt,
ratingAsInt,
} from "./smapi"; } from "./smapi";
import { LinkCodes, InMemoryLinkCodes } from "./link_codes"; import { LinkCodes, InMemoryLinkCodes } from "./link_codes";
import { MusicService, isSuccess } from "./music_service"; import { MusicService, isSuccess } from "./music_service";
@@ -105,6 +110,8 @@ function server(
const accessTokens = serverOpts.accessTokens(); const accessTokens = serverOpts.accessTokens();
const clock = serverOpts.clock; const clock = serverOpts.clock;
const startUpTime = dayjs();
const app = express(); const app = express();
const i8n = makeI8N(service.name); const i8n = makeI8N(service.name);
@@ -113,8 +120,7 @@ function server(
} }
app.use(express.urlencoded({ extended: false })); app.use(express.urlencoded({ extended: false }));
// todo: pass options in here? app.use(express.static(path.resolve(__dirname, "..", "web", "public")));
app.use(express.static("./web/public"));
app.engine("eta", Eta.renderFile); app.engine("eta", Eta.renderFile);
app.set("view engine", "eta"); app.set("view engine", "eta");
@@ -251,6 +257,28 @@ function server(
}); });
app.get(PRESENTATION_MAP_ROUTE, (_, res) => { app.get(PRESENTATION_MAP_ROUTE, (_, res) => {
const LastModified = startUpTime.format("HH:mm:ss D MMM YYYY");
const nowPlayingRatingsMatch = (value: number) => {
const rating = ratingFromInt(value);
const nextLove = { ...rating, love: !rating.love };
const nextStar = { ...rating, stars: (rating.stars === 5 ? 0 : rating.stars + 1) }
const loveRatingIcon = bonobUrl.append({pathname: rating.love ? '/love-selected.svg' : '/love-unselected.svg'}).href();
const starsRatingIcon = bonobUrl.append({pathname: `/star${rating.stars}.svg`}).href();
return `<Match propname="rating" value="${value}">
<Ratings>
<Rating Id="${ratingAsInt(nextLove)}" AutoSkip="NEVER" OnSuccessStringId="LOVE_SUCCESS" StringId="LOVE">
<Icon Controller="universal" LastModified="${LastModified}" Uri="${loveRatingIcon}" />
</Rating>
<Rating Id="${-ratingAsInt(nextStar)}" AutoSkip="NEVER" OnSuccessStringId="STAR_SUCCESS" StringId="STAR">
<Icon Controller="universal" LastModified="${LastModified}" Uri="${starsRatingIcon}" />
</Rating>
</Ratings>
</Match>`
}
res.type("application/xml").send(`<?xml version="1.0" encoding="utf-8" ?> res.type("application/xml").send(`<?xml version="1.0" encoding="utf-8" ?>
<Presentation> <Presentation>
<PresentationMap type="ArtWorkSizeMap"> <PresentationMap type="ArtWorkSizeMap">
@@ -283,16 +311,34 @@ function server(
</SearchCategories> </SearchCategories>
</Match> </Match>
</PresentationMap> </PresentationMap>
<PresentationMap type="NowPlayingRatings" trackEnabled="true" programEnabled="false">
${nowPlayingRatingsMatch(100)}
${nowPlayingRatingsMatch(101)}
${nowPlayingRatingsMatch(110)}
${nowPlayingRatingsMatch(111)}
${nowPlayingRatingsMatch(120)}
${nowPlayingRatingsMatch(121)}
${nowPlayingRatingsMatch(130)}
${nowPlayingRatingsMatch(131)}
${nowPlayingRatingsMatch(140)}
${nowPlayingRatingsMatch(141)}
${nowPlayingRatingsMatch(150)}
${nowPlayingRatingsMatch(151)}
</PresentationMap>
</Presentation>`); </Presentation>`);
}); });
app.get("/stream/track/:id", async (req, res) => { app.get("/stream/track/:id", async (req, res) => {
const id = req.params["id"]!; const id = req.params["id"]!;
const trace = uuid();
logger.info( 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( const authToken = pipe(
req.header(BONOB_ACCESS_TOKEN_HEADER), req.query[BONOB_ACCESS_TOKEN_HEADER] as string,
O.fromNullable, O.fromNullable,
O.map((accessToken) => accessTokens.authTokenFor(accessToken)), O.map((accessToken) => accessTokens.authTokenFor(accessToken)),
O.getOrElseW(() => undefined) O.getOrElseW(() => undefined)
@@ -310,42 +356,44 @@ function server(
}) })
.then((stream) => ({ musicLibrary: it, stream })) .then((stream) => ({ musicLibrary: it, stream }))
) )
.then(({ musicLibrary, stream }) => { .then(({ stream }) => {
logger.info( logger.info(
`stream response from music service for ${id}, status=${ `${trace} bnb<- stream response from music service for ${id}, status=${
stream.status stream.status
}, headers=(${JSON.stringify(stream.headers)})` }, headers=(${JSON.stringify(stream.headers)})`
); );
const sonosisfyContentType = (contentType: string) =>
contentType
.split(";")
.map((it) => it.trim())
.map((it) => sonosifyMimeType(it))
.join("; ");
const respondWith = ({ const respondWith = ({
status, status,
filter, filter,
headers, headers,
sendStream, sendStream,
nowPlaying,
}: { }: {
status: number; status: number;
filter: Transform; filter: Transform;
headers: Record<string, string | undefined>; headers: Record<string, string>;
sendStream: boolean; sendStream: boolean;
nowPlaying: boolean;
}) => { }) => {
logger.info( logger.info(
`<- /stream/track/${id}, status=${status}, headers=${JSON.stringify( `${trace} bnb-> ${
headers req.path
)}` }, status=${status}, headers=${JSON.stringify(headers)}`
); );
(nowPlaying
? musicLibrary.nowPlaying(id)
: Promise.resolve(true)
).then((_) => {
res.status(status); res.status(status);
Object.entries(stream.headers) Object.entries(headers)
.filter(([_, v]) => v !== undefined) .filter(([_, v]) => v !== undefined)
.forEach(([header, value]) => res.setHeader(header, value)); .forEach(([header, value]) => {
res.setHeader(header, value!);
});
if (sendStream) stream.stream.pipe(filter).pipe(res); if (sendStream) stream.stream.pipe(filter).pipe(res);
else res.send(); else res.send();
});
}; };
if (stream.status == 200) { if (stream.status == 200) {
@@ -353,25 +401,27 @@ function server(
status: 200, status: 200,
filter: new PassThrough(), filter: new PassThrough(),
headers: { headers: {
"content-type": stream.headers["content-type"], "content-type": sonosisfyContentType(
stream.headers["content-type"]
),
"content-length": stream.headers["content-length"], "content-length": stream.headers["content-length"],
"accept-ranges": stream.headers["accept-ranges"], "accept-ranges": stream.headers["accept-ranges"],
}, },
sendStream: req.method == "GET", sendStream: req.method == "GET",
nowPlaying: req.method == "GET",
}); });
} else if (stream.status == 206) { } else if (stream.status == 206) {
respondWith({ respondWith({
status: 206, status: 206,
filter: new PassThrough(), filter: new PassThrough(),
headers: { headers: {
"content-type": stream.headers["content-type"], "content-type": sonosisfyContentType(
stream.headers["content-type"]
),
"content-length": stream.headers["content-length"], "content-length": stream.headers["content-length"],
"content-range": stream.headers["content-range"], "content-range": stream.headers["content-range"],
"accept-ranges": stream.headers["accept-ranges"], "accept-ranges": stream.headers["accept-ranges"],
}, },
sendStream: req.method == "GET", sendStream: req.method == "GET",
nowPlaying: req.method == "GET",
}); });
} else { } else {
respondWith({ respondWith({
@@ -379,7 +429,6 @@ function server(
filter: new PassThrough(), filter: new PassThrough(),
headers: {}, headers: {},
sendStream: req.method == "GET", sendStream: req.method == "GET",
nowPlaying: false,
}); });
} }
}); });
@@ -457,25 +506,22 @@ function server(
"centre", "centre",
]; ];
app.get("/art/:type/:ids/size/:size", (req, res) => { app.get("/art/:ids/size/:size", (req, res) => {
const authToken = accessTokens.authTokenFor( const authToken = accessTokens.authTokenFor(
req.query[BONOB_ACCESS_TOKEN_HEADER] as string req.query[BONOB_ACCESS_TOKEN_HEADER] as string
); );
const type = req.params["type"]!;
const ids = req.params["ids"]!.split("&"); const ids = req.params["ids"]!.split("&");
const size = Number.parseInt(req.params["size"]!); const size = Number.parseInt(req.params["size"]!);
if (!authToken) { if (!authToken) {
return res.status(401).send(); return res.status(401).send();
} else if (type != "artist" && type != "album") {
return res.status(400).send();
} else if (!(size > 0)) { } else if (!(size > 0)) {
return res.status(400).send(); return res.status(400).send();
} }
return musicService return musicService
.login(authToken) .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((coverArts) => coverArts.filter((it) => it))
.then(shuffle) .then(shuffle)
.then((coverArts) => { .then((coverArts) => {
@@ -513,12 +559,9 @@ function server(
} }
}) })
.catch((e: Error) => { .catch((e: Error) => {
logger.error( logger.error(`Failed fetching image ${ids.join("&")}/size/${size}`, {
`Failed fetching image ${type}/${ids.join("&")}/size/${size}`,
{
cause: e, cause: e,
} });
);
return res.status(500).send(); return res.status(500).send();
}); });
}); });

View File

@@ -14,11 +14,11 @@ import {
Genre, Genre,
MusicService, MusicService,
Playlist, Playlist,
Rating,
slice2, slice2,
Track, Track,
} from "./music_service"; } from "./music_service";
import { AccessTokens } from "./access_tokens"; import { AccessTokens } from "./access_tokens";
import { BONOB_ACCESS_TOKEN_HEADER } from "./server";
import { Clock } from "./clock"; import { Clock } from "./clock";
import { URLBuilder } from "./url_builder"; import { URLBuilder } from "./url_builder";
import { asLANGs, I8N } from "./i8n"; import { asLANGs, I8N } from "./i8n";
@@ -81,6 +81,13 @@ export type GetDeviceAuthTokenResult = {
}; };
}; };
export const ratingAsInt = (rating: Rating): number =>
rating.stars * 10 + (rating.love ? 1 : 0) + 100;
export const ratingFromInt = (value: number): Rating => {
const x = value - 100;
return { love: x % 10 == 1, stars: Math.floor(x / 10) };
};
export type MediaCollection = { export type MediaCollection = {
id: string; id: string;
itemType: "collection"; itemType: "collection";
@@ -215,10 +222,7 @@ const genre = (bonobUrl: URLBuilder, genre: Genre) => ({
itemType: "container", itemType: "container",
id: `genre:${genre.id}`, id: `genre:${genre.id}`,
title: genre.name, title: genre.name,
albumArtURI: iconArtURI( albumArtURI: iconArtURI(bonobUrl, iconForGenre(genre.name)).href(),
bonobUrl,
iconForGenre(genre.name)
).href(),
}); });
const playlist = (bonobUrl: URLBuilder, playlist: Playlist) => ({ const playlist = (bonobUrl: URLBuilder, playlist: Playlist) => ({
@@ -238,37 +242,44 @@ export const playlistAlbumArtURL = (
bonobUrl: URLBuilder, bonobUrl: URLBuilder,
playlist: Playlist 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) { if (ids.length == 0) {
return iconArtURI(bonobUrl, "error"); return iconArtURI(bonobUrl, "error");
} else { } else {
return bonobUrl.append({ 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) => export const defaultAlbumArtURI = (
bonobUrl.append({ pathname: `/art/album/${album.id}/size/180` });
export const iconArtURI = (
bonobUrl: URLBuilder, 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({ bonobUrl.append({
pathname: `/icon/${icon}/size/legacy` pathname: `/icon/${icon}/size/legacy`,
}); });
export const defaultArtistArtURI = ( export const defaultArtistArtURI = (
bonobUrl: URLBuilder, bonobUrl: URLBuilder,
artist: ArtistSummary 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) => ({ export const album = (bonobUrl: URLBuilder, album: AlbumSummary) => ({
itemType: "album", itemType: "album",
id: `album:${album.id}`, id: `album:${album.id}`,
artist: album.artistName, artist: album.artistName,
artistId: album.artistId, artistId: `artist:${album.artistId}`,
title: album.name, title: album.name,
albumArtURI: defaultAlbumArtURI(bonobUrl, album).href(), albumArtURI: defaultAlbumArtURI(bonobUrl, album).href(),
canPlay: true, canPlay: true,
@@ -281,22 +292,25 @@ export const album = (bonobUrl: URLBuilder, album: AlbumSummary) => ({
export const track = (bonobUrl: URLBuilder, track: Track) => ({ export const track = (bonobUrl: URLBuilder, track: Track) => ({
itemType: "track", itemType: "track",
id: `track:${track.id}`, id: `track:${track.id}`,
mimeType: track.mimeType, mimeType: sonosifyMimeType(track.mimeType),
title: track.name, title: track.name,
trackMetadata: { trackMetadata: {
album: track.album.name, album: track.album.name,
albumId: track.album.id, albumId: `album:${track.album.id}`,
albumArtist: track.artist.name, albumArtist: track.artist.name,
albumArtistId: track.artist.id, albumArtistId: `artist:${track.artist.id}`,
albumArtURI: defaultAlbumArtURI(bonobUrl, track.album).href(), albumArtURI: defaultAlbumArtURI(bonobUrl, track).href(),
artist: track.artist.name, artist: track.artist.name,
artistId: track.artist.id, artistId: `artist:${track.artist.id}`,
duration: track.duration, duration: track.duration,
genre: track.album.genre?.name, genre: track.album.genre?.name,
genreId: track.album.genre?.id, genreId: track.album.genre?.id,
trackNumber: track.number, trackNumber: track.number,
}, },
dynamic: {
property: [{ name: "rating", value: `${ratingAsInt(track.rating)}` }],
},
}); });
export const artist = (bonobUrl: URLBuilder, artist: ArtistSummary) => ({ export const artist = (bonobUrl: URLBuilder, artist: ArtistSummary) => ({
@@ -368,7 +382,7 @@ function bindSmapiSoapServiceToExpress(
const urlWithToken = (accessToken: string) => const urlWithToken = (accessToken: string) =>
bonobUrl.append({ bonobUrl.append({
searchParams: { searchParams: {
"bat": accessToken, bat: accessToken,
}, },
}); });
@@ -400,14 +414,9 @@ function bindSmapiSoapServiceToExpress(
getMediaURIResult: bonobUrl getMediaURIResult: bonobUrl
.append({ .append({
pathname: `/stream/${type}/${typeId}`, pathname: `/stream/${type}/${typeId}`,
searchParams: { bat: accessToken },
}) })
.href(), .href(),
httpHeaders: [
{
header: BONOB_ACCESS_TOKEN_HEADER,
value: accessToken,
},
],
})), })),
getMediaMetadata: async ( getMediaMetadata: async (
{ id }: { id: string }, { id }: { id: string },
@@ -505,25 +514,7 @@ function bindSmapiSoapServiceToExpress(
case "track": case "track":
return musicLibrary.track(typeId).then((it) => ({ return musicLibrary.track(typeId).then((it) => ({
getExtendedMetadataResult: { getExtendedMetadataResult: {
mediaMetadata: { mediaMetadata: track(urlWithToken(accessToken), it),
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(),
},
},
}, },
})); }));
case "album": case "album":
@@ -598,6 +589,24 @@ function bindSmapiSoapServiceToExpress(
albumArtURI: iconArtURI(bonobUrl, "albums").href(), albumArtURI: iconArtURI(bonobUrl, "albums").href(),
itemType: "albumList", itemType: "albumList",
}, },
{
id: "randomAlbums",
title: lang("random"),
albumArtURI: iconArtURI(bonobUrl, "random").href(),
itemType: "albumList",
},
{
id: "favouriteAlbums",
title: lang("favourites"),
albumArtURI: iconArtURI(bonobUrl, "heart").href(),
itemType: "albumList",
},
{
id: "starredAlbums",
title: lang("topRated"),
albumArtURI: iconArtURI(bonobUrl, "star").href(),
itemType: "albumList",
},
{ {
id: "playlists", id: "playlists",
title: lang("playlists"), title: lang("playlists"),
@@ -615,18 +624,6 @@ function bindSmapiSoapServiceToExpress(
albumArtURI: iconArtURI(bonobUrl, "genres").href(), albumArtURI: iconArtURI(bonobUrl, "genres").href(),
itemType: "container", itemType: "container",
}, },
{
id: "randomAlbums",
title: lang("random"),
albumArtURI: iconArtURI(bonobUrl, "random").href(),
itemType: "albumList",
},
{
id: "starredAlbums",
title: lang("starred"),
albumArtURI: iconArtURI(bonobUrl, "starred").href(),
itemType: "albumList",
},
{ {
id: "recentlyAdded", id: "recentlyAdded",
title: lang("recentlyAdded"), title: lang("recentlyAdded"),
@@ -707,6 +704,11 @@ function bindSmapiSoapServiceToExpress(
type: "random", type: "random",
...paging, ...paging,
}); });
case "favouriteAlbums":
return albums({
type: "favourited",
...paging,
});
case "starredAlbums": case "starredAlbums":
return albums({ return albums({
type: "starred", type: "starred",
@@ -714,17 +716,17 @@ function bindSmapiSoapServiceToExpress(
}); });
case "recentlyAdded": case "recentlyAdded":
return albums({ return albums({
type: "newest", type: "recentlyAdded",
...paging, ...paging,
}); });
case "recentlyPlayed": case "recentlyPlayed":
return albums({ return albums({
type: "recent", type: "recentlyPlayed",
...paging, ...paging,
}); });
case "mostPlayed": case "mostPlayed":
return albums({ return albums({
type: "frequent", type: "mostPlayed",
...paging, ...paging,
}); });
case "genres": case "genres":
@@ -890,6 +892,18 @@ function bindSmapiSoapServiceToExpress(
} }
}) })
.then((_) => ({ removeFromContainerResult: { updateId: "" } })), .then((_) => ({ removeFromContainerResult: { updateId: "" } })),
rateItem: async (
{ id, rating }: { id: string; rating: number },
_,
soapyHeaders: SoapyHeaders
) =>
auth(musicService, accessTokens, soapyHeaders?.credentials)
.then(splitId(id))
.then(({ musicLibrary, typeId }) =>
musicLibrary.rate(typeId, ratingFromInt(Math.abs(rating)))
)
.then((_) => ({ rateItemResult: { shouldSkip: false } })),
setPlayedSeconds: async ( setPlayedSeconds: async (
{ id, seconds }: { id: string; seconds: string }, { id, seconds }: { id: string; seconds: string },
_, _,
@@ -900,18 +914,29 @@ function bindSmapiSoapServiceToExpress(
.then(({ musicLibrary, type, typeId }) => { .then(({ musicLibrary, type, typeId }) => {
switch (type) { switch (type) {
case "track": case "track":
musicLibrary.track(typeId).then(({ duration }) => { return musicLibrary
.track(typeId)
.then(({ duration }) => {
if ( if (
(duration < 30 && +seconds >= 10) || (duration < 30 && +seconds >= 10) ||
(duration >= 30 && +seconds >= 30) (duration >= 30 && +seconds >= 30)
) { ) {
musicLibrary.scrobble(typeId); return musicLibrary.scrobble(typeId);
} else {
return Promise.resolve(true);
}
})
.then(() => {
if (+seconds > 0) {
return musicLibrary.nowPlaying(typeId);
} else {
return Promise.resolve(true);
} }
}); });
break; break;
default: default:
logger.info("Unsupported scrobble", { id, seconds }); logger.info("Unsupported scrobble", { id, seconds });
break; return Promise.resolve(true);
} }
}) })
.then((_) => ({ .then((_) => ({

View File

@@ -9,27 +9,40 @@ import qs from "querystring";
import { URLBuilder } from "./url_builder"; import { URLBuilder } from "./url_builder";
import { LANG } from "./i8n"; 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"; export const PRESENTATION_AND_STRINGS_VERSION =
process.env["BNB_DEBUG"] === "true"
? `${Math.round(new Date().getTime() / 1000)}`
: "23";
// NOTE: manifest requires https for the URL, // NOTE: manifest requires https for the URL, otherwise you will get an error trying to register
// otherwise you will get an error trying to register
export type Capability = export type Capability =
| "search" | "search"
| "trFavorites" | "trFavorites" // Favorites: Adding/Removing Tracks (deprecated)
| "alFavorites" | "alFavorites" // Favorites: Adding/Removing Albums (deprecated)
| "ucPlaylists" | "ucPlaylists" // User Content Playlists
| "extendedMD" | "extendedMD" // Extended Metadata (More Menu, Info & Options)
| "contextHeaders" | "contextHeaders"
| "authorizationHeader" | "authorizationHeader"
| "logging" | "logging" // Playback duration logging at track end (deprecated)
| "manifest"; | "manifest";
export const BONOB_CAPABILITIES: Capability[] = [ export const BONOB_CAPABILITIES: Capability[] = [
"search", "search",
// "trFavorites",
// "alFavorites",
"ucPlaylists", "ucPlaylists",
"extendedMD", "extendedMD",
"logging", "logging",
@@ -88,8 +101,8 @@ export interface Sonos {
export const SONOS_DISABLED: Sonos = { export const SONOS_DISABLED: Sonos = {
devices: () => Promise.resolve([]), devices: () => Promise.resolve([]),
services: () => Promise.resolve([]), services: () => Promise.resolve([]),
remove: (_: number) => Promise.resolve(true), remove: (_: number) => Promise.resolve(false),
register: (_: Service) => Promise.resolve(true), register: (_: Service) => Promise.resolve(false),
}; };
export const asService = (musicService: MusicService): Service => ({ export const asService = (musicService: MusicService): Service => ({
@@ -118,7 +131,7 @@ export const asDevice = (sonosDevice: SonosDevice): Device => ({
export const asRemoveCustomdForm = (csrfToken: string, sid: number) => ({ export const asRemoveCustomdForm = (csrfToken: string, sid: number) => ({
csrfToken, csrfToken,
sid: `${sid}` sid: `${sid}`,
}); });
export const asCustomdForm = (csrfToken: string, service: Service) => ({ 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)); const anyDevice = await sonosDevices().then((devices) => head(devices));
if (!anyDevice) { if (!anyDevice) {
@@ -195,7 +211,7 @@ export function autoDiscoverySonos(sonosSeedHost?: string): Sonos {
); );
return false; return false;
} }
const form = customdForm(csrfToken) const form = customdForm(csrfToken);
logger.info(`${action} with sonos @ ${customd}`, { form }); logger.info(`${action} with sonos @ ${customd}`, { form });
return axios return axios
.post(customd, new URLSearchParams(qs.stringify(form)), { .post(customd, new URLSearchParams(qs.stringify(form)), {
@@ -218,16 +234,20 @@ export function autoDiscoverySonos(sonosSeedHost?: string): Sonos {
) )
.then((it) => it.map(asService)), .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 = ( export type Discovery = {
discoveryEnabled: boolean = true, enabled: boolean;
sonosSeedHost: string | undefined = undefined seedHost?: string;
): Sonos => };
discoveryEnabled ? autoDiscoverySonos(sonosSeedHost) : SONOS_DISABLED;
export default sonos; export default (sonosDiscovery: Discovery = { enabled: true }): Sonos =>
sonosDiscovery.enabled
? autoDiscoverySonos(sonosDiscovery.seedHost)
: SONOS_DISABLED;

View File

@@ -18,14 +18,20 @@ import {
AlbumSummary, AlbumSummary,
Genre, Genre,
Track, Track,
CoverArt,
Rating,
AlbumQueryType,
} from "./music_service"; } from "./music_service";
import X2JS from "x2js";
import sharp from "sharp"; import sharp from "sharp";
import _, { pick } from "underscore"; import _ from "underscore";
import fse from "fs-extra";
import path from "path";
import axios, { AxiosRequestConfig } from "axios"; import axios, { AxiosRequestConfig } from "axios";
import { Encryption } from "./encryption"; import { Encryption } from "./encryption";
import randomString from "./random_string"; import randomString from "./random_string";
import { b64Encode, b64Decode } from "./b64";
import logger from "./logger";
export const BROWSER_HEADERS = { export const BROWSER_HEADERS = {
accept: accept:
@@ -55,36 +61,36 @@ export const isDodgyImage = (url: string) => url.endsWith(DODGY_IMAGE_NAME);
export const validate = (url: string | undefined) => export const validate = (url: string | undefined) =>
url && !isDodgyImage(url) ? url : undefined; url && !isDodgyImage(url) ? url : undefined;
export type SubconicEnvelope = { export type SubsonicEnvelope = {
"subsonic-response": SubsonicResponse; "subsonic-response": SubsonicResponse;
}; };
export type SubsonicResponse = { export type SubsonicResponse = {
_status: string; status: string;
}; };
export type album = { export type album = {
_id: string; id: string;
_name: string; name: string;
_genre: string | undefined; artist: string | undefined;
_year: string | undefined; artistId: string | undefined;
_coverArt: string | undefined; coverArt: string | undefined;
_artist: string; genre: string | undefined;
_artistId: string; year: string | undefined;
}; };
export type artistSummary = { export type artistSummary = {
_id: string; id: string;
_name: string; name: string;
_albumCount: string; albumCount: number;
_artistImageUrl: string | undefined; artistImageUrl: string | undefined;
}; };
export type GetArtistsResponse = SubsonicResponse & { export type GetArtistsResponse = SubsonicResponse & {
artists: { artists: {
index: { index: {
artist: artistSummary[]; artist: artistSummary[];
_name: string; name: string;
}[]; }[];
}; };
}; };
@@ -96,9 +102,9 @@ export type GetAlbumListResponse = SubsonicResponse & {
}; };
export type genre = { export type genre = {
_songCount: string; songCount: number;
_albumCount: string; albumCount: number;
__text: string; value: string;
}; };
export type GetGenresResponse = SubsonicResponse & { export type GetGenresResponse = SubsonicResponse & {
@@ -109,8 +115,8 @@ export type GetGenresResponse = SubsonicResponse & {
export type SubsonicError = SubsonicResponse & { export type SubsonicError = SubsonicResponse & {
error: { error: {
_code: string; code: string;
_message: string; message: string;
}; };
}; };
@@ -140,22 +146,25 @@ export type GetArtistResponse = SubsonicResponse & {
}; };
export type song = { export type song = {
_id: string; id: string;
_parent: string; parent: string | undefined;
_title: string; title: string;
_album: string; album: string | undefined;
_artist: string; artist: string | undefined;
_track: string | undefined; track: number | undefined;
_genre: string; year: string | undefined;
_coverArt: string; genre: string | undefined;
_created: "2004-11-08T23:36:11"; coverArt: string | undefined;
_duration: string | undefined; created: string | undefined;
_bitRate: "128"; duration: number | undefined;
_suffix: "mp3"; bitRate: number | undefined;
_contentType: string; suffix: string | undefined;
_albumId: string; contentType: string | undefined;
_artistId: string; albumId: string | undefined;
_type: "music"; artistId: string | undefined;
type: string | undefined;
userRating: number | undefined;
starred: string | undefined;
}; };
export type GetAlbumResponse = { export type GetAlbumResponse = {
@@ -165,30 +174,15 @@ export type GetAlbumResponse = {
}; };
export type playlist = { export type playlist = {
_id: string; id: string;
_name: string; name: string;
};
export type entry = {
_id: string;
_parent: string;
_title: string;
_album: string;
_artist: string;
_track: string;
_year: string;
_genre: string;
_contentType: string;
_duration: string;
_albumId: string;
_artistId: string;
}; };
export type GetPlaylistResponse = { export type GetPlaylistResponse = {
playlist: { playlist: {
_id: string; id: string;
_name: string; name: string;
entry: entry[]; entry: song[];
}; };
}; };
@@ -208,6 +202,13 @@ export type GetSongResponse = {
song: song; song: song;
}; };
export type GetStarredResponse = {
starred2: {
song: song[];
album: album[];
};
};
export type Search3Response = SubsonicResponse & { export type Search3Response = SubsonicResponse & {
searchResult3: { searchResult3: {
artist: artistSummary[]; artist: artistSummary[];
@@ -222,6 +223,12 @@ export function isError(
return (subsonicResponse as SubsonicError).error !== undefined; 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 = { export type IdName = {
id: string; id: string;
name: string; name: string;
@@ -238,31 +245,43 @@ export type getAlbumListParams = {
export const MAX_ALBUM_LIST = 500; export const MAX_ALBUM_LIST = 500;
const asTrack = (album: Album, song: song) => ({ const maybeAsCoverArt = (coverArt: string | undefined) =>
id: song._id, coverArt ? `coverArt:${coverArt}` : undefined;
name: song._title,
mimeType: song._contentType, export const asTrack = (album: Album, song: song): Track => ({
duration: parseInt(song._duration || "0"), id: song.id,
number: parseInt(song._track || "0"), name: song.title,
genre: maybeAsGenre(song._genre), mimeType: song.contentType!,
duration: song.duration || 0,
number: song.track || 0,
genre: maybeAsGenre(song.genre),
coverArt: maybeAsCoverArt(song.coverArt),
album, album,
artist: { artist: {
id: song._artistId, id: `${song.artistId!}`,
name: song._artist, name: song.artist!,
},
rating: {
love: song.starred != undefined,
stars:
song.userRating && song.userRating <= 5 && song.userRating >= 0
? song.userRating
: 0,
}, },
}); });
const asAlbum = (album: album) => ({ const asAlbum = (album: album): Album => ({
id: album._id, id: album.id,
name: album._name, name: album.name,
year: album._year, year: album.year,
genre: maybeAsGenre(album._genre), genre: maybeAsGenre(album.genre),
artistId: album._artistId, artistId: album.artistId,
artistName: album._artist, artistName: album.artist,
coverArt: maybeAsCoverArt(album.coverArt),
}); });
export const asGenre = (genreName: string) => ({ export const asGenre = (genreName: string) => ({
id: genreName, id: b64Encode(genreName),
name: genreName, name: genreName,
}); });
@@ -297,19 +316,73 @@ export const asURLSearchParams = (q: any) => {
return urlSearchParams; return urlSearchParams;
}; };
export class Navidrome implements MusicService { export type ImageFetcher = (url: string) => Promise<CoverArt | undefined>;
export const cachingImageFetcher =
(cacheDir: string, delegate: ImageFetcher) =>
async (url: string): Promise<CoverArt | undefined> => {
const filename = path.join(cacheDir, `${Md5.hashStr(url)}.png`);
return fse
.readFile(filename)
.then((data) => ({ contentType: "image/png", data }))
.catch(() =>
delegate(url).then((image) => {
if (image) {
return sharp(image.data)
.png()
.toBuffer()
.then((png) => {
return fse
.writeFile(filename, png)
.then(() => ({ contentType: "image/png", data: png }));
});
} else {
return undefined;
}
})
);
};
export const axiosImageFetcher = (url: string): Promise<CoverArt | undefined> =>
axios
.get(url, {
headers: BROWSER_HEADERS,
responseType: "arraybuffer",
})
.then((res) => ({
contentType: res.headers["content-type"],
data: Buffer.from(res.data, "binary"),
}))
.catch(() => undefined);
const AlbumQueryTypeToSubsonicType: Record<AlbumQueryType, string> = {
alphabeticalByArtist: "alphabeticalByArtist",
alphabeticalByName: "alphabeticalByName",
byGenre: "byGenre",
random: "random",
recentlyPlayed: "recent",
mostPlayed: "frequent",
recentlyAdded: "newest",
favourited: "starred",
starred: "highest",
};
export class Subsonic implements MusicService {
url: string; url: string;
encryption: Encryption; encryption: Encryption;
streamClientApplication: StreamClientApplication; streamClientApplication: StreamClientApplication;
externalImageFetcher: ImageFetcher;
constructor( constructor(
url: string, url: string,
encryption: Encryption, encryption: Encryption,
streamClientApplication: StreamClientApplication = DEFAULT streamClientApplication: StreamClientApplication = DEFAULT,
externalImageFetcher: ImageFetcher = axiosImageFetcher
) { ) {
this.url = url; this.url = url;
this.encryption = encryption; this.encryption = encryption;
this.streamClientApplication = streamClientApplication; this.streamClientApplication = streamClientApplication;
this.externalImageFetcher = externalImageFetcher;
} }
get = async ( get = async (
@@ -334,7 +407,7 @@ export class Navidrome implements MusicService {
}) })
.then((response) => { .then((response) => {
if (response.status != 200 && response.status != 206) { 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; } else return response;
}); });
@@ -343,51 +416,27 @@ export class Navidrome implements MusicService {
path: string, path: string,
q: {} = {} q: {} = {}
): Promise<T> => ): Promise<T> =>
this.get({ username, password }, path, q) this.get({ username, password }, path, { f: "json", ...q })
.then( .then((response) => response.data as SubsonicEnvelope)
(response) =>
new X2JS({
arrayAccessFormPaths: [
"subsonic-response.album.song",
"subsonic-response.albumList2.album",
"subsonic-response.artist.album",
"subsonic-response.artists.index",
"subsonic-response.artists.index.artist",
"subsonic-response.artistInfo2.similarArtist",
"subsonic-response.genres.genre",
"subsonic-response.playlist.entry",
"subsonic-response.playlists.playlist",
"subsonic-response.searchResult3.album",
"subsonic-response.searchResult3.artist",
"subsonic-response.searchResult3.song",
"subsonic-response.similarSongs2.song",
"subsonic-response.topSongs.song",
],
}).xml2js(response.data) as SubconicEnvelope
)
.then((json) => json["subsonic-response"]) .then((json) => json["subsonic-response"])
.then((json) => { .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; else return json as unknown as T;
}); });
generateToken = async (credentials: Credentials) => generateToken = async (credentials: Credentials) =>
this.getJSON(credentials, "/rest/ping.view") this.getJSON(credentials, "/rest/ping.view")
.then(() => ({ .then(() => ({
authToken: Buffer.from( authToken: b64Encode(
JSON.stringify(this.encryption.encrypt(JSON.stringify(credentials))) JSON.stringify(this.encryption.encrypt(JSON.stringify(credentials)))
).toString("base64"), ),
userId: credentials.username, userId: credentials.username,
nickname: credentials.username, nickname: credentials.username,
})) }))
.catch((e) => ({ message: `${e}` })); .catch((e) => ({ message: `${e}` }));
parseToken = (token: string): Credentials => parseToken = (token: string): Credentials =>
JSON.parse( JSON.parse(this.encryption.decrypt(JSON.parse(b64Decode(token))));
this.encryption.decrypt(
JSON.parse(Buffer.from(token, "base64").toString("ascii"))
)
);
getArtists = ( getArtists = (
credentials: Credentials credentials: Credentials
@@ -396,9 +445,9 @@ export class Navidrome implements MusicService {
.then((it) => (it.artists.index || []).flatMap((it) => it.artist || [])) .then((it) => (it.artists.index || []).flatMap((it) => it.artist || []))
.then((artists) => .then((artists) =>
artists.map((artist) => ({ artists.map((artist) => ({
id: artist._id, id: `${artist.id}`,
name: artist._name, name: artist.name,
albumCount: Number.parseInt(artist._albumCount), albumCount: artist.albumCount,
})) }))
); );
@@ -414,9 +463,9 @@ export class Navidrome implements MusicService {
large: validate(it.artistInfo2.largeImageUrl), large: validate(it.artistInfo2.largeImageUrl),
}, },
similarArtist: (it.artistInfo2.similarArtist || []).map((artist) => ({ similarArtist: (it.artistInfo2.similarArtist || []).map((artist) => ({
id: artist._id, id: `${artist.id}`,
name: artist._name, name: artist.name,
inLibrary: artist._id != "-1", inLibrary: artist.id != "-1",
})), })),
})); }));
@@ -424,12 +473,13 @@ export class Navidrome implements MusicService {
this.getJSON<GetAlbumResponse>(credentials, "/rest/getAlbum", { id }) this.getJSON<GetAlbumResponse>(credentials, "/rest/getAlbum", { id })
.then((it) => it.album) .then((it) => it.album)
.then((album) => ({ .then((album) => ({
id: album._id, id: album.id,
name: album._name, name: album.name,
year: album._year, year: album.year,
genre: maybeAsGenre(album._genre), genre: maybeAsGenre(album.genre),
artistId: album._artistId, artistId: album.artistId,
artistName: album._artist, artistName: album.artist,
coverArt: maybeAsCoverArt(album.coverArt),
})); }));
getArtist = ( getArtist = (
@@ -441,16 +491,9 @@ export class Navidrome implements MusicService {
}) })
.then((it) => it.artist) .then((it) => it.artist)
.then((it) => ({ .then((it) => ({
id: it._id, id: it.id,
name: it._name, name: it.name,
albums: (it.album || []).map((album) => ({ albums: this.toAlbumSummary(it.album || []),
id: album._id,
name: album._name,
year: album._year,
genre: maybeAsGenre(album._genre),
artistId: it._id,
artistName: it._name,
})),
})); }));
getArtistWithInfo = (credentials: Credentials, id: string) => getArtistWithInfo = (credentials: Credentials, id: string) =>
@@ -477,19 +520,25 @@ export class Navidrome implements MusicService {
}) })
.then((it) => it.song) .then((it) => it.song)
.then((song) => .then((song) =>
this.getAlbum(credentials, song._albumId).then((album) => this.getAlbum(credentials, song.albumId!).then((album) =>
asTrack(album, song) asTrack(album, song)
) )
); );
getStarred = (credentials: Credentials) =>
this.getJSON<GetStarredResponse>(credentials, "/rest/getStarred2").then(
(it) => new Set(it.starred2.song.map((it) => it.id))
);
toAlbumSummary = (albumList: album[]): AlbumSummary[] => toAlbumSummary = (albumList: album[]): AlbumSummary[] =>
albumList.map((album) => ({ albumList.map((album) => ({
id: album._id, id: album.id,
name: album._name, name: album.name,
year: album._year, year: album.year,
genre: maybeAsGenre(album._genre), genre: maybeAsGenre(album.genre),
artistId: album._artistId, artistId: album.artistId,
artistName: album._artist, artistName: album.artist,
coverArt: maybeAsCoverArt(album.coverArt),
})); }));
search3 = (credentials: Credentials, q: any) => search3 = (credentials: Credentials, q: any) =>
@@ -504,13 +553,38 @@ export class Navidrome implements MusicService {
songs: it.searchResult3.song || [], songs: it.searchResult3.song || [],
})); }));
getAlbumList2 = (credentials: Credentials, q: AlbumQuery) =>
Promise.all([
this.getArtists(credentials).then((it) =>
_.inject(it, (total, artist) => total + artist.albumCount, 0)
),
this.getJSON<GetAlbumListResponse>(credentials, "/rest/getAlbumList2", {
type: AlbumQueryTypeToSubsonicType[q.type],
...(q.genre ? { genre: b64Decode(q.genre) } : {}),
size: 500,
offset: q._index,
})
.then((response) => response.albumList2.album || [])
.then(this.toAlbumSummary),
]).then(([total, albums]) => ({
results: albums.slice(0, q._count),
total: albums.length == 500 ? total : q._index + albums.length,
}));
// getStarred2 = (credentials: Credentials): Promise<{ albums: Album[] }> =>
// this.getJSON<GetStarredResponse>(credentials, "/rest/getStarred2")
// .then((it) => it.starred2)
// .then((it) => ({
// albums: it.album.map(asAlbum),
// }));
async login(token: string) { async login(token: string) {
const navidrome = this; const subsonic = this;
const credentials: Credentials = this.parseToken(token); const credentials: Credentials = this.parseToken(token);
const musicLibrary: MusicLibrary = { const musicLibrary: MusicLibrary = {
artists: (q: ArtistQuery): Promise<Result<ArtistSummary>> => artists: (q: ArtistQuery): Promise<Result<ArtistSummary>> =>
navidrome subsonic
.getArtists(credentials) .getArtists(credentials)
.then(slice2(q)) .then(slice2(q))
.then(([page, total]) => ({ .then(([page, total]) => ({
@@ -518,46 +592,24 @@ export class Navidrome implements MusicService {
results: page.map((it) => ({ id: it.id, name: it.name })), results: page.map((it) => ({ id: it.id, name: it.name })),
})), })),
artist: async (id: string): Promise<Artist> => artist: async (id: string): Promise<Artist> =>
navidrome.getArtistWithInfo(credentials, id), subsonic.getArtistWithInfo(credentials, id),
albums: async (q: AlbumQuery): Promise<Result<AlbumSummary>> => { albums: async (q: AlbumQuery): Promise<Result<AlbumSummary>> =>
return Promise.all([ subsonic.getAlbumList2(credentials, q),
navidrome album: (id: string): Promise<Album> => subsonic.getAlbum(credentials, id),
.getArtists(credentials)
.then((it) =>
_.inject(it, (total, artist) => total + artist.albumCount, 0)
),
navidrome
.getJSON<GetAlbumListResponse>(credentials, "/rest/getAlbumList2", {
...pick(q, "type", "genre"),
size: 500,
offset: q._index,
})
.then((response) => response.albumList2.album || [])
.then(navidrome.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),
genres: () => genres: () =>
navidrome subsonic
.getJSON<GetGenresResponse>(credentials, "/rest/getGenres") .getJSON<GetGenresResponse>(credentials, "/rest/getGenres")
.then((it) => .then((it) =>
pipe( pipe(
it.genres.genre || [], it.genres.genre || [],
A.filter((it) => Number.parseInt(it._albumCount) > 0), A.filter((it) => it.albumCount > 0),
A.map((it) => it.__text), A.map((it) => it.value),
A.sort(ordString), A.sort(ordString),
A.map((it) => ({ id: it, name: it })) A.map((it) => ({ id: b64Encode(it), name: it }))
) )
), ),
tracks: (albumId: string) => tracks: (albumId: string) =>
navidrome subsonic
.getJSON<GetAlbumResponse>(credentials, "/rest/getAlbum", { .getJSON<GetAlbumResponse>(credentials, "/rest/getAlbum", {
id: albumId, id: albumId,
}) })
@@ -565,7 +617,41 @@ export class Navidrome implements MusicService {
.then((album) => .then((album) =>
(album.song || []).map((song) => asTrack(asAlbum(album), song)) (album.song || []).map((song) => asTrack(asAlbum(album), song))
), ),
track: (trackId: string) => navidrome.getTrack(credentials, trackId), track: (trackId: string) => subsonic.getTrack(credentials, trackId),
rate: (trackId: string, rating: Rating) =>
Promise.resolve(true)
.then(() => {
if (rating.stars >= 0 && rating.stars <= 5) {
return subsonic.getTrack(credentials, trackId);
} else {
throw `Invalid rating.stars value of ${rating.stars}`;
}
})
.then((track) => {
const thingsToUpdate = [];
if (track.rating.love != rating.love) {
thingsToUpdate.push(
subsonic.getJSON(
credentials,
`/rest/${rating.love ? "star" : "unstar"}`,
{
id: trackId,
}
)
);
}
if (track.rating.stars != rating.stars) {
thingsToUpdate.push(
subsonic.getJSON(credentials, `/rest/setRating`, {
id: trackId,
rating: rating.stars,
})
);
}
return Promise.all(thingsToUpdate);
})
.then(() => true)
.catch(() => false),
stream: async ({ stream: async ({
trackId, trackId,
range, range,
@@ -573,8 +659,8 @@ export class Navidrome implements MusicService {
trackId: string; trackId: string;
range: string | undefined; range: string | undefined;
}) => }) =>
navidrome.getTrack(credentials, trackId).then((track) => subsonic.getTrack(credentials, trackId).then((track) =>
navidrome subsonic
.get( .get(
credentials, credentials,
`/rest/stream`, `/rest/stream`,
@@ -608,40 +694,49 @@ export class Navidrome implements MusicService {
stream: res.data, stream: res.data,
})) }))
), ),
coverArt: async (id: string, type: "album" | "artist", size?: number) => { coverArt: async (coverArt: string, size?: number) => {
if (type == "album") { const [type, id] = splitCoverArtId(coverArt);
return navidrome.getCoverArt(credentials, id, size).then((res) => ({ if (type == "coverArt") {
return subsonic
.getCoverArt(credentials, id, size)
.then((res) => ({
contentType: res.headers["content-type"], contentType: res.headers["content-type"],
data: Buffer.from(res.data, "binary"), data: Buffer.from(res.data, "binary"),
})); }))
.catch((e) => {
logger.error(`Failed getting coverArt ${coverArt}: ${e}`);
return undefined;
});
} else { } else {
return navidrome.getArtistWithInfo(credentials, id).then((artist) => { return subsonic
.getArtistWithInfo(credentials, id)
.then((artist) => {
const albumsWithCoverArt = artist.albums.filter(
(it) => it.coverArt
);
if (artist.image.large) { if (artist.image.large) {
return axios return this.externalImageFetcher(artist.image.large!).then(
.get(artist.image.large!, { (image) => {
headers: BROWSER_HEADERS, if (image && size) {
responseType: "arraybuffer", return sharp(image.data)
})
.then((res) => {
const image = Buffer.from(res.data, "binary");
if (size) {
return sharp(image)
.resize(size) .resize(size)
.toBuffer() .toBuffer()
.then((resized) => ({ .then((resized) => ({
contentType: res.headers["content-type"], contentType: image.contentType,
data: resized, data: resized,
})); }));
} else { } else {
return { return image;
contentType: res.headers["content-type"],
data: image,
};
} }
}); }
} else if (artist.albums.length > 0) { );
return navidrome } else if (albumsWithCoverArt.length > 0) {
.getCoverArt(credentials, artist.albums[0]!.id, size) return subsonic
.getCoverArt(
credentials,
splitCoverArtId(albumsWithCoverArt[0]!.coverArt!)[1],
size
)
.then((res) => ({ .then((res) => ({
contentType: res.headers["content-type"], contentType: res.headers["content-type"],
data: Buffer.from(res.data, "binary"), data: Buffer.from(res.data, "binary"),
@@ -649,55 +744,59 @@ export class Navidrome implements MusicService {
} else { } else {
return undefined; return undefined;
} }
})
.catch((e) => {
logger.error(`Failed getting coverArt ${coverArt}: ${e}`);
return undefined;
}); });
} }
}, },
scrobble: async (id: string) => scrobble: async (id: string) =>
navidrome subsonic
.get(credentials, `/rest/scrobble`, { .getJSON(credentials, `/rest/scrobble`, {
id, id,
submission: true, submission: true,
}) })
.then((_) => true) .then((_) => true)
.catch(() => false), .catch(() => false),
nowPlaying: async (id: string) => nowPlaying: async (id: string) =>
navidrome subsonic
.get(credentials, `/rest/scrobble`, { .getJSON(credentials, `/rest/scrobble`, {
id, id,
submission: false, submission: false,
}) })
.then((_) => true) .then((_) => true)
.catch(() => false), .catch(() => false),
searchArtists: async (query: string) => searchArtists: async (query: string) =>
navidrome subsonic
.search3(credentials, { query, artistCount: 20 }) .search3(credentials, { query, artistCount: 20 })
.then(({ artists }) => .then(({ artists }) =>
artists.map((artist) => ({ artists.map((artist) => ({
id: artist._id, id: artist.id,
name: artist._name, name: artist.name,
})) }))
), ),
searchAlbums: async (query: string) => searchAlbums: async (query: string) =>
navidrome subsonic
.search3(credentials, { query, albumCount: 20 }) .search3(credentials, { query, albumCount: 20 })
.then(({ albums }) => navidrome.toAlbumSummary(albums)), .then(({ albums }) => subsonic.toAlbumSummary(albums)),
searchTracks: async (query: string) => searchTracks: async (query: string) =>
navidrome subsonic
.search3(credentials, { query, songCount: 20 }) .search3(credentials, { query, songCount: 20 })
.then(({ songs }) => .then(({ songs }) =>
Promise.all( Promise.all(
songs.map((it) => navidrome.getTrack(credentials, it._id)) songs.map((it) => subsonic.getTrack(credentials, it.id))
) )
), ),
playlists: async () => playlists: async () =>
navidrome subsonic
.getJSON<GetPlaylistsResponse>(credentials, "/rest/getPlaylists") .getJSON<GetPlaylistsResponse>(credentials, "/rest/getPlaylists")
.then((it) => it.playlists.playlist || []) .then((it) => it.playlists.playlist || [])
.then((playlists) => .then((playlists) =>
playlists.map((it) => ({ id: it._id, name: it._name })) playlists.map((it) => ({ id: it.id, name: it.name }))
), ),
playlist: async (id: string) => playlist: async (id: string) =>
navidrome subsonic
.getJSON<GetPlaylistResponse>(credentials, "/rest/getPlaylist", { .getJSON<GetPlaylistResponse>(credentials, "/rest/getPlaylist", {
id, id,
}) })
@@ -705,59 +804,54 @@ export class Navidrome implements MusicService {
.then((playlist) => { .then((playlist) => {
let trackNumber = 1; let trackNumber = 1;
return { return {
id: playlist._id, id: playlist.id,
name: playlist._name, name: playlist.name,
entries: (playlist.entry || []).map((entry) => ({ entries: (playlist.entry || []).map((entry) => ({
id: entry._id, ...asTrack(
name: entry._title, {
mimeType: entry._contentType, id: entry.albumId!,
duration: parseInt(entry._duration || "0"), name: entry.album!,
year: entry.year,
genre: maybeAsGenre(entry.genre),
artistName: entry.artist,
artistId: entry.artistId,
coverArt: maybeAsCoverArt(entry.coverArt),
},
entry
),
number: trackNumber++, number: trackNumber++,
genre: maybeAsGenre(entry._genre),
album: {
id: entry._albumId,
name: entry._album,
year: entry._year,
genre: maybeAsGenre(entry._genre),
artistName: entry._artist,
artistId: entry._artistId,
},
artist: {
id: entry._artistId,
name: entry._artist,
},
})), })),
}; };
}), }),
createPlaylist: async (name: string) => createPlaylist: async (name: string) =>
navidrome subsonic
.getJSON<GetPlaylistResponse>(credentials, "/rest/createPlaylist", { .getJSON<GetPlaylistResponse>(credentials, "/rest/createPlaylist", {
name, name,
}) })
.then((it) => it.playlist) .then((it) => it.playlist)
.then((it) => ({ id: it._id, name: it._name })), .then((it) => ({ id: it.id, name: it.name })),
deletePlaylist: async (id: string) => deletePlaylist: async (id: string) =>
navidrome subsonic
.getJSON<GetPlaylistResponse>(credentials, "/rest/deletePlaylist", { .getJSON<GetPlaylistResponse>(credentials, "/rest/deletePlaylist", {
id, id,
}) })
.then((_) => true), .then((_) => true),
addToPlaylist: async (playlistId: string, trackId: string) => addToPlaylist: async (playlistId: string, trackId: string) =>
navidrome subsonic
.getJSON<GetPlaylistResponse>(credentials, "/rest/updatePlaylist", { .getJSON<GetPlaylistResponse>(credentials, "/rest/updatePlaylist", {
playlistId, playlistId,
songIdToAdd: trackId, songIdToAdd: trackId,
}) })
.then((_) => true), .then((_) => true),
removeFromPlaylist: async (playlistId: string, indicies: number[]) => removeFromPlaylist: async (playlistId: string, indicies: number[]) =>
navidrome subsonic
.getJSON<GetPlaylistResponse>(credentials, "/rest/updatePlaylist", { .getJSON<GetPlaylistResponse>(credentials, "/rest/updatePlaylist", {
playlistId, playlistId,
songIndexToRemove: indicies, songIndexToRemove: indicies,
}) })
.then((_) => true), .then((_) => true),
similarSongs: async (id: string) => similarSongs: async (id: string) =>
navidrome subsonic
.getJSON<GetSimilarSongsResponse>( .getJSON<GetSimilarSongsResponse>(
credentials, credentials,
"/rest/getSimilarSongs2", "/rest/getSimilarSongs2",
@@ -767,15 +861,15 @@ export class Navidrome implements MusicService {
.then((songs) => .then((songs) =>
Promise.all( Promise.all(
songs.map((song) => songs.map((song) =>
navidrome subsonic
.getAlbum(credentials, song._albumId) .getAlbum(credentials, song.albumId!)
.then((album) => asTrack(album, song)) .then((album) => asTrack(album, song))
) )
) )
), ),
topSongs: async (artistId: string) => topSongs: async (artistId: string) =>
navidrome.getArtist(credentials, artistId).then(({ name }) => subsonic.getArtist(credentials, artistId).then(({ name }) =>
navidrome subsonic
.getJSON<GetTopSongsResponse>(credentials, "/rest/getTopSongs", { .getJSON<GetTopSongsResponse>(credentials, "/rest/getTopSongs", {
artist: name, artist: name,
count: 50, count: 50,
@@ -784,8 +878,8 @@ export class Navidrome implements MusicService {
.then((songs) => .then((songs) =>
Promise.all( Promise.all(
songs.map((song) => songs.map((song) =>
navidrome subsonic
.getAlbum(credentials, song._albumId) .getAlbum(credentials, song.albumId!)
.then((album) => asTrack(album, song)) .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

@@ -3,8 +3,17 @@ import { v4 as uuid } from "uuid";
import { Credentials } from "../src/smapi"; import { Credentials } from "../src/smapi";
import { Service, Device } from "../src/sonos"; import { Service, Device } from "../src/sonos";
import { Album, Artist, Track, albumToAlbumSummary, artistToArtistSummary, PlaylistSummary, Playlist } from "../src/music_service"; import {
Album,
Artist,
Track,
albumToAlbumSummary,
artistToArtistSummary,
PlaylistSummary,
Playlist,
} from "../src/music_service";
import randomString from "../src/random_string"; import randomString from "../src/random_string";
import { b64Encode } from "../src/b64";
const randomInt = (max: number) => Math.floor(Math.random() * Math.floor(max)); const randomInt = (max: number) => Math.floor(Math.random() * Math.floor(max));
const randomIpAddress = () => `127.0.${randomInt(255)}.${randomInt(255)}`; const randomIpAddress = () => `127.0.${randomInt(255)}.${randomInt(255)}`;
@@ -28,12 +37,14 @@ export const aService = (fields: Partial<Service> = {}): Service => ({
...fields, ...fields,
}); });
export function aPlaylistSummary(fields: Partial<PlaylistSummary> = {}): PlaylistSummary { export function aPlaylistSummary(
fields: Partial<PlaylistSummary> = {}
): PlaylistSummary {
return { return {
id: `playlist-${uuid()}`, id: `playlist-${uuid()}`,
name: `playlistname-${randomString()}`, name: `playlistname-${randomString()}`,
...fields ...fields,
} };
} }
export function aPlaylist(fields: Partial<Playlist> = {}): Playlist { export function aPlaylist(fields: Partial<Playlist> = {}): Playlist {
@@ -41,8 +52,8 @@ export function aPlaylist(fields: Partial<Playlist> = {}): Playlist {
id: `playlist-${uuid()}`, id: `playlist-${uuid()}`,
name: `playlist-${randomString()}`, name: `playlist-${randomString()}`,
entries: [aTrack(), aTrack()], entries: [aTrack(), aTrack()],
...fields ...fields,
} };
} }
export function aDevice(fields: Partial<Device> = {}): Device { export function aDevice(fields: Partial<Device> = {}): Device {
@@ -104,31 +115,43 @@ export function anArtist(fields: Partial<Artist> = {}): Artist {
], ],
...fields, ...fields,
}; };
artist.albums.forEach(album => { artist.albums.forEach((album) => {
album.artistId = artist.id; album.artistId = artist.id;
album.artistName = artist.name; album.artistName = artist.name;
}) });
return artist; return artist;
} }
export const HIP_HOP = { id: "genre_hip_hop", name: "Hip-Hop" }; export const aGenre = (name: string) => ({ id: b64Encode(name), name });
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 SAMPLE_GENRES = [HIP_HOP, METAL, NEW_WAVE, POP, POP_ROCK, REGGAE, ROCK, SKA]; 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)]; export const randomGenre = () => SAMPLE_GENRES[randomInt(SAMPLE_GENRES.length)];
export function aTrack(fields: Partial<Track> = {}): Track { export function aTrack(fields: Partial<Track> = {}): Track {
const id = uuid(); const id = uuid();
const artist = anArtist(); const artist = anArtist();
const genre = fields.genre || randomGenre(); const genre = fields.genre || randomGenre();
const rating = { love: false, stars: Math.floor(Math.random() * 5) };
return { return {
id, id,
name: `Track ${id}`, name: `Track ${id}`,
@@ -137,10 +160,14 @@ export function aTrack(fields: Partial<Track> = {}): Track {
number: randomInt(100), number: randomInt(100),
genre, genre,
artist: artistToArtistSummary(artist), artist: artistToArtistSummary(artist),
album: albumToAlbumSummary(anAlbum({ artistId: artist.id, artistName: artist.name, genre })), album: albumToAlbumSummary(
anAlbum({ artistId: artist.id, artistName: artist.name, genre })
),
coverArt: `coverArt:${uuid()}`,
rating,
...fields, ...fields,
}; };
} };
export function anAlbum(fields: Partial<Album> = {}): Album { export function anAlbum(fields: Partial<Album> = {}): Album {
const id = uuid(); const id = uuid();
@@ -151,6 +178,7 @@ export function anAlbum(fields: Partial<Album> = {}): Album {
year: `19${randomInt(99)}`, year: `19${randomInt(99)}`,
artistId: `Artist ${uuid()}`, artistId: `Artist ${uuid()}`,
artistName: `Artist ${randomString()}`, artistName: `Artist ${randomString()}`,
coverArt: `coverArt:${uuid()}`,
...fields, ...fields,
}; };
} }
@@ -167,7 +195,8 @@ export const BLONDIE: Artist = {
year: "1976", year: "1976",
genre: NEW_WAVE, genre: NEW_WAVE,
artistId: BLONDIE_ID, artistId: BLONDIE_ID,
artistName: BLONDIE_NAME artistName: BLONDIE_NAME,
coverArt: `coverArt:${uuid()}`,
}, },
{ {
id: uuid(), id: uuid(),
@@ -175,7 +204,8 @@ export const BLONDIE: Artist = {
year: "1978", year: "1978",
genre: POP_ROCK, genre: POP_ROCK,
artistId: BLONDIE_ID, artistId: BLONDIE_ID,
artistName: BLONDIE_NAME artistName: BLONDIE_NAME,
coverArt: `coverArt:${uuid()}`,
}, },
], ],
image: { image: {
@@ -192,9 +222,33 @@ export const BOB_MARLEY: Artist = {
id: BOB_MARLEY_ID, id: BOB_MARLEY_ID,
name: BOB_MARLEY_NAME, name: BOB_MARLEY_NAME,
albums: [ 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(),
{ id: uuid(), name: "Kaya", year: "1978", genre: SKA, artistId: BOB_MARLEY_ID, artistName: BOB_MARLEY_NAME }, 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: { image: {
small: "http://localhost/BOB_MARLEY/sml", small: "http://localhost/BOB_MARLEY/sml",
@@ -231,6 +285,7 @@ export const METALLICA: Artist = {
genre: METAL, genre: METAL,
artistId: METALLICA_ID, artistId: METALLICA_ID,
artistName: METALLICA_NAME, artistName: METALLICA_NAME,
coverArt: `coverArt:${uuid()}`,
}, },
{ {
id: uuid(), id: uuid(),
@@ -239,6 +294,7 @@ export const METALLICA: Artist = {
genre: METAL, genre: METAL,
artistId: METALLICA_ID, artistId: METALLICA_ID,
artistName: METALLICA_NAME, artistName: METALLICA_NAME,
coverArt: `coverArt:${uuid()}`,
}, },
], ],
image: { image: {
@@ -252,3 +308,4 @@ export const METALLICA: Artist = {
export const ALL_ARTISTS = [BOB_MARLEY, BLONDIE, MADONNA, METALLICA]; export const ALL_ARTISTS = [BOB_MARLEY, BLONDIE, MADONNA, METALLICA];
export const ALL_ALBUMS = ALL_ARTISTS.flatMap((it) => it.albums || []); export const ALL_ALBUMS = ALL_ARTISTS.flatMap((it) => it.albums || []);

View File

@@ -1,5 +1,81 @@
import { hostname } from "os"; 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", () => { describe("config", () => {
const OLD_ENV = process.env; const OLD_ENV = process.env;
@@ -43,26 +119,22 @@ describe("config", () => {
} }
describe("bonobUrl", () => { describe("bonobUrl", () => {
describe("when BONOB_URL is specified", () => { ["BNB_URL", "BONOB_URL", "BONOB_WEB_ADDRESS"].forEach((key) => {
describe(`when ${key} is specified`, () => {
it("should be used", () => { it("should be used", () => {
const url = "http://bonob1.example.com:8877/"; const url = "http://bonob1.example.com:8877/";
process.env["BONOB_URL"] = url;
expect(config().bonobUrl.href()).toEqual(url); process.env["BNB_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_URL"] = "";
process.env["BONOB_WEB_ADDRESS"] = url; process.env["BONOB_WEB_ADDRESS"] = "";
process.env[key] = url;
expect(config().bonobUrl.href()).toEqual(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", () => { describe("when BONOB_PORT is not specified", () => {
it(`should default to http://${hostname()}:4534`, () => { it(`should default to http://${hostname()}:4534`, () => {
expect(config().bonobUrl.href()).toEqual( expect(config().bonobUrl.href()).toEqual(
@@ -71,6 +143,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", () => { describe("when BONOB_PORT is specified as 3322", () => {
it(`should default to http://${hostname()}:3322`, () => { it(`should default to http://${hostname()}:3322`, () => {
process.env["BONOB_PORT"] = "3322"; process.env["BONOB_PORT"] = "3322";
@@ -82,92 +163,75 @@ 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("icons", () => {
describe("foregroundColor", () => { describe("foregroundColor", () => {
describe("when BONOB_ICON_FOREGROUND_COLOR is not specified", () => { ["BNB_ICON_FOREGROUND_COLOR", "BONOB_ICON_FOREGROUND_COLOR"].forEach(
(k) => {
describe(`when ${k} is not specified`, () => {
it(`should default to undefined`, () => { it(`should default to undefined`, () => {
expect(config().icons.foregroundColor).toEqual(undefined); expect(config().icons.foregroundColor).toEqual(undefined);
}); });
}); });
describe("when BONOB_ICON_FOREGROUND_COLOR is ''", () => { describe(`when ${k} is ''`, () => {
it(`should default to undefined`, () => { it(`should default to undefined`, () => {
process.env["BONOB_ICON_FOREGROUND_COLOR"] = ""; process.env[k] = "";
expect(config().icons.foregroundColor).toEqual(undefined); expect(config().icons.foregroundColor).toEqual(undefined);
}); });
}); });
describe("when BONOB_ICON_FOREGROUND_COLOR is specified", () => { describe(`when ${k} is specified`, () => {
it(`should use it`, () => { it(`should use it`, () => {
process.env["BONOB_ICON_FOREGROUND_COLOR"] = "pink"; process.env[k] = "pink";
expect(config().icons.foregroundColor).toEqual("pink"); expect(config().icons.foregroundColor).toEqual("pink");
}); });
}); });
describe("when BONOB_ICON_FOREGROUND_COLOR is an invalid string", () => { describe(`when ${k} is an invalid string`, () => {
it(`should blow up`, () => { it(`should blow up`, () => {
process.env["BONOB_ICON_FOREGROUND_COLOR"] = "#dfasd"; process.env[k] = "#dfasd";
expect(() => config()).toThrow( expect(() => config()).toThrow(
"Invalid color specified for BONOB_ICON_FOREGROUND_COLOR" `Invalid value specified for 'BNB_ICON_FOREGROUND_COLOR', must match ${WORD}`
); );
}); });
}); });
}
);
}); });
describe("backgroundColor", () => { describe("backgroundColor", () => {
describe("when BONOB_ICON_BACKGROUND_COLOR is not specified", () => { ["BNB_ICON_BACKGROUND_COLOR", "BONOB_ICON_BACKGROUND_COLOR"].forEach(
(k) => {
describe(`when ${k} is not specified`, () => {
it(`should default to undefined`, () => { it(`should default to undefined`, () => {
expect(config().icons.backgroundColor).toEqual(undefined); expect(config().icons.backgroundColor).toEqual(undefined);
}); });
}); });
describe("when BONOB_ICON_BACKGROUND_COLOR is ''", () => { describe(`when ${k} is ''`, () => {
it(`should default to undefined`, () => { it(`should default to undefined`, () => {
process.env["BONOB_ICON_BACKGROUND_COLOR"] = ""; process.env[k] = "";
expect(config().icons.backgroundColor).toEqual(undefined); expect(config().icons.backgroundColor).toEqual(undefined);
}); });
}); });
describe("when BONOB_ICON_BACKGROUND_COLOR is specified", () => { describe(`when ${k} is specified`, () => {
it(`should use it`, () => { it(`should use it`, () => {
process.env["BONOB_ICON_BACKGROUND_COLOR"] = "blue"; process.env[k] = "blue";
expect(config().icons.backgroundColor).toEqual("blue"); expect(config().icons.backgroundColor).toEqual("blue");
}); });
}); });
describe("when BONOB_ICON_BACKGROUND_COLOR is an invalid string", () => { describe(`when ${k} is an invalid string`, () => {
it(`should blow up`, () => { it(`should blow up`, () => {
process.env["BONOB_ICON_BACKGROUND_COLOR"] = "#red"; process.env[k] = "#red";
expect(() => config()).toThrow( expect(() => config()).toThrow(
"Invalid color specified for BONOB_ICON_BACKGROUND_COLOR" `Invalid value specified for 'BNB_ICON_BACKGROUND_COLOR', must match ${WORD}`
); );
}); });
}); });
}
);
}); });
}); });
@@ -176,11 +240,13 @@ describe("config", () => {
expect(config().secret).toEqual("bonob"); expect(config().secret).toEqual("bonob");
}); });
it("should be overridable", () => { ["BNB_SECRET", "BONOB_SECRET"].forEach((key) => {
process.env["BONOB_SECRET"] = "new secret"; it(`should be overridable using ${key}`, () => {
process.env[key] = "new secret";
expect(config().secret).toEqual("new secret"); expect(config().secret).toEqual("new secret");
}); });
}); });
});
describe("sonos", () => { describe("sonos", () => {
describe("serviceName", () => { describe("serviceName", () => {
@@ -188,83 +254,137 @@ describe("config", () => {
expect(config().sonos.serviceName).toEqual("bonob"); expect(config().sonos.serviceName).toEqual("bonob");
}); });
["BNB_SONOS_SERVICE_NAME", "BONOB_SONOS_SERVICE_NAME"].forEach((k) => {
it("should be overridable", () => { it("should be overridable", () => {
process.env["BONOB_SONOS_SERVICE_NAME"] = "foobar1000"; process.env[k] = "foobar1000";
expect(config().sonos.serviceName).toEqual("foobar1000"); expect(config().sonos.serviceName).toEqual("foobar1000");
}); });
}); });
});
["BNB_SONOS_DEVICE_DISCOVERY", "BONOB_SONOS_DEVICE_DISCOVERY"].forEach(
(k) => {
describeBooleanConfigValue( describeBooleanConfigValue(
"deviceDiscovery", "deviceDiscovery",
"BONOB_SONOS_DEVICE_DISCOVERY", k,
true, true,
(config) => config.sonos.deviceDiscovery (config) => config.sonos.discovery.enabled
);
}
); );
describe("seedHost", () => { describe("seedHost", () => {
it("should default to undefined", () => { it("should default to undefined", () => {
expect(config().sonos.seedHost).toBeUndefined(); expect(config().sonos.discovery.seedHost).toBeUndefined();
}); });
["BNB_SONOS_SEED_HOST", "BONOB_SONOS_SEED_HOST"].forEach((k) => {
it("should be overridable", () => { it("should be overridable", () => {
process.env["BONOB_SONOS_SEED_HOST"] = "123.456.789.0"; process.env[k] = "123.456.789.0";
expect(config().sonos.seedHost).toEqual("123.456.789.0"); expect(config().sonos.discovery.seedHost).toEqual("123.456.789.0");
});
}); });
}); });
["BNB_SONOS_AUTO_REGISTER", "BONOB_SONOS_AUTO_REGISTER"].forEach((k) => {
describeBooleanConfigValue( describeBooleanConfigValue(
"autoRegister", "autoRegister",
"BONOB_SONOS_AUTO_REGISTER", k,
false, false,
(config) => config.sonos.autoRegister (config) => config.sonos.autoRegister
); );
});
describe("sid", () => { describe("sid", () => {
it("should default to 246", () => { it("should default to 246", () => {
expect(config().sonos.sid).toEqual(246); expect(config().sonos.sid).toEqual(246);
}); });
["BNB_SONOS_SERVICE_ID", "BONOB_SONOS_SERVICE_ID"].forEach((k) => {
it("should be overridable", () => { it("should be overridable", () => {
process.env["BONOB_SONOS_SERVICE_ID"] = "786"; process.env[k] = "786";
expect(config().sonos.sid).toEqual(786); expect(config().sonos.sid).toEqual(786);
}); });
}); });
}); });
});
describe("navidrome", () => { describe("subsonic", () => {
describe("url", () => { describe("url", () => {
it("should default to http://${hostname()}:4533", () => { ["BNB_SUBSONIC_URL", "BONOB_SUBSONIC_URL", "BONOB_NAVIDROME_URL"].forEach(
expect(config().navidrome.url).toEqual(`http://${hostname()}:4533`); (k) => {
describe(`when ${k} is not specified`, () => {
it(`should default to http://${hostname()}:4533`, () => {
expect(config().subsonic.url).toEqual(
`http://${hostname()}:4533`
);
});
}); });
it("should be overridable", () => { describe(`when ${k} is ''`, () => {
process.env["BONOB_NAVIDROME_URL"] = "http://farfaraway.com"; it(`should default to http://${hostname()}:4533`, () => {
expect(config().navidrome.url).toEqual("http://farfaraway.com"); 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", () => { describe("customClientsFor", () => {
it("should default to undefined", () => { 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"; "BNB_SUBSONIC_CUSTOM_CLIENTS",
expect(config().navidrome.customClientsFor).toEqual("whoop/whoop"); "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");
}); });
}); });
}); });
describe("artistImageCache", () => {
it("should default to undefined", () => {
expect(config().subsonic.artistImageCache).toBeUndefined();
});
it(`should be overridable for BNB_SUBSONIC_ARTIST_IMAGE_CACHE`, () => {
process.env["BNB_SUBSONIC_ARTIST_IMAGE_CACHE"] = "/some/path";
expect(config().subsonic.artistImageCache).toEqual("/some/path");
});
});
});
["BNB_SCROBBLE_TRACKS", "BONOB_SCROBBLE_TRACKS"].forEach((k) => {
describeBooleanConfigValue( describeBooleanConfigValue(
"scrobbleTracks", "scrobbleTracks",
"BONOB_SCROBBLE_TRACKS", k,
true, true,
(config) => config.scrobbleTracks (config) => config.scrobbleTracks
); );
});
["BNB_REPORT_NOW_PLAYING", "BONOB_REPORT_NOW_PLAYING"].forEach((k) => {
describeBooleanConfigValue( describeBooleanConfigValue(
"reportNowPlaying", "reportNowPlaying",
"BONOB_REPORT_NOW_PLAYING", k,
true, true,
(config) => config.reportNowPlaying (config) => config.reportNowPlaying
); );
}); });
});

View File

@@ -175,8 +175,8 @@ describe("InMemoryMusicService", () => {
describe("fetching tracks for an album", () => { describe("fetching tracks for an album", () => {
it("should return only tracks on that album", async () => { it("should return only tracks on that album", async () => {
expect(await musicLibrary.tracks(artist1Album1.id)).toEqual([ expect(await musicLibrary.tracks(artist1Album1.id)).toEqual([
track1, { ...track1, rating: { love: false, stars: 0 } },
track2, { ...track2, rating: { love: false, stars: 0 } },
]); ]);
}); });
}); });
@@ -192,7 +192,7 @@ describe("InMemoryMusicService", () => {
describe("fetching a single track", () => { describe("fetching a single track", () => {
describe("when it exists", () => { describe("when it exists", () => {
it("should return the track", async () => { it("should return the track", async () => {
expect(await musicLibrary.track(track3.id)).toEqual(track3); expect(await musicLibrary.track(track3.id)).toEqual({ ...track3, rating: { love: false, stars: 0 } },);
}); });
}); });
}); });
@@ -221,7 +221,10 @@ describe("InMemoryMusicService", () => {
], ],
}); });
const artist2 = anArtist({ name: "artist2", albums: [artist2_album1] }); const artist2 = anArtist({ name: "artist2", albums: [artist2_album1] });
const artist3 = anArtist({ name: "artist3", albums: [artist3_album1, artist3_album2] }); const artist3 = anArtist({
name: "artist3",
albums: [artist3_album1, artist3_album2],
});
const artistWithNoAlbums = anArtist({ albums: [] }); const artistWithNoAlbums = anArtist({ albums: [] });
const allAlbums = [artist1, artist2, artist3, artistWithNoAlbums].flatMap( const allAlbums = [artist1, artist2, artist3, artistWithNoAlbums].flatMap(
@@ -258,7 +261,7 @@ describe("InMemoryMusicService", () => {
}); });
expect(albums.total).toEqual(totalAlbumCount); expect(albums.total).toEqual(totalAlbumCount);
expect(albums.results.length).toEqual(3) expect(albums.results.length).toEqual(3);
// cannot really assert the results and they will change every time // cannot really assert the results and they will change every time
}); });
}); });
@@ -302,13 +305,11 @@ describe("InMemoryMusicService", () => {
type: "alphabeticalByName", type: "alphabeticalByName",
}) })
).toEqual({ ).toEqual({
results: results: _.sortBy(allAlbums, "name").map(albumToAlbumSummary),
_.sortBy(allAlbums, 'name').map(albumToAlbumSummary),
total: totalAlbumCount, total: totalAlbumCount,
}); });
}); });
}); });
}); });
describe("fetching a page", () => { describe("fetching a page", () => {
@@ -467,9 +468,9 @@ describe("InMemoryMusicService", () => {
it("should provide an array of artists", async () => { it("should provide an array of artists", async () => {
expect(await musicLibrary.genres()).toEqual([ expect(await musicLibrary.genres()).toEqual([
HIP_HOP, HIP_HOP,
SKA,
POP, POP,
ROCK, ROCK,
SKA,
]); ]);
}); });
}); });

View File

@@ -5,6 +5,8 @@ import { pipe } from "fp-ts/lib/function";
import { ordString, fromCompare } from "fp-ts/lib/Ord"; import { ordString, fromCompare } from "fp-ts/lib/Ord";
import { shuffle } from "underscore"; import { shuffle } from "underscore";
import { b64Encode, b64Decode } from "../src/b64";
import { import {
MusicService, MusicService,
Credentials, Credentials,
@@ -20,6 +22,7 @@ import {
albumToAlbumSummary, albumToAlbumSummary,
Track, Track,
Genre, Genre,
Rating,
} from "../src/music_service"; } from "../src/music_service";
export class InMemoryMusicService implements MusicService { export class InMemoryMusicService implements MusicService {
@@ -37,9 +40,7 @@ export class InMemoryMusicService implements MusicService {
this.users[username] == password this.users[username] == password
) { ) {
return Promise.resolve({ return Promise.resolve({
authToken: Buffer.from(JSON.stringify({ username, password })).toString( authToken: b64Encode(JSON.stringify({ username, password })),
"base64"
),
userId: username, userId: username,
nickname: username, nickname: username,
}); });
@@ -49,9 +50,7 @@ export class InMemoryMusicService implements MusicService {
} }
login(token: string): Promise<MusicLibrary> { login(token: string): Promise<MusicLibrary> {
const credentials = JSON.parse( const credentials = JSON.parse(b64Decode(token)) as Credentials;
Buffer.from(token, "base64").toString("ascii")
) as Credentials;
if (this.users[credentials.username] != credentials.password) if (this.users[credentials.username] != credentials.password)
return Promise.reject("Invalid auth token"); return Promise.reject("Invalid auth token");
@@ -78,7 +77,9 @@ export class InMemoryMusicService implements MusicService {
case "alphabeticalByArtist": case "alphabeticalByArtist":
return artist2Album; return artist2Album;
case "alphabeticalByName": case "alphabeticalByName":
return artist2Album.sort((a, b) => a.album.name.localeCompare(b.album.name)); return artist2Album.sort((a, b) =>
a.album.name.localeCompare(b.album.name)
);
case "byGenre": case "byGenre":
return artist2Album.filter( return artist2Album.filter(
(it) => it.album.genre?.id === q.genre (it) => it.album.genre?.id === q.genre
@@ -109,25 +110,28 @@ export class InMemoryMusicService implements MusicService {
A.map((it) => O.fromNullable(it.genre)), A.map((it) => O.fromNullable(it.genre)),
A.compact, A.compact,
A.uniq(fromEquals((x, y) => x.id === y.id)), A.uniq(fromEquals((x, y) => x.id === y.id)),
A.sort( A.sort(fromCompare<Genre>((x, y) => ordString.compare(x.id, y.id)))
fromCompare<Genre>((x, y) => ordString.compare(x.id, y.id))
)
) )
), ),
tracks: (albumId: string) => tracks: (albumId: string) =>
Promise.resolve(this.tracks.filter((it) => it.album.id === albumId)), Promise.resolve(
this.tracks
.filter((it) => it.album.id === albumId)
.map((it) => ({ ...it, rating: { love: false, stars: 0 } }))
),
rate: (_: string, _2: Rating) => Promise.resolve(false),
track: (trackId: string) => track: (trackId: string) =>
pipe( pipe(
this.tracks.find((it) => it.id === trackId), this.tracks.find((it) => it.id === trackId),
O.fromNullable, O.fromNullable,
O.map((it) => Promise.resolve(it)), O.map((it) => Promise.resolve({ ...it, rating: { love: false, stars: 0 } })),
O.getOrElse(() => O.getOrElse(() =>
Promise.reject(`Failed to find track with id ${trackId}`) Promise.reject(`Failed to find track with id ${trackId}`)
) )
), ),
stream: (_: { trackId: string; range: string | undefined }) => stream: (_: { trackId: string; range: string | undefined }) =>
Promise.reject("unsupported operation"), 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}`), Promise.reject(`Cannot retrieve coverArt for ${id}, size ${size}`),
scrobble: async (_: string) => { scrobble: async (_: string) => {
return Promise.resolve(true); return Promise.resolve(true);
@@ -141,10 +145,14 @@ export class InMemoryMusicService implements MusicService {
playlists: async () => Promise.resolve([]), playlists: async () => Promise.resolve([]),
playlist: async (id: string) => playlist: async (id: string) =>
Promise.reject(`No playlist with id ${id}`), Promise.reject(`No playlist with id ${id}`),
createPlaylist: async (_: string) => Promise.reject("Unsupported operation"), createPlaylist: async (_: string) =>
deletePlaylist: async (_: string) => Promise.reject("Unsupported operation"), Promise.reject("Unsupported operation"),
addToPlaylist: async (_: string) => Promise.reject("Unsupported operation"), deletePlaylist: async (_: string) =>
removeFromPlaylist: async (_: string, _2: number[]) => Promise.reject("Unsupported operation"), Promise.reject("Unsupported operation"),
addToPlaylist: async (_: string) =>
Promise.reject("Unsupported operation"),
removeFromPlaylist: async (_: string, _2: number[]) =>
Promise.reject("Unsupported operation"),
similarSongs: async (_: string) => Promise.resolve([]), similarSongs: async (_: string) => Promise.resolve([]),
topSongs: async (_: string) => Promise.resolve([]), topSongs: async (_: string) => Promise.resolve([]),
}); });

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, bonobUrl,
new InMemoryMusicService(), new InMemoryMusicService(),
{ {
version: "v123.456" version: "v123.456",
} }
); );
@@ -233,8 +233,7 @@ describe("server", () => {
const fakeSonos: Sonos = { const fakeSonos: Sonos = {
devices: () => Promise.resolve([]), devices: () => Promise.resolve([]),
services: () => services: () => Promise.resolve([]),
Promise.resolve([]),
remove: () => Promise.resolve(false), remove: () => Promise.resolve(false),
register: () => Promise.resolve(false), register: () => Promise.resolve(false),
}; };
@@ -397,7 +396,8 @@ describe("server", () => {
const fakeSonos: Sonos = { const fakeSonos: Sonos = {
devices: () => Promise.resolve([device1, device2]), devices: () => Promise.resolve([device1, device2]),
services: () => Promise.resolve([service1, service2, bonobService]), services: () =>
Promise.resolve([service1, service2, bonobService]),
remove: () => Promise.resolve(false), remove: () => Promise.resolve(false),
register: () => Promise.resolve(false), register: () => Promise.resolve(false),
}; };
@@ -707,7 +707,6 @@ describe("server", () => {
const musicLibrary = { const musicLibrary = {
stream: jest.fn(), stream: jest.fn(),
scrobble: jest.fn(), scrobble: jest.fn(),
nowPlaying: jest.fn(),
}; };
let now = dayjs(); let now = dayjs();
const accessTokens = new ExpiringAccessTokens({ now: () => now }); const accessTokens = new ExpiringAccessTokens({ now: () => now });
@@ -756,13 +755,14 @@ describe("server", () => {
it("should return a 401", async () => { it("should return a 401", async () => {
now = now.add(1, "day"); now = now.add(1, "day");
const res = await request(server) const res = await request(server).head(
.head(
bonobUrl bonobUrl
.append({ pathname: `/stream/track/${trackId}` }) .append({
pathname: `/stream/track/${trackId}`,
searchParams: { bat: accessToken },
})
.path() .path()
) );
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
expect(res.status).toEqual(401); expect(res.status).toEqual(401);
}); });
@@ -774,7 +774,8 @@ describe("server", () => {
const trackStream = { const trackStream = {
status: 200, status: 200,
headers: { 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", "content-length": "123",
}, },
stream: streamContent(""), stream: streamContent(""),
@@ -786,14 +787,13 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.head( .head(
bonobUrl bonobUrl
.append({ pathname: `/stream/track/${trackId}` }) .append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path() .path()
) );
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
expect(res.status).toEqual(trackStream.status); expect(res.status).toEqual(trackStream.status);
expect(res.headers["content-type"]).toEqual( 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.headers["content-length"]).toEqual("123");
expect(res.body).toEqual({}); expect(res.body).toEqual({});
@@ -812,8 +812,10 @@ describe("server", () => {
musicLibrary.stream.mockResolvedValue(trackStream); musicLibrary.stream.mockResolvedValue(trackStream);
const res = await request(server) const res = await request(server)
.head(`/stream/track/${trackId}`) .head(bonobUrl
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken); .append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path()
);
expect(res.status).toEqual(404); expect(res.status).toEqual(404);
expect(res.body).toEqual({}); expect(res.body).toEqual({});
@@ -840,10 +842,9 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.get( .get(
bonobUrl bonobUrl
.append({ pathname: `/stream/track/${trackId}` }) .append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path() .path()
) );
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
expect(res.status).toEqual(401); expect(res.status).toEqual(401);
}); });
@@ -863,14 +864,12 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.get( .get(
bonobUrl bonobUrl
.append({ pathname: `/stream/track/${trackId}` }) .append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path() .path()
) );
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
expect(res.status).toEqual(404); expect(res.status).toEqual(404);
expect(musicLibrary.nowPlaying).not.toHaveBeenCalled();
expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId }); expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId });
}); });
}); });
@@ -883,26 +882,25 @@ describe("server", () => {
const stream = { const stream = {
status: 200, status: 200,
headers: { 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), stream: streamContent(content),
}; };
musicService.login.mockResolvedValue(musicLibrary); musicService.login.mockResolvedValue(musicLibrary);
musicLibrary.stream.mockResolvedValue(stream); musicLibrary.stream.mockResolvedValue(stream);
musicLibrary.nowPlaying.mockResolvedValue(true);
const res = await request(server) const res = await request(server)
.get( .get(
bonobUrl bonobUrl
.append({ pathname: `/stream/track/${trackId}` }) .append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path() .path()
) );
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
expect(res.status).toEqual(stream.status); expect(res.status).toEqual(stream.status);
expect(res.headers["content-type"]).toEqual( expect(res.headers["content-type"]).toEqual(
"audio/mp3; charset=utf-8" "audio/flac; charset=utf-8"
); );
expect(res.header["accept-ranges"]).toBeUndefined(); expect(res.header["accept-ranges"]).toBeUndefined();
expect(res.headers["content-length"]).toEqual( expect(res.headers["content-length"]).toEqual(
@@ -911,7 +909,6 @@ describe("server", () => {
expect(Object.keys(res.headers)).not.toContain("content-range"); expect(Object.keys(res.headers)).not.toContain("content-range");
expect(musicService.login).toHaveBeenCalledWith(authToken); expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.nowPlaying).toHaveBeenCalledWith(trackId);
expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId }); expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId });
}); });
}); });
@@ -931,15 +928,13 @@ describe("server", () => {
musicService.login.mockResolvedValue(musicLibrary); musicService.login.mockResolvedValue(musicLibrary);
musicLibrary.stream.mockResolvedValue(stream); musicLibrary.stream.mockResolvedValue(stream);
musicLibrary.nowPlaying.mockResolvedValue(true);
const res = await request(server) const res = await request(server)
.get( .get(
bonobUrl bonobUrl
.append({ pathname: `/stream/track/${trackId}` }) .append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path() .path()
) );
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
expect(res.status).toEqual(stream.status); expect(res.status).toEqual(stream.status);
expect(res.headers["content-type"]).toEqual( expect(res.headers["content-type"]).toEqual(
@@ -951,7 +946,6 @@ describe("server", () => {
expect(Object.keys(res.headers)).not.toContain("content-range"); expect(Object.keys(res.headers)).not.toContain("content-range");
expect(musicService.login).toHaveBeenCalledWith(authToken); expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.nowPlaying).toHaveBeenCalledWith(trackId);
expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId }); expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId });
}); });
}); });
@@ -970,15 +964,13 @@ describe("server", () => {
musicService.login.mockResolvedValue(musicLibrary); musicService.login.mockResolvedValue(musicLibrary);
musicLibrary.stream.mockResolvedValue(stream); musicLibrary.stream.mockResolvedValue(stream);
musicLibrary.nowPlaying.mockResolvedValue(true);
const res = await request(server) const res = await request(server)
.get( .get(
bonobUrl bonobUrl
.append({ pathname: `/stream/track/${trackId}` }) .append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path() .path()
) );
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
expect(res.status).toEqual(stream.status); expect(res.status).toEqual(stream.status);
expect(res.header["content-type"]).toEqual( expect(res.header["content-type"]).toEqual(
@@ -990,7 +982,6 @@ describe("server", () => {
expect(res.header["content-range"]).toBeUndefined(); expect(res.header["content-range"]).toBeUndefined();
expect(musicService.login).toHaveBeenCalledWith(authToken); expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.nowPlaying).toHaveBeenCalledWith(trackId);
expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId }); expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId });
}); });
}); });
@@ -1010,15 +1001,13 @@ describe("server", () => {
musicService.login.mockResolvedValue(musicLibrary); musicService.login.mockResolvedValue(musicLibrary);
musicLibrary.stream.mockResolvedValue(stream); musicLibrary.stream.mockResolvedValue(stream);
musicLibrary.nowPlaying.mockResolvedValue(true);
const res = await request(server) const res = await request(server)
.get( .get(
bonobUrl bonobUrl
.append({ pathname: `/stream/track/${trackId}` }) .append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path() .path()
) );
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
expect(res.status).toEqual(stream.status); expect(res.status).toEqual(stream.status);
expect(res.header["content-type"]).toEqual( expect(res.header["content-type"]).toEqual(
@@ -1032,7 +1021,6 @@ describe("server", () => {
); );
expect(musicService.login).toHaveBeenCalledWith(authToken); expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.nowPlaying).toHaveBeenCalledWith(trackId);
expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId }); expect(musicLibrary.stream).toHaveBeenCalledWith({ trackId });
}); });
}); });
@@ -1053,17 +1041,15 @@ describe("server", () => {
musicService.login.mockResolvedValue(musicLibrary); musicService.login.mockResolvedValue(musicLibrary);
musicLibrary.stream.mockResolvedValue(stream); musicLibrary.stream.mockResolvedValue(stream);
musicLibrary.nowPlaying.mockResolvedValue(true);
const requestedRange = "40-"; const requestedRange = "40-";
const res = await request(server) const res = await request(server)
.get( .get(
bonobUrl bonobUrl
.append({ pathname: `/stream/track/${trackId}` }) .append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path() .path()
) )
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken)
.set("Range", requestedRange); .set("Range", requestedRange);
expect(res.status).toEqual(stream.status); expect(res.status).toEqual(stream.status);
@@ -1076,7 +1062,6 @@ describe("server", () => {
expect(res.header["content-range"]).toBeUndefined(); expect(res.header["content-range"]).toBeUndefined();
expect(musicService.login).toHaveBeenCalledWith(authToken); expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.nowPlaying).toHaveBeenCalledWith(trackId);
expect(musicLibrary.stream).toHaveBeenCalledWith({ expect(musicLibrary.stream).toHaveBeenCalledWith({
trackId, trackId,
range: requestedRange, range: requestedRange,
@@ -1099,15 +1084,13 @@ describe("server", () => {
musicService.login.mockResolvedValue(musicLibrary); musicService.login.mockResolvedValue(musicLibrary);
musicLibrary.stream.mockResolvedValue(stream); musicLibrary.stream.mockResolvedValue(stream);
musicLibrary.nowPlaying.mockResolvedValue(true);
const res = await request(server) const res = await request(server)
.get( .get(
bonobUrl bonobUrl
.append({ pathname: `/stream/track/${trackId}` }) .append({ pathname: `/stream/track/${trackId}`, searchParams: { bat: accessToken } })
.path() .path()
) )
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken)
.set("Range", "4000-5000"); .set("Range", "4000-5000");
expect(res.status).toEqual(stream.status); expect(res.status).toEqual(stream.status);
@@ -1122,7 +1105,6 @@ describe("server", () => {
); );
expect(musicService.login).toHaveBeenCalledWith(authToken); expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.nowPlaying).toHaveBeenCalledWith(trackId);
expect(musicLibrary.stream).toHaveBeenCalledWith({ expect(musicLibrary.stream).toHaveBeenCalledWith({
trackId, trackId,
range: "4000-5000", range: "4000-5000",
@@ -1173,7 +1155,7 @@ describe("server", () => {
describe("when there is no access-token", () => { describe("when there is no access-token", () => {
it("should return a 401", async () => { 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); expect(res.status).toEqual(401);
}); });
@@ -1184,7 +1166,7 @@ describe("server", () => {
now = now.add(1, "day"); now = now.add(1, "day");
const res = await request(server).get( 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); expect(res.status).toEqual(401);
@@ -1192,18 +1174,6 @@ describe("server", () => {
}); });
describe("when there is a valid access token", () => { 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", () => { describe("artist art", () => {
["0", "-1", "foo"].forEach((size) => { ["0", "-1", "foo"].forEach((size) => {
describe(`invalid size of ${size}`, () => { describe(`invalid size of ${size}`, () => {
@@ -1211,7 +1181,7 @@ describe("server", () => {
musicService.login.mockResolvedValue(musicLibrary); musicService.login.mockResolvedValue(musicLibrary);
const res = await request(server) const res = await request(server)
.get( .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); .set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1231,7 +1201,7 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.get( .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); .set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1242,8 +1212,7 @@ describe("server", () => {
expect(musicService.login).toHaveBeenCalledWith(authToken); expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.coverArt).toHaveBeenCalledWith( expect(musicLibrary.coverArt).toHaveBeenCalledWith(
albumId, `artist:${albumId}`,
"artist",
180 180
); );
}); });
@@ -1257,7 +1226,7 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.get( .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); .set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1267,11 +1236,24 @@ describe("server", () => {
}); });
describe("fetching multiple images as a collage", () => { 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", () => { describe("fetching a collage of 4 when all are available", () => {
it("should return the image and a 200", async () => { 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); musicService.login.mockResolvedValue(musicLibrary);
@@ -1285,7 +1267,7 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.get( .get(
`/art/artist/${ids.join( `/art/${ids.join(
"&" "&"
)}/size/200?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}` )}/size/200?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
) )
@@ -1296,11 +1278,7 @@ describe("server", () => {
expect(musicService.login).toHaveBeenCalledWith(authToken); expect(musicService.login).toHaveBeenCalledWith(authToken);
ids.forEach((id) => { ids.forEach((id) => {
expect(musicLibrary.coverArt).toHaveBeenCalledWith( expect(musicLibrary.coverArt).toHaveBeenCalledWith(id, 200);
id,
"artist",
200
);
}); });
const image = await Image.load(res.body); const image = await Image.load(res.body);
@@ -1311,7 +1289,7 @@ describe("server", () => {
describe("fetching a collage of 4, however only 1 is available", () => { describe("fetching a collage of 4, however only 1 is available", () => {
it("should return the single image", async () => { 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); musicService.login.mockResolvedValue(musicLibrary);
@@ -1321,26 +1299,28 @@ describe("server", () => {
musicLibrary.coverArt.mockResolvedValueOnce( musicLibrary.coverArt.mockResolvedValueOnce(
coverArtResponse({ coverArtResponse({
data: png, data: png,
contentType: "image/some-mime-type" contentType: "image/some-mime-type",
}) })
); );
const res = await request(server) const res = await request(server)
.get( .get(
`/art/artist/${ids.join( `/art/${ids.join(
"&" "&"
)}/size/200?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}` )}/size/200?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
) )
.set(BONOB_ACCESS_TOKEN_HEADER, accessToken); .set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
expect(res.status).toEqual(200); 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", () => { describe("fetching a collage of 4 and all are missing", () => {
it("should return a 404", async () => { 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); musicService.login.mockResolvedValue(musicLibrary);
@@ -1350,7 +1330,7 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.get( .get(
`/art/artist/${ids.join( `/art/${ids.join(
"&" "&"
)}/size/200?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}` )}/size/200?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
) )
@@ -1362,7 +1342,17 @@ describe("server", () => {
describe("fetching a collage of 9 when all are available", () => { describe("fetching a collage of 9 when all are available", () => {
it("should return the image and a 200", async () => { 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); musicService.login.mockResolvedValue(musicLibrary);
@@ -1376,7 +1366,7 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.get( .get(
`/art/artist/${ids.join( `/art/${ids.join(
"&" "&"
)}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}` )}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
) )
@@ -1387,11 +1377,7 @@ describe("server", () => {
expect(musicService.login).toHaveBeenCalledWith(authToken); expect(musicService.login).toHaveBeenCalledWith(authToken);
ids.forEach((id) => { ids.forEach((id) => {
expect(musicLibrary.coverArt).toHaveBeenCalledWith( expect(musicLibrary.coverArt).toHaveBeenCalledWith(id, 180);
id,
"artist",
180
);
}); });
const image = await Image.load(res.body); const image = await Image.load(res.body);
@@ -1402,7 +1388,17 @@ describe("server", () => {
describe("fetching a collage of 9 when only 2 are available", () => { describe("fetching a collage of 9 when only 2 are available", () => {
it("should still return an image and a 200", async () => { 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); musicService.login.mockResolvedValue(musicLibrary);
@@ -1426,7 +1422,7 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.get( .get(
`/art/artist/${ids.join( `/art/${ids.join(
"&" "&"
)}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}` )}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
) )
@@ -1437,11 +1433,7 @@ describe("server", () => {
expect(musicService.login).toHaveBeenCalledWith(authToken); expect(musicService.login).toHaveBeenCalledWith(authToken);
ids.forEach((id) => { ids.forEach((id) => {
expect(musicLibrary.coverArt).toHaveBeenCalledWith( expect(musicLibrary.coverArt).toHaveBeenCalledWith(id, 180);
id,
"artist",
180
);
}); });
const image = await Image.load(res.body); const image = await Image.load(res.body);
@@ -1452,7 +1444,19 @@ describe("server", () => {
describe("fetching a collage of 11", () => { describe("fetching a collage of 11", () => {
it("should still return an image and a 200, though will only display 9", async () => { 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); musicService.login.mockResolvedValue(musicLibrary);
@@ -1466,7 +1470,7 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.get( .get(
`/art/artist/${ids.join( `/art/${ids.join(
"&" "&"
)}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}` )}/size/180?${BONOB_ACCESS_TOKEN_HEADER}=${accessToken}`
) )
@@ -1477,11 +1481,7 @@ describe("server", () => {
expect(musicService.login).toHaveBeenCalledWith(authToken); expect(musicService.login).toHaveBeenCalledWith(authToken);
ids.forEach((id) => { ids.forEach((id) => {
expect(musicLibrary.coverArt).toHaveBeenCalledWith( expect(musicLibrary.coverArt).toHaveBeenCalledWith(id, 180);
id,
"artist",
180
);
}); });
const image = await Image.load(res.body); const image = await Image.load(res.body);
@@ -1498,7 +1498,7 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.get( .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); .set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1515,7 +1515,7 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.get( .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); .set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1531,7 +1531,7 @@ describe("server", () => {
musicService.login.mockResolvedValue(musicLibrary); musicService.login.mockResolvedValue(musicLibrary);
const res = await request(server) const res = await request(server)
.get( .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); .set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1553,7 +1553,7 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.get( .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); .set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1564,8 +1564,7 @@ describe("server", () => {
expect(musicService.login).toHaveBeenCalledWith(authToken); expect(musicService.login).toHaveBeenCalledWith(authToken);
expect(musicLibrary.coverArt).toHaveBeenCalledWith( expect(musicLibrary.coverArt).toHaveBeenCalledWith(
albumId, `coverArt:${albumId}`,
"album",
180 180
); );
}); });
@@ -1578,7 +1577,7 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.get( .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); .set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1593,7 +1592,7 @@ describe("server", () => {
const res = await request(server) const res = await request(server)
.get( .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); .set(BONOB_ACCESS_TOKEN_HEADER, accessToken);
@@ -1669,7 +1668,7 @@ describe("server", () => {
"playlists", "playlists",
"genres", "genres",
"random", "random",
"starred", "heart",
"recentlyAdded", "recentlyAdded",
"recentlyPlayed", "recentlyPlayed",
"mostPlayed", "mostPlayed",
@@ -1723,7 +1722,13 @@ describe("server", () => {
expect(svg).toContain(`fill="brightpink"`); 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 () => { it(`should return a ${theme} icon on ${date}`, async () => {
const response = await request( const response = await request(
server({ now: () => dayjs(date) }) server({ now: () => dayjs(date) })
@@ -1737,14 +1742,50 @@ describe("server", () => {
}); });
} }
itShouldBeFestive("christmas '22", "2022/12/25", "christmas", "red", "green") itShouldBeFestive(
itShouldBeFestive("christmas '23", "2023/12/25", "christmas", "red", "green") "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(
itShouldBeFestive("halloween", "2023/10/31", "halloween", "black", "orange") "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(
itShouldBeFestive("cny '23", "2023/01/22", "yoRabbit", "red", "yellow") "cny '22",
"2022/02/01",
"yoTiger",
"red",
"yellow"
);
itShouldBeFestive(
"cny '23",
"2023/01/22",
"yoRabbit",
"red",
"yellow"
);
}); });
}); });
}); });

File diff suppressed because it is too large Load Diff

View File

@@ -274,12 +274,13 @@ describe("sonos", () => {
describe("when is disabled", () => { describe("when is disabled", () => {
it("should return a disabled client", async () => { it("should return a disabled client", async () => {
const disabled = sonos(false); const disabled = sonos({ enabled: false });
expect(disabled).toEqual(SONOS_DISABLED); expect(disabled).toEqual(SONOS_DISABLED);
expect(await disabled.devices()).toEqual([]); expect(await disabled.devices()).toEqual([]);
expect(await disabled.services()).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); sonosManager.InitializeWithDiscovery.mockResolvedValue(true);
const actualDevices = await sonos(true, undefined).devices(); const actualDevices = await sonos({ enabled: true }).devices();
expect(SonosManager).toHaveBeenCalledTimes(1); expect(SonosManager).toHaveBeenCalledTimes(1);
expect(sonosManager.InitializeWithDiscovery).toHaveBeenCalledWith(10); expect(sonosManager.InitializeWithDiscovery).toHaveBeenCalledWith(10);
@@ -331,7 +332,7 @@ describe("sonos", () => {
); );
sonosManager.InitializeWithDiscovery.mockResolvedValue(true); sonosManager.InitializeWithDiscovery.mockResolvedValue(true);
const actualDevices = await sonos(true, "").devices(); const actualDevices = await sonos({ enabled: true, seedHost: "" }).devices();
expect(SonosManager).toHaveBeenCalledTimes(1); expect(SonosManager).toHaveBeenCalledTimes(1);
expect(sonosManager.InitializeWithDiscovery).toHaveBeenCalledWith(10); expect(sonosManager.InitializeWithDiscovery).toHaveBeenCalledWith(10);
@@ -354,7 +355,7 @@ describe("sonos", () => {
); );
sonosManager.InitializeFromDevice.mockResolvedValue(true); 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).toHaveBeenCalledTimes(1);
expect(sonosManager.InitializeFromDevice).toHaveBeenCalledWith( expect(sonosManager.InitializeFromDevice).toHaveBeenCalledWith(
@@ -377,7 +378,7 @@ describe("sonos", () => {
); );
sonosManager.InitializeWithDiscovery.mockResolvedValue(true); sonosManager.InitializeWithDiscovery.mockResolvedValue(true);
const actualDevices = await sonos(true, undefined).devices(); const actualDevices = await sonos({ enabled: true, seedHost: undefined }).devices();
expect(actualDevices).toEqual([ expect(actualDevices).toEqual([
{ {
@@ -408,7 +409,7 @@ describe("sonos", () => {
); );
sonosManager.InitializeWithDiscovery.mockResolvedValue(false); 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 { Express } from "express";
import { ReadStream } from "fs";
import { IHttpClient } from "soap";
import request from "supertest"; import request from "supertest";
import * as req from "axios";
function supersoap(server: Express) { function supersoap(server: Express): IHttpClient {
return { return {
request: ( request: (
rurl: string, rurl: string,
@@ -15,12 +18,19 @@ function supersoap(server: Express) {
data == null data == null
? request(server).get(withoutHost).send() ? request(server).get(withoutHost).send()
: request(server).post(withoutHost).send(data); : request(server).post(withoutHost).send(data);
req return req
.set(exheaders || {}) .set(exheaders || {})
.then((response) => callback(null, response, response.text)) .then((response) => callback(null, response, response.text))
.catch(callback); .catch(callback);
}, },
}
requestStream: (
_: string,
_2: any
): req.AxiosPromise<ReadStream> => {
throw "Not Implemented!!";
},
};
} }
export default supersoap export default supersoap;

View File

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M16.5,3C13.605,3,12,5.09,12,5.09S10.395,3,7.5,3C4.462,3,2,5.462,2,8.5c0,4.171,4.912,8.213,6.281,9.49C9.858,19.46,12,21.35,12,21.35s2.142-1.89,3.719-3.36C17.088,16.713,22,12.671,22,8.5C22,5.462,19.538,3,16.5,3z M14.811,16.11c-0.177,0.16-0.331,0.299-0.456,0.416c-0.751,0.7-1.639,1.503-2.355,2.145c-0.716-0.642-1.605-1.446-2.355-2.145c-0.126-0.117-0.28-0.257-0.456-0.416C7.769,14.827,4,11.419,4,8.5C4,6.57,5.57,5,7.5,5c1.827,0,2.886,1.275,2.914,1.308L12,8l1.586-1.692C13.596,6.295,14.673,5,16.5,5C18.43,5,20,6.57,20,8.5C20,11.419,16.231,14.827,14.811,16.11z"/>
</svg>

After

Width:  |  Height:  |  Size: 638 B

View File

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M16.5,3C13.605,3,12,5.09,12,5.09S10.395,3,7.5,3C4.462,3,2,5.462,2,8.5c0,4.171,4.912,8.213,6.281,9.49C9.858,19.46,12,21.35,12,21.35s2.142-1.89,3.719-3.36C17.088,16.713,22,12.671,22,8.5C22,5.462,19.538,3,16.5,3z"/>
</svg>

After

Width:  |  Height:  |  Size: 293 B

3
web/icons/Star-16101.svg Normal file
View File

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<path fill="none" stroke="#000" stroke-miterlimit="10" stroke-width="2" d="M16 4.587L19.486 12.407 28 13.306 21.64 19.037 23.416 27.413 16 23.135 8.584 27.413 10.36 19.037 4 13.306 12.514 12.407z"/>
</svg>

After

Width:  |  Height:  |  Size: 270 B

3
web/icons/Star-43879.svg Normal file
View File

@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">
<path fill="none" stroke="#000" stroke-miterlimit="10" d="M8 2.25L9.701 6.283 13.875 6.738 10.753 9.686 11.631 14 8 11.788 4.369 14 5.247 9.686 2.125 6.738 6.299 6.283z"/>
</svg>

After

Width:  |  Height:  |  Size: 241 B

View File

@@ -0,0 +1,4 @@
<svg width="44" height="44" viewBox="0 0 44 44" fill="none"
xmlns="http://www.w3.org/2000/svg">
<path d="M26.4287 14.0097C25.1137 13.9677 23.7987 14.4057 22.7378 15.3397L22.2507 15.7707L21.7618 15.3377C19.6558 13.4727 16.4607 13.5687 14.4717 15.5577L14.4647 15.5657C12.5117 17.5177 12.5117 20.6837 14.4647 22.6367L21.8897 30.0607C22.0847 30.2567 22.4018 30.2567 22.5968 30.0607L29.8757 22.7817C31.8717 20.7867 31.9697 17.4207 29.9277 15.4747C28.9507 14.5427 27.6967 14.0437 26.4287 14.0097Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 518 B

View File

@@ -0,0 +1,4 @@
<svg width="44" height="44" viewBox="0 0 44 44" fill="none"
xmlns="http://www.w3.org/2000/svg">
<path d="M28.5217 21.3077L22.2437 27.5867L15.8788 21.2227C14.5428 19.8857 14.7378 17.5727 16.4758 16.5097C17.7548 15.7267 19.4187 15.9657 20.5557 16.9447L20.7367 17.0997L21.9117 18.1417C22.1007 18.3097 22.3857 18.3097 22.5747 18.1417L23.7498 17.0997L24.0597 16.8307C25.4047 15.6457 27.4587 15.7457 28.6877 17.0637C29.8018 18.2567 29.6757 20.1537 28.5217 21.3077ZM26.4287 14.0097C25.1137 13.9677 23.7987 14.4057 22.7378 15.3397L22.2507 15.7707L21.7618 15.3377C19.6558 13.4727 16.4607 13.5687 14.4717 15.5577L14.4647 15.5657C12.5117 17.5177 12.5117 20.6837 14.4647 22.6367L21.8897 30.0607C22.0847 30.2567 22.4018 30.2567 22.5968 30.0607L29.8757 22.7817C31.8717 20.7867 31.9697 17.4207 29.9277 15.4747C28.9507 14.5427 27.6967 14.0437 26.4287 14.0097Z" fill="white" fill-opacity="0.6"/>
</svg>

After

Width:  |  Height:  |  Size: 890 B

View File

@@ -0,0 +1,10 @@
<html>
<body style="background-color: black;">
<img src="star0.svg" width="80px"><br>
<img src="star1.svg" width="80px"><br>
<img src="star2.svg" width="80px"><br>
<img src="star3.svg" width="80px"><br>
<img src="star4.svg" width="80px"><br>
<img src="star5.svg" width="80px"><br>
</body>
</html>

5
web/public/star0.svg Normal file
View File

@@ -0,0 +1,5 @@
<svg version="1.1" baseProfile="basic" id="_x38_8"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 44 44" xml:space="preserve">
<path id="star" fill="#FFFFFF" d="M28,31l-6-4.3L16,31l2.6-6.8l-5.1-4.3h6l2.5-6.9l2.6,6.9h6l-5.1,4.3L28,31z"/>
</svg>

After

Width:  |  Height:  |  Size: 312 B

6
web/public/star1.svg Normal file
View File

@@ -0,0 +1,6 @@
<svg version="1.1" baseProfile="basic" id="_x38_8"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 44 44" xml:space="preserve">
<path id="star" fill="#FBB040" d="M28,31l-6-4.3L16,31l2.6-6.8l-5.1-4.3h6l2.5-6.9l2.6,6.9h6l-5.1,4.3L28,31z"/>
<circle cx="22" cy="32" r="2" fill="#FBB040"/>
</svg>

After

Width:  |  Height:  |  Size: 361 B

7
web/public/star2.svg Normal file
View File

@@ -0,0 +1,7 @@
<svg version="1.1" baseProfile="basic" id="_x38_8"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 44 44" xml:space="preserve">
<path id="star" fill="#FBB040" d="M28,31l-6-4.3L16,31l2.6-6.8l-5.1-4.3h6l2.5-6.9l2.6,6.9h6l-5.1,4.3L28,31z"/>
<circle cx="22" cy="32" r="2" fill="#FBB040"/>
<circle cx="14" cy="26" r="2" fill="#FBB040"/>
</svg>

After

Width:  |  Height:  |  Size: 410 B

8
web/public/star3.svg Normal file
View File

@@ -0,0 +1,8 @@
<svg version="1.1" baseProfile="basic" id="_x38_8"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 44 44" xml:space="preserve">
<path id="star" fill="#FBB040" d="M28,31l-6-4.3L16,31l2.6-6.8l-5.1-4.3h6l2.5-6.9l2.6,6.9h6l-5.1,4.3L28,31z"/>
<circle cx="22" cy="32" r="2" fill="#FBB040"/>
<circle cx="14" cy="26" r="2" fill="#FBB040"/>
<circle cx="17" cy="16" r="2" fill="#FBB040"/>
</svg>

After

Width:  |  Height:  |  Size: 459 B

9
web/public/star4.svg Normal file
View File

@@ -0,0 +1,9 @@
<svg version="1.1" baseProfile="basic" id="_x38_8"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 44 44" xml:space="preserve">
<path id="star" fill="#FBB040" d="M28,31l-6-4.3L16,31l2.6-6.8l-5.1-4.3h6l2.5-6.9l2.6,6.9h6l-5.1,4.3L28,31z"/>
<circle cx="22" cy="32" r="2" fill="#FBB040"/>
<circle cx="14" cy="26" r="2" fill="#FBB040"/>
<circle cx="17" cy="16" r="2" fill="#FBB040"/>
<circle cx="27" cy="16" r="2" fill="#FBB040"/>
</svg>

After

Width:  |  Height:  |  Size: 508 B

10
web/public/star5.svg Normal file
View File

@@ -0,0 +1,10 @@
<svg version="1.1" baseProfile="basic" id="_x38_8"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 44 44" xml:space="preserve">
<path id="star" fill="#FBB040" d="M28,31l-6-4.3L16,31l2.6-6.8l-5.1-4.3h6l2.5-6.9l2.6,6.9h6l-5.1,4.3L28,31z"/>
<circle cx="22" cy="32" r="2" fill="#FBB040"/>
<circle cx="14" cy="26" r="2" fill="#FBB040"/>
<circle cx="17" cy="16" r="2" fill="#FBB040"/>
<circle cx="27" cy="16" r="2" fill="#FBB040"/>
<circle cx="30" cy="26" r="2" fill="#FBB040"/>
</svg>

After

Width:  |  Height:  |  Size: 557 B

3483
yarn.lock

File diff suppressed because it is too large Load Diff