Skip to content

Commit 50a4509

Browse files
committed
Add fade command and make playback and parsing more robust
New command: - fade [next|prev|fav|uri|file]: fade the group out, switch the source, wait until it plays, and fade back in. Defaults: 6 s out, 4 s in. --out, --in and --volume adjust the fade. "fade file" uses the built-in file server. Ctrl-C or an error restores the volumes. Robustness: - Parse arguments with node:util parseArgs. Each command declares its argument count, options and subcommands. Blank arguments are errors. - One Ctrl-C handler: the first press cleans up, the second quits. - WebSocket errors tell if a request was sent, was rejected, or has an unknown outcome. Favorites fall back to UPnP only when it is safe. - Validate snapshots on load, save them atomically, and restore each part with a warning on failure. - watch ends when the speaker closes the connection. - Build SOAP and DIDL with Bun.XML, validate the discovery cache, and pin @types/bun to 1.4.2.
1 parent 534e306 commit 50a4509

19 files changed

Lines changed: 792 additions & 311 deletions

‎README.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ sonos kantine volume 20 # the first word can be a room name
3838
sonos -s couch volume +5 # or use -s; names can be partial
3939
sonos gv -3 # group volume
4040
sonos pause | play | toggle | next | prev
41+
sonos fade # fade out, next song, fade in (6s out, 4s in)
42+
sonos fade fav "seeed radio" --out 10 --in 6 # also: fade prev, fade uri <uri>
43+
sonos fade file ~/Music/track.mp3 --volume 15 # serves the file until it ends
4144
sonos favorites # list Sonos favorites
4245
sonos fav "seeed radio" # play a favorite (by name or number)
4346
sonos play-uri https://st01.sslstream.dlf.de/dlf/01/128/mp3/stream.mp3 "Deutschlandfunk"
@@ -60,6 +63,8 @@ Options: `--json` for JSON output, `--dry-run` to print changing requests
6063
without sending them, `--refresh` to ignore the discovery cache.
6164
Unknown options and extra arguments are errors (exit code 2), so a typo
6265
such as `--dryrun` never sends a change.
66+
Command options are accepted only by their commands. `--player` and
67+
`--household` cannot be combined.
6368

6469
Environment: `SONOS_SPEAKER` sets the default room, `SONOS_HOST` sets the IP
6570
of one speaker (for networks without multicast).
@@ -89,6 +94,12 @@ sonos ws favorites getFavorites --household
8994
| `src/snapshot.ts` | save and restore source, track, position and volumes (like SoCo `snapshot.py`) |
9095
| `src/tts.ts` | text to speech with the macOS `say` command |
9196
| `src/xml.ts` | XML parsing (Bun.XML, normalized) and DIDL-Lite |
97+
| `src/arguments.ts` | strict argument parsing and command contracts |
98+
| `src/playback.ts` | local file playback and interruption |
99+
| `src/fade.ts` | volume fade around a change of song (defaults in `FADE_DEFAULTS`) |
100+
| `src/interrupt.ts` | Ctrl-C handling: first press cleans up, second press quits |
101+
| `src/watch.ts` | live event display and subscription lifecycle |
102+
| `src/validation.ts` | shared object boundary check |
92103
| `src/cli.ts` | command-line interface |
93104

94105
## Not ported

‎bun.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎docs/BUN-NATIVE-RESEARCH.md‎

Lines changed: 125 additions & 0 deletions
Large diffs are not rendered by default.

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
"build": "bun build src/cli.ts --compile --outfile dist/sonos"
3535
},
3636
"devDependencies": {
37-
"@types/bun": "latest"
37+
"@types/bun": "1.4.2"
3838
},
3939
"peerDependencies": {
4040
"typescript": "^7"

‎src/arguments.ts‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import { parseArgs } from "node:util";
2+
import { SonosError } from "./soap.ts";
3+
4+
export class UsageError extends SonosError {}
5+
6+
export type OptionDefinitions = Record<string, { type: "boolean" | "string"; short?: string }>;
7+
export type ArgumentCount = readonly [min: number, max: number];
8+
9+
export interface Action<Context> {
10+
/** Positional argument count. Without it, the action takes no arguments. */
11+
args?: ArgumentCount;
12+
run: (ctx: Context, args: string[]) => Promise<void>;
13+
}
14+
15+
interface CommandInfo {
16+
names: string[];
17+
usage: string;
18+
help: string;
19+
options?: OptionDefinitions;
20+
}
21+
22+
/** With subcommands, the first argument selects the action. The first subcommand is the default. */
23+
export type Command<Context> = CommandInfo & (Action<Context> | { subcommands: Record<string, Action<Context>> });
24+
25+
const GLOBAL_OPTIONS: OptionDefinitions = {
26+
help: { type: "boolean", short: "h" },
27+
json: { type: "boolean" },
28+
"dry-run": { type: "boolean" },
29+
refresh: { type: "boolean" },
30+
speaker: { type: "string", short: "s" },
31+
};
32+
33+
export function parseArguments(argv: string[], commands: CommandInfo[]) {
34+
const definitions: OptionDefinitions = Object.assign({}, GLOBAL_OPTIONS, ...commands.map((c) => c.options));
35+
try {
36+
// Numeric operands must keep their sign without being parsed as short options.
37+
const parsed = parseArgs({
38+
args: argv.map((arg) => /^-(?:\d+(?:\.\d*)?|\.\d+)$/.test(arg) ? arg.slice(1) : arg),
39+
options: definitions,
40+
strict: true,
41+
allowPositionals: true,
42+
tokens: true,
43+
});
44+
const flags = new Set<string>();
45+
const options = new Map<string, string>();
46+
const positional: string[] = [];
47+
for (const token of parsed.tokens) {
48+
if (token.kind === "positional") positional.push(argv[token.index]!);
49+
else if (token.kind === "option") {
50+
if (token.value === undefined) flags.add(token.name);
51+
else {
52+
const value = token.inlineValue ? token.value : argv[token.index + 1]!;
53+
if (!value) throw new UsageError(`Option --${token.name} needs a value`);
54+
options.set(token.name, value);
55+
}
56+
}
57+
}
58+
return { flags, options, positional };
59+
} catch (err) {
60+
throw new UsageError(err instanceof Error ? err.message : String(err));
61+
}
62+
}
63+
64+
/** Checks the options and the argument count, and returns the action with its arguments. */
65+
export function resolveAction<Context>(command: Command<Context>, args: string[], supplied: Iterable<string>): [Action<Context>, string[]] {
66+
for (const name of supplied) {
67+
if (!Object.hasOwn(GLOBAL_OPTIONS, name) && !Object.hasOwn(command.options ?? {}, name)) {
68+
throw new UsageError(`Option --${name} is not supported by "${command.names[0]}"`);
69+
}
70+
}
71+
let action: Action<Context>;
72+
if ("subcommands" in command) {
73+
const [name = Object.keys(command.subcommands)[0]!, ...rest] = args;
74+
const subcommand = Object.hasOwn(command.subcommands, name) ? command.subcommands[name] : undefined;
75+
if (!subcommand) throw new UsageError(`Unknown ${command.names[0]} command: ${name}`);
76+
[action, args] = [subcommand, rest];
77+
} else {
78+
action = command;
79+
}
80+
const [min, max] = action.args ?? [0, 0];
81+
if (args.length < min || args.length > max) throw new UsageError(`Usage: sonos ${command.usage}`);
82+
// An empty name must not match the first favorite or room.
83+
if (args.some((arg) => !arg.trim())) throw new UsageError(`Empty argument. Usage: sonos ${command.usage}`);
84+
return [action, args];
85+
}

0 commit comments

Comments
 (0)