Compare commits

..
Author SHA1 Message Date
Waters ChurchandClaude Fable 5.1 1274360ee6 Send Message 1.0.0: one PIN, one place to send from; Slack 1.3.0 and ProdCom 1.4.0 become messaging providers
A new send-message module owns everything a dashboard sends: the PIN
(switchable off in admin), the unlock tokens, the Send message and Quick
replies tiles, the quick replies and quick emojis. It opens no upstream
connection of its own — it finds every module declaring
provides: ["messaging"] through the shell's module list and hands each
message to that module's POST /messaging/send over loopback, so Slack keeps
its one Slack connection and ProdCom its one ProdCom connection. Providers
check the browser's unlock token with GET /verify over loopback before
touching their upstream, so no browser on the network can post as the
location without having entered the PIN here.

Slack 1.3.0 is view-only plus reactions: the Sending group, PIN, send tiles
and quick replies are gone; it serves the messaging descriptor (channels as
recipients) and its reactions ride on the Send Message unlock. A layout's
old Send message / Quick replies tiles draw nothing until removed.

ProdCom 1.4.0 serves the descriptor as identities — only channels with
typingEnabled, since typed text goes out *as* a channel — and posts with
POST /api/v1/channels/{id}/send. Its tile is a click-to-target like Slack's
(accent stripe along the bottom), and typed entries carry a keyboard mark.

The tiles: click any Slack or ProdCom transcript to point sends there; a
Send as menu (only for platforms with identities, hidden otherwise) picks
the ProdCom channel to speak as; the choice is saved with the tile so named
layouts remember it. Wording follows the role — "Send message to #ops…" /
"Send message to ProdCom as FOH…". The PIN pad's dots ride on a real
numeric input so a phone's keyboard appears. Outcome is an icon beside
Send (check / blocked, five seconds, sentence as tooltip). A pill on the
box's bottom edge trades box height for rows of quick-emoji keys, a row
at a time; the single row scrolls sideways on a narrow tile with Send
pinned in place.

The module guide documents the provider contract and the page bus
(window.proddashMessaging + proddash:messaging:* events) the tiles share;
the ProdCom mock gained the send route.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-05 13:55:55 -04:00
michael 3b81efcb51 Merge pull request 'Update check: say what the forge answered, not zlib's "incorrect header check"' (#34) from claude/update-error-message into main 2026-09-30 14:23:04 -04:00
Waters Church 409f2c258e Merge remote-tracking branch 'origin/main' into claude/update-error-message
# Conflicts:
#	package.json
2026-09-30 14:22:25 -04:00
michael 7f6e5bd151 Merge pull request 'Shell 1.10.1: header menus open where their button is, folded bar or not; ProdCom 1.3.3 keeps its filter on a narrow tile' (#39) from claude/prodcom-filter-button-visibility-8a1d2d into main 2026-09-30 14:21:52 -04:00
michael 2307770ce9 Merge pull request 'SPL Meter 0.5.0: the capture tool ships prebuilt, for Apple silicon and Intel' (#38) from claude/spl-prebuilt-helper into main 2026-09-30 14:20:46 -04:00
michael fe3811b03e Merge pull request 'Timers 1.7.0: the LTC capture tool ships prebuilt, for Apple silicon and Intel' (#37) from claude/timers-prebuilt-helper into main 2026-09-30 14:19:52 -04:00
Waters ChurchandClaude Fable 5.1 41811ead1c Shell 1.10.1: header menus open where their button is, folded bar or not; ProdCom 1.3.3 keeps its filter on a narrow tile
A tile's dropdown menus (ProdCom's Channels, the Timers menu) opened but
never showed under a folded-away title bar — in fullscreen, or with
auto-hide on. The bar carries a backdrop-filter and a transform while
folded, and either one makes a fixed-positioned descendant position
itself against the bar instead of the viewport: the menu landed a
screen-height below its button, inside the tile's overflow. A tile near
the top of the screen showed a misplaced menu; anything lower showed
nothing at all.

The shell now hosts every header menu on the body, under an element
carrying the tile's data-module so a module's scoped CSS still reaches
its items; places it whole inside the viewport; holds a folded bar open
while one of its menus is open (the pointer has to travel down into the
menu); and marks the open menu's button the way the gear is marked.

ProdCom: seven controls need ~175 px of bar, and the shell clips what a
narrow tile cannot fit — the Channels button went with the rest. Below
380 px the six secondary controls fold into a ⋯ menu offering the same
actions, so the filter is the last thing to go.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-30 14:08:02 -04:00
Waters ChurchandClaude Fable 5.1 0929af46ca SPL Meter 0.5.0: the capture tool ships prebuilt, for Apple silicon and Intel
Same move as Timers 1.7.0. The capture tool existed only where the macOS
app build had compiled it, with the module trying swiftc on the booth as a
fallback — NA has been logging "spawn spl-capture ENOENT" since its
catalog install. Under the module guide's rule it now ships built:
bin/spl-capture-macos-arm64 and bin/spl-capture-macos-x86_64, signed with
the Developer ID (hardened runtime, audio-input entitlement), from
native/spl-capture.swift via native/build.sh. captureTool() picks the
binary for this platform; where there is none — Windows, until a Windows
implementation exists — measurement reports itself off in the health line
and the device picker while the module stays mounted. The runtime build
and its "building…" state are gone, and the old top-level binary is no
longer gitignored.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-30 10:12:42 -04:00
Waters ChurchandClaude Fable 5.1 2817a444c3 Timers 1.7.0: the LTC capture tool ships prebuilt, for Apple silicon and Intel
The tool used to be compiled by the macOS app build, or by the module
itself on the booth with swiftc — and a catalog install got source only,
which the unbundled 1.10.0 shell made every fresh install. Under the module
guide's rule it now ships built: bin/ltc-capture-macos-arm64 and
bin/ltc-capture-macos-x86_64, signed with the Developer ID (hardened
runtime, audio-input entitlement), from native/ltc-capture.swift via
native/build.sh. Nothing is built or looked for on the machine any more:
captureTool() picks the binary for this platform, and where there is none
— Windows, until a Windows implementation exists — timecode reports itself
off in the tile and the health line while the rest of the module runs.
The runtime build, its "building…" states and the device picker's build
kick are gone with it. The old top-level binary is no longer gitignored
(it is no longer written).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-30 10:11:08 -04:00
michael c11389473f Merge pull request 'Release builds: Intel disk images, a Windows bundle, and where to download them' (#24) from claude/release-builds into main 2026-09-30 09:58:11 -04:00
Waters ChurchandClaude Fable 5.1 c6a44e6ddc Windows build script: executable, like the Mac one
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-30 09:54:51 -04:00
Waters ChurchandClaude Fable 5.1 2f14b30d68 Windows bundle: no modules either, and the read-me says where they come from
The same change the Mac build got in 1.10.0: the bundle carries the shell
alone; the admin page's catalog installs modules into %APPDATA%\ProdDash.
README.txt gains the step.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-30 09:46:51 -04:00
Waters Church b5d39c60dc Merge remote-tracking branch 'origin/main' into claude/release-builds 2026-09-30 09:46:12 -04:00
michael 407eaecc23 Merge pull request 'Shell 1.10.0: a packaged ProdDash carries no modules' (#36) from claude/unbundled-shell into main 2026-09-30 09:42:23 -04:00
Waters ChurchandClaude Fable 5.1 ac1f17b9ed Shell 1.10.0: a packaged ProdDash carries no modules
The macOS app and the Windows bundle shipped every module in the repo, on
by default, and a shell update silently added whatever new module had
landed on main — Band Lineup appeared on AB that way. A module was also
only as fresh as the last shell update. Now a packaged install (no .git —
the same test the updater uses to choose the archive over git pull)
carries no modules at all: every one arrives from the admin page's catalog
into the data directory, and the shell's own update never writes modules/.
A git checkout keeps running the modules in its tree.

Existing installs move over by themselves: at the first start, the bundled
modules that are switched on are copied into the data directory as
installed copies (a compiled helper keeps its mode), an uninstalled one is
dropped, and the app folder's modules/ is removed. Settings are keyed by
module id, so nothing changes for the operator.

Around it: the dashboard's empty state says "No modules yet — open Admin"
when the registry is empty; the admin page says "Nothing installed yet",
puts a checkbox on every compatible catalog entry and an Install selected
button (POST /api/admin/modules/install {ids}) that fetches them in one go.
The Mac build stops copying modules/ and no longer compiles or signs Swift
helpers — those ship prebuilt inside a module, per the guide.

tools/unbundled.test.js drives a packaged copy of the shell through the
move, an archive update that must not bring modules back, and a multi-install.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-30 09:34:10 -04:00
michael c37575f662 Merge pull request 'Module rules: a native helper ships prebuilt, for Apple silicon and Windows' (#35) from claude/module-helper-rules into main 2026-09-29 16:45:35 -04:00
Waters ChurchandClaude Fable 5.1 07e4c78417 Module rules: a native helper ships prebuilt, for Apple silicon and Windows
The machine running ProdDash is a packaged app or the Windows bundle plus
modules from the admin page's catalog. It has no compiler, and the catalog
delivers exactly the folder that is in the repo — so a module's native
program (audio capture, a decoder) ships already built, inside the module
folder, one file per platform: bin/<name>-macos-arm64 and
bin/<name>-win-x64.exe are required, Intel macOS optional, source and the
script that rebuilds every binary under native/.

The guide's rule 3 now says so, "The shape of a module" shows the layout,
and a new "Native helpers" section gives the contract: pick the binary by
platform at runtime, report the feature off when there is none — never
build, never search the machine, never ask the operator to install
anything — one command-line contract in any language per platform, bump
the version when a binary changes, keep them lean, sign the macOS one.
CLAUDE.md carries the one-line version. Rules only: no module changes here.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 16:34:34 -04:00
michael 9ca301b4be Merge pull request 'PCO Plan 1.9.0: a Song Key tile, keys as notes, and AbleSet-shaped section chips' (#32) from claude/pco-song-key into main 2026-09-29 14:58:47 -04:00
Waters ChurchandClaude Opus 5 ece2c0a2c3 Centre the NOW tag; the type badge was already fine
Re-measuring the badges properly changed the answer. The earlier reading
that said the type badge sat 0.52px high was measuring the wrong glyphs: it
fed the canvas the element's raw text ("Song", "Media") while the page
renders text-transform: uppercase ("SONG", "MEDIA"), and a lowercase 'd' or
'g' has an ascender and a descender the capitals never draw.

Measured against the text as actually rendered, the type badge is within
0.10px of centred and wants nothing. The NOW tag was the one off, by 0.59px,
the same way the section chips were. So: the badge padding added in the last
commit is reverted, and the NOW tag gets the correction instead.

That line now reads, in px off centre: NOW 0.01, type badge 0.10, key badge
0.16, section chip -0.01.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-29 14:57:43 -04:00
Waters ChurchandClaude Opus 5 32180bf299 Centre the text in the song-section chips
The chips looked top-heavy, and measuring said so: the capitals sat 5.12px
below the top of the chip and 4.22px above the bottom. Uppercase text has no
descenders, so the font's descent allowance below the baseline is empty
space the letters never use, while the gap between the ascender line and the
cap height sits above them.

The padding is now a touch shallower on top and deeper below, which puts the
letters themselves in the middle: 4.67px above, 4.68px below. In em, so it
holds wherever the tile's text size is set.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-29 14:57:43 -04:00
Waters ChurchandClaude Opus 5 06066529bc Keys read as notes on the Plan tile's badge too
The item badge still showed Planning Center's raw "Bb" and "F#m" while the
Song Key tile beside it showed B♭ and F♯m. One module should not spell the
same thing two ways.

The notation moves into key-notation.js and both tiles import it, rather
than each keeping its own copy of the parse: the day one of them changes,
they all should.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-29 14:57:43 -04:00
Waters ChurchandClaude Opus 5 4e5b60e82b PCO Plan 1.9.0: a Song Key tile, and AbleSet-shaped section chips
**Song Key**, a third entry in the + picker: the key of the item
ProPresenter has live, as large as the tile allows. It is set as a note —
B♭, F♯m rather than Bb and F#m — with the song's name and the next keyed
song under it. All three are tile settings: the colour, the name and the
next key. There is no new connection; it reads the same streamed state the
Plan tile does.

The accidental and the quality sit on the same line as the letter. Raising
the accidental read as two stacked characters at tile sizes, which is worse
than plain at a glance from the back of a room.

When the ProPresenter feed that picks the item goes away the key stays up —
the band still needs it — but faded, and the tile's dot says it is the last
item rather than the current one.

**The section chips** on the Plan tile's current item are rounded squares
now, with the tinted ground and transparent border the AbleSet module gives
its own section pills, so the two read as one family. The chip playing keeps
its own ground so its progress fills against the chip rather than against
the row behind it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-29 14:57:43 -04:00
Waters ChurchandClaude Fable 5.1 601dc9e8b0 Update check: say what the forge answered, not zlib's "incorrect header check"
A Gitea that requires a sign-in does not refuse the branch archive: it
redirects the download to its login page, which arrives as a 200 of HTML,
and the admin page then reported zlib failing to unpack it — "incorrect
header check". Both booths showed exactly that on 29 Sept once the sign-in
requirement was switched on.

The updater now names the case: "… requires a sign-in to read
michael/ProdDash@main — turn off 'require sign-in to view' in Gitea, or
make the repo readable without one". Any other answer that is not a gzip
archive says what came back instead — a web page, or the content type —
and where to look.

tools/update-check.test.js drives the check against a mock forge: the login
redirect, a bare HTML answer, an HTTP error, and a real archive that must
still parse and be offered.

Shell 1.9.3.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-29 14:54:05 -04:00
michael 92b98b6579 Merge pull request 'SPL Meter 0.4.3: a failed capture-tool build must not park the listener forever' (#31) from claude/spl-build-retry into main 2026-09-28 11:31:49 -04:00
michael 58f3e5010a Merge pull request 'SPL Meter 0.4.2: the device picker can build the tool it needs' (#18) from claude/spl-devices-without-binary into main 2026-09-28 11:30:36 -04:00
michael 7cc19ef696 Merge pull request 'Timers 1.6.0: the ProPresenter video countdown, with looping videos hidden' (#33) from claude/timers-video-countdown into main 2026-09-27 11:35:52 -04:00
Waters ChurchandClaude Fable 5 86a3270f1c Timers 1.6.0: the ProPresenter video countdown, with looping videos hidden
Time left on the video ProPresenter is playing — the one number a booth
needs during a bumper or sermon video — was missing: the module only read
the configured timers, and the video countdown lives in the transport
routes. Verified live on ProPresenter 21.4:
  GET /v1/transport/presentation/current → { is_playing, uuid, name,
    artist, audio_only, duration }
  GET /v1/transport/presentation/time    → bare seconds as a sub-second
    float — better than /v1/timer/video_countdown's whole-second string,
    so no quantization phase lock is needed, only an anchor hold (a frame
    is broadcast only when the anchor drifts, not per poll).

The Video card rides the ProPresenter source: transport current on the
slow lane, position on the hot path (skipped while no media is loaded),
running/paused/idle from is_playing and position, the media name (minus
its file extension) as the detail line. It persists as an idle '—'
between videos — a wall tile must not appear and vanish with the media —
and is absent only on a ProPresenter whose transport routes 404.

No looping flag exists anywhere in the API, so looping is inferred: the
same media's position jumping backwards is a wrap, and the flag sticks
until the media changes. Each tile gets a 'Looping videos' switch
(default off): off, a looping background's meaningless time is hidden —
the card sits out of a multi-card tile, and a solo Video tile shows a
quiet 'Looping' card instead of sitting empty. Shown loops never take
the warn/overrun tones: a 15 s background flashing red every wrap would
cry wolf all service.

The picker offers 'Video' as its own tile (solo gear carries the loop
switch); pp-timers-mock gains the transport routes with a 4-minute cycle
(bumper playing → paused → resumed → nothing → looping background).
Verified in the browser across the whole cycle, both tile kinds, and the
per-tile toggle. Selftests pass.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-27 11:32:36 -04:00
Waters ChurchandClaude Fable 5 e9d6edc2c8 SPL Meter 0.4.3: a failed capture-tool build must not park the listener forever
Same deadlock the Timers module hit live on AB (fixed there in 1.5.1):
start() skipped scheduling its retry while a build was in flight, and
ensureCaptureBinary's onReady only fires on build SUCCESS. A failed
build therefore left the listener waiting forever on a callback that
never comes — "Building the capture tool…" indefinitely — and a binary
scp'd in from outside (the required path on AB, whose CLT cannot
compile) was never picked up without a module remount.

onReady stays as the fast path; the 30-second retry is now armed in
every not-ready state, so a failed build keeps re-checking and an
externally supplied binary is found within half a minute.

Reproduced pre-fix (build fails at 0s, binary copied in at 3s, still
untouched at 38s) and verified post-fix (retry at 30s spawns it).
spl-capture --selftest unchanged against the IEC 61672 table.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-09-27 11:03:57 -04:00
michael b3b7b29007 Merge pull request 'Timers 1.5.1: a failed capture-tool build must not park the listener forever' (#30) from claude/timers-build-retry into main 2026-09-27 10:59:17 -04:00
Waters ChurchandClaude Fable 5.1 b5c539ba05 Release builds: Intel disk images, a Windows bundle, and where to download them
launcher/macos/build.sh takes ARCH=x86_64 for Intel Macs — the Swift target
and the embedded Node follow (nodejs.org calls that one darwin-x64). The
default stays arm64.

launcher/windows/build.sh is new: the same payload plus Node for Windows,
checksum-verified against nodejs.org, and ProdDash.bat, which keeps the
server running and starts it again on exit code 75 — the admin page's update
restart — the way the macOS launcher does. No Windows launcher app yet.

The README's Run it section now points at the Releases page and the
ProdDash-releases repo that holds the files, one line each for Apple
silicon, Intel and Windows.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-24 17:53:19 -04:00
Waters ChurchandClaude Opus 5 9313c9e42a SPL Meter 0.4.2: the device picker can build the tool it needs
NA could not list a single audio interface. The module was installed from
the catalog, which ships source only because the capture binary is
gitignored, and the picker shells out to that binary with --list. So it
returned nothing, forever:

  [spl-meter] device list failed: spawn .../spl-capture ENOENT

The missing-binary build existed, but only inside the listener, and the
listener only starts once a device has been picked. No tool meant no device
list, and no device meant no listener to build the tool. Nothing was going
to break that on its own.

The build now lives at module scope and both callers use it: init() asks for
it on mount whether or not a device is configured, and /devices asks again
each time it is called, so opening the admin page is enough to start it. It
is still a plain spawn that never touches the event loop, and health() now
names the situation instead of leaving an empty dropdown unexplained.

Also removed two per-listener build flags left shadowing the module-scope
ones, which would have made the "is a build already running" test always
false and let a second build start under the first.

Tested the way it actually failed: a data directory holding only the six
source files, no binary. The build starts on mount and /devices answers with
the real device list moments later.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-23 15:25:43 -04:00
52 changed files with 5109 additions and 1837 deletions
+2 -6
View File
@@ -8,12 +8,8 @@ dist/
config/modules.json
config/layouts/
# compiled per-machine, source sits next to it
modules/propresenter-timers/ltc-capture
# the launcher's build output, and its cache of the Node runtime it embeds
launcher/macos/build/
launcher/macos/.cache/
# Compiled per-machine, source sits next to it (see spl-capture.swift).
modules/spl-meter/spl-capture
launcher/windows/build/
launcher/windows/.cache/
+8 -2
View File
@@ -3,7 +3,8 @@
Modular production dashboard web app for Waters Church, developed in this repo.
The app lives at the repo root and is built: zero-dependency Node server
(`server.js`, Node 18+), dashboard shell client in `public/`, admin page at
`/admin`, modules in `modules/`, and a native macOS menu-bar launcher in
`/admin`, modules in `modules/` (the repo's copies — a packaged install ships
none and installs them from the admin page's catalog), and a native macOS menu-bar launcher in
`launcher/macos/` (Swift, no dependencies — the shipped macOS app: it carries
the server and its own Node runtime, supervises them, and owns the macOS
permissions modules declare; see its README). Runtime state (module
@@ -28,7 +29,12 @@ title-bar controls). The rules that matter most:
ship inside the module folder** (zero deps is the norm). **Everything the
module does runs inside its server entry** — no helper scripts, companion
programs or daemons the operator starts by hand; a listener or decoder is
started in `init()` and stopped in `stop()`. Declare `"proddash": ">=x.y.z"`
started in `init()` and stopped in `stop()`. **A native helper ships
prebuilt inside the module folder for Apple silicon macOS and 64-bit
Windows** (`bin/<name>-macos-arm64`, `bin/<name>-win-x64.exe`, source and
build script under `native/`); nothing is ever compiled on the machine
running ProdDash, and a missing binary means the feature reports itself
off, not a broken module. Declare `"proddash": ">=x.y.z"`
and bump the module's `version` on every change.
- Browsers never call upstream services directly; the module's server routes
proxy everything (no CORS, secrets stay server-side).
+102 -36
View File
@@ -30,11 +30,23 @@ and a clear degraded state, then recover on their own.
## Run it
Ready-made builds are on the
[Releases page](http://chronicles-ab.waterschurch.org:3000/michael/ProdDash/releases);
the files themselves live in
[ProdDash-releases](http://chronicles-ab.waterschurch.org:3000/michael/ProdDash-releases).
There is a disk image for Apple silicon Macs, one for Intel Macs, and a
bundle for 64-bit Windows. Every build updates itself afterwards from the
admin page, so the download only has to be recent, not current.
### macOS — the app
Open the disk image and drag **ProdDash** to Applications. That's the whole
Download the disk image for your Mac — `ProdDash-<version>-arm64.dmg` for
Apple silicon, `ProdDash-<version>-x86_64.dmg` for Intel — open it and drag
**ProdDash** to Applications. That's the whole
installation: the app carries the dashboard and its own Node runtime, so
nothing else has to be installed and nothing can be missing. It lives in the
nothing else has to be installed. It carries no modules — open **Admin →
Available modules**, tick the ones this machine needs and press **Install
selected**; each updates on its own from then on. It lives in the
menu bar, starts and stops the server, can open at login, and holds the
permissions the modules need — the microphone the LTC listener reads, and
local network access for ProdCom and ProPresenter. macOS grants those to the
@@ -43,12 +55,26 @@ a launchd job) simply doesn't have them, and an LTC input goes silently to
zeroes.
Build the disk image from a checkout with
[launcher/macos](launcher/macos)/`build.sh`:
[launcher/macos](launcher/macos)/`build.sh` (`ARCH=x86_64` in front of it
for Intel):
```bash
cd launcher/macos && ./build.sh --dmg
```
### Windows — the bundle
Download `ProdDash-<version>-win-x64.zip`, unzip it somewhere you can write
to — `C:\ProdDash`, say, not Program Files, because updates write into the
folder — and double-click **ProdDash.bat**. The window it opens is the
dashboard running: it stays open, and it starts the server again when the
admin page applies an update. Allow `node.exe` on private networks when the
firewall asks, so other screens can reach it. Settings and layouts live in
`%APPDATA%\ProdDash`, so a new bundle never loses them. To start with
Windows, put a shortcut to `ProdDash.bat` in `shell:startup`. There is no
menu-bar-style launcher for Windows yet; the bundle is built with
[launcher/windows](launcher/windows)/`build.sh`.
### Anywhere else, or from a checkout
Requires [Node.js](https://nodejs.org) 18 or newer.
@@ -179,13 +205,15 @@ below. Nothing is installed without someone clicking.
- **Available modules** lists modules in the repo that aren't installed
here. **Install** downloads the module into the data directory's `modules/`
and starts it right away — nothing is written into the app folder, and no
restart is needed. Modules that ship with your copy of ProdDash are
"bundled"; ones you installed are "installed"; if both exist, the newer
version runs.
restart is needed. Tick several and press **Install selected** to fetch
them in one go. A packaged ProdDash (the app, the Windows bundle) ships
with no modules at all: this list is how every one of them arrives, and a
ProdDash update never brings one along. A git checkout also runs the
modules in its own tree ("bundled"); if both exist, the newer version runs.
- **Uninstall** on a module card removes an installed module's files. For a
bundled module (its folder belongs to the app) it hides the module from
every dashboard instead; it reappears under Available modules and can be
brought back without downloading. Settings are kept either way.
checkout's bundled module (its folder belongs to the repo) it hides the
module from every dashboard instead; it reappears under Available modules
and can be brought back without downloading. Settings are kept either way.
- **Module updates**: when the repo has a newer version of an installed
module, its card shows **Update to vX**.
- **Version requirements**: every module declares the ProdDash versions it
@@ -290,7 +318,13 @@ below. Nothing is installed without someone clicking.
- **ProdCom** — live transcript stream with in-place updates of in-progress
speech, channel colors, per-tile channel visibility toggles and group
presets, timestamps, text size, a top-down / bottom-up direction toggle
and jump-to-latest in the title bar.
and jump-to-latest in the title bar. Text typed into a channel (from a
dashboard, or ProdCom's own box) is marked with a keyboard; an automation's
with a bolt. The module also offers its channels to **Send Message** as
identities: a click anywhere in the transcript points that module's tiles
at ProdCom (the tile's bottom edge lights up in the accent color), and the
channel the text goes out *as* is picked from their Send as menu — only
channels ProdCom lets text be typed onto are offered.
Admin config: ProdCom server (host : port), API key.
Tile settings: channel icons, direction and timestamps.
- **ProPresenter** — what's live and what's next, with slide progress,
@@ -303,9 +337,11 @@ below. Nothing is installed without someone clicking.
status, NOW and NEXT labels, slide count, progress bar, the next list and
its item tags, plus tidy titles.
- **Timers** — live ProPresenter timers (countdown, countdown-to-time,
elapsed) and LTC timecode as auto-sized cards. The + picker lists every
discovered timer (and the LTC card) as its own tile, or add "All timers"
and pick a selection via the tile's "Timers ▾" menu; overruns are
elapsed), the **video countdown** (time left on what ProPresenter is
playing, with a per-tile "Looping videos" switch so looping backgrounds
stay hidden) and LTC timecode as auto-sized cards. The + picker lists
every discovered timer (and the LTC card) as its own tile, or add "All
timers" and pick a selection via the tile's "Timers ▾" menu; overruns are
unmistakably red. Read-only — no start/stop controls. Admin config is in
three groups: **ProPresenter** (endpoint host : port, API password),
**LTC Timecode** (the listener switch, and — when it's on — the audio
@@ -323,8 +359,9 @@ below. Nothing is installed without someone clicking.
session (Start ProdDash.command) and approve the one-time prompt; a server
started over SSH or by bare launchd silently captures zeros. (Engine
self-test: `node modules/propresenter-timers/ltc.selftest.js`.)
- **PCO Plan** — Planning Center Services, as two tiles in the + picker:
**Plan** (the order of service) and **Teams** (who is scheduled).
- **PCO Plan** — Planning Center Services, as three tiles in the + picker:
**Plan** (the order of service), **Teams** (who is scheduled) and **Song
Key** (the key of the item on screen).
**Plan** shows every
plan item with its scheduled start time, length, type, song key,
@@ -355,6 +392,16 @@ below. Nothing is installed without someone clicking.
is switched off, or it has no host — nothing to turn off and nothing to
explain.
**Song Key** is one value, as large as the tile allows: the key of the item
ProPresenter has live, with the song's name and the next key under it — both
switches, as is the colour. When the feed that picks the item is gone the key
stays up, faded, and the tile's dot says so rather than pretending to be
current.
Keys are written as notes wherever the module shows one: Planning Center's
`Bb` and `F#m` read as B♭ and F♯m, on the Plan tile's item badge and in the
Song Key tile alike.
**Teams** shows the same plan's team and position assignments — each team
as a band of its people, with their photo (fetched through ProdDash, never
by the browser; initials when Planning Center has none) and a dot for
@@ -365,29 +412,47 @@ below. Nothing is installed without someone clicking.
has signed up for are hidden until you ask for them — that list comes from
the service type, since Planning Center only returns a team once somebody
is on it.
- **Slack** — live transcripts of this location's Slack channels, plus
PIN-protected sending as the location. The + picker lists one transcript
tile per configured channel, titled `#channel`, and two send surfaces (one
of each per dashboard): **Send message**, a free-text box with the admin's
quick emojis one press away, and **Quick replies**, a grid of preset
buttons. Both post to the channel of whichever transcript was clicked last
— its bottom edge lights up in the accent color — and to the first
configured channel until one is clicked. Messages arrive with avatars,
names and times, Slack's inline formatting and the workspace's custom
emoji; a right-click on one opens the reaction menu, and text size and
jump-to-latest sit in the title bar. Nothing leaves the machine until the
PIN is entered: one PIN unlocks every Slack tile on that dashboard page
until the auto-lock idles out, a reload asks again, and the lock button on
a send tile's title bar ends it early.
Admin config is in four groups: **Slack account** (the location account's
- **Slack** — live transcripts of this location's Slack channels. The +
picker lists one transcript tile per configured channel, titled
`#channel`. Messages arrive with avatars, names and times, Slack's inline
formatting and the workspace's custom emoji; text size and jump-to-latest
sit in the title bar. Sending is the **Send Message** module's: a click
anywhere in a transcript points its tiles at that channel (the bottom
edge lights up in the accent color), and a message then leaves through
this module's one Slack connection, as the location. A right-click on a
message opens the reaction menu, which rides on the same unlock — with
the page locked, or no Send message tile on it, it says so instead of
reacting. This module has no PIN, send tile or quick replies of its own.
Admin config is in three groups: **Slack account** (the location account's
User OAuth Token — `xoxp-…`, so messages are literally from the campus —
or a bot token plus "Send as"), **Channels** (the joined channels to
follow, one transcript tile each), **Transcript** (refresh interval,
messages kept, thread replies) and **Sending** (the switch on the group's
title row, a 4–8 digit PIN, auto-lock minutes, quick replies one per line
as `Label | Message` — add `| #channel` to bind one to a channel — and up
to eight quick emojis).
follow, one transcript tile and one Send Message destination each) and
**Transcript** (refresh interval, messages kept, thread replies).
Tile settings: avatars, timestamps, names and channel notices.
- **Send Message** — the one place a dashboard sends from, whatever the
platform. Two tiles, one of each per dashboard: **Send message**, a
free-text box with the admin's quick emojis one press away, and **Quick
replies**, a grid of preset buttons. Both go wherever the operator last
pointed them with a click on a Slack or ProdCom transcript. A platform
whose destinations are identities rather than recipients — ProdCom, where
typed text goes out *as* a channel — also gets a **Send as** menu in the
title bar listing those identities; the menu exists only while such a
platform is installed, and Slack's channels are never in it. The choice is
saved with the tile, so a named layout remembers it; the transcript it
points at carries the accent stripe. The module
owns no connection of its own — it finds every installed module that
offers messaging and hands the message to it over loopback — and it owns
the PIN: nothing leaves the machine until it is entered on one of its
tiles, one entry unlocks every messaging tile on that dashboard page
(Slack's reaction menu included) until the auto-lock idles out, a reload
asks again, and the lock button ends it early. The PIN pad takes taps, a
keyboard, or a phone's — tapping the dots raises it. The PIN can be
switched off for a booth that doesn't need one.
Admin config: **PIN** (the switch on the group's title row, 4–8 digits,
auto-lock minutes) and **Presets** (quick replies one per line as
`Label | Message` — add `| slack:#channel` or `| prodcom:Channel` to bind
one to a destination — and up to eight quick emojis).
Tile settings: quick emojis on the Send message tile.
- **Resi Cues** — how long until the next Resi cue point, for a campus
running video from another site. The tile is one number, as large as it
will go: the countdown to the next cue, its name above it, and the playhead
@@ -443,7 +508,8 @@ below. Nothing is installed without someone clicking.
reference for module authors.
To develop modules against mocks instead of real gear:
`node tools/prodcom-mock.js` (ProdCom on `127.0.0.1:24480`),
`node tools/prodcom-mock.js` (ProdCom on `127.0.0.1:24480`, including the
send route the Send Message module uses),
`node band-lineup-display/tmp/pp-mock.js 1599` (ProPresenter slides on
`127.0.0.1:1599`), `node tools/pp-timers-mock.js 1600` (ProPresenter
timers + timecode on `127.0.0.1:1600`), `node tools/pco-mock.js`
+193 -12
View File
@@ -28,7 +28,10 @@ people running the booth depend on them.
ProdDash. If your feature needs a listener, a decoder or a worker, your
server entry owns it: start it in `init()`, stop it in `stop()`, report
it in `health()`. A child process the module itself spawns and supervises
is fine; a program someone launches by hand is not.
is fine; a program someone launches by hand is not. **A native helper —
anything that is not JavaScript — ships prebuilt inside the module folder,
for Apple silicon macOS and 64-bit Windows; nothing is ever compiled on
the machine running ProdDash** (see "Native helpers" below).
4. **Declare the ProdDash version you need** (`"proddash": ">=1.1.0"` in the
manifest) and **bump your own `version`** whenever you change the module.
The admin page refuses to install a module whose requirement the running
@@ -83,19 +86,86 @@ modules/<id>/
├── module.json manifest (required)
├── client.js ES module, client entry (required)
├── server.js server entry (optional — only if you need server code)
├── bin/ native helpers, prebuilt per platform (only if you need one)
│ ├── <name>-macos-arm64
│ └── <name>-win-x64.exe
├── native/ their source and the script that builds every bin/ file
└── ... assets (css, images…) served statically at /modules/<id>/
```
**Installation is exactly this:** in the admin page, open **Available
modules** and press **Install** — the module is downloaded from the ProdDash
repo into the server's data directory (`<data dir>/modules/<id>/`) and starts
immediately. Developing locally? Drop the folder into `modules/` (bundled
with the checkout) or into the data directory's `modules/` and restart. No
shell code changes, ever. Modules bundled with a checkout and modules
installed from the admin page live side by side; when both have the same id
the newer version runs. **Uninstall** in the admin page removes an installed
module's files (a bundled one is hidden instead, since its folder belongs to
the app); its settings are kept for a later reinstall.
immediately. A packaged ProdDash — the macOS app, the Windows bundle — ships
with **no modules at all**: every one of them arrives this way, and the
shell's own update never brings one along, so what is in git is exactly what
runs on a booth. Developing locally? A git checkout runs whatever is in its
own `modules/` folder (the repo's copies, "bundled"), or drop a folder into
the data directory's `modules/` and restart. No shell code changes, ever. In
a checkout the two live side by side; when both have the same id the newer
version runs. **Uninstall** in the admin page removes an installed module's
files (in a checkout, the tree's copy is hidden instead, since that folder
belongs to the repo); its settings are kept for a later reinstall.
### Native helpers
Some features need a program JavaScript cannot be: reading an audio input,
decoding timecode, measuring sound. Rule 3 says the module owns that program;
this section says how it ships: **already built, for every platform it runs
on, inside the module folder.** The machine running ProdDash is a packaged
app or the Windows bundle plus modules from the admin page's catalog. It has
no compiler and never will — the catalog delivers exactly the folder that is
in the repo, so the binaries live in git next to the code.
- **Platforms.** Apple silicon macOS and 64-bit Windows are required. Intel
macOS is welcome but optional. One file per platform in `bin/`, named for
what it is:
| Platform | File |
| --- | --- |
| macOS, Apple silicon | `bin/<name>-macos-arm64` |
| Windows, 64-bit | `bin/<name>-win-x64.exe` |
| macOS, Intel (optional) | `bin/<name>-macos-x86_64` |
- **Pick it at runtime, and cope without it.** Choose by `process.platform`
and `process.arch`; when there is no file for this machine, the feature
says so — in `health()` and in the tile's `setStatus` — and everything else
in the module keeps working. Never try to build it, never look for a copy
elsewhere on the machine, never tell the operator to install anything.
```js
const HELPERS = {
darwin: { arm64: 'ltc-capture-macos-arm64', x64: 'ltc-capture-macos-x86_64' },
win32: { x64: 'ltc-capture-win-x64.exe' },
};
const name = HELPERS[process.platform]?.[process.arch];
const helper = name ? path.join(__dirname, 'bin', name) : '';
if (!helper || !fs.existsSync(helper)) {
// Timecode is off on this platform. Say it once, keep the clock running.
}
```
- **One contract, any language.** Every platform's binary speaks the same
command line and output format, so `server.js` has one code path. What is
behind it is your choice per platform — Swift against CoreAudio on macOS,
C#, C or Rust on Windows — the module does not care.
- **Source and build beside it.** Keep the source under `native/` with one
script that produces every `bin/` file from a checkout, so any binary can be
rebuilt from what is committed. A helper that cannot be rebuilt does not
ship.
- **Bump the module version whenever a binary changes**, like any other
file — that is how installs learn about it.
- **Keep them lean.** Optimised builds, no debug symbols, a few megabytes at
most: the catalog fetches the whole repo as one archive, capped at 80 MB.
- **Signing.** Apple silicon refuses unsigned code, so sign the macOS binary
— Developer ID when you have it, ad-hoc at least. Windows needs nothing:
files the app writes carry no download mark, so SmartScreen never sees
them. Permissions come from the launcher (see "Permissions macOS has to
grant"), not from the binary.
A helper that ends up existing for one platform only is an exception made
on purpose, not a default: say so in the module's README and in the health
line, so a Windows booth knows why the feature is off.
## module.json
@@ -132,7 +202,7 @@ the app); its settings are kept for a later reinstall.
| `proddash` | yes | The ProdDash versions this module works with: `">=1.1.0"`, `"^1.1.0"`, `">=1.1.0 <2.0.0"`, or `"*"`. A module whose requirement the running shell doesn't meet is listed in the admin page but never loaded, and can't be installed from the catalog. |
| `description` | no | Shown in the admin page / picker. |
| `permissions` | no | What macOS must allow before this module can work — see **Permissions macOS has to grant**. Ignored by the shell; read by the macOS launcher. |
| `provides` | no | Capabilities other modules can consume — `["timers"]` today. Forwarded in `/api/modules` so a consumer can find you. See **Working with other modules**. |
| `provides` | no | Capabilities other modules can consume — `["timers"]`, `["messaging"]`. Forwarded in `/api/modules` so a consumer can find you. See **Working with other modules**. |
| `client` | yes | Client entry file, loaded as an ES module. |
| `server` | no | Server entry file (CommonJS), loaded with `require()`. |
| `style` | no | A stylesheet the shell injects once per module. |
@@ -391,7 +461,8 @@ const menu = moduleApi.header.addMenu({
build(menuEl) {
// called on every open with an emptied menu element — fill it with
// buttons (give them your scoped classes; the container is styled and
// fixed-positioned by the shell, so the tile's overflow can't clip it)
// positioned by the shell, hosted on the body under an element carrying
// your data-module, so your scoped CSS applies and nothing clips it)
},
});
menu.setLabel('Channels (2/4) ▾'); // update the button text any time
@@ -699,6 +770,108 @@ comment every 15 s); the consumer uses the stream when it exists and polls
wall — the Timers module lets them hide any of them per tile, but every entry
you add is a decision someone has to make.
### Offering messaging to the Send Message module
The Send Message module is the one place a dashboard sends from — a
PIN-gated compose box and a grid of quick replies — whatever the platform.
It owns nothing upstream: a module that *can* deliver a message (Slack posts
to a channel, ProdCom puts typed text on a comms channel) offers that over
its own routes, keeps its one upstream connection, and the Send Message
module hands messages to it over loopback. A provider has no PIN, no send
tile and no quick replies of its own; the shell's Add-tile picker shows the
Send message and Quick replies tiles once, under Send Message.
A module offers messaging by:
1. Declaring it — `"provides": ["messaging"]` in `module.json`. The Send
Message module re-reads `/api/modules` every 30 s, so a provider installed
mid-session shows up without a restart.
2. Serving `GET /messaging` — what it can send to, from state it already
holds (it is polled every few seconds while a send tile is open):
```json
{
"label": "Slack",
"identity": "Apollo Beach",
"destinationRole": "recipient",
"status": { "state": "ok", "message": "Apollo Beach · #production, #ops" },
"destinations": [
{ "id": "C01ABC", "label": "#production" },
{ "id": "C02DEF", "label": "#ops", "color": "#5c9de0" }
],
"emptyMessage": "",
"maxChars": 4000
}
```
| Field | Meaning |
| --- | --- |
| `label` | The platform's name, as the sending line and the Send as menu show it. |
| `identity` | Who a message appears to come from when that is fixed by the connection, or `''`. Shown as "as Apollo Beach". |
| `destinationRole` | What a destination *is*. `recipient` (the default): a message goes **to** it — a Slack channel — and the operator picks one by clicking its transcript tile, so it never appears in the Send as menu. `identity`: a message goes out **as** it — a ProdCom channel — and the Send as menu lists them; the tiles then say "Send message to ProdCom as FOH" and "Sent to ProdCom as FOH". The menu exists only while some installed platform offers identities. |
| `status` | `ok`, `connecting` or `error` plus one line — the same thing your `health()` says. A provider in error is still listed, so the operator sees why a send will fail before trying. |
| `destinations` | Where a message can go, or who it can go out as: a stable `id` (what `/messaging/send` receives), a `label`, and an optional `color`. Offer only what will work — ProdCom lists just the channels that accept typed text. Order is the order the menu shows. |
| `emptyMessage` | Optional: why the list is empty, when you know ("No ProdCom channel accepts typed text — turn on typing for one in ProdCom"). The tiles show it in place of a destination. |
| `maxChars` | The longest text you accept; the Send Message module refuses longer ones before asking you. |
3. Serving `POST /messaging/send` — `{ "destination": "<id>", "text": "…" }`
with the browser's unlock token as `Authorization: Bearer …`. **Check the
token before touching your upstream**: the Send Message module owns the
PIN, so ask it — `GET http://127.0.0.1:${shell.port}/api/modules/send-message/verify`
with the same `Authorization` header answers `200 { ok: true, expiresAt }`
or `401`. A `404` means no Send Message module is installed or enabled:
refuse with a sentence that says so. Without this check, any browser on
the network could post as the location by calling your route directly.
Answer `200 { "ok": true, "label": "#ops" }` when it landed, otherwise
`{ "error": "<one sentence a tech can act on>", "code": "…" }` with `400`
(bad destination or text), `401` (the token was refused), `429` (your
upstream is rate-limiting) or `502` (your upstream failed). Validate the
destination against your own list — never pass an arbitrary id upstream.
The same verification gates any other outbound action a module offers from
its tiles — the Slack transcript's emoji reactions ride on it — so a module
never needs a PIN of its own: one unlock serves every messaging tile on the
page. The `slack` and `prodcom-transcript` modules are the reference
implementations (`verifyUnlock()` in either server entry is the whole check).
### Messaging on the page
Where the next message goes is a fact about the whole dashboard, not one
tile: the Send message tile, the Quick replies tile and every transcript on
the page must agree, and they belong to different modules. Modules don't
import each other, so the agreement lives on `window` — one plain object plus
`CustomEvent`s on `window`, created by whichever messaging-aware tile mounts
first:
```js
window.proddashMessaging = {
version: 1,
target: { provider: '', destination: '', providerLabel: '', destinationLabel: '', identity: '' },
unlock: { token: '', expiresAt: 0, reason: '' },
quickEmojis: [], // the Send Message module's admin list, plain strings
transcripts: new Map(), // instanceId → { provider, destination }
senders: new Set(), // instanceIds of Send message / Quick replies tiles
};
```
Events, all named `proddash:messaging:<name>` with the payload in `detail`:
| Event | Who sends it | Meaning |
| --- | --- | --- |
| `select` | a transcript tile, or a Send as menu | `{ provider, destination }` — the operator pointed the senders here. A tile bound to one recipient (a Slack channel transcript) names it; one that shows a whole platform (ProdCom) sends `destination: ''` and the Send Message tile keeps the identity it has chosen for that platform. |
| `target` | the Send Message tiles | `window.proddashMessaging.target` changed: where the next message goes, resolved. A transcript compares `provider` (and `destination`, when it has one) and lights its bottom edge. |
| `unlock` | the Send Message tiles; a provider's tile on a `401` | `window.proddashMessaging.unlock` changed. Read the token from the object, never cache it; `''` means locked, with `reason` saying why. |
| `transcripts` | transcript tiles | the `transcripts` map changed (a tile mounted, unmounted or learned its channel). Register once you know your destination; unregister in `stop()`. This is how a dashboard with one transcript sends there by default. |
| `senders` | the Send Message tiles | the `senders` set changed — a transcript's locked note can say "add a Send message tile" rather than "enter the PIN". |
A transcript tile needs only three things: emit `select` on a click in its
body, register in `transcripts`, and toggle a target class on `target`. A
tile that performs a gated action itself (a reaction) reads
`window.proddashMessaging.unlock.token` and sends it as the Bearer token to
its own module's route. The Send Message tiles save the chosen platform and
per-platform destination in their instance settings, so a named layout
remembers them; the page object is the live copy.
## Complete minimal example
A working clock — copy-paste this as your starter. (A slightly fancier
@@ -792,8 +965,16 @@ client-side failures (a tile that fails to start says so in the tile).
**Mock upstreams** (so you can develop without the real gear):
- ProdCom: `node tools/prodcom-mock.js` (port 24480) — channels, groups,
history, and a live stream with in-progress speech. Point the
transcript module's ProdCom URL at `http://127.0.0.1:24480`.
history, a live stream with in-progress speech, and
`POST /api/v1/channels/{id}/send`, which lands typed text in the channel
as a `source: "typed"` entry (so a send from the Send Message module can
be watched arriving; a text containing `!429` answers RATE_LIMITED, and
`PRODCOM_MOCK_KEY=…` makes it demand that API key). Point the transcript
module's ProdCom endpoint at `127.0.0.1`, port `24480`.
- Send Message: no mock — it talks to the installed modules. Run the Slack
and ProdCom mocks, set a PIN under Send Message in `/admin` (or switch the
PIN off), add a transcript or two plus Send message and Quick replies from
+, and watch a send arrive in the transcript you clicked.
- ProPresenter: `node band-lineup-display/tmp/pp-mock.js 1599` — playlists
and an advancing slide index (including the arrangement-repeat case).
Point the Now/Next module at host `127.0.0.1`, port `1599`.
+5 -3
View File
@@ -51,6 +51,7 @@ the cycle rather than spinning forever.
```bash
./build.sh # build/ProdDash.app — the whole application
./build.sh --dmg # …and build/ProdDash-<version>-arm64.dmg
ARCH=x86_64 ./build.sh --dmg # the same for Intel Macs (…-x86_64.dmg)
./build.sh --install # …and copy it to /Applications
./build.sh --run # …and open it
./build.sh --notarize # with --dmg: notarise and staple (Developer ID)
@@ -68,9 +69,10 @@ Builds for **Apple Silicon**. To change that, or to move to a newer Node, edit
against nodejs.org's published checksums either way.
The app icon is built from `public/icons/icon-512.png`, so ProdDash's own icon
is the app's icon. A module's native helper is compiled during the build
(`<name>.swift` beside a module's files becomes `<name>`), so the Mac running
ProdDash never needs a compiler.
is the app's icon. The app carries no modules: they are installed from the
admin page's catalog into the data directory, and a module's native helper
ships prebuilt inside it (see the module guide), so the Mac running ProdDash
never needs a compiler.
## Signing
+15 -25
View File
@@ -1,6 +1,8 @@
#!/bin/zsh
# Build ProdDash.app — the whole application: launcher, server and its own
# Node runtime, with nothing to install first.
# Node runtime, with nothing to install first. It carries no modules: those
# come from the admin page's catalog into the data directory, and a module's
# native helper ships prebuilt inside it (docs/MODULE-GUIDE.md).
#
# ./build.sh build/ProdDash.app, self-contained
# ./build.sh --dmg …and build/ProdDash-<version>-arm64.dmg
@@ -11,6 +13,8 @@
# ./build.sh --dev launcher only — no Node, no server payload, so
# it runs against the checkout. Seconds, not
# minutes, while working on the launcher itself.
# ARCH=x86_64 ./build.sh the same for Intel Macs (default: arm64, Apple
# silicon); the Node it embeds follows.
#
# Signing: a "Developer ID Application" certificate is used when one is
# installed (override with CODESIGN_IDENTITY). Without one the app is signed
@@ -27,8 +31,13 @@ LAUNCHER_VERSION="1.0.0"
# The Node the app ships. Bump it here; the download is checksum-verified
# against nodejs.org's own SHASUMS256.txt and cached in .cache/.
NODE_VERSION="v24.21.0"
ARCH="arm64"
ARCH="${ARCH:-arm64}" # arm64 (Apple silicon) or x86_64 (Intel)
DEPLOYMENT_TARGET="13.0"
case "$ARCH" in
arm64) NODE_ARCH="arm64" ;;
x86_64) NODE_ARCH="x64" ;; # nodejs.org's name for it
*) echo "build.sh: ARCH must be arm64 or x86_64, not $ARCH" >&2; exit 2 ;;
esac
REPO_ROOT="../.."
OUT_DIR="build"
@@ -106,7 +115,7 @@ fi
# ── the server, and the Node that runs it ────────────────────────────────
if [[ $DEV -eq 0 ]]; then
TARBALL="node-$NODE_VERSION-darwin-$ARCH.tar.gz"
TARBALL="node-$NODE_VERSION-darwin-$NODE_ARCH.tar.gz"
mkdir -p "$CACHE_DIR"
if [[ ! -f "$CACHE_DIR/$TARBALL" ]]; then
echo " fetching Node $NODE_VERSION (~50 MB, cached for next time)"
@@ -125,25 +134,16 @@ if [[ $DEV -eq 0 ]]; then
echo " embedding Node $NODE_VERSION"
mkdir -p "$CONTENTS/Resources/node/bin"
tar -xzf "$CACHE_DIR/$TARBALL" -C "$CONTENTS/Resources/node/bin" --strip-components 2 \
"node-$NODE_VERSION-darwin-$ARCH/bin/node"
"node-$NODE_VERSION-darwin-$NODE_ARCH/bin/node"
echo " embedding ProdDash $VERSION"
echo " embedding ProdDash $VERSION (no modules — the catalog installs them)"
mkdir -p "$PAYLOAD/config"
cp "$REPO_ROOT/server.js" "$REPO_ROOT/package.json" "$PAYLOAD/"
cp -R "$REPO_ROOT/public" "$REPO_ROOT/modules" "$PAYLOAD/"
cp -R "$REPO_ROOT/public" "$PAYLOAD/"
# Only the checked-in defaults: config/ also holds this machine's own
# modules.json and layouts when ProdDash has ever run from the checkout.
cp "$REPO_ROOT/config/proddash.json" "$PAYLOAD/config/"
find "$PAYLOAD" -name '.DS_Store' -delete
# A module's native helper is built here, so the Mac running ProdDash needs
# no compiler: <name>.swift beside a module's files becomes <name>.
for source in "$PAYLOAD"/modules/*/*.swift; do
[[ -e "$source" ]] || continue
helper="${source%.swift}"
echo " compiling $(basename "$(dirname "$source")")/$(basename "$helper")"
swiftc -O -target "$ARCH-apple-macos$DEPLOYMENT_TARGET" -o "$helper" "$source"
done
fi
# ── signing ──────────────────────────────────────────────────────────────
@@ -165,16 +165,6 @@ fi
if [[ -f "$CONTENTS/Resources/node/bin/node" ]]; then
codesign "${SIGN[@]}" --entitlements Resources/node.entitlements "$CONTENTS/Resources/node/bin/node"
fi
if [[ $DEV -eq 0 ]]; then
for helper in "$PAYLOAD"/modules/*/*; do
# A compiled helper is the extensionless executable beside a module's
# sources — test the name, not the path, which has dots all over it.
name=$(basename "$helper")
[[ -f "$helper" && -x "$helper" && "$name" != *.* ]] || continue
echo " signing $name"
codesign "${SIGN[@]}" --entitlements Resources/helper.entitlements "$helper"
done
fi
codesign "${SIGN[@]}" --entitlements Resources/ProdDash.entitlements --identifier "$BUNDLE_ID" "$APP"
codesign --verify --deep --strict "$APP" && echo " signature verifies"
+121
View File
@@ -0,0 +1,121 @@
#!/bin/zsh
# Build the Windows bundle — ProdDash-<version>-win-x64.zip: the dashboard,
# its own Node runtime and a start script, so nothing has to be installed on
# the Windows machine. Unzip, double-click ProdDash.bat, done. It carries no
# modules: those come from the admin page's catalog into %APPDATA%\ProdDash.
#
# ./build.sh build/ProdDash-<version>-win-x64.zip
#
# Builds on macOS or Linux (zsh, curl, shasum, unzip, zip). Node for Windows
# comes from nodejs.org, checksum-verified against its SHASUMS256.txt and
# cached in .cache/. There is no Windows launcher app yet: ProdDash.bat keeps
# the server running and starts it again when the admin page applies an
# update (the server exits with code 75 to ask for that).
set -e -u
cd "$(dirname "$0")"
APP_NAME="ProdDash"
# The Node the bundle ships — keep in step with launcher/macos/build.sh.
NODE_VERSION="v24.21.0"
NODE_DIST="node-$NODE_VERSION-win-x64"
REPO_ROOT="../.."
OUT_DIR="build"
CACHE_DIR=".cache"
for tool in curl shasum unzip zip; do
command -v "$tool" >/dev/null || { echo "build.sh: $tool not found" >&2; exit 1; }
done
VERSION=$(sed -n 's/.*"version" *: *"\([^"]*\)".*/\1/p' "$REPO_ROOT/package.json" | head -1)
[[ -n "$VERSION" ]] || { echo "build.sh: can't read the version from package.json" >&2; exit 1; }
NAME="$APP_NAME-$VERSION-win-x64"
STAGE="$OUT_DIR/$NAME"
echo "ProdDash $VERSION — building the Windows bundle"
rm -rf "$OUT_DIR"
mkdir -p "$STAGE/node" "$STAGE/config" "$CACHE_DIR"
# ── Node for Windows ─────────────────────────────────────────────────────
ZIPFILE="$NODE_DIST.zip"
if [[ ! -f "$CACHE_DIR/$ZIPFILE" ]]; then
echo " fetching Node $NODE_VERSION for Windows (~30 MB, cached for next time)"
curl -fsSL --retry 3 -o "$CACHE_DIR/$ZIPFILE.part" "https://nodejs.org/dist/$NODE_VERSION/$ZIPFILE"
mv "$CACHE_DIR/$ZIPFILE.part" "$CACHE_DIR/$ZIPFILE"
fi
SUMS="$CACHE_DIR/SHASUMS256-$NODE_VERSION.txt"
[[ -f "$SUMS" ]] || curl -fsSL --retry 3 -o "$SUMS" "https://nodejs.org/dist/$NODE_VERSION/SHASUMS256.txt"
# This binary ships under ProdDash's name — check it every build.
WANT=$(awk -v f="$ZIPFILE" '$2 == f {print $1}' "$SUMS")
GOT=$(shasum -a 256 "$CACHE_DIR/$ZIPFILE" | awk '{print $1}')
if [[ -z "$WANT" || "$WANT" != "$GOT" ]]; then
echo "build.sh: $ZIPFILE does not match nodejs.org's checksum — refusing to ship it" >&2
exit 1
fi
echo " embedding Node $NODE_VERSION (node.exe and its licence)"
unzip -q -j "$CACHE_DIR/$ZIPFILE" "$NODE_DIST/node.exe" "$NODE_DIST/LICENSE" -d "$STAGE/node"
# ── ProdDash ─────────────────────────────────────────────────────────────
echo " embedding ProdDash $VERSION (no modules — the catalog installs them)"
cp "$REPO_ROOT/server.js" "$REPO_ROOT/package.json" "$STAGE/"
cp -R "$REPO_ROOT/public" "$STAGE/"
# Only the checked-in defaults: config/ also holds this machine's own
# modules.json and layouts when ProdDash has ever run from the checkout.
cp "$REPO_ROOT/config/proddash.json" "$STAGE/config/"
find "$STAGE" -name '.DS_Store' -delete
# ── the start script and the read-me, with Windows line endings ──────────
crlf() { awk '{ printf "%s\r\n", $0 }' > "$1"; }
crlf "$STAGE/ProdDash.bat" <<'BAT'
@echo off
rem ProdDash - double-click to start. Keep this window open: closing it stops the dashboard.
title ProdDash
cd /d "%~dp0"
rem The server exits with code 75 after applying an update from the admin page; start it again.
set PRODDASH_LAUNCHER=1
:run
"%~dp0node\node.exe" server.js
set CODE=%ERRORLEVEL%
if %CODE% EQU 75 goto run
echo.
echo ProdDash stopped (exit code %CODE%). Press any key to close this window.
pause >nul
BAT
crlf "$STAGE/README.txt" <<README
ProdDash $VERSION for Windows (64-bit)
=======================================
Nothing to install. This folder holds the dashboard and its own copy of Node.
1. Move this folder somewhere you can write to, for example C:\ProdDash
(not Program Files: updates write into this folder).
2. Double-click ProdDash.bat. A window opens and stays open while the
dashboard runs; closing it stops the dashboard.
- If Windows warns about the file, choose More info, then Run anyway.
- When Windows Defender Firewall asks about node.exe, allow it on
private networks so other screens can reach the dashboard.
3. Open http://localhost:24500 on this PC. Other devices on the network use
http://<this PC's IP address>:24500. Settings are on the admin page,
http://localhost:24500/admin.
4. The bundle ships without modules. On the admin page, tick the ones this
PC needs under Available modules and press Install selected; each one
updates on its own from then on.
Your settings and layouts live in %APPDATA%\ProdDash, not in this folder,
so unzipping a new version or updating never loses them.
Start with Windows: press Win+R, type shell:startup, press Enter, and put a
shortcut to ProdDash.bat in the folder that opens.
Updates: the admin page's Update now fetches the new version into this
folder and restarts the dashboard; the window stays open. A copy of the
version it replaced is kept for a short while in case the new one will not
start.
README
# ── zip ──────────────────────────────────────────────────────────────────
echo " zipping"
(cd "$OUT_DIR" && zip -q -r -X "$NAME.zip" "$NAME")
echo "built $OUT_DIR/$NAME.zip ($(du -sh "$OUT_DIR/$NAME.zip" | awk '{print $1}'))"
+9 -5
View File
@@ -1,8 +1,8 @@
/* PCO Plan — client part.
The module presents two tiles and this is the entry for both: the Teams
tile (picker entry "teams") is built by teams-client.js, everything below
draws the Plan tile.
The module presents three tiles and this is the entry for all of them: the
Teams tile (picker entry "teams") is built by teams-client.js and the Song
Key tile ("key") by key-client.js; everything below draws the Plan tile.
The server part reads Planning Center and (optionally) follows the
ProPresenter module's live item; this tile only renders the plan it is
@@ -13,6 +13,8 @@
the connection settings. */
import createTeams from "./teams-client.js";
import createKey from "./key-client.js";
import { prettyKey } from "./key-notation.js";
const REFRESH_SVG = '<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-2.64-6.36"/><path d="M21 3v6h-6"/></svg>';
@@ -21,8 +23,9 @@ const MINUS_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" st
const PLUS_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"/></svg>';
export default function create({ root, moduleApi }) {
// Tiles added as "Teams" carry that variant and have their own settings.
// Each picker entry carries its variant and its own settings.
if (moduleApi.variant === "teams") return createTeams({ root, moduleApi });
if (moduleApi.variant === "key") return createKey({ root, moduleApi });
return createPlan({ root, moduleApi });
}
@@ -367,7 +370,8 @@ function createPlan({ root, moduleApi }) {
if (on('showKey') && item.keyName) {
const key = document.createElement('span');
key.className = 'pp-key';
key.textContent = item.keyName;
// B♭, F♯m — the same notation the Song Key tile uses.
key.textContent = prettyKey(item.keyName);
titleLine.appendChild(key);
}
if (on('showNowIndicator')) {
+181
View File
@@ -0,0 +1,181 @@
/* PCO Plan — the Song Key tile.
One thing, big: the key of the plan item on screen. It reads the same
streamed state the Plan tile does, so it needs no connection of its own;
which item is current comes from the ProPresenter module, as ever. */
import { parseKey, prettyKey } from "./key-notation.js";
export default function createKey({ root, moduleApi }) {
let state = null;
let stream = null;
let feedOffline = false;
root.innerHTML = `
<div class="pk-wrap">
<div class="pk-key"></div>
<div class="pk-name"></div>
<div class="pk-next"></div>
</div>`;
const wrap = root.querySelector('.pk-wrap');
const keyEl = root.querySelector('.pk-key');
const nameEl = root.querySelector('.pk-name');
const nextEl = root.querySelector('.pk-next');
const cfg = () => moduleApi.instanceSettings || {};
const on = (key) => cfg()[key] !== false; // unset = shown
/* ── the item on screen, and the one after it ───────────────────── */
function items() {
return Array.isArray(state?.items) ? state.items : [];
}
function currentItem() {
const id = state?.live?.following ? state.live.currentItemId : '';
return id ? items().find((it) => it.id === id) || null : null;
}
/** The next item that actually has a key — a talk between two songs is skipped. */
function nextKeyed(after) {
const list = items();
const from = after ? list.findIndex((it) => it.id === after.id) + 1 : 0;
if (from <= 0) return null;
for (let i = from; i < list.length; i += 1) {
if (list[i].keyName) return list[i];
}
return null;
}
function titleOf(item) {
return item ? (item.song?.title || item.title || '') : '';
}
/* ── render ─────────────────────────────────────────────────────── */
function renderStatus() {
if (feedOffline) return moduleApi.setStatus('error', 'ProdDash server unreachable — reconnecting…');
if (!state) return moduleApi.setStatus('connecting', 'Connecting…');
if (!state.configured) return moduleApi.setStatus('error', 'No Planning Center credentials — add them in Admin');
if (!state.serviceTypeSet) return moduleApi.setStatus('error', 'No service type selected — pick one in Admin');
if (!state.reachable) {
return moduleApi.setStatus(state.lastFetched ? 'error' : 'connecting', state.lastError || 'Reading the plan…');
}
const item = currentItem();
if (!state.live?.following) return moduleApi.setStatus('ok', 'Not following ProPresenter — no item is current');
// The key on screen stays — the band still needs it — but a tile must
// never look confidently live while the feed that chose it is gone.
if (!state.live.available) {
return moduleApi.setStatus('error', `${state.live.reason || 'ProPresenter feed unavailable'} — showing the last item`);
}
if (!state.live.ppReachable) return moduleApi.setStatus('error', 'ProPresenter unreachable — showing the last item');
if (!item) return moduleApi.setStatus('ok', 'Waiting for an item to go live');
moduleApi.setStatus('ok', `${titleOf(item)}${item.keyName ? ` — ${prettyKey(item.keyName)}` : ' — no key in the plan'}`);
}
/**
* A key is a note, so it is worth setting properly: "Bb" and "F#m" read
* better with the accidental raised and the minor kept small.
*/
function drawKey(text) {
keyEl.innerHTML = '';
const parts = parseKey(text);
if (!parts) {
keyEl.textContent = text;
return;
}
keyEl.appendChild(document.createTextNode(parts.note));
if (parts.accidental) {
const acc = document.createElement('span');
acc.className = 'pk-accidental';
acc.textContent = parts.accidental;
keyEl.appendChild(acc);
}
if (parts.quality) {
const tail = document.createElement('span');
tail.className = 'pk-quality';
tail.textContent = parts.quality;
keyEl.appendChild(tail);
}
}
function render() {
wrap.classList.toggle('is-offline', feedOffline);
const live = state?.live;
wrap.classList.toggle('is-stale', Boolean(live?.following && (!live.available || !live.ppReachable)));
const color = String(cfg().keyColor || '').trim();
wrap.style.setProperty('--pk-color', /^[#a-zA-Z0-9(),.%\s-]+$/.test(color) && color ? color : '#4ea1ff');
renderStatus();
const item = currentItem();
const key = item?.keyName || '';
wrap.classList.toggle('has-key', Boolean(key));
if (!state || !state.configured || !state.serviceTypeSet) {
drawKey('—');
nameEl.textContent = state ? 'Set up PCO Plan in Admin' : 'Connecting…';
nextEl.textContent = '';
return;
}
if (!item) {
drawKey('—');
nameEl.textContent = state.live?.following ? 'Nothing live' : 'Not following ProPresenter';
nextEl.textContent = '';
return;
}
drawKey(key || '—');
nameEl.textContent = on('showSongName') ? titleOf(item) : '';
nameEl.hidden = !nameEl.textContent;
const next = on('showNextKey') ? nextKeyed(item) : null;
nextEl.textContent = next ? `Next: ${prettyKey(next.keyName)} · ${titleOf(next)}` : '';
nextEl.hidden = !nextEl.textContent;
}
/* ── live feed ──────────────────────────────────────────────────── */
function accept(payload) {
if (!payload || typeof payload !== 'object' || !payload.state) return;
state = payload.state;
feedOffline = false;
render();
}
function connect() {
stream = moduleApi.sse('/stream', {
open() { feedOffline = false; render(); },
error() { feedOffline = true; render(); },
events: {
state(ev) {
try {
accept(JSON.parse(ev.data));
} catch { /* a bad frame is not fatal */ }
},
},
});
}
/* ── lifecycle ──────────────────────────────────────────────────── */
return {
start() {
moduleApi.setStatus('connecting', 'Connecting…');
moduleApi.fetch('/state')
.then((res) => (res.ok ? res.json() : null))
.then((body) => { if (body && !state) accept(body); })
.catch(() => { /* the stream will cover it */ });
connect();
render();
},
stop() {
stream?.close();
stream = null;
root.innerHTML = '';
},
onConfigChange() {
// Admin holds the connection only; the server re-inits and re-sends.
},
};
}
+25
View File
@@ -0,0 +1,25 @@
/* PCO Plan — how a song key is written.
Planning Center stores keys as typed: "Bb", "F#m", "Ab". Every tile in this
module shows them as notes instead — B♭, F♯m, A♭ — so the plan, the badge
on an item and the Song Key tile all agree. Shared rather than repeated
because the day one of them changes, they all should. */
/** "F#m" → { note: 'F', accidental: '♯', quality: 'm' }; anything odd → null. */
export function parseKey(raw) {
const match = /^([A-G])\s*([#b♯♭]?)\s*(.*)$/.exec(String(raw || '').trim());
if (!match) return null;
const [, note, accidental, quality] = match;
return {
note,
accidental: accidental === '#' ? '♯' : accidental === 'b' ? '♭' : accidental,
quality: quality.trim(),
};
}
/** The same thing as one string, for a badge or a caption. */
export function prettyKey(raw) {
const parts = parseKey(raw);
if (!parts) return String(raw || '').trim();
return `${parts.note}${parts.accidental}${parts.quality}`;
}
+32 -2
View File
@@ -1,9 +1,9 @@
{
"id": "pco-plan",
"name": "PCO Plan",
"version": "1.8.0",
"version": "1.9.0",
"proddash": ">=1.4.0",
"description": "Order of service and team assignments from Planning Center Services",
"description": "Order of service, team assignments and the song key from Planning Center Services",
"provides": [
"timers"
],
@@ -621,6 +621,36 @@
"columns": 2
}
}
},
{
"id": "key",
"name": "Song Key",
"description": "The key of the item on screen, big",
"defaultSize": {
"w": 2,
"h": 2
},
"minSize": {
"w": 1,
"h": 1
},
"instanceSchema": {
"keyColor": {
"type": "color",
"label": "Key",
"default": "#4ea1ff"
},
"showSongName": {
"type": "boolean",
"label": "Song name",
"default": true
},
"showNextKey": {
"type": "boolean",
"label": "Next key",
"default": true
}
}
}
]
}
+94 -7
View File
@@ -206,7 +206,9 @@
[data-module="pco-plan"] .pp-now-tag {
display: none;
padding: 0.05em 0.45em;
/* Optically centred like the section chips: uppercase has no descenders,
so the capitals sat 0.59px low in the pill. */
padding: 0.018em 0.45em 0.082em;
border-radius: 999px;
background: var(--pp-current);
color: var(--bg);
@@ -635,25 +637,110 @@
[data-module="pco-plan"] .pp-abs-sec {
flex: none;
padding: 0.1em 0.5em;
border-radius: 999px;
border: 1px solid var(--border);
/* Uppercase text has no descenders, so the font's descent allowance below
the baseline leaves the caps sitting high in the box — measured at 0.9px
too much headroom. The padding is a touch shallower on top and deeper
below to centre the letters themselves; in em, so it holds at any text
size. */
padding: 0.095em 0.55em 0.185em;
/* The same rounded square, tinted ground and transparent border the AbleSet
module gives its own section pills, so the two read as one family. */
border-radius: 0.35em;
border: 1px solid transparent;
background: color-mix(in srgb, var(--text) 8%, var(--panel));
font-size: 0.72em;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
white-space: nowrap;
color: var(--muted);
transition: color 0.2s ease, border-color 0.2s ease;
transition: color 0.2s ease, border-color 0.2s ease, background 0.2s ease;
}
[data-module="pco-plan"] .pp-abs-sec.is-done { opacity: 0.45; }
/* The section now playing fills left to right as it goes, like the row. */
/* The section playing keeps its own ground and fills across it, so the
progress reads against the chip rather than against the row behind it. */
[data-module="pco-plan"] .pp-abs-sec.is-now {
color: var(--text);
border-color: color-mix(in srgb, var(--pp-current) 60%, transparent);
background:
linear-gradient(90deg,
color-mix(in srgb, var(--pp-current) 40%, transparent) var(--pp-sec-fill, 0%),
transparent var(--pp-sec-fill, 0%));
color-mix(in srgb, var(--pp-current) 45%, var(--panel)) var(--pp-sec-fill, 0%),
color-mix(in srgb, var(--text) 8%, var(--panel)) var(--pp-sec-fill, 0%));
}
/* ── the Song Key tile ────────────────────────────────────────────────
One value, as large as the tile allows. Sizes come from the tile itself
(container units), like the AbleSet module's single readouts, so a small
tile and a wall-sized one both read properly. */
[data-module="pco-plan"] .pk-wrap {
--pk-color: #4ea1ff;
position: absolute;
inset: 0;
container-type: size;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.2em;
padding: 4%;
text-align: center;
user-select: none;
}
[data-module="pco-plan"] .pk-key {
font-size: clamp(18px, 46cqmin, 260px);
font-weight: 800;
line-height: 1;
letter-spacing: -0.01em;
color: var(--muted);
white-space: nowrap;
}
[data-module="pco-plan"] .pk-wrap.has-key .pk-key { color: var(--pk-color); }
/* A key is a note, but it has to read as one word at a glance from the back
of a room: the accidental and the quality sit on the same line as the
letter, only smaller. Raising the accidental looked like two stacked
characters at tile sizes. */
[data-module="pco-plan"] .pk-accidental {
font-size: 0.68em;
margin-left: 0.01em;
}
[data-module="pco-plan"] .pk-quality {
font-size: 0.5em;
font-weight: 700;
margin-left: 0.05em;
opacity: 0.85;
}
[data-module="pco-plan"] .pk-name {
max-width: 100%;
font-size: clamp(9px, 9cqmin, 30px);
font-weight: 600;
line-height: 1.2;
color: var(--text);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
[data-module="pco-plan"] .pk-name[hidden] { display: none; }
[data-module="pco-plan"] .pk-next {
max-width: 100%;
font-size: clamp(8px, 6.5cqmin, 20px);
font-weight: 600;
color: var(--muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
[data-module="pco-plan"] .pk-next[hidden] { display: none; }
[data-module="pco-plan"] .pk-wrap.is-offline { opacity: 0.6; }
/* The feed that picks the item is gone: the key stays readable, but faded,
so nobody trusts it as current without looking at the status dot. */
[data-module="pco-plan"] .pk-wrap.is-stale .pk-key { opacity: 0.55; }
[data-module="pco-plan"] .pk-wrap.is-stale .pk-name,
[data-module="pco-plan"] .pk-wrap.is-stale .pk-next { opacity: 0.6; }
+171 -10
View File
@@ -5,7 +5,45 @@
(hidden channels, channel icons, timestamps, text size, flow direction)
persists in instance settings, and the data comes from the module's own
server, which keeps one connection to ProdCom for every dashboard: a
snapshot on connect (`state`), then each changed entry (`entry`). */
snapshot on connect (`state`), then each changed entry (`entry`).
Messaging: a click anywhere in the tile makes ProdCom the platform the
Send Message module's tiles send through (the channel the text goes out
*as* is picked in their Send as menu, among the channels ProdCom lets text
be typed onto); while it is, the tile's bottom edge carries the accent
stripe.
That is shared through the page bus below — see "Messaging on the page"
in docs/MODULE-GUIDE.md. Text typed from a dashboard comes back on the
stream as an entry with source "typed" and is drawn with a keyboard mark. */
/* ── the page bus (shared with the Send Message module) ───────────── */
const PROVIDER_ID = 'prodcom-transcript';
const BUS_EVENT = 'proddash:messaging:';
function messagingBus() {
if (!window.proddashMessaging) {
window.proddashMessaging = {
version: 1,
target: { provider: '', destination: '', providerLabel: '', destinationLabel: '', identity: '' },
unlock: { token: '', expiresAt: 0, reason: '' },
quickEmojis: [],
transcripts: new Map(),
senders: new Set(),
};
}
return window.proddashMessaging;
}
function emit(name, detail = {}) {
window.dispatchEvent(new CustomEvent(BUS_EVENT + name, { detail }));
}
function on(name, fn) {
const handler = (e) => fn(e.detail || {});
window.addEventListener(BUS_EVENT + name, handler);
return () => window.removeEventListener(BUS_EVENT + name, handler);
}
/* the text-size buttons: a drawn − and + at the icon size, like every other header icon */
const MINUS_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><path d="M5 12h14"/></svg>';
@@ -21,6 +59,8 @@ export default function create({ root, moduleApi }) {
let hiddenChannels = new Set(moduleApi.instanceSettings.hiddenChannels || []);
let stream = null; // moduleApi.sse handle
let stopped = false;
let lastStatus = null; // the link's last status, re-reported when the target changes
const bus = messagingBus();
/* ── DOM skeleton ───────────────────────────────────────────────── */
@@ -39,6 +79,26 @@ export default function create({ root, moduleApi }) {
const emptyEl = root.querySelector('.pt-empty');
const jumpBtn = root.querySelector('.pt-jump');
/* ── the send target: a click anywhere in the body points the senders here ── */
wrap.addEventListener('click', () => {
if (!channels.size) return; // nothing to send to yet
emit('select', { provider: PROVIDER_ID, destination: '' });
});
function isTarget() {
return bus.target.provider === PROVIDER_ID;
}
function paintTarget() {
if (stopped) return;
const on = isTarget();
if (on === wrap.classList.contains('is-target')) return;
wrap.classList.toggle('is-target', on);
if (lastStatus) applyStatus(lastStatus);
}
const offTarget = on('target', paintTarget);
/* ── title-bar controls ─────────────────────────────────────────── */
const CLOCK_SVG = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>';
@@ -81,8 +141,8 @@ export default function create({ root, moduleApi }) {
moduleApi.saveInstanceSettings({ textSize: Math.min(48, Math.max(10, current + delta)) });
applyInstanceSettings();
}
moduleApi.header.addButton({ icon: MINUS_SVG, title: 'Smaller text', onClick: () => bumpTextSize(-2) });
moduleApi.header.addButton({ icon: PLUS_SVG, title: 'Larger text', onClick: () => bumpTextSize(2) });
const minusBtn = moduleApi.header.addButton({ icon: MINUS_SVG, title: 'Smaller text', onClick: () => bumpTextSize(-2) });
const plusBtn = moduleApi.header.addButton({ icon: PLUS_SVG, title: 'Larger text', onClick: () => bumpTextSize(2) });
// icon and tooltip track the current direction — applyInstanceSettings sets both
const flowBtn = moduleApi.header.addButton({
@@ -95,7 +155,7 @@ export default function create({ root, moduleApi }) {
},
});
moduleApi.header.addButton({
const latestBtn = moduleApi.header.addButton({
icon: JUMP_SVG,
title: 'Latest',
onClick() {
@@ -112,6 +172,82 @@ export default function create({ root, moduleApi }) {
});
clearBtn.classList.add('pt-clear');
/* ── a narrow tile: the bar keeps Channels, the rest fold into ⋯ ──
Seven controls need ~175 px, and the shell clips whatever the bar
cannot fit — on a 3-column tile among many, or one squeezed by the
fullscreen fit, that used to take the channel filter with it. Below
COMPACT_PX the six secondary controls hide and a single ⋯ menu offers
the same actions, so the filter button is the last thing to go. */
const MORE_SVG = '<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><circle cx="5" cy="12" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="19" cy="12" r="2"/></svg>';
const COMPACT_PX = 380; // tile width below which the full bar no longer fits
let moreMenuEl = null;
const moreMenu = moduleApi.header.addMenu({
icon: MORE_SVG,
title: 'More',
build(menu) {
menu.classList.add('pt-menu');
moreMenuEl = menu;
rebuildMoreMenu();
},
});
const moreWrap = moreMenu.button.parentElement; // the shell's .tile-dd
const secondaryBtns = [timeBtn, minusBtn, plusBtn, flowBtn, latestBtn, clearBtn];
function addMoreItem(label, { on = null, onClick } = {}) {
const item = document.createElement('button');
item.className = 'pt-channel-item' + (on ? ' on' : '');
if (on !== null) {
item.setAttribute('role', 'menuitemcheckbox');
item.setAttribute('aria-checked', String(on));
} else {
item.setAttribute('role', 'menuitem');
}
const check = document.createElement('span');
check.className = 'check';
check.textContent = '✓';
const name = document.createElement('span');
name.className = 'name';
name.textContent = label;
item.append(check, name);
item.addEventListener('click', (e) => {
e.stopPropagation(); // the rebuild detaches this item — keep the menu open
onClick();
});
moreMenuEl.appendChild(item);
}
function rebuildMoreMenu() {
if (!moreMenuEl) return;
moreMenuEl.innerHTML = '';
const s = moduleApi.instanceSettings;
addMoreItem('Timestamps', { on: Boolean(s.showTimes), onClick: () => timeBtn.click() });
addMoreItem('Newest first', { on: newestFirst(), onClick: () => flowBtn.click() });
const divider = document.createElement('div');
divider.className = 'pt-menu-divider';
moreMenuEl.appendChild(divider);
addMoreItem('Smaller text', { onClick: () => bumpTextSize(-2) });
addMoreItem('Larger text', { onClick: () => bumpTextSize(2) });
addMoreItem('Latest', { onClick: () => { moreMenu.close(); latestBtn.click(); } });
addMoreItem('Clear', { onClick: () => { moreMenu.close(); clearView(); } });
}
let compact = null; // unknown until the first measurement
function applyCompact(width) {
const next = width > 0 && width < COMPACT_PX;
if (next === compact) return;
compact = next;
for (const btn of secondaryBtns) btn.hidden = compact;
moreWrap.hidden = !compact;
if (!compact) moreMenu.close();
}
// the tile's own body tells the width; onResize only knows grid cells
const sizeWatch = new ResizeObserver((entries) => {
applyCompact(entries[0]?.contentRect.width || root.clientWidth);
});
sizeWatch.observe(root);
applyCompact(root.clientWidth);
function applyInstanceSettings() {
const s = moduleApi.instanceSettings;
const size = Math.min(48, Math.max(10, Number(s.textSize) || 15));
@@ -126,6 +262,7 @@ export default function create({ root, moduleApi }) {
flowBtn.classList.toggle('active', up);
flowBtn.title = up ? 'Newest first' : 'Oldest first';
jumpBtn.textContent = (up ? '↑' : '↓') + ' New messages';
rebuildMoreMenu(); // its checkmarks mirror the buttons
}
applyInstanceSettings();
@@ -309,10 +446,18 @@ export default function create({ root, moduleApi }) {
const avatar = document.createElement('span');
avatar.className = 'avatar';
avatar.style.color = info.color;
avatar.innerHTML =
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">' +
'<circle cx="12" cy="8.5" r="3.2"/>' +
'<path d="M5.5 19c1.6-3.2 3.9-4.8 6.5-4.8s4.9 1.6 6.5 4.8"/></svg>';
// speech is a person; typed text (from a dashboard, or ProdCom's own
// box) a keyboard; an automation a bolt
avatar.innerHTML = entry.source === 'typed'
? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
'<rect x="3" y="7" width="18" height="11" rx="2"/><path d="M7 11h1M11 11h1M15 11h1M8 14.5h8"/></svg>'
: entry.source === 'automation'
? '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
'<path d="M13 3 5 14h6l-1 7 8-11h-6z"/></svg>'
: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true">' +
'<circle cx="12" cy="8.5" r="3.2"/>' +
'<path d="M5.5 19c1.6-3.2 3.9-4.8 6.5-4.8s4.9 1.6 6.5 4.8"/></svg>';
if (entry.source === 'typed' || entry.source === 'automation') el.classList.add(entry.source);
const ch = document.createElement('span');
ch.className = 'channel';
@@ -357,14 +502,27 @@ export default function create({ root, moduleApi }) {
function applyStatus(st) {
if (!st || typeof st !== 'object') return;
if (st.state === 'ok') moduleApi.setStatus('ok', st.message || 'Live');
else moduleApi.setStatus(st.state === 'error' ? 'error' : 'connecting', st.message || 'Connecting to ProdCom…');
lastStatus = st;
if (st.state === 'ok') {
// the Send Message tiles point here: typed text goes out as the chosen channel
const as = !isTarget() ? ''
: bus.target.destinationLabel ? ` · sends go out as ${bus.target.destinationLabel}`
: ' · selected — no channel accepts typed text';
moduleApi.setStatus('ok', (st.message || 'Live') + as);
} else moduleApi.setStatus(st.state === 'error' ? 'error' : 'connecting', st.message || 'Connecting to ProdCom…');
}
function applySnapshot(snap) {
if (!snap || typeof snap !== 'object') return;
channels.clear();
for (const ch of snap.channels || []) channels.set(String(ch.id), { name: ch.name, color: ch.color || '#8b98a5' });
// On the page and able to send: that is what lets the Send Message tiles
// pick ProdCom by default when it is the only transcript showing.
if (channels.size && !bus.transcripts.has(moduleApi.instanceId)) {
bus.transcripts.set(moduleApi.instanceId, { provider: PROVIDER_ID, destination: '' });
emit('transcripts', {});
}
wrap.classList.toggle('is-target', isTarget());
groups.clear();
for (const g of snap.groups || []) groups.set(String(g.id), { name: g.name, channelIds: g.channelIds || [] });
rebuildChannelMenu();
@@ -415,6 +573,9 @@ export default function create({ root, moduleApi }) {
},
stop() {
stopped = true;
sizeWatch.disconnect();
offTarget();
if (bus.transcripts.delete(moduleApi.instanceId)) emit('transcripts', {});
stream?.close();
root.innerHTML = ''; // header controls are removed by the shell
},
+7 -4
View File
@@ -1,15 +1,18 @@
{
"id": "prodcom-transcript",
"name": "ProdCom",
"version": "1.3.2",
"proddash": ">=1.1.0",
"description": "Live ProdCom transcript",
"version": "1.4.0",
"proddash": ">=1.4.0",
"description": "Live ProdCom transcript; typed text to a ProdCom channel through the Send Message module",
"permissions": [
{
"kind": "local-network",
"reason": "Reaching the ProdCom API on this network"
}
],
"provides": [
"messaging"
],
"client": "client.js",
"server": "server.js",
"style": "style.css",
@@ -29,7 +32,7 @@
"host": "",
"port": 24480
},
"help": "The ProdCom server at THIS location — every campus has its own. Blank until you set it, so a new install never reads another campus's comms."
"help": "The ProdCom server at THIS location — every campus has its own. Blank until you set it, so a new install never reads another campus’s comms. The Send Message module sends typed text to these channels through this connection."
},
"apiKey": {
"type": "password",
+217 -11
View File
@@ -11,19 +11,36 @@
* connections; ProdCom now sees one.)
*
* Routes (under /api/modules/prodcom-transcript):
* GET /state → { status, channels, groups, entries } (entries by date)
* GET /stream → SSE: `state` (the snapshot, first), then `entry` for each
* changed entry, `clear`, and `status` when the link changes
* GET /state → { status, channels, groups, entries } (entries by date)
* GET /stream → SSE: `state` (the snapshot, first), then `entry` for each
* changed entry, `clear`, and `status` when the link changes
* GET /messaging → what the Send Message module may send as: every
* channel that accepts typed text (typingEnabled), as
* an identity — typed text goes out *as* that channel
* (the module guide's contract)
* POST /messaging/send → { destination, text } with the Send Message unlock
* as a Bearer token — checked with that module over
* loopback, then POST /api/v1/channels/{id}/send, so a
* dashboard's typed text goes out on a ProdCom channel
* over this one connection. This module has no PIN and
* no send tile of its own.
*
* ProdCom's API, as the reference listener speaks it:
* GET /api/v1/channels, /api/v1/groups, /api/v1/transcript?limit=N and the
* SSE /api/v1/transcript/stream, whose frames carry an entry, or a
* { type, entry | data } wrapper, in a few historical shapes (see
* extractEntries). A bearer API key is sent when one is configured.
* extractEntries). POST /api/v1/channels/{id}/send with { text } puts typed
* text on a channel (it comes back on the stream with source "typed"). A
* bearer API key is sent when one is configured.
*/
const http = require('http');
/** The module that owns the PIN and the unlock tokens — see verifyUnlock(). */
const SENDER_ID = 'send-message';
const MAX_TEXT_CHARS = 2000;
const BODY_LIMIT_BYTES = 64 * 1024;
const HISTORY_LIMIT = 100; // entries asked for on (re)connect
const ENTRIES_MAX = 300; // entries kept in memory
const RETRY_MIN_MS = 2000;
@@ -67,13 +84,92 @@ function normalizeEntry(e) {
text: String(e.text ?? ''),
date: e.date ? String(e.date) : new Date().toISOString(),
inProgress: Boolean(e.inProgress),
// audio (speech), typed (a dashboard or ProdCom's own box), automation
source: e.source === 'typed' || e.source === 'automation' ? String(e.source) : 'audio',
};
}
/* ── small helpers ──────────────────────────────────────────────────── */
function sendJson(res, code, body) {
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(body));
}
function readJson(req) {
return new Promise((resolve, reject) => {
let data = '';
let size = 0;
req.on('data', (chunk) => {
size += chunk.length;
if (size > BODY_LIMIT_BYTES) {
reject(new Error('Request body too large.'));
req.destroy();
return;
}
data += chunk;
});
req.on('end', () => {
if (!data.trim()) return resolve({});
try {
const body = JSON.parse(data);
resolve(body && typeof body === 'object' ? body : {});
} catch {
reject(new Error('Malformed JSON.'));
}
});
req.on('error', reject);
});
}
/** Route handlers are async — the shell only catches synchronous throws. */
function guard(fn) {
return (req, res) => {
Promise.resolve()
.then(() => fn(req, res))
.catch((err) => {
if (!res.headersSent) sendJson(res, 500, { error: err?.message || String(err) });
else try { res.end(); } catch { /* gone */ }
});
};
}
function bearer(req) {
const m = /^Bearer\s+([A-Za-z0-9]+)\s*$/.exec(String(req.headers.authorization || ''));
return m ? m[1] : '';
}
/**
* Is the unlock token on this request good? Only the Send Message module
* knows — it owns the PIN — so ask it over loopback. Answers { ok: true,
* expiresAt } or { ok: false, status, error, code } ready to send back.
*/
async function verifyUnlock(req, shellPort) {
const token = bearer(req);
if (!token) return { ok: false, status: 401, error: 'Locked — enter the PIN', code: 'locked' };
if (!shellPort) return { ok: false, status: 503, error: 'This ProdDash cannot verify a PIN (needs 1.4.0 or newer)', code: 'no_shell_port' };
let res;
try {
res = await fetch(`http://127.0.0.1:${shellPort}/api/modules/${SENDER_ID}/verify`, {
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
signal: AbortSignal.timeout(5000),
});
} catch (err) {
return { ok: false, status: 502, error: `Cannot reach the Send Message module (${err.cause?.code || err.message})`, code: 'sender_unreachable' };
}
if (res.status === 404) return { ok: false, status: 503, error: 'Install the Send Message module to send from a dashboard', code: 'no_sender' };
let body = {};
try { body = await res.json(); } catch { /* a non-JSON refusal */ }
if (res.status === 401 || body?.ok === false) return { ok: false, status: 401, error: body?.error || 'Locked — enter the PIN', code: body?.code || 'locked' };
if (!res.ok) return { ok: false, status: 502, error: `Send Message module answered HTTP ${res.status}`, code: 'sender_error' };
return { ok: true, expiresAt: Number(body?.expiresAt) || 0 };
}
let current = null; // the running instance, for routes()
module.exports = {
init({ config, log }) {
init({ config, log, shell }) {
const shellPort = Number(shell && shell.port) || 0;
const target = resolveTarget(config);
const apiKey = String(config.apiKey || '');
const channels = [];
@@ -148,7 +244,14 @@ module.exports = {
getJson('/api/v1/channels'),
getJson('/api/v1/groups').catch(() => ({ data: [] })), // groups are optional in ProdCom
]);
channels.splice(0, channels.length, ...(ch.data || []).map((c) => ({ id: String(c.id), name: String(c.name || c.id), color: c.color || '#8b98a5' })));
channels.splice(0, channels.length, ...(ch.data || []).map((c) => ({
id: String(c.id),
name: String(c.name || c.id),
color: c.color || '#8b98a5',
// whether ProdCom lets text be typed onto this channel (an older
// ProdCom that doesn't say is taken at its word when asked)
typingEnabled: c.typingEnabled !== false,
})));
groups.splice(0, groups.length, ...(gr.data || []).map((g) => ({ id: String(g.id), name: String(g.name || g.id), channelIds: Array.isArray(g.channelIds) ? g.channelIds.map(String) : [] })));
}
@@ -264,9 +367,75 @@ module.exports = {
log('no ProdCom server configured — set the endpoint in /admin');
}
/** A channel by id, or by name (case-insensitive) — ProdCom accepts both, the tiles use ids. */
function channelByRef(ref) {
const s = String(ref ?? '').trim();
if (!s) return null;
return channels.find((c) => c.id === s) || channels.find((c) => c.name.toLowerCase() === s.toLowerCase()) || null;
}
/**
* What the Send Message module may send as: the channels that accept
* typed text. A ProdCom channel is an identity, not a recipient — text
* typed onto it goes out *as* that channel — so the destinations are
* declared as such, and a channel with typing off is left out.
*/
function messagingDescriptor() {
const h = current ? current.health() : { status: 'connecting', message: 'Restarting…' };
return {
label: 'ProdCom',
identity: '',
destinationRole: 'identity',
status: { state: h.status, message: h.message },
destinations: channels.filter((c) => c.typingEnabled).map((c) => ({ id: c.id, label: c.name, color: c.color || '' })),
emptyMessage: channels.length
? 'No ProdCom channel accepts typed text — turn on typing for one in ProdCom'
: 'No ProdCom channels yet',
maxChars: MAX_TEXT_CHARS,
};
}
/** Typed text onto a channel: the one ProdCom connection does the talking. */
async function sendText(ch, text) {
if (!target) return { status: 502, error: 'No ProdCom server configured — set the endpoint in Admin → ProdCom', code: 'no_target' };
let res;
try {
res = await fetch(new URL(`/api/v1/channels/${encodeURIComponent(ch.id)}/send`, target), {
method: 'POST',
headers: { 'content-type': 'application/json; charset=utf-8', accept: 'application/json', ...authHeaders() },
body: JSON.stringify({ text }),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
} catch (err) {
return { status: 502, error: `ProdCom unreachable (${err.cause?.code || err.code || err.message}) — not sent`, code: 'network' };
}
if (res.ok) {
res.body?.cancel?.().catch?.(() => {});
return { status: 200 };
}
let detail = '';
let code = '';
try {
const body = await res.json();
detail = String(body?.error?.message || '');
code = String(body?.error?.code || '');
} catch { /* no JSON */ }
const tail = detail ? ` — ${detail}` : '';
if (res.status === 401) return { status: 502, error: `ProdCom rejected the API key (${code || 'UNAUTHORIZED'}) — check Admin → ProdCom`, code: 'unauthorized' };
if (res.status === 404) return { status: 404, error: `ProdCom has no channel "${ch.name}" any more (${code || 'NOT_FOUND'}) — pick another in Send as`, code: 'not_found' };
if (res.status === 429) return { status: 429, error: `ProdCom is rate-limiting — try again in a moment${tail}`, code: 'ratelimited' };
if (res.status === 400 || res.status === 422) return { status: 400, error: `ProdCom refused the message (${code || res.status})${tail}`, code: 'refused' };
return { status: 502, error: `ProdCom answered HTTP ${res.status}${tail}`, code: code || `http_${res.status}` };
}
current = {
snapshot,
streams,
shellPort,
channelByRef,
messagingDescriptor,
sendText,
log,
health() {
if (status.state === 'ok') return { status: 'ok', message: `Live — ${channels.length} channel${channels.length === 1 ? '' : 's'}, ${entries.size} entries` };
// Nothing to connect to is a setting that is missing, not a link that
@@ -295,15 +464,52 @@ module.exports = {
},
routes() {
const sendJson = (res, code, body) => {
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(body));
};
const unmounted = (res) => sendJson(res, 503, { error: 'ProdCom module is restarting — try again' });
return {
'GET /state': (req, res) => {
if (!current) return sendJson(res, 503, { error: 'ProdCom module is restarting — try again' });
if (!current) return unmounted(res);
sendJson(res, 200, current.snapshot());
},
// The Send Message module reads this over loopback: where it may send.
'GET /messaging': (req, res) => {
if (!current) return unmounted(res);
sendJson(res, 200, current.messagingDescriptor());
},
// …and hands a message here, with the browser's unlock token. The token
// is checked with the Send Message module first: no PIN entered there,
// nothing goes out on a channel.
'POST /messaging/send': guard(async (req, res) => {
if (!current) return unmounted(res);
const v = await verifyUnlock(req, current.shellPort);
if (!v.ok) return sendJson(res, v.status, { error: v.error, code: v.code });
let body;
try {
body = await readJson(req);
} catch (err) {
return sendJson(res, 400, { error: err.message });
}
const text = String(body.text ?? '').replace(/\r\n/g, '\n').trim();
if (!text) return sendJson(res, 400, { error: 'Nothing to send' });
if (text.length > MAX_TEXT_CHARS) return sendJson(res, 400, { error: `Too long — ${MAX_TEXT_CHARS} characters at most` });
const ch = current.channelByRef(body.destination);
if (!ch) {
const s = String(body.destination ?? '').trim();
return sendJson(res, 400, { error: s ? `No ProdCom channel "${s}" — pick another in Send as` : 'Which ProdCom channel?', code: 'bad_destination' });
}
if (!ch.typingEnabled) {
return sendJson(res, 400, { error: `${ch.name} doesn't accept typed text — turn on typing for it in ProdCom`, code: 'typing_off' });
}
const out = await current.sendText(ch, text);
if (out.status !== 200) {
current.log(`send to ${ch.name} failed: ${out.error}`);
return sendJson(res, out.status, { error: out.error, code: out.code });
}
const preview = text.replace(/\s+/g, ' ').slice(0, 60);
current.log(`sent to ${ch.name}: "${preview}${text.length > 60 ? '…' : ''}"`);
sendJson(res, 200, { ok: true, label: ch.name, expiresAt: v.expiresAt });
}),
'GET /stream': (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
+36 -1
View File
@@ -9,6 +9,28 @@
flex-direction: column;
}
/* ── the send target ──
A click anywhere in the tile makes ProdCom the platform the Send Message
tiles send to. While it is, a 3px accent stripe runs along the bottom edge
of the tile body — drawn just inside our root, since the tile chrome
around it belongs to the shell. The others hint at it faintly on hover.
(The same mark as the Slack transcript's.) */
[data-module="prodcom-transcript"] .pt-wrap::after {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 3px;
background: var(--accent);
opacity: 0;
pointer-events: none;
z-index: 3;
transition: opacity 0.15s ease;
}
[data-module="prodcom-transcript"] .pt-wrap:hover::after { opacity: 0.3; }
[data-module="prodcom-transcript"] .pt-wrap.is-target::after { opacity: 1; }
/* ── channels button ──
Icon-only; the count appears next to it while some channels are hidden. */
@@ -20,9 +42,13 @@
}
[data-module="prodcom-transcript"] .pt-count[hidden] { display: none; }
/* narrow tile: the secondary controls fold into the ⋯ menu (client.js) */
[data-module="prodcom-transcript"] .tile-btn[hidden],
[data-module="prodcom-transcript"] .tile-dd[hidden] { display: none; }
/* ── channels menu ──
The menu container is created and positioned by the shell (.tile-menu);
it lives inside the tile, so [data-module] scoping still applies. */
it hangs off the body under a [data-module] host, so scoping still applies. */
[data-module="prodcom-transcript"] .pt-channel-item {
display: flex;
@@ -145,6 +171,15 @@
overflow-wrap: break-word;
}
/* typed text (from a dashboard, or ProdCom's own box) and automations carry
their own mark in the picture slot; the text reads the same */
[data-module="prodcom-transcript"] .pt-entry.typed .avatar,
[data-module="prodcom-transcript"] .pt-entry.automation .avatar {
background: color-mix(in srgb, var(--ch, var(--muted)) 10%, transparent);
outline: 1px dashed color-mix(in srgb, var(--ch, var(--muted)) 55%, transparent);
outline-offset: -1px;
}
[data-module="prodcom-transcript"] .pt-entry.in-progress .text { color: var(--muted); }
[data-module="prodcom-transcript"] .pt-entry.in-progress .text::after {
content: "▍";
Binary file not shown.
Binary file not shown.
+15 -3
View File
@@ -70,6 +70,7 @@ const DEFAULTS = {
showDetail: true,
showSeconds: true,
leadingZeros: false,
showLoops: false,
clock24h: true,
clockSeconds: true,
clockDate: false,
@@ -384,7 +385,12 @@ export default function create({ root, moduleApi }) {
for (const source of state.sources) {
for (const timer of source.timers) {
if (keyOf(source, timer) !== solo) continue;
return [{ id: source.id, source, items: [{ key: solo, source, timer }] }];
// A solo video tile with looping media hidden must not sit empty:
// it shows a quiet card instead of a countdown nobody should read.
const shown = timer.looping && pref('showLoops') !== true
? { ...timer, state: 'idle', remainingMs: null, elapsedMs: null, startedAt: null, asOf: null, status: { text: 'Looping', tone: 'muted' } }
: timer;
return [{ id: source.id, source, items: [{ key: solo, source, timer: shown }] }];
}
}
// The timer this tile was added for is not offered right now. Nothing is
@@ -398,7 +404,11 @@ export default function create({ root, moduleApi }) {
const items = [];
for (const timer of source.timers) {
const key = keyOf(source, timer);
if (!hidden.has(key)) items.push({ key, source, timer });
if (hidden.has(key)) continue;
// A looping background's time means nothing — the card sits out
// while a loop plays (per tile: the "Looping videos" switch).
if (timer.looping && pref('showLoops') !== true) continue;
items.push({ key, source, timer });
}
// Every timer of a live source hidden on purpose: nothing to say.
if (!items.length && source.timers.length) continue;
@@ -666,7 +676,9 @@ export default function create({ root, moduleApi }) {
card.mono = null;
}
text = value === null ? '—' : fmtDuration(value, { ...digits, up: timer.kind === 'countdown' });
tone = toneFor(timer, value);
// A shown loop never warns or overruns — it wraps at zero by design,
// and a background flashing red every pass would cry wolf all service.
tone = timer.looping ? (timer.state === 'running' ? 'ok' : 'muted') : toneFor(timer, value);
statusText = timer.status?.text || defaultStatus(timer, value, tone);
statusTone = timer.status?.tone || tone;
detailText = timer.detail || '';
+34 -113
View File
@@ -3,8 +3,8 @@
/**
* Built-in LTC listener — capture child + in-process decode.
*
* Spawns the module's native capture tool (ltc-capture, compiled from
* ltc-capture.swift beside it) for the admin-configured audio device, reads
* Spawns the module's native capture tool (bin/ltc-capture-macos-<arch>,
* shipped prebuilt; source in native/) for the admin-configured audio device, reads
* the interleaved s16le stream, extracts the configured channel, and decodes
* SMPTE LTC with ltc.js — all inside the module server. Reports upward via
* onUpdate roughly 4×/s:
@@ -16,17 +16,13 @@
* shows (short — "Not configured — see Admin"), `detail` is the full story
* for the admin health line and the log.
*
* The capture binary is per-machine (gitignored), and a catalog install or
* update ships source only — the update even wipes a previously built
* binary. ensureCaptureBinary() therefore rebuilds it with swiftc in the
* background as part of coming up: kicked when the LTC source starts and by
* the admin device picker, never on the event loop (a blocking build once
* froze the whole server — see spl-meter's history), built to a temp name
* and renamed so a killed build can't leave a half-written "binary", and
* rebuilt when a module update leaves the source newer than the binary.
* A dead capture child is restarted with backoff — fast for a crash, slow
* for config-shaped failures (unknown device, ambiguity) that never fix
* themselves.
* The capture tool ships prebuilt inside the module, one binary per
* platform under bin/ (module guide, "Native helpers"): nothing is ever
* built on the machine running ProdDash. captureTool() picks the binary for
* this platform; when there is none, timecode reports itself off and the
* rest of the module carries on. A dead capture child is restarted with
* backoff — fast for a crash, slow for config-shaped failures (unknown
* device, ambiguity) that never fix themselves.
*
* macOS gotcha this file can't fix: microphone permission. A ProdDash
* server launched over SSH or from a bare launchd job gets SILENT ZEROS
@@ -51,107 +47,43 @@ const RUNNING_WINDOW_MS = 400;
/** stderr line the capture prints once the device is open. */
const CAPTURING_RE = /capturing "(.+)": (\d+) channels @ (\d+) Hz/;
/* ── the capture tool: build it when the install didn't bring one ──────── */
/* ── the capture tool: prebuilt, one binary per platform ───────────────── */
/** Tile-facing words (short); the detail goes to admin health and the log. */
const TOOL_BUILDING = 'Capture tool building…';
const TOOL_MISSING = 'Capture tool unavailable — see Admin';
const BUILD_HELP = 'LTC capture tool could not be built here — build it on any Mac of the '
+ 'same architecture with `swiftc -O -o ltc-capture ltc-capture.swift` (both files are in '
+ 'the module folder) and copy the binary next to ltc-capture.swift';
let building = false;
let buildFailed = false;
/** What the module ships in bin/, by platform and architecture. */
const HELPERS = {
darwin: { arm64: 'ltc-capture-macos-arm64', x64: 'ltc-capture-macos-x86_64' },
win32: { x64: 'ltc-capture-win-x64.exe' },
};
/**
* Make sure the capture tool exists, building it in the background when it
* does not — module scope, so the LTC source can kick it the moment it
* starts and the admin device picker can kick it before any device is
* configured (a listener-only build would deadlock: no tool → no device
* list → no device → no listener). A catalog install ships source only and
* a catalog update deletes the module folder (old binary included), so this
* IS the install step for the tool.
* The capture tool for this machine. It is never built here and never
* looked for anywhere else: the module ships it, or timecode is off on this
* platform and says so. `ready` means a usable binary at `bin`; otherwise
* `error` is the short tile text and `detail` names the platform.
*
* Never blocks (a synchronous build once held the whole server's event loop
* — every module — for the duration). Builds to a temp name and renames, so
* a killed or crashed build can't leave a truncated file that looks like a
* ready binary. A binary older than the source (a module update over an
* existing folder) keeps serving while a replacement builds behind it.
*
* @returns {{ready:boolean, error:string, detail:string}} `ready` = a binary
* is usable right now; otherwise `error` is the short tile text and
* `detail` the full one.
* @returns {{ready:boolean, bin:string, error:string, detail:string}}
*/
function ensureCaptureBinary({ moduleDir, log, onReady }) {
const bin = path.join(moduleDir, 'ltc-capture');
const src = bin + '.swift';
const ok = { ready: true, error: '', detail: '' };
let haveBin = false;
let stale = false;
try {
haveBin = fs.existsSync(bin);
if (haveBin && fs.existsSync(src)) stale = fs.statSync(src).mtimeMs > fs.statSync(bin).mtimeMs;
} catch { /* treat as missing */ }
if (haveBin && !stale) return ok;
if (!fs.existsSync(src)) {
return haveBin ? ok : { ready: false, error: TOOL_MISSING, detail: 'ltc-capture.swift is missing from the module folder' };
}
const notYet = haveBin ? ok : {
function captureTool(moduleDir, platform = process.platform, arch = process.arch) {
const name = HELPERS[platform]?.[arch] || '';
const bin = name ? path.join(moduleDir, 'bin', name) : '';
if (bin && fs.existsSync(bin)) return { ready: true, bin, error: '', detail: '' };
const here = `${platform === 'darwin' ? 'macOS' : platform === 'win32' ? 'Windows' : platform} ${arch}`;
return {
ready: false,
error: building || !buildFailed ? TOOL_BUILDING : TOOL_MISSING,
detail: building || !buildFailed ? 'Building the LTC capture tool — ready in a moment' : BUILD_HELP,
bin: '',
error: TOOL_MISSING,
detail: `The module ships no LTC capture tool for ${here}${name ? ` (bin/${name} is missing)` : ''} — timecode is off on this machine`,
};
if (building || buildFailed) return notYet;
building = true;
const tmp = bin + '.building';
log(stale ? 'ltc-capture is older than its source — rebuilding it in the background'
: 'ltc-capture binary missing — building it in the background');
const build = spawn('swiftc', ['-O', '-o', tmp, src], { stdio: ['ignore', 'ignore', 'pipe'] });
let buildErr = '';
build.stderr.setEncoding('utf8');
build.stderr.on('data', (t) => { buildErr = (buildErr + t).slice(-800); });
const giveUp = setTimeout(() => {
try { build.kill('SIGKILL'); } catch { /* already gone */ }
}, 300000);
giveUp.unref?.();
build.on('error', (err) => {
clearTimeout(giveUp);
building = false;
buildFailed = true;
try { fs.rmSync(tmp, { force: true }); } catch { /* nothing to clean */ }
log(`swiftc could not be run: ${err.message}`);
});
build.on('exit', (code) => {
clearTimeout(giveUp);
building = false;
if (code === 0 && fs.existsSync(tmp)) {
try {
fs.renameSync(tmp, bin);
} catch (err) {
buildFailed = true;
log(`ltc-capture built but could not be moved into place: ${err.message}`);
return;
}
buildFailed = false;
log('ltc-capture built');
if (typeof onReady === 'function') onReady();
return;
}
buildFailed = true;
try { fs.rmSync(tmp, { force: true }); } catch { /* nothing to clean */ }
log(`ltc-capture build failed (exit ${code})` + (buildErr ? `: ${buildErr.trim().split('\n').pop()}` : ''));
});
return notYet;
}
/**
* @param {{device:string, channel:number, moduleDir:string, log:Function,
* onUpdate:(u:object)=>void}} opts
* @returns {{stop:()=>void}}
*/
function createLtcListener({ device, channel, moduleDir, log, onUpdate }) {
const bin = path.join(moduleDir, 'ltc-capture');
let child = null;
let stopped = false;
let restartTimer = null;
@@ -181,22 +113,11 @@ function createLtcListener({ device, channel, moduleDir, log, onUpdate }) {
function start() {
if (stopped) return;
const tool = ensureCaptureBinary({
moduleDir,
log,
onReady() {
// The build this start() was waiting on landed — go now.
if (!stopped) { clearTimeout(restartTimer); restartTimer = null; start(); }
},
});
const tool = captureTool(moduleDir);
if (!tool.ready) {
// No binary for this platform: say so and look again later — a module
// update remounts us anyway, this is only belt and braces.
report({ error: tool.error, detail: tool.detail });
// onReady is only the FAST path (a successful build restarts us at
// once). The slow retry must stay armed regardless: a failed build
// never calls back, and a binary can also arrive from outside — scp'd
// in on a machine whose toolchain can't build (AB's broken CLT).
// Waiting on onReady alone deadlocked exactly that way in production:
// "Capture tool building…" forever, with a working binary on disk.
scheduleRestart(BAD_CONFIG_RETRY_MS);
return;
}
@@ -206,7 +127,7 @@ function createLtcListener({ device, channel, moduleDir, log, onUpdate }) {
let decoder = null;
let stderrTail = '';
child = spawn(bin, ['--device', device], { stdio: ['ignore', 'pipe', 'pipe'] });
child = spawn(tool.bin, ['--device', device], { stdio: ['ignore', 'pipe', 'pipe'] });
child.stderr.setEncoding('utf8');
child.stderr.on('data', (text) => {
@@ -298,4 +219,4 @@ function createLtcListener({ device, channel, moduleDir, log, onUpdate }) {
};
}
module.exports = { createLtcListener, ensureCaptureBinary };
module.exports = { createLtcListener, captureTool };
+7 -1
View File
@@ -1,7 +1,7 @@
{
"id": "propresenter-timers",
"name": "Timers",
"version": "1.5.1",
"version": "1.7.0",
"proddash": ">=1.4.0",
"description": "Timers, Clocks, and LTC From configured Modules",
"provides": [
@@ -161,6 +161,12 @@
"default": false,
"group": "Show"
},
"showLoops": {
"type": "switch",
"label": "Looping videos",
"default": false,
"group": "Show"
},
"showHeadings": {
"type": "switch",
"label": "Source headings",
+48
View File
@@ -0,0 +1,48 @@
#!/bin/zsh
# Build this module's native helper for every macOS architecture it ships —
# ../bin/ltc-capture-macos-arm64 and ../bin/ltc-capture-macos-x86_64 —
# from ltc-capture.swift beside this script. Run it on any Mac with the
# Xcode command line tools; both architectures cross-compile from either.
# The binaries are committed: a machine running ProdDash never builds
# anything (docs/MODULE-GUIDE.md, "Native helpers").
#
# Signed with a Developer ID Application certificate when one is installed
# (override with CODESIGN_IDENTITY) — hardened runtime plus the audio-input
# entitlement, which a helper that reads a microphone needs under the
# hardened runtime — and ad-hoc otherwise, which is fine on your own Macs.
#
# Windows is not built here: there is no Windows implementation of this
# tool yet, so on Windows the module reports timecode off.
set -e -u
cd "$(dirname "$0")"
NAME="ltc-capture"
DEPLOYMENT_TARGET="13.0"
command -v swiftc >/dev/null || {
echo "build.sh: swiftc not found — install the Xcode command line tools: xcode-select --install" >&2
exit 1
}
IDENTITY="${CODESIGN_IDENTITY:-}"
if [[ -z "$IDENTITY" ]]; then
IDENTITY=$(security find-identity -v -p codesigning 2>/dev/null \
| awk -F'"' '/Developer ID Application/ {print $2; exit}')
fi
if [[ -n "$IDENTITY" ]]; then
echo "signing as $IDENTITY"
SIGN=(--force --sign "$IDENTITY" --options runtime --timestamp)
else
echo "signing ad-hoc (no Developer ID installed — fine on your own Macs)"
SIGN=(--force --sign - --options runtime)
fi
mkdir -p ../bin
for ARCH in arm64 x86_64; do
OUT="../bin/$NAME-macos-$ARCH"
echo " compiling $OUT"
swiftc -O -whole-module-optimization -target "$ARCH-apple-macos$DEPLOYMENT_TARGET" -o "$OUT" "$NAME.swift"
codesign "${SIGN[@]}" --entitlements helper.entitlements "$OUT"
codesign --verify --strict "$OUT"
echo " built $OUT ($(du -h "$OUT" | awk '{print $1}'))"
done
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- The helper reads an audio input; under the hardened runtime that
needs saying. The permission itself comes from the launcher. -->
<key>com.apple.security.device.audio-input</key>
<true/>
</dict>
</plist>
@@ -4,12 +4,12 @@
// The module decodes LTC in-process (ltc.js) and spawns this to move
// samples from an input device to a pipe. Production machines rarely have
// ffmpeg/sox, and shipping a third-party binary for that one job is
// overkill — this is the whole job, natively. The module compiles it on
// first use when swiftc is available; otherwise build it once on any
// same-architecture Mac and copy the binary next to this source:
// overkill — this is the whole job, natively. It ships prebuilt in the
// module's bin/ (one binary per platform, committed — a booth never
// builds anything). To rebuild after a change here, on any Mac with the
// Xcode command line tools:
//
// swiftc -O -o modules/propresenter-timers/ltc-capture \
// modules/propresenter-timers/ltc-capture.swift (once, ~5 s)
// modules/propresenter-timers/native/build.sh (both architectures, ~10 s)
//
// ltc-capture --list
// every input-capable device: name, input channels, sample rate
+149 -17
View File
@@ -81,7 +81,7 @@
const http = require('http');
const path = require('path');
const { spawn } = require('child_process');
const { createLtcListener, ensureCaptureBinary } = require('./ltc-listener');
const { createLtcListener, captureTool } = require('./ltc-listener');
const { createTimerPhase } = require('./phase');
const manifest = require('./module.json');
@@ -255,6 +255,21 @@ function createProPresenterSource({ config, log }) {
/** uuid → phase tracker: whole-second reports → one stable anchor (see phase.js). */
const phases = new Map();
/* The video countdown — time left on what the presentation layer is
playing, from the transport routes (verified live on ProPresenter 21.4):
GET /v1/transport/presentation/current → { is_playing, uuid, name,
artist, audio_only, duration } (no looping flag exists — inferred)
GET /v1/transport/presentation/time → bare seconds, sub-second
float — better than /v1/timer/video_countdown's whole-second string,
so no quantization phase lock is needed, only an anchor hold. */
let media = null; // { uuid, name, duration, playing } from the slow lane
let mediaAt = 0;
let transportOk = null; // null until the first answer; false = no transport route (older ProPresenter)
let videoPos = null; // playback position in seconds (float)
let videoAsOf = 0; // server ms when videoPos was measured
let videoAnchor = null; // published { remainingMs, asOf }, held while it predicts the measurements
let loopingUuid = ''; // media seen wrapping — a looping background
function url(target) {
const built = new URL(`http://${host}:${port}${target}`);
if (password) built.searchParams.set('password', password);
@@ -390,6 +405,121 @@ function createProPresenterSource({ config, log }) {
return out;
}
/**
* Follow the presentation transport layer. Failures here only drop the
* video card, never the whole source — the timers must survive a
* ProPresenter build with transport quirks.
*/
async function pollVideo() {
if (tick % SLOW_EVERY === 1) {
try {
const raw = await requestJson('/v1/transport/presentation/current');
const uuid = String(raw?.uuid || '');
if (!media || media.uuid !== uuid) {
if (media && media.uuid !== uuid) loopingUuid = '';
videoPos = null;
videoAnchor = null;
}
media = uuid ? {
uuid,
name: String(raw.name || ''),
duration: Number(raw.duration) > 0 ? Number(raw.duration) : 0,
playing: Boolean(raw.is_playing),
} : null;
mediaAt = Date.now();
transportOk = true;
} catch (err) {
media = null; // the slow lane retries in ~2 s
if (err && err.status === 404) transportOk = false; // no transport route on this build
}
}
if (!media) {
videoPos = null;
videoAnchor = null;
return;
}
try {
const pos = Number(await requestJson('/v1/transport/presentation/time'));
if (Number.isFinite(pos) && pos >= 0) {
// Same media, position jumped back by more than a stutter: it
// wrapped — a looping background. Sticks until the media changes.
// (A video manually re-triggered from the start looks the same and
// is mislabeled for that pass; loops re-wrap, replays don't recur.)
if (videoPos !== null && media.playing && videoPos - pos > 1.5) loopingUuid = media.uuid;
videoPos = pos;
videoAsOf = Date.now();
} else {
videoPos = null;
}
} catch {
videoPos = null;
}
}
/** The video countdown as one synthetic timer card (id 'video'). The card
persists as an idle "—" between videos — a wall tile must not appear
and vanish with the media — and is only absent entirely on a
ProPresenter without transport routes. */
function videoTimer() {
if (transportOk !== true) return null;
if (!media) {
return {
id: 'video',
label: 'Video',
kind: 'countdown',
state: 'idle',
asOf: mediaAt || updatedAt,
startedAt: null,
elapsedMs: null,
remainingMs: null,
targetMs: null,
looping: false,
status: null,
detail: '',
};
}
const playing = media.playing;
const dur = media.duration > 0 ? media.duration * 1000 : null;
let remainingMs = null;
let asOf = videoAsOf || mediaAt;
if (videoPos !== null && dur !== null) {
remainingMs = Math.max(0, dur - videoPos * 1000);
if (playing) {
// Hold the published anchor while it still predicts the measured
// position: the tiles extrapolate locally, and a fresh anchor per
// poll would broadcast a frame every 500 ms for nothing.
const p = videoAnchor;
const predicted = p ? p.remainingMs - (videoAsOf - p.asOf) : NaN;
if (p && Math.abs(predicted - remainingMs) < 120) {
remainingMs = p.remainingMs;
asOf = p.asOf;
} else {
videoAnchor = { remainingMs, asOf };
}
} else {
videoAnchor = null;
}
} else {
videoAnchor = null;
}
const looping = media.uuid === loopingUuid;
return {
id: 'video',
label: 'Video',
kind: 'countdown',
state: playing ? 'running' : videoPos > 0 ? 'paused' : 'idle',
asOf,
startedAt: null,
elapsedMs: remainingMs !== null && dur !== null ? dur - remainingMs : null,
remainingMs,
targetMs: dur,
looping,
status: looping ? { text: playing ? 'Looping' : 'Paused', tone: 'muted' } : null,
// The media name, without the file extension nobody reads on a wall.
detail: media.name.replace(/\.(mp4|mov|m4v|mxf|avi|mkv|mp3|wav|aiff?)$/i, ''),
};
}
function status() {
if (!configured) return 'error';
if (reachable) return 'ok';
@@ -429,6 +559,9 @@ function createProPresenterSource({ config, log }) {
const currentTimes = await requestJson('/v1/timers/current');
updatedAt = Date.now();
timers = mergeTimers(currentTimes, updatedAt);
await pollVideo();
const video = videoTimer();
if (video) timers.push(video);
reachable = true;
lastError = '';
} catch (err) {
@@ -527,11 +660,8 @@ function createLtcSource({ config, log, moduleDir }) {
kind: 'ltc',
start(e) {
emit = e;
// Kick the capture-tool build right away: a catalog install ships
// source only and a catalog update wipes any previously built binary,
// so coming up after an install/update must rebuild it without
// waiting for a device to be picked or a listener to need it.
ensureCaptureBinary({ moduleDir, log });
// The capture tool ships prebuilt in the module; the listener picks
// it for this platform when it starts and says so when there is none.
if (!device) {
word = {
error: 'Not configured — see Admin',
@@ -970,6 +1100,8 @@ const GEAR = {
all: { instanceSchema: FULL_SCHEMA, instanceGroups: FULL_GROUPS },
/** One ProPresenter or module timer: its elements, and the tone its digits take per state. */
timer: gearOf([...TIMER_ELEMENTS, ...COLOURS], OPEN_COLOURS),
/** The video countdown: a timer card, plus whether looping media counts. */
video: gearOf([...TIMER_ELEMENTS, 'showLoops', ...COLOURS], OPEN_COLOURS),
/** The timecode: running, no signal (warning) and stopped (idle) — it never overruns, and frames are frames. */
ltc: gearOf(['showNames', 'showStatus', 'runningColor', 'warningColor', 'idleColor'], OPEN_COLOURS),
/** The time of day: plain digits, so only how they read. */
@@ -983,6 +1115,7 @@ function gearFor(source, timer) {
if (source.kind === 'ltc') return GEAR.ltc;
if (source.kind === 'clock') return GEAR.clock;
if (timer.kind === 'clock') return GEAR.providerClock;
if (source.id === 'propresenter' && timer.id === 'video') return GEAR.video;
return GEAR.timer;
}
@@ -1191,7 +1324,8 @@ module.exports = {
for (const t of src.timers) {
const description = src.kind === 'ltc' ? 'The incoming LTC timecode on its own'
: src.kind === 'clock' ? 'The time of day on its own'
: `This ${src.label} ${KIND_WORD[t.kind] || 'timer'} on its own`;
: src.id === 'propresenter' && t.id === 'video' ? 'Time left on the video ProPresenter is playing'
: `This ${src.label} ${KIND_WORD[t.kind] || 'timer'} on its own`;
// Layouts from before 1.3.0 hold 'timer:<uuid>' / 'ltc' — the same tiles.
const aliases = src.id === 'propresenter' ? [`timer:${t.id}`] : src.kind === 'ltc' ? ['ltc'] : [];
out.push({ id: `solo:${src.id}:${t.id}`, name: t.label, description, ...oneCard, ...gearFor(src, t), ...(aliases.length ? { aliases } : {}) });
@@ -1222,23 +1356,21 @@ module.exports = {
},
// The admin device picker asks this machine what it can hear. The
// options shape matches the admin select's optionsRoute contract.
// Opening the picker also kicks the capture-tool build when a catalog
// install/update left only the source — without this, no tool meant
// no device list, and no device meant nothing would ever build it.
// options shape matches the admin select's optionsRoute contract. The
// capture tool ships prebuilt in the module (bin/); with none for this
// platform the list is empty and the error says so.
'GET /ltc/devices': (req, res) => {
const tool = ensureCaptureBinary({ moduleDir: __dirname, log });
const tool = captureTool(__dirname);
if (!tool.ready) {
sendJson(res, 200, { options: [], error: tool.detail || tool.error });
sendJson(res, 200, { options: [], error: tool.detail });
return;
}
const bin = path.join(__dirname, 'ltc-capture');
const child = spawn(bin, ['--list'], { stdio: ['ignore', 'ignore', 'pipe'], timeout: 4000 });
const child = spawn(tool.bin, ['--list'], { stdio: ['ignore', 'ignore', 'pipe'], timeout: 4000 });
let err = '';
child.stderr.setEncoding('utf8');
child.stderr.on('data', (t) => { err += t; });
child.on('error', () => {
sendJson(res, 200, { options: [], error: 'LTC capture tool missing — see modules/propresenter-timers/ltc-capture.swift' });
child.on('error', (e) => {
sendJson(res, 200, { options: [], error: `LTC capture tool could not be run: ${e.message}` });
});
child.on('exit', () => {
if (res.writableEnded) return;
File diff suppressed because it is too large Load Diff
+63
View File
@@ -0,0 +1,63 @@
{
"id": "send-message",
"name": "Send Message",
"version": "1.0.0",
"proddash": ">=1.4.0",
"description": "PIN-protected sending to Slack, ProdCom and any other messaging module, from one tile",
"client": "client.js",
"server": "server.js",
"style": "style.css",
"minSize": {
"w": 2,
"h": 2
},
"defaultSize": {
"w": 3,
"h": 3
},
"configGroups": {
"PIN": {
"toggle": "pinEnabled",
"help": "Nothing leaves this machine until the PIN is entered on a Send message or Quick replies tile. One PIN unlocks every messaging tile on that dashboard page — Send message, Quick replies and Slack's reaction menu — until Auto-lock minutes pass without a send; a reload asks again. With the PIN switched off, the tiles send without asking. Sending stays refused while the PIN is on but not yet set."
},
"Presets": {
"help": "Quick replies are one per line, Label | Message. Add | platform:destination to bind one — slack:#production or prodcom:FOH — and that reply always goes there, whichever transcript is selected. Quick emojis are sent as a message of their own with one press from the Send message tile."
}
},
"configSchema": {
"pinEnabled": {
"type": "switch",
"label": "PIN",
"default": true,
"group": "PIN"
},
"pin": {
"type": "password",
"label": "PIN",
"default": "",
"group": "PIN",
"help": "4–8 digits; the pad unlocks by itself once they are all in."
},
"pinIdleMinutes": {
"type": "number",
"label": "Auto-lock (min)",
"default": 10,
"group": "PIN"
},
"quickReplies": {
"type": "text",
"label": "Quick replies",
"default": "",
"group": "Presets",
"help": "One per line: Label | Message. Add | slack:#channel or | prodcom:Channel to bind one to a destination."
},
"quickEmojis": {
"type": "string",
"label": "Quick emojis",
"default": "👍 🙏 ✅ 👀 🎉",
"group": "Presets",
"help": "Emoji separated by spaces, eight at most. Sent as plain text to whatever is selected."
}
},
"instanceSchema": {}
}
+806
View File
@@ -0,0 +1,806 @@
'use strict';
/**
* Send Message — server part.
*
* One place a dashboard sends from, whatever the platform. The module owns
* nothing upstream: it finds every module whose manifest says
* "provides": ["messaging"] (Slack, ProdCom, whatever comes next) through
* the shell's /api/modules over loopback, reads each one's destinations
* from its GET /messaging, and hands a message to the provider's
* POST /messaging/send — so Slack keeps its one Slack connection, ProdCom
* its one ProdCom connection, and this module never opens a second one.
*
* It also owns the PIN. A browser unlocks here and gets a token; every
* gated action anywhere — a send through this module, a reaction in a
* Slack transcript — carries that token, and the provider checks it with
* GET /verify over loopback before touching its upstream. No provider has
* a PIN of its own, and no browser on the network can reach a provider's
* send route without having entered the PIN here.
*
* GET /state providers (destinations, identity, status), pin flags, quick emojis
* GET /stream SSE `state` events (change-detected, heartbeated)
* POST /unlock { pin } → { token, expiresAt } (constant-time, lockout)
* with the PIN switched off: {} → a token, no questions
* POST /lock Bearer → forget that token
* GET /verify Bearer → { ok, expiresAt }, 401 otherwise — for providers
* GET /quick Bearer → preset labels, indexes and bindings (never the text)
* POST /send Bearer, { provider, destination, text }
* POST /quick Bearer, { index, provider, destination }
*
* The provider contract is in docs/MODULE-GUIDE.md ("Offering messaging").
*/
const crypto = require('crypto');
const SELF_ID = 'send-message';
const CAPABILITY = 'messaging';
/** SSE comment ping cadence — keeps idle connections alive through sleepy Wi-Fi. */
const HEARTBEAT_MS = 15000;
/** Re-read /api/modules: a newly installed provider shows up without a restart. */
const DISCOVER_MS = 30000;
const DISCOVER_RETRY_MS = 5000; // …sooner while the shell isn't answering yet (boot)
const DISCOVER_FIRST_MS = 1500; // init() runs before the shell listens
/** Each provider's /messaging, re-read this often while a tile is watching… */
const DESCRIBE_MS = 4000;
/** …and this slowly with nobody looking. */
const DESCRIBE_IDLE_MS = 30000;
/** A tile counts as watching for this long after its last /state or /stream. */
const IDLE_AFTER_MS = 30000;
const LOOPBACK_TIMEOUT_MS = 5000;
/** A provider's send may itself wait on its upstream. */
const SEND_TIMEOUT_MS = 15000;
const PIN_RE = /^\d{4,8}$/;
const PIN_MAX_WRONG = 5;
const PIN_LOCKOUT_MS = 30000;
/** With the PIN off, a token is minted on request and simply lasts. */
const NO_PIN_TOKEN_MS = 7 * 24 * 60 * 60 * 1000;
const SEND_MIN_INTERVAL_MS = 1000;
const DEFAULT_MAX_CHARS = 4000;
const BODY_LIMIT_BYTES = 64 * 1024;
const UNLOCK_SWEEP_MS = 30000;
/** Set by init(), read by routes() — rebuilt together on remount. */
let current = null;
/* ── small helpers ──────────────────────────────────────────────────── */
function sendJson(res, code, body) {
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(body));
}
function readJson(req) {
return new Promise((resolve, reject) => {
let data = '';
let size = 0;
req.on('data', (chunk) => {
size += chunk.length;
if (size > BODY_LIMIT_BYTES) {
reject(new Error('Request body too large.'));
req.destroy();
return;
}
data += chunk;
});
req.on('end', () => {
if (!data.trim()) return resolve({});
try {
const body = JSON.parse(data);
resolve(body && typeof body === 'object' ? body : {});
} catch {
reject(new Error('Malformed JSON.'));
}
});
req.on('error', reject);
});
}
/** Route handlers are async — the shell only catches synchronous throws. */
function guard(fn) {
return (req, res) => {
Promise.resolve()
.then(() => fn(req, res))
.catch((err) => {
if (!res.headersSent) sendJson(res, 500, { error: err?.message || String(err) });
else try { res.end(); } catch { /* gone */ }
});
};
}
function bearer(req) {
const m = /^Bearer\s+([A-Za-z0-9]+)\s*$/.exec(String(req.headers.authorization || ''));
return m ? m[1] : '';
}
function clientIp(req) {
return String(req.socket?.remoteAddress || '');
}
/** Constant-time PIN compare (lengths are folded in after the timing-safe step). */
function pinMatches(given, expected) {
const a = Buffer.alloc(16);
const b = Buffer.alloc(16);
a.write(String(given).slice(0, 16));
b.write(String(expected).slice(0, 16));
const same = crypto.timingSafeEqual(a, b);
return same && given.length === expected.length;
}
function errorText(err) {
return String(err?.cause?.code || err?.code || err?.message || err || 'error');
}
/**
* "Label | Message | platform:destination" per line. A line with no "|" is
* both its label and its message. The binding (optional) names a provider
* — its module id, a prefix of it ("prodcom"), or its label ("Slack") — and
* one of its destinations by id or label ("#production", "FOH"); a reply
* that carries one always goes there, whatever is selected.
*/
function parseQuickReplies(text) {
const out = [];
for (const rawLine of String(text || '').split(/\r?\n/)) {
const line = rawLine.trim();
if (!line) continue;
const parts = line.split('|').map((p) => p.trim());
const label = parts[0];
const message = parts.length > 1 && parts[1] ? parts[1] : label;
const binding = parts.length > 2 ? parts[2] : '';
if (!label || !message) continue;
out.push({ label, message, binding });
}
return out;
}
/** "👍 🙏 ✅" → ['👍', '🙏', '✅'] — plain text tokens, eight at most. */
function parseQuickEmojis(text) {
return String(text || '').split(/\s+/).filter(Boolean).slice(0, 8);
}
/** A provider's GET /messaging answer, as the tiles and the send route use it. */
function normalizeDescriptor(id, fallbackLabel, body) {
const b = body && typeof body === 'object' ? body : {};
const st = b.status && typeof b.status === 'object' ? b.status : {};
const state = st.state === 'ok' || st.state === 'error' ? st.state : 'connecting';
const destinations = [];
const seen = new Set();
for (const d of Array.isArray(b.destinations) ? b.destinations : []) {
if (!d || typeof d !== 'object') continue;
const did = String(d.id ?? '').trim();
if (!did || seen.has(did)) continue;
seen.add(did);
destinations.push({ id: did, label: String(d.label || did), color: typeof d.color === 'string' ? d.color : '' });
}
const maxChars = Math.trunc(Number(b.maxChars));
return {
id,
label: String(b.label || fallbackLabel || id),
identity: String(b.identity || ''),
// recipient: a message goes *to* a destination (a Slack channel);
// identity: it goes out *as* one (a ProdCom channel) — the Send as menu
// lists only the latter, and the wording follows
destinationRole: b.destinationRole === 'identity' ? 'identity' : 'recipient',
status: { state, message: String(st.message || '') },
destinations,
// what to say when the list is empty, if the provider knows why
emptyMessage: String(b.emptyMessage || ''),
maxChars: maxChars > 0 ? Math.min(DEFAULT_MAX_CHARS * 10, maxChars) : DEFAULT_MAX_CHARS,
};
}
/** "Slack → #ops" / "ProdCom as FOH" — how a provider + destination pair reads. */
function pairLabel(descriptor, destination) {
return descriptor.destinationRole === 'identity'
? `${descriptor.label} as ${destination.label}`
: `${descriptor.label} → ${destination.label}`;
}
/* ── the module ─────────────────────────────────────────────────────── */
module.exports = {
init({ config, log, shell }) {
/* ── config ── */
const shellPort = Number(shell && shell.port) || 0;
const pinEnabled = config.pinEnabled !== false;
const pin = String(config.pin || '').trim();
const pinOk = PIN_RE.test(pin);
const idleMs = Math.min(240, Math.max(1, Number(config.pinIdleMinutes) || 10)) * 60 * 1000;
const quickReplies = parseQuickReplies(config.quickReplies);
const quickEmojis = parseQuickEmojis(config.quickEmojis);
/* ── state (all inside this closure so a re-init starts clean) ── */
let stopped = false;
const providers = new Map(); // module id → { id, label, descriptor | null, error, at }
let listError = ''; // the last /api/modules failure ('' while fine)
let listedAt = 0;
let discoverTimer = null;
let describeTimer = null;
let describing = null; // one descriptor sweep in flight
const streams = new Set();
const unlocks = new Map(); // token → { expiresAt, lastSendAt, ip }
const pinAttempts = new Map(); // ip → { count, lockedUntil }
let lastInterest = Date.now();
let lastSig = '';
const loopback = (path) => `http://127.0.0.1:${shellPort}${path}`;
function watched() {
return streams.size > 0 || Date.now() - lastInterest < IDLE_AFTER_MS;
}
/* ── discovery: who offers messaging ── */
async function discover() {
discoverTimer = null;
if (stopped) return;
try {
if (!shellPort) throw new Error('shell port unknown (needs ProdDash 1.4.0)');
const res = await fetch(loopback('/api/modules'), {
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(LOOPBACK_TIMEOUT_MS),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const body = await res.json();
if (stopped) return;
const mods = (Array.isArray(body?.modules) ? body.modules : [])
.filter((m) => m && typeof m.id === 'string' && m.id !== SELF_ID && Array.isArray(m.provides) && m.provides.includes(CAPABILITY));
const keep = new Set();
for (const m of mods) {
keep.add(m.id);
const have = providers.get(m.id);
if (have) have.label = String(m.name || m.id);
else {
providers.set(m.id, { id: m.id, label: String(m.name || m.id), descriptor: null, error: '', at: 0 });
log(`module "${m.id}" offers messaging`);
}
}
for (const id of [...providers.keys()]) {
if (keep.has(id)) continue;
providers.delete(id);
log(`module "${id}" no longer offers messaging`);
}
listError = '';
listedAt = Date.now();
await describeAll();
} catch (err) {
listError = errorText(err);
broadcastIfChanged();
}
if (!stopped) {
discoverTimer = setTimeout(discover, listError ? DISCOVER_RETRY_MS : DISCOVER_MS);
discoverTimer.unref?.();
}
}
/** Read one provider's /messaging; a failure is kept on the entry, not thrown. */
async function describe(p) {
try {
const res = await fetch(loopback(`/api/modules/${encodeURIComponent(p.id)}/messaging`), {
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(LOOPBACK_TIMEOUT_MS),
});
if (res.status === 404) {
// Disabled or uninstalled, most likely: let the module list decide
// now rather than at the next 30 s pass, so the tiles drop it at once.
if (!discoverTimer && !stopped) {
discoverTimer = setTimeout(discover, 250);
discoverTimer.unref?.();
}
throw new Error('not answering (disabled or restarting)');
}
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const body = await res.json();
if (stopped) return;
p.descriptor = normalizeDescriptor(p.id, p.label, body);
if (p.error) log(`${p.label}: describing itself again`);
p.error = '';
p.at = Date.now();
} catch (err) {
const text = errorText(err);
if (p.error !== text) log(`${p.label}: cannot read its destinations — ${text}`);
p.error = text;
}
}
function describeAll() {
if (!describing) {
describing = Promise.all([...providers.values()].map(describe))
.then(() => broadcastIfChanged())
.finally(() => { describing = null; });
}
return describing;
}
function scheduleDescribe(delay = null) {
if (stopped) return;
clearTimeout(describeTimer);
describeTimer = setTimeout(async () => {
describeTimer = null;
await describeAll();
scheduleDescribe();
}, delay ?? (watched() ? DESCRIBE_MS : DESCRIBE_IDLE_MS));
describeTimer.unref?.();
}
/** Somebody is looking: catch up at once if the list is stale or empty. */
function wake() {
lastInterest = Date.now();
if (stopped) return;
if ((!providers.size || listError) && Date.now() - listedAt > DISCOVER_RETRY_MS && !discoverTimer) {
discoverTimer = setTimeout(discover, 50);
discoverTimer.unref?.();
} else if (describeTimer) {
// The idle cadence was in force; move to the watched one now.
scheduleDescribe(DESCRIBE_MS);
}
}
/* ── what the tiles see ── */
function providerView(p) {
const d = p.descriptor;
if (!d) {
return {
id: p.id,
label: p.label,
identity: '',
destinationRole: 'recipient',
status: { state: p.error ? 'error' : 'connecting', message: p.error ? `${p.label} module ${p.error}` : 'Reading destinations…' },
destinations: [],
emptyMessage: '',
maxChars: DEFAULT_MAX_CHARS,
error: p.error,
};
}
return { ...d, error: p.error, status: p.error ? { state: 'error', message: `${p.label} module ${p.error}` } : d.status };
}
function health() {
if (!shellPort) return { status: 'error', message: 'This module needs ProdDash 1.4.0 or newer' };
const pinLine = !pinEnabled ? 'PIN off' : pinOk ? 'PIN set' : 'PIN on but not set — sending refused';
if (listError) return { status: listedAt ? 'connecting' : 'error', message: `Cannot read the module list (${listError}) · ${pinLine}` };
if (!listedAt) return { status: 'connecting', message: 'Looking for messaging modules…' };
const list = [...providers.values()];
if (!list.length) return { status: 'error', message: `No module offers messaging — install Slack or ProdCom · ${pinLine}` };
const parts = list.map((p) => {
const v = providerView(p);
if (v.error) return `${v.label}: ${v.error}`;
const n = v.destinations.length;
const who = v.identity ? ` as ${v.identity}` : '';
// a provider that is up but unhappy says why, so the admin line does too
const why = v.status.state !== 'ok' && v.status.message ? ` — ${v.status.message}`
: !n && v.emptyMessage ? ` — ${v.emptyMessage}` : '';
const noun = v.destinationRole === 'identity' ? 'identit' + (n === 1 ? 'y' : 'ies') : 'destination' + (n === 1 ? '' : 's');
return `${v.label}${who} (${n} ${noun})${why}`;
});
const bad = list.some((p) => p.error || p.descriptor?.status.state === 'error');
const pending = list.some((p) => !p.descriptor);
return {
status: pinEnabled && !pinOk ? 'error' : bad ? 'error' : pending ? 'connecting' : 'ok',
message: `${parts.join(' · ')} · ${pinLine}`,
};
}
function snapshot() {
const h = health();
return {
providers: [...providers.values()].map(providerView),
pin: {
enabled: pinEnabled,
set: pinOk,
// the pad submits by itself once this many digits are in (never the PIN)
length: pinEnabled && pinOk ? pin.length : 0,
idleMinutes: idleMs / 60000,
},
quickEmojis,
quickCount: quickReplies.length,
status: { state: h.status, message: h.message },
};
}
function broadcastIfChanged() {
const snap = snapshot();
const sig = JSON.stringify(snap);
if (sig === lastSig) return;
lastSig = sig;
if (!streams.size) return;
const payload = `event: state\ndata: ${JSON.stringify(snap)}\n\n`;
for (const res of streams) {
try {
res.write(payload);
} catch {
streams.delete(res);
}
}
}
/* ── the PIN and its unlock tokens ── */
function sweepUnlocks() {
const now = Date.now();
for (const [t, u] of unlocks) if (u.expiresAt <= now) unlocks.delete(t);
for (const [ip, a] of pinAttempts) if (a.lockedUntil && a.lockedUntil <= now && !a.count) pinAttempts.delete(ip);
}
/** The unlock behind a token, or null; a hit slides its idle expiry along. */
function verify(token) {
const u = token ? unlocks.get(token) : null;
if (!u) return null;
const now = Date.now();
if (u.expiresAt <= now) {
unlocks.delete(token);
return null;
}
if (pinEnabled) u.expiresAt = now + idleMs;
return { token, ...u };
}
/** Everything a send needs before anyone is asked; answers the refusal itself. */
function sendGate(req, res) {
if (pinEnabled && !pinOk) {
sendJson(res, 403, { error: 'Set a PIN in Admin → Send Message, or switch the PIN off', code: 'no_pin' });
return null;
}
const u = verify(bearer(req));
if (!u) {
sendJson(res, 401, { error: 'Locked — enter the PIN', code: 'locked' });
return null;
}
return u;
}
function unlock(req, res, given) {
const ip = clientIp(req);
const now = Date.now();
if (!pinEnabled) {
const t = crypto.randomBytes(32).toString('hex');
const expiresAt = now + NO_PIN_TOKEN_MS;
unlocks.set(t, { expiresAt, lastSendAt: 0, ip });
return sendJson(res, 200, { token: t, expiresAt, idleMs: NO_PIN_TOKEN_MS, pinEnabled: false });
}
if (!pinOk) return sendJson(res, 403, { error: 'Set a PIN in Admin → Send Message, or switch the PIN off', code: 'no_pin' });
let a = pinAttempts.get(ip);
if (a && a.lockedUntil > now) {
const secs = Math.ceil((a.lockedUntil - now) / 1000);
return sendJson(res, 429, { error: `Too many wrong PINs — locked for ${secs} s`, code: 'lockout', retryAfter: secs });
}
if (a && a.lockedUntil && a.lockedUntil <= now) a = null; // lockout served — clean slate
const str = String(given ?? '');
if (!PIN_RE.test(str) || !pinMatches(str, pin)) {
const count = (a ? a.count : 0) + 1;
if (count >= PIN_MAX_WRONG) {
pinAttempts.set(ip, { count: 0, lockedUntil: now + PIN_LOCKOUT_MS });
log(`wrong PIN ×${PIN_MAX_WRONG} from ${ip} — locked for ${PIN_LOCKOUT_MS / 1000} s`);
return sendJson(res, 429, { error: `Wrong PIN — locked for ${PIN_LOCKOUT_MS / 1000} s`, code: 'lockout', retryAfter: PIN_LOCKOUT_MS / 1000 });
}
pinAttempts.set(ip, { count, lockedUntil: 0 });
return sendJson(res, 401, { error: 'Wrong PIN', code: 'wrong_pin', triesLeft: PIN_MAX_WRONG - count });
}
pinAttempts.delete(ip);
const t = crypto.randomBytes(32).toString('hex');
const expiresAt = now + idleMs;
unlocks.set(t, { expiresAt, lastSendAt: 0, ip });
log(`unlocked from ${ip} (auto-lock after ${idleMs / 60000} min idle)`);
return sendJson(res, 200, { token: t, expiresAt, idleMs, pinEnabled: true });
}
/* ── destinations and bindings ── */
function findProvider(ref) {
const s = String(ref ?? '').trim().toLowerCase();
if (!s) return null;
for (const p of providers.values()) if (p.id.toLowerCase() === s) return p;
for (const p of providers.values()) {
const label = (p.descriptor?.label || p.label).toLowerCase();
if (label === s || p.id.toLowerCase().startsWith(s) || label.replace(/\s+/g, '') === s.replace(/\s+/g, '')) return p;
}
return null;
}
function findDestination(p, ref) {
const s = String(ref ?? '').trim();
if (!p?.descriptor || !s) return null;
const list = p.descriptor.destinations;
const exact = list.find((d) => d.id === s);
if (exact) return exact;
const name = s.replace(/^#/, '').toLowerCase();
return list.find((d) => d.label.replace(/^#/, '').toLowerCase() === name) || null;
}
/** A quick reply's "platform:destination" → { provider, destination } or { error }. */
function resolveBinding(binding) {
const s = String(binding || '').trim();
if (!s) return null;
const i = s.indexOf(':');
if (i > 0) {
const p = findProvider(s.slice(0, i));
if (!p) return { error: `No messaging module called "${s.slice(0, i).trim()}" for this quick reply` };
if (!p.descriptor) return { error: `${p.label} hasn't listed its destinations yet — try again in a moment` };
const d = findDestination(p, s.slice(i + 1));
if (!d) return { error: `${p.descriptor.label} has no destination "${s.slice(i + 1).trim()}" — check the quick reply in Admin → Send Message` };
return { provider: p, destination: d };
}
for (const p of providers.values()) {
const d = findDestination(p, s);
if (d) return { provider: p, destination: d };
}
return { error: `No destination "${s}" on any messaging module — check the quick reply in Admin → Send Message` };
}
/** The label a tile shows for a binding — resolved when it can be, the raw text otherwise. */
function bindingLabel(binding) {
const r = resolveBinding(binding);
if (!r) return '';
if (r.error) return String(binding).trim();
return pairLabel(r.provider.descriptor, r.destination);
}
/**
* The provider and destination a browser asked for. Both must be ones
* the module has listed — a PIN-unlocked browser chooses among what the
* providers offer, never an arbitrary id.
*/
async function chooseTarget(providerRef, destinationRef) {
const p = findProvider(providerRef);
if (!p) {
const s = String(providerRef ?? '').trim();
return { error: s ? `${s} isn't offering messaging right now — is the module enabled?` : 'Pick where to send first' };
}
if (!p.descriptor) await describe(p);
if (!p.descriptor) return { error: `${p.label} module ${p.error || 'is not answering'}` };
let d = findDestination(p, destinationRef);
if (!d && String(destinationRef ?? '').trim()) {
await describe(p); // a channel added a moment ago
d = findDestination(p, destinationRef);
}
if (!d) {
const s = String(destinationRef ?? '').trim();
return { error: s ? `${p.descriptor.label} has no destination "${s}" — pick another in Send as` : `Pick a ${p.descriptor.label} destination in Send as` };
}
return { provider: p, destination: d };
}
/* ── delivery: hand the message to the provider over loopback ── */
async function deliver(req, res, unlock, { provider, destination, text, what }) {
const now = Date.now();
if (now - unlock.lastSendAt < SEND_MIN_INTERVAL_MS) {
return sendJson(res, 429, { error: 'One message per second — try again', code: 'too_fast' });
}
const u = unlocks.get(unlock.token);
if (u) u.lastSendAt = now;
const max = provider.descriptor?.maxChars || DEFAULT_MAX_CHARS;
if (text.length > max) return sendJson(res, 400, { error: `Too long for ${provider.descriptor.label} — ${max} characters at most`, code: 'too_long' });
const label = provider.descriptor.label;
let answer;
try {
const r = await fetch(loopback(`/api/modules/${encodeURIComponent(provider.id)}/messaging/send`), {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
Accept: 'application/json',
Authorization: `Bearer ${unlock.token}`,
},
body: JSON.stringify({ destination: destination.id, text }),
signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
});
let body = {};
try { body = await r.json(); } catch { /* a non-JSON refusal */ }
answer = { status: r.status, body: body && typeof body === 'object' ? body : {} };
} catch (err) {
const message = `${label} module unreachable (${errorText(err)}) — not sent`;
log(`${what} → ${pairLabel(provider.descriptor, destination)} failed: ${message}`);
return sendJson(res, 502, { error: message, code: 'provider_unreachable' });
}
if (answer.status === 404) {
return sendJson(res, 502, { error: `${label} module isn't answering (disabled or restarting) — not sent`, code: 'provider_gone' });
}
if (answer.status < 200 || answer.status >= 300 || answer.body.ok === false) {
const message = String(answer.body.error || `${label} answered HTTP ${answer.status}`);
log(`${what} → ${pairLabel(provider.descriptor, destination)} failed: ${message}`);
const status = answer.status === 401 ? 401 : [400, 404, 429].includes(answer.status) ? answer.status : 502;
return sendJson(res, status, { error: message, code: answer.body.code || `http_${answer.status}` });
}
const preview = text.replace(/\s+/g, ' ').slice(0, 60);
log(`${what} → ${pairLabel(provider.descriptor, destination)}: "${preview}${text.length > 60 ? '…' : ''}"`);
scheduleDescribe(500); // the provider may have something new to say about itself
return sendJson(res, 200, {
ok: true,
provider: provider.id,
providerLabel: label,
destination: destination.id,
label: String(answer.body.label || destination.label),
role: provider.descriptor.destinationRole,
expiresAt: u ? u.expiresAt : unlock.expiresAt,
});
}
/* ── go ── */
const heartbeat = setInterval(() => {
for (const res of streams) {
try {
res.write(': ping\n\n');
} catch {
streams.delete(res);
}
}
}, HEARTBEAT_MS);
heartbeat.unref?.();
const sweeper = setInterval(sweepUnlocks, UNLOCK_SWEEP_MS);
sweeper.unref?.();
if (!shellPort) log('the shell did not say which port it serves on — this module needs ProdDash 1.4.0 or newer');
else {
if (pinEnabled && !pinOk) log('the PIN is on but not set (4–8 digits) — send tiles stay locked until it is, or until the PIN is switched off');
if (!pinEnabled) log('PIN off — send tiles send without asking');
discoverTimer = setTimeout(discover, DISCOVER_FIRST_MS);
discoverTimer.unref?.();
scheduleDescribe();
}
current = {
streams,
snapshot,
health,
wake,
verify,
sendGate,
unlock,
chooseTarget,
deliver,
resolveBinding,
bindingLabel,
quickReplies,
lock(req, res) {
const t = bearer(req);
if (t) unlocks.delete(t);
return sendJson(res, 200, { ok: true });
},
};
return {
stop() {
stopped = true;
clearTimeout(discoverTimer);
clearTimeout(describeTimer);
clearInterval(heartbeat);
clearInterval(sweeper);
unlocks.clear(); // an admin Apply locks every send tile
for (const res of streams) {
try { res.end(); } catch { /* already gone */ }
}
streams.clear();
if (current && current.streams === streams) current = null;
},
health,
};
},
/** The picker: the two send surfaces, one of each per dashboard. */
tiles() {
return [
{
id: 'send',
name: 'Send message',
description: 'A message to the transcript clicked last, on any platform',
single: true,
defaultSize: { w: 3, h: 3 },
minSize: { w: 2, h: 2 },
settings: { view: 'send' },
instanceSchema: {
showEmojis: { type: 'switch', label: 'Quick emojis', default: true },
},
},
{
id: 'quick',
name: 'Quick replies',
description: 'Preset buttons, one press each',
single: true,
defaultSize: { w: 3, h: 2 },
minSize: { w: 2, h: 1 },
settings: { view: 'quick' },
instanceSchema: {},
},
];
},
routes() {
const unmounted = (res) => sendJson(res, 503, { error: 'Send Message module is restarting — try again' });
return {
'GET /state': (req, res) => {
if (!current) return unmounted(res);
current.wake();
sendJson(res, 200, current.snapshot());
},
'GET /stream': (req, res) => {
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
});
res.write('retry: 3000\n\n');
if (!current) {
res.write(`event: state\ndata: ${JSON.stringify({ providers: [], pin: { enabled: true, set: false, length: 0 }, quickEmojis: [], status: { state: 'connecting', message: 'Send Message module is restarting…' } })}\n\n`);
return void res.end();
}
res.write(`event: state\ndata: ${JSON.stringify(current.snapshot())}\n\n`);
try { req.socket.setKeepAlive(true, 15000); } catch { /* gone */ }
current.streams.add(res);
current.wake();
req.on('close', () => current && current.streams.delete(res));
},
'POST /unlock': guard(async (req, res) => {
if (!current) return unmounted(res);
let body;
try {
body = await readJson(req);
} catch (err) {
return sendJson(res, 400, { error: err.message });
}
current.unlock(req, res, body.pin);
}),
'POST /lock': (req, res) => {
if (!current) return unmounted(res);
current.lock(req, res);
},
// Providers ask this over loopback before an upstream action: is this unlock good?
'GET /verify': (req, res) => {
if (!current) return unmounted(res);
const u = current.verify(bearer(req));
if (!u) return sendJson(res, 401, { ok: false, error: 'Locked — enter the PIN', code: 'locked' });
sendJson(res, 200, { ok: true, expiresAt: u.expiresAt });
},
// Labels, indexes and bindings only — the message text never leaves the server.
'GET /quick': (req, res) => {
if (!current) return unmounted(res);
const unlock = current.sendGate(req, res);
if (!unlock) return;
sendJson(res, 200, {
presets: current.quickReplies.map((q, index) => ({ index, label: q.label, target: current.bindingLabel(q.binding) })),
expiresAt: unlock.expiresAt,
});
},
'POST /send': guard(async (req, res) => {
if (!current) return unmounted(res);
const unlock = current.sendGate(req, res);
if (!unlock) return;
let body;
try {
body = await readJson(req);
} catch (err) {
return sendJson(res, 400, { error: err.message });
}
const text = String(body.text ?? '').replace(/\r\n/g, '\n').trim();
if (!text) return sendJson(res, 400, { error: 'Nothing to send' });
const target = await current.chooseTarget(body.provider, body.destination);
if (target.error) return sendJson(res, 400, { error: target.error, code: 'bad_target' });
await current.deliver(req, res, unlock, { ...target, text, what: 'sent' });
}),
'POST /quick': guard(async (req, res) => {
if (!current) return unmounted(res);
const unlock = current.sendGate(req, res);
if (!unlock) return;
let body;
try {
body = await readJson(req);
} catch (err) {
return sendJson(res, 400, { error: err.message });
}
const index = Math.trunc(Number(body.index));
const preset = Number.isInteger(index) ? current.quickReplies[index] : null;
if (!preset) return sendJson(res, 404, { error: 'No such quick reply — the list may have changed in Admin' });
// A bound reply ignores the selection; an unbound one needs it.
let target = current.resolveBinding(preset.binding);
if (!target) target = await current.chooseTarget(body.provider, body.destination);
if (target.error) return sendJson(res, 400, { error: target.error, code: 'bad_target' });
await current.deliver(req, res, unlock, { ...target, text: preset.message, what: `quick reply "${preset.label}"` });
}),
};
},
};
+527
View File
@@ -0,0 +1,527 @@
/* Send Message module — scoped to its tiles, shell variables only.
The gate (PIN pad), the compose box and the preset grid were the Slack
module's send surfaces until 1.3.0; they live here now, for every platform. */
[data-module="send-message"] .sm-wrap {
--sm-size: 14px;
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
container-type: size;
font-size: var(--sm-size);
color: var(--text);
}
[data-module="send-message"] .sm-wrap:focus { outline: none; }
[data-module="send-message"] [hidden] { display: none !important; }
/* ── the gate ── */
[data-module="send-message"] .sm-gate,
[data-module="send-message"] .sm-compose {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
padding: 6px 10px;
overflow: auto;
}
[data-module="send-message"] .sm-note {
margin: auto;
padding: 10px;
text-align: center;
color: var(--muted);
font-size: 0.9em;
line-height: 1.45;
}
[data-module="send-message"] .sm-note.is-error { color: var(--danger); }
/* The pad never shrinks below its content (min-height stays `auto` on it
and on the key grid) — a shrunken grid would spill its rows under the
message line, which then swallows the taps. A tile too short for it
scrolls instead (.sm-gate has overflow: auto). */
[data-module="send-message"] .sm-pad {
flex: 1 1 auto;
display: flex;
flex-direction: column;
gap: 4px;
max-width: 340px;
width: 100%;
margin: 0 auto;
}
[data-module="send-message"] .sm-pad.sm-shake { animation: sm-shake 0.4s ease; }
@keyframes sm-shake {
10%, 90% { transform: translateX(-2px); }
20%, 80% { transform: translateX(3px); }
30%, 50%, 70% { transform: translateX(-5px); }
40%, 60% { transform: translateX(5px); }
}
/* one line: "Enter PIN · Slack · as Apollo Beach → #production" */
[data-module="send-message"] .sm-pad-head {
flex: none;
text-align: center;
font-size: 0.8em;
color: var(--muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-module="send-message"] .sm-pad-head b { font-weight: 700; color: var(--text); }
/* The dots ride on a real numeric input: tapping them focuses it, which is
what raises a phone's keyboard; on a desktop the keyboard types into it
directly. The input itself is invisible — the dots are its display. */
[data-module="send-message"] .sm-field {
flex: none;
position: relative;
height: 24px;
cursor: text;
}
[data-module="send-message"] .sm-dots {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
pointer-events: none;
}
[data-module="send-message"] .sm-dot {
width: 11px;
height: 11px;
border-radius: 50%;
border: 2px solid var(--muted);
transition: background 0.12s, border-color 0.12s;
}
[data-module="send-message"] .sm-dot.on { background: var(--accent); border-color: var(--accent); }
[data-module="send-message"] .sm-pin-input {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
border: 0;
border-radius: 8px;
background: transparent;
color: transparent;
caret-color: transparent;
font: inherit;
text-align: center;
outline: none;
-webkit-text-fill-color: transparent;
}
[data-module="send-message"] .sm-pin-input::selection { background: transparent; }
[data-module="send-message"] .sm-pin-input:focus-visible { box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 45%, transparent); }
[data-module="send-message"] .sm-keys {
flex: 1 1 auto;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(4, minmax(24px, 1fr));
gap: 4px;
}
[data-module="send-message"] .sm-key {
min-width: 0;
min-height: 24px;
border: 1px solid var(--border);
border-radius: 10px;
background: color-mix(in srgb, var(--text) 5%, var(--panel));
color: var(--text);
font: inherit;
font-size: clamp(13px, 9cqh, 26px);
font-weight: 600;
font-variant-numeric: tabular-nums;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
transition: background 0.1s;
}
[data-module="send-message"] .sm-key:hover { background: var(--border); }
[data-module="send-message"] .sm-key:active { background: color-mix(in srgb, var(--accent) 30%, var(--panel)); }
[data-module="send-message"] .sm-key svg { width: 1.1em; height: 1.1em; }
[data-module="send-message"] .sm-key-back { color: var(--muted); }
[data-module="send-message"] .sm-key-blank { visibility: hidden; }
[data-module="send-message"] .sm-pad.is-busy .sm-keys { opacity: 0.6; pointer-events: none; }
[data-module="send-message"] .sm-pad-msg {
flex: none;
min-height: 1.1em;
text-align: center;
font-size: 0.78em;
line-height: 1.1;
color: var(--muted);
}
[data-module="send-message"] .sm-pad-msg.is-error { color: var(--danger); font-weight: 600; }
/* A tile too short for the keypad (the smallest Send message / Quick replies
tiles) shows the dots and a hint instead — the dots still take a tap and
the keyboard, and a taller tile brings the keys back. .sm-wrap is the size
container the height is measured against. */
[data-module="send-message"] .sm-pad-hint {
display: none;
flex: none;
text-align: center;
font-size: 0.78em;
line-height: 1.3;
color: var(--muted);
}
@container (max-height: 176px) {
[data-module="send-message"] .sm-pad .sm-keys { display: none; }
[data-module="send-message"] .sm-pad .sm-pad-hint { display: block; }
[data-module="send-message"] .sm-pad { justify-content: center; }
}
/* ── unlocked ── */
[data-module="send-message"] .sm-compose { gap: 6px; }
[data-module="send-message"] .sm-compose-head {
flex: none;
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
font-size: 0.8em;
color: var(--muted);
}
[data-module="send-message"] .sm-sending {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-module="send-message"] .sm-lock-link {
flex: none;
padding: 1px 8px;
border: 1px solid var(--border);
border-radius: 999px;
background: none;
color: var(--muted);
font: inherit;
font-size: 0.9em;
cursor: pointer;
}
[data-module="send-message"] .sm-lock-link:hover { color: var(--text); background: var(--border); }
/* The box takes whatever the quick emoji rows leave it, down to one line. */
[data-module="send-message"] .sm-box {
flex: 1 1 auto;
min-height: 0;
position: relative;
display: flex;
flex-direction: column;
}
[data-module="send-message"] .sm-input {
flex: 1 1 auto;
min-height: calc(1.4em + 16px);
width: 100%;
resize: none;
padding: 7px 9px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg);
color: var(--text);
font: inherit;
line-height: 1.4;
}
[data-module="send-message"] .sm-input:focus { outline: none; border-color: var(--accent); }
/* The grip: a small pill centred on the box's bottom edge, straddling the
border. Drag it up for more emoji rows. It is positioned over the box, so
it adds no height between the box and the keys. */
[data-module="send-message"] .sm-grip {
position: absolute;
left: 50%;
bottom: -6px;
transform: translateX(-50%);
width: 44px;
height: 12px;
display: flex;
align-items: center;
justify-content: center;
cursor: ns-resize;
touch-action: none;
z-index: 1;
-webkit-tap-highlight-color: transparent;
}
[data-module="send-message"] .sm-grip::before {
content: "";
width: 26px;
height: 4px;
border-radius: 2px;
background: var(--muted);
box-shadow: 0 0 0 1.5px var(--panel);
transition: background 0.12s, width 0.12s;
}
[data-module="send-message"] .sm-grip:hover::before,
[data-module="send-message"] .sm-grip:focus-visible::before,
[data-module="send-message"] .sm-grip.is-dragging::before { background: var(--accent); width: 34px; }
[data-module="send-message"] .sm-grip:focus { outline: none; }
/* The smallest Send message tile (two grid rows, a 110px body): the compose
area tightens its padding, gaps and the box's one-line minimum so that two
rows of quick emoji keys still fit under the box. .sm-wrap is the size
container the height is measured against. */
@container (max-height: 150px) {
[data-module="send-message"] .sm-compose { padding: 3px 10px; gap: 2px; }
[data-module="send-message"] .sm-input { padding: 4px 9px; line-height: 1.25; min-height: calc(1.25em + 10px); }
}
/* The Send button and the outcome icon sit right under the box, level with
the first row of keys; further rows of keys run on below them. */
[data-module="send-message"] .sm-compose-foot {
flex: none;
display: flex;
align-items: flex-start;
gap: 8px;
min-height: 1.6em;
min-width: 0;
}
/* the outcome of a send, as an icon beside the Send button: a check (accent
— green on the default theme) or a blocked sign (danger), fading out as
its five seconds run down; the sentence is the tooltip. The slot keeps its
width while empty so the Send button never shifts. */
[data-module="send-message"] .sm-feedback {
flex: none;
width: 1.45em;
min-height: 2.1em; /* the Send button's height, so the icon centres on it */
display: flex;
align-items: center;
justify-content: center;
}
[data-module="send-message"] .sm-countdown { align-self: center; }
[data-module="send-message"] .sm-feedback svg {
width: 1.45em;
height: 1.45em;
flex: none;
animation: sm-pop 0.18s ease-out, sm-fade 0.6s ease-in 4.4s forwards;
}
[data-module="send-message"] .sm-feedback.is-ok { color: var(--accent); }
[data-module="send-message"] .sm-feedback.is-error { color: var(--danger); cursor: help; }
/* the Quick replies foot has no Send button: the icon keeps to the right edge */
[data-module="send-message"] .sm-compose-foot.is-quick { justify-content: flex-end; }
@keyframes sm-pop {
from { transform: scale(0.6); opacity: 0; }
to { transform: none; opacity: 1; }
}
@keyframes sm-fade {
to { opacity: 0; }
}
[data-module="send-message"] .sm-countdown {
flex: none;
font-size: 0.75em;
color: var(--warn);
font-variant-numeric: tabular-nums;
}
[data-module="send-message"] .sm-sendbtn {
flex: none;
padding: 6px 16px;
border: none;
border-radius: 8px;
background: var(--accent);
color: var(--accent-text);
font: inherit;
font-weight: 700;
cursor: pointer;
}
[data-module="send-message"] .sm-sendbtn:hover { background: color-mix(in srgb, var(--accent) 85%, var(--text)); }
[data-module="send-message"] .sm-sendbtn:disabled { opacity: 0.6; cursor: default; }
/* quick emojis: one press each sends it as a message of its own. The keys
take whatever room the foot has to the left of the outcome icon and the
Send button. As one row (the default) they scroll sideways when the tile
is narrow (trackpad, touch, or the wheel — client.js turns a vertical
wheel into a horizontal scroll) while Send keeps its place; with more
rows allotted from the grip they wrap, --sm-quick-rows rows tall. One key
is --sm-key square, so a row's pitch is --sm-key plus the 4px gap. */
[data-module="send-message"] .sm-emoji-sendrow {
--sm-quick-rows: 1;
--sm-key: calc(2.31 * var(--sm-size));
flex: 1 1 auto;
display: flex;
gap: 4px;
min-width: var(--sm-key);
overflow-x: auto;
overflow-y: hidden;
overscroll-behavior-x: contain;
scrollbar-width: none;
}
[data-module="send-message"] .sm-emoji-sendrow.is-multi {
flex-wrap: wrap;
align-content: flex-start;
height: calc(var(--sm-quick-rows) * var(--sm-key) + (var(--sm-quick-rows) - 1) * 4px);
overflow-x: hidden;
overflow-y: auto;
overscroll-behavior: contain;
}
[data-module="send-message"] .sm-emoji-sendrow::-webkit-scrollbar { display: none; }
/* more keys off one edge or the other: that edge fades out (client.js sets the classes) */
[data-module="send-message"] .sm-emoji-sendrow.has-more { mask-image: linear-gradient(to right, #000 calc(100% - 16px), transparent); }
[data-module="send-message"] .sm-emoji-sendrow.has-less { mask-image: linear-gradient(to right, transparent, #000 16px); }
[data-module="send-message"] .sm-emoji-sendrow.has-less.has-more { mask-image: linear-gradient(to right, transparent, #000 16px, #000 calc(100% - 16px), transparent); }
[data-module="send-message"] .sm-emoji-sendrow:empty { display: none; }
[data-module="send-message"] .sm-emoji-send {
flex: none;
width: var(--sm-key);
height: var(--sm-key);
padding: 0;
border: 1px solid var(--border);
border-radius: 8px;
background: color-mix(in srgb, var(--text) 5%, var(--panel));
color: var(--text);
font: inherit;
font-size: 1.1em;
line-height: 1;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
transition: background 0.1s, border-color 0.1s;
}
[data-module="send-message"] .sm-emoji-send:hover { border-color: var(--accent); background: var(--border); }
[data-module="send-message"] .sm-emoji-send:active { background: color-mix(in srgb, var(--accent) 30%, var(--panel)); }
[data-module="send-message"] .sm-emoji-send.is-busy { opacity: 0.6; }
[data-module="send-message"] .sm-emoji-send.is-sent { background: var(--accent); border-color: transparent; }
[data-module="send-message"] .sm-emoji-char { font-size: 1em; line-height: 1; }
/* a :code: or a word rather than one emoji: a wider pill of small text */
[data-module="send-message"] .sm-emoji-send.is-text {
width: auto;
max-width: 7em;
padding: 0 7px;
}
[data-module="send-message"] .sm-emoji-send.is-text .sm-emoji-char {
font-size: 0.72em;
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* the preset grid: big targets, labels wrap */
[data-module="send-message"] .sm-grid {
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(150px, 100%), 1fr));
grid-auto-rows: minmax(44px, auto);
gap: 6px;
align-content: start;
overflow-y: auto;
}
[data-module="send-message"] .sm-grid .sm-note { grid-column: 1 / -1; }
[data-module="send-message"] .sm-quick {
min-width: 0;
min-height: 44px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 2px;
padding: 6px 10px;
border: 1px solid var(--border);
border-radius: 10px;
background: color-mix(in srgb, var(--accent) 12%, var(--panel));
color: var(--text);
font: inherit;
font-weight: 600;
line-height: 1.25;
text-align: center;
cursor: pointer;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
transition: background 0.1s;
}
[data-module="send-message"] .sm-quick:hover { background: color-mix(in srgb, var(--accent) 22%, var(--panel)); }
[data-module="send-message"] .sm-quick:active { background: color-mix(in srgb, var(--accent) 40%, var(--panel)); }
[data-module="send-message"] .sm-quick.is-busy { opacity: 0.7; }
[data-module="send-message"] .sm-quick.is-sent {
background: var(--accent);
border-color: transparent;
color: var(--accent-text);
}
[data-module="send-message"] .sm-quick-label { overflow-wrap: anywhere; }
[data-module="send-message"] .sm-quick-chan {
font-size: 0.72em;
font-weight: 500;
color: var(--muted);
}
/* sent: the words step aside for a check, in the button itself */
[data-module="send-message"] .sm-quick { position: relative; }
[data-module="send-message"] .sm-quick-check {
position: absolute;
inset: 0;
display: none;
align-items: center;
justify-content: center;
}
[data-module="send-message"] .sm-quick-check svg { width: 1.6em; height: 1.6em; animation: sm-pop 0.18s ease-out; }
[data-module="send-message"] .sm-quick.is-sent .sm-quick-label,
[data-module="send-message"] .sm-quick.is-sent .sm-quick-chan { visibility: hidden; }
[data-module="send-message"] .sm-quick.is-sent .sm-quick-check { display: flex; }
/* ── the Send as menu ──
The menu container is created and positioned by the shell (.tile-menu);
it hangs off the body under a [data-module] host, so scoping still applies. */
[data-module="send-message"] .sm-menu { min-width: 180px; max-height: min(60vh, 420px); overflow-y: auto; }
[data-module="send-message"] .sm-menu-head {
padding: 6px 9px 2px;
font-size: 11px;
color: var(--muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
[data-module="send-message"] .sm-menu-head b { color: var(--text); font-weight: 700; }
[data-module="send-message"] .sm-menu-head.is-error b { color: var(--danger); }
[data-module="send-message"] .sm-menu-head.is-muted b { color: var(--muted); }
[data-module="send-message"] .sm-menu-head + .sm-menu-head,
[data-module="send-message"] .sm-menu-item + .sm-menu-head,
[data-module="send-message"] .sm-menu-note + .sm-menu-head {
margin-top: 4px;
border-top: 1px solid var(--border);
padding-top: 8px;
}
[data-module="send-message"] .sm-menu-note {
padding: 4px 9px 6px;
font-size: 11px;
color: var(--muted);
max-width: 260px;
line-height: 1.35;
}
[data-module="send-message"] .sm-menu-item {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 6px 9px;
background: none;
border: none;
border-radius: 6px;
color: var(--text);
font-size: 12px;
font-family: inherit;
text-align: left;
cursor: pointer;
white-space: nowrap;
}
[data-module="send-message"] .sm-menu-item:hover { background: var(--border); }
[data-module="send-message"] .sm-menu-item .check {
width: 14px;
flex: none;
color: var(--accent);
font-weight: 700;
visibility: hidden;
}
[data-module="send-message"] .sm-menu-item.on .check { visibility: visible; }
[data-module="send-message"] .sm-menu-item.remembered .check { visibility: visible; color: var(--muted); opacity: 0.6; }
[data-module="send-message"] .sm-menu-item .name { font-weight: 600; }
[data-module="send-message"] .sm-menu-item.on .name { color: var(--accent); }
+114 -782
View File
File diff suppressed because it is too large Load Diff
+9 -43
View File
@@ -1,9 +1,12 @@
{
"id": "slack",
"name": "Slack",
"version": "1.2.1",
"version": "1.3.0",
"proddash": ">=1.4.0",
"description": "Live transcripts of this location's Slack channels, plus PIN-protected sending as the location",
"description": "Live transcripts of this location's Slack channels; messages and reactions leave as the location through the Send Message module",
"provides": [
"messaging"
],
"client": "client.js",
"server": "server.js",
"style": "style.css",
@@ -18,14 +21,10 @@
"configGroups": {
"Slack account": {
"collapsed": "whenSet",
"help": "Create a Slack app in the workspace (api.slack.com/apps → Create New App → From scratch) and, under OAuth & Permissions → User Token Scopes, add channels:history, channels:read, groups:history, groups:read, chat:write, users:read, reactions:write (emoji reactions) and emoji:read (the workspace's custom emoji). Sign in to Slack as this location's account — the one named for the campus — open the app's OAuth & Permissions page and press Install to Workspace (or Reinstall to Workspace), then copy the User OAuth Token (xoxp-…) it shows and paste it here: messages from this machine are then literally from the location. A bot token (xoxb-…) works too; it posts as the app, with \"Send as\" naming the location."
"help": "Create a Slack app in the workspace (api.slack.com/apps → Create New App → From scratch) and, under OAuth & Permissions → User Token Scopes, add channels:history, channels:read, groups:history, groups:read, chat:write, users:read, reactions:write (emoji reactions) and emoji:read (the workspace's custom emoji). Sign in to Slack as this location's account — the one named for the campus — open the app's OAuth & Permissions page and press Install to Workspace (or Reinstall to Workspace), then copy the User OAuth Token (xoxp-…) it shows and paste it here: messages sent from this machine through the Send Message module are then literally from the location. A bot token (xoxb-…) works too; it posts as the app, with \"Send as\" naming the location."
},
"Channels": {
"help": "Every channel picked here becomes its own transcript tile in the + picker, titled with the channel's name. The Send message and Quick replies tiles post to whichever transcript was clicked last — its bottom edge lights up in the accent colour — and until one is clicked, to the first channel here whose transcript is on that dashboard: with a single transcript up, that one. A send never goes to a channel the dashboard is not showing. Only channels the account has joined are listed; join one in Slack first. Each channel is read on its own schedule, all of them together kept inside Slack's rate limit."
},
"Sending": {
"toggle": "sendEnabled",
"help": "Messages and emoji reactions leave this machine only after the PIN is entered — on a Send or Quick replies tile, or in the reaction menu a right-click on a transcript message opens. One PIN unlocks every Slack tile on that dashboard page until Auto-lock minutes pass without a send; a reload asks again. Sending stays refused until a 4–8 digit PIN is set here. A message goes to the channel of the transcript clicked last. Quick emojis are sent with one press from the Send message tile and offered first when reacting. Quick replies are one per line, Label | Message, with an optional | #channel-name to bind that one to a channel: a bound reply always goes there, whichever transcript is selected."
"help": "Every channel picked here becomes its own transcript tile in the + picker, titled with the channel's name, and a destination the Send Message module's tiles can post to: a click on a transcript points them at its channel (its bottom edge lights up in the accent colour) — that is the only way a Slack channel is chosen; the Send as menu is for platforms that send as an identity. Only channels the account has joined are listed; join one in Slack first. Each channel is read on its own schedule, all of them together kept inside Slack's rate limit."
}
},
"configSchema": {
@@ -41,7 +40,7 @@
"label": "Send as",
"default": "",
"group": "Slack account",
"help": "Only used with a bot token — a user token always sends as its own account; needs the chat:write.customize scope."
"help": "Only used with a bot token — a user token always sends as its own account; needs the chat:write.customize scope. Applies to messages the Send Message module posts through this account."
},
"channels": {
"type": "multiselect",
@@ -49,7 +48,7 @@
"default": [],
"group": "Channels",
"optionsRoute": "/channels",
"help": "One transcript tile per channel; until a transcript is clicked, sends go to the first channel here that the dashboard is actually showing. Only channels the account has joined are listed — join one in Slack first."
"help": "One transcript tile per channel, and one destination each for the Send Message module. Only channels the account has joined are listed — join one in Slack first."
},
"pollSeconds": {
"type": "number",
@@ -69,39 +68,6 @@
"label": "Thread replies",
"default": false,
"group": "Transcript"
},
"sendEnabled": {
"type": "switch",
"label": "Sending",
"default": false,
"group": "Sending"
},
"pin": {
"type": "password",
"label": "PIN",
"default": "",
"group": "Sending",
"help": "4–8 digits; the pad unlocks by itself once they are all in."
},
"pinIdleMinutes": {
"type": "number",
"label": "Auto-lock (min)",
"default": 10,
"group": "Sending"
},
"quickReplies": {
"type": "text",
"label": "Quick replies",
"default": "",
"group": "Sending",
"help": "One per line: Label | Message. Add | #channel-name to bind one to a channel — it then ignores which transcript is selected."
},
"quickEmojis": {
"type": "string",
"label": "Quick emojis",
"default": "👍 🙏 ✅ 👀 🎉",
"group": "Sending",
"help": "Emoji or :codes: separated by spaces, eight at most. One press sends one from the Send message tile; they also head the reaction menu."
}
},
"instanceSchema": {
+108 -339
View File
@@ -6,26 +6,29 @@
* One Slack Web API connection per ProdDash machine — the campus's shared
* location account (a user token), or a bot — polling the configured
* channels' recent history (one poller per channel, all inside one rate
* budget) and fanning the lot out to every tile over SSE, plus PIN-gated
* sending from this machine so a message reads as coming from the location.
* Browsers never talk to Slack; the token and the PIN stay here.
* budget) and fanning the lot out to every tile over SSE. Browsers never
* talk to Slack; the token stays here.
*
* GET /state snapshot: identity, channels (keyed by id), sending state
* GET /stream SSE `state` events (change-detected, heartbeated)
* GET /channels admin multiselect options — the channels the account is in
* POST /unlock { pin } → { token, expiresAt } (constant-time, lockout)
* POST /lock Bearer → forget that unlock token
* GET /quick Bearer → preset labels + indexes (never the message text)
* POST /send Bearer, { text, channel } → chat.postMessage
* POST /react Bearer, { channel, ts, name, remove? } → reactions.add / .remove
* GET /emoji { standard: {code: emoji}, custom: {name: {url}|{char}}, version }
* Sending is not this module's: the Send Message module owns the PIN, the
* send tiles and the quick replies, and hands a message to this module's
* POST /messaging/send over loopback, so it still leaves through this one
* connection, as the location. Every outbound action — a message, an emoji
* reaction from a transcript — carries that module's unlock token and is
* checked with it (GET /verify, over loopback) before Slack is asked. This
* module has no PIN of its own and cannot post without one entered there.
*
* GET /state snapshot: identity, channels (keyed by id)
* GET /stream SSE `state` events (change-detected, heartbeated)
* GET /channels admin multiselect options — the channels the account is in
* GET /messaging the configured channels as destinations (the module guide's contract)
* POST /messaging/send Bearer (Send Message unlock), { destination, text } → chat.postMessage
* POST /react Bearer (Send Message unlock), { channel, ts, name, remove? } → reactions.add / .remove
* GET /emoji { standard: {code: emoji}, custom: {name: {url}|{char}}, version }
* GET /emoji-image/<name>, GET /avatar/<u/USER|b/BOT> images proxied from Slack's CDN
* POST /quick Bearer, { index, channel } → post that preset
*
* `channel` on /send and /quick must be one of the configured channel ids
* (400 otherwise): a PIN-unlocked browser chooses among the admin's channels,
* never an arbitrary one. A quick reply with its own "| #channel" ignores the
* request's channel — an explicit binding wins over the selection.
* `destination` / `channel` must be one of the configured channel ids (400
* otherwise): an unlocked browser chooses among the admin's channels, never
* an arbitrary one.
*
* Rate budget. Slack allows an internal app roughly 50+ conversations.history
* calls a minute per token (Tier 3). The module keeps all its pollers under
@@ -46,8 +49,6 @@
* tools/slack-mock.js for development.
*/
const crypto = require('crypto');
const DEFAULT_API_BASE = 'https://slack.com/api';
const API_BASE = String(process.env.SLACK_API_BASE || DEFAULT_API_BASE).replace(/\/+$/, '');
@@ -92,14 +93,11 @@ const FIRST_READ_STAGGER_MS = 250;
const MIN_SLOT_GAP_MS = 200;
/** tiles() waits at most this long for the first conversations.info answers after boot. */
const NAMES_WAIT_MS = 1500;
const PIN_RE = /^\d{4,8}$/;
const PIN_MAX_WRONG = 5;
const PIN_LOCKOUT_MS = 30000;
const SEND_MIN_INTERVAL_MS = 1000;
const MAX_TEXT_CHARS = 4000;
const BODY_LIMIT_BYTES = 64 * 1024;
const DEFAULT_ICON = ':satellite_antenna:';
const UNLOCK_SWEEP_MS = 30000;
/** The module that owns the PIN and the unlock tokens — see verifyUnlock(). */
const SENDER_ID = 'send-message';
/** Set by init(), read by routes() and tiles() — all rebuilt together on remount. */
let current = null;
@@ -238,7 +236,6 @@ const EMOJI_NAMES = require('./emoji.json').names;
const EMOJI_CODE_RE = /^([a-z0-9_+-]{1,100})(?:::(skin-tone-[2-6]))?$/i;
/** How long the workspace's custom emoji list is believed before emoji.list is asked again. */
const EMOJI_LIST_TTL_MS = 60 * 60 * 1000;
let emojiReverse = null; // character (variation selector stripped) → the name Slack knows it by
/** The character for a standard code, '' for a custom or unknown one. */
function emojiChar(code) {
@@ -250,45 +247,6 @@ function emojiChar(code) {
return tone ? base.replace(/\uFE0F/g, '') + tone : base;
}
/** The short name for a character ('' if Slack has none) — a reaction needs the name, not the glyph. */
function emojiName(char) {
if (!emojiReverse) {
emojiReverse = new Map();
for (const [name, ch] of Object.entries(EMOJI_NAMES)) {
if (name.startsWith('skin-tone-')) continue;
const key = ch.replace(/\uFE0F/g, '');
if (!emojiReverse.has(key)) emojiReverse.set(key, name); // keys are sorted: "+1" wins over "thumbsup"
}
}
const s = String(char || '').replace(/\uFE0F/g, '');
const tone = /[\u{1F3FB}-\u{1F3FF}]$/u.exec(s);
if (tone) {
const base = emojiReverse.get(s.slice(0, -tone[0].length));
const toneName = Object.keys(EMOJI_NAMES).find((n) => n.startsWith('skin-tone-') && EMOJI_NAMES[n] === tone[0]);
return base && toneName ? `${base}::${toneName}` : '';
}
return emojiReverse.get(s) || '';
}
/**
* The admin's "Quick emojis" — "👍 🙏 :white_check_mark: :party_parrot:" →
* [{ name, char }]. A standard emoji gets both; a custom code keeps its name
* and no character (the browser draws the image); a glyph Slack has no name
* for can be sent but not reacted with (name ''). Eight at most.
*/
function parseQuickEmojis(text) {
const out = [];
for (const tok of String(text || '').split(/\s+/).filter(Boolean)) {
const code = /^:([^:\s]+(?:::skin-tone-[2-6])?):$/i.exec(tok);
if (code) {
const name = code[1].toLowerCase();
if (EMOJI_CODE_RE.test(name)) out.push({ name, char: emojiChar(name) });
} else out.push({ name: emojiName(tok), char: tok });
if (out.length >= 8) break;
}
return out;
}
/* Avatars and custom emoji are images on Slack's CDN; browsers only talk to
ProdDash, so the module fetches them and keeps them a while. */
const IMAGE_CACHE_MAX = 400;
@@ -453,38 +411,30 @@ function bearer(req) {
return m ? m[1] : '';
}
function clientIp(req) {
return String(req.socket?.remoteAddress || '');
}
/** Constant-time PIN compare (lengths are folded in after the timing-safe step). */
function pinMatches(given, expected) {
const a = Buffer.alloc(16);
const b = Buffer.alloc(16);
a.write(String(given).slice(0, 16));
b.write(String(expected).slice(0, 16));
const same = crypto.timingSafeEqual(a, b);
return same && given.length === expected.length;
}
/**
* "Label | Message | #channel" per line. A line with no "|" is both its label
* and its message; the channel (optional) is a name the account can see —
* a reply that carries one always goes there, whatever transcript is selected.
* Is the unlock token on this request good? Only the Send Message module
* knows — it owns the PIN — so ask it over loopback. Answers { ok: true,
* expiresAt } or { ok: false, status, error, code } ready to send back.
*/
function parseQuickReplies(text) {
const out = [];
for (const rawLine of String(text || '').split(/\r?\n/)) {
const line = rawLine.trim();
if (!line) continue;
const parts = line.split('|').map((p) => p.trim());
const label = parts[0];
const message = parts.length > 1 && parts[1] ? parts[1] : label;
const channel = parts.length > 2 ? parts[2].replace(/^#/, '') : '';
if (!label || !message) continue;
out.push({ label, message, channel });
async function verifyUnlock(req, shellPort) {
const token = bearer(req);
if (!token) return { ok: false, status: 401, error: 'Locked — enter the PIN', code: 'locked' };
if (!shellPort) return { ok: false, status: 503, error: 'This ProdDash cannot verify a PIN (needs 1.4.0 or newer)', code: 'no_shell_port' };
let res;
try {
res = await fetch(`http://127.0.0.1:${shellPort}/api/modules/${SENDER_ID}/verify`, {
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
signal: AbortSignal.timeout(5000),
});
} catch (err) {
return { ok: false, status: 502, error: `Cannot reach the Send Message module (${err.cause?.code || err.message})`, code: 'sender_unreachable' };
}
return out;
if (res.status === 404) return { ok: false, status: 503, error: 'Install the Send Message module to send or react from a dashboard', code: 'no_sender' };
let body = {};
try { body = await res.json(); } catch { /* a non-JSON refusal */ }
if (res.status === 401 || body?.ok === false) return { ok: false, status: 401, error: body?.error || 'Locked — enter the PIN', code: body?.code || 'locked' };
if (!res.ok) return { ok: false, status: 502, error: `Send Message module answered HTTP ${res.status}`, code: 'sender_error' };
return { ok: true, expiresAt: Number(body?.expiresAt) || 0 };
}
const SYSTEM_SUBTYPES = new Set([
@@ -497,8 +447,9 @@ const SYSTEM_SUBTYPES = new Set([
/* ── the module ─────────────────────────────────────────────────────── */
module.exports = {
init({ config, log }) {
init({ config, log, shell }) {
/* ── config ── */
const shellPort = Number(shell && shell.port) || 0;
const token = String(config.token || '').trim();
const sendAs = String(config.sendAs || '').trim();
const channelIds = configuredChannels(config);
@@ -508,12 +459,6 @@ module.exports = {
const historyCount = Math.min(HISTORY_MAX, Math.max(HISTORY_MIN, Math.trunc(Number(config.historyCount)) || 40));
const includeReplies = Boolean(config.includeReplies);
const threadFetchesPerPoll = Math.max(1, Math.floor(THREAD_FETCHES_PER_POLL / Math.max(1, channelIds.length)));
const sendEnabled = Boolean(config.sendEnabled);
const pin = String(config.pin || '').trim();
const pinOk = PIN_RE.test(pin);
const idleMs = Math.min(240, Math.max(1, Number(config.pinIdleMinutes) || 10)) * 60 * 1000;
const quickReplies = parseQuickReplies(config.quickReplies);
const quickEmojis = parseQuickEmojis(config.quickEmojis);
/* ── state (all inside this closure so a re-init starts clean) ── */
let stopped = false;
@@ -531,8 +476,6 @@ module.exports = {
let lastInterest = Date.now();
const epoch = Date.now(); // the phase-locked slots count from here
const streams = new Set();
const unlocks = new Map(); // token -> { expiresAt, lastSendAt, ip }
const pinAttempts = new Map(); // ip -> { count, lockedUntil }
/**
* One channel's poller: its own window, thread cache, timer and error,
@@ -724,21 +667,6 @@ module.exports = {
}
}
/** "#name" or a channel id → the channel id, or '' when the account can't see it. */
async function resolveChannelRef(ref) {
const s = String(ref || '').trim();
if (!s) return '';
if (/^[CG][A-Z0-9]{6,}$/.test(s)) return s;
const name = s.replace(/^#/, '').toLowerCase();
let list = await loadChannelList();
let hit = list.find((c) => c.name.toLowerCase() === name);
if (!hit) {
list = await loadChannelList(true);
hit = list.find((c) => c.name.toLowerCase() === name);
}
return hit ? hit.id : '';
}
/* ── normalisation ── */
function nameFor(m) {
if (m.subtype === 'bot_message' && m.username) return String(m.username);
@@ -845,7 +773,7 @@ module.exports = {
return { state: 'ok', message: `${labelOf(ch)} · live` };
}
/** The admin health line: who, which channels, what's wrong, sending. */
/** The admin health line: who, which channels, what's wrong. */
function health() {
if (!token) return { status: 'error', message: 'No Slack token — paste the location account’s User OAuth Token in Admin → Slack' };
if (authError) return { status: 'error', message: authError };
@@ -854,9 +782,8 @@ module.exports = {
const list = [...pollers.values()];
if (!list.length) return { status: 'error', message: `${who} · pick channels in Admin → Slack → Channels` };
const names = list.map(labelOf).join(', ');
const sending = !sendEnabled ? 'sending off' : !pinOk ? 'sending on — set a 4–8 digit PIN' : 'sending on';
const problems = [...new Set(list.filter((ch) => ch.error).map((ch) => (ch.error.includes(labelOf(ch)) ? ch.error : `${labelOf(ch)}: ${ch.error}`)))];
if (problems.length) return { status: 'error', message: `${who} · ${names} · ${problems.join(' · ')} · ${sending}` };
if (problems.length) return { status: 'error', message: `${who} · ${names} · ${problems.join(' · ')}` };
if (list.some((ch) => !ch.lastPollAt)) return { status: 'connecting', message: `${who} · ${names} · first read…` };
const stale = list.filter(isStale);
if (stale.length) {
@@ -864,7 +791,7 @@ module.exports = {
return { status: 'connecting', message: `${who} · ${names} · ${ago}` };
}
const cadence = intervalMs > pollMs ? ` · every ${intervalMs / 1000} s (rate budget)` : '';
return { status: 'ok', message: `${who} · ${names}${cadence} · ${sending}` };
return { status: 'ok', message: `${who} · ${names}${cadence}` };
}
function channelView(ch) {
@@ -899,10 +826,6 @@ module.exports = {
includeReplies,
historyCount,
pollSeconds: intervalMs / 1000,
sending: { enabled: sendEnabled, pinSet: pinOk, idleMinutes: idleMs / 60000 },
// the pad submits by itself once this many digits are in (never the PIN)
pinLength: pinOk ? pin.length : 0,
quickEmojis,
emojiVersion,
status: { state: h.status, message: h.message, lastPollAt },
apiBase: API_BASE,
@@ -1135,57 +1058,17 @@ module.exports = {
]);
}
/* ── unlock tokens ── */
function sweepUnlocks() {
const now = Date.now();
for (const [t, u] of unlocks) if (u.expiresAt <= now) unlocks.delete(t);
for (const [ip, a] of pinAttempts) if (a.lockedUntil && a.lockedUntil <= now && !a.count) pinAttempts.delete(ip);
}
/** The unlock behind a request, or null (the client re-asks for the PIN). */
function unlockFor(req) {
const t = bearer(req);
const u = t ? unlocks.get(t) : null;
if (!u) return null;
if (u.expiresAt <= Date.now()) {
unlocks.delete(t);
return null;
}
return { token: t, ...u };
}
/** Everything a send needs before Slack is asked; answers the response itself when refusing. */
function sendGate(req, res) {
if (!sendEnabled) {
sendJson(res, 403, { error: 'Sending is off — turn it on in Admin → Slack → Sending', code: 'sending_off' });
return null;
}
if (!pinOk) {
sendJson(res, 403, { error: 'Set a PIN in Admin → Slack → Sending', code: 'no_pin' });
return null;
}
const u = unlockFor(req);
if (!u) {
sendJson(res, 401, { error: 'Locked — enter the PIN', code: 'locked' });
return null;
}
return u;
}
/**
* The channel a browser asked to post to. Only a configured channel id is
* accepted — the selection is a choice among the admin's channels, never
* a way to reach some other one. Nothing asked for → the first configured.
* The channel a browser (or the Send Message module) asked to post to.
* Only a configured channel id is accepted — the selection is a choice
* among the admin's channels, never a way to reach some other one.
*/
function chooseTarget(requested) {
const s = String(requested ?? '').trim();
if (s) {
if (pollers.has(s)) return { id: s };
const name = lookupChannel(s);
return { error: `${name ? `#${name}` : s} isn't one of the configured channels — pick it in Admin → Slack → Channels` };
}
if (!channelIds.length) return { error: 'No channel configured — pick channels in Admin → Slack → Channels' };
return { id: channelIds[0] };
if (!s) return { error: 'Which channel?' };
if (pollers.has(s)) return { id: s };
const name = lookupChannel(s);
return { error: `${name ? `#${name}` : s} isn't one of the configured channels — pick it in Admin → Slack → Channels` };
}
async function postMessage(targetChannelId, text) {
@@ -1197,17 +1080,30 @@ module.exports = {
return slackCall(token, 'chat.postMessage', params, { json: true });
}
/** What the Send Message module may send to: the configured channels, as destinations. */
function messagingDescriptor() {
const h = health();
return {
label: 'Slack',
identity: sendingAs(),
destinationRole: 'recipient', // a channel is where a message goes, not who sends it
status: { state: h.status, message: h.message },
destinations: channelIds.map((id) => ({ id, label: `#${lookupChannel(id) || id}` })),
maxChars: MAX_TEXT_CHARS,
};
}
/**
* Add or remove a reaction on behalf of an unlock — the same gate as a
* send, since it is the location's name on it. The message's channel must
* be one of the configured ones. `already_reacted` / `no_reaction` count
* as done: Slack already holds the state that was asked for.
* Add or remove a reaction on behalf of a verified unlock — the same
* gate as a send, since it is the location's name on it. The message's
* channel must be one of the configured ones. `already_reacted` /
* `no_reaction` count as done: Slack already holds the state asked for.
*/
async function react(req, res, unlock, { channel, ts, name, remove }) {
async function react(req, res, verified, { channel, ts, name, remove }) {
if (!identity || authError) {
return sendJson(res, 502, { error: authError || 'Slack token not checked yet — try again in a moment' });
}
const target = String(channel ?? '').trim() ? chooseTarget(channel) : { error: 'Which channel?' };
const target = chooseTarget(channel);
if (target.error) return sendJson(res, 400, { error: target.error, code: 'bad_channel' });
const stamp = String(ts ?? '').trim();
if (!/^\d{1,16}\.\d{1,9}$/.test(stamp)) return sendJson(res, 400, { error: 'Which message?' });
@@ -1225,52 +1121,30 @@ module.exports = {
return sendJson(res, status, { error: message, code: err.code });
}
}
const u = unlocks.get(unlock.token);
if (u) u.expiresAt = Date.now() + idleMs;
log(`${remove ? 'removed' : 'added'} :${code}: on ${stamp} in #${targetName} as ${sendingAs()}`);
if (pollers.has(target.id)) pollSoon(pollers.get(target.id));
return sendJson(res, 200, { ok: true, expiresAt: u ? u.expiresAt : unlock.expiresAt, channel: `#${targetName}` });
return sendJson(res, 200, { ok: true, expiresAt: verified.expiresAt, channel: `#${targetName}` });
}
/**
* Post on behalf of an unlock; answers the response. `targetId` is an
* already-validated configured channel; `presetChannel` (a quick reply's
* own "| #channel") overrides it.
*/
async function deliver(req, res, unlock, { text, targetId, presetChannel = '', what }) {
const now = Date.now();
if (now - unlock.lastSendAt < SEND_MIN_INTERVAL_MS) {
return sendJson(res, 429, { error: 'One message per second — try again', code: 'too_fast' });
}
unlocks.get(unlock.token).lastSendAt = now;
/** Post to an already-validated configured channel; answers the response. */
async function deliver(req, res, verified, { text, targetId, what }) {
if (!identity || authError) {
return sendJson(res, 502, { error: authError || 'Slack token not checked yet — try again in a moment' });
}
let target = targetId || '';
if (presetChannel) {
try {
target = await resolveChannelRef(presetChannel);
} catch (err) {
return sendJson(res, 502, { error: describeError(err, { name: identity.name, channel: presetChannel }) });
}
if (!target) return sendJson(res, 400, { error: `No channel named #${String(presetChannel).replace(/^#/, '')} that ${identity.name} can see` });
}
if (!target) return sendJson(res, 400, { error: 'No channel configured — pick channels in Admin → Slack → Channels' });
const targetName = lookupChannel(target) || target;
const targetName = lookupChannel(targetId) || targetId;
try {
const data = await postMessage(target, text);
const u = unlocks.get(unlock.token);
if (u) u.expiresAt = Date.now() + idleMs;
const data = await postMessage(targetId, text);
const preview = text.replace(/\s+/g, ' ').slice(0, 60);
log(`${what} → #${targetName} as ${sendingAs()}: "${preview}${text.length > 60 ? '…' : ''}"`);
if (pollers.has(target)) pollSoon(pollers.get(target));
if (pollers.has(targetId)) pollSoon(pollers.get(targetId));
return sendJson(res, 200, {
ok: true,
ts: String(data.ts || ''),
label: `#${targetName}`,
channel: `#${targetName}`,
channelId: target,
channelId: targetId,
sendingAs: sendingAs(),
expiresAt: u ? u.expiresAt : unlock.expiresAt,
expiresAt: verified.expiresAt,
});
} catch (err) {
const message = describeError(err, { name: sendingAs() || identity.name, channel: targetName });
@@ -1290,12 +1164,9 @@ module.exports = {
}
}, HEARTBEAT_MS);
heartbeat.unref?.();
const sweeper = setInterval(sweepUnlocks, UNLOCK_SWEEP_MS);
sweeper.unref?.();
if (!token) log('no Slack token configured — paste one in /admin');
else {
if (sendEnabled && !pinOk) log('sending is on but no valid PIN (4–8 digits) is set — send tiles stay locked');
if (!channelIds.length) log('no channels configured — pick some in /admin → Slack → Channels');
else {
if (!Array.isArray(config.channels) || !config.channels.length) {
@@ -1311,8 +1182,8 @@ module.exports = {
streams,
snapshot,
health,
quickReplies,
sendGate,
shellPort,
messagingDescriptor,
deliver,
react,
/** Everything a tile needs to draw emoji: the shipped table plus the workspace's own. */
@@ -1331,7 +1202,6 @@ module.exports = {
if (kind === 'b') return botIcons.get(id) || '';
return '';
},
unlockFor,
chooseTarget,
namesReady,
touch() { lastInterest = Date.now(); },
@@ -1347,44 +1217,8 @@ module.exports = {
loadChannelList,
channelIds,
channelName: (id) => lookupChannel(id),
pinOk,
sendEnabled,
identityName: () => identity?.name || '',
sendingAs,
unlock(req, res, given) {
if (!sendEnabled) return sendJson(res, 403, { error: 'Sending is off — turn it on in Admin → Slack → Sending', code: 'sending_off' });
if (!pinOk) return sendJson(res, 403, { error: 'Set a PIN in Admin → Slack → Sending', code: 'no_pin' });
const ip = clientIp(req);
const now = Date.now();
let a = pinAttempts.get(ip);
if (a && a.lockedUntil > now) {
const secs = Math.ceil((a.lockedUntil - now) / 1000);
return sendJson(res, 429, { error: `Too many wrong PINs — locked for ${secs} s`, code: 'lockout', retryAfter: secs });
}
if (a && a.lockedUntil && a.lockedUntil <= now) a = null; // lockout served — clean slate
const str = String(given ?? '');
if (!PIN_RE.test(str) || !pinMatches(str, pin)) {
const count = (a ? a.count : 0) + 1;
if (count >= PIN_MAX_WRONG) {
pinAttempts.set(ip, { count: 0, lockedUntil: now + PIN_LOCKOUT_MS });
log(`wrong PIN ×${PIN_MAX_WRONG} from ${ip} — locked for ${PIN_LOCKOUT_MS / 1000} s`);
return sendJson(res, 429, { error: `Wrong PIN — locked for ${PIN_LOCKOUT_MS / 1000} s`, code: 'lockout', retryAfter: PIN_LOCKOUT_MS / 1000 });
}
pinAttempts.set(ip, { count, lockedUntil: 0 });
return sendJson(res, 401, { error: 'Wrong PIN', code: 'wrong_pin', triesLeft: PIN_MAX_WRONG - count });
}
pinAttempts.delete(ip);
const t = crypto.randomBytes(32).toString('hex');
const expiresAt = now + idleMs;
unlocks.set(t, { expiresAt, lastSendAt: 0, ip });
log(`unlocked from ${ip} (auto-lock after ${idleMs / 60000} min idle)`);
return sendJson(res, 200, { token: t, expiresAt, idleMs, sendingAs: sendingAs() });
},
lock(req, res) {
const t = bearer(req);
if (t) unlocks.delete(t);
return sendJson(res, 200, { ok: true });
},
};
return {
@@ -1398,8 +1232,6 @@ module.exports = {
}
}
clearInterval(heartbeat);
clearInterval(sweeper);
unlocks.clear(); // an admin Apply locks every send tile
for (const res of streams) {
try { res.end(); } catch { /* already gone */ }
}
@@ -1412,16 +1244,17 @@ module.exports = {
/**
* The picker: one transcript per configured channel, titled with the
* channel's name (the shell makes the entry's name the tile's title), then
* the two send surfaces, one of each per dashboard. Between init() and a
* poller's first answer a name may still be unknown — "#<id>" then.
* channel's name (the shell makes the entry's name the tile's title).
* Between init() and a poller's first answer a name may still be unknown
* — "#<id>" then. The send surfaces that used to follow here are the Send
* Message module's since 1.3.0; a layout's old Send message / Quick
* replies tiles draw nothing until they are removed.
*/
async tiles({ config }) {
const c = current;
const ids = c ? c.channelIds : configuredChannels(config || {});
if (c) await c.namesReady();
const who = c?.sendingAs() ? ` as ${c.sendingAs()}` : '';
const entries = ids.map((id) => ({
return ids.map((id) => ({
id: `transcript:${id}`,
name: `#${(c && c.channelName(id)) || id}`,
description: 'Live transcript',
@@ -1429,27 +1262,6 @@ module.exports = {
minSize: { w: 2, h: 2 },
settings: { view: 'transcript', channel: id },
}));
entries.push(
{
id: 'send',
name: 'Send message',
description: `PIN-protected message to the transcript clicked last${who}`,
single: true,
defaultSize: { w: 3, h: 3 },
minSize: { w: 2, h: 2 },
settings: { view: 'send' },
},
{
id: 'quick',
name: 'Quick replies',
description: `PIN-protected preset buttons${who}`,
single: true,
defaultSize: { w: 3, h: 2 },
minSize: { w: 2, h: 1 },
settings: { view: 'quick' },
},
);
return entries;
},
routes() {
@@ -1498,22 +1310,6 @@ module.exports = {
}
}),
'POST /unlock': guard(async (req, res) => {
if (!current) return unmounted(res);
let body;
try {
body = await readJson(req);
} catch (err) {
return sendJson(res, 400, { error: err.message });
}
current.unlock(req, res, body.pin);
}),
'POST /lock': (req, res) => {
if (!current) return unmounted(res);
current.lock(req, res);
},
// The emoji a tile may need to draw — fetched once per page, again when the version bumps.
'GET /emoji': (req, res) => {
if (!current) return unmounted(res);
@@ -1530,35 +1326,19 @@ module.exports = {
await serveImage(res, current.avatarUrl(decodeURIComponent(String(req.wildcard || '').replace(/^\/+/, ''))));
}),
// A reaction as the location — PIN-gated like a send.
'POST /react': guard(async (req, res) => {
// The Send Message module reads this over loopback: where it may send.
'GET /messaging': (req, res) => {
if (!current) return unmounted(res);
const unlock = current.sendGate(req, res);
if (!unlock) return;
let body;
try {
body = await readJson(req);
} catch (err) {
return sendJson(res, 400, { error: err.message });
}
await current.react(req, res, unlock, { channel: body.channel, ts: body.ts, name: body.name, remove: Boolean(body.remove) });
}),
// Labels and indexes only — the message text never leaves the server.
'GET /quick': (req, res) => {
if (!current) return unmounted(res);
const unlock = current.sendGate(req, res);
if (!unlock) return;
sendJson(res, 200, {
presets: current.quickReplies.map((q, index) => ({ index, label: q.label, channel: q.channel ? `#${q.channel}` : '' })),
expiresAt: unlock.expiresAt,
});
sendJson(res, 200, current.messagingDescriptor());
},
'POST /send': guard(async (req, res) => {
// …and hands a message here, with the browser's unlock token. The token
// is checked with the Send Message module first: no PIN entered there,
// nothing is posted.
'POST /messaging/send': guard(async (req, res) => {
if (!current) return unmounted(res);
const unlock = current.sendGate(req, res);
if (!unlock) return;
const v = await verifyUnlock(req, current.shellPort);
if (!v.ok) return sendJson(res, v.status, { error: v.error, code: v.code });
let body;
try {
body = await readJson(req);
@@ -1568,34 +1348,23 @@ module.exports = {
const text = String(body.text ?? '').replace(/\r\n/g, '\n').trim();
if (!text) return sendJson(res, 400, { error: 'Nothing to send' });
if (text.length > MAX_TEXT_CHARS) return sendJson(res, 400, { error: `Too long — ${MAX_TEXT_CHARS} characters at most` });
const target = current.chooseTarget(body.channel);
if (target.error) return sendJson(res, 400, { error: target.error, code: 'bad_channel' });
await current.deliver(req, res, unlock, { text, targetId: target.id, what: 'sent' });
const target = current.chooseTarget(body.destination ?? body.channel);
if (target.error) return sendJson(res, 400, { error: target.error, code: 'bad_destination' });
await current.deliver(req, res, v, { text, targetId: target.id, what: 'sent' });
}),
'POST /quick': guard(async (req, res) => {
// A reaction as the location — the same unlock as a send.
'POST /react': guard(async (req, res) => {
if (!current) return unmounted(res);
const unlock = current.sendGate(req, res);
if (!unlock) return;
const v = await verifyUnlock(req, current.shellPort);
if (!v.ok) return sendJson(res, v.status, { error: v.error, code: v.code });
let body;
try {
body = await readJson(req);
} catch (err) {
return sendJson(res, 400, { error: err.message });
}
const index = Math.trunc(Number(body.index));
const preset = Number.isInteger(index) ? current.quickReplies[index] : null;
if (!preset) return sendJson(res, 404, { error: 'No such quick reply — the list may have changed in Admin' });
// A channel the browser names is checked even when the preset's own
// binding is about to override it — an unconfigured id is never accepted.
const target = current.chooseTarget(body.channel);
if (target.error && (body.channel || !preset.channel)) return sendJson(res, 400, { error: target.error, code: 'bad_channel' });
await current.deliver(req, res, unlock, {
text: preset.message,
targetId: target.id || '',
presetChannel: preset.channel,
what: `quick reply "${preset.label}"`,
});
await current.react(req, res, v, { channel: body.channel, ts: body.ts, name: body.name, remove: Boolean(body.remove) });
}),
};
},
+18 -308
View File
@@ -1,7 +1,8 @@
/* Slack module — scoped to its tiles, shell variables only.
--sl-size (per tile, from the header's A− / A+) drives every font size.
Transcript rows follow the ProdCom transcript's layout: a square picture,
then a name line with the time, the text, the reactions. */
then a name line with the time, the text, the reactions. The send tiles
and the PIN pad moved to the Send Message module in 1.3.0. */
[data-module="slack"] .sl-wrap {
--sl-size: 14px;
@@ -34,8 +35,8 @@
/* ── the send target ── */
/* A click anywhere in a transcript's body makes its channel the one Send
message and Quick replies post to. The chosen one carries a 3px accent
/* A click anywhere in a transcript's body makes its channel the one the
Send Message module's tiles post to. The chosen one carries a 3px accent
stripe along the bottom edge of the tile body — drawn just inside our
root, since the tile chrome around it belongs to the shell. The others
hint at it faintly on hover. */
@@ -279,307 +280,6 @@
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.35);
}
/* ── send / quick replies: the gate ── */
[data-module="slack"] .sl-gate,
[data-module="slack"] .sl-compose {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
padding: 6px 10px;
overflow: auto;
}
[data-module="slack"] .sl-note {
margin: auto;
padding: 10px;
text-align: center;
color: var(--muted);
font-size: 0.9em;
line-height: 1.45;
}
[data-module="slack"] .sl-note.is-error { color: var(--danger); }
/* The pad never shrinks below its content (min-height stays `auto` on it
and on the key grid) — a shrunken grid would spill its rows under the
message line, which then swallows the taps. A tile too short for it
scrolls instead (.sl-gate has overflow: auto). */
[data-module="slack"] .sl-pad {
flex: 1 1 auto;
display: flex;
flex-direction: column;
gap: 4px;
max-width: 340px;
width: 100%;
margin: 0 auto;
}
[data-module="slack"] .sl-pad.sl-shake { animation: sl-shake 0.4s ease; }
@keyframes sl-shake {
10%, 90% { transform: translateX(-2px); }
20%, 80% { transform: translateX(3px); }
30%, 50%, 70% { transform: translateX(-5px); }
40%, 60% { transform: translateX(5px); }
}
/* one line: "Enter PIN · sending as Apollo Beach → #production" */
[data-module="slack"] .sl-pad-head {
flex: none;
text-align: center;
font-size: 0.8em;
color: var(--muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-module="slack"] .sl-pad-head b { font-weight: 700; color: var(--text); }
[data-module="slack"] .sl-dots {
flex: none;
display: flex;
justify-content: center;
gap: 8px;
height: 14px;
}
[data-module="slack"] .sl-dot {
width: 11px;
height: 11px;
border-radius: 50%;
border: 2px solid var(--muted);
transition: background 0.12s, border-color 0.12s;
}
[data-module="slack"] .sl-dot.on { background: var(--accent); border-color: var(--accent); }
[data-module="slack"] .sl-keys {
flex: 1 1 auto;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(4, minmax(24px, 1fr));
gap: 4px;
}
[data-module="slack"] .sl-key {
min-width: 0;
min-height: 24px;
border: 1px solid var(--border);
border-radius: 10px;
background: color-mix(in srgb, var(--text) 5%, var(--panel));
color: var(--text);
font: inherit;
font-size: clamp(13px, 9cqh, 26px);
font-weight: 600;
font-variant-numeric: tabular-nums;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
transition: background 0.1s;
}
[data-module="slack"] .sl-key:hover { background: var(--border); }
[data-module="slack"] .sl-key:active { background: color-mix(in srgb, var(--accent) 30%, var(--panel)); }
[data-module="slack"] .sl-key svg { width: 1.1em; height: 1.1em; }
[data-module="slack"] .sl-key-back { color: var(--muted); }
[data-module="slack"] .sl-key-blank { visibility: hidden; }
[data-module="slack"] .sl-pad.is-busy .sl-keys { opacity: 0.6; pointer-events: none; }
[data-module="slack"] .sl-pad-msg {
flex: none;
min-height: 1.1em;
text-align: center;
font-size: 0.78em;
line-height: 1.1;
color: var(--muted);
}
[data-module="slack"] .sl-pad-msg.is-error { color: var(--danger); font-weight: 600; }
/* A tile too short for the keypad (the smallest Send message / Quick replies
tiles) shows the dots and a hint instead — digits typed on the keyboard
still land, and a taller tile brings the keys back. .sl-wrap is the size
container the height is measured against. */
[data-module="slack"] .sl-pad-hint {
display: none;
flex: none;
text-align: center;
font-size: 0.78em;
line-height: 1.3;
color: var(--muted);
}
@container (max-height: 176px) {
[data-module="slack"] .sl-pad .sl-keys { display: none; }
[data-module="slack"] .sl-pad .sl-pad-hint { display: block; }
[data-module="slack"] .sl-pad { justify-content: center; }
}
/* ── send / quick replies: unlocked ── */
[data-module="slack"] .sl-compose { gap: 6px; }
[data-module="slack"] .sl-compose-head {
flex: none;
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
font-size: 0.8em;
color: var(--muted);
}
[data-module="slack"] .sl-sending {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-module="slack"] .sl-lock-link {
flex: none;
padding: 1px 8px;
border: 1px solid var(--border);
border-radius: 999px;
background: none;
color: var(--muted);
font: inherit;
font-size: 0.9em;
cursor: pointer;
}
[data-module="slack"] .sl-lock-link:hover { color: var(--text); background: var(--border); }
[data-module="slack"] .sl-input {
flex: 1;
min-height: 2.6em;
width: 100%;
resize: none;
padding: 7px 9px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg);
color: var(--text);
font: inherit;
line-height: 1.4;
}
[data-module="slack"] .sl-input:focus { outline: none; border-color: var(--accent); }
[data-module="slack"] .sl-compose-foot {
flex: none;
display: flex;
align-items: center;
gap: 8px;
min-height: 1.6em;
}
[data-module="slack"] .sl-msg {
flex: 1;
min-width: 0;
font-size: 0.8em;
color: var(--muted);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
[data-module="slack"] .sl-msg.is-flash { color: var(--accent); font-weight: 700; }
[data-module="slack"] .sl-msg.is-error { color: var(--danger); white-space: normal; font-weight: 600; }
[data-module="slack"] .sl-countdown {
flex: none;
font-size: 0.75em;
color: var(--warn);
font-variant-numeric: tabular-nums;
}
[data-module="slack"] .sl-sendbtn {
flex: none;
padding: 6px 16px;
border: none;
border-radius: 8px;
background: var(--accent);
color: var(--accent-text);
font: inherit;
font-weight: 700;
cursor: pointer;
}
[data-module="slack"] .sl-sendbtn:hover { background: color-mix(in srgb, var(--accent) 85%, var(--text)); }
[data-module="slack"] .sl-sendbtn:disabled { opacity: 0.6; cursor: default; }
/* quick emojis: one press each sends it as a message of its own */
[data-module="slack"] .sl-emoji-sendrow {
flex: none;
display: flex;
gap: 4px;
min-width: 0;
overflow: hidden;
}
[data-module="slack"] .sl-emoji-send {
flex: none;
width: 2.1em;
height: 2.1em;
padding: 0;
border: 1px solid var(--border);
border-radius: 8px;
background: color-mix(in srgb, var(--text) 5%, var(--panel));
color: var(--text);
font: inherit;
font-size: 1.1em;
line-height: 1;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
transition: background 0.1s, border-color 0.1s;
}
[data-module="slack"] .sl-emoji-send:hover { border-color: var(--accent); background: var(--border); }
[data-module="slack"] .sl-emoji-send:active { background: color-mix(in srgb, var(--accent) 30%, var(--panel)); }
[data-module="slack"] .sl-emoji-send.is-busy { opacity: 0.6; }
[data-module="slack"] .sl-emoji-send.is-sent { background: var(--accent); border-color: transparent; }
[data-module="slack"] .sl-emoji-send .sl-emoji { width: 1.2em; height: 1.2em; vertical-align: middle; }
/* the preset grid: big targets, labels wrap */
[data-module="slack"] .sl-grid {
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(min(150px, 100%), 1fr));
grid-auto-rows: minmax(44px, auto);
gap: 6px;
align-content: start;
overflow-y: auto;
}
[data-module="slack"] .sl-grid .sl-note { grid-column: 1 / -1; }
[data-module="slack"] .sl-quick {
min-width: 0;
min-height: 44px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 2px;
padding: 6px 10px;
border: 1px solid var(--border);
border-radius: 10px;
background: color-mix(in srgb, var(--accent) 12%, var(--panel));
color: var(--text);
font: inherit;
font-weight: 600;
line-height: 1.25;
text-align: center;
cursor: pointer;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
transition: background 0.1s;
}
[data-module="slack"] .sl-quick:hover { background: color-mix(in srgb, var(--accent) 22%, var(--panel)); }
[data-module="slack"] .sl-quick:active { background: color-mix(in srgb, var(--accent) 40%, var(--panel)); }
[data-module="slack"] .sl-quick.is-busy { opacity: 0.7; }
[data-module="slack"] .sl-quick.is-sent {
background: var(--accent);
border-color: transparent;
color: var(--accent-text);
}
[data-module="slack"] .sl-quick-label { overflow-wrap: anywhere; }
[data-module="slack"] .sl-quick-chan {
font-size: 0.72em;
font-weight: 500;
color: var(--muted);
}
[data-module="slack"] .sl-quick.is-sent .sl-quick-chan { color: inherit; }
/* ── the reaction menu (on document.body, so nothing clips it) ── */
[data-module="slack"].sl-emoji-menu {
@@ -671,7 +371,17 @@
[data-module="slack"] .sl-emoji-msg:empty { display: none; }
[data-module="slack"] .sl-emoji-msg.is-error { color: var(--danger); font-weight: 600; }
/* the PIN pad inside the menu: fixed sizes, no tile to scale with */
[data-module="slack"] .sl-emoji-menu .sl-pad { max-width: 100%; gap: 6px; }
[data-module="slack"] .sl-emoji-menu .sl-keys { grid-template-rows: repeat(4, 40px); }
[data-module="slack"] .sl-emoji-menu .sl-key { font-size: 17px; }
/* locked: the PIN is entered in the Send Message module's tile, not here */
[data-module="slack"] .sl-emoji-locked {
padding: 4px 2px 2px;
font-size: 0.86em;
line-height: 1.4;
color: var(--muted);
}
[data-module="slack"] .sl-emoji-locked b { color: var(--text); font-weight: 700; }
[data-module="slack"] .sl-emoji-reason {
display: block;
margin-top: 4px;
color: var(--warn);
font-size: 0.9em;
}
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1,7 +1,7 @@
{
"id": "spl-meter",
"name": "SPL Meter",
"version": "0.4.1",
"version": "0.5.0",
"proddash": ">=1.5.0",
"description": "Calibrated sound level, Leq and RTA from an audio input on this machine",
"permissions": [
+48
View File
@@ -0,0 +1,48 @@
#!/bin/zsh
# Build this module's native helper for every macOS architecture it ships —
# ../bin/spl-capture-macos-arm64 and ../bin/spl-capture-macos-x86_64 —
# from spl-capture.swift beside this script. Run it on any Mac with the
# Xcode command line tools; both architectures cross-compile from either.
# The binaries are committed: a machine running ProdDash never builds
# anything (docs/MODULE-GUIDE.md, "Native helpers").
#
# Signed with a Developer ID Application certificate when one is installed
# (override with CODESIGN_IDENTITY) — hardened runtime plus the audio-input
# entitlement, which a helper that reads a microphone needs under the
# hardened runtime — and ad-hoc otherwise, which is fine on your own Macs.
#
# Windows is not built here: there is no Windows implementation of this
# tool yet, so on Windows the module reports measurement off.
set -e -u
cd "$(dirname "$0")"
NAME="spl-capture"
DEPLOYMENT_TARGET="13.0"
command -v swiftc >/dev/null || {
echo "build.sh: swiftc not found — install the Xcode command line tools: xcode-select --install" >&2
exit 1
}
IDENTITY="${CODESIGN_IDENTITY:-}"
if [[ -z "$IDENTITY" ]]; then
IDENTITY=$(security find-identity -v -p codesigning 2>/dev/null \
| awk -F'"' '/Developer ID Application/ {print $2; exit}')
fi
if [[ -n "$IDENTITY" ]]; then
echo "signing as $IDENTITY"
SIGN=(--force --sign "$IDENTITY" --options runtime --timestamp)
else
echo "signing ad-hoc (no Developer ID installed — fine on your own Macs)"
SIGN=(--force --sign - --options runtime)
fi
mkdir -p ../bin
for ARCH in arm64 x86_64; do
OUT="../bin/$NAME-macos-$ARCH"
echo " compiling $OUT"
swiftc -O -whole-module-optimization -target "$ARCH-apple-macos$DEPLOYMENT_TARGET" -o "$OUT" "$NAME.swift"
codesign "${SIGN[@]}" --entitlements helper.entitlements "$OUT"
codesign --verify --strict "$OUT"
echo " built $OUT ($(du -h "$OUT" | awk '{print $1}'))"
done
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<!-- The helper reads an audio input; under the hardened runtime that
needs saying. The permission itself comes from the launcher. -->
<key>com.apple.security.device.audio-input</key>
<true/>
</dict>
</plist>
@@ -8,10 +8,11 @@
// measurement is done here and only the answers cross the pipe.
//
// Everything below uses Accelerate, which ships with macOS. No third-party
// code, no package manager, ~2 s to build:
// code, no package manager. It ships prebuilt in the module's bin/ (one
// binary per platform, committed — a booth never builds anything). To
// rebuild after a change here, on any Mac with the Xcode command line tools:
//
// swiftc -O -o modules/spl-meter/spl-capture \
// modules/spl-meter/spl-capture.swift
// modules/spl-meter/native/build.sh (both architectures)
//
// spl-capture --list
// every input-capable device: name, input channels, sample rate
+14 -2
View File
@@ -20,7 +20,7 @@
*/
const path = require('path');
const { createSplListener } = require('./spl-listener');
const { createSplListener, captureTool } = require('./spl-listener');
/** Reference level of a sound level calibrator. Effectively always 94 dB. */
const CALIBRATOR_DB = 94;
@@ -114,11 +114,16 @@ module.exports = {
error: '',
streams: new Set(),
silentSince: null,
toolMissing: '',
listener: null,
lastSent: '',
pinger: null,
};
// The capture tool ships prebuilt in the module (bin/); with none for
// this platform every reading is off and the health line says so.
state.toolMissing = captureTool(moduleDir).missing;
if (!config.enabled) {
state.error = 'Sound level measurement is off — turn it on in ProdDash settings';
return { stop() { teardown(); }, health: () => ({ status: 'error', message: state.error }) };
@@ -177,6 +182,7 @@ module.exports = {
return {
stop() { teardown(); },
health() {
if (state.toolMissing) return { status: 'error', message: state.toolMissing };
if (state.error) return { status: 'error', message: state.error };
if (!state.frame) return { status: 'connecting', message: 'waiting for the first reading' };
const quiet = silentMs();
@@ -300,6 +306,12 @@ module.exports = {
/** Device list for the admin page. Runs the capture tool's --list,
which is the only thing that knows what CoreAudio can see. */
'GET /devices': async (req, res) => {
const tool = captureTool(__dirname);
if (tool.missing) {
log(`device list unavailable — ${tool.missing}`);
json(res, 200, { options: [], error: tool.missing });
return;
}
try {
const devices = await listDevices();
json(res, 200, {
@@ -429,7 +441,7 @@ function teardown() {
function listDevices() {
return new Promise((resolve, reject) => {
const { execFile } = require('child_process');
execFile(path.join(__dirname, 'spl-capture'), ['--list'], { timeout: 10000 },
execFile(captureTool(__dirname).bin, ['--list'], { timeout: 10000 },
(err, stdout) => {
if (err && !stdout) { reject(err); return; }
try { resolve(JSON.parse(stdout).devices || []); }
+42 -73
View File
@@ -3,7 +3,8 @@
/**
* Sound level listener — owns the native capture child.
*
* Spawns spl-capture (compiled from spl-capture.swift beside it) for the
* Spawns spl-capture (bin/spl-capture-macos-<arch>, shipped prebuilt;
* source in native/) for the
* admin-configured device and channels, reads its JSON lines, and hands the
* latest frame upward. All measurement happens in the child; this file is
* plumbing and supervision, nothing more.
@@ -13,11 +14,11 @@
* { frame: {...}, meta: {...} } measuring
* { error: '<what is wrong and how to fix it>' } not measuring
*
* The capture binary is per-machine and gitignored, exactly like the Timers
* module's ltc-capture. It normally arrives already built — compiled beside
* the app, or copied from any Mac of the same architecture. When it is
* missing this will build it, but in the background and never on the event
* loop: see ensureBinary for what that cost the first time it was wrong.
* The capture tool ships prebuilt inside the module, one binary per
* platform under bin/ (module guide, "Native helpers"), exactly like the
* Timers module's ltc-capture: nothing is ever built on the machine running
* ProdDash. captureTool() picks the binary for this platform; when there is
* none, measurement reports itself off and the rest of the module carries on.
*
* The same macOS gotcha applies as for LTC, and is worth repeating because
* it costs an afternoon every time: a ProdDash launched over SSH or from a
@@ -30,6 +31,33 @@ const path = require('path');
const fs = require('fs');
const { spawn } = require('child_process');
/* ── the capture tool: prebuilt, one binary per platform ───────────────── */
/** What the module ships in bin/, by platform and architecture. */
const HELPERS = {
darwin: { arm64: 'spl-capture-macos-arm64', x64: 'spl-capture-macos-x86_64' },
win32: { x64: 'spl-capture-win-x64.exe' },
};
/**
* The capture tool for this machine. It is never built here and never
* looked for anywhere else: the module ships it, or measurement is off on
* this platform and says so. `bin` is the usable binary; otherwise
* `missing` is what to tell the admin page and the tiles.
*
* @returns {{bin:string, missing:string}}
*/
function captureTool(moduleDir, platform = process.platform, arch = process.arch) {
const name = HELPERS[platform]?.[arch] || '';
const bin = name ? path.join(moduleDir, 'bin', name) : '';
if (bin && fs.existsSync(bin)) return { bin, missing: '' };
const here = `${platform === 'darwin' ? 'macOS' : platform === 'win32' ? 'Windows' : platform} ${arch}`;
return {
bin: '',
missing: `The module ships no sound level capture tool for ${here}${name ? ` (bin/${name} is missing)` : ''} — measurement is off on this machine`,
};
}
const RESTART_MS = 5000;
/** An immediate exit is config-shaped (bad device, channel out of range) —
retrying every 5 s would only fill the log with the same sentence. */
@@ -45,7 +73,6 @@ const STALL_MS = 3000;
*/
function createSplListener(opts) {
const { device, channels, weighting, bands, calibration, moduleDir, log, onUpdate } = opts;
const bin = path.join(moduleDir, 'spl-capture');
let child = null;
let stopped = false;
@@ -53,66 +80,8 @@ function createSplListener(opts) {
let stallTimer = null;
let startedAt = 0;
let meta = null;
let building = false;
let buildFailed = false;
let lastFrameWall = 0;
const BUILD_HELP = 'Sound level capture tool missing — build it on any Apple Silicon Mac with '
+ '`swiftc -O -o modules/spl-meter/spl-capture modules/spl-meter/spl-capture.swift` '
+ 'and copy it next to spl-capture.swift';
/**
* Build the capture tool if it is missing, WITHOUT blocking.
*
* This used to be a spawnSync, copied from the LTC listener where the
* source is a third the size and builds in a few seconds. Here it took
* nearly two minutes on the production Mac and froze the entire ProdDash
* server for every second of it — one module's optional helper took the
* whole dashboard down, then did it again on every retry. Nothing that
* runs while a service might be on is allowed to hold the event loop.
*
* The build is a fallback for a module installed from the catalog on a
* machine with a Swift toolchain. The normal path is a binary built
* alongside the app, or copied from any same-architecture Mac.
*
* @returns {string} '' when the binary is ready, otherwise what to say.
*/
function ensureBinary() {
if (fs.existsSync(bin)) return '';
const src = bin + '.swift';
if (!fs.existsSync(src)) return 'spl-capture.swift is missing from the module folder';
if (building) return 'Building the capture tool — this takes a minute or two';
if (buildFailed) return BUILD_HELP;
building = true;
log('spl-capture binary missing — building it in the background');
const build = spawn('swiftc', ['-O', '-o', bin, src], { stdio: ['ignore', 'ignore', 'pipe'] });
let buildErr = '';
build.stderr.setEncoding('utf8');
build.stderr.on('data', (t) => { buildErr = (buildErr + t).slice(-800); });
const giveUp = setTimeout(() => {
try { build.kill('SIGKILL'); } catch { /* already gone */ }
}, 300000);
build.on('error', (err) => {
clearTimeout(giveUp);
building = false; buildFailed = true;
log(`swiftc could not be run: ${err.message}`);
});
build.on('exit', (code) => {
clearTimeout(giveUp);
building = false;
if (code === 0 && fs.existsSync(bin)) {
log('spl-capture built');
buildFailed = false;
if (!stopped) { clearTimeout(restartTimer); restartTimer = null; start(); }
return;
}
buildFailed = true;
log(`spl-capture build failed (exit ${code})` + (buildErr ? `: ${buildErr.trim().split('\n').pop()}` : ''));
});
return 'Building the capture tool — this takes a minute or two';
}
function scheduleRestart(ms) {
if (stopped || restartTimer) return;
restartTimer = setTimeout(() => { restartTimer = null; start(); }, ms);
@@ -132,12 +101,12 @@ function createSplListener(opts) {
function start() {
if (stopped) return;
const missing = ensureBinary();
if (missing) {
onUpdate({ error: missing });
// A build in flight calls start() itself when it lands; anything else
// is config-shaped and should back off hard rather than spin.
if (!building) scheduleRestart(BAD_CONFIG_RETRY_MS);
const tool = captureTool(moduleDir);
if (tool.missing) {
// No binary for this platform: say so and look again later — a module
// update remounts us anyway, this is only belt and braces.
onUpdate({ error: tool.missing });
scheduleRestart(BAD_CONFIG_RETRY_MS);
return;
}
@@ -153,7 +122,7 @@ function createSplListener(opts) {
let stderrTail = '';
let buf = '';
child = spawn(bin, args, { stdio: ['pipe', 'pipe', 'pipe'] });
child = spawn(tool.bin, args, { stdio: ['pipe', 'pipe', 'pipe'] });
child.stderr.setEncoding('utf8');
child.stderr.on('data', (text) => {
@@ -236,4 +205,4 @@ function createSplListener(opts) {
};
}
module.exports = { createSplListener };
module.exports = { createSplListener, captureTool };
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "proddash",
"version": "1.9.2",
"version": "1.10.2",
"private": true,
"description": "Modular production dashboard for Waters Church \u2014 zero-dependency Node server + vanilla client",
"license": "UNLICENSED",
+1
View File
@@ -443,6 +443,7 @@ a.btn { text-decoration: none; }
margin-bottom: 10px;
}
.catalog-main { flex: 1; min-width: 0; }
.catalog-pick { margin: 5px 10px 0 0; flex: none; }
.catalog-title { display: flex; align-items: center; gap: 8px; }
.catalog-row .module-desc { margin: 4px 0 2px; }
.catalog-row .module-health { margin-top: 2px; }
+43
View File
@@ -962,6 +962,13 @@ async function loadState() {
for (const mod of state.modules || []) {
modulesList.appendChild(buildModuleCard(mod));
}
if (!(state.modules || []).length) {
// A packaged ProdDash starts like this: the catalog below is the way in.
const none = document.createElement('div');
none.className = 'layouts-empty';
none.textContent = 'Nothing installed yet — pick from Available modules below.';
modulesList.appendChild(none);
}
renderPin(state);
loadTheme();
loadLayouts();
@@ -1163,6 +1170,7 @@ function renderAvailable(cat) {
els.updateSlot.appendChild(btn);
}
const available = cat.available || [];
installSelectedBtn.hidden = available.filter((a) => a.compatible).length < 2;
if (!available.length) {
const none = document.createElement('div');
none.className = 'layouts-empty';
@@ -1205,11 +1213,46 @@ function renderAvailable(cat) {
btn.disabled = !item.compatible;
btn.title = item.compatible ? '' : item.reason;
btn.addEventListener('click', () => installFromCatalog(item, btn));
if (item.compatible) {
const pick = document.createElement('input');
pick.type = 'checkbox';
pick.className = 'catalog-pick';
pick.dataset.id = item.id;
pick.dataset.name = item.name;
pick.title = 'Tick several, then Install selected';
row.append(pick);
}
row.append(main, btn);
availableList.appendChild(row);
}
}
const installSelectedBtn = document.getElementById('install-selected');
/** The ticked modules, in one request; the answer says which ones landed. */
async function installSelected() {
const picks = [...availableList.querySelectorAll('.catalog-pick:checked')];
if (!picks.length) return toast('Tick the modules to install first', true);
installSelectedBtn.disabled = true;
installSelectedBtn.textContent = `Installing ${picks.length}…`;
try {
const r = await api('/api/admin/modules/install', { method: 'POST', body: JSON.stringify({ ids: picks.map((p) => p.dataset.id) }) });
const done = (r.results || []).filter((x) => x.ok).length;
const failed = (r.results || []).filter((x) => !x.ok);
toast(failed.length
? `${done} installed; ${failed.map((f) => `${f.id}: ${f.error}`).join(' · ')}`
: `${done} module${done === 1 ? '' : 's'} installed`, failed.length > 0);
await loadState();
} catch (e) {
if (e.authRequired) showLogin();
else toast(e.message, true);
} finally {
installSelectedBtn.disabled = false;
installSelectedBtn.textContent = 'Install selected';
}
}
installSelectedBtn.addEventListener('click', installSelected);
async function installFromCatalog(item, btn) {
btn.disabled = true;
const label = btn.textContent;
+1
View File
@@ -58,6 +58,7 @@
<section id="available-section" hidden>
<h1 class="admin-h1">Available modules</h1>
<div class="catalog-toolbar">
<button class="btn small primary" id="install-selected" hidden>Install selected</button>
<button class="btn small" id="catalog-refresh">Check again</button>
<span class="admin-status" id="catalog-status"></span>
</div>
+51 -10
View File
@@ -510,6 +510,7 @@ function reconcileOfferedTiles() {
}
if (changed) rebuildDividers();
scheduleOfferedRecheck();
refreshEmptyState(); // the registry may have gone from nothing to something
}
/* A module's entry list can change without anyone saving admin config: PCO
@@ -639,8 +640,10 @@ function buildTile(tile) {
el.addEventListener('pointermove', (ev) => {
if (!headIsOff(tile)) return;
// Mid-drag the tile moves under the pointer, and mid-resize the edges do
// — neither is a moment to take the bar away.
// — neither is a moment to take the bar away. Nor is an open header
// menu, which hangs below the bar and is about to be pointed at.
if (el.classList.contains('dragging') || el.classList.contains('resizing')) return;
if (el.classList.contains('menu-open')) return;
const y = ev.clientY - el.getBoundingClientRect().top;
const shown = el.classList.contains('head-peek');
// It takes less to hold the bar open than to open it, so a bar that
@@ -651,6 +654,7 @@ function buildTile(tile) {
el.addEventListener('pointerleave', () => {
if (el.classList.contains('dragging') || el.classList.contains('resizing')) return;
if (el.classList.contains('menu-open')) return; // the pointer is on its way to the menu
el.classList.remove('head-peek');
});
@@ -658,7 +662,7 @@ function buildTile(tile) {
applyHeadState(tile, el);
grid.appendChild(el);
const entry = { el, body, dot, titleEl: title, controls, instance: null };
const entry = { el, body, dot, titleEl: title, controls, instance: null, openMenus: new Set() };
tileEls.set(tile.id, entry);
applyRect(tile);
@@ -676,6 +680,15 @@ function buildTile(tile) {
function refreshEmptyState() {
emptyEl.hidden = tiles.length > 0;
if (emptyEl.hidden) return;
// Two different empties: a bare board, and a ProdDash with nothing to put
// on one — a packaged install starts without modules until Admin adds some.
const noModules = registry.size === 0;
if (noModules === emptyEl.classList.contains('no-modules')) return;
emptyEl.classList.toggle('no-modules', noModules);
emptyEl.innerHTML = noModules
? 'No modules yet — <a href="/admin">open Admin</a> and install some under Available modules.'
: 'No tiles yet — use “+ Add tile” to build this dashboard.<br>Every browser keeps its own layout.';
}
/* ── drag to move ───────────────────────────────────────────────────── */
@@ -1416,34 +1429,60 @@ function buildModuleApi(tile, man, entry) {
menu.className = 'tile-menu';
menu.hidden = true;
/* The menu lives on the body, not in the bar. A folded-away bar
(auto-hide, fullscreen) carries a backdrop-filter and a transform,
and either one makes a fixed-positioned descendant position
itself against the bar instead of the viewport — the menu landed
a screen-height below its button, inside the tile's overflow, and
never showed. Its host carries the tile's data-module so the
module's scoped CSS still reaches the items. */
const host = document.createElement('div');
host.className = 'tile-menu-host';
if (man) host.dataset.module = man.id;
host.appendChild(menu);
const setOpen = (on) => {
if (on === !menu.hidden) return;
menu.hidden = !on;
btn.classList.toggle('is-open', on);
if (on) entry.openMenus.add(menu);
else entry.openMenus.delete(menu);
// an open menu holds a folded-away bar out; when the last one
// closes with the pointer elsewhere, the bar goes back
entry.el.classList.toggle('menu-open', entry.openMenus.size > 0);
if (!on && !entry.openMenus.size && !entry.el.matches(':hover')) entry.el.classList.remove('head-peek');
};
const open = () => {
if (typeof build === 'function') {
menu.innerHTML = '';
build(menu);
}
menu.hidden = false;
// fixed positioning (escapes the tile's overflow): under the
// button, right-aligned, clamped to the viewport
setOpen(true);
// under the button, right-aligned, kept whole inside the viewport
const r = btn.getBoundingClientRect();
menu.style.top = Math.min(r.bottom + 6, window.innerHeight - 80) + 'px';
menu.style.left = '0px';
menu.style.top = '0px';
const w = menu.offsetWidth;
const h = menu.offsetHeight;
menu.style.top = Math.max(8, Math.min(r.bottom + 6, window.innerHeight - h - 8)) + 'px';
menu.style.left = Math.max(8, Math.min(r.right - w, window.innerWidth - w - 8)) + 'px';
};
btn.addEventListener('click', (e) => {
e.stopPropagation();
if (menu.hidden) open();
else menu.hidden = true;
else setOpen(false);
});
const onDocClick = (e) => {
if (!menu.hidden && !menu.contains(e.target) && !btn.contains(e.target)) menu.hidden = true;
if (!menu.hidden && !menu.contains(e.target) && !btn.contains(e.target)) setOpen(false);
};
document.addEventListener('click', onDocClick);
docListeners.add(onDocClick);
wrap.append(btn, menu);
wrap.append(btn);
entry.controls.appendChild(wrap);
document.body.appendChild(host);
headerEls.add(wrap);
headerEls.add(host);
return {
button: btn,
menu,
@@ -1451,7 +1490,7 @@ function buildModuleApi(tile, man, entry) {
btn.textContent = text;
},
close() {
menu.hidden = true;
setOpen(false);
},
};
},
@@ -1463,6 +1502,8 @@ function buildModuleApi(tile, man, entry) {
for (const handle of [...sseHandles]) handle.close();
for (const el of headerEls) el.remove();
headerEls.clear();
entry.openMenus.clear();
entry.el.classList.remove('menu-open');
for (const fn of docListeners) document.removeEventListener('click', fn);
docListeners.clear();
},
+3 -2
View File
@@ -445,8 +445,9 @@ body.menu-hidden #topbar {
}
.tile-dd { position: relative; display: inline-flex; }
/* a module header menu — fixed-positioned by the shell so the tile's
overflow:hidden can't clip it */
/* a module header menu — hosted on the body (shell.js addMenu) so neither
the tile's overflow nor a folded-away bar's backdrop-filter can touch it */
.tile-menu-host { display: contents; }
.tile-menu {
position: fixed;
z-index: 70;
+92 -1
View File
@@ -277,6 +277,52 @@ function isUninstalled(id) {
return moduleState(id).uninstalled === true;
}
/**
* A packaged install that still carries modules in its app folder — every
* install made before 1.10.0 does — moves them into the data directory
* once, as installed copies, and drops the app-folder copies. Nothing
* changes for the operator: the same modules run with the same settings
* (config is keyed by module id), and from now on each updates on its own
* from the catalog. A compiled helper sitting in a bundled folder travels
* with it. A module the operator had uninstalled is simply dropped — the
* catalog still offers it, and its settings stay in modules.json.
*/
function unbundleModules() {
if (!PACKAGED || !fs.existsSync(BUNDLED_MODULES_DIR)) return;
const installed = new Map(readManifests(INSTALLED_MODULES_DIR, 'installed').map((m) => [m.id, m]));
let moved = 0;
let failed = 0;
for (const man of readManifests(BUNDLED_MODULES_DIR, 'bundled')) {
if (isUninstalled(man.id)) continue;
const copy = installed.get(man.id);
if (copy && compareVersions(copy.version, man.version) >= 0) continue; // the data directory already has as good or better
const dest = path.join(INSTALLED_MODULES_DIR, man.id);
const staging = path.join(INSTALLED_MODULES_DIR, `.${man.id}.moving`);
try {
fs.mkdirSync(INSTALLED_MODULES_DIR, { recursive: true });
fs.rmSync(staging, { recursive: true, force: true });
fs.cpSync(man.dir, staging, { recursive: true }); // keeps modes: a compiled helper stays executable
fs.rmSync(dest, { recursive: true, force: true });
fs.renameSync(staging, dest);
moved += 1;
console.log(`[proddash] moved bundled module "${man.id}" v${man.version} into the data directory${copy ? ` (over the installed v${copy.version})` : ''}`);
} catch (err) {
failed += 1;
console.error(`[proddash] could not move bundled module "${man.id}" into the data directory:`, err?.message || err);
}
}
if (failed) {
console.warn(`[proddash] ${failed} bundled module${failed === 1 ? '' : 's'} stay in the app folder for now — tried again at the next start`);
return;
}
try {
fs.rmSync(BUNDLED_MODULES_DIR, { recursive: true, force: true });
console.log(`[proddash] the app folder carries no modules now${moved ? ` — ${moved} moved into the data directory` : ''}; the admin page's catalog installs and updates them`);
} catch (err) {
console.warn("[proddash] could not remove the app folder's modules:", err?.message || err);
}
}
function moduleState(id) {
const s = modulesConfig[id];
return s && typeof s === 'object' ? s : {};
@@ -910,9 +956,21 @@ async function fetchArchive() {
signal: AbortSignal.timeout(30000),
headers: { 'User-Agent': `ProdDash/${SHELL_VERSION}` },
});
if (!res.ok) throw new Error(`HTTP ${res.status} fetching ${REPO.owner}/${REPO.repo}@${REPO.branch}`);
const where = `${REPO.owner}/${REPO.repo}@${REPO.branch}`;
// A forge that wants a sign-in does not refuse: it redirects the download
// to its login page, which arrives as a 200 of HTML. Say that, not
// zlib's "incorrect header check".
if (res.redirected && /\/user\/login\b|\/login\b/.test(new URL(res.url).pathname)) {
throw new Error(`${FORGE.base} requires a sign-in to read ${where} — turn off "require sign-in to view" in Gitea, or make the repo readable without one`);
}
if (!res.ok) throw new Error(`HTTP ${res.status} fetching ${where}`);
const gz = Buffer.from(await res.arrayBuffer());
if (gz.length > MAX_ARCHIVE_BYTES) throw new Error('archive is unexpectedly large');
if (gz.length < 2 || gz[0] !== 0x1f || gz[1] !== 0x8b) {
const type = String(res.headers.get('content-type') || 'unknown type').split(';')[0].trim();
const looksHtml = /^\s*<(!doctype|html)/i.test(gz.subarray(0, 64).toString('utf8'));
throw new Error(`${FORGE.base} answered with ${looksHtml ? 'a web page' : type} instead of the ${where} archive — check the forge address and that the repo is readable without a sign-in`);
}
const { files, comment } = parseTar(zlib.gunzipSync(gz));
const stripped = new Map(); // drop the archive's single top-level folder
for (const [p, data] of files) {
@@ -1235,9 +1293,18 @@ const DATA_DIR_INSIDE_ROOT = (() => {
return rel.split(path.sep).join('/') + '/';
})();
/* A packaged install — the macOS app, the Windows bundle: anything that is
not a git checkout, the same test the updater uses to choose the archive
over git pull — carries no modules of its own. Every module comes from
the catalog into the data directory, and the shell's own update never
brings one along. A checkout keeps running the modules in its tree, which
is what development wants. */
const PACKAGED = !fs.existsSync(path.join(ROOT, '.git'));
function isKeptOnUpdate(rel) {
if (rel.startsWith('.git/')) return true;
if (rel === 'config/modules.json' || rel.startsWith('config/layouts/')) return true;
if (PACKAGED && (rel === 'modules' || rel.startsWith('modules/'))) return true;
return Boolean(DATA_DIR_INSIDE_ROOT) && `${rel}/`.startsWith(DATA_DIR_INSIDE_ROOT);
}
@@ -1580,6 +1647,29 @@ async function handleAdminApi(req, res, urlPath) {
return;
}
// Several at once — a fresh install picking its set. One result per id;
// a failure stops nothing else.
if (urlPath === '/api/admin/modules/install' && req.method === 'POST') {
if (refuseAdminWrite(req, res)) return;
let body = {};
try {
body = JSON.parse((await readBody(req)) || '{}');
} catch {
return sendJson(res, 400, { error: 'Malformed request.' });
}
const ids = Array.isArray(body.ids) ? [...new Set(body.ids.map((id) => String(id)))] : [];
if (!ids.length) return sendJson(res, 400, { error: 'Nothing to install.' });
const results = [];
for (const id of ids) {
try {
results.push({ ok: true, ...(await installModule(id)) });
} catch (err) {
results.push({ ok: false, id, error: err?.message || String(err) });
}
}
return sendJson(res, 200, { ok: results.every((r) => r.ok), results });
}
const install = urlPath.match(/^\/api\/admin\/modules\/([^/]+)\/install$/);
if (install && req.method === 'POST') {
if (refuseAdminWrite(req, res)) return;
@@ -2074,6 +2164,7 @@ server.requestTimeout = 0;
/* ── boot ───────────────────────────────────────────────────────────── */
unbundleModules();
discoverModules();
mountAllModules();
+29
View File
@@ -152,10 +152,39 @@ const server = http.createServer((req, res) => {
if (p === '/v1/timers') return sendJson(res, TIMERS.filter((t) => !DROP.has(t.id.uuid)));
if (p === '/v1/timers/current') return sendJson(res, currentTimes().filter((t) => !DROP.has(t.id.uuid)));
if (p === '/v1/timecode/status' && !NO_LTC) return sendJson(res, timecodeStatus());
if (p === '/v1/transport/presentation/current') return sendJson(res, transport().current);
if (p === '/v1/transport/presentation/time') return sendJson(res, transport().time);
sendJson(res, { error: 'not found' }, 404);
});
/* ── transport (video countdown): a 4-minute cycle ─────────────────
0–60 s "Sermon Bumper.mp4" (3:00) playing
60–75 s the same bumper paused at 1:00
75–90 s playing again
90–120 s nothing loaded
120–240 s "Autumn Loop.mp4" (0:15) playing and wrapping — the module
must infer looping from the position jumping back.
Shapes match ProPresenter 21.4 live: `current` = { is_playing, uuid,
name, artist, audio_only, duration }, `time` = bare seconds (float). */
function transport() {
const phase = ((Date.now() - startedAt) / 1000) % 240;
const none = { current: { is_playing: false, uuid: '', name: '', artist: '', audio_only: false, duration: 0 }, time: -1 };
if (phase < 90) {
const playing = phase < 60 || phase >= 75;
const pos = Math.min(phase, 60) + (phase >= 75 ? phase - 75 : 0);
return {
current: { is_playing: playing, uuid: 'MEDIA-BUMPER', name: 'Sermon Bumper.mp4', artist: '', audio_only: false, duration: 180 },
time: Math.round(pos * 10) / 10,
};
}
if (phase < 120) return none;
return {
current: { is_playing: true, uuid: 'MEDIA-LOOP', name: 'Autumn Loop.mp4', artist: '', audio_only: false, duration: 15 },
time: Math.round(((phase - 120) % 15) * 10) / 10,
};
}
/* ── stage-display websocket (/stagedisplay) ─────────────────────── */
const cryptoMod = require('crypto');
+70 -9
View File
@@ -1,9 +1,15 @@
/**
* Mock ProdCom API for verifying the prodcom-transcript module without a
* live ProdCom. Serves the endpoints the module uses — channels, groups,
* transcript history and the SSE stream — and simulates live speech:
* entries appear in progress, grow word by word (same id, in-place update),
* then complete.
* transcript history, the SSE stream and POST /api/v1/channels/{id}/send —
* and simulates live speech: entries appear in progress, grow word by word
* (same id, in-place update), then complete. Text sent to a channel lands
* in that channel's history as a completed entry with source "typed" and
* goes out on the stream, which is how a send from the Send Message module
* can be watched arriving in the transcript tile. A text containing "!429"
* answers RATE_LIMITED; an unknown channel NOT_FOUND. With PRODCOM_MOCK_KEY
* set, every request must carry it as a Bearer token (UNAUTHORIZED
* otherwise) — the module's "API key" field.
*
* node tools/prodcom-mock.js [port] (default 24480)
*
@@ -17,12 +23,13 @@ const http = require('http');
const PORT = Number.parseInt(process.argv[2] || '24480', 10);
const STEP_MS = Number.parseInt(process.env.PRODCOM_STEP_MS || '700', 10);
const API_KEY = String(process.env.PRODCOM_MOCK_KEY || '');
const CHANNELS = [
{ id: 'ch-stage', name: 'Stage', color: '#e0645c' },
{ id: 'ch-foh', name: 'FOH', color: '#5c9de0' },
{ id: 'ch-video', name: 'Video', color: '#5cd08c' },
{ id: 'ch-light', name: 'Lighting', color: '#e0b45c' },
{ id: 'ch-stage', name: 'Stage', color: '#e0645c', sourceType: 'localAudio', typingEnabled: true, isSelected: true, unreadCount: 0 },
{ id: 'ch-foh', name: 'FOH', color: '#5c9de0', sourceType: 'localAudio', typingEnabled: true, isSelected: false, unreadCount: 0 },
{ id: 'ch-video', name: 'Video', color: '#5cd08c', sourceType: 'network', typingEnabled: false, isSelected: false, unreadCount: 0 },
{ id: 'ch-light', name: 'Lighting', color: '#e0b45c', sourceType: 'network', typingEnabled: false, isSelected: false, unreadCount: 0 },
];
const GROUPS = [
@@ -69,6 +76,7 @@ function stepSimulation() {
text: words[0],
date: new Date().toISOString(),
inProgress: true,
source: 'audio',
};
speaking = { entry, words, at: 1 };
history.push(entry);
@@ -90,15 +98,68 @@ function stepSimulation() {
setInterval(stepSimulation, STEP_MS);
function sendJson(res, body) {
res.writeHead(200, { 'Content-Type': 'application/json' });
function sendJson(res, body, status = 200) {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(body));
}
/** ProdCom's error envelope. */
function sendError(res, status, code, message) {
sendJson(res, { error: { code, message }, meta: { timestamp: new Date().toISOString() } }, status);
}
function readBody(req) {
return new Promise((resolve) => {
let data = '';
req.on('data', (c) => { data += c; });
req.on('end', () => {
try { resolve(data ? JSON.parse(data) : {}); } catch { resolve(null); }
});
req.on('error', () => resolve(null));
});
}
/** Typed text onto a channel: a completed entry with source "typed", like ProdCom makes. */
function sendText(channel, text) {
const entry = {
id: 'e' + RUN + '-' + nextId++,
channelId: channel.id,
channelName: channel.name,
text,
date: new Date().toISOString(),
inProgress: false,
source: 'typed',
hasBeenSeen: false,
};
history.push(entry);
if (history.length > 200) history.shift();
broadcast(entry);
console.log(`[prodcom-mock] typed → ${channel.name}: ${text}`);
}
const server = http.createServer((req, res) => {
const url = new URL(req.url, `http://x.invalid`);
const p = url.pathname;
if (API_KEY && req.headers.authorization !== `Bearer ${API_KEY}`) {
return sendError(res, 401, 'UNAUTHORIZED', 'Authentication required or invalid API key');
}
// POST /api/v1/channels/{id or name}/send { text }
const send = /^\/api\/v1\/channels\/([^/]+)\/send$/.exec(p);
if (send && req.method === 'POST') {
const ref = decodeURIComponent(send[1]);
const channel = CHANNELS.find((c) => c.id === ref) || CHANNELS.find((c) => c.name.toLowerCase() === ref.toLowerCase());
return void readBody(req).then((body) => {
if (!channel) return sendError(res, 404, 'NOT_FOUND', 'Channel not found');
const text = typeof body?.text === 'string' ? body.text.trim() : '';
if (!body || !text) return sendError(res, 400, 'VALIDATION_ERROR', 'text is required');
if (text.includes('!429')) return sendError(res, 429, 'RATE_LIMITED', 'Slow down');
sendText(channel, text);
sendJson(res, { data: { sent: true }, meta: { timestamp: new Date().toISOString() } });
});
}
if (p === '/api/v1/channels') return sendJson(res, { data: CHANNELS });
if (p === '/api/v1/groups') return sendJson(res, { data: GROUPS });
if (p === '/api/v1/transcript') {
+203
View File
@@ -0,0 +1,203 @@
'use strict';
/**
* A packaged ProdDash carries no modules. This drives a packaged copy of the
* shell — server.js and its client in a folder with no .git — through the
* three things that make that true:
*
* 1. an install made before 1.10.0 still has modules in its app folder:
* at boot they move into the data directory once, executables keeping
* their mode, an uninstalled one is dropped, and the app folder's
* modules/ is gone;
* 2. a shell update from an archive that carries modules/ never writes
* them into the app folder — they show up in the catalog instead;
* 3. a fresh install lists everything the repo offers, and installing
* several at once lands them in the data directory and mounts them.
*
* node tools/unbundled.test.js
*
* Plain Node, no dependencies: a mock forge, a temp app folder, a temp data
* directory. Exits non-zero on the first failure and cleans up after itself.
*/
const assert = require('node:assert/strict');
const { spawn, execFileSync } = require('node:child_process');
const fs = require('node:fs');
const http = require('node:http');
const net = require('node:net');
const os = require('node:os');
const path = require('node:path');
const REPO = path.join(__dirname, '..');
function freePort() {
return new Promise((resolve, reject) => {
const probe = net.createServer();
probe.listen(0, '127.0.0.1', () => {
const { port } = probe.address();
probe.close(() => resolve(port));
});
probe.on('error', reject);
});
}
async function waitFor(url, ms = 15000) {
const deadline = Date.now() + ms;
let last = '';
while (Date.now() < deadline) {
try {
const r = await fetch(url);
if (r.ok) return;
last = 'HTTP ' + r.status;
} catch (err) {
last = err.message;
}
await new Promise((r) => setTimeout(r, 200));
}
throw new Error('server did not come up: ' + last);
}
function writeModule(dir, id, version, extra = {}) {
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'module.json'), JSON.stringify({ id, name: id[0].toUpperCase() + id.slice(1), version, client: 'client.js', ...extra }));
fs.writeFileSync(path.join(dir, 'client.js'), 'export default function () {}\n');
}
/** The repo as a forge would archive it: one top-level folder, the shell files, and modules/. */
function buildArchive(dir) {
const top = path.join(dir, 'ProdDash-main');
fs.mkdirSync(top, { recursive: true });
fs.copyFileSync(path.join(REPO, 'server.js'), path.join(top, 'server.js'));
fs.writeFileSync(path.join(top, 'package.json'), JSON.stringify({ name: 'proddash', version: '9.9.9' }));
writeModule(path.join(top, 'modules', 'demo'), 'demo', '2.0.0');
writeModule(path.join(top, 'modules', 'other'), 'other', '1.0.0');
writeModule(path.join(top, 'modules', 'third'), 'third', '1.0.0');
const out = path.join(dir, 'main.tar.gz');
execFileSync('tar', ['-czf', out, '-C', dir, 'ProdDash-main']);
return fs.readFileSync(out);
}
/** A packaged install as it was before 1.10.0: the shell plus bundled modules, no .git. */
function buildPackagedApp(app) {
fs.mkdirSync(path.join(app, 'config'), { recursive: true });
fs.copyFileSync(path.join(REPO, 'server.js'), path.join(app, 'server.js'));
fs.copyFileSync(path.join(REPO, 'package.json'), path.join(app, 'package.json'));
fs.cpSync(path.join(REPO, 'public'), path.join(app, 'public'), { recursive: true });
fs.writeFileSync(path.join(app, 'config', 'proddash.json'), JSON.stringify({ port: 24500 }));
writeModule(path.join(app, 'modules', 'demo'), 'demo', '1.0.0');
fs.mkdirSync(path.join(app, 'modules', 'demo', 'bin'));
fs.writeFileSync(path.join(app, 'modules', 'demo', 'bin', 'demo-helper'), '#!/bin/sh\necho helper\n');
fs.chmodSync(path.join(app, 'modules', 'demo', 'bin', 'demo-helper'), 0o755);
writeModule(path.join(app, 'modules', 'gone'), 'gone', '1.0.0');
}
(async () => {
const work = fs.mkdtempSync(path.join(os.tmpdir(), 'proddash-unbundled-'));
const app = path.join(work, 'app');
const dataDir = path.join(work, 'data');
fs.mkdirSync(dataDir);
buildPackagedApp(app);
// The operator had uninstalled "gone" before this update.
fs.writeFileSync(path.join(dataDir, 'modules.json'), JSON.stringify({ gone: { uninstalled: true } }));
const archive = buildArchive(path.join(work, 'forge'));
const forge = http.createServer((req, res) => {
if (req.url.startsWith('/michael/ProdDash/archive/main.tar.gz')) {
res.writeHead(200, { 'Content-Type': 'application/gzip' });
return res.end(archive);
}
res.writeHead(404);
res.end();
});
const forgePort = await freePort();
await new Promise((r) => forge.listen(forgePort, '127.0.0.1', r));
const port = await freePort();
const base = `http://127.0.0.1:${port}`;
const env = {
...process.env,
PRODDASH_DATA_DIR: dataDir,
PORT: String(port),
PRODDASH_FORGE: `http://127.0.0.1:${forgePort}`,
PRODDASH_REPO: 'michael/ProdDash',
PRODDASH_NO_REMOTE_CHECK: '1',
PRODDASH_LAUNCHER: '1', // a supervisor is watching: an update exits 75 instead of respawning
};
let log = '';
let child = null;
const start = () => {
child = spawn(process.execPath, ['server.js'], { cwd: app, env, stdio: ['ignore', 'pipe', 'pipe'] });
child.stdout.on('data', (d) => { log += d; });
child.stderr.on('data', (d) => { log += d; });
return child;
};
const exited = (proc) => new Promise((resolve) => proc.on('exit', resolve));
const api = async (p, init = {}) => {
const r = await fetch(base + p, { headers: { 'Content-Type': 'application/json' }, ...init });
return { status: r.status, body: await r.json().catch(() => ({})) };
};
const moduleIds = async () => (await api('/api/modules')).body.modules.map((m) => m.id).sort();
let failed = false;
try {
// ── 1. the move ──
start();
await waitFor(base + '/api/theme');
const moved = path.join(dataDir, 'modules', 'demo');
assert.ok(fs.existsSync(path.join(moved, 'module.json')), 'demo moved into the data directory');
const helper = path.join(moved, 'bin', 'demo-helper');
assert.ok(fs.existsSync(helper), 'its compiled helper came along');
assert.ok(fs.statSync(helper).mode & 0o111, 'and is still executable');
assert.equal(fs.existsSync(path.join(dataDir, 'modules', 'gone')), false, 'an uninstalled module is dropped, not moved');
assert.equal(fs.existsSync(path.join(app, 'modules')), false, "the app folder's modules/ is gone");
assert.deepEqual(await moduleIds(), ['demo'], 'demo runs, gone does not');
assert.match(log, /moved bundled module "demo" v1\.0\.0 into the data directory/);
assert.match(log, /the app folder carries no modules now/);
const state = (await api('/api/admin/state')).body;
assert.equal(state.modules.find((m) => m.id === 'demo')?.source, 'installed', 'demo is an installed copy now');
// The catalog sees the repo's modules/ — as offers, not as a bundle.
let cat = (await api('/api/admin/catalog?refresh=1')).body;
assert.equal(cat.shell.remote.error, '', 'the mock forge answers: ' + cat.shell.remote.error);
assert.deepEqual(cat.updates.map((u) => `${u.id} ${u.installedVersion}->${u.version}`), ['demo 1.0.0->2.0.0']);
assert.deepEqual(cat.available.map((a) => a.id).sort(), ['gone', 'other', 'third'].filter((id) => id !== 'gone'), 'other and third are on offer');
// ── 2. a shell update carries no modules ──
const running = child;
const up = await api('/api/admin/update', { method: 'POST', body: '{}' });
assert.equal(up.status, 200, 'update: ' + JSON.stringify(up.body));
assert.equal(await exited(running), 75, 'the server asks its supervisor for a restart');
assert.equal(fs.existsSync(path.join(app, 'modules')), false, 'the archive\'s modules/ was not written into the app folder');
assert.equal(JSON.parse(fs.readFileSync(path.join(app, 'package.json'), 'utf8')).version, '9.9.9', 'but the shell itself was updated');
log = '';
start();
await waitFor(base + '/api/theme');
assert.doesNotMatch(log, /moved bundled module/, 'nothing left to move on the second start');
assert.deepEqual(await moduleIds(), ['demo'], 'still just demo, from the data directory');
cat = (await api('/api/admin/catalog')).body;
assert.deepEqual(cat.available.map((a) => a.id).sort(), ['other', 'third'], 'the new modules are offers, not installs');
// ── 3. several at once ──
const many = await api('/api/admin/modules/install', { method: 'POST', body: JSON.stringify({ ids: ['other', 'third', 'nope'] }) });
assert.equal(many.status, 200);
assert.equal(many.body.ok, false, 'one of them does not exist');
assert.deepEqual(many.body.results.map((r) => `${r.id}:${r.ok}`), ['other:true', 'third:true', 'nope:false']);
assert.ok(fs.existsSync(path.join(dataDir, 'modules', 'other', 'module.json')), 'other landed in the data directory');
assert.deepEqual(await moduleIds(), ['demo', 'other', 'third'], 'and both are mounted');
const empty = await api('/api/admin/modules/install', { method: 'POST', body: '{}' });
assert.equal(empty.status, 400, 'nothing to install is said');
console.log('unbundled shell: every check passed');
} catch (err) {
failed = true;
console.error('FAIL:', err.message);
console.error('--- last of the server log ---\n' + log.slice(-2500));
} finally {
try { child?.kill('SIGTERM'); } catch { /* gone */ }
forge.close();
await new Promise((r) => setTimeout(r, 400));
fs.rmSync(work, { recursive: true, force: true });
}
process.exit(failed ? 1 : 0);
})();
+176
View File
@@ -0,0 +1,176 @@
'use strict';
/**
* The update check against a forge that misbehaves: the admin page must say
* what went wrong in words, never zlib's "incorrect header check".
*
* node tools/update-check.test.js
*
* Plain Node, no dependencies. Starts a mock forge whose answer to the
* branch-archive download can be switched at runtime, starts server.js on a
* spare port pointed at it, and reads the shell status the admin page shows
* after each kind of answer:
*
* - a Gitea that requires a sign-in redirects the download to its login
* page (a 200 of HTML) — the case that hit both booths on 2026-09-29;
* - a captive portal or a wrong address answers HTML outright;
* - a plain HTTP error;
* - and a real archive, which must still parse and offer the update.
*
* Exits non-zero on the first failure and always stops what it started.
*/
const assert = require('node:assert/strict');
const { spawn, execFileSync } = require('node:child_process');
const fs = require('node:fs');
const http = require('node:http');
const net = require('node:net');
const os = require('node:os');
const path = require('node:path');
const ROOT = path.join(__dirname, '..');
function freePort() {
return new Promise((resolve, reject) => {
const probe = net.createServer();
probe.listen(0, '127.0.0.1', () => {
const { port } = probe.address();
probe.close(() => resolve(port));
});
probe.on('error', reject);
});
}
async function waitFor(url, ms = 15000) {
const deadline = Date.now() + ms;
let last = '';
while (Date.now() < deadline) {
try {
const r = await fetch(url);
if (r.ok) return;
last = 'HTTP ' + r.status;
} catch (err) {
last = err.message;
}
await new Promise((r) => setTimeout(r, 200));
}
throw new Error('server did not come up: ' + last);
}
/** A branch archive the way a forge would build one: one top-level folder. */
function buildArchive(dir) {
const top = path.join(dir, 'ProdDash-main');
fs.mkdirSync(path.join(top, 'modules', 'demo'), { recursive: true });
fs.writeFileSync(path.join(top, 'package.json'), JSON.stringify({ name: 'proddash', version: '9.9.9' }));
fs.writeFileSync(path.join(top, 'modules', 'demo', 'module.json'), JSON.stringify({ id: 'demo', name: 'Demo', version: '1.0.0', client: 'client.js' }));
fs.writeFileSync(path.join(top, 'modules', 'demo', 'client.js'), 'export default function () {}\n');
const out = path.join(dir, 'main.tar.gz');
execFileSync('tar', ['-czf', out, '-C', dir, 'ProdDash-main']);
return fs.readFileSync(out);
}
(async () => {
const work = fs.mkdtempSync(path.join(os.tmpdir(), 'proddash-update-test-'));
const dataDir = path.join(work, 'data');
fs.mkdirSync(dataDir);
const archive = buildArchive(path.join(work, 'forge'));
// ── the mock forge ──
let mode = 'ok';
const LOGIN_PAGE = '<!DOCTYPE html>\n<html><head><title>Sign in</title></head><body>Sign in to continue</body></html>';
const forge = http.createServer((req, res) => {
const url = new URL(req.url, 'http://forge.invalid');
if (url.pathname === '/user/login') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
return res.end(LOGIN_PAGE);
}
if (url.pathname !== '/michael/ProdDash/archive/main.tar.gz') {
res.writeHead(404, { 'Content-Type': 'text/plain' });
return res.end('not here');
}
switch (mode) {
case 'login-redirect':
res.writeHead(303, { Location: '/user/login?redirect_to=' + encodeURIComponent(url.pathname) });
return res.end();
case 'html':
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
return res.end('<html><body>You must log in to this network first</body></html>');
case 'notfound':
res.writeHead(404, { 'Content-Type': 'text/plain' });
return res.end('no such branch');
default:
res.writeHead(200, { 'Content-Type': 'application/gzip' });
return res.end(archive);
}
});
const forgePort = await freePort();
await new Promise((r) => forge.listen(forgePort, '127.0.0.1', r));
const forgeBase = `http://127.0.0.1:${forgePort}`;
// ── ProdDash, pointed at it ──
const port = await freePort();
const child = spawn(process.execPath, ['server.js'], {
cwd: ROOT,
env: {
...process.env,
PRODDASH_DATA_DIR: dataDir,
PORT: String(port),
PRODDASH_FORGE: forgeBase,
PRODDASH_REPO: 'michael/ProdDash',
PRODDASH_NO_REMOTE_CHECK: '1',
PRODDASH_LAUNCHER: '1',
},
stdio: ['ignore', 'pipe', 'pipe'],
});
let log = '';
child.stdout.on('data', (d) => { log += d; });
child.stderr.on('data', (d) => { log += d; });
const base = `http://127.0.0.1:${port}`;
/** What the admin page shows after a forced check. Admin is open: a fresh data dir has no PIN. */
const check = async (m) => {
mode = m;
const r = await fetch(base + '/api/admin/catalog?refresh=1');
assert.equal(r.status, 200, `catalog: HTTP ${r.status}`);
const body = await r.json();
return body.shell;
};
let failed = false;
try {
await waitFor(base + '/api/theme');
let shell = await check('login-redirect');
assert.match(shell.remote.error, /requires a sign-in/, 'a login redirect is named as such: ' + shell.remote.error);
assert.match(shell.remote.error, /require sign-in to view/, 'and the Gitea setting to look at is named');
assert.doesNotMatch(shell.remote.error, /header check/, 'never zlib\'s words');
assert.equal(shell.updateAvailable, false);
shell = await check('html');
assert.match(shell.remote.error, /answered with a web page instead of the michael\/ProdDash@main archive/, shell.remote.error);
shell = await check('notfound');
assert.match(shell.remote.error, /HTTP 404 fetching michael\/ProdDash@main/, shell.remote.error);
shell = await check('ok');
assert.equal(shell.remote.error, '', 'a real archive clears the error: ' + shell.remote.error);
assert.equal(shell.remote.version, '9.9.9', 'and is read');
assert.equal(shell.updateAvailable, true, 'and offered');
// Back to a broken forge: the last good read is not mistaken for a current one.
shell = await check('login-redirect');
assert.match(shell.remote.error, /requires a sign-in/);
console.log('update check: every check passed');
} catch (err) {
failed = true;
console.error('FAIL:', err.message);
console.error('--- last of the server log ---\n' + log.slice(-2000));
} finally {
child.kill('SIGTERM');
forge.close();
await new Promise((r) => setTimeout(r, 400));
fs.rmSync(work, { recursive: true, force: true });
}
process.exit(failed ? 1 : 0);
})();