@volumio/plugin-sdk 0.0.0-stage → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +118 -2
  3. package/bin/volumio-plugin.js +158 -0
  4. package/package.json +37 -4
  5. package/registry/functions.json +93 -0
  6. package/registry/g2-baseline.json +485 -0
  7. package/schema/manifest.schema.json +95 -0
  8. package/src/audit.js +46 -0
  9. package/src/check.js +114 -0
  10. package/src/deploy.js +183 -0
  11. package/src/fromV1.js +54 -0
  12. package/src/g2/baseline.js +31 -0
  13. package/src/g2/gitleaks.toml +4 -0
  14. package/src/g2/index.js +18 -0
  15. package/src/g2/js.js +63 -0
  16. package/src/g2/rule.js +94 -0
  17. package/src/g2/secrets.js +85 -0
  18. package/src/g2/shell.js +145 -0
  19. package/src/index.js +3 -0
  20. package/src/init.js +60 -0
  21. package/src/licence.js +88 -0
  22. package/src/manifest.js +36 -0
  23. package/src/package.js +170 -0
  24. package/src/socketio.js +76 -0
  25. package/templates/generic/AGENTS.md +60 -0
  26. package/templates/generic/CLAUDE.md +2 -0
  27. package/templates/generic/LICENSE +21 -0
  28. package/templates/generic/README.md +13 -0
  29. package/templates/generic/UIConfig.json +23 -0
  30. package/templates/generic/VOLUMIO_API.md +91 -0
  31. package/templates/generic/config.json +3 -0
  32. package/templates/generic/gitignore +2 -0
  33. package/templates/generic/i18n/strings_en.json +8 -0
  34. package/templates/generic/index.js +81 -0
  35. package/templates/generic/install.sh +4 -0
  36. package/templates/generic/package.json +17 -0
  37. package/templates/generic/test/plugin.test.js +24 -0
  38. package/templates/generic/test/volumio.js +29 -0
  39. package/templates/generic/uninstall.sh +4 -0
  40. package/templates/generic/volumio-plugin.json +13 -0
  41. package/templates/music_service/UIConfig.json +23 -0
  42. package/templates/music_service/catalog.json +4 -0
  43. package/templates/music_service/config.json +3 -0
  44. package/templates/music_service/i18n/strings_en.json +8 -0
  45. package/templates/music_service/index.js +135 -0
  46. package/templates/music_service/test/music.test.js +52 -0
  47. package/templates/music_service/test/plugin.test.js +29 -0
  48. package/templates/music_service/volumio-plugin.json +13 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) {{year}} {{author}}
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,13 @@
1
+ # {{title}}
2
+
3
+ {{description}}
4
+
5
+ ## Develop
6
+
7
+ ```bash
8
+ npm install # dependencies, for the tests
9
+ npm test # runs the plugin against a fake Volumio
10
+ npx --package=@volumio/plugin-sdk volumio-plugin check . # the checks the store runs on every submission
11
+ ```
12
+
13
+ `volumio-plugin.json` describes the plugin: edit it, never `package.json`'s name or version. The package for Volumio is built from it.
@@ -0,0 +1,23 @@
1
+ {
2
+ "page": { "label": "TRANSLATE.PLUGIN_NAME" },
3
+ "sections": [
4
+ {
5
+ "id": "settings",
6
+ "element": "section",
7
+ "label": "TRANSLATE.SETTINGS",
8
+ "icon": "fa-cog",
9
+ "onSave": { "type": "controller", "endpoint": "{{type}}/{{id}}", "method": "saveSettings" },
10
+ "saveButton": { "label": "TRANSLATE.SAVE", "data": ["greeting"] },
11
+ "content": [
12
+ {
13
+ "id": "greeting",
14
+ "element": "input",
15
+ "type": "text",
16
+ "label": "TRANSLATE.GREETING",
17
+ "doc": "TRANSLATE.GREETING_DOC",
18
+ "value": ""
19
+ }
20
+ ]
21
+ }
22
+ ]
23
+ }
@@ -0,0 +1,91 @@
1
+ # Volumio plugin API 1
2
+
3
+ How Volumio 4 runs a plugin whose manifest says `"engines": { "api": "1" }`: what it calls, what it expects back, and the mistakes that break a plugin on the device. A plugin written for a later API comes with its own version of this file; `AGENTS.md` stays the same.
4
+
5
+ ## The plugin
6
+
7
+ - `index.js` exports a class. Volumio creates one instance, `new Plugin(context)`, and keeps it while the device runs.
8
+ - `context.coreCommand` is Volumio's command router (`this.commandRouter` in the template), `context.logger` its log.
9
+ - Node 20.5, CommonJS (`require`). Code that needs a build step keeps the built `index.js` at the package root.
10
+ - The plugin lives in `/data/plugins/<type>/<id>/`, its saved settings in `/data/configuration/<type>/<id>/config.json`.
11
+ - `v-conf` comes from Volumio's own copy, `/volumio/node_modules/v-conf`, as in the template; other dependencies go in `package.json`.
12
+
13
+ ## Promises: kew only
14
+
15
+ Every method Volumio calls returns a kew promise (`const libQ = require('kew')`): `libQ.resolve(value)`, `libQ.reject(error)`, or `libQ.defer()` and its `promise`.
16
+
17
+ - Volumio checks the type of what each lifecycle method returns. An `async` method or a native `Promise` fails that check: the log says "does not return adequate promise" and an `onStart` that fails it leaves the plugin FAILED. Write these methods as plain functions.
18
+ - Volumio chains `.then` and `.fail` on what other methods return; a native `Promise` has no `.fail` and throws there.
19
+ - kew promises have `.then`, `.fail` and `.fin`, no `.catch`.
20
+ - `async` functions are fine inside the plugin. Turn their result into a kew promise where Volumio calls in:
21
+
22
+ ```js
23
+ onStart() {
24
+ const defer = libQ.defer();
25
+ this.connect().then((value) => defer.resolve(value), (error) => defer.reject(error));
26
+ return defer.promise;
27
+ }
28
+ ```
29
+
30
+ Call `defer.resolve` and `defer.reject` on `defer`, as above: passed on their own, as `.then(defer.resolve)`, they lose it and the promise never settles.
31
+
32
+ - Wait on a promise or an event, not on a timer. A timer or child process the plugin starts, `onStop` stops.
33
+
34
+ ## Lifecycle
35
+
36
+ | Method | Volumio calls it | Returns |
37
+ | --- | --- | --- |
38
+ | `constructor(context)` | When Volumio loads an enabled plugin: at boot, or when the user enables it | Keeps `context`; does no work |
39
+ | `getConfigurationFiles()` | Before `onVolumioStart` | `['config.json']`, not a promise: Volumio copies it to the configuration folder the first time |
40
+ | `onVolumioStart()` | Right after loading | kew promise; loads the configuration |
41
+ | `onStart()` | After `onVolumioStart` | kew promise; starts the plugin's work |
42
+ | `onStop()` | When the plugin is disabled | kew promise; undoes everything `onStart` did |
43
+ | `onVolumioShutdown()`, `onVolumioReboot()` | Optional, before power off and reboot | kew promise |
44
+ | `getUIConfig()` | When the settings page opens | kew promise of the page |
45
+ | The `method` of a section's `onSave` | When the user presses Save | kew promise; gets `{ <field id>: value }` for the ids in `saveButton.data` |
46
+
47
+ At boot Volumio waits at most 30 seconds for all plugins' `onVolumioStart`, then for all `onStart`, and then goes on without the slow ones. Resolve quickly and do long work afterwards.
48
+
49
+ ## Settings
50
+
51
+ - `config.json` holds each setting with its type and default: `{ "greeting": { "type": "string", "value": "Hello" } }`.
52
+ - Load it with `v-conf` in `onVolumioStart`, from `this.commandRouter.pluginManager.getConfigurationFile(this.context, 'config.json')`. `this.config.get(key)` reads, `this.config.set(key, value)` writes and saves.
53
+ - `UIConfig.json` is the settings page: `sections`, each with `content` fields, an `onSave` of `{ "type": "controller", "endpoint": "<type>/<id>", "method": "<method>" }` and a `saveButton` with the field ids to send.
54
+ - Text is a key, `"TRANSLATE.GREETING"`, looked up in `i18n/strings_<language>.json`, English when a key is missing. `getUIConfig` builds the page with `this.commandRouter.i18nJson(<language file>, <English file>, <UIConfig.json>)` and fills in the saved values.
55
+
56
+ ## Calling Volumio
57
+
58
+ Through `this.commandRouter`. Only these are covered by this contract:
59
+
60
+ | Call | Does |
61
+ | --- | --- |
62
+ | `pushToastMessage(type, title, message)` | Shows a notification: `success`, `info`, `warning` or `error` |
63
+ | `sharedVars.get('language_code')` | The user's language, as `en` |
64
+ | `pluginManager.getConfigurationFile(context, name)` | Where a configuration file lives |
65
+ | `i18nJson(languageFile, englishFile, jsonFile)` | A kew promise of `jsonFile` with its `TRANSLATE.` keys translated |
66
+ | `executeOnPlugin(type, id, method, data)` | Calls a method of another plugin; `undefined` when it is not installed |
67
+ | `broadcastMessage(event, payload)` | Sends a message to every open Volumio UI |
68
+ | `volumioAddToBrowseSources(source)`, `volumioRemoveToBrowseSources(name)`, `volumioUpdateToBrowseSources(name, source)` | A `music_service`'s entry in Browse: add, remove, change in place |
69
+ | `servicePushState(state, id)` | A `music_service` that plays by itself tells Volumio what it plays |
70
+
71
+ Never assign to a `commandRouter` method, and never `require` Volumio's own files.
72
+
73
+ ## music_service
74
+
75
+ ### Browse
76
+
77
+ - `onStart` adds `{ name, uri, plugin_type: 'music_service', plugin_name: '<id>' }` with `volumioAddToBrowseSources`; `onStop` removes it by `name`.
78
+ - Every URI the plugin hands out starts with `music_service/<id>`. Volumio sends a Browse request to the first source whose `uri` starts the requested URI, after its own: favourites, playlists, search, `artists://`, `albums://`, `genres://`, upnp, radio. A root that is only the id can lose its pages to them.
79
+ - `handleBrowseUri(uri)` resolves `{ navigation: { prev: { uri }, lists: [{ title, availableListViews: ['list', 'grid'], items }] } }`. An item: `{ service: '<id>', type, title, artist, album, albumart or icon, uri }`; `type` `folder` opens with another `handleBrowseUri`, `song` plays. An unknown URI rejects.
80
+
81
+ ### Play
82
+
83
+ - `explodeUri(uri)` resolves a list of tracks, even for one track: the queue adds them all, Favourites reads the first.
84
+ - A track `{ service: 'mpd', type: 'track', uri: <stream URL>, name, title, artist, album, albumart }` hands playback to MPD, which then handles pause, stop and seek. Use it whenever the service gives a stream URL.
85
+ - A plugin that plays by itself sets `service: '<id>'` and implements `clearAddPlayTrack(track)`, `stop()`, `pause()`, `resume()` and `seek(milliseconds)`, each returning a kew promise, and reports every change of state with `servicePushState`.
86
+
87
+ ### Search
88
+
89
+ - `search({ value })` resolves `null` when nothing matches, or one list `{ title, availableListViews, items }` with items as in Browse.
90
+ - Never reject and never throw: Volumio searches every source together, and one failure can lose the whole result. On an error, log it and resolve `null`.
91
+ - Searching every source, Volumio stops waiting for a plugin after 5 seconds. Searching only this plugin, from its own Browse page, it waits as long as the plugin takes: put a time limit on every request `search` makes.
@@ -0,0 +1,3 @@
1
+ {
2
+ "greeting": { "type": "string", "value": "Hello from Volumio" }
3
+ }
@@ -0,0 +1,2 @@
1
+ node_modules/
2
+ dist-plugin/
@@ -0,0 +1,8 @@
1
+ {
2
+ "PLUGIN_NAME": "{{title}}",
3
+ "SETTINGS": "Settings",
4
+ "SAVE": "Save",
5
+ "GREETING": "Greeting",
6
+ "GREETING_DOC": "Written to the log when the plugin starts",
7
+ "SAVED": "Settings saved"
8
+ }
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const libQ = require('kew');
6
+
7
+ // Volumio's own copy, as every plugin on the device uses; the tests use the devDependency.
8
+ const volumioModule = (name) => {
9
+ try {
10
+ return require(`/volumio/node_modules/${name}`);
11
+ } catch {
12
+ return require(name);
13
+ }
14
+ };
15
+ const VConf = volumioModule('v-conf');
16
+
17
+ // Volumio creates one instance with `new` and calls the methods below.
18
+ // Every method Volumio calls returns a kew promise (libQ): Volumio rejects
19
+ // async functions and native Promises ("does not return adequate promise").
20
+ module.exports = class {{className}} {
21
+ constructor(context) {
22
+ this.context = context;
23
+ this.commandRouter = context.coreCommand;
24
+ this.logger = context.logger;
25
+ }
26
+
27
+ // Volumio copies these files to /data/configuration/<type>/<id>/ on first start.
28
+ getConfigurationFiles() {
29
+ return ['config.json'];
30
+ }
31
+
32
+ onVolumioStart() {
33
+ this.config = new VConf();
34
+ this.config.loadFile(this.commandRouter.pluginManager.getConfigurationFile(this.context, 'config.json'));
35
+ return libQ.resolve();
36
+ }
37
+
38
+ onStart() {
39
+ this.strings = this.loadStrings();
40
+ this.logger.info(`{{id}}: ${this.config.get('greeting')}`);
41
+ return libQ.resolve();
42
+ }
43
+
44
+ onStop() {
45
+ return libQ.resolve();
46
+ }
47
+
48
+ // The settings page: UIConfig.json, translated, with the saved values filled in.
49
+ getUIConfig() {
50
+ const lang = this.commandRouter.sharedVars.get('language_code');
51
+ return this.commandRouter
52
+ .i18nJson(this.file(`i18n/strings_${lang}.json`), this.file('i18n/strings_en.json'), this.file('UIConfig.json'))
53
+ .then((uiconf) => {
54
+ uiconf.sections[0].content[0].value = this.config.get('greeting');
55
+ return uiconf;
56
+ });
57
+ }
58
+
59
+ // Called by the Save button of the settings page (onSave in UIConfig.json).
60
+ saveSettings(data) {
61
+ this.config.set('greeting', data.greeting);
62
+ this.commandRouter.pushToastMessage('success', this.strings.PLUGIN_NAME, this.strings.SAVED);
63
+ return libQ.resolve();
64
+ }
65
+
66
+ // The plugin's own strings in the user's language, English for any missing key.
67
+ loadStrings() {
68
+ const read = (lang) => {
69
+ try {
70
+ return JSON.parse(fs.readFileSync(this.file(`i18n/strings_${lang}.json`), 'utf8'));
71
+ } catch {
72
+ return {};
73
+ }
74
+ };
75
+ return { ...read('en'), ...read(this.commandRouter.sharedVars.get('language_code')) };
76
+ }
77
+
78
+ file(name) {
79
+ return path.join(__dirname, name);
80
+ }
81
+ };
@@ -0,0 +1,4 @@
1
+ #!/bin/sh
2
+ # Volumio runs this with sh (dash) as root: POSIX sh only, no pipefail.
3
+ set -eu
4
+ echo "plugininstallend"
@@ -0,0 +1,17 @@
1
+ {
2
+ "private": true,
3
+ "main": "index.js",
4
+ "license": "MIT",
5
+ "scripts": {
6
+ "test": "node --test"
7
+ },
8
+ "engines": {
9
+ "node": ">=20"
10
+ },
11
+ "dependencies": {
12
+ "kew": "^0.7.0"
13
+ },
14
+ "devDependencies": {
15
+ "v-conf": "^1.4.3"
16
+ }
17
+ }
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+
3
+ // Runs the plugin as Volumio does, with a fake Volumio around it: `npm test`.
4
+ const { test } = require('node:test');
5
+ const assert = require('node:assert/strict');
6
+ const Plugin = require('..');
7
+ const { fakeVolumio, isKew } = require('./volumio');
8
+
9
+ test('every lifecycle method returns a kew promise', () => {
10
+ const plugin = new Plugin(fakeVolumio().context);
11
+ for (const method of ['onVolumioStart', 'onStart', 'onStop']) assert.ok(isKew(plugin[method]()), method);
12
+ });
13
+
14
+ test('the settings page shows the saved greeting, and Save stores a new one', async () => {
15
+ const volumio = fakeVolumio();
16
+ const plugin = new Plugin(volumio.context);
17
+ plugin.onVolumioStart();
18
+ plugin.onStart();
19
+ assert.equal((await plugin.getUIConfig()).sections[0].content[0].value, 'Hello from Volumio');
20
+
21
+ assert.ok(isKew(plugin.saveSettings({ greeting: 'Ciao' })));
22
+ assert.equal(plugin.config.get('greeting'), 'Ciao');
23
+ assert.equal(volumio.toasts[0].type, 'success');
24
+ });
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+
3
+ // A fake Volumio around the plugin, recording what the plugin asks of it.
4
+ const fs = require('fs');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const libQ = require('kew');
8
+
9
+ exports.fakeVolumio = () => {
10
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'plugin-test-'));
11
+ fs.copyFileSync(path.join(__dirname, '..', 'config.json'), path.join(dir, 'config.json'));
12
+ const toasts = [];
13
+ const logs = [];
14
+ const browseSources = [];
15
+ const coreCommand = {
16
+ pluginManager: { getConfigurationFile: (context, name) => path.join(dir, name) },
17
+ sharedVars: { get: (key) => (key === 'language_code' ? 'en' : undefined) },
18
+ pushToastMessage: (type, title, message) => toasts.push({ type, title, message }),
19
+ i18nJson: (dictionary, fallback, file) => libQ.resolve(JSON.parse(fs.readFileSync(file, 'utf8'))),
20
+ volumioAddToBrowseSources: (source) => browseSources.push(source),
21
+ volumioRemoveToBrowseSources: (name) => browseSources.splice(browseSources.findIndex((s) => s.name === name), 1),
22
+ volumioUpdateToBrowseSources: (name, source) => browseSources.forEach((s, i) => { if (s.name === name) browseSources[i] = source; }),
23
+ };
24
+ const context = { coreCommand, logger: { info: (m) => logs.push(m), warn: () => {}, error: () => {} } };
25
+ return { context, toasts, logs, browseSources };
26
+ };
27
+
28
+ // kew promises are objects with then and fail; native Promises are not.
29
+ exports.isKew = (p) => typeof p?.then === 'function' && typeof p.fail === 'function';
@@ -0,0 +1,4 @@
1
+ #!/bin/sh
2
+ # Volumio runs this with sh (dash) as root: POSIX sh only, no pipefail.
3
+ set -eu
4
+ echo "pluginuninstallend"
@@ -0,0 +1,13 @@
1
+ {
2
+ "id": "{{id}}",
3
+ "version": "0.1.0",
4
+ "type": "{{type}}",
5
+ "function": "{{function}}",
6
+ "title": "{{title}}",
7
+ "description": "{{description}}",
8
+ "icon": "fa-puzzle-piece",
9
+ "engines": { "volumio": ">=4.0.0 <5.0.0", "api": "1" },
10
+ "arch": ["armhf", "amd64"],
11
+ "permissions": ["ui:toast"],
12
+ "license": "MIT"
13
+ }
@@ -0,0 +1,23 @@
1
+ {
2
+ "page": { "label": "TRANSLATE.PLUGIN_NAME" },
3
+ "sections": [
4
+ {
5
+ "id": "settings",
6
+ "element": "section",
7
+ "label": "TRANSLATE.SETTINGS",
8
+ "icon": "fa-cog",
9
+ "onSave": { "type": "controller", "endpoint": "{{type}}/{{id}}", "method": "saveSettings" },
10
+ "saveButton": { "label": "TRANSLATE.SAVE", "data": ["browse_name"] },
11
+ "content": [
12
+ {
13
+ "id": "browse_name",
14
+ "element": "input",
15
+ "type": "text",
16
+ "label": "TRANSLATE.BROWSE_NAME",
17
+ "doc": "TRANSLATE.BROWSE_NAME_DOC",
18
+ "value": ""
19
+ }
20
+ ]
21
+ }
22
+ ]
23
+ }
@@ -0,0 +1,4 @@
1
+ [
2
+ { "id": "1", "title": "First track", "artist": "Your artist", "album": "Your album", "url": "https://example.com/stream/first.mp3" },
3
+ { "id": "2", "title": "Second track", "artist": "Your artist", "album": "Your album", "url": "https://example.com/stream/second.mp3" }
4
+ ]
@@ -0,0 +1,3 @@
1
+ {
2
+ "browse_name": { "type": "string", "value": "{{title}}" }
3
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "PLUGIN_NAME": "{{title}}",
3
+ "SETTINGS": "Settings",
4
+ "SAVE": "Save",
5
+ "BROWSE_NAME": "Name in Browse",
6
+ "BROWSE_NAME_DOC": "The name of this source on Volumio's Browse page",
7
+ "SAVED": "Settings saved"
8
+ }
@@ -0,0 +1,135 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const libQ = require('kew');
6
+
7
+ // Volumio's own copy, as every plugin on the device uses; the tests use the devDependency.
8
+ const volumioModule = (name) => {
9
+ try {
10
+ return require(`/volumio/node_modules/${name}`);
11
+ } catch {
12
+ return require(name);
13
+ }
14
+ };
15
+ const VConf = volumioModule('v-conf');
16
+
17
+ // What the plugin offers. Replace it with calls to your service.
18
+ const catalog = require('./catalog.json');
19
+
20
+ // Every URI the plugin hands to Volumio starts with this. Volumio sends Browse to the
21
+ // first source whose URI starts the requested one, and routes favourites, playlists, radio,
22
+ // search and upnp itself: a root that started with the id would lose radio_*, upnp_* and
23
+ // the like to them.
24
+ const ROOT = 'music_service/{{id}}';
25
+ const trackUri = (track) => `${ROOT}/track/${track.id}`;
26
+
27
+ // Volumio creates one instance with `new` and calls the methods below.
28
+ // Every method Volumio calls returns a kew promise (libQ): Volumio rejects
29
+ // async functions and native Promises ("does not return adequate promise").
30
+ module.exports = class {{className}} {
31
+ constructor(context) {
32
+ this.context = context;
33
+ this.commandRouter = context.coreCommand;
34
+ this.logger = context.logger;
35
+ }
36
+
37
+ // Volumio copies these files to /data/configuration/<type>/<id>/ on first start.
38
+ getConfigurationFiles() {
39
+ return ['config.json'];
40
+ }
41
+
42
+ onVolumioStart() {
43
+ this.config = new VConf();
44
+ this.config.loadFile(this.commandRouter.pluginManager.getConfigurationFile(this.context, 'config.json'));
45
+ return libQ.resolve();
46
+ }
47
+
48
+ onStart() {
49
+ this.strings = this.loadStrings();
50
+ this.commandRouter.volumioAddToBrowseSources(this.browseSource());
51
+ return libQ.resolve();
52
+ }
53
+
54
+ onStop() {
55
+ this.commandRouter.volumioRemoveToBrowseSources(this.browseSource().name);
56
+ return libQ.resolve();
57
+ }
58
+
59
+ // The plugin's entry in Volumio's Browse page, under the name set in the settings page.
60
+ browseSource() {
61
+ return { name: this.config.get('browse_name'), uri: ROOT, plugin_type: 'music_service', plugin_name: '{{id}}' };
62
+ }
63
+
64
+ // Browse: the lists to show for a URI.
65
+ handleBrowseUri(uri) {
66
+ if (uri !== ROOT) return libQ.reject(new Error(`{{id}}: no page for ${uri}`));
67
+ return libQ.resolve({
68
+ navigation: {
69
+ prev: { uri: '/' },
70
+ lists: [{ availableListViews: ['list', 'grid'], items: catalog.map((track) => this.listItem(track)) }],
71
+ },
72
+ });
73
+ }
74
+
75
+ // Play: what a URI plays, as a list: Favourites reads the first item. service 'mpd'
76
+ // hands the stream URL to MPD, which then handles pause, stop and seek; the plugin
77
+ // needs no playback code of its own.
78
+ explodeUri(uri) {
79
+ const track = catalog.find((t) => trackUri(t) === uri);
80
+ if (!track) return libQ.reject(new Error(`{{id}}: nothing plays ${uri}`));
81
+ const { title, artist, album } = track;
82
+ return libQ.resolve([{ service: 'mpd', type: 'track', uri: track.url, name: title, title, artist, album }]);
83
+ }
84
+
85
+ // Search: Volumio asks every source at once. Resolve null when nothing matches and
86
+ // on any error: never reject, or the whole search may fail.
87
+ search(query) {
88
+ const value = String(query?.value ?? '').toLowerCase();
89
+ const found = value ? catalog.filter((t) => [t.title, t.artist, t.album].some((f) => f.toLowerCase().includes(value))) : [];
90
+ if (!found.length) return libQ.resolve(null);
91
+ return libQ.resolve({ title: this.strings.PLUGIN_NAME, availableListViews: ['list', 'grid'], items: found.map((t) => this.listItem(t)) });
92
+ }
93
+
94
+ listItem(track) {
95
+ const { title, artist, album } = track;
96
+ return { service: '{{id}}', type: 'song', title, artist, album, icon: 'fa fa-music', uri: trackUri(track) };
97
+ }
98
+
99
+ // The settings page: UIConfig.json, translated, with the saved values filled in.
100
+ getUIConfig() {
101
+ const lang = this.commandRouter.sharedVars.get('language_code');
102
+ return this.commandRouter
103
+ .i18nJson(this.file(`i18n/strings_${lang}.json`), this.file('i18n/strings_en.json'), this.file('UIConfig.json'))
104
+ .then((uiconf) => {
105
+ uiconf.sections[0].content[0].value = this.config.get('browse_name');
106
+ return uiconf;
107
+ });
108
+ }
109
+
110
+ // Called by the Save button of the settings page (onSave in UIConfig.json): renames
111
+ // the entry in Browse where it is. An empty name goes back to the plugin's title.
112
+ saveSettings(data) {
113
+ const previous = this.browseSource().name;
114
+ this.config.set('browse_name', String(data.browse_name ?? '').trim() || this.strings.PLUGIN_NAME);
115
+ this.commandRouter.volumioUpdateToBrowseSources(previous, this.browseSource());
116
+ this.commandRouter.pushToastMessage('success', this.strings.PLUGIN_NAME, this.strings.SAVED);
117
+ return libQ.resolve();
118
+ }
119
+
120
+ // The plugin's own strings in the user's language, English for any missing key.
121
+ loadStrings() {
122
+ const read = (lang) => {
123
+ try {
124
+ return JSON.parse(fs.readFileSync(this.file(`i18n/strings_${lang}.json`), 'utf8'));
125
+ } catch {
126
+ return {};
127
+ }
128
+ };
129
+ return { ...read('en'), ...read(this.commandRouter.sharedVars.get('language_code')) };
130
+ }
131
+
132
+ file(name) {
133
+ return path.join(__dirname, name);
134
+ }
135
+ };
@@ -0,0 +1,52 @@
1
+ 'use strict';
2
+
3
+ // Browse, play and search as Volumio calls them: `npm test`.
4
+ const { test } = require('node:test');
5
+ const assert = require('node:assert/strict');
6
+ const Plugin = require('..');
7
+ const catalog = require('../catalog.json');
8
+ const { fakeVolumio, isKew } = require('./volumio');
9
+
10
+ const started = () => {
11
+ const volumio = fakeVolumio();
12
+ const plugin = new Plugin(volumio.context);
13
+ plugin.onVolumioStart();
14
+ plugin.onStart();
15
+ return { plugin, volumio };
16
+ };
17
+
18
+ test('the plugin is in Browse while it runs', () => {
19
+ const { plugin, volumio } = started();
20
+ assert.deepEqual(volumio.browseSources.map((s) => s.uri), ['music_service/{{id}}']);
21
+ plugin.onStop();
22
+ assert.deepEqual(volumio.browseSources, []);
23
+ });
24
+
25
+ test('Browse lists the catalog, and each item plays its stream through MPD', async () => {
26
+ const { plugin } = started();
27
+ const browse = plugin.handleBrowseUri('music_service/{{id}}');
28
+ assert.ok(isKew(browse));
29
+ const items = (await browse).navigation.lists[0].items;
30
+ assert.deepEqual(items.map((i) => i.title), catalog.map((t) => t.title));
31
+
32
+ // A list of one: Favourites reads the first item.
33
+ const [played, ...rest] = await plugin.explodeUri(items[0].uri);
34
+ assert.deepEqual(rest, []);
35
+ assert.equal(played.service, 'mpd');
36
+ assert.equal(played.uri, catalog[0].url);
37
+ });
38
+
39
+ test('an unknown URI is rejected', async () => {
40
+ const { plugin } = started();
41
+ // assert.rejects takes native Promises only: the async function wraps the kew one.
42
+ await assert.rejects(async () => plugin.handleBrowseUri('music_service/{{id}}/nowhere'));
43
+ await assert.rejects(async () => plugin.explodeUri('music_service/{{id}}/track/nowhere'));
44
+ });
45
+
46
+ test('search finds by title, and resolves null when nothing matches', async () => {
47
+ const { plugin } = started();
48
+ const found = await plugin.search({ value: catalog[0].title.toUpperCase() });
49
+ assert.equal(found.items[0].uri, (await plugin.handleBrowseUri('music_service/{{id}}')).navigation.lists[0].items[0].uri);
50
+ assert.equal(await plugin.search({ value: 'no such track' }), null);
51
+ assert.equal(await plugin.search({}), null);
52
+ });
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+
3
+ // Runs the plugin as Volumio does, with a fake Volumio around it: `npm test`.
4
+ const { test } = require('node:test');
5
+ const assert = require('node:assert/strict');
6
+ const Plugin = require('..');
7
+ const { fakeVolumio, isKew } = require('./volumio');
8
+ const { PLUGIN_NAME } = require('../i18n/strings_en.json');
9
+
10
+ test('every lifecycle method returns a kew promise', () => {
11
+ const plugin = new Plugin(fakeVolumio().context);
12
+ for (const method of ['onVolumioStart', 'onStart', 'onStop']) assert.ok(isKew(plugin[method]()), method);
13
+ });
14
+
15
+ test('the settings page shows the name in Browse, and Save renames the entry', async () => {
16
+ const volumio = fakeVolumio();
17
+ const plugin = new Plugin(volumio.context);
18
+ plugin.onVolumioStart();
19
+ plugin.onStart();
20
+ assert.equal((await plugin.getUIConfig()).sections[0].content[0].value, PLUGIN_NAME);
21
+ assert.equal(volumio.browseSources[0].name, PLUGIN_NAME);
22
+
23
+ assert.ok(isKew(plugin.saveSettings({ browse_name: ' My music ' })));
24
+ assert.deepEqual(volumio.browseSources.map((s) => s.name), ['My music']);
25
+ assert.equal(volumio.toasts[0].type, 'success');
26
+
27
+ plugin.saveSettings({ browse_name: '' });
28
+ assert.deepEqual(volumio.browseSources.map((s) => s.name), [PLUGIN_NAME]);
29
+ });
@@ -0,0 +1,13 @@
1
+ {
2
+ "id": "{{id}}",
3
+ "version": "0.1.0",
4
+ "type": "{{type}}",
5
+ "function": "{{function}}",
6
+ "title": "{{title}}",
7
+ "description": "{{description}}",
8
+ "icon": "fa-puzzle-piece",
9
+ "engines": { "volumio": ">=4.0.0 <5.0.0", "api": "1" },
10
+ "arch": ["armhf", "amd64"],
11
+ "permissions": ["ui:toast", "browse-source", "playback"],
12
+ "license": "MIT"
13
+ }