Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee3b1b51bf | ||
|
|
4e5a1bc393 | ||
|
|
7e46fffc34 | ||
|
|
b20beb250b | ||
|
|
9d93634382 | ||
|
|
3cba68e256 | ||
|
|
bcae4bb318 | ||
|
|
0b300d6ddb | ||
|
|
1101ffac34 | ||
|
|
7e758ecca8 | ||
|
|
2bd47fb96a | ||
|
|
0801c119ae | ||
|
|
433be06bc7 | ||
|
|
74318eb34e | ||
|
|
a4f8a807ff | ||
|
|
59730837ad | ||
|
|
4c459e2745 | ||
|
|
b9dd4178c4 | ||
|
|
a6a5d71ef0 | ||
|
|
c55c3d2baf | ||
|
|
d3e059a878 | ||
|
|
38d82d2ac6 | ||
|
|
9f831f04bc | ||
|
|
a8ef35b287 | ||
|
|
a45552fed3 | ||
|
|
a5e8ecb21f |
@@ -2,3 +2,5 @@
|
||||
!package.json
|
||||
!src/
|
||||
!src/**
|
||||
!scripts/
|
||||
!scripts/**
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
PULSE_SIGNAGE_IMAGE=git.lzstealth.com/lzstealth/pulse-signage:latest
|
||||
PULSE_SIGNAGE_SHARED_SECRET=
|
||||
|
||||
DB_HOST=mysql
|
||||
DB_PORT=3306
|
||||
DB_NAME=pulse-signage
|
||||
DB_USER=pulse-signage
|
||||
DB_PASSWORD=signage_password
|
||||
MYSQL_ROOT_PASSWORD=root_password
|
||||
|
||||
PLAYER_PUBLIC_BASE_URL=http://localhost:8081
|
||||
PLAYER_INTERNAL_BASE_URL=http://player:8081
|
||||
|
||||
SESSION_MAX_AGE_DAYS=14
|
||||
DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_NAME=Admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin
|
||||
PASSWORD_HASH_ITERATIONS=310000
|
||||
@@ -3,6 +3,8 @@ media/
|
||||
!src/web/lib/media/
|
||||
!src/web/lib/media/**
|
||||
docker-compose.dev.yml
|
||||
/docker-compose/*.dev.yml
|
||||
/docker-compose/*.env
|
||||
/dev-demo-seed.js
|
||||
.vscode/
|
||||
.env
|
||||
@@ -10,3 +12,4 @@ npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.DS_Store
|
||||
TODO.md
|
||||
|
||||
+217
@@ -2,6 +2,223 @@
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## 2.6.9 - 2026-08-08
|
||||
|
||||
### Fixed
|
||||
|
||||
- The connected-clients view no longer exposes or sorts by client IP, so the table stays focused on the player identity, screen, and playback state.
|
||||
- The connected-clients dashboard row renderer now keeps the actions column aligned after removing the IP column, so row updates no longer append a duplicate actions cell.
|
||||
|
||||
## 2.6.8 - 2026-08-08
|
||||
|
||||
### Fixed
|
||||
|
||||
- The screen-group command buttons stay disabled until a real target group is selected, so the placeholder "Select Screen Group" state cannot send commands.
|
||||
|
||||
## 2.6.7 - 2026-08-08
|
||||
|
||||
### Fixed
|
||||
|
||||
- Admin client commands now stay on the bridge for remote players, so screen control no longer depends on a public player address.
|
||||
- The connected-clients screen-group controls now use the same async bulk-command path as the dashboard, including the All Screens option and live pause/blackout toggles.
|
||||
|
||||
## 2.6.6 - 2026-08-07
|
||||
|
||||
### Fixed
|
||||
|
||||
- Timetable entry editing now validates end times locally, requires the end to be at least one minute after the start, and highlights the end field when the value is invalid.
|
||||
|
||||
## 2.6.5 - 2026-08-07
|
||||
|
||||
### Added
|
||||
|
||||
- Multiple players are now supported across the player registry, dashboard snapshots, and screen group management, so a deployment can track more than one connected player at a time.
|
||||
- The player-agent can now run remotely, which lets a player connect through the bridge instead of requiring everything to stay on the same host.
|
||||
- The Docker Compose setup now includes a public stack with a player bridge service and a separate remote player stack, so local and split-device deployments share the same documented layout.
|
||||
- Dedicated local and remote compose manifests now live at `docker-compose/docker-compose.yml` and `docker-compose/docker-compose.remote.yml`, with matching example env files for the two deployment modes.
|
||||
- Admin client commands now have a dedicated route and test coverage, which keeps dashboard actions aligned with the current player control-plane flow.
|
||||
|
||||
### Changed
|
||||
|
||||
- Screen group views now show each registered player's public base URL and computed player URL on the edit screen instead of assuming a single local player.
|
||||
- The dashboard status indicator now reports the connected player count, which makes the live feed status more explicit when several players are online.
|
||||
- Player command dispatch, playlist playback, and render preloading were tightened so the player keeps using the active web base URL and can warm assets before the slide is shown.
|
||||
- Playlist video-duration selection now uses the longest matching video region when a slide contains more than one video region.
|
||||
- Media sync, font sync, and upload sync now follow the newer player-agent workflow, keeping background tasks and dashboard refreshes consistent with split-device deployments.
|
||||
- The onboarding landing page now shows a built-in QR placeholder and falls back to it when the QR request fails, so the screen never starts blank.
|
||||
- Upload sync now resolves the player internal base URL once per batch and reuses it for queued upload and delete operations, keeping mirrored media writes pointed at the active player endpoint.
|
||||
- The connected clients list now defaults to client name, then IP address, so rows stay in a stable order when connection details change.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Connected clients search results now keep the row action column, because the row template resolves `currentUser` from the parent view context while rendering inside the `clients` loop.
|
||||
- The move-client modal now carries the row's player base URL through to the redirect step, so clients move correctly even when local and bridge-backed players are mixed.
|
||||
- Paginated table cards now only apply their minimum height when the table content would otherwise exceed that threshold, which keeps short result sets compact in smaller browser windows.
|
||||
|
||||
## 2.6.4 - 2026-08-07
|
||||
|
||||
### Fixed
|
||||
|
||||
- The screen table no longer stores a player foreign key, and screen/player URLs now resolve from the current player registration instead of a screen assignment.
|
||||
|
||||
## 2.6.3 - 2026-08-07
|
||||
|
||||
### Fixed
|
||||
|
||||
- The screen table no longer enforces a foreign key to the player table, which keeps player assignments flexible while preserving the existing screen schema.
|
||||
|
||||
## 2.6.2 - 2026-08-07
|
||||
|
||||
### Fixed
|
||||
|
||||
- The player registry now upgrades to an integer player id with a separate player identifier so the schema migration can complete cleanly on existing databases.
|
||||
- Dashboard screen lookups now tolerate the upgraded player table layout during the rollout.
|
||||
|
||||
## 2.6.1 - 2026-08-06
|
||||
|
||||
### Fixed
|
||||
|
||||
|
||||
### Changed
|
||||
|
||||
- The web side now resolves the player base URL from the database-backed player registration record instead of depending on a web-container environment fallback.
|
||||
- Player registrations now store a separate friendly identifier, so a player can keep the same device key while showing a label like `Shop2`.
|
||||
|
||||
## 2.5.14 - 2026-08-06
|
||||
|
||||
### Added
|
||||
|
||||
- Added branded Windows and Linux kiosk launcher downloads on the dashboard, with updated copy that explains the launcher behavior more clearly.
|
||||
- Kiosk launchers now start the browser in kiosk mode, suppress notifications for Chromium-based browsers, and use the correct Firefox kiosk flag.
|
||||
|
||||
|
||||
## 2.5.13 - 2026-08-05
|
||||
|
||||
### Fixed
|
||||
|
||||
- Slide and template save forms now allow larger multipart text fields, so rich region content no longer trips Multer's default field-value limit.
|
||||
|
||||
## 2.5.12 - 2026-08-05
|
||||
|
||||
### Fixed
|
||||
|
||||
- The auth route test now loads the alias bootstrap before the login flow, so isolated test runs do not depend on prior module initialization.
|
||||
- The slide editor now blocks pasted data images in TinyMCE so image content must come through the upload flow.
|
||||
|
||||
## 2.5.11 - 2026-08-05
|
||||
|
||||
### Fixed
|
||||
|
||||
- Single-slide playlists now re-render the active slide immediately when a refresh arrives, instead of waiting for a transition that never happens.
|
||||
- Playlist create and update flows now redirect to the canonical `/playlists/:id/edit` path after saving.
|
||||
- Slide preview popups now keep rich-text spacing and line height consistent with the editor preview.
|
||||
|
||||
## 2.5.10 - 2026-08-05
|
||||
|
||||
### Fixed
|
||||
|
||||
- Slide editor rich-text updates now keep the hidden field and preview state in sync after inline formatting actions.
|
||||
|
||||
## 2.5.9 - 2026-08-05
|
||||
|
||||
### Fixed
|
||||
|
||||
- Screen playlist refreshes now wait until the next slide transition before applying a pending update, so one-slide playlists do not swap immediately during a refresh.
|
||||
- Playlist rows now show the mute control for any playable media region, including RTMP slides, instead of only video regions.
|
||||
|
||||
## 2.5.8 - 2026-08-05
|
||||
|
||||
### Fixed
|
||||
|
||||
- MariaDB migrations now retry alternate foreign-key constraint names when screen-to-player constraint creation reports a duplicate-key error.
|
||||
|
||||
## 2.5.7 - 2026-08-05
|
||||
|
||||
### Fixed
|
||||
|
||||
- QR template backgrounds now use a single solid color only, and the editor no longer exposes a background gradient mode.
|
||||
|
||||
## 2.5.6 - 2026-08-05
|
||||
|
||||
### Added
|
||||
|
||||
- Onboarding QR rendering now uses the vendored `qr-code-styling` library directly, with a wider quiet zone and extra frame padding so the code does not clip at the corners.
|
||||
|
||||
### Changed
|
||||
|
||||
- The shared QR helper now renders `qr-code-styling` in Node without the old `qrcode` or `qrcode-generator` packages.
|
||||
- The onboarding QR endpoint now generates the styled QR at request time, and the player onboarding page requests it only after confirming the player is not already onboarded.
|
||||
- Playlist QR preview backfill now uses the same styled QR helper as onboarding, so playlist snapshots and generated previews stay consistent.
|
||||
- The onboarding QR layout now keeps the code inset within its frame so the corners have more breathing room.
|
||||
|
||||
## 2.5.5 - 2026-08-04
|
||||
|
||||
### Added
|
||||
|
||||
- A shared Dupe flow was added to most admin create pages and list views, including roles, users, playlists, slides, templates, canvas sizes, announcements, and supported data sources.
|
||||
|
||||
### Changed
|
||||
|
||||
- RBAC roles now include a Dupe action that opens a copy-on-create flow with the selected permissions already populated.
|
||||
- Users now include a Dupe action that opens the add-user form with the copied name and roles, while leaving the username blank for a new login.
|
||||
- User usernames are now editable from the admin users section, while the personal account password page remains unchanged.
|
||||
- The users form now allows creating an account without assigning any roles.
|
||||
- Save and New on the users form now returns to the blank create page instead of falling back to the list.
|
||||
- Password updates now accept a slightly lighter policy of 10 characters with 3 of 4 character classes, and the account and user password forms now describe the updated requirement.
|
||||
- The slide rich-text editor now groups underline, strikethrough, subscript, and superscript into a single split-button control, with the main button using the underline icon and the dropdown exposing the other text-format actions.
|
||||
- Chip formatting in the slide rich-text editor now uses a reusable inline-format helper so the chip action continues to sync and mark the editor as edited when applied.
|
||||
- RSS, API, and timetable placeholder help text now uses the same transform examples, spacing, and typography as the timetable version, with the hint shown after the visible placeholders and before any overflow disclosure.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Cells and inputs now enforce route-specific character limits on the form itself and on the matching save paths, so overlong values no longer fail at submit time.
|
||||
- Playlist rows now use a grip drag handle with separate up/down move controls, and the drag grip cursor now changes to grab and grabbing on hover and drag.
|
||||
- Playlist duration inputs now respect a min-only limit correctly, so the shared limiter no longer coerces values down to 0 when no max attribute is present.
|
||||
- Playlist row video and mute toggles now use the correct filled/outline Bootstrap button styles for their current state without relying on the `active` class.
|
||||
- Slides table search now only matches slide titles and template names, and no longer searches within slide content.
|
||||
- Banner marquee text now measures its real cycle width so top-banner and lower-third announcements loop continuously instead of resetting from a fixed start position.
|
||||
- Slide editor template selection now stays editable on blank slides until the user makes a real content edit, so TinyMCE hydration no longer locks the canvas immediately.
|
||||
- Slide editor region cards now share a common header shell, so the image and video chips stay aligned with the other region types on the Video Webpage and HTML RTMP pages.
|
||||
- Firefox preview popup now centers the preview canvas in normal layout flow and scales from the center, so the popup preview lines up correctly in Chrome and Firefox.
|
||||
- Canvas size edits now keep the width and height fields locked while the size is in use, and oversized canvas dimensions are rejected at 16384 instead of reaching the save path.
|
||||
- Schedule rules now start collapsed by default, use the built-in card collapse behavior, and keep validation messages visible without re-highlighting empty paired inputs.
|
||||
- Timetable group deletes now scan slide content for the actual `timetable_group_id` field, so groups that are still referenced by slides stay protected from deletion.
|
||||
- Timetable add and edit pages now keep cancel confirmation tied to timetable entry edits, so changes inside the entries table are treated as unsaved form changes.
|
||||
- Screen add and edit pages now keep the Player URL box in a stable two-column layout, so switching between the forms no longer causes the page to jump or shift.
|
||||
- Screen add pages now show the secondary Save and Close / Save and New actions, and screen edit delete actions now prompt for confirmation before removing the screen.
|
||||
- Admin user password resets now keep the selected user in view by returning to that user's edit page after saving.
|
||||
- Account password saves now refresh the page after the success toast is queued so the confirmation message stays visible.
|
||||
- Shared toast handling now preserves a pending success message across the redirect so refreshes do not drop the confirmation banner.
|
||||
- Announcement create and edit pages now keep the save action buttons visible, and the edit-page delete action now prompts for confirmation before deleting.
|
||||
- Active announcements are now blocked from deletion with a clearer edit-page message that explains why.
|
||||
- Slide template create now shows the background image remove button and clear flag, matching the edit page behavior.
|
||||
- Template create now exposes Save & Close and Save & New actions, and template edit delete actions now use the shared action-button helper with a confirmation prompt instead of a separate hidden form.
|
||||
- The advanced animation modal now shows intro, outro, and loop durations as 1-200% fields, with 100% saving back as 1000ms.
|
||||
- The advanced animation modal now hard-limits repeat counts to 999 so attention-seeker animations cannot be configured with unbounded loops.
|
||||
- Template editor region boxes now rerender when the canvas or stage resizes, and region width/height changes now keep the lock ratio, stay within the canvas, and shift back on-canvas instead of spilling over.
|
||||
- Background tasks and scheduled tasks now render timestamps in 24-hour format, and the background task queue keeps a confirmation prompt before clearing finished items.
|
||||
|
||||
## 2.5.4 - 2026-08-03
|
||||
|
||||
### Changed
|
||||
|
||||
- The API source bearer token field now uses a password input with a right-side toggle to show or hide the token.
|
||||
|
||||
### Fixed
|
||||
|
||||
- QR code regions now render at the correct size in the slide editor preview, and the QR chip header now matches the other region cards.
|
||||
- The dashboard onboarding link now uses the player public base URL stored in the database instead of a `/screen/...` URL.
|
||||
|
||||
## 2.5.3 - 2026-08-03
|
||||
|
||||
### Changed
|
||||
|
||||
- The user edit page delete action now shows a confirmation prompt before removing an account.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Schedule modal cancel now restores the original rule set instead of keeping edits made after the modal opened.
|
||||
|
||||
## 2.5.2 - 2026-08-03
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -8,6 +8,7 @@ COPY package*.json ./
|
||||
RUN npm install --omit=dev --no-audit --no-fund
|
||||
|
||||
COPY src ./src
|
||||
COPY scripts ./scripts
|
||||
|
||||
RUN mkdir -p /app/src/web/public/vendor/animate.css && cp /app/node_modules/animate.css/animate.min.css /app/src/web/public/vendor/animate.css/animate.min.css
|
||||
RUN mkdir -p /app/src/player/public/vendor/animate.css && cp /app/node_modules/animate.css/animate.min.css /app/src/player/public/vendor/animate.css/animate.min.css
|
||||
|
||||
@@ -1,81 +1,39 @@
|
||||
# Pulse Signage
|
||||
|
||||
Pulse Signage is a self-hosted digital signage platform built for teams that want clear, flexible control over what appears on every screen.
|
||||
Pulse Signage is a self-hosted digital signage platform for teams that want clear, reliable control over the content on every screen.
|
||||
|
||||
It gives you one place to manage playlists, slides, templates, screen assignments, announcements, data-driven content, and live player control without handing that workflow to a third-party service.
|
||||
It gives you one place to publish playlists, slides, announcements, and live updates without handing the workflow to a third-party service.
|
||||
|
||||
## Why It Stands Out
|
||||
## What It Can Do
|
||||
|
||||
- Keep signage under your own control.
|
||||
- Build polished screen experiences with reusable templates and playlists.
|
||||
- Push announcements, schedules, RSS feeds, API content, and other dynamic content to screens.
|
||||
- See what is live, what is queued, and what needs attention from a single admin dashboard.
|
||||
- Use the same system for everyday signage, timed messages, and more structured information displays.
|
||||
- Run polished screen experiences with playlists, slides, and reusable templates.
|
||||
- Keep announcements, schedules, RSS feeds, API content, and other live data in sync.
|
||||
- Manage many screens from a single dashboard.
|
||||
- Support everyday signage, event messages, lobbies, dashboards, and other always-on displays.
|
||||
- Keep the player, dashboard, and bridge connected so updates move quickly and consistently.
|
||||
|
||||
## What It Handles
|
||||
## Why It Fits
|
||||
|
||||
- Screens and playlist assignments.
|
||||
- Slides, templates, and canvas sizes.
|
||||
- Announcements and screen-specific targeting.
|
||||
- RSS feeds, API sources, and schedule-based content.
|
||||
- Roles and permissions for admin access.
|
||||
- Background tasks and scheduled refresh jobs.
|
||||
- Player onboarding and live playback control.
|
||||
- It keeps signage under your own control.
|
||||
- It is built for teams that need screens to stay current without extra manual work.
|
||||
- It works well for offices, venues, campuses, and operations teams.
|
||||
- It stays focused on display management instead of trying to be a general-purpose CMS.
|
||||
|
||||
## Simple Deployment
|
||||
## Deploying
|
||||
|
||||
Pulse Signage ships with a Docker Compose stack for the published image:
|
||||
Docker Compose is the recommended way to deploy Pulse Signage. It keeps the web app, player, bridge, and database together in a predictable setup.
|
||||
|
||||
- Published-image stack: `docker compose -f docker-compose.yml up -d`
|
||||
If you want the details, start with the [Compose guide](docker-compose/README.md).
|
||||
|
||||
Use this stack when you want to run the tagged image instead of building from source.
|
||||
## Docs
|
||||
|
||||
## Environment File
|
||||
- [Documentation home](docs/README.md) - the technical reference index.
|
||||
- [API reference](docs/api.md) - the player HTTP surface and onboarding endpoints.
|
||||
- [Database schema](docs/schema.md) - the tables and data model the app maintains.
|
||||
- [WebSocket reference](docs/websocket.md) - the live player and snapshot channels.
|
||||
- [Compose guide](docker-compose/README.md) - deployment options and service layout.
|
||||
- [Changelog](CHANGELOG.md) - release history and notable changes.
|
||||
|
||||
The compose files read from a root `.env` file. Start by copying `.env.example` to `.env`, then adjust the values for your setup.
|
||||
## Explore The Docs
|
||||
|
||||
The variables are split by who uses them:
|
||||
|
||||
Shared across the stack:
|
||||
|
||||
- `PULSE_SIGNAGE_IMAGE`
|
||||
- `PULSE_SIGNAGE_SHARED_SECRET`
|
||||
|
||||
Web container:
|
||||
|
||||
- `SESSION_MAX_AGE_DAYS`
|
||||
- `DEFAULT_ADMIN_USERNAME`
|
||||
- `DEFAULT_ADMIN_NAME`
|
||||
- `DEFAULT_ADMIN_PASSWORD`
|
||||
- `PASSWORD_HASH_ITERATIONS`
|
||||
|
||||
Player container:
|
||||
|
||||
- `PLAYER_PUBLIC_BASE_URL`
|
||||
- `PLAYER_INTERNAL_BASE_URL`
|
||||
|
||||
MySQL container:
|
||||
|
||||
- `DB_HOST`
|
||||
- `DB_PORT`
|
||||
- `DB_NAME`
|
||||
- `DB_USER`
|
||||
- `DB_PASSWORD`
|
||||
- `MYSQL_ROOT_PASSWORD`
|
||||
|
||||
`DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, and `DB_PASSWORD` are shared in practice because both app containers talk to the same database service.
|
||||
|
||||
`PLAYER_INTERNAL_BASE_URL` is used by the web side for server-to-player calls, while `PLAYER_PUBLIC_BASE_URL` is used for browser-facing player links.
|
||||
|
||||
## First-Time Use
|
||||
|
||||
The first startup seeds a default admin account if the database is empty.
|
||||
|
||||
- Username: `admin`
|
||||
- Password: `admin`
|
||||
|
||||
## In Practice
|
||||
|
||||
Pulse Signage is designed to feel focused and reliable rather than heavy or noisy. It works well when you want a clean internal signage system for offices, venues, dashboards, or any environment where screens need to stay up to date without a lot of manual effort.
|
||||
|
||||
The player and admin pieces stay linked, so changes made in the dashboard can flow out to screens quickly and consistently.
|
||||
The project includes a dashboard for managing content, a player runtime for rendering screens, an onboarding flow for connecting devices, and a bridge layer for remote screens. If you want to understand how the pieces fit together, the docs above cover the technical details without repeating the project overview.
|
||||
@@ -0,0 +1,26 @@
|
||||
# Shared application settings
|
||||
PULSE_SIGNAGE_IMAGE="git.lzstealth.com/lzstealth/pulse-signage:latest"
|
||||
PULSE_SIGNAGE_SHARED_SECRET=""
|
||||
|
||||
# Database settings for the web, player, and bridge services
|
||||
DB_HOST="mysql"
|
||||
DB_PORT=3306
|
||||
DB_NAME="pulse-signage"
|
||||
DB_USER="pulse-signage"
|
||||
DB_PASSWORD="signage_password"
|
||||
MYSQL_ROOT_PASSWORD="root_password"
|
||||
|
||||
# Player settings
|
||||
PLAYER_IDENTIFIER="player-local"
|
||||
PLAYER_PUBLIC_URL="http://localhost:8081"
|
||||
PLAYER_INTERNAL_URL="http://player:8081"
|
||||
|
||||
# Web app bootstrap settings
|
||||
SESSION_MAX_AGE_DAYS=14
|
||||
DEFAULT_ADMIN_USERNAME="admin"
|
||||
DEFAULT_ADMIN_NAME="Admin"
|
||||
DEFAULT_ADMIN_PASSWORD="password123"
|
||||
|
||||
# Bridge settings for the player-bridge service
|
||||
WEB_INTERNAL_URL="http://web:8080"
|
||||
BRIDGE_INTERNAL_URL="http://player-bridge:8090"
|
||||
@@ -0,0 +1,11 @@
|
||||
# Shared application settings
|
||||
PULSE_SIGNAGE_IMAGE="git.lzstealth.com/lzstealth/pulse-signage:latest"
|
||||
PULSE_SIGNAGE_SHARED_SECRET=""
|
||||
|
||||
# Player settings
|
||||
PLAYER_IDENTIFIER="player-remote"
|
||||
PLAYER_PUBLIC_URL="http://localhost:8081"
|
||||
PLAYER_AGENT_RECONNECT_DELAY_MS=5000
|
||||
|
||||
# Remote player connectivity settings
|
||||
BRIDGE_PUBLIC_URL="http://player-bridge.example.com:8090"
|
||||
@@ -0,0 +1,229 @@
|
||||
# Docker Compose Setup
|
||||
|
||||
This folder contains the Docker Compose definitions for Pulse Signage, including the public stack and the remote player stack.
|
||||
|
||||
## Files
|
||||
|
||||
- [docker-compose.yml](docker-compose.yml) - full public stack with web, player, player bridge, and MySQL.
|
||||
- [.env.example](.env.example) - sample environment values for the public stack.
|
||||
- [docker-compose.remote.yml](docker-compose.remote.yml) - remote player-only stack for machines that sit behind the player bridge.
|
||||
- [.env.remote.example](.env.remote.example) - sample environment values for the remote stack.
|
||||
|
||||
## Stack Overview
|
||||
|
||||
### Public stack
|
||||
|
||||
The main compose stack is the most complete setup. It runs:
|
||||
|
||||
- `web` - the dashboard and admin app.
|
||||
- `player` - the local screen player.
|
||||
- `player-bridge` - the bridge service that proxies dashboard commands and player communication.
|
||||
- `mysql` - the database used by the web, player, and bridge services.
|
||||
|
||||
This is the stack to use when you want the full app running on one machine.
|
||||
|
||||
### Remote player
|
||||
|
||||
The remote stack runs only the `player` service.
|
||||
|
||||
Use it when the player is installed on a remote device and connects back through the player bridge instead of running the full app separately.
|
||||
|
||||
## Services
|
||||
|
||||
### `web`
|
||||
|
||||
The dashboard and admin application.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- serves the web UI on port `8080`
|
||||
- reads and writes application data from MySQL
|
||||
- forwards player actions through the configured bridge base URL
|
||||
- renders connected clients, dashboard pages, and admin workflows
|
||||
|
||||
Key configuration:
|
||||
|
||||
- `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, `DB_PASSWORD`
|
||||
- `PULSE_SIGNAGE_SHARED_SECRET`
|
||||
- `SESSION_MAX_AGE_DAYS`
|
||||
- `DEFAULT_ADMIN_USERNAME`
|
||||
- `DEFAULT_ADMIN_NAME`
|
||||
- `DEFAULT_ADMIN_PASSWORD`
|
||||
- `PASSWORD_HASH_ITERATIONS`
|
||||
|
||||
### `player`
|
||||
|
||||
The screen runtime that renders playlists and receives commands.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- serves the player UI on port `8081`
|
||||
- connects to MySQL in local mode
|
||||
- connects to the bridge in remote mode through `BRIDGE_PUBLIC_URL`
|
||||
- registers live connections and accepts control commands
|
||||
|
||||
Key configuration:
|
||||
|
||||
- `PLAYER_PUBLIC_URL`
|
||||
- `PLAYER_INTERNAL_URL`
|
||||
- `BRIDGE_INTERNAL_URL`
|
||||
- `PLAYER_IDENTIFIER`
|
||||
- `BRIDGE_PUBLIC_URL` in remote mode
|
||||
- `PULSE_SIGNAGE_SHARED_SECRET`
|
||||
- database settings in local mode
|
||||
|
||||
### `player-bridge`
|
||||
|
||||
The bridge layer that connects the dashboard to the player network.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- serves the bridge API on port `8090`
|
||||
- forwards authenticated dashboard commands to registered players
|
||||
- exposes screen connection snapshots and player registration data
|
||||
- proxies command traffic between the web app and remote players
|
||||
|
||||
Key configuration:
|
||||
|
||||
- `PULSE_SIGNAGE_SHARED_SECRET`
|
||||
- `WEB_INTERNAL_URL` for the bridge when it should call the web app directly instead of inferring from request headers
|
||||
- `DB_HOST`, `DB_PORT`, `DB_NAME`, `DB_USER`, `DB_PASSWORD`
|
||||
|
||||
### `mysql`
|
||||
|
||||
The MySQL 8.4 database used by the public stack.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- stores application data, screen state, onboarding state, and registry records
|
||||
- provides persistent storage through `mysql_data`
|
||||
|
||||
Key configuration:
|
||||
|
||||
- `MYSQL_DATABASE`
|
||||
- `MYSQL_USER`
|
||||
- `MYSQL_PASSWORD`
|
||||
- `MYSQL_ROOT_PASSWORD`
|
||||
|
||||
## Environment Files
|
||||
|
||||
### `.env.example`
|
||||
|
||||
Use this file as a starting point for the public compose stack.
|
||||
|
||||
Important values:
|
||||
|
||||
- `PULSE_SIGNAGE_IMAGE` - image to run for all app services
|
||||
- `PULSE_SIGNAGE_SHARED_SECRET` - long random secret shared by the web, player, and bridge services for authenticated requests
|
||||
- `PLAYER_IDENTIFIER` - unique local player identifier
|
||||
- `DB_*` - MySQL credentials and database name for the stack
|
||||
- `PLAYER_PUBLIC_URL` - public URL the player advertises
|
||||
- `PLAYER_INTERNAL_URL` - internal URL the web app uses for local player calls
|
||||
- `BRIDGE_INTERNAL_URL` - bridge URL the web app uses for player snapshot and command forwarding
|
||||
- `WEB_INTERNAL_URL` - internal URL the bridge uses to call the web app directly
|
||||
- `SESSION_MAX_AGE_DAYS` - dashboard session lifetime
|
||||
- `DEFAULT_ADMIN_*` - bootstrap admin account values
|
||||
- `PASSWORD_HASH_ITERATIONS` - password hashing cost
|
||||
- `MYSQL_ROOT_PASSWORD` - root password for the local MySQL container
|
||||
|
||||
### `.env.remote.example`
|
||||
|
||||
Use this file on a remote player device.
|
||||
|
||||
Important values:
|
||||
|
||||
- `PULSE_SIGNAGE_IMAGE` - image to run on the device
|
||||
- `PULSE_SIGNAGE_SHARED_SECRET` - must match the public stack and should be the same long random value used everywhere in the deployment
|
||||
- `PLAYER_IDENTIFIER` - unique remote player identifier
|
||||
- `PLAYER_PUBLIC_URL` - public URL for the remote player
|
||||
- `BRIDGE_PUBLIC_URL` - bridge URL the player connects back to
|
||||
- `PLAYER_AGENT_RECONNECT_DELAY_MS` - reconnect delay for the player agent
|
||||
|
||||
### `PULSE_SIGNAGE_SHARED_SECRET`
|
||||
|
||||
This secret is the shared signing key for requests between the services. Use a single value for every service that needs to talk to the same stack, including the web app, player, bridge, and any remote player that connects back to that bridge.
|
||||
|
||||
Recommended shape:
|
||||
|
||||
- at least 32 random bytes
|
||||
- ideally 64 hex characters, or another equally long cryptographically random string
|
||||
- not a password, phrase, or anything human-readable
|
||||
|
||||
If you want a quick local value, generate one with a password manager or a command such as `openssl rand -hex 32`.
|
||||
|
||||
Leave it blank only if you intentionally want to run without request signing in a throwaway local setup.
|
||||
|
||||
## Main Configuration Variables
|
||||
|
||||
| Variable | Used By | Purpose |
|
||||
| --- | --- | --- |
|
||||
| `PULSE_SIGNAGE_IMAGE` | web, player, bridge, remote player | Docker image to run for the app services. |
|
||||
| `PULSE_SIGNAGE_SHARED_SECRET` | web, player, bridge, remote player | Shared secret for authenticated requests between services. |
|
||||
| `DB_HOST` | web, player, bridge | Database host name. |
|
||||
| `DB_PORT` | web, player, bridge | Database port. |
|
||||
| `DB_NAME` | web, player, bridge, mysql | Database name. |
|
||||
| `DB_USER` | web, player, bridge, mysql | Database user. |
|
||||
| `DB_PASSWORD` | web, player, bridge, mysql | Database password. |
|
||||
| `MYSQL_ROOT_PASSWORD` | mysql | Root password for the local MySQL container. |
|
||||
| `SESSION_MAX_AGE_DAYS` | web | Session cookie lifetime. |
|
||||
| `DEFAULT_ADMIN_USERNAME` | web | Bootstrap admin username. |
|
||||
| `DEFAULT_ADMIN_NAME` | web | Bootstrap admin display name. |
|
||||
| `DEFAULT_ADMIN_PASSWORD` | web | Bootstrap admin password. |
|
||||
| `PASSWORD_HASH_ITERATIONS` | web | Password hashing cost. |
|
||||
| `PLAYER_INTERNAL_URL` | web, player | Internal player URL used by the dashboard and player runtime. |
|
||||
| `BRIDGE_INTERNAL_URL` | web | Bridge URL used by the web app for player snapshot and command forwarding. |
|
||||
| `WEB_INTERNAL_URL` | player-bridge | Internal web URL used by the bridge to call the dashboard app directly. |
|
||||
| `PLAYER_PUBLIC_URL` | player, remote player | Public URL advertised by the player. |
|
||||
| `BRIDGE_PUBLIC_URL` | player, remote player | URL of the bridge service. |
|
||||
| `PLAYER_IDENTIFIER` | player | Stable player identifier. |
|
||||
| `PLAYER_AGENT_RECONNECT_DELAY_MS` | remote player | Delay before reconnecting to the bridge. |
|
||||
| `MYSQL_DATABASE` | mysql | Database name used by the local MySQL container. |
|
||||
| `MYSQL_USER` | mysql | Database user used by the local MySQL container. |
|
||||
| `MYSQL_PASSWORD` | mysql | Database password used by the local MySQL container. |
|
||||
|
||||
## Ports
|
||||
|
||||
Public stack ports:
|
||||
|
||||
- `8080` - web dashboard
|
||||
- `8081` - player
|
||||
- `8090` - player bridge
|
||||
- `3306` - MySQL
|
||||
|
||||
Remote stack ports:
|
||||
|
||||
- `8081` - player only
|
||||
|
||||
## Volumes
|
||||
|
||||
### Public stack
|
||||
|
||||
- `mysql_data` - persistent MySQL data.
|
||||
- `pulse-signage` - shared media and cache volume for the app services.
|
||||
|
||||
### Remote stack
|
||||
|
||||
- `pulse-signage` - shared media and cache volume for the remote player.
|
||||
|
||||
## Networks
|
||||
|
||||
Each compose file creates its own named network:
|
||||
|
||||
- `pulse-signage` for the public stack
|
||||
- `pulse-signage-remote` for remote player deployment.
|
||||
|
||||
## Notes
|
||||
|
||||
- The public stack expects the app services and MySQL to share the same `PULSE_SIGNAGE_SHARED_SECRET`.
|
||||
- A remote player must use the same `PULSE_SIGNAGE_SHARED_SECRET` as the bridge it connects to.
|
||||
- The bridge service is the dashboard-facing command path for connected remote players.
|
||||
- The remote player should point `BRIDGE_PUBLIC_URL` at the bridge, not at the public web endpoint.
|
||||
- The `PULSE_SIGNAGE_IMAGE` tag defaults to the published image, but it can be overridden for local builds or custom releases.
|
||||
|
||||
## Recommended Setup
|
||||
|
||||
1. Copy `.env.example` to a local `.env` file for the public stack.
|
||||
2. Copy `.env.remote.example` to a device-specific `.env` file for the remote player.
|
||||
3. Make sure `PULSE_SIGNAGE_SHARED_SECRET` matches everywhere.
|
||||
4. Start the public stack first, then start the remote player after the bridge is reachable.
|
||||
5. Verify that the player appears in Connected clients before testing screen commands.
|
||||
@@ -0,0 +1,28 @@
|
||||
name: pulse-signage-remote
|
||||
|
||||
services:
|
||||
|
||||
player:
|
||||
image: ${PULSE_SIGNAGE_IMAGE:-git.lzstealth.com/lzstealth/pulse-signage:latest}
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- pulse_signage
|
||||
ports:
|
||||
- "8081:8081"
|
||||
environment:
|
||||
PLAYER_PUBLIC_URL: ${PLAYER_PUBLIC_URL:-http://localhost:8081}
|
||||
BRIDGE_PUBLIC_URL: ${BRIDGE_PUBLIC_URL:-}
|
||||
PULSE_SIGNAGE_SHARED_SECRET: ${PULSE_SIGNAGE_SHARED_SECRET:-}
|
||||
volumes:
|
||||
- pulse-signage:/app/media
|
||||
command: ["node", "src/player.js"]
|
||||
|
||||
|
||||
|
||||
volumes:
|
||||
pulse-signage:
|
||||
|
||||
networks:
|
||||
pulse_signage:
|
||||
name: pulse-signage-remote
|
||||
external: false
|
||||
@@ -1,60 +1,84 @@
|
||||
name: pulse-signage
|
||||
|
||||
services:
|
||||
web:
|
||||
image: ${PULSE_SIGNAGE_IMAGE:-git.lzstealth.com/lzstealth/pulse-signage:latest}
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- pulse_signage
|
||||
ports:
|
||||
- "8080:8080"
|
||||
environment:
|
||||
DB_HOST: ${DB_HOST:-mysql}
|
||||
DB_PORT: ${DB_PORT:-3306}
|
||||
DB_NAME: ${DB_NAME:-signage}
|
||||
DB_USER: ${DB_USER:-signage_user}
|
||||
DB_NAME: ${DB_NAME:-pulse-signage}
|
||||
DB_USER: ${DB_USER:-pulse-signage}
|
||||
DB_PASSWORD: ${DB_PASSWORD:-signage_password}
|
||||
PULSE_SIGNAGE_SHARED_SECRET: ${PULSE_SIGNAGE_SHARED_SECRET:-}
|
||||
BRIDGE_INTERNAL_URL: ${BRIDGE_INTERNAL_URL:-http://player-bridge:8090}
|
||||
SESSION_MAX_AGE_DAYS: ${SESSION_MAX_AGE_DAYS:-14}
|
||||
DASHBOARD_REFRESH_INTERVAL_MS: ${DASHBOARD_REFRESH_INTERVAL_MS:-2000}
|
||||
DEFAULT_ADMIN_USERNAME: ${DEFAULT_ADMIN_USERNAME:-admin}
|
||||
DEFAULT_ADMIN_NAME: ${DEFAULT_ADMIN_NAME:-Admin}
|
||||
DEFAULT_ADMIN_PASSWORD: ${DEFAULT_ADMIN_PASSWORD:-admin}
|
||||
PASSWORD_HASH_ITERATIONS: ${PASSWORD_HASH_ITERATIONS:-310000}
|
||||
DEFAULT_ADMIN_PASSWORD: ${DEFAULT_ADMIN_PASSWORD:-password123}
|
||||
volumes:
|
||||
- media:/app/media
|
||||
- pulse-signage:/app/media
|
||||
command: ["node", "src/web.js"]
|
||||
depends_on:
|
||||
mysql:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- pulse_signage
|
||||
|
||||
player:
|
||||
image: ${PULSE_SIGNAGE_IMAGE:-git.lzstealth.com/lzstealth/pulse-signage:latest}
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- pulse_signage
|
||||
ports:
|
||||
- "8081:8081"
|
||||
environment:
|
||||
PLAYER_PUBLIC_BASE_URL: ${PLAYER_PUBLIC_BASE_URL:-http://localhost:8081}
|
||||
PLAYER_INTERNAL_BASE_URL: ${PLAYER_INTERNAL_BASE_URL:-http://player:8081}
|
||||
PLAYER_PUBLIC_URL: ${PLAYER_PUBLIC_URL:-http://localhost:8081}
|
||||
PLAYER_INTERNAL_URL: ${PLAYER_INTERNAL_URL:-http://player:8081}
|
||||
PLAYER_IDENTIFIER: ${PLAYER_IDENTIFIER:-player-local}
|
||||
PULSE_SIGNAGE_SHARED_SECRET: ${PULSE_SIGNAGE_SHARED_SECRET:-}
|
||||
DB_HOST: ${DB_HOST:-mysql}
|
||||
DB_PORT: ${DB_PORT:-3306}
|
||||
DB_NAME: ${DB_NAME:-signage}
|
||||
DB_USER: ${DB_USER:-signage_user}
|
||||
DB_NAME: ${DB_NAME:-pulse-signage}
|
||||
DB_USER: ${DB_USER:-pulse-signage}
|
||||
DB_PASSWORD: ${DB_PASSWORD:-signage_password}
|
||||
volumes:
|
||||
- media:/app/media
|
||||
- pulse-signage:/app/media
|
||||
command: ["node", "src/player.js"]
|
||||
depends_on:
|
||||
mysql:
|
||||
condition: service_healthy
|
||||
|
||||
player-bridge:
|
||||
image: ${PULSE_SIGNAGE_IMAGE:-git.lzstealth.com/lzstealth/pulse-signage:latest}
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- pulse_signage
|
||||
ports:
|
||||
- "8090:8090"
|
||||
environment:
|
||||
WEB_INTERNAL_URL: ${WEB_INTERNAL_URL:-http://web:8080}
|
||||
PULSE_SIGNAGE_SHARED_SECRET: ${PULSE_SIGNAGE_SHARED_SECRET:-}
|
||||
DB_HOST: ${DB_HOST:-mysql}
|
||||
DB_PORT: ${DB_PORT:-3306}
|
||||
DB_NAME: ${DB_NAME:-pulse-signage}
|
||||
DB_USER: ${DB_USER:-pulse-signage}
|
||||
DB_PASSWORD: ${DB_PASSWORD:-signage_password}
|
||||
command: ["node", "src/player-bridge/index.js"]
|
||||
depends_on:
|
||||
mysql:
|
||||
condition: service_healthy
|
||||
|
||||
mysql:
|
||||
image: mysql:8.4
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "3306:3306"
|
||||
environment:
|
||||
MYSQL_DATABASE: ${DB_NAME:-signage}
|
||||
MYSQL_USER: ${DB_USER:-signage_user}
|
||||
MYSQL_DATABASE: ${DB_NAME:-pulse-signage}
|
||||
MYSQL_USER: ${DB_USER:-pulse-signage}
|
||||
MYSQL_PASSWORD: ${DB_PASSWORD:-signage_password}
|
||||
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-root_password}
|
||||
command:
|
||||
@@ -72,9 +96,9 @@ services:
|
||||
|
||||
volumes:
|
||||
mysql_data:
|
||||
media:
|
||||
pulse-signage:
|
||||
|
||||
networks:
|
||||
pulse_signage:
|
||||
name: pulse_signage
|
||||
name: pulse-signage
|
||||
external: false
|
||||
@@ -0,0 +1,13 @@
|
||||
# Documentation
|
||||
|
||||
This folder contains the technical reference material for Pulse Signage.
|
||||
|
||||
## What’s Here
|
||||
|
||||
- [API reference](api.md) - the player HTTP surface and onboarding endpoints.
|
||||
- [Database schema](schema.md) - the tables and data model used by the app.
|
||||
- [WebSocket reference](websocket.md) - the live player and snapshot channels.
|
||||
|
||||
## How To Read It
|
||||
|
||||
If you want the big picture first, start with the main [project README](../README.md). It gives a plain overview of what Pulse Signage does, while the pages in this folder explain how the pieces work.
|
||||
+17
@@ -78,6 +78,11 @@ Response fields:
|
||||
Returns the upload directory configured for the player service.
|
||||
Access: internal-only.
|
||||
|
||||
Response fields:
|
||||
|
||||
- `mediaDir`
|
||||
- `uploadDir`
|
||||
|
||||
### `PUT /api/media/{filename}`
|
||||
Writes an uploaded file into the player upload directory.
|
||||
Access: internal-only and write-protected behind your deployment boundary.
|
||||
@@ -95,6 +100,14 @@ Query fields:
|
||||
- `source` required
|
||||
- `disableAudio` optional
|
||||
|
||||
Response fields:
|
||||
|
||||
- `key`
|
||||
- `playlistUrl`
|
||||
- `disableAudio`
|
||||
- `ready`
|
||||
- `live`
|
||||
|
||||
### `GET /api/rtmp/streams/{key}/index.m3u8`
|
||||
Returns the RTMP session HLS manifest.
|
||||
Access: internal-only.
|
||||
@@ -114,6 +127,7 @@ Response fields:
|
||||
- `slides`
|
||||
- `rssFeeds`
|
||||
- `apiSources`
|
||||
- `timetableGroups`
|
||||
- `revision`
|
||||
|
||||
### `GET /api/screens/{slug}/connections`
|
||||
@@ -198,6 +212,7 @@ Response fields:
|
||||
|
||||
`GET /api/media/config` returns an object with:
|
||||
|
||||
- `mediaDir`
|
||||
- `uploadDir`
|
||||
|
||||
### RTMP Session Response
|
||||
@@ -208,6 +223,7 @@ Response fields:
|
||||
- `playlistUrl`
|
||||
- `disableAudio`
|
||||
- `ready`
|
||||
- `live`
|
||||
|
||||
### Onboarding Write Response
|
||||
|
||||
@@ -230,6 +246,7 @@ Response fields:
|
||||
- `slides`
|
||||
- `rssFeeds`
|
||||
- `apiSources`
|
||||
- `timetableGroups`
|
||||
- `revision`
|
||||
|
||||
### Connections Response
|
||||
|
||||
+9
-9
@@ -21,7 +21,8 @@ Primary keys are `id` unless noted otherwise. Timestamps are stored as `created_
|
||||
|
||||
### `a_roles`
|
||||
|
||||
- `id`, `name`, `description`, `created_at`, `created_by`, `modified_at`, `modified_by`
|
||||
- `id`, `role_key`, `name`, `description`, `created_at`, `created_by`, `modified_at`, `modified_by`
|
||||
- `role_key` is unique.
|
||||
- `name` is unique.
|
||||
|
||||
### `a_permissions`
|
||||
@@ -93,7 +94,7 @@ Primary keys are `id` unless noted otherwise. Timestamps are stored as `created_
|
||||
|
||||
### `c_playlist_slides`
|
||||
|
||||
- `id`, `playlist_id`, `slide_id`, `position`, `duration_seconds`, `use_video_duration`, `created_at`, `created_by`, `modified_at`, `modified_by`
|
||||
- `id`, `playlist_id`, `slide_id`, `position`, `duration_seconds`, `use_video_duration`, `disable_audio`, `created_at`, `created_by`, `modified_at`, `modified_by`
|
||||
- Foreign keys:
|
||||
- `playlist_id` -> `c_playlists.id` with `ON DELETE CASCADE`
|
||||
- `slide_id` -> `c_slides.id` with `ON DELETE CASCADE`
|
||||
@@ -112,7 +113,7 @@ Primary keys are `id` unless noted otherwise. Timestamps are stored as `created_
|
||||
## Devices
|
||||
|
||||
- `d_players` - player registry and connection metadata.
|
||||
- `d_screens` - screen records and playlist/player assignment.
|
||||
- `d_screens` - screen records and playlist assignment.
|
||||
- `d_onboarding_devices` - device-to-screen bindings and onboarded client names.
|
||||
|
||||
## Announcements
|
||||
@@ -122,18 +123,18 @@ Primary keys are `id` unless noted otherwise. Timestamps are stored as `created_
|
||||
|
||||
### `d_players`
|
||||
|
||||
- `device_id`, `public_base_url`, `internal_base_url`, `last_seen_at`, `created_at`, `modified_at`
|
||||
- `device_id` is the primary key.
|
||||
- `id`, `identifier`, `public_base_url`, `internal_base_url`, `last_seen_at`, `created_at`, `modified_at`
|
||||
- `id` is the primary key.
|
||||
- `identifier` is unique and is the stable player identity used by the app.
|
||||
|
||||
### `d_screens`
|
||||
|
||||
- `id`, `name`, `slug`, `playlist_id`, `player_id`, `created_at`, `created_by`, `modified_at`, `modified_by`
|
||||
- `id`, `name`, `slug`, `playlist_id`, `created_at`, `created_by`, `modified_at`, `modified_by`
|
||||
- `slug` is unique.
|
||||
- Foreign keys:
|
||||
- `playlist_id` -> `c_playlists.id` with `ON DELETE SET NULL`
|
||||
- `player_id` -> `d_players.id` with `ON DELETE RESTRICT`
|
||||
|
||||
- `player_id` is required and defaults to `'1'` for the current singleton-player model.
|
||||
- Screens are no longer tied to a player foreign key directly; player registration and live connection metadata are tracked separately in `d_players`.
|
||||
|
||||
### `d_onboarding_devices`
|
||||
|
||||
@@ -275,7 +276,6 @@ erDiagram
|
||||
C_SLIDES ||--o{ C_PLAYLIST_SLIDES : included_in
|
||||
C_PLAYLIST_SLIDES ||--o{ C_PLAYLIST_SLIDE_SCHEDULE_RULES : has_rules
|
||||
|
||||
D_PLAYERS ||--o{ D_SCREENS : assigned_to
|
||||
C_PLAYLISTS ||--o{ D_SCREENS : uses
|
||||
D_SCREENS ||--o{ D_ONBOARDING_DEVICES : binds
|
||||
D_ANNOUNCEMENTS ||--o{ D_ANNOUNCEMENT_SCREENS : targets
|
||||
|
||||
Generated
+2
-207
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "pulse-signage",
|
||||
"version": "2.5.1",
|
||||
"version": "2.5.9",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "pulse-signage",
|
||||
"version": "2.5.1",
|
||||
"version": "2.5.9",
|
||||
"dependencies": {
|
||||
"@sparticuz/chromium": "^137.0.0",
|
||||
"animate.css": "^4.1.1",
|
||||
@@ -19,7 +19,6 @@
|
||||
"multer": "^2.2.0",
|
||||
"mysql2": "^3.14.3",
|
||||
"puppeteer-core": "^24.16.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"sharp": "^0.35.3",
|
||||
"ws": "^8.21.0"
|
||||
},
|
||||
@@ -1089,15 +1088,6 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/camelcase": {
|
||||
"version": "5.3.1",
|
||||
"resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz",
|
||||
"integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/chokidar": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
|
||||
@@ -1136,17 +1126,6 @@
|
||||
"devtools-protocol": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/cliui": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
|
||||
"integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"string-width": "^4.2.0",
|
||||
"strip-ansi": "^6.0.0",
|
||||
"wrap-ansi": "^6.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/color-convert": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
|
||||
@@ -1240,15 +1219,6 @@
|
||||
"ms": "2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/decamelize": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz",
|
||||
"integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/degenerator": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/degenerator/-/degenerator-5.0.1.tgz",
|
||||
@@ -1306,12 +1276,6 @@
|
||||
"integrity": "sha512-Tpm17fxYzt+J7VrGdc1k8YdRqS3YV7se/M6KeemEqvUbq/n7At1rWVuXMxQgpWkdwSdIEKYbU//Bve+Shm4YNQ==",
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/dijkstrajs": {
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz",
|
||||
"integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/dotenv": {
|
||||
"version": "17.4.2",
|
||||
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz",
|
||||
@@ -1618,19 +1582,6 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/find-up": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
|
||||
"integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"locate-path": "^5.0.0",
|
||||
"path-exists": "^4.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/follow-redirects": {
|
||||
"version": "1.16.0",
|
||||
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz",
|
||||
@@ -2082,18 +2033,6 @@
|
||||
"integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/locate-path": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
|
||||
"integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-locate": "^4.1.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/long": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
|
||||
@@ -2411,42 +2350,6 @@
|
||||
"wrappy": "1"
|
||||
}
|
||||
},
|
||||
"node_modules/p-limit": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
|
||||
"integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-try": "^2.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/p-locate": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
|
||||
"integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"p-limit": "^2.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/p-try": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
|
||||
"integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/pac-proxy-agent": {
|
||||
"version": "7.2.0",
|
||||
"resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz",
|
||||
@@ -2511,15 +2414,6 @@
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/path-exists": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
|
||||
"integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/path-to-regexp": {
|
||||
"version": "0.1.13",
|
||||
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz",
|
||||
@@ -2545,15 +2439,6 @@
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/pngjs": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz",
|
||||
"integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/progress": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
|
||||
@@ -2691,23 +2576,6 @@
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/qrcode": {
|
||||
"version": "1.5.4",
|
||||
"resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz",
|
||||
"integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"dijkstrajs": "^1.0.1",
|
||||
"pngjs": "^5.0.0",
|
||||
"yargs": "^15.3.1"
|
||||
},
|
||||
"bin": {
|
||||
"qrcode": "bin/qrcode"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=10.13.0"
|
||||
}
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.15.3",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
|
||||
@@ -2784,12 +2652,6 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/require-main-filename": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz",
|
||||
"integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/safe-buffer": {
|
||||
"version": "5.2.1",
|
||||
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
|
||||
@@ -2873,12 +2735,6 @@
|
||||
"node": ">= 0.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/set-blocking": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
|
||||
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/setprototypeof": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
|
||||
@@ -3352,32 +3208,12 @@
|
||||
"integrity": "sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/which-module": {
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz",
|
||||
"integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/wordwrap": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz",
|
||||
"integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/wrap-ansi": {
|
||||
"version": "6.2.0",
|
||||
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
|
||||
"integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ansi-styles": "^4.0.0",
|
||||
"string-width": "^4.1.0",
|
||||
"strip-ansi": "^6.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/wrappy": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
|
||||
@@ -3405,47 +3241,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/y18n": {
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz",
|
||||
"integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/yargs": {
|
||||
"version": "15.4.1",
|
||||
"resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz",
|
||||
"integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cliui": "^6.0.0",
|
||||
"decamelize": "^1.2.0",
|
||||
"find-up": "^4.1.0",
|
||||
"get-caller-file": "^2.0.1",
|
||||
"require-directory": "^2.1.1",
|
||||
"require-main-filename": "^2.0.0",
|
||||
"set-blocking": "^2.0.0",
|
||||
"string-width": "^4.2.0",
|
||||
"which-module": "^2.0.0",
|
||||
"y18n": "^4.0.0",
|
||||
"yargs-parser": "^18.1.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/yargs-parser": {
|
||||
"version": "18.1.3",
|
||||
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz",
|
||||
"integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"camelcase": "^5.0.0",
|
||||
"decamelize": "^1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/yauzl": {
|
||||
"version": "2.10.0",
|
||||
"resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz",
|
||||
|
||||
+1
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "pulse-signage",
|
||||
"version": "2.5.2",
|
||||
"version": "2.6.9",
|
||||
"private": false,
|
||||
"description": "Pulse Signage application with MySQL and media storage",
|
||||
"repository": {
|
||||
@@ -28,7 +28,6 @@
|
||||
"multer": "^2.2.0",
|
||||
"mysql2": "^3.14.3",
|
||||
"puppeteer-core": "^24.16.0",
|
||||
"qrcode": "^1.5.4",
|
||||
"sharp": "^0.35.3",
|
||||
"ws": "^8.21.0"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
@echo off
|
||||
setlocal EnableExtensions EnableDelayedExpansion
|
||||
|
||||
set "TARGET_URL=%~1"
|
||||
if not defined TARGET_URL set "TARGET_URL=http://localhost:8081"
|
||||
|
||||
set "BROWSER_PATH="
|
||||
set "BROWSER_KIND="
|
||||
|
||||
for %%B in (chrome.exe msedge.exe firefox.exe) do if not defined BROWSER_PATH (
|
||||
for /f "delims=" %%I in ('where %%B 2^>nul') do if not defined BROWSER_PATH (
|
||||
set "BROWSER_PATH=%%I"
|
||||
set "BROWSER_KIND=%%~nB"
|
||||
)
|
||||
)
|
||||
|
||||
if not defined BROWSER_PATH if not defined BROWSER_KIND (
|
||||
for %%P in (
|
||||
"%ProgramFiles%\Google\Chrome\Application\chrome.exe"
|
||||
"%ProgramFiles(x86)%\Google\Chrome\Application\chrome.exe"
|
||||
"%LocalAppData%\Google\Chrome\Application\chrome.exe"
|
||||
) do if not defined BROWSER_PATH if exist "%%~fP" (
|
||||
set "BROWSER_PATH=%%~fP"
|
||||
set "BROWSER_KIND=chrome"
|
||||
)
|
||||
)
|
||||
|
||||
if not defined BROWSER_PATH if not defined BROWSER_KIND (
|
||||
for %%P in (
|
||||
"%ProgramFiles%\Microsoft\Edge\Application\msedge.exe"
|
||||
"%ProgramFiles(x86)%\Microsoft\Edge\Application\msedge.exe"
|
||||
"%LocalAppData%\Microsoft\Edge\Application\msedge.exe"
|
||||
) do if not defined BROWSER_PATH if exist "%%~fP" (
|
||||
set "BROWSER_PATH=%%~fP"
|
||||
set "BROWSER_KIND=edge"
|
||||
)
|
||||
)
|
||||
|
||||
if not defined BROWSER_PATH if not defined BROWSER_KIND (
|
||||
for %%P in (
|
||||
"%ProgramFiles%\Mozilla Firefox\firefox.exe"
|
||||
"%ProgramFiles(x86)%\Mozilla Firefox\firefox.exe"
|
||||
"%LocalAppData%\Mozilla Firefox\firefox.exe"
|
||||
) do if not defined BROWSER_PATH if exist "%%~fP" (
|
||||
set "BROWSER_PATH=%%~fP"
|
||||
set "BROWSER_KIND=firefox"
|
||||
)
|
||||
)
|
||||
|
||||
if not defined BROWSER_PATH (
|
||||
echo No supported browser was found.
|
||||
echo Tried Chrome, Edge, and Firefox in PATH and common install locations.
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo Launching !BROWSER_KIND! in kiosk mode: !TARGET_URL!
|
||||
if /I "!BROWSER_KIND!"=="firefox" (
|
||||
start "" "!BROWSER_PATH!" -kiosk "!TARGET_URL!"
|
||||
) else (
|
||||
start "" "!BROWSER_PATH!" --disable-notifications --kiosk "!TARGET_URL!"
|
||||
)
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
target_url="${1:-http://localhost:8081}"
|
||||
|
||||
find_browser() {
|
||||
local candidate
|
||||
for candidate in "$@"; do
|
||||
if command -v "$candidate" >/dev/null 2>&1; then
|
||||
printf '%s' "$candidate"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
browser=""
|
||||
browser_kind=""
|
||||
|
||||
if browser="$(find_browser google-chrome-stable google-chrome chromium chromium-browser msedge microsoft-edge firefox)"; then
|
||||
case "$browser" in
|
||||
firefox)
|
||||
browser_kind="firefox"
|
||||
;;
|
||||
msedge|microsoft-edge)
|
||||
browser_kind="edge"
|
||||
;;
|
||||
*)
|
||||
browser_kind="chrome"
|
||||
;;
|
||||
esac
|
||||
else
|
||||
echo "No supported browser was found."
|
||||
echo "Tried Chrome, Chromium, Edge, and Firefox in PATH."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Launching ${browser_kind} in kiosk mode: ${target_url}"
|
||||
|
||||
case "$browser_kind" in
|
||||
firefox)
|
||||
exec "$browser" -kiosk "$target_url"
|
||||
;;
|
||||
edge|chrome)
|
||||
exec "$browser" --disable-notifications --kiosk "$target_url"
|
||||
;;
|
||||
esac
|
||||
+16
@@ -7,6 +7,21 @@ const PASSWORD_KEY_LENGTH = 32;
|
||||
const PASSWORD_DIGEST = 'sha256';
|
||||
const SESSION_BYTES = 32;
|
||||
|
||||
function validatePasswordStrength(password) {
|
||||
const value = String(password || '');
|
||||
const hasLowercase = /[a-z]/.test(value);
|
||||
const hasUppercase = /[A-Z]/.test(value);
|
||||
const hasNumber = /[0-9]/.test(value);
|
||||
const hasSymbol = /[^A-Za-z0-9]/.test(value);
|
||||
const categoryCount = [hasLowercase, hasUppercase, hasNumber, hasSymbol].filter(Boolean).length;
|
||||
|
||||
if (value.length < 10 || categoryCount < 3) {
|
||||
return 'Password must be at least 10 characters and include 3 of: uppercase, lowercase, number, and symbol.';
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
function hashPassword(password, salt) {
|
||||
const safePassword = String(password || '');
|
||||
const safeSalt = salt || crypto.randomBytes(16).toString('hex');
|
||||
@@ -40,6 +55,7 @@ function hashSessionToken(token) {
|
||||
module.exports = {
|
||||
hashPassword,
|
||||
verifyPassword,
|
||||
validatePasswordStrength,
|
||||
createSessionToken,
|
||||
hashSessionToken
|
||||
};
|
||||
@@ -37,6 +37,8 @@ module.exports = {
|
||||
slugify: data.slugify,
|
||||
uniqueScreenSlug: data.uniqueScreenSlug,
|
||||
parseJsonSafe: data.parseJsonSafe,
|
||||
validateMaxLength: data.validateMaxLength,
|
||||
truncateToMaxLength: data.truncateToMaxLength,
|
||||
fetchAdminData: data.fetchAdminData,
|
||||
fetchPlaylistsPage: data.fetchPlaylistsPage,
|
||||
fetchSlidesPage: data.fetchSlidesPage,
|
||||
@@ -84,13 +86,16 @@ module.exports = {
|
||||
fetchScreenById: data.fetchScreenById,
|
||||
fetchScreenEditData: data.fetchScreenEditData,
|
||||
fetchScreenPlayerUrls: data.fetchScreenPlayerUrls,
|
||||
fetchPlayerPublicBaseUrl: data.fetchPlayerPublicBaseUrl,
|
||||
fetchScreenPlayerRecord: data.fetchScreenPlayerRecord,
|
||||
fetchTemplateById: data.fetchTemplateById,
|
||||
fetchPlayerRegistrations: data.fetchPlayerRegistrations,
|
||||
fetchSlideById: data.fetchSlideById,
|
||||
fetchTemplatesData: data.fetchTemplatesData,
|
||||
fetchCanvasSizesData: data.fetchCanvasSizesData,
|
||||
fetchCanvasSizeById: data.fetchCanvasSizeById,
|
||||
buildCanvasSizePayload: data.buildCanvasSizePayload,
|
||||
MAX_CANVAS_SIZE_DIMENSION: data.MAX_CANVAS_SIZE_DIMENSION,
|
||||
buildSlidePayload: data.buildSlidePayload,
|
||||
extractTemplateRegions: data.extractTemplateRegions,
|
||||
buildTemplatePayload: data.buildTemplatePayload,
|
||||
|
||||
+1
-1
@@ -93,7 +93,7 @@ async function fetchSlidesPage(pool, page, pageSize, searchTerm, sortKey, sortDi
|
||||
LEFT JOIN c_canvas_sizes cs ON cs.id = st.canvas_size_id
|
||||
ORDER BY s.id DESC`,
|
||||
countSql: 'SELECT COUNT(*) AS count FROM c_slides',
|
||||
searchColumns: ['s.title', 'st.name', 's.content_json'],
|
||||
searchColumns: ['s.title', 'st.name'],
|
||||
searchTerm: searchTerm,
|
||||
sortColumns: {
|
||||
title: 's.title',
|
||||
|
||||
@@ -6,6 +6,9 @@ const {
|
||||
DEFAULT_ANNOUNCEMENT_ICON,
|
||||
normalizeAnnouncementIcon: normalizeAnnouncementIconFromConfig
|
||||
} = require('./announcement-icons');
|
||||
const { validateMaxLength } = require('./utils');
|
||||
|
||||
const SHORT_LABEL_MAX_LENGTH = 255;
|
||||
|
||||
const ANNOUNCEMENT_TYPES = ['lower-third', 'fullscreen', 'top-banner'];
|
||||
const ANNOUNCEMENT_COLORS = ['primary', 'secondary', 'success', 'info', 'warning', 'danger', 'dark', 'light'];
|
||||
@@ -57,7 +60,7 @@ function normalizeAnnouncementScreenIds(value) {
|
||||
|
||||
function buildAnnouncementPayload(input) {
|
||||
const message = normalizeAnnouncementMessage(input && input.message);
|
||||
const shortLabel = normalizeAnnouncementShortLabel(input && input.short_label);
|
||||
const shortLabel = validateMaxLength(normalizeAnnouncementShortLabel(input && input.short_label), SHORT_LABEL_MAX_LENGTH, 'Announcement short description');
|
||||
const announcementType = normalizeAnnouncementType(input && input.announcement_type);
|
||||
const colorKey = normalizeAnnouncementColor(input && input.color_key);
|
||||
const iconKey = normalizeAnnouncementIconFromConfig(input && input.icon_key);
|
||||
|
||||
+14
-9
@@ -2,7 +2,12 @@
|
||||
|
||||
const http = require('http');
|
||||
const https = require('https');
|
||||
const { fetchPagedRows } = require('./utils');
|
||||
const { fetchPagedRows, validateMaxLength } = require('./utils');
|
||||
|
||||
const NAME_MAX_LENGTH = 255;
|
||||
const URL_MAX_LENGTH = 1024;
|
||||
const AUTH_MAX_LENGTH = 255;
|
||||
const ITEMS_PATH_MAX_LENGTH = 255;
|
||||
|
||||
function normalizeUpdateIntervalUnit(value) {
|
||||
const unit = String(value || '').trim().toLowerCase();
|
||||
@@ -171,15 +176,15 @@ function buildApiSourcePayload(req, existingApiSource) {
|
||||
return fallbackValue;
|
||||
}
|
||||
|
||||
const name = String(req.body.name || fallback.name || '').trim();
|
||||
const apiUrl = String(req.body.api_url || req.body.apiUrl || fallback.api_url || '').trim();
|
||||
const name = validateMaxLength(req.body.name || fallback.name || '', NAME_MAX_LENGTH, 'API source name');
|
||||
const apiUrl = validateMaxLength(req.body.api_url || req.body.apiUrl || fallback.api_url || '', URL_MAX_LENGTH, 'API source URL');
|
||||
const authMethod = normalizeAuthMethod(readBodyValue('auth_method', readBodyValue('authMethod', fallback.auth_method || 'none')));
|
||||
const authUsername = String(readBodyValue('auth_username', readBodyValue('authUsername', fallback.auth_username || '')) || '').trim();
|
||||
const authPassword = String(readBodyValue('auth_password', readBodyValue('authPassword', fallback.auth_password || '')) || '');
|
||||
const authBearerToken = String(readBodyValue('auth_bearer_token', readBodyValue('authBearerToken', fallback.auth_bearer_token || '')) || '').trim();
|
||||
const authHeaderName = String(readBodyValue('auth_header_name', readBodyValue('authHeaderName', fallback.auth_header_name || 'X-API-Key')) || 'X-API-Key').trim() || 'X-API-Key';
|
||||
const authHeaderValue = String(readBodyValue('auth_header_value', readBodyValue('authHeaderValue', fallback.auth_header_value || '')) || '').trim();
|
||||
const itemsPath = String(readBodyValue('items_path', readBodyValue('itemsPath', fallback.items_path || '')) || '').trim();
|
||||
const authUsername = validateMaxLength(readBodyValue('auth_username', readBodyValue('authUsername', fallback.auth_username || '')) || '', AUTH_MAX_LENGTH, 'API source username');
|
||||
const authPassword = validateMaxLength(readBodyValue('auth_password', readBodyValue('authPassword', fallback.auth_password || '')) || '', AUTH_MAX_LENGTH, 'API source password');
|
||||
const authBearerToken = validateMaxLength(readBodyValue('auth_bearer_token', readBodyValue('authBearerToken', fallback.auth_bearer_token || '')) || '', AUTH_MAX_LENGTH, 'API source bearer token');
|
||||
const authHeaderName = validateMaxLength(readBodyValue('auth_header_name', readBodyValue('authHeaderName', fallback.auth_header_name || 'X-API-Key')) || 'X-API-Key', AUTH_MAX_LENGTH, 'API source header name') || 'X-API-Key';
|
||||
const authHeaderValue = validateMaxLength(readBodyValue('auth_header_value', readBodyValue('authHeaderValue', fallback.auth_header_value || '')) || '', AUTH_MAX_LENGTH, 'API source header value');
|
||||
const itemsPath = validateMaxLength(readBodyValue('items_path', readBodyValue('itemsPath', fallback.items_path || '')) || '', ITEMS_PATH_MAX_LENGTH, 'API source items path');
|
||||
const updateIntervalValue = Math.max(1, Number(req.body.update_interval_value || req.body.updateIntervalValue || fallback.update_interval_value || 60));
|
||||
const updateIntervalUnit = normalizeUpdateIntervalUnit(req.body.update_interval_unit || req.body.updateIntervalUnit || fallback.update_interval_unit || 'minutes');
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Canvas size data access and pagination helpers.
|
||||
|
||||
const { fetchPagedRows } = require('./utils');
|
||||
const MAX_CANVAS_SIZE_DIMENSION = 16384;
|
||||
|
||||
async function fetchCanvasSizesData(pool) {
|
||||
const [canvasSizes] = await pool.query('SELECT id, name, width, height, created_at, modified_at, created_by, modified_by FROM c_canvas_sizes ORDER BY width ASC, height ASC, name ASC');
|
||||
@@ -33,10 +34,31 @@ async function fetchCanvasSizeById(pool, id) {
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
function readCanvasDimension(rawValue, fallbackValue, fieldName) {
|
||||
const sourceValue = rawValue !== undefined && rawValue !== null && String(rawValue).trim() !== ''
|
||||
? rawValue
|
||||
: fallbackValue;
|
||||
const numericValue = Number(sourceValue);
|
||||
|
||||
if (!Number.isFinite(numericValue)) {
|
||||
const error = new Error('Canvas size ' + fieldName + ' must be a number.');
|
||||
error.statusCode = 400;
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (numericValue > MAX_CANVAS_SIZE_DIMENSION) {
|
||||
const error = new Error('Canvas size dimensions must be 16384 or less.');
|
||||
error.statusCode = 400;
|
||||
throw error;
|
||||
}
|
||||
|
||||
return Math.max(1, numericValue);
|
||||
}
|
||||
|
||||
function buildCanvasSizePayload(req, existingCanvasSize) {
|
||||
const name = String(req.body.name || '').trim();
|
||||
const width = Math.max(1, Number(req.body.width || (existingCanvasSize && existingCanvasSize.width) || 0));
|
||||
const height = Math.max(1, Number(req.body.height || (existingCanvasSize && existingCanvasSize.height) || 0));
|
||||
const width = readCanvasDimension(req.body.width, existingCanvasSize && existingCanvasSize.width, 'width');
|
||||
const height = readCanvasDimension(req.body.height, existingCanvasSize && existingCanvasSize.height, 'height');
|
||||
|
||||
if (!name) {
|
||||
const error = new Error('Canvas size name is required.');
|
||||
@@ -55,5 +77,6 @@ module.exports = {
|
||||
fetchCanvasSizesData,
|
||||
fetchCanvasSizesPage,
|
||||
fetchCanvasSizeById,
|
||||
buildCanvasSizePayload
|
||||
buildCanvasSizePayload,
|
||||
MAX_CANVAS_SIZE_DIMENSION
|
||||
};
|
||||
|
||||
+10
-3
@@ -7,16 +7,19 @@ const { fetchPlaylistById } = require('./playlists');
|
||||
const { normalizeDisplayMode, fetchTimetablesData, fetchTimetableGroupsPage, fetchTimetableGroupById, fetchTimetableEntriesByGroupId, buildTimetableGroupPayload } = require('./schedules');
|
||||
const { fetchApiSourcesData, fetchApiSourcesPage, fetchApiSourceById, fetchApiSourceResponse, buildApiSourcePayload } = require('./api-sources');
|
||||
const { fetchRssFeedsData, fetchRssFeedsPage, fetchRssFeedById, fetchRssFeedItemsByFeedId, normalizeRssFeedItem, buildRssFeedPayload, fetchRssFeedItems, replaceRssFeedItems } = require('./rss-feeds');
|
||||
const { slugify, uniqueScreenSlug, fetchScreenById, fetchScreenEditData, fetchScreenPlayerUrls, fetchScreenPlayerRecord } = require('./screens');
|
||||
const { slugify, uniqueScreenSlug, fetchScreenById, fetchScreenEditData, fetchScreenPlayerUrls, fetchPlayerPublicBaseUrl, fetchScreenPlayerRecord, fetchPlayerRecordByIdentifier } = require('./screens');
|
||||
const { fetchPlayerRegistrations } = require('./player-registry');
|
||||
const { fetchTemplateById, fetchTemplatesData, extractTemplateRegions, buildTemplatePayload } = require('./templates');
|
||||
const { fetchCanvasSizesData, fetchCanvasSizeById, buildCanvasSizePayload } = require('./canvas-sizes');
|
||||
const { fetchCanvasSizesData, fetchCanvasSizeById, buildCanvasSizePayload, MAX_CANVAS_SIZE_DIMENSION } = require('./canvas-sizes');
|
||||
const { fetchSlideById, buildSlidePayload } = require('./slides');
|
||||
const { parseJsonSafe, fetchDuplicateName } = require('./utils');
|
||||
const { parseJsonSafe, fetchDuplicateName, validateMaxLength, truncateToMaxLength } = require('./utils');
|
||||
|
||||
module.exports = {
|
||||
slugify,
|
||||
uniqueScreenSlug,
|
||||
parseJsonSafe,
|
||||
validateMaxLength,
|
||||
truncateToMaxLength,
|
||||
fetchAdminData,
|
||||
fetchPlaylistsPage,
|
||||
fetchSlidesPage,
|
||||
@@ -59,13 +62,17 @@ module.exports = {
|
||||
fetchScreenById,
|
||||
fetchScreenEditData,
|
||||
fetchScreenPlayerUrls,
|
||||
fetchPlayerPublicBaseUrl,
|
||||
fetchScreenPlayerRecord,
|
||||
fetchPlayerRecordByIdentifier,
|
||||
fetchPlayerRegistrations,
|
||||
fetchTemplateById,
|
||||
fetchSlideById,
|
||||
fetchTemplatesData,
|
||||
fetchCanvasSizesData,
|
||||
fetchCanvasSizeById,
|
||||
buildCanvasSizePayload,
|
||||
MAX_CANVAS_SIZE_DIMENSION,
|
||||
buildSlidePayload,
|
||||
extractTemplateRegions,
|
||||
buildTemplatePayload,
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
function normalizeDeviceId(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/[^a-zA-Z0-9_-]/g, '')
|
||||
.slice(0, 128);
|
||||
}
|
||||
|
||||
function normalizeBaseUrl(value) {
|
||||
return String(value || '').trim().replace(/\/$/, '');
|
||||
}
|
||||
|
||||
function normalizeIdentifier(value) {
|
||||
return String(value || '').trim().slice(0, 255);
|
||||
}
|
||||
|
||||
async function columnExists(pool, tableName, columnName) {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT COUNT(*) AS column_count
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = ?
|
||||
AND COLUMN_NAME = ?`,
|
||||
[tableName, columnName]
|
||||
);
|
||||
|
||||
return Number(rows && rows[0] && rows[0].column_count) > 0;
|
||||
}
|
||||
|
||||
async function fetchPlayerRegistrations(pool) {
|
||||
if (!pool) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const [rows] = await pool.query(
|
||||
`SELECT id, identifier, public_base_url, internal_base_url, last_seen_at, modified_at
|
||||
FROM d_players
|
||||
ORDER BY modified_at DESC, identifier ASC`
|
||||
);
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
function getConfiguredPlayerIdentifier() {
|
||||
return normalizeDeviceId(process.env.PLAYER_IDENTIFIER || process.env.PLAYER_DEVICE_ID || '');
|
||||
}
|
||||
|
||||
async function resolvePlayerRegistration(pool, identifier) {
|
||||
const normalizedIdentifier = normalizeDeviceId(identifier);
|
||||
if (!pool || !normalizedIdentifier) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hasIdentifierColumn = await columnExists(pool, 'd_players', 'identifier');
|
||||
const hasDeviceIdColumn = await columnExists(pool, 'd_players', 'device_id');
|
||||
const identifierColumn = hasIdentifierColumn ? 'identifier' : (hasDeviceIdColumn ? 'device_id' : '');
|
||||
if (!identifierColumn) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const selectIdExpression = hasIdentifierColumn ? 'id' : 'NULL AS id';
|
||||
const selectIdentifierExpression = hasIdentifierColumn ? 'identifier' : 'device_id AS identifier';
|
||||
const orderByExpression = hasIdentifierColumn ? 'modified_at DESC, id DESC' : 'modified_at DESC';
|
||||
|
||||
const [rows] = await pool.query(
|
||||
`SELECT ${selectIdExpression}, ${selectIdentifierExpression}, public_base_url, internal_base_url, last_seen_at
|
||||
FROM d_players
|
||||
WHERE ${identifierColumn} = ?
|
||||
LIMIT 1`,
|
||||
[normalizedIdentifier]
|
||||
);
|
||||
|
||||
if (rows[0]) {
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
const [fallbackRows] = await pool.query(
|
||||
`SELECT ${selectIdExpression}, ${selectIdentifierExpression}, public_base_url, internal_base_url, last_seen_at
|
||||
FROM d_players
|
||||
ORDER BY ${orderByExpression}
|
||||
LIMIT 1`
|
||||
);
|
||||
|
||||
return fallbackRows[0] || null;
|
||||
}
|
||||
|
||||
async function upsertPlayerRegistration(pool, options) {
|
||||
const identifier = normalizeDeviceId(options && (options.identifier || options.deviceId));
|
||||
const publicBaseUrl = normalizeBaseUrl(options && options.publicBaseUrl);
|
||||
const internalBaseUrl = normalizeBaseUrl(options && options.internalBaseUrl);
|
||||
|
||||
if (!pool || !identifier) {
|
||||
return null;
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
`INSERT INTO d_players (identifier, public_base_url, internal_base_url, last_seen_at)
|
||||
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
public_base_url = VALUES(public_base_url),
|
||||
internal_base_url = VALUES(internal_base_url),
|
||||
last_seen_at = CURRENT_TIMESTAMP,
|
||||
modified_at = CURRENT_TIMESTAMP`,
|
||||
[identifier, publicBaseUrl || null, internalBaseUrl || null]
|
||||
);
|
||||
|
||||
return resolvePlayerRegistration(pool, identifier);
|
||||
}
|
||||
|
||||
async function recordPlayerHeartbeat(pool, options) {
|
||||
const identifier = normalizeDeviceId(options && (options.identifier || options.deviceId));
|
||||
const publicBaseUrl = normalizeBaseUrl(options && options.publicBaseUrl);
|
||||
const internalBaseUrl = normalizeBaseUrl(options && options.internalBaseUrl);
|
||||
|
||||
if (!pool || !identifier) {
|
||||
return null;
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
`INSERT INTO d_players (identifier, public_base_url, internal_base_url, last_seen_at)
|
||||
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
public_base_url = COALESCE(VALUES(public_base_url), public_base_url),
|
||||
internal_base_url = COALESCE(VALUES(internal_base_url), internal_base_url),
|
||||
last_seen_at = CURRENT_TIMESTAMP,
|
||||
modified_at = CURRENT_TIMESTAMP`,
|
||||
[identifier, publicBaseUrl || null, internalBaseUrl || null]
|
||||
);
|
||||
|
||||
return resolvePlayerRegistration(pool, identifier);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
normalizeDeviceId: normalizeDeviceId,
|
||||
normalizeIdentifier: normalizeIdentifier,
|
||||
getConfiguredPlayerIdentifier: getConfiguredPlayerIdentifier,
|
||||
fetchPlayerRegistrations: fetchPlayerRegistrations,
|
||||
resolvePlayerRegistration: resolvePlayerRegistration,
|
||||
upsertPlayerRegistration: upsertPlayerRegistration,
|
||||
recordPlayerHeartbeat: recordPlayerHeartbeat
|
||||
};
|
||||
@@ -0,0 +1,562 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const QRCodeStyling = require(path.join(__dirname, '..', 'web', 'public', 'vendor', 'qr-code-styling', 'qr-code-styling.js'));
|
||||
const puppeteer = require('puppeteer-core');
|
||||
const chromiumModule = require('@sparticuz/chromium');
|
||||
const QR_PNG_WIDTH = 2048;
|
||||
const QR_STYLING_SCRIPT_PATH = path.join(__dirname, '..', 'web', 'public', 'vendor', 'qr-code-styling', 'qr-code-styling.js');
|
||||
const SYSTEM_CHROMIUM_PATHS = [
|
||||
process.env.PUPPETEER_EXECUTABLE_PATH,
|
||||
process.env.CHROMIUM_PATH,
|
||||
'/usr/bin/chromium',
|
||||
'/usr/bin/chromium-browser',
|
||||
'/usr/local/bin/chromium',
|
||||
'/snap/bin/chromium'
|
||||
].filter(Boolean);
|
||||
const chromium = chromiumModule && typeof chromiumModule.executablePath === 'function'
|
||||
? chromiumModule
|
||||
: chromiumModule && chromiumModule.default && typeof chromiumModule.default.executablePath === 'function'
|
||||
? chromiumModule.default
|
||||
: chromiumModule;
|
||||
let qrBrowserPromise = null;
|
||||
|
||||
function escapeXml(value) {
|
||||
return String(value === undefined || value === null ? '' : value).replace(/[&<>"']/g, function (character) {
|
||||
return {
|
||||
'&': '&',
|
||||
'<': '<',
|
||||
'>': '>',
|
||||
'"': '"',
|
||||
"'": '''
|
||||
}[character];
|
||||
});
|
||||
}
|
||||
|
||||
function serializeNode(node) {
|
||||
if (!node) {
|
||||
return '';
|
||||
}
|
||||
if (node.nodeType === 3) {
|
||||
return escapeXml(node.textContent || '');
|
||||
}
|
||||
|
||||
const attributeEntries = Object.keys(node.attributes || {}).map(function (name) {
|
||||
return name + '="' + escapeXml(node.attributes[name]) + '"';
|
||||
});
|
||||
if (node.tagName === 'svg' && node.namespaceURI === 'http://www.w3.org/2000/svg' && !Object.prototype.hasOwnProperty.call(node.attributes || {}, 'xmlns')) {
|
||||
attributeEntries.unshift('xmlns="http://www.w3.org/2000/svg"');
|
||||
}
|
||||
const attributes = attributeEntries.join(' ');
|
||||
const children = (node.childNodes || []).map(serializeNode).join('') + escapeXml(node.textContent || '');
|
||||
return '<' + node.tagName + (attributes ? ' ' + attributes : '') + '>' + children + '</' + node.tagName + '>';
|
||||
}
|
||||
|
||||
function createDomNode(tagName, namespaceUri) {
|
||||
return {
|
||||
tagName: tagName,
|
||||
namespaceURI: namespaceUri || null,
|
||||
attributes: {},
|
||||
childNodes: [],
|
||||
parentNode: null,
|
||||
nodeType: 1,
|
||||
textContent: '',
|
||||
style: {},
|
||||
setAttribute: function (name, value) {
|
||||
this.attributes[name] = String(value);
|
||||
},
|
||||
appendChild: function (child) {
|
||||
if (child) {
|
||||
this.childNodes.push(child);
|
||||
child.parentNode = this;
|
||||
}
|
||||
return child;
|
||||
},
|
||||
removeChild: function (child) {
|
||||
this.childNodes = this.childNodes.filter(function (node) { return node !== child; });
|
||||
return child;
|
||||
},
|
||||
get firstChild() {
|
||||
return this.childNodes[0] || null;
|
||||
},
|
||||
get outerHTML() {
|
||||
return serializeNode(this);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function createCanvasContext() {
|
||||
return {
|
||||
fillStyle: '#000000',
|
||||
strokeStyle: '#000000',
|
||||
lineWidth: 1,
|
||||
beginPath: function () {},
|
||||
closePath: function () {},
|
||||
clearRect: function () {},
|
||||
fillRect: function () {},
|
||||
strokeRect: function () {},
|
||||
moveTo: function () {},
|
||||
lineTo: function () {},
|
||||
arc: function () {},
|
||||
rect: function () {},
|
||||
fill: function () {},
|
||||
stroke: function () {},
|
||||
save: function () {},
|
||||
restore: function () {},
|
||||
translate: function () {},
|
||||
rotate: function () {},
|
||||
scale: function () {},
|
||||
setTransform: function () {},
|
||||
transform: function () {},
|
||||
drawImage: function () {},
|
||||
measureText: function (text) {
|
||||
return { width: String(text === undefined || text === null ? '' : text).length * 8 };
|
||||
},
|
||||
createLinearGradient: function () {
|
||||
return { addColorStop: function () {} };
|
||||
},
|
||||
createRadialGradient: function () {
|
||||
return { addColorStop: function () {} };
|
||||
},
|
||||
createPattern: function () {
|
||||
return null;
|
||||
},
|
||||
getImageData: function () {
|
||||
return { data: [] };
|
||||
},
|
||||
putImageData: function () {},
|
||||
clip: function () {}
|
||||
};
|
||||
}
|
||||
|
||||
function createCanvasNode() {
|
||||
const node = createDomNode('canvas', 'http://www.w3.org/1999/xhtml');
|
||||
node.width = 0;
|
||||
node.height = 0;
|
||||
node.getContext = function () {
|
||||
return createCanvasContext();
|
||||
};
|
||||
node.toDataURL = function () {
|
||||
return '';
|
||||
};
|
||||
node.toBlob = function (callback) {
|
||||
if (typeof callback === 'function') {
|
||||
callback(null);
|
||||
}
|
||||
};
|
||||
return node;
|
||||
}
|
||||
|
||||
function createQrStylingWindow() {
|
||||
const document = {
|
||||
createElement: function (tagName) {
|
||||
if (String(tagName || '').toLowerCase() === 'canvas') {
|
||||
return createCanvasNode();
|
||||
}
|
||||
return createDomNode(tagName, 'http://www.w3.org/1999/xhtml');
|
||||
},
|
||||
createElementNS: function (namespaceUri, tagName) {
|
||||
return createDomNode(tagName, namespaceUri);
|
||||
},
|
||||
createTextNode: function (text) {
|
||||
return {
|
||||
nodeType: 3,
|
||||
textContent: String(text === undefined || text === null ? '' : text),
|
||||
parentNode: null
|
||||
};
|
||||
},
|
||||
body: createDomNode('body', 'http://www.w3.org/1999/xhtml'),
|
||||
head: createDomNode('head', 'http://www.w3.org/1999/xhtml')
|
||||
};
|
||||
|
||||
const window = {
|
||||
document: document,
|
||||
navigator: { userAgent: 'node' },
|
||||
URL: {
|
||||
createObjectURL: function () { return ''; },
|
||||
revokeObjectURL: function () {}
|
||||
}
|
||||
};
|
||||
|
||||
window.window = window;
|
||||
window.self = window;
|
||||
window.Image = class {
|
||||
constructor() {
|
||||
this.onload = null;
|
||||
this.onerror = null;
|
||||
this.width = 1;
|
||||
this.height = 1;
|
||||
this.naturalWidth = 1;
|
||||
this.naturalHeight = 1;
|
||||
this._src = '';
|
||||
}
|
||||
|
||||
set src(value) {
|
||||
this._src = String(value === undefined || value === null ? '' : value);
|
||||
if (typeof this.onload === 'function') {
|
||||
setTimeout(() => this.onload(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
get src() {
|
||||
return this._src;
|
||||
}
|
||||
};
|
||||
window.HTMLImageElement = window.Image;
|
||||
|
||||
window.XMLSerializer = class {
|
||||
serializeToString(node) {
|
||||
return serializeNode(node);
|
||||
}
|
||||
};
|
||||
|
||||
return { window: window, document: document };
|
||||
}
|
||||
|
||||
async function renderStyledQrRawData(options, format) {
|
||||
const previousWindow = global.window;
|
||||
const previousDocument = global.document;
|
||||
const previousXMLSerializer = global.XMLSerializer;
|
||||
const dom = createQrStylingWindow();
|
||||
|
||||
global.window = dom.window;
|
||||
global.document = dom.document;
|
||||
global.XMLSerializer = dom.window.XMLSerializer;
|
||||
|
||||
try {
|
||||
const qrCode = new QRCodeStyling(options);
|
||||
const blob = await qrCode.getRawData(format);
|
||||
if (!blob) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (typeof blob === 'string') {
|
||||
return blob;
|
||||
}
|
||||
|
||||
if (typeof blob.text === 'function') {
|
||||
return blob.text();
|
||||
}
|
||||
|
||||
if (typeof blob.arrayBuffer === 'function') {
|
||||
const buffer = await blob.arrayBuffer();
|
||||
const bytes = new Uint8Array(buffer);
|
||||
let binary = '';
|
||||
for (let index = 0; index < bytes.length; index += 1) {
|
||||
binary += String.fromCharCode(bytes[index]);
|
||||
}
|
||||
return binary;
|
||||
}
|
||||
|
||||
return '';
|
||||
} finally {
|
||||
global.window = previousWindow;
|
||||
global.document = previousDocument;
|
||||
global.XMLSerializer = previousXMLSerializer;
|
||||
}
|
||||
}
|
||||
|
||||
function svgToDataUrl(svg) {
|
||||
const markup = String(svg === undefined || svg === null ? '' : svg).trim();
|
||||
if (!markup) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(markup);
|
||||
}
|
||||
|
||||
function normalizeQrStyleColor(value, fallback) {
|
||||
const raw = String(value === undefined || value === null ? '' : value).trim();
|
||||
return raw || fallback;
|
||||
}
|
||||
|
||||
function normalizeQrStyleNumber(value, fallback, min, max) {
|
||||
const parsed = Number(value);
|
||||
if (!Number.isFinite(parsed)) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
let next = parsed;
|
||||
if (typeof min === 'number') {
|
||||
next = Math.max(min, next);
|
||||
}
|
||||
if (typeof max === 'number') {
|
||||
next = Math.min(max, next);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function buildQrStylingOptions(source) {
|
||||
const text = String(source && source.value === undefined ? '' : source && source.value === null ? '' : source.value || '').trim();
|
||||
const qrStyle = source && typeof source === 'object' ? source : {};
|
||||
const dotsGradient = qrStyle.qr_dots_color_mode === 'gradient' ? {
|
||||
type: String(qrStyle.qr_dots_gradient_type || 'linear').trim() || 'linear',
|
||||
rotation: normalizeQrStyleNumber(qrStyle.qr_dots_gradient_rotation, 0, undefined, undefined),
|
||||
colorStops: [
|
||||
{ offset: 0, color: normalizeQrStyleColor(qrStyle.qr_dots_gradient_color_1, normalizeQrStyleColor(qrStyle.qr_dots_color, '#000000')) },
|
||||
{ offset: 1, color: normalizeQrStyleColor(qrStyle.qr_dots_gradient_color_2, '#ffffff') }
|
||||
]
|
||||
} : null;
|
||||
const cornersSquareGradient = qrStyle.qr_corners_square_color_mode === 'gradient' ? {
|
||||
type: String(qrStyle.qr_corners_square_gradient_type || 'linear').trim() || 'linear',
|
||||
rotation: normalizeQrStyleNumber(qrStyle.qr_corners_square_gradient_rotation, 0, undefined, undefined),
|
||||
colorStops: [
|
||||
{ offset: 0, color: normalizeQrStyleColor(qrStyle.qr_corners_square_gradient_color_1, normalizeQrStyleColor(qrStyle.qr_corners_square_color, '#000000')) },
|
||||
{ offset: 1, color: normalizeQrStyleColor(qrStyle.qr_corners_square_gradient_color_2, '#ffffff') }
|
||||
]
|
||||
} : null;
|
||||
const cornersDotGradient = qrStyle.qr_corners_dot_color_mode === 'gradient' ? {
|
||||
type: String(qrStyle.qr_corners_dot_gradient_type || 'linear').trim() || 'linear',
|
||||
rotation: normalizeQrStyleNumber(qrStyle.qr_corners_dot_gradient_rotation, 0, undefined, undefined),
|
||||
colorStops: [
|
||||
{ offset: 0, color: normalizeQrStyleColor(qrStyle.qr_corners_dot_gradient_color_1, normalizeQrStyleColor(qrStyle.qr_corners_dot_color, '#000000')) },
|
||||
{ offset: 1, color: normalizeQrStyleColor(qrStyle.qr_corners_dot_gradient_color_2, '#ffffff') }
|
||||
]
|
||||
} : null;
|
||||
|
||||
return {
|
||||
width: QR_PNG_WIDTH,
|
||||
height: QR_PNG_WIDTH,
|
||||
type: 'canvas',
|
||||
data: text,
|
||||
margin: normalizeQrStyleNumber(qrStyle.qr_margin, 10, 0, undefined),
|
||||
qrOptions: {},
|
||||
dotsOptions: {
|
||||
type: String(qrStyle.qr_dots_type || 'square').trim() || 'square',
|
||||
color: normalizeQrStyleColor(qrStyle.qr_dots_color, '#000000'),
|
||||
gradient: dotsGradient || undefined
|
||||
},
|
||||
cornersSquareOptions: {
|
||||
type: String(qrStyle.qr_corners_square_type || 'square').trim() || 'square',
|
||||
color: normalizeQrStyleColor(qrStyle.qr_corners_square_color, '#000000'),
|
||||
gradient: cornersSquareGradient || undefined
|
||||
},
|
||||
cornersDotOptions: {
|
||||
type: String(qrStyle.qr_corners_dot_type || 'square').trim() || 'square',
|
||||
color: normalizeQrStyleColor(qrStyle.qr_corners_dot_color, '#000000'),
|
||||
gradient: cornersDotGradient || undefined
|
||||
},
|
||||
backgroundOptions: {
|
||||
color: qrStyle.qr_background_transparent ? 'transparent' : normalizeQrStyleColor(qrStyle.qr_background_color, '#ffffff')
|
||||
},
|
||||
image: String(qrStyle.qr_image || '').trim() || undefined,
|
||||
imageOptions: {
|
||||
hideBackgroundDots: Boolean(qrStyle.qr_image_hide_background_dots),
|
||||
imageSize: normalizeQrStyleNumber(qrStyle.qr_image_size, 0.4, 0, 1),
|
||||
margin: normalizeQrStyleNumber(qrStyle.qr_image_margin, 5, 0, undefined)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function getQrBrowser() {
|
||||
if (qrBrowserPromise) {
|
||||
return qrBrowserPromise;
|
||||
}
|
||||
|
||||
qrBrowserPromise = (async function () {
|
||||
let executablePath = SYSTEM_CHROMIUM_PATHS.find(function (candidate) {
|
||||
return fs.existsSync(candidate);
|
||||
}) || '';
|
||||
const usingSystemChromium = Boolean(executablePath);
|
||||
|
||||
if (!executablePath && chromium && typeof chromium.executablePath === 'function') {
|
||||
executablePath = await chromium.executablePath();
|
||||
}
|
||||
|
||||
if (!executablePath || !fs.existsSync(executablePath)) {
|
||||
throw new Error('Chromium executable was not found.');
|
||||
}
|
||||
|
||||
return puppeteer.launch({
|
||||
args: usingSystemChromium
|
||||
? [
|
||||
'--no-sandbox',
|
||||
'--disable-setuid-sandbox',
|
||||
'--disable-dev-shm-usage',
|
||||
'--disable-gpu'
|
||||
]
|
||||
: puppeteer.defaultArgs({
|
||||
args: chromium && chromium.args ? chromium.args : [],
|
||||
headless: 'shell'
|
||||
}),
|
||||
defaultViewport: usingSystemChromium
|
||||
? { width: QR_PNG_WIDTH, height: QR_PNG_WIDTH, deviceScaleFactor: 1 }
|
||||
: chromium && chromium.defaultViewport ? chromium.defaultViewport : null,
|
||||
executablePath: executablePath,
|
||||
headless: usingSystemChromium ? true : 'shell'
|
||||
});
|
||||
})();
|
||||
|
||||
return qrBrowserPromise;
|
||||
}
|
||||
|
||||
async function blobToDataUrl(blob) {
|
||||
if (!blob) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (typeof blob === 'string') {
|
||||
return blob;
|
||||
}
|
||||
|
||||
if (typeof blob.arrayBuffer === 'function') {
|
||||
const buffer = await blob.arrayBuffer();
|
||||
const bytes = new Uint8Array(buffer);
|
||||
let binary = '';
|
||||
for (let index = 0; index < bytes.length; index += 1) {
|
||||
binary += String.fromCharCode(bytes[index]);
|
||||
}
|
||||
return 'data:' + String(blob.type || 'image/png') + ';base64,' + Buffer.from(binary, 'binary').toString('base64');
|
||||
}
|
||||
|
||||
if (typeof blob.text === 'function') {
|
||||
return blob.text();
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
async function createStyledQrCodeDataUrl(value) {
|
||||
const source = value && typeof value === 'object' ? value : { value: value };
|
||||
const options = buildQrStylingOptions(source);
|
||||
if (!options.data) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return svgToDataUrl(await createStyledQrCodeSvg(options.data));
|
||||
}
|
||||
|
||||
async function createStyledQrCodeSvg(value) {
|
||||
const source = value && typeof value === 'object' ? value : { value: value };
|
||||
const options = buildQrStylingOptions(source);
|
||||
if (!options.data) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return renderStyledQrRawData(options, 'svg');
|
||||
}
|
||||
|
||||
async function createQrCodeDataUrlPlain(value) {
|
||||
return createStyledQrCodeDataUrl(value);
|
||||
}
|
||||
|
||||
async function createQrCodeSvg(value) {
|
||||
return createStyledQrCodeSvg(value);
|
||||
}
|
||||
|
||||
async function createQrCodeDataUrl(value) {
|
||||
return createStyledQrCodeDataUrl(value);
|
||||
}
|
||||
|
||||
async function buildQrCodeContent(value, options) {
|
||||
const source = value && typeof value === 'object' ? value : { value: value };
|
||||
const forcePreviewRefresh = Boolean(options && options.forcePreviewRefresh);
|
||||
const text = String(source.value === undefined || source.value === null ? '' : source.value).trim();
|
||||
const hasBooleanField = function (key) {
|
||||
return Object.prototype.hasOwnProperty.call(source, key);
|
||||
};
|
||||
const margin = Number(source.qr_margin);
|
||||
const normalizeHex = function (value) {
|
||||
const raw = String(value === undefined || value === null ? '' : value).trim();
|
||||
return raw || undefined;
|
||||
};
|
||||
const normalizeNumber = function (value, min, max, round) {
|
||||
const parsed = Number(value);
|
||||
if (!Number.isFinite(parsed)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let next = parsed;
|
||||
if (round) {
|
||||
next = Math.round(next);
|
||||
}
|
||||
if (typeof min === 'number') {
|
||||
next = Math.max(min, next);
|
||||
}
|
||||
if (typeof max === 'number') {
|
||||
next = Math.min(max, next);
|
||||
}
|
||||
return next;
|
||||
};
|
||||
const style = {
|
||||
qr_margin: Number.isFinite(margin) && margin >= 0 ? Math.round(margin) : undefined,
|
||||
qr_border_radius: Number.isFinite(Number(source.qr_border_radius)) ? Math.max(0, Math.round(Number(source.qr_border_radius))) : undefined,
|
||||
qr_background_color: String(source.qr_background_color === undefined || source.qr_background_color === null ? '' : source.qr_background_color).trim() || undefined,
|
||||
qr_background_transparent: hasBooleanField('qr_background_transparent') ? Boolean(source.qr_background_transparent) : undefined,
|
||||
qr_background_color_mode: 'single',
|
||||
qr_background_gradient_type: String(source.qr_background_gradient_type === undefined || source.qr_background_gradient_type === null ? '' : source.qr_background_gradient_type).trim() || undefined,
|
||||
qr_background_gradient_rotation: normalizeNumber(source.qr_background_gradient_rotation),
|
||||
qr_background_gradient_color_1: normalizeHex(source.qr_background_gradient_color_1),
|
||||
qr_background_gradient_color_2: normalizeHex(source.qr_background_gradient_color_2),
|
||||
qr_dots_color: String(source.qr_dots_color === undefined || source.qr_dots_color === null ? '' : source.qr_dots_color).trim() || undefined,
|
||||
qr_dots_type: String(source.qr_dots_type === undefined || source.qr_dots_type === null ? '' : source.qr_dots_type).trim() || undefined,
|
||||
qr_dots_color_mode: String(source.qr_dots_color_mode === undefined || source.qr_dots_color_mode === null ? '' : source.qr_dots_color_mode).trim() || undefined,
|
||||
qr_dots_gradient_type: String(source.qr_dots_gradient_type === undefined || source.qr_dots_gradient_type === null ? '' : source.qr_dots_gradient_type).trim() || undefined,
|
||||
qr_dots_gradient_rotation: normalizeNumber(source.qr_dots_gradient_rotation),
|
||||
qr_dots_gradient_color_1: normalizeHex(source.qr_dots_gradient_color_1),
|
||||
qr_dots_gradient_color_2: normalizeHex(source.qr_dots_gradient_color_2),
|
||||
qr_corners_square_color: String(source.qr_corners_square_color === undefined || source.qr_corners_square_color === null ? '' : source.qr_corners_square_color).trim() || undefined,
|
||||
qr_corners_square_type: String(source.qr_corners_square_type === undefined || source.qr_corners_square_type === null ? '' : source.qr_corners_square_type).trim() || undefined,
|
||||
qr_corners_square_color_mode: String(source.qr_corners_square_color_mode === undefined || source.qr_corners_square_color_mode === null ? '' : source.qr_corners_square_color_mode).trim() || undefined,
|
||||
qr_corners_square_gradient_type: String(source.qr_corners_square_gradient_type === undefined || source.qr_corners_square_gradient_type === null ? '' : source.qr_corners_square_gradient_type).trim() || undefined,
|
||||
qr_corners_square_gradient_rotation: normalizeNumber(source.qr_corners_square_gradient_rotation),
|
||||
qr_corners_square_gradient_color_1: normalizeHex(source.qr_corners_square_gradient_color_1),
|
||||
qr_corners_square_gradient_color_2: normalizeHex(source.qr_corners_square_gradient_color_2),
|
||||
qr_corners_dot_color: String(source.qr_corners_dot_color === undefined || source.qr_corners_dot_color === null ? '' : source.qr_corners_dot_color).trim() || undefined,
|
||||
qr_corners_dot_type: String(source.qr_corners_dot_type === undefined || source.qr_corners_dot_type === null ? '' : source.qr_corners_dot_type).trim() || undefined,
|
||||
qr_corners_dot_color_mode: String(source.qr_corners_dot_color_mode === undefined || source.qr_corners_dot_color_mode === null ? '' : source.qr_corners_dot_color_mode).trim() || undefined,
|
||||
qr_corners_dot_gradient_type: String(source.qr_corners_dot_gradient_type === undefined || source.qr_corners_dot_gradient_type === null ? '' : source.qr_corners_dot_gradient_type).trim() || undefined,
|
||||
qr_corners_dot_gradient_rotation: normalizeNumber(source.qr_corners_dot_gradient_rotation),
|
||||
qr_corners_dot_gradient_color_1: normalizeHex(source.qr_corners_dot_gradient_color_1),
|
||||
qr_corners_dot_gradient_color_2: normalizeHex(source.qr_corners_dot_gradient_color_2),
|
||||
qr_image: String(source.qr_image === undefined || source.qr_image === null ? '' : source.qr_image).trim() || undefined,
|
||||
qr_image_size: Number.isFinite(Number(source.qr_image_size)) ? Math.max(0, Math.min(1, Number(source.qr_image_size))) : undefined,
|
||||
qr_image_margin: Number.isFinite(Number(source.qr_image_margin)) ? Math.max(0, Math.round(Number(source.qr_image_margin))) : undefined,
|
||||
qr_image_hide_background_dots: hasBooleanField('qr_image_hide_background_dots') ? Boolean(source.qr_image_hide_background_dots) : undefined
|
||||
};
|
||||
const content = {
|
||||
type: 'qr-code',
|
||||
value: text
|
||||
};
|
||||
|
||||
Object.keys(style).forEach((key) => {
|
||||
if (style[key] !== undefined) {
|
||||
content[key] = style[key];
|
||||
}
|
||||
});
|
||||
|
||||
content.qr_background_use_gradient = false;
|
||||
content.qr_dots_use_gradient = content.qr_dots_gradient_type && content.qr_dots_gradient_type !== 'none';
|
||||
content.qr_corners_square_use_gradient = content.qr_corners_square_gradient_type && content.qr_corners_square_gradient_type !== 'none';
|
||||
content.qr_corners_dot_use_gradient = content.qr_corners_dot_gradient_type && content.qr_corners_dot_gradient_type !== 'none';
|
||||
|
||||
const svg = String(source.qr_svg === undefined || source.qr_svg === null ? '' : source.qr_svg).trim();
|
||||
if (svg) {
|
||||
content.qr_svg = svg;
|
||||
}
|
||||
|
||||
const preview = forcePreviewRefresh ? '' : String(source.qr_preview === undefined || source.qr_preview === null ? '' : source.qr_preview).trim();
|
||||
if (preview) {
|
||||
content.qr_preview = preview;
|
||||
}
|
||||
|
||||
if (text && !content.qr_preview) {
|
||||
const generatedSvg = await createQrCodeSvg(text);
|
||||
if (generatedSvg) {
|
||||
content.qr_svg = generatedSvg;
|
||||
}
|
||||
const generatedDataUrl = await createStyledQrCodeDataUrl(content);
|
||||
if (generatedDataUrl) {
|
||||
content.qr_preview = generatedDataUrl;
|
||||
}
|
||||
}
|
||||
|
||||
return content;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
createQrCodeSvg,
|
||||
createStyledQrCodeSvg,
|
||||
createStyledQrCodeDataUrl,
|
||||
createQrCodeDataUrl,
|
||||
buildQrCodeContent
|
||||
};
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
const http = require('http');
|
||||
const https = require('https');
|
||||
const { fetchPagedRows } = require('./utils');
|
||||
const { fetchPagedRows, validateMaxLength } = require('./utils');
|
||||
|
||||
const NAME_MAX_LENGTH = 255;
|
||||
const URL_MAX_LENGTH = 1024;
|
||||
|
||||
function normalizeUpdateIntervalUnit(value) {
|
||||
const unit = String(value || '').trim().toLowerCase();
|
||||
@@ -255,8 +258,8 @@ async function replaceRssFeedItems(connection, rssFeedId, items) {
|
||||
|
||||
function buildRssFeedPayload(req, existingRssFeed) {
|
||||
const fallback = existingRssFeed || {};
|
||||
const name = String(req.body.name || fallback.name || '').trim();
|
||||
const feedUrl = String(req.body.feed_url || req.body.feedUrl || fallback.feed_url || '').trim();
|
||||
const name = validateMaxLength(req.body.name || fallback.name || '', NAME_MAX_LENGTH, 'RSS feed name');
|
||||
const feedUrl = validateMaxLength(req.body.feed_url || req.body.feedUrl || fallback.feed_url || '', URL_MAX_LENGTH, 'RSS feed URL');
|
||||
const updateIntervalValue = Math.max(1, Number(req.body.update_interval_value || req.body.updateIntervalValue || fallback.update_interval_value || 60));
|
||||
const updateIntervalUnit = normalizeUpdateIntervalUnit(req.body.update_interval_unit || req.body.updateIntervalUnit || fallback.update_interval_unit || 'minutes');
|
||||
const itemLimit = Math.max(1, Number(req.body.item_limit || req.body.itemLimit || fallback.item_limit || 1));
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
// Timetable group and entry data access helpers.
|
||||
|
||||
const { fetchPagedRows } = require('./utils');
|
||||
const { fetchPagedRows, validateMaxLength } = require('./utils');
|
||||
|
||||
const NAME_MAX_LENGTH = 255;
|
||||
const DESCRIPTION_MAX_LENGTH = 255;
|
||||
|
||||
function normalizeDisplayMode(value) {
|
||||
const mode = String(value || 'upcoming').trim().toLowerCase();
|
||||
@@ -95,8 +98,8 @@ async function fetchTimetableEntriesByGroupId(pool, timetableGroupId) {
|
||||
|
||||
function buildTimetableGroupPayload(req, existingTimetableGroup) {
|
||||
const fallback = existingTimetableGroup || {};
|
||||
const name = String(req.body.name || fallback.name || '').trim();
|
||||
const shortDescription = String(req.body.short_description || req.body.shortDescription || fallback.short_description || '').trim();
|
||||
const name = validateMaxLength(req.body.name || fallback.name || '', NAME_MAX_LENGTH, 'Timetable group name');
|
||||
const shortDescription = validateMaxLength(req.body.short_description || req.body.shortDescription || fallback.short_description || '', DESCRIPTION_MAX_LENGTH, 'Timetable group description');
|
||||
|
||||
if (!name) {
|
||||
const error = new Error('Timetable group name is required.');
|
||||
|
||||
+57
-16
@@ -13,6 +13,27 @@ function normalizePlayerBaseUrl(value) {
|
||||
return String(value || '').trim().replace(/\/$/, '');
|
||||
}
|
||||
|
||||
function getConfiguredPlayerIdentifier() {
|
||||
return String(process.env.PLAYER_IDENTIFIER || process.env.PLAYER_DEVICE_ID || '').trim() || null;
|
||||
}
|
||||
|
||||
async function fetchPlayerRecordByIdentifier(pool, identifier) {
|
||||
const normalizedIdentifier = String(identifier || '').trim();
|
||||
if (!normalizedIdentifier) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [rows] = await pool.query(
|
||||
`SELECT id, identifier, public_base_url, internal_base_url, last_seen_at
|
||||
FROM d_players
|
||||
WHERE identifier = ?
|
||||
LIMIT 1`,
|
||||
[normalizedIdentifier]
|
||||
);
|
||||
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
function buildScreenPlayerUrl(screen, fallbackBaseUrl) {
|
||||
const slug = String(screen && screen.slug || '').trim();
|
||||
if (!slug) {
|
||||
@@ -28,20 +49,21 @@ function buildScreenPlayerUrl(screen, fallbackBaseUrl) {
|
||||
}
|
||||
|
||||
async function fetchScreenPlayerUrls(pool) {
|
||||
const playerBaseUrl = await fetchPlayerPublicBaseUrl(pool);
|
||||
if (!playerBaseUrl) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const [rows] = await pool.query(`
|
||||
SELECT s.slug, p.public_base_url
|
||||
FROM d_screens s
|
||||
LEFT JOIN d_players p ON p.device_id = s.player_id
|
||||
WHERE p.public_base_url IS NOT NULL
|
||||
AND TRIM(p.public_base_url) <> ''
|
||||
ORDER BY p.modified_at DESC, s.slug ASC
|
||||
SELECT slug
|
||||
FROM d_screens
|
||||
ORDER BY slug ASC
|
||||
`);
|
||||
|
||||
const playerUrls = {};
|
||||
rows.forEach(function (row) {
|
||||
const slug = String(row && row.slug || '').trim();
|
||||
const publicBaseUrl = normalizePlayerBaseUrl(row && row.public_base_url);
|
||||
const playerUrl = buildScreenPlayerUrl({ slug: slug }, publicBaseUrl);
|
||||
const playerUrl = buildScreenPlayerUrl({ slug: slug }, playerBaseUrl);
|
||||
if (slug && playerUrl && !playerUrls[slug]) {
|
||||
playerUrls[slug] = playerUrl;
|
||||
}
|
||||
@@ -50,17 +72,33 @@ async function fetchScreenPlayerUrls(pool) {
|
||||
return playerUrls;
|
||||
}
|
||||
|
||||
async function fetchScreenPlayerRecord(pool, slug) {
|
||||
async function fetchPlayerPublicBaseUrl(pool) {
|
||||
const configuredPlayerIdentifier = getConfiguredPlayerIdentifier();
|
||||
const [rows] = await pool.query(`
|
||||
SELECT p.device_id, p.public_base_url, p.internal_base_url, p.last_seen_at
|
||||
FROM d_screens s
|
||||
JOIN d_players p ON p.device_id = s.player_id
|
||||
WHERE s.slug = ?
|
||||
ORDER BY p.modified_at DESC, p.device_id ASC
|
||||
SELECT public_base_url
|
||||
FROM d_players
|
||||
WHERE identifier = ?
|
||||
LIMIT 1
|
||||
`, [slug]);
|
||||
`, [configuredPlayerIdentifier]);
|
||||
|
||||
return rows[0] || null;
|
||||
return normalizePlayerBaseUrl(rows[0] && rows[0].public_base_url) || null;
|
||||
}
|
||||
|
||||
async function fetchScreenPlayerRecord(pool, slug) {
|
||||
if (slug) {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT slug
|
||||
FROM d_screens
|
||||
WHERE slug = ?
|
||||
LIMIT 1`,
|
||||
[slug]
|
||||
);
|
||||
if (!rows.length) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return fetchPlayerRecordByIdentifier(pool, getConfiguredPlayerIdentifier());
|
||||
}
|
||||
|
||||
async function uniqueScreenSlug(pool, baseSlug, excludeId) {
|
||||
@@ -101,8 +139,11 @@ async function fetchScreenEditData(pool) {
|
||||
module.exports = {
|
||||
slugify,
|
||||
normalizePlayerBaseUrl,
|
||||
getConfiguredPlayerIdentifier,
|
||||
fetchPlayerRecordByIdentifier,
|
||||
buildScreenPlayerUrl,
|
||||
fetchScreenPlayerUrls,
|
||||
fetchPlayerPublicBaseUrl,
|
||||
fetchScreenPlayerRecord,
|
||||
uniqueScreenSlug,
|
||||
fetchScreenById,
|
||||
|
||||
+164
-8
@@ -1,7 +1,10 @@
|
||||
// Slide data access helpers, including rich-text normalization and payload building.
|
||||
|
||||
const { fetchTemplateById } = require('./templates');
|
||||
const { parseJsonSafe } = require('./utils');
|
||||
const { parseJsonSafe, validateMaxLength } = require('./utils');
|
||||
|
||||
const TITLE_MAX_LENGTH = 255;
|
||||
const { buildQrCodeContent } = require('./qr-code');
|
||||
|
||||
const ALLOWED_RICH_TEXT_TAGS = ['b', 'strong', 'i', 'em', 'u', 'br', 'p', 'div', 'ul', 'ol', 'li'];
|
||||
const DEFAULT_FONT_SIZE = 32;
|
||||
@@ -111,9 +114,130 @@ function getTextRegionStyle(body, region, existingContent) {
|
||||
};
|
||||
}
|
||||
|
||||
function buildTemplateContent(template, body, filesByField, existingContent) {
|
||||
function getQrRegionStyle(body, region, existingContent) {
|
||||
const existing = existingContent && existingContent[region.region_key] ? existingContent[region.region_key] : {};
|
||||
const styleKeys = [
|
||||
'qr_margin',
|
||||
'qr_background_color',
|
||||
'qr_background_transparent',
|
||||
'qr_background_color_mode',
|
||||
'qr_background_gradient_type',
|
||||
'qr_background_gradient_rotation',
|
||||
'qr_background_gradient_color_1',
|
||||
'qr_background_gradient_color_2',
|
||||
'qr_dots_color',
|
||||
'qr_dots_type',
|
||||
'qr_dots_color_mode',
|
||||
'qr_dots_gradient_type',
|
||||
'qr_dots_gradient_rotation',
|
||||
'qr_dots_gradient_color_1',
|
||||
'qr_dots_gradient_color_2',
|
||||
'qr_corners_square_color',
|
||||
'qr_corners_square_type',
|
||||
'qr_corners_square_color_mode',
|
||||
'qr_corners_square_gradient_type',
|
||||
'qr_corners_square_gradient_rotation',
|
||||
'qr_corners_square_gradient_color_1',
|
||||
'qr_corners_square_gradient_color_2',
|
||||
'qr_corners_dot_color',
|
||||
'qr_corners_dot_type',
|
||||
'qr_corners_dot_color_mode',
|
||||
'qr_corners_dot_gradient_type',
|
||||
'qr_corners_dot_gradient_rotation',
|
||||
'qr_corners_dot_gradient_color_1',
|
||||
'qr_corners_dot_gradient_color_2',
|
||||
'qr_image',
|
||||
'qr_image_size',
|
||||
'qr_image_margin',
|
||||
'qr_image_hide_background_dots',
|
||||
'qr_border_radius'
|
||||
];
|
||||
const style = {};
|
||||
|
||||
styleKeys.forEach((key) => {
|
||||
const fieldNames = [`region_${key}_${region.id}`, `${key}_${region.id}`];
|
||||
let fieldName = fieldNames[0];
|
||||
let hasSubmittedValue = false;
|
||||
let submitted;
|
||||
|
||||
for (let index = 0; index < fieldNames.length; index += 1) {
|
||||
const candidate = fieldNames[index];
|
||||
if (Object.prototype.hasOwnProperty.call(body || {}, candidate)) {
|
||||
fieldName = candidate;
|
||||
hasSubmittedValue = true;
|
||||
submitted = body[candidate];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const value = String(submitted || '').trim();
|
||||
|
||||
if (key === 'qr_background_transparent' || key === 'qr_image_hide_background_dots') {
|
||||
style[key] = hasSubmittedValue;
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === 'qr_background_color_mode' || key === 'qr_dots_color_mode' || key === 'qr_corners_square_color_mode' || key === 'qr_corners_dot_color_mode' || key === 'qr_background_gradient_type' || key === 'qr_dots_gradient_type' || key === 'qr_corners_square_gradient_type' || key === 'qr_corners_dot_gradient_type') {
|
||||
style[key] = value === 'none' ? 'none' : value;
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === 'qr_image') {
|
||||
style[key] = value;
|
||||
return;
|
||||
}
|
||||
|
||||
if (submitted === undefined) {
|
||||
if (existing[key] !== undefined && existing[key] !== null && String(existing[key]).trim() !== '') {
|
||||
style[key] = existing[key];
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (value !== '') {
|
||||
if (key === 'qr_margin') {
|
||||
const parsedMargin = Number(value);
|
||||
if (Number.isFinite(parsedMargin)) {
|
||||
style[key] = Math.max(0, Math.round(parsedMargin));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === 'qr_image_size') {
|
||||
const parsedSize = Number(value);
|
||||
if (Number.isFinite(parsedSize)) {
|
||||
style[key] = Math.max(0, Math.min(1, parsedSize));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === 'qr_image_margin' || key === 'qr_border_radius') {
|
||||
const parsedImageMargin = Number(value);
|
||||
if (Number.isFinite(parsedImageMargin)) {
|
||||
style[key] = Math.max(0, Math.round(parsedImageMargin));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
style[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
return style;
|
||||
}
|
||||
|
||||
async function getRssFeedItemCount(pool, feedId) {
|
||||
const [rows] = await pool.query(
|
||||
'SELECT COUNT(*) AS count FROM i_rss_feed_items WHERE rss_feed_id = ?',
|
||||
[feedId]
|
||||
);
|
||||
|
||||
return Number(rows && rows[0] && rows[0].count) || 0;
|
||||
}
|
||||
|
||||
async function buildTemplateContent(pool, template, body, filesByField, existingContent) {
|
||||
const content = {};
|
||||
template.regions.forEach((region) => {
|
||||
for (const region of template.regions) {
|
||||
if (region.region_type === 'image') {
|
||||
const uploaded = filesByField[`region_image_${region.id}`];
|
||||
const existing = body[`existing_region_image_${region.id}`];
|
||||
@@ -142,6 +266,24 @@ function buildTemplateContent(template, body, filesByField, existingContent) {
|
||||
type: 'webpage',
|
||||
value: submitted === undefined ? current : String(submitted || '').trim()
|
||||
};
|
||||
} else if (region.region_type === 'qr-code') {
|
||||
const uploadedImage = filesByField[`region_qr_image_${region.id}`];
|
||||
const submitted = body[`region_qr_code_${region.id}`];
|
||||
const submittedSvg = body[`region_qr_svg_${region.id}`];
|
||||
const submittedPreview = body[`region_qr_preview_${region.id}`];
|
||||
const existingImage = body[`existing_region_qr_image_${region.id}`];
|
||||
const current = existingContent && existingContent[region.region_key] ? existingContent[region.region_key] : {};
|
||||
const nextValue = submitted === undefined ? String(current.value !== undefined ? current.value : current.qr_code || '').trim() : String(submitted || '').trim();
|
||||
const qrStyle = getQrRegionStyle(body, region, existingContent);
|
||||
delete qrStyle.qr_image;
|
||||
content[region.region_key] = {
|
||||
type: 'qr-code',
|
||||
value: nextValue,
|
||||
qr_svg: submittedSvg === undefined ? String(current.qr_svg || '').trim() : String(submittedSvg || '').trim(),
|
||||
qr_preview: submittedPreview === undefined ? String(current.qr_preview || '').trim() : String(submittedPreview || '').trim(),
|
||||
qr_image: uploadedImage ? `/media/uploads/${uploadedImage.filename}` : String(existingImage === undefined ? String(current.qr_image || '').trim() : String(existingImage || '').trim()),
|
||||
...qrStyle
|
||||
};
|
||||
} else if (region.region_type === 'rtmp') {
|
||||
const submitted = body[`region_rtmp_${region.id}`];
|
||||
const current = existingContent && existingContent[region.region_key] ? existingContent[region.region_key] : {};
|
||||
@@ -173,11 +315,13 @@ function buildTemplateContent(template, body, filesByField, existingContent) {
|
||||
const feedId = body[`region_rss_feed_id_${region.id}`];
|
||||
const itemNumber = body[`region_rss_item_number_${region.id}`];
|
||||
const parsedItemNumber = Math.max(1, Number(itemNumber || current.item_number || 1));
|
||||
const normalizedFeedId = feedId === undefined || feedId === null || feedId === '' ? Number(current.feed_id || 0) : Number(feedId);
|
||||
const itemCount = normalizedFeedId > 0 ? Math.max(1, await getRssFeedItemCount(pool, normalizedFeedId) || 1) : 1;
|
||||
content[region.region_key] = {
|
||||
type: 'rss',
|
||||
value: stripEditorOnlyMarkup(normalizeEditorMarkup(submitted === undefined ? String(current.value || '') : String(submitted || ''))),
|
||||
feed_id: feedId === undefined || feedId === null || feedId === '' ? (current.feed_id || null) : Number(feedId),
|
||||
item_number: Number.isFinite(parsedItemNumber) && parsedItemNumber > 0 ? parsedItemNumber : 1,
|
||||
item_number: Math.min(itemCount, Number.isFinite(parsedItemNumber) && parsedItemNumber > 0 ? parsedItemNumber : 1),
|
||||
variable_name: 'item',
|
||||
font_family: style.font_family,
|
||||
font_size: style.font_size,
|
||||
@@ -202,7 +346,7 @@ function buildTemplateContent(template, body, filesByField, existingContent) {
|
||||
font_size: style.font_size,
|
||||
font_color: style.font_color
|
||||
};
|
||||
} else if (!['text', 'image', 'video', 'webpage', 'html', 'rtmp', 'rss', 'api'].includes(String(region.region_type || '').trim())) {
|
||||
} else if (!['text', 'image', 'video', 'webpage', 'qr-code', 'html', 'rtmp', 'rss', 'api'].includes(String(region.region_type || '').trim())) {
|
||||
const current = existingContent && existingContent[region.region_key] && typeof existingContent[region.region_key] === 'object' ? existingContent[region.region_key] : {};
|
||||
const suffix = '_' + region.id;
|
||||
const generic = {};
|
||||
@@ -249,12 +393,12 @@ function buildTemplateContent(template, body, filesByField, existingContent) {
|
||||
font_color: style.font_color
|
||||
};
|
||||
}
|
||||
});
|
||||
}
|
||||
return content;
|
||||
}
|
||||
|
||||
async function buildSlidePayload(pool, req, existingSlide) {
|
||||
const title = String(req.body.title || '').trim();
|
||||
const title = validateMaxLength(req.body.title || '', TITLE_MAX_LENGTH, 'Slide title');
|
||||
const templateId = req.body.template_id ? Number(req.body.template_id) : null;
|
||||
const filesByField = getFilesByField(req.files || []);
|
||||
const template = templateId ? await fetchTemplateById(pool, templateId) : null;
|
||||
@@ -273,10 +417,22 @@ async function buildSlidePayload(pool, req, existingSlide) {
|
||||
}
|
||||
|
||||
if (template) {
|
||||
const content = await buildTemplateContent(pool, template, req.body, filesByField, existingContent);
|
||||
await Promise.all(Object.keys(content).map(async function (regionKey) {
|
||||
const region = template.regions.find(function (item) {
|
||||
return String(item.region_key || '').trim() === regionKey;
|
||||
});
|
||||
if (!region || region.region_type !== 'qr-code') {
|
||||
return;
|
||||
}
|
||||
|
||||
content[regionKey] = await buildQrCodeContent(content[regionKey]);
|
||||
}));
|
||||
|
||||
return {
|
||||
title,
|
||||
templateId: template.id,
|
||||
contentJson: JSON.stringify(buildTemplateContent(template, req.body, filesByField, existingContent))
|
||||
contentJson: JSON.stringify(content)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
// Template data access helpers and region normalization logic.
|
||||
|
||||
const { parseJsonSafe, readFormArray } = require('./utils');
|
||||
const { parseJsonSafe, readFormArray, validateMaxLength } = require('./utils');
|
||||
const animationPresets = require('../web/public/js/templates/animation-presets');
|
||||
|
||||
const TEMPLATE_NAME_MAX_LENGTH = 255;
|
||||
const REGION_NAME_MAX_LENGTH = 255;
|
||||
|
||||
function sanitizeBackgroundColor(value) {
|
||||
const raw = String(value || '').trim();
|
||||
if (/^#[0-9a-fA-F]{6}$/.test(raw) || /^#[0-9a-fA-F]{3}$/.test(raw)) {
|
||||
@@ -137,10 +140,11 @@ function extractTemplateRegions(body) {
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed.map((region) => {
|
||||
const regionType = normalizeTemplateRegionType(region.region_type);
|
||||
const regionName = validateMaxLength(region.region_name || region.region_key || region.label || '', REGION_NAME_MAX_LENGTH, 'Region name');
|
||||
return {
|
||||
region_key: String(region.region_name || region.region_key || region.label || '').trim(),
|
||||
region_key: regionName,
|
||||
region_type: regionType,
|
||||
label: String(region.region_name || region.label || region.region_key || '').trim(),
|
||||
label: regionName,
|
||||
lock_ratio: normalizeTemplateRegionLockRatio(region.lock_ratio),
|
||||
animation_json: normalizeTemplateRegionAnimationConfig(region.animation_json),
|
||||
x: Number(region.x || 0),
|
||||
@@ -167,7 +171,7 @@ function extractTemplateRegions(body) {
|
||||
const regions = [];
|
||||
|
||||
for (let i = 0; i < keys.length; i += 1) {
|
||||
const name = String(names[i] || keys[i] || labels[i] || '').trim();
|
||||
const name = validateMaxLength(names[i] || keys[i] || labels[i] || '', REGION_NAME_MAX_LENGTH, 'Region name');
|
||||
const rawType = String(types[i] || 'text').trim();
|
||||
const regionType = normalizeTemplateRegionType(rawType);
|
||||
if (!name) {
|
||||
@@ -236,7 +240,7 @@ function getFilesByField(files) {
|
||||
}
|
||||
|
||||
async function buildTemplatePayload(pool, req, existingTemplate) {
|
||||
const name = String(req.body.name || '').trim();
|
||||
const name = validateMaxLength(req.body.name || '', TEMPLATE_NAME_MAX_LENGTH, 'Template name');
|
||||
const canvasSizeId = req.body.canvas_size_id ? Number(req.body.canvas_size_id) : null;
|
||||
let canvasWidth = Math.max(1, Number((existingTemplate && existingTemplate.canvas_size_width) || 1920));
|
||||
let canvasHeight = Math.max(1, Number((existingTemplate && existingTemplate.canvas_size_height) || 1080));
|
||||
|
||||
+100
-1
@@ -24,6 +24,26 @@ function readFormArray(body, key) {
|
||||
return [body[key]];
|
||||
}
|
||||
|
||||
function validateMaxLength(value, maxLength, fieldName) {
|
||||
const text = String(value || '').trim();
|
||||
const limit = Number(maxLength);
|
||||
if (Number.isFinite(limit) && limit > 0 && text.length > limit) {
|
||||
const error = new Error(fieldName + ' must be ' + limit + ' characters or fewer.');
|
||||
error.statusCode = 400;
|
||||
throw error;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
function truncateToMaxLength(value, maxLength) {
|
||||
const text = String(value || '').trim();
|
||||
const limit = Number(maxLength);
|
||||
if (!Number.isFinite(limit) || limit <= 0 || text.length <= limit) {
|
||||
return text;
|
||||
}
|
||||
return text.slice(0, limit);
|
||||
}
|
||||
|
||||
function normalizePageNumber(value) {
|
||||
const pageNumber = Math.floor(Number(value) || 1);
|
||||
return Math.max(1, pageNumber);
|
||||
@@ -201,6 +221,75 @@ function findTopLevelWhereIndex(sql) {
|
||||
return lastWhereIndex;
|
||||
}
|
||||
|
||||
function findTopLevelGroupByIndex(sql) {
|
||||
const text = String(sql || '');
|
||||
let depth = 0;
|
||||
let inSingleQuote = false;
|
||||
let inDoubleQuote = false;
|
||||
let inBacktick = false;
|
||||
let lastGroupByIndex = -1;
|
||||
|
||||
for (let index = 0; index < text.length; index += 1) {
|
||||
const character = text[index];
|
||||
const previousCharacter = index > 0 ? text[index - 1] : '';
|
||||
|
||||
if (inSingleQuote) {
|
||||
if (character === '\'' && previousCharacter !== '\\') {
|
||||
inSingleQuote = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (inDoubleQuote) {
|
||||
if (character === '"' && previousCharacter !== '\\') {
|
||||
inDoubleQuote = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (inBacktick) {
|
||||
if (character === '`') {
|
||||
inBacktick = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (character === '\'') {
|
||||
inSingleQuote = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (character === '"') {
|
||||
inDoubleQuote = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (character === '`') {
|
||||
inBacktick = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (character === '(') {
|
||||
depth += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (character === ')' && depth > 0) {
|
||||
depth -= 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (depth === 0 && /[gG]/.test(character)) {
|
||||
const remaining = text.slice(index);
|
||||
if (/^group\s+by\b/i.test(remaining)) {
|
||||
lastGroupByIndex = index;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lastGroupByIndex;
|
||||
}
|
||||
|
||||
function buildSearchFilter(searchColumns, searchTerm) {
|
||||
const columns = Array.isArray(searchColumns) ? searchColumns.map(function (column) {
|
||||
return String(column || '').trim();
|
||||
@@ -238,17 +327,24 @@ async function fetchPagedRows(pool, options) {
|
||||
throw new Error('fetchPagedRows requires selectSql and countSql.');
|
||||
}
|
||||
const orderByIndex = findTopLevelOrderByIndex(selectSql);
|
||||
const groupByIndex = findTopLevelGroupByIndex(selectSql);
|
||||
let baseSelectSql = selectSql;
|
||||
let orderBySql = '';
|
||||
let groupBySql = '';
|
||||
|
||||
if (orderByIndex >= 0) {
|
||||
baseSelectSql = selectSql.slice(0, orderByIndex).trim();
|
||||
orderBySql = selectSql.slice(orderByIndex).trim();
|
||||
}
|
||||
|
||||
if (groupByIndex >= 0 && (orderByIndex < 0 || groupByIndex < orderByIndex)) {
|
||||
baseSelectSql = selectSql.slice(0, groupByIndex).trim();
|
||||
groupBySql = selectSql.slice(groupByIndex, orderByIndex >= 0 ? orderByIndex : selectSql.length).trim();
|
||||
}
|
||||
|
||||
const hasTopLevelWhere = findTopLevelWhereIndex(baseSelectSql) >= 0;
|
||||
const searchClause = searchFilter.clause ? (hasTopLevelWhere ? searchFilter.clause.replace(/^\s*WHERE\s+/i, ' AND ') : searchFilter.clause) : '';
|
||||
const filteredSelectSql = `${baseSelectSql}${searchClause}`;
|
||||
const filteredSelectSql = `${baseSelectSql}${searchClause}${groupBySql ? ' ' + groupBySql : ''}`;
|
||||
const countQuery = searchFilter.clause
|
||||
? `SELECT COUNT(*) AS count FROM (${filteredSelectSql}) AS filtered_rows`
|
||||
: countSql;
|
||||
@@ -294,10 +390,13 @@ async function fetchDuplicateName(pool, tableName, name, excludeId, columnName)
|
||||
module.exports = {
|
||||
parseJsonSafe,
|
||||
readFormArray,
|
||||
validateMaxLength,
|
||||
truncateToMaxLength,
|
||||
normalizePageNumber,
|
||||
normalizeSortDirection,
|
||||
buildSortOrderClause,
|
||||
findTopLevelOrderByIndex,
|
||||
findTopLevelGroupByIndex,
|
||||
buildSearchFilter,
|
||||
fetchPagedRows,
|
||||
fetchDuplicateName
|
||||
|
||||
+31
-1
@@ -1,5 +1,17 @@
|
||||
// Snapshot only: keep this file aligned with the current schema state.
|
||||
async function ensureSchema(pool, options) {
|
||||
const schemaLockName = 'pulse_signage_schema_lock';
|
||||
const schemaConnection = await pool.getConnection();
|
||||
|
||||
try {
|
||||
pool = schemaConnection;
|
||||
|
||||
const [lockRows] = await pool.query('SELECT GET_LOCK(?, 120) AS lock_acquired', [schemaLockName]);
|
||||
if (!Number(lockRows && lockRows[0] && lockRows[0].lock_acquired)) {
|
||||
throw new Error('Unable to acquire the schema migration lock.');
|
||||
}
|
||||
|
||||
try {
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS c_canvas_sizes (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
@@ -116,13 +128,24 @@ async function ensureSchema(pool, options) {
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||
`);
|
||||
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS d_players (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
identifier VARCHAR(128) NOT NULL UNIQUE,
|
||||
public_base_url VARCHAR(512) NULL,
|
||||
internal_base_url VARCHAR(512) NULL,
|
||||
last_seen_at TIMESTAMP NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
modified_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||
`);
|
||||
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS d_screens (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
slug VARCHAR(255) NOT NULL UNIQUE,
|
||||
playlist_id INT NULL,
|
||||
player_id INT NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
created_by INT NULL,
|
||||
modified_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
@@ -362,6 +385,13 @@ async function ensureSchema(pool, options) {
|
||||
|
||||
const { runMigrations } = require('./migrations');
|
||||
await runMigrations(pool, options);
|
||||
} finally {
|
||||
await pool.query('SELECT RELEASE_LOCK(?)', [schemaLockName]).catch(function () {
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
schemaConnection.release();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
+140
-6
@@ -19,10 +19,6 @@ const VERSIONED_MIGRATIONS = [
|
||||
`);
|
||||
}
|
||||
|
||||
// Seed the singleton player row used by the current one-player model.
|
||||
// For multi-player support, this seed and the hardcoded screen_id/player_id mapping will need to be replaced.
|
||||
await pool.query(`INSERT IGNORE INTO d_players (device_id) VALUES ('1')`);
|
||||
|
||||
// Store the player pointer on screens so we can resolve the player without needing a player-side screen_id.
|
||||
// This is the singleton-player shortcut; a multi-player model should make this relational instead of hardcoded to '1'.
|
||||
if (!(await columnExists(pool, 'd_screens', 'player_id'))) {
|
||||
@@ -212,6 +208,93 @@ const VERSIONED_MIGRATIONS = [
|
||||
run: async function (pool) {
|
||||
await ensureColumn(pool, 'c_template_regions', 'animation_json', 'JSON NULL', 'lock_ratio');
|
||||
}
|
||||
},
|
||||
{
|
||||
version: '2.6.2',
|
||||
label: 'v2.6.2 player identity schema',
|
||||
run: async function (pool) {
|
||||
if (!(await columnExists(pool, 'd_players', 'device_id'))) {
|
||||
await dropForeignKeyIfExists(pool, 'd_screens', 'player_id');
|
||||
|
||||
if (!(await columnExists(pool, 'd_players', 'identifier'))) {
|
||||
await ensureColumn(pool, 'd_players', 'identifier', 'VARCHAR(128) NOT NULL UNIQUE', 'id');
|
||||
}
|
||||
if (!(await columnExists(pool, 'd_players', 'id'))) {
|
||||
await ensureColumn(pool, 'd_players', 'id', 'INT NOT NULL AUTO_INCREMENT', null);
|
||||
await pool.query('ALTER TABLE d_players ADD PRIMARY KEY (id)');
|
||||
} else if (!(await columnIsAutoIncrement(pool, 'd_players', 'id'))) {
|
||||
await pool.query('ALTER TABLE d_players MODIFY COLUMN id INT NOT NULL AUTO_INCREMENT');
|
||||
}
|
||||
await pool.query('ALTER TABLE d_screens MODIFY COLUMN player_id INT NULL AFTER playlist_id');
|
||||
return;
|
||||
}
|
||||
|
||||
await dropForeignKeyIfExists(pool, 'd_screens', 'player_id');
|
||||
|
||||
await pool.query('DROP TABLE IF EXISTS d_players_rebuild');
|
||||
await pool.query(`
|
||||
CREATE TABLE d_players_rebuild (
|
||||
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
identifier VARCHAR(128) NOT NULL UNIQUE,
|
||||
public_base_url VARCHAR(512) NULL,
|
||||
internal_base_url VARCHAR(512) NULL,
|
||||
last_seen_at TIMESTAMP NULL,
|
||||
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
modified_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||
`);
|
||||
|
||||
await pool.query(`
|
||||
INSERT INTO d_players_rebuild (identifier, public_base_url, internal_base_url, last_seen_at, created_at, modified_at)
|
||||
SELECT DISTINCT
|
||||
device_id AS identifier,
|
||||
public_base_url,
|
||||
internal_base_url,
|
||||
last_seen_at,
|
||||
created_at,
|
||||
modified_at
|
||||
FROM d_players
|
||||
ORDER BY COALESCE(created_at, modified_at, device_id), device_id
|
||||
`);
|
||||
|
||||
await pool.query('DROP TEMPORARY TABLE IF EXISTS d_player_id_map');
|
||||
await pool.query(`
|
||||
CREATE TEMPORARY TABLE d_player_id_map AS
|
||||
SELECT old_players.device_id AS old_device_id, rebuilt_players.id AS new_player_id
|
||||
FROM d_players old_players
|
||||
JOIN d_players_rebuild rebuilt_players ON rebuilt_players.identifier = old_players.device_id
|
||||
`);
|
||||
|
||||
await pool.query(
|
||||
`UPDATE d_screens s
|
||||
JOIN d_player_id_map m ON m.old_device_id = CAST(s.player_id AS CHAR)
|
||||
SET s.player_id = m.new_player_id
|
||||
WHERE s.player_id IS NOT NULL`
|
||||
);
|
||||
|
||||
await pool.query('DROP TABLE d_players');
|
||||
await pool.query('RENAME TABLE d_players_rebuild TO d_players');
|
||||
|
||||
await pool.query('ALTER TABLE d_screens MODIFY COLUMN player_id INT NULL AFTER playlist_id');
|
||||
}
|
||||
},
|
||||
{
|
||||
version: '2.6.3',
|
||||
label: 'v2.6.3 screen-player fk removal',
|
||||
run: async function (pool) {
|
||||
await dropForeignKeyIfExists(pool, 'd_screens', 'player_id');
|
||||
if (await columnExists(pool, 'd_screens', 'player_id')) {
|
||||
await pool.query('ALTER TABLE d_screens MODIFY COLUMN player_id INT NULL AFTER playlist_id');
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
version: '2.6.4',
|
||||
label: 'v2.6.4 drop screen player id',
|
||||
run: async function (pool) {
|
||||
await dropForeignKeyIfExists(pool, 'd_screens', 'player_id');
|
||||
await dropColumnIfExists(pool, 'd_screens', 'player_id');
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
@@ -228,6 +311,20 @@ async function columnExists(pool, tableName, columnName) {
|
||||
return Number(rows && rows[0] && rows[0].column_count) > 0;
|
||||
}
|
||||
|
||||
async function columnIsAutoIncrement(pool, tableName, columnName) {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT COUNT(*) AS auto_increment_count
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = ?
|
||||
AND COLUMN_NAME = ?
|
||||
AND EXTRA LIKE '%auto_increment%'`,
|
||||
[tableName, columnName]
|
||||
);
|
||||
|
||||
return Number(rows && rows[0] && rows[0].auto_increment_count) > 0;
|
||||
}
|
||||
|
||||
async function ensureColumn(pool, tableName, columnName, columnDefinition, afterColumn) {
|
||||
if (await columnExists(pool, tableName, columnName)) {
|
||||
return;
|
||||
@@ -282,13 +379,39 @@ async function ensureForeignKey(pool, tableName, constraintName, columnName, ref
|
||||
await pool.query('ALTER TABLE ' + tableName + ' ADD CONSTRAINT ' + candidateName + ' FOREIGN KEY (' + columnName + ') REFERENCES ' + referencedTable + '(' + referencedColumn + ') ON DELETE ' + onDeleteAction);
|
||||
return;
|
||||
} catch (error) {
|
||||
if (!error || (error.code !== 'ER_FK_DUP_NAME' && error.errno !== 1826)) {
|
||||
if (!error || (error.code !== 'ER_FK_DUP_NAME' && error.errno !== 1826 && error.errno !== 121)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function dropForeignKeyIfExists(pool, tableName, columnName) {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT CONSTRAINT_NAME AS constraint_name
|
||||
FROM information_schema.KEY_COLUMN_USAGE
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = ?
|
||||
AND COLUMN_NAME = ?
|
||||
AND REFERENCED_TABLE_NAME IS NOT NULL
|
||||
LIMIT 1`,
|
||||
[tableName, columnName]
|
||||
);
|
||||
|
||||
const constraintName = String(rows && rows[0] && rows[0].constraint_name || '').trim();
|
||||
if (!constraintName) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await pool.query('ALTER TABLE ' + tableName + ' DROP FOREIGN KEY ' + constraintName);
|
||||
} catch (error) {
|
||||
if (!error || (error.code !== 'ER_CANT_DROP_FIELD_OR_KEY' && error.errno !== 1091)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function dropColumnIfExists(pool, tableName, columnName) {
|
||||
if (await columnExists(pool, tableName, columnName)) {
|
||||
try {
|
||||
@@ -443,9 +566,20 @@ async function runMigrations(pool, options) {
|
||||
// Only run migrations that are newer than the installed schema version and not beyond the app version.
|
||||
const targetVersion = String(appVersion || '0.0.0').trim();
|
||||
const currentVersion = String(options && options.currentVersion || '0.0.0').trim();
|
||||
const legacyPlayerSchemaPresent = await columnExists(pool, 'd_players', 'device_id');
|
||||
const screenPlayerColumnPresent = await columnExists(pool, 'd_screens', 'player_id');
|
||||
let effectiveCurrentVersion = currentVersion;
|
||||
|
||||
if (!legacyPlayerSchemaPresent && compareVersions(effectiveCurrentVersion, '2.1.0') < 0) {
|
||||
effectiveCurrentVersion = '2.1.0';
|
||||
}
|
||||
|
||||
if (!screenPlayerColumnPresent && compareVersions(effectiveCurrentVersion, '2.6.3') < 0) {
|
||||
effectiveCurrentVersion = '2.6.3';
|
||||
}
|
||||
|
||||
for (const migration of VERSIONED_MIGRATIONS) {
|
||||
if (compareVersions(migration.version, currentVersion) > 0 && compareVersions(migration.version, targetVersion) <= 0) {
|
||||
if (compareVersions(migration.version, effectiveCurrentVersion) > 0 && compareVersions(migration.version, targetVersion) <= 0) {
|
||||
await migration.run(pool);
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+361
-21
@@ -2,6 +2,7 @@ const express = require('express');
|
||||
const fs = require('fs');
|
||||
const http = require('http');
|
||||
const path = require('path');
|
||||
const { WebSocket } = require('ws');
|
||||
const common = require('./common');
|
||||
const { createPlayerRuntime } = require('./player/runtime');
|
||||
const { createPlayerPlaylistService } = require('./player/playlist');
|
||||
@@ -10,26 +11,48 @@ const { normalizeDeviceId, registerPlayerOnboardingRoutes, commitDeviceBinding }
|
||||
const { createOnboardingStore } = require('./player/onboarding/store');
|
||||
const { registerPlayerRoutes } = require('./player/routes');
|
||||
const { ensureFontLibrary } = require('#src/web/lib/media/font-library');
|
||||
const { createRequestAuthHeaders } = require('#src/request-auth');
|
||||
const { getConfiguredPlayerIdentifier, recordPlayerHeartbeat } = require('#src/data/player-registry');
|
||||
|
||||
|
||||
// Player runtime, media API, and websocket wiring.
|
||||
async function start() {
|
||||
const app = express();
|
||||
const pool = common.createPool();
|
||||
const pool = String(process.env.BRIDGE_PUBLIC_URL || '').trim().replace(/\/$/, '') ? null : common.createPool();
|
||||
const PORT = Number(process.env.PLAYER_PORT || 8081);
|
||||
const PLAYER_PUBLIC_BASE_URL = String(process.env.PLAYER_PUBLIC_BASE_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, '');
|
||||
const PLAYER_INTERNAL_BASE_URL = String(process.env.PLAYER_INTERNAL_BASE_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, '');
|
||||
const PLAYER_IDENTIFIER = '1';
|
||||
const PLAYER_PUBLIC_URL = String(process.env.PLAYER_PUBLIC_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, '');
|
||||
const BRIDGE_PUBLIC_URL = String(process.env.BRIDGE_PUBLIC_URL || '').trim().replace(/\/$/, '');
|
||||
const isRemotePlayer = Boolean(BRIDGE_PUBLIC_URL);
|
||||
const PLAYER_INTERNAL_URL = String(isRemotePlayer ? BRIDGE_PUBLIC_URL : (process.env.PLAYER_INTERNAL_URL || PLAYER_PUBLIC_URL || process.env.PLAYER_BASE_URL || '')).trim().replace(/\/$/, '');
|
||||
const PLAYER_DEVICE_ID = getConfiguredPlayerIdentifier();
|
||||
const ASSET_DIR = path.join(__dirname, 'player', 'public');
|
||||
const MEDIA_DIR = path.join(__dirname, '..', 'media');
|
||||
const ONBOARDING_QUEUE_FILE = path.join(MEDIA_DIR, 'player-onboarding-queue.json');
|
||||
const DB_SYNC_INTERVAL_MS = Number(process.env.PLAYER_DB_SYNC_INTERVAL_MS || 15000);
|
||||
const onboardingStore = createOnboardingStore(ONBOARDING_QUEUE_FILE);
|
||||
let thinClientSocket = null;
|
||||
const playerRuntime = createPlayerRuntime({
|
||||
pool: pool,
|
||||
normalizeDeviceId: normalizeDeviceId
|
||||
normalizeDeviceId: normalizeDeviceId,
|
||||
notifySnapshot: function (snapshot) {
|
||||
if (!thinClientSocket || thinClientSocket.readyState !== WebSocket.OPEN) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
thinClientSocket.send(JSON.stringify({
|
||||
type: 'snapshot',
|
||||
deviceId: PLAYER_DEVICE_ID,
|
||||
slug: snapshot && snapshot.slug ? String(snapshot.slug).trim() : '',
|
||||
connections: Array.isArray(snapshot && snapshot.connections) ? snapshot.connections : []
|
||||
}));
|
||||
} catch (_error) {
|
||||
}
|
||||
}
|
||||
});
|
||||
const playerPlaylistService = createPlayerPlaylistService({
|
||||
const playerPlaylistService = isRemotePlayer
|
||||
? null
|
||||
: createPlayerPlaylistService({
|
||||
pool: pool,
|
||||
common: common,
|
||||
snapshotDir: path.join(MEDIA_DIR, 'player-cache', 'screen-playlists')
|
||||
@@ -40,14 +63,158 @@ async function start() {
|
||||
const server = http.createServer(app);
|
||||
playerRuntime.installWebsocket(server);
|
||||
app.use(express.json());
|
||||
|
||||
let hasLoggedPlayerStartup = false;
|
||||
|
||||
function logPlayerStartup(connectionState) {
|
||||
if (hasLoggedPlayerStartup) {
|
||||
return;
|
||||
}
|
||||
|
||||
hasLoggedPlayerStartup = true;
|
||||
console.info('[player] startup', {
|
||||
mode: isRemotePlayer ? 'bridge client' : 'local',
|
||||
connected: connectionState && typeof connectionState.connected === 'boolean' ? connectionState.connected : false,
|
||||
publicBaseUrl: PLAYER_PUBLIC_URL || null,
|
||||
bridgeBaseUrl: PLAYER_INTERNAL_URL || null,
|
||||
bridgeWebSocketUrl: BRIDGE_PUBLIC_URL ? createThinClientWebSocketUrl() : null
|
||||
});
|
||||
}
|
||||
|
||||
fs.mkdirSync(MEDIA_DIR, { recursive: true });
|
||||
|
||||
function resolveLocalMediaFilePath(fileName) {
|
||||
const relativePath = path.normalize(String(fileName || '').trim()).replace(/^([\\/])+/, '');
|
||||
if (!relativePath || relativePath === '.' || relativePath.startsWith('..') || path.isAbsolute(relativePath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const resolvedMediaDir = path.resolve(MEDIA_DIR);
|
||||
const resolvedFilePath = path.resolve(MEDIA_DIR, relativePath);
|
||||
if (resolvedFilePath !== resolvedMediaDir && !resolvedFilePath.startsWith(resolvedMediaDir + path.sep)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return resolvedFilePath;
|
||||
}
|
||||
|
||||
async function triggerWebMediaSync() {
|
||||
if (!isRemotePlayer || !BRIDGE_PUBLIC_URL) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const authHeaders = createRequestAuthHeaders({
|
||||
method: 'POST',
|
||||
pathname: '/api/internal/sync/player-media'
|
||||
});
|
||||
const response = await fetch(`${BRIDGE_PUBLIC_URL}/api/internal/sync/player-media`, {
|
||||
method: 'POST',
|
||||
headers: Object.assign({
|
||||
Accept: 'application/json'
|
||||
}, authHeaders)
|
||||
});
|
||||
|
||||
return Boolean(response && response.ok);
|
||||
} catch (_error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
let webMediaSyncCompleted = false;
|
||||
|
||||
async function handleThinClientCommand(socket, rawMessage) {
|
||||
let payload = null;
|
||||
try {
|
||||
payload = JSON.parse(String(rawMessage || ''));
|
||||
} catch (_error) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!payload || typeof payload !== 'object' || Array.isArray(payload) || String(payload.type || '').trim() !== 'command') {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestId = String(payload.requestId || '').trim() || null;
|
||||
const command = String(payload.command || '').trim().toLowerCase();
|
||||
const response = {
|
||||
type: 'command-response',
|
||||
requestId: requestId,
|
||||
ok: false
|
||||
};
|
||||
|
||||
try {
|
||||
if (command === 'media-put') {
|
||||
const relativePath = String(payload.relativePath || payload.filename || '').trim();
|
||||
const filePath = resolveLocalMediaFilePath(relativePath);
|
||||
const bodyBase64 = String(payload.bodyBase64 || '').trim();
|
||||
if (!filePath || !bodyBase64) {
|
||||
response.error = 'Invalid media payload.';
|
||||
} else {
|
||||
const bodyBuffer = Buffer.from(bodyBase64, 'base64');
|
||||
await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
|
||||
await fs.promises.writeFile(filePath, bodyBuffer);
|
||||
response.ok = true;
|
||||
}
|
||||
} else if (command === 'media-delete') {
|
||||
const relativePath = String(payload.relativePath || payload.filename || '').trim();
|
||||
const filePath = resolveLocalMediaFilePath(relativePath);
|
||||
if (!filePath) {
|
||||
response.error = 'Invalid media path.';
|
||||
} else {
|
||||
try {
|
||||
await fs.promises.unlink(filePath);
|
||||
} catch (error) {
|
||||
if (!error || error.code !== 'ENOENT') {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
response.ok = true;
|
||||
}
|
||||
} else if (['refresh', 'reload', 'redirect', 'pause', 'blackout', 'previous', 'next', 'setclientname'].indexOf(command) !== -1) {
|
||||
const screenSlug = String(payload.screenSlug || payload.slug || '').trim();
|
||||
if (!screenSlug) {
|
||||
response.error = 'Screen slug is required.';
|
||||
} else if (payload.connectionId) {
|
||||
const sent = await playerRuntime.sendCommandToConnection(screenSlug, String(payload.connectionId || '').trim(), payload);
|
||||
response.ok = sent > 0;
|
||||
if (!response.ok) {
|
||||
response.error = 'Player is not connected.';
|
||||
}
|
||||
} else {
|
||||
const sent = await playerRuntime.broadcastCommand(screenSlug, payload);
|
||||
response.ok = sent > 0;
|
||||
if (!response.ok) {
|
||||
response.error = 'Player is not connected.';
|
||||
}
|
||||
}
|
||||
} else {
|
||||
response.error = 'Unsupported command.';
|
||||
}
|
||||
} catch (error) {
|
||||
response.error = error && error.message ? error.message : 'Command failed.';
|
||||
}
|
||||
|
||||
if (socket && socket.readyState === WebSocket.OPEN) {
|
||||
socket.send(JSON.stringify(response));
|
||||
}
|
||||
}
|
||||
app.use(function (error, _req, res, _next) {
|
||||
console.error(error);
|
||||
res.status(error.statusCode || 500).send(error.statusCode ? error.message : 'Internal server error');
|
||||
});
|
||||
|
||||
await ensureFontLibrary(MEDIA_DIR);
|
||||
|
||||
registerPlayerOnboardingRoutes(app, {
|
||||
pool: pool,
|
||||
common: common,
|
||||
playerRuntime: playerRuntime,
|
||||
onboardingStore: onboardingStore,
|
||||
playerPublicBaseUrl: PLAYER_PUBLIC_BASE_URL,
|
||||
playerInternalBaseUrl: PLAYER_INTERNAL_BASE_URL,
|
||||
QRCode: require('qrcode')
|
||||
playerPublicBaseUrl: PLAYER_PUBLIC_URL,
|
||||
playerInternalBaseUrl: PLAYER_INTERNAL_URL,
|
||||
bridgeBaseUrl: BRIDGE_PUBLIC_URL,
|
||||
playerDeviceId: PLAYER_DEVICE_ID
|
||||
});
|
||||
registerPlayerRoutes(app, {
|
||||
pool: pool,
|
||||
@@ -57,27 +224,189 @@ async function start() {
|
||||
playerRuntime: playerRuntime,
|
||||
playerPlaylistService: playerPlaylistService,
|
||||
rtmpStreamService: rtmpStreamService,
|
||||
playerPublicBaseUrl: PLAYER_PUBLIC_BASE_URL,
|
||||
playerInternalBaseUrl: PLAYER_INTERNAL_BASE_URL,
|
||||
playerIdentifier: PLAYER_IDENTIFIER
|
||||
playerPublicBaseUrl: PLAYER_PUBLIC_URL,
|
||||
playerInternalBaseUrl: PLAYER_INTERNAL_URL,
|
||||
bridgeBaseUrl: BRIDGE_PUBLIC_URL,
|
||||
playerDeviceId: PLAYER_DEVICE_ID
|
||||
});
|
||||
|
||||
app.use(function (error, _req, res, _next) {
|
||||
console.error(error);
|
||||
res.status(error.statusCode || 500).send(error.statusCode ? error.message : 'Internal server error');
|
||||
function createThinClientWebSocketUrl() {
|
||||
if (!BRIDGE_PUBLIC_URL) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return BRIDGE_PUBLIC_URL.replace(/^http:/i, 'ws:').replace(/^https:/i, 'wss:') + '/ws/players';
|
||||
}
|
||||
|
||||
function startThinClientRegistration() {
|
||||
const thinClientUrl = createThinClientWebSocketUrl();
|
||||
if (!thinClientUrl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let socket = null;
|
||||
let reconnectTimer = null;
|
||||
let heartbeatTimer = null;
|
||||
|
||||
function clearTimers() {
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
}
|
||||
if (heartbeatTimer) {
|
||||
clearInterval(heartbeatTimer);
|
||||
heartbeatTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function connect() {
|
||||
clearTimers();
|
||||
const timestamp = String(Date.now());
|
||||
const authHeaders = createRequestAuthHeaders({
|
||||
method: 'GET',
|
||||
pathname: '/ws/players',
|
||||
timestamp: timestamp
|
||||
});
|
||||
let webMediaSyncTriggered = false;
|
||||
socket = new WebSocket(thinClientUrl, {
|
||||
headers: Object.assign({
|
||||
'x-pulse-request-timestamp': timestamp
|
||||
}, authHeaders)
|
||||
});
|
||||
thinClientSocket = socket;
|
||||
|
||||
function sendSnapshot(slug) {
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
socket.send(JSON.stringify({
|
||||
type: 'snapshot',
|
||||
deviceId: PLAYER_DEVICE_ID,
|
||||
slug: String(slug || '').trim(),
|
||||
connections: playerRuntime.snapshotConnections(slug)
|
||||
}));
|
||||
} catch (_error) {
|
||||
}
|
||||
}
|
||||
|
||||
socket.on('open', function () {
|
||||
logPlayerStartup({
|
||||
connected: true
|
||||
});
|
||||
|
||||
fs.mkdirSync(MEDIA_DIR, { recursive: true });
|
||||
await ensureFontLibrary(MEDIA_DIR);
|
||||
socket.send(JSON.stringify({
|
||||
type: 'register',
|
||||
deviceId: PLAYER_DEVICE_ID,
|
||||
publicBaseUrl: PLAYER_PUBLIC_URL,
|
||||
internalBaseUrl: PLAYER_INTERNAL_URL
|
||||
}));
|
||||
|
||||
playerRuntime.snapshotSlugs().forEach(function (slug) {
|
||||
sendSnapshot(slug);
|
||||
});
|
||||
|
||||
if (!webMediaSyncCompleted) {
|
||||
triggerWebMediaSync().then(function (success) {
|
||||
webMediaSyncTriggered = Boolean(success);
|
||||
webMediaSyncCompleted = Boolean(success) || webMediaSyncCompleted;
|
||||
}).catch(function () {
|
||||
webMediaSyncTriggered = false;
|
||||
});
|
||||
}
|
||||
|
||||
heartbeatTimer = setInterval(function () {
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
||||
return;
|
||||
}
|
||||
socket.send(JSON.stringify({
|
||||
type: 'heartbeat',
|
||||
deviceId: PLAYER_DEVICE_ID,
|
||||
publicBaseUrl: PLAYER_PUBLIC_URL,
|
||||
internalBaseUrl: PLAYER_INTERNAL_URL
|
||||
}));
|
||||
|
||||
if (!webMediaSyncTriggered && !webMediaSyncCompleted) {
|
||||
triggerWebMediaSync().then(function (success) {
|
||||
webMediaSyncTriggered = Boolean(success);
|
||||
webMediaSyncCompleted = Boolean(success) || webMediaSyncCompleted;
|
||||
}).catch(function () {
|
||||
webMediaSyncTriggered = false;
|
||||
});
|
||||
}
|
||||
}, DB_SYNC_INTERVAL_MS);
|
||||
});
|
||||
|
||||
socket.on('message', function (rawMessage) {
|
||||
handleThinClientCommand(socket, rawMessage).catch(function (error) {
|
||||
try {
|
||||
socket.send(JSON.stringify({
|
||||
type: 'command-response',
|
||||
requestId: null,
|
||||
ok: false,
|
||||
error: error && error.message ? error.message : 'Command failed.'
|
||||
}));
|
||||
} catch (_sendError) {
|
||||
// ignore send errors
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('close', function () {
|
||||
clearTimers();
|
||||
thinClientSocket = null;
|
||||
reconnectTimer = setTimeout(connect, 5000);
|
||||
});
|
||||
|
||||
socket.on('error', function () {
|
||||
try {
|
||||
socket.close();
|
||||
} catch (_error) {
|
||||
// ignore reconnect noise
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
connect();
|
||||
return function stop() {
|
||||
clearTimers();
|
||||
if (socket) {
|
||||
try {
|
||||
socket.close();
|
||||
} catch (_error) {
|
||||
// ignore close errors
|
||||
}
|
||||
socket = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
if (!isRemotePlayer) {
|
||||
logPlayerStartup({
|
||||
connected: false
|
||||
});
|
||||
}
|
||||
|
||||
const stopThinClientRegistration = startThinClientRegistration();
|
||||
|
||||
server.listen(PORT, function () {
|
||||
console.log(`Pulse Signage app listening on port ${PORT}`);
|
||||
});
|
||||
|
||||
async function syncDatabaseState() {
|
||||
if (isRemotePlayer) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await common.ensureSchema(pool, { mediaDir: MEDIA_DIR });
|
||||
await common.bootstrapDatabase(pool);
|
||||
await recordPlayerHeartbeat(pool, {
|
||||
deviceId: PLAYER_DEVICE_ID,
|
||||
publicBaseUrl: PLAYER_PUBLIC_URL,
|
||||
internalBaseUrl: PLAYER_INTERNAL_URL
|
||||
}).catch(function (error) {
|
||||
console.error(error);
|
||||
});
|
||||
|
||||
if (playerRuntime.snapshotAllConnections().length > 0) {
|
||||
await common.pruneStaleOnboardingDevices(pool);
|
||||
@@ -100,16 +429,27 @@ async function start() {
|
||||
|
||||
await syncDatabaseState();
|
||||
|
||||
if (PLAYER_IDENTIFIER) {
|
||||
if (PLAYER_DEVICE_ID && !isRemotePlayer) {
|
||||
const { upsertPlayerRegistration } = require('./player/onboarding');
|
||||
await upsertPlayerRegistration(pool, PLAYER_IDENTIFIER, PLAYER_PUBLIC_BASE_URL, PLAYER_INTERNAL_BASE_URL, null);
|
||||
await upsertPlayerRegistration(pool, PLAYER_DEVICE_ID, PLAYER_PUBLIC_URL, PLAYER_INTERNAL_URL).catch(function (error) {
|
||||
console.error(error);
|
||||
});
|
||||
}
|
||||
|
||||
setInterval(function () {
|
||||
if (isRemotePlayer) {
|
||||
return;
|
||||
}
|
||||
syncDatabaseState().catch(function (error) {
|
||||
console.error(error);
|
||||
});
|
||||
}, DB_SYNC_INTERVAL_MS);
|
||||
|
||||
process.on('exit', function () {
|
||||
if (typeof stopThinClientRegistration === 'function') {
|
||||
stopThinClientRegistration();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { start };
|
||||
|
||||
@@ -99,7 +99,6 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2.5rem;
|
||||
min-width: 100%;
|
||||
width: max-content;
|
||||
backface-visibility: hidden;
|
||||
will-change: transform;
|
||||
@@ -148,7 +147,7 @@
|
||||
transform: translate3d(0, 0, 0);
|
||||
}
|
||||
to {
|
||||
transform: translate3d(-50%, 0, 0);
|
||||
transform: translate3d(calc(-1 * var(--announcement-scroll-distance, 0px)), 0, 0);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -178,21 +177,10 @@
|
||||
}
|
||||
|
||||
var track = root.querySelector('.player-announcement__message-track');
|
||||
if (!track) {
|
||||
if (!track || typeof window.initPlayerAnnouncementMarquee !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (track.dataset.marqueeMeasured === 'true') {
|
||||
return;
|
||||
}
|
||||
|
||||
var rate = Number(track.getAttribute('data-announcement-marquee-rate') || 44) || 44;
|
||||
var singlePassWidth = Math.max(1, track.scrollWidth / 2);
|
||||
var durationSeconds = Math.max(8, singlePassWidth / rate);
|
||||
var durationValue = durationSeconds.toFixed(2) + 's';
|
||||
|
||||
track.dataset.marqueeMeasured = 'true';
|
||||
track.style.setProperty('--announcement-scroll-duration', durationValue);
|
||||
track.style.animationDuration = durationValue;
|
||||
window.initPlayerAnnouncementMarquee(track, { container: root.querySelector('.player-announcement__message') || root });
|
||||
}());
|
||||
</script>
|
||||
@@ -101,7 +101,6 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2.5rem;
|
||||
min-width: 100%;
|
||||
width: max-content;
|
||||
backface-visibility: hidden;
|
||||
will-change: transform;
|
||||
@@ -150,7 +149,7 @@
|
||||
transform: translate3d(0, 0, 0);
|
||||
}
|
||||
to {
|
||||
transform: translate3d(-50%, 0, 0);
|
||||
transform: translate3d(calc(-1 * var(--announcement-scroll-distance, 0px)), 0, 0);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -180,21 +179,10 @@
|
||||
}
|
||||
|
||||
var track = root.querySelector('.player-announcement__message-track');
|
||||
if (!track) {
|
||||
if (!track || typeof window.initPlayerAnnouncementMarquee !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (track.dataset.marqueeMeasured === 'true') {
|
||||
return;
|
||||
}
|
||||
|
||||
var rate = Number(track.getAttribute('data-announcement-marquee-rate') || 44) || 44;
|
||||
var singlePassWidth = Math.max(1, track.scrollWidth / 2);
|
||||
var durationSeconds = Math.max(8, singlePassWidth / rate);
|
||||
var durationValue = durationSeconds.toFixed(2) + 's';
|
||||
|
||||
track.dataset.marqueeMeasured = 'true';
|
||||
track.style.setProperty('--announcement-scroll-duration', durationValue);
|
||||
track.style.animationDuration = durationValue;
|
||||
window.initPlayerAnnouncementMarquee(track, { container: root.querySelector('.player-announcement__message') || root });
|
||||
}());
|
||||
</script>
|
||||
+134
-48
@@ -1,7 +1,10 @@
|
||||
// Player onboarding routes and signup flow helpers.
|
||||
|
||||
const express = require('express');
|
||||
const { isClientNameAvailable, withClientNameReservation } = require('#src/data/client-name-check');
|
||||
const { getSharedSecret, verifyPageAuthToken } = require('#src/request-auth');
|
||||
const { createStyledQrCodeSvg } = require('#src/data/qr-code');
|
||||
const { getSharedSecret, verifyPageAuthToken, createRequestAuthHeaders } = require('#src/request-auth');
|
||||
const { resolvePlayerRegistration, upsertPlayerRegistration: upsertPlayerRegistrationRecord } = require('#src/data/player-registry');
|
||||
const { isTransientDbError } = require('./store');
|
||||
|
||||
const ONBOARDING_SIGNUP_LIMIT_WINDOW_MS = 5 * 60 * 1000;
|
||||
@@ -13,7 +16,7 @@ function normalizeDeviceId(value) {
|
||||
}
|
||||
|
||||
function getPublicBaseUrl(req, configuredUrl) {
|
||||
const configured = String(configuredUrl || process.env.PLAYER_PUBLIC_BASE_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, '');
|
||||
const configured = String(configuredUrl || process.env.PLAYER_PUBLIC_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, '');
|
||||
if (configured) {
|
||||
return configured;
|
||||
}
|
||||
@@ -47,7 +50,7 @@ function getPlayerPublicBaseUrl(req, configuredUrl) {
|
||||
}
|
||||
|
||||
function getPlayerInternalBaseUrl(configuredUrl) {
|
||||
const configured = String(configuredUrl || process.env.PLAYER_INTERNAL_BASE_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, '');
|
||||
const configured = String(configuredUrl || process.env.PLAYER_INTERNAL_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, '');
|
||||
return configured || null;
|
||||
}
|
||||
|
||||
@@ -132,7 +135,7 @@ async function commitDeviceBinding(pool, deviceId, clientName, screenSlug, isNam
|
||||
});
|
||||
}
|
||||
|
||||
async function upsertPlayerRegistration(pool, deviceId, publicBaseUrl, internalBaseUrl, screenSlug) {
|
||||
async function upsertPlayerRegistration(pool, deviceId, publicBaseUrl, internalBaseUrl) {
|
||||
const normalizedDeviceId = normalizeDeviceId(deviceId);
|
||||
const normalizedPublicBaseUrl = String(publicBaseUrl || '').trim().replace(/\/$/, '');
|
||||
const normalizedInternalBaseUrl = String(internalBaseUrl || '').trim().replace(/\/$/, '');
|
||||
@@ -140,18 +143,11 @@ async function upsertPlayerRegistration(pool, deviceId, publicBaseUrl, internalB
|
||||
return null;
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
`INSERT INTO d_players (device_id, public_base_url, internal_base_url, last_seen_at)
|
||||
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
|
||||
ON DUPLICATE KEY UPDATE public_base_url = VALUES(public_base_url), internal_base_url = VALUES(internal_base_url), last_seen_at = CURRENT_TIMESTAMP, modified_at = CURRENT_TIMESTAMP`,
|
||||
[normalizedDeviceId, normalizedPublicBaseUrl || null, normalizedInternalBaseUrl || null]
|
||||
);
|
||||
|
||||
return {
|
||||
device_id: normalizedDeviceId,
|
||||
public_base_url: normalizedPublicBaseUrl || null,
|
||||
internal_base_url: normalizedInternalBaseUrl || null
|
||||
};
|
||||
return upsertPlayerRegistrationRecord(pool, {
|
||||
identifier: normalizedDeviceId,
|
||||
publicBaseUrl: normalizedPublicBaseUrl || null,
|
||||
internalBaseUrl: normalizedInternalBaseUrl || null
|
||||
});
|
||||
}
|
||||
|
||||
async function bindPlayerToScreen(pool, deviceId, screenSlug) {
|
||||
@@ -166,25 +162,9 @@ async function bindPlayerToScreen(pool, deviceId, screenSlug) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const screenId = Number(screenRows[0].id);
|
||||
const connection = await pool.getConnection();
|
||||
try {
|
||||
await connection.beginTransaction();
|
||||
// Current model: every screen binds to the shared player row '1'.
|
||||
// If we introduce multiple players, resolve the correct player row here instead of hardcoding it.
|
||||
await connection.query("UPDATE d_screens SET player_id = '1', modified_at = CURRENT_TIMESTAMP WHERE id = ?", [screenId]);
|
||||
await connection.commit();
|
||||
} catch (error) {
|
||||
await connection.rollback();
|
||||
throw error;
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
|
||||
return {
|
||||
screen_id: screenId,
|
||||
screen_slug: normalizedScreenSlug,
|
||||
player_id: '1'
|
||||
screen_id: Number(screenRows[0].id),
|
||||
screen_slug: normalizedScreenSlug
|
||||
};
|
||||
}
|
||||
|
||||
@@ -222,15 +202,67 @@ function registerPlayerOnboardingRoutes(app, options) {
|
||||
const pool = options && options.pool ? options.pool : null;
|
||||
const common = options && options.common ? options.common : null;
|
||||
const playerRuntime = options && options.playerRuntime ? options.playerRuntime : null;
|
||||
const QRCode = options && options.QRCode ? options.QRCode : null;
|
||||
const onboardingStore = options && options.onboardingStore ? options.onboardingStore : null;
|
||||
const playerPublicUrl = String(options && options.playerPublicBaseUrl || process.env.PLAYER_PUBLIC_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, '');
|
||||
const bridgeBaseUrl = String(options && options.bridgeBaseUrl || process.env.BRIDGE_PUBLIC_URL || '').trim().replace(/\/$/, '');
|
||||
const playerDeviceId = normalizeDeviceId(options && options.playerDeviceId);
|
||||
|
||||
if (!app || !pool || !common || !playerRuntime || !QRCode) {
|
||||
throw new Error('registerPlayerOnboardingRoutes requires app, pool, common, playerRuntime, and QRCode.');
|
||||
if (!app || !common) {
|
||||
throw new Error('registerPlayerOnboardingRoutes requires app and common.');
|
||||
}
|
||||
|
||||
if (!bridgeBaseUrl && (!pool || !playerRuntime)) {
|
||||
throw new Error('registerPlayerOnboardingRoutes requires pool and playerRuntime unless bridgeBaseUrl is configured.');
|
||||
}
|
||||
|
||||
const sharedSecret = getSharedSecret();
|
||||
|
||||
async function fetchThinClient(req, pathname, options) {
|
||||
if (!bridgeBaseUrl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const requestOptions = options && typeof options === 'object' ? options : {};
|
||||
const method = String(requestOptions.method || req.method || 'GET').trim().toUpperCase();
|
||||
const body = Object.prototype.hasOwnProperty.call(requestOptions, 'body') ? requestOptions.body : undefined;
|
||||
const requestPathname = String(pathname || '').split('?')[0];
|
||||
const headers = Object.assign({}, requestOptions.headers || {}, createRequestAuthHeaders({
|
||||
method: method,
|
||||
pathname: requestPathname,
|
||||
body: body
|
||||
}));
|
||||
|
||||
if (req.headers['x-pulse-page-auth']) {
|
||||
headers['x-pulse-page-auth'] = String(req.headers['x-pulse-page-auth']).trim();
|
||||
}
|
||||
if (requestOptions.contentType) {
|
||||
headers['content-type'] = requestOptions.contentType;
|
||||
}
|
||||
|
||||
return fetch(new URL(pathname, bridgeBaseUrl).toString(), {
|
||||
method: method,
|
||||
headers: headers,
|
||||
body: body === undefined || body === null || method === 'GET' || method === 'HEAD' ? undefined : body
|
||||
});
|
||||
}
|
||||
|
||||
async function readJsonResponse(response) {
|
||||
if (!response) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const contentType = String(response.headers && typeof response.headers.get === 'function' ? response.headers.get('content-type') : '').toLowerCase();
|
||||
if (contentType.indexOf('application/json') === -1 && contentType.indexOf('+json') === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return await response.json();
|
||||
} catch (_error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function requireOnboardingPageAuth(req, res, next) {
|
||||
if (!sharedSecret) {
|
||||
return next();
|
||||
@@ -254,7 +286,7 @@ function registerPlayerOnboardingRoutes(app, options) {
|
||||
app.get('/onboard', async function (req, res, next) {
|
||||
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
|
||||
try {
|
||||
res.send(common.renderPlayerOnboardingFormPage(String(req.query.deviceId || '').trim()));
|
||||
res.send(common.renderPlayerOnboardingFormPage(String(req.query.deviceId || playerDeviceId || '').trim()));
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -272,15 +304,32 @@ function registerPlayerOnboardingRoutes(app, options) {
|
||||
next();
|
||||
}, async function (req, res, next) {
|
||||
try {
|
||||
const status = await getOnboardingStatus(pool, req.query.deviceId);
|
||||
const deviceId = normalizeDeviceId(req.query.deviceId) || playerDeviceId;
|
||||
if (bridgeBaseUrl) {
|
||||
const response = await fetchThinClient(req, '/api/onboarding/status?deviceId=' + encodeURIComponent(deviceId || ''), {
|
||||
method: 'GET'
|
||||
});
|
||||
if (!response) {
|
||||
return res.status(502).json({ error: 'Player bridge unavailable.' });
|
||||
}
|
||||
res.status(response.status);
|
||||
const payload = await readJsonResponse(response);
|
||||
if (!payload) {
|
||||
return res.status(502).json({ error: 'Player bridge returned an invalid response.' });
|
||||
}
|
||||
payload.playerUrl = payload && payload.screenSlug ? `${getPublicBaseUrl(req, playerPublicUrl)}/screen/${encodeURIComponent(payload.screenSlug)}` : null;
|
||||
return res.json(payload);
|
||||
}
|
||||
|
||||
const status = await getOnboardingStatus(pool, deviceId);
|
||||
res.json({
|
||||
deviceId: normalizeDeviceId(req.query.deviceId),
|
||||
deviceId: normalizeDeviceId(deviceId),
|
||||
onboarded: Boolean(status && status.screen_id),
|
||||
clientName: status ? status.client_name : null,
|
||||
screenId: status ? status.screen_id : null,
|
||||
screenSlug: status ? status.screen_slug : null,
|
||||
screenName: status ? status.screen_name : null,
|
||||
playerUrl: status && status.screen_slug ? `${getPublicBaseUrl(req)}/screen/${encodeURIComponent(status.screen_slug)}` : null
|
||||
playerUrl: status && status.screen_slug ? `${getPublicBaseUrl(req, playerPublicUrl)}/screen/${encodeURIComponent(status.screen_slug)}` : null
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
@@ -289,6 +338,16 @@ function registerPlayerOnboardingRoutes(app, options) {
|
||||
|
||||
app.get('/api/onboarding/screens', requireOnboardingPageAuth, async function (_req, res, next) {
|
||||
try {
|
||||
if (bridgeBaseUrl) {
|
||||
const response = await fetchThinClient(_req, '/api/onboarding/screens', {
|
||||
method: 'GET'
|
||||
});
|
||||
res.status(response.status);
|
||||
const text = await response.text();
|
||||
res.type(response.headers.get('content-type') || 'application/json');
|
||||
return res.send(text);
|
||||
}
|
||||
|
||||
const [rows] = await pool.query('SELECT id, name, slug FROM d_screens ORDER BY name ASC, id ASC');
|
||||
res.json({ screens: rows });
|
||||
} catch (error) {
|
||||
@@ -298,12 +357,12 @@ function registerPlayerOnboardingRoutes(app, options) {
|
||||
|
||||
app.get('/api/onboarding/qr', async function (req, res, next) {
|
||||
try {
|
||||
const deviceId = normalizeDeviceId(req.query.deviceId);
|
||||
const deviceId = normalizeDeviceId(req.query.deviceId) || playerDeviceId;
|
||||
if (!deviceId) {
|
||||
return res.status(400).json({ error: 'Device ID is required' });
|
||||
}
|
||||
const onboardingUrl = `${getPublicBaseUrl(req, options && options.playerPublicBaseUrl)}/onboard?deviceId=${encodeURIComponent(deviceId)}`;
|
||||
const svg = await QRCode.toString(onboardingUrl, { type: 'svg', margin: 1, errorCorrectionLevel: 'M' });
|
||||
const onboardingUrl = `${getPublicBaseUrl(req, playerPublicUrl)}/onboard?deviceId=${encodeURIComponent(deviceId)}`;
|
||||
const svg = await createStyledQrCodeSvg({ value: onboardingUrl, qr_margin: 20 });
|
||||
res.set('Content-Type', 'image/svg+xml; charset=utf-8');
|
||||
res.set('Cache-Control', 'no-store');
|
||||
res.send(svg);
|
||||
@@ -312,9 +371,9 @@ function registerPlayerOnboardingRoutes(app, options) {
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/onboarding', requireOnboardingPageAuth, async function (req, res, next) {
|
||||
app.post('/api/onboarding', requireOnboardingPageAuth, express.json(), async function (req, res, next) {
|
||||
try {
|
||||
const deviceId = normalizeDeviceId(req.body && req.body.deviceId);
|
||||
const deviceId = normalizeDeviceId(req.body && req.body.deviceId) || playerDeviceId;
|
||||
const clientName = String((req.body && req.body.clientName) || '').trim();
|
||||
const screenSlug = String((req.body && req.body.screenSlug) || '').trim();
|
||||
const retryAfterSeconds = isOnboardingSignupRateLimited(req, deviceId);
|
||||
@@ -322,6 +381,30 @@ function registerPlayerOnboardingRoutes(app, options) {
|
||||
res.set('Retry-After', String(retryAfterSeconds));
|
||||
return res.status(429).json({ error: 'Too many onboarding attempts. Please try again later.' });
|
||||
}
|
||||
|
||||
if (bridgeBaseUrl) {
|
||||
const forwardedBody = Object.assign({}, req.body || {}, {
|
||||
deviceId: deviceId
|
||||
});
|
||||
const response = await fetch(new URL('/api/onboarding', bridgeBaseUrl).toString(), {
|
||||
method: 'POST',
|
||||
headers: Object.assign({
|
||||
'content-type': 'application/json'
|
||||
}, createRequestAuthHeaders({
|
||||
method: 'POST',
|
||||
pathname: '/api/onboarding',
|
||||
body: forwardedBody
|
||||
}), req.headers['x-pulse-page-auth'] ? { 'x-pulse-page-auth': String(req.headers['x-pulse-page-auth']).trim() } : {}),
|
||||
body: JSON.stringify(forwardedBody)
|
||||
});
|
||||
res.status(response.status);
|
||||
const payload = await readJsonResponse(response);
|
||||
if (!payload) {
|
||||
return res.status(502).json({ error: 'Player bridge returned an invalid response.' });
|
||||
}
|
||||
payload.playerUrl = payload && payload.screenSlug ? `${getPublicBaseUrl(req, playerPublicUrl)}/screen/${encodeURIComponent(payload.screenSlug)}` : `${getPublicBaseUrl(req, playerPublicUrl)}/screen/${encodeURIComponent(screenSlug)}`;
|
||||
return res.json(payload);
|
||||
}
|
||||
if (!deviceId) {
|
||||
return res.status(400).json({ error: 'Device ID is required' });
|
||||
}
|
||||
@@ -340,11 +423,14 @@ function registerPlayerOnboardingRoutes(app, options) {
|
||||
screenId: status && status.screen_id ? status.screen_id : null,
|
||||
screenSlug: status ? status.screen_slug : screenSlug,
|
||||
screenName: status && status.screen_name ? status.screen_name : null,
|
||||
playerUrl: status && status.screen_slug ? `${getPublicBaseUrl(req)}/screen/${encodeURIComponent(status.screen_slug)}` : `${getPublicBaseUrl(req)}/screen/${encodeURIComponent(screenSlug)}`,
|
||||
playerUrl: status && status.screen_slug ? `${getPublicBaseUrl(req, playerPublicUrl)}/screen/${encodeURIComponent(status.screen_slug)}` : `${getPublicBaseUrl(req, playerPublicUrl)}/screen/${encodeURIComponent(screenSlug)}`,
|
||||
queued: Boolean(status && status.queued)
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
const statusCode = Number(error && error.statusCode || error && error.status || 500);
|
||||
res.status(Number.isFinite(statusCode) && statusCode >= 400 ? statusCode : 500).json({
|
||||
error: error && error.message ? error.message : 'Onboarding failed.'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -7,6 +7,12 @@
|
||||
var form = document.getElementById("onboarding-form");
|
||||
var message = document.getElementById("onboarding-message");
|
||||
var screenSelect = document.getElementById("onboarding-screen-select");
|
||||
function getSessionStorageItem(key) {
|
||||
try { return window.sessionStorage.getItem(key) || ""; } catch (_error) { return ""; }
|
||||
}
|
||||
function setSessionStorageItem(key, value) {
|
||||
try { window.sessionStorage.setItem(key, value); } catch (_error) {}
|
||||
}
|
||||
function setMessage(value) { if (message) { message.textContent = value || ""; } }
|
||||
function parseResponseError(response) {
|
||||
return response.text().then(function (text) {
|
||||
@@ -39,11 +45,17 @@
|
||||
return screens;
|
||||
});
|
||||
}
|
||||
if (!deviceId) { setMessage("Missing device id. Scan the QR code from the player screen again."); return; }
|
||||
try { window.localStorage.setItem(deviceKey, deviceId); } catch (_error) {}
|
||||
try {
|
||||
if (!deviceId) {
|
||||
deviceId = window.sessionStorage.getItem(deviceKey) || "";
|
||||
}
|
||||
if (deviceId) {
|
||||
window.sessionStorage.setItem(deviceKey, deviceId);
|
||||
}
|
||||
} catch (_error) {}
|
||||
loadScreens().then(function () {
|
||||
try {
|
||||
var storedClientName = window.localStorage.getItem(clientNameKey) || "";
|
||||
var storedClientName = getSessionStorageItem(clientNameKey) || "";
|
||||
var storedScreenSlug = window.localStorage.getItem(screenKey) || "";
|
||||
var clientNameInput = form.querySelector("input[name=\"clientName\"]");
|
||||
if (clientNameInput && storedClientName) { clientNameInput.value = storedClientName; }
|
||||
@@ -58,10 +70,14 @@
|
||||
if (!clientName) { setMessage("Client name is required."); return; }
|
||||
if (!screenSlug) { setMessage("Screen is required."); return; }
|
||||
setMessage("Saving client...");
|
||||
var payload = { clientName: clientName, screenSlug: screenSlug };
|
||||
if (deviceId) {
|
||||
payload.deviceId = deviceId;
|
||||
}
|
||||
fetch("/api/onboarding", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
||||
body: JSON.stringify({ deviceId: deviceId, clientName: clientName, screenSlug: screenSlug })
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
.then(function (response) {
|
||||
if (response.ok) {
|
||||
@@ -73,7 +89,7 @@
|
||||
})
|
||||
.then(function (payload) {
|
||||
if (!payload || !payload.screenSlug) { throw new Error("Unable to save onboarding."); }
|
||||
if (payload.clientName) { try { window.localStorage.setItem(clientNameKey, payload.clientName); } catch (_error) {} }
|
||||
if (payload.clientName) { setSessionStorageItem(clientNameKey, payload.clientName); }
|
||||
try { window.localStorage.setItem(screenKey, payload.screenSlug); } catch (_error) {}
|
||||
setMessage("Onboarding complete.");
|
||||
if (form) {
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
(function () {
|
||||
var deviceKey = "pulse-signage-player-device-id";
|
||||
var clientNameKey = "pulse-signage-player-client-name";
|
||||
function getSessionStorageItem(key) {
|
||||
try { return window.sessionStorage.getItem(key) || ""; } catch (_error) { return ""; }
|
||||
}
|
||||
function setSessionStorageItem(key, value) {
|
||||
try { window.sessionStorage.setItem(key, value); } catch (_error) {}
|
||||
}
|
||||
function getClientNameStorageKey(_screenSlug) {
|
||||
return clientNameKey;
|
||||
}
|
||||
@@ -11,6 +17,7 @@
|
||||
var localForm = document.getElementById("onboarding-local-form");
|
||||
var localMessage = document.getElementById("onboarding-message");
|
||||
var localScreenSelect = document.getElementById("onboarding-screen-select");
|
||||
var qrPlaceholderSrc = "data:image/svg+xml;charset=utf-8,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 320 320%22%3E%3Crect width=%22320%22 height=%22320%22 rx=%2224%22 fill=%22%23ffffff%22/%3E%3Crect x=%2230%22 y=%2230%22 width=%22260%22 height=%22260%22 rx=%2218%22 fill=%22%23f8fafc%22 stroke=%22%23cbd5e1%22 stroke-width=%223%22 stroke-dasharray=%2212 10%22/%3E%3Cpath d=%22M106 118h108M106 156h108M106 194h72%22 stroke=%22%2394a3b8%22 stroke-width=%2214%22 stroke-linecap=%22round%22/%3E%3Ccircle cx=%22128%22 cy=%22248%22 r=%2212%22 fill=%22%2394a3b8%22/%3E%3Ctext x=%22160%22 y=%2278%22 text-anchor=%22middle%22 fill=%22%230f172a%22 font-family=%22Arial,sans-serif%22 font-size=%2224%22 font-weight=%22700%22%3EQR code loading%3C/text%3E%3Ctext x=%22160%22 y=%22266%22 text-anchor=%22middle%22 fill=%22%234b5563%22 font-family=%22Arial,sans-serif%22 font-size=%2214%22%3EPlease wait%3C/text%3E%3C/svg%3E";
|
||||
function parseResponseError(response) {
|
||||
return response.text().then(function (text) {
|
||||
var fallbackMessage = text && text.trim() ? text.trim() : "Unable to save onboarding.";
|
||||
@@ -24,10 +31,10 @@
|
||||
}
|
||||
function getDeviceId() {
|
||||
var stored = "";
|
||||
try { stored = window.localStorage.getItem(deviceKey) || ""; } catch (_error) { stored = ""; }
|
||||
try { stored = window.sessionStorage.getItem(deviceKey) || ""; } catch (_error) { stored = ""; }
|
||||
if (stored) { return stored; }
|
||||
var next = (window.crypto && window.crypto.randomUUID ? window.crypto.randomUUID() : "device-" + Date.now() + "-" + Math.random().toString(16).slice(2));
|
||||
try { window.localStorage.setItem(deviceKey, next); } catch (_error2) {}
|
||||
try { window.sessionStorage.setItem(deviceKey, next); } catch (_error2) {}
|
||||
return next;
|
||||
}
|
||||
function setStatus(message) { if (status) { status.textContent = message; } }
|
||||
@@ -60,7 +67,11 @@
|
||||
.catch(function () { setSelectOptions(localScreenSelect, [], selectedSlug); return []; });
|
||||
}
|
||||
function loadQr(deviceId) {
|
||||
if (qr) { qr.src = "/api/onboarding/qr?deviceId=" + encodeURIComponent(deviceId); }
|
||||
if (!qr) { return; }
|
||||
qr.onerror = function () {
|
||||
qr.src = qrPlaceholderSrc;
|
||||
};
|
||||
qr.src = "/api/onboarding/qr?deviceId=" + encodeURIComponent(deviceId);
|
||||
}
|
||||
function submitOnboarding(deviceId, clientName, screenSlug) {
|
||||
return fetch("/api/onboarding", {
|
||||
@@ -78,8 +89,8 @@
|
||||
})
|
||||
.then(function (payload) {
|
||||
if (!payload || !payload.screenSlug) { throw new Error("Unable to save onboarding."); }
|
||||
if (payload.clientName) { try { window.localStorage.setItem(clientNameKey, payload.clientName); } catch (_error) {} }
|
||||
if (payload.clientName && payload.screenSlug) { try { window.localStorage.setItem(getClientNameStorageKey(payload.screenSlug), payload.clientName); } catch (_error2) {} }
|
||||
if (payload.clientName) { setSessionStorageItem(clientNameKey, payload.clientName); }
|
||||
if (payload.clientName && payload.screenSlug) { setSessionStorageItem(getClientNameStorageKey(payload.screenSlug), payload.clientName); }
|
||||
try { window.localStorage.setItem(screenKey, payload.screenSlug); } catch (_error) {}
|
||||
setLocalMessage("Onboarding complete.");
|
||||
if (localForm) {
|
||||
@@ -94,8 +105,8 @@
|
||||
.then(function (response) { return response.ok ? response.json() : null; })
|
||||
.then(function (payload) {
|
||||
if (payload && payload.onboarded && payload.screenSlug) {
|
||||
if (payload.clientName) { try { window.localStorage.setItem(clientNameKey, payload.clientName); } catch (_error) {} }
|
||||
if (payload.clientName && payload.screenSlug) { try { window.localStorage.setItem(getClientNameStorageKey(payload.screenSlug), payload.clientName); } catch (_error2) {} }
|
||||
if (payload.clientName) { setSessionStorageItem(clientNameKey, payload.clientName); }
|
||||
if (payload.clientName && payload.screenSlug) { setSessionStorageItem(getClientNameStorageKey(payload.screenSlug), payload.clientName); }
|
||||
try { window.localStorage.setItem(screenKey, payload.screenSlug); } catch (_error) {}
|
||||
window.location.replace("/screen/" + encodeURIComponent(payload.screenSlug));
|
||||
return true;
|
||||
@@ -122,17 +133,20 @@
|
||||
loadScreens().then(function () {
|
||||
try {
|
||||
var storedScreenSlug = window.localStorage.getItem(screenKey) || "";
|
||||
var storedClientName = window.localStorage.getItem(clientNameKey) || "";
|
||||
if (!storedClientName && storedScreenSlug) { storedClientName = window.localStorage.getItem(getClientNameStorageKey(storedScreenSlug)) || ""; }
|
||||
var storedClientName = getSessionStorageItem(clientNameKey) || "";
|
||||
if (!storedClientName && storedScreenSlug) { storedClientName = getSessionStorageItem(getClientNameStorageKey(storedScreenSlug)) || ""; }
|
||||
if (storedClientName && localForm) {
|
||||
var clientNameInput = localForm.querySelector("input[name=\"clientName\"]");
|
||||
if (clientNameInput && !clientNameInput.value) { clientNameInput.value = storedClientName; }
|
||||
if (clientNameInput) { clientNameInput.value = storedClientName; }
|
||||
}
|
||||
if (storedScreenSlug && localScreenSelect) { localScreenSelect.value = storedScreenSlug; }
|
||||
} catch (_error) {}
|
||||
});
|
||||
redirectIfOnboarded(deviceId).then(function (redirected) {
|
||||
if (redirected) { return; }
|
||||
if (qr && !qr.getAttribute("src")) {
|
||||
qr.src = qrPlaceholderSrc;
|
||||
}
|
||||
loadQr(deviceId);
|
||||
setStatus("Waiting for onboarding to finish.");
|
||||
window.setInterval(function () { redirectIfOnboarded(deviceId); }, 2000);
|
||||
|
||||
@@ -4,9 +4,25 @@
|
||||
const onboardingClientNameStorageKey = 'pulse-signage-player-client-name';
|
||||
const onboardingDeviceIdStorageKey = 'pulse-signage-player-device-id';
|
||||
|
||||
function getSessionStorageItem(key) {
|
||||
try {
|
||||
return window.sessionStorage.getItem(key) || '';
|
||||
} catch (_error) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function setSessionStorageItem(key, value) {
|
||||
try {
|
||||
window.sessionStorage.setItem(key, value);
|
||||
} catch (_error) {
|
||||
// ignore storage errors
|
||||
}
|
||||
}
|
||||
|
||||
function getOnboardingDeviceId() {
|
||||
try {
|
||||
var storedDeviceId = window.localStorage.getItem(onboardingDeviceIdStorageKey) || '';
|
||||
var storedDeviceId = getSessionStorageItem(onboardingDeviceIdStorageKey);
|
||||
return String(storedDeviceId || '').trim();
|
||||
} catch (_error) {
|
||||
return '';
|
||||
@@ -19,24 +35,14 @@
|
||||
return onboardingClientName;
|
||||
}
|
||||
try {
|
||||
var storedClientName = window.localStorage.getItem(onboardingClientNameStorageKey);
|
||||
var storedClientName = getSessionStorageItem(onboardingClientNameStorageKey);
|
||||
if (storedClientName) {
|
||||
onboardingClientName = storedClientName;
|
||||
try {
|
||||
window.localStorage.setItem('pulse-signage-player-client-name', storedClientName);
|
||||
} catch (_mirrorError) {
|
||||
// ignore storage errors
|
||||
}
|
||||
return onboardingClientName;
|
||||
}
|
||||
var genericClientName = window.localStorage.getItem('pulse-signage-player-client-name');
|
||||
var genericClientName = getSessionStorageItem('pulse-signage-player-client-name');
|
||||
if (genericClientName) {
|
||||
onboardingClientName = genericClientName;
|
||||
try {
|
||||
window.localStorage.setItem(onboardingClientNameStorageKey, genericClientName);
|
||||
} catch (_error) {
|
||||
// ignore storage errors
|
||||
}
|
||||
return onboardingClientName;
|
||||
}
|
||||
} catch (_error) {
|
||||
@@ -51,12 +57,8 @@
|
||||
return;
|
||||
}
|
||||
onboardingClientName = normalizedName;
|
||||
try {
|
||||
window.localStorage.setItem('pulse-signage-player-client-name', normalizedName);
|
||||
window.localStorage.setItem(onboardingClientNameStorageKey, normalizedName);
|
||||
} catch (_error) {
|
||||
// ignore storage errors
|
||||
}
|
||||
setSessionStorageItem('pulse-signage-player-client-name', normalizedName);
|
||||
setSessionStorageItem(onboardingClientNameStorageKey, normalizedName);
|
||||
if (socket && socket.readyState === WebSocket.OPEN) {
|
||||
sendCommandState(socket);
|
||||
}
|
||||
|
||||
+34
-4
@@ -3,6 +3,7 @@
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { createStyledQrCodeDataUrl } = require('../data/qr-code');
|
||||
|
||||
function createPlayerPlaylistService(options) {
|
||||
const pool = options && options.pool ? options.pool : null;
|
||||
@@ -56,6 +57,10 @@ function createPlayerPlaylistService(options) {
|
||||
await fs.promises.writeFile(filePath, JSON.stringify(payload, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
async function createQrPreviewDataUrl(value) {
|
||||
return createStyledQrCodeDataUrl(value);
|
||||
}
|
||||
|
||||
async function buildScreenPlaylist(slug) {
|
||||
try {
|
||||
const [screenRows] = await pool.query('SELECT id, name, slug, playlist_id, created_at, modified_at, created_by, modified_by FROM d_screens WHERE slug = ?', [slug]);
|
||||
@@ -139,23 +144,27 @@ function createPlayerPlaylistService(options) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const videoRegion = Object.keys(parsed).map(function (key) { return parsed[key]; }).find(function (region) {
|
||||
const videoRegions = Object.keys(parsed).map(function (key) { return parsed[key]; }).filter(function (region) {
|
||||
return region && typeof region === 'object' && String(region.type || '').trim().toLowerCase() === 'video' && Number(region.duration_seconds || 0) > 0;
|
||||
});
|
||||
|
||||
const duration = Math.round(Number(videoRegion && videoRegion.duration_seconds || 0) * 1000) / 1000;
|
||||
const duration = videoRegions.reduce(function (longest, region) {
|
||||
const regionDuration = Math.round(Number(region.duration_seconds || 0) * 1000) / 1000;
|
||||
return regionDuration > longest ? regionDuration : longest;
|
||||
}, 0);
|
||||
return Number.isFinite(duration) && duration > 0 ? duration : null;
|
||||
} catch (_error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const slides = slideRows.map(function (slide) {
|
||||
const slides = await Promise.all(slideRows.map(async function (slide) {
|
||||
const storedDuration = Number(slide.duration_seconds || 0);
|
||||
const videoDuration = slide.use_video_duration ? getVideoRegionDurationSeconds(slide.content_json) : null;
|
||||
const disableAudio = slide.disable_audio === undefined || slide.disable_audio === null ? true : Boolean(slide.disable_audio);
|
||||
const videoCacheBust = String(slide.modified_at || slide.content_json || slide.id || '');
|
||||
const content = common.parseJsonSafe(slide.content_json) || {};
|
||||
const qrBackfillTasks = [];
|
||||
Object.keys(content).forEach(function (key) {
|
||||
const region = content[key];
|
||||
if (region && typeof region === 'object') {
|
||||
@@ -168,6 +177,27 @@ function createPlayerPlaylistService(options) {
|
||||
region.cache_bust = videoCacheBust;
|
||||
}
|
||||
});
|
||||
|
||||
Object.keys(content).forEach(function (key) {
|
||||
const region = content[key];
|
||||
if (!region || typeof region !== 'object' || String(region.type || '').trim().toLowerCase() !== 'qr-code') {
|
||||
return;
|
||||
}
|
||||
|
||||
if (region.qr_preview && /^data:image\//i.test(String(region.qr_preview || '').trim())) {
|
||||
return;
|
||||
}
|
||||
|
||||
qrBackfillTasks.push(createQrPreviewDataUrl(region.value).then(function (preview) {
|
||||
if (preview) {
|
||||
region.qr_preview = preview;
|
||||
}
|
||||
return null;
|
||||
}).catch(function () {
|
||||
return null;
|
||||
}));
|
||||
});
|
||||
await Promise.all(qrBackfillTasks);
|
||||
return {
|
||||
id: slide.id,
|
||||
title: slide.title,
|
||||
@@ -180,7 +210,7 @@ function createPlayerPlaylistService(options) {
|
||||
template: slide.template_id ? templatesById[slide.template_id] || null : null,
|
||||
content: content
|
||||
};
|
||||
});
|
||||
}));
|
||||
|
||||
let rssFeeds = [];
|
||||
if (typeof common.fetchRssFeedsData === 'function' && typeof common.fetchRssFeedItemsByFeedId === 'function') {
|
||||
|
||||
@@ -116,6 +116,8 @@ body.thumbnail-preview .player-offline-banner {
|
||||
display: block;
|
||||
background: #fff;
|
||||
border-radius: 18px;
|
||||
padding: 16px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.onboarding-form {
|
||||
@@ -393,18 +395,6 @@ body.screen-blackout #app {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.template-region.text > *,
|
||||
.template-region.api > *,
|
||||
.template-region.rss > * {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.template-region.text > * + *,
|
||||
.template-region.api > * + *,
|
||||
.template-region.rss > * + * {
|
||||
margin-top: 0.5em;
|
||||
}
|
||||
|
||||
.template-region.text ul,
|
||||
.template-region.text ol,
|
||||
.template-region.api ul,
|
||||
@@ -443,6 +433,14 @@ body.screen-blackout #app {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.template-region.qr-code img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: contain;
|
||||
display: block;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.template-region.html iframe {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
|
||||
@@ -54,12 +54,68 @@
|
||||
});
|
||||
}
|
||||
|
||||
function getComputedGapWidth(track) {
|
||||
if (!track || !window.getComputedStyle) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
var computedStyle = window.getComputedStyle(track);
|
||||
var gapValue = String(computedStyle.columnGap || computedStyle.gap || '0').trim();
|
||||
var gap = Number.parseFloat(gapValue);
|
||||
return Number.isFinite(gap) ? gap : 0;
|
||||
}
|
||||
|
||||
function getElementWidth(element) {
|
||||
if (!element || !element.getBoundingClientRect) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return Math.max(0, element.getBoundingClientRect().width || 0);
|
||||
}
|
||||
|
||||
function initPlayerAnnouncementMarquee(track, options) {
|
||||
if (!track || track.dataset.marqueeMeasured === 'true') {
|
||||
return;
|
||||
}
|
||||
|
||||
var settings = options || {};
|
||||
var rate = Number(settings.rate || track.getAttribute('data-announcement-marquee-rate') || 44) || 44;
|
||||
var textSelector = String(settings.textSelector || '.player-announcement__message-text').trim() || '.player-announcement__message-text';
|
||||
var textNodes = Array.prototype.slice.call(track.querySelectorAll(textSelector));
|
||||
if (!textNodes.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
var container = settings.container || track.parentElement || track;
|
||||
var containerWidth = Math.max(1, getElementWidth(container) || 0);
|
||||
var gapWidth = getComputedGapWidth(track);
|
||||
var firstItemWidth = Math.max(1, getElementWidth(textNodes[0]) || 0);
|
||||
var cycleWidth = Math.max(1, firstItemWidth + gapWidth);
|
||||
var minimumTrackWidth = Math.max(containerWidth + cycleWidth, cycleWidth * 2);
|
||||
var cloneIndex = 0;
|
||||
|
||||
while (getElementWidth(track) < minimumTrackWidth && cloneIndex < 8) {
|
||||
var clone = textNodes[cloneIndex % textNodes.length].cloneNode(true);
|
||||
clone.setAttribute('aria-hidden', 'true');
|
||||
track.appendChild(clone);
|
||||
cloneIndex += 1;
|
||||
}
|
||||
|
||||
var durationSeconds = Math.max(8, cycleWidth / rate);
|
||||
var durationValue = durationSeconds.toFixed(2) + 's';
|
||||
|
||||
track.dataset.marqueeMeasured = 'true';
|
||||
track.style.setProperty('--announcement-scroll-distance', cycleWidth.toFixed(2) + 'px');
|
||||
track.style.setProperty('--announcement-scroll-duration', durationValue);
|
||||
track.style.animationDuration = durationValue;
|
||||
}
|
||||
|
||||
function renderPlayerAnnouncementMarkup(announcement) {
|
||||
var normalizedType = normalizeAnnouncementType(announcement && announcement.announcement_type);
|
||||
var colorKey = normalizeAnnouncementColor(announcement && announcement.color_key);
|
||||
var colorTokens = getAnnouncementColorTokens(colorKey);
|
||||
var iconKey = normalizeAnnouncementIcon(announcement && announcement.icon_key);
|
||||
var text = escapeHtml(String(announcement && announcement.message || '').trim()).replace(/\n/g, '<br />');
|
||||
var text = escapeHtml(String(announcement && announcement.message || '').trim()).replace(/[\r\n]+/g, ' ');
|
||||
var titleText = escapeHtml(String(announcement && announcement.short_label || 'Announcement').trim() || 'Announcement');
|
||||
var templates = window.playerAnnouncementTemplates || {};
|
||||
var templateName = normalizedType === 'fullscreen' ? 'fullscreen' : normalizedType === 'top-banner' ? 'topBanner' : 'lowerThird';
|
||||
@@ -77,4 +133,5 @@
|
||||
}
|
||||
|
||||
window.renderPlayerAnnouncementMarkup = renderPlayerAnnouncementMarkup;
|
||||
window.initPlayerAnnouncementMarquee = initPlayerAnnouncementMarquee;
|
||||
})();
|
||||
@@ -130,9 +130,10 @@ function scheduleSlideAdvance(delayMs) {
|
||||
slideExpiresAt = null;
|
||||
pausedRemainingMs = null;
|
||||
clearSlideOutroTimer();
|
||||
applyPendingPlaylistUpdate();
|
||||
const activeSlides = getCurrentActiveSlides();
|
||||
if (activeSlides.length < 2) {
|
||||
refresh();
|
||||
showCurrent();
|
||||
return;
|
||||
}
|
||||
if (index >= activeSlides.length) {
|
||||
@@ -262,20 +263,33 @@ function renderSlideMarkup(markup, shouldFade) {
|
||||
});
|
||||
}
|
||||
|
||||
function schedulePostRenderSetup(root, delayMs) {
|
||||
if (!root) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (root.isConnected === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof syncRtmpRegions === 'function') {
|
||||
syncRtmpRegions(root);
|
||||
}
|
||||
|
||||
if (!isThumbnailPreview()) {
|
||||
initializeRegionInstances(root);
|
||||
}
|
||||
|
||||
initializeRenderedVideoPlayback(root, delayMs);
|
||||
|
||||
if (typeof playRegionAnimations === 'function') {
|
||||
playRegionAnimations(root, 'intro');
|
||||
}
|
||||
}
|
||||
|
||||
if (!shouldFade) {
|
||||
app.innerHTML = markup;
|
||||
if (typeof syncRtmpRegions === 'function') {
|
||||
syncRtmpRegions(app);
|
||||
}
|
||||
if (!isThumbnailPreview()) {
|
||||
initializeRegionInstances(app);
|
||||
}
|
||||
initializeRenderedVideoPlayback(app);
|
||||
if (typeof playRegionAnimations === 'function') {
|
||||
window.requestAnimationFrame(function () {
|
||||
playRegionAnimations(app, 'intro');
|
||||
});
|
||||
}
|
||||
schedulePostRenderSetup(app, 0);
|
||||
return app.firstElementChild;
|
||||
}
|
||||
|
||||
@@ -324,11 +338,7 @@ function renderSlideMarkup(markup, shouldFade) {
|
||||
app.innerHTML = '';
|
||||
nextShell.style.opacity = '1';
|
||||
app.appendChild(nextShell);
|
||||
if (typeof syncRtmpRegions === 'function') {
|
||||
syncRtmpRegions(nextShell);
|
||||
}
|
||||
initializeRegionInstances(nextShell);
|
||||
initializeRenderedVideoPlayback(nextShell, slideFadeDurationMs / 2);
|
||||
schedulePostRenderSetup(nextShell, slideFadeDurationMs / 2);
|
||||
return nextShell;
|
||||
}
|
||||
|
||||
@@ -339,24 +349,12 @@ function renderSlideMarkup(markup, shouldFade) {
|
||||
pauseRenderedVideoPlayback(previousShell, slideFadeDurationMs / 2);
|
||||
|
||||
app.appendChild(nextShell);
|
||||
void nextShell.offsetHeight;
|
||||
window.requestAnimationFrame(function () {
|
||||
nextShell.style.opacity = '1';
|
||||
previousShell.style.opacity = '0';
|
||||
if (typeof playRegionAnimations === 'function') {
|
||||
playRegionAnimations(nextShell, 'intro');
|
||||
}
|
||||
schedulePostRenderSetup(nextShell, slideFadeDurationMs / 2);
|
||||
});
|
||||
|
||||
if (typeof syncRtmpRegions === 'function') {
|
||||
syncRtmpRegions(nextShell);
|
||||
}
|
||||
|
||||
if (!isThumbnailPreview()) {
|
||||
initializeRegionInstances(nextShell);
|
||||
}
|
||||
initializeRenderedVideoPlayback(nextShell, slideFadeDurationMs / 2);
|
||||
|
||||
slideTransitionTimer = window.setTimeout(function () {
|
||||
if (previousShell && previousShell.parentNode) {
|
||||
previousShell.parentNode.removeChild(previousShell);
|
||||
|
||||
@@ -54,6 +54,9 @@ async function renderSlideAtIndex(sourceSlides, targetIndex) {
|
||||
index = currentIndex;
|
||||
var markup = buildSlideMarkup(slide);
|
||||
renderSlideMarkup(markup, currentPlaylistFadeBetweenSlides);
|
||||
if (typeof scheduleSlideMarkupPreload === 'function') {
|
||||
scheduleSlideMarkupPreload(availableSlides, currentIndex);
|
||||
}
|
||||
sendCommandState(slide);
|
||||
if (!isPaused) {
|
||||
scheduleSlideAdvance(getSlideHoldDelay(Math.max(1, Number(slide.duration_seconds || 10)) * 1000));
|
||||
@@ -85,12 +88,14 @@ function applyPendingPlaylistUpdate() {
|
||||
// Render the current active slide or the empty state.
|
||||
function showCurrent() {
|
||||
clearSlideTimer();
|
||||
applyPendingPlaylistUpdate();
|
||||
const activeSlides = getCurrentActiveSlides();
|
||||
syncWebpagePreloads(activeSlides, index);
|
||||
if (typeof syncRtmpWarmups === 'function') {
|
||||
syncRtmpWarmups(activeSlides, index);
|
||||
}
|
||||
if (typeof scheduleSlideMarkupPreload === 'function') {
|
||||
scheduleSlideMarkupPreload(activeSlides, index);
|
||||
}
|
||||
if (!activeSlides.length) {
|
||||
renderEmpty(slides.length ? 'No slides are scheduled for this time.' : 'No slides assigned to this screen yet.');
|
||||
lastRenderedViewKey = getCurrentRenderKey(activeSlides);
|
||||
@@ -100,6 +105,16 @@ function showCurrent() {
|
||||
lastRenderedViewKey = getCurrentRenderKey(activeSlides);
|
||||
}
|
||||
|
||||
function isSlideInList(slide, slideList) {
|
||||
if (!slide || !Array.isArray(slideList)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return slideList.some(function (item) {
|
||||
return item && Number(item.id) === Number(slide.id);
|
||||
});
|
||||
}
|
||||
|
||||
// Skip the current slide when an RTMP feed is unavailable and the playlist asks for it.
|
||||
function handleRtmpPlaybackFailure(message, options) {
|
||||
if (!currentPlaylistSkipUnavailableRtmp) {
|
||||
@@ -166,6 +181,7 @@ function refresh() {
|
||||
const data = JSON.parse(request.responseText || '{}');
|
||||
const nextSignature = getPlaylistRevision(data);
|
||||
const nextSlides = Array.isArray(data.slides) ? data.slides.map(normalizeSlide) : [];
|
||||
const nextActiveSlides = getActiveSlidesFrom(nextSlides);
|
||||
const nextFadeBetweenSlides = Boolean(data && data.playlist && data.playlist.fade_between_slides);
|
||||
const nextSkipUnavailableRtmp = Boolean(data && data.playlist && data.playlist.skip_unavailable_rtmp);
|
||||
savePlaylistSnapshot({
|
||||
@@ -197,19 +213,26 @@ function refresh() {
|
||||
}
|
||||
return;
|
||||
}
|
||||
syncWebpagePreloads(getActiveSlidesFrom(nextSlides), index);
|
||||
syncWebpagePreloads(nextActiveSlides, index);
|
||||
if (typeof syncRtmpWarmups === 'function') {
|
||||
syncRtmpWarmups(getActiveSlidesFrom(nextSlides), index);
|
||||
syncRtmpWarmups(nextActiveSlides, index);
|
||||
}
|
||||
if (currentActiveSlides.length < 2) {
|
||||
slides = nextSlides;
|
||||
currentPlaylistSignature = nextSignature;
|
||||
currentPlaylistFadeBetweenSlides = nextFadeBetweenSlides;
|
||||
currentPlaylistSkipUnavailableRtmp = nextSkipUnavailableRtmp;
|
||||
pendingPlaylistUpdate = null;
|
||||
index = 0;
|
||||
if (typeof scheduleSlideMarkupPreload === 'function') {
|
||||
scheduleSlideMarkupPreload(nextActiveSlides, index);
|
||||
}
|
||||
if (nextActiveSlides.length < 2) {
|
||||
pendingPlaylistUpdate = {
|
||||
slides: nextSlides,
|
||||
signature: nextSignature,
|
||||
fadeBetweenSlides: nextFadeBetweenSlides,
|
||||
skipUnavailableRtmp: nextSkipUnavailableRtmp
|
||||
};
|
||||
if (!isSlideInList(lastRenderedSlide, nextSlides)) {
|
||||
applyPendingPlaylistUpdate();
|
||||
showCurrent();
|
||||
sendCommandState(lastRenderedSlide);
|
||||
return;
|
||||
}
|
||||
logDebug('Playlist update detected; applying on next slide transition.');
|
||||
return;
|
||||
}
|
||||
pendingPlaylistUpdate = {
|
||||
|
||||
@@ -84,7 +84,7 @@ function getCurrentRenderKey(activeSlides) {
|
||||
return [currentPlaylistSignature || '', viewportKey, 'slide', slide && slide.id ? slide.id : ''].join('|');
|
||||
}
|
||||
|
||||
// Pick the current slide and the next slide for webpage preloading.
|
||||
// Pick the next slide for webpage preloading.
|
||||
function getWebpagePreloadSlides(sourceSlides, targetIndex) {
|
||||
const availableSlides = Array.isArray(sourceSlides) ? sourceSlides : [];
|
||||
if (!availableSlides.length) {
|
||||
@@ -97,19 +97,71 @@ function getWebpagePreloadSlides(sourceSlides, targetIndex) {
|
||||
}
|
||||
|
||||
const preloadSlides = [];
|
||||
const currentSlide = availableSlides[normalizedIndex];
|
||||
const nextSlide = availableSlides[normalizedIndex + 1];
|
||||
|
||||
if (currentSlide) {
|
||||
preloadSlides.push(currentSlide);
|
||||
}
|
||||
if (nextSlide && nextSlide !== currentSlide) {
|
||||
if (nextSlide) {
|
||||
preloadSlides.push(nextSlide);
|
||||
}
|
||||
|
||||
return preloadSlides;
|
||||
}
|
||||
|
||||
// Pick the next slide to warm its markup before it becomes visible.
|
||||
function getSlideMarkupPreloadSlides(sourceSlides, targetIndex) {
|
||||
const availableSlides = Array.isArray(sourceSlides) ? sourceSlides : [];
|
||||
if (!availableSlides.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
let normalizedIndex = Number(targetIndex || 0);
|
||||
if (!Number.isFinite(normalizedIndex) || normalizedIndex < 0 || normalizedIndex >= availableSlides.length) {
|
||||
normalizedIndex = 0;
|
||||
}
|
||||
|
||||
const preloadSlides = [];
|
||||
const nextSlide = availableSlides[normalizedIndex + 1];
|
||||
|
||||
if (nextSlide) {
|
||||
preloadSlides.push(nextSlide);
|
||||
}
|
||||
|
||||
return preloadSlides;
|
||||
}
|
||||
|
||||
function scheduleSlideMarkupPreload(sourceSlides, targetIndex) {
|
||||
if (window.__pulseThumbnailPreview) {
|
||||
return;
|
||||
}
|
||||
|
||||
const preloadSlides = getSlideMarkupPreloadSlides(sourceSlides, targetIndex);
|
||||
if (!preloadSlides.length || typeof primeSlideMarkup !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const slide = preloadSlides[0];
|
||||
const preloadSignature = [
|
||||
currentPlaylistSignature || '',
|
||||
slide && slide.id ? slide.id : '',
|
||||
slide && slide.template_id ? slide.template_id : '',
|
||||
slide && slide.modified_at ? slide.modified_at : '',
|
||||
window.innerWidth + 'x' + window.innerHeight,
|
||||
videoRegionRenderVersion || 0
|
||||
].join('|');
|
||||
|
||||
if (scheduleSlideMarkupPreload.signature === preloadSignature) {
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleSlideMarkupPreload.signature = preloadSignature;
|
||||
|
||||
window.setTimeout(function () {
|
||||
if (scheduleSlideMarkupPreload.signature !== preloadSignature) {
|
||||
return;
|
||||
}
|
||||
primeSlideMarkup(slide);
|
||||
}, 0);
|
||||
}
|
||||
|
||||
// Mount hidden iframe preloads for the chosen webpage URLs.
|
||||
function syncWebpagePreloads(sourceSlides, targetIndex) {
|
||||
const urls = getWebpageUrls(getWebpagePreloadSlides(sourceSlides, targetIndex));
|
||||
@@ -136,13 +188,13 @@ function syncWebpagePreloads(sourceSlides, targetIndex) {
|
||||
preloadSignature = signature;
|
||||
}
|
||||
|
||||
// Return a stable client id for this browser session.
|
||||
// Return a stable client id for this screen session.
|
||||
function getCommandClientId() {
|
||||
if (commandClientId) {
|
||||
return commandClientId;
|
||||
}
|
||||
try {
|
||||
var storedClientId = window.localStorage.getItem(commandClientStorageKey);
|
||||
var storedClientId = window.sessionStorage.getItem(commandClientStorageKey);
|
||||
if (storedClientId) {
|
||||
commandClientId = storedClientId;
|
||||
return commandClientId;
|
||||
@@ -152,7 +204,7 @@ function getCommandClientId() {
|
||||
}
|
||||
commandClientId = (window.crypto && window.crypto.randomUUID ? window.crypto.randomUUID() : 'client-' + Date.now() + '-' + Math.random().toString(16).slice(2));
|
||||
try {
|
||||
window.localStorage.setItem(commandClientStorageKey, commandClientId);
|
||||
window.sessionStorage.setItem(commandClientStorageKey, commandClientId);
|
||||
} catch (_error2) {
|
||||
// ignore storage errors
|
||||
}
|
||||
|
||||
@@ -893,6 +893,45 @@ function getSlideMarkupCacheKey(slide) {
|
||||
return [currentPlaylistSignature || '', slide && slide.id ? slide.id : '', slide && slide.template_id ? slide.template_id : '', slide && slide.modified_at ? slide.modified_at : '', viewportKey, videoRegionRenderVersion || 0].join('|');
|
||||
}
|
||||
|
||||
function restorePlayerCanvasDimensions(width, height) {
|
||||
if (!document || !document.documentElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
var style = document.documentElement.style;
|
||||
if (width) {
|
||||
style.setProperty('--player-canvas-width', width);
|
||||
} else {
|
||||
style.removeProperty('--player-canvas-width');
|
||||
}
|
||||
|
||||
if (height) {
|
||||
style.setProperty('--player-canvas-height', height);
|
||||
} else {
|
||||
style.removeProperty('--player-canvas-height');
|
||||
}
|
||||
}
|
||||
|
||||
function primeSlideMarkup(slide) {
|
||||
if (!slide) {
|
||||
return '';
|
||||
}
|
||||
|
||||
var cachedMarkup = getCachedSlideMarkup(slide);
|
||||
if (cachedMarkup) {
|
||||
return cachedMarkup;
|
||||
}
|
||||
|
||||
var previousWidth = document && document.documentElement && document.documentElement.style ? String(document.documentElement.style.getPropertyValue('--player-canvas-width') || '') : '';
|
||||
var previousHeight = document && document.documentElement && document.documentElement.style ? String(document.documentElement.style.getPropertyValue('--player-canvas-height') || '') : '';
|
||||
|
||||
try {
|
||||
return buildSlideMarkupForState(slide, false);
|
||||
} finally {
|
||||
restorePlayerCanvasDimensions(previousWidth.trim(), previousHeight.trim());
|
||||
}
|
||||
}
|
||||
|
||||
function notifyVideoRegionSourceReady() {
|
||||
if (typeof videoRegionRenderVersion === 'number') {
|
||||
videoRegionRenderVersion += 1;
|
||||
@@ -919,9 +958,12 @@ function setCachedSlideMarkup(slide, markup) {
|
||||
|
||||
// Slide rendering and markup cache helpers.
|
||||
// Choose the right slide renderer and cache the result.
|
||||
function buildSlideMarkup(slide) {
|
||||
function buildSlideMarkupForState(slide, updateCurrentState) {
|
||||
if (updateCurrentState) {
|
||||
lastRenderedSlide = slide || null;
|
||||
syncBlackoutState();
|
||||
}
|
||||
|
||||
var cachedMarkup = getCachedSlideMarkup(slide);
|
||||
if (cachedMarkup) {
|
||||
return cachedMarkup;
|
||||
@@ -938,3 +980,7 @@ function buildSlideMarkup(slide) {
|
||||
setCachedSlideMarkup(slide, markup);
|
||||
return markup;
|
||||
}
|
||||
|
||||
function buildSlideMarkup(slide) {
|
||||
return buildSlideMarkupForState(slide, true);
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ async function networkFirst(request, cacheName, cacheKeyRequest) {
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
throw _error;
|
||||
return new Response('', { status: 504, statusText: 'Offline' });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// QR code region rendering for embedded URL-to-image output.
|
||||
|
||||
var registry = window.pulsePlayerRegionTypes;
|
||||
|
||||
function renderQrCodeRegion(region, regionContent) {
|
||||
var borderRadius = Math.max(0, Math.round(Number(regionContent && regionContent.qr_border_radius || 0)));
|
||||
var radiusStyle = borderRadius > 0 ? 'border-radius:' + borderRadius + 'px;overflow:hidden;' : '';
|
||||
var preview = String(regionContent && regionContent.qr_preview || '').trim();
|
||||
|
||||
if (!preview) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return '<div class="template-region qr-code" style="' + region.baseStyle + radiusStyle + '"><img class="template-region-qr-code-image" src="' + escapeHtml(preview) + '" alt="QR code" role="img" draggable="false" style="background:transparent;display:block;width:100%;height:100%;object-fit:contain;' + radiusStyle + '" /></div>';
|
||||
}
|
||||
|
||||
registry.register('qr-code', {
|
||||
renderRegion: renderQrCodeRegion,
|
||||
initRegion: function () {}
|
||||
});
|
||||
@@ -304,13 +304,9 @@ function getRtmpWarmupSlides(sourceSlides, targetIndex) {
|
||||
}
|
||||
|
||||
var warmupSlides = [];
|
||||
var currentSlide = availableSlides[normalizedIndex];
|
||||
var nextSlide = availableSlides[normalizedIndex + 1];
|
||||
|
||||
if (currentSlide) {
|
||||
warmupSlides.push(currentSlide);
|
||||
}
|
||||
if (nextSlide && nextSlide !== currentSlide) {
|
||||
if (nextSlide) {
|
||||
warmupSlides.push(nextSlide);
|
||||
}
|
||||
|
||||
@@ -693,12 +689,11 @@ function startRtmpPlayback(video, sourceUrl, disableAudio, skipUnavailable, plac
|
||||
if (window.Hls && window.Hls.isSupported && window.Hls.isSupported()) {
|
||||
var hls = new window.Hls({
|
||||
enableWorker: true,
|
||||
lowLatencyMode: true,
|
||||
liveSyncDurationCount: 4,
|
||||
liveMaxLatencyDurationCount: 8,
|
||||
maxBufferLength: 20,
|
||||
liveSyncDurationCount: 6,
|
||||
liveMaxLatencyDurationCount: 12,
|
||||
maxBufferLength: 30,
|
||||
maxLiveSyncPlaybackRate: 1,
|
||||
backBufferLength: 30
|
||||
backBufferLength: 60
|
||||
});
|
||||
video.__rtmpHls = hls;
|
||||
hls.attachMedia(video);
|
||||
|
||||
@@ -40,7 +40,7 @@ function renderTextRegion(region, regionContent) {
|
||||
var fontFamily = sanitizeFontFamily(regionContent.font_family || region.fontFamily || defaultStyle.font_family);
|
||||
var fontSize = sanitizeFontSize(regionContent.font_size || region.fontSize || defaultStyle.font_size);
|
||||
var fontColor = sanitizeTextColor(regionContent.font_color || region.fontColor || defaultStyle.font_color);
|
||||
var contentStyle = 'width:' + region.pixelWidth + 'px;height:' + region.pixelHeight + 'px;transform:scale(' + region.canvasScale + ');transform-origin:top left;' + (fontFamily ? 'font-family:' + escapeHtml(fontFamily) + ';' : '') + 'font-size:' + fontSize + 'px;color:' + escapeHtml(fontColor) + ';';
|
||||
var contentStyle = 'width:' + region.pixelWidth + 'px;height:' + region.pixelHeight + 'px;transform:scale(' + region.canvasScale + ');transform-origin:top left;line-height:1.5;' + (fontFamily ? 'font-family:' + escapeHtml(fontFamily) + ';' : '') + 'font-size:' + fontSize + 'px;color:' + escapeHtml(fontColor) + ';';
|
||||
var renderedBody = renderEditorJsContent(rawValue);
|
||||
return renderedBody ? '<div class="template-region text" style="' + region.baseStyle + '"><div class="template-region-text-scale" style="' + contentStyle + '">' + renderedBody + '</div></div>' : '';
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ function renderVideoRegion(region, regionContent) {
|
||||
videoRegionLastGoodSrcCache[regionKey] = requestedSrc;
|
||||
}
|
||||
setVideoSourceAvailability(requestedSrc, true);
|
||||
return '<div class="template-region video" style="' + region.baseStyle + '"><video src="' + escapeHtml(requestedSrcVersioned) + '" title="' + escapeHtml(region.label) + '" data-disable-audio="' + (disableAudio ? '1' : '0') + '" autoplay' + (disableAudio ? ' muted' : '') + ' loop playsinline preload="auto" disablepictureinpicture oncanplay="this.play().catch(function () {})" onloadedmetadata="this.play().catch(function () {})"></video></div>';
|
||||
return '<div class="template-region video" style="' + region.baseStyle + '"><video src="' + escapeHtml(requestedSrcVersioned) + '" title="' + escapeHtml(region.label) + '" data-disable-audio="' + (disableAudio ? '1' : '0') + '" autoplay' + (disableAudio ? ' muted' : '') + ' loop playsinline preload="auto" disablepictureinpicture oncanplay="this.play().catch(function () {})"></video></div>';
|
||||
}
|
||||
|
||||
var requestedState = getVideoSourceAvailability(requestedSrc);
|
||||
@@ -132,7 +132,7 @@ function renderVideoRegion(region, regionContent) {
|
||||
if (regionKey) {
|
||||
videoRegionLastGoodSrcCache[regionKey] = requestedSrc;
|
||||
}
|
||||
return '<div class="template-region video" style="' + region.baseStyle + '"><video src="' + escapeHtml(requestedSrcVersioned) + '" title="' + escapeHtml(region.label) + '" data-disable-audio="' + (disableAudio ? '1' : '0') + '" autoplay' + (disableAudio ? ' muted' : '') + ' loop playsinline preload="auto" disablepictureinpicture oncanplay="this.play().catch(function () {})" onloadedmetadata="this.play().catch(function () {})"></video></div>';
|
||||
return '<div class="template-region video" style="' + region.baseStyle + '"><video src="' + escapeHtml(requestedSrcVersioned) + '" title="' + escapeHtml(region.label) + '" data-disable-audio="' + (disableAudio ? '1' : '0') + '" autoplay' + (disableAudio ? ' muted' : '') + ' loop playsinline preload="auto" disablepictureinpicture oncanplay="this.play().catch(function () {})"></video></div>';
|
||||
}
|
||||
|
||||
scheduleVideoSourceProbe(regionKey, requestedSrc, false);
|
||||
@@ -141,7 +141,7 @@ function renderVideoRegion(region, regionContent) {
|
||||
if (cachedSrc !== requestedSrc) {
|
||||
logVideoRegionStatus('Keeping the previous playable video until the new mirrored file finishes transferring.', 'region=' + regionKey + ' old=' + cachedSrc + ' new=' + requestedSrc);
|
||||
}
|
||||
return '<div class="template-region video" style="' + region.baseStyle + '"><video src="' + escapeHtml(cachedSrcVersioned) + '" title="' + escapeHtml(region.label) + '" data-disable-audio="' + (disableAudio ? '1' : '0') + '" autoplay' + (disableAudio ? ' muted' : '') + ' loop playsinline preload="auto" disablepictureinpicture oncanplay="this.play().catch(function () {})" onloadedmetadata="this.play().catch(function () {})"></video></div>';
|
||||
return '<div class="template-region video" style="' + region.baseStyle + '"><video src="' + escapeHtml(cachedSrcVersioned) + '" title="' + escapeHtml(region.label) + '" data-disable-audio="' + (disableAudio ? '1' : '0') + '" autoplay' + (disableAudio ? ' muted' : '') + ' loop playsinline preload="auto" disablepictureinpicture oncanplay="this.play().catch(function () {})"></video></div>';
|
||||
}
|
||||
|
||||
return '';
|
||||
|
||||
@@ -442,8 +442,9 @@ function getPlayerRegionScriptPaths() {
|
||||
|
||||
function getPlayerRegionScripts() {
|
||||
const sharedPlaceholderUtilsPath = path.join(__dirname, '..', 'web', 'public', 'js', 'shared', 'placeholder-utils.js');
|
||||
const sharedQrSvgUtilsPath = path.join(__dirname, '..', 'web', 'public', 'js', 'shared', 'qr-code-svg.js');
|
||||
const playerRegionScriptPaths = getPlayerRegionScriptPaths();
|
||||
const scriptPaths = [sharedPlaceholderUtilsPath].concat(playerRegionScriptPaths);
|
||||
const scriptPaths = [sharedPlaceholderUtilsPath, sharedQrSvgUtilsPath].concat(playerRegionScriptPaths);
|
||||
const statSignature = scriptPaths.map(function (filePath) {
|
||||
return fs.statSync(filePath).mtimeMs;
|
||||
}).join('|');
|
||||
|
||||
@@ -46,7 +46,7 @@ function renderOnboardingLandingBody() {
|
||||
' <div class="onboarding-layout">',
|
||||
' <div class="onboarding-qr-pane">',
|
||||
' <div class="onboarding-qr-frame">',
|
||||
' <img id="onboarding-qr" alt="Onboarding QR code" />',
|
||||
' <img id="onboarding-qr" alt="Onboarding QR code" src="data:image/svg+xml;charset=utf-8,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 320 320%22%3E%3Crect width=%22320%22 height=%22320%22 rx=%2224%22 fill=%22%23ffffff%22/%3E%3Crect x=%2230%22 y=%2230%22 width=%22260%22 height=%22260%22 rx=%2218%22 fill=%22%23f8fafc%22 stroke=%22%23cbd5e1%22 stroke-width=%223%22 stroke-dasharray=%2212 10%22/%3E%3Cpath d=%22M106 118h108M106 156h108M106 194h72%22 stroke=%22%2394a3b8%22 stroke-width=%2214%22 stroke-linecap=%22round%22/%3E%3Ccircle cx=%22128%22 cy=%22248%22 r=%2212%22 fill=%22%2394a3b8%22/%3E%3Ctext x=%22160%22 y=%2278%22 text-anchor=%22middle%22 fill=%22%230f172a%22 font-family=%22Arial,sans-serif%22 font-size=%2224%22 font-weight=%22700%22%3EQR code loading%3C/text%3E%3Ctext x=%22160%22 y=%22266%22 text-anchor=%22middle%22 fill=%22%234b5563%22 font-family=%22Arial,sans-serif%22 font-size=%2214%22%3EPlease wait%3C/text%3E%3C/svg%3E" />',
|
||||
' </div>',
|
||||
' <div id="onboarding-status" class="onboarding-status">Preparing onboarding link...</div>',
|
||||
' </div>',
|
||||
|
||||
+181
-9
@@ -3,7 +3,7 @@
|
||||
const fs = require('fs');
|
||||
const express = require('express');
|
||||
const path = require('path');
|
||||
const { getSharedSecret, createPageAuthBundle, verifyPageAuthToken, verifyRequestAuth } = require('#src/request-auth');
|
||||
const { getSharedSecret, createPageAuthBundle, verifyPageAuthToken, verifyRequestAuth, createRequestAuthHeaders } = require('#src/request-auth');
|
||||
const { buildThumbnailPreviewData } = require('./thumbnail-preview');
|
||||
|
||||
const TRANSIENT_DB_ERROR_CODES = ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'ENOTFOUND', 'PROTOCOL_CONNECTION_LOST', 'POOL_CLOSED', 'ERR_POOL_CLOSED'];
|
||||
@@ -12,6 +12,17 @@ function isTransientDbError(error) {
|
||||
return Boolean(error && TRANSIENT_DB_ERROR_CODES.indexOf(String(error.code || '').trim()) !== -1);
|
||||
}
|
||||
|
||||
function isBridgeFetchError(error) {
|
||||
const message = String(error && error.message || '').toLowerCase();
|
||||
return Boolean(error && (
|
||||
message.indexOf('fetch failed') !== -1 ||
|
||||
message.indexOf('network error') !== -1 ||
|
||||
message.indexOf('econnreset') !== -1 ||
|
||||
message.indexOf('econnrefused') !== -1 ||
|
||||
message.indexOf('enotfound') !== -1
|
||||
));
|
||||
}
|
||||
|
||||
function registerPlayerRoutes(app, options) {
|
||||
const pool = options && options.pool ? options.pool : null;
|
||||
const common = options && options.common ? options.common : null;
|
||||
@@ -20,16 +31,70 @@ function registerPlayerRoutes(app, options) {
|
||||
const playerRuntime = options && options.playerRuntime ? options.playerRuntime : null;
|
||||
const playerPlaylistService = options && options.playerPlaylistService ? options.playerPlaylistService : null;
|
||||
const rtmpStreamService = options && options.rtmpStreamService ? options.rtmpStreamService : null;
|
||||
const playerPublicBaseUrl = String(options && options.playerPublicBaseUrl || process.env.PLAYER_PUBLIC_BASE_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, '');
|
||||
const playerInternalBaseUrl = String(options && options.playerInternalBaseUrl || process.env.PLAYER_INTERNAL_BASE_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, '');
|
||||
const playerIdentifier = String(options && options.playerIdentifier || '1').trim() || '1';
|
||||
const playerPublicUrl = String(options && options.playerPublicBaseUrl || process.env.PLAYER_PUBLIC_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, '');
|
||||
const playerInternalUrl = String(options && options.playerInternalBaseUrl || process.env.PLAYER_INTERNAL_URL || process.env.PLAYER_BASE_URL || '').trim().replace(/\/$/, '');
|
||||
const bridgeBaseUrl = String(options && options.bridgeBaseUrl || process.env.BRIDGE_PUBLIC_URL || '').trim().replace(/\/$/, '');
|
||||
const playerDeviceId = String(options && options.playerDeviceId || '').trim() || null;
|
||||
|
||||
if (!app || !pool || !common || !mediaDir || !assetDir || !playerRuntime || !playerPlaylistService || !rtmpStreamService) {
|
||||
throw new Error('registerPlayerRoutes requires app, pool, common, mediaDir, assetDir, playerRuntime, playerPlaylistService, and rtmpStreamService.');
|
||||
if (!app || !common || !mediaDir || !assetDir || !playerRuntime || !rtmpStreamService) {
|
||||
throw new Error('registerPlayerRoutes requires app, common, mediaDir, assetDir, playerRuntime, and rtmpStreamService.');
|
||||
}
|
||||
|
||||
if (!bridgeBaseUrl && (!pool || !playerPlaylistService)) {
|
||||
throw new Error('registerPlayerRoutes requires pool and playerPlaylistService unless bridgeBaseUrl is configured.');
|
||||
}
|
||||
|
||||
const sharedSecret = getSharedSecret();
|
||||
|
||||
async function fetchBridge(req, pathname, options) {
|
||||
if (!bridgeBaseUrl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const requestOptions = options && typeof options === 'object' ? options : {};
|
||||
const method = String(requestOptions.method || req.method || 'GET').trim().toUpperCase();
|
||||
const body = Object.prototype.hasOwnProperty.call(requestOptions, 'body') ? requestOptions.body : undefined;
|
||||
const requestPathname = String(pathname || '').split('?')[0];
|
||||
const headers = Object.assign({}, requestOptions.headers || {}, createRequestAuthHeaders({
|
||||
method: method,
|
||||
pathname: requestPathname,
|
||||
body: body
|
||||
}));
|
||||
|
||||
if (req.headers['x-pulse-page-auth']) {
|
||||
headers['x-pulse-page-auth'] = String(req.headers['x-pulse-page-auth']).trim();
|
||||
}
|
||||
if (req.headers['if-none-match']) {
|
||||
headers['if-none-match'] = String(req.headers['if-none-match']).trim();
|
||||
}
|
||||
if (requestOptions.contentType) {
|
||||
headers['content-type'] = requestOptions.contentType;
|
||||
}
|
||||
|
||||
return fetch(new URL(pathname, bridgeBaseUrl).toString(), {
|
||||
method: method,
|
||||
headers: headers,
|
||||
body: body === undefined || body === null || method === 'GET' || method === 'HEAD' ? undefined : body
|
||||
});
|
||||
}
|
||||
|
||||
async function readJsonResponse(response) {
|
||||
if (!response) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const contentType = String(response.headers && typeof response.headers.get === 'function' ? response.headers.get('content-type') : '').toLowerCase();
|
||||
if (contentType.indexOf('application/json') === -1 && contentType.indexOf('+json') === -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return await response.json();
|
||||
} catch (_error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function requirePageAuth(allowedScopes) {
|
||||
return function (req, res, next) {
|
||||
if (!sharedSecret) {
|
||||
@@ -114,6 +179,26 @@ function registerPlayerRoutes(app, options) {
|
||||
});
|
||||
|
||||
app.get('/api/media/config', requireRequestAuth, function (_req, res) {
|
||||
if (bridgeBaseUrl) {
|
||||
void fetch(new URL('/api/media/config', bridgeBaseUrl).toString(), {
|
||||
method: 'GET',
|
||||
headers: createRequestAuthHeaders({
|
||||
method: 'GET',
|
||||
pathname: '/api/media/config'
|
||||
})
|
||||
}).then(async function (response) {
|
||||
res.status(response.status);
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (contentType) {
|
||||
res.type(contentType);
|
||||
}
|
||||
res.send(await response.text());
|
||||
}).catch(function (_error) {
|
||||
res.status(502).json({ error: 'Thin client unavailable.' });
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
res.json({
|
||||
mediaDir: mediaDir,
|
||||
uploadDir: path.join(mediaDir, 'uploads')
|
||||
@@ -213,9 +298,35 @@ function registerPlayerRoutes(app, options) {
|
||||
app.get('/screen/:slug', function (req, res) {
|
||||
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
|
||||
res.set('Pragma', 'no-cache');
|
||||
if (bridgeBaseUrl) {
|
||||
const pageAuthToken = createPageAuthBundle({ scope: 'player', slug: String(req.params.slug || '').trim() }).token;
|
||||
void fetchBridge(req, '/api/screens/' + encodeURIComponent(req.params.slug) + '/playlist?ts=' + Date.now(), {
|
||||
method: 'GET',
|
||||
headers: pageAuthToken ? { 'x-pulse-page-auth': pageAuthToken } : {}
|
||||
}).then(async function (response) {
|
||||
if (!response || response.status >= 400) {
|
||||
res.set('X-Player-Offline', '1');
|
||||
return res.send(common.renderPlayerPage(req.params.slug, null));
|
||||
}
|
||||
const data = await readJsonResponse(response);
|
||||
if (!data) {
|
||||
res.set('X-Player-Offline', '1');
|
||||
return res.send(common.renderPlayerPage(req.params.slug, null));
|
||||
}
|
||||
res.send(common.renderPlayerPage(req.params.slug, data));
|
||||
}).catch(function (error) {
|
||||
if (!isBridgeFetchError(error)) {
|
||||
console.error(error);
|
||||
}
|
||||
res.set('X-Player-Offline', '1');
|
||||
res.send(common.renderPlayerPage(req.params.slug, null));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const { bindPlayerToScreen } = require('./onboarding');
|
||||
if (playerIdentifier) {
|
||||
void bindPlayerToScreen(pool, playerIdentifier, req.params.slug)
|
||||
if (playerDeviceId) {
|
||||
void bindPlayerToScreen(pool, playerDeviceId, req.params.slug)
|
||||
.catch(function (error) {
|
||||
console.error(error);
|
||||
});
|
||||
@@ -231,6 +342,19 @@ function registerPlayerRoutes(app, options) {
|
||||
|
||||
app.get('/api/internal/slide-thumbnails/:id/preview', requireRequestAuth, async function (req, res, next) {
|
||||
try {
|
||||
if (bridgeBaseUrl) {
|
||||
const response = await fetchBridge(req, '/api/internal/slide-thumbnails/' + encodeURIComponent(req.params.id) + '/preview', {
|
||||
method: 'GET'
|
||||
});
|
||||
if (!response) {
|
||||
return res.status(502).send('Thin client unavailable');
|
||||
}
|
||||
res.status(response.status);
|
||||
res.set('Cache-Control', response.headers.get('cache-control') || 'no-store, no-cache, must-revalidate, proxy-revalidate');
|
||||
res.type(response.headers.get('content-type') || 'text/html; charset=utf-8');
|
||||
return res.send(await response.text());
|
||||
}
|
||||
|
||||
const slide = await common.fetchSlideById(pool, Number(req.params.id));
|
||||
if (!slide) {
|
||||
return res.status(404).send('Slide not found');
|
||||
@@ -273,6 +397,29 @@ function registerPlayerRoutes(app, options) {
|
||||
|
||||
app.get('/api/screens/:slug/playlist', requirePageAuth(['player']), async function (req, res, next) {
|
||||
try {
|
||||
if (bridgeBaseUrl) {
|
||||
const response = await fetchBridge(req, '/api/screens/' + encodeURIComponent(req.params.slug) + '/playlist', {
|
||||
method: 'GET'
|
||||
});
|
||||
if (!response) {
|
||||
return res.status(502).json({ error: 'Thin client unavailable.' });
|
||||
}
|
||||
res.status(response.status);
|
||||
const etag = response.headers.get('etag');
|
||||
const cacheControl = response.headers.get('cache-control');
|
||||
if (etag) {
|
||||
res.set('ETag', etag);
|
||||
}
|
||||
if (cacheControl) {
|
||||
res.set('Cache-Control', cacheControl);
|
||||
}
|
||||
if (response.status === 304) {
|
||||
return res.end();
|
||||
}
|
||||
res.type(response.headers.get('content-type') || 'application/json');
|
||||
return res.send(await response.text());
|
||||
}
|
||||
|
||||
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
|
||||
const data = await playerPlaylistService.buildScreenPlaylist(req.params.slug);
|
||||
if (!data.screen) {
|
||||
@@ -293,6 +440,29 @@ function registerPlayerRoutes(app, options) {
|
||||
|
||||
app.get('/api/screens/:slug/announcement', requirePageAuth(['player']), async function (req, res, next) {
|
||||
try {
|
||||
if (bridgeBaseUrl) {
|
||||
const response = await fetchBridge(req, '/api/screens/' + encodeURIComponent(req.params.slug) + '/announcement', {
|
||||
method: 'GET'
|
||||
});
|
||||
if (!response) {
|
||||
return res.status(502).json({ error: 'Thin client unavailable.' });
|
||||
}
|
||||
res.status(response.status);
|
||||
const etag = response.headers.get('etag');
|
||||
const cacheControl = response.headers.get('cache-control');
|
||||
if (etag) {
|
||||
res.set('ETag', etag);
|
||||
}
|
||||
if (cacheControl) {
|
||||
res.set('Cache-Control', cacheControl);
|
||||
}
|
||||
if (response.status === 304) {
|
||||
return res.end();
|
||||
}
|
||||
res.type(response.headers.get('content-type') || 'application/json');
|
||||
return res.send(await response.text());
|
||||
}
|
||||
|
||||
res.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
|
||||
const announcement = typeof common.fetchActiveAnnouncement === 'function'
|
||||
? await common.fetchActiveAnnouncement(pool, req.params.slug)
|
||||
@@ -335,6 +505,7 @@ function registerPlayerRoutes(app, options) {
|
||||
const connections = playerRuntime.snapshotConnections(req.params.slug);
|
||||
let screen = null;
|
||||
let screenLookupFailed = false;
|
||||
if (pool && typeof pool.query === 'function') {
|
||||
try {
|
||||
const [screenRows] = await pool.query('SELECT id, name, slug FROM d_screens WHERE slug = ?', [req.params.slug]);
|
||||
screen = screenRows[0] || null;
|
||||
@@ -344,6 +515,7 @@ function registerPlayerRoutes(app, options) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
res.json({
|
||||
screen: screen,
|
||||
screenSlug: req.params.slug,
|
||||
@@ -374,7 +546,7 @@ function registerPlayerRoutes(app, options) {
|
||||
const isRedirectCommand = command === 'redirect';
|
||||
let screen = null;
|
||||
let screenLookupFailed = false;
|
||||
if (!isRedirectCommand) {
|
||||
if (!isRedirectCommand && pool && typeof pool.query === 'function') {
|
||||
try {
|
||||
const [screenRows] = await pool.query('SELECT id, name, slug FROM d_screens WHERE slug = ?', [req.params.slug]);
|
||||
screen = screenRows[0] || null;
|
||||
|
||||
+88
-15
@@ -21,6 +21,7 @@ function normalizePlayerPublicBaseUrl(pageUrl) {
|
||||
|
||||
function createPlayerRuntime(options) {
|
||||
const pool = options && options.pool ? options.pool : null;
|
||||
const notifySnapshot = typeof options.notifySnapshot === 'function' ? options.notifySnapshot : null;
|
||||
const normalizeDeviceId = typeof options.normalizeDeviceId === 'function'
|
||||
? options.normalizeDeviceId
|
||||
: function (value) {
|
||||
@@ -44,6 +45,76 @@ function createPlayerRuntime(options) {
|
||||
return ip;
|
||||
}
|
||||
|
||||
function firstHeaderValue(value) {
|
||||
return String(value || '').trim().split(',')[0].trim();
|
||||
}
|
||||
|
||||
function isPrivateOrReservedIp(ip) {
|
||||
const normalized = normalizeClientIp(ip);
|
||||
if (!normalized) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const lower = normalized.toLowerCase();
|
||||
if (lower === 'localhost' || lower === '::1') {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (/^10\./.test(lower) || /^192\.168\./.test(lower) || /^127\./.test(lower) || /^169\.254\./.test(lower)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (/^172\.(1[6-9]|2\d|3[0-1])\./.test(lower)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (lower.startsWith('fc') || lower.startsWith('fd') || lower.startsWith('fe80:') || lower.startsWith('::ffff:127.')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function pickForwardedIp(candidates) {
|
||||
const normalizedCandidates = Array.isArray(candidates)
|
||||
? candidates.map(function (candidate) {
|
||||
return normalizeClientIp(candidate);
|
||||
}).filter(Boolean)
|
||||
: [];
|
||||
|
||||
const publicCandidate = normalizedCandidates.find(function (candidate) {
|
||||
return !isPrivateOrReservedIp(candidate);
|
||||
});
|
||||
|
||||
return publicCandidate || normalizedCandidates[0] || null;
|
||||
}
|
||||
|
||||
function resolveRequestIp(request) {
|
||||
const forwardedFor = String(request && request.headers && request.headers['x-forwarded-for'] || '').split(',');
|
||||
const forwardedForIp = pickForwardedIp(forwardedFor);
|
||||
if (forwardedForIp) {
|
||||
return forwardedForIp;
|
||||
}
|
||||
|
||||
const realIp = pickForwardedIp([firstHeaderValue(request && request.headers && request.headers['x-real-ip'])]);
|
||||
if (realIp) {
|
||||
return realIp;
|
||||
}
|
||||
|
||||
const forwarded = firstHeaderValue(request && request.headers && request.headers.forwarded);
|
||||
if (forwarded) {
|
||||
const forwardedMatches = Array.from(forwarded.matchAll(/(?:^|,\s*|;\s*)for=(?:"?\[?)([^"\];,\s]+)/gi)).map(function (match) {
|
||||
return match[1];
|
||||
});
|
||||
const forwardedIp = pickForwardedIp(forwardedMatches);
|
||||
if (forwardedIp) {
|
||||
return forwardedIp;
|
||||
}
|
||||
}
|
||||
|
||||
return normalizeClientIp(request && request.socket && request.socket.remoteAddress);
|
||||
}
|
||||
|
||||
function parseCookies(cookieHeader) {
|
||||
return String(cookieHeader || '').split(/;\s*/).reduce(function (cookies, pair) {
|
||||
if (!pair) {
|
||||
@@ -144,7 +215,6 @@ function createPlayerRuntime(options) {
|
||||
const clientName = String(connection.clientName || '').trim();
|
||||
const clientId = String(connection.clientId || '').trim();
|
||||
const userAgent = String(connection.userAgent || '').trim();
|
||||
const clientIp = String(connection.clientIp || '').trim();
|
||||
const viewport = connection.viewport && typeof connection.viewport === 'object'
|
||||
? connection.viewport
|
||||
: null;
|
||||
@@ -160,10 +230,6 @@ function createPlayerRuntime(options) {
|
||||
labelParts.push(`id ${clientId.slice(-6)}`);
|
||||
}
|
||||
|
||||
if (clientIp) {
|
||||
labelParts.push(clientIp);
|
||||
}
|
||||
|
||||
if (viewport && Number.isFinite(Number(viewport.width)) && Number.isFinite(Number(viewport.height))) {
|
||||
labelParts.push(`${Number(viewport.width)}x${Number(viewport.height)}`);
|
||||
}
|
||||
@@ -197,8 +263,6 @@ function createPlayerRuntime(options) {
|
||||
blackout: Boolean(connection.blackout),
|
||||
currentSlideId: connection.currentSlide && connection.currentSlide.id ? connection.currentSlide.id : null,
|
||||
currentSlideTitle: connection.currentSlide && connection.currentSlide.title ? connection.currentSlide.title : null,
|
||||
clientIp: connection.clientIp || null,
|
||||
remoteAddress: connection.remoteAddress || null,
|
||||
connectedAt: connection.connectedAt ? connection.connectedAt.toISOString() : null,
|
||||
lastSeenAt: connection.lastSeenAt ? connection.lastSeenAt.toISOString() : null
|
||||
};
|
||||
@@ -222,6 +286,10 @@ function createPlayerRuntime(options) {
|
||||
return allConnections;
|
||||
}
|
||||
|
||||
function snapshotSlugs() {
|
||||
return Array.from(connectionsBySlug.keys());
|
||||
}
|
||||
|
||||
async function isClientNameAvailableOnScreen(poolArg, clientName, excludeDeviceId) {
|
||||
return isClientNameAvailable(poolArg || pool, clientName, excludeDeviceId, snapshotAllConnections());
|
||||
}
|
||||
@@ -229,6 +297,16 @@ function createPlayerRuntime(options) {
|
||||
function broadcastConnectionSnapshot(slug) {
|
||||
const key = String(slug || '').trim();
|
||||
const bucket = dashboardListenersBySlug.get(key);
|
||||
const connections = snapshotConnections(slug);
|
||||
if (notifySnapshot) {
|
||||
try {
|
||||
notifySnapshot({
|
||||
slug: key,
|
||||
connections: connections
|
||||
});
|
||||
} catch (_error) {
|
||||
}
|
||||
}
|
||||
if (!bucket || !bucket.size) {
|
||||
return;
|
||||
}
|
||||
@@ -236,7 +314,7 @@ function createPlayerRuntime(options) {
|
||||
const payload = JSON.stringify({
|
||||
type: 'snapshot',
|
||||
slug: key,
|
||||
connections: snapshotConnections(slug),
|
||||
connections: connections,
|
||||
sentAt: new Date().toISOString()
|
||||
});
|
||||
|
||||
@@ -416,9 +494,6 @@ function createPlayerRuntime(options) {
|
||||
return;
|
||||
}
|
||||
|
||||
const remoteAddress = request.socket && request.socket.remoteAddress ? request.socket.remoteAddress : null;
|
||||
const forwardedFor = normalizeClientIp(String(request.headers['x-forwarded-for'] || '').split(',')[0]);
|
||||
const normalizedRemoteAddress = normalizeClientIp(remoteAddress);
|
||||
const connectionId = crypto.randomUUID();
|
||||
const connection = {
|
||||
id: connectionId,
|
||||
@@ -433,9 +508,7 @@ function createPlayerRuntime(options) {
|
||||
paused: false,
|
||||
blackout: false,
|
||||
playerPublicBaseUrl: null,
|
||||
clientIp: forwardedFor || normalizedRemoteAddress,
|
||||
remoteAddress: normalizedRemoteAddress,
|
||||
label: forwardedFor || normalizedRemoteAddress || 'connected client',
|
||||
label: 'connected client',
|
||||
connectedAt: new Date(),
|
||||
lastSeenAt: new Date()
|
||||
};
|
||||
@@ -476,7 +549,6 @@ function createPlayerRuntime(options) {
|
||||
}
|
||||
connection.paused = Boolean(payload.paused);
|
||||
connection.blackout = Boolean(payload.blackout);
|
||||
connection.clientIp = payload.clientIp ? normalizeClientIp(payload.clientIp) || connection.clientIp : connection.clientIp;
|
||||
connection.currentSlide = payload.currentSlide && typeof payload.currentSlide === 'object' ? {
|
||||
id: payload.currentSlide.id || null,
|
||||
title: payload.currentSlide.title || '',
|
||||
@@ -508,6 +580,7 @@ function createPlayerRuntime(options) {
|
||||
broadcastAnnouncementRefresh: broadcastAnnouncementRefresh,
|
||||
snapshotConnections: snapshotConnections,
|
||||
snapshotAllConnections: snapshotAllConnections,
|
||||
snapshotSlugs: snapshotSlugs,
|
||||
isClientNameAvailableOnScreen: isClientNameAvailableOnScreen,
|
||||
sendCommandToConnection: sendCommandToConnection,
|
||||
broadcastCommand: broadcastCommand
|
||||
|
||||
+66
-53
@@ -1,12 +1,15 @@
|
||||
// Permission section definitions and normalization helpers for RBAC.
|
||||
|
||||
const PERMISSION_SECTIONS = [
|
||||
{
|
||||
sectionName: 'Main navigation',
|
||||
order: 10,
|
||||
permissions: [
|
||||
{
|
||||
key: 'dashboard',
|
||||
order: 10,
|
||||
name: 'Dashboard',
|
||||
sectionName: 'Main navigation',
|
||||
actions: [
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'Access the dashboard overview.' },
|
||||
{ key: 'allow', name: 'Allow', description: 'Send global player commands.' }
|
||||
]
|
||||
@@ -15,18 +18,22 @@ const PERMISSION_SECTIONS = [
|
||||
key: 'clients',
|
||||
order: 20,
|
||||
name: 'Connected clients',
|
||||
sectionName: 'Main navigation',
|
||||
actions: [
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View connected player clients and live status.' },
|
||||
{ key: 'allow', name: 'Allow', description: 'Use the connected client command buttons.' }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
key: 'screens',
|
||||
order: 30,
|
||||
name: 'Screens',
|
||||
sectionName: 'Content',
|
||||
actions: [
|
||||
order: 20,
|
||||
permissions: [
|
||||
{
|
||||
key: 'screens',
|
||||
order: 10,
|
||||
name: 'Screens',
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View the screen list and open screen details.' },
|
||||
{ key: 'create', name: 'Create', description: 'Create new screens.' },
|
||||
{ key: 'update', name: 'Update', description: 'Update screens.' },
|
||||
@@ -35,10 +42,9 @@ const PERMISSION_SECTIONS = [
|
||||
},
|
||||
{
|
||||
key: 'playlists',
|
||||
order: 40,
|
||||
order: 20,
|
||||
name: 'Playlists',
|
||||
sectionName: 'Content',
|
||||
actions: [
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View playlists and playlist contents.' },
|
||||
{ key: 'create', name: 'Create', description: 'Create new playlists.' },
|
||||
{ key: 'update', name: 'Update', description: 'Update playlists and playlist slides.' },
|
||||
@@ -47,10 +53,9 @@ const PERMISSION_SECTIONS = [
|
||||
},
|
||||
{
|
||||
key: 'slides',
|
||||
order: 50,
|
||||
order: 30,
|
||||
name: 'Slides',
|
||||
sectionName: 'Content',
|
||||
actions: [
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View slides.' },
|
||||
{ key: 'create', name: 'Create', description: 'Create new slides.' },
|
||||
{ key: 'update', name: 'Update', description: 'Update slide content.' },
|
||||
@@ -59,10 +64,9 @@ const PERMISSION_SECTIONS = [
|
||||
},
|
||||
{
|
||||
key: 'templates',
|
||||
order: 60,
|
||||
order: 40,
|
||||
name: 'Slide templates',
|
||||
sectionName: 'Content',
|
||||
actions: [
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View slide templates.' },
|
||||
{ key: 'create', name: 'Create', description: 'Create new slide templates.' },
|
||||
{ key: 'update', name: 'Update', description: 'Update slide templates.' },
|
||||
@@ -71,10 +75,9 @@ const PERMISSION_SECTIONS = [
|
||||
},
|
||||
{
|
||||
key: 'canvas-sizes',
|
||||
order: 70,
|
||||
order: 50,
|
||||
name: 'Canvas sizes',
|
||||
sectionName: 'Content',
|
||||
actions: [
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View canvas sizes.' },
|
||||
{ key: 'create', name: 'Create', description: 'Create new canvas sizes.' },
|
||||
{ key: 'update', name: 'Update', description: 'Update canvas sizes.' },
|
||||
@@ -83,22 +86,26 @@ const PERMISSION_SECTIONS = [
|
||||
},
|
||||
{
|
||||
key: 'announcements',
|
||||
order: 80,
|
||||
order: 60,
|
||||
name: 'Announcements',
|
||||
sectionName: 'Content',
|
||||
actions: [
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View announcements.' },
|
||||
{ key: 'create', name: 'Create', description: 'Create new announcements.' },
|
||||
{ key: 'update', name: 'Update', description: 'Update announcements.' },
|
||||
{ key: 'delete', name: 'Delete', description: 'Delete announcements.' }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
key: 'rss-feeds',
|
||||
order: 90,
|
||||
name: 'RSS feeds',
|
||||
sectionName: 'Data Sources',
|
||||
actions: [
|
||||
order: 30,
|
||||
permissions: [
|
||||
{
|
||||
key: 'rss-feeds',
|
||||
order: 10,
|
||||
name: 'RSS feeds',
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View configured RSS feeds.' },
|
||||
{ key: 'create', name: 'Create', description: 'Create new RSS feeds.' },
|
||||
{ key: 'update', name: 'Update', description: 'Update RSS feeds.' },
|
||||
@@ -107,10 +114,9 @@ const PERMISSION_SECTIONS = [
|
||||
},
|
||||
{
|
||||
key: 'api-sources',
|
||||
order: 100,
|
||||
order: 20,
|
||||
name: 'API sources',
|
||||
sectionName: 'Data Sources',
|
||||
actions: [
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View configured API sources.' },
|
||||
{ key: 'create', name: 'Create', description: 'Create new API sources.' },
|
||||
{ key: 'update', name: 'Update', description: 'Update API sources.' },
|
||||
@@ -119,22 +125,26 @@ const PERMISSION_SECTIONS = [
|
||||
},
|
||||
{
|
||||
key: 'timetables',
|
||||
order: 110,
|
||||
order: 30,
|
||||
name: 'Timetables',
|
||||
sectionName: 'Data Sources',
|
||||
actions: [
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View configured timetable groups.' },
|
||||
{ key: 'create', name: 'Create', description: 'Create new timetable groups.' },
|
||||
{ key: 'update', name: 'Update', description: 'Update timetable groups and entries.' },
|
||||
{ key: 'delete', name: 'Delete', description: 'Delete timetable groups.' }
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
key: 'users',
|
||||
order: 120,
|
||||
name: 'Users',
|
||||
sectionName: 'Settings',
|
||||
actions: [
|
||||
order: 40,
|
||||
permissions: [
|
||||
{
|
||||
key: 'users',
|
||||
order: 10,
|
||||
name: 'Users',
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View users and role assignments.' },
|
||||
{ key: 'create', name: 'Create', description: 'Create new users.' },
|
||||
{ key: 'update', name: 'Update', description: 'Update users, passwords, and role assignments.' },
|
||||
@@ -143,10 +153,9 @@ const PERMISSION_SECTIONS = [
|
||||
},
|
||||
{
|
||||
key: 'rbac',
|
||||
order: 130,
|
||||
order: 20,
|
||||
name: 'Roles and permissions',
|
||||
sectionName: 'Settings',
|
||||
actions: [
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View roles and permissions.' },
|
||||
{ key: 'create', name: 'Create', description: 'Create new roles.' },
|
||||
{ key: 'update', name: 'Update', description: 'Update role details and permissions.' },
|
||||
@@ -155,10 +164,9 @@ const PERMISSION_SECTIONS = [
|
||||
},
|
||||
{
|
||||
key: 'fonts',
|
||||
order: 140,
|
||||
order: 30,
|
||||
name: 'Fonts',
|
||||
sectionName: 'Settings',
|
||||
actions: [
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View managed fonts.' },
|
||||
{ key: 'create', name: 'Create', description: 'Upload managed fonts.' },
|
||||
{ key: 'delete', name: 'Delete', description: 'Remove managed fonts.' }
|
||||
@@ -166,39 +174,44 @@ const PERMISSION_SECTIONS = [
|
||||
},
|
||||
{
|
||||
key: 'background-tasks',
|
||||
order: 150,
|
||||
order: 40,
|
||||
name: 'Task Queue',
|
||||
sectionName: 'Settings',
|
||||
actions: [
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View queued background tasks.' },
|
||||
{ key: 'allow', name: 'Allow', description: 'Manage queued background tasks and clear finished items.' }
|
||||
]
|
||||
},
|
||||
{
|
||||
key: 'scheduled-tasks',
|
||||
order: 160,
|
||||
order: 50,
|
||||
name: 'Scheduled tasks',
|
||||
sectionName: 'Settings',
|
||||
actions: [
|
||||
permissions: [
|
||||
{ key: 'read', name: 'Read', description: 'View scheduled refresh tasks.' },
|
||||
{ key: 'allow', name: 'Allow', description: 'Run scheduled refreshes manually.' }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
const PERMISSIONS = PERMISSION_SECTIONS.flatMap(function (section) {
|
||||
return section.actions.map(function (action) {
|
||||
return (Array.isArray(section.permissions) ? section.permissions : []).flatMap(function (resource) {
|
||||
return (Array.isArray(resource.permissions) ? resource.permissions : []).map(function (action, index) {
|
||||
return {
|
||||
key: `${section.key}.${action.key}`,
|
||||
name: section.name,
|
||||
key: `${resource.key}.${action.key}`,
|
||||
name: resource.name,
|
||||
sectionOrder: section.order,
|
||||
actionName: action.name,
|
||||
permissionOrder: index + 1,
|
||||
sectionName: section.sectionName,
|
||||
sectionKey: section.key,
|
||||
resourceKey: resource.key,
|
||||
resourceOrder: resource.order,
|
||||
resourceName: resource.name,
|
||||
actionKey: action.key,
|
||||
description: action.description
|
||||
};
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const DEFAULT_ROLE = {
|
||||
|
||||
+9
-4
@@ -6,7 +6,7 @@ const multer = require('multer');
|
||||
const fs = require('fs');
|
||||
const crypto = require('crypto');
|
||||
const common = require('./common');
|
||||
const { verifyPassword, createSessionToken, hashSessionToken, hashPassword } = require('#src/auth');
|
||||
const { verifyPassword, createSessionToken, hashSessionToken, hashPassword, validatePasswordStrength } = require('#src/auth');
|
||||
const pages = require('#src/web/pages');
|
||||
const registerMiddleware = require('#src/web/middleware');
|
||||
const { createBackgroundTaskQueue } = require('#src/web/lib/background-tasks/queue');
|
||||
@@ -62,7 +62,8 @@ async function start() {
|
||||
const playerActionService = createPlayerActionService({
|
||||
pool: pool,
|
||||
common: common,
|
||||
playerInternalBaseUrl: webConfig.playerInternalBaseUrl
|
||||
playerInternalBaseUrl: webConfig.playerInternalUrl,
|
||||
bridgeInternalBaseUrl: webConfig.bridgeInternalUrl
|
||||
});
|
||||
const notifyPlayerScreens = createNotifyPlayerScreens(playerActionService.forwardPlayerCommand);
|
||||
|
||||
@@ -70,8 +71,8 @@ async function start() {
|
||||
const webBootstrap = createWebBootstrap({
|
||||
pool: pool,
|
||||
common: common,
|
||||
playerInternalBaseUrl: webConfig.playerInternalBaseUrl,
|
||||
playerPublicBaseUrl: webConfig.playerPublicBaseUrl,
|
||||
playerInternalBaseUrl: webConfig.playerInternalUrl,
|
||||
bridgeInternalBaseUrl: webConfig.bridgeInternalUrl,
|
||||
uploadDir: webConfig.uploadsDir,
|
||||
formatDashboardDate: formatDashboardDate,
|
||||
notifyPlayerScreens: notifyPlayerScreens,
|
||||
@@ -131,6 +132,7 @@ async function start() {
|
||||
formatDashboardDate: formatDashboardDate,
|
||||
getAuditUserId: getAuditUserId,
|
||||
hashPassword: hashPassword,
|
||||
validatePasswordStrength: validatePasswordStrength,
|
||||
readArrayField: readArrayField,
|
||||
rbacData: rbacData,
|
||||
fetchOrderedPlaylistSlides: fetchOrderedPlaylistSlides,
|
||||
@@ -155,6 +157,8 @@ async function start() {
|
||||
},
|
||||
hasAnyPermission: hasAnyPermission,
|
||||
backgroundTaskQueue: backgroundTaskQueue,
|
||||
mediaDir: webConfig.mediaDir,
|
||||
uploadSyncService: webBootstrap.uploadSyncService,
|
||||
collectUploadReferencesFromSlide: collectUploadReferencesFromSlide,
|
||||
collectUploadReferencesFromTemplate: collectUploadReferencesFromTemplate,
|
||||
collectUploadReferencesFromPayload: collectUploadReferencesFromPayload,
|
||||
@@ -207,6 +211,7 @@ async function start() {
|
||||
initializeBackgroundTasks: initializeBackgroundTasks,
|
||||
captureSlideThumbnail: captureSlideThumbnail,
|
||||
server: server,
|
||||
webBaseUrl: webConfig.webInternalUrl,
|
||||
dataSourceStartupRefreshStaggerMs: webConfig.dataSourceStartupRefreshStaggerMs
|
||||
});
|
||||
|
||||
|
||||
Vendored
+57
-64
@@ -8,8 +8,8 @@ const { createRequestAuthHeaders } = require('#src/request-auth');
|
||||
function createWebBootstrap(options) {
|
||||
const pool = options && options.pool;
|
||||
const common = options && options.common;
|
||||
const configuredPlayerInternalBaseUrl = String(options && options.playerInternalBaseUrl || '').replace(/\/$/, '');
|
||||
const playerPublicBaseUrl = String(options && options.playerPublicBaseUrl || '').replace(/\/$/, '');
|
||||
const configuredPlayerInternalUrl = String(options && options.playerInternalBaseUrl || '').replace(/\/$/, '');
|
||||
const configuredBridgeInternalUrl = String(options && options.bridgeInternalBaseUrl || process.env.BRIDGE_INTERNAL_URL || '').trim().replace(/\/$/, '');
|
||||
const uploadDir = String(options && options.uploadDir || '').trim();
|
||||
const dashboardRefreshIntervalMs = 5000;
|
||||
const formatDashboardDate = options && options.formatDashboardDate;
|
||||
@@ -22,53 +22,12 @@ function createWebBootstrap(options) {
|
||||
|
||||
const dashboardWs = new WebSocketServer({ noServer: true });
|
||||
const dashboardClients = new Set();
|
||||
const playerSnapshotCache = new Map();
|
||||
const playerSnapshotSockets = new Map();
|
||||
const playerSnapshotCache = options && options.playerSnapshotCache ? options.playerSnapshotCache : new Map();
|
||||
const playerSnapshotSockets = options && options.playerSnapshotSockets ? options.playerSnapshotSockets : new Map();
|
||||
let dashboardRefreshInFlight = null;
|
||||
let broadcastDashboardState = null;
|
||||
let playerInternalBaseUrl = null;
|
||||
let playerInternalBaseUrlPromise = null;
|
||||
|
||||
async function getPlayerInternalBaseUrl() {
|
||||
if (playerInternalBaseUrl) {
|
||||
return playerInternalBaseUrl;
|
||||
}
|
||||
|
||||
if (playerInternalBaseUrlPromise) {
|
||||
return playerInternalBaseUrlPromise;
|
||||
}
|
||||
|
||||
playerInternalBaseUrlPromise = (async function () {
|
||||
if (!pool) {
|
||||
return configuredPlayerInternalBaseUrl || null;
|
||||
}
|
||||
|
||||
try {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT internal_base_url
|
||||
FROM d_players
|
||||
WHERE device_id = '1'
|
||||
LIMIT 1`
|
||||
);
|
||||
const resolvedBaseUrl = String(rows && rows[0] && rows[0].internal_base_url || '').trim().replace(/\/$/, '');
|
||||
return resolvedBaseUrl || configuredPlayerInternalBaseUrl || null;
|
||||
} catch (_error) {
|
||||
return configuredPlayerInternalBaseUrl || null;
|
||||
}
|
||||
})().then(function (baseUrl) {
|
||||
playerInternalBaseUrl = baseUrl || null;
|
||||
playerInternalBaseUrlPromise = null;
|
||||
return playerInternalBaseUrl;
|
||||
}, function () {
|
||||
playerInternalBaseUrlPromise = null;
|
||||
return configuredPlayerInternalBaseUrl || null;
|
||||
});
|
||||
|
||||
return playerInternalBaseUrlPromise;
|
||||
}
|
||||
|
||||
async function getPlayerSnapshotSocketUrl(slug) {
|
||||
const resolvedPlayerInternalBaseUrl = await getPlayerInternalBaseUrl();
|
||||
function getPlayerSnapshotSocketUrl(slug) {
|
||||
const resolvedPlayerInternalBaseUrl = configuredBridgeInternalUrl || configuredPlayerInternalUrl;
|
||||
if (!resolvedPlayerInternalBaseUrl) {
|
||||
throw new Error('Unable to resolve the player internal base URL.');
|
||||
}
|
||||
@@ -79,34 +38,28 @@ function createWebBootstrap(options) {
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function storePlayerSnapshot(slug, connections) {
|
||||
const normalizedSlug = String(slug || '').trim();
|
||||
const normalizedConnections = Array.isArray(connections) ? connections : [];
|
||||
playerSnapshotCache.set(normalizedSlug, {
|
||||
slug: normalizedSlug,
|
||||
count: normalizedConnections.length,
|
||||
connections: normalizedConnections
|
||||
});
|
||||
}
|
||||
|
||||
function clearPlayerSnapshotSocket(slug) {
|
||||
const key = String(slug || '').trim();
|
||||
playerSnapshotSockets.delete(key);
|
||||
}
|
||||
|
||||
function ensurePlayerSnapshotSubscription(slug) {
|
||||
if (options && typeof options.ensurePlayerSnapshotSubscription === 'function' && options.ensurePlayerSnapshotSubscription !== ensurePlayerSnapshotSubscription) {
|
||||
return options.ensurePlayerSnapshotSubscription(slug);
|
||||
}
|
||||
|
||||
const key = String(slug || '').trim();
|
||||
if (!key || playerSnapshotSockets.has(key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
playerSnapshotSockets.set(key, null);
|
||||
const socketUrlPromise = getPlayerSnapshotSocketUrl(key);
|
||||
const authHeaders = createRequestAuthHeaders({
|
||||
method: 'GET',
|
||||
pathname: `/ws/screens/${encodeURIComponent(key)}/events`
|
||||
});
|
||||
socketUrlPromise.then(function (socketUrl) {
|
||||
|
||||
Promise.resolve(getPlayerSnapshotSocketUrl(key)).then(function (socketUrl) {
|
||||
const socket = new WebSocket(socketUrl, {
|
||||
headers: authHeaders
|
||||
});
|
||||
@@ -118,7 +71,11 @@ function createWebBootstrap(options) {
|
||||
if (!payload || payload.type !== 'snapshot' || payload.slug !== key) {
|
||||
return;
|
||||
}
|
||||
storePlayerSnapshot(key, payload.connections || []);
|
||||
playerSnapshotCache.set(key, {
|
||||
slug: key,
|
||||
count: Array.isArray(payload.connections) ? payload.connections.length : 0,
|
||||
connections: Array.isArray(payload.connections) ? payload.connections : []
|
||||
});
|
||||
if (broadcastDashboardState) {
|
||||
broadcastDashboardState().catch(function (error) {
|
||||
console.error(error);
|
||||
@@ -152,10 +109,10 @@ function createWebBootstrap(options) {
|
||||
const dashboardStateService = createDashboardStateService({
|
||||
pool: pool,
|
||||
common: common,
|
||||
thinClientBaseUrl: configuredBridgeInternalUrl,
|
||||
playerSnapshotCache: playerSnapshotCache,
|
||||
playerSnapshotSockets: playerSnapshotSockets,
|
||||
ensurePlayerSnapshotSubscription: ensurePlayerSnapshotSubscription,
|
||||
playerPublicBaseUrl: playerPublicBaseUrl,
|
||||
formatDashboardDate: formatDashboardDate
|
||||
});
|
||||
const buildDashboardState = dashboardStateService.buildDashboardState;
|
||||
@@ -163,7 +120,7 @@ function createWebBootstrap(options) {
|
||||
const uploadSyncService = createUploadSyncService({
|
||||
pool: pool,
|
||||
common: common,
|
||||
playerInternalBaseUrl: configuredPlayerInternalBaseUrl,
|
||||
playerInternalBaseUrl: configuredPlayerInternalUrl,
|
||||
playerSnapshotCache: playerSnapshotCache,
|
||||
notifyPlayerScreens: notifyPlayerScreens,
|
||||
backgroundTaskQueue: backgroundTaskQueue
|
||||
@@ -177,12 +134,44 @@ function createWebBootstrap(options) {
|
||||
const collectUploadPathsFromDirectory = uploadSyncService.collectUploadPathsFromDirectory;
|
||||
const syncPlaylistUploadsOnChange = uploadSyncService.syncPlaylistUploadsOnChange;
|
||||
const runMediaSyncTask = uploadSyncService.runMediaSyncTask;
|
||||
let lastDashboardState = null;
|
||||
|
||||
function getFallbackDashboardState() {
|
||||
return lastDashboardState || {
|
||||
playlists: [],
|
||||
screens: [],
|
||||
clients: [],
|
||||
kioskPlayers: [],
|
||||
slides: [],
|
||||
playerServiceConnected: false,
|
||||
connectedPlayersCount: 0,
|
||||
connectedClientsCount: 0
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveDashboardState() {
|
||||
try {
|
||||
const state = await buildDashboardState();
|
||||
lastDashboardState = state;
|
||||
return state;
|
||||
} catch (error) {
|
||||
if (lastDashboardState) {
|
||||
console.error(error);
|
||||
return lastDashboardState;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function sendDashboardStateToSocket(socket) {
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN) {
|
||||
return;
|
||||
}
|
||||
const state = await buildDashboardState();
|
||||
const state = await resolveDashboardState().catch(function (error) {
|
||||
console.error(error);
|
||||
return getFallbackDashboardState();
|
||||
});
|
||||
socket.send(JSON.stringify({ type: 'dashboard-state', state: state }));
|
||||
}
|
||||
|
||||
@@ -192,7 +181,10 @@ function createWebBootstrap(options) {
|
||||
}
|
||||
|
||||
dashboardRefreshInFlight = (async function () {
|
||||
const state = await buildDashboardState();
|
||||
const state = await resolveDashboardState().catch(function (error) {
|
||||
console.error(error);
|
||||
return getFallbackDashboardState();
|
||||
});
|
||||
const payload = JSON.stringify({ type: 'dashboard-state', state: state });
|
||||
for (const socket of dashboardClients) {
|
||||
if (socket && socket.readyState === WebSocket.OPEN) {
|
||||
@@ -261,6 +253,7 @@ function createWebBootstrap(options) {
|
||||
return {
|
||||
upload: upload,
|
||||
uploadSyncService: uploadSyncService,
|
||||
playerInternalBaseUrl: configuredPlayerInternalUrl || null,
|
||||
buildDashboardState: buildDashboardState,
|
||||
collectUploadReferencesFromSlide: collectUploadReferencesFromSlide,
|
||||
collectUploadReferencesFromTemplate: collectUploadReferencesFromTemplate,
|
||||
|
||||
+19
-3
@@ -28,6 +28,15 @@ function registerGeneralHelpers(Handlebars) {
|
||||
|
||||
return `${text.slice(0, Math.max(0, limit - 1)).trimEnd()}…`;
|
||||
});
|
||||
|
||||
Handlebars.registerHelper('textLengthAttrs', function (maxLength) {
|
||||
const limit = Number(maxLength);
|
||||
if (!Number.isFinite(limit) || limit < 1) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return new Handlebars.SafeString(`maxlength="${Handlebars.escapeExpression(String(Math.floor(limit)))}" data-limit-text-length`);
|
||||
});
|
||||
}
|
||||
|
||||
// URL helpers for generating links and external URL checks.
|
||||
@@ -49,7 +58,11 @@ function registerUrlHelpers(Handlebars) {
|
||||
});
|
||||
|
||||
Handlebars.registerHelper('playerUrl', function (slug) {
|
||||
const base = (process.env.PLAYER_PUBLIC_BASE_URL || process.env.PLAYER_BASE_URL || 'http://localhost:3001').replace(/\/$/, '');
|
||||
const base = String(arguments[1] || '').trim().replace(/\/$/, '');
|
||||
if (!base) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return `${base}/screen/${encodeURIComponent(slug)}`;
|
||||
});
|
||||
}
|
||||
@@ -112,12 +125,14 @@ function registerActionHelpers(Handlebars) {
|
||||
label: String(hash.deleteLabel || 'Delete'),
|
||||
className: String(hash.deleteClass || 'btn btn-danger'),
|
||||
url: String(hash.deleteUrl || '').trim(),
|
||||
formId: String(hash.deleteFormId || '').trim(),
|
||||
confirmMessage: String(hash.deleteConfirmMessage || '').trim(),
|
||||
disabled: hash.deleteDisabled === undefined ? false : String(hash.deleteDisabled).toLowerCase() !== 'false',
|
||||
title: String(hash.deleteTitle || '')
|
||||
};
|
||||
|
||||
const resolvedDeleteUrl = deleteAction.url || (!deleteAction.disabled && saveUrl ? saveUrl.replace(/\/+$/, '') + '/delete' : '');
|
||||
const resolvedDeleteFormId = deleteAction.formId || '';
|
||||
|
||||
if (!formId) {
|
||||
return '';
|
||||
@@ -141,10 +156,11 @@ function registerActionHelpers(Handlebars) {
|
||||
}
|
||||
|
||||
if (showDelete && (deleteAction.disabled || resolvedDeleteUrl)) {
|
||||
const deleteActionAttr = resolvedDeleteUrl ? ` data-delete-action-url="${escape(resolvedDeleteUrl)}"` : '';
|
||||
const deleteActionAttr = resolvedDeleteUrl && !resolvedDeleteFormId ? ` data-delete-action-url="${escape(resolvedDeleteUrl)}"` : '';
|
||||
const deleteFormAttr = resolvedDeleteFormId ? ` form="${escape(resolvedDeleteFormId)}"` : '';
|
||||
const confirmAttr = deleteAction.confirmMessage ? ` data-confirm-message="${escape(deleteAction.confirmMessage)}"` : '';
|
||||
const titleAttr = deleteAction.disabled && deleteAction.title ? ` title="${escape(deleteAction.title)}"` : '';
|
||||
parts.push(`<button type="button" class="${escape(deleteAction.className)}"${deleteActionAttr}${confirmAttr}${deleteAction.disabled ? ' disabled' : ''}${titleAttr}>${escape(deleteAction.label)}</button>`);
|
||||
parts.push(`<button type="${resolvedDeleteFormId ? 'submit' : 'button'}" class="${escape(deleteAction.className)}"${deleteFormAttr}${deleteActionAttr}${confirmAttr}${deleteAction.disabled ? ' disabled' : ''}${titleAttr}>${escape(deleteAction.label)}</button>`);
|
||||
}
|
||||
|
||||
parts.push('</div>');
|
||||
|
||||
@@ -2,6 +2,35 @@
|
||||
|
||||
const { normalizePermissionKeys } = require('#src/rbac');
|
||||
|
||||
function getRequestOrigin(req) {
|
||||
const forwardedProto = String(req && req.headers && req.headers['x-forwarded-proto'] || '').trim().split(',')[0];
|
||||
const protocol = forwardedProto || (req && req.socket && req.socket.encrypted ? 'https' : 'http');
|
||||
const forwardedHost = String(req && req.headers && req.headers['x-forwarded-host'] || '').trim().split(',')[0];
|
||||
const host = forwardedHost || String(req && req.headers && req.headers.host || '').trim();
|
||||
return host ? `${protocol}://${host}`.replace(/\/$/, '') : 'http://localhost';
|
||||
}
|
||||
|
||||
function normalizeReturnToPath(value, baseUrl) {
|
||||
const rawValue = String(value || '').trim();
|
||||
if (!rawValue) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const normalizedBaseUrl = String(baseUrl || '').trim().replace(/\/$/, '') || 'http://localhost';
|
||||
|
||||
try {
|
||||
const parsed = new URL(rawValue, normalizedBaseUrl);
|
||||
const baseOrigin = new URL(normalizedBaseUrl).origin;
|
||||
if (parsed.origin !== baseOrigin) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return parsed.pathname + parsed.search + parsed.hash;
|
||||
} catch (_error) {
|
||||
return rawValue.charAt(0) === '/' ? rawValue : '';
|
||||
}
|
||||
}
|
||||
|
||||
function createSessionService(options) {
|
||||
const sessionCookieName = String(options && options.sessionCookieName || '').trim();
|
||||
const sessionMaxAgeMs = Number(options && options.sessionMaxAgeMs);
|
||||
@@ -142,7 +171,8 @@ function createSessionService(options) {
|
||||
return next();
|
||||
}
|
||||
setAuthMessageCookie(res, 'Please sign in to continue.');
|
||||
res.redirect('/login');
|
||||
const returnTo = normalizeReturnToPath(req && (req.originalUrl || req.url || req.path), getRequestOrigin(req));
|
||||
res.redirect(returnTo ? '/login?returnTo=' + encodeURIComponent(returnTo) : '/login');
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -154,8 +184,9 @@ function createSessionService(options) {
|
||||
consumeAuthMessageCookie: consumeAuthMessageCookie,
|
||||
loadCurrentUser: loadCurrentUser,
|
||||
createUserSession: createUserSession,
|
||||
requireAuth: requireAuth
|
||||
requireAuth: requireAuth,
|
||||
getRequestOrigin: getRequestOrigin
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createSessionService };
|
||||
module.exports = { createSessionService, normalizeReturnToPath, getRequestOrigin };
|
||||
@@ -1,16 +1,18 @@
|
||||
const { resolvePlayerRegistration } = require('#src/data/player-registry');
|
||||
|
||||
const TASK = {
|
||||
taskType: 'slide-thumbnail-refresh'
|
||||
};
|
||||
|
||||
async function fetchPlayerInternalBaseUrl(pool) {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT internal_base_url
|
||||
FROM d_players
|
||||
WHERE device_id = '1'
|
||||
LIMIT 1`
|
||||
);
|
||||
async function fetchPlayerInternalBaseUrl(pool, configuredPlayerInternalBaseUrl) {
|
||||
const configured = String(configuredPlayerInternalBaseUrl || '').trim().replace(/\/$/, '');
|
||||
if (configured) {
|
||||
return configured;
|
||||
}
|
||||
|
||||
return String(rows && rows[0] && rows[0].internal_base_url || '').trim().replace(/\/$/, '') || null;
|
||||
const { getConfiguredPlayerIdentifier } = require('#src/data/player-registry');
|
||||
const player = await resolvePlayerRegistration(pool, getConfiguredPlayerIdentifier());
|
||||
return String(player && player.internal_base_url || '').trim().replace(/\/$/, '') || null;
|
||||
}
|
||||
|
||||
function registerSlideThumbnailRefreshTask(options) {
|
||||
@@ -19,6 +21,7 @@ function registerSlideThumbnailRefreshTask(options) {
|
||||
const pool = options && options.pool;
|
||||
const common = options && options.common;
|
||||
const mediaDir = String(options && options.mediaDir || '').trim();
|
||||
const configuredWebBaseUrl = String(options && options.webBaseUrl || '').trim().replace(/\/$/, '');
|
||||
|
||||
if (!backgroundTaskQueue || typeof captureSlideThumbnail !== 'function' || !pool || !common || !mediaDir) {
|
||||
throw new Error('registerSlideThumbnailRefreshTask requires the slide thumbnail dependencies.');
|
||||
@@ -32,18 +35,19 @@ function registerSlideThumbnailRefreshTask(options) {
|
||||
throw new Error('Slide id is required.');
|
||||
}
|
||||
|
||||
const playerInternalBaseUrl = await fetchPlayerInternalBaseUrl(pool);
|
||||
if (!playerInternalBaseUrl) {
|
||||
throw new Error('Player internal base URL is required.');
|
||||
const webBaseUrl = configuredWebBaseUrl || `http://127.0.0.1:${Number(process.env.WEB_PORT || 8080)}`;
|
||||
if (!webBaseUrl) {
|
||||
throw new Error('Web base URL is required.');
|
||||
}
|
||||
|
||||
return captureSlideThumbnail({
|
||||
pool: pool,
|
||||
common: common,
|
||||
mediaDir: mediaDir,
|
||||
baseUrl: playerInternalBaseUrl,
|
||||
baseUrl: webBaseUrl,
|
||||
slideId: slideId,
|
||||
previousThumbnailPath: payload.previousThumbnailPath || null
|
||||
previousThumbnailPath: payload.previousThumbnailPath || null,
|
||||
fontStylesheetHref: payload.fontStylesheetHref || ''
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
const { resolvePlayerRegistration } = require('#src/data/player-registry');
|
||||
|
||||
const TASK = {
|
||||
taskType: 'template-slide-thumbnail-refresh'
|
||||
};
|
||||
|
||||
async function fetchPlayerInternalBaseUrl(pool) {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT internal_base_url
|
||||
FROM d_players
|
||||
WHERE device_id = '1'
|
||||
LIMIT 1`
|
||||
);
|
||||
async function fetchPlayerInternalBaseUrl(pool, configuredPlayerInternalBaseUrl) {
|
||||
const configured = String(configuredPlayerInternalBaseUrl || '').trim().replace(/\/$/, '');
|
||||
if (configured) {
|
||||
return configured;
|
||||
}
|
||||
|
||||
return String(rows && rows[0] && rows[0].internal_base_url || '').trim().replace(/\/$/, '') || null;
|
||||
const { getConfiguredPlayerIdentifier } = require('#src/data/player-registry');
|
||||
const player = await resolvePlayerRegistration(pool, getConfiguredPlayerIdentifier());
|
||||
return String(player && player.internal_base_url || '').trim().replace(/\/$/, '') || null;
|
||||
}
|
||||
|
||||
function registerTemplateSlideThumbnailRefreshTask(options) {
|
||||
@@ -19,6 +21,7 @@ function registerTemplateSlideThumbnailRefreshTask(options) {
|
||||
const pool = options && options.pool;
|
||||
const common = options && options.common;
|
||||
const mediaDir = String(options && options.mediaDir || '').trim();
|
||||
const configuredWebBaseUrl = String(options && options.webBaseUrl || '').trim().replace(/\/$/, '');
|
||||
|
||||
if (!backgroundTaskQueue || typeof captureSlideThumbnail !== 'function' || !pool || !common || !mediaDir) {
|
||||
throw new Error('registerTemplateSlideThumbnailRefreshTask requires the template thumbnail dependencies.');
|
||||
@@ -32,9 +35,9 @@ function registerTemplateSlideThumbnailRefreshTask(options) {
|
||||
throw new Error('Template id is required.');
|
||||
}
|
||||
|
||||
const playerInternalBaseUrl = await fetchPlayerInternalBaseUrl(pool);
|
||||
if (!playerInternalBaseUrl) {
|
||||
throw new Error('Player internal base URL is required.');
|
||||
const webBaseUrl = configuredWebBaseUrl || `http://127.0.0.1:${Number(process.env.WEB_PORT || 8080)}`;
|
||||
if (!webBaseUrl) {
|
||||
throw new Error('Web base URL is required.');
|
||||
}
|
||||
|
||||
const [slides] = await pool.query(
|
||||
@@ -52,7 +55,7 @@ function registerTemplateSlideThumbnailRefreshTask(options) {
|
||||
pool: pool,
|
||||
common: common,
|
||||
mediaDir: mediaDir,
|
||||
baseUrl: playerInternalBaseUrl,
|
||||
baseUrl: webBaseUrl,
|
||||
slideId: slideId,
|
||||
previousThumbnailPath: slide && slide.thumbnail_path ? slide.thumbnail_path : null
|
||||
});
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
const TASK = {
|
||||
key: 'onboarding-device-prune',
|
||||
title: 'Onboarding device prune',
|
||||
category: 'cleanup',
|
||||
trigger: 'scheduled recurring task, hourly',
|
||||
purpose: 'remove stale onboarding device bindings that have been idle for more than one minute.',
|
||||
taskType: 'recurring-run',
|
||||
intervalMs: 60 * 60 * 1000
|
||||
};
|
||||
|
||||
function registerOnboardingDevicePruneTask(options) {
|
||||
const backgroundTaskQueue = options && options.backgroundTaskQueue;
|
||||
const pool = options && options.pool;
|
||||
const common = options && options.common;
|
||||
|
||||
if (!backgroundTaskQueue || !pool || !common || typeof common.pruneStaleOnboardingDevices !== 'function') {
|
||||
throw new Error('registerOnboardingDevicePruneTask requires the onboarding prune dependencies.');
|
||||
}
|
||||
|
||||
backgroundTaskQueue.registerRecurringTask({
|
||||
key: TASK.key,
|
||||
title: TASK.title,
|
||||
category: TASK.category,
|
||||
intervalMs: TASK.intervalMs,
|
||||
metadata: {},
|
||||
run: async function () {
|
||||
await common.pruneStaleOnboardingDevices(pool);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { registerOnboardingDevicePruneTask };
|
||||
@@ -8,22 +8,30 @@ const TASK = {
|
||||
function registerInitialFontSyncTask(options) {
|
||||
const backgroundTaskQueue = options && options.backgroundTaskQueue;
|
||||
const mediaDir = String(options && options.mediaDir || '').trim();
|
||||
const uploadSyncService = options && options.uploadSyncService;
|
||||
|
||||
if (!backgroundTaskQueue || !mediaDir) {
|
||||
throw new Error('registerInitialFontSyncTask requires the initial font sync dependencies.');
|
||||
}
|
||||
|
||||
const metadataPromise = uploadSyncService && typeof uploadSyncService.getPlayerTaskMetadata === 'function'
|
||||
? uploadSyncService.getPlayerTaskMetadata()
|
||||
: Promise.resolve({});
|
||||
|
||||
return Promise.resolve(metadataPromise).then(function (metadata) {
|
||||
return backgroundTaskQueue.enqueueTask({
|
||||
key: TASK.key,
|
||||
title: 'Initial font sync',
|
||||
category: TASK.category,
|
||||
taskType: 'font-sync',
|
||||
metadata: Object.assign({}, metadata || {}),
|
||||
payload: {
|
||||
mode: 'initial',
|
||||
uploadDir: mediaDir,
|
||||
operations: collectFontLibrarySyncOperations(mediaDir)
|
||||
},
|
||||
persist: true
|
||||
});
|
||||
}).catch(function (error) {
|
||||
console.warn('Unable to queue initial font sync:', error);
|
||||
});
|
||||
|
||||
@@ -6,21 +6,29 @@ const TASK = {
|
||||
function registerInitialMediaSyncTask(options) {
|
||||
const backgroundTaskQueue = options && options.backgroundTaskQueue;
|
||||
const mediaDir = String(options && options.mediaDir || '').trim();
|
||||
const uploadSyncService = options && options.uploadSyncService;
|
||||
|
||||
if (!backgroundTaskQueue || !mediaDir) {
|
||||
throw new Error('registerInitialMediaSyncTask requires the initial media sync dependencies.');
|
||||
}
|
||||
|
||||
const metadataPromise = uploadSyncService && typeof uploadSyncService.getPlayerTaskMetadata === 'function'
|
||||
? uploadSyncService.getPlayerTaskMetadata()
|
||||
: Promise.resolve({});
|
||||
|
||||
return Promise.resolve(metadataPromise).then(function (metadata) {
|
||||
return backgroundTaskQueue.enqueueTask({
|
||||
key: TASK.key,
|
||||
title: 'Initial media sync',
|
||||
category: TASK.category,
|
||||
taskType: 'media-sync',
|
||||
metadata: Object.assign({}, metadata || {}),
|
||||
payload: {
|
||||
mode: 'initial',
|
||||
uploadDir: mediaDir
|
||||
},
|
||||
persist: true
|
||||
});
|
||||
}).catch(function (error) {
|
||||
console.warn('Unable to queue initial media sync:', error);
|
||||
});
|
||||
|
||||
@@ -5,8 +5,9 @@ function createWebConfig() {
|
||||
const uploadsDir = path.join(mediaDir, 'uploads');
|
||||
const thumbnailsDir = path.join(mediaDir, 'thumbnails');
|
||||
const assetDir = path.join(__dirname, '..', 'public');
|
||||
const playerInternalBaseUrl = (process.env.PLAYER_INTERNAL_BASE_URL || process.env.PLAYER_BASE_URL || 'http://player:8081').replace(/\/$/, '');
|
||||
const playerPublicBaseUrl = (process.env.PLAYER_PUBLIC_BASE_URL || process.env.PLAYER_BASE_URL || 'http://localhost:8081').replace(/\/$/, '');
|
||||
const playerInternalUrl = (process.env.PLAYER_INTERNAL_URL || process.env.PLAYER_BASE_URL || 'http://player:8081').replace(/\/$/, '');
|
||||
const bridgeInternalUrl = (process.env.BRIDGE_INTERNAL_URL || 'http://player-bridge:8090').replace(/\/$/, '');
|
||||
const webInternalUrl = (process.env.WEB_INTERNAL_URL || `http://127.0.0.1:${Number(process.env.WEB_PORT || 8080)}`).replace(/\/$/, '');
|
||||
const sessionCookieName = 'digital_signage_session';
|
||||
const sessionMaxAgeDays = Number(process.env.SESSION_MAX_AGE_DAYS || 14);
|
||||
const sessionMaxAgeMs = (Number.isFinite(sessionMaxAgeDays) && sessionMaxAgeDays > 0 ? sessionMaxAgeDays : 14) * 24 * 60 * 60 * 1000;
|
||||
@@ -19,8 +20,9 @@ function createWebConfig() {
|
||||
uploadsDir: uploadsDir,
|
||||
thumbnailsDir: thumbnailsDir,
|
||||
assetDir: assetDir,
|
||||
playerInternalBaseUrl: playerInternalBaseUrl,
|
||||
playerPublicBaseUrl: playerPublicBaseUrl,
|
||||
playerInternalUrl: playerInternalUrl,
|
||||
bridgeInternalUrl: bridgeInternalUrl,
|
||||
webInternalUrl: webInternalUrl,
|
||||
sessionCookieName: sessionCookieName,
|
||||
sessionMaxAgeMs: sessionMaxAgeMs,
|
||||
dataSourceStartupRefreshStaggerMs: dataSourceStartupRefreshStaggerMs
|
||||
|
||||
@@ -6,6 +6,10 @@ function normalizeClientName(value) {
|
||||
return String(value || '').trim();
|
||||
}
|
||||
|
||||
function normalizePlayerBaseUrl(value) {
|
||||
return String(value || '').trim().replace(/\/$/, '');
|
||||
}
|
||||
|
||||
function enrichScreensWithConnections(screens, connectionsBySlug, onboardingNameBySlug, playerUrlsBySlug) {
|
||||
return (screens || []).map(function (screen) {
|
||||
const connectionState = connectionsBySlug[screen.slug] || { count: 0, connections: [] };
|
||||
@@ -18,11 +22,12 @@ function enrichScreensWithConnections(screens, connectionsBySlug, onboardingName
|
||||
});
|
||||
}
|
||||
|
||||
function buildClientRows(screens, connectionsBySlug, onboardingNameBySlug, onboardingNameByDeviceId, formatDashboardDate) {
|
||||
function buildClientRows(screens, connectionsBySlug, onboardingNameBySlug, onboardingNameByDeviceId, playerIdentifierByBaseUrl, formatDashboardDate) {
|
||||
return (screens || []).flatMap(function (screen) {
|
||||
const connectionState = connectionsBySlug[screen.slug] || { count: 0, connections: [] };
|
||||
return (connectionState.connections || []).map(function (connection) {
|
||||
const deviceId = String(connection.deviceId || '').trim();
|
||||
const playerBaseUrl = normalizePlayerBaseUrl(connection.playerPublicBaseUrl);
|
||||
return Object.assign({}, connection, {
|
||||
screen_slug: screen.slug,
|
||||
screen_name: screen.name,
|
||||
@@ -30,12 +35,55 @@ function buildClientRows(screens, connectionsBySlug, onboardingNameBySlug, onboa
|
||||
playlist_name: screen.playlist_name || null,
|
||||
connectedAtLabel: formatDashboardDate(connection.connectedAt),
|
||||
lastSeenAtLabel: formatDashboardDate(connection.lastSeenAt),
|
||||
player_url: screen.player_url || String(connection.page || '').trim() || null
|
||||
player_identifier: playerIdentifierByBaseUrl && playerBaseUrl ? (playerIdentifierByBaseUrl[playerBaseUrl] || null) : null,
|
||||
player_url: playerBaseUrl || null
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function isRecentPlayerRegistration(player, staleSeconds) {
|
||||
const lastSeenAt = player && player.last_seen_at;
|
||||
const lastSeenAtValue = lastSeenAt instanceof Date ? lastSeenAt.getTime() : new Date(lastSeenAt).getTime();
|
||||
const cutoffTime = Date.now() - Math.max(30, Number(staleSeconds || 60)) * 1000;
|
||||
|
||||
return Number.isFinite(lastSeenAtValue) && lastSeenAtValue >= cutoffTime;
|
||||
}
|
||||
|
||||
function buildKioskLauncherPlayers(playerRegistrations, staleSeconds) {
|
||||
return (Array.isArray(playerRegistrations) ? playerRegistrations : [])
|
||||
.filter(function (player) {
|
||||
return Boolean(player && String(player.identifier || '').trim() && String(player.public_base_url || '').trim() && isRecentPlayerRegistration(player, staleSeconds));
|
||||
})
|
||||
.map(function (player) {
|
||||
return {
|
||||
player_identifier: String(player.identifier || '').trim(),
|
||||
player_url: String(player.public_base_url || '').trim().replace(/\/$/, '')
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchConnectedPlayerCount(pool, connectedPlayerCountStaleSeconds) {
|
||||
const staleSeconds = Math.max(30, Number(connectedPlayerCountStaleSeconds || 60));
|
||||
if (!pool || typeof pool.query !== 'function' || !Number.isFinite(staleSeconds)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT COUNT(*) AS connected_count
|
||||
FROM d_players
|
||||
WHERE last_seen_at IS NOT NULL
|
||||
AND last_seen_at >= DATE_SUB(NOW(), INTERVAL ${staleSeconds} SECOND)`
|
||||
);
|
||||
|
||||
const count = Number(rows && rows[0] && rows[0].connected_count);
|
||||
return Number.isFinite(count) && count >= 0 ? count : null;
|
||||
} catch (_error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function compareScreenNames(left, right) {
|
||||
const leftName = String(left && left.name || '').trim();
|
||||
const rightName = String(right && right.name || '').trim();
|
||||
@@ -51,6 +99,7 @@ function compareScreenNames(left, right) {
|
||||
function createDashboardStateService(options) {
|
||||
const pool = options && options.pool;
|
||||
const common = options && options.common;
|
||||
const connectedPlayerCountStaleSeconds = options && options.connectedPlayerCountStaleSeconds;
|
||||
const playerSnapshotCache = options && options.playerSnapshotCache;
|
||||
const playerSnapshotSockets = options && options.playerSnapshotSockets;
|
||||
const ensurePlayerSnapshotSubscription = options && options.ensurePlayerSnapshotSubscription;
|
||||
@@ -63,11 +112,19 @@ function createDashboardStateService(options) {
|
||||
async function buildDashboardState() {
|
||||
const data = await common.fetchAdminData(pool);
|
||||
const screensData = data.screens || [];
|
||||
const connectedPlayersCount = await fetchConnectedPlayerCount(pool, connectedPlayerCountStaleSeconds);
|
||||
const playerUrlsBySlug = typeof common.fetchScreenPlayerUrls === 'function'
|
||||
? await common.fetchScreenPlayerUrls(pool)
|
||||
: {};
|
||||
const playerRegistrations = typeof common.fetchPlayerRegistrations === 'function'
|
||||
? await common.fetchPlayerRegistrations(pool)
|
||||
: [];
|
||||
screensData.forEach(function (screen) {
|
||||
try {
|
||||
ensurePlayerSnapshotSubscription(screen.slug);
|
||||
} catch (_error) {
|
||||
// Keep building dashboard state when one player snapshot subscription fails.
|
||||
}
|
||||
});
|
||||
|
||||
const [onboardingRows] = await pool.query(
|
||||
@@ -91,6 +148,15 @@ function createDashboardStateService(options) {
|
||||
}
|
||||
});
|
||||
|
||||
const playerIdentifierByBaseUrl = {};
|
||||
(Array.isArray(playerRegistrations) ? playerRegistrations : []).forEach(function (player) {
|
||||
const baseUrl = normalizePlayerBaseUrl(player && player.public_base_url);
|
||||
const identifier = normalizeClientName(player && player.identifier);
|
||||
if (baseUrl && identifier) {
|
||||
playerIdentifierByBaseUrl[baseUrl] = identifier;
|
||||
}
|
||||
});
|
||||
|
||||
const connectionsBySlug = {};
|
||||
screensData.forEach(function (screen) {
|
||||
const cached = playerSnapshotCache.get(String(screen.slug || '').trim());
|
||||
@@ -106,7 +172,8 @@ function createDashboardStateService(options) {
|
||||
});
|
||||
})
|
||||
.sort(compareScreenNames);
|
||||
const clients = buildClientRows(screens, connectionsBySlug, onboardingNameBySlug, onboardingNameByDeviceId, formatDashboardDate);
|
||||
const clients = buildClientRows(screens, connectionsBySlug, onboardingNameBySlug, onboardingNameByDeviceId, playerIdentifierByBaseUrl, formatDashboardDate);
|
||||
const kioskPlayers = buildKioskLauncherPlayers(playerRegistrations, connectedPlayerCountStaleSeconds);
|
||||
const playerServiceConnected = Array.from(playerSnapshotSockets.values()).some(function (socket) {
|
||||
return socket && socket.readyState === WebSocket.OPEN;
|
||||
});
|
||||
@@ -115,8 +182,10 @@ function createDashboardStateService(options) {
|
||||
playlists: data.playlists || [],
|
||||
screens: screens,
|
||||
clients: clients,
|
||||
kioskPlayers: kioskPlayers,
|
||||
slides: data.slides || [],
|
||||
playerServiceConnected: playerServiceConnected,
|
||||
connectedPlayersCount: connectedPlayersCount !== null ? connectedPlayersCount : 0,
|
||||
connectedClientsCount: screens.reduce(function (total, screen) {
|
||||
return total + Number(screen.player_connection_count || 0);
|
||||
}, 0)
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
module.exports = {
|
||||
createUploadSyncService: require('./upload-sync').createUploadSyncService,
|
||||
captureSlideThumbnail: require('./slide-thumbnails').captureSlideThumbnail,
|
||||
captureSlideThumbnail: function captureSlideThumbnail(options) {
|
||||
return require('./slide-thumbnails').captureSlideThumbnail(options);
|
||||
},
|
||||
fontLibrary: require('./font-library')
|
||||
};
|
||||
@@ -0,0 +1,156 @@
|
||||
// Pure thumbnail preview payload helpers shared by routes and screenshot capture.
|
||||
|
||||
const {
|
||||
escapeHtml,
|
||||
renderEditorJsContent,
|
||||
sanitizeFontFamily,
|
||||
sanitizeFontSize,
|
||||
sanitizeTextColor
|
||||
} = require('#src/player/render-helpers');
|
||||
|
||||
function normalizeBaseUrl(baseUrl) {
|
||||
return String(baseUrl || '').trim().replace(/\/$/, '');
|
||||
}
|
||||
|
||||
function resolveAssetUrl(baseUrl, value) {
|
||||
const raw = String(value || '').trim();
|
||||
if (!raw) {
|
||||
return '';
|
||||
}
|
||||
if (/^(?:https?:)?\/\//i.test(raw) || raw.startsWith('data:')) {
|
||||
return raw;
|
||||
}
|
||||
const normalizedBaseUrl = normalizeBaseUrl(baseUrl);
|
||||
if (!normalizedBaseUrl) {
|
||||
return raw;
|
||||
}
|
||||
if (raw.startsWith('/')) {
|
||||
return normalizedBaseUrl + raw;
|
||||
}
|
||||
return normalizedBaseUrl + '/' + raw.replace(/^\/+/, '');
|
||||
}
|
||||
|
||||
function getThumbnailCanvasSize(slide) {
|
||||
const template = slide && slide.template ? slide.template : null;
|
||||
return {
|
||||
width: Math.max(1, Number(template && template.canvas_size_width ? template.canvas_size_width : 1920)),
|
||||
height: Math.max(1, Number(template && template.canvas_size_height ? template.canvas_size_height : 1080))
|
||||
};
|
||||
}
|
||||
|
||||
function getRegionContent(slide, region) {
|
||||
const content = slide && slide.content && slide.content[region.region_key] ? slide.content[region.region_key] : {};
|
||||
return content && typeof content === 'object' ? content : { value: content };
|
||||
}
|
||||
|
||||
function buildThumbnailRegionStyle(region, canvasWidth, canvasHeight) {
|
||||
const left = Number.isFinite(Number(region && region.x)) && canvasWidth > 0 ? (Number(region.x) / canvasWidth) * 100 : 0;
|
||||
const top = Number.isFinite(Number(region && region.y)) && canvasHeight > 0 ? (Number(region.y) / canvasHeight) * 100 : 0;
|
||||
const width = Number.isFinite(Number(region && region.width)) && canvasWidth > 0 ? (Number(region.width) / canvasWidth) * 100 : 0;
|
||||
const height = Number.isFinite(Number(region && region.height)) && canvasHeight > 0 ? (Number(region.height) / canvasHeight) * 100 : 0;
|
||||
|
||||
return 'left:' + left + '%;top:' + top + '%;width:' + width + '%;height:' + height + '%;z-index:' + Number(region && region.z_index || 0) + ';';
|
||||
}
|
||||
|
||||
function hasVisibleContent(html) {
|
||||
return Boolean(String(html || '').replace(/<[^>]+>/g, '').trim());
|
||||
}
|
||||
|
||||
function buildTextRegionMarkup(region, regionContent) {
|
||||
const fontFamily = sanitizeFontFamily(regionContent.font_family || region.font_family);
|
||||
const fontSize = sanitizeFontSize(regionContent.font_size || region.font_size);
|
||||
const fontColor = sanitizeTextColor(regionContent.font_color || region.font_color);
|
||||
const renderedBody = renderEditorJsContent(regionContent.value || '');
|
||||
if (!hasVisibleContent(renderedBody)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return '<div class="slide-preview-region slide-preview-text-region" style="' + region.baseStyle + '"><div class="slide-preview-text-content" style="width:' + region.pixelWidth + 'px;height:' + region.pixelHeight + 'px;overflow:hidden;' + (fontFamily ? 'font-family:' + escapeHtml(fontFamily) + ';' : '') + 'font-size:' + fontSize + 'px;color:' + escapeHtml(fontColor || '#000000') + ';">' + renderedBody + '</div></div>';
|
||||
}
|
||||
|
||||
function buildRegionInnerHtml(region, regionContent, baseUrl) {
|
||||
const regionType = String(regionContent.type || region.region_type || 'text').trim().toLowerCase();
|
||||
const rawValue = regionContent && regionContent.value !== undefined ? regionContent.value : '';
|
||||
|
||||
if (regionType === 'image') {
|
||||
const src = resolveAssetUrl(baseUrl, rawValue);
|
||||
return src
|
||||
? '<div class="slide-preview-region slide-preview-image-region" style="' + region.baseStyle + '"><img class="slide-preview-image" src="' + escapeHtml(src) + '" alt="' + escapeHtml(region.label || region.region_key || 'image') + '" /></div>'
|
||||
: '';
|
||||
}
|
||||
|
||||
if (regionType === 'video') {
|
||||
const src = resolveAssetUrl(baseUrl, rawValue);
|
||||
return src
|
||||
? '<div class="slide-preview-region slide-preview-video-region" style="' + region.baseStyle + '"><video class="slide-preview-video" src="' + escapeHtml(src) + '" title="' + escapeHtml(region.label || region.region_key || 'video') + '" muted playsinline preload="metadata"></video></div>'
|
||||
: '';
|
||||
}
|
||||
|
||||
if (regionType === 'webpage') {
|
||||
const src = resolveAssetUrl(baseUrl, rawValue);
|
||||
return src
|
||||
? '<div class="slide-preview-region slide-preview-webpage-region" style="' + region.baseStyle + '"><iframe src="' + escapeHtml(src) + '" title="' + escapeHtml(region.label || region.region_key || 'webpage') + '" loading="eager" referrerpolicy="no-referrer" scrolling="no"></iframe></div>'
|
||||
: '';
|
||||
}
|
||||
|
||||
if (regionType === 'qr-code') {
|
||||
const src = String(regionContent.qr_preview || '').trim();
|
||||
const borderRadius = Math.max(0, Math.round(Number(regionContent.qr_border_radius || 0)));
|
||||
const radiusStyle = borderRadius > 0 ? ' style="border-radius:' + borderRadius + 'px;overflow:hidden;"' : '';
|
||||
return src
|
||||
? '<div class="slide-preview-region slide-preview-qr-code-region" style="' + region.baseStyle + radiusStyle + '"><img class="slide-preview-image" src="' + escapeHtml(src) + '" alt="' + escapeHtml(region.label || region.region_key || 'qr code') + '" /></div>'
|
||||
: '';
|
||||
}
|
||||
|
||||
if (regionType === 'html') {
|
||||
const html = String(rawValue || '').trim();
|
||||
return html
|
||||
? '<div class="slide-preview-region slide-preview-html-region" style="' + region.baseStyle + '"><iframe sandbox="" srcdoc="<!doctype html><html><head><style>html,body{margin:0;width:100%;height:100%;overflow:hidden;background:transparent;}</style></head><body>' + escapeHtml(html) + '</body></html>" title="' + escapeHtml(region.label || region.region_key || 'html') + '" loading="eager" scrolling="no"></iframe></div>'
|
||||
: '';
|
||||
}
|
||||
|
||||
if (regionType === 'rtmp') {
|
||||
const label = String(rawValue || '').trim() || 'RTMP source';
|
||||
return '<div class="slide-preview-region slide-preview-rtmp-region" style="' + region.baseStyle + '"><div class="slide-preview-rtmp-placeholder">' + escapeHtml(label) + '</div></div>';
|
||||
}
|
||||
|
||||
return buildTextRegionMarkup(region, regionContent);
|
||||
}
|
||||
|
||||
function buildThumbnailPreviewMarkup(slide, baseUrl) {
|
||||
const template = slide && slide.template ? slide.template : null;
|
||||
if (!template) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const canvasSize = getThumbnailCanvasSize(slide);
|
||||
const normalizedBaseUrl = normalizeBaseUrl(baseUrl);
|
||||
return (Array.isArray(template.regions) ? template.regions : []).map(function (region) {
|
||||
const regionContent = getRegionContent(slide, region);
|
||||
const previewRegion = Object.assign({}, region, {
|
||||
baseStyle: buildThumbnailRegionStyle(region, canvasSize.width, canvasSize.height),
|
||||
pixelWidth: Math.max(1, Math.round(Number(region && region.width || 0) || 1)),
|
||||
pixelHeight: Math.max(1, Math.round(Number(region && region.height || 0) || 1))
|
||||
});
|
||||
return buildRegionInnerHtml(previewRegion, regionContent, normalizedBaseUrl);
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function buildThumbnailPreviewPayload(slide, options) {
|
||||
const template = slide && slide.template ? slide.template : null;
|
||||
const canvasSize = getThumbnailCanvasSize(slide);
|
||||
return {
|
||||
thumbnailPreview: true,
|
||||
canvasWidth: canvasSize.width,
|
||||
canvasHeight: canvasSize.height,
|
||||
backgroundColor: template && template.background_color ? String(template.background_color) : '#111111',
|
||||
backgroundImagePath: template && template.background_image_path ? String(template.background_image_path) : '',
|
||||
fontStylesheetHref: String(options && options.fontStylesheetHref || '').trim(),
|
||||
html: buildThumbnailPreviewMarkup(slide, options && options.baseUrl)
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildThumbnailPreviewPayload: buildThumbnailPreviewPayload,
|
||||
buildThumbnailPreviewMarkup: buildThumbnailPreviewMarkup
|
||||
};
|
||||
@@ -2,14 +2,6 @@
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const puppeteer = require('puppeteer-core');
|
||||
const chromiumModule = require('@sparticuz/chromium');
|
||||
const sharp = require('sharp');
|
||||
const chromium = chromiumModule && typeof chromiumModule.executablePath === 'function'
|
||||
? chromiumModule
|
||||
: chromiumModule && chromiumModule.default && typeof chromiumModule.default.executablePath === 'function'
|
||||
? chromiumModule.default
|
||||
: chromiumModule;
|
||||
const {
|
||||
escapeHtml,
|
||||
mediaKind,
|
||||
@@ -73,6 +65,23 @@ function getRegionContent(slide, region) {
|
||||
return content && typeof content === 'object' ? content : { value: content };
|
||||
}
|
||||
|
||||
function getThumbnailCanvasSize(slide) {
|
||||
const template = slide && slide.template ? slide.template : null;
|
||||
return {
|
||||
width: Math.max(1, Number(template && template.canvas_size_width ? template.canvas_size_width : 1920)),
|
||||
height: Math.max(1, Number(template && template.canvas_size_height ? template.canvas_size_height : 1080))
|
||||
};
|
||||
}
|
||||
|
||||
function buildThumbnailRegionStyle(region, canvasWidth, canvasHeight) {
|
||||
const left = Number.isFinite(Number(region && region.x)) && canvasWidth > 0 ? (Number(region.x) / canvasWidth) * 100 : 0;
|
||||
const top = Number.isFinite(Number(region && region.y)) && canvasHeight > 0 ? (Number(region.y) / canvasHeight) * 100 : 0;
|
||||
const width = Number.isFinite(Number(region && region.width)) && canvasWidth > 0 ? (Number(region.width) / canvasWidth) * 100 : 0;
|
||||
const height = Number.isFinite(Number(region && region.height)) && canvasHeight > 0 ? (Number(region.height) / canvasHeight) * 100 : 0;
|
||||
|
||||
return 'left:' + left + '%;top:' + top + '%;width:' + width + '%;height:' + height + '%;z-index:' + Number(region && region.z_index || 0) + ';';
|
||||
}
|
||||
|
||||
function hasVisibleContent(html) {
|
||||
return Boolean(String(html || '').replace(/<[^>]+>/g, '').trim());
|
||||
}
|
||||
@@ -86,7 +95,7 @@ function buildTextRegionMarkup(region, regionContent) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return '<div class="template-region text" style="' + region.baseStyle + '"><div class="template-region-text-scale" style="width:' + region.pixelWidth + 'px;height:' + region.pixelHeight + 'px;' + (fontFamily ? 'font-family:' + escapeHtml(fontFamily) + ';' : '') + 'font-size:' + fontSize + 'px;color:' + escapeHtml(fontColor || '#000000') + ';">' + renderedBody + '</div></div>';
|
||||
return '<div class="slide-preview-region slide-preview-text-region" style="' + region.baseStyle + '"><div class="slide-preview-text-content" style="width:' + region.pixelWidth + 'px;height:' + region.pixelHeight + 'px;overflow:hidden;' + (fontFamily ? 'font-family:' + escapeHtml(fontFamily) + ';' : '') + 'font-size:' + fontSize + 'px;color:' + escapeHtml(fontColor || '#000000') + ';">' + renderedBody + '</div></div>';
|
||||
}
|
||||
|
||||
function buildRegionInnerHtml(region, regionContent, baseUrl) {
|
||||
@@ -96,40 +105,98 @@ function buildRegionInnerHtml(region, regionContent, baseUrl) {
|
||||
if (regionType === 'image') {
|
||||
const src = resolveAssetUrl(baseUrl, rawValue);
|
||||
return src
|
||||
? '<img src="' + escapeHtml(src) + '" alt="' + escapeHtml(region.label || region.region_key || 'image') + '" />'
|
||||
? '<div class="slide-preview-region slide-preview-image-region" style="' + region.baseStyle + '"><img class="slide-preview-image" src="' + escapeHtml(src) + '" alt="' + escapeHtml(region.label || region.region_key || 'image') + '" /></div>'
|
||||
: '';
|
||||
}
|
||||
|
||||
if (regionType === 'video') {
|
||||
const src = resolveAssetUrl(baseUrl, rawValue);
|
||||
return src
|
||||
? '<video src="' + escapeHtml(src) + '" title="' + escapeHtml(region.label || region.region_key || 'video') + '" muted playsinline preload="metadata"></video>'
|
||||
? '<div class="slide-preview-region slide-preview-video-region" style="' + region.baseStyle + '"><video class="slide-preview-video" src="' + escapeHtml(src) + '" title="' + escapeHtml(region.label || region.region_key || 'video') + '" muted playsinline preload="metadata"></video></div>'
|
||||
: '';
|
||||
}
|
||||
|
||||
if (regionType === 'webpage') {
|
||||
const src = resolveAssetUrl(baseUrl, rawValue);
|
||||
return src
|
||||
? '<iframe src="' + escapeHtml(src) + '" title="' + escapeHtml(region.label || region.region_key || 'webpage') + '" loading="eager" referrerpolicy="no-referrer" scrolling="no"></iframe>'
|
||||
? '<div class="slide-preview-region slide-preview-webpage-region" style="' + region.baseStyle + '"><iframe src="' + escapeHtml(src) + '" title="' + escapeHtml(region.label || region.region_key || 'webpage') + '" loading="eager" referrerpolicy="no-referrer" scrolling="no"></iframe></div>'
|
||||
: '';
|
||||
}
|
||||
|
||||
if (regionType === 'qr-code') {
|
||||
const src = String(regionContent.qr_preview || '').trim();
|
||||
const borderRadius = Math.max(0, Math.round(Number(regionContent.qr_border_radius || 0)));
|
||||
const radiusStyle = borderRadius > 0 ? ' style="border-radius:' + borderRadius + 'px;overflow:hidden;"' : '';
|
||||
return src
|
||||
? '<div class="slide-preview-region slide-preview-qr-code-region" style="' + region.baseStyle + radiusStyle + '"><img class="slide-preview-image" src="' + escapeHtml(src) + '" alt="' + escapeHtml(region.label || region.region_key || 'qr code') + '" /></div>'
|
||||
: '';
|
||||
}
|
||||
|
||||
if (regionType === 'html') {
|
||||
const html = String(rawValue || '').trim();
|
||||
return html
|
||||
? '<iframe sandbox="" srcdoc="<!doctype html><html><head><style>html,body{margin:0;width:100%;height:100%;overflow:hidden;background:transparent;}</style></head><body>' + escapeHtml(html) + '</body></html>" title="' + escapeHtml(region.label || region.region_key || 'html') + '" loading="eager" scrolling="no"></iframe>'
|
||||
? '<div class="slide-preview-region slide-preview-html-region" style="' + region.baseStyle + '"><iframe sandbox="" srcdoc="<!doctype html><html><head><style>html,body{margin:0;width:100%;height:100%;overflow:hidden;background:transparent;}</style></head><body>' + escapeHtml(html) + '</body></html>" title="' + escapeHtml(region.label || region.region_key || 'html') + '" loading="eager" scrolling="no"></iframe></div>'
|
||||
: '';
|
||||
}
|
||||
|
||||
if (regionType === 'rtmp') {
|
||||
const label = String(rawValue || '').trim() || 'RTMP source';
|
||||
return '<div class="template-region-rtmp-placeholder">' + escapeHtml(label) + '</div>';
|
||||
return '<div class="slide-preview-region slide-preview-rtmp-region" style="' + region.baseStyle + '"><div class="slide-preview-rtmp-placeholder">' + escapeHtml(label) + '</div></div>';
|
||||
}
|
||||
|
||||
return buildTextRegionMarkup(region, regionContent);
|
||||
}
|
||||
|
||||
async function loadChromium() {
|
||||
const chromiumModule = await import('@sparticuz/chromium');
|
||||
const resolved = chromiumModule && chromiumModule.default ? chromiumModule.default : chromiumModule;
|
||||
return resolved;
|
||||
}
|
||||
|
||||
async function loadPuppeteer() {
|
||||
return require('puppeteer-core');
|
||||
}
|
||||
|
||||
function loadSharp() {
|
||||
return require('sharp');
|
||||
}
|
||||
|
||||
function buildThumbnailPreviewMarkup(slide, baseUrl) {
|
||||
const template = slide && slide.template ? slide.template : null;
|
||||
if (!template) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const canvasSize = getThumbnailCanvasSize(slide);
|
||||
const normalizedBaseUrl = normalizeBaseUrl(baseUrl);
|
||||
return (Array.isArray(template.regions) ? template.regions : []).map(function (region) {
|
||||
const regionContent = getRegionContent(slide, region);
|
||||
const previewRegion = Object.assign({}, region, {
|
||||
baseStyle: buildThumbnailRegionStyle(region, canvasSize.width, canvasSize.height),
|
||||
pixelWidth: Math.max(1, Math.round(Number(region && region.width || 0) || 1)),
|
||||
pixelHeight: Math.max(1, Math.round(Number(region && region.height || 0) || 1))
|
||||
});
|
||||
return buildRegionInnerHtml(previewRegion, regionContent, normalizedBaseUrl);
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function buildThumbnailPreviewPayload(slide, options) {
|
||||
const template = slide && slide.template ? slide.template : null;
|
||||
const canvasSize = getThumbnailCanvasSize(slide);
|
||||
return {
|
||||
thumbnailPreview: true,
|
||||
canvasWidth: canvasSize.width,
|
||||
canvasHeight: canvasSize.height,
|
||||
backgroundColor: template && template.background_color ? String(template.background_color) : '#111111',
|
||||
backgroundImagePath: template && template.background_image_path ? String(template.background_image_path) : '',
|
||||
fontStylesheetHref: String(options && options.fontStylesheetHref || '').trim(),
|
||||
html: buildThumbnailPreviewMarkup(slide, options && options.baseUrl)
|
||||
};
|
||||
}
|
||||
|
||||
async function launchBrowser() {
|
||||
const puppeteer = await loadPuppeteer();
|
||||
const chromium = await loadChromium();
|
||||
let executablePath = SYSTEM_CHROMIUM_PATHS.find(function (candidate) {
|
||||
return fs.existsSync(candidate);
|
||||
}) || '';
|
||||
@@ -169,6 +236,7 @@ async function launchBrowser() {
|
||||
}
|
||||
|
||||
async function captureSlideThumbnail(options) {
|
||||
const sharp = loadSharp();
|
||||
const pool = options && options.pool;
|
||||
const common = options && options.common;
|
||||
const mediaDir = String(options && options.mediaDir || '').trim();
|
||||
@@ -185,7 +253,6 @@ async function captureSlideThumbnail(options) {
|
||||
throw new Error('Slide not found.');
|
||||
}
|
||||
|
||||
const canvasSize = getCanvasSize(slide);
|
||||
const thumbnailDir = path.join(mediaDir, 'thumbnails');
|
||||
const thumbnailRelativePath = String(slide.thumbnail_path || '').trim() || '/media/thumbnails/slides/slide-' + slide.id + '.png';
|
||||
const filePath = path.join(mediaDir, thumbnailRelativePath.replace(/^\/+media\//, ''));
|
||||
@@ -197,11 +264,11 @@ async function captureSlideThumbnail(options) {
|
||||
|
||||
async function waitForThumbnailRender(page) {
|
||||
await page.waitForFunction(function () {
|
||||
return document.readyState === 'complete' && Boolean(document.querySelector('.slide-canvas'));
|
||||
return document.readyState === 'complete' && Boolean(document.querySelector('#popup-preview-canvas'));
|
||||
}, { timeout: 30000 });
|
||||
|
||||
await page.waitForFunction(function () {
|
||||
var canvas = document.querySelector('.slide-canvas');
|
||||
var canvas = document.querySelector('#popup-preview-canvas');
|
||||
if (!canvas) {
|
||||
return false;
|
||||
}
|
||||
@@ -235,18 +302,26 @@ async function captureSlideThumbnail(options) {
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
try {
|
||||
const previewPath = '/api/internal/slide-thumbnails/' + slide.id + '/preview';
|
||||
const previewPath = '/api/internal/slide-thumbnails/' + slide.id + '/popup-preview';
|
||||
const previewUrl = baseUrl + previewPath;
|
||||
const previewPayload = buildThumbnailPreviewPayload(slide, {
|
||||
baseUrl: baseUrl,
|
||||
fontStylesheetHref: options && options.fontStylesheetHref ? options.fontStylesheetHref : ''
|
||||
});
|
||||
await page.setViewport({
|
||||
width: Math.max(1, Number(previewPayload.canvasWidth || PLAYER_VIEWPORT.width)),
|
||||
height: Math.max(1, Number(previewPayload.canvasHeight || PLAYER_VIEWPORT.height)),
|
||||
deviceScaleFactor: 1
|
||||
});
|
||||
await page.setExtraHTTPHeaders(createRequestAuthHeaders({
|
||||
method: 'GET',
|
||||
pathname: previewPath
|
||||
}));
|
||||
await page.setViewport(PLAYER_VIEWPORT);
|
||||
await page.goto(previewUrl, { waitUntil: 'domcontentloaded', timeout: 30000 });
|
||||
await waitForThumbnailRender(page);
|
||||
const canvas = await page.$('.slide-canvas');
|
||||
const canvas = await page.$('#popup-preview-canvas');
|
||||
if (!canvas) {
|
||||
throw new Error('Player render did not produce a slide canvas.');
|
||||
throw new Error('Popup preview did not produce a slide canvas.');
|
||||
}
|
||||
await canvas.screenshot({ path: fullSizePath });
|
||||
} finally {
|
||||
@@ -289,5 +364,7 @@ async function captureSlideThumbnail(options) {
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
captureSlideThumbnail: captureSlideThumbnail
|
||||
captureSlideThumbnail: captureSlideThumbnail,
|
||||
buildThumbnailPreviewPayload: buildThumbnailPreviewPayload,
|
||||
buildThumbnailPreviewMarkup: buildThumbnailPreviewMarkup
|
||||
};
|
||||
@@ -6,11 +6,48 @@ const crypto = require('crypto');
|
||||
const multer = require('multer');
|
||||
const { createRequestAuthHeaders } = require('#src/request-auth');
|
||||
const { collectFontLibrarySyncOperations } = require('./font-library');
|
||||
const { fetchPlayerRegistrations, getConfiguredPlayerIdentifier } = require('#src/data/player-registry');
|
||||
|
||||
function normalizeUploadRoot(uploadDir) {
|
||||
return path.resolve(String(uploadDir || '').trim());
|
||||
}
|
||||
|
||||
function isLocalLikeBaseUrl(value) {
|
||||
let host = '';
|
||||
try {
|
||||
host = new URL(String(value || '').trim().replace(/\/$/, '')).hostname.toLowerCase();
|
||||
} catch (_error) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return host === 'localhost'
|
||||
|| host === '127.0.0.1'
|
||||
|| host === '::1'
|
||||
|| host === 'host.docker.internal'
|
||||
|| host === 'player'
|
||||
|| host === 'web'
|
||||
|| host === 'player-bridge'
|
||||
|| host.endsWith('.local')
|
||||
|| host.endsWith('.internal')
|
||||
|| host.endsWith('.docker.internal');
|
||||
}
|
||||
|
||||
function normalizeBaseUrl(value) {
|
||||
return String(value || '').trim().replace(/\/$/, '');
|
||||
}
|
||||
|
||||
function normalizePlayerRowBaseUrl(player) {
|
||||
return normalizeBaseUrl(player && player.internal_base_url);
|
||||
}
|
||||
|
||||
function isRecentPlayerRegistration(player, staleSeconds) {
|
||||
const lastSeenAt = player && player.last_seen_at;
|
||||
const lastSeenAtValue = lastSeenAt instanceof Date ? lastSeenAt.getTime() : new Date(lastSeenAt).getTime();
|
||||
const cutoffTime = Date.now() - Math.max(30, Number(staleSeconds || 60)) * 1000;
|
||||
|
||||
return Number.isFinite(lastSeenAtValue) && lastSeenAtValue >= cutoffTime;
|
||||
}
|
||||
|
||||
function createUploadSyncService(options) {
|
||||
const pool = options && options.pool;
|
||||
const common = options && options.common;
|
||||
@@ -19,55 +56,145 @@ function createUploadSyncService(options) {
|
||||
const notifyPlayerScreens = options && options.notifyPlayerScreens;
|
||||
const backgroundTaskQueue = options && options.backgroundTaskQueue;
|
||||
const MAX_UPLOAD_BYTES = 1024 * 1024 * 1024;
|
||||
const MAX_FIELD_BYTES = 10 * 1024 * 1024;
|
||||
const PLAYER_UPLOAD_SYNC_RETRY_LOG_INTERVAL_MS = 60000;
|
||||
const pendingPlayerUploadSyncs = new Map();
|
||||
let pendingPlayerUploadSyncFlushTimer = null;
|
||||
let pendingPlayerUploadSyncFlushInFlight = null;
|
||||
let pendingPlayerUploadSyncRetryLogAt = 0;
|
||||
const pendingPlaylistUploadSyncs = new Map();
|
||||
let pendingPlaylistUploadSyncFlushTimer = null;
|
||||
let pendingPlaylistUploadSyncFlushInFlight = null;
|
||||
let playerInternalBaseUrl = null;
|
||||
let playerInternalBaseUrlPromise = null;
|
||||
let playerTaskMetadata = null;
|
||||
let playerTaskMetadataPromise = null;
|
||||
|
||||
if (!common || !playerSnapshotCache || typeof notifyPlayerScreens !== 'function') {
|
||||
throw new Error('createUploadSyncService requires the upload dependencies.');
|
||||
}
|
||||
|
||||
async function getPlayerInternalBaseUrl() {
|
||||
if (playerInternalBaseUrl) {
|
||||
return playerInternalBaseUrl;
|
||||
const metadata = await getPlayerTaskMetadata();
|
||||
if (!metadata || metadata.playerActive === false) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (playerInternalBaseUrlPromise) {
|
||||
return playerInternalBaseUrlPromise;
|
||||
return metadata.playerInternalBaseUrl ? metadata.playerInternalBaseUrl : null;
|
||||
}
|
||||
|
||||
playerInternalBaseUrlPromise = (async function () {
|
||||
if (!pool) {
|
||||
return configuredPlayerInternalBaseUrl || null;
|
||||
async function getPlayerTaskMetadata() {
|
||||
if (playerTaskMetadata) {
|
||||
return playerTaskMetadata;
|
||||
}
|
||||
|
||||
if (playerTaskMetadataPromise) {
|
||||
return playerTaskMetadataPromise;
|
||||
}
|
||||
|
||||
playerTaskMetadataPromise = (async function () {
|
||||
try {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT internal_base_url
|
||||
FROM d_players
|
||||
WHERE device_id = '1'
|
||||
LIMIT 1`
|
||||
);
|
||||
const resolvedBaseUrl = String(rows && rows[0] && rows[0].internal_base_url || '').trim().replace(/\/$/, '');
|
||||
return resolvedBaseUrl || configuredPlayerInternalBaseUrl || null;
|
||||
} catch (_error) {
|
||||
return configuredPlayerInternalBaseUrl || null;
|
||||
if (pool && typeof fetchPlayerRegistrations === 'function') {
|
||||
const configuredPlayerIdentifier = getConfiguredPlayerIdentifier();
|
||||
const players = await fetchPlayerRegistrations(pool);
|
||||
const registeredPlayers = Array.isArray(players) ? players : [];
|
||||
const recentPlayers = registeredPlayers.filter(function (player) {
|
||||
return isRecentPlayerRegistration(player, 60);
|
||||
});
|
||||
const preferredPlayer = recentPlayers.find(function (player) {
|
||||
const internalBaseUrl = normalizePlayerRowBaseUrl(player);
|
||||
return internalBaseUrl && !isLocalLikeBaseUrl(internalBaseUrl);
|
||||
}) || recentPlayers.find(function (player) {
|
||||
return String(player && player.identifier || '').trim() === configuredPlayerIdentifier;
|
||||
}) || recentPlayers[0] || null;
|
||||
if (preferredPlayer) {
|
||||
const resolvedInternalBaseUrl = normalizePlayerRowBaseUrl(preferredPlayer);
|
||||
const resolvedPublicBaseUrl = normalizeBaseUrl(preferredPlayer && preferredPlayer.public_base_url);
|
||||
const resolvedIdentifier = String(preferredPlayer && preferredPlayer.identifier || '').trim();
|
||||
playerInternalBaseUrl = resolvedInternalBaseUrl || null;
|
||||
playerTaskMetadata = {
|
||||
playerIdentifier: resolvedIdentifier || null,
|
||||
playerPublicBaseUrl: resolvedPublicBaseUrl || null,
|
||||
playerInternalBaseUrl: resolvedInternalBaseUrl || null,
|
||||
playerLabel: resolvedIdentifier || resolvedPublicBaseUrl || resolvedInternalBaseUrl || null,
|
||||
playerActive: true
|
||||
};
|
||||
return playerTaskMetadata;
|
||||
}
|
||||
})().then(function (baseUrl) {
|
||||
playerInternalBaseUrl = baseUrl || null;
|
||||
playerInternalBaseUrlPromise = null;
|
||||
return playerInternalBaseUrl;
|
||||
|
||||
if (registeredPlayers.length) {
|
||||
const stalePlayer = registeredPlayers.find(function (player) {
|
||||
return String(player && player.identifier || '').trim() === configuredPlayerIdentifier;
|
||||
}) || registeredPlayers[0] || null;
|
||||
const staleInternalBaseUrl = normalizePlayerRowBaseUrl(stalePlayer);
|
||||
const stalePublicBaseUrl = normalizeBaseUrl(stalePlayer && stalePlayer.public_base_url);
|
||||
const staleIdentifier = String(stalePlayer && stalePlayer.identifier || '').trim();
|
||||
playerInternalBaseUrl = staleInternalBaseUrl || null;
|
||||
playerTaskMetadata = {
|
||||
playerIdentifier: staleIdentifier || null,
|
||||
playerPublicBaseUrl: stalePublicBaseUrl || null,
|
||||
playerInternalBaseUrl: staleInternalBaseUrl || null,
|
||||
playerLabel: staleIdentifier || stalePublicBaseUrl || staleInternalBaseUrl || null,
|
||||
playerActive: false
|
||||
};
|
||||
return playerTaskMetadata;
|
||||
}
|
||||
}
|
||||
} catch (_error) {
|
||||
}
|
||||
|
||||
playerInternalBaseUrl = configuredPlayerInternalBaseUrl || null;
|
||||
playerTaskMetadata = {
|
||||
playerIdentifier: getConfiguredPlayerIdentifier() || null,
|
||||
playerPublicBaseUrl: null,
|
||||
playerInternalBaseUrl: playerInternalBaseUrl,
|
||||
playerLabel: getConfiguredPlayerIdentifier() || playerInternalBaseUrl || null,
|
||||
playerActive: true
|
||||
};
|
||||
return playerTaskMetadata;
|
||||
})().then(function (metadata) {
|
||||
playerTaskMetadataPromise = null;
|
||||
return metadata || null;
|
||||
}, function () {
|
||||
playerInternalBaseUrlPromise = null;
|
||||
return configuredPlayerInternalBaseUrl || null;
|
||||
playerTaskMetadataPromise = null;
|
||||
return {
|
||||
playerIdentifier: getConfiguredPlayerIdentifier() || null,
|
||||
playerPublicBaseUrl: null,
|
||||
playerInternalBaseUrl: configuredPlayerInternalBaseUrl || null,
|
||||
playerLabel: getConfiguredPlayerIdentifier() || configuredPlayerInternalBaseUrl || null
|
||||
};
|
||||
});
|
||||
|
||||
return playerInternalBaseUrlPromise;
|
||||
return playerTaskMetadataPromise;
|
||||
}
|
||||
|
||||
function formatPlayerTaskLabel(metadata) {
|
||||
const playerLabel = String(metadata && metadata.playerLabel || '').trim();
|
||||
if (playerLabel) {
|
||||
return playerLabel;
|
||||
}
|
||||
|
||||
const playerIdentifier = String(metadata && metadata.playerIdentifier || '').trim();
|
||||
if (playerIdentifier) {
|
||||
return playerIdentifier;
|
||||
}
|
||||
|
||||
const playerPublicBaseUrl = String(metadata && metadata.playerPublicBaseUrl || '').trim();
|
||||
if (playerPublicBaseUrl) {
|
||||
return playerPublicBaseUrl;
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
function logMediaSyncSummary(level, message, metadata, details) {
|
||||
const suffix = formatPlayerTaskLabel(metadata);
|
||||
const logger = level === 'warn' ? console.warn : console.info;
|
||||
if (details !== undefined) {
|
||||
logger(`[media-sync] ${message}${suffix ? ` for ${suffix}` : ''}`, details);
|
||||
return;
|
||||
}
|
||||
logger(`[media-sync] ${message}${suffix ? ` for ${suffix}` : ''}`);
|
||||
}
|
||||
|
||||
function createUploadMiddleware(uploadDir) {
|
||||
@@ -84,7 +211,8 @@ function createUploadSyncService(options) {
|
||||
return multer({
|
||||
storage: storage,
|
||||
limits: {
|
||||
fileSize: MAX_UPLOAD_BYTES
|
||||
fileSize: MAX_UPLOAD_BYTES,
|
||||
fieldSize: MAX_FIELD_BYTES
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -276,6 +404,15 @@ function createUploadSyncService(options) {
|
||||
return Boolean(localUploadDir);
|
||||
}
|
||||
|
||||
function isPlayerUnavailableError(error) {
|
||||
const code = String(error && error.cause && error.cause.code || error && error.code || '').trim().toUpperCase();
|
||||
return code === 'ENOTFOUND' || code === 'ECONNREFUSED' || code === 'EAI_AGAIN' || code === 'ETIMEDOUT';
|
||||
}
|
||||
|
||||
function isPlayerUnavailableResponse(response) {
|
||||
return Boolean(response) && Number(response.status) === 503;
|
||||
}
|
||||
|
||||
function queuePlayerUploadSync(operation) {
|
||||
if (!operation || !operation.uploadPath) {
|
||||
return;
|
||||
@@ -301,15 +438,18 @@ function createUploadSyncService(options) {
|
||||
console.warn('Unable to flush pending upload syncs:', error);
|
||||
});
|
||||
}, 5000);
|
||||
if (pendingPlayerUploadSyncFlushTimer && typeof pendingPlayerUploadSyncFlushTimer.unref === 'function') {
|
||||
pendingPlayerUploadSyncFlushTimer.unref();
|
||||
}
|
||||
}
|
||||
|
||||
async function pushUploadFileToPlayer(uploadPath, localUploadDir) {
|
||||
async function pushUploadFileToPlayer(uploadPath, localUploadDir, resolvedPlayerInternalBaseUrl) {
|
||||
if (!uploadPath || !shouldMirrorUploads(localUploadDir)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const resolvedPlayerInternalBaseUrl = await getPlayerInternalBaseUrl();
|
||||
if (!resolvedPlayerInternalBaseUrl) {
|
||||
const targetBaseUrl = String(resolvedPlayerInternalBaseUrl || '').trim() || await getPlayerInternalBaseUrl();
|
||||
if (!targetBaseUrl) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -334,7 +474,7 @@ function createUploadSyncService(options) {
|
||||
pathname: `/api/media/${encodeURIComponent(relativePath)}`,
|
||||
body: fileBuffer
|
||||
});
|
||||
const response = await fetch(`${resolvedPlayerInternalBaseUrl}/api/media/${encodeURIComponent(relativePath)}`, {
|
||||
const response = await fetch(`${targetBaseUrl}/api/media/${encodeURIComponent(relativePath)}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/octet-stream',
|
||||
@@ -343,23 +483,27 @@ function createUploadSyncService(options) {
|
||||
body: fileBuffer
|
||||
});
|
||||
if (!response.ok) {
|
||||
if (!isPlayerUnavailableResponse(response)) {
|
||||
console.warn('Unable to sync upload to player:', relativePath, response.status, response.statusText);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (!isPlayerUnavailableError(error)) {
|
||||
console.warn('Unable to sync upload to player:', relativePath, error);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeUploadFileFromPlayer(uploadPath, localUploadDir) {
|
||||
async function removeUploadFileFromPlayer(uploadPath, localUploadDir, resolvedPlayerInternalBaseUrl) {
|
||||
if (!uploadPath || !shouldMirrorUploads(localUploadDir)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const resolvedPlayerInternalBaseUrl = await getPlayerInternalBaseUrl();
|
||||
if (!resolvedPlayerInternalBaseUrl) {
|
||||
const targetBaseUrl = String(resolvedPlayerInternalBaseUrl || '').trim() || await getPlayerInternalBaseUrl();
|
||||
if (!targetBaseUrl) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -372,7 +516,7 @@ function createUploadSyncService(options) {
|
||||
method: 'DELETE',
|
||||
pathname: `/api/media/${encodeURIComponent(relativePath)}`
|
||||
});
|
||||
const response = await fetch(`${resolvedPlayerInternalBaseUrl}/api/media/${encodeURIComponent(relativePath)}`, {
|
||||
const response = await fetch(`${targetBaseUrl}/api/media/${encodeURIComponent(relativePath)}`, {
|
||||
method: 'DELETE',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
@@ -380,12 +524,16 @@ function createUploadSyncService(options) {
|
||||
}
|
||||
});
|
||||
if (!response.ok && response.status !== 404) {
|
||||
if (!isPlayerUnavailableResponse(response)) {
|
||||
console.warn('Unable to remove upload from player:', relativePath, response.status, response.statusText);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (!isPlayerUnavailableError(error)) {
|
||||
console.warn('Unable to remove upload from player:', relativePath, error);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -395,9 +543,10 @@ function createUploadSyncService(options) {
|
||||
return;
|
||||
}
|
||||
|
||||
const resolvedPlayerInternalBaseUrl = await getPlayerInternalBaseUrl();
|
||||
const uniqueRefs = Array.from(new Set((uploadRefs || []).map(normalizeUploadReference).filter(Boolean)));
|
||||
for (let i = 0; i < uniqueRefs.length; i += 1) {
|
||||
const success = await pushUploadFileToPlayer(uniqueRefs[i], localUploadDir);
|
||||
const success = await pushUploadFileToPlayer(uniqueRefs[i], localUploadDir, resolvedPlayerInternalBaseUrl);
|
||||
if (!success) {
|
||||
queuePlayerUploadSync({
|
||||
type: 'put',
|
||||
@@ -531,6 +680,11 @@ function createUploadSyncService(options) {
|
||||
return pendingPlaylistUploadSyncFlushInFlight;
|
||||
}
|
||||
|
||||
if (pendingPlaylistUploadSyncFlushTimer) {
|
||||
clearTimeout(pendingPlaylistUploadSyncFlushTimer);
|
||||
pendingPlaylistUploadSyncFlushTimer = null;
|
||||
}
|
||||
|
||||
if (!pendingPlaylistUploadSyncs.size) {
|
||||
return null;
|
||||
}
|
||||
@@ -550,6 +704,10 @@ function createUploadSyncService(options) {
|
||||
|
||||
pendingPlaylistUploadSyncs.delete(operation.key);
|
||||
}
|
||||
|
||||
if (pendingEntries.length) {
|
||||
logMediaSyncSummary('info', `Playlist sync flushed ${pendingEntries.length} task${pendingEntries.length === 1 ? '' : 's'}`, pendingEntries[0] && pendingEntries[0].metadata);
|
||||
}
|
||||
})().finally(function () {
|
||||
pendingPlaylistUploadSyncFlushInFlight = null;
|
||||
if (pendingPlaylistUploadSyncs.size) {
|
||||
@@ -565,24 +723,58 @@ function createUploadSyncService(options) {
|
||||
return pendingPlayerUploadSyncFlushInFlight;
|
||||
}
|
||||
|
||||
if (pendingPlayerUploadSyncFlushTimer) {
|
||||
clearTimeout(pendingPlayerUploadSyncFlushTimer);
|
||||
pendingPlayerUploadSyncFlushTimer = null;
|
||||
}
|
||||
|
||||
if (!pendingPlayerUploadSyncs.size) {
|
||||
return null;
|
||||
}
|
||||
|
||||
pendingPlayerUploadSyncFlushInFlight = (async function () {
|
||||
const pendingEntries = Array.from(pendingPlayerUploadSyncs.values());
|
||||
const playerMetadata = pendingEntries.length && pendingEntries[0] && pendingEntries[0].metadata
|
||||
? pendingEntries[0].metadata
|
||||
: await getPlayerTaskMetadata();
|
||||
if (playerMetadata && playerMetadata.playerActive === false) {
|
||||
pendingPlayerUploadSyncs.clear();
|
||||
pendingPlayerUploadSyncRetryLogAt = 0;
|
||||
return;
|
||||
}
|
||||
const resolvedPlayerInternalBaseUrl = playerMetadata && playerMetadata.playerInternalBaseUrl
|
||||
? playerMetadata.playerInternalBaseUrl
|
||||
: await getPlayerInternalBaseUrl();
|
||||
let successCount = 0;
|
||||
let failureCount = 0;
|
||||
for (let i = 0; i < pendingEntries.length; i += 1) {
|
||||
const operation = pendingEntries[i];
|
||||
let success = false;
|
||||
if (operation.type === 'delete') {
|
||||
success = await removeUploadFileFromPlayer(operation.uploadPath, operation.uploadDir);
|
||||
success = await removeUploadFileFromPlayer(operation.uploadPath, operation.uploadDir, resolvedPlayerInternalBaseUrl);
|
||||
} else {
|
||||
success = await pushUploadFileToPlayer(operation.uploadPath, operation.uploadDir);
|
||||
success = await pushUploadFileToPlayer(operation.uploadPath, operation.uploadDir, resolvedPlayerInternalBaseUrl);
|
||||
}
|
||||
if (success) {
|
||||
successCount += 1;
|
||||
pendingPlayerUploadSyncs.delete(operation.uploadPath);
|
||||
} else {
|
||||
failureCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (successCount) {
|
||||
logMediaSyncSummary('info', `Media sync completed ${successCount} upload${successCount === 1 ? '' : 's'}`, playerMetadata);
|
||||
}
|
||||
if (failureCount) {
|
||||
const now = Date.now();
|
||||
if (!pendingPlayerUploadSyncRetryLogAt || now - pendingPlayerUploadSyncRetryLogAt >= PLAYER_UPLOAD_SYNC_RETRY_LOG_INTERVAL_MS) {
|
||||
pendingPlayerUploadSyncRetryLogAt = now;
|
||||
logMediaSyncSummary('warn', `Player unavailable, retry queued for ${failureCount} upload${failureCount === 1 ? '' : 's'}`, playerMetadata);
|
||||
}
|
||||
} else if (!pendingPlayerUploadSyncs.size) {
|
||||
pendingPlayerUploadSyncRetryLogAt = 0;
|
||||
}
|
||||
})().finally(function () {
|
||||
pendingPlayerUploadSyncFlushInFlight = null;
|
||||
if (pendingPlayerUploadSyncs.size) {
|
||||
@@ -678,12 +870,14 @@ function createUploadSyncService(options) {
|
||||
safePayload.operation = Object.assign({}, safePayload.operation);
|
||||
delete safePayload.operation.pool;
|
||||
}
|
||||
const playerMetadata = await getPlayerTaskMetadata();
|
||||
|
||||
const definition = {
|
||||
key: taskKey,
|
||||
title: title,
|
||||
category: 'media-sync',
|
||||
taskType: 'media-sync',
|
||||
metadata: Object.assign({}, playerMetadata || {}),
|
||||
payload: safePayload,
|
||||
persist: true
|
||||
};
|
||||
@@ -721,7 +915,8 @@ function createUploadSyncService(options) {
|
||||
flushPendingPlaylistUploadSyncs: flushPendingPlaylistUploadSyncs,
|
||||
flushPendingPlayerUploadSyncs: flushPendingPlayerUploadSyncs,
|
||||
runMediaSyncTask: runMediaSyncTask,
|
||||
queueMediaSyncTask: queueMediaSyncTask
|
||||
queueMediaSyncTask: queueMediaSyncTask,
|
||||
getPlayerTaskMetadata: getPlayerTaskMetadata
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+198
-40
@@ -1,8 +1,42 @@
|
||||
const { createRequestAuthHeaders } = require('#src/request-auth');
|
||||
const { getConfiguredPlayerIdentifier } = require('#src/data/player-registry');
|
||||
|
||||
function isLocalLikeBaseUrl(value) {
|
||||
let host = '';
|
||||
try {
|
||||
host = new URL(String(value || '').trim().replace(/\/$/, '')).hostname.toLowerCase();
|
||||
} catch (_error) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return host === 'localhost'
|
||||
|| host === '127.0.0.1'
|
||||
|| host === '::1'
|
||||
|| host === 'host.docker.internal'
|
||||
|| host === 'player'
|
||||
|| host === 'web'
|
||||
|| host === 'player-bridge'
|
||||
|| host.endsWith('.local')
|
||||
|| host.endsWith('.internal')
|
||||
|| host.endsWith('.docker.internal');
|
||||
}
|
||||
|
||||
function normalizeBaseUrl(value) {
|
||||
return String(value || '').trim().replace(/\/$/, '');
|
||||
}
|
||||
|
||||
function isRecentPlayerRegistration(player, staleSeconds) {
|
||||
const lastSeenAt = player && player.last_seen_at;
|
||||
const lastSeenAtValue = lastSeenAt instanceof Date ? lastSeenAt.getTime() : new Date(lastSeenAt).getTime();
|
||||
const cutoffTime = Date.now() - Math.max(30, Number(staleSeconds || 60)) * 1000;
|
||||
|
||||
return Number.isFinite(lastSeenAtValue) && lastSeenAtValue >= cutoffTime;
|
||||
}
|
||||
|
||||
function createPlayerActionService(options) {
|
||||
const pool = options && options.pool;
|
||||
const configuredPlayerInternalBaseUrl = String(options && options.playerInternalBaseUrl || '').replace(/\/$/, '');
|
||||
const configuredBridgeInternalBaseUrl = String(options && options.bridgeInternalBaseUrl || '').trim().replace(/\/$/, '');
|
||||
const common = options && options.common;
|
||||
|
||||
if (!common) {
|
||||
@@ -22,26 +56,38 @@ function createPlayerActionService(options) {
|
||||
}
|
||||
|
||||
playerInternalBaseUrlPromise = (async function () {
|
||||
if (!pool) {
|
||||
return configuredPlayerInternalBaseUrl || null;
|
||||
try {
|
||||
if (pool && typeof fetchPlayerRegistrations === 'function') {
|
||||
const configuredPlayerIdentifier = getConfiguredPlayerIdentifier();
|
||||
const players = await fetchPlayerRegistrations(pool);
|
||||
const exactPlayer = Array.isArray(players)
|
||||
? players.find(function (player) {
|
||||
return String(player && player.identifier || '').trim() === configuredPlayerIdentifier;
|
||||
})
|
||||
: null;
|
||||
const registeredPlayers = Array.isArray(players) ? players : [];
|
||||
const preferredPlayer = exactPlayer || registeredPlayers.find(function (player) {
|
||||
const internalBaseUrl = normalizeBaseUrl(player && player.internal_base_url);
|
||||
return internalBaseUrl && !isLocalLikeBaseUrl(internalBaseUrl);
|
||||
}) || registeredPlayers[0] || null;
|
||||
const resolvedBaseUrl = normalizeBaseUrl(preferredPlayer && preferredPlayer.internal_base_url);
|
||||
if (resolvedBaseUrl) {
|
||||
playerInternalBaseUrl = resolvedBaseUrl;
|
||||
return resolvedBaseUrl;
|
||||
}
|
||||
}
|
||||
} catch (_error) {
|
||||
}
|
||||
|
||||
try {
|
||||
const [rows] = await pool.query(
|
||||
`SELECT internal_base_url
|
||||
FROM d_players
|
||||
WHERE device_id = '1'
|
||||
LIMIT 1`
|
||||
);
|
||||
const resolvedBaseUrl = String(rows && rows[0] && rows[0].internal_base_url || '').trim().replace(/\/$/, '');
|
||||
return resolvedBaseUrl || configuredPlayerInternalBaseUrl || null;
|
||||
} catch (_error) {
|
||||
return configuredPlayerInternalBaseUrl || null;
|
||||
if (configuredPlayerInternalBaseUrl) {
|
||||
playerInternalBaseUrl = configuredPlayerInternalBaseUrl;
|
||||
return configuredPlayerInternalBaseUrl;
|
||||
}
|
||||
|
||||
return null;
|
||||
})().then(function (baseUrl) {
|
||||
playerInternalBaseUrl = baseUrl || null;
|
||||
playerInternalBaseUrlPromise = null;
|
||||
return playerInternalBaseUrl;
|
||||
return baseUrl || null;
|
||||
}, function () {
|
||||
playerInternalBaseUrlPromise = null;
|
||||
return configuredPlayerInternalBaseUrl || null;
|
||||
@@ -50,24 +96,26 @@ function createPlayerActionService(options) {
|
||||
return playerInternalBaseUrlPromise;
|
||||
}
|
||||
|
||||
async function forwardPlayerCommand(slug, commandOrPayload, connectionId) {
|
||||
async function forwardPlayerCommandToBaseUrl(baseUrl, slug, commandOrPayload, connectionId) {
|
||||
const targetBaseUrl = normalizeBaseUrl(baseUrl);
|
||||
if (!targetBaseUrl) {
|
||||
throw new Error('Unable to resolve the player internal base URL.');
|
||||
}
|
||||
|
||||
const payload = typeof commandOrPayload === 'object' && commandOrPayload !== null
|
||||
? Object.assign({}, commandOrPayload)
|
||||
: { command: commandOrPayload };
|
||||
if (connectionId) {
|
||||
payload.connectionId = connectionId;
|
||||
}
|
||||
|
||||
const authHeaders = createRequestAuthHeaders({
|
||||
method: 'POST',
|
||||
pathname: `/api/screens/${encodeURIComponent(slug)}/commands`,
|
||||
body: payload
|
||||
});
|
||||
const resolvedPlayerInternalBaseUrl = await getPlayerInternalBaseUrl();
|
||||
if (!resolvedPlayerInternalBaseUrl) {
|
||||
throw new Error('Unable to resolve the player internal base URL.');
|
||||
}
|
||||
|
||||
const response = await fetch(`${resolvedPlayerInternalBaseUrl}/api/screens/${encodeURIComponent(slug)}/commands`, {
|
||||
const response = await fetch(`${targetBaseUrl}/api/screens/${encodeURIComponent(slug)}/commands`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -89,6 +137,84 @@ function createPlayerActionService(options) {
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchScreenConnectionsFromBaseUrl(baseUrl, slug) {
|
||||
const targetBaseUrl = normalizeBaseUrl(baseUrl);
|
||||
if (!targetBaseUrl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const authHeaders = createRequestAuthHeaders({
|
||||
method: 'GET',
|
||||
pathname: `/api/screens/${encodeURIComponent(slug)}/connections`
|
||||
});
|
||||
|
||||
const response = await fetch(`${targetBaseUrl}/api/screens/${encodeURIComponent(slug)}/connections`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...authHeaders
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(function () { return ''; });
|
||||
const error = new Error(errorText || `Unable to fetch connections for player ${slug}.`);
|
||||
error.statusCode = response.status;
|
||||
throw error;
|
||||
}
|
||||
|
||||
return response.json().catch(function () {
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
async function forwardPlayerCommandToDevice(deviceId, commandOrPayload) {
|
||||
const targetDeviceId = String(deviceId || '').trim();
|
||||
const targetBridgeBaseUrl = normalizeBaseUrl(configuredBridgeInternalBaseUrl);
|
||||
if (!targetDeviceId) {
|
||||
throw new Error('Device ID is required.');
|
||||
}
|
||||
if (!targetBridgeBaseUrl) {
|
||||
throw new Error('Unable to resolve the player bridge base URL.');
|
||||
}
|
||||
|
||||
const payload = typeof commandOrPayload === 'object' && commandOrPayload !== null
|
||||
? Object.assign({}, commandOrPayload)
|
||||
: { command: commandOrPayload };
|
||||
|
||||
const authHeaders = createRequestAuthHeaders({
|
||||
method: 'POST',
|
||||
pathname: `/api/players/${encodeURIComponent(targetDeviceId)}/commands`,
|
||||
body: payload
|
||||
});
|
||||
|
||||
const response = await fetch(`${targetBridgeBaseUrl}/api/players/${encodeURIComponent(targetDeviceId)}/commands`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
...authHeaders
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(function () { return ''; });
|
||||
const error = new Error(errorText || `Unable to send command to player ${targetDeviceId}.`);
|
||||
error.statusCode = response.status;
|
||||
throw error;
|
||||
}
|
||||
|
||||
return response.json().catch(function () {
|
||||
return { ok: true };
|
||||
});
|
||||
}
|
||||
|
||||
async function forwardPlayerCommand(slug, commandOrPayload, connectionId) {
|
||||
const resolvedPlayerInternalBaseUrl = await getPlayerInternalBaseUrl();
|
||||
return forwardPlayerCommandToBaseUrl(resolvedPlayerInternalBaseUrl, slug, commandOrPayload, connectionId);
|
||||
}
|
||||
|
||||
async function forwardAnnouncementRefresh(slug) {
|
||||
const authHeaders = createRequestAuthHeaders({
|
||||
method: 'POST',
|
||||
@@ -123,33 +249,63 @@ function createPlayerActionService(options) {
|
||||
}
|
||||
|
||||
async function getScreenConnections(slug) {
|
||||
const authHeaders = createRequestAuthHeaders({
|
||||
method: 'GET',
|
||||
pathname: `/api/screens/${encodeURIComponent(slug)}/connections`
|
||||
});
|
||||
const resolvedPlayerInternalBaseUrl = await getPlayerInternalBaseUrl();
|
||||
if (!resolvedPlayerInternalBaseUrl) {
|
||||
const bridgeBaseUrl = normalizeBaseUrl(configuredBridgeInternalBaseUrl);
|
||||
const playerBaseUrl = await getPlayerInternalBaseUrl();
|
||||
const targetBaseUrls = Array.from(new Set([bridgeBaseUrl, playerBaseUrl].map(normalizeBaseUrl).filter(Boolean)));
|
||||
if (!targetBaseUrls.length) {
|
||||
throw new Error('Unable to resolve the player internal base URL.');
|
||||
}
|
||||
|
||||
const response = await fetch(`${resolvedPlayerInternalBaseUrl}/api/screens/${encodeURIComponent(slug)}/connections`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
...authHeaders
|
||||
}
|
||||
const results = await Promise.allSettled(targetBaseUrls.map(function (baseUrl) {
|
||||
return fetchScreenConnectionsFromBaseUrl(baseUrl, slug);
|
||||
}));
|
||||
|
||||
const successfulResults = results.filter(function (result) {
|
||||
return result.status === 'fulfilled' && result.value;
|
||||
}).map(function (result) {
|
||||
return result.value;
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(function () { return ''; });
|
||||
const error = new Error(errorText || `Unable to load screen connections for ${slug}.`);
|
||||
error.statusCode = response.status;
|
||||
throw error;
|
||||
if (!successfulResults.length) {
|
||||
const rejection = results.find(function (result) {
|
||||
return result.status === 'rejected';
|
||||
});
|
||||
throw rejection ? rejection.reason : new Error(`Unable to fetch connections for player ${slug}.`);
|
||||
}
|
||||
|
||||
return response.json().catch(function () {
|
||||
return { connections: [] };
|
||||
const mergedConnections = [];
|
||||
const seenKeys = new Set();
|
||||
|
||||
successfulResults.forEach(function (result) {
|
||||
const connections = Array.isArray(result && result.connections) ? result.connections : [];
|
||||
connections.forEach(function (connection) {
|
||||
const key = [
|
||||
String(connection && connection.id || '').trim(),
|
||||
String(connection && connection.clientId || '').trim(),
|
||||
String(connection && connection.deviceId || '').trim(),
|
||||
String(connection && connection.playerPublicBaseUrl || '').trim()
|
||||
].join('|');
|
||||
if (!key || seenKeys.has(key)) {
|
||||
return;
|
||||
}
|
||||
seenKeys.add(key);
|
||||
mergedConnections.push(connection);
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
screen: successfulResults.find(function (result) {
|
||||
return Boolean(result && result.screen);
|
||||
}) ? successfulResults.find(function (result) {
|
||||
return Boolean(result && result.screen);
|
||||
}).screen : null,
|
||||
screenSlug: slug,
|
||||
count: mergedConnections.length,
|
||||
connections: mergedConnections,
|
||||
degraded: results.some(function (result) {
|
||||
return result.status === 'fulfilled' && Boolean(result.value && result.value.degraded);
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
async function getScreenDeleteBlockMessage(pool, screen, getScreenConnections) {
|
||||
@@ -197,6 +353,8 @@ function createPlayerActionService(options) {
|
||||
forwardPlayerCommand: forwardPlayerCommand,
|
||||
forwardAnnouncementRefresh: forwardAnnouncementRefresh,
|
||||
getScreenConnections: getScreenConnections,
|
||||
forwardPlayerCommandToBaseUrl: forwardPlayerCommandToBaseUrl,
|
||||
forwardPlayerCommandToDevice: forwardPlayerCommandToDevice,
|
||||
getScreenDeleteBlockMessage: getScreenDeleteBlockMessage,
|
||||
getSlideDeleteBlockMessage: getSlideDeleteBlockMessage,
|
||||
getTemplateDeleteBlockMessage: getTemplateDeleteBlockMessage,
|
||||
|
||||
@@ -25,6 +25,7 @@ async function initializeWebServer(options) {
|
||||
uploadSyncService: webBootstrap.uploadSyncService,
|
||||
captureSlideThumbnail: captureSlideThumbnail,
|
||||
mediaDir: mediaDir,
|
||||
webBaseUrl: options && options.webBaseUrl ? options.webBaseUrl : null,
|
||||
dataSourceStartupRefreshStaggerMs: dataSourceStartupRefreshStaggerMs
|
||||
});
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ module.exports = function registerMiddleware(app, deps) {
|
||||
});
|
||||
|
||||
app.use(function (req, res, next) {
|
||||
if (req.path === '/' || req.path === '/login' || req.path === '/logout' || req.path.indexOf('/api/internal/slide-thumbnails/') === 0) {
|
||||
if (req.path === '/' || req.path === '/login' || req.path === '/logout' || req.path.indexOf('/api/internal/slide-thumbnails/') === 0 || req.path === '/api/internal/sync/player-media') {
|
||||
return next();
|
||||
}
|
||||
|
||||
|
||||
@@ -259,6 +259,10 @@
|
||||
opacity: 0.84;
|
||||
}
|
||||
|
||||
.rbac-permissions-table tbody tr:last-child > * {
|
||||
border-bottom-width: 0;
|
||||
}
|
||||
|
||||
.template-designer-form--previewing .region-item [disabled],
|
||||
.template-designer-form--previewing .template-details-card [disabled],
|
||||
.template-designer-form--previewing .template-options-card [disabled],
|
||||
@@ -270,15 +274,33 @@
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.announcement-type-picker {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.announcement-icon-picker__toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
width: 100%;
|
||||
min-height: calc(1.5em + 0.75rem + 2px);
|
||||
min-height: calc(2.375rem + 2px);
|
||||
padding: 0.375rem 0.75rem;
|
||||
border: 1px solid var(--bs-border-color);
|
||||
border-radius: 0.375rem;
|
||||
border-radius: 0.875rem;
|
||||
background: var(--bs-body-bg);
|
||||
color: var(--bs-body-color);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.announcement-type-picker__toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
width: 100%;
|
||||
min-height: calc(2.375rem + 2px);
|
||||
padding: 0.375rem 0.75rem;
|
||||
border: 1px solid var(--bs-border-color);
|
||||
border-radius: 0.875rem;
|
||||
background: var(--bs-body-bg);
|
||||
color: var(--bs-body-color);
|
||||
text-align: left;
|
||||
@@ -289,23 +311,73 @@
|
||||
box-shadow: 0 0 0 0.2rem rgba(var(--bs-primary-rgb), 0.25);
|
||||
}
|
||||
|
||||
.announcement-type-picker__toggle:focus-visible {
|
||||
outline: 0;
|
||||
box-shadow: 0 0 0 0.2rem rgba(var(--bs-primary-rgb), 0.25);
|
||||
}
|
||||
|
||||
.announcement-icon-picker__toggle-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.75rem;
|
||||
height: 1.75rem;
|
||||
border-radius: 0.5rem;
|
||||
border-radius: 0.7rem;
|
||||
background: rgba(var(--bs-primary-rgb), 0.1);
|
||||
color: var(--bs-primary);
|
||||
font-size: 1rem;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.announcement-icon-picker__toggle-label {
|
||||
.announcement-type-picker__toggle-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.75rem;
|
||||
height: 1.75rem;
|
||||
border-radius: 0.7rem;
|
||||
background: rgba(var(--bs-primary-rgb), 0.1);
|
||||
color: var(--bs-primary);
|
||||
font-size: 1rem;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.announcement-icon-picker__toggle-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.1rem;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.announcement-type-picker__toggle-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.1rem;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.announcement-icon-picker__toggle-label {
|
||||
font-weight: 600;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.announcement-type-picker__toggle-label {
|
||||
font-weight: 600;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.announcement-icon-picker__toggle-hint {
|
||||
color: var(--bs-secondary-color);
|
||||
font-size: 0.78rem;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.announcement-type-picker__toggle-hint {
|
||||
color: var(--bs-secondary-color);
|
||||
font-size: 0.78rem;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.announcement-icon-picker__caret {
|
||||
@@ -314,6 +386,12 @@
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.announcement-type-picker__caret {
|
||||
flex: 0 0 auto;
|
||||
color: var(--bs-secondary-color);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.announcement-icon-picker__menu {
|
||||
position: absolute;
|
||||
z-index: 20;
|
||||
@@ -329,6 +407,26 @@
|
||||
box-shadow: 0 1rem 2rem rgba(15, 23, 42, 0.18);
|
||||
}
|
||||
|
||||
.announcement-type-picker__menu {
|
||||
position: absolute;
|
||||
z-index: 20;
|
||||
top: calc(100% + 0.5rem);
|
||||
bottom: auto;
|
||||
left: 0;
|
||||
width: min(100%, 28rem);
|
||||
max-width: calc(100vw - 1rem);
|
||||
padding: 0.75rem;
|
||||
border: 1px solid var(--bs-border-color);
|
||||
border-radius: 1rem;
|
||||
background: var(--bs-body-bg);
|
||||
box-shadow: 0 1rem 2rem rgba(15, 23, 42, 0.18);
|
||||
}
|
||||
|
||||
.announcement-type-picker__menu.is-open-above {
|
||||
top: auto;
|
||||
bottom: calc(100% + 0.5rem);
|
||||
}
|
||||
|
||||
.announcement-icon-picker__menu.is-open-above {
|
||||
top: auto;
|
||||
bottom: calc(100% + 0.5rem);
|
||||
@@ -350,6 +448,12 @@
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.announcement-type-picker__grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(8rem, 1fr));
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.announcement-icon-picker__option {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -363,6 +467,20 @@
|
||||
transition: transform 120ms ease, border-color 120ms ease, background-color 120ms ease, box-shadow 120ms ease;
|
||||
}
|
||||
|
||||
.announcement-type-picker__option {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem;
|
||||
border: 1px solid var(--bs-border-color);
|
||||
border-radius: 0.75rem;
|
||||
background: var(--bs-body-bg);
|
||||
color: var(--bs-body-color);
|
||||
text-align: left;
|
||||
transition: transform 120ms ease, border-color 120ms ease, background-color 120ms ease, box-shadow 120ms ease;
|
||||
}
|
||||
|
||||
.announcement-icon-picker__option:hover,
|
||||
.announcement-icon-picker__option:focus-visible {
|
||||
border-color: rgba(var(--bs-primary-rgb), 0.7);
|
||||
@@ -371,6 +489,14 @@
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.announcement-type-picker__option:hover,
|
||||
.announcement-type-picker__option:focus-visible {
|
||||
border-color: rgba(var(--bs-primary-rgb), 0.7);
|
||||
background: rgba(var(--bs-primary-rgb), 0.04);
|
||||
box-shadow: 0 0 0 0.15rem rgba(var(--bs-primary-rgb), 0.15);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.announcement-icon-picker__option.is-selected {
|
||||
border-color: var(--bs-primary);
|
||||
background: rgba(var(--bs-primary-rgb), 0.12);
|
||||
@@ -378,11 +504,154 @@
|
||||
box-shadow: 0 0 0 0.15rem rgba(var(--bs-primary-rgb), 0.12);
|
||||
}
|
||||
|
||||
.announcement-type-picker__option.is-selected {
|
||||
border-color: var(--bs-primary);
|
||||
box-shadow: 0 0 0 0.15rem rgba(var(--bs-primary-rgb), 0.12);
|
||||
}
|
||||
|
||||
.announcement-icon-picker__option i {
|
||||
font-size: 1.05rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.announcement-type-picker__option-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 2.5rem;
|
||||
border-radius: 0.65rem;
|
||||
background: rgba(var(--bs-primary-rgb), 0.1);
|
||||
color: var(--bs-primary);
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.announcement-type-picker__option-icon i {
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.announcement-type-picker__label {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.1;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.announcement-screen-picker {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 0.5rem;
|
||||
max-height: 18rem;
|
||||
padding: 0.25rem;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.announcement-screen-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.announcement-screen-action {
|
||||
flex: 1 1 9rem;
|
||||
}
|
||||
|
||||
.announcement-screen-option {
|
||||
position: relative;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.announcement-screen-option > .btn-check {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.announcement-screen-chip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
min-height: 2.5rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border: 1px solid var(--bs-border-color);
|
||||
border-radius: 0.875rem;
|
||||
background: var(--bs-body-bg);
|
||||
color: var(--bs-body-color);
|
||||
cursor: pointer;
|
||||
transition: transform 120ms ease, border-color 120ms ease, background-color 120ms ease, box-shadow 120ms ease;
|
||||
}
|
||||
|
||||
.announcement-screen-chip:hover,
|
||||
.announcement-screen-chip:focus-visible {
|
||||
border-color: rgba(var(--bs-primary-rgb), 0.7);
|
||||
background: rgba(var(--bs-primary-rgb), 0.04);
|
||||
box-shadow: 0 0 0 0.15rem rgba(var(--bs-primary-rgb), 0.12);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.announcement-screen-option > .btn-check:checked + .announcement-screen-chip {
|
||||
border-color: var(--bs-primary);
|
||||
background: rgba(var(--bs-primary-rgb), 0.08);
|
||||
box-shadow: 0 0 0 0.15rem rgba(var(--bs-primary-rgb), 0.12);
|
||||
}
|
||||
|
||||
.announcement-screen-chip__check {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-left: auto;
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
border-radius: 999px;
|
||||
background: rgba(var(--bs-primary-rgb), 0.1);
|
||||
color: var(--bs-primary);
|
||||
opacity: 0;
|
||||
transform: scale(0.85);
|
||||
transition: opacity 120ms ease, transform 120ms ease, background-color 120ms ease, color 120ms ease;
|
||||
}
|
||||
|
||||
.announcement-screen-chip__check-icon {
|
||||
font-size: 0.9rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.announcement-screen-option > .btn-check:checked + .announcement-screen-chip .announcement-screen-chip__check {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
|
||||
.announcement-screen-chip__text {
|
||||
display: block;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
@media (max-width: 576px) {
|
||||
.announcement-screen-picker {
|
||||
max-height: 16rem;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 576px) {
|
||||
.announcement-type-picker__menu {
|
||||
width: calc(100vw - 2rem);
|
||||
right: 0;
|
||||
left: auto;
|
||||
}
|
||||
|
||||
.announcement-type-picker__grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(7rem, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 576px) {
|
||||
.announcement-icon-picker__menu {
|
||||
width: calc(100vw - 2rem);
|
||||
@@ -425,7 +694,8 @@
|
||||
|
||||
.table-pagination-page .app-content {
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.table-pagination-page .app-content .container-fluid {
|
||||
@@ -461,7 +731,7 @@
|
||||
display: flex;
|
||||
flex: 0 1 auto;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
min-height: var(--table-pagination-card-min-height, 0);
|
||||
max-height: var(--table-pagination-card-max-height, var(--background-tasks-task-card-max-height, calc(100dvh - 12rem)));
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -607,6 +877,67 @@
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.dashboard-launcher-actions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: flex-end;
|
||||
align-items: flex-end;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.dashboard-launcher-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.dashboard-launcher-copy {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dashboard-kiosk-launcher-confirmation {
|
||||
background: var(--bs-tertiary-bg);
|
||||
}
|
||||
|
||||
.dashboard-kiosk-launcher-confirmation .form-check.form-switch {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding-left: 0;
|
||||
}
|
||||
|
||||
.dashboard-kiosk-launcher-confirmation .form-check-input {
|
||||
float: none;
|
||||
margin: 0;
|
||||
transform: scale(0.92);
|
||||
transform-origin: left center;
|
||||
}
|
||||
|
||||
.dashboard-kiosk-launcher-confirmation .form-check-label {
|
||||
letter-spacing: 0.01em;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.dashboard-launcher-open-button {
|
||||
min-width: 5rem;
|
||||
}
|
||||
|
||||
.dashboard-kiosk-launcher-download {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.dashboard-kiosk-launcher-download.disabled,
|
||||
.dashboard-kiosk-launcher-download[aria-disabled='true'] {
|
||||
pointer-events: none;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.dashboard-launcher-download {
|
||||
width: 9rem;
|
||||
}
|
||||
|
||||
.screen-command-card .card-header {
|
||||
padding-top: 1rem;
|
||||
padding-bottom: 1rem;
|
||||
@@ -1179,6 +1510,31 @@ html[data-bs-theme='dark'] .template-field-card .tox .tox-collection {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.slide-preview-text-content {
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.slide-preview-text-content > * {
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
.slide-preview-text-content > *:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.slide-preview-text-content > *:last-child {
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
|
||||
.slide-preview-text-content ul,
|
||||
.slide-preview-text-content ol {
|
||||
padding-left: 1.2em;
|
||||
}
|
||||
|
||||
.slide-preview-text-content code {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.slide-preview-image {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
@@ -1844,6 +2200,83 @@ html[data-bs-theme='dark'] .template-field-card .tox .tox-collection {
|
||||
border-radius: var(--bs-border-radius);
|
||||
}
|
||||
|
||||
.announcement-color-picker {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.announcement-color-picker__grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(8, minmax(0, 1fr));
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.announcement-color-picker__option {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 0.375rem;
|
||||
padding: 0.375rem;
|
||||
border: 1px solid var(--bs-border-color);
|
||||
border-radius: 0.75rem;
|
||||
background: var(--bs-body-bg);
|
||||
color: var(--bs-body-color);
|
||||
text-align: left;
|
||||
transition: transform 120ms ease, border-color 120ms ease, background-color 120ms ease, box-shadow 120ms ease;
|
||||
}
|
||||
|
||||
.announcement-color-picker__option:hover,
|
||||
.announcement-color-picker__option:focus-visible {
|
||||
border-color: rgba(var(--bs-primary-rgb), 0.7);
|
||||
background: rgba(var(--bs-primary-rgb), 0.04);
|
||||
box-shadow: 0 0 0 0.15rem rgba(var(--bs-primary-rgb), 0.15);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.announcement-color-picker__option.is-selected {
|
||||
border-color: var(--bs-primary);
|
||||
box-shadow: 0 0 0 0.15rem rgba(var(--bs-primary-rgb), 0.12);
|
||||
}
|
||||
|
||||
.announcement-color-picker__swatch {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 2.5rem;
|
||||
border-radius: 0.65rem;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.announcement-color-picker__check {
|
||||
opacity: 0;
|
||||
transform: scale(0.8);
|
||||
transition: opacity 120ms ease, transform 120ms ease;
|
||||
}
|
||||
|
||||
.announcement-color-picker__option.is-selected .announcement-color-picker__check {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
|
||||
.announcement-color-picker__label {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.1;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.announcement-color-picker__grid {
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.announcement-color-picker__grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
.announcement-icon-preview {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1871,7 +2304,8 @@ html[data-bs-theme='dark'] .template-field-card .tox .tox-collection {
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
padding-top: 0.25rem;
|
||||
margin-bottom: 0.75rem;
|
||||
padding-bottom: 0.5rem;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.api-region-placeholder-title {
|
||||
@@ -2220,6 +2654,50 @@ html[data-bs-theme='dark'] .template-field-card .tox .tox-collection {
|
||||
flex: 1 1 0;
|
||||
}
|
||||
|
||||
.schedule-day-grid .schedule-day-option {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.schedule-day-grid .schedule-day-option > .btn-check {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.schedule-day-grid .schedule-day-option > .schedule-day-button {
|
||||
width: 100%;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.schedule-day-grid .schedule-day-option:first-child > .schedule-day-button {
|
||||
border-top-left-radius: var(--bs-btn-border-radius);
|
||||
border-bottom-left-radius: var(--bs-btn-border-radius);
|
||||
}
|
||||
|
||||
.schedule-day-grid .schedule-day-option:last-child > .schedule-day-button {
|
||||
border-top-right-radius: var(--bs-btn-border-radius);
|
||||
border-bottom-right-radius: var(--bs-btn-border-radius);
|
||||
}
|
||||
|
||||
.schedule-day-grid .schedule-day-option + .schedule-day-option {
|
||||
margin-left: -1px;
|
||||
}
|
||||
|
||||
.schedule-day-grid .schedule-day-button.is-invalid {
|
||||
color: var(--bs-danger);
|
||||
border-color: var(--bs-danger);
|
||||
background-color: rgba(var(--bs-danger-rgb), 0.08);
|
||||
}
|
||||
|
||||
.schedule-day-grid .btn-check:checked + .schedule-day-button.is-invalid {
|
||||
color: #fff;
|
||||
border-color: var(--bs-danger);
|
||||
background-color: var(--bs-danger);
|
||||
}
|
||||
|
||||
.slide-schedule-dialog {
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
@@ -2283,11 +2761,9 @@ html[data-bs-theme='dark'] .template-field-card .tox .tox-collection {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.slide-schedule-content .schedule-rule-card.collapsed-card > .card-body {
|
||||
display: block !important;
|
||||
padding: 0 !important;
|
||||
max-height: 0;
|
||||
overflow: hidden;
|
||||
.slide-schedule-content .schedule-rule-card.collapsed-card > .card-body,
|
||||
.slide-schedule-content .schedule-rule-card.collapsed-card > .card-footer {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.slide-schedule-content .schedule-rule-card.collapsed-card .card-header {
|
||||
@@ -2332,8 +2808,18 @@ td[data-label="Actions"] > div {
|
||||
}
|
||||
|
||||
.playlist-duration-input {
|
||||
width: 6rem;
|
||||
min-width: 6rem;
|
||||
width: 4rem !important;
|
||||
min-width: 4rem !important;
|
||||
flex: 0 0 4rem !important;
|
||||
}
|
||||
|
||||
.playlist-duration-input-group {
|
||||
display: inline-flex !important;
|
||||
flex: 0 0 auto !important;
|
||||
width: fit-content !important;
|
||||
max-width: fit-content !important;
|
||||
border-radius: var(--bs-border-radius-sm);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.playlist-duration-input::-webkit-outer-spin-button,
|
||||
@@ -2356,6 +2842,13 @@ td[data-label="Actions"] > div {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.playlist-duration-prefix {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.playlist-use-video-duration {
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -2424,13 +2917,24 @@ table.table > :not(caption) > * > * {
|
||||
.playlist-order-cell {
|
||||
width: 1%;
|
||||
white-space: nowrap;
|
||||
vertical-align: top;
|
||||
padding-top: 0 !important;
|
||||
padding-bottom: 0 !important;
|
||||
}
|
||||
|
||||
.playlist-order-cell-inner {
|
||||
display: inline-flex;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
width: 100%;
|
||||
gap: 0.65rem;
|
||||
}
|
||||
|
||||
.playlist-order-stepper {
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.02rem;
|
||||
}
|
||||
|
||||
.playlist-drag-handle {
|
||||
@@ -2438,26 +2942,46 @@ table.table > :not(caption) > * > * {
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.35rem;
|
||||
height: 1.9rem;
|
||||
height: 1.35rem;
|
||||
line-height: 1;
|
||||
cursor: grab;
|
||||
cursor: grab !important;
|
||||
text-decoration: none;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.playlist-drag-handle:hover,
|
||||
.playlist-drag-handle:focus {
|
||||
cursor: grab !important;
|
||||
}
|
||||
|
||||
.playlist-drag-handle:active,
|
||||
.playlist-drag-handle[aria-grabbed="true"] {
|
||||
cursor: grabbing !important;
|
||||
}
|
||||
|
||||
.playlist-drag-handle-icon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.1rem;
|
||||
height: 1.9rem;
|
||||
height: 1.1rem;
|
||||
font-size: 1rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.playlist-drag-handle-svg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
fill: currentColor;
|
||||
.playlist-order-move {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.15rem;
|
||||
height: 1.15rem;
|
||||
line-height: 1;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.playlist-order-move:hover,
|
||||
.playlist-order-move:focus {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.playlist-drag-handle:active,
|
||||
|
||||
@@ -157,10 +157,14 @@
|
||||
return Boolean(form && form.dataset && form.dataset.dirty === 'true');
|
||||
}
|
||||
|
||||
function isRegionEditorField(target) {
|
||||
return Boolean(target && typeof target.closest === 'function' && target.closest('.region-item'));
|
||||
}
|
||||
|
||||
function initDirtyTracking() {
|
||||
document.addEventListener('input', function (event) {
|
||||
var target = event.target;
|
||||
if (!target || !target.form) {
|
||||
if (!target || !target.form || isRegionEditorField(target)) {
|
||||
return;
|
||||
}
|
||||
markFormDirty(target.form);
|
||||
@@ -168,13 +172,101 @@
|
||||
|
||||
document.addEventListener('change', function (event) {
|
||||
var target = event.target;
|
||||
if (!target || !target.form) {
|
||||
if (!target || !target.form || isRegionEditorField(target)) {
|
||||
return;
|
||||
}
|
||||
markFormDirty(target.form);
|
||||
}, true);
|
||||
}
|
||||
|
||||
function clampLimitedInputValue(input) {
|
||||
if (!input || !input.matches || !input.matches('input[data-limit-input-value]')) {
|
||||
return;
|
||||
}
|
||||
|
||||
var minAttr = input.getAttribute('min');
|
||||
var maxAttr = input.getAttribute('max');
|
||||
var minValue = minAttr === null || minAttr === '' ? null : Number(minAttr);
|
||||
var maxValue = maxAttr === null || maxAttr === '' ? null : Number(maxAttr);
|
||||
var rawValue = String(input.value || '').trim();
|
||||
|
||||
if (!rawValue) {
|
||||
return;
|
||||
}
|
||||
|
||||
var numericValue = Number(rawValue);
|
||||
if (!Number.isFinite(numericValue)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Number.isFinite(minValue) && numericValue < minValue) {
|
||||
input.value = String(minValue);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Number.isFinite(maxValue) && numericValue > maxValue) {
|
||||
input.value = String(maxValue);
|
||||
}
|
||||
}
|
||||
|
||||
function initLimitedInputValues() {
|
||||
document.addEventListener('input', function (event) {
|
||||
clampLimitedInputValue(event.target);
|
||||
}, true);
|
||||
|
||||
document.addEventListener('change', function (event) {
|
||||
clampLimitedInputValue(event.target);
|
||||
}, true);
|
||||
|
||||
document.addEventListener('paste', function (event) {
|
||||
var target = event.target;
|
||||
if (!target || !target.matches || !target.matches('input[data-limit-input-value]')) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.setTimeout(function () {
|
||||
clampLimitedInputValue(target);
|
||||
}, 0);
|
||||
}, true);
|
||||
}
|
||||
|
||||
function clampLimitedTextValue(input) {
|
||||
if (!input || !input.matches || !input.matches('input[data-limit-text-length], textarea[data-limit-text-length]')) {
|
||||
return;
|
||||
}
|
||||
|
||||
var maxLength = Number(input.getAttribute('maxlength'));
|
||||
if (!Number.isFinite(maxLength) || maxLength < 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
var value = String(input.value || '');
|
||||
if (value.length > maxLength) {
|
||||
input.value = value.slice(0, maxLength);
|
||||
}
|
||||
}
|
||||
|
||||
function initLimitedTextInputValues() {
|
||||
document.addEventListener('input', function (event) {
|
||||
clampLimitedTextValue(event.target);
|
||||
}, true);
|
||||
|
||||
document.addEventListener('change', function (event) {
|
||||
clampLimitedTextValue(event.target);
|
||||
}, true);
|
||||
|
||||
document.addEventListener('paste', function (event) {
|
||||
var target = event.target;
|
||||
if (!target || !target.matches || !target.matches('input[data-limit-text-length], textarea[data-limit-text-length]')) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.setTimeout(function () {
|
||||
clampLimitedTextValue(target);
|
||||
}, 0);
|
||||
}, true);
|
||||
}
|
||||
|
||||
function initCancelConfirm() {
|
||||
document.addEventListener('click', function (event) {
|
||||
var cancelTarget = event.target.closest('[data-confirm-unsaved]');
|
||||
@@ -210,6 +302,24 @@
|
||||
return savedMessage;
|
||||
}
|
||||
|
||||
function parseAsyncSaveErrorMessage(responseText) {
|
||||
var errorMessage = parseAsyncSaveResponseMessage(responseText);
|
||||
if (errorMessage) {
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
return String(responseText || '').trim();
|
||||
}
|
||||
|
||||
function isWarningSaveError(error) {
|
||||
var status = Number(error && error.status);
|
||||
if (status === 400 || status === 422) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return /region names must be unique/i.test(String(error && error.message || ''));
|
||||
}
|
||||
|
||||
function getAsyncSaveActionField(form) {
|
||||
if (!form || !form.querySelector) {
|
||||
return null;
|
||||
@@ -302,7 +412,10 @@
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(await response.text() || (settings.errorMessage || 'Unable to save changes.'));
|
||||
var responseText = await response.text();
|
||||
var error = new Error(parseAsyncSaveErrorMessage(responseText) || (settings.errorMessage || 'Unable to save changes.'));
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (isLoginRedirect(response)) {
|
||||
@@ -353,11 +466,25 @@
|
||||
})
|
||||
: parseAsyncSaveResponseMessage(responseText);
|
||||
|
||||
showToast(successMessage || String(settings.fallbackSuccessMessage || 'Saved.'), 'success');
|
||||
var resolvedSuccessMessage = successMessage || String(settings.fallbackSuccessMessage || 'Saved.');
|
||||
|
||||
if (form.dataset && form.dataset.asyncSaveRefreshPage === 'true') {
|
||||
if (typeof window.queueToastAfterRefresh === 'function') {
|
||||
window.queueToastAfterRefresh(resolvedSuccessMessage, 'success');
|
||||
} else if (typeof showToast === 'function') {
|
||||
showToast(resolvedSuccessMessage, 'success');
|
||||
}
|
||||
window.setTimeout(function () {
|
||||
window.location.reload();
|
||||
}, 1000);
|
||||
return true;
|
||||
}
|
||||
|
||||
showToast(resolvedSuccessMessage, 'success');
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (typeof showToast === 'function') {
|
||||
var variant = Number(error && error.status) >= 400 && Number(error && error.status) < 500 ? 'warning' : 'danger';
|
||||
var variant = isWarningSaveError(error) ? 'warning' : 'danger';
|
||||
showToast(error && error.message ? error.message : (settings.errorMessage || 'Unable to save changes.'), variant);
|
||||
} else {
|
||||
window.alert(error && error.message ? error.message : (settings.errorMessage || 'Unable to save changes.'));
|
||||
@@ -812,7 +939,7 @@
|
||||
return;
|
||||
}
|
||||
|
||||
element.textContent = formatDashboardDate(date);
|
||||
element.textContent = formatDashboardDate(date, element.getAttribute('data-local-datetime-format') === '24h');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -852,6 +979,8 @@
|
||||
initConfirmForms();
|
||||
initDeleteButtons();
|
||||
initDirtyTracking();
|
||||
initLimitedInputValues();
|
||||
initLimitedTextInputValues();
|
||||
initCancelConfirm();
|
||||
initAsyncCommandForms();
|
||||
initAsyncSaveForms();
|
||||
@@ -862,6 +991,10 @@
|
||||
attachSlideThumbFallbacks(document);
|
||||
window.initJsonTogglePanels = initJsonTogglePanels;
|
||||
window.initLocalDateTimes = initLocalDateTimes;
|
||||
window.clampLimitedInputValue = clampLimitedInputValue;
|
||||
window.initLimitedInputValues = initLimitedInputValues;
|
||||
window.clampLimitedTextValue = clampLimitedTextValue;
|
||||
window.initLimitedTextInputValues = initLimitedTextInputValues;
|
||||
window.createSlideThumbPlaceholder = createSlideThumbPlaceholder;
|
||||
window.attachSlideThumbFallbacks = attachSlideThumbFallbacks;
|
||||
}());
|
||||
|
||||
@@ -18,21 +18,127 @@ function updateAnnouncementDurationFields() {
|
||||
}
|
||||
}
|
||||
|
||||
function updateAnnouncementColorPreview() {
|
||||
var colorSelect = document.getElementById('announcement-color');
|
||||
var preview = document.querySelector('[data-announcement-color-preview]');
|
||||
if (!colorSelect || !preview) {
|
||||
function updateAnnouncementColorPickerSelection() {
|
||||
var colorInput = document.getElementById('announcement-color');
|
||||
var picker = document.querySelector('[data-announcement-color-picker-shell]');
|
||||
if (!colorInput || !picker) {
|
||||
return;
|
||||
}
|
||||
|
||||
var selectedOption = colorSelect.options[colorSelect.selectedIndex] || null;
|
||||
var colorKey = String(colorSelect.value || '').trim().toLowerCase() || 'primary';
|
||||
var label = selectedOption ? String(selectedOption.textContent || selectedOption.label || colorKey).trim() : colorKey;
|
||||
var selectedValue = String(colorInput.value || '').trim().toLowerCase() || 'primary';
|
||||
picker.querySelectorAll('[data-announcement-color-option]').forEach(function (button) {
|
||||
var isSelected = String(button.getAttribute('data-color-key') || '').trim().toLowerCase() === selectedValue;
|
||||
button.classList.toggle('is-selected', isSelected);
|
||||
button.setAttribute('aria-pressed', isSelected ? 'true' : 'false');
|
||||
});
|
||||
}
|
||||
|
||||
preview.className = 'announcement-color-preview text-bg-' + colorKey;
|
||||
preview.setAttribute('aria-label', label);
|
||||
preview.setAttribute('title', label);
|
||||
preview.textContent = '';
|
||||
function setAnnouncementScreenSelection(isSelected) {
|
||||
document.querySelectorAll('input[name="screen_ids[]"]').forEach(function (input) {
|
||||
input.checked = isSelected;
|
||||
});
|
||||
}
|
||||
|
||||
function positionAnnouncementTypePicker() {
|
||||
var picker = document.querySelector('[data-announcement-type-picker]');
|
||||
var toggle = document.querySelector('[data-announcement-type-picker-toggle]');
|
||||
var shell = document.querySelector('[data-announcement-type-picker-shell]');
|
||||
if (!picker || picker.hidden || !toggle || !shell) {
|
||||
return;
|
||||
}
|
||||
|
||||
var padding = 8;
|
||||
var toggleRect = toggle.getBoundingClientRect();
|
||||
var menuRect = picker.getBoundingClientRect();
|
||||
var viewportHeight = window.innerHeight || document.documentElement.clientHeight || toggleRect.bottom;
|
||||
var placementAbove = false;
|
||||
var spaceBelow = viewportHeight - toggleRect.bottom - padding;
|
||||
var spaceAbove = toggleRect.top - padding;
|
||||
|
||||
if (menuRect.height > spaceBelow && spaceAbove > spaceBelow) {
|
||||
placementAbove = true;
|
||||
}
|
||||
|
||||
picker.classList.toggle('is-open-above', placementAbove);
|
||||
}
|
||||
|
||||
function closeAnnouncementTypePicker() {
|
||||
var picker = document.querySelector('[data-announcement-type-picker]');
|
||||
var toggle = document.querySelector('[data-announcement-type-picker-toggle]');
|
||||
if (!picker) {
|
||||
return;
|
||||
}
|
||||
|
||||
picker.hidden = true;
|
||||
picker.classList.remove('is-open-above');
|
||||
if (toggle) {
|
||||
toggle.setAttribute('aria-expanded', 'false');
|
||||
}
|
||||
}
|
||||
|
||||
function openAnnouncementTypePicker() {
|
||||
var picker = document.querySelector('[data-announcement-type-picker]');
|
||||
var toggle = document.querySelector('[data-announcement-type-picker-toggle]');
|
||||
if (!picker) {
|
||||
return;
|
||||
}
|
||||
|
||||
picker.hidden = false;
|
||||
if (toggle) {
|
||||
toggle.setAttribute('aria-expanded', 'true');
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined' && window.requestAnimationFrame) {
|
||||
window.requestAnimationFrame(positionAnnouncementTypePicker);
|
||||
} else {
|
||||
positionAnnouncementTypePicker();
|
||||
}
|
||||
}
|
||||
|
||||
function updateAnnouncementTypePickerSelection() {
|
||||
var typeInput = document.getElementById('announcement-type');
|
||||
var previewButton = document.querySelector('[data-announcement-type-picker-toggle]');
|
||||
var picker = document.querySelector('[data-announcement-type-picker]');
|
||||
if (!typeInput || !previewButton || !picker) {
|
||||
return;
|
||||
}
|
||||
|
||||
var selectedValue = String(typeInput.value || '').trim().toLowerCase();
|
||||
var selectedOption = picker.querySelector('[data-announcement-type-option][data-type-key="' + selectedValue + '"]');
|
||||
var label = selectedOption ? String(selectedOption.getAttribute('data-type-label') || selectedOption.textContent || selectedValue).trim() : selectedValue;
|
||||
var iconKey = selectedOption ? String(selectedOption.getAttribute('data-type-icon') || '').trim().toLowerCase() : '';
|
||||
var icon = previewButton.querySelector('[data-announcement-type-picker-icon]');
|
||||
var text = previewButton.querySelector('[data-announcement-type-picker-label]');
|
||||
|
||||
previewButton.setAttribute('aria-label', label);
|
||||
previewButton.setAttribute('title', label);
|
||||
if (icon) {
|
||||
icon.className = 'bi bi-' + iconKey;
|
||||
}
|
||||
if (text) {
|
||||
text.textContent = label;
|
||||
}
|
||||
|
||||
picker.querySelectorAll('[data-announcement-type-option]').forEach(function (button) {
|
||||
var isSelected = String(button.getAttribute('data-type-key') || '').trim().toLowerCase() === selectedValue;
|
||||
button.classList.toggle('is-selected', isSelected);
|
||||
button.setAttribute('aria-pressed', isSelected ? 'true' : 'false');
|
||||
});
|
||||
}
|
||||
|
||||
function setAnnouncementTypeValue(typeKey) {
|
||||
var typeInput = document.getElementById('announcement-type');
|
||||
if (!typeInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
var normalized = String(typeKey || '').trim().toLowerCase();
|
||||
if (!normalized) {
|
||||
return;
|
||||
}
|
||||
|
||||
typeInput.value = normalized;
|
||||
updateAnnouncementTypePickerSelection();
|
||||
}
|
||||
|
||||
function updateAnnouncementIconPreview() {
|
||||
@@ -155,21 +261,90 @@ function setAnnouncementIconValue(iconKey) {
|
||||
}
|
||||
|
||||
function initAnnouncementForm() {
|
||||
var typeInput = document.getElementById('announcement-type');
|
||||
var typePickerToggle = document.querySelector('[data-announcement-type-picker-toggle]');
|
||||
var typePicker = document.querySelector('[data-announcement-type-picker]');
|
||||
var typePickerClose = document.querySelector('[data-announcement-type-picker-close]');
|
||||
var modeSelect = document.getElementById('announcement-duration-mode');
|
||||
var colorSelect = document.getElementById('announcement-color');
|
||||
var colorInput = document.getElementById('announcement-color');
|
||||
var colorPicker = document.querySelector('[data-announcement-color-picker-shell]');
|
||||
var screenSelectAll = document.querySelector('[data-announcement-screen-select-all]');
|
||||
var screenSelectNone = document.querySelector('[data-announcement-screen-select-none]');
|
||||
var iconSelect = document.getElementById('announcement-icon');
|
||||
var iconPickerToggle = document.querySelector('[data-announcement-icon-picker-toggle]');
|
||||
var iconPicker = document.querySelector('[data-announcement-icon-picker]');
|
||||
var iconPickerClose = document.querySelector('[data-announcement-icon-picker-close]');
|
||||
|
||||
if (typeInput) {
|
||||
updateAnnouncementTypePickerSelection();
|
||||
}
|
||||
|
||||
if (typePickerToggle) {
|
||||
typePickerToggle.addEventListener('click', function (event) {
|
||||
event.preventDefault();
|
||||
var isExpanded = typePicker && !typePicker.hidden;
|
||||
if (isExpanded) {
|
||||
closeAnnouncementTypePicker();
|
||||
} else {
|
||||
openAnnouncementTypePicker();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (typePickerClose) {
|
||||
typePickerClose.addEventListener('click', function (event) {
|
||||
event.preventDefault();
|
||||
closeAnnouncementTypePicker();
|
||||
});
|
||||
}
|
||||
|
||||
if (typePicker) {
|
||||
typePicker.addEventListener('click', function (event) {
|
||||
var button = event.target && event.target.closest ? event.target.closest('[data-announcement-type-option]') : null;
|
||||
if (!button) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
setAnnouncementTypeValue(button.getAttribute('data-type-key'));
|
||||
closeAnnouncementTypePicker();
|
||||
});
|
||||
}
|
||||
|
||||
if (modeSelect) {
|
||||
modeSelect.addEventListener('change', updateAnnouncementDurationFields);
|
||||
updateAnnouncementDurationFields();
|
||||
}
|
||||
|
||||
if (colorSelect) {
|
||||
colorSelect.addEventListener('change', updateAnnouncementColorPreview);
|
||||
updateAnnouncementColorPreview();
|
||||
if (colorInput) {
|
||||
updateAnnouncementColorPickerSelection();
|
||||
}
|
||||
|
||||
if (colorPicker) {
|
||||
colorPicker.addEventListener('click', function (event) {
|
||||
var button = event.target && event.target.closest ? event.target.closest('[data-announcement-color-option]') : null;
|
||||
if (!button) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
colorInput.value = String(button.getAttribute('data-color-key') || '').trim().toLowerCase();
|
||||
updateAnnouncementColorPickerSelection();
|
||||
});
|
||||
}
|
||||
|
||||
if (screenSelectAll) {
|
||||
screenSelectAll.addEventListener('click', function (event) {
|
||||
event.preventDefault();
|
||||
setAnnouncementScreenSelection(true);
|
||||
});
|
||||
}
|
||||
|
||||
if (screenSelectNone) {
|
||||
screenSelectNone.addEventListener('click', function (event) {
|
||||
event.preventDefault();
|
||||
setAnnouncementScreenSelection(false);
|
||||
});
|
||||
}
|
||||
|
||||
if (iconSelect) {
|
||||
@@ -210,8 +385,17 @@ function initAnnouncementForm() {
|
||||
}
|
||||
|
||||
window.addEventListener('resize', positionAnnouncementIconPicker);
|
||||
window.addEventListener('resize', positionAnnouncementTypePicker);
|
||||
|
||||
document.addEventListener('click', function (event) {
|
||||
var typePickerNode = document.querySelector('[data-announcement-type-picker]');
|
||||
var typeToggleNode = document.querySelector('[data-announcement-type-picker-toggle]');
|
||||
if (typePickerNode && !typePickerNode.hidden) {
|
||||
if (!(typePickerNode.contains(event.target) || (typeToggleNode && typeToggleNode.contains(event.target)))) {
|
||||
closeAnnouncementTypePicker();
|
||||
}
|
||||
}
|
||||
|
||||
var picker = document.querySelector('[data-announcement-icon-picker]');
|
||||
var toggle = document.querySelector('[data-announcement-icon-picker-toggle]');
|
||||
if (!picker || picker.hidden) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -9,6 +9,29 @@
|
||||
var methodSelect = form.querySelector('[data-api-source-auth-method]');
|
||||
var authDetailsSection = form.querySelector('[data-api-source-auth-details-section]');
|
||||
var panels = Array.prototype.slice.call(form.querySelectorAll('[data-api-source-auth-panel]'));
|
||||
var bearerTokenInput = form.querySelector('[data-api-source-bearer-token-input]');
|
||||
var bearerTokenToggle = form.querySelector('[data-api-source-bearer-token-toggle]');
|
||||
|
||||
function updateBearerTokenToggle() {
|
||||
if (!bearerTokenInput || !bearerTokenToggle) {
|
||||
return;
|
||||
}
|
||||
|
||||
var isVisible = bearerTokenInput.type === 'text';
|
||||
bearerTokenToggle.setAttribute('aria-pressed', String(isVisible));
|
||||
bearerTokenToggle.setAttribute('aria-label', isVisible ? 'Hide bearer token' : 'Show bearer token');
|
||||
bearerTokenToggle.innerHTML = '<i class="bi ' + (isVisible ? 'bi-eye-slash' : 'bi-eye') + '" aria-hidden="true"></i>';
|
||||
}
|
||||
|
||||
function toggleBearerTokenVisibility() {
|
||||
if (!bearerTokenInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
bearerTokenInput.type = bearerTokenInput.type === 'password' ? 'text' : 'password';
|
||||
updateBearerTokenToggle();
|
||||
bearerTokenInput.focus();
|
||||
}
|
||||
|
||||
function updatePanels() {
|
||||
var method = String(methodSelect && methodSelect.value || 'none').trim();
|
||||
@@ -28,5 +51,10 @@
|
||||
methodSelect.addEventListener('change', updatePanels);
|
||||
}
|
||||
|
||||
if (bearerTokenToggle && bearerTokenInput) {
|
||||
bearerTokenToggle.addEventListener('click', toggleBearerTokenVisibility);
|
||||
updateBearerTokenToggle();
|
||||
}
|
||||
|
||||
updatePanels();
|
||||
}());
|
||||
@@ -10,6 +10,10 @@
|
||||
return;
|
||||
}
|
||||
|
||||
function markDirty() {
|
||||
form.dataset.dirty = 'true';
|
||||
}
|
||||
|
||||
function pad(value) {
|
||||
return String(value).padStart(2, '0');
|
||||
}
|
||||
@@ -43,6 +47,101 @@
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
function parseDateTimeLocalValue(value) {
|
||||
var raw = String(value || '').trim();
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
var date = new Date(raw);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
function clearFieldValidity(input) {
|
||||
if (!input) {
|
||||
return;
|
||||
}
|
||||
|
||||
input.setCustomValidity('');
|
||||
input.classList.remove('is-invalid');
|
||||
if (input.removeAttribute) {
|
||||
input.removeAttribute('aria-invalid');
|
||||
}
|
||||
}
|
||||
|
||||
function setFieldValidity(input, message) {
|
||||
if (!input) {
|
||||
return;
|
||||
}
|
||||
|
||||
input.setCustomValidity(message);
|
||||
input.classList.add('is-invalid');
|
||||
if (input.setAttribute) {
|
||||
input.setAttribute('aria-invalid', 'true');
|
||||
}
|
||||
}
|
||||
|
||||
function validateEntryRow(row) {
|
||||
if (!row) {
|
||||
return;
|
||||
}
|
||||
|
||||
var startInput = row.querySelector('[name="entry_start_datetime[]"]');
|
||||
var endInput = row.querySelector('[name="entry_end_datetime[]"]');
|
||||
var startValue;
|
||||
var endValue;
|
||||
var startDate;
|
||||
var endDate;
|
||||
|
||||
clearFieldValidity(endInput);
|
||||
|
||||
if (!startInput || !endInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
startValue = String(startInput.value || '').trim();
|
||||
endValue = String(endInput.value || '').trim();
|
||||
|
||||
if (!startValue || !endValue) {
|
||||
return;
|
||||
}
|
||||
|
||||
startDate = parseDateTimeLocalValue(startValue);
|
||||
endDate = parseDateTimeLocalValue(endValue);
|
||||
|
||||
if (!startDate || !endDate) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (endDate.getTime() < startDate.getTime() + 60000) {
|
||||
setFieldValidity(endInput, 'End time must be at least 1 minute after the start time.');
|
||||
}
|
||||
}
|
||||
|
||||
function bindRowValidation(row) {
|
||||
if (!row) {
|
||||
return;
|
||||
}
|
||||
|
||||
var startInput = row.querySelector('[name="entry_start_datetime[]"]');
|
||||
var endInput = row.querySelector('[name="entry_end_datetime[]"]');
|
||||
|
||||
if (!startInput || !endInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
function handleValidation() {
|
||||
validateEntryRow(row);
|
||||
}
|
||||
|
||||
startInput.addEventListener('input', handleValidation);
|
||||
startInput.addEventListener('change', handleValidation);
|
||||
endInput.addEventListener('input', handleValidation);
|
||||
endInput.addEventListener('change', handleValidation);
|
||||
|
||||
validateEntryRow(row);
|
||||
}
|
||||
|
||||
function toUtcDateTimeLocalValue(value) {
|
||||
var localDate = new Date(String(value || '').trim());
|
||||
return Number.isNaN(localDate.getTime()) ? '' : localDate.toISOString();
|
||||
@@ -95,6 +194,7 @@
|
||||
}
|
||||
button.addEventListener('click', function () {
|
||||
row.remove();
|
||||
markDirty();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -105,12 +205,15 @@
|
||||
return;
|
||||
}
|
||||
bindRemove(row);
|
||||
bindRowValidation(row);
|
||||
body.appendChild(fragment);
|
||||
markDirty();
|
||||
}
|
||||
|
||||
body.querySelectorAll('[data-timetable-entry-row]').forEach(function (row) {
|
||||
bindRemove(row);
|
||||
syncRowValuesToLocal(row);
|
||||
bindRowValidation(row);
|
||||
});
|
||||
|
||||
form.addEventListener('formdata', function (event) {
|
||||
|
||||
@@ -197,6 +197,341 @@
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function parseLocalDate(value) {
|
||||
var date = new Date(String(value || '').trim());
|
||||
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
|
||||
}
|
||||
|
||||
function isDayInDateRange(startDatetime, endDatetime, dayIndex) {
|
||||
var startDate = parseLocalDate(startDatetime);
|
||||
var endDate = parseLocalDate(endDatetime);
|
||||
var currentDate;
|
||||
|
||||
if (!startDate || !endDate) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (currentDate = new Date(startDate.getTime()); currentDate.getTime() <= endDate.getTime(); currentDate.setDate(currentDate.getDate() + 1)) {
|
||||
if (currentDate.getDay() === Number(dayIndex)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function getTimeParts(value) {
|
||||
var match = String(value || '').trim().match(/^(\d{2}):(\d{2})(?::\d{2})?$/);
|
||||
|
||||
if (!match) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
hours: Number(match[1]),
|
||||
minutes: Number(match[2])
|
||||
};
|
||||
}
|
||||
|
||||
function combineDateAndTime(baseDate, timeValue) {
|
||||
var timeParts = getTimeParts(timeValue);
|
||||
|
||||
if (!baseDate || !timeParts) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Date(
|
||||
baseDate.getFullYear(),
|
||||
baseDate.getMonth(),
|
||||
baseDate.getDate(),
|
||||
timeParts.hours,
|
||||
timeParts.minutes,
|
||||
0,
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
function hasScheduleRuleOverlap(startDatetime, endDatetime, startTime, endTime, selectedDays) {
|
||||
var startDateTime = new Date(String(startDatetime || '').trim());
|
||||
var endDateTime = new Date(String(endDatetime || '').trim());
|
||||
var startDate = parseLocalDate(startDatetime);
|
||||
var endDate = parseLocalDate(endDatetime);
|
||||
var allowedDays = Array.isArray(selectedDays) && selectedDays.length ? selectedDays : [0, 1, 2, 3, 4, 5, 6];
|
||||
var currentDate;
|
||||
|
||||
if (!startDate || !endDate || Number.isNaN(startDateTime.getTime()) || Number.isNaN(endDateTime.getTime())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (currentDate = new Date(startDate.getTime()); currentDate.getTime() <= endDate.getTime(); currentDate.setDate(currentDate.getDate() + 1)) {
|
||||
if (allowedDays.indexOf(currentDate.getDay()) === -1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
var dayStart = combineDateAndTime(currentDate, startTime);
|
||||
var dayEnd = combineDateAndTime(currentDate, endTime);
|
||||
|
||||
if (!dayStart || !dayEnd) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (dayEnd >= startDateTime && dayStart <= endDateTime) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
function getDateRangeDayIndices(startDatetime, endDatetime) {
|
||||
var startDate = parseLocalDate(startDatetime);
|
||||
var endDate = parseLocalDate(endDatetime);
|
||||
var dayIndices = [];
|
||||
var currentDate;
|
||||
|
||||
if (!startDate || !endDate) {
|
||||
return dayIndices;
|
||||
}
|
||||
|
||||
for (currentDate = new Date(startDate.getTime()); currentDate.getTime() <= endDate.getTime(); currentDate.setDate(currentDate.getDate() + 1)) {
|
||||
if (dayIndices.indexOf(currentDate.getDay()) === -1) {
|
||||
dayIndices.push(currentDate.getDay());
|
||||
}
|
||||
}
|
||||
|
||||
return dayIndices;
|
||||
}
|
||||
|
||||
function setDayInputError(card, dayInput, message) {
|
||||
var dayInputs = card ? Array.prototype.slice.call(card.querySelectorAll('[data-schedule-rule-day]')) : [];
|
||||
var dayLabels = card ? Array.prototype.slice.call(card.querySelectorAll('.schedule-day-button')) : [];
|
||||
var feedbackNode = card ? card.querySelector('[data-schedule-rule-feedback]') : null;
|
||||
var dayIndex = dayInputs.indexOf(dayInput);
|
||||
|
||||
if (dayInput) {
|
||||
dayInput.setCustomValidity(message);
|
||||
dayInput.classList.add('is-invalid');
|
||||
dayInput.setAttribute('aria-invalid', 'true');
|
||||
}
|
||||
|
||||
if (dayIndex !== -1 && dayLabels[dayIndex]) {
|
||||
dayLabels[dayIndex].classList.add('is-invalid');
|
||||
dayLabels[dayIndex].setAttribute('aria-invalid', 'true');
|
||||
}
|
||||
|
||||
if (feedbackNode) {
|
||||
var messageNode = document.createElement('div');
|
||||
messageNode.textContent = message;
|
||||
feedbackNode.appendChild(messageNode);
|
||||
feedbackNode.hidden = false;
|
||||
}
|
||||
}
|
||||
|
||||
function appendRuleFeedbackMessage(card, message) {
|
||||
var feedbackNode = card ? card.querySelector('[data-schedule-rule-feedback]') : null;
|
||||
|
||||
if (!feedbackNode) {
|
||||
return;
|
||||
}
|
||||
|
||||
var messageNode = document.createElement('div');
|
||||
messageNode.textContent = message;
|
||||
feedbackNode.appendChild(messageNode);
|
||||
feedbackNode.hidden = false;
|
||||
}
|
||||
|
||||
function validateScheduleRuleCard(card) {
|
||||
var fields = getRuleFields(card);
|
||||
var dayInputs = Array.prototype.slice.call(fields.days || []);
|
||||
var dayLabels = getRuleDayLabels(card);
|
||||
var checkedDayInputs = dayInputs.filter(function (input) {
|
||||
return Boolean(input && input.checked);
|
||||
});
|
||||
var checkedDayIndices = checkedDayInputs.map(function (input) {
|
||||
return Number(input && input.value);
|
||||
});
|
||||
var startDatetime = String(fields.startDatetime && fields.startDatetime.value || '').trim();
|
||||
var endDatetime = String(fields.endDatetime && fields.endDatetime.value || '').trim();
|
||||
var startTime = String(fields.startTime && fields.startTime.value || '').trim();
|
||||
var endTime = String(fields.endTime && fields.endTime.value || '').trim();
|
||||
clearRuleValidity(card);
|
||||
|
||||
if ((startDatetime || endDatetime) && (!startDatetime || !endDatetime)) {
|
||||
setRuleError(!startDatetime ? fields.startDatetime : fields.endDatetime, 'Start and end datetimes must both be set for this rule.');
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((startTime || endTime) && (!startTime || !endTime)) {
|
||||
setRuleError(!startTime ? fields.startTime : fields.endTime, 'Start and end times must both be set for this rule.');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (startDatetime && endDatetime && new Date(endDatetime) <= new Date(startDatetime)) {
|
||||
setRuleError(fields.endDatetime, 'End datetime must be after start datetime.');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (startTime && endTime && endTime <= startTime) {
|
||||
setRuleError(fields.endTime, 'End time must be after start time.');
|
||||
if (fields.startTime) {
|
||||
fields.startTime.classList.add('is-invalid');
|
||||
fields.startTime.setAttribute('aria-invalid', 'true');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (startDatetime && endDatetime) {
|
||||
var dateRangeDayIndices = getDateRangeDayIndices(startDatetime, endDatetime);
|
||||
var dayIndicesToCheck = checkedDayIndices.length ? checkedDayIndices : [0, 1, 2, 3, 4, 5, 6];
|
||||
var invalidDayInputs = checkedDayInputs.filter(function (input) {
|
||||
return dateRangeDayIndices.indexOf(Number(input && input.value)) === -1;
|
||||
});
|
||||
|
||||
invalidDayInputs.forEach(function (input) {
|
||||
var dayIndex = dayInputs.indexOf(input);
|
||||
|
||||
if (dayIndex !== -1 && dayLabels[dayIndex]) {
|
||||
dayLabels[dayIndex].classList.add('is-invalid');
|
||||
dayLabels[dayIndex].setAttribute('aria-invalid', 'true');
|
||||
}
|
||||
});
|
||||
|
||||
if (checkedDayInputs.length && invalidDayInputs.length === checkedDayInputs.length) {
|
||||
setDayInputError(card, invalidDayInputs[0] || checkedDayInputs[0] || dayInputs[0], 'Selected days must overlap the date range.');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (startTime && endTime && !hasScheduleRuleOverlap(startDatetime, endDatetime, startTime, endTime, dayIndicesToCheck)) {
|
||||
setRuleError(fields.endTime, 'Start and end times must overlap the date range.');
|
||||
if (fields.startTime) {
|
||||
fields.startTime.classList.add('is-invalid');
|
||||
fields.startTime.setAttribute('aria-invalid', 'true');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function getScheduleRuleValidationIssue(card) {
|
||||
var fields = getRuleFields(card);
|
||||
var dayInputs = Array.prototype.slice.call(fields.days || []);
|
||||
var checkedDayInputs = dayInputs.filter(function (input) {
|
||||
return Boolean(input && input.checked);
|
||||
});
|
||||
var checkedDayIndices = checkedDayInputs.map(function (input) {
|
||||
return Number(input && input.value);
|
||||
});
|
||||
var startDatetime = String(fields.startDatetime && fields.startDatetime.value || '').trim();
|
||||
var endDatetime = String(fields.endDatetime && fields.endDatetime.value || '').trim();
|
||||
var startTime = String(fields.startTime && fields.startTime.value || '').trim();
|
||||
var endTime = String(fields.endTime && fields.endTime.value || '').trim();
|
||||
|
||||
if (startDatetime || endDatetime) {
|
||||
if (!startDatetime || !endDatetime) {
|
||||
return {
|
||||
type: 'datetime-pair',
|
||||
target: !startDatetime ? fields.startDatetime : fields.endDatetime,
|
||||
message: 'Start and end datetimes must both be set for this rule.'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (startTime || endTime) {
|
||||
if (!startTime || !endTime) {
|
||||
return {
|
||||
type: 'time-pair',
|
||||
target: !startTime ? fields.startTime : fields.endTime,
|
||||
message: 'Start and end times must both be set for this rule.'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (startDatetime && endDatetime && new Date(endDatetime) <= new Date(startDatetime)) {
|
||||
return {
|
||||
type: 'datetime-order',
|
||||
target: fields.endDatetime,
|
||||
message: 'End datetime must be after start datetime.'
|
||||
};
|
||||
}
|
||||
|
||||
if (startTime && endTime && endTime <= startTime) {
|
||||
return {
|
||||
type: 'time-order',
|
||||
target: fields.endTime,
|
||||
message: 'End time must be after start time.'
|
||||
};
|
||||
}
|
||||
|
||||
if (startDatetime && endDatetime) {
|
||||
var dateRangeDayIndices = getDateRangeDayIndices(startDatetime, endDatetime);
|
||||
var dayIndicesToCheck = checkedDayIndices.length ? checkedDayIndices : [0, 1, 2, 3, 4, 5, 6];
|
||||
var invalidDayInputs = checkedDayInputs.filter(function (input) {
|
||||
return dateRangeDayIndices.indexOf(Number(input && input.value)) === -1;
|
||||
});
|
||||
|
||||
if (checkedDayInputs.length && invalidDayInputs.length === checkedDayInputs.length) {
|
||||
return {
|
||||
type: 'day-overlap',
|
||||
target: checkedDayInputs[0] || dayInputs[0] || fields.endDatetime,
|
||||
message: 'Selected days must overlap the date range.'
|
||||
};
|
||||
}
|
||||
|
||||
if (startTime && endTime && !hasScheduleRuleOverlap(startDatetime, endDatetime, startTime, endTime, dayIndicesToCheck)) {
|
||||
return {
|
||||
type: 'time-overlap',
|
||||
target: fields.endTime,
|
||||
secondaryTarget: fields.startTime,
|
||||
message: 'Start and end times must overlap the date range.'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function applyScheduleRuleValidationIssue(card, issue) {
|
||||
var fields = getRuleFields(card);
|
||||
var dayLabels = getRuleDayLabels(card);
|
||||
|
||||
clearRuleValidity(card);
|
||||
|
||||
if (!issue) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (issue.type === 'time-overlap') {
|
||||
setRuleError(issue.target || fields.endTime, issue.message);
|
||||
if (issue.secondaryTarget) {
|
||||
issue.secondaryTarget.classList.add('is-invalid');
|
||||
issue.secondaryTarget.setAttribute('aria-invalid', 'true');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (issue.type === 'day-overlap') {
|
||||
var dayInputs = Array.prototype.slice.call(fields.days || []);
|
||||
var dayIndex = dayInputs.indexOf(issue.target);
|
||||
|
||||
setRuleError(issue.target, issue.message);
|
||||
if (dayIndex !== -1 && dayLabels[dayIndex]) {
|
||||
dayLabels[dayIndex].classList.add('is-invalid');
|
||||
dayLabels[dayIndex].setAttribute('aria-invalid', 'true');
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
setRuleError(issue.target, issue.message);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Video duration helpers.
|
||||
function getVideoDurationButtonLabel(isPressed) {
|
||||
return isPressed ? 'Disable use video duration' : 'Use video duration';
|
||||
@@ -213,7 +548,7 @@
|
||||
return '';
|
||||
}
|
||||
|
||||
return '<button type="button" class="btn btn-outline-info btn-sm playlist-use-video-duration' + (isPressed ? ' active' : '') + '" data-use-video-duration-button aria-pressed="' + (isPressed ? 'true' : 'false') + '" aria-label="' + getVideoDurationButtonLabel(isPressed) + '" title="' + getVideoDurationButtonLabel(isPressed) + '">' + buildVideoDurationButtonContent(isPressed) + '</button>';
|
||||
return '<button type="button" class="btn ' + (isPressed ? 'btn-info' : 'btn-outline-info') + ' btn-sm playlist-use-video-duration" data-use-video-duration-button aria-pressed="' + (isPressed ? 'true' : 'false') + '" aria-label="' + getVideoDurationButtonLabel(isPressed) + '" title="' + getVideoDurationButtonLabel(isPressed) + '">' + buildVideoDurationButtonContent(isPressed) + '</button>';
|
||||
}
|
||||
|
||||
function getDisableAudioButtonLabel(isPressed) {
|
||||
@@ -241,7 +576,6 @@
|
||||
|
||||
button.classList.toggle('btn-outline-secondary', Boolean(isPressed));
|
||||
button.classList.toggle('btn-secondary', !Boolean(isPressed));
|
||||
button.classList.toggle('active', !Boolean(isPressed));
|
||||
button.setAttribute('aria-pressed', isPressed ? 'true' : 'false');
|
||||
button.setAttribute('aria-label', getDisableAudioButtonLabel(isPressed));
|
||||
button.setAttribute('title', getDisableAudioButtonLabel(isPressed));
|
||||
@@ -253,7 +587,8 @@
|
||||
return;
|
||||
}
|
||||
|
||||
button.classList.toggle('active', Boolean(isPressed));
|
||||
button.classList.toggle('btn-outline-info', !Boolean(isPressed));
|
||||
button.classList.toggle('btn-info', Boolean(isPressed));
|
||||
button.setAttribute('aria-pressed', isPressed ? 'true' : 'false');
|
||||
button.setAttribute('aria-label', getVideoDurationButtonLabel(isPressed));
|
||||
button.setAttribute('title', getVideoDurationButtonLabel(isPressed));
|
||||
@@ -382,7 +717,11 @@
|
||||
return '' +
|
||||
'<td class="playlist-order-cell" data-label="Order">' +
|
||||
'<div class="playlist-order-cell-inner">' +
|
||||
'<button type="button" class="playlist-drag-handle btn btn-link p-0 text-body-secondary" data-playlist-drag-handle aria-label="Drag to reorder" title="Drag to reorder"><span class="playlist-drag-handle-icon" aria-hidden="true"><svg class="playlist-drag-handle-svg" viewBox="0 0 24 32" focusable="false" aria-hidden="true"><polygon points="12,2 20,9 4,9"></polygon><rect x="4" y="14" width="16" height="4" rx="2"></rect><polygon points="4,23 20,23 12,30"></polygon></svg></span></button>' +
|
||||
'<div class="playlist-order-stepper" aria-label="Reorder slide controls">' +
|
||||
'<button type="button" class="playlist-order-move playlist-order-move-up btn btn-link p-0 text-body-secondary" data-playlist-row-move="up" aria-label="Move slide up" title="Move slide up"><i class="bi bi-caret-up-fill" aria-hidden="true" data-playlist-row-move-icon="up"></i></button>' +
|
||||
'<button type="button" class="playlist-drag-handle btn btn-link p-0 text-body-secondary" data-playlist-drag-handle aria-label="Drag to reorder" title="Drag to reorder"><span class="playlist-drag-handle-icon" aria-hidden="true"><i class="bi bi-grip-horizontal"></i></span></button>' +
|
||||
'<button type="button" class="playlist-order-move playlist-order-move-down btn btn-link p-0 text-body-secondary" data-playlist-row-move="down" aria-label="Move slide down" title="Move slide down"><i class="bi bi-caret-down-fill" aria-hidden="true" data-playlist-row-move-icon="down"></i></button>' +
|
||||
'</div>' +
|
||||
'<span class="playlist-order-number"></span>' +
|
||||
'</div>' +
|
||||
'</td>';
|
||||
@@ -412,8 +751,11 @@
|
||||
|
||||
function buildPlaylistDurationCellMarkup(values, durationActionMarkup) {
|
||||
return '' +
|
||||
'<td data-label="Config"><div class="playlist-duration-field">' +
|
||||
'<input name="duration_seconds[]" type="text" inputmode="decimal" value="' + values.duration_seconds + '" required form="playlist-edit-form" class="form-control form-control-sm playlist-duration-input text-end"' + (values.useVideoDuration ? ' disabled' : '') + ' />' +
|
||||
'<td data-label="Playback"><div class="playlist-duration-field">' +
|
||||
'<div class="input-group input-group-sm flex-nowrap playlist-duration-input-group">' +
|
||||
'<span class="input-group-text playlist-duration-prefix text-body-secondary" aria-hidden="true"><i class="bi bi-clock"></i></span>' +
|
||||
'<input name="duration_seconds[]" type="text" inputmode="decimal" min="1" value="' + values.duration_seconds + '" required form="playlist-edit-form" class="form-control form-control-sm playlist-duration-input text-end" data-limit-input-value' + (values.useVideoDuration ? ' disabled' : '') + ' />' +
|
||||
'</div>' +
|
||||
'<input type="hidden" name="use_video_duration[]" value="' + (values.useVideoDuration ? '1' : '0') + '" form="playlist-edit-form" />' +
|
||||
'<input type="hidden" name="disable_audio[]" value="' + (values.disableAudio ? '1' : '0') + '" form="playlist-edit-form" data-playlist-disable-audio-input />' +
|
||||
(values.useVideoDuration ? '<input type="hidden" name="duration_seconds[]" value="' + values.duration_seconds + '" form="playlist-edit-form" data-video-duration-mirror />' : '') +
|
||||
@@ -478,9 +820,18 @@
|
||||
});
|
||||
}
|
||||
|
||||
function closeScheduleModal() {
|
||||
function closeScheduleModal(options) {
|
||||
var dialog = document.getElementById('slide-schedule-dialog');
|
||||
var content = document.getElementById('slide-schedule-content');
|
||||
var shouldDiscardDraft = Boolean(options && options.discardDraft);
|
||||
var shouldPreserveChanges = Boolean(options && options.preserveChanges);
|
||||
|
||||
if (shouldDiscardDraft && !shouldPreserveChanges && typeof window.restorePlaylistScheduleDraft === 'function') {
|
||||
window.restorePlaylistScheduleDraft();
|
||||
}
|
||||
if (shouldDiscardDraft && typeof window.clearPlaylistScheduleDraft === 'function') {
|
||||
window.clearPlaylistScheduleDraft();
|
||||
}
|
||||
|
||||
if (content) {
|
||||
content.innerHTML = '';
|
||||
@@ -577,8 +928,7 @@
|
||||
'<div class="d-flex align-items-center gap-4 ms-auto flex-shrink-0">' +
|
||||
'<button type="button" class="btn btn-sm btn-outline-danger" data-remove-schedule-rule data-confirm-message="Remove this rule?">Remove</button>' +
|
||||
'<button type="button" class="btn btn-tool p-0 text-body-secondary" data-lte-toggle="card-collapse" aria-label="Collapse rule ' + String(ruleIndex) + '" title="Collapse rule ' + String(ruleIndex) + '">' +
|
||||
'<i class="bi bi-dash-lg" aria-hidden="true" data-lte-icon="collapse"></i>' +
|
||||
'<i class="bi bi-plus-lg" aria-hidden="true" data-lte-icon="expand"></i>' +
|
||||
'<i class="bi ' + (isCollapsed ? 'bi-plus-lg' : 'bi-dash-lg') + '" aria-hidden="true" data-schedule-rule-collapse-icon></i>' +
|
||||
'<span class="visually-hidden">Collapse rule ' + String(ruleIndex) + '</span>' +
|
||||
'</button>' +
|
||||
'</div>' +
|
||||
@@ -605,11 +955,14 @@
|
||||
'</div>' +
|
||||
'<div class="col-12">' +
|
||||
'<div class="btn-group btn-group-sm w-100 schedule-day-grid" role="group" aria-label="Schedule days">' + DAY_NAMES.map(function (label, dayIndex) {
|
||||
return '<input class="btn-check" type="checkbox" id="schedule-rule-' + String(ruleIndex) + '-day-' + String(dayIndex) + '" value="' + String(dayIndex) + '" autocomplete="off"' + (selectedDays.has(dayIndex) ? ' checked' : '') + ' data-schedule-rule-day />' +
|
||||
'<label class="btn btn-outline-primary flex-fill schedule-day-button" for="schedule-rule-' + String(ruleIndex) + '-day-' + String(dayIndex) + '">' + label + '</label>';
|
||||
return '<span class="schedule-day-option">' +
|
||||
'<input class="btn-check" type="checkbox" id="schedule-rule-' + String(ruleIndex) + '-day-' + String(dayIndex) + '" value="' + String(dayIndex) + '" autocomplete="off"' + (selectedDays.has(dayIndex) ? ' checked' : '') + ' data-schedule-rule-day />' +
|
||||
'<label class="btn btn-outline-primary flex-fill schedule-day-button" for="schedule-rule-' + String(ruleIndex) + '-day-' + String(dayIndex) + '">' + label + '</label>' +
|
||||
'</span>';
|
||||
}).join('') + '</div>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<div class="invalid-feedback d-block mt-2" data-schedule-rule-feedback aria-live="polite" hidden></div>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
}
|
||||
@@ -629,6 +982,7 @@
|
||||
var isDraftMode = Boolean(form.getAttribute('data-schedule-draft') === 'true');
|
||||
var rowKeyInput = form.querySelector('[name="row_key"]');
|
||||
var draftStore = window.__playlistScheduleDraftStore = window.__playlistScheduleDraftStore || {};
|
||||
var draftSnapshotStore = window.__playlistScheduleDraftSnapshotStore = window.__playlistScheduleDraftSnapshotStore || {};
|
||||
var cancelButton = scope.querySelector('[data-schedule-cancel]');
|
||||
|
||||
// Draft state is keyed by the row being edited so cancel/save can restore it later.
|
||||
@@ -659,6 +1013,41 @@
|
||||
};
|
||||
}
|
||||
|
||||
function captureScheduleDraftState() {
|
||||
return getRuleCards().map(function (card) {
|
||||
return {
|
||||
rule: readRuleDraftFromCard(card),
|
||||
isCollapsed: Boolean(card && card.classList && card.classList.contains('collapsed-card'))
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function renderScheduleDraftState(ruleStates) {
|
||||
var states = Array.isArray(ruleStates) ? ruleStates : [];
|
||||
|
||||
scheduleRuleList.innerHTML = '';
|
||||
states.forEach(function (ruleState, index) {
|
||||
var card = createRuleCardElement(ruleState && ruleState.rule ? ruleState.rule : {}, index + 1, { isCollapsed: Boolean(ruleState && ruleState.isCollapsed) });
|
||||
|
||||
if (card) {
|
||||
scheduleRuleList.appendChild(card);
|
||||
}
|
||||
});
|
||||
refreshRuleNumbers();
|
||||
syncScheduleRulesField();
|
||||
}
|
||||
|
||||
function restoreScheduleDraft() {
|
||||
var draftKey = getScheduleDraftKey();
|
||||
var snapshot = draftKey && Object.prototype.hasOwnProperty.call(draftSnapshotStore, draftKey) ? draftSnapshotStore[draftKey] : null;
|
||||
|
||||
if (!draftKey || !Array.isArray(snapshot)) {
|
||||
return;
|
||||
}
|
||||
|
||||
renderScheduleDraftState(snapshot);
|
||||
}
|
||||
|
||||
function getScheduleDraftRules() {
|
||||
var draftKey = getScheduleDraftKey();
|
||||
if (!draftKey || !Object.prototype.hasOwnProperty.call(draftStore, draftKey)) {
|
||||
@@ -687,9 +1076,18 @@
|
||||
if (draftKey && Object.prototype.hasOwnProperty.call(draftStore, draftKey)) {
|
||||
delete draftStore[draftKey];
|
||||
}
|
||||
if (draftKey && Object.prototype.hasOwnProperty.call(draftSnapshotStore, draftKey)) {
|
||||
delete draftSnapshotStore[draftKey];
|
||||
}
|
||||
}
|
||||
|
||||
window.clearPlaylistScheduleDraft = clearScheduleDraft;
|
||||
window.restorePlaylistScheduleDraft = restoreScheduleDraft;
|
||||
|
||||
var draftKey = getScheduleDraftKey();
|
||||
if (draftKey && !Object.prototype.hasOwnProperty.call(draftSnapshotStore, draftKey)) {
|
||||
draftSnapshotStore[draftKey] = captureScheduleDraftState();
|
||||
}
|
||||
|
||||
function getRuleCards() {
|
||||
return Array.prototype.slice.call(scheduleRuleList.querySelectorAll('[data-schedule-rule-card]'));
|
||||
@@ -725,13 +1123,71 @@
|
||||
return card ? card.querySelector('[data-remove-schedule-rule]') : null;
|
||||
}
|
||||
|
||||
function getRuleDayLabels(card) {
|
||||
return card ? Array.prototype.slice.call(card.querySelectorAll('.schedule-day-button')) : [];
|
||||
}
|
||||
|
||||
function getCollapseRuleButton(card) {
|
||||
return card ? card.querySelector('[data-schedule-rule-collapse], [data-lte-toggle="card-collapse"]') : null;
|
||||
}
|
||||
|
||||
function getCollapseRuleIcon(card) {
|
||||
return card ? card.querySelector('[data-schedule-rule-collapse-icon]') : null;
|
||||
}
|
||||
|
||||
function syncRuleCollapseButtonState(card) {
|
||||
var button = getCollapseRuleButton(card);
|
||||
var icon = getCollapseRuleIcon(card);
|
||||
var numberNode = getRuleNumberNode(card);
|
||||
var ruleIndex = numberNode ? String(numberNode.textContent || '') : '';
|
||||
var isCollapsed = Boolean(card && card.classList && card.classList.contains('collapsed-card'));
|
||||
var label = (isCollapsed ? 'Expand' : 'Collapse') + ' rule ' + ruleIndex;
|
||||
|
||||
if (!button) {
|
||||
return;
|
||||
}
|
||||
|
||||
button.setAttribute('aria-expanded', isCollapsed ? 'false' : 'true');
|
||||
button.setAttribute('aria-label', label);
|
||||
button.setAttribute('title', label);
|
||||
|
||||
if (icon) {
|
||||
icon.classList.remove('bi-dash-lg', 'bi-plus-lg');
|
||||
icon.classList.add(isCollapsed ? 'bi-plus-lg' : 'bi-dash-lg');
|
||||
}
|
||||
|
||||
var visibleLabel = button.querySelector('.visually-hidden');
|
||||
if (visibleLabel) {
|
||||
visibleLabel.textContent = label;
|
||||
}
|
||||
}
|
||||
|
||||
function clearRuleValidity(card) {
|
||||
var fields = getRuleFields(card);
|
||||
var dayInputs = Array.prototype.slice.call(fields.days || []);
|
||||
var dayLabels = getRuleDayLabels(card);
|
||||
var feedbackNode = card ? card.querySelector('[data-schedule-rule-feedback]') : null;
|
||||
[fields.startDatetime, fields.endDatetime, fields.startTime, fields.endTime].forEach(function (input) {
|
||||
if (input) {
|
||||
input.setCustomValidity('');
|
||||
input.classList.remove('is-invalid');
|
||||
input.removeAttribute('aria-invalid');
|
||||
}
|
||||
});
|
||||
dayInputs.forEach(function (input) {
|
||||
input.setCustomValidity('');
|
||||
input.classList.remove('is-invalid');
|
||||
input.removeAttribute('aria-invalid');
|
||||
});
|
||||
dayLabels.forEach(function (label) {
|
||||
label.classList.remove('is-invalid');
|
||||
label.removeAttribute('aria-invalid');
|
||||
});
|
||||
|
||||
if (feedbackNode) {
|
||||
feedbackNode.innerHTML = '';
|
||||
feedbackNode.hidden = true;
|
||||
}
|
||||
}
|
||||
|
||||
function setRuleError(input, message) {
|
||||
@@ -739,37 +1195,96 @@
|
||||
return;
|
||||
}
|
||||
input.setCustomValidity(message);
|
||||
if (String(input.value || '').trim()) {
|
||||
input.classList.add('is-invalid');
|
||||
input.setAttribute('aria-invalid', 'true');
|
||||
}
|
||||
|
||||
function validateRuleCard(card) {
|
||||
appendRuleFeedbackMessage(input.closest ? input.closest('[data-schedule-rule-card]') : null, message);
|
||||
}
|
||||
|
||||
function validateScheduleRuleCard(card) {
|
||||
var fields = getRuleFields(card);
|
||||
var dayInputs = Array.prototype.slice.call(fields.days || []);
|
||||
var dayLabels = getRuleDayLabels(card);
|
||||
var checkedDayInputs = dayInputs.filter(function (input) {
|
||||
return Boolean(input && input.checked);
|
||||
});
|
||||
var checkedDayIndices = checkedDayInputs.map(function (input) {
|
||||
return Number(input && input.value);
|
||||
});
|
||||
var startDatetime = String(fields.startDatetime && fields.startDatetime.value || '').trim();
|
||||
var endDatetime = String(fields.endDatetime && fields.endDatetime.value || '').trim();
|
||||
var startTime = String(fields.startTime && fields.startTime.value || '').trim();
|
||||
var endTime = String(fields.endTime && fields.endTime.value || '').trim();
|
||||
var hasDateInput = Boolean(startDatetime || endDatetime);
|
||||
var hasTimeInput = Boolean(startTime || endTime);
|
||||
var isValid = true;
|
||||
|
||||
clearRuleValidity(card);
|
||||
|
||||
if (hasDateInput && (!startDatetime || !endDatetime)) {
|
||||
setRuleError(fields.startDatetime || fields.endDatetime, 'Start and end datetimes must both be set for this rule.');
|
||||
return false;
|
||||
}
|
||||
if (hasTimeInput && (!startTime || !endTime)) {
|
||||
setRuleError(fields.startTime || fields.endTime, 'Start and end times must both be set for this rule.');
|
||||
return false;
|
||||
}
|
||||
if (startDatetime && endDatetime && new Date(endDatetime) < new Date(startDatetime)) {
|
||||
setRuleError(fields.endDatetime, 'End datetime must be after start datetime.');
|
||||
return false;
|
||||
}
|
||||
if (startTime && endTime && endTime < startTime) {
|
||||
setRuleError(fields.endTime, 'End time must be after start time.');
|
||||
return false;
|
||||
if ((startDatetime || endDatetime) && (!startDatetime || !endDatetime)) {
|
||||
setRuleError(!startDatetime ? fields.startDatetime : fields.endDatetime, 'Start and end datetimes must both be set for this rule.');
|
||||
isValid = false;
|
||||
}
|
||||
|
||||
return true;
|
||||
if ((startTime || endTime) && (!startTime || !endTime)) {
|
||||
setRuleError(!startTime ? fields.startTime : fields.endTime, 'Start and end times must both be set for this rule.');
|
||||
isValid = false;
|
||||
}
|
||||
|
||||
if (startDatetime && endDatetime && new Date(endDatetime) <= new Date(startDatetime)) {
|
||||
setRuleError(fields.endDatetime, 'End datetime must be after start datetime.');
|
||||
isValid = false;
|
||||
}
|
||||
|
||||
if (startTime && endTime && endTime <= startTime) {
|
||||
setRuleError(fields.endTime, 'End time must be after start time.');
|
||||
if (fields.startTime) {
|
||||
fields.startTime.classList.add('is-invalid');
|
||||
fields.startTime.setAttribute('aria-invalid', 'true');
|
||||
}
|
||||
isValid = false;
|
||||
}
|
||||
|
||||
if (startDatetime && endDatetime) {
|
||||
var dateRangeDayIndices = getDateRangeDayIndices(startDatetime, endDatetime);
|
||||
var dayIndicesToCheck = checkedDayIndices.length ? checkedDayIndices : [0, 1, 2, 3, 4, 5, 6];
|
||||
var invalidDayInputs = checkedDayInputs.filter(function (input) {
|
||||
return dateRangeDayIndices.indexOf(Number(input && input.value)) === -1;
|
||||
});
|
||||
|
||||
invalidDayInputs.forEach(function (input) {
|
||||
var dayIndex = dayInputs.indexOf(input);
|
||||
|
||||
if (dayIndex !== -1 && dayLabels[dayIndex]) {
|
||||
dayLabels[dayIndex].classList.add('is-invalid');
|
||||
dayLabels[dayIndex].setAttribute('aria-invalid', 'true');
|
||||
}
|
||||
});
|
||||
|
||||
if (checkedDayInputs.length && invalidDayInputs.length === checkedDayInputs.length) {
|
||||
setDayInputError(card, checkedDayInputs[0] || dayInputs[0], 'Selected days must overlap the date range.');
|
||||
isValid = false;
|
||||
}
|
||||
|
||||
if (startTime && endTime && !hasScheduleRuleOverlap(startDatetime, endDatetime, startTime, endTime, dayIndicesToCheck)) {
|
||||
setRuleError(fields.endTime, 'Start and end times must overlap the date range.');
|
||||
if (fields.startTime) {
|
||||
fields.startTime.classList.add('is-invalid');
|
||||
fields.startTime.setAttribute('aria-invalid', 'true');
|
||||
}
|
||||
isValid = false;
|
||||
}
|
||||
}
|
||||
|
||||
return isValid;
|
||||
}
|
||||
|
||||
function updateLiveRuleValidity(card) {
|
||||
validateScheduleRuleCard(card);
|
||||
}
|
||||
|
||||
function validateRuleCard(card) {
|
||||
return validateScheduleRuleCard(card);
|
||||
}
|
||||
|
||||
function readRuleFromCard(card) {
|
||||
@@ -924,37 +1439,47 @@
|
||||
card.querySelector('[data-schedule-rule-start-time]').value = String(normalizedRule.start_time || '');
|
||||
card.querySelector('[data-schedule-rule-end-time]').value = String(normalizedRule.end_time || '');
|
||||
card.querySelector('[data-remove-schedule-rule]').setAttribute('data-confirm-message', 'Remove this rule?');
|
||||
card.querySelector('[data-lte-toggle="card-collapse"]').setAttribute('aria-label', 'Collapse rule ' + String(ruleIndex));
|
||||
card.querySelector('[data-lte-toggle="card-collapse"]').setAttribute('title', 'Collapse rule ' + String(ruleIndex));
|
||||
card.querySelector('[data-lte-toggle="card-collapse"] .visually-hidden').textContent = 'Collapse rule ' + String(ruleIndex);
|
||||
updateRuleCardDayOptions(card, ruleKey, normalizedRule);
|
||||
|
||||
card.querySelector('[data-lte-toggle="card-collapse"]').addEventListener('click', function (event) {
|
||||
event.preventDefault();
|
||||
card.classList.toggle('collapsed-card');
|
||||
persistScheduleDraft();
|
||||
});
|
||||
|
||||
if (isCollapsed) {
|
||||
card.classList.add('collapsed-card');
|
||||
} else {
|
||||
card.classList.remove('collapsed-card');
|
||||
}
|
||||
|
||||
try {
|
||||
updateLiveRuleValidity(card);
|
||||
} catch (_error) {
|
||||
clearRuleValidity(card);
|
||||
}
|
||||
syncRuleCollapseButtonState(card);
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
function addRule(rule, options) {
|
||||
var ruleCount = getRuleCards().length + 1;
|
||||
var card = createRuleCardElement(rule || {}, ruleCount, options);
|
||||
|
||||
if (!card) {
|
||||
scheduleRuleList.insertAdjacentHTML('beforeend', buildScheduleRuleCardMarkup(rule || {}, ruleCount, Boolean(options && options.isCollapsed)));
|
||||
card = scheduleRuleList.lastElementChild;
|
||||
}
|
||||
|
||||
if (!card) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (card.parentNode !== scheduleRuleList) {
|
||||
scheduleRuleList.appendChild(card);
|
||||
}
|
||||
refreshRuleNumbers();
|
||||
syncScheduleRulesField();
|
||||
return card;
|
||||
}
|
||||
|
||||
function handleCardChange(card) {
|
||||
clearRuleValidity(card);
|
||||
updateLiveRuleValidity(card);
|
||||
updateRuleCardSummary(card);
|
||||
syncScheduleRulesField();
|
||||
}
|
||||
@@ -1020,6 +1545,16 @@
|
||||
|
||||
scheduleRuleList.addEventListener('click', function (event) {
|
||||
var removeButton = event.target && event.target.closest ? event.target.closest('[data-remove-schedule-rule]') : null;
|
||||
var collapseButton = event.target && event.target.closest ? event.target.closest('[data-schedule-rule-collapse], [data-lte-toggle="card-collapse"]') : null;
|
||||
|
||||
if (collapseButton) {
|
||||
window.setTimeout(function () {
|
||||
syncRuleCollapseButtonState(collapseButton.closest('[data-schedule-rule-card]'));
|
||||
persistScheduleDraft();
|
||||
}, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!removeButton) {
|
||||
return;
|
||||
}
|
||||
@@ -1047,16 +1582,14 @@
|
||||
|
||||
var draftRules = getScheduleDraftRules();
|
||||
if (draftRules !== null) {
|
||||
scheduleRuleList.innerHTML = '';
|
||||
draftRules.forEach(function (rule) {
|
||||
addRule(rule && rule.rule ? rule.rule : {}, { isCollapsed: Boolean(rule && rule.isCollapsed) });
|
||||
});
|
||||
syncScheduleRulesField();
|
||||
renderScheduleDraftState(draftRules);
|
||||
} else if (!getRuleCards().length) {
|
||||
syncScheduleRulesField();
|
||||
} else {
|
||||
refreshRuleNumbers();
|
||||
getRuleCards().forEach(function (card) {
|
||||
syncRuleCollapseButtonState(card);
|
||||
updateLiveRuleValidity(card);
|
||||
updateRuleCardSummary(card);
|
||||
});
|
||||
syncScheduleRulesField();
|
||||
@@ -1587,9 +2120,36 @@
|
||||
var rows = getRows();
|
||||
rows.forEach(function (row, index) {
|
||||
var orderNumber = row.querySelector('.playlist-order-number');
|
||||
var moveUpButton = row.querySelector('[data-playlist-row-move="up"]');
|
||||
var moveDownButton = row.querySelector('[data-playlist-row-move="down"]');
|
||||
var moveUpIcon = row.querySelector('[data-playlist-row-move-icon="up"]');
|
||||
var moveDownIcon = row.querySelector('[data-playlist-row-move-icon="down"]');
|
||||
var isFirst = index === 0;
|
||||
var isLast = index === rows.length - 1;
|
||||
|
||||
if (orderNumber) {
|
||||
orderNumber.textContent = String(index + 1);
|
||||
}
|
||||
|
||||
if (moveUpButton) {
|
||||
moveUpButton.disabled = isFirst;
|
||||
moveUpButton.setAttribute('aria-disabled', isFirst ? 'true' : 'false');
|
||||
}
|
||||
|
||||
if (moveUpIcon) {
|
||||
moveUpIcon.classList.toggle('bi-caret-up-fill', !isFirst);
|
||||
moveUpIcon.classList.toggle('bi-caret-up', isFirst);
|
||||
}
|
||||
|
||||
if (moveDownButton) {
|
||||
moveDownButton.disabled = isLast;
|
||||
moveDownButton.setAttribute('aria-disabled', isLast ? 'true' : 'false');
|
||||
}
|
||||
|
||||
if (moveDownIcon) {
|
||||
moveDownIcon.classList.toggle('bi-caret-down-fill', !isLast);
|
||||
moveDownIcon.classList.toggle('bi-caret-down', isLast);
|
||||
}
|
||||
});
|
||||
syncAddSlideOptions();
|
||||
syncPlaylistCanvasLock();
|
||||
@@ -1615,6 +2175,38 @@
|
||||
});
|
||||
}
|
||||
|
||||
function movePlaylistRowByOffset(row, offset) {
|
||||
var currentTbody = document.getElementById('playlist-items-body') || tbody;
|
||||
var rows = getRows();
|
||||
var currentIndex = rows.indexOf(row);
|
||||
var targetIndex;
|
||||
var referenceRow;
|
||||
|
||||
if (!currentTbody || !row || currentIndex === -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
targetIndex = currentIndex + Number(offset || 0);
|
||||
if (targetIndex < 0 || targetIndex >= rows.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
referenceRow = rows[targetIndex];
|
||||
|
||||
if (targetIndex > currentIndex) {
|
||||
referenceRow = referenceRow ? referenceRow.nextSibling : null;
|
||||
}
|
||||
|
||||
if (referenceRow) {
|
||||
currentTbody.insertBefore(row, referenceRow);
|
||||
} else {
|
||||
currentTbody.appendChild(row);
|
||||
}
|
||||
|
||||
updateRowOrder(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
function populatePlaylistSlideRow(row, values, rowKey) {
|
||||
var canvasWidth = Number(values.canvas_width);
|
||||
var canvasHeight = Number(values.canvas_height);
|
||||
@@ -1848,6 +2440,7 @@
|
||||
return;
|
||||
}
|
||||
|
||||
var moveButton = event.target.closest('[data-playlist-row-move]');
|
||||
var removeButton = event.target.closest('[data-playlist-remove-row]');
|
||||
var durationButton = event.target.closest('.playlist-use-video-duration');
|
||||
var muteButton = event.target.closest('.playlist-disable-audio');
|
||||
@@ -1857,6 +2450,13 @@
|
||||
return;
|
||||
}
|
||||
|
||||
if (moveButton) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
movePlaylistRowByOffset(row, moveButton.getAttribute('data-playlist-row-move') === 'up' ? -1 : 1);
|
||||
return;
|
||||
}
|
||||
|
||||
if (removeButton) {
|
||||
event.preventDefault();
|
||||
row.remove();
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
// RBAC permission matrix helpers for checkbox groups.
|
||||
|
||||
(function () {
|
||||
function getGroupCheckboxes(group) {
|
||||
return Array.prototype.slice.call(group.querySelectorAll('input[name="permission_keys[]"]'));
|
||||
function getPermissionSections() {
|
||||
return Array.prototype.slice.call(document.querySelectorAll('[data-permission-section]'));
|
||||
}
|
||||
|
||||
function getPermissionRows(container) {
|
||||
return Array.prototype.slice.call(container.querySelectorAll('[data-permission-row]'));
|
||||
}
|
||||
|
||||
function getRowCheckboxes(row) {
|
||||
return Array.prototype.slice.call(row.querySelectorAll('input[name="permission_keys[]"]'));
|
||||
}
|
||||
|
||||
function getPermissionKey(checkbox) {
|
||||
@@ -19,8 +27,12 @@
|
||||
return String(parts[1] || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function syncPermissionGroup(group) {
|
||||
var checkboxes = getGroupCheckboxes(group);
|
||||
function syncPermissionRow(row) {
|
||||
if (!row) {
|
||||
return;
|
||||
}
|
||||
|
||||
var checkboxes = getRowCheckboxes(row);
|
||||
if (!checkboxes.length) {
|
||||
return;
|
||||
}
|
||||
@@ -55,19 +67,57 @@
|
||||
}
|
||||
}
|
||||
|
||||
function handleGroupChange(event) {
|
||||
function setRowCheckboxes(row, checked) {
|
||||
if (!row) {
|
||||
return;
|
||||
}
|
||||
|
||||
var checkboxes = getRowCheckboxes(row);
|
||||
if (!checkboxes.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
checkboxes.forEach(function (checkbox) {
|
||||
checkbox.checked = Boolean(checked);
|
||||
});
|
||||
|
||||
syncPermissionRow(row);
|
||||
}
|
||||
|
||||
function toggleRowCheckboxes(row) {
|
||||
if (!row) {
|
||||
return;
|
||||
}
|
||||
|
||||
var checkboxes = getRowCheckboxes(row);
|
||||
if (!checkboxes.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
var allChecked = checkboxes.every(function (checkbox) {
|
||||
return Boolean(checkbox.checked);
|
||||
});
|
||||
|
||||
setRowCheckboxes(row, !allChecked);
|
||||
}
|
||||
|
||||
function findPermissionRow(targetId) {
|
||||
return document.querySelector('[data-permission-row-id="' + targetId + '"]');
|
||||
}
|
||||
|
||||
function handleRowChange(event) {
|
||||
var checkbox = event.target && event.target.matches ? event.target : null;
|
||||
if (!checkbox || checkbox.tagName !== 'INPUT' || checkbox.type !== 'checkbox') {
|
||||
return;
|
||||
}
|
||||
|
||||
var actionKey = getActionKey(checkbox);
|
||||
var group = checkbox.closest('.accordion-item');
|
||||
if (!group) {
|
||||
var row = checkbox.closest('[data-permission-row]');
|
||||
if (!row) {
|
||||
return;
|
||||
}
|
||||
|
||||
var checkboxes = getGroupCheckboxes(group);
|
||||
var checkboxes = getRowCheckboxes(row);
|
||||
var readCheckbox = checkboxes.find(function (candidate) {
|
||||
return getActionKey(candidate) === 'read';
|
||||
}) || null;
|
||||
@@ -91,8 +141,28 @@
|
||||
}
|
||||
|
||||
function initPermissionGroups() {
|
||||
document.querySelectorAll('.accordion-item').forEach(function (group) {
|
||||
syncPermissionGroup(group);
|
||||
getPermissionSections().forEach(function (section) {
|
||||
getPermissionRows(section).forEach(function (row) {
|
||||
syncPermissionRow(row);
|
||||
});
|
||||
});
|
||||
|
||||
document.addEventListener('click', function (event) {
|
||||
var control = event.target && event.target.closest ? event.target.closest('[data-permission-row-toggle]') : null;
|
||||
if (!control) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
var targetId = String(control.getAttribute('data-permission-row-target') || '').trim();
|
||||
if (!targetId) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (control.hasAttribute('data-permission-row-toggle')) {
|
||||
toggleRowCheckboxes(findPermissionRow(targetId));
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('change', function (event) {
|
||||
@@ -104,8 +174,8 @@
|
||||
return;
|
||||
}
|
||||
|
||||
handleGroupChange(event);
|
||||
syncPermissionGroup(checkbox.closest('.accordion-item'));
|
||||
handleRowChange(event);
|
||||
syncPermissionRow(checkbox.closest('[data-permission-row]'));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -58,13 +58,26 @@
|
||||
return registry[normalizeType(type)] || null;
|
||||
}
|
||||
|
||||
function getRegionTypeLabel(type, definition) {
|
||||
return String(definition && definition.label ? definition.label : type || '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function compareRegionTypeEntries(left, right) {
|
||||
var leftLabel = getRegionTypeLabel(left && left.type, left && left.definition);
|
||||
var rightLabel = getRegionTypeLabel(right && right.type, right && right.definition);
|
||||
|
||||
return leftLabel.localeCompare(rightLabel, undefined, { sensitivity: 'base' }) || String(left && left.type || '').localeCompare(String(right && right.type || ''), undefined, { sensitivity: 'base' });
|
||||
}
|
||||
|
||||
function list() {
|
||||
return Object.keys(registry).map(function (type) {
|
||||
return {
|
||||
type: type,
|
||||
definition: registry[type] || {}
|
||||
};
|
||||
});
|
||||
}).sort(compareRegionTypeEntries);
|
||||
}
|
||||
|
||||
function getDefaultRegionSize(regionType, lockRatio) {
|
||||
@@ -91,18 +104,38 @@
|
||||
return String(definition.label);
|
||||
}
|
||||
|
||||
var normalized = normalizeType(regionType);
|
||||
if (!normalized) {
|
||||
return 'Region';
|
||||
return 'Text';
|
||||
}
|
||||
|
||||
return normalized
|
||||
.split(/[_-]+/)
|
||||
.filter(function (segment) { return segment; })
|
||||
.map(function (segment) {
|
||||
return segment.charAt(0).toUpperCase() + segment.slice(1);
|
||||
})
|
||||
.join(' ') || 'Region';
|
||||
function escapeHtml(value) {
|
||||
return String(value === undefined || value === null ? '' : value)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function renderEditorCardShell(options) {
|
||||
var settings = options || {};
|
||||
var region = settings.region || {};
|
||||
var cardClass = String(settings.cardClass || 'card card-outline card-secondary admin-form-card template-field-card mb-3');
|
||||
var cardAttrs = String(settings.cardAttrs || '');
|
||||
var cardStyle = settings.cardStyle ? ' style="' + escapeHtml(settings.cardStyle) + '"' : '';
|
||||
var bodyClass = String(settings.bodyClass || 'card-body p-3 d-grid');
|
||||
var bodyAttrs = String(settings.bodyAttrs || '');
|
||||
var bodyStyle = settings.bodyStyle ? ' style="' + escapeHtml(settings.bodyStyle) + '"' : '';
|
||||
var headerActions = String(settings.headerActions || '');
|
||||
var bodyHtml = String(settings.bodyHtml || '');
|
||||
|
||||
return '' +
|
||||
'<div class="' + cardClass + '" data-region-id="' + escapeHtml(region.id) + '"' + cardAttrs + cardStyle + '>' +
|
||||
'<div class="card-header template-field-head">' +
|
||||
'<strong>' + escapeHtml(region.label) + '</strong>' +
|
||||
'<div class="template-field-actions">' + headerActions + '</div>' +
|
||||
'</div>' +
|
||||
'<div class="' + bodyClass + '"' + bodyAttrs + bodyStyle + '>' + bodyHtml + '</div>' +
|
||||
'</div>';
|
||||
}
|
||||
|
||||
root.pulseRegionTypes = {
|
||||
@@ -111,6 +144,7 @@
|
||||
list: list,
|
||||
getDefaultRegionSize: getDefaultRegionSize,
|
||||
getDefaultRegionStyle: getDefaultRegionStyle,
|
||||
getRegionChipLabel: getRegionChipLabel
|
||||
getRegionChipLabel: getRegionChipLabel,
|
||||
renderEditorCardShell: renderEditorCardShell
|
||||
};
|
||||
}());
|
||||
@@ -178,12 +178,25 @@
|
||||
return 'video';
|
||||
}
|
||||
|
||||
if (button && button.hasAttribute('data-remove-region-qr-image')) {
|
||||
return 'qr-image';
|
||||
}
|
||||
|
||||
if (button && button.hasAttribute('data-remove-region-image')) {
|
||||
return 'image';
|
||||
}
|
||||
|
||||
if (card && card.dataset && String(card.dataset.regionMediaType || '').trim()) {
|
||||
return String(card.dataset.regionMediaType || '').trim() === 'video' ? 'video' : 'image';
|
||||
var regionMediaType = String(card.dataset.regionMediaType || '').trim();
|
||||
if (regionMediaType === 'video') {
|
||||
return 'video';
|
||||
}
|
||||
|
||||
if (regionMediaType === 'qr-image') {
|
||||
return 'qr-image';
|
||||
}
|
||||
|
||||
return 'image';
|
||||
}
|
||||
|
||||
return 'image';
|
||||
@@ -194,7 +207,15 @@
|
||||
return callbacks.getExistingMediaPrefix(mediaType);
|
||||
}
|
||||
|
||||
return String(mediaType || '').trim() === 'video' ? 'existing_region_video_' : 'existing_region_image_';
|
||||
if (String(mediaType || '').trim() === 'video') {
|
||||
return 'existing_region_video_';
|
||||
}
|
||||
|
||||
if (String(mediaType || '').trim() === 'qr-image') {
|
||||
return 'existing_region_qr_image_';
|
||||
}
|
||||
|
||||
return 'existing_region_image_';
|
||||
}
|
||||
|
||||
function getMediaPrefix(mediaType) {
|
||||
@@ -202,7 +223,15 @@
|
||||
return callbacks.getMediaPrefix(mediaType);
|
||||
}
|
||||
|
||||
return String(mediaType || '').trim() === 'video' ? 'region_video_' : 'region_image_';
|
||||
if (String(mediaType || '').trim() === 'video') {
|
||||
return 'region_video_';
|
||||
}
|
||||
|
||||
if (String(mediaType || '').trim() === 'qr-image') {
|
||||
return 'region_qr_image_';
|
||||
}
|
||||
|
||||
return 'region_image_';
|
||||
}
|
||||
|
||||
function getVideoDurationHiddenInput(regionId) {
|
||||
@@ -214,18 +243,33 @@
|
||||
}
|
||||
|
||||
function handleRemove(button) {
|
||||
var regionId = button.getAttribute('data-remove-region-image') || button.getAttribute('data-remove-region-video');
|
||||
var regionId = button.getAttribute('data-remove-region-image') || button.getAttribute('data-remove-region-video') || button.getAttribute('data-remove-region-qr-image');
|
||||
var card = getCard(regionId);
|
||||
var mediaType = getMediaType(button, card);
|
||||
var hidden = card && card.querySelector('input[type="hidden"][name="' + getExistingPrefix(mediaType) + regionId + '"]');
|
||||
var input = card && card.querySelector('input[type="file"][name="' + getMediaPrefix(mediaType) + regionId + '"]');
|
||||
var hiddenName = getExistingPrefix(mediaType) + regionId;
|
||||
var inputName = getMediaPrefix(mediaType) + regionId;
|
||||
var hidden = card && card.querySelector('input[type="hidden"][name="' + hiddenName + '"]');
|
||||
var input = card && card.querySelector('input[type="file"][name="' + inputName + '"]');
|
||||
|
||||
if (!hidden && regionId) {
|
||||
hidden = templateFields.querySelector('input[type="hidden"][name="' + hiddenName + '"]');
|
||||
}
|
||||
|
||||
if (!input && regionId) {
|
||||
input = templateFields.querySelector('input[type="file"][name="' + inputName + '"]');
|
||||
}
|
||||
var uploadPath = input ? String(input.dataset.uploadedPath || '').trim() : '';
|
||||
var hasPendingUpload = input && input.dataset && String(input.dataset.uploadToken || '').trim();
|
||||
|
||||
if (input && input.dataset.previewUrl) {
|
||||
URL.revokeObjectURL(input.dataset.previewUrl);
|
||||
delete input.dataset.previewUrl;
|
||||
}
|
||||
|
||||
if (input && hasPendingUpload) {
|
||||
input.dataset.uploadCancelRequested = '1';
|
||||
}
|
||||
|
||||
if (input && input.dataset.uploadedNeedsCleanup === '1' && uploadPath && typeof callbacks.queueUploadCleanup === 'function') {
|
||||
callbacks.queueUploadCleanup([uploadPath]);
|
||||
}
|
||||
@@ -238,6 +282,7 @@
|
||||
|
||||
if (hidden) {
|
||||
hidden.value = '';
|
||||
hidden.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
}
|
||||
|
||||
var durationHidden = getVideoDurationHiddenInput(regionId);
|
||||
@@ -259,7 +304,7 @@
|
||||
}
|
||||
|
||||
templateFields.addEventListener('click', function (event) {
|
||||
var button = event.target && event.target.closest ? event.target.closest('[data-remove-region-image], [data-remove-region-video]') : null;
|
||||
var button = event.target && event.target.closest ? event.target.closest('[data-remove-region-image], [data-remove-region-video], [data-remove-region-qr-image]') : null;
|
||||
|
||||
if (!button || !templateFields.contains(button)) {
|
||||
return;
|
||||
@@ -273,7 +318,7 @@
|
||||
return;
|
||||
}
|
||||
|
||||
var button = event.target && event.target.closest ? event.target.closest('[data-remove-region-image], [data-remove-region-video]') : null;
|
||||
var button = event.target && event.target.closest ? event.target.closest('[data-remove-region-image], [data-remove-region-video], [data-remove-region-qr-image]') : null;
|
||||
|
||||
if (!button || !templateFields.contains(button)) {
|
||||
return;
|
||||
@@ -304,7 +349,15 @@
|
||||
return callbacks.getMediaTypeFromInput(input);
|
||||
}
|
||||
|
||||
return input && input.name && input.name.indexOf('region_video_') === 0 ? 'video' : 'image';
|
||||
if (input && input.name && input.name.indexOf('region_video_') === 0) {
|
||||
return 'video';
|
||||
}
|
||||
|
||||
if (input && input.name && input.name.indexOf('region_qr_image_') === 0) {
|
||||
return 'qr-image';
|
||||
}
|
||||
|
||||
return 'image';
|
||||
}
|
||||
|
||||
function getMediaPrefix(mediaType) {
|
||||
@@ -312,7 +365,15 @@
|
||||
return callbacks.getMediaPrefix(mediaType);
|
||||
}
|
||||
|
||||
return String(mediaType || '').trim() === 'video' ? 'region_video_' : 'region_image_';
|
||||
if (String(mediaType || '').trim() === 'video') {
|
||||
return 'region_video_';
|
||||
}
|
||||
|
||||
if (String(mediaType || '').trim() === 'qr-image') {
|
||||
return 'region_qr_image_';
|
||||
}
|
||||
|
||||
return 'region_image_';
|
||||
}
|
||||
|
||||
function getExistingMediaPrefix(mediaType) {
|
||||
@@ -320,7 +381,15 @@
|
||||
return callbacks.getExistingMediaPrefix(mediaType);
|
||||
}
|
||||
|
||||
return String(mediaType || '').trim() === 'video' ? 'existing_region_video_' : 'existing_region_image_';
|
||||
if (String(mediaType || '').trim() === 'video') {
|
||||
return 'existing_region_video_';
|
||||
}
|
||||
|
||||
if (String(mediaType || '').trim() === 'qr-image') {
|
||||
return 'existing_region_qr_image_';
|
||||
}
|
||||
|
||||
return 'existing_region_image_';
|
||||
}
|
||||
|
||||
function getUploadZone(input) {
|
||||
@@ -440,7 +509,7 @@
|
||||
}
|
||||
|
||||
function getPendingUploadCleanupPaths() {
|
||||
return Array.prototype.slice.call(templateFields.querySelectorAll('input[type="file"][name^="region_image_"], input[type="file"][name^="region_video_"]')).map(function (input) {
|
||||
return Array.prototype.slice.call(templateFields.querySelectorAll('input[type="file"][name^="region_image_"], input[type="file"][name^="region_video_"], input[type="file"][name^="region_qr_image_"]')).map(function (input) {
|
||||
if (!input || String(input.dataset.uploadedNeedsCleanup || '') !== '1') {
|
||||
return null;
|
||||
}
|
||||
@@ -450,7 +519,7 @@
|
||||
}
|
||||
|
||||
function clearPendingUploadCleanupPaths() {
|
||||
Array.prototype.slice.call(templateFields.querySelectorAll('input[type="file"][name^="region_image_"], input[type="file"][name^="region_video_"]')).forEach(function (input) {
|
||||
Array.prototype.slice.call(templateFields.querySelectorAll('input[type="file"][name^="region_image_"], input[type="file"][name^="region_video_"], input[type="file"][name^="region_qr_image_"]')).forEach(function (input) {
|
||||
if (!input) {
|
||||
return;
|
||||
}
|
||||
@@ -465,7 +534,7 @@
|
||||
}
|
||||
|
||||
var mediaType = getMediaTypeFromInput(input);
|
||||
var regionId = input.name.replace(/^region_(?:image|video)_/, '');
|
||||
var regionId = input.name.replace(/^region_(?:image|video|qr_image)_/, '');
|
||||
var card = getCard(regionId);
|
||||
var hidden = card && card.querySelector('input[type="hidden"][name="' + getExistingMediaPrefix(mediaType) + regionId + '"]');
|
||||
var zone = getUploadZone(input);
|
||||
@@ -475,6 +544,7 @@
|
||||
var uploadUrl = String(callbacks.uploadUrl || '/slides/uploads');
|
||||
var uploadTimeoutMs = Math.max(1, Number(callbacks.uploadTimeoutMs || 30000));
|
||||
|
||||
delete input.dataset.uploadCancelRequested;
|
||||
input.dataset.uploadToken = uploadToken;
|
||||
setUploadState(input, true, 0, 'Uploading...', true);
|
||||
|
||||
@@ -549,8 +619,19 @@
|
||||
delete input.dataset.previewUrl;
|
||||
}
|
||||
|
||||
if (String(input.dataset.uploadCancelRequested || '') === '1') {
|
||||
if (uploadedPath) {
|
||||
queueUploadCleanup([uploadedPath]);
|
||||
}
|
||||
|
||||
setUploadState(input, false);
|
||||
resolve(payload);
|
||||
return;
|
||||
}
|
||||
|
||||
if (hidden) {
|
||||
hidden.value = uploadedPath;
|
||||
hidden.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
}
|
||||
input.dataset.uploadedPath = uploadedPath;
|
||||
input.dataset.uploadedNeedsCleanup = '1';
|
||||
@@ -611,6 +692,7 @@
|
||||
xhr.onloadend = function () {
|
||||
if (input.dataset.uploadToken === uploadToken) {
|
||||
delete input.dataset.uploadToken;
|
||||
delete input.dataset.uploadCancelRequested;
|
||||
setUploadState(input, false);
|
||||
}
|
||||
};
|
||||
@@ -647,7 +729,7 @@
|
||||
templateFields.dataset.regionMediaUploadBound = '1';
|
||||
|
||||
templateFields.addEventListener('change', function (event) {
|
||||
var input = event.target && event.target.matches && event.target.matches('input[type="file"][name^="region_image_"], input[type="file"][name^="region_video_"]') ? event.target : null;
|
||||
var input = event.target && event.target.matches && event.target.matches('input[type="file"][name^="region_image_"], input[type="file"][name^="region_video_"], input[type="file"][name^="region_qr_image_"]') ? event.target : null;
|
||||
|
||||
if (!input || !templateFields.contains(input)) {
|
||||
return;
|
||||
|
||||
@@ -232,7 +232,6 @@
|
||||
'</div>' +
|
||||
'<input type="hidden" name="region_font_size_' + region.id + '" value="' + escapeHtml(context.fontSize || '') + '" />' +
|
||||
'<input type="hidden" name="region_text_' + region.id + '" value="' + escapeHtml(current.value !== undefined ? current.value : '') + '" />' +
|
||||
'<div class="muted slide-image-file">Use transforms like {{name.upper()}}, {{name.title()}}, or {{name.lower()}} on leaf fields.</div>' +
|
||||
'<div class="api-region-placeholder-section">' +
|
||||
'<div class="api-region-placeholder-title">Available placeholders</div>' +
|
||||
'<div class="d-flex flex-wrap gap-2" data-placeholder-chips>' + ((placeholderFields.length && window.placeholderChips && typeof window.placeholderChips.renderChips === 'function') ? window.placeholderChips.renderChips(placeholderFields) : placeholderChips || '<span class="muted slide-image-file">No JSON fields available.</span>') + '</div>' +
|
||||
|
||||
@@ -20,19 +20,13 @@
|
||||
function renderEditorCard(context) {
|
||||
var region = context.region;
|
||||
var current = String(context.current || '');
|
||||
return '' +
|
||||
'<div class="card card-outline card-secondary admin-form-card template-field-card mb-3" data-region-id="' + region.id + '">' +
|
||||
'<div class="card-header template-field-head">' +
|
||||
'<strong>' + escapeHtml(region.label) + '</strong>' +
|
||||
'<span class="chip">HTML</span>' +
|
||||
'</div>' +
|
||||
'<div class="card-body p-3 d-grid">' +
|
||||
'<label style="display:block;">HTML content' +
|
||||
return registry.renderEditorCardShell({
|
||||
region: region,
|
||||
headerActions: '<span class="chip">HTML</span>',
|
||||
bodyHtml: '' +
|
||||
'<textarea name="region_html_' + region.id + '" class="form-control" rows="10" placeholder="<div>Hello</div>">' + escapeHtml(current) + '</textarea>' +
|
||||
'</label>' +
|
||||
'<div class="muted slide-image-file">HTML is rendered in a sandboxed iframe preview.</div>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
'<div class="muted slide-image-file">HTML is rendered in a sandboxed iframe preview.</div>'
|
||||
});
|
||||
}
|
||||
|
||||
registry.register('html', {
|
||||
|
||||
@@ -34,13 +34,11 @@
|
||||
var uploadMaxLabel = String(uploadConfig.limitLabel || context.uploadMaxLabel || '100 MB');
|
||||
var uploadAccept = Array.isArray(uploadConfig.accept) ? uploadConfig.accept.join(', ') : String(uploadConfig.accept || 'image/png, image/jpeg, image/gif, image/webp');
|
||||
var uploadHelpText = String(uploadConfig.helpText || 'PNG, JPG, GIF, or WebP');
|
||||
return '' +
|
||||
'<div class="card card-outline card-secondary admin-form-card template-field-card mb-3" data-region-id="' + region.id + '" data-region-media-type="image">' +
|
||||
'<div class="card-header template-field-head">' +
|
||||
'<strong>' + escapeHtml(region.label) + '</strong>' +
|
||||
'<span class="chip">Image</span>' +
|
||||
'</div>' +
|
||||
'<div class="card-body p-3 d-grid">' +
|
||||
return registry.renderEditorCardShell({
|
||||
region: region,
|
||||
headerActions: '<span class="chip">Image</span>',
|
||||
cardAttrs: ' data-region-media-type="image"',
|
||||
bodyHtml: '' +
|
||||
'<div class="row g-3 align-items-start">' +
|
||||
'<div class="col-12 col-md-8 d-flex flex-column">' +
|
||||
'<label class="slide-image-region-upload-zone" data-region-upload-zone="' + region.id + '" for="region_image_' + region.id + '">' +
|
||||
@@ -72,9 +70,8 @@
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<input type="hidden" name="existing_region_image_' + region.id + '" value="' + escapeHtml(current) + '" />' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
'<input type="hidden" name="existing_region_image_' + region.id + '" value="' + escapeHtml(current) + '" />'
|
||||
});
|
||||
}
|
||||
|
||||
function buildEditorCardContext(context) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -55,6 +55,11 @@
|
||||
}) || null;
|
||||
}
|
||||
|
||||
function getFeedItemCount(feedId, feeds) {
|
||||
var feed = getFeedById(feedId, feeds);
|
||||
return feed && Array.isArray(feed.items) ? feed.items.length : 0;
|
||||
}
|
||||
|
||||
function getFieldList(feedId, feeds) {
|
||||
var feed = getFeedById(feedId, feeds);
|
||||
var sampleItem = feed && Array.isArray(feed.items) ? feed.items[0] : null;
|
||||
@@ -128,7 +133,8 @@
|
||||
var feed = getFeedById(feedId, feeds);
|
||||
var items = feed && Array.isArray(feed.items) ? feed.items : [];
|
||||
var parsedItemNumber = Math.max(1, Number(itemNumber || 1));
|
||||
var index = Number.isFinite(parsedItemNumber) && parsedItemNumber > 0 ? parsedItemNumber - 1 : 0;
|
||||
var itemCount = Math.max(1, items.length || 1);
|
||||
var index = Number.isFinite(parsedItemNumber) && parsedItemNumber > 0 ? Math.min(itemCount, parsedItemNumber) - 1 : 0;
|
||||
return items[index] || null;
|
||||
}
|
||||
|
||||
@@ -208,6 +214,7 @@
|
||||
var region = context.region;
|
||||
var current = context.current || {};
|
||||
var config = context.config || {};
|
||||
var itemNumberLimit = Math.max(1, Number(context.itemNumberLimit || 1));
|
||||
var placeholderChips = String(context.placeholderChips || '');
|
||||
var feedOptions = String(context.feedOptions || '');
|
||||
return '' +
|
||||
@@ -232,15 +239,15 @@
|
||||
'</div>' +
|
||||
'<div class="col-6 col-md-4">' +
|
||||
'<label class="form-label" for="region_rss_item_number_' + region.id + '">Entry number</label>' +
|
||||
'<input id="region_rss_item_number_' + region.id + '" type="number" min="1" step="1" name="region_rss_item_number_' + region.id + '" class="form-control" value="' + escapeHtml(config.item_number) + '" />' +
|
||||
'<input id="region_rss_item_number_' + region.id + '" type="number" min="1" max="' + escapeHtml(itemNumberLimit) + '" step="1" name="region_rss_item_number_' + region.id + '" class="form-control" value="' + escapeHtml(config.item_number) + '" />' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<input type="hidden" name="region_font_size_' + region.id + '" value="' + escapeHtml(context.fontSize || '') + '" />' +
|
||||
'<input type="hidden" name="region_text_' + region.id + '" value="' + escapeHtml(current.value !== undefined ? current.value : '') + '" />' +
|
||||
'<div class="muted slide-image-file">Use transforms like {{title.upper()}}, {{title.title()}}, or {{title.lower()}} on leaf fields.</div>' +
|
||||
'<div class="api-region-placeholder-section">' +
|
||||
'<div class="api-region-placeholder-title">Available placeholders</div>' +
|
||||
'<div class="d-flex flex-wrap gap-2" data-placeholder-chips>' + (placeholderChips || '<span class="muted slide-image-file">No RSS fields available.</span>') + '</div>' +
|
||||
'<div class="text-body-secondary small mt-1">Placeholder values support transforms, for example <code>{{title.upper()}}</code>, <code>{{title.title()}}</code>, <code>{{title.lower()}}</code>, or <code>{{publishedAt.format("MMM D, YYYY")}}</code>.</div>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
@@ -250,6 +257,7 @@
|
||||
var region = context.region;
|
||||
var current = context.current || {};
|
||||
var config = context.config || {};
|
||||
var itemNumberLimit = Math.max(1, Number(getFeedItemCount(config.feed_id, feeds) || 1));
|
||||
var placeholderChips = String(context.placeholderChips || '');
|
||||
var feedOptions = String(context.feedOptions || '');
|
||||
|
||||
@@ -257,6 +265,7 @@
|
||||
region: region,
|
||||
current: current,
|
||||
config: config,
|
||||
itemNumberLimit: itemNumberLimit,
|
||||
fontSize: context.fontSize || '',
|
||||
placeholderChips: placeholderChips,
|
||||
feedOptions: feedOptions,
|
||||
|
||||
@@ -21,24 +21,12 @@
|
||||
function renderEditorCard(context) {
|
||||
var region = context.region;
|
||||
var current = String(context.current || '');
|
||||
var disableAudio = context.disableAudio === undefined ? false : Boolean(context.disableAudio);
|
||||
return '' +
|
||||
'<div class="card card-outline card-secondary admin-form-card template-field-card mb-3" data-region-id="' + region.id + '">' +
|
||||
'<div class="card-header template-field-head">' +
|
||||
'<strong>' + escapeHtml(region.label) + '</strong>' +
|
||||
'<span class="chip">RTMP</span>' +
|
||||
'</div>' +
|
||||
'<div class="card-body p-3 d-grid">' +
|
||||
'<label style="display:block;">RTMP URL' +
|
||||
'<input type="url" name="region_rtmp_' + region.id + '" class="form-control" value="' + escapeHtml(current) + '" placeholder="rtmp://example.com/live/stream" />' +
|
||||
'</label>' +
|
||||
'<label class="form-check m-0">' +
|
||||
'<input class="form-check-input" type="checkbox" name="region_disable_audio_' + region.id + '" value="1"' + (disableAudio ? ' checked' : '') + ' />' +
|
||||
'<span class="form-check-label">Disable audio</span>' +
|
||||
'</label>' +
|
||||
'<div class="muted slide-image-file">Player controls stay hidden and the stream is not interactive.</div>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
return registry.renderEditorCardShell({
|
||||
region: region,
|
||||
headerActions: '<span class="chip">RTMP</span>',
|
||||
bodyHtml: '' +
|
||||
'<input type="url" name="region_rtmp_' + region.id + '" class="form-control" value="' + escapeHtml(current) + '" placeholder="rtmp://example.com/live/stream" />'
|
||||
});
|
||||
}
|
||||
|
||||
registry.register('rtmp', {
|
||||
|
||||
@@ -219,7 +219,7 @@
|
||||
'<div class="api-region-placeholder-section schedule-placeholder-section" data-schedule-placeholder-chips>' +
|
||||
'<div class="api-region-placeholder-title">Available placeholders</div>' +
|
||||
'<div class="d-flex flex-wrap gap-2">' + renderSchedulePlaceholderChips(currentGroup, currentEntries) + '</div>' +
|
||||
'<div class="text-body-secondary small mt-2">Format start and end values with expressions like <code>{{start.format("MMM D, YYYY h:mm A")}}</code> and <code>{{end.format("MMM D, YYYY h:mm A")}}</code>.</div>' +
|
||||
'<div class="text-body-secondary small mt-1">Placeholder values support transforms, for example <code>{{title.upper()}}</code>, <code>{{title.title()}}</code>, <code>{{title.lower()}}</code> or <code>{{start.format("MMM D, YYYY h:mm A")}}</code>.</div>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
var fontSize = style && style.font_size ? 'font-size:' + Math.max(1, Math.round(Number(style.font_size))) + 'px;' : '';
|
||||
var width = Math.max(1, Math.round(Number(region && region.width ? region.width : 0) || 1));
|
||||
var height = Math.max(1, Math.round(Number(region && region.height ? region.height : 0) || 1));
|
||||
var wrapperStyle = 'width:' + width + 'px;height:' + height + 'px;overflow:hidden;' + fontFamily + fontSize + color;
|
||||
var wrapperStyle = 'width:' + width + 'px;height:' + height + 'px;overflow:hidden;line-height:1.5;' + fontFamily + fontSize + color;
|
||||
return '<div class="slide-preview-text-content" style="' + wrapperStyle + '">' + sanitizePreviewHtml(raw) + '</div>';
|
||||
}
|
||||
|
||||
|
||||
@@ -313,6 +313,7 @@
|
||||
'<div>' +
|
||||
'<div class="api-region-placeholder-title mb-2">Available placeholders</div>' +
|
||||
'<div class="d-flex flex-wrap gap-2">' + renderPlaceholderChips() + '</div>' +
|
||||
'<div class="text-body-secondary small mt-1">Placeholder values support transforms, for example <code>{{title.upper()}}</code>, <code>{{title.title()}}</code>, or <code>{{title.lower()}}</code>.</div>' +
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
|
||||
@@ -39,13 +39,11 @@
|
||||
var uploadVideoMaxLabel = String(uploadConfig.limitLabel || context.uploadVideoMaxLabel || '1 GB');
|
||||
var uploadAccept = Array.isArray(uploadConfig.accept) ? uploadConfig.accept.join(', ') : String(uploadConfig.accept || 'video/mp4, video/webm, video/ogg');
|
||||
var uploadHelpText = String(uploadConfig.helpText || 'MP4, WebM, or Ogg');
|
||||
return '' +
|
||||
'<div class="card card-outline card-secondary admin-form-card template-field-card mb-3" data-region-id="' + region.id + '" data-region-media-type="video">' +
|
||||
'<div class="card-header template-field-head">' +
|
||||
'<strong>' + escapeHtml(region.label) + '</strong>' +
|
||||
'<span class="chip">Video</span>' +
|
||||
'</div>' +
|
||||
'<div class="card-body p-3 d-grid">' +
|
||||
return registry.renderEditorCardShell({
|
||||
region: region,
|
||||
headerActions: '<span class="chip">Video</span>',
|
||||
cardAttrs: ' data-region-media-type="video"',
|
||||
bodyHtml: '' +
|
||||
'<div class="row g-3 align-items-start">' +
|
||||
'<div class="col-12 col-md-8 d-flex flex-column">' +
|
||||
'<label class="slide-image-region-upload-zone" data-region-upload-zone="' + region.id + '" for="region_video_' + region.id + '">' +
|
||||
@@ -78,9 +76,8 @@
|
||||
'</div>' +
|
||||
'</div>' +
|
||||
'<input type="hidden" name="existing_region_video_' + region.id + '" value="' + escapeHtml(current) + '" />' +
|
||||
'<input type="hidden" name="existing_region_video_duration_' + region.id + '" value="' + escapeHtml(currentDuration) + '" />' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
'<input type="hidden" name="existing_region_video_duration_' + region.id + '" value="' + escapeHtml(currentDuration) + '" />'
|
||||
});
|
||||
}
|
||||
|
||||
function buildEditorCardContext(context) {
|
||||
|
||||
@@ -20,19 +20,12 @@
|
||||
function renderEditorCard(context) {
|
||||
var region = context.region;
|
||||
var current = String(context.current || '');
|
||||
return '' +
|
||||
'<div class="card card-outline card-secondary admin-form-card template-field-card mb-3" data-region-id="' + region.id + '">' +
|
||||
'<div class="card-header template-field-head">' +
|
||||
'<strong>' + escapeHtml(region.label) + '</strong>' +
|
||||
'<span class="chip">Webpage</span>' +
|
||||
'</div>' +
|
||||
'<div class="card-body p-3 d-grid">' +
|
||||
'<label style="display:block;">Webpage URL' +
|
||||
'<input type="url" name="region_webpage_' + region.id + '" class="form-control" value="' + escapeHtml(current) + '" placeholder="https://example.com" />' +
|
||||
'</label>' +
|
||||
'<div class="muted slide-image-file">The webpage will be loaded in an iframe.</div>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
return registry.renderEditorCardShell({
|
||||
region: region,
|
||||
headerActions: '<span class="chip">Webpage</span>',
|
||||
bodyHtml: '' +
|
||||
'<input type="url" name="region_webpage_' + region.id + '" class="form-control" value="' + escapeHtml(current) + '" placeholder="https://example.com" />'
|
||||
});
|
||||
}
|
||||
|
||||
registry.register('webpage', {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// Shared QR SVG helpers for browser renderers.
|
||||
|
||||
(function () {
|
||||
function normalizeSvgMarkup(svg) {
|
||||
var markup = String(svg || '').trim();
|
||||
if (!markup) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return markup.replace(/^<\?xml[^>]*>\s*/i, '');
|
||||
}
|
||||
|
||||
function stripBackground(svg) {
|
||||
var markup = String(svg || '').trim();
|
||||
if (!markup) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return markup
|
||||
.replace(/<path\b[^>]*fill="#ffffff"[^>]*d="M0 0h[^\"]*"[^>]*\s*\/>/i, '')
|
||||
.replace(/<path\b[^>]*fill="#ffffff"[^>]*d="M0 0h[^\"]*"[^>]*><\/path>/i, '')
|
||||
.replace(/<rect\b[^>]*fill="#ffffff"[^>]*x="0"[^>]*y="0"[^>]*width="\d+"[^>]*height="\d+"[^>]*\s*\/?>(?:<\/rect>)?/i, '');
|
||||
}
|
||||
|
||||
function normalizePreviewSvg(svg) {
|
||||
var markup = normalizeSvgMarkup(stripBackground(svg));
|
||||
if (!markup || markup.charAt(0) !== '<') {
|
||||
return markup;
|
||||
}
|
||||
|
||||
return markup.replace(/^<svg\b([^>]*)>/i, function (_match, attrText) {
|
||||
var attrs = String(attrText || '');
|
||||
if (!/\bwidth\s*=\s*/i.test(attrs)) {
|
||||
attrs += ' width="95%"';
|
||||
}
|
||||
if (!/\bheight\s*=\s*/i.test(attrs)) {
|
||||
attrs += ' height="95%"';
|
||||
}
|
||||
if (!/\bpreserveAspectRatio\s*=\s*/i.test(attrs)) {
|
||||
attrs += ' preserveAspectRatio="xMidYMid meet"';
|
||||
}
|
||||
if (!/\bstyle\s*=\s*/i.test(attrs)) {
|
||||
attrs += ' style="display:block;width:95%;height:95%;"';
|
||||
}
|
||||
return '<svg' + attrs + '>';
|
||||
});
|
||||
}
|
||||
|
||||
window.pulseQrSvgUtils = {
|
||||
normalizeSvgMarkup: normalizeSvgMarkup,
|
||||
stripBackground: stripBackground,
|
||||
normalizePreviewSvg: normalizePreviewSvg
|
||||
};
|
||||
}());
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user