Add local MPC-HC Companion development module
This commit is contained in:
parent
aceab5554b
commit
12c7eadc27
|
|
@ -56,6 +56,13 @@ with quick-start examples and links to detailed documentation in `docs/`.
|
|||
from pinned FFmpeg source, with source, LGPL notices and the recipe bundled.
|
||||
Include upstream notices/provenance, never commit binaries.
|
||||
|
||||
- `companion-modules/media-player-classic/` is the local MPC-HC module for Companion 5.1.
|
||||
Preserve numeric action IDs and upstream MIT attribution. Use Node.js 22.20+
|
||||
(22.x); run `npm test`, `npm run check`, and `npm run package` in the module.
|
||||
`setup.py` installs locked dependencies and can back up/configure the launcher.
|
||||
Keep dependencies, packages, and caches untracked; real-player playback checks
|
||||
are separate from automated mock HTTP tests.
|
||||
|
||||
## Repository layout
|
||||
|
||||
- `tools/` and `tests/`: Python prototypes and their regression tests.
|
||||
|
|
|
|||
|
|
@ -49,4 +49,5 @@ opening reports, and reading video timings.
|
|||
- [Rundown converter](docs/rundown-converter.md) · [Sample findings](docs/rundown-corpus.md)
|
||||
- [Development](docs/development.md) · [CI and coverage](docs/ci.md)
|
||||
- [Cross builds and portable releases](docs/releases.md)
|
||||
- [MPC-HC Companion module development](companion-modules/media-player-classic/README.md)
|
||||
- [Future ideas](Ideas.md)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,5 @@
|
|||
node_modules/
|
||||
pkg/
|
||||
*.tgz
|
||||
.npm-cache/
|
||||
DEBUG-PACKAGED
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
node_modules
|
||||
pkg
|
||||
package-lock.json
|
||||
*.tgz
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
The MIT License
|
||||
|
||||
Copyright (c) 2019 Bitfocus AS & Andreas H. Thomsen (McHauge)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
# MPC-HC Companion module — local development
|
||||
|
||||
A local development port of the original Media Player Classic module for
|
||||
**Companion 5.1.0**, using Companion module API 2 and Node.js 22. It preserves
|
||||
all 138 original numeric command IDs and provides matching button presets.
|
||||
See [UPSTREAM.md](UPSTREAM.md) for provenance and [LICENSE](LICENSE) for attribution.
|
||||
|
||||
## Install on this computer
|
||||
|
||||
From the repository root:
|
||||
|
||||
```sh
|
||||
python3 companion-modules/media-player-classic/setup.py \
|
||||
--node-bin /home/beffroi/Softs/companion-x64/resources/node-runtimes/node22/bin \
|
||||
--companion-config /home/beffroi/.config/companion/config.json \
|
||||
--package
|
||||
```
|
||||
|
||||
The helper installs dependencies from `package-lock.json`, runs tests and
|
||||
format checks, optionally builds a `.tgz`, and enables the developer folder.
|
||||
It backs up the launcher configuration before changing it and preserves other
|
||||
settings. It refuses to replace an existing different developer folder.
|
||||
It does not restart Companion, alter connections, or send player commands.
|
||||
Restart Companion after changing its launcher settings.
|
||||
|
||||
Alternatively, install **Node.js 22.20+ (22.x) with npm**, run `python3 setup.py`
|
||||
inside this module, and configure Companion manually:
|
||||
|
||||
1. Open the Companion launcher settings (cog).
|
||||
2. Enable **Developer Modules** and select the **parent** folder:
|
||||
`/home/beffroi/Documents/Git/beffroi-tools/companion-modules`.
|
||||
3. In Connections, add **MPC-HC: Media Player Classic**, selecting version **dev**.
|
||||
Use a distinct label such as `MPC_DEV` while testing.
|
||||
4. Set host **192.168.10.146** and port **13579** for the current player.
|
||||
5. In MPC-HC, enable **View → Options → Player → Web Interface → Listen on port**.
|
||||
Allow remote access from this Companion computer if the player is on another host.
|
||||
6. Confirm the connection is OK, then use its presets on a spare button page.
|
||||
|
||||
The module appears in Connections; a development module need not appear as an
|
||||
installed store version on the Modules page. Existing connections remain on
|
||||
their selected version until you explicitly change them.
|
||||
|
||||
## Edit, test, and update
|
||||
|
||||
On this machine, use the bundled runtime in a terminal:
|
||||
|
||||
```sh
|
||||
export PATH="/home/beffroi/Softs/companion-x64/resources/node-runtimes/node22/bin:$PATH"
|
||||
cd companion-modules/media-player-classic
|
||||
npm test
|
||||
npm run check
|
||||
npm run format # apply formatting after edits
|
||||
npm run package # produce media-player-classic-1.1.0-dev.0.tgz
|
||||
```
|
||||
|
||||
Companion watches the developer folder and reloads the module after source
|
||||
changes. No copying or packaging is needed for everyday edits. Disable and
|
||||
re-enable `MPC_DEV` if a reload does not occur. Changes briefly interrupt only
|
||||
connections using this development module.
|
||||
|
||||
After pulling dependency updates, rerun `setup.py` (without
|
||||
`--companion-config` if already configured). It uses `npm ci` to reproduce the
|
||||
locked dependency versions. Keep the lockfile committed. Packages, dependencies,
|
||||
and npm caches are ignored by Git.
|
||||
|
||||
For another computer later, build the package and import the `.tgz` through
|
||||
Companion's Modules page. Test the packaged build separately from source.
|
||||
No fork, publishing, or additional update server is required for local use.
|
||||
|
||||
## Layout
|
||||
|
||||
- `src/main.js`: Companion lifecycle, configuration, and connection status.
|
||||
- `src/client.js`: HTTP transport, timeout, and cancellation.
|
||||
- `src/commands.js`: original command catalog and stable action IDs.
|
||||
- `src/definitions.js`: action and preset definitions.
|
||||
- `test/`: mock HTTP integration tests; never contact the real player.
|
||||
- `companion/HELP.md`: help displayed inside Companion.
|
||||
|
||||
## Battle-testing checklist
|
||||
|
||||
Automated tests exercise all 138 command URLs against a mock server, HTTP errors,
|
||||
redirect refusal, timeout, cancellation, and configuration validation. They do
|
||||
not establish that every legacy command still works in current MPC-HC.
|
||||
|
||||
On a spare page with a disposable media file:
|
||||
|
||||
- Record the exact MPC-HC version, Companion version, and module Git commit.
|
||||
- Check Play, Pause, Stop, seeking, volume, mute, fullscreen, and playlist navigation.
|
||||
- Check presets render and trigger the expected action once.
|
||||
- Disable the player web interface, trigger an action, and confirm a useful error.
|
||||
Re-enable it and confirm the next action succeeds; commands are never retried.
|
||||
- Edit the module and verify reload; disable/re-enable its connection.
|
||||
- Restart Companion and verify the developer connection returns.
|
||||
- Test existing button compatibility before moving your normal MPC connection to dev.
|
||||
- Import and smoke-test a packaged build before upstreaming.
|
||||
|
||||
Initialization probes `/variables.html`; status afterward reflects the last HTTP
|
||||
request. There is no continuous health polling or playback-state feedback yet.
|
||||
A successful HTTP response confirms delivery, not that MPC-HC performed a command.
|
||||
Open File opens the player's dialog; it does not accept or upload a path.
|
||||
|
||||
To roll back, select the official version for any connection using dev, or remove
|
||||
`MPC_DEV`, disable Developer Modules, and restart Companion. The helper's
|
||||
`config.json.before-mpc-dev-*` backup can restore launcher settings while Companion
|
||||
is stopped. Your normal button configuration is not changed by the helper.
|
||||
|
||||
## References
|
||||
|
||||
- [Companion developer folders](https://companion.free/for-developers/module-development/local-modules/)
|
||||
- [Module packaging](https://companion.free/for-developers/module-development/module-lifecycle/module-packaging/)
|
||||
- [Original MPC module](https://github.com/bitfocus/companion-module-media-player-classic)
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
# Upstream provenance
|
||||
|
||||
Based on https://github.com/bitfocus/companion-module-media-player-classic
|
||||
commit `2ed43ac76a1d69f3e27bdb07ceb84233065ced2b` (version 1.0.1). The command catalog and preset behavior
|
||||
come from that MIT-licensed module. Its copyright notice is preserved in LICENSE.
|
||||
|
||||
This is a local development port to Companion API 2, not an upstream release.
|
||||
Existing numeric action IDs and host/port configuration keys are preserved.
|
||||
No public fork or pull request has been created.
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
# Media Player Classic — local development
|
||||
|
||||
Enable **View → Options → Player → Web Interface → Listen on port** in MPC-HC.
|
||||
The default port is **13579**. Enter the player computer's IP address and port
|
||||
in this connection. For a remote player, allow connections from the Companion
|
||||
computer in the player settings and firewall.
|
||||
|
||||
This module preserves the original 138 command actions and provides a preset
|
||||
for each. Commands such as Open File open a dialog on the player computer;
|
||||
they do not upload a file from Companion. Available commands depend on the
|
||||
MPC-HC build. A successful HTTP response confirms delivery, not playback state.
|
||||
|
||||
Connection initialization checks `/variables.html`. Actions update connection
|
||||
status on success or failure. There is no periodic polling, playback feedback,
|
||||
or automatic command retry. Re-enable the connection to repeat the initial check.
|
||||
|
||||
This is a local test build. Select the **dev** module version to use it.
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
{
|
||||
"$schema": "../node_modules/@companion-module/base/assets/manifest.schema.json",
|
||||
"type": "connection",
|
||||
"id": "media-player-classic",
|
||||
"name": "Media Player Classic (local development)",
|
||||
"shortname": "MPC",
|
||||
"description": "Local MPC-HC development module",
|
||||
"version": "1.1.0-dev.0",
|
||||
"license": "MIT",
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "Beffroi"
|
||||
}
|
||||
],
|
||||
"runtime": {
|
||||
"type": "node22",
|
||||
"api": "nodejs-ipc",
|
||||
"apiVersion": "2.1.3",
|
||||
"entrypoint": "../src/main.js"
|
||||
},
|
||||
"legacyIds": [],
|
||||
"manufacturer": "MPC-HC",
|
||||
"products": ["Media Player Classic"],
|
||||
"keywords": ["Video", "Media"],
|
||||
"repository": "git+https://git.dandaedre.com/Beffroi/beffroi-tools.git",
|
||||
"bugs": "https://git.dandaedre.com/Beffroi/beffroi-tools/issues"
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"name": "media-player-classic",
|
||||
"version": "1.1.0-dev.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "src/main.js",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^22.20"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "node --test",
|
||||
"check": "prettier --check .",
|
||||
"format": "prettier --write .",
|
||||
"package": "companion-module-build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@companion-module/base": "2.1.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@companion-module/tools": "3.1.1",
|
||||
"prettier": "3.9.9"
|
||||
},
|
||||
"prettier": "@companion-module/tools/.prettierrc.json"
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Install/update dependencies and validate the local Companion module."""
|
||||
import argparse
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--node-bin', type=Path, help='Directory containing Node.js 22.20+ and npm')
|
||||
parser.add_argument('--companion-config', type=Path, help='Enable developer modules in this launcher config.json; restart Companion afterward')
|
||||
parser.add_argument('--package', action='store_true', help='Also build an importable .tgz')
|
||||
args = parser.parse_args()
|
||||
root = Path(__file__).resolve().parent
|
||||
env = os.environ.copy()
|
||||
if args.node_bin:
|
||||
env['PATH'] = str(args.node_bin.resolve()) + os.pathsep + env.get('PATH', '')
|
||||
node = shutil.which('node', path=env.get('PATH'))
|
||||
npm = shutil.which('npm', path=env.get('PATH'))
|
||||
if not node or not npm:
|
||||
parser.error('Install Node.js 22.20+ (22.x) with npm, or pass --node-bin.')
|
||||
version = subprocess.check_output([node, '--version'], text=True, env=env).strip()
|
||||
parts = version.lstrip('v').split('.')
|
||||
if int(parts[0]) != 22 or int(parts[1]) < 20:
|
||||
parser.error(f'Found {version}; use Node.js 22.20+ (22.x) for the pinned module build tools.')
|
||||
for command in [['ci', '--no-audit', '--no-fund', '--cache', str(root / '.npm-cache')], ['test'], ['run', 'check']]:
|
||||
subprocess.run([npm, *command], cwd=root, env=env, check=True)
|
||||
if args.package:
|
||||
subprocess.run([npm, 'run', 'package'], cwd=root, env=env, check=True)
|
||||
dev_path = root.parent
|
||||
if args.companion_config:
|
||||
config_path = args.companion_config.expanduser().resolve(strict=True)
|
||||
config = json.loads(config_path.read_text())
|
||||
current = config.get('dev_modules_path')
|
||||
if current and Path(current).resolve() != dev_path:
|
||||
parser.error(f'Existing developer folder is {current}; refusing to replace it. Add this module there manually.')
|
||||
if not config.get('enable_developer') or current != str(dev_path):
|
||||
stamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S-%f')
|
||||
backup = config_path.with_name(config_path.name + '.before-mpc-dev-' + stamp)
|
||||
shutil.copy2(config_path, backup)
|
||||
config.update(enable_developer=True, dev_modules_path=str(dev_path))
|
||||
temporary = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(mode='w', dir=config_path.parent, delete=False) as file:
|
||||
temporary = Path(file.name)
|
||||
json.dump(config, file, indent=2)
|
||||
file.write('\n')
|
||||
shutil.copymode(config_path, temporary)
|
||||
os.replace(temporary, config_path)
|
||||
finally:
|
||||
if temporary and temporary.exists():
|
||||
temporary.unlink()
|
||||
print(f'Launcher configuration updated; backup: {backup}')
|
||||
print('Restart Companion to load the developer settings. Existing connections retain their selected version.')
|
||||
print(f'Developer modules folder: {dev_path}')
|
||||
print('Enable developer modules in the Companion launcher and select the dev version of MPC-HC in Connections.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
export function endpoint(config) {
|
||||
const host = String(config.host ?? '').trim()
|
||||
const port = Number(config.port ?? 13579)
|
||||
if (!host || /[\s/@?#]/.test(host) || !Number.isInteger(port) || port < 1 || port > 65535) {
|
||||
throw new Error('Set a valid MPC-HC host and port (1–65535).')
|
||||
}
|
||||
const url = new URL(`http://${host.includes(':') && !host.startsWith('[') ? `[${host}]` : host}:${port}/`)
|
||||
return url
|
||||
}
|
||||
|
||||
export class MpcClient {
|
||||
constructor(config, timeout = 5000) {
|
||||
this.url = endpoint(config)
|
||||
this.timeout = timeout
|
||||
this.abort = new AbortController()
|
||||
}
|
||||
|
||||
async request(path) {
|
||||
const response = await fetch(new URL(path, this.url), {
|
||||
signal: AbortSignal.any([this.abort.signal, AbortSignal.timeout(this.timeout)]),
|
||||
redirect: 'error',
|
||||
})
|
||||
await response.body?.cancel()
|
||||
if (!response.ok) throw new Error(`MPC-HC returned HTTP ${response.status}`)
|
||||
}
|
||||
|
||||
async command(id) {
|
||||
if (!/^\d+$/.test(String(id))) throw new Error('Invalid MPC-HC command ID')
|
||||
await this.request(`/command.html?wm_command=${id}`)
|
||||
}
|
||||
|
||||
async probe() {
|
||||
await this.request('/variables.html')
|
||||
}
|
||||
|
||||
close() {
|
||||
this.abort.abort()
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,141 @@
|
|||
// Command IDs and labels from the upstream MPC module; see UPSTREAM.md and LICENSE.
|
||||
export const commands = {
|
||||
800: 'Open File',
|
||||
801: 'Open DVD',
|
||||
802: 'Open Device',
|
||||
804: 'Close',
|
||||
805: 'Save As',
|
||||
806: 'Save Image',
|
||||
807: 'Save Image (auto)',
|
||||
808: 'Save thumbnails',
|
||||
809: 'Load Subtitle',
|
||||
810: 'Save Subtitle',
|
||||
814: 'Properties',
|
||||
816: 'Exit',
|
||||
817: 'Toggle Caption&Menu',
|
||||
818: 'Toggle Seeker',
|
||||
819: 'Toggle Controls',
|
||||
820: 'Toggle Information',
|
||||
821: 'Toggle Statistics',
|
||||
822: 'Toggle Status',
|
||||
823: 'Toggle Subresync Bar',
|
||||
824: 'Toggle Playlist Bar',
|
||||
825: 'Toggle Capture Bar',
|
||||
826: 'Toggle Shader Editor Bar',
|
||||
827: 'View Minimal',
|
||||
828: 'View Compact',
|
||||
829: 'View Normal',
|
||||
830: 'Fullscreen',
|
||||
831: 'Fullscreen (w/o res.change)',
|
||||
832: 'Zoom 50%',
|
||||
833: 'Zoom 100%',
|
||||
834: 'Zoom 200`%',
|
||||
835: 'VidFrm Half',
|
||||
836: 'VidFrm Normal',
|
||||
837: 'VidFrm Double',
|
||||
838: 'VidFrm Stretch',
|
||||
839: 'VidFrm Inside',
|
||||
840: 'VidFrm Outside',
|
||||
860: 'Next AR Preset',
|
||||
861: 'PnS Reset',
|
||||
862: 'PnS Inc Size',
|
||||
863: 'PnS Dec Size',
|
||||
864: 'PnS Inc Width',
|
||||
865: 'PnS Dec Width',
|
||||
866: 'PnS Inc Height',
|
||||
867: 'PnS Dec Height',
|
||||
868: 'PnS Left',
|
||||
869: 'PnS Right',
|
||||
870: 'PnS Up',
|
||||
871: 'PnS Down',
|
||||
872: 'PnS Up/Left',
|
||||
873: 'PnS Up/Right',
|
||||
874: 'PnS Down/Left',
|
||||
875: 'PnS Down/Right',
|
||||
876: 'PnS Center',
|
||||
877: 'PnS Rotate X+',
|
||||
878: 'PnS Rotate X-',
|
||||
879: 'PnS Rotate Y+',
|
||||
880: 'PnS Rotate Y-',
|
||||
881: 'PnS Rotate Z+',
|
||||
882: 'PnS Rotate Z-',
|
||||
884: 'Always On Top',
|
||||
886: 'Options',
|
||||
887: 'Play',
|
||||
888: 'Pause',
|
||||
889: 'Play/Pause',
|
||||
890: 'Stop',
|
||||
891: 'Framestep',
|
||||
892: 'Framestep back',
|
||||
893: 'Go To',
|
||||
894: 'Decrease Rate',
|
||||
895: 'Increase Rate',
|
||||
896: 'Reset Rate',
|
||||
897: 'Jump Backward (keyframe)',
|
||||
898: 'Jump Forward (keyframe)',
|
||||
899: 'Jump Backward (small)',
|
||||
900: 'Jump Forward (small)',
|
||||
901: 'Jump Backward (medium)',
|
||||
902: 'Jump Forward (medium)',
|
||||
903: 'Jump Backward (large)',
|
||||
904: 'Jump Forward (large)',
|
||||
905: 'Audio Delay +10ms',
|
||||
906: 'Audio Delay -10ms',
|
||||
907: 'Volume Up',
|
||||
908: 'Volume Down',
|
||||
909: 'Volume Mute',
|
||||
918: 'Previous Playlist Item',
|
||||
919: 'Next Playlist Item',
|
||||
920: 'Previous',
|
||||
921: 'Next',
|
||||
922: 'DVD Title Menu',
|
||||
923: 'DVD Root Menu',
|
||||
924: 'DVD Subtitle Menu',
|
||||
925: 'DVD Audio Menu',
|
||||
926: 'DVD Angle Menu',
|
||||
927: 'DVD Chapter Menu',
|
||||
928: 'DVD Menu Left',
|
||||
929: 'DVD Menu Right',
|
||||
930: 'DVD Menu Up',
|
||||
931: 'DVD Menu Down',
|
||||
932: 'DVD Menu Activate',
|
||||
933: 'DVD Menu Back',
|
||||
934: 'DVD Menu Leave',
|
||||
943: 'Boss key',
|
||||
948: 'Player Menu (short)',
|
||||
949: 'Player Menu (long)',
|
||||
950: 'Filters Menu',
|
||||
951: 'Next Audio',
|
||||
952: 'Prev Audio',
|
||||
953: 'Next Subtitle',
|
||||
954: 'Prev Subtitle',
|
||||
955: 'On/Off Subtitle',
|
||||
956: 'Next Audio (OGM)',
|
||||
957: 'Prev Audio (OGM)',
|
||||
958: 'Next Subtitle (OGM)',
|
||||
959: 'Prev Subtitle (OGM)',
|
||||
960: 'Next Angle (DVD)',
|
||||
961: 'Prev Angle (DVD)',
|
||||
962: 'Next Audio (DVD)',
|
||||
963: 'Prev Audio (DVD)',
|
||||
964: 'Next Subtitle (DVD)',
|
||||
965: 'Prev Subtitle (DVD)',
|
||||
966: 'On/Off Subtitle (DVD)',
|
||||
967: 'Zoom Auto Fit',
|
||||
969: 'Volume boost increase',
|
||||
970: 'Volume boost decrease',
|
||||
971: 'Volume boost Min',
|
||||
972: 'Volume boost Max',
|
||||
2302: 'Reload Subtitles',
|
||||
24000: 'Subtitle Delay -',
|
||||
24001: 'Subtitle Delay +',
|
||||
32769: 'Tearing Test',
|
||||
32770: 'Toggle Pixel Shader',
|
||||
32778: 'Remaining Time',
|
||||
32779: 'Toggle Direct3D fullscreen',
|
||||
32780: 'Goto Prev Subtitle',
|
||||
32781: 'Goto Next Subtitle',
|
||||
32782: 'Shift Subtitle Left',
|
||||
32783: 'Shift Subtitle Right',
|
||||
32784: 'Display Stats',
|
||||
}
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import { commands } from './commands.js'
|
||||
|
||||
export function actions(send) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(commands).map(([id, name]) => [
|
||||
id,
|
||||
{
|
||||
name,
|
||||
options: [],
|
||||
callback: async () => send(id),
|
||||
},
|
||||
]),
|
||||
)
|
||||
}
|
||||
|
||||
export function presets() {
|
||||
return Object.fromEntries(
|
||||
Object.entries(commands).map(([id, name]) => [
|
||||
id,
|
||||
{
|
||||
type: 'simple',
|
||||
name,
|
||||
style: { text: name, size: 'auto', color: 0xffffff, bgcolor: 0 },
|
||||
steps: [{ down: [{ actionId: id, options: {} }], up: [] }],
|
||||
feedbacks: [],
|
||||
},
|
||||
]),
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
import { InstanceBase, InstanceStatus } from '@companion-module/base'
|
||||
import { MpcClient } from './client.js'
|
||||
import { actions, presets } from './definitions.js'
|
||||
|
||||
export const UpgradeScripts = []
|
||||
|
||||
export default class MpcInstance extends InstanceBase {
|
||||
async init(config) {
|
||||
this.setActionDefinitions(actions((id) => this.send(id)))
|
||||
const buttons = presets()
|
||||
this.setPresetDefinitions([{ id: 'commands', name: 'Commands', definitions: Object.keys(buttons) }], buttons)
|
||||
await this.configUpdated(config)
|
||||
}
|
||||
|
||||
async configUpdated(config) {
|
||||
this.client?.close()
|
||||
this.client = undefined
|
||||
try {
|
||||
this.client = new MpcClient(config)
|
||||
} catch (error) {
|
||||
this.updateStatus(InstanceStatus.BadConfig, error.message)
|
||||
return
|
||||
}
|
||||
this.updateStatus(InstanceStatus.Connecting)
|
||||
// Do not block module initialization on an unavailable player.
|
||||
void this.perform((client) => client.probe())
|
||||
}
|
||||
|
||||
async perform(operation) {
|
||||
const client = this.client
|
||||
if (!client) return
|
||||
try {
|
||||
await operation(client)
|
||||
if (client === this.client) this.updateStatus(InstanceStatus.Ok)
|
||||
} catch (error) {
|
||||
if (client !== this.client) return
|
||||
const detail = error.cause?.code ?? error.message
|
||||
this.updateStatus(InstanceStatus.ConnectionFailure, String(detail))
|
||||
this.log('error', `MPC-HC request failed: ${detail}. Check the player Web Interface setting, host, and port.`)
|
||||
}
|
||||
}
|
||||
|
||||
async send(id) {
|
||||
await this.perform((client) => client.command(id))
|
||||
}
|
||||
|
||||
async destroy() {
|
||||
this.client?.close()
|
||||
this.client = undefined
|
||||
}
|
||||
|
||||
getConfigFields() {
|
||||
return [
|
||||
{
|
||||
type: 'static-text',
|
||||
id: 'info',
|
||||
label: 'MPC-HC setup',
|
||||
width: 12,
|
||||
value:
|
||||
'Enable View → Options → Player → Web Interface → Listen on port. Allow this Companion computer to connect.',
|
||||
},
|
||||
{
|
||||
type: 'textinput',
|
||||
id: 'host',
|
||||
label: 'Player IP address or hostname',
|
||||
width: 8,
|
||||
default: '127.0.0.1',
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
type: 'number',
|
||||
id: 'port',
|
||||
label: 'Web interface port',
|
||||
width: 4,
|
||||
default: 13579,
|
||||
min: 1,
|
||||
max: 65535,
|
||||
required: true,
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { createServer } from 'node:http'
|
||||
import { test } from 'node:test'
|
||||
import { MpcClient, endpoint } from '../src/client.js'
|
||||
import { actions, presets } from '../src/definitions.js'
|
||||
|
||||
async function server(t, handler) {
|
||||
const server = createServer(handler)
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
t.after(() => {
|
||||
server.closeAllConnections()
|
||||
server.close()
|
||||
})
|
||||
return { host: '127.0.0.1', port: server.address().port }
|
||||
}
|
||||
|
||||
test('all original actions and presets dispatch their numeric command IDs', async (t) => {
|
||||
const paths = []
|
||||
const client = new MpcClient(
|
||||
await server(t, (req, res) => {
|
||||
paths.push(req.url)
|
||||
res.end('ok')
|
||||
}),
|
||||
)
|
||||
t.after(() => client.close())
|
||||
const definitions = actions((id) => client.command(id))
|
||||
assert.equal(Object.keys(definitions).length, 138)
|
||||
for (const [id, action] of Object.entries(definitions)) {
|
||||
await action.callback()
|
||||
assert.equal(paths.at(-1), `/command.html?wm_command=${id}`)
|
||||
assert.equal(presets()[id].steps[0].down[0].actionId, id)
|
||||
}
|
||||
await client.probe()
|
||||
assert.equal(paths.at(-1), '/variables.html')
|
||||
})
|
||||
|
||||
test('HTTP failures and redirects fail rather than reporting success', async (t) => {
|
||||
for (const status of [404, 500, 302]) {
|
||||
const client = new MpcClient(
|
||||
await server(t, (_, res) => {
|
||||
res.writeHead(status, { Location: '/other' })
|
||||
res.end()
|
||||
}),
|
||||
)
|
||||
t.after(() => client.close())
|
||||
await assert.rejects(client.probe())
|
||||
}
|
||||
})
|
||||
|
||||
test('timeouts and module destruction cancel pending requests', async (t) => {
|
||||
const config = await server(t, () => {})
|
||||
const timeout = new MpcClient(config, 30)
|
||||
await assert.rejects(timeout.probe(), { name: 'TimeoutError' })
|
||||
timeout.close()
|
||||
const client = new MpcClient(config)
|
||||
const pending = client.probe()
|
||||
client.close()
|
||||
await assert.rejects(pending, { name: 'AbortError' })
|
||||
})
|
||||
|
||||
test('reject invalid configuration and command injection', async () => {
|
||||
for (const config of [
|
||||
{ host: '' },
|
||||
{ host: 'localhost/path' },
|
||||
{ host: 'localhost', port: 0 },
|
||||
{ host: 'localhost', port: 65536 },
|
||||
]) {
|
||||
assert.throws(() => endpoint(config))
|
||||
}
|
||||
assert.equal(endpoint({ host: '::1' }).hostname, '[::1]')
|
||||
const client = new MpcClient({ host: 'localhost' })
|
||||
await assert.rejects(client.command('887&extra=1'))
|
||||
client.close()
|
||||
})
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import { createServer } from 'node:http'
|
||||
import { test } from 'node:test'
|
||||
import { InstanceStatus } from '@companion-module/base'
|
||||
import MpcInstance from '../src/main.js'
|
||||
|
||||
function instance() {
|
||||
const state = { statuses: [] }
|
||||
const module = new MpcInstance({
|
||||
_isInstanceContext: true,
|
||||
id: 'test-mpc',
|
||||
label: 'MPC_TEST',
|
||||
setActionDefinitions: (actions) => {
|
||||
state.actions = actions
|
||||
},
|
||||
setPresetDefinitions: (sections, presets) => {
|
||||
state.sections = sections
|
||||
state.presets = presets
|
||||
},
|
||||
updateStatus: (status) => state.statuses.push(status),
|
||||
})
|
||||
return { module, state }
|
||||
}
|
||||
|
||||
test('initialization registers API 2 presets; successful actions recover failed requests', async (t) => {
|
||||
let status = 200
|
||||
const server = createServer((_, response) => {
|
||||
response.writeHead(status)
|
||||
response.end()
|
||||
})
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
const { module, state } = instance()
|
||||
t.after(async () => {
|
||||
await module.destroy()
|
||||
server.closeAllConnections()
|
||||
server.close()
|
||||
})
|
||||
await module.init({ host: '127.0.0.1', port: server.address().port })
|
||||
await module.send('887')
|
||||
assert.equal(state.statuses.at(-1), InstanceStatus.Ok)
|
||||
assert.equal(Object.keys(state.actions).length, 138)
|
||||
assert.deepEqual(state.sections[0].definitions, Object.keys(state.presets))
|
||||
assert.ok(Object.values(state.presets).every((preset) => preset.type === 'simple'))
|
||||
status = 503
|
||||
await module.send('887')
|
||||
assert.equal(state.statuses.at(-1), InstanceStatus.ConnectionFailure)
|
||||
status = 200
|
||||
await module.send('888')
|
||||
assert.equal(state.statuses.at(-1), InstanceStatus.Ok)
|
||||
})
|
||||
|
||||
test('configuration changes and destroy cancel stale operations without overwriting status', async (t) => {
|
||||
const server = createServer(() => {})
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
t.after(() => {
|
||||
server.closeAllConnections()
|
||||
server.close()
|
||||
})
|
||||
const { module, state } = instance()
|
||||
await module.init({ host: '127.0.0.1', port: server.address().port })
|
||||
const oldRequest = module.send('887')
|
||||
await module.configUpdated({ host: '' })
|
||||
await oldRequest
|
||||
assert.equal(state.statuses.at(-1), InstanceStatus.BadConfig)
|
||||
await module.configUpdated({ host: '127.0.0.1', port: server.address().port })
|
||||
const pending = module.send('888')
|
||||
await module.destroy()
|
||||
const count = state.statuses.length
|
||||
await pending
|
||||
assert.equal(state.statuses.length, count)
|
||||
assert.equal(module.client, undefined)
|
||||
})
|
||||
Loading…
Reference in New Issue